Open History to see the last commit
1import {
2 ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
3 EnvironmentId,
4 MessageId,
5 ThreadId,
6} from "@t3tools/contracts";
7import { useState, type ReactNode } from "react";
8import { describe, expect, it, vi } from "vite-plus/test";
9
10import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
11import { act, render } from "../../../test/render";
12
13const mocks = vi.hoisted(() => ({ observeSource: vi.fn(), dispose: vi.fn() }));
14vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
15 ...(await importOriginal()),
16 observeAssistantCitationCommentSource: mocks.observeSource,
17}));
18vi.mock(import("@tanstack/react-router"), async (importOriginal) => ({
19 ...(await importOriginal()),
20 useNavigate: () => vi.fn(),
21 Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,
22}));
23
24import { AssistantCitationChip } from "./AssistantCitationChip";
25
26const citation = {
27 version: 1 as const,
28 environmentId: EnvironmentId.make("environment"),
29 threadId: ThreadId.make("thread"),
30 messageId: MessageId.make("source"),
31 text: "hello",
32 start: 0,
33 end: 5,
34 prefix: "",
35 suffix: "",
36};
37
38// The mocked source observer is shared, so every test starts by resetting it.
39function setup() {
40 mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
41 mocks.dispose.mockClear();
42 const source = document.createElement("p");
43 source.textContent = "hello";
44 document.body.append(source);
45 const range = document.createRange();
46 range.selectNodeContents(source);
47 const sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
48 return { sourceAnchor, [Symbol.dispose]: () => source.remove() };
49}
50
51function mount(sourceAnchor: AssistantCitationSourceAnchor, onSave: () => boolean) {
52 function Composer() {
53 const [open, setOpen] = useState(true);
54 return (
55 <AssistantCitationChip
56 citation={citation}
57 composer
58 commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
59 />
60 );
61 }
62 return render(<Composer />);
63}
64
65const textarea = () =>
66 document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
67
68async function typeComment(value: string) {
69 const input = textarea()!;
70 await act(async () => {
71 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
72 input,
73 value,
74 );
75 input.dispatchEvent(new Event("input", { bubbles: true }));
76 });
77}
78
79async function removeSource() {
80 const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
81 await act(async () => onUnavailable());
82}
83
84async function clickButton(label: string) {
85 const button = [...document.querySelectorAll("button")].find(
86 (element) => element.textContent?.trim() === label,
87 );
88 expect(button, `button ${label}`).toBeDefined();
89 await act(async () => button!.click());
90}
91
92describe("citation comment source disappearance", () => {
93 it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
94 using source = setup();
95 const onSave = vi.fn(() => true);
96 await using _screen = await mount(source.sourceAnchor, onSave);
97 const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
98 await typeComment(draft);
99 await removeSource();
100
101 expect(textarea()?.value).toBe(draft);
102 expect(textarea()?.getAttribute("aria-invalid")).toBe("true");
103 expect(onSave).not.toHaveBeenCalled();
104 expect(mocks.dispose).toHaveBeenCalled();
105 expect(mocks.observeSource).toHaveBeenCalledTimes(1);
106
107 await typeComment("shortened comment");
108 await clickButton("Save");
109 expect(onSave).toHaveBeenCalledWith("shortened comment");
110 expect(textarea()).toBeNull();
111 });
112
113 it("preserves a rejected save and allows a later retry", async () => {
114 using source = setup();
115 const onSave = vi.fn(() => false);
116 await using _screen = await mount(source.sourceAnchor, onSave);
117 await typeComment("keep this draft");
118 await removeSource();
119
120 expect(onSave).toHaveBeenCalledWith("keep this draft");
121 expect(textarea()?.value).toBe("keep this draft");
122 onSave.mockReturnValue(true);
123 await clickButton("Save");
124 expect(onSave).toHaveBeenLastCalledWith("keep this draft");
125 expect(textarea()).toBeNull();
126 });
127});