Skip to content

Commit 1a8ecc6

Browse files
authored
feat(web): a quote in a sent message shows as an inset card (#34181)
Co-authored-by: maria-rcks <[email protected]>
1 parent 0318ead commit 1a8ecc6

8 files changed

Lines changed: 122 additions & 97 deletions

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ import { defaultUrlTransform } from "react-markdown";
9696
import { parseAssistantCitationHref } from "@t3tools/shared/assistantCitations";
9797
import { parseComposerContextHref } from "@t3tools/shared/composerContextReferences";
9898
import { parseThreadLinkHref } from "@t3tools/shared/threadLinks";
99-
import { AssistantCitationChip } from "./chat/AssistantCitationChip";
99+
import { AssistantCitationEmbed } from "./chat/AssistantCitationChip";
100100
import { MarkdownThreadLink } from "./chat/MarkdownThreadLink";
101101
import { mathKind } from "@t3tools/shared/markdownMath";
102102
import remarkMath from "remark-math";
@@ -964,6 +964,15 @@ const ChatMarkdownRendererContext = React.createContext<
964964
// Isolate streamed source text from the renderer context; only offset-based renderers need it.
965965
const ChatMarkdownTextContext = React.createContext("");
966966

967+
// A quote card is a block. These say nothing else shares its paragraph or list item on that side.
968+
const LIST_MARKER = String.raw`(?:[-*+]|\d+[.)])[ \t]+`;
969+
const CITATION_LEADS_BLOCK = new RegExp(
970+
String.raw`(?:(?:^|\n[ \t]*\n)[ \t>]*(?:${LIST_MARKER})?|\n[ \t>]*${LIST_MARKER})$`,
971+
);
972+
const CITATION_ENDS_BLOCK = new RegExp(
973+
String.raw`^[ \t]*(?:$|\n[ \t]*(?:\n|$)|\n[ \t>]*${LIST_MARKER})`,
974+
);
975+
967976
function markdownHeadingRenderer(level: 1 | 2 | 3 | 4 | 5 | 6) {
968977
const Tag = `h${level}` as const;
969978
return function MarkdownHeading({
@@ -1108,7 +1117,17 @@ const CHAT_MARKDOWN_COMPONENTS = {
11081117
} = use(ChatMarkdownRendererContext);
11091118
const text = use(ChatMarkdownTextContext);
11101119
const citation = href ? parseAssistantCitationHref(href) : null;
1111-
if (citation) return <AssistantCitationChip citation={citation} />;
1120+
if (citation) {
1121+
const before = node?.position?.start.offset;
1122+
const after = node?.position?.end.offset;
1123+
return (
1124+
<AssistantCitationEmbed
1125+
citation={citation}
1126+
leading={before !== undefined && CITATION_LEADS_BLOCK.test(text.slice(0, before))}
1127+
trailing={after !== undefined && CITATION_ENDS_BLOCK.test(text.slice(after))}
1128+
/>
1129+
);
1130+
}
11121131
const threadLink = href ? parseThreadLinkHref(href) : null;
11131132
if (threadLink) {
11141133
const written = hastPlainTextDeep(node);

‎apps/web/src/components/ComposerPromptEditorTiptap.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -523,7 +523,6 @@ function ComposerCitationNodeView({ node, editor, getPos }: NodeViewProps) {
523523
>
524524
<AssistantCitationChip
525525
citation={citation}
526-
composer
527526
commentEditor={{
528527
open: commentTarget !== null,
529528
sourceAnchor: commentTarget?.sourceAnchor,

‎apps/web/src/components/chat/AssistantCitationChip.browser.test.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,6 @@ function mount(
6161
return (
6262
<AssistantCitationChip
6363
citation={chipCitation}
64-
composer
6564
commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
6665
/>
6766
);

‎apps/web/src/components/chat/AssistantCitationChip.tsx‎

Lines changed: 78 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import {
55
serializeAssistantCitation,
66
} from "@t3tools/shared/assistantCitations";
77
import { Link, useNavigate } from "@tanstack/react-router";
8-
import { ArrowUpRightIcon, PencilIcon, QuoteIcon } from "lucide-react";
8+
import { PencilIcon, QuoteIcon } from "lucide-react";
99
import {
1010
useEffect,
1111
useEffectEvent,
@@ -24,24 +24,93 @@ import {
2424
import { cn } from "~/lib/utils";
2525
import { useQuietThreadShell } from "~/state/entities";
2626
import { ContextChip, ContextChipAction, ContextChipLabel } from "../ContextChip";
27-
import { ContextChipPopover } from "../contextChipParts";
28-
import { Button } from "../ui/button";
29-
import { Popover, PopoverClose, PopoverPopup, PopoverTrigger } from "../ui/popover";
30-
import { getVirtualizedScrollFadeClassName } from "../ui/scroll-area";
27+
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
3128
import { AssistantCitationCommentEditor } from "./AssistantCitationCommentEditor";
3229
import { resolveAssistantCitationCommentDismissal } from "./assistantCitationCommentDismissal";
3330
import { observeAssistantCitationCommentSource } from "./AssistantCitationSource";
3431
import { composerFloatingLayerProps } from "./composerEventScope";
35-
import { observeResize } from "~/lib/observeResize";
3632
import { textDirection } from "~/textDirection";
3733

34+
function useCitationSourceLinkProps(citation: AssistantCitation) {
35+
const navigate = useNavigate();
36+
const sourceThread = useQuietThreadShell(
37+
scopeThreadRef(citation.environmentId, citation.threadId),
38+
);
39+
return {
40+
...assistantCitationRoute(citation, sourceThread),
41+
"data-markdown-copy": serializeAssistantCitation(citation),
42+
onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
43+
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
44+
return;
45+
}
46+
event.preventDefault();
47+
void navigate(assistantCitationNavigation(citation, sourceThread));
48+
},
49+
};
50+
}
51+
52+
/**
53+
* A quoted response inside a message. Clicking it goes to the source; its comment follows as
54+
* text. `leading` and `trailing` say it starts or ends its block, which already has spacing.
55+
*/
56+
export function AssistantCitationEmbed({
57+
citation,
58+
leading,
59+
trailing,
60+
}: {
61+
citation: AssistantCitation;
62+
leading: boolean;
63+
trailing: boolean;
64+
}) {
65+
const wholeResponse = citation.prefix === "" && citation.suffix === "";
66+
const flat = (text: string) => text.replace(/\s+/g, " ");
67+
const { comment, ...quoted } = citation;
68+
const linkProps = useCitationSourceLinkProps(citation);
69+
return (
70+
// One copy boundary for the card and its comment, so a copied quote carries the comment once.
71+
<span
72+
data-markdown-copy={linkProps["data-markdown-copy"]}
73+
className={cn("block", !leading && "mt-[0.65rem]", !trailing && "mb-[0.65rem]")}
74+
>
75+
<Link
76+
{...linkProps}
77+
// A selection inside the card's boundary copies the quote here and the comment as text.
78+
data-markdown-copy={serializeAssistantCitation(quoted)}
79+
// The quote is findable in its source message; here it is clamped and mostly hidden.
80+
data-thread-find-ignore
81+
aria-label={`Go to quoted response: ${assistantCitationLabel(quoted)}`}
82+
// The message's markdown styles colour and underline links; a quote is neither.
83+
className="block min-w-0 rounded-lg bg-black/10 px-2.5 py-1.5 text-start text-sm text-muted-foreground! no-underline! wrap-break-word hover:bg-black/14 focus-visible:outline-2 focus-visible:outline-ring dark:bg-black/35 dark:hover:bg-black/50"
84+
>
85+
<span className="line-clamp-2" dir={textDirection(citation.text)}>
86+
{wholeResponse ? (
87+
flat(citation.text)
88+
) : (
89+
<>
90+
{citation.prefix ? `…${flat(citation.prefix)}` : null}
91+
<mark className="rounded-sm bg-foreground/12 px-0.5 text-foreground">
92+
{flat(citation.text)}
93+
</mark>
94+
{citation.suffix ? `${flat(citation.suffix)}…` : null}
95+
</>
96+
)}
97+
</span>
98+
</Link>
99+
{comment ? (
100+
<span className="mt-1.5 block whitespace-pre-wrap" dir={textDirection(comment)}>
101+
{comment}
102+
</span>
103+
) : null}
104+
</span>
105+
);
106+
}
107+
108+
/** The citation chip in the composer, with its comment editor. */
38109
export function AssistantCitationChip({
39110
citation,
40-
composer = false,
41111
commentEditor,
42112
}: {
43113
citation: AssistantCitation;
44-
composer?: boolean;
45114
commentEditor?: {
46115
open: boolean;
47116
sourceAnchor?: AssistantCitationSourceAnchor | undefined;
@@ -53,10 +122,7 @@ export function AssistantCitationChip({
53122
onRestoreFocus?: () => void;
54123
};
55124
}) {
56-
const navigate = useNavigate();
57-
const sourceThread = useQuietThreadShell(
58-
scopeThreadRef(citation.environmentId, citation.threadId),
59-
);
125+
const sourceLinkProps = useCitationSourceLinkProps(citation);
60126
const commentInputRef = useRef<HTMLTextAreaElement>(null);
61127
const commentPopupRef = useRef<HTMLDivElement>(null);
62128
const draftCommentRef = useRef<string | null>(null);
@@ -116,17 +182,6 @@ export function AssistantCitationChip({
116182
}
117183
: undefined;
118184
const label = assistantCitationLabel(citation);
119-
const sourceLinkProps = {
120-
...assistantCitationRoute(citation, sourceThread),
121-
"data-markdown-copy": serializeAssistantCitation(citation),
122-
onClick: (event: ReactMouseEvent<HTMLAnchorElement>) => {
123-
if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
124-
return;
125-
}
126-
event.preventDefault();
127-
void navigate(assistantCitationNavigation(citation, sourceThread));
128-
},
129-
};
130185
const composerSourceLink = (
131186
<Link
132187
{...sourceLinkProps}
@@ -139,27 +194,6 @@ export function AssistantCitationChip({
139194
</ContextChipLabel>
140195
</Link>
141196
);
142-
if (!composer) {
143-
return (
144-
<ContextChipPopover
145-
kind="citation"
146-
icon={<QuoteIcon />}
147-
label={label}
148-
accessibleLabel={`Quoted assistant text: ${label}`}
149-
copyMarkdown={serializeAssistantCitation(citation)}
150-
>
151-
<div className="flex max-h-[calc(var(--available-height)_-_1rem_-_2px)] flex-col items-start gap-3 p-1 text-sm">
152-
<AssistantCitationQuote citation={citation} />
153-
<PopoverClose
154-
render={<Button variant="outline" size="sm" render={<Link {...sourceLinkProps} />} />}
155-
>
156-
<ArrowUpRightIcon aria-hidden="true" />
157-
Go to source
158-
</PopoverClose>
159-
</div>
160-
</ContextChipPopover>
161-
);
162-
}
163197
return (
164198
<ContextChip
165199
kind="citation"
@@ -262,34 +296,3 @@ export function AssistantCitationChip({
262296
</ContextChip>
263297
);
264298
}
265-
266-
function AssistantCitationQuote({ citation }: { citation: AssistantCitation }) {
267-
const [fade, setFade] = useState({ top: false, bottom: false });
268-
const updateFade = (element: HTMLElement) => {
269-
const top = element.scrollTop > 1;
270-
const bottom = element.scrollHeight - element.clientHeight - element.scrollTop > 1;
271-
setFade((current) =>
272-
current.top === top && current.bottom === bottom ? current : { top, bottom },
273-
);
274-
};
275-
const observeFade = (element: HTMLDivElement | null) =>
276-
element ? observeResize(element, () => updateFade(element)) : undefined;
277-
return (
278-
<div
279-
ref={observeFade}
280-
onScroll={(event) => updateFade(event.currentTarget)}
281-
className={cn(
282-
"max-h-64 min-h-0 space-y-3 self-stretch overflow-y-auto whitespace-pre-wrap wrap-break-word",
283-
getVirtualizedScrollFadeClassName(fade),
284-
)}
285-
>
286-
<blockquote
287-
className="border-l-2 border-border pl-3 text-muted-foreground"
288-
dir={textDirection(citation.text)}
289-
>
290-
{citation.text}
291-
</blockquote>
292-
{citation.comment ? <p dir={textDirection(citation.comment)}>{citation.comment}</p> : null}
293-
</div>
294-
);
295-
}

‎apps/web/src/components/chat/MessagesTimeline.logic.test.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4762,22 +4762,25 @@ describe("subagent continued by a later turn", () => {
47624762
});
47634763

47644764
describe("shouldCollapseUserMessage", () => {
4765-
it("measures a quote chip by its label, not its encoded link", () => {
4765+
it("measures a quote by its card, not its encoded link", () => {
47664766
const quote = "A long assistant paragraph that the user quoted. ".repeat(40);
4767-
const citation = serializeAssistantCitation({
4768-
version: 1,
4767+
const source = {
4768+
version: 1 as const,
47694769
environmentId: EnvironmentId.make("environment"),
47704770
threadId: ThreadId.make("thread"),
47714771
messageId: MessageId.make("source"),
47724772
text: quote,
4773-
comment: "Why does this matter?",
47744773
start: 0,
47754774
end: quote.length,
47764775
prefix: "",
47774776
suffix: "",
4778-
});
4777+
};
4778+
const citation = serializeAssistantCitation({ ...source, comment: "Why does this matter?" });
4779+
const bare = serializeAssistantCitation(source);
47794780

47804781
expect(shouldCollapseUserMessage(`${citation} Can you expand on this?`)).toBe(false);
47814782
expect(shouldCollapseUserMessage(`${citation} ${"More text. ".repeat(60)}`)).toBe(true);
4783+
expect(shouldCollapseUserMessage(bare.repeat(2))).toBe(false);
4784+
expect(shouldCollapseUserMessage(bare.repeat(10))).toBe(true);
47824785
});
47834786
});

‎apps/web/src/components/chat/MessagesTimeline.logic.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,7 @@ import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-mes
33
import { isLiveSubagentTurnItem } from "@t3tools/client-runtime/state/subagentRuntime";
44
import * as DateTime from "effect/DateTime";
55
import * as Equal from "effect/Equal";
6-
import {
7-
assistantCitationLabel,
8-
collectAssistantCitations,
9-
} from "@t3tools/shared/assistantCitations";
6+
import { collectAssistantCitations } from "@t3tools/shared/assistantCitations";
107
import { shallow } from "zustand/vanilla/shallow";
118
import { claudeResumeCompactionAge } from "@t3tools/shared/claudeCompaction";
129
import {
@@ -2701,7 +2698,9 @@ function visibleUserMessageText(text: string): string {
27012698
let visible = "";
27022699
let cursor = 0;
27032700
for (const match of collectAssistantCitations(text)) {
2704-
visible += linkLabels(text.slice(cursor, match.start)) + assistantCitationLabel(match.citation);
2701+
// A quote shows as a two-line card, counted here as a mark, with its comment under it.
2702+
visible += linkLabels(text.slice(cursor, match.start));
2703+
visible += "\n\u275D\n" + (match.citation.comment ?? "") + "\n";
27052704
cursor = match.end;
27062705
}
27072706
return visible + linkLabels(text.slice(cursor));

‎packages/shared/src/threadFindText.test.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ it("indexes nested disclosure summaries and bodies in rendered order", () => {
9696
).toEqual(["Outer", "first", "Inner", "second"]);
9797
});
9898

99-
it("indexes the citation chip label instead of its link text", () => {
99+
it("indexes a citation by its comment, not its quote or link text", () => {
100100
const citation = {
101101
version: 1 as const,
102102
environmentId: EnvironmentId.make("environment"),
@@ -110,12 +110,13 @@ it("indexes the citation chip label instead of its link text", () => {
110110
};
111111
const text = `Please fix ${serializeAssistantCitation(citation)} thanks`;
112112
expect(searchableMessageSegments({ role: "user", text, streaming: false })).toEqual([
113-
"Please fix cited needle thanks",
114-
]);
115-
const commented = serializeAssistantCitation({ ...citation, comment: "my note" });
116-
expect(searchableMessageSegments({ role: "user", text: commented, streaming: false })).toEqual([
117-
"my note",
113+
"Please fix ",
114+
" thanks",
118115
]);
116+
const commented = serializeAssistantCitation({ ...citation, comment: "my\nnote" });
117+
expect(
118+
searchableMessageSegments({ role: "user", text: `fix ${commented} thanks`, streaming: false }),
119+
).toEqual(["fix ", "my note thanks"]);
119120
});
120121

121122
it("indexes insight bodies without hidden fences and keeps user and plan text literal", () => {

‎packages/shared/src/threadFindText.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ import {
2525
isAttachmentOnlyBootstrapPrompt,
2626
parseComposerContextHref,
2727
} from "./composerContextReferences.ts";
28-
import { assistantCitationLabel, parseAssistantCitationHref } from "./assistantCitations.ts";
28+
import { parseAssistantCitationHref } from "./assistantCitations.ts";
2929
import type { OrchestrationV2ConversationMessage } from "@t3tools/contracts";
3030
import { proposedPlanTitle, stripDisplayedPlanMarkdown } from "./proposedPlanText.ts";
3131
import { unified } from "unified";
@@ -150,7 +150,9 @@ function markdownThreadFindText(
150150
const citation =
151151
node.tagName === "a" && typeof href === "string" ? parseAssistantCitationHref(href) : null;
152152
if (citation) {
153-
text += assistantCitationLabel(citation);
153+
// The quote card is not searched, and it splits the text before it from its comment.
154+
flush();
155+
text += (citation.comment ?? "").replace(/\r?\n/g, " ");
154156
return;
155157
}
156158
{

0 commit comments

Comments
 (0)