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
@@ -34,7 +34,7 @@ import { MarkerService } from "./marker-service.js";
34
34
  import { SlashCommandsService, parseSlash } from "./slash-commands.js";
35
35
  import { ModelAdminService } from "./model-admin.js";
36
36
  import { FilesService, MACHINE_ROOT, desktopDirWire, workspacePath } from "./files-service.js";
37
- import { isExtensionDisabled, isExtensionEnabled, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
37
+ import { isExtensionDisabled, isExtensionEnabled, normalizeDisabledPluginTools, normalizeRetryMaxAttempts, normalizeSkillList, ClientStateStore, } from "./client-state.js";
38
38
  import { bilingual, pick, resolveServerLang } from "./i18n.js";
39
39
  import { SubagentTemplatesStore, pickTemplatePrompt } from "./subagent-templates.js";
40
40
  import { ComposerDraftsStore } from "./composer-drafts.js";
@@ -45,6 +45,7 @@ import { decodeText } from "./text-sniff.js";
45
45
  import { makeEditSoftTool } from "./edit-soft-tool.js";
46
46
  import { collectSubagentDescendantIds, makeSubagentTools, subagentTitle, withSubagentOwner, } from "./subagents.js";
47
47
  import { makeDelegateTaskTool } from "./delegate-task.js";
48
+ import { makeConversationReadTool, parseTranscriptLines, toTranscriptInput, } from "./conversation-read-tool.js";
48
49
  import { buildAttachmentMessages, parseModelSpec } from "./attachments.js";
49
50
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
50
51
  import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
@@ -1331,6 +1332,86 @@ export class ClientSession {
1331
1332
  return !!t && t.enabled;
1332
1333
  },
1333
1334
  };
1335
+ /** conversation_read 工具的数据宿主:读本客户端的 conversation 体系 +
1336
+ * 落盘会话目录。运行中对话按 id(实时消息,含未落盘的);历史按 path,
1337
+ * 且必须是会话列表里的路径(任意文件不给读)。跨标签页的实时运行不在
1338
+ * this.convs 里——以落盘历史为准(工具 description 会告诉模型)。 */
1339
+ conversationReadHost() {
1340
+ return {
1341
+ listRunningConversations: () => {
1342
+ const out = [];
1343
+ for (const c of this.convs.values()) {
1344
+ let messageCount = 0;
1345
+ let isStreaming = false;
1346
+ try {
1347
+ messageCount = c.session.getSessionStats().totalMessages;
1348
+ isStreaming = c.session.isStreaming;
1349
+ }
1350
+ catch {
1351
+ // 会话替换中——报默认值
1352
+ }
1353
+ out.push({
1354
+ id: c.id,
1355
+ title: c.title,
1356
+ cwd: c.cwd,
1357
+ messageCount,
1358
+ isStreaming,
1359
+ isSubagent: !!c.isSubagent,
1360
+ ...(c.parentId ? { parentId: c.parentId } : {}),
1361
+ });
1362
+ }
1363
+ return out;
1364
+ },
1365
+ readRunningConversation: (id) => {
1366
+ const c = this.convs.get(id);
1367
+ if (!c)
1368
+ return undefined;
1369
+ let raw = [];
1370
+ try {
1371
+ raw = (c.session.messages ??
1372
+ c.session.agent.state.messages ??
1373
+ []);
1374
+ }
1375
+ catch {
1376
+ raw = [];
1377
+ }
1378
+ return { title: c.title, cwd: c.cwd, isSubagent: !!c.isSubagent, messages: raw.map(toTranscriptInput) };
1379
+ },
1380
+ listHistorySessions: async (scope, cwd) => {
1381
+ const infos = scope === "all"
1382
+ ? await SessionManager.listAll(piSessionsRoot())
1383
+ : await SessionManager.list(cwd || this.cwd, piSessionsRoot());
1384
+ return infos.map((s) => ({
1385
+ path: s.path,
1386
+ name: s.name,
1387
+ firstMessage: s.firstMessage,
1388
+ messageCount: s.messageCount,
1389
+ modified: s.modified.getTime(),
1390
+ cwd: s.cwd,
1391
+ }));
1392
+ },
1393
+ readHistorySession: async (path) => {
1394
+ const all = await SessionManager.listAll(piSessionsRoot());
1395
+ const hit = all.find((s) => resolve(s.path) === resolve(path));
1396
+ if (!hit)
1397
+ return undefined;
1398
+ try {
1399
+ if (statSync(hit.path).size > 16 * 1024 * 1024)
1400
+ return undefined;
1401
+ const text = readFileSync(hit.path, "utf8");
1402
+ return {
1403
+ title: hit.name || hit.firstMessage,
1404
+ cwd: hit.cwd,
1405
+ sessionPath: hit.path,
1406
+ messages: parseTranscriptLines(text),
1407
+ };
1408
+ }
1409
+ catch {
1410
+ return undefined;
1411
+ }
1412
+ },
1413
+ };
1414
+ }
1334
1415
  widgetsTimer = null;
1335
1416
  /** Model-stall watchdog interval (see startStallTimer). */
1336
1417
  stallTimer = null;
@@ -1711,9 +1792,9 @@ export class ClientSession {
1711
1792
  ...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang()),
1712
1793
  // 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置)。
1713
1794
  makeEditSoftTool(effectiveCwd, () => this.getLang()),
1714
- // 插件注册的 AI 工具(创建时刻的实时快照;后续注册经
1715
- // refreshPluginTools 动态补入已有会话)。
1716
- ...(this.pluginToolsProvider?.() ?? []).map(pluginToolToDefinition),
1795
+ // 插件注册的 AI 工具(创建时刻的实时快照,已按 disabledPluginTools 过滤;
1796
+ // 后续注册经 refreshPluginTools 动态补入已有会话)。
1797
+ ...this.enabledPluginToolDefs(),
1717
1798
  // 第一方子代理工具(spawn/get_result/steer/list/stop)。子代理会话
1718
1799
  // 也注册了它们,因此可自然嵌套派发。host 按 ownerId 包装:子代理的
1719
1800
  // 父对话 = 真正调用 spawn 的那个会话(本 runtime 所属会话),而不是
@@ -1740,6 +1821,11 @@ export class ClientSession {
1740
1821
  // 操作用户授权的页面 → page_response 回来。ownerId 语义同上(本 runtime
1741
1822
  // 所属会话,不是派发瞬间的 active)。
1742
1823
  makeBrowserPageTool(this, ownerId),
1824
+ // 别的对话读取(运行中含子代理 + 历史转录,只读):用户引用了别的
1825
+ // 对话(引用 chip / 粘过来的 id / “看看之前那个对话”)时用。子代理
1826
+ // 会话同样注册了它,可自然嵌套读取。不需要 ownerId——读的是本
1827
+ // 客户端的 conversation 体系与落盘历史,与派发者无关。
1828
+ makeConversationReadTool(this.conversationReadHost(), () => this.getLang()),
1743
1829
  ],
1744
1830
  });
1745
1831
  // 终端工具开关从创建起就生效(工具始终注册进注册表,只调活跃集)。
@@ -2228,6 +2314,40 @@ export class ClientSession {
2228
2314
  return { ok: false, error: err.message };
2229
2315
  }
2230
2316
  }
2317
+ /** 插件扩展点(供 llmProvider):孤立补全的环境(cwd/agentDir/回落模型)。
2318
+ * 取最近活跃的主对话(跳过子代理);model 读不到就只给 cwd(调用方再回落默认模型)。
2319
+ * 纯数据组装,不 emit、不改状态。 */
2320
+ llmEnvForPlugins() {
2321
+ let target = null;
2322
+ try {
2323
+ for (const c of this.convs.values()) {
2324
+ if (c.isSubagent)
2325
+ continue;
2326
+ if (!target || c.lastActiveAt > target.lastActiveAt)
2327
+ target = c;
2328
+ }
2329
+ if (!target) {
2330
+ for (const c of this.convs.values()) {
2331
+ if (!target || c.lastActiveAt > target.lastActiveAt)
2332
+ target = c;
2333
+ }
2334
+ }
2335
+ }
2336
+ catch {
2337
+ target = null;
2338
+ }
2339
+ const cwd = target?.cwd ?? this.cwd;
2340
+ let fallbackModel;
2341
+ try {
2342
+ const m = target?.session?.model;
2343
+ if (m?.provider && m.id)
2344
+ fallbackModel = { provider: m.provider, id: m.id };
2345
+ }
2346
+ catch {
2347
+ /* model 读不到就回落默认 */
2348
+ }
2349
+ return { cwd, agentDir: this.agentDir, ...(fallbackModel ? { fallbackModel } : {}) };
2350
+ }
2231
2351
  /** 插件扩展点 v2(供 modelLister):复用 listModels 的模型列表映射 {id,provider,vision}。
2232
2352
  * 与 listModels 唯一差别:不做网络 refresh(插件列表走缓存目录,15s 超时也不等),只读不 emit。 */
2233
2353
  async listModelsForPlugins() {
@@ -3271,7 +3391,9 @@ export class ClientSession {
3271
3391
  return;
3272
3392
  }
3273
3393
  try {
3274
- const targets = collectTargets(this.agentDir, ClientSession.currentAppVersion());
3394
+ const targets = collectTargets(this.agentDir, ClientSession.currentAppVersion(), undefined, {
3395
+ projectCwd: this.conv?.cwd ?? this.cwd,
3396
+ });
3275
3397
  const items = sortUpdateItems(await checkAllUpdates(targets, undefined, () => this.getLang(), resolveNpmRegistry(this.agentDir)));
3276
3398
  this.updatesAllCache = { at: Date.now(), items };
3277
3399
  this.emit({ type: "update_status_all", items });
@@ -3466,6 +3588,15 @@ export class ClientSession {
3466
3588
  refreshProviderModels(providerId, reqId) {
3467
3589
  return this.modelAdmin.refreshProviderModels(providerId, reqId, () => this.getLang());
3468
3590
  }
3591
+ /** Force-refresh built-in providers' official pi.dev catalogs (bypass the
3592
+ * SDK's 4h freshness window) — refresh_builtin_result. */
3593
+ refreshBuiltinModels(reqId) {
3594
+ return this.modelAdmin.refreshBuiltinModels(reqId);
3595
+ }
3596
+ /** Append one model to a built-in provider's models.json overlay entry. */
3597
+ appendBuiltinModel(providerId, model, reqId) {
3598
+ return this.modelAdmin.appendBuiltinModel(providerId, model, reqId);
3599
+ }
3469
3600
  /** Copy a built-in provider into an editable custom-provider draft
3470
3601
  * (clone_provider_result) — lets the user run a second API key without
3471
3602
  * overwriting the built-in one. */
@@ -3647,6 +3778,10 @@ export class ClientSession {
3647
3778
  markerChanged = true;
3648
3779
  }
3649
3780
  await this.settingsSvc.set(rest);
3781
+ if (rest.disabledPluginTools !== undefined) {
3782
+ this.refreshPluginTools();
3783
+ this.flushSnapshot();
3784
+ }
3650
3785
  if (markerChanged) {
3651
3786
  // 标记开关影响 system prompt 引导,需重载生效(流式中则延迟)
3652
3787
  this.pushSettings();
@@ -3694,6 +3829,7 @@ export class ClientSession {
3694
3829
  * 所以这两条路径之后都要重放本方法(见 reloadSession/创建处)。 */
3695
3830
  applyToolGating(session) {
3696
3831
  applyAgentToolsGating(session, effectiveDisabledAgentTools(this.settingsSvc.current));
3832
+ this.syncPluginTools(session);
3697
3833
  // SDK 的 setActiveToolsByName 只改 agent.state.tools,不派发任何事件——门控后
3698
3834
  // 主动推一次快照,否则快照里的 tools 要等下一个 SDK 事件才对齐(会话空闲时永远
3699
3835
  // 等不到;回归:tests/terminal-smoke-test.mjs「agent exposes persistent terminal tools」)。
@@ -3702,11 +3838,17 @@ export class ClientSession {
3702
3838
  if (active && active.session === session)
3703
3839
  this.flushSnapshot();
3704
3840
  }
3705
- /** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除)。
3841
+ /** 当前启用的插件 AI 工具定义(provider 快照按 disabledPluginTools 过滤;
3842
+ * 未知/已卸载插件的禁用条目保留但不影响现有工具)。 */
3843
+ enabledPluginToolDefs() {
3844
+ const off = new Set(normalizeDisabledPluginTools(this.settingsSvc.current.disabledPluginTools));
3845
+ return (this.pluginToolsProvider?.() ?? []).filter((t) => !off.has(t.name)).map(pluginToolToDefinition);
3846
+ }
3847
+ /** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除;禁用工具同步移除)。
3706
3848
  * 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。 */
3707
3849
  syncPluginTools(session) {
3708
3850
  try {
3709
- const defs = (this.pluginToolsProvider?.() ?? []).map(pluginToolToDefinition);
3851
+ const defs = this.enabledPluginToolDefs();
3710
3852
  const next = syncPluginToolsIntoSession(session, defs, this.appliedPluginToolNames);
3711
3853
  if (next)
3712
3854
  this.appliedPluginToolNames = new Set(next);
@@ -4702,8 +4844,25 @@ export class ClientSession {
4702
4844
  if (cwdChanged) {
4703
4845
  this.cwd = newCwd;
4704
4846
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, newCwd);
4705
- await this.restoreProjectProviderKeysForCwd(newCwd);
4706
- await this.restoreProjectModelForCwd(newCwd);
4847
+ // 模型/key 恢复不挡快照:后台做,带代际 guard(用户又切走就跳过),
4848
+ // 做完补一次 flush 刷新模型栏。
4849
+ {
4850
+ const convId = id;
4851
+ void (async () => {
4852
+ try {
4853
+ await this.restoreProjectProviderKeysForCwd(newCwd);
4854
+ if (this.disposed || this.activeId !== convId || this.cwd !== newCwd)
4855
+ return;
4856
+ await this.restoreProjectModelForCwd(newCwd);
4857
+ if (this.disposed || this.activeId !== convId || this.cwd !== newCwd)
4858
+ return;
4859
+ this.flushSnapshot();
4860
+ }
4861
+ catch {
4862
+ /* 静默:恢复失败保持会话默认 */
4863
+ }
4864
+ })();
4865
+ }
4707
4866
  // Mirror set_cwd's project-switch side-effects so the whole UI follows
4708
4867
  // the new workspace, not just the chat pane.
4709
4868
  try {
@@ -4714,7 +4873,7 @@ export class ClientSession {
4714
4873
  }
4715
4874
  this.stateStore.remember(this.clientId, newCwd);
4716
4875
  void this.pushProjects();
4717
- void this.refreshSessions();
4876
+ this.refreshSessionsOnSwitch();
4718
4877
  void this.listFiles(undefined);
4719
4878
  void this.listCommands();
4720
4879
  }
@@ -4783,6 +4942,16 @@ export class ClientSession {
4783
4942
  messageCount,
4784
4943
  isStreaming,
4785
4944
  isSubagent: !!conv.isSubagent,
4945
+ // 落盘会话才有文件(inMemory 子代理缺省):右键复制路径 / AI 按 path 读历史时用。
4946
+ ...(() => {
4947
+ try {
4948
+ const f = conv.session.sessionFile;
4949
+ return f ? { sessionFile: f } : {};
4950
+ }
4951
+ catch {
4952
+ return {};
4953
+ }
4954
+ })(),
4786
4955
  // 子代理带 error 标记:左栏红点提示(普通对话不参与)。
4787
4956
  ...(conv.isSubagent ? this.subagentRunOutcome(conv) : {}),
4788
4957
  parentId: conv.parentId,
@@ -4829,6 +4998,12 @@ export class ClientSession {
4829
4998
  */
4830
4999
  sessionInfosCache = null;
4831
5000
  static SESSION_INFO_CACHE_TTL = 3000;
5001
+ /** 最近项目列表缓存:pushProjects 的全量扫盘(SessionManager.listAll +
5002
+ * existsSync 逐个校验)昂贵,切项目/新对话/跨客户端通知时频繁触发 ——
5003
+ * TTL 内直接复用并把当前 cwd 合并进去,不反复扫盘。 */
5004
+ projectsCache = null;
5005
+ static PROJECTS_CACHE_TTL = 15_000;
5006
+ projectsInFlight = null;
4832
5007
  async loadSessionInfos() {
4833
5008
  const now = Date.now();
4834
5009
  const c = this.sessionInfosCache;
@@ -4851,6 +5026,13 @@ export class ClientSession {
4851
5026
  this.sessionsRequested = true;
4852
5027
  await this.pushSessions();
4853
5028
  }
5029
+ /** 切项目时的会话列表刷新:历史面板没打开过就不扫盘(只清缓存),打开过
5030
+ * 才重推 —— 首访切项目的转录解析不在关键路径上。 */
5031
+ refreshSessionsOnSwitch() {
5032
+ this.invalidateSessionInfos();
5033
+ if (this.sessionsRequested)
5034
+ void this.refreshSessions();
5035
+ }
4854
5036
  async pushSessions() {
4855
5037
  if (!this.sessionsRequested)
4856
5038
  return;
@@ -4882,6 +5064,7 @@ export class ClientSession {
4882
5064
  /** Remove an entry from the client's recent-project list (UI state only). */
4883
5065
  async removeProject(path) {
4884
5066
  this.stateStore.removeProject(this.clientId, path);
5067
+ this.invalidateProjectsCache();
4885
5068
  await this.pushProjects();
4886
5069
  }
4887
5070
  /** Permanently delete a persisted session transcript file (history list ✕).
@@ -5071,7 +5254,8 @@ export class ClientSession {
5071
5254
  this.emitConversations();
5072
5255
  }
5073
5256
  /** Dismiss 口径的「已结束子代理」:非 streaming 且无保留态(存活终端/
5074
- * 审查/后台唤醒等),与 dismissFinishedSubagents 的候选口径一致。 */
5257
+ * 审查/后台唤醒等),与 dismissFinishedSubagents 的候选口径一致。
5258
+ * issue #181:终端只看用户终端,残留 AI bash 不算(随移出一起释放)。 */
5075
5259
  isDismissableFinishedSubagent(conv) {
5076
5260
  let streaming = true;
5077
5261
  try {
@@ -5086,8 +5270,8 @@ export class ClientSession {
5086
5270
  reviewing: conv.goal.reviewing,
5087
5271
  wizardRunning: conv.wizardRunning,
5088
5272
  streaming: false,
5089
- // 与 displaceActive 同口径:只看“用过”的存活终端。
5090
- openTerminals: conv.terminals.countBlockingLive(),
5273
+ // Dismiss 口径:只看“用过”的用户终端(AI bash 不钉住,见上)。
5274
+ openTerminals: conv.terminals.countUserBlockingLive(),
5091
5275
  listed: false,
5092
5276
  promptedSinceActive: false,
5093
5277
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -5158,7 +5342,10 @@ export class ClientSession {
5158
5342
  });
5159
5343
  return;
5160
5344
  }
5161
- if (conv.terminals.countBlockingLive() > 0) {
5345
+ // issue #181:只看用户终端——AI bash(agentBash)是 agent 的内部执行记录,
5346
+ // 随对话一起释放(removeConversation 里 killAll),不得阻断移出;否则残留的
5347
+ // ai-bash-98/99 会把会话永久钉在列表里。用户亲手开且用过的终端仍拦截。
5348
+ if (conv.terminals.countUserBlockingLive() > 0) {
5162
5349
  this.emit({
5163
5350
  type: "notice",
5164
5351
  level: "warning",
@@ -5167,7 +5354,7 @@ export class ClientSession {
5167
5354
  });
5168
5355
  return;
5169
5356
  }
5170
- // 没动过的空 shell(点开终端 tab 自动建的那个)不拦截:随对话一起释放
5357
+ // 没动过的空 shell(点开终端 tab 自动建的那个)与 AI bash 不拦截:随对话一起释放
5171
5358
  // (removeConversation 里 killAll)。
5172
5359
  if (shouldRetainActive({
5173
5360
  reviewing: conv.goal.reviewing,
@@ -5421,8 +5608,8 @@ export class ClientSession {
5421
5608
  reviewing: conv.goal.reviewing,
5422
5609
  wizardRunning: conv.wizardRunning,
5423
5610
  streaming: false,
5424
- // 与 displaceActive 同口径:只看“用过”的存活终端。
5425
- openTerminals: conv.terminals.countBlockingLive(),
5611
+ // Dismiss 口径:只看“用过”的用户终端(issue #181,AI bash 不钉住)。
5612
+ openTerminals: conv.terminals.countUserBlockingLive(),
5426
5613
  listed: false,
5427
5614
  promptedSinceActive: false,
5428
5615
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -5713,34 +5900,77 @@ export class ClientSession {
5713
5900
  * opened before the recent-list feature existed still show up).
5714
5901
  */
5715
5902
  async pushProjects() {
5716
- try {
5717
- const saved = this.stateStore.get(this.clientId);
5718
- const removedProjects = new Set(this.stateStore.getRemovedProjects(this.clientId));
5719
- const map = new Map();
5720
- for (const p of saved.projects)
5721
- map.set(p.path, p.lastUsed);
5722
- const all = await SessionManager.listAll(piSessionsRoot());
5723
- for (const s of all) {
5724
- if (s.cwd) {
5725
- const t = s.modified.getTime();
5726
- const prev = map.get(s.cwd);
5727
- if (prev === undefined || t > prev)
5728
- map.set(s.cwd, t);
5729
- }
5903
+ const now = Date.now();
5904
+ const cached = this.projectsCache;
5905
+ // TTL 命中:直接复用(把当前 cwd 合并进去,刚 remember 的新项目也可见)。
5906
+ if (cached && now - cached.at < ClientSession.PROJECTS_CACHE_TTL) {
5907
+ this.emit({ type: "projects", projects: this.withCurrentCwd(cached.projects, now) });
5908
+ return;
5909
+ }
5910
+ // 已有扫描在跑:搭车等它,不要并发扫两遍盘。
5911
+ if (this.projectsInFlight) {
5912
+ try {
5913
+ const projects = await this.projectsInFlight;
5914
+ if (projects)
5915
+ this.emit({ type: "projects", projects: this.withCurrentCwd(projects, Date.now()) });
5916
+ }
5917
+ catch {
5918
+ /* 首发扫描已自行 emit 错误结果,这里不再补 */
5730
5919
  }
5731
- // Only keep directories that still exist — a deleted/unmounted workspace
5732
- // is useless in the picker. Tombstoned entries (explicitly removed by
5733
- // the user) stay hidden even though session files still mention them.
5734
- const projects = [...map.entries()]
5735
- .filter(([path]) => !removedProjects.has(path) && existsSync(path))
5736
- .map(([path, lastUsed]) => ({ path, lastUsed }))
5737
- .sort((a, b) => b.lastUsed - a.lastUsed)
5738
- .slice(0, 20);
5739
- this.emit({ type: "projects", projects });
5920
+ return;
5740
5921
  }
5741
- catch {
5742
- this.emit({ type: "projects", projects: [] });
5922
+ const run = (async () => {
5923
+ try {
5924
+ const saved = this.stateStore.get(this.clientId);
5925
+ const removedProjects = new Set(this.stateStore.getRemovedProjects(this.clientId));
5926
+ const map = new Map();
5927
+ for (const p of saved.projects)
5928
+ map.set(p.path, p.lastUsed);
5929
+ const all = await SessionManager.listAll(piSessionsRoot());
5930
+ for (const s of all) {
5931
+ if (s.cwd) {
5932
+ const t = s.modified.getTime();
5933
+ const prev = map.get(s.cwd);
5934
+ if (prev === undefined || t > prev)
5935
+ map.set(s.cwd, t);
5936
+ }
5937
+ }
5938
+ // Only keep directories that still exist — a deleted/unmounted workspace
5939
+ // is useless in the picker. Tombstoned entries (explicitly removed by
5940
+ // the user) stay hidden even though session files still mention them.
5941
+ const projects = [...map.entries()]
5942
+ .filter(([path]) => !removedProjects.has(path) && existsSync(path))
5943
+ .map(([path, lastUsed]) => ({ path, lastUsed }))
5944
+ .sort((a, b) => b.lastUsed - a.lastUsed)
5945
+ .slice(0, 20);
5946
+ this.projectsCache = { at: Date.now(), projects };
5947
+ this.emit({ type: "projects", projects });
5948
+ return projects;
5949
+ }
5950
+ catch {
5951
+ this.emit({ type: "projects", projects: [] });
5952
+ return null;
5953
+ }
5954
+ finally {
5955
+ this.projectsInFlight = null;
5956
+ }
5957
+ })();
5958
+ this.projectsInFlight = run;
5959
+ await run;
5960
+ }
5961
+ /** 缓存命中时把当前 cwd 并进去:命中则刷新 lastUsed 重排,未命中则补到首位
5962
+ * (remember 刚写入的新项目在 TTL 窗口内也可见,不必等下一次扫盘)。 */
5963
+ withCurrentCwd(projects, now) {
5964
+ if (projects.some((p) => p.path === this.cwd)) {
5965
+ return projects
5966
+ .map((p) => (p.path === this.cwd && p.lastUsed < now ? { ...p, lastUsed: now } : p))
5967
+ .sort((a, b) => b.lastUsed - a.lastUsed);
5743
5968
  }
5969
+ return [{ path: this.cwd, lastUsed: now }, ...projects].slice(0, 20);
5970
+ }
5971
+ /** 最近项目缓存失效(用户显式移除项目后,下一次推送必须重扫)。 */
5972
+ invalidateProjectsCache() {
5973
+ this.projectsCache = null;
5744
5974
  }
5745
5975
  /** List a workspace directory (relative to the configured cwd). */
5746
5976
  async listFiles(relPath) {
@@ -5815,6 +6045,14 @@ export class ClientSession {
5815
6045
  async copyEntry(src, destDir, move) {
5816
6046
  return this.files.copyEntry(src, destDir, move);
5817
6047
  }
6048
+ /** 文件树右键菜单:在系统资源管理器中定位(issue #187)。 */
6049
+ async revealEntry(path) {
6050
+ return this.files.revealEntry(path);
6051
+ }
6052
+ /** 文件树右键菜单:用系统默认应用打开文件(issue #187)。 */
6053
+ async openDefaultEntry(path) {
6054
+ return this.files.openDefaultEntry(path);
6055
+ }
5818
6056
  async makeDir(relPath) {
5819
6057
  return this.files.makeDir(relPath);
5820
6058
  }
@@ -5931,6 +6169,15 @@ export class ClientSession {
5931
6169
  this.removeConversation(displaced.id);
5932
6170
  }
5933
6171
  else {
6172
+ // 冷切换的 runtime 创建要 1~2s(扫技能/扩展)—— 先回一条 ack +
6173
+ // 快照,点击看起来不再 frozen;落地后再推第二次全量。
6174
+ this.emit({
6175
+ type: "notice",
6176
+ level: "info",
6177
+ text: `正在切换到工作目录:${abs}`,
6178
+ textEn: `Switching to directory: ${abs}`,
6179
+ });
6180
+ this.flushSnapshot();
5934
6181
  // First visit to this project: resume its most recent session —
5935
6182
  // unless that transcript is streaming on another client (#145):
5936
6183
  // default-opening it would strand the tab on a conversation it
@@ -5985,8 +6232,25 @@ export class ClientSession {
5985
6232
  this.conv.lastActiveAt = Date.now();
5986
6233
  this.cwd = abs;
5987
6234
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
5988
- await this.restoreProjectProviderKeysForCwd(abs);
5989
- await this.restoreProjectModelForCwd(abs);
6235
+ // 模型/key 恢复不挡快照:后台做,带切换代际 guard(用户又切走就跳过,
6236
+ // 否则会把旧项目的 key 套到新对话上),做完补一次 flush 刷新模型栏。
6237
+ {
6238
+ const convId = this.activeId;
6239
+ void (async () => {
6240
+ try {
6241
+ await this.restoreProjectProviderKeysForCwd(abs);
6242
+ if (this.disposed || this.activeId !== convId || this.cwd !== abs)
6243
+ return;
6244
+ await this.restoreProjectModelForCwd(abs);
6245
+ if (this.disposed || this.activeId !== convId || this.cwd !== abs)
6246
+ return;
6247
+ this.flushSnapshot();
6248
+ }
6249
+ catch {
6250
+ /* 静默:恢复失败保持会话默认 */
6251
+ }
6252
+ })();
6253
+ }
5990
6254
  // 工作区跟随型插件(编辑器文件树等)同步切根。
5991
6255
  try {
5992
6256
  this.onCwdChanged?.(abs, this.roots);
@@ -6008,7 +6272,7 @@ export class ClientSession {
6008
6272
  text: `已切换到工作目录:${abs}`,
6009
6273
  textEn: `Switched to directory: ${abs}`,
6010
6274
  });
6011
- void this.refreshSessions();
6275
+ this.refreshSessionsOnSwitch();
6012
6276
  void this.listFiles(undefined);
6013
6277
  // Commands are per-project (.pi/commands.json in the current cwd).
6014
6278
  void this.listCommands();
@@ -6418,6 +6682,116 @@ export class AgentService {
6418
6682
  void cs.prompt(text);
6419
6683
  return { conversationId: before, clientId };
6420
6684
  }
6685
+ /** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
6686
+ * 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
6687
+ * cwd 按任务配置 pin 住(不存在即失败,不默默跑错目录);可选模型/思考强度
6688
+ * 在投递前应用(失败即返回错误,不回落,避免账单/效果与预期不符)。
6689
+ * fire-and-forget 投递后等待运行结束(最长 10 分钟轮询),回填真实 outcome
6690
+ * (成功/失败/耗时/会话 id)供历史记录与通知使用;超时按失败记录(运行本身
6691
+ * 不中止,继续在后台跑完)。 */
6692
+ async chatFromScheduler(task) {
6693
+ const safe = String(task.id ?? "task").replace(/[^A-Za-z0-9_-]/g, "") || "task";
6694
+ const clientId = `scheduler:${safe}`;
6695
+ const text = String(task.prompt ?? "");
6696
+ if (!text.trim())
6697
+ return { ok: false, error: "触发指令为空" };
6698
+ if (this.quiesced)
6699
+ return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
6700
+ const cwd = String(task.cwd ?? "").trim();
6701
+ try {
6702
+ if (!cwd || !statSync(cwd).isDirectory())
6703
+ throw new Error("not-a-dir");
6704
+ }
6705
+ catch {
6706
+ return { ok: false, error: `目标项目不存在或不是目录:${cwd || "(空)"}` };
6707
+ }
6708
+ try {
6709
+ const cs = await this.attach(clientId, () => { });
6710
+ if (cs.cwd !== cwd)
6711
+ await cs.setCwd(cwd);
6712
+ const model = String(task.model ?? "").trim();
6713
+ if (model) {
6714
+ try {
6715
+ await cs.setModel(model);
6716
+ }
6717
+ catch (err) {
6718
+ return { ok: false, error: `切换模型失败(${model}):${err.message}` };
6719
+ }
6720
+ }
6721
+ const thinking = String(task.thinkingLevel ?? "").trim();
6722
+ if (thinking) {
6723
+ try {
6724
+ cs.setThinking(thinking);
6725
+ }
6726
+ catch (err) {
6727
+ return { ok: false, error: `切换思考强度失败(${thinking}):${err.message}` };
6728
+ }
6729
+ }
6730
+ const conversationId = cs.readConversationForPlugins()?.conversationId ?? "";
6731
+ void cs.prompt(`[定时任务] ${text}`);
6732
+ // 等待运行结束:每 2s 轮询,最长 10 分钟。超时按失败记录(运行继续)。
6733
+ const deadline = Date.now() + 10 * 60 * 1000;
6734
+ for (;;) {
6735
+ await new Promise((r) => setTimeout(r, 2000));
6736
+ let streaming = false;
6737
+ let lastError;
6738
+ try {
6739
+ const snap = cs.readConversationForPlugins();
6740
+ streaming = snap?.isStreaming === true;
6741
+ const msgs = snap?.messages ?? [];
6742
+ for (let i = msgs.length - 1; i >= 0; i--) {
6743
+ const m = msgs[i];
6744
+ if (m.role === "assistant" && m.errorMessage) {
6745
+ lastError = m.errorMessage;
6746
+ break;
6747
+ }
6748
+ if (m.role === "assistant")
6749
+ break;
6750
+ }
6751
+ }
6752
+ catch {
6753
+ streaming = false;
6754
+ }
6755
+ if (!streaming) {
6756
+ if (lastError)
6757
+ return { ok: false, conversationId: conversationId || undefined, error: lastError };
6758
+ return { ok: true, conversationId: conversationId || undefined };
6759
+ }
6760
+ if (Date.now() >= deadline)
6761
+ return { ok: false, conversationId: conversationId || undefined, error: "运行超时(10 分钟),仍在后台继续" };
6762
+ }
6763
+ }
6764
+ catch (err) {
6765
+ return { ok: false, error: err.message };
6766
+ }
6767
+ }
6768
+ /** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
6769
+ * 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
6770
+ * quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
6771
+ async completeForPlugins(pluginId, req) {
6772
+ try {
6773
+ if (this.quiesced)
6774
+ return { ok: false, error: "插件 LLM 调用被拒绝,请等服务器恢复后重试" };
6775
+ let env;
6776
+ const agentDir = process.env.PI_CODING_AGENT_DIR ?? getAgentDir();
6777
+ try {
6778
+ const cs = this.pluginClient();
6779
+ env = cs?.llmEnvForPlugins() ?? { cwd: this.cwd, agentDir };
6780
+ }
6781
+ catch {
6782
+ env = { cwd: this.cwd, agentDir };
6783
+ }
6784
+ const mod = await import("./plugin-llm.js");
6785
+ const r = await mod.completeWithIsolatedSession(env, { ...req, prompt: String(req?.prompt ?? "") });
6786
+ if (!r.ok)
6787
+ return r;
6788
+ console.log(`[plugin:${pluginId}] llm.complete ok(模型 ${r.model},输出 ${r.text.length} 字)`);
6789
+ return r;
6790
+ }
6791
+ catch (err) {
6792
+ return { ok: false, error: err.message };
6793
+ }
6794
+ }
6421
6795
  /** index.ts calls this when a browser socket opens/closes. */
6422
6796
  noteSocketOpen() {
6423
6797
  this.socketCount += 1;