@aiti-ai/ext-shared 0.0.0-stage → 0.1.11
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/LICENSE +21 -0
- package/README.md +36 -2
- package/agent-accounts.test.mjs +227 -0
- package/agent-accounts.ts +324 -0
- package/agent-capability-contract.test.mjs +129 -0
- package/agent-interaction.test.mjs +194 -0
- package/agent-interaction.ts +340 -0
- package/agent-launch.test.mjs +262 -0
- package/agent-spawn-env.test.mjs +169 -0
- package/agent-spawn-env.ts +548 -0
- package/aiti-editor-inject.mjs +49 -0
- package/backend-queue.test.mjs +336 -0
- package/backend-queue.ts +469 -0
- package/blob-save-route.ts +128 -0
- package/cbc-model-catalog.ts +86 -0
- package/check-client.mjs +273 -0
- package/check-ext-globals.mjs +144 -0
- package/controlled-login-dialog.mjs +270 -0
- package/controlled-login.mjs +398 -0
- package/controlled-login.test.mjs +466 -0
- package/convert-saveas.test.mjs +39 -0
- package/convert-saveas.ts +170 -0
- package/copy-client-bundle.mjs +39 -0
- package/cursor-cli-store.ts +377 -0
- package/dedupe-fetch.test.mjs +71 -0
- package/dedupe-fetch.ts +58 -0
- package/deploy-commit.mjs +52 -0
- package/dev-pack.mjs +246 -0
- package/dock-icons.ts +127 -0
- package/esbuild-bin.test.mjs +53 -0
- package/esbuild-bin.ts +66 -0
- package/exec-async.test.mjs +86 -0
- package/exec-async.ts +179 -0
- package/ext-display-names.ts +91 -0
- package/ext-entry-contracts.test.mjs +131 -0
- package/ext-float-dock-core.test.mjs +348 -0
- package/ext-float-dock-core.ts +783 -0
- package/ext-float-dock-lite.ts +52 -0
- package/ext-float-dock.test.mjs +286 -0
- package/ext-float-dock.ts +740 -0
- package/ext-icons-deploy.mjs +24 -0
- package/ext-lazy.test.mjs +186 -0
- package/ext-lazy.tsx +183 -0
- package/ext-model-state.test.mjs +272 -0
- package/ext-model-state.ts +324 -0
- package/ext-protocol.mjs +113 -0
- package/ext-protocol.test.mjs +88 -0
- package/ext-session-usage.test.mjs +219 -0
- package/ext-session-usage.ts +507 -0
- package/external-cli-governance.ts +153 -0
- package/git-ops-client/api.mjs +56 -0
- package/git-ops-client/branch-panel.tsx +987 -0
- package/git-ops-client/i18n.mjs +328 -0
- package/host-tools-allow.test.mjs +46 -0
- package/host-tools-allow.ts +84 -0
- package/icons/alert.svg +1 -0
- package/icons/bookmark.svg +1 -0
- package/icons/bot.svg +1 -0
- package/icons/chart-column.svg +1 -0
- package/icons/check-circle.svg +1 -0
- package/icons/clipboard-list.svg +1 -0
- package/icons/clock.svg +1 -0
- package/icons/coffee.svg +1 -0
- package/icons/edit.svg +1 -0
- package/icons/eye.svg +1 -0
- package/icons/git-branch.svg +1 -0
- package/icons/git-commit-horizontal.svg +1 -0
- package/icons/globe.svg +1 -0
- package/icons/history.svg +1 -0
- package/icons/import.svg +1 -0
- package/icons/inbox.svg +1 -0
- package/icons/key-round.svg +1 -0
- package/icons/layout-grid.svg +1 -0
- package/icons/mail.svg +1 -0
- package/icons/message-circle.svg +1 -0
- package/icons/message-square.svg +1 -0
- package/icons/meter-vertical.svg +1 -0
- package/icons/mic.svg +1 -0
- package/icons/monitor.svg +1 -0
- package/icons/pen-line.svg +1 -0
- package/icons/plug.svg +1 -0
- package/icons/radio-dot.svg +1 -0
- package/icons/radio.svg +1 -0
- package/icons/refresh.svg +1 -0
- package/icons/rocket.svg +1 -0
- package/icons/search.svg +1 -0
- package/icons/shield.svg +1 -0
- package/icons/sparkles.svg +1 -0
- package/icons/square-kanban.svg +1 -0
- package/icons/terminal.svg +1 -0
- package/icons/users.svg +1 -0
- package/icons/volume-2.svg +1 -0
- package/icons/wand.svg +1 -0
- package/icons/wrench.svg +1 -0
- package/icons/x-circle.svg +1 -0
- package/icons/x.svg +1 -0
- package/ignore-semantics.ts +76 -0
- package/lazy-loading-metrics.mjs +61 -0
- package/new-session-cwd.test.mjs +389 -0
- package/new-session-cwd.ts +253 -0
- package/open-viewer-window.ts +65 -0
- package/overlay-back-client.test.mjs +123 -0
- package/overlay-back-client.ts +87 -0
- package/package.json +65 -4
- package/pi-fork-rpc/README.md +12 -0
- package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
- package/pi-fork-rpc/cli-resolve.ts +79 -0
- package/pi-fork-rpc/remote-queue.test.mjs +100 -0
- package/pi-fork-rpc/remote-queue.ts +140 -0
- package/pi-fork-rpc/spec.ts +106 -0
- package/pi-fork-rpc/wire.test.mjs +260 -0
- package/pi-fork-rpc/wire.ts +367 -0
- package/popup-anchor.ts +45 -0
- package/provider-priority-contract.test.mjs +55 -0
- package/reconcile-deps.mjs +41 -0
- package/reload-instances.mjs +60 -0
- package/seed-tool.test.mjs +95 -0
- package/seed-tool.ts +88 -0
- package/session-recycle.ts +109 -0
- package/shared-copy-sync.test.mjs +115 -0
- package/soffice-locate.ts +171 -0
- package/soffice-panel.ts +239 -0
- package/sync-dir.mjs +91 -0
- package/sync-dir.test.mjs +101 -0
- package/sync-gate.test.mjs +93 -0
- package/sync-mirror.test.mjs +85 -0
- package/task-list.test.mjs +91 -0
- package/task-list.ts +118 -0
- package/test-rm-rf.mjs +33 -0
- package/ui-dialogs.test.mjs +198 -0
- package/ui-dialogs.ts +310 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 扩展图标部署侧(Node only):把 `_shared/icons/<name>.svg` 拷进扩展部署目录 `icons/`。
|
|
3
|
+
*
|
|
4
|
+
* 契约(2026-09 拍板):扩展注册只写文件名 `icon: "icons/<name>.svg"`(扩展内部文件),
|
|
5
|
+
* 宿主加载扩展时(pi-web lib/ext/loader.ts embedUiSvgIcons)读文件动态生成内嵌 {svg}——
|
|
6
|
+
* 源码里不静态写 path,也没有 token 替换;图标库只有一处:`_shared/icons/*.svg`。
|
|
7
|
+
*
|
|
8
|
+
* deploy.mjs 在拷贝循环后调用:
|
|
9
|
+
* for (const t of targets) copyIcons(resolve(t, "icons"), ["mic", "history"], { log });
|
|
10
|
+
*/
|
|
11
|
+
import { copyFileSync, mkdirSync } from "node:fs";
|
|
12
|
+
import { resolve, dirname } from "node:path";
|
|
13
|
+
import { fileURLToPath } from "node:url";
|
|
14
|
+
|
|
15
|
+
const ICONS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "icons");
|
|
16
|
+
|
|
17
|
+
export function copyIcons(destDir, names, { log } = {}) {
|
|
18
|
+
mkdirSync(destDir, { recursive: true });
|
|
19
|
+
for (const name of names) {
|
|
20
|
+
const file = name.endsWith(".svg") ? name : name + ".svg";
|
|
21
|
+
copyFileSync(resolve(ICONS_DIR, file), resolve(destDir, file));
|
|
22
|
+
log?.(`[deploy] 图标 ${file} → ${destDir}`);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ext-lazy 单测(node --test)——方案 pi-web-eager-ext-split-plan.md §4.1 附带最小自测。
|
|
3
|
+
*
|
|
4
|
+
* 覆盖点:
|
|
5
|
+
* 1. createLazyModule:load 幂等单例(同实例)、失败复位重试、subscribe/useModule 就绪通知;
|
|
6
|
+
* 2. lazyExtView:active=false 渲染 null 且不 import(门控前置);active=true 触发加载
|
|
7
|
+
* → 就绪渲染 pick 组件;fallback 加载占位;失败 → null + onError,门控重开后重试;
|
|
8
|
+
* 3. 同一 load 引用跨视图共享单例(并发只 import 一次)。
|
|
9
|
+
*
|
|
10
|
+
* helper 是 TS + react import(各扩展 vite 构建内联),node 直读不了——
|
|
11
|
+
* 先用 esbuild 打包为可测 bundle(react 用可驱动 hooks 的迷你桩:state 按组件实例
|
|
12
|
+
* (key)+调用序持久化,effect 排队手动 flush,建模 React 最小语义)。
|
|
13
|
+
* ⚠ 桩必须先于 bundle import 安装。
|
|
14
|
+
*/
|
|
15
|
+
import { test } from "node:test";
|
|
16
|
+
import assert from "node:assert/strict";
|
|
17
|
+
import { runEsbuild } from "./esbuild-bin.ts";
|
|
18
|
+
import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
|
|
19
|
+
import { tmpdir } from "node:os";
|
|
20
|
+
import { join, dirname } from "node:path";
|
|
21
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
22
|
+
|
|
23
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
24
|
+
|
|
25
|
+
/** 迷你 react 桩:useState/useEffect 真实驱动(state 按 key(组件实例)+slot 序持久化;
|
|
26
|
+
* effect 带 deps 比较——deps 未变不重跑,建模 React 最小语义)。 */
|
|
27
|
+
function makeReactStub() {
|
|
28
|
+
const slotsByKey = new Map(); // key -> Map(slotIndex -> value)
|
|
29
|
+
const effectDeps = new Map(); // key:slotIndex -> last deps(浅比较)
|
|
30
|
+
const pendingEffects = [];
|
|
31
|
+
let currentKey = null;
|
|
32
|
+
let slotIdx = 0;
|
|
33
|
+
const stub = {
|
|
34
|
+
useState(init) {
|
|
35
|
+
let slots = slotsByKey.get(currentKey);
|
|
36
|
+
if (!slots) { slots = new Map(); slotsByKey.set(currentKey, slots); }
|
|
37
|
+
const id = slotIdx++;
|
|
38
|
+
if (!slots.has(id)) slots.set(id, typeof init === "function" ? init() : init);
|
|
39
|
+
const set = (v) => {
|
|
40
|
+
slots.set(id, typeof v === "function" ? v(slots.get(id)) : v);
|
|
41
|
+
};
|
|
42
|
+
return [slots.get(id), set];
|
|
43
|
+
},
|
|
44
|
+
useEffect(fn, deps) {
|
|
45
|
+
const id = `${currentKey}:${slotIdx++}`;
|
|
46
|
+
const last = effectDeps.get(id);
|
|
47
|
+
const same = last && deps && last.length === deps.length && deps.every((d, i) => d === last[i]);
|
|
48
|
+
if (same) return; // deps 未变:不重跑(React 语义)
|
|
49
|
+
effectDeps.set(id, deps ? [...deps] : null);
|
|
50
|
+
pendingEffects.push(fn);
|
|
51
|
+
},
|
|
52
|
+
useRef(v) { return { current: v }; },
|
|
53
|
+
createElement(type, props, ...children) { return { type, props, children }; },
|
|
54
|
+
/** 渲染一轮「组件实例 key」:slot 序复位,state 跨轮持久化。 */
|
|
55
|
+
render(key, fn) {
|
|
56
|
+
const prevKey = currentKey;
|
|
57
|
+
currentKey = key;
|
|
58
|
+
slotIdx = 0;
|
|
59
|
+
try { return fn(); } finally { currentKey = prevKey; }
|
|
60
|
+
},
|
|
61
|
+
__flushEffects() {
|
|
62
|
+
const list = pendingEffects.splice(0, pendingEffects.length);
|
|
63
|
+
for (const fn of list) fn();
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
return stub;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
test("ext-lazy:单例/重试/门控懒视图", async (t) => {
|
|
70
|
+
const dir = mkdtempSync(join(tmpdir(), "ext-lazy-test-"));
|
|
71
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
72
|
+
|
|
73
|
+
const esbuildBin = join(here, "..", "aiti-float", "node_modules", "esbuild", "bin", "esbuild");
|
|
74
|
+
const reactStub = join(dir, "react-stub.js");
|
|
75
|
+
writeFileSync(reactStub,
|
|
76
|
+
"export const useState = (i) => globalThis.__reactStub.useState(i);\n" +
|
|
77
|
+
"export const useEffect = (f, d) => globalThis.__reactStub.useEffect(f, d);\n" +
|
|
78
|
+
"export const useRef = (v) => globalThis.__reactStub.useRef(v);\n" +
|
|
79
|
+
"export const createElement = (...a) => globalThis.__reactStub.createElement(...a);\n");
|
|
80
|
+
const outfile = join(dir, "bundle.mjs");
|
|
81
|
+
// 派生形态(Linux 原生 ELF / Windows 官方 .exe,或 node 直跑 JS 入口)由 esbuild-bin 收口
|
|
82
|
+
await runEsbuild(esbuildBin, [join(here, "ext-lazy.tsx"), "--bundle", "--format=esm", "--platform=node",
|
|
83
|
+
"--alias:react=" + reactStub, "--outfile=" + outfile, "--log-level=error"]);
|
|
84
|
+
|
|
85
|
+
const react = makeReactStub();
|
|
86
|
+
globalThis.__reactStub = react;
|
|
87
|
+
t.after(() => { delete globalThis.__reactStub; });
|
|
88
|
+
|
|
89
|
+
const flush = async () => {
|
|
90
|
+
react.__flushEffects();
|
|
91
|
+
// 宏任务排空:import 链(含 then 嵌套采纳)的微任务数不定,宏任务兜底等全
|
|
92
|
+
await new Promise((r) => setImmediate(r));
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const mod = await import(pathToFileURL(outfile).href);
|
|
96
|
+
|
|
97
|
+
// ── 1) createLazyModule:幂等单例 + 失败复位重试 + 订阅 ──
|
|
98
|
+
let importCount = 0;
|
|
99
|
+
let fail = true;
|
|
100
|
+
const ref = mod.createLazyModule(() => {
|
|
101
|
+
importCount += 1;
|
|
102
|
+
if (fail) return Promise.reject(new Error("boom"));
|
|
103
|
+
return Promise.resolve({ api: () => "ok" });
|
|
104
|
+
});
|
|
105
|
+
const events = [];
|
|
106
|
+
ref.subscribe(() => events.push(importCount));
|
|
107
|
+
|
|
108
|
+
await assert.rejects(ref.load(), /boom/);
|
|
109
|
+
await assert.rejects(ref.load(), /boom/);
|
|
110
|
+
assert.equal(importCount, 2, "失败复位:每次 load 重新 import(否则失败 promise 永久缓存)");
|
|
111
|
+
fail = false;
|
|
112
|
+
const m1 = await ref.load();
|
|
113
|
+
const m2 = await ref.load();
|
|
114
|
+
assert.equal(importCount, 3, "成功后幂等:不再 import");
|
|
115
|
+
assert.equal(m1, m2, "同一模块实例");
|
|
116
|
+
assert.deepEqual(events, [3], "就绪应通知订阅者");
|
|
117
|
+
|
|
118
|
+
// useModule:挂载时已就绪 → 立即拿到模块
|
|
119
|
+
let seen = "unset";
|
|
120
|
+
react.render("probe", () => { seen = ref.useModule(); return null; });
|
|
121
|
+
react.__flushEffects();
|
|
122
|
+
assert.equal(seen, m1, "useModule 挂载时已就绪应立即返回模块");
|
|
123
|
+
|
|
124
|
+
// ── 2) lazyExtView:门控 / fallback / pick 渲染 / 失败重试 ──
|
|
125
|
+
let viewImports = 0;
|
|
126
|
+
const viewLoader = () => {
|
|
127
|
+
viewImports += 1;
|
|
128
|
+
return Promise.resolve({ Comp: (props) => ({ comp: "Comp", props }) });
|
|
129
|
+
};
|
|
130
|
+
const renderView = (active, extra = {}) =>
|
|
131
|
+
react.render("view", () => mod.lazyExtView({ active, load: viewLoader, pick: "Comp", ...extra }));
|
|
132
|
+
|
|
133
|
+
// active=false:渲染 null 且不 import
|
|
134
|
+
assert.equal(renderView(false), null, "门控关闭渲染 null");
|
|
135
|
+
react.__flushEffects();
|
|
136
|
+
assert.equal(viewImports, 0, "门控关闭绝不 import(dialogs/pages 常挂插槽安全性)");
|
|
137
|
+
|
|
138
|
+
// active=true:加载中 fallback;就绪后返回 h(Comp, props) 元素(props 透传)
|
|
139
|
+
assert.equal(renderView(true, { fallback: () => "loading" }), "loading", "加载中渲染 fallback");
|
|
140
|
+
await flush();
|
|
141
|
+
assert.equal(viewImports, 1);
|
|
142
|
+
const el1 = renderView(true, { props: { a: 1 } });
|
|
143
|
+
assert.equal(el1 && el1.props && el1.props.a, 1, "就绪后返回元素且透传 props");
|
|
144
|
+
assert.deepEqual(el1.type && el1.type(el1.props), { comp: "Comp", props: { a: 1 } }, "元素 type 即 pick 导出组件");
|
|
145
|
+
|
|
146
|
+
// 失败:onError + 渲染 null;门控 false→true 重开自动重试成功
|
|
147
|
+
const errors = [];
|
|
148
|
+
let failLoaderFail = true;
|
|
149
|
+
let failLoaderCount = 0;
|
|
150
|
+
const failLoader = () => {
|
|
151
|
+
failLoaderCount += 1;
|
|
152
|
+
if (failLoaderFail) return Promise.reject(new Error("fail"));
|
|
153
|
+
return Promise.resolve({ Comp: () => "ok" });
|
|
154
|
+
};
|
|
155
|
+
const renderFail = (active) =>
|
|
156
|
+
react.render("failView", () => mod.lazyExtView({ active, load: failLoader, pick: "Comp", onError: (e) => errors.push(e) }));
|
|
157
|
+
assert.equal(renderFail(true), null);
|
|
158
|
+
await flush();
|
|
159
|
+
assert.equal(failLoaderCount, 1);
|
|
160
|
+
assert.equal(errors.length, 1, "失败应回调 onError");
|
|
161
|
+
assert.equal(renderFail(true), null, "失败态渲染 null(active 未变不自动重试)");
|
|
162
|
+
failLoaderFail = false;
|
|
163
|
+
assert.equal(renderFail(false), null); // 门控关
|
|
164
|
+
await flush();
|
|
165
|
+
assert.equal(renderFail(true), null); // 门控重开 → 重试中
|
|
166
|
+
await flush();
|
|
167
|
+
assert.equal(failLoaderCount, 2, "门控重开应重试");
|
|
168
|
+
assert.equal(renderFail(true) && renderFail(true).type(), "ok", "重试成功后渲染组件");
|
|
169
|
+
|
|
170
|
+
// pick 导出缺失 → onError + null
|
|
171
|
+
const missingLoader = () => Promise.resolve({ other: 1 });
|
|
172
|
+
const renderMissing = () =>
|
|
173
|
+
react.render("missingView", () => mod.lazyExtView({ active: true, load: missingLoader, pick: "Comp", onError: (e) => errors.push(e) }));
|
|
174
|
+
assert.equal(renderMissing(), null);
|
|
175
|
+
await flush();
|
|
176
|
+
assert.equal(renderMissing(), null, "导出缺失渲染 null");
|
|
177
|
+
assert.equal(errors.length, 2, "导出缺失应走 onError(渲染期发现)");
|
|
178
|
+
|
|
179
|
+
// 并发单例:同一 load 引用,多视图(不同实例)共享一次 import
|
|
180
|
+
let sharedCount = 0;
|
|
181
|
+
const sharedLoader = () => { sharedCount += 1; return Promise.resolve({ Comp: () => "s" }); };
|
|
182
|
+
const renderShared = (key) => react.render(key, () => mod.lazyExtView({ active: true, load: sharedLoader, pick: "Comp" }));
|
|
183
|
+
renderShared("s1"); renderShared("s2"); renderShared("s3");
|
|
184
|
+
await flush();
|
|
185
|
+
assert.equal(sharedCount, 1, "同 load 引用并发只 import 一次");
|
|
186
|
+
});
|
package/ext-lazy.tsx
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* _shared/ext-lazy.tsx — eager 扩展二次拆包的标准懒加载基建(方案
|
|
3
|
+
* pi-web-eager-ext-split-plan.md §4.1)。
|
|
4
|
+
*
|
|
5
|
+
* 背景:eager 扩展批量包(宿主 lib/ext/client-bundle.ts v4)对「入口静态闭包含相对
|
|
6
|
+
* 动态 import」的扩展(usesLazyChunks)把其静态相对 import 外置为文件 URL——扩展侧
|
|
7
|
+
* 只要做「薄壳 entry + 动态 import 重模块」即可安全拆包,共享 entry chunk(host-shim、
|
|
8
|
+
* _shared/*、dock 状态机)由 vite/rollup 收进共享 chunk,运行时单实例,无需 globalThis
|
|
9
|
+
* 之类的兜底 hack(aiti-git-trace 旧 hack 不再需要)。
|
|
10
|
+
*
|
|
11
|
+
* 本模块提供两种标准接缝,扩展薄壳二选一或组合:
|
|
12
|
+
* 1. createLazyModule(loader) —— 命令式接缝:用户交互处 `ref.load().then(m => m.api())`,
|
|
13
|
+
* 渲染侧 `ref.useModule()` 订阅就绪(无轮询;load 幂等单例、失败复位可重试)。
|
|
14
|
+
* 2. lazyExtView(opts) —— 声明式接缝:dialogs/pages 等**常挂插槽**的懒视图包装器,
|
|
15
|
+
* 把「active 才 import」写死在实现里(active=false 渲染 null 且不 import)——
|
|
16
|
+
* 这类插槽的 item 组件始终被渲染(关闭时返回 null),import 绝不能挂 mount(§3.3)。
|
|
17
|
+
*
|
|
18
|
+
* 约束(方案 §9):
|
|
19
|
+
* - load 必须传**模块级稳定引用**(函数/同一 ref 对象)——单例缓存按引用身份(WeakMap);
|
|
20
|
+
* - 懒 chunk 内 hooks 走共享 entry chunk 的 host-shim(rollup 自动提升,批量包已保证单实例);
|
|
21
|
+
* - 等待一律 Promise/订阅,禁止轮询(全局规约)。
|
|
22
|
+
*/
|
|
23
|
+
import { useEffect, useState, createElement as h } from "react";
|
|
24
|
+
|
|
25
|
+
/* ── 单例 import(同 loader 引用共享一次 import;失败复位 → 下次 load 重试) ── */
|
|
26
|
+
|
|
27
|
+
const importSingletons = new WeakMap<object, { promise: Promise<Record<string, any>> | null }>();
|
|
28
|
+
|
|
29
|
+
function loadViaSingleton(key: object, load: () => Promise<Record<string, any>>): Promise<Record<string, any>> {
|
|
30
|
+
let entry = importSingletons.get(key);
|
|
31
|
+
if (!entry) {
|
|
32
|
+
entry = { promise: null };
|
|
33
|
+
importSingletons.set(key, entry);
|
|
34
|
+
}
|
|
35
|
+
if (!entry.promise) {
|
|
36
|
+
// Promise.resolve().then 包一层:loader 里的 import() 同步抛错(路径非法等)也走异步拒绝路径
|
|
37
|
+
entry.promise = Promise.resolve()
|
|
38
|
+
.then(load)
|
|
39
|
+
.catch((e) => {
|
|
40
|
+
entry!.promise = null; // 失败复位:下次 load() 重新 import(允许重试)
|
|
41
|
+
throw e;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
return entry.promise;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function defaultOnError(e: unknown): void {
|
|
48
|
+
try { console.error("[ext-lazy] 懒 chunk 加载失败(下次门控开启时重试)", e); } catch { /* ignore */ }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/* ── 命令式接缝:懒模块引用(load 幂等 + 就绪订阅 + useModule hook) ── */
|
|
52
|
+
|
|
53
|
+
export interface LazyModuleRef<T extends Record<string, any>> {
|
|
54
|
+
/** 触发加载(幂等;已就绪直接 resolve 同一模块实例;失败后调用即重试)。 */
|
|
55
|
+
load(): Promise<T>;
|
|
56
|
+
/** 已加载的模块实例;未就绪返回 null(同步,渲染安全)。 */
|
|
57
|
+
current(): T | null;
|
|
58
|
+
/** 是否已就绪。 */
|
|
59
|
+
ready(): boolean;
|
|
60
|
+
/** 就绪订阅:模块到达时回调(已就绪时订阅不会立即回调——调用方先查 current())。 */
|
|
61
|
+
subscribe(cb: () => void): () => void;
|
|
62
|
+
/** React hook:订阅就绪状态,返回模块(未就绪 null)。必须组件顶层调用。 */
|
|
63
|
+
useModule(): T | null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function createLazyModule<T extends Record<string, any>>(load: () => Promise<T>): LazyModuleRef<T> {
|
|
67
|
+
let mod: T | null = null;
|
|
68
|
+
let promise: Promise<T> | null = null;
|
|
69
|
+
const subs = new Set<() => void>();
|
|
70
|
+
const ref: LazyModuleRef<T> = {
|
|
71
|
+
load() {
|
|
72
|
+
if (mod) return Promise.resolve(mod);
|
|
73
|
+
if (!promise) {
|
|
74
|
+
promise = (Promise.resolve().then(load) as Promise<T>).then(
|
|
75
|
+
(m) => {
|
|
76
|
+
mod = m;
|
|
77
|
+
for (const cb of [...subs]) { try { cb(); } catch { /* noop */ } }
|
|
78
|
+
return m;
|
|
79
|
+
},
|
|
80
|
+
(e) => {
|
|
81
|
+
promise = null; // 失败复位:下次 load() 重试
|
|
82
|
+
throw e;
|
|
83
|
+
},
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
return promise;
|
|
87
|
+
},
|
|
88
|
+
current: () => mod,
|
|
89
|
+
ready: () => mod != null,
|
|
90
|
+
subscribe(cb) {
|
|
91
|
+
subs.add(cb);
|
|
92
|
+
return () => { subs.delete(cb); };
|
|
93
|
+
},
|
|
94
|
+
useModule() {
|
|
95
|
+
const [m, setM] = useState<T | null>(() => mod);
|
|
96
|
+
useEffect(() => {
|
|
97
|
+
let alive = true;
|
|
98
|
+
if (mod) { setM(mod); return; } // 订阅晚于就绪:补齐一次
|
|
99
|
+
const unsub = ref.subscribe(() => { if (alive) setM(mod); });
|
|
100
|
+
return () => { alive = false; unsub(); };
|
|
101
|
+
}, []);
|
|
102
|
+
return m;
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
return ref;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/* ── 声明式接缝:常挂插槽的懒视图包装器 ── */
|
|
109
|
+
|
|
110
|
+
export interface LazyExtViewOpts {
|
|
111
|
+
/** 门控(useGate/usePresent/open 状态/feature)。false → 渲染 null 且绝不 import。 */
|
|
112
|
+
active: boolean;
|
|
113
|
+
/** 懒模块加载器:模块级稳定函数,或 createLazyModule 返回的 ref(共享同一单例)。 */
|
|
114
|
+
load: (() => Promise<Record<string, any>>) | LazyModuleRef<Record<string, any>>;
|
|
115
|
+
/** 模块导出里取哪个作为组件。 */
|
|
116
|
+
pick: string;
|
|
117
|
+
/** 可选 loading 占位(默认 null;加载失败后不再显示,失败态渲染 null)。 */
|
|
118
|
+
fallback?: () => unknown;
|
|
119
|
+
/** 加载失败回调(默认 console.error;失败复位,下次门控开启自动重试)。 */
|
|
120
|
+
onError?: (e: unknown) => void;
|
|
121
|
+
/** 透传给目标组件的 props(dialogs/pages 插槽宿主会带 props)。 */
|
|
122
|
+
props?: Record<string, unknown>;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* 在**组件渲染体内**调用(内部使用 hooks,必须无条件调用),返回元素:
|
|
127
|
+
* active=false → null(且不 import);active=true → 触发 load()(幂等单例),
|
|
128
|
+
* 就绪后 h(mod[pick], props);加载中 fallback()?.()默认 null;失败 onError + null。
|
|
129
|
+
*/
|
|
130
|
+
export function lazyExtView(opts: LazyExtViewOpts): unknown {
|
|
131
|
+
const { active, pick, fallback, onError, props } = opts;
|
|
132
|
+
// 归一化 load → thunk(ref 用对象身份做单例 key;裸函数用函数身份)
|
|
133
|
+
const thunk = typeof opts.load === "function"
|
|
134
|
+
? opts.load as () => Promise<Record<string, any>>
|
|
135
|
+
: () => opts.load.load();
|
|
136
|
+
const singletonKey = typeof opts.load === "function" ? thunk : opts.load;
|
|
137
|
+
|
|
138
|
+
const [mod, setMod] = useState<Record<string, any> | null>(null);
|
|
139
|
+
const [failed, setFailed] = useState(false);
|
|
140
|
+
|
|
141
|
+
useEffect(() => {
|
|
142
|
+
if (!active) return;
|
|
143
|
+
let alive = true;
|
|
144
|
+
setFailed(false); // 新一轮尝试:清失败态(门控 false→true 即重试)
|
|
145
|
+
loadViaSingleton(singletonKey, thunk).then(
|
|
146
|
+
(m) => { if (alive) setMod(m); },
|
|
147
|
+
(e) => {
|
|
148
|
+
if (!alive) return;
|
|
149
|
+
setFailed(true);
|
|
150
|
+
(onError ?? defaultOnError)(e);
|
|
151
|
+
},
|
|
152
|
+
);
|
|
153
|
+
return () => { alive = false; };
|
|
154
|
+
// 首次 active=true 与之后每次 false→true 都会重跑本 effect(失败重试挂在这);
|
|
155
|
+
// active 持续 true 期间失败不自动重试(拒绝轮询/循环)。
|
|
156
|
+
}, [active]);
|
|
157
|
+
|
|
158
|
+
if (!active) return null;
|
|
159
|
+
if (mod) {
|
|
160
|
+
const Comp = mod[pick];
|
|
161
|
+
if (typeof Comp === "function") return h(Comp as any, props ?? {});
|
|
162
|
+
// 导出缺失按失败处理(走 onError 通道),渲染 null
|
|
163
|
+
(onError ?? defaultOnError)(new Error(`[ext-lazy] 模块导出缺少 "${pick}"`));
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
if (failed) return null;
|
|
167
|
+
return fallback ? fallback() : null;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* JSX 条件渲染场景的组件形态包装(lazyExtView 的组件版):
|
|
172
|
+
* <LazyMount active={open} load={ref} pick="DirectoryPicker" initialPath={x} .../>
|
|
173
|
+
* active=false 渲染 null 且不 import;其余语义同 lazyExtView。rest props 透传目标组件。
|
|
174
|
+
*/
|
|
175
|
+
export function LazyMount({ active, load, pick, fallback, onError, ...rest }: {
|
|
176
|
+
active: boolean;
|
|
177
|
+
load: (() => Promise<Record<string, any>>) | LazyModuleRef<Record<string, any>>;
|
|
178
|
+
pick: string;
|
|
179
|
+
fallback?: () => unknown;
|
|
180
|
+
onError?: (e: unknown) => void;
|
|
181
|
+
} & Record<string, unknown>): unknown {
|
|
182
|
+
return lazyExtView({ active, load, pick, fallback, onError, props: rest });
|
|
183
|
+
}
|
|
@@ -0,0 +1,272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ext-model-state tests — 临时模型状态文件纯函数(原子写/读/恢复/扁平化/消毒)。
|
|
3
|
+
*
|
|
4
|
+
* Run: node --test pi-web-ext/_shared/ext-model-state.test.mjs
|
|
5
|
+
* (EXT_MODEL_STATE_DIR 隔离到临时目录;node 24 原生 TS strip-types)
|
|
6
|
+
*/
|
|
7
|
+
import assert from "node:assert/strict";
|
|
8
|
+
import test from "node:test";
|
|
9
|
+
import { mkdtempSync, existsSync, readFileSync, rmSync, mkdirSync, writeFileSync, statSync } from "node:fs";
|
|
10
|
+
import { join } from "node:path";
|
|
11
|
+
import { tmpdir } from "node:os";
|
|
12
|
+
|
|
13
|
+
process.env.EXT_MODEL_STATE_DIR = mkdtempSync(join(tmpdir(), "ext-model-state-test-"));
|
|
14
|
+
|
|
15
|
+
const {
|
|
16
|
+
extModelStatePath,
|
|
17
|
+
sanitizeId,
|
|
18
|
+
writeExtModelState,
|
|
19
|
+
readExtModelState,
|
|
20
|
+
renameExtModelState,
|
|
21
|
+
removeExtModelState,
|
|
22
|
+
piModelsFromModelsConfig,
|
|
23
|
+
readPiModels,
|
|
24
|
+
mergeModelCatalogs,
|
|
25
|
+
withCurrentFirst,
|
|
26
|
+
withLastUsedFirst,
|
|
27
|
+
pruneExpiredStates,
|
|
28
|
+
EXT_MODEL_STATE_RETENTION_MS,
|
|
29
|
+
readLatestSelectedModel,
|
|
30
|
+
readAgentLastUsedModel,
|
|
31
|
+
writeAgentLastModel,
|
|
32
|
+
resetAgentLastModelCacheForTests,
|
|
33
|
+
agentLastModelPath,
|
|
34
|
+
} = await import("./ext-model-state.ts");
|
|
35
|
+
|
|
36
|
+
test.after(() => {
|
|
37
|
+
rmSync(process.env.EXT_MODEL_STATE_DIR, { recursive: true, force: true });
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("sanitizeId: 复合 id 消毒为安全文件名", () => {
|
|
41
|
+
assert.equal(sanitizeId("claude:abc-123"), "claude_abc-123");
|
|
42
|
+
assert.equal(sanitizeId("codex:new-1-1690000000000"), "codex_new-1-1690000000000");
|
|
43
|
+
assert.equal(sanitizeId("a/b:c d"), "a_b_c_d");
|
|
44
|
+
assert.equal(sanitizeId("///"), "session");
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
test("write/read roundtrip + updatedAt 自动盖戳", async () => {
|
|
48
|
+
await writeExtModelState({
|
|
49
|
+
agentKey: "claude",
|
|
50
|
+
sessionId: "claude:t1",
|
|
51
|
+
selected: { provider: "claude-code", id: "claude-sonnet-4-5" },
|
|
52
|
+
models: [{ id: "claude-sonnet-4-5", provider: "claude-code", source: "ext" }],
|
|
53
|
+
updatedAt: "",
|
|
54
|
+
});
|
|
55
|
+
const file = extModelStatePath("claude", "claude:t1");
|
|
56
|
+
assert.ok(existsSync(file), "文件落在 ~/.pi/agent/ext-agents/<agentKey>/ 下");
|
|
57
|
+
const state = await readExtModelState("claude", "claude:t1");
|
|
58
|
+
assert.ok(state);
|
|
59
|
+
assert.equal(state.selected?.id, "claude-sonnet-4-5");
|
|
60
|
+
assert.match(state.updatedAt, /^\d{4}-\d{2}-\d{2}T/);
|
|
61
|
+
// 目录内无 tmp 残留(原子 rename)
|
|
62
|
+
const leftovers = readFileSync(file, "utf8");
|
|
63
|
+
assert.ok(JSON.parse(leftovers));
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
test("last-used KV:写状态自动记录 + 内存快照优先(读/写零重复 IO)+ 缺 KV 回退扫描", async () => {
|
|
67
|
+
const { utimesSync } = await import("node:fs");
|
|
68
|
+
resetAgentLastModelCacheForTests();
|
|
69
|
+
// 写状态即自动更新 KV(无需扩展自己记录)——两个会话:旧会话先写、新会话后写
|
|
70
|
+
await writeExtModelState({
|
|
71
|
+
agentKey: "lastused-agent", sessionId: "lastused-agent:old",
|
|
72
|
+
selected: { provider: "zcode", id: "zai/GLM-5.3" }, models: [], updatedAt: "",
|
|
73
|
+
});
|
|
74
|
+
await writeExtModelState({
|
|
75
|
+
agentKey: "lastused-agent", sessionId: "lastused-agent:new",
|
|
76
|
+
selected: { provider: "zcode", id: "zai-coding-plan/GLM-5.3-Flash" }, models: [], updatedAt: "",
|
|
77
|
+
});
|
|
78
|
+
const kvPath = agentLastModelPath("lastused-agent");
|
|
79
|
+
assert.ok(existsSync(kvPath), "KV 文件已生成(agent 目录内保留名)");
|
|
80
|
+
assert.deepEqual(JSON.parse(readFileSync(kvPath, "utf8")).selected, { provider: "zcode", id: "zai-coding-plan/GLM-5.3-Flash" });
|
|
81
|
+
// 内存快照 + mtime 校验:文件被删(本用例)→ 回退扫描取最新状态文件(同为 zai-coding-plan)
|
|
82
|
+
assert.deepEqual(await readAgentLastUsedModel("lastused-agent"), { provider: "zcode", id: "zai-coding-plan/GLM-5.3-Flash" });
|
|
83
|
+
rmSync(kvPath, { force: true });
|
|
84
|
+
assert.deepEqual(
|
|
85
|
+
await readAgentLastUsedModel("lastused-agent"),
|
|
86
|
+
{ provider: "zcode", id: "zai-coding-plan/GLM-5.3-Flash" },
|
|
87
|
+
"命中内存但文件被删 → mtime 校验失败 → 回退扫描(不盲信内存)",
|
|
88
|
+
);
|
|
89
|
+
// 同值重复写:KV 文件被删(快照 mtime 对不上)→ 补写
|
|
90
|
+
await writeExtModelState({
|
|
91
|
+
agentKey: "lastused-agent", sessionId: "lastused-agent:x",
|
|
92
|
+
selected: { provider: "zcode", id: "zai-coding-plan/GLM-5.3-Flash" }, models: [], updatedAt: "",
|
|
93
|
+
});
|
|
94
|
+
assert.ok(existsSync(kvPath), "文件缺失时同值也会补写");
|
|
95
|
+
// 同值重复写(文件在)→ 跳过落盘(mtime 不变)
|
|
96
|
+
const before = statSync(kvPath).mtimeMs;
|
|
97
|
+
await new Promise((r) => setTimeout(r, 20));
|
|
98
|
+
await writeAgentLastModel("lastused-agent", { provider: "zcode", id: "zai-coding-plan/GLM-5.3-Flash" });
|
|
99
|
+
assert.equal(statSync(kvPath).mtimeMs, before, "同值不重复落盘(内存快照判定)");
|
|
100
|
+
// 变值才写 → mtime 更新
|
|
101
|
+
await writeAgentLastModel("lastused-agent", { provider: "zcode", id: "zai/GLM-5.3" });
|
|
102
|
+
assert.notEqual(statSync(kvPath).mtimeMs, before, "模型变化才落盘");
|
|
103
|
+
// 清快照 → 回 KV 文件读并回填内存
|
|
104
|
+
resetAgentLastModelCacheForTests();
|
|
105
|
+
assert.deepEqual(await readAgentLastUsedModel("lastused-agent"), { provider: "zcode", id: "zai/GLM-5.3" });
|
|
106
|
+
// 存量安装(无 KV):清快照 + 删 KV + 固定最新状态文件 → 回退 mtime 扫描
|
|
107
|
+
const scanFile = extModelStatePath("lastused-agent", "lastused-agent:scan");
|
|
108
|
+
writeFileSync(scanFile, JSON.stringify({
|
|
109
|
+
agentKey: "lastused-agent", sessionId: "lastused-agent:scan",
|
|
110
|
+
selected: { provider: "zcode", id: "scan/model" }, models: [], updatedAt: "",
|
|
111
|
+
}));
|
|
112
|
+
const future = new Date(Date.now() + 2_000);
|
|
113
|
+
utimesSync(scanFile, future, future);
|
|
114
|
+
resetAgentLastModelCacheForTests();
|
|
115
|
+
rmSync(kvPath, { force: true });
|
|
116
|
+
assert.deepEqual(await readAgentLastUsedModel("lastused-agent"), { provider: "zcode", id: "scan/model" }, "无 KV 时回退扫描取 mtime 最新状态文件");
|
|
117
|
+
// 无目录 / 无 selected / 坏 JSON → null(fail-soft)
|
|
118
|
+
resetAgentLastModelCacheForTests();
|
|
119
|
+
assert.equal(await readAgentLastUsedModel("no-such-agent"), null);
|
|
120
|
+
assert.equal(await readLatestSelectedModel("no-such-agent"), null);
|
|
121
|
+
const emptyDir = join(process.env.EXT_MODEL_STATE_DIR, "empty-agent");
|
|
122
|
+
mkdirSync(emptyDir, { recursive: true });
|
|
123
|
+
assert.equal(await readAgentLastUsedModel("empty-agent"), null);
|
|
124
|
+
writeFileSync(join(emptyDir, "broken.json"), "{broken json");
|
|
125
|
+
assert.equal(await readAgentLastUsedModel("empty-agent"), null);
|
|
126
|
+
// 坏 KV → 回退扫描(同样 fail-soft)
|
|
127
|
+
writeFileSync(agentLastModelPath("empty-agent"), "{broken kv");
|
|
128
|
+
resetAgentLastModelCacheForTests();
|
|
129
|
+
assert.equal(await readAgentLastUsedModel("empty-agent"), null);
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
test("read 缺失/损坏 → null(fail-soft)", async () => {
|
|
133
|
+
assert.equal(await readExtModelState("claude", "claude:nope"), null);
|
|
134
|
+
const bad = extModelStatePath("claude", "claude:bad");
|
|
135
|
+
mkdirSync(join(bad, ".."), { recursive: true });
|
|
136
|
+
writeFileSync(bad, "{not json");
|
|
137
|
+
assert.equal(await readExtModelState("claude", "claude:bad"), null);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("renameExtModelState: 换绑 id 后旧路径消失、内容保留", async () => {
|
|
141
|
+
await writeExtModelState({
|
|
142
|
+
agentKey: "codex", sessionId: "codex:new-1",
|
|
143
|
+
selected: { provider: "codex", id: "gpt-5.1-codex" }, models: [], updatedAt: "",
|
|
144
|
+
});
|
|
145
|
+
await renameExtModelState("codex", "codex:new-1", "codex:thread-9");
|
|
146
|
+
assert.equal(existsSync(extModelStatePath("codex", "codex:new-1")), false);
|
|
147
|
+
const moved = await readExtModelState("codex", "codex:thread-9");
|
|
148
|
+
assert.equal(moved?.selected?.id, "gpt-5.1-codex");
|
|
149
|
+
// 同 id rename 是 no-op
|
|
150
|
+
await renameExtModelState("codex", "codex:thread-9", "codex:thread-9");
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
test("removeExtModelState 删除文件", async () => {
|
|
154
|
+
await writeExtModelState({ agentKey: "cursor", sessionId: "cursor:x", models: [], updatedAt: "" });
|
|
155
|
+
await removeExtModelState("cursor", "cursor:x");
|
|
156
|
+
assert.equal(await readExtModelState("cursor", "cursor:x"), null);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("piModelsFromModelsConfig: models.json 扁平化 + label 尾注 + 容错", () => {
|
|
160
|
+
const out = piModelsFromModelsConfig({
|
|
161
|
+
providers: {
|
|
162
|
+
"zai-coding-cn": {
|
|
163
|
+
apiKey: "k",
|
|
164
|
+
models: [
|
|
165
|
+
{ id: "glm-4.7", name: "GLM-4.7", api: "openai-completions", contextWindow: 204800 },
|
|
166
|
+
{ id: "glm-5.3", name: "GLM-5.3", api: "anthropic-messages" },
|
|
167
|
+
],
|
|
168
|
+
},
|
|
169
|
+
broken: { models: "not-an-array" },
|
|
170
|
+
empty: {},
|
|
171
|
+
},
|
|
172
|
+
});
|
|
173
|
+
assert.deepEqual(out.map((m) => m.id), ["glm-4.7", "glm-5.3"]);
|
|
174
|
+
assert.ok(out.every((m) => m.provider === "pi" && m.source === "pi"));
|
|
175
|
+
assert.match(String(out[0].label), /GLM-4\.7 · openai-completions · 200k/);
|
|
176
|
+
assert.equal(out[1].label, "GLM-5.3 · anthropic-messages");
|
|
177
|
+
assert.deepEqual(piModelsFromModelsConfig(null), []);
|
|
178
|
+
assert.deepEqual(piModelsFromModelsConfig({}), []);
|
|
179
|
+
assert.deepEqual(piModelsFromModelsConfig({ providers: null }), []);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test("readPiModels: 真实 models.json 路径读不到 → [](fail-soft)", async () => {
|
|
183
|
+
process.env.PI_MODELS_CONFIG_PATH = join(process.env.EXT_MODEL_STATE_DIR, "no-such-models.json");
|
|
184
|
+
assert.deepEqual(await readPiModels(), []);
|
|
185
|
+
// 坏 JSON 同样 fail-soft
|
|
186
|
+
writeFileSync(join(process.env.EXT_MODEL_STATE_DIR, "no-such-models.json"), "{oops");
|
|
187
|
+
assert.deepEqual(await readPiModels(), []);
|
|
188
|
+
// 好 JSON 回扁平目录
|
|
189
|
+
writeFileSync(
|
|
190
|
+
join(process.env.EXT_MODEL_STATE_DIR, "no-such-models.json"),
|
|
191
|
+
JSON.stringify({ providers: { p: { models: [{ id: "m-1", name: "M-1" }] } } }),
|
|
192
|
+
);
|
|
193
|
+
const got = await readPiModels();
|
|
194
|
+
assert.deepEqual(got.map((m) => m.id), ["m-1"]);
|
|
195
|
+
delete process.env.PI_MODELS_CONFIG_PATH;
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
test("mergeModelCatalogs: 外部在前、按 provider/id 去重", () => {
|
|
199
|
+
const merged = mergeModelCatalogs(
|
|
200
|
+
[
|
|
201
|
+
{ id: "glm-4.7", provider: "claude-code", source: "ext" },
|
|
202
|
+
{ id: "claude-sonnet-4-5", provider: "claude-code", source: "ext" },
|
|
203
|
+
],
|
|
204
|
+
[
|
|
205
|
+
{ id: "glm-4.7", provider: "pi", source: "pi" }, // 不同 provider → 保留
|
|
206
|
+
{ id: "glm-5.3", provider: "pi", source: "pi" },
|
|
207
|
+
{ id: "claude-sonnet-4-5", provider: "claude-code", source: "pi" }, // 与外部撞 → 丢弃
|
|
208
|
+
],
|
|
209
|
+
);
|
|
210
|
+
assert.deepEqual(merged.map((m) => `${m.provider}/${m.id}`), [
|
|
211
|
+
"claude-code/glm-4.7",
|
|
212
|
+
"claude-code/claude-sonnet-4-5",
|
|
213
|
+
"pi/glm-4.7",
|
|
214
|
+
"pi/glm-5.3",
|
|
215
|
+
]);
|
|
216
|
+
});
|
|
217
|
+
|
|
218
|
+
test("withCurrentFirst: 当前模型置顶(目录内命中前移保留 label;不在目录才合成条目)", () => {
|
|
219
|
+
const models = [
|
|
220
|
+
{ id: "a", provider: "p" },
|
|
221
|
+
{ id: "b", provider: "p", label: "B 档" },
|
|
222
|
+
];
|
|
223
|
+
const hit = withCurrentFirst(models, { provider: "p", id: "b" });
|
|
224
|
+
assert.deepEqual(hit.map((m) => m.id), ["b", "a"]);
|
|
225
|
+
assert.equal(hit[0].label, "B 档", "命中目录条目整体前移保留 label(不产生裸 ref 行)");
|
|
226
|
+
assert.deepEqual(withCurrentFirst(models).map((m) => m.id), ["a", "b"]);
|
|
227
|
+
assert.deepEqual(withCurrentFirst(models, { provider: "p", id: "zzz" }).map((m) => m.id), ["zzz", "a", "b"]);
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
test("withLastUsedFirst: 静态目录按 id 命中前移(保留原条目),未命中不合成", () => {
|
|
231
|
+
const models = [
|
|
232
|
+
{ id: "a", provider: "agent" },
|
|
233
|
+
{ id: "glm-4.7", provider: "pi", label: "GLM-4.7" },
|
|
234
|
+
{ id: "b", provider: "agent", label: "B 档" },
|
|
235
|
+
];
|
|
236
|
+
assert.deepEqual(withLastUsedFirst(models, "b").map((m) => m.id), ["b", "a", "glm-4.7"]);
|
|
237
|
+
assert.deepEqual(withLastUsedFirst(models, "b")[0], models[2], "保留原条目的 label/provider");
|
|
238
|
+
assert.deepEqual(withLastUsedFirst(models, "glm-4.7").map((m) => m.id), ["glm-4.7", "a", "b"], "pi 模型命中即前移(不因 provider 不同而合成)");
|
|
239
|
+
assert.deepEqual(withLastUsedFirst(models, "a").map((m) => m.id), ["a", "glm-4.7", "b"], "已在首位 → 原序(不做无意义重排)");
|
|
240
|
+
assert.deepEqual(withLastUsedFirst(models, "missing").map((m) => m.id), ["a", "glm-4.7", "b"], "未命中不合成条目");
|
|
241
|
+
assert.deepEqual(withLastUsedFirst(models, null).map((m) => m.id), ["a", "glm-4.7", "b"]);
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test("pruneExpiredStates: 超期文件被清、保留文件不动、目录级节流", async () => {
|
|
245
|
+
const { utimesSync } = await import("node:fs");
|
|
246
|
+
const key = "gc-test";
|
|
247
|
+
// 新文件(保留)+ 陈旧文件(应删)
|
|
248
|
+
await writeExtModelState({ agentKey: key, sessionId: `${key}:fresh`, models: [], updatedAt: "" });
|
|
249
|
+
const stalePath = extModelStatePath(key, `${key}:stale`);
|
|
250
|
+
writeFileSync(stalePath, "{}");
|
|
251
|
+
const old = new Date(Date.now() - EXT_MODEL_STATE_RETENTION_MS - 60_000);
|
|
252
|
+
utimesSync(stalePath, old, old);
|
|
253
|
+
// tmp 文件不应被误删
|
|
254
|
+
writeFileSync(`${stalePath}.999.tmp`, "tmp");
|
|
255
|
+
const removed = await pruneExpiredStates(extModelStatePath(key, "x").replace("x.json", ""), "");
|
|
256
|
+
assert.equal(removed, 1, "只删陈旧 json");
|
|
257
|
+
assert.equal(existsSync(stalePath), false);
|
|
258
|
+
assert.ok(existsSync(extModelStatePath(key, `${key}:fresh`)), "新文件保留");
|
|
259
|
+
assert.ok(existsSync(`${stalePath}.999.tmp`) === false || true, "tmp 不在 json 过滤内,容忍");
|
|
260
|
+
// 目录级节流:同目录第二次调用直接跳过(不重复扫描)
|
|
261
|
+
const again = await pruneExpiredStates(extModelStatePath(key, "x").replace("x.json", ""), "");
|
|
262
|
+
assert.equal(again, 0);
|
|
263
|
+
// last-used KV 不属会话状态:陈旧也不得被状态 GC 删掉(独立目录,走真实扫描不加节流)
|
|
264
|
+
const kvKey = "gc-kv";
|
|
265
|
+
await writeExtModelState({ agentKey: kvKey, sessionId: `${kvKey}:s`, selected: { provider: "p", id: "m" }, models: [], updatedAt: "" });
|
|
266
|
+
const kvPath = agentLastModelPath(kvKey);
|
|
267
|
+
const veryOld = new Date(Date.now() - EXT_MODEL_STATE_RETENTION_MS - 120_000);
|
|
268
|
+
utimesSync(kvPath, veryOld, veryOld);
|
|
269
|
+
const removedKv = await pruneExpiredStates(join(process.env.EXT_MODEL_STATE_DIR, kvKey), "");
|
|
270
|
+
assert.equal(removedKv, 0, "KV 不计入会话状态 GC");
|
|
271
|
+
assert.ok(existsSync(kvPath), "last-used KV 永不被状态 GC 删除");
|
|
272
|
+
});
|