pi-web-ui 0.87.2 → 0.89.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +66 -1
  2. package/bin/pi-web-ui.mjs +463 -0
  3. package/dist/server/agent-service.js +419 -45
  4. package/dist/server/attachments.js +39 -0
  5. package/dist/server/client-state.js +22 -0
  6. package/dist/server/conversation-read-tool.js +325 -0
  7. package/dist/server/dsh/dsh-agent-service.js +32 -3
  8. package/dist/server/files-service.js +103 -0
  9. package/dist/server/host-metrics.js +59 -0
  10. package/dist/server/index.js +381 -8
  11. package/dist/server/model-admin.js +285 -36
  12. package/dist/server/plugin-facilities.js +115 -2
  13. package/dist/server/plugin-llm.js +129 -0
  14. package/dist/server/plugin-permissions.js +176 -0
  15. package/dist/server/plugin-schedule.js +211 -0
  16. package/dist/server/plugins.js +1005 -68
  17. package/dist/server/scheduler-tasks.js +405 -0
  18. package/dist/server/settings-service.js +8 -1
  19. package/dist/server/terminals.js +14 -1
  20. package/dist/server/tool-manager.js +6 -1
  21. package/dist/server/update-check.js +249 -19
  22. package/extensions/webui.ts +9 -2
  23. package/package.json +4 -2
  24. package/plugin-sdk/README.md +127 -0
  25. package/plugin-sdk/index.d.ts +454 -0
  26. package/plugin-sdk/index.mjs +545 -0
  27. package/plugin-sdk/package.json +9 -0
  28. package/plugins/catalog.json +11 -2
  29. package/web/dist/assets/TerminalPanel-BOUmN3uu.js +6 -0
  30. package/web/dist/assets/TerminalPanel-DOrYoP_4.css +32 -0
  31. package/web/dist/assets/index-3XU67qMh.js +376 -0
  32. package/web/dist/assets/index-B-gdvWtW.css +10 -0
  33. package/web/dist/index.html +2 -3
  34. package/web/dist/assets/index-CYuoen3I.js +0 -374
  35. package/web/dist/assets/index-F86qWlJy.css +0 -41
@@ -1,14 +1,17 @@
1
1
  /**
2
2
  * All-source update check: pi-web-ui itself, the installed pi core
3
3
  * (@earendil-works/pi-coding-agent — probed via `pi --version`, with a
4
- * vendored-copy fallback), plus the DIRECT pi extensions declared in
5
- * <agentDir>/npm/package.json (fallback: raw node_modules walk).
4
+ * vendored-copy fallback), the DIRECT pi extensions declared in
5
+ * <agentDir>/npm/package.json (fallback: raw node_modules walk), plus the
6
+ * git-source extensions declared in global/project settings.json (issue #178).
6
7
  * Pure logic lives here so it can be unit-tested with an injected fetcher
7
8
  * (and an injected pi-core probe); ClientSession only wires it to the wire
8
9
  * protocol.
9
10
  */
11
+ import { execFile } from "node:child_process";
10
12
  import { readdirSync, readFileSync, realpathSync, existsSync } from "node:fs";
11
13
  import { delimiter, dirname, join } from "node:path";
14
+ import { promisify } from "node:util";
12
15
  import { pick } from "./i18n.js";
13
16
  const PI_CORE_PACKAGE = "@earendil-works/pi-coding-agent";
14
17
  /** npm 官方源;用户在 <agentDir>/npm/.npmrc 里配了镜像/私有源时会被覆盖(issue #151)。 */
@@ -155,6 +158,203 @@ function readLocalPackage(dir) {
155
158
  return null;
156
159
  }
157
160
  }
161
+ // -- git-source extensions (issue #178) --------------------------------------
162
+ // The panel historically enumerated only npm direct deps, so `git:` entries in
163
+ // settings.json never appeared. pi core updates both (`updateConfiguredSources`
164
+ // buckets npmCandidates/gitCandidates), keyed by normalized `git:host/path`.
165
+ const execFileAsync = promisify(execFile);
166
+ /** Matches pi core NETWORK_TIMEOUT_MS so slow forges degrade the same way. */
167
+ const GIT_TIMEOUT_MS = 10_000;
168
+ function hasUnsafeGitPart(value, allowSlash) {
169
+ if (value.includes("\0") || value.includes("\\") || value.startsWith("/"))
170
+ return true;
171
+ if (!allowSlash && value.includes("/"))
172
+ return true;
173
+ if (value.split("/").includes(".."))
174
+ return true;
175
+ return false;
176
+ }
177
+ function normalizeGitRepo(host, path, ref) {
178
+ const cleanPath = path.replace(/\.git$/, "").replace(/^\/+|\/+$/g, "");
179
+ if (!host || !cleanPath || cleanPath.split("/").length < 2)
180
+ return null;
181
+ if (hasUnsafeGitPart(host, false) || hasUnsafeGitPart(cleanPath, true))
182
+ return null;
183
+ if (ref !== null && (ref === "" || ref.includes("\0")))
184
+ return null;
185
+ return {
186
+ host,
187
+ path: cleanPath,
188
+ ref,
189
+ shorthand: `${host}/${cleanPath}`,
190
+ identity: `git:${host}/${cleanPath}`,
191
+ };
192
+ }
193
+ /** Split `rest` (the part after the host) on the first `@` into path + ref. */
194
+ function splitGitRef(rest) {
195
+ const at = rest.indexOf("@");
196
+ if (at < 0)
197
+ return { path: rest, ref: null };
198
+ return { path: rest.slice(0, at), ref: rest.slice(at + 1) || null };
199
+ }
200
+ /**
201
+ * Parse a settings `packages` entry into a git source, or null when it is not
202
+ * one. Accepts the same shapes pi core does (`parseGitUrl`): `git:`-prefixed
203
+ * shorthand/URLs plus bare explicit protocol URLs. `npm:`/local entries yield
204
+ * null — they are handled by the npm enumeration, not here.
205
+ */
206
+ export function parseGitExtensionSource(entry) {
207
+ const trimmed = entry.trim();
208
+ if (!trimmed || trimmed.startsWith("npm:"))
209
+ return null;
210
+ const url = trimmed.startsWith("git:") ? trimmed.slice(4).trim() : trimmed;
211
+ if (!url)
212
+ return null;
213
+ // scp-like: git@host:owner/repo[.git][@ref]
214
+ const scp = url.match(/^git@([^:]+):(.+)$/);
215
+ if (scp) {
216
+ const { path, ref } = splitGitRef(scp[2]);
217
+ return normalizeGitRepo(scp[1], path, ref);
218
+ }
219
+ // Explicit protocol URLs (bare or git:-prefixed).
220
+ if (/^(https?|ssh|git):\/\//i.test(url)) {
221
+ let host;
222
+ let rest;
223
+ try {
224
+ const parsed = new URL(url);
225
+ host = parsed.hostname;
226
+ rest = parsed.pathname.replace(/^\/+/, "");
227
+ }
228
+ catch {
229
+ return null;
230
+ }
231
+ const { path, ref } = splitGitRef(rest);
232
+ return normalizeGitRepo(host, path, ref);
233
+ }
234
+ // Shorthand only with an explicit git: prefix (bare `a/b` is a local path).
235
+ if (!trimmed.startsWith("git:"))
236
+ return null;
237
+ const slash = url.indexOf("/");
238
+ if (slash < 0)
239
+ return null;
240
+ const host = url.slice(0, slash);
241
+ if (!host.includes(".") && host !== "localhost")
242
+ return null;
243
+ const { path, ref } = splitGitRef(url.slice(slash + 1));
244
+ return normalizeGitRepo(host, path, ref);
245
+ }
246
+ /**
247
+ * Total switch for the git-source check (issue #178 step 8). `0/false/no/off`
248
+ * disables it (large-monorepo escape hatch); unset or anything else enables.
249
+ */
250
+ export function isGitExtensionCheckEnabled(env = process.env) {
251
+ const v = (env.PI_WEB_GIT_EXTENSION_CHECK ?? "").trim().toLowerCase();
252
+ return v !== "0" && v !== "false" && v !== "no" && v !== "off";
253
+ }
254
+ function readSettingsPackagesFile(file) {
255
+ try {
256
+ const data = JSON.parse(readFileSync(file, "utf8"));
257
+ if (!data || typeof data !== "object" || !Array.isArray(data.packages))
258
+ return [];
259
+ return data.packages.filter((p) => typeof p === "string" || (p !== null && typeof p === "object"));
260
+ }
261
+ catch {
262
+ return [];
263
+ }
264
+ }
265
+ function readGitCloneNameVersion(installDir) {
266
+ try {
267
+ const pkg = JSON.parse(readFileSync(join(installDir, "package.json"), "utf8"));
268
+ if (!pkg.name || !pkg.version)
269
+ return null;
270
+ return { name: pkg.name, version: pkg.version };
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ }
276
+ /**
277
+ * Enumerate `git:` entries from global (<agentDir>/settings.json) plus project
278
+ * (<projectCwd>/.pi/settings.json) settings — the same two scopes pi core
279
+ * updates. Project wins on identity collision (mirrors core dedupePackages).
280
+ * Entries whose clone is missing are still listed (version `?`): checkAll
281
+ * reports them as per-item errors instead of silently dropping the row.
282
+ */
283
+ export function listGitExtensions(agentDir, projectCwd, env = process.env) {
284
+ if (!isGitExtensionCheckEnabled(env))
285
+ return [];
286
+ const scopes = [];
287
+ if (projectCwd)
288
+ scopes.push({ file: join(projectCwd, ".pi", "settings.json"), gitRoot: join(projectCwd, ".pi", "git") });
289
+ scopes.push({ file: join(agentDir, "settings.json"), gitRoot: join(agentDir, "git") });
290
+ const seen = new Set();
291
+ const out = [];
292
+ for (const { file, gitRoot } of scopes) {
293
+ for (const pkg of readSettingsPackagesFile(file)) {
294
+ const raw = typeof pkg === "string" ? pkg : typeof pkg.source === "string" ? pkg.source : null;
295
+ if (!raw)
296
+ continue;
297
+ const parsed = parseGitExtensionSource(raw);
298
+ if (!parsed || seen.has(parsed.identity))
299
+ continue;
300
+ seen.add(parsed.identity);
301
+ const installDir = join(gitRoot, parsed.host, ...parsed.path.split("/"));
302
+ const nv = readGitCloneNameVersion(installDir);
303
+ out.push({
304
+ name: nv?.name ?? parsed.shorthand,
305
+ version: nv?.version ?? "?",
306
+ kind: "git-extension",
307
+ source: parsed.shorthand,
308
+ installDir,
309
+ ref: parsed.ref,
310
+ });
311
+ }
312
+ }
313
+ return out.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
314
+ }
315
+ /** Display form for git rows: `<version> (<short sha>)`, sha-only when the
316
+ * clone has no readable package.json version (issue #178 step 5). */
317
+ export function formatGitVersion(version, sha) {
318
+ const short = sha.slice(0, 7);
319
+ return version && version !== "?" ? `${version} (${short})` : short;
320
+ }
321
+ async function runGit(args, cwd) {
322
+ const { stdout } = await execFileAsync("git", args, {
323
+ cwd,
324
+ timeout: GIT_TIMEOUT_MS,
325
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
326
+ });
327
+ return stdout.trim();
328
+ }
329
+ /**
330
+ * Compare a clone's HEAD against its remote (lightweight: `ls-remote` fetches
331
+ * refs only, no objects). Upstream branch wins when configured, else origin
332
+ * HEAD — the same order pi core `getRemoteGitHead` uses.
333
+ */
334
+ export async function defaultCheckGitExtension(installDir) {
335
+ const localSha = await runGit(["rev-parse", "HEAD"], installDir);
336
+ if (!/^[0-9a-f]{40}$/i.test(localSha))
337
+ throw new Error(`Bad local HEAD: ${localSha.slice(0, 20)}`);
338
+ let remoteSha = null;
339
+ try {
340
+ const upstream = await runGit(["rev-parse", "--abbrev-ref", "@{upstream}"], installDir);
341
+ const branch = upstream.match(/^origin\/(.+)$/)?.[1];
342
+ if (branch) {
343
+ const out = await runGit(["ls-remote", "origin", `refs/heads/${branch}`], installDir);
344
+ remoteSha = out.match(/^([0-9a-f]{40})\s+/m)?.[1] ?? null;
345
+ }
346
+ }
347
+ catch {
348
+ /* no usable upstream — fall through to origin HEAD */
349
+ }
350
+ if (!remoteSha) {
351
+ const out = await runGit(["ls-remote", "origin", "HEAD"], installDir);
352
+ remoteSha = out.match(/^([0-9a-f]{40})\s+HEAD$/m)?.[1] ?? null;
353
+ }
354
+ if (!remoteSha)
355
+ throw new Error("Failed to determine remote HEAD");
356
+ return { localSha, remoteSha };
357
+ }
158
358
  /** How long a pi probe result stays hot (mirrors ClientSession.piCliProbe). */
159
359
  const PI_PROBE_TTL_MS = 10_000;
160
360
  let piCoreProbe = null;
@@ -236,13 +436,14 @@ function readVendoredPiCore(agentDir) {
236
436
  }
237
437
  }
238
438
  /**
239
- * Build the full local target list: webui + the pi core + installed packages.
439
+ * Build the full local target list: webui + the pi core + installed packages
440
+ * + git-source extensions (issue #178) from global and project settings.
240
441
  * The pi core version comes from the CLI probe (injectable for tests), falling
241
442
  * back to the vendored copy under <agentDir>/npm/node_modules. Packages
242
443
  * listing the core directly are filtered out so the pi-core row wins — never
243
444
  * two rows for the same package.
244
445
  */
245
- export function collectTargets(agentDir, webuiVersion, probePiCore = defaultProbePiCore) {
446
+ export function collectTargets(agentDir, webuiVersion, probePiCore = defaultProbePiCore, opts) {
246
447
  const targets = [{ name: "pi-web-ui", version: webuiVersion, kind: "webui" }];
247
448
  const coreVersion = probePiCore() ?? readVendoredPiCore(agentDir);
248
449
  if (coreVersion) {
@@ -253,6 +454,7 @@ export function collectTargets(agentDir, webuiVersion, probePiCore = defaultProb
253
454
  });
254
455
  }
255
456
  targets.push(...listInstalledPackages(agentDir).filter((pkg) => pkg.name !== PI_CORE_PACKAGE));
457
+ targets.push(...listGitExtensions(agentDir, opts?.projectCwd));
256
458
  return targets;
257
459
  }
258
460
  /** Default fetcher (real network). Tests inject a fake. */
@@ -361,24 +563,61 @@ export async function fetchLatest(fetcher, name, registry = NPM_DEFAULT_REGISTRY
361
563
  };
362
564
  }
363
565
  /**
364
- * Check every target against the registry. One failed lookup degrades to an
365
- * error item (upToDate: false) without failing the rest. Results keep the
366
- * input order. Bounded concurrency (CONCURRENCY) keeps registry load polite.
566
+ * Check every target: npm kinds against the registry, git-extension kinds
567
+ * against their clone's remote (`ls-remote`, refs only). One failed lookup
568
+ * degrades to an error item (upToDate: false) without failing the rest.
569
+ * Results keep the input order. Bounded concurrency (CONCURRENCY) keeps
570
+ * registry/remote load polite. The git checker is injectable for tests.
367
571
  */
368
572
  export async function checkAll(targets, fetcher = defaultFetcher,
369
- /** 单项 registry 查询失败时的 error 文案语言(默认英文)。 */
573
+ /** 单项查询失败时的 error 文案语言(默认英文)。 */
370
574
  lang,
371
575
  /** 镜像/私有源配置(默认官方源;调用方经 resolveNpmRegistry 传入 .npmrc,issue #151)。 */
372
- registryConfig) {
576
+ registryConfig,
577
+ /** git 源远端比较(默认真 git;单测注入 fake,issue #178)。 */
578
+ gitCheck = defaultCheckGitExtension) {
373
579
  const l = lang?.() ?? "en";
374
580
  const registry = registryConfig?.registry ?? NPM_DEFAULT_REGISTRY;
375
581
  const authHeader = registryConfig?.authHeader ?? null;
582
+ const fail = (t, errMessage) => ({
583
+ name: t.name,
584
+ kind: t.kind,
585
+ current: t.version,
586
+ latest: null,
587
+ latestPublishedAt: null,
588
+ upToDate: false,
589
+ ...(t.source ? { source: t.source } : {}),
590
+ error: pick(l, `检查更新失败:${errMessage}`, `Failed to check for updates: ${errMessage}`, "updatecheck.check.failed", {
591
+ errMessage,
592
+ }),
593
+ });
376
594
  const results = Array.from({ length: targets.length });
377
595
  let cursor = 0;
378
596
  async function worker() {
379
597
  while (cursor < targets.length) {
380
598
  const i = cursor++;
381
599
  const t = targets[i];
600
+ if (t.kind === "git-extension") {
601
+ try {
602
+ if (!t.installDir)
603
+ throw new Error("missing install dir");
604
+ const { localSha, remoteSha } = await gitCheck(t.installDir);
605
+ const upToDate = localSha.trim() === remoteSha.trim();
606
+ results[i] = {
607
+ name: t.name,
608
+ kind: t.kind,
609
+ current: formatGitVersion(t.version, localSha),
610
+ latest: formatGitVersion(t.version, remoteSha),
611
+ latestPublishedAt: null,
612
+ upToDate,
613
+ ...(t.source ? { source: t.source } : {}),
614
+ };
615
+ }
616
+ catch (err) {
617
+ results[i] = fail(t, err.message);
618
+ }
619
+ continue;
620
+ }
382
621
  try {
383
622
  const { latest, latestPublishedAt } = await fetchLatest(fetcher, t.name, registry, authHeader);
384
623
  results[i] = {
@@ -391,16 +630,7 @@ registryConfig) {
391
630
  };
392
631
  }
393
632
  catch (err) {
394
- const errMessage = err.message;
395
- results[i] = {
396
- name: t.name,
397
- kind: t.kind,
398
- current: t.version,
399
- latest: null,
400
- latestPublishedAt: null,
401
- upToDate: false,
402
- error: pick(l, `检查更新失败:${errMessage}`, `Failed to check for updates: ${errMessage}`, "updatecheck.check.failed", { errMessage }),
403
- };
633
+ results[i] = fail(t, err.message);
404
634
  }
405
635
  }
406
636
  }
@@ -80,7 +80,8 @@ async function openBrowser(url: string): Promise<void> {
80
80
  platform === "darwin" ? ["open", url] : platform === "win32" ? ["cmd", "/c", "start", "", url] : ["xdg-open", url];
81
81
  // 无界面环境缺少 xdg-open 等打开器时,ENOENT 以异步 'error' 事件触发,
82
82
  // try/catch 拦不住会崩掉整个进程 —— 必须挂 error 监听。
83
- spawn(cmd, rest, { stdio: "ignore", detached: true })
83
+ // Windows 下 detached 子进程会新建控制台闪窗;改为不 detached 并 windowsHide。
84
+ spawn(cmd, rest, { stdio: "ignore", detached: process.platform !== "win32", windowsHide: true })
84
85
  .on("error", (err) => {
85
86
  if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
86
87
  console.warn(
@@ -163,7 +164,13 @@ export default function (pi: ExtensionAPI): void {
163
164
  PI_WEB_CWD: cwd,
164
165
  ...(process.env.PI_WEB_DATA_DIR ? {} : { PI_WEB_DATA_DIR: join(cwd, ".pi-web") }),
165
166
  };
166
- const proc = spawn(NODE, [SERVER_ENTRY], { cwd, env, stdio: "ignore", detached: true });
167
+ const proc = spawn(NODE, [SERVER_ENTRY], {
168
+ cwd,
169
+ env,
170
+ stdio: "ignore",
171
+ detached: process.platform !== "win32",
172
+ windowsHide: true,
173
+ });
167
174
  proc.unref();
168
175
  running.set(sid, { proc, port, cwd, url });
169
176
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-web-ui",
3
- "version": "0.87.2",
3
+ "version": "0.89.0",
4
4
  "description": "Web chat interface for the pi coding agent, powered by the pi SDK (@earendil-works/pi-coding-agent) — one-command run, Docker/systemd/launchd deployable",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -21,6 +21,7 @@
21
21
  "themes/",
22
22
  "deploy/",
23
23
  "extensions/",
24
+ "plugin-sdk/",
24
25
  "plugins/catalog.json",
25
26
  "CHANGELOG.md",
26
27
  "README.md",
@@ -87,6 +88,7 @@
87
88
  "@xterm/addon-fit": "^0.11.0",
88
89
  "@xterm/xterm": "^6.0.0",
89
90
  "compression": "^1.8.1",
91
+ "electron-updater": "^6.8.9",
90
92
  "express": "^4.21.2",
91
93
  "highlight.js": "^11.10.0",
92
94
  "katex": "^0.16.47",
@@ -114,9 +116,9 @@
114
116
  "@vitejs/plugin-react": "^4.3.4",
115
117
  "concurrently": "^9.1.0",
116
118
  "cross-env": "^10.1.0",
117
- "esbuild": "^0.25.12",
118
119
  "electron": "^44.0.0",
119
120
  "electron-builder": "^26.0.0",
121
+ "esbuild": "^0.25.12",
120
122
  "jsdom": "^26.1.0",
121
123
  "mermaid": "^11.17.2",
122
124
  "oxlint": "^1.81.0",
@@ -0,0 +1,127 @@
1
+ # 插件 SDK(starter)
2
+
3
+ ## 脚手架:`pi-web-ui plugin create`
4
+
5
+ 不用手拷文件,一条命令生成最小可跑骨架(`manifest.json` + `index.mjs` + `client/entry.mjs` + `README.md`,SDK 自动拷进 `sdk/`):
6
+
7
+ ```bash
8
+ pi-web-ui plugin create my-plugin --template minimal # 零权限,可直接激活
9
+ pi-web-ui plugin create my-plugin --template ui-slot # composer.actions 按钮 + onUiAction 示例
10
+ pi-web-ui plugin create my-plugin --template agent-tool # registerAgentTool 示例
11
+ pi-web-ui plugin create my-plugin --template renderer # view:false + renderers 示例
12
+ ```
13
+
14
+ 常用选项:`--dir <插件父目录>`(默认 `<dataDir>/plugins`,也可用 `--data-dir` 指定数据目录)、`--force`(目标已存在时覆盖)。生成后会自动做一次 manifest 基础校验 + 生成文件的 `node --check`,有 warning 会直接打印;生效只需刷新浏览器(或发 `plugins_reload`),未运行则下次启动生效。
15
+
16
+ ---
17
+
18
+ `@pi-web-ui/plugin-sdk` 是写插件的**起手包**:`index.mjs`(零依赖纯 ESM,可直接拷进插件目录)+ `index.d.ts`(宿主接口精简类型,编辑器补全用)。
19
+
20
+ > 和 `server/plugins.ts` 的全量 `PluginHost` 是**同语义的精简版**:运行时以宿主实际注入为准,宿主版本见 `PLUGIN_API_VERSION`。SDK 只求“写得顺”,不做运行时 polyfill。
21
+
22
+ ## 怎么用
23
+
24
+ 1. 把 `index.mjs`(和要补全就把 `index.d.ts`)拷进你的插件目录(如 `my-plugin/sdk/`);
25
+ 2. 服务端入口:
26
+
27
+ ```js
28
+ import { definePlugin, selectOptions } from "./sdk/index.mjs";
29
+
30
+ export default definePlugin({
31
+ async activate(host) {
32
+ const tone = String(host.getSettings().tone ?? "short");
33
+ const off = host.ui.register({
34
+ slot: "composer.actions",
35
+ id: "tone",
36
+ label: "语气",
37
+ kind: "select",
38
+ action: "my-plugin:tone",
39
+ value: tone,
40
+ options: selectOptions([
41
+ { value: "short", label: "简短" },
42
+ { value: "full", label: "详细" },
43
+ ]),
44
+ });
45
+ // 反激活时注销(可选,宿主也会统一清理)
46
+ return;
47
+ },
48
+ });
49
+ ```
50
+
51
+ 3. 客户端视图(`client/entry.mjs`):
52
+
53
+ ```js
54
+ import { defineView, onUiAction } from "./sdk/index.mjs";
55
+
56
+ export default defineView({
57
+ mount(el, ctx) {
58
+ const status = document.createElement("div");
59
+ status.textContent = "就绪";
60
+ el.appendChild(status);
61
+ // 动作回调走宿主桥(client bundle 与宿主同页,window 直达),
62
+ // 要落盘/跨端再经 ctx.send 发给服务端入口。
63
+ return onUiAction("my-plugin:tone", (itemId, value) => {
64
+ status.textContent = `语气:${value ?? ""}`;
65
+ ctx.send({ action: "my-plugin:tone", value });
66
+ });
67
+ },
68
+ });
69
+ ```
70
+
71
+ 注意 `select` 的切换值是第二个参数:`onUiAction("my-plugin:tone", (itemId, value) => …)`。
72
+
73
+ ## 本地单测(createMockHost)
74
+
75
+ 插件作者不用起服务就能测 `activate`:SDK 自带 `createMockHost(overrides?)`(零依赖纯 ESM,`node --test` / vitest 均可):
76
+
77
+ ```js
78
+ // my-plugin/index.test.mjs —— 跑法:node --test index.test.mjs
79
+ import { describe, it } from "node:test";
80
+ import assert from "node:assert/strict";
81
+ import plugin from "./index.mjs";
82
+ import { createMockHost } from "./sdk/index.mjs";
83
+
84
+ describe("my-plugin", () => {
85
+ it("activate 注册 UI + 读注入的设置", async () => {
86
+ const host = createMockHost({ settings: { tone: "full" } });
87
+ await plugin.activate(host);
88
+ const reg = host.calls.find((c) => c.method === "ui.register");
89
+ assert.ok(reg, "应该调过 host.ui.register");
90
+ assert.equal(reg.args[0].value, "full"); // 读到的是注入的预设
91
+ });
92
+
93
+ it("reset() 清空记录;emit 模拟客户端消息", async () => {
94
+ const host = createMockHost();
95
+ await plugin.activate(host);
96
+ host.reset();
97
+ assert.equal(host.calls.length, 0);
98
+ assert.equal(host.logs.length, 0);
99
+ host.mock.emit("onMessage", { action: "my-plugin:tone" }, "client-1");
100
+ });
101
+ });
102
+ ```
103
+
104
+ 要点:
105
+
106
+ - `host.calls`:全量调用记录 `{ method, args, seq }`(嵌套按点分路径,如 `"ui.register"`、`"fs.readText"`;`log`/`storage` 也记;`seq` 为本次窗口内序号)。`host.mock.calls(method?)` 按方法名过滤;`host.logs`:分级条目 `{ level, text }`;`host.reset()` 只清空两者(settings/handlers/注册表这些 fake 状态保留,要全新状态就重新 `createMockHost()`,零成本)。
107
+ - `overrides.settings` 是 `getSettings()` 返回的预设对象(同一引用);`host.mock.setSettings(next)` 合并预设,`host.mock.emitSettings(next)` 合并 + 触发 `onSettingsChanged`(模拟用户在设置面板保存)。其余 `overrides` 键整体替换对应方法(`fs`/`ui`/`llm` 等命名空间传对象 = 按子键合并覆盖),被覆盖的方法仍进 `calls` 记录。
108
+ - 无注入回退(与宿主无 provider 时同语义):`conversations.list/search` 回 `[]`、`get` 回 `null`;`prompt`/`steer`/`abortRun`/`chatWait`/`llm.complete`/`net.fetch`/`bash`/`scm` 回 `{ ok:false, … }`;`requestPermission` 回 `false`;`dialogs.select/input` 回 `{ ok:false }`、`confirm` 回 `false`;`notifyAction` resolve `null`;`schedule()` 只记调用不设真定时器(单测不泄漏句柄)。两处刻意差异:`chat()` 未注入时 resolve `{ ok:false }` 而不是 reject(真宿主 reject,由 `chatWait` 包成 `{ ok:false }`);`fs.read/readPath` 给空 `Uint8Array`(浏览器侧 import 本文件也安全)。
109
+ - 注册/订阅类返回注销函数,传进来的 handler 存进 `host.mock.handlers[method]`,用 `host.mock.emit(method, ...args)` 同步触发(异步 handler 用 `await host.mock.emitAsync(...)` 按序 await,返回各返回值)。工具/命令/路由/定时任务的定义体另存进 `host.mock.agentTools/commands/routes/schedules`(活数组,注销即摘除;工具的 `execute` 可直接调);`schedule()` 不设真定时器,用 `await host.mock.fireSchedules()` 手动触发。
110
+ - `ui` 是内存注册表(同 id 覆盖、单次上限 32 条):`list()` 真反映 register/update/remove/arrange。
111
+ - 脚手架可直接生成这个最小单测:`pi-web-ui plugin create my-plugin --with-test`(生成 `index.test.mjs`,现有模板默认不变)。
112
+ - `sdk/index.mjs` 是静态拷贝:`SDK_VERSION` 与 `plugin-sdk/package.json` 的 version 保持一致;已装插件用 `pi-web-ui plugin upgrade-sdk [id]` 一键刷新拷贝(版本号对不上才拷,无拷贝的插件跳过)。
113
+ - mock 只在 SDK 层:不断言、不碰 `server/plugins.ts` 运行时。类型见 `index.d.ts` 的 `MockHost` / `MockHostOverrides` / `createMockHost`。
114
+
115
+ ## 本次 P0 新增速览
116
+
117
+ | 能力 | 服务端 | 视图 |
118
+ | ------------------------------------------------------------------------------------------------ | --------------------- | ------------------------------- |
119
+ | `host.fs.stat/mkdir/append/glob`(+ `*Path` 跨目录版) | ✅ | — |
120
+ | `kind: "select"` + `options` + `value`,`host.ui.update(id, { value })` 刷新 | ✅ | 顶栏/输入框/消息工具条已渲染 |
121
+ | `when` 肯定形条件(`file.isDir` / `file.isFile` / `session.isRunning` / `message.hasSelection`) | — | 右键菜单现场求值,置灰 |
122
+ | `settings` 新增 `secret` 类型(加密存,浏览器只见有无) | ✅ | 设置表单掩码 + 留空不改 |
123
+ | `host.llm.complete`(孤立无工具补全,不建对话) | ✅(要 `llm` 能力族) | — |
124
+ | `schedule` 持久版(`{id, persistent, catchUp, label}`,落盘+补跑+进后台面板) | ✅ | — |
125
+ | `host.requestPermission`(动态授权:net 补主机 / llm 限模型,用户逐条确认可记住) | ✅(基础族须已声明) | 确认框 + 设置面板「已授权能力」 |
126
+
127
+ 完整契约见 `docs/architecture-plugins.md`。