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): 修复伙伴候选链故障恢复触发 (#4916)

Dash78d819d9ae84
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts
index b71d4b5d3d..4aaacd1660 100644
--- a/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts
@@ -18,10 +18,16 @@ function harness() {
let generation = 0;
const current = { agentKind: 'codex', model: 'current', providerId: 'openai', effort: 'high', fastMode: false };
const candidate = { ...current, agentKind: 'claude-code', model: 'fallback' };
- const readCandidate = vi.fn(async () => ({ isBot: true, candidate }));
- const switchAgent = vi.fn(async () => ({ switched: true }));
+ const readCandidate = vi.fn(async (): Promise<{ isBot: boolean; candidate: typeof candidate | null }> => ({ isBot: true, candidate }));
+ const switchAgent = vi.fn(async () => ({ switched: true, engineReady: true }));
const accept = vi.fn();
const withLock = vi.fn(async (_id: string, task: () => Promise<unknown>) => task());
+ const apply = vi.fn(async (): Promise<{ deferred: boolean; superseded: boolean; generation?: number; contextWindowConfirmationRequired?: number }> => ({ deferred: false, superseded: false }));
+ const cancel = vi.fn(() => true);
+ const clearCredential = vi.fn();
+ const pendingCredential = vi.fn(() => ({ model: 'next', providerId: 'openai' }));
+ const failed = vi.fn(() => true);
+ const query = { from: () => query, where: () => query, limit: async () => [{ status: 'active' }] };
const deps = {
agentSwitchPending: pending,
sessionRuntimeGenerationMatches: (_id: string, expected?: number) => expected === undefined || expected === generation,
@@ -35,6 +41,16 @@ function harness() {
performSessionAgentSwitch: switchAgent,
agentSwitchDeps: {},
acceptSessionRuntimeMutation: accept,
+ applySessionRuntimeSelection: apply,
+ cancelPendingSessionRuntimeMutation: cancel,
+ getPendingCredentialSwitchTarget: pendingCredential,
+ clearPendingCredentialSwitchForSession: clearCredential,
+ broadcastSessionRuntimeProjection: vi.fn(async () => {}),
+ recordFailedSessionRuntimeFallbackCandidate: failed,
+ getDbClient: () => ({ drizzle: { select: () => query } }),
+ sessions: { status: 'status', id: 'id' }, eq: vi.fn(),
+ runtimeSelectionRequiresModelWindowConfirmation: (result: { contextWindowConfirmationRequired?: number }) => result.contextWindowConfirmationRequired !== undefined,
+ isRemoteModelSwitchRouteChangeError: () => false,
log: { info: vi.fn(), warn: vi.fn(), debug: vi.fn() },
};
const js = transpileModule(`${guard}\n${fallback}\nreturn { run: maybeApplySessionRuntimeFallback, allowed: canApplyAutomaticRuntimeSelection };`, {
@@ -45,10 +61,87 @@ function harness() {
pending.set('session', { sameAgentSelection: true, targetAgentKind: 'codex', model: 'chosen', providerId: 'xd' });
generation += 1;
};
- return { ...runtime, pending, pick, readCandidate, switchAgent, accept, withLock, generation: () => generation };
+ return { ...runtime, pending, pick, readCandidate, switchAgent, accept, withLock, apply, cancel, clearCredential, pendingCredential, failed, current, candidate, generation: () => generation };
}
describe('automatic runtime selection respects the user send boundary', () => {
+ it('stops after a committed harness switch whose engine failed to start', async () => {
+ const h = harness();
+ h.switchAgent.mockResolvedValue({ switched: true, engineReady: false });
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'failed' });
+ expect(h.accept).toHaveBeenCalledWith(expect.objectContaining({ profile: h.candidate }));
+ expect(h.readCandidate).toHaveBeenCalledOnce();
+ expect(h.failed).not.toHaveBeenCalled();
+ expect(h.apply).not.toHaveBeenCalled();
+ });
+
+ it('reports chain exhaustion distinctly from a switched runtime', async () => {
+ const h = harness();
+ h.readCandidate.mockResolvedValue({ isBot: true, candidate: null });
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'exhausted' });
+ expect(h.switchAgent).not.toHaveBeenCalled();
+ expect(h.apply).not.toHaveBeenCalled();
+ });
+
+ it('skips a failed candidate once and reaches the next configured route', async () => {
+ const h = harness();
+ const next = { ...h.candidate, model: 'next', providerId: 'other' };
+ h.readCandidate.mockResolvedValueOnce({ isBot: true, candidate: h.candidate })
+ .mockResolvedValue({ isBot: true, candidate: next });
+ h.switchAgent.mockRejectedValueOnce(new Error('Failed to start agent'));
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'switched' });
+ expect(h.failed).toHaveBeenCalledWith('session', 0, h.candidate);
+ expect(h.switchAgent).toHaveBeenCalledTimes(2);
+ expect(h.accept).toHaveBeenCalledWith(expect.objectContaining({ profile: next }));
+ expect(h.pending.get('session')).toBeUndefined();
+ });
+
+ it('returns a failed result when the last candidate cannot start', async () => {
+ const h = harness();
+ h.readCandidate.mockResolvedValueOnce({ isBot: true, candidate: h.candidate })
+ .mockResolvedValue({ isBot: true, candidate: null });
+ h.switchAgent.mockRejectedValue(new Error('Failed to start agent'));
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'failed' });
+ expect(h.switchAgent).toHaveBeenCalledOnce();
+ expect(h.pending.get('session')).toBeUndefined();
+ });
+
+ it('does not claim a superseded same-harness selection succeeded', async () => {
+ const h = harness();
+ h.readCandidate.mockResolvedValue({ isBot: true, candidate: { ...h.current, model: 'next' } });
+ h.apply.mockResolvedValue({ deferred: false, superseded: true });
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'superseded' });
+ expect(h.apply).toHaveBeenCalledWith('session', 'next', 'openai', expect.anything(),
+ expect.objectContaining({ source: 'fallback', sessionLockHeld: true }));
+ });
+
+ it('withdraws its own deferred fallback instead of sending through a pending route', async () => {
+ const h = harness();
+ h.readCandidate.mockResolvedValue({ isBot: true, candidate: { ...h.current, model: 'next' } });
+ h.apply.mockResolvedValue({ deferred: true, superseded: false, generation: 1 });
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'failed' });
+ expect(h.cancel).toHaveBeenCalledWith('session', 1);
+ expect(h.clearCredential).toHaveBeenCalledWith('session', { wake: false });
+ });
+
+ it('does not clear a newer credential intent when deferred fallback was superseded', async () => {
+ const h = harness();
+ h.readCandidate.mockResolvedValue({ isBot: true, candidate: { ...h.current, model: 'next' } });
+ h.apply.mockResolvedValue({ deferred: true, superseded: false, generation: 1 });
+ h.cancel.mockReturnValue(false);
+ expect(await h.run('session', 1, 1, true)).toMatchObject({ outcome: 'failed' });
+ expect(h.clearCredential).not.toHaveBeenCalled();
+ });
+
+ it('rechecks cancellation after the same-harness route lock is acquired', async () => {
+ const h = harness();
+ let current = true;
+ h.readCandidate.mockResolvedValue({ isBot: true, candidate: { ...h.current, model: 'next' } });
+ h.withLock.mockImplementationOnce(async (_id: string, run: () => Promise<unknown>) => { current = false; return run(); });
+ expect(await h.run('session', 1, 1, true, () => current)).toMatchObject({ outcome: 'superseded' });
+ expect(h.apply).not.toHaveBeenCalled();
+ });
+
it('rejects a new automatic request even when it read the generation after the user selected', async () => {
const h = harness();
h.pick();
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 298012e2ef..5bb7a1db9c 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -11133,6 +11133,30 @@ describe('AgentInputCoordinator 中断自动续跑', () => {
]);
});
+ it.each([false, true])('Pi 候选恢复沿用 durable progress 判定,hasProgress=%s', async (hasProgress) => {
+ const h = createHarness();
+ const sid = 'bot-pi-candidate-recovery';
+ const item = makeItem('q-pi', 'original request with possible side effects');
+ const info = { ...TAKEOVER_INFO, reason: 'pi-gateway-drop', error: 'Connection error.' };
+ h.setResumableTurnErrorTakeover(info);
+ h.setHasAssistantProgressAfter(async () => hasProgress);
+ h.isResumableTurnErrorCandidate.mockImplementation((signals, input) =>
+ signals.reason === 'pi-gateway-drop' && input?.clientId === item.clientId);
+ h.coordinator.enqueue(sid, item);
+ await flush();
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', info.error, { reason: info.reason });
+ await flush();
+ expect(h.isResumableTurnErrorCandidate).toHaveBeenCalledWith(
+ { message: info.error, reason: info.reason }, expect.objectContaining({ clientId: item.clientId }),
+ );
+ expect(latestProjection(h.projections).error).toBeNull();
+ expect(await h.coordinator.autoRetryLastError(sid, info.sessionTotal)).toBe('resumed');
+ await flush();
+ const sent = h.sendToAgent.mock.calls[1]?.[1];
+ expect(sent).toEqual({ type: 'user', content: hasProgress ? CONTINUE_AFTER_ERROR_PROMPT : item.text });
+ });
+
it('scheduler 来源复用同一套自动续跑并保留 run origin', async () => {
const h = createHarness();
const sid = 'resumable-error-scheduler';
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts
new file mode 100644
index 0000000000..467b58d344
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts
@@ -0,0 +1,149 @@
+import { readFileSync } from 'node:fs';
+import { ScriptTarget, transpileModule } from 'typescript';
+import { describe, expect, it, vi } from 'vitest';
+import { canResumeAfterRuntimeFallback, isBotCandidateUnavailable } from '../botCandidateRecovery';
+import { isInterruptedTurnError, isAcceptedTurnContinuationOnlyReason } from '../interruptedTurnAutoResume';
+
+const source = readFileSync(new URL('../register.ts', import.meta.url), 'utf8');
+
+/** Execute the production registration callbacks without starting Electron or touching accounts. */
+function harness(bot = true) {
+ const item = { clientId: 'input', createOpts: {} };
+ const hints = source.slice(source.indexOf(' const botFallbackInputs ='), source.indexOf(' const sendToAgentAccepted:'));
+ const callbacks = source.slice(source.indexOf(' isResumableTurnErrorCandidate: canRecoverTurn,'), source.indexOf(' steerToAgent: (sessionId, message, sendOpts) =>'));
+ let current = true;
+ let scheduled: (() => Promise<void>) | undefined;
+ const resume = vi.fn(async () => 'resumed');
+ const fallback = vi.fn(async () => ({ session: null, outcome: 'switched' }));
+ const finalize = vi.fn();
+ const guard = vi.fn(() => ({ action: 'resume', attempt: 1, maxAttempts: 5,
+ episodeAttempt: 1, maxEpisodeAttempts: 10, sessionTotal: 1, attemptToken: 1, delayMs: 1000 }));
+ const deps = {
+ isInterruptedTurnError, isBotCandidateUnavailable, canResumeAfterRuntimeFallback,
+ isAcceptedTurnContinuationOnlyReason,
+ inputCoordinator: { isExecutionPaused: () => false, autoRetryLastError: resume },
+ interruptedTurnAutoResumeGuard: { onInterruptedTurn: guard, noteResumeSendFailed: vi.fn() },
+ maybeApplySessionRuntimeFallback: fallback,
+ autoResumeBookkeeping: {
+ beginAttempt: vi.fn(), finalizeSuppressedError: finalize,
+ schedule: (_id: string, _token: number, _delay: number, run: (attempt: { isCurrent(): boolean }) => Promise<void>) => {
+ scheduled = () => run({ isCurrent: () => current });
+ },
+ },
+ saveTurnStartedAtForDeferred: vi.fn(), beginSchedulerAutoResume: vi.fn(),
+ pendingSessionRuntimeFallbackRebuilds: new WeakMap(),
+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ };
+ const js = transpileModule(`${hints}\nreturn { callbacks: { ${callbacks} }, botFallbackInputs };`, {
+ compilerOptions: { target: ScriptTarget.ES2022 },
+ }).outputText;
+ const runtime = new Function(...Object.keys(deps), js)(...Object.values(deps));
+ if (bot) runtime.botFallbackInputs.add(item.createOpts);
+ return { item, ...runtime.callbacks, resume, fallback, finalize, guard,
+ run: () => scheduled!(), cancel: () => { current = false; } };
+}
+
+describe('Bot candidate recovery', () => {
+ // Claude assistant envelopes may carry only a stable SDK tag, without an HTTP status.
+ it.each([
+ ['authentication_failed', true], ['rate_limit', true], ['server_error', true],
+ ['billing_error', true], ['invalid_request', false], ['max_output_tokens', false],
+ ['unknown', false],
+ ] as const)('classifies statusless Claude %s envelopes and preserves control reasons', (sdkError, unavailable) => {
+ for (const reason of [undefined, 'turn-failed']) {
+ expect(isBotCandidateUnavailable({ sdkError, reason, message: `SDK error: ${sdkError}` })).toBe(unavailable);
+ }
+ for (const reason of ['context_overflow', 'user_denied', 'tool_use_loop_detected']) {
+ expect(isBotCandidateUnavailable({ sdkError, reason, errorStatus: 503 })).toBe(false);
+ }
+ });
+
+ it.each(['switched', 'exhausted'])('routes a statusless server error through Bot fallback (%s)', async (outcome) => {
+ const h = harness();
+ const signals = { sdkError: 'server_error', message: 'Internal server error' };
+ h.fallback.mockResolvedValue({ session: null, outcome });
+ expect(h.isResumableTurnErrorCandidate(signals, h.item)).toBe(true);
+ expect(h.onResumableTurnError('s', signals, h.item)).not.toBeNull();
+ await h.run();
+ expect(h.fallback).toHaveBeenCalledWith('s', 1, 1, true, expect.any(Function));
+ expect(h.resume).toHaveBeenCalledTimes(outcome === 'switched' ? 1 : 0);
+ if (outcome === 'exhausted') expect(h.finalize).toHaveBeenCalledWith('s', 1, { surfaceBanner: true });
+ });
+
+ it.each([
+ { reason: 'pi-gateway-drop', message: 'Connection error.' },
+ { reason: 'user_model_access_denied', sdkError: 'user_model_access_denied', errorStatus: 403 },
+ { sdkError: 'user_model_access_denied' },
+ { errorStatus: 403, message: 'Permission denied' },
+ { reason: 'turn-failed', errorStatus: 403, message: 'Permission denied' },
+ { errorStatus: 401 }, { errorStatus: 402 }, { errorStatus: 429 }, { errorStatus: 503 },
+ { sdkError: 'authentication_failed' }, { sdkError: 'billing_error' },
+ { message: 'model deepseek does not exist' }, { message: 'Failed to start agent' },
+ { message: 'Selected model is at capacity. Please try a different model.' },
+ ])('allows a different candidate for %j', (signals) => {
+ expect(isBotCandidateUnavailable(signals)).toBe(true);
+ });
+
+ it.each([
+ { reason: 'tool_use_loop_detected', message: 'Connection error.' },
+ { reason: 'context_overflow', errorStatus: 503 },
+ { reason: 'user_denied', errorStatus: 403, message: 'Permission denied' },
+ { message: 'Permission denied' },
+ { message: 'User rejected permission', errorStatus: 403 },
+ { message: 'Approval required', errorStatus: 403 },
+ { message: 'User rejected permission' }, { message: 'Tool business failure' },
+ { sdkError: 'invalid_request', message: 'prompt too long' },
+ { message: 'invalid encrypted content' }, { message: 'thread not found' },
+ ])('does not reinterpret control or input failures %j', (signals) => {
+ expect(isBotCandidateUnavailable(signals)).toBe(false);
+ });
+
+ const drop = { reason: 'pi-gateway-drop', message: 'Connection error.' };
+ it('takes over an exhausted Pi route only for a host-identified Bot input', async () => {
+ const ordinary = harness(false);
+ expect(ordinary.isResumableTurnErrorCandidate(drop, ordinary.item)).toBe(false);
+ expect(ordinary.onResumableTurnError('s', drop, ordinary.item)).toBeNull();
+ expect(ordinary.guard).not.toHaveBeenCalled();
+ const bot = harness();
+ expect(bot.isResumableTurnErrorCandidate(drop, bot.item)).toBe(true);
+ expect(bot.onResumableTurnError('s', drop, bot.item)).not.toBeNull();
+ expect(bot.resume).not.toHaveBeenCalled();
+ await bot.run();
+ expect(bot.fallback).toHaveBeenCalledWith('s', 1, 1, true, expect.any(Function));
+ expect(bot.resume).toHaveBeenCalledWith('s', 1);
+ });
+
+ it.each(['exhausted', 'failed', 'unchanged', 'superseded'])('returns the error without resending when fallback is %s', async (outcome) => {
+ const h = harness();
+ h.fallback.mockResolvedValue({ session: null, outcome });
+ h.onResumableTurnError('s', drop, h.item);
+ await h.run();
+ expect(h.resume).not.toHaveBeenCalled();
+ expect(h.finalize).toHaveBeenCalledWith('s', 1, { surfaceBanner: true });
+ });
+
+ it('retains ordinary network auto-resume without requiring a route change', async () => {
+ const h = harness(false);
+ h.fallback.mockResolvedValue({ session: null, outcome: 'unchanged' });
+ h.onResumableTurnError('s', { message: 'Connection error.' }, h.item);
+ await h.run();
+ expect(h.fallback).toHaveBeenCalledWith('s', 1, 1, false, expect.any(Function));
+ expect(h.resume).toHaveBeenCalledOnce();
+ });
+
+ it('does not revive recovery after Stop or a newer user turn', async () => {
+ const h = harness();
+ h.fallback.mockImplementation(async () => { h.cancel(); return { session: null, outcome: 'switched' }; });
+ h.onResumableTurnError('s', drop, h.item);
+ await h.run();
+ expect(h.resume).not.toHaveBeenCalled();
+ expect(h.finalize).not.toHaveBeenCalled();
+ });
+
+ it('does not bypass the existing episode budget', () => {
+ const h = harness();
+ h.guard.mockReturnValue({ action: 'stop' } as ReturnType<typeof h.guard>);
+ expect(h.onResumableTurnError('s', drop, h.item)).toBeNull();
+ expect(h.fallback).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index 5eff967dca..f2385b8c20 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -393,7 +393,10 @@ export interface AgentInputCoordinatorDeps {
* 但**红横幅与 error 行落库都发生在决策之前**。用这个判定把那两件事先按住,
* 决策落定后再放行(见 `isAutoResumeDeferred`)。
*/
- isResumableTurnErrorCandidate?: (signals: InterruptedTurnErrorSignals) => boolean;
+ isResumableTurnErrorCandidate?: (
+ signals: InterruptedTurnErrorSignals,
+ item?: AgentInputQueuedMessage | null,
+ ) => boolean;
/**
* 一条被 `isAutoResumeDeferred` 按住的 error 最终**没能走到决策**(用户气泡持久化失败等),
* host 必须把压住的 error 行补落,否则那次中断在历史里彻底消失(不变量 I2)。
@@ -3434,7 +3437,7 @@ export class AgentInputCoordinator {
state.activeTurn = null;
state.stickyError = null;
const schedulerItem = active.item && isSchedulerOriginItem(active.item);
- const resumableCandidate = this.isResumableTurnErrorCandidate(sessionId, message, signals);
+ const resumableCandidate = this.isResumableTurnErrorCandidate(sessionId, message, signals, active.item);
const outcome = this.setActiveTurnRecovery(state, active.item, {
allowSchedulerAutoResume: Boolean(schedulerItem && resumableCandidate),
});
@@ -3495,7 +3498,7 @@ export class AgentInputCoordinator {
// 所以先用纯判定问一句「这条有可能被接管吗」:有可能就**先不设 error** —— 否则接管
// 成功时用户已经先看过一帧红横幅,违反「接管态为真时 error 必为 null」(不变量 I1,
// greptile P1)。判定为假(认证失效、协议错等确定性失败)时照旧立刻呈现,不受影响。
- const resumableCandidate = this.isResumableTurnErrorCandidate(sessionId, message, signals);
+ const resumableCandidate = this.isResumableTurnErrorCandidate(sessionId, message, signals, active.item);
recordPendingTerminalEvent(active, {
type: 'error',
message,
@@ -5966,10 +5969,14 @@ export class AgentInputCoordinator {
sessionId: string,
message?: string,
signals?: Omit<InterruptedTurnErrorSignals, 'message'>,
+ item?: AgentInputQueuedMessage | null,
): boolean {
if (!this.deps.isResumableTurnErrorCandidate) return false;
try {
- return this.deps.isResumableTurnErrorCandidate({ ...(signals ?? {}), message }) === true;
+ return this.deps.isResumableTurnErrorCandidate(
+ { ...(signals ?? {}), message },
+ item,
+ ) === true;
} catch (err) {
log.warn('isResumableTurnErrorCandidate failed', { sessionId, error: errorMessage(err) });
return false;
diff --git a/apps/desktop/src/main/maker-ipc/botCandidateRecovery.ts b/apps/desktop/src/main/maker-ipc/botCandidateRecovery.ts
new file mode 100644
index 0000000000..4db3ce09d1
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/botCandidateRecovery.ts
@@ -0,0 +1,36 @@
+import { isNetworkishErrorMessage, isOverloadErrorMessage } from '@cindy/maker-core';
+import type { InterruptedTurnErrorSignals } from './interruptedTurnAutoResume.js';
+
+/** A failed provider may be replaced, even when retrying that provider is forbidden. */
+export function isBotCandidateUnavailable(signals: InterruptedTurnErrorSignals): boolean {
+ const reason = signals.reason ?? '';
+ // Explicit product/control failures must never be reinterpreted from their text.
+ if (reason && ![
+ 'pi-gateway-drop', 'upstream-overload', 'empty-response', 'turn-failed',
+ 'provider_auth_or_access', 'provider_quota_limit', 'provider_rate_limit',
+ 'provider_server_error', 'model_unavailable', 'user_model_access_denied', 'agent-start-failed',
+ ].includes(reason)) return false;
+ if (reason && reason !== 'turn-failed') return true;
+ const tag = signals.sdkError ?? '';
+ if (['authentication_failed', 'authentication_error', 'rate_limit', 'server_error', 'billing_error',
+ 'model_not_found', 'user_model_access_denied', 'agent_start_failed'].includes(tag)) return true;
+ const message = signals.message ?? '';
+ if (/user (?:denied|rejected)|approval (?:denied|required)|context.{0,20}(?:overflow|too long)|prompt too long/i.test(message)) return false;
+ if ([401, 402, 403, 429, 500, 502, 503, 504, 529].includes(signals.errorStatus ?? 0)) return true;
+ if (/permission denied/i.test(message)) return false;
+ return isNetworkishErrorMessage(message) || isOverloadErrorMessage(message, signals.errorStatus)
+ || /invalid api key|missing bearer token|no available oauth accounts|credit balance too low|insufficient_quota|quota exceeded|rate.limit exceeded|model.{0,80}(?:not found|does not exist|unavailable)|(?:failed to (?:start|spawn)|could not start) (?:the )?(?:agent|pi|codex|claude)/i.test(message);
+}
+
+/** The Session reference is only a teardown lease, never proof that a route changed. */
+export interface RuntimeFallbackResult<T> {
+ session: T | null;
+ outcome: 'unchanged' | 'switched' | 'exhausted' | 'failed' | 'superseded';
+}
+
+export function canResumeAfterRuntimeFallback(
+ requireRouteChange: boolean,
+ result: RuntimeFallbackResult<unknown>,
+): boolean {
+ return result.outcome !== 'superseded' && (!requireRouteChange || result.outcome === 'switched');
+}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 75de0fae5f..ab4fab2287 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1117,6 +1117,11 @@ import {
type InterruptedTurnErrorSignals,
} from './interruptedTurnAutoResume.js';
import { readInterruptedTurnAutoResumeSettings } from '../maker-host/interrupted-turn-auto-resume-store.js';
+import {
+ isBotCandidateUnavailable,
+ canResumeAfterRuntimeFallback,
+ type RuntimeFallbackResult,
+} from './botCandidateRecovery.js';
import {
broadcastGhostMessageBlocked,
@@ -11571,25 +11576,29 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
sessionId: string,
episodeAttempt: number,
attemptToken: number,
- ): Promise<Session | null> => {
+ requireRouteChange = false,
+ isCurrent: () => boolean = () => true,
+ ): Promise<RuntimeFallbackResult<Session>> => {
const runtimeOwnerEpoch = captureSessionRuntimeControlOwnerEpoch();
let runtimeSession: Session | null = null;
let blockAutoResumeForModelWindowConfirmation = false;
try {
const profiles = await readSessionRuntimeProfiles(sessionId);
- if (!profiles) return null;
+ if (!profiles || !isCurrent()) return { session: null, outcome: 'superseded' };
// A previously accepted Agent/fallback mutation owns the next boundary.
// Do not let a later infrastructure retry replace that pending intent.
if (profiles.control.pending ||
- !canApplyAutomaticRuntimeSelection(sessionId, profiles.control.generation)) return null;
+ !canApplyAutomaticRuntimeSelection(sessionId, profiles.control.generation)) return { session: null, outcome: 'superseded' };
// Bot routes are explicit and ordered. They switch on the first recoverable
// failure and never depend on the generic Session fallback toggle/catalog
// guesser. Ordinary Sessions keep their existing second-attempt behavior.
const botFallback = await readBotFallbackCandidate(sessionId, profiles.effective);
+ if (!isCurrent()) return { session: null, outcome: 'superseded' };
let currentForFallback = profiles.effective;
let candidate = botFallback.candidate;
if (!botFallback.isBot) {
- if (episodeAttempt < 2 || !readSessionRuntimeFallbackSettings().enabled) return null;
+ if (requireRouteChange) return { session: null, outcome: 'exhausted' };
+ if (episodeAttempt < 2 || !readSessionRuntimeFallbackSettings().enabled) return { session: null, outcome: 'unchanged' };
const providers = await getDesktopProviderService().listProviders({
allowSideEffects: false,
catalog: getActiveCatalog(),
@@ -11614,7 +11623,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
maxHops: 2,
});
}
- if (!candidate) return null;
+ if (!candidate) return { session: null, outcome: 'exhausted' };
runtimeSession = maker.getSession(sessionId) ?? null;
if (runtimeSession) {
pendingSessionRuntimeFallbackRebuilds.set(runtimeSession, attemptToken);
@@ -11626,6 +11635,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
try {
await withSendToSessionLock(sessionId, async () => {
if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch)) return;
+ if (!isCurrent()) return;
const [runtimeStatus] = await getDbClient()
.drizzle.select({ status: sessions.status })
.from(sessions)
@@ -11662,25 +11672,42 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// this one recovery boundary instead of retrying the broken primary and
// waiting for another user-visible failure before trying route N+1.
while (candidate) {
+ if (!isCurrent()) return { session: runtimeSession, outcome: 'superseded' };
const selected = candidate;
- const applyCandidate = () =>
- applySessionRuntimeSelection(
+ const applyCandidate = () => withSendToSessionLock(sessionId, async () => {
+ if (!isCurrent() || !sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch) ||
+ !canApplyAutomaticRuntimeSelection(sessionId, profiles.control.generation)) {
+ return { deferred: false, superseded: true };
+ }
+ const result = await applySessionRuntimeSelection(
sessionId,
selected.model,
selected.providerId,
{ effort: selected.effort, fastMode: selected.fastMode },
{
source: 'fallback',
+ sessionLockHeld: true,
expectedGeneration: profiles.control.generation,
previousProfile: currentForFallback,
effortExplicit: false,
fastExplicit: false,
},
);
+ if (requireRouteChange && result.deferred && result.generation !== undefined &&
+ cancelPendingSessionRuntimeMutation(sessionId, result.generation)) {
+ const pendingCredential = getPendingCredentialSwitchTarget(sessionId);
+ if (pendingCredential?.model === selected.model &&
+ pendingCredential.providerId === selected.providerId) {
+ clearPendingCredentialSwitchForSession(sessionId, { wake: false });
+ }
+ await broadcastSessionRuntimeProjection(sessionId);
+ }
+ return result;
+ });
if (selected.agentKind !== currentForFallback.agentKind) {
try {
const result = await withSendToSessionLock(sessionId, async () => {
- if (!sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch) ||
+ if (!isCurrent() || !sessionRuntimeControlOwnerEpochMatches(runtimeOwnerEpoch) ||
!canApplyAutomaticRuntimeSelection(sessionId, profiles.control.generation)) return null;
const switched = await performSessionAgentSwitch(agentSwitchDeps, {
sessionId,
@@ -11702,11 +11729,15 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
}
return switched;
});
- if (!result) return runtimeSession;
+ if (!result) return { session: runtimeSession, outcome: 'superseded' };
if (!result.switched) {
if (await advanceConfiguredBotRoute(selected)) continue;
- return runtimeSession;
+ return { session: runtimeSession, outcome: 'exhausted' };
}
+ // The route transaction has already committed, including a new
+ // generation. Its failed bootstrap must not resume input or advance
+ // candidates using the pre-switch profile/generation captured above.
+ if (!result.engineReady) return { session: runtimeSession, outcome: 'failed' };
} catch (error) {
if (await advanceConfiguredBotRoute(selected)) continue;
throw error;
@@ -11719,7 +11750,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
toProviderId: selected.providerId,
toModel: selected.model,
});
- return runtimeSession;
+ return { session: runtimeSession, outcome: 'switched' };
}
let result: Awaited<ReturnType<typeof applySessionRuntimeSelection>>;
try {
@@ -11761,6 +11792,10 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
'automatic model-window confirmation is unsupported; runtime selection was not changed',
);
}
+ if (result.deferred && requireRouteChange) {
+ // The automatic intent was withdrawn inside the route lock above.
+ return { session: runtimeSession, outcome: 'failed' };
+ }
log.info('automatic session runtime fallback evaluated', {
sessionId,
episodeAttempt,
@@ -11771,9 +11806,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
toModel: selected.model,
applied: !result.superseded,
});
- return runtimeSession;
+ return { session: runtimeSession, outcome: result.superseded ? 'superseded' : 'switched' };
}
- return runtimeSession;
+ return { session: runtimeSession, outcome: 'exhausted' };
} catch (error) {
log.warn('automatic session runtime fallback skipped after switch failure', {
sessionId,
@@ -11787,7 +11822,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
if (runtimeSession) pendingSessionRuntimeFallbackRebuilds.delete(runtimeSession);
throw error;
}
- return runtimeSession;
+ return { session: runtimeSession, outcome: 'failed' };
}
};
@@ -12576,6 +12611,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
log,
});
+ // Host-only hints belong to the dispatched input, not a persistent session cache.
+ // The fallback transaction still rechecks the authoritative Bot link and chain.
+ const botFallbackInputs = new WeakSet<object>();
+ const canRecoverTurn = (signals: InterruptedTurnErrorSignals, item?: AgentInputQueuedMessage | null) =>
+ isInterruptedTurnError(signals) ||
+ (!!item && botFallbackInputs.has(item.createOpts) && isBotCandidateUnavailable(signals));
+
const sendToAgentAccepted: typeof sendToAgentAcceptedUnlocked = async (...args) => {
const [sessionId] = args;
if (typeof sessionId !== 'string') return await sendToAgentAcceptedUnlocked(...args);
@@ -12603,6 +12645,13 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
.where(eq(sessions.id, sessionId))
.limit(1);
const blocked = botSessionInputBlockReason(botInput ?? null);
+ if (args[2] && typeof args[2] === 'object') {
+ if (botInput?.source === 'bot' && ['canonical', 'delegation'].includes(botInput.role ?? '')) {
+ botFallbackInputs.add(args[2]);
+ } else {
+ botFallbackInputs.delete(args[2]);
+ }
+ }
if (botInput?.source === CINDY_MAKE_SESSION_SOURCE && (args[3] as Record<PropertyKey, unknown> | undefined)?.[CINDY_MAKE_TASK_DISPATCH] !== true) {
await assertCindyMakeTaskReady(sessionId);
}
@@ -13658,8 +13707,7 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
// 纯判定,无副作用:coordinator 用它在「决策还做不了」的时序里先把红横幅与 error 行
// 按住(见 isAutoResumeDeferred)。与下面 onResumableTurnError 的第一道门是同一个函数,
// 两处必须同判据 —— 否则会出现"按住了却永远不接管"或"没按住却接管"的错配。
- isResumableTurnErrorCandidate: (signals: InterruptedTurnErrorSignals) =>
- isInterruptedTurnError(signals),
+ isResumableTurnErrorCandidate: canRecoverTurn,
// 被按住的 error 最终没接管 → 只补落 error 行(横幅 coordinator 自己设)。
onResumableTurnErrorDiscarded: (
sessionId: string,
@@ -13676,7 +13724,8 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
signals: InterruptedTurnErrorSignals,
item: AgentInputQueuedMessage,
) => {
- if (!isInterruptedTurnError(signals) || inputCoordinator.isExecutionPaused(sessionId)) return null;
+ if (!canRecoverTurn(signals, item) || inputCoordinator.isExecutionPaused(sessionId)) return null;
+ const requireRouteChange = botFallbackInputs.has(item.createOpts) && isBotCandidateUnavailable(signals);
const erroredAt = Date.now();
const decision = interruptedTurnAutoResumeGuard.onInterruptedTurn(sessionId, erroredAt);
if (decision.action !== 'resume') {
@@ -13733,11 +13782,22 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
return (async () => {
let fallbackRebuildSession: Session | null = null;
try {
- fallbackRebuildSession = await maybeApplySessionRuntimeFallback(
+ const fallback = await maybeApplySessionRuntimeFallback(
sessionId,
decision.episodeAttempt,
decision.attemptToken,
+ requireRouteChange,
+ () => attempt.isCurrent() && !inputCoordinator.isExecutionPaused(sessionId),
);
+ fallbackRebuildSession = fallback.session;
+ if (!attempt.isCurrent()) return;
+ if (!canResumeAfterRuntimeFallback(requireRouteChange, fallback)) {
+ interruptedTurnAutoResumeGuard.noteResumeSendFailed(sessionId, decision.attemptToken);
+ autoResumeBookkeeping.finalizeSuppressedError(sessionId, decision.attemptToken, {
+ surfaceBanner: true,
+ });
+ return;
+ }
// 退避窗口内用户可能已经自己发了消息 / 清了会话。判据是 coordinator 的 recovery
// 与**接管态**(enqueue / clearError / teardown 会清掉接管态,recovery 未必),
// autoRetryLastError 内部复核后会 no-op 并返回非 resumed —— 此时必须回滚
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index c4e5e5a105..ba86538473 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -123,6 +123,12 @@ harness + provider + model + effort + fastMode
- 第一项是首选;首次主任务启动和确定性重建从第一项开始尝试。
- 只有连接、鉴权、配额、容量、模型不可用和启动失败等“候选不可用”错误才进入下一项。
+- 候选不可用与原路由自动续跑分开判定;Pi 原生重连耗尽(`pi-gateway-drop`)仍可切到伙伴候选链。
+ 已落库失败回合只有在切换成功后才自动发送:有持久产出时只续跑,确认零产出才重发原文。
+ 候选耗尽、切换失败或需要换窗确认时交还错误,不继续重试失效路由;复用现有恢复额度和退避,
+ 不覆盖用户的新选择。实现与回归见 `maker-ipc/botCandidateRecovery.ts`、
+ `maker-ipc/__tests__/botCandidateRecovery.test.ts` 和 `sessionRuntimeFallbackIntent.test.ts`。
+ 跨 harness 路由已提交但新引擎启动失败时停止自动恢复并显示错误;不使用提交前的路由代次继续推进候选。
- 用户拒绝授权、工具业务失败、参数错误和已经产生副作用后的失败不得触发透明重放。
- 同一轮最多按生效候选链各尝试一次;不得循环。用户显式配置的链不得追加目录候选。
- 同 harness 可在安全边界切模型;跨 harness 必须走既有 agent-switch / 交接重建事务。