pi-web-ui 0.110.0 → 0.112.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 (110) hide show
  1. package/CHANGELOG.md +55 -2
  2. package/bin/frp-manager.mjs +92 -7
  3. package/dist/server/agent-formatters.js +10 -6
  4. package/dist/server/agent-service-daemon.js +27 -9
  5. package/dist/server/agent-service.js +1442 -489
  6. package/dist/server/approval-audit.js +119 -0
  7. package/dist/server/approval-default-rules.js +4 -4
  8. package/dist/server/approval-rules.js +42 -17
  9. package/dist/server/attachment-store.js +8 -8
  10. package/dist/server/attachments.js +114 -31
  11. package/dist/server/canvas/canvas-agent-tool.js +593 -0
  12. package/dist/server/canvas/canvas-cards.js +144 -0
  13. package/dist/server/canvas/canvas-dispatch.js +155 -0
  14. package/dist/server/canvas/canvas-orchestrator.js +1094 -0
  15. package/dist/server/canvas/canvas-store.js +260 -0
  16. package/dist/server/client-id-utils.js +2 -2
  17. package/dist/server/client-state.js +52 -0
  18. package/dist/server/context-budget.js +6 -3
  19. package/dist/server/delegate-mode.js +6 -3
  20. package/dist/server/delegate-task.js +18 -3
  21. package/dist/server/dispatch-domain-handlers.js +3 -0
  22. package/dist/server/dsh/dsh-agent-service.js +357 -20
  23. package/dist/server/dsh/dsh-client.js +10 -1
  24. package/dist/server/dsh/dsh-serialize.js +1 -1
  25. package/dist/server/dsh/runtime/goal-rpc.mjs +128 -3
  26. package/dist/server/dsh/runtime/launcher.mjs +59 -5
  27. package/dist/server/dsh/runtime/runtime-root.mjs +353 -40
  28. package/dist/server/durable/durable-agent-service.js +3 -0
  29. package/dist/server/durable/durable-driver.js +75 -9
  30. package/dist/server/durable/durable-loader.js +1 -14
  31. package/dist/server/durable/durable-models.js +107 -0
  32. package/dist/server/durable/index.js +0 -4
  33. package/dist/server/engine-probe.js +76 -37
  34. package/dist/server/eval-tool.js +28 -3
  35. package/dist/server/file-transfer-routes.js +8 -2
  36. package/dist/server/files-service.js +10 -2
  37. package/dist/server/goal-service.js +7 -0
  38. package/dist/server/index.js +480 -59
  39. package/dist/server/json-utils.js +57 -0
  40. package/dist/server/marker-service.js +11 -1
  41. package/dist/server/markers/marker.js +45 -4
  42. package/dist/server/markers/registry.js +31 -0
  43. package/dist/server/message-window.js +44 -8
  44. package/dist/server/model-admin.js +68 -106
  45. package/dist/server/model-resolver.js +66 -44
  46. package/dist/server/office-parse.js +394 -7
  47. package/dist/server/plan-manager.js +3 -6
  48. package/dist/server/plugin-api-catalog.js +7 -0
  49. package/dist/server/plugin-assets.js +238 -0
  50. package/dist/server/plugin-facilities.js +22 -0
  51. package/dist/server/plugin-ui-slots.js +1 -0
  52. package/dist/server/plugins.js +296 -25
  53. package/dist/server/preset-fields.js +60 -2
  54. package/dist/server/preset-share.js +8 -2
  55. package/dist/server/prompt-assembler.js +9 -2
  56. package/dist/server/prompt-composer.js +84 -44
  57. package/dist/server/protocol-version.js +1 -1
  58. package/dist/server/queue-utils.js +156 -0
  59. package/dist/server/remote-ssh-service.js +16 -4
  60. package/dist/server/sdk-builtin-extensions.js +85 -0
  61. package/dist/server/server-config.js +66 -0
  62. package/dist/server/session-parser.js +49 -13
  63. package/dist/server/session-search.js +4 -3
  64. package/dist/server/settings-service.js +56 -7
  65. package/dist/server/soft-cap.js +8 -6
  66. package/dist/server/subagent-helpers.js +22 -1
  67. package/dist/server/subagent-notify.js +93 -0
  68. package/dist/server/subagent-security-gate.js +282 -0
  69. package/dist/server/subagent-templates.js +8 -0
  70. package/dist/server/subagents.js +144 -17
  71. package/dist/server/terminals.js +196 -8
  72. package/dist/server/text-quote.js +61 -0
  73. package/dist/server/tool-approval.js +63 -4
  74. package/dist/server/tool-guards.js +208 -0
  75. package/dist/server/tool-host-factories.js +46 -10
  76. package/dist/server/tool-manager.js +30 -0
  77. package/dist/server/tool-overrides.js +21 -11
  78. package/dist/server/univer-service.js +448 -0
  79. package/dist/server/universal/driver-base.js +8 -0
  80. package/dist/server/universal/drivers/claude-code.js +39 -5
  81. package/dist/server/universal/drivers/dsh-driver.js +3 -0
  82. package/dist/server/universal/index.js +0 -1
  83. package/dist/server/universal/universal-attachments.js +5 -0
  84. package/dist/server/universal/universal-service.js +5 -0
  85. package/dist/server/universal/universal-session.js +114 -21
  86. package/dist/server/update-check.js +90 -5
  87. package/dist/server/workspace-snapshot.js +33 -2
  88. package/dist/server/worktree-service.js +189 -1
  89. package/docs/dsh-engine.md +493 -0
  90. package/package.json +5 -4
  91. package/plugin-sdk/client-utils.mjs +192 -5
  92. package/plugin-sdk/index.d.ts +80 -1
  93. package/plugin-sdk/index.mjs +99 -0
  94. package/plugin-sdk/package.json +5 -1
  95. package/plugins/catalog.json +33 -0
  96. package/themes/aetheris.css +114 -0
  97. package/themes/bases/obsidian-base.css +216 -0
  98. package/themes/md-preview.css +113 -0
  99. package/themes/wallpaper-flow.css +182 -0
  100. package/web/dist/assets/{TerminalPanel-BHjM6pzY.js → TerminalPanel-Dqr1dK28.js} +2 -2
  101. package/web/dist/assets/index-Dh8BX-lP.js +720 -0
  102. package/web/dist/assets/index-DqrC1I_a.css +1 -0
  103. package/web/dist/assets/{markdown-DXwnfD9T.js → markdown-BJZlfvdP.js} +24 -24
  104. package/web/dist/assets/markdown-DSNUiDzp.css +1 -0
  105. package/web/dist/index.html +13 -4
  106. package/web/dist/sw.js +1 -1
  107. package/web/dist/assets/es-DIDZppIF.js +0 -2
  108. package/web/dist/assets/index-DwInT7-a.css +0 -1
  109. package/web/dist/assets/index-GfVFIgIL.js +0 -693
  110. package/web/dist/assets/markdown-CCeVCbci.css +0 -1
@@ -19,7 +19,7 @@ import { ModelAdminService } from "../model-admin.js";
19
19
  import { WebUIContext } from "../webui-context.js";
20
20
  import { ClaudeCodeDriver, probeClaudeCode } from "./drivers/claude-code.js";
21
21
  import { normalizeUiLayout, settingsPresetToUi } from "../client-state.js";
22
- import { readModelsJson } from "../model-resolver.js";
22
+ import { readModelsJson, getModelThinkingLevelFromSettings, saveModelThinkingLevelToSettings, } from "../model-resolver.js";
23
23
  import { DEFAULT_UNIVERSAL_CAPABILITIES } from "../engine-capabilities.js";
24
24
  import { unsupportedToolInfo } from "../tool-info.js";
25
25
  import { SandboxManager } from "../sandbox-service.js";
@@ -31,6 +31,7 @@ import { scanAtMentions, createAttachmentUiMessages, formatPromptWithSkills } fr
31
31
  import { scmCommitContext } from "../scm.js";
32
32
  import { buildCommitMsgInput, sanitizeCommitMessage } from "../scm-commitmsg.js";
33
33
  import { getAppVersion } from "../pkg-info.js";
34
+ import { createQueuedEntry, removeQueuedEntry, toQueuedPromptItems } from "../queue-utils.js";
34
35
  import { SubagentTemplatesStore, DEFAULT_TEMPLATES, pickTemplatePrompt, } from "../subagent-templates.js";
35
36
  import { subagentTitle, isSubagentTerminal, computeWaitCapMs, makeSubagentTools, } from "../subagents.js";
36
37
  import { recordSubagentHandoff, formatSubagentHandoffMessage, } from "../subagent-handoff.js";
@@ -38,6 +39,23 @@ import { pick } from "../i18n.js";
38
39
  import { fetchRemoteSkillMarket, fetchRemoteSkillContent, fetchRemoteMcpMarket } from "../market-service.js";
39
40
  import { exportPresetVia, importPresetVia, importPresetFromUrlVia, pushPresetCatalogVia, sharePresetVia, } from "../preset-share.js";
40
41
  const SNAPSHOT_INTERVAL_MS = 60;
42
+ function clampThinkingLevelToSupported(supported, current) {
43
+ if (supported.includes(current))
44
+ return current;
45
+ const order = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
46
+ const curIdx = order.indexOf(current);
47
+ if (curIdx === -1)
48
+ return supported[0] ?? "off";
49
+ for (let i = curIdx; i < order.length; i++) {
50
+ if (supported.includes(order[i]))
51
+ return order[i];
52
+ }
53
+ for (let i = curIdx - 1; i >= 0; i--) {
54
+ if (supported.includes(order[i]))
55
+ return order[i];
56
+ }
57
+ return supported[0] ?? "off";
58
+ }
41
59
  export class UniversalSession {
42
60
  cwd;
43
61
  clientId;
@@ -65,6 +83,9 @@ export class UniversalSession {
65
83
  activeConvId;
66
84
  conversations = new Map();
67
85
  isStreaming = false;
86
+ /** 在途回合归属的会话 id(#700/#701):prompt 开始时锚定,finalizeTurn 收尾时消费并清空。
87
+ * 会话切换/回滚不再让流式回写与回合收尾锚错会话,避免跨对话内容污染落盘。 */
88
+ turnConvId = null;
68
89
  streamingMessage = null;
69
90
  streamingThinking = "";
70
91
  streamingText = "";
@@ -104,10 +125,11 @@ export class UniversalSession {
104
125
  const templatesPath = join(this.dataDir || process.env.PI_WEB_DATA_DIR || join(homedir(), ".pi-web"), "subagent-templates.json");
105
126
  this.subagentTemplates = new SubagentTemplatesStore(templatesPath);
106
127
  this.subagentHost = {
107
- spawnSubagent: async (prompt, type, cwd, templateName, model, parentId, persist) => {
108
- const { convId } = await this.spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist);
128
+ spawnSubagent: async (prompt, type, cwd, templateName, model, parentId, persist, thinking, notifyOnDone, _isolation, _extra) => {
129
+ const { convId } = await this.spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist, undefined, thinking, notifyOnDone);
109
130
  return convId;
110
131
  },
132
+ finalizeSubagentWorktree: async (_convId) => { },
111
133
  getSubagent: (convId) => {
112
134
  const conv = this.conversations.get(convId);
113
135
  if (!conv || !conv.isSubagent)
@@ -117,6 +139,7 @@ export class UniversalSession {
117
139
  listSubagents: (scope) => this.listSubagents(scope),
118
140
  steerSubagent: (convId, message) => this.steerSubagent(convId, message),
119
141
  stopSubagent: (convId) => this.stopSubagent(convId),
142
+ markSubagentsConsumed: (_runIds) => { },
120
143
  listTemplates: () => this.subagentTemplates
121
144
  .list()
122
145
  .filter((t) => t.enabled !== false)
@@ -239,6 +262,20 @@ export class UniversalSession {
239
262
  if (savedModel) {
240
263
  this.currentModel = savedModel;
241
264
  }
265
+ // 恢复思考强度记忆:模型专属记忆 > 全局默认 > 既有默认
266
+ const rememberedThinking = getModelThinkingLevelFromSettings(this.currentModel, this.agentDir);
267
+ if (rememberedThinking) {
268
+ this.thinkingLevel = rememberedThinking;
269
+ }
270
+ if (typeof this.driver.getSupportedThinkingLevels === "function") {
271
+ const supported = this.driver.getSupportedThinkingLevels(this.currentModel);
272
+ if (supported.length > 0 && !supported.includes(this.thinkingLevel)) {
273
+ this.thinkingLevel = clampThinkingLevelToSupported(supported, this.thinkingLevel);
274
+ }
275
+ }
276
+ if (typeof this.driver.setThinkingLevel === "function") {
277
+ this.driver.setThinkingLevel(this.thinkingLevel);
278
+ }
242
279
  this.modelAdmin = new ModelAdminService({
243
280
  agentDir: this.agentDir,
244
281
  emit: (msg) => this.send(msg),
@@ -444,8 +481,9 @@ export class UniversalSession {
444
481
  conversationId: conv.id,
445
482
  rev: this.rev,
446
483
  messages: conv.messages,
447
- streamingMessage: this.streamingMessage,
448
- isStreaming: this.isStreaming,
484
+ // 回合归属会话才携带流式态:切走后的前台会话快照不再混入后台回合内容(#701)
485
+ streamingMessage: !this.turnConvId || this.turnConvId === conv.id ? this.streamingMessage : null,
486
+ isStreaming: !this.turnConvId || this.turnConvId === conv.id ? this.isStreaming : false,
449
487
  isEphemeral: Boolean(conv.isEphemeral),
450
488
  draft: this.sessionDrafts.get(conv.id) ?? null,
451
489
  model: {
@@ -455,10 +493,16 @@ export class UniversalSession {
455
493
  vision: curModel.vision,
456
494
  },
457
495
  thinkingLevel: this.thinkingLevel,
458
- availableThinkingLevels: ["off", "low", "medium", "high"],
496
+ availableThinkingLevels: typeof this.driver.getSupportedThinkingLevels === "function"
497
+ ? this.driver.getSupportedThinkingLevels(this.currentModel)
498
+ : ["off", "minimal", "low", "medium", "high", "xhigh", "max"],
459
499
  queue: {
460
500
  steering: [],
461
501
  followUp: this.followUpQueue.map((q) => q.text),
502
+ entries: {
503
+ steering: [],
504
+ followUp: toQueuedPromptItems(this.followUpQueue),
505
+ },
462
506
  },
463
507
  tools: [],
464
508
  version: this.version,
@@ -500,7 +544,8 @@ export class UniversalSession {
500
544
  async prompt(text, attachments, _queue) {
501
545
  if (this.isStreaming) {
502
546
  if (_queue === true) {
503
- this.followUpQueue.push({ text, attachments });
547
+ const entry = createQueuedEntry(text, { attachments });
548
+ this.followUpQueue.push(entry);
504
549
  this.flushSnapshot();
505
550
  this.emitNotice("info", "已加入排队,将在当前回复生成完成后自动发送", "Queued — will send after current response settles");
506
551
  return;
@@ -548,6 +593,7 @@ export class UniversalSession {
548
593
  }
549
594
  this.isStreaming = true;
550
595
  const conv = this.activeConv;
596
+ this.turnConvId = conv.id;
551
597
  const now = Date.now();
552
598
  // 2. 扫描用户文本中的 @ 提及(文件路径与技能指令)
553
599
  const availableSkills = await this.collectUniversalSkills();
@@ -705,7 +751,7 @@ export class UniversalSession {
705
751
  return;
706
752
  this.send({
707
753
  type: "message_delta",
708
- conversationId: this.activeConvId,
754
+ conversationId: this.turnConvId ?? this.activeConvId,
709
755
  seq: ++this.deltaSeq,
710
756
  messageId: this.streamingMessage.id,
711
757
  usage: null,
@@ -717,16 +763,19 @@ export class UniversalSession {
717
763
  clearTimeout(this.snapshotTimer);
718
764
  this.snapshotTimer = null;
719
765
  }
766
+ // 回合收尾锚定回合归属会话:中途切走/回滚不再把本轮内容写进别的会话(#700/#701)
767
+ const turnId = this.turnConvId;
768
+ this.turnConvId = null;
769
+ const conv = (turnId && this.conversations.get(turnId)) || this.activeConv;
720
770
  if (this.streamingMessage) {
721
- this.activeConv.messages.push(this.streamingMessage);
771
+ conv.messages.push(this.streamingMessage);
722
772
  this.streamingMessage = null;
723
773
  }
724
774
  if (this.pendingToolResults.length > 0) {
725
- this.activeConv.messages.push(...this.pendingToolResults);
775
+ conv.messages.push(...this.pendingToolResults);
726
776
  this.pendingToolResults = [];
727
777
  }
728
778
  // 累计会话统计与上下文占用(底座统一驱动底栏上下文环、Token 计数、缓存命中率与累计成本)
729
- const conv = this.activeConv;
730
779
  if (!conv.stats) {
731
780
  conv.stats = {
732
781
  tokens: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
@@ -756,20 +805,24 @@ export class UniversalSession {
756
805
  // 回写 Claude 分配的 session ID(保证多轮上下文连续)
757
806
  if (typeof this.driver.getActiveSessionId === "function") {
758
807
  const activeSid = this.driver.getActiveSessionId();
759
- if (activeSid && this.activeConv.driverSessionId !== activeSid) {
760
- this.activeConv.driverSessionId = activeSid;
808
+ if (activeSid && conv.driverSessionId !== activeSid) {
809
+ conv.driverSessionId = activeSid;
761
810
  }
762
811
  }
763
812
  this.isStreaming = false;
764
813
  this.streamingThinking = "";
814
+ // 先取本轮全文再清空:内联标记解析在清空之后读 streamingText,
815
+ // 条件恒为 false,[[conv:rename]]/[[action:suggest]] 在 universal
816
+ // 引擎(claude/durable 等驱动)下从不被解析。
817
+ const finalText = this.streamingText;
765
818
  this.streamingText = "";
766
- this.activeConv.updatedAt = Date.now();
767
- if (!this.activeConv.isEphemeral) {
768
- this.store.saveConversation(this.cwd, this.activeConv);
819
+ conv.updatedAt = Date.now();
820
+ if (!conv.isEphemeral) {
821
+ this.store.saveConversation(this.cwd, conv);
769
822
  }
770
823
  // 解析本轮生成的内联标记(如 [[conv:rename:...]] / [[action:suggest:...]])
771
- if (this.streamingText && this.streamingText.includes("[[")) {
772
- void this.markerSvc.handleAssistantText(this.activeConv.id, this.streamingText);
824
+ if (finalText && finalText.includes("[[")) {
825
+ void this.markerSvc.handleAssistantText(conv.id, finalText);
773
826
  }
774
827
  this.flushSnapshot();
775
828
  void this.refreshSessions();
@@ -804,8 +857,14 @@ export class UniversalSession {
804
857
  }
805
858
  }
806
859
  }
807
- removeQueued() {
808
- /* 通用底座暂无插队队列 */
860
+ removeQueued(kind, text, index, id) {
861
+ if (kind === "followUp") {
862
+ const next = removeQueuedEntry(this.followUpQueue, { id, text, index });
863
+ if (next.length !== this.followUpQueue.length) {
864
+ this.followUpQueue = next;
865
+ this.flushSnapshot();
866
+ }
867
+ }
809
868
  }
810
869
  // ---------------------------------------------------------------------------
811
870
  // 对话生命周期
@@ -982,6 +1041,11 @@ export class UniversalSession {
982
1041
  if (!targetConv) {
983
1042
  targetConv = this.activeConv;
984
1043
  }
1044
+ // 回滚与在途回合互斥:先落定在途回合再截断,否则 finalize 与 slice 交错导致截断/错位(#700)
1045
+ if (targetConv.id === this.activeConvId && (this.isStreaming || this.streamingMessage)) {
1046
+ await this.abort();
1047
+ targetConv = this.activeConv;
1048
+ }
985
1049
  const idx = targetConv.messages.findIndex((m) => m.id === messageId);
986
1050
  if (idx < 0) {
987
1051
  this.emitNotice("error", "找不到指定的回滚目标消息", "Rollback target message not found");
@@ -1379,6 +1443,22 @@ export class UniversalSession {
1379
1443
  if (this.driver.setModel) {
1380
1444
  await this.driver.setModel(modelId);
1381
1445
  }
1446
+ // 优先恢复该模型的全局思考强度记忆或全局默认强度
1447
+ const remembered = getModelThinkingLevelFromSettings(modelId, this.agentDir);
1448
+ if (remembered) {
1449
+ this.thinkingLevel = remembered;
1450
+ }
1451
+ // 校验并平滑适应新模型支持的思考强度
1452
+ if (typeof this.driver.getSupportedThinkingLevels === "function") {
1453
+ const supported = this.driver.getSupportedThinkingLevels(modelId);
1454
+ if (supported.length > 0 && !supported.includes(this.thinkingLevel)) {
1455
+ const clamped = clampThinkingLevelToSupported(supported, this.thinkingLevel);
1456
+ this.thinkingLevel = clamped;
1457
+ }
1458
+ }
1459
+ if (typeof this.driver.setThinkingLevel === "function") {
1460
+ this.driver.setThinkingLevel(this.thinkingLevel);
1461
+ }
1382
1462
  const info = this.resolveCurrentModelInfo();
1383
1463
  this.emitNotice("info", `已切换到模型:${info.name}`, `Switched to model: ${info.name}`);
1384
1464
  this.flushSnapshot();
@@ -1401,6 +1481,13 @@ export class UniversalSession {
1401
1481
  }
1402
1482
  setThinking(level) {
1403
1483
  this.thinkingLevel = level;
1484
+ if (typeof this.driver.setThinkingLevel === "function") {
1485
+ this.driver.setThinkingLevel(level);
1486
+ }
1487
+ // 同步持久化至全局 settings.json 的 modelThinkingLevels
1488
+ if (this.currentModel) {
1489
+ saveModelThinkingLevelToSettings(this.currentModel, level, this.agentDir);
1490
+ }
1404
1491
  this.flushSnapshot();
1405
1492
  }
1406
1493
  async setCwd(path) {
@@ -1814,6 +1901,9 @@ export class UniversalSession {
1814
1901
  retainFinishedConversations: false,
1815
1902
  openRecentSessionOnProjectSwitch: true,
1816
1903
  skillsFullText: [],
1904
+ skillsCatalogMaxDesc: 250,
1905
+ skillsCatalogShowLocation: false,
1906
+ skillsCatalogBudget: 20000,
1817
1907
  visionBridgeEnabled: false,
1818
1908
  visionBridgeModel: null,
1819
1909
  visionBridgePromptMode: "append",
@@ -1829,6 +1919,7 @@ export class UniversalSession {
1829
1919
  uiLayout: normalizeUiLayout(s?.uiLayout),
1830
1920
  promptTemplate: s?.promptTemplate ?? "",
1831
1921
  promptOverrides: s?.promptOverrides ?? {},
1922
+ promptDisabled: [...(s?.promptDisabled ?? [])],
1832
1923
  toolPromptOverrides: {},
1833
1924
  effectiveSystemPrompt: "",
1834
1925
  promptSourceDefaults: {},
@@ -1990,6 +2081,7 @@ export class UniversalSession {
1990
2081
  customSystemPrompt: s.customSystemPrompt,
1991
2082
  promptTemplate: s.promptTemplate,
1992
2083
  promptOverrides: s.promptOverrides ? { ...s.promptOverrides } : {},
2084
+ promptDisabled: [...(s.promptDisabled ?? [])],
1993
2085
  disabledSkills: [...(s?.disabledSkills ?? [])],
1994
2086
  disabledExtensions: [...(s?.disabledExtensions ?? [])],
1995
2087
  reviewPrompt: s.reviewPrompt ?? "",
@@ -2014,6 +2106,7 @@ export class UniversalSession {
2014
2106
  this.stateStore.saveSettings(this.clientId, {
2015
2107
  promptMode: found.promptMode,
2016
2108
  customSystemPrompt: found.customSystemPrompt,
2109
+ promptDisabled: [...(found.promptDisabled ?? [])],
2017
2110
  disabledSkills: [...(found.disabledSkills ?? [])],
2018
2111
  disabledExtensions: [...(found.disabledExtensions ?? [])],
2019
2112
  reviewPrompt: found.reviewPrompt ?? "",
@@ -2233,7 +2326,7 @@ export class UniversalSession {
2233
2326
  return count;
2234
2327
  }
2235
2328
  /** 创建并启动一个子代理会话 */
2236
- async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title) {
2329
+ async spawnSubagent(prompt, type, cwd, templateName, model, parentId, persist = false, title, _thinking, _notifyOnDone) {
2237
2330
  const maxSubagents = Number(process.env.PI_WEB_MAX_SUBAGENTS) || 8;
2238
2331
  const liveCount = this.getLiveSubagentsCount();
2239
2332
  if (liveCount >= maxSubagents) {
@@ -316,15 +316,100 @@ async function runGit(args, cwd) {
316
316
  });
317
317
  return stdout.trim();
318
318
  }
319
+ /**
320
+ * Patterns to query via `git ls-remote` for a requested ref name.
321
+ * Full `refs/` paths are queried directly (with peeled tag fallback);
322
+ * shorthand names look up branches, tags, and peeled tags.
323
+ */
324
+ export function buildLsRemotePatternsForRef(ref) {
325
+ if (ref.startsWith("refs/")) {
326
+ return [ref, `${ref}^{}`];
327
+ }
328
+ return [`refs/heads/${ref}`, `refs/tags/${ref}`, `refs/tags/${ref}^{}`, ref, `${ref}^{}`];
329
+ }
330
+ /**
331
+ * Pick the remote commit SHA corresponding to a requested ref from `git ls-remote` output.
332
+ *
333
+ * Precedence:
334
+ * 1. Full/explicit ref match (`refs/...^{}`, direct `refs/...`, or `HEAD`)
335
+ * 2. Branch ref: `refs/heads/<ref>`
336
+ * 3. Tag ref: peeled annotated tag (`refs/tags/<ref>^{}`) wins over lightweight tag (`refs/tags/<ref>`)
337
+ */
338
+ export function pickRemoteShaForRef(output, ref) {
339
+ const map = new Map();
340
+ for (const line of output.split(/\r?\n/)) {
341
+ const match = line.trim().match(/^([0-9a-f]{40})\s+(\S+)$/i);
342
+ if (match) {
343
+ map.set(match[2], match[1]);
344
+ }
345
+ }
346
+ // Full / explicit ref match
347
+ if (map.has(`${ref}^{}`))
348
+ return map.get(`${ref}^{}`);
349
+ if (map.has(ref))
350
+ return map.get(ref);
351
+ // Branch: refs/heads/<ref>
352
+ const branchRef = `refs/heads/${ref}`;
353
+ if (map.has(branchRef))
354
+ return map.get(branchRef);
355
+ // Tag: peeled tag wins over unpeeled tag
356
+ const peeledTagRef = `refs/tags/${ref}^{}`;
357
+ if (map.has(peeledTagRef))
358
+ return map.get(peeledTagRef);
359
+ const tagRef = `refs/tags/${ref}`;
360
+ if (map.has(tagRef))
361
+ return map.get(tagRef);
362
+ return null;
363
+ }
319
364
  /**
320
365
  * Compare a clone's HEAD against its remote (lightweight: `ls-remote` fetches
321
- * refs only, no objects). Upstream branch wins when configured, else origin
322
- * HEAD — the same order pi core `getRemoteGitHead` uses.
366
+ * refs only, no objects). When a configured ref (`@...`) is given, the remote
367
+ * benchmark is resolved from that ref (branch, tag, or commit sha) instead of
368
+ * blindly comparing against the checked-out branch's upstream (issue #665).
369
+ * When ref is absent, upstream branch wins when configured, else origin HEAD.
323
370
  */
324
- export async function defaultCheckGitExtension(installDir) {
371
+ export async function defaultCheckGitExtension(installDir, ref) {
325
372
  const localSha = await runGit(["rev-parse", "HEAD"], installDir);
326
373
  if (!/^[0-9a-f]{40}$/i.test(localSha))
327
374
  throw new Error(`Bad local HEAD: ${localSha.slice(0, 20)}`);
375
+ const targetRef = ref?.trim() || null;
376
+ if (targetRef) {
377
+ let remoteSha = null;
378
+ let lsRemoteError = null;
379
+ try {
380
+ const patterns = buildLsRemotePatternsForRef(targetRef);
381
+ const out = await runGit(["ls-remote", "origin", ...patterns], installDir);
382
+ remoteSha = pickRemoteShaForRef(out, targetRef);
383
+ }
384
+ catch (err) {
385
+ lsRemoteError = err;
386
+ }
387
+ if (!remoteSha && /^[0-9a-f]{7,40}$/i.test(targetRef)) {
388
+ // Commit SHA reference: if local HEAD already matches the requested SHA (prefix or exact),
389
+ // the clone is fully up to date.
390
+ if (localSha.toLowerCase().startsWith(targetRef.toLowerCase())) {
391
+ remoteSha = localSha;
392
+ }
393
+ else {
394
+ try {
395
+ const parsed = await runGit(["rev-parse", `${targetRef}^{commit}`], installDir);
396
+ if (/^[0-9a-f]{40}$/i.test(parsed))
397
+ remoteSha = parsed;
398
+ }
399
+ catch {
400
+ /* commit not present in local repo yet */
401
+ }
402
+ if (!remoteSha)
403
+ remoteSha = targetRef;
404
+ }
405
+ }
406
+ if (!remoteSha) {
407
+ if (lsRemoteError)
408
+ throw lsRemoteError;
409
+ throw new Error(`Failed to resolve remote ref: ${targetRef}`);
410
+ }
411
+ return { localSha, remoteSha };
412
+ }
328
413
  let remoteSha = null;
329
414
  try {
330
415
  const upstream = await runGit(["rev-parse", "--abbrev-ref", "@{upstream}"], installDir);
@@ -758,8 +843,8 @@ gitCheck = defaultCheckGitExtension) {
758
843
  try {
759
844
  if (!t.installDir)
760
845
  throw new Error("missing install dir");
761
- const { localSha, remoteSha } = await gitCheck(t.installDir);
762
- const upToDate = localSha.trim() === remoteSha.trim();
846
+ const { localSha, remoteSha } = await gitCheck(t.installDir, t.ref);
847
+ const upToDate = localSha.trim().toLowerCase() === remoteSha.trim().toLowerCase();
763
848
  results[i] = {
764
849
  name: t.name,
765
850
  kind: t.kind,
@@ -21,6 +21,9 @@ import { gitDirOf } from "./scm.js";
21
21
  const exec = promisify(execFile);
22
22
  /** 单次 git 快照/还原命令超时时间(毫秒)。 */
23
23
  const GIT_SNAPSHOT_TIMEOUT_MS = 15_000;
24
+ /** 物理还原互斥链(#697):同一 cwd 的 git read-tree/clean 序列串行执行,
25
+ * 杜绝并发回滚交错破坏 index/工作区;key 为 resolve 后的 cwd。 */
26
+ const pendingRestores = new Map();
24
27
  /** 执行单条 git 命令,返回 stdout。 */
25
28
  async function runGit(cwd, args, envExtra) {
26
29
  const { stdout } = await exec("git", ["-c", "core.quotepath=false", ...args], {
@@ -221,8 +224,10 @@ export async function createWorkspaceSnapshot(cwd) {
221
224
  }
222
225
  if (!tree)
223
226
  return null;
224
- // 异步更新持久化影子 index 缓存供下轮秒级复用
225
- void copyFile(tempIndex, cachePath).catch(() => { });
227
+ // 异步更新持久化影子 index 缓存供下轮秒级复用。必须 await 后再进 finally:
228
+ // 否则 finally 里 rm(tempIndex) 会在拷贝中途删掉源文件,Windows 上拷贝要么
229
+ // EBUSY 失败、要么把半截内容写进 cachePath(下轮读坏缓存再回落,缓存失效)。
230
+ await copyFile(tempIndex, cachePath).catch(() => { });
226
231
  // 优化 3:检查 tree 是否与该 cwd 上次快照完全一致
227
232
  const normCwd = resolve(cwd);
228
233
  const last = lastSnapshotByCwd.get(normCwd);
@@ -283,6 +288,32 @@ export async function createWorkspaceSnapshot(cwd) {
283
288
  * 同仓库的兄弟目录在以上任何一步都不受影响。
284
289
  */
285
290
  export async function restoreWorkspaceSnapshot(cwd, snapshotRef) {
291
+ const key = resolve(cwd);
292
+ const prev = pendingRestores.get(key);
293
+ let release;
294
+ const gate = new Promise((r) => {
295
+ release = r;
296
+ });
297
+ const mine = (prev ?? Promise.resolve()).then(() => gate);
298
+ pendingRestores.set(key, mine);
299
+ if (prev) {
300
+ try {
301
+ await prev;
302
+ }
303
+ catch {
304
+ // 前一还原失败不阻塞后继
305
+ }
306
+ }
307
+ try {
308
+ return await restoreWorkspaceSnapshotInner(cwd, snapshotRef);
309
+ }
310
+ finally {
311
+ if (pendingRestores.get(key) === mine)
312
+ pendingRestores.delete(key);
313
+ release();
314
+ }
315
+ }
316
+ async function restoreWorkspaceSnapshotInner(cwd, snapshotRef) {
286
317
  const gitDir = await gitDirOf(cwd);
287
318
  if (!gitDir) {
288
319
  return { success: false, error: "Workspace is not a Git repository" };
@@ -232,7 +232,20 @@ export async function removeWorktree(cwd, targetPathInput, force = false, lang)
232
232
  if (force)
233
233
  args.push("--force");
234
234
  args.push(targetPath);
235
- await runGit(cwd, args);
235
+ let lastErr;
236
+ for (let attempt = 0; attempt < 3; attempt++) {
237
+ try {
238
+ await runGit(cwd, args);
239
+ return;
240
+ }
241
+ catch (err) {
242
+ lastErr = err;
243
+ if (attempt < 2) {
244
+ await new Promise((r) => setTimeout(r, 200));
245
+ }
246
+ }
247
+ }
248
+ throw lastErr;
236
249
  }
237
250
  /** 获取当前目录的完整工作树上下文元数据(用于 UI 横幅与快照)。 */
238
251
  export async function getWorktreeContext(cwd) {
@@ -260,3 +273,178 @@ export async function getWorktreeContext(cwd) {
260
273
  return null;
261
274
  }
262
275
  }
276
+ /** 仓库级异步操作互斥锁(防止多个子代理并发创建/删除工作树时碰撞 Git 内部文件锁)。 */
277
+ const repoLocks = new Map();
278
+ export async function withRepoLock(repoPath, task) {
279
+ const key = normalizeWirePath(repoPath);
280
+ const prev = repoLocks.get(key) ?? Promise.resolve();
281
+ let release;
282
+ const gate = new Promise((resolve) => {
283
+ release = resolve;
284
+ });
285
+ repoLocks.set(key, prev.catch(() => { }).then(() => gate));
286
+ try {
287
+ await prev.catch(() => { });
288
+ return await task();
289
+ }
290
+ finally {
291
+ release();
292
+ if (repoLocks.get(key) === gate) {
293
+ repoLocks.delete(key);
294
+ }
295
+ }
296
+ }
297
+ /** 自动将 .worktrees/ 加入 .git/info/exclude(零污染:防止未在 .gitignore 忽略此目录的用户仓库出现 untracked 脏状态)。 */
298
+ export async function ensureWorktreeExcluded(repoPath) {
299
+ try {
300
+ const gitCommonDir = (await runGit(repoPath, ["rev-parse", "--git-common-dir"], FAST_GIT_TIMEOUT_MS)).trim();
301
+ const absGitCommon = resolve(repoPath, gitCommonDir);
302
+ const excludeFile = resolve(absGitCommon, "info", "exclude");
303
+ const { existsSync, readFileSync, appendFileSync, mkdirSync, writeFileSync } = await import("node:fs");
304
+ if (existsSync(excludeFile)) {
305
+ const content = readFileSync(excludeFile, "utf-8");
306
+ if (!content.includes(".worktrees")) {
307
+ appendFileSync(excludeFile, "\n# pi-web-ui worktrees\n.worktrees/\n");
308
+ }
309
+ }
310
+ else {
311
+ mkdirSync(resolve(absGitCommon, "info"), { recursive: true });
312
+ writeFileSync(excludeFile, "# pi-web-ui worktrees\n.worktrees/\n", "utf-8");
313
+ }
314
+ }
315
+ catch {
316
+ // non-fatal
317
+ }
318
+ }
319
+ /**
320
+ * 为子代理创建专用的 Git 工作树与分支(issue #728)。
321
+ * 自动从当前 HEAD 检出,并建立依赖软链接(node_modules/.venv 等),使子代理可立即执行测试。
322
+ */
323
+ export async function createSubagentWorktree(baseCwd, subagentId, lang) {
324
+ const l = lang?.() ?? "en";
325
+ const inside = await isInsideGitRepo(baseCwd);
326
+ if (!inside) {
327
+ throw new Error(pick(l, `Git 工作树隔离失败:目录「${baseCwd}」不是 Git 仓库。worktree 隔离模式要求工作区位于有效的 Git 仓库中。`, `Git worktree isolation failed: "${baseCwd}" is not a Git repository. Worktree isolation mode requires a valid Git repository.`, "worktree.isolation.not_git", { baseCwd }));
328
+ }
329
+ const rawText = await runGit(baseCwd, ["worktree", "list", "--porcelain"]);
330
+ const rawItems = parseWorktreePorcelain(rawText);
331
+ const mainRepoPath = rawItems[0]?.path || normalizeWirePath(resolve(baseCwd));
332
+ const worktreeDir = normalizeWirePath(resolve(mainRepoPath, ".worktrees", subagentId));
333
+ const branchName = `subagent/${subagentId}`;
334
+ // 获取创建时刻的当前 HEAD SHA 作为基准
335
+ const baseCommit = (await runGit(baseCwd, ["rev-parse", "HEAD"])).trim();
336
+ // 确定子代理的执行目录(若 baseCwd 在 mainRepoPath 的子目录中,则映射至工作树对应子目录)
337
+ const normBase = normalizeWirePath(resolve(baseCwd));
338
+ const normMain = normalizeWirePath(resolve(mainRepoPath));
339
+ let subagentCwd = worktreeDir;
340
+ if (normBase.startsWith(normMain + "/")) {
341
+ const rel = normBase.slice(normMain.length + 1);
342
+ subagentCwd = normalizeWirePath(resolve(worktreeDir, rel));
343
+ }
344
+ await withRepoLock(mainRepoPath, async () => {
345
+ await ensureWorktreeExcluded(mainRepoPath);
346
+ const { mkdirSync, existsSync, symlinkSync } = await import("node:fs");
347
+ mkdirSync(resolve(mainRepoPath, ".worktrees"), { recursive: true });
348
+ // 使用 -B 确保分支已存在时安全重置,HEAD 确保从当前状态检出
349
+ await runGit(mainRepoPath, ["worktree", "add", "-B", branchName, worktreeDir, "HEAD"]);
350
+ // 依赖桥接:若主仓库根有 node_modules 或 .venv,在工作树中建立目录软连接/Junction,
351
+ // 这样子代理可立即运行 npm test / python 测试,无需耗时重装依赖
352
+ for (const depDir of ["node_modules", ".venv"]) {
353
+ const src = resolve(mainRepoPath, depDir);
354
+ const dest = resolve(worktreeDir, depDir);
355
+ if (existsSync(src) && !existsSync(dest)) {
356
+ try {
357
+ symlinkSync(src, dest, process.platform === "win32" ? "junction" : "dir");
358
+ }
359
+ catch {
360
+ // 软链接失败不阻断工作树核心流程
361
+ }
362
+ }
363
+ }
364
+ });
365
+ return {
366
+ worktreePath: worktreeDir,
367
+ mainRepoPath,
368
+ branch: branchName,
369
+ baseCommit,
370
+ subagentCwd,
371
+ };
372
+ }
373
+ /**
374
+ * 终态判定与清理(issue #728):
375
+ * 双重判定改动(未提交修改 + 领先 commit 数):
376
+ * - 无改动:自动安全清理工作树并删除临时分支;
377
+ * - 有改动:保留工作树与分支供父对话审阅、合并或清理。
378
+ */
379
+ export async function finalizeSubagentWorktree(wt, lang) {
380
+ if (wt.finalized)
381
+ return wt;
382
+ const { existsSync } = await import("node:fs");
383
+ if (!existsSync(wt.worktreePath)) {
384
+ wt.finalized = true;
385
+ wt.cleanedUp = true;
386
+ return wt;
387
+ }
388
+ try {
389
+ const { isDirty, count: uncommittedCount } = await getUncommittedCount(wt.worktreePath);
390
+ let aheadCount = 0;
391
+ try {
392
+ const currentHead = (await runGit(wt.worktreePath, ["rev-parse", "HEAD"])).trim();
393
+ if (currentHead !== wt.baseCommit) {
394
+ aheadCount = await getAheadCount(wt.worktreePath, wt.baseCommit);
395
+ if (aheadCount === 0 && currentHead !== wt.baseCommit) {
396
+ aheadCount = 1;
397
+ }
398
+ }
399
+ }
400
+ catch {
401
+ aheadCount = 0;
402
+ }
403
+ wt.isDirty = isDirty;
404
+ wt.uncommittedCount = uncommittedCount;
405
+ wt.aheadCount = aheadCount;
406
+ const hasChanges = isDirty || aheadCount > 0;
407
+ if (!hasChanges) {
408
+ // 没有改动 -> 自动清理工作树与临时分支
409
+ await withRepoLock(wt.mainRepoPath, async () => {
410
+ // 先移除建立的软链接/Junction,防止 Windows 下锁死目录句柄
411
+ for (const depDir of ["node_modules", ".venv"]) {
412
+ const p = resolve(wt.worktreePath, depDir);
413
+ if (existsSync(p)) {
414
+ try {
415
+ const { unlinkSync } = await import("node:fs");
416
+ unlinkSync(p);
417
+ }
418
+ catch { }
419
+ }
420
+ }
421
+ await removeWorktree(wt.mainRepoPath, wt.worktreePath, true, lang);
422
+ try {
423
+ await runGit(wt.mainRepoPath, ["branch", "-D", wt.branch]);
424
+ }
425
+ catch { }
426
+ });
427
+ wt.cleanedUp = true;
428
+ }
429
+ else {
430
+ // 有改动 -> 完整保留,由父对话决定合并还是清理
431
+ wt.cleanedUp = false;
432
+ }
433
+ wt.finalized = true;
434
+ }
435
+ catch (err) {
436
+ wt.finalized = true;
437
+ wt.error = err.message;
438
+ }
439
+ return wt;
440
+ }
441
+ /** 剪枝清理已损坏或残留的孤儿工作树 */
442
+ export async function pruneOrphanSubagentWorktrees(cwd) {
443
+ try {
444
+ const inside = await isInsideGitRepo(cwd);
445
+ if (!inside)
446
+ return;
447
+ await runGit(cwd, ["worktree", "prune"], FAST_GIT_TIMEOUT_MS);
448
+ }
449
+ catch { }
450
+ }