Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(web): cite assistant responses with inline citations #9146

Mergedjuliusmarmingemerged 4 commits intomain fromrefs/pull/9146/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Quoting part of an assistant response meant copying text that lost all connection to where it came from. This adds citations: select text in an assistant response, choose Cite in composer, and an inline quote chip lands at your cursor — with an optional comment bubble anchored right at the selected passage. Clicking a chip (in the draft or a sent message) navigates to the source response, smooth-scrolls it into view — loading older history and unfolding turns when needed — and pulses a highlight on the exact quoted text that holds for a moment before fading.

How it works:

  • Citations serialize as self-contained t3-citation:// Markdown links carrying the quote, source IDs, offsets, context, and optional comment — no new tables, migrations, or sidecar draft state. They survive drafts, stashes, copy/paste, reloads, and sending.
  • The composer treats them as atomic inline chips (Lexical decorator nodes) alongside mentions and skills; comments edit as one undoable change via the chip's pencil.
  • ProviderService.sendTurn expands citations into readable quote data for every adapter (quote marked as reference material, comment as user-authored), while persisted messages keep the clickable links. Title/branch generation and stash previews see plain text.
  • Source matching normalizes whitespace and uses surrounding context, so quotes still resolve after edits and never guess between ambiguous repeats.
  • The terminal's "select text to copy" menu and the new citation menu share one release-triggered selection observer with consistent positioning.
  • Mobile renders sent quotes as readable blockquotes with the comment below; it doesn't create citations. Docs in docs/user/composer.md and docs/internals/assistant-citations.md.

Demo

Selection → cite → comment bubble at the selection → chip in composer → click-to-source with the pulse-and-hold highlight:

https://gh-file-drop-api-prod-mi5fy3sowv63ufte.pinglabs.workers.dev/f/35ecd10e3b53aa45/citation-demo.mp4

Built with Claude Fable 5 (Codex CLI + Claude Code).

🤖 Generated with Claude Code


Note

Medium Risk Changes the provider turn input pipeline (citation expansion and re-validation against send limits) and orchestration title/branch inputs, though malformed citations pass through and expansion is covered by tests.

Overview Users can quote assistant messages end-to-end: select text in the web timeline, insert an inline citation chip in the Lexical composer (optional comment, paste/copy/undo-safe), and follow chips back to the source message with history loading, turn expansion, scroll, and a temporary highlight.

Citations are stored as t3-citation:// markdown links in message text and drafts. Server-side, ProviderService.sendTurn expands them into numbered quote placeholders plus a structured assistant_citations JSON block for adapters while keeping the canonical links in persisted messages; title/branch generation and stash previews use plain-text citation content. Mobile only renders citations as readable text in the feed.

Chat markdown renders citation links as chips; composer submission validates both encoded and expanded prompt length. The terminal drawer reuses a shared observeSelectionActions helper for selection menus (replacing bespoke mouseup timing).

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 393a90910807e6d35cc84fa26a26b5d4fe3d593a. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Note

Add inline citations for assistant responses with selection, composer chips, and provider expansion

  • Users select assistant text in the timeline to create a citation chip in the composer; chips support comments, editing, removal, and persistence across drafts and clipboard copy
  • Citations encode as version-1 t3-citation URIs with bounded identifiers, quote text, offsets, and context; parseAssistantCitationHref and collectAssistantCitations in assistantCitations.ts validate and collect them while leaving malformed links untouched
  • expandAssistantCitationsForProvider replaces serialized citation links with numbered quote references plus a structured assistant_citations context block; ProviderService.sendTurn in ProviderService.ts runs expansion before adapter dispatch and re-validates expanded input against the provider limit
  • Citation navigation in useAssistantCitationTarget and MessagesTimeline loads missing history, expands collapsed turns, scrolls to the source, highlights it with CSS custom highlights, and warns on unavailable sources; title and branch-name generation in ProviderCommandReactor.ts now receive plain-text citation content instead of serialized markup
  • Mobile renders citations as readable text only via renderAssistantCitationsAsText in ThreadFeed.tsx; terminal selection handling in ThreadTerminalDrawer.tsx moves to the shared observeSelectionActions observer with ownership-aware menu dismissal
  • Risk: getComposerPromptLengthValidationMessage in composerSubmission.ts now rejects drafts when either serialized or expanded citation text exceeds the provider limit; CHAT_MARKDOWN_SANITIZE_SCHEMA in ChatMarkdown.tsx now permits the t3-citation protocol in hrefs
Macroscope summarized 393a909.
    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    2. @@ -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;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/assistantCitationNavigation.ts:28

      Valid maximum-size citations are rejected when the encoded hash exceeds 140,000 characters, so navigation reaches the destination but the citation cannot be decoded or highlighted. Because the 8,000-unit quote/comment limits can produce a percent-encoded href over 105 KB and Base64url expands it further, raise or remove this cap (while enforcing the citation limits on the decoded value).

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/lib/assistantCitationNavigation.ts around line 28:
      
      Valid maximum-size citations are rejected when the encoded hash exceeds 140,000 characters, so navigation reaches the destination but the citation cannot be decoded or highlighted. Because the 8,000-unit quote/comment limits can produce a percent-encoded href over 105 KB and Base64url expands it further, raise or remove this cap (while enforcing the citation limits on the decoded value).
      @@ -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;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/useAssistantCitationTarget.ts:78

      Citations whose source message is missing never complete when the thread is empty: MessagesTimeline does not mount a viewport, so useAssistantCitationTarget returns before the missing-source branch runs, leaving positioning true indefinitely without showing the unavailable-source warning. Perform the history/source lookup without requiring viewport, and only gate list positioning on the viewport being available.

      Suggested change
      78- if (!viewport || historyLoading) return;
      78+ if (historyLoading) return;
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/chat/useAssistantCitationTarget.ts around line 78:
      
      Citations whose source message is missing never complete when the thread is empty: `MessagesTimeline` does not mount a viewport, so `useAssistantCitationTarget` returns before the missing-source branch runs, leaving `positioning` true indefinitely without showing the unavailable-source warning. Perform the history/source lookup without requiring `viewport`, and only gate list positioning on the viewport being available.
    3. @@ -0,0 +22,21 @@
      22+
      23+ return (
      24+ <div
      25+ 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+ <textarea
      36+ 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"
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      This raw <textarea> reconstructs the shared Textarea primitive (field-sizing-content, min-h, text-base sm:text-sm, placeholder color, outline-none) but loses its contract: aria-invalid gets no visual treatment and disabled/focus styling is not shared, so the over-limit state is conveyed only by the helper text. The repo already has a borderless inline comment box built on the primitive — DiffCommentAnnotation uses <Textarea unstyled size="sm" className=... /> and overrides geometry through [&_[data-slot=textarea]]:….

      Consider rendering the shared Textarea with unstyled and the same class overrides instead of a hand-rolled control.

      Posted via Macroscope — UI Consistency
      @@ -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.altKey
      102+ ) {
      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>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      The label always uses the composer label class, which includes select-none, even when the chip renders read-only in a sent message (ChatMarkdown passes no onRemove). Every other chat-rendered chip keeps its label selectable — FileTagChipContent switches to CHAT_INLINE_CHIP_LABEL_CLASS_NAME via its selectable flag, and SkillInlineText uses it directly — so users can select and copy message text (and serializeRenderedMarkdownFragment can pick the chip up from a real selection). Here the quote label drops out of any selection dragged across the message.

      Consider mirroring the FileTagChip pattern: import CHAT_INLINE_CHIP_LABEL_CLASS_NAME and pick it when onRemove is undefined, e.g. cn(onRemove ? COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME : CHAT_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[16em]"). The unconditional contentEditable={false} on the wrapper (line 82) is likewise only needed for the composer variant — ComposerCitationNode's decorator wrapper already sets it.

      Posted via Macroscope — UI Consistency
    4. @@ -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);

      Mobile renders citations for all messages unnecessarily

      Low Severity

      renderAssistantCitationsAsText is called unconditionally for every message (both user and assistant roles) at the top of the message rendering block. Assistant messages never contain [Assistant quote](t3-citation://...) links — citations are only inserted into user messages via the composer. For assistant messages, this runs a regex scan across potentially large text for no reason. Gating the call behind isUser avoids unnecessary work on every assistant message render.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 22c1ce8cb7efcc214448e022eaf7198a620ddd8e. Configure [here](https://www.cursor.com/dashboard/bugbot).
    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This XXL change adds a new cross-platform citation workflow with persistent composer data, virtualized source navigation, provider prompt expansion, and changes to existing terminal selection behavior. The supplied unresolved Medium findings also identify citation-size and unavailable-source handling risks that merit human review.

      Not approved because:

      • 3 blocking correctness issues found at or above your repo's Minimum Blocking Severity
      Adjust the Minimum Blocking Severity for this repo — including turning it Off — in [Settings](https://app.macroscope.com/pingdotgg/settings#Repos). You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. Note

      Written by gpt-5.6-sol on behalf of Maria

      Refined the citation controls in 0562c44b5:

      • replaced the oversized selection menu with a compact Cite action
      • kept the whole composer citation clickable for source navigation
      • removed the composer tooltip and fill change on hover
      • made the composer edit and remove controls use the primary blue

      Light mode

      Citation controls in light mode

      Dark mode

      Citation controls in dark mode

      Verified with 126 focused tests, web typecheck, targeted lint, formatting, and direct light/dark browser checks. Hovering a composer citation shows no tooltip, and selecting the quote or label still opens the source highlight.

    7. @@ -52,3 +52,20 @@
      5252 GitHub Copilot, or OpenCode Zen, beneath its name. Search by that provider name to narrow the list
      5353 when starting a thread or changing an existing thread's model.
      5454
      55+## Quote an assistant response
      56+
      57+On web and desktop, select text in an assistant response, then choose **Cite in composer** from the
      58+menu that appears when you release the selection. This inserts an inline quote chip at your cursor
      59+and opens an optional comment bubble beside the selected text; press `Enter` or choose **Save** to
      60+attach the comment, or leave it blank to keep just the quote. You can type before and after the
      61+chip, such as a quote followed by "what do you mean?". A selection must stay within one response
      62+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 pencil
      65+button to add or change the comment, and the remove button to delete the quote and its comment from
      66+the draft. Copying, reloading, and restoring a [stashed prompt](#prompt-stash) keep each comment
      67+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
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium user/composer.md:71

      This documentation promises that citations navigate to responses in older history, but useAssistantCitationTarget stops after requestedPages.size >= 20 and reports “Could not load the cited response” even when loadEarlier has more pages, so citations more than 20 history pages back cannot be opened as documented. Qualify or remove the “including in older history” claim.

      Suggested change
      71-and highlight the quoted passage — including in older history. The
      71+and highlight the quoted passage when the source response is available to the citation navigator. The
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @docs/user/composer.md around line 71:
      
      This documentation promises that citations navigate to responses in older history, but `useAssistantCitationTarget` stops after `requestedPages.size >= 20` and reports “Could not load the cited response” even when `loadEarlier` has more pages, so citations more than 20 history pages back cannot be opened as documented. Qualify or remove the “including in older history” claim.
      @@ -52,3 +52,7 @@
      5252 GitHub Copilot, or OpenCode Zen, beneath its name. Search by that provider name to narrow the list
      5353 when starting a thread or changing an existing thread's model.
      5454
      55+## Quote an assistant response
      56+
      57+On web and desktop, select text in an assistant response, then choose **Cite in composer** from the
      58+menu that appears when you release the selection. This inserts an inline quote chip at your cursor
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low user/composer.md:58

      Users cannot find the documented Cite in composer control because AssistantSelectionToolbar renders a Cite button, not a menu item with that visible label. Update the instruction to name the visible Cite button (its accessible label is Cite selection in composer).

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @docs/user/composer.md around line 58:
      
      Users cannot find the documented **Cite in composer** control because `AssistantSelectionToolbar` renders a **Cite** button, not a menu item with that visible label. Update the instruction to name the visible **Cite** button (its accessible label is `Cite selection in composer`).
    8. Thread transfer impact

      ✅ Thread transfer remains within every enforced ceiling.

      ProviderMetricMain baselineThis PRImpactPR ceiling
      CodexTotal thread wire13.5 KiB13.5 KiB0 B (0.0%)15.1 KiB✅
      CodexThread snapshot wire6.9 KiB6.9 KiB+7 B (+0.1%)7.3 KiB✅
      CodexLive turn WebSocket wire6.6 KiB6.6 KiB−7 B (−0.1%)7.8 KiB✅
      CodexLive turn WebSocket decoded57.0 KiB57.0 KiB0 B (0.0%)66.4 KiB✅
      CodexLive turn messages10100 (0.0%)21✅
      ClaudeTotal thread wire13.3 KiB13.3 KiB+33 B (+0.2%)15.1 KiB✅
      ClaudeThread snapshot wire6.9 KiB6.9 KiB+9 B (+0.1%)7.3 KiB✅
      ClaudeLive turn WebSocket wire6.4 KiB6.4 KiB+24 B (+0.4%)7.8 KiB✅
      ClaudeLive turn WebSocket decoded56.4 KiB56.4 KiB0 B (0.0%)66.4 KiB✅
      ClaudeLive turn messages10100 (0.0%)21✅

      Baseline: 9fdafdf · PR result: 393a909 · Source CI: success

      Scenario and decoded snapshot size

      10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.

      • Codex decoded thread snapshot: 109.4 KiB
      • Claude decoded thread snapshot: 110.1 KiB

      Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.

    9. juliusmarminge merged thise7deb2a

    10. juliusmarminge closed this

    11. @@ -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+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/assistantTextSelection.ts:252

      resolveAssistantCitationRange expands a citation ending at the normalized boundary of a multi-character whitespace run to the end of that raw run, so a selection such as "x " in "a x y" highlights "x " instead of the captured text. rawTextOffset treats every offset after the whitespace token's start as a request for the raw token end; at the normalized token boundary it should advance by only the normalized offset (one space), not by match[0].length.

      -        match.index +
      -        (whitespace && normalizedOffset > offset ? match[0].length : normalizedOffset - offset)
      +        match.index + normalizedOffset - offset
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/lib/assistantTextSelection.ts around lines 252-255:
      
      `resolveAssistantCitationRange` expands a citation ending at the normalized boundary of a multi-character whitespace run to the end of that raw run, so a selection such as `"x "` in `"a x  y"` highlights `"x  "` instead of the captured text. `rawTextOffset` treats every offset after the whitespace token's start as a request for the raw token end; at the normalized token boundary it should advance by only the normalized offset (one space), not by `match[0].length`.
      @@ -746,7 +757,7 @@
      746757 });
      747758 const inputTextWithAttachmentPaths =
      748759 attachmentPathLines.length === 0
      749- ? parsed.input
      750- : [parsed.input, attachmentPathLines.join("\n")]
      760+ ? inputTextWithCitations
      761+ : [inputTextWithCitations, attachmentPathLines.join("\n")]
      751762 .filter((part): part is string => typeof part === "string" && part.length > 0)
      752763 .join("\n\n");
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Layers/ProviderService.ts:759

      adapter.sendTurn receives inputTextWithAttachmentPaths without validating its final length, so expanded citation text at the 120,000-character limit can become an oversized prompt when resolvable attachment path lines are appended. Validate the joined inputTextWithAttachmentPaths after constructing it.

      Suggested change
      759- attachmentPathLines.length === 0
      760- ? inputTextWithCitations
      761- : [inputTextWithCitations, attachmentPathLines.join("\n")]
      762- .filter((part): part is string => typeof part === "string" && part.length > 0)
      763- .join("\n\n");
      759+ const inputTextWithAttachmentPaths =
      760+ attachmentPathLines.length === 0
      761+ ? inputTextWithCitations
      762+ : [inputTextWithCitations, attachmentPathLines.join("\n")]
      763+ .filter((part): part is string => typeof part === "string" && part.length > 0)
      764+ .join("\n\n");
      765+ yield* decodeInputOrValidationError({
      766+ operation: "ProviderService.sendTurn",
      767+ schema: ProviderSendTurnInput.fields.input,
      768+ payload: inputTextWithAttachmentPaths,
      769+ });
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/provider/Layers/ProviderService.ts around lines 759-763:
      
      `adapter.sendTurn` receives `inputTextWithAttachmentPaths` without validating its final length, so expanded citation text at the 120,000-character limit can become an oversized prompt when resolvable attachment path lines are appended. Validate the joined `inputTextWithAttachmentPaths` after constructing it.
      @@ -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+ };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/assistantTextSelection.ts:144

      When a selection crosses consecutive <br> elements, readAssistantText returns only one \n instead of one per break, so the saved quote and offsets no longer represent the text the user selected. Because separator is a boolean, later breaks overwrite the pending separator; track the number of consecutive breaks and emit that many separators.

      -  let separator = false;
      +  let separator = 0;
      @@
      -      if (separator && length > 0) {
      +      if (separator > 0 && length > 0) {
               parts.push("\n");
      -        length += 1;
      +        length += separator;
             }
      -      separator = false;
      +      separator = 0;
      @@
      -    if (block || element.tagName === "BR") separator = true;
      +    if (element.tagName === "BR") separator += 1;
      +    else if (block) separator = Math.max(separator, 1);
      @@
      -    if (block) separator = true;
      +    if (block) separator = Math.max(separator, 1);
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/lib/assistantTextSelection.ts around lines 144-167:
      
      When a selection crosses consecutive `<br>` elements, `readAssistantText` returns only one `\n` instead of one per break, so the saved quote and offsets no longer represent the text the user selected. Because `separator` is a boolean, later breaks overwrite the pending separator; track the number of consecutive breaks and emit that many separators.
      @@ -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(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/assistantCitations.ts:21

      formatAssistantCitationHref emits IDs such as . and .. as literal path segments, so new URL() normalizes them and parseAssistantCitationHref returns null instead of the original citation. Sources with these valid IDs are therefore serialized but cannot be collected, expanded, or navigated; percent-encode . in encodePathPart as well.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @packages/shared/src/assistantCitations.ts around line 21:
      
      `formatAssistantCitationHref` emits IDs such as `.` and `..` as literal path segments, so `new URL()` normalizes them and `parseAssistantCitationHref` returns `null` instead of the original citation. Sources with these valid IDs are therefore serialized but cannot be collected, expanded, or navigated; percent-encode `.` in `encodePathPart` as well.
      @@ -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({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ThreadTerminalDrawer.tsx:778

      In browser mode, clicking Copy or Add-to-chat in the selection menu never executes the action: observeSelectionActions treats the fallback menu's DOM pointerdown outside mount as an interaction, invalidates the request, and closes the menu before its click resolves. Pass the menu element through getActionElement (or otherwise exempt the fallback menu) so interactions with the menu remain part of the active selection flow.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/ThreadTerminalDrawer.tsx around line 778:
      
      In browser mode, clicking `Copy` or `Add-to-chat` in the selection menu never executes the action: `observeSelectionActions` treats the fallback menu's DOM pointerdown outside `mount` as an interaction, invalidates the request, and closes the menu before its click resolves. Pass the menu element through `getActionElement` (or otherwise exempt the fallback menu) so interactions with the menu remain part of the active selection flow.
      @@ -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;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/AssistantCitationCommentEditor.tsx:18

      Save is disabled for a comment whose trimmed value is at most ASSISTANT_CITATION_MAX_COMMENT_LENGTH, such as an 8,000-character comment with one leading or trailing space. commentTooLong checks the untrimmed value, while withAssistantCitationComment trims before persisting; validate comment.trim() so the editor uses the same value as the storage contract.

      -  const commentTooLong = comment.length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH;
      +  const commentTooLong = comment.trim().length > ASSISTANT_CITATION_MAX_COMMENT_LENGTH;
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/chat/AssistantCitationCommentEditor.tsx around line 18:
      
      `Save` is disabled for a comment whose trimmed value is at most `ASSISTANT_CITATION_MAX_COMMENT_LENGTH`, such as an 8,000-character comment with one leading or trailing space. `commentTooLong` checks the untrimmed value, while `withAssistantCitationComment` trims before persisting; validate `comment.trim()` so the editor uses the same value as the storage contract.
    12. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      There are 3 total unresolved issues (including 1 from previous review).

      Fix All in Cursor Bugbot Autofix is ON, but it could not run because the branch was deleted or merged before autofix could start. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 393a90910807e6d35cc84fa26a26b5d4fe3d593a. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -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+ };

      Scroll cancels the Cite toolbar

      Medium Severity

      observeSelectionActions treats any descendant scroll as a cancel. After pointerup, pointerDown is already false, so a selection scroll-into-view or LegendList layout scroll clears the pending timer and sets dismissed. selectionchange will not recover, so the Cite control never appears for selections that move the timeline.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 393a90910807e6d35cc84fa26a26b5d4fe3d593a. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -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;

      Large citation hashes fail navigation

      Low Severity

      assistantCitationFromLocation drops hashes longer than 140,000 characters, but assistantCitationHash base64url-encodes the full t3-citation href. A near-max Unicode quote plus comment encodes past that cap, so chip clicks still change the thread route and then never activate highlight or history loading.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 393a90910807e6d35cc84fa26a26b5d4fe3d593a. Configure [here](https://www.cursor.com/dashboard/bugbot).
    13. @juliusmarminge @maria-rcks @t3dotgg Is there any chance that the cite button could be placed above the text?

      I always select text as I read it and right now the cite button always gets in my way of reading the text. Sometimes it's placed on the same line I'm reading and sometimes it's placed on the next so it ends up blocking text that I'm yet to read.

Sign in to join this conversation.