Skip to content

feat(agent-core-v2): add cross-process session occupancy lock - #4246

Merged
7Sageer merged 36 commits into
mainfrom
session-lock
Oct 20, 2026
Merged

7Sageer merged 36 commits into
mainfrom
session-lock

Conversation

@7Sageer

@7Sageer 7Sageer commented Oct 15, 2026 •

Copy link
Copy Markdown
Collaborator

Requirement or Bug

避免多个客户端同时写入同一会话,导致 wire 分叉和元数据互相覆盖。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

  • 同一会话同一时刻仅允许一个进程写入;打开和查看不受影响。
  • 占用冲突在各客户端呈现为可重试错误;发现他端更新后自动重载,发送和 compact 自动重试一次,undo 仅重载。
  • 元数据写入前重读以保留他端修改;重载后可按原 ID 恢复已有 fork agent 的上下文和 /btw 状态,并恢复 kap WS 订阅。
  • 失效锁自动回收;锁 I/O 失败时告警并降级为无锁。

Behavior Changes and Affected Users

行为 之前 之后 受影响人群 退路
多客户端同时写同一会话 wire 分叉、元数据互相覆盖 后写入方收到 session.occupied;只读操作不受影响 TUI、desktop / web、VS Code、ACP、print 对方结束后重试;锁 I/O 失败时降级为旧行为
他端更新后再发送、compact 或 undo 在旧上下文上继续写入 自动重载;发送和 compact 自动重试一次,undo 需再次执行;已有 side chat 可继续使用 各客户端与 SDK 无
他端运行中修改元数据、fork 或删除会话 可能覆盖修改或读取不完整数据 返回 session.occupied TUI、desktop / web、API 脚本 对方结束后重试
print 遇到占用 继续执行 stderr 提示并以退出码 4 结束;stream-json 输出结构化错误 print 脚本 既有退出码不变
kap 返回冲突错误 无专用错误码 SESSION_OCCUPIED(40931);SESSION_STALE(40932)仅由 undo 返回 desktop / web、外部 API 客户端 未识别新错误码时按普通错误处理
自动任务遇到冲突 照常提交或写入 cron 跳过本次;后台 wire 写入等待后续 flush;resume 的迁移或修复延后 cron 用户、后台任务、旧版本会话 重新载入或后续可写入时恢复
崩溃遗留锁或锁 I/O 异常 无锁 失效锁自动回收;异机锁仍视为占用;I/O 异常时降级为无锁 共享 home、权限受限环境 可手动删除异常锁文件
会话关闭后重开 WS 事件可能丢失 自动恢复订阅并推送 transcript reset kap WS 客户端 无

测试覆盖:

  • agent-core-v2:锁生命周期、外部修改检测、重载重试、元数据与 wire 写入、fork agent 和 /btw 恢复。
  • kap-server、node-sdk、klient:错误码、自动重试、WS 重订阅和 agent 恢复。
  • apps/kimi-code、apps/vscode:占用提示、输入与队列保留、print 输出及退出码。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

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.
Copilot AI balanced review requested due to automatic review settings October 15, 2026 11:57
@changeset-bot

changeset-bot Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: dd97dac

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Minor

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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@7Hanrui

7Hanrui commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-20T08:05:18.280433Z dd97dac New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7d5c9e7401

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +214 to +218
if (!state.lockWarned) {
state.lockWarned = true;
console.warn(
`[append-log] ${scope}/${key}: session lock unavailable; keeping writes in memory`,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject mutations when session lock acquisition fails

When another client owns the session, durable mutations that do not call beginSessionRun first—such as setPermission, setThinking, or setModel—still update the local fold and report success, while this path merely leaves their wire records pending. If the session closes while the owner remains active, retirement deletes that pending state; if a later flush succeeds, it appends the stale mutation without checking externallyModified. Thus settings can be silently lost or written over a newer history; ownership must be acquired before committing the mutation, and failure must propagate to the caller rather than buffering it.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
Comment on lines +2078 to +2079
onSelect: (action) => {
if (action !== 'retry') return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route the Cancel selection through cancellation cleanup

When a TUI user moves to the displayed Cancel option and presses Enter, onSelect('cancel') hits this return and performs none of the onCancel cleanup: the dialog remains mounted, the submitted text stays removed, and recalled attachments are not released. Esc works because it invokes onCancel directly, so the selected Cancel action should invoke that same path.

Useful? React with 👍 / 👎.

Comment on lines +113 to +116
private async ensureWriteOwnership(): Promise<void> {
if (this.sessionLocks.held(this.ctx.sessionId)) return;
this.sessionLocks.beginRun(this.ctx.sessionId);
const existing = await this.store.get<SessionMeta>(this.scope, META_KEY);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refresh metadata after acquiring a run lock elsewhere

When a prompt has already acquired the session run lock, this early return skips re-reading state.json, even though beginSessionRun only checked the main wire journal for external changes. If another client changed metadata while this client was idle—for example, setting a custom title or archiving the session—then this client's next prompt updates lastPrompt from its stale this.data snapshot and overwrites that newer metadata. Refresh or version-check metadata on the first metadata write of each newly acquired run, rather than treating possession of the wire lock as proof that the metadata snapshot is current.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment thread packages/acp-server/src/session.ts Outdated
Comment on lines +134 to +139
if (code === SESSION_OCCUPIED_CODE || code === SESSION_STALE_CODE) {
log.warn('acp: prompt rejected due to a cross-client session conflict', {
sessionId,
conflict: code,
});
return RequestError.invalidRequest({ code }, message);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reload ACP sessions after reporting a stale conflict

For an ACP client whose session was updated by another process, mapping session.stale to invalidRequest leaves the stale engine scope live, so every subsequent prompt fails with the same error. Even issuing ACP session/load or session/resume does not recover because resumeAcpSession explicitly passes an already-live scope through; the client must know to close the session first, despite the error only saying to reload. Handle the stale case by closing and re-materializing the engine session, as the CLI and kap-server paths do, before allowing the ACP client to retry.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

Comment on lines +213 to +217
private alive(holder: SessionLockHolder): boolean {
if (holder.hostname !== '' && holder.hostname !== this.hostname) return true;
if (!pidAlive(holder.pid)) return false;
const bootTime = Date.now() - os.uptime() * 1000;
return holder.startedAt >= bootTime;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Detect PID reuse before honoring a stale lock

After a crash or forced termination leaves a lock file behind, the OS can reuse its PID for an unrelated process during the same boot. In that case pidAlive succeeds and startedAt >= bootTime is necessarily true for any valid lock created this boot, so the abandoned lock is treated as live until the unrelated process exits and the session remains unusable. Persist and compare an actual process-start identity, or use another reclaimable liveness mechanism, rather than using the lock acquisition timestamp only as a reboot check.

Useful? React with 👍 / 👎.

Comment on lines +59 to +62
if (this.activity.state().busy) return;
await this.appendLogStore.flush().catch(() => undefined);
if (this.activity.state().busy) return;
this.sessionLocks.endRun(this.ctx.sessionId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Hold the lock through non-activity lifecycle operations

The release timer only consults ISessionActivityView.busy, which tracks turns, background tasks, and compaction but not session lifecycle work. A live archive acquires the run lock through setArchived(true) and then drains agents, waits for close listeners, and closes logs without an explicit lease; once activity becomes idle, this timer can release the lock after three seconds while that archive is still in progress. A second process can then start the same session while the first process is still tearing it down, so lifecycle operations such as archive need an explicit lease for their full duration or must participate in the busy state.

Useful? React with 👍 / 👎.

- 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
@7Hanrui

7Hanrui commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d0ebcf0a22

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

if (known === undefined) return false;
const disk = this.diskLength(scope, key);
if (disk === undefined) return false;
return disk !== known;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Detect journal replacement beyond its byte length

When an SDK caller deletes and recreates an empty session under the same explicit ID while another process still has the old scope open, both journals contain a single metadata record whose timestamp changes but whose encoded byte length remains identical. This comparison therefore reports no external modification, allowing the old process to acquire the lock and append using its obsolete in-memory fold instead of raising session.stale, silently mixing the old and replacement sessions. Track a journal identity, generation, or content fingerprint rather than only its size.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

releaseQuiescence = await quiesceSessionAgents(reloaded.session, reloaded.agent);
};
flushWires = () => flushSessionWires(reloaded.session, reloaded.agent);
await runTurn(reloaded.session, reloaded.agent);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve occupied handling on the stale retry

If the first print-mode attempt reports session.stale and another client acquires the session after the reload but before this retry, the second runTurn throws session.occupied outside the surrounding catch. It therefore bypasses reportSessionOccupied, so headless callers lose the documented exit code 4 and stream-json callers do not receive the structured session.occupied error. Route the retry through the same conflict handler, or use a bounded retry loop that handles both errors consistently.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

Comment on lines +595 to +598
state.detached = undefined;
this.attachWorkView(session, state);
this.attachAgents(sessionId, session, state);
this.attachInteractions(sessionId, state);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refresh the event journal when reattaching a session

When the external writer is another kap-server process sharing the same home directory, it advances server/events/<session>.jsonl while this process is detached. The retained SessionEventJournal still caches its old sequence number, but this reattachment reuses it without reopening or rescanning the file, so the next local event appends a duplicate or out-of-order sequence and makes snapshot cursors and WebSocket resume results inconsistent for desktop and web clients. Reopen the journal from disk during reattachment while preserving the subscription targets separately.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

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.
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.
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.
@7Hanrui

7Hanrui commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 60abd1ecdb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +60 to +62
await this.appendLogStore.flush().catch(() => undefined);
if (this.activity.state().busy) return;
this.sessionLocks.endRun(this.ctx.sessionId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Acquire a lease for metadata writes

When an idle metadata mutation such as setTitle takes longer than three seconds, or starts while this timer is awaiting a slow global flush, it only calls beginRun and does not increment an explicit lease; metadata writes also do not mark session activity as busy. This endRun can therefore unlink the lock while state.json is still being written, allowing another process to acquire the session and overwrite or race a mutation that already reported success. Although lifecycle operations now take explicit leases, the fresh evidence here is that SessionMetadata.applyUpdate still relies solely on the ambient run lock.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

};
flushWires = () => flushSessionWires(reloaded.session, reloaded.agent);
try {
await runTurn(reloaded.session, reloaded.agent);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid rerunning goal creation after a stale reload

For print-mode /goal requests against a stale resumed session, the first runTurn calls createGoal before runNativeTurn detects session.stale, and runNativeGoal also emits a goal summary from its finally block. Retrying the entire closure here invokes createGoal again after reload: a normal goal then fails with goal.already_exists once the first goal record is flushed during close, while /goal replace replaces the newly created goal and emits duplicate summaries to stream-json. Reload before the goal mutation or retry only the turn portion.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
@@ -2037,10 +2042,84 @@ export class KimiTUI {
return;
}
this.staging.trackDispatch(stagingLease, session.prompt(sdkInput, { promptId: submissionId }), (error) => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply conflict recovery to every TUI prompt path

The new occupied/stale recovery is attached only to the normal session.prompt dispatch. Existing inline-skill and plugin-command submissions also reach AgentLoopService.submit and now receive these conflict errors, but their unchanged handlers only show a generic failure after the editor input has been consumed; inline-skill failures additionally leave the optimistic transcript entry in place. Thus these TUI users get neither the retry/cancel dialog nor stale reload and input restoration promised for sending from a second client. Route all prompt-launch variants through the same recovery path.

AGENTS.md reference: AGENTS.md:L102-L104

Useful? React with 👍 / 👎.

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
...(options?.imageAttachmentIds ?? []),
...(options?.videoAttachmentIds ?? []),
]);
await reloadSessionAfterStale(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve staged attachments across stale reloads

When the rejected prompt contains a pasted image or video, releaseRecalled keeps its staged media usable only while the attachment store still owns the corresponding IDs. This reload calls switchToSession, whose transcript reset clears the attachment store and deletes those staged files, and only afterward does handleSessionStale restore the original placeholder text. The next submission treats the now-unknown placeholders as plain text, so clipboard media is silently and irrecoverably dropped instead of being returned with the user's message. Preserve or rehydrate the attachment snapshots across this reload.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

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.
- 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
@7Hanrui

7Hanrui commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 786853ce66

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".


SESSION_BUSY: 40901,
APPROVAL_ALREADY_RESOLVED: 40902,
SESSION_OCCUPIED: 40903,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Allocate a distinct code for session occupancy

When a kap-server client encounters session occupancy, this emits 40903, but the published API already assigns 40903 to an already-completed prompt (docs/en/reference/server-api.md:1093,1121,1153). Desktop, web, or external clients that special-case that documented idempotency outcome can therefore interpret an occupied rejection as completion and silently discard the unsent prompt. Assign occupancy an unused protocol code and update both locale documents and API snapshots.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

Comment on lines +105 to +106
const disk = this.diskLength(scope, key);
if (disk !== undefined) state.knownLength = disk;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Snapshot only journal bytes consumed by the reader

When another process appends after this reader reaches EOF but before the finally block stats the file, knownLength includes records that were never decoded into the in-memory fold. After the writer releases its lock, externallyModified sees equal lengths and allows this stale client to append instead of raising session.stale, silently mixing histories. Record the byte count actually consumed, or capture a stable file snapshot before reading.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +2194 to +2197
restore: () => {
this.staging.releaseRecalled(rewrite.imageAttachmentIds);
this.restoreInputText(args);
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Restore the plugin command, not only its arguments

When an occupied plugin command is cancelled, or a stale session is reloaded, this restores only args; the original input was /${pluginId}:${commandName} ${args}. For example, cancelling /foo:bar x leaves only x in the editor, so pressing Enter sends an ordinary prompt rather than retrying the command, while an argument-free command restores an empty editor. Reconstruct and restore the complete command line.

AGENTS.md reference: AGENTS.md:L102-L104

Useful? React with 👍 / 👎.


submit(input: UserEntry, options?: LoopSubmitOptions): LoopSubmitResult {
if (this.disposing) throw abortError('Agent loop disposed');
beginSessionRun(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reload stale sessions before retrying cron deliveries

When a loaded session was changed by another process before a cron job becomes due, this new check throws session.stale, but deliverFire catches every submit exception and merely returns false (cronService.ts:195-205). The cursor remains due while the same stale scope is retried on every tick, so unattended recurring and one-shot cron jobs never fire again until some separate user action reloads the session. Reload or retire the session when cron encounters this error instead of repeatedly retrying the stale scope.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +416 to +417
if (this.tryHoldSessionLock() && !this.log.externallyModified(this.wireScope, AGENT_WIRE_RECORD_KEY)) {
await this.log.rewrite(this.wireScope, AGENT_WIRE_RECORD_KEY, rewrittenRecords);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Persist deferred wire migrations before accepting writes

When a client opens an older-format session while another process holds the lock, this condition skips the required journal rewrite but discards rewrittenRecords instead of remembering that migration is pending. Once the other process releases the lock without changing the file, beginSessionRun considers the journal current and appends modern records under the old protocol header; later readers then apply the old migration to those new records and can misread or corrupt the session. Preserve the deferred rewrite and complete it after acquiring ownership, before permitting any append.

AGENTS.md reference: AGENTS.md:L102-L104

Useful? React with 👍 / 👎.

…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.
@7Hanrui

7Hanrui commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 610f8e36ab

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

this.sessionLocks,
this.appendLogStore,
this.sessionContext.sessionId,
this.sessionContext.scope(`agents/${MAIN_AGENT_ID}`),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Validate the active agent journal before accepting writes

When another client directly advances a subagent journal without changing agents/main/wire.jsonl, submitting to that subagent checks only the unchanged main journal here. Because beginSessionRun also caches the successful check by session token rather than by journal, the subsequent append proceeds from the stale subagent fold and can silently mix histories. Validate the current agent's journal, or all loaded journals, before accepting writes.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 45e05a5. On the first check of each lock hold, beginSessionRun now runs externallyModified over the wire of every agent loaded in this process (IAgentLifecycleService.list()), not only main. If any of them changed on disk, it releases the lock and throws session.stale. An agent that is not loaded is read from disk when it loads, so it does not need the check. All four call sites (loop submit, manual compaction, undo, print preflight) go through the same function.

Comment thread apps/kimi-code/src/tui/kimi-tui.ts Outdated
this.setAppState({ streamingPhase: 'idle' });
this.resetLivePane();
const mediaSnapshot = this.imageStore.snapshot();
void (async () => {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Block editor input while stale reload is running

After a stale prompt, the UI is set back to idle and this reload is launched without being awaited or represented as an in-flight session replacement. A user can therefore type another message while reloadSessionAfterStale is pending; when it finishes, the unconditional restore() replaces that newly typed text with the rejected prompt, silently losing the user's intervening input. Keep the editor unavailable until reload and restoration complete, or merge with any text entered during the reload.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 45e05a5. The stale branch no longer drops to idle before the reload. The request stays in flight until the reload, the attachment restore and the input restore have finished, so Enter during the reload queues the message instead of sending it to the closing session. The queue is kept across switchToSession and drained into the reloaded session. When the rejected prompt is restored, text typed during the reload is appended after it instead of being overwritten.


submit(input: UserEntry, options?: LoopSubmitOptions): LoopSubmitResult {
if (this.disposing) throw abortError('Agent loop disposed');
beginSessionRun(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Check staleness before persisting prompt metadata

For normal prompts and bundled-skill prompts, AgentPromptChannel calls applyPromptMetadataUpdate before reaching this new stale check. If another process changed the wire journal and released the lock, the rejected client first persists the unsent prompt as lastPrompt (and can generate a title/index update), then beginSessionRun throws session.stale; reloading does not undo that metadata mutation. Perform the stale preflight before prompt metadata is written so a rejected prompt cannot silently alter session metadata.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly addressed in c4c3e88. Whether to derive a title from the prompt is now decided inside the metadata service, after state.json has been re-read for the new lock hold. A stale cache can no longer overwrite a title another client wrote, and SessionMetaUpdated only carries a title that was actually written.

Writing lastPrompt before the stale check is accepted as is. The rejected prompt goes back to the input and is normally resent right after the reload, which records the same lastPrompt. If the user drops it instead, the session list shows that text as the last prompt until the next send. A title is derived from the rejected prompt only when the session is still untitled on disk, and that is the title the resend would produce anyway. Running the stale preflight first would change the call order at six call sites (prompt channel, plugin commands, two skill paths, two kap prompt routes) for a preview field.

Comment on lines +580 to +583
state.knownInteractions.clear();
state.deferredWork = undefined;
state.transcriptSeeded.clear();
state.deferredTranscriptSeeds.clear();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear volatile snapshot trackers when detaching

When a stale kap-server session is detached while another process finishes its turn or subagents, this block clears subscriptions and transcript state but preserves state.tracker and state.roster. Reattachment only listens for future events, so REST snapshots and WebSocket resyncs can continue reporting an obsolete in-flight turn or running subagents until another local turn happens; clear or rebuild both trackers at the detach/reattach boundary.

AGENTS.md reference: AGENTS.md:L114-L116

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 45e05a5. detachSession now clears the in-flight turn tracker and the subagent roster for the session, so after reattach the REST snapshot and the WS resync no longer report the turn or the subagents of the closed handle.

"session.init_failed": "Failed to initialize the session.",
"session.closed": "Session was closed.",
"session.fork_active_turn": "Wait for the current response before forking.",
"session.stale": "Session was updated by another client. Reopen the session to load the latest updates.",

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Surface session conflicts as preflight errors in VS Code

When a VS Code prompt is rejected with session.stale or session.occupied before TurnBegin, SessionRuntime emits a preflight error, whose store handler restores the input without rendering an inline error; the only visible notification is the toast gated by isPreflightError(code). Neither new code is in PREFLIGHT_CODES, and occupancy has no message entry at all, so sending appears to be silently ignored even though this stale message was added. Add both conflict codes to the preflight set and provide the occupancy message or recovery action.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 45e05a5. session.occupied and session.stale are now in PREFLIGHT_CODES, and ERROR_MESSAGES has an entry for session.occupied with the same copy the engine emits. The webview withdraws the message, puts the text back in the input, and shows the toast; the toast text comes from getUserMessage in the extension host.

…sion 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.
- 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.
@7Hanrui

7Hanrui commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 45e05a5d30

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +264 to +266
if (this.tryHoldForWrite()) {
await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Abort creation when initial metadata cannot acquire the lock

When two processes create the same explicit session ID before either has appended its index entry, the second process reaches this branch while the first holds the new session lock. tryHoldForWrite() returns false, but creation continues, mirrors the in-memory metadata, and reports success without writing state.json; subsequent operations run against a ghost scope for the other process's session and can later persist stale state. Propagate session.occupied and abort materialization instead of silently skipping the initial write.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +127 to +132
beginSessionRun(
this.sessionLocks,
this.appendLogStore,
this.session,
this.agentLifecycle,
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Hold an explicit lease for the entire undo operation

When undo restoration or participant reconciliation takes more than three seconds, beginSessionRun is the only hold acquired here, while ISessionActivityView.busy remains false because undo is not a turn, task, or compaction. The release timer can therefore unlink the lock after the branch switch but before the later restore/reconciliation records finish, allowing another process to mutate the same session concurrently. Acquire an explicit lease around the complete undo transaction.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +217 to +219
private alive(holder: SessionLockHolder): boolean {
if (holder.hostname !== '' && holder.hostname !== this.hostname) return true;
if (!pidAlive(holder.pid)) return false;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reclaim stale locks created on another host

When KIMI_CODE_HOME is on shared storage and the lock-owning host crashes or becomes unavailable, any client on a differently named host treats the holder as alive unconditionally. The PID and timestamp are never examined, so the session remains permanently occupied until someone manually deletes the lock file. Use a remotely reclaimable lease or an expiry/liveness mechanism instead of making every foreign-host lock immortal.

AGENTS.md reference: AGENTS.md:L102-L104

Useful? React with 👍 / 👎.

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.
@7Hanrui

7Hanrui commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 84e33ca296

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +317 to +320
await closeSessionById(app.accessor, resolved.session.id);
const reloaded = await resolveNativeSession(app, opts, workDir, defaultModel, stderr);
resolved = reloaded;
restorePermission = reloaded.restorePermission;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve the permission mode across stale print reloads

When a resumed print-mode session hits session.stale, resolveNativeSession has already changed its permission mode to auto and saved a closure that restores the previous mode. This closes the old scope without invoking that closure, then replaces restorePermission with the reloaded scope's closure; because closing drains the old wire, the reload observes auto as its previous mode. A one-off headless run can therefore silently leave future interactive clients in auto mode. Restore the original override before closing, or perform stale preflight before applying the temporary permission change.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

);
}

const lastCheckedTokens = new Map<string, string>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Clear cached staleness tokens after lock holds end

In a long-lived process such as kap-server, the first run of every distinct session inserts its ID and random lock token into this process-global map, but ending the run, closing the session, deleting it, and disposing the lock service never remove the entry. Servers that encounter an unbounded stream of session IDs therefore retain all of those strings for the lifetime of the process. Keep the checked token in the held-lock state or remove it whenever the corresponding lock hold ends.

Useful? React with 👍 / 👎.

@7Hanrui

7Hanrui commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 0f29b9173c

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +90 to +92
this.log.bindWriteGuard(this.wireScope, AGENT_WIRE_RECORD_KEY, () =>
this.sessionLocks.tryHold(this.sessionContext.sessionId),
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate shell commands before executing them

When a TUI ! command or SDK runShellCommand() runs while another process owns the session, this guard only prevents the resulting wire records from reaching disk; AgentShellCommandService.run() still appends the shell input and executes the command before ownership is checked. The caller therefore receives a successful result and any filesystem side effects occur, while the command history remains buffered, may be appended after unrelated external updates, or is silently dropped when the session closes. Acquire the session run gate and perform stale recovery before starting the command rather than relying on the journal write guard.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +1014 to +1016
onReloaded: async (handle) => {
this.wireSession(handle);
await this.notifyStaleReload(sessionId, await this.resumedSessionSummary(handle));

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reuse resume options when rebuilding stale sessions

When an SDK session was resumed with includeSubagents: true or a finite replayTurnLimit, the first stale prompt closes it and this callback rebuilds the public resume state with resumedSessionSummary(handle) using neither option. Session.getResumeState() consequently loses every subagent snapshot and folds the entire main-agent journal instead of the requested window; the TUI also always supplies REPLAY_FETCH_TURN_LIMIT, so a stale recovery of a long session can unexpectedly read the full journal. Retain the original resume options per live session and reuse them for the stale-reload summary.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +251 to +255
preparedMedia = await resolvePromptMediaFiles(
resolvedSessionMedia,
core.accessor.get(IFileService),
core.accessor.get(IBootstrapService).cacheDir,
{

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Acquire the session lock before materializing media

When an occupied session receives a prompt containing a compressed or unsupported image/file, this call writes originals into media-originals or materialized files into attachments before metadata update or loop.submit() performs the first ownership check. The later session.occupied rejection calls preparedMedia.discard(), but that only deletes temporary IFileService uploads, not these direct session-directory writes, so every rejected request can leave unreferenced files behind and repeated requests can grow attachments without bound. The skill-activation path has the same ordering at packages/kap-server/src/routes/skills.ts:261-281; preflight ownership before either media preparation or track all persisted paths for rollback.

Useful? React with 👍 / 👎.

@7Sageer 7Sageer mentioned this pull request Oct 19, 2026
5 of 6 tasks
@7Hanrui

7Hanrui commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: da853589ae

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +79 to +80
await closeSessionById(accessor, sessionId);
const session = await resumeSessionById(accessor, sessionId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Serialize stale recovery with in-flight session operations

When two requests are already using the same stale scope—for example, an attachment-heavy skill activation is awaiting media preparation while a normal prompt reaches the run gate—the prompt can enter this branch and dispose the scope underneath the slower request. That request still holds services from the disposed scope, so when it resumes and submits its turn it fails with an abort/"Agent loop disposed" error, which kap reports as an internal error instead of reloading and retrying. The close and resume calls are individually lifecycle-serialized, but the original run() callbacks are not; serialize the whole run/recovery/retry transaction per session or detect and retry operations whose scope generation was replaced.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

Comment on lines +296 to +300
const { previousPermissionMode } = resolved;
if (previousPermissionMode !== undefined) {
restorePermission = async () => {
resolved.agent.accessor.get(IAgentPermissionModeService).setMode(previousPermissionMode);
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refresh the saved permission mode after stale reloads

When another client changes the permission mode after print mode loaded the session but before its run gate detects the external update, stale recovery replaces resolved.agent with the reloaded agent at lines 341–347, while this cleanup closure retains the permission value captured from the old scope. Shutdown therefore applies the pre-update value to the new agent and silently overwrites the other client's setting; capture the reloaded agent's current mode before forcing it to auto and restore that value instead.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

if (this._compacting) return false;
const data: CompactionBeginData = { source: input.source, instruction: input.instruction };
if (data.source === 'manual') {
this.runGate.begin();

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Release run holds when validation prevents a run

When manual compaction is requested for an empty history or otherwise fails validateCompactionStart, this acquires the session hold before validation throws, but no compaction activity starts to justify retaining it. The same ordering exists for an unavailable undo at undoService.ts:124-125; in both cases an unrelated process that retries immediately receives session.occupied for the full three-second idle delay even though the operation already failed. Release the hold on pre-start failures or use a scoped acquisition that is retained only after validation succeeds.

Useful? React with 👍 / 👎.

const agent = session.accessor.get(IAgentLifecycleService).handleOf(agentContext.agentId)!;
if (opts.model !== undefined) await agent.accessor.get(IAgentProfileService).setModel(opts.model);
agent.accessor.get(IAgentPermissionModeService).setMode('auto');
resolved = { ...resolved, session, agent };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Recompute the goal model after stale reloads

When print goal mode resumes without --model and another client configures a model after the initial load, the run gate correctly reloads the updated agent, but this spread retains the old resolved.goalModel. The retry then passes that stale value to ensureNativeGoal; if the session was initially model-less, requireConfiguredModel still rejects even though the reloaded agent now has a valid model. Recompute goalModel from the reloaded profile before retrying.

AGENTS.md reference: AGENTS.md:L122-L124

Useful? React with 👍 / 👎.

@7Hanrui

7Hanrui commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: ff080c7805

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

let targetId: string | undefined;
let targetSessionDir: string | undefined;
const quiescenceHolds: IDisposable[] = [];
const sourceLease = this.sessionLocks.lease(sourceId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refresh the fork source after taking its lease

When a process keeps a source session loaded while another process updates and releases it, this lease succeeds but the fork still reads the first process's cached ISessionMetadata and materialized agent roster. The directory copy can therefore contain the latest journals while the subsequently written target state.json silently restores stale title/custom data and omits newly added agents, orphaning their copied journals. Reload or validate the live source after acquiring ownership, or read its metadata and roster from disk under the lease.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

reply.send(okEnvelope({ activated: true, skill_name: parsed.id }, req.id));
};
try {
await reloadOnStale(core.accessor, session_id, activateOnce);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preflight activation before retrying it

When a stale session is detected during skill activation, AgentSkillService.activate() has already dispatched and persisted skill.activated before loop.submit() reaches the run gate, but this wrapper reloads and invokes the entire activation again. Closing the stale scope flushes the first activation, and the retry generates a new activation ID, leaving an orphan marker plus the successful marker in journal/transcript event streams and counting telemetry twice; SDK plugin-command and bundled-skill retries have the same pre-gate side effect. Validate ownership before dispatching activation events, or make the retry reuse or roll back those effects.

Useful? React with 👍 / 👎.

Comment on lines +105 to +106
this.refreshBeforeWrite = false;
const existing = await this.store.get<SessionMeta>(this.scope, META_KEY);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Retry metadata refresh after a read failure

When store.get() transiently rejects after the lock is acquired, this clears refreshBeforeWrite before the refresh succeeds. Because the lock remains locally held, an immediate retry does not emit another onDidHold event and therefore skips the disk read, allowing applyUpdate() to write the stale cached SessionMeta over changes made by the previous owner; a decode failure can likewise be followed by a retry that overwrites the unreadable file. Clear the flag only after a successful read, or restore it when the read fails.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

@7Hanrui

7Hanrui commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@codex review

@7Sageer
7Sageer marked this pull request as ready for review October 20, 2026 04:51

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b253934c2d

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +173 to +178
if (!this.sessionLocks.tryHold(this.ctx.sessionId)) {
this.log.warn(
'session metadata agent registration skipped; session is in use by another client',
{ sessionId: this.ctx.sessionId, agentId },
);
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Propagate occupancy when agent registration fails

When a second client invokes /sessions/{id}:btw while another process owns the session, SessionBtwService.start() creates the child scope but this branch silently skips its state.json roster entry. The route then returns a successful agent_id; after the lock is released the child can write a journal, but closing or reloading the session makes that conversation unresolvable and leaves the journal orphaned. New-agent creation should surface session.occupied and unwind instead of reporting success.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +144 to +145
* When another client has updated this session, calls that start a run
* (prompt, steer, compact, …) reload the session from disk and retry once;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Route direct skill activation through stale reload

For SDK callers using Session.activateSkill(), an externally updated session now reaches the run gate and throws session.stale, but SDKRpcClientV2.activateSkill() is the run-starting method that was not wrapped in withStaleReload. The handler documented here is therefore never invoked for direct skill activation, and every retry keeps failing against the same stale scope until the caller manually reloads; wrap this path like prompt, bundled-skill, and plugin-command activation.

Useful? React with 👍 / 👎.

Comment on lines 88 to +92
this._register(this.log.acquire(this.wireScope, AGENT_WIRE_RECORD_KEY));
this._register(
this.log.bindWriteGuard(this.wireScope, AGENT_WIRE_RECORD_KEY, () =>
this.sessionLocks.tryHold(this.sessionContext.sessionId),
),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Keep the write guard bound through log retirement

When an append is pending because another process owns the session and this agent is then disposed, these registrations are torn down in reverse order: the write guard is removed before log.acquire() is released. The ensuing retired-state flush therefore sees no guard and silently appends the pending records while the other process still holds the lock, allowing concurrent journal writes instead of the intended guarded drop; retain the guard until retirement has completed or store it on the retiring log state.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

@pkg-pr-new

pkg-pr-new Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@dd97dac
npx https://pkg.pr.new/@moonshot-ai/kimi-code@dd97dac

commit: dd97dac

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b253934c2d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +256 to +258
if (this.sessionLocks.tryHold(this.ctx.sessionId)) {
await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject duplicate cross-process session creation

When two independent SDK processes concurrently call createSession with the same explicit id, both can complete their index existence check before either has written metadata. The first process acquires the new lock; the second reaches this branch, treats tryHold() === false as success, and returns a live session whose initial state.json was never persisted. It may later mutate the first caller's session after the lock is released, despite both creates reporting success. Reserve the requested ID for the entire create transaction and surface SESSION_ALREADY_EXISTS or SESSION_OCCUPIED to the loser.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines 325 to 327
while (state.flushPromise === owned && state.pending.length > 0) {
if (!this.writeAllowed(scope, key, state)) break;
await this.drain(scope, key, state, wroteBox);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Reject context mutations while the write guard is declined

When another process holds a session, public SDK calls such as Session.clearContext() and Session.importContext() mutate the local context and dispatch durable wire events without entering the run gate. This branch merely stops flushing and reports success, so closing the stale scope while the other holder remains drops the requested change; if a later flush obtains the lock, it instead appends a stale context.clear or imported message after the other process's history. Preflight ownership/staleness before these mutators, rather than silently retaining their records for a later flush.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +150 to +157
async applyPromptMetadata(lastPrompt: string, title: string): Promise<boolean> {
return this.enqueueUpdate(async () => {
if (!(await this.prepareWrite())) return false;
const applyTitle = this.data.titleKind !== 'custom' && isUntitled(this.data.title);
const patch: SessionMetaPatch = applyTitle
? { lastPrompt, title, titleKind: 'replaceable' }
: { lastPrompt };
return (await this.applyUpdate(patch)) && applyTitle;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Gate prompt metadata before persisting it

When a loaded client is stale, prompt submission writes lastPrompt (and potentially the generated title) here before loop.submit() reaches the run gate. If stale recovery then reloads and its one retry finds the session occupied, the request is rejected and the TUI may let the user cancel, but the rejected text remains persisted as the session preview/title. Perform the stale/ownership check before applying prompt metadata, or roll this update back when the submit is not accepted.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

Comment on lines +239 to +241
if (this.sessionLocks.tryHold(this.ctx.sessionId)) {
await this.store.set(this.scope, META_KEY, encodeSessionMeta(this.data));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Hold a lease through metadata migration writes

When resuming an older session whose state.json needs migration, this acquires only the idle run hold before awaiting the atomic write. On a slow or remote filesystem, or with a large custom metadata payload, that write can exceed the three-second idle delay; releaseWhenIdle() then unlinks the lock, another client can update the document, and this delayed atomic rename replaces that newer update with the migration snapshot. Retain an explicit lease for the whole migration write.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

@7Hanrui

7Hanrui commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5560a33f47

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +103 to +106
this.sessionLocks.hold(this.ctx.sessionId);
if (this.refreshBeforeWrite) {
this.refreshBeforeWrite = false;
const existing = await this.store.get<SessionMeta>(this.scope, META_KEY);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Hold a lease while refreshing session metadata

When an idle metadata update runs on a slow or remote filesystem, this unleased store.get() can outlast the three-second idle-release timer, allowing the run gate to release the lock while the read is still in progress. If another process then updates and releases the session before this read returns, applyUpdate() reacquires the lock only after the stale snapshot has been installed and silently overwrites the newer metadata. Acquire a lease before the refresh and retain it through the subsequent write so the read-modify-write transaction remains exclusive.

AGENTS.md reference: AGENTS.md:L130-L132

Useful? React with 👍 / 👎.

await lifecycle.create({
agentId,
forkedFrom: meta.forkedFrom,
labels: meta.labels,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Preserve legacy subagent lineage during lazy restore

When a resumed session contains an older AgentMeta with parentAgentId or swarmItem stored in the top-level compatibility fields rather than labels, this lazy restore drops those values by passing only meta.labels. AgentLifecycleService.create() then constructs replacement metadata with parentAgentId: 'main' and no swarm item, and registerAgent() can persist that replacement, silently changing nested-agent ownership and losing swarm identity. Use labelsFromAgentMeta(meta), as the existing subagent rebuild paths do, before recreating the agent.

AGENTS.md reference: AGENTS.md:L110-L112

Useful? React with 👍 / 👎.

Comment on lines 178 to 180
const closeSubscription = service.onDidCloseSession((event) => {
this.evictSession(event.sessionId);
this.detachSession(event.sessionId);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Evict broadcaster state after permanent session closes

When a long-running kap server opens and then permanently closes many sessions, every close now only marks its SessionState detached instead of removing it from sessions; if no matching onDidCreateSession follows, neither unsubscribe() nor any other path evicts that state. Each closed session therefore retains its journal object, buffered tail, and subscription maps until the whole broadcaster shuts down, so memory grows with every distinct closed session. Distinguish stale-reload closes from terminal closes, or evict detached states once reattachment is no longer pending.

AGENTS.md reference: AGENTS.md:L126-L128

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dd97daca55

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

private async prepareWrite(): Promise<boolean> {
await this.ready;
if (this.disposed) return false;
this.sessionLocks.hold(this.ctx.sessionId);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Acquire occupancy before generating a title

When POST /sessions/{id}/title/generate (or the SDK title-generation call) targets a session another process is writing, SessionTitleService.generateAndApply() has already composed conversation text and called fetchChatTitle before setGeneratedTitleIfUncustomized() reaches this new lock acquisition. The request then returns session.occupied, but it has still sent session content to the title service and consumed a title-generation request. Preflight the session lock/run gate before composing or dispatching title generation.

Useful? React with 👍 / 👎.

@7Sageer
7Sageer merged commit 3079e95 into main Oct 20, 2026
16 checks passed
@7Sageer
7Sageer deleted the session-lock branch October 20, 2026 09:21
7Sageer added a commit that referenced this pull request Oct 20, 2026
* 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]>
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants