Open History to see the last commit
1import { upgradeLegacyContextMessage } from "@t3tools/shared/composerContextLegacy";
2import { elementContextToPreviewAnnotation } from "../lib/elementContext";
3import { previewAnnotationContextRecord } from "../lib/composerContextRecords";
4import { EnvironmentId, MessageId, ThreadId, type AssistantCitation } from "@t3tools/contracts";
5import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
6import { afterEach, describe, expect, it, vi } from "vite-plus/test";
7import {
8 $createParagraphNode,
9 $createTextNode,
10 $getRoot,
11 $getSelection,
12 $isElementNode,
13 $isRangeSelection,
14 COMMAND_PRIORITY_EDITOR,
15 createEditor,
16 PASTE_COMMAND,
17} from "lexical";
18
19import {
20 importPastedComposerText,
21 readPastedComposerContext,
22 registerComposerInlineTokenPaste,
23} from "./composerInlineTokenPaste";
24import {
25 $consumeComposerCitationCommentRequest,
26 $createComposerCitationNode,
27 ComposerCitationNode,
28 type ComposerCitationCommentRequest,
29} from "./ComposerCitationNode";
30import { splitPromptIntoComposerSegments } from "../composer-editor-mentions";
31import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
32
33vi.mock("./chat/AssistantCitationChip", () => ({ AssistantCitationChip: () => null }));
34
35const citation: AssistantCitation = {
36 version: 1,
37 environmentId: EnvironmentId.make("remote/雪"),
38 threadId: ThreadId.make("thread-1"),
39 messageId: MessageId.make("message-1"),
40 text: 'Keep "👋", (punctuation) and @AGENTS.md.',
41 start: 5,
42 end: 43,
43 prefix: "前: ",
44 suffix: " 後",
45};
46const citationSource = serializeAssistantCitation(citation).replaceAll("+", "%20");
47
48function createCitationEditor(text = "") {
49 const editor = createEditor({ nodes: [ComposerCitationNode] });
50 editor.update(
51 () => {
52 const paragraph = $createParagraphNode();
53 $getRoot().append(paragraph);
54 if (text) paragraph.append($createTextNode(text));
55 paragraph.selectEnd();
56 },
57 { discrete: true },
58 );
59 registerComposerInlineTokenPaste(editor, {
60 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
61 createCitationNode: $createComposerCitationNode,
62 createContextReferenceNode: (reference) => $createTextNode(`<context:${reference.contextId}>`),
63 getExpandedAbsoluteOffsetForPoint: (_node, offset) => offset,
64 });
65 return editor;
66}
67
68function $citationNodes() {
69 const paragraph = $getRoot().getFirstChildOrThrow();
70 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
71 return paragraph.getChildren().filter((node) => node instanceof ComposerCitationNode);
72}
73
74function pasteText(editor: ReturnType<typeof createEditor>, text: string) {
75 const event = new TestClipboardEvent(text);
76 editor.update(
77 () => {
78 editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
79 },
80 { discrete: true },
81 );
82 return event;
83}
84
85class TestClipboardEvent extends Event {
86 readonly clipboardData: DataTransfer;
87
88 constructor(text: string, extra: Record<string, string> = {}) {
89 super("paste", { cancelable: true });
90 this.clipboardData = {
91 files: [],
92 getData: (type: string) => (type === "text/plain" ? text : (extra[type] ?? "")),
93 } as unknown as DataTransfer;
94 }
95}
96
97describe("registerComposerInlineTokenPaste", () => {
98 afterEach(() => {
99 vi.unstubAllGlobals();
100 });
101
102 it("handles a copied mention without also running the plain-text paste fallback", () => {
103 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
104 const editor = createEditor();
105 const mention = "[improve-deploy-error-logging.md](.changeset/improve-deploy-error-logging.md)";
106 const plainTextFallback = vi.fn(() => {
107 const selection = $getSelection();
108 if (!$isRangeSelection(selection)) return false;
109 selection.insertText(mention);
110 return true;
111 });
112
113 editor.update(
114 () => {
115 const paragraph = $createParagraphNode();
116 $getRoot().append(paragraph);
117 paragraph.selectEnd();
118 },
119 { discrete: true },
120 );
121 registerComposerInlineTokenPaste(editor, {
122 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
123 createCitationNode: $createComposerCitationNode,
124 createContextReferenceNode: (reference) =>
125 $createTextNode(`<context:${reference.contextId}>`),
126 getExpandedAbsoluteOffsetForPoint: () => 0,
127 });
128 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
129
130 const event = new TestClipboardEvent(mention);
131 let handled = false;
132 editor.update(
133 () => {
134 handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
135 },
136 { discrete: true },
137 );
138
139 expect(handled).toBe(true);
140 expect(plainTextFallback).not.toHaveBeenCalled();
141 expect(event.defaultPrevented).toBe(true);
142 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
143 "<mention:.changeset/improve-deploy-error-logging.md> ",
144 );
145 });
146
147 it.each([
148 "yarn expo install @expo/ui",
149 "npm install @jane/foo.js",
150 "import '@scope/pkg/sub/path'",
151 ])("leaves scoped package command %s to the plain-text paste fallback", (command) => {
152 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
153 const editor = createEditor();
154 const plainTextFallback = vi.fn((event: ClipboardEvent) => {
155 const selection = $getSelection();
156 if (!$isRangeSelection(selection)) return false;
157 selection.insertText(event.clipboardData?.getData("text/plain") ?? "");
158 return true;
159 });
160
161 editor.update(
162 () => {
163 const paragraph = $createParagraphNode();
164 $getRoot().append(paragraph);
165 paragraph.selectEnd();
166 },
167 { discrete: true },
168 );
169 registerComposerInlineTokenPaste(editor, {
170 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
171 createCitationNode: $createComposerCitationNode,
172 createContextReferenceNode: (reference) =>
173 $createTextNode(`<context:${reference.contextId}>`),
174 getExpandedAbsoluteOffsetForPoint: () => 0,
175 });
176 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
177
178 const event = new TestClipboardEvent(command);
179 let handled = false;
180 editor.update(
181 () => {
182 handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
183 },
184 { discrete: true },
185 );
186
187 expect(handled).toBe(true);
188 expect(plainTextFallback).toHaveBeenCalledOnce();
189 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(command);
190 });
191
192 it("pastes a canonical scoped folder link as a mention", () => {
193 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
194 const editor = createEditor();
195 const mention = "[sub](@scope/pkg/sub)";
196 const plainTextFallback = vi.fn(() => true);
197
198 editor.update(
199 () => {
200 const paragraph = $createParagraphNode();
201 $getRoot().append(paragraph);
202 paragraph.selectEnd();
203 },
204 { discrete: true },
205 );
206 registerComposerInlineTokenPaste(editor, {
207 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
208 createCitationNode: $createComposerCitationNode,
209 createContextReferenceNode: (reference) =>
210 $createTextNode(`<context:${reference.contextId}>`),
211 getExpandedAbsoluteOffsetForPoint: () => 0,
212 });
213 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
214
215 const event = new TestClipboardEvent(mention);
216 let handled = false;
217 editor.update(
218 () => {
219 handled = editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
220 },
221 { discrete: true },
222 );
223
224 expect(handled).toBe(true);
225 expect(plainTextFallback).not.toHaveBeenCalled();
226 expect(event.defaultPrevented).toBe(true);
227 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
228 "<mention:@scope/pkg/sub> ",
229 );
230 });
231
232 it("restores multiple citation nodes beside punctuation and Unicode without changing their source", () => {
233 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
234 const editor = createCitationEditor();
235 const secondSource = serializeAssistantCitation({
236 ...citation,
237 messageId: MessageId.make("message-2"),
238 text: "Another quote 👋",
239 });
240 const text = `前(${citationSource}),${secondSource}${citationSource}`;
241 const plainTextFallback = vi.fn(() => true);
242 editor.registerCommand(PASTE_COMMAND, plainTextFallback, COMMAND_PRIORITY_EDITOR);
243
244 const event = pasteText(editor, text);
245
246 expect(event.defaultPrevented).toBe(true);
247 expect(plainTextFallback).not.toHaveBeenCalled();
248 editor.getEditorState().read(() => {
249 expect($getRoot().getTextContent()).toBe(text);
250 expect($citationNodes().map((node) => node.getTextContent())).toEqual([
251 citationSource,
252 secondSource,
253 citationSource,
254 ]);
255 });
256 });
257
258 it("restores citations alongside mentions and only pads a trailing mention", () => {
259 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
260 const editor = createCitationEditor();
261
262 pasteText(editor, `${citationSource}\n[AGENTS.md](AGENTS.md) ${citationSource}`);
263
264 editor.getEditorState().read(() => {
265 expect($getRoot().getTextContent()).toBe(
266 `${citationSource}\n<mention:AGENTS.md> ${citationSource}`,
267 );
268 expect($citationNodes()).toHaveLength(2);
269 });
270
271 const trailingMentionEditor = createCitationEditor();
272 pasteText(trailingMentionEditor, `${citationSource} [AGENTS.md](AGENTS.md)`);
273
274 expect(trailingMentionEditor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
275 `${citationSource} <mention:AGENTS.md> `,
276 );
277 });
278
279 it.each(["what do you mean??\nPlease keep the indentation:\n café 👋"])(
280 "keeps the edited comment %j bound to its quote through an editor reload and paste",
281 (comment) => {
282 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
283 const editor = createCitationEditor();
284 const commentedCitation = { ...citation, comment };
285 const source = serializeAssistantCitation(commentedCitation);
286 pasteText(editor, `前(${citationSource})後`);
287 editor.update(
288 () => {
289 $citationNodes()[0]!.setComment(comment);
290 },
291 { discrete: true },
292 );
293
294 editor.getEditorState().read(() => {
295 expect($getRoot().getTextContent()).toBe(`前(${source})後`);
296 expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
297 });
298
299 const restored = createCitationEditor();
300 restored.setEditorState(restored.parseEditorState(editor.getEditorState().toJSON()));
301 restored.update(
302 () => {
303 const paragraph = $getRoot().getFirstChildOrThrow();
304 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
305 paragraph.selectStart().insertText("About ");
306 },
307 { discrete: true },
308 );
309
310 restored.getEditorState().read(() => {
311 expect($getRoot().getTextContent()).toBe(`About 前(${source})後`);
312 expect($getRoot().getChildrenSize()).toBe(1);
313 expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
314 });
315
316 const pasted = createCitationEditor();
317 pasteText(
318 pasted,
319 restored.getEditorState().read(() => $getRoot().getTextContent()),
320 );
321 pasted.getEditorState().read(() => {
322 expect($getRoot().getTextContent()).toBe(`About 前(${source})後`);
323 expect($citationNodes()[0]!.exportJSON().citation).toEqual(commentedCitation);
324 });
325 },
326 );
327
328 it("edits only one repeated quote without moving selection or mutating earlier editor states", () => {
329 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
330 const editor = createCitationEditor();
331 const prompt = `前(${citationSource}),(${citationSource})後`;
332 pasteText(editor, prompt);
333 editor.update(
334 () => {
335 $getRoot().getAllTextNodes().at(-1)!.select(2, 1);
336 },
337 { discrete: true },
338 );
339 const beforeEdit = editor.getEditorState();
340 const selection = beforeEdit.read(() => $getSelection()!.clone());
341 const node = beforeEdit.read(() => $citationNodes()[1]!);
342 editor.update(() => node.setComment("First draft"), { discrete: true });
343 const comment = "Use this occurrence, not the earlier quote.";
344 editor.update(() => node.setComment(comment), { discrete: true });
345 const afterEdit = editor.getEditorState();
346 const source = serializeAssistantCitation({ ...citation, comment });
347
348 afterEdit.read(() => {
349 expect($getRoot().getTextContent()).toBe(`前(${citationSource}),(${source})後`);
350 expect($citationNodes().map((citationNode) => citationNode.exportJSON().citation)).toEqual([
351 citation,
352 { ...citation, comment },
353 ]);
354 expect($getSelection()?.is(selection)).toBe(true);
355 });
356 beforeEdit.read(() => {
357 expect($getRoot().getTextContent()).toBe(prompt);
358 expect($citationNodes().map((citationNode) => citationNode.exportJSON().citation)).toEqual([
359 citation,
360 citation,
361 ]);
362 });
363
364 editor.setEditorState(beforeEdit);
365 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(prompt);
366 editor.setEditorState(afterEdit);
367 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
368 `前(${citationSource}),(${source})後`,
369 );
370 });
371
372 it.each(["", " \n\t "])("clears a comment with %j without removing the quote", (comment) => {
373 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
374 const editor = createCitationEditor();
375 pasteText(editor, citationSource);
376 editor.update(() => $citationNodes()[0]!.setComment("Remove this comment."), {
377 discrete: true,
378 });
379 editor.update(() => $citationNodes()[0]!.setComment(comment), { discrete: true });
380
381 editor.getEditorState().read(() => {
382 expect($citationNodes()).toHaveLength(1);
383 expect($citationNodes()[0]!.exportJSON().citation).toStrictEqual(citation);
384 expect($getRoot().getTextContent()).toBe(serializeAssistantCitation(citation));
385 });
386 });
387
388 it("keeps a citation pasted after an unfinished @ restorable as a chip", () => {
389 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
390 const editor = createCitationEditor("@");
391
392 pasteText(editor, citationSource);
393
394 const prompt = editor.getEditorState().read(() => $getRoot().getTextContent());
395 expect(splitPromptIntoComposerSegments(prompt)).toEqual([
396 { type: "text", text: "@" },
397 { type: "citation", citation, source: citationSource },
398 ]);
399 });
400
401 it("copies, cuts, and pastes selected citation nodes with all source metadata intact", () => {
402 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
403 const editor = createCitationEditor();
404 const firstCitation = { ...citation, comment: "Explain the first occurrence." };
405 const secondCitation = { ...citation, comment: "Keep the second occurrence.\n café 👋" };
406 const selectedText = `${serializeAssistantCitation(firstCitation)},${serializeAssistantCitation(secondCitation)}`;
407 pasteText(editor, `before ${citationSource},${citationSource} after`);
408 editor.update(
409 () => {
410 $citationNodes()[0]!.setComment(firstCitation.comment);
411 $citationNodes()[1]!.setComment(secondCitation.comment);
412 },
413 { discrete: true },
414 );
415 let copied = "";
416 editor.update(
417 () => {
418 const paragraph = $getRoot().getFirstChildOrThrow();
419 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
420 paragraph.select(1, 4);
421 const selection = $getSelection();
422 if (!$isRangeSelection(selection)) throw new Error("Expected a range selection");
423 copied = selection.getTextContent();
424 selection.removeText();
425 },
426 { discrete: true },
427 );
428
429 expect(copied).toBe(selectedText);
430 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe("before after");
431
432 pasteText(editor, copied);
433
434 editor.getEditorState().read(() => {
435 expect($getRoot().getTextContent()).toBe(`before ${selectedText} after`);
436 expect($citationNodes().map((node) => node.exportJSON().citation)).toEqual([
437 firstCitation,
438 secondCitation,
439 ]);
440 });
441 });
442
443 it.each([true, false])(
444 "deletes a citation and its comment atomically, backwards=%s",
445 (backwards) => {
446 const editor = createCitationEditor();
447 const commentedCitation = { ...citation, comment: "Delete this with its quote.\n café 👋" };
448 const source = serializeAssistantCitation(commentedCitation);
449 editor.update(
450 () => {
451 const paragraph = $getRoot().getFirstChildOrThrow();
452 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
453 const before = $createTextNode("前(");
454 const after = $createTextNode(")後");
455 paragraph.append(
456 before,
457 $createComposerCitationNode(citation, citationSource).setComment(
458 commentedCitation.comment,
459 ),
460 after,
461 );
462 if (backwards) {
463 after.selectStart();
464 } else {
465 before.selectEnd();
466 }
467 },
468 { discrete: true },
469 );
470 const beforeDeletion = editor.getEditorState();
471 const serialized = beforeDeletion.toJSON();
472
473 editor.update(
474 () => {
475 const selection = $getSelection();
476 if (!$isRangeSelection(selection)) throw new Error("Expected a range selection");
477 selection.deleteCharacter(backwards);
478 },
479 { discrete: true },
480 );
481
482 const afterDeletion = editor.getEditorState();
483 expect(afterDeletion.read(() => $getRoot().getTextContent())).toBe("前()後");
484
485 editor.setEditorState(beforeDeletion);
486 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
487 `前(${source})後`,
488 );
489 editor.setEditorState(afterDeletion);
490 expect(editor.getEditorState().read(() => $citationNodes())).toHaveLength(0);
491
492 editor.setEditorState(editor.parseEditorState(serialized));
493 editor.getEditorState().read(() => {
494 expect($getRoot().getTextContent()).toBe(`前(${source})後`);
495 expect($citationNodes()[0]?.exportJSON().citation).toEqual(commentedCitation);
496 });
497 },
498 );
499});
500
501describe("context reference paste", () => {
502 it.each([
503 { focus: "focused", prefix: "" },
504 { focus: "blurred", prefix: "" },
505 { focus: "focused", prefix: "log ".repeat(10_000) },
506 { focus: "blurred", prefix: "log ".repeat(10_000) },
507 ])(
508 "imports structured paste when $focus with $prefix.length extra characters",
509 ({ focus, prefix }) => {
510 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
511 const editor = createEditor({ nodes: [ComposerCitationNode] });
512 editor.update(
513 () => {
514 const paragraph = $createParagraphNode();
515 $getRoot().append(paragraph);
516 paragraph.selectEnd();
517 },
518 { discrete: true },
519 );
520 const imported: string[] = [];
521 const importFragment = (
522 fragment: import("@t3tools/contracts").ComposerContextClipboardFragment,
523 ) => {
524 imported.push(...fragment.records.map((record) => record.contextId));
525 return new Map([["img-old", "img-new"]]);
526 };
527 registerComposerInlineTokenPaste(editor, {
528 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
529 createCitationNode: $createComposerCitationNode,
530 createContextReferenceNode: (reference) =>
531 $createTextNode(`<context:${reference.contextId}>`),
532 getExpandedAbsoluteOffsetForPoint: () => 0,
533 importContextFragment: importFragment,
534 });
535 const event = new TestClipboardEvent(
536 `${prefix} and [T](t3-context://v1/terminal/ctx-t)`,
537 {
538 "web application/x-t3-context-fragment+json": JSON.stringify({
539 version: 1,
540 source: { environmentId: "env-1" },
541 records: [
542 {
543 version: 1,
544 contextId: "img-old",
545 kind: "image",
546 label: "shot",
547 attachmentId: "a",
548 name: "shot.png",
549 mimeType: "image/png",
550 sizeBytes: 1,
551 },
552 {
553 version: 1,
554 contextId: "ctx-t",
555 kind: "terminal",
556 label: "T",
557 terminalId: "t",
558 terminalLabel: "T",
559 lineStart: 1,
560 lineEnd: 1,
561 text: "x",
562 },
563 {
564 version: 1,
565 contextId: "img-unrelated",
566 kind: "image",
567 label: "other",
568 attachmentId: "b",
569 name: "other.png",
570 mimeType: "image/png",
571 sizeBytes: 1,
572 },
573 ],
574 }),
575 },
576 );
577 expect(
578 readPastedComposerContext(event.clipboardData)?.records.map((record) => record.contextId),
579 ).toEqual(["img-old", "ctx-t"]);
580 if (focus === "blurred") {
581 expect(importPastedComposerText(event.clipboardData, importFragment)).toBe(
582 `${prefix} and [T](t3-context://v1/terminal/ctx-t)`,
583 );
584 expect(imported).toEqual(["img-old", "ctx-t"]);
585 return;
586 }
587 editor.update(
588 () => {
589 editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
590 },
591 { discrete: true },
592 );
593 expect(imported).toEqual(["img-old", "ctx-t"]);
594 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
595 `${prefix}<context:img-new> and <context:ctx-t>`,
596 );
597 },
598 );
599
600 it("converts a copied legacy element into a sendable annotation and rewrites its link", () => {
601 const copied = upgradeLegacyContextMessage(
602 [
603 "Fix this",
604 "",
605 "<element_context>",
606 "- <button>:",
607 " url: https://example.com",
608 " selector: #save",
609 " html:",
610 " <button>Save</button>",
611 " styles:",
612 " color: red;",
613 "</element_context>",
614 ].join("\n"),
615 );
616 const event = new TestClipboardEvent(copied.text, {
617 "web application/x-t3-context-fragment+json": JSON.stringify({
618 version: 1,
619 source: { environmentId: "env-1" },
620 records: copied.records,
621 }),
622 });
623 const annotations: ReturnType<typeof previewAnnotationContextRecord>[] = [];
624 const text = importPastedComposerText(event.clipboardData, (fragment) => {
625 const record = fragment.records[0]!;
626 if (record.kind !== "element" || "payload" in record) throw new Error("Expected element");
627 const annotation = previewAnnotationContextRecord(
628 elementContextToPreviewAnnotation(record, "imported", "2026-01-01T00:00:00Z"),
629 );
630 annotations.push(annotation);
631 return new Map([[record.contextId, annotation.contextId]]);
632 });
633 expect(text).toContain("t3-context://v1/preview-annotation/preview-annotation_imported");
634 expect(annotations[0]?.elements?.[0]).toMatchObject({
635 selector: "#save",
636 htmlPreview: "<button>Save</button>",
637 styles: "color: red;",
638 });
639 });
640
641 it("imports an annotation's dependent screenshot when only its chip is pasted", () => {
642 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
643 const editor = createEditor({ nodes: [ComposerCitationNode] });
644 editor.update(
645 () => {
646 const paragraph = $createParagraphNode();
647 $getRoot().append(paragraph);
648 paragraph.selectEnd();
649 },
650 { discrete: true },
651 );
652 const imported: string[] = [];
653 registerComposerInlineTokenPaste(editor, {
654 createMentionNode: (path) => $createTextNode(`<mention:${path}>`),
655 createCitationNode: $createComposerCitationNode,
656 createContextReferenceNode: (reference) =>
657 $createTextNode(`<context:${reference.contextId}>`),
658 getExpandedAbsoluteOffsetForPoint: () => 0,
659 importContextFragment: (fragment) => {
660 imported.push(...fragment.records.map((record) => record.contextId));
661 return new Map();
662 },
663 });
664 const annotationId = "preview-annotation_ann-1";
665 const screenshotId = "image_ann-1";
666 const event = new TestClipboardEvent(
667 `[Fix button](t3-context://v1/preview-annotation/${annotationId})`,
668 {
669 "web application/x-t3-context-fragment+json": JSON.stringify({
670 version: 1,
671 source: { environmentId: "env-1" },
672 records: [
673 {
674 version: 1,
675 contextId: annotationId,
676 kind: "preview-annotation",
677 label: "Fix button",
678 annotationId: "ann-1",
679 pageUrl: "https://example.com",
680 pageTitle: "Example",
681 comment: "Fix button",
682 targetSummary: "1 selected element",
683 styleChanges: [],
684 screenshotContextId: screenshotId,
685 },
686 {
687 version: 1,
688 contextId: screenshotId,
689 kind: "image",
690 label: "annotation.png",
691 attachmentId: "attachment-1",
692 name: "annotation.png",
693 mimeType: "image/png",
694 sizeBytes: 10,
695 },
696 {
697 version: 1,
698 contextId: "image_unrelated",
699 kind: "image",
700 label: "unrelated.png",
701 attachmentId: "attachment-2",
702 name: "unrelated.png",
703 mimeType: "image/png",
704 sizeBytes: 10,
705 },
706 ],
707 }),
708 },
709 );
710 editor.update(
711 () => {
712 editor.dispatchCommand(PASTE_COMMAND, event as ClipboardEvent);
713 },
714 { discrete: true },
715 );
716
717 expect(imported).toEqual([annotationId, screenshotId]);
718 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
719 `<context:${annotationId}>`,
720 );
721 });
722
723 it("turns pasted context links into reference nodes", () => {
724 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
725 const editor = createCitationEditor("see ");
726 pasteText(editor, "[Terminal 1 line 4](t3-context://v1/terminal/ctx-1) now");
727 expect(editor.getEditorState().read(() => $getRoot().getTextContent())).toBe(
728 "see <context:ctx-1> now",
729 );
730 });
731});
732
733describe("citation comment opening", () => {
734 const sourceAnchor: AssistantCitationSourceAnchor = {
735 source: { nodeType: 1 } as HTMLElement,
736 range: { collapsed: false } as Range,
737 viewport: { nodeType: 1 } as HTMLElement,
738 };
739 afterEach(() => {
740 vi.unstubAllGlobals();
741 });
742
743 it("opens only the newly inserted occurrence after committing its exact prompt", () => {
744 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
745 const editor = createCitationEditor();
746 const previousValue = `前 ${citationSource} middle\nbefore after ${citationSource} 後`;
747 pasteText(editor, previousValue);
748 const citationStart = `前 ${citationSource} middle\nbefore `.length;
749 const value =
750 previousValue.slice(0, citationStart) +
751 `${citationSource} ` +
752 previousValue.slice(citationStart);
753 const request: ComposerCitationCommentRequest = {
754 previousValue,
755 value,
756 citationStart,
757 sourceAnchor,
758 };
759 const requestRef = { current: request as ComposerCitationCommentRequest | null };
760
761 editor.getEditorState().read(() => {
762 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
763 expect(requestRef.current).toBe(request);
764 });
765 editor.update(
766 () => {
767 const text = $getRoot()
768 .getAllTextNodes()
769 .find((node) => node.getTextContent() === "before after ");
770 if (!text) throw new Error("Expected insertion text");
771 text.select("before ".length, "before ".length);
772 },
773 { discrete: true },
774 );
775 pasteText(editor, `${citationSource} `);
776
777 editor.getEditorState().read(() => {
778 const selection = $getSelection()?.clone();
779 expect($getRoot().getTextContent()).toBe(value);
780 expect($citationNodes()).toHaveLength(3);
781 const target = $consumeComposerCitationCommentRequest(requestRef);
782 expect(target?.nodeKey).toBe($citationNodes()[1]!.getKey());
783 expect(target?.sourceAnchor).toBe(sourceAnchor);
784 expect($getSelection()?.is(selection!)).toBe(true);
785 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
786 });
787 });
788
789 it("does not reopen comments when an inserted citation is restored or pasted", () => {
790 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
791 const editor = createCitationEditor("before ");
792 const previousState = editor.getEditorState();
793 const value = `before ${citationSource} `;
794 const requestRef: { current: ComposerCitationCommentRequest | null } = {
795 current: { previousValue: "before ", value, citationStart: "before ".length, sourceAnchor },
796 };
797 pasteText(editor, `${citationSource} `);
798 const insertedState = editor.getEditorState();
799 insertedState.read(() => {
800 expect($consumeComposerCitationCommentRequest(requestRef)?.nodeKey).toBe(
801 $citationNodes()[0]!.getKey(),
802 );
803 });
804 editor.update(() => $citationNodes()[0]!.setComment("Keep this attached."), {
805 discrete: true,
806 });
807 const commentedState = editor.getEditorState();
808
809 for (const restoredState of [previousState, insertedState, commentedState]) {
810 editor.setEditorState(restoredState);
811 editor.getEditorState().read(() => {
812 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
813 });
814 }
815
816 const reloaded = createCitationEditor();
817 reloaded.setEditorState(reloaded.parseEditorState(commentedState.toJSON()));
818 reloaded.getEditorState().read(() => {
819 expect($consumeComposerCitationCommentRequest({ current: null })).toBeNull();
820 expect($citationNodes()[0]!.exportJSON().citation.comment).toBe("Keep this attached.");
821 });
822 const pasted = createCitationEditor();
823 pasteText(
824 pasted,
825 commentedState.read(() => $getRoot().getTextContent()),
826 );
827 pasted.getEditorState().read(() => {
828 expect($consumeComposerCitationCommentRequest({ current: null })).toBeNull();
829 expect($citationNodes()[0]!.exportJSON().citation.comment).toBe("Keep this attached.");
830 });
831 });
832
833 it("discards an opening request if another prompt replaces the insertion", () => {
834 vi.stubGlobal("ClipboardEvent", TestClipboardEvent);
835 const editor = createCitationEditor();
836 const requestRef: { current: ComposerCitationCommentRequest | null } = {
837 current: { previousValue: "", value: citationSource, citationStart: 0, sourceAnchor },
838 };
839 editor.update(
840 () => {
841 const selection = $getSelection();
842 if (!$isRangeSelection(selection)) throw new Error("Expected an insertion point");
843 selection.insertText("A different draft");
844 },
845 { discrete: true },
846 );
847 editor.getEditorState().read(() => {
848 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
849 });
850 editor.update(
851 () => {
852 const paragraph = $getRoot().getFirstChildOrThrow();
853 if (!$isElementNode(paragraph)) throw new Error("Expected a composer paragraph");
854 paragraph.clear().selectStart();
855 },
856 { discrete: true },
857 );
858 pasteText(editor, citationSource);
859 editor.getEditorState().read(() => {
860 expect($getRoot().getTextContent()).toBe(citationSource);
861 expect($consumeComposerCitationCommentRequest(requestRef)).toBeNull();
862 });
863 });
864});