nodeReplToolCallBlockInteraction.test.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /** @vitest-environment jsdom */
  2. import type { IBroadcastService } from "@zcode/services";
  3. import {
  4. createElement,
  5. type ComponentProps,
  6. type CSSProperties,
  7. type ReactNode,
  8. } from "react";
  9. import {
  10. cleanup,
  11. fireEvent,
  12. render,
  13. screen,
  14. waitFor,
  15. } from "@testing-library/react";
  16. import { afterEach, describe, expect, it, vi } from "vitest";
  17. import { ImagePreviewDialog } from "@/components/ai-elements/image-preview-dialog.js";
  18. import { TooltipProvider } from "@/components/ui/tooltip.js";
  19. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  20. import { StoreProvider } from "@/store/StoreProvider.js";
  21. import { NodeReplToolCallBlock } from "@/ToolCallBlocks/renderers/node-repl.js";
  22. vi.mock("@/components/ai-elements/code-block.js", () => ({
  23. CodeBlock: ({
  24. children,
  25. code,
  26. style,
  27. }: {
  28. children: ReactNode;
  29. code: string;
  30. style?: CSSProperties;
  31. }) =>
  32. createElement(
  33. "div",
  34. { "data-testid": "code-block", style },
  35. children,
  36. createElement("pre", null, code),
  37. ),
  38. CodeBlockActions: ({ children }: { children: ReactNode }) =>
  39. createElement("div", null, children),
  40. CodeBlockCopyButton: (props: ComponentProps<"button">) =>
  41. createElement("button", { ...props, type: "button" }),
  42. CodeBlockHeader: ({ children }: { children: ReactNode }) =>
  43. createElement("div", null, children),
  44. CodeBlockTitle: ({ children }: { children: ReactNode }) =>
  45. createElement("div", null, children),
  46. CodeBlockWrapButton: (props: ComponentProps<"button">) =>
  47. createElement("button", { ...props, type: "button" }),
  48. }));
  49. const mockBroadcastService: IBroadcastService = {
  50. send: async () => {},
  51. onMessage: () => ({ dispose: () => {} }),
  52. };
  53. const displayModel = {
  54. inlinePreview: { type: "none" as const },
  55. planResult: null,
  56. viewerSource: null,
  57. viewerLabelId: "codeViewer.viewCode" as const,
  58. showSummaryFileLink: false,
  59. showInput: false,
  60. showOutput: false,
  61. showKind: false,
  62. };
  63. function renderImageToolCall(source?: "browser_turn_end", imageCount = 1) {
  64. const toolCall = {
  65. toolId: source ? "tool-browser-turn-screenshot" : "tool-node-repl-image",
  66. toolName: "mcp__node_repl__js",
  67. kind: "mcp__node_repl__js",
  68. input: source
  69. ? { source }
  70. : { code: "nodeRepl.emitImage(await tab.screenshot());" },
  71. output: "",
  72. raw: {
  73. schemaVersion: 1,
  74. display: {
  75. kind: "node_repl_images",
  76. ...(source ? { source } : {}),
  77. images: Array.from({ length: imageCount }, (_, index) => ({
  78. base64: index === 0 ? "AAAA" : "BBBB",
  79. mimeType: "image/png",
  80. })),
  81. },
  82. },
  83. status: "completed" as const,
  84. };
  85. return render(
  86. createElement(
  87. ZCodeIntlProvider,
  88. { initialLocale: "zh-CN" },
  89. createElement(
  90. StoreProvider,
  91. { broadcastService: mockBroadcastService },
  92. createElement(
  93. TooltipProvider,
  94. null,
  95. createElement(NodeReplToolCallBlock, {
  96. toolCallNode: { toolCall, childToolCalls: [] },
  97. workspacePath: "/workspace",
  98. displayModel,
  99. viewerSource: null,
  100. rawFileSummaries: [],
  101. isRunning: false,
  102. statusLabel: "已执行",
  103. childToolList: null,
  104. forceOpen: true,
  105. canToggle: true,
  106. showIcon: true,
  107. }),
  108. ),
  109. ),
  110. ),
  111. );
  112. }
  113. afterEach(() => {
  114. cleanup();
  115. vi.restoreAllMocks();
  116. vi.unstubAllGlobals();
  117. });
  118. describe("node repl tool interaction", () => {
  119. it("uses the real code height when opening the tool and execution details", () => {
  120. const toolCall = {
  121. toolId: "tool-node-repl-stable-details-height",
  122. toolName: "js",
  123. kind: "js",
  124. title: "js",
  125. input: {
  126. code: "return await tab.title();",
  127. title: "读取页面标题",
  128. },
  129. output: { type: "text", value: '{\n "title": "示例页面"\n}' },
  130. status: "completed" as const,
  131. };
  132. render(
  133. createElement(
  134. ZCodeIntlProvider,
  135. { initialLocale: "zh-CN" },
  136. createElement(
  137. StoreProvider,
  138. { broadcastService: mockBroadcastService },
  139. createElement(
  140. TooltipProvider,
  141. null,
  142. createElement(NodeReplToolCallBlock, {
  143. toolCallNode: { toolCall, childToolCalls: [] },
  144. workspacePath: "/workspace",
  145. displayModel,
  146. viewerSource: null,
  147. rawFileSummaries: [],
  148. isRunning: false,
  149. statusLabel: "已执行",
  150. childToolList: null,
  151. forceOpen: true,
  152. canToggle: true,
  153. showIcon: true,
  154. }),
  155. ),
  156. ),
  157. ),
  158. );
  159. const [resultBlock] = screen.getAllByTestId("code-block");
  160. expect(resultBlock.style.contentVisibility).toBe("visible");
  161. expect(resultBlock.style.containIntrinsicSize).toBe("none");
  162. const expandedContent = screen.getByTestId("node-repl-expanded-content");
  163. expect(expandedContent.className).not.toContain("bg-card");
  164. expect(expandedContent.className).not.toContain("border");
  165. const resultSurface = screen.getByTestId("node-repl-result-surface");
  166. expect(resultSurface.className).toContain("bg-card");
  167. expect(resultSurface.className).toContain("rounded-xl");
  168. expect(resultSurface.className).toContain("border");
  169. expect(resultSurface.className).toContain("border-border");
  170. fireEvent.click(screen.getByRole("button", { name: "查看执行细节" }));
  171. const [, detailsBlock] = screen.getAllByTestId("code-block");
  172. expect(detailsBlock.style.contentVisibility).toBe("visible");
  173. expect(detailsBlock.style.containIntrinsicSize).toBe("none");
  174. const detailSurface = screen.getByTestId("node-repl-detail-surface");
  175. expect(detailSurface.className).toContain("bg-card");
  176. expect(detailSurface.className).toContain("rounded-xl");
  177. expect(detailSurface.className).toContain("border");
  178. expect(detailSurface.className).toContain("border-border");
  179. });
  180. it("renders a short single-line result as secondary text instead of a code block", () => {
  181. const toolCall = {
  182. toolId: "tool-node-repl-compact-result",
  183. toolName: "js",
  184. kind: "js",
  185. input: {
  186. code: "return await tab.title();",
  187. title: "读取页面标题",
  188. },
  189. output: { type: "text", value: "示例页面" },
  190. status: "completed" as const,
  191. };
  192. render(
  193. createElement(
  194. ZCodeIntlProvider,
  195. { initialLocale: "zh-CN" },
  196. createElement(
  197. StoreProvider,
  198. { broadcastService: mockBroadcastService },
  199. createElement(
  200. TooltipProvider,
  201. null,
  202. createElement(NodeReplToolCallBlock, {
  203. toolCallNode: { toolCall, childToolCalls: [] },
  204. workspacePath: "/workspace",
  205. displayModel,
  206. viewerSource: null,
  207. rawFileSummaries: [],
  208. isRunning: false,
  209. statusLabel: "已执行",
  210. childToolList: null,
  211. forceOpen: true,
  212. canToggle: true,
  213. showIcon: true,
  214. }),
  215. ),
  216. ),
  217. ),
  218. );
  219. const resultSurface = screen.getByTestId("node-repl-result-surface");
  220. expect(resultSurface.textContent).toBe("示例页面");
  221. expect(resultSurface.className).toContain("bg-card");
  222. expect(resultSurface.className).toContain("border-border");
  223. expect(screen.queryByTestId("code-block")).toBeNull();
  224. });
  225. it.each([
  226. ["显式 Node REPL 图片", undefined],
  227. ["自动轮尾图片", "browser_turn_end" as const],
  228. ])(
  229. "opens and closes the fullscreen preview for %s",
  230. async (_name, source) => {
  231. renderImageToolCall(source);
  232. const thumbnail = screen.getByRole("button", { name: "打开图片预览 1" });
  233. expect(thumbnail.className).toContain("max-w-1/2");
  234. expect(thumbnail.querySelector("img")?.className).toContain("max-h-90");
  235. expect(thumbnail.querySelector("img")?.className).toContain("rounded-xl");
  236. expect(screen.queryByTestId("node-repl-image-lightbox")).toBeNull();
  237. fireEvent.click(thumbnail);
  238. const lightbox = screen.getByTestId("node-repl-image-lightbox");
  239. const previewImage = screen.getByTestId("node-repl-image-lightbox-image");
  240. expect(lightbox.className).toContain("w-[calc(100vw-1rem)]");
  241. expect(lightbox.className).toContain("h-[calc(100dvh-1rem)]");
  242. expect(lightbox.className).toContain("sm:w-[calc(100vw-2rem)]");
  243. expect(lightbox.className).toContain("pointer-events-auto");
  244. expect(lightbox.className).toContain("[app-region:no-drag]");
  245. expect(previewImage.getAttribute("src")).toBe(
  246. "data:image/png;base64,AAAA",
  247. );
  248. expect(previewImage.className).toContain("max-h-full");
  249. expect(previewImage.className).toContain("max-w-full");
  250. expect(previewImage.getAttribute("draggable")).toBe("false");
  251. expect(screen.getByText("100%")).toBeTruthy();
  252. expect(screen.getByRole("button", { name: "下载图片" })).toBeTruthy();
  253. expect(screen.queryByRole("button", { name: "上一张图片" })).toBeNull();
  254. const closeButton = screen.getByRole("button", { name: "关闭" });
  255. const topActions = closeButton.parentElement;
  256. expect(
  257. screen.getByRole("button", { name: "下载图片" }).parentElement,
  258. ).toBe(topActions);
  259. expect(topActions?.className).toContain("pointer-events-auto");
  260. expect(topActions?.className).toContain("[app-region:no-drag]");
  261. expect(topActions?.className).toContain("right-4");
  262. expect(topActions?.className).toContain("top-4");
  263. expect(topActions?.className).toContain(
  264. "platform-windows-desktop:right-6",
  265. );
  266. expect(topActions?.className).toContain(
  267. "platform-windows-desktop:top-[calc(env(titlebar-area-height,48px)_+_0.5rem)]",
  268. );
  269. expect(topActions?.className).toContain("platform-linux-desktop:right-6");
  270. expect(topActions?.className).toContain("platform-linux-desktop:top-4");
  271. expect(topActions?.className).toContain("platform-mac-desktop:top-12");
  272. fireEvent.click(previewImage);
  273. expect(screen.getByTestId("node-repl-image-lightbox")).toBeTruthy();
  274. const previewViewport = previewImage.parentElement as HTMLDivElement;
  275. const setPointerCapture = vi.fn();
  276. const releasePointerCapture = vi.fn();
  277. previewViewport.setPointerCapture = setPointerCapture;
  278. previewViewport.hasPointerCapture = vi.fn(() => true);
  279. previewViewport.releasePointerCapture = releasePointerCapture;
  280. fireEvent.pointerDown(previewViewport, {
  281. clientX: 100,
  282. clientY: 100,
  283. pointerId: 7,
  284. });
  285. fireEvent.pointerUp(previewViewport, {
  286. clientX: 100,
  287. clientY: 100,
  288. pointerId: 7,
  289. });
  290. expect(setPointerCapture).toHaveBeenCalledWith(7);
  291. expect(releasePointerCapture).toHaveBeenCalledWith(7);
  292. fireEvent.keyDown(screen.getByTestId("node-repl-image-lightbox"), {
  293. key: "Escape",
  294. code: "Escape",
  295. });
  296. await waitFor(() =>
  297. expect(screen.queryByTestId("node-repl-image-lightbox")).toBeNull(),
  298. );
  299. expect(document.activeElement).toBe(thumbnail);
  300. fireEvent.click(thumbnail);
  301. fireEvent.click(screen.getByRole("button", { name: "关闭" }));
  302. await waitFor(() =>
  303. expect(screen.queryByTestId("node-repl-image-lightbox")).toBeNull(),
  304. );
  305. expect(document.activeElement).toBe(thumbnail);
  306. },
  307. );
  308. it("groups Browser Use result images and navigates inside the shared preview", () => {
  309. renderImageToolCall(undefined, 2);
  310. const gallery = document.querySelector("[data-node-repl-image-gallery]");
  311. expect(gallery?.className).toContain("grid-cols-1");
  312. expect(gallery?.className).toContain("sm:grid-cols-2");
  313. expect(gallery?.className).toContain("md:flex-wrap");
  314. expect(gallery?.className).toContain(
  315. "md:[&>[data-image-thumbnail-trigger]]:h-44",
  316. );
  317. fireEvent.click(screen.getByRole("button", { name: "打开图片预览 1" }));
  318. expect(
  319. screen.getByTestId("node-repl-image-lightbox-image").getAttribute("src"),
  320. ).toBe("data:image/png;base64,AAAA");
  321. fireEvent.click(screen.getByRole("button", { name: "下一张图片" }));
  322. expect(
  323. screen.getByTestId("node-repl-image-lightbox-image").getAttribute("src"),
  324. ).toBe("data:image/png;base64,BBBB");
  325. fireEvent.keyDown(screen.getByTestId("node-repl-image-lightbox"), {
  326. key: "ArrowLeft",
  327. code: "ArrowLeft",
  328. });
  329. expect(
  330. screen.getByTestId("node-repl-image-lightbox-image").getAttribute("src"),
  331. ).toBe("data:image/png;base64,AAAA");
  332. });
  333. it("falls back to browser-native navigation when a remote image rejects CORS fetch", async () => {
  334. vi.stubGlobal(
  335. "fetch",
  336. vi.fn(async () => Promise.reject(new TypeError("Failed to fetch"))),
  337. );
  338. const anchorClick = vi
  339. .spyOn(HTMLAnchorElement.prototype, "click")
  340. .mockImplementation(() => undefined);
  341. render(
  342. createElement(
  343. ZCodeIntlProvider,
  344. { initialLocale: "zh-CN" },
  345. createElement(ImagePreviewDialog, {
  346. initialIndex: 0,
  347. items: [
  348. {
  349. alt: "remote cat",
  350. src: "https://images.example.test/no-cors-cat.png",
  351. },
  352. ],
  353. onOpenChange: vi.fn(),
  354. open: true,
  355. }),
  356. ),
  357. );
  358. fireEvent.click(screen.getByRole("button", { name: "下载图片" }));
  359. await waitFor(() => expect(anchorClick).toHaveBeenCalledTimes(1));
  360. expect(
  361. document.querySelector(
  362. 'a[href="https://images.example.test/no-cors-cat.png"]',
  363. ),
  364. ).toBeNull();
  365. });
  366. it("navigates from an image to a video in the shared media gallery", () => {
  367. const onActiveIndexChange = vi.fn();
  368. const pause = vi
  369. .spyOn(HTMLMediaElement.prototype, "pause")
  370. .mockImplementation(() => undefined);
  371. render(
  372. createElement(
  373. ZCodeIntlProvider,
  374. { initialLocale: "zh-CN" },
  375. createElement(ImagePreviewDialog, {
  376. initialIndex: 0,
  377. items: [
  378. { alt: "shot.png", mediaType: "image/png", src: "blob:image" },
  379. { alt: "demo.mp4", mediaType: "video/mp4", src: "blob:video" },
  380. ],
  381. onActiveIndexChange,
  382. onOpenChange: vi.fn(),
  383. open: true,
  384. }),
  385. ),
  386. );
  387. expect(screen.getByRole("img", { name: "shot.png" })).not.toBeNull();
  388. expect(screen.getByRole("button", { name: "下载图片" })).not.toBeNull();
  389. fireEvent.click(screen.getByRole("button", { name: "下一张图片" }));
  390. const video = document.querySelector("video");
  391. expect(onActiveIndexChange).toHaveBeenCalledWith(1);
  392. expect(video?.getAttribute("src")).toBe("blob:video");
  393. expect(video?.hasAttribute("controls")).toBe(true);
  394. expect(video?.hasAttribute("playsinline")).toBe(true);
  395. expect(screen.queryByRole("button", { name: "下载图片" })).toBeNull();
  396. expect(screen.queryByRole("button", { name: "放大" })).toBeNull();
  397. fireEvent.keyDown(window, { key: "ArrowLeft" });
  398. expect(onActiveIndexChange).toHaveBeenLastCalledWith(0);
  399. expect(screen.getByRole("img", { name: "shot.png" })).not.toBeNull();
  400. expect(pause).toHaveBeenCalled();
  401. fireEvent.click(screen.getByRole("button", { name: "下一张图片" }));
  402. const reopenedVideo = document.querySelector("video");
  403. fireEvent.error(reopenedVideo!);
  404. expect(screen.getByRole("alert").textContent).toContain(
  405. "当前设备不支持预览",
  406. );
  407. expect(screen.getByRole("button", { name: "上一张图片" })).not.toBeNull();
  408. });
  409. it("does not navigate natively when Content-Length exceeds the Web download limit", async () => {
  410. vi.stubGlobal(
  411. "fetch",
  412. vi.fn(async () => ({
  413. body: new ReadableStream(),
  414. headers: new Headers({
  415. "content-length": String(50 * 1024 * 1024 + 1),
  416. }),
  417. ok: true,
  418. })),
  419. );
  420. const anchorClick = vi
  421. .spyOn(HTMLAnchorElement.prototype, "click")
  422. .mockImplementation(() => undefined);
  423. render(
  424. createElement(
  425. ZCodeIntlProvider,
  426. { initialLocale: "zh-CN" },
  427. createElement(ImagePreviewDialog, {
  428. initialIndex: 0,
  429. items: [
  430. {
  431. alt: "large remote image",
  432. src: "https://images.example.test/large.png",
  433. },
  434. ],
  435. onOpenChange: vi.fn(),
  436. open: true,
  437. }),
  438. ),
  439. );
  440. fireEvent.click(screen.getByRole("button", { name: "下载图片" }));
  441. await waitFor(() =>
  442. expect(
  443. (screen.getByRole("button", { name: "下载图片" }) as HTMLButtonElement)
  444. .disabled,
  445. ).toBe(false),
  446. );
  447. expect(anchorClick).not.toHaveBeenCalled();
  448. });
  449. });