cua-bridge.test.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 type { ComputerUseRuntime } from "@zcode/zcode-cua";
  5. import { createComputerUseBridgeGlobals, NODE_REPL_CUA_BRIDGE_SYMBOL } from "../src/cua-bridge.js";
  6. import { createNodeReplCuaBroker, type NodeReplCuaBroker } from "../src/cua-broker.js";
  7. import { createNodeReplCallLedger, type NodeReplCallLedger } from "../src/call-ledger/contract.js";
  8. import { CUA_APP_ASSOCIATIONS_META_KEY } from "@zcode/zcode-cua/host-display-contract";
  9. // broker 只认本次调用的 token,会话信息取自账本条目,目标应用身份记入条目的 facts
  10. // (apps/zcode-cli/docs/design/v2/tool/20-node-repl-call-ledger.md「CUA broker」)。
  11. const fullRequestMeta = {
  12. runtime_scope: "main" as const,
  13. session_id: "session-1",
  14. workspace_path: "/workspace",
  15. workspace_identity: "ssh://host/workspace",
  16. workspace_key: "ssh://host/workspace",
  17. remote_session_id: "remote-1",
  18. turn_id: "turn-1",
  19. client_mode: "web-remote-replayable",
  20. delivery_kind: "web-remote-replayable",
  21. trace_id: "trace-1",
  22. span_id: "span-1",
  23. };
  24. describe("node_repl CUA bridge", () => {
  25. let broker: NodeReplCuaBroker | undefined;
  26. afterEach(async () => {
  27. await broker?.close();
  28. broker = undefined;
  29. });
  30. async function startBroker(
  31. execute: ComputerUseRuntime["execute"],
  32. ): Promise<{ broker: NodeReplCuaBroker; ledger: NodeReplCallLedger }> {
  33. const ledger = createNodeReplCallLedger();
  34. broker = createNodeReplCuaBroker({
  35. runtime: { execute, closeSession: async () => undefined, dispose: async () => undefined },
  36. ledger,
  37. // 不传 platform 时 createNodeReplCuaBroker 会走 POSIX 分支,在 tmpdir 里建
  38. // `znrc-*.sock`;Windows 的 net.Server.listen 只接受命名管道,给文件路径直接
  39. // EACCES,于是这条用例在 Windows 上从来没跑过。产品代码本身是对的(它按
  40. // platform 分支选管道或 unix socket),所以测试必须跑在真实平台上,而不是
  41. // 默默假设 POSIX。
  42. platform: process.platform,
  43. });
  44. await broker.ready;
  45. return { broker, ledger };
  46. }
  47. function bridgeFor(
  48. started: { broker: NodeReplCuaBroker },
  49. token: string,
  50. requestMeta: Record<string, unknown> = fullRequestMeta,
  51. ) {
  52. const active = { generation: 1, requestMeta, signal: new AbortController().signal };
  53. const globals = createComputerUseBridgeGlobals({
  54. broker: { socketPath: started.broker.connection.socketPath, token },
  55. documentationRoot: "/tmp/docs",
  56. generation: 1,
  57. getActiveCall: () => active,
  58. session: () => ({ mergeResponseMeta: () => undefined }) as never,
  59. });
  60. return globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  61. call(method: string, input: unknown): Promise<CallToolResult>;
  62. };
  63. }
  64. /** 绕过 bridge,直接往 broker 的 socket 发一行请求。 */
  65. async function sendRaw(socketPath: string, request: Record<string, unknown>): Promise<string> {
  66. return await new Promise<string>((resolve) => {
  67. const socket = createConnection(socketPath);
  68. let buffer = "";
  69. socket.once("connect", () => socket.end(`${JSON.stringify(request)}\n`));
  70. socket.on("data", (chunk) => {
  71. buffer += chunk.toString("utf8");
  72. if (buffer.includes("\n")) resolve(buffer.trim());
  73. });
  74. socket.once("error", () => resolve(buffer.trim()));
  75. });
  76. }
  77. it("forwards the call's trusted request context to the shared runtime", async () => {
  78. const calls: unknown[] = [];
  79. const started = await startBroker(async (input) => {
  80. calls.push(input);
  81. return {
  82. content: [{ type: "text", text: "ok" }],
  83. structuredContent: { state_id: "state-1" },
  84. } satisfies CallToolResult;
  85. });
  86. const call = started.ledger.open(fullRequestMeta);
  87. await expect(
  88. bridgeFor(started, call.token).call("screenshot", { display_id: 1 }),
  89. ).resolves.toMatchObject({ structuredContent: { state_id: "state-1" } });
  90. expect(calls).toHaveLength(1);
  91. expect(calls[0]).toMatchObject({
  92. toolName: "screenshot",
  93. arguments: { display_id: 1 },
  94. context: {
  95. runtimeScope: "main",
  96. sessionId: "session-1",
  97. workspacePath: "/workspace",
  98. workspaceIdentity: "ssh://host/workspace",
  99. workspaceKey: "ssh://host/workspace",
  100. remoteSessionId: "remote-1",
  101. turnId: "turn-1",
  102. clientMode: "web-remote-replayable",
  103. deliveryKind: "web-remote-replayable",
  104. trace: { traceId: "trace-1", spanId: "span-1" },
  105. },
  106. });
  107. });
  108. it("ignores a context sent by the Worker and uses the call's own", async () => {
  109. // cell 绕过 bridge 时可以自报任意会话;broker 必须只用账本条目里来自 core 的会话信息。
  110. const calls: Array<{ context: Record<string, unknown> }> = [];
  111. const started = await startBroker(async (input) => {
  112. calls.push(input as never);
  113. return { content: [{ type: "text", text: "ok" }] };
  114. });
  115. const call = started.ledger.open(fullRequestMeta);
  116. const response = await sendRaw(started.broker.connection.socketPath, {
  117. id: "direct",
  118. token: call.token,
  119. method: "screenshot",
  120. input: {},
  121. context: { sessionId: "someone-else", runtimeScope: "main", workspaceKey: "/elsewhere" },
  122. });
  123. expect(JSON.parse(response)).toMatchObject({ id: "direct", ok: true });
  124. expect(calls[0]?.context).toMatchObject({
  125. sessionId: "session-1",
  126. workspaceKey: "ssh://host/workspace",
  127. });
  128. });
  129. it("records the target app identity from the broker response in the call's facts", async () => {
  130. // 工具卡的 App 图标只能来自 broker 拿到的 runtime 结果:这一跳在 Worker 之外,cell 改不了。
  131. // producer 自带的内联 icon PNG 不进 run 结果(会话协议不承载 data URL),只保留 appKey/displayName。
  132. const started = await startBroker(
  133. async () =>
  134. ({
  135. content: [{ type: "text", text: "clicked" }],
  136. _meta: {
  137. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  138. schemaVersion: 1,
  139. primary: {
  140. appKey: "darwin:com.apple.notes",
  141. displayName: "Notes",
  142. icon: { mimeType: "image/png", data: "iVBORw0KGgo=" },
  143. },
  144. },
  145. },
  146. }) satisfies CallToolResult,
  147. );
  148. const call = started.ledger.open(fullRequestMeta);
  149. const other = started.ledger.open({ ...fullRequestMeta, session_id: "session-2" });
  150. await bridgeFor(started, call.token).call("left_click", { app_ref: { pid: 1 } });
  151. expect(call.facts.cuaApps).toEqual([{ appKey: "darwin:com.apple.notes", displayName: "Notes" }]);
  152. expect(other.facts.cuaApps).toEqual([]);
  153. });
  154. it("ignores app associations that carry no primary identity", async () => {
  155. // list_apps 声明的是 items 模式,没有 primary;request_access / stop 声明 none。
  156. // 这些调用不能覆盖同一 cell 里前面动作已经确立的身份。
  157. const started = await startBroker(
  158. async () =>
  159. ({
  160. content: [{ type: "text", text: "[]" }],
  161. _meta: {
  162. [CUA_APP_ASSOCIATIONS_META_KEY]: {
  163. schemaVersion: 1,
  164. items: [{ resultIndex: 0, application: { appKey: "darwin:com.apple.finder" } }],
  165. },
  166. },
  167. }) satisfies CallToolResult,
  168. );
  169. const call = started.ledger.open(fullRequestMeta);
  170. // 前提:调用确实到达 broker 并成功返回。
  171. await expect(bridgeFor(started, call.token).call("list_apps", {})).resolves.toMatchObject({
  172. content: [{ type: "text", text: "[]" }],
  173. });
  174. expect(call.facts.cuaApps).toEqual([]);
  175. });
  176. it("rejects subagents before opening the broker", async () => {
  177. const active = {
  178. generation: 1,
  179. requestMeta: { runtime_scope: "subagent" as const, session_id: "subagent-1" },
  180. signal: new AbortController().signal,
  181. };
  182. const globals = createComputerUseBridgeGlobals({
  183. documentationRoot: "/tmp/docs",
  184. generation: 1,
  185. getActiveCall: () => active,
  186. session: () => ({ mergeResponseMeta: () => undefined }) as never,
  187. });
  188. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  189. call(method: string, input: unknown): Promise<CallToolResult>;
  190. };
  191. await expect(bridge.call("screenshot", {})).rejects.toThrow(
  192. "Computer Use is not available in subagent",
  193. );
  194. });
  195. it("rejects a subagent call that bypasses the bridge", async () => {
  196. let executed = 0;
  197. const started = await startBroker(async () => {
  198. executed += 1;
  199. return { content: [{ type: "text", text: "should not run" }] };
  200. });
  201. // 条目来自 core 的 subagent 请求;Worker 自报 main 也不能绕过。
  202. const call = started.ledger.open({ ...fullRequestMeta, runtime_scope: "subagent" });
  203. const response = await sendRaw(started.broker.connection.socketPath, {
  204. id: "direct",
  205. token: call.token,
  206. method: "screenshot",
  207. input: {},
  208. context: { sessionId: "session-1", runtimeScope: "main", workspaceKey: "/workspace" },
  209. });
  210. expect(JSON.parse(response)).toEqual({
  211. id: "direct",
  212. ok: false,
  213. error: "Computer Use is not available in subagent",
  214. });
  215. expect(executed).toBe(0);
  216. });
  217. it("fails closed after a worker generation changes", async () => {
  218. const active = {
  219. generation: 1,
  220. requestMeta: { runtime_scope: "main" as const, session_id: "session-1" },
  221. signal: new AbortController().signal,
  222. };
  223. const globals = createComputerUseBridgeGlobals({
  224. broker: { socketPath: "/tmp/does-not-exist.sock", token: "token" },
  225. documentationRoot: "/tmp/docs",
  226. generation: 2,
  227. getActiveCall: () => active,
  228. session: () => ({ mergeResponseMeta: () => undefined }) as never,
  229. });
  230. const bridge = globals[NODE_REPL_CUA_BRIDGE_SYMBOL] as {
  231. assertAvailable(): void;
  232. };
  233. expect(() => bridge.assertAvailable()).toThrow("runtime binding is stale");
  234. });
  235. it("rejects forged tokens and tokens of closed calls", async () => {
  236. let executed = 0;
  237. const started = await startBroker(async () => {
  238. executed += 1;
  239. return { content: [{ type: "text", text: "should not run" }] };
  240. });
  241. const closed = started.ledger.open(fullRequestMeta);
  242. closed.close();
  243. for (const token of ["wrong-token", closed.token]) {
  244. const response = await sendRaw(started.broker.connection.socketPath, {
  245. id: "forged",
  246. token,
  247. method: "screenshot",
  248. input: {},
  249. });
  250. expect(response).toContain("not authorized");
  251. }
  252. expect(executed).toBe(0);
  253. expect(closed.facts.computerUse).toBe(false);
  254. });
  255. // 会话能力标签 computer_use 的口径是「真实尝试」(session-features-header.md「BUA/CUA 标签的补充规则」):
  256. // 带本次调用 token 的请求到达 broker 就记,broker 侧的拒绝、runtime 的失败都算。
  257. it("records computerUse for every request that reaches the broker, whatever the outcome", async () => {
  258. const started = await startBroker(async (input) => {
  259. if (input.toolName === ("click" as never)) {
  260. throw new Error("Computer Use Helper is not running");
  261. }
  262. return { content: [{ type: "text", text: "no such app" }], isError: true };
  263. });
  264. const failedResult = started.ledger.open(fullRequestMeta);
  265. const thrown = started.ledger.open(fullRequestMeta);
  266. const subagent = started.ledger.open({ ...fullRequestMeta, runtime_scope: "subagent" });
  267. const malformed = started.ledger.open(fullRequestMeta);
  268. const untouched = started.ledger.open(fullRequestMeta);
  269. await expect(
  270. bridgeFor(started, failedResult.token).call("get_app_state", { app: "Nowhere" }),
  271. ).resolves.toMatchObject({ isError: true });
  272. await expect(bridgeFor(started, thrown.token).call("click", {})).rejects.toThrow(
  273. "Computer Use Helper is not running",
  274. );
  275. // 绕过 bridge 的 subagent 请求由 broker 拒绝。
  276. expect(
  277. JSON.parse(
  278. await sendRaw(started.broker.connection.socketPath, {
  279. id: "direct",
  280. token: subagent.token,
  281. method: "screenshot",
  282. input: {},
  283. }),
  284. ),
  285. ).toMatchObject({ ok: false, error: "Computer Use is not available in subagent" });
  286. expect(
  287. JSON.parse(
  288. await sendRaw(started.broker.connection.socketPath, {
  289. id: "direct",
  290. token: malformed.token,
  291. }),
  292. ),
  293. ).toMatchObject({ ok: false, error: "Computer Use broker request is invalid" });
  294. expect(failedResult.facts.computerUse).toBe(true);
  295. expect(thrown.facts.computerUse).toBe(true);
  296. expect(subagent.facts.computerUse).toBe(true);
  297. expect(malformed.facts.computerUse).toBe(true);
  298. expect(untouched.facts.computerUse).toBe(false);
  299. });
  300. it("does not record attempts the Worker-side bridge stops before reaching the broker", async () => {
  301. let executed = 0;
  302. const started = await startBroker(async () => {
  303. executed += 1;
  304. return { content: [{ type: "text", text: "should not run" }] };
  305. });
  306. const bootstrapOnly = started.ledger.open(fullRequestMeta);
  307. const subagentMeta = { ...fullRequestMeta, runtime_scope: "subagent" };
  308. const subagent = started.ledger.open(subagentMeta);
  309. // SDK 引导只调用 assertAvailable,不发请求。
  310. const bootstrapBridge = bridgeFor(started, bootstrapOnly.token) as unknown as {
  311. assertAvailable(): void;
  312. };
  313. bootstrapBridge.assertAvailable();
  314. // subagent 由 Worker 侧 bridge 先拒绝(这条检查保留,见 session-features-header.md)。
  315. await expect(
  316. bridgeFor(started, subagent.token, subagentMeta).call("screenshot", {}),
  317. ).rejects.toThrow("Computer Use is not available in subagent");
  318. expect(executed).toBe(0);
  319. expect(bootstrapOnly.facts.computerUse).toBe(false);
  320. expect(subagent.facts.computerUse).toBe(false);
  321. });
  322. });