@xbrowser/cli 1.34.0 → 1.36.0

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 (63) hide show
  1. package/README.md +137 -80
  2. package/dist/{browser-ZWEJ663M.js → browser-IEZOLTHA.js} +3 -3
  3. package/dist/{browser-GXL6V2JW.js → browser-NHQDQRXB.js} +3 -2
  4. package/dist/{browser-X7LO42UI.js → browser-XELRNYBL.js} +3 -3
  5. package/dist/cdp-driver-CCG3OJUQ.js +49 -0
  6. package/dist/{cdp-driver-GCFEMRFJ.js → cdp-driver-HBMCD7NU.js} +2 -2
  7. package/dist/{cdp-driver-QOUSRPR2.js → cdp-driver-MJD7YIQI.js} +2 -2
  8. package/dist/{cdp-driver-4MNHDU2J.js → cdp-driver-YJU4GRSV.js} +196 -95
  9. package/dist/chunk-2IOFJ6A3.js +149 -0
  10. package/dist/chunk-3SZTCI33.js +147 -0
  11. package/dist/{chunk-VYTQLZAX.js → chunk-5UXRFNXG.js} +28 -2
  12. package/dist/{chunk-NAIHOVDZ.js → chunk-63526WET.js} +2 -8
  13. package/dist/{chunk-YIL44YDX.js → chunk-6DS3T6UK.js} +196 -95
  14. package/dist/{chunk-J4NOL5XX.js → chunk-7KVH6MQG.js} +1099 -204
  15. package/dist/{chunk-N7DFS4V7.js → chunk-ENTENDF5.js} +9 -3
  16. package/dist/{chunk-R57Z5KZX.js → chunk-GVJ2UY65.js} +1078 -185
  17. package/dist/{chunk-3E6VVMK2.js → chunk-GYGVHWG3.js} +272 -1460
  18. package/dist/{chunk-2KPI5GKP.js → chunk-IYCB2KJL.js} +2 -8
  19. package/dist/chunk-KSB4PMCY.js +1380 -0
  20. package/dist/{chunk-RMYKVZIZ.js → chunk-L6QJUB33.js} +28 -2
  21. package/dist/{chunk-TBJUSUKF.js → chunk-NBT2CE3H.js} +140 -96
  22. package/dist/{chunk-DZ6XEPAH.js → chunk-PGEZJ6V3.js} +9 -3
  23. package/dist/chunk-RGL2YTWQ.js +64 -0
  24. package/dist/chunk-RL5FFY2Q.js +150 -0
  25. package/dist/{chunk-43TEMG4U.js → chunk-SBMVECDS.js} +3 -1
  26. package/dist/{chunk-BND5O5KC.js → chunk-SQLICOPZ.js} +177 -240
  27. package/dist/{chunk-O5PASNI7.js → chunk-UUW5EGES.js} +139 -237
  28. package/dist/{chunk-SH6OTPXN.js → chunk-WGWPWNIA.js} +78 -17
  29. package/dist/chunk-YW4BIJQL.js +489 -0
  30. package/dist/{chunk-R7AG7ONI.js → chunk-ZCZELQCS.js} +196 -95
  31. package/dist/chunk-ZR4NHTUV.js +39 -0
  32. package/dist/cli.js +2284 -307
  33. package/dist/convert-JNOM6H6A.js +490 -0
  34. package/dist/{convert-R3XXYKC6.js → convert-K6TLQEPX.js} +5 -3
  35. package/dist/{daemon-client-7D6EZNOE.js → daemon-client-AKQK5IIB.js} +79 -18
  36. package/dist/{daemon-client-HEGAXWGK.js → daemon-client-BBPQWLUX.js} +7 -1
  37. package/dist/daemon-main.js +2305 -164
  38. package/dist/human-interaction-BGAZC3JR.js +12 -0
  39. package/dist/human-interaction-TPKPEE7A.js +11 -0
  40. package/dist/human-interaction-ZSD3IX6Q.js +12 -0
  41. package/dist/index.d.ts +251 -97
  42. package/dist/index.js +2929 -298
  43. package/dist/{launcher-TOLF23ET.js → launcher-AUJK5QQM.js} +1 -1
  44. package/dist/{launcher-ZYB32LSZ.js → launcher-QBAZ6F5L.js} +1 -1
  45. package/dist/mistake-ledger-2B4N54CO.js +29 -0
  46. package/dist/{recovery-ORHJSBDN.js → recovery-5AGY7CV3.js} +4 -5
  47. package/dist/{recovery-XDKN63O5.js → recovery-7NRRHLS4.js} +2 -2
  48. package/dist/{recovery-JFGV3DBX.js → recovery-TIBRFGRP.js} +2 -2
  49. package/dist/run-routes-64IBBVOX.js +24 -0
  50. package/dist/run-routes-FG4LIACU.js +26 -0
  51. package/dist/{server-5U56MQD2.js → server-K22LJBO2.js} +5 -4
  52. package/dist/{server-R4OYD7ZC.js → server-ZHZDJJMG.js} +5 -3
  53. package/dist/{session-recorder-RUNQOJ7T.js → session-recorder-CNTY5KXF.js} +1 -1
  54. package/dist/{session-recorder-N7VEKJVW.js → session-recorder-KMKSQWEP.js} +1 -1
  55. package/dist/{session-replayer-GHEFFNGV.js → session-replayer-4TCLQI76.js} +1 -1
  56. package/dist/viewer-routes-CEO7HWCB.js +11 -0
  57. package/package.json +3 -2
  58. package/dist/chunk-ETCO4SNK.js +0 -206
  59. package/dist/chunk-QCV2PI7U.js +0 -184
  60. package/dist/convert-LB3GJTLR.js +0 -207
  61. package/dist/human-interaction-ISMMOJOK.js +0 -8
  62. package/dist/human-interaction-STTZZZ5N.js +0 -8
  63. package/dist/human-interaction-UXFYV7DU.js +0 -8
@@ -7,15 +7,17 @@ import {
7
7
  recordMistake
8
8
  } from "./chunk-3DC3Y5OE.js";
9
9
  import {
10
+ buildId,
10
11
  version
11
- } from "./chunk-43TEMG4U.js";
12
+ } from "./chunk-SBMVECDS.js";
12
13
  import {
13
14
  buildViewerUrl
14
15
  } from "./chunk-TZPKFUBT.js";
15
16
  import {
16
- ScreencastCapturer,
17
+ HumanInteractionManager,
18
+ isHumanWaitActive,
17
19
  resolveScreenshotsDir
18
- } from "./chunk-QCV2PI7U.js";
20
+ } from "./chunk-SQLICOPZ.js";
19
21
  import "./chunk-CG3D3CHY.js";
20
22
  import {
21
23
  commandLogStore,
@@ -24,7 +26,7 @@ import {
24
26
  } from "./chunk-VEDJ5XSQ.js";
25
27
  import {
26
28
  SessionRecorder
27
- } from "./chunk-VYTQLZAX.js";
29
+ } from "./chunk-5UXRFNXG.js";
28
30
  import {
29
31
  closeEphemeralContext,
30
32
  closeSessionByName,
@@ -35,14 +37,18 @@ import {
35
37
  getAllSessions,
36
38
  getBrowser,
37
39
  getSessionById,
40
+ newSessionId,
41
+ readSessionDiskMeta,
42
+ registerSession,
38
43
  resolveCDPEndpoint,
39
44
  resolveLaunchOpts,
40
45
  saveSessionDiskMeta,
46
+ sessions,
41
47
  setActivePage
42
- } from "./chunk-DZ6XEPAH.js";
48
+ } from "./chunk-PGEZJ6V3.js";
43
49
  import {
44
50
  createRuleEngine
45
- } from "./chunk-R7AG7ONI.js";
51
+ } from "./chunk-ZCZELQCS.js";
46
52
  import {
47
53
  queryJS
48
54
  } from "./chunk-A7NEA4PA.js";
@@ -51,20 +57,20 @@ import {
51
57
  sleep,
52
58
  wheelDelta
53
59
  } from "./chunk-SMYSNO4M.js";
54
- import "./chunk-2KPI5GKP.js";
60
+ import "./chunk-IYCB2KJL.js";
55
61
  import {
56
62
  errMsg
57
63
  } from "./chunk-GDKLH7ZY.js";
58
64
  import "./chunk-KFQGP6VL.js";
59
65
 
60
66
  // src/daemon/daemon-main.ts
61
- import { writeFileSync as writeFileSync5, mkdirSync as mkdirSync5, appendFileSync, unlinkSync } from "fs";
62
- import { join as join9 } from "path";
63
- import { homedir as homedir7 } from "os";
67
+ import { writeFileSync as writeFileSync6, mkdirSync as mkdirSync6, appendFileSync, unlinkSync as unlinkSync2 } from "fs";
68
+ import { join as join10 } from "path";
69
+ import { homedir as homedir8 } from "os";
64
70
  import { startHttpServer } from "@dyyz1993/xcli-core";
65
71
 
66
72
  // src/daemon/rpc-handlers.ts
67
- import { readFileSync as readFileSync7 } from "fs";
73
+ import { readFileSync as readFileSync8 } from "fs";
68
74
  import {
69
75
  createSessionMeta,
70
76
  removeSession
@@ -72,7 +78,7 @@ import {
72
78
 
73
79
  // src/executor.ts
74
80
  import {
75
- ok as ok33,
81
+ ok as ok32,
76
82
  fail as fail19,
77
83
  isCommandResult,
78
84
  normalizeTips as normalizeTips8,
@@ -1389,14 +1395,14 @@ var preflightCommand = registerCommand({
1389
1395
  let pageUrl = null;
1390
1396
  try {
1391
1397
  const { fileURLToPath } = await import("url");
1392
- const { join: join10, dirname: dirname3 } = await import("path");
1393
- const { existsSync: existsSync4 } = await import("fs");
1398
+ const { join: join11, dirname: dirname3 } = await import("path");
1399
+ const { existsSync: existsSync5 } = await import("fs");
1394
1400
  const here = typeof __filename !== "undefined" ? __filename : fileURLToPath(import.meta.url);
1395
1401
  const candidates = [
1396
- join10(dirname3(here), "..", "assets", "preflight.html"),
1397
- join10(process.cwd(), "assets", "preflight.html")
1402
+ join11(dirname3(here), "..", "assets", "preflight.html"),
1403
+ join11(process.cwd(), "assets", "preflight.html")
1398
1404
  ];
1399
- pageUrl = candidates.find((c) => existsSync4(c)) || null;
1405
+ pageUrl = candidates.find((c) => existsSync5(c)) || null;
1400
1406
  } catch {
1401
1407
  }
1402
1408
  if (pageUrl) {
@@ -3369,6 +3375,19 @@ function stripHashAnchorQuery(url) {
3369
3375
  return url;
3370
3376
  }
3371
3377
  }
3378
+ function createPageBudget(limit, used) {
3379
+ let reserved = used;
3380
+ return {
3381
+ tryAcquire() {
3382
+ if (reserved >= limit) return false;
3383
+ reserved++;
3384
+ return true;
3385
+ },
3386
+ isExhausted() {
3387
+ return reserved >= limit;
3388
+ }
3389
+ };
3390
+ }
3372
3391
  async function extractLinks(page, origin) {
3373
3392
  return page.evaluate((evalOrigin) => {
3374
3393
  return Array.from(document.querySelectorAll("a[href]")).map((a) => {
@@ -3646,6 +3665,7 @@ var crawlCommand = registerCommand({
3646
3665
  await seedPage.close();
3647
3666
  const pagePool = [];
3648
3667
  const poolSize = Math.min(options.concurrency, options.limit);
3668
+ const budget = createPageBudget(options.limit, results.length);
3649
3669
  for (let i = 0; i < poolSize; i++) {
3650
3670
  const ctx2 = await browser.newContext();
3651
3671
  contexts.push(ctx2);
@@ -3663,7 +3683,7 @@ var crawlCommand = registerCommand({
3663
3683
  return null;
3664
3684
  };
3665
3685
  const crawlWorker = async (page) => {
3666
- while (results.length < options.limit) {
3686
+ while (budget.tryAcquire()) {
3667
3687
  const item = dequeueNext();
3668
3688
  if (!item) break;
3669
3689
  completedCount++;
@@ -3677,7 +3697,7 @@ var crawlCommand = registerCommand({
3677
3697
  const pageTitle = await page.title();
3678
3698
  const pageContent = options.format === "html" ? pageHtml : htmlToMarkdown(pageHtml, { onlyMainContent: options.onlyMainContent });
3679
3699
  results.push({ url: page.url(), title: pageTitle, content: pageContent });
3680
- if (results.length >= options.limit) break;
3700
+ if (budget.isExhausted()) break;
3681
3701
  const links = await extractLinks(page, startUrl.origin);
3682
3702
  for (const link of links) {
3683
3703
  try {
@@ -4751,18 +4771,18 @@ import { z as z25 } from "zod";
4751
4771
  import { ok as ok24, fail as fail11, normalizeTips as normalizeTips3 } from "@dyyz1993/xcli-core";
4752
4772
 
4753
4773
  // src/runtime/ref-store.ts
4754
- var sessions = /* @__PURE__ */ new Map();
4774
+ var sessions2 = /* @__PURE__ */ new Map();
4755
4775
  function normalizeAgentRef(ref) {
4756
4776
  return ref.startsWith("@") ? ref.slice(1) : ref;
4757
4777
  }
4758
4778
  function replaceRefs(sessionKey2, screenHash, targets) {
4759
- sessions.set(sessionKey2, {
4779
+ sessions2.set(sessionKey2, {
4760
4780
  screenHash,
4761
4781
  targets: new Map(targets.map((target) => [target.ref, target]))
4762
4782
  });
4763
4783
  }
4764
4784
  function getRefTarget(sessionKey2, ref) {
4765
- const session = sessions.get(sessionKey2);
4785
+ const session = sessions2.get(sessionKey2);
4766
4786
  const target = session?.targets.get(normalizeAgentRef(ref));
4767
4787
  if (!session || !target) return null;
4768
4788
  return { screenHash: session.screenHash, target };
@@ -7361,6 +7381,857 @@ function attachDetectAntiBot(ctx) {
7361
7381
  };
7362
7382
  }
7363
7383
 
7384
+ // src/browser/bridge-session.ts
7385
+ var DEFAULT_BRIDGE_HTTP = "http://127.0.0.1:9347";
7386
+ function bridgeHttpBase() {
7387
+ return process.env.XBROWSER_BRIDGE_HTTP || DEFAULT_BRIDGE_HTTP;
7388
+ }
7389
+ async function bridgeExec(cmd, args) {
7390
+ let resp;
7391
+ try {
7392
+ resp = await fetch(`${bridgeHttpBase()}/exec`, {
7393
+ method: "POST",
7394
+ headers: { "Content-Type": "application/json" },
7395
+ body: JSON.stringify({ cmd, args })
7396
+ });
7397
+ } catch (e) {
7398
+ throw new Error(`[bridge-session] bridge \u901A\u9053\u4E0D\u53EF\u8FBE\uFF08\u4F1A\u8BDD\u89C6\u4E3A closed\uFF09: ${e instanceof Error ? e.message : String(e)}`);
7399
+ }
7400
+ const reply = await resp.json().catch(() => null);
7401
+ if (!reply) throw new Error("[bridge-session] bridge \u54CD\u5E94\u975E JSON\uFF08\u4F1A\u8BDD\u89C6\u4E3A closed\uFF09");
7402
+ if (reply.ok !== true) throw new Error(`[bridge-session] ${cmd} \u5931\u8D25: ${reply.error ?? "unknown"}`);
7403
+ return reply.data ?? {};
7404
+ }
7405
+ function unimplemented(op) {
7406
+ throw new Error(`[bridge-session] \u672A\u652F\u6301\u300C${op}\u300D\u2014\u2014bridge \u4F1A\u8BDD v1 \u80FD\u529B\u9762\uFF1A\u5BFC\u822A/\u6C42\u503C/\u70B9\u51FB/\u586B\u5199/\u952E\u5165/\u622A\u56FE/\u8F6E\u8BE2\u7B49\u5F85\uFF1B\u4E8B\u4EF6\u7C7B\u80FD\u529B\uFF08\u7F51\u7EDC\u6355\u83B7\u3001waitForEvent \u7B49\uFF09\u9700\u8981 CDP \u4E8B\u4EF6\u4E0A\u884C\uFF0C\u6682\u672A\u5F00\u653E`);
7407
+ }
7408
+ var sleep2 = (ms) => new Promise((r) => setTimeout(r, ms));
7409
+ async function pollUntil2(pred, timeoutMs, intervalMs = 120) {
7410
+ const deadline = Date.now() + timeoutMs;
7411
+ while (Date.now() < deadline) {
7412
+ if (await pred()) return true;
7413
+ await sleep2(intervalMs);
7414
+ }
7415
+ return await pred();
7416
+ }
7417
+ function toExpression(fn, args) {
7418
+ if (typeof fn === "string") return fn;
7419
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7420
+ return `(${fn.toString()})(${callArgs})`;
7421
+ }
7422
+ function rectExpression(selector, index) {
7423
+ return `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); const el = els[${index}]; if (!el) return null; const r = el.getBoundingClientRect(); return { x: r.x, y: r.y, width: r.width, height: r.height }; })()`;
7424
+ }
7425
+ function stateExpression(selector, index) {
7426
+ return `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); const el = els[${index}]; if (!el) return null; const visible = !!(el.offsetWidth || el.offsetHeight || el.getClientRects().length); return { found: true, visible, text: el.textContent, html: el.innerHTML, disabled: el.disabled === true || el.getAttribute('disabled') !== null }; })()`;
7427
+ }
7428
+ var BridgePage = class {
7429
+ taskName;
7430
+ tabId;
7431
+ _url;
7432
+ closed = false;
7433
+ mouse;
7434
+ keyboard;
7435
+ ctxStub;
7436
+ constructor(taskName, tabId) {
7437
+ this.taskName = taskName;
7438
+ this.tabId = tabId;
7439
+ this._url = "about:blank";
7440
+ this.mouse = new BridgeMouse(this);
7441
+ this.keyboard = new BridgeKeyboard(this);
7442
+ this.ctxStub = new BridgeContextStub(this);
7443
+ }
7444
+ get bridgeTabId() {
7445
+ return this.tabId;
7446
+ }
7447
+ get bridgeTaskName() {
7448
+ return this.taskName;
7449
+ }
7450
+ /** 会话内 tab 被任务组回收后重锚(task-open 复用路径刷新 tabId) */
7451
+ retab(tabId) {
7452
+ this.tabId = tabId;
7453
+ }
7454
+ async exec(cmd, args = {}) {
7455
+ return bridgeExec(cmd, { ...args, tabId: this.tabId, task: this.taskName });
7456
+ }
7457
+ async evalExpr(expression) {
7458
+ const data = await this.exec("evaluate", { expression });
7459
+ if (data.ok !== true) throw new Error(`[bridge-session] evaluate \u5931\u8D25: ${String(data.error ?? "unknown")}`);
7460
+ return data.value ?? null;
7461
+ }
7462
+ async rectOf(selector, index = 0) {
7463
+ const raw = await this.evalExpr(rectExpression(selector, index));
7464
+ if (raw == null) return null;
7465
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
7466
+ }
7467
+ async stateOf(selector, index = 0) {
7468
+ const raw = await this.evalExpr(stateExpression(selector, index));
7469
+ if (raw == null) return null;
7470
+ return typeof raw === "string" ? JSON.parse(raw) : raw;
7471
+ }
7472
+ async trustedClickAt(x, y) {
7473
+ const r = await this.exec("trustedClick", { x, y });
7474
+ if (r.ok !== true) throw new Error(`[bridge-session] trustedClick \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7475
+ }
7476
+ async clickSelector(selector, index = 0) {
7477
+ await this.waitForSelector(selector, { state: "attached", timeout: 8e3 }).catch(() => {
7478
+ throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7479
+ });
7480
+ const rect = await this.rectOf(selector, index);
7481
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7482
+ await this.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7483
+ }
7484
+ // ── Navigation ──
7485
+ async goto(url, opts) {
7486
+ await this.exec("navigate", { url });
7487
+ this._url = url;
7488
+ await this.waitForLoadState(opts?.waitUntil ?? "load", opts?.timeout ?? 3e4).catch(() => {
7489
+ });
7490
+ return {
7491
+ status: () => 200,
7492
+ ok: () => true,
7493
+ url: () => url,
7494
+ headers: () => ({})
7495
+ };
7496
+ }
7497
+ async goBack() {
7498
+ await this._cdpSend("Page.navigateToHistory", { entryId: -1 });
7499
+ }
7500
+ async goForward() {
7501
+ await this._cdpSend("Page.navigateToHistory", { entryId: 1 });
7502
+ }
7503
+ async reload(opts) {
7504
+ await this._cdpSend("Page.reload", {});
7505
+ await this.waitForLoadState("load", opts?.timeout ?? 3e4).catch(() => {
7506
+ });
7507
+ }
7508
+ async waitForLoadState(state = "load", timeout = 3e4) {
7509
+ const want = state === "domcontentloaded" ? ["interactive", "complete"] : ["complete"];
7510
+ const ok33 = await pollUntil2(async () => {
7511
+ const rs = await this.evalExpr("document.readyState").catch(() => "loading");
7512
+ return want.includes(rs);
7513
+ }, timeout);
7514
+ if (!ok33) throw new Error(`[bridge-session] waitForLoadState(${state}) \u8D85\u65F6`);
7515
+ }
7516
+ async waitForTimeout(ms) {
7517
+ await sleep2(ms);
7518
+ }
7519
+ async waitForSelector(selector, opts) {
7520
+ const state = opts?.state ?? "visible";
7521
+ const timeout = opts?.timeout ?? 3e4;
7522
+ const ok33 = await pollUntil2(async () => {
7523
+ const st = await this.stateOf(selector).catch(() => null);
7524
+ if (!st) return state === "detached";
7525
+ if (state === "attached") return st.found;
7526
+ if (state === "visible") return st.found && st.visible;
7527
+ if (state === "hidden") return !st.found || !st.visible;
7528
+ return !st.found;
7529
+ }, timeout);
7530
+ if (!ok33) throw new Error(`[bridge-session] waitForSelector(${selector}, ${state}) \u8D85\u65F6`);
7531
+ }
7532
+ async waitForFunction(fn, opts, ...args) {
7533
+ const expression = toExpression(fn, args);
7534
+ const timeout = opts?.timeout ?? 3e4;
7535
+ const interval = typeof opts?.polling === "number" ? opts.polling : 120;
7536
+ let last = null;
7537
+ const ok33 = await pollUntil2(async () => {
7538
+ last = await this.evalExpr(expression).catch(() => false);
7539
+ return Boolean(last);
7540
+ }, timeout, interval);
7541
+ if (!ok33) throw new Error(`[bridge-session] waitForFunction \u8D85\u65F6\uFF08last=${JSON.stringify(last)?.slice(0, 80)}\uFF09`);
7542
+ return last;
7543
+ }
7544
+ async waitForURL(url, opts) {
7545
+ const match = (href) => {
7546
+ if (typeof url === "string") return href === url || href.startsWith(url);
7547
+ if (url instanceof RegExp) return url.test(href);
7548
+ return url(href);
7549
+ };
7550
+ const ok33 = await pollUntil2(async () => {
7551
+ const href = await this.evalExpr("location.href").catch(() => "");
7552
+ if (match(href)) {
7553
+ this._url = href;
7554
+ return true;
7555
+ }
7556
+ return false;
7557
+ }, opts?.timeout ?? 3e4);
7558
+ if (!ok33) throw new Error("[bridge-session] waitForURL \u8D85\u65F6");
7559
+ }
7560
+ async waitForResponse() {
7561
+ return unimplemented("waitForResponse\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
7562
+ }
7563
+ async waitForRequest() {
7564
+ return unimplemented("waitForRequest\uFF08\u4E8B\u4EF6\u7C7B\uFF09");
7565
+ }
7566
+ url() {
7567
+ return this._url;
7568
+ }
7569
+ async title() {
7570
+ return this.evalExpr("document.title");
7571
+ }
7572
+ async content() {
7573
+ return this.evalExpr("document.documentElement.outerHTML");
7574
+ }
7575
+ // ── Evaluation ──
7576
+ async evaluate(fn, ...args) {
7577
+ return this.evalExpr(toExpression(fn, args));
7578
+ }
7579
+ async $eval(selector, fn, ...args) {
7580
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7581
+ const expression = `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) throw new Error('no element: ${selector.replace(/'/g, "\\'")}'); return (${typeof fn === "string" ? fn : fn.toString()})(${callArgs.length ? "el, " + callArgs : "el"}); })()`;
7582
+ return this.evalExpr(expression);
7583
+ }
7584
+ async $$eval(selector, fn, ...args) {
7585
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7586
+ const expression = `(() => { const els = document.querySelectorAll(${JSON.stringify(selector)}); return (${typeof fn === "string" ? fn : fn.toString()})(${callArgs.length ? "els, " + callArgs : "els"}); })()`;
7587
+ return this.evalExpr(expression);
7588
+ }
7589
+ // ── Locator ──
7590
+ locator(selector) {
7591
+ return new BridgeLocator(this, selector, 0);
7592
+ }
7593
+ getByText(text, opts) {
7594
+ return new BridgeLocator(this, BridgeLocator.textQuery(text, opts?.exact ?? true), 0, true);
7595
+ }
7596
+ getByRole(role, opts) {
7597
+ const name = opts?.name ? `[aria-label*=${JSON.stringify(opts.name)}]` : "";
7598
+ return new BridgeLocator(this, `[role="${role}"]${name}, ${role}${name}`, 0);
7599
+ }
7600
+ getByLabel(label, opts) {
7601
+ void opts;
7602
+ return new BridgeLocator(this, `label[for], [aria-label*=${JSON.stringify(label)}]`, 0);
7603
+ }
7604
+ getByPlaceholder(text) {
7605
+ return new BridgeLocator(this, `[placeholder*=${JSON.stringify(text)}]`, 0);
7606
+ }
7607
+ getByTestId(id) {
7608
+ return new BridgeLocator(this, `[data-testid="${id}"]`, 0);
7609
+ }
7610
+ getByAltText(text) {
7611
+ return new BridgeLocator(this, `[alt*=${JSON.stringify(text)}]`, 0);
7612
+ }
7613
+ getByTitle(text) {
7614
+ return new BridgeLocator(this, `[title*=${JSON.stringify(text)}]`, 0);
7615
+ }
7616
+ // ── Interaction shortcuts ──
7617
+ async click(selector, _opts) {
7618
+ await this.clickSelector(selector);
7619
+ }
7620
+ async dblclick(selector, _opts) {
7621
+ const rect = await this.rectOf(selector);
7622
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7623
+ const x = Math.round(rect.x + rect.width / 2);
7624
+ const y = Math.round(rect.y + rect.height / 2);
7625
+ await this.trustedClickAt(x, y);
7626
+ await sleep2(60);
7627
+ await this.trustedClickAt(x, y);
7628
+ }
7629
+ async fill(selector, value, _opts) {
7630
+ const direct = await this.exec("fill", { selector, value });
7631
+ if (direct.ok === true) return;
7632
+ const typed = await this.exec("type", { selector, text: value });
7633
+ if (typed.ok !== true) throw new Error(`[bridge-session] fill \u5931\u8D25: ${String(direct.error ?? typed.error ?? "unknown")}`);
7634
+ }
7635
+ async press(selector, key, _opts) {
7636
+ await this.clickSelector(selector);
7637
+ await this.keyboard.press(key);
7638
+ }
7639
+ async hover(selector, _opts) {
7640
+ const rect = await this.rectOf(selector);
7641
+ if (!rect) throw new Error(`[bridge-session] \u5143\u7D20\u672A\u627E\u5230: ${selector}`);
7642
+ await this.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7643
+ }
7644
+ async type(selector, text, _opts) {
7645
+ const r = await this.exec("type", { selector, text });
7646
+ if (r.ok !== true) throw new Error(`[bridge-session] type \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7647
+ }
7648
+ async check(selector, _opts) {
7649
+ const st = await this.stateOf(selector);
7650
+ if (st && !await this.evalExpr(`document.querySelector(${JSON.stringify(selector)}).checked`)) {
7651
+ await this.clickSelector(selector);
7652
+ }
7653
+ }
7654
+ async uncheck(selector, _opts) {
7655
+ const checked = await this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.checked === true`);
7656
+ if (checked) await this.clickSelector(selector);
7657
+ }
7658
+ async selectOption(selector, value) {
7659
+ const v = Array.isArray(value) ? value : [value];
7660
+ const result = await this.evalExpr(
7661
+ `(() => { const el = document.querySelector(${JSON.stringify(selector)}); if (!el) return []; const vals = ${JSON.stringify(v)}; let applied = []; for (const opt of el.options) { if (vals.includes(opt.value) || vals.includes(opt.text)) { opt.selected = true; applied.push(opt.value); } } el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); return applied; })()`
7662
+ );
7663
+ return result ?? [];
7664
+ }
7665
+ // ── Convenience selectors ──
7666
+ async textContent(selector) {
7667
+ const st = await this.stateOf(selector);
7668
+ return st?.text ?? null;
7669
+ }
7670
+ async innerText(selector) {
7671
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerText ?? ''`);
7672
+ }
7673
+ async innerHTML(selector) {
7674
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.innerHTML ?? ''`);
7675
+ }
7676
+ async getAttribute(selector, name) {
7677
+ return this.evalExpr(`document.querySelector(${JSON.stringify(selector)})?.getAttribute(${JSON.stringify(name)}) ?? null`);
7678
+ }
7679
+ // ── Query ──
7680
+ async $(selector) {
7681
+ const st = await this.stateOf(selector);
7682
+ return st ? new BridgeElementHandle(this, selector, 0) : null;
7683
+ }
7684
+ async $$(selector) {
7685
+ const count = await this.evalExpr(`document.querySelectorAll(${JSON.stringify(selector)}).length`);
7686
+ return Array.from({ length: count }, (_, i) => new BridgeElementHandle(this, selector, i));
7687
+ }
7688
+ // ── Screen ──
7689
+ async screenshot(_opts) {
7690
+ const r = await this.exec("screenshot", {});
7691
+ const b64 = r.base64;
7692
+ if (!b64) throw new Error(`[bridge-session] screenshot \u5931\u8D25: ${String(r.error ?? "no base64")}`);
7693
+ return Buffer.from(b64, "base64");
7694
+ }
7695
+ async pdf(_opts) {
7696
+ return unimplemented("pdf");
7697
+ }
7698
+ viewportSize() {
7699
+ return null;
7700
+ }
7701
+ async setViewportSize(_size) {
7702
+ unimplemented("setViewportSize");
7703
+ }
7704
+ async setDeviceScaleFactor(_dsf) {
7705
+ unimplemented("setDeviceScaleFactor");
7706
+ }
7707
+ // ── Scripts / UA / Frames / OOPIF ──
7708
+ async addInitScript(_script) {
7709
+ unimplemented("addInitScript");
7710
+ }
7711
+ async setUserAgent(_ua) {
7712
+ unimplemented("setUserAgent");
7713
+ }
7714
+ async discoverFrames() {
7715
+ return [];
7716
+ }
7717
+ async evaluateInFrame(_urlIncludes, _expression) {
7718
+ return unimplemented("evaluateInFrame");
7719
+ }
7720
+ async listFrameTargets() {
7721
+ return [];
7722
+ }
7723
+ async frameMouse(_urlIncludes, _opts) {
7724
+ return unimplemented("frameMouse");
7725
+ }
7726
+ async runFrameMouse(_urlIncludes, _fn) {
7727
+ return unimplemented("runFrameMouse");
7728
+ }
7729
+ async clickInFrame(_urlIncludes, _selector, _opts) {
7730
+ return unimplemented("clickInFrame");
7731
+ }
7732
+ async fillInFrame(_urlIncludes, _selector, _text, _opts) {
7733
+ return unimplemented("fillInFrame");
7734
+ }
7735
+ // ── Page management ──
7736
+ async bringToFront() {
7737
+ await this._cdpSend("Page.bringToFront", {});
7738
+ }
7739
+ async setExtraHTTPHeaders(_headers) {
7740
+ unimplemented("setExtraHTTPHeaders");
7741
+ }
7742
+ async setOfflineMode(_offline) {
7743
+ unimplemented("setOfflineMode");
7744
+ }
7745
+ async route(_url, _handler) {
7746
+ unimplemented("route");
7747
+ }
7748
+ async unroute(_url, _handler) {
7749
+ unimplemented("unroute");
7750
+ }
7751
+ async setInputFiles(_selector, _files) {
7752
+ unimplemented("setInputFiles");
7753
+ }
7754
+ async dropFiles(_selector, _payload) {
7755
+ unimplemented("dropFiles");
7756
+ }
7757
+ setBeforeUnloadBehavior(_mode) {
7758
+ }
7759
+ async dragAndDrop(_source, _target) {
7760
+ unimplemented("dragAndDrop");
7761
+ }
7762
+ // ── Dialog / events ──
7763
+ on(_event, _handler) {
7764
+ }
7765
+ off(_event, _handler) {
7766
+ }
7767
+ async waitForEvent(_event, opts) {
7768
+ await sleep2(opts?.timeout ?? 3e4);
7769
+ return unimplemented(`waitForEvent(${_event})\u2014\u2014\u4E8B\u4EF6\u7C7B\u80FD\u529B`);
7770
+ }
7771
+ // ── CDP escape hatch ──
7772
+ async _cdpSend(method, params) {
7773
+ const r = await this.exec("cdp", { method, params: params ?? {} });
7774
+ if (r.ok !== true) throw new Error(`[bridge-session] cdp ${method} \u5931\u8D25: ${String(r.error ?? "unknown")}`);
7775
+ return r.data ?? null;
7776
+ }
7777
+ _subscribe(_event, _handler) {
7778
+ return () => {
7779
+ };
7780
+ }
7781
+ // ── Lifecycle ──
7782
+ async close() {
7783
+ if (this.closed) return;
7784
+ this.closed = true;
7785
+ await bridgeExec("task-close", { name: this.taskName }).catch(() => {
7786
+ });
7787
+ }
7788
+ isClosed() {
7789
+ return this.closed;
7790
+ }
7791
+ context() {
7792
+ return this.ctxStub;
7793
+ }
7794
+ browser() {
7795
+ return this.ctxStub.browser();
7796
+ }
7797
+ mainFrame() {
7798
+ return new BridgeFrame(this);
7799
+ }
7800
+ frames() {
7801
+ return [this.mainFrame()];
7802
+ }
7803
+ };
7804
+ var BridgeLocator = class _BridgeLocator {
7805
+ constructor(page, selector, index, isText = false) {
7806
+ this.page = page;
7807
+ this.selector = selector;
7808
+ this.index = index;
7809
+ this.isText = isText;
7810
+ }
7811
+ page;
7812
+ selector;
7813
+ index;
7814
+ isText;
7815
+ /** text 伪查询编码:==精确 / ~包含(无等价 CSS,rect() 编译为 evaluate 表达式) */
7816
+ static textQuery(text, exact) {
7817
+ return `${exact ? "==" : "~"}${text}`;
7818
+ }
7819
+ async rect() {
7820
+ if (!this.isText) return this.page.rectOf(this.selector, this.index);
7821
+ const m = /^(==|~)([\s\S]*)$/.exec(this.selector);
7822
+ const exact = m?.[1] === "==";
7823
+ const text = JSON.stringify(m?.[2] ?? this.selector);
7824
+ const cmp = exact ? `e.textContent.trim() === ${text}` : `e.textContent.includes(${text})`;
7825
+ const expression = `(() => { const cand = [...document.querySelectorAll('a,button,[role=button],input,select,textarea,label,h1,h2,h3,p,span,div,li')]; const el = cand.filter(e => ${cmp})[${this.index}]; if (!el) return null; const b = el.getBoundingClientRect(); return { x: b.x, y: b.y, width: b.width, height: b.height }; })()`;
7826
+ const r = await this.page.evaluate(expression);
7827
+ const v = r;
7828
+ return v == null ? null : typeof v === "string" ? JSON.parse(v) : v;
7829
+ }
7830
+ async click(_opts) {
7831
+ const rect = await this.rect();
7832
+ if (!rect) throw new Error(`[bridge-session] locator \u672A\u547D\u4E2D: ${this.selector}`);
7833
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7834
+ }
7835
+ async fill(value, _opts) {
7836
+ if (!this.isText) {
7837
+ await this.page.fill(this.selector, value);
7838
+ return;
7839
+ }
7840
+ await this.click();
7841
+ await this.page.keyboard.type(value);
7842
+ }
7843
+ async press(key, _opts) {
7844
+ await this.page.keyboard.press(key);
7845
+ }
7846
+ async pressSequentially(text, opts) {
7847
+ await this.page.keyboard.type(text, opts);
7848
+ }
7849
+ async hover(_opts) {
7850
+ const rect = await this.rect();
7851
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7852
+ }
7853
+ async type(text, _opts) {
7854
+ await this.page.keyboard.type(text);
7855
+ }
7856
+ async check(_opts) {
7857
+ await this.click();
7858
+ }
7859
+ async uncheck(_opts) {
7860
+ await this.click();
7861
+ }
7862
+ async selectOption(value) {
7863
+ if (!this.isText) return this.page.selectOption(this.selector, value);
7864
+ return unimplemented("text locator selectOption");
7865
+ }
7866
+ async screenshot(opts) {
7867
+ return this.page.screenshot(opts);
7868
+ }
7869
+ async focus() {
7870
+ if (!this.isText) await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.focus()`);
7871
+ }
7872
+ async waitFor(opts) {
7873
+ if (!this.isText) await this.page.waitForSelector(this.selector, opts);
7874
+ }
7875
+ async count() {
7876
+ if (!this.isText) return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)}).length`);
7877
+ const rect = await this.rect();
7878
+ return rect ? 1 : 0;
7879
+ }
7880
+ async isVisible() {
7881
+ const rect = await this.rect();
7882
+ return rect !== null && rect.width + rect.height > 0;
7883
+ }
7884
+ async isHidden() {
7885
+ return !await this.isVisible();
7886
+ }
7887
+ async isEnabled() {
7888
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7889
+ return st ? !st.disabled : false;
7890
+ }
7891
+ async isDisabled() {
7892
+ return !await this.isEnabled();
7893
+ }
7894
+ async boundingBox() {
7895
+ return this.rect();
7896
+ }
7897
+ async textContent() {
7898
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7899
+ return st?.text ?? null;
7900
+ }
7901
+ async innerText() {
7902
+ return await this.textContent() ?? "";
7903
+ }
7904
+ async innerHTML() {
7905
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7906
+ return st?.html ?? "";
7907
+ }
7908
+ async getAttribute(name) {
7909
+ return this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.getAttribute(${JSON.stringify(name)}) ?? null`);
7910
+ }
7911
+ async evaluate(fn, ...args) {
7912
+ const callArgs = args.map((a) => JSON.stringify(a ?? null)).join(", ");
7913
+ return this.page.evaluate(`(() => { const el = document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]; return el ? (${typeof fn === "string" ? fn : fn.toString()})(${callArgs}) : null; })()`);
7914
+ }
7915
+ async ariaSnapshot() {
7916
+ return unimplemented("ariaSnapshot");
7917
+ }
7918
+ first() {
7919
+ return new _BridgeLocator(this.page, this.selector, 0, this.isText);
7920
+ }
7921
+ last() {
7922
+ return unimplemented("locator.last()");
7923
+ }
7924
+ nth(index) {
7925
+ return new _BridgeLocator(this.page, this.selector, index, this.isText);
7926
+ }
7927
+ filter(_opts) {
7928
+ return unimplemented("locator.filter()");
7929
+ }
7930
+ async all() {
7931
+ const n = await this.count();
7932
+ return Array.from({ length: n }, (_, i) => new _BridgeLocator(this.page, this.selector, i, this.isText));
7933
+ }
7934
+ };
7935
+ var BridgeElementHandle = class {
7936
+ constructor(page, selector, index) {
7937
+ this.page = page;
7938
+ this.selector = selector;
7939
+ this.index = index;
7940
+ }
7941
+ page;
7942
+ selector;
7943
+ index;
7944
+ async click(_opts) {
7945
+ const rect = await this.page.rectOf(this.selector, this.index);
7946
+ if (!rect) throw new Error("[bridge-session] element \u672A\u547D\u4E2D");
7947
+ await this.page.trustedClickAt(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7948
+ }
7949
+ async fill(value, _opts) {
7950
+ await this.page.fill(this.selector, value);
7951
+ }
7952
+ async hover() {
7953
+ const rect = await this.page.rectOf(this.selector, this.index);
7954
+ if (rect) await this.page.mouse.move(Math.round(rect.x + rect.width / 2), Math.round(rect.y + rect.height / 2));
7955
+ }
7956
+ async press(key) {
7957
+ await this.page.keyboard.press(key);
7958
+ }
7959
+ async screenshot(opts) {
7960
+ return this.page.screenshot(opts);
7961
+ }
7962
+ async boundingBox() {
7963
+ return this.page.rectOf(this.selector, this.index);
7964
+ }
7965
+ async isVisible() {
7966
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7967
+ return Boolean(st?.visible);
7968
+ }
7969
+ async isEnabled() {
7970
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7971
+ return st ? !st.disabled : false;
7972
+ }
7973
+ async textContent() {
7974
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7975
+ return st?.text ?? null;
7976
+ }
7977
+ async innerText() {
7978
+ return await this.textContent() ?? "";
7979
+ }
7980
+ async innerHTML() {
7981
+ const st = await this.page.stateOf(this.selector, this.index).catch(() => null);
7982
+ return st?.html ?? "";
7983
+ }
7984
+ async getAttribute(name) {
7985
+ return this.page.getAttribute(this.selector, name);
7986
+ }
7987
+ async scrollIntoViewIfNeeded() {
7988
+ await this.page.evaluate(`document.querySelectorAll(${JSON.stringify(this.selector)})[${this.index}]?.scrollIntoView({ block: 'center' })`);
7989
+ }
7990
+ dispose() {
7991
+ }
7992
+ };
7993
+ var KEY_CODES = {
7994
+ Enter: 13,
7995
+ Tab: 9,
7996
+ Escape: 27,
7997
+ Backspace: 8,
7998
+ Delete: 46,
7999
+ ArrowUp: 38,
8000
+ ArrowDown: 40,
8001
+ ArrowLeft: 37,
8002
+ ArrowRight: 39,
8003
+ Home: 36,
8004
+ End: 35,
8005
+ PageUp: 33,
8006
+ PageDown: 34
8007
+ };
8008
+ var BridgeMouse = class {
8009
+ constructor(page) {
8010
+ this.page = page;
8011
+ }
8012
+ page;
8013
+ async dispatch(params) {
8014
+ await this.page._cdpSend("Input.dispatchMouseEvent", params);
8015
+ }
8016
+ async click(x, y, opts) {
8017
+ const button = opts?.button ?? "left";
8018
+ const clickCount = opts?.clickCount ?? 1;
8019
+ const buttons = button === "left" ? 1 : button === "right" ? 2 : 4;
8020
+ await this.dispatch({ type: "mousePressed", x, y, button, buttons, clickCount });
8021
+ if (opts?.delay) await sleep2(opts.delay);
8022
+ await this.dispatch({ type: "mouseReleased", x, y, button, buttons, clickCount });
8023
+ }
8024
+ async dblclick(x, y, opts) {
8025
+ await this.click(x, y, { ...opts, clickCount: 1 });
8026
+ await sleep2(60);
8027
+ await this.click(x, y, { ...opts, clickCount: 2 });
8028
+ }
8029
+ async down(opts) {
8030
+ const button = opts?.button ?? "left";
8031
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button, buttons: button === "left" ? 1 : button === "right" ? 2 : 4, clickCount: 1 });
8032
+ }
8033
+ async up(opts) {
8034
+ const button = opts?.button ?? "left";
8035
+ await this.dispatch({ type: "mouseReleased", x: 0, y: 0, button, buttons: 0, clickCount: 1 });
8036
+ }
8037
+ async move(x, y, opts) {
8038
+ const steps = Math.max(1, opts?.steps ?? 1);
8039
+ for (let i = 1; i <= steps; i++) {
8040
+ await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 0 });
8041
+ }
8042
+ }
8043
+ async wheel(deltaX, deltaY) {
8044
+ await this.dispatch({ type: "mouseWheel", x: 0, y: 0, deltaX, deltaY });
8045
+ }
8046
+ async wheelAt(x, y, deltaX, deltaY) {
8047
+ await this.move(x, y);
8048
+ await this.dispatch({ type: "mouseWheel", x, y, deltaX, deltaY });
8049
+ }
8050
+ async drag(x, y, opts) {
8051
+ await this.dispatch({ type: "mousePressed", x: 0, y: 0, button: "left", buttons: 1, clickCount: 1 });
8052
+ const steps = Math.max(1, opts?.steps ?? 10);
8053
+ for (let i = 1; i <= steps; i++) await this.dispatch({ type: "mouseMoved", x: Math.round(x), y: Math.round(y), buttons: 1 });
8054
+ await this.dispatch({ type: "mouseReleased", x, y, button: "left", buttons: 0, clickCount: 1 });
8055
+ }
8056
+ };
8057
+ var BridgeKeyboard = class {
8058
+ constructor(page) {
8059
+ this.page = page;
8060
+ }
8061
+ page;
8062
+ async key(event) {
8063
+ await this.page._cdpSend("Input.dispatchKeyEvent", {
8064
+ type: event.type,
8065
+ key: event.key,
8066
+ code: event.code ?? event.key,
8067
+ windowsVirtualKeyCode: KEY_CODES[event.key] ?? (event.key.length === 1 ? event.key.toUpperCase().charCodeAt(0) : 0),
8068
+ nativeVirtualKeyCode: KEY_CODES[event.key] ?? 0,
8069
+ ...event.modifiers !== void 0 ? { modifiers: event.modifiers } : {},
8070
+ ...event.text !== void 0 ? { text: event.text } : {}
8071
+ });
8072
+ }
8073
+ async press(key, _opts) {
8074
+ await this.key({ type: "keyDown", key });
8075
+ await this.key({ type: "keyUp", key });
8076
+ }
8077
+ async pressNav(key) {
8078
+ await this.key({ type: "keyDown", key });
8079
+ }
8080
+ async pressCombo(key, modifier) {
8081
+ const bits = { Alt: 1, Meta: 4, Control: 2, Shift: 8 };
8082
+ await this.key({ type: "keyDown", key: modifier, modifiers: bits[modifier] });
8083
+ await this.key({ type: "keyDown", key, modifiers: bits[modifier] });
8084
+ await this.key({ type: "keyUp", key, modifiers: bits[modifier] });
8085
+ await this.key({ type: "keyUp", key: modifier });
8086
+ }
8087
+ async down(key) {
8088
+ await this.key({ type: "keyDown", key });
8089
+ }
8090
+ async up(key) {
8091
+ await this.key({ type: "keyUp", key });
8092
+ }
8093
+ async type(text, _opts) {
8094
+ const r = await this.page.exec("trusted-type", { text });
8095
+ if (r.ok !== true) {
8096
+ for (const ch of text) await this.key({ type: "keyDown", key: ch, text: ch });
8097
+ }
8098
+ }
8099
+ async insertText(text) {
8100
+ await this.page._cdpSend("Input.insertText", { text });
8101
+ }
8102
+ };
8103
+ var BridgeFrame = class {
8104
+ constructor(bridgePage) {
8105
+ this.bridgePage = bridgePage;
8106
+ }
8107
+ bridgePage;
8108
+ url() {
8109
+ return this.bridgePage.url();
8110
+ }
8111
+ name() {
8112
+ return "";
8113
+ }
8114
+ isDetached() {
8115
+ return this.bridgePage.isClosed();
8116
+ }
8117
+ page() {
8118
+ return this.bridgePage;
8119
+ }
8120
+ async evaluate(fn, ...args) {
8121
+ return this.bridgePage.evaluate(fn, ...args);
8122
+ }
8123
+ async $(selector) {
8124
+ return this.bridgePage.$(selector);
8125
+ }
8126
+ async $$(selector) {
8127
+ return this.bridgePage.$$(selector);
8128
+ }
8129
+ };
8130
+ var BridgeBrowserStub = class {
8131
+ disconnected = false;
8132
+ ctx;
8133
+ constructor(ctx) {
8134
+ this.ctx = ctx;
8135
+ }
8136
+ async close() {
8137
+ }
8138
+ async disconnect() {
8139
+ this.disconnected = true;
8140
+ }
8141
+ async newContext(_opts) {
8142
+ return unimplemented("browser.newContext");
8143
+ }
8144
+ contexts() {
8145
+ return [this.ctx];
8146
+ }
8147
+ async discoverContexts() {
8148
+ }
8149
+ on(_event, _handler) {
8150
+ }
8151
+ off(_event, _handler) {
8152
+ }
8153
+ };
8154
+ var BridgeContextStub = class {
8155
+ constructor(bridgePage) {
8156
+ this.bridgePage = bridgePage;
8157
+ this.browserStub = new BridgeBrowserStub(this);
8158
+ }
8159
+ bridgePage;
8160
+ browserStub;
8161
+ async newPage() {
8162
+ return this.bridgePage;
8163
+ }
8164
+ pages() {
8165
+ return this.bridgePage.isClosed() ? [] : [this.bridgePage];
8166
+ }
8167
+ async close() {
8168
+ await this.bridgePage.close();
8169
+ }
8170
+ browser() {
8171
+ return this.browserStub;
8172
+ }
8173
+ async newCDPSession(_page) {
8174
+ return unimplemented("newCDPSession");
8175
+ }
8176
+ async addInitScript(_script) {
8177
+ unimplemented("addInitScript");
8178
+ }
8179
+ async cookies(_urls) {
8180
+ return [];
8181
+ }
8182
+ async addCookies(_cookies) {
8183
+ unimplemented("addCookies");
8184
+ }
8185
+ async clearCookies() {
8186
+ unimplemented("clearCookies");
8187
+ }
8188
+ on(_event, _handler) {
8189
+ }
8190
+ off(_event, _handler) {
8191
+ }
8192
+ };
8193
+ var realMetaStore = {
8194
+ read: (name) => readSessionDiskMeta(name),
8195
+ save: (name, data) => {
8196
+ saveSessionDiskMeta(name, data);
8197
+ }
8198
+ };
8199
+ var metaStore = realMetaStore;
8200
+ async function findOrCreateBridgeSession(name, opts) {
8201
+ const store = metaStore ?? realMetaStore;
8202
+ const meta = store.read(name);
8203
+ if (meta?.kind !== "bridge" && !opts?.preferBridge) return null;
8204
+ const inMemory = sessions.find(name);
8205
+ if (inMemory?.bridge) return inMemory;
8206
+ const taskName = meta?.taskName ?? name;
8207
+ const opened = await bridgeExec("task-open", { name: taskName }).catch(() => null);
8208
+ const tabId = Number(opened?.tabId ?? 0);
8209
+ if (!opened || !tabId) {
8210
+ throw new Error("[bridge-session] task-open \u5931\u8D25\uFF1Abridge \u672A\u542F\u52A8\u6216\u6269\u5C55\u672A\u8FDE\u63A5\uFF08\u5148\u8DD1 xbrowser chrome-bridge serve / revive\uFF09");
8211
+ }
8212
+ const id = meta?.id ?? newSessionId();
8213
+ const createdAt = meta?.createdAt ?? (/* @__PURE__ */ new Date()).toISOString();
8214
+ store.save(name, {
8215
+ id,
8216
+ kind: "bridge",
8217
+ taskName,
8218
+ tabId,
8219
+ url: opts?.url ?? meta?.url ?? "",
8220
+ createdAt
8221
+ });
8222
+ const page = new BridgePage(taskName, tabId);
8223
+ const session = registerSession({
8224
+ id,
8225
+ name,
8226
+ context: page.context(),
8227
+ page,
8228
+ browser: page.browser(),
8229
+ createdAt,
8230
+ bridge: { taskName, tabId }
8231
+ });
8232
+ return session;
8233
+ }
8234
+
7364
8235
  // src/tips/dom-watcher.ts
7365
8236
  var DOM_WATCHER_SCRIPT = `
7366
8237
  (function() {
@@ -7871,6 +8742,41 @@ function getTipsManager() {
7871
8742
  return globalTipsManager;
7872
8743
  }
7873
8744
 
8745
+ // src/utils/zod-internal.ts
8746
+ function asZodSchema(value) {
8747
+ return value;
8748
+ }
8749
+
8750
+ // src/utils/kebab-params.ts
8751
+ function toCamelCase(key) {
8752
+ return key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
8753
+ }
8754
+ function schemaParamNames(schema) {
8755
+ for (let node = schema, depth = 0; node != null && depth < 5; depth++) {
8756
+ const internal = asZodSchema(node);
8757
+ const shape = internal.shape ?? internal._def?.shape;
8758
+ if (shape) {
8759
+ return new Set(Object.keys(typeof shape === "function" ? shape() : shape));
8760
+ }
8761
+ node = internal._def?.innerType ?? internal._def?.schema;
8762
+ }
8763
+ return void 0;
8764
+ }
8765
+ function normalizeKebabParams(schema, params) {
8766
+ const names = schemaParamNames(schema);
8767
+ if (!names) return params;
8768
+ let renamed;
8769
+ for (const [key, value] of Object.entries(params)) {
8770
+ if (!key.includes("-")) continue;
8771
+ const camelKey = toCamelCase(key);
8772
+ if (camelKey === key || !names.has(camelKey) || names.has(key)) continue;
8773
+ renamed ??= { ...params };
8774
+ if (!(camelKey in params)) renamed[camelKey] = value;
8775
+ delete renamed[key];
8776
+ }
8777
+ return renamed ?? params;
8778
+ }
8779
+
7874
8780
  // src/hooks/loader.ts
7875
8781
  var FAIL_KEYWORDS = [
7876
8782
  "\u767B\u5F55",
@@ -8053,7 +8959,6 @@ function streamCommandEvent(sessionId, message) {
8053
8959
  // src/executor/chain.ts
8054
8960
  import {
8055
8961
  fail as fail18,
8056
- ok as ok32,
8057
8962
  TipCollector as TipCollector2,
8058
8963
  normalizeTips as normalizeTips7,
8059
8964
  unquote as unquote2
@@ -8298,7 +9203,34 @@ function parsePluginParams(args, schema, base = {}) {
8298
9203
  // src/executor/chain.ts
8299
9204
  async function executeChain(input, options, executeCommand2) {
8300
9205
  const pipelines = parseCommandChain(input, { fileMode: options?.fileMode });
8301
- const sessionName = options?.sessionName || "default";
9206
+ let sessionName = options?.sessionName || "default";
9207
+ for (const pipeline of pipelines) {
9208
+ const cleaned = [];
9209
+ for (const step of pipeline.pipeline) {
9210
+ const tokens = splitCommand(step);
9211
+ let stripped = false;
9212
+ const kept = [];
9213
+ for (let i = 0; i < tokens.length; i++) {
9214
+ if (options?.fixedSession && (tokens[i] === "--session" || tokens[i].startsWith("--session="))) {
9215
+ throw new Error("Set the session on the run, outside the command chain");
9216
+ }
9217
+ if (tokens[i] === "--session" && i + 1 < tokens.length) {
9218
+ sessionName = tokens[i + 1];
9219
+ stripped = true;
9220
+ i++;
9221
+ continue;
9222
+ }
9223
+ if (tokens[i].startsWith("--session=")) {
9224
+ sessionName = tokens[i].slice("--session=".length);
9225
+ stripped = true;
9226
+ continue;
9227
+ }
9228
+ kept.push(tokens[i]);
9229
+ }
9230
+ cleaned.push(stripped ? kept.join(" ") : step);
9231
+ }
9232
+ pipeline.pipeline = cleaned;
9233
+ }
8302
9234
  const results = [];
8303
9235
  const totalStart = Date.now();
8304
9236
  let session = await findOrRestoreSession(sessionName, options?.cdpEndpoint);
@@ -8325,6 +9257,14 @@ async function executeChain(input, options, executeCommand2) {
8325
9257
  if (parts.length === 0) continue;
8326
9258
  const cmdName = parts[0];
8327
9259
  const cmdArgs = parts.slice(1);
9260
+ if (options?.handoff && cmdName === "handoff" && cmdArgs.length === 0) {
9261
+ const started = Date.now();
9262
+ const solved = await options.handoff();
9263
+ const message = solved ? "Human handoff completed" : "Human handoff timed out";
9264
+ results.push({ command: cmdName, raw: cmdStr, success: solved, data: null, message, duration: Date.now() - started });
9265
+ if (!solved || type === "or") return stoppedChain(solved, results, totalStart, results.length, message);
9266
+ continue;
9267
+ }
8328
9268
  const loader = await getPluginLoader();
8329
9269
  const internalLoader = loader.getCore().loader;
8330
9270
  const resolvedName = loader.resolveSiteName(cmdName);
@@ -8419,6 +9359,38 @@ async function executePluginChainStep(context) {
8419
9359
  }
8420
9360
  }
8421
9361
  }
9362
+ const needsBrowser = cmdEntry.scope === "page" || cmdEntry.scope === "browser";
9363
+ if (needsBrowser && !process.env.XBROWSER_DAEMON_WORKER) {
9364
+ const { forwardPluginExec } = await import("./daemon-client-AKQK5IIB.js");
9365
+ const userTimeout = typeof pluginParams.timeout === "number" && pluginParams.timeout > 0 ? pluginParams.timeout * 1e3 + 3e4 : void 0;
9366
+ const startFwd = Date.now();
9367
+ const fwd = await forwardPluginExec(
9368
+ `${cmdName}.${subCommand}`,
9369
+ pluginParams,
9370
+ sessionName,
9371
+ void 0,
9372
+ userTimeout
9373
+ );
9374
+ if (fwd != null) {
9375
+ const fwdOk = fwd.success !== false;
9376
+ results.push({
9377
+ command: `${cmdName} ${subCommand}`,
9378
+ raw: cmdStr,
9379
+ success: fwdOk,
9380
+ data: fwd.data ?? null,
9381
+ message: fwd.message,
9382
+ tips: Array.isArray(fwd.tips) ? fwd.tips : void 0,
9383
+ duration: Date.now() - startFwd
9384
+ });
9385
+ if (type === "and" && !fwdOk) {
9386
+ return stoppedChain(false, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' failed (&& chain): ${fwd.message ?? ""}`);
9387
+ }
9388
+ if (type === "or" && fwdOk) {
9389
+ return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9390
+ }
9391
+ return void 0;
9392
+ }
9393
+ }
8422
9394
  const pluginCtx = {
8423
9395
  args: pluginArgs,
8424
9396
  options: pluginParams,
@@ -8486,12 +9458,14 @@ async function executePluginChainStep(context) {
8486
9458
  }
8487
9459
  if (outputs.length > 0) hookOutputs = outputs;
8488
9460
  }
8489
- const data = raw?.data ?? raw;
9461
+ const success = raw?.success !== false;
9462
+ const data = raw?.data ?? (success ? raw : null);
9463
+ const message = success ? void 0 : raw.message ?? "Plugin command failed";
8490
9464
  recordArchive(session.id, sessionName, {
8491
9465
  step: results.length,
8492
9466
  command: `${cmdName} ${subCommand}`,
8493
9467
  params: pluginParams,
8494
- result: { success: true, data, tips: tipsToMessages(raw?.tips) },
9468
+ result: { success, data, message, tips: tipsToMessages(raw?.tips) },
8495
9469
  toolCalls: [],
8496
9470
  duration,
8497
9471
  timestamp: start
@@ -8499,11 +9473,15 @@ async function executePluginChainStep(context) {
8499
9473
  results.push({
8500
9474
  command: `${cmdName} ${subCommand}`,
8501
9475
  raw: cmdStr,
8502
- ...ok32(data),
9476
+ success,
9477
+ data,
9478
+ message,
9479
+ tips: normalizeTips7(raw?.tips),
8503
9480
  duration,
8504
9481
  ...hookOutputs ? { hookOutputs } : {}
8505
9482
  });
8506
- if (type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
9483
+ if (!success && type === "and") return stoppedChain(false, results, totalStart, results.length, message);
9484
+ if (success && type === "or") return stoppedChain(true, results, totalStart, results.length, `Command '${cmdName} ${subCommand}' succeeded (|| chain)`);
8507
9485
  } catch (error) {
8508
9486
  const duration = Date.now() - start;
8509
9487
  const message = errMsg(error);
@@ -8610,7 +9588,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8610
9588
  }
8611
9589
  let targetPageOverride = null;
8612
9590
  if (_target && extraOpts?.cdpEndpoint) {
8613
- const { findTargetPage } = await import("./browser-ZWEJ663M.js");
9591
+ const { findTargetPage } = await import("./browser-IEZOLTHA.js");
8614
9592
  targetPageOverride = await findTargetPage(extraOpts.cdpEndpoint, _target);
8615
9593
  if (!targetPageOverride) {
8616
9594
  return errorResult(`Target "${_target}" not found. Use 'xbrowser targets --cdp ${extraOpts.cdpEndpoint}' to list available pages.`);
@@ -8618,6 +9596,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8618
9596
  params = { ...params, url: targetPageOverride.url };
8619
9597
  }
8620
9598
  if (command.parameters) {
9599
+ params = normalizeKebabParams(command.parameters, params);
8621
9600
  const result = command.parameters.safeParse(params);
8622
9601
  if (!result.success) {
8623
9602
  return errorResult(
@@ -8627,46 +9606,55 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8627
9606
  params = result.data;
8628
9607
  }
8629
9608
  if (command.scope !== "cli" && !process.env.XBROWSER_DAEMON_WORKER) {
8630
- const { forwardExec } = await import("./daemon-client-7D6EZNOE.js");
9609
+ const { forwardExec } = await import("./daemon-client-AKQK5IIB.js");
8631
9610
  const longRunning = /^(vision-task|task|crawl|scrape|record|replay)$/.test(commandName);
8632
9611
  const result = await forwardExec(
8633
9612
  commandName,
8634
9613
  params,
8635
9614
  sessionName,
8636
9615
  extraOpts?.cdpEndpoint,
8637
- longRunning ? 20 * 6e4 : void 0
9616
+ longRunning ? 20 * 6e4 : void 0,
9617
+ extraOpts?.bridge
8638
9618
  );
8639
9619
  if (result) return result;
8640
9620
  }
8641
9621
  let session;
8642
- const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
8643
- if (existing) {
8644
- session = existing;
8645
- if (session.page) {
8646
- try {
8647
- await Promise.race([
8648
- session.page.evaluate(() => true),
8649
- new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
8650
- ]);
8651
- } catch (err) {
8652
- const msg = err instanceof Error ? err.message : String(err);
8653
- if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
8654
- await closeSessionByName(session.name);
8655
- session = void 0;
9622
+ const bridgeSession = await findOrCreateBridgeSession(sessionName, {
9623
+ preferBridge: extraOpts?.bridge === true,
9624
+ url: params.url
9625
+ });
9626
+ if (bridgeSession) {
9627
+ session = bridgeSession;
9628
+ } else {
9629
+ const existing = await findOrRestoreSession(sessionName, extraOpts?.cdpEndpoint);
9630
+ if (existing) {
9631
+ session = existing;
9632
+ if (session.page) {
9633
+ try {
9634
+ await Promise.race([
9635
+ session.page.evaluate(() => true),
9636
+ new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
9637
+ ]);
9638
+ } catch (err) {
9639
+ const msg = err instanceof Error ? err.message : String(err);
9640
+ if (/closed|detached|destroyed|not found|Session closed/i.test(msg)) {
9641
+ await closeSessionByName(session.name);
9642
+ session = void 0;
9643
+ }
8656
9644
  }
8657
9645
  }
8658
- }
8659
- if (session && targetPageOverride && session.page) {
8660
- const currentUrl = session.page.url();
8661
- if (currentUrl !== targetPageOverride.url) {
8662
- await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
8663
- });
9646
+ if (session && targetPageOverride && session.page) {
9647
+ const currentUrl = session.page.url();
9648
+ if (currentUrl !== targetPageOverride.url) {
9649
+ await session.page.goto(targetPageOverride.url, { waitUntil: "domcontentloaded", timeout: 15e3 }).catch(() => {
9650
+ });
9651
+ }
8664
9652
  }
9653
+ } else if (command.scope !== "project") {
9654
+ session = await createSession(sessionName, params.url, {
9655
+ cdpEndpoint: extraOpts?.cdpEndpoint
9656
+ });
8665
9657
  }
8666
- } else if (command.scope !== "project") {
8667
- session = await createSession(sessionName, params.url, {
8668
- cdpEndpoint: extraOpts?.cdpEndpoint
8669
- });
8670
9658
  }
8671
9659
  const ctx = {
8672
9660
  page: session?.page,
@@ -8815,7 +9803,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8815
9803
  timestamp: start
8816
9804
  });
8817
9805
  if (isSuccess) {
8818
- return { ...ok33(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
9806
+ return { ...ok32(raw.data, merged.length > 0 ? merged : raw.tips), duration, ...hookOutputs ? { hookOutputs } : {} };
8819
9807
  }
8820
9808
  const fc = classifyFailure(raw.message);
8821
9809
  return {
@@ -8838,7 +9826,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8838
9826
  duration,
8839
9827
  timestamp: start
8840
9828
  });
8841
- return { ...ok33(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
9829
+ return { ...ok32(raw, smartTipNormalized), duration, ...hookOutputs ? { hookOutputs } : {} };
8842
9830
  } catch (err) {
8843
9831
  const end = Date.now();
8844
9832
  const duration = end - start;
@@ -8851,7 +9839,7 @@ async function executeCommand(commandName, params, sessionName = "default", extr
8851
9839
  });
8852
9840
  if (session?.page && process.env.XBROWSER_RECOVERY && !extraOpts?._recoveryAttempted) {
8853
9841
  try {
8854
- const { attemptRecovery } = await import("./recovery-ORHJSBDN.js");
9842
+ const { attemptRecovery } = await import("./recovery-5AGY7CV3.js");
8855
9843
  const recovery = await attemptRecovery(
8856
9844
  session.page,
8857
9845
  sessionName,
@@ -9444,12 +10432,197 @@ var PlaybackEngine = class _PlaybackEngine {
9444
10432
  }
9445
10433
  };
9446
10434
 
10435
+ // src/browser/session-persistence.ts
10436
+ import {
10437
+ lstatSync,
10438
+ existsSync as existsSync4,
10439
+ mkdirSync as mkdirSync5,
10440
+ readdirSync,
10441
+ readFileSync as readFileSync7,
10442
+ renameSync,
10443
+ unlinkSync,
10444
+ writeFileSync as writeFileSync5
10445
+ } from "fs";
10446
+ import { homedir as homedir7 } from "os";
10447
+ import { join as join9 } from "path";
10448
+ import { randomUUID } from "crypto";
10449
+ function savedSessionsDir() {
10450
+ return process.env.XBROWSER_SAVED_SESSIONS_DIR || join9(homedir7(), ".xbrowser", "saved-sessions");
10451
+ }
10452
+ function sanitizeSessionName(name) {
10453
+ if (!name || name === "." || name === "..") {
10454
+ throw new Error(`Invalid session name "${name}": must be a non-empty file-safe name`);
10455
+ }
10456
+ if (name.length > 64) {
10457
+ throw new Error(`Invalid session name: too long (max 64 chars, got ${name.length})`);
10458
+ }
10459
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) {
10460
+ throw new Error(
10461
+ `Invalid session name "${name}": only [A-Za-z0-9._-] allowed and it must start with an alphanumeric character`
10462
+ );
10463
+ }
10464
+ return name;
10465
+ }
10466
+ function pageOrigin(url) {
10467
+ if (!url.startsWith("http://") && !url.startsWith("https://")) return "";
10468
+ try {
10469
+ return new URL(url).origin;
10470
+ } catch {
10471
+ return "";
10472
+ }
10473
+ }
10474
+ function localStorageSnapshotExpr(origin) {
10475
+ return "((origin) => { try { if (location.origin !== origin) return null; const items = Object.create(null); for (let i = 0; i < localStorage.length; i++) { const k = localStorage.key(i); if (k !== null) items[k] = localStorage.getItem(k) ?? ''; } return JSON.stringify(items); } catch { return null; } })(" + JSON.stringify(origin) + ")";
10476
+ }
10477
+ function localStorageApplyExpr(origin, items) {
10478
+ return "((origin, items) => { if (location.origin !== origin) return false; for (const [k, v] of Object.entries(items)) { try { localStorage.setItem(k, v); } catch { return false; } } return true; })(" + JSON.stringify(origin) + "," + JSON.stringify(items) + ")";
10479
+ }
10480
+ function atomicWriteJson(file, data) {
10481
+ const tmp = `${file}.${randomUUID()}.tmp`;
10482
+ writeFileSync5(tmp, JSON.stringify(data, null, 2), { mode: 384, flag: "wx" });
10483
+ try {
10484
+ renameSync(tmp, file);
10485
+ } finally {
10486
+ if (existsSync4(tmp)) unlinkSync(tmp);
10487
+ }
10488
+ }
10489
+ function assertSelfLaunched(kind) {
10490
+ if (kind.isCDP) {
10491
+ throw new Error(
10492
+ `Refusing to persist login state for CDP-attached session "${kind.name}": persistence is opt-in and limited to self-launched headless sessions`
10493
+ );
10494
+ }
10495
+ if (kind.bridge) {
10496
+ throw new Error(
10497
+ `Refusing to persist login state for chrome-bridge session "${kind.name}": persistence is opt-in and limited to self-launched headless sessions`
10498
+ );
10499
+ }
10500
+ }
10501
+ async function saveLoginSessionState(input, opts = {}) {
10502
+ const name = sanitizeSessionName(input.name);
10503
+ assertSelfLaunched(input);
10504
+ const cookies = await input.context.cookies();
10505
+ const localStorageByOrigin = {};
10506
+ for (const page of input.context.pages()) {
10507
+ const origin = pageOrigin(page.url());
10508
+ if (!origin || localStorageByOrigin[origin]) continue;
10509
+ const raw = await Promise.resolve(
10510
+ page.evaluate(localStorageSnapshotExpr(origin))
10511
+ ).catch(() => null);
10512
+ if (typeof raw !== "string") continue;
10513
+ try {
10514
+ const parsed = JSON.parse(raw);
10515
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
10516
+ localStorageByOrigin[origin] = parsed;
10517
+ }
10518
+ } catch {
10519
+ }
10520
+ }
10521
+ const state = {
10522
+ version: 1,
10523
+ name,
10524
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
10525
+ cookies,
10526
+ localStorage: localStorageByOrigin
10527
+ };
10528
+ const dir = opts.dir ?? savedSessionsDir();
10529
+ mkdirSync5(dir, { recursive: true, mode: 448 });
10530
+ const info = lstatSync(dir);
10531
+ if (!info.isDirectory() || process.platform !== "win32" && (info.mode & 63) !== 0) {
10532
+ throw new Error("Saved sessions directory must be private (0700)");
10533
+ }
10534
+ const file = join9(dir, `${name}.json`);
10535
+ atomicWriteJson(file, state);
10536
+ return {
10537
+ name,
10538
+ createdAt: state.createdAt,
10539
+ cookieCount: cookies.length,
10540
+ origins: Object.keys(localStorageByOrigin),
10541
+ file
10542
+ };
10543
+ }
10544
+ function readSavedLoginState(name, opts) {
10545
+ const safeName = sanitizeSessionName(name);
10546
+ const file = join9(opts.dir ?? savedSessionsDir(), `${safeName}.json`);
10547
+ let state;
10548
+ try {
10549
+ state = JSON.parse(readFileSync7(file, "utf8"));
10550
+ } catch {
10551
+ throw new Error(`No saved login state found for session "${safeName}" (expected ${file})`);
10552
+ }
10553
+ if (state.version !== 1) {
10554
+ throw new Error(`Saved login state "${safeName}" has unsupported version ${String(state.version)}`);
10555
+ }
10556
+ if (state.name !== safeName) {
10557
+ throw new Error(`Saved login state name mismatch: file is "${state.name}", requested "${safeName}"`);
10558
+ }
10559
+ return state;
10560
+ }
10561
+ async function restoreLoginSessionState(name, target, opts = {}) {
10562
+ const state = readSavedLoginState(name, opts);
10563
+ await target.context.addCookies(state.cookies);
10564
+ const originsRestored = [];
10565
+ const originsSkipped = [];
10566
+ const allowNavigate = opts.navigate !== false;
10567
+ for (const [origin, items] of Object.entries(state.localStorage)) {
10568
+ if (Object.keys(items).length === 0) continue;
10569
+ let page = target.context.pages().find((p) => pageOrigin(p.url()) === origin);
10570
+ if (!page && allowNavigate && typeof target.page.goto === "function") {
10571
+ await Promise.resolve(
10572
+ target.page.goto(`${origin}/`, { waitUntil: "domcontentloaded", timeout: 15e3 })
10573
+ ).catch(() => {
10574
+ });
10575
+ if (pageOrigin(target.page.url()) === origin) page = target.page;
10576
+ }
10577
+ if (!page) {
10578
+ originsSkipped.push(origin);
10579
+ continue;
10580
+ }
10581
+ const applied = await Promise.resolve(
10582
+ page.evaluate(localStorageApplyExpr(origin, items))
10583
+ ).catch(() => false);
10584
+ if (applied) originsRestored.push(origin);
10585
+ else originsSkipped.push(origin);
10586
+ }
10587
+ return {
10588
+ name: state.name,
10589
+ cookiesRestored: state.cookies.length,
10590
+ originsRestored,
10591
+ originsSkipped
10592
+ };
10593
+ }
10594
+ async function saveLoginSessionByName(name, opts = {}) {
10595
+ const session = sessions.find(name);
10596
+ if (!session) {
10597
+ throw new Error(`No active session named "${name}" \u2014 open a self-launched session first`);
10598
+ }
10599
+ return saveLoginSessionState(
10600
+ {
10601
+ name: session.name,
10602
+ isCDP: session.isCDP,
10603
+ bridge: !!session.bridge,
10604
+ context: session.context
10605
+ },
10606
+ opts
10607
+ );
10608
+ }
10609
+ async function restoreLoginSessionByName(savedName, targetSessionName, opts = {}) {
10610
+ const session = sessions.find(targetSessionName);
10611
+ if (!session) {
10612
+ throw new Error(`No active session named "${targetSessionName}" \u2014 open a self-launched session first`);
10613
+ }
10614
+ assertSelfLaunched(session);
10615
+ return restoreLoginSessionState(savedName, { context: session.context, page: session.page }, opts);
10616
+ }
10617
+
9447
10618
  // src/daemon/rpc-handlers.ts
9448
10619
  import { TipCollector as TipCollector4 } from "@dyyz1993/xcli-core";
10620
+ var daemonStartedAt = (/* @__PURE__ */ new Date()).toISOString();
9449
10621
  var activeRecorders = /* @__PURE__ */ new Map();
9450
10622
  var replayResumeResolvers = /* @__PURE__ */ new Map();
9451
10623
  function createRPCHandler() {
9452
10624
  let previewWS = null;
10625
+ const managedRuns = /* @__PURE__ */ new Set();
9453
10626
  const INTERACTION_COMMANDS2 = /* @__PURE__ */ new Set([
9454
10627
  "click",
9455
10628
  "fill",
@@ -9471,6 +10644,11 @@ function createRPCHandler() {
9471
10644
  return handleSessionClose(params);
9472
10645
  case "session:list":
9473
10646
  return handleSessionList();
10647
+ case "session:run":
10648
+ return handleManagedRun(params);
10649
+ case "session:save":
10650
+ case "session:restore":
10651
+ return handleSessionState(method, params);
9474
10652
  // ── Command execution ──
9475
10653
  case "exec":
9476
10654
  return handleExec(params);
@@ -9486,7 +10664,7 @@ function createRPCHandler() {
9486
10664
  return handleAgentWait(params);
9487
10665
  // ── Utility ──
9488
10666
  case "ping":
9489
- return { ok: true, pid: process.pid };
10667
+ return { ok: true, pid: process.pid, version, buildId, startedAt: daemonStartedAt };
9490
10668
  case "plugins:reload":
9491
10669
  return handlePluginsReload();
9492
10670
  // ── Network analysis ──
@@ -9632,7 +10810,7 @@ function createRPCHandler() {
9632
10810
  return result;
9633
10811
  } catch (err) {
9634
10812
  const errorMessage = errMsg(err);
9635
- const { attemptRecovery } = await import("./recovery-ORHJSBDN.js");
10813
+ const { attemptRecovery } = await import("./recovery-5AGY7CV3.js");
9636
10814
  const recovery = await attemptRecovery(
9637
10815
  session?.page,
9638
10816
  sessionName,
@@ -9720,6 +10898,7 @@ function createRPCHandler() {
9720
10898
  }
9721
10899
  async function handleSessionClose(params) {
9722
10900
  const name = params.name;
10901
+ if (managedRuns.has(name)) throw new Error(`Session "${name}" is busy`);
9723
10902
  if (previewWS) previewWS.unregisterSession(name);
9724
10903
  await closeSessionByName(name);
9725
10904
  removeSession(name);
@@ -9730,7 +10909,9 @@ function createRPCHandler() {
9730
10909
  id: s.id,
9731
10910
  name: s.name,
9732
10911
  url: s.page?.url() ?? null,
9733
- createdAt: s.createdAt
10912
+ createdAt: s.createdAt,
10913
+ // --session 统一路由:bridge 通道会话标注 kind/taskName
10914
+ ...s.bridge ? { kind: "bridge", taskName: s.bridge.taskName } : {}
9734
10915
  }));
9735
10916
  }
9736
10917
  async function handleExec(params) {
@@ -9780,16 +10961,83 @@ function createRPCHandler() {
9780
10961
  }
9781
10962
  } catch {
9782
10963
  }
10964
+ const releaseReservation = reserveCommandAction(sessionName, command, cmdParams, preElement);
10965
+ let recorded = false;
9783
10966
  try {
9784
- const result = await executeCommand(command, cmdParams, sessionName, { cdpEndpoint: endpoint });
10967
+ const result = await executeCommand(command, cmdParams, sessionName, {
10968
+ cdpEndpoint: endpoint,
10969
+ bridge: params.bridge === true
10970
+ });
9785
10971
  registerSessionIfNew(sessionName);
9786
- await injectCommandToRecorder(sessionName, command, cmdParams, urlBeforeCommand, preElement);
10972
+ if (result.success) {
10973
+ await injectCommandToRecorder(sessionName, command, cmdParams, urlBeforeCommand, preElement);
10974
+ recorded = true;
10975
+ }
9787
10976
  return result;
9788
10977
  } finally {
10978
+ if (!recorded) releaseReservation();
9789
10979
  if (needsPause) await previewWS.resumeScreencast(sessionName).catch(() => {
9790
10980
  });
9791
10981
  }
9792
10982
  }
10983
+ function requireSessionName(value) {
10984
+ if (typeof value !== "string") throw new Error("A session name is required");
10985
+ return sanitizeSessionName(value);
10986
+ }
10987
+ async function withManagedSession(name, action) {
10988
+ if (managedRuns.has(name)) throw new Error(`Session "${name}" is busy`);
10989
+ managedRuns.add(name);
10990
+ try {
10991
+ return await action();
10992
+ } finally {
10993
+ managedRuns.delete(name);
10994
+ }
10995
+ }
10996
+ async function getManagedSession(name, restore = false) {
10997
+ const existing = findSession(name);
10998
+ const metadata = readSessionDiskMeta(name);
10999
+ if (existing?.isCDP || existing?.bridge || metadata?.kind === "bridge" || metadata?.cdpEndpoint) {
11000
+ throw new Error(`Session "${name}" is assigned to an external browser`);
11001
+ }
11002
+ if (existing && restore) throw new Error(`Close session "${name}" before restoring its login state`);
11003
+ const session = existing ?? await createSession(name, void 0, { headless: true });
11004
+ registerSessionIfNew(name);
11005
+ return session;
11006
+ }
11007
+ async function handleManagedRun(params) {
11008
+ const name = requireSessionName(params.session);
11009
+ const input = params.chain;
11010
+ if (typeof input !== "string" || !input.trim()) throw new Error("A command chain is required");
11011
+ return withManagedSession(name, async () => {
11012
+ const session = await getManagedSession(name);
11013
+ return executeChain2(input, {
11014
+ sessionName: name,
11015
+ fileMode: params.fileMode === true,
11016
+ fixedSession: true,
11017
+ handoff: async () => {
11018
+ if (!previewWS) throw new Error("Viewer is unavailable");
11019
+ const activeSession = findSession(name) ?? session;
11020
+ const manager = new HumanInteractionManager(previewWS, activeSession.page, name);
11021
+ const result = await manager.waitForHuman({ autoDetect: false, reason: "Manual handoff" });
11022
+ return result.solved;
11023
+ }
11024
+ });
11025
+ });
11026
+ }
11027
+ async function handleSessionState(method, params) {
11028
+ const name = requireSessionName(params.session);
11029
+ return withManagedSession(name, async () => {
11030
+ if (method === "session:save") return saveLoginSessionByName(name);
11031
+ await getManagedSession(name, true);
11032
+ try {
11033
+ return await restoreLoginSessionByName(name, name);
11034
+ } catch (error) {
11035
+ previewWS?.unregisterSession(name);
11036
+ await closeSessionByName(name);
11037
+ throw error;
11038
+ }
11039
+ });
11040
+ }
9793
11041
  async function handleChain(params) {
9794
11042
  const input = params.chain;
9795
11043
  const sessionName = params.session || "default";
@@ -9938,9 +11186,7 @@ function createRPCHandler() {
9938
11186
  const limit = params.limit || 50;
9939
11187
  return { session: sessionName, commands: commandLogStore.list(sessionName, { limit }) };
9940
11188
  }
9941
- async function injectCommandToRecorder(sessionName, command, params, urlBeforeCommand, preElement) {
9942
- const recorder = activeRecorders.get(sessionName);
9943
- if (!recorder) return;
11189
+ function describeCommandAction(command, params) {
9944
11190
  const COMMAND_ACTION_MAP = {
9945
11191
  goto: "goto",
9946
11192
  fill: "cdp-fill",
@@ -9949,8 +11195,8 @@ function createRPCHandler() {
9949
11195
  select: "change",
9950
11196
  scroll: "scroll"
9951
11197
  };
9952
- const actionType = COMMAND_ACTION_MAP[command];
9953
- if (!actionType) return;
11198
+ const type = COMMAND_ACTION_MAP[command];
11199
+ if (!type) return void 0;
9954
11200
  const selector = params.selector || params.css;
9955
11201
  let value = params.value || params.expression;
9956
11202
  if (value === void 0 || value === "") {
@@ -9961,6 +11207,26 @@ function createRPCHandler() {
9961
11207
  const dist = params.distance ?? 300;
9962
11208
  value = `${dir}:${dist}`;
9963
11209
  }
11210
+ return { type, selector, value };
11211
+ }
11212
+ function reserveCommandAction(sessionName, command, params, preElement) {
11213
+ const recorder = activeRecorders.get(sessionName);
11214
+ const action = describeCommandAction(command, params);
11215
+ if (!recorder || !action?.selector) return () => {
11216
+ };
11217
+ return recorder.reserveCommandAction({
11218
+ type: action.type,
11219
+ // Same converged selector as injectCommandToRecorder (rec-duel d04/d06).
11220
+ selector: preElement?.selector || action.selector,
11221
+ value: action.value
11222
+ });
11223
+ }
11224
+ async function injectCommandToRecorder(sessionName, command, params, urlBeforeCommand, preElement) {
11225
+ const recorder = activeRecorders.get(sessionName);
11226
+ if (!recorder) return;
11227
+ const action = describeCommandAction(command, params);
11228
+ if (!action) return;
11229
+ const { type: actionType, selector, value } = action;
9964
11230
  let currentUrl = params.url || urlBeforeCommand;
9965
11231
  if (command !== "goto" && urlBeforeCommand && urlBeforeCommand !== "about:blank") {
9966
11232
  currentUrl = urlBeforeCommand;
@@ -10060,8 +11326,8 @@ function createRPCHandler() {
10060
11326
  const existingData = SessionRecorder.readData(sessionName);
10061
11327
  if (existingData) {
10062
11328
  if (outputPath) {
10063
- const { writeFileSync: writeFileSync6 } = await import("fs");
10064
- writeFileSync6(outputPath, JSON.stringify(existingData, null, 2), "utf-8");
11329
+ const { writeFileSync: writeFileSync7 } = await import("fs");
11330
+ writeFileSync7(outputPath, JSON.stringify(existingData, null, 2), "utf-8");
10065
11331
  }
10066
11332
  return {
10067
11333
  ok: true,
@@ -10078,14 +11344,14 @@ function createRPCHandler() {
10078
11344
  const { data, summary } = await recorder.stop();
10079
11345
  activeRecorders.delete(sessionName);
10080
11346
  if (outputPath) {
10081
- const { writeFileSync: writeFileSync6, mkdirSync: mkdirSync6 } = await import("fs");
11347
+ const { writeFileSync: writeFileSync7, mkdirSync: mkdirSync7 } = await import("fs");
10082
11348
  const { dirname: dirname3 } = await import("path");
10083
- mkdirSync6(dirname3(outputPath), { recursive: true });
11349
+ mkdirSync7(dirname3(outputPath), { recursive: true });
10084
11350
  if (outputPath.endsWith(".yaml") || outputPath.endsWith(".yml")) {
10085
11351
  const yaml2 = (await import("yaml")).default;
10086
- writeFileSync6(outputPath, yaml2.stringify(data), "utf-8");
11352
+ writeFileSync7(outputPath, yaml2.stringify(data), "utf-8");
10087
11353
  } else {
10088
- writeFileSync6(outputPath, JSON.stringify(data, null, 2), "utf-8");
11354
+ writeFileSync7(outputPath, JSON.stringify(data, null, 2), "utf-8");
10089
11355
  }
10090
11356
  }
10091
11357
  return {
@@ -10172,7 +11438,7 @@ function createRPCHandler() {
10172
11438
  let rawContent;
10173
11439
  let parsed;
10174
11440
  try {
10175
- rawContent = readFileSync7(file, "utf8");
11441
+ rawContent = readFileSync8(file, "utf8");
10176
11442
  try {
10177
11443
  parsed = JSON.parse(rawContent);
10178
11444
  } catch {
@@ -10197,7 +11463,7 @@ function createRPCHandler() {
10197
11463
  if (isNewFormat) {
10198
11464
  try {
10199
11465
  const replayErrors = [];
10200
- const { SessionReplayer } = await import("./session-replayer-GHEFFNGV.js");
11466
+ const { SessionReplayer } = await import("./session-replayer-4TCLQI76.js");
10201
11467
  const replayer = new SessionReplayer({
10202
11468
  page: session.page,
10203
11469
  stepDelay: slowMo * 500,
@@ -10249,10 +11515,10 @@ function createRPCHandler() {
10249
11515
  const errors = Array.isArray(input.errors) ? input.errors : [];
10250
11516
  const eventsPlayed = typeof input.eventsPlayed === "number" ? input.eventsPlayed : 0;
10251
11517
  const totalEvents = typeof input.totalEvents === "number" ? input.totalEvents : eventsPlayed + errors.length;
10252
- const ok34 = input.ok ?? errors.length === 0;
11518
+ const ok33 = input.ok ?? errors.length === 0;
10253
11519
  return {
10254
- ok: ok34,
10255
- success: ok34,
11520
+ ok: ok33,
11521
+ success: ok33,
10256
11522
  duration: typeof input.duration === "number" ? input.duration : 0,
10257
11523
  eventsPlayed,
10258
11524
  totalEvents,
@@ -10279,6 +11545,18 @@ function createRPCHandler() {
10279
11545
  }
10280
11546
  }
10281
11547
 
11548
+ // src/daemon/health.ts
11549
+ function buildHealthPayload(identity, startedAt, pid) {
11550
+ return {
11551
+ status: "ok",
11552
+ pid,
11553
+ version: identity.version,
11554
+ buildId: identity.buildId,
11555
+ startedAt,
11556
+ activeSessions: sessions.size
11557
+ };
11558
+ }
11559
+
10282
11560
  // src/websocket-server.ts
10283
11561
  import { EventEmitter as EventEmitter2 } from "events";
10284
11562
 
@@ -10500,19 +11778,24 @@ var StreamCoordinator = class {
10500
11778
  });
10501
11779
  }
10502
11780
  sink;
10503
- lastFrameData = null;
10504
- lastFrameViewport = null;
10505
- lastUncroppedFrameData = null;
10506
- lastUncroppedFrameViewport = null;
10507
11781
  stateManager = new StreamStateManager();
10508
11782
  frameRateController = new FrameRateController();
10509
11783
  frameProcessor = new FrameProcessor();
10510
11784
  sessionCrops = /* @__PURE__ */ new Map();
11785
+ sessionFrames = /* @__PURE__ */ new Map();
11786
+ frameCacheSeq = 0;
10511
11787
  // -----------------------------------------------------------------------
10512
11788
  // Public accessors
10513
11789
  // -----------------------------------------------------------------------
10514
- getLastFrameViewport() {
10515
- return this.lastFrameViewport;
11790
+ /**
11791
+ * Cached viewport for a session's last frame. When `sessionId` is omitted
11792
+ * (legacy callers), falls back to the most recently updated session's
11793
+ * viewport so old call sites keep behaving like the former global cache.
11794
+ */
11795
+ getLastFrameViewport(sessionId) {
11796
+ const entry = sessionId !== void 0 ? this.sessionFrames.get(sessionId) : this.latestFrameCache();
11797
+ if (!entry) return null;
11798
+ return entry.uncroppedViewport ?? entry.viewport ?? null;
10516
11799
  }
10517
11800
  getCrop(sessionId) {
10518
11801
  return this.sessionCrops.get(sessionId);
@@ -10531,12 +11814,26 @@ var StreamCoordinator = class {
10531
11814
  resetFrameRate() {
10532
11815
  this.frameRateController.reset();
10533
11816
  }
10534
- /** Clear cached last-frame data. */
10535
- clearLastFrame() {
10536
- this.lastFrameData = null;
10537
- this.lastFrameViewport = null;
10538
- this.lastUncroppedFrameData = null;
10539
- this.lastUncroppedFrameViewport = null;
11817
+ /**
11818
+ * Clear cached last-frame data. With `sessionId`, only that session's cache
11819
+ * is dropped (other concurrent sessions keep theirs). Without it (legacy
11820
+ * callers), every session's cache is cleared — same as the old global clear.
11821
+ */
11822
+ clearLastFrame(sessionId) {
11823
+ if (sessionId === void 0) {
11824
+ this.sessionFrames.clear();
11825
+ return;
11826
+ }
11827
+ this.sessionFrames.delete(sessionId);
11828
+ }
11829
+ /**
11830
+ * Full teardown of per-session stream state (last-frame cache + crop).
11831
+ * Must be called when a session unregisters so a later session reusing the
11832
+ * same id can never replay the previous occupant's stale frame.
11833
+ */
11834
+ releaseSession(sessionId) {
11835
+ this.sessionFrames.delete(sessionId);
11836
+ this.sessionCrops.delete(sessionId);
10540
11837
  }
10541
11838
  // -----------------------------------------------------------------------
10542
11839
  // Frame capture callbacks (used by SessionManager)
@@ -10551,8 +11848,10 @@ var StreamCoordinator = class {
10551
11848
  resetStaticSnapshotTimer();
10552
11849
  (async () => {
10553
11850
  const data = frame.data.toString("base64");
10554
- this.lastUncroppedFrameData = data;
10555
- this.lastUncroppedFrameViewport = frame.viewport;
11851
+ const cache = this.getOrCreateFrameCache(sessionId);
11852
+ cache.uncroppedData = data;
11853
+ cache.uncroppedViewport = frame.viewport;
11854
+ this.touchFrameCache(cache);
10556
11855
  this.stateManager.onFrameReceived();
10557
11856
  const config = this.stateManager.getConfig();
10558
11857
  if (!this.frameRateController.shouldSendFrame(config.maxFps)) {
@@ -10588,8 +11887,10 @@ var StreamCoordinator = class {
10588
11887
  }
10589
11888
  const screenshot = await page.screenshot({ type: "jpeg", quality: 100 });
10590
11889
  const data = screenshot.toString("base64");
10591
- this.lastUncroppedFrameData = data;
10592
- this.lastUncroppedFrameViewport = viewport;
11890
+ const cache = this.getOrCreateFrameCache(sessionId);
11891
+ cache.uncroppedData = data;
11892
+ cache.uncroppedViewport = viewport;
11893
+ this.touchFrameCache(cache);
10593
11894
  await this.processAndBroadcast(
10594
11895
  data,
10595
11896
  viewport,
@@ -10601,12 +11902,16 @@ var StreamCoordinator = class {
10601
11902
  );
10602
11903
  }
10603
11904
  /**
10604
- * Process and broadcast the current last frame for a session (used for
10605
- * replay and crop changes).
11905
+ * Process and broadcast the cached last frame for a session (used for
11906
+ * replay and crop changes). Strictly per-session: a session with no cached
11907
+ * frame of its own replays nothing — it must never fall back to another
11908
+ * session's frame.
10606
11909
  */
10607
11910
  async replayLastFrame(sessionId) {
10608
- const data = this.lastUncroppedFrameData ?? this.lastFrameData;
10609
- const viewport = this.lastUncroppedFrameViewport ?? this.lastFrameViewport;
11911
+ const entry = this.sessionFrames.get(sessionId);
11912
+ if (!entry) return;
11913
+ const data = entry.uncroppedData ?? entry.data;
11914
+ const viewport = entry.uncroppedViewport ?? entry.viewport;
10610
11915
  if (!data || !viewport) return;
10611
11916
  await this.processAndBroadcast(
10612
11917
  data,
@@ -10625,7 +11930,7 @@ var StreamCoordinator = class {
10625
11930
  // Private helpers
10626
11931
  // -----------------------------------------------------------------------
10627
11932
  async handleStateChange(_newState) {
10628
- if (!this.lastFrameData || !this.lastFrameViewport) return;
11933
+ if (this.sessionFrames.size === 0) return;
10629
11934
  }
10630
11935
  async processAndBroadcast(frameData, frameViewport, sessionId, frameSessionId, frameId, frameTimestamp, frameUrl) {
10631
11936
  const config = this.stateManager.getConfig();
@@ -10667,15 +11972,181 @@ var StreamCoordinator = class {
10667
11972
  const headerLen = Buffer.alloc(4);
10668
11973
  headerLen.writeUInt32BE(header.length, 0);
10669
11974
  const payload = Buffer.concat([headerLen, header, processedBuffer]);
10670
- this.lastFrameData = frameData;
10671
- this.lastFrameViewport = frameViewport;
11975
+ const cache = this.getOrCreateFrameCache(sessionId);
11976
+ cache.data = frameData;
11977
+ cache.viewport = frameViewport;
11978
+ this.touchFrameCache(cache);
10672
11979
  this.sink.broadcastBinaryToSession(sessionId, payload);
10673
11980
  }
11981
+ // -----------------------------------------------------------------------
11982
+ // Per-session frame-cache helpers
11983
+ // -----------------------------------------------------------------------
11984
+ getOrCreateFrameCache(sessionId) {
11985
+ let entry = this.sessionFrames.get(sessionId);
11986
+ if (!entry) {
11987
+ entry = { uncroppedData: null, uncroppedViewport: null, data: null, viewport: null, seq: 0 };
11988
+ this.sessionFrames.set(sessionId, entry);
11989
+ }
11990
+ return entry;
11991
+ }
11992
+ touchFrameCache(entry) {
11993
+ entry.seq = ++this.frameCacheSeq;
11994
+ }
11995
+ /** Most recently updated entry — only used by the legacy no-arg fallback. */
11996
+ latestFrameCache() {
11997
+ let latest;
11998
+ for (const entry of this.sessionFrames.values()) {
11999
+ if (!latest || entry.seq > latest.seq) latest = entry;
12000
+ }
12001
+ return latest;
12002
+ }
10674
12003
  };
10675
12004
 
10676
12005
  // src/ws/session-manager.ts
10677
12006
  import { EventEmitter } from "events";
10678
12007
 
12008
+ // src/screencast.ts
12009
+ var ScreencastCapturer = class {
12010
+ interval;
12011
+ quality;
12012
+ type;
12013
+ maxWidth;
12014
+ maxHeight;
12015
+ isCapturing = false;
12016
+ frameCallback = null;
12017
+ // CDP Cast state
12018
+ cdpSession = null;
12019
+ sessionId = "";
12020
+ // Fallback polling state
12021
+ fallbackTimer = null;
12022
+ constructor(options = {}) {
12023
+ this.interval = options.interval || 100;
12024
+ this.quality = options.quality || 60;
12025
+ this.type = options.type || "jpeg";
12026
+ this.maxWidth = options.width || 1920;
12027
+ this.maxHeight = options.height || 1080;
12028
+ }
12029
+ /**
12030
+ * Start screencast capture using CDP Page.startScreencast.
12031
+ *
12032
+ * If CDP session creation fails (non-Chromium, restricted access),
12033
+ * automatically falls back to `page.screenshot()` polling.
12034
+ */
12035
+ async startCapture(page, sessionId, onFrame) {
12036
+ if (this.isCapturing) {
12037
+ throw new Error("Screencast is already capturing");
12038
+ }
12039
+ this.isCapturing = true;
12040
+ this.frameCallback = onFrame;
12041
+ this.sessionId = sessionId;
12042
+ try {
12043
+ const cdp = await page.context().newCDPSession(page);
12044
+ this.cdpSession = cdp;
12045
+ cdp.on("Page.screencastFrame", async (params) => {
12046
+ const cb = this.frameCallback;
12047
+ if (!cb) return;
12048
+ cdp.send("Page.screencastFrameAck", { sessionId: params.sessionId }).catch(() => {
12049
+ });
12050
+ const logicalViewport = page.viewportSize();
12051
+ const viewport = logicalViewport ?? {
12052
+ width: params.metadata?.deviceWidth || this.maxWidth,
12053
+ height: params.metadata?.deviceHeight || this.maxHeight
12054
+ };
12055
+ cb({
12056
+ id: crypto.randomUUID(),
12057
+ sessionId: this.sessionId,
12058
+ timestamp: Date.now(),
12059
+ data: Buffer.from(params.data, "base64"),
12060
+ url: page.url(),
12061
+ viewport
12062
+ });
12063
+ });
12064
+ await cdp.send("Page.startScreencast", {
12065
+ format: this.type === "png" ? "png" : "jpeg",
12066
+ quality: this.type === "jpeg" ? this.quality : void 0,
12067
+ maxWidth: this.maxWidth,
12068
+ maxHeight: this.maxHeight
12069
+ });
12070
+ } catch {
12071
+ this.cdpSession = null;
12072
+ this.startFallbackPolling(page, sessionId);
12073
+ }
12074
+ }
12075
+ /**
12076
+ * Fallback: periodic page.screenshot() polling when CDP Cast is unavailable.
12077
+ */
12078
+ startFallbackPolling(page, sessionId) {
12079
+ const captureLoop = async () => {
12080
+ if (!this.frameCallback) return;
12081
+ try {
12082
+ const frame = await this.captureFrame(page, sessionId);
12083
+ this.frameCallback(frame);
12084
+ } catch {
12085
+ }
12086
+ };
12087
+ captureLoop();
12088
+ this.fallbackTimer = setInterval(captureLoop, this.interval);
12089
+ }
12090
+ /**
12091
+ * Capture a single screenshot frame from the page (fallback mode).
12092
+ */
12093
+ async captureFrame(page, sessionId) {
12094
+ let viewport = page.viewportSize();
12095
+ if (!viewport) {
12096
+ try {
12097
+ viewport = await page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
12098
+ } catch {
12099
+ viewport = { width: 1920, height: 1080 };
12100
+ }
12101
+ }
12102
+ const screenshot = await page.screenshot({
12103
+ type: this.type,
12104
+ quality: this.type === "jpeg" ? this.quality : void 0
12105
+ });
12106
+ return {
12107
+ id: crypto.randomUUID(),
12108
+ sessionId,
12109
+ timestamp: Date.now(),
12110
+ data: screenshot,
12111
+ url: page.url(),
12112
+ viewport: viewport || { width: 0, height: 0 }
12113
+ };
12114
+ }
12115
+ /**
12116
+ * Stop the current screencast capture.
12117
+ */
12118
+ async stopCapture() {
12119
+ if (this.cdpSession) {
12120
+ try {
12121
+ this.cdpSession.off("Page.screencastFrame", () => {
12122
+ });
12123
+ await this.cdpSession.send("Page.stopScreencast");
12124
+ } catch {
12125
+ }
12126
+ try {
12127
+ await this.cdpSession.detach();
12128
+ } catch {
12129
+ }
12130
+ this.cdpSession = null;
12131
+ }
12132
+ if (this.fallbackTimer) {
12133
+ clearInterval(this.fallbackTimer);
12134
+ this.fallbackTimer = null;
12135
+ }
12136
+ this.isCapturing = false;
12137
+ this.frameCallback = null;
12138
+ }
12139
+ isActive() {
12140
+ return this.isCapturing;
12141
+ }
12142
+ setInterval(interval) {
12143
+ this.interval = interval;
12144
+ }
12145
+ setQuality(quality) {
12146
+ this.quality = quality;
12147
+ }
12148
+ };
12149
+
10679
12150
  // src/ws/element-monitor.ts
10680
12151
  var ElementMonitor = class {
10681
12152
  constructor(page, onFocusChange, onViewsUpdate, getClientCount) {
@@ -11007,6 +12478,7 @@ var SessionManager = class extends EventEmitter {
11007
12478
  });
11008
12479
  }
11009
12480
  unregisterSession(sessionId) {
12481
+ this.streamCoordinator?.releaseSession(sessionId);
11010
12482
  const sc = this.screencasts.get(sessionId);
11011
12483
  if (!sc) return;
11012
12484
  if (sc.capturer.isActive()) {
@@ -11364,13 +12836,13 @@ var FileListHandler = class {
11364
12836
  async handle(ctx) {
11365
12837
  const msg = ctx.message;
11366
12838
  try {
11367
- const { readdirSync, statSync } = await import("fs");
11368
- const { join: join10, resolve } = await import("path");
12839
+ const { readdirSync: readdirSync2, statSync } = await import("fs");
12840
+ const { join: join11, resolve } = await import("path");
11369
12841
  const targetPath = resolve(msg.path);
11370
- const entries = readdirSync(targetPath);
12842
+ const entries = readdirSync2(targetPath);
11371
12843
  const files = entries.map((name) => {
11372
12844
  try {
11373
- const stat = statSync(join10(targetPath, name));
12845
+ const stat = statSync(join11(targetPath, name));
11374
12846
  return { name, isDir: stat.isDirectory(), size: stat.size, modified: stat.mtime.toISOString() };
11375
12847
  } catch {
11376
12848
  return { name, isDir: false, size: 0, modified: "" };
@@ -11387,10 +12859,10 @@ var FileDownloadHandler = class {
11387
12859
  async handle(ctx) {
11388
12860
  const msg = ctx.message;
11389
12861
  try {
11390
- const { readFileSync: readFileSync8 } = await import("fs");
12862
+ const { readFileSync: readFileSync9 } = await import("fs");
11391
12863
  const { resolve, basename } = await import("path");
11392
12864
  const targetPath = resolve(msg.path);
11393
- const data = readFileSync8(targetPath);
12865
+ const data = readFileSync9(targetPath);
11394
12866
  const base64 = data.toString("base64");
11395
12867
  const ext = targetPath.split(".").pop()?.toLowerCase() || "";
11396
12868
  const mimeMap = {
@@ -11453,7 +12925,7 @@ var FocusClearHandler = class {
11453
12925
  async handle(ctx) {
11454
12926
  if (!ctx.sessionId) return;
11455
12927
  this.sc.deleteCrop(ctx.sessionId);
11456
- const vp = this.sc.getLastFrameViewport();
12928
+ const vp = this.sc.getLastFrameViewport(ctx.sessionId);
11457
12929
  if (vp) {
11458
12930
  ctx.broadcastToSession(ctx.sessionId, { type: "status", data: { status: "connected", viewport: vp } });
11459
12931
  }
@@ -11471,7 +12943,7 @@ var SelectViewHandler = class {
11471
12943
  if (!ctx.sessionId) return;
11472
12944
  if (!msg.rect) {
11473
12945
  this.sc.deleteCrop(ctx.sessionId);
11474
- const vp = this.sc.getLastFrameViewport();
12946
+ const vp = this.sc.getLastFrameViewport(ctx.sessionId);
11475
12947
  if (vp) {
11476
12948
  ctx.broadcastToSession(ctx.sessionId, { type: "status", data: { status: "connected", viewport: vp } });
11477
12949
  }
@@ -11533,7 +13005,418 @@ var MessageDispatcher = class {
11533
13005
  }
11534
13006
  };
11535
13007
 
13008
+ // src/ws/workspace-controller.ts
13009
+ import { randomUUID as randomUUID2 } from "crypto";
13010
+ var LOOPBACK_ADDRESSES = /* @__PURE__ */ new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]);
13011
+ var LOOPBACK_HOSTNAMES = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
13012
+ function checkWorkspaceTrust(peer, viewerPort) {
13013
+ if (!peer) return { ok: true };
13014
+ const { remoteAddress, origin } = peer;
13015
+ if (remoteAddress !== void 0 && remoteAddress !== "" && !LOOPBACK_ADDRESSES.has(remoteAddress)) {
13016
+ return { ok: false, reason: `Workspace controls are restricted to local viewers (peer ${remoteAddress} is not loopback).` };
13017
+ }
13018
+ if (origin !== void 0 && origin !== "") {
13019
+ let parsed;
13020
+ try {
13021
+ parsed = new URL(origin);
13022
+ } catch {
13023
+ return { ok: false, reason: `Invalid Origin for workspace controls: ${origin}` };
13024
+ }
13025
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
13026
+ return { ok: false, reason: `Unsupported Origin protocol for workspace controls: ${parsed.protocol}` };
13027
+ }
13028
+ if (!LOOPBACK_HOSTNAMES.has(parsed.hostname)) {
13029
+ return { ok: false, reason: `Workspace controls are restricted to the local Viewer origin (got ${origin}).` };
13030
+ }
13031
+ const originPort = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
13032
+ if (viewerPort > 0 && originPort !== String(viewerPort)) {
13033
+ return { ok: false, reason: `Workspace controls accept the local Viewer origin only (origin port ${originPort} != viewer port ${viewerPort}).` };
13034
+ }
13035
+ }
13036
+ return { ok: true };
13037
+ }
13038
+ var WorkspaceError = class extends Error {
13039
+ };
13040
+ var NAVIGATE_TIMEOUT_MS = 15e3;
13041
+ var HISTORY_TIMEOUT_MS = 15e3;
13042
+ function assertSafeNavigationUrl(raw) {
13043
+ const trimmed = (raw ?? "").trim();
13044
+ if (!trimmed) throw new WorkspaceError("Navigation URL is empty");
13045
+ let parsed;
13046
+ try {
13047
+ parsed = new URL(trimmed);
13048
+ } catch {
13049
+ throw new WorkspaceError(`Invalid URL: ${trimmed}`);
13050
+ }
13051
+ if (parsed.protocol === "about:") {
13052
+ if (parsed.href === "about:blank") return "about:blank";
13053
+ throw new WorkspaceError(`Unsupported URL scheme: ${parsed.protocol} (only about:blank is allowed)`);
13054
+ }
13055
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
13056
+ throw new WorkspaceError(`Unsupported URL scheme: ${parsed.protocol} (only http/https/about:blank are allowed)`);
13057
+ }
13058
+ return parsed.href;
13059
+ }
13060
+ var WorkspaceController = class {
13061
+ constructor(sessionManager) {
13062
+ this.sessionManager = sessionManager;
13063
+ }
13064
+ sessionManager;
13065
+ resolver;
13066
+ handoffProbe;
13067
+ /**
13068
+ * Stable opaque IDs per tab. Keyed by the XBPage instance — the CDP
13069
+ * driver's `context.pages()` returns the same wrapper objects on every
13070
+ * call, so identity holds across snapshots. IDs die with the page (WeakMap)
13071
+ * and with the controller (daemon restart) — clients holding a stale ID
13072
+ * get a "tab no longer exists" error and re-pull state.
13073
+ */
13074
+ tabIds = /* @__PURE__ */ new WeakMap();
13075
+ tabIdFor(page) {
13076
+ let id = this.tabIds.get(page);
13077
+ if (!id) {
13078
+ id = "tab-" + randomUUID2().slice(0, 8);
13079
+ this.tabIds.set(page, id);
13080
+ }
13081
+ return id;
13082
+ }
13083
+ /**
13084
+ * Per-session mutation serialization. Overlapping viewers (or a racing
13085
+ * navigate + tab close) must not interleave: two concurrent closes on a
13086
+ * two-tab session could both pass the last-tab guard and leave the session
13087
+ * pageless, and a stale select index could rebind onto a just-closed page.
13088
+ * Every mutation re-snapshots `context.pages()` at its turn, so running
13089
+ * them one-at-a-time per session keeps the last-tab invariant and index
13090
+ * freshness. Reads (`workspace_request`) stay unserialized.
13091
+ */
13092
+ mutationQueues = /* @__PURE__ */ new Map();
13093
+ /** Host (daemon) injects session ownership lookup. */
13094
+ setResolver(resolver) {
13095
+ this.resolver = resolver;
13096
+ }
13097
+ /** Host (daemon) injects the waitForHuman handoff-waiting probe. */
13098
+ setHandoffProbe(probe) {
13099
+ this.handoffProbe = probe;
13100
+ }
13101
+ /** Runs mutations one at a time per session; rejections propagate to caller. */
13102
+ enqueueMutation(sessionId, task) {
13103
+ const prev = this.mutationQueues.get(sessionId) ?? Promise.resolve();
13104
+ const run = prev.catch(() => {
13105
+ }).then(task);
13106
+ const tail = run.then(() => void 0, () => void 0);
13107
+ this.mutationQueues.set(sessionId, tail);
13108
+ tail.finally(() => {
13109
+ if (this.mutationQueues.get(sessionId) === tail) this.mutationQueues.delete(sessionId);
13110
+ }).catch(() => {
13111
+ });
13112
+ return run;
13113
+ }
13114
+ // -----------------------------------------------------------------------
13115
+ // Dispatch
13116
+ // -----------------------------------------------------------------------
13117
+ async dispatch(ctx) {
13118
+ try {
13119
+ switch (ctx.message.type) {
13120
+ case "workspace_request":
13121
+ await this.onRequest(ctx);
13122
+ return;
13123
+ case "workspace_navigate":
13124
+ await this.onNavigate(ctx);
13125
+ return;
13126
+ case "workspace_history":
13127
+ await this.onHistory(ctx);
13128
+ return;
13129
+ case "workspace_tab":
13130
+ await this.onTab(ctx);
13131
+ return;
13132
+ default:
13133
+ this.replyError(ctx, `Unknown workspace message type: ${ctx.message.type}`);
13134
+ }
13135
+ } catch (err) {
13136
+ if (err instanceof WorkspaceError) {
13137
+ this.replyError(ctx, err.message);
13138
+ return;
13139
+ }
13140
+ this.replyError(ctx, err instanceof Error ? err.message : String(err));
13141
+ }
13142
+ }
13143
+ // -----------------------------------------------------------------------
13144
+ // Handlers
13145
+ // -----------------------------------------------------------------------
13146
+ async onRequest(ctx) {
13147
+ const resolved = this.resolveSession(ctx);
13148
+ const state = await this.buildState(resolved);
13149
+ ctx.sendToClient(ctx.clientId, state);
13150
+ }
13151
+ async onNavigate(ctx) {
13152
+ if (!ctx.sessionId) {
13153
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
13154
+ }
13155
+ await this.enqueueMutation(ctx.sessionId, async () => {
13156
+ const msg = ctx.message;
13157
+ const resolved = this.resolveSession(ctx);
13158
+ this.requireManaged(resolved);
13159
+ const url = assertSafeNavigationUrl(typeof msg.url === "string" ? msg.url : "");
13160
+ await resolved.handle.page.goto(url, { waitUntil: "domcontentloaded", timeout: NAVIGATE_TIMEOUT_MS });
13161
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
13162
+ });
13163
+ }
13164
+ async onHistory(ctx) {
13165
+ if (!ctx.sessionId) {
13166
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
13167
+ }
13168
+ await this.enqueueMutation(ctx.sessionId, async () => {
13169
+ const msg = ctx.message;
13170
+ const resolved = this.resolveSession(ctx);
13171
+ this.requireManaged(resolved);
13172
+ const action = msg.action;
13173
+ const page = resolved.handle.page;
13174
+ if (action === "back") {
13175
+ await page.goBack({ timeout: HISTORY_TIMEOUT_MS });
13176
+ } else if (action === "forward") {
13177
+ await page.goForward({ timeout: HISTORY_TIMEOUT_MS });
13178
+ } else if (action === "reload") {
13179
+ await page.reload({ timeout: HISTORY_TIMEOUT_MS });
13180
+ } else {
13181
+ throw new WorkspaceError(`Invalid history action: ${String(action)} (expected back | forward | reload)`);
13182
+ }
13183
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
13184
+ });
13185
+ }
13186
+ async onTab(ctx) {
13187
+ if (!ctx.sessionId) {
13188
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
13189
+ }
13190
+ await this.enqueueMutation(ctx.sessionId, async () => {
13191
+ const msg = ctx.message;
13192
+ const resolved = this.resolveSession(ctx);
13193
+ this.requireManaged(resolved);
13194
+ const context = resolved.handle.context;
13195
+ if (!context) {
13196
+ throw new WorkspaceError("Session has no owned browser context; workspace tab controls are unavailable");
13197
+ }
13198
+ switch (msg.action) {
13199
+ case "new":
13200
+ await this.tabNew(ctx, resolved, context);
13201
+ return;
13202
+ case "select":
13203
+ await this.tabSelect(ctx, resolved, context, msg);
13204
+ return;
13205
+ case "close":
13206
+ await this.tabClose(ctx, resolved, context, msg);
13207
+ return;
13208
+ default:
13209
+ throw new WorkspaceError(`Invalid tab action: ${String(msg.action)} (expected new | select | close)`);
13210
+ }
13211
+ });
13212
+ }
13213
+ // -----------------------------------------------------------------------
13214
+ // Tab operations (mirror src/commands/tab.ts semantics)
13215
+ // -----------------------------------------------------------------------
13216
+ async tabNew(ctx, resolved, context) {
13217
+ const newPage = await context.newPage();
13218
+ this.rebindActivePage(resolved, newPage);
13219
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
13220
+ }
13221
+ /**
13222
+ * Resolves the target page for select/close.
13223
+ *
13224
+ * `tabId` (stable opaque ID from workspace_state) is the preferred path:
13225
+ * it names the exact tab regardless of index shifts caused by earlier
13226
+ * queued closes, and a stale ID (tab already closed) is rejected instead
13227
+ * of silently acting on whatever now sits at that position. `index` is
13228
+ * the legacy fallback resolved against the CURRENT snapshot (kept for
13229
+ * mock/test clients). If both are supplied, tabId wins.
13230
+ */
13231
+ resolveTabTarget(pages, activePage, action, msg) {
13232
+ const tabId = typeof msg.tabId === "string" ? msg.tabId.trim() : "";
13233
+ if (tabId) {
13234
+ const target = pages.find((pg) => this.tabIds.get(pg) === tabId);
13235
+ if (!target) {
13236
+ throw new WorkspaceError(
13237
+ `Tab ${tabId} no longer exists (it may have been closed). Send workspace_request to refresh the tab list.`
13238
+ );
13239
+ }
13240
+ return target;
13241
+ }
13242
+ if (typeof msg.index === "number") {
13243
+ if (!Number.isInteger(msg.index) || msg.index < 0 || msg.index >= pages.length) {
13244
+ throw new WorkspaceError(`Invalid tab index: ${String(msg.index)}. Valid range: 0-${Math.max(0, pages.length - 1)}`);
13245
+ }
13246
+ return pages[msg.index];
13247
+ }
13248
+ if (action === "close") return activePage;
13249
+ throw new WorkspaceError("workspace_tab select requires a tabId (preferred) or an integer index");
13250
+ }
13251
+ async tabSelect(ctx, resolved, context, msg) {
13252
+ const pages = context.pages();
13253
+ const targetPage = this.resolveTabTarget(pages, resolved.handle.page, "select", msg);
13254
+ await targetPage.bringToFront().catch(() => {
13255
+ });
13256
+ for (let i = 0; i < 5; i++) {
13257
+ const okProbe = await targetPage.evaluate("1").then(() => true, () => false);
13258
+ if (okProbe) break;
13259
+ await new Promise((r) => setTimeout(r, 300));
13260
+ }
13261
+ try {
13262
+ const mouse = targetPage.mouse;
13263
+ if (mouse) await mouse.move(1, 1).catch(() => {
13264
+ });
13265
+ } catch {
13266
+ }
13267
+ this.rebindActivePage(resolved, targetPage);
13268
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
13269
+ }
13270
+ async tabClose(ctx, resolved, context, msg) {
13271
+ const pages = context.pages();
13272
+ const activePage = resolved.handle.page;
13273
+ const pageToClose = this.resolveTabTarget(pages, activePage, "close", msg);
13274
+ if (pages.length <= 1) {
13275
+ throw new WorkspaceError("Cannot close the last remaining tab");
13276
+ }
13277
+ const isActivePage = pageToClose === activePage;
13278
+ await pageToClose.close();
13279
+ const remainingPages = context.pages();
13280
+ if (remainingPages.length === 0) {
13281
+ throw new WorkspaceError("All tabs closed; the session needs a page");
13282
+ }
13283
+ if (isActivePage) {
13284
+ const closeIndex = pages.indexOf(pageToClose);
13285
+ const switchIndex = closeIndex >= 0 && closeIndex < remainingPages.length ? closeIndex : remainingPages.length - 1;
13286
+ this.rebindActivePage(resolved, remainingPages[switchIndex]);
13287
+ }
13288
+ ctx.sendToTrustedSessionClients(resolved.sessionId, await this.buildState(resolved));
13289
+ }
13290
+ // -----------------------------------------------------------------------
13291
+ // State building
13292
+ // -----------------------------------------------------------------------
13293
+ /**
13294
+ * Builds the `workspace_state` payload for a session.
13295
+ *
13296
+ * - Managed sessions enumerate the full context tab list.
13297
+ * - Externally-owned sessions (or standalone mode without a resolver) get
13298
+ * a read-only single-page state describing only the bound page — the
13299
+ * user's other tabs are never enumerated.
13300
+ */
13301
+ async buildState(resolved) {
13302
+ const { sessionId, handle } = resolved;
13303
+ const context = handle.context;
13304
+ const handoffWaiting = this.handoffProbe?.(sessionId) === true ? { handoffWaiting: true } : {};
13305
+ if (!handle.managed || !context) {
13306
+ const page = handle.page;
13307
+ if (!page) {
13308
+ return { type: "workspace_state", sessionId, tabs: [], activeIndex: -1, readOnly: true, ...handoffWaiting };
13309
+ }
13310
+ const title = await page.title().catch(() => "");
13311
+ return {
13312
+ type: "workspace_state",
13313
+ sessionId,
13314
+ tabs: [{ id: this.tabIdFor(page), index: 0, url: page.url(), ...title ? { title } : {} }],
13315
+ activeIndex: 0,
13316
+ readOnly: true,
13317
+ ...handoffWaiting
13318
+ };
13319
+ }
13320
+ const pages = context.pages();
13321
+ const activePage = handle.page;
13322
+ let activeIndex = pages.findIndex((pg) => pg === activePage);
13323
+ const tabs = [];
13324
+ for (let i = 0; i < pages.length; i++) {
13325
+ const url = pages[i].url();
13326
+ const title = await pages[i].title().catch(() => "");
13327
+ if (pages[i] === activePage) activeIndex = i;
13328
+ tabs.push({ id: this.tabIdFor(pages[i]), index: i, url, ...title ? { title } : {} });
13329
+ }
13330
+ if (activeIndex < 0 && tabs.length > 0) {
13331
+ activeIndex = 0;
13332
+ }
13333
+ return { type: "workspace_state", sessionId, tabs, activeIndex, ...handoffWaiting };
13334
+ }
13335
+ // -----------------------------------------------------------------------
13336
+ // Session resolution / guards
13337
+ // -----------------------------------------------------------------------
13338
+ /**
13339
+ * Resolves the client's bound session. Bound session ownership: the client
13340
+ * must be bound to a registered session; operations never touch sessions
13341
+ * other than the one this client is bound to.
13342
+ */
13343
+ resolveSession(ctx) {
13344
+ if (!ctx.sessionId) {
13345
+ throw new WorkspaceError('Not bound to a session. Connect via /preview/<sessionId> or send {"type":"bind"} first.');
13346
+ }
13347
+ const resolved = this.resolveBySessionId(ctx.sessionId);
13348
+ if (!resolved) {
13349
+ throw new WorkspaceError(`Session "${ctx.sessionId}" not found`);
13350
+ }
13351
+ return resolved;
13352
+ }
13353
+ /**
13354
+ * SessionId → handle. Prefers the host resolver (daemon, authoritative
13355
+ * ManagedSession); falls back to the WS-registered page as a read-only
13356
+ * single-page session (standalone viewer without a resolver).
13357
+ */
13358
+ resolveBySessionId(sessionId) {
13359
+ const handle = this.resolver?.(sessionId);
13360
+ if (handle?.page) {
13361
+ return { sessionId, handle };
13362
+ }
13363
+ const wsPage = this.sessionManager.getPageForSession(sessionId);
13364
+ if (wsPage) {
13365
+ return { sessionId, handle: { page: wsPage, context: null, managed: false } };
13366
+ }
13367
+ return void 0;
13368
+ }
13369
+ /**
13370
+ * Pushes a fresh `workspace_state` to the session's viewers via the
13371
+ * supplied trusted-targeting send (never the legacy broadcast — tab
13372
+ * metadata must not reach untrusted clients). Used by WSServer on
13373
+ * `page-switched` so panels stay in sync when the active tab changes
13374
+ * out-of-band (e.g. a CLI `tab switch` command).
13375
+ */
13376
+ async pushState(sessionId, send) {
13377
+ const resolved = this.resolveBySessionId(sessionId);
13378
+ if (!resolved) return;
13379
+ send(sessionId, await this.buildState(resolved));
13380
+ }
13381
+ requireManaged(resolved) {
13382
+ if (!resolved.handle.managed || !resolved.handle.context) {
13383
+ throw new WorkspaceError(
13384
+ `Session "${resolved.sessionId}" is attached to an external browser; workspace navigation and tab controls are read-only. Reopen the session as a managed (self-launched) session to control it.`
13385
+ );
13386
+ }
13387
+ }
13388
+ // -----------------------------------------------------------------------
13389
+ // Active page coherence
13390
+ // -----------------------------------------------------------------------
13391
+ /**
13392
+ * Rebinds the session's active page after a tab switch/new/close using the
13393
+ * existing lifecycle helpers:
13394
+ * 1. host-side `setActivePage` (browser.ts) updates the ManagedSession,
13395
+ * 2. SessionManager re-registration moves the screencast + element monitor
13396
+ * to the new page and emits `page-switched` (viewer follows the tab).
13397
+ */
13398
+ rebindActivePage(resolved, page) {
13399
+ resolved.handle.setActivePage?.(page);
13400
+ resolved.handle.page = page;
13401
+ this.sessionManager.registerSession(resolved.sessionId, page, void 0);
13402
+ }
13403
+ // -----------------------------------------------------------------------
13404
+ // Replies
13405
+ // -----------------------------------------------------------------------
13406
+ replyError(ctx, message) {
13407
+ ctx.sendToClient(ctx.clientId, { type: "workspace_error", message });
13408
+ }
13409
+ };
13410
+
11536
13411
  // src/websocket-server.ts
13412
+ function extractPeerInfo(req) {
13413
+ const r = req;
13414
+ if (!r) return void 0;
13415
+ const remoteAddress = typeof r.socket?.remoteAddress === "string" ? r.socket.remoteAddress : void 0;
13416
+ const origin = typeof r.headers?.origin === "string" ? r.headers.origin : void 0;
13417
+ if (remoteAddress === void 0 && origin === void 0) return void 0;
13418
+ return { ...remoteAddress !== void 0 ? { remoteAddress } : {}, ...origin !== void 0 ? { origin } : {} };
13419
+ }
11537
13420
  var WSServer = class extends EventEmitter2 {
11538
13421
  port;
11539
13422
  host;
@@ -11543,6 +13426,7 @@ var WSServer = class extends EventEmitter2 {
11543
13426
  streamCoordinator;
11544
13427
  sessionManager;
11545
13428
  messageDispatcher;
13429
+ workspaceController;
11546
13430
  constructor(config = {}) {
11547
13431
  super();
11548
13432
  this.port = config.port ?? 9223;
@@ -11551,8 +13435,24 @@ var WSServer = class extends EventEmitter2 {
11551
13435
  this.sessionManager = new SessionManager();
11552
13436
  this.sessionManager.setStreamCoordinator(this.streamCoordinator);
11553
13437
  this.messageDispatcher = new MessageDispatcher(this.streamCoordinator, this.sessionManager);
13438
+ this.workspaceController = new WorkspaceController(this.sessionManager);
11554
13439
  this.setupSessionManagerEvents();
11555
13440
  }
13441
+ /**
13442
+ * Injects the session ownership lookup used by workspace controls
13443
+ * (navigate / history / tab). The daemon maps WS sessionIds to
13444
+ * ManagedSessions; without a resolver the workspace is read-only.
13445
+ */
13446
+ setWorkspaceSessionResolver(resolver) {
13447
+ this.workspaceController.setResolver(resolver);
13448
+ }
13449
+ /**
13450
+ * Injects the waitForHuman handoff probe so workspace state can flag
13451
+ * `handoffWaiting` for late-connecting/reconnecting viewers.
13452
+ */
13453
+ setWorkspaceHandoffProbe(probe) {
13454
+ this.workspaceController.setHandoffProbe(probe);
13455
+ }
11556
13456
  // -----------------------------------------------------------------------
11557
13457
  // SessionManager event wiring
11558
13458
  // -----------------------------------------------------------------------
@@ -11574,8 +13474,10 @@ var WSServer = class extends EventEmitter2 {
11574
13474
  this.emit("screencast-stopped", sessionId);
11575
13475
  });
11576
13476
  this.sessionManager.on("page-switched", (sessionId, page) => {
11577
- this.streamCoordinator.clearLastFrame();
13477
+ this.streamCoordinator.clearLastFrame(sessionId);
11578
13478
  this.broadcastToSession(sessionId, { type: "navigation", url: page.url(), title: "" });
13479
+ this.workspaceController.pushState(sessionId, (sid, message) => this.sendWorkspaceToSessionClients(sid, message)).catch(() => {
13480
+ });
11579
13481
  });
11580
13482
  }
11581
13483
  // -----------------------------------------------------------------------
@@ -11615,7 +13517,7 @@ var WSServer = class extends EventEmitter2 {
11615
13517
  });
11616
13518
  }
11617
13519
  this.sessionManager.incrementClientCount(sessionId);
11618
- if (this.streamCoordinator.getLastFrameViewport()) {
13520
+ if (this.streamCoordinator.getLastFrameViewport(sessionId)) {
11619
13521
  this.streamCoordinator.replayLastFrame(sessionId).catch(() => {
11620
13522
  });
11621
13523
  }
@@ -11646,7 +13548,7 @@ var WSServer = class extends EventEmitter2 {
11646
13548
  if (sc?.page) {
11647
13549
  (async () => {
11648
13550
  try {
11649
- const vp = this.streamCoordinator.getLastFrameViewport() || sc.page.viewportSize() || await sc.page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
13551
+ const vp = this.streamCoordinator.getLastFrameViewport(sessionId) || sc.page.viewportSize() || await sc.page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
11650
13552
  this.sendToClient(clientId, {
11651
13553
  type: "status",
11652
13554
  data: { status: "connected", sessionId, viewport: vp ?? void 0 }
@@ -11723,10 +13625,11 @@ var WSServer = class extends EventEmitter2 {
11723
13625
  // Connection handler
11724
13626
  // -----------------------------------------------------------------------
11725
13627
  setupConnectionHandler(wsServer2) {
11726
- wsServer2.on("connection", (ws, _req, sessionIdFromUrl) => {
13628
+ wsServer2.on("connection", (ws, req, sessionIdFromUrl) => {
11727
13629
  const wsLike = ws;
11728
13630
  const clientId = crypto.randomUUID();
11729
- const client = { id: clientId, ws: wsLike };
13631
+ const peer = extractPeerInfo(req);
13632
+ const client = { id: clientId, ws: wsLike, ...peer ? { peer } : {} };
11730
13633
  this.sessionManager.addClient(client);
11731
13634
  if (sessionIdFromUrl) {
11732
13635
  client.requestedSessionId = sessionIdFromUrl;
@@ -11776,7 +13679,7 @@ var WSServer = class extends EventEmitter2 {
11776
13679
  if (initPage) {
11777
13680
  (async () => {
11778
13681
  try {
11779
- const vp = this.streamCoordinator.getLastFrameViewport() || initPage.viewportSize() || await initPage.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
13682
+ const vp = this.streamCoordinator.getLastFrameViewport(initSessionId) || initPage.viewportSize() || await initPage.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));
11780
13683
  this.sendToClient(clientId, {
11781
13684
  type: "status",
11782
13685
  data: { status: "connected", sessionId: initSessionId || void 0, viewport: vp ?? void 0 }
@@ -11829,6 +13732,22 @@ var WSServer = class extends EventEmitter2 {
11829
13732
  });
11830
13733
  return;
11831
13734
  }
13735
+ if (msg.type === "workspace_request" || msg.type === "workspace_navigate" || msg.type === "workspace_history" || msg.type === "workspace_tab") {
13736
+ const trust = checkWorkspaceTrust(this.sessionManager.getClient(clientId)?.peer, this.port);
13737
+ if (!trust.ok) {
13738
+ this.sendToClient(clientId, { type: "workspace_error", message: trust.reason });
13739
+ return;
13740
+ }
13741
+ await this.workspaceController.dispatch({
13742
+ clientId,
13743
+ sessionId,
13744
+ message: msg,
13745
+ sendToClient: (id, message) => this.sendToClient(id, message),
13746
+ sendToTrustedSessionClients: (sid, message) => this.sendWorkspaceToSessionClients(sid, message),
13747
+ broadcastToSession: (sid, message) => this.broadcastToSession(sid, message)
13748
+ });
13749
+ return;
13750
+ }
11832
13751
  const ctx = {
11833
13752
  clientId,
11834
13753
  sessionId,
@@ -11870,6 +13789,21 @@ var WSServer = class extends EventEmitter2 {
11870
13789
  this.sendToClient(clientId, message);
11871
13790
  }
11872
13791
  }
13792
+ /**
13793
+ * Sends a workspace message ONLY to the session's trusted clients
13794
+ * (loopback peer / loopback Viewer origin, per checkWorkspaceTrust).
13795
+ * `workspace_state` carries tab titles/URLs of managed sessions and must
13796
+ * never be broadcast to legacy LAN clients bound to the same session.
13797
+ */
13798
+ sendWorkspaceToSessionClients(sessionId, message) {
13799
+ const clients = this.sessionManager.getSessionClients(sessionId);
13800
+ if (!clients) return;
13801
+ for (const clientId of clients) {
13802
+ const peer = this.sessionManager.getClient(clientId)?.peer;
13803
+ if (!checkWorkspaceTrust(peer, this.port).ok) continue;
13804
+ this.sendToClient(clientId, message);
13805
+ }
13806
+ }
11873
13807
  broadcast(message) {
11874
13808
  for (const clientId of this.sessionManager.getAllClientIds()) {
11875
13809
  this.sendToClient(clientId, message);
@@ -12032,12 +13966,195 @@ connectWS();
12032
13966
  </script></body></html>`;
12033
13967
  }
12034
13968
 
13969
+ // src/daemon/preview-workspace.ts
13970
+ var glyphs = {
13971
+ plus: '<path d="M12 5v14M5 12h14"/>',
13972
+ back: '<path d="m12 19-7-7 7-7M5 12h14"/>',
13973
+ forward: '<path d="M5 12h14m-7-7 7 7-7 7"/>',
13974
+ reload: '<path d="M20 7v5h-5M4 17v-5h5"/><path d="M6 7a7 7 0 0 1 12-1l2 6M4 12l2 6a7 7 0 0 0 12-1"/>'
13975
+ };
13976
+ function icon(name) {
13977
+ return `<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${glyphs[name]}</svg>`;
13978
+ }
13979
+ var workspaceHeader = `
13980
+ <header class="workspace-header">
13981
+ <div class="workspace-top">
13982
+ <span class="workspace-brand">xbrowser</span>
13983
+ <div id="workspace-tabs" class="workspace-tabs" aria-label="\u6D4F\u89C8\u5668\u6807\u7B7E\u9875"></div>
13984
+ <button type="button" class="workspace-icon" id="workspace-new" disabled aria-label="\u65B0\u5EFA\u6807\u7B7E\u9875" title="\u65B0\u5EFA\u6807\u7B7E\u9875">${icon("plus")}</button>
13985
+ <div class="workspace-status" id="workspace-status" role="status"><span class="workspace-dot"></span><span id="workspace-status-text">\u8FDE\u63A5\u4E2D</span></div>
13986
+ </div>
13987
+ <div class="workspace-navigation">
13988
+ <button type="button" class="workspace-icon" data-workspace-history="back" disabled aria-label="\u540E\u9000" title="\u540E\u9000">${icon("back")}</button>
13989
+ <button type="button" class="workspace-icon" data-workspace-history="forward" disabled aria-label="\u524D\u8FDB" title="\u524D\u8FDB">${icon("forward")}</button>
13990
+ <button type="button" class="workspace-icon" data-workspace-history="reload" disabled aria-label="\u5237\u65B0" title="\u5237\u65B0">${icon("reload")}</button>
13991
+ <form id="workspace-address-form" class="workspace-address-form" role="search">
13992
+ <input id="workspace-address" aria-label="\u7F51\u9875\u5730\u5740" autocomplete="off" spellcheck="false" inputmode="url" placeholder="\u8F93\u5165\u7F51\u5740" readonly>
13993
+ </form>
13994
+ </div>
13995
+ <p id="workspace-error" class="workspace-error" role="alert" hidden></p>
13996
+ </header>`;
13997
+ var workspaceStyle = `
13998
+ :root{color-scheme:dark;--work-base:#101517;--work-panel:#181f21;--work-press:#233033;--work-line:#344145;--work-text:#e0eceb;--work-muted:#a1b7b6;--work-accent:#83dfc5}
13999
+ html,body{background:var(--work-base);color:var(--work-text);font-family:Geist,"Helvetica Neue",sans-serif}
14000
+ [hidden]{display:none!important}
14001
+ .workspace-header{flex:none;background:var(--work-panel);color:var(--work-text)}
14002
+ .workspace-top,.workspace-navigation{display:flex;align-items:center;gap:6px;padding:6px 12px;border-bottom:1px solid var(--work-line);min-width:0}
14003
+ .workspace-top{min-height:43px;background:#141b1d}
14004
+ .workspace-brand{font:700 12px/1.2 "IBM Plex Mono",monospace;color:var(--work-accent);margin-right:8px;flex:none}
14005
+ .workspace-tabs{display:flex;align-items:center;gap:3px;min-width:0;overflow-x:auto;scrollbar-width:thin}
14006
+ .workspace-tab{display:flex;align-items:center;border:1px solid transparent;border-radius:8px;max-width:205px;min-width:78px;background:var(--work-base)}
14007
+ .workspace-tab.active{background:var(--work-press);border-color:var(--work-line)}
14008
+ .workspace-tab-select{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;border:0;background:transparent;color:var(--work-text);font:inherit;font-size:12px;padding:7px 10px;text-align:left;cursor:pointer}
14009
+ .workspace-tab .workspace-icon{min-width:24px;height:24px;margin-right:2px}
14010
+ .workspace-status{margin-left:auto;display:flex;align-items:center;gap:6px;white-space:nowrap;font-size:12px;color:var(--work-muted)}
14011
+ .workspace-dot{width:7px;height:7px;border-radius:50%;background:var(--work-muted)}
14012
+ .workspace-status[data-state=live] .workspace-dot{background:var(--work-accent)}
14013
+ .workspace-status[data-state=waiting]{color:#ffca8a}
14014
+ .workspace-status[data-state=waiting] .workspace-dot{background:#ffca8a}
14015
+ .workspace-icon,.workspace-button{display:inline-flex;align-items:center;justify-content:center;min-width:30px;min-height:29px;border:1px solid transparent;border-radius:7px;background:transparent;color:var(--work-text);cursor:pointer;font:inherit;font-size:12px}
14016
+ .workspace-icon:hover:enabled,.workspace-icon[aria-expanded=true],.workspace-button:hover:enabled{background:var(--work-press)}
14017
+ .workspace-icon:disabled,.workspace-button:disabled{opacity:.4;cursor:default}
14018
+ .workspace-header :focus-visible{outline:2px solid var(--work-accent);outline-offset:1px}
14019
+ .workspace-address-form{flex:1;min-width:0;margin:0 2px}
14020
+ .workspace-address-form input{width:100%;min-height:30px;padding:6px 10px;border:1px solid var(--work-line);border-radius:7px;background:var(--work-base);color:var(--work-text);font:12px/1.4 "IBM Plex Mono",monospace}
14021
+ .workspace-address-form input[readonly]{color:var(--work-muted)}
14022
+ .workspace-error{padding:6px 12px;color:#ffca8a;font-size:12px;overflow-wrap:anywhere}
14023
+ .workspace-body{flex:1 1 0;min-height:0;display:flex;position:relative}
14024
+ .viewport{background:var(--work-base)}
14025
+ .viewport .waiting{color:var(--work-muted)}
14026
+ .bar{background:var(--work-panel);border-color:var(--work-line);height:34px}
14027
+ .bar #url{color:var(--work-muted)}
14028
+ #handoff-done{background:#224138;color:#baffeb;padding:0 9px}
14029
+ @media(max-width:520px){
14030
+ body{height:100dvh}
14031
+ .workspace-top,.workspace-navigation{padding:3px 6px;gap:3px}
14032
+ .workspace-brand{margin-right:2px}
14033
+ .workspace-tab{max-width:135px}
14034
+ .workspace-icon,.workspace-tab-select,.workspace-tab .workspace-icon{min-height:44px}
14035
+ .workspace-icon,.workspace-tab .workspace-icon{min-width:44px}
14036
+ .workspace-address-form input{min-height:44px;font-size:16px}
14037
+ .touchpad{flex:0 0 clamp(72px,18vh,150px)}
14038
+ .bar{height:46px;gap:4px;padding:0 5px}
14039
+ .bar .conn,.bar .quality-badge{display:none}
14040
+ #handoff-done{min-height:44px}
14041
+ }
14042
+ `;
14043
+ var workspaceScript = String.raw`
14044
+ function createWorkspace({ getUrl, send }) {
14045
+ const address = $('workspace-address');
14046
+ const tabList = $('workspace-tabs');
14047
+ const newTab = $('workspace-new');
14048
+ const nav = [...document.querySelectorAll('[data-workspace-history]')];
14049
+ const error = $('workspace-error');
14050
+ const status = $('workspace-status');
14051
+ const statusText = $('workspace-status-text');
14052
+ const resume = $('handoff-done');
14053
+ let connected = false;
14054
+ let waiting = false;
14055
+ let lastUrl = '';
14056
+ let renderedTabs = '';
14057
+
14058
+ function showConnection(next) {
14059
+ connected = next;
14060
+ status.dataset.state = waiting && next ? 'waiting' : next ? 'live' : 'offline';
14061
+ statusText.textContent = next ? (waiting ? '等待人工继续' : '已连接') : '已断开';
14062
+ resume.hidden = !next || !waiting;
14063
+ }
14064
+
14065
+ function enableControls(enabled) {
14066
+ address.readOnly = !enabled;
14067
+ newTab.disabled = !enabled;
14068
+ for (const button of nav) button.disabled = !enabled;
14069
+ }
14070
+
14071
+ function updateUrl(url) {
14072
+ lastUrl = url;
14073
+ if (document.activeElement !== address) address.value = url === 'about:blank' ? '' : url;
14074
+ }
14075
+
14076
+ function showTabs(message) {
14077
+ waiting = message.handoffWaiting === true;
14078
+ showConnection(connected);
14079
+ const tabs = Array.isArray(message.tabs) ? message.tabs : [];
14080
+ const editable = message.readOnly !== true && tabs.length > 0;
14081
+ enableControls(editable);
14082
+ error.hidden = true;
14083
+ const activeTab = tabs.find(tab => tab.index === message.activeIndex);
14084
+ if (activeTab) updateUrl(activeTab.url || '');
14085
+ const tabState = JSON.stringify([tabs, message.activeIndex, editable]);
14086
+ if (tabState === renderedTabs) return;
14087
+ renderedTabs = tabState;
14088
+ tabList.replaceChildren(...tabs.map(tab => {
14089
+ const row = document.createElement('div');
14090
+ const active = tab.index === message.activeIndex;
14091
+ row.className = 'workspace-tab' + (active ? ' active' : '');
14092
+ const choose = document.createElement('button');
14093
+ choose.type = 'button';
14094
+ choose.className = 'workspace-tab-select';
14095
+ choose.textContent = tab.title || (tab.url === 'about:blank' ? '新标签页' : tab.url) || '标签页';
14096
+ choose.title = choose.textContent;
14097
+ choose.setAttribute('aria-pressed', String(active));
14098
+ choose.disabled = !editable;
14099
+ choose.addEventListener('click', () => send({type:'workspace_tab',action:'select',tabId:tab.id}));
14100
+ row.append(choose);
14101
+ if (editable && tabs.length > 1) {
14102
+ const close = document.createElement('button');
14103
+ close.type = 'button';
14104
+ close.className = 'workspace-icon';
14105
+ close.textContent = '×';
14106
+ close.setAttribute('aria-label', '关闭 ' + choose.textContent);
14107
+ close.addEventListener('click', () => send({type:'workspace_tab',action:'close',tabId:tab.id}));
14108
+ row.append(close);
14109
+ }
14110
+ return row;
14111
+ }));
14112
+ }
14113
+
14114
+ $('workspace-address-form').addEventListener('submit', event => {
14115
+ event.preventDefault();
14116
+ const url = address.value.trim();
14117
+ if (!address.readOnly && url) {
14118
+ address.blur();
14119
+ send({type:'workspace_navigate',url});
14120
+ }
14121
+ });
14122
+ address.addEventListener('keydown', event => {
14123
+ if (event.key === 'Escape') { address.blur(); updateUrl(lastUrl); }
14124
+ });
14125
+ newTab.addEventListener('click', () => send({type:'workspace_tab',action:'new'}));
14126
+ nav.forEach(button => button.addEventListener('click', () => send({type:'workspace_history',action:button.dataset.workspaceHistory})));
14127
+
14128
+ return {
14129
+ open() { showConnection(true); },
14130
+ bound() { send({type:'workspace_request'}); },
14131
+ close() {
14132
+ waiting = false;
14133
+ renderedTabs = '';
14134
+ enableControls(false);
14135
+ for (const button of tabList.querySelectorAll('button')) button.disabled = true;
14136
+ showConnection(false);
14137
+ },
14138
+ frame() { updateUrl(getUrl()); },
14139
+ message(message) {
14140
+ if (message.type === 'workspace_state') { showTabs(message); return true; }
14141
+ if (message.type === 'workspace_error') { error.textContent = message.message; error.hidden = false; return true; }
14142
+ if (message.type === 'captcha-detected') { waiting = true; showConnection(connected); }
14143
+ if (message.type === 'resolved' || message.type === 'handoff-timeout') { waiting = false; showConnection(connected); }
14144
+ return false;
14145
+ },
14146
+ };
14147
+ }
14148
+ `;
14149
+
12035
14150
  // src/daemon/preview-main-template.ts
12036
14151
  function previewHTML(sessionId, _host) {
14152
+ const safeTitle = sessionId.replace(/[&<>]/g, (char) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" })[char]);
14153
+ const sessionLiteral = JSON.stringify(sessionId).replace(/</g, "\\u003c");
12037
14154
  return `<!DOCTYPE html>
12038
14155
  <html lang="en"><head><meta charset="utf-8">
12039
14156
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
12040
- <title>xbrowser \u2014 ${sessionId}</title>
14157
+ <title>xbrowser \u2014 ${safeTitle}</title>
12041
14158
  <style>
12042
14159
  *{margin:0;padding:0;box-sizing:border-box;-webkit-tap-highlight-color:transparent}
12043
14160
  html,body{height:100%;overflow:hidden;background:#1a1a2e;color:#eee;font-family:system-ui,-apple-system,sans-serif}
@@ -12103,11 +14220,14 @@ body{display:flex;flex-direction:column;touch-action:manipulation}
12103
14220
  .view-tab span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
12104
14221
  .view-tab.active{background:#0f3460;color:#cde;font-weight:600}
12105
14222
  .view-tab:active{background:#1a5276}
14223
+ ${workspaceStyle}
12106
14224
  </style></head><body>
14225
+ ${workspaceHeader}
12107
14226
  <div class="bar">
12108
14227
  <span class="dot" id="status"></span>
12109
14228
  <span class="url" id="url">connecting...</span>
12110
14229
  <span class="conn" id="conn"></span>
14230
+ <button type="button" class="mode-btn" id="handoff-done" title="\u7EE7\u7EED\u6682\u505C\u7684\u4EFB\u52A1" hidden>\u7EE7\u7EED\u4EFB\u52A1</button>
12111
14231
  <button class="mode-btn" id="mode-btn" title="Switch mode (Mobile/Tablet/PC)">\u{1F4F1}</button>
12112
14232
  <div id="qualityBadge" class="quality-badge quality-static" style="font-size:10px;padding:2px 8px;border-radius:10px;background:#556;color:#eee;white-space:nowrap;flex-shrink:0">static</div>
12113
14233
  <button id="stats-btn" style="font-size:11px;padding:2px 8px;border-radius:10px;background:#0f3460;color:#8af;border:none;cursor:pointer;flex-shrink:0">\u{1F4CA}</button>
@@ -12139,10 +14259,12 @@ body{display:flex;flex-direction:column;touch-action:manipulation}
12139
14259
  <div>Uptime: <span id="stat-uptime" style="color:#8af">0s</span></div>
12140
14260
  </div>
12141
14261
  <div class="view-tabs" id="view-tabs"></div>
14262
+ <div class="workspace-body">
12142
14263
  <div class="viewport" id="viewport">
12143
14264
  <canvas id="screen"></canvas>
12144
14265
  <div class="waiting" id="wait">Waiting for screencast...</div>
12145
14266
  </div>
14267
+ </div>
12146
14268
  <div class="toolbar" id="toolbar">
12147
14269
  <button class="toolbar-btn" data-key="Tab">Tab</button>
12148
14270
  <button class="toolbar-btn" data-key="ArrowUp">&uarr;</button>
@@ -12192,7 +14314,7 @@ body{display:flex;flex-direction:column;touch-action:manipulation}
12192
14314
  <div class="cursor-label" id="cursor-label"></div>
12193
14315
  <script>
12194
14316
  (function(){
12195
- const sid='${sessionId}';
14317
+ const sid=${sessionLiteral};
12196
14318
  const PROTO=location.protocol==='https:'?'wss:':'ws:';
12197
14319
  let ws=null;
12198
14320
  let connected=false;
@@ -12216,7 +14338,7 @@ let statEl=null;
12216
14338
  let lastHoverSent=0;
12217
14339
 
12218
14340
  const $=id=>document.getElementById(id);
12219
- const canvas=$('screen'),ctx=canvas.getContext('2d');wait=$('wait'),dot=$('status'),urlEl=$('url'),connEl=$('conn');
14341
+ const canvas=$('screen'),ctx=canvas.getContext('2d'),wait=$('wait'),dot=$('status'),urlEl=$('url'),connEl=$('conn');
12220
14342
  const viewportEl=$('viewport'),cursorEl=$('cursor'),cursorLabelEl=$('cursor-label');
12221
14343
  const touchpadEl=$('touchpad'),toolbarEl=$('toolbar');
12222
14344
  const inputPanel=$('input-panel'),inputField=$('input-field'),inputLabel=$('input-label');
@@ -12362,28 +14484,20 @@ function resizeCanvas(){
12362
14484
  const box=viewportEl.getBoundingClientRect();
12363
14485
  const bw=box.width,bh=box.height;
12364
14486
  if(!bw||!bh||!remoteViewport.width||!remoteViewport.height) return;
12365
- const vpAspect=remoteViewport.width/remoteViewport.height;
12366
- // Fit the remote viewport inside the available box without cropping:
12367
- // pick the scale that keeps both dimensions within bounds.
12368
- const scaleByWidth=bw/remoteViewport.width;
12369
- const scaleByHeight=bh/remoteViewport.height;
12370
- const scale=Math.min(scaleByWidth,scaleByHeight);
12371
- const cw=remoteViewport.width*scale;
12372
- const ch=remoteViewport.height*scale;
12373
- if(canvas.width!==Math.round(cw)||canvas.height!==Math.round(ch)){
12374
- canvas.width=Math.round(cw);
12375
- canvas.height=Math.round(ch);
12376
- }
12377
- canvas.style.width=cw+'px';
12378
- canvas.style.height=ch+'px';
14487
+ // Keep the last frame in the backing canvas when the notes panel or
14488
+ // window changes the available display size.
14489
+ const scale=Math.min(bw/remoteViewport.width,bh/remoteViewport.height);
14490
+ canvas.style.width=(remoteViewport.width*scale)+'px';
14491
+ canvas.style.height=(remoteViewport.height*scale)+'px';
12379
14492
  }
12380
14493
  window.addEventListener('resize',resizeCanvas);
12381
14494
  resizeCanvas();
12382
14495
 
12383
14496
  function drawFrame(bitmap){
12384
- const cw=canvas.width,ch=canvas.height;
12385
- if(!cw||!ch) return;
12386
- ctx.drawImage(bitmap,0,0,cw,ch);
14497
+ const cw=bitmap.width,ch=bitmap.height;
14498
+ if(canvas.width!==cw) canvas.width=cw;
14499
+ if(canvas.height!==ch) canvas.height=ch;
14500
+ ctx.drawImage(bitmap,0,0);
12387
14501
  if(activeViewId==='main'&&!viewSwitching){
12388
14502
  if(!fullPageSnapshot) fullPageSnapshot=document.createElement('canvas');
12389
14503
  if(fullPageSnapshot.width!==cw||fullPageSnapshot.height!==ch){
@@ -12400,6 +14514,7 @@ function connectWS(){
12400
14514
  connected=true;
12401
14515
  dot.className='dot ok';
12402
14516
  connEl.textContent='WS';
14517
+ workspace.open();
12403
14518
  if(deviceMode==='desktop') createPCKeyboard();
12404
14519
  checkFocus();
12405
14520
  // Apply crop from URL params (?crop=x,y,w,h or ?selector=.cls)
@@ -12412,6 +14527,7 @@ function connectWS(){
12412
14527
  try{
12413
14528
  if(typeof e.data==='string'){
12414
14529
  var _m=JSON.parse(e.data);
14530
+ if(workspace.message(_m)) return;
12415
14531
  if(_m.type==='views_update'){
12416
14532
  updateViewTabs(_m.views);
12417
14533
  return;
@@ -12464,6 +14580,7 @@ function connectWS(){
12464
14580
  currentUrl=header.data.url;
12465
14581
  urlEl.textContent=currentUrl;
12466
14582
  }
14583
+ workspace.frame();
12467
14584
  if(header.data.streamState) updateQualityBadge(header.data.streamState,header.data.fps);
12468
14585
  }
12469
14586
  return;
@@ -12487,6 +14604,7 @@ function connectWS(){
12487
14604
  currentUrl=m.data.url;
12488
14605
  urlEl.textContent=currentUrl;
12489
14606
  }
14607
+ workspace.frame();
12490
14608
  }else if(m.type==='error'&&m.data.code==='SESSION_NOT_FOUND'){
12491
14609
  dot.className='dot';
12492
14610
  connEl.textContent='ERR';
@@ -12499,7 +14617,10 @@ function connectWS(){
12499
14617
  },3000);
12500
14618
  }else if(m.type==='status'){
12501
14619
  connEl.textContent=m.data.status==='connected'?'OK':'...';
12502
- if(m.data.message) urlEl.textContent=m.data.message;
14620
+ if(m.data.message){
14621
+ urlEl.textContent=m.data.message;
14622
+ if(m.data.status==='connected'&&m.data.sessionId===sid) workspace.bound();
14623
+ }
12503
14624
  if(m.data.viewport){
12504
14625
  if(viewSwitching){
12505
14626
  remoteViewport=m.data.viewport;
@@ -12516,6 +14637,7 @@ function connectWS(){
12516
14637
  }else if(m.type==='navigation'){
12517
14638
  currentUrl=m.url||'';
12518
14639
  urlEl.textContent=currentUrl;
14640
+ workspace.frame();
12519
14641
  }else if(m.type==='input_focused'){
12520
14642
  if(suppressFocus) return;
12521
14643
  currentFocusedSelector=m.selector||'';
@@ -12573,6 +14695,7 @@ function connectWS(){
12573
14695
  dot.className='dot';
12574
14696
  connEl.textContent='';
12575
14697
  urlEl.textContent='disconnected';
14698
+ workspace.close();
12576
14699
  wait.style.display='block';
12577
14700
  canvas.style.display='none';
12578
14701
  if(originalViewport){remoteViewport=originalViewport;originalViewport=null;viewportLocked=false;}
@@ -12702,6 +14825,8 @@ function sendMsg(obj){
12702
14825
  }
12703
14826
  }
12704
14827
 
14828
+ $('handoff-done').addEventListener('click',()=>sendMsg({type:'solved'}));
14829
+
12705
14830
  function parseFocusHash(){
12706
14831
  var h=location.hash;
12707
14832
  if(!h) return null;
@@ -12880,6 +15005,7 @@ var _pcKBInit=false;
12880
15005
  var _pcComposing=false;
12881
15006
  var pcHiddenInput=null;
12882
15007
  var pcLastInputValue='';
15008
+ const pcForwardedKeys=new Set();
12883
15009
  function createPCKeyboard(){
12884
15010
  if(_pcKBInit) return;
12885
15011
  _pcKBInit=true;
@@ -12908,6 +15034,7 @@ function createPCKeyboard(){
12908
15034
  });
12909
15035
  document.addEventListener('keydown',function(e){
12910
15036
  if(deviceMode!=='desktop') return;
15037
+ if(e.target instanceof Element && e.target.closest('.workspace-header,.bar')) return;
12911
15038
  if(e.isComposing||_pcComposing) return;
12912
15039
  var key=e.key;
12913
15040
  if(!key) return;
@@ -12920,6 +15047,7 @@ function createPCKeyboard(){
12920
15047
  if(!isControlKey&&(tag==='INPUT'||tag==='TEXTAREA')) return;
12921
15048
 
12922
15049
  e.preventDefault();
15050
+ pcForwardedKeys.add(e.code||key);
12923
15051
  sendMsg({type:'input_keyboard',action:'down',key:key});
12924
15052
  if(key.length===1){
12925
15053
  sendMsg({type:'input_insert_text',text:key});
@@ -12927,15 +15055,8 @@ function createPCKeyboard(){
12927
15055
  sendUserActivity();
12928
15056
  });
12929
15057
  document.addEventListener('keyup',function(e){
12930
- if(deviceMode!=='desktop') return;
12931
- if(e.isComposing||_pcComposing) return;
12932
- var key=e.key;
12933
- if(!key) return;
12934
-
12935
- var isControlKey=key.length>1;
12936
- var tag=e.target&&e.target.tagName;
12937
- if(!isControlKey&&(tag==='INPUT'||tag==='TEXTAREA')) return;
12938
-
15058
+ const key=e.key;
15059
+ if(!key||!pcForwardedKeys.delete(e.code||key)) return;
12939
15060
  e.preventDefault();
12940
15061
  sendMsg({type:'input_keyboard',action:'up',key:key});
12941
15062
  sendUserActivity();
@@ -12945,7 +15066,7 @@ function removePCKeyboard(){}
12945
15066
  function pcFocusHiddenInput(){
12946
15067
  if(deviceMode==='desktop'&&pcHiddenInput&&document.activeElement!==pcHiddenInput){
12947
15068
  var tag=document.activeElement&&document.activeElement.tagName;
12948
- if(tag!=='INPUT'&&tag!=='TEXTAREA'){
15069
+ if(tag!=='INPUT'&&tag!=='TEXTAREA'&&!document.activeElement?.closest('.workspace-header,.bar')){
12949
15070
  pcHiddenInput.focus({preventScroll:true});
12950
15071
  }
12951
15072
  }
@@ -13237,8 +15358,7 @@ inputField.addEventListener('keydown',(e)=>{
13237
15358
  // --- Device Mode ---
13238
15359
  function detectMode(){
13239
15360
  if('ontouchstart' in window||navigator.maxTouchPoints>0){
13240
- var w=window.screen.width,h=window.screen.height;
13241
- var minDim=Math.min(w,h);
15361
+ const minDim=Math.min(window.innerWidth,window.innerHeight);
13242
15362
  if(minDim>=768) return 'tablet';
13243
15363
  return 'mobile';
13244
15364
  }
@@ -13425,14 +15545,16 @@ window.__xb_getState=function(){
13425
15545
  // --- Init ---
13426
15546
  deviceMode=detectMode();
13427
15547
  applyMode(deviceMode);
15548
+ ${workspaceScript}
15549
+ const workspace=createWorkspace({getUrl:()=>currentUrl,send:sendMsg});
13428
15550
  connectWS();
13429
15551
  })();
13430
15552
  </script></body></html>`;
13431
15553
  }
13432
15554
 
13433
15555
  // src/daemon/daemon-main.ts
13434
- var CONFIG_DIR3 = join9(homedir7(), ".xbrowser");
13435
- var LOG_FILE = join9(CONFIG_DIR3, "daemon.log");
15556
+ var CONFIG_DIR3 = join10(homedir8(), ".xbrowser");
15557
+ var LOG_FILE = join10(CONFIG_DIR3, "daemon.log");
13436
15558
  function log(msg) {
13437
15559
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").substring(0, 19);
13438
15560
  const line = `[DAEMON ${ts}] ${msg}
@@ -13445,7 +15567,8 @@ function log(msg) {
13445
15567
  async function main() {
13446
15568
  process.env.XBROWSER_DAEMON_WORKER = "1";
13447
15569
  const daemonPort = parseInt(process.env.XBROWSER_DAEMON_PORT || "9224", 10);
13448
- log(`Daemon main starting (pid=${process.pid})`);
15570
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
15571
+ log(`Daemon main starting (pid=${process.pid} version=${version} build=${buildId})`);
13449
15572
  const rpcHandler = createRPCHandler();
13450
15573
  const server = startHttpServer({
13451
15574
  port: daemonPort,
@@ -13455,7 +15578,7 @@ async function main() {
13455
15578
  pathname: "/health",
13456
15579
  handler: (_req, res) => {
13457
15580
  res.writeHead(200, { "Content-Type": "application/json" });
13458
- res.end(JSON.stringify({ status: "ok", pid: process.pid, version }));
15581
+ res.end(JSON.stringify(buildHealthPayload({ version, buildId }, startedAt, process.pid)));
13459
15582
  }
13460
15583
  }
13461
15584
  ]
@@ -13464,7 +15587,7 @@ async function main() {
13464
15587
  if (err.code === "EADDRINUSE") {
13465
15588
  log(`Port ${daemonPort} already in use \u2014 another daemon instance likely won the startup race. Exiting gracefully.`);
13466
15589
  try {
13467
- unlinkSync(join9(CONFIG_DIR3, "daemon.json"));
15590
+ unlinkSync2(join10(CONFIG_DIR3, "daemon.json"));
13468
15591
  } catch {
13469
15592
  }
13470
15593
  process.exit(0);
@@ -13496,6 +15619,20 @@ async function main() {
13496
15619
  await previewWS.attachToServer(server, "/preview");
13497
15620
  log(`Preview WS attached to HTTP server on /preview`);
13498
15621
  rpcHandler.setPreviewWS(previewWS);
15622
+ previewWS.setWorkspaceSessionResolver((sessionId) => {
15623
+ const session = findSession(sessionId);
15624
+ if (!session) return void 0;
15625
+ if (session.isCDP || session.bridge) {
15626
+ return { page: session.page, context: null, managed: false };
15627
+ }
15628
+ return {
15629
+ page: session.page,
15630
+ context: session.context,
15631
+ managed: true,
15632
+ setActivePage: (page) => setActivePage(session, page)
15633
+ };
15634
+ });
15635
+ previewWS.setWorkspaceHandoffProbe((sessionId) => isHumanWaitActive(previewWS, sessionId));
13499
15636
  previewWS.on("screencast-started", (sid) => log(`Preview screencast started: ${sid}`));
13500
15637
  previewWS.on("screencast-stopped", (sid) => log(`Preview screencast stopped: ${sid}`));
13501
15638
  previewWS.on("reconnect-request", ({ sessionId }) => {
@@ -13505,8 +15642,8 @@ async function main() {
13505
15642
  log(`Reconnect failed: ${e instanceof Error ? e.message : String(e)}`);
13506
15643
  });
13507
15644
  });
13508
- mkdirSync5(CONFIG_DIR3, { recursive: true });
13509
- writeFileSync5(join9(CONFIG_DIR3, "daemon.json"), JSON.stringify({
15645
+ mkdirSync6(CONFIG_DIR3, { recursive: true });
15646
+ writeFileSync6(join10(CONFIG_DIR3, "daemon.json"), JSON.stringify({
13510
15647
  port: daemonPort,
13511
15648
  pid: process.pid,
13512
15649
  startedAt: Date.now()
@@ -13540,14 +15677,18 @@ async function main() {
13540
15677
  console.error("Daemon unhandledRejection:", msg);
13541
15678
  });
13542
15679
  try {
13543
- const bridgeUp = await fetch("http://127.0.0.1:9347/status").then((r) => r.ok).catch(() => false);
13544
- if (!bridgeUp) {
13545
- const { spawn } = await import("child_process");
13546
- const path2 = await import("path");
13547
- const serverPath = path2.join(process.cwd(), ".xcli", "plugins", "chrome-bridge", "server.mjs");
13548
- const child = spawn(process.execPath, [serverPath, "9346"], { detached: true, stdio: "ignore" });
13549
- child.unref();
13550
- log("chrome-bridge server auto-started (WS:9346/HTTP:9347)");
15680
+ if (process.env.XBROWSER_BRIDGE_HTTP) {
15681
+ log("chrome-bridge autostart skipped (XBROWSER_BRIDGE_HTTP set)");
15682
+ } else {
15683
+ const bridgeUp = await fetch("http://127.0.0.1:9347/status").then((r) => r.ok).catch(() => false);
15684
+ if (!bridgeUp) {
15685
+ const { spawn } = await import("child_process");
15686
+ const path2 = await import("path");
15687
+ const serverPath = path2.join(process.cwd(), ".xcli", "plugins", "chrome-bridge", "server.mjs");
15688
+ const child = spawn(process.execPath, [serverPath, "9346"], { detached: true, stdio: "ignore" });
15689
+ child.unref();
15690
+ log("chrome-bridge server auto-started (WS:9346/HTTP:9347)");
15691
+ }
13551
15692
  }
13552
15693
  } catch {
13553
15694
  }