mcp-server.test.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. import { randomUUID } from "node:crypto";
  2. import { existsSync, readFileSync } from "node:fs";
  3. import { createServer } from "node:net";
  4. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  5. import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
  6. import { tmpdir } from "node:os";
  7. import { join, resolve } from "node:path";
  8. import { afterEach, beforeEach, describe, expect, it } from "vitest";
  9. import {
  10. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  11. ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY,
  12. ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY,
  13. ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY,
  14. } from "@zcode/contracts";
  15. import { CUA_APP_ASSOCIATIONS_META_KEY } from "@zcode/zcode-cua/host-display-contract";
  16. import {
  17. captureComputerUseRuntimeFromEnvironment,
  18. createInProcessNodeReplExecutor,
  19. createNodeReplMcpRuntime,
  20. main,
  21. type NodeReplMcpRuntime,
  22. } from "../src/server.js";
  23. import { toMcpRunResult } from "../src/result.js";
  24. import type { NodeReplCallFacts } from "../src/call-ledger/contract.js";
  25. /** 主线程账本里记下的可信事实(20-node-repl-call-ledger.md「结果组装」)。 */
  26. function ledgerFacts(facts: Partial<NodeReplCallFacts> = {}): NodeReplCallFacts {
  27. return { cuaApps: [], browserScreenshots: [], browserUse: false, computerUse: false, ...facts };
  28. }
  29. import {
  30. NODE_REPL_DEFAULT_TIMEOUT_MS,
  31. NODE_REPL_SERVER_INSTRUCTIONS,
  32. JS_TOOL_DESCRIPTION,
  33. } from "../src/tool-contract.js";
  34. describe("node_repl MCP server", () => {
  35. const packageVersion = (
  36. JSON.parse(readFileSync(resolve(import.meta.dirname, "../package.json"), "utf8")) as {
  37. version: string;
  38. }
  39. ).version;
  40. let client: Client;
  41. let runtime: NodeReplMcpRuntime;
  42. const requestMeta = (
  43. sessionId: string,
  44. runtimeScope: "main" | "subagent" = "main",
  45. turnId = "turn-1",
  46. ) => ({
  47. "com.zcode/request-context": {
  48. runtime_scope: runtimeScope,
  49. session_id: sessionId,
  50. turn_id: turnId,
  51. },
  52. });
  53. beforeEach(async () => {
  54. runtime = createNodeReplMcpRuntime({ executeJs: createInProcessNodeReplExecutor() });
  55. client = new Client({ name: "node-repl-test", version: "0.1.0" });
  56. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  57. await runtime.server.connect(serverTransport);
  58. await client.connect(clientTransport);
  59. });
  60. afterEach(async () => {
  61. await client.close();
  62. runtime.dispose();
  63. });
  64. it("exports the main entrypoint required by the packaged plugin host", () => {
  65. expect(main).toBeTypeOf("function");
  66. expect(client.getServerVersion()).toEqual({
  67. name: "node_repl",
  68. version: packageVersion,
  69. });
  70. });
  71. it("captures Computer Use credentials before the plugin host restores its environment", async () => {
  72. const capturedRuntime = captureComputerUseRuntimeFromEnvironment({
  73. ZCODE_CUA_PERMISSION_BROKER_SOCKET: "/tmp/deferred-cua.sock",
  74. ZCODE_CUA_PERMISSION_BROKER_TOKEN: "deferred-cua-token",
  75. });
  76. expect(capturedRuntime).toBeDefined();
  77. let forwardedBroker: unknown;
  78. const deferredRuntime = createNodeReplMcpRuntime({
  79. cuaRuntime: capturedRuntime,
  80. executeJs: async (input) => {
  81. forwardedBroker = input.cuaBroker;
  82. return { logs: "", result: "ok" };
  83. },
  84. });
  85. const deferredClient = new Client({ name: "deferred-cua-test", version: "0.1.0" });
  86. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  87. await deferredRuntime.server.connect(serverTransport);
  88. await deferredClient.connect(clientTransport);
  89. try {
  90. await deferredClient.callTool({
  91. name: "js",
  92. arguments: { code: "1", title: "验证 Computer Use bridge" },
  93. _meta: requestMeta("deferred-cua-session"),
  94. });
  95. expect(forwardedBroker).toMatchObject({
  96. socketPath: expect.any(String),
  97. token: expect.any(String),
  98. });
  99. } finally {
  100. await deferredClient.close();
  101. deferredRuntime.dispose();
  102. }
  103. });
  104. it("requires user-facing titles in the model schema while preserving legacy runtime input", async () => {
  105. const { tools } = await client.listTools();
  106. expect(tools.map((tool) => tool.name).sort()).toEqual(["js"]);
  107. const js = tools.find((tool) => tool.name === "js");
  108. expect(js?.inputSchema).toMatchObject({
  109. additionalProperties: false,
  110. required: ["code", "title"],
  111. type: "object",
  112. });
  113. expect(Object.keys(js?.inputSchema.properties ?? {}).sort()).toEqual([
  114. "code",
  115. "timeout_ms",
  116. "title",
  117. ]);
  118. expect(js?.inputSchema.properties?.code).toMatchObject({
  119. description: "JavaScript code to execute in the Node REPL session",
  120. });
  121. expect(js?.inputSchema.properties?.timeout_ms).toMatchObject({
  122. description: expect.stringContaining(
  123. "You MUST provide this when the code is expected to run longer than 30000 ms",
  124. ),
  125. });
  126. expect(js?.description).toContain("required `title`");
  127. expect(NODE_REPL_DEFAULT_TIMEOUT_MS).toBe(60_000);
  128. expect(NODE_REPL_SERVER_INSTRUCTIONS).toContain("default to a 60000 ms timeout");
  129. expect(js?.description).toContain("after 60000 ms");
  130. expect(js?.description).toContain(
  131. "you MUST set `timeout_ms` to at least the estimated total runtime plus 15000 ms",
  132. );
  133. expect(js?.description).not.toContain("after 30000 ms");
  134. const legacyCall = await client.callTool({
  135. name: "js",
  136. arguments: { code: '"legacy";' },
  137. });
  138. expect(legacyCall.isError).not.toBe(true);
  139. expect(legacyCall.content).toContainEqual(
  140. expect.objectContaining({ type: "text", text: "=> legacy" }),
  141. );
  142. });
  143. it("limits every model-visible node_repl description to official browser/computer use", async () => {
  144. const { tools } = await client.listTools();
  145. const js = tools.find((tool) => tool.name === "js");
  146. expect(NODE_REPL_SERVER_INSTRUCTIONS).toMatch(/^Browser Use and Computer Use only\./);
  147. expect(NODE_REPL_SERVER_INSTRUCTIONS).toContain("Do not use this server for unrelated tasks");
  148. expect(js?.description).toMatch(/^Browser Use and Computer Use only\./);
  149. expect(js?.description).toContain("Do not use it as a general-purpose JavaScript runtime");
  150. });
  151. it("teaches the generic node_repl tool to keep CUA results structured", () => {
  152. expect(JS_TOOL_DESCRIPTION).toContain("do not console.log/JSON.stringify the complete result");
  153. expect(JS_TOOL_DESCRIPTION).toContain("use nodeRepl.write for short text-only status");
  154. expect(JS_TOOL_DESCRIPTION).toContain("get_app_state");
  155. expect(JS_TOOL_DESCRIPTION).toContain("nodeRepl.write(state.text)");
  156. expect(JS_TOOL_DESCRIPTION).toContain("state.state_id");
  157. expect(JS_TOOL_DESCRIPTION).toContain(
  158. "Every Computer Use JavaScript call must start with the complete SDK bootstrap",
  159. );
  160. expect(JS_TOOL_DESCRIPTION).toContain(
  161. "Never rely on agent, runtime, browser, or imported bindings from an earlier call",
  162. );
  163. expect(JS_TOOL_DESCRIPTION).toContain(
  164. "Never use screenshot_display.bounds or app/window bounds as raster pixel coordinates",
  165. );
  166. expect(JS_TOOL_DESCRIPTION).toContain(
  167. "Metadata methods such as list_apps and list_windows may not return action_sent",
  168. );
  169. // open_application 已从 Computer Use 面上删除(get_app_state 负责绑定并按需拉起)。
  170. // 工具描述曾漏改,导致每次请求都告诉模型有这个不存在的方法。
  171. expect(JS_TOOL_DESCRIPTION).not.toContain("open_application");
  172. });
  173. it("creates a fresh kernel for every js call", async () => {
  174. const first = await client.callTool({
  175. name: "js",
  176. arguments: {
  177. code: "globalThis.counter = 41; counter;",
  178. title: "初始化计数",
  179. },
  180. _meta: requestMeta("session-1"),
  181. });
  182. expect(first.content).toContainEqual(expect.objectContaining({ type: "text", text: "=> 41" }));
  183. const second = await client.callTool({
  184. name: "js",
  185. arguments: {
  186. code: "({ counterType: typeof globalThis.counter, session: nodeRepl.requestMeta.session_id });",
  187. },
  188. _meta: requestMeta("session-1", "main", "turn-2"),
  189. });
  190. expect(second.content).toContainEqual(
  191. expect.objectContaining({
  192. type: "text",
  193. text: expect.stringContaining('"counterType": "undefined"'),
  194. }),
  195. );
  196. expect(second.content).toContainEqual(
  197. expect.objectContaining({
  198. type: "text",
  199. text: expect.stringContaining('"session": "session-1"'),
  200. }),
  201. );
  202. });
  203. it("exposes js as the only node_repl tool and rejects the two retired ones", async () => {
  204. // 修复原因:2026-09-18 下架 js_reset 与 js_add_node_module_dir,node_repl 只留 js。
  205. // js_reset 自 fresh-kernel 改造起就是固定返回成功的空操作,而"永不失败"会让弱模型连续
  206. // 重复调用它(工单 ZCT-2100503886992535552:155 次连调、19 分钟 4837 万输入 token 直到 429)。
  207. // js_add_node_module_dir 则是把宿主职责推给模型——模型无法自行知道该传哪个 node_modules,
  208. // 能告诉它的只有 skill 文档,而文档知道的路径宿主自己就能注入;实测两者调用量均为 0。
  209. // 必须同时守住两件事:不再出现在模型工具面,且调用时明确失败而非静默成功——
  210. // Tool not found 才是模型换策略所需的信号。
  211. const { tools } = await client.listTools();
  212. expect(tools.map((tool) => tool.name)).toEqual(["js"]);
  213. for (const retired of ["js_reset", "js_add_node_module_dir"]) {
  214. await expect(
  215. client.callTool({ name: retired, arguments: {}, _meta: requestMeta("session-1") }),
  216. ).rejects.toThrow(`Tool ${retired} not found`);
  217. }
  218. });
  219. it("supports top-level await import syntax", async () => {
  220. const result = await client.callTool({
  221. name: "js",
  222. arguments: {
  223. code: 'const pathModule = await import("node:path"); pathModule.sep;',
  224. },
  225. _meta: requestMeta("session-1"),
  226. });
  227. expect(result.isError).not.toBe(true);
  228. expect(result.content).toContainEqual(
  229. expect.objectContaining({
  230. type: "text",
  231. text: expect.stringMatching(/^=> [\\/]$/),
  232. }),
  233. );
  234. });
  235. it("ignores spoofed top-level session metadata in favor of the host namespace", async () => {
  236. const result = await client.callTool({
  237. name: "js",
  238. arguments: { code: "nodeRepl.requestMeta.session_id;" },
  239. _meta: {
  240. session_id: "spoofed-session",
  241. ...requestMeta("trusted-session"),
  242. },
  243. });
  244. expect(result.isError).not.toBe(true);
  245. expect(result.content).toContainEqual(
  246. expect.objectContaining({ type: "text", text: "=> trusted-session" }),
  247. );
  248. });
  249. it("keeps generic JavaScript available for subagent calls", async () => {
  250. const result = await client.callTool({
  251. name: "js",
  252. arguments: { code: "21 * 2;" },
  253. _meta: requestMeta("subagent-session", "subagent"),
  254. });
  255. expect(result.isError).not.toBe(true);
  256. expect(result.content).toContainEqual(expect.objectContaining({ type: "text", text: "=> 42" }));
  257. });
  258. it("returns a structured error without suppressing the standard MCP error marker", async () => {
  259. const result = await client.callTool({
  260. name: "js",
  261. arguments: {
  262. code: [
  263. 'nodeRepl.write("internal diagnostic that must not reach the model");',
  264. "const error = new Error(\"browser tab 'iab-tab:test' returned an invalid viewport\");",
  265. 'error.name = "BrowserCommandError";',
  266. "throw error;",
  267. ].join("\n"),
  268. },
  269. });
  270. expect(result.isError).toBe(true);
  271. expect(result.content).toEqual([
  272. {
  273. type: "text",
  274. text: "browser tab 'iab-tab:test' returned an invalid viewport",
  275. },
  276. ]);
  277. expect(result._meta).toBeUndefined();
  278. expect(JSON.stringify(result)).not.toContain("BrowserCommandError");
  279. expect(JSON.stringify(result)).not.toContain("internal diagnostic");
  280. expect(JSON.stringify(result)).not.toContain(" at ");
  281. });
  282. it("projects images plus response metadata from a fresh call", async () => {
  283. const output = await client.callTool({
  284. name: "js",
  285. arguments: {
  286. code: 'nodeRepl.setResponseMeta({ browser_use: { url: "https://example.test" } }); await nodeRepl.emitImage({ base64: "AAAA", mimeType: "image/png" }); "done";',
  287. },
  288. _meta: requestMeta("session-1"),
  289. });
  290. expect(output.content).toContainEqual(
  291. expect.objectContaining({
  292. type: "image",
  293. data: "AAAA",
  294. mimeType: "image/png",
  295. }),
  296. );
  297. expect(output._meta).toEqual({
  298. browser_use: { url: "https://example.test" },
  299. "zcode/nodeReplEmittedImage": true,
  300. });
  301. });
  302. it("carries no copy of the Computer Use assets", () => {
  303. // 宿主与两个能力插件独立之后,CUA 的 SDK 与文档只有一份,属于 computer-use 插件;
  304. // 宿主按 ZCODE_CUA_PLUGIN_ROOT 去取。2026-09-11 之前 browser-use 各存一份手工副本,
  305. // 其中文档那份悄悄停在重构前的 API,兜底路径会把它发给模型。
  306. for (const relative of [
  307. "../../browser-use-plugin/scripts/computer-use-client.mjs",
  308. "../../browser-use-plugin/docs/computer-use.md",
  309. "../scripts/computer-use-client.mjs",
  310. "../docs/computer-use.md",
  311. ]) {
  312. expect(
  313. existsSync(resolve(import.meta.dirname, relative)),
  314. `${relative} must not exist: the canonical copy lives in zcode-cua-plugin`,
  315. ).toBe(false);
  316. }
  317. expect(
  318. existsSync(
  319. resolve(import.meta.dirname, "../../zcode-cua-plugin/scripts/computer-use-client.mjs"),
  320. ),
  321. ).toBe(true);
  322. });
  323. it("orders image blocks before the text block so image-first providers keep the raster", () => {
  324. const result = toMcpRunResult({
  325. logs: "log line",
  326. result: "done",
  327. images: [
  328. { base64: "AQID", mimeType: "image/png" },
  329. { base64: "BAUG", mimeType: "image/jpeg" },
  330. ],
  331. });
  332. expect(result.content).toEqual([
  333. { type: "image", data: "AQID", mimeType: "image/png" },
  334. { type: "image", data: "BAUG", mimeType: "image/jpeg" },
  335. { type: "text", text: "log line\n=> done" },
  336. ]);
  337. });
  338. it("drops a byte-identical emitImage duplicate so a redundant call cannot cost the whole frame", () => {
  339. // Bug 原因(2026-09-11 真机):模型写
  340. // const shot = await app.getScreenshot(); await nodeRepl.emitImage(shot);
  341. // getScreenshot 已经经 emitStructuredResult 投过「图 + 权威」,于是结果里两张图,
  342. // exact-raster 门按「每个结果只允许一张最终 raster」把整帧原子否决。
  343. //
  344. // 门不能放宽(frame_id 绑定像素坐标),但逐字节相同的那份是纯冗余,丢掉即可,
  345. // 冗余调用不再连累整帧被否决。
  346. const authority = JSON.stringify({
  347. image_ref: { actionable: true, frame_id: "frame-1", height: 2, width: 4 },
  348. });
  349. const result = toMcpRunResult({
  350. structuredResults: [
  351. {
  352. content: [
  353. { type: "image", data: "AQID", mimeType: "image/png" },
  354. { type: "text", text: authority },
  355. ],
  356. },
  357. ],
  358. images: [{ base64: "AQID", mimeType: "image/png" }],
  359. } as never);
  360. const images = result.content.filter((block) => block.type === "image");
  361. expect(images).toEqual([{ type: "image", data: "AQID", mimeType: "image/png" }]);
  362. // 权威必须紧跟在存活的那张图后面 —— 原子对不能被去重打散。
  363. expect(result.content[0]?.type).toBe("image");
  364. expect((result.content[1] as { text?: string }).text).toBe(authority);
  365. });
  366. it("keeps a different model image so a genuine two-raster result still reaches the gate", () => {
  367. // 字节不同就不是冗余:那是真的两张 raster,判定权仍属完整性门,宿主不得代它放行。
  368. const result = toMcpRunResult({
  369. structuredResults: [{ content: [{ type: "image", data: "AQID", mimeType: "image/png" }] }],
  370. images: [{ base64: "ZZZZ", mimeType: "image/png" }],
  371. } as never);
  372. expect(result.content.filter((block) => block.type === "image")).toHaveLength(2);
  373. });
  374. it("flattens an SDK CallToolResult so CUA action-state and image references stay top-level", () => {
  375. const embedded = {
  376. content: [
  377. { type: "text", text: "Clicked Save." },
  378. {
  379. type: "text",
  380. text: JSON.stringify({
  381. schema_version: "zcode-cua-action-outcome-v1",
  382. action_sent: true,
  383. verification_status: "verified",
  384. state_available: true,
  385. }),
  386. },
  387. { type: "text", text: '{"image_ref":"frame-1"}' },
  388. ],
  389. structuredContent: { action_state: { state_id: "state-2" } },
  390. };
  391. const result = toMcpRunResult({
  392. logs: "",
  393. result: `=> ${JSON.stringify(embedded)}`,
  394. images: [{ base64: "AQID", mimeType: "image/png" }],
  395. });
  396. expect(result.content).toEqual([
  397. { type: "image", data: "AQID", mimeType: "image/png" },
  398. ...embedded.content,
  399. ]);
  400. expect(result).toMatchObject({ structuredContent: embedded.structuredContent });
  401. });
  402. it("keeps an SDK result authoritative when the model logs its returned value", () => {
  403. const structured = {
  404. content: [
  405. { type: "image", data: "AQID", mimeType: "image/png" },
  406. { type: "text", text: '{"image_ref":"frame-2"}' },
  407. ],
  408. structuredContent: { state_id: "state-2" },
  409. _meta: { "zcode-cua": "official" },
  410. };
  411. const result = toMcpRunResult({
  412. logs: `console output\n${JSON.stringify({ content: structured.content })}`,
  413. result: JSON.stringify({ content: structured.content }),
  414. structuredResults: [structured],
  415. });
  416. expect(result.content).toEqual([
  417. ...structured.content,
  418. {
  419. type: "text",
  420. text: 'console output\n{"content":[{"type":"image","data":"AQID","mimeType":"image/png"},{"type":"text","text":"{\\"image_ref\\":\\"frame-2\\"}"}]}',
  421. },
  422. ]);
  423. expect(result).toMatchObject({
  424. structuredContent: structured.structuredContent,
  425. _meta: structured._meta,
  426. });
  427. });
  428. it("keeps CUA sideband metadata without adding a legacy action text block", () => {
  429. const result = toMcpRunResult({
  430. logs: "state_id=s-2\nelements (1):",
  431. result: undefined,
  432. structuredResults: [
  433. {
  434. content: [],
  435. _meta: { "zcode.cua/target-app-display-v1": { pid: 7 } },
  436. },
  437. ],
  438. });
  439. expect(result.content).toEqual([{ type: "text", text: "state_id=s-2\nelements (1):" }]);
  440. expect(result._meta).toMatchObject({
  441. "zcode.cua/target-app-display-v1": { pid: 7 },
  442. });
  443. });
  444. it("keeps the single text block when no image is emitted", () => {
  445. expect(toMcpRunResult({ logs: "", result: undefined }).content).toEqual([
  446. { type: "text", text: "(no output)" },
  447. ]);
  448. });
  449. it("projects browser screenshot indices from the ledger and removes spoofed metadata", () => {
  450. const screenshot = toMcpRunResult(
  451. { logs: "", images: [{ base64: "AQID", mimeType: "image/png" }] },
  452. ledgerFacts({ browserScreenshots: [{ base64: "AQID", mimeType: "image/png" }] }),
  453. );
  454. // image 现在从 content[0] 开始,image 下标与 content 下标一致,不再有 +1 偏移。
  455. expect(screenshot.content[0]).toEqual({
  456. type: "image",
  457. data: "AQID",
  458. mimeType: "image/png",
  459. });
  460. expect(screenshot._meta).toMatchObject({
  461. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  462. });
  463. const spoofed = toMcpRunResult({
  464. logs: "",
  465. images: [{ base64: "BAUG", mimeType: "image/png" }],
  466. responseMeta: {
  467. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [1],
  468. },
  469. });
  470. expect(spoofed._meta).not.toHaveProperty(ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY);
  471. // Worker 结果消息里的下标可以被 cell 冒充(MR !3207 评审 CR-01),账本里没有截图时一律不采信。
  472. const forgedRun = toMcpRunResult(
  473. {
  474. logs: "",
  475. images: [{ base64: "BAUG", mimeType: "image/png" }],
  476. browserScreenshotImageIndices: [0],
  477. },
  478. ledgerFacts(),
  479. );
  480. expect(forgedRun._meta).not.toHaveProperty(ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY);
  481. });
  482. it("projects the CUA app identity recorded in the ledger and drops the sandbox-forgeable key", () => {
  483. // `nodeRepl.setResponseMeta` / `nodeRepl.emitStructuredResult` 都挂在模型可见的 sandbox
  484. // globals 上,所以 producer 键经这两条通道到达时不可信 —— 模型能让工具卡声称自己操作了
  485. // 别的应用。可信事实只来自主线程 CUA broker 记进账本的身份。
  486. const trusted = toMcpRunResult(
  487. {
  488. logs: "",
  489. responseMeta: {
  490. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  491. schemaVersion: 1,
  492. primary: { appKey: "darwin:com.apple.systempreferences", displayName: "System Settings" },
  493. },
  494. },
  495. },
  496. ledgerFacts({ cuaApps: [{ appKey: "darwin:com.apple.notes", displayName: "Notes" }] }),
  497. );
  498. expect(trusted._meta).toMatchObject({
  499. [ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY]: {
  500. appKey: "darwin:com.apple.notes",
  501. displayName: "Notes",
  502. },
  503. });
  504. // 伪造的 producer 键必须整条消失,不能与可信键并存后被下游误取。
  505. expect(trusted._meta).not.toHaveProperty(CUA_APP_ASSOCIATIONS_META_KEY);
  506. // 没有可信记录时,光靠沙箱伪造拿不到任何身份。
  507. const forgedOnly = toMcpRunResult({
  508. logs: "",
  509. responseMeta: {
  510. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  511. schemaVersion: 1,
  512. primary: { appKey: "darwin:com.apple.notes" },
  513. },
  514. },
  515. } as never);
  516. expect(forgedOnly._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY);
  517. expect(forgedOnly._meta ?? {}).not.toHaveProperty(CUA_APP_ASSOCIATIONS_META_KEY);
  518. // Worker 结果消息里的 cuaApp 可以被 cell 冒充(MR !3207 评审 CR-01),不采信。
  519. const forgedRun = toMcpRunResult(
  520. { logs: "", cuaApp: { appKey: "darwin:com.apple.notes" } },
  521. ledgerFacts(),
  522. );
  523. expect(forgedRun._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY);
  524. });
  525. // 会话能力标签的两个 key 只按账本写(session-features-header.md「BUA/CUA 标签的补充规则」)。
  526. it("writes the runtime-call keys only from the ledger and drops copies the cell writes", () => {
  527. const forged = {
  528. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  529. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  530. };
  531. // 口径是真实尝试:cell 以错误结束也写。
  532. const failed = toMcpRunResult(
  533. { logs: "", error: { name: "Error", message: "boom" } },
  534. ledgerFacts({ browserUse: true, computerUse: true }),
  535. );
  536. expect(failed.isError).toBe(true);
  537. expect(failed._meta).toMatchObject(forged);
  538. const browserOnly = toMcpRunResult(
  539. { logs: "", responseMeta: forged },
  540. ledgerFacts({ browserUse: true }),
  541. );
  542. expect(browserOnly._meta).toMatchObject({ [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true });
  543. expect(browserOnly._meta).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  544. // sandbox 通道写入的同名 key、Worker 结果消息里冒充的字段(MR !3207 评审 CR-01)一律不采信。
  545. for (const run of [
  546. { logs: "", responseMeta: forged },
  547. {
  548. logs: "",
  549. result: JSON.stringify({ content: [{ type: "text", text: "x" }], _meta: forged }),
  550. },
  551. { logs: "", browserUse: true, computerUse: true },
  552. ]) {
  553. const result = toMcpRunResult(run as never, ledgerFacts());
  554. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY);
  555. expect(result._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  556. }
  557. });
  558. it("maps screenshot indices to their real content positions when only some images are screenshots", () => {
  559. const result = toMcpRunResult({
  560. logs: "",
  561. images: [
  562. { base64: "AAAA", mimeType: "image/png" },
  563. { base64: "BBBB", mimeType: "image/png" },
  564. { base64: "CCCC", mimeType: "image/png" },
  565. ],
  566. }, ledgerFacts({
  567. browserScreenshots: [
  568. { base64: "AAAA", mimeType: "image/png" },
  569. { base64: "CCCC", mimeType: "image/png" },
  570. ],
  571. }));
  572. expect(result._meta).toMatchObject({
  573. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0, 2],
  574. });
  575. // 每个声明的下标都必须真的指向 content 里的 image block(越界或指到 text 都会让原图落盘错位)。
  576. for (const index of [0, 2]) {
  577. expect(result.content[index]?.type).toBe("image");
  578. }
  579. expect(result.content[1]).toEqual({ type: "image", data: "BBBB", mimeType: "image/png" });
  580. });
  581. it("derives screenshot indices from what the browser proxy saw, end to end", async () => {
  582. // 真实 MCP server + 浏览器代理 broker + 假的上游浏览器 broker:可信的截图下标只来自代理在
  583. // 主线程记下的截图(20-node-repl-call-ledger.md「结果组装」)。
  584. const upstreamPath =
  585. process.platform === "win32"
  586. ? `\\\\.\\pipe\\zcode-ledger-e2e-${randomUUID()}`
  587. : join(tmpdir(), `zle-${randomUUID()}.sock`);
  588. const upstreamRequests: Array<Record<string, unknown>> = [];
  589. const upstream = createServer((socket) => {
  590. let buffer = "";
  591. socket.on("data", (chunk) => {
  592. buffer += chunk.toString("utf8");
  593. const newline = buffer.indexOf("\n");
  594. if (newline < 0) return;
  595. const request = JSON.parse(buffer.slice(0, newline)) as Record<string, unknown>;
  596. upstreamRequests.push(request);
  597. socket.end(
  598. `${JSON.stringify({
  599. id: request.id,
  600. ok: true,
  601. result: { ok: true, elapsedMs: 1, image: { base64: "AQID", mimeType: "image/png" } },
  602. })}\n`,
  603. );
  604. });
  605. });
  606. await new Promise<void>((resolveListen) => upstream.listen(upstreamPath, resolveListen));
  607. const browserRuntime = createNodeReplMcpRuntime({
  608. executeJs: createInProcessNodeReplExecutor(),
  609. browserBrokerUpstream: { socketPath: upstreamPath, token: "u".repeat(64) },
  610. });
  611. const browserClient = new Client({ name: "node-repl-ledger-e2e", version: "0.1.0" });
  612. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  613. await browserRuntime.server.connect(serverTransport);
  614. await browserClient.connect(clientTransport);
  615. try {
  616. const result = await browserClient.callTool({
  617. name: "js",
  618. arguments: {
  619. code: [
  620. 'const bridge = globalThis[Symbol.for("zcode.node-repl.browser-control-bridge")];',
  621. 'const shot = await bridge.execute("browser-1", 1, { method: "screenshot" });',
  622. "await nodeRepl.emitImage(shot.image);",
  623. '"shot";',
  624. ].join("\n"),
  625. },
  626. _meta: requestMeta("ledger-session"),
  627. });
  628. expect(result.content).toEqual([
  629. { type: "image", data: "AQID", mimeType: "image/png" },
  630. { type: "text", text: "=> shot" },
  631. ]);
  632. expect(result._meta).toMatchObject({
  633. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]: [0],
  634. });
  635. // 上游收到的是上游 token 与本次调用来自 core 的会话信息。
  636. expect(upstreamRequests).toHaveLength(1);
  637. expect(upstreamRequests[0]).toMatchObject({
  638. op: "execute",
  639. token: "u".repeat(64),
  640. sessionId: "ledger-session",
  641. runtimeScope: "main",
  642. turnId: "turn-1",
  643. });
  644. } finally {
  645. await browserClient.close();
  646. browserRuntime.dispose();
  647. await new Promise<void>((resolveClose) => upstream.close(() => resolveClose()));
  648. if (process.platform !== "win32") await rm(upstreamPath, { force: true });
  649. }
  650. });
  651. it("marks runtime calls that reach the real brokers, end to end, and nothing else", async () => {
  652. // 真实 MCP server + 两个 broker:浏览器上游拒绝命令、CUA runtime 抛错,cell 也都接住了错误;
  653. // 口径是真实尝试,两个 key 照样写出(session-features-header.md「BUA/CUA 标签的补充规则」)。
  654. const upstreamPath =
  655. process.platform === "win32"
  656. ? `\\\\.\\pipe\\zcode-runtime-use-e2e-${randomUUID()}`
  657. : join(tmpdir(), `zru-${randomUUID()}.sock`);
  658. const upstream = createServer((socket) => {
  659. let buffer = "";
  660. socket.on("data", (chunk) => {
  661. buffer += chunk.toString("utf8");
  662. const newline = buffer.indexOf("\n");
  663. if (newline < 0) return;
  664. const request = JSON.parse(buffer.slice(0, newline)) as { id?: unknown };
  665. const response = { id: request.id, ok: false, error: "Browser is not connected" };
  666. socket.end(`${JSON.stringify(response)}\n`);
  667. });
  668. });
  669. await new Promise<void>((resolveListen) => upstream.listen(upstreamPath, resolveListen));
  670. let cuaExecuted = 0;
  671. const useRuntime = createNodeReplMcpRuntime({
  672. executeJs: createInProcessNodeReplExecutor(),
  673. browserBrokerUpstream: { socketPath: upstreamPath, token: "u".repeat(64) },
  674. cuaRuntime: {
  675. execute: async () => {
  676. cuaExecuted += 1;
  677. throw new Error("Computer Use Helper is not running");
  678. },
  679. closeSession: async () => undefined,
  680. dispose: async () => undefined,
  681. },
  682. });
  683. const useClient = new Client({ name: "node-repl-runtime-use-e2e", version: "0.1.0" });
  684. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  685. await useRuntime.server.connect(serverTransport);
  686. await useClient.connect(clientTransport);
  687. const forged = JSON.stringify({
  688. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  689. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  690. });
  691. // CUA broker 要求 workspace 信息,缺了会在调用 runtime 之前拒绝。
  692. const callMeta = {
  693. "com.zcode/request-context": {
  694. ...requestMeta("runtime-use-session")["com.zcode/request-context"],
  695. workspace_path: "/workspace",
  696. },
  697. };
  698. try {
  699. const called = await useClient.callTool({
  700. name: "js",
  701. arguments: {
  702. code: [
  703. 'const browser = globalThis[Symbol.for("zcode.node-repl.browser-control-bridge")];',
  704. 'const cua = globalThis[Symbol.for("zcode.node-repl.computer-use-bridge")];',
  705. "const outcomes = [];",
  706. "try { await browser.list(); } catch (error) { outcomes.push(error.message); }",
  707. 'try { await cua.call("screenshot", {}); } catch (error) { outcomes.push(error.message); }',
  708. 'outcomes.join(" | ");',
  709. ].join("\n"),
  710. },
  711. _meta: callMeta,
  712. });
  713. // 前提:两次调用都到达了 broker,并且都失败了。
  714. expect(called.content).toContainEqual({
  715. type: "text",
  716. text: "=> Browser is not connected | Computer Use Helper is not running",
  717. });
  718. expect(cuaExecuted).toBe(1);
  719. expect(called._meta).toMatchObject({
  720. [ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY]: true,
  721. [ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY]: true,
  722. });
  723. // 只做 CUA 引导、只在代码里提到运行时、经 sandbox 通道自己写 key:都没有请求到达 broker。
  724. const notCalled = await useClient.callTool({
  725. name: "js",
  726. arguments: {
  727. code: [
  728. 'globalThis[Symbol.for("zcode.node-repl.computer-use-bridge")].assertAvailable();',
  729. "// await agent.browsers.list(); await setupComputerUseRuntime({ globals: globalThis });",
  730. `nodeRepl.setResponseMeta(${forged});`,
  731. `nodeRepl.emitStructuredResult({ content: [{ type: "text", text: "forged" }], _meta: ${forged} });`,
  732. '"done";',
  733. ].join("\n"),
  734. },
  735. _meta: callMeta,
  736. });
  737. // 前提:cell 正常执行完,sandbox 通道确实生效了。
  738. expect(notCalled.isError).not.toBe(true);
  739. expect(notCalled.content).toContainEqual({ type: "text", text: "forged" });
  740. expect(notCalled._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_BROWSER_USE_META_KEY);
  741. expect(notCalled._meta ?? {}).not.toHaveProperty(ZCODE_MCP_NODE_REPL_COMPUTER_USE_META_KEY);
  742. expect(cuaExecuted).toBe(1);
  743. } finally {
  744. await useClient.close();
  745. useRuntime.dispose();
  746. await new Promise<void>((resolveClose) => upstream.close(() => resolveClose()));
  747. if (process.platform !== "win32") await rm(upstreamPath, { force: true });
  748. }
  749. });
  750. it("tells the model it may end the turn after repeated js calls without progress", async () => {
  751. const stderr: string[] = [];
  752. const guardedRuntime = createNodeReplMcpRuntime({
  753. executeJs: createInProcessNodeReplExecutor(),
  754. writeStderr: (text) => stderr.push(text),
  755. });
  756. const guardedClient = new Client({ name: "no-progress-test", version: "0.1.0" });
  757. const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
  758. await guardedRuntime.server.connect(serverTransport);
  759. await guardedClient.connect(clientTransport);
  760. const call = (code: string, turnId: string) =>
  761. guardedClient.callTool({
  762. name: "js",
  763. arguments: { code, title: "本轮结束" },
  764. _meta: requestMeta("no-progress-session", "main", turnId),
  765. }) as Promise<{ content: Array<{ type: string; text?: string }>; isError?: boolean }>;
  766. try {
  767. const results = [];
  768. for (let index = 0; index < 10; index += 1) {
  769. results.push(await call(`// end ${index}`, "turn-a"));
  770. }
  771. for (const result of results.slice(0, 9)) {
  772. expect(result.content).toEqual([{ type: "text", text: "(no output)" }]);
  773. }
  774. expect(results[9]).toEqual({
  775. content: [
  776. { type: "text", text: "(no output)" },
  777. { type: "text", text: "[node_repl] No progress ×10. You may end this turn." },
  778. ],
  779. });
  780. expect(stderr).toEqual([
  781. "[node_repl] no-progress hint kind=no_progress count=10 session=no-progress-session turn=turn-a\n",
  782. ]);
  783. expect((await call("// end", "turn-b")).content).toEqual([
  784. { type: "text", text: "(no output)" },
  785. ]);
  786. } finally {
  787. await guardedClient.close();
  788. guardedRuntime.dispose();
  789. }
  790. });
  791. });