@xbrowser/cli 1.29.0 → 1.30.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +2 -2
  2. package/dist/{browser-XD3IOU5I.js → browser-6PFTHZI3.js} +2 -2
  3. package/dist/{browser-2K3XYAKM.js → browser-I2NLJN2A.js} +1 -1
  4. package/dist/{browser-OTEMG5NL.js → browser-KOUA4ZDA.js} +2 -2
  5. package/dist/{cdp-driver-AAS55KT2.js → cdp-driver-3ETNFQA4.js} +1 -1
  6. package/dist/{cdp-driver-XTPY7EXP.js → cdp-driver-U7HDQMQ5.js} +257 -19
  7. package/dist/{cdp-driver-O5I7SJ24.js → cdp-driver-WBFJNOLD.js} +1 -1
  8. package/dist/{chunk-SCYBNSOG.js → chunk-3K57RYVC.js} +378 -115
  9. package/dist/{chunk-FNXA6FDM.js → chunk-BND5O5KC.js} +2 -1
  10. package/dist/{chunk-P33R7F2D.js → chunk-BOZTIIBT.js} +30 -45
  11. package/dist/{chunk-GDKKVT2P.js → chunk-KPTD3SNJ.js} +379 -116
  12. package/dist/{chunk-CO2ZVOVT.js → chunk-NINETOM4.js} +30 -45
  13. package/dist/{chunk-SOPN4XDK.js → chunk-O5PASNI7.js} +2 -1
  14. package/dist/{chunk-NQPXZ74W.js → chunk-OCECE22C.js} +257 -19
  15. package/dist/{chunk-LFSLNHW5.js → chunk-OSIDUT4H.js} +286 -63
  16. package/dist/{chunk-HBMEFSTB.js → chunk-QCV2PI7U.js} +2 -1
  17. package/dist/{chunk-UZ6XPUBD.js → chunk-RMYKVZIZ.js} +78 -0
  18. package/dist/{chunk-N5XTLNKS.js → chunk-SPNWUUHA.js} +257 -19
  19. package/dist/{chunk-PGKV24QN.js → chunk-TBJUSUKF.js} +1 -1
  20. package/dist/{chunk-FCPVQFTQ.js → chunk-VYTQLZAX.js} +78 -0
  21. package/dist/cli.js +45 -16
  22. package/dist/daemon-main.js +581 -157
  23. package/dist/{human-interaction-CTZ4IWXJ.js → human-interaction-ISMMOJOK.js} +2 -2
  24. package/dist/{human-interaction-HJCK45SL.js → human-interaction-STTZZZ5N.js} +1 -1
  25. package/dist/{human-interaction-V3VDGHHI.js → human-interaction-UXFYV7DU.js} +1 -1
  26. package/dist/index.d.ts +106 -12
  27. package/dist/index.js +195 -46
  28. package/dist/{recovery-EBKORYEU.js → recovery-JFGV3DBX.js} +1 -1
  29. package/dist/{recovery-5C4FBA5O.js → recovery-ORHJSBDN.js} +2 -2
  30. package/dist/{recovery-IMZUGWSS.js → recovery-XDKN63O5.js} +1 -1
  31. package/dist/{server-ZTI2K5YJ.js → server-TG47W7MV.js} +3 -3
  32. package/dist/{server-LNZTDAKT.js → server-U3YAX5MJ.js} +2 -2
  33. package/dist/{session-recorder-DF2YGH2E.js → session-recorder-N7VEKJVW.js} +1 -1
  34. package/dist/{session-recorder-R3GDGXLJ.js → session-recorder-RUNQOJ7T.js} +1 -1
  35. package/dist/{session-replayer-CLTZ2URU.js → session-replayer-XLWQ47BB.js} +1 -1
  36. package/package.json +4 -1
@@ -15,7 +15,7 @@ import {
15
15
  import {
16
16
  ScreencastCapturer,
17
17
  resolveScreenshotsDir
18
- } from "./chunk-HBMEFSTB.js";
18
+ } from "./chunk-QCV2PI7U.js";
19
19
  import "./chunk-CG3D3CHY.js";
20
20
  import {
21
21
  commandLogStore,
@@ -24,7 +24,7 @@ import {
24
24
  } from "./chunk-VEDJ5XSQ.js";
25
25
  import {
26
26
  SessionRecorder
27
- } from "./chunk-FCPVQFTQ.js";
27
+ } from "./chunk-VYTQLZAX.js";
28
28
  import {
29
29
  closeEphemeralContext,
30
30
  closeSessionByName,
@@ -39,10 +39,10 @@ import {
39
39
  resolveLaunchOpts,
40
40
  saveSessionDiskMeta,
41
41
  setActivePage
42
- } from "./chunk-CO2ZVOVT.js";
42
+ } from "./chunk-NINETOM4.js";
43
43
  import {
44
44
  createRuleEngine
45
- } from "./chunk-NQPXZ74W.js";
45
+ } from "./chunk-OCECE22C.js";
46
46
  import {
47
47
  queryJS
48
48
  } from "./chunk-A7NEA4PA.js";
@@ -140,6 +140,7 @@ function registerCommand(def) {
140
140
  parameters: def.parameters,
141
141
  result: def.result,
142
142
  selectorParams: def.selectorParams,
143
+ examples: def.examples,
143
144
  handler: def.handler
144
145
  };
145
146
  registry.set(cmd.name, cmd);
@@ -371,14 +372,23 @@ var clickCommand = registerCommand({
371
372
  clickCount: z2.number().optional(),
372
373
  delay: z2.number().optional(),
373
374
  waitCaptcha: z2.boolean().optional().default(false).describe("\u70B9\u51FB\u540E\u68C0\u6D4B captcha \u5E76\u7B49\u5F85\u89E3\u51B3"),
374
- waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09")
375
+ waitCaptchaTimeout: z2.number().int().optional().default(18e4).describe("Captcha \u7B49\u5F85\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09"),
376
+ frame: z2.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u9009\u62E9\u5668\u5728\u8DE8\u57DF iframe \u7684 DOM \u5185\u89E3\u6790\u5E76\u70B9\u51FB\uFF08\u8FDB\u7A0B\u9694\u79BB\u4E0B\u552F\u4E00\u53EF\u4FE1\u901A\u9053\uFF09")
375
377
  }),
376
378
  result: z2.object({
377
379
  selector: z2.string(),
378
380
  newTab: z2.object({ url: z2.string(), title: z2.string() }).optional(),
379
- captcha: z2.any().optional()
381
+ captcha: z2.any().optional(),
382
+ frame: z2.string().optional(),
383
+ x: z2.number().optional(),
384
+ y: z2.number().optional()
380
385
  }),
381
386
  handler: async (p, ctx) => {
387
+ const frameTarget = p.frame ?? ctx.frame;
388
+ if (frameTarget) {
389
+ const { x, y } = await ctx.page.clickInFrame(frameTarget, p.selector);
390
+ return ok2({ selector: p.selector, frame: frameTarget, x, y });
391
+ }
382
392
  let detectedNewPage;
383
393
  let cleanup;
384
394
  if (ctx.browserContext?.on) {
@@ -469,15 +479,22 @@ var fillCommand = registerCommand({
469
479
  parameters: z2.object({
470
480
  selector: z2.string(),
471
481
  value: z2.string(),
472
- clear: z2.boolean().optional()
482
+ clear: z2.boolean().optional(),
483
+ frame: z2.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u5728\u8DE8\u57DF iframe \u5185\u586B\u5165\uFF08\u805A\u7126\u70B9\u51FB + insertText + \u56DE\u8BFB\uFF09")
473
484
  }),
474
485
  result: z2.object({
475
486
  selector: z2.string(),
476
487
  value: z2.string(),
477
488
  cleared: z2.boolean(),
478
- reactMode: z2.boolean().optional()
489
+ reactMode: z2.boolean().optional(),
490
+ frame: z2.string().optional()
479
491
  }),
480
492
  handler: async (p, ctx) => {
493
+ const frameTarget = p.frame ?? ctx.frame;
494
+ if (frameTarget) {
495
+ const { value } = await ctx.page.fillInFrame(frameTarget, p.selector, p.value);
496
+ return ok2({ selector: p.selector, value, cleared: true, frame: frameTarget });
497
+ }
481
498
  const page = ctx.page;
482
499
  const shouldClear = p.clear !== false;
483
500
  if (shouldClear) {
@@ -664,15 +681,22 @@ var textCommand = registerCommand({
664
681
  scope: "page",
665
682
  selectorParams: ["selector"],
666
683
  parameters: z3.object({
667
- selector: z3.string().optional()
684
+ selector: z3.string().optional(),
685
+ frame: z3.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u5728\u8DE8\u57DF iframe \u7684 DOM \u5185\u8BFB\u53D6\u6587\u672C")
668
686
  }),
669
- result: z3.object({ text: z3.string() }),
687
+ result: z3.object({ text: z3.string(), frame: z3.string().optional() }),
670
688
  handler: async (p, ctx) => {
689
+ const frameTarget = p.frame ?? ctx.frame;
690
+ if (frameTarget) {
691
+ const expr = p.selector ? `(() => { const el = document.querySelector(${JSON.stringify(p.selector)}); return el ? (el.textContent ?? '').trim() : null; })()` : `(document.body?.innerText || '').trim()`;
692
+ const text2 = await ctx.page.evaluateInFrame(frameTarget, expr);
693
+ return ok3({ text: text2 || "", frame: frameTarget });
694
+ }
671
695
  if (p.selector) {
672
696
  const text2 = await ctx.page.textContent(p.selector);
673
697
  return ok3({ text: text2 || "" });
674
698
  }
675
- const text = await ctx.page.evaluate(() => document.body?.innerText || "");
699
+ const text = await ctx.page.evaluate(() => (document.body?.innerText || "").trim());
676
700
  return ok3({ text });
677
701
  }
678
702
  });
@@ -796,43 +820,64 @@ import { z as z6 } from "zod";
796
820
  import { ok as ok6 } from "@dyyz1993/xcli-core";
797
821
  var mouseCommand = registerCommand({
798
822
  name: "mouse",
799
- description: "Control the mouse (move, click, etc.)",
823
+ description: "Control the mouse (move, click, wheel, etc.) (--frame <url-substring> \u65F6\u5728\u8DE8\u57DF iframe \u5185\u64CD\u4F5C\uFF0C\u5750\u6807\u4E3A iframe \u5C40\u90E8\u5750\u6807)",
800
824
  scope: "page",
801
825
  parameters: z6.object({
802
- action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
826
+ action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
803
827
  x: z6.coerce.number(),
804
828
  y: z6.coerce.number(),
829
+ "delta-x": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u6A2A\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u53F3\uFF09"),
830
+ "delta-y": z6.coerce.number().optional().describe("wheel \u52A8\u4F5C\uFF1A\u7EB5\u5411\u6EDA\u52A8\u91CF\uFF08\u6B63\u503C\u5411\u4E0B\uFF09"),
805
831
  button: z6.enum(["left", "right", "middle"]).optional(),
806
- steps: z6.coerce.number().optional()
832
+ steps: z6.coerce.number().optional(),
833
+ frame: z6.string().optional().describe("URL \u542B\u6B64\u5B50\u4E32\u7684 OOPIF\u2014\u2014\u8F93\u5165\u6D3E\u53D1\u5230 iframe \u81EA\u5DF1\u7684 session\uFF08\u8DE8\u57DF iframe \u552F\u4E00\u53EF\u4FE1\u901A\u9053\uFF09\uFF0C\u5750\u6807\u7528 iframe \u5C40\u90E8\u5750\u6807\u7CFB")
807
834
  }),
808
835
  result: z6.object({
809
- action: z6.enum(["move", "down", "up", "click", "dblclick", "drag"]),
836
+ action: z6.enum(["move", "down", "up", "click", "dblclick", "drag", "wheel"]),
810
837
  x: z6.number(),
811
838
  y: z6.number()
812
839
  }),
813
840
  handler: async (p, ctx) => {
814
841
  const button = p.button || "left";
815
- switch (p.action) {
816
- case "move":
817
- await ctx.page.mouse.move(p.x, p.y, { steps: p.steps || 1 });
818
- break;
819
- case "down":
820
- await ctx.page.mouse.move(p.x, p.y);
821
- await ctx.page.mouse.down({ button });
822
- break;
823
- case "up":
824
- await ctx.page.mouse.move(p.x, p.y);
825
- await ctx.page.mouse.up({ button });
826
- break;
827
- case "click":
828
- await ctx.page.mouse.click(p.x, p.y, { button });
829
- break;
830
- case "dblclick":
831
- await ctx.page.mouse.dblclick(p.x, p.y, { button });
832
- break;
833
- case "drag":
834
- await ctx.page.mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
835
- break;
842
+ const frame = p.frame ?? ctx.frame;
843
+ const dispatch = async (mouse) => {
844
+ switch (p.action) {
845
+ case "move":
846
+ await mouse.move(p.x, p.y, { steps: p.steps || 1 });
847
+ break;
848
+ case "down":
849
+ await mouse.move(p.x, p.y);
850
+ await mouse.down({ button });
851
+ break;
852
+ case "up":
853
+ await mouse.move(p.x, p.y);
854
+ await mouse.up({ button });
855
+ break;
856
+ case "click":
857
+ await mouse.click(p.x, p.y, { button });
858
+ break;
859
+ case "dblclick":
860
+ await mouse.dblclick(p.x, p.y, { button });
861
+ break;
862
+ case "drag":
863
+ await mouse.drag(p.x, p.y, p.steps ? { steps: p.steps } : {});
864
+ break;
865
+ case "wheel":
866
+ await mouse.wheelAt(p.x, p.y, Number(p["delta-x"] ?? 0), Number(p["delta-y"] ?? 0));
867
+ break;
868
+ }
869
+ };
870
+ if (frame) {
871
+ try {
872
+ await ctx.page.runFrameMouse(frame, dispatch);
873
+ } catch (err) {
874
+ if (p.action === "drag" && /session/i.test(String(err))) {
875
+ throw new Error(`frame session \u5728\u62D6\u52A8\u4E2D\u5931\u6548\uFF08iframe \u53EF\u80FD\u5DF2\u91CD\u5EFA\uFF09\u2014\u2014\u91CD\u65B0\u7528 eval --frame \u8BFB\u53D6\u76EE\u6807\u5750\u6807\u540E\u518D\u62D6`);
876
+ }
877
+ throw err;
878
+ }
879
+ } else {
880
+ await dispatch(ctx.page.mouse);
836
881
  }
837
882
  return ok6({ action: p.action, x: p.x, y: p.y });
838
883
  }
@@ -1274,7 +1319,8 @@ var evaluateCommand = registerCommand({
1274
1319
  direction: "client\u2192browser"
1275
1320
  });
1276
1321
  engine.stop();
1277
- const result = p.frame ? await ctx.page.evaluateInFrame(p.frame, expression) : await ctx.page.evaluate(expression);
1322
+ const frame = p.frame ?? ctx.frame;
1323
+ const result = frame ? await ctx.page.evaluateInFrame(frame, expression) : await ctx.page.evaluate(expression);
1278
1324
  const response = ok9({ result });
1279
1325
  if (decision && decision.severity === "danger") {
1280
1326
  response.tips = normalizeTips2([`${decision.suggestion}`]);
@@ -1703,24 +1749,98 @@ import { z as z16 } from "zod";
1703
1749
  import { ok as ok16, fail as fail7 } from "@dyyz1993/xcli-core";
1704
1750
  var framesCommand = registerCommand({
1705
1751
  name: "frames",
1706
- description: "List all frames in the current page",
1752
+ description: "List all frames in the current page (\u542B\u8DE8\u57DF OOPIF\u2014\u2014\u5B83\u4EEC\u53EA\u5728\u6D4F\u89C8\u5668\u7EA7 target \u5217\u8868\u53EF\u89C1\uFF1B\u9644 parentUrl/depth \u5C42\u7EA7)",
1707
1753
  scope: "page",
1708
1754
  result: z16.object({
1709
1755
  frames: z16.array(z16.object({
1710
1756
  index: z16.number(),
1711
1757
  name: z16.string().nullable(),
1712
- url: z16.string()
1713
- }))
1758
+ url: z16.string(),
1759
+ oopif: z16.boolean().optional(),
1760
+ targetId: z16.string().optional(),
1761
+ parentUrl: z16.string().nullable().optional(),
1762
+ depth: z16.number().nullable().optional()
1763
+ })),
1764
+ warnings: z16.array(z16.string()).optional()
1714
1765
  }),
1715
1766
  handler: async (_p, ctx) => {
1716
1767
  const discover = ctx.page.discoverFrames;
1717
1768
  const rawFrames = discover ? await discover.call(ctx.page) : ctx.page.frames();
1769
+ const mainUrl = ctx.page.url();
1718
1770
  const frameList = rawFrames.map((frame, index) => ({
1719
1771
  index,
1720
1772
  name: frame.name(),
1721
- url: frame.url()
1773
+ url: frame.url(),
1774
+ parentUrl: null,
1775
+ depth: null
1722
1776
  }));
1723
- return ok16({ frames: frameList });
1777
+ const norm = (u) => u.replace(/\/+$/, "");
1778
+ for (const e of frameList) {
1779
+ if (norm(e.url) === norm(mainUrl)) {
1780
+ e.parentUrl = null;
1781
+ e.depth = 0;
1782
+ }
1783
+ }
1784
+ if (typeof ctx.page.listFrameTargets === "function") {
1785
+ const targets = await ctx.page.listFrameTargets();
1786
+ const knownUrls = new Set(frameList.map((f) => f.url));
1787
+ for (const t of targets) {
1788
+ if (knownUrls.has(t.url)) continue;
1789
+ frameList.push({ index: frameList.length, name: null, url: t.url, oopif: true, targetId: t.targetId, parentUrl: null, depth: null });
1790
+ }
1791
+ }
1792
+ const warnings = [];
1793
+ try {
1794
+ const CHILDREN = `JSON.stringify([...document.querySelectorAll('iframe')].map(f=>({src:f.src||'',name:f.name||''})))`;
1795
+ const matchChild = (childSrc, frameUrl) => {
1796
+ const a = norm(childSrc);
1797
+ const b = norm(frameUrl);
1798
+ return Boolean(a && b && (a === b || a.includes(b) || b.includes(a)));
1799
+ };
1800
+ const childrenCache = /* @__PURE__ */ new Map();
1801
+ const childrenOf = async (url) => {
1802
+ const hit = childrenCache.get(url);
1803
+ if (hit) return hit;
1804
+ let out = [];
1805
+ try {
1806
+ const raw = norm(url) === norm(mainUrl) ? await ctx.page.evaluate(CHILDREN) : await ctx.page.evaluateInFrame(url, CHILDREN);
1807
+ out = JSON.parse(String(raw || "[]"));
1808
+ } catch {
1809
+ }
1810
+ childrenCache.set(url, out);
1811
+ return out;
1812
+ };
1813
+ let frontier = frameList.filter((e) => e.depth === 0).map((e) => ({ url: e.url, depth: 0 }));
1814
+ for (let depth = 0; frontier.length > 0 && frameList.some((e) => e.depth === null) && depth < 6; depth++) {
1815
+ const next = [];
1816
+ for (const node of frontier) {
1817
+ const kids = await childrenOf(node.url);
1818
+ if (kids.length === 0) continue;
1819
+ for (const e of frameList) {
1820
+ if (e.depth !== null) continue;
1821
+ if (kids.some((k) => matchChild(k.src, e.url))) {
1822
+ e.parentUrl = node.url;
1823
+ e.depth = node.depth + 1;
1824
+ next.push({ url: e.url, depth: e.depth });
1825
+ }
1826
+ }
1827
+ }
1828
+ frontier = next;
1829
+ }
1830
+ } catch {
1831
+ }
1832
+ const urls = frameList.map((e) => e.url);
1833
+ for (let i = 0; i < urls.length; i++) {
1834
+ for (let j = i + 1; j < urls.length; j++) {
1835
+ const a = urls[i];
1836
+ const b = urls[j];
1837
+ if (a && b && (a.includes(b) || b.includes(a))) {
1838
+ const shorter = a.includes(b) ? b : a;
1839
+ warnings.push(`URL \u5B50\u4E32\u6B67\u4E49\uFF1A"${shorter}" \u540C\u65F6\u547D\u4E2D ${a} \u548C ${b}\u2014\u2014--frame \u8BF7\u5199\u66F4\u957F/\u66F4\u7CBE\u786E\u7684\u5B50\u4E32`);
1840
+ }
1841
+ }
1842
+ }
1843
+ return ok16({ frames: frameList, warnings });
1724
1844
  }
1725
1845
  });
1726
1846
  var frameCommand = registerCommand({
@@ -3279,8 +3399,26 @@ async function detectSpaRoutes(page, origin) {
3279
3399
  }
3280
3400
  } catch {
3281
3401
  }
3402
+ try {
3403
+ const vueRoutes = await page.evaluate((evalOrigin) => {
3404
+ const win = window;
3405
+ const vue3App = win.__vue_app__;
3406
+ const globalProperties = vue3App?.config?.globalProperties;
3407
+ let router = globalProperties?.$router;
3408
+ if (!router) {
3409
+ const root = document.querySelector("#app");
3410
+ const vm = root ? root.__vue__ : void 0;
3411
+ const rootVm = vm?.$root;
3412
+ router = vm?.$router ?? rootVm?.$router;
3413
+ }
3414
+ const routeList = router?.options?.routes ?? [];
3415
+ return routeList.filter((route) => route.path && route.path !== "/" && !route.path.includes(":") && !route.path.includes("*")).map((route) => `${evalOrigin.replace(/\/$/, "")}/#${route.path}`);
3416
+ }, origin);
3417
+ for (const route of vueRoutes) routeSet.add(route);
3418
+ } catch {
3419
+ }
3282
3420
  return Array.from(routeSet).map(
3283
- (p) => `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
3421
+ (p) => p.startsWith("http") ? p : `${origin.replace(/\/$/, "")}${p.startsWith("/") ? "" : "/"}${p}`
3284
3422
  );
3285
3423
  }
3286
3424
  function parseRobotsTxt(text) {
@@ -3473,7 +3611,14 @@ var crawlCommand = registerCommand({
3473
3611
  results.push({ url: seedPage.url(), title, content });
3474
3612
  const firstLinks = await extractLinks(seedPage, startUrl.origin);
3475
3613
  if (options.enableSpa) {
3476
- const spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
3614
+ let spaRoutes = [];
3615
+ try {
3616
+ spaRoutes = await detectSpaRoutes(seedPage, startUrl.origin);
3617
+ } catch (error) {
3618
+ const message = error instanceof Error ? error.message : String(error);
3619
+ process.stderr.write(`[SPA] Route detection failed: ${message}
3620
+ `);
3621
+ }
3477
3622
  for (const route of spaRoutes) {
3478
3623
  try {
3479
3624
  const absNorm = normalizeUrl(stripHashAnchorQuery(route));
@@ -4622,25 +4767,6 @@ function getRefTarget(sessionKey2, ref) {
4622
4767
  if (!session || !target) return null;
4623
4768
  return { screenHash: session.screenHash, target };
4624
4769
  }
4625
- function inheritStableRefs(key, rawTargets) {
4626
- const prev = sessions.get(key);
4627
- if (!prev || prev.targets.size === 0) {
4628
- return rawTargets.map((target, index) => ({ ...target, ref: `e${index + 1}` }));
4629
- }
4630
- const bySelector = /* @__PURE__ */ new Map();
4631
- let maxId = 0;
4632
- for (const [ref, target] of prev.targets) {
4633
- bySelector.set(target.selector, ref);
4634
- const id = Number(ref.slice(1));
4635
- if (Number.isFinite(id) && id > maxId) maxId = id;
4636
- }
4637
- let next = maxId + 1;
4638
- return rawTargets.map((target) => {
4639
- const inherited = bySelector.get(target.selector);
4640
- if (inherited) return { ...target, ref: inherited };
4641
- return { ...target, ref: `e${next++}` };
4642
- });
4643
- }
4644
4770
 
4645
4771
  // src/utils/resolve-selector.ts
4646
4772
  function buildElementSelector(el) {
@@ -5203,14 +5329,6 @@ async function observePage(page, sessionId, options = {}) {
5203
5329
  const direct = el.getAttribute("aria-label") || el.getAttribute("placeholder") || el.getAttribute("title") || input.value || el.textContent || "";
5204
5330
  return direct.replace(/\s+/g, " ").trim().slice(0, 120);
5205
5331
  }
5206
- function actionsFor(role, editable) {
5207
- const actions = [];
5208
- if (editable) actions.push("fill", "type");
5209
- if (role === "combobox") actions.push("select");
5210
- if (role === "checkbox" || role === "radio") actions.push("check");
5211
- actions.push("click", "hover");
5212
- return Array.from(new Set(actions));
5213
- }
5214
5332
  const selector = [
5215
5333
  "a[href]",
5216
5334
  "button",
@@ -5221,7 +5339,14 @@ async function observePage(page, sessionId, options = {}) {
5221
5339
  "label",
5222
5340
  "[role]",
5223
5341
  "[tabindex]",
5224
- '[contenteditable="true"]'
5342
+ '[contenteditable="true"]',
5343
+ // 非标准可交互控件:内联事件属性(agent-browser 基于 aria tree 完全不覆盖这类)。
5344
+ // 仅抓 HTML 显式声明 onclick/onmousedown 等的元素;addEventListener 绑定的无法静态发现。
5345
+ "[onclick]",
5346
+ "[onmousedown]",
5347
+ "[onmouseup]",
5348
+ "[onmouseover]",
5349
+ "[onkeydown]"
5225
5350
  ].join(",");
5226
5351
  const candidates = Array.from(document.querySelectorAll(selector));
5227
5352
  const seen = /* @__PURE__ */ new Set();
@@ -5245,13 +5370,10 @@ async function observePage(page, sessionId, options = {}) {
5245
5370
  role,
5246
5371
  name: textName(el),
5247
5372
  tag,
5248
- visible,
5249
5373
  enabled,
5250
5374
  editable,
5251
5375
  ...checked !== void 0 ? { checked } : {},
5252
- ...editable && input.value ? { value: input.value.slice(0, 120) } : {},
5253
- ...visible ? { box: { x: Math.round(rect.x), y: Math.round(rect.y), width: Math.round(rect.width), height: Math.round(rect.height) } } : {},
5254
- actions: actionsFor(role, editable)
5376
+ ...editable && input.value ? { value: input.value.slice(0, 120) } : {}
5255
5377
  });
5256
5378
  if (targets2.length >= limit) break;
5257
5379
  }
@@ -5265,13 +5387,15 @@ async function observePage(page, sessionId, options = {}) {
5265
5387
  { includeHidden: !!options.includeHidden, limit: options.limit ?? 80 }
5266
5388
  )
5267
5389
  ]);
5268
- const targets = inheritStableRefs(sessionKey(sessionId), raw.targets);
5390
+ const targets = raw.targets.map((target, index) => ({
5391
+ ref: `e${index + 1}`,
5392
+ ...target
5393
+ }));
5269
5394
  replaceRefs(sessionKey(sessionId), raw.screenHash, targets);
5270
5395
  return {
5271
5396
  url: page.url(),
5272
5397
  title,
5273
5398
  screenHash: raw.screenHash,
5274
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
5275
5399
  targets
5276
5400
  };
5277
5401
  }
@@ -5456,23 +5580,8 @@ async function waitForPage(page, input) {
5456
5580
  return { success: true, matched: "selector", timeout, elapsed: Date.now() - startedAt };
5457
5581
  }
5458
5582
  if (input.text) {
5459
- const textToFind = input.text;
5460
- const matched = await pollUntil(timeout, pollInterval, async () => {
5461
- return page.evaluate((text) => {
5462
- const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
5463
- while (walker.nextNode()) {
5464
- if (walker.currentNode.textContent?.includes(text)) return true;
5465
- }
5466
- return false;
5467
- }, textToFind);
5468
- });
5469
- return {
5470
- success: matched,
5471
- matched: "text",
5472
- timeout,
5473
- elapsed: Date.now() - startedAt,
5474
- ...matched ? {} : { message: `Timed out waiting for text: ${input.text}` }
5475
- };
5583
+ await page.getByText(input.text).first().waitFor({ state: "visible", timeout });
5584
+ return { success: true, matched: "text", timeout, elapsed: Date.now() - startedAt };
5476
5585
  }
5477
5586
  if (input.url) {
5478
5587
  const matched = await pollUntil(timeout, pollInterval, async () => matchUrlPattern(page.url(), input.url));
@@ -5528,20 +5637,48 @@ async function waitForPage(page, input) {
5528
5637
  // src/commands/snapshot.ts
5529
5638
  var snapshotCommand = registerCommand({
5530
5639
  name: "snapshot",
5531
- description: "Capture a quick page state snapshot \u2014 aria tree, visible text, or DOM summary",
5640
+ description: "Get page state: interactive @refs to operate (default); --type aria=page outline; --type text=content; --type dom=debug DOM",
5532
5641
  scope: "page",
5533
5642
  selectorParams: ["selector"],
5643
+ examples: [
5644
+ {
5645
+ cmd: "xbrowser snapshot",
5646
+ description: "I want to OPERATE the page \u2192 returns clickable/fillable @refs (use click @e1, fill @e2)",
5647
+ output: '@e1 [button] "Submit"\n@e2 [textbox editable] "Email"'
5648
+ },
5649
+ {
5650
+ cmd: "xbrowser snapshot --type aria",
5651
+ description: "I want the page OUTLINE/skeleton (nav, heading hierarchy, regions)",
5652
+ output: 'banner:\n navigation:\n link "Home"\nmain:\n heading "Welcome"'
5653
+ },
5654
+ {
5655
+ cmd: "xbrowser snapshot --type text",
5656
+ description: "I want the page TEXT CONTENT (extract body copy/information)",
5657
+ output: "Welcome\nPlease enter your email\nSubmit"
5658
+ },
5659
+ {
5660
+ cmd: "xbrowser snapshot --type dom",
5661
+ description: "I want to DEBUG the DOM (tag names, attributes, nesting)"
5662
+ },
5663
+ {
5664
+ cmd: "xbrowser snapshot --selectors",
5665
+ description: "I want to operate AND need stable CSS selectors (reuse across sessions)",
5666
+ output: "e1: #submit | e2: #email"
5667
+ }
5668
+ ],
5534
5669
  parameters: z25.object({
5535
- type: z25.enum(["aria", "text", "dom", "all"]).default("aria").describe("Snapshot type: aria (accessibility tree), text (visible text), dom (element summary), all (combined)"),
5536
- selector: z25.string().optional().describe("Scope to a specific element"),
5537
- depth: z25.number().optional().default(6).describe("Max depth for DOM/aria tree"),
5538
- interactive: z25.boolean().optional().default(false).describe("Return interactive agent refs only"),
5539
- interactiveOnly: z25.boolean().optional().default(false).describe("Alias for interactive"),
5540
- i: z25.boolean().optional().default(false).describe("Short alias for interactive"),
5541
- compact: z25.boolean().optional().default(false).describe("Include compact xbrowser style snapshot text"),
5542
- c: z25.boolean().optional().default(false).describe("Short alias for compact"),
5543
- selectors: z25.boolean().optional().default(false).describe("Include ref to CSS selector map"),
5544
- all: z25.boolean().optional().default(false).describe("Include hidden interactive targets when using interactive snapshot")
5670
+ type: z25.enum(["interactive", "aria", "text", "dom", "all"]).default("interactive").describe(
5671
+ "Choose by intent: interactive(default)=operate page, get @refs of clickable/fillable elements; aria=page outline (nav/headings/regions); text=page text content; dom=debug DOM tags/attrs; all=everything"
5672
+ ),
5673
+ selector: z25.string().optional().describe("\u9650\u5B9A\u5230\u67D0\u4E2A\u5143\u7D20\uFF08CSS \u9009\u62E9\u5668\uFF09\uFF0C\u53EA\u5FEB\u7167\u8BE5\u5B50\u6811"),
5674
+ depth: z25.number().optional().default(6).describe("aria/dom \u6811\u7684\u6700\u5927\u6DF1\u5EA6"),
5675
+ interactive: z25.boolean().optional().default(false).describe("\u5F3A\u5236 interactive \u6A21\u5F0F\uFF08\u7B49\u540C --type interactive\uFF0C\u517C\u5BB9 -i\uFF09"),
5676
+ interactiveOnly: z25.boolean().optional().default(false).describe("interactive \u7684\u522B\u540D"),
5677
+ i: z25.boolean().optional().default(false).describe("interactive \u7684\u77ED\u522B\u540D"),
5678
+ compact: z25.boolean().optional().default(false).describe("\u9644\u5E26\u7D27\u51D1\u6587\u672C\u5FEB\u7167\uFF08interactive \u6A21\u5F0F\u9ED8\u8BA4\u5DF2\u542B\uFF09"),
5679
+ c: z25.boolean().optional().default(false).describe("compact \u7684\u77ED\u522B\u540D"),
5680
+ selectors: z25.boolean().optional().describe("\u9644\u5E26 ref \u2192 CSS \u9009\u62E9\u5668\u6620\u5C04\uFF08\u9700\u8981\u7A33\u5B9A\u9009\u62E9\u5668\u65F6\u5F00\uFF09"),
5681
+ all: z25.boolean().optional().default(false).describe("interactive \u6A21\u5F0F\u4E0B\u8FDE\u9690\u85CF\u5143\u7D20\u4E00\u8D77\u91C7\u96C6\uFF08\u6CE8\u610F\uFF1A\u8FD9\u662F\u91C7\u96C6\u8303\u56F4\uFF0C\u4E0D\u662F --type all \u7684\u5408\u5E76\u5FEB\u7167\uFF09")
5545
5682
  }),
5546
5683
  result: z25.object({
5547
5684
  url: z25.string(),
@@ -5554,14 +5691,13 @@ var snapshotCommand = registerCommand({
5554
5691
  const page = ctx.page;
5555
5692
  const url = page.url();
5556
5693
  const title = await page.title().catch(() => "");
5557
- if (p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors) {
5694
+ const wantInteractive = p.type === "interactive" || p.interactive || p.interactiveOnly || p.i || p.compact || p.c || p.selectors;
5695
+ if (wantInteractive) {
5558
5696
  const observation = await observePage(page, ctx.sessionId, {
5559
5697
  includeHidden: p.all
5560
5698
  });
5561
5699
  if (p.selectors) observation.selectors = buildSelectorMap(observation);
5562
- if (p.compact || p.c || p.interactive || p.interactiveOnly || p.i) {
5563
- observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5564
- }
5700
+ observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5565
5701
  return ok24(observation, normalizeTips3([
5566
5702
  `refs refreshed for ${observation.targets.length} targets; use click @e1 or fill @e2 "text"`
5567
5703
  ]));
@@ -5581,14 +5717,20 @@ var snapshotCommand = registerCommand({
5581
5717
  return ok24({ url, title, dom });
5582
5718
  }
5583
5719
  if (p.type === "all") {
5584
- const [aria, text, dom] = await Promise.all([
5720
+ const [observation, aria, text, dom] = await Promise.all([
5721
+ observePage(page, ctx.sessionId, { includeHidden: p.all }),
5585
5722
  captureAriaSnapshot(page, p.selector, p.depth),
5586
5723
  captureTextSnapshot(page, p.selector),
5587
5724
  captureDomSnapshot(page, p.selector, p.depth ?? 6)
5588
5725
  ]);
5726
+ observation.compact = formatObservationCompact(observation, { selectors: p.selectors });
5727
+ if (p.selectors) observation.selectors = buildSelectorMap(observation);
5589
5728
  const tips = await buildRefTips(page, aria);
5590
5729
  persistSemantics(url, aria);
5591
- return ok24({ url, title, aria, text, dom }, normalizeTips3(tips));
5730
+ return ok24({ ...observation, aria, text, dom }, normalizeTips3([
5731
+ ...tips,
5732
+ `${observation.targets.length} interactive targets + aria + text + dom combined`
5733
+ ]));
5592
5734
  }
5593
5735
  return fail11(`Unknown snapshot type: ${p.type}`);
5594
5736
  }
@@ -5617,16 +5759,29 @@ async function buildRefTips(page, aria) {
5617
5759
  }
5618
5760
  }
5619
5761
  async function captureAriaSnapshot(page, selector, _depth) {
5762
+ let raw;
5620
5763
  try {
5621
5764
  const locator = selector ? page.locator(selector).first() : page.locator("body");
5622
- return await locator.ariaSnapshot();
5765
+ raw = await locator.ariaSnapshot();
5623
5766
  } catch {
5624
5767
  try {
5625
- return await page.locator("body").ariaSnapshot();
5768
+ raw = await page.locator("body").ariaSnapshot();
5626
5769
  } catch {
5627
5770
  return "(aria snapshot not available)";
5628
5771
  }
5629
5772
  }
5773
+ return filterAriaNoise(raw);
5774
+ }
5775
+ function filterAriaNoise(raw) {
5776
+ return raw.split("\n").filter((line) => {
5777
+ const t = line.trim();
5778
+ if (!t) return false;
5779
+ if (t === "none:" || t.startsWith("none: ")) return false;
5780
+ if (t.includes("InlineTextBox")) return false;
5781
+ if (t.includes("ListMarker")) return false;
5782
+ if (/^[a-z]+$/.test(t) || /^[a-z]+:$/.test(t)) return false;
5783
+ return true;
5784
+ }).join("\n");
5630
5785
  }
5631
5786
  async function captureTextSnapshot(page, selector) {
5632
5787
  if (selector) {
@@ -7465,6 +7620,9 @@ var TipGenerator = class {
7465
7620
  categoryLabel(category) {
7466
7621
  const labels = {
7467
7622
  dialog: "Dialog",
7623
+ filechooser: "File Chooser",
7624
+ popup: "Popup",
7625
+ download: "Download",
7468
7626
  modal: "Modal",
7469
7627
  popover: "Popover",
7470
7628
  notification: "\u901A\u77E5",
@@ -7529,8 +7687,62 @@ var TipsManager = class {
7529
7687
  generator = new TipGenerator(this.contextTracker);
7530
7688
  beforeSnapshot = null;
7531
7689
  lastDetectionTime = 0;
7690
+ // CDP 弹窗事件检测(filechooser / dialog / popup)
7691
+ detectedEvents = [];
7692
+ eventListenersAttached = false;
7693
+ lastCommandName = "";
7532
7694
  async beforeCommand(page, commandName, params) {
7533
7695
  this.contextTracker.record(commandName, params);
7696
+ this.lastCommandName = commandName;
7697
+ if (!this.eventListenersAttached && typeof page.on === "function") {
7698
+ this.eventListenersAttached = true;
7699
+ page.on("dialog", (dialog) => {
7700
+ const d = dialog;
7701
+ try {
7702
+ this.detectedEvents.push({
7703
+ type: "dialog",
7704
+ message: `[${d.type()}] ${d.message().slice(0, 200)}`,
7705
+ commandName: this.lastCommandName
7706
+ });
7707
+ } catch {
7708
+ }
7709
+ });
7710
+ page.on("filechooser", (chooser) => {
7711
+ const c = chooser;
7712
+ try {
7713
+ this.detectedEvents.push({
7714
+ type: "filechooser",
7715
+ message: `\u6587\u4EF6\u9009\u62E9\u5F39\u7A97${c.isMultiple ? "\uFF08\u591A\u9009\uFF09" : ""}\uFF1Aselector=${c.selector || "input[type=file]"}`,
7716
+ selector: c.selector,
7717
+ commandName: this.lastCommandName
7718
+ });
7719
+ } catch {
7720
+ }
7721
+ });
7722
+ page.on("popup", (info) => {
7723
+ const p = info;
7724
+ try {
7725
+ this.detectedEvents.push({
7726
+ type: "popup",
7727
+ message: `\u65B0\u7A97\u53E3\u5F39\u7A97\uFF1Aurl=${p.url || "(unknown)"}${p.windowName ? ` name=${p.windowName}` : ""}`,
7728
+ commandName: this.lastCommandName
7729
+ });
7730
+ } catch {
7731
+ }
7732
+ });
7733
+ page.on("download", (info) => {
7734
+ const d = info;
7735
+ try {
7736
+ const stateLabel = d.state === "completed" ? "\u5B8C\u6210" : d.state === "canceled" ? "\u53D6\u6D88" : "\u5F00\u59CB";
7737
+ this.detectedEvents.push({
7738
+ type: "download",
7739
+ message: `\u6587\u4EF6\u4E0B\u8F7D${stateLabel}\uFF1A${d.filename || "unknown"}${d.url ? ` (${d.url.slice(0, 80)})` : ""}`,
7740
+ commandName: this.lastCommandName
7741
+ });
7742
+ } catch {
7743
+ }
7744
+ });
7745
+ }
7534
7746
  if (!this.domWatcher) {
7535
7747
  this.domWatcher = new DomWatcher(page);
7536
7748
  }
@@ -7573,20 +7785,59 @@ var TipsManager = class {
7573
7785
  }
7574
7786
  }
7575
7787
  async afterCommand() {
7576
- if (!this.domWatcher || !this.beforeSnapshot) return [];
7788
+ if (!this.domWatcher || !this.beforeSnapshot) {
7789
+ const cdpTips = this.collectCdpEventTips();
7790
+ this.detectedEvents = [];
7791
+ return cdpTips;
7792
+ }
7577
7793
  await this.debounce();
7578
7794
  try {
7579
7795
  const currentElements = await this.domWatcher.scanOverlays();
7580
7796
  const afterSnapshot = buildSnapshot(currentElements);
7581
7797
  const newElements = this.generator.diff(this.beforeSnapshot, afterSnapshot, currentElements);
7582
7798
  const tips = this.generator.generate(newElements);
7799
+ const cdpTips = this.collectCdpEventTips();
7800
+ tips.push(...cdpTips);
7583
7801
  this.beforeSnapshot = null;
7802
+ this.detectedEvents = [];
7584
7803
  return tips;
7585
7804
  } catch {
7805
+ const cdpTips = this.collectCdpEventTips();
7586
7806
  this.beforeSnapshot = null;
7587
- return [];
7807
+ this.detectedEvents = [];
7808
+ return cdpTips;
7588
7809
  }
7589
7810
  }
7811
+ /**
7812
+ * 把检测到的 CDP 弹窗事件转成 SmartTip
7813
+ * 包括:dialog(alert/confirm/prompt)、filechooser(文件选择弹窗)、popup(新窗口)
7814
+ */
7815
+ collectCdpEventTips() {
7816
+ if (this.detectedEvents.length === 0) return [];
7817
+ return this.detectedEvents.map((evt) => {
7818
+ const suggestions = [];
7819
+ if (evt.type === "dialog") {
7820
+ suggestions.push("\u6B64\u5F39\u7A97\u53EF\u80FD\u963B\u585E\u540E\u7EED\u64CD\u4F5C");
7821
+ suggestions.push('\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 page.on("dialog") \u62E6\u622A');
7822
+ } else if (evt.type === "filechooser") {
7823
+ suggestions.push("\u6B64\u5F39\u7A97\u7531\u9875\u9762\u64CD\u4F5C\u89E6\u53D1\uFF08\u5982\u70B9\u51FB\u4E0A\u4F20\u6309\u94AE\uFF09");
7824
+ suggestions.push("\u5982\u9700\u81EA\u52A8\u5904\u7406\uFF1A\u4F7F\u7528 --path/--paths \u53C2\u6570\u4E0A\u4F20\u6587\u4EF6");
7825
+ } else if (evt.type === "popup") {
7826
+ suggestions.push("\u9875\u9762\u5C1D\u8BD5\u6253\u5F00\u65B0\u7A97\u53E3\uFF08\u53EF\u80FD\u88AB\u6D4F\u89C8\u5668\u62E6\u622A\uFF09");
7827
+ suggestions.push('\u5982\u9700\u5904\u7406\uFF1A\u68C0\u67E5\u5F39\u7A97\u62E6\u622A\u8BBE\u7F6E\u6216\u4F7F\u7528 page.on("popup") \u76D1\u542C');
7828
+ } else if (evt.type === "download") {
7829
+ suggestions.push("\u9875\u9762\u89E6\u53D1\u4E86\u6587\u4EF6\u4E0B\u8F7D");
7830
+ suggestions.push("\u5982\u9700\u63A7\u5236\u8DEF\u5F84\uFF1Apage.setDownloadBehavior(path)");
7831
+ }
7832
+ return {
7833
+ category: evt.type,
7834
+ priority: "p1",
7835
+ message: `\u{1F514} [\u5F39\u7A97\u68C0\u6D4B] ${evt.message}\uFF08\u89E6\u53D1\u547D\u4EE4: ${evt.commandName || "\u672A\u77E5"}\uFF09`,
7836
+ selector: evt.selector,
7837
+ suggestions
7838
+ };
7839
+ });
7840
+ }
7590
7841
  debounce() {
7591
7842
  const ms = tipsDebounceMs();
7592
7843
  if (ms <= 0) return Promise.resolve();
@@ -7607,6 +7858,9 @@ var TipsManager = class {
7607
7858
  this.contextTracker.clear();
7608
7859
  this.domWatcher = null;
7609
7860
  this.lastDetectionTime = 0;
7861
+ this.detectedEvents = [];
7862
+ this.eventListenersAttached = false;
7863
+ this.lastCommandName = "";
7610
7864
  }
7611
7865
  };
7612
7866
  var globalTipsManager = null;
@@ -8091,6 +8345,9 @@ async function executeChain(input, options, executeCommand2) {
8091
8345
  continue;
8092
8346
  }
8093
8347
  const { params } = parseCommandArgs(cmdName, cmdArgs, unquote2);
8348
+ if (options?.frame && params._frame === void 0 && params.frame === void 0) {
8349
+ params._frame = options.frame;
8350
+ }
8094
8351
  if (cmdName === "goto" && params.url) {
8095
8352
  const existing = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
8096
8353
  if (!existing) {
@@ -8346,9 +8603,14 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8346
8603
  const { _tabIndex: _u, ...rest } = params;
8347
8604
  params = rest;
8348
8605
  }
8606
+ const _frame = params._frame;
8607
+ if (_frame) {
8608
+ const { _frame: _u, ...rest } = params;
8609
+ params = rest;
8610
+ }
8349
8611
  let targetPageOverride = null;
8350
8612
  if (_target && extraOpts?.cdpEndpoint) {
8351
- const { findTargetPage } = await import("./browser-OTEMG5NL.js");
8613
+ const { findTargetPage } = await import("./browser-KOUA4ZDA.js");
8352
8614
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8353
8615
  if (!targetPageOverride) {
8354
8616
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8412,6 +8674,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8412
8674
  browserContext: session?.context,
8413
8675
  sessionId: session?.id,
8414
8676
  cdpEndpoint: session?.cdpEndpoint || extraOpts?.cdpEndpoint,
8677
+ frame: _frame,
8415
8678
  args: [],
8416
8679
  options: {},
8417
8680
  cwd: process.cwd(),
@@ -8588,7 +8851,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8588
8851
  });
8589
8852
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
8590
8853
  try {
8591
- const { attemptRecovery } = await import("./recovery-5C4FBA5O.js");
8854
+ const { attemptRecovery } = await import("./recovery-ORHJSBDN.js");
8592
8855
  const recovery = await attemptRecovery(
8593
8856
  session.page,
8594
8857
  sessionName,
@@ -9369,7 +9632,7 @@ function createRPCHandler() {
9369
9632
  return result;
9370
9633
  } catch (err) {
9371
9634
  const errorMessage = errMsg(err);
9372
- const { attemptRecovery } = await import("./recovery-5C4FBA5O.js");
9635
+ const { attemptRecovery } = await import("./recovery-ORHJSBDN.js");
9373
9636
  const recovery = await attemptRecovery(
9374
9637
  session?.page,
9375
9638
  sessionName,
@@ -9934,7 +10197,7 @@ function createRPCHandler() {
9934
10197
  if (isNewFormat) {
9935
10198
  try {
9936
10199
  const replayErrors = [];
9937
- const { SessionReplayer } = await import("./session-replayer-CLTZ2URU.js");
10200
+ const { SessionReplayer } = await import("./session-replayer-XLWQ47BB.js");
9938
10201
  const replayer = new SessionReplayer({
9939
10202
  page: session.page,
9940
10203
  stepDelay: slowMo * 500,
@@ -10178,8 +10441,8 @@ var FrameProcessor = class {
10178
10441
  screencastQuality = 80;
10179
10442
  async process(data, config, viewportWidth, viewportHeight, cropConfig) {
10180
10443
  const buffer = Buffer.from(data, "base64");
10181
- const needsResize = config.scale < 1 && !!viewportWidth && !!viewportHeight;
10182
10444
  const needsCrop = !!cropConfig;
10445
+ const needsResize = needsCrop && !!cropConfig || config.scale < 1 && !!viewportWidth && !!viewportHeight;
10183
10446
  const needsReencode = config.format !== this.screencastFormat || config.quality !== this.screencastQuality;
10184
10447
  if (!needsResize && !needsCrop && !needsReencode) {
10185
10448
  return buffer;
@@ -10208,9 +10471,15 @@ var FrameProcessor = class {
10208
10471
  }
10209
10472
  }
10210
10473
  if (needsResize) {
10211
- const newWidth = Math.round((viewportWidth ?? 0) * config.scale);
10212
- const newHeight = Math.round((viewportHeight ?? 0) * config.scale);
10213
- processed = processed.resize(newWidth, newHeight);
10474
+ const newWidth = Math.round(
10475
+ cropConfig ? cropConfig.width : (viewportWidth ?? 0) * config.scale
10476
+ );
10477
+ const newHeight = Math.round(
10478
+ cropConfig ? cropConfig.height : (viewportHeight ?? 0) * config.scale
10479
+ );
10480
+ if (newWidth > 0 && newHeight > 0) {
10481
+ processed = processed.resize(newWidth, newHeight);
10482
+ }
10214
10483
  }
10215
10484
  if (config.format === "jpeg") {
10216
10485
  processed = processed.jpeg({ quality: config.quality });
@@ -10233,6 +10502,8 @@ var StreamCoordinator = class {
10233
10502
  sink;
10234
10503
  lastFrameData = null;
10235
10504
  lastFrameViewport = null;
10505
+ lastUncroppedFrameData = null;
10506
+ lastUncroppedFrameViewport = null;
10236
10507
  stateManager = new StreamStateManager();
10237
10508
  frameRateController = new FrameRateController();
10238
10509
  frameProcessor = new FrameProcessor();
@@ -10264,6 +10535,8 @@ var StreamCoordinator = class {
10264
10535
  clearLastFrame() {
10265
10536
  this.lastFrameData = null;
10266
10537
  this.lastFrameViewport = null;
10538
+ this.lastUncroppedFrameData = null;
10539
+ this.lastUncroppedFrameViewport = null;
10267
10540
  }
10268
10541
  // -----------------------------------------------------------------------
10269
10542
  // Frame capture callbacks (used by SessionManager)
@@ -10277,15 +10550,16 @@ var StreamCoordinator = class {
10277
10550
  return (frame) => {
10278
10551
  resetStaticSnapshotTimer();
10279
10552
  (async () => {
10280
- this.lastFrameData = frame.data.toString("base64");
10281
- this.lastFrameViewport = frame.viewport;
10553
+ const data = frame.data.toString("base64");
10554
+ this.lastUncroppedFrameData = data;
10555
+ this.lastUncroppedFrameViewport = frame.viewport;
10282
10556
  this.stateManager.onFrameReceived();
10283
10557
  const config = this.stateManager.getConfig();
10284
10558
  if (!this.frameRateController.shouldSendFrame(config.maxFps)) {
10285
10559
  return;
10286
10560
  }
10287
10561
  await this.processAndBroadcast(
10288
- this.lastFrameData,
10562
+ data,
10289
10563
  frame.viewport,
10290
10564
  sessionId,
10291
10565
  frame.sessionId,
@@ -10303,7 +10577,8 @@ var StreamCoordinator = class {
10303
10577
  */
10304
10578
  async takeStaticSnapshot(sessionId, page, clientCount) {
10305
10579
  if (clientCount <= 0) return;
10306
- let viewport = page.viewportSize();
10580
+ const logicalViewport = page.viewportSize();
10581
+ let viewport = logicalViewport;
10307
10582
  if (!viewport) {
10308
10583
  try {
10309
10584
  viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
@@ -10312,10 +10587,11 @@ var StreamCoordinator = class {
10312
10587
  }
10313
10588
  }
10314
10589
  const screenshot = await page.screenshot({ type: "jpeg", quality: 100 });
10315
- this.lastFrameData = screenshot.toString("base64");
10316
- this.lastFrameViewport = viewport;
10590
+ const data = screenshot.toString("base64");
10591
+ this.lastUncroppedFrameData = data;
10592
+ this.lastUncroppedFrameViewport = viewport;
10317
10593
  await this.processAndBroadcast(
10318
- this.lastFrameData,
10594
+ data,
10319
10595
  viewport,
10320
10596
  sessionId,
10321
10597
  sessionId,
@@ -10329,10 +10605,12 @@ var StreamCoordinator = class {
10329
10605
  * replay and crop changes).
10330
10606
  */
10331
10607
  async replayLastFrame(sessionId) {
10332
- if (!this.lastFrameData || !this.lastFrameViewport) return;
10608
+ const data = this.lastUncroppedFrameData ?? this.lastFrameData;
10609
+ const viewport = this.lastUncroppedFrameViewport ?? this.lastFrameViewport;
10610
+ if (!data || !viewport) return;
10333
10611
  await this.processAndBroadcast(
10334
- this.lastFrameData,
10335
- this.lastFrameViewport,
10612
+ data,
10613
+ viewport,
10336
10614
  sessionId,
10337
10615
  sessionId,
10338
10616
  crypto.randomUUID(),
@@ -10352,8 +10630,11 @@ var StreamCoordinator = class {
10352
10630
  async processAndBroadcast(frameData, frameViewport, sessionId, frameSessionId, frameId, frameTimestamp, frameUrl) {
10353
10631
  const config = this.stateManager.getConfig();
10354
10632
  const crop = this.sessionCrops.get(sessionId);
10355
- const cropConfig = crop ? crop.box : void 0;
10356
- const effectiveViewport = crop ? { width: crop.box.width, height: crop.box.height } : frameViewport;
10633
+ const cropFitsViewport = crop ? crop.box.x >= 0 && crop.box.y >= 0 && crop.box.x + crop.box.width <= frameViewport.width + 1 && crop.box.y + crop.box.height <= frameViewport.height + 1 : true;
10634
+ const cropConfig = crop && cropFitsViewport ? crop.box : void 0;
10635
+ const frameIsAlreadyCrop = crop && !cropConfig && Math.abs(frameViewport.width - crop.box.width) <= 1 && Math.abs(frameViewport.height - crop.box.height) <= 1;
10636
+ const processCrop = frameIsAlreadyCrop ? void 0 : cropConfig;
10637
+ const effectiveViewport = cropConfig ? { width: cropConfig.width, height: cropConfig.height } : frameViewport;
10357
10638
  const adjustedConfig = adjustConfigForSize(
10358
10639
  config,
10359
10640
  effectiveViewport.width,
@@ -10364,11 +10645,12 @@ var StreamCoordinator = class {
10364
10645
  const processedBuffer = await this.frameProcessor.process(
10365
10646
  frameData,
10366
10647
  adjustedConfig,
10367
- // Pass the ORIGINAL viewport (not cropped) so crop coordinates
10368
- // can be scaled correctly from viewport space to frame pixel space.
10369
- crop ? frameViewport.width : effectiveViewport.width,
10370
- crop ? frameViewport.height : effectiveViewport.height,
10371
- cropConfig
10648
+ // The full viewport maps crop coordinates to source-frame pixels.
10649
+ // FrameProcessor sizes the final crop from cropConfig, never from this
10650
+ // full-page viewport.
10651
+ frameViewport.width,
10652
+ frameViewport.height,
10653
+ processCrop
10372
10654
  );
10373
10655
  const header = Buffer.from(JSON.stringify({
10374
10656
  type: "screenshot",
@@ -10377,7 +10659,7 @@ var StreamCoordinator = class {
10377
10659
  id: frameId,
10378
10660
  timestamp: frameTimestamp,
10379
10661
  url: frameUrl,
10380
- viewport: effectiveViewport,
10662
+ viewport: cropConfig ? effectiveViewport : frameViewport,
10381
10663
  streamState: this.stateManager.getState(),
10382
10664
  fps: this.frameRateController.getCurrentFps()
10383
10665
  }
@@ -10385,6 +10667,8 @@ var StreamCoordinator = class {
10385
10667
  const headerLen = Buffer.alloc(4);
10386
10668
  headerLen.writeUInt32BE(header.length, 0);
10387
10669
  const payload = Buffer.concat([headerLen, header, processedBuffer]);
10670
+ this.lastFrameData = frameData;
10671
+ this.lastFrameViewport = frameViewport;
10388
10672
  this.sink.broadcastBinaryToSession(sessionId, payload);
10389
10673
  }
10390
10674
  };
@@ -10519,21 +10803,58 @@ var ElementMonitor = class {
10519
10803
  if (this.getClientCount() <= 0) return;
10520
10804
  try {
10521
10805
  const elements = await this.page.evaluate(() => {
10522
- const sel = '[role="dialog"],dialog,[class*="modal"],[class*="popup"],[class*="overlay"],[class*="drawer"],form';
10806
+ const sel = [
10807
+ '[role="dialog"]',
10808
+ "dialog",
10809
+ '[class*="modal"]',
10810
+ '[class*="popup"]',
10811
+ '[class*="overlay"]',
10812
+ '[class*="drawer"]',
10813
+ "form",
10814
+ "img",
10815
+ "canvas"
10816
+ ].join(",");
10523
10817
  const els = document.querySelectorAll(sel);
10524
10818
  const results = [];
10525
10819
  const vpW = window.innerWidth, vpH = window.innerHeight;
10526
10820
  for (const el of els) {
10527
10821
  const r = el.getBoundingClientRect();
10528
- if (r.width < 50 || r.height < 30) continue;
10529
- if (r.width * r.height > vpW * vpH * 0.9) continue;
10530
10822
  const style = window.getComputedStyle(el);
10531
10823
  if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") continue;
10824
+ if (r.bottom < 0 || r.right < 0 || r.top > vpH || r.left > vpW) continue;
10532
10825
  const htmlEl = el;
10826
+ const isImage = el.tagName === "IMG" || el.tagName === "CANVAS";
10827
+ const semantic = `${el.id} ${typeof htmlEl.className === "string" ? htmlEl.className : ""} ${el.getAttribute("alt") || ""} ${el.getAttribute("title") || ""} ${el.getAttribute("src") || ""}`.toLowerCase();
10828
+ const looksLikeQr = isImage && /(qr|qrcode|barcode|二维码)/.test(semantic);
10829
+ const square = Math.abs(r.width - r.height) <= Math.max(8, Math.min(r.width, r.height) * 0.12);
10830
+ if (isImage) {
10831
+ if (r.width < 48 || r.height < 48) continue;
10832
+ if (r.width > vpW || r.height > vpH) continue;
10833
+ if (looksLikeQr && !square) continue;
10834
+ if (!looksLikeQr && !el.getAttribute("src") && !el.getAttribute("alt") && !el.getAttribute("title")) continue;
10835
+ } else {
10836
+ if (r.width < 50 || r.height < 30) continue;
10837
+ if (r.width * r.height > vpW * vpH * 0.9) continue;
10838
+ }
10839
+ let kind = "view";
10840
+ let src;
10841
+ let text;
10842
+ if (looksLikeQr) {
10843
+ kind = "qr";
10844
+ src = el.getAttribute("src") || void 0;
10845
+ text = el.getAttribute("alt") || el.getAttribute("title") || void 0;
10846
+ } else if (isImage) {
10847
+ kind = "image";
10848
+ src = el.getAttribute("src") || void 0;
10849
+ text = el.getAttribute("alt") || el.getAttribute("title") || void 0;
10850
+ }
10533
10851
  results.push({
10534
10852
  tag: el.tagName,
10535
10853
  id: el.id || "",
10536
10854
  cls: (typeof htmlEl.className === "string" ? htmlEl.className : "").slice(0, 40),
10855
+ kind,
10856
+ ...src ? { src } : {},
10857
+ ...text ? { text } : {},
10537
10858
  rect: { x: Math.round(r.x), y: Math.round(r.y), width: Math.round(r.width), height: Math.round(r.height) }
10538
10859
  });
10539
10860
  }
@@ -10550,9 +10871,12 @@ var ElementMonitor = class {
10550
10871
  if (!dupe) deduped.push(el);
10551
10872
  }
10552
10873
  deduped.sort((a, b) => b.rect.width * b.rect.height - a.rect.width * a.rect.height);
10874
+ deduped.sort((a, b) => Number(b.kind === "qr") - Number(a.kind === "qr"));
10553
10875
  const views = deduped.map((e, i) => ({
10554
10876
  id: "el-" + i + "-" + (e.id || e.tag),
10555
- label: e.id || e.cls || e.tag,
10877
+ label: e.kind === "qr" ? e.text || "QR code" : e.kind === "image" ? e.text || e.src || "Image" : e.id || e.cls || e.tag,
10878
+ kind: e.kind,
10879
+ ...e.src ? { src: e.src } : {},
10556
10880
  rect: e.rect
10557
10881
  }));
10558
10882
  this.onViewsUpdate({ type: "views_update", views });
@@ -10605,7 +10929,11 @@ var SessionManager = class extends EventEmitter {
10605
10929
  // Session registration
10606
10930
  // -----------------------------------------------------------------------
10607
10931
  registerSession(sessionId, page, options) {
10608
- if (this.screencasts.has(sessionId)) return;
10932
+ if (this.screencasts.has(sessionId)) {
10933
+ if (this.screencasts.get(sessionId).page === page) return;
10934
+ this.updateSessionPage(sessionId, page);
10935
+ return;
10936
+ }
10609
10937
  this.screencasts.set(sessionId, {
10610
10938
  capturer: new ScreencastCapturer({
10611
10939
  interval: options?.interval ?? 100,
@@ -10631,6 +10959,53 @@ var SessionManager = class extends EventEmitter {
10631
10959
  }
10632
10960
  }
10633
10961
  }
10962
+ // Per-session serialization for page switches: rapid `tab switch` commands
10963
+ // must not interleave stopCapture/startCapture on the shared capturer.
10964
+ pageSwitchTasks = /* @__PURE__ */ new Map();
10965
+ /**
10966
+ * Rebind an already-registered session to a new Page (e.g. after
10967
+ * `tab switch` / `tab new` / `tab close` rebound the session's active
10968
+ * page). Moves the ElementMonitor to the new page, notifies viewers via
10969
+ * the `page-switched` event, and restarts the capturer when it is
10970
+ * streaming so frames immediately come from the new tab.
10971
+ */
10972
+ updateSessionPage(sessionId, page) {
10973
+ const sc = this.screencasts.get(sessionId);
10974
+ if (!sc || sc.page === page) return;
10975
+ const oldMonitor = this.monitors.get(sessionId);
10976
+ if (oldMonitor) {
10977
+ oldMonitor.stop();
10978
+ this.monitors.delete(sessionId);
10979
+ }
10980
+ const monitor = new ElementMonitor(
10981
+ page,
10982
+ (msg) => this.emit("broadcast", sessionId, msg),
10983
+ (msg) => this.emit("broadcast", sessionId, msg),
10984
+ () => this.getSessionClientCount(sessionId)
10985
+ );
10986
+ this.monitors.set(sessionId, monitor);
10987
+ monitor.start();
10988
+ sc.page = page;
10989
+ this.emit("page-switched", sessionId, page);
10990
+ const prev = this.pageSwitchTasks.get(sessionId) ?? Promise.resolve();
10991
+ const task = prev.catch(() => {
10992
+ }).then(async () => {
10993
+ const cur = this.screencasts.get(sessionId);
10994
+ if (!cur || cur.page !== page) return;
10995
+ if (cur.capturer.isActive()) {
10996
+ await cur.capturer.stopCapture().catch(() => {
10997
+ });
10998
+ }
10999
+ if (this.screencasts.get(sessionId) === cur && !cur.capturer.isActive() && cur.clientCount > 0) {
11000
+ await this.startCapturer(sessionId).catch(() => {
11001
+ });
11002
+ }
11003
+ });
11004
+ this.pageSwitchTasks.set(sessionId, task);
11005
+ task.finally(() => {
11006
+ if (this.pageSwitchTasks.get(sessionId) === task) this.pageSwitchTasks.delete(sessionId);
11007
+ });
11008
+ }
10634
11009
  unregisterSession(sessionId) {
10635
11010
  const sc = this.screencasts.get(sessionId);
10636
11011
  if (!sc) return;
@@ -11198,6 +11573,10 @@ var WSServer = class extends EventEmitter2 {
11198
11573
  this.sessionManager.on("screencast-stopped", (sessionId) => {
11199
11574
  this.emit("screencast-stopped", sessionId);
11200
11575
  });
11576
+ this.sessionManager.on("page-switched", (sessionId, page) => {
11577
+ this.streamCoordinator.clearLastFrame();
11578
+ this.broadcastToSession(sessionId, { type: "navigation", url: page.url(), title: "" });
11579
+ });
11201
11580
  }
11202
11581
  // -----------------------------------------------------------------------
11203
11582
  // Public session API (delegates to SessionManager)
@@ -11436,7 +11815,11 @@ var WSServer = class extends EventEmitter2 {
11436
11815
  return;
11437
11816
  }
11438
11817
  const fmt = msg.format === "webp" ? "webp" : "png";
11439
- page2.screenshot({ type: fmt, quality: fmt === "webp" ? msg.quality ?? 90 : void 0 }).then((buf) => {
11818
+ page2.screenshot({
11819
+ type: fmt,
11820
+ quality: fmt === "webp" ? msg.quality ?? 90 : void 0,
11821
+ ...msg.clip ? { clip: { ...msg.clip, scale: msg.scale } } : {}
11822
+ }).then((buf) => {
11440
11823
  this.sendToClient(clientId, {
11441
11824
  type: "snapshot_result",
11442
11825
  data: { data: buf.toString("base64"), format: fmt }
@@ -11863,17 +12246,27 @@ $('reconnect-btn').addEventListener('click',()=>{
11863
12246
  // Preview shows in bottom-right for 5s with countdown \u2192 click to fullscreen
11864
12247
  var snapshotDataUrl=null;
11865
12248
  var snapshotCountdownTimer=null;
12249
+ var suppressSnapshotPreview=false;
11866
12250
  $('snapshot-btn').addEventListener('click',function(){
11867
12251
  var btn=$('snapshot-btn');
11868
12252
  btn.textContent='\u23F3';
11869
- // Request high-quality screenshot from daemon
11870
- sendMsg({type:'snapshot_request',format:'webp',quality:90});
12253
+ requestSnapshot();
11871
12254
  });
12255
+ function requestSnapshot(clip,scale){
12256
+ var btn=$('snapshot-btn');
12257
+ if(btn) btn.textContent='\u23F3';
12258
+ sendMsg({type:'snapshot_request',format:'webp',quality:95,...(clip?{clip:clip,scale:scale||1}:{})});
12259
+ }
11872
12260
  // Handle snapshot response
11873
12261
  // (added to ws.onmessage handler below)
11874
12262
  var snapshotPendingHandler=function(msg){
11875
12263
  if(msg.type==='snapshot_result'&&msg.data){
11876
12264
  var data=msg.data;
12265
+ if(suppressSnapshotPreview){
12266
+ suppressSnapshotPreview=false;
12267
+ $('snapshot-btn').textContent='\u{1F4F7}';
12268
+ return;
12269
+ }
11877
12270
  snapshotDataUrl='data:image/'+(data.format||'png')+';base64,'+data.data;
11878
12271
  var img=$('snapshot-img');
11879
12272
  img.src=snapshotDataUrl;
@@ -11922,6 +12315,15 @@ $('snapshot-preview').addEventListener('click',function(){
11922
12315
  $('snapshot-fullscreen').addEventListener('click',function(){
11923
12316
  this.style.display='none';
11924
12317
  });
12318
+ document.addEventListener('keydown',function(e){
12319
+ if(e.key==='Escape'){
12320
+ var fullscreen=$('snapshot-fullscreen');
12321
+ if(fullscreen.style.display==='flex'){
12322
+ fullscreen.style.display='none';
12323
+ e.stopPropagation();
12324
+ }
12325
+ }
12326
+ },true);
11925
12327
  // Auto-detect dead connection: if no frames for 30s, show warning
11926
12328
  let lastFrameAt=Date.now();
11927
12329
  setInterval(()=>{
@@ -12040,13 +12442,24 @@ function connectWS(){
12040
12442
  statLatency=Math.max(0,Date.now()-header.data.timestamp);
12041
12443
  }
12042
12444
  const blob=new Blob([jpegData],{type:'image/jpeg'});
12043
- createImageBitmap(blob).then(function(bmp){
12044
- drawFrame(bmp);
12045
- bmp.close();
12046
- });
12047
- canvas.style.display='block';
12048
- wait.style.display='none';
12049
- if(header.data.viewport&&!viewportLocked&&!viewSwitching){remoteViewport=header.data.viewport;viewportLocked=true;resizeCanvas();}
12445
+ var incomingViewport=header.data.viewport;
12446
+ if(incomingViewport&&!viewportLocked&&!viewSwitching){
12447
+ remoteViewport={width:incomingViewport.width,height:incomingViewport.height};
12448
+ viewportLocked=true;
12449
+ resizeCanvas();
12450
+ }
12451
+ // During view switches the server can still deliver one in-flight
12452
+ // full-page frame after the crop status arrives. Drawing it while
12453
+ // remoteViewport remains the crop size produces a stretched corner.
12454
+ var viewportMatches=!incomingViewport||(incomingViewport.width===remoteViewport.width&&incomingViewport.height===remoteViewport.height);
12455
+ if(viewportMatches){
12456
+ createImageBitmap(blob).then(function(bmp){
12457
+ drawFrame(bmp);
12458
+ bmp.close();
12459
+ });
12460
+ canvas.style.display='block';
12461
+ wait.style.display='none';
12462
+ }
12050
12463
  if(header.data.url&&header.data.url!==currentUrl){
12051
12464
  currentUrl=header.data.url;
12052
12465
  urlEl.textContent=currentUrl;
@@ -12246,6 +12659,17 @@ function selectView(vid){
12246
12659
  }else{
12247
12660
  var v=detectedViews.find(function(x){return x.id===vid});
12248
12661
  if(v){
12662
+ if(v.kind==='image'||v.kind==='qr'){
12663
+ suppressSnapshotPreview=true;
12664
+ requestSnapshot(v.rect,v.kind==='qr'?4:2);
12665
+ if(!originalViewport) originalViewport={width:remoteViewport.width,height:remoteViewport.height};
12666
+ sendMsg({type:'select_view',rect:v.rect});
12667
+ remoteViewport={width:v.rect.width,height:v.rect.height};
12668
+ viewportLocked=true;
12669
+ resizeCanvas();
12670
+ renderViewTabs();
12671
+ return;
12672
+ }
12249
12673
  if(!originalViewport) originalViewport={width:remoteViewport.width,height:remoteViewport.height};
12250
12674
  sendMsg({type:'select_view',rect:v.rect});
12251
12675
  remoteViewport={width:v.rect.width,height:v.rect.height};