Skip to content

feat(web): share background KAP daemon across web, rc, and ssh - #5408

Draft
7Sageer wants to merge 9 commits into
mainfrom
feat/shared-kap-daemon
Draft

7Sageer wants to merge 9 commits into
mainfrom
feat/shared-kap-daemon

Conversation

@7Sageer

@7Sageer 7Sageer commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Screenshots / Recordings

kimi web、kimi rc 与新增的 kimi daemon 在 macOS / Linux 上的终端输出对比(默认拉起或复用后台共享 daemon 并立即返回终端提示符):

Before After
  ▐█▛█▛█▌  Kimi server ready  2.7.3
  ▐█████▌  Local web UI is available from this machine.

  Local:    http://127.0.0.1:58627/#token=YOUR_SERVER_TOKEN
  Network:  off  use --host to enable

  Token:    YOUR_SERVER_TOKEN

  Logs:     off  use --log-level info to enable
  Stop:     Ctrl+C
  ▐█▛█▛█▌  Kimi server ready  2.7.3
  ▐█████▌  Local web UI is available from this machine.

  Local:    http://127.0.0.1:58627/#token=YOUR_SERVER_TOKEN
  Network:  off  use --no-daemon --host to enable

  Token:    YOUR_SERVER_TOKEN

  Logs:     /home/dev/.kimi-code/server/daemon.log
  Stop:     kimi daemon stop

新增 kimi daemon status 输出:

Kimi daemon  running
  Version:         2.7.3 (KAP v1)
  PID:             48210
  Started:         2026-11-25T08:00:00.000Z
  Listeners:       http://127.0.0.1:58627 · unix:/home/dev/.kimi-code/server/daemon.sock
  Remote Control:  on  https://code-rc.kimi.com/devices/dev_example/  (workstation)
  Active sessions: 1
    - ses_01jc8x9q  [turn]  Investigate build failure
  Logs:            /home/dev/.kimi-code/server/daemon.log

Requirement or Bug

在同一台机器上同时使用 kimi web、kimi rc(Remote Control)和桌面端 SSH 远程连接时,此前每次命令都会独立拉起一个新的 kap-server 进程:Web 端口递增分裂、Remote Control 发生单实例锁冲突,会话和运行状态也无法在多端之间实时共享;同时桌面端通过 SSH 连接远程主机时,缺少独立的 KAP 协议版本双向校验。

本 PR 在 macOS 和 Linux 上引入共享的常驻后台 kap-server daemon(同时监听 loopback TCP 与 daemon.sock,统一托管会话与 Remote Control 偏好),提供 kimi daemon status|stop|restart 与 kimi rc stop 管理命令及 --no-daemon 前台逃生口,并在 /api/v1/meta 与 SSH ensure-daemon 握手中暴露独立的 kap_version 实现两端版本双向兼容拦截。

Bug Reproduction Steps

N/A

Root Cause

N/A

Code Changes

核心思路

把原先散落在 kimi web(前台常驻 TCP)、kimi rc(前台常驻 TCP + 独立隧道)和 kimi server ensure-daemon(仅监听 UDS 且 10 分钟空闲退出)的三套独立进程模型,收敛为单个常驻后台 kap-server daemon:同一个进程同时监听本机 loopback TCP(强制 Bearer token 鉴权)与 0700 目录下的 daemon.sock(免鉴权,按首非空白字节自动分流 JSONL RPC 与 HTTP/WS)。所有客户端入口都不拥有 daemon 生命周期,命令打印地址或二维码后立即返回;TUI 本体与桌面端本地会话保持现有进程内路径不变,Windows 本期保持独立前台运行;同时通过独立的 kap_version 在连接建立阶段拦截远端过旧或本机客户端过旧的不兼容组合。

概念

概念 回答什么问题 本 PR 之后
共享 kimi daemon 同一台机器同时开启 Web、RC、SSH 时谁持有引擎与隧道 单个后台 kap-server 同时监听 127.0.0.1:<port> 与 daemon.sock,常驻不按空闲自动退出,由 kimi daemon stop|restart 管理
daemon.sock 首字节嗅探 SSH 的 JSONL RPC 流与本机 CLI 的控制请求如何共用同一个 UDS 0700 目录下免鉴权;连接首非空白字节为 { 时走 JsonlRpcStream,否则作为受信 Unix HTTP/WS 连接交给 Fastify http.Server
RC 偏好持久化(daemon-settings.json) daemon 重启或升级替换后 Remote Control 隧道如何保持在线 开启 RC 时写入 remote_control_enabled: true,启动时自动恢复;kimi rc stop、Web 关闭 RC、OAuth 登出或网页端主动下线设备时清除
kap_version 桌面端与远程 SSH 主机的 KAP 协议何时兼容、不兼容时谁需要升级 在 GET /api/v1/meta 与 ensure-daemon 握手中返回实际运行 daemon 的 kap_version;远端偏低报 executor_outdated(或升级后旧 daemon 忙时报 remote_busy),远端偏高报 client_outdated

结构图

flowchart TB
    Browser["浏览器 (本机)"] -->|"HTTP / WS + Bearer Token"| TCP
    Phone["手机 / 远程浏览器"] -->|"Relay 隧道"| RC
    DesktopSSH["桌面端 (SSH)"] -->|"SSH stdio (JSONL)"| UDS
    CLI["CLI: kimi web / rc / daemon"] -->|"UDS HTTP 控制请求"| UDS

    subgraph Daemon["kimi daemon (kap-server)"]
        TCP["Loopback TCP Listener (127.0.0.1:58627+)"]
        RC["RemoteControlManager (偏好持久化于 daemon-settings.json)"]
        UDS["daemon.sock (0700 目录免鉴权 · JSONL + HTTP 首字节嗅探)"]
        Engine["共享引擎 Scope: 会话 / 回合 / 审批 / 配置 / MCP / 日志"]
        RC --> TCP
        TCP --> Engine
        UDS --> Engine
    end
Loading

因为 TCP 暴露在本机回环网络栈上而 daemon.sock 受限于 0700 用户目录权限,所以鉴权钩子通过进程内 WeakSet 仅放行来自 daemon.sock 的连接与 RPC 注入请求,保证 loopback TCP 上的所有 REST 与 WebSocket 请求依然严格校验 server.token。

关键决策

决策 选择 没选 理由
复用形态 单个后台 daemon 双监听 loopback TCP + daemon.sock kimi web / rc 在前台起轻量网关转发到 UDS 前台网关需要重复处理字节转发、鉴权与 RC 独立后台保活,且终端 Ctrl+C 与后台会话生命周期语义割裂;直接双监听结构最简单且多端状态天然一致
显式启动参数与受管理环境变量冲突 未传 --no-daemon 时直接报错退出,提示 kimi daemon restart 或 --no-daemon 静默忽略参数复用旧 daemon,或静默回退到前台独立进程 静默沿用旧配置会让用户误以为新环境变量或 --host 已生效,静默回退又会重新制造端口分裂
升级后遇到非空闲旧版 daemon 继续复用运行中的旧版 daemon 并在 stderr 提示(SSH 侧仅在旧 daemon 的 kap_version 不兼容时报 remote_busy) 强制杀掉旧 daemon 或无条件拒绝连接 不打断正在执行的回合与活跃 WebSocket 连接;若只是补丁升级且 kap_version 一致,SSH 与本地 CLI 都能无感继续工作
远端/本地 KAP 版本控制策略 连接握手双向对比 kap_version,不匹配时明确区分提示升级远端 CLI 或更新本机应用 daemon 后台自动静默自更新 后台自更新涉及跨平台文件替换锁、灰度策略与重启中断恢复,第一阶段先通过明确的协议版本契约与 UI 指引消除静默不兼容

阅读指南

  1. packages/kap-server/src/transport/stdioRpc.ts 与 packages/kap-server/src/start.ts:看双监听如何同时挂载 TCP 与 daemon.sock、如何做 JSONL/HTTP 首字节嗅探并隔离 Unix 免鉴权与 TCP Bearer 鉴权,以及 RC 偏好恢复。
  2. packages/kap-server/src/services/daemonSettings.ts、routes/remoteControl.ts、routes/oauth.ts:看 remote_control_enabled 何时写入、恢复与清除。
  3. packages/kap-server/src/services/hosts/sshKapBridge.ts 与 apps/kimi-code/src/cli/sub/web/ensure-daemon.ts:看 kap_version 如何从实际运行的 daemon 透传到握手标记,并在两端不匹配时区分 executor_outdated、remote_busy 与 client_outdated。
  4. apps/kimi-code/src/cli/sub/web/daemon-client.ts、cli/sub/daemon.ts、cli/sub/web/run.ts:看 daemon.lock 串行拉起、daemon.json 状态与受管理环境变量摘要比对、kimi web / kimi rc [stop] / kimi daemon status|stop|restart 的完整控制流。
  5. apps/kimi-code/src/tui/commands/web.ts:看 TUI 内 /web 与 /remote-control 如何改为复用共享 daemon 并打开已持久化会话。
  6. 其余 packages/app-*、packages/kap-server/schema/* 与 docs/{zh,en}/* 为 client_outdated 文案映射、OpenAPI 契约刷新与中英文用户文档同步,可快速略读。

具体变化大纲

 kimi web / kimi rc (macOS & Linux, 未传 --no-daemon / --json)
-  startServerForeground()  # 阻塞当前终端,Ctrl+C 退出,各自绑定独立端口并争抢 rc.json 锁
+  collectExplicitForegroundFlags() -> 存在 --host/--port 等前台专属参数时直接报错提示 --no-daemon
+  ensureSharedDaemon()             # 经 daemon.lock 串行化
+    probeRunningDaemon()           # 经 daemon.sock 读取 /api/v1/meta 与 daemon.json
+      diffManagedDaemonEnv()       # KIMI_* 或代理环境变量摘要不一致时报错提示 kimi daemon restart / --no-daemon
+      version !== cliVersion       # 调 /api/v1/shutdown?if_idle=true:空闲则替换,忙碌则复用并向 stderr 提示
+    spawnDetachedDaemonProcess()   # 未运行时后台拉起 `kimi server --daemon-server`
+  (若开启 RC) enableDaemonRemoteControl() # POST /api/v1/remote-control 持久化偏好并返回二维码链接
+  打印横幅 / 二维码并打开浏览器后立即返回
 SshKapBridge.checkBootstrapOutput(marker)
   protocol < HOST_PROTOCOL_VERSION -> throw HostConnectError('executor_outdated')
+  protocol > HOST_PROTOCOL_VERSION -> throw HostConnectError('client_outdated')
   remoteKap = marker.kap_version ?? marker.api_level
-  remoteKap < HOST_API_LEVEL       -> throw HostConnectError('executor_outdated')
+  remoteKap < KAP_VERSION:
+    marker.cli_version !== marker.version -> throw HostConnectError('remote_busy')
+    otherwise                             -> throw HostConnectError('executor_outdated')
+  remoteKap > KAP_VERSION          -> throw HostConnectError('client_outdated')

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
macOS / Linux 下运行 kimi web 在当前终端前台常驻运行独立 server,按 Ctrl+C 停止 拉起或复用后台共享 daemon,打印 URL 与 token、打开浏览器后立即返回;日志写入 ~/.kimi-code/server/daemon.log 依赖 kimi web 在前台阻塞进程(如 systemd/supervisor 脚本或临时单次启动)的 macOS / Linux CLI 用户 传入 --no-daemon(或脚本集成使用 --json);停止后台服务用 kimi daemon stop
macOS / Linux 下运行 kimi rc / kimi web --rc 在前台持有 Remote Control 隧道,按 Ctrl+C 下线;若已有 RC 实例则报锁冲突 由共享 daemon 托管并持久化 RC 偏好,打印二维码后立即返回;重复执行幂等复用,daemon 重启后自动恢复 RC 习惯按 Ctrl+C 关闭远程控制隧道的远程控制用户 关闭 RC 用 kimi rc stop;需要前台独立进程时传 --no-daemon
未带 --no-daemon 给 kimi web 传入 --host、--port、--log-level、--dangerous-bypass-auth 等服务参数 直接按所传参数新建前台 server 明确报错退出,不污染共享 loopback daemon 也不静默忽略参数 在 macOS / Linux 下开启局域网共享(--host)或指定端口的 Web 用户 按报错提示加上 --no-daemon(例如 kimi web --no-daemon --host)
当前 shell 的受管理 KIMI_* 或代理环境变量与运行中 daemon 启动时不一致 每次命令新建独立进程读取当前 shell 环境 kimi web / kimi rc 检测到摘要不一致时报错退出,不静默沿用旧环境 在终端临时导出 KIMI_CODE_PASSWORD、HTTPS_PROXY、KIMI_CODE_EXPERIMENTAL_* 等环境变量后运行 kimi web 的用户 运行 kimi daemon restart 应用新环境,或传入 --no-daemon
TUI 内执行 /web 或 /remote-control(macOS / Linux) 退出 TUI 后在当前终端前台启动新 server(易与已有 Web 端口分裂或与已有 RC 锁冲突) 复用共享 daemon,退出 TUI 释放会话锁后打印访问信息、打开当前已持久化会话并立即返回 shell(进行中的回合不迁移) 在 macOS / Linux TUI 中使用 /web、/remote-control 交接会话的用户 Windows 仍保持原前台路径;CLI 下可用 --no-daemon
SSH kimi server ensure-daemon 生命周期与升级忙碌行为 独立仅监听 UDS 的进程,空闲 10 分钟自动退出;CLI 升级后若旧 daemon 有活跃工作则直接报 version_mismatch_busy 拒绝连接 与 Web / RC 共用双监听 daemon,不再按空闲自动退出;旧 daemon 忙碌时优先复用并汇报旧 daemon 实际 kap_version,仅在 kap_version < KAP_VERSION 时报 remote_busy 桌面端 SSH 远程主机用户 远端可执行 kimi daemon stop 或 kimi daemon restart
SSH 远端协议版本高于本机桌面端(remote > local) checkBootstrapOutput 只检查 <,放行更高协议版本后可能在后续请求中因未知不兼容报错 握手阶段直接拦截并归类为 client_outdated,UI 提示更新本机 Kimi Code 应用(不显示误导性的远端 kimi upgrade 命令) 本机桌面端长期未更新、而远端服务器先行升级到未来不兼容 KAP 版本的桌面端 SSH 用户 更新本机 Kimi Code 应用
GET /api/v1/meta 响应结构 返回 kimi_agent_protocol_version、server_version 等字段 新增整数字段 kap_version(当前为 1) 桌面端、Web 端及通过 KAP 接入的外部 AI Agent / 脚本 纯新增响应字段,向后兼容

旧路径能力对照(前台独立服务 -> 共享 daemon + --no-daemon)

  • --port / --host / --allowed-host / --insecure-no-tls / --allow-remote-shutdown / --dangerous-bypass-auth / --log-level / --debug-endpoints / --web-title:全部保留在 --no-daemon 前台模式中;未加 --no-daemon 时显式拦截并提示。
  • --json(供外部 Agent 子进程拉起一次性服务):保持原有独立前台内存 token 行为不变。
  • Windows 平台:本期 isSharedDaemonSupported() 在 win32 返回 false,kimi web、kimi rc 与 TUI /web、/rc 原样走独立前台路径。
  • SSH_AUTH_SOCK 转发:在共享 daemon 每次拉起与 ensure-daemon 连接时原子更新 ~/.kimi-code/server/forwarded-ssh-agent.sock 符号链接,保持不变。
  • server.token 与 kimi web rotate-token:共享 daemon 继续读取同一 server.token 并注册到 server/instances/,轮换 token 无需重启。

受影响模块与验证结论

  • 受影响模块:packages/kap-server、packages/remote-control、apps/kimi-code(CLI web/rc/daemon 与 TUI /web、/rc)、packages/app-core、packages/app-components、packages/app-i18n、docs/{zh,en}。
  • 平台核对说明:改动涉及 UDS 路径、后台脱离进程(detached 子进程)与信号停止逻辑,已在 macOS(Darwin)上通过真实 startServer 双监听套接字(TCP + daemon.sock JSONL/HTTP 嗅探)及 CLI/TUI 单元与集成测试验证;Windows 分支通过 platform: 'win32' / isSharedDaemonSupported() === false 单测验证保持前台回退逻辑,未在真实 Windows 机器上实机运行。
验证命令与测试覆盖明细
  • pnpm lint:0 退出(通过 cli-dependencies、check-comments、oxlint --type-aware --deny-warnings、check-import-boundaries、guards、ratchet、test-doubles、legacy-e2e、quarantine、instructions、e2e-boundary)。
  • pnpm run check:duplication <base-sha>:检查新增源码无重复克隆。
  • 类型检查:packages/remote-control、packages/kap-server、apps/kimi-code、apps/desktop(主进程 tsc 与渲染进程 vue-tsc)均 0 错误通过。
  • 测试用例:
    • packages/kap-server/test/apiSurface.test.ts:验证 /api/v1/meta 新增 kap_version 契约快照与 HOST_API_LEVEL 摘要。
    • packages/kap-server/test/hosts.test.ts:覆盖 kap_version 双向拦截(executor_outdated / client_outdated / 升级忙碌时的 remote_busy 与兼容复用)、双监听 TCP Bearer 鉴权 + daemon.sock 免鉴权 JSONL/HTTP 首字节嗅探、daemon-settings.json 原子读写。
    • apps/kimi-code/test/cli/web/web.test.ts & apps/kimi-code/test/cli/options.test.ts:覆盖 kimi web / kimi rc 默认共享 daemon 返回、显式前台参数拦截、受管理 KIMI_* 环境变量摘要冲突报错、升级忙碌复用提示、kimi daemon status|stop|restart 及 --probe。
    • apps/kimi-code/test/tui/commands/web.test.ts:覆盖 TUI /web 与 /remote-control 复用共享 daemon、RC 冲突留守 TUI 报错提示,以及非支持平台回退前台服务。
    • packages/app-components/test/hostsPanel.test.ts:覆盖 client_outdated 在主机设置测试面板中的本地升级提示且不渲染远端 kimi upgrade 复制按钮。

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.

@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: bc56926

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

This PR includes changesets to release 4 packages
Name Type
kimi-code-app Patch
@moonshot-ai/remote-control Patch
@moonshot-ai/kimi-code Minor
@moonshot-ai/kap-server 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

@7Hanrui

7Hanrui commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 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-26T12:42:43.110074Z 70bbf46 Manual request
ℹ️ 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: 90a6316924

ℹ️ 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 +382 to +385
export async function probeRunningDaemon(homeDir: string): Promise<RunningDaemonInfo | undefined> {
const socketPath = daemonSocketPath(homeDir);
const metaRes = await daemonHttpRequest<MetaWire>(socketPath, 'GET', '/api/v1/meta', undefined, 2_000);
if (metaRes === undefined || metaRes.status !== 200 || metaRes.envelope.code !== 0) {

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 Fall back to JSONL when probing old daemons

When upgrading while the previous release's SSH daemon is still serving active work, this raw-HTTP probe cannot detect it because that daemon's Unix socket accepts only JSONL RPC. ensureSharedDaemon therefore starts a second server, whose startup unlinks and rebinds the same socket while the old process continues serving existing SSH streams; both processes can then operate on the same home and session data concurrently. Probe through the legacy JSONL protocol before concluding that the daemon is absent.

AGENTS.md reference: AGENTS.md:L112-L116

Useful? React with 👍 / 👎.

const STOP_GRACE_MS = 5_000;
const KILL_GRACE_MS = 2_000;

const MANAGED_DAEMON_ENV_KEYS = [

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 Track every daemon-affecting environment override

This allowlist omits documented invocation-level settings such as KIMI_MODEL_API_KEY, KIMI_MODEL_BASE_URL, KIMI_CODE_DANGEROUS_COMMAND_GUARD, and KIMI_WEB_SEARCH_API_KEY. After the first daemon starts, changing one of these variables and running kimi web again produces no mismatch error and silently continues with the original value, whereas the former foreground process inherited each invocation's environment. The daemon hash must cover all bootstrap-consumed environment overrides rather than this subset.

AGENTS.md reference: AGENTS.md:L207-L209

Useful? React with 👍 / 👎.

const dataDir = getDataDir();
let daemonResult: Awaited<ReturnType<typeof ensureSharedDaemon>>;
try {
daemonResult = await ensureSharedDaemon({ homeDir: dataDir });

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 daemon environment from TUI handoffs

When a daemon was started under a different environment, /web reuses it without checkEnv: true; /remote-control repeats the same omission at line 96. Consequently even tracked settings such as KIMI_CODE_PASSWORD are silently ignored for TUI users, unlike the equivalent kimi web and kimi rc commands, which reject the mismatch and explain how to restart or use the foreground path.

AGENTS.md reference: AGENTS.md:L211-L213

Useful? React with 👍 / 👎.

Comment on lines +352 to +354
const dir = dirname(socketPath);
await mkdir(dir, { recursive: true, mode: 0o700 });
await chmod(dir, 0o700).catch(() => {});

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 chmod on the shared temporary directory

When a long home path makes daemonSocketPath() fall back to ${tmpdir()}/kimi-daemon-*.sock, dir here is the system temporary directory itself. A privileged/root invocation can therefore change /tmp to mode 0700, preventing other users and services from accessing it; on user-owned platform temp directories it also overwrites permissions that this process did not establish. Create a daemon-owned private subdirectory or only chmod directories created under the Kimi home.

Useful? React with 👍 / 👎.

Comment on lines +733 to +735
const daemon = await probeRunningDaemon(options.homeDir);
const state = await readDaemonState(options.homeDir);
const pid = daemon?.pid ?? (state !== undefined && pidAlive(state.pid) ? state.pid : undefined);

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 Do not signal an unverified PID from stale state

If the daemon crashes without deleting daemon.json and the OS later reuses its PID, a failed socket probe still accepts that unrelated live PID here. stopSharedDaemon then sends it SIGTERM and potentially SIGKILL, so kimi daemon stop or restart can terminate an unrelated user process. Treat the state as stale when no daemon answers, or record and verify a process-start identity before signaling.

Useful? React with 👍 / 👎.

Comment on lines +334 to +338
const incompatibleFlags = collectExplicitForegroundFlags(opts);
if (incompatibleFlags.length > 0) {
throw new Error(
`Cannot apply ${incompatibleFlags.join(', ')} to the shared background daemon. Re-run with '--no-daemon' to start an independent foreground server with these options.`,
);

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 documented dev server scripts in foreground mode

On macOS/Linux this rejects the explicit --debug-endpoints used by apps/kimi-code/package.json's dev:server, dev:kap-server, and dev:kap-server:multi scripts, so each documented local server command exits with the --no-daemon error before starting. Update those scripts to pass --no-daemon (or exempt the development path) when introducing this guard.

AGENTS.md reference: apps/kimi-code/AGENTS.md:L70-L74

Useful? React with 👍 / 👎.

Comment on lines +623 to +627
'/api/v1/sessions?busy=true&page_size=50',
undefined,
3_000,
);
if (res === undefined || res.status !== 200 || res.envelope.code !== 0) 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 Fail closed when active-session inspection fails

When this request times out or returns a non-success response, it is converted to an empty session list, so kimi daemon stop and restart proceed without --force or confirmation and then signal the daemon even if work is active. Propagate inspection failures instead of treating them as proof that the daemon is idle.

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

Useful? React with 👍 / 👎.

Comment thread apps/kimi-code/src/cli/sub/web/run.ts Outdated
Comment on lines +573 to +574
const origin = `http://${v2.host}:${String(v2.port)}`;
await writeDaemonState(homeDir, {

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 Publish the bound address before reporting daemon readiness

When the default TCP port is occupied and the server selects a later port, the Unix-socket listener can answer /meta before this state write completes. During that window probeRunningDaemon substitutes 127.0.0.1:58627, so the spawning kimi web invocation can report or open the unrelated service occupying that port instead of the new daemon. Make readiness contingent on publishing the selected address, or obtain the bound address directly from the probe response.

Useful? React with 👍 / 👎.

Comment thread apps/kimi-code/src/cli/sub/web/run.ts Outdated
Comment on lines +573 to +574
const origin = `http://${v2.host}:${String(v2.port)}`;
await writeDaemonState(homeDir, {

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 Publish the bound address before reporting daemon readiness

When the default TCP port is occupied and the server selects a later port, the Unix-socket listener can answer /meta before this state write completes. During that window probeRunningDaemon substitutes 127.0.0.1:58627, so the spawning kimi web can print or open an unrelated service on the occupied default port instead of the newly started daemon. Publish the selected address before the socket becomes probeable, or make the probe wait for matching state.

Useful? React with 👍 / 👎.

Comment on lines +138 to 141
await opts.persistPreference?.(false).catch((persistError: unknown) => {
requestLog(req)?.warn({ err: persistError }, 'remote-control preference clear failed');
});
const status = await opts.service.disable();

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 Serialize Remote Control preference updates with toggles

When one client sends disable while another enable request is still waiting for the tunnel to start, this path persists false before entering RemoteControlManager's serialized disable queue. The enable request can then finish and persist true at line 159 before the queued disable turns the tunnel off, leaving the saved preference enabled; the next daemon restart unexpectedly restores remote access despite the successful stop. Persist the final state inside the same serialized operation as the tunnel transition.

Useful? React with 👍 / 👎.

# Conflicts:
#	docs/en/reference/kimi-command.md
#	docs/zh/reference/kimi-command.md
#	packages/kap-server/test/apiSurface.test.ts
#	tests/e2e/AGENTS.md
# Conflicts:
#	tests/e2e/AGENTS.md
#	tests/e2e/surfaces/web.ts
# Conflicts:
#	packages/kap-server/test/apiSurface.test.ts
@7Hanrui

7Hanrui commented Nov 26, 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: 70bbf46e7a

ℹ️ 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 rc: Awaited<ReturnType<typeof enableDaemonRemoteControl>>;
try {
rc = await enableDaemonRemoteControl(daemonResult.daemon.socketPath);

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 Resolve the token before enabling Remote Control

When server.token is missing or unreadable while the daemon is already running, this call successfully enables Remote Control and persists the enabled preference before the later token check reports an error and returns. The user remains in the TUI believing the handoff failed, but the tunnel stays active and can be restored after a daemon restart; validate the token before enabling the tunnel or disable it on this failure path.

AGENTS.md reference: AGENTS.md:L211-L213

Useful? React with 👍 / 👎.

exiting = true;
await removeDaemonStateForPid(homeDir, process.pid).catch(() => {});
await shutdownTelemetry({ timeoutMs: CLI_SHUTDOWN_TIMEOUT_MS }).catch(() => {});
process.exit(0);

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 Do not force a successful exit after cleanup failures

When any daemon shutdown cleanup rejects—for example while closing the server or draining session metadata—finalizeExit still terminates the process with status 0. In the core-drain path, onDidClose is invoked from a finally block and calls this function before the rejection can even propagate; kimi daemon stop consequently observes a dead process and reports success although cleanup may have been skipped and state may not have been flushed. Preserve the cleanup failure through daemon termination and surface it to the management command instead of unconditionally forcing a successful exit.

AGENTS.md reference: AGENTS.md:L211-L213

Useful? React with 👍 / 👎.

This branch has not been deployed

No deployments
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.

2 participants