mcp-server.test.ts 22 KB

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