browserControlProtocol.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. browserBackendDescriptorSchema,
  4. browserBackendListResultSchema,
  5. browserCommandSchema,
  6. browserCommandResultSchema,
  7. browserSnapshotSchema,
  8. } from "../src/browser-use/index.js";
  9. import {
  10. zcodeBrowserExecuteParamsSchema,
  11. zcodeBrowserExecuteResultSchema,
  12. zcodeBrowserListParamsSchema,
  13. zcodeBrowserListResultSchema,
  14. zcodeProtocolMethods,
  15. zcodeProtocolSessionMethodContracts,
  16. } from "../src/zcode-protocol/index.js";
  17. const IAB_DESCRIPTOR = {
  18. id: "iab-runtime-1",
  19. generation: 1,
  20. type: "iab" as const,
  21. name: "ZCode In-app Browser",
  22. capabilities: {
  23. browser: [{ id: "visibility", description: "Browser visibility control" }],
  24. tab: [{ id: "cdp", description: "Controlled CDP commands" }],
  25. },
  26. apiSupportOverrides: { "Tabs.finalize": true },
  27. metadata: { buildFlavor: "development" },
  28. };
  29. describe("browser command schema", () => {
  30. it("parses each core method", () => {
  31. expect(browserCommandSchema.parse({ method: "navigate", url: "https://x" }).method).toBe(
  32. "navigate",
  33. );
  34. expect(browserCommandSchema.parse({ method: "snapshot" }).method).toBe("snapshot");
  35. expect(browserCommandSchema.parse({ method: "click", ref: "e1" }).method).toBe("click");
  36. expect(browserCommandSchema.parse({ method: "screenshot" }).method).toBe("screenshot");
  37. expect(browserCommandSchema.parse({ method: "getState" }).method).toBe("getState");
  38. expect(browserCommandSchema.parse({ method: "activateTab", tabId: "t-1" }).method).toBe(
  39. "activateTab",
  40. );
  41. });
  42. it("rejects navigate without url and unknown method and extra keys", () => {
  43. expect(() => browserCommandSchema.parse({ method: "navigate" })).toThrow();
  44. expect(() => browserCommandSchema.parse({ method: "teleport" })).toThrow();
  45. expect(() => browserCommandSchema.parse({ method: "activateTab" })).toThrow();
  46. expect(() => browserCommandSchema.parse({ method: "snapshot", bogus: 1 })).toThrow();
  47. });
  48. // dwf 子代理关闭时连 tab 一起关;桌面中继按这份 schema 校验 params,漏了字段命令就到不了 main。
  49. it("closeSession 接受可选 closeTabs,拒绝非布尔值", () => {
  50. expect(browserCommandSchema.parse({ method: "closeSession" })).toEqual({
  51. method: "closeSession",
  52. });
  53. expect(
  54. zcodeBrowserExecuteParamsSchema.parse({
  55. requestId: "req-close",
  56. sessionId: "sess_dwf-dwfrun-1-actor_1_1",
  57. command: { method: "closeSession", closeTabs: true },
  58. }).command,
  59. ).toEqual({ method: "closeSession", closeTabs: true });
  60. expect(() =>
  61. browserCommandSchema.parse({ method: "closeSession", closeTabs: "yes" }),
  62. ).toThrow();
  63. });
  64. it("parses list method (agent 对象模型 browsers.list)", () => {
  65. const parsed = browserCommandSchema.parse({ method: "list" });
  66. expect(parsed.method).toBe("list");
  67. // list 不带 tabId:作用于会话级别,多余字段被 strict 拒绝。
  68. expect(() => browserCommandSchema.parse({ method: "list", tabId: "t" })).toThrow();
  69. });
  70. it("viewport 与 Playwright Page 参数一致,并对 API 越界直接报错", () => {
  71. expect(
  72. browserCommandSchema.parse({
  73. method: "browserViewportSet",
  74. tabId: "t-1",
  75. width: 375,
  76. height: 667,
  77. }),
  78. ).toEqual({ method: "browserViewportSet", tabId: "t-1", width: 375, height: 667 });
  79. expect(
  80. browserCommandSchema.parse({ method: "browserViewportSet", width: 320, height: 320 }),
  81. ).toMatchObject({ width: 320, height: 320 });
  82. expect(
  83. browserCommandSchema.parse({ method: "browserViewportSet", width: 3840, height: 2160 }),
  84. ).toMatchObject({ width: 3840, height: 2160 });
  85. expect(() =>
  86. browserCommandSchema.parse({ method: "browserViewportSet", width: 319, height: 667 }),
  87. ).toThrow();
  88. expect(() =>
  89. browserCommandSchema.parse({ method: "browserViewportSet", width: 3841, height: 667 }),
  90. ).toThrow();
  91. expect(() =>
  92. browserCommandSchema.parse({ method: "browserViewportSet", width: 375, height: 2161 }),
  93. ).toThrow();
  94. expect(() =>
  95. browserCommandSchema.parse({ method: "browserViewportSet", width: 375.5, height: 667 }),
  96. ).toThrow();
  97. });
  98. it("按协议约定校验 playwrightWaitForTimeout 非负整数", () => {
  99. expect(
  100. browserCommandSchema.parse({
  101. method: "playwrightWaitForTimeout",
  102. timeoutMs: 0,
  103. tabId: "t-1",
  104. }),
  105. ).toEqual({ method: "playwrightWaitForTimeout", timeoutMs: 0, tabId: "t-1" });
  106. expect(() =>
  107. browserCommandSchema.parse({ method: "playwrightWaitForTimeout", timeoutMs: -1 }),
  108. ).toThrow();
  109. expect(() =>
  110. browserCommandSchema.parse({ method: "playwrightWaitForTimeout", timeoutMs: 1.5 }),
  111. ).toThrow();
  112. });
  113. it("严格校验 WebView 异步录制命令、受限动作和时长边界", () => {
  114. expect(
  115. browserCommandSchema.parse({
  116. method: "recordingStart",
  117. tabId: "t-1",
  118. options: {
  119. viewport: { width: 1280, height: 720 },
  120. fps: 25,
  121. jpegQuality: 80,
  122. maxDurationMs: 60_000,
  123. showCursor: true,
  124. actions: [
  125. { type: "wait", durationMs: 500 },
  126. { type: "click", selector: "#start" },
  127. { type: "type", selector: "#name", text: "ZCode" },
  128. { type: "hover", x: 120, y: 80, durationMs: 200 },
  129. { type: "scroll", deltaX: 0, deltaY: 600, durationMs: 800 },
  130. { type: "waitFor", selector: ".done", timeoutMs: 3_000 },
  131. ],
  132. },
  133. }),
  134. ).toMatchObject({ method: "recordingStart", tabId: "t-1" });
  135. expect(
  136. browserCommandSchema.parse({
  137. method: "recordingStatus",
  138. recordingId: "recording-1",
  139. outputPath: "recordings/demo.webm",
  140. }),
  141. ).toMatchObject({ method: "recordingStatus", outputPath: "recordings/demo.webm" });
  142. expect(
  143. browserCommandSchema.parse({ method: "recordingCancel", recordingId: "recording-1" }),
  144. ).toMatchObject({ method: "recordingCancel" });
  145. expect(() =>
  146. browserCommandSchema.parse({
  147. method: "recordingStart",
  148. options: { maxDurationMs: 90_001, actions: [] },
  149. }),
  150. ).toThrow();
  151. expect(() =>
  152. browserCommandSchema.parse({
  153. method: "recordingStart",
  154. options: { actions: [{ type: "eval", script: "document.body.remove()" }] },
  155. }),
  156. ).toThrow();
  157. expect(() =>
  158. browserCommandSchema.parse({
  159. method: "recordingStatus",
  160. recordingId: "recording-1",
  161. outputPath: "../outside.webm",
  162. }),
  163. ).toThrow();
  164. expect(() =>
  165. browserCommandSchema.parse({
  166. method: "recordingStatus",
  167. recordingId: "recording-1",
  168. outputPath: "recordings/legacy.mp4",
  169. }),
  170. ).toThrow();
  171. });
  172. it("严格校验 Playwright page/locator command envelope", () => {
  173. expect(
  174. browserCommandSchema.parse({
  175. method: "playwright",
  176. action: {
  177. name: "locator",
  178. selector: 'internal:role=button[name="Save"i]',
  179. operation: "click",
  180. modifiers: ["ControlOrMeta"],
  181. timeoutMs: 1000,
  182. },
  183. tabId: "t-1",
  184. }),
  185. ).toMatchObject({ method: "playwright", tabId: "t-1" });
  186. expect(() =>
  187. browserCommandSchema.parse({
  188. method: "playwright",
  189. action: { name: "locator", selector: "button", operation: "teleport" },
  190. }),
  191. ).toThrow();
  192. expect(() =>
  193. browserCommandSchema.parse({
  194. method: "playwright",
  195. action: { name: "waitForURL", url: "https://x", timeoutMs: 0 },
  196. }),
  197. ).toThrow();
  198. });
  199. it("严格保留 CUA path、scroll anchor/delta 与组合按键", () => {
  200. expect(
  201. browserCommandSchema.parse({
  202. method: "cuaDrag",
  203. path: [
  204. { x: 1, y: 2 },
  205. { x: 3, y: 4 },
  206. ],
  207. modifiers: ["Shift"],
  208. }),
  209. ).toMatchObject({
  210. method: "cuaDrag",
  211. path: [
  212. { x: 1, y: 2 },
  213. { x: 3, y: 4 },
  214. ],
  215. });
  216. expect(
  217. browserCommandSchema.parse({
  218. method: "cuaScroll",
  219. x: 10,
  220. y: 20,
  221. scrollX: 0,
  222. scrollY: 100,
  223. }),
  224. ).toMatchObject({ method: "cuaScroll", x: 10, y: 20, scrollY: 100 });
  225. expect(
  226. browserCommandSchema.parse({ method: "cuaKeypress", keys: ["ControlOrMeta", "A"] }),
  227. ).toMatchObject({ method: "cuaKeypress", keys: ["ControlOrMeta", "A"] });
  228. expect(() => browserCommandSchema.parse({ method: "cuaDrag", path: [] })).toThrow();
  229. expect(() => browserCommandSchema.parse({ method: "cuaKeypress", keys: [] })).toThrow();
  230. });
  231. it("每个变体接受可选 tabId(协议 tabId 寻址)", () => {
  232. const nav = browserCommandSchema.parse({
  233. method: "navigate",
  234. url: "https://x",
  235. tabId: "t-1",
  236. });
  237. expect(nav.tabId).toBe("t-1");
  238. const state = browserCommandSchema.parse({ method: "getState", tabId: "t-2" });
  239. expect(state.tabId).toBe("t-2");
  240. // 不带 tabId 仍合法(缺省作用于默认 view)。
  241. expect(browserCommandSchema.parse({ method: "getState" }).tabId).toBeUndefined();
  242. });
  243. });
  244. describe("browser command result tabs", () => {
  245. it("round-trips recording job status and artifact without extra fields", () => {
  246. expect(
  247. browserCommandResultSchema.parse({
  248. ok: true,
  249. recording: {
  250. id: "recording-1",
  251. status: "completed",
  252. phase: "completed",
  253. progress: 1,
  254. startedAt: 1,
  255. updatedAt: 2,
  256. artifact: {
  257. path: "recordings/demo.webm",
  258. mimeType: "video/webm",
  259. width: 1280,
  260. height: 720,
  261. fps: 25,
  262. durationMs: 4_000,
  263. frameCount: 100,
  264. },
  265. },
  266. elapsedMs: 1,
  267. }),
  268. ).toMatchObject({
  269. recording: {
  270. status: "completed",
  271. artifact: { path: "recordings/demo.webm", mimeType: "video/webm" },
  272. },
  273. });
  274. });
  275. it("result round-trips list tabs(BrowserTabSummary[])", () => {
  276. const parsed = browserCommandResultSchema.parse({
  277. ok: true,
  278. tabs: [
  279. {
  280. tabId: "t-1",
  281. url: "https://a",
  282. title: "A",
  283. active: true,
  284. viewport: { width: 1280, height: 720 },
  285. },
  286. {
  287. tabId: "t-2",
  288. url: "https://b",
  289. title: "B",
  290. viewport: { width: 375, height: 667 },
  291. },
  292. ],
  293. elapsedMs: 3,
  294. });
  295. expect(parsed.tabs).toHaveLength(2);
  296. expect(parsed.tabs?.[0]).toEqual({
  297. tabId: "t-1",
  298. url: "https://a",
  299. title: "A",
  300. active: true,
  301. viewport: { width: 1280, height: 720 },
  302. });
  303. });
  304. it("拒绝 tabs 内多余字段(strict)", () => {
  305. expect(() =>
  306. browserCommandResultSchema.parse({
  307. ok: true,
  308. tabs: [
  309. {
  310. tabId: "t",
  311. url: "u",
  312. title: "x",
  313. viewport: { width: 1280, height: 720 },
  314. bogus: 1,
  315. },
  316. ],
  317. elapsedMs: 1,
  318. }),
  319. ).toThrow();
  320. });
  321. });
  322. describe("browser DOM snapshot schema", () => {
  323. it("同时保留动作 refs 与有界可见语义 DOM", () => {
  324. const parsed = browserSnapshotSchema.parse({
  325. url: "https://example.com",
  326. title: "Example",
  327. elements: [
  328. {
  329. ref: "e1",
  330. tag: "a",
  331. role: "link",
  332. name: "Details",
  333. selector: "#details",
  334. xpath: "//*[@id='details']",
  335. rect: { x: 1, y: 2, width: 30, height: 10 },
  336. inViewport: true,
  337. attributes: { id: "details", href: "/details", "data-testid": "details-link" },
  338. },
  339. ],
  340. truncated: false,
  341. dom: [
  342. { tag: "h1", depth: 1, inViewport: true, text: "Example heading" },
  343. {
  344. tag: "a",
  345. depth: 2,
  346. inViewport: true,
  347. ref: "e1",
  348. role: "link",
  349. name: "Details",
  350. attributes: { href: "/details" },
  351. },
  352. ],
  353. domTruncated: false,
  354. });
  355. expect(parsed.elements[0]?.ref).toBe("e1");
  356. expect(parsed.dom?.[0]?.text).toBe("Example heading");
  357. expect(parsed.dom?.[1]?.ref).toBe("e1");
  358. expect(JSON.stringify(parsed).indexOf('"dom"')).toBeLessThan(
  359. JSON.stringify(parsed).indexOf('"elements"'),
  360. );
  361. });
  362. it("语义 DOM 节点继续保持 strict", () => {
  363. expect(() =>
  364. browserSnapshotSchema.parse({
  365. url: "https://example.com",
  366. title: "Example",
  367. elements: [],
  368. truncated: false,
  369. dom: [{ tag: "p", depth: 1, inViewport: true, text: "x", unexpected: true }],
  370. }),
  371. ).toThrow();
  372. });
  373. });
  374. describe("browser backend descriptor schema", () => {
  375. it.each(["iab", "extension", "cdp"] as const)("接受 %s backend family", (type) => {
  376. const parsed = browserBackendDescriptorSchema.parse({
  377. ...IAB_DESCRIPTOR,
  378. id: `${type}-runtime-1`,
  379. type,
  380. });
  381. expect(parsed.type).toBe(type);
  382. expect(parsed.id).toBe(`${type}-runtime-1`);
  383. });
  384. it("拒绝把 Playwright 当作 backend,并拒绝 descriptor 多余字段", () => {
  385. expect(() =>
  386. browserBackendDescriptorSchema.parse({ ...IAB_DESCRIPTOR, type: "playwright" }),
  387. ).toThrow();
  388. expect(() =>
  389. browserBackendDescriptorSchema.parse({ ...IAB_DESCRIPTOR, available: true }),
  390. ).toThrow();
  391. });
  392. it("list result round-trips descriptor 数组且保持 strict", () => {
  393. const parsed = browserBackendListResultSchema.parse({ browsers: [IAB_DESCRIPTOR] });
  394. expect(parsed.browsers).toEqual([IAB_DESCRIPTOR]);
  395. expect(() =>
  396. browserBackendListResultSchema.parse({ browsers: [IAB_DESCRIPTOR], stale: [] }),
  397. ).toThrow();
  398. });
  399. });
  400. describe("interaction/browserList protocol", () => {
  401. it("注册严格 method contract", () => {
  402. expect(zcodeProtocolMethods.interactionBrowserList).toBe("interaction/browserList");
  403. const entry = zcodeProtocolSessionMethodContracts[zcodeProtocolMethods.interactionBrowserList];
  404. expect(entry?.params).toBe(zcodeBrowserListParamsSchema);
  405. expect(entry?.result).toBe(zcodeBrowserListResultSchema);
  406. });
  407. it("round-trips 完整 discovery context", () => {
  408. const parsed = zcodeBrowserListParamsSchema.parse({
  409. requestId: "req-list-1",
  410. sessionId: "sess-1",
  411. turnId: "turn-1",
  412. workspaceKey: "ssh://host/repo",
  413. workspacePath: "/repo",
  414. workspaceIdentity: "ssh://host/repo",
  415. remoteSessionId: "remote-1",
  416. clientMode: "web-remote-replayable",
  417. sessionContext: "live",
  418. });
  419. expect(parsed.workspaceKey).toBe("ssh://host/repo");
  420. expect(parsed.clientMode).toBe("web-remote-replayable");
  421. });
  422. it("拒绝缺失隔离 context 或多余字段", () => {
  423. expect(() =>
  424. zcodeBrowserListParamsSchema.parse({
  425. requestId: "req-list-1",
  426. sessionId: "sess-1",
  427. }),
  428. ).toThrow();
  429. expect(() =>
  430. zcodeBrowserListParamsSchema.parse({
  431. requestId: "req-list-1",
  432. sessionId: "sess-1",
  433. workspaceKey: "/repo",
  434. workspacePath: "/repo",
  435. clientMode: "desktop-continuous",
  436. sessionContext: "live",
  437. unexpected: true,
  438. }),
  439. ).toThrow();
  440. });
  441. it("result 使用统一 descriptor list schema", () => {
  442. expect(
  443. zcodeBrowserListResultSchema.parse({ browsers: [IAB_DESCRIPTOR] }).browsers[0]?.type,
  444. ).toBe("iab");
  445. });
  446. });
  447. describe("interaction/browserExecute protocol", () => {
  448. it("registers the method", () => {
  449. expect(zcodeProtocolMethods.interactionBrowserExecute).toBe("interaction/browserExecute");
  450. });
  451. it("has a contract entry with params/result schemas", () => {
  452. const entry =
  453. zcodeProtocolSessionMethodContracts[zcodeProtocolMethods.interactionBrowserExecute];
  454. expect(entry).toBeDefined();
  455. expect(entry?.params).toBeDefined();
  456. expect(entry?.result).toBeDefined();
  457. });
  458. it("params round-trips a navigate command", () => {
  459. const params = {
  460. requestId: "req-1",
  461. sessionId: "sess-1",
  462. command: { method: "navigate", url: "https://example.com" } as const,
  463. };
  464. const parsed = zcodeBrowserExecuteParamsSchema.parse(params);
  465. expect(parsed.command.method).toBe("navigate");
  466. expect(parsed.sessionId).toBe("sess-1");
  467. });
  468. it("params round-trips browserId + workspace/session context", () => {
  469. const parsed = zcodeBrowserExecuteParamsSchema.parse({
  470. requestId: "req-2",
  471. sessionId: "sess-1",
  472. turnId: "turn-1",
  473. browserId: "extension-runtime-3",
  474. workspaceKey: "ssh://host/repo",
  475. workspacePath: "/repo",
  476. workspaceIdentity: "ssh://host/repo",
  477. remoteSessionId: "remote-1",
  478. clientMode: "web-remote-replayable",
  479. sessionContext: "live",
  480. command: { method: "getState" },
  481. });
  482. expect(parsed.browserId).toBe("extension-runtime-3");
  483. expect(parsed.workspaceIdentity).toBe("ssh://host/repo");
  484. expect(parsed.clientMode).toBe("web-remote-replayable");
  485. });
  486. it("兼容旧 execute params,但继续拒绝未知字段", () => {
  487. expect(
  488. zcodeBrowserExecuteParamsSchema.parse({
  489. requestId: "legacy-req",
  490. sessionId: "legacy-session",
  491. command: { method: "getState" },
  492. }).browserId,
  493. ).toBeUndefined();
  494. expect(() =>
  495. zcodeBrowserExecuteParamsSchema.parse({
  496. requestId: "legacy-req",
  497. sessionId: "legacy-session",
  498. command: { method: "getState" },
  499. backend: "iab",
  500. }),
  501. ).toThrow();
  502. });
  503. it("result round-trips ok + image", () => {
  504. const result = {
  505. ok: true,
  506. image: { base64: "iVBOR", mimeType: "image/png" as const },
  507. elapsedMs: 12,
  508. };
  509. const parsed = zcodeBrowserExecuteResultSchema.parse(result);
  510. expect(parsed.ok).toBe(true);
  511. expect(parsed.image?.base64).toBe("iVBOR");
  512. });
  513. it("result round-trips structured error", () => {
  514. const parsed = browserCommandResultSchema.parse({
  515. ok: false,
  516. error: { code: "navigation_blocked", message: "no" },
  517. elapsedMs: 1,
  518. });
  519. expect(parsed.error?.code).toBe("navigation_blocked");
  520. });
  521. it("result round-trips duplicate request id errors", () => {
  522. const parsed = zcodeBrowserExecuteResultSchema.parse({
  523. ok: false,
  524. error: {
  525. code: "duplicate_request_id",
  526. message: "browser requestId 'duplicate' is already running",
  527. sideEffect: "none",
  528. },
  529. elapsedMs: 0,
  530. });
  531. expect(parsed.error).toMatchObject({ code: "duplicate_request_id", sideEffect: "none" });
  532. });
  533. });