cua-bridge.test.ts 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { createConnection } from "node:net";
  2. import { afterEach, describe, expect, it } from "vitest";
  3. import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
  4. import { createComputerUseBridgeGlobals, NODE_REPL_CUA_BRIDGE_SYMBOL } from "../src/cua-bridge.js";
  5. import { createNodeReplCuaBroker, type NodeReplCuaBroker } from "../src/cua-broker.js";
  6. import { CUA_APP_ASSOCIATIONS_META_KEY } from "@zcode/zcode-cua/host-display-contract";
  7. describe("node_repl CUA bridge", () => {
  8. let broker: NodeReplCuaBroker | undefined;
  9. afterEach(async () => {
  10. await broker?.close();
  11. broker = undefined;
  12. });
  13. it("forwards the complete trusted request context to the shared runtime", async () => {
  14. const calls: unknown[] = [];
  15. broker = createNodeReplCuaBroker({
  16. runtime: {
  17. execute: async (input) => {
  18. calls.push(input);
  19. return {
  20. content: [{ type: "text", text: "ok" }],
  21. structuredContent: { state_id: "state-1" },
  22. } satisfies CallToolResult;
  23. },
  24. closeSession: async () => undefined,
  25. dispose: async () => undefined,
  26. },
  27. // 不传 platform 时 createNodeReplCuaBroker 会走 POSIX 分支,在 tmpdir 里建
  28. // `znrc-*.sock`;Windows 的 net.Server.listen 只接受命名管道,给文件路径直接
  29. // EACCES,于是这条用例在 Windows 上从来没跑过。产品代码本身是对的(它按
  30. // platform 分支选管道或 unix socket),所以测试必须跑在真实平台上,而不是
  31. // 默默假设 POSIX。
  32. platform: process.platform,
  33. });
  34. await broker.ready;
  35. const active = {
  36. generation: 3,
  37. requestMeta: {
  38. runtime_scope: "main" as const,
  39. session_id: "session-1",
  40. workspace_path: "/workspace",
  41. workspace_identity: "ssh://host/workspace",
  42. workspace_key: "ssh://host/workspace",
  43. remote_session_id: "remote-1",
  44. turn_id: "turn-1",
  45. client_mode: "web-remote-replayable",
  46. delivery_kind: "web-remote-replayable",
  47. trace_id: "trace-1",
  48. span_id: "span-1",
  49. },
  50. signal: new AbortController().signal,
  51. };
  52. const session = { mergeResponseMeta: () => undefined } as never;
  53. const globals = createComputerUseBridgeGlobals({
  54. broker: broker.connection,
  55. documentationRoot: "/tmp/docs",
  56. generation: active.generation,
  57. getActiveCall: () => active,
  58. session: () => session,
  59. });
  60. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  61. call(method: string, input: unknown): Promise<CallToolResult>;
  62. };
  63. await expect(bridge.call("screenshot", { display_id: 1 })).resolves.toMatchObject({
  64. structuredContent: { state_id: "state-1" },
  65. });
  66. expect(calls).toHaveLength(1);
  67. expect(calls[0]).toMatchObject({
  68. toolName: "screenshot",
  69. arguments: { display_id: 1 },
  70. context: {
  71. sessionId: "session-1",
  72. workspacePath: "/workspace",
  73. workspaceIdentity: "ssh://host/workspace",
  74. workspaceKey: "ssh://host/workspace",
  75. remoteSessionId: "remote-1",
  76. clientMode: "web-remote-replayable",
  77. deliveryKind: "web-remote-replayable",
  78. trace: { traceId: "trace-1", spanId: "span-1" },
  79. },
  80. });
  81. });
  82. it("records the target app identity from the broker response, not from sandbox code", async () => {
  83. // 工具卡的 App 图标只能来自 broker 响应:这一跳沙箱看不见,也改不了。producer 自带的
  84. // 内联 icon PNG 不进 run 结果(会话协议不承载 data URL),只保留 appKey/displayName。
  85. broker = createNodeReplCuaBroker({
  86. runtime: {
  87. execute: async () =>
  88. ({
  89. content: [{ type: "text", text: "clicked" }],
  90. _meta: {
  91. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  92. schemaVersion: 1,
  93. primary: {
  94. appKey: "darwin:com.apple.notes",
  95. displayName: "Notes",
  96. icon: { mimeType: "image/png", data: "iVBORw0KGgo=" },
  97. },
  98. },
  99. },
  100. }) satisfies CallToolResult,
  101. closeSession: async () => undefined,
  102. dispose: async () => undefined,
  103. },
  104. platform: process.platform,
  105. });
  106. await broker.ready;
  107. const active = {
  108. generation: 1,
  109. requestMeta: { runtime_scope: "main" as const, session_id: "session-1", workspace_key: "ws" },
  110. signal: new AbortController().signal,
  111. };
  112. const recorded: unknown[] = [];
  113. const session = {
  114. mergeResponseMeta: () => undefined,
  115. recordCuaAppIdentity: (app: unknown) => recorded.push(app),
  116. } as never;
  117. const globals = createComputerUseBridgeGlobals({
  118. broker: broker.connection,
  119. documentationRoot: "/tmp/docs",
  120. generation: 1,
  121. getActiveCall: () => active,
  122. session: () => session,
  123. });
  124. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  125. call(method: string, input: unknown): Promise<CallToolResult>;
  126. };
  127. await bridge.call("left_click", { app_ref: { pid: 1 } });
  128. expect(recorded).toEqual([{ appKey: "darwin:com.apple.notes", displayName: "Notes" }]);
  129. });
  130. it("ignores app associations that carry no primary identity", async () => {
  131. // list_apps 声明的是 items 模式,没有 primary;request_access / stop 声明 none。
  132. // 这些调用不能覆盖同一 cell 里前面动作已经确立的身份。
  133. broker = createNodeReplCuaBroker({
  134. runtime: {
  135. execute: async () =>
  136. ({
  137. content: [{ type: "text", text: "[]" }],
  138. _meta: {
  139. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  140. schemaVersion: 1,
  141. items: [{ resultIndex: 0, application: { appKey: "darwin:com.apple.finder" } }],
  142. },
  143. },
  144. }) satisfies CallToolResult,
  145. closeSession: async () => undefined,
  146. dispose: async () => undefined,
  147. },
  148. platform: process.platform,
  149. });
  150. await broker.ready;
  151. const active = {
  152. generation: 1,
  153. requestMeta: { runtime_scope: "main" as const, session_id: "session-1", workspace_key: "ws" },
  154. signal: new AbortController().signal,
  155. };
  156. const recorded: unknown[] = [];
  157. const globals = createComputerUseBridgeGlobals({
  158. broker: broker.connection,
  159. documentationRoot: "/tmp/docs",
  160. generation: 1,
  161. getActiveCall: () => active,
  162. session: () =>
  163. ({
  164. mergeResponseMeta: () => undefined,
  165. recordCuaAppIdentity: (app: unknown) => recorded.push(app),
  166. }) as never,
  167. });
  168. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  169. call(method: string, input: unknown): Promise<CallToolResult>;
  170. };
  171. await bridge.call("list_apps", {});
  172. expect(recorded).toEqual([]);
  173. });
  174. it("rejects subagents before opening the broker", async () => {
  175. const active = {
  176. generation: 1,
  177. requestMeta: { runtime_scope: "subagent" as const, session_id: "subagent-1" },
  178. signal: new AbortController().signal,
  179. };
  180. const globals = createComputerUseBridgeGlobals({
  181. documentationRoot: "/tmp/docs",
  182. generation: 1,
  183. getActiveCall: () => active,
  184. session: () => ({ mergeResponseMeta: () => undefined }) as never,
  185. });
  186. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  187. call(method: string, input: unknown): Promise<CallToolResult>;
  188. };
  189. await expect(bridge.call("screenshot", {})).rejects.toThrow(
  190. "Computer Use is not available in subagent",
  191. );
  192. });
  193. it("fails closed after a worker generation changes", async () => {
  194. const active = {
  195. generation: 1,
  196. requestMeta: { runtime_scope: "main" as const, session_id: "session-1" },
  197. signal: new AbortController().signal,
  198. };
  199. const globals = createComputerUseBridgeGlobals({
  200. broker: { socketPath: "/tmp/does-not-exist.sock", token: "token" },
  201. documentationRoot: "/tmp/docs",
  202. generation: 2,
  203. getActiveCall: () => active,
  204. session: () => ({ mergeResponseMeta: () => undefined }) as never,
  205. });
  206. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  207. assertAvailable(): void;
  208. };
  209. expect(() => bridge.assertAvailable()).toThrow("runtime binding is stale");
  210. });
  211. it("rejects a forged broker token", async () => {
  212. broker = createNodeReplCuaBroker({
  213. runtime: {
  214. execute: async () => ({ content: [{ type: "text", text: "should not run" }] }),
  215. closeSession: async () => undefined,
  216. dispose: async () => undefined,
  217. },
  218. platform: process.platform,
  219. });
  220. await broker.ready;
  221. const result = await new Promise<string>((resolve) => {
  222. const socket = createConnection(broker!.connection.socketPath);
  223. let buffer = "";
  224. socket.once("connect", () => {
  225. socket.end(
  226. `${JSON.stringify({
  227. id: "forged",
  228. token: "wrong-token",
  229. method: "screenshot",
  230. input: {},
  231. context: { sessionId: "session-1", workspaceKey: "/workspace" },
  232. })}\n`,
  233. );
  234. });
  235. socket.on("data", (chunk) => {
  236. buffer += chunk.toString("utf8");
  237. if (buffer.includes("\n")) resolve(buffer.trim());
  238. });
  239. socket.once("error", () => resolve(buffer.trim()));
  240. });
  241. expect(result).toContain("not authorized");
  242. });
  243. });