v4CodeCommentComposer.test.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import { act, createElement } from "react";
  2. import { createRoot, type Root } from "react-dom/client";
  3. import { afterEach, describe, expect, it, vi } from "vitest";
  4. import {
  5. dispatchCodeCommentAddToChat,
  6. dispatchCodeCommentRemoveFromChat,
  7. type CodeCommentPayload,
  8. } from "@/lib/codeCommentContext.js";
  9. import type { ConversationSelectionReference } from "@/lib/conversationSelectionReference.js";
  10. import type { WebElementContextComposerAttachment } from "@/lib/webElementContext.js";
  11. import type { PptxElementReference } from "@/lib/pptxElementReference.js";
  12. import {
  13. countComposerPromptContexts,
  14. parseComposerPromptContexts,
  15. serializeComposerPromptContexts,
  16. } from "@/v4/composer/composerPromptContexts.js";
  17. import {
  18. useCodeCommentContexts,
  19. type UseCodeCommentContextsResult,
  20. } from "@/v4/composer/useCodeCommentContexts.js";
  21. let latestApi: UseCodeCommentContextsResult | null = null;
  22. function createMinimalElement(ownerDocument: Document, tagName = "div") {
  23. const element = {
  24. addEventListener: () => {},
  25. appendChild: (child: Node) => {
  26. Object.assign(child, { parentNode: element });
  27. element.childNodes.push(child);
  28. return child;
  29. },
  30. childNodes: [] as Node[],
  31. insertBefore: (child: Node, beforeChild?: Node | null) => {
  32. Object.assign(child, { parentNode: element });
  33. const beforeIndex = beforeChild ? element.childNodes.indexOf(beforeChild) : -1;
  34. if (beforeIndex >= 0) element.childNodes.splice(beforeIndex, 0, child);
  35. else element.childNodes.push(child);
  36. return child;
  37. },
  38. nodeName: tagName.toUpperCase(),
  39. nodeType: 1,
  40. ownerDocument,
  41. parentNode: null as Node | null,
  42. removeChild: (child: Node) => {
  43. element.childNodes = element.childNodes.filter((candidate) => candidate !== child);
  44. Object.assign(child, { parentNode: null });
  45. return child;
  46. },
  47. removeEventListener: () => {},
  48. style: {},
  49. tagName: tagName.toUpperCase(),
  50. };
  51. return element as unknown as Element;
  52. }
  53. function installMinimalDom() {
  54. const target = new EventTarget();
  55. const documentMock = {
  56. addEventListener: () => {},
  57. createComment: (nodeValue: string) => ({ nodeType: 8, nodeValue, parentNode: null }),
  58. createElement: (tagName: string) =>
  59. createMinimalElement(documentMock as unknown as Document, tagName),
  60. createElementNS: (_namespace: string, tagName: string) =>
  61. createMinimalElement(documentMock as unknown as Document, tagName),
  62. createTextNode: (nodeValue: string) => ({ nodeType: 3, nodeValue, parentNode: null }),
  63. nodeType: 9,
  64. removeEventListener: () => {},
  65. } as unknown as Document & { defaultView?: unknown };
  66. const windowMock = {
  67. addEventListener: target.addEventListener.bind(target),
  68. cancelAnimationFrame: () => {},
  69. clearTimeout,
  70. dispatchEvent: target.dispatchEvent.bind(target),
  71. document: documentMock,
  72. HTMLIFrameElement: function HTMLIFrameElement() {},
  73. HTMLElement: function HTMLElement() {},
  74. Node: function Node() {},
  75. removeEventListener: target.removeEventListener.bind(target),
  76. requestAnimationFrame: (callback: FrameRequestCallback) => {
  77. callback(0);
  78. return 0;
  79. },
  80. setTimeout,
  81. };
  82. documentMock.defaultView = windowMock;
  83. vi.stubGlobal("document", documentMock);
  84. vi.stubGlobal("window", windowMock);
  85. vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
  86. return createMinimalElement(documentMock, "div");
  87. }
  88. function Harness({
  89. listen,
  90. onContextRemoved,
  91. requestFocus,
  92. scopeKey = "/target\0session-1",
  93. }: {
  94. listen: boolean;
  95. onContextRemoved: (context: CodeCommentPayload & { id: string }) => void;
  96. requestFocus: () => void;
  97. scopeKey?: string;
  98. }) {
  99. latestApi = useCodeCommentContexts({
  100. listenAddToChatEvents: listen,
  101. onContextRemoved,
  102. requestFocus,
  103. scopeKey,
  104. });
  105. return null;
  106. }
  107. function renderHarness(props: Parameters<typeof Harness>[0]): Root {
  108. const root = createRoot(installMinimalDom());
  109. act(() => root.render(createElement(Harness, props)));
  110. return root;
  111. }
  112. function comment(
  113. workspaceIdentity: string,
  114. value: string,
  115. ): CodeCommentPayload {
  116. return {
  117. id: "same-id",
  118. workspacePath: "/source",
  119. workspaceIdentity,
  120. sourcePath: "/source/example.ts",
  121. sourceTitle: "example.ts",
  122. startLine: 4,
  123. endLine: 5,
  124. selectedText: "const value = 1;",
  125. comment: value,
  126. };
  127. }
  128. afterEach(() => {
  129. latestApi = null;
  130. vi.restoreAllMocks();
  131. vi.unstubAllGlobals();
  132. });
  133. describe("V4 code comment composer context", () => {
  134. it("claims add-to-chat, replaces the same source comment, focuses, and removes exactly", () => {
  135. const requestFocus = vi.fn();
  136. const onContextRemoved = vi.fn();
  137. const root = renderHarness({ listen: true, onContextRemoved, requestFocus });
  138. act(() => {
  139. expect(dispatchCodeCommentAddToChat(comment("remote:ssh:a:/source", "first"))).toBe(true);
  140. expect(dispatchCodeCommentAddToChat(comment("remote:ssh:a:/source", "updated"))).toBe(true);
  141. expect(dispatchCodeCommentAddToChat(comment("remote:ssh:b:/source", "other"))).toBe(true);
  142. });
  143. expect(latestApi?.contexts).toMatchObject([
  144. { comment: "updated", workspaceIdentity: "remote:ssh:a:/source" },
  145. { comment: "other", workspaceIdentity: "remote:ssh:b:/source" },
  146. ]);
  147. expect(requestFocus).toHaveBeenCalledTimes(3);
  148. act(() => {
  149. dispatchCodeCommentRemoveFromChat({
  150. id: "same-id",
  151. workspacePath: "/source",
  152. workspaceIdentity: "remote:ssh:a:/source",
  153. });
  154. });
  155. expect(latestApi?.contexts).toMatchObject([
  156. { comment: "other", workspaceIdentity: "remote:ssh:b:/source" },
  157. ]);
  158. expect(onContextRemoved).toHaveBeenCalledWith(
  159. expect.objectContaining({ workspaceIdentity: "remote:ssh:a:/source" }),
  160. );
  161. act(() => root.unmount());
  162. });
  163. it("does not claim events in a background pane", () => {
  164. const root = renderHarness({
  165. listen: false,
  166. onContextRemoved: vi.fn(),
  167. requestFocus: vi.fn(),
  168. });
  169. expect(dispatchCodeCommentAddToChat(comment("remote:ssh:a:/source", "first"))).toBe(false);
  170. expect(latestApi?.contexts).toHaveLength(0);
  171. act(() => root.unmount());
  172. });
  173. it("clears the claimed comment when the target composer scope changes", () => {
  174. const requestFocus = vi.fn();
  175. const onContextRemoved = vi.fn();
  176. const firstProps = { listen: true, onContextRemoved, requestFocus };
  177. const root = renderHarness(firstProps);
  178. act(() => {
  179. dispatchCodeCommentAddToChat(comment("remote:ssh:a:/source", "first"));
  180. });
  181. expect(latestApi?.contexts).toHaveLength(1);
  182. act(() => {
  183. root.render(
  184. createElement(Harness, {
  185. ...firstProps,
  186. scopeKey: "/target\0session-2",
  187. }),
  188. );
  189. });
  190. expect(latestApi?.contexts).toHaveLength(0);
  191. expect(onContextRemoved).toHaveBeenCalledWith(
  192. expect.objectContaining({ id: "same-id" }),
  193. );
  194. act(() => root.unmount());
  195. });
  196. });
  197. describe("V4 composer prompt contexts", () => {
  198. it("serializes and parses conversation selections, code comments, and web elements", () => {
  199. const selection: ConversationSelectionReference = {
  200. id: "selection-1",
  201. sourceSessionId: "source-session",
  202. sourceRowId: 3,
  203. contentType: "assistant",
  204. text: "selected answer",
  205. };
  206. const webElement: WebElementContextComposerAttachment = {
  207. id: "element-1",
  208. workspacePath: "/target",
  209. pageUrl: "https://example.test",
  210. pageTitle: "Example",
  211. tagName: "button",
  212. text: "Save",
  213. capturedAt: 1,
  214. };
  215. const codeComment = { ...comment("remote:ssh:a:/source", "rename this"), id: "comment-1" };
  216. const pptxElement: PptxElementReference = {
  217. id: "pptx-1",
  218. workspacePath: "/target",
  219. sourcePath: "/target/deck.pptx",
  220. sourceTitle: "deck.pptx",
  221. sourceFingerprint: `sha256:${"a".repeat(64)}`,
  222. slideIndex: 0,
  223. slidePart: "ppt/slides/slide1.xml",
  224. nodeId: "7",
  225. nodeName: "Title 1",
  226. nodeType: "shape",
  227. bounds: { x: 0, y: 0, width: 100, height: 30 },
  228. zIndex: 1,
  229. capturedAt: 1,
  230. };
  231. const serialized = serializeComposerPromptContexts("visible body", {
  232. codeComments: [codeComment],
  233. conversationSelections: [selection],
  234. webElements: [webElement],
  235. pptxElements: [pptxElement],
  236. });
  237. expect(serialized.indexOf("# userselect:")).toBeGreaterThan(0);
  238. expect(serialized.indexOf("# Code comments:")).toBeGreaterThan(
  239. serialized.indexOf("# userselect:"),
  240. );
  241. expect(serialized.indexOf("# Web page elements:")).toBeGreaterThan(
  242. serialized.indexOf("# Code comments:"),
  243. );
  244. expect(
  245. serialized.indexOf("# Presentation element comments:"),
  246. ).toBeGreaterThan(
  247. serialized.indexOf("# Web page elements:"),
  248. );
  249. expect(
  250. parseComposerPromptContexts(serialized, {
  251. workspacePath: "/target",
  252. workspaceIdentity: "remote:ssh:target:/target",
  253. }),
  254. ).toMatchObject({
  255. visibleContent: "visible body",
  256. codeComments: [{ comment: "rename this", sourcePath: "/source/example.ts" }],
  257. conversationSelections: [{ text: "selected answer" }],
  258. webElements: [{ pageUrl: "https://example.test", tagName: "button" }],
  259. pptxElements: [{ sourceTitle: "deck.pptx", nodeId: "7" }],
  260. });
  261. expect(
  262. countComposerPromptContexts({
  263. codeComments: [codeComment],
  264. conversationSelections: [selection],
  265. webElements: [webElement],
  266. pptxElements: [pptxElement],
  267. }),
  268. ).toBe(4);
  269. });
  270. });