pi-web-ui 0.88.0 → 0.90.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 (36) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist/server/agent-service.js +464 -68
  3. package/dist/server/attachments.js +39 -0
  4. package/dist/server/auth-cookie.js +23 -0
  5. package/dist/server/client-state.js +35 -0
  6. package/dist/server/composer-drafts.js +20 -2
  7. package/dist/server/conversation-read-tool.js +325 -0
  8. package/dist/server/dsh/dsh-agent-service.js +46 -11
  9. package/dist/server/file-archives.js +258 -0
  10. package/dist/server/file-transfer-routes.js +113 -0
  11. package/dist/server/files-service.js +123 -1
  12. package/dist/server/index.js +361 -14
  13. package/dist/server/marker-service.js +3 -1
  14. package/dist/server/model-admin.js +285 -36
  15. package/dist/server/plugins.js +152 -5
  16. package/dist/server/queue-utils.js +16 -0
  17. package/dist/server/schedule-agent-tool.js +240 -0
  18. package/dist/server/scheduler-tasks.js +414 -0
  19. package/dist/server/settings-service.js +76 -2
  20. package/dist/server/terminals.js +14 -1
  21. package/dist/server/tool-manager.js +16 -1
  22. package/dist/server/update-check.js +253 -19
  23. package/dist/server/webui-context.js +4 -0
  24. package/dist/server/ws-unknown-types.js +44 -0
  25. package/extensions/webui.ts +9 -2
  26. package/package.json +7 -3
  27. package/plugin-sdk/index.d.ts +4 -0
  28. package/plugin-sdk/index.mjs +9 -0
  29. package/plugins/catalog.json +11 -2
  30. package/web/dist/assets/TerminalPanel-BDbdLhpT.js +6 -0
  31. package/web/dist/assets/index-1f_DP8S3.js +380 -0
  32. package/web/dist/assets/index-DeUwDA-C.css +10 -0
  33. package/web/dist/index.html +2 -2
  34. package/web/dist/assets/TerminalPanel-CDH27dNP.js +0 -6
  35. package/web/dist/assets/index-CQg5A74_.js +0 -375
  36. package/web/dist/assets/index-DTEcxHWs.css +0 -10
@@ -26,7 +26,7 @@ import { Type } from "typebox";
26
26
  import { BgServerTracker } from "./bg-servers.js";
27
27
  import { checkAll as checkAllUpdates, collectTargets, compareVersions as compareSemver, resolveNpmRegistry, sortUpdateItems, } from "./update-check.js";
28
28
  import { hasActiveSubagentRun, hasPendingWaitSubscription, shouldRetainActive } from "./wait-subscription-scan.js";
29
- import { removeFirstOccurrence } from "./queue-utils.js";
29
+ import { removeQueuedByIndexOrText } from "./queue-utils.js";
30
30
  import { syncPluginToolsIntoSession } from "./plugins.js";
31
31
  import { SettingsService } from "./settings-service.js";
32
32
  import { GoalService } from "./goal-service.js";
@@ -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,8 @@ 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";
49
+ import { makeScheduleTools } from "./schedule-agent-tool.js";
48
50
  import { buildAttachmentMessages, parseModelSpec } from "./attachments.js";
49
51
  import { buildVisionBridgePrompt, findVisionModels, transcribeImages } from "./vision-bridge.js";
50
52
  import { BUILTIN_SOUL, DEFAULT_PROMPT_TEMPLATE, buildToolsSchemaText, renderPromptTemplate, resolveSectionTexts, } from "./prompt-composer.js";
@@ -773,6 +775,15 @@ function collectSessionAnchors(filePath, q, cap = 10) {
773
775
  export function piSessionsRoot() {
774
776
  return process.env.PI_CODING_AGENT_SESSION_DIR || undefined;
775
777
  }
778
+ /** Guardrail: only transcripts under the shared sessions root
779
+ * (<agentDir>/sessions/) may be opened/deleted/renamed — never arbitrary files.
780
+ * Shared by deleteSession/renameSession/switchSession so the open path cannot
781
+ * escape the confinement the write paths already enforce. */
782
+ export function isInsideSessionsDir(agentDir, targetPath) {
783
+ const abs = resolve(targetPath);
784
+ const sessionsRoot = resolve(agentDir, "sessions");
785
+ return abs.startsWith(sessionsRoot + sep);
786
+ }
776
787
  export class ClientSession {
777
788
  clientId;
778
789
  /** Set by AgentService.attach: reflects the SERVICE-wide quiesce flag
@@ -845,6 +856,8 @@ export class ClientSession {
845
856
  onConversationChanged = undefined;
846
857
  /** index.ts 注入:读取插件当前注册的 AI 工具(attach 时拷贝到每个新会话)。 */
847
858
  pluginToolsProvider = undefined;
859
+ /** index.ts 经 AgentService 注入:内置调度存储(定时任务 Agent 工具用;未注入时工具直接报错)。 */
860
+ schedulerStore = undefined;
848
861
  /** index.ts 注入:读取插件当前注册的斜杠命令(目录展示 + prompt 拦截执行)。 */
849
862
  pluginCommandsProvider = undefined;
850
863
  /** index.ts 注入:读取插件注册的常驻后台任务(并入 bg_servers 面板)。 */
@@ -1331,6 +1344,94 @@ export class ClientSession {
1331
1344
  return !!t && t.enabled;
1332
1345
  },
1333
1346
  };
1347
+ /** schedule_* 工具的数据宿主:全局调度存储+创建时刻 live 的 cwd/活动对话。 */
1348
+ scheduleToolHost() {
1349
+ return {
1350
+ store: () => this.schedulerStore,
1351
+ cwd: () => this.cwd,
1352
+ activeConversationId: () => this.activeId,
1353
+ };
1354
+ }
1355
+ /** conversation_read 工具的数据宿主:读本客户端的 conversation 体系 +
1356
+ * 落盘会话目录。运行中对话按 id(实时消息,含未落盘的);历史按 path,
1357
+ * 且必须是会话列表里的路径(任意文件不给读)。跨标签页的实时运行不在
1358
+ * this.convs 里——以落盘历史为准(工具 description 会告诉模型)。 */
1359
+ conversationReadHost() {
1360
+ return {
1361
+ listRunningConversations: () => {
1362
+ const out = [];
1363
+ for (const c of this.convs.values()) {
1364
+ let messageCount = 0;
1365
+ let isStreaming = false;
1366
+ try {
1367
+ messageCount = c.session.getSessionStats().totalMessages;
1368
+ isStreaming = c.session.isStreaming;
1369
+ }
1370
+ catch {
1371
+ // 会话替换中——报默认值
1372
+ }
1373
+ out.push({
1374
+ id: c.id,
1375
+ title: c.title,
1376
+ cwd: c.cwd,
1377
+ messageCount,
1378
+ isStreaming,
1379
+ isSubagent: !!c.isSubagent,
1380
+ ...(c.parentId ? { parentId: c.parentId } : {}),
1381
+ });
1382
+ }
1383
+ return out;
1384
+ },
1385
+ readRunningConversation: (id) => {
1386
+ const c = this.convs.get(id);
1387
+ if (!c)
1388
+ return undefined;
1389
+ let raw = [];
1390
+ try {
1391
+ raw = (c.session.messages ??
1392
+ c.session.agent.state.messages ??
1393
+ []);
1394
+ }
1395
+ catch {
1396
+ raw = [];
1397
+ }
1398
+ return { title: c.title, cwd: c.cwd, isSubagent: !!c.isSubagent, messages: raw.map(toTranscriptInput) };
1399
+ },
1400
+ listHistorySessions: async (scope, cwd) => {
1401
+ const infos = scope === "all"
1402
+ ? await SessionManager.listAll(piSessionsRoot())
1403
+ : await SessionManager.list(cwd || this.cwd, piSessionsRoot());
1404
+ return infos.map((s) => ({
1405
+ path: s.path,
1406
+ name: s.name,
1407
+ firstMessage: s.firstMessage,
1408
+ messageCount: s.messageCount,
1409
+ modified: s.modified.getTime(),
1410
+ cwd: s.cwd,
1411
+ }));
1412
+ },
1413
+ readHistorySession: async (path) => {
1414
+ const all = await SessionManager.listAll(piSessionsRoot());
1415
+ const hit = all.find((s) => resolve(s.path) === resolve(path));
1416
+ if (!hit)
1417
+ return undefined;
1418
+ try {
1419
+ if (statSync(hit.path).size > 16 * 1024 * 1024)
1420
+ return undefined;
1421
+ const text = readFileSync(hit.path, "utf8");
1422
+ return {
1423
+ title: hit.name || hit.firstMessage,
1424
+ cwd: hit.cwd,
1425
+ sessionPath: hit.path,
1426
+ messages: parseTranscriptLines(text),
1427
+ };
1428
+ }
1429
+ catch {
1430
+ return undefined;
1431
+ }
1432
+ },
1433
+ };
1434
+ }
1334
1435
  widgetsTimer = null;
1335
1436
  /** Model-stall watchdog interval (see startStallTimer). */
1336
1437
  stallTimer = null;
@@ -1711,9 +1812,9 @@ export class ClientSession {
1711
1812
  ...makePersistentTerminalTools(terminals, effectiveCwd, () => this.getLang()),
1712
1813
  // 不覆盖内置 edit 的独立宽松编辑工具(缩进不敏感匹配;开关看设置)。
1713
1814
  makeEditSoftTool(effectiveCwd, () => this.getLang()),
1714
- // 插件注册的 AI 工具(创建时刻的实时快照;后续注册经
1715
- // refreshPluginTools 动态补入已有会话)。
1716
- ...(this.pluginToolsProvider?.() ?? []).map(pluginToolToDefinition),
1815
+ // 插件注册的 AI 工具(创建时刻的实时快照,已按 disabledPluginTools 过滤;
1816
+ // 后续注册经 refreshPluginTools 动态补入已有会话)。
1817
+ ...this.enabledPluginToolDefs(),
1717
1818
  // 第一方子代理工具(spawn/get_result/steer/list/stop)。子代理会话
1718
1819
  // 也注册了它们,因此可自然嵌套派发。host 按 ownerId 包装:子代理的
1719
1820
  // 父对话 = 真正调用 spawn 的那个会话(本 runtime 所属会话),而不是
@@ -1740,6 +1841,16 @@ export class ClientSession {
1740
1841
  // 操作用户授权的页面 → page_response 回来。ownerId 语义同上(本 runtime
1741
1842
  // 所属会话,不是派发瞬间的 active)。
1742
1843
  makeBrowserPageTool(this, ownerId),
1844
+ // 别的对话读取(运行中含子代理 + 历史转录,只读):用户引用了别的
1845
+ // 对话(引用 chip / 粘过来的 id / “看看之前那个对话”)时用。子代理
1846
+ // 会话同样注册了它,可自然嵌套读取。不需要 ownerId——读的是本
1847
+ // 客户端的 conversation 体系与落盘历史,与派发者无关。
1848
+ makeConversationReadTool(this.conversationReadHost(), () => this.getLang()),
1849
+ // 定时唤醒三件套(schedule_task/list/cancel,issue #193):默认绑定
1850
+ // 发起对话(ownerId,无则活动对话),到期 steer 语义唤醒它;子代理
1851
+ // 会话同样注册(owner 即真正派发的父对话)。开关走统一工具 tab。
1852
+ // DSH 引擎无 customTool 注册面,不接。
1853
+ ...makeScheduleTools(this.scheduleToolHost(), ownerId, () => this.getLang()),
1743
1854
  ],
1744
1855
  });
1745
1856
  // 终端工具开关从创建起就生效(工具始终注册进注册表,只调活跃集)。
@@ -1949,12 +2060,13 @@ export class ClientSession {
1949
2060
  this.startWidgetsTimer();
1950
2061
  this.startStallTimer();
1951
2062
  }
1952
- /** Poll extension widgets so TUI-only overlays (e.g. rpiv-todo) stay live. */
2063
+ /** Poll extension widgets so TUI-only overlays (e.g. rpiv-todo) stay live.
2064
+ * Skips the refresh when no widgets are mounted — the common case. */
1953
2065
  startWidgetsTimer() {
1954
2066
  if (this.widgetsTimer)
1955
2067
  return;
1956
2068
  this.widgetsTimer = setInterval(() => {
1957
- if (!this.disposed)
2069
+ if (!this.disposed && this.webUi.hasWidgets())
1958
2070
  this.webUi.refresh();
1959
2071
  }, WIDGET_REFRESH_MS);
1960
2072
  }
@@ -3305,7 +3417,9 @@ export class ClientSession {
3305
3417
  return;
3306
3418
  }
3307
3419
  try {
3308
- const targets = collectTargets(this.agentDir, ClientSession.currentAppVersion());
3420
+ const targets = collectTargets(this.agentDir, ClientSession.currentAppVersion(), undefined, {
3421
+ projectCwd: this.conv?.cwd ?? this.cwd,
3422
+ });
3309
3423
  const items = sortUpdateItems(await checkAllUpdates(targets, undefined, () => this.getLang(), resolveNpmRegistry(this.agentDir)));
3310
3424
  this.updatesAllCache = { at: Date.now(), items };
3311
3425
  this.emit({ type: "update_status_all", items });
@@ -3500,6 +3614,15 @@ export class ClientSession {
3500
3614
  refreshProviderModels(providerId, reqId) {
3501
3615
  return this.modelAdmin.refreshProviderModels(providerId, reqId, () => this.getLang());
3502
3616
  }
3617
+ /** Force-refresh built-in providers' official pi.dev catalogs (bypass the
3618
+ * SDK's 4h freshness window) — refresh_builtin_result. */
3619
+ refreshBuiltinModels(reqId) {
3620
+ return this.modelAdmin.refreshBuiltinModels(reqId);
3621
+ }
3622
+ /** Append one model to a built-in provider's models.json overlay entry. */
3623
+ appendBuiltinModel(providerId, model, reqId) {
3624
+ return this.modelAdmin.appendBuiltinModel(providerId, model, reqId);
3625
+ }
3503
3626
  /** Copy a built-in provider into an editable custom-provider draft
3504
3627
  * (clone_provider_result) — lets the user run a second API key without
3505
3628
  * overwriting the built-in one. */
@@ -3681,6 +3804,10 @@ export class ClientSession {
3681
3804
  markerChanged = true;
3682
3805
  }
3683
3806
  await this.settingsSvc.set(rest);
3807
+ if (rest.disabledPluginTools !== undefined) {
3808
+ this.refreshPluginTools();
3809
+ this.flushSnapshot();
3810
+ }
3684
3811
  if (markerChanged) {
3685
3812
  // 标记开关影响 system prompt 引导,需重载生效(流式中则延迟)
3686
3813
  this.pushSettings();
@@ -3694,7 +3821,15 @@ export class ClientSession {
3694
3821
  await this.pushSlashCommands();
3695
3822
  this.pushSettings();
3696
3823
  }
3697
- catch { }
3824
+ catch (err) {
3825
+ console.error(`[settings] marker reload failed (conv ${this.activeId}):`, err);
3826
+ this.emit({
3827
+ type: "notice",
3828
+ level: "error",
3829
+ text: `设置应用失败:${err.message}`,
3830
+ textEn: `Failed to apply settings: ${err.message}`,
3831
+ });
3832
+ }
3698
3833
  }
3699
3834
  }
3700
3835
  }
@@ -3728,6 +3863,7 @@ export class ClientSession {
3728
3863
  * 所以这两条路径之后都要重放本方法(见 reloadSession/创建处)。 */
3729
3864
  applyToolGating(session) {
3730
3865
  applyAgentToolsGating(session, effectiveDisabledAgentTools(this.settingsSvc.current));
3866
+ this.syncPluginTools(session);
3731
3867
  // SDK 的 setActiveToolsByName 只改 agent.state.tools,不派发任何事件——门控后
3732
3868
  // 主动推一次快照,否则快照里的 tools 要等下一个 SDK 事件才对齐(会话空闲时永远
3733
3869
  // 等不到;回归:tests/terminal-smoke-test.mjs「agent exposes persistent terminal tools」)。
@@ -3736,11 +3872,17 @@ export class ClientSession {
3736
3872
  if (active && active.session === session)
3737
3873
  this.flushSnapshot();
3738
3874
  }
3739
- /** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除)。
3875
+ /** 当前启用的插件 AI 工具定义(provider 快照按 disabledPluginTools 过滤;
3876
+ * 未知/已卸载插件的禁用条目保留但不影响现有工具)。 */
3877
+ enabledPluginToolDefs() {
3878
+ const off = new Set(normalizeDisabledPluginTools(this.settingsSvc.current.disabledPluginTools));
3879
+ return (this.pluginToolsProvider?.() ?? []).filter((t) => !off.has(t.name)).map(pluginToolToDefinition);
3880
+ }
3881
+ /** 把插件 AI 工具同步进一个已存在的会话(新增/更新/移除;禁用工具同步移除)。
3740
3882
  * 实际 diff 逻辑在 plugins.ts 的 syncPluginToolsIntoSession(可单测)。 */
3741
3883
  syncPluginTools(session) {
3742
3884
  try {
3743
- const defs = (this.pluginToolsProvider?.() ?? []).map(pluginToolToDefinition);
3885
+ const defs = this.enabledPluginToolDefs();
3744
3886
  const next = syncPluginToolsIntoSession(session, defs, this.appliedPluginToolNames);
3745
3887
  if (next)
3746
3888
  this.appliedPluginToolNames = new Set(next);
@@ -3915,6 +4057,8 @@ export class ClientSession {
3915
4057
  const conv = this.conv;
3916
4058
  // 输入框内容被消费(发送/斜杠执行)→ 清掉该会话存过的草稿(best-effort)。
3917
4059
  // 快捷短语发送(不碰输入框)同样清:客户端发送成功后会把当前草稿重存回来。
4060
+ // clear() 同时记录 clear 时间戳水位:清掉之后才 landing 的旧 draft_update
4061
+ // (防抖延迟 / 跨 tab 陈旧写,ts <= 水位)由 store 直接丢弃,不复活。
3918
4062
  try {
3919
4063
  this.drafts.clear(conv.session.sessionId);
3920
4064
  }
@@ -4181,13 +4325,18 @@ export class ClientSession {
4181
4325
  this.flushSnapshot();
4182
4326
  }
4183
4327
  /**
4184
- * Remove ONE queued prompt text (the ✕ on a pending bubble) so it is neither
4328
+ * Remove ONE queued prompt (the ✕ on a pending bubble) so it is neither
4185
4329
  * shown nor eventually delivered. The pi SDK has no per-item queue API, so we
4186
- * drain the SDK queue (clearQueue), drop the target text and re-queue the rest
4330
+ * drain the SDK queue (clearQueue), drop the target item and re-queue the rest
4187
4331
  * in their original order; the SDK re-emits queue_update which re-syncs
4188
4332
  * conv.queueSteering / conv.queueFollowUp.
4333
+ *
4334
+ * `index` identifies WHICH bubble was clicked (same duplicate text can be
4335
+ * queued twice — text alone drops the wrong one). It is checked against the
4336
+ * item still at that position; on any mismatch we fall back to first-occurrence
4337
+ * text match (old clients, or the queue shifted between click and handling).
4189
4338
  */
4190
- async removeQueued(kind, text) {
4339
+ async removeQueued(kind, text, index) {
4191
4340
  const conv = this.conv;
4192
4341
  // Always-defined display mirrors; also the provenance of bubble rendering.
4193
4342
  const local = kind === "steer" ? conv.queueSteering : conv.queueFollowUp;
@@ -4200,17 +4349,19 @@ export class ClientSession {
4200
4349
  if (!s) {
4201
4350
  // Runtime not bound yet (fresh conversation) — drop the display mirror;
4202
4351
  // a later queue_update reconciles any SDK-side state.
4203
- const i = local.indexOf(text);
4204
- if (i >= 0)
4205
- local.splice(i, 1);
4352
+ const next = removeQueuedByIndexOrText(local, text, index);
4353
+ if (next.length !== local.length) {
4354
+ local.splice(0, local.length, ...next);
4355
+ }
4206
4356
  this.flushSnapshot();
4207
4357
  return;
4208
4358
  }
4209
4359
  const { steering, followUp } = s.clearQueue();
4210
- // 只移除第一条匹配:气泡 ✕ 对应的是「一条」消息,重复文本不能连带删除
4211
- // (旧实现用值过滤会把所有同文本项一起删掉,与本地显示镜像不一致)。
4212
- const keptSteering = kind === "steer" ? removeFirstOccurrence(steering, text) : steering;
4213
- const keptFollowUp = kind === "followUp" ? removeFirstOccurrence(followUp, text) : followUp;
4360
+ // 气泡 ✕ 对应的是「第几个气泡」(index),不是「哪段文本」:同一文本排队两次时
4361
+ // 按文本只会删掉第一条,点第二个气泡却删掉第一个。用 index 定位,位置对不上
4362
+ // (队列在点击与执行之间变化)或旧客户端没发 index 时回落到第一处文本匹配。
4363
+ const keptSteering = kind === "steer" ? removeQueuedByIndexOrText(steering, text, index) : steering;
4364
+ const keptFollowUp = kind === "followUp" ? removeQueuedByIndexOrText(followUp, text, index) : followUp;
4214
4365
  // Re-queue the survivors in original order. Guard each call so a single
4215
4366
  // failure can't leave the queue half-drained silently.
4216
4367
  for (const t of keptSteering) {
@@ -4247,7 +4398,8 @@ export class ClientSession {
4247
4398
  /** 存指定会话的未发送草稿(`draft_update` 入口,经 DispatchSession.saveDraft)。
4248
4399
  * 按消息自带的 sessionId 落键(不按 active 会话:切会话时的「离开刷盘」
4249
4400
  * 晚于服务端的切换到达)。空白新会话的转录还没落盘,但 id 内存里已有。
4250
- * 存完不推快照:同页的草稿本来就是自己打的;恢复走全量快照的 draft 字段。 */
4401
+ * 存完不推快照:同页的草稿本来就是自己打的;恢复走全量快照的 draft 字段。
4402
+ * 陈旧写由 ComposerDraftsStore 的 clear 水位丢弃(ts <= clearTs 不复活)。 */
4251
4403
  saveDraft(sessionId, text, ts) {
4252
4404
  try {
4253
4405
  if (!sessionId)
@@ -4736,8 +4888,25 @@ export class ClientSession {
4736
4888
  if (cwdChanged) {
4737
4889
  this.cwd = newCwd;
4738
4890
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, newCwd);
4739
- await this.restoreProjectProviderKeysForCwd(newCwd);
4740
- await this.restoreProjectModelForCwd(newCwd);
4891
+ // 模型/key 恢复不挡快照:后台做,带代际 guard(用户又切走就跳过),
4892
+ // 做完补一次 flush 刷新模型栏。
4893
+ {
4894
+ const convId = id;
4895
+ void (async () => {
4896
+ try {
4897
+ await this.restoreProjectProviderKeysForCwd(newCwd);
4898
+ if (this.disposed || this.activeId !== convId || this.cwd !== newCwd)
4899
+ return;
4900
+ await this.restoreProjectModelForCwd(newCwd);
4901
+ if (this.disposed || this.activeId !== convId || this.cwd !== newCwd)
4902
+ return;
4903
+ this.flushSnapshot();
4904
+ }
4905
+ catch {
4906
+ /* 静默:恢复失败保持会话默认 */
4907
+ }
4908
+ })();
4909
+ }
4741
4910
  // Mirror set_cwd's project-switch side-effects so the whole UI follows
4742
4911
  // the new workspace, not just the chat pane.
4743
4912
  try {
@@ -4748,7 +4917,7 @@ export class ClientSession {
4748
4917
  }
4749
4918
  this.stateStore.remember(this.clientId, newCwd);
4750
4919
  void this.pushProjects();
4751
- void this.refreshSessions();
4920
+ this.refreshSessionsOnSwitch();
4752
4921
  void this.listFiles(undefined);
4753
4922
  void this.listCommands();
4754
4923
  }
@@ -4817,6 +4986,16 @@ export class ClientSession {
4817
4986
  messageCount,
4818
4987
  isStreaming,
4819
4988
  isSubagent: !!conv.isSubagent,
4989
+ // 落盘会话才有文件(inMemory 子代理缺省):右键复制路径 / AI 按 path 读历史时用。
4990
+ ...(() => {
4991
+ try {
4992
+ const f = conv.session.sessionFile;
4993
+ return f ? { sessionFile: f } : {};
4994
+ }
4995
+ catch {
4996
+ return {};
4997
+ }
4998
+ })(),
4820
4999
  // 子代理带 error 标记:左栏红点提示(普通对话不参与)。
4821
5000
  ...(conv.isSubagent ? this.subagentRunOutcome(conv) : {}),
4822
5001
  parentId: conv.parentId,
@@ -4863,6 +5042,12 @@ export class ClientSession {
4863
5042
  */
4864
5043
  sessionInfosCache = null;
4865
5044
  static SESSION_INFO_CACHE_TTL = 3000;
5045
+ /** 最近项目列表缓存:pushProjects 的全量扫盘(SessionManager.listAll +
5046
+ * existsSync 逐个校验)昂贵,切项目/新对话/跨客户端通知时频繁触发 ——
5047
+ * TTL 内直接复用并把当前 cwd 合并进去,不反复扫盘。 */
5048
+ projectsCache = null;
5049
+ static PROJECTS_CACHE_TTL = 15_000;
5050
+ projectsInFlight = null;
4866
5051
  async loadSessionInfos() {
4867
5052
  const now = Date.now();
4868
5053
  const c = this.sessionInfosCache;
@@ -4885,6 +5070,13 @@ export class ClientSession {
4885
5070
  this.sessionsRequested = true;
4886
5071
  await this.pushSessions();
4887
5072
  }
5073
+ /** 切项目时的会话列表刷新:历史面板没打开过就不扫盘(只清缓存),打开过
5074
+ * 才重推 —— 首访切项目的转录解析不在关键路径上。 */
5075
+ refreshSessionsOnSwitch() {
5076
+ this.invalidateSessionInfos();
5077
+ if (this.sessionsRequested)
5078
+ void this.refreshSessions();
5079
+ }
4888
5080
  async pushSessions() {
4889
5081
  if (!this.sessionsRequested)
4890
5082
  return;
@@ -4916,6 +5108,7 @@ export class ClientSession {
4916
5108
  /** Remove an entry from the client's recent-project list (UI state only). */
4917
5109
  async removeProject(path) {
4918
5110
  this.stateStore.removeProject(this.clientId, path);
5111
+ this.invalidateProjectsCache();
4919
5112
  await this.pushProjects();
4920
5113
  }
4921
5114
  /** Permanently delete a persisted session transcript file (history list ✕).
@@ -4931,10 +5124,7 @@ export class ClientSession {
4931
5124
  async deleteSession(path) {
4932
5125
  try {
4933
5126
  const abs = resolve(path);
4934
- // Guardrail: only transcripts under the shared sessions root
4935
- // (<agentDir>/sessions/) may be deleted — never arbitrary files.
4936
- const sessionsRoot = resolve(this.agentDir, "sessions");
4937
- if (!abs.startsWith(sessionsRoot + sep)) {
5127
+ if (!isInsideSessionsDir(this.agentDir, abs)) {
4938
5128
  this.emit({
4939
5129
  type: "notice",
4940
5130
  level: "error",
@@ -5034,8 +5224,7 @@ export class ClientSession {
5034
5224
  if (!trimmed)
5035
5225
  return;
5036
5226
  const abs = resolve(path);
5037
- const sessionsRoot = resolve(this.agentDir, "sessions");
5038
- if (!abs.startsWith(sessionsRoot + sep)) {
5227
+ if (!isInsideSessionsDir(this.agentDir, abs)) {
5039
5228
  this.emit({
5040
5229
  type: "notice",
5041
5230
  level: "error",
@@ -5105,7 +5294,8 @@ export class ClientSession {
5105
5294
  this.emitConversations();
5106
5295
  }
5107
5296
  /** Dismiss 口径的「已结束子代理」:非 streaming 且无保留态(存活终端/
5108
- * 审查/后台唤醒等),与 dismissFinishedSubagents 的候选口径一致。 */
5297
+ * 审查/后台唤醒等),与 dismissFinishedSubagents 的候选口径一致。
5298
+ * issue #181:终端只看用户终端,残留 AI bash 不算(随移出一起释放)。 */
5109
5299
  isDismissableFinishedSubagent(conv) {
5110
5300
  let streaming = true;
5111
5301
  try {
@@ -5120,8 +5310,8 @@ export class ClientSession {
5120
5310
  reviewing: conv.goal.reviewing,
5121
5311
  wizardRunning: conv.wizardRunning,
5122
5312
  streaming: false,
5123
- // 与 displaceActive 同口径:只看“用过”的存活终端。
5124
- openTerminals: conv.terminals.countBlockingLive(),
5313
+ // Dismiss 口径:只看“用过”的用户终端(AI bash 不钉住,见上)。
5314
+ openTerminals: conv.terminals.countUserBlockingLive(),
5125
5315
  listed: false,
5126
5316
  promptedSinceActive: false,
5127
5317
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -5192,7 +5382,10 @@ export class ClientSession {
5192
5382
  });
5193
5383
  return;
5194
5384
  }
5195
- if (conv.terminals.countBlockingLive() > 0) {
5385
+ // issue #181:只看用户终端——AI bash(agentBash)是 agent 的内部执行记录,
5386
+ // 随对话一起释放(removeConversation 里 killAll),不得阻断移出;否则残留的
5387
+ // ai-bash-98/99 会把会话永久钉在列表里。用户亲手开且用过的终端仍拦截。
5388
+ if (conv.terminals.countUserBlockingLive() > 0) {
5196
5389
  this.emit({
5197
5390
  type: "notice",
5198
5391
  level: "warning",
@@ -5201,7 +5394,7 @@ export class ClientSession {
5201
5394
  });
5202
5395
  return;
5203
5396
  }
5204
- // 没动过的空 shell(点开终端 tab 自动建的那个)不拦截:随对话一起释放
5397
+ // 没动过的空 shell(点开终端 tab 自动建的那个)与 AI bash 不拦截:随对话一起释放
5205
5398
  // (removeConversation 里 killAll)。
5206
5399
  if (shouldRetainActive({
5207
5400
  reviewing: conv.goal.reviewing,
@@ -5455,8 +5648,8 @@ export class ClientSession {
5455
5648
  reviewing: conv.goal.reviewing,
5456
5649
  wizardRunning: conv.wizardRunning,
5457
5650
  streaming: false,
5458
- // 与 displaceActive 同口径:只看“用过”的存活终端。
5459
- openTerminals: conv.terminals.countBlockingLive(),
5651
+ // Dismiss 口径:只看“用过”的用户终端(issue #181,AI bash 不钉住)。
5652
+ openTerminals: conv.terminals.countUserBlockingLive(),
5460
5653
  listed: false,
5461
5654
  promptedSinceActive: false,
5462
5655
  hasActiveSubagentRun: () => hasActiveSubagentRun({ sessionId: conv.session.sessionFile }),
@@ -5526,6 +5719,16 @@ export class ClientSession {
5526
5719
  let openedTerminals = null;
5527
5720
  try {
5528
5721
  const targetPath = resolve(path);
5722
+ if (!isInsideSessionsDir(this.agentDir, targetPath)) {
5723
+ this.emit({
5724
+ type: "notice",
5725
+ level: "error",
5726
+ text: "只能打开会话目录中的对话记录",
5727
+ textEn: "Only transcripts inside the session directory can be opened",
5728
+ });
5729
+ this.flushSnapshot();
5730
+ return;
5731
+ }
5529
5732
  // A session may already be open in the running-conversation map. Reuse it
5530
5733
  // instead of creating a second writer for the same JSONL transcript.
5531
5734
  for (const conv of this.convs.values()) {
@@ -5747,34 +5950,77 @@ export class ClientSession {
5747
5950
  * opened before the recent-list feature existed still show up).
5748
5951
  */
5749
5952
  async pushProjects() {
5750
- try {
5751
- const saved = this.stateStore.get(this.clientId);
5752
- const removedProjects = new Set(this.stateStore.getRemovedProjects(this.clientId));
5753
- const map = new Map();
5754
- for (const p of saved.projects)
5755
- map.set(p.path, p.lastUsed);
5756
- const all = await SessionManager.listAll(piSessionsRoot());
5757
- for (const s of all) {
5758
- if (s.cwd) {
5759
- const t = s.modified.getTime();
5760
- const prev = map.get(s.cwd);
5761
- if (prev === undefined || t > prev)
5762
- map.set(s.cwd, t);
5763
- }
5953
+ const now = Date.now();
5954
+ const cached = this.projectsCache;
5955
+ // TTL 命中:直接复用(把当前 cwd 合并进去,刚 remember 的新项目也可见)。
5956
+ if (cached && now - cached.at < ClientSession.PROJECTS_CACHE_TTL) {
5957
+ this.emit({ type: "projects", projects: this.withCurrentCwd(cached.projects, now) });
5958
+ return;
5959
+ }
5960
+ // 已有扫描在跑:搭车等它,不要并发扫两遍盘。
5961
+ if (this.projectsInFlight) {
5962
+ try {
5963
+ const projects = await this.projectsInFlight;
5964
+ if (projects)
5965
+ this.emit({ type: "projects", projects: this.withCurrentCwd(projects, Date.now()) });
5764
5966
  }
5765
- // Only keep directories that still exist — a deleted/unmounted workspace
5766
- // is useless in the picker. Tombstoned entries (explicitly removed by
5767
- // the user) stay hidden even though session files still mention them.
5768
- const projects = [...map.entries()]
5769
- .filter(([path]) => !removedProjects.has(path) && existsSync(path))
5770
- .map(([path, lastUsed]) => ({ path, lastUsed }))
5771
- .sort((a, b) => b.lastUsed - a.lastUsed)
5772
- .slice(0, 20);
5773
- this.emit({ type: "projects", projects });
5967
+ catch {
5968
+ /* 首发扫描已自行 emit 错误结果,这里不再补 */
5969
+ }
5970
+ return;
5774
5971
  }
5775
- catch {
5776
- this.emit({ type: "projects", projects: [] });
5972
+ const run = (async () => {
5973
+ try {
5974
+ const saved = this.stateStore.get(this.clientId);
5975
+ const removedProjects = new Set(this.stateStore.getRemovedProjects(this.clientId));
5976
+ const map = new Map();
5977
+ for (const p of saved.projects)
5978
+ map.set(p.path, p.lastUsed);
5979
+ const all = await SessionManager.listAll(piSessionsRoot());
5980
+ for (const s of all) {
5981
+ if (s.cwd) {
5982
+ const t = s.modified.getTime();
5983
+ const prev = map.get(s.cwd);
5984
+ if (prev === undefined || t > prev)
5985
+ map.set(s.cwd, t);
5986
+ }
5987
+ }
5988
+ // Only keep directories that still exist — a deleted/unmounted workspace
5989
+ // is useless in the picker. Tombstoned entries (explicitly removed by
5990
+ // the user) stay hidden even though session files still mention them.
5991
+ const projects = [...map.entries()]
5992
+ .filter(([path]) => !removedProjects.has(path) && existsSync(path))
5993
+ .map(([path, lastUsed]) => ({ path, lastUsed }))
5994
+ .sort((a, b) => b.lastUsed - a.lastUsed)
5995
+ .slice(0, 20);
5996
+ this.projectsCache = { at: Date.now(), projects };
5997
+ this.emit({ type: "projects", projects });
5998
+ return projects;
5999
+ }
6000
+ catch {
6001
+ this.emit({ type: "projects", projects: [] });
6002
+ return null;
6003
+ }
6004
+ finally {
6005
+ this.projectsInFlight = null;
6006
+ }
6007
+ })();
6008
+ this.projectsInFlight = run;
6009
+ await run;
6010
+ }
6011
+ /** 缓存命中时把当前 cwd 并进去:命中则刷新 lastUsed 重排,未命中则补到首位
6012
+ * (remember 刚写入的新项目在 TTL 窗口内也可见,不必等下一次扫盘)。 */
6013
+ withCurrentCwd(projects, now) {
6014
+ if (projects.some((p) => p.path === this.cwd)) {
6015
+ return projects
6016
+ .map((p) => (p.path === this.cwd && p.lastUsed < now ? { ...p, lastUsed: now } : p))
6017
+ .sort((a, b) => b.lastUsed - a.lastUsed);
5777
6018
  }
6019
+ return [{ path: this.cwd, lastUsed: now }, ...projects].slice(0, 20);
6020
+ }
6021
+ /** 最近项目缓存失效(用户显式移除项目后,下一次推送必须重扫)。 */
6022
+ invalidateProjectsCache() {
6023
+ this.projectsCache = null;
5778
6024
  }
5779
6025
  /** List a workspace directory (relative to the configured cwd). */
5780
6026
  async listFiles(relPath) {
@@ -5849,8 +6095,19 @@ export class ClientSession {
5849
6095
  async copyEntry(src, destDir, move) {
5850
6096
  return this.files.copyEntry(src, destDir, move);
5851
6097
  }
5852
- async makeDir(relPath) {
5853
- return this.files.makeDir(relPath);
6098
+ /** 文件树右键菜单:在系统资源管理器中定位(issue #187)。 */
6099
+ async revealEntry(path) {
6100
+ return this.files.revealEntry(path);
6101
+ }
6102
+ /** 文件树右键菜单:用系统默认应用打开文件(issue #187)。 */
6103
+ async openDefaultEntry(path) {
6104
+ return this.files.openDefaultEntry(path);
6105
+ }
6106
+ async makeDir(relPath, setAsCwd = false) {
6107
+ const created = await this.files.makeDir(relPath);
6108
+ if (created && setAsCwd) {
6109
+ await this.setCwd(created);
6110
+ }
5854
6111
  }
5855
6112
  async cycleModel() {
5856
6113
  try {
@@ -5965,6 +6222,15 @@ export class ClientSession {
5965
6222
  this.removeConversation(displaced.id);
5966
6223
  }
5967
6224
  else {
6225
+ // 冷切换的 runtime 创建要 1~2s(扫技能/扩展)—— 先回一条 ack +
6226
+ // 快照,点击看起来不再 frozen;落地后再推第二次全量。
6227
+ this.emit({
6228
+ type: "notice",
6229
+ level: "info",
6230
+ text: `正在切换到工作目录:${abs}`,
6231
+ textEn: `Switching to directory: ${abs}`,
6232
+ });
6233
+ this.flushSnapshot();
5968
6234
  // First visit to this project: resume its most recent session —
5969
6235
  // unless that transcript is streaming on another client (#145):
5970
6236
  // default-opening it would strand the tab on a conversation it
@@ -6019,8 +6285,25 @@ export class ClientSession {
6019
6285
  this.conv.lastActiveAt = Date.now();
6020
6286
  this.cwd = abs;
6021
6287
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
6022
- await this.restoreProjectProviderKeysForCwd(abs);
6023
- await this.restoreProjectModelForCwd(abs);
6288
+ // 模型/key 恢复不挡快照:后台做,带切换代际 guard(用户又切走就跳过,
6289
+ // 否则会把旧项目的 key 套到新对话上),做完补一次 flush 刷新模型栏。
6290
+ {
6291
+ const convId = this.activeId;
6292
+ void (async () => {
6293
+ try {
6294
+ await this.restoreProjectProviderKeysForCwd(abs);
6295
+ if (this.disposed || this.activeId !== convId || this.cwd !== abs)
6296
+ return;
6297
+ await this.restoreProjectModelForCwd(abs);
6298
+ if (this.disposed || this.activeId !== convId || this.cwd !== abs)
6299
+ return;
6300
+ this.flushSnapshot();
6301
+ }
6302
+ catch {
6303
+ /* 静默:恢复失败保持会话默认 */
6304
+ }
6305
+ })();
6306
+ }
6024
6307
  // 工作区跟随型插件(编辑器文件树等)同步切根。
6025
6308
  try {
6026
6309
  this.onCwdChanged?.(abs, this.roots);
@@ -6042,7 +6325,7 @@ export class ClientSession {
6042
6325
  text: `已切换到工作目录:${abs}`,
6043
6326
  textEn: `Switched to directory: ${abs}`,
6044
6327
  });
6045
- void this.refreshSessions();
6328
+ this.refreshSessionsOnSwitch();
6046
6329
  void this.listFiles(undefined);
6047
6330
  // Commands are per-project (.pi/commands.json in the current cwd).
6048
6331
  void this.listCommands();
@@ -6260,6 +6543,8 @@ export class AgentService {
6260
6543
  pluginBgTasksProvider = undefined;
6261
6544
  /** index.ts 注入:停止插件任务(kill_background_server with taskId)。 */
6262
6545
  pluginStopBgTask = undefined;
6546
+ /** index.ts 注入:内置调度存储(attach 时拷贝到每个新会话,供 schedule_* 工具)。 */
6547
+ schedulerStore = undefined;
6263
6548
  clients = new Map();
6264
6549
  /** Quiesce (draining) state — the service refuses NEW work (prompts, forks,
6265
6550
  * session resumes, new clients) so a deploy/upgrade/backup can stop cleanly
@@ -6353,6 +6638,33 @@ export class AgentService {
6353
6638
  }
6354
6639
  return undefined;
6355
6640
  }
6641
+ /** issue #193:定时任务唤醒发起对话。逐个客户端找持有方,用 steer 语义投递
6642
+ * (运行时插队、未跑时普通投递,不切用户当前对话);都找不到回 ok:false,
6643
+ * 调用方(index.ts executor)回落无头执行。quiesced 时直接拒绝。 */
6644
+ async wakeConversation(id, text) {
6645
+ if (!id || !text.trim())
6646
+ return { ok: false, error: "唤醒目标或文本为空" };
6647
+ if (this.quiesced)
6648
+ return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
6649
+ for (const cs of this.clients.values()) {
6650
+ try {
6651
+ const r = await cs.steerOwnConversation(id, text);
6652
+ if (r) {
6653
+ try {
6654
+ cs.flushSnapshot();
6655
+ }
6656
+ catch {
6657
+ // 推送失败不影响已投递的唤醒
6658
+ }
6659
+ return { ok: true, conversationId: id };
6660
+ }
6661
+ }
6662
+ catch {
6663
+ // 单客户端坏了继续找下一个
6664
+ }
6665
+ }
6666
+ return { ok: false, error: "目标对话不在运行中(已关闭或服务重启过)" };
6667
+ }
6356
6668
  /** issue #145:别处在某 cwd 下正在跑的对话(同项目并行感知用,不含请求方)。 */
6357
6669
  listProjectRunners(cwd, excludeClientId) {
6358
6670
  const out = [];
@@ -6452,6 +6764,89 @@ export class AgentService {
6452
6764
  void cs.prompt(text);
6453
6765
  return { conversationId: before, clientId };
6454
6766
  }
6767
+ /** 内置定时任务的无头执行(issue #184,server/scheduler-tasks.ts 的 executor)。
6768
+ * 每个任务独立伪客户端 `scheduler:<taskId>`(专属会话连续、无浏览器也能跑);
6769
+ * cwd 按任务配置 pin 住(不存在即失败,不默默跑错目录);可选模型/思考强度
6770
+ * 在投递前应用(失败即返回错误,不回落,避免账单/效果与预期不符)。
6771
+ * fire-and-forget 投递后等待运行结束(最长 10 分钟轮询),回填真实 outcome
6772
+ * (成功/失败/耗时/会话 id)供历史记录与通知使用;超时按失败记录(运行本身
6773
+ * 不中止,继续在后台跑完)。 */
6774
+ async chatFromScheduler(task) {
6775
+ const safe = String(task.id ?? "task").replace(/[^A-Za-z0-9_-]/g, "") || "task";
6776
+ const clientId = `scheduler:${safe}`;
6777
+ const text = String(task.prompt ?? "");
6778
+ if (!text.trim())
6779
+ return { ok: false, error: "触发指令为空" };
6780
+ if (this.quiesced)
6781
+ return { ok: false, error: "服务器正忙(quiesced),请稍后重试" };
6782
+ const cwd = String(task.cwd ?? "").trim();
6783
+ try {
6784
+ if (!cwd || !statSync(cwd).isDirectory())
6785
+ throw new Error("not-a-dir");
6786
+ }
6787
+ catch {
6788
+ return { ok: false, error: `目标项目不存在或不是目录:${cwd || "(空)"}` };
6789
+ }
6790
+ try {
6791
+ const cs = await this.attach(clientId, () => { });
6792
+ if (cs.cwd !== cwd)
6793
+ await cs.setCwd(cwd);
6794
+ const model = String(task.model ?? "").trim();
6795
+ if (model) {
6796
+ try {
6797
+ await cs.setModel(model);
6798
+ }
6799
+ catch (err) {
6800
+ return { ok: false, error: `切换模型失败(${model}):${err.message}` };
6801
+ }
6802
+ }
6803
+ const thinking = String(task.thinkingLevel ?? "").trim();
6804
+ if (thinking) {
6805
+ try {
6806
+ cs.setThinking(thinking);
6807
+ }
6808
+ catch (err) {
6809
+ return { ok: false, error: `切换思考强度失败(${thinking}):${err.message}` };
6810
+ }
6811
+ }
6812
+ const conversationId = cs.readConversationForPlugins()?.conversationId ?? "";
6813
+ void cs.prompt(`[定时任务] ${text}`);
6814
+ // 等待运行结束:每 2s 轮询,最长 10 分钟。超时按失败记录(运行继续)。
6815
+ const deadline = Date.now() + 10 * 60 * 1000;
6816
+ for (;;) {
6817
+ await new Promise((r) => setTimeout(r, 2000));
6818
+ let streaming = false;
6819
+ let lastError;
6820
+ try {
6821
+ const snap = cs.readConversationForPlugins();
6822
+ streaming = snap?.isStreaming === true;
6823
+ const msgs = snap?.messages ?? [];
6824
+ for (let i = msgs.length - 1; i >= 0; i--) {
6825
+ const m = msgs[i];
6826
+ if (m.role === "assistant" && m.errorMessage) {
6827
+ lastError = m.errorMessage;
6828
+ break;
6829
+ }
6830
+ if (m.role === "assistant")
6831
+ break;
6832
+ }
6833
+ }
6834
+ catch {
6835
+ streaming = false;
6836
+ }
6837
+ if (!streaming) {
6838
+ if (lastError)
6839
+ return { ok: false, conversationId: conversationId || undefined, error: lastError };
6840
+ return { ok: true, conversationId: conversationId || undefined };
6841
+ }
6842
+ if (Date.now() >= deadline)
6843
+ return { ok: false, conversationId: conversationId || undefined, error: "运行超时(10 分钟),仍在后台继续" };
6844
+ }
6845
+ }
6846
+ catch (err) {
6847
+ return { ok: false, error: err.message };
6848
+ }
6849
+ }
6455
6850
  /** 插件直调模型(host.llm.complete 的落地):孤立无工具的一次性补全。
6456
6851
  * 不建对话、不进历史、不碰任何会话状态;花费走用户自己的模型额度。
6457
6852
  * quiesced 时拒绝;无客户端时用进程 cwd + 默认模型照常跑。 */
@@ -6559,6 +6954,7 @@ export class AgentService {
6559
6954
  cs.notifyExternalClients = (msg) => this.notifyClientsExcept(clientId, msg);
6560
6955
  cs.onRunningChanged = () => this.pokeExternalRunning(clientId);
6561
6956
  cs.steerConversationElsewhere = (id, text) => this.steerElsewhere(clientId, id, text);
6957
+ cs.schedulerStore = this.schedulerStore;
6562
6958
  // Make sure the restored/default workspace appears in the project list.
6563
6959
  this.stateStore.remember(clientId, cwd);
6564
6960
  if (cwd !== this.cwd) {