Open History to see the last commit
1# Assistant citations
2
3> For maintainers. Using T3 Code? See [Quote an assistant response](../user/composer.md#quote-an-assistant-response).
4
5Assistant citations store a selected excerpt and its source in ordinary message text. They need
6no database migration, citation table, or sidecar draft metadata. The saved excerpt remains
7available even when the source response is missing or has changed.
8
9## Serialized form
10
11[`AssistantCitation`][contract] defines version 1. [`assistantCitations.ts`][shared] serializes it
12as a Markdown link with the literal label `Assistant quote`:
13
14```text
15[Assistant quote](t3-citation://v1/<environmentId>/<threadId>/<messageId>?text=<quote>&start=<start>&end=<end>&prefix=<prefix>&suffix=<suffix>&comment=<optional-user-comment>)
16```
17
18The formatter percent-encodes each path segment and uses `URLSearchParams` for the query. The
19environment, thread, and message IDs identify the source without a browser origin, so local,
20remote, and tunnel clients share one form. Opening the source still requires access to its
21environment.
22
23The parser accepts only version 1 with exactly three source IDs and one of each selector field;
24`comment` is optional and links without one keep their original format. It rejects credentials,
25ports, malformed encoding, and extra or duplicate query fields. IDs have a 512-character limit,
26the quote and comment each fit in 8,000 UTF-16 code units, offsets are nonnegative safe integers
27with `end > start`, prefix and suffix each fit in 32 code units, and the URI itself is capped at
28160,000 characters. Malformed or unsupported links remain ordinary prompt text everywhere:
29collectors, provider expansion, and readable fallbacks all skip them. Parsing validates the
30payload, not the existence of its source.
31
32## Selection and source matching
33
34[`assistantTextSelection.ts`][selection] captures one native DOM range inside one assistant
35response, including backward and paragraph selections. Empty range endpoints at neighboring blocks
36are narrowed to the first and last selected text nodes before validating the source, so
37triple-click selections that end at the next block still resolve. The text stream follows DOM
38order, inserts line breaks between blocks and at `<br>`, and includes displayed code and link
39text. Controls, hidden subtrees, CSS-generated content, and soft wrapping do not contribute.
40
41`text` keeps the exact selected excerpt, including line breaks and indentation. `start`, `end`,
42`prefix`, and `suffix` use the rendered-text stream after each JavaScript whitespace run collapses
43to one space, without trimming, in UTF-16 code units. Context boundaries avoid splitting
44surrogate pairs.
45
46Resolution uses the same normalization and case-sensitive matching. It checks the saved offsets
47against the quote and context, then searches for a context-matching occurrence if positions have
48moved. A unique quote can still match after its context changes. Multiple context-matching
49occurrences are ambiguous, even if one remains at the saved offsets; the resolver does not guess.
50
51## Composer and clients
52
53[`AssistantSelectionToolbar`][toolbar] offers **Cite in composer** for a selection within one
54response and disables it above the quote limit. It shares [`selectionActions.ts`][actions] with
55the terminal's selection menu: the observer opens actions only after a primary-button release from
56a gesture that started inside the surface, waits out the 500 ms repeat-click window so
57double/triple clicks can finish, anchors to the release point (or the text end for keyboard
58selections), and dismisses on outside interaction, scrolling, or `Escape`. The toolbar registers
59its own element with the observer so interacting with it cannot replace the captured quote.
60
61`ChatView` inserts the serialized link at the last composer cursor. A one-shot editor request then
62opens the comment editor beside the cited source text, carrying the live DOM range for positioning
63and an editing highlight; that range is transient and never becomes part of the citation.
64`withAssistantCitationComment` trims outer whitespace and removes the field when blank; it never
65changes the saved quote or selector. Restoring or pasting a citation does not reopen the editor.
66
67[`ComposerCitationNode`][node] is an inline Lexical `DecoratorNode` holding the quote and comment
68as one atomic chip. Its label shows the comment when present, otherwise a short quote preview; the
69node retains the full serialized source and returns it from `getTextContent()`. Comment edits
70update the citation and serialized source together as one undoable change. The token parser,
71clipboard handling, and cursor mapping treat citations as inline tokens alongside mentions and
72skills, so drafts, stashes, and pastes reconstruct chips from the prompt string alone. Sent
73messages keep the same links; `ChatMarkdown` renders valid citation URIs as read-only
74[`AssistantCitationChip`][chip]s, and the whole chip supplies its serialized value to Markdown
75copy so the displayed label is not duplicated as text.
76
77## Source navigation
78
79[`assistantCitationNavigation.ts`][navigation] routes to the source thread with
80`#assistant-citation=<base64url-encoded citation URI>`; the encoding keeps router hash
81normalization from decoding quote whitespace or source IDs. Each click adds a fresh activation ID
82to navigation state so the same link can reveal its source again after dismissal.
83
84[`useAssistantCitationTarget`][target] loads earlier history (bounded at 20 pages or a repeated
85cursor, with a warning past that), expands a folded turn, and asks the virtual list to mount the
86source row. While positioning, the timeline disables initial end-scroll and scroll maintenance and
87keeps the cited row mounted until measured; the activation ID doubles as the list's data version
88so pinning rows recalculates a stationary Legend list without discarding measurements.
89
90[`AssistantCitationSource`][source] resolves the DOM range, smoothly scrolls to it, and pulses
91only that text through the CSS Highlight API: two 650 ms pulses driven by a registered opacity
92property, with the second settling into a held highlight before fading out. Navigation owns the
93highlight's start time and completion state: range repairs keep the original clock, remounting
94resumes only the remaining time, and an expired or dismissed highlight cannot revive. Reduced
95motion scrolls instantly and holds the highlight without pulsing. Browsers
96without the Highlight API temporarily select the range and remove only that owned selection.
97User navigation or `Escape` cancels pending positioning; missing messages or unmatched text
98produce warnings without changing the saved quote. The separate comment-editing highlight uses
99the same range-repair observer while its editor is open.
100
101Desktop shares the web implementation. Mobile's `ThreadFeed` uses `renderAssistantCitationsAsText`
102to show sent quotes as readable Markdown blockquotes with each user comment below its quote; it
103does not create citations or navigate to sources.
104
105## Provider input and titles
106
107[`ProviderService.sendTurn`][provider] calls `expandAssistantCitationsForProvider` before routing
108to any adapter; persisted messages keep their links. Each distinct serialized link becomes an
109inline `[assistant-quote-N]` marker, and one `<assistant_citations>` block carries JSON entries
110with an `id` and the complete `citation`. The block identifies `citation.text` as quoted reference
111material, not new instructions, and `citation.comment` as the user's comment about that quote.
112JSON encoding escapes `<`, `>`, and `&` so content cannot close the wrapper. The expansion is
113shared by all providers; there is no per-adapter citation handling or source lookup at send time.
114
115The 120,000-character provider input limit applies both before and after expansion:
116[`composerSubmission.ts`][submission] checks the larger length client-side and keeps an over-limit
117draft editable, and the server revalidates the expanded input before dispatch. Expansion does not
118apply to pending user-input answers.
119
120`assistantCitationsToPlainText` supplies readable input for title seeds, stash previews, and the
121server's title and branch-name helpers, which see the quoted text and comment rather than an
122encoded URI.
123
124[contract]: ../../packages/contracts/src/assistantCitations.ts
125[shared]: ../../packages/shared/src/assistantCitations.ts
126[selection]: ../../apps/web/src/lib/assistantTextSelection.ts
127[toolbar]: ../../apps/web/src/components/chat/AssistantSelectionToolbar.tsx
128[actions]: ../../apps/web/src/lib/selectionActions.ts
129[node]: ../../apps/web/src/components/ComposerCitationNode.tsx
130[chip]: ../../apps/web/src/components/chat/AssistantCitationChip.tsx
131[navigation]: ../../apps/web/src/lib/assistantCitationNavigation.ts
132[target]: ../../apps/web/src/components/chat/useAssistantCitationTarget.ts
133[source]: ../../apps/web/src/components/chat/AssistantCitationSource.tsx
134[provider]: ../../apps/server/src/provider/Layers/ProviderService.ts
135[submission]: ../../apps/web/src/components/chat/composerSubmission.ts