Skip to content

fix(sdk): allow resuming occupied sessions - #4910

Merged
7Sageer merged 1 commit into
MoonshotAI:mainfrom
7Sageer:fix-resume-occupied-session
Nov 13, 2026
Merged

7Sageer merged 1 commit into
MoonshotAI:mainfrom
7Sageer:fix-resume-occupied-session

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Requirement or Bug

当同一会话正在 Web 等另一个客户端中运行时,TUI 选择 resume 会直接报 session.occupied,用户无法查看已有历史。这个 PR 让 resume 可以恢复并显示历史,同时保留发送消息时的写入互斥与显式接管流程。

Bug Reproduction Steps

  1. 在一个客户端中创建会话并发送消息,使其持有会话写锁。
  2. 在另一个 CLI 进程中通过 kimi --resume <session-id> 或 Sessions picker 恢复同一会话。
  3. 修改前:恢复失败并提示 This session is in use by another ... instance;修改后:历史正常显示,且提交新消息仍返回 session.occupied。

Root Cause

AgentLoopService.initializeLoop() 在加载历史前无条件申请写锁,使只读恢复与后续写入共享同一个入口。另一个客户端持锁时,整个 resume 因此失败。

这是针对锁层级的修复:初始化先尝试获取短期租约;没有待恢复写入时允许只读创建 loop,有待处理输入或任务完成通知时仍必须先取得写锁。

Code Changes

 initializeLoop
-  acquire write lease before reading history
+  try to acquire a write lease
   restore journal, profile, and task history
+  if pending work needs delivery and the lease is unavailable
+    require the write lease as before
   create loop
   release the short lease when held
  • SessionRunGateService.tryAcquire() 复用现有 stale 检查;仅将 session.occupied 转为无租约结果,其他错误继续抛出。
  • AgentLoopService.initializeLoop() 在没有待恢复工作时允许只读启动;存在待处理输入或需要补发的任务完成通知时,仍通过 acquire() 保留原拒绝行为。
  • begin() 的占用和 stale 语义不变。acquire() 仍用于发送消息及其他写入路径,没有自动 takeover,也没有修改 TUI 的重试 / 接管交互。

Screenshots / Recordings

真实构建的 CLI 在另一个客户端持锁时执行 --resume,历史消息正常显示,没有出现 session.occupied。以下文本来自该进程的 PTY 输出,示例会话与目录均为临时数据。

 ⠋ Restoring session…
 ╭────────────────────────────────────────────────────────────────────────╮
 │  ▐█▛█▛█▌  Welcome to Kimi Code!                                        │
 │  Directory: /workspace/example.test                                    │
 │  Session:   session_0b49c45a-94aa-4ce1-9845-f2e4d3e28eba             │
 ╰────────────────────────────────────────────────────────────────────────╯
 ❯ Show existing history
 ╭────────────────────────────────────────────────────────────────────────╮
 │ >                                                                      │
 ╰────────────────────────────────────────────────────────────────────────╯

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
无待恢复写入的占用会话 resume TUI、SDK 等客户端在加载历史时因 session.occupied 失败 可以恢复并读取历史,不接管另一客户端的锁 无;此前该操作无法完成 无需配置;发送消息仍保留占用提示
有待处理输入或待补发任务通知的占用会话初始化 必须取得写锁,否则返回 session.occupied 保持相同行为 崩溃恢复、后台任务完成通知等需要避免并发写入的客户端 原有锁释放或显式 takeover 流程不变
占用会话的消息发送 返回 session.occupied,TUI 提供重试 / 接管 保持相同行为 TUI、SDK、print 等发送写入的客户端 原有交互不变
  • sessionRunGate.test.ts:覆盖可选租约的占用结果、原有 direct hold 释放语义。
  • rpc-events.test.ts:覆盖无恢复工作时只读启动、发送仍拒绝,以及崩溃通知恢复仍需锁且只投递一次。
  • sdk-rpc-client-v2.test.ts:两个独立 engine 实例共享持久化 home,一方持锁,另一方恢复历史并确认写入拒绝。
  • 没有修改 RPC / SDK 方法签名、配置、会话存储格式或用户文档中已有契约;因此不需要额外文档更新。
验证结果
  • agent-core-v2 与 node-sdk TypeScript 检查通过。
  • sessionRunGate.test.ts、rpc-events.test.ts、coreLoopService.test.ts 全部通过。
  • sdk-rpc-client-v2.test.ts 完整文件通过。
  • CLI 构建,以及 v2-run-print.test.ts、kimi-tui-startup.test.ts 通过。
  • 新增双客户端用例在未修改基线上以 session.occupied 失败,修复后通过。
  • 真实 PTY 中验证 Web 持锁时 CLI 恢复历史成功。
  • pre-commit 的 oxlint 与类型感知检查通过。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).(本 PR 为内部修复,无关联 issue;问题与复现步骤已在上方说明。)
  • 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.(现有文档未描述旧的占用拒绝行为;本次只修正该行为,无配置、命令或契约变化。)

Copilot AI balanced review requested due to automatic review settings November 13, 2026 05:50
@changeset-bot

changeset-bot Bot commented Nov 13, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 1b91fed

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 Patch

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

@7Hanrui

7Hanrui commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

@codex review

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 insufficient remaining quota. Try requesting a review at a lower effort level.

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T05:59:57.242210Z 1b91fed Draft marked ready
ℹ️ 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.

@7Sageer
7Sageer marked this pull request as ready for review November 13, 2026 05:56
@pkg-pr-new

pkg-pr-new Bot commented Nov 13, 2026

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

commit: 1b91fed

@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: 1b91feddc2

ℹ️ 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".

isLive: (taskId) => this.toolExecutor.handler(taskId)?.snapshot().status === 'running',
});
const pendingWork = (snapshot.input.inbox?.normal?.length ?? 0) + (snapshot.input.inbox?.notify?.length ?? 0);
if (lease === undefined && (completions.length > 0 || pendingWork > 0)) lease = this.runGate.acquire();

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 Allow read-only resume with a task running in the owner

If another client holds this session while a detached task is still running, its persisted task.started record is converted to lost by AgentTaskService.restore(). restoreTaskCompletions() then creates a lost-task notice in this process, which has no handler for the owner's task, so this condition calls acquire() and raises session.occupied; resume still cannot open history for these sessions. Only escalate for recovery notifications that are actually pending, not a task that may still be live behind the lock.

AGENTS.md reference: AGENTS.md:L113-L113

Useful? React with 👍 / 👎.

@7Sageer
7Sageer merged commit 6130601 into MoonshotAI:main Nov 13, 2026
18 checks passed
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