browserCommandExecutor.test.ts 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323
  1. import { createContext, runInContext } from "node:vm";
  2. import { describe, expect, it, vi } from "vitest";
  3. import {
  4. executeBrowserCommandOnView,
  5. isAllowedBrowserUrl,
  6. type ControlledView,
  7. } from "../src/main/browserView/browserCommandExecutor.js";
  8. import { normalizePlaywrightTimeout } from "../src/main/browserView/browserPlaywrightTimeout.js";
  9. function makeView(
  10. overrides: Partial<{
  11. cdpSend: (m: string, p?: unknown, sessionId?: string) => Promise<unknown>;
  12. captureViewportScreenshot: NonNullable<ControlledView["captureViewportScreenshot"]>;
  13. executeJavaScript: (script: string) => Promise<unknown>;
  14. getURL: () => string;
  15. normalizeScreenshotToCssPixels: boolean;
  16. resizeScreenshotToCssPixels: NonNullable<ControlledView["resizeScreenshotToCssPixels"]>;
  17. }> = {},
  18. ): ControlledView {
  19. return {
  20. webContents: {
  21. loadURL: vi.fn(async () => {}),
  22. getURL: overrides.getURL ?? (() => "https://example.com"),
  23. getTitle: () => "Example",
  24. canGoBack: () => true,
  25. canGoForward: () => true,
  26. goBack: vi.fn(() => {}),
  27. goForward: vi.fn(() => {}),
  28. reload: vi.fn(() => {}),
  29. executeJavaScript:
  30. overrides.executeJavaScript ??
  31. vi.fn(async () => ({
  32. url: "https://x",
  33. title: "X",
  34. truncated: false,
  35. elements: [
  36. {
  37. ref: "e1",
  38. tag: "button",
  39. selector: "button",
  40. xpath: "/button",
  41. rect: { x: 0, y: 0, width: 10, height: 10 },
  42. inViewport: true,
  43. },
  44. ],
  45. dom: [
  46. { tag: "h1", depth: 1, inViewport: true, text: "Example heading" },
  47. {
  48. tag: "p",
  49. depth: 2,
  50. inViewport: true,
  51. text: "Readable paragraph",
  52. },
  53. ],
  54. domTruncated: false,
  55. })),
  56. },
  57. cdp: {
  58. send: overrides.cdpSend ?? vi.fn(async () => ({ data: "iVBORw0KGgo=" })),
  59. },
  60. normalizeScreenshotToCssPixels: overrides.normalizeScreenshotToCssPixels,
  61. resizeScreenshotToCssPixels: overrides.resizeScreenshotToCssPixels,
  62. captureViewportScreenshot: overrides.captureViewportScreenshot,
  63. };
  64. }
  65. function pngHeaderData(width: number, height: number, marker = 0): string {
  66. const header = Buffer.alloc(25);
  67. Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(header);
  68. header.writeUInt32BE(13, 8);
  69. header.write("IHDR", 12, "ascii");
  70. header.writeUInt32BE(width, 16);
  71. header.writeUInt32BE(height, 20);
  72. header[24] = marker;
  73. return header.toString("base64");
  74. }
  75. describe("isAllowedBrowserUrl", () => {
  76. it("allows about/http/https, blocks others", () => {
  77. expect(isAllowedBrowserUrl("https://x.com")).toBe(true);
  78. expect(isAllowedBrowserUrl("http://localhost:3000")).toBe(true);
  79. expect(isAllowedBrowserUrl("about:blank")).toBe(true);
  80. expect(isAllowedBrowserUrl("about:srcdoc")).toBe(false);
  81. expect(isAllowedBrowserUrl("about:config")).toBe(false);
  82. expect(isAllowedBrowserUrl("data:text/html,hello")).toBe(false);
  83. expect(isAllowedBrowserUrl("javascript:alert(1)")).toBe(false);
  84. expect(isAllowedBrowserUrl("file:///etc/passwd")).toBe(false);
  85. });
  86. });
  87. describe("executeBrowserCommandOnView", () => {
  88. it("navigate calls loadURL for allowed urls and returns state", async () => {
  89. const view = makeView();
  90. const r = await executeBrowserCommandOnView(view, {
  91. method: "navigate",
  92. url: "https://example.com",
  93. });
  94. expect(view.webContents.loadURL).toHaveBeenCalledWith(
  95. "https://example.com",
  96. );
  97. expect(r.ok).toBe(true);
  98. expect(r.state?.url).toBe("https://example.com");
  99. });
  100. it("navigate blocks javascript: without calling loadURL", async () => {
  101. const view = makeView();
  102. const r = await executeBrowserCommandOnView(view, {
  103. method: "navigate",
  104. url: "javascript:alert(1)",
  105. });
  106. expect(view.webContents.loadURL).not.toHaveBeenCalled();
  107. expect(r.ok).toBe(false);
  108. expect(r.error?.code).toBe("navigation_blocked");
  109. });
  110. it("navigate 在 loadURL 永不 resolve 时返回结构化 timeout,不能伪造成功", async () => {
  111. const view = makeView();
  112. view.webContents.loadURL = vi.fn(() => new Promise<void>(() => {})); // 永不 resolve
  113. const r = await executeBrowserCommandOnView(
  114. view,
  115. { method: "navigate", url: "https://example.com" },
  116. { navigateSettleMs: 10 },
  117. );
  118. expect(view.webContents.loadURL).toHaveBeenCalledWith(
  119. "https://example.com",
  120. );
  121. expect(r).toMatchObject({
  122. ok: false,
  123. error: { code: "timeout", sideEffect: "uncertain" },
  124. });
  125. });
  126. it("navigate 透传 loadURL reject 为结构化 execution_error", async () => {
  127. const view = makeView();
  128. view.webContents.loadURL = vi.fn(async () => {
  129. throw Object.assign(new Error("ERR_CONNECTION_RESET"), {
  130. code: "ERR_CONNECTION_RESET",
  131. });
  132. });
  133. const r = await executeBrowserCommandOnView(
  134. view,
  135. { method: "navigate", url: "https://example.com" },
  136. { navigateSettleMs: 5_000 },
  137. );
  138. expect(r).toMatchObject({
  139. ok: false,
  140. error: {
  141. code: "execution_error",
  142. message: "ERR_CONNECTION_RESET",
  143. sideEffect: "uncertain",
  144. },
  145. });
  146. });
  147. it("navigate 将已提交到等价移动域名的 ERR_ABORTED 识别为成功", async () => {
  148. let currentUrl = "https://www.ituring.com.cn/";
  149. const view = makeView({
  150. getURL: () => currentUrl,
  151. executeJavaScript: vi.fn(async () => ({
  152. href: currentUrl,
  153. readyState: "complete",
  154. })),
  155. });
  156. view.webContents.loadURL = vi.fn(async () => {
  157. currentUrl = "https://m.ituring.com.cn/search?q=Skill";
  158. throw Object.assign(
  159. new Error(
  160. "ERR_ABORTED (-3) loading 'https://m.ituring.com.cn/search?q=Skill'",
  161. ),
  162. { code: "ERR_ABORTED", errno: -3 },
  163. );
  164. });
  165. const result = await executeBrowserCommandOnView(view, {
  166. method: "navigate",
  167. url: "https://www.ituring.com.cn/search?q=Skill",
  168. });
  169. expect(result).toMatchObject({
  170. ok: true,
  171. state: { url: "https://m.ituring.com.cn/search?q=Skill" },
  172. });
  173. });
  174. it("navigate 不吞掉仍停在旧 document 的 ERR_ABORTED", async () => {
  175. vi.useFakeTimers();
  176. try {
  177. const view = makeView({
  178. getURL: () => "https://example.com/old",
  179. executeJavaScript: vi.fn(async () => ({
  180. href: "https://example.com/old",
  181. readyState: "complete",
  182. })),
  183. });
  184. view.webContents.loadURL = vi.fn(async () => {
  185. throw Object.assign(new Error("ERR_ABORTED"), { code: "ERR_ABORTED" });
  186. });
  187. const pending = executeBrowserCommandOnView(view, {
  188. method: "navigate",
  189. url: "https://example.com/new",
  190. });
  191. await vi.advanceTimersByTimeAsync(525);
  192. await expect(pending).resolves.toMatchObject({
  193. ok: false,
  194. error: { code: "execution_error", sideEffect: "uncertain" },
  195. });
  196. } finally {
  197. vi.useRealTimers();
  198. }
  199. });
  200. it("screenshot uses CDP Page.captureScreenshot and returns base64", async () => {
  201. const send = vi.fn(async () => ({ data: "PNGDATA" }));
  202. const view = makeView({ cdpSend: send });
  203. const r = await executeBrowserCommandOnView(view, { method: "screenshot" });
  204. expect(send).toHaveBeenCalledWith("Page.captureScreenshot", {
  205. format: "png",
  206. captureBeyondViewport: false,
  207. });
  208. expect(r.ok).toBe(true);
  209. expect(r.image?.base64).toBe("PNGDATA");
  210. expect(r.image?.mimeType).toBe("image/png");
  211. });
  212. it("viewport screenshot 优先使用宿主已合成的 guest surface", async () => {
  213. const send = vi.fn(async () => ({ data: "CDP_TILED" }));
  214. const captureViewportScreenshot = vi.fn(async () => "SURFACE_OK");
  215. const view = makeView({ cdpSend: send, captureViewportScreenshot });
  216. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  217. expect(result).toMatchObject({
  218. ok: true,
  219. image: { base64: "SURFACE_OK", mimeType: "image/png" },
  220. });
  221. expect(captureViewportScreenshot).toHaveBeenCalledOnce();
  222. expect(send).not.toHaveBeenCalled();
  223. });
  224. it("clip screenshot 不复用仅覆盖 viewport 的 guest surface", async () => {
  225. const send = vi.fn(async () => ({ data: "CLIP_OK" }));
  226. const captureViewportScreenshot = vi.fn(async () => "SURFACE_ONLY");
  227. const view = makeView({ cdpSend: send, captureViewportScreenshot });
  228. const result = await executeBrowserCommandOnView(view, {
  229. method: "screenshot",
  230. clip: { x: 10, y: 20, width: 30, height: 40 },
  231. });
  232. expect(result.image?.base64).toBe("CLIP_OK");
  233. expect(captureViewportScreenshot).not.toHaveBeenCalled();
  234. expect(send).toHaveBeenCalledWith("Page.captureScreenshot", {
  235. format: "png",
  236. captureBeyondViewport: true,
  237. clip: { x: 10, y: 20, width: 30, height: 40, scale: 1 },
  238. });
  239. });
  240. it("responsive screenshot starts at CSS 1x instead of pre-scaling from Retina metrics", async () => {
  241. const expectedImage = pngHeaderData(1440, 900);
  242. const send = vi.fn(async (method: string) => {
  243. if (method === "Page.getLayoutMetrics") {
  244. return {
  245. visualViewport: { pageX: 0, pageY: 0, clientWidth: 2880, clientHeight: 1800 },
  246. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 1440, clientHeight: 900 },
  247. };
  248. }
  249. return { data: expectedImage };
  250. });
  251. const view = makeView({ cdpSend: send, normalizeScreenshotToCssPixels: true });
  252. const r = await executeBrowserCommandOnView(view, { method: "screenshot" });
  253. expect(r.ok).toBe(true);
  254. expect(r.image?.base64).toBe(expectedImage);
  255. expect(send).toHaveBeenNthCalledWith(1, "Page.getLayoutMetrics");
  256. expect(send).toHaveBeenNthCalledWith(2, "Page.captureScreenshot", {
  257. format: "png",
  258. captureBeyondViewport: false,
  259. clip: { x: 0, y: 0, width: 1440, height: 900, scale: 1 },
  260. });
  261. expect(send).toHaveBeenCalledTimes(2);
  262. });
  263. it("supersamples a size-correct low-detail raster using the dynamic CSS target", async () => {
  264. const lowDetailImage = pngHeaderData(1280, 720, 1);
  265. const highResolutionImage = pngHeaderData(2560, 1440, 2);
  266. const sharpCssImage = pngHeaderData(1280, 720, 3);
  267. let captureCount = 0;
  268. const send = vi.fn(async (method: string) => {
  269. if (method === "Page.getLayoutMetrics") {
  270. return {
  271. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 1280, clientHeight: 720 },
  272. };
  273. }
  274. captureCount += 1;
  275. return { data: captureCount === 1 ? lowDetailImage : highResolutionImage };
  276. });
  277. const resizeScreenshotToCssPixels = vi.fn(() => sharpCssImage);
  278. const view = makeView({
  279. cdpSend: send,
  280. normalizeScreenshotToCssPixels: true,
  281. resizeScreenshotToCssPixels,
  282. });
  283. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  284. expect(result).toMatchObject({
  285. ok: true,
  286. image: { base64: sharpCssImage, mimeType: "image/png" },
  287. });
  288. expect(send).toHaveBeenNthCalledWith(2, "Page.captureScreenshot", {
  289. format: "png",
  290. captureBeyondViewport: false,
  291. clip: { x: 0, y: 0, width: 1280, height: 720, scale: 1 },
  292. });
  293. expect(send).toHaveBeenNthCalledWith(3, "Page.captureScreenshot", {
  294. format: "png",
  295. captureBeyondViewport: false,
  296. clip: { x: 0, y: 0, width: 1280, height: 720, scale: 2 },
  297. });
  298. expect(resizeScreenshotToCssPixels).toHaveBeenCalledWith(highResolutionImage, {
  299. width: 1280,
  300. height: 720,
  301. });
  302. });
  303. it("does not supersample a large dynamic target when the bounded quality gain is too small", async () => {
  304. const expectedImage = pngHeaderData(3840, 2160, 1);
  305. const send = vi.fn(async (method: string) => {
  306. if (method === "Page.getLayoutMetrics") {
  307. return {
  308. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 3840, clientHeight: 2160 },
  309. };
  310. }
  311. return { data: expectedImage };
  312. });
  313. const view = makeView({
  314. cdpSend: send,
  315. normalizeScreenshotToCssPixels: true,
  316. resizeScreenshotToCssPixels: vi.fn(),
  317. });
  318. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  319. expect(result).toMatchObject({
  320. ok: true,
  321. image: { base64: expectedImage, mimeType: "image/png" },
  322. });
  323. expect(send).toHaveBeenCalledTimes(2);
  324. expect(view.resizeScreenshotToCssPixels).not.toHaveBeenCalled();
  325. });
  326. it("derives a non-integer supersample scale from the current target instead of fixed dimensions", async () => {
  327. const lowDetailImage = pngHeaderData(3000, 1000, 1);
  328. const highResolutionImage = pngHeaderData(4096, 1365, 2);
  329. const sharpCssImage = pngHeaderData(3000, 1000, 3);
  330. let captureCount = 0;
  331. const send = vi.fn(async (method: string) => {
  332. if (method === "Page.getLayoutMetrics") {
  333. return {
  334. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 3000, clientHeight: 1000 },
  335. };
  336. }
  337. captureCount += 1;
  338. return { data: captureCount === 1 ? lowDetailImage : highResolutionImage };
  339. });
  340. const resizeScreenshotToCssPixels = vi.fn(() => sharpCssImage);
  341. const view = makeView({
  342. cdpSend: send,
  343. normalizeScreenshotToCssPixels: true,
  344. resizeScreenshotToCssPixels,
  345. });
  346. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  347. expect(result.image?.base64).toBe(sharpCssImage);
  348. const secondCapture = send.mock.calls[2];
  349. expect(secondCapture?.[0]).toBe("Page.captureScreenshot");
  350. expect((secondCapture![1] as { clip: { scale: number } }).clip.scale).toBeCloseTo(
  351. 4096 / 3000,
  352. );
  353. expect(resizeScreenshotToCssPixels).toHaveBeenCalledWith(highResolutionImage, {
  354. width: 3000,
  355. height: 1000,
  356. });
  357. });
  358. it("corrects an undersized Retina screenshot only after observing its PNG dimensions", async () => {
  359. const undersizedImage = pngHeaderData(640, 360, 1);
  360. const correctedImage = pngHeaderData(1280, 720, 2);
  361. let captureCount = 0;
  362. const send = vi.fn(async (method: string) => {
  363. if (method === "Page.getLayoutMetrics") {
  364. return {
  365. visualViewport: { pageX: 0, pageY: 0, clientWidth: 2560, clientHeight: 1440 },
  366. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 1280, clientHeight: 720 },
  367. };
  368. }
  369. captureCount += 1;
  370. return { data: captureCount === 1 ? undersizedImage : correctedImage };
  371. });
  372. const view = makeView({ cdpSend: send, normalizeScreenshotToCssPixels: true });
  373. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  374. expect(result).toMatchObject({
  375. ok: true,
  376. image: { base64: correctedImage, mimeType: "image/png" },
  377. });
  378. expect(send).toHaveBeenNthCalledWith(2, "Page.captureScreenshot", {
  379. format: "png",
  380. captureBeyondViewport: false,
  381. clip: { x: 0, y: 0, width: 1280, height: 720, scale: 1 },
  382. });
  383. expect(send).toHaveBeenNthCalledWith(3, "Page.captureScreenshot", {
  384. format: "png",
  385. captureBeyondViewport: false,
  386. clip: { x: 0, y: 0, width: 1280, height: 720, scale: 2 },
  387. });
  388. });
  389. it("downsamples an oversized raster to the dynamic CSS target without fractional CDP capture", async () => {
  390. const oversizedImage = pngHeaderData(2057, 1370, 1);
  391. const resizedImage = pngHeaderData(1371, 913, 2);
  392. const send = vi.fn(async (method: string) => {
  393. if (method === "Page.getLayoutMetrics") {
  394. return {
  395. visualViewport: { pageX: 0, pageY: 0, clientWidth: 2057, clientHeight: 1370 },
  396. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 1371, clientHeight: 913 },
  397. };
  398. }
  399. return { data: oversizedImage };
  400. });
  401. const resizeScreenshotToCssPixels = vi.fn(() => resizedImage);
  402. const view = makeView({
  403. cdpSend: send,
  404. normalizeScreenshotToCssPixels: true,
  405. resizeScreenshotToCssPixels,
  406. });
  407. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  408. expect(result).toMatchObject({
  409. ok: true,
  410. image: { base64: resizedImage, mimeType: "image/png" },
  411. });
  412. expect(send).toHaveBeenNthCalledWith(2, "Page.captureScreenshot", {
  413. format: "png",
  414. captureBeyondViewport: false,
  415. clip: { x: 0, y: 0, width: 1371, height: 913, scale: 1 },
  416. });
  417. expect(send).toHaveBeenCalledTimes(2);
  418. expect(resizeScreenshotToCssPixels).toHaveBeenCalledWith(oversizedImage, {
  419. width: 1371,
  420. height: 913,
  421. });
  422. });
  423. it("keeps the high-resolution first raster when host downsampling fails", async () => {
  424. const oversizedImage = pngHeaderData(1800, 1200, 1);
  425. const send = vi.fn(async (method: string) => {
  426. if (method === "Page.getLayoutMetrics") {
  427. return {
  428. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 900, clientHeight: 600 },
  429. };
  430. }
  431. return { data: oversizedImage };
  432. });
  433. const view = makeView({
  434. cdpSend: send,
  435. normalizeScreenshotToCssPixels: true,
  436. resizeScreenshotToCssPixels: vi.fn(() => undefined),
  437. });
  438. const result = await executeBrowserCommandOnView(view, { method: "screenshot" });
  439. expect(result).toMatchObject({
  440. ok: true,
  441. image: { base64: oversizedImage, mimeType: "image/png" },
  442. });
  443. expect(send).toHaveBeenCalledTimes(2);
  444. });
  445. it("screenshot fails structured when CDP returns no data", async () => {
  446. const view = makeView({ cdpSend: vi.fn(async () => ({})) });
  447. const r = await executeBrowserCommandOnView(view, { method: "screenshot" });
  448. expect(r.ok).toBe(false);
  449. expect(r.error?.code).toBe("execution_error");
  450. });
  451. it("getState reads webContents getters", async () => {
  452. const view = makeView();
  453. const r = await executeBrowserCommandOnView(view, { method: "getState" });
  454. expect(r.ok).toBe(true);
  455. expect(r.state?.title).toBe("Example");
  456. });
  457. it("unimplemented method returns capability_unsupported", async () => {
  458. const view = makeView();
  459. // fill 仍未实现(click/type/press/scroll 已在 T-B/T-C 实现)。
  460. const r = await executeBrowserCommandOnView(view, {
  461. method: "fill",
  462. ref: "e1",
  463. value: "x",
  464. });
  465. expect(r.ok).toBe(false);
  466. expect(r.error?.code).toBe("capability_unsupported");
  467. });
  468. it("snapshot 注入脚本并返回 ok + result.snapshot(ref=e1)", async () => {
  469. const view = makeView();
  470. const r = await executeBrowserCommandOnView(view, { method: "snapshot" });
  471. expect(view.webContents.executeJavaScript).toHaveBeenCalledTimes(1);
  472. // 传入的应是包含 __zcodeRefs 的注入脚本字符串。
  473. const script = (
  474. view.webContents.executeJavaScript as ReturnType<typeof vi.fn>
  475. ).mock.calls[0][0];
  476. expect(typeof script).toBe("string");
  477. expect(script).toContain("__zcodeRefs");
  478. expect(script).toContain("DOM_SEL");
  479. expect(script).toContain("domTruncated");
  480. expect(r.ok).toBe(true);
  481. expect(r.snapshot?.elements[0]?.ref).toBe("e1");
  482. expect(r.snapshot?.dom?.[0]).toMatchObject({
  483. tag: "h1",
  484. text: "Example heading",
  485. });
  486. expect(r.snapshot?.url).toBe("https://x");
  487. });
  488. it("snapshot 在 executeJavaScript 抛错时结构化为 execution_error", async () => {
  489. const view = makeView({
  490. executeJavaScript: vi.fn(async () => {
  491. throw new Error("script boom");
  492. }),
  493. });
  494. const r = await executeBrowserCommandOnView(view, { method: "snapshot" });
  495. expect(r.ok).toBe(false);
  496. expect(r.error?.code).toBe("execution_error");
  497. expect(r.error?.message).toContain("script boom");
  498. });
  499. it("playwright locator query 使用 isolated Playwright runtime,不执行页面 main-world JS", async () => {
  500. const executeJavaScript = vi.fn();
  501. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  502. if (method === "Page.getFrameTree")
  503. return { frameTree: { frame: { id: "main" } } };
  504. if (method === "Page.createIsolatedWorld")
  505. return { executionContextId: 1 };
  506. if (method === "Runtime.evaluate") {
  507. const expression = String(
  508. (params as { expression?: unknown }).expression ?? "",
  509. );
  510. if (expression.startsWith("Boolean(globalThis."))
  511. return { result: { value: true } };
  512. expect(expression).toContain("injected.querySelectorAll");
  513. expect(expression).toContain("internal:role=button");
  514. expect(expression).not.toContain(
  515. "querySelectorStrictWithVisibleFallback",
  516. );
  517. return { result: { value: 2 } };
  518. }
  519. return {};
  520. });
  521. const r = await executeBrowserCommandOnView(
  522. makeView({ executeJavaScript, cdpSend }),
  523. {
  524. method: "playwright",
  525. action: {
  526. name: "locator",
  527. selector: 'internal:role=button[name="Save"i]',
  528. operation: "count",
  529. },
  530. },
  531. );
  532. expect(r).toMatchObject({ ok: true, value: 2 });
  533. expect(executeJavaScript).not.toHaveBeenCalled();
  534. });
  535. it("playwright locator click 通过 CDP Input 产生可信输入", async () => {
  536. let actionabilityExpression = "";
  537. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  538. if (method === "Page.getFrameTree")
  539. return { frameTree: { frame: { id: "main" } } };
  540. if (method === "Page.createIsolatedWorld")
  541. return { executionContextId: 1 };
  542. if (method === "Runtime.evaluate") {
  543. const expression = String(
  544. (params as { expression?: unknown }).expression ?? "",
  545. );
  546. if (expression.startsWith("Boolean(globalThis."))
  547. return { result: { value: true } };
  548. if (expression.includes("const checkStates"))
  549. actionabilityExpression = expression;
  550. return {
  551. result: { value: { count: 1, actionable: true, x: 10, y: 20 } },
  552. };
  553. }
  554. return {};
  555. });
  556. const view = makeView({ cdpSend });
  557. const r = await executeBrowserCommandOnView(view, {
  558. method: "playwright",
  559. action: {
  560. name: "locator",
  561. selector: "button",
  562. operation: "click",
  563. timeoutMs: 100,
  564. },
  565. });
  566. expect(r.ok).toBe(true);
  567. expect(actionabilityExpression).toContain("requestAnimationFrame");
  568. expect(actionabilityExpression).toContain("stableFrames < 2");
  569. expect(actionabilityExpression).toContain("injected.expectHitTarget");
  570. expect(cdpSend).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  571. type: "mousePressed",
  572. x: 10,
  573. y: 20,
  574. button: "left",
  575. clickCount: 1,
  576. });
  577. });
  578. it("locator.downloadMedia 在 isolated world 提取 URL,不降级为普通 click", async () => {
  579. const expressions: string[] = [];
  580. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  581. if (method === "Page.getFrameTree")
  582. return { frameTree: { frame: { id: "main" } } };
  583. if (method === "Page.createIsolatedWorld")
  584. return { executionContextId: 1 };
  585. if (method === "Runtime.evaluate") {
  586. const expression = String(
  587. (params as { expression?: unknown }).expression ?? "",
  588. );
  589. expressions.push(expression);
  590. if (expression.startsWith("Boolean(globalThis."))
  591. return { result: { value: true } };
  592. if (expression.includes("actionability")) {
  593. return {
  594. result: { value: { count: 1, actionable: true, x: 10, y: 20 } },
  595. };
  596. }
  597. if (
  598. expression.includes(
  599. "Matched element does not expose a downloadable URL",
  600. )
  601. ) {
  602. return { result: { value: true } };
  603. }
  604. return {
  605. result: { value: { count: 1, actionable: true, x: 10, y: 20 } },
  606. };
  607. }
  608. return {};
  609. });
  610. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  611. method: "playwright",
  612. action: { name: "locator", selector: "img", operation: "downloadMedia" },
  613. });
  614. expect(result.ok).toBe(true);
  615. expect(
  616. expressions.some((expression) =>
  617. expression.includes('document.createElement("a")'),
  618. ),
  619. ).toBe(true);
  620. expect(cdpSend).not.toHaveBeenCalledWith(
  621. "Input.dispatchMouseEvent",
  622. expect.objectContaining({ type: "mousePressed" }),
  623. );
  624. });
  625. it("playwright locator 缺失时把超长显式 timeout 截断到 3000ms", async () => {
  626. vi.useFakeTimers();
  627. try {
  628. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  629. if (method === "Page.getFrameTree")
  630. return { frameTree: { frame: { id: "main" } } };
  631. if (method === "Page.createIsolatedWorld")
  632. return { executionContextId: 1 };
  633. if (method === "Runtime.evaluate") {
  634. const expression = String(
  635. (params as { expression?: unknown }).expression ?? "",
  636. );
  637. if (expression.startsWith("Boolean(globalThis."))
  638. return { result: { value: true } };
  639. return { result: { value: { count: 0, actionable: false } } };
  640. }
  641. return {};
  642. });
  643. const pending = executeBrowserCommandOnView(makeView({ cdpSend }), {
  644. method: "playwright",
  645. action: {
  646. name: "locator",
  647. selector: "#missing",
  648. operation: "fill",
  649. timeoutMs: 30_000,
  650. },
  651. });
  652. await vi.advanceTimersByTimeAsync(3_000);
  653. await expect(pending).resolves.toMatchObject({
  654. ok: false,
  655. elapsedMs: 3_000,
  656. error: {
  657. code: "timeout",
  658. message: expect.stringContaining("Do not retry the same locator"),
  659. },
  660. });
  661. } finally {
  662. vi.useRealTimers();
  663. }
  664. });
  665. it("playwright fill 不等待 stable 且不检查 hit-target", async () => {
  666. let actionabilityExpression = "";
  667. let fillExpression = "";
  668. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  669. if (method === "Page.getFrameTree")
  670. return { frameTree: { frame: { id: "main" } } };
  671. if (method === "Page.createIsolatedWorld")
  672. return { executionContextId: 1 };
  673. if (method === "Runtime.evaluate") {
  674. const expression = String(
  675. (params as { expression?: unknown }).expression ?? "",
  676. );
  677. if (expression.startsWith("Boolean(globalThis."))
  678. return { result: { value: true } };
  679. if (expression.includes("const checkStates")) {
  680. actionabilityExpression = expression;
  681. return { result: { value: { count: 1, actionable: true } } };
  682. }
  683. if (expression.includes("injected.fill")) {
  684. fillExpression = expression;
  685. return { result: { value: "done" } };
  686. }
  687. }
  688. return {};
  689. });
  690. await expect(
  691. executeBrowserCommandOnView(makeView({ cdpSend }), {
  692. method: "playwright",
  693. action: {
  694. name: "locator",
  695. selector: "textarea",
  696. operation: "fill",
  697. value: "hello",
  698. },
  699. }),
  700. ).resolves.toMatchObject({ ok: true });
  701. expect(actionabilityExpression).toContain("if (false) {");
  702. expect(actionabilityExpression).toContain('stateNames.push("editable")');
  703. expect(actionabilityExpression).toContain(
  704. "if (!false) return { count: 1, actionable: true, checked }",
  705. );
  706. for (const expression of [actionabilityExpression, fillExpression]) {
  707. expect(expression).toContain("querySelectorStrictWithVisibleFallback");
  708. expect(expression).toContain(
  709. "if (visibleMatches.length === 1) return visibleMatches[0]",
  710. );
  711. expect(expression).toContain(
  712. "throw injected.strictModeViolationError(parsedSelector, matches)",
  713. );
  714. }
  715. });
  716. it("playwright fill needsinput 使用同一 locator token 的 virtual paste", async () => {
  717. const expressions: string[] = [];
  718. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  719. if (method === "Page.getFrameTree")
  720. return { frameTree: { frame: { id: "main" } } };
  721. if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
  722. if (method === "Runtime.evaluate") {
  723. const options = params as { expression?: string; returnByValue?: boolean };
  724. const expression = options.expression ?? "";
  725. expressions.push(expression);
  726. if (expression.startsWith("Boolean(globalThis."))
  727. return { result: { value: true } };
  728. if (expression.includes("const checkStates"))
  729. return { result: { value: { count: 1, actionable: true } } };
  730. if (expression.includes("injected.fill"))
  731. return { result: { value: "needsinput" } };
  732. if (options.returnByValue === false) return { result: { value: null } };
  733. if (expression.includes("const pageFunction = async"))
  734. return { result: { value: { ok: true, data: {} } } };
  735. }
  736. return {};
  737. });
  738. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  739. method: "playwright",
  740. action: {
  741. name: "locator",
  742. selector: "textarea",
  743. operation: "fill",
  744. value: "hello",
  745. },
  746. });
  747. expect(result.ok).toBe(true);
  748. const fillExpression = expressions.find((expression) => expression.includes("injected.fill"));
  749. const pasteExpression = expressions.find((expression) =>
  750. expression.includes("const pageFunction = async"),
  751. );
  752. expect(fillExpression).toContain("__zcodeIabInputTargetToken");
  753. expect(pasteExpression).toContain("__zcodeIabInputTargetToken");
  754. expect(cdpSend).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
  755. });
  756. it("playwright fill 在 locator token 漂移后明确失败且不回退 Input.insertText", async () => {
  757. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  758. if (method === "Page.getFrameTree")
  759. return { frameTree: { frame: { id: "main" } } };
  760. if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
  761. if (method === "Runtime.evaluate") {
  762. const options = params as { expression?: string; returnByValue?: boolean };
  763. const expression = options.expression ?? "";
  764. if (expression.startsWith("Boolean(globalThis."))
  765. return { result: { value: true } };
  766. if (expression.includes("const checkStates"))
  767. return { result: { value: { count: 1, actionable: true } } };
  768. if (expression.includes("injected.fill"))
  769. return { result: { value: "needsinput" } };
  770. if (options.returnByValue === false) return { result: { value: null } };
  771. if (expression.includes("const pageFunction = async")) {
  772. return {
  773. result: {
  774. value: {
  775. ok: false,
  776. error: "Active element is no longer the expected input target",
  777. },
  778. },
  779. };
  780. }
  781. }
  782. return {};
  783. });
  784. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  785. method: "playwright",
  786. action: {
  787. name: "locator",
  788. selector: "textarea",
  789. operation: "fill",
  790. value: "must-not-leak",
  791. },
  792. });
  793. expect(result).toMatchObject({
  794. ok: false,
  795. error: {
  796. code: "execution_error",
  797. message: expect.stringContaining("Active element is no longer the expected input target"),
  798. },
  799. });
  800. expect(cdpSend).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
  801. });
  802. it("playwright press 在下发 CDP key 前校验 locator input token", async () => {
  803. const expressions: string[] = [];
  804. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  805. if (method === "Page.getFrameTree")
  806. return { frameTree: { frame: { id: "main" } } };
  807. if (method === "Page.createIsolatedWorld") return { executionContextId: 1 };
  808. if (method === "Runtime.evaluate") {
  809. const expression = String((params as { expression?: unknown }).expression ?? "");
  810. expressions.push(expression);
  811. if (expression.startsWith("Boolean(globalThis."))
  812. return { result: { value: true } };
  813. if (expression.includes("const checkStates"))
  814. return { result: { value: { count: 1, actionable: true } } };
  815. if (expression.includes("Object.defineProperty(element"))
  816. return { result: { value: "done" } };
  817. if (expression.includes("deepestActiveElement(document)"))
  818. return { result: { value: true } };
  819. }
  820. return {};
  821. });
  822. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  823. method: "playwright",
  824. action: { name: "locator", selector: "textarea", operation: "press", value: "Enter" },
  825. });
  826. expect(result.ok).toBe(true);
  827. expect(expressions.some((expression) => expression.includes("__zcodeIabInputTargetToken"))).toBe(
  828. true,
  829. );
  830. expect(cdpSend).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
  831. type: "keyDown",
  832. key: "Enter",
  833. code: "Enter",
  834. windowsVirtualKeyCode: 13,
  835. });
  836. });
  837. it("playwright 单元素 action 在多匹配时选择唯一 visible 元素", async () => {
  838. const fillTargets: string[] = [];
  839. const element = (id: string, visible: boolean) => ({
  840. id,
  841. isConnected: true,
  842. visible,
  843. scrollIntoView: vi.fn(),
  844. getBoundingClientRect: () => ({
  845. bottom: 20,
  846. height: 10,
  847. left: 10,
  848. right: 30,
  849. top: 10,
  850. width: 20,
  851. }),
  852. ownerDocument: {
  853. defaultView: {
  854. requestAnimationFrame: (callback: () => void) => callback(),
  855. },
  856. },
  857. });
  858. const hidden = element("mobile-hidden", false);
  859. const visible = element("desktop-visible", true);
  860. const injected = {
  861. checkDeprecatedSelectorUsage: vi.fn(),
  862. elementState: (
  863. candidate: typeof hidden,
  864. state: "editable" | "enabled" | "visible",
  865. ) => ({
  866. matches: state === "visible" ? candidate.visible : true,
  867. }),
  868. fill: (candidate: typeof hidden) => {
  869. fillTargets.push(candidate.id);
  870. return "done";
  871. },
  872. parseSelector: (selector: string) => selector,
  873. querySelectorAll: () => [hidden, visible],
  874. strictModeViolationError: () =>
  875. new Error(
  876. "strict mode violation: resolved to 2 elements:\n" +
  877. ' 1) <input data-testid="mobile-search"> aka getByTestId("mobile-search")\n' +
  878. ' 2) <input data-testid="desktop-search"> aka getByTestId("desktop-search")',
  879. ),
  880. };
  881. const runtime = createContext({
  882. __zcodePlaywrightInjected: injected,
  883. document: {},
  884. innerHeight: 800,
  885. innerWidth: 1200,
  886. setTimeout,
  887. });
  888. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  889. if (method === "Page.getFrameTree")
  890. return { frameTree: { frame: { id: "main" } } };
  891. if (method === "Page.createIsolatedWorld")
  892. return { executionContextId: 1 };
  893. if (method === "Runtime.evaluate") {
  894. const expression = String(
  895. (params as { expression?: unknown }).expression ?? "",
  896. );
  897. try {
  898. return { result: { value: await runInContext(expression, runtime) } };
  899. } catch (error) {
  900. return {
  901. exceptionDetails: {
  902. exception: {
  903. description: error instanceof Error ? error.message : String(error),
  904. },
  905. },
  906. };
  907. }
  908. }
  909. return {};
  910. });
  911. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  912. method: "playwright",
  913. action: {
  914. name: "locator",
  915. selector: 'internal:role=textbox[name="搜索"i]',
  916. operation: "fill",
  917. value: "世界杯",
  918. },
  919. });
  920. expect(result).toMatchObject({ ok: true });
  921. expect(fillTargets).toEqual(["desktop-visible"]);
  922. hidden.visible = true;
  923. const ambiguous = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  924. method: "playwright",
  925. action: {
  926. name: "locator",
  927. selector: 'internal:role=textbox[name="搜索"i]',
  928. operation: "fill",
  929. value: "世界杯决赛",
  930. },
  931. });
  932. expect(ambiguous).toMatchObject({
  933. ok: false,
  934. error: {
  935. code: "execution_error",
  936. message: expect.stringContaining('getByTestId("mobile-search")'),
  937. },
  938. });
  939. expect(ambiguous.error?.message).toContain(
  940. 'getByTestId("desktop-search")',
  941. );
  942. expect(fillTargets).toEqual(["desktop-visible"]);
  943. });
  944. it("playwright pointer probe 空 payload 返回结构化错误,不泄漏 undefined.count", async () => {
  945. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  946. if (method === "Page.getFrameTree")
  947. return { frameTree: { frame: { id: "main" } } };
  948. if (method === "Page.createIsolatedWorld")
  949. return { executionContextId: 1 };
  950. if (method === "Runtime.evaluate") {
  951. const expression = String(
  952. (params as { expression?: unknown }).expression ?? "",
  953. );
  954. if (expression.startsWith("Boolean(globalThis."))
  955. return { result: { value: true } };
  956. if (expression.includes("const checkStates"))
  957. return { result: { value: {} } };
  958. }
  959. return {};
  960. });
  961. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  962. method: "playwright",
  963. action: { name: "locator", selector: "button", operation: "click" },
  964. });
  965. expect(result).toMatchObject({
  966. ok: false,
  967. error: {
  968. code: "execution_error",
  969. message: expect.stringContaining(
  970. "pointer probe returned an invalid payload",
  971. ),
  972. },
  973. });
  974. expect(result.error?.message).not.toContain("undefined");
  975. });
  976. it("playwright force click 跳过 visible/enabled 与 receives-events,但仍等待稳定矩形", async () => {
  977. let actionabilityExpression = "";
  978. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  979. if (method === "Page.getFrameTree")
  980. return { frameTree: { frame: { id: "main" } } };
  981. if (method === "Page.createIsolatedWorld")
  982. return { executionContextId: 1 };
  983. if (method === "Runtime.evaluate") {
  984. const expression = String(
  985. (params as { expression?: unknown }).expression ?? "",
  986. );
  987. if (expression.startsWith("Boolean(globalThis."))
  988. return { result: { value: true } };
  989. if (expression.includes("const checkStates")) {
  990. actionabilityExpression = expression;
  991. return {
  992. result: { value: { count: 1, actionable: true, x: 10, y: 20 } },
  993. };
  994. }
  995. }
  996. return {};
  997. });
  998. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  999. method: "playwright",
  1000. action: {
  1001. force: true,
  1002. name: "locator",
  1003. selector: "button",
  1004. operation: "click",
  1005. },
  1006. });
  1007. expect(result.ok).toBe(true);
  1008. expect(actionabilityExpression).toContain("if (!true)");
  1009. expect(actionabilityExpression).toContain(
  1010. 'if (false) stateNames.push("enabled")',
  1011. );
  1012. expect(actionabilityExpression).toContain("if (true) {");
  1013. });
  1014. it("playwright click 在 execution context navigation race 后重新解析 locator", async () => {
  1015. let actionabilityCalls = 0;
  1016. let nextContextId = 0;
  1017. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  1018. if (method === "Page.getFrameTree")
  1019. return { frameTree: { frame: { id: "main" } } };
  1020. if (method === "Page.createIsolatedWorld") {
  1021. nextContextId += 1;
  1022. return { executionContextId: nextContextId };
  1023. }
  1024. if (method === "Runtime.evaluate") {
  1025. const expression = String(
  1026. (params as { expression?: unknown }).expression ?? "",
  1027. );
  1028. if (expression.startsWith("Boolean(globalThis."))
  1029. return { result: { value: true } };
  1030. if (expression.includes("const checkStates")) {
  1031. actionabilityCalls += 1;
  1032. if (actionabilityCalls === 1) {
  1033. return {
  1034. exceptionDetails: { text: "Execution context was destroyed." },
  1035. };
  1036. }
  1037. return {
  1038. result: { value: { count: 1, actionable: true, x: 10, y: 20 } },
  1039. };
  1040. }
  1041. }
  1042. return {};
  1043. });
  1044. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  1045. method: "playwright",
  1046. action: { name: "locator", selector: "button", operation: "click" },
  1047. });
  1048. expect(result.ok).toBe(true);
  1049. expect(actionabilityCalls).toBe(2);
  1050. expect(
  1051. cdpSend.mock.calls.filter(([method]) => method === "Page.getFrameTree"),
  1052. ).toHaveLength(2);
  1053. });
  1054. it("playwright click 允许等位新节点跨帧保持几何稳定并派发可信输入", async () => {
  1055. let actionabilityExpression = "";
  1056. let currentNode: { isConnected: boolean };
  1057. const makeNode = (id: string) => ({
  1058. id,
  1059. isConnected: true,
  1060. scrollIntoView: vi.fn(),
  1061. getBoundingClientRect: () => ({
  1062. bottom: 30,
  1063. height: 20,
  1064. left: 10,
  1065. right: 30,
  1066. top: 10,
  1067. width: 20,
  1068. }),
  1069. ownerDocument: {
  1070. defaultView: {
  1071. requestAnimationFrame: (callback: () => void) => {
  1072. if (currentNode === originalNode) {
  1073. originalNode.isConnected = false;
  1074. currentNode = replacementNode;
  1075. }
  1076. callback();
  1077. },
  1078. },
  1079. },
  1080. });
  1081. const originalNode = makeNode("old");
  1082. const replacementNode = makeNode("replacement");
  1083. currentNode = originalNode;
  1084. const injected = {
  1085. checkDeprecatedSelectorUsage: vi.fn(),
  1086. elementState: () => ({ matches: true }),
  1087. expectHitTarget: () => "done",
  1088. parseSelector: (selector: string) => selector,
  1089. querySelectorAll: () => [currentNode],
  1090. strictModeViolationError: () => new Error("strict violation"),
  1091. };
  1092. const runtime = createContext({
  1093. __zcodePlaywrightInjected: injected,
  1094. document: {},
  1095. innerHeight: 800,
  1096. innerWidth: 1200,
  1097. setTimeout,
  1098. });
  1099. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  1100. if (method === "Page.getFrameTree")
  1101. return { frameTree: { frame: { id: "main" } } };
  1102. if (method === "Page.createIsolatedWorld")
  1103. return { executionContextId: 1 };
  1104. if (method === "Runtime.evaluate") {
  1105. const expression = String(
  1106. (params as { expression?: unknown }).expression ?? "",
  1107. );
  1108. if (expression.startsWith("Boolean(globalThis."))
  1109. return { result: { value: true } };
  1110. if (expression.includes("const checkStates")) {
  1111. actionabilityExpression = expression;
  1112. return { result: { value: await runInContext(expression, runtime) } };
  1113. }
  1114. }
  1115. return {};
  1116. });
  1117. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  1118. method: "playwright",
  1119. action: { name: "locator", selector: "button", operation: "click" },
  1120. });
  1121. expect(result.ok).toBe(true);
  1122. // el-table 等页面会在 rAF 间用同 selector 的新节点替换旧节点;稳定性应比较当前目标几何,
  1123. // 不能把旧 node identity 的 detach 永久折算成 count=0。
  1124. expect(actionabilityExpression).toContain("resolveCurrentElement");
  1125. expect(actionabilityExpression).not.toContain(
  1126. "if (!element.isConnected) return { count: 0, actionable: false }",
  1127. );
  1128. expect(originalNode.isConnected).toBe(false);
  1129. expect(currentNode).toBe(replacementNode);
  1130. expect(cdpSend).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1131. type: "mousePressed",
  1132. x: 20,
  1133. y: 20,
  1134. button: "left",
  1135. clickCount: 1,
  1136. });
  1137. });
  1138. it("playwright transformed iframe click 通过 content quad 换算并校验 frame owner", async () => {
  1139. let nextContextId = 0;
  1140. let frameSelectorExpression = "";
  1141. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  1142. if (method === "Page.getFrameTree")
  1143. return { frameTree: { frame: { id: "main" } } };
  1144. if (method === "Page.createIsolatedWorld") {
  1145. nextContextId += 1;
  1146. return { executionContextId: nextContextId };
  1147. }
  1148. if (method === "Runtime.evaluate") {
  1149. const expression = String(
  1150. (params as { expression?: unknown }).expression ?? "",
  1151. );
  1152. if (expression.startsWith("Boolean(globalThis."))
  1153. return { result: { value: true } };
  1154. if (
  1155. expression.includes("frame locator resolved to no elements") &&
  1156. expression.includes("return resolvedElement")
  1157. ) {
  1158. frameSelectorExpression = expression;
  1159. return { result: { objectId: "iframe-object" } };
  1160. }
  1161. if (expression.includes("const checkStates")) {
  1162. return {
  1163. result: { value: { count: 1, actionable: true, x: 10, y: 20 } },
  1164. };
  1165. }
  1166. if (expression.includes("globalThis.innerWidth")) {
  1167. return { result: { value: { width: 200, height: 100 } } };
  1168. }
  1169. if (expression.includes("elements.length"))
  1170. return { result: { value: 1 } };
  1171. }
  1172. if (method === "DOM.describeNode") {
  1173. if ((params as { objectId?: string }).objectId === "iframe-object") {
  1174. return { node: { backendNodeId: 7, frameId: "child" } };
  1175. }
  1176. return { node: { localName: "iframe" } };
  1177. }
  1178. if (method === "DOM.getContentQuads") {
  1179. return { quads: [[100, 50, 300, 70, 290, 170, 90, 150]] };
  1180. }
  1181. if (method === "DOM.getNodeForLocation") return { backendNodeId: 7 };
  1182. return {};
  1183. });
  1184. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  1185. method: "playwright",
  1186. action: {
  1187. name: "locator",
  1188. selector: "iframe >> internal:control=enter-frame >> button",
  1189. operation: "click",
  1190. },
  1191. });
  1192. expect(result.ok).toBe(true);
  1193. expect(frameSelectorExpression).toContain(
  1194. "querySelectorStrictWithVisibleFallback",
  1195. );
  1196. expect(cdpSend).toHaveBeenCalledWith(
  1197. "DOM.getNodeForLocation",
  1198. {
  1199. includeUserAgentShadowDOM: true,
  1200. x: 108,
  1201. y: 71,
  1202. },
  1203. undefined,
  1204. );
  1205. expect(cdpSend).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1206. type: "mousePressed",
  1207. x: 108,
  1208. y: 71,
  1209. button: "left",
  1210. clickCount: 1,
  1211. });
  1212. });
  1213. it("playwright locator 单次 actionability probe 卡住也在 3000ms 内返回 timeout", async () => {
  1214. vi.useFakeTimers();
  1215. try {
  1216. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  1217. if (method === "Page.getFrameTree")
  1218. return { frameTree: { frame: { id: "main" } } };
  1219. if (method === "Page.createIsolatedWorld")
  1220. return { executionContextId: 1 };
  1221. if (method === "Runtime.evaluate") {
  1222. const expression = String(
  1223. (params as { expression?: unknown }).expression ?? "",
  1224. );
  1225. if (expression.startsWith("Boolean(globalThis."))
  1226. return { result: { value: true } };
  1227. return await new Promise<never>(() => undefined);
  1228. }
  1229. return {};
  1230. });
  1231. const pending = executeBrowserCommandOnView(makeView({ cdpSend }), {
  1232. method: "playwright",
  1233. action: {
  1234. name: "locator",
  1235. selector: "textarea",
  1236. operation: "fill",
  1237. value: "hello",
  1238. },
  1239. });
  1240. await vi.advanceTimersByTimeAsync(3_000);
  1241. await expect(pending).resolves.toMatchObject({
  1242. ok: false,
  1243. elapsedMs: 3_000,
  1244. error: { code: "timeout" },
  1245. });
  1246. expect(cdpSend).toHaveBeenCalledWith(
  1247. "Runtime.terminateExecution",
  1248. undefined,
  1249. undefined,
  1250. );
  1251. } finally {
  1252. vi.useRealTimers();
  1253. }
  1254. });
  1255. it("playwright locator strict violation 保留 injected runtime 的候选详情", async () => {
  1256. let actionabilityExpression = "";
  1257. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  1258. if (method === "Page.getFrameTree")
  1259. return { frameTree: { frame: { id: "main" } } };
  1260. if (method === "Page.createIsolatedWorld")
  1261. return { executionContextId: 1 };
  1262. if (method === "Runtime.evaluate") {
  1263. const expression = String(
  1264. (params as { expression?: unknown }).expression ?? "",
  1265. );
  1266. if (expression.startsWith("Boolean(globalThis."))
  1267. return { result: { value: true } };
  1268. if (expression.includes("const checkStates")) {
  1269. actionabilityExpression = expression;
  1270. return {
  1271. exceptionDetails: {
  1272. exception: {
  1273. description:
  1274. "strict mode violation: getByText('购买') resolved to 2 elements:\n" +
  1275. ' 1) <button data-testid="header-buy">购买</button> aka getByTestId("header-buy")\n' +
  1276. ' 2) <button data-testid="card-buy">购买</button> aka getByTestId("card-buy")',
  1277. },
  1278. },
  1279. };
  1280. }
  1281. }
  1282. return {};
  1283. });
  1284. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  1285. method: "playwright",
  1286. action: { name: "locator", selector: "text=购买", operation: "click" },
  1287. });
  1288. expect(result).toMatchObject({
  1289. ok: false,
  1290. error: {
  1291. code: "execution_error",
  1292. message: expect.stringContaining(
  1293. 'getByTestId("header-buy")',
  1294. ),
  1295. },
  1296. });
  1297. expect(result.error?.message).toContain('getByTestId("card-buy")');
  1298. expect(actionabilityExpression).toContain(
  1299. "throw injected.strictModeViolationError(parsedSelector, matches)",
  1300. );
  1301. });
  1302. it("playwright domSnapshot 与 elementScreenshot 走 DOM-first/按需视觉两条独立通道", async () => {
  1303. const cdpSend = vi.fn(async (method: string, params?: unknown) => {
  1304. if (method === "Page.getLayoutMetrics") {
  1305. return {
  1306. visualViewport: { pageX: 0, pageY: 0, clientWidth: 800, clientHeight: 1200 },
  1307. cssVisualViewport: { pageX: 0, pageY: 0, clientWidth: 400, clientHeight: 600 },
  1308. };
  1309. }
  1310. if (method === "Page.getFrameTree")
  1311. return { frameTree: { frame: { id: "main" } } };
  1312. if (method === "Page.createIsolatedWorld")
  1313. return { executionContextId: 1 };
  1314. if (method === "Runtime.evaluate") {
  1315. const expression = String(
  1316. (params as { expression?: unknown }).expression ?? "",
  1317. );
  1318. if (expression.startsWith("Boolean(globalThis."))
  1319. return { result: { value: false } };
  1320. if (expression.includes("globalThis.__zcodePlaywrightInjected = new")) {
  1321. return { result: { value: true } };
  1322. }
  1323. if (expression.includes("elementsFromPoint(options.x, options.y)")) {
  1324. return {
  1325. result: {
  1326. value: [
  1327. {
  1328. tagName: "button",
  1329. preview: "<button>Save</button>",
  1330. selector: { primary: "button", candidates: ["button"] },
  1331. },
  1332. ],
  1333. },
  1334. };
  1335. }
  1336. return {
  1337. result: {
  1338. value: {
  1339. full: '- heading "Example" [level=1] [ref=e1]',
  1340. iframeDepths: {},
  1341. iframeRefs: [],
  1342. },
  1343. },
  1344. };
  1345. }
  1346. if (method === "Page.captureScreenshot") return { data: "PNGDATA" };
  1347. return {};
  1348. });
  1349. const view = makeView({ cdpSend, normalizeScreenshotToCssPixels: true });
  1350. await expect(
  1351. executeBrowserCommandOnView(view, {
  1352. method: "playwright",
  1353. action: { name: "domSnapshot" },
  1354. }),
  1355. ).resolves.toMatchObject({
  1356. ok: true,
  1357. value: '- heading "Example" [level=1]',
  1358. });
  1359. await expect(
  1360. executeBrowserCommandOnView(view, {
  1361. method: "playwright",
  1362. action: { name: "elementInfo", x: 1, y: 2 },
  1363. }),
  1364. ).resolves.toMatchObject({ ok: true, value: [{ tagName: "button" }] });
  1365. await expect(
  1366. executeBrowserCommandOnView(view, {
  1367. method: "playwright",
  1368. action: { name: "elementScreenshot", x: 1, y: 2 },
  1369. }),
  1370. ).resolves.toMatchObject({ ok: true, image: { base64: "PNGDATA" } });
  1371. expect(cdpSend).toHaveBeenCalledWith("Page.captureScreenshot", {
  1372. format: "png",
  1373. captureBeyondViewport: false,
  1374. clip: { x: 0, y: 0, width: 400, height: 600, scale: 1 },
  1375. });
  1376. expect(view.webContents.executeJavaScript).not.toHaveBeenCalled();
  1377. expect(cdpSend).toHaveBeenCalledWith(
  1378. "Runtime.evaluate",
  1379. expect.objectContaining({ contextId: 1, returnByValue: true }),
  1380. );
  1381. });
  1382. it("playwright domSnapshot 顶层 3000ms 预算耗尽后返回结构化 timeout", async () => {
  1383. const cdpSend = vi.fn(async (method: string) => {
  1384. if (method === "Page.getFrameTree")
  1385. return { frameTree: { frame: { id: "main" } } };
  1386. if (method === "Page.createIsolatedWorld")
  1387. return { executionContextId: 1 };
  1388. if (method === "Runtime.evaluate")
  1389. throw new Error("Script execution timed out");
  1390. return {};
  1391. });
  1392. await expect(
  1393. executeBrowserCommandOnView(makeView({ cdpSend }), {
  1394. method: "playwright",
  1395. action: { name: "domSnapshot" },
  1396. }),
  1397. ).resolves.toMatchObject({
  1398. ok: false,
  1399. error: { code: "timeout", message: "Script execution timed out" },
  1400. });
  1401. });
  1402. it("playwright evaluate 允许页面副作用并走 CDP 硬 timeout", async () => {
  1403. const cdpSend = vi.fn(async (_method: string, params?: unknown) => {
  1404. const expression = (params as { expression: string }).expression;
  1405. expect(expression).toContain("document.body.append");
  1406. return { result: { value: "Example" } };
  1407. });
  1408. const r = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  1409. method: "playwright",
  1410. action: {
  1411. name: "evaluate",
  1412. expression: "document.body.append(document.createElement('div'))",
  1413. expressionKind: "string",
  1414. timeoutMs: 1234,
  1415. },
  1416. });
  1417. expect(r).toMatchObject({ ok: true, value: "Example" });
  1418. expect(cdpSend).toHaveBeenCalledWith(
  1419. "Runtime.evaluate",
  1420. expect.objectContaining({
  1421. awaitPromise: true,
  1422. returnByValue: true,
  1423. timeout: 1234,
  1424. }),
  1425. );
  1426. });
  1427. it("playwright evaluate 页面异常只返回执行错误,不附加只读限制提示", async () => {
  1428. const cdpSend = vi.fn(async () => ({
  1429. exceptionDetails: {
  1430. exception: {
  1431. description: "Error: page script failed",
  1432. },
  1433. },
  1434. }));
  1435. const result = await executeBrowserCommandOnView(makeView({ cdpSend }), {
  1436. method: "playwright",
  1437. action: {
  1438. name: "evaluate",
  1439. expression: "document.body.getBoundingClientRect()",
  1440. expressionKind: "string",
  1441. },
  1442. });
  1443. expect(result).toMatchObject({
  1444. ok: false,
  1445. error: { code: "execution_error" },
  1446. });
  1447. expect(result.error?.message).toContain("page script failed");
  1448. expect(result.error?.message).not.toContain("read-only");
  1449. expect(result.error?.message).not.toContain("Possible side-effect");
  1450. });
  1451. it("Playwright routine timeout 默认并截断为 3000ms", async () => {
  1452. expect(normalizePlaywrightTimeout(undefined)).toBe(3_000);
  1453. expect(normalizePlaywrightTimeout(250)).toBe(250);
  1454. expect(normalizePlaywrightTimeout(30_000)).toBe(3_000);
  1455. expect(normalizePlaywrightTimeout(30_000, 120_000)).toBe(30_000);
  1456. const timeouts: unknown[] = [];
  1457. const cdpSend = vi.fn(async (_method: string, params?: unknown) => {
  1458. timeouts.push((params as { timeout?: unknown }).timeout);
  1459. return { result: { value: "Example" } };
  1460. });
  1461. const view = makeView({ cdpSend });
  1462. await executeBrowserCommandOnView(view, {
  1463. method: "playwright",
  1464. action: {
  1465. name: "evaluate",
  1466. expression: "document.title",
  1467. expressionKind: "string",
  1468. },
  1469. });
  1470. await executeBrowserCommandOnView(view, {
  1471. method: "playwright",
  1472. action: {
  1473. name: "evaluate",
  1474. expression: "document.title",
  1475. expressionKind: "string",
  1476. timeoutMs: 30_000,
  1477. },
  1478. });
  1479. expect(timeouts).toEqual([3_000, 3_000]);
  1480. });
  1481. it("waitForLoadState 明确拒绝 networkidle", async () => {
  1482. const result = await executeBrowserCommandOnView(makeView(), {
  1483. method: "playwright",
  1484. action: {
  1485. name: "waitForLoadState",
  1486. state: "networkidle",
  1487. timeoutMs: 100,
  1488. },
  1489. });
  1490. expect(result).toMatchObject({
  1491. ok: false,
  1492. error: {
  1493. code: "execution_error",
  1494. message: "playwright_wait_for_load_state does not support networkidle",
  1495. },
  1496. });
  1497. });
  1498. it("wraps CDP throw into execution_error", async () => {
  1499. const view = makeView({
  1500. cdpSend: vi.fn(async () => {
  1501. throw new Error("cdp boom");
  1502. }),
  1503. });
  1504. const r = await executeBrowserCommandOnView(view, { method: "screenshot" });
  1505. expect(r.ok).toBe(false);
  1506. expect(r.error?.code).toBe("execution_error");
  1507. expect(r.error?.message).toContain("cdp boom");
  1508. });
  1509. it("把 generation abort 映射成 cancelled,而不是页面执行错误", async () => {
  1510. const controller = new AbortController();
  1511. controller.abort();
  1512. const r = await executeBrowserCommandOnView(
  1513. makeView(),
  1514. { method: "playwright", action: { name: "domSnapshot" } },
  1515. { signal: controller.signal },
  1516. );
  1517. expect(r).toMatchObject({
  1518. ok: false,
  1519. error: { code: "cancelled", message: "Browser command cancelled" },
  1520. });
  1521. });
  1522. it("back 调 goBack 并返回 state", async () => {
  1523. const view = makeView();
  1524. const r = await executeBrowserCommandOnView(view, { method: "back" });
  1525. expect(view.webContents.goBack).toHaveBeenCalledTimes(1);
  1526. expect(r.ok).toBe(true);
  1527. expect(r.state?.url).toBe("https://example.com");
  1528. });
  1529. it("forward 调 goForward 并返回 state", async () => {
  1530. const view = makeView();
  1531. const r = await executeBrowserCommandOnView(view, { method: "forward" });
  1532. expect(view.webContents.goForward).toHaveBeenCalledTimes(1);
  1533. expect(r.ok).toBe(true);
  1534. });
  1535. it("reload 调 reload 并返回 state", async () => {
  1536. const view = makeView();
  1537. const r = await executeBrowserCommandOnView(view, { method: "reload" });
  1538. expect(view.webContents.reload).toHaveBeenCalledTimes(1);
  1539. expect(r.ok).toBe(true);
  1540. });
  1541. it("click 解析 ref 中心点并发 CDP mousePressed/mouseReleased(ok:true)", async () => {
  1542. const send = vi.fn(async () => ({}));
  1543. const view = makeView({
  1544. cdpSend: send,
  1545. executeJavaScript: vi.fn(async () => ({ cx: 50, cy: 60 })),
  1546. });
  1547. const r = await executeBrowserCommandOnView(view, {
  1548. method: "click",
  1549. ref: "e1",
  1550. });
  1551. expect(r.ok).toBe(true);
  1552. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1553. type: "mousePressed",
  1554. x: 50,
  1555. y: 60,
  1556. button: "left",
  1557. clickCount: 1,
  1558. });
  1559. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1560. type: "mouseReleased",
  1561. x: 50,
  1562. y: 60,
  1563. button: "left",
  1564. clickCount: 1,
  1565. });
  1566. });
  1567. it("click ref 未找到(resolve 返回 null)→ ok:false ref_not_found", async () => {
  1568. const send = vi.fn(async () => ({}));
  1569. const view = makeView({
  1570. cdpSend: send,
  1571. executeJavaScript: vi.fn(async () => null),
  1572. });
  1573. const r = await executeBrowserCommandOnView(view, {
  1574. method: "click",
  1575. ref: "e404",
  1576. });
  1577. expect(r.ok).toBe(false);
  1578. expect(r.error?.code).toBe("ref_not_found");
  1579. // 未找到时不应发鼠标事件。
  1580. expect(send).not.toHaveBeenCalled();
  1581. });
  1582. it("type 在 guest focused target 执行 virtual paste,不调用 Input.insertText", async () => {
  1583. const expressions: string[] = [];
  1584. const send = vi.fn(async (method: string, params?: unknown) => {
  1585. if (method !== "Runtime.evaluate") return {};
  1586. const options = params as { expression?: string; returnByValue?: boolean };
  1587. expressions.push(options.expression ?? "");
  1588. return options.returnByValue === false
  1589. ? { result: { value: null } }
  1590. : { result: { value: { ok: true, data: {} } } };
  1591. });
  1592. const view = makeView({ cdpSend: send });
  1593. const r = await executeBrowserCommandOnView(view, {
  1594. method: "type",
  1595. text: "hi",
  1596. });
  1597. expect(r.ok).toBe(true);
  1598. expect(send).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
  1599. expect(expressions[0]).toContain("focusedFrameElementInRoot");
  1600. expect(expressions[1]).toContain('new view.ClipboardEvent("paste"');
  1601. expect(expressions[1]).toContain('mime_type":"text/plain","text":"hi"');
  1602. });
  1603. it("type 在 OOPIF target 延迟注册时等待 child session,paste 后释放 attach", async () => {
  1604. let attachAttempts = 0;
  1605. const send = vi.fn(
  1606. async (method: string, params?: unknown, sessionId?: string) => {
  1607. if (method === "Runtime.evaluate") {
  1608. const options = params as { expression?: string; returnByValue?: boolean };
  1609. if (options.returnByValue === false) {
  1610. return sessionId == null
  1611. ? { result: { objectId: "focused-frame" } }
  1612. : { result: { value: null } };
  1613. }
  1614. return { result: { value: { ok: true, data: {} } } };
  1615. }
  1616. if (method === "DOM.describeNode") return { node: { frameId: "oopif-frame" } };
  1617. if (method === "Target.attachToTarget") {
  1618. attachAttempts += 1;
  1619. if (attachAttempts === 1) throw new Error("No target with given id found");
  1620. return { sessionId: "oopif-session" };
  1621. }
  1622. if (method === "Page.createIsolatedWorld")
  1623. throw new Error("No frame for given id found");
  1624. if (method === "Target.getTargets") {
  1625. return { targetInfos: [{ targetId: "oopif-frame", type: "iframe" }] };
  1626. }
  1627. return {};
  1628. },
  1629. );
  1630. const result = await executeBrowserCommandOnView(makeView({ cdpSend: send }), {
  1631. method: "type",
  1632. text: "guest-only",
  1633. });
  1634. expect(result.ok).toBe(true);
  1635. expect(send).toHaveBeenCalledWith(
  1636. "Runtime.evaluate",
  1637. expect.objectContaining({
  1638. expression: expect.stringContaining("guest-only"),
  1639. returnByValue: true,
  1640. }),
  1641. "oopif-session",
  1642. );
  1643. expect(send).toHaveBeenCalledWith("Target.detachFromTarget", {
  1644. sessionId: "oopif-session",
  1645. });
  1646. expect(send).not.toHaveBeenCalledWith("Input.insertText", expect.anything());
  1647. });
  1648. it("press Enter 映射为 windowsVirtualKeyCode:13 的 keyDown+keyUp", async () => {
  1649. const send = vi.fn(async () => ({}));
  1650. const view = makeView({ cdpSend: send });
  1651. const r = await executeBrowserCommandOnView(view, {
  1652. method: "press",
  1653. key: "Enter",
  1654. });
  1655. expect(r.ok).toBe(true);
  1656. expect(send).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
  1657. type: "keyDown",
  1658. key: "Enter",
  1659. code: "Enter",
  1660. windowsVirtualKeyCode: 13,
  1661. });
  1662. expect(send).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
  1663. type: "keyUp",
  1664. key: "Enter",
  1665. code: "Enter",
  1666. windowsVirtualKeyCode: 13,
  1667. });
  1668. });
  1669. it("scroll {y:300} 发 CDP mouseWheel deltaY:300", async () => {
  1670. const send = vi.fn(async () => ({}));
  1671. const view = makeView({ cdpSend: send });
  1672. const r = await executeBrowserCommandOnView(view, {
  1673. method: "scroll",
  1674. y: 300,
  1675. });
  1676. expect(r.ok).toBe(true);
  1677. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1678. type: "mouseWheel",
  1679. x: 0,
  1680. y: 0,
  1681. deltaX: 0,
  1682. deltaY: 300,
  1683. });
  1684. });
  1685. it("click 用坐标 (x,y) 直接点(不经 resolveRefCenter/executeJavaScript)", async () => {
  1686. const send = vi.fn(async () => ({}));
  1687. const exec = vi.fn(async () => null);
  1688. const view = makeView({ cdpSend: send, executeJavaScript: exec });
  1689. const r = await executeBrowserCommandOnView(view, {
  1690. method: "click",
  1691. x: 120,
  1692. y: 240,
  1693. });
  1694. expect(r.ok).toBe(true);
  1695. // 坐标路不解析 ref。
  1696. expect(exec).not.toHaveBeenCalled();
  1697. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1698. type: "mousePressed",
  1699. x: 120,
  1700. y: 240,
  1701. button: "left",
  1702. clickCount: 1,
  1703. });
  1704. });
  1705. it("click 带 modifiers(Control+Shift) 映射位掩码 2|8=10 传给 dispatchMouseEvent", async () => {
  1706. const send = vi.fn(async () => ({}));
  1707. const view = makeView({ cdpSend: send });
  1708. const r = await executeBrowserCommandOnView(view, {
  1709. method: "click",
  1710. x: 10,
  1711. y: 20,
  1712. modifiers: ["Control", "Shift"],
  1713. });
  1714. expect(r.ok).toBe(true);
  1715. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1716. type: "mousePressed",
  1717. x: 10,
  1718. y: 20,
  1719. button: "left",
  1720. clickCount: 1,
  1721. modifiers: 10,
  1722. });
  1723. });
  1724. it("click ref 与 (x,y) 都缺 → execution_error(不发鼠标事件)", async () => {
  1725. const send = vi.fn(async () => ({}));
  1726. const view = makeView({ cdpSend: send });
  1727. const r = await executeBrowserCommandOnView(view, { method: "click" });
  1728. expect(r.ok).toBe(false);
  1729. expect(r.error?.code).toBe("execution_error");
  1730. expect(send).not.toHaveBeenCalled();
  1731. });
  1732. it("press 带 modifiers(Meta) 映射位掩码 4 传给 dispatchKeyEvent", async () => {
  1733. const send = vi.fn(async () => ({}));
  1734. const view = makeView({ cdpSend: send });
  1735. const r = await executeBrowserCommandOnView(view, {
  1736. method: "press",
  1737. key: "Enter",
  1738. modifiers: ["Meta"],
  1739. });
  1740. expect(r.ok).toBe(true);
  1741. expect(send).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
  1742. type: "keyDown",
  1743. key: "Enter",
  1744. code: "Enter",
  1745. windowsVirtualKeyCode: 13,
  1746. modifiers: 4,
  1747. });
  1748. });
  1749. it("CUA keypress 按顺序按下组合键并逆序释放", async () => {
  1750. const send = vi.fn(async () => ({}));
  1751. const result = await executeBrowserCommandOnView(
  1752. makeView({ cdpSend: send }),
  1753. {
  1754. method: "cuaKeypress",
  1755. keys: ["Control", "Shift", "A"],
  1756. },
  1757. );
  1758. expect(result.ok).toBe(true);
  1759. const keyEvents = send.mock.calls
  1760. .filter((call) => call[0] === "Input.dispatchKeyEvent")
  1761. .map((call) => call[1]);
  1762. expect(keyEvents).toEqual([
  1763. expect.objectContaining({
  1764. type: "keyDown",
  1765. key: "Control",
  1766. modifiers: 2,
  1767. }),
  1768. expect.objectContaining({ type: "keyDown", key: "Shift", modifiers: 10 }),
  1769. expect.objectContaining({ type: "keyDown", key: "A", modifiers: 10 }),
  1770. expect.objectContaining({ type: "keyUp", key: "A", modifiers: 10 }),
  1771. expect.objectContaining({ type: "keyUp", key: "Shift", modifiers: 2 }),
  1772. expect.objectContaining({ type: "keyUp", key: "Control" }),
  1773. ]);
  1774. });
  1775. it("CUA scroll 在 Electron guest 中用 mouseWheel 保留锚点、delta 和 modifiers", async () => {
  1776. const send = vi.fn(async () => ({}));
  1777. const result = await executeBrowserCommandOnView(
  1778. makeView({ cdpSend: send }),
  1779. {
  1780. method: "cuaScroll",
  1781. x: 120,
  1782. y: 240,
  1783. scrollX: 30,
  1784. scrollY: -80,
  1785. modifiers: ["Shift"],
  1786. },
  1787. );
  1788. expect(result.ok).toBe(true);
  1789. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1790. type: "mouseMoved",
  1791. x: 120,
  1792. y: 240,
  1793. modifiers: 8,
  1794. });
  1795. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1796. type: "mouseWheel",
  1797. x: 120,
  1798. y: 240,
  1799. deltaX: 30,
  1800. deltaY: -80,
  1801. modifiers: 8,
  1802. });
  1803. expect(send).not.toHaveBeenCalledWith("Input.synthesizeScrollGesture", expect.anything());
  1804. });
  1805. it("DOM CUA scroll 使用 node 中心或 viewport 中心作为锚点", async () => {
  1806. const nodeSend = vi.fn(async () => ({}));
  1807. const nodeResult = await executeBrowserCommandOnView(
  1808. makeView({
  1809. cdpSend: nodeSend,
  1810. executeJavaScript: vi.fn(async () => ({ cx: 20, cy: 40 })),
  1811. }),
  1812. { method: "domCuaScroll", nodeId: "e1", scrollX: 0, scrollY: 50 },
  1813. );
  1814. expect(nodeResult.ok).toBe(true);
  1815. expect(nodeSend).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1816. type: "mouseWheel",
  1817. x: 20,
  1818. y: 40,
  1819. deltaX: 0,
  1820. deltaY: 50,
  1821. });
  1822. const pageSend = vi.fn(async (method: string) =>
  1823. method === "Page.getLayoutMetrics"
  1824. ? { cssVisualViewport: { clientWidth: 800, clientHeight: 600 } }
  1825. : {},
  1826. );
  1827. const pageResult = await executeBrowserCommandOnView(
  1828. makeView({ cdpSend: pageSend }),
  1829. {
  1830. method: "domCuaScroll",
  1831. scrollX: 10,
  1832. scrollY: 20,
  1833. },
  1834. );
  1835. expect(pageResult.ok).toBe(true);
  1836. expect(pageSend).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1837. type: "mouseWheel",
  1838. x: 400,
  1839. y: 300,
  1840. deltaX: 10,
  1841. deltaY: 20,
  1842. });
  1843. });
  1844. it("hover 用坐标发 CDP mouseMoved", async () => {
  1845. const send = vi.fn(async () => ({}));
  1846. const view = makeView({ cdpSend: send });
  1847. const r = await executeBrowserCommandOnView(view, {
  1848. method: "hover",
  1849. x: 33,
  1850. y: 44,
  1851. });
  1852. expect(r.ok).toBe(true);
  1853. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1854. type: "mouseMoved",
  1855. x: 33,
  1856. y: 44,
  1857. });
  1858. });
  1859. it("hover 用 ref 经 resolveRefCenter 再 mouseMoved", async () => {
  1860. const send = vi.fn(async () => ({}));
  1861. const view = makeView({
  1862. cdpSend: send,
  1863. executeJavaScript: vi.fn(async () => ({ cx: 7, cy: 8 })),
  1864. });
  1865. const r = await executeBrowserCommandOnView(view, {
  1866. method: "hover",
  1867. ref: "e1",
  1868. });
  1869. expect(r.ok).toBe(true);
  1870. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1871. type: "mouseMoved",
  1872. x: 7,
  1873. y: 8,
  1874. });
  1875. });
  1876. it("hover ref 与坐标都缺 → execution_error", async () => {
  1877. const view = makeView();
  1878. const r = await executeBrowserCommandOnView(view, { method: "hover" });
  1879. expect(r.ok).toBe(false);
  1880. expect(r.error?.code).toBe("execution_error");
  1881. });
  1882. it("select 注入脚本(含 __zcodeRefs),脚本回 ok → ok:true", async () => {
  1883. const exec = vi.fn(async () => ({ ok: true }));
  1884. const view = makeView({ executeJavaScript: exec });
  1885. const r = await executeBrowserCommandOnView(view, {
  1886. method: "select",
  1887. ref: "e1",
  1888. values: ["opt-a"],
  1889. });
  1890. expect(r.ok).toBe(true);
  1891. const script = exec.mock.calls[0][0] as string;
  1892. expect(script).toContain("__zcodeRefs");
  1893. // values 经 JSON.stringify 内插。
  1894. expect(script).toContain('["opt-a"]');
  1895. });
  1896. it("select 脚本回 ref_not_found → ref_not_found", async () => {
  1897. const view = makeView({
  1898. executeJavaScript: vi.fn(async () => ({ error: "ref_not_found" })),
  1899. });
  1900. const r = await executeBrowserCommandOnView(view, {
  1901. method: "select",
  1902. ref: "e404",
  1903. values: ["x"],
  1904. });
  1905. expect(r.ok).toBe(false);
  1906. expect(r.error?.code).toBe("ref_not_found");
  1907. });
  1908. it("select 非 select 元素 / 无匹配 → execution_error", async () => {
  1909. const notSelect = makeView({
  1910. executeJavaScript: vi.fn(async () => ({ error: "not_select" })),
  1911. });
  1912. const r1 = await executeBrowserCommandOnView(notSelect, {
  1913. method: "select",
  1914. ref: "e1",
  1915. values: ["x"],
  1916. });
  1917. expect(r1.ok).toBe(false);
  1918. expect(r1.error?.code).toBe("execution_error");
  1919. const noMatch = makeView({
  1920. executeJavaScript: vi.fn(async () => ({ error: "no_match" })),
  1921. });
  1922. const r2 = await executeBrowserCommandOnView(noMatch, {
  1923. method: "select",
  1924. ref: "e1",
  1925. values: ["x"],
  1926. });
  1927. expect(r2.ok).toBe(false);
  1928. expect(r2.error?.code).toBe("execution_error");
  1929. });
  1930. it("check 注入脚本(含 checked 目标),脚本回 ok → ok:true", async () => {
  1931. const exec = vi.fn(async () => ({ ok: true, checked: true }));
  1932. const view = makeView({ executeJavaScript: exec });
  1933. const r = await executeBrowserCommandOnView(view, {
  1934. method: "check",
  1935. ref: "e1",
  1936. checked: true,
  1937. });
  1938. expect(r.ok).toBe(true);
  1939. const script = exec.mock.calls[0][0] as string;
  1940. expect(script).toContain("__zcodeRefs");
  1941. expect(script).toContain("var want=true");
  1942. });
  1943. it("check 非 checkbox/radio → execution_error;ref 未找到 → ref_not_found", async () => {
  1944. const notCheck = makeView({
  1945. executeJavaScript: vi.fn(async () => ({ error: "not_checkable" })),
  1946. });
  1947. const r1 = await executeBrowserCommandOnView(notCheck, {
  1948. method: "check",
  1949. ref: "e1",
  1950. });
  1951. expect(r1.ok).toBe(false);
  1952. expect(r1.error?.code).toBe("execution_error");
  1953. const gone = makeView({
  1954. executeJavaScript: vi.fn(async () => ({ error: "ref_not_found" })),
  1955. });
  1956. const r2 = await executeBrowserCommandOnView(gone, {
  1957. method: "check",
  1958. ref: "e9",
  1959. });
  1960. expect(r2.ok).toBe(false);
  1961. expect(r2.error?.code).toBe("ref_not_found");
  1962. });
  1963. it("drag from/to 坐标发 mousePressed@from → mouseReleased@to(含插值 mouseMoved)", async () => {
  1964. const send = vi.fn(async () => ({}));
  1965. const view = makeView({ cdpSend: send });
  1966. const r = await executeBrowserCommandOnView(view, {
  1967. method: "drag",
  1968. from: { x: 0, y: 0 },
  1969. to: { x: 100, y: 50 },
  1970. });
  1971. expect(r.ok).toBe(true);
  1972. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1973. type: "mousePressed",
  1974. x: 0,
  1975. y: 0,
  1976. button: "left",
  1977. clickCount: 1,
  1978. });
  1979. expect(send).toHaveBeenCalledWith("Input.dispatchMouseEvent", {
  1980. type: "mouseReleased",
  1981. x: 100,
  1982. y: 50,
  1983. button: "left",
  1984. clickCount: 1,
  1985. });
  1986. // 至少发过若干插值 mouseMoved(buttons:1)。
  1987. const moves = send.mock.calls.filter(
  1988. (c) =>
  1989. c[0] === "Input.dispatchMouseEvent" &&
  1990. (c[1] as { type?: string }).type === "mouseMoved",
  1991. );
  1992. expect(moves.length).toBeGreaterThanOrEqual(10);
  1993. });
  1994. it("CUA drag 保留调用方完整 path,不重建为首尾直线", async () => {
  1995. const send = vi.fn(async () => ({}));
  1996. const path = [
  1997. { x: 1, y: 2 },
  1998. { x: 8, y: 30 },
  1999. { x: 21, y: 13 },
  2000. ];
  2001. const result = await executeBrowserCommandOnView(
  2002. makeView({ cdpSend: send }),
  2003. {
  2004. method: "cuaDrag",
  2005. path,
  2006. modifiers: ["Alt"],
  2007. },
  2008. );
  2009. expect(result.ok).toBe(true);
  2010. const movedPoints = send.mock.calls
  2011. .filter(
  2012. (call) =>
  2013. call[0] === "Input.dispatchMouseEvent" &&
  2014. (call[1] as { type?: string; buttons?: number }).type ===
  2015. "mouseMoved" &&
  2016. (call[1] as { buttons?: number }).buttons === 1,
  2017. )
  2018. .map((call) => ({
  2019. x: (call[1] as { x: number }).x,
  2020. y: (call[1] as { y: number }).y,
  2021. }));
  2022. expect(movedPoints).toEqual(path.slice(1));
  2023. expect(send).toHaveBeenCalledWith(
  2024. "Input.dispatchMouseEvent",
  2025. expect.objectContaining({
  2026. type: "mouseReleased",
  2027. x: 21,
  2028. y: 13,
  2029. modifiers: 1,
  2030. }),
  2031. );
  2032. });
  2033. it("drag fromRef 解析失败 → ref_not_found(不发鼠标事件)", async () => {
  2034. const send = vi.fn(async () => ({}));
  2035. const view = makeView({
  2036. cdpSend: send,
  2037. executeJavaScript: vi.fn(async () => null),
  2038. });
  2039. const r = await executeBrowserCommandOnView(view, {
  2040. method: "drag",
  2041. fromRef: "e404",
  2042. to: { x: 1, y: 1 },
  2043. });
  2044. expect(r.ok).toBe(false);
  2045. expect(r.error?.code).toBe("ref_not_found");
  2046. expect(send).not.toHaveBeenCalled();
  2047. });
  2048. it("drag 缺终点 → execution_error", async () => {
  2049. const view = makeView();
  2050. const r = await executeBrowserCommandOnView(view, {
  2051. method: "drag",
  2052. from: { x: 0, y: 0 },
  2053. });
  2054. expect(r.ok).toBe(false);
  2055. expect(r.error?.code).toBe("execution_error");
  2056. });
  2057. it("screenshot clip → Page.captureScreenshot 带 clip{...,scale:1}", async () => {
  2058. const send = vi.fn(async () => ({ data: "PNG" }));
  2059. const view = makeView({ cdpSend: send });
  2060. const r = await executeBrowserCommandOnView(view, {
  2061. method: "screenshot",
  2062. clip: { x: 1, y: 2, width: 30, height: 40 },
  2063. });
  2064. expect(r.ok).toBe(true);
  2065. expect(send).toHaveBeenCalledWith("Page.captureScreenshot", {
  2066. format: "png",
  2067. captureBeyondViewport: true,
  2068. clip: { x: 1, y: 2, width: 30, height: 40, scale: 1 },
  2069. });
  2070. });
  2071. it("screenshot fullPage → 先 getLayoutMetrics 再用 contentSize 作 clip", async () => {
  2072. const send = vi.fn(async (method: string) => {
  2073. if (method === "Page.getLayoutMetrics") {
  2074. return { cssContentSize: { x: 0, y: 0, width: 800, height: 2000 } };
  2075. }
  2076. return { data: "FULLPNG" };
  2077. });
  2078. const view = makeView({ cdpSend: send });
  2079. const r = await executeBrowserCommandOnView(view, {
  2080. method: "screenshot",
  2081. fullPage: true,
  2082. });
  2083. expect(r.ok).toBe(true);
  2084. expect(r.image?.base64).toBe("FULLPNG");
  2085. expect(send).toHaveBeenCalledWith("Page.getLayoutMetrics");
  2086. expect(send).toHaveBeenCalledWith("Page.captureScreenshot", {
  2087. format: "png",
  2088. captureBeyondViewport: true,
  2089. clip: { x: 0, y: 0, width: 800, height: 2000, scale: 1 },
  2090. });
  2091. });
  2092. it("getState 补 scroll/viewport 字段(executeJavaScript 读窗口信息)", async () => {
  2093. const view = makeView({
  2094. executeJavaScript: vi.fn(async () => ({
  2095. scrollX: 5,
  2096. scrollY: 600,
  2097. innerWidth: 1280,
  2098. innerHeight: 720,
  2099. })),
  2100. });
  2101. const r = await executeBrowserCommandOnView(view, { method: "getState" });
  2102. expect(r.ok).toBe(true);
  2103. expect(r.state?.scrollX).toBe(5);
  2104. expect(r.state?.scrollY).toBe(600);
  2105. expect(r.state?.viewportWidth).toBe(1280);
  2106. expect(r.state?.viewportHeight).toBe(720);
  2107. });
  2108. it("elementInfo 命中元素 → result.element(复用快照元素结构)", async () => {
  2109. const view = makeView({
  2110. executeJavaScript: vi.fn(async () => ({
  2111. ref: "p1",
  2112. tag: "a",
  2113. role: "link",
  2114. name: "Home",
  2115. selector: "#home",
  2116. xpath: "//*[@id='home']",
  2117. rect: { x: 10, y: 20, width: 40, height: 12 },
  2118. inViewport: true,
  2119. })),
  2120. });
  2121. const r = await executeBrowserCommandOnView(view, {
  2122. method: "elementInfo",
  2123. x: 15,
  2124. y: 25,
  2125. });
  2126. expect(r.ok).toBe(true);
  2127. expect(r.element?.ref).toBe("p1");
  2128. expect(r.element?.role).toBe("link");
  2129. });
  2130. it("elementInfo 未命中(null) → ok:true 且无 element", async () => {
  2131. const view = makeView({ executeJavaScript: vi.fn(async () => null) });
  2132. const r = await executeBrowserCommandOnView(view, {
  2133. method: "elementInfo",
  2134. x: 0,
  2135. y: 0,
  2136. });
  2137. expect(r.ok).toBe(true);
  2138. expect(r.element).toBeUndefined();
  2139. });
  2140. it("evaluate JSON 结果 → result.value 反序列化", async () => {
  2141. const exec = vi.fn(async () => ({
  2142. ok: true,
  2143. kind: "json",
  2144. data: '{"a":1,"b":[2,3]}',
  2145. }));
  2146. const view = makeView({ executeJavaScript: exec });
  2147. const r = await executeBrowserCommandOnView(view, {
  2148. method: "evaluate",
  2149. expression: "({a:1,b:[2,3]})",
  2150. });
  2151. expect(r.ok).toBe(true);
  2152. expect(r.value).toEqual({ a: 1, b: [2, 3] });
  2153. // 表达式被包进只读 IIFE。
  2154. const script = exec.mock.calls[0][0] as string;
  2155. expect(script).toContain("return (({a:1,b:[2,3]})");
  2156. });
  2157. it("evaluate 不可序列化 → 返回 String() 结果", async () => {
  2158. const view = makeView({
  2159. executeJavaScript: vi.fn(async () => ({
  2160. ok: true,
  2161. kind: "str",
  2162. data: "function foo(){}",
  2163. })),
  2164. });
  2165. const r = await executeBrowserCommandOnView(view, {
  2166. method: "evaluate",
  2167. expression: "foo",
  2168. });
  2169. expect(r.ok).toBe(true);
  2170. expect(r.value).toBe("function foo(){}");
  2171. });
  2172. it("evaluate 页面抛错 → execution_error", async () => {
  2173. const view = makeView({
  2174. executeJavaScript: vi.fn(async () => ({
  2175. ok: false,
  2176. message: "x is not defined",
  2177. })),
  2178. });
  2179. const r = await executeBrowserCommandOnView(view, {
  2180. method: "evaluate",
  2181. expression: "x.y",
  2182. });
  2183. expect(r.ok).toBe(false);
  2184. expect(r.error?.code).toBe("execution_error");
  2185. expect(r.error?.message).toContain("x is not defined");
  2186. });
  2187. });