mcp-server.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. import { existsSync, readFileSync } from "node:fs";
  2. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
  4. import { tmpdir } from "node:os";
  5. import { join, resolve } from "node:path";
  6. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  7. import {
  8. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  9. ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY,
  10. } from "@zcode/contracts";
  11. import { CUA_APP_ASSOCIATIONS_META_KEY } from "@zcode/zcode-cua/host-display-contract";
  12. import {
  13. captureComputerUseRuntimeFromEnvironment,
  14. createInProcessNodeReplExecutor,
  15. createNodeReplMcpRuntime,
  16. main,
  17. type NodeReplMcpRuntime,
  18. } from "../src/server.js";
  19. import { toMcpRunResult } from "../src/result.js";
  20. import {
  21. NODE_REPL_DEFAULT_TIMEOUT_MS,
  22. NODE_REPL_SERVER_INSTRUCTIONS,
  23. JS_TOOL_DESCRIPTION,
  24. } from "../src/tool-contract.js";
  25. describe("node_repl MCP server", () => {
  26. const packageVersion = (
  27. JSON.parse(readFileSync(resolve(import.meta.dirname, "../package.json"), "utf8")) as {
  28. version: string;
  29. }
  30. ).version;
  31. let client: Client;
  32. let runtime: NodeReplMcpRuntime;
  33. const requestMeta = (
  34. sessionId: string,
  35. runtimeScope: "main" | "subagent" = "main",
  36. turnId = "turn-1",
  37. ) => ({
  38. "com.zcode/request-context": {
  39. runtime_scope: runtimeScope,
  40. session_id: sessionId,
  41. turn_id: turnId,
  42. },
  43. });
  44. beforeEach(async () => {
  45. runtime = createNodeReplMcpRuntime({ executeJs: createInProcessNodeReplExecutor() });
  46. client = new Client({ name: "node-repl-test", version: "0.1.0" });
  47. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  48. await runtime.server.connect(serverTransport);
  49. await client.connect(clientTransport);
  50. });
  51. afterEach(async () => {
  52. await client.close();
  53. runtime.dispose();
  54. });
  55. it("exports the main entrypoint required by the packaged plugin host", () => {
  56. expect(main).toBeTypeOf("function");
  57. expect(client.getServerVersion()).toEqual({
  58. name: "node_repl",
  59. version: packageVersion,
  60. });
  61. });
  62. it("captures Computer Use credentials before the plugin host restores its environment", async () => {
  63. const capturedRuntime = captureComputerUseRuntimeFromEnvironment({
  64. ZCODE_CUA_PERMISSION_BROKER_SOCKET: "/tmp/deferred-cua.sock",
  65. ZCODE_CUA_PERMISSION_BROKER_TOKEN: "deferred-cua-token",
  66. });
  67. expect(capturedRuntime).toBeDefined();
  68. let forwardedBroker: unknown;
  69. const deferredRuntime = createNodeReplMcpRuntime({
  70. cuaRuntime: capturedRuntime,
  71. executeJs: async (input) => {
  72. forwardedBroker = input.cuaBroker;
  73. return { logs: "", result: "ok" };
  74. },
  75. });
  76. const deferredClient = new Client({ name: "deferred-cua-test", version: "0.1.0" });
  77. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  78. await deferredRuntime.server.connect(serverTransport);
  79. await deferredClient.connect(clientTransport);
  80. try {
  81. await deferredClient.callTool({
  82. name: "js",
  83. arguments: { code: "1", title: "验证 Computer Use bridge" },
  84. _meta: requestMeta("deferred-cua-session"),
  85. });
  86. expect(forwardedBroker).toMatchObject({
  87. socketPath: expect.any(String),
  88. token: expect.any(String),
  89. });
  90. } finally {
  91. await deferredClient.close();
  92. deferredRuntime.dispose();
  93. }
  94. });
  95. it("requires user-facing titles in the model schema while preserving legacy runtime input", async () => {
  96. const { tools } = await client.listTools();
  97. expect(tools.map((tool) => tool.name).sort()).toEqual(["js"]);
  98. const js = tools.find((tool) => tool.name === "js");
  99. expect(js?.inputSchema).toMatchObject({
  100. additionalProperties: false,
  101. required: ["code", "title"],
  102. type: "object",
  103. });
  104. expect(Object.keys(js?.inputSchema.properties ?? {}).sort()).toEqual([
  105. "code",
  106. "timeout_ms",
  107. "title",
  108. ]);
  109. expect(js?.inputSchema.properties?.code).toMatchObject({
  110. description: "JavaScript code to execute in the Node REPL session",
  111. });
  112. expect(js?.inputSchema.properties?.timeout_ms).toMatchObject({
  113. description: expect.stringContaining(
  114. "You MUST provide this when the code is expected to run longer than 30000 ms",
  115. ),
  116. });
  117. expect(js?.description).toContain("required `title`");
  118. expect(NODE_REPL_DEFAULT_TIMEOUT_MS).toBe(60_000);
  119. expect(NODE_REPL_SERVER_INSTRUCTIONS).toContain("default to a 60000 ms timeout");
  120. expect(js?.description).toContain("after 60000 ms");
  121. expect(js?.description).toContain(
  122. "you MUST set `timeout_ms` to at least the estimated total runtime plus 15000 ms",
  123. );
  124. expect(js?.description).not.toContain("after 30000 ms");
  125. const legacyCall = await client.callTool({
  126. name: "js",
  127. arguments: { code: '"legacy";' },
  128. });
  129. expect(legacyCall.isError).not.toBe(true);
  130. expect(legacyCall.content).toContainEqual(
  131. expect.objectContaining({ type: "text", text: "=> legacy" }),
  132. );
  133. });
  134. it("limits every model-visible node_repl description to official browser/computer use", async () => {
  135. const { tools } = await client.listTools();
  136. const js = tools.find((tool) => tool.name === "js");
  137. expect(NODE_REPL_SERVER_INSTRUCTIONS).toMatch(/^Browser Use and Computer Use only\./);
  138. expect(NODE_REPL_SERVER_INSTRUCTIONS).toContain("Do not use this server for unrelated tasks");
  139. expect(js?.description).toMatch(/^Browser Use and Computer Use only\./);
  140. expect(js?.description).toContain("Do not use it as a general-purpose JavaScript runtime");
  141. });
  142. it("teaches the generic node_repl tool to keep CUA results structured", () => {
  143. expect(JS_TOOL_DESCRIPTION).toContain("do not console.log/JSON.stringify the complete result");
  144. expect(JS_TOOL_DESCRIPTION).toContain("use nodeRepl.write for short text-only status");
  145. expect(JS_TOOL_DESCRIPTION).toContain("get_app_state");
  146. expect(JS_TOOL_DESCRIPTION).toContain("nodeRepl.write(state.text)");
  147. expect(JS_TOOL_DESCRIPTION).toContain("state.state_id");
  148. expect(JS_TOOL_DESCRIPTION).toContain(
  149. "Every Computer Use JavaScript call must start with the complete SDK bootstrap",
  150. );
  151. expect(JS_TOOL_DESCRIPTION).toContain(
  152. "Never rely on agent, runtime, browser, or imported bindings from an earlier call",
  153. );
  154. expect(JS_TOOL_DESCRIPTION).toContain(
  155. "Never use screenshot_display.bounds or app/window bounds as raster pixel coordinates",
  156. );
  157. expect(JS_TOOL_DESCRIPTION).toContain(
  158. "Metadata methods such as list_apps and list_windows may not return action_sent",
  159. );
  160. // open_application 已从 Computer Use 面上删除(get_app_state 负责绑定并按需拉起)。
  161. // 工具描述曾漏改,导致每次请求都告诉模型有这个不存在的方法。
  162. expect(JS_TOOL_DESCRIPTION).not.toContain("open_application");
  163. });
  164. it("creates a fresh kernel for every js call", async () => {
  165. const first = await client.callTool({
  166. name: "js",
  167. arguments: {
  168. code: "globalThis.counter = 41; counter;",
  169. title: "初始化计数",
  170. },
  171. _meta: requestMeta("session-1"),
  172. });
  173. expect(first.content).toContainEqual(expect.objectContaining({ type: "text", text: "=> 41" }));
  174. const second = await client.callTool({
  175. name: "js",
  176. arguments: {
  177. code: "({ counterType: typeof globalThis.counter, session: nodeRepl.requestMeta.session_id });",
  178. },
  179. _meta: requestMeta("session-1", "main", "turn-2"),
  180. });
  181. expect(second.content).toContainEqual(
  182. expect.objectContaining({
  183. type: "text",
  184. text: expect.stringContaining('"counterType": "undefined"'),
  185. }),
  186. );
  187. expect(second.content).toContainEqual(
  188. expect.objectContaining({
  189. type: "text",
  190. text: expect.stringContaining('"session": "session-1"'),
  191. }),
  192. );
  193. });
  194. it("exposes js as the only node_repl tool and rejects the two retired ones", async () => {
  195. // 修复原因:2026-09-18 下架 js_reset 与 js_add_node_module_dir,node_repl 只留 js。
  196. // js_reset 自 fresh-kernel 改造起就是固定返回成功的空操作,而"永不失败"会让弱模型连续
  197. // 重复调用它(工单 ZCT-2100503886992535552:155 次连调、19 分钟 4837 万输入 token 直到 429)。
  198. // js_add_node_module_dir 则是把宿主职责推给模型——模型无法自行知道该传哪个 node_modules,
  199. // 能告诉它的只有 skill 文档,而文档知道的路径宿主自己就能注入;实测两者调用量均为 0。
  200. // 必须同时守住两件事:不再出现在模型工具面,且调用时明确失败而非静默成功——
  201. // Tool not found 才是模型换策略所需的信号。
  202. const { tools } = await client.listTools();
  203. expect(tools.map((tool) => tool.name)).toEqual(["js"]);
  204. for (const retired of ["js_reset", "js_add_node_module_dir"]) {
  205. await expect(
  206. client.callTool({ name: retired, arguments: {}, _meta: requestMeta("session-1") }),
  207. ).rejects.toThrow(`Tool ${retired} not found`);
  208. }
  209. });
  210. it("supports top-level await import syntax", async () => {
  211. const result = await client.callTool({
  212. name: "js",
  213. arguments: {
  214. code: 'const pathModule = await import("node:path"); pathModule.sep;',
  215. },
  216. _meta: requestMeta("session-1"),
  217. });
  218. expect(result.isError).not.toBe(true);
  219. expect(result.content).toContainEqual(
  220. expect.objectContaining({
  221. type: "text",
  222. text: expect.stringMatching(/^=> [\\/]$/),
  223. }),
  224. );
  225. });
  226. it("ignores spoofed top-level session metadata in favor of the host namespace", async () => {
  227. const result = await client.callTool({
  228. name: "js",
  229. arguments: { code: "nodeRepl.requestMeta.session_id;" },
  230. _meta: {
  231. session_id: "spoofed-session",
  232. ...requestMeta("trusted-session"),
  233. },
  234. });
  235. expect(result.isError).not.toBe(true);
  236. expect(result.content).toContainEqual(
  237. expect.objectContaining({ type: "text", text: "=> trusted-session" }),
  238. );
  239. });
  240. it("keeps generic JavaScript available for subagent calls", async () => {
  241. const result = await client.callTool({
  242. name: "js",
  243. arguments: { code: "21 * 2;" },
  244. _meta: requestMeta("subagent-session", "subagent"),
  245. });
  246. expect(result.isError).not.toBe(true);
  247. expect(result.content).toContainEqual(expect.objectContaining({ type: "text", text: "=> 42" }));
  248. });
  249. it("returns a structured error without suppressing the standard MCP error marker", async () => {
  250. const result = await client.callTool({
  251. name: "js",
  252. arguments: {
  253. code: [
  254. 'nodeRepl.write("internal diagnostic that must not reach the model");',
  255. "const error = new Error(\"browser tab 'iab-tab:test' returned an invalid viewport\");",
  256. 'error.name = "BrowserCommandError";',
  257. "throw error;",
  258. ].join("\n"),
  259. },
  260. });
  261. expect(result.isError).toBe(true);
  262. expect(result.content).toEqual([
  263. {
  264. type: "text",
  265. text: "browser tab 'iab-tab:test' returned an invalid viewport",
  266. },
  267. ]);
  268. expect(result._meta).toBeUndefined();
  269. expect(JSON.stringify(result)).not.toContain("BrowserCommandError");
  270. expect(JSON.stringify(result)).not.toContain("internal diagnostic");
  271. expect(JSON.stringify(result)).not.toContain(" at ");
  272. });
  273. it("projects images plus response metadata from a fresh call", async () => {
  274. const output = await client.callTool({
  275. name: "js",
  276. arguments: {
  277. code: 'nodeRepl.setResponseMeta({ browser_use: { url: "https://example.test" } }); await nodeRepl.emitImage({ base64: "AAAA", mimeType: "image/png" }); "done";',
  278. },
  279. _meta: requestMeta("session-1"),
  280. });
  281. expect(output.content).toContainEqual(
  282. expect.objectContaining({
  283. type: "image",
  284. data: "AAAA",
  285. mimeType: "image/png",
  286. }),
  287. );
  288. expect(output._meta).toEqual({
  289. browser_use: { url: "https://example.test" },
  290. "zcode/nodeReplEmittedImage": true,
  291. });
  292. });
  293. it("carries no copy of the Computer Use assets", () => {
  294. // 宿主与两个能力插件独立之后,CUA 的 SDK 与文档只有一份,属于 computer-use 插件;
  295. // 宿主按 ZCODE_CUA_PLUGIN_ROOT 去取。2026-09-11 之前 browser-use 各存一份手工副本,
  296. // 其中文档那份悄悄停在重构前的 API,兜底路径会把它发给模型。
  297. for (const relative of [
  298. "../../browser-use-plugin/scripts/computer-use-client.mjs",
  299. "../../browser-use-plugin/docs/computer-use.md",
  300. "../scripts/computer-use-client.mjs",
  301. "../docs/computer-use.md",
  302. ]) {
  303. expect(
  304. existsSync(resolve(import.meta.dirname, relative)),
  305. `${relative} must not exist: the canonical copy lives in zcode-cua-plugin`,
  306. ).toBe(false);
  307. }
  308. expect(
  309. existsSync(
  310. resolve(import.meta.dirname, "../../zcode-cua-plugin/scripts/computer-use-client.mjs"),
  311. ),
  312. ).toBe(true);
  313. });
  314. it("orders image blocks before the text block so image-first providers keep the raster", () => {
  315. const result = toMcpRunResult({
  316. logs: "log line",
  317. result: "done",
  318. images: [
  319. { base64: "AQID", mimeType: "image/png" },
  320. { base64: "BAUG", mimeType: "image/jpeg" },
  321. ],
  322. });
  323. expect(result.content).toEqual([
  324. { type: "image", data: "AQID", mimeType: "image/png" },
  325. { type: "image", data: "BAUG", mimeType: "image/jpeg" },
  326. { type: "text", text: "log line\n=> done" },
  327. ]);
  328. });
  329. it("drops a byte-identical emitImage duplicate so a redundant call cannot cost the whole frame", () => {
  330. // Bug 原因(2026-09-11 真机):模型写
  331. // const shot = await app.getScreenshot(); await nodeRepl.emitImage(shot);
  332. // getScreenshot 已经经 emitStructuredResult 投过「图 + 权威」,于是结果里两张图,
  333. // exact-raster 门按「每个结果只允许一张最终 raster」把整帧原子否决。
  334. //
  335. // 门不能放宽(frame_id 绑定像素坐标),但逐字节相同的那份是纯冗余,丢掉即可,
  336. // 冗余调用不再连累整帧被否决。
  337. const authority = JSON.stringify({
  338. image_ref: { actionable: true, frame_id: "frame-1", height: 2, width: 4 },
  339. });
  340. const result = toMcpRunResult({
  341. structuredResults: [
  342. {
  343. content: [
  344. { type: "image", data: "AQID", mimeType: "image/png" },
  345. { type: "text", text: authority },
  346. ],
  347. },
  348. ],
  349. images: [{ base64: "AQID", mimeType: "image/png" }],
  350. } as never);
  351. const images = result.content.filter((block) => block.type === "image");
  352. expect(images).toEqual([{ type: "image", data: "AQID", mimeType: "image/png" }]);
  353. // 权威必须紧跟在存活的那张图后面 —— 原子对不能被去重打散。
  354. expect(result.content[0]?.type).toBe("image");
  355. expect((result.content[1] as { text?: string }).text).toBe(authority);
  356. });
  357. it("keeps a different model image so a genuine two-raster result still reaches the gate", () => {
  358. // 字节不同就不是冗余:那是真的两张 raster,判定权仍属完整性门,宿主不得代它放行。
  359. const result = toMcpRunResult({
  360. structuredResults: [{ content: [{ type: "image", data: "AQID", mimeType: "image/png" }] }],
  361. images: [{ base64: "ZZZZ", mimeType: "image/png" }],
  362. } as never);
  363. expect(result.content.filter((block) => block.type === "image")).toHaveLength(2);
  364. });
  365. it("flattens an SDK CallToolResult so CUA action-state and image references stay top-level", () => {
  366. const embedded = {
  367. content: [
  368. { type: "text", text: "Clicked Save." },
  369. {
  370. type: "text",
  371. text: JSON.stringify({
  372. schema_version: "zcode-cua-action-outcome-v1",
  373. action_sent: true,
  374. verification_status: "verified",
  375. state_available: true,
  376. }),
  377. },
  378. { type: "text", text: '{"image_ref":"frame-1"}' },
  379. ],
  380. structuredContent: { action_state: { state_id: "state-2" } },
  381. };
  382. const result = toMcpRunResult({
  383. logs: "",
  384. result: `=> ${JSON.stringify(embedded)}`,
  385. images: [{ base64: "AQID", mimeType: "image/png" }],
  386. });
  387. expect(result.content).toEqual([
  388. { type: "image", data: "AQID", mimeType: "image/png" },
  389. ...embedded.content,
  390. ]);
  391. expect(result).toMatchObject({ structuredContent: embedded.structuredContent });
  392. });
  393. it("keeps an SDK result authoritative when the model logs its returned value", () => {
  394. const structured = {
  395. content: [
  396. { type: "image", data: "AQID", mimeType: "image/png" },
  397. { type: "text", text: '{"image_ref":"frame-2"}' },
  398. ],
  399. structuredContent: { state_id: "state-2" },
  400. _meta: { "zcode-cua": "official" },
  401. };
  402. const result = toMcpRunResult({
  403. logs: `console output\n${JSON.stringify({ content: structured.content })}`,
  404. result: JSON.stringify({ content: structured.content }),
  405. structuredResults: [structured],
  406. });
  407. expect(result.content).toEqual([
  408. ...structured.content,
  409. {
  410. type: "text",
  411. text: 'console output\n{"content":[{"type":"image","data":"AQID","mimeType":"image/png"},{"type":"text","text":"{\\"image_ref\\":\\"frame-2\\"}"}]}',
  412. },
  413. ]);
  414. expect(result).toMatchObject({
  415. structuredContent: structured.structuredContent,
  416. _meta: structured._meta,
  417. });
  418. });
  419. it("keeps CUA sideband metadata without adding a legacy action text block", () => {
  420. const result = toMcpRunResult({
  421. logs: "state_id=s-2\nelements (1):",
  422. result: undefined,
  423. structuredResults: [
  424. {
  425. content: [],
  426. _meta: { "zcode.cua/target-app-display-v1": { pid: 7 } },
  427. },
  428. ],
  429. });
  430. expect(result.content).toEqual([{ type: "text", text: "state_id=s-2\nelements (1):" }]);
  431. expect(result._meta).toMatchObject({
  432. "zcode.cua/target-app-display-v1": { pid: 7 },
  433. });
  434. });
  435. it("keeps the single text block when no image is emitted", () => {
  436. expect(toMcpRunResult({ logs: "", result: undefined }).content).toEqual([
  437. { type: "text", text: "(no output)" },
  438. ]);
  439. });
  440. it("projects trusted browser screenshot image indices and removes spoofed response metadata", () => {
  441. const screenshot = toMcpRunResult({
  442. logs: "",
  443. images: [{ base64: "AQID", mimeType: "image/png" }],
  444. browserScreenshotImageIndices: [0],
  445. });
  446. // image 现在从 content[0] 开始,image 下标与 content 下标一致,不再有 +1 偏移。
  447. expect(screenshot.content[0]).toEqual({
  448. type: "image",
  449. data: "AQID",
  450. mimeType: "image/png",
  451. });
  452. expect(screenshot._meta).toMatchObject({
  453. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  454. });
  455. const spoofed = toMcpRunResult({
  456. logs: "",
  457. images: [{ base64: "BAUG", mimeType: "image/png" }],
  458. responseMeta: {
  459. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [1],
  460. },
  461. });
  462. expect(spoofed._meta).not.toHaveProperty(ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY);
  463. });
  464. it("projects the CUA app identity recorded by the bridge and drops the sandbox-forgeable key", () => {
  465. // `nodeRepl.setResponseMeta` / `nodeRepl.emitStructuredResult` 都挂在模型可见的 sandbox
  466. // globals 上,所以 producer 键经这两条通道到达时不可信 —— 模型能让工具卡声称自己操作了
  467. // 别的应用。可信事实只来自 CUA bridge 从 broker 响应直接记录的 run.cuaApp。
  468. const trusted = toMcpRunResult({
  469. logs: "",
  470. cuaApp: { appKey: "darwin:com.apple.notes", displayName: "Notes" },
  471. responseMeta: {
  472. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  473. schemaVersion: 1,
  474. primary: { appKey: "darwin:com.apple.systempreferences", displayName: "System Settings" },
  475. },
  476. },
  477. } as never);
  478. expect(trusted._meta).toMatchObject({
  479. [ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY]: {
  480. appKey: "darwin:com.apple.notes",
  481. displayName: "Notes",
  482. },
  483. });
  484. // 伪造的 producer 键必须整条消失,不能与可信键并存后被下游误取。
  485. expect(trusted._meta).not.toHaveProperty(CUA_APP_ASSOCIATIONS_META_KEY);
  486. // 没有可信记录时,光靠沙箱伪造拿不到任何身份。
  487. const forgedOnly = toMcpRunResult({
  488. logs: "",
  489. responseMeta: {
  490. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  491. schemaVersion: 1,
  492. primary: { appKey: "darwin:com.apple.notes" },
  493. },
  494. },
  495. } as never);
  496. expect(forgedOnly._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY);
  497. expect(forgedOnly._meta ?? {}).not.toHaveProperty(CUA_APP_ASSOCIATIONS_META_KEY);
  498. });
  499. it("maps screenshot indices to their real content positions when only some images are screenshots", () => {
  500. const result = toMcpRunResult({
  501. logs: "",
  502. images: [
  503. { base64: "AAAA", mimeType: "image/png" },
  504. { base64: "BBBB", mimeType: "image/png" },
  505. { base64: "CCCC", mimeType: "image/png" },
  506. ],
  507. browserScreenshotImageIndices: [0, 2],
  508. });
  509. expect(result._meta).toMatchObject({
  510. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0, 2],
  511. });
  512. // 每个声明的下标都必须真的指向 content 里的 image block(越界或指到 text 都会让原图落盘错位)。
  513. for (const index of [0, 2]) {
  514. expect(result.content[index]?.type).toBe("image");
  515. }
  516. expect(result.content[1]).toEqual({ type: "image", data: "BBBB", mimeType: "image/png" });
  517. });
  518. });