pi-web-ui 0.110.0 → 0.111.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 (64) hide show
  1. package/bin/frp-manager.mjs +85 -7
  2. package/dist/server/agent-formatters.js +10 -6
  3. package/dist/server/agent-service-daemon.js +27 -9
  4. package/dist/server/agent-service.js +140 -24
  5. package/dist/server/attachments.js +114 -31
  6. package/dist/server/canvas/canvas-agent-tool.js +587 -0
  7. package/dist/server/canvas/canvas-cards.js +144 -0
  8. package/dist/server/canvas/canvas-dispatch.js +155 -0
  9. package/dist/server/canvas/canvas-orchestrator.js +1027 -0
  10. package/dist/server/canvas/canvas-store.js +260 -0
  11. package/dist/server/client-id-utils.js +2 -2
  12. package/dist/server/client-state.js +24 -0
  13. package/dist/server/context-budget.js +6 -3
  14. package/dist/server/dsh/dsh-agent-service.js +115 -9
  15. package/dist/server/dsh/dsh-client.js +10 -1
  16. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  17. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  18. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  19. package/dist/server/durable/durable-agent-service.js +3 -0
  20. package/dist/server/file-transfer-routes.js +8 -2
  21. package/dist/server/files-service.js +10 -2
  22. package/dist/server/index.js +137 -4
  23. package/dist/server/marker-service.js +3 -1
  24. package/dist/server/markers/marker.js +45 -4
  25. package/dist/server/markers/registry.js +31 -0
  26. package/dist/server/message-window.js +6 -3
  27. package/dist/server/office-parse.js +394 -7
  28. package/dist/server/plugin-api-catalog.js +6 -0
  29. package/dist/server/plugins.js +97 -20
  30. package/dist/server/preset-fields.js +35 -1
  31. package/dist/server/preset-share.js +3 -0
  32. package/dist/server/prompt-assembler.js +7 -1
  33. package/dist/server/prompt-composer.js +66 -36
  34. package/dist/server/protocol-version.js +1 -1
  35. package/dist/server/remote-ssh-service.js +16 -4
  36. package/dist/server/settings-service.js +19 -3
  37. package/dist/server/tool-manager.js +30 -0
  38. package/dist/server/univer-service.js +448 -0
  39. package/dist/server/universal/drivers/claude-code.js +19 -2
  40. package/dist/server/universal/universal-attachments.js +5 -0
  41. package/dist/server/universal/universal-service.js +5 -0
  42. package/dist/server/universal/universal-session.js +28 -12
  43. package/dist/server/update-check.js +90 -5
  44. package/dist/server/workspace-snapshot.js +33 -2
  45. package/docs/dsh-engine.md +497 -0
  46. package/package.json +5 -4
  47. package/plugin-sdk/index.d.ts +17 -0
  48. package/plugin-sdk/index.mjs +5 -0
  49. package/plugins/catalog.json +22 -0
  50. package/themes/aetheris.css +114 -0
  51. package/themes/bases/obsidian-base.css +216 -0
  52. package/themes/md-preview.css +113 -0
  53. package/themes/wallpaper-flow.css +182 -0
  54. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-BiUNySMA.js} +2 -2
  55. package/web/dist/assets/index-B0ajS__T.js +697 -0
  56. package/web/dist/assets/index-BHik5WGG.css +1 -0
  57. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  58. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  59. package/web/dist/index.html +4 -4
  60. package/web/dist/sw.js +1 -1
  61. package/web/dist/assets/es-DIDZppIF.js +0 -2
  62. package/web/dist/assets/index-DwInT7-a.css +0 -1
  63. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  64. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -12,7 +12,7 @@
12
12
  */
13
13
 
14
14
  import { spawn, spawnSync } from "node:child_process";
15
- import { randomBytes } from "node:crypto";
15
+ import { createHash, randomBytes } from "node:crypto";
16
16
  import { chmodSync, createWriteStream, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
17
17
  import { homedir, tmpdir } from "node:os";
18
18
  import { dirname, join } from "node:path";
@@ -212,8 +212,6 @@ TMP_DIR="$(mktemp -d /tmp/frps-install-XXXXXX)"
212
212
  echo "📦 架构: linux_\${FRP_ARCH},正在下载 \${TAR_NAME}..."
213
213
 
214
214
  DOWNLOAD_URLS=(
215
- "https://ghfast.top/https://github.com/fatedier/frp/releases/download/v\${FRP_VERSION}/\${TAR_NAME}"
216
- "https://ghproxy.net/https://github.com/fatedier/frp/releases/download/v\${FRP_VERSION}/\${TAR_NAME}"
217
215
  "https://github.com/fatedier/frp/releases/download/v\${FRP_VERSION}/\${TAR_NAME}"
218
216
  )
219
217
 
@@ -235,6 +233,38 @@ if [ "$DOWNLOAD_SUCCESS" -ne 1 ]; then
235
233
  exit 1
236
234
  fi
237
235
 
236
+ echo "🔐 校验下载文件 SHA256..."
237
+ for cu in \
238
+ "https://github.com/fatedier/frp/releases/download/v\${FRP_VERSION}/frp_\${FRP_VERSION}_sha256_checksums.txt" \
239
+ "https://github.com/fatedier/frp/releases/download/v\${FRP_VERSION}/frp_sha256_checksums.txt"; do
240
+ if curl -fsSL --connect-timeout 10 -m 30 "$cu" -o "$TMP_DIR/checksums.txt" 2>/dev/null; then
241
+ break
242
+ fi
243
+ done
244
+ if [ -s "$TMP_DIR/checksums.txt" ]; then
245
+ EXPECTED=""
246
+ while read -r h f; do
247
+ fname="\${f#*}"
248
+ if [ "$fname" = "$TAR_NAME" ] && [ "\${#h}" -eq 64 ]; then
249
+ EXPECTED="$h"
250
+ break
251
+ fi
252
+ done < "$TMP_DIR/checksums.txt"
253
+ if [ -n "$EXPECTED" ]; then
254
+ ACTUAL="$(sha256sum "$TMP_DIR/$TAR_NAME" | awk '{print $1}')"
255
+ if [ "$ACTUAL" != "$EXPECTED" ]; then
256
+ echo "❌ SHA256 校验失败,下载文件可能被篡改,已中止安装" >&2
257
+ rm -rf "$TMP_DIR"
258
+ exit 1
259
+ fi
260
+ echo "✅ SHA256 校验通过"
261
+ else
262
+ echo "⚠ 未在官方 checksums 中找到 \${TAR_NAME},跳过校验"
263
+ fi
264
+ else
265
+ echo "⚠ 未获取到官方 checksums 文件,跳过校验"
266
+ fi
267
+
238
268
  echo "📂 解压并安装到 /usr/local/bin/frps..."
239
269
  tar -zxvf "$TMP_DIR/$TAR_NAME" -C "$TMP_DIR" >/dev/null
240
270
  EXTRACTED_DIR="$(find "$TMP_DIR" -maxdepth 1 -type d -name "frp_*" | head -n 1)"
@@ -304,11 +334,37 @@ echo "==========================================================================
304
334
 
305
335
  /** 候选下载 URL 列表 */
306
336
  export function getFrpDownloadUrls(version, archiveName) {
307
- return [
308
- `https://github.com/fatedier/frp/releases/download/v${version}/${archiveName}`,
309
- `https://ghfast.top/https://github.com/fatedier/frp/releases/download/v${version}/${archiveName}`,
310
- `https://ghproxy.net/https://github.com/fatedier/frp/releases/download/v${version}/${archiveName}`,
337
+ // 只使用官方 GitHub 发布源:第三方代理镜像(ghfast.top/ghproxy.net 等)可能被
338
+ // 接管换包,配合 root 安装即供应链投毒。需要加速请自行配置 HTTP(S) 代理。
339
+ return [`https://github.com/fatedier/frp/releases/download/v${version}/${archiveName}`];
340
+ }
341
+
342
+ /** 从官方 release 的 checksums 文件解析指定归档的 SHA256(两种文件名都试)。 */
343
+ export async function fetchFrpSha256(version, archiveName) {
344
+ const candidates = [
345
+ `https://github.com/fatedier/frp/releases/download/v${version}/frp_${version}_sha256_checksums.txt`,
346
+ `https://github.com/fatedier/frp/releases/download/v${version}/frp_sha256_checksums.txt`,
311
347
  ];
348
+ for (const url of candidates) {
349
+ try {
350
+ const res = await fetch(url, { redirect: "follow", signal: AbortSignal.timeout(30_000) });
351
+ if (!res.ok) continue;
352
+ const lines = (await res.text()).split(/\r?\n/);
353
+ for (const line of lines) {
354
+ const parts = line.trim().split(/\s+/);
355
+ if (parts.length >= 2 && /^[0-9a-f]{64}$/.test(parts[0]) && parts[1].replace(/^\*+/, "") === archiveName) {
356
+ return parts[0];
357
+ }
358
+ }
359
+ } catch {
360
+ // 尝试下一个候选
361
+ }
362
+ }
363
+ return null;
364
+ }
365
+
366
+ function sha256File(filePath) {
367
+ return createHash("sha256").update(readFileSync(filePath)).digest("hex");
312
368
  }
313
369
 
314
370
  /** 从多个镜像源下载文件 */
@@ -445,6 +501,28 @@ export async function ensureLocalFrpc({ dataDir, version = DEFAULT_FRP_VERSION,
445
501
 
446
502
  try {
447
503
  await downloadFileWithFallback(urls, tmpArchive);
504
+ // 供应链守卫:无论来自哪个源,下载物必须与官方 SHA256 一致,否则拒绝安装。
505
+ const expectedSha = await fetchFrpSha256(version, arcName);
506
+ if (!expectedSha) {
507
+ rmSync(tmpArchive, { force: true });
508
+ throw new Error(
509
+ pick(
510
+ `无法获取 ${arcName} 的官方 SHA256 校验和,已拒绝无校验安装(请升级 FRP_VERSION 或检查网络)`,
511
+ `Official SHA256 checksum for ${arcName} unavailable; refusing unsigned install`,
512
+ ),
513
+ );
514
+ }
515
+ const actualSha = sha256File(tmpArchive);
516
+ if (actualSha !== expectedSha) {
517
+ rmSync(tmpArchive, { force: true });
518
+ throw new Error(
519
+ pick(
520
+ `SHA256 校验失败(期望 ${expectedSha},实际 ${actualSha}),下载文件可能被篡改,已中止安装`,
521
+ `SHA256 mismatch (expected ${expectedSha}, got ${actualSha}); download may be tampered, install aborted`,
522
+ ),
523
+ );
524
+ }
525
+ console.log(pick(`✅ SHA256 校验通过`, `✅ SHA256 verified`));
448
526
  console.log(pick(`📦 下载完成,正在解压提取 ${binName}...`, `📦 Download complete, extracting ${binName}...`));
449
527
 
450
528
  if (isZip) {
@@ -207,16 +207,20 @@ export function modelKeyOf(session) {
207
207
  return null;
208
208
  return `${m.provider}/${m.id}`;
209
209
  }
210
- /** 会话当前模型的上下文窗口(未知时 0):live 统计优先,模型定义回落。 */
210
+ /** 会话当前模型的上下文窗口(未知时 0)。
211
+ * live 统计与模型定义取较大值:换模型前的快照(128000 缺省窗口常见)
212
+ * 不能盖住已经装上的更大配置窗口,否则软上限会被判成非法并回退到 16K reserve。 */
211
213
  export function contextWindowOf(session) {
214
+ let live = 0;
212
215
  try {
213
- const live = session?.getSessionStats?.()?.contextUsage?.contextWindow;
214
- if (typeof live === "number" && live > 0)
215
- return Math.floor(live);
216
+ const raw = session?.getSessionStats?.()?.contextUsage?.contextWindow;
217
+ if (typeof raw === "number" && raw > 0)
218
+ live = Math.floor(raw);
216
219
  }
217
220
  catch {
218
- // 会话未就绪 → 回落模型定义。
221
+ // 会话未就绪 → 只用模型定义。
219
222
  }
220
223
  const def = session?.model?.contextWindow;
221
- return typeof def === "number" && def > 0 ? Math.floor(def) : 0;
224
+ const modelWindow = typeof def === "number" && def > 0 ? Math.floor(def) : 0;
225
+ return Math.max(live, modelWindow);
222
226
  }
@@ -1123,7 +1123,12 @@ export class AgentService {
1123
1123
  // 也无需事后拆 runtime)。之前只拦 running:空闲持有照样恢复出双
1124
1124
  // writer,两边轮流发送分叉历史。其他客户端不存在时不扫目录。
1125
1125
  let createOpts;
1126
- if (this.clients.size > 0) {
1126
+ const isPseudo = AgentService.isPseudoClientId(clientId);
1127
+ if (isPseudo) {
1128
+ // 伪客户端(插件无头调用、定时调度任务、Canvas专用通道等):严禁自动恢复并占有工作区历史会话,强制空白
1129
+ createOpts = { blank: true };
1130
+ }
1131
+ else if (this.clients.size > 0) {
1127
1132
  try {
1128
1133
  const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore.dataDir, cwd);
1129
1134
  const recentPath = await findMostRecentSessionFileFast(sessionBaseDir, cwd);
@@ -1224,6 +1229,11 @@ export class AgentService {
1224
1229
  for (const cs of this.clients.values())
1225
1230
  void cs.pushSlashCommands();
1226
1231
  }
1232
+ /** 插件内联标记变化时由 index.ts 触发:重推各客户端 markers 与设置状态。 */
1233
+ applyPluginMarkers() {
1234
+ for (const cs of this.clients.values())
1235
+ cs.refreshPluginMarkers();
1236
+ }
1227
1237
  /** 插件常驻后台任务变化时由 index.ts 触发:重推各客户端的 bg_servers。 */
1228
1238
  refreshBackgroundServers() {
1229
1239
  for (const cs of this.clients.values())
@@ -1234,14 +1244,22 @@ export class AgentService {
1234
1244
  const cs = this.clients.get(clientId);
1235
1245
  if (cs) {
1236
1246
  cs.detachSink(send);
1237
- // 最后一个 sink 断开 = 该客户端不再在线 → 它的行从「另一处」变成「另一处
1238
- // (离线)」。立刻让其他客户端重推一次补上离线标记;宽限期
1239
- // (OFFLINE_ROW_TTL_MS)到期后再推一次,行随之消失(issue #291 的
1240
- // 「残骸不永久占位」仍然成立)。
1241
- if (!AgentService.isPseudoClientId(clientId) && cs.sinkCount() === 0) {
1242
- this.offlineSince.set(clientId, Date.now());
1243
- this.pokeExternalRunning(clientId);
1244
- this.armOfflineRowExpiry(clientId, cs);
1247
+ if (cs.sinkCount() === 0) {
1248
+ if (clientId.startsWith("canvas:") || clientId.startsWith("canvas-")) {
1249
+ // Canvas 辅助连接一旦关闭,立即从客户端池回收并释放资源,绝不残留
1250
+ this.clients.delete(clientId);
1251
+ void cs.dispose().catch(() => { });
1252
+ return;
1253
+ }
1254
+ // 最后一个 sink 断开 = 该客户端不再在线 → 它的行从「另一处」变成「另一处
1255
+ // (离线)」。立刻让其他客户端重推一次补上离线标记;宽限期
1256
+ // (OFFLINE_ROW_TTL_MS)到期后再推一次,行随之消失(issue #291 的
1257
+ // 「残骸不永久占位」仍然成立)。
1258
+ if (!AgentService.isPseudoClientId(clientId)) {
1259
+ this.offlineSince.set(clientId, Date.now());
1260
+ this.pokeExternalRunning(clientId);
1261
+ this.armOfflineRowExpiry(clientId, cs);
1262
+ }
1245
1263
  }
1246
1264
  }
1247
1265
  else if (this.pending.has(clientId)) {
@@ -101,6 +101,7 @@ import { makeLspTool } from "./lsp-tool.js";
101
101
  import { makeMcpManageTool } from "./mcp-agent-tool.js";
102
102
  import { makeSandboxTool } from "./sandbox-tool.js";
103
103
  import { makeWorktreeTool } from "./worktree-tool.js";
104
+ import { makeCanvasTool } from "./canvas/canvas-agent-tool.js";
104
105
  import { getWorktreeContext, removeWorktree, normalizeWirePath } from "./worktree-service.js";
105
106
  import { sameSessionFile } from "./scheduler-tasks.js";
106
107
  import { buildAttachmentMessages, findTurnBaseEntryId, parseModelSpec } from "./attachments.js";
@@ -420,7 +421,7 @@ export class ClientSession {
420
421
  customType: "terminal-bash-done",
421
422
  content: [{ type: "text", text }],
422
423
  display: true,
423
- })
424
+ }, { deliverAs: "nextTurn" })
424
425
  .catch(() => { });
425
426
  }
426
427
  }
@@ -581,6 +582,10 @@ export class ClientSession {
581
582
  });
582
583
  }
583
584
  }
585
+ // 换模型之后同步重算软上限。setModel 的 model_select 不进 session.subscribe,
586
+ // 首轮压缩检查会用到换模型前的 reserve(1M 窗口算出的 74 万泄漏到小窗口上,
587
+ // 触发点变成负数,上下文到几万 token 就压)。
588
+ this.refreshCompactionOverride(conv);
584
589
  // 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
585
590
  // 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
586
591
  // SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
@@ -930,7 +935,17 @@ export class ClientSession {
930
935
  if (!session || !this.lazyLoadingOn())
931
936
  return empty;
932
937
  try {
933
- const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME);
938
+ // PATCH-F1: 目录排除 MCP deferred 工具——「恒定全集」在 MCP deferred 后会把
939
+ // 数百个工具摘要常驻 tools 节(实测 318 工具时 2042→20854 chars,+75K tok/轮)。
940
+ // deferred 工具按设计不声明给模型,其发现走 mcp 网关(searchTools)与
941
+ // tool_search 的 BM25 元数据(零 schema 注入);目录里列出它们违背 deferred
942
+ // 语义且每轮全价。目录其余部分仍恒定(MCP deferred 集合会话内固定),不影响前缀缓存。
943
+ const mcpDeferred = new Set((session.getAllTools?.() ?? [])
944
+ .filter((t) => typeof t?.namespace?.name === "string" &&
945
+ t.namespace.name.startsWith("mcp__") &&
946
+ (t.exposure ?? "codemode") === "deferred")
947
+ .map((t) => t.name));
948
+ const names = this.allowedToolNames(session, conv).filter((n) => n !== LOAD_TOOLS_TOOL_NAME && !mcpDeferred.has(n));
934
949
  const snippets = {};
935
950
  const signatures = {};
936
951
  for (const name of names) {
@@ -1180,6 +1195,9 @@ export class ClientSession {
1180
1195
  contextFiles: src.contextFiles,
1181
1196
  skills: effectiveSkills,
1182
1197
  skillsFullText: showSkills ? normalizeSkillList(this.settingsSvc.current.skillsFullText) : [],
1198
+ skillsCatalogMaxDesc: this.settingsSvc.current.skillsCatalogMaxDesc,
1199
+ skillsCatalogShowLocation: this.settingsSvc.current.skillsCatalogShowLocation,
1200
+ skillsCatalogBudget: this.settingsSvc.current.skillsCatalogBudget,
1183
1201
  };
1184
1202
  }
1185
1203
  /** skill 全文注入({{skills}} 全文模式):最好努力读名单里技能的文件正文。 */
@@ -1191,12 +1209,16 @@ export class ClientSession {
1191
1209
  * 仅在完全默认且全功能 standard 状态下返回 undefined 让 SDK 拼装。 */
1192
1210
  renderMainCompose(src) {
1193
1211
  const preset = src.preset ?? this.conv?.agentPreset ?? this.settingsSvc.current.defaultAgentPreset ?? "standard";
1212
+ const showSkills = presetShowsSkillCatalog(preset);
1213
+ const effectiveSkills = showSkills ? this.fillSkillContents(src.skills) : [];
1194
1214
  return renderMainCompose(this.composeInputs(src), {
1195
1215
  promptTemplate: this.settingsSvc.current.promptTemplate,
1196
1216
  promptOverrides: this.settingsSvc.current.promptOverrides,
1197
1217
  preset,
1198
1218
  disabledToolCount: effectiveDisabledAgentTools(this.settingsSvc.current).length,
1199
1219
  isLazy: src.lazy,
1220
+ hasSkills: effectiveSkills.length > 0,
1221
+ hasSkillsFullText: (this.settingsSvc.current.skillsFullText?.length ?? 0) > 0,
1200
1222
  });
1201
1223
  }
1202
1224
  /** 从指定会话(缺省 = 活跃会话)收集工具/资源快照 → 一次算出 ①各来源默认(自动)
@@ -2566,6 +2588,12 @@ export class ClientSession {
2566
2588
  await this.refreshWorktreeInfo();
2567
2589
  },
2568
2590
  }, () => this.getLang()),
2591
+ // 画布流水线编辑工具(canvas:增删改查/重排/运行/调试;新节点 cwd 跟随当前项目)。
2592
+ makeCanvasTool({
2593
+ dataDir: this.stateStore.dataDir,
2594
+ lang: () => this.getLang(),
2595
+ getCwd: () => (ownerId ? this.convs.get(ownerId)?.cwd : undefined) ?? effectiveCwd,
2596
+ }),
2569
2597
  ].map((t) =>
2570
2598
  // 目标审查闸门在最外层(理由最贴合此刻);插件工具也在这个数组里,
2571
2599
  // 创建时注册的同样被闸门覆盖(后续动态补入的走 syncPluginTools,与
@@ -5968,18 +5996,20 @@ export class ClientSession {
5968
5996
  }
5969
5997
  }
5970
5998
  }
5971
- /** 会话模型变化时重放该会话的软上限覆盖。SDK 恢复历史会话的模型
5999
+ /** 会话模型或窗口变化时重放该会话的软上限覆盖。SDK 恢复历史会话的模型
5972
6000
  * (findInitialModel)与 /model 命令都不经过 pi-web-ui 的 setModel
5973
6001
  * 路径,注入过的 reserve 会停留在旧模型窗口的换算值上——例如默认
5974
6002
  * 模型(1M 窗口)算出 748576,泄漏到 500K 窗口的会话后压缩触发点
5975
- * 变成负数,上下文几万 token 就被反复压缩。onEvent 每个事件比对
5976
- * 一次 model key(O(1) 字符串比较),变化才重放。 */
6003
+ * 变成负数,上下文几万 token 就被反复压缩。onEvent 比对模型 key 与窗口,
6004
+ * 有变化才重放。setModel 本身不发 session 事件,子代理创建路径另有同步重算。 */
5977
6005
  reapplySoftCapIfModelChanged(conv) {
5978
6006
  try {
5979
6007
  const key = modelKeyOf(conv.session);
5980
- if (conv.lastModelKey === key)
6008
+ const contextWindow = contextWindowOf(conv.session);
6009
+ if (conv.lastModelKey === key && conv.lastContextWindow === contextWindow)
5981
6010
  return;
5982
6011
  conv.lastModelKey = key;
6012
+ conv.lastContextWindow = contextWindow;
5983
6013
  if (key)
5984
6014
  this.applyCompactionOverrideForConv(conv, this.settingsSvc.current);
5985
6015
  }
@@ -5987,6 +6017,18 @@ export class ClientSession {
5987
6017
  // 会话未就绪或已释放 → 留给创建/换模型路径与后续事件重试。
5988
6018
  }
5989
6019
  }
6020
+ /** setModel 只向扩展发 model_select,不走 session.subscribe,
6021
+ * onEvent 里的重放赶不上首轮压缩检查。换完模型后必须同步重算。 */
6022
+ refreshCompactionOverride(conv) {
6023
+ try {
6024
+ this.applyCompactionOverrideForConv(conv, this.settingsSvc.current);
6025
+ conv.lastModelKey = modelKeyOf(conv.session);
6026
+ conv.lastContextWindow = contextWindowOf(conv.session);
6027
+ }
6028
+ catch {
6029
+ // 会话未就绪 → 首个 SDK 事件仍会走 reapplySoftCapIfModelChanged。
6030
+ }
6031
+ }
5990
6032
  /** 当前活动对话的生效软上限(快照底栏标记线用;null = 关闭/未知)。 */
5991
6033
  activeSoftCap(contextWindow) {
5992
6034
  try {
@@ -6550,10 +6592,12 @@ export class ClientSession {
6550
6592
  }
6551
6593
  // 延迟加载(默认开):未加载的已登记工具一律当「临时禁用」——与用户禁用名单 /
6552
6594
  // 计划模式闸门走同一条门控链,不做第二套机制。加载只是把名字从这份名单里拿出来。
6595
+ let loadedNames = [];
6553
6596
  const lazy = this.lazyLoadingOn();
6554
6597
  if (lazy) {
6555
6598
  try {
6556
6599
  const loaded = this.lazyLoadedFor(session, this.sessionHasTranscript(session));
6600
+ loadedNames = [...loaded];
6557
6601
  for (const name of lazyLoadingDisabledTools(session.getAllTools().map((t) => t.name), loaded)) {
6558
6602
  disabled.add(name);
6559
6603
  }
@@ -6567,7 +6611,10 @@ export class ClientSession {
6567
6611
  }
6568
6612
  applyAgentToolsGating(session, [...disabled], targetPreset, {
6569
6613
  // load_tools 不在任何预设白名单里,又必须在延迟加载开启时永远可用(ask 预设本来就无工具,不强加;非延迟加载模式不激活)。
6570
- forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME] : [],
6614
+ // 显式 load_tools 加载过的名字一并强制激活:PATCH-B1 门控会无条件剔除
6615
+ // exposure≠direct 的 MCP 工具(连 deferred 的也在内),若这里不把它们
6616
+ // 加回活跃集,会复现 #652 的死路变体——「已加载且目录可见,但永不活跃」。
6617
+ forceActive: lazy && targetPreset !== "ask" ? [LOAD_TOOLS_TOOL_NAME, ...loadedNames] : [],
6571
6618
  });
6572
6619
  const ownerId = conv?.id;
6573
6620
  syncSubagentOverride(session, disabled.has("subagent"), () => ownerId
@@ -7117,6 +7164,11 @@ export class ClientSession {
7117
7164
  for (const conv of this.convs.values())
7118
7165
  this.syncPluginTools(conv.session);
7119
7166
  }
7167
+ /** index.ts 经 pluginMgr.onMarkersChanged 触发:刷新客户端 markers 设置与小部件。 */
7168
+ refreshPluginMarkers() {
7169
+ this.settingsSvc.push();
7170
+ this.markerSvc.pushOverlay(this.activeId);
7171
+ }
7120
7172
  async applySettingsReload() {
7121
7173
  // 兼容旧入口:reload + 刷目录在宿主回调里完成
7122
7174
  return this.settingsSvc.applyRuntime();
@@ -7283,6 +7335,10 @@ export class ClientSession {
7283
7335
  * (随主对话一起搬)。activity = 该对话最近一次活跃时间(离线行的宽限期判定用,
7284
7336
  * 见 OFFLINE_ROW_TTL_MS)。 */
7285
7337
  streamingSummariesAll() {
7338
+ // 画布专用客户端(CanvasStudio)绝不参与聊天会话列表感知,杜绝向 elsewhere 暴露任何条目
7339
+ if (this.clientId?.startsWith("canvas:") || this.clientId?.startsWith("canvas-")) {
7340
+ return [];
7341
+ }
7286
7342
  const out = [];
7287
7343
  const seenFiles = new Set();
7288
7344
  for (const conv of this.convs.values()) {
@@ -7466,8 +7522,8 @@ export class ClientSession {
7466
7522
  catch {
7467
7523
  // ignore
7468
7524
  }
7525
+ const s = this.session;
7469
7526
  try {
7470
- const s = this.session;
7471
7527
  // Native slash commands (see NATIVE_COMMANDS) are executed here and
7472
7528
  // never reach the SDK. Extension / skill / template commands fall
7473
7529
  // through — AgentSession.prompt() handles those itself.
@@ -7846,18 +7902,21 @@ export class ClientSession {
7846
7902
  }
7847
7903
  }
7848
7904
  else {
7905
+ // 空闲提问:必须携带 deliverAs: "nextTurn",将附件(图片、文件引用、视觉证据等)
7906
+ // 注入 SDK 的 _pendingNextTurnMessages,并在随后的 s.prompt() 中由 SDK 作为上下文消息
7907
+ // 传递给 LLM 并落盘(fixes #667)。严禁在此清空 _pendingNextTurnMessages。
7849
7908
  for (const aside of asides) {
7850
- await s.sendCustomMessage(aside.message);
7909
+ await s.sendCustomMessage(aside.message, { deliverAs: "nextTurn" });
7851
7910
  }
7852
7911
  if (asides.length > 0) {
7853
7912
  this.flushSnapshot();
7854
7913
  }
7855
- if (Array.isArray(s._pendingNextTurnMessages)) {
7856
- s._pendingNextTurnMessages = [];
7857
- }
7858
7914
  }
7859
7915
  if (promptAc.signal.aborted) {
7860
7916
  conv.activePromptAc = undefined;
7917
+ if (Array.isArray(s._pendingNextTurnMessages)) {
7918
+ s._pendingNextTurnMessages = [];
7919
+ }
7861
7920
  // #492:同上——前置阶段的 abort 也必须给回执,不能静默黑洞。
7862
7921
  this.emit({
7863
7922
  type: "notice",
@@ -7924,6 +7983,9 @@ export class ClientSession {
7924
7983
  }
7925
7984
  catch (err) {
7926
7985
  conv.activePromptAc = undefined;
7986
+ if (Array.isArray(conv.session?._pendingNextTurnMessages)) {
7987
+ conv.session._pendingNextTurnMessages = [];
7988
+ }
7927
7989
  this.emit({
7928
7990
  type: "notice",
7929
7991
  level: "error",
@@ -9400,8 +9462,21 @@ export class ClientSession {
9400
9462
  }
9401
9463
  /** Switch the ACTIVE conversation without interrupting any other chat. */
9402
9464
  async switchConversation(id) {
9403
- if (!this.convs.has(id) || id === this.activeId)
9465
+ if (id === this.activeId)
9466
+ return;
9467
+ if (!this.convs.has(id)) {
9468
+ this.emit({
9469
+ type: "transition_progress",
9470
+ kind: "conversation",
9471
+ target: id,
9472
+ phase: "error",
9473
+ progress: 100,
9474
+ text: "对话已不存在或已结束",
9475
+ textEn: "Conversation no longer exists or has finished",
9476
+ });
9477
+ this.flushSnapshot();
9404
9478
  return;
9479
+ }
9405
9480
  const displaced = this.displaceActive();
9406
9481
  this.activeId = id;
9407
9482
  const newCwd = this.conv.cwd;
@@ -9418,10 +9493,26 @@ export class ClientSession {
9418
9493
  this.emitConversations();
9419
9494
  this.goalSvc.emitGoalStatus();
9420
9495
  this.pushTerminals();
9421
- // The switched-to conversation has its own runtime (own resource cache).
9422
- void this.pushSlashCommands();
9423
9496
  if (cwdChanged) {
9424
9497
  this.cwd = newCwd;
9498
+ this.files.unwatchGit();
9499
+ this.roots = this.stateStore.getWorkspaceRoots(this.clientId, newCwd);
9500
+ }
9501
+ // 核心:快照与完成信号优先!在繁重的工作区扫描/设置推送之前第一时间发往
9502
+ // 浏览器,0ms 呈现对话内容与状态,绝不让前端在空转中等待文件树与设置大包。
9503
+ this.flushSnapshot();
9504
+ this.emit({
9505
+ type: "transition_progress",
9506
+ kind: "conversation",
9507
+ target: id,
9508
+ phase: "done",
9509
+ progress: 100,
9510
+ text: "对话切换完成",
9511
+ textEn: "Conversation switched",
9512
+ });
9513
+ // 工作区跟随副作用(命令/项目/会话/文件树/插件通知/设置)异步推进,不阻塞会话呈现
9514
+ void this.pushSlashCommands();
9515
+ if (cwdChanged) {
9425
9516
  // 模型/key 恢复不挡快照:后台做,带代际 guard(用户又切走就跳过),
9426
9517
  // 做完补一次 flush 刷新模型栏。
9427
9518
  {
@@ -9448,7 +9539,6 @@ export class ClientSession {
9448
9539
  // 当前打开对话变了 → 插件重拉(轨迹视图切会话后即刷新,不等轮询)。
9449
9540
  this.notifyConversationChanged();
9450
9541
  this.pushSettings();
9451
- this.flushSnapshot();
9452
9542
  }
9453
9543
  /** 左栏「运行的对话」的展示口径(issue #140)。
9454
9544
  *
@@ -9798,11 +9888,11 @@ export class ClientSession {
9798
9888
  await this.pushSessions();
9799
9889
  }
9800
9890
  /** 切项目时的会话列表刷新:sessionInfosCache 已按 cwdKey 隔离(30s TTL),
9801
- * 若刚刚在 setCwd 并行预热过(<2s 内)则直接复用预热结果推送,不再清空重扫。 */
9891
+ * 若在 TTL 内则直接复用缓存推送,不再全盘清空重扫。 */
9802
9892
  refreshSessionsOnSwitch() {
9803
9893
  const cwdKey = normalizePathKey(this.cwd);
9804
9894
  const cached = ClientSession.sessionInfosCache.get(cwdKey);
9805
- if (!cached || Date.now() - cached.at > 2_000) {
9895
+ if (!cached || Date.now() - cached.at > ClientSession.SESSION_INFO_CACHE_TTL) {
9806
9896
  ClientSession.sessionInfosCache.delete(cwdKey);
9807
9897
  }
9808
9898
  if (this.sessionsRequested)
@@ -10899,6 +10989,7 @@ export class ClientSession {
10899
10989
  // 计划模式的写类/旁路工具剥离对重开的会话同样生效。下同(forkSession/setCwd)。
10900
10990
  this.applyToolGating(conv.session, conv.agentPreset);
10901
10991
  this.cwd = targetCwd;
10992
+ this.files.unwatchGit();
10902
10993
  // 打开的历史会话可能属于另一个项目 —— 工作区跟随面(roots/文件树/
10903
10994
  // 历史列表/命令目录/最近项目)必须跟着切,否则 UI 停在旧项目。
10904
10995
  this.applyCwdSideEffects(targetCwd);
@@ -11164,6 +11255,14 @@ export class ClientSession {
11164
11255
  if (targetConv.session.isStreaming) {
11165
11256
  await targetConv.session.abort();
11166
11257
  }
11258
+ // 回滚开始时的会话长度:物理还原前复核,若期间已有新回合写入则跳过还原保新改动(#697)
11259
+ let sessionLenAtRollback = -1;
11260
+ try {
11261
+ sessionLenAtRollback = targetConv.session.agent.state.messages.length;
11262
+ }
11263
+ catch {
11264
+ // best effort
11265
+ }
11167
11266
  // 重置分支 leaf 到目标 entry.id
11168
11267
  targetConv.session.sessionManager.branch(entry.id);
11169
11268
  const branchedContext = targetConv.session.sessionManager.buildSessionContext();
@@ -11214,18 +11313,35 @@ export class ClientSession {
11214
11313
  // 查找最贴近该 entry 的快照(按 entryId 或 <= entryTs 的最后一份快照)
11215
11314
  const matched = findMatchingWorkspaceSnapshot(targetConv.workspaceSnapshots ?? [], entry.id, entryTs);
11216
11315
  if (matched) {
11217
- const res = await restoreWorkspaceSnapshot(targetConv.cwd, matched.snapshotRef);
11218
- if (res.success) {
11219
- workspaceRestored = true;
11316
+ let sessionLenNow = -1;
11317
+ try {
11318
+ sessionLenNow = targetConv.session.agent.state.messages.length;
11220
11319
  }
11221
- else {
11320
+ catch {
11321
+ // best effort
11322
+ }
11323
+ if (sessionLenAtRollback >= 0 && sessionLenNow > sessionLenAtRollback) {
11222
11324
  this.emit({
11223
11325
  type: "notice",
11224
11326
  level: "warning",
11225
- text: `会话已回滚,但工作区物理文件还原失败:${res.error}`,
11226
- textEn: `Session rolled back, but workspace file restore failed: ${res.error}`,
11327
+ text: "检测到回滚期间已有新对话写入,为保护新改动已跳过工作区物理文件还原(会话历史仍已回滚)。",
11328
+ textEn: "New messages arrived during rollback; skipped workspace file restore to protect new changes (history still rolled back).",
11227
11329
  });
11228
11330
  }
11331
+ else {
11332
+ const res = await restoreWorkspaceSnapshot(targetConv.cwd, matched.snapshotRef);
11333
+ if (res.success) {
11334
+ workspaceRestored = true;
11335
+ }
11336
+ else {
11337
+ this.emit({
11338
+ type: "notice",
11339
+ level: "warning",
11340
+ text: `会话已回滚,但工作区物理文件还原失败:${res.error}`,
11341
+ textEn: `Session rolled back, but workspace file restore failed: ${res.error}`,
11342
+ });
11343
+ }
11344
+ }
11229
11345
  }
11230
11346
  else {
11231
11347
  this.emit({