v4WebElementContextAttachment.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. import { act, createElement, type ReactNode } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import {
  5. WEB_ELEMENT_CONTEXT_REMOVE_FROM_CHAT_EVENT,
  6. dispatchWebElementContextAddToChat,
  7. type WebElementContextPayload,
  8. } from "@/lib/webElementContext.js";
  9. import {
  10. dispatchCodeCommentAddToChat,
  11. type CodeCommentPayload,
  12. } from "@/lib/codeCommentContext.js";
  13. import { ConversationComposer } from "@/v4/ConversationComposer.js";
  14. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  15. const { chatPromptEditorProps } = vi.hoisted(() => ({
  16. chatPromptEditorProps: [] as Array<Record<string, unknown>>,
  17. }));
  18. vi.mock("@/ControlHintTooltip.js", async () => {
  19. const React = await import("react");
  20. return {
  21. ControlHintTooltip: ({ children }: { children: ReactNode }) =>
  22. React.createElement(React.Fragment, null, children),
  23. };
  24. });
  25. vi.mock("@/prompt-editor/ChatPromptEditor.js", async () => {
  26. const React = await import("react");
  27. return {
  28. ChatPromptEditor: (props: Record<string, unknown>) => {
  29. chatPromptEditorProps.push(props);
  30. const inputApiRef = props.inputApiRef as
  31. | { current: Record<string, unknown> | null }
  32. | undefined;
  33. if (inputApiRef) {
  34. inputApiRef.current = {
  35. clear: vi.fn(),
  36. focus: vi.fn(),
  37. getEditorState: () => null,
  38. getMarkdown: () => "",
  39. setEditorStateJson: vi.fn(),
  40. setText: vi.fn(),
  41. };
  42. }
  43. return React.createElement(
  44. "form",
  45. { "data-testid": "mock-chat-prompt-editor" },
  46. props.topContent as ReactNode,
  47. props.leadingActions as ReactNode,
  48. props.submitControl as ReactNode,
  49. );
  50. },
  51. };
  52. });
  53. vi.mock("@/components/ai-elements/attachments.js", async () => {
  54. const React = await import("react");
  55. const Passthrough = ({
  56. children,
  57. ...props
  58. }: {
  59. children?: React.ReactNode;
  60. } & Record<string, unknown>) => React.createElement("div", props, children);
  61. const Trigger = ({ children }: { children?: React.ReactNode }) =>
  62. React.createElement(React.Fragment, null, children);
  63. const Span = (props: Record<string, unknown>) => React.createElement("span", props);
  64. return {
  65. Attachment: Passthrough,
  66. AttachmentHoverCard: Passthrough,
  67. AttachmentHoverCardContent: Passthrough,
  68. AttachmentHoverCardTrigger: Trigger,
  69. AttachmentInfo: Span,
  70. AttachmentPreview: Span,
  71. AttachmentRemove: (props: Record<string, unknown>) => React.createElement("button", props),
  72. Attachments: Passthrough,
  73. };
  74. });
  75. vi.mock("@/v4/composer/useComposerAttachments.js", () => ({
  76. useComposerAttachments: () => ({
  77. attachmentError: null,
  78. adoptSentAttachments: vi.fn(async () => {}),
  79. attachmentInputRef: { current: null },
  80. attachments: [],
  81. clearAttachments: vi.fn(),
  82. handleAttachmentInputChange: vi.fn(),
  83. handleDragLeaveComposer: vi.fn(),
  84. handleDragOverComposer: vi.fn(),
  85. handleDropComposer: vi.fn(),
  86. handlePaste: vi.fn(),
  87. handleWhiteboardMentionSelected: vi.fn(),
  88. hasAttachments: false,
  89. hasUnreadyAttachments: false,
  90. isDraggingOverComposer: false,
  91. openAttachmentPicker: vi.fn(),
  92. prepareForSend: vi.fn(async () => []),
  93. removeAttachment: vi.fn(),
  94. retryAttachment: vi.fn(),
  95. setAttachmentError: vi.fn(),
  96. }),
  97. }));
  98. vi.mock("@/v4/composer/V4ComposerToolbar.js", async () => {
  99. const React = await import("react");
  100. return {
  101. V4ComposerModeSwitch: () => React.createElement("span", null, "mode"),
  102. V4ComposerModelControls: () => React.createElement("span", null, "model"),
  103. };
  104. });
  105. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  106. const element = {
  107. addEventListener: () => {},
  108. appendChild: (child: Node) => {
  109. Object.assign(child, { parentNode: element });
  110. element.childNodes.push(child);
  111. return child;
  112. },
  113. attributes: new Map<string, string>(),
  114. childNodes: [] as Node[],
  115. getAttribute: (name: string) => element.attributes.get(name) ?? null,
  116. insertBefore: (child: Node, beforeChild?: Node | null) => {
  117. Object.assign(child, { parentNode: element });
  118. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  119. if (beforeIndex >= 0) {
  120. element.childNodes.splice(beforeIndex, 0, child);
  121. } else {
  122. element.childNodes.push(child);
  123. }
  124. return child;
  125. },
  126. nodeName: tagName.toUpperCase(),
  127. nodeType: 1,
  128. ownerDocument,
  129. parentNode: null as Node | null,
  130. removeAttribute: (name: string) => {
  131. element.attributes.delete(name);
  132. },
  133. removeChild: (child: Node) => {
  134. element.childNodes = element.childNodes.filter((item) => item !== child);
  135. Object.assign(child, { parentNode: null });
  136. return child;
  137. },
  138. removeEventListener: () => {},
  139. setAttribute: (name: string, value: string) => {
  140. element.attributes.set(name, String(value));
  141. },
  142. style: {},
  143. tagName: tagName.toUpperCase(),
  144. };
  145. return element as unknown as Element;
  146. }
  147. function createStorageMock(): Storage {
  148. const values = new Map<string, string>();
  149. return {
  150. clear: () => values.clear(),
  151. getItem: (key: string) => values.get(key) ?? null,
  152. key: (index: number) => Array.from(values.keys())[index] ?? null,
  153. get length() {
  154. return values.size;
  155. },
  156. removeItem: (key: string) => {
  157. values.delete(key);
  158. },
  159. setItem: (key: string, value: string) => {
  160. values.set(key, String(value));
  161. },
  162. } as Storage;
  163. }
  164. function installMinimalDom() {
  165. class CustomEventMock<T = unknown> extends Event {
  166. detail: T;
  167. constructor(type: string, init?: CustomEventInit<T>) {
  168. super(type, init);
  169. this.detail = init?.detail as T;
  170. }
  171. }
  172. const target = new EventTarget();
  173. const documentMock = {
  174. addEventListener: () => {},
  175. createComment: (nodeValue: string) => ({
  176. nodeType: 8,
  177. nodeValue,
  178. parentNode: null,
  179. }),
  180. createElement: (tagName: string) =>
  181. createMinimalElement(documentMock as unknown as Document, tagName),
  182. createElementNS: (_namespace: string, tagName: string) =>
  183. createMinimalElement(documentMock as unknown as Document, tagName),
  184. createTextNode: (nodeValue: string) => ({
  185. nodeType: 3,
  186. nodeValue,
  187. parentNode: null,
  188. }),
  189. nodeType: 9,
  190. removeEventListener: () => {},
  191. } as unknown as Document & { defaultView?: unknown };
  192. const windowMock = {
  193. addEventListener: target.addEventListener.bind(target),
  194. cancelAnimationFrame: () => {},
  195. clearTimeout,
  196. CustomEvent: CustomEventMock,
  197. dispatchEvent: target.dispatchEvent.bind(target),
  198. document: documentMock,
  199. HTMLIFrameElement: function HTMLIFrameElement() {},
  200. HTMLElement: function HTMLElement() {},
  201. localStorage: createStorageMock(),
  202. matchMedia: () => ({
  203. addEventListener: () => {},
  204. addListener: () => {},
  205. matches: false,
  206. removeEventListener: () => {},
  207. removeListener: () => {},
  208. }),
  209. Node: function Node() {},
  210. removeEventListener: target.removeEventListener.bind(target),
  211. requestAnimationFrame: (callback: FrameRequestCallback) => {
  212. callback(0);
  213. return 0;
  214. },
  215. setTimeout,
  216. };
  217. documentMock.defaultView = windowMock;
  218. Object.defineProperty(globalThis, "CustomEvent", {
  219. configurable: true,
  220. value: CustomEventMock,
  221. });
  222. Object.defineProperty(globalThis, "document", {
  223. configurable: true,
  224. value: documentMock,
  225. });
  226. Object.defineProperty(globalThis, "window", {
  227. configurable: true,
  228. value: windowMock,
  229. });
  230. Object.defineProperty(globalThis, "IS_REACT_ACT_ENVIRONMENT", {
  231. configurable: true,
  232. value: true,
  233. });
  234. return createMinimalElement(documentMock, "div");
  235. }
  236. function collectText(node: unknown): string {
  237. if (!node || typeof node !== "object") return "";
  238. const candidate = node as {
  239. childNodes?: unknown[];
  240. nodeValue?: string;
  241. textContent?: string;
  242. };
  243. if (typeof candidate.nodeValue === "string") return candidate.nodeValue;
  244. if (candidate.childNodes && candidate.childNodes.length > 0) {
  245. return candidate.childNodes.map((child) => collectText(child)).join("");
  246. }
  247. return typeof candidate.textContent === "string" ? candidate.textContent : "";
  248. }
  249. function makePayload(overrides: Partial<WebElementContextPayload> = {}): WebElementContextPayload {
  250. return {
  251. capturedAt: 1_700_000_000_000,
  252. id: "element-1",
  253. pageTitle: "Docs",
  254. pageUrl: "https://example.test/docs",
  255. role: "button",
  256. tagName: "button",
  257. text: "Submit",
  258. workspaceIdentity: "remote:workspace",
  259. workspacePath: "/workspace",
  260. ...overrides,
  261. };
  262. }
  263. function flushAsyncWork() {
  264. return new Promise((resolve) => setTimeout(resolve, 0));
  265. }
  266. function renderComposer(onSendText: (text: string, options?: unknown) => Promise<void>) {
  267. const container = installMinimalDom();
  268. const root: Root = createRoot(container);
  269. act(() => {
  270. root.render(
  271. createElement(
  272. ZCodeIntlProvider,
  273. { initialLocale: "en-US" },
  274. createElement(ConversationComposer, {
  275. composerDraft: { text: "", updatedAt: 0 },
  276. updateComposerContent: vi.fn(),
  277. replaceComposerDraft: vi.fn(),
  278. draftMode: true,
  279. onSelectModel: vi.fn(),
  280. onSelectThought: vi.fn(),
  281. onSendText,
  282. onStop: vi.fn(),
  283. onSwitchMode: vi.fn(),
  284. provider: undefined,
  285. sessionId: null,
  286. snapshot: null,
  287. workspaceIdentity: "remote:workspace",
  288. workspacePath: "/workspace",
  289. }),
  290. ),
  291. );
  292. });
  293. return { container, root };
  294. }
  295. afterEach(() => {
  296. chatPromptEditorProps.length = 0;
  297. delete (globalThis as { CustomEvent?: unknown }).CustomEvent;
  298. delete (globalThis as { document?: unknown }).document;
  299. delete (globalThis as { window?: unknown }).window;
  300. delete (globalThis as { IS_REACT_ACT_ENVIRONMENT?: unknown }).IS_REACT_ACT_ENVIRONMENT;
  301. });
  302. describe("V4 web element context attachment", () => {
  303. it("accepts focused workspace events and submits the prompt with a web element context block", async () => {
  304. const onSendText = vi.fn(async () => {});
  305. const { container, root } = renderComposer(onSendText);
  306. await act(async () => {
  307. dispatchWebElementContextAddToChat(
  308. makePayload({ id: "ignored", workspaceIdentity: "other-workspace" }),
  309. );
  310. });
  311. expect(collectText(container)).not.toContain("web element");
  312. await act(async () => {
  313. dispatchWebElementContextAddToChat(makePayload());
  314. });
  315. expect(collectText(container)).toContain("1 web element");
  316. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  317. expect(typeof submit).toBe("function");
  318. await act(async () => {
  319. (submit as (value: string) => void)("");
  320. await flushAsyncWork();
  321. });
  322. expect(onSendText).toHaveBeenCalledTimes(1);
  323. expect(onSendText.mock.calls[0]?.[0]).toContain("# Web page elements:");
  324. expect(onSendText.mock.calls[0]?.[0]).toContain("Text:\n```\nSubmit\n```");
  325. expect(onSendText.mock.calls[0]?.[1]).toMatchObject({
  326. contextAttachmentCount: 1,
  327. });
  328. expect(collectText(container)).not.toContain("1 web element");
  329. await act(async () => {
  330. root.unmount();
  331. });
  332. });
  333. it("removes matching web element contexts through the remove event and keeps them after failed send", async () => {
  334. const onSendText = vi.fn(async () => {
  335. throw new Error("send failed");
  336. });
  337. const { container, root } = renderComposer(onSendText);
  338. await act(async () => {
  339. dispatchWebElementContextAddToChat(makePayload());
  340. });
  341. expect(collectText(container)).toContain("1 web element");
  342. await act(async () => {
  343. window.dispatchEvent(
  344. new CustomEvent(WEB_ELEMENT_CONTEXT_REMOVE_FROM_CHAT_EVENT, {
  345. detail: {
  346. id: "missing",
  347. workspaceIdentity: "remote:workspace",
  348. workspacePath: "/workspace",
  349. },
  350. }),
  351. );
  352. });
  353. expect(collectText(container)).toContain("1 web element");
  354. const submit = chatPromptEditorProps.at(-1)?.onSubmit;
  355. await act(async () => {
  356. (submit as (value: string) => void)("Please inspect this");
  357. await flushAsyncWork();
  358. });
  359. expect(onSendText).toHaveBeenCalledTimes(1);
  360. expect(collectText(container)).toContain("1 web element");
  361. await act(async () => {
  362. window.dispatchEvent(
  363. new CustomEvent(WEB_ELEMENT_CONTEXT_REMOVE_FROM_CHAT_EVENT, {
  364. detail: {
  365. id: "element-1",
  366. workspaceIdentity: "remote:workspace",
  367. workspacePath: "/workspace",
  368. },
  369. }),
  370. );
  371. });
  372. expect(collectText(container)).not.toContain("1 web element");
  373. await act(async () => {
  374. root.unmount();
  375. });
  376. });
  377. });
  378. describe("V4 code comment context attachment", () => {
  379. it("allows Enter to submit an empty editor when a code comment is attached", async () => {
  380. const onSendText = vi.fn(async () => {});
  381. const { root } = renderComposer(onSendText);
  382. const codeComment: CodeCommentPayload = {
  383. id: "comment-1",
  384. workspaceIdentity: "remote:workspace",
  385. workspacePath: "/workspace",
  386. sourcePath: "/workspace/example.ts",
  387. sourceTitle: "example.ts",
  388. startLine: 4,
  389. endLine: 5,
  390. selectedText: "const value = 1;",
  391. comment: "rename this",
  392. };
  393. await act(async () => {
  394. expect(dispatchCodeCommentAddToChat(codeComment)).toBe(true);
  395. });
  396. expect(chatPromptEditorProps.at(-1)?.allowSubmitWhenEmpty).toBe(true);
  397. await act(async () => {
  398. root.unmount();
  399. });
  400. });
  401. });