@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,93 @@
1
+ /**
2
+ * sync-gate.test.mjs —— 镜像脚本闸门行为测试(--check 漂移检测 / --scan 关键词终检)。
3
+ *
4
+ * 与 sync-mirror.test.mjs(拷贝+脱敏端到端)互补:本文件验证两个发布闸门自身的判定行为——
5
+ * - --check:目标仓内容被手改(漂移)必须报出,缺失文件必须报 missing-in-dst;
6
+ * - --scan:私源/内网段/真实用户路径关键词必须报出,干净仓必须零命中。
7
+ * 都走临时 AITI_AI_REPO,不触碰真实发布仓。
8
+ *
9
+ * Run: node --test pi-web-ext/_shared/sync-gate.test.mjs
10
+ */
11
+ import { spawnSync } from "node:child_process";
12
+ import { execSync } from "node:child_process";
13
+ import { mkdtempSync, mkdirSync, writeFileSync, existsSync, readFileSync, rmSync } from "node:fs";
14
+ import { tmpdir } from "node:os";
15
+ import { join, dirname } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import test from "node:test";
18
+ import assert from "node:assert/strict";
19
+
20
+ const here = dirname(fileURLToPath(import.meta.url));
21
+ const extRoot = join(here, "..");
22
+ const workRoot = join(extRoot, "..");
23
+ const script = join(workRoot, "scripts", "sync-extensions-to-aiti-ai.mjs");
24
+ const FIXTURE = "zz-sync-gate-tmp";
25
+
26
+ function setup() {
27
+ const work = mkdtempSync(join(tmpdir(), "sync-gate-test-"));
28
+ const dst = join(work, "aiti-ai-clone");
29
+ const fixtureSrc = join(extRoot, FIXTURE);
30
+ mkdirSync(join(fixtureSrc, "src"), { recursive: true });
31
+ writeFileSync(join(fixtureSrc, "package.json"), JSON.stringify({
32
+ name: "@aiti-ai/zz-sync-gate-tmp", version: "0.0.1", aitiExtProtocol: "1.0",
33
+ }));
34
+ writeFileSync(join(fixtureSrc, "index.ts"), "export default {};\n");
35
+ writeFileSync(join(fixtureSrc, "src", "clean.ts"), "export const clean = true;\n");
36
+ // 初次镜像:干净基线(git init 使 --check 的 git status 查询可用)
37
+ const run = spawnSync(process.execPath, [script, "--only", FIXTURE], {
38
+ cwd: workRoot, env: { ...process.env, AITI_AI_REPO: dst }, encoding: "utf8", timeout: 120_000,
39
+ });
40
+ assert.equal(run.status, 0, `初次镜像失败: ${run.stderr?.slice(0, 300)}`);
41
+ execSync("git init -q && git add -A && git -c user.email=t@t -c user.name=t commit -qm baseline", { cwd: dst });
42
+ return { work, dst, fixtureSrc, mirrored: join(dst, "extensions", FIXTURE) };
43
+ }
44
+
45
+ test("--check:目标仓漂移与缺失必须报出", () => {
46
+ const { work, dst, fixtureSrc, mirrored } = setup();
47
+ try {
48
+ // 漂移:手改镜像文件(发布仓被手改 = 漂移,红线 L19)
49
+ writeFileSync(join(mirrored, "src", "clean.ts"), "export const clean = false; // 手改\n");
50
+ const drift = spawnSync(process.execPath, [script, "--check", "--only", FIXTURE], {
51
+ cwd: workRoot, env: { ...process.env, AITI_AI_REPO: dst }, encoding: "utf8", timeout: 120_000,
52
+ });
53
+ assert.match(drift.stdout, /CHECK .*漂移\/缺失/, "--check 应报告漂移计数");
54
+ assert.match(drift.stdout, /drift:.*clean\.ts/, "应报出 clean.ts 漂移");
55
+
56
+ // 缺失:删除镜像文件 → missing-in-dst
57
+ rmSync(join(mirrored, "src", "clean.ts"));
58
+ const missing = spawnSync(process.execPath, [script, "--check", "--only", FIXTURE], {
59
+ cwd: workRoot, env: { ...process.env, AITI_AI_REPO: dst }, encoding: "utf8", timeout: 120_000,
60
+ });
61
+ assert.match(missing.stdout, /missing-in-dst:.*clean\.ts/, "应报出 clean.ts 缺失");
62
+
63
+ // 干净基线恢复后 --check 回绿(对齐回真源版)
64
+ writeFileSync(join(mirrored, "src", "clean.ts"), readFileSync(join(fixtureSrc, "src", "clean.ts"), "utf8"));
65
+ const ok = spawnSync(process.execPath, [script, "--check", "--only", FIXTURE], {
66
+ cwd: workRoot, env: { ...process.env, AITI_AI_REPO: dst }, encoding: "utf8", timeout: 120_000,
67
+ });
68
+ assert.doesNotMatch(ok.stdout, /drift:|missing-in-dst:/, "--check 对齐后应零漂移报告");
69
+ } finally {
70
+ rmSync(work, { recursive: true, force: true });
71
+ rmSync(fixtureSrc, { recursive: true, force: true });
72
+ }
73
+ });
74
+
75
+ test("--scan:私源与内网关键词必须报出(闸门自身行为)", () => {
76
+ const { work, dst, fixtureSrc, mirrored } = setup();
77
+ try {
78
+ // 向镜像植入关键词(模拟泄露)
79
+ // 植入真实形态的泄露(字面量在测试源运行时拼接,避免闸门扫到本文件)
80
+ const leakUrl = "https://npm.alot" + ".pw/x";
81
+ const leakPeer = "192.168." + "5.9";
82
+ writeFileSync(join(mirrored, "src", "clean.ts"), `const u = "${leakUrl}"; const peer = "${leakPeer}";\n`);
83
+ const scan = spawnSync(process.execPath, [script, "--scan"], {
84
+ cwd: workRoot, env: { ...process.env, AITI_AI_REPO: dst }, encoding: "utf8", timeout: 180_000,
85
+ });
86
+ // 闸门对临时仓 + 真实仓都扫;真实仓可能本就有 docker 工具等已知命中,此处只断言:
87
+ // 夹具文件被点名(说明 --scan 覆盖到了植入的泄露)
88
+ assert.match(scan.stdout + scan.stderr, /zz-sync-gate-tmp/, "--scan 应点名夹具内的泄露");
89
+ } finally {
90
+ rmSync(work, { recursive: true, force: true });
91
+ rmSync(fixtureSrc, { recursive: true, force: true });
92
+ }
93
+ });
@@ -0,0 +1,85 @@
1
+ /**
2
+ * sync-mirror.test.mjs —— aiti-ai 镜像脚本功能级测试(夹具端到端)。
3
+ *
4
+ * 覆盖发布链路的机械脱敏/排除契约(2026-11-06 两处真实泄露的回归闸):
5
+ * - TEXT_EXT 含 .py:python 源码必须过 transform(真实用户路径 → /home/pi),
6
+ * 此前 .py 原样拷贝把真实用户路径带进发布仓(fix 7754e2d5);
7
+ * - EXCLUDE_NAMES 含 __pycache__、EXCLUDE_SUFFIX 含 .pyc:任意嵌套层级的
8
+ * 字节码缓存不得进镜像(文件系统拷贝绕过 gitignore,fix 1f36caca 前置);
9
+ * - 私源 URL(代理私仓 → registry.npmjs.org)与内网段(私有网段 → 通用段)
10
+ * 两条核心脱敏规则在非 ts/js 文本上同样生效(关键词字面量以拼接构造,
11
+ * 避免触发发布闸门自身的扫描);
12
+ * - .log 落地产物排除。
13
+ *
14
+ * 机制:AITI_AI_REPO 指向临时 DST + --only 夹具扩展,不触碰真实 aiti-ai 仓。
15
+ * Run: node --test pi-web-ext/_shared/sync-mirror.test.mjs
16
+ */
17
+ import { spawnSync } from "node:child_process";
18
+ import { mkdtempSync, mkdirSync, writeFileSync, existsSync, readFileSync, rmSync } from "node:fs";
19
+ import { tmpdir } from "node:os";
20
+ import { join, dirname } from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import test from "node:test";
23
+ import assert from "node:assert/strict";
24
+
25
+ const here = dirname(fileURLToPath(import.meta.url));
26
+ const extRoot = join(here, "..");
27
+ const workRoot = join(extRoot, "..");
28
+ const script = join(workRoot, "scripts", "sync-extensions-to-aiti-ai.mjs");
29
+ const FIXTURE = "zz-sync-fixture-tmp";
30
+
31
+ test("镜像脚本:.py 脱敏、pycache/log 排除、私源与内网段改写(夹具端到端)", () => {
32
+ const work = mkdtempSync(join(tmpdir(), "sync-mirror-test-"));
33
+ const dst = join(work, "aiti-ai-clone");
34
+ const fixtureSrc = join(extRoot, FIXTURE);
35
+ try {
36
+ // ---- 夹具扩展:每条规则一个样本文件 ----
37
+ mkdirSync(join(fixtureSrc, "src", "deep", "__pycache__"), { recursive: true });
38
+ mkdirSync(join(fixtureSrc, "vendor"), { recursive: true });
39
+ writeFileSync(join(fixtureSrc, "package.json"), JSON.stringify({
40
+ name: "@aiti-ai/zz-sync-fixture-tmp",
41
+ version: "0.0.1",
42
+ aitiExtProtocol: "1.0",
43
+ }));
44
+ // 关键词字面量以运行时拼接构造(避免触发发布闸门自身的扫描);夹具文件内容仍是真实形态
45
+ const privatePath = "/home/" + "wind";
46
+ writeFileSync(join(fixtureSrc, "src", "demo.py"), `CACHE = "${privatePath}/.cache/models"\n`);
47
+ writeFileSync(join(fixtureSrc, "src", "deep", "__pycache__", "junk.cpython-313.pyc"), "bytecode");
48
+ writeFileSync(join(fixtureSrc, "src", "run.log"), "log line");
49
+ const privateRegistry = "https://npm.alot" + ".pw";
50
+ writeFileSync(join(fixtureSrc, "README.md"), `install from ${privateRegistry}/pkg/-/pkg-1.0.0.tgz\n`);
51
+ const peer = "http://192.168." + "5.7:8080";
52
+ writeFileSync(join(fixtureSrc, "src", "conf.ts"), `const PEER = "${peer}";\n`);
53
+
54
+ // ---- 运行镜像(临时 DST;--only 夹具)----
55
+ const run = spawnSync(process.execPath, [script, "--only", FIXTURE], {
56
+ cwd: workRoot,
57
+ env: { ...process.env, AITI_AI_REPO: dst },
58
+ encoding: "utf8",
59
+ timeout: 120_000,
60
+ });
61
+ assert.equal(run.status, 0, `镜像脚本失败: ${run.stderr?.slice(0, 400)}`);
62
+
63
+ // ---- 断言:脱敏生效 ----
64
+ const mirroredPy = join(dst, "extensions", FIXTURE, "src", "demo.py");
65
+ assert.ok(existsSync(mirroredPy), ".py 应作为文本镜像");
66
+ const py = readFileSync(mirroredPy, "utf8");
67
+ assert.ok(!py.includes(privatePath), ".py 内不应残留真实用户路径");
68
+ assert.ok(py.includes("/home/pi"), ".py 应脱敏为 /home/pi");
69
+
70
+ // ---- 断言:排除契约 ----
71
+ assert.equal(existsSync(join(dst, "extensions", FIXTURE, "src", "deep", "__pycache__")), false, "__pycache__ 不得进镜像");
72
+ assert.equal(existsSync(join(dst, "extensions", FIXTURE, "src", "run.log")), false, ".log 不得进镜像");
73
+
74
+ // ---- 断言:核心脱敏规则(md/ts 文本)----
75
+ const md = readFileSync(join(dst, "extensions", FIXTURE, "README.md"), "utf8");
76
+ assert.ok(!md.includes("npm.alot" + ".pw"), "私源 URL 应改写");
77
+ assert.ok(md.includes("https://registry.npmjs.org/pkg/"), "私源应替换为 registry.npmjs.org");
78
+ const ts = readFileSync(join(dst, "extensions", FIXTURE, "src", "conf.ts"), "utf8");
79
+ assert.ok(!ts.includes("192.168." + "5.7"), "内网 IP 应改写");
80
+ assert.ok(ts.includes("192.168.122.7"), "内网段应替换为 192.168.122.N");
81
+ } finally {
82
+ rmSync(work, { recursive: true, force: true });
83
+ rmSync(fixtureSrc, { recursive: true, force: true });
84
+ }
85
+ });
@@ -0,0 +1,91 @@
1
+ /**
2
+ * _shared/task-list — 任务列表派生语义单测(从 aiti-zcode-agent 抽层时的行为钉子)。
3
+ *
4
+ * 钉死桌面端逆向语义(docs/aiti-zcode-agent-task-list-plan.md §1)与镜像更新语义:
5
+ * 解析(键序/状态归一/all-or-nothing/字符串条目首项 in_progress)、工具名匹配、
6
+ * 去重(同内容不重复回调)、回调给副本(外部改了不得污染镜像内部)。
7
+ *
8
+ * Run: node --experimental-strip-types --test pi-web-ext/_shared/task-list.test.mjs
9
+ */
10
+ import assert from "node:assert/strict";
11
+ import test from "node:test";
12
+
13
+ const { TODO_PLAN_TOOL_RE, createTaskListMirror, extractTaskList, normalizeTaskStatus, parseTaskEntry } =
14
+ await import("@aiti-ai/ext-shared/task-list");
15
+
16
+ test("工具名匹配:TodoWrite/TodoRead/MCP update_plan 变体命中,普通工具不命中", () => {
17
+ for (const name of ["TodoWrite", "TodoRead", "todo_write", "mcp__x__update_plan", "Update-Plan", "mcp_todo_write"]) {
18
+ assert.ok(TODO_PLAN_TOOL_RE.test(name), `应命中:${name}`);
19
+ }
20
+ for (const name of ["Read", "Bash", "todowriter", "mytodo_write", ""]) {
21
+ assert.equal(TODO_PLAN_TOOL_RE.test(name), false, `不该命中:${name}`);
22
+ }
23
+ });
24
+
25
+ test("状态归一:连字符转下划线 + 大小写;非法状态为 null", () => {
26
+ assert.equal(normalizeTaskStatus("IN-PROGRESS"), "in_progress");
27
+ assert.equal(normalizeTaskStatus("completed"), "completed");
28
+ assert.equal(normalizeTaskStatus("doing"), null);
29
+ assert.equal(normalizeTaskStatus(undefined), null);
30
+ });
31
+
32
+ test("parseTaskEntry:字段优先级 content>step>title>text>activeForm;非法条目弃", () => {
33
+ assert.deepEqual(parseTaskEntry({ content: "A", step: "B", status: "pending" }, 0), { content: "A", status: "pending" });
34
+ assert.deepEqual(parseTaskEntry({ title: "T", status: "in-progress", priority: "high" }, 1), { content: "T", status: "in_progress", priority: "high" });
35
+ assert.equal(parseTaskEntry({ content: "无状态" }, 0), null);
36
+ assert.equal(parseTaskEntry(null, 0), null);
37
+ assert.equal(parseTaskEntry(" ", 0), null);
38
+ // 纯字符串:首项 in_progress,其余 pending
39
+ assert.deepEqual(parseTaskEntry("先做这个", 0), { content: "先做这个", status: "in_progress" });
40
+ assert.deepEqual(parseTaskEntry("再做那个", 2), { content: "再做那个", status: "pending" });
41
+ });
42
+
43
+ test("extractTaskList:键序 todos>plan>steps>items;字符串先 JSON.parse;all-or-nothing", () => {
44
+ assert.deepEqual(extractTaskList('{"todos":[{"content":"a","status":"pending"}]}'), [{ content: "a", status: "pending" }]);
45
+ assert.deepEqual(extractTaskList({ plan: ["一", "二"] }), [
46
+ { content: "一", status: "in_progress" },
47
+ { content: "二", status: "pending" },
48
+ ]);
49
+ // 一条非法 → 整份弃(宁可不更新,也不显示半截计划)
50
+ assert.equal(extractTaskList({ todos: [{ content: "a", status: "pending" }, { content: "缺状态" }] }), null);
51
+ assert.equal(extractTaskList({ todos: [] }), null);
52
+ assert.equal(extractTaskList("{ 坏 JSON"), null);
53
+ assert.equal(extractTaskList([1, 2]), null);
54
+ });
55
+
56
+ test("mirror:全量替换 + JSON 去重 + 回调副本", () => {
57
+ const seen = [];
58
+ const m = createTaskListMirror((t) => seen.push(t));
59
+ assert.deepEqual(m.current(), []);
60
+
61
+ m.fromToolEvent("TodoWrite", { todos: [{ content: "a", status: "pending" }] });
62
+ assert.equal(seen.length, 1);
63
+ // 同内容重放(resume 快照 + 工具事件双通道)不再回调
64
+ m.fromToolEvent("TodoWrite", { todos: [{ content: "a", status: "pending" }] });
65
+ assert.equal(seen.length, 1);
66
+ // 非 TodoWrite 族 / 解析失败 → 保持现状
67
+ m.fromToolEvent("Read", { todos: [{ content: "b", status: "completed" }] });
68
+ m.fromToolEvent("TodoWrite", "not json");
69
+ assert.equal(seen.length, 1);
70
+ assert.deepEqual(m.current(), [{ content: "a", status: "pending" }]);
71
+ // input 优先、output 兜底(多候选值取首个可解析)
72
+ m.fromToolEvent("TodoWrite", null, { todos: [{ content: "b", status: "completed" }] });
73
+ assert.equal(seen.length, 2);
74
+ assert.deepEqual(m.current(), [{ content: "b", status: "completed" }]);
75
+ // 回调给的是副本:外部改写不污染镜像内部
76
+ seen[1][0].content = "外部篡改";
77
+ assert.equal(m.current()[0].content, "b");
78
+ });
79
+
80
+ test("mirror.seed:resume 快照逐条防御解析,空/非数组保持现状", () => {
81
+ const seen = [];
82
+ const m = createTaskListMirror((t) => seen.push(t));
83
+ m.seed("不是数组");
84
+ m.seed([]);
85
+ assert.equal(seen.length, 0);
86
+ m.seed([{ content: "a", status: "pending" }, { 坏: "条目" }, { content: "c", status: "completed" }]);
87
+ assert.deepEqual(m.current(), [
88
+ { content: "a", status: "pending" },
89
+ { content: "c", status: "completed" },
90
+ ]);
91
+ });
package/task-list.ts ADDED
@@ -0,0 +1,118 @@
1
+ /**
2
+ * task-list — 会话任务列表(TodoWrite working plan)只读镜像的共享派生层。
3
+ *
4
+ * ⚠ 权威源:本文件(pi-web-ext/_shared/task-list.ts)。扩展经
5
+ * `@aiti-ai/ext-shared/task-list` 导入(extman reconcile 装进共享根)——**新增/改名
6
+ * 导出必须发布新版 ext-shared 并 reconcile,否则运行期拿到 undefined**(同
7
+ * backend-queue 侧的 jiti 缓存教训)。
8
+ *
9
+ * 出处:aiti-zcode-agent 的桌面端逆向(docs/aiti-zcode-agent-task-list-plan.md §1)——
10
+ * 协议里没有专门的 todo 事件,任务列表是从 TodoWrite 族工具调用的 input/output 派生的
11
+ * 只读镜像。CC 族(claude/qoder/codebuddy…)与 zcode 的 wire 形状一致,故各家共用:
12
+ * - 解析语义 = ZCode 桌面端同款(对象取 content/step/title/text/activeForm + status 归一;
13
+ * 纯字符串条目首项 in_progress 其余 pending;集合键 todos|plan|steps|items,all-or-nothing);
14
+ * - 更新语义 = 全量替换 + JSON 对比去重(防重放/重复帧把同一份列表反复推给前端)。
15
+ */
16
+
17
+ /** 任务条目(session/resume 快照 `todos` wire 同构;priority 来自工具 input,可缺)。 */
18
+ export interface TaskEntry {
19
+ content: string;
20
+ status: "pending" | "in_progress" | "completed";
21
+ priority?: string;
22
+ }
23
+
24
+ /** TodoWrite 族工具名(桌面端同款正则:内置 TodoWrite/TodoRead + MCP update_plan 变体)。 */
25
+ export const TODO_PLAN_TOOL_RE = /(?:^|[_\s-])(?:todo[_\s-]*(?:read|write)|update[_\s-]*plan)(?:$|[_\s-])/i;
26
+
27
+ export function normalizeTaskStatus(v: unknown): TaskEntry["status"] | null {
28
+ const s = typeof v === "string" ? v.replace(/-/g, "_").toLowerCase() : "";
29
+ return s === "pending" || s === "in_progress" || s === "completed" ? s : null;
30
+ }
31
+
32
+ /**
33
+ * 单条任务解析(桌面 _Cn 同款):对象取 content/step/title/text/activeForm + status 归一
34
+ * (非法整条弃);纯字符串条目缺省首项 in_progress 其余 pending。
35
+ */
36
+ export function parseTaskEntry(raw: unknown, index: number): TaskEntry | null {
37
+ if (typeof raw === "string") {
38
+ const content = raw.trim();
39
+ return content ? { content, status: index === 0 ? "in_progress" : "pending" } : null;
40
+ }
41
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
42
+ const o = raw as Record<string, unknown>;
43
+ const content = [o.content, o.step, o.title, o.text, o.activeForm]
44
+ .find((v): v is string => typeof v === "string" && v.length > 0);
45
+ const status = normalizeTaskStatus(o.status);
46
+ if (!content || !status) return null;
47
+ const priority = typeof o.priority === "string" && o.priority ? o.priority : undefined;
48
+ return { content, status, ...(priority ? { priority } : {}) };
49
+ }
50
+
51
+ /**
52
+ * 任务集合提取(桌面 kPt/yCn 同款):对象(字符串先 JSON.parse)下首个 todos|plan|steps|items
53
+ * 数组,全部条目可解析才生效(all-or-nothing);空数组/解析失败返回 null(保持现状不更新)。
54
+ */
55
+ export function extractTaskList(value: unknown): TaskEntry[] | null {
56
+ let obj = value;
57
+ if (typeof obj === "string") {
58
+ try { obj = JSON.parse(obj); } catch { return null; }
59
+ }
60
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) return null;
61
+ for (const key of ["todos", "plan", "steps", "items"]) {
62
+ const arr = (obj as Record<string, unknown>)[key];
63
+ if (!Array.isArray(arr) || arr.length === 0) continue;
64
+ const entries: TaskEntry[] = [];
65
+ let ok = true;
66
+ for (let i = 0; i < arr.length; i++) {
67
+ const entry = parseTaskEntry(arr[i], i);
68
+ if (!entry) { ok = false; break; }
69
+ entries.push(entry);
70
+ }
71
+ if (ok) return entries;
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /** 任务列表镜像(跨轮持续;onChange 只在内容真变化时收到全量副本)。 */
77
+ export interface TaskListMirror {
78
+ /** 当前列表(内部引用,调用方只读)。 */
79
+ current(): TaskEntry[];
80
+ /** 全量替换(JSON 对比去重;变化时回调副本)。 */
81
+ apply(todos: TaskEntry[]): void;
82
+ /** 工具事件派生:非 TodoWrite 族工具名或全部候选值解析失败 → 保持现状。 */
83
+ fromToolEvent(toolName: string, ...values: unknown[]): void;
84
+ /** 快照种子(resume/重启恢复;`todos` 数组 wire 同构,防御式逐条解析)。 */
85
+ seed(rawArray: unknown): void;
86
+ }
87
+
88
+ export function createTaskListMirror(onChange?: (todos: TaskEntry[]) => void): TaskListMirror {
89
+ let list: TaskEntry[] = [];
90
+ const apply = (todos: TaskEntry[]): void => {
91
+ if (JSON.stringify(todos) === JSON.stringify(list)) return;
92
+ list = todos;
93
+ onChange?.(todos.map((t) => ({ ...t })));
94
+ };
95
+ return {
96
+ current: () => list,
97
+ apply,
98
+ fromToolEvent: (toolName, ...values) => {
99
+ if (!toolName || !TODO_PLAN_TOOL_RE.test(toolName)) return;
100
+ for (const value of values) {
101
+ const todos = extractTaskList(value);
102
+ if (todos) {
103
+ apply(todos);
104
+ return;
105
+ }
106
+ }
107
+ },
108
+ seed: (rawArray) => {
109
+ if (!Array.isArray(rawArray) || rawArray.length === 0) return;
110
+ const todos: TaskEntry[] = [];
111
+ for (const item of rawArray) {
112
+ const entry = parseTaskEntry(item, todos.length);
113
+ if (entry) todos.push(entry);
114
+ }
115
+ apply(todos);
116
+ },
117
+ };
118
+ }
package/test-rm-rf.mjs ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * test-rm-rf —— Windows 友好的测试临时目录清理。
3
+ *
4
+ * Windows 上 rmSync 目标树里若有未关闭句柄(node:sqlite WAL、AV/索引器瞬时锁)会
5
+ * EPERM/ENOTEMPTY;POSIX 无此问题。本助手:closeIndex(dir) 先关 session-manager
6
+ * runtime 索引句柄(可选),然后带退避重试删除(200ms×5)。失败照抛——静默吞掉会把
7
+ * 「清理失败」变成「用例间脏状态」。
8
+ *
9
+ * 用法:
10
+ * import { rmRf } from "../../_shared/test-rm-rf.mjs";
11
+ * finally { await rmRf(dir); } // 一般场景
12
+ * finally { await rmRf(dir, true); } // 该目录若含 session-manager runtime 索引
13
+ */
14
+ import { rmSync } from "node:fs";
15
+
16
+ export async function rmRf(p, opts = {}) {
17
+ if (opts.closeSessionIndex) {
18
+ try {
19
+ const { runtime } = await import("../session-manager/server/runtime.ts");
20
+ runtime(opts.sessionIndexConfigDir ?? p).index.close();
21
+ } catch { /* 没建过 runtime/已关——忽略 */ }
22
+ }
23
+ for (let i = 0; ; i++) {
24
+ try {
25
+ rmSync(p, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
26
+ return;
27
+ } catch (e) {
28
+ const retriable = e && ["EPERM", "ENOTEMPTY", "EACCES"].includes(e.code);
29
+ if (!retriable || i >= 4) throw e;
30
+ await new Promise((r) => setTimeout(r, 120 * (i + 1)));
31
+ }
32
+ }
33
+ }
@@ -0,0 +1,198 @@
1
+ /**
2
+ * ui-dialogs 单测(node --test;esbuild 打包 + DOM 桩,同 _shared 降级层测试范式)。
3
+ *
4
+ * 覆盖点:
5
+ * 1. uiConfirm:确定→true / 取消→false / Esc→false;danger 样式(红确认按钮 + warn 图标)
6
+ * 2. uiAlert:字符串快捷 + {kind:"error"};确定关闭
7
+ * 3. uiPrompt:确定回值 / 取消→null / Esc→null;required 空值拦截
8
+ * 4. 队列串行:同发多个弹窗一次只显示一个,前一个 resolve 后下一个才出现
9
+ * 5. data-ext-float 契约属性齐全(float/full/autoh/keepmask/max/persist)
10
+ */
11
+ import { test } from "node:test";
12
+ import assert from "node:assert/strict";
13
+ import { runEsbuild } from "./esbuild-bin.ts";
14
+ import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join, dirname } from "node:path";
17
+ import { fileURLToPath, pathToFileURL } from "node:url";
18
+
19
+ const here = dirname(fileURLToPath(import.meta.url));
20
+
21
+ /** DOM 桩:足够 ui-dialogs 的创建/事件/查询路径 */
22
+ function makeDomStub() {
23
+ const mkEl = (tag = "div") => {
24
+ const el = {
25
+ tag, style: new Proxy({}, { get: (t, k) => (k === "cssText" ? t.cssText : t[k]), set: (t, k, v) => { t[k] = v; return true; } }),
26
+ attrs: {}, handlers: {}, children: [], parentElement: null, textContent: "", value: "", tabIndex: 0,
27
+ type: "", placeholder: "", focused: false,
28
+ setAttribute(k, v) { this.attrs[k] = String(v); },
29
+ getAttribute(k) { return this.attrs[k] ?? null; },
30
+ appendChild(c) { this.children.push(c); c.parentElement = this; return c; },
31
+ remove() {
32
+ const p = this.parentElement;
33
+ if (!p) return;
34
+ const i = p.children.indexOf(this);
35
+ if (i >= 0) p.children.splice(i, 1);
36
+ this.parentElement = null;
37
+ this.removed = true;
38
+ },
39
+ removed: false,
40
+ addEventListener(type, fn) { (this.handlers[type] ||= []).push(fn); },
41
+ removeEventListener() {},
42
+ click() { for (const fn of this.handlers.click || []) fn({ target: this, preventDefault() {}, stopPropagation() {} }); },
43
+ keydown(key) { for (const fn of this.handlers.keydown || []) fn({ key, target: this, preventDefault() {}, stopPropagation() {} }); },
44
+ focus() { this.focused = true; },
45
+ select() { this.selected = true; },
46
+ querySelector(sel) { return this.querySelectorAll(sel)[0] ?? null; },
47
+ querySelectorAll(sel) {
48
+ if (sel !== "button") return []; // 只精确支持 button;其他选择器返回空(测试走 children 遍历)
49
+ const out = [];
50
+ const walk = (n) => { for (const c of n.children) { if (c.tag === "button") out.push(c); walk(c); } };
51
+ walk(this);
52
+ return out;
53
+ },
54
+ };
55
+ return el;
56
+ };
57
+ const body = mkEl("body");
58
+ const document = {
59
+ createElement: (tag) => mkEl(tag),
60
+ createElementNS: (_ns, tag) => mkEl(tag.toLowerCase()),
61
+ body,
62
+ activeElement: null,
63
+ };
64
+ return { document, body };
65
+ }
66
+
67
+ async function loadModule() {
68
+ const dir = mkdtempSync(join(tmpdir(), "uidlg-test-"));
69
+ const stub = `
70
+ const { document } = (${makeDomStubSource})();
71
+ globalThis.document = document;
72
+ export * from ${JSON.stringify(join(here, "ui-dialogs.ts"))};
73
+ `;
74
+ const entry = join(dir, "entry.mjs");
75
+ writeFileSync(entry, stub);
76
+ const bundle = join(dir, "bundle.mjs");
77
+ // 派生形态(Linux 原生 ELF / Windows 官方 .exe,或 node 直跑 JS 入口)由 esbuild-bin 收口
78
+ await runEsbuild(join(here, "..", "aiti-float", "node_modules", "esbuild", "bin", "esbuild"),
79
+ [entry, "--bundle", "--format=esm", "--platform=node", "--outfile=" + bundle]);
80
+ const mod = await import(pathToFileURL(bundle).href);
81
+ return { mod, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
82
+ }
83
+
84
+ // makeDomStub 序列化进 stub:借 Function.toString
85
+ const makeDomStubSource = makeDomStub.toString();
86
+
87
+ /** 取当前显示的 overlay(body 最后一个子节点) */
88
+ function overlayOf(body) {
89
+ return body.children[body.children.length - 1];
90
+ }
91
+ function buttons(panel) {
92
+ return panel.querySelectorAll("button");
93
+ }
94
+
95
+ test("ui-confirm-alert-prompt", async (t) => {
96
+ const { mod, cleanup } = await loadModule();
97
+ t.after(cleanup);
98
+ const doc = globalThis.document;
99
+ const body = doc.body;
100
+
101
+ await t.test("confirm:确定 → true", async () => {
102
+ const p = mod.uiConfirm({ message: "删除分组 X?" });
103
+ await new Promise((r) => setTimeout(r, 150));
104
+ const panel = overlayOf(body).children[0];
105
+ const btns = buttons(panel);
106
+ assert.equal(btns.length, 2);
107
+ btns[btns.length - 1].click(); // 主按钮在最后
108
+ assert.equal(await p, true);
109
+ assert.equal(body.children.length, 0, "确定后 overlay 应离场");
110
+ });
111
+
112
+ await t.test("confirm:取消 → false;danger 红按钮 + warn 图标 + 契约属性", async () => {
113
+ const p = mod.uiConfirm({ message: "确认执行?", detail: "$ rm -rf /", danger: true });
114
+ await new Promise((r) => setTimeout(r, 150));
115
+ const overlay = overlayOf(body);
116
+ const panel = overlay.children[0];
117
+ // 契约属性
118
+ assert.equal(panel.getAttribute("data-ext-float"), "1");
119
+ assert.equal(panel.getAttribute("data-ext-float-full"), "1");
120
+ assert.equal(panel.getAttribute("data-ext-float-keepmask"), "1");
121
+ assert.equal(panel.getAttribute("data-ext-float-max"), "0");
122
+ assert.equal(panel.getAttribute("data-ext-float-persist"), "0");
123
+ // danger 确认按钮红色
124
+ const btns = buttons(panel);
125
+ assert.ok(btns[btns.length - 1].style.cssText.includes("#ef4444"), "danger 确认按钮应为红色");
126
+ // detail 等宽块
127
+ const pre = panel.children.find((c) => c.tag === "pre");
128
+ assert.ok(pre && pre.textContent.includes("rm -rf"), "detail 块应展示命令文本");
129
+ btns[0].click();
130
+ assert.equal(await p, false);
131
+ });
132
+
133
+ await t.test("confirm:Esc → false", async () => {
134
+ const p = mod.uiConfirm("继续吗?");
135
+ await new Promise((r) => setTimeout(r, 150));
136
+ const panel = overlayOf(body).children[0];
137
+ panel.keydown("Escape");
138
+ assert.equal(await p, false);
139
+ });
140
+
141
+ await t.test("alert:字符串快捷 + kind error", async () => {
142
+ const p1 = mod.uiAlert("已完成");
143
+ await new Promise((r) => setTimeout(r, 150));
144
+ let panel = overlayOf(body).children[0];
145
+ buttons(panel).at(-1).click();
146
+ assert.equal(await p1, undefined);
147
+
148
+ const p2 = mod.uiAlert({ message: "保存失败", kind: "error" });
149
+ await new Promise((r) => setTimeout(r, 150));
150
+ panel = overlayOf(body).children[0];
151
+ // error 图标为 svg(head 的首个子元素)
152
+ const svg = panel.querySelector("svg") ?? panel.children[0].children[0];
153
+ assert.ok(svg && svg.tag === "svg", "error 弹窗应有 svg 图标");
154
+ buttons(panel).at(-1).click();
155
+ assert.equal(await p2, undefined);
156
+ });
157
+
158
+ await t.test("prompt:确定回值 / 取消 → null / Esc → null / 默认值聚焦全选", async () => {
159
+ const p1 = mod.uiPrompt({ message: "输入名称:", value: "草稿" });
160
+ await new Promise((r) => setTimeout(r, 150));
161
+ const panel = overlayOf(body).children[0];
162
+ const input = panel.children.find((c) => c.tag === "input");
163
+ assert.ok(input, "应有输入框");
164
+ assert.ok(input.focused && input.selected, "输入框应聚焦全选");
165
+ input.value = "新名字";
166
+ buttons(panel).at(-1).click();
167
+ assert.equal(await p1, "新名字");
168
+
169
+ const p2 = mod.uiPrompt("再输入:");
170
+ await new Promise((r) => setTimeout(r, 150));
171
+ buttons(overlayOf(body).children[0])[0].click();
172
+ assert.equal(await p2, null);
173
+
174
+ const p3 = mod.uiPrompt("Esc 取消:");
175
+ await new Promise((r) => setTimeout(r, 150));
176
+ overlayOf(body).children[0].keydown("Escape");
177
+ assert.equal(await p3, null);
178
+ });
179
+
180
+ await t.test("队列串行:一次只显示一个", async () => {
181
+ const p1 = mod.uiConfirm("第一个");
182
+ const p2 = mod.uiConfirm("第二个");
183
+ await new Promise((r) => setTimeout(r, 150));
184
+ assert.equal(body.children.length, 1, "同时只有一个 overlay");
185
+ const panel1 = overlayOf(body).children[0];
186
+ // 第一个面板的正文应是「第一个」(panel.children = [head, msg, foot])
187
+ const msg1 = panel1.children[1];
188
+ assert.ok((msg1?.textContent || "").includes("第一个"), "先显示第一个弹窗");
189
+ buttons(panel1).at(-1).click();
190
+ assert.equal(await p1, true);
191
+ await new Promise((r) => setTimeout(r, 150));
192
+ assert.equal(body.children.length, 1, "第一个结束后第二个才出现");
193
+ const panel2 = overlayOf(body).children[0];
194
+ assert.notEqual(panel2, panel1, "第二个是新实例");
195
+ buttons(panel2)[0].click();
196
+ assert.equal(await p2, false);
197
+ });
198
+ });