Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(comments): resolve and reopen document discussions with a folded resolved state (#6864)

gbirmancb38155d0365
diff --git a/apps/web/src/features/block-md/comments/CommentMargin.tsx b/apps/web/src/features/block-md/comments/CommentMargin.tsx
index 2e4bae51d3..f9b275b1f6 100644
--- a/apps/web/src/features/block-md/comments/CommentMargin.tsx
+++ b/apps/web/src/features/block-md/comments/CommentMargin.tsx
@@ -1,6 +1,7 @@
import {
type CommentId,
isDraftThreadId,
+ type Root,
type ThreadId,
} from '@core/comments/commentType';
import { MinimizedThread } from '@core/comments/MinimizedThreads';
@@ -130,6 +131,12 @@ export const CommentMargin = (props: { wideEnough: boolean }) => {
}
);
+ // A caret inside resolved text does not unfold its thread; only opening it
+ // from the margin or a link does.
+ const isThreadActive = (thread: Root) =>
+ isActiveSelector(thread.threadId) &&
+ (!thread.resolved || commentState.activeCommentThread === thread.threadId);
+
const commentsContext = useCommentsContext(setThreadHeights);
// Touch devices never expand floating thread cards; the active thread is
@@ -154,7 +161,7 @@ export const CommentMargin = (props: { wideEnough: boolean }) => {
<MinimizedThread
comment={thread()}
layout={layout()}
- isActive={isActiveSelector(thread().threadId)}
+ isActive={isThreadActive(thread())}
maxHeight={maxHeight()}
expandable={!isTouchDevice()}
/>
@@ -163,7 +170,7 @@ export const CommentMargin = (props: { wideEnough: boolean }) => {
<Thread
comment={thread()}
layout={layout()}
- isActive={isActiveSelector(thread().threadId)}
+ isActive={isThreadActive(thread())}
maxHeight={maxHeight()}
/>
</Show>
diff --git a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
index 802a3f647e..a33c9c8469 100644
--- a/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
+++ b/apps/web/src/features/block-md/comments/MessageCommentsProvider.tsx
@@ -183,8 +183,28 @@ export const MessageCommentsProvider: VoidComponent<{
);
});
element.toggleAttribute('data-comment-inactive', inactive);
+ // Resolved discussions keep their range but drop the highlight; an
+ // overlapping open or unloaded discussion keeps it.
+ const resolved = node.getIDs().every((id) => {
+ const live = threads.filter(
+ (thread) =>
+ thread.state.anchor?.type === 'markdown' &&
+ thread.state.anchor.mark_id === id &&
+ !thread.state.deleted_at
+ );
+ return live.length > 0 && live.every((thread) => thread.state.resolved);
+ });
+ element.toggleAttribute('data-comment-resolved', resolved);
};
+ const refreshMarkPresentation = (markId: string) =>
+ editor.getEditorState().read(() => {
+ for (const [key, element] of Object.entries(mountedMarks[markId] ?? {})) {
+ const node = $getNodeByKey<CommentNode>(key);
+ if (node && element) updateMarkPresentation(node, element);
+ }
+ });
+
const removeThreadPlacement = (state: MessageThread['state']) => {
if (!state.deleted_at && state.anchor !== null) return;
const markIds =
@@ -460,6 +480,7 @@ export const MessageCommentsProvider: VoidComponent<{
element?.classList.remove('draft');
element?.removeAttribute('data-comment-inactive');
}
+ untrack(() => refreshMarkPresentation(anchor.id));
setMarks(anchor.id, anchor);
}
diff --git a/apps/web/src/lib/core/comments/MinimizedThreads.tsx b/apps/web/src/lib/core/comments/MinimizedThreads.tsx
index f2a80109cc..7bed7db8d7 100644
--- a/apps/web/src/lib/core/comments/MinimizedThreads.tsx
+++ b/apps/web/src/lib/core/comments/MinimizedThreads.tsx
@@ -1,8 +1,9 @@
import { Popover } from '@kobalte/core/popover';
import ChatTeardrop from '@phosphor/chat-teardrop.svg';
+import CheckCircle from '@phosphor/check-circle.svg';
import { cn, Layer } from '@ui';
import type { EditorThemeClasses } from 'lexical';
-import { createEffect, createSignal, useContext } from 'solid-js';
+import { createEffect, createSignal, on, Show, useContext } from 'solid-js';
import type { Layout, Root } from './commentType';
import { MeasureContainer } from './MeasureContainer';
import { CommentsContext, ThreadCard } from './Thread';
@@ -30,6 +31,16 @@ export function MinimizedThread(props: {
}
const { highlightedCommentId, setActiveThread } = useContext(CommentsContext);
+ // Resolving from the expanded card folds the thread back to its badge.
+ createEffect(
+ on(
+ () => props.comment.resolved,
+ (resolved) => {
+ if (resolved) setExpanded(false);
+ },
+ { defer: true }
+ )
+ );
createEffect(() => {
if (!expandable()) return;
const hId = highlightedCommentId();
@@ -87,7 +98,17 @@ export function MinimizedThread(props: {
'bg-comment/10 group-hover:bg-comment/20': props.isActive,
})}
>
- <ChatTeardrop class="size-4" onClick={clickHandler} />
+ <Show
+ when={props.comment.resolved}
+ fallback={
+ <ChatTeardrop class="size-4" onClick={clickHandler} />
+ }
+ >
+ <CheckCircle
+ class="size-4 text-success"
+ onClick={clickHandler}
+ />
+ </Show>
<div class="flex items-center px-1 h-6">
<span class="text-xs text-center">{commentCount()}</span>
</div>
diff --git a/apps/web/src/lib/core/comments/Thread.test.tsx b/apps/web/src/lib/core/comments/Thread.test.tsx
index dc3df7dfe9..ef0866a503 100644
--- a/apps/web/src/lib/core/comments/Thread.test.tsx
+++ b/apps/web/src/lib/core/comments/Thread.test.tsx
@@ -21,7 +21,12 @@ import {
const mocks = vi.hoisted(() => ({
unifiedDiscussions: true,
confirmed: vi.fn(),
+ patchThread: vi.fn(),
}));
+vi.mock('@queries/messages/mutations', () => ({
+ usePatchThreadMutation: () => ({ mutate: mocks.patchThread }),
+}));
+vi.mock('@core/component/UserIcon', () => ({ UserIcon: () => null }));
vi.mock('@core/util/url', () => ({
buildSimpleEntityUrl: (
entity: { type: string; id: string },
@@ -80,6 +85,9 @@ vi.mock(
})
);
vi.mock('@ui', () => ({
+ Button: (props: ParentProps<{ onClick?: (e: MouseEvent) => void }>) => (
+ <button onClick={(e) => props.onClick?.(e)}>{props.children}</button>
+ ),
Layer: (props: ParentProps) => props.children,
cn: (...values: string[]) => values.join(' '),
}));
@@ -90,6 +98,7 @@ vi.mock('./MeasureContainer', () => ({
const writeText = vi.fn();
beforeEach(() => {
mocks.unifiedDiscussions = true;
+ mocks.patchThread.mockReset();
writeText.mockReset();
vi.stubGlobal('navigator', { clipboard: { writeText } });
});
@@ -213,6 +222,39 @@ describe('anchored comment links', () => {
expect(card(view).hasAttribute('data-expanded')).toBe(true);
});
+ it('folds an expanded minimized comment back to its badge once resolved', async () => {
+ const [resolved, setResolved] = createSignal(false);
+ const view = render(() => (
+ <CommentsContext.Provider
+ value={{
+ documentId: 'document',
+ documentType: 'md',
+ canComment: () => true,
+ isDocumentOwner: () => true,
+ highlightedCommentId: () => null,
+ setActiveThread: () => {},
+ setThreadHeight: () => {},
+ getCommentById: () => undefined,
+ ownedComment: () => false,
+ inComment: true,
+ commentOperations: noopCommentOperations,
+ }}
+ >
+ <MinimizedThread
+ comment={{ ...comment, resolved: resolved() }}
+ layout={{ calculatedYPos: 0 }}
+ isActive={false}
+ />
+ </CommentsContext.Provider>
+ ));
+ fireEvent.click(view.getByText('1'));
+ expect(card(view).hasAttribute('data-expanded')).toBe(true);
+ setResolved(true);
+ await waitFor(() =>
+ expect(card(view).hasAttribute('data-expanded')).toBe(false)
+ );
+ });
+
it('dismisses an expanded minimized comment on a press outside it', async () => {
const view = renderThreadBody('md', true);
fireEvent.click(view.getByText('1'));
@@ -247,3 +289,82 @@ describe('anchored comment links', () => {
}
);
});
+
+describe('resolved discussions', () => {
+ const renderThread = (props: { resolved: boolean; isActive: boolean }) => {
+ const setActiveThread = vi.fn();
+ const view = render(() => (
+ <CommentsContext.Provider
+ value={{
+ documentId: 'document',
+ documentType: 'md',
+ canComment: () => true,
+ isDocumentOwner: () => true,
+ highlightedCommentId: () => null,
+ setActiveThread,
+ setThreadHeight: () => {},
+ getCommentById: () => undefined,
+ ownedComment: () => false,
+ inComment: true,
+ commentOperations: noopCommentOperations,
+ messageOperations: { createComment: async () => null },
+ }}
+ >
+ <ThreadBody
+ comment={{
+ ...comment,
+ text: 'Fix the\n\nintro',
+ replyCount: 2,
+ resolved: props.resolved,
+ }}
+ isActive={props.isActive}
+ />
+ </CommentsContext.Provider>
+ ));
+ return { view, setActiveThread };
+ };
+
+ it('folds an inactive resolved thread to a one-line summary that opens it', () => {
+ const { view, setActiveThread } = renderThread({
+ resolved: true,
+ isActive: false,
+ });
+ expect(view.queryByRole('link')).toBeNull();
+ expect(view.getByText('Fix the intro')).toBeTruthy();
+ expect(view.getByText('2 replies')).toBeTruthy();
+ fireEvent.click(
+ view.getByRole('button', { name: 'Show resolved comment' })
+ );
+ expect(setActiveThread).toHaveBeenCalledWith('comment-root');
+ });
+
+ it('reopens an active resolved thread', () => {
+ const { view } = renderThread({ resolved: true, isActive: true });
+ expect(view.getByRole('link')).toBeTruthy();
+ fireEvent.click(view.getByRole('button', { name: 'Reopen' }));
+ expect(mocks.patchThread).toHaveBeenCalledWith({
+ parent: { type: 'document', id: 'document' },
+ rootId: 'comment-root',
+ patch: { resolved: false },
+ });
+ });
+
+ it('resolves an active open thread and releases focus so it folds', () => {
+ const { view, setActiveThread } = renderThread({
+ resolved: false,
+ isActive: true,
+ });
+ fireEvent.click(view.getByRole('button', { name: 'Resolve' }));
+ expect(mocks.patchThread).toHaveBeenCalledWith({
+ parent: { type: 'document', id: 'document' },
+ rootId: 'comment-root',
+ patch: { resolved: true },
+ });
+ expect(setActiveThread).toHaveBeenCalledWith(null);
+ });
+
+ it('offers no resolve action on an inactive open thread', () => {
+ const { view } = renderThread({ resolved: false, isActive: false });
+ expect(view.queryByRole('button', { name: 'Resolve' })).toBeNull();
+ });
+});
diff --git a/apps/web/src/lib/core/comments/Thread.tsx b/apps/web/src/lib/core/comments/Thread.tsx
index 2921e1f758..4d55cfc815 100644
--- a/apps/web/src/lib/core/comments/Thread.tsx
+++ b/apps/web/src/lib/core/comments/Thread.tsx
@@ -4,13 +4,19 @@ import { buildPostMessageSendPayload } from '@channel/Input/message-payload';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
import { createTheme } from '@core/component/LexicalMarkdown/theme';
import type { UserMentionRecord } from '@core/component/LexicalMarkdown/utils/mentionsUtils';
+import { UserIcon } from '@core/component/UserIcon';
import {
enableUnifiedDocumentDiscussions,
isFeatureEnabled,
} from '@core/constant/featureFlags';
import { MessageThreadById } from '@core/messages/MessageThread';
import { buildSimpleEntityUrl } from '@core/util/url';
-import { Layer } from '@ui';
+import { markdownToPlainText } from '@macro-inc/lexical-core';
+import ArrowCounterClockwise from '@phosphor/arrow-counter-clockwise.svg';
+import Check from '@phosphor/check.svg';
+import CheckCircle from '@phosphor/check-circle.svg';
+import { usePatchThreadMutation } from '@queries/messages/mutations';
+import { Button, Layer } from '@ui';
import type { EditorThemeClasses } from 'lexical';
import {
type Accessor,
@@ -167,6 +173,18 @@ function MessageThreadBody(props: ThreadBodyProps) {
const highlighted = context.highlightedCommentId();
return typeof highlighted === 'string' ? highlighted : null;
};
+ const patchThread = usePatchThreadMutation();
+ const resolved = () => !!props.comment.resolved;
+ const setResolved = (value: boolean) =>
+ patchThread.mutate({
+ parent: parent(),
+ rootId: String(props.comment.threadId),
+ patch: { resolved: value },
+ });
+ // A resolved thread folds to one line unless it is the active thread (a
+ // comment link activates its thread, so linked threads open too).
+ const collapsed = () => resolved() && !props.isActive;
+
return (
<StaticMarkdownContext theme={props.theme ?? baseCommentTheme}>
<Show
@@ -191,25 +209,102 @@ function MessageThreadBody(props: ThreadBodyProps) {
/>
}
>
- <MessageThreadById
- parent={parent()}
- rootId={String(props.comment.threadId)}
- canWrite={context.canComment()}
- hideReplyInput={props.hideReplyInput}
- onEditingChange={context.setMessageEditing}
- targetId={targetId()}
- buildLink={(message) =>
- buildSimpleEntityUrl(
- { type: context.documentType, id: context.documentId },
- { [MD_URL_PARAMS.commentId]: message.id }
- )
+ <Show
+ when={!collapsed()}
+ fallback={
+ <ResolvedThreadSummary
+ comment={props.comment}
+ onOpen={() => context.setActiveThread(props.comment.threadId)}
+ />
}
- />
+ >
+ <MessageThreadById
+ parent={parent()}
+ rootId={String(props.comment.threadId)}
+ canWrite={context.canComment()}
+ hideReplyInput={props.hideReplyInput}
+ onEditingChange={context.setMessageEditing}
+ targetId={targetId()}
+ buildLink={(message) =>
+ buildSimpleEntityUrl(
+ { type: context.documentType, id: context.documentId },
+ { [MD_URL_PARAMS.commentId]: message.id }
+ )
+ }
+ />
+ <Show when={resolved()}>
+ <div class="mt-1 flex items-center gap-1.5 text-xs text-success">
+ <CheckCircle class="size-3.5 shrink-0" />
+ <span class="flex-1">Resolved</span>
+ <Show when={context.canComment()}>
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={() => setResolved(false)}
+ >
+ <ArrowCounterClockwise />
+ Reopen
+ </Button>
+ </Show>
+ </div>
+ </Show>
+ <Show when={!resolved() && props.isActive && context.canComment()}>
+ <div class="mt-1 flex justify-end">
+ <Button
+ size="xs"
+ variant="ghost"
+ onClick={(e: MouseEvent) => {
+ // The card's container re-activates the thread on click.
+ e.stopPropagation();
+ setResolved(true);
+ context.setActiveThread(null);
+ }}
+ >
+ <Check />
+ Resolve
+ </Button>
+ </div>
+ </Show>
+ </Show>
</Show>
</StaticMarkdownContext>
);
}
+/** The one-line stand-in for a resolved thread: who started it and how it began. */
+function ResolvedThreadSummary(props: { comment: Root; onOpen: () => void }) {
+ const preview = createMemo(() =>
+ markdownToPlainText(props.comment.text).trim().replace(/\s+/g, ' ')
+ );
+ const replyCount = () =>
+ props.comment.replyCount ?? props.comment.children.length;
+ return (
+ <button
+ type="button"
+ class="flex w-full min-w-0 items-center gap-2 rounded-lg px-1 py-0.5 text-left text-xs text-ink-extra-muted hover:bg-hover"
+ aria-label="Show resolved comment"
+ onClick={(e) => {
+ e.stopPropagation();
+ props.onOpen();
+ }}
+ >
+ <CheckCircle class="size-4 shrink-0 text-success" />
+ <UserIcon
+ id={props.comment.owner}
+ size="sm"
+ suppressClick
+ isDeleted={false}
+ />
+ <span class="min-w-0 flex-1 truncate">{preview()}</span>
+ <Show when={replyCount() > 0}>
+ <span class="shrink-0 tabular-nums">
+ {`${replyCount()} ${replyCount() > 1 ? 'replies' : 'reply'}`}
+ </span>
+ </Show>
+ </button>
+ );
+}
+
function LegacyThreadBody(props: ThreadBodyProps) {
const {
canComment,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
index 81ba7baa75..58d7c7ef34 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
@@ -615,6 +615,17 @@ mark {
padding-bottom: 0;
}
+.md-mark.comment[data-comment-resolved] {
+ background: unset;
+ border-bottom: none;
+ padding-bottom: 0;
+}
+
+.md-mark.selected.comment[data-comment-resolved] {
+ border-bottom: 2px dotted oklch(from var(--color-yellow) l c h / 0.5);
+ padding-bottom: 2px;
+}
+
.md-no-comments {
.md-mark.comment {
background: unset !important;
diff --git a/apps/web/src/lib/queries/messages/mutations.ts b/apps/web/src/lib/queries/messages/mutations.ts
index c01d55bae3..4b4ddbb240 100644
--- a/apps/web/src/lib/queries/messages/mutations.ts
+++ b/apps/web/src/lib/queries/messages/mutations.ts
@@ -705,9 +705,22 @@ export function usePatchThreadMutation() {
applyThreadState(input.parent, state);
return state;
},
- onError: () => toast.failure('Could not update discussion'),
+ // Resolving collapses the card at once; a failure restores the prior state.
+ onMutate: (input) => {
+ const { resolved } = input.patch;
+ if (resolved == null) return;
+ const previous = getCachedThreadState(input.parent, input.rootId);
+ if (!previous || previous.resolved === resolved) return;
+ applyThreadState(input.parent, { ...previous, resolved });
+ return { previous };
+ },
+ onError: (_error, input, context) => {
+ if (context?.previous) applyThreadState(input.parent, context.previous);
+ toast.failure('Could not update discussion');
+ },
}));
}
+
export function useDeleteThreadMutation() {
return useMutation(() => ({
mutationFn: async (input: { parent: MessageParent; rootId: string }) => {
diff --git a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx b/apps/web/src/lib/queries/messages/tests/mutations.test.tsx
index 70f0dd0989..3360f7b20d 100644
--- a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx
+++ b/apps/web/src/lib/queries/messages/tests/mutations.test.tsx
@@ -9,7 +9,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
let testQueryClient: QueryClient;
-const mocks = vi.hoisted(() => ({ delete: vi.fn() }));
+const mocks = vi.hoisted(() => ({ delete: vi.fn(), patchThread: vi.fn() }));
vi.mock('../../client', () => ({
get queryClient() {
return testQueryClient;
@@ -22,7 +22,7 @@ vi.mock('@service-storage/messages', () => ({ entityMessagesClient: mocks }));
vi.mock('../subscription', () => ({ useMessageSubscription: () => {} }));
import { messageKeys } from '../keys';
-import { useDeleteMessageMutation } from '../mutations';
+import { useDeleteMessageMutation, usePatchThreadMutation } from '../mutations';
import { handleMessageEvent, onThreadStateUpdated } from '../sync';
import { getThreadRepliesQueryKey } from '../thread-replies';
import {
@@ -52,6 +52,7 @@ function message(
beforeEach(() => {
mocks.delete.mockReset();
+ mocks.patchThread.mockReset();
testQueryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
@@ -282,3 +283,87 @@ describe('root deletion', () => {
expect(thread.replies).toHaveLength(1);
});
});
+
+describe('thread resolution', () => {
+ const parent: MessageParent = { type: 'document', id: 'doc' };
+ const state = {
+ root_id: 'root',
+ user_id: 'macro|[email protected]',
+ resolved: false,
+ created_at: time,
+ updated_at: time,
+ anchor: { type: 'markdown' as const, mark_id: 'mark' },
+ };
+ const timelineKey = getMessageTimelineQueryKey(parent);
+ const threadKey = getThreadRepliesQueryKey(parent, 'root');
+ const cachedResolved = () => ({
+ timeline:
+ testQueryClient.getQueryData<MessageTimelineData>(timelineKey)!.pages[0]
+ .items[0].state.resolved,
+ thread:
+ testQueryClient.getQueryData<MessageThread>(threadKey)!.state.resolved,
+ });
+
+ function setup() {
+ const root: MessageListItem = {
+ ...message(parent, 'root'),
+ state,
+ thread: { reply_count: 0, preview: [], latest_reply_at: null },
+ };
+ testQueryClient.setQueryData<MessageTimelineData>(timelineKey, {
+ pageParams: [null],
+ pages: [{ items: [root], next_cursor: null, previous_cursor: null }],
+ });
+ testQueryClient.setQueryData<MessageThread>(threadKey, {
+ state,
+ root,
+ replies: [],
+ });
+ let mutation!: ReturnType<typeof usePatchThreadMutation>;
+ function Harness() {
+ mutation = usePatchThreadMutation();
+ return null;
+ }
+ render(() => (
+ <QueryClientProvider client={testQueryClient}>
+ <Harness />
+ </QueryClientProvider>
+ ));
+ return mutation;
+ }
+
+ it('shows the resolution before the server confirms it', async () => {
+ let confirm!: () => void;
+ mocks.patchThread.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ confirm = () => resolve({ ...state, resolved: true });
+ })
+ );
+ const mutation = setup();
+ const pending = mutation.mutateAsync({
+ parent,
+ rootId: 'root',
+ patch: { resolved: true },
+ });
+ await vi.waitFor(() =>
+ expect(cachedResolved()).toEqual({ timeline: true, thread: true })
+ );
+ confirm();
+ await pending;
+ expect(cachedResolved()).toEqual({ timeline: true, thread: true });
+ });
+
+ it('restores the prior state when resolving fails', async () => {
+ mocks.patchThread.mockRejectedValue(new Error('offline'));
+ const mutation = setup();
+ await expect(
+ mutation.mutateAsync({
+ parent,
+ rootId: 'root',
+ patch: { resolved: true },
+ })
+ ).rejects.toThrow('offline');
+ expect(cachedResolved()).toEqual({ timeline: false, thread: false });
+ });
+});