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

ComposerPromptEditor.test.ts

852 lines30.7 KB

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