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.

fix(notifications): name agent comment senders and scroll to Discussion targets (#6924)

gbirman5995f5326ef2
diff --git a/apps/web/src/components/app/PreviewPanel.test.tsx b/apps/web/src/components/app/PreviewPanel.test.tsx
index d54ff0b6dd..ef91c1d01c 100644
--- a/apps/web/src/components/app/PreviewPanel.test.tsx
+++ b/apps/web/src/components/app/PreviewPanel.test.tsx
@@ -12,6 +12,7 @@ import {
const mocks = vi.hoisted(() => ({
navigateChannel: vi.fn(),
navigateCalendar: vi.fn(),
+ navigateDocument: vi.fn(),
mounts: vi.fn(),
unmounts: vi.fn(),
}));
@@ -21,6 +22,13 @@ vi.mock('@app/features/next-soup/utils', () => ({
getChannelEntityTarget: () => ({ kind: 'latest' }),
navigateChannelEntityToTarget: mocks.navigateChannel,
navigateCalendarPreviewToTarget: mocks.navigateCalendar,
+ navigateDocumentEntityToComment: mocks.navigateDocument,
+ getDocumentCommentTarget: (entity: {
+ commentTarget?: { commentId: string };
+ }) =>
+ entity.commentTarget
+ ? { commentId: entity.commentTarget.commentId, params: {} }
+ : undefined,
calendarViewTargetForEntity: vi.fn(),
reminderSplitTarget: vi.fn(),
}));
@@ -50,6 +58,7 @@ afterEach(() => {
function setup(initial: PreviewPanelSelection) {
const [entity, setEntity] = createSignal(initial);
+ const [navigationRequest, setNavigationRequest] = createSignal(0);
let preview: ReturnType<typeof useMaybePreviewPanel>;
const element = () => {
preview = useMaybePreviewPanel();
@@ -75,6 +84,7 @@ function setup(initial: PreviewPanelSelection) {
const view = render(() => (
<PreviewPanel
selectedEntity={entity()}
+ navigationRequest={navigationRequest()}
orchestrator={orchestrator}
splitPanelContext={{} as PreviewPanelProps['splitPanelContext']}
onFocusOut={onFocusOut}
@@ -83,6 +93,7 @@ function setup(initial: PreviewPanelSelection) {
return {
...view,
setEntity,
+ requestNavigation: () => setNavigationRequest((count) => count + 1),
createBlockInstance,
onFocusOut,
previewEntity: () => preview?.previewEntity(),
@@ -200,3 +211,32 @@ describe('channel preview navigation', () => {
expect(mocks.mounts).toHaveBeenCalledTimes(1);
});
});
+
+describe('re-opening the previewed selection', () => {
+ const document = {
+ type: 'document',
+ id: 'doc-1',
+ fileType: 'md',
+ commentTarget: { commentId: 'comment-1' },
+ } satisfies PreviewPanelSelection;
+
+ it('navigates the document to its comment again on each request', () => {
+ const view = setup(document);
+ expect(mocks.navigateDocument).toHaveBeenCalledTimes(1);
+
+ view.setEntity({ ...document });
+ expect(mocks.navigateDocument).toHaveBeenCalledTimes(1);
+
+ view.requestNavigation();
+ view.requestNavigation();
+ expect(mocks.navigateDocument).toHaveBeenCalledTimes(3);
+ expect(view.createBlockInstance).toHaveBeenCalledTimes(1);
+ expect(mocks.unmounts).not.toHaveBeenCalled();
+ });
+
+ it('re-targets a channel on request', () => {
+ const view = setup(channelSelections[1]);
+ view.requestNavigation();
+ expect(mocks.navigateChannel).toHaveBeenCalledTimes(2);
+ });
+});
diff --git a/apps/web/src/components/app/PreviewPanel.tsx b/apps/web/src/components/app/PreviewPanel.tsx
index 10245a55c1..9b549bfa61 100644
--- a/apps/web/src/components/app/PreviewPanel.tsx
+++ b/apps/web/src/components/app/PreviewPanel.tsx
@@ -47,6 +47,11 @@ export const [PreviewPanelContext, useMaybePreviewPanel] =
export type PreviewPanelProps = {
selectedEntity: PreviewPanelSelection | undefined;
+ /**
+ * Bumped by the host when the user re-opens the selection already shown, so
+ * the block navigates to its target again.
+ */
+ navigationRequest?: number;
orchestrator: BlockOrchestrator;
splitPanelContext: SplitPanelContextType;
onFocusOut?: VoidFunction;
@@ -115,8 +120,19 @@ function PreviewPanelContent(
return entity;
});
+ const navigation = createMemo(
+ () => ({
+ selection: navigationSelection(),
+ request: props.navigationRequest ?? 0,
+ }),
+ undefined,
+ {
+ equals: (a, b) => a.selection === b.selection && a.request === b.request,
+ }
+ );
+
createRenderEffect(
- on(navigationSelection, () => {
+ on(navigation, () => {
const entity = props.selectedEntity;
setInteractedWith(false);
if (!blockInstance()) return;
diff --git a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
index eccb629b11..ad561b8582 100644
--- a/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
+++ b/apps/web/src/features/block-md/component/DocumentDiscussion.tsx
@@ -6,7 +6,10 @@ import {
DiscussionProvider,
} from '@core/comments/discussion';
import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
-import { useUrlParams } from '@core/component/ParamsProvider';
+import {
+ useParamNavigationCount,
+ useUrlParams,
+} from '@core/component/ParamsProvider';
import {
enableUnifiedDocumentDiscussions,
isFeatureEnabled,
@@ -15,11 +18,12 @@ import {
DocumentConversation,
DocumentConversationComposer,
} from '@core/messages/DocumentConversation';
+import { scrollToRenderedTarget } from '@core/messages/scroll-to-rendered-target';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
import { buildSimpleEntityUrl } from '@core/util/url';
import type { MessageParent } from '@service-storage/messages';
-import { Show } from 'solid-js';
+import { createEffect, createMemo, on, onCleanup, Show } from 'solid-js';
import { createDocumentDiscussionSource } from '../comments/documentDiscussionSource';
import { URL_PARAMS } from '../constants';
import { useMarkdownDocument } from '../context/markdown-document-context';
@@ -77,22 +81,51 @@ export function MessageDocumentDiscussion(props: {
const parent: MessageParent = { type: 'document', id };
const floating = () =>
props.floatingComposerOnTouch === true && isTouchDevice();
+ let container: HTMLDivElement | undefined;
+ // Scroll to the linked message once per navigation of `comment_id`, as the
+ // margin does for anchored comments. A repeat navigation to the same message
+ // still scrolls; the URL value showing through after a navigation cleared it
+ // does not.
+ const commentNavigationCount = useParamNavigationCount(URL_PARAMS.commentId);
+ const scrollRequest = createMemo(
+ () => {
+ const commentId = params.commentId();
+ if (!commentId) return undefined;
+ const count = commentNavigationCount();
+ return {
+ commentId,
+ key: count === 0 ? `url:${commentId}` : `navigation:${count}`,
+ };
+ },
+ undefined,
+ { equals: (a, b) => a?.key === b?.key }
+ );
+ let scrolledKey: string | undefined;
+ createEffect(
+ on(scrollRequest, (request) => {
+ if (!request || !container || request.key === scrolledKey) return;
+ scrolledKey = request.key;
+ onCleanup(scrollToRenderedTarget(container, request.commentId));
+ })
+ );
return (
<>
- <DocumentConversation
- parent={parent}
- canWrite={permissions.canComment()}
- targetId={params.commentId()}
- label={props.label}
- buildLink={(message) =>
- buildSimpleEntityUrl(
- { type: blockName, id },
- { [URL_PARAMS.commentId]: message.id }
- )
- }
- hideComposer={floating()}
- hideWhenEmpty={floating()}
- />
+ <div ref={container} class="contents">
+ <DocumentConversation
+ parent={parent}
+ canWrite={permissions.canComment()}
+ targetId={params.commentId()}
+ label={props.label}
+ buildLink={(message) =>
+ buildSimpleEntityUrl(
+ { type: blockName, id },
+ { [URL_PARAMS.commentId]: message.id }
+ )
+ }
+ hideComposer={floating()}
+ hideWhenEmpty={floating()}
+ />
+ </div>
<Show when={floating() && permissions.canComment()}>
<StaticMarkdownContext>
<MobileMessageComposer
diff --git a/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx b/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx
index e5cee42dce..7aa4beec4b 100644
--- a/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx
+++ b/apps/web/src/features/block-md/component/MessageDocumentDiscussion.test.tsx
@@ -2,14 +2,23 @@ import { FloatRegion } from '@components/app/mobile/float-regions/FloatRegion';
import { FloatRegions } from '@components/app/mobile/float-regions/float-region-state';
import { setVirtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
import { cleanup, render, screen } from '@solidjs/testing-library';
-import { createSignal, onCleanup, type ParentProps } from 'solid-js';
-import { afterEach, describe, expect, it, vi } from 'vitest';
+import {
+ batch,
+ createSignal,
+ For,
+ onCleanup,
+ type ParentProps,
+} from 'solid-js';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocumentDiscussion } from './DocumentDiscussion';
const mocks = vi.hoisted(() => ({
mount: vi.fn(),
unmount: vi.fn(),
conversation: vi.fn(),
+ commentId: (): string | null => null,
+ navigationCount: (): number => 0,
+ renderedMessageIds: (): string[] => [],
}));
vi.mock('@core/constant/featureFlags', async (importOriginal) => ({
@@ -39,7 +48,11 @@ vi.mock('@core/messages/DocumentConversation', () => ({
hideWhenEmpty?: boolean;
}) => {
mocks.conversation(props);
- return null;
+ return (
+ <For each={mocks.renderedMessageIds()}>
+ {(id) => <div data-message-id={id} />}
+ </For>
+ );
},
DocumentConversationComposer: () => {
mocks.mount();
@@ -48,7 +61,8 @@ vi.mock('@core/messages/DocumentConversation', () => ({
},
}));
vi.mock('@core/component/ParamsProvider', () => ({
- useUrlParams: () => ({ commentId: () => null }),
+ useUrlParams: () => ({ commentId: () => mocks.commentId() }),
+ useParamNavigationCount: () => () => mocks.navigationCount(),
}));
vi.mock('@channel/Input/ChannelInputContainer', () => ({
ChannelInputContainer: (props: ParentProps) => props.children,
@@ -133,3 +147,82 @@ describe('mobile document discussion accessory behind the flag', () => {
expect(mocks.mount).toHaveBeenCalledOnce();
});
});
+
+describe('scrolling to a linked Discussion message', () => {
+ const scrollIntoView = vi.fn();
+ const [commentId, setCommentId] = createSignal<string | null>(null);
+ const [navigationCount, setNavigationCount] = createSignal(0);
+ const [renderedMessageIds, setRenderedMessageIds] = createSignal<string[]>(
+ []
+ );
+ const flushMutations = () => new Promise((resolve) => setTimeout(resolve));
+ const scrolledIds = () =>
+ scrollIntoView.mock.contexts.map(
+ (element) => (element as HTMLElement).dataset.messageId
+ );
+
+ beforeEach(() => {
+ Element.prototype.scrollIntoView = scrollIntoView;
+ mocks.commentId = commentId;
+ mocks.navigationCount = navigationCount;
+ mocks.renderedMessageIds = renderedMessageIds;
+ setCommentId(null);
+ setNavigationCount(0);
+ setRenderedMessageIds([]);
+ });
+
+ afterEach(() => {
+ scrollIntoView.mockReset();
+ });
+
+ const navigate = (id: string) =>
+ batch(() => {
+ setCommentId(id);
+ setNavigationCount((count) => count + 1);
+ });
+
+ it('scrolls to the target once it renders after its data loads', async () => {
+ setCommentId('m2');
+ setup();
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ setRenderedMessageIds(['m1', 'm2']);
+ await flushMutations();
+
+ expect(scrolledIds()).toEqual(['m2']);
+ });
+
+ it('scrolls again when a later navigation targets another message', async () => {
+ setRenderedMessageIds(['m1', 'm2']);
+ setup();
+ navigate('m1');
+ navigate('m2');
+ await flushMutations();
+
+ expect(scrolledIds()).toEqual(['m1', 'm2']);
+ });
+
+ it('scrolls again on a repeat navigation to the same message', async () => {
+ setRenderedMessageIds(['m1']);
+ setup();
+ navigate('m1');
+ navigate('m1');
+ await flushMutations();
+
+ expect(scrolledIds()).toEqual(['m1', 'm1']);
+ });
+
+ it('does not steal scroll on later renders or when the value shows through again', async () => {
+ setRenderedMessageIds(['m1']);
+ setup();
+ navigate('m1');
+ await flushMutations();
+
+ setRenderedMessageIds(['m1', 'm2']);
+ setCommentId(null);
+ setCommentId('m1');
+ await flushMutations();
+
+ expect(scrolledIds()).toEqual(['m1']);
+ });
+});
diff --git a/apps/web/src/features/entity/extractors-notification/notification-description.tsx b/apps/web/src/features/entity/extractors-notification/notification-description.tsx
index 42afcbcda0..600d1dce9b 100644
--- a/apps/web/src/features/entity/extractors-notification/notification-description.tsx
+++ b/apps/web/src/features/entity/extractors-notification/notification-description.tsx
@@ -1,6 +1,10 @@
import type { NotificationType } from '@core/types';
import { getDisplayNameParts, tryMacroId } from '@core/user';
import type { NotificationStack } from '@notifications';
+import {
+ getNotificationAgentSender,
+ getUniqueAgentSenders,
+} from '@notifications/notification-sender';
import { createMemo } from 'solid-js';
import type { Notification } from '../types/notification';
import {
@@ -57,7 +61,8 @@ export function NotificationDescription(props: NotificationDescriptionProps) {
// Sender display labels for the notification/stack. GitHub PR senders are
// always named by the GitHub login carried in the notification metadata —
// never by a linked Macro user's name, even when the notification has a
- // `sender_id`. Macro senders resolve to their display name.
+ // `sender_id`. Macro senders resolve to their display name; agents, which
+ // have no `sender_id`, are named from the metadata.
// Memoized so the per-sender name resolution (which has side effects: it
// queues a fetch and registers a reactive effect) runs once per dependency
// change rather than on every call from the description() formatters.
@@ -71,14 +76,19 @@ export function NotificationDescription(props: NotificationDescriptionProps) {
if (props.notification.sender_id) {
return [macroFirstName(props.notification.sender_id)];
}
- return [];
+ const agent = getNotificationAgentSender(props.notification);
+ return agent ? [agent.name] : [];
}
if (props.stack) {
if (isGithubNotificationType(props.stack.type)) {
return getUniqueGithubLogins(props.stack.notifications);
}
const macroIds = getUniqueSenderIds(props.stack.notifications);
- return macroIds.map(macroFirstName);
+ const agents = getUniqueAgentSenders(props.stack.notifications);
+ return [
+ ...macroIds.map(macroFirstName),
+ ...agents.map((agent) => agent.name),
+ ];
}
return [];
});
diff --git a/apps/web/src/features/entity/extractors-notification/notification-sender-icon.tsx b/apps/web/src/features/entity/extractors-notification/notification-sender-icon.tsx
index e666325291..9f7ff30807 100644
--- a/apps/web/src/features/entity/extractors-notification/notification-sender-icon.tsx
+++ b/apps/web/src/features/entity/extractors-notification/notification-sender-icon.tsx
@@ -1,12 +1,19 @@
-import { UserGroup } from '@core/component/UserGroup';
+import { BotIcon } from '@channel/Message/BotIcon';
import { UserIcon } from '@core/component/UserIcon';
import type { NotificationStack } from '@notifications';
-import { Avatar } from '@ui';
-import { Match, Show, Switch } from 'solid-js';
+import {
+ getNotificationAgentSender,
+ getUniqueAgentSenders,
+ type NotificationAgentSender,
+} from '@notifications/notification-sender';
+import { Avatar, AvatarGroup } from '@ui';
+import { createMemo, For, Match, Show, Switch } from 'solid-js';
+import { match } from 'ts-pattern';
import type { Notification } from '../types/notification';
import {
getGithubSenderAvatarUrl,
getGithubSenderLogin,
+ getUniqueSenderIds,
isGithubNotificationType,
} from './notification-description-helpers';
@@ -16,23 +23,14 @@ interface NotificationSenderIconProps {
size?: 'sm' | 'md' | 'lg';
}
-/**
- * Gets unique sender IDs from a notification stack
- */
-function getUniqueSenderIds(notifications: Notification[]): string[] {
- const senderIds = new Set<string>();
- for (const notification of notifications) {
- if (notification.sender_id) {
- senderIds.add(notification.sender_id);
- }
- }
- return Array.from(senderIds);
-}
+type Sender =
+ | { kind: 'user'; id: string }
+ | { kind: 'agent'; agent: NotificationAgentSender };
/**
* Displays the sender icon(s) for a notification
- * - Single sender: shows UserIcon
- * - Multiple senders: shows UserGroup with overlapping avatars
+ * - Single sender: shows UserIcon, or BotIcon for an agent
+ * - Multiple senders: shows overlapping avatars
*/
export function NotificationSenderIcon(props: NotificationSenderIconProps) {
const size = () => props.size ?? 'sm';
@@ -65,8 +63,40 @@ export function NotificationSenderIcon(props: NotificationSenderIconProps) {
return [];
};
- const hasSenders = () => senderIds().length > 0;
- const hasMultipleSenders = () => senderIds().length > 1;
+ // Agents carry no `sender_id`; they come from the notification metadata.
+ const agentSenders = (): NotificationAgentSender[] => {
+ if (props.notification) {
+ const agent = getNotificationAgentSender(props.notification);
+ return agent ? [agent] : [];
+ }
+ if (props.stack) {
+ return getUniqueAgentSenders(props.stack.notifications);
+ }
+ return [];
+ };
+
+ const senders = createMemo((): Sender[] => [
+ ...senderIds().map((id) => ({ kind: 'user' as const, id })),
+ ...agentSenders().map((agent) => ({ kind: 'agent' as const, agent })),
+ ]);
+
+ const maxShown = () => (senders().length === 2 ? 2 : 1);
+ const remaining = () => Math.max(0, senders().length - maxShown());
+
+ const renderSender = (sender: Sender) =>
+ match(sender)
+ .with({ kind: 'user' }, (user) => (
+ <UserIcon
+ id={user.id}
+ size={size()}
+ suppressClick
+ showTooltip={false}
+ />
+ ))
+ .with({ kind: 'agent' }, ({ agent }) => (
+ <BotIcon name={agent.name} avatarUrl={agent.avatarUrl} size={size()} />
+ ))
+ .exhaustive();
return (
<Switch>
@@ -77,26 +107,16 @@ export function NotificationSenderIcon(props: NotificationSenderIconProps) {
</Avatar>
)}
</Match>
- <Match when={hasSenders()}>
- <Show
- when={hasMultipleSenders()}
- fallback={
- <UserIcon
- id={senderIds()[0]}
- size={size()}
- suppressClick
- showTooltip={false}
- />
- }
- >
- <UserGroup
- userIds={senderIds()}
- maxUsers={senderIds().length === 2 ? 2 : 1}
- size={size()}
- suppressClick
- showTooltip={false}
- />
- </Show>
+ <Match when={senders().length === 1 && senders()[0]}>
+ {(sender) => renderSender(sender())}
+ </Match>
+ <Match when={senders().length > 1}>
+ <AvatarGroup size={size()}>
+ <For each={senders().slice(0, maxShown())}>{renderSender}</For>
+ <Show when={remaining()}>
+ <AvatarGroup.Count size={size()}>+{remaining()}</AvatarGroup.Count>
+ </Show>
+ </AvatarGroup>
</Match>
</Switch>
);
diff --git a/apps/web/src/features/entity/tests/notification-agent-sender.test.tsx b/apps/web/src/features/entity/tests/notification-agent-sender.test.tsx
new file mode 100644
index 0000000000..149d7b9e1b
--- /dev/null
+++ b/apps/web/src/features/entity/tests/notification-agent-sender.test.tsx
@@ -0,0 +1,160 @@
+import type { NotificationStack } from '@notifications';
+import {
+ getNotificationAgentSender,
+ getUniqueAgentSenders,
+} from '@notifications/notification-sender';
+import { cleanup, render } from '@solidjs/testing-library';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { NotificationDescription } from '../extractors-notification/notification-description';
+import { NotificationSenderIcon } from '../extractors-notification/notification-sender-icon';
+import type { Notification } from '../types/notification';
+
+vi.mock('@core/user', () => ({
+ getDisplayNameParts: (id: string) => ({
+ firstName: id === 'macro|[email protected]' ? 'Peter' : 'Ana',
+ fullName: '',
+ }),
+ tryMacroId: (id: string) => id,
+}));
+vi.mock('@core/component/UserIcon', () => ({
+ UserIcon: (props: { id: string }) => (
+ <span data-testid="user-icon">{props.id}</span>
+ ),
+}));
+vi.mock('@channel/Message/BotIcon', () => ({
+ BotIcon: (props: { name?: string; avatarUrl?: string }) => (
+ <span data-testid="bot-icon" data-avatar={props.avatarUrl ?? ''}>
+ {props.name}
+ </span>
+ ),
+}));
+
+afterEach(cleanup);
+
+const commentNotification = (
+ overrides: {
+ senderId?: string | null;
+ senderDisplayName?: string | null;
+ senderProfilePictureUrl?: string | null;
+ tag?: string;
+ } = {}
+): Notification =>
+ ({
+ id: crypto.randomUUID(),
+ sender_id: overrides.senderId ?? null,
+ notification_metadata: {
+ tag: overrides.tag ?? 'replied_to_document_comment_thread',
+ content: {
+ commentId: 'comment-1',
+ documentName: 'Plan',
+ senderDisplayName: overrides.senderDisplayName ?? null,
+ senderProfilePictureUrl: overrides.senderProfilePictureUrl ?? null,
+ },
+ },
+ }) as unknown as Notification;
+
+const stackOf = (notifications: Notification[]) =>
+ ({
+ type: 'replied_to_document_comment_thread',
+ notifications,
+ }) as unknown as NotificationStack;
+
+describe('getNotificationAgentSender', () => {
+ it('reads the agent name and avatar from comment metadata', () => {
+ expect(
+ getNotificationAgentSender(
+ commentNotification({
+ senderDisplayName: 'Macro',
+ senderProfilePictureUrl: 'https://cdn/macro.png',
+ })
+ )
+ ).toEqual({ name: 'Macro', avatarUrl: 'https://cdn/macro.png' });
+ });
+
+ it('ignores human senders and notifications without an agent name', () => {
+ expect(
+ getNotificationAgentSender(
+ commentNotification({
+ senderId: 'macro|[email protected]',
+ senderDisplayName: 'Macro',
+ })
+ )
+ ).toBeUndefined();
+ expect(getNotificationAgentSender(commentNotification())).toBeUndefined();
+ });
+
+ it('only treats comment notifications as agent-authored', () => {
+ expect(
+ getNotificationAgentSender(
+ commentNotification({
+ tag: 'channel_mention',
+ senderDisplayName: 'Macro',
+ })
+ )
+ ).toBeUndefined();
+ });
+
+ it('deduplicates agents across a stack by name', () => {
+ expect(
+ getUniqueAgentSenders([
+ commentNotification({ senderDisplayName: 'Macro' }),
+ commentNotification({ senderDisplayName: 'Macro' }),
+ commentNotification({ senderDisplayName: 'Helper' }),
+ ]).map((agent) => agent.name)
+ ).toEqual(['Macro', 'Helper']);
+ });
+});
+
+describe('agent-authored comment notifications', () => {
+ it('names the agent before the action', () => {
+ const { container } = render(() => (
+ <NotificationDescription
+ notification={commentNotification({ senderDisplayName: 'Macro' })}
+ />
+ ));
+ expect(container.textContent).toBe('Macro replied to a comment');
+ });
+
+ it('shows the agent icon in the sender slot', () => {
+ const { getByTestId } = render(() => (
+ <NotificationSenderIcon
+ notification={commentNotification({
+ senderDisplayName: 'Macro',
+ senderProfilePictureUrl: 'https://cdn/macro.png',
+ })}
+ />
+ ));
+ const icon = getByTestId('bot-icon');
+ expect(icon.textContent).toBe('Macro');
+ expect(icon.dataset.avatar).toBe('https://cdn/macro.png');
+ });
+
+ it('counts the agent as a sender in a stack', () => {
+ const stack = stackOf([
+ commentNotification({ senderId: 'macro|[email protected]' }),
+ commentNotification({ senderDisplayName: 'Macro' }),
+ commentNotification({ senderDisplayName: 'Macro' }),
+ ]);
+ const { container, getAllByTestId } = render(() => (
+ <>
+ <NotificationDescription stack={stack} />
+ <NotificationSenderIcon stack={stack} />
+ </>
+ ));
+ expect(container.textContent).toContain('3 replies from Peter and Macro');
+ expect(getAllByTestId('user-icon')).toHaveLength(1);
+ expect(getAllByTestId('bot-icon')).toHaveLength(1);
+ });
+
+ it('names a stack from a single agent', () => {
+ const { container } = render(() => (
+ <NotificationDescription
+ stack={stackOf([
+ commentNotification({ senderDisplayName: 'Macro' }),
+ commentNotification({ senderDisplayName: 'Macro' }),
+ ])}
+ />
+ ));
+ expect(container.textContent).toBe('Macro: 2 replies');
+ });
+});
diff --git a/apps/web/src/features/inbox-view/components/HomeListEntity.tsx b/apps/web/src/features/inbox-view/components/HomeListEntity.tsx
index 105732abf9..e9c692892b 100644
--- a/apps/web/src/features/inbox-view/components/HomeListEntity.tsx
+++ b/apps/web/src/features/inbox-view/components/HomeListEntity.tsx
@@ -6,6 +6,7 @@ import { Entity, MaybeEntityRow } from '@entity';
import type { BaseListEntityProps } from '@entity/composed/list-entity/shared';
import { unreadFilterFn } from '@entity/utils/filter';
import { getDocumentCommentNotification } from '@notifications/document-comment-notification';
+import { getNotificationAgentSender } from '@notifications/notification-sender';
import type { UnifiedNotification } from '@notifications/types';
import ArrowBendUpLeftIcon from '@phosphor-icons/core/regular/arrow-bend-up-left.svg?component-solid';
import ChatTeardropIcon from '@phosphor-icons/core/regular/chat-teardrop.svg?component-solid';
@@ -180,10 +181,13 @@ function HomeCommentTitle(props: {
}) {
const sender = () => {
const senderId = props.notification.sender_id;
- return senderId
- ? getDisplayName(tryMacroId(senderId), { emailFallback: 'local-part' }) ||
- 'Someone'
- : 'Someone';
+ if (senderId) {
+ return (
+ getDisplayName(tryMacroId(senderId), { emailFallback: 'local-part' }) ||
+ 'Someone'
+ );
+ }
+ return getNotificationAgentSender(props.notification)?.name ?? 'Someone';
};
const action = () =>
match(props.notification.notification_metadata.tag)
diff --git a/apps/web/src/features/inbox-view/components/home-press.test.tsx b/apps/web/src/features/inbox-view/components/home-press.test.tsx
index 76227ec12d..5523f41b8e 100644
--- a/apps/web/src/features/inbox-view/components/home-press.test.tsx
+++ b/apps/web/src/features/inbox-view/components/home-press.test.tsx
@@ -128,4 +128,38 @@ describe('Home document comment row', () => {
it('reads as the plain document once the notification is done', () => {
expect(renderRow('done').textContent).not.toContain('mentioned you');
});
+
+ it('names the agent that replied instead of someone', () => {
+ const row = render(() => (
+ <HomeListEntity
+ entity={
+ {
+ type: 'document',
+ id: 'doc-1',
+ name: 'Plan',
+ ownerId: 'test-user',
+ fileType: 'md',
+ notifications: () => [
+ {
+ ...commentNotification('unseen'),
+ sender_id: null,
+ notification_metadata: {
+ tag: 'replied_to_document_comment_thread',
+ content: {
+ commentId: 'comment-1',
+ documentName: 'Plan',
+ senderDisplayName: 'Macro',
+ },
+ },
+ },
+ ],
+ } as never
+ }
+ occurrenceKey="doc-1"
+ />
+ )).container.querySelector<HTMLElement>('[data-home-item]')!;
+
+ expect(row.textContent).toContain('Macro replied on Recent chat');
+ expect(row.textContent).not.toContain('Someone');
+ });
});
diff --git a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx b/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
index 4b23f237b1..bc9fbe83aa 100644
--- a/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view-context.test.tsx
@@ -6,6 +6,7 @@ import {
useSplitRouter,
} from '@app/lib/split-router';
import { createMemorySplitRouterLocation } from '@app/lib/split-router/integrations/memory';
+import type { PreviewPanelSelection } from '@components/app/previewTarget';
import { appSplitRoutes } from '@components/app/split-layout/split-router/app-routes';
import { cleanup, render } from '@solidjs/testing-library';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -102,6 +103,7 @@ vi.mock('@core/constant/allBlocks', () => ({
fileTypeToResolvedBlockName: (type: string) =>
['task', 'snippet', 'skill'].includes(type) ? 'md' : type,
isBlockAlias: () => false,
+ itemToBlockName: (item: { fileType?: string }) => item.fileType ?? 'md',
resolveBlockAlias: (type: string) => type,
}));
vi.mock('@components/app/createPreviewSelectionGuard', () => ({
@@ -458,6 +460,34 @@ describe('InboxViewProvider route selection', () => {
expect(context.previewEntity()).toBeUndefined();
});
+ it('asks the preview to navigate again when the previewed row is re-opened', async () => {
+ const { context, location, router } = mountProvider();
+ const row = {
+ type: 'document',
+ id: 'doc-1',
+ fileType: 'md',
+ commentTarget: { commentId: 'comment-1' },
+ } satisfies PreviewPanelSelection;
+
+ context.openPreview(row);
+ await router.settled();
+ const url = location.read().pathname + location.read().search;
+ expect(context.previewNavigationRequest()).toBe(0);
+
+ expect(context.openPreview({ ...row })).toBe(true);
+ expect(context.openPreview({ ...row })).toBe(true);
+ await router.settled();
+ expect(context.previewNavigationRequest()).toBe(2);
+ expect(location.read().pathname + location.read().search).toBe(url);
+
+ context.openPreview({ ...row, commentTarget: { commentId: 'comment-2' } });
+ await router.settled();
+ expect(context.previewNavigationRequest()).toBe(2);
+ expect(location.read().search).toContain(
+ 's0.inbox-preview.targetCommentId=comment-2'
+ );
+ });
+
it('round-trips calendar, reminder, foreign, and document subtype targets', async () => {
const { context, location, router } = mountProvider();
diff --git a/apps/web/src/features/inbox-view/inbox-view-context.tsx b/apps/web/src/features/inbox-view/inbox-view-context.tsx
index 6cd1dcbccd..d9906029fe 100644
--- a/apps/web/src/features/inbox-view/inbox-view-context.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view-context.tsx
@@ -11,7 +11,13 @@ import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { createAssertedContextProvider } from '@core/context/createContext';
import { useUserId } from '@core/context/user';
import type { ContextProviderProps } from '@solid-primitives/context';
-import { type Accessor, createEffect, createMemo, on } from 'solid-js';
+import {
+ type Accessor,
+ createEffect,
+ createMemo,
+ createSignal,
+ on,
+} from 'solid-js';
import {
createStore,
produce,
@@ -47,6 +53,8 @@ export type InboxViewContext = {
state: Store<InboxViewState>;
setState: SetStoreFunction<InboxViewState>;
previewEntity: Accessor<PreviewPanelSelection | undefined>;
+ /** Counts re-opens of the selection already previewed, such as a re-click. */
+ previewNavigationRequest: Accessor<number>;
openPreview: (entity: PreviewPanelSelection) => boolean;
closePreview: () => void;
setTab: (tab: InboxTab) => void;
@@ -134,8 +142,24 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<
},
}
);
+ const [previewNavigationRequest, setPreviewNavigationRequest] =
+ createSignal(0);
+ // Re-opening the previewed selection leaves the route unchanged, so the
+ // preview sees no new selection; the request asks it to navigate again.
+ const isPreviewed = (entity: PreviewPanelSelection) => {
+ const current = previewEntity();
+ return (
+ current !== undefined &&
+ JSON.stringify(inboxPreviewNavigation(current)) ===
+ JSON.stringify(inboxPreviewNavigation(entity))
+ );
+ };
const openPreview = (entity: PreviewPanelSelection) => {
if (!selectPreview.canSelect(entity)) return false;
+ if (isPreviewed(entity)) {
+ setPreviewNavigationRequest((count) => count + 1);
+ return true;
+ }
navigatePreview(entity);
return true;
};
@@ -178,6 +202,7 @@ export const [InboxViewProvider, useInboxView] = createAssertedContextProvider<
state,
setState,
previewEntity,
+ previewNavigationRequest,
openPreview,
closePreview,
setTab,
diff --git a/apps/web/src/features/inbox-view/inbox-view.tsx b/apps/web/src/features/inbox-view/inbox-view.tsx
index 9bc77830a1..0b87fc9cf5 100644
--- a/apps/web/src/features/inbox-view/inbox-view.tsx
+++ b/apps/web/src/features/inbox-view/inbox-view.tsx
@@ -154,12 +154,14 @@ function InboxViewRoot() {
export function InboxDetailRouteView() {
const panel = useSplitPanelOrThrow();
const orchestrator = useGlobalBlockOrchestrator();
- const { previewEntity, closePreview } = useInboxView();
+ const { previewEntity, previewNavigationRequest, closePreview } =
+ useInboxView();
return (
<Suspense>
<PreviewPanel
selectedEntity={previewEntity()}
+ navigationRequest={previewNavigationRequest()}
orchestrator={orchestrator}
splitPanelContext={panel}
headerLeading={<HomeReturnBreadcrumb onReturn={closePreview} />}
diff --git a/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx b/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx
index 741255770b..ddce496242 100644
--- a/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx
+++ b/apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx
@@ -29,6 +29,7 @@ import { formatCompactRelativeTimestamp } from '@entity/utils/timestamp';
import MacroLogo from '@icon/macro-logo.svg';
import GithubIcon from '@icon/mcp-github.svg';
import { formatCalendarReminderTime } from '@notifications';
+import { getNotificationSenderFallbackName } from '@notifications/notification-sender';
import FilesIcon from '@phosphor/files.svg';
import GitMergeIcon from '@phosphor/git-merge.svg';
import GitPullRequestIcon from '@phosphor/git-pull-request.svg';
@@ -119,46 +120,6 @@ const getGithubSender = (entity: EntityData, notification?: Notification) => {
return { id: login, fallbackName: login, imageUrl };
};
-const getNotificationSenderFallbackName = (
- notification: Notification
-): string | undefined => {
- const content = notification.notification_metadata.content as
- | {
- sender?: string;
- senderDisplayName?: string | null;
- senderGithubLogin?: string;
- botName?: string;
- mentionedBy?: string;
- }
- | undefined;
-
- switch (notification.notification_metadata.tag) {
- case 'new_email':
- return content?.sender ?? undefined;
- case 'ai_response':
- return 'Macro agent';
- case 'agent_session_settled':
- case 'agent_session_waiting_for_input':
- return content?.botName;
- case 'agent_session_mentioned':
- return content?.mentionedBy ?? content?.botName;
- case 'channel_message_send':
- return content?.sender ?? notification.sender_id ?? undefined;
- case 'commented_on_document':
- case 'mentioned_in_document_comment':
- case 'replied_to_document_comment_thread':
- return content?.senderDisplayName ?? undefined;
- case 'github_pr_status_changed':
- case 'github_review_requested':
- case 'github_pr_comment':
- case 'github_pr_mention':
- case 'github_pr_review':
- return content?.senderGithubLogin ?? notification.sender_id ?? undefined;
- default:
- return undefined;
- }
-};
-
const getTimestamp = (entity: EntityData, notification?: Notification) => {
// The reminder's body already says when it fires, so the timestamp says when
// it was set instead — the way other rows show when they arrived.
diff --git a/apps/web/src/features/notifications/notification-sender.ts b/apps/web/src/features/notifications/notification-sender.ts
new file mode 100644
index 0000000000..19c6a578f5
--- /dev/null
+++ b/apps/web/src/features/notifications/notification-sender.ts
@@ -0,0 +1,103 @@
+import { match } from 'ts-pattern';
+import type { UnifiedNotification } from './types';
+
+type SenderMetadataContent = {
+ sender?: string;
+ senderDisplayName?: string | null;
+ senderGithubLogin?: string;
+ senderProfilePictureUrl?: string | null;
+ botName?: string;
+ mentionedBy?: string;
+};
+
+const senderContent = (
+ notification: UnifiedNotification
+): SenderMetadataContent | undefined =>
+ (notification.notification_metadata as { content?: SenderMetadataContent })
+ .content;
+
+/**
+ * The sender name carried in the notification metadata, for notifications
+ * whose sender is not (only) a Macro user id: email senders, agents, bots and
+ * GitHub logins.
+ */
+export function getNotificationSenderFallbackName(
+ notification: UnifiedNotification
+): string | undefined {
+ const content = senderContent(notification);
+
+ return match(notification.notification_metadata.tag)
+ .with('new_email', () => content?.sender ?? undefined)
+ .with('ai_response', () => 'Macro agent')
+ .with(
+ 'agent_session_settled',
+ 'agent_session_waiting_for_input',
+ () => content?.botName
+ )
+ .with(
+ 'agent_session_mentioned',
+ () => content?.mentionedBy ?? content?.botName
+ )
+ .with(
+ 'channel_message_send',
+ () => content?.sender ?? notification.sender_id ?? undefined
+ )
+ .with(
+ 'commented_on_document',
+ 'mentioned_in_document_comment',
+ 'replied_to_document_comment_thread',
+ () => content?.senderDisplayName ?? undefined
+ )
+ .with(
+ 'github_pr_status_changed',
+ 'github_review_requested',
+ 'github_pr_comment',
+ 'github_pr_mention',
+ 'github_pr_review',
+ () => content?.senderGithubLogin ?? notification.sender_id ?? undefined
+ )
+ .otherwise(() => undefined);
+}
+
+export type NotificationAgentSender = {
+ name: string;
+ avatarUrl?: string;
+};
+
+/**
+ * The agent that authored a comment notification. Agent-authored comments
+ * carry no `sender_id` (it only holds human senders); the agent's name and
+ * avatar travel in the metadata instead.
+ */
+export function getNotificationAgentSender(
+ notification: UnifiedNotification
+): NotificationAgentSender | undefined {
+ if (notification.sender_id) return undefined;
+
+ return match(notification.notification_metadata.tag)
+ .with(
+ 'commented_on_document',
+ 'mentioned_in_document_comment',
+ 'replied_to_document_comment_thread',
+ () => {
+ const name = getNotificationSenderFallbackName(notification)?.trim();
+ if (!name) return undefined;
+ const avatarUrl =
+ senderContent(notification)?.senderProfilePictureUrl ?? undefined;
+ return { name, avatarUrl };
+ }
+ )
+ .otherwise(() => undefined);
+}
+
+/** Unique agent senders across a stack, by name, preserving order. */
+export function getUniqueAgentSenders(
+ notifications: UnifiedNotification[]
+): NotificationAgentSender[] {
+ const byName = new Map<string, NotificationAgentSender>();
+ for (const notification of notifications) {
+ const agent = getNotificationAgentSender(notification);
+ if (agent && !byName.has(agent.name)) byName.set(agent.name, agent);
+ }
+ return Array.from(byName.values());
+}
diff --git a/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.ts b/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.ts
new file mode 100644
index 0000000000..de376a57b7
--- /dev/null
+++ b/apps/web/src/lib/core/messages/scroll-to-rendered-target.test.ts
@@ -0,0 +1,98 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { scrollToRenderedTarget } from './scroll-to-rendered-target';
+
+const scrollIntoView = vi.fn();
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ Element.prototype.scrollIntoView = scrollIntoView;
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ scrollIntoView.mockReset();
+ document.body.innerHTML = '';
+});
+
+const flushMutations = () => Promise.resolve();
+
+function renderTarget(root: HTMLElement, id: string) {
+ const target = document.createElement('div');
+ target.dataset.messageId = id;
+ root.append(target);
+ return target;
+}
+
+describe('scrollToRenderedTarget', () => {
+ it('scrolls a target that is already rendered', () => {
+ const root = document.body.appendChild(document.createElement('div'));
+ const target = renderTarget(root, 'm1');
+
+ scrollToRenderedTarget(root, 'm1');
+
+ expect(scrollIntoView).toHaveBeenCalledOnce();
+ expect(scrollIntoView.mock.contexts[0]).toBe(target);
+ });
+
+ it('waits for the target to render, then scrolls once', async () => {
+ const root = document.body.appendChild(document.createElement('div'));
+ scrollToRenderedTarget(root, 'm1');
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ renderTarget(root, 'other');
+ await flushMutations();
+ expect(scrollIntoView).not.toHaveBeenCalled();
+
+ renderTarget(root, 'm1');
+ await flushMutations();
+ renderTarget(root, 'later');
+ await flushMutations();
+ expect(scrollIntoView).toHaveBeenCalledOnce();
+ });
+
+ it('never scrolls after the user starts scrolling', async () => {
+ const root = document.body.appendChild(document.createElement('div'));
+ scrollToRenderedTarget(root, 'm1');
+
+ window.dispatchEvent(new WheelEvent('wheel'));
+ renderTarget(root, 'm1');
+ await flushMutations();
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it('gives up after the timeout', async () => {
+ const root = document.body.appendChild(document.createElement('div'));
+ scrollToRenderedTarget(root, 'm1', {
+ timeoutMs: 100,
+ });
+
+ vi.advanceTimersByTime(100);
+ renderTarget(root, 'm1');
+ await flushMutations();
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+
+ it('matches an id with selector metacharacters literally', () => {
+ const root = document.body.appendChild(document.createElement('div'));
+ renderTarget(root, 'm1');
+ const target = renderTarget(root, 'm1"], [data-message-id="m1');
+
+ expect(() =>
+ scrollToRenderedTarget(root, 'm1"], [data-message-id="m1')
+ ).not.toThrow();
+ expect(scrollIntoView.mock.contexts).toEqual([target]);
+ });
+
+ it('stops waiting when cancelled', async () => {
+ const root = document.body.appendChild(document.createElement('div'));
+ const cancel = scrollToRenderedTarget(root, 'm1');
+
+ cancel();
+ renderTarget(root, 'm1');
+ await flushMutations();
+
+ expect(scrollIntoView).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/core/messages/scroll-to-rendered-target.ts b/apps/web/src/lib/core/messages/scroll-to-rendered-target.ts
new file mode 100644
index 0000000000..6624fc9065
--- /dev/null
+++ b/apps/web/src/lib/core/messages/scroll-to-rendered-target.ts
@@ -0,0 +1,52 @@
+const DEFAULT_TIMEOUT_MS = 10_000;
+
+const USER_SCROLL_EVENTS = ['wheel', 'touchmove', 'keydown'] as const;
+
+/**
+ * Scrolls the message element under `root` whose `data-message-id` is
+ * `messageId` into view, now or as soon as it renders. Gives up after
+ * `timeoutMs`, or as soon as the user starts scrolling themselves, so a slow
+ * load never yanks the view later.
+ * Returns a cancel function.
+ */
+export function scrollToRenderedTarget(
+ root: HTMLElement,
+ messageId: string,
+ options?: { timeoutMs?: number }
+): () => void {
+ let done = false;
+ let observer: MutationObserver | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+
+ const cancel = () => {
+ if (done) return;
+ done = true;
+ observer?.disconnect();
+ if (timer !== undefined) clearTimeout(timer);
+ for (const type of USER_SCROLL_EVENTS)
+ window.removeEventListener(type, cancel, true);
+ };
+
+ const tryScroll = () => {
+ // Compared, not interpolated into a selector: the id comes from the URL.
+ const target = Array.from(
+ root.querySelectorAll<HTMLElement>('[data-message-id]')
+ ).find((element) => element.dataset.messageId === messageId);
+ if (!target) return false;
+ cancel();
+ target.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ return true;
+ };
+
+ if (tryScroll()) return cancel;
+
+ observer = new MutationObserver(() => {
+ tryScroll();
+ });
+ observer.observe(root, { childList: true, subtree: true });
+ timer = setTimeout(cancel, options?.timeoutMs ?? DEFAULT_TIMEOUT_MS);
+ for (const type of USER_SCROLL_EVENTS)
+ window.addEventListener(type, cancel, { capture: true, passive: true });
+
+ return cancel;
+}