@aiti-ai/ext-shared 0.0.0-stage → 0.1.8

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 (131) hide show
  1. package/LICENSE +21 -0
  2. package/agent-accounts.test.mjs +227 -0
  3. package/agent-accounts.ts +324 -0
  4. package/agent-capability-contract.test.mjs +129 -0
  5. package/agent-interaction.test.mjs +194 -0
  6. package/agent-interaction.ts +340 -0
  7. package/agent-launch.test.mjs +262 -0
  8. package/agent-spawn-env.test.mjs +169 -0
  9. package/agent-spawn-env.ts +548 -0
  10. package/aiti-editor-inject.mjs +49 -0
  11. package/backend-queue.test.mjs +336 -0
  12. package/backend-queue.ts +469 -0
  13. package/blob-save-route.ts +128 -0
  14. package/cbc-model-catalog.ts +86 -0
  15. package/check-client.mjs +273 -0
  16. package/check-ext-globals.mjs +144 -0
  17. package/controlled-login-dialog.mjs +270 -0
  18. package/controlled-login.mjs +398 -0
  19. package/controlled-login.test.mjs +466 -0
  20. package/convert-saveas.test.mjs +39 -0
  21. package/convert-saveas.ts +170 -0
  22. package/copy-client-bundle.mjs +39 -0
  23. package/cursor-cli-store.ts +377 -0
  24. package/dedupe-fetch.test.mjs +71 -0
  25. package/dedupe-fetch.ts +58 -0
  26. package/deploy-commit.mjs +52 -0
  27. package/dev-pack.mjs +246 -0
  28. package/dock-icons.ts +127 -0
  29. package/esbuild-bin.test.mjs +53 -0
  30. package/esbuild-bin.ts +66 -0
  31. package/exec-async.test.mjs +86 -0
  32. package/exec-async.ts +179 -0
  33. package/ext-display-names.ts +91 -0
  34. package/ext-entry-contracts.test.mjs +131 -0
  35. package/ext-float-dock-core.test.mjs +348 -0
  36. package/ext-float-dock-core.ts +783 -0
  37. package/ext-float-dock-lite.ts +52 -0
  38. package/ext-float-dock.test.mjs +286 -0
  39. package/ext-float-dock.ts +740 -0
  40. package/ext-icons-deploy.mjs +24 -0
  41. package/ext-lazy.test.mjs +186 -0
  42. package/ext-lazy.tsx +183 -0
  43. package/ext-model-state.test.mjs +272 -0
  44. package/ext-model-state.ts +324 -0
  45. package/ext-protocol.mjs +113 -0
  46. package/ext-protocol.test.mjs +88 -0
  47. package/ext-session-usage.test.mjs +219 -0
  48. package/ext-session-usage.ts +507 -0
  49. package/external-cli-governance.ts +153 -0
  50. package/git-ops-client/api.mjs +56 -0
  51. package/git-ops-client/branch-panel.tsx +987 -0
  52. package/git-ops-client/i18n.mjs +328 -0
  53. package/host-tools-allow.test.mjs +46 -0
  54. package/host-tools-allow.ts +84 -0
  55. package/icons/alert.svg +1 -0
  56. package/icons/bookmark.svg +1 -0
  57. package/icons/bot.svg +1 -0
  58. package/icons/chart-column.svg +1 -0
  59. package/icons/check-circle.svg +1 -0
  60. package/icons/clipboard-list.svg +1 -0
  61. package/icons/clock.svg +1 -0
  62. package/icons/coffee.svg +1 -0
  63. package/icons/edit.svg +1 -0
  64. package/icons/eye.svg +1 -0
  65. package/icons/git-branch.svg +1 -0
  66. package/icons/git-commit-horizontal.svg +1 -0
  67. package/icons/globe.svg +1 -0
  68. package/icons/history.svg +1 -0
  69. package/icons/import.svg +1 -0
  70. package/icons/inbox.svg +1 -0
  71. package/icons/key-round.svg +1 -0
  72. package/icons/layout-grid.svg +1 -0
  73. package/icons/mail.svg +1 -0
  74. package/icons/message-circle.svg +1 -0
  75. package/icons/message-square.svg +1 -0
  76. package/icons/meter-vertical.svg +1 -0
  77. package/icons/mic.svg +1 -0
  78. package/icons/monitor.svg +1 -0
  79. package/icons/pen-line.svg +1 -0
  80. package/icons/plug.svg +1 -0
  81. package/icons/radio-dot.svg +1 -0
  82. package/icons/radio.svg +1 -0
  83. package/icons/refresh.svg +1 -0
  84. package/icons/rocket.svg +1 -0
  85. package/icons/search.svg +1 -0
  86. package/icons/shield.svg +1 -0
  87. package/icons/sparkles.svg +1 -0
  88. package/icons/square-kanban.svg +1 -0
  89. package/icons/terminal.svg +1 -0
  90. package/icons/users.svg +1 -0
  91. package/icons/volume-2.svg +1 -0
  92. package/icons/wand.svg +1 -0
  93. package/icons/wrench.svg +1 -0
  94. package/icons/x-circle.svg +1 -0
  95. package/icons/x.svg +1 -0
  96. package/ignore-semantics.ts +76 -0
  97. package/lazy-loading-metrics.mjs +61 -0
  98. package/new-session-cwd.test.mjs +389 -0
  99. package/new-session-cwd.ts +253 -0
  100. package/open-viewer-window.ts +65 -0
  101. package/overlay-back-client.test.mjs +123 -0
  102. package/overlay-back-client.ts +87 -0
  103. package/package.json +65 -4
  104. package/pi-fork-rpc/README.md +12 -0
  105. package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
  106. package/pi-fork-rpc/cli-resolve.ts +79 -0
  107. package/pi-fork-rpc/remote-queue.test.mjs +100 -0
  108. package/pi-fork-rpc/remote-queue.ts +140 -0
  109. package/pi-fork-rpc/spec.ts +106 -0
  110. package/pi-fork-rpc/wire.test.mjs +260 -0
  111. package/pi-fork-rpc/wire.ts +367 -0
  112. package/popup-anchor.ts +45 -0
  113. package/provider-priority-contract.test.mjs +55 -0
  114. package/reconcile-deps.mjs +41 -0
  115. package/reload-instances.mjs +60 -0
  116. package/seed-tool.test.mjs +95 -0
  117. package/seed-tool.ts +88 -0
  118. package/session-recycle.ts +109 -0
  119. package/shared-copy-sync.test.mjs +115 -0
  120. package/soffice-locate.ts +171 -0
  121. package/soffice-panel.ts +239 -0
  122. package/sync-dir.mjs +91 -0
  123. package/sync-dir.test.mjs +101 -0
  124. package/sync-gate.test.mjs +93 -0
  125. package/sync-mirror.test.mjs +85 -0
  126. package/task-list.test.mjs +91 -0
  127. package/task-list.ts +118 -0
  128. package/test-rm-rf.mjs +33 -0
  129. package/ui-dialogs.test.mjs +198 -0
  130. package/ui-dialogs.ts +310 -0
  131. package/README.md +0 -3
@@ -0,0 +1,76 @@
1
+ /**
2
+ * ignore 语义共享模块(.gitignore / .aitiignore / .dockerignore 实用子集)
3
+ *
4
+ * ⭐ 权威源:本文件。副本同步至消费扩展(改这里务必三处同步):
5
+ * - aiti-doc-center/lib/ignore-semantics.ts(walkFiles 收集器)
6
+ * - aiti-plan-first/lib/ignore-semantics.ts(选择器 fs walk 兜底 + session-md .aitiignore 过滤)
7
+ * - aiti-git-trace 不用本模块(.gitignore/.aitiignore 经 git 排除机制:ls-files
8
+ * --exclude-standard / --exclude-per-directory,见其 §16.3 listMd v2)
9
+ *
10
+ * 语义(gitignore 实用子集,Linux 大小写敏感):
11
+ * - `#` 注释、空行跳过;`!` 负规则(后命中覆盖先行)
12
+ * - 尾 `/` 仅目录(目录与其内容经 (?:/.*)? 一并命中)
13
+ * - 含 `/`(含首 `/`)= 锚定到 ignore 文件所在目录;无斜杠 = 任意深度 basename
14
+ * - 「两个星号 + 斜杠」前缀 = 任意深度;中段同款 = 零或多目录;尾段 = 目录下任意;星/问号 = 单层通配
15
+ * - 分段构建保证段边界(skills 通配不误吞 skillsfoo;a 加双星加 b 不误吞 a 加 xb)
16
+ *
17
+ * API:
18
+ * compileIgnoreGlob(glob) 单条 glob → RegExp
19
+ * compileIgnoreLines(text) 多行 ignore 文本 → IgnoreRule[]
20
+ * matchRules(rules, rel) 后命中覆盖先行;null = 无规则命中(调用方决定默认值)
21
+ */
22
+
23
+ export interface IgnoreRule { neg: boolean; dirOnly: boolean; re: RegExp }
24
+
25
+ function escSeg(seg: string): string {
26
+ let r = "";
27
+ for (const ch of seg) {
28
+ if (ch === "*") r += "[^/]*";
29
+ else if (ch === "?") r += "[^/]";
30
+ else r += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
31
+ }
32
+ return r;
33
+ }
34
+
35
+ /** 单条 gitignore 式 glob → 正则(分段构建保证段边界) */
36
+ export function compileIgnoreGlob(glob: string): RegExp {
37
+ let body = glob;
38
+ let pre = "";
39
+ let tail = "(?:/.*)?";
40
+ if (body === "**") return /^.*$/;
41
+ const anchored = body.includes("/");
42
+ if (body.endsWith("/**")) { body = body.slice(0, -3); tail = "/.*"; }
43
+ else if (body.endsWith("/")) { body = body.slice(0, -1); tail = "/.*"; }
44
+ if (!anchored) pre += "(?:.*/)?"; // 无斜杠 → 任意深度
45
+ if (body.startsWith("**/")) { pre += "(?:.*/)?"; body = body.slice(3); }
46
+ else if (body.startsWith("**")) { pre += ".*"; body = body.slice(2); }
47
+ if (!body) return new RegExp("^" + pre + (tail === "/.*" ? "/.*" : "") + "$");
48
+ if (body.startsWith("/")) body = body.slice(1); // 锚定:去根斜杠(/sub/x.md → sub/x.md)
49
+ const segs = body.split("/**/");
50
+ return new RegExp("^" + pre + segs.map(escSeg).join("(?:.*/)?") + tail + "$");
51
+ }
52
+
53
+
54
+ export function compileIgnoreLines(text: string): IgnoreRule[] {
55
+ const out: IgnoreRule[] = [];
56
+ for (let raw of String(text || "").split(/\r?\n/)) {
57
+ raw = raw.replace(/\s+$/, "");
58
+ if (!raw || raw.startsWith("#")) continue;
59
+ let neg = false;
60
+ if (raw.startsWith("!")) { neg = true; raw = raw.slice(1); }
61
+ let dirOnly = raw.endsWith("/");
62
+ if (dirOnly) raw = raw.slice(0, -1);
63
+ if (!raw) continue;
64
+ out.push({ neg, dirOnly, re: compileIgnoreGlob(raw) });
65
+ }
66
+ return out;
67
+ }
68
+
69
+ /** 规则匹配:后命中覆盖先行(含 ! 否定);无命中返回 null(调用方决定默认值) */
70
+ export function matchRules(rules: IgnoreRule[], rel: string): boolean | null {
71
+ let decision: boolean | null = null;
72
+ for (const r of rules) {
73
+ if (r.re.test(rel)) decision = !r.neg;
74
+ }
75
+ return decision;
76
+ }
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * lazy-loading-metrics — 懒加载 v2 度量脚本(docs/aiti-ext-lazy-loading-plan.md §8)。
4
+ *
5
+ * 对指定 pi-web 实例统计「首屏扩展 client 传输量」:无头拉取页面 + PerformanceObserver
6
+ * 采样扩展 bundle 请求数与传输字节。用法:
7
+ *
8
+ * node tools/lazy-loading-metrics.mjs [baseUrl] [timeoutMs]
9
+ *
10
+ * 默认 baseUrl = http://127.0.0.1:3001/dev(dev 实例)。生产传 https://pi.example.com。
11
+ * 依赖:无(Node 内置 fetch;页面侧注入采集脚本经 CDP 不可用时降级为 bundle 字节求和)。
12
+ */
13
+ const base = (process.argv[2] || "http://127.0.0.1:3001/dev").replace(/\/$/, "");
14
+ const manifestUrl = `${base}/api/extensions/manifest`;
15
+
16
+ const d = await fetch(manifestUrl).then((r) => r.json()).catch(() => null);
17
+ if (!d) { console.error(`[metrics] manifest 拉取失败: ${manifestUrl}`); process.exit(1); }
18
+
19
+ const lazy = d.extensions.filter((x) => x.ui && x.ui.clientImmediately === false).map((x) => x.id);
20
+ const immediate = d.extensions.filter((x) => !x.ui || x.ui.clientImmediately !== false).map((x) => x.id);
21
+
22
+ /** 单个 bundle 的传输字节(对实例再发一次请求,带 Accept-Encoding 模拟首屏传输) */
23
+ async function bytesOf(url) {
24
+ try {
25
+ const r = await fetch(url, { headers: { "accept-encoding": "gzip" } });
26
+ if (!r.ok) return -1;
27
+ const buf = await r.arrayBuffer();
28
+ return Math.round(buf.byteLength / 1024);
29
+ } catch { return -1; }
30
+ }
31
+
32
+ /** 首屏 = 即时扩展的 client bundle(懒扩展不计入;其重 chunk 按交互另计) */
33
+ let immediateKB = 0, missing = [];
34
+ for (const id of immediate) {
35
+ const e = d.extensions.find((x) => x.id === id);
36
+ if (!e?.clientUrl) continue;
37
+ const kb = await bytesOf(`${base}${e.clientUrl}`);
38
+ if (kb < 0) { missing.push(id); continue; }
39
+ immediateKB += kb;
40
+ }
41
+
42
+ /** 懒扩展 bundle 体量(对照:若它们仍即时,首屏会多多少) */
43
+ let deferredKB = 0;
44
+ for (const id of lazy) {
45
+ const e = d.extensions.find((x) => x.id === id);
46
+ if (!e?.clientUrl) continue;
47
+ const kb = await bytesOf(`${base}${e.clientUrl}`);
48
+ if (kb > 0) deferredKB += kb;
49
+ }
50
+
51
+ console.log("═".repeat(64));
52
+ console.log(`实例: ${base}`);
53
+ console.log(`扩展总数: ${d.extensions.length} 懒: ${lazy.length} 即时: ${immediate.length}`);
54
+ console.log(`failed: ${(d.failed || []).length ? JSON.stringify(d.failed) : "无"}`);
55
+ console.log("─".repeat(64));
56
+ console.log(`首屏(即时扩展 bundle 字节和): ${immediateKB} KB`);
57
+ console.log(`懒扩展 bundle 体量(按需,不计首屏): ${deferredKB} KB`);
58
+ console.log(`懒化收益 ≈ ${(100 * deferredKB / (immediateKB + deferredKB)).toFixed(1)}% 移出首屏`);
59
+ if (missing.length) console.log(`⚠ 拉取失败(忽略计值): ${missing.join(", ")}`);
60
+ console.log("─".repeat(64));
61
+ console.log("验收基线(§2 目标): 首屏 ≤1.2MB;交互前懒扩展 0 请求(页面侧 Network 面板核对)");
@@ -0,0 +1,389 @@
1
+ /**
2
+ * new-session-cwd 共享判定单测(node --test;纯函数,--experimental-strip-types 直跑)。
3
+ *
4
+ * 方案:docs/pi-web-at-new-session-cwd-plan.md(v1)+ docs/pi-web-at-new-session-cwd-v2-plan.md(v2)
5
+ * 覆盖(v2 语义):pathCovers / stripCommonDirs / longestCovering / resolveNewSessionCwd 四档判定
6
+ * (保持 / 关注目录切走(repoRoot 优先、嵌套取最深) / 已知 workspace 最长匹配 / 常规目录剥离 /
7
+ * 无 cwd 归一化)/ resolveNewSessionCwdClient 快路径短路 + sessions 派生 + git-trace 端点复核 +
8
+ * 失败降级 / buildAtText / openNewSession / openNewSessionWithExtSvc 服务优先与降级。
9
+ * 注意:fetchKnownWorkspaces 有模块级 TTL 缓存(60s),依赖它的用例开头必须 _resetWsCacheForTest()。
10
+ */
11
+ import { test } from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import {
14
+ pathCovers, normDir, stripCommonDirs, longestCovering, DEFAULT_EXCLUDE_DIR_NAMES,
15
+ resolveNewSessionCwd, resolveNewSessionCwdClient, buildAtText, openNewSession, openNewSessionWithExtSvc,
16
+ _resetWsCacheForTest,
17
+ } from "./new-session-cwd.ts";
18
+
19
+ test("pathCovers:相等 / 互为前缀 / 无关", () => {
20
+ assert.ok(pathCovers("/a/b", "/a/b"));
21
+ assert.ok(pathCovers("/a/b/c", "/a/b")); // 子目录被父覆盖
22
+ assert.ok(pathCovers("/a/b", "/a/b/c")); // 父被子覆盖(doc-center 双向 wsCovers 同款)
23
+ assert.ok(!pathCovers("/a/bc", "/a/b")); // 非前缀边界(b 是 bc 前缀但不是目录边界)
24
+ assert.ok(!pathCovers("/a", "/b"));
25
+ assert.ok(!pathCovers("", "/b"));
26
+ assert.ok(!pathCovers("/a", ""));
27
+ });
28
+
29
+ test("pathCovers:路径归一(尾斜杠 / win 反斜杠)", () => {
30
+ assert.ok(pathCovers("/a/b/", "/a/b"));
31
+ assert.ok(pathCovers("D:\\workspace\\proj", "D:/workspace/proj/src"));
32
+ assert.ok(pathCovers("D:/workspace/proj/src", "D:\\workspace\\proj"));
33
+ });
34
+
35
+ test("DEFAULT_EXCLUDE_DIR_NAMES:v2 用户拍板清单", () => {
36
+ assert.deepEqual(DEFAULT_EXCLUDE_DIR_NAMES, ["docs", "doc", "tmp", "temp", "design", "designs"]);
37
+ });
38
+
39
+ test("stripCommonDirs:单层常规目录剥离 / 多重 / 大小写 / 非常规不动 / win 反斜杠", () => {
40
+ assert.equal(stripCommonDirs("/home/w/proj/docs"), "/home/w/proj");
41
+ assert.equal(stripCommonDirs("/home/w/proj/docs/design"), "/home/w/proj"); // 连续剥两层
42
+ assert.equal(stripCommonDirs("/home/w/proj/Design"), "/home/w/proj"); // 大小写不敏感
43
+ assert.equal(stripCommonDirs("/home/w/proj/src"), "/home/w/proj/src"); // 非常规名不动
44
+ assert.equal(stripCommonDirs("D:\\workspace\\proj\\tmp"), "D:/workspace/proj");
45
+ assert.equal(stripCommonDirs("/home/w/proj"), "/home/w/proj");
46
+ });
47
+
48
+ test("longestCovering:最长(最深)覆盖 / 不选目标的子目录 / 空候选", () => {
49
+ const cands = ["/home/w", "/home/w/proj", "/home/w/other"];
50
+ assert.equal(longestCovering("/home/w/proj/src/x.ts", cands), "/home/w/proj");
51
+ assert.equal(longestCovering("/home/w/proj", cands), "/home/w/proj"); // 相等命中
52
+ assert.equal(longestCovering("/home/w/other/a", cands), "/home/w/other");
53
+ // 候选是目标的子目录(如 workspace 候选是 proj 内部的 src)→ 不得选(coversDir 单向)
54
+ assert.equal(longestCovering("/home/w/proj", ["/home/w/proj/src"]), null);
55
+ assert.equal(longestCovering("/x/y/z.ts", []), null);
56
+ assert.equal(longestCovering("/x/y/z.ts", ["", null, undefined]), null);
57
+ });
58
+
59
+ test("resolveNewSessionCwd:目标在当前 CWD 内 → 保持", () => {
60
+ const r = resolveNewSessionCwd({ targetDir: "/home/w/pi-web/lib", targetPath: "/home/w/pi-web/lib/a.ts", currentCwd: "/home/w/pi-web" });
61
+ assert.equal(r.cwd, "/home/w/pi-web");
62
+ assert.equal(r.switched, false);
63
+ });
64
+
65
+ test("resolveNewSessionCwd:当前 CWD 在目标内(目标=父层)→ 保持", () => {
66
+ const r = resolveNewSessionCwd({ targetDir: "/home/w", currentCwd: "/home/w/pi-web" });
67
+ assert.equal(r.cwd, "/home/w/pi-web");
68
+ assert.equal(r.switched, false);
69
+ });
70
+
71
+ test("resolveNewSessionCwd v2:目标在关注路径内 → 切到关注路径(不再保持)", () => {
72
+ // 当前 cwd 在 A 仓,目标在 B 仓——B 是 A 的 watchPaths(git-trace 配置的跨仓关注)→ 切到 B
73
+ const r = resolveNewSessionCwd({
74
+ targetDir: "/home/w/other-proj/src", targetPath: "/home/w/other-proj/src/x.ts",
75
+ currentCwd: "/home/w/pi-web",
76
+ watchPaths: ["/home/w/other-proj"],
77
+ });
78
+ assert.equal(r.cwd, "/home/w/other-proj");
79
+ assert.equal(r.switched, true);
80
+ });
81
+
82
+ test("resolveNewSessionCwd v2:关注路径 {path,repoRoot} 对象 → repoRoot 优先", () => {
83
+ // 用户关注的 path 是仓库子目录 → 命中时用 repoRoot(仓库根更符合 workspace 概念)
84
+ const r = resolveNewSessionCwd({
85
+ targetDir: "/home/w/other-proj/packages/core",
86
+ targetPath: "/home/w/other-proj/packages/core/README.md",
87
+ currentCwd: "/home/w/pi-web",
88
+ watchPaths: [{ path: "/home/w/other-proj/packages/core", repoRoot: "/home/w/other-proj" }],
89
+ });
90
+ assert.equal(r.cwd, "/home/w/other-proj");
91
+ assert.equal(r.switched, true);
92
+ });
93
+
94
+ test("resolveNewSessionCwd v2:关注路径嵌套取最深", () => {
95
+ const r = resolveNewSessionCwd({
96
+ targetDir: "/home/w/mono/apps/foo",
97
+ targetPath: "/home/w/mono/apps/foo/x.ts",
98
+ currentCwd: "/home/w/pi-web",
99
+ watchPaths: ["/home/w/mono", { path: "/home/w/mono/apps/foo", repoRoot: "/home/w/mono/apps/foo" }],
100
+ });
101
+ assert.equal(r.cwd, "/home/w/mono/apps/foo"); // 更深命中优先
102
+ });
103
+
104
+ test("resolveNewSessionCwd v2:关注路径配置在目标子层(目标目录是其父)→ 切到关注路径", () => {
105
+ const r = resolveNewSessionCwd({
106
+ targetDir: "/home/w/other-proj",
107
+ targetPath: "/home/w/other-proj",
108
+ currentCwd: "/home/w/pi-web",
109
+ watchPaths: [{ path: "/home/w/other-proj/src", repoRoot: "/home/w/other-proj" }],
110
+ });
111
+ assert.equal(r.cwd, "/home/w/other-proj");
112
+ assert.equal(r.switched, true);
113
+ });
114
+
115
+ test("resolveNewSessionCwd v2:已知 workspace 覆盖 → 最长匹配", () => {
116
+ const r = resolveNewSessionCwd({
117
+ targetDir: "/home/w/pi-web/lib", targetPath: "/home/w/pi-web/lib/x.ts",
118
+ currentCwd: "/home/w/pi-work",
119
+ knownWorkspaces: ["/home/w", "/home/w/pi-web", "/home/w/other"],
120
+ });
121
+ assert.equal(r.cwd, "/home/w/pi-web");
122
+ assert.equal(r.switched, true);
123
+ });
124
+
125
+ test("resolveNewSessionCwd v2:常规目录剥离(无 workspace 命中)", () => {
126
+ const r = resolveNewSessionCwd({
127
+ targetDir: "/home/w/proj/docs", targetPath: "/home/w/proj/docs/guide.md",
128
+ currentCwd: "/home/w/other",
129
+ knownWorkspaces: ["/home/w/other", "/home/w/unrelated"],
130
+ });
131
+ assert.equal(r.cwd, "/home/w/proj"); // docs 剥掉,proj 不在已知 workspace → 用剥离结果
132
+ assert.equal(r.switched, true);
133
+ });
134
+
135
+ test("resolveNewSessionCwd v2:剥离后命中 workspace → 用 workspace", () => {
136
+ const r = resolveNewSessionCwd({
137
+ targetDir: "/home/w/pi-web/docs", targetPath: "/home/w/pi-web/docs/guide.md",
138
+ currentCwd: "/home/w/pi-work",
139
+ knownWorkspaces: ["/home/w/pi-work", "/home/w/pi-web"],
140
+ });
141
+ assert.equal(r.cwd, "/home/w/pi-web"); // 剥 docs 后 /home/w/pi-web 命中已知 workspace
142
+ });
143
+
144
+ test("resolveNewSessionCwd v2:无 CWD → 已知 workspace 命中(不落深目录,修 v1 bug)", () => {
145
+ const r = resolveNewSessionCwd({
146
+ targetDir: "/home/w/pi-web/docs", targetPath: "/home/w/pi-web/docs/guide.md",
147
+ currentCwd: "",
148
+ knownWorkspaces: ["/home/w/pi-web"],
149
+ });
150
+ assert.equal(r.cwd, "/home/w/pi-web");
151
+ assert.equal(r.switched, false); // 无当前 cwd → 恒 false
152
+ });
153
+
154
+ test("resolveNewSessionCwd v2:无 CWD → 关注目录命中", () => {
155
+ const r = resolveNewSessionCwd({
156
+ targetDir: "/home/w/other-proj/src", targetPath: "/home/w/other-proj/src/x.ts",
157
+ currentCwd: "",
158
+ watchPaths: [{ path: "/home/w/other-proj", repoRoot: "/home/w/other-proj" }],
159
+ });
160
+ assert.equal(r.cwd, "/home/w/other-proj");
161
+ assert.equal(r.switched, false);
162
+ });
163
+
164
+ test("resolveNewSessionCwd v2:无 CWD 且无候选 → 剥离常规目录后的目录", () => {
165
+ const r = resolveNewSessionCwd({
166
+ targetDir: "/home/w/proj/tmp", targetPath: "/home/w/proj/tmp/x.log",
167
+ currentCwd: null,
168
+ });
169
+ assert.equal(r.cwd, "/home/w/proj");
170
+ assert.equal(r.switched, false);
171
+ });
172
+
173
+ test("resolveNewSessionCwd:目标属于其它工作区且无关注/已知 → 切走(剥离后)", () => {
174
+ const r = resolveNewSessionCwd({ targetDir: "/home/w/other-proj", currentCwd: "/home/w/pi-web" });
175
+ assert.equal(r.cwd, "/home/w/other-proj");
176
+ assert.equal(r.switched, true);
177
+ });
178
+
179
+ test("resolveNewSessionCwd:空 targetDir/targetPath → 返回当前 cwd", () => {
180
+ const r = resolveNewSessionCwd({ targetDir: "", currentCwd: "/a" });
181
+ assert.equal(r.cwd, "/a");
182
+ assert.equal(r.switched, false);
183
+ const r2 = resolveNewSessionCwd({ targetDir: "", targetPath: "", currentCwd: null });
184
+ assert.equal(r2.cwd, "");
185
+ });
186
+
187
+ test("resolveNewSessionCwd v2:文件在 CWD 内但 targetPath 更深(docs 子目录)→ 保持(不剥)", () => {
188
+ // 当前 CWD = 项目根,文件在项目 docs 子目录 → ① 命中保持(v2 原则:已在 CWD 内不随便切)
189
+ const r = resolveNewSessionCwd({
190
+ targetDir: "/home/w/pi-web/docs", targetPath: "/home/w/pi-web/docs/guide.md",
191
+ currentCwd: "/home/w/pi-web",
192
+ knownWorkspaces: ["/home/w/pi-web"],
193
+ });
194
+ assert.equal(r.cwd, "/home/w/pi-web");
195
+ assert.equal(r.switched, false);
196
+ });
197
+
198
+ // ── client 流程(resolveNewSessionCwdClient)──────────────
199
+ test("resolveNewSessionCwdClient:目标在当前 CWD 内 → 快路径短路,不发请求", async () => {
200
+ let called = 0;
201
+ const cwd = await resolveNewSessionCwdClient({
202
+ targetDir: "/home/w/pi-web/lib", targetPath: "/home/w/pi-web/lib/a.ts",
203
+ currentCwd: "/home/w/pi-web",
204
+ apiUrl: () => { called++; return "http://x/ext"; },
205
+ fetchFn: (async () => { throw new Error("不应发起请求"); })
206
+ });
207
+ assert.equal(cwd, "/home/w/pi-web");
208
+ assert.equal(called, 0);
209
+ });
210
+
211
+ test("resolveNewSessionCwdClient:切走时拉 sessions 派生 + 端点复核(关注命中 → 切关注目录)", async () => {
212
+ _resetWsCacheForTest();
213
+ const calls = [];
214
+ const cwd = await resolveNewSessionCwdClient({
215
+ targetDir: "/home/w/other-proj/src", targetPath: "/home/w/other-proj/src/x.ts",
216
+ currentCwd: "/home/w/pi-web",
217
+ apiUrl: (p) => { calls.push(p); return "http://host" + p; },
218
+ fetchFn: (async (url) => {
219
+ if (String(url).includes("/api/sessions")) {
220
+ return { ok: true, json: async () => ({ sessions: [{ cwd: "/home/w/pi-web" }, { projectRoot: "/home/w/other-proj" }] }) };
221
+ }
222
+ return { ok: true, json: async () => ({ ok: true, cwd: "/home/w/other-proj", switched: true }) };
223
+ })
224
+ });
225
+ assert.equal(cwd, "/home/w/other-proj");
226
+ // sessions 先(派生已知列表)→ 端点后
227
+ assert.deepEqual(calls, ["/api/sessions", "/api/extensions/aiti-git-trace/new-session-cwd"]);
228
+ });
229
+
230
+ test("resolveNewSessionCwdClient:端点复核命中切走 → 用端点结果", async () => {
231
+ _resetWsCacheForTest();
232
+ const cwd = await resolveNewSessionCwdClient({
233
+ targetDir: "/home/w/other-proj",
234
+ currentCwd: "/home/w/pi-web",
235
+ apiUrl: (p) => "http://host" + p,
236
+ fetchFn: (async (url) => {
237
+ if (String(url).includes("/api/sessions")) return { ok: true, json: async () => ({ sessions: [] }) };
238
+ return { ok: true, json: async () => ({ ok: true, cwd: "/home/w/other-proj", switched: true }) };
239
+ })
240
+ });
241
+ assert.equal(cwd, "/home/w/other-proj");
242
+ });
243
+
244
+ test("resolveNewSessionCwdClient:端点失败/缺席 → 本地判定兜底(已知列表在手)", async () => {
245
+ _resetWsCacheForTest();
246
+ // git-trace 端点 fetch 抛异常(未装/404)→ 兜底 = 本地 resolveNewSessionCwd(knownWorkspaces 已从 sessions 派生)
247
+ const cwd = await resolveNewSessionCwdClient({
248
+ targetDir: "/home/w/pi-web/docs", targetPath: "/home/w/pi-web/docs/guide.md",
249
+ currentCwd: "/home/w/pi-work",
250
+ apiUrl: (p) => "http://host" + p,
251
+ fetchFn: (async (url) => {
252
+ if (String(url).includes("/api/sessions")) return { ok: true, json: async () => ({ sessions: [{ cwd: "/home/w/pi-web" }] }) };
253
+ throw new Error("network");
254
+ })
255
+ });
256
+ assert.equal(cwd, "/home/w/pi-web"); // 端点缺席 → 已知 workspace 命中,不落 docs 子目录
257
+ });
258
+
259
+ test("resolveNewSessionCwdClient:端点返回非 ok → 兜底", async () => {
260
+ _resetWsCacheForTest();
261
+ const cwd = await resolveNewSessionCwdClient({
262
+ targetDir: "/home/w/other-proj",
263
+ currentCwd: "/home/w/pi-web",
264
+ apiUrl: (p) => "http://host" + p,
265
+ fetchFn: (async (url) => {
266
+ if (String(url).includes("/api/sessions")) return { ok: true, json: async () => ({ sessions: [] }) };
267
+ return { ok: true, json: async () => ({ ok: false, error: "缺少 targetDir" }) };
268
+ })
269
+ });
270
+ assert.equal(cwd, "/home/w/other-proj");
271
+ });
272
+
273
+ test("resolveNewSessionCwdClient:无 cwd → 不短路,sessions 命中归一化 workspace", async () => {
274
+ _resetWsCacheForTest();
275
+ const cwd = await resolveNewSessionCwdClient({
276
+ targetDir: "/home/w/pi-web/docs", targetPath: "/home/w/pi-web/docs/guide.md",
277
+ currentCwd: "",
278
+ apiUrl: (p) => "http://host" + p,
279
+ fetchFn: (async (url) => {
280
+ if (String(url).includes("/api/sessions")) return { ok: true, json: async () => ({ sessions: [{ projectRoot: "/home/w/pi-web" }] }) };
281
+ return { ok: true, json: async () => ({ ok: true, cwd: "/home/w/pi-web", switched: false }) };
282
+ })
283
+ });
284
+ assert.equal(cwd, "/home/w/pi-web");
285
+ });
286
+
287
+ test("resolveNewSessionCwdClient:sessions 拉取失败 → 降级 [],本地判定仍工作", async () => {
288
+ _resetWsCacheForTest();
289
+ const cwd = await resolveNewSessionCwdClient({
290
+ targetDir: "/home/w/proj/tmp", targetPath: "/home/w/proj/tmp/x.log",
291
+ currentCwd: "/home/w/other",
292
+ apiUrl: (p) => "http://host" + p,
293
+ fetchFn: (async (url) => {
294
+ if (String(url).includes("/api/sessions")) throw new Error("sessions 挂了");
295
+ return { ok: true, json: async () => ({ ok: true, cwd: "/home/w/proj", switched: true }) };
296
+ })
297
+ });
298
+ assert.equal(cwd, "/home/w/proj"); // 端点结果优先;sessions 缺席不影响主流程
299
+ });
300
+
301
+ test("buildAtText:与宿主 buildAtMentionText 同格式(空格加引号、目录尾斜杠)", () => {
302
+ assert.equal(buildAtText("docs/a.md"), "@docs/a.md ");
303
+ assert.equal(buildAtText("my docs/a.md"), '@"my docs/a.md" ');
304
+ assert.equal(buildAtText("proj", true), "@proj/ ");
305
+ assert.equal(buildAtText("my proj", true), '@"my proj/" ');
306
+ assert.equal(buildAtText("proj/", true), "@proj/ "); // 尾斜杠归一
307
+ assert.equal(buildAtText("D:/workspace/a b.md"), '@"D:/workspace/a b.md" ');
308
+ });
309
+
310
+ test("openNewSession:pendingComposer + CWD 判定 + 派发(dispatch 注入;node 无 window)", async () => {
311
+ _resetWsCacheForTest();
312
+ const win = {};
313
+ const events = [];
314
+ await openNewSession({
315
+ text: "@docs/a.md ", targetDir: "/home/w/pi-web/lib", targetPath: "/home/w/pi-web/lib/a.ts", currentCwd: "/home/w/pi-web",
316
+ apiUrl: () => "http://x",
317
+ fetchFn: (async () => { throw new Error("不应发起请求(containment 保持)"); }),
318
+ dispatch: (evt) => events.push(evt),
319
+ windowRef: win,
320
+ });
321
+ assert.ok(win.__piWebPendingComposer);
322
+ assert.equal(win.__piWebPendingComposer.text, "@docs/a.md ");
323
+ assert.ok(win.__piWebPendingComposer.at > 0);
324
+ assert.equal(events.length, 1);
325
+ assert.equal(events[0].type, "pi-web:new-session");
326
+ assert.equal(events[0].detail.cwd, "/home/w/pi-web"); // 保持当前
327
+ });
328
+
329
+ test("openNewSession:切走路径(sessions + git-trace 端点复核后切到目标)", async () => {
330
+ _resetWsCacheForTest();
331
+ const events = [];
332
+ await openNewSession({
333
+ text: "@/home/w/other ", targetDir: "/home/w/other", targetPath: "/home/w/other/x.ts", currentCwd: "/home/w/pi-web",
334
+ apiUrl: (p) => "http://host" + p,
335
+ fetchFn: (async (url) => {
336
+ if (String(url).includes("/api/sessions")) return { ok: true, json: async () => ({ sessions: [] }) };
337
+ return { ok: true, json: async () => ({ ok: true, cwd: "/home/w/other", switched: true }) };
338
+ }),
339
+ dispatch: (evt) => events.push(evt),
340
+ windowRef: {},
341
+ });
342
+ assert.equal(events[0].detail.cwd, "/home/w/other");
343
+ });
344
+
345
+ test("openNewSessionWithExtSvc:session-manager.mention 服务优先(targetPath 透传)", async () => {
346
+ let svcCalled = 0;
347
+ const svc = {
348
+ openNewSession: async (_t, o) => { svcCalled++; assert.equal(o.targetDir, "/home/w/pi-web/lib"); assert.equal(o.targetPath, "/home/w/pi-web/lib/a.ts"); assert.equal(o.currentCwd, "/home/w/pi-web"); },
349
+ };
350
+ await openNewSessionWithExtSvc({
351
+ text: "@docs/a.md ", targetDir: "/home/w/pi-web/lib", targetPath: "/home/w/pi-web/lib/a.ts", currentCwd: "/home/w/pi-web",
352
+ apiUrl: () => "http://x",
353
+ extSvc: (k) => (k === "session-manager.mention" ? svc : undefined),
354
+ });
355
+ assert.equal(svcCalled, 1);
356
+ });
357
+
358
+ test("openNewSessionWithExtSvc:服务缺席 → 降级 _shared 同源实现", async () => {
359
+ _resetWsCacheForTest();
360
+ let fetchCalled = 0;
361
+ const events = [];
362
+ await openNewSessionWithExtSvc({
363
+ text: "@docs/a.md ", targetDir: "/home/w/pi-web/lib", targetPath: "/home/w/pi-web/lib/a.ts", currentCwd: "/home/w/pi-web",
364
+ apiUrl: () => "http://x",
365
+ extSvc: () => undefined, // session-manager 缺席
366
+ fetchFn: (async () => { fetchCalled++; throw new Error("不应有请求(containment 保持)"); }),
367
+ dispatch: (evt) => events.push(evt),
368
+ windowRef: {},
369
+ });
370
+ assert.equal(fetchCalled, 0);
371
+ assert.equal(events.length, 1);
372
+ assert.equal(events[0].detail.cwd, "/home/w/pi-web"); // 降级路径行为与共享实现一致
373
+ });
374
+
375
+ test("openNewSessionWithExtSvc:无 extSvc 注入 → 直接降级(切走全链路)", async () => {
376
+ _resetWsCacheForTest();
377
+ const events = [];
378
+ await openNewSessionWithExtSvc({
379
+ text: "@/home/w/other ", targetDir: "/home/w/other", targetPath: "/home/w/other/x.ts", currentCwd: "/home/w/pi-web",
380
+ apiUrl: (p) => "http://host" + p,
381
+ fetchFn: (async (url) => {
382
+ if (String(url).includes("/api/sessions")) return { ok: true, json: async () => ({ sessions: [] }) };
383
+ return { ok: true, json: async () => ({ ok: true, cwd: "/home/w/other", switched: true }) };
384
+ }),
385
+ dispatch: (evt) => events.push(evt),
386
+ });
387
+ assert.equal(events.length, 1);
388
+ assert.equal(events[0].detail.cwd, "/home/w/other");
389
+ });