Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

assistantTextSelection.test.ts

584 lines21.0 KB

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