Open History to see the last commit
1import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
2import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
3import { afterEach, describe, expect, it, vi } from "vite-plus/test";
4import {
5 $createParagraphNode,
6 $createTextNode,
7 $getRoot,
8 $getSelection,
9 $isElementNode,
10 $isRangeSelection,
11 COMMAND_PRIORITY_EDITOR,
12 createEditor,
13 PASTE_COMMAND,
14} from "lexical";
15
16import { registerComposerInlineTokenPaste } from "./composerInlineTokenPaste";
17import {
18 $consumeComposerCitationCommentRequest,
19 $createComposerCitationNode,
20 ComposerCitationNode,
21 type ComposerCitationCommentRequest,
22} from "./ComposerCitationNode";
23import { splitPromptIntoComposerSegments } from "../composer-editor-mentions";
24import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
25
26vi.mock("./chat/AssistantCitationChip", () => ({ AssistantCitationChip: () => null }));
27
28const citation: AssistantCitation = {
29 version: 1,
30 environmentId: EnvironmentId.make("remote/雪"),
31 threadId: ThreadId.make("thread-1"),
32 messageId: MessageId.make("message-1"),
33 text: 'Keep "👋", (punctuation) and @AGENTS.md.',
34 start: 5,
35 end: 43,
36 prefix: "前: ",
37 suffix: " 後",
38};
39const citationSource = serializeAssistantCitation(citation).replaceAll("+", "%20");
40
41function createCitationEditor(text = "") {
42 const editor = createEditor({ nodes: [ComposerCitationNode] });
43 editor.update(
44 () => {
45 const paragraph = $createParagraphNode();
46 $getRoot().append(paragraph);
47 if (text) paragraph.append($createTextNode(text));
48 paragraph.selectEnd();
49 },
50 { discrete: true },
51 );
52 registerComposerInlineTokenPaste(editor, {
53 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
54 createCitationNode: $createComposerCitationNode,
55 getExpandedAbsoluteOffsetForPoint: (_node, offset) => offset,
56 });
57 return editor;
58}
59
60function $citationNodes() {
61 const paragraph = $getRoot().getFirstChildOrThrow();
62 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
63 return paragraph.getChildren().filter((node) => node instanceof ComposerCitationNode);
64}
65
66function pasteText(editor: ReturnType<typeof createEditor>, text: string) {
67 const event = new TestClipboardEvent(text);
68 editor.update(
69 () => {
70 editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
71 },
72 { discrete: true },
73 );
74 return event;
75}
76
77class TestClipboardEvent extends Event {
78 readonly clipboardData: DataTransfer;
79
80 constructor(text: string) {
81 super("paste", { cancelable: true });
82 this.clipboardData = {
83 files: [],
84 getData: (type: string) => (type === "text/plain" ? text : ""),
85 } as unknown as DataTransfer;
86 }
87}
88
89describe("registerComposerInlineTokenPaste", () => {
90 afterEach(() => {
91 vi.unstubAllGlobals();
92 });
93
94 it("handles a copied mention without also running the plain-text paste fallback", () => {
95 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
96 const editor = createEditor();
97 const mention = "[improve-deploy-error-logging.md](.changeset/improve-deploy-error-logging.md)";
98 const plainTextFallback = vi.fn(() => {
99 const selection = $getSelection();
100 if (!$isRangeSelection(selection)) return false;
101 selection.insertText(mention);
102 return true;
103 });
104
105 editor.update(
106 () => {
107 const paragraph = $createParagraphNode();
108 $getRoot().append(paragraph);
109 paragraph.selectEnd();
110 },
111 { discrete: true },
112 );
113 registerComposerInlineTokenPaste(editor, {
114 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
115 createCitationNode: $createComposerCitationNode,
116 getExpandedAbsoluteOffsetForPoint: () => 0,
117 });
118 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
119
120 const event = new TestClipboardEvent(mention);
121 let handled = false;
122 editor.update(
123 () => {
124 handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
125 },
126 { discrete: true },
127 );
128
129 expect(handled).toBe(true);
130 expect(plainTextFallback).not.toHaveBeenCalled();
131 expect(event.defaultPrevented).toBe(true);
132 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
133 "<mention:.changeset/improve-deploy-error-logging.md> ",
134 );
135 });
136
137 it.each([
138 "yarn expo install @expo/ui",
139 "npm install @jane/foo.js",
140 "import '@scope/pkg/sub/path'",
141 ])("leaves scoped package command %s to the plain-text paste fallback", (command) => {
142 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
143 const editor = createEditor();
144 const plainTextFallback = vi.fn((event: ClipboardEvent) => {
145 const selection = $getSelection();
146 if (!$isRangeSelection(selection)) return false;
147 selection.insertText(event.clipboardData?.getData("text/plain") ?? "");
148 return true;
149 });
150
151 editor.update(
152 () => {
153 const paragraph = $createParagraphNode();
154 $getRoot().append(paragraph);
155 paragraph.selectEnd();
156 },
157 { discrete: true },
158 );
159 registerComposerInlineTokenPaste(editor, {
160 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
161 createCitationNode: $createComposerCitationNode,
162 getExpandedAbsoluteOffsetForPoint: () => 0,
163 });
164 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
165
166 const event = new TestClipboardEvent(command);
167 let handled = false;
168 editor.update(
169 () => {
170 handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
171 },
172 { discrete: true },
173 );
174
175 expect(handled).toBe(true);
176 expect(plainTextFallback).toHaveBeenCalledOnce();
177 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(command);
178 });
179
180 it("pastes a canonical scoped folder link as a mention", () => {
181 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
182 const editor = createEditor();
183 const mention = "[sub](@scope/pkg/sub)";
184 const plainTextFallback = vi.fn(() => true);
185
186 editor.update(
187 () => {
188 const paragraph = $createParagraphNode();
189 $getRoot().append(paragraph);
190 paragraph.selectEnd();
191 },
192 { discrete: true },
193 );
194 registerComposerInlineTokenPaste(editor, {
195 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
196 createCitationNode: $createComposerCitationNode,
197 getExpandedAbsoluteOffsetForPoint: () => 0,
198 });
199 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
200
201 const event = new TestClipboardEvent(mention);
202 let handled = false;
203 editor.update(
204 () => {
205 handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
206 },
207 { discrete: true },
208 );
209
210 expect(handled).toBe(true);
211 expect(plainTextFallback).not.toHaveBeenCalled();
212 expect(event.defaultPrevented).toBe(true);
213 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
214 "<mention:@scope/pkg/sub> ",
215 );
216 });
217
218 it("restores multiple citation nodes beside punctuation and Unicode without changing their source", () => {
219 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
220 const editor = createCitationEditor();
221 const secondSource = serializeAssistantCitation({
222 ...citation,
223 messageId: MessageId.make("message-2"),
224 text: "Another quote 👋",
225 });
226 const text = `前(${citationSource}),${secondSource}${citationSource}`;
227 const plainTextFallback = vi.fn(() => true);
228 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
229
230 const event = pasteText(editor, text);
231
232 expect(event.defaultPrevented).toBe(true);
233 expect(plainTextFallback).not.toHaveBeenCalled();
234 editor.getEditorState().read(() => {
235 expect($getRoot().getTextContent()).toBe(text);
236 expect($citationNodes().map((node) => node.getTextContent())).toEqual([
237 citationSource,
238 secondSource,
239 citationSource,
240 ]);
241 });
242 });
243
244 it("restores citations alongside mentions and only pads a trailing mention", () => {
245 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
246 const editor = createCitationEditor();
247
248 pasteText(editor, `${citationSource}\n[AGENTS.md](AGENTS.md) ${citationSource}`);
249
250 editor.getEditorState().read(() => {
251 expect($getRoot().getTextContent()).toBe(
252 `${citationSource}\n<mention:AGENTS.md> ${citationSource}`,
253 );
254 expect($citationNodes()).toHaveLength(2);
255 });
256
257 const trailingMentionEditor = createCitationEditor();
258 pasteText(trailingMentionEditor, `${citationSource} [AGENTS.md](AGENTS.md)`);
259
260 expect(trailingMentionEditor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
261 `${citationSource} <mention:AGENTS.md> `,
262 );
263 });
264
265 it.each(["what do you mean??\nPlease keep the indentation:\n café 👋"])(
266 "keeps the edited comment %j bound to its quote through an editor reload and paste",
267 (comment) => {
268 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
269 const editor = createCitationEditor();
270 const commentedCitation = { ...citation, comment };
271 const source = serializeAssistantCitation(commentedCitation);
272 pasteText(editor, `前(${citationSource})後`);
273 editor.update(
274 () => {
275 $citationNodes()[0]!.setComment(comment);
276 },
277 { discrete: true },
278 );
279
280 editor.getEditorState().read(() => {
281 expect($getRoot().getTextContent()).toBe(`前(${source})後`);
282 expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
283 });
284
285 const restored = createCitationEditor();
286 restored.setEditorState(restored.parseEditorState(editor.getEditorState().toJSON()));
287 restored.update(
288 () => {
289 const paragraph = $getRoot().getFirstChildOrThrow();
290 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
291 paragraph.selectStart().insertText("About ");
292 },
293 { discrete: true },
294 );
295
296 restored.getEditorState().read(() => {
297 expect($getRoot().getTextContent()).toBe(`About 前(${source})後`);
298 expect($getRoot().getChildrenSize()).toBe(1);
299 expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
300 });
301
302 const pasted = createCitationEditor();
303 pasteText(
304 pasted,
305 restored.getEditorState().read(() => $getRoot().getTextContent()),
306 );
307 pasted.getEditorState().read(() => {
308 expect($getRoot().getTextContent()).toBe(`About 前(${source})後`);
309 expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
310 });
311 },
312 );
313
314 it("edits only one repeated quote without moving selection or mutating earlier editor states", () => {
315 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
316 const editor = createCitationEditor();
317 const prompt = `前(${citationSource}),(${citationSource})後`;
318 pasteText(editor, prompt);
319 editor.update(
320 () => {
321 $getRoot().getAllTextNodes().at(-1)!.select(2, 1);
322 },
323 { discrete: true },
324 );
325 const beforeEdit = editor.getEditorState();
326 const selection = beforeEdit.read(() => $getSelection()!.clone());
327 const node = beforeEdit.read(() => $citationNodes()[1]!);
328 editor.update(() => node.setComment("First draft"), { discrete: true });
329 const comment = "Use this occurrence, not the earlier quote.";
330 editor.update(() => node.setComment(comment), { discrete: true });
331 const afterEdit = editor.getEditorState();
332 const source = serializeAssistantCitation({ ...citation, comment });
333
334 afterEdit.read(() => {
335 expect($getRoot().getTextContent()).toBe(`前(${citationSource}),(${source})後`);
336 expect($citationNodes().map((citationNode) => citationNode.exportJSON().citation)).toEqual([
337 citation,
338 { ...citation, comment },
339 ]);
340 expect($getSelection()?.is(selection)).toBe(true);
341 });
342 beforeEdit.read(() => {
343 expect($getRoot().getTextContent()).toBe(prompt);
344 expect($citationNodes().map((citationNode) => citationNode.exportJSON().citation)).toEqual([
345 citation,
346 citation,
347 ]);
348 });
349
350 editor.setEditorState(beforeEdit);
351 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(prompt);
352 editor.setEditorState(afterEdit);
353 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
354 `前(${citationSource}),(${source})後`,
355 );
356 });
357
358 it.each(["", " \n\t "])("clears a comment with %j without removing the quote", (comment) => {
359 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
360 const editor = createCitationEditor();
361 pasteText(editor, citationSource);
362 editor.update(() => $citationNodes()[0]!.setComment("Remove this comment."), {
363 discrete: true,
364 });
365 editor.update(() => $citationNodes()[0]!.setComment(comment), { discrete: true });
366
367 editor.getEditorState().read(() => {
368 expect($citationNodes()).toHaveLength(1);
369 expect($citationNodes()[0]!.exportJSON().citation).toStrictEqual(citation);
370 expect($getRoot().getTextContent()).toBe(serializeAssistantCitation(citation));
371 });
372 });
373
374 it("keeps a citation pasted after an unfinished @ restorable as a chip", () => {
375 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
376 const editor = createCitationEditor("@");
377
378 pasteText(editor, citationSource);
379
380 const prompt = editor.getEditorState().read(() => $getRoot().getTextContent());
381 expect(splitPromptIntoComposerSegments(prompt)).toEqual([
382 { type: "text", text: "@" },
383 { type: "citation", citation, source: citationSource },
384 ]);
385 });
386
387 it("copies, cuts, and pastes selected citation nodes with all source metadata intact", () => {
388 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
389 const editor = createCitationEditor();
390 const firstCitation = { ...citation, comment: "Explain the first occurrence." };
391 const secondCitation = { ...citation, comment: "Keep the second occurrence.\n café 👋" };
392 const selectedText = `${serializeAssistantCitation(firstCitation)},${serializeAssistantCitation(secondCitation)}`;
393 pasteText(editor, `before ${citationSource},${citationSource} after`);
394 editor.update(
395 () => {
396 $citationNodes()[0]!.setComment(firstCitation.comment);
397 $citationNodes()[1]!.setComment(secondCitation.comment);
398 },
399 { discrete: true },
400 );
401 let copied = "";
402 editor.update(
403 () => {
404 const paragraph = $getRoot().getFirstChildOrThrow();
405 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
406 paragraph.select(1, 4);
407 const selection = $getSelection();
408 if (!$isRangeSelection(selection)) throw new Error("Expected a range selection");
409 copied = selection.getTextContent();
410 selection.removeText();
411 },
412 { discrete: true },
413 );
414
415 expect(copied).toBe(selectedText);
416 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe("before after");
417
418 pasteText(editor, copied);
419
420 editor.getEditorState().read(() => {
421 expect($getRoot().getTextContent()).toBe(`before ${selectedText} after`);
422 expect($citationNodes().map((node) => node.exportJSON().citation)).toEqual([
423 firstCitation,
424 secondCitation,
425 ]);
426 });
427 });
428
429 it.each([true, false])(
430 "deletes a citation and its comment atomically, backwards=%s",
431 (backwards) => {
432 const editor = createCitationEditor();
433 const commentedCitation = { ...citation, comment: "Delete this with its quote.\n café 👋" };
434 const source = serializeAssistantCitation(commentedCitation);
435 editor.update(
436 () => {
437 const paragraph = $getRoot().getFirstChildOrThrow();
438 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
439 const before = $createTextNode("前(");
440 const after = $createTextNode(")後");
441 paragraph.append(
442 before,
443 $createComposerCitationNode(citation, citationSource).setComment(
444 commentedCitation.comment,
445 ),
446 after,
447 );
448 if (backwards) {
449 after.selectStart();
450 } else {
451 before.selectEnd();
452 }
453 },
454 { discrete: true },
455 );
456 const beforeDeletion = editor.getEditorState();
457 const serialized = beforeDeletion.toJSON();
458
459 editor.update(
460 () => {
461 const selection = $getSelection();
462 if (!$isRangeSelection(selection)) throw new Error("Expected a range selection");
463 selection.deleteCharacter(backwards);
464 },
465 { discrete: true },
466 );
467
468 const afterDeletion = editor.getEditorState();
469 expect(afterDeletion.read(() => $getRoot().getTextContent())).toBe("前()後");
470
471 editor.setEditorState(beforeDeletion);
472 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
473 `前(${source})後`,
474 );
475 editor.setEditorState(afterDeletion);
476 expect(editor.getEditorState().read(() => $citationNodes())).toHaveLength(0);
477
478 editor.setEditorState(editor.parseEditorState(serialized));
479 editor.getEditorState().read(() => {
480 expect($getRoot().getTextContent()).toBe(`前(${source})後`);
481 expect($citationNodes()[0]?.exportJSON().citation).toEqual(commentedCitation);
482 });
483 },
484 );
485});
486
487describe("citation comment opening", () => {
488 const sourceAnchor: AssistantCitationSourceAnchor = {
489 source: { nodeType: 1 } as HTMLElement,
490 range: { collapsed: false } as Range,
491 viewport: { nodeType: 1 } as HTMLElement,
492 };
493 afterEach(() => {
494 vi.unstubAllGlobals();
495 });
496
497 it("opens only the newly inserted occurrence after committing its exact prompt", () => {
498 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
499 const editor = createCitationEditor();
500 const previousValue = `前 ${citationSource} middle\nbefore after ${citationSource} 後`;
501 pasteText(editor, previousValue);
502 const citationStart = `前 ${citationSource} middle\nbefore `.length;
503 const value =
504 previousValue.slice(0, citationStart) +
505 `${citationSource} ` +
506 previousValue.slice(citationStart);
507 const request: ComposerCitationCommentRequest = {
508 previousValue,
509 value,
510 citationStart,
511 sourceAnchor,
512 };
513 const requestRef = { current: request as ComposerCitationCommentRequest | null };
514
515 editor.getEditorState().read(() => {
516 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
517 expect(requestRef.current).toBe(request);
518 });
519 editor.update(
520 () => {
521 const text = $getRoot()
522 .getAllTextNodes()
523 .find((node) => node.getTextContent() === "before after ");
524 if (!text) throw new Error("Expected insertion text");
525 text.select("before ".length, "before ".length);
526 },
527 { discrete: true },
528 );
529 pasteText(editor, `${citationSource} `);
530
531 editor.getEditorState().read(() => {
532 const selection = $getSelection()?.clone();
533 expect($getRoot().getTextContent()).toBe(value);
534 expect($citationNodes()).toHaveLength(3);
535 const target = $consumeComposerCitationCommentRequest(requestRef);
536 expect(target?.nodeKey).toBe($citationNodes()[1]!.getKey());
537 expect(target?.sourceAnchor).toBe(sourceAnchor);
538 expect($getSelection()?.is(selection!)).toBe(true);
539 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
540 });
541 });
542
543 it("does not reopen comments when an inserted citation is restored or pasted", () => {
544 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
545 const editor = createCitationEditor("before ");
546 const previousState = editor.getEditorState();
547 const value = `before ${citationSource} `;
548 const requestRef: { current: ComposerCitationCommentRequest | null } = {
549 current: { previousValue: "before ", value, citationStart: "before ".length, sourceAnchor },
550 };
551 pasteText(editor, `${citationSource} `);
552 const insertedState = editor.getEditorState();
553 insertedState.read(() => {
554 expect($consumeComposerCitationCommentRequest(requestRef)?.nodeKey).toBe(
555 $citationNodes()[0]!.getKey(),
556 );
557 });
558 editor.update(() => $citationNodes()[0]!.setComment("Keep this attached."), {
559 discrete: true,
560 });
561 const commentedState = editor.getEditorState();
562
563 for (const restoredState of [previousState, insertedState, commentedState]) {
564 editor.setEditorState(restoredState);
565 editor.getEditorState().read(() => {
566 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
567 });
568 }
569
570 const reloaded = createCitationEditor();
571 reloaded.setEditorState(reloaded.parseEditorState(commentedState.toJSON()));
572 reloaded.getEditorState().read(() => {
573 expect($consumeComposerCitationCommentRequest({ current: null })).toBeNull();
574 expect($citationNodes()[0]!.exportJSON().citation.comment).toBe("Keep this attached.");
575 });
576 const pasted = createCitationEditor();
577 pasteText(
578 pasted,
579 commentedState.read(() => $getRoot().getTextContent()),
580 );
581 pasted.getEditorState().read(() => {
582 expect($consumeComposerCitationCommentRequest({ current: null })).toBeNull();
583 expect($citationNodes()[0]!.exportJSON().citation.comment).toBe("Keep this attached.");
584 });
585 });
586
587 it("discards an opening request if another prompt replaces the insertion", () => {
588 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
589 const editor = createCitationEditor();
590 const requestRef: { current: ComposerCitationCommentRequest | null } = {
591 current: { previousValue: "", value: citationSource, citationStart: 0, sourceAnchor },
592 };
593 editor.update(
594 () => {
595 const selection = $getSelection();
596 if (!$isRangeSelection(selection)) throw new Error("Expected an insertion point");
597 selection.insertText("A different draft");
598 },
599 { discrete: true },
600 );
601 editor.getEditorState().read(() => {
602 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
603 });
604 editor.update(
605 () => {
606 const paragraph = $getRoot().getFirstChildOrThrow();
607 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
608 paragraph.clear().selectStart();
609 },
610 { discrete: true },
611 );
612 pasteText(editor, citationSource);
613 editor.getEditorState().read(() => {
614 expect($getRoot().getTextContent()).toBe(citationSource);
615 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
616 });
617 });
618});