browserCommandExecutor.test.ts 77 KB

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