pi-web-ui 0.103.1 → 0.103.3

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.
package/CHANGELOG.md CHANGED
@@ -10,6 +10,35 @@
10
10
 
11
11
  ## [Unreleased]
12
12
 
13
+ ## [0.103.3] — 2026-10-11
14
+
15
+ ### Added
16
+
17
+ - **飞书机器人官方插件(plugins/feishu v0.1.0)** —— 支持飞书开放平台应用机器人接入(WebSocket 长连接免公网 IP,以及自定义群机器人 Webhook 通知);支持私聊与群聊 @ 触发对话、富文本与交互式卡片发送、表情回应、历史消息搜索,以及 App Secret / Encrypt Key / Verification Token 加密存储。
18
+ - **子代理并发名额按活跃态统计与 `PI_WEB_MAX_SUBAGENTS` 环境变量(#589)** —— 子代理配额改为仅统计正在运行(`status === "running"`)的子代理,已完成的子代理不再永久占用名额;新增 `PI_WEB_MAX_SUBAGENTS` 环境变量支持调整并发上限(默认 16)。
19
+
20
+ ### Fixed
21
+
22
+ - **`todo_list` 工具 Schema 显式补齐 `action.type`(#590)** —— 为 `todo_list` 工具的 `action` 参数显式声明 `type: "string"`,修复 Moonshot / Kimi 等严格校验 JSON Schema 的端点每次请求返回 HTTP 400 的问题,并新增静态守卫单测拦截缺失 `type` 的 `Type.Unsafe` 定义。
23
+ - **主对话执行中设定目标时自动中断旧运行并让位给执行者(#591)** —— 设目标首轮派发目标执行者前,若主对话仍有设目标前的旧运行在飞,服务端先通过 `interruptMainConv` 中断旧运行并弹出提示(同时豁免该次预期让位 abort 误清目标),避免主对话与目标执行者在同一工作区并行动工互相干扰;委托期间用户在主对话发起的新聊天不受影响。
24
+ - **WebUI 主题代理保留单参数装饰器包裹的组件正文(#592)** —— 在 `mockThemeProxy` 中补齐 `italic`、`underline`、`inverse` 单参数装饰器并将通用兜底改为取最后一个字符串参数,修复扩展 widget 使用单参数主题装饰器时正文被清空的问题。
25
+
26
+ <!-- auto-i18n:start -->
27
+
28
+ ### i18n
29
+
30
+ - 服务端新增 key(1):`agent.goal.preempt_main`
31
+ - 服务端文案变更(1):`agent.subagent.limit.reached`
32
+
33
+ <!-- auto-i18n:end -->
34
+
35
+ ## [0.103.2] — 2026-10-11
36
+
37
+ ### Added
38
+
39
+ - **微信通道插件根目录联动与交互升级(plugins/wechat-ilink v0.3.0)** —— 支持微信通道与当前工作区根目录联动,扫码与配对视图优化。
40
+ - **左侧栏运行中会话项目分组右键菜单** —— 左栏非当前项目的运行中会话分组标题支持右键调出项目操作菜单(以项目打开、移除等)。
41
+
13
42
  ## [0.103.1] — 2026-10-11
14
43
 
15
44
  ### Fixed
@@ -31,9 +60,11 @@
31
60
  - **样式与 CSS 变量兼容性修复** —— 统一目录浏览器 SSH 相关面板的 Hover 高亮样式为系统标准 `--bg-elev2`,消除未定义变量告警。
32
61
 
33
62
  <!-- auto-i18n:start -->
63
+
34
64
  ### i18n
35
65
 
36
66
  - 前端新增 key(21):`workspaceModeLocal`、`workspaceModeRemote`、`sshHost`、`sshPort`、`sshUser`、`sshAuthType`、`sshPassword`、`sshKeyPath`、`sshAgent`、`sshSaveProfile`、`sshProfileName`、`sshConnectAndProbe`、`sshConnecting`、`sshSavedProfiles`、`sshInstallTool`、`sshInstalling`、`sshSkipAndBrowse`、`sshOpenRemoteWorkspace`、`sshDisconnect`、`sshDeleteProfileConfirm`、`tuiOverlayTitle`
67
+
37
68
  <!-- auto-i18n:end -->
38
69
 
39
70
  ## [0.102.0] — 2026-10-10
@@ -47,9 +78,11 @@
47
78
  - **SFTP 插件深度增强与引擎优化** —— 扩充默认 SSH 私钥探测路径与连接稳定性;优化客户端文件操作列表与动作响应机制。
48
79
 
49
80
  <!-- auto-i18n:start -->
81
+
50
82
  ### i18n
51
83
 
52
84
  - 前端新增 key(28):`modelQuestionRejectWithNote`、`modelQuestionRejectWithNoteTip`、`recommended`、`keyShortcutTip`、`questionCardWaiting`、`questionCardCancelled`、`questionCardRejectReason`、`questionCardUserCustom`、`questionCardNoSelection`、`tpl.confirmFillTitle`、`tpl.confirmFillDesc`、`tpl.confirmFillAppend`、`tpl.confirmFillOverwrite`、`pluginOfficialMarket`、`pluginOfficialMarketHint`、`pluginOfficialLink`、`pluginOfficialLinkHint`、`copyConversationLink`、`copyMessageLink`、`codemodeModeLabel`、`codemodeModeHint`、`codemodeModeOn`、`codemodeModeOnly`、`codemodeInlineBudgetLabel`、`codemodeInlineBudgetHint`、`codemodeNestedApprovalBadge`、`codemodeNestedApprovalDesc`、`codemodeSavedImages`
85
+
53
86
  <!-- auto-i18n:end -->
54
87
 
55
88
  ## [0.101.0] — 2026-10-10
@@ -1609,6 +1642,8 @@ when?, children?}`,也收 `topbar` / `settings` 这类简写别名);宿主
1609
1642
  - 0.29.0(2026-08-23):全局搜索弹窗(Ctrl+K)+ 消息列表惰性窗口化。
1610
1643
 
1611
1644
  [Unreleased]: https://github.com/xing-shuyin/pi-web-ui/compare/v0.101.0...main
1645
+ [0.103.3]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.103.3
1646
+ [0.103.2]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.103.2
1612
1647
  [0.103.1]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.103.1
1613
1648
  [0.103.0]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.103.0
1614
1649
  [0.102.0]: https://github.com/xing-shuyin/pi-web-ui/releases/tag/v0.102.0
@@ -5,8 +5,16 @@ export const RUN_ARGS_CAP = 4000;
5
5
  export const RUN_RESULT_CAP = 4000;
6
6
  /** Cap on simultaneously open NON-subagent conversations of ONE project */
7
7
  export const MAX_OPEN_CONVERSATIONS = 8;
8
- /** 同时存活的子代理上限(按客户端计,含嵌套派生的孙子辈)。 */
8
+ /** 同时运行(非终态)的子代理默认并发上限(按客户端计,含嵌套派生的孙子辈;可通过 PI_WEB_MAX_SUBAGENTS 覆盖,#589)。 */
9
9
  export const MAX_SUBAGENTS = 16;
10
+ /** 读取当前生效的子代理并发上限(支持 PI_WEB_MAX_SUBAGENTS 环境变量覆盖,默认 16,最小 1)。 */
11
+ export function getMaxSubagents() {
12
+ const raw = Number(process.env.PI_WEB_MAX_SUBAGENTS);
13
+ if (Number.isFinite(raw) && raw > 0) {
14
+ return Math.max(1, Math.floor(raw));
15
+ }
16
+ return MAX_SUBAGENTS;
17
+ }
10
18
  /** SubagentSnapshot.prompt 下发上限:存的是全量 prompt,快照里只带前 N 字符。 */
11
19
  export const SUBAGENT_PROMPT_SNAPSHOT_CAP = 2000;
12
20
  export const DEFAULT_CONV_TITLE = "新对话";
@@ -55,7 +55,7 @@ import { ComposerDraftsStore } from "./composer-drafts.js";
55
55
  import { readPermissionFromSession } from "./permission-preset.js";
56
56
  import { createWorkspaceSnapshot, restoreWorkspaceSnapshot, findMatchingWorkspaceSnapshot, } from "./workspace-snapshot.js";
57
57
  import { createScheduleToolHost, createConversationReadHost, createClaimToolHost, createCompactContextHost, createSkillToolHost, } from "./tool-host-factories.js";
58
- import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf } from "./subagent-helpers.js";
58
+ import { toSubagentSnapshot, listSubagentSnapshots, subagentRunOutcome, roleOutcomeOf, countActiveSubagents, } from "./subagent-helpers.js";
59
59
  import { resolveUserMessageEntryId, resolveConversationMessageEntry } from "./message-entry-resolver.js";
60
60
  import { fillSkillContents } from "./skill-content-filler.js";
61
61
  import { hasSettledAssistantUsage, estimateNonSystemTokens, renderMainCompose } from "./prompt-assembler.js";
@@ -204,7 +204,7 @@ import { makeMarkersListTool } from "./markers-list-tool.js";
204
204
  import { makeAskUserQuestionTool, shouldPopQuestion } from "./ask-user-question-tool.js";
205
205
  import { normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, } from "./browser-page-tool.js";
206
206
  export { makeAskUserQuestionTool, shouldPopQuestion, normalizePageCallTimeoutMs, collectBrowserPageArgs, formatPageCallResult, formatBrowserPageError, makeBrowserPageTool, extractShotImage, };
207
- import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP, MAX_OPEN_CONVERSATIONS, MAX_SUBAGENTS, SUBAGENT_PROMPT_SNAPSHOT_CAP, DEFAULT_CONV_TITLE, truncRun, previewToolResult, atomicWriteFileSync, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
207
+ import { RUN_TASK_CAP, RUN_ARGS_CAP, RUN_RESULT_CAP, MAX_OPEN_CONVERSATIONS, getMaxSubagents, SUBAGENT_PROMPT_SNAPSHOT_CAP, DEFAULT_CONV_TITLE, truncRun, previewToolResult, atomicWriteFileSync, conversationTitle, pluginToolToDefinition, contentFingerprint, extractPartialText, extractAssistantTextFromContent, firstSentence, modelKeyOf, contextWindowOf, } from "./agent-formatters.js";
208
208
  export { workspacePath };
209
209
  import { MAX_TRANSCRIPT_SCAN_BYTES, MAX_SEARCH_TEXT_CHARS, sessionMatchesMetadata, messageSearchText, collectSessionAnchors, piSessionsRoot, isInsideSessionsDir, readCwdFromSessionHeader, } from "./session-search.js";
210
210
  export { piSessionsRoot, isInsideSessionsDir };
@@ -425,6 +425,8 @@ export class ClientSession {
425
425
  .catch(() => { });
426
426
  }
427
427
  }
428
+ /** 正在创建 runtime 尚未注册进 convs 的轻量子代理数量(防并发 spawn 绕过并发名额,#589)。 */
429
+ spawningSubagents = 0;
428
430
  /** 创建子代理 conversation(inMemory runtime + 独立 terminals),listed 入左栏,
429
431
  * 并在其上触发一次完整回合。返回 convId(= 工具 runId)。
430
432
  *
@@ -443,159 +445,188 @@ export class ClientSession {
443
445
  }
444
446
  }
445
447
  else {
446
- const liveSubagents = [...this.convs.values()].filter((c) => c.isSubagent).length;
447
- if (liveSubagents >= MAX_SUBAGENTS) {
448
- throw new Error(pick(this.getLang(), `子代理数量已达上限(${MAX_SUBAGENTS} 个),请先用 subagent_wait_all 等一部分完成、或用 subagent_stop 停掉不需要的再派发`, `Subagent limit reached (${MAX_SUBAGENTS} live). Wait for some with subagent_wait_all or stop unneeded ones with subagent_stop before spawning more`, "agent.subagent.limit.reached", { limit: MAX_SUBAGENTS }));
449
- }
450
- }
451
- // 真正的派发者(withSubagentOwner 按 runtime 归属填入):cwd 基准 / 跟随模型 /
452
- // 跟随思考强度一律读它,而不是派发瞬间的 active——后台对话产出时用户可能正
453
- // 看着别的项目,读 active 会跟错模型、把相对 cwd 解析到错误的项目下。
454
- const spawner = parentId ? this.convs.get(parentId) : undefined;
455
- const spawnerSession = spawner?.session ?? this.session;
456
- const baseCwd = spawner?.cwd ?? this.cwd;
457
- // 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
458
- const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
459
- const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
460
- const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
461
- const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
462
- const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
463
- if (!persist) {
464
- // 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
465
- // 但保持 persist = false(不写 .jsonl 对话文件、不污染历史记录)
466
- const ephemeralDir = join(this.agentDir, "subagent-sessions", conversationId);
467
- try {
468
- mkdirSync(ephemeralDir, { recursive: true });
469
- sessionManager.sessionDir = ephemeralDir;
448
+ // #589:名额与可见性解耦——只统计正在运行/启动中的活跃子代理,已结束(done/canceled/error)
449
+ // 的子代理留在左栏供用户审阅追溯,不再占用并发名额,使 wait_all / stop 能真正释放名额。
450
+ const maxSubagents = getMaxSubagents();
451
+ const liveSubagents = countActiveSubagents(this.convs.values(), this.spawningSubagents);
452
+ if (liveSubagents >= maxSubagents) {
453
+ throw new Error(pick(this.getLang(), `同时运行的子代理数量已达上限(${maxSubagents} 个),请先用 subagent_wait_all 等一部分完成、或用 subagent_stop 停掉不需要的再派发`, `Active subagent limit reached (${maxSubagents} live). Wait for some with subagent_wait_all or stop unneeded ones with subagent_stop before spawning more`, "agent.subagent.limit.reached", { limit: maxSubagents }));
470
454
  }
471
- catch { }
472
455
  }
473
- const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
474
- cwd: sessionBaseDir,
475
- agentDir: this.agentDir,
476
- sessionManager,
477
- });
478
- const conv = this.makeConversation(runtime, conversationId, terminals);
479
- conv.cwd = resolvedCwd;
480
- conv.isSubagent = !persist;
481
- // 父对话 = 真正派发它的会话(按会话归属的 host 包装填入)。直接用 active
482
- // 会错:后台对话运行时用户可能正看着别的项目对话,孩子会被记到无关
483
- // 对话名下、沉到别的项目组底部(issue #95)。缺省才回退到 active。
484
- conv.parentId = parentId ?? this.activeId ?? undefined;
485
- conv.subagentType = type;
486
- conv.subagentPrompt = prompt;
487
- // 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
488
- // (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
489
- conv.subagentTemplate = apply;
490
- // 插件工具门与模板扩展白名单对齐:白名单非空时插件/MCP 工具(无 SDK
491
- // extensionKey 身份)不进该会话。工厂期 customTools 不注册 + 下面的
492
- // syncPluginTools 不回补,模板热改不影响已运行的子代理(与 prompt/技能一致)。
493
- conv.subagentBarsPluginTools = !!apply && apply.enabledExtensions.length > 0;
494
- conv.listed = true;
495
- conv.title = title ?? subagentTitle(prompt);
496
- this.convs.set(conv.id, conv);
497
- // 子代理会话同样订阅 SDK 事件:否则 onEvent 永不触发,点开查看时没有
498
- // message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
499
- // 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
500
- conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
501
- // 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
502
- this.applyRetryOverrides();
503
- // 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
504
- this.applyCompactionOverrides();
505
- this.applyCodemodeOverrides();
506
- // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
507
- // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
456
+ const isEphemeralSubagent = !persist;
457
+ if (isEphemeralSubagent) {
458
+ this.spawningSubagents++;
459
+ }
460
+ let handedOffToConv = false;
508
461
  try {
509
- await conv.session.bindExtensions({
510
- mode: "rpc",
511
- // 子代理的扩展照常拿到完整 ExtensionUIContext(扩展调用新增方法不会因
512
- // 局部 mock 缺失而崩),但它是 headless 的:UI 输出全部丢弃、弹窗按取消返回,
513
- // 因此既不与主对话的 widget/status 串台,也不会让扩展卡在永远无人应答的弹窗上。
514
- uiContext: WebUIContext.headless(),
515
- onError: this.makeExtensionErrorReporter({
516
- text: `子代理 ${conversationId}:`,
517
- textEn: `Subagent ${conversationId}: `,
518
- }),
462
+ // 真正的派发者(withSubagentOwner 按 runtime 归属填入):cwd 基准 / 跟随模型 /
463
+ // 跟随思考强度一律读它,而不是派发瞬间的 active——后台对话产出时用户可能正
464
+ // 看着别的项目,读 active 会跟错模型、把相对 cwd 解析到错误的项目下。
465
+ const spawner = parentId ? this.convs.get(parentId) : undefined;
466
+ const spawnerSession = spawner?.session ?? this.session;
467
+ const baseCwd = spawner?.cwd ?? this.cwd;
468
+ // 相对 cwd 按派发者所在目录解析:直接透传会相对 server 进程 cwd 落到别处。
469
+ const resolvedCwd = isRemoteWorkspaceUri(baseCwd) ? baseCwd : cwd ? resolve(baseCwd, cwd) : baseCwd;
470
+ const sessionBaseDir = resolveWorkspaceSessionDir(this.stateStore?.dataDir, resolvedCwd);
471
+ const conversationId = persist ? `conv-${randomUUID().slice(0, 8)}` : `sa-${randomUUID().slice(0, 8)}`;
472
+ const terminals = this.makeTerminalManager(conversationId, resolvedCwd);
473
+ const sessionManager = persist ? SessionManager.create(sessionBaseDir) : SessionManager.inMemory(sessionBaseDir);
474
+ if (!persist) {
475
+ // 为内存子代理提供隔离的临时运行目录(供 SoL-Pi 等依赖 getSessionDir 的扩展正常放置缓存),
476
+ // 但保持 persist = false(不写 .jsonl 对话文件、不污染历史记录)
477
+ const ephemeralDir = join(this.agentDir, "subagent-sessions", conversationId);
478
+ try {
479
+ mkdirSync(ephemeralDir, { recursive: true });
480
+ sessionManager.sessionDir = ephemeralDir;
481
+ }
482
+ catch { }
483
+ }
484
+ const runtime = await createAgentSessionRuntime(this.makeRuntimeFactory(terminals, apply, conversationId), {
485
+ cwd: sessionBaseDir,
486
+ agentDir: this.agentDir,
487
+ sessionManager,
519
488
  });
520
- }
521
- catch {
522
- // 绑定失败不阻断运行。
523
- }
524
- // 指定模型(显式 model 参数 → 模板 model → 设置面板默认)时,在首回合前
525
- // 给子代理会话换模型;全都不给 = 跟随主对话:把发起会话当前的模型也
526
- // 显式搬过来(新 runtime 的默认模型未必等于主对话刚选的模型)。
527
- const resolvedModel = model ?? (apply?.model?.trim() || null) ?? (this.settingsSvc.current.subagentDefaultModel || null);
528
- const followModel = resolvedModel
529
- ? resolvedModel
530
- : spawnerSession.model
531
- ? `${spawnerSession.model.provider}/${spawnerSession.model.id}`
532
- : null;
533
- if (followModel) {
534
- const slash = followModel.indexOf("/");
535
- const m = slash > 0 && slash < followModel.length - 1
536
- ? this.sharedModelRuntime?.getModel(followModel.slice(0, slash), followModel.slice(slash + 1))
537
- : undefined;
538
- if (m) {
489
+ const conv = this.makeConversation(runtime, conversationId, terminals);
490
+ conv.cwd = resolvedCwd;
491
+ conv.isSubagent = !persist;
492
+ if (conv.isSubagent) {
493
+ // 首轮 sendUserMessage 进入流式前的预检/模型切换窗口标记为投递中,
494
+ // 确保并发名额与快照状态在此窗口内均按运行中处理(#589)。
495
+ conv.promptInFlight = true;
496
+ }
497
+ // 父对话 = 真正派发它的会话(按会话归属的 host 包装填入)。直接用 active
498
+ // 会错:后台对话运行时用户可能正看着别的项目对话,孩子会被记到无关
499
+ // 对话名下、沉到别的项目组底部(issue #95)。缺省才回退到 active。
500
+ conv.parentId = parentId ?? this.activeId ?? undefined;
501
+ conv.subagentType = type;
502
+ conv.subagentPrompt = prompt;
503
+ // 模板快照留在对话上:forceReset 重建 runtime 时工厂要按同一模板组装
504
+ // (system prompt/技能/扩展白名单),否则重建后回落主会话设置。
505
+ conv.subagentTemplate = apply;
506
+ // 插件工具门与模板扩展白名单对齐:白名单非空时插件/MCP 工具(无 SDK
507
+ // extensionKey 身份)不进该会话。工厂期 customTools 不注册 + 下面的
508
+ // syncPluginTools 不回补,模板热改不影响已运行的子代理(与 prompt/技能一致)。
509
+ conv.subagentBarsPluginTools = !!apply && apply.enabledExtensions.length > 0;
510
+ conv.listed = true;
511
+ conv.title = title ?? subagentTitle(prompt);
512
+ this.convs.set(conv.id, conv);
513
+ if (isEphemeralSubagent) {
514
+ handedOffToConv = true;
515
+ this.spawningSubagents = Math.max(0, this.spawningSubagents - 1);
516
+ }
517
+ // 子代理会话同样订阅 SDK 事件:否则 onEvent 永不触发,点开查看时没有
518
+ // message_delta 流式增量、快照也不刷新,只能靠切走切回时的 flushSnapshot
519
+ // 看到新内容(dismiss/释放流程本来就会 unsubscribe,不泄漏)。
520
+ conv.unsubscribe = conv.session.subscribe((event) => this.onEvent(conv, event));
521
+ // 子代理不走 bindSession——这里同样注入面板的重试次数覆盖。
522
+ this.applyRetryOverrides();
523
+ // 软上限覆盖同样重放(子代理跟随主对话的压缩阈值,issue #229)。
524
+ this.applyCompactionOverrides();
525
+ this.applyCodemodeOverrides();
526
+ // 扩展绑定(rpc 模式);用 headless 的 Web UI context:
527
+ // 扩展绑定时不会因缺方法崩,UI 输出也不下发(不会与主对话的 widget/status 冲突)。
528
+ try {
529
+ await conv.session.bindExtensions({
530
+ mode: "rpc",
531
+ // 子代理的扩展照常拿到完整 ExtensionUIContext(扩展调用新增方法不会因
532
+ // 局部 mock 缺失而崩),但它是 headless 的:UI 输出全部丢弃、弹窗按取消返回,
533
+ // 因此既不与主对话的 widget/status 串台,也不会让扩展卡在永远无人应答的弹窗上。
534
+ uiContext: WebUIContext.headless(),
535
+ onError: this.makeExtensionErrorReporter({
536
+ text: `子代理 ${conversationId}:`,
537
+ textEn: `Subagent ${conversationId}: `,
538
+ }),
539
+ });
540
+ }
541
+ catch {
542
+ // 绑定失败不阻断运行。
543
+ }
544
+ // 指定模型(显式 model 参数 → 模板 model → 设置面板默认)时,在首回合前
545
+ // 给子代理会话换模型;全都不给 = 跟随主对话:把发起会话当前的模型也
546
+ // 显式搬过来(新 runtime 的默认模型未必等于主对话刚选的模型)。
547
+ const resolvedModel = model ?? (apply?.model?.trim() || null) ?? (this.settingsSvc.current.subagentDefaultModel || null);
548
+ const followModel = resolvedModel
549
+ ? resolvedModel
550
+ : spawnerSession.model
551
+ ? `${spawnerSession.model.provider}/${spawnerSession.model.id}`
552
+ : null;
553
+ if (followModel) {
554
+ const slash = followModel.indexOf("/");
555
+ const m = slash > 0 && slash < followModel.length - 1
556
+ ? this.sharedModelRuntime?.getModel(followModel.slice(0, slash), followModel.slice(slash + 1))
557
+ : undefined;
558
+ if (m) {
559
+ try {
560
+ // 先恢复该 provider 的项目密钥(setModel 的鉴权检查要用),再换模型。
561
+ // 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
562
+ await this.restoreKeyForModel(followModel, resolvedCwd);
563
+ await conv.session.setModel(m);
564
+ }
565
+ catch (err) {
566
+ // 换模型失败不阻断运行——沿用默认模型继续。
567
+ this.emit({
568
+ type: "notice",
569
+ level: "warning",
570
+ text: `子代理模型切换失败(将按默认模型运行):${followModel}(${err.message})`,
571
+ textEn: `Failed to set subagent model, running with default: ${followModel} (${err.message})`,
572
+ });
573
+ }
574
+ }
575
+ else {
576
+ this.emit({
577
+ type: "notice",
578
+ level: "warning",
579
+ text: `子代理模型不存在,将按默认模型运行:${followModel}`,
580
+ textEn: `Subagent model not found, running with default: ${followModel}`,
581
+ });
582
+ }
583
+ }
584
+ // 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
585
+ // 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
586
+ // SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
587
+ // 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
588
+ // 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
589
+ const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
590
+ if (thinkingLevel) {
539
591
  try {
540
- // 先恢复该 provider 的项目密钥(setModel 的鉴权检查要用),再换模型。
541
- // 按子代理自己的目录恢复(跨目录派发时派发者的密钥不一定适用)。
542
- await this.restoreKeyForModel(followModel, resolvedCwd);
543
- await conv.session.setModel(m);
592
+ conv.session.setThinkingLevel(thinkingLevel);
544
593
  }
545
594
  catch (err) {
546
- // 换模型失败不阻断运行——沿用默认模型继续。
595
+ // 强度不合法/会话未就绪都不阻断运行(沿用当前档位)。
547
596
  this.emit({
548
597
  type: "notice",
549
598
  level: "warning",
550
- text: `子代理模型切换失败(将按默认模型运行):${followModel}(${err.message})`,
551
- textEn: `Failed to set subagent model, running with default: ${followModel} (${err.message})`,
599
+ text: `子代理思考强度设置失败(将按当前档位运行):${thinkingLevel}(${err.message})`,
600
+ textEn: `Failed to set subagent thinking level, keeping the current one: ${thinkingLevel} (${err.message})`,
552
601
  });
553
602
  }
554
603
  }
555
- else {
604
+ // 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
605
+ // 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
606
+ conv.kickoff = conv.session
607
+ .sendUserMessage(prompt)
608
+ .catch((err) => {
556
609
  this.emit({
557
610
  type: "notice",
558
- level: "warning",
559
- text: `子代理模型不存在,将按默认模型运行:${followModel}`,
560
- textEn: `Subagent model not found, running with default: ${followModel}`,
611
+ level: "error",
612
+ text: `子代理 ${conversationId} 启动失败: ${err instanceof Error ? err.message : String(err)}`,
613
+ textEn: `Subagent ${conversationId} failed to start: ${err instanceof Error ? err.message : String(err)}`,
561
614
  });
615
+ })
616
+ .finally(() => {
617
+ conv.promptInFlight = false;
618
+ });
619
+ if (persist) {
620
+ this.pushProjects().catch(() => { });
562
621
  }
622
+ this.emitConversations();
623
+ return conv.id;
563
624
  }
564
- // 思考强度:模板指定则固定用它,否则跟随派发者当前强度(与「跟随派发者模型」
565
- // 同一取数源:spawnerSession)。所以子代理默认与派发者一致,而不是默默回到
566
- // SDK 默认档位。放在换模型之后:setModel 会按模型能力重算强度,我们先让它
567
- // 算完再覆盖。不传 persist:只影响这个子代理会话,不动全局默认强度;模型不
568
- // 支持的档位由 SDK 自动收敛(reasoning:false 的模型只能是 off)。
569
- const thinkingLevel = apply?.thinkingLevel?.trim() || spawnerSession.thinkingLevel;
570
- if (thinkingLevel) {
571
- try {
572
- conv.session.setThinkingLevel(thinkingLevel);
573
- }
574
- catch (err) {
575
- // 强度不合法/会话未就绪都不阻断运行(沿用当前档位)。
576
- this.emit({
577
- type: "notice",
578
- level: "warning",
579
- text: `子代理思考强度设置失败(将按当前档位运行):${thinkingLevel}(${err.message})`,
580
- textEn: `Failed to set subagent thinking level, keeping the current one: ${thinkingLevel} (${err.message})`,
581
- });
625
+ finally {
626
+ if (isEphemeralSubagent && !handedOffToConv) {
627
+ this.spawningSubagents = Math.max(0, this.spawningSubagents - 1);
582
628
  }
583
629
  }
584
- // 触发回合(后台执行;失败转识为通知)。把 Promise 挂在对话上:目标模式的
585
- // 「等本回合结束」要先等它落定,才能区分「还没开跑」与「已跑完」。
586
- conv.kickoff = conv.session.sendUserMessage(prompt).catch((err) => {
587
- this.emit({
588
- type: "notice",
589
- level: "error",
590
- text: `子代理 ${conversationId} 启动失败: ${err instanceof Error ? err.message : String(err)}`,
591
- textEn: `Subagent ${conversationId} failed to start: ${err instanceof Error ? err.message : String(err)}`,
592
- });
593
- });
594
- if (persist) {
595
- this.pushProjects().catch(() => { });
596
- }
597
- this.emitConversations();
598
- return conv.id;
599
630
  }
600
631
  getSubagentSnapshot(convId) {
601
632
  const conv = this.convs.get(convId);
@@ -1292,8 +1323,11 @@ export class ClientSession {
1292
1323
  },
1293
1324
  stopSubagent: async (convId) => {
1294
1325
  const conv = this.convs.get(convId);
1295
- if (conv && (conv.session.isStreaming || !conv.session.isIdle)) {
1296
- await this.interruptRun(conv, pick(this.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1326
+ if (conv) {
1327
+ conv.promptInFlight = false;
1328
+ if (conv.session.isStreaming || !conv.session.isIdle) {
1329
+ await this.interruptRun(conv, pick(this.getLang(), "用户停止子代理", "User stopped the subagent", "agent.subagent.stop.user"));
1330
+ }
1297
1331
  }
1298
1332
  },
1299
1333
  getWatchdogTimeoutMs: () => this.getBaseToolWatchdogTimeoutMs(),
@@ -1722,7 +1756,7 @@ export class ClientSession {
1722
1756
  if (!conv)
1723
1757
  return;
1724
1758
  try {
1725
- if (conv.session.isStreaming || !conv.session.isIdle) {
1759
+ if (this.conversationStreaming(conv) || !conv.session.isIdle) {
1726
1760
  await this.interruptRun(conv, pick(this.getLang(), "目标模式停止角色对话", "Goal mode stopped a role conversation", "agent.role.stop"));
1727
1761
  }
1728
1762
  }
@@ -1730,6 +1764,19 @@ export class ClientSession {
1730
1764
  // best-effort
1731
1765
  }
1732
1766
  },
1767
+ interruptMainConv: async (convId) => {
1768
+ const conv = this.convs.get(convId);
1769
+ if (!conv)
1770
+ return;
1771
+ try {
1772
+ if (this.conversationStreaming(conv) || !conv.session.isIdle) {
1773
+ await this.interruptRun(conv, pick(this.getLang(), "目标已设定,主对话当前运行已让位给目标执行者", "Goal set — stopped the main conversation's run so the goal executor can take over", "agent.goal.preempt_main"));
1774
+ }
1775
+ }
1776
+ catch {
1777
+ // best-effort
1778
+ }
1779
+ },
1733
1780
  dismissRoleAgent: async (convId) => {
1734
1781
  const conv = this.convs.get(convId);
1735
1782
  if (!conv)
@@ -3418,6 +3465,7 @@ export class ClientSession {
3418
3465
  // 本轮结束且无后续重试:任何残留占位都是过期的(会话替换、
3419
3466
  // 结束信号丢失等),清掉,否则横幅会卡住不消失。
3420
3467
  conv.retryState = null;
3468
+ conv.promptInFlight = false;
3421
3469
  }
3422
3470
  // 轨迹事件:本轮结束(放最前——aborted 中断路径也会 break,
3423
3471
  // 轨迹里必须留下「已停止」而不是凭空消失)。
@@ -3577,6 +3625,8 @@ export class ClientSession {
3577
3625
  break;
3578
3626
  }
3579
3627
  case "agent_start": {
3628
+ // 本轮已正式进入流式(session.isStreaming=true),清除首轮启动期投递标记(#589)。
3629
+ conv.promptInFlight = false;
3580
3630
  // 轨迹事件:新一轮开始(任务文本由 prompt() 暂存;steer/内部续跑
3581
3631
  // 无暂存时省略,插件回退为「继续执行」)。
3582
3632
  const task = conv.pendingTask;
@@ -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",
@@ -13,7 +13,7 @@ export function makeMarkersListTool(getActiveId, markerSvc) {
13
13
  label: "List marker state",
14
14
  description: "Read-only query of inline marker state. All WRITE operations must use inline markers ([[todo:new:...]] etc.) in the reply body — never this tool.",
15
15
  parameters: Type.Object({
16
- action: Type.Unsafe({ enum: ["list"] }),
16
+ action: Type.Unsafe({ type: "string", enum: ["list"] }),
17
17
  tool: Type.Optional(Type.Literal("todo")),
18
18
  includeDeleted: Type.Optional(Type.Boolean({
19
19
  description: "Include deleted tasks (tombstones, todo only).",