Open History to see the last commit
1import {
2 ASSISTANT_CITATION_MAX_COMMENT_LENGTH,
3 type AssistantCitation,
4 EnvironmentId,
5 MessageId,
6 ThreadId,
7} from "@t3tools/contracts";
8import { useState, type ReactNode } from "react";
9import { describe, expect, it, vi } from "vite-plus/test";
10import { page, userEvent } from "vite-plus/test/browser";
11import * as Effect from "effect/Effect";
12import * as Option from "effect/Option";
13
14import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
15import "~/index.css";
16import { act, render } from "../../../test/render";
17import { chooseAudioDestination, chooseTranscriptCleanup } from "../../speech/voiceConsent";
18
19const mocks = vi.hoisted(() => ({
20 observeSource: vi.fn(),
21 dispose: vi.fn(),
22 transcribeCalls: 0,
23 transcript: null as Promise<string> | null,
24}));
25const environment = vi.hoisted(() => ({
26 environmentId: "environment",
27 serverConfig: {
28 environment: { capabilities: { voiceTranscription: true, cloudVoiceTranscription: false } },
29 },
30}));
31const preparedConnection = vi.hoisted(() => ({
32 environmentId: "environment",
33 label: "environment",
34}));
35vi.mock(import("../../state/session"), async (importOriginal) => ({
36 ...(await importOriginal()),
37 useEnvironmentScope: () => true,
38 usePreparedConnection: ((environmentId: string | null) =>
39 environmentId === preparedConnection.environmentId
40 ? Option.some(preparedConnection)
41 : Option.none()) as never,
42}));
43vi.mock(import("../../state/environments"), async (importOriginal) => ({
44 ...(await importOriginal()),
45 useEnvironment: ((environmentId: string | null) =>
46 environmentId === environment.environmentId ? environment : null) as never,
47}));
48vi.mock(import("../../speech/runEnvironmentSpeech"), () => ({
49 runEnvironmentSpeech: Effect.runPromise as never,
50}));
51vi.mock(import("@t3tools/client-runtime/voice-input"), async (importOriginal) => ({
52 ...(await importOriginal()),
53 getEnvironmentSpeechStatus: (() =>
54 Effect.succeed({
55 supported: true,
56 state: "ready",
57 modelId: "test-model",
58 model: "Test",
59 size: 1,
60 supportsStreaming: false,
61 supportsTranslation: false,
62 acceleration: "auto",
63 benchmarkTier: "accelerated",
64 modelUnloadTimeout: "min_15",
65 gpuDevices: [],
66 })) as never,
67}));
68vi.mock(import("../../speech/browserVoiceInput"), () => ({
69 createAppleSpeechVoiceInputPlatform: vi.fn() as never,
70 createBrowserVoiceInputPlatform: (() => ({
71 recorder: {
72 uri: "blob:recording",
73 prepareToRecordAsync: async () => {},
74 record() {},
75 stop: async () => {},
76 },
77 transcriber: {
78 prepare: async () => ({
79 locale: "en",
80 transcribe: async () => {
81 mocks.transcribeCalls += 1;
82 return mocks.transcript ?? "dictated comment";
83 },
84 }),
85 },
86 cancelRecording() {},
87 deleteRecording() {},
88 })) as never,
89}));
90vi.mock(import("./AssistantCitationSource"), async (importOriginal) => ({
91 ...(await importOriginal()),
92 observeAssistantCitationCommentSource: mocks.observeSource,
93}));
94vi.mock(import("@tanstack/react-router"), async (importOriginal) => ({
95 ...(await importOriginal()),
96 useNavigate: () => vi.fn(),
97 Link: (({ children }: { children: ReactNode }) => <a>{children}</a>) as never,
98}));
99
100import { AssistantCitationChip } from "./AssistantCitationChip";
101
102const citation = {
103 version: 1 as const,
104 environmentId: EnvironmentId.make("environment"),
105 threadId: ThreadId.make("thread"),
106 messageId: MessageId.make("source"),
107 text: "hello",
108 start: 0,
109 end: 5,
110 prefix: "",
111 suffix: "",
112};
113
114// The mocked source observer is shared, so every test starts by resetting it.
115function setup() {
116 mocks.observeSource.mockReset().mockReturnValue(mocks.dispose);
117 mocks.dispose.mockClear();
118 const source = document.createElement("p");
119 source.textContent = "hello";
120 document.body.append(source);
121 const range = document.createRange();
122 range.selectNodeContents(source);
123 const sourceAnchor = { source, range, viewport: document.body } as AssistantCitationSourceAnchor;
124 return { sourceAnchor, [Symbol.dispose]: () => source.remove() };
125}
126
127function useDictation() {
128 chooseAudioDestination({ kind: "environment", environmentId: citation.environmentId });
129 chooseTranscriptCleanup(false);
130 mocks.transcribeCalls = 0;
131 mocks.transcript = null;
132}
133
134function mount(
135 sourceAnchor: AssistantCitationSourceAnchor | undefined,
136 onSave: () => boolean,
137 chipCitation: AssistantCitation = citation,
138) {
139 function Composer() {
140 const [open, setOpen] = useState(true);
141 return (
142 <AssistantCitationChip
143 citation={chipCitation}
144 commentEditor={{ open, sourceAnchor, onOpenChange: setOpen, onSave }}
145 />
146 );
147 }
148 return render(
149 <>
150 <Composer />
151 <button type="button">Outside</button>
152 </>,
153 );
154}
155
156const textarea = () =>
157 document.querySelector<HTMLTextAreaElement>('textarea[aria-label="Comment on selected text"]');
158
159async function typeComment(value: string) {
160 const input = textarea()!;
161 await act(async () => {
162 Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")!.set!.call(
163 input,
164 value,
165 );
166 input.dispatchEvent(new Event("input", { bubbles: true }));
167 });
168}
169
170async function removeSource() {
171 const { onUnavailable } = mocks.observeSource.mock.lastCall![0];
172 await act(async () => onUnavailable());
173}
174
175async function clickButton(label: string) {
176 const button = [...document.querySelectorAll("button")].find(
177 (element) => element.textContent?.trim() === label,
178 );
179 expect(button, `button ${label}`).toBeDefined();
180 await act(async () => button!.click());
181}
182
183describe("citation comment source disappearance", () => {
184 it("preserves an over-length draft at the composer until it can be shortened and saved", async () => {
185 using source = setup();
186 const onSave = vi.fn(() => true);
187 await using _screen = await mount(source.sourceAnchor, onSave);
188 const draft = "x".repeat(ASSISTANT_CITATION_MAX_COMMENT_LENGTH + 1);
189 await typeComment(draft);
190 await removeSource();
191
192 expect(textarea()?.value).toBe(draft);
193 expect(textarea()?.getAttribute("aria-invalid")).toBe("true");
194 expect(onSave).not.toHaveBeenCalled();
195 expect(mocks.dispose).toHaveBeenCalled();
196 expect(mocks.observeSource).toHaveBeenCalledTimes(1);
197
198 await typeComment("shortened comment");
199 await clickButton("Save");
200 expect(onSave).toHaveBeenCalledWith("shortened comment");
201 expect(textarea()).toBeNull();
202 });
203
204 it("keeps a draft open and unsaved when the cited row unmounts mid-typing", async () => {
205 using source = setup();
206 const onSave = vi.fn(() => true);
207 await using _screen = await mount(source.sourceAnchor, onSave);
208 await typeComment("if it's a good bug rep");
209 await removeSource();
210
211 expect(onSave).not.toHaveBeenCalled();
212 expect(textarea()?.value).toBe("if it's a good bug rep");
213
214 await typeComment("if it's a good bug report");
215 await clickButton("Save");
216 expect(onSave).toHaveBeenCalledExactlyOnceWith("if it's a good bug report");
217 });
218
219 it("preserves a rejected save and allows a later retry", async () => {
220 using source = setup();
221 const onSave = vi.fn(() => false);
222 await using _screen = await mount(source.sourceAnchor, onSave);
223 await typeComment("keep this draft");
224 await removeSource();
225 await clickButton("Save");
226
227 expect(onSave).toHaveBeenCalledWith("keep this draft");
228 expect(textarea()?.value).toBe("keep this draft");
229 onSave.mockReturnValue(true);
230 await clickButton("Save");
231 expect(onSave).toHaveBeenLastCalledWith("keep this draft");
232 expect(textarea()).toBeNull();
233 });
234});
235
236describe("citation comment caret", () => {
237 it("opens a saved comment with the caret after its end, scrolled into view", async () => {
238 using _source = setup();
239 const comment = `${"line\n".repeat(40)}end`;
240 await using _screen = await mount(
241 undefined,
242 vi.fn(() => true),
243 { ...citation, comment },
244 );
245 await vi.waitFor(() => expect(document.activeElement).toBe(textarea()));
246 const input = textarea()!;
247
248 expect(input.scrollHeight).toBeGreaterThan(input.clientHeight);
249 expect(input.scrollTop).toBe(input.scrollHeight - input.clientHeight);
250 await userEvent.keyboard("!");
251 expect(input.value).toBe(`${comment}!`);
252 });
253
254 it("saves with Tab then Enter after typing a comment", async () => {
255 using _source = setup();
256 const onSave = vi.fn(() => true);
257 await using _screen = await mount(undefined, onSave);
258 await vi.waitFor(() => expect(document.activeElement).toBe(textarea()));
259
260 await userEvent.keyboard("agreed");
261 await userEvent.keyboard("{Tab}");
262 await userEvent.keyboard("{Enter}");
263
264 expect(onSave).toHaveBeenCalledWith("agreed");
265 });
266});
267
268describe("citation comment popup position", () => {
269 it("opens at its anchor instead of sliding in from the window corner", async () => {
270 using source = setup();
271 await using _screen = await mount(
272 source.sourceAnchor,
273 vi.fn(() => true),
274 );
275 const positioner = () =>
276 document.querySelector<HTMLElement>('[data-slot="popover-positioner"]');
277 await vi.waitFor(() => expect(positioner()?.style.opacity).not.toBe("0"));
278
279 const moves = positioner()!
280 .getAnimations()
281 .filter(
282 (animation) =>
283 animation instanceof CSSTransition &&
284 ["transform", "top", "left"].includes(animation.transitionProperty),
285 );
286 expect(moves).toEqual([]);
287 });
288
289 it("stays on screen when the cited text ends in a code block's hidden overflow", async () => {
290 using _source = setup();
291 const message = document.createElement("div");
292 message.className = "chat-markdown";
293 message.style.width = "240px";
294 const pre = document.createElement("pre");
295 const code = document.createElement("code");
296 // Highlighted code is split into token spans, so the range's last client rect
297 // covers only the final token, wholly inside the hidden overflow.
298 for (let index = 0; index < 40; index += 1) {
299 const token = document.createElement("span");
300 token.textContent = `token${index} `;
301 code.append(token);
302 }
303 pre.append(code);
304 message.append(pre);
305 document.body.prepend(message);
306 using _message = { [Symbol.dispose]: () => message.remove() };
307 const range = document.createRange();
308 range.selectNodeContents(code);
309 const rects = range.getClientRects();
310 expect(rects.item(rects.length - 1)!.left).toBeGreaterThan(window.innerWidth);
311 const sourceAnchor = {
312 source: message,
313 range,
314 viewport: document.body,
315 } as AssistantCitationSourceAnchor;
316
317 await using _screen = await mount(
318 sourceAnchor,
319 vi.fn(() => true),
320 );
321 const popup = () => document.querySelector<HTMLElement>('[data-slot="popover-popup"]');
322 await vi.waitFor(() => expect(popup()?.getBoundingClientRect().width).toBeGreaterThan(0));
323 // Typing scrolls ancestors to reveal the caret, which shifts the whole app
324 // sideways when the box is off screen.
325 await userEvent.keyboard("note");
326
327 expect(textarea()?.value).toBe("note");
328 expect(document.scrollingElement?.scrollLeft).toBe(0);
329 expect(document.body.scrollLeft).toBe(0);
330 const rect = popup()!.getBoundingClientRect();
331 expect(rect.left).toBeGreaterThanOrEqual(0);
332 expect(rect.right).toBeLessThanOrEqual(window.innerWidth);
333 });
334});
335
336describe("citation comment dictation", () => {
337 async function startDictation(onSave: () => boolean) {
338 using _source = setup();
339 useDictation();
340 const screen = await mount(undefined, onSave);
341 await page.getByRole("button", { name: "Start voice input" }).click();
342 await expect.element(page.getByRole("button", { name: "Finish voice input" })).toBeVisible();
343 return screen;
344 }
345
346 it("keeps the dictation when the box is clicked away while recording", async () => {
347 const onSave = vi.fn(() => true);
348 await using _screen = await startDictation(onSave);
349
350 await page.getByRole("button", { name: "Outside" }).click();
351
352 await vi.waitFor(() => expect(onSave).toHaveBeenCalledWith("dictated comment"));
353 });
354
355 it("keeps the dictation when the box is clicked away while transcribing", async () => {
356 const onSave = vi.fn(() => true);
357 await using _screen = await startDictation(onSave);
358 let finish!: (text: string) => void;
359 mocks.transcript = new Promise((resolve) => (finish = resolve));
360 await page.getByRole("button", { name: "Finish voice input" }).click();
361 await vi.waitFor(() => expect(mocks.transcribeCalls).toBe(1));
362
363 await page.getByRole("button", { name: "Outside" }).click();
364 finish("dictated comment");
365
366 await vi.waitFor(() => expect(onSave).toHaveBeenCalledWith("dictated comment"));
367 });
368});