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
feat(comments): route PDF comments through the message API behind the unified discussions flag (#6872)
gbirmanc77f883c75b6
diff --git a/apps/web/src/features/block-pdf/component/PageOverlay.tsx b/apps/web/src/features/block-pdf/component/PageOverlay.tsxindex 32b67c0045..1860f93645 100644--- a/apps/web/src/features/block-pdf/component/PageOverlay.tsx+++ b/apps/web/src/features/block-pdf/component/PageOverlay.tsx@@ -11,6 +11,7 @@ import { useCreatePlaceable } from '@block-pdf/store/placeables';import { PayloadMode, type PayloadType } from '@block-pdf/type/placeables';import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';import { useIsAuthenticated } from '@core/auth';+import type { ThreadId } from '@core/comments/commentType';import { openLoginModal } from '@core/component/TopBar/LoginButton';import { cn } from '@ui';import { detect } from 'detect-browser';@@ -57,7 +58,7 @@ export interface IHighlightObj {width: number;height: number;color: IColor;- threadId: number | null;+ threadId: ThreadId | null;highlightId: string;rectId: string;text?: string;diff --git a/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsx b/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsxindex b878ef97a6..0d62edda1e 100644--- a/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsx+++ b/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsx@@ -23,6 +23,7 @@ vi.mock('@block-pdf/store/comments/commentLayout', () => ({vi.mock('@block-pdf/store/comments/commentOperations', () => ({useCreateComment: () => vi.fn(),+ useCreateMessageComment: () => vi.fn(),useDeleteComment: () => vi.fn(),useUpdateComment: () => vi.fn(),}));@@ -45,6 +46,7 @@ vi.mock('../context/pdf-comments-context', () => ({vi.mock('../context/pdf-document-context', () => ({usePdfDocument: () => ({documentId: () => 'document-id',+ annotations: { unified: false },isNested: () => false,permissions: {canComment: () => true,@@ -61,6 +63,7 @@ vi.mock('@core/comments/Thread', async () => {return {baseCommentTheme: { text: { base: '' } },CommentsContext: createContext(),+ noopCommentOperations: {},Thread: (props: {comment: { threadId: ThreadId };layout: { calculatedYPos: number };diff --git a/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx b/apps/web/src/features/block-pdf/component/RightMarginLayout.tsxindex 5bfb1b956e..19b097c4ed 100644--- a/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx+++ b/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx@@ -6,6 +6,7 @@ import {import { usePageCommentLayout } from '@block-pdf/store/comments/commentLayout';import {useCreateComment,+ useCreateMessageComment,useDeleteComment,useUpdateComment,} from '@block-pdf/store/comments/commentOperations';@@ -14,6 +15,7 @@ import {baseCommentTheme,CommentsContext,type CommentsContextType,+ noopCommentOperations,Thread,} from '@core/comments/Thread';import { useUserId } from '@core/context/user';@@ -39,6 +41,25 @@ export function RightMarginLayout(props: { pageIndex: number }) {);}+function useCommentOperations(): Pick<+ CommentsContextType,+ 'commentOperations' | 'messageOperations'+> {+ if (usePdfDocument().annotations.unified) {+ return {+ commentOperations: noopCommentOperations,+ messageOperations: { createComment: useCreateMessageComment() },+ };+ }+ return {+ commentOperations: {+ createComment: useCreateComment(),+ deleteComment: useDeleteComment(),+ updateComment: useUpdateComment(),+ },+ };+}+const useCommentsContext = (setThreadHeight: CommentsContextType['setThreadHeight']): CommentsContextType => {@@ -53,9 +74,7 @@ const useCommentsContext = (}};- const createComment = useCreateComment();- const updateComment = useUpdateComment();- const deleteComment = useDeleteComment();+ const operations = useCommentOperations();const userId = useUserId();const ownedComment = (id: CommentId) => {@@ -75,11 +94,7 @@ const useCommentsContext = (documentId: pdf.documentId(),documentType: 'pdf',ownedComment,- commentOperations: {- createComment,- deleteComment,- updateComment,- },+ ...operations,inComment: true,highlightedCommentId: () => null,};diff --git a/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx b/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsxindex cd229c141f..0e7f46eac1 100644--- a/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx+++ b/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx@@ -12,20 +12,22 @@ export const FreeCommentPlaceable: Component<{return (<CommentIndicator- threadId={props.payload.threadId}isActive={isActiveThreadSelector(props.payload.threadId)}setActive={() => comments.activateThread(props.payload.threadId)}- numComments={props.payload.comments.length}+ numComments={+ props.payload.replyCount == null+ ? props.payload.comments.length+ : 1 + props.payload.replyCount+ }/>);};export const NewFreeCommentPlaceable: Component = () => {- return <CommentIndicator threadId={-1} isActive={true} numComments={1} />;+ return <CommentIndicator isActive={true} numComments={1} />;};function CommentIndicator(props: {- threadId: number;numComments: number;isActive: boolean;setActive?: () => void;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.tsindex 886062c9ce..6b2094c6db 100644--- a/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.ts+++ b/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.ts@@ -4,6 +4,7 @@ import type { DeleteCommentResponse } from '@service-storage/generated/schemas/dimport type { DeleteUnthreadedAnchorResponse } from '@service-storage/generated/schemas/deleteUnthreadedAnchorResponse';import type { EditAnchorResponse } from '@service-storage/generated/schemas/editAnchorResponse';import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';+import type { MessageListItem } from '@service-storage/messages';import { waitFor } from '@solidjs/testing-library';import { createRoot } from 'solid-js';import { beforeEach, describe, expect, it, vi } from 'vitest';@@ -15,14 +16,37 @@ const annotationQueries = vi.hoisted(() => ({getPdfComments: vi.fn(async (_documentId: string) => []),}));+const messageRoots = vi.hoisted(() => ({+ parents: [] as string[],+ setRoots: (_roots: MessageListItem[]) => {},+}));+vi.mock('../queries/annotations', () => annotationQueries);+vi.mock('@queries/messages/document-messages', async () => {+ const { createSignal } = await import('solid-js');+ const [roots, setRoots] = createSignal<MessageListItem[]>([]);+ messageRoots.setRoots = setRoots;+ return {+ useMessageRootsQuery: (parent: () => { type: string; id: string }) => {+ messageRoots.parents.push(`${parent().type}:${parent().id}`);+ return {+ get data() {+ return roots();+ },+ };+ },+ };+});-function setup(documentId: string): {+function setup(+ documentId: string,+ unified = false+): {annotations: PdfAnnotations;dispose: () => void;} {return createRoot((dispose) => ({- annotations: createPdfAnnotations(() => documentId),+ annotations: createPdfAnnotations(() => documentId, unified),dispose,}));}@@ -56,7 +80,8 @@ function createHighlight(function createServerHighlight(uuid: string,- threadId?: number+ threadId?: number,+ rootId?: string): CreateUnthreadedAnchorResponse {return {uuid,@@ -74,6 +99,54 @@ function createServerHighlight(text: 'server highlight',owner: 'user-1',threadId,+ rootId,+ };+}++function createServerPlaceable(+ uuid: string,+ binding: { threadId?: number; rootId?: string }+): CreateUnthreadedAnchorResponse {+ return {+ uuid,+ documentId: 'document-1',+ anchorType: 'placeable',+ owner: 'user-1',+ ...binding,+ page: 1,+ originalPage: 1,+ originalIndex: -1,+ xPct: 0.1,+ yPct: 0.2,+ widthPct: 0.05,+ heightPct: 0.05,+ rotation: 0,+ wasEdited: false,+ wasDeleted: false,+ shouldLockOnSave: false,+ };+}++function root(id: string, content = 'first comment'): MessageListItem {+ const created_at = '2026-09-09T00:00:00Z';+ return {+ id,+ parent: { type: 'document', id: 'document-1' },+ sender_id: 'user-1',+ content,+ mentions: [],+ attachments: [],+ reactions: [],+ created_at,+ updated_at: created_at,+ state: {+ root_id: id,+ user_id: 'user-1',+ resolved: false,+ created_at,+ updated_at: created_at,+ },+ thread: { reply_count: 0, preview: [], latest_reply_at: null },};}@@ -103,6 +176,8 @@ function createCommentResponse(beforeEach(() => {annotationQueries.getPdfAnchors.mockClear();annotationQueries.getPdfComments.mockClear();+ messageRoots.parents.length = 0;+ messageRoots.setRoots([]);});describe('createPdfAnnotations', () => {@@ -136,6 +211,7 @@ describe('createPdfAnnotations', () => {exposesAnchorMutate: false,exposesCommentThreadMutate: false,});+ expect(messageRoots.parents).toEqual([]);first.dispose();second.dispose();@@ -293,3 +369,247 @@ describe('createPdfAnnotations', () => {dispose();});});++describe('createPdfAnnotations on the message API', () => {+ async function waitForAnchors(annotations: PdfAnnotations) {+ await waitFor(() => expect(annotations.anchors()).toEqual([]));+ }++ it('reads the document discussion instead of the legacy comments', async () => {+ const { annotations, dispose } = setup('document-1', true);+ await waitForAnchors(annotations);++ expect({+ unified: annotations.unified,+ messageParents: messageRoots.parents,+ legacyCommentQueries: annotationQueries.getPdfComments.mock.calls.length,+ commentThreads: annotations.commentThreads(),+ }).toEqual({+ unified: true,+ messageParents: ['document:document-1'],+ legacyCommentQueries: 0,+ commentThreads: undefined,+ });+ dispose();+ });++ it('projects anchors and their discussion roots into highlights', async () => {+ const { annotations, dispose } = setup('document-1', true);+ await waitForAnchors(annotations);++ annotations.commands.applyCreatedAnchor(+ createServerHighlight('highlight-1', undefined, 'root-1')+ );+ // A threaded highlight waits for its discussion.+ expect(annotations.highlightsByUuid()).toEqual({});++ messageRoots.setRoots([root('root-1')]);+ await waitFor(() => {+ expect(annotations.highlightsByUuid()['highlight-1']?.thread).toEqual({+ threadId: 'root-1',+ rootId: 'root-1',+ anchorId: 'highlight-1',+ page: 2,+ comments: [root('root-1')],+ replyCount: 0,+ isResolved: false,+ });+ });++ // A deleted discussion drops out of the join.+ const deleted = root('root-1');+ deleted.state = { ...deleted.state, deleted_at: '2026-09-10T00:00:00Z' };+ messageRoots.setRoots([deleted]);+ await waitFor(() => {+ expect(annotations.highlightsByUuid()).toEqual({});+ });+ dispose();+ });++ it('keeps open comment drafts when the discussion or anchors change', async () => {+ const { annotations, dispose } = setup('document-1', true);+ await waitForAnchors(annotations);+ annotations.commands.applyCreatedAnchor(+ createServerHighlight('existing-highlight')+ );+ await waitFor(() =>+ expect(annotations.highlightsByUuid()['existing-highlight']).toBeTruthy()+ );+ const existing = annotations.highlightsByUuid()['existing-highlight']!;+ annotations.commands.beginExistingHighlightCommentDraft(existing);+ annotations.commands.beginNewHighlightCommentDrafts([+ createHighlight('new-highlight'),+ ]);++ // Another client posts a discussion and an unrelated anchor arrives.+ messageRoots.setRoots([root('root-9')]);+ annotations.commands.applyCreatedAnchor(+ createServerHighlight('other-highlight')+ );++ await waitFor(() =>+ expect(annotations.highlightsByUuid()['other-highlight']).toBeTruthy()+ );+ expect({+ existing:+ annotations.highlightsByUuid()['existing-highlight']?.hasTempThread,+ created: annotations.highlightsByUuid()['new-highlight']?.hasTempThread,+ }).toEqual({ existing: true, created: true });++ // Once the server holds a draft's highlight with its discussion, the+ // draft gives way to the saved thread.+ messageRoots.setRoots([root('root-9'), root('root-10')]);+ annotations.commands.applyCreatedAnchor(+ createServerHighlight('new-highlight', undefined, 'root-10')+ );+ await waitFor(() =>+ expect(+ annotations.highlightsByUuid()['new-highlight']?.thread?.threadId+ ).toBe('root-10')+ );+ expect(annotations.highlightsByUuid()['new-highlight']?.hasTempThread).toBe(+ false+ );+ dispose();+ });++ it('binds a posted root to its anchor and releases anchors of a deleted discussion', async () => {+ const { annotations, dispose } = setup('document-1', true);+ await waitForAnchors(annotations);+ messageRoots.setRoots([root('root-1'), root('root-2')]);++ annotations.commands.applyCreatedAnchor(+ createServerHighlight('highlight-1')+ );+ annotations.commands.applyCreatedAnchor(+ createServerPlaceable('placeable-1', { rootId: 'root-2' })+ );+ annotations.commands.attachAnchorRoot('highlight-1', 'root-1');++ await waitFor(() => {+ expect(+ annotations.highlightsByUuid()['highlight-1']?.thread?.threadId+ ).toBe('root-1');+ });++ annotations.commands.applyThreadDeleted('root-1');+ annotations.commands.applyThreadDeleted('root-2');++ expect(+ annotations+ .anchors()+ ?.map((anchor) => ({ uuid: anchor.uuid, rootId: anchor.rootId }))+ ).toEqual([{ uuid: 'highlight-1', rootId: null }]);+ await waitFor(() => {+ expect(annotations.highlightsByUuid()['highlight-1']?.thread).toBeNull();+ });+ dispose();+ });+});++/**+ * Production runs both paths on the same documents. Imported anchors carry+ * both ids; an anchor written by one path carries only its own. Neither client+ * may treat the other's discussion as a bare highlight it can delete or+ * re-thread.+ */+describe('anchors shared between legacy and message clients', () => {+ const messageHighlight = () =>+ createServerHighlight('message-highlight', undefined, 'root-1');+ const legacyHighlight = () => createServerHighlight('legacy-highlight', 31);+ const importedHighlight = () =>+ createServerHighlight('imported-highlight', 32, 'root-2');+ const bareHighlight = () => createServerHighlight('bare-highlight');++ function seed(annotations: PdfAnnotations) {+ for (const anchor of [+ messageHighlight(),+ legacyHighlight(),+ importedHighlight(),+ bareHighlight(),+ createServerPlaceable('message-placeable', { rootId: 'root-3' }),+ createServerPlaceable('legacy-placeable', { threadId: 33 }),+ ])+ annotations.commands.applyCreatedAnchor(anchor);+ }++ const threadIdsByAnchor = (annotations: PdfAnnotations) =>+ Object.fromEntries(+ (annotations.anchors() ?? []).map((anchor) => [+ anchor.uuid,+ annotations.anchorThread(anchor)?.threadId ??+ annotations.anchorThread(anchor),+ ])+ );++ it('keeps a legacy client off anchors created through the message path', async () => {+ const { annotations, dispose } = setup('document-1', false);+ await waitForInitialResources(annotations);+ // The message roots exist, but a legacy client never reads them.+ messageRoots.setRoots([root('root-1'), root('root-2'), root('root-3')]);+ seed(annotations);+ for (const threadId of [31, 32, 33])+ annotations.commands.applyCreatedComment(+ createCommentResponse(threadId, threadId + 10)+ );++ await waitFor(() => {+ expect(Object.keys(annotations.highlightsByUuid()).sort()).toEqual([+ 'bare-highlight',+ 'imported-highlight',+ 'legacy-highlight',+ ]);+ });+ expect(threadIdsByAnchor(annotations)).toEqual({+ 'message-highlight': undefined,+ 'legacy-highlight': 31,+ 'imported-highlight': 32,+ 'bare-highlight': null,+ 'message-placeable': undefined,+ 'legacy-placeable': 33,+ });+ // Hidden, so it is never offered as a highlight to delete or comment on.+ expect(annotations.highlightsByUuid()['message-highlight']).toBeUndefined();+ dispose();+ });++ it('keeps a message client off anchors only a legacy thread holds', async () => {+ const { annotations, dispose } = setup('document-1', true);+ await waitFor(() => expect(annotations.anchors()).toEqual([]));+ messageRoots.setRoots([root('root-1'), root('root-2'), root('root-3')]);+ seed(annotations);++ await waitFor(() => {+ expect(Object.keys(annotations.highlightsByUuid()).sort()).toEqual([+ 'bare-highlight',+ 'imported-highlight',+ 'message-highlight',+ ]);+ });+ expect(threadIdsByAnchor(annotations)).toEqual({+ 'message-highlight': 'root-1',+ 'legacy-highlight': undefined,+ 'imported-highlight': 'root-2',+ 'bare-highlight': null,+ 'message-placeable': 'root-3',+ 'legacy-placeable': undefined,+ });+ dispose();+ });++ it('shows a highlight whose message discussion was deleted as bare to both clients', async () => {+ // The server detaches a highlight when its discussion is deleted.+ const detached = { ...messageHighlight(), rootId: null };+ for (const unified of [false, true]) {+ const { annotations, dispose } = setup('document-1', unified);+ await waitFor(() => expect(annotations.anchors()).toEqual([]));+ annotations.commands.applyCreatedAnchor(detached);+ await waitFor(() => {+ expect(+ annotations.highlightsByUuid()['message-highlight']?.thread+ ).toBeNull();+ });+ dispose();+ }+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-annotations.ts b/apps/web/src/features/block-pdf/primitives/pdf-annotations.tsindex e7e29a0e7f..6f3486d13c 100644--- a/apps/web/src/features/block-pdf/primitives/pdf-annotations.ts+++ b/apps/web/src/features/block-pdf/primitives/pdf-annotations.ts@@ -1,3 +1,9 @@+import {+ enableUnifiedDocumentDiscussions,+ isFeatureEnabled,+} from '@core/constant/featureFlags';+import { useMessageRootsQuery } from '@queries/messages/document-messages';+import type { Anchor } from '@service-storage/generated/schemas/anchor';import type { Comment } from '@service-storage/generated/schemas/comment';import type { CommentThread } from '@service-storage/generated/schemas/commentThread';import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';@@ -6,6 +12,7 @@ import type { DeleteCommentResponse } from '@service-storage/generated/schemas/dimport type { DeleteUnthreadedAnchorResponse } from '@service-storage/generated/schemas/deleteUnthreadedAnchorResponse';import type { EditAnchorResponse } from '@service-storage/generated/schemas/editAnchorResponse';import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';+import type { MessageListItem } from '@service-storage/messages';import {type Accessor,batch,@@ -13,27 +20,109 @@ import {createMemo,createResource,createSignal,+ untrack,} from 'solid-js';import { createStore, produce, reconcile } from 'solid-js/store';import type { IHighlight } from '../model/Highlight';import { getPdfAnchors, getPdfComments } from '../queries/annotations';+import type { ThreadPayload } from '../type/comments';export type HighlightUuidMap = Partial<Record<string, IHighlight>>;export type HighlightPageMap = Partial<Record<number, HighlightUuidMap>>;-export function createPdfAnnotations(documentId: Accessor<string>) {+/** The discussion a PDF anchor points at, from the root's timeline entry. */+export function messageThreadPayload(+ root: MessageListItem,+ anchorId: string,+ page: number+): ThreadPayload {+ return {+ threadId: root.id,+ rootId: root.id,+ anchorId,+ page,+ comments: [root, ...root.thread.preview],+ replyCount: root.thread.reply_count,+ isResolved: root.state.resolved,+ };+}++export type AnchorBinding =+ | { kind: 'unthreaded' }+ | { kind: 'thread'; threadId: number | string }+ | { kind: 'foreign' };++/**+ * Which discussion an anchor carries for this client. Legacy clients join on+ * the annotation thread id and message clients on the root id; imported+ * anchors carry both. An anchor bound only to the other store's discussion is+ * foreign: it stays hidden, so this client can neither delete it nor thread a+ * second discussion onto it.+ */+export function anchorBinding(+ anchor: Pick<Anchor, 'threadId' | 'rootId'>,+ unified: boolean+): AnchorBinding {+ const own = unified ? anchor.rootId : anchor.threadId;+ if (own != null) return { kind: 'thread', threadId: own };+ const other = unified ? anchor.threadId : anchor.rootId;+ return other != null ? { kind: 'foreign' } : { kind: 'unthreaded' };+}++/**+ * PDF annotation state: anchor geometry from the annotation endpoints joined+ * with the document's discussions. With unified document discussions on, the+ * discussions are message roots read through the shared message API and+ * anchors reference them by `rootId`; otherwise they are the legacy annotation+ * comment threads referenced by `threadId`.+ */+export function createPdfAnnotations(+ documentId: Accessor<string>,+ unified = isFeatureEnabled(enableUnifiedDocumentDiscussions)+) {const [highlightsByPage, setHighlightsByPage] = createStore<HighlightPageMap>({});const [convertedHighlightDraftId, setConvertedHighlightDraftId] =createSignal<string>();const [commentThreadsResource, { mutate: mutateCommentThreads }] =- createResource(documentId, getPdfComments);- const [anchorsResource, { mutate: mutateAnchors }] = createResource(- documentId,- getPdfAnchors+ createResource(() => !unified && documentId(), getPdfComments);+ const [anchorsResource, { mutate: mutateAnchors, refetch: refetchAnchors }] =+ createResource(documentId, getPdfAnchors);+ const roots = unified+ ? useMessageRootsQuery(() => ({ type: 'document', id: documentId() }))+ : undefined;+ const messageThreads = createMemo(() =>+ (roots?.data ?? []).filter((root) => !root.state.deleted_at)+ );+ const messageThreadsByRootId = createMemo(+ () => new Map(messageThreads().map((root) => [root.id, root])));+ /** The discussion on an anchor, `null` when unthreaded, `undefined` while hidden. */+ const anchorThread = (anchor: Anchor): ThreadPayload | null | undefined => {+ const binding = anchorBinding(anchor, unified);+ if (binding.kind === 'unthreaded') return null;+ if (binding.kind === 'foreign') return undefined;+ if (unified) {+ const root = messageThreadsByRootId().get(String(binding.threadId));+ return root && messageThreadPayload(root, anchor.uuid, anchor.page);+ }+ const commentThread = (commentThreadsResource() ?? []).find(+ (thread) => thread.thread.threadId === binding.threadId+ );+ return (+ commentThread && {+ threadId: commentThread.thread.threadId,+ rootId: commentThread.comments[0].commentId,+ anchorId: anchor.uuid,+ page: anchor.page,+ comments: commentThread.comments,+ isResolved: commentThread.thread.resolved,+ }+ );+ };+const highlightsByUuid = createMemo(() => {const result: HighlightUuidMap = {};for (const pageHighlights of Object.values(highlightsByPage)) {@@ -51,21 +140,25 @@ export function createPdfAnnotations(documentId: Accessor<string>) {);createEffect(() => {+ // Rebuilding from the server keeps comment drafts the server has not+ // superseded: discussions and anchors change under an open composer.+ const drafts = untrack(() =>+ Object.values(highlightsByUuid()).filter(+ (highlight): highlight is IHighlight => !!highlight?.hasTempThread+ )+ );setHighlightsByPage(reconcile({}));- const anchors = anchorsResource();- if (!anchors || anchors.length === 0) return;+ const anchors = anchorsResource() ?? [];- const commentThreads = commentThreadsResource() ?? [];const highlightAnchors = anchors.filter((anchor) => anchor.anchorType === 'highlight');const mappedAnchors = highlightAnchors.flatMap((anchor) => {- const commentThread = commentThreads.find(- (thread) => thread.thread.threadId === anchor.threadId- );- if (!commentThread && anchor.threadId) return [];+ const thread = anchorThread(anchor);+ // A threaded highlight renders once its discussion has loaded.+ if (thread === undefined) return [];const highlight: IHighlight = {owner: anchor.owner,@@ -86,23 +179,23 @@ export function createPdfAnnotations(documentId: Accessor<string>) {width: anchor.pageViewportWidth,height: anchor.pageViewportHeight,},- thread: commentThread- ? {- threadId: commentThread.thread.threadId,- rootId: commentThread.comments[0].commentId,- anchorId: anchor.uuid,- page: anchor.page,- comments: commentThread.comments,- isResolved: commentThread.thread.resolved,- }- : null,+ thread,};return highlight;});+ const mappedByUuid = new Map(+ mappedAnchors.map((highlight) => [highlight.uuid, highlight])+ );+ const keptDrafts = drafts.flatMap((draft) => {+ const saved = mappedByUuid.get(draft.uuid);+ if (!saved) return draft.existsOnServer ? [] : [draft];+ return saved.thread ? [] : [{ ...saved, hasTempThread: true }];+ });+batch(() => {- for (const highlight of mappedAnchors) {+ for (const highlight of [...mappedAnchors, ...keptDrafts]) {setHighlightsByPage(highlight.pageNum, (previous) => ({...previous,[highlight.uuid]: highlight,@@ -113,7 +206,10 @@ export function createPdfAnnotations(documentId: Accessor<string>) {const commands = {applyCreatedAnchor(response: CreateUnthreadedAnchorResponse) {- mutateAnchors((previous) => [...(previous ?? []), response]);+ mutateAnchors((previous) => [+ ...(previous ?? []).filter((anchor) => anchor.uuid !== response.uuid),+ response,+ ]);},applyDeletedAnchor(response: DeleteUnthreadedAnchorResponse) {mutateAnchors((previous) =>@@ -206,6 +302,27 @@ export function createPdfAnnotations(documentId: Accessor<string>) {}});},+ /** Bind an existing anchor to the message root just posted on it. */+ attachAnchorRoot(uuid: string, rootId: string) {+ mutateAnchors((previous) =>+ (previous ?? []).map((anchor) =>+ anchor.uuid === uuid ? { ...anchor, rootId } : anchor+ )+ );+ },+ /** A deleted message discussion takes its placeable with it and detaches its highlight. */+ applyThreadDeleted(rootId: string) {+ mutateAnchors((previous) =>+ (previous ?? []).flatMap((anchor) => {+ if (anchor.rootId !== rootId) return [anchor];+ if (anchor.anchorType === 'placeable') return [];+ return [{ ...anchor, rootId: null }];+ })+ );+ },+ refetchAnchors() {+ return refetchAnchors();+ },beginExistingHighlightCommentDraft(highlight: IHighlight) {batch(() => {setConvertedHighlightDraftId(highlight.uuid);@@ -272,7 +389,10 @@ export function createPdfAnnotations(documentId: Accessor<string>) {};return {+ /** Whether discussions read and write through the shared message API. */+ unified,anchors: () => anchorsResource(),+ anchorThread,commentThreads: () => commentThreadsResource(),highlightsByPage,highlightsByUuid,diff --git a/apps/web/src/features/block-pdf/queries/annotations.ts b/apps/web/src/features/block-pdf/queries/annotations.tsindex 969b090938..0aeb140df1 100644--- a/apps/web/src/features/block-pdf/queries/annotations.ts+++ b/apps/web/src/features/block-pdf/queries/annotations.ts@@ -1,4 +1,5 @@import { storageServiceClient } from '@service-storage/client';+import type { CreateUnthreadedAnchorRequest } from '@service-storage/generated/schemas/createUnthreadedAnchorRequest';export async function getPdfComments(documentId: string) {const result = await storageServiceClient.annotations.getComments({@@ -13,3 +14,18 @@ export async function getPdfAnchors(documentId: string) {});return result.isOk() ? result.value.data : [];}++export async function createPdfAnchor(+ documentId: string,+ body: CreateUnthreadedAnchorRequest+) {+ const result = await storageServiceClient.annotations.createAnchor({+ documentId,+ body,+ });+ if (result.isErr()) {+ console.error('Unable to create anchor');+ return null;+ }+ return result.value;+}diff --git a/apps/web/src/features/block-pdf/signal/tab.test.tsx b/apps/web/src/features/block-pdf/signal/tab.test.tsxindex edf23189e6..d1d6c38bc3 100644--- a/apps/web/src/features/block-pdf/signal/tab.test.tsx+++ b/apps/web/src/features/block-pdf/signal/tab.test.tsx@@ -19,6 +19,11 @@ vi.mock('../queries/annotations', () => ({getPdfComments: vi.fn(async () => []),}));+vi.mock('@queries/messages/document-messages', () => ({+ useMessageRootsQuery: () => ({ data: [] }),+ useMessageActions: () => ({}),+}));+afterEach(cleanup);type TabTestApi = {diff --git a/apps/web/src/features/block-pdf/store/comments/anchoredThread.ts b/apps/web/src/features/block-pdf/store/comments/anchoredThread.tsnew file mode 100644index 0000000000..d07d45739d--- /dev/null+++ b/apps/web/src/features/block-pdf/store/comments/anchoredThread.ts@@ -0,0 +1,80 @@+import type {+ PdfReply,+ PdfRoot,+ ThreadPayload,+ ViewerCommentType,+} from '@block-pdf/type/comments';+import {+ commentView,+ isLegacyComment,+ isMessageComment,+} from '@core/comments/commentType';+import { sortComments } from '../commentsResource';++/** The root and loaded replies of an anchored discussion, in the shared comment shape. */+export function anchoredThread(+ type: ViewerCommentType,+ thread: ThreadPayload+): { root: PdfRoot; replies: PdfReply[] } | null {+ const messages = thread.comments.filter(isMessageComment);+ if (messages.length > 0) {+ const [rootMessage, ...replyMessages] = messages;+ const commentBase = {+ type,+ isNew: false,+ threadId: thread.threadId,+ rootId: thread.rootId,+ anchorId: thread.anchorId,+ };+ const replies: PdfReply[] = replyMessages.map((message) => ({+ ...commentBase,+ ...commentView(message),+ }));+ const root: PdfRoot = {+ ...commentBase,+ ...commentView(rootMessage),+ children: replies.map((reply) => reply.id),+ replyCount: thread.replyCount,+ resolved: thread.isResolved,+ };+ return { root, replies };+ }++ const comments = thread.comments.filter(isLegacyComment).sort(sortComments);++ const rootComment = comments[0];+ if (!rootComment) return null;++ const commentBase = {+ type,+ isNew: false,+ threadId: rootComment.threadId,+ rootId: rootComment.commentId,+ anchorId: thread.anchorId,+ };++ const replies: PdfReply[] = [];+ for (let i = 1; i < comments.length; i++) {+ const comment = comments[i];+ replies.push({+ ...commentBase,+ id: comment.commentId,+ createdAt: comment.createdAt,+ owner: comment.owner,+ author: comment.sender || comment.owner,+ text: comment.text,+ });+ }++ const root: PdfRoot = {+ ...commentBase,+ id: rootComment.commentId,+ createdAt: rootComment.createdAt,+ owner: rootComment.owner,+ author: rootComment.sender || rootComment.owner,+ text: rootComment.text,+ children: replies.map((r) => r.id),+ };++ return { root, replies };+}diff --git a/apps/web/src/features/block-pdf/store/comments/commentEffect.ts b/apps/web/src/features/block-pdf/store/comments/commentEffect.tsindex 5acdbe59ad..3bd7b1bc81 100644--- a/apps/web/src/features/block-pdf/store/comments/commentEffect.ts+++ b/apps/web/src/features/block-pdf/store/comments/commentEffect.ts@@ -40,7 +40,7 @@ const useScrollToActiveThreadEffect = () => {if (activeThreadId == null) return;if (!hasActiveThread()) return;- if (typeof activeThreadId === 'number')+ if (!isPdfDraftThreadId(activeThreadId))scrollToCommentThread(activeThreadId);});};diff --git a/apps/web/src/features/block-pdf/store/comments/commentOperations.ts b/apps/web/src/features/block-pdf/store/comments/commentOperations.tsindex 36177774e6..2c7278d3e5 100644--- a/apps/web/src/features/block-pdf/store/comments/commentOperations.ts+++ b/apps/web/src/features/block-pdf/store/comments/commentOperations.ts@@ -7,15 +7,19 @@ import {import {type CommentId,type DeleteCommentInfo,+ isDraftThreadId,isRoot,+ type MessageCommentOperations,type ThreadId,} from '@core/comments/commentType';import { threadMeasureContainerId } from '@core/comments/Thread';+import { toast } from '@core/component/Toast/Toast';import type {CreateCommentRequest,EditCommentRequest,} from '@service-storage/generated/schemas';import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';+import type { Message } from '@service-storage/messages';import { createCallback } from '@solid-primitives/rootless';import { usePdfComments } from '../../context/pdf-comments-context';import { usePdfViewer } from '../../context/pdf-viewer-context';@@ -27,6 +31,13 @@ import {useDeleteCommentResource,useEditCommentResource,} from '../commentsResource';+import {+ useAttachHighlightMessageComment,+ useCreateFreeMessageComment,+ useCreateHighlightMessageComment,+ useCreateMessageThreadReply,+ useDeleteMessageThread,+} from '../messageCommentsResource';import { useDeleteNewFreeComment, useNewThreadPlaceable } from './freeComments';import { useDeleteNewHighlightComment } from './highlightComments';@@ -113,6 +124,104 @@ export function useCreateComment() {);}+/**+ * Message-path comment writes: a draft posts a root carrying its highlight or+ * placeable anchor; anything else replies to that root.+ */+export function useCreateMessageComment(): MessageCommentOperations['createComment'] {+ const analytics = useAnalytics();+ const annotations = usePdfDocument().annotations;+ const comments = usePdfComments();++ const deleteNewComments = useDeleteNewComments();+ const createFreeComment = useCreateFreeMessageComment();+ const createHighlightComment = useCreateHighlightMessageComment();+ const attachHighlightComment = useAttachHighlightMessageComment();+ const createThreadReply = useCreateMessageThreadReply();+ const newThreadPlaceable = useNewThreadPlaceable();++ return createCallback(async (input) => {+ analytics.track('comment_create', { blockType: 'pdf' });+ const { threadId, ...message } = input;++ if (!isDraftThreadId(threadId) && !isPdfDraftThreadId(threadId)) {+ return createThreadReply({ ...message, thread_id: String(threadId) });+ }++ // The shared composer posts with the generic draft id; the active thread+ // names the PDF draft being composed.+ const activeThreadId = comments.activeThreadId();+ const drafts = comments+ .all()+ .filter(+ (comment): comment is PdfRootLayout => isRoot(comment) && comment.isNew+ );+ const draft =+ drafts.find((comment) => comment.threadId === activeThreadId) ??+ drafts.at(0);+ if (!draft) {+ console.error('Unable to comment');+ return null;+ }++ let created: Message | null = null;+ switch (draft.type) {+ case 'highlight': {+ const highlight = annotations.highlightsByUuid()[draft.anchorId];+ if (!highlight) {+ console.error('Unable to find highlight');+ return null;+ }+ created = highlight.existsOnServer+ ? await attachHighlightComment(message, highlight.uuid)+ : await createHighlightComment(message, highlight);+ break;+ }+ case 'free': {+ const placeable = newThreadPlaceable();+ if (!placeable || placeable.internalId !== draft.anchorId) {+ console.error('Unable to find new thread placeable');+ return null;+ }+ created = await createFreeComment(message, placeable);+ break;+ }+ default:+ console.error('invalid comment type', draft.type);+ return null;+ }++ if (created) {+ deleteNewComments();+ comments.activateThread(created.id);+ }+ return created;+ });+}++/** Removes a whole message discussion; a draft is simply discarded. */+export function useDeleteMessageCommentThread() {+ const analytics = useAnalytics();+ const deleteThread = useDeleteMessageThread();+ const deleteNewComments = useDeleteNewComments();++ return createCallback(async (threadId: ThreadId) => {+ if (isDraftThreadId(threadId) || isPdfDraftThreadId(threadId)) {+ deleteNewComments();+ return false;+ }+ try {+ await deleteThread(String(threadId));+ } catch (error) {+ console.error('Unable to delete comment thread', error);+ toast.failure('Unable to delete comment');+ return false;+ }+ analytics.track('comment_delete', { blockType: 'pdf' });+ return true;+ });+}+export function useUpdateComment() {const analytics = useAnalytics();@@ -183,7 +292,7 @@ export function useScrollToCommentThread() {});};- return async (threadId: number) => {+ return async (threadId: ThreadId) => {const measureContainerId = threadMeasureContainerId(documentId(), threadId);let measureContainer = document.getElementById(measureContainerId);const pdfRoot = rootElement();diff --git a/apps/web/src/features/block-pdf/store/comments/freeComments.ts b/apps/web/src/features/block-pdf/store/comments/freeComments.tsindex d67e867e56..90afe0b1ce 100644--- a/apps/web/src/features/block-pdf/store/comments/freeComments.ts+++ b/apps/web/src/features/block-pdf/store/comments/freeComments.ts@@ -1,9 +1,7 @@import {createPdfDraftThreadId,type PdfComment,- type PdfReply,type PdfRoot,- type ViewerCommentType,} from '@block-pdf/type/comments';import {type IThreadPlaceable,@@ -13,7 +11,7 @@ import { useUserId } from '@core/context/user';import { createMemo } from 'solid-js';import { usePdfDocument } from '../../context/pdf-document-context';import { usePdfViewer } from '../../context/pdf-viewer-context';-import { sortComments } from '../commentsResource';+import { anchoredThread } from './anchoredThread';export { isThreadPlaceable };@@ -22,52 +20,6 @@ const getThreadPlaceablePos = (scaledPageHeight: number) => placeable.position.yPct * scaledPageHeight;-const getFreeCommentThread = (- commentPlaceable: IThreadPlaceable-): { root: PdfRoot; replies: PdfReply[] } | null => {- const commentType: ViewerCommentType = 'free';-- const thread = commentPlaceable.payload;- if (!thread) return null;-- const comments = [...thread.comments].sort(sortComments);-- const rootComment = comments[0];-- const commentBase = {- type: commentType,- isNew: false,- threadId: rootComment.threadId,- rootId: rootComment.commentId,- anchorId: commentPlaceable.internalId,- };-- const replies: PdfReply[] = [];- for (let i = 1; i < comments.length; i++) {- const comment = comments[i];- replies.push({- ...commentBase,- id: comment.commentId,- createdAt: comment.createdAt,- owner: comment.owner,- author: comment.sender || comment.owner,- text: comment.text,- });- }-- const root: PdfRoot = {- ...commentBase,- id: rootComment.commentId,- createdAt: rootComment.createdAt,- owner: rootComment.owner,- author: rootComment.sender || rootComment.owner,- text: rootComment.text,- children: replies.map((r) => r.id),- };-- return { root, replies };-};-const useServerCommentPlaceables = () => {const annotations = usePdfDocument().annotations;@@ -75,21 +27,14 @@ const useServerCommentPlaceables = () => {const anchorsData = annotations.anchors();if (!anchorsData || anchorsData.length === 0) return [];- const commentThreadsData = annotations.commentThreads();- if (!commentThreadsData || commentThreadsData.length === 0) return [];-const freeCommentAnchors = anchorsData.filter((a) => a.anchorType === 'placeable');return freeCommentAnchors.flatMap((a) => {- const commentThread = commentThreadsData.find(- (ct) => ct.thread.threadId === a.threadId- );- if (!commentThread) {- console.error('Comment thread not found for free comment anchor', a);- return [];- }+ // A comment placeable exists for its discussion; render once that has loaded.+ const thread = annotations.anchorThread(a);+ if (!thread) return [];// TODO: deprecate unneeded fieldsconst placeable: IThreadPlaceable = {@@ -104,14 +49,7 @@ const useServerCommentPlaceables = () => {heightPct: a.heightPct,rotation: 0,},- payload: {- threadId: commentThread.thread.threadId,- rootId: commentThread.comments[0].commentId,- anchorId: a.uuid,- page: a.page,- comments: commentThread.comments,- isResolved: commentThread.thread.resolved,- },+ payload: thread,allowableEdits: a.allowableEdits as any,wasEdited: a.wasEdited,wasDeleted: a.wasDeleted,@@ -169,8 +107,8 @@ export const useFreeComments = () => {originalYPosition,};- const isNew = commentPlaceable.payload == null;- if (isNew) {+ const thread = commentPlaceable.payload;+ if (!thread) {const currentUserId = userId();if (!currentUserId) {console.error('User ID not found');@@ -197,7 +135,7 @@ export const useFreeComments = () => {continue;}- const freeCommentThread = getFreeCommentThread(commentPlaceable);+ const freeCommentThread = anchoredThread('free', thread);if (!freeCommentThread) continue;const { root, replies } = freeCommentThread;diff --git a/apps/web/src/features/block-pdf/store/comments/highlightComments.ts b/apps/web/src/features/block-pdf/store/comments/highlightComments.tsindex 6789b82a34..d4cdedd80b 100644--- a/apps/web/src/features/block-pdf/store/comments/highlightComments.ts+++ b/apps/web/src/features/block-pdf/store/comments/highlightComments.ts@@ -3,9 +3,7 @@ import { useCurrentPageViewport } from '@block-pdf/signal/pdfViewer';import {createPdfDraftThreadId,type PdfComment,- type PdfReply,type PdfRoot,- type ViewerCommentType,} from '@block-pdf/type/comments';import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';import { useUserId } from '@core/context/user';@@ -19,7 +17,7 @@ import {HighlightType,type IHighlight,} from '../../model/Highlight';-import { sortComments } from '../commentsResource';+import { anchoredThread } from './anchoredThread';import { useDeleteNewComments } from './commentOperations';const getHighlightPos = (highlight: IHighlight, viewportHeight: number) => {@@ -33,52 +31,6 @@ const getHighlightPos = (highlight: IHighlight, viewportHeight: number) => {}};-const getHighlightThread = (- highlight: IHighlight-): { root: PdfRoot; replies: PdfReply[] } | null => {- const commentType: ViewerCommentType = 'highlight';-- const thread = highlight.thread;- if (!thread) return null;-- const comments = [...thread.comments].sort(sortComments);-- const rootComment = comments[0];-- const commentBase = {- type: commentType,- isNew: false,- threadId: rootComment.threadId,- rootId: rootComment.commentId,- anchorId: highlight.uuid,- };-- const replies: PdfReply[] = [];- for (let i = 1; i < comments.length; i++) {- const comment = comments[i];- replies.push({- ...commentBase,- id: comment.commentId,- createdAt: comment.createdAt,- owner: comment.owner,- author: comment.sender || comment.owner,- text: comment.text,- });- }-- const root: PdfRoot = {- ...commentBase,- id: rootComment.commentId,- createdAt: rootComment.createdAt,- owner: rootComment.owner,- author: rootComment.sender || rootComment.owner,- text: rootComment.text,- children: replies.map((r) => r.id),- };-- return { root, replies };-};-export const useHighlightComments = () => {const userId = useUserId();const pdf = usePdfDocument();@@ -133,7 +85,8 @@ export const useHighlightComments = () => {continue;}- const highlightThread = getHighlightThread(highlight);+ if (!highlight.thread) continue;+ const highlightThread = anchoredThread('highlight', highlight.thread);if (!highlightThread) continue;const { root, replies } = highlightThread;diff --git a/apps/web/src/features/block-pdf/store/commentsResource.test.ts b/apps/web/src/features/block-pdf/store/commentsResource.test.tsnew file mode 100644index 0000000000..990df47c03--- /dev/null+++ b/apps/web/src/features/block-pdf/store/commentsResource.test.ts@@ -0,0 +1,47 @@+import type { MessageEvent } from '@service-storage/generated/schemas/messageEvent';+import type { Message } from '@service-storage/messages';+import { describe, expect, it, vi } from 'vitest';+import { changesAnchors } from './commentsResource';++vi.mock('@service-connection/websocket', () => ({+ createConnectionWebsocketEffect: vi.fn(),+ parseWebsocketPayload: vi.fn(),+}));++const parent = { type: 'document', id: 'document-1' } as const;++function posted(threadId: string | null): MessageEvent {+ return {+ actor: 'user-1',+ parent,+ change: {+ type: 'posted',+ message: { id: 'message-1', parent, thread_id: threadId } as Message,+ mentions: [],+ },+ } as unknown as MessageEvent;+}++describe('changesAnchors', () => {+ it('reloads anchors when a message client posts a root or changes a thread', () => {+ const threadUpdated = {+ actor: 'user-1',+ parent,+ change: { type: 'thread_updated', state: {} },+ } as MessageEvent;++ expect({+ root: changesAnchors(posted(null), 'document-1'),+ reply: changesAnchors(posted('root-1'), 'document-1'),+ threadUpdated: changesAnchors(threadUpdated, 'document-1'),+ otherDocument: changesAnchors(posted(null), 'document-2'),+ malformed: changesAnchors(undefined, 'document-1'),+ }).toEqual({+ root: true,+ reply: false,+ threadUpdated: true,+ otherDocument: false,+ malformed: false,+ });+ });+});diff --git a/apps/web/src/features/block-pdf/store/commentsResource.ts b/apps/web/src/features/block-pdf/store/commentsResource.tsindex 8c8d63835e..78427ea2eb 100644--- a/apps/web/src/features/block-pdf/store/commentsResource.ts+++ b/apps/web/src/features/block-pdf/store/commentsResource.ts@@ -2,8 +2,11 @@ import type { IHighlight } from '@block-pdf/model/Highlight';import type { IThreadPlaceable } from '@block-pdf/type/placeables';import { useUserId } from '@core/context/user';import { compareDateAsc } from '@core/util/date';--import { createConnectionWebsocketEffect } from '@service-connection/websocket';+import { onThreadStateUpdated } from '@queries/messages/sync';+import {+ createConnectionWebsocketEffect,+ parseWebsocketPayload,+} from '@service-connection/websocket';import { storageServiceClient } from '@service-storage/client';import type { AnnotationIncrementalUpdate } from '@service-storage/generated/schemas/annotationIncrementalUpdate';import type { Comment } from '@service-storage/generated/schemas/comment';@@ -15,6 +18,8 @@ import type { DeleteCommentRequest } from '@service-storage/generated/schemas/deimport type { DeleteUnthreadedAnchorRequest } from '@service-storage/generated/schemas/deleteUnthreadedAnchorRequest';import type { EditAnchorRequest } from '@service-storage/generated/schemas/editAnchorRequest';import type { EditCommentRequest } from '@service-storage/generated/schemas/editCommentRequest';+import type { MessageEvent } from '@service-storage/generated/schemas/messageEvent';+import { onCleanup } from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';export const sortComments = (a: Comment, b: Comment) => {@@ -350,11 +355,40 @@ export function useEditPdfFreeCommentAnchor() {};}+/**+ * A message-path discussion creates, binds, or removes its anchor on the+ * server: a new root or a thread state change. Both paths reload anchors on+ * one, so neither acts on a stale binding.+ */+export function changesAnchors(+ event: MessageEvent | undefined,+ documentId: string+) {+ if (event?.parent?.type !== 'document' || event.parent.id !== documentId)+ return false;+ const change = event.change;+ if (change.type === 'thread_updated') return true;+ return change.type === 'posted' && !change.message.thread_id;+}++/** Annotation updates that only concern legacy comment threads. */+const legacyCommentUpdates = new Set([+ 'create-comment',+ 'edit-comment',+ 'delete-comment',+]);+export function usePdfCommentRealtimeBehavior() {const currentUserId = useUserId();const { annotations, documentId } = usePdfDocument();createConnectionWebsocketEffect((msg) => {+ if (msg.type === 'message_update') {+ const event = parseWebsocketPayload<MessageEvent>(msg.type, msg.data);+ if (changesAnchors(event, documentId()))+ void annotations.commands.refetchAnchors();+ return;+ }if (msg.type === 'comment') {let incrementalUpdate: AnnotationIncrementalUpdate;try {@@ -369,6 +403,12 @@ export function usePdfCommentRealtimeBehavior() {console.warn('unable to parse annotation incremental update', e);return;}+ // Message-path discussions are not in the legacy comment store.+ if (+ annotations.unified &&+ legacyCommentUpdates.has(incrementalUpdate.updateType)+ )+ return;switch (incrementalUpdate.updateType) {case 'create-comment':@@ -407,4 +447,17 @@ export function usePdfCommentRealtimeBehavior() {}}});++ if (annotations.unified) {+ onCleanup(+ onThreadStateUpdated((parent, state) => {+ if (+ parent.type === 'document' &&+ parent.id === documentId() &&+ state.deleted_at+ )+ annotations.commands.applyThreadDeleted(state.root_id);+ })+ );+ }}diff --git a/apps/web/src/features/block-pdf/store/highlight.ts b/apps/web/src/features/block-pdf/store/highlight.tsindex cdc0084a94..4d3deba0ab 100644--- a/apps/web/src/features/block-pdf/store/highlight.ts+++ b/apps/web/src/features/block-pdf/store/highlight.ts@@ -1,4 +1,5 @@import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';+import { toast } from '@core/component/Toast/Toast';import { batch } from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';import { Highlight, type IHighlight } from '../model/Highlight';@@ -6,6 +7,7 @@ import {useCreateUnthreadedHighlightResource,useDeleteUnthreadedHighlightResource,} from './commentsResource';+import { useDeleteMessageThread } from './messageCommentsResource';export const useSetSelectionHighlights = () => {const pdf = usePdfDocument();@@ -50,10 +52,26 @@ export const useAddNewHighlights = () => {export function useRemoveHighlight() {const deleteHighlight = useDeleteUnthreadedHighlightResource();+ const deleteMessageThread = useDeleteMessageThread();const pdf = usePdfDocument();- return (uuid: string) => {+ return async (uuid: string) => {pdf.closeSelectionMenu();- deleteHighlight(uuid);+ // The annotation endpoint deletes only a legacy thread with its highlight,+ // so a message discussion goes first; the server then detaches the highlight.+ const rootId = pdf.annotations.unified+ ? pdf.annotations.anchors()?.find((anchor) => anchor.uuid === uuid)+ ?.rootId+ : null;+ try {+ if (rootId) await deleteMessageThread(rootId);+ await deleteHighlight(uuid);+ } catch (error) {+ console.error('Unable to remove highlight', error);+ toast.failure('Unable to remove highlight');+ }+ // Supersede the reload the discussion delete started, which can+ // otherwise land after the highlight is gone and restore it.+ if (rootId) void pdf.annotations.commands.refetchAnchors();};}diff --git a/apps/web/src/features/block-pdf/store/messageCommentsResource.ts b/apps/web/src/features/block-pdf/store/messageCommentsResource.tsnew file mode 100644index 0000000000..03d72a4ee3--- /dev/null+++ b/apps/web/src/features/block-pdf/store/messageCommentsResource.ts@@ -0,0 +1,155 @@+import type { IHighlight } from '@block-pdf/model/Highlight';+import type { IThreadPlaceable } from '@block-pdf/type/placeables';+import { useMessageActions } from '@queries/messages/document-messages';+import type { CreateUnthreadedAnchorRequest } from '@service-storage/generated/schemas/createUnthreadedAnchorRequest';+import type { CreateUnthreadedAnchorResponse } from '@service-storage/generated/schemas/createUnthreadedAnchorResponse';+import type { PostMessage } from '@service-storage/messages';+import { usePdfDocument } from '../context/pdf-document-context';+import { createPdfAnchor } from '../queries/annotations';++/** A comment body without its thread placement, which the PDF resources decide. */+export type MessageCommentInput = Omit<PostMessage, 'thread_id' | 'anchor'>;++function useDocumentMessageActions() {+ const { documentId } = usePdfDocument();+ return useMessageActions(() => ({ type: 'document', id: documentId() }));+}++async function createHighlightAnchor(+ documentId: string,+ highlight: IHighlight+): Promise<CreateUnthreadedAnchorResponse | null> {+ if (highlight.pageViewport == null) {+ console.error('Highlight page viewport is null');+ return null;+ }+ const body: CreateUnthreadedAnchorRequest = {+ uuid: highlight.uuid,+ page: highlight.pageNum,+ fileType: 'pdf',+ anchorType: 'highlight',+ text: highlight.text,+ alpha: highlight.color.alpha ?? 1,+ blue: highlight.color.blue,+ red: highlight.color.red,+ green: highlight.color.green,+ highlightRects: highlight.rects,+ highlightType: 1,+ pageViewportHeight: highlight.pageViewport.height,+ pageViewportWidth: highlight.pageViewport.width,+ };+ return createPdfAnchor(documentId, body);+}++/** Posts a root whose placeable anchor the server creates with it. */+export function useCreateFreeMessageComment() {+ const { annotations, documentId } = usePdfDocument();+ const messages = useDocumentMessageActions();++ return async (input: MessageCommentInput, placeable: IThreadPlaceable) => {+ const [page] = placeable.pageRange;+ if (page === undefined) {+ throw new Error('Cannot create a PDF comment without a page');+ }+ const message = await messages.post({+ ...input,+ anchor: {+ type: 'pdf_placeable',+ anchor_id: placeable.internalId,+ page,+ x_pct: placeable.position.xPct,+ y_pct: placeable.position.yPct,+ width_pct: placeable.position.widthPct,+ height_pct: placeable.position.heightPct,+ },+ });+ // Show the placeable from the draft's geometry until the anchors reload.+ annotations.commands.applyCreatedAnchor({+ anchorType: 'placeable',+ documentId: documentId(),+ uuid: placeable.internalId,+ owner: placeable.owner,+ rootId: message.id,+ page,+ originalPage: placeable.originalPage,+ originalIndex: placeable.originalIndex,+ xPct: placeable.position.xPct,+ yPct: placeable.position.yPct,+ widthPct: placeable.position.widthPct,+ heightPct: placeable.position.heightPct,+ rotation: placeable.position.rotation,+ allowableEdits: placeable.allowableEdits,+ wasEdited: placeable.wasEdited,+ wasDeleted: placeable.wasDeleted,+ shouldLockOnSave: placeable.shouldLockOnSave,+ });+ void annotations.commands.refetchAnchors();+ return message;+ };+}++/** Posts a root on a highlight that already exists on the server. */+export function useAttachHighlightMessageComment() {+ const annotations = usePdfDocument().annotations;+ const messages = useDocumentMessageActions();++ return async (input: MessageCommentInput, uuid: string) => {+ const message = await messages.post({+ ...input,+ anchor: { type: 'pdf_highlight', anchor_id: uuid },+ });+ annotations.commands.attachAnchorRoot(uuid, message.id);+ void annotations.commands.refetchAnchors();+ return message;+ };+}++/**+ * Saves a drafted highlight, then posts its root. The anchor joins the local+ * state together with its discussion so the draft card is replaced by the+ * thread rather than by a bare highlight.+ */+export function useCreateHighlightMessageComment() {+ const { annotations, documentId } = usePdfDocument();+ const messages = useDocumentMessageActions();++ return async (input: MessageCommentInput, highlight: IHighlight) => {+ const anchor = await createHighlightAnchor(documentId(), highlight);+ if (!anchor) return null;+ try {+ const message = await messages.post({+ ...input,+ anchor: { type: 'pdf_highlight', anchor_id: anchor.uuid },+ });+ annotations.commands.applyCreatedAnchor({+ ...anchor,+ rootId: message.id,+ });+ void annotations.commands.refetchAnchors();+ return message;+ } catch (error) {+ // The highlight was saved; keep it visible without a discussion.+ annotations.commands.applyCreatedAnchor(anchor);+ throw error;+ }+ };+}++export function useCreateMessageThreadReply() {+ const messages = useDocumentMessageActions();++ return (input: MessageCommentInput & { thread_id: string }) =>+ messages.post(input);+}++/** Deletes a discussion; the server removes its placeable or detaches its highlight. */+export function useDeleteMessageThread() {+ const annotations = usePdfDocument().annotations;+ const messages = useDocumentMessageActions();++ return async (rootId: string) => {+ await messages.deleteThread(rootId);+ annotations.commands.applyThreadDeleted(rootId);+ void annotations.commands.refetchAnchors();+ };+}diff --git a/apps/web/src/features/block-pdf/store/placeables.test.tsx b/apps/web/src/features/block-pdf/store/placeables.test.tsxindex 17e4debeef..c89d46b50f 100644--- a/apps/web/src/features/block-pdf/store/placeables.test.tsx+++ b/apps/web/src/features/block-pdf/store/placeables.test.tsx@@ -18,6 +18,11 @@ vi.mock('../queries/annotations', () => ({getPdfComments: vi.fn(async () => []),}));+vi.mock('@queries/messages/document-messages', () => ({+ useMessageRootsQuery: () => ({ data: [] }),+ useMessageActions: () => ({}),+}));+vi.mock('@core/context/user', () => ({useUserId: () => () => 'user-1',}));@@ -28,6 +33,7 @@ vi.mock('../signal/pdfViewer', () => ({vi.mock('./comments/commentOperations', () => ({useDeleteComment: () => vi.fn(),+ useDeleteMessageCommentThread: () => vi.fn(),useDeleteNewComments: () => vi.fn(),}));diff --git a/apps/web/src/features/block-pdf/store/placeables.ts b/apps/web/src/features/block-pdf/store/placeables.tsindex af08709e68..87797bc7cf 100644--- a/apps/web/src/features/block-pdf/store/placeables.ts+++ b/apps/web/src/features/block-pdf/store/placeables.ts@@ -3,6 +3,7 @@ import { PageModel } from '@block-pdf/model/Page';import { useIsPopup } from '@block-pdf/signal/pdfViewer';import {useDeleteComment,+ useDeleteMessageCommentThread,useDeleteNewComments,} from '@block-pdf/store/comments/commentOperations';import { createPdfDraftThreadId } from '@block-pdf/type/comments';@@ -679,6 +680,8 @@ export function useDeletePlaceable() {const modificationData = pdf.model.modificationData;const placeableIdMap = usePlaceableIdMap();const deleteComment = useDeleteComment();+ const deleteMessageCommentThread = useDeleteMessageCommentThread();+ const deleteNewComments = useDeleteNewComments();return createCallback((uuid: string) => {const placeable = placeableIdMap()[uuid];@@ -687,6 +690,16 @@ export function useDeletePlaceable() {return;}+ if (isThreadPlaceable(placeable) && pdf.annotations.unified) {+ const threadId = placeable.payload?.threadId;+ if (threadId == null) {+ deleteNewComments();+ return;+ }+ void deleteMessageCommentThread(threadId);+ return;+ }+if (isThreadPlaceable(placeable)) {let rootId = placeable.payload?.rootId;if (!rootId) {diff --git a/apps/web/src/features/block-pdf/type/comments.ts b/apps/web/src/features/block-pdf/type/comments.tsindex 7fbb6934ee..32dc75976d 100644--- a/apps/web/src/features/block-pdf/type/comments.ts+++ b/apps/web/src/features/block-pdf/type/comments.ts@@ -5,13 +5,20 @@ import type {ThreadId,} from '@core/comments/commentType';import type { Comment } from '@service-storage/generated/schemas/comment';+import type { Message } from '@service-storage/messages';+/**+ * The discussion on a PDF anchor: legacy annotation comments, or a message+ * root with its loaded reply preview when the document is on the message API.+ */export type ThreadPayload = {- threadId: number;- rootId: number;+ threadId: ThreadId;+ rootId: CommentId;anchorId: string; // uuidpage: number;- comments: Comment[];+ comments: Comment[] | Message[];+ /** Total live replies of a message thread; comments holds only the loaded preview. */+ replyCount?: number;isResolved: boolean;};diff --git a/apps/web/src/lib/core/comments/Thread.test.tsx b/apps/web/src/lib/core/comments/Thread.test.tsxindex ef0866a503..0db1dc7175 100644--- a/apps/web/src/lib/core/comments/Thread.test.tsx+++ b/apps/web/src/lib/core/comments/Thread.test.tsx@@ -137,9 +137,12 @@ describe('anchored comment links', () => {expect(view.getByText('9')).toBeTruthy();expect(view.queryByText('4')).toBeNull();});+ // A document passes message operations exactly when it reads through the+ // message API, which follows the flag unless a test says otherwise.const renderThreadBody = (documentType: CommentsContextType['documentType'] = 'md',- minimized = false+ minimized = false,+ messageApi = mocks.unifiedDiscussions) =>render(() => (<CommentsContext.Provider@@ -155,7 +158,9 @@ describe('anchored comment links', () => {ownedComment: () => false,inComment: true,commentOperations: noopCommentOperations,- messageOperations: { createComment: async () => null },+ messageOperations: messageApi+ ? { createComment: async () => null }+ : undefined,}}>{minimized ? (@@ -183,9 +188,16 @@ describe('anchored comment links', () => {});- it('keeps PDF on the legacy path while its flag-on discussion is deferred', () => {+ it('renders a PDF on the message API through the message thread', () => {const view = renderThreadBody('pdf');- // The message thread (mocked as the copy-link anchor) is markdown-only.+ const url = new URL(view.getByRole('link').getAttribute('href')!);+ expect(url.pathname).toBe('/app/pdf/document');+ });++ it('keeps a PDF on the legacy path when its annotations did not choose the message API', () => {+ // The flag is on, but the PDF read it as off when its annotations loaded.+ const view = renderThreadBody('pdf', false, false);+ // The message thread is mocked as the copy-link anchor.expect(view.queryByRole('link')).toBeNull();expect(view.getByText('Comment')).toBeTruthy();});diff --git a/apps/web/src/lib/core/comments/Thread.tsx b/apps/web/src/lib/core/comments/Thread.tsxindex 4d55cfc815..5cf0f137bd 100644--- a/apps/web/src/lib/core/comments/Thread.tsx+++ b/apps/web/src/lib/core/comments/Thread.tsx@@ -154,11 +154,14 @@ type ThreadBodyProps = {* renders it directly.*/export function ThreadBody(props: ThreadBodyProps) {- // PDF flag-on discussions are deferred, so PDF stays on the legacy path even- // when the flag is on; only markdown documents use the message thread.const context = useContext(CommentsContext);- return isFeatureEnabled(enableUnifiedDocumentDiscussions) &&- context.documentType !== 'pdf' ? (+ // A PDF picks its comment store once, when its annotations load, and passes+ // message operations exactly when it chose the message API.+ const unified =+ context.documentType === 'pdf'+ ? context.messageOperations != null+ : isFeatureEnabled(enableUnifiedDocumentDiscussions);+ return unified ? (<MessageThreadBody {...props} />) : (<LegacyThreadBody {...props} />diff --git a/apps/web/src/lib/document-processing-types/pdf/protocol.ts b/apps/web/src/lib/document-processing-types/pdf/protocol.tsindex 58ce6e091d..4072b5989e 100644--- a/apps/web/src/lib/document-processing-types/pdf/protocol.ts+++ b/apps/web/src/lib/document-processing-types/pdf/protocol.ts@@ -1,4 +1,5 @@import type { Comment } from '@service-storage/generated/schemas/comment';+import type { Message } from '@service-storage/messages';import { z } from 'zod';const numberSetSchema = z@@ -21,12 +22,19 @@ export enum PdfShapeType {SQUARE = 'square',}+/**+ * A PDF comment thread: legacy annotation comments with numeric ids, or a+ * message root and its loaded reply preview when the document reads through+ * the shared message API.+ */export type PdfThreadPayload = {- threadId: number;- rootId: number;+ threadId: number | string;+ rootId: number | string;anchorId: string;page: number;- comments: Comment[];+ comments: Comment[] | Message[];+ /** Total live replies of a message thread; comments holds only the loaded preview. */+ replyCount?: number;isResolved: boolean;};diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 73e98a07ec..b73e8dd6b4 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -529,10 +529,19 @@ editable view removes the retained mark when the document loads. Read-onlyviewers see plain text without a dead comment highlight; the stored documentand overlapping live comments stay intact.-Unified PDF discussions are deferred: PDFs keep the legacy comment subsystem-regardless of the flag, so PDF comments (the side-panel `Comments` section,-anchored margin threads, highlight comments, and placeable comments) behave as-they do with the flag off. The message-backed PDF path is a follow-up.+PDFs follow the same flag. With it on, PDF comment threads in the right margin+use the channel composer (`Leave a comment...`, Enter sends) and the message+thread controls. Highlight comments come from selecting text and choosing the+comment button in the selection menu; placeable comments come from the toolbar+`Comment` tool and a click on the page. Discussions read and post through+`/dss/messages/document/<id>`; anchor geometry still loads from+`/dss/annotations/anchors/document/<id>`, and `/dss/annotations/comments/...`+is not called. Deleting a highlight's discussion keeps the highlight as a plain+highlight; deleting a placeable's discussion removes the placeable. With the+flag off, PDFs use the legacy composer (`Add a comment...`). A PDF anchor+created by the other path is hidden rather than shown as a bare highlight, so a+comment written on one path does not appear on the other until the comment+importer runs.With the flag off, documents behave exactly as described above this section.