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(agent): reply to selected transcript text as a referenced paste (#5996)

Wolf Mermelstein6f31c150768e
diff --git a/apps/web/src/features/block-agent/component/AgentComposer.tsx b/apps/web/src/features/block-agent/component/AgentComposer.tsx
index 3a7ebc1230..ab361eb012 100644
--- a/apps/web/src/features/block-agent/component/AgentComposer.tsx
+++ b/apps/web/src/features/block-agent/component/AgentComposer.tsx
@@ -15,8 +15,14 @@ import {
} from '../ui';
export function AgentComposer() {
- const { composer, loadFailed, metadata, pending, resuming } =
- useAgentSession();
+ const {
+ composer,
+ loadFailed,
+ metadata,
+ pending,
+ resuming,
+ registerQuoteInsert,
+ } = useAgentSession();
// A session still being created was created by this user, one action ago,
// and has an empty transcript: the only thing to do with it is type. The
@@ -43,6 +49,7 @@ export function AgentComposer() {
commands={() => metadata()?.availableCommands ?? []}
onSend={composer.send}
onStop={composer.stop}
+ registerQuoteInsert={registerQuoteInsert}
modelControl={
<AgentModelSelector
model={metadata()?.model ?? null}
diff --git a/apps/web/src/features/block-agent/component/ReplyToSelection.tsx b/apps/web/src/features/block-agent/component/ReplyToSelection.tsx
new file mode 100644
index 0000000000..a0e2c3beb1
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/ReplyToSelection.tsx
@@ -0,0 +1,81 @@
+/**
+ * ChatGPT / Claude-style quote-reply: selecting transcript text shows a
+ * "Reply to this" chip; choosing it hands the selected text to `onReply`
+ * (the composer inserts it as a referenced paste chip).
+ *
+ * Positioning is the same `floatWithSelection` directive the format / mention
+ * menus use. This component only decides when the chip is allowed to mount.
+ */
+
+import { floatWithSelection } from '@core/component/LexicalMarkdown/directive/floatWithSelection';
+import { ScopedPortal } from '@core/component/ScopedPortal';
+import { isMobile } from '@core/mobile/isMobile';
+import { debouncedDependent } from '@core/util/debounce';
+import Quote from '@phosphor/quotes.svg';
+import { createSignal, onCleanup, Show } from 'solid-js';
+import { readReplyableSelection } from '../state/reply-selection';
+
+false && floatWithSelection;
+
+export function ReplyToSelection(props: {
+ /** Selections outside this element (e.g. in the composer) are ignored. */
+ container: HTMLElement | undefined;
+ onReply: (text: string) => void;
+}) {
+ // On mobile the native selection toolbar takes this chip's place.
+ if (isMobile()) return '';
+
+ const [domSelection, setDomSelection] = createSignal<Selection>();
+ // Lag the appearance so the chip doesn't flash while a selection is being
+ // dragged out (same delay as the floating format menu).
+ const show = debouncedDependent(() => domSelection() !== undefined, 100);
+
+ const syncFromDocument = () => {
+ const replyable = readReplyableSelection(props.container);
+ setDomSelection(
+ replyable ? (document.getSelection() ?? undefined) : undefined
+ );
+ };
+
+ document.addEventListener('selectionchange', syncFromDocument);
+ onCleanup(() => {
+ document.removeEventListener('selectionchange', syncFromDocument);
+ });
+
+ const reply = () => {
+ const text = readReplyableSelection(props.container);
+ document.getSelection()?.removeAllRanges();
+ setDomSelection(undefined);
+ if (text) props.onReply(text);
+ };
+
+ return (
+ <Show when={show() && domSelection()}>
+ {(selection) => (
+ <ScopedPortal scope="block">
+ <button
+ type="button"
+ class="fixed top-0 left-0 z-highlight-menu flex items-center gap-1.5 rounded-full border border-edge bg-surface px-2.5 py-1 text-xs font-medium text-ink shadow-lg hover:overlay-hover"
+ use:floatWithSelection={{
+ selection: selection(),
+ reactiveOnContainer: props.container,
+ useBlockBoundary: true,
+ moveWithSelection: true,
+ floatingOptions: { placement: 'top' },
+ }}
+ on:mousedown={(event: MouseEvent) => {
+ // Keep the selection alive through the click: a default
+ // mousedown would collapse it, hiding the chip before the
+ // click lands and leaving nothing to quote.
+ event.preventDefault();
+ }}
+ onClick={reply}
+ >
+ <Quote class="size-3.5 shrink-0" />
+ Reply to this
+ </button>
+ </ScopedPortal>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/Transcript.tsx b/apps/web/src/features/block-agent/component/Transcript.tsx
index 891c49f9d7..82a9204d12 100644
--- a/apps/web/src/features/block-agent/component/Transcript.tsx
+++ b/apps/web/src/features/block-agent/component/Transcript.tsx
@@ -24,6 +24,7 @@ import { createSignal, onCleanup } from 'solid-js';
import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';
import { useAgentSession } from '../context/AgentSessionContext';
import { Message } from './AgentMessage';
+import { ReplyToSelection } from './ReplyToSelection';
/** The channel's `NEAR_BOTTOM_THRESHOLD`: within this, the view follows. */
const NEAR_BOTTOM_PX = 50;
@@ -33,13 +34,14 @@ const SETTLE_MS = 1000;
const ITEM_SIZE = 96;
export function Transcript() {
- const { messages } = useAgentSession();
+ const { messages, quoteSelection } = useAgentSession();
let scrollRef: HTMLDivElement | undefined;
let handle: VirtualizerHandle | undefined;
let cancelPin: (() => void) | undefined;
let growthObserver: ResizeObserver | undefined;
let viewportObserver: ResizeObserver | undefined;
+ const [transcriptEl, setTranscriptEl] = createSignal<HTMLDivElement>();
onCleanup(() => {
cancelPin?.();
@@ -157,7 +159,7 @@ export function Transcript() {
};
return (
- <div class="relative flex-1 min-h-0">
+ <div class="relative flex-1 min-h-0" ref={setTranscriptEl}>
<Scroll scrollRef={attachScroller}>
<div
class="flex flex-col [overflow-anchor:none]"
@@ -200,6 +202,7 @@ export function Transcript() {
scrollState={scrollState}
onScrollToBottom={pinToBottom}
/>
+ <ReplyToSelection container={transcriptEl()} onReply={quoteSelection} />
</div>
);
}
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index f8351df4cf..6fbfba60e8 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -25,6 +25,7 @@ import {
useContext,
} from 'solid-js';
import { controlOutcome } from '../state/control-message';
+import type { QuoteInsert } from '../ui';
import { createAgentSessionFeed } from './create-agent-session-feed';
import {
type ComposerController,
@@ -83,6 +84,13 @@ export type AgentSessionState = {
*/
resuming: Accessor<boolean>;
composer: ComposerController;
+ /**
+ * Quote selected transcript text into the composer as a referenced paste
+ * chip. No-op until the composer editor has mounted.
+ */
+ quoteSelection: QuoteInsert;
+ /** The composer registers its quote-insert handler here on mount. */
+ registerQuoteInsert: (insert: QuoteInsert | undefined) => void;
};
const AgentSessionCtx = createContext<AgentSessionState>();
@@ -118,6 +126,15 @@ export function AgentSessionProvider(
controlOutcome: (requestId) => controlOutcome(feed.messages(), requestId),
});
+ // The transcript's "Reply to this" chip hands selected text to the
+ // composer through here. A plain variable, not a signal: it is only read
+ // at call time, never rendered from.
+ let quoteInsert: QuoteInsert | undefined;
+ const registerQuoteInsert = (insert: QuoteInsert | undefined) => {
+ quoteInsert = insert;
+ };
+ const quoteSelection: QuoteInsert = (text) => quoteInsert?.(text);
+
// Anything the service can only deliver over a live transport: a prompt on
// the wire, or a model change waiting to be seen in the fold.
const awaitingRuntime = () =>
@@ -143,6 +160,8 @@ export function AgentSessionProvider(
status: status.status,
resuming,
composer,
+ quoteSelection,
+ registerQuoteInsert,
}}
>
{props.children}
diff --git a/apps/web/src/features/block-agent/debug/Gallery.tsx b/apps/web/src/features/block-agent/debug/Gallery.tsx
index ff7a334754..28b81d9c84 100644
--- a/apps/web/src/features/block-agent/debug/Gallery.tsx
+++ b/apps/web/src/features/block-agent/debug/Gallery.tsx
@@ -11,6 +11,7 @@ import type {
} from '@service-agent-fold/generated/types';
import { createSignal, type JSX, onCleanup } from 'solid-js';
import { Message } from '../component/AgentMessage';
+import { ReplyToSelection } from '../component/ReplyToSelection';
import {
ActionLine,
AgentInput,
@@ -20,6 +21,7 @@ import {
DiffChanges,
PierreDiff,
QuestionAnswers,
+ type QuoteInsert,
TextShimmer,
Thought,
TodoList,
@@ -39,6 +41,37 @@ function Item(props: { label: string; children: JSX.Element }) {
);
}
+/**
+ * Select text in the fixture message: a "Reply to this" chip should appear
+ * and insert a referenced paste into the composer below.
+ */
+function ReplyToSelectionDemo() {
+ const [container, setContainer] = createSignal<HTMLDivElement>();
+ let quoteInsert: QuoteInsert | undefined;
+
+ return (
+ <div class="flex flex-col gap-3">
+ <p class="text-xs text-ink-muted">
+ Select any of the message text, then click Reply to this.
+ </p>
+ <div ref={setContainer} class="relative">
+ <Message message={FIXTURE_MESSAGE} />
+ <ReplyToSelection
+ container={container()}
+ onReply={(text) => quoteInsert?.(text)}
+ />
+ </div>
+ <AgentInput
+ placeholder="Referenced text lands here"
+ onSend={(content) => console.info('[gallery] send', content)}
+ registerQuoteInsert={(insert) => {
+ quoteInsert = insert;
+ }}
+ />
+ </div>
+ );
+}
+
/** Flips every few seconds so the running→done animations stay observable. */
function usePulse(intervalMs = 2500) {
const [on, setOn] = createSignal(true);
@@ -265,6 +298,10 @@ export default function AgentUiGallery() {
</div>
</Item>
+ <Item label="Reply to selection">
+ <ReplyToSelectionDemo />
+ </Item>
+
<Item label="AgentInput (idle / busy)">
<AgentInput
onSend={(content) => console.info('[gallery] send', content)}
diff --git a/apps/web/src/features/block-agent/state/reply-selection.test.ts b/apps/web/src/features/block-agent/state/reply-selection.test.ts
new file mode 100644
index 0000000000..6f9ac9c406
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/reply-selection.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+import { normalizeReplySelection, selectionIsInside } from './reply-selection';
+
+describe('normalizeReplySelection', () => {
+ it('trims whitespace and nbsp', () => {
+ expect(normalizeReplySelection(' hello world ')).toBe('hello world');
+ expect(normalizeReplySelection('\u00a0quoted\u00a0')).toBe('quoted');
+ });
+
+ it('rejects whitespace-only selections', () => {
+ expect(normalizeReplySelection(' \n\t ')).toBeUndefined();
+ expect(normalizeReplySelection('\u00a0')).toBeUndefined();
+ expect(normalizeReplySelection('')).toBeUndefined();
+ });
+});
+
+describe('selectionIsInside', () => {
+ it('requires the common ancestor to live in the container', () => {
+ const container = document.createElement('div');
+ const outside = document.createElement('div');
+ const inside = document.createElement('span');
+ inside.textContent = 'quoted';
+ container.append(inside);
+ document.body.append(container, outside);
+
+ const inRange = document.createRange();
+ inRange.selectNodeContents(inside);
+ expect(selectionIsInside(container, inRange)).toBe(true);
+
+ outside.textContent = 'nope';
+ const outRange = document.createRange();
+ outRange.selectNodeContents(outside);
+ expect(selectionIsInside(container, outRange)).toBe(false);
+
+ container.remove();
+ outside.remove();
+ });
+});
diff --git a/apps/web/src/features/block-agent/state/reply-selection.ts b/apps/web/src/features/block-agent/state/reply-selection.ts
new file mode 100644
index 0000000000..3aad602219
--- /dev/null
+++ b/apps/web/src/features/block-agent/state/reply-selection.ts
@@ -0,0 +1,28 @@
+/**
+ * Whether a native text selection is a quote-reply candidate: non-empty,
+ * non-collapsed, and fully inside the transcript container.
+ */
+
+export function normalizeReplySelection(text: string): string | undefined {
+ const trimmed = text.replace(/\u00a0/g, ' ').trim();
+ return trimmed.length > 0 ? trimmed : undefined;
+}
+
+export function selectionIsInside(
+ container: Node | null | undefined,
+ range: Range
+): boolean {
+ if (!container) return false;
+ return container.contains(range.commonAncestorContainer);
+}
+
+export function readReplyableSelection(
+ container: Node | null | undefined
+): string | undefined {
+ if (!container) return undefined;
+ const sel = document.getSelection();
+ if (!sel || sel.isCollapsed || sel.rangeCount === 0) return undefined;
+ const range = sel.getRangeAt(0);
+ if (!selectionIsInside(container, range)) return undefined;
+ return normalizeReplySelection(sel.toString());
+}
diff --git a/apps/web/src/features/block-agent/ui/AgentInput.tsx b/apps/web/src/features/block-agent/ui/AgentInput.tsx
index 956be4186c..d49a7869b3 100644
--- a/apps/web/src/features/block-agent/ui/AgentInput.tsx
+++ b/apps/web/src/features/block-agent/ui/AgentInput.tsx
@@ -9,8 +9,12 @@
import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';
import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';
import type { AgentCommandItem } from '@core/component/LexicalMarkdown/plugins';
+import { $insertReferencedPaste } from '@macro-inc/lexical-core';
import { Button, SendButton, Surface } from '@ui';
-import { createSignal, type JSX, Show } from 'solid-js';
+import { createSignal, type JSX, onCleanup, onMount, Show } from 'solid-js';
+
+/** Quote text into the composer as a referenced paste chip. */
+export type QuoteInsert = (text: string) => void;
export interface AgentInputProps {
placeholder?: string;
@@ -28,6 +32,12 @@ export interface AgentInputProps {
onStop?: () => void;
/** Sits as a pill above the input box, e.g. the session's model selector. */
modelControl?: JSX.Element;
+ /**
+ * Ref-style: receives the quote-insert function once the editor mounts
+ * (and `undefined` again on unmount), so the transcript's "Reply to this"
+ * chip can quote selected text into this composer.
+ */
+ registerQuoteInsert?: (insert: QuoteInsert | undefined) => void;
}
/** Past this height the controls drop below the text instead of overlaying it. */
@@ -70,6 +80,17 @@ export function AgentInput(props: AgentInputProps) {
})
.onChange(setMarkdown);
+ onMount(() => {
+ props.registerQuoteInsert?.((text) => {
+ // Discrete so the chip is committed to the DOM before focus moves in.
+ editor.lexical.update(() => $insertReferencedPaste(text), {
+ discrete: true,
+ });
+ editor.controls.focus();
+ });
+ onCleanup(() => props.registerQuoteInsert?.(undefined));
+ });
+
return (
<div class="flex flex-col gap-1.5">
{/* Above the surface rather than inside it: the pill belongs to the
diff --git a/apps/web/src/features/block-agent/ui/index.ts b/apps/web/src/features/block-agent/ui/index.ts
index 8da6b88a3b..3486b3ae38 100644
--- a/apps/web/src/features/block-agent/ui/index.ts
+++ b/apps/web/src/features/block-agent/ui/index.ts
@@ -7,7 +7,11 @@
*/
export { ActionLine, type ActionLineProps } from './ActionLine';
-export { AgentInput, type AgentInputProps } from './AgentInput';
+export {
+ AgentInput,
+ type AgentInputProps,
+ type QuoteInsert,
+} from './AgentInput';
export { AgentModelSelector } from './AgentModelSelector';
export { AnimatedNumber } from './AnimatedNumber';
export {
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx
index 345cd517fb..431cc44607 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/PasteNode.tsx
@@ -20,8 +20,9 @@ import { removeNodeAndRestoreSelection } from '../../plugins/shared/removeNodeAn
/**
* Block-level decorator for a {@link PasteNode}. Renders a compact collapsed
* monospace preview that looks like a code fence and fades to the background
- * color at the bottom, with a "pasted" pill in the bottom-left and a hamburger
- * menu floating in the top-right (Convert to text / Delete). Clicking the node
+ * color at the bottom, with a "pasted" / "referenced" pill in the bottom-left
+ * and a hamburger menu floating in the top-right (Convert to text / Delete).
+ * Clicking the node
* opens the full text styled like a code fence: a scrollable popup on desktop
* and a bottom drawer on mobile, both dismissable with `esc` or by clicking
* outside. Mirrors the DocumentCard.
@@ -34,6 +35,11 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
const [open, setOpen] = createSignal(false);
const [menuOpen, setMenuOpen] = createSignal(false);
+ // The origin value doubles as the pill label: "pasted" or "referenced".
+ const origin = () => props.origin ?? 'pasted';
+ const originTitle = () =>
+ origin() === 'referenced' ? 'Referenced text' : 'Pasted text';
+
const isSelectedAsNode = () => {
const sel = selection();
if (!sel) return false;
@@ -63,7 +69,7 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
const copyText = () => {
try {
navigator.clipboard.writeText(props.content);
- toast.success('Copied pasted text to clipboard');
+ toast.success(`Copied ${origin()} text to clipboard`);
} catch (e) {
console.error('Failed to copy pasted text to clipboard', e);
}
@@ -112,9 +118,10 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
<div class="pointer-events-none absolute inset-x-0 bottom-0 h-16 bg-gradient-to-b from-transparent to-message" />
</div>
- {/* "pasted" pill floating bottom-left. */}
+ {/* Origin pill floating bottom-left: "pasted" for clipboard dumps,
+ "referenced" for quote-replies from selected conversation text. */}
<span class="absolute bottom-2 left-2 inline-flex items-center px-2 py-1 text-xs leading-none rounded-full border border-edge bg-surface">
- pasted
+ {origin()}
</span>
{/* Hamburger menu floating top-right. Hidden in static / read-only
@@ -163,7 +170,7 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
class="rounded-lg border border-edge bg-surface shadow-lg"
>
<div class="flex items-center justify-between px-4 py-2 border-b border-edge text-xs text-ink-muted">
- <span>Pasted text</span>
+ <span>{originTitle()}</span>
<div class="flex items-center gap-2">
<span>{lineLabel()}</span>
<Button
@@ -184,10 +191,10 @@ export function PasteNode(props: PasteNodeDecoratorProps) {
<MobileDrawer side="bottom" open={open()} onOpenChange={setOpen}>
<MobileDrawer.Portal>
<MobileDrawer.Overlay class="fixed inset-0 z-modal-overlay bg-modal-overlay pattern-diagonal-4 pattern-edge-muted" />
- <MobileDrawer.Content aria-label="Pasted text">
+ <MobileDrawer.Content aria-label={originTitle()}>
<MobileDrawer.Handle />
<div class="flex items-center justify-between px-4 pb-2 text-xs text-ink-muted shrink-0">
- <span>Pasted text</span>
+ <span>{originTitle()}</span>
<div class="flex items-center gap-2">
<span>{lineLabel()}</span>
<Button
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts b/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts
index f9b5a42724..3302dc5fd3 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/directive/floatWithSelection.ts
@@ -80,11 +80,18 @@ export function floatWithSelection(
if (anchor) {
setCurrentAnchor(anchor);
const spacing = accessor()?.spacing ?? DEFAULT_SPACING;
+ const floatingOptions = accessor()?.floatingOptions ?? {};
+ const preferredPlacement = floatingOptions.placement ?? 'bottom-start';
const { placement } = await computePosition(anchor, floatingEl, {
- placement: 'bottom-start',
+ placement: preferredPlacement,
middleware: [
flip({
- fallbackPlacements: ['top-start'],
+ // Default menus sit below the caret and flip above. A caller that
+ // asked for another side (e.g. `placement: 'top'`) should flip to
+ // the opposite side instead of being stuck on `top-start`.
+ ...(preferredPlacement === 'bottom-start'
+ ? { fallbackPlacements: ['top-start'] as const }
+ : {}),
boundary,
padding: iosSafePadding(spacing),
}),
@@ -92,6 +99,7 @@ export function floatWithSelection(
shift({ padding: spacing, boundary }),
hide(),
],
+ ...floatingOptions,
});
decidedPlacement = placement;
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
index 6264824920..afa1990026 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/version.ts
@@ -16,5 +16,6 @@
* Version 2.3 - Jul 15, 2026. Added TagMentionNode.
* 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.
*/
-export const MARKDOWN_VERSION_COUNTER = 2.5;
+export const MARKDOWN_VERSION_COUNTER = 2.6;
diff --git a/packages/lexical-core/nodes/PasteNode.ts b/packages/lexical-core/nodes/PasteNode.ts
index e92908d24b..d1447c9dc6 100644
--- a/packages/lexical-core/nodes/PasteNode.ts
+++ b/packages/lexical-core/nodes/PasteNode.ts
@@ -3,6 +3,8 @@ import { $unwrapNode } from '@lexical/utils';
import {
$applyNodeReplacement,
$createParagraphNode,
+ $getRoot,
+ $isElementNode,
type DOMConversionMap,
type EditorConfig,
type EditorThemeClasses,
@@ -19,8 +21,18 @@ import { DecoratorBlockNode } from './DecoratorBlockNode';
const VERSION = 1;
+export const PASTE_ORIGINS = ['pasted', 'referenced'] as const;
+export type PasteOrigin = (typeof PASTE_ORIGINS)[number];
+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
+ * selected conversation text. Defaults to `pasted` so existing documents
+ * keep their original label.
+ */
+ origin?: PasteOrigin;
};
export type SerializedPasteNode = Spread<PasteNodeData, SerializedLexicalNode>;
@@ -30,16 +42,23 @@ export type PasteNodeDecoratorProps = PasteNodeData & {
theme: EditorThemeClasses;
};
+/** Coerce unknown serialized/DOM values to a known origin. */
+export function normalizePasteOrigin(value: unknown): PasteOrigin {
+ return value === 'referenced' ? 'referenced' : DEFAULT_PASTE_ORIGIN;
+}
+
/**
- * A block-level node that holds a large chunk of pasted plain text. It renders
- * a collapsed monospace preview (like a code fence) that fades out at the
- * bottom and can be expanded into a popup with the full text, mirroring the
- * Anthropic "pasted" chip. Structurally it follows {@link DocumentCardNode}.
+ * A block-level node that holds a large chunk of pasted or referenced plain
+ * text. It renders a collapsed monospace preview (like a code fence) that fades
+ * out at the bottom and can be expanded into a popup with the full text,
+ * mirroring the Anthropic "pasted" chip. Structurally it follows
+ * {@link DocumentCardNode}.
*/
export class PasteNode extends DecoratorBlockNode<
DecoratorComponent<PasteNodeDecoratorProps> | undefined
> {
__content: string;
+ __origin: PasteOrigin;
static getType() {
return 'paste';
@@ -50,17 +69,23 @@ export class PasteNode extends DecoratorBlockNode<
}
static clone(node: PasteNode) {
- return new PasteNode(node.__content, node.__key);
+ return new PasteNode(node.__content, node.__origin, node.__key);
}
- constructor(content: string, key?: NodeKey) {
+ constructor(
+ content: string,
+ origin: PasteOrigin = DEFAULT_PASTE_ORIGIN,
+ key?: NodeKey
+ ) {
super('center', key);
this.__content = content;
+ this.__origin = origin;
}
static importJSON(serializedNode: SerializedPasteNode) {
const node = $createPasteNode({
content: serializedNode.content,
+ origin: normalizePasteOrigin(serializedNode.origin),
});
$applyIdFromSerialized(node, serializedNode);
return node;
@@ -70,6 +95,7 @@ export class PasteNode extends DecoratorBlockNode<
return {
...super.exportJSON(),
content: this.__content,
+ origin: this.__origin,
type: PasteNode.getType(),
version: VERSION,
};
@@ -78,6 +104,7 @@ export class PasteNode extends DecoratorBlockNode<
exportComponentProps(): PasteNodeData {
return {
content: this.__content,
+ origin: this.__origin,
};
}
@@ -98,7 +125,10 @@ export class PasteNode extends DecoratorBlockNode<
return null;
}
const content = domNode.getAttribute('data-content') || '';
- const node = $createPasteNode({ content });
+ const origin = normalizePasteOrigin(
+ domNode.getAttribute('data-paste-origin')
+ );
+ const node = $createPasteNode({ content, origin });
return { node };
};
@@ -118,6 +148,7 @@ export class PasteNode extends DecoratorBlockNode<
return {
'data-paste-node': 'true',
'data-content': this.__content,
+ 'data-paste-origin': this.__origin,
};
}
@@ -150,12 +181,22 @@ export class PasteNode extends DecoratorBlockNode<
writable.__content = content;
}
+ getOrigin(): PasteOrigin {
+ return this.__origin;
+ }
+
+ setOrigin(origin: PasteOrigin) {
+ const writable = this.getWritable();
+ writable.__origin = origin;
+ }
+
decorate(_: LexicalEditor, config: EditorConfig) {
const decorator = getDecorator<PasteNodeDecoratorProps>(PasteNode);
if (decorator) {
return () =>
decorator({
content: this.__content,
+ origin: this.__origin,
key: this.getKey(),
theme: config.theme,
});
@@ -164,7 +205,10 @@ export class PasteNode extends DecoratorBlockNode<
}
export function $createPasteNode(params: PasteNodeData): PasteNode {
- const node = new PasteNode(params.content);
+ const node = new PasteNode(
+ params.content,
+ normalizePasteOrigin(params.origin)
+ );
return $applyNodeReplacement(node);
}
@@ -190,3 +234,44 @@ export function $convertPasteToText(pasteNode: PasteNode): void {
$unwrapNode(wrapper);
lastChild?.selectEnd();
}
+
+/**
+ * Insert a referenced paste chip at the top of the document, stacking above
+ * any existing paste chips and the user's draft, then put the caret in the
+ * first non-paste block so they can type a reply. No-op for whitespace-only
+ * content.
+ */
+export function $insertReferencedPaste(content: string): void {
+ const trimmed = content.trim();
+ if (!trimmed) return;
+
+ const root = $getRoot();
+ const node = $createPasteNode({
+ content: trimmed,
+ origin: 'referenced',
+ });
+
+ const first = root.getFirstChild();
+ if (first) {
+ first.insertBefore(node);
+ } else {
+ root.append(node);
+ }
+
+ // Skip past any chips already stacked below to find the draft.
+ let lastPaste: PasteNode = node;
+ let next = lastPaste.getNextSibling();
+ while ($isPasteNode(next)) {
+ lastPaste = next;
+ next = lastPaste.getNextSibling();
+ }
+
+ if ($isElementNode(next)) {
+ next.selectEnd();
+ return;
+ }
+
+ const paragraph = $createParagraphNode();
+ lastPaste.insertAfter(paragraph);
+ paragraph.selectEnd();
+}
diff --git a/packages/lexical-core/tests/paste.test.ts b/packages/lexical-core/tests/paste.test.ts
index 1587bfe876..5b9ae13af0 100644
--- a/packages/lexical-core/tests/paste.test.ts
+++ b/packages/lexical-core/tests/paste.test.ts
@@ -2,12 +2,18 @@ import {
$convertFromMarkdownString,
$convertToMarkdownString,
} from '@lexical/markdown';
-import { $getRoot, createEditor } from 'lexical';
+import {
+ $createParagraphNode,
+ $createTextNode,
+ $getRoot,
+ createEditor,
+} from 'lexical';
import { describe, expect, it } from 'vitest';
import { SupportedNodeTypes } from '../node-list';
import {
$convertPasteToText,
$createPasteNode,
+ $insertReferencedPaste,
$isPasteNode,
} from '../nodes/PasteNode';
import { EXTERNAL_TRANSFORMERS, INTERNAL_TRANSFORMERS } from '../transformers';
@@ -59,6 +65,74 @@ describe('PasteNode - internal transformer round-trip', () => {
const node = root.getChildren().find($isPasteNode);
expect(node).toBeDefined();
expect(node?.getContent()).toBe(content);
+ expect(node?.getOrigin()).toBe('pasted');
+ });
+ });
+
+ it('round-trips a referenced origin', async () => {
+ const editor = makeEditor();
+ const content = 'quoted from the agent';
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ root.append($createPasteNode({ content, origin: 'referenced' }));
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ let markdown = '';
+ editor.getEditorState().read(() => {
+ markdown = $convertToMarkdownString(INTERNAL_TRANSFORMERS);
+ });
+
+ expect(markdown).toContain('"origin":"referenced"');
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ $convertFromMarkdownString(markdown, INTERNAL_TRANSFORMERS);
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor.getEditorState().read(() => {
+ const node = $getRoot().getChildren().find($isPasteNode);
+ expect(node?.getContent()).toBe(content);
+ expect(node?.getOrigin()).toBe('referenced');
+ });
+ });
+
+ it('defaults missing origin to pasted', async () => {
+ const editor = makeEditor();
+ const payload = JSON.stringify({ content: 'legacy paste' })
+ .replace(/</g, '\\u003c')
+ .replace(/>/g, '\\u003e');
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ $convertFromMarkdownString(
+ `<m-paste>${payload}</m-paste>`,
+ INTERNAL_TRANSFORMERS
+ );
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor.getEditorState().read(() => {
+ const node = $getRoot().getChildren().find($isPasteNode);
+ expect(node?.getContent()).toBe('legacy paste');
+ expect(node?.getOrigin()).toBe('pasted');
});
});
@@ -190,3 +264,50 @@ describe('PasteNode - convert to text', () => {
expect(markdown).toContain('- two');
});
});
+
+describe('PasteNode - insert referenced', () => {
+ it('inserts a referenced chip above an existing draft', async () => {
+ const editor = makeEditor();
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ const root = $getRoot();
+ root.clear();
+ const draft = $createParagraphNode();
+ draft.append($createTextNode('what about this?'));
+ root.append(draft);
+ $insertReferencedPaste('the quoted line');
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor.getEditorState().read(() => {
+ const children = $getRoot().getChildren();
+ const chip = children[0];
+ expect($isPasteNode(chip)).toBe(true);
+ if (!$isPasteNode(chip)) return;
+ expect(chip.getOrigin()).toBe('referenced');
+ expect(chip.getContent()).toBe('the quoted line');
+ expect(children[1]?.getTextContent()).toBe('what about this?');
+ });
+ });
+
+ it('ignores whitespace-only content', async () => {
+ const editor = makeEditor();
+
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $insertReferencedPaste(' \n');
+ },
+ { onUpdate: () => resolve() }
+ );
+ });
+
+ editor.getEditorState().read(() => {
+ expect($getRoot().getChildren().some($isPasteNode)).toBe(false);
+ });
+ });
+});
diff --git a/packages/lexical-core/transformers/paste.ts b/packages/lexical-core/transformers/paste.ts
index c66e716563..7c0fffbfec 100644
--- a/packages/lexical-core/transformers/paste.ts
+++ b/packages/lexical-core/transformers/paste.ts
@@ -1,6 +1,11 @@
import type { ElementTransformer } from '@lexical/markdown';
import type { ElementNode, LexicalNode } from 'lexical';
-import { $createPasteNode, $isPasteNode, PasteNode } from '../nodes/PasteNode';
+import {
+ $createPasteNode,
+ $isPasteNode,
+ normalizePasteOrigin,
+ PasteNode,
+} from '../nodes/PasteNode';
import {
replaceElementWithUnknownMention,
UnknownMentionNode,
@@ -19,6 +24,7 @@ export const I_PASTE_NODE: ElementTransformer = {
if (!$isPasteNode(node)) return null;
const data = JSON.stringify({
content: node.getContent(),
+ origin: node.getOrigin(),
})
.replace(/</g, '\\u003c')
.replace(/>/g, '\\u003e');
@@ -32,7 +38,10 @@ export const I_PASTE_NODE: ElementTransformer = {
try {
const data = JSON.parse(match[1]);
if (!('content' in data)) throw new Error('Missing field content');
- const pasteNode = $createPasteNode({ content: data.content });
+ const pasteNode = $createPasteNode({
+ content: data.content,
+ origin: normalizePasteOrigin(data.origin),
+ });
parentNode.replace(pasteNode);
} catch (e) {
console.error('Error in I_PASTE_NODE replace:', e);