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. diff --git a/apps/kimi-code/src/tui/kimi-tui.ts b/apps/kimi-code/src/tui/kimi-tui.ts index 24a72043f..64aeae3f6 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'; @@ -687,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); } @@ -1215,18 +1223,32 @@ 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; - 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); + } + } + return 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 false; + } + throw error; } } @@ -2210,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(); 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()),