Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 冷 Pi 切模核实失败时保留并记录原始恢复原因 (#5509)

FicoWang8e393cb2ba1d
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
index 66692ff03f..468872b8b9 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeControlWiring.test.ts
@@ -11,6 +11,14 @@ const registerSource = readFileSync(resolve(mainRoot, 'maker-ipc/register.ts'),
/\r\n?/g,
'\n',
);
+const coldPiRehydrationSource = readFileSync(
+ resolve(mainRoot, 'maker-ipc/coldPiRehydration.ts'),
+ 'utf8',
+);
+const coldPiRehydrationFailureSource = readFileSync(
+ resolve(mainRoot, 'maker-ipc/coldPiRehydrationFailure.ts'),
+ 'utf8',
+);
const runtimeControlSource = readFileSync(
resolve(mainRoot, 'maker-ipc/sessionRuntimeControl.ts'),
'utf8',
@@ -977,7 +985,7 @@ describe('session runtime control wiring', () => {
it('rehydrates a cold Pi runtime before model-window assessment', () => {
const rehydrate = handlerBody(
registerSource,
- 'async function rehydrateColdPiRuntimeForWindowVerification(',
+ 'const rehydrateColdPiRuntimeForWindowVerification = createColdPiRehydrationForWindowVerification({',
'const agentSwitchDeps:',
);
const rolloverWiring = handlerBody(
@@ -986,9 +994,12 @@ describe('session runtime control wiring', () => {
'const pendingCredentialSwitchService = new PendingCredentialSwitchService({',
);
- expect(rehydrate).toContain("row.agentKind !== 'pi'");
+ // The flow itself lives in coldPiRehydration.ts so its failure paths can be executed
+ // in unit tests (#5508); register.ts only wires DB, probe and bootstrap into it.
+ expect(coldPiRehydrationSource).toContain("row.agentKind !== 'pi'");
expect(rehydrate).toContain('resumeSessionId: row.sdkSessionId');
- expect(rehydrate).toContain('await bootstrapSession(createOpts)');
+ expect(rehydrate).toContain('bootstrapSession: (createOpts) => bootstrapSession(createOpts)');
+ expect(rehydrate).toContain('checkWorkDirExists(sessionId, workingDir, agentKind, remoteHostId)');
expect(rehydrate).not.toContain('.send(');
expect(rolloverWiring).toContain('rehydrateColdPiRuntimeForWindowVerification,');
@@ -1003,7 +1014,56 @@ describe('session runtime control wiring', () => {
const apply = setModel.indexOf('await applyRuntimeSetModelChange({');
expect(rehydrateCall).toBeGreaterThan(-1);
expect(rehydrateCall).toBeLessThan(apply);
- expect(setModel).toContain('Pi current runtime could not be verified');
+ // The user-facing message is assembled by the diagnostics helper (#5508); the
+ // established prefix still lives there so copy and remote clients keep matching.
+ expect(setModel).toContain('reportColdPiRehydrationFailure(');
+ expect(coldPiRehydrationFailureSource).toContain('Pi current runtime could not be verified');
+ });
+
+ it('surfaces why a cold Pi rehydration failed instead of swallowing the error (#5508)', () => {
+ // Every fail-closed branch carries a category (executed for real in
+ // coldPiRehydration.test.ts); probe/lookup/options/bootstrap stages keep their cause.
+ for (const category of ['session-row-missing', 'not-local-pi', 'native-session-missing', 'working-dir-missing']) {
+ expect(coldPiRehydrationSource).toMatch(new RegExp(`new ColdPiRehydrationError\\(\\s*'${category}'`));
+ }
+ for (const category of ['session-lookup-failed', 'working-dir-probe-failed', 'session-options-failed', 'bootstrap-failed']) {
+ expect(coldPiRehydrationSource).toMatch(new RegExp(`stage\\(\\s*'${category}'`));
+ }
+ expect(coldPiRehydrationSource).not.toContain('throw new Error(');
+ expect(coldPiRehydrationSource).toContain('{ cause: error }');
+
+ const setModel = handlerBody(
+ registerSource,
+ 'const handleSetModel = async (',
+ 'const recoverRemoteRuntimeAxisPersistence',
+ );
+ const rehydrateCall = setModel.indexOf('await rehydrateColdPiRuntimeForWindowVerification(sessionId)');
+ const catchBlock = setModel.slice(rehydrateCall, setModel.indexOf('rehydratedColdPiRuntime = liveSessionBeforeRouteChange;'));
+ expect(catchBlock).toContain('} catch (error) {');
+ expect(catchBlock).not.toContain('} catch {');
+ // Both the thrown failure and the "not live after bootstrap" case go through the one
+ // reporter, which logs the full reason and throws the IPC error with a safe detail.
+ expect(catchBlock.match(/reportColdPiRehydrationFailure\(/g)).toHaveLength(2);
+ expect(catchBlock).toContain("new ColdPiRehydrationError('runtime-not-live'");
+ expect(catchBlock).toContain('log,');
+ expect(catchBlock).toContain('throwIpcError,');
+ // The error code and fail-closed outcome are unchanged: still no route change on failure.
+ expect(catchBlock.match(/localModelWindowSwitchErrorCode\('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'\)/g)).toHaveLength(2);
+
+ // Raw reasons (which may carry local paths or stderr) stay in the main log; the IPC
+ // message only carries the category and the name/code-based detail.
+ const reporterStart = coldPiRehydrationFailureSource.indexOf('export function reportColdPiRehydrationFailure(');
+ expect(reporterStart).toBeGreaterThan(-1);
+ const reporter = coldPiRehydrationFailureSource.slice(reporterStart);
+ expect(reporter).toContain('reason: failure.reason');
+ expect(reporter).toContain('coldPiRehydrationFailureMessage(failure)');
+ const messageBuilder = handlerBody(
+ coldPiRehydrationFailureSource,
+ 'export function coldPiRehydrationFailureMessage(',
+ 'export interface ColdPiRehydrationFailureContext',
+ );
+ expect(messageBuilder).toContain('failure.detail');
+ expect(messageBuilder).not.toContain('failure.reason');
});
it('skips the cold Pi window rehydration when the live usage leaves the target headroom', () => {
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/coldPiRehydration.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/coldPiRehydration.test.ts
new file mode 100644
index 0000000000..01edb02fb8
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/coldPiRehydration.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createIpcError } from '../../../shared/ipc-errors';
+import {
+ createColdPiRehydrationForWindowVerification,
+ type ColdPiRehydrationDeps,
+} from '../coldPiRehydration';
+import {
+ ColdPiRehydrationError,
+ reportColdPiRehydrationFailure,
+} from '../coldPiRehydrationFailure';
+
+const LOCAL_PATH = '/Users/alice/Projects/secret-client/.worktrees/feature-x';
+
+interface Row {
+ agentKind: string;
+ remoteHostId: string | null;
+ sdkSessionId: string | null;
+ workingDir: string | null;
+ model: string;
+}
+
+interface Opts {
+ id: string;
+ agentKind: string;
+ workingDir?: string;
+ remoteHostId?: string | null;
+ resumeSessionId?: string;
+ extraDirs?: string[];
+}
+
+function errnoError(message: string, code: string): NodeJS.ErrnoException {
+ const error = new Error(message) as NodeJS.ErrnoException;
+ error.code = code;
+ return error;
+}
+
+const piRow: Row = {
+ agentKind: 'pi',
+ remoteHostId: null,
+ sdkSessionId: 'native-1',
+ workingDir: LOCAL_PATH,
+ model: 'pi-old',
+};
+
+function harness(overrides: Partial<ColdPiRehydrationDeps<Row, Opts>> = {}) {
+ const deps: ColdPiRehydrationDeps<Row, Opts> = {
+ hasLiveSession: vi.fn(() => false),
+ loadSessionRow: vi.fn(async () => piRow),
+ buildCreateOpts: vi.fn((sessionId, row) => ({
+ id: sessionId,
+ agentKind: 'pi',
+ workingDir: row.workingDir,
+ remoteHostId: null,
+ resumeSessionId: row.sdkSessionId,
+ })),
+ checkWorkDirExists: vi.fn(async () => true),
+ prepareCreateOpts: vi.fn(async (_sessionId, opts) => {
+ opts.extraDirs = ['/tmp/extra'];
+ }),
+ bootstrapSession: vi.fn(async () => ({ session: {} })),
+ ...overrides,
+ };
+ return { deps, rehydrate: createColdPiRehydrationForWindowVerification(deps) };
+}
+
+async function failure(run: Promise<unknown>): Promise<ColdPiRehydrationError> {
+ try {
+ await run;
+ } catch (error) {
+ expect(error).toBeInstanceOf(ColdPiRehydrationError);
+ return error as ColdPiRehydrationError;
+ }
+ throw new Error('expected the rehydration to fail');
+}
+
+describe('cold Pi rehydration for window verification (#5508)', () => {
+ it('does nothing when the runtime is already live', async () => {
+ const { deps, rehydrate } = harness({ hasLiveSession: vi.fn(() => true) });
+ await expect(rehydrate('s-1')).resolves.toBeUndefined();
+ expect(deps.loadSessionRow).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ });
+
+ it('bootstraps the persisted Pi session with the prepared create options', async () => {
+ const { deps, rehydrate } = harness();
+ await rehydrate('s-1');
+ expect(deps.checkWorkDirExists).toHaveBeenCalledWith('s-1', LOCAL_PATH, 'pi', null);
+ expect(deps.bootstrapSession).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 's-1', resumeSessionId: 'native-1', extraDirs: ['/tmp/extra'] }),
+ );
+ });
+
+ it.each([
+ ['session-row-missing', { loadSessionRow: vi.fn(async () => undefined) }],
+ ['not-local-pi', { loadSessionRow: vi.fn(async () => ({ ...piRow, agentKind: 'codex' })) }],
+ ['not-local-pi', { loadSessionRow: vi.fn(async () => ({ ...piRow, remoteHostId: 'host-1' })) }],
+ ['native-session-missing', { loadSessionRow: vi.fn(async () => ({ ...piRow, sdkSessionId: null })) }],
+ ['working-dir-missing', { loadSessionRow: vi.fn(async () => ({ ...piRow, workingDir: null })) }],
+ ['working-dir-missing', { checkWorkDirExists: vi.fn(async () => false) }],
+ ] as const)('fails closed with category %s', async (category, overrides) => {
+ const { deps, rehydrate } = harness(overrides as Partial<ColdPiRehydrationDeps<Row, Opts>>);
+ const error = await failure(rehydrate('s-1'));
+ expect(error.category).toBe(category);
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ });
+
+ it('classifies a working-directory probe timeout instead of reporting unknown', async () => {
+ const probeError = errnoError(`workdir probe timed out for ${LOCAL_PATH}`, 'WORKDIR_PROBE_TIMEOUT');
+ const { deps, rehydrate } = harness({ checkWorkDirExists: vi.fn(async () => { throw probeError; }) });
+ const error = await failure(rehydrate('s-1'));
+ expect(error.category).toBe('working-dir-probe-failed');
+ expect(error.cause).toBe(probeError);
+ expect(error.message).toContain(LOCAL_PATH);
+ expect(error.detail).toBe('Error WORKDIR_PROBE_TIMEOUT');
+ expect(deps.prepareCreateOpts).not.toHaveBeenCalled();
+ expect(deps.bootstrapSession).not.toHaveBeenCalled();
+ });
+
+ it('classifies a permission or I/O probe failure the same way', async () => {
+ const probeError = errnoError(`EACCES: permission denied, stat '${LOCAL_PATH}'`, 'EACCES');
+ const { rehydrate } = harness({ checkWorkDirExists: vi.fn(async () => { throw probeError; }) });
+ const error = await failure(rehydrate('s-1'));
+ expect(error.category).toBe('working-dir-probe-failed');
+ expect(error.detail).toBe('Error EACCES');
+ });
+
+ it('classifies session lookup and option preparation failures', async () => {
+ const dbError = new TypeError('database is closed');
+ const lookup = await failure(harness({ loadSessionRow: vi.fn(async () => { throw dbError; }) }).rehydrate('s-1'));
+ expect(lookup.category).toBe('session-lookup-failed');
+ expect(lookup.cause).toBe(dbError);
+ expect(lookup.detail).toBe('TypeError');
+
+ const optionsError = errnoError(`ENOENT: no such file, open '${LOCAL_PATH}/.orca.json'`, 'ENOENT');
+ const options = await failure(
+ harness({ prepareCreateOpts: vi.fn(async () => { throw optionsError; }) }).rehydrate('s-1'),
+ );
+ expect(options.category).toBe('session-options-failed');
+ expect(options.detail).toBe('Error ENOENT');
+ });
+
+ it('keeps the bootstrap cause and its original message for the log', async () => {
+ const bootstrapError = new Error(`pi exited with code 1\nstderr: cannot open ${LOCAL_PATH}/.pi/session`);
+ const { rehydrate } = harness({ bootstrapSession: vi.fn(async () => { throw bootstrapError; }) });
+ const error = await failure(rehydrate('s-1'));
+ expect(error.category).toBe('bootstrap-failed');
+ expect(error.cause).toBe(bootstrapError);
+ expect(error.message).toContain('pi exited with code 1');
+ expect(error.detail).toBe('Error');
+ });
+
+ it('end to end: a probe failure reaches the main log with its path but crosses IPC without it', async () => {
+ const probeError = errnoError(`EACCES: permission denied, stat '${LOCAL_PATH}'`, 'EACCES');
+ const { rehydrate } = harness({ checkWorkDirExists: vi.fn(async () => { throw probeError; }) });
+ const warn = vi.fn();
+ const throwIpcError = vi.fn((code, message) => {
+ throw createIpcError(code, message);
+ });
+
+ let thrown: unknown;
+ try {
+ await rehydrate('s-1');
+ } catch (error) {
+ try {
+ reportColdPiRehydrationFailure(
+ { log: { warn }, throwIpcError, errorCode: 'MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN' },
+ { sessionId: 's-1', fromModel: 'pi-old', toModel: 'pi-new', currentProviderId: null, nextProviderId: null },
+ error,
+ );
+ } catch (ipcError) {
+ thrown = ipcError;
+ }
+ }
+
+ expect(thrown).toBeInstanceOf(Error);
+ const ipcMessage = (thrown as Error).message;
+ expect(ipcMessage).toBe(
+ '[MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN] Pi current runtime could not be verified (working-dir-probe-failed: Error EACCES); runtime selection was not changed',
+ );
+ expect(ipcMessage).not.toContain(LOCAL_PATH);
+ expect((thrown as { code?: string }).code).toBe('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN');
+
+ const [, fields] = warn.mock.calls[0] as [string, Record<string, unknown>];
+ expect(fields.category).toBe('working-dir-probe-failed');
+ expect(fields.reason).toContain(LOCAL_PATH);
+ expect(fields.detail).toBe('Error EACCES');
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/coldPiRehydrationFailure.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/coldPiRehydrationFailure.test.ts
new file mode 100644
index 0000000000..84a2b0cb5a
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/coldPiRehydrationFailure.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it, vi } from 'vitest';
+import { createIpcError } from '../../../shared/ipc-errors';
+import {
+ COLD_PI_REHYDRATION_FAILURE_LOG_MESSAGE,
+ ColdPiRehydrationError,
+ coldPiRehydrationFailureMessage,
+ describeCauseForIpc,
+ describeColdPiRehydrationFailure,
+ redactLocalPaths,
+ reportColdPiRehydrationFailure,
+ sanitizeColdPiRehydrationReason,
+} from '../coldPiRehydrationFailure';
+
+const LOCAL_PATH = '/Users/alice/Projects/secret-client/.worktrees/feature-x';
+
+function errnoError(message: string, code: string): NodeJS.ErrnoException {
+ const error = new Error(message) as NodeJS.ErrnoException;
+ error.code = code;
+ return error;
+}
+
+describe('cold Pi rehydration failure diagnostics (#5508)', () => {
+ it('keeps the category and message of typed rehydration errors', () => {
+ const error = new ColdPiRehydrationError('working-dir-missing', 'working directory is missing for session s-1');
+ expect(describeColdPiRehydrationFailure(error)).toEqual({
+ category: 'working-dir-missing',
+ reason: 'working directory is missing for session s-1',
+ detail: 'working directory is missing for session s-1',
+ });
+ expect(error.name).toBe('ColdPiRehydrationError');
+ });
+
+ it('wraps causes without losing the original error, but never copies the cause message into the IPC detail', () => {
+ const cause = errnoError(`spawn pi ENOENT: ${LOCAL_PATH}/.pi/bin/pi\nstderr: provider unreachable`, 'ENOENT');
+ const error = new ColdPiRehydrationError('bootstrap-failed', `session s-1 bootstrap failed: ${cause.message}`, { cause });
+ expect(error.cause).toBe(cause);
+ const failure = describeColdPiRehydrationFailure(error);
+ expect(failure.category).toBe('bootstrap-failed');
+ // Full reason (main log only) keeps the path and stderr, flattened to one line.
+ expect(failure.reason).toContain(LOCAL_PATH);
+ expect(failure.reason).not.toContain('\n');
+ // IPC detail is name + code only.
+ expect(failure.detail).toBe('Error ENOENT');
+ });
+
+ it('classifies anything else as unknown while keeping the raw message out of the IPC detail', () => {
+ expect(describeColdPiRehydrationFailure(new TypeError('db is closed'))).toEqual({
+ category: 'unknown',
+ reason: 'db is closed',
+ detail: 'TypeError',
+ });
+ expect(describeColdPiRehydrationFailure('plain string')).toEqual({
+ category: 'unknown',
+ reason: 'plain string',
+ detail: 'non-error string',
+ });
+ expect(describeColdPiRehydrationFailure(undefined)).toEqual({
+ category: 'unknown',
+ reason: 'no error detail',
+ detail: 'no error detail',
+ });
+ expect(describeColdPiRehydrationFailure(errnoError(`EACCES: permission denied, stat '${LOCAL_PATH}'`, 'EACCES'))).toEqual({
+ category: 'unknown',
+ reason: `EACCES: permission denied, stat '${LOCAL_PATH}'`,
+ detail: 'Error EACCES',
+ });
+ });
+
+ it('describes causes for IPC by error name and code only', () => {
+ expect(describeCauseForIpc(errnoError(`stat '${LOCAL_PATH}' timed out`, 'WORKDIR_PROBE_TIMEOUT'))).toBe(
+ 'Error WORKDIR_PROBE_TIMEOUT',
+ );
+ expect(describeCauseForIpc(new RangeError(LOCAL_PATH))).toBe('RangeError');
+ expect(describeCauseForIpc(null)).toBe('no error detail');
+ expect(describeCauseForIpc({ message: LOCAL_PATH })).toBe('non-error object');
+ });
+
+ it('redacts POSIX, Windows and home-relative paths from any explicit detail', () => {
+ expect(redactLocalPaths(`cannot read ${LOCAL_PATH}/settings.json (EACCES)`)).toBe('cannot read <path> (EACCES)');
+ expect(redactLocalPaths('cannot read C:\\Users\\alice\\AppData\\Roaming\\Cindy\\x.json')).toBe('cannot read <path>');
+ expect(redactLocalPaths('cannot read ~/Library/Caches/Cindy/session.json')).toBe('cannot read <path>');
+ // Segments with spaces are only redacted up to the first space; detail never carries raw messages anyway.
+ expect(redactLocalPaths('cannot read ~/Library/Application Support/Cindy')).toBe('cannot read <path> Support/Cindy');
+ expect(new ColdPiRehydrationError('bootstrap-failed', 'x', { detail: `pi binary at ${LOCAL_PATH}/pi` }).detail).toBe(
+ 'pi binary at <path>',
+ );
+ expect(redactLocalPaths(' ')).toBe('no error detail');
+ });
+
+ it('bounds and flattens reasons so logs stay single-line', () => {
+ const long = `line one\n${'x'.repeat(600)}`;
+ const reason = sanitizeColdPiRehydrationReason(new Error(long));
+ expect(reason).not.toContain('\n');
+ expect(reason.length).toBe(240);
+ expect(reason.endsWith('…')).toBe(true);
+ expect(redactLocalPaths('y'.repeat(600)).length).toBe(120);
+ });
+
+ it('keeps the established message prefix so existing wiring and copy still match', () => {
+ const message = coldPiRehydrationFailureMessage({
+ category: 'session-row-missing',
+ reason: 'session s-1 has no database row',
+ detail: 'session s-1 has no database row',
+ });
+ expect(message).toBe(
+ 'Pi current runtime could not be verified (session-row-missing: session s-1 has no database row); runtime selection was not changed',
+ );
+ expect(message.startsWith('Pi current runtime could not be verified')).toBe(true);
+ });
+
+ it('reports the full reason to the main log and only the category + safe detail across IPC', () => {
+ const warn = vi.fn();
+ const throwIpcError = vi.fn((code, message) => {
+ throw createIpcError(code, message);
+ });
+ const cause = errnoError(`EACCES: permission denied, stat '${LOCAL_PATH}'`, 'EACCES');
+ const error = new ColdPiRehydrationError(
+ 'working-dir-probe-failed',
+ `working directory probe failed for session s-1: ${cause.message}`,
+ { cause },
+ );
+ const context = {
+ sessionId: 's-1',
+ fromModel: 'pi-old',
+ toModel: 'pi-new',
+ currentProviderId: 'anthropic',
+ nextProviderId: 'openai',
+ };
+
+ expect(() =>
+ reportColdPiRehydrationFailure(
+ { log: { warn }, throwIpcError, errorCode: 'MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN' },
+ context,
+ error,
+ ),
+ ).toThrowError(
+ '[MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN] Pi current runtime could not be verified (working-dir-probe-failed: Error EACCES); runtime selection was not changed',
+ );
+
+ expect(warn).toHaveBeenCalledTimes(1);
+ const [message, fields] = warn.mock.calls[0] as [string, Record<string, unknown>];
+ expect(message).toBe(COLD_PI_REHYDRATION_FAILURE_LOG_MESSAGE);
+ expect(fields).toMatchObject({
+ ...context,
+ category: 'working-dir-probe-failed',
+ detail: 'Error EACCES',
+ });
+ expect(fields.reason).toContain(LOCAL_PATH);
+
+ expect(throwIpcError).toHaveBeenCalledTimes(1);
+ const [code, ipcMessage] = throwIpcError.mock.calls[0] as [string, string];
+ expect(code).toBe('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN');
+ expect(ipcMessage).not.toContain(LOCAL_PATH);
+ expect(ipcMessage).not.toContain('permission denied');
+ });
+
+ it('uses the caller-supplied error code so device-link invokes keep their mapping', () => {
+ const throwIpcError = vi.fn((code, message) => {
+ throw createIpcError(code, message);
+ });
+ expect(() =>
+ reportColdPiRehydrationFailure(
+ { log: { warn: vi.fn() }, throwIpcError, errorCode: 'PRECONDITION_FAILED' },
+ { sessionId: 's-2', fromModel: null, toModel: 'pi-new', currentProviderId: null, nextProviderId: null },
+ new ColdPiRehydrationError('runtime-not-live', 'rehydrated Pi runtime is not live after bootstrap'),
+ ),
+ ).toThrowError(
+ '[PRECONDITION_FAILED] Pi current runtime could not be verified (runtime-not-live: rehydrated Pi runtime is not live after bootstrap); runtime selection was not changed',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/coldPiRehydration.ts b/apps/desktop/src/main/maker-ipc/coldPiRehydration.ts
new file mode 100644
index 0000000000..582053e300
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/coldPiRehydration.ts
@@ -0,0 +1,97 @@
+/**
+ * 冷 Pi 切模核实前的运行时恢复(#5508)。
+ *
+ * 从 register.ts 抽出来,只为了让每一条失败路径都能被真实执行到:会话行读取、
+ * 本地 Pi 判定、原生会话 ID、工作目录探测、Orca/extraDirs 选项合成、bootstrap,
+ * 每一步失败都抛带类别的 `ColdPiRehydrationError`;探测阶段的超时 / 权限错误不再
+ * 落到 `unknown`。所有分支仍 fail-closed:不会以缺失信息继续切模。
+ */
+
+import { ColdPiRehydrationError, type ColdPiRehydrationFailureCategory } from './coldPiRehydrationFailure.js';
+
+export interface ColdPiSessionRow {
+ agentKind: string;
+ remoteHostId: string | null;
+ sdkSessionId: string | null;
+ workingDir: string | null;
+}
+
+export type ColdPiResumableRow<Row extends ColdPiSessionRow> = Row & {
+ sdkSessionId: string;
+ workingDir: string;
+};
+
+export interface ColdPiRehydrationDeps<
+ Row extends ColdPiSessionRow,
+ Opts extends { workingDir?: string; agentKind: string; remoteHostId?: string | null },
+> {
+ hasLiveSession(sessionId: string): boolean;
+ loadSessionRow(sessionId: string): Promise<Row | undefined>;
+ buildCreateOpts(sessionId: string, row: ColdPiResumableRow<Row>): Opts;
+ checkWorkDirExists(
+ sessionId: string,
+ workingDir: Opts['workingDir'],
+ agentKind: Opts['agentKind'],
+ remoteHostId: Opts['remoteHostId'],
+ ): Promise<boolean>;
+ /** 合成 Orca vendor options 与 extraDirs;失败归为 session-options-failed。 */
+ prepareCreateOpts(sessionId: string, createOpts: Opts): Promise<void>;
+ bootstrapSession(createOpts: Opts): Promise<unknown>;
+}
+
+async function stage<T>(
+ category: ColdPiRehydrationFailureCategory,
+ describe: string,
+ run: () => Promise<T>,
+): Promise<T> {
+ try {
+ return await run();
+ } catch (error) {
+ if (error instanceof ColdPiRehydrationError) throw error;
+ const message = error instanceof Error ? error.message : String(error);
+ throw new ColdPiRehydrationError(category, `${describe}: ${message}`, { cause: error });
+ }
+}
+
+export function createColdPiRehydrationForWindowVerification<
+ Row extends ColdPiSessionRow,
+ Opts extends { workingDir?: string; agentKind: string; remoteHostId?: string | null },
+>(deps: ColdPiRehydrationDeps<Row, Opts>) {
+ return async function rehydrateColdPiRuntimeForWindowVerification(sessionId: string): Promise<void> {
+ if (deps.hasLiveSession(sessionId)) return;
+ const row = await stage('session-lookup-failed', `session ${sessionId} row lookup failed`, () =>
+ deps.loadSessionRow(sessionId),
+ );
+ // 失败分类只为诊断(#5508):每个分支仍 fail-closed,切模不会继续。
+ if (!row) {
+ throw new ColdPiRehydrationError('session-row-missing', `session ${sessionId} has no database row`);
+ }
+ if (row.agentKind !== 'pi' || row.remoteHostId) {
+ throw new ColdPiRehydrationError(
+ 'not-local-pi',
+ `session ${sessionId} is not a local Pi runtime (agentKind=${row.agentKind}${row.remoteHostId ? ', remote' : ''})`,
+ );
+ }
+ if (!row.sdkSessionId) {
+ throw new ColdPiRehydrationError('native-session-missing', `session ${sessionId} has no native Pi session to resume`);
+ }
+ if (!row.workingDir) {
+ throw new ColdPiRehydrationError('working-dir-missing', `session ${sessionId} has no working directory`);
+ }
+ const createOpts = deps.buildCreateOpts(sessionId, row as ColdPiResumableRow<Row>);
+ // 探测只把 ENOENT 视为「目录不存在」;超时、权限、I/O 错误会原样抛出,这里按
+ // 探测失败单独分类,并保留错误码供日志与 IPC 概述使用。
+ const workDirExists = await stage(
+ 'working-dir-probe-failed',
+ `working directory probe failed for session ${sessionId}`,
+ () => deps.checkWorkDirExists(sessionId, createOpts.workingDir, createOpts.agentKind, createOpts.remoteHostId),
+ );
+ if (!workDirExists) {
+ throw new ColdPiRehydrationError('working-dir-missing', `working directory is missing for session ${sessionId}`);
+ }
+ await stage('session-options-failed', `session ${sessionId} create options could not be prepared`, () =>
+ deps.prepareCreateOpts(sessionId, createOpts),
+ );
+ await stage('bootstrap-failed', `session ${sessionId} bootstrap failed`, () => deps.bootstrapSession(createOpts));
+ };
+}
diff --git a/apps/desktop/src/main/maker-ipc/coldPiRehydrationFailure.ts b/apps/desktop/src/main/maker-ipc/coldPiRehydrationFailure.ts
new file mode 100644
index 0000000000..2a41afa451
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/coldPiRehydrationFailure.ts
@@ -0,0 +1,160 @@
+/**
+ * 冷 Pi 切模前的运行时恢复失败原因(#5508)。
+ *
+ * `handleSetModel` 在冷 Pi 有原生会话 ID 时先恢复旧运行时核实当前窗口;恢复失败原本
+ * 被裸 `catch {}` 吞掉,只抛固定文案「Pi current runtime could not be verified」。
+ * 用户与日志都看不到是会话行缺失、工作目录不存在还是 bootstrap 失败,重试又会走同一条
+ * 失败路径,排查无从下手。
+ *
+ * 这里把失败分成两层:
+ * - `reason`:完整的单行原因(来自原始异常 message),只进 Main 日志;
+ * - `detail`:可跨 IPC 的概述,只含类别约定文案与错误名称/错误码,不带原始 message,
+ * 因此工作目录探测或 bootstrap 抛出的本机路径、stderr 不会进入渲染层。
+ * 错误码与用户可见文案不变,行为仍然 fail-closed、不改路由。
+ */
+
+import type { IpcErrorCode } from '../../shared/ipc-errors.js';
+
+export type ColdPiRehydrationFailureCategory =
+ | 'session-lookup-failed'
+ | 'session-row-missing'
+ | 'not-local-pi'
+ | 'native-session-missing'
+ | 'working-dir-missing'
+ | 'working-dir-probe-failed'
+ | 'session-options-failed'
+ | 'bootstrap-failed'
+ | 'runtime-not-live'
+ | 'unknown';
+
+export interface ColdPiRehydrationFailure {
+ category: ColdPiRehydrationFailureCategory;
+ /** 完整单行、有界的原因,只写 Main 日志。 */
+ reason: string;
+ /** 跨 IPC 的概述:类别约定文案或「错误名 错误码」,不含原始 message。 */
+ detail: string;
+}
+
+const REASON_MAX_LENGTH = 240;
+const DETAIL_MAX_LENGTH = 120;
+
+export class ColdPiRehydrationError extends Error {
+ /** 跨 IPC 的概述;未显式给出时按 `cause` 的错误名/错误码生成,不会回退到 message。 */
+ readonly detail: string;
+
+ constructor(
+ readonly category: ColdPiRehydrationFailureCategory,
+ message: string,
+ options?: { cause?: unknown; detail?: string },
+ ) {
+ super(message, options?.cause === undefined ? undefined : { cause: options.cause });
+ this.name = 'ColdPiRehydrationError';
+ this.detail = redactLocalPaths(
+ options?.detail ?? (options?.cause === undefined ? message : describeCauseForIpc(options.cause)),
+ );
+ }
+}
+
+/** 压成单行并截断:原因来自异常 message,可能含多行栈或超长路径。 */
+export function sanitizeColdPiRehydrationReason(raw: unknown): string {
+ const text = raw instanceof Error ? raw.message : typeof raw === 'string' ? raw : String(raw ?? '');
+ const singleLine = text.replace(/\s+/g, ' ').trim();
+ if (!singleLine) return 'no error detail';
+ return singleLine.length > REASON_MAX_LENGTH
+ ? `${singleLine.slice(0, REASON_MAX_LENGTH - 1)}…`
+ : singleLine;
+}
+
+/**
+ * 只取错误名与错误码(如 `Error EACCES`、`Error WORKDIR_PROBE_TIMEOUT`)。message
+ * 可能带本机路径、命令行或子进程 stderr,一律不进 IPC。
+ */
+export function describeCauseForIpc(cause: unknown): string {
+ if (cause instanceof Error) {
+ const code = (cause as { code?: unknown }).code;
+ const name = cause.name && cause.name !== 'Error' ? cause.name : 'Error';
+ return typeof code === 'string' && code ? `${name} ${code}` : name;
+ }
+ if (cause === null || cause === undefined) return 'no error detail';
+ return `non-error ${typeof cause}`;
+}
+
+/**
+ * 兜底脱敏:把 POSIX / Windows / `~` 开头的绝对路径替换为 `<path>`。类别约定文案本身不含
+ * 路径,这里只防未来有人把路径拼进 detail。
+ */
+export function redactLocalPaths(text: string): string {
+ const singleLine = text.replace(/\s+/g, ' ').trim();
+ // `~/…` 先于绝对路径处理,否则 `/Library/…` 会先被吃掉而留下 `~`。路径段含空格时
+ // 只能脱敏到第一个空格为止:detail 的来源是类别约定文案与错误码,这里只是兜底。
+ const redacted = singleLine
+ .replace(/~[\\/][^\s'"`<>|]*/g, '<path>')
+ .replace(/(?:[A-Za-z]:)?[\\/](?:[^\s'"`<>|]+[\\/])+[^\s'"`<>|]*/g, '<path>');
+ if (!redacted) return 'no error detail';
+ return redacted.length > DETAIL_MAX_LENGTH
+ ? `${redacted.slice(0, DETAIL_MAX_LENGTH - 1)}…`
+ : redacted;
+}
+
+export function describeColdPiRehydrationFailure(error: unknown): ColdPiRehydrationFailure {
+ if (error instanceof ColdPiRehydrationError) {
+ return {
+ category: error.category,
+ reason: sanitizeColdPiRehydrationReason(error),
+ detail: error.detail,
+ };
+ }
+ return {
+ category: 'unknown',
+ reason: sanitizeColdPiRehydrationReason(error),
+ detail: redactLocalPaths(describeCauseForIpc(error)),
+ };
+}
+
+/**
+ * 抛给渲染层的错误信息。保留原固定前缀(接线测试与既有文案依赖它),括号内只附失败
+ * 类别与 IPC 概述;渲染层按错误码映射用户文案,完整原因看 Main 日志。
+ */
+export function coldPiRehydrationFailureMessage(failure: ColdPiRehydrationFailure): string {
+ return `Pi current runtime could not be verified (${failure.category}: ${failure.detail}); runtime selection was not changed`;
+}
+
+export interface ColdPiRehydrationFailureContext {
+ sessionId: string;
+ fromModel: string | null;
+ toModel: string;
+ currentProviderId: string | null | undefined;
+ nextProviderId: string | null | undefined;
+}
+
+export interface ColdPiRehydrationFailureReporterDeps {
+ log: { warn(...args: unknown[]): void };
+ throwIpcError: (code: IpcErrorCode, message: string) => never;
+ errorCode: IpcErrorCode;
+}
+
+export const COLD_PI_REHYDRATION_FAILURE_LOG_MESSAGE =
+ 'set-model: cold Pi runtime rehydration failed; runtime selection unchanged';
+
+/**
+ * 冷 Pi 恢复失败的唯一出口:完整原因写 Main 日志,IPC 错误只带类别与脱敏概述。
+ * 错误码由调用方给出(设备链路下仍映射为 PRECONDITION_FAILED),fail-closed 不变。
+ */
+export function reportColdPiRehydrationFailure(
+ deps: ColdPiRehydrationFailureReporterDeps,
+ context: ColdPiRehydrationFailureContext,
+ error: unknown,
+): never {
+ const failure = describeColdPiRehydrationFailure(error);
+ deps.log.warn(COLD_PI_REHYDRATION_FAILURE_LOG_MESSAGE, {
+ sessionId: context.sessionId,
+ category: failure.category,
+ reason: failure.reason,
+ detail: failure.detail,
+ fromModel: context.fromModel,
+ toModel: context.toModel,
+ currentProviderId: context.currentProviderId,
+ nextProviderId: context.nextProviderId,
+ });
+ return deps.throwIpcError(deps.errorCode, coldPiRehydrationFailureMessage(failure));
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 0d45d58e13..47fa655621 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -432,6 +432,8 @@ import {
} from '../../shared/orca-worker-permission-mode.js';
import { t } from '../i18n.js';
import { createLogger } from '../logger.js';
+import { createColdPiRehydrationForWindowVerification } from './coldPiRehydration.js';
+import { ColdPiRehydrationError, reportColdPiRehydrationFailure } from './coldPiRehydrationFailure.js';
import {
desktopClaudeAuthAdapter,
desktopCodexAuthAdapter,
@@ -8706,50 +8708,42 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
}
- async function rehydrateColdPiRuntimeForWindowVerification(sessionId: string): Promise<void> {
- if (maker.getSession(sessionId)) return;
- const [row] = await getDbClient()
- .drizzle.select()
- .from(sessions)
- .where(eq(sessions.id, sessionId))
- .limit(1);
- if (
- !row ||
- row.agentKind !== 'pi' ||
- row.remoteHostId ||
- !row.sdkSessionId ||
- !row.workingDir
- ) {
- throw new Error(`session ${sessionId} cannot rehydrate a local Pi runtime for verification`);
- }
- const createOpts = buildCreateOptsWithStderr({
- id: sessionId,
- agentKind: 'pi',
- workingDir: row.workingDir,
- model: row.model,
- providerId: row.providerId,
- effort: (row.effort ?? undefined) as CreateOpts['effort'],
- fastMode: !!row.fastMode,
- permissionMode: (row.permissionMode ?? 'ask') as CreateOpts['permissionMode'],
- planMode: !!row.planModeEnabled,
- title: row.title ?? undefined,
- resumeSessionId: row.sdkSessionId,
- orcaRole: row.orcaRole ?? undefined,
- });
- const workDirExists = await checkWorkDirExists(
- sessionId,
- createOpts.workingDir,
- createOpts.agentKind,
- createOpts.remoteHostId,
- );
- if (!workDirExists) {
- throw new Error(`working directory is missing for session ${sessionId}`);
- }
- await synthesizeOrcaVendorOptionsFromDb(sessionId, createOpts);
- const extraDirs = await readSessionExtraDirsFromDb(sessionId);
- if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
- await bootstrapSession(createOpts);
- }
+ // 冷 Pi 切模核实前的运行时恢复(#5508):流程在 coldPiRehydration.ts 内,每条失败
+ // 路径都带类别;这里只接 DB、工作目录探测与 bootstrap。
+ const rehydrateColdPiRuntimeForWindowVerification = createColdPiRehydrationForWindowVerification({
+ hasLiveSession: (sessionId) => !!maker.getSession(sessionId),
+ loadSessionRow: async (sessionId) => {
+ const [row] = await getDbClient()
+ .drizzle.select()
+ .from(sessions)
+ .where(eq(sessions.id, sessionId))
+ .limit(1);
+ return row;
+ },
+ buildCreateOpts: (sessionId, row) =>
+ buildCreateOptsWithStderr({
+ id: sessionId,
+ agentKind: 'pi',
+ workingDir: row.workingDir,
+ model: row.model,
+ providerId: row.providerId,
+ effort: (row.effort ?? undefined) as CreateOpts['effort'],
+ fastMode: !!row.fastMode,
+ permissionMode: (row.permissionMode ?? 'ask') as CreateOpts['permissionMode'],
+ planMode: !!row.planModeEnabled,
+ title: row.title ?? undefined,
+ resumeSessionId: row.sdkSessionId,
+ orcaRole: row.orcaRole ?? undefined,
+ }),
+ checkWorkDirExists: (sessionId, workingDir, agentKind, remoteHostId) =>
+ checkWorkDirExists(sessionId, workingDir, agentKind, remoteHostId),
+ prepareCreateOpts: async (sessionId, createOpts) => {
+ await synthesizeOrcaVendorOptionsFromDb(sessionId, createOpts);
+ const extraDirs = await readSessionExtraDirsFromDb(sessionId);
+ if (extraDirs.length > 0) createOpts.extraDirs = extraDirs;
+ },
+ bootstrapSession: (createOpts) => bootstrapSession(createOpts),
+ });
const agentSwitchDeps: MakerSessionAgentSwitchHandlerDeps = {
withSessionLock: withSendToSessionLock,
@@ -18393,19 +18387,39 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
nextProviderId: targetRouteProviderId,
});
} else {
+ // 原始失败原因必须留下来(#5508):同一条冷路径每次重试都会再失败,
+ // 没有类别与原因就无法区分会话行缺失、工作目录丢失还是 bootstrap 失败。
+ // 完整原因只进 Main 日志;IPC 错误只带类别与脱敏概述,错误码与 fail-closed 不变。
+ const coldPiFailureContext = {
+ sessionId,
+ fromModel: currentRuntimeModel ?? null,
+ toModel: model,
+ currentProviderId,
+ nextProviderId: targetRouteProviderId,
+ };
try {
await rehydrateColdPiRuntimeForWindowVerification(sessionId);
- } catch {
- throwIpcError(
- localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),
- 'Pi current runtime could not be verified; runtime selection was not changed',
+ } catch (error) {
+ reportColdPiRehydrationFailure(
+ {
+ log,
+ throwIpcError,
+ errorCode: localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),
+ },
+ coldPiFailureContext,
+ error,
);
}
liveSessionBeforeRouteChange = maker.getSession(sessionId);
if (!liveSessionBeforeRouteChange) {
- throwIpcError(
- localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),
- 'Pi current runtime could not be verified; runtime selection was not changed',
+ reportColdPiRehydrationFailure(
+ {
+ log,
+ throwIpcError,
+ errorCode: localModelWindowSwitchErrorCode('MODEL_WINDOW_CURRENT_CONTEXT_UNKNOWN'),
+ },
+ coldPiFailureContext,
+ new ColdPiRehydrationError('runtime-not-live', 'rehydrated Pi runtime is not live after bootstrap'),
);
}
rehydratedColdPiRuntime = liveSessionBeforeRouteChange;