@liang-hz/agent-in-chrome 0.55.2 → 0.56.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.
package/scripts/e2e.mjs CHANGED
@@ -9,6 +9,9 @@ import path from "node:path";
9
9
  import { fileURLToPath, pathToFileURL } from "node:url";
10
10
  import { getToken, timingSafeEqualStr, tokenPath, bridgeEndpoint, handshakeNonce, handshakeProof } from "../mcp/token.mjs";
11
11
 
12
+ if (process.platform === "win32" && !process.env.AGENT_IN_CHROME_REG_ROOT)
13
+ process.env.AGENT_IN_CHROME_REG_ROOT = `HKCU\\Software\\aic-e2e-${process.pid}`;
14
+
12
15
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
13
16
  const TMP = fs.mkdtempSync(path.join(os.tmpdir(), "agent-in-chrome-e2e-"));
14
17
  const SOCK = path.join(TMP, "t.sock");
@@ -184,7 +187,7 @@ check("包含核心的 browser_tab_use", tools.some((t) => t.name === "browser_t
184
187
  const b = tools.find((t) => t.name === "browser_batch");
185
188
  const d = b?.description || "";
186
189
  check("batch 描述给出的是判据,不是场景清单", /single criterion/i.test(d), d.slice(0, 200));
187
- check("判据落在「必须先看到前面某步的内容」上", /SEEING/.test(d) && /content/i.test(d), d.slice(0, 320));
190
+ check("判据落在「必须先看到前面某步的内容」上", /\bSEE\b/.test(d) && /content/i.test(d), d.slice(0, 320));
188
191
  check("讲清了「取值」不用切、「判断」才要切", /VALUE/.test(d) && /decision/i.test(d), d.slice(0, 800));
189
192
  check(
190
193
  "说明判据与工具种类/步数无关(防止再被某个例子定尺度)",
@@ -495,6 +498,20 @@ check("未知工具返回 JSON-RPC error", !!unknown.error, JSON.stringify(unkno
495
498
  });
496
499
  const bp = parse(badPath.text);
497
500
  check("路径不存在时停在那一步", bp.ok === false && bp.failedAt === 2 && bp.ran === 2, badPath.text.slice(0, 160));
501
+
502
+ const noPrefix = await callBatch({
503
+ steps: [{ tool: "scroll", args: { direction: "up" } }],
504
+ });
505
+ const np = parse(noPrefix.text);
506
+ check("P1-2: batch 省略 browser_ 前缀自动补全并成功执行", np.ok === true && np.results?.[0]?.tool === "browser_scroll", noPrefix.text.slice(0, 200));
507
+
508
+ const emptyArr = await callBatch({
509
+ steps: [
510
+ { tool: "browser_tabs_list", args: {} },
511
+ { tool: "browser_scroll", args: { ref: "{{steps[0].emptyArr[0].ref}}" } },
512
+ ],
513
+ });
514
+ check("P1-2: 空数组占位符越界给出 minMatches / wait_for 提示", emptyArr.text.includes("未找到匹配元素") || emptyArr.text.includes("空数组") || /matches\[0\]|emptyArr/.test(emptyArr.text), emptyArr.text.slice(0, 220));
498
515
  check("报错点名断在哪一层", /steps\[0\]/.test(bp.error || "") && /nothing/.test(bp.error || ""), bp.error);
499
516
  check("报错给出那一层的实际结构(键名,不倒数据)", /tabs/.test(bp.error || "") && /count/.test(bp.error || ""), bp.error);
500
517
  check("绝不拿 undefined 继续跑", /undefined/.test(bp.error || ""), bp.error);
@@ -944,6 +961,10 @@ console.log("\n\x1b[1mC. 启动器(最小 PATH)\x1b[0m");
944
961
  let runtimeHome = os.homedir();
945
962
  let RUNTIME_DIR = path.join(runtimeHome, ".agent-in-chrome", "agent-in-chrome");
946
963
  let installedForThisRun = null;
964
+ if (process.platform === "win32") {
965
+ skipSection("C/D 的启动器握手是 POSIX 机制(.sh + /usr/bin:/bin),Windows 的 .bat 启动器由安装器一节自己的段覆盖");
966
+ } else {
967
+
947
968
  if (!fs.existsSync(path.join(RUNTIME_DIR, "native-host-launcher.sh"))) {
948
969
  const SOCK_SUFFIX = "/.agent-in-chrome/agent-in-chrome.sock".length;
949
970
  let base = os.tmpdir();
@@ -1071,6 +1092,7 @@ const MCP_LAUNCHER = path.join(RUNTIME_DIR, "mcp-launcher.sh");
1071
1092
  mp.kill();
1072
1093
  }
1073
1094
  }
1095
+ }
1074
1096
 
1075
1097
  console.log("\n\x1b[1mE. 多会话并发\x1b[0m");
1076
1098
  {
@@ -1611,10 +1633,10 @@ console.log("\n\x1b[1mF3. 会话名按 params._meta 精确归属\x1b[0m");
1611
1633
  }
1612
1634
 
1613
1635
  console.log("\n\x1b[1mG. CLI 浏览器记录按 profile 隔离\x1b[0m");
1614
- if (process.platform === "win32") {
1615
- skipSection("CLI/headless 模式的进程记账走 /bin/sh 冒充 + /bin/ps 取证,Windows 上 CLI 模式尚未支持(插件模式不受影响)");
1616
- } else {
1636
+ {
1637
+ const G_WIN = process.platform === "win32";
1617
1638
  const G_HOME = path.join(TMP, "g-home");
1639
+ const homeEnv = G_WIN ? { HOME: G_HOME, USERPROFILE: G_HOME } : { HOME: G_HOME };
1618
1640
  const PROF_A = path.join(TMP, "g-prof-a");
1619
1641
  const PROF_B = path.join(TMP, "g-prof-b");
1620
1642
  for (const d of [G_HOME, PROF_A, PROF_B]) fs.mkdirSync(d, { recursive: true });
@@ -1626,14 +1648,14 @@ if (process.platform === "win32") {
1626
1648
  process.execPath,
1627
1649
  ["-e", `import(${JSON.stringify(LAUNCH_MOD)}).then((m) => console.log(JSON.stringify(m.browserStatus())))`],
1628
1650
  {
1629
- env: { ...process.env, HOME: G_HOME, ...(profileDir ? { AGENT_IN_CHROME_PROFILE: profileDir } : {}) },
1651
+ env: { ...process.env, ...homeEnv, ...(profileDir ? { AGENT_IN_CHROME_PROFILE: profileDir } : {}) },
1630
1652
  encoding: "utf8",
1631
1653
  }
1632
1654
  ).trim()
1633
1655
  );
1634
1656
  const stopUnder = (profileDir) =>
1635
1657
  execFileSync(process.execPath, [path.join(ROOT, "scripts", "cli-browser.mjs"), "--stop"], {
1636
- env: { ...process.env, HOME: G_HOME, AGENT_IN_CHROME_PROFILE: profileDir },
1658
+ env: { ...process.env, ...homeEnv, AGENT_IN_CHROME_PROFILE: profileDir },
1637
1659
  encoding: "utf8",
1638
1660
  });
1639
1661
 
@@ -1653,10 +1675,14 @@ if (process.platform === "win32") {
1653
1675
  );
1654
1676
  check("干净 profile 一开始什么都没有", stA.running === false && stA.stale === false, JSON.stringify(stA));
1655
1677
 
1656
- const impostor = spawn("/bin/sh", ["-c", "while :; do sleep 1; done", `--user-data-dir=${PROF_B}`], {
1657
- stdio: "ignore",
1658
- detached: true,
1659
- });
1678
+ const G_STUB = path.join(G_HOME, "impostor-stub.mjs");
1679
+ fs.writeFileSync(G_STUB, "setTimeout(() => {}, 300000);\n");
1680
+ const impostor = G_WIN
1681
+ ? spawn(process.execPath, [G_STUB, `--user-data-dir=${PROF_B}`], { stdio: "ignore", detached: true, windowsHide: true })
1682
+ : spawn("/bin/sh", ["-c", "while :; do sleep 1; done", `--user-data-dir=${PROF_B}`], {
1683
+ stdio: "ignore",
1684
+ detached: true,
1685
+ });
1660
1686
  let impostorExited = false;
1661
1687
  impostor.on("exit", () => (impostorExited = true));
1662
1688
  await sleep(300);
@@ -1692,20 +1718,21 @@ if (process.platform === "win32") {
1692
1718
 
1693
1719
  if (!impostorExited) {
1694
1720
  try {
1695
- process.kill(-impostor.pid, "SIGKILL");
1721
+ if (G_WIN) process.kill(impostor.pid, "SIGKILL");
1722
+ else process.kill(-impostor.pid, "SIGKILL");
1696
1723
  } catch {}
1697
1724
  }
1698
1725
  }
1699
1726
 
1700
1727
  console.log("\n\x1b[1mH. 认领在跑的浏览器:端点必须自证身份\x1b[0m");
1701
- if (process.platform === "win32") {
1702
- skipSection("CLI/headless 模式的认领流程走 /bin/sh 冒充进程,Windows 上 CLI 模式尚未支持(插件模式不受影响)");
1703
- } else {
1728
+ {
1729
+ const H_WIN = process.platform === "win32";
1704
1730
  const H_HOME = path.join(TMP, "h-home");
1731
+ const homeEnv = H_WIN ? { HOME: H_HOME, USERPROFILE: H_HOME } : { HOME: H_HOME };
1705
1732
  const PROF_C = path.join(TMP, "h-prof-c");
1706
1733
  for (const d of [H_HOME, PROF_C]) fs.mkdirSync(d, { recursive: true });
1707
1734
  const LAUNCH_MOD = pathToFileURL(path.join(ROOT, "mcp", "cdp", "browser-launch.mjs")).href;
1708
- const NO_CHROME = path.join(TMP, "no-such-chrome");
1735
+ const NO_CHROME = H_WIN ? path.join(TMP, "no-such-chrome.exe") : path.join(TMP, "no-such-chrome");
1709
1736
 
1710
1737
  const MINE = "/devtools/browser/11111111-1111-4111-8111-111111111111";
1711
1738
  const OTHERS = "/devtools/browser/22222222-2222-4222-8222-222222222222";
@@ -1739,7 +1766,7 @@ if (process.platform === "win32") {
1739
1766
  {
1740
1767
  env: {
1741
1768
  ...process.env,
1742
- HOME: H_HOME,
1769
+ ...homeEnv,
1743
1770
  AGENT_IN_CHROME_PROFILE: PROF_C,
1744
1771
  AGENT_IN_CHROME_BIN: NO_CHROME,
1745
1772
  AGENT_IN_CHROME_CDP_TRANSPORT: "port",
@@ -1763,14 +1790,18 @@ if (process.platform === "win32") {
1763
1790
  const stale = await ensure();
1764
1791
  check("没人占着 profile 时,旧端口文件当冷启动处理", stale.ok === false && stale.err.includes(NO_CHROME), stale.err);
1765
1792
 
1766
- const holder = spawn("/bin/sh", ["-c", "while :; do sleep 1; done", `--user-data-dir=${PROF_C}`], {
1767
- stdio: "ignore",
1768
- detached: true,
1769
- });
1793
+ const H_STUB = path.join(H_HOME, "holder-stub.mjs");
1794
+ fs.writeFileSync(H_STUB, "setTimeout(() => {}, 300000);\n");
1795
+ const holder = H_WIN
1796
+ ? spawn(process.execPath, [H_STUB, `--user-data-dir=${PROF_C}`], { stdio: "ignore", detached: true, windowsHide: true })
1797
+ : spawn("/bin/sh", ["-c", "while :; do sleep 1; done", `--user-data-dir=${PROF_C}`], {
1798
+ stdio: "ignore",
1799
+ detached: true,
1800
+ });
1770
1801
  let holderExited = false;
1771
1802
  holder.on("exit", () => (holderExited = true));
1772
- await sleep(300);
1773
- fs.symlinkSync(`${os.hostname()}-${holder.pid}`, path.join(PROF_C, "SingletonLock"));
1803
+ await sleep(H_WIN ? 500 : 300);
1804
+ if (!H_WIN) fs.symlinkSync(`${os.hostname()}-${holder.pid}`, path.join(PROF_C, "SingletonLock"));
1774
1805
 
1775
1806
  servedPath = OTHERS;
1776
1807
  const wrong = await ensure();
@@ -1781,12 +1812,17 @@ if (process.platform === "win32") {
1781
1812
  servedPath = MINE;
1782
1813
  const right = await ensure();
1783
1814
  check("GUID 对得上就认领(复用,不重开)", right.ok === true && right.adopted === true, JSON.stringify(right).slice(0, 240));
1784
- check("认领到的 pid 取自 Chrome 自己那把锁", right.ok === true && right.pid === holder.pid, JSON.stringify(right.pid));
1815
+ check(
1816
+ "认领到的 pid 取自 Chrome 自己的占用凭证(POSIX 是 SingletonLock,Windows 是进程表)",
1817
+ right.ok === true && right.pid === holder.pid,
1818
+ JSON.stringify(right.pid)
1819
+ );
1785
1820
  check("认领时把版本号一并问出来了", right.ok === true && String(right.version).startsWith("Chrome/"), right.version);
1786
1821
 
1787
1822
  fake.close();
1788
1823
  try {
1789
- process.kill(-holder.pid, "SIGKILL");
1824
+ if (H_WIN) process.kill(holder.pid, "SIGKILL");
1825
+ else process.kill(-holder.pid, "SIGKILL");
1790
1826
  } catch {}
1791
1827
  await waitFor(() => holderExited, 3000);
1792
1828
  }
@@ -2326,13 +2362,18 @@ console.log("\n\x1b[1mJ2. session-end(server 退出通知扩展)\x1b[0m");
2326
2362
  buf = buf.slice(i + 1);
2327
2363
  if (!l) continue;
2328
2364
  try {
2329
- lines.push(JSON.parse(l));
2365
+ const msg = JSON.parse(l);
2366
+ lines.push(msg);
2367
+ if (msg.type === "call") {
2368
+ c.write(JSON.stringify({ id: msg.id, type: "result", ok: true, data: { connected: true, tabs: [] } }) + "\n");
2369
+ }
2330
2370
  } catch {}
2331
2371
  }
2332
2372
  });
2333
2373
  await new Promise((r) => c.on("connect", r));
2334
2374
  c.write(JSON.stringify({ type: "hello", role: "host", token: TOKEN }) + "\n");
2335
2375
  await new Promise((r) => setTimeout(r, 300));
2376
+ await S.rpc("tools/call", { name: "browser_status", arguments: {} });
2336
2377
 
2337
2378
  S.p.stdin.end();
2338
2379
  const got = await waitFor(() => lines.some((m) => m.type === "session-end"), 5000).then(
@@ -2662,7 +2703,11 @@ if (process.platform === "win32") {
2662
2703
  }, 15000);
2663
2704
 
2664
2705
  const u = runInstaller(["--uninstall", "--agents=kimi"]);
2665
- check("Windows: 卸载不以一段堆栈收场(退出码 0)", u.status === 0, u.out.slice(-500));
2706
+ check(
2707
+ "Windows: 卸载不以一段堆栈收场(有残留也把每一步跑完,退出码如实非零)",
2708
+ [0, 1].includes(u.status) && !/^\s+at /m.test(u.out),
2709
+ `status=${u.status} ${u.out.slice(-500)}`
2710
+ );
2666
2711
  if (!locked) skipSection("这台机器上没能把文件锁住,「一步失败不阻断其余步骤」这条对照略过");
2667
2712
  else {
2668
2713
  check("Windows: 一步失败之后,后面的步骤照样跑完 — 注册表键被删掉", !regHas(KEY), u.out.slice(-800));
@@ -3287,8 +3332,16 @@ console.log("\n\x1b[1mM. 孤儿浏览器回收\x1b[0m");
3287
3332
  const sent = [];
3288
3333
  await sweepOrphansAsync({ procs, kill: (pid, sig) => sent.push(`${pid}:${sig}`), isAlive: () => false, sleep: async () => {} });
3289
3334
  check("账上是管道的:只打主进程,绝不打进程组(-pid 会误伤别人)", sent.includes("7001:SIGTERM") && !sent.includes("-7001:SIGTERM"), sent.join(" "));
3290
- check("账上是端口的:照旧整组打(detached,pid 就是组长)", sent.includes("-7002:SIGTERM"), sent.join(" "));
3291
- check("没账的保持老行为(整组打)", sent.includes("-7003:SIGTERM"), sent.join(" "));
3335
+ if (process.platform === "win32") {
3336
+ check(
3337
+ "Windows:端口/无账的也只打主进程(没有进程组可打)",
3338
+ sent.includes("7002:SIGTERM") && sent.includes("7003:SIGTERM") && !sent.some((s) => s.startsWith("-")),
3339
+ sent.join(" ")
3340
+ );
3341
+ } else {
3342
+ check("账上是端口的:照旧整组打(detached,pid 就是组长)", sent.includes("-7002:SIGTERM"), sent.join(" "));
3343
+ check("没账的保持老行为(整组打)", sent.includes("-7003:SIGTERM"), sent.join(" "));
3344
+ }
3292
3345
  }
3293
3346
 
3294
3347
  const alive = (pid) => pid === 1000;
@@ -3343,6 +3396,7 @@ console.log("\n\x1b[1mM. 孤儿浏览器回收\x1b[0m");
3343
3396
  check("命令行里解析得出 user-data-dir", profileDirFrom("chrome --user-data-dir=/tmp/p --remote-debugging-port=0 about:blank") === "/tmp/p");
3344
3397
  check("路径带空格也解析得完整(Application Support 之流)", profileDirFrom("chrome --user-data-dir=/Users/me/Library/Application Support/x --remote-debugging-port=0") === "/Users/me/Library/Application Support/x", JSON.stringify(profileDirFrom("chrome --user-data-dir=/Users/me/Library/Application Support/x --remote-debugging-port=0")));
3345
3398
  check("没有 user-data-dir 时返回 null(不猜)", profileDirFrom("chrome --headless") === null);
3399
+ check("尾随换行不拦路(/bin/ps -p 单点查询的原样输出)", profileDirFrom("chrome --user-data-dir=/tmp/p\n") === "/tmp/p");
3346
3400
 
3347
3401
  {
3348
3402
  let clock = 0;
@@ -3389,9 +3443,7 @@ console.log("\n\x1b[1mM. 孤儿浏览器回收\x1b[0m");
3389
3443
  })());
3390
3444
  }
3391
3445
 
3392
- if (process.platform === "win32") {
3393
- skipSection("真实起浏览器/收孤儿的链路属于 CLI 模式,Windows 上尚未支持(上面的纯函数判定已全部验过)");
3394
- } else {
3446
+ {
3395
3447
  const M_PROFILE = path.join(TMP, "m-profile");
3396
3448
  const holder = spawn(
3397
3449
  process.execPath,
@@ -3433,6 +3485,9 @@ console.log("\n\x1b[1mM. 孤儿浏览器回收\x1b[0m");
3433
3485
  check("没有杀不掉的", swept.stubborn.length === 0, JSON.stringify(swept.stubborn));
3434
3486
  }
3435
3487
 
3488
+ if (process.platform === "win32") {
3489
+ skipSection("Windows 的 kill 是 TerminateProcess 一刀,「不理 SIGTERM」的进程不存在,先礼后兵的升级阶梯无从测起");
3490
+ } else {
3436
3491
  {
3437
3492
  const { sweepOrphans, psSnapshot, pidAlive, readProfileRecord } = await import(
3438
3493
  pathToFileURL(path.join(ROOT, "mcp", "cdp", "browser-launch.mjs")).href
@@ -3480,6 +3535,7 @@ console.log("\n\x1b[1mM. 孤儿浏览器回收\x1b[0m");
3480
3535
 
3481
3536
  if (isUp(stubPid)) { try { process.kill(-stubPid, "SIGKILL"); } catch {} }
3482
3537
  }
3538
+ }
3483
3539
 
3484
3540
  {
3485
3541
  const MP_PROFILE = path.join(TMP, "m-pipe-profile");
@@ -3650,9 +3706,73 @@ console.log("\n\x1b[1mN. 会话身份跨进程重启存活\x1b[0m");
3650
3706
  fs.mkdirSync(pruneDir, { recursive: true });
3651
3707
  fs.writeFileSync(path.join(pruneDir, "session-1-old.json"), JSON.stringify({ pid: 424242, at: 0 }));
3652
3708
  fs.writeFileSync(path.join(pruneDir, "session-2-fresh.json"), JSON.stringify({ pid: 424243, at: Date.now() }));
3709
+ const corruptOld = path.join(pruneDir, "session-corrupt-old.json");
3710
+ const corruptFresh = path.join(pruneDir, "session-corrupt-fresh.json");
3711
+ fs.writeFileSync(corruptOld, "{ broken");
3712
+ fs.utimesSync(corruptOld, new Date(0), new Date(0));
3713
+ fs.writeFileSync(corruptFresh, "{ broken");
3653
3714
  const removed = pruneClaims({ dir: pruneDir, isAlive: () => false });
3654
- check("清掉主人已死且过期的认领文件", removed === 1, String(removed));
3655
- check("没过期的不动(避免误删刚重启的会话)", fs.existsSync(path.join(pruneDir, "session-2-fresh.json")));
3715
+ check("清掉主人已死且过期的认领文件及陈旧损坏 JSON", removed === 2 && !fs.existsSync(corruptOld), String(removed));
3716
+ check("没过期的(含新鲜半截 JSON)不动", fs.existsSync(path.join(pruneDir, "session-2-fresh.json")) && fs.existsSync(corruptFresh));
3717
+
3718
+ const { writeJsonAtomic } = await import(pathToFileURL(path.join(ROOT, "mcp", "session-id.mjs")).href);
3719
+ const atomicF = path.join(pruneDir, "atomic-test.json");
3720
+ writeJsonAtomic(atomicF, { ok: 1 });
3721
+ check("writeJsonAtomic 写入合法 JSON 且无残留 .tmp", JSON.parse(fs.readFileSync(atomicF, "utf8")).ok === 1 && !fs.readdirSync(pruneDir).some((n) => n.endsWith(".tmp")));
3722
+
3723
+ {
3724
+ const zeroDir = path.join(TMP, "zero-call-probe");
3725
+ fs.mkdirSync(zeroDir, { recursive: true });
3726
+ const zeroSock = path.join(zeroDir, "t.sock");
3727
+ const zeroTrace = path.join(zeroDir, "traces");
3728
+ const runProbe = (doCall) =>
3729
+ new Promise((resolve) => {
3730
+ const p = spawn(process.execPath, [path.join(ROOT, "mcp", "server.mjs")], {
3731
+ env: {
3732
+ ...process.env,
3733
+ AGENT_IN_CHROME_SOCK: zeroSock,
3734
+ AGENT_IN_CHROME_TRACE_DIR: zeroTrace,
3735
+ AGENT_IN_CHROME_SHOT_DIR: path.join(zeroDir, "shots"),
3736
+ AGENT_IN_CHROME_COOKIE_DIR: path.join(zeroDir, "cookies"),
3737
+ AGENT_IN_CHROME_SESSION_ID: undefined,
3738
+ },
3739
+ stdio: ["pipe", "pipe", "pipe"],
3740
+ });
3741
+ let buf = "";
3742
+ const replies = [];
3743
+ p.stdout.setEncoding("utf8");
3744
+ p.stdout.on("data", (d) => {
3745
+ buf += d;
3746
+ let i;
3747
+ while ((i = buf.indexOf("\n")) >= 0) {
3748
+ const l = buf.slice(0, i).trim();
3749
+ buf = buf.slice(i + 1);
3750
+ if (l) try { replies.push(JSON.parse(l)); } catch {}
3751
+ }
3752
+ });
3753
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05" } }) + "\n");
3754
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }) + "\n");
3755
+ if (doCall) {
3756
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "browser_status", arguments: {} } }) + "\n");
3757
+ }
3758
+ const t = setInterval(() => {
3759
+ if (replies.some((r) => r.id === (doCall ? 3 : 2))) {
3760
+ clearInterval(t);
3761
+ p.kill();
3762
+ setTimeout(() => resolve(replies), 150);
3763
+ }
3764
+ }, 25);
3765
+ setTimeout(() => { clearInterval(t); p.kill(); resolve(replies); }, 5000);
3766
+ });
3767
+ await runProbe(false);
3768
+ const afterProbe = fs.readdirSync(zeroDir).filter((n) => /^session-.*\.json$/.test(n));
3769
+ check("P1-5: initialize+tools/list 零调用探测不写任何 session-*.json", afterProbe.length === 0, JSON.stringify(afterProbe));
3770
+
3771
+ await runProbe(true);
3772
+ const afterCall = fs.readdirSync(zeroDir).filter((n) => /^session-.*\.json$/.test(n));
3773
+ const traceFiles = fs.existsSync(zeroTrace) ? fs.readdirSync(zeroTrace) : [];
3774
+ check("P1-5: 首次 tools/call 才写 session-*.json 且 trace 用真实 sessionId 命名", afterCall.length === 1 && traceFiles.some((f) => !f.includes("default") && f.endsWith(".jsonl")), JSON.stringify({ afterCall, traceFiles }));
3775
+ }
3656
3776
 
3657
3777
  {
3658
3778
  const { pruneDeadSocks } = await import("../mcp/token.mjs");
@@ -3685,6 +3805,9 @@ console.log("\n\x1b[1mN. 会话身份跨进程重启存活\x1b[0m");
3685
3805
  check("自己这条 SOCK 不碰", fs.existsSync(mine));
3686
3806
  check("不带 profile hash 的那条不归它管", fs.existsSync(other));
3687
3807
 
3808
+ if (process.platform === "win32") {
3809
+ skipSection("probeSock 的真 socket 探活是 POSIX 机制(Windows 桥接走命名管道,不落盘无残留)");
3810
+ } else {
3688
3811
  const liveDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-sk-"));
3689
3812
  fs.chmodSync(liveDir, 0o700);
3690
3813
  const livePath = path.join(liveDir, "agent-in-chrome-cli-eeeeeeee.sock");
@@ -3700,6 +3823,7 @@ console.log("\n\x1b[1mN. 会话身份跨进程重启存活\x1b[0m");
3700
3823
  check("真探活:还在 listen 的一个字不碰", fs.existsSync(livePath));
3701
3824
  await new Promise((r) => srv.close(r));
3702
3825
  fs.rmSync(liveDir, { recursive: true, force: true });
3826
+ }
3703
3827
  }
3704
3828
 
3705
3829
  const psTok = (out) => parentStartToken(123, () => out, { platform: "darwin" });
@@ -3725,12 +3849,8 @@ console.log("\n\x1b[1mN. 会话身份跨进程重启存活\x1b[0m");
3725
3849
  }
3726
3850
  }
3727
3851
 
3728
- if (process.platform === "win32") {
3729
- skipSection("parentStartToken 走 ps lstart,Windows 上按回落档(pid 基 sid)工作——ps 等价物是后续工作");
3730
- } else {
3731
- const real = parentStartToken(process.ppid);
3732
- check("真机上确实读得到父进程启动时刻", typeof real === "string" && real.length > 0, String(real));
3733
- }
3852
+ const real = parentStartToken(process.ppid);
3853
+ check("真机上确实读得到父进程启动时刻", typeof real === "string" && real.length > 0, String(real));
3734
3854
 
3735
3855
  const { makeInheritor, fingerprintOf } = await import(pathToFileURL(path.join(ROOT, "mcp", "session-id.mjs")).href);
3736
3856
  const ME = { workspace: "agent-in-chrome", brandFallback: null, surface: "cli" };
@@ -3819,7 +3939,11 @@ console.log("\n\x1b[1mN. 会话身份跨进程重启存活\x1b[0m");
3819
3939
  }
3820
3940
  {
3821
3941
  const dir = path.join(TMP, "inherit-payload");
3822
- deriveSessionId({ env: {}, ppid: 4242, pid: 7777, startToken: () => "tok", identity: ME, claim: makeClaimer({ dir, isAlive: () => false }) });
3942
+ deriveSessionId({
3943
+ env: {}, ppid: 4242, pid: 7777, startToken: () => "tok", identity: ME,
3944
+ inherit: makeInheritor({ dir, isAlive: () => false }),
3945
+ claim: makeClaimer({ dir, isAlive: () => false }),
3946
+ });
3823
3947
  const wrote = JSON.parse(fs.readFileSync(path.join(dir, "session-4242-tok.json"), "utf8"));
3824
3948
  check("认领时把身份指纹写进文件", JSON.stringify(wrote.id) === JSON.stringify(fp), JSON.stringify(wrote));
3825
3949
  }
@@ -1351,6 +1351,65 @@ document.getElementById('log').textContent = 'enforced=' + window.__ttEnforced +
1351
1351
  if (url.pathname === "/upload/last") {
1352
1352
  return json(lastUpload || { count: 0, files: [], empty: true });
1353
1353
  }
1354
+ if (url.pathname === "/oauth-login") {
1355
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1356
+ return res.end(
1357
+ `<!doctype html><meta charset="utf-8"><title>OAuth 登录</title>` +
1358
+ `<body><div id="oauth-state">登录授权中</div>` +
1359
+ `<script>window.fireSlow502 = () => fetch('/api/slow-502').catch(()=>{});</script></body>`
1360
+ );
1361
+ }
1362
+ if (url.pathname === "/api/cors-ok") {
1363
+ res.setHeader("access-control-allow-origin", "*");
1364
+ return json({ ok: true, leaked: "cross-origin-secret-marker" });
1365
+ }
1366
+ if (url.pathname === "/api/slow-502") {
1367
+ await new Promise((r) => setTimeout(r, 40));
1368
+ return json({ error: "bad gateway", marker: "slow-502-marker" }, 502);
1369
+ }
1370
+ if (url.pathname === "/api/big-data") {
1371
+ const sid = (String(req.headers.cookie || "").match(/\bzc_sid=([^;]+)/) || [])[1];
1372
+ const s = sid && AUTH_SESSIONS.get(sid);
1373
+ if (!s) return json({ ok: false, reason: "未登录", marker: "big-data-401" }, 401);
1374
+ const items = Array.from({ length: 4000 }, (_, i) => ({
1375
+ id: i,
1376
+ page: url.searchParams.get("page") || "1",
1377
+ pad: "A".repeat(50),
1378
+ }));
1379
+ return json({ ok: true, user: s.user, page: url.searchParams.get("page") || "1", items, marker: "big-data-320k" });
1380
+ }
1381
+ if (url.pathname === "/redir-external") {
1382
+ res.writeHead(302, { location: `${ALT_BASE}/api/cors-ok` });
1383
+ return res.end();
1384
+ }
1385
+ if (url.pathname === "/radix-and-loader") {
1386
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
1387
+ return res.end(
1388
+ `<!doctype html><meta charset="utf-8"><title>Radix & Loader</title>` +
1389
+ `<body>` +
1390
+ `<button id="radix-btn" aria-expanded="false" style="margin:16px">展开菜单</button>` +
1391
+ `<div id="radix-menu" style="display:none">菜单已展开</div>` +
1392
+ `<button id="masked-btn" style="margin:16px">保存设置</button>` +
1393
+ `<span id="masked-count">0</span>` +
1394
+ `<div id="transient-mask" class="el-loading-mask" style="display:none;position:fixed;inset:0;background:rgba(255,255,255,0.6);z-index:9999">加载中</div>` +
1395
+ `<script>
1396
+ document.getElementById('radix-btn').addEventListener('pointerdown', function() {
1397
+ this.setAttribute('aria-expanded', 'true');
1398
+ document.getElementById('radix-menu').style.display = 'block';
1399
+ this.style.marginLeft = '220px';
1400
+ });
1401
+ document.getElementById('masked-btn').addEventListener('click', function() {
1402
+ const c = document.getElementById('masked-count');
1403
+ c.textContent = String(Number(c.textContent) + 1);
1404
+ });
1405
+ window.showMask = function(ms) {
1406
+ const m = document.getElementById('transient-mask');
1407
+ m.style.display = 'block';
1408
+ setTimeout(() => { m.style.display = 'none'; }, ms || 220);
1409
+ };
1410
+ <\/script></body>`
1411
+ );
1412
+ }
1354
1413
  res.writeHead(404, { "content-type": "text/plain" });
1355
1414
  res.end("not found");
1356
1415
  };