Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
51 changes: 33 additions & 18 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 @@ -1217,16 +1219,29 @@ export class KimiTUI {
// setPermission is idempotent and needs no such guard.
private async applyStartupModesToResumedSession(session: Session): Promise<void> {
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;

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 Abort after the resumed session disappears

When setPermission, getStatus, or setPlanMode reports SESSION_NOT_FOUND, this handler only displays a message and then returns to its callers. The startup path still proceeds to setSession(session) and syncRuntimeState(session), so the same dead SDK session is installed and the next RPC fails again instead of cleanly aborting or starting over; the session-picker path likewise continues to hide the picker after a failed apply. This affects the exact stale/closed-session race this catch is trying to handle.

Useful? React with 👍 / 👎.

}
throw error;
}
}

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