Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): preserve fallback recovery across harness switches
xuzini-xzn900062a910c6
diff --git a/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts b/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.tsindex ef36de9c76..74f33c1a73 100644--- a/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts+++ b/apps/desktop/src/main/__tests__/sessionRuntimeFallbackIntent.test.ts@@ -1,6 +1,7 @@import { readFileSync } from 'node:fs';import { transpileModule, ScriptTarget } from 'typescript';import { describe, expect, it, vi } from 'vitest';+import { shouldPreserveRuntimeFallbackAutoResume } from '../maker-ipc/interruptedTurnAutoResume';import { createPendingAgentSwitchRegistry } from '../maker-ipc/sessionAgentSwitchHandler';const source = readFileSync(new URL('../maker-ipc/register.ts', import.meta.url), 'utf8');@@ -230,3 +231,63 @@ it.each(['device-b', 'share:one'])('applies a same-engine fallback at %s withoutexpect.objectContaining({ source: 'fallback', sessionLockHeld: true }));expect(h.failed).not.toHaveBeenCalled();});++// Execute the production close predicate: the old Session is a lease for one+// scheduled recovery attempt, even when the replacement uses another harness.+const preserveFallback = source.slice(+ source.indexOf('function shouldPreserveSessionRuntimeFallbackAutoResume('),+ source.indexOf('export function stopActiveGoalTurnForClear('),+);+const preserveFallbackJs = transpileModule(`${preserveFallback}\nreturn shouldPreserveSessionRuntimeFallbackAutoResume;`, {+ compilerOptions: { target: ScriptTarget.ES2022 },+}).outputText;++function closeHarness() {+ const session = { id: 'session' };+ const leases = new WeakMap<object, number>([[session, 7]]);+ const guard = vi.fn(() => true);+ const bookkeeping = vi.fn(() => true);+ const pending = vi.fn(() => true);+ const token = vi.fn(() => 7);+ const scheduled = vi.fn(() => true);+ const deps = {+ shouldPreserveRuntimeFallbackAutoResume,+ pendingSessionRuntimeFallbackRebuilds: leases,+ interruptedTurnAutoResumeGuard: { isCurrentAttempt: guard },+ autoResumeBookkeeping: { isCurrentAttempt: bookkeeping, hasLiveSchedule: scheduled },+ agentInputCoordinatorHolder: { isAutoResumePending: pending, getAutoResumeAttemptToken: token },+ };+ const preserve = new Function(...Object.keys(deps), preserveFallbackJs)(...Object.values(deps));+ return { session, leases, guard, bookkeeping, pending, token, scheduled, preserve };+}++describe('runtime fallback close handoff', () => {+ it.each(['requested', 'runtime-refresh', 'agent-switch'])('preserves the active attempt during %s', (reason) => {+ const h = closeHarness();+ expect(h.preserve(h.session, reason)).toBe(true);+ expect(h.guard).toHaveBeenCalledWith('session', 7);+ expect(h.bookkeeping).toHaveBeenCalledWith('session', 7);+ });++ it('does not transfer a lease to another Session with the same id', () => {+ const h = closeHarness();+ expect(h.preserve({ id: h.session.id }, 'agent-switch')).toBe(false);+ });++ it.each(['unexpected', 'deleted'])('does not preserve unrelated close reason %s', (reason) => {+ const h = closeHarness();+ expect(h.preserve(h.session, reason)).toBe(false);+ });++ it.each(['guard', 'bookkeeping', 'pending', 'scheduled'] as const)('does not revive recovery after %s was cleared', (field) => {+ const h = closeHarness();+ h[field].mockReturnValue(false);+ expect(h.preserve(h.session, 'agent-switch')).toBe(false);+ });++ it('does not preserve an attempt replaced by a newer input', () => {+ const h = closeHarness();+ h.token.mockReturnValue(8);+ expect(h.preserve(h.session, 'agent-switch')).toBe(false);+ });+});diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.tsindex 7d013093eb..6fc64d61f6 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botCandidateRecovery.test.ts@@ -58,6 +58,26 @@ describe('Bot candidate recovery', () => {}});+ it.each([undefined, 'unknown'])('recovers a text-only session limit with SDK tag %s', async (sdkError) => {+ const signals = { sdkError, message: "You've hit your session limit · resets 9:30pm (Asia/Shanghai)" };+ const ordinary = harness(false);+ expect(ordinary.isResumableTurnErrorCandidate(signals, ordinary.item)).toBe(false);+ const h = harness();+ 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).toHaveBeenCalledOnce();+ });++ it.each([+ { reason: 'user_denied' }, { reason: 'context_overflow' },+ { sdkError: 'invalid_request' },+ { message: "You've hit your session limit: budget_exceeded" },+ ])('preserves explicit failures despite session-limit text %j', (override) => {+ expect(isBotCandidateUnavailable({ message: "You've hit your session limit", ...override })).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' };diff --git a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.tsindex 31d0f29baa..c276b01cca 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/interruptedTurnAutoResume.test.ts@@ -17,7 +17,7 @@ describe('runtime fallback rebuild ownership', () => {it.each(['runtime-refresh', 'requested', 'unexpected', 'agent-switch', 'deleted'])('preserves the exact live retry only for its own rebuild: %s', closeReason => {const input = { closeReason, leasedAttemptToken: 1, guardIsCurrentAttempt: true,bookIsCurrentAttempt: true, coordinatorAttemptToken: 1, isAutoResumePending: true, hasLiveSchedule: true };- expect(shouldPreserveRuntimeFallbackAutoResume(input)).toBe(['runtime-refresh', 'requested'].includes(closeReason));+ expect(shouldPreserveRuntimeFallbackAutoResume(input)).toBe(['runtime-refresh', 'requested', 'agent-switch'].includes(closeReason));for (const stale of [{ leasedAttemptToken: undefined }, { guardIsCurrentAttempt: false },{ bookIsCurrentAttempt: false }, { coordinatorAttemptToken: 2 }, { isAutoResumePending: false }, { hasLiveSchedule: false }]) {expect(shouldPreserveRuntimeFallbackAutoResume({ ...input, ...stale })).toBe(false);diff --git a/apps/desktop/src/main/maker-ipc/botCandidateRecovery.ts b/apps/desktop/src/main/maker-ipc/botCandidateRecovery.tsindex 6b3462ebb7..34e022dd33 100644--- a/apps/desktop/src/main/maker-ipc/botCandidateRecovery.ts+++ b/apps/desktop/src/main/maker-ipc/botCandidateRecovery.ts@@ -24,7 +24,10 @@ export function isBotCandidateUnavailable(signals: InterruptedTurnErrorSignals):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)+ // Some Claude session-limit envelopes omit both HTTP status and SDK classification.+ // A known input/control error must not be reclassified from this text alone.+ const sessionLimit = (!tag || tag === 'unknown') && /\byou['’]ve hit your session limit\b/i.test(message);+ return sessionLimit || isNetworkishErrorMessage(message) || isOverloadErrorMessage(message, signals.errorStatus)|| /invalid api key|missing bearer token|no available oauth accounts|credit balance too low|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);}diff --git a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.tsindex 1e98a6d1f8..a6eff337f0 100644--- a/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts+++ b/apps/desktop/src/main/maker-ipc/interruptedTurnAutoResume.ts@@ -182,7 +182,7 @@ export function shouldPreserveWaitingContinuationOnlyAutoResume(input: {return input.hasLiveSchedule || input.hasQueuedAutoResume;}-/** Keep only the exact fallback callback across its requested runtime rebuild. */+/** Keep only the exact fallback callback across a runtime rebuild or cross-harness switch. */export function shouldPreserveRuntimeFallbackAutoResume(input: {closeReason: unknown;leasedAttemptToken: number | undefined;@@ -192,7 +192,7 @@ export function shouldPreserveRuntimeFallbackAutoResume(input: {isAutoResumePending: boolean;hasLiveSchedule: boolean;}): boolean {- return (input.closeReason === 'requested' || input.closeReason === 'runtime-refresh')+ return (input.closeReason === 'requested' || input.closeReason === 'runtime-refresh' || input.closeReason === 'agent-switch')&& input.leasedAttemptToken !== undefined&& input.guardIsCurrentAttempt && input.bookIsCurrentAttempt&& input.coordinatorAttemptToken === input.leasedAttemptTokendiff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex c97da5160b..522e3115c3 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -4389,7 +4389,7 @@ function shouldPreserveContinuationOnlyAutoResume(* Runtime fallback runs inside the already-fired retry callback. A route change* may synchronously close the old process before autoRetryLastError can reuse* its recovery record, so preserve only that exact callback token across the- * requested close/rebuild handoff.+ * requested close/rebuild or cross-harness agent-switch handoff.*/function shouldPreserveSessionRuntimeFallbackAutoResume(session: WiredSession,