Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import {
3 ASSISTANT_CITATION_CONTEXT_LENGTH,
4 EnvironmentId,
5 MessageId,
6 ThreadId,
7} from "@t3tools/contracts";
8import {
9 formatAssistantCitationHref,
10 parseAssistantCitationHref,
11} from "@t3tools/shared/assistantCitations";
12β
13import {
14 type AssistantTextSelector,
15 captureAssistantTextSelection,
16 createAssistantTextSelector,
17 findAssistantCitationText,
18} from "./assistantTextSelection";
19β
20function selector(
21 text: string,
22 overrides: Partial<Omit<AssistantTextSelector, "text">> = {},
23): AssistantTextSelector {
24 return {
25 text,
26 start: 0,
27 end: text.replace(/\s+/g, " ").length,
28 prefix: "",
29 suffix: "",
30 ...overrides,
31 };
32}
33β
34function roundTripSelector(selector: AssistantTextSelector) {
35 return parseAssistantCitationHref(
36 formatAssistantCitationHref({
37 version: 1,
38 environmentId: EnvironmentId.make("environment"),
39 threadId: ThreadId.make("thread"),
40 messageId: MessageId.make("assistant"),
41 ...selector,
42 }),
43 );
44}
45β
46class SelectionNode {
47 parentElement: SelectionNode | null = null;
48 childNodes: SelectionNode[] = [];
49β
50 constructor(
51 readonly tagName: string,
52 readonly data = "",
53 readonly attributes: Record<string, string> = {},
54 ) {}
55β
56 get nodeType() {
57 return this.tagName === "#text" ? 3 : 1;
58 }
59 get length() {
60 return this.data.length;
61 }
62 get firstChild(): SelectionNode | null {
63 return this.childNodes[0] ?? null;
64 }
65 get lastChild(): SelectionNode | null {
66 return this.childNodes.at(-1) ?? null;
67 }
68 get previousSibling(): SelectionNode | null {
69 const siblings = this.parentElement?.childNodes;
70 return siblings?.[siblings.indexOf(this) - 1] ?? null;
71 }
72 get nextSibling(): SelectionNode | null {
73 const siblings = this.parentElement?.childNodes;
74 return siblings?.[siblings.indexOf(this) + 1] ?? null;
75 }
76 append(...children: SelectionNode[]) {
77 for (const child of children) child.parentElement = this;
78 this.childNodes.push(...children);
79 return this;
80 }
81 contains(node: SelectionNode): boolean {
82 return node === this || this.childNodes.some((child) => child.contains(node));
83 }
84 matches(selector: string) {
85 return selector.split(", ").some((part) => {
86 if (!part.startsWith("[")) return part === this.tagName.toLowerCase();
87 const [attribute, value] = part.slice(1, -1).split("=");
88 return (
89 Object.hasOwn(this.attributes, attribute!) &&
90 (value === undefined || this.attributes[attribute!] === value)
91 );
92 });
93 }
94 closest(selector: string): SelectionNode | null {
95 return this.matches(selector) ? this : (this.parentElement?.closest(selector) ?? null);
96 }
97}
98β
99function textNode(text: string) {
100 return new SelectionNode("#text", text);
101}
102β
103function assistantSource(...children: SelectionNode[]) {
104 return new SelectionNode("DIV", "", { "data-assistant-citation-source": "assistant" }).append(
105 ...children,
106 );
107}
108β
109function nativeSelection(
110 start: [SelectionNode, number],
111 end: [SelectionNode, number],
112 backwards = false,
113) {
114 let root = start[0];
115 while (root.parentElement !== null) root = root.parentElement;
116 // Give every DOM boundary its own position, including element boundaries
117 // immediately before text offset 0 and after its final character.
118 const positions = new Map<SelectionNode, number[]>();
119 let position = 0;
120 const index = (node: SelectionNode) => {
121 const offsets = [position++];
122 positions.set(node, offsets);
123 if (node.nodeType === 3) {
124 for (let offset = 0; offset < node.length; offset++) offsets.push(position++);
125 } else {
126 for (const child of node.childNodes) {
127 index(child);
128 offsets.push(position++);
129 }
130 }
131 };
132 index(root);
133 const at = (node: SelectionNode, offset: number) => positions.get(node)![offset]!;
134β
135 class SelectionRange {
136 constructor(
137 public startContainer: SelectionNode,
138 public startOffset: number,
139 public endContainer: SelectionNode,
140 public endOffset: number,
141 ) {}
142 get collapsed() {
143 return this.startContainer === this.endContainer && this.startOffset === this.endOffset;
144 }
145 get commonAncestorContainer() {
146 let ancestor = this.startContainer;
147 while (!ancestor.contains(this.endContainer)) ancestor = ancestor.parentElement!;
148 return ancestor;
149 }
150 cloneRange() {
151 return new SelectionRange(
152 this.startContainer,
153 this.startOffset,
154 this.endContainer,
155 this.endOffset,
156 );
157 }
158 setStart(node: SelectionNode, offset: number) {
159 this.startContainer = node;
160 this.startOffset = offset;
161 }
162 setEnd(node: SelectionNode, offset: number) {
163 this.endContainer = node;
164 this.endOffset = offset;
165 }
166 intersectsNode(node: SelectionNode) {
167 const parent = node.parentElement;
168 if (parent === null) return true;
169 const offset = parent.childNodes.indexOf(node);
170 return (
171 at(parent, offset) < at(this.endContainer, this.endOffset) &&
172 at(parent, offset + 1) > at(this.startContainer, this.startOffset)
173 );
174 }
175 }
176β
177 const range = new SelectionRange(...start, ...end);
178 const anchor = backwards ? end : start;
179 const focus = backwards ? start : end;
180 return {
181 isCollapsed: range.collapsed,
182 rangeCount: 1,
183 anchorNode: anchor[0],
184 anchorOffset: anchor[1],
185 focusNode: focus[0],
186 focusOffset: focus[1],
187 getRangeAt: () => range,
188 } as unknown as Selection;
189}
190β
191function capture(viewport: SelectionNode, selection: Selection) {
192 return captureAssistantTextSelection(viewport as unknown as HTMLElement, selection);
193}
194β
195describe("captureAssistantTextSelection", () => {
196 it.each([
197 { boundary: "next text", backwards: false },
198 { boundary: "next block", backwards: false },
199 { boundary: "parent", backwards: false },
200 { boundary: "next text", backwards: true },
201 { boundary: "next block", backwards: true },
202 { boundary: "parent", backwards: true },
203 ])(
204 "captures a paragraph ending at $boundary, backwards=$backwards",
205 ({ boundary, backwards }) => {
206 const quote = textNode("A paragraph π cafe\u0301.");
207 const source = assistantSource(new SelectionNode("P").append(quote));
208 const nextText = textNode("Another response.");
209 const nextBlock = assistantSource(new SelectionNode("P").append(nextText));
210 const viewport = new SelectionNode("MAIN").append(source, nextBlock);
211 const end: [SelectionNode, number] =
212 boundary === "next text"
213 ? [nextText, 0]
214 : boundary === "next block"
215 ? [nextBlock, 0]
216 : [viewport, 1];
217 const selection = nativeSelection([quote, 0], end, backwards);
218 const captured = capture(viewport, selection);
219β
220 expect(captured?.source).toBe(source);
221 expect(captured?.selector).toEqual(selector(quote.data));
222 expect(captured?.range.endContainer).toBe(quote);
223 expect(captured?.range.endOffset).toBe(quote.length);
224 expect(selection.getRangeAt(0).endContainer).toBe(end[0]);
225 expect(selection.getRangeAt(0).endOffset).toBe(end[1]);
226 },
227 );
228β
229 it("finds the source when both endpoints are parent boundaries", () => {
230 const quote = textNode("Only this response.");
231 const source = assistantSource(new SelectionNode("P").append(quote));
232 const viewport = new SelectionNode("MAIN").append(source, assistantSource(textNode("Next.")));
233 expect(capture(viewport, nativeSelection([viewport, 0], [viewport, 1]))?.selector).toEqual(
234 selector(quote.data),
235 );
236 });
237β
238 it("captures the final paragraph when Chromium extends to the timestamp paragraph boundary", () => {
239 const quote = textNode("The final paragraph.");
240 const source = assistantSource(
241 new SelectionNode("P").append(textNode("Earlier answer.")),
242 new SelectionNode("P").append(quote),
243 );
244 const timestampText = textNode("1:50 AM");
245 const timestamp = new SelectionNode("P").append(timestampText);
246 new SelectionNode("MAIN").append(
247 new SelectionNode("DIV").append(source, new SelectionNode("DIV").append(timestamp)),
248 );
249 const selection = nativeSelection([quote, 0], [timestamp, 0]);
250 selection.toString = () => `${quote.data}\n\n\n`;
251β
252 expect(capture(source, selection)?.selector).toEqual(
253 selector(quote.data, {
254 start: "Earlier answer. ".length,
255 end: "Earlier answer. The final paragraph.".length,
256 prefix: "Earlier answer. ",
257 }),
258 );
259 expect(capture(source, nativeSelection([quote, 0], [timestampText, 1]))).toBeNull();
260 });
261β
262 it("does not attribute an empty starting endpoint to the previous response", () => {
263 const previous = textNode("Previous response.");
264 const quote = textNode("Selected response.");
265 const source = assistantSource(quote);
266 const viewport = new SelectionNode("MAIN").append(assistantSource(previous), source);
267 const captured = capture(
268 viewport,
269 nativeSelection([previous, previous.length], [quote, quote.length]),
270 );
271 expect(captured?.source).toBe(source);
272 expect(captured?.selector).toEqual(selector(quote.data));
273 });
274β
275 it.each([false, true])(
276 "rejects actual overlap with another response, backwards=%s",
277 (backwards) => {
278 const first = textNode("Repeated quote.");
279 const second = textNode(first.data);
280 const viewport = new SelectionNode("MAIN").append(
281 assistantSource(first),
282 assistantSource(second),
283 );
284 expect(capture(viewport, nativeSelection([first, 0], [second, 1], backwards))).toBeNull();
285 },
286 );
287β
288 it("accepts a control endpoint only when none of its text is selected", () => {
289 const quote = textNode("A paragraph.");
290 const control = textNode("Copy");
291 const source = assistantSource(
292 new SelectionNode("P").append(quote),
293 new SelectionNode("BUTTON").append(control),
294 );
295 expect(capture(source, nativeSelection([quote, 0], [control, 0]))?.selector).toEqual(
296 selector(quote.data),
297 );
298 expect(capture(source, nativeSelection([quote, 0], [control, 1]))).toBeNull();
299 });
300β
301 it.each([
302 new SelectionNode("BUTTON"),
303 new SelectionNode("SPAN", "", { role: "button" }),
304 new SelectionNode("DIV", "", { contenteditable: "true" }),
305 new SelectionNode("SPAN", "", { hidden: "" }),
306 new SelectionNode("SPAN", "", { "aria-hidden": "true" }),
307 ])("rejects selected text at excluded endpoints: %j", (excluded) => {
308 const quote = textNode("A paragraph.");
309 const control = textNode("Excluded");
310 const source = assistantSource(quote, excluded.append(control));
311 expect(capture(source, nativeSelection([quote, 0], [control, 1]))).toBeNull();
312 expect(capture(source, nativeSelection([control, 0], [control, control.length]))).toBeNull();
313 });
314β
315 it("keeps exact multiline Unicode text and omits interior controls and hidden text", () => {
316 const first = textNode("Before π ");
317 const code = textNode("first line\r\n second line\tπ");
318 const source = assistantSource(
319 new SelectionNode("P").append(first, new SelectionNode("EM").append(textNode("cafe\u0301"))),
320 new SelectionNode("BUTTON").append(textNode("Copy")),
321 new SelectionNode("SPAN", "", { hidden: "" }).append(textNode("Hidden")),
322 new SelectionNode("PRE").append(new SelectionNode("CODE").append(code)),
323 );
324 expect(
325 capture(source, nativeSelection([first, 0], [code, code.length], true))?.selector,
326 ).toEqual(selector("Before π cafe\u0301\nfirst line\r\n second line\tπ"));
327 });
328β
329 it("rejects a source outside the supplied viewport", () => {
330 const quote = textNode("Outside.");
331 assistantSource(quote);
332 expect(
333 capture(new SelectionNode("MAIN"), nativeSelection([quote, 0], [quote, quote.length])),
334 ).toBeNull();
335 });
336});
337β
338describe("createAssistantTextSelector", () => {
339 it("keeps exact selected whitespace while normalizing its UTF-16 positions", () => {
340 const text = "Before \n quote\t \n after";
341 expect(
342 createAssistantTextSelector(text, "Before \n".length, "Before \n quote\t".length),
343 ).toEqual({
344 text: " quote\t",
345 start: 6,
346 end: 13,
347 prefix: "Before",
348 suffix: "after",
349 });
350 });
351β
352 it.each([
353 0,
354 ASSISTANT_CITATION_CONTEXT_LENGTH - 2,
355 ASSISTANT_CITATION_CONTEXT_LENGTH - 1,
356 ASSISTANT_CITATION_CONTEXT_LENGTH,
357 ])("keeps complete context code points with %i neighboring UTF-16 units", (paddingLength) => {
358 const padding = "x".repeat(paddingLength);
359 const text = `π${padding}quote${padding}π`;
360 const start = text.indexOf("quote");
361 const captured = createAssistantTextSelector(text, start, start + 5);
362 const keepEmoji = paddingLength + 2 <= ASSISTANT_CITATION_CONTEXT_LENGTH;
363 expect(captured).toEqual({
364 text: "quote",
365 start,
366 end: start + 5,
367 prefix: `${keepEmoji ? "π" : ""}${padding}`,
368 suffix: `${padding}${keepEmoji ? "π" : ""}`,
369 });
370 expect(roundTripSelector(captured!)).toMatchObject(captured!);
371 });
372β
373 it("preserves multiline quotes and their matching location through a citation URL", () => {
374 const quote = "selected\r\n code π";
375 const prefix = "x".repeat(ASSISTANT_CITATION_CONTEXT_LENGTH - 1);
376 const suffix = "y".repeat(ASSISTANT_CITATION_CONTEXT_LENGTH - 1);
377 const text = `${quote} elsewhere\nπ${prefix}${quote}${suffix}π`;
378 const rawStart = text.lastIndexOf(quote);
379 const captured = createAssistantTextSelector(text, rawStart, rawStart + quote.length);
380 const start = "selected code π elsewhere π".length + prefix.length;
381 const end = start + "selected code π".length;
382 expect(captured).toEqual({ text: quote, start, end, prefix, suffix });
383β
384 const parsed = roundTripSelector(captured!);
385 expect(parsed).toMatchObject(captured!);
386 expect(findAssistantCitationText(text, parsed!)).toEqual({ start, end });
387 expect(findAssistantCitationText(`Inserted paragraph.\n${text}`, parsed!)).toEqual({
388 start: "Inserted paragraph. ".length + start,
389 end: "Inserted paragraph. ".length + end,
390 });
391 });
392β
393 it.each(["prefix", "suffix"])(
394 "does not relocate to a replacement-character decoy after clipping the %s",
395 (side) => {
396 const prefix = "x".repeat(ASSISTANT_CITATION_CONTEXT_LENGTH - (side === "prefix" ? 1 : 0));
397 const suffix = "y".repeat(ASSISTANT_CITATION_CONTEXT_LENGTH - (side === "suffix" ? 1 : 0));
398 const occurrence = (character: string) =>
399 `${side === "prefix" ? character : ""}${prefix}quote${suffix}${side === "suffix" ? character : ""}`;
400 const text = `${occurrence("π")} / ${occurrence("\uFFFD")}`;
401 const start = text.indexOf("quote");
402 const captured = createAssistantTextSelector(text, start, start + 5);
403 const parsed = roundTripSelector(captured!);
404 expect(parsed).toMatchObject(captured!);
405 expect(findAssistantCitationText(text, captured!)).toBeNull();
406 expect(findAssistantCitationText(text, parsed!)).toBeNull();
407 },
408 );
409β
410 it.each(["", " \n\t\r\n"])("rejects empty or whitespace-only selections: %j", (text) => {
411 expect(createAssistantTextSelector(text, 0, text.length)).toBeNull();
412 });
413});
414β
415describe("findAssistantCitationText", () => {
416 it("resolves an exact selection with its saved position and context", () => {
417 expect(
418 findAssistantCitationText(
419 "Before the selected text after.",
420 selector("selected text", { start: 11, end: 24, prefix: "Before the ", suffix: " after." }),
421 ),
422 ).toEqual({ start: 11, end: 24 });
423 });
424β
425 it("finds a unique quote when insertion before it shifts its offsets", () => {
426 expect(
427 findAssistantCitationText(
428 "An inserted paragraph. Before the selected text after.",
429 selector("selected text", { start: 11, end: 24, prefix: "Before the ", suffix: " after." }),
430 ),
431 ).toEqual({ start: 34, end: 47 });
432 });
433β
434 it("still finds a unique quote after its surrounding text changes", () => {
435 expect(
436 findAssistantCitationText(
437 "New selected text nearby.",
438 selector("selected text", { start: 11, end: 24, prefix: "Before the ", suffix: " after." }),
439 ),
440 ).toEqual({ start: 4, end: 17 });
441 });
442β
443 it("uses both context sides when each side alone matches several repeated quotes", () => {
444 const text = "left quote one; other quote two; left quote two";
445 expect(
446 findAssistantCitationText(
447 text,
448 selector("quote", { start: 5, end: 10, prefix: "left ", suffix: " two" }),
449 ),
450 ).toEqual({ start: 38, end: 43 });
451 });
452β
453 it("does not trust stale offsets that now point at another occurrence", () => {
454 expect(
455 findAssistantCitationText(
456 "wrong quote here; right quote there",
457 selector("quote", { start: 6, end: 11, prefix: "right ", suffix: " there" }),
458 ),
459 ).toEqual({ start: 24, end: 29 });
460 });
461β
462 it.each([
463 { prefix: "first ", suffix: "", expected: { start: 6, end: 11 } },
464 { prefix: "", suffix: " last", expected: { start: 14, end: 19 } },
465 ])(
466 "allows a single context side to disambiguate: $prefix / $suffix",
467 ({ expected, ...context }) => {
468 expect(
469 findAssistantCitationText("first quote / quote last", selector("quote", context)),
470 ).toEqual(expected);
471 },
472 );
473β
474 it("does not guess between quotes without context, even at the saved position", () => {
475 expect(findAssistantCitationText("quote / quote", selector("quote"))).toBeNull();
476 });
477β
478 it("does not use distance or saved offsets to break a context tie", () => {
479 expect(
480 findAssistantCitationText(
481 "same quote end / same quote end",
482 selector("quote", { start: 5, end: 10, prefix: "same ", suffix: " end" }),
483 ),
484 ).toBeNull();
485 });
486β
487 it("rejects repeated quotes when neither occurrence matches all supplied context", () => {
488 expect(
489 findAssistantCitationText(
490 "left quote wrong / wrong quote right",
491 selector("quote", { prefix: "left ", suffix: " right" }),
492 ),
493 ).toBeNull();
494 });
495β
496 it("counts overlapping occurrences when checking ambiguity", () => {
497 expect(findAssistantCitationText("banana", selector("ana", { start: 1, end: 4 }))).toBeNull();
498 });
499β
500 it("matches multiline code after indentation, tabs, and line endings change", () => {
501 const quote = "if (ready) {\r\n run();\r\n}";
502 expect(
503 findAssistantCitationText(
504 "Example:\nif (ready) {\n\trun();\n}\nDone.",
505 selector(quote, { prefix: "Example:\n", suffix: "\nDone." }),
506 ),
507 ).toEqual({ start: 9, end: 30 });
508 });
509β
510 it("normalizes nonbreaking spaces and keeps selected boundary whitespace", () => {
511 expect(
512 findAssistantCitationText(
513 "before\u00a0\n quoted\t text \nafter",
514 selector("\nquoted text\t"),
515 ),
516 ).toEqual({ start: 6, end: 19 });
517 });
518β
519 it("does not trim the document's leading whitespace out of its offsets", () => {
520 expect(findAssistantCitationText("\n\t quote", selector("quote"))).toEqual({
521 start: 1,
522 end: 6,
523 });
524 });
525β
526 it("uses UTF-16 offsets for emoji and combining characters", () => {
527 expect(findAssistantCitationText("π cafe\u0301 π done", selector("cafe\u0301 π"))).toEqual({
528 start: 3,
529 end: 11,
530 });
531 });
532β
533 it("uses up to 32 UTF-16 context units without requiring the entire surrounding text", () => {
534 const prefix = "x".repeat(ASSISTANT_CITATION_CONTEXT_LENGTH - 1) + " ";
535 const suffix = " " + "y".repeat(ASSISTANT_CITATION_CONTEXT_LENGTH - 1);
536 const text = `unrelated quote / ${prefix}quote${suffix} changed further away`;
537 const start = text.lastIndexOf("quote");
538 expect(findAssistantCitationText(text, selector("quote", { prefix, suffix }))).toEqual({
539 start,
540 end: start + 5,
541 });
542 });
543β
544 it.each(["", " \n\t\r\n", "absent", "QUOTE", "qu.te"])(
545 "rejects empty or missing literal text: %j",
546 (quote) => {
547 expect(findAssistantCitationText("quote", selector(quote))).toBeNull();
548 },
549 );
550β
551 it.each([
552 { start: -1, end: 4 },
553 { start: 2.5, end: 7.5 },
554 { start: Number.NaN, end: Number.NaN },
555 { start: Number.POSITIVE_INFINITY, end: Number.POSITIVE_INFINITY },
556 { start: 8, end: 3 },
557 ])("treats invalid stored offsets as unusable hints: $start / $end", (offsets) => {
558 expect(findAssistantCitationText("a quote", selector("quote", offsets))).toEqual({
559 start: 2,
560 end: 7,
561 });
562 });
563});