pi-web-ui 0.103.2 → 0.104.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 (41) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/dist/server/agent-formatters.js +18 -2
  3. package/dist/server/agent-service-daemon.js +4 -3
  4. package/dist/server/agent-service.js +773 -181
  5. package/dist/server/compaction-markers.js +111 -3
  6. package/dist/server/delegate-mode.js +2 -0
  7. package/dist/server/dispatch-domain-handlers.js +25 -0
  8. package/dist/server/dsh/dsh-agent-service.js +265 -11
  9. package/dist/server/goal-review-gate.js +2 -0
  10. package/dist/server/goal-service.js +59 -2
  11. package/dist/server/index.js +1 -0
  12. package/dist/server/markers-list-tool.js +1 -1
  13. package/dist/server/market-service.js +36 -9
  14. package/dist/server/mcp-agent-tool.js +164 -0
  15. package/dist/server/mcp-manager.js +182 -0
  16. package/dist/server/plan-mode.js +3 -0
  17. package/dist/server/plugin-api-catalog.js +24 -0
  18. package/dist/server/plugins.js +113 -0
  19. package/dist/server/preset-share.js +52 -1
  20. package/dist/server/remote-ssh-service.js +90 -25
  21. package/dist/server/sandbox-service.js +705 -0
  22. package/dist/server/sandbox-tool.js +365 -0
  23. package/dist/server/session-parser.js +48 -21
  24. package/dist/server/subagent-helpers.js +32 -1
  25. package/dist/server/terminals.js +210 -10
  26. package/dist/server/tool-manager.js +24 -0
  27. package/dist/server/webui-context.js +16 -2
  28. package/dist/server/workspace-snapshot.js +51 -13
  29. package/package.json +1 -1
  30. package/plugin-sdk/index.d.ts +39 -0
  31. package/plugin-sdk/index.mjs +14 -0
  32. package/plugins/catalog.json +110 -0
  33. package/themes/zhujian-dark.css +711 -0
  34. package/themes/zhujian.css +760 -0
  35. package/web/dist/assets/{TerminalPanel-DQFDRz0A.js → TerminalPanel-28naZdcs.js} +1 -1
  36. package/web/dist/assets/index-DbGGBf5I.js +680 -0
  37. package/web/dist/assets/index-RqIdFOsh.css +1 -0
  38. package/web/dist/index.html +2 -2
  39. package/web/dist/sw.js +1 -1
  40. package/web/dist/assets/index-CYQdZEbx.css +0 -1
  41. package/web/dist/assets/index-aGRL6x3h.js +0 -680
@@ -18,7 +18,7 @@
18
18
  * - looksLikeChainCorruption:识别链损坏报错,供 open 重试分支用。
19
19
  */
20
20
  import { randomUUID } from "node:crypto";
21
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
21
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
22
22
  import { reorderEntriesForMainBranch } from "./session-branch.js";
23
23
  export const COMPACTION_PENDING_TYPE = "pi-web-ui/compaction-pending";
24
24
  export const COMPACTION_DONE_TYPE = "pi-web-ui/compaction-done";
@@ -50,6 +50,37 @@ function parentIdOf(entry) {
50
50
  const p = entry.parentId;
51
51
  return typeof p === "string" ? p : null;
52
52
  }
53
+ /**
54
+ * 对超长 message 行(>512 字节,例如数十 KB~数 MB 的 toolResult / assistant 回复)
55
+ * 仅从前 260 个字符提取拓扑校验所需的头字段(type/id/parentId/timestamp),
56
+ * 避免在预检健康文件时对整行大载荷执行全量 JSON.parse;若该行真触发了 id/parentId
57
+ * 改写(dirty=true),写回前再按需解析完整 JSON。
58
+ */
59
+ function parseFastMessageSlotHeader(line) {
60
+ if (line.length <= 512)
61
+ return null;
62
+ const head = line.slice(0, 260);
63
+ if (!/"type"\s*:\s*"message"/.test(head))
64
+ return null;
65
+ const idMatch = /"id"\s*:\s*"([^"\\]+)"/.exec(head);
66
+ if (!idMatch)
67
+ return null;
68
+ let parentId = null;
69
+ const parentStrMatch = /"parentId"\s*:\s*"([^"\\]*)"/.exec(head);
70
+ if (parentStrMatch) {
71
+ parentId = parentStrMatch[1];
72
+ }
73
+ else if (!/"parentId"\s*:\s*null/.test(head)) {
74
+ return null;
75
+ }
76
+ const tsMatch = /"timestamp"\s*:\s*"([^"\\]+)"/.exec(head);
77
+ return {
78
+ type: "message",
79
+ id: idMatch[1],
80
+ parentId,
81
+ ...(tsMatch ? { timestamp: tsMatch[1] } : {}),
82
+ };
83
+ }
53
84
  /**
54
85
  * 修复会话转录文本。健康文件原样返回(changed=false,text === raw)。
55
86
  * 有坏必修:pending 残留→删(子节点旁路);重复 id→首个保留、其余改名,
@@ -69,6 +100,17 @@ export function repairSessionTranscript(raw) {
69
100
  const slots = lines.map((line) => {
70
101
  if (!line.trim())
71
102
  return { raw: line, entry: null, removed: false, dirty: false, finalId: null };
103
+ const fastEntry = parseFastMessageSlotHeader(line);
104
+ if (fastEntry) {
105
+ return {
106
+ raw: line,
107
+ entry: fastEntry,
108
+ removed: false,
109
+ dirty: false,
110
+ partial: true,
111
+ finalId: fastEntry.id,
112
+ };
113
+ }
72
114
  try {
73
115
  const parsed = JSON.parse(line);
74
116
  if (typeof parsed === "object" && parsed !== null) {
@@ -282,16 +324,79 @@ export function repairSessionTranscript(raw) {
282
324
  for (const s of slots) {
283
325
  if (s.removed)
284
326
  continue;
285
- out.push(s.dirty && s.entry ? JSON.stringify(s.entry) : s.raw);
327
+ if (s.dirty && s.entry) {
328
+ if (s.partial) {
329
+ try {
330
+ const full = JSON.parse(s.raw);
331
+ full.id = s.entry.id;
332
+ full.parentId = s.entry.parentId;
333
+ out.push(JSON.stringify(full));
334
+ continue;
335
+ }
336
+ catch {
337
+ /* fallback */
338
+ }
339
+ }
340
+ out.push(JSON.stringify(s.entry));
341
+ }
342
+ else {
343
+ out.push(s.raw);
344
+ }
286
345
  }
287
346
  result.text = out.join("\n");
288
347
  return result;
289
348
  }
349
+ /**
350
+ * 已校验健康的会话文件指纹缓存(filePath -> `${mtimeMs}:${size}`,LRU 上限 512):
351
+ * switchSession 每次打开历史会话都会先调 repairSessionFile;若文件自上次校验后
352
+ * mtime 与 size 均未变,直接跳过整文件同步读取与全量 JSON.parse(耗时从数十毫秒降至 0.01ms)。
353
+ */
354
+ const healthyTranscriptCache = new Map();
355
+ const HEALTHY_TRANSCRIPT_CACHE_MAX = 512;
356
+ function rememberHealthyTranscript(filePath) {
357
+ try {
358
+ const st = statSync(filePath);
359
+ const sig = `${st.mtimeMs}:${st.size}`;
360
+ healthyTranscriptCache.delete(filePath);
361
+ healthyTranscriptCache.set(filePath, sig);
362
+ while (healthyTranscriptCache.size > HEALTHY_TRANSCRIPT_CACHE_MAX) {
363
+ const oldest = healthyTranscriptCache.keys().next();
364
+ if (oldest.done)
365
+ break;
366
+ healthyTranscriptCache.delete(oldest.value);
367
+ }
368
+ }
369
+ catch {
370
+ /* best effort */
371
+ }
372
+ }
290
373
  /**
291
374
  * 落盘版修复:健康文件只读不写;坏文件先写 <原名>.bak(已存在则保留最早那份,
292
375
  * 不覆盖),再写回修复文本。读失败/写失败返回 null(调用方按原错误继续抛)。
293
376
  */
294
377
  export function repairSessionFile(filePath) {
378
+ try {
379
+ const st = statSync(filePath);
380
+ const sig = `${st.mtimeMs}:${st.size}`;
381
+ if (healthyTranscriptCache.get(filePath) === sig) {
382
+ healthyTranscriptCache.delete(filePath);
383
+ healthyTranscriptCache.set(filePath, sig);
384
+ return {
385
+ text: "",
386
+ changed: false,
387
+ removedPending: 0,
388
+ renamedIds: 0,
389
+ rewiredParents: 0,
390
+ cyclesBroken: 0,
391
+ interrupted: false,
392
+ file: filePath,
393
+ backup: null,
394
+ };
395
+ }
396
+ }
397
+ catch {
398
+ return null;
399
+ }
295
400
  let raw;
296
401
  try {
297
402
  raw = readFileSync(filePath, "utf8");
@@ -300,13 +405,16 @@ export function repairSessionFile(filePath) {
300
405
  return null;
301
406
  }
302
407
  const r = repairSessionTranscript(raw);
303
- if (!r.changed)
408
+ if (!r.changed) {
409
+ rememberHealthyTranscript(filePath);
304
410
  return { ...r, file: filePath, backup: null };
411
+ }
305
412
  try {
306
413
  const bak = `${filePath}.bak`;
307
414
  if (!existsSync(bak))
308
415
  writeFileSync(bak, raw, "utf8");
309
416
  writeFileSync(filePath, r.text, "utf8");
417
+ rememberHealthyTranscript(filePath);
310
418
  return { ...r, file: filePath, backup: bak };
311
419
  }
312
420
  catch {
@@ -50,6 +50,8 @@ const BLOCKED_TOOLS = new Set([
50
50
  // 代码求值(eval 沙箱可写真实文件系统 —— 主对话只审阅不施工,#436)
51
51
  "eval",
52
52
  "codemode",
53
+ "mcp_manage",
54
+ "sandbox",
53
55
  "format",
54
56
  "prettier",
55
57
  "lint_fix",
@@ -47,6 +47,31 @@ export function handleFileMessage(msg, cs) {
47
47
  case "set_workspace_roots":
48
48
  void cs.setWorkspaceRoots(msg.roots);
49
49
  return true;
50
+ case "create_sandbox":
51
+ void cs.createSandbox?.({
52
+ name: msg.name,
53
+ sourcePath: msg.sourcePath,
54
+ ephemeral: msg.ephemeral,
55
+ });
56
+ return true;
57
+ case "reset_sandbox":
58
+ void cs.resetSandbox?.(msg.path);
59
+ return true;
60
+ case "persist_sandbox":
61
+ void cs.persistSandbox?.(msg.path);
62
+ return true;
63
+ case "promote_sandbox":
64
+ void cs.promoteSandbox?.(msg.targetPath, msg.path, msg.switchToTarget);
65
+ return true;
66
+ case "diff_sandbox":
67
+ void cs.diffSandbox?.(msg.path);
68
+ return true;
69
+ case "apply_sandbox_to_source":
70
+ void cs.applySandboxToSource?.(msg.path);
71
+ return true;
72
+ case "destroy_sandbox":
73
+ void cs.destroySandbox?.(msg.path);
74
+ return true;
50
75
  default:
51
76
  return false;
52
77
  }
@@ -34,6 +34,7 @@ import { ClientStateStore, DEFAULT_RETRY_MAX_ATTEMPTS, normalizeBgCleanupMinutes
34
34
  import { normalizeUiLayout, normalizeKeepRecentMessages, DEFAULT_KEEP_RECENT_MESSAGES } from "../client-state.js";
35
35
  import { PLAN_MODE_SYSTEM_PROMPT } from "../plan-mode.js";
36
36
  import { FilesService, workspacePath, desktopDirWire } from "../files-service.js";
37
+ import { SandboxManager, isSameOrSubpath } from "../sandbox-service.js";
37
38
  import { QuiesceRejectedError } from "../agent-service.js";
38
39
  import { NATIVE_COMMANDS, parseSlash } from "../slash-commands.js";
39
40
  import { bilingual, pick, resolveServerLang } from "../i18n.js";
@@ -52,12 +53,12 @@ import { firstUserText, findSessionFilesForCwd, readSessionLog, replayEventsToMe
52
53
  import { generatePresetClones, PRESET_DEFAULT_ID } from "./preset-clones.js";
53
54
  import { dshContextUsage, lastUsageFromEvents, normalizeDshUsage } from "./dsh-usage.js";
54
55
  import { exportPresetVia, importPresetFromUrlVia, importPresetVia, packageVersion, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
56
+ import { getMaxOpenConversations } from "../agent-formatters.js";
55
57
  const SNAPSHOT_INTERVAL_MS = 60;
56
58
  /** 用户主目录(wire 格式):进程内不变,模块加载时求值一次(右栏 🏠)。 */
57
59
  const HOME_WIRE = homedir().replace(/\\/g, "/");
58
60
  /** 桌面目录(wire 格式):进程内不变,不存在则空串 → 前端不渲染 🖥️。 */
59
61
  const DESKTOP_WIRE = desktopDirWire(HOME_WIRE);
60
- const MAX_OPEN_CONVERSATIONS = 8;
61
62
  /** 新会话默认权限预设(沙箱内 + 无审批弹窗;无头运行的当前行为,保持不变)。 */
62
63
  const PERMISSION_DEFAULT_PRESET = "workspace-write-never";
63
64
  /** 前端提供的三档(官方 workspace-write 走 ask,无应答者时是死路,不提供)。 */
@@ -213,6 +214,7 @@ export class DshClientSession {
213
214
  presetCloneIds = [];
214
215
  files;
215
216
  bg;
217
+ sandboxes;
216
218
  /** 插件扩展点(index.ts 注入)。 */
217
219
  onToolEvent;
218
220
  pluginToolsProvider;
@@ -239,6 +241,7 @@ export class DshClientSession {
239
241
  this.dataDir = dataDir;
240
242
  this.agentDir = agentDir;
241
243
  this.sessionRoot = dshSessionRoot(dataDir);
244
+ this.sandboxes = new SandboxManager(dataDir);
242
245
  try {
243
246
  mkdirSync(this.sessionRoot, { recursive: true });
244
247
  }
@@ -1256,6 +1259,7 @@ export class DshClientSession {
1256
1259
  desktopDir: DESKTOP_WIRE,
1257
1260
  sessionId: conv.sessionId,
1258
1261
  conversationId: this.activeId,
1262
+ sandbox: this.sandboxes.getByCwd(this.cwd) ?? null,
1259
1263
  rev,
1260
1264
  streamingMessage: conv.streaming ? conv.streaming.toUiMessage(conv.lastEventAt, this.model, "deepseek") : null,
1261
1265
  isStreaming: conv.isStreaming,
@@ -1451,12 +1455,13 @@ export class DshClientSession {
1451
1455
  }
1452
1456
  }
1453
1457
  const openInProject = [...this.convs.values()].filter((c) => c.cwd === this.cwd).length;
1454
- if (openInProject >= MAX_OPEN_CONVERSATIONS) {
1458
+ const maxOpenConversations = getMaxOpenConversations();
1459
+ if (openInProject >= maxOpenConversations) {
1455
1460
  this.emit({
1456
1461
  type: "notice",
1457
1462
  level: "warning",
1458
- text: `当前项目运行的对话已达上限(${MAX_OPEN_CONVERSATIONS} 个)`,
1459
- textEn: `This project already has the max open conversations (${MAX_OPEN_CONVERSATIONS}).`,
1463
+ text: `当前项目运行的对话已达上限(${maxOpenConversations} 个)`,
1464
+ textEn: `This project already has the max open conversations (${maxOpenConversations}).`,
1460
1465
  });
1461
1466
  return false;
1462
1467
  }
@@ -2390,8 +2395,22 @@ export class DshClientSession {
2390
2395
  if (!removedKeys.has(normalizePathKey(this.cwd))) {
2391
2396
  projects.set(this.cwd, Date.now());
2392
2397
  }
2398
+ for (const sbx of this.sandboxes.list()) {
2399
+ if (!removedKeys.has(normalizePathKey(sbx.path)) && !projects.has(sbx.path)) {
2400
+ projects.set(sbx.path, sbx.createdAt);
2401
+ }
2402
+ }
2393
2403
  const list = [...projects.entries()]
2394
- .map(([path, lastUsed]) => ({ path, lastUsed }))
2404
+ .filter(([path]) => {
2405
+ if (isSameOrSubpath(path, this.sandboxes.sandboxesRoot)) {
2406
+ return Boolean(this.sandboxes.getByCwd(path));
2407
+ }
2408
+ return true;
2409
+ })
2410
+ .map(([path, lastUsed]) => {
2411
+ const sbx = this.sandboxes.getByCwd(path);
2412
+ return sbx ? { path, lastUsed, sandbox: sbx } : { path, lastUsed };
2413
+ })
2395
2414
  .sort((a, b) => b.lastUsed - a.lastUsed)
2396
2415
  .slice(0, 30);
2397
2416
  this.emit({ type: "projects", projects: list });
@@ -2423,9 +2442,205 @@ export class DshClientSession {
2423
2442
  return out || null;
2424
2443
  }
2425
2444
  async removeProject(path) {
2445
+ const sbx = this.sandboxes.get(path) ?? this.sandboxes.getByCwd(path);
2446
+ if (sbx) {
2447
+ await this.destroySandbox(sbx.path);
2448
+ return;
2449
+ }
2426
2450
  this.stateStore.removeProject(this.clientId, path);
2427
2451
  await this.pushProjects();
2428
2452
  }
2453
+ async createSandbox(opts) {
2454
+ try {
2455
+ const { sandbox, copiedFiles } = await this.sandboxes.create(opts);
2456
+ await this.setCwd(sandbox.path);
2457
+ await this.pushProjects();
2458
+ const modeZh = sandbox.sourcePath ? `已从源项目导入 ${copiedFiles} 个文件` : "空白隔离环境";
2459
+ const modeEn = sandbox.sourcePath ? `imported ${copiedFiles} files from source` : "blank isolated workspace";
2460
+ this.emit({
2461
+ type: "notice",
2462
+ level: "info",
2463
+ text: `🧪 沙盒「${sandbox.name}」已启动(${modeZh},一切修改与原项目完全隔离)`,
2464
+ textEn: `🧪 Sandbox "${sandbox.name}" started (${modeEn}; all changes are strictly isolated)`,
2465
+ });
2466
+ }
2467
+ catch (err) {
2468
+ this.emit({
2469
+ type: "notice",
2470
+ level: "error",
2471
+ text: `创建沙盒失败:${err.message}`,
2472
+ textEn: `Failed to create sandbox: ${err.message}`,
2473
+ });
2474
+ }
2475
+ }
2476
+ async resetSandbox(path) {
2477
+ const target = path?.trim() || this.cwd;
2478
+ try {
2479
+ const { sandbox, copiedFiles } = await this.sandboxes.reset(target);
2480
+ await this.listFiles();
2481
+ this.flushSnapshot();
2482
+ this.emit({
2483
+ type: "notice",
2484
+ level: "info",
2485
+ text: sandbox.sourcePath
2486
+ ? `🔄 已重置沙盒「${sandbox.name}」(重新从源项目同步 ${copiedFiles} 个文件)`
2487
+ : `🔄 已清空并重置沙盒「${sandbox.name}」`,
2488
+ textEn: sandbox.sourcePath
2489
+ ? `🔄 Reset sandbox "${sandbox.name}" (re-synced ${copiedFiles} files from source)`
2490
+ : `🔄 Cleared and reset sandbox "${sandbox.name}"`,
2491
+ });
2492
+ }
2493
+ catch (err) {
2494
+ this.emit({
2495
+ type: "notice",
2496
+ level: "error",
2497
+ text: `重置沙盒失败:${err.message}`,
2498
+ textEn: `Failed to reset sandbox: ${err.message}`,
2499
+ });
2500
+ }
2501
+ }
2502
+ async persistSandbox(path) {
2503
+ const target = path?.trim() || this.cwd;
2504
+ try {
2505
+ const sandbox = this.sandboxes.persist(target);
2506
+ await this.pushProjects();
2507
+ this.flushSnapshot();
2508
+ this.emit({
2509
+ type: "notice",
2510
+ level: "info",
2511
+ text: `📌 沙盒「${sandbox.name}」已转为永久保留`,
2512
+ textEn: `📌 Sandbox "${sandbox.name}" is now saved permanently`,
2513
+ });
2514
+ }
2515
+ catch (err) {
2516
+ this.emit({
2517
+ type: "notice",
2518
+ level: "error",
2519
+ text: `转换永久沙盒失败:${err.message}`,
2520
+ textEn: `Failed to persist sandbox: ${err.message}`,
2521
+ });
2522
+ }
2523
+ }
2524
+ async promoteSandbox(targetPath, path, switchToTarget = true) {
2525
+ const sbxTarget = path?.trim() || this.cwd;
2526
+ try {
2527
+ const { sandbox, targetPath: resolvedTarget, copiedFiles } = await this.sandboxes.promote(sbxTarget, targetPath);
2528
+ if (switchToTarget) {
2529
+ await this.setCwd(resolvedTarget);
2530
+ }
2531
+ else {
2532
+ await this.pushProjects();
2533
+ }
2534
+ this.emit({
2535
+ type: "notice",
2536
+ level: "info",
2537
+ text: `📤 已将沙盒「${sandbox.name}」导出为正式项目:${resolvedTarget}(共 ${copiedFiles} 个文件)`,
2538
+ textEn: `📤 Exported sandbox "${sandbox.name}" to formal project: ${resolvedTarget} (${copiedFiles} files)`,
2539
+ });
2540
+ }
2541
+ catch (err) {
2542
+ this.emit({
2543
+ type: "notice",
2544
+ level: "error",
2545
+ text: `导出沙盒失败:${err.message}`,
2546
+ textEn: `Failed to export sandbox: ${err.message}`,
2547
+ });
2548
+ }
2549
+ }
2550
+ async diffSandbox(path) {
2551
+ const target = path?.trim() || this.cwd;
2552
+ try {
2553
+ const res = await this.sandboxes.diffWithSource(target);
2554
+ this.emit({
2555
+ type: "sandbox_diff",
2556
+ diff: {
2557
+ sandboxId: res.sandbox.id,
2558
+ path: res.sandbox.path,
2559
+ sourcePath: res.sourcePath,
2560
+ added: res.added.slice(0, 200),
2561
+ modified: res.modified.slice(0, 200),
2562
+ deleted: res.deleted.slice(0, 200),
2563
+ unchangedCount: res.unchangedCount,
2564
+ },
2565
+ });
2566
+ }
2567
+ catch (err) {
2568
+ this.emit({
2569
+ type: "sandbox_diff",
2570
+ diff: {
2571
+ sandboxId: "",
2572
+ path: target,
2573
+ added: [],
2574
+ modified: [],
2575
+ deleted: [],
2576
+ unchangedCount: 0,
2577
+ error: err.message,
2578
+ },
2579
+ });
2580
+ }
2581
+ }
2582
+ async applySandboxToSource(path) {
2583
+ const target = path?.trim() || this.cwd;
2584
+ try {
2585
+ const { sandbox, sourcePath, copiedFiles } = await this.sandboxes.applyToSource(target);
2586
+ this.emit({
2587
+ type: "notice",
2588
+ level: "info",
2589
+ text: `✅ 已将沙盒「${sandbox.name}」中的 ${copiedFiles} 个文件同步回源项目:${sourcePath}`,
2590
+ textEn: `✅ Applied ${copiedFiles} files from sandbox "${sandbox.name}" back to source project: ${sourcePath}`,
2591
+ });
2592
+ }
2593
+ catch (err) {
2594
+ this.emit({
2595
+ type: "notice",
2596
+ level: "error",
2597
+ text: `写回源项目失败:${err.message}`,
2598
+ textEn: `Failed to apply sandbox changes to source: ${err.message}`,
2599
+ });
2600
+ }
2601
+ }
2602
+ async destroySandbox(path) {
2603
+ const target = path?.trim() || this.cwd;
2604
+ const sbx = this.sandboxes.get(target) ?? this.sandboxes.getByCwd(target);
2605
+ if (!sbx) {
2606
+ this.stateStore.removeProject(this.clientId, target);
2607
+ await this.pushProjects();
2608
+ return;
2609
+ }
2610
+ try {
2611
+ const activeInSbx = isSameOrSubpath(this.cwd, sbx.path);
2612
+ if (activeInSbx) {
2613
+ let fallbackCwd = sbx.sourcePath && existsSync(sbx.sourcePath) ? sbx.sourcePath : "";
2614
+ if (!fallbackCwd) {
2615
+ const recent = await this.stateStore.getRecentProjects(this.clientId);
2616
+ const other = recent.find((p) => {
2617
+ const pk = normalizePathKey(p.path);
2618
+ return pk !== normalizePathKey(sbx.path) && existsSync(p.path);
2619
+ });
2620
+ fallbackCwd = other?.path || homedir();
2621
+ }
2622
+ await this.setCwd(fallbackCwd);
2623
+ }
2624
+ await this.sandboxes.destroy(sbx.id);
2625
+ this.stateStore.removeProject(this.clientId, sbx.path);
2626
+ await this.pushProjects();
2627
+ this.flushSnapshot();
2628
+ this.emit({
2629
+ type: "notice",
2630
+ level: "info",
2631
+ text: `🗑️ 已销毁沙盒项目「${sbx.name}」并清理隔离目录`,
2632
+ textEn: `🗑️ Destroyed sandbox project "${sbx.name}" and cleaned up isolated directory`,
2633
+ });
2634
+ }
2635
+ catch (err) {
2636
+ this.emit({
2637
+ type: "notice",
2638
+ level: "error",
2639
+ text: `销毁沙盒失败:${err.message}`,
2640
+ textEn: `Failed to destroy sandbox: ${err.message}`,
2641
+ });
2642
+ }
2643
+ }
2429
2644
  async listFiles(relPath) {
2430
2645
  await this.files.listFiles(relPath);
2431
2646
  }
@@ -4178,6 +4393,15 @@ export class DshClientSession {
4178
4393
  try {
4179
4394
  const abs = resolve(newCwd);
4180
4395
  if (!existsSync(abs) || !statSync(abs).isDirectory()) {
4396
+ this.emit({
4397
+ type: "transition_progress",
4398
+ kind: "cwd",
4399
+ target: newCwd,
4400
+ phase: "error",
4401
+ progress: 100,
4402
+ text: `切换工作目录失败:目录不存在:${newCwd}`,
4403
+ textEn: `Failed to switch directory; does not exist: ${newCwd}`,
4404
+ });
4181
4405
  this.emit({
4182
4406
  type: "notice",
4183
4407
  level: "error",
@@ -4186,8 +4410,28 @@ export class DshClientSession {
4186
4410
  });
4187
4411
  return;
4188
4412
  }
4189
- if (abs === this.cwd)
4413
+ if (abs === this.cwd) {
4414
+ this.emit({
4415
+ type: "transition_progress",
4416
+ kind: "cwd",
4417
+ target: abs,
4418
+ phase: "done",
4419
+ progress: 100,
4420
+ text: `已在工作目录:${abs}`,
4421
+ textEn: `Already in directory: ${abs}`,
4422
+ });
4190
4423
  return;
4424
+ }
4425
+ this.emit({
4426
+ type: "transition_progress",
4427
+ kind: "cwd",
4428
+ target: abs,
4429
+ phase: "runtime",
4430
+ progress: 45,
4431
+ text: `正在切换工作目录并重启运行环境:${abs}`,
4432
+ textEn: `Switching workspace & restarting runtime: ${abs}`,
4433
+ });
4434
+ await new Promise((r) => setImmediate(r));
4191
4435
  this.cwd = abs;
4192
4436
  this.roots = this.stateStore.getWorkspaceRoots(this.clientId, abs);
4193
4437
  this.stateStore.remember(this.clientId, abs);
@@ -4225,15 +4469,16 @@ export class DshClientSession {
4225
4469
  continue;
4226
4470
  if (c.isStreaming)
4227
4471
  continue;
4228
- // 只看“用过”的存活终端:没动过的空 shell 不阻止项目切换时的旧会话回收。
4229
- if (c.terminals.countBlockingLive() > 0)
4230
- continue;
4472
+ // 只看“用过”的存活终端:没动过的空 shell 不阻止项目切换时的旧会话回收。\n\t\t\t\tif (c.terminals.countBlockingLive() > 0) continue;
4231
4473
  this.removeConversation(id);
4232
4474
  }
4233
4475
  this.onCwdChanged?.(abs);
4234
4476
  this.emit({
4235
- type: "notice",
4236
- level: "info",
4477
+ type: "transition_progress",
4478
+ kind: "cwd",
4479
+ target: abs,
4480
+ phase: "done",
4481
+ progress: 100,
4237
4482
  text: `已切换到工作目录:${abs}`,
4238
4483
  textEn: `Switched to directory: ${abs}`,
4239
4484
  });
@@ -4247,6 +4492,15 @@ export class DshClientSession {
4247
4492
  this.flushSnapshot(true);
4248
4493
  }
4249
4494
  catch (err) {
4495
+ this.emit({
4496
+ type: "transition_progress",
4497
+ kind: "cwd",
4498
+ target: newCwd,
4499
+ phase: "error",
4500
+ progress: 100,
4501
+ text: `切换目录失败:${err.message}`,
4502
+ textEn: `Failed to switch directory: ${err.message}`,
4503
+ });
4250
4504
  this.emit({
4251
4505
  type: "notice",
4252
4506
  level: "error",
@@ -53,6 +53,8 @@ const WRITE_TOOLS = new Set([
53
53
  "git",
54
54
  // 代码求值(eval 沙箱可写真实文件系统 —— 审查回合只读核实,#436)
55
55
  "eval",
56
+ "mcp_manage",
57
+ "sandbox",
56
58
  // 形态变换(会重写整个文件树)
57
59
  "format",
58
60
  "prettier",
@@ -590,10 +590,16 @@ export class GoalService {
590
590
  // the wizard's internal one, which kicks off itself). This makes the direct
591
591
  // goal-bar path behave like the AI-提炼 path: set a target → agent begins.
592
592
  if (opts?.autoStart !== false) {
593
+ const gen = conv.goalGeneration;
594
+ // #591:主对话若仍在跑设目标前的旧任务,首轮派发执行者前先中断让位,
595
+ // 避免主对话与目标执行者在同一工作区并行动工、污染采样 diff。
596
+ await this.preemptMainRunForGoal(conv, gen);
597
+ if (!this.isCurrentDelegated(conv, gen))
598
+ return;
593
599
  // 目标模式 2.0(唯一路径):主对话当审查者,干活的是常驻执行对话 ——
594
600
  // 不向主对话注入「请开始实现」,改由服务端驱动循环(等执行者跑完再把
595
601
  // 审查指令交给主对话)。
596
- this.startDelegatedLoop(conv, conv.goalGeneration, text);
602
+ this.startDelegatedLoop(conv, gen, text);
597
603
  this.host.flushSnapshot();
598
604
  }
599
605
  }
@@ -1197,6 +1203,12 @@ export class GoalService {
1197
1203
  onAgentEnd(conv, aborted) {
1198
1204
  const g = conv.goal;
1199
1205
  if (aborted) {
1206
+ // #591:设目标时服务端主动中断主对话的旧运行以让位给执行者 —— 该次 abort
1207
+ // 是预期交接,不是用户按了 Stop,不得把刚设好的目标清掉。
1208
+ if (conv.preemptingMainRun) {
1209
+ conv.preemptingMainRun = false;
1210
+ return null;
1211
+ }
1200
1212
  if (g.goal && g.conversationId === conv.id) {
1201
1213
  // 中止的若是审查回合(服务端正在等 verdict):只作废这一次审查(走无 JSON
1202
1214
  // 重试/受阻),目标与执行对话都保留 —— 用户按 Stop 往往只是想掐掉那段机器
@@ -1290,12 +1302,53 @@ export class GoalService {
1290
1302
  }
1291
1303
  isConvStreaming(conv) {
1292
1304
  try {
1293
- return conv.session?.isStreaming === true;
1305
+ if (conv.promptInFlight)
1306
+ return true;
1307
+ if (conv.session?.isStreaming === true)
1308
+ return true;
1309
+ if (typeof conv.session?.isIdle === "boolean" && !conv.session.isIdle) {
1310
+ return true;
1311
+ }
1312
+ return false;
1294
1313
  }
1295
1314
  catch {
1296
1315
  return false;
1297
1316
  }
1298
1317
  }
1318
+ /**
1319
+ * #591:首轮派发目标执行者前,若主对话仍在执行设目标之前的旧任务,先中断它并提示用户。
1320
+ * 仅在首轮派发前生效(按 goalGeneration 去重),委托执行期间用户在主对话发起的新聊天不受影响。
1321
+ */
1322
+ async preemptMainRunForGoal(conv, goalGeneration) {
1323
+ if (!this.isConvStreaming(conv))
1324
+ return;
1325
+ if (conv.preemptedGoalGen === goalGeneration)
1326
+ return;
1327
+ conv.preemptedGoalGen = goalGeneration;
1328
+ conv.preemptingMainRun = true;
1329
+ try {
1330
+ if (this.host.interruptMainConv) {
1331
+ await this.host.interruptMainConv(conv.id);
1332
+ }
1333
+ else {
1334
+ await this.host.stopRoleAgent?.(conv.id);
1335
+ }
1336
+ }
1337
+ catch {
1338
+ // best-effort
1339
+ }
1340
+ finally {
1341
+ conv.preemptingMainRun = false;
1342
+ }
1343
+ if (!this.isCurrentDelegated(conv, goalGeneration))
1344
+ return;
1345
+ this.host.emit({
1346
+ type: "notice",
1347
+ level: "info",
1348
+ text: "🎯 目标已设:主对话当前的运行已停止,接下来由目标执行者接手",
1349
+ textEn: "🎯 Goal set: stopped the main conversation's current run so the goal executor can take over",
1350
+ });
1351
+ }
1299
1352
  /** 启动委托循环(同一对话同时只允许一个在飞;旧循环退场中到来的请求排队接力)。 */
1300
1353
  startDelegatedLoop(conv, goalGeneration, goalText) {
1301
1354
  if (this.delegatedLoops.has(conv.id)) {
@@ -1626,6 +1679,10 @@ export class GoalService {
1626
1679
  this.beginRoundVitals(conv, existing.convId);
1627
1680
  return existing.convId;
1628
1681
  }
1682
+ // #591:向导结束 / 排队接力等路径直接进 startDelegatedLoop 时,首轮 spawn 前同样保证主对话旧运行已让位。
1683
+ await this.preemptMainRunForGoal(conv, goalGeneration);
1684
+ if (!this.isCurrentDelegated(conv, goalGeneration))
1685
+ return undefined;
1629
1686
  try {
1630
1687
  const convId = await host.spawnRoleAgent({
1631
1688
  role: "executor",