nodeReplToolCallBlock.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. import type { IBroadcastService } from "@zcode/services";
  2. import { createElement, type ReactElement } from "react";
  3. import { renderToStaticMarkup } from "react-dom/server";
  4. import { describe, expect, it } from "vitest";
  5. import { ZCodeIntlProvider } from "@/i18n/IntlProvider.js";
  6. import { buildNodeReplDisplayModel } from "@/lib/nodeReplToolDisplay.js";
  7. import { StoreProvider } from "@/store/StoreProvider.js";
  8. import { ToolCallBlock } from "@/ToolCallBlocks.js";
  9. import { NodeReplToolCallBlock } from "@/ToolCallBlocks/renderers/node-repl.js";
  10. import { TooltipProvider } from "@/components/ui/tooltip.js";
  11. const localStorageState = new Map<string, string>();
  12. Object.defineProperty(globalThis, "localStorage", {
  13. configurable: true,
  14. value: {
  15. clear: () => localStorageState.clear(),
  16. getItem: (key: string) => localStorageState.get(key) ?? null,
  17. removeItem: (key: string) => localStorageState.delete(key),
  18. setItem: (key: string, value: string) => localStorageState.set(key, value),
  19. },
  20. });
  21. Object.defineProperty(globalThis, "document", {
  22. configurable: true,
  23. value: {
  24. documentElement: {
  25. classList: {
  26. contains: () => false,
  27. toggle: () => {},
  28. },
  29. },
  30. },
  31. });
  32. const mockBroadcastService: IBroadcastService = {
  33. send: async () => {},
  34. onMessage: () => ({ dispose: () => {} }),
  35. };
  36. const displayModel = {
  37. inlinePreview: { type: "none" as const },
  38. planResult: null,
  39. viewerSource: null,
  40. viewerLabelId: "codeViewer.viewCode" as const,
  41. showSummaryFileLink: false,
  42. showInput: false,
  43. showOutput: false,
  44. showKind: false,
  45. };
  46. function renderWithProviders(element: ReactElement) {
  47. return renderToStaticMarkup(
  48. createElement(
  49. ZCodeIntlProvider,
  50. { initialLocale: "zh-CN" },
  51. createElement(
  52. StoreProvider,
  53. { broadcastService: mockBroadcastService },
  54. createElement(TooltipProvider, null, element),
  55. ),
  56. ),
  57. );
  58. }
  59. describe("node repl tool display", () => {
  60. it("normalizes user title, code and projected text output", () => {
  61. expect(
  62. buildNodeReplDisplayModel({
  63. toolId: "tool-node-repl-model",
  64. toolName: "js",
  65. kind: "js",
  66. title: "js",
  67. input: {
  68. code: "globalThis.browser = await agent.browsers.getDefault();",
  69. title: "选择浏览器并读取操作说明",
  70. },
  71. output: {
  72. type: "text",
  73. value: "# Selected Browser\n- Name: ZCode In-app Browser",
  74. },
  75. status: "completed",
  76. }),
  77. ).toMatchObject({
  78. operation: "run",
  79. userTitle: "选择浏览器并读取操作说明",
  80. code: "globalThis.browser = await agent.browsers.getDefault();",
  81. resultText: "# Selected Browser\n- Name: ZCode In-app Browser",
  82. });
  83. });
  84. it("removes leading blank code lines without changing the first line indentation", () => {
  85. const model = buildNodeReplDisplayModel({
  86. toolId: "tool-node-repl-leading-code-lines",
  87. toolName: "js",
  88. kind: "js",
  89. title: "检查页面",
  90. input: { code: "\n \t\r\n const title = await tab.title();\n return title;\n" },
  91. output: { type: "text", value: "Example" },
  92. status: "completed",
  93. });
  94. expect(model.code).toBe(" const title = await tab.title();\n return title;\n");
  95. });
  96. it("extracts text and image blocks from the real MCP CallToolResult shape", () => {
  97. const model = buildNodeReplDisplayModel({
  98. toolId: "tool-node-repl-mcp-content",
  99. toolName: "mcp__node_repl__js",
  100. kind: "mcp__node_repl__js",
  101. title: "检查页面截图",
  102. input: { code: "await nodeRepl.emitImage(await tab.screenshot());" },
  103. output: {
  104. content: [
  105. { type: "text", text: "=> ready" },
  106. { type: "image", data: "AAAA", mimeType: "image/png" },
  107. ],
  108. },
  109. status: "completed",
  110. });
  111. expect(model.resultText).toBe("ready");
  112. expect(model.images).toEqual([{ base64: "AAAA", mimeType: "image/png" }]);
  113. });
  114. it("keeps snapshot display images without the model-facing attachment placeholder", () => {
  115. const toolCall = {
  116. toolId: "tool-node-repl-display-image",
  117. toolName: "mcp__node_repl__js",
  118. kind: "mcp__node_repl__js",
  119. title: "截图查看",
  120. input: { code: "nodeRepl.emitImage(await tab.screenshot());" },
  121. output: "(no output)\n[Attached image/png: MCP image]",
  122. raw: {
  123. schemaVersion: 1,
  124. display: {
  125. kind: "node_repl_images",
  126. images: [{ base64: "AAAA", mimeType: "image/png" }],
  127. },
  128. },
  129. status: "completed",
  130. } as const;
  131. const model = buildNodeReplDisplayModel(toolCall);
  132. const html = renderWithProviders(
  133. createElement(NodeReplToolCallBlock, {
  134. toolCallNode: { toolCall, childToolCalls: [] },
  135. workspacePath: "/workspace",
  136. displayModel,
  137. viewerSource: null,
  138. rawFileSummaries: [],
  139. isRunning: false,
  140. statusLabel: "已执行",
  141. childToolList: null,
  142. forceOpen: true,
  143. canToggle: true,
  144. showIcon: true,
  145. }),
  146. );
  147. expect(model.resultText).toBeUndefined();
  148. expect(model.images).toEqual([{ base64: "AAAA", mimeType: "image/png" }]);
  149. expect(html).toContain('src="data:image/png;base64,AAAA"');
  150. expect(html).toContain("w-fit max-w-1/2 cursor-zoom-in overflow-hidden rounded-xl");
  151. expect(html).toContain("h-auto max-h-90 max-w-full rounded-xl border border-border");
  152. expect(html).not.toContain("Attached image");
  153. });
  154. it("投影 CUA App 身份,并把工具卡 leading icon 换成该 App 的图标", () => {
  155. const toolCall = {
  156. toolId: "tool-node-repl-cua-app",
  157. toolName: "mcp__node_repl__js",
  158. kind: "mcp__node_repl__js",
  159. title: "在备忘录里新建一条笔记",
  160. input: { code: "await app.elements(); await el.click();", title: "在备忘录里新建一条笔记" },
  161. output: "clicked",
  162. raw: {
  163. schemaVersion: 1,
  164. display: {
  165. kind: "node_repl_images",
  166. app: { appKey: "darwin:com.apple.notes", displayName: "Notes" },
  167. },
  168. },
  169. status: "completed",
  170. } as const;
  171. const model = buildNodeReplDisplayModel(toolCall);
  172. expect(model.app).toEqual({ appKey: "darwin:com.apple.notes", displayName: "Notes" });
  173. const html = renderWithProviders(
  174. createElement(NodeReplToolCallBlock, {
  175. toolCallNode: { toolCall, childToolCalls: [] },
  176. workspacePath: "/workspace",
  177. displayModel,
  178. viewerSource: null,
  179. rawFileSummaries: [],
  180. isRunning: false,
  181. statusLabel: "已执行",
  182. childToolList: null,
  183. forceOpen: false,
  184. canToggle: true,
  185. showIcon: true,
  186. }),
  187. );
  188. // 注意:SSR 不跑 effect,图标解析拿不到 data URL,因此下面两条只能证明「没退化成 CUA 的
  189. // 指针图标」,**不能**证明 App 图标链路接上了 —— 那部分由 nodeReplCuaAppIcon.test.ts 在
  190. // jsdom 下用真实 platform mock 覆盖(含去掉接线即变红的阴性对照)。
  191. expect(html).toContain("lucide-square-mouse-pointer");
  192. expect(html).not.toContain("lucide-mouse-pointer-click");
  193. // 摘要行仍只显示模型给的 title,不额外拼 App 名(否则和 title 重复)。
  194. expect(html).toContain("在备忘录里新建一条笔记");
  195. expect(html).not.toContain("Notes");
  196. });
  197. it("没有 App 身份时保持原有的 node_repl 图标路径", () => {
  198. const model = buildNodeReplDisplayModel({
  199. toolId: "tool-node-repl-no-app",
  200. toolName: "mcp__node_repl__js",
  201. kind: "mcp__node_repl__js",
  202. title: "算一下",
  203. input: { code: "1 + 1" },
  204. output: "=> 2",
  205. status: "completed",
  206. });
  207. expect(model.app).toBeUndefined();
  208. });
  209. it("renders a browser turn-end screenshot as a standalone image", () => {
  210. const toolCall = {
  211. toolId: "tool-browser-turn-screenshot",
  212. toolName: "mcp__node_repl__js",
  213. kind: "mcp__node_repl__js",
  214. input: { source: "browser_turn_end" },
  215. output: "",
  216. raw: {
  217. schemaVersion: 1,
  218. display: {
  219. kind: "node_repl_images",
  220. source: "browser_turn_end",
  221. images: [{ base64: "AAAA", mimeType: "image/png" }],
  222. },
  223. },
  224. status: "completed",
  225. } as const;
  226. const model = buildNodeReplDisplayModel(toolCall);
  227. const html = renderWithProviders(
  228. createElement(NodeReplToolCallBlock, {
  229. toolCallNode: { toolCall, childToolCalls: [] },
  230. workspacePath: "/workspace",
  231. displayModel,
  232. viewerSource: null,
  233. rawFileSummaries: [],
  234. isRunning: false,
  235. statusLabel: "已执行",
  236. childToolList: null,
  237. showIcon: true,
  238. }),
  239. );
  240. expect(model.displaySource).toBe("browser_turn_end");
  241. expect(html).toContain('src="data:image/png;base64,AAAA"');
  242. expect(html).toContain("w-fit max-w-1/2 cursor-zoom-in overflow-hidden rounded-xl");
  243. expect(html).toContain("h-auto max-h-90 max-w-full rounded-xl");
  244. expect(html).not.toContain("查看执行详情");
  245. expect(html).not.toContain("执行 JavaScript");
  246. });
  247. it("removes internal completion markers from projected results", () => {
  248. const createModel = (value: string) =>
  249. buildNodeReplDisplayModel({
  250. toolId: "tool-node-repl-completion-marker",
  251. toolName: "js",
  252. kind: "js",
  253. title: "打开目标页面",
  254. input: { code: "await tab.goto('https://example.com');" },
  255. output: { type: "text", value },
  256. status: "completed",
  257. });
  258. expect(createModel("=> 已打开目标页面").resultText).toBe("已打开目标页面");
  259. expect(createModel("页面加载完成\n=> 已打开目标页面").resultText).toBe(
  260. "页面加载完成\n已打开目标页面",
  261. );
  262. });
  263. it("removes the persisted-output envelope while preserving the full result reference", () => {
  264. const model = buildNodeReplDisplayModel({
  265. toolId: "tool-node-repl-artifact",
  266. toolName: "js",
  267. kind: "js",
  268. title: "js",
  269. input: { code: "nodeRepl.write(largeResult);" },
  270. output: {
  271. type: "text",
  272. value:
  273. "<persisted-output>\nOutput too large (31 KB). Full output saved to: /tmp/full-result.json\n\nPreview (first 2 KB):\npreview text\n</persisted-output>",
  274. },
  275. status: "completed",
  276. });
  277. expect(model.resultText).toBe("preview text");
  278. expect(model.persistedResult).toEqual({
  279. artifactPath: "/tmp/full-result.json",
  280. sizeLabel: "31 KB",
  281. });
  282. });
  283. it("rejects implementation-only titles and extracts structured failures", () => {
  284. const model = buildNodeReplDisplayModel({
  285. toolId: "tool-node-repl-error",
  286. toolName: "js",
  287. kind: "js",
  288. title: "js",
  289. input: {
  290. code: "throw new Error('boom');",
  291. title: "Run JavaScript",
  292. },
  293. output: {
  294. logs: "",
  295. error: {
  296. name: "Error",
  297. message: "boom",
  298. stack: "Error: boom\n at cell:1:1",
  299. },
  300. },
  301. status: "failed",
  302. });
  303. expect(model.userTitle).toBeUndefined();
  304. expect(model.error).toEqual({
  305. summary: "Error: boom",
  306. stack: "Error: boom\n at cell:1:1",
  307. });
  308. });
  309. it("routes runs to a user-friendly result-first renderer without raw payloads", () => {
  310. const toolCall = {
  311. toolId: "tool-node-repl-render",
  312. toolName: "js",
  313. kind: "js",
  314. title: "js",
  315. input: {
  316. code: "globalThis.browser = await agent.browsers.getDefault();",
  317. title: "选择浏览器并读取操作说明",
  318. },
  319. output: {
  320. type: "text",
  321. value: "已选择应用内浏览器,并读取操作说明。",
  322. },
  323. status: "completed" as const,
  324. raw: {
  325. toolId: "raw-tool-id-should-not-render",
  326. toolName: "js",
  327. rawInput: { secretDebugField: "hidden" },
  328. },
  329. };
  330. const html = renderWithProviders(
  331. createElement(NodeReplToolCallBlock, {
  332. toolCallNode: { toolCall, childToolCalls: [] },
  333. workspacePath: "/workspace",
  334. displayModel,
  335. viewerSource: null,
  336. rawFileSummaries: [],
  337. isRunning: false,
  338. statusLabel: "已执行",
  339. childToolList: null,
  340. forceOpen: true,
  341. canToggle: true,
  342. showIcon: true,
  343. }),
  344. );
  345. expect(html).toContain("选择浏览器并读取操作说明");
  346. expect(html).toContain("已完成");
  347. expect(html).not.toContain("操作已完成");
  348. expect(html).toContain("已选择应用内浏览器,并读取操作说明。");
  349. expect(html).not.toContain(">结果</span>");
  350. expect(html).not.toContain('aria-label="复制结果"');
  351. expect(html).toContain("查看执行细节");
  352. expect(html).toContain("text-foreground-subtlest");
  353. expect(html).toContain("hover:bg-transparent");
  354. expect(html).toContain("hover:text-foreground");
  355. expect(html).toContain(
  356. "rounded-xl border border-border bg-card px-3 py-2 text-ui-base text-foreground-subtle",
  357. );
  358. expect(html).toContain("lucide-square-mouse-pointer");
  359. expect(html).not.toContain("font-medium whitespace-nowrap shrink-0");
  360. expect(html).not.toContain("Parameters");
  361. expect(html).not.toContain("raw-tool-id-should-not-render");
  362. expect(html).not.toContain("secretDebugField");
  363. });
  364. it("recovers the user title from serialized input when the projected input only has code", () => {
  365. const model = buildNodeReplDisplayModel({
  366. toolId: "tool-node-repl-serialized-title",
  367. toolName: "js",
  368. kind: "js",
  369. title: "js",
  370. input: { code: "return await tab.title();" },
  371. output: { type: "text", value: "Example" },
  372. status: "completed",
  373. raw: {
  374. rawInput: JSON.stringify({
  375. code: "return await tab.title();",
  376. title: "读取当前页面标题",
  377. }),
  378. },
  379. });
  380. expect(model.userTitle).toBe("读取当前页面标题");
  381. });
  382. it("uses friendly summaries for reset and working-directory configuration", () => {
  383. const resetHtml = renderWithProviders(
  384. createElement(ToolCallBlock, {
  385. toolCallNode: {
  386. toolCall: {
  387. toolId: "tool-node-repl-reset",
  388. toolName: "js_reset",
  389. kind: "js_reset",
  390. title: "js_reset",
  391. input: {},
  392. output: { ok: true },
  393. status: "completed",
  394. },
  395. childToolCalls: [],
  396. },
  397. workspacePath: "/workspace",
  398. }),
  399. );
  400. const configureHtml = renderWithProviders(
  401. createElement(ToolCallBlock, {
  402. toolCallNode: {
  403. toolCall: {
  404. toolId: "tool-node-repl-configure",
  405. toolName: "js_add_node_module_dir",
  406. kind: "js_add_node_module_dir",
  407. title: "js_add_node_module_dir",
  408. input: { dir: "/workspace/node_modules" },
  409. output: { ok: true, dirs: ["/workspace/node_modules"] },
  410. status: "completed",
  411. },
  412. childToolCalls: [],
  413. },
  414. workspacePath: "/workspace",
  415. }),
  416. );
  417. expect(resetHtml).toContain("已重置操作环境");
  418. expect(resetHtml).not.toContain("&quot;ok&quot;");
  419. expect(configureHtml).toContain("已配置运行目录");
  420. expect(configureHtml).toContain("/workspace/node_modules");
  421. expect(configureHtml).not.toContain("&quot;dirs&quot;");
  422. });
  423. it("recognizes the Codex-compatible MCP node_repl tool names", () => {
  424. const resetHtml = renderWithProviders(
  425. createElement(ToolCallBlock, {
  426. toolCallNode: {
  427. toolCall: {
  428. toolId: "tool-node-repl-mcp-reset",
  429. toolName: "mcp__node_repl__js_reset",
  430. kind: "mcp__node_repl__js_reset",
  431. title: "mcp__node_repl__js_reset",
  432. input: {},
  433. output: { ok: true },
  434. status: "completed",
  435. },
  436. childToolCalls: [],
  437. },
  438. workspacePath: "/workspace",
  439. }),
  440. );
  441. const configureHtml = renderWithProviders(
  442. createElement(ToolCallBlock, {
  443. toolCallNode: {
  444. toolCall: {
  445. toolId: "tool-node-repl-mcp-configure",
  446. toolName: "mcp__node_repl__js_add_node_module_dir",
  447. kind: "mcp__node_repl__js_add_node_module_dir",
  448. title: "mcp__node_repl__js_add_node_module_dir",
  449. input: { path: "/workspace/node_modules" },
  450. output: { ok: true },
  451. status: "completed",
  452. },
  453. childToolCalls: [],
  454. },
  455. workspacePath: "/workspace",
  456. }),
  457. );
  458. expect(resetHtml).toContain("已重置操作环境");
  459. expect(configureHtml).toContain("已配置运行目录");
  460. expect(configureHtml).toContain("/workspace/node_modules");
  461. });
  462. it("keeps the Node REPL renderer when MCP presentation metadata is present", () => {
  463. const html = renderWithProviders(
  464. createElement(ToolCallBlock, {
  465. toolCallNode: {
  466. toolCall: {
  467. toolId: "tool-node-repl-mcp-presentation",
  468. toolName: "mcp__node_repl__js",
  469. kind: "mcp__node_repl__js",
  470. input: {
  471. code: "return await tab.title();",
  472. title: "读取当前页面标题",
  473. },
  474. output: {
  475. content: [{ type: "text", text: "=> Example" }],
  476. },
  477. raw: {
  478. display: {
  479. kind: "mcp_tool",
  480. serverName: "node_repl",
  481. toolName: "js",
  482. description: "Run JavaScript in the persistent Node kernel.",
  483. },
  484. },
  485. status: "completed",
  486. },
  487. childToolCalls: [],
  488. },
  489. workspacePath: "/workspace",
  490. }),
  491. );
  492. expect(html).toContain("读取当前页面标题");
  493. expect(html).toContain("lucide-square-mouse-pointer");
  494. expect(html).not.toContain(">Node repl<");
  495. });
  496. });