Repository navigation
fix: hide AgentSwarm calls rejected before any subagent starts - #4414
Merged
Merged
Conversation
While swarm mode is off the core rejects AgentSwarm before any subagent starts, but the TUI still drew the call as a swarm whose members all failed, and resumed sessions replayed it as a failed swarm card. - Do not create the swarm panel while swarm mode is off, and remove the panel when a call ends before any subagent started (swarm mode off, input validation, a rejected approval, or a blocking hook). - Create the panel when the first subagent spawns, so a swarm that does run is never hidden when the TUI's swarm state lags behind. - Skip such calls when replaying a session. - Tell the model to point the user to /swarm only when they asked for a swarm, and otherwise to continue without mentioning swarm mode.
🦋 Changeset detectedLatest commit: ff58033 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
Grapedge
approved these changes
Oct 26, 2026
Merged
4 of 5 tasks
liruifengv
added a commit
that referenced
this pull request
Oct 27, 2026
* feat(agent-core-v2): add cross-process session occupancy lock (#4246) * feat(agent-core-v2): add cross-process session occupancy lock Multiple clients (TUI / kap-server / VS Code / ACP) running core in separate processes could open the same session and corrupt each other's wire.jsonl and metadata. Each session now holds a cross-process occupancy lock ({homeDir}/locks/sessions/{id}.lock) taken only while writing: runs acquire it on submit / compact / undo / cron / delete / fork / cold-archive, the append log holds it before flushing, and a stale check compares the main agent wire's on-disk length with the length this process knows. Collisions surface as session.occupied (holder in details); writes by another client detected after acquire surface as session.stale and the caller reloads before continuing. kap-server maps them to SESSION_OCCUPIED (40903) / SESSION_STALE (40930), reloads the session on stale, and re-attaches WS subscriptions; the TUI shows an occupancy dialog (retry/cancel) or reloads and replays history keeping the input; print exits with code 4 on occupied and reloads automatically on stale; VS Code / ACP get minimal occupancy notices. Locks are released a few seconds after the session goes idle, on close, and on process exit; locking I/O failures degrade to unlocked operation with a warning. * docs: document session occupancy error codes and lock directory * fix: address codex review on session occupancy lock - metadata: re-read state.json on the first write of each lock-hold epoch (holdToken), so pure-metadata changes made by another client (title, archive) are not clobbered by turn-end lastPrompt writes - lifecycle: hold an explicit lease across live archive(), matching delete(), so the idle release timer cannot drop the lock mid-teardown - tui: route the occupied dialog's Cancel selection through the same cleanup as Esc (restore input, release recalled media) - acp: tell stale-session users to close and reopen the session - append-log: warn when retirement drops records kept in memory because the session lock was unavailable * fix: always run the staleness check in beginSessionRun The prompt channels (AgentPromptChannel.submit/submitSteer, kap /prompts, promptWithSkills) write prompt metadata before calling loop.submit, and the metadata write acquires the session lock first. beginSessionRun then short-circuited on 'already held' and skipped the wire-length staleness check, so the main prompt path never detected updates written by another client. Drop the already-held shortcut: the check is a single stat and always passes while the lock is continuously held, so every acquisition path now runs it regardless of order. * fix(print): preserve occupied handling on the stale retry If another client acquires the session between the reload and the retry, the retried turn now goes through the same conflict handler: session.occupied reports to stderr / stream-json and exits with code 4 instead of bubbling out as exit code 1. * fix: do not mistake own in-flight writes for external modification storage.append grows the file (writeFile) before fsync/close complete, and knownLength only catches up afterwards; a beginSessionRun landing in that window (steer, queued prompts, cron fires during a turn) was misjudged as session.stale and deleted the lock file mid-turn. Track in-flight bytes per log and compare disk against known + in-flight. Cover the analogous rewrite window (post-rename syncDir) with an expected-final-length marker. * fix: bound the staleness comparison and check once per lock hold The equality check disk !== known + inFlight moved the false-positive window to before the append lands (mkdir/open) and into chunked writes, so beginSessionRun during a turn (steer, cron, queued prompts) could misjudge, delete the lock file mid-turn, and later append behind another client. Compare known <= disk <= known + inFlight instead, and evaluate the check only on a fresh hold (holdToken epoch): re-entrant runs pass through without a stat, matching the RFC's 'already held passes through' while every acquisition path still triggers the check exactly once per hold. Also unify the occupancy prompt copy across clients: the engine error message is now the single user-facing text ('该会话正在被其他 Kimi Code 进程使用;请停止其他进程中的会话或退出该进程后重试'), and the TUI dialog, /compact /undo errors, print output, and the VS Code fallback all display it instead of maintaining their own wordings. * fix: address third-round codex review - metadata: hold an explicit lease across each state.json write so the idle release timer cannot unlink the lock mid-write - print: preflight the session lock before goal creation; make goal creation idempotent and emit the goal summary only for attempts that did not fail with session.stale, so a stale reload + retry neither duplicates the goal nor the summary - tui: route every prompt-launch path (plain, goal steer, plugin command, inline skill, batch steer) through one conflict handler with the occupied dialog and stale reload + input restore - tui: snapshot and restore the attachment store across stale reloads so pasted media placeholders still resolve after history replay * fix: move session occupancy to a fresh error code, use English copy, release locks on exit SESSION_OCCUPIED reused 40903, which belonged to PROMPT_ALREADY_COMPLETED until #3747 retired it, and web clients still allowlist 40903 for that old meaning; reusing it conflated the two semantics. Move session occupancy to the never-used 40931 and update the server API reference in both locales. The occupied error message was hardcoded in Chinese while every other engine error is English, so the TUI, print mode, VS Code, and ACP clients all rendered mixed-language output; replace it with an English equivalent. The lock release hook ran on 'beforeExit', which never fires when the process leaves through process.exit (SIGHUP in the TUI goes through emergencyTerminalExit), leaving stale lock files that could keep a session looking occupied forever after a hostname change or pid reuse. releaseAll is fully synchronous, so hook 'exit' instead. * fix(agent-core-v2): decide prompt-derived titles after re-reading session metadata applyPromptMetadataUpdate decided whether to derive a title from the prompt from the in-memory metadata cache, which is only refreshed when the session lock is re-acquired. If another client named the session in the meantime, the stale cache still looked untitled, so the next prompt from this client overwrote the other client's title — both on the stale path, where the prompt is rejected afterwards, and on the fresh path, where the other client only changed the title on disk. Move the untitled check into SessionMetadata.applyPromptMetadata, which runs after ensureWriteOwnership() has re-read state.json, so the decision is based on the latest persisted metadata. The published SessionMetaUpdated event now carries the derived title only when it was actually written. * fix: address fourth-round codex review - vscode: classify session.occupied and session.stale as preflight errors so the webview toasts them instead of silently swallowing the send, and give session.occupied the same English copy the engine emits (the toast text comes from getUserMessage in the extension host). - engine: beginSessionRun now takes the session context and agent lifecycle service, and on the first check of each lock hold it runs externallyModified over every loaded agent's wire (scope agents/<agentId>, key wire.jsonl) instead of only the main agent's, so a fork that only touched a subagent journal is detected as stale. All four call sites (loop submit, manual compaction begin, undo, print preflight) pass the extra dependency. - tui: keep the request in flight across a stale reload instead of dropping to idle, so input submitted during the reload queues rather than racing the closing session; park the queue around switchToSession (resetSessionRuntime would clear it) and drain it into the reloaded session afterwards; when restoring the rejected text, prepend it before content the user typed during the reload instead of overwriting it. - kap-server: clear the in-flight turn tracker and subagent roster in detachSession so a reattached session no longer reports stale in-flight turns or running subagents in REST snapshots and WS resyncs. * fix: harden session conflict recovery Detect external appends that race journal reads so a later run cannot miss session.stale. Keep deferred wire migrations pending and finish them before appending, while rejecting the append if migration still cannot complete. Restore the complete plugin command after an occupied cancellation, including commands without arguments. * fix: scope session staleness cache to session context Replace the process-global session-id map with a WeakMap keyed by ISessionContext so closed and reloaded sessions do not retain cache entries for the lifetime of the process. * fix: document session conflicts for metadata routes Declare SESSION_OCCUPIED and SESSION_STALE in the response schemas for profile updates, title generation, and child creation. Cover the OpenAPI declarations and the existing HTTP 200 conflict envelopes with regression tests. * refactor: centralize session conflict handling Move session error mapping and stale reloads into one shared route helper, reuse shared conflict response declarations, and cover skill activation conflicts. Remove the duplicate prompt, session, and skill error mappers while preserving their existing envelopes. * fix(sdk): restate session conflict errors * fix(tui): keep the reloaded session open and resend after a stale conflict * fix(agent-core-v2): lazily rebuild registered agents after a session reload * refactor: simplify session conflict handling * refactor: hygiene fixes from session-lock review - kap-server: move SESSION_STALE to 40932 (collided with DEFAULT_WORKSPACE_UNAVAILABLE at 40930) and pin ErrorCode value uniqueness with a test - node-sdk: fold six catch-and-restate copies into a restate() helper - acp-server: sync mapPromptLaunchError docstring with the occupied/stale branches - replace hardcoded session.stale/session.occupied literals with ErrorCodes constants - inline the single-use sessionStaleError - restore the strict timer-leak assertion with a warmup baseline instead of a blanket +1 allowance - narrow SessionState.detached to ?: true * refactor: introduce session-level run gate - replace the beginSessionRun free function with ISessionRunGate, a Session-scoped service; loop/compaction/undo now inject one dependency instead of four, and sessionLock.ts no longer imports session-layer modules - tryHold() absorbs the duplicated try/catch hold copies in wireService and sessionMetadataService - resolve IAgentLifecycleService lazily inside the gate to avoid a construction-time cycle with agentLifecycleService * refactor: tighten session lock and conflict recovery structure - Narrow ISessionLockService to hold/tryHold/release/lease/held and share the hold bookkeeping between the memory and node-fs backends; drop holdToken and the module-level exit hook state. - Session metadata refreshes on a new hold via onDidHold and skips agent registration through tryHold instead of catching session.occupied. - AppendLogStore reads sizes through IFileSystemStorageService.sizeSync and exposes a generic write guard instead of a session-lock binding. - kap: reload stale sessions only at the call sites that can raise session.stale and log reload failures; error mapping stays side-effect free. - TUI: recover from a stale conflict through the in-place session reload with history replay, removing the same-session switch special case, the media store snapshot, and the queue parking. - print: bound stale reloads with a simple retry loop. * refactor(agent-core-v2): merge session lock release into run gate * test(agent-core-v2): reuse append log fixtures * refactor(agent-core-v2): break run gate and agent lifecycle dependency cycle * refactor: reload stale sessions in core instead of each host Stale detection already lived in core, but every host re-implemented the recovery: TUI, print, and kap each closed and resumed the session, and TUI and web resent the rejected input themselves. Core now exposes reloadOnStale: on session.stale it closes and resumes the session, lets the caller refresh, then retries the call once (undo reloads and still rejects, since its count depends on what the user saw). - kap: prompt submit, skill activation, and compact retry in place instead of returning 40932; undo still returns 40932 after reloading - print: retries through reloadOnStale on the same session id and keeps the original permission mode to restore - SDK: run-starting calls reload and retry internally; Session gains setStaleReloadHandler so hosts refresh before the retry - TUI: drops its own reload/resend/queue-merge path; the stale handler replays history and keeps in-flight messages * docs(server-api): note that only undo returns 40932 after a stale reload * refactor(agent-core-v2): ask each agent's wire whether it was modified externally * refactor(agent-core-v2): clarify agent restoration helper name * Delete .changeset/ensure-agent-lazy-rebuild.md Signed-off-by: 7Sageer <[email protected]> * fix(tui): wrap session occupied notice --------- Signed-off-by: 7Sageer <[email protected]> * revert: remove default workspace session creation (#4295) * chore: merge release/2026-10-20 into release/2026-10-21 (#4294) * feat(kap-server): add remote control device deletion (#4192) (#4195) * feat(kap-server): add remote control device deletion * fix(kap-server): coordinate with the local tunnel before deleting this machine's device Co-authored-by: liruifengv <[email protected]> * ci: enable recoverable publishing for the October release (#4218) * ci: publish core releases from isolated release branches * ci: simplify release recovery to the CLI package * ci: publish VS Code from approved release commits * test: await release test registration for type-aware lint * test: avoid assuming order of independent tower events * ci: limit release migration to existing publishing flow * chore: sync web dist from code-app (#4221) * chore: sync web dist from code-app code-app: f828bac439ab5b9266ff8387c2afb96ecfcb59ae * ci: retrigger (flaky rpc-events teardown ENOTEMPTY) --------- Co-authored-by: kimi-agent-bot <[email protected]> * ci: release packages (#4220) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * feat(tui): queue /compact behind the running turn (#4276) * feat(tui): queue /compact behind the running turn * docs: note /compact queueing while the agent is busy * fix(tui): harden queued /compact edge cases - keep /compact blocked while a compaction holds the turn (busy reason normalized to compacting) - treat the first queued /compact as a FIFO barrier for Ctrl-S manual steer - gate the failed-fire retry timer on the session actually going idle * fix(tui): cover remaining /compact queue review edges - advertise Ctrl-S in the queue pane only for items ahead of the compact barrier - queue /compact when the awaited lazy session creation lands on a running turn - document the auto-compaction skip for queued /compact in docs and the changeset * fix(tui): guard queued /compact against concurrent compactions - requeue without firing when another compaction already started (the SDK's begin() swallows this as a silent no-op; declared residual window needs the contract to expose the result) - restore the input when a duplicate /compact is refused after lazy session creation * fix(tui): render requeued /compact and mark it always available in docs - request a render after restoring a compact item to the queue so it does not appear vanished during backoff - the reference table's availability column now matches the queueing behavior (/compact is accepted during streaming and runs in order) * fix(tui): steer messages ahead of a queued /compact automatically The automatic (tower/WaitFor) steer batch now slices at the first queued /compact just like the manual path, so pre-barrier prompts still end a WaitFor promptly instead of being blocked by an unrelated compact item. Batches containing bash or skill items ahead of the barrier keep their existing all-or-nothing semantics. * test(tui): drive the tower steer barrier case through the WaitFor event path * chore: downgrade the /compact queue changeset to patch (#4279) * feat: add cloud-gated model switch confirmation (#4286) * feat(cli): add cloud-gated model switch confirmation dialog * feat(server): expose named client_configs endpoint for cloud-controlled clients * fix(server): keep broadcasting compaction events to transcript subscribers * Revert "fix(server): keep broadcasting compaction events to transcript subscribers" This reverts commit e489915. * fix(cli): address review findings on the model switch confirmation * test(cli): fix the auth-flow gate test typing * fix: close the login-path holes in the model switch gate - install the refreshed model catalog before matching the cloud rule, so an alias introduced by /login no longer bypasses the confirmation - return 'gated' from refreshConfigAfterLogin and forward the picked effort to the dialog; setDefaultModel skips its follow-up activation while the gate owns the switch - ignore Escape once a dialog action was chosen so the input lock survives the new-session creation * fix: keep displaced panels alive when the new-session switch settles The async finalizer of a settled dialog action now only restores the editor while the model-switch dialog still owns the editor replacement, so an approval or question panel mounted over it is never wiped out with its reverse-RPC request still pending. * feat: support id lists and always-fresh model switch confirmation configs (#4292) * feat: accept id lists in model switch confirmation rules * feat: fetch client configs fresh on every request The /client_configs endpoint now proxies the cloud per request instead of serving a copy cached at server startup, so config changes take effect without a server restart. The startup warm-up and the in-memory store are removed; region is resolved per request. --------- Co-authored-by: qer <[email protected]> Co-authored-by: Kimi Agent <[email protected]> Co-authored-by: kimi-agent-bot <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * chore: sync web dist from code-app (#4304) code-app: 913137036c35c608f3a487eb2c7b4a8815b53b95 Co-authored-by: kimi-agent-bot <[email protected]> * ci: release packages (#4288) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix: decouple workspace trust from runtime initialization (#4348) * fix(kap-server): decouple workspace trust from runtime initialization * fix: preserve workspace trust errors * fix: emit workspace trust recovery changes * fix: complete workspace trust recovery * fix(agent-core-v2): reclaim session locks from zombie processes (#4320) (cherry picked from commit 0a90e2e) * feat: let users take over a session lock left by an exited process (#4328) * feat: let users take over a session lock left by an exited process Session locks judged alive by mistake (a different hostname, pid reuse, or a failed process-state probe) blocked the session with no way out. Add a takeover path: the lock service evicts another process's lock, the SDK exposes Session.takeOverLock(), kap-server adds POST /api/v1/sessions/{id}:takeover, and the TUI offers Take over once a retry is still occupied. KIMI_CODE_SESSION_LOCK=0 turns the lock off for a process. * fix(agent-core-v2): evict the lock directly on takeover Takeover went through the reclaim marker, so a stale marker left by a crashed reclaimer on another host made takeover a silent no-op while the API reported success. Unlink the lock file directly instead. * fix(agent-core-v2): surface takeover failures when the lock cannot be removed Takeover swallowed unlink errors, so a lock file another user owns in a shared sticky directory was reported as taken over while the next retry stayed occupied. Ignore only ENOENT and let other errors reach the caller. Also fix the run gate test bootstrap stub typing. * fix(tui): simplify the session takeover copy * fix(tui): tie the takeover warning to the takeover action * fix(tui): drop the holder line from the takeover dialog * refactor(tui): move the session occupancy dialogs into a controller (cherry picked from commit e7f1a99) * chore: sync web dist from code-app code-app: 76483646b7c46a61bff868f1473535e0a32b473d --------- Co-authored-by: 7Sageer <[email protected]> * feat: show session lock holder client names (#4356) * chore: sync web dist from code-app (#4357) code-app: 7be8bf55306625ade7b5dbead86bc789d22d0159 Co-authored-by: kimi-agent-bot <[email protected]> * ci: release packages (#4353) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * test: isolate cloud config in message flow tests (#4363) (#4383) (cherry picked from commit 087db85) Co-authored-by: grapedge <[email protected]> * fix(agent-core-v2): leave swarm mode to the user (#4384) * fix(agent-core-v2): leave swarm mode to the user AgentSwarm now runs only while swarm mode is on, and only the user can turn swarm mode on, so the model can no longer start a swarm by itself. - Reject AgentSwarm at resolve time while swarm mode is off and check again right before it runs; no subagents start and swarm mode stays off. - Stop AgentSwarm from entering swarm mode, reject the tool trigger, and ignore tool-triggered entries that older versions recorded on replay. - Skip the one-AgentSwarm-per-response veto while swarm mode is off so the other tools in that response still run. - Say in the AgentSwarm description and the swarm exit reminder that only the user can turn swarm mode on. - Update the tools and slash-command reference docs. * fix(transcript): ignore model-started swarm entries when folding history Swarm mode entries with the tool trigger come only from older versions, where the model started a swarm by itself. The engine already ignores them on replay, so a session that stopped mid-swarm resumes with swarm mode off. Folding history still marked swarm mode on from that entry, and no later status update turned it off, so the web UI kept showing swarm mode as on. Keep the swarm.enter marker in history, but leave meta.modes untouched for tool-triggered entries. * fix(agent-core-v2): launch subagents only on explicit request (#4386) The main agent launched subagents on its own: the explore type told it to delegate any exploration needing more than three searches and to run several explore agents at once, the Agent description sold delegation, and the EnterPlanMode description sent plan mode to an explore subagent first. - Agent description: launch a subagent only when the user asks for one, or AGENTS.md, a skill, or a multi-agent mode the user turned on calls for it; agent type descriptions only pick a type once launching is authorized. - System prompt: state the same rule for Agent. - Drop the delegation nudges from the Agent and explore descriptions and from the EnterPlanMode description. - Swarm exit reminder: once swarm mode ends, handle the next request without subagents unless it asks for them. * chore: clarify subagent changeset * ci: release packages (#4385) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * fix: hide AgentSwarm calls rejected before any subagent starts (#4414) While swarm mode is off the core rejects AgentSwarm before any subagent starts, but the TUI still drew the call as a swarm whose members all failed, and resumed sessions replayed it as a failed swarm card. - Do not create the swarm panel while swarm mode is off, and remove the panel when a call ends before any subagent started (swarm mode off, input validation, a rejected approval, or a blocking hook). - Create the panel when the first subagent spawns, so a swarm that does run is never hidden when the TUI's swarm state lags behind. - Skip such calls when replaying a session. - Tell the model to point the user to /swarm only when they asked for a swarm, and otherwise to continue without mentioning swarm mode. * feat: warn about high usage when swarm mode turns on (#4423) Swarm runs many agents in parallel and can use many times the tokens of a normal task. Show a warning line under "Swarm activated" whenever /swarm, /swarm on, or /swarm <task> turns swarm mode on, suggesting a small task first and turning swarm off when done. * feat: add session-aware model switch confirmations (#4424) * feat: add session-aware model switch confirmations * chore: remove changesets * fix: harden model switch confirmation loading * fix(cli): merge duplicated permission-mode notice lines in swarm and goal start prompts (#4432) * feat: add cloud-controlled effort switching prompts (#4436) * feat: add cloud-controlled effort switching prompts * fix: rename effort switch client config * fix: refine model and effort switch prompts * docs: update model switch release note to English (#4440) * chore: sync web dist from code-app (#4443) code-app: e3e6af32171e939399cea2edc728757dcae0ba18 Co-authored-by: kimi-agent-bot <[email protected]> * ci: release packages (#4417) Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> * test(tui): use the release gate fixtures in auth-flow.test.ts The merged gate path needs the release fixtures (session_type rules + model capabilities); keep main's unique auth/refreshProviderModels tests alongside release's. * fix: drop unused isSessionOccupiedError import left by the sync resolution * test(tui): align goal start prompt expectations with the merged notice copy #4432 merged the duplicated permission-mode notice lines; update the goal and fullscreen dock expectations to the merged copy (the body now fits at maxBodyRows=6, so no scroll suffix). --------- Signed-off-by: 7Sageer <[email protected]> Co-authored-by: 7Sageer <[email protected]> Co-authored-by: qer <[email protected]> Co-authored-by: liruifengv <[email protected]> Co-authored-by: kimi-agent-bot <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: Kai <[email protected]> Co-authored-by: grapedge <[email protected]>
11 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Requirement or Bug
2.3.3 hotfix:swarm 模式关闭时模型调用
AgentSwarm会被拒绝,TUI 却把这次拒绝画成"所有子 agent 都失败"的 swarm 面板。改为不显示这次调用,由模型在回复里向用户解释。Bug Reproduction Steps
kimi,不开 swarm 模式。use agentswarm to analyse kimi code tools and make a summary。AgentSwarm,调用被拒绝。TUI 显示Agent Swarm面板:7 个格子都是✗ Swarm mode is…,底部是红色Failed.。实际上一个子 agent 都没启动。Root Cause
AgentSwarm在 swarm 模式关闭时直接返回错误,但工具仍在工具列表里。模型看不到开关状态(swarm 提醒只在开启、关闭时注入),用户点名要 swarm 时,模型照样会调用。items建好了面板。拒绝结果是一个不含逐个子 agent 结果的整体错误,markSwarmFailed把所有格子都标成失败。恢复会话时走通用工具卡片,显示Agent swarm: ✗ Failed.。这是根本修复:被拒绝的调用是给模型的纠错信号,不是一次 swarm 运行,TUI 不再把它当成 swarm 展示;需要向用户解释时,由模型的回复负责。
Code Changes
TUI 实时路径(
subagent-event-handler.ts):最后一项是兜底:如果 TUI 记录的 swarm 状态没跟上,而 core 实际启动了子 agent,面板会在第一个子 agent 启动时出现,不会把真在跑的 swarm 藏掉。
TUI 会话回放(
session-replay.ts、streaming-ui.ts):renderToolResult + AgentSwarm + 报错 + 属于拒绝 → discardToolCall:移除已挂上的卡片 onToolCallEnd"属于拒绝"由
agent-swarm-progress.ts的isAgentSwarmRejection判定:输出里没有逐个子 agent 的结果,也不含 aborted / cancelled / interrupted。判定不依赖拒绝文案本身,core 以后改文案也不会失效。core 只有在启动任何子 agent 之前就结束调用时,才会返回这种输出:swarm 模式关闭、参数校验失败、审批被拒、hook 拦截。core 的拒绝文案(
agentSwarmTool.ts):第一句不变;第二句末尾的until they do前加了again;新增两句:Behavior Changes and Affected Users
AgentSwarm✗,底部Failed.Agent swarm: ✗ Failed.Aborted by the user等),以及子 agent 启动后的失败/swarm开启,或用/swarm <task>;否则不用 AgentSwarm 继续,不提 swarm 模式AgentSwarm的会话kimi -p/swarm提示文本改动:
agentSwarmTool.ts的拒绝结果do not call AgentSwarm until they do改为do not call AgentSwarm again until they doAgentSwarm的 agent:每个 session 的主 agent,以及配了AgentSwarm的自定义 subagentIf the user asked for a swarm, tell them swarm mode is off and that they can turn it on with /swarm, or run /swarm <task> to start the task as a swarm.Otherwise, continue without AgentSwarm and do not mention swarm mode.本 PR 没有改动契约文件:manifest、
apiSurface快照、packages/node-sdk/src/index.ts、externalHooks、acp-server、apps/kimi-code/src/cli/。受影响模块与测试:
subagent-event-handler.ts:kimi-tui-message-flow.test.ts新增 3 条:swarm 关闭时不渲染被拒绝的调用(参数流式输出时和结果返回后都没有面板);swarm 开启但校验失败时移除面板;swarm 显示为关闭、子 agent 却启动时补建面板。kimi-tui-message-flow.test.ts中 7 条,activity-pane.test.ts、subagent-event-handler.test.ts)补上了 swarm 模式开启这个前提。真实场景下 swarm 能运行,swarm 模式一定是开着的;这些测试继续钉住正常 swarm 的渲染。session-replay.ts、streaming-ui.ts:message-replay.test.ts新增 2 条:回放时不显示被拒绝的调用;取消的调用仍显示Agent swarm: ⊘ Aborted.。原有结构化结果的回放测试不变。agent-swarm-progress.ts:agent-swarm-progress.test.ts新增isAgentSwarmRejection用例,覆盖拒绝、校验失败、结构化结果、取消。agentSwarmTool.ts:swarm.test.ts钉住新增的两句。验证:
apps/kimi-code全量测试通过(4073 passed,2 skipped),类型检查通过。agent-core-v2的swarm.test.ts、tool.test.ts:188 passed。另有 1 个 Agent 前台超时用例失败,在不含本改动的代码上同样失败(fix(agent-core-v2): leave swarm mode to the user #4384 已记录,CI 上通过)。Checklist
/approve).(内部 hotfix,没有 issue)gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.(文档只写了"swarm 关闭时调用会被拒绝",没有写拒绝时的界面,无需更新)