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(md/channel): quote reply node v1 with backlink (#6119)

Seamus2904e2beb489
diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsx
index eab7acd65e..f8f170a179 100644
--- a/apps/web/src/features/channel/Channel/Channel.tsx
+++ b/apps/web/src/features/channel/Channel/Channel.tsx
@@ -92,7 +92,7 @@ import {
import { ChannelInputContainer } from '../Input/ChannelInputContainer';
import { hasSendableInputContent } from '../Input/utils/sendable-content';
import { ChannelThread } from '../Thread';
-import { buildQuoteReplyValue } from '../Thread/utils/message-actions';
+import { buildReplyTargetValue } from '../Thread/utils/message-actions';
import { isUnifiedInputMode } from '../unified-input-mode';
import { ActiveCallMessage } from './ActiveCallMessage';
import { ChannelDropZone } from './ChannelDropZone';
@@ -414,13 +414,20 @@ export function Channel(props: ChannelProps) {
return state;
};
- const openQuoteReplyInput = (message: MessageData) => {
+ const openReplyTargetInput = (
+ message: MessageData,
+ selectedText?: string,
+ renderedText?: string
+ ) => {
const threadId = message.thread_id ?? message.id;
const state = threadManager.getOrCreateThreadState(threadId);
const beforeSnapshot = state.replyInputState();
const nextSnapshot: InputSnapshot = {
- value: buildQuoteReplyValue({
- quotedContent: message.content,
+ value: buildReplyTargetValue({
+ channelId: props.channelId,
+ message,
+ selectedText,
+ renderedText,
existingValue: beforeSnapshot?.value,
}),
mentions: beforeSnapshot?.mentions ?? [],
@@ -455,7 +462,7 @@ export function Channel(props: ChannelProps) {
removeReaction: removeReactionMutation.mutate,
onReply: (ctx) => {
if (ctx.message.thread_id) {
- openQuoteReplyInput(ctx.message);
+ openReplyTargetInput(ctx.message, ctx.selectedText, ctx.renderedText);
return;
}
openReplyInput(ctx.message);
@@ -905,7 +912,7 @@ export function Channel(props: ChannelProps) {
getTargetMessage={() => {
const target = unifiedInput.replyTarget();
if (target?.message) return target.message;
- // A restored quote-reply has no resolvable
+ // A restored referenced reply has no resolvable
// message (messageById only indexes thread
// roots) — don't misattribute it to the root.
if (target?.replyId) return undefined;
diff --git a/apps/web/src/features/channel/Channel/UnifiedReplyInput.tsx b/apps/web/src/features/channel/Channel/UnifiedReplyInput.tsx
index 028cfb86f2..b7daab508b 100644
--- a/apps/web/src/features/channel/Channel/UnifiedReplyInput.tsx
+++ b/apps/web/src/features/channel/Channel/UnifiedReplyInput.tsx
@@ -8,7 +8,7 @@ import { ThreadReplyChannelInput } from '../Thread/ThreadReplyChannelInput';
/**
* Thread-reply face of the unified-input mode. Registers into the same
* `ThreadState` slots and persistence keys as the inline `ThreadReplyInput`,
- * so drafts and the `openReplyInput`/`openQuoteReplyInput` flows are shared
+ * so drafts and the reply-reference insertion flow are shared
* between inline and unified-input modes.
*/
export function UnifiedReplyInput(props: {
@@ -16,7 +16,7 @@ export function UnifiedReplyInput(props: {
threadId: string;
state: ThreadState;
/**
- * The message the reply is bound to — a specific reply for quote-replies,
+ * The message the reply is bound to — a specific referenced reply,
* otherwise the thread root.
*/
getTargetMessage: () => MessageData | undefined;
diff --git a/apps/web/src/features/channel/Input/types.ts b/apps/web/src/features/channel/Input/types.ts
index 35a230e103..6bd25e2a2e 100644
--- a/apps/web/src/features/channel/Input/types.ts
+++ b/apps/web/src/features/channel/Input/types.ts
@@ -86,7 +86,7 @@ export type RestoreSnapshotOptions = {
/**
* `'trailing-paragraph'` places the caret at the end of the restored
* content's trailing paragraph, appending an empty one when the content
- * ends in a non-paragraph block (e.g. a quote-reply's blockquote) — so
+ * ends in a non-paragraph block (e.g. a reply reference) — so
* typing never extends the block itself. With `focus: false` the caret
* is placed when the input is next focused programmatically (e.g. via a
* focus request), so the restore itself never steals focus.
diff --git a/apps/web/src/features/channel/Input/utils/select-trailing-paragraph.ts b/apps/web/src/features/channel/Input/utils/select-trailing-paragraph.ts
index 696f913a73..c3ec97bfea 100644
--- a/apps/web/src/features/channel/Input/utils/select-trailing-paragraph.ts
+++ b/apps/web/src/features/channel/Input/utils/select-trailing-paragraph.ts
@@ -4,11 +4,11 @@ import { $createParagraphNode, $getRoot, $isParagraphNode } from 'lexical';
* Move the caret to the end of the editor content, ensuring it lands on its
* own paragraph when the content ends in a non-paragraph block.
*
- * Restoring a quote-reply leaves the blockquote as the final block — the
+ * Restoring an explicit reply can leave its decorator as the final block — the
* markdown importer drops whitespace-only trailing paragraphs and parks the
* caret at the start of the content — so typing would extend the quote
- * itself. Appending an empty paragraph puts the caret on a fresh line below
- * the quote instead. Content that already ends in a paragraph (e.g. an
+ * block itself. Appending an empty paragraph puts the caret on a fresh line
+ * below the reference instead. Content that already ends in a paragraph (e.g. an
* existing draft) keeps its shape, with the caret at the end of it.
*
* Must be called inside `editor.update()`.
diff --git a/apps/web/src/features/channel/Message/ActionMenu.tsx b/apps/web/src/features/channel/Message/ActionMenu.tsx
index 6b917690cd..8865885d9c 100644
--- a/apps/web/src/features/channel/Message/ActionMenu.tsx
+++ b/apps/web/src/features/channel/Message/ActionMenu.tsx
@@ -17,6 +17,10 @@ import {
onCleanup,
Show,
} from 'solid-js';
+import {
+ getRenderedMessageReplyText,
+ getSelectedMessageText,
+} from './browser-selection';
import {
useMessage,
useMessageActionMenuVisibility,
@@ -61,12 +65,14 @@ type ActionMenuProps = {
function ActionButton(props: {
action: ActionItem;
onClick: JSX.EventHandlerUnion<HTMLButtonElement, MouseEvent>;
+ onPointerDown?: JSX.EventHandlerUnion<HTMLButtonElement, PointerEvent>;
}) {
return (
<Button
aria-label={props.action.label}
data-message-action={props.action.id}
onClick={props.onClick}
+ onPointerDown={props.onPointerDown}
tooltip={props.action.label}
size="icon-sm"
variant="ghost"
@@ -85,6 +91,8 @@ function ActionMenuContent(props: ActionMenuProps) {
const actions = useMessageActions();
const actionMenuVisibility = useMessageActionMenuVisibility();
const [emojiMenuOpen, setEmojiMenuOpen] = createSignal(false);
+ let selectedReplyText: string | undefined;
+ let renderedReplyText: string | undefined;
const handleEmojiMenuOpenChange = (isOpen: boolean) => {
setEmojiMenuOpen(isOpen);
@@ -237,8 +245,42 @@ function ActionMenuContent(props: ActionMenuProps) {
{(action) => (
<ActionButton
action={action}
+ onPointerDown={(event) => {
+ if (action.id !== 'reply') return;
+ selectedReplyText = getSelectedMessageText(
+ event.currentTarget,
+ message().id
+ );
+ renderedReplyText = getRenderedMessageReplyText(
+ event.currentTarget,
+ message().id
+ );
+ }}
onClick={(event) => {
- void action.onClick?.({ message: message(), event });
+ const selectedText =
+ action.id === 'reply'
+ ? (selectedReplyText ??
+ getSelectedMessageText(
+ event.currentTarget,
+ message().id
+ ))
+ : undefined;
+ selectedReplyText = undefined;
+ const renderedText =
+ action.id === 'reply'
+ ? (renderedReplyText ??
+ getRenderedMessageReplyText(
+ event.currentTarget,
+ message().id
+ ))
+ : undefined;
+ renderedReplyText = undefined;
+ void action.onClick?.({
+ message: message(),
+ event,
+ selectedText,
+ renderedText,
+ });
}}
/>
)}
diff --git a/apps/web/src/features/channel/Message/Content.tsx b/apps/web/src/features/channel/Message/Content.tsx
index e911c01d6e..aa4bdd9e03 100644
--- a/apps/web/src/features/channel/Message/Content.tsx
+++ b/apps/web/src/features/channel/Message/Content.tsx
@@ -26,6 +26,7 @@ export function Content(props: ContentProps) {
return (
<Show when={message().content}>
<div
+ data-message-content
class={cn(
'whitespace-pre-wrap wrap-break-word max-w-full',
bigEmoji() ? 'text-4xl' : 'text-sm',
diff --git a/apps/web/src/features/channel/Message/SenderName.tsx b/apps/web/src/features/channel/Message/SenderName.tsx
index ffd26abd60..881579b368 100644
--- a/apps/web/src/features/channel/Message/SenderName.tsx
+++ b/apps/web/src/features/channel/Message/SenderName.tsx
@@ -1,9 +1,7 @@
import { getDisplayName, tryMacroId } from '@core/user';
-import { senderFromStorageId } from '@queries/channel/message-sender';
-import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
+import { getBotDisplayName } from '@queries/channel/message-sender';
import { cn } from '@ui';
import { Show } from 'solid-js';
-import { MACRO_AI_BOT_ID, MACRO_AI_NAME } from '../macroAi';
import { useMessage } from './context';
import type { MessageData } from './types';
@@ -12,17 +10,6 @@ type SenderNameProps = {
hidden?: boolean;
};
-/** Resolve a bot sender's display name, or `undefined` for user senders. */
-function botName(
- senderId: string,
- sender: ApiMessageSender | undefined
-): string | undefined {
- const parsed = sender ?? senderFromStorageId(senderId);
- if (parsed.type !== 'bot') return undefined;
- if (parsed.name) return parsed.name;
- return parsed.id === MACRO_AI_BOT_ID ? MACRO_AI_NAME : 'Bot';
-}
-
export function MessageSenderName(props: SenderNameProps) {
const message = useMessage();
@@ -39,6 +26,6 @@ export function SenderName(props: { message: MessageData }) {
const macroId = () => tryMacroId(props.message.sender_id);
const displayName = () => getDisplayName(macroId());
const agentName = () =>
- botName(props.message.sender_id, props.message.sender);
+ getBotDisplayName(props.message.sender_id, props.message.sender);
return <>{agentName() ?? displayName()}</>;
}
diff --git a/apps/web/src/features/channel/Message/browser-selection.ts b/apps/web/src/features/channel/Message/browser-selection.ts
new file mode 100644
index 0000000000..8ed09a627a
--- /dev/null
+++ b/apps/web/src/features/channel/Message/browser-selection.ts
@@ -0,0 +1,51 @@
+/**
+ * Return selected browser text only when both ends of the selection belong to
+ * the clicked message's rendered Markdown content.
+ */
+function getMessageContent(
+ actionTarget: Element,
+ messageId: string
+): HTMLElement | undefined {
+ const messageRoot = actionTarget.closest<HTMLElement>('[data-message]');
+ if (!messageRoot || messageRoot.dataset.messageId !== messageId) {
+ return undefined;
+ }
+ return (
+ messageRoot.querySelector<HTMLElement>('[data-message-content]') ??
+ undefined
+ );
+}
+
+export function getSelectedMessageText(
+ actionTarget: Element,
+ messageId: string,
+ selection: Selection | null = window.getSelection()
+): string | undefined {
+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {
+ return undefined;
+ }
+
+ const content = getMessageContent(actionTarget, messageId);
+ const anchor = selection.anchorNode;
+ const focus = selection.focusNode;
+ if (!content || !anchor || !focus) return undefined;
+ if (!content.contains(anchor) || !content.contains(focus)) return undefined;
+
+ const text = selection.toString().trim();
+ return text || undefined;
+}
+
+/** Return decorator-provided, already-resolved text for a reply preview. */
+export function getRenderedMessageReplyText(
+ actionTarget: Element,
+ messageId: string
+): string | undefined {
+ const preview = getMessageContent(actionTarget, messageId)?.querySelector(
+ '[data-message-reply-preview]'
+ );
+ const explicitText = preview?.getAttribute('data-message-reply-preview');
+ const renderedText =
+ preview instanceof HTMLElement ? preview.innerText : undefined;
+ const text = (explicitText || renderedText || preview?.textContent)?.trim();
+ return text || undefined;
+}
diff --git a/apps/web/src/features/channel/Message/tests/action-menu.test.tsx b/apps/web/src/features/channel/Message/tests/action-menu.test.tsx
index cf3d294251..3187807c73 100644
--- a/apps/web/src/features/channel/Message/tests/action-menu.test.tsx
+++ b/apps/web/src/features/channel/Message/tests/action-menu.test.tsx
@@ -93,4 +93,58 @@ describe('ActionMenu', () => {
expect(container.querySelector('[data-message-hover-actions]')).toBeNull();
});
+
+ it('passes browser-selected message text to Reply', () => {
+ const onReply = vi.fn();
+ const { container } = render(() => (
+ <Root message={message} actions={{ onReply }}>
+ <div data-message-content>only this phrase should be quoted</div>
+ <ActionMenu />
+ </Root>
+ ));
+ const root = container.querySelector<HTMLElement>('[data-message]')!;
+ const content = container.querySelector<HTMLElement>(
+ '[data-message-content]'
+ )!;
+ const range = document.createRange();
+ range.setStart(content.firstChild!, 5);
+ range.setEnd(content.firstChild!, 16);
+ window.getSelection()?.removeAllRanges();
+ window.getSelection()?.addRange(range);
+
+ fireEvent.pointerEnter(root);
+ const reply = container.querySelector<HTMLButtonElement>(
+ '[data-message-action="reply"]'
+ )!;
+ fireEvent.pointerDown(reply);
+ fireEvent.click(reply);
+
+ expect(onReply).toHaveBeenCalledWith(
+ expect.objectContaining({ selectedText: 'this phrase' })
+ );
+ });
+
+ it('passes resolved decorator text to Reply', () => {
+ const onReply = vi.fn();
+ const { container } = render(() => (
+ <Root message={message} actions={{ onReply }}>
+ <div data-message-content>
+ <div data-message-reply-preview>Resolved bot response</div>
+ </div>
+ <ActionMenu />
+ </Root>
+ ));
+ const root = container.querySelector<HTMLElement>('[data-message]')!;
+
+ fireEvent.pointerEnter(root);
+ const reply = container.querySelector<HTMLButtonElement>(
+ '[data-message-action="reply"]'
+ )!;
+ fireEvent.pointerDown(reply);
+ fireEvent.click(reply);
+
+ expect(onReply).toHaveBeenCalledWith(
+ expect.objectContaining({ renderedText: 'Resolved bot response' })
+ );
+ });
});
diff --git a/apps/web/src/features/channel/Message/types.ts b/apps/web/src/features/channel/Message/types.ts
index 846df03eb2..1409760bd0 100644
--- a/apps/web/src/features/channel/Message/types.ts
+++ b/apps/web/src/features/channel/Message/types.ts
@@ -23,6 +23,10 @@ export type MessageActionContext = {
message: MessageData;
event?: MessageActionEvent;
emoji?: string;
+ /** Browser-selected text within this message at the time Reply was chosen. */
+ selectedText?: string;
+ /** Resolved text exposed by a dynamic decorator for use in reply previews. */
+ renderedText?: string;
};
export type MessageActionHandler = (
diff --git a/apps/web/src/features/channel/StandaloneThread/EditableThread.tsx b/apps/web/src/features/channel/StandaloneThread/EditableThread.tsx
index 2630c973f4..c902ce15bc 100644
--- a/apps/web/src/features/channel/StandaloneThread/EditableThread.tsx
+++ b/apps/web/src/features/channel/StandaloneThread/EditableThread.tsx
@@ -10,7 +10,7 @@ import { createChannelMessageActions } from '../Channel/create-channel-message-a
import { createDeleteMessageConfirmation } from '../Channel/create-delete-message-confirmation';
import type { InputHandle, InputSnapshot } from '../Input';
import { Thread } from '../Thread';
-import { buildQuoteReplyValue } from '../Thread/utils/message-actions';
+import { buildReplyTargetValue } from '../Thread/utils/message-actions';
import { channelReplyInputOffsetX } from '../Thread/utils/thread-rail-geometry';
import { useStandaloneThread } from './context';
import { StandaloneThread } from './StandaloneThread';
@@ -43,12 +43,15 @@ function EditableThreadInner() {
deleteMessage: deleteConfirmation.requestDelete,
addReaction: addReactionMutation.mutate,
removeReaction: removeReactionMutation.mutate,
- onReply: ({ message }) => {
+ onReply: ({ message, selectedText, renderedText }) => {
if (message.thread_id) {
const current = replyInputState();
const nextSnapshot: InputSnapshot = {
- value: buildQuoteReplyValue({
- quotedContent: message.content,
+ value: buildReplyTargetValue({
+ channelId: ctx.channelId(),
+ message,
+ selectedText,
+ renderedText,
existingValue: current?.value,
}),
mentions: current?.mentions ?? [],
diff --git a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
index fad6f5606f..e693b3b5e0 100644
--- a/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
+++ b/apps/web/src/features/channel/Thread/ThreadReplyList.tsx
@@ -33,7 +33,7 @@ export function ThreadReplyList(props: {
) => boolean;
selectedReplyId?: Accessor<string | undefined>;
/**
- * Reply targeted by channel navigation or bound to the unified input's reply (quote-reply).
+ * Reply targeted by channel navigation or referenced by the unified input.
*/
targetedReplyId?: Accessor<string | undefined>;
isThreadFocused?: Accessor<boolean>;
diff --git a/apps/web/src/features/channel/Thread/tests/message-actions.test.ts b/apps/web/src/features/channel/Thread/tests/message-actions.test.ts
index 607f89ef21..13b6448d77 100644
--- a/apps/web/src/features/channel/Thread/tests/message-actions.test.ts
+++ b/apps/web/src/features/channel/Thread/tests/message-actions.test.ts
@@ -2,7 +2,7 @@ import { URL_PARAMS } from '@channel/Channel/link';
import { describe, expect, it } from 'vitest';
import {
buildMessageLink,
- buildQuoteReplyValue,
+ buildReplyTargetValue,
canDeleteMessage,
canEditMessage,
canReplyToMessage,
@@ -60,30 +60,83 @@ describe('message-actions helpers', () => {
).toBe(false);
});
- it('builds quote reply markdown before existing draft text', () => {
+ const threadReply = {
+ id: 'reply-1',
+ content: 'first line\nsecond line',
+ sender_id: 'macro|[email protected]',
+ thread_id: 'thread-1',
+ };
+
+ it('builds a reply-target node before existing draft text', () => {
expect(
- buildQuoteReplyValue({
- quotedContent: 'first line\nsecond line',
+ buildReplyTargetValue({
+ channelId: 'channel-1',
+ message: threadReply,
existingValue: 'draft',
})
- ).toBe('> first line\n> second line\n\ndraft');
+ ).toBe(
+ '<m-reply-target>{"channelId":"channel-1","targetMessageId":"reply-1","targetThreadId":"thread-1","displayText":"first line second line","senderId":"macro|[email protected]"}</m-reply-target>\n\ndraft'
+ );
});
- it('does not insert a quote for empty quoted content', () => {
+ it('uses browser-selected text for the reply preview', () => {
expect(
- buildQuoteReplyValue({
- quotedContent: ' \n ',
- existingValue: 'draft',
+ buildReplyTargetValue({
+ channelId: 'channel-1',
+ message: threadReply,
+ selectedText: 'specific\nselection',
})
- ).toBe('draft');
+ ).toContain('"displayText":"specific selection"');
+ });
+
+ it('uses resolved decorator text for a bot reply preview', () => {
+ expect(
+ buildReplyTargetValue({
+ channelId: 'channel-1',
+ message: {
+ ...threadReply,
+ content:
+ '> original prompt\n\n<m-magic-chip>{"agentSessionId":"session-1","promptedMessage":{"turn":0,"author":"user"},"status":"booting"}</m-magic-chip>',
+ },
+ renderedText: 'The resolved bot response',
+ })
+ ).toContain('"displayText":"The resolved bot response"');
+ });
+
+ it('drops an unresolved magic chip from the fallback preview', () => {
+ expect(
+ buildReplyTargetValue({
+ channelId: 'channel-1',
+ message: {
+ ...threadReply,
+ content:
+ '> original prompt\n\n<m-magic-chip>{"agentSessionId":"session-1","promptedMessage":{"turn":0,"author":"user"},"status":"booting"}</m-magic-chip>',
+ },
+ })
+ ).toContain('"displayText":"> original prompt"');
});
- it('flattens existing quote markers instead of nesting blockquotes', () => {
+ it('ignores a leading reply-target block in the automatic preview', () => {
expect(
- buildQuoteReplyValue({
- quotedContent: '> first line\n>> second line',
+ buildReplyTargetValue({
+ channelId: 'channel-1',
+ message: {
+ ...threadReply,
+ content:
+ '<m-reply-target>{"channelId":"channel-1","targetMessageId":"earlier-reply","targetThreadId":"thread-1","displayText":"earlier preview","senderId":"macro|[email protected]"}</m-reply-target>\n\nmy response',
+ },
})
- ).toBe('> first line\n> second line\n\n ');
+ ).toContain('"displayText":"my response"');
+ });
+
+ it('does not add a reply-target node for a top-level message', () => {
+ expect(
+ buildReplyTargetValue({
+ channelId: 'channel-1',
+ message: { ...threadReply, thread_id: null },
+ existingValue: 'draft',
+ })
+ ).toBe('draft');
});
it('detects if user already reacted with the default emoji', () => {
diff --git a/apps/web/src/features/channel/Thread/utils/message-actions.ts b/apps/web/src/features/channel/Thread/utils/message-actions.ts
index 0e73b3c0a6..e2b174f574 100644
--- a/apps/web/src/features/channel/Thread/utils/message-actions.ts
+++ b/apps/web/src/features/channel/Thread/utils/message-actions.ts
@@ -1,6 +1,10 @@
import { getChannelParams } from '@channel/Channel/link';
import { buildSimpleEntityUrl } from '@core/util/url';
-import { quoteMarkdown } from '@macro-inc/lexical-core/utils/quote-markdown';
+import {
+ buildReplyTargetMarkdown,
+ markdownToPlainText,
+ stripLeadingReplyTargetMarkdown,
+} from '@macro-inc/lexical-core';
import type { MessageData } from '../../Message';
export const DEFAULT_REACTION_EMOJI = '👍';
@@ -51,18 +55,43 @@ export function canReplyToMessage(
return !message.deleted_at;
}
-export function buildQuoteReplyValue(input: {
- quotedContent: string;
+function oneLinePreview(text: string): string {
+ return text.trim().replace(/\s+/g, ' ');
+}
+
+function stripMagicChipMarkdown(markdown: string): string {
+ return markdown.replace(/<m-magic-chip>.*?<\/m-magic-chip>/gs, '');
+}
+
+export function buildReplyTargetValue(input: {
+ channelId: string;
+ message: Pick<MessageData, 'id' | 'content' | 'sender_id' | 'thread_id'>;
+ selectedText?: string;
+ renderedText?: string;
existingValue?: string;
}): string {
- const quote = quoteMarkdown(input.quotedContent);
- const existingValue = input.existingValue?.trimStart() ?? '';
+ if (!input.message.thread_id) return input.existingValue ?? '';
- if (!quote) return existingValue;
+ const messageText = markdownToPlainText(
+ stripMagicChipMarkdown(
+ stripLeadingReplyTargetMarkdown(input.message.content)
+ )
+ );
+ const displayText = oneLinePreview(
+ input.selectedText || input.renderedText || messageText
+ );
+ const replyTarget = buildReplyTargetMarkdown({
+ channelId: input.channelId,
+ targetMessageId: input.message.id,
+ targetThreadId: input.message.thread_id,
+ displayText,
+ senderId: input.message.sender_id,
+ });
+ const existingValue = input.existingValue?.trimStart() ?? '';
return existingValue
- ? `${quote}\n\n${existingValue}`
- : `${quote}\n\n${EMPTY_REPLY_PARAGRAPH}`;
+ ? `${replyTarget}\n\n${existingValue}`
+ : `${replyTarget}\n\n${EMPTY_REPLY_PARAGRAPH}`;
}
export function hasReactionFromUser(
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
index ac27769744..3cfa5bed51 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/builder/buildHandleFromConfig.ts
@@ -7,6 +7,7 @@ import {
actionsPlugin,
agentCommandsPlugin,
awaitPlugin,
+ blockDecoratorTrailingParagraphPlugin,
codePlugin,
createAccessoryStore,
createDraggableBlockStore,
@@ -127,6 +128,10 @@ export function buildHandleFromConfig(config: EditorConfig): EditorHandle {
.state<string>(setMarkdownState, 'markdown');
}
+ if (config.type !== 'plain-text' && !config.singleLine) {
+ plugins.use(blockDecoratorTrailingParagraphPlugin());
+ }
+
// History
if (config.history) {
plugins.history(config.history.timeGap);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
index 782e682aec..4d0c63d24b 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/MarkdownTextarea.tsx
@@ -33,6 +33,7 @@ import {
type AutoLinkMatchMode,
autoRegister,
awaitPlugin,
+ blockDecoratorTrailingParagraphPlugin,
codePlugin,
createAccessoryStore,
customSelectionDataPlugin,
@@ -213,6 +214,7 @@ export function MarkdownTextarea(props: MarkdownTextareaProps) {
.delete()
.state<string>(setMarkdownState, 'markdown')
.history(400)
+ .use(blockDecoratorTrailingParagraphPlugin())
.use(restoreFocusPlugin())
.use(checkboxToTaskPlugin())
.use(mediaPlugin())
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
index 03a651e4e5..17b450db70 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/core/StaticMarkdown.tsx
@@ -27,6 +27,7 @@ import {
type MagicChipNode,
normalizedLanguage,
type PasteNode,
+ type ReplyTargetNode,
type SnapshotNode,
SupportedNodeTypes,
type TagMentionNode,
@@ -88,6 +89,7 @@ import { MagicChip as MagicChipDecorator } from '../decorator/MagicChip';
import { MarkdownImage as ImageDecorator } from '../decorator/MarkdownImage';
import { MarkdownVideo as VideoDecorator } from '../decorator/MarkdownVideo';
import { PasteNode as PasteNodeDecorator } from '../decorator/PasteNode';
+import { ReplyTarget as ReplyTargetDecorator } from '../decorator/ReplyTarget';
import { Snapshot as SnapshotDecorator } from '../decorator/Snapshot';
import { TagMention as TagMentionDecorator } from '../decorator/TagMention';
import { ThemeMention as ThemeMentionDecorator } from '../decorator/ThemeMention';
@@ -508,6 +510,25 @@ const AgentContext: TypedRenderableEntity<AgentContextNode> = {
),
};
+const ReplyTarget: TypedRenderableEntity<ReplyTargetNode> = {
+ guard: (node: LexicalNode): node is ReplyTargetNode =>
+ node.__type === 'reply-target',
+ render: (props) => (
+ // `data-reply-target-node` mirrors the editor block wrapper so the shared
+ // spacing rule applies in static markdown too.
+ <div
+ class="max-w-full"
+ data-reply-target-node={props.node.__targetMessageId}
+ >
+ <ReplyTargetDecorator
+ {...props.node.exportComponentProps()}
+ key={props.node.getKey()}
+ theme={props.theme}
+ />
+ </div>
+ ),
+};
+
const MagicChip: TypedRenderableEntity<MagicChipNode> = {
guard: (node: LexicalNode): node is MagicChipNode =>
node.__type === 'magic-chip',
@@ -873,6 +894,7 @@ const InlineEntities: RenderableEntity[] = [
eraseRenderableEntity(GroupMention),
eraseRenderableEntity(Await),
eraseRenderableEntity(AgentContext),
+ eraseRenderableEntity(ReplyTarget),
eraseRenderableEntity(MagicChip),
eraseRenderableEntity(Snapshot),
eraseRenderableEntity(Image),
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
index 436030918b..8da1a288c7 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/MagicChipView.tsx
@@ -28,6 +28,9 @@ const ActivityLine: Component<{
type="button"
class="flex h-6 w-full min-w-0 items-center gap-2 text-left"
data-magic-chip={props.agentSessionId}
+ data-message-reply-preview={`${props.activity.label}${
+ props.activity.detail ? ` ${props.activity.detail}` : ''
+ }`}
disabled={!props.onOpen}
onMouseDown={(event) => event.preventDefault()}
onClick={props.onOpen}
@@ -54,7 +57,10 @@ const ActivityLine: Component<{
/** The response, quoted as if the agent had answered inline. */
const AnswerBody: Component<{ markdown: string }> = (props) => (
- <div class="w-full border-l-2 border-accent pl-3 text-left text-sm leading-6">
+ <div
+ class="w-full border-l-2 border-accent pl-3 text-left text-sm leading-6"
+ data-message-reply-preview
+ >
<StaticMarkdownContext theme={channelTheme}>
<StaticMarkdown markdown={props.markdown} target="external" />
</StaticMarkdownContext>
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsx
new file mode 100644
index 0000000000..7826a5b76b
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ReplyTarget.tsx
@@ -0,0 +1,69 @@
+import { URL_PARAMS as CHANNEL_PARAMS } from '@block-channel/constants';
+import { StaticMarkdown } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';
+import { singleLineMarkdownTheme } from '@core/component/LexicalMarkdown/theme';
+import { getDisplayName, tryMacroId } from '@core/user';
+import { openInNewSplitForMention } from '@core/util/openInNewSplit';
+import type { ReplyTargetDecoratorProps } from '@macro-inc/lexical-core';
+import { useChannelBotsQuery } from '@queries/channel/channel-bots';
+import { getBotDisplayName } from '@queries/channel/message-sender';
+import { createCallback } from '@solid-primitives/rootless';
+import { openDocument } from '../core/BlockLink';
+
+/** Single-line channel reply reference rendered by a ReplyTargetNode. */
+export function ReplyTarget(props: ReplyTargetDecoratorProps) {
+ const channelBots = useChannelBotsQuery(() => props.channelId);
+ const senderName = () =>
+ getBotDisplayName(props.senderId, undefined, channelBots.data) ||
+ getDisplayName(tryMacroId(props.senderId), {}) ||
+ props.senderId;
+
+ const openTarget = createCallback((event: MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ openDocument(
+ 'channel',
+ props.channelId,
+ {
+ [CHANNEL_PARAMS.message]: props.targetMessageId,
+ [CHANNEL_PARAMS.thread]: props.targetThreadId,
+ },
+ openInNewSplitForMention(event.shiftKey, true)
+ );
+ });
+
+ return (
+ <button
+ type="button"
+ class="group/reply-target flex w-full min-w-0 items-center gap-1 py-1 text-left text-xs text-ink-muted rounded-md hover:bg-hover"
+ aria-label={`Replying to ${senderName()}: ${props.displayText}`}
+ data-reply-target-target-message-id={props.targetMessageId}
+ on:mousedown={(event) => event.preventDefault()}
+ on:click={openTarget}
+ >
+ <svg
+ viewBox="0 0 20 21.333"
+ class="ml-1 h-[1.333rem] w-5 shrink-0 overflow-visible text-edge transition-opacity group-hover/reply-target:opacity-0"
+ fill="none"
+ aria-hidden="true"
+ >
+ <path
+ d="M20 10.667H8a8 5.333 0 0 0-8 5.333v5.333"
+ stroke="currentColor"
+ stroke-width="2"
+ vector-effect="non-scaling-stroke"
+ />
+ </svg>
+ <span class="shrink-0 font-semibold text-ink-disabled transition-colors group-hover/reply-target:text-ink-subtle">
+ {senderName()}
+ </span>
+ <div class="min-w-0 flex-1 overflow-hidden italic text-ink-subtle transition-colors group-hover/reply-target:text-ink-muted">
+ <StaticMarkdown
+ markdown={props.displayText}
+ theme={singleLineMarkdownTheme}
+ target="internal"
+ singleLine
+ />
+ </div>
+ </button>
+ );
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
index f522d1c69a..061e907e4c 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/init.ts
@@ -14,6 +14,7 @@ import {
MagicChipNode,
PasteNode as PasteNodeClass,
PullRequestMentionNode,
+ ReplyTargetNode,
SnapshotNode,
TagMentionNode,
ThemeMentionNode,
@@ -42,6 +43,7 @@ import { MarkdownImage } from './component/decorator/MarkdownImage';
import { MarkdownVideo } from './component/decorator/MarkdownVideo';
import { PasteNode } from './component/decorator/PasteNode';
import { PullRequestMention } from './component/decorator/PullRequestMention';
+import { ReplyTarget } from './component/decorator/ReplyTarget';
import { Snapshot } from './component/decorator/Snapshot';
import { TagMention } from './component/decorator/TagMention';
import { ThemeMention } from './component/decorator/ThemeMention';
@@ -63,6 +65,7 @@ export function initializeLexical() {
setDecorator(DocumentCardNode, DocumentCard);
setDecorator(PasteNodeClass, PasteNode);
setDecorator(PullRequestMentionNode, PullRequestMention);
+ setDecorator(ReplyTargetNode, ReplyTarget);
setDecorator(ContactMentionNode, ContactMention);
setDecorator(DateMentionNode, DateMention);
setDecorator(DiffInsertNode, DiffInsert);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/blockDecoratorTrailingParagraphPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/blockDecoratorTrailingParagraphPlugin.test.ts
new file mode 100644
index 0000000000..34d5bf4b5e
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/blockDecoratorTrailingParagraphPlugin.test.ts
@@ -0,0 +1,106 @@
+/**
+ * @vitest-environment jsdom
+ */
+
+import {
+ $createReplyTargetNode,
+ ReplyTargetNode,
+} from '@macro-inc/lexical-core';
+import {
+ $createParagraphNode,
+ $getRoot,
+ $isParagraphNode,
+ createEditor,
+} from 'lexical';
+import { describe, expect, it } from 'vitest';
+import { blockDecoratorTrailingParagraphPlugin } from './blockDecoratorTrailingParagraphPlugin';
+
+const quoteReplyData = {
+ channelId: 'channel-1',
+ targetMessageId: 'message-1',
+ targetThreadId: 'thread-1',
+ displayText: 'Reply preview',
+ senderId: 'sender-1',
+};
+
+function createTestEditor() {
+ const editor = createEditor({
+ namespace: 'block-decorator-trailing-paragraph-test',
+ nodes: [ReplyTargetNode],
+ onError: (error) => {
+ throw error;
+ },
+ });
+ const cleanup = blockDecoratorTrailingParagraphPlugin()(editor);
+ return { editor, cleanup };
+}
+
+describe('blockDecoratorTrailingParagraphPlugin', () => {
+ it('adds a paragraph after a trailing block decorator', () => {
+ const { editor, cleanup } = createTestEditor();
+
+ editor.update(
+ () => {
+ $getRoot().append($createReplyTargetNode(quoteReplyData));
+ },
+ { discrete: true }
+ );
+
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(2);
+ expect(children[0]).toBeInstanceOf(ReplyTargetNode);
+ expect($isParagraphNode(children[1])).toBe(true);
+ });
+
+ cleanup();
+ });
+
+ it('recreates the caret target when its paragraph is deleted', () => {
+ const { editor, cleanup } = createTestEditor();
+
+ editor.update(
+ () => {
+ $getRoot().append(
+ $createReplyTargetNode(quoteReplyData),
+ $createParagraphNode()
+ );
+ },
+ { discrete: true }
+ );
+ editor.update(
+ () => {
+ $getRoot().getLastChild()?.remove();
+ },
+ { discrete: true }
+ );
+
+ editor.read(() => {
+ const children = $getRoot().getChildren();
+ expect(children).toHaveLength(2);
+ expect($isParagraphNode(children[1])).toBe(true);
+ });
+
+ cleanup();
+ });
+
+ it('does not add another paragraph when one already trails the decorator', () => {
+ const { editor, cleanup } = createTestEditor();
+
+ editor.update(
+ () => {
+ $getRoot().append(
+ $createReplyTargetNode(quoteReplyData),
+ $createParagraphNode()
+ );
+ },
+ { discrete: true }
+ );
+
+ editor.read(() => {
+ expect($getRoot().getChildren()).toHaveLength(2);
+ });
+
+ cleanup();
+ });
+});
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/blockDecoratorTrailingParagraphPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/blockDecoratorTrailingParagraphPlugin.ts
new file mode 100644
index 0000000000..af063cacff
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/blockDecoratorTrailingParagraphPlugin.ts
@@ -0,0 +1,19 @@
+import {
+ $createParagraphNode,
+ $isDecoratorNode,
+ type LexicalEditor,
+ RootNode,
+} from 'lexical';
+
+/**
+ * Keep an editable caret target after a block decorator at the end of the
+ * document. Inline decorators do not need a separate paragraph.
+ */
+export function blockDecoratorTrailingParagraphPlugin() {
+ return (editor: LexicalEditor) =>
+ editor.registerNodeTransform(RootNode, (root) => {
+ const lastChild = root.getLastChild();
+ if (!$isDecoratorNode(lastChild) || lastChild.isInline()) return;
+ root.append($createParagraphNode());
+ });
+}
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/index.ts
new file mode 100644
index 0000000000..58c4f4abf2
--- /dev/null
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/block-decorator-trailing-paragraph/index.ts
@@ -0,0 +1 @@
+export * from './blockDecoratorTrailingParagraphPlugin';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts
index dbe53e501c..1d3a4c2a26 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/index.ts
@@ -2,6 +2,7 @@ export * from './actions';
export * from './agent-commands';
export * from './await';
export * from './blame-tooltip';
+export * from './block-decorator-trailing-paragraph';
export * from './checklist';
export * from './code';
export * from './comments';
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
index 646da0e379..2b913b2086 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/styles.css
@@ -533,6 +533,18 @@ in a cell — move the indent inside the box so markers stay visible.
margin-top: -1rem;
}
+/*
+A ReplyTarget preview acts as a header for the message body that follows it, so
+pull the next block up close. This only shrinks the *following* block's top
+margin, leaving the reply target's own margins untouched -- so spacing against
+the container (and when the reply target is the last block) stays exactly as it
+would naturally be.
+Scoped under .md to outrank the block's Tailwind `mt-4`.
+*/
+.md [data-reply-target-node] + * {
+ margin-top: 0.375rem;
+}
+
mark {
color: currentColor;
background-color: unset;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
index afa1990026..d4fb6f1a78 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
@@ -17,5 +17,6 @@
* Version 2.4 - Aug 2026. MagicChipNode: block response surface, channelId optional for standalone sessions.
* Version 2.5 - Aug 2026. Added expandable AgentContextNode.
* Version 2.6 - Aug 2026. PasteNode origin: pasted (default) or referenced.
+ * Version 3.0 - Sep 2026. Added ReplyTargetNode.
*/
-export const MARKDOWN_VERSION_COUNTER = 2.6;
+export const MARKDOWN_VERSION_COUNTER = 3.0;
diff --git a/apps/web/src/lib/queries/channel/message-sender.ts b/apps/web/src/lib/queries/channel/message-sender.ts
index bdd8e75701..22440dcd59 100644
--- a/apps/web/src/lib/queries/channel/message-sender.ts
+++ b/apps/web/src/lib/queries/channel/message-sender.ts
@@ -1,9 +1,14 @@
+import { CURSOR_BOT_NAME, isCursorBotId } from '@core/constant/cursorAgent';
+import { isMacroAgentId, MACRO_AGENT_NAME } from '@core/constant/macroAgent';
+import { isMacroCoderId, MACRO_CODER_NAME } from '@core/constant/macroCoder';
+import { isMacroNewId, MACRO_NEW_NAME } from '@core/constant/macroNew';
import type {
ApiChannelMessage,
ApiThreadReply,
ChannelMessagesPage,
} from '@service-storage/client';
import type { ApiMessageSender } from '@service-storage/generated/schemas/apiMessageSender';
+import type { Bot } from '@service-storage/generated/schemas/bot';
type WithMaybeSender<
T extends { sender_id: string; sender: ApiMessageSender },
@@ -30,6 +35,34 @@ export function senderFromStorageId(senderId: string): ApiMessageSender {
return { type: 'user', id: senderId };
}
+function systemBotDisplayName(id: string): string | undefined {
+ if (isMacroAgentId(id)) return MACRO_AGENT_NAME;
+ if (isMacroCoderId(id)) return MACRO_CODER_NAME;
+ if (isMacroNewId(id)) return MACRO_NEW_NAME;
+ if (isCursorBotId(id)) return CURSOR_BOT_NAME;
+ return undefined;
+}
+
+/** Resolve a channel bot sender to its display name. */
+export function getBotDisplayName(
+ senderId: string,
+ sender?: ApiMessageSender,
+ bots: readonly Pick<Bot, 'id' | 'name'>[] = []
+): string | undefined {
+ const parsed = sender ?? senderFromStorageId(senderId);
+ const systemName =
+ systemBotDisplayName(parsed.id) ?? systemBotDisplayName(senderId);
+
+ if (parsed.type !== 'bot' && !systemName) return undefined;
+
+ return (
+ parsed.name ??
+ systemName ??
+ bots.find((bot) => bot.id === parsed.id)?.name ??
+ 'Bot'
+ );
+}
+
export function isBotSenderId(senderId: string): boolean {
return senderFromStorageId(senderId).type === 'bot';
}
diff --git a/apps/web/src/lib/queries/channel/tests/message-sender.test.ts b/apps/web/src/lib/queries/channel/tests/message-sender.test.ts
index 1dd462bb8d..2d34ebdde6 100644
--- a/apps/web/src/lib/queries/channel/tests/message-sender.test.ts
+++ b/apps/web/src/lib/queries/channel/tests/message-sender.test.ts
@@ -1,6 +1,11 @@
+import {
+ MACRO_CODER_NAME,
+ MACRO_CODER_PRINCIPAL_ID,
+} from '@core/constant/macroCoder';
import { describe, expect, it } from 'vitest';
import {
type ChannelMessageWithMaybeSender,
+ getBotDisplayName,
normalizeChannelMessageSender,
senderFromStorageId,
} from '../message-sender';
@@ -81,4 +86,25 @@ describe('message sender normalization', () => {
avatar_url: 'https://example.com/bot.png',
});
});
+
+ it('resolves bot names from channel bot data', () => {
+ expect(
+ getBotDisplayName('bot|00000000-0000-0000-0000-000000000001', undefined, [
+ {
+ id: '00000000-0000-0000-0000-000000000001',
+ name: 'Deploy Bot',
+ },
+ ])
+ ).toBe('Deploy Bot');
+ });
+
+ it('resolves built-in agent names without channel bot data', () => {
+ expect(getBotDisplayName(MACRO_CODER_PRINCIPAL_ID)).toBe(MACRO_CODER_NAME);
+ });
+
+ it('uses a generic label rather than exposing an unknown bot UUID', () => {
+ expect(getBotDisplayName('bot|00000000-0000-0000-0000-000000000002')).toBe(
+ 'Bot'
+ );
+ });
});
diff --git a/crates/agent_harness/src/domain/model.rs b/crates/agent_harness/src/domain/model.rs
index 54db102f1e..b5e1ba289d 100644
--- a/crates/agent_harness/src/domain/model.rs
+++ b/crates/agent_harness/src/domain/model.rs
@@ -235,7 +235,7 @@ pub struct AnnouncePrompt {
pub bot_id: BotId,
/// Where the mention was posted.
pub origin: AnnounceOrigin,
- /// The mention's text, quoted in the announcement.
+ /// The mention's text, shown in the announcement's reply target.
pub content: String,
/// Who mentioned the bot.
pub sender: MacroUserIdStr<'static>,
@@ -252,9 +252,11 @@ pub struct SessionAnnouncement {
pub origin_channel_id: Uuid,
/// Thread where the announcement should be posted.
pub origin_thread_id: Uuid,
+ /// Channel message targeted by the announcement.
+ pub origin_message_id: Uuid,
/// Folded user message that prompts the anchored agent response.
pub prompted_message_id: MessageId,
- /// Text of the prompting message, quoted back in the announcement.
+ /// Text of the prompting message, shown in the reply target.
pub prompted_content: String,
/// User whose mention triggered the announcement.
pub triggered_by: MacroUserIdStr<'static>,
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index 6b5627bffb..6925106e0f 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -287,6 +287,7 @@ where
bot_id: session.bot_id,
origin_channel_id: prompt.origin.channel_id,
origin_thread_id: prompt.origin.thread_id,
+ origin_message_id: prompt.origin.message_id,
prompted_message_id: self
.inner
.sessions
@@ -474,6 +475,7 @@ where
bot_id: request.bot_id,
origin_channel_id: thread.channel_id,
origin_thread_id: thread.thread_id,
+ origin_message_id: thread.message_id,
prompted_message_id: MessageId::first(AuthorKind::User),
prompted_content: thread.content,
triggered_by: request.owner,
@@ -899,6 +901,7 @@ where
bot_id,
origin_channel_id: origin.channel_id,
origin_thread_id: origin.thread_id,
+ origin_message_id: origin.message_id,
prompted_message_id: MessageId::first(AuthorKind::User),
prompted_content: origin.content.clone(),
triggered_by: origin.sender.clone(),
@@ -1103,6 +1106,7 @@ where
bot_id: session.bot_id,
origin_channel_id: origin.channel_id,
origin_thread_id: origin.thread_id,
+ origin_message_id: origin.message_id,
prompted_message_id: self.sessions.next_prompt_message_id(session_id).await?,
prompted_content: prompt.prompt.clone(),
triggered_by: triggered_by.clone(),
diff --git a/crates/agent_harness/src/outbound/channel_announcer.rs b/crates/agent_harness/src/outbound/channel_announcer.rs
index 43c82a29cd..c54160d117 100644
--- a/crates/agent_harness/src/outbound/channel_announcer.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer.rs
@@ -6,10 +6,10 @@
//! through the channel API. The composition root decides which
//! `ChannelService` implementation (and side-effect stack) this wraps.
//!
-//! The announcement quotes the prompting message above the session's magic
-//! chip. The content is composed by the lexical service — the one place that
-//! builds message markdown from real Lexical nodes — so this adapter never
-//! formats markdown itself.
+//! The announcement places a structured reply target above the session's
+//! magic chip. The content is composed by the lexical service — the one place
+//! that builds message markdown from real Lexical nodes — so this adapter
+//! never formats markdown itself.
#[cfg(test)]
mod test;
@@ -20,7 +20,7 @@ use channel_sender::ChannelSender;
use channels::domain::models::{PostMessageNotificationPolicy, PostMessageRequest};
use channels::domain::ports::ChannelService;
use lexical_client::LexicalClient;
-use lexical_client::parse_markdown::AgentAnnouncementChip;
+use lexical_client::parse_markdown::{AgentAnnouncementChip, AgentAnnouncementReplyTarget};
use crate::domain::error::{HarnessError, Result};
use crate::domain::model::SessionAnnouncement;
@@ -35,6 +35,16 @@ fn announcement_chip(announcement: &SessionAnnouncement) -> AgentAnnouncementChi
}
}
+fn announcement_reply_target(announcement: &SessionAnnouncement) -> AgentAnnouncementReplyTarget {
+ AgentAnnouncementReplyTarget {
+ channel_id: announcement.origin_channel_id.to_string(),
+ target_message_id: announcement.origin_message_id.to_string(),
+ target_thread_id: announcement.origin_thread_id.to_string(),
+ display_text: announcement.prompted_content.clone(),
+ sender_id: announcement.triggered_by.as_ref().to_owned(),
+ }
+}
+
/// Posts session announcements as their session's bot through a
/// [`ChannelService`].
pub struct ChannelAnnouncer<Channels> {
@@ -55,10 +65,11 @@ where
Channels: ChannelService + Send + Sync + 'static,
{
async fn announce(&self, announcement: SessionAnnouncement) -> Result<()> {
+ let reply_target = announcement_reply_target(&announcement);
let chip = announcement_chip(&announcement);
let content = self
.lexical
- .compose_agent_announcement(&announcement.prompted_content, &chip)
+ .compose_agent_announcement(&reply_target, &chip)
.await
.map_err(|error| HarnessError::Announce(rootcause::report!(error).into()))?;
diff --git a/crates/agent_harness/src/outbound/channel_announcer/test.rs b/crates/agent_harness/src/outbound/channel_announcer/test.rs
index 7ef95c2b68..f135e2ee06 100644
--- a/crates/agent_harness/src/outbound/channel_announcer/test.rs
+++ b/crates/agent_harness/src/outbound/channel_announcer/test.rs
@@ -4,19 +4,24 @@ use macro_uuid::Uuid;
use super::*;
use bot_id::BotId;
-#[test]
-fn chip_carries_the_announcement_identity() {
- let announcement = SessionAnnouncement {
+fn announcement() -> SessionAnnouncement {
+ SessionAnnouncement {
bot_id: BotId::TEST_A,
session_id: agent_session::domain::model::AgentSessionId::TEST_A,
origin_channel_id: Uuid::from_u128(1),
origin_thread_id: Uuid::from_u128(2),
+ origin_message_id: Uuid::from_u128(3),
prompted_message_id: agent_session::domain::model::MessageId::first(
agent_session::domain::model::AuthorKind::User,
),
prompted_content: "@claude fix the failing test".to_owned(),
triggered_by: MacroUserIdStr::try_from_email("[email protected]").unwrap(),
- };
+ }
+}
+
+#[test]
+fn chip_carries_the_announcement_identity() {
+ let announcement = announcement();
assert_eq!(
announcement_chip(&announcement),
@@ -30,3 +35,17 @@ fn chip_carries_the_announcement_identity() {
}
);
}
+
+#[test]
+fn reply_target_carries_the_originating_channel_message() {
+ assert_eq!(
+ announcement_reply_target(&announcement()),
+ AgentAnnouncementReplyTarget {
+ channel_id: "00000000-0000-0000-0000-000000000001".to_owned(),
+ target_message_id: "00000000-0000-0000-0000-000000000003".to_owned(),
+ target_thread_id: "00000000-0000-0000-0000-000000000002".to_owned(),
+ display_text: "@claude fix the failing test".to_owned(),
+ sender_id: "macro|[email protected]".to_owned(),
+ }
+ );
+}
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index c7fab61dae..86a4fe38de 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -16,9 +16,9 @@ mod test;
pub enum ChannelKind {
/// The thread the session was created from, where the bot was pinged.
MentionThread,
- /// The session's thread, where the message quote-replied without a
- /// mention.
- QuoteReply,
+ /// The session's thread, where the message explicitly targeted another
+ /// message without a mention.
+ ExplicitReply,
/// The session's thread, where a model inferred the message was addressed
/// to the agent.
Inferred,
diff --git a/crates/agent_trigger/src/domain/broker_events/test.rs b/crates/agent_trigger/src/domain/broker_events/test.rs
index 2a319e827d..f3f04d86fc 100644
--- a/crates/agent_trigger/src/domain/broker_events/test.rs
+++ b/crates/agent_trigger/src/domain/broker_events/test.rs
@@ -100,7 +100,7 @@ fn event_names_match_the_wire() {
fn channel_kinds_round_trip_in_snake_case() {
for (kind, wire) in [
(ChannelKind::MentionThread, "mention_thread"),
- (ChannelKind::QuoteReply, "quote_reply"),
+ (ChannelKind::ExplicitReply, "explicit_reply"),
(ChannelKind::Inferred, "inferred"),
] {
let value = serde_json::to_value(kind).expect("serialize kind");
diff --git a/crates/agent_trigger/src/domain/processing.rs b/crates/agent_trigger/src/domain/processing.rs
index 64c9c2a12b..970d7851c5 100644
--- a/crates/agent_trigger/src/domain/processing.rs
+++ b/crates/agent_trigger/src/domain/processing.rs
@@ -7,8 +7,8 @@ use macro_event_broker::{EventBrokerError, MacroEvent as _, MacroEventBroker};
use super::broker_events::AgentTriggerEventName;
use super::service::{
- AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ImplicitTriggerJudge,
- ReplyDetector, TeamMembershipLookup, ThreadHistory,
+ AgentBotLookup, AgentTriggerService, ChannelParticipationLookup, ExplicitReplyDetector,
+ ImplicitTriggerJudge, TeamMembershipLookup, ThreadHistory,
};
/// Failure while evaluating or publishing one channel event.
@@ -39,7 +39,7 @@ where
Bots: AgentBotLookup,
Teams: TeamMembershipLookup,
Channels: ChannelParticipationLookup,
- Replies: ReplyDetector,
+ Replies: ExplicitReplyDetector,
Judge: ImplicitTriggerJudge,
History: ThreadHistory,
Broker: MacroEventBroker,
diff --git a/crates/agent_trigger/src/domain/service.rs b/crates/agent_trigger/src/domain/service.rs
index eb723c53eb..5166d538a6 100644
--- a/crates/agent_trigger/src/domain/service.rs
+++ b/crates/agent_trigger/src/domain/service.rs
@@ -71,13 +71,12 @@ pub trait ChannelParticipationLookup: Send + Sync + 'static {
) -> impl Future<Output = Result<bool>> + Send;
}
-/// Detects whether a message is composed as a quote-reply - a leading
-/// blockquote followed by the reply itself, the shape the editor produces
-/// when replying to a message.
+/// Detects whether a message is composed as an explicit reply: a leading
+/// reply target followed by the author's response.
#[cfg_attr(test, mockall::automock)]
-pub trait ReplyDetector: Send + Sync + 'static {
- /// Whether this markdown is a quote-reply.
- fn is_quote_reply(&self, markdown: &str) -> impl Future<Output = Result<bool>> + Send;
+pub trait ExplicitReplyDetector: Send + Sync + 'static {
+ /// Whether this markdown is an explicit reply.
+ fn is_explicit_reply(&self, markdown: &str) -> impl Future<Output = Result<bool>> + Send;
}
/// Reads whole threads, so an unmentioned message can be judged against the
@@ -124,7 +123,7 @@ where
Bots: AgentBotLookup,
Teams: TeamMembershipLookup,
Channels: ChannelParticipationLookup,
- Replies: ReplyDetector,
+ Replies: ExplicitReplyDetector,
Judge: ImplicitTriggerJudge,
History: ThreadHistory,
{
@@ -307,7 +306,7 @@ where
}
/// Evaluates an unmentioned message against the sessions rooted at its
- /// thread: a quote-reply is forwarded outright, anything else only when
+ /// thread: an explicit reply is forwarded outright, anything else only when
/// the judge reads it as addressed to the agent.
///
/// Only fires when exactly one agent is live in the thread; picking among
@@ -349,10 +348,10 @@ where
}
};
- let kind = if self.is_quote_reply(posted).await {
- // A quote-reply says who it answers on its face, so it needs no
+ let kind = if self.is_explicit_reply(posted).await {
+ // An explicit reply says who it answers on its face, so it needs no
// thread read at all.
- ChannelKind::QuoteReply
+ ChannelKind::ExplicitReply
} else if self
.is_addressed_to_agent(posted, &self.transcript(posted, thread_id, &session).await)
.await
@@ -379,12 +378,12 @@ where
)))
}
- async fn is_quote_reply(&self, posted: &ChannelMessagePostedMetadata) -> bool {
+ async fn is_explicit_reply(&self, posted: &ChannelMessagePostedMetadata) -> bool {
self.replies
- .is_quote_reply(&posted.content)
+ .is_explicit_reply(&posted.content)
.await
.inspect_err(|error| {
- tracing::warn!(error = ?error, "quote-reply detection failed; treating as not a reply");
+ tracing::warn!(error = ?error, "explicit reply detection failed; treating as not a reply");
})
.unwrap_or(false)
}
diff --git a/crates/agent_trigger/src/domain/service/test.rs b/crates/agent_trigger/src/domain/service/test.rs
index 760143e6da..93cab619c6 100644
--- a/crates/agent_trigger/src/domain/service/test.rs
+++ b/crates/agent_trigger/src/domain/service/test.rs
@@ -137,7 +137,7 @@ type TestService = AgentTriggerService<
MockAgentBotLookup,
MockTeamMembershipLookup,
MockChannelParticipationLookup,
- MockReplyDetector,
+ MockExplicitReplyDetector,
MockImplicitTriggerJudge,
MockThreadHistory,
>;
@@ -165,7 +165,7 @@ impl From<MockAgentBotLookup> for FactMocks {
fn service(
sessions: MockAgentSessionRepo,
facts: impl Into<FactMocks>,
- replies: MockReplyDetector,
+ replies: MockExplicitReplyDetector,
judge: MockImplicitTriggerJudge,
) -> TestService {
service_reading(sessions, facts, replies, judge, thread_of(vec![]))
@@ -174,7 +174,7 @@ fn service(
fn service_reading(
sessions: MockAgentSessionRepo,
facts: impl Into<FactMocks>,
- replies: MockReplyDetector,
+ replies: MockExplicitReplyDetector,
judge: MockImplicitTriggerJudge,
history: MockThreadHistory,
) -> TestService {
@@ -202,8 +202,11 @@ fn thread_of(messages: Vec<ThreadMessage>) -> MockThreadHistory {
/// Mocks for tests whose message never reaches the implicit path; any call is
/// a test failure.
-fn no_implicit() -> (MockReplyDetector, MockImplicitTriggerJudge) {
- (MockReplyDetector::new(), MockImplicitTriggerJudge::new())
+fn no_implicit() -> (MockExplicitReplyDetector, MockImplicitTriggerJudge) {
+ (
+ MockExplicitReplyDetector::new(),
+ MockImplicitTriggerJudge::new(),
+ )
}
fn existing_channel_metadata(
@@ -579,10 +582,10 @@ fn agent_bots() -> MockAgentBotLookup {
bots
}
-fn detector(result: Result<bool>) -> MockReplyDetector {
- let mut replies = MockReplyDetector::new();
+fn detector(result: Result<bool>) -> MockExplicitReplyDetector {
+ let mut replies = MockExplicitReplyDetector::new();
replies
- .expect_is_quote_reply()
+ .expect_is_explicit_reply()
.once()
.return_once(move |_| Box::pin(async move { result }));
replies
@@ -620,7 +623,7 @@ fn thread_message(id: u128, sender: ChannelSender<'static>, content: &str) -> Th
}
#[tokio::test]
-async fn a_quote_reply_in_a_session_thread_triggers_without_a_mention() {
+async fn an_explicit_reply_in_a_session_thread_triggers_without_a_mention() {
let posted = message(vec![]);
let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
let service = service(
@@ -634,7 +637,7 @@ async fn a_quote_reply_in_a_session_thread_triggers_without_a_mention() {
let metadata = existing_channel_metadata(&events);
assert_eq!(metadata.session_id, AgentSessionId::TEST_A);
assert_eq!(metadata.bot_id, BotId::TEST_A);
- assert_eq!(metadata.kind, ChannelKind::QuoteReply);
+ assert_eq!(metadata.kind, ChannelKind::ExplicitReply);
}
#[tokio::test]
@@ -835,7 +838,7 @@ async fn the_judge_reads_the_thread_around_the_agent() {
}
#[tokio::test]
-async fn a_quote_reply_never_reads_the_thread() {
+async fn an_explicit_reply_never_reads_the_thread() {
let posted = message(vec![]);
let sessions = implicit_sessions(vec![thread_session(AgentSessionId::TEST_A, BotId::TEST_A)]);
let mut history = MockThreadHistory::new();
@@ -851,7 +854,7 @@ async fn a_quote_reply_never_reads_the_thread() {
let events = service.evaluate(&posted).await.expect("evaluate message");
assert_eq!(
existing_channel_metadata(&events).kind,
- ChannelKind::QuoteReply
+ ChannelKind::ExplicitReply
);
}
diff --git a/crates/agent_trigger/src/domain/yield_event.rs b/crates/agent_trigger/src/domain/yield_event.rs
index 6cb1473b5e..d401e688cb 100644
--- a/crates/agent_trigger/src/domain/yield_event.rs
+++ b/crates/agent_trigger/src/domain/yield_event.rs
@@ -40,7 +40,7 @@ pub enum NoEventReason {
session_id: AgentSessionId,
},
/// The message sat in a session's thread without a mention, and neither
- /// quote-reply detection nor the model judged it addressed to the agent.
+ /// explicit reply detection nor the model judged it addressed to the agent.
NotAddressedToAgent {
/// Session whose thread carried the message.
session_id: AgentSessionId,
diff --git a/crates/agent_trigger/src/outbound/lexical_explicit_reply_detector.rs b/crates/agent_trigger/src/outbound/lexical_explicit_reply_detector.rs
new file mode 100644
index 0000000000..ae4c81bf88
--- /dev/null
+++ b/crates/agent_trigger/src/outbound/lexical_explicit_reply_detector.rs
@@ -0,0 +1,25 @@
+//! Explicit-reply detection backed by the lexical service.
+
+use agent_session::domain::error::Result;
+use lexical_client::LexicalClient;
+
+use crate::domain::service::ExplicitReplyDetector;
+
+/// Detects explicit replies by parsing the markdown with the lexical service,
+/// so detection matches the `ReplyTargetNode` the editor itself produces.
+pub struct LexicalExplicitReplyDetector {
+ client: LexicalClient,
+}
+
+impl LexicalExplicitReplyDetector {
+ /// Creates a detector calling the given lexical service client.
+ pub const fn new(client: LexicalClient) -> Self {
+ Self { client }
+ }
+}
+
+impl ExplicitReplyDetector for LexicalExplicitReplyDetector {
+ async fn is_explicit_reply(&self, markdown: &str) -> Result<bool> {
+ Ok(self.client.is_explicit_reply(markdown).await?)
+ }
+}
diff --git a/crates/agent_trigger/src/outbound/lexical_reply_detector.rs b/crates/agent_trigger/src/outbound/lexical_reply_detector.rs
deleted file mode 100644
index ebad953ffb..0000000000
--- a/crates/agent_trigger/src/outbound/lexical_reply_detector.rs
+++ /dev/null
@@ -1,25 +0,0 @@
-//! Quote-reply detection backed by the lexical service.
-
-use agent_session::domain::error::Result;
-use lexical_client::LexicalClient;
-
-use crate::domain::service::ReplyDetector;
-
-/// Detects quote-replies by parsing the markdown with the lexical service,
-/// so detection matches the nodes the editor itself produces.
-pub struct LexicalReplyDetector {
- client: LexicalClient,
-}
-
-impl LexicalReplyDetector {
- /// Creates a detector calling the given lexical service client.
- pub const fn new(client: LexicalClient) -> Self {
- Self { client }
- }
-}
-
-impl ReplyDetector for LexicalReplyDetector {
- async fn is_quote_reply(&self, markdown: &str) -> Result<bool> {
- Ok(self.client.is_quote_reply(markdown).await?)
- }
-}
diff --git a/crates/agent_trigger/src/outbound/mod.rs b/crates/agent_trigger/src/outbound/mod.rs
index e3b274a6ba..05f05406d4 100644
--- a/crates/agent_trigger/src/outbound/mod.rs
+++ b/crates/agent_trigger/src/outbound/mod.rs
@@ -3,9 +3,9 @@
mod bot_repo_agent_lookup;
mod channel_thread_history;
mod fast_model_judge;
-mod lexical_reply_detector;
+mod lexical_explicit_reply_detector;
pub use bot_repo_agent_lookup::BotRepoAgentLookup;
pub use channel_thread_history::ChannelThreadHistory;
pub use fast_model_judge::FastModelTriggerJudge;
-pub use lexical_reply_detector::LexicalReplyDetector;
+pub use lexical_explicit_reply_detector::LexicalExplicitReplyDetector;
diff --git a/crates/lexical_client/src/parse_markdown.rs b/crates/lexical_client/src/parse_markdown.rs
index be463fd175..26ba28ae1a 100644
--- a/crates/lexical_client/src/parse_markdown.rs
+++ b/crates/lexical_client/src/parse_markdown.rs
@@ -35,14 +35,14 @@ struct MentionsRequest<'a> {
}
#[derive(Debug, serde::Serialize)]
-struct QuoteReplyRequest<'a> {
+struct ExplicitReplyRequest<'a> {
markdown: &'a str,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
-struct QuoteReplyResponse {
- is_quote_reply: bool,
+struct ExplicitReplyResponse {
+ is_explicit_reply: bool,
}
/// An entity mention extracted from markdown by the lexical service
@@ -78,10 +78,27 @@ pub struct AgentAnnouncementChip {
pub status: String,
}
+/// The channel message targeted by an agent-session announcement, in the
+/// shape the lexical service's `ReplyTargetNode` validates.
+#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AgentAnnouncementReplyTarget {
+ /// Channel containing the targeted message.
+ pub channel_id: String,
+ /// Targeted channel message.
+ pub target_message_id: String,
+ /// Thread containing the targeted message.
+ pub target_thread_id: String,
+ /// Static one-line preview rendered by the reply target.
+ pub display_text: String,
+ /// Sender of the targeted message.
+ pub sender_id: String,
+}
+
#[derive(Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
struct AgentAnnouncementRequest<'a> {
- prompt_markdown: &'a str,
+ reply_target: &'a AgentAnnouncementReplyTarget,
chip: &'a AgentAnnouncementChip,
}
@@ -297,23 +314,20 @@ impl LexicalClient {
Ok(data.mentions)
}
- /// Composes the channel message announcing an agent session — the prompt
- /// quoted back as a blockquote above the session's Magic Chip — via the
- /// lexical service, so the markdown is built from real Lexical nodes.
- #[tracing::instrument(skip(self, prompt_markdown, chip), err)]
+ /// Composes the channel message announcing an agent session — a structured
+ /// reply target above the session's Magic Chip — via the lexical service,
+ /// so the markdown is built from real Lexical nodes.
+ #[tracing::instrument(skip(self, reply_target, chip), err)]
pub async fn compose_agent_announcement(
&self,
- prompt_markdown: &str,
+ reply_target: &AgentAnnouncementReplyTarget,
chip: &AgentAnnouncementChip,
) -> Result<String> {
let url = format!("{}/agent-announcement", self.url);
let response = check_response(
self.client
.post(&url)
- .json(&AgentAnnouncementRequest {
- prompt_markdown,
- chip,
- })
+ .json(&AgentAnnouncementRequest { reply_target, chip })
.send()
.await?,
)
@@ -348,22 +362,22 @@ impl LexicalClient {
Ok(data.markdown)
}
- /// Parses `markdown` via the lexical service and reports whether it is
- /// composed as a quote-reply: a leading blockquote followed by the reply
- /// itself, the shape the editor produces when replying to a message.
+ /// Parses `markdown` via the lexical service and reports whether it starts
+ /// with a `ReplyTargetNode` followed by the author's non-empty reply.
+ /// Standard Markdown blockquotes carry no reply semantics.
#[tracing::instrument(skip(self, markdown), err)]
- pub async fn is_quote_reply(&self, markdown: &str) -> Result<bool> {
- let url = format!("{}/quote-reply", self.url);
+ pub async fn is_explicit_reply(&self, markdown: &str) -> Result<bool> {
+ let url = format!("{}/explicit-reply", self.url);
let response = check_response(
self.client
.post(&url)
- .json(&QuoteReplyRequest { markdown })
+ .json(&ExplicitReplyRequest { markdown })
.send()
.await?,
)
.await?;
- let data: QuoteReplyResponse = response.json().await.context("unexpected response")?;
- Ok(data.is_quote_reply)
+ let data: ExplicitReplyResponse = response.json().await.context("unexpected response")?;
+ Ok(data.is_explicit_reply)
}
async fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T> {
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/AGENT_GUIDE/channels.md
index 8c7b4e4dbc..31ca177d9e 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/AGENT_GUIDE/channels.md
@@ -20,6 +20,17 @@ Placeholder `Type @ to share with #<name>`. Click it, `type_text`, press Enter t
The message renders immediately with avatar, email, timestamp. Composer extras: `Attach
files`, `Format`, a `Task` switch (turns the message into a task), `Send message` button.
+Hover a message for its action menu. `Reply` on a top-level message opens that thread. On
+an existing thread reply, it inserts a one-line reply-target reference into the composer;
+clicking the reference navigates back to that reply. If text in the message is
+browser-selected before `Reply` is clicked, the reference previews only the selected text.
+For agent-session messages, the reference previews the resolved answer or current activity
+rather than the internal Magic Chip marker.
+Agent-session announcements use the same ReplyTarget reference for the prompting channel
+message; ordinary Markdown blockquotes remain presentation-only and do not count as replies.
+The composer always keeps an editable empty line after a block reference, including after
+the user deletes that line, so clicking below the reference can restore the text caret.
+
## Channel tabs
Radio group at the top of the channel pane: `Messages` / `Attachments` / `Participants`,
diff --git a/packages/lexical-core/decoratorRegistry.ts b/packages/lexical-core/decoratorRegistry.ts
index 3de5b6a702..77fedc44d1 100644
--- a/packages/lexical-core/decoratorRegistry.ts
+++ b/packages/lexical-core/decoratorRegistry.ts
@@ -50,6 +50,10 @@ import type {
PullRequestMentionDecoratorProps,
PullRequestMentionNode,
} from './nodes/PullRequestMentionNode';
+import type {
+ ReplyTargetDecoratorProps,
+ ReplyTargetNode,
+} from './nodes/ReplyTargetNode';
import type {
SnapshotDecoratorProps,
SnapshotNode,
@@ -127,6 +131,10 @@ export interface NodeDecoratorMap {
klass: typeof PullRequestMentionNode;
props: PullRequestMentionDecoratorProps;
};
+ ReplyTargetNode: {
+ klass: typeof ReplyTargetNode;
+ props: ReplyTargetDecoratorProps;
+ };
EquationNode: {
klass: typeof EquationNode;
props: EquationDecoratorProps;
diff --git a/packages/lexical-core/index.ts b/packages/lexical-core/index.ts
index bde298f45f..9d24200dbc 100644
--- a/packages/lexical-core/index.ts
+++ b/packages/lexical-core/index.ts
@@ -27,6 +27,7 @@ export * from './nodes/MagicChipNode';
export * from './nodes/MediaNode';
export * from './nodes/PasteNode';
export * from './nodes/PullRequestMentionNode';
+export * from './nodes/ReplyTargetNode';
export * from './nodes/SnapshotNode';
export * from './nodes/TagMentionNode';
export * from './nodes/ThemeMentionNode';
diff --git a/packages/lexical-core/node-list.ts b/packages/lexical-core/node-list.ts
index 2c2ac3c1ca..b8288b993f 100644
--- a/packages/lexical-core/node-list.ts
+++ b/packages/lexical-core/node-list.ts
@@ -36,6 +36,7 @@ import { InlineSearchNode } from './nodes/InlineSearchNode';
import { MagicChipNode } from './nodes/MagicChipNode';
import { PasteNode } from './nodes/PasteNode';
import { PullRequestMentionNode } from './nodes/PullRequestMentionNode';
+import { ReplyTargetNode } from './nodes/ReplyTargetNode';
import { SearchMatchNode } from './nodes/SearchMatchNode';
import { SnapshotNode } from './nodes/SnapshotNode';
import { TagMentionNode } from './nodes/TagMentionNode';
@@ -81,6 +82,7 @@ export const SupportedNodeTypes = [
ContactMentionNode,
DateMentionNode,
PullRequestMentionNode,
+ ReplyTargetNode,
GroupMentionNode,
InlineSearchNode,
UnlinkedTextNode,
diff --git a/packages/lexical-core/nodes/PasteNode.ts b/packages/lexical-core/nodes/PasteNode.ts
index d1447c9dc6..e584d660b6 100644
--- a/packages/lexical-core/nodes/PasteNode.ts
+++ b/packages/lexical-core/nodes/PasteNode.ts
@@ -28,7 +28,7 @@ export const DEFAULT_PASTE_ORIGIN: PasteOrigin = 'pasted';
export type PasteNodeData = {
content: string;
/**
- * Why this chip exists: a large clipboard paste, or a quote-reply from
+ * Why this chip exists: a large clipboard paste, or a reply-target from
* selected conversation text. Defaults to `pasted` so existing documents
* keep their original label.
*/
diff --git a/packages/lexical-core/nodes/ReplyTargetNode.ts b/packages/lexical-core/nodes/ReplyTargetNode.ts
new file mode 100644
index 0000000000..7be8074d27
--- /dev/null
+++ b/packages/lexical-core/nodes/ReplyTargetNode.ts
@@ -0,0 +1,208 @@
+import {
+ $applyNodeReplacement,
+ DecoratorNode,
+ type DOMConversionMap,
+ type EditorConfig,
+ type EditorThemeClasses,
+ type LexicalEditor,
+ type LexicalNode,
+ type NodeKey,
+ type SerializedLexicalNode,
+ type Spread,
+} from 'lexical';
+import { type DecoratorComponent, getDecorator } from '../decoratorRegistry';
+import { $applyIdFromSerialized } from '../plugins/nodeIdPlugin';
+
+const VERSION = 1;
+
+export const REPLY_TARGET_NODE_TYPE = 'reply-target';
+export const REPLY_TARGET_NODE_TAG = 'm-reply-target';
+
+/** The message reference and preview persisted by a reply-target node. */
+export type ReplyTargetData = {
+ channelId: string;
+ targetMessageId: string;
+ targetThreadId: string;
+ displayText: string;
+ senderId: string;
+};
+
+/** Return whether a value is a valid reply-target-node payload. */
+export function isReplyTargetData(value: unknown): value is ReplyTargetData {
+ if (!value || typeof value !== 'object') return false;
+ const data = value as Record<string, unknown>;
+ return (
+ typeof data.channelId === 'string' &&
+ typeof data.targetMessageId === 'string' &&
+ typeof data.targetThreadId === 'string' &&
+ typeof data.displayText === 'string' &&
+ typeof data.senderId === 'string'
+ );
+}
+
+/** Serialize reply-target data into the internal Markdown representation. */
+export function buildReplyTargetMarkdown(data: ReplyTargetData): string {
+ const payload = JSON.stringify(data).replace(/</g, '\\u003c');
+ return `<${REPLY_TARGET_NODE_TAG}>${payload}</${REPLY_TARGET_NODE_TAG}>`;
+}
+
+/** Remove one leading reply-target block from internal Markdown. */
+export function stripLeadingReplyTargetMarkdown(markdown: string): string {
+ const pattern = new RegExp(
+ `^\\s*<${REPLY_TARGET_NODE_TAG}>.*?<\\/${REPLY_TARGET_NODE_TAG}>\\s*`,
+ 's'
+ );
+ return markdown.replace(pattern, '');
+}
+
+/** Serialized form of a reply-target node. */
+export type SerializedReplyTargetNode = Spread<
+ ReplyTargetData,
+ SerializedLexicalNode
+>;
+
+/** Props passed to the application-provided reply-target decorator. */
+export type ReplyTargetDecoratorProps = ReplyTargetData & {
+ key: NodeKey;
+ theme: EditorThemeClasses;
+};
+
+/** A block-level reference to another message in a channel thread. */
+export class ReplyTargetNode extends DecoratorNode<
+ DecoratorComponent<ReplyTargetDecoratorProps> | undefined
+> {
+ __channelId: string;
+ __targetMessageId: string;
+ __targetThreadId: string;
+ __displayText: string;
+ __senderId: string;
+
+ static getType(): typeof REPLY_TARGET_NODE_TYPE {
+ return REPLY_TARGET_NODE_TYPE;
+ }
+
+ static clone(node: ReplyTargetNode): ReplyTargetNode {
+ return new ReplyTargetNode(
+ node.__channelId,
+ node.__targetMessageId,
+ node.__targetThreadId,
+ node.__displayText,
+ node.__senderId,
+ node.__key
+ );
+ }
+
+ constructor(
+ channelId: string,
+ targetMessageId: string,
+ targetThreadId: string,
+ displayText: string,
+ senderId: string,
+ key?: NodeKey
+ ) {
+ super(key);
+ this.__channelId = channelId;
+ this.__targetMessageId = targetMessageId;
+ this.__targetThreadId = targetThreadId;
+ this.__displayText = displayText;
+ this.__senderId = senderId;
+ }
+
+ static importJSON(
+ serializedNode: SerializedReplyTargetNode
+ ): ReplyTargetNode {
+ if (!isReplyTargetData(serializedNode)) {
+ throw new Error('invalid reply-target data');
+ }
+ const node = $createReplyTargetNode(serializedNode);
+ $applyIdFromSerialized(node, serializedNode);
+ return node;
+ }
+
+ exportJSON(): SerializedReplyTargetNode {
+ return {
+ ...super.exportJSON(),
+ ...this.exportComponentProps(),
+ type: REPLY_TARGET_NODE_TYPE,
+ version: VERSION,
+ };
+ }
+
+ exportComponentProps(): ReplyTargetData {
+ return {
+ channelId: this.__channelId,
+ targetMessageId: this.__targetMessageId,
+ targetThreadId: this.__targetThreadId,
+ displayText: this.__displayText,
+ senderId: this.__senderId,
+ };
+ }
+
+ isInline(): false {
+ return false;
+ }
+
+ isKeyboardSelectable(): true {
+ return true;
+ }
+
+ createDOM(_config: EditorConfig): HTMLElement {
+ const element = document.createElement('div');
+ element.setAttribute('data-reply-target-node', this.__targetMessageId);
+ return element;
+ }
+
+ updateDOM(): false {
+ return false;
+ }
+
+ exportDOM() {
+ const element = document.createElement('div');
+ element.setAttribute('data-reply-target-node', this.__targetMessageId);
+ element.textContent = this.__displayText;
+ return { element };
+ }
+
+ static importDOM(): DOMConversionMap | null {
+ return null;
+ }
+
+ getTextContent(): string {
+ return this.__displayText;
+ }
+
+ getSearchText(): string {
+ return this.__displayText;
+ }
+
+ decorate(_: LexicalEditor, config: EditorConfig) {
+ const decorator = getDecorator<ReplyTargetDecoratorProps>(ReplyTargetNode);
+ if (!decorator) return;
+ return () =>
+ decorator({
+ ...this.exportComponentProps(),
+ key: this.getKey(),
+ theme: config.theme,
+ });
+ }
+}
+
+/** Create a block-level channel reply-target reference. */
+export function $createReplyTargetNode(data: ReplyTargetData): ReplyTargetNode {
+ return $applyNodeReplacement(
+ new ReplyTargetNode(
+ data.channelId,
+ data.targetMessageId,
+ data.targetThreadId,
+ data.displayText,
+ data.senderId
+ )
+ );
+}
+
+/** Return whether a Lexical node is a reply-target node. */
+export function $isReplyTargetNode(
+ node: LexicalNode | null | undefined
+): node is ReplyTargetNode {
+ return node instanceof ReplyTargetNode;
+}
diff --git a/packages/lexical-core/tests/agent-announcement.test.ts b/packages/lexical-core/tests/agent-announcement.test.ts
index 1444ecf364..4aabb97da1 100644
--- a/packages/lexical-core/tests/agent-announcement.test.ts
+++ b/packages/lexical-core/tests/agent-announcement.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest';
+import { buildReplyTargetMarkdown } from '../nodes/ReplyTargetNode';
import { composeAgentSessionAnnouncement } from '../utils/agent-announcement';
import { markdownToSerializedEditorStateWithIds } from '../utils/markdown-state';
import { quoteMarkdown } from '../utils/quote-markdown';
@@ -13,6 +14,16 @@ const chip = {
const chipMarkdown =
'<m-magic-chip>{"agentSessionId":"session-1","channelId":"channel-1","promptedMessage":{"turn":0,"author":"user"},"status":"booting"}</m-magic-chip>';
+const replyTarget = {
+ channelId: 'channel-1',
+ targetMessageId: 'message-1',
+ targetThreadId: 'thread-1',
+ displayText: '@claude fix the failing test it broke on main',
+ senderId: 'macro|[email protected]',
+};
+
+const replyTargetMarkdown = buildReplyTargetMarkdown(replyTarget);
+
const channelLessChip = {
agentSessionId: 'session-2',
promptedMessage: { turn: 0, author: 'user' },
@@ -38,57 +49,79 @@ describe('quoteMarkdown', () => {
});
describe('composeAgentSessionAnnouncement', () => {
- it('quotes the prompt above the magic chip', () => {
+ it('places the structured reply target above the magic chip', () => {
const markdown = composeAgentSessionAnnouncement({
- promptMarkdown: '@claude fix the failing test\nit broke on main',
+ replyTarget,
chip,
});
- expect(markdown).toBe(
- `> @claude fix the failing test\n> it broke on main\n\n${chipMarkdown}`
- );
+ expect(markdown).toBe(`${replyTargetMarkdown}\n\n${chipMarkdown}`);
});
- it('emits only the chip for a blank prompt', () => {
+ it('emits only the chip for a blank reply-target preview', () => {
expect(
- composeAgentSessionAnnouncement({ promptMarkdown: ' ', chip })
+ composeAgentSessionAnnouncement({
+ replyTarget: { ...replyTarget, displayText: ' ' },
+ chip,
+ })
).toBe(chipMarkdown);
});
- it('keeps a user-authored agent context tag visible in the quoted prompt', () => {
+ it('keeps user-authored markup in the reply-target display text', () => {
+ const displayText =
+ 'visible\n\n<m-agent-context>{"version":1,"text":"private"}</m-agent-context>';
+ expect(
+ composeAgentSessionAnnouncement({
+ replyTarget: { ...replyTarget, displayText },
+ chip,
+ })
+ ).toBe(
+ `${buildReplyTargetMarkdown({ ...replyTarget, displayText: displayText.replace(/\s+/g, ' ') })}\n\n${chipMarkdown}`
+ );
+ });
+
+ it('omits a leading reply target from the announcement preview', () => {
+ const nestedReplyTarget = buildReplyTargetMarkdown({
+ ...replyTarget,
+ displayText: 'earlier message',
+ });
+
expect(
composeAgentSessionAnnouncement({
- promptMarkdown:
- 'visible\n\n<m-agent-context>{"version":1,"text":"private"}</m-agent-context>',
+ replyTarget: {
+ ...replyTarget,
+ displayText: `${nestedReplyTarget}\n\nnew response`,
+ },
chip,
})
).toBe(
- `> visible\n> \n> <m-agent-context>{"version":1,"text":"private"}</m-agent-context>\n\n${chipMarkdown}`
+ `${buildReplyTargetMarkdown({ ...replyTarget, displayText: 'new response' })}\n\n${chipMarkdown}`
);
});
it('composes a session chip without a legacy dedicated channel', () => {
expect(
composeAgentSessionAnnouncement({
- promptMarkdown: 'please look at this',
+ replyTarget: { ...replyTarget, displayText: 'please look at this' },
chip: channelLessChip,
})
).toBe(
- '> please look at this\n\n<m-magic-chip>{"agentSessionId":"session-2","promptedMessage":{"turn":0,"author":"user"},"status":"booting"}</m-magic-chip>'
+ '<m-reply-target>{"channelId":"channel-1","targetMessageId":"message-1","targetThreadId":"thread-1","displayText":"please look at this","senderId":"macro|[email protected]"}</m-reply-target>\n\n<m-magic-chip>{"agentSessionId":"session-2","promptedMessage":{"turn":0,"author":"user"},"status":"booting"}</m-magic-chip>'
);
});
- it('produces markdown the editor parses back into a quote and a chip', () => {
+ it('parses back into a reply target and a chip', () => {
const markdown = composeAgentSessionAnnouncement({
- promptMarkdown: 'please look at this',
+ replyTarget,
chip,
});
const state = markdownToSerializedEditorStateWithIds(markdown);
expect(state.root.children.map((child) => child.type)).toEqual([
- 'quote',
+ 'reply-target',
'magic-chip',
]);
+ expect(state.root.children[0]).toMatchObject(replyTarget);
expect(state.root.children[1]).toMatchObject(chip);
});
});
diff --git a/packages/lexical-core/tests/explicit-reply.test.ts b/packages/lexical-core/tests/explicit-reply.test.ts
new file mode 100644
index 0000000000..caef1dd4d7
--- /dev/null
+++ b/packages/lexical-core/tests/explicit-reply.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+import { buildReplyTargetMarkdown } from '../nodes/ReplyTargetNode';
+import { isExplicitReplyMarkdown } from '../utils/explicit-reply';
+
+describe('isExplicitReplyMarkdown', () => {
+ it('detects a reply-target node followed by a response', () => {
+ const reply = buildReplyTargetMarkdown({
+ channelId: 'channel-1',
+ targetMessageId: 'reply-1',
+ targetThreadId: 'thread-1',
+ displayText: 'please fix this',
+ senderId: 'macro|[email protected]',
+ });
+
+ expect(isExplicitReplyMarkdown(`${reply}\n\nyes, on it`)).toBe(true);
+ expect(isExplicitReplyMarkdown(reply)).toBe(false);
+ });
+
+ it('rejects plain text', () => {
+ expect(isExplicitReplyMarkdown('just a normal message')).toBe(false);
+ });
+
+ it('does not treat a blockquote followed by content as an explicit reply', () => {
+ expect(isExplicitReplyMarkdown('> quoted text\n\nordinary response')).toBe(
+ false
+ );
+ });
+
+ it('rejects a quote appearing after the reply', () => {
+ expect(isExplicitReplyMarkdown('as I said\n\n> earlier message')).toBe(
+ false
+ );
+ });
+
+ it('rejects empty markdown', () => {
+ expect(isExplicitReplyMarkdown('')).toBe(false);
+ });
+});
diff --git a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
index 03fb3e89db..1007105767 100644
--- a/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
+++ b/packages/lexical-core/tests/internal-transformer-fallbacks.test.ts
@@ -148,6 +148,7 @@ describe('internal transformer fallbacks', () => {
['<m-image>{"alt":"missing url"}</m-image>', 'Unknown Image'],
['<m-video>{bad}</m-video>', 'Unknown Video'],
['<m-watermark>{bad}</m-watermark>', 'Unknown Watermark'],
+ ['<m-reply-target>{bad}</m-reply-target>', 'Unknown Reply Target'],
[
'<m-email-thread-embed>{bad}</m-email-thread-embed>',
'Unknown Email Thread',
diff --git a/packages/lexical-core/tests/quote-reply.test.ts b/packages/lexical-core/tests/quote-reply.test.ts
deleted file mode 100644
index 61a22d429c..0000000000
--- a/packages/lexical-core/tests/quote-reply.test.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { isQuoteReplyMarkdown } from '../utils/quote-reply';
-
-describe('isQuoteReplyMarkdown', () => {
- it('detects a quote followed by a reply', () => {
- expect(isQuoteReplyMarkdown('> can you fix the tests\n\nyes, on it')).toBe(
- true
- );
- });
-
- it('detects a multi-line quote', () => {
- expect(
- isQuoteReplyMarkdown('> first line\n> second line\n\nlooks right to me')
- ).toBe(true);
- });
-
- it('rejects plain text', () => {
- expect(isQuoteReplyMarkdown('just a normal message')).toBe(false);
- });
-
- it('rejects a bare quote with no reply', () => {
- expect(isQuoteReplyMarkdown('> quoted with nothing to say')).toBe(false);
- });
-
- it('rejects a quote appearing after the reply', () => {
- expect(isQuoteReplyMarkdown('as I said\n\n> earlier message')).toBe(false);
- });
-
- it('rejects empty markdown', () => {
- expect(isQuoteReplyMarkdown('')).toBe(false);
- });
-});
diff --git a/packages/lexical-core/tests/reply-target-node.test.ts b/packages/lexical-core/tests/reply-target-node.test.ts
new file mode 100644
index 0000000000..9204e304b6
--- /dev/null
+++ b/packages/lexical-core/tests/reply-target-node.test.ts
@@ -0,0 +1,71 @@
+import { createHeadlessEditor } from '@lexical/headless';
+import { $convertToMarkdownString } from '@lexical/markdown';
+import { describe, expect, it } from 'vitest';
+import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import {
+ buildReplyTargetMarkdown,
+ stripLeadingReplyTargetMarkdown,
+} from '../nodes/ReplyTargetNode';
+import { EXTERNAL_TRANSFORMERS } from '../transformers';
+import {
+ markdownToSerializedEditorStateWithIds,
+ serializedEditorStateToMarkdown,
+} from '../utils/markdown-state';
+import { markdownToEmbeddingText, markdownToPlainText } from '../utils/parsers';
+
+const data = {
+ channelId: 'channel-1',
+ targetMessageId: 'reply-1',
+ targetThreadId: 'thread-1',
+ displayText: 'A one-line preview',
+ senderId: 'macro|[email protected]',
+};
+const markdown = buildReplyTargetMarkdown(data);
+
+describe('ReplyTargetNode', () => {
+ it('round-trips through internal Markdown as a block decorator', () => {
+ const state = markdownToSerializedEditorStateWithIds(markdown);
+
+ expect(state.root.children[0]).toMatchObject({
+ type: 'reply-target',
+ ...data,
+ });
+ expect(serializedEditorStateToMarkdown(state)).toBe(markdown);
+ });
+
+ it('exposes its preview to plain text and embedding conversion', () => {
+ expect(markdownToPlainText(markdown)).toBe(data.displayText);
+ expect(markdownToEmbeddingText(markdown)).toBe(data.displayText);
+ });
+
+ it('exports externally as a standard Markdown blockquote', () => {
+ const editor = createHeadlessEditor({
+ nodes: [...SupportedNodeTypes, ...NodeReplacements],
+ });
+ const state = editor.parseEditorState(
+ markdownToSerializedEditorStateWithIds(markdown)
+ );
+
+ expect(
+ state.read(() => $convertToMarkdownString(EXTERNAL_TRANSFORMERS))
+ ).toBe(`> ${data.displayText}`);
+ });
+
+ it('escapes a closing-tag injection in display text', () => {
+ expect(
+ buildReplyTargetMarkdown({
+ ...data,
+ displayText: '</m-reply-target>still visible',
+ })
+ ).not.toContain('</m-reply-target>still visible');
+ });
+
+ it('strips one leading reply-target block from Markdown', () => {
+ expect(stripLeadingReplyTargetMarkdown(`${markdown}\n\nmy response`)).toBe(
+ 'my response'
+ );
+ expect(stripLeadingReplyTargetMarkdown(`before\n\n${markdown}`)).toBe(
+ `before\n\n${markdown}`
+ );
+ });
+});
diff --git a/packages/lexical-core/transformers/index.ts b/packages/lexical-core/transformers/index.ts
index a09a000161..6eebb3cba1 100644
--- a/packages/lexical-core/transformers/index.ts
+++ b/packages/lexical-core/transformers/index.ts
@@ -32,6 +32,7 @@ import {
I_USER_MENTION,
} from './mentions';
import { E_PASTE_NODE, I_PASTE_NODE } from './paste';
+import { E_REPLY_TARGET_NODE, I_REPLY_TARGET_NODE } from './reply-target';
import { E_SNAPSHOT_NODE, I_SNAPSHOT_NODE } from './snapshot';
import { E_TABLE_NODE, I_TABLE_NODE } from './tables';
import {
@@ -76,6 +77,7 @@ export const INTERNAL_TRANSFORMERS: Transformer[] = [
I_DATE_MENTION,
I_AWAIT_NODE,
I_MAGIC_CHIP,
+ I_REPLY_TARGET_NODE,
I_AGENT_CONTEXT,
I_TABLE_NODE,
HTML_BLOCKQUOTE,
@@ -110,6 +112,7 @@ export const EXTERNAL_TRANSFORMERS: Transformer[] = [
E_PR_MENTION,
E_CONTACT_MENTION,
E_DATE_MENTION,
+ E_REPLY_TARGET_NODE,
E_TAG_MENTION,
// order matters
E_MULTILINE_BLOCK_EQUATION_NODE,
@@ -159,6 +162,7 @@ export const ALL_TRANSFORMERS: Transformer[] = [
E_DATE_MENTION,
I_AWAIT_NODE,
I_MAGIC_CHIP,
+ I_REPLY_TARGET_NODE,
I_AGENT_CONTEXT,
I_MACRO_QUOTE,
I_EQUATION_NODE,
diff --git a/packages/lexical-core/transformers/reply-target.ts b/packages/lexical-core/transformers/reply-target.ts
new file mode 100644
index 0000000000..86cf6ce9c7
--- /dev/null
+++ b/packages/lexical-core/transformers/reply-target.ts
@@ -0,0 +1,52 @@
+import type { ElementTransformer } from '@lexical/markdown';
+import type { ElementNode, LexicalNode } from 'lexical';
+import {
+ $createReplyTargetNode,
+ $isReplyTargetNode,
+ buildReplyTargetMarkdown,
+ isReplyTargetData,
+ ReplyTargetNode,
+} from '../nodes/ReplyTargetNode';
+import {
+ replaceElementWithUnknownMention,
+ UnknownMentionNode,
+} from './unknownFallback';
+
+/** Internal Markdown transformer for channel reply-target references. */
+export const I_REPLY_TARGET_NODE: ElementTransformer = {
+ dependencies: [ReplyTargetNode, UnknownMentionNode],
+ type: 'element',
+ regExp: /^<m-reply-target>(.*?)<\/m-reply-target>$/s,
+ export: (node: LexicalNode) => {
+ if (!$isReplyTargetNode(node)) return null;
+ return buildReplyTargetMarkdown(node.exportComponentProps());
+ },
+ replace: (parent: ElementNode, _, match: string[]) => {
+ try {
+ const data: unknown = JSON.parse(match[1] ?? '');
+ if (!isReplyTargetData(data)) {
+ throw new Error('invalid reply-target data');
+ }
+ parent.replace($createReplyTargetNode(data));
+ } catch (error) {
+ console.error('Error in I_REPLY_TARGET_NODE replace:', error);
+ replaceElementWithUnknownMention(parent, 'Unknown Reply Target');
+ }
+ },
+};
+
+/** External Markdown transformer for channel reply-target references. */
+export const E_REPLY_TARGET_NODE: ElementTransformer = {
+ dependencies: [ReplyTargetNode],
+ type: 'element',
+ regExp: /$^/,
+ export: (node: LexicalNode) => {
+ if (!$isReplyTargetNode(node)) return null;
+ const { displayText } = node.exportComponentProps();
+ return displayText
+ .split('\n')
+ .map((line) => `> ${line}`)
+ .join('\n');
+ },
+ replace: () => false,
+};
diff --git a/packages/lexical-core/utils/agent-announcement.ts b/packages/lexical-core/utils/agent-announcement.ts
index 51fed4ad45..41c74308f8 100644
--- a/packages/lexical-core/utils/agent-announcement.ts
+++ b/packages/lexical-core/utils/agent-announcement.ts
@@ -1,42 +1,52 @@
import { createHeadlessEditor } from '@lexical/headless';
-import {
- $convertFromMarkdownString,
- $convertToMarkdownString,
-} from '@lexical/markdown';
+import { $convertToMarkdownString } from '@lexical/markdown';
import { $getRoot } from 'lexical';
import { NodeReplacements, SupportedNodeTypes } from '../node-list';
import {
$createMagicChipNode,
type MagicChipData,
} from '../nodes/MagicChipNode';
+import {
+ $createReplyTargetNode,
+ stripLeadingReplyTargetMarkdown,
+ type ReplyTargetData,
+} from '../nodes/ReplyTargetNode';
import { ALL_TRANSFORMERS } from '../transformers';
-import { quoteMarkdown } from './quote-markdown';
/** Everything the announcement for one agent-session prompt is built from. */
export type AgentSessionAnnouncement = {
- /** Markdown of the message that prompted the session, quoted back. */
- promptMarkdown: string;
+ /** Message the agent announcement explicitly replies to. */
+ replyTarget: ReplyTargetData;
/** The Magic Chip anchoring the session's live response. */
chip: MagicChipData;
};
/**
- * Compose the channel message that announces an agent session: the prompting
- * message quoted back (exactly as quote-reply would), followed by the
- * session's Magic Chip. Built headlessly from real Lexical nodes so the
- * serialized markdown always matches what the editor itself produces.
+ * Compose the channel message that announces an agent session: a structured
+ * reply target followed by the session's Magic Chip. Built headlessly from
+ * real Lexical nodes so the serialized markdown always matches what the
+ * editor itself produces.
*/
export function composeAgentSessionAnnouncement(
announcement: AgentSessionAnnouncement
): string {
+ const replyTarget = {
+ ...announcement.replyTarget,
+ displayText: stripLeadingReplyTargetMarkdown(
+ announcement.replyTarget.displayText
+ )
+ .trim()
+ .replace(/\s+/g, ' '),
+ };
const editor = createHeadlessEditor({
nodes: [...SupportedNodeTypes, ...NodeReplacements],
});
editor.update(
() => {
- const quote = quoteMarkdown(announcement.promptMarkdown);
- if (quote) $convertFromMarkdownString(quote, ALL_TRANSFORMERS);
+ if (replyTarget.displayText) {
+ $getRoot().append($createReplyTargetNode(replyTarget));
+ }
$getRoot().append($createMagicChipNode(announcement.chip));
},
{ discrete: true }
diff --git a/packages/lexical-core/utils/quote-reply.ts b/packages/lexical-core/utils/explicit-reply.ts
similarity index 60%
rename from packages/lexical-core/utils/quote-reply.ts
rename to packages/lexical-core/utils/explicit-reply.ts
index 125abe1626..054ab4d6b2 100644
--- a/packages/lexical-core/utils/quote-reply.ts
+++ b/packages/lexical-core/utils/explicit-reply.ts
@@ -1,19 +1,18 @@
import { createHeadlessEditor } from '@lexical/headless';
import { $convertFromMarkdownString } from '@lexical/markdown';
-import { $isQuoteNode } from '@lexical/rich-text';
import { $getRoot } from 'lexical';
import { NodeReplacements, SupportedNodeTypes } from '../node-list';
+import { $isReplyTargetNode } from '../nodes/ReplyTargetNode';
import { ALL_TRANSFORMERS } from '../transformers';
/**
- * Whether a macro markdown string is composed as a quote-reply: a leading
- * blockquote quoting the replied-to message, followed by the reply itself —
- * the shape `buildQuoteReplyValue` produces in the channel input.
+ * Whether a macro markdown string is composed as an explicit reply: a leading
+ * reply-target node followed by the author's response.
*
- * A bare blockquote with nothing after it is not a reply; there is no message
- * of the author's own.
+ * A bare reference with nothing after it is not a reply; there is no message
+ * of the author's own. Standard Markdown blockquotes carry no reply semantics.
*/
-export function isQuoteReplyMarkdown(markdown: string): boolean {
+export function isExplicitReplyMarkdown(markdown: string): boolean {
const editor = createHeadlessEditor({
nodes: [...SupportedNodeTypes, ...NodeReplacements],
});
@@ -28,7 +27,7 @@ export function isQuoteReplyMarkdown(markdown: string): boolean {
return editor.getEditorState().read(() => {
const [first, ...rest] = $getRoot().getChildren();
return (
- $isQuoteNode(first) &&
+ $isReplyTargetNode(first) &&
rest.some((node) => node.getTextContent().trim() !== '')
);
});
diff --git a/packages/lexical-core/utils/mentions.ts b/packages/lexical-core/utils/mentions.ts
index 8cd6eec334..dfb5f3c119 100644
--- a/packages/lexical-core/utils/mentions.ts
+++ b/packages/lexical-core/utils/mentions.ts
@@ -176,6 +176,7 @@ export {
parseGroupMentions,
parseLinks,
parsePullRequestMentions,
+ parseReplyTargets,
parseTagMentions,
parseUserMentions,
} from './parsers';
diff --git a/packages/lexical-core/utils/parsers.ts b/packages/lexical-core/utils/parsers.ts
index abab38920f..dbd33fd2b9 100644
--- a/packages/lexical-core/utils/parsers.ts
+++ b/packages/lexical-core/utils/parsers.ts
@@ -120,6 +120,21 @@ export function parseDocumentCards(text: string): string {
);
}
+/** Replace reply-target nodes with their user-visible preview text. */
+export function parseReplyTargets(text: string): string {
+ return text.replace(
+ /<m-reply-target>(.*?)<\/m-reply-target>/gs,
+ (_, json) => {
+ try {
+ const data = JSON.parse(json);
+ return data.displayText || '';
+ } catch {
+ return '';
+ }
+ }
+ );
+}
+
export function parseSnapshots(text: string): string {
return text.replace(/<m-snapshot>(.*?)<\/m-snapshot>/g, (_, encoded) => {
try {
@@ -168,27 +183,25 @@ export function stripAgentContext(text: string): string {
* - Snapshots: documentName (base64-encoded payload)
* - Group mentions: @groupAlias (e.g., @here)
* - Links: text (fallback to url)
+ * - Reply targets: displayText
*/
export function markdownToPlainText(markdown: string): string {
- return stripAgentContext(
- parseLinks(
- parseDocumentCards(
- parseSnapshots(
- parseTagMentions(
- parsePullRequestMentions(
- parseDocumentMentions(
- parseGroupMentions(
- parseDateMentions(
- parseContactMentions(parseUserMentions(markdown))
- )
- )
- )
- )
- )
- )
- )
- )
- );
+ const transforms: Array<(text: string) => string> = [
+ parseUserMentions,
+ parseContactMentions,
+ parseDateMentions,
+ parseGroupMentions,
+ parseDocumentMentions,
+ parsePullRequestMentions,
+ parseTagMentions,
+ parseSnapshots,
+ parseDocumentCards,
+ parseLinks,
+ parseReplyTargets,
+ stripAgentContext,
+ ];
+
+ return transforms.reduce((text, transform) => transform(text), markdown);
}
/**
@@ -211,6 +224,7 @@ type MentionTagPayload = {
emailOrDomain?: string;
displayFormat?: string;
groupAlias?: string;
+ displayText?: string;
equation?: string;
};
@@ -369,6 +383,11 @@ export function markdownToEmbeddingText(markdown: string): string {
);
text = replaceJsonTag(text, 'm-theme-mention', (data) => data.name || '');
text = replaceJsonTag(text, 'm-await', (data) => data.text || '');
+ text = replaceJsonTag(
+ text,
+ 'm-reply-target',
+ (data) => data.displayText || ''
+ );
text = replaceJsonTag(text, 'm-watermark', () => '');
// Anything still tagged is an unrecognized m-* node: drop it entirely so
diff --git a/services/agent_harness_service/src/trigger.rs b/services/agent_harness_service/src/trigger.rs
index e9c4d409e1..bd42e17f2c 100644
--- a/services/agent_harness_service/src/trigger.rs
+++ b/services/agent_harness_service/src/trigger.rs
@@ -4,7 +4,7 @@ use agent_session::outbound::postgres::PgAgentSessionRepo;
use agent_trigger::domain::processing::process_channel_event;
use agent_trigger::domain::service::AgentTriggerService;
use agent_trigger::outbound::{
- BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector,
+ BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyDetector,
};
use bots::outbound::pg_bots_repo::PgBotsRepo;
use channels::domain::broker_events::ChannelMacroEvent;
@@ -63,7 +63,7 @@ async fn run(pool: PgPool, kafka_brokers: String, internal_api_key: String) -> a
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
- LexicalReplyDetector::new(lexical),
+ LexicalExplicitReplyDetector::new(lexical),
FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),
ChannelThreadHistory::new(PgChannelsRepo::new(pool)),
);
diff --git a/services/agent_trigger_service/src/main.rs b/services/agent_trigger_service/src/main.rs
index 55612246dd..c5373514e6 100644
--- a/services/agent_trigger_service/src/main.rs
+++ b/services/agent_trigger_service/src/main.rs
@@ -6,7 +6,7 @@ use agent_session::outbound::postgres::PgAgentSessionRepo;
use agent_trigger::domain::processing::process_channel_event;
use agent_trigger::domain::service::AgentTriggerService;
use agent_trigger::outbound::{
- BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalReplyDetector,
+ BotRepoAgentLookup, ChannelThreadHistory, FastModelTriggerJudge, LexicalExplicitReplyDetector,
};
use anyhow::Context as _;
use bots::outbound::pg_bots_repo::PgBotsRepo;
@@ -70,7 +70,7 @@ async fn run() -> anyhow::Result<()> {
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
BotRepoAgentLookup::new(PgBotsRepo::new(pool.clone())),
- LexicalReplyDetector::new(lexical),
+ LexicalExplicitReplyDetector::new(lexical),
FastModelTriggerJudge::new(ai_usage::pg_recorder(pool.clone())),
ChannelThreadHistory::new(PgChannelsRepo::new(pool)),
);
diff --git a/services/lexical-service/src/endpoints/agent-announcement.ts b/services/lexical-service/src/endpoints/agent-announcement.ts
index e67126cf62..5f3177de29 100644
--- a/services/lexical-service/src/endpoints/agent-announcement.ts
+++ b/services/lexical-service/src/endpoints/agent-announcement.ts
@@ -10,7 +10,13 @@ import { handleEndpointError } from "../lib/error-handler";
import { standardErrorResponses } from "../lib/schemas";
const agentAnnouncementRequest = z.object({
- promptMarkdown: z.string(),
+ replyTarget: z.object({
+ channelId: z.string(),
+ targetMessageId: z.string(),
+ targetThreadId: z.string(),
+ displayText: z.string(),
+ senderId: z.string(),
+ }),
chip: z.object({
agentSessionId: z.string(),
channelId: z.string().optional(),
@@ -28,9 +34,9 @@ const agentAnnouncementResponse = z.object({
export class AgentAnnouncementEndpoint extends OpenAPIRoute {
schema = {
- summary: "Compose a agent-harness bot respose",
+ summary: "Compose an agent-harness bot response",
description:
- "Builds a response from the agent harness bot. Usually a simple quote + magic chip.",
+ "Builds an agent-harness announcement from a structured reply target and magic chip.",
request: {
body: {
content: {
diff --git a/services/lexical-service/src/endpoints/explicit-reply.ts b/services/lexical-service/src/endpoints/explicit-reply.ts
new file mode 100644
index 0000000000..51830326a8
--- /dev/null
+++ b/services/lexical-service/src/endpoints/explicit-reply.ts
@@ -0,0 +1,53 @@
+import { isExplicitReplyMarkdown } from "@macro-inc/lexical-core/utils/explicit-reply";
+import { OpenAPIRoute } from "chanfana";
+import type { Context } from "hono";
+import { z } from "zod";
+import { handleEndpointError } from "../lib/error-handler";
+import { standardErrorResponses } from "../lib/schemas";
+
+const explicitReplyRequest = z.object({
+ markdown: z.string(),
+});
+
+const explicitReplyResponse = z.object({
+ isExplicitReply: z.boolean(),
+});
+
+export class ExplicitReplyEndpoint extends OpenAPIRoute {
+ schema = {
+ summary: "Detect whether Markdown is an explicit reply",
+ description:
+ "Reports whether Macro Markdown begins with a ReplyTarget node followed by authored content. Standard blockquotes do not count as replies.",
+ request: {
+ body: {
+ content: {
+ "application/json": {
+ schema: explicitReplyRequest,
+ },
+ },
+ },
+ },
+ responses: {
+ 200: {
+ description: "Successfully evaluated the markdown",
+ content: {
+ "application/json": {
+ schema: explicitReplyResponse,
+ },
+ },
+ },
+ ...standardErrorResponses,
+ },
+ };
+
+ async handle(c: Context) {
+ try {
+ const { body } = await this.getValidatedData<typeof this.schema>();
+ return c.json({
+ isExplicitReply: isExplicitReplyMarkdown(body.markdown),
+ });
+ } catch (error) {
+ return handleEndpointError(error, c);
+ }
+ }
+}
diff --git a/services/lexical-service/src/endpoints/quote-reply.ts b/services/lexical-service/src/endpoints/quote-reply.ts
deleted file mode 100644
index 6d3073ac45..0000000000
--- a/services/lexical-service/src/endpoints/quote-reply.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { OpenAPIRoute } from 'chanfana';
-import type { Context } from 'hono';
-import { z } from 'zod';
-import { handleEndpointError } from '../lib/error-handler';
-import { standardErrorResponses } from '../lib/schemas';
-import { isQuoteReplyMarkdown } from '@macro-inc/lexical-core/utils/quote-reply';
-
-const quoteReplyRequest = z.object({
- markdown: z.string(),
-});
-
-const quoteReplyResponse = z.object({
- isQuoteReply: z.boolean(),
-});
-
-export class QuoteReplyEndpoint extends OpenAPIRoute {
- schema = {
- summary: 'Detect whether markdown is a quote-reply',
- description:
- 'Parses a macro markdown string as Lexical editor state and reports whether it is composed as a quote-reply: a leading blockquote quoting the replied-to message, followed by the reply itself.',
- request: {
- body: {
- content: {
- 'application/json': {
- schema: quoteReplyRequest,
- },
- },
- },
- },
- responses: {
- 200: {
- description: 'Successfully evaluated the markdown',
- content: {
- 'application/json': {
- schema: quoteReplyResponse,
- },
- },
- },
- ...standardErrorResponses,
- },
- };
-
- async handle(c: Context) {
- try {
- const { body } = await this.getValidatedData<typeof this.schema>();
- return c.json({ isQuoteReply: isQuoteReplyMarkdown(body.markdown) });
- } catch (error) {
- return handleEndpointError(error, c);
- }
- }
-}
diff --git a/services/lexical-service/src/index.ts b/services/lexical-service/src/index.ts
index 5bf37dc5b8..98420a9be9 100644
--- a/services/lexical-service/src/index.ts
+++ b/services/lexical-service/src/index.ts
@@ -11,7 +11,7 @@ import { MarkdownEndpoint } from "./endpoints/markdown";
import { MarkdownSnapshotEndpoint } from "./endpoints/markdown-snapshot";
import { MentionsEndpoint } from "./endpoints/mentions";
import { PlaintextEndpoint } from "./endpoints/plaintext";
-import { QuoteReplyEndpoint } from "./endpoints/quote-reply";
+import { ExplicitReplyEndpoint } from "./endpoints/explicit-reply";
import { SearchTextEndpoint } from "./endpoints/search-text";
import { XmlEndpoint } from "./endpoints/xml";
@@ -44,7 +44,7 @@ app.use("/xml/*", internalAuth);
app.use("/markdown/*", internalAuth);
app.use("/snapshot/*", internalAuth);
app.use("/mentions", internalAuth);
-app.use("/quote-reply", internalAuth);
+app.use("/explicit-reply", internalAuth);
app.use("/agent-announcement", internalAuth);
app.use("/agent-context", internalAuth);
app.use("/internal/health", internalAuth);
@@ -70,7 +70,7 @@ openapi.get("/markdown/:docId", MarkdownEndpoint);
openapi.get("/xml/:docId", XmlEndpoint);
openapi.post("/snapshot/markdown", MarkdownSnapshotEndpoint);
openapi.post("/mentions", MentionsEndpoint);
-openapi.post("/quote-reply", QuoteReplyEndpoint);
+openapi.post("/explicit-reply", ExplicitReplyEndpoint);
openapi.post("/agent-announcement", AgentAnnouncementEndpoint);
openapi.post("/agent-context", AgentContextEndpoint);
openapi.get("/internal/health", (c) => c.json({ status: "healthy" }));