feat(web): cite assistant responses with inline citations #9146
Mergedjuliusmarmingemerged 4 commits into
main fromrefs/pull/9146/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- @@ -0,0 +8,21 @@8+9+import { randomUUID } from "./utils";10+11+declare module "@tanstack/react-router" {12+ interface HistoryState {13+ assistantCitationActivation?: string;14+ }15+}16+17+const CITATION_HASH_PREFIX = "assistant-citation=";18+19+/** Base64url keeps router hash normalization from decoding quote whitespace or source IDs. */20+export function assistantCitationHash(citation: AssistantCitation) {21+ return `${CITATION_HASH_PREFIX}${Encoding.encodeBase64Url(formatAssistantCitationHref(citation))}`;22+}23+24+export function assistantCitationFromLocation(href: string) {25+ const hashIndex = href.indexOf("#");26+ if (hashIndex === -1) return null;27+ const hash = href.slice(hashIndex + 1);28+ if (!hash.startsWith(CITATION_HASH_PREFIX) || hash.length > 140_000) return null;@@ -0,0 +58,21 @@58+ if (navigationRef.current?.target.key !== request.key) {59+ const target: AssistantCitationTarget = {60+ ...request,61+ activationRef: { current: { scrolled: false, dismissed: false } },62+ onComplete: () => {63+ if (navigationRef.current?.target !== target) return;64+ navigationRef.current.done = true;65+ // ChatView's thread-open effect can run after our initial opt-out.66+ onManualNavigation();67+ setFinishedKey(target.key);68+ },69+ };70+ navigationRef.current = {71+ target,72+ requestedPages: new Set(),73+ done: false,74+ };75+ setReady(null);76+ onManualNavigation();77+ }78+ if (!viewport || historyLoading) return;
- @@ -0,0 +22,21 @@22+23+ return (24+ <div25+ data-citation-comment-editor="true"26+ onKeyDown={(event) => {27+ event.stopPropagation();28+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;29+ if (event.key === "Escape") {30+ event.preventDefault();31+ onCancel();32+ }33+ }}34+ >35+ <textarea36+ ref={inputRef}37+ aria-label="Comment on selected text"38+ aria-description="Enter to save the citation comment; Shift+Enter for a new line."39+ aria-invalid={commentTooLong || undefined}40+ placeholder="Add an optional comment..."41+ rows={2}42+ className="field-sizing-content block max-h-40 min-h-16 w-full resize-none bg-transparent px-1 py-1.5 text-base outline-none placeholder:text-muted-foreground sm:text-sm"@@ -0,0 +94,21 @@94+ resetScroll={false}95+ onClick={(event) => {96+ if (97+ event.button !== 0 ||98+ event.metaKey ||99+ event.ctrlKey ||100+ event.shiftKey ||101+ event.altKey102+ ) {103+ return;104+ }105+ event.preventDefault();106+ void navigate(assistantCitationNavigation(citation));107+ }}108+ className="inline-flex h-full min-w-0 items-center gap-[0.33em] rounded-sm text-inherit no-underline hover:bg-primary/10 focus-visible:outline-2 focus-visible:outline-primary"109+ aria-label={`View cited assistant text: ${label}`}110+ />111+ }112+ >113+ <QuoteIcon aria-hidden="true" className={COMPOSER_INLINE_CHIP_ICON_CLASS_NAME} />114+ <span className={cn(COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[16em]")}>{label}</span>apps/web/src/components/chat/AssistantSelectionToolbar.tsx line 147OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +127,21 @@127+ return true;128+ };129+ return createPortal(130+ <div131+ ref={toolbarRef}132+ role="toolbar"133+ aria-label="Assistant text selection"134+ className="dropdown-glass fixed z-50 max-w-[calc(100vw-1rem)] rounded-lg p-1 text-popover-foreground"135+ style={{ left: selection.position.x, top: selection.position.y }}136+ onKeyDown={(event) => {137+ event.stopPropagation();138+ if (event.key === "Escape" && !event.nativeEvent.isComposing) {139+ event.preventDefault();140+ dismiss();141+ }142+ }}143+ >144+ <button145+ type="button"146+ disabled={tooLong}147+ className="flex min-h-8 w-full items-center gap-2 rounded-sm px-2 py-1 text-left text-base text-foreground outline-none hover:bg-accent hover:text-accent-foreground focus-visible:bg-accent focus-visible:text-accent-foreground disabled:pointer-events-none disabled:text-muted-foreground disabled:opacity-64 sm:min-h-7 sm:text-sm"
- @@ -1390,4 +1391,4 @@13901391 if (entry.type === "message") {13911392 const { message } = entry;13921393 const isUser = message.role === "user";1393- const renderedText = message.text;1394+ const renderedText = renderAssistantCitationsAsText(message.text);packages/shared/src/assistantCitations.ts line 186Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -0,0 +166,21 @@166+ .replace(/[\\`*_[\]{}()#+.!|~-]/g, "\\$&");167+}168+169+/** Native clients display the complete quote and keep the user's comment outside the quote block. */170+export function renderAssistantCitationsAsText(prompt: string): string {171+ const matches = collectAssistantCitations(prompt);172+ let text = "";173+ let cursor = 0;174+ for (const match of matches) {175+ const quote = escapeMarkdownText(match.citation.text);176+ text += `${prompt.slice(cursor, match.start)}\n\n> Assistant quote:\n${quote177+ .split("\n")178+ .map((line) => `> ${line}`)179+ .join("\n")}\n\n`;180+ if (match.citation.comment !== undefined) {181+ text += `Comment: ${escapeMarkdownText(match.citation.comment)}\n\n`;182+ }183+ cursor = match.end;184+ }185+ return text + prompt.slice(cursor);186+}
- @@ -52,3 +52,20 @@5252 GitHub Copilot, or OpenCode Zen, beneath its name. Search by that provider name to narrow the list5353 when starting a thread or changing an existing thread's model.545455+## Quote an assistant response56+57+On web and desktop, select text in an assistant response, then choose **Cite in composer** from the58+menu that appears when you release the selection. This inserts an inline quote chip at your cursor59+and opens an optional comment bubble beside the selected text; press `Enter` or choose **Save** to60+attach the comment, or leave it blank to keep just the quote. You can type before and after the61+chip, such as a quote followed by "what do you mean?". A selection must stay within one response62+and fit in 8,000 characters.63+64+The chip shows your comment when it has one, or a short quote preview otherwise. Use the pencil65+button to add or change the comment, and the remove button to delete the quote and its comment from66+the draft. Copying, reloading, and restoring a [stashed prompt](#prompt-stash) keep each comment67+with its quote, and sending tells the agent which words were quoted and which comment you wrote.68+The quoted text and comment count toward the message limit.69+70+Select a chip in the composer or a sent message to open the source thread, scroll to the response,71+and highlight the quoted passage — including in older history. The@@ -52,3 +52,7 @@5252 GitHub Copilot, or OpenCode Zen, beneath its name. Search by that provider name to narrow the list5353 when starting a thread or changing an existing thread's model.545455+## Quote an assistant response56+57+On web and desktop, select text in an assistant response, then choose **Cite in composer** from the58+menu that appears when you release the selection. This inserts an inline quote chip at your cursor
juliusmarminge merged thise7deb2a
juliusmarminge closed this
- @@ -0,0 +235,21 @@235+ const start = range.startContainer === chunk.node ? range.startOffset : 0;236+ const end = range.endContainer === chunk.node ? range.endOffset : chunk.node.length;237+ if (start === end) continue;238+ rawStart ??= chunk.start + start;239+ rawEnd = chunk.start + end;240+ }241+ if (rawStart === null) return null;242+ const selector = createAssistantTextSelector(stream.text, rawStart, rawEnd);243+ return selector === null ? null : { source, selector, range };244+}245+246+function rawTextOffset(text: string, normalizedOffset: number): number {247+ let offset = 0;248+ for (const match of text.matchAll(/\s+|\S+/g)) {249+ const whitespace = /\s/.test(match[0][0]!);250+ const length = whitespace ? 1 : match[0].length;251+ if (normalizedOffset <= offset + length) {252+ return (253+ match.index +254+ (whitespace && normalizedOffset > offset ? match[0].length : normalizedOffset - offset)255+ );@@ -746,7 +757,7 @@746757 });747758 const inputTextWithAttachmentPaths =748759 attachmentPathLines.length === 0749- ? parsed.input750- : [parsed.input, attachmentPathLines.join("\n")]760+ ? inputTextWithCitations761+ : [inputTextWithCitations, attachmentPathLines.join("\n")]751762 .filter((part): part is string => typeof part === "string" && part.length > 0)752763 .join("\n\n");@@ -0,0 +147,21 @@147+ if (node.nodeType === 3) {148+ const text = node as Text;149+ if (text.length === 0) return;150+ if (separator && length > 0) {151+ parts.push("\n");152+ length += 1;153+ }154+ separator = false;155+ chunks.push({ node: text, start: length, end: length + text.length });156+ parts.push(text.data);157+ length += text.length;158+ return;159+ }160+ if (node.nodeType !== 1) return;161+ const element = node as Element;162+ if (element.matches(EXCLUDED_SELECTOR)) return;163+ const block = element.matches(BLOCK_SELECTOR);164+ if (block || element.tagName === "BR") separator = true;165+ for (const child of element.childNodes) visit(child);166+ if (block) separator = true;167+ };@@ -0,0 +1,21 @@1+import {2+ ASSISTANT_CITATION_MAX_COMMENT_LENGTH,3+ ASSISTANT_CITATION_MAX_TEXT_LENGTH,4+ AssistantCitation,5+} from "@t3tools/contracts";6+import * as Option from "effect/Option";7+import * as Schema from "effect/Schema";8+9+const CITATION_PROTOCOL = "t3-citation:";10+const CITATION_HREF_PREFIX = `${CITATION_PROTOCOL}//v1/`;11+// Percent encoding needs up to nine characters per UTF-16 code unit; 16k covers selectors.12+const MAX_CITATION_HREF_LENGTH =13+ 9 * (ASSISTANT_CITATION_MAX_TEXT_LENGTH + ASSISTANT_CITATION_MAX_COMMENT_LENGTH) + 16_000;14+const CITATION_LINK = new RegExp(15+ String.raw`\[Assistant quote\]\((${CITATION_HREF_PREFIX}[^\s)]{1,${MAX_CITATION_HREF_LENGTH - CITATION_HREF_PREFIX.length}})\)`,16+ "g",17+);18+const decodeCitation = Schema.decodeUnknownOption(AssistantCitation);19+20+function encodePathPart(value: string): string {21+ return encodeURIComponent(value).replace(@@ -828,20 +778 @@828- return;829- }830- selectionPointerRef.current = { x: event.clientX, y: event.clientY };831- const delay = terminalSelectionActionDelayForClickCount(event.detail);832- selectionActionTimerRef.current = window.setTimeout(() => {833- selectionActionTimerRef.current = null;834- window.requestAnimationFrame(() => {835- void showSelectionAction();836- });837- }, delay);838- };839- const handlePointerDown = (event: PointerEvent) => {840- clearSelectionAction();841- selectionGestureActiveRef.current = event.button === 0;842- };843- window.addEventListener("mouseup", handleMouseUp);844- mount.addEventListener("pointerdown", handlePointerDown);845- setupCleanups.push(() => {846- window.removeEventListener("mouseup", handleMouseUp);847- mount.removeEventListener("pointerdown", handlePointerDown);778+ selectionActions = observeSelectionActions({@@ -0,0 +1,18 @@1+import { ASSISTANT_CITATION_MAX_COMMENT_LENGTH, type AssistantCitation } from "@t3tools/contracts";2+import { useState, type Ref } from "react";3+4+import { Button } from "../ui/button";5+6+export function AssistantCitationCommentEditor({7+ citation,8+ inputRef,9+ onSubmit,10+ onCancel,11+}: {12+ citation: AssistantCitation;13+ inputRef?: Ref<HTMLTextAreaElement>;14+ onSubmit: (comment: string) => boolean;15+ onCancel: () => void;16+}) {17+ const [comment, setComment] = useState(citation.comment ?? "");18+ const commentTooLong = comment.length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH;
- @@ -0,0 +123,21 @@123+ dismiss();124+ } else if (!pointerDown) {125+ cancelPending();126+ gestureActive = false;127+ pointer = null;128+ dismissed = false;129+ }130+ };131+ const onFocusIn = (event: FocusEvent) => {132+ if (isActionTarget(event.target)) cancel();133+ else if (!pointerDown && getActionElement?.()) dismiss();134+ };135+ const onScroll = () => {136+ cancelPending();137+ // Autoscroll during a drag must not cancel that gesture's eventual release.138+ if (!pointerDown) {139+ pointer = null;140+ dismissed = true;141+ }142+ onDismiss("cancel");143+ };@@ -0,0 +8,21 @@8+9+import { randomUUID } from "./utils";10+11+declare module "@tanstack/react-router" {12+ interface HistoryState {13+ assistantCitationActivation?: string;14+ }15+}16+17+const CITATION_HASH_PREFIX = "assistant-citation=";18+19+/** Base64url keeps router hash normalization from decoding quote whitespace or source IDs. */20+export function assistantCitationHash(citation: AssistantCitation) {21+ return `${CITATION_HASH_PREFIX}${Encoding.encodeBase64Url(formatAssistantCitationHref(citation))}`;22+}23+24+export function assistantCitationFromLocation(href: string) {25+ const hashIndex = href.indexOf("#");26+ if (hashIndex === -1) return null;27+ const hash = href.slice(hashIndex + 1);28+ if (!hash.startsWith(CITATION_HASH_PREFIX) || hash.length > 140_000) return null;
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed