From fb517a24f651b38615117aed9f513fded7b5dd06 Mon Sep 17 00:00:00 2001 From: qyz7438 <157498369+qyz7438@users.noreply.github.com> Date: Fri, 26 Jun 2026 00:01:08 +0800 Subject: [PATCH 1/3] fix(agent-core, kimi-code): handle stale closed sessions during resume When a session is closed while initialization is still running (for example, because an MCP server fails to start), the session object can remain in CoreRPCImpl.sessions even though the underlying directory exists on disk. Resuming that session later then fails with [session.not_found] because requireSession rejects the closed object. Changes: - Track Session.closed state and guard close() against double close. - In resumeSessionWithOverrides, drop stale closed session objects so a fresh session can be reconstructed from persisted state. - In requireSession, return a clear SESSION_NOT_FOUND error when the requested session has been closed. - In the TUI, catch SESSION_NOT_FOUND when applying startup modes to a resumed session and show an actionable message instead of crashing. Fixes symptom reported in MoonshotAI/kimi-code where resuming a session after an MCP initialization failure produced [session.not_found]. --- apps/kimi-code/src/tui/kimi-tui.ts | 51 +++++++++++++++--------- packages/agent-core/src/rpc/core-impl.ts | 18 ++++++++- packages/agent-core/src/session/index.ts | 9 +++++ 3 files changed, 59 insertions(+), 19 deletions(-) diff --git a/apps/kimi-code/src/tui/kimi-tui.ts b/apps/kimi-code/src/tui/kimi-tui.ts index 24a72043f..856752aee 100644 --- a/apps/kimi-code/src/tui/kimi-tui.ts +++ b/apps/kimi-code/src/tui/kimi-tui.ts @@ -9,15 +9,17 @@ import { Spacer, } from '@earendil-works/pi-tui'; import type { DeviceAuthorization } from '@moonshot-ai/kimi-code-oauth'; -import type { - ApprovalRequest, - ApprovalResponse, - BackgroundTaskInfo, - CreateSessionOptions, - KimiHarness, - PermissionMode, - PromptPart, - Session, +import { + ErrorCodes, + isKimiError, + type ApprovalRequest, + type ApprovalResponse, + type BackgroundTaskInfo, + type CreateSessionOptions, + type KimiHarness, + type PermissionMode, + type PromptPart, + type Session, } from '@moonshot-ai/kimi-code-sdk'; import type { MigrationPlan } from '@moonshot-ai/migration-legacy'; import { resolve } from 'pathe'; @@ -1217,16 +1219,29 @@ export class KimiTUI { // setPermission is idempotent and needs no such guard. private async applyStartupModesToResumedSession(session: Session): Promise { const { startup } = this.options; - if (startup.auto) { - await session.setPermission('auto'); - } else if (startup.yolo) { - await session.setPermission('yolo'); - } - if (startup.plan) { - const status = await session.getStatus(); - if (!status.planMode) { - await session.setPlanMode(true); + try { + if (startup.auto) { + await session.setPermission('auto'); + } else if (startup.yolo) { + await session.setPermission('yolo'); } + if (startup.plan) { + const status = await session.getStatus(); + if (!status.planMode) { + await session.setPlanMode(true); + } + } + } catch (error) { + if (isKimiError(error) && error.code === ErrorCodes.SESSION_NOT_FOUND) { + this.showError( + `Session disappeared during startup. ` + + `This usually means the session was closed while initialization was still running ` + + `(for example, an MCP server failed to start). ` + + `Try running the command again, or start a fresh session.`, + ); + return; + } + throw error; } } diff --git a/packages/agent-core/src/rpc/core-impl.ts b/packages/agent-core/src/rpc/core-impl.ts index 7088fba23..8f55d6041 100644 --- a/packages/agent-core/src/rpc/core-impl.ts +++ b/packages/agent-core/src/rpc/core-impl.ts @@ -374,7 +374,14 @@ export class KimiCore implements PromisableMethods { ...localWorkspaceDirs.additionalDirs, ...callerAdditionalDirs, ]); - const active = this.sessions.get(summary.id); + let active = this.sessions.get(summary.id); + if (active !== undefined && active.closed) { + // The session object is still in the map but has already been closed + // (e.g. by an earlier failed initialization or crash). Remove it so + // we can build a fresh session from persisted state. + this.sessions.delete(summary.id); + active = undefined; + } if (active !== undefined) { if (overrides.kaos !== undefined) { active.setToolKaos(overrides.kaos.withCwd(summary.workDir)); @@ -954,6 +961,15 @@ export class KimiCore implements PromisableMethods { details: { sessionId }, }); } + if (session.closed) { + throw new KimiError( + ErrorCodes.SESSION_NOT_FOUND, + `Session "${sessionId}" has been closed. ` + + `This can happen when session initialization fails (for example, an MCP server could not start). ` + + `Try resuming the session again, or start a fresh session.`, + { details: { sessionId } }, + ); + } return session; } diff --git a/packages/agent-core/src/session/index.ts b/packages/agent-core/src/session/index.ts index 1fd9e9e6b..6cd0eb04d 100644 --- a/packages/agent-core/src/session/index.ts +++ b/packages/agent-core/src/session/index.ts @@ -171,6 +171,11 @@ export class Session { }; private writeMetadataPromise = Promise.resolve(); private agentsMdWarning: string | undefined; + private isClosed = false; + + get closed(): boolean { + return this.isClosed; + } constructor(public readonly options: SessionOptions) { // Attach the per-session log sink up front so the constructor's @@ -316,6 +321,8 @@ export class Session { } async close(): Promise { + if (this.isClosed) return; + this.isClosed = true; try { await Promise.allSettled( Array.from(this.readyAgents(), async (agent) => agent.cron?.stop()), @@ -334,6 +341,8 @@ export class Session { } async closeForReload(): Promise { + if (this.isClosed) return; + this.isClosed = true; try { await Promise.allSettled( Array.from(this.readyAgents(), async (agent) => agent.cron?.stop()), From ee1921d135941d9a2f4472c7a99843f9d71057c2 Mon Sep 17 00:00:00 2001 From: qyz7438 <157498369+qyz7438@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:13:57 +0800 Subject: [PATCH 2/3] fixup! abort cleanly when resumed session disappears during startup Address review feedback: when applyStartupModesToResumedSession detects SESSION_NOT_FOUND, it now returns false instead of swallowing the error. - Startup path throws so init() fails instead of installing a dead session. - Session-picker path leaves the picker open so the user can choose again. --- apps/kimi-code/src/tui/kimi-tui.ts | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/apps/kimi-code/src/tui/kimi-tui.ts b/apps/kimi-code/src/tui/kimi-tui.ts index 856752aee..64aeae3f6 100644 --- a/apps/kimi-code/src/tui/kimi-tui.ts +++ b/apps/kimi-code/src/tui/kimi-tui.ts @@ -689,7 +689,13 @@ export class KimiTUI { session = await this.harness.createSession(createSessionOptions); } if (session !== undefined && shouldReplayHistory) { - await this.applyStartupModesToResumedSession(session); + const modesApplied = await this.applyStartupModesToResumedSession(session); + if (!modesApplied) { + throw new Error( + `Session "${session.id}" disappeared while applying startup modes. ` + + `Try running the command again, or start a fresh session.`, + ); + } if (startup.model !== undefined) { await session.setModel(startup.model); } @@ -1217,7 +1223,7 @@ export class KimiTUI { // session may already be in plan mode from its persisted records, and // re-entering plan mode throws, so only enable it when it is not active yet. // setPermission is idempotent and needs no such guard. - private async applyStartupModesToResumedSession(session: Session): Promise { + private async applyStartupModesToResumedSession(session: Session): Promise { const { startup } = this.options; try { if (startup.auto) { @@ -1231,6 +1237,7 @@ export class KimiTUI { await session.setPlanMode(true); } } + return true; } catch (error) { if (isKimiError(error) && error.code === ErrorCodes.SESSION_NOT_FOUND) { this.showError( @@ -1239,7 +1246,7 @@ export class KimiTUI { `(for example, an MCP server failed to start). ` + `Try running the command again, or start a fresh session.`, ); - return; + return false; } throw error; } @@ -2225,7 +2232,12 @@ export class KimiTUI { const switched = await this.resumeSession(session.id); if (!switched) return; if (applyStartupModes) { - await this.applyStartupModesToResumedSession(this.requireSession()); + const modesApplied = await this.applyStartupModesToResumedSession(this.requireSession()); + if (!modesApplied) { + // The resumed session disappeared while applying startup modes. + // Leave the picker open so the user can choose another session. + return; + } this.applyStartupPermissionAndPlanToAppState(); } this.hideSessionPicker(); From 5afd3dc58dd2b6c4838267fd02122cc3ad3c3b33 Mon Sep 17 00:00:00 2001 From: qyz7438 <157498369+qyz7438@users.noreply.github.com> Date: Fri, 26 Jun 2026 01:17:16 +0800 Subject: [PATCH 3/3] chore: add changeset for session-not-found fix --- .changeset/fix-session-not-found-on-resume.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 .changeset/fix-session-not-found-on-resume.md diff --git a/.changeset/fix-session-not-found-on-resume.md b/.changeset/fix-session-not-found-on-resume.md new file mode 100644 index 000000000..3916cada2 --- /dev/null +++ b/.changeset/fix-session-not-found-on-resume.md @@ -0,0 +1,8 @@ +--- +"@moonshot-ai/agent-core": patch +"@moonshot-ai/kimi-code": patch +--- + +Fix stale closed session handling during resume to prevent `[session.not_found]` errors after initialization failures. + +When a session was closed while initialization was still running (for example, because an MCP server failed to start), the session object could remain in memory while the persisted directory still existed. Resuming that session later then failed with `[session.not_found]`. The session map now drops stale closed sessions during resume, and the TUI aborts cleanly if the session disappears while applying startup modes.