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): simplify document discussion controls (#6628)
gbirmanfea63bdfc2df
diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.tsxindex 6dc174a8ae..eccb629b11 100644--- a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx@@ -82,7 +82,6 @@ export function MessageDocumentDiscussion(props: {<DocumentConversationparent={parent}canWrite={permissions.canComment()}- canManage={permissions.isOwner()}targetId={params.commentId()}label={props.label}buildLink={(message) =>diff --git a/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx b/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsxindex 864f461b46..e5cee42dce 100644--- a/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx+++ b/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx@@ -34,7 +34,6 @@ vi.mock('@core/messages/DocumentConversation', () => ({DocumentConversation: (props: {parent: { type: string; id: string };canWrite: boolean;- canManage: boolean;buildLink: (message: { id: string }) => string;hideComposer?: boolean;hideWhenEmpty?: boolean;@@ -101,7 +100,6 @@ describe('mobile document discussion accessory behind the flag', () => {expect.objectContaining({parent: { type: 'document', id: 'document' },canWrite: true,- canManage: false,hideComposer: true,hideWhenEmpty: true,})diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsxindex 0811f07063..c53550cb62 100644--- a/apps/web/src/features/channel/Input/ChannelInput.tsx+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx@@ -24,7 +24,7 @@ import {} from '@core/util/upload';import type { EntityData } from '@entity';import type { MessageParent } from '@service-storage/messages';-import { CollapsedInput, ComposerSurface } from '@ui';+import { CollapsedInput, ComposerSurface, cn } from '@ui';import { $getRoot } from 'lexical';import {type Accessor,@@ -34,6 +34,7 @@ import {Show,Switch,} from 'solid-js';+import { Dynamic } from 'solid-js/web';import { useAgentMentionUsers } from '../use-agent-mention-users';import { useMessageBotMentionUsers } from '../use-channel-bot-mention-users';import { CHANNEL_FILE_PICKER_ACCEPT } from './accepted-file-types';@@ -77,6 +78,13 @@ export type ChannelInputProps = InputCallbacks & {* Defaults to `false`.*/collapsible?: boolean;+ /**+ * Drop the composer's own card chrome (rounding, background, shadow) and sit+ * flat on whatever surface hosts it. For composers that already live inside a+ * card, such as a document margin thread, where the composer's card would+ * read as a second box inside the first.+ */+ flat?: boolean;};function WebDefaultActions(props: { input: InputData }) {@@ -474,17 +482,20 @@ export function ChannelInput(props: ChannelInputProps) {onSend={() => void inputState.commands.send()}/></Show>- <ComposerSurface- onFocusOut={(e) => {+ <Dynamic+ component={props.flat ? 'div' : ComposerSurface}+ onFocusOut={(e: FocusEvent & { currentTarget: HTMLElement }) => {const next = e.relatedTarget as Node | null;if (next && e.currentTarget.contains(next)) return;if (isInternalRefocus) return;collapsedInput.collapse();}}- class={isCollapsed() ? 'hidden' : undefined}+ // `ComposerSurface` stretches itself; a bare div would take its+ // content width inside a centering flex host, such as the margin card.+ class={cn(props.flat && 'w-full', isCollapsed() && 'hidden')}>{renderSurfaceContent()}- </ComposerSurface>+ </Dynamic></Input.Root>);}diff --git a/apps/web/src/lib/core/comments/Thread.tsx b/apps/web/src/lib/core/comments/Thread.tsxindex 347e5b2e8e..1fba6fc116 100644--- a/apps/web/src/lib/core/comments/Thread.tsx+++ b/apps/web/src/lib/core/comments/Thread.tsx@@ -133,6 +133,13 @@ type ThreadBodyProps = {* instead of hover-revealed buttons (the touch drawer has no hover).*/actionsDropdown?: boolean;+ /**+ * The host already draws a card — the floating margin thread. A draft's+ * composer drops its own card chrome so it does not read as a box inside a+ * box. The touch drawer leaves this off: there the composer sits on the+ * drawer body and its card is the only one.+ */+ flatComposer?: boolean;};/**@@ -171,6 +178,7 @@ function MessageThreadBody(props: ThreadBodyProps) {<ChannelInputparent={parent()}participants={participants}+ flat={props.flatComposer}input={{ mode: 'reply', placeholder: 'Leave a comment...' }}onClose={() => context.setActiveThread(null)}onSend={async (snapshot) => {@@ -191,7 +199,6 @@ function MessageThreadBody(props: ThreadBodyProps) {parent={parent()}rootId={String(props.comment.threadId)}canWrite={context.canComment()}- canManage={context.isDocumentOwner()}hideReplyInput={props.hideReplyInput}onEditingChange={context.setMessageEditing}targetId={targetId()}@@ -438,6 +445,7 @@ export function Thread(props: {comment={props.comment}isActive={props.isActive}theme={props.theme}+ flatComposer/></div></Layer>diff --git a/apps/web/src/lib/core/messages/DocumentConversation.test.tsx b/apps/web/src/lib/core/messages/DocumentConversation.test.tsxindex e07c40e960..3664a5cb1b 100644--- a/apps/web/src/lib/core/messages/DocumentConversation.test.tsx+++ b/apps/web/src/lib/core/messages/DocumentConversation.test.tsx@@ -1,6 +1,5 @@-import type { ReferencedThread } from '@service-storage/generated/schemas/referencedThread';import type { MessageListItem } from '@service-storage/messages';-import { cleanup, fireEvent, render } from '@solidjs/testing-library';+import { cleanup, render } from '@solidjs/testing-library';import { type Accessor, createSignal, For, type ParentProps } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';import { DocumentConversation } from './DocumentConversation';@@ -10,8 +9,6 @@ const mocks = vi.hoisted(() => ({linkResolved: true,contacts: [{ id: 'user|[email protected]', name: 'Ann', email: '[email protected]' }],capturedParticipants: undefined as (() => Array<{ id: string }>) | undefined,- references: vi.fn(),- source: vi.fn(),}));vi.mock('@channel/Input', () => ({@@ -51,9 +48,6 @@ vi.mock('@queries/messages/document-messages', () => ({vi.mock('@queries/messages/mutations', () => ({useSendMessageMutation: () => ({}),}));-vi.mock('@queries/messages/references', () => ({- useChannelReferenceThreadsQuery: mocks.references,-}));vi.mock('@queries/messages/timeline', () => ({useMessageTimelineQuery: mocks.timeline,}));@@ -66,18 +60,6 @@ vi.mock('./MessageThread', () => ({</For></article>),- MessageThreadFromSource: (props: {- parent: ReferencedThread['parent'];- rootId: string;- canWrite: boolean;- }) => {- mocks.source({- parent: props.parent,- rootId: props.rootId,- canWrite: props.canWrite,- });- return <article>source {props.rootId}</article>;- },}));afterEach(() => {@@ -114,21 +96,6 @@ function thread(const anchor = { type: 'markdown', mark_id: 'mark' } as const;-const sources: ReferencedThread[] = [- {- parent: { type: 'channel', id: 'launch' },- root_id: 'source-a',- channel_name: 'Launch',- can_reply: true,- },- {- parent: { type: 'channel', id: 'archive' },- root_id: 'source-b',- channel_name: null,- can_reply: false,- },-];-function discussion(initialPages: MessageListItem[][],targetId?: string,@@ -139,32 +106,14 @@ function discussion(} = {}) {const [pages, setPages] = createSignal(initialPages);- const [referencesFailed, setReferencesFailed] = createSignal(false);mocks.timeline.mockReturnValue({isSuccess: true,get data() {return { pages: pages().map((items) => ({ items })) };},});- mocks.references.mockImplementation(- (_parent: unknown, enabled: Accessor<boolean>) => ({- get isPending() {- return !enabled();- },- get isSuccess() {- return enabled() && !referencesFailed();- },- get isError() {- return enabled() && referencesFailed();- },- get data() {- return enabled() ? sources : undefined;- },- })- );return {setPages,- setReferencesFailed,...render(() => (<DocumentConversationparent={{ type: 'document', id: 'document' }}@@ -283,96 +232,4 @@ describe('DocumentConversation placement', () => {'remote discussion',]);});-- it('adds channel threads that mention the document only while requested, each against its source channel', () => {- const view = discussion([[thread('discussion', null)]]);- const toggle = view.getByRole<HTMLInputElement>('checkbox', {- name: 'Include channel mentions',- });- expect(toggle.checked).toBe(false);- expect(view.queryByText('source source-a')).toBeNull();- expect(mocks.source).not.toHaveBeenCalled();-- fireEvent.click(toggle);- expect(view.getAllByRole('article').map((el) => el.textContent)).toEqual([- 'discussion',- 'source source-a',- 'source source-b',- ]);- expect(- view.getByRole('link', { name: 'From Launch' }).getAttribute('href')- ).toBe('/channel/launch/source-a');- expect(- view- .getByRole('link', { name: 'From Channel conversation' })- .getAttribute('href')- ).toBe('/channel/archive/source-b');- expect(mocks.source.mock.calls.map(([props]) => props)).toEqual([- {- parent: { type: 'channel', id: 'launch' },- rootId: 'source-a',- canWrite: true,- },- {- parent: { type: 'channel', id: 'archive' },- rootId: 'source-b',- canWrite: false,- },- ]);-- fireEvent.click(toggle);- expect(view.getAllByRole('article').map((el) => el.textContent)).toEqual([- 'discussion',- ]);- });-- it('keeps the toggle inside a touch conversation and keeps shown source threads visible once the roots are gone', () => {- const view = discussion([[]], undefined, {- hideComposer: true,- hideWhenEmpty: true,- });- expect(view.queryByRole('checkbox')).toBeNull();-- view.setPages([[thread('discussion', null)]]);- fireEvent.click(- view.getByRole('checkbox', { name: 'Include channel mentions' })- );- expect(view.getByText('source source-a')).toBeTruthy();-- view.setPages([[]]);- expect(view.getByRole('button', { name: /Discussion/ })).toBeTruthy();- expect(view.getAllByRole('article').map((el) => el.textContent)).toEqual([- 'source source-a',- 'source source-b',- ]);-- // The disabled query still holds its last result; unchecking must not keep- // an empty Discussion mounted on touch.- fireEvent.click(- view.getByRole('checkbox', { name: 'Include channel mentions' })- );- expect(view.queryByRole('button', { name: /Discussion/ })).toBeNull();- expect(view.queryAllByRole('article')).toEqual([]);- });-- it('keeps the last authorized source threads on a failed refresh and offers a retry', () => {- const view = discussion([[thread('discussion', null)]]);- fireEvent.click(- view.getByRole('checkbox', { name: 'Include channel mentions' })- );- view.setReferencesFailed(true);- expect(view.getAllByRole('article').map((el) => el.textContent)).toEqual([- 'discussion',- 'source source-a',- 'source source-b',- ]);- expect(- view.getByRole('button', {- name: 'Could not load channel mentions. Retry',- })- ).toBeTruthy();- expect(- view.queryByText('No channel threads mention this document.')- ).toBeNull();- });});diff --git a/apps/web/src/lib/core/messages/DocumentConversation.tsx b/apps/web/src/lib/core/messages/DocumentConversation.tsxindex 370bc20fa6..f9f1f7c070 100644--- a/apps/web/src/lib/core/messages/DocumentConversation.tsx+++ b/apps/web/src/lib/core/messages/DocumentConversation.tsx@@ -1,17 +1,15 @@import { ChannelInput, type InputHandle } from '@channel/Input';import { buildPostMessageSendPayload } from '@channel/Input/message-payload';-import { buildMessageLink } from '@channel/Thread/utils/message-actions';import { useMessageBotMentionUsers } from '@channel/use-channel-bot-mention-users';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { useUserId } from '@core/context/user';import { useContacts } from '@queries/contacts/contacts';import { useMessageLink } from '@queries/messages/document-messages';import { useSendMessageMutation } from '@queries/messages/mutations';-import { useChannelReferenceThreadsQuery } from '@queries/messages/references';import { useMessageTimelineQuery } from '@queries/messages/timeline';import type { MessageParent } from '@service-storage/messages';import { createMemo, createSignal, For, Show } from 'solid-js';-import { MessageThread, MessageThreadFromSource } from './MessageThread';+import { MessageThread } from './MessageThread';import type { MessageData } from './types';/** The root composer, inline below the roots or floating on touch devices. */@@ -57,7 +55,6 @@ export function DocumentConversationComposer(props: {export function DocumentConversation(props: {parent: MessageParent;canWrite: boolean;- canManage?: boolean;targetId?: string | null;buildLink?: (message: MessageData) => string;label?: string;@@ -67,7 +64,6 @@ export function DocumentConversation(props: {hideWhenEmpty?: boolean;}) {const [expanded, setExpanded] = createSignal(true);- const [includeReferences, setIncludeReferences] = createSignal(false);const target = useMessageLink(() => props.parent,() => props.targetId@@ -78,10 +74,6 @@ export function DocumentConversation(props: {target.rootId,target.resolved);- const references = useChannelReferenceThreadsQuery(- () => props.parent,- includeReferences- );// Until the link resolves, the shared latest page would flash before the window jumps.const messages = () =>target.resolved() && query.isSuccess@@ -98,25 +90,8 @@ export function DocumentConversation(props: {const messagesById = createMemo(() => new Map(messages().map((message) => [message.id, message])));- // Keyed by root so a refreshed list keeps each source thread's drafts and- // focus; a failed refetch keeps the last authorized list rather than- // unmounting the threads. Unchecking empties it even though the disabled- // query retains its last result.- const sourcesById = createMemo(- () =>- new Map(- (includeReferences() && !references.isPending- ? (references.data ?? [])- : []- ).map((item) => [item.root_id, item])- )- );return (- <Show- when={- !props.hideWhenEmpty || messages().length > 0 || sourcesById().size > 0- }- >+ <Show when={!props.hideWhenEmpty || messages().length > 0}><section class="mt-3 pb-12" data-document-conversation><buttontype="button"@@ -126,16 +101,6 @@ export function DocumentConversation(props: {{expanded() ? '▾' : '▸'} {props.label ?? 'Discussion'}</button><Show when={expanded() || props.targetId}>- <label class="mt-2 flex items-center gap-2 text-xs text-ink-muted">- <input- type="checkbox"- checked={includeReferences()}- onChange={(event) =>- setIncludeReferences(event.currentTarget.checked)- }- />- Include channel mentions- </label><StaticMarkdownContext><Show when={!target.resolved() || query.isPending}><p class="text-xs text-ink-muted">Loading comments...</p>@@ -158,7 +123,6 @@ export function DocumentConversation(props: {<MessageThreaddata={messagesById().get(id)!}canWrite={props.canWrite}- canManage={props.canManage}targetId={target.rootId() === id ? target.messageId() : null}buildLink={props.buildLink}/>@@ -172,46 +136,6 @@ export function DocumentConversation(props: {Load newer comments</button></Show>- <Show when={includeReferences()}>- <Show when={references.isPending}>- <p class="text-xs text-ink-muted">- Loading channel mentions...- </p>- </Show>- <Show when={references.isError}>- <button onClick={() => void references.refetch()}>- Could not load channel mentions. Retry- </button>- </Show>- <Show when={references.isSuccess && sourcesById().size === 0}>- <p class="text-xs text-ink-muted">- No channel threads mention this document.- </p>- </Show>- <For each={[...sourcesById().keys()]}>- {(id) => {- const item = () => sourcesById().get(id)!;- return (- <div class="mt-4" data-source-channel-thread={id}>- <a- class="text-xs text-ink-muted underline"- href={buildMessageLink(- item().parent.id,- item().root_id- )}- >- From {item().channel_name || 'Channel conversation'}- </a>- <MessageThreadFromSource- parent={item().parent}- rootId={item().root_id}- canWrite={item().can_reply}- />- </div>- );- }}- </For>- </Show><Show when={props.canWrite && !props.hideComposer}><div class="mt-4"><DocumentConversationComposer parent={props.parent} />diff --git a/apps/web/src/lib/core/messages/MessageThread.test.tsx b/apps/web/src/lib/core/messages/MessageThread.test.tsxindex a835ffe84c..2a5f13a18c 100644--- a/apps/web/src/lib/core/messages/MessageThread.test.tsx+++ b/apps/web/src/lib/core/messages/MessageThread.test.tsx@@ -2,25 +2,18 @@ import { useMessageActionDrawer } from '@channel/Mobile/message-action-drawer-coimport type { ThreadProps } from '@channel/Thread/types';import type {MessageListItem,- MessageParent,MessageThread as ThreadData,} from '@service-storage/messages';import { cleanup, fireEvent, render } from '@solidjs/testing-library';-import { type Accessor, Show } from 'solid-js';+import { Show } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';-import {- MessageThread,- MessageThreadFromSource,- threadListItem,-} from './MessageThread';+import { MessageThread, threadListItem } from './MessageThread';const mocks = vi.hoisted(() => ({edit: vi.fn(),editor: vi.fn(),remove: vi.fn(),clipboard: vi.fn().mockResolvedValue(undefined),- subscribe: vi.fn(),- byIds: vi.fn(),}));vi.mock('@app/lib/analytics/analytics-context', () => ({useAnalytics: () => ({ track: vi.fn() }),@@ -56,19 +49,12 @@ vi.mock('@queries/messages/mutations', () => ({useDeleteMessageMutation: () => ({}),useDeleteThreadMutation: () => ({}),usePatchMessageMutation: () => ({}),- usePatchThreadMutation: () => ({}),}));vi.mock('@queries/messages/reactions', () => ({useAddReactionMutation: () => ({}),useRemoveReactionMutation: () => ({}),}));-vi.mock('@queries/messages/subscription', () => ({- useMessageSubscription: mocks.subscribe,-}));vi.mock('@queries/messages/thread-replies', () => ({}));-vi.mock('@queries/messages/timeline', () => ({- useMessageTimelineByIdsQuery: mocks.byIds,-}));vi.mock('@channel/Thread/ChannelThread', () => ({ChannelThread: (props: ThreadProps) => {const drawer = useMessageActionDrawer();@@ -142,9 +128,6 @@ const message: MessageListItem = {thread: { reply_count: 0, preview: [] },};-const channel: MessageParent = { type: 'channel', id: 'launch' };-const sourceMessage: MessageListItem = { ...message, parent: channel };-function openActions(view: ReturnType<typeof render>) {fireEvent.click(view.getByRole('button', { name: 'Long press message' }));return view.getByRole('dialog', { name: 'Message actions' });@@ -184,6 +167,18 @@ describe('document message touch actions', () => {});});+describe('document discussion controls', () => {+ // A document thread carries no thread-level controls of its own: resolve was+ // dead, and deleting a discussion is moving onto the root message's delete.+ it('renders no resolve or delete-discussion control', () => {+ const view = render(() => <MessageThread data={message} canWrite />);+ expect(view.queryByRole('button', { name: 'Resolve' })).toBeNull();+ expect(+ view.queryByRole('button', { name: 'Delete discussion' })+ ).toBeNull();+ });+});+describe('threadListItem', () => {const reply = (id: string, createdAt: string) =>({@@ -216,122 +211,3 @@ describe('threadListItem', () => {expect(item.thread.latest_reply_at).toBe('2026-01-05T00:00:00Z');});});--describe('source channel threads in a document', () => {- function renderSource(canWrite: boolean) {- mocks.byIds.mockReturnValue({ isSuccess: true, data: [sourceMessage] });- return render(() => (- <MessageThreadFromSource- parent={channel}- rootId="root"- canWrite={canWrite}- canManage- />- ));- }-- it('reads, subscribes, and mutates through the source channel and keeps its links', async () => {- Object.defineProperty(navigator, 'clipboard', {- configurable: true,- value: { writeText: mocks.clipboard },- });- const view = renderSource(true);- const [subscribed] = mocks.subscribe.mock.calls[0] as [- Accessor<MessageParent>,- ];- expect(subscribed()).toEqual(channel);- const [parent, ids] = mocks.byIds.mock.calls[0] as [- Accessor<MessageParent>,- Accessor<string[]>,- ];- expect(parent()).toEqual(channel);- expect(ids()).toEqual(['root']);- expect(view.getByText('thread of channel launch')).toBeTruthy();- expect(- (- mocks.editor.mock.calls[0][0] as { parent: Accessor<MessageParent> }- ).parent()- ).toEqual(channel);-- openActions(view);- expect(view.getByRole('button', { name: 'Reply' })).toBeTruthy();- fireEvent.click(view.getByRole('button', { name: 'Edit' }));- expect(mocks.edit).toHaveBeenCalledWith(sourceMessage);- fireEvent.click(view.getByRole('button', { name: 'Delete' }));- expect(mocks.remove).toHaveBeenCalledWith({- parent: channel,- messageID: 'root',- threadID: undefined,- });- fireEvent.click(view.getByRole('button', { name: 'Copy link' }));- expect(mocks.clipboard).toHaveBeenCalledWith(- 'https://macro.test/app/channel/launch?channel_message_id=root'- );- expect(view.queryByRole('button', { name: 'Resolve' })).toBeNull();- expect(- view.queryByRole('button', { name: 'Delete discussion' })- ).toBeNull();- });-- it('renders a read-only source thread with no reply, edit, or delete controls', () => {- const view = renderSource(false);- expect(view.getByText('thread of channel launch')).toBeTruthy();- openActions(view);- expect(view.queryByRole('button', { name: 'Reply' })).toBeNull();- expect(view.queryByRole('button', { name: 'Edit' })).toBeNull();- expect(view.queryByRole('button', { name: 'Delete' })).toBeNull();- expect(view.getByRole('button', { name: 'Copy link' })).toBeTruthy();- expect(view.queryByRole('button', { name: 'Resolve' })).toBeNull();- expect(- view.queryByRole('button', { name: 'Delete discussion' })- ).toBeNull();- });-- it('shows nothing until the source root is readable and hides a root that disappears', () => {- mocks.byIds.mockReturnValue({ isSuccess: true, data: [] });- const view = render(() => (- <MessageThreadFromSource parent={channel} rootId="root" canWrite />- ));- expect(view.queryByText('thread of channel launch')).toBeNull();- });-- it('keeps rendering the cached source root while a refetch fails', () => {- mocks.byIds.mockReturnValue({- isPending: false,- isSuccess: false,- isError: true,- data: [sourceMessage],- });- const view = render(() => (- <MessageThreadFromSource parent={channel} rootId="root" canWrite />- ));- expect(view.getByText('thread of channel launch')).toBeTruthy();- });-- it('renders nothing while the source root is still loading', () => {- mocks.byIds.mockReturnValue({ isPending: true, isSuccess: false });- const view = render(() => (- <MessageThreadFromSource parent={channel} rootId="root" canWrite />- ));- expect(view.queryByText('thread of channel launch')).toBeNull();- });-- it('offers a retry when the source root request fails with nothing cached', () => {- const refetch = vi.fn();- mocks.byIds.mockReturnValue({- isPending: false,- isSuccess: false,- isError: true,- data: undefined,- refetch,- });- const view = render(() => (- <MessageThreadFromSource parent={channel} rootId="root" canWrite />- ));- expect(view.queryByText('thread of channel launch')).toBeNull();- fireEvent.click(- view.getByRole('button', { name: 'Could not load thread. Retry' })- );- expect(refetch).toHaveBeenCalled();- });-});diff --git a/apps/web/src/lib/core/messages/MessageThread.tsx b/apps/web/src/lib/core/messages/MessageThread.tsxindex 98674cf168..6b8542293a 100644--- a/apps/web/src/lib/core/messages/MessageThread.tsx+++ b/apps/web/src/lib/core/messages/MessageThread.tsx@@ -10,17 +10,13 @@ import { useUserId } from '@core/context/user';import { useHotkeyDOMScope } from '@core/hotkey/hotkeys';import {useDeleteMessageMutation,- useDeleteThreadMutation,usePatchMessageMutation,- usePatchThreadMutation,} from '@queries/messages/mutations';import {useAddReactionMutation,useRemoveReactionMutation,} from '@queries/messages/reactions';-import { useMessageSubscription } from '@queries/messages/subscription';import { useMessageThreadQuery } from '@queries/messages/thread-replies';-import { useMessageTimelineByIdsQuery } from '@queries/messages/timeline';import type {MessageListItem,MessageParent,@@ -44,7 +40,6 @@ export function threadListItem(thread: ThreadData): MessageListItem {type ThreadOptions = {canWrite: boolean;- canManage?: boolean;buildLink?: (message: MessageData) => string;targetId?: string | null;expanded?: boolean;@@ -66,8 +61,6 @@ export function MessageThread(const remove = useDeleteMessageMutation();const confirm = createDeleteMessageConfirmation(remove.mutate);const patch = usePatchMessageMutation();- const patchThread = usePatchThreadMutation();- const deleteThread = useDeleteThreadMutation();const addReaction = useAddReactionMutation();const removeReaction = useRemoveReactionMutation();const editor = createMessageEditor({@@ -104,50 +97,6 @@ export function MessageThread(class="relative isolate"><confirm.ConfirmationDialog />- <Show when={props.data.parent.type === 'document'}>- <div class="mb-5 flex items-center justify-end gap-3 text-xs text-ink-muted touch:mb-0">- <Show when={props.data.state.resolved}>- <span>Resolved</span>- </Show>- <Show when={props.canWrite}>- <button- type="button"- onClick={() =>- patchThread.mutate({- parent: props.data.parent,- rootId: props.data.id,- patch: { resolved: !props.data.state.resolved },- })- }- >- {props.data.state.resolved ? 'Reopen' : 'Resolve'}- </button>- </Show>- <Show- when={- props.canWrite &&- (props.canManage || props.data.state.user_id === userId())- }- >- <button- type="button"- onClick={() => {- if (- window.confirm(- 'Delete this discussion and all its replies?'- )- )- deleteThread.mutate({- parent: props.data.parent,- rootId: props.data.id,- });- }}- >- Delete discussion- </button>- </Show>- </div>- </Show><ChannelThreaddata={() => props.data}parent={() => props.data.parent}@@ -222,33 +171,3 @@ export function MessageThreadById(</Show>);}--/** Reference discovery selects roots; live data and lazy replies remain in the common caches. */-export function MessageThreadFromSource(- props: ThreadOptions & { parent: MessageParent; rootId: string }-) {- useMessageSubscription(() => props.parent);- const query = useMessageTimelineByIdsQuery(- () => props.parent,- () => [props.rootId]- );- // A failed refetch keeps the cached root so an open reply draft survives.- const root = () =>- query.isPending- ? undefined- : query.data?.find((item) => item.id === props.rootId);- return (- <Show- when={root()}- fallback={- <Show when={query.isError}>- <button onClick={() => void query.refetch()}>- Could not load thread. Retry- </button>- </Show>- }- >- {(data) => <MessageThread {...props} data={data()} />}- </Show>- );-}diff --git a/apps/web/src/lib/queries/messages/keys.ts b/apps/web/src/lib/queries/messages/keys.tsindex c1ad1571c4..67555ac6d1 100644--- a/apps/web/src/lib/queries/messages/keys.ts+++ b/apps/web/src/lib/queries/messages/keys.ts@@ -14,7 +14,6 @@ export const messageKeys = createQueryKeys('messages', {resolveMessage: (parent: MessageParent, messageId: string) => ({queryKey: [parent, messageId],}),- references: (parent: MessageParent) => ({ queryKey: [parent] }),});export const MessageNonceKeys = {MESSAGE: 'message',diff --git a/apps/web/src/lib/queries/messages/references.ts b/apps/web/src/lib/queries/messages/references.tsdeleted file mode 100644index ab9217852c..0000000000--- a/apps/web/src/lib/queries/messages/references.ts+++ /dev/null@@ -1,72 +0,0 @@-import { createReconnectEffect } from '@macro-inc/collaboration/websocket';-import {- createConnectionWebsocketEffect,- ws,-} from '@service-connection/websocket';-import { parseWebsocketPayload } from '@service-connection/websocket-payload';-import type { MessageEvent } from '@service-storage/generated/schemas/messageEvent';-import type { ReferencedThread } from '@service-storage/generated/schemas/referencedThread';-import {- entityMessagesClient,- type MessageCursor,- type MessageParent,-} from '@service-storage/messages';-import { useQuery } from '@tanstack/solid-query';-import type { Accessor } from 'solid-js';-import { queryClient } from '../client';-import { messageKeys } from './keys';--/**- * Channel membership changes and mentions in channels this client does not- * track reach it through no live frame, so discovery also polls while shown.- */-const REFERENCE_REFRESH_INTERVAL_MS = 30_000;--/** Source changes that can add or remove a discovered thread; typing and reactions cannot. */-const DISCOVERY_CHANGES: ReadonlySet<MessageEvent['change']['type']> = new Set([- 'posted',- 'edited',- 'message_deleted',- 'thread_updated',-]);--/** The server pages authorized identities; the Discussion shows the whole set. */-async function fetchReferencedThreads(parent: MessageParent) {- const threads: ReferencedThread[] = [];- let cursor: MessageCursor | null | undefined;- do {- const page = await entityMessagesClient.references(parent, cursor);- threads.push(...page.threads);- cursor = page.next_cursor;- } while (cursor);- return threads;-}--/** Optional, permission-filtered source threads; source messages remain channel-owned. */-export function useChannelReferenceThreadsQuery(- parent: Accessor<MessageParent>,- enabled: Accessor<boolean>-) {- const queryKey = () => messageKeys.references(parent()).queryKey;- const query = useQuery(() => ({- queryKey: queryKey(),- enabled: enabled() && parent().type === 'document',- refetchInterval: enabled() ? REFERENCE_REFRESH_INTERVAL_MS : false,- queryFn: () => fetchReferencedThreads(parent()),- }));- const invalidate = () => {- if (!enabled()) return;- void queryClient.invalidateQueries({ queryKey: queryKey() });- };- createConnectionWebsocketEffect((frame) => {- if (frame.type !== 'message_update') return;- const event = parseWebsocketPayload<MessageEvent>(frame.type, frame.data);- if (- event?.parent?.type === 'channel' &&- DISCOVERY_CHANGES.has(event.change?.type)- )- invalidate();- });- createReconnectEffect(ws, invalidate);- return query;-}diff --git a/apps/web/src/lib/queries/messages/tests/references.test.ts b/apps/web/src/lib/queries/messages/tests/references.test.tsdeleted file mode 100644index 99b5735357..0000000000--- a/apps/web/src/lib/queries/messages/tests/references.test.ts+++ /dev/null@@ -1,137 +0,0 @@-import type { ReferencedThread } from '@service-storage/generated/schemas/referencedThread';-import type { MessageParent } from '@service-storage/messages';-import { createRoot } from 'solid-js';-import { afterEach, beforeEach, expect, it, vi } from 'vitest';-import { useChannelReferenceThreadsQuery } from '../references';--const mocks = vi.hoisted(() => ({- references: vi.fn(),- invalidate: vi.fn().mockResolvedValue(undefined),- updates: new Set<(frame: unknown) => void>(),- reconnects: new Set<() => void>(),-}));-vi.mock('@service-connection/websocket', async () => {- const { onCleanup } = await import('solid-js');- return {- ws: {},- createConnectionWebsocketEffect: (callback: (frame: unknown) => void) => {- mocks.updates.add(callback);- onCleanup(() => mocks.updates.delete(callback));- },- };-});-vi.mock('@macro-inc/collaboration/websocket', async () => {- const { onCleanup } = await import('solid-js');- return {- createReconnectEffect: (_ws: unknown, callback: () => void) => {- mocks.reconnects.add(callback);- onCleanup(() => mocks.reconnects.delete(callback));- },- };-});-vi.mock('@service-storage/messages', () => ({- entityMessagesClient: { references: mocks.references },-}));-vi.mock('@tanstack/solid-query', () => ({- useQuery: (options: () => unknown) => options(),-}));-vi.mock('../../client', () => ({- queryClient: { invalidateQueries: mocks.invalidate },-}));--type QueryOptions = {- queryKey: unknown[];- enabled: boolean;- refetchInterval: number | false;- queryFn: () => Promise<ReferencedThread[]>;-};--const document: MessageParent = { type: 'document', id: 'doc' };-const disposers: (() => void)[] = [];-function mount(enabled: boolean) {- return createRoot((dispose) => {- disposers.push(dispose);- return useChannelReferenceThreadsQuery(- () => document,- () => enabled- ) as unknown as QueryOptions;- });-}-function emit(frame: unknown) {- for (const listener of mocks.updates) listener(frame);-}-function messageUpdate(change: string, parentType = 'channel') {- return {- type: 'message_update',- data: JSON.stringify({- parent: { type: parentType, id: 'source' },- change: { type: change },- }),- };-}-function source(root: string, channel = 'launch'): ReferencedThread {- return {- parent: { type: 'channel', id: channel },- root_id: root,- channel_name: 'Launch',- can_reply: true,- };-}--beforeEach(() => vi.clearAllMocks());-afterEach(() => {- for (const dispose of disposers.splice(0)) dispose();-});--it('reads every page of authorized source identities under the document key', async () => {- const cursor = { created_at: '2026-09-09T00:00:00Z', id: 'root-a' };- mocks.references- .mockResolvedValueOnce({ threads: [source('root-a')], next_cursor: cursor })- .mockResolvedValueOnce({ threads: [source('root-b')], next_cursor: null });- const options = mount(true);- expect(options.queryKey).toEqual(['messages', 'references', document]);- expect(options.enabled).toBe(true);- expect(options.refetchInterval).toBe(30_000);- await expect(options.queryFn()).resolves.toEqual([- source('root-a'),- source('root-b'),- ]);- expect(mocks.references.mock.calls).toEqual([- [document, undefined],- [document, cursor],- ]);-});--it('refreshes discovery only for source changes that can add or remove a thread', () => {- vi.spyOn(console, 'warn').mockImplementation(() => {});- mount(true);- emit(messageUpdate('typing'));- emit(messageUpdate('reaction_changed'));- emit(messageUpdate('posted', 'document'));- emit({ type: 'contacts_invalidation' });- emit({ type: 'message_update', data: '{not json' });- expect(mocks.invalidate).not.toHaveBeenCalled();- for (const change of [- 'posted',- 'edited',- 'message_deleted',- 'thread_updated',- ])- emit(messageUpdate(change));- expect(mocks.invalidate).toHaveBeenCalledTimes(4);- for (const reconnect of mocks.reconnects) reconnect();- expect(mocks.invalidate).toHaveBeenCalledTimes(5);- expect(mocks.invalidate).toHaveBeenLastCalledWith({- queryKey: ['messages', 'references', document],- });-});--it('stays idle while channel mentions are hidden', () => {- const options = mount(false);- expect(options.enabled).toBe(false);- expect(options.refetchInterval).toBe(false);- emit(messageUpdate('posted'));- for (const reconnect of mocks.reconnects) reconnect();- expect(mocks.invalidate).not.toHaveBeenCalled();- expect(mocks.references).not.toHaveBeenCalled();-});diff --git a/apps/web/src/lib/service-clients/service-storage/messages.ts b/apps/web/src/lib/service-clients/service-storage/messages.tsindex b65597f2c6..b23f5904db 100644--- a/apps/web/src/lib/service-clients/service-storage/messages.ts+++ b/apps/web/src/lib/service-clients/service-storage/messages.ts@@ -5,7 +5,6 @@ import type { MessageCursor } from './generated/schemas/messageCursor';import type { MessageParent } from './generated/schemas/messageParent';import type { MessageThread } from './generated/schemas/messageThread';import type { PostMessage } from './generated/schemas/postMessage';-import type { ReferencedThreadPage } from './generated/schemas/referencedThreadPage';import type { ThreadPatch } from './generated/schemas/threadPatch';import type { ThreadState } from './generated/schemas/threadState';@@ -52,14 +51,6 @@ export const entityMessagesClient = {`${path(parent)}?${new URLSearchParams({ selection: JSON.stringify(selection) })}`);},- references(parent: MessageParent, cursor?: MessageCursor | null) {- const query = new URLSearchParams({ limit: '100' });- if (cursor) {- query.set('created_at', cursor.created_at);- query.set('cursor_id', cursor.id);- }- return request<ReferencedThreadPage>(`${path(parent)}/references?${query}`);- },get(parent: MessageParent, id: string) {return request<Message>(`${path(parent)}/items/${encodeURIComponent(id)}`);},diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex f4408ff1ae..d689b11e87 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -456,20 +456,6 @@ preview replies per thread. Expand a thread to load its replies;`Load earlier comments` pages backward. Live updates preserve unsent repliesand edits while updating the surrounding thread.-The `Include channel mentions` checkbox under the `Discussion` header is off by-default. Checking it adds channel threads whose messages mention this document,-each under a `From <channel name>` link to the source channel, after the-document's own comments. These threads stay channel-owned: replies, edits, and-reactions post to the channel, `Copy link` yields the channel link, and-`Resolve` / `Delete discussion` do not appear on them. Only channels the viewer-can read are listed, and a thread from a channel the viewer cannot post in has-no reply, edit, or delete controls. The list refreshes on live channel message-changes, on reconnect, and every 30 seconds while the checkbox is on, so a new-mention in another channel or a lost channel membership shows up or disappears-within that interval. A reply draft in a listed thread survives those-refreshes. Unchecking hides the channel threads again without touching the-document's comments.-Select text and choose the comment action to create an anchored comment. Thesethreads appear beside their text in the margin (or in the active thread draweron phones) and never in the bottom Discussion, including after live updates or@@ -481,9 +467,8 @@ conversation anchored to the remaining text. On phones, the active Markdownthread opens in a drawer with a pinned reply composer; long-press any messagefor edit, delete, copy-link, and reaction actions.-`Resolve` / `Reopen` changes the discussion state. Deleting the root message-leaves a tombstone and retains its replies. `Delete discussion` explicitly-removes the whole thread and requests confirmation. `Copy link` targets the+A document thread carries no thread-level controls above it. Deleting the root+message leaves a tombstone and retains its replies. `Copy link` targets thespecific comment with `comment_id=<message id>`. Previously copied numeric linksstill resolve under current document permissions. Deleting an anchored Markdowndiscussion removes its mark while preserving the document text and any