Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/fix-session-not-found-on-resume.md
Original file line number Diff line number Diff line change
@@ -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.
69 changes: 48 additions & 21 deletions apps/kimi-code/src/tui/kimi-tui.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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<void> {
private async applyStartupModesToResumedSession(session: Session): Promise<boolean> {
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;
}
}

Expand Down Expand Up @@ -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();
Expand Down
18 changes: 17 additions & 1 deletion packages/agent-core/src/rpc/core-impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,7 +374,14 @@ export class KimiCore implements PromisableMethods<CoreAPI> {
...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));
Expand Down Expand Up @@ -954,6 +961,15 @@ export class KimiCore implements PromisableMethods<CoreAPI> {
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;
}

Expand Down
9 changes: 9 additions & 0 deletions packages/agent-core/src/session/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -316,6 +321,8 @@ export class Session {
}

async close(): Promise<void> {
if (this.isClosed) return;
this.isClosed = true;
try {
await Promise.allSettled(
Array.from(this.readyAgents(), async (agent) => agent.cron?.stop()),
Expand All @@ -334,6 +341,8 @@ export class Session {
}

async closeForReload(): Promise<void> {
if (this.isClosed) return;
this.isClosed = true;
try {
await Promise.allSettled(
Array.from(this.readyAgents(), async (agent) => agent.cron?.stop()),
Expand Down