nodeReplToolCallBlock.test.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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).not.toContain("Attached image");
  151. });
  152. it("投影 CUA App 身份,摘要保留模型标题且不重复 App 名", () => {
  153. const toolCall = {
  154. toolId: "tool-node-repl-cua-app",
  155. toolName: "mcp__node_repl__js",
  156. kind: "mcp__node_repl__js",
  157. title: "在备忘录里新建一条笔记",
  158. input: { code: "await app.elements(); await el.click();", title: "在备忘录里新建一条笔记" },
  159. output: "clicked",
  160. raw: {
  161. schemaVersion: 1,
  162. display: {
  163. kind: "node_repl_images",
  164. app: { appKey: "darwin:com.apple.notes", displayName: "Notes" },
  165. },
  166. },
  167. status: "completed",
  168. } as const;
  169. const model = buildNodeReplDisplayModel(toolCall);
  170. expect(model.app).toEqual({ appKey: "darwin:com.apple.notes", displayName: "Notes" });
  171. const html = renderWithProviders(
  172. createElement(NodeReplToolCallBlock, {
  173. toolCallNode: { toolCall, childToolCalls: [] },
  174. workspacePath: "/workspace",
  175. displayModel,
  176. viewerSource: null,
  177. rawFileSummaries: [],
  178. isRunning: false,
  179. statusLabel: "已执行",
  180. childToolList: null,
  181. forceOpen: false,
  182. canToggle: true,
  183. showIcon: true,
  184. }),
  185. );
  186. // 摘要行仍只显示模型给的 title,不额外拼 App 名(否则和 title 重复)。
  187. expect(html).toContain("在备忘录里新建一条笔记");
  188. expect(html).not.toContain("Notes");
  189. });
  190. it("没有 App 身份时保持原有的 node_repl 图标路径", () => {
  191. const model = buildNodeReplDisplayModel({
  192. toolId: "tool-node-repl-no-app",
  193. toolName: "mcp__node_repl__js",
  194. kind: "mcp__node_repl__js",
  195. title: "算一下",
  196. input: { code: "1 + 1" },
  197. output: "=> 2",
  198. status: "completed",
  199. });
  200. expect(model.app).toBeUndefined();
  201. });
  202. it("renders a browser turn-end screenshot as a standalone image", () => {
  203. const toolCall = {
  204. toolId: "tool-browser-turn-screenshot",
  205. toolName: "mcp__node_repl__js",
  206. kind: "mcp__node_repl__js",
  207. input: { source: "browser_turn_end" },
  208. output: "",
  209. raw: {
  210. schemaVersion: 1,
  211. display: {
  212. kind: "node_repl_images",
  213. source: "browser_turn_end",
  214. images: [{ base64: "AAAA", mimeType: "image/png" }],
  215. },
  216. },
  217. status: "completed",
  218. } as const;
  219. const model = buildNodeReplDisplayModel(toolCall);
  220. const html = renderWithProviders(
  221. createElement(NodeReplToolCallBlock, {
  222. toolCallNode: { toolCall, childToolCalls: [] },
  223. workspacePath: "/workspace",
  224. displayModel,
  225. viewerSource: null,
  226. rawFileSummaries: [],
  227. isRunning: false,
  228. statusLabel: "已执行",
  229. childToolList: null,
  230. showIcon: true,
  231. }),
  232. );
  233. expect(model.displaySource).toBe("browser_turn_end");
  234. expect(html).toContain('src="data:image/png;base64,AAAA"');
  235. expect(html).not.toContain("查看执行详情");
  236. expect(html).not.toContain("执行 JavaScript");
  237. });
  238. it("removes internal completion markers from projected results", () => {
  239. const createModel = (value: string) =>
  240. buildNodeReplDisplayModel({
  241. toolId: "tool-node-repl-completion-marker",
  242. toolName: "js",
  243. kind: "js",
  244. title: "打开目标页面",
  245. input: { code: "await tab.goto('https://example.com');" },
  246. output: { type: "text", value },
  247. status: "completed",
  248. });
  249. expect(createModel("=> 已打开目标页面").resultText).toBe("已打开目标页面");
  250. expect(createModel("页面加载完成\n=> 已打开目标页面").resultText).toBe(
  251. "页面加载完成\n已打开目标页面",
  252. );
  253. });
  254. it("removes the persisted-output envelope while preserving the full result reference", () => {
  255. const model = buildNodeReplDisplayModel({
  256. toolId: "tool-node-repl-artifact",
  257. toolName: "js",
  258. kind: "js",
  259. title: "js",
  260. input: { code: "nodeRepl.write(largeResult);" },
  261. output: {
  262. type: "text",
  263. value:
  264. "<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>",
  265. },
  266. status: "completed",
  267. });
  268. expect(model.resultText).toBe("preview text");
  269. expect(model.persistedResult).toEqual({
  270. artifactPath: "/tmp/full-result.json",
  271. sizeLabel: "31 KB",
  272. });
  273. });
  274. it("rejects implementation-only titles and extracts structured failures", () => {
  275. const model = buildNodeReplDisplayModel({
  276. toolId: "tool-node-repl-error",
  277. toolName: "js",
  278. kind: "js",
  279. title: "js",
  280. input: {
  281. code: "throw new Error('boom');",
  282. title: "Run JavaScript",
  283. },
  284. output: {
  285. logs: "",
  286. error: {
  287. name: "Error",
  288. message: "boom",
  289. stack: "Error: boom\n at cell:1:1",
  290. },
  291. },
  292. status: "failed",
  293. });
  294. expect(model.userTitle).toBeUndefined();
  295. expect(model.error).toEqual({
  296. summary: "Error: boom",
  297. stack: "Error: boom\n at cell:1:1",
  298. });
  299. });
  300. it("routes runs to a user-friendly result-first renderer without raw payloads", () => {
  301. const toolCall = {
  302. toolId: "tool-node-repl-render",
  303. toolName: "js",
  304. kind: "js",
  305. title: "js",
  306. input: {
  307. code: "globalThis.browser = await agent.browsers.getDefault();",
  308. title: "选择浏览器并读取操作说明",
  309. },
  310. output: {
  311. type: "text",
  312. value: "已选择应用内浏览器,并读取操作说明。",
  313. },
  314. status: "completed" as const,
  315. raw: {
  316. toolId: "raw-tool-id-should-not-render",
  317. toolName: "js",
  318. rawInput: { secretDebugField: "hidden" },
  319. },
  320. };
  321. const html = renderWithProviders(
  322. createElement(NodeReplToolCallBlock, {
  323. toolCallNode: { toolCall, childToolCalls: [] },
  324. workspacePath: "/workspace",
  325. displayModel,
  326. viewerSource: null,
  327. rawFileSummaries: [],
  328. isRunning: false,
  329. statusLabel: "已执行",
  330. childToolList: null,
  331. forceOpen: true,
  332. canToggle: true,
  333. showIcon: true,
  334. }),
  335. );
  336. expect(html).toContain("选择浏览器并读取操作说明");
  337. expect(html).toContain("已完成");
  338. expect(html).toContain("已选择应用内浏览器,并读取操作说明。");
  339. expect(html).not.toContain(">结果</span>");
  340. expect(html).not.toContain('aria-label="复制结果"');
  341. expect(html).toContain("查看执行细节");
  342. expect(html).not.toContain("Parameters");
  343. expect(html).not.toContain("raw-tool-id-should-not-render");
  344. expect(html).not.toContain("secretDebugField");
  345. });
  346. it("recovers the user title from serialized input when the projected input only has code", () => {
  347. const model = buildNodeReplDisplayModel({
  348. toolId: "tool-node-repl-serialized-title",
  349. toolName: "js",
  350. kind: "js",
  351. title: "js",
  352. input: { code: "return await tab.title();" },
  353. output: { type: "text", value: "Example" },
  354. status: "completed",
  355. raw: {
  356. rawInput: JSON.stringify({
  357. code: "return await tab.title();",
  358. title: "读取当前页面标题",
  359. }),
  360. },
  361. });
  362. expect(model.userTitle).toBe("读取当前页面标题");
  363. });
  364. it("uses friendly summaries for reset and working-directory configuration", () => {
  365. const resetHtml = renderWithProviders(
  366. createElement(ToolCallBlock, {
  367. toolCallNode: {
  368. toolCall: {
  369. toolId: "tool-node-repl-reset",
  370. toolName: "js_reset",
  371. kind: "js_reset",
  372. title: "js_reset",
  373. input: {},
  374. output: { ok: true },
  375. status: "completed",
  376. },
  377. childToolCalls: [],
  378. },
  379. workspacePath: "/workspace",
  380. }),
  381. );
  382. const configureHtml = renderWithProviders(
  383. createElement(ToolCallBlock, {
  384. toolCallNode: {
  385. toolCall: {
  386. toolId: "tool-node-repl-configure",
  387. toolName: "js_add_node_module_dir",
  388. kind: "js_add_node_module_dir",
  389. title: "js_add_node_module_dir",
  390. input: { dir: "/workspace/node_modules" },
  391. output: { ok: true, dirs: ["/workspace/node_modules"] },
  392. status: "completed",
  393. },
  394. childToolCalls: [],
  395. },
  396. workspacePath: "/workspace",
  397. }),
  398. );
  399. expect(resetHtml).toContain("已重置操作环境");
  400. expect(resetHtml).not.toContain("&quot;ok&quot;");
  401. expect(configureHtml).toContain("已配置运行目录");
  402. expect(configureHtml).toContain("/workspace/node_modules");
  403. expect(configureHtml).not.toContain("&quot;dirs&quot;");
  404. });
  405. it("recognizes the Codex-compatible MCP node_repl tool names", () => {
  406. const resetHtml = renderWithProviders(
  407. createElement(ToolCallBlock, {
  408. toolCallNode: {
  409. toolCall: {
  410. toolId: "tool-node-repl-mcp-reset",
  411. toolName: "mcp__node_repl__js_reset",
  412. kind: "mcp__node_repl__js_reset",
  413. title: "mcp__node_repl__js_reset",
  414. input: {},
  415. output: { ok: true },
  416. status: "completed",
  417. },
  418. childToolCalls: [],
  419. },
  420. workspacePath: "/workspace",
  421. }),
  422. );
  423. const configureHtml = renderWithProviders(
  424. createElement(ToolCallBlock, {
  425. toolCallNode: {
  426. toolCall: {
  427. toolId: "tool-node-repl-mcp-configure",
  428. toolName: "mcp__node_repl__js_add_node_module_dir",
  429. kind: "mcp__node_repl__js_add_node_module_dir",
  430. title: "mcp__node_repl__js_add_node_module_dir",
  431. input: { path: "/workspace/node_modules" },
  432. output: { ok: true },
  433. status: "completed",
  434. },
  435. childToolCalls: [],
  436. },
  437. workspacePath: "/workspace",
  438. }),
  439. );
  440. expect(resetHtml).toContain("已重置操作环境");
  441. expect(configureHtml).toContain("已配置运行目录");
  442. expect(configureHtml).toContain("/workspace/node_modules");
  443. });
  444. it("keeps the Node REPL renderer when MCP presentation metadata is present", () => {
  445. const html = renderWithProviders(
  446. createElement(ToolCallBlock, {
  447. toolCallNode: {
  448. toolCall: {
  449. toolId: "tool-node-repl-mcp-presentation",
  450. toolName: "mcp__node_repl__js",
  451. kind: "mcp__node_repl__js",
  452. input: {
  453. code: "return await tab.title();",
  454. title: "读取当前页面标题",
  455. },
  456. output: {
  457. content: [{ type: "text", text: "=> Example" }],
  458. },
  459. raw: {
  460. display: {
  461. kind: "mcp_tool",
  462. serverName: "node_repl",
  463. toolName: "js",
  464. description: "Run JavaScript in the persistent Node kernel.",
  465. },
  466. },
  467. status: "completed",
  468. },
  469. childToolCalls: [],
  470. },
  471. workspacePath: "/workspace",
  472. }),
  473. );
  474. expect(html).toContain("读取当前页面标题");
  475. expect(html).toContain("lucide-square-mouse-pointer");
  476. expect(html).not.toContain(">Node repl<");
  477. });
  478. });