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(messages): show channel threads that mention a document in its Discussion (#6445)
gbirman03497d44625b
diff --git a/apps/web/src/lib/core/messages/DocumentConversation.test.tsx b/apps/web/src/lib/core/messages/DocumentConversation.test.tsxindex 5450d5b4c6..e07c40e960 100644--- a/apps/web/src/lib/core/messages/DocumentConversation.test.tsx+++ b/apps/web/src/lib/core/messages/DocumentConversation.test.tsx@@ -1,5 +1,6 @@+import type { ReferencedThread } from '@service-storage/generated/schemas/referencedThread';import type { MessageListItem } from '@service-storage/messages';-import { cleanup, render } from '@solidjs/testing-library';+import { cleanup, fireEvent, 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';@@ -9,6 +10,8 @@ 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', () => ({@@ -18,6 +21,10 @@ vi.mock('@channel/Input', () => ({},}));vi.mock('@channel/Input/message-payload', () => ({}));+vi.mock('@channel/Thread/utils/message-actions', () => ({+ buildMessageLink: (channelId: string, messageId: string) =>+ `/channel/${channelId}/${messageId}`,+}));vi.mock('@channel/use-channel-bot-mention-users', () => ({useMessageBotMentionUsers: () => [],}));@@ -44,6 +51,9 @@ 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,}));@@ -56,6 +66,18 @@ 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(() => {@@ -92,6 +114,21 @@ 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,@@ -102,14 +139,32 @@ 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' }}@@ -228,4 +283,96 @@ 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 76e7022d06..370bc20fa6 100644--- a/apps/web/src/lib/core/messages/DocumentConversation.tsx+++ b/apps/web/src/lib/core/messages/DocumentConversation.tsx@@ -1,15 +1,17 @@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 } from './MessageThread';+import { MessageThread, MessageThreadFromSource } from './MessageThread';import type { MessageData } from './types';/** The root composer, inline below the roots or floating on touch devices. */@@ -65,6 +67,7 @@ export function DocumentConversation(props: {hideWhenEmpty?: boolean;}) {const [expanded, setExpanded] = createSignal(true);+ const [includeReferences, setIncludeReferences] = createSignal(false);const target = useMessageLink(() => props.parent,() => props.targetId@@ -75,6 +78,10 @@ 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@@ -91,8 +98,25 @@ 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}>+ <Show+ when={+ !props.hideWhenEmpty || messages().length > 0 || sourcesById().size > 0+ }+ ><section class="mt-3 pb-12" data-document-conversation><buttontype="button"@@ -102,6 +126,16 @@ 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>@@ -138,6 +172,46 @@ 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 011f930faf..a835ffe84c 100644--- a/apps/web/src/lib/core/messages/MessageThread.test.tsx+++ b/apps/web/src/lib/core/messages/MessageThread.test.tsx@@ -2,17 +2,25 @@ 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 { Show } from 'solid-js';+import { type Accessor, Show } from 'solid-js';import { afterEach, describe, expect, it, vi } from 'vitest';-import { MessageThread, threadListItem } from './MessageThread';+import {+ MessageThread,+ MessageThreadFromSource,+ 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() }),@@ -26,7 +34,10 @@ vi.mock('@core/hotkey/hotkeys', () => ({useHotkeyDOMScope: () => [() => {}, 'scope'],}));vi.mock('@channel/Channel/create-message-editor', () => ({- createMessageEditor: () => ({ start: mocks.edit }),+ createMessageEditor: (options: unknown) => {+ mocks.editor(options);+ return { start: mocks.edit };+ },}));vi.mock('@channel/Channel/create-delete-message-confirmation', () => ({createDeleteMessageConfirmation: () => ({@@ -34,6 +45,13 @@ vi.mock('@channel/Channel/create-delete-message-confirmation', () => ({ConfirmationDialog: () => null,}),}));+vi.mock('@channel/Thread/utils/message-actions', async (importOriginal) => ({+ ...(await importOriginal<+ typeof import('@channel/Thread/utils/message-actions')+ >()),+ buildMessageLink: (channelId: string, messageId: string) =>+ `https://macro.test/app/channel/${channelId}?channel_message_id=${messageId}`,+}));vi.mock('@queries/messages/mutations', () => ({useDeleteMessageMutation: () => ({}),useDeleteThreadMutation: () => ({}),@@ -44,50 +62,54 @@ vi.mock('@queries/messages/reactions', () => ({useAddReactionMutation: () => ({}),useRemoveReactionMutation: () => ({}),}));-vi.mock('@queries/messages/subscription', () => ({}));+vi.mock('@queries/messages/subscription', () => ({+ useMessageSubscription: mocks.subscribe,+}));vi.mock('@queries/messages/thread-replies', () => ({}));-vi.mock('@queries/messages/timeline', () => ({}));+vi.mock('@queries/messages/timeline', () => ({+ useMessageTimelineByIdsQuery: mocks.byIds,+}));vi.mock('@channel/Thread/ChannelThread', () => ({ChannelThread: (props: ThreadProps) => {const drawer = useMessageActionDrawer();return (- <button- onClick={() =>- drawer?.open(props.data(), props.getMessageActions?.(props.data()))- }- >- Long press message- </button>+ <>+ <p>+ thread of {props.parent().type} {props.parent().id}+ </p>+ <button+ onClick={() =>+ drawer?.open(props.data(), props.getMessageActions?.(props.data()))+ }+ >+ Long press message+ </button>+ </>);},}));vi.mock('@channel/Mobile/ActionDrawer', () => ({ActionDrawer: () => {const drawer = useMessageActionDrawer();+ const action = (name: 'onReply' | 'onEdit' | 'onDelete' | 'onCopyLink') =>+ drawer?.actions()?.[name];+ const button = (+ label: string,+ name: 'onReply' | 'onEdit' | 'onDelete' | 'onCopyLink'+ ) => (+ <Show when={action(name)}>+ <button onClick={() => action(name)?.({ message: drawer!.message()! })}>+ {label}+ </button>+ </Show>+ );return (<Show when={drawer?.isOpen()}><div role="dialog" aria-label="Message actions">- <button- onClick={() =>- drawer?.actions()?.onEdit?.({ message: drawer.message()! })- }- >- Edit- </button>- <button- onClick={() =>- drawer?.actions()?.onDelete?.({ message: drawer.message()! })- }- >- Delete- </button>- <button- onClick={() =>- drawer?.actions()?.onCopyLink?.({ message: drawer.message()! })- }- >- Copy link- </button>+ {button('Reply', 'onReply')}+ {button('Edit', 'onEdit')}+ {button('Delete', 'onDelete')}+ {button('Copy link', 'onCopyLink')}</div></Show>);@@ -120,6 +142,14 @@ 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' });+}+describe('document message touch actions', () => {it('provides edit, delete, and copy-link actions outside a channel', async () => {Object.defineProperty(navigator, 'clipboard', {@@ -137,8 +167,7 @@ describe('document message touch actions', () => {}/>));- fireEvent.click(view.getByRole('button', { name: 'Long press message' }));- expect(view.getByRole('dialog', { name: 'Message actions' })).toBeTruthy();+ openActions(view);fireEvent.click(view.getByRole('button', { name: 'Edit' }));expect(mocks.edit).toHaveBeenCalledWith(message);expect(editing).toHaveBeenCalledWith('root', true);@@ -187,3 +216,122 @@ 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 1026759c78..98674cf168 100644--- a/apps/web/src/lib/core/messages/MessageThread.tsx+++ b/apps/web/src/lib/core/messages/MessageThread.tsx@@ -18,7 +18,9 @@ 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,@@ -220,3 +222,33 @@ 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 67555ac6d1..c1ad1571c4 100644--- a/apps/web/src/lib/queries/messages/keys.ts+++ b/apps/web/src/lib/queries/messages/keys.ts@@ -14,6 +14,7 @@ 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.tsnew file mode 100644index 0000000000..ab9217852c--- /dev/null+++ b/apps/web/src/lib/queries/messages/references.ts@@ -0,0 +1,72 @@+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.tsnew file mode 100644index 0000000000..99b5735357--- /dev/null+++ b/apps/web/src/lib/queries/messages/tests/references.test.ts@@ -0,0 +1,137 @@+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/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex 057e833167..8f7f2a98b0 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -450,6 +450,20 @@ 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