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(providers): 切换 Claude 账号时重建凭证进程

Dashbb5c6ca6ac14
diff --git a/apps/desktop/src/main/maker-host/codex-credential-switch.ts b/apps/desktop/src/main/maker-host/codex-credential-switch.ts
index 70e9a4a83c..0458bc8b5e 100644
--- a/apps/desktop/src/main/maker-host/codex-credential-switch.ts
+++ b/apps/desktop/src/main/maker-host/codex-credential-switch.ts
@@ -1,4 +1,4 @@
-import { isOpenAiSubscriptionProvider } from '@cindy/model-providers';
+import { isOpenAiSubscriptionProvider, providerCatalogId } from '@cindy/model-providers';
import {
canReuseCodexHostForCredentialMode,
canReuseHostForCredentialMode,
@@ -304,14 +304,18 @@ export function shouldCloseSessionForCredentialSwitch(
model: input.nextModel,
});
- // Tool Search 是 Claude 子进程的 spawn-time env。跨越上游 capability 边界时即使
- // provider-oauth 凭证家族可复用,也必须重建本会话,不能把旧 flag 热切到新来源。
- if (
- input.agentKind === 'claude-code' &&
- claudeToolSearchMode(currentProviderId, currentMode, getActiveCatalog().providers.find(p => p.id === currentProviderId)?.auth.native) !==
- claudeToolSearchMode(nextProviderId, nextMode, getActiveCatalog().providers.find(p => p.id === nextProviderId)?.auth.native)
- ) {
- return true;
+ if (input.agentKind === 'claude-code') {
+ const providers = getActiveCatalog().providers;
+ const current = providers.find(provider => provider.id === currentProviderId);
+ const next = providers.find(provider => provider.id === nextProviderId);
+ // Native Claude tokens and account IDs are frozen in the spawn env. Equal
+ // credential families do not make two accounts interchangeable in a live process.
+ if (currentProviderId !== nextProviderId && [current, next].some(
+ provider => provider && providerCatalogId(provider) === 'anthropic',
+ )) return true;
+ // Tool Search is also spawn-time state, independent of the credential family.
+ if (claudeToolSearchMode(currentProviderId, currentMode, current?.auth.native) !==
+ claudeToolSearchMode(nextProviderId, nextMode, next?.auth.native)) return true;
}
// ── 远端压缩身份边界(codex, proxy-active)────────────────────────────────
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
index 4fddcacea9..c1ff05f99e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/runtimeSetModel.test.ts
@@ -4,6 +4,7 @@ import { setCustomProviders } from '../../maker-host/active-catalog.js';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { acceptSessionRuntimeMutation, getPendingSessionRuntimeMutation, clearSessionRuntimeControlState } from '../sessionRuntimeControl.js';
import { createPendingAgentSwitchRegistry } from '../sessionAgentSwitchHandler.js';
+import { PendingCredentialSwitchService } from '../pendingCredentialSwitch.js';
import { withSendToSessionLock } from '../sendToSessionLock.js';
import {
@@ -676,6 +677,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {
model: 'codex/gpt-5.5',
providerId: 'xd',
+ forceSessionRebuild: true,
});
expect(closeSession).not.toHaveBeenCalled();
expect(setModel).not.toHaveBeenCalled();
@@ -784,6 +786,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {
model: 'codex/gpt-5.5',
providerId: 'xd',
+ forceSessionRebuild: true,
});
expect(setModel).not.toHaveBeenCalled();
expect(getSessionProvider(sessionId)).toBe('openai');
@@ -991,6 +994,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {
model: 'gpt-5.5',
providerId: 'xd',
+ forceSessionRebuild: true,
});
expect(closeSession).not.toHaveBeenCalled();
// route 保持旧值:运行中的 turn 继续用原来源,pending 兑现时才写新值。
@@ -1097,6 +1101,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {
model: 'gpt-5.4',
providerId: 'xd',
+ forceSessionRebuild: true,
});
// route 保持旧值,等 pending 兑现。
expect(getSessionProvider(sessionId)).toBe('openai');
@@ -1324,6 +1329,7 @@ describe('applyRuntimeSetModelChange', () => {
expect(registerPendingCredentialSwitch).toHaveBeenCalledWith(sessionId, {
model: 'gpt-5.6-sol',
providerId: 'openai',
+ forceSessionRebuild: true,
});
expect(closeSession).not.toHaveBeenCalled();
expect(setModel).not.toHaveBeenCalled();
@@ -1695,6 +1701,75 @@ describe('context configuration refresh across live routes', () => {
});
});
+describe('Claude native account switching', () => {
+ it.each([
+ ['claude-a', 'claude-b'], ['claude-b', 'claude-a'],
+ ['anthropic', 'claude-a'], ['claude-a', 'anthropic'],
+ ['xd', 'claude-a'], ['claude-a', 'xd'],
+ ].flatMap(([from, to]) => ([false, true, 'race'] as const).map(busy => ({ from, to, busy }))))(
+ 'rebuilds $from to $to at the safe boundary (busy=$busy)', async ({ from, to, busy }) => {
+ const original = BUNDLED_CATALOG.providers.find(p => p.id === 'anthropic')!;
+ setCustomProviders(['claude-a', 'claude-b'].map(id => ({ ...original, id,
+ auth: { method: 'oauth' as const, native: 'claude' as const }, source: 'user' as const })));
+ const sessionId = rememberSession(`claude-accounts-${from}-${to}-${busy}`);
+ setSessionProvider(sessionId, from);
+ let running = busy !== false;
+ const isTurnRunning = vi.fn(() => running);
+ if (busy === 'race') isTurnRunning.mockReturnValueOnce(false);
+ const setModel = vi.fn(async () => {});
+ const cleanup = vi.fn(async () => {});
+ const closeSession = vi.fn(async (id: string) => {
+ expect(getSessionProvider(id)).toBe(from);
+ await rehydrateCloseSuppression.runOnCloseSideEffects(id, cleanup);
+ });
+ const maker: RuntimeSetModelMaker = {
+ getSession: () => ({ agentKind: 'claude-code', model: 'claude-opus-5', setModel }),
+ listActiveSessions: () => [
+ { id: sessionId, agentKind: 'claude-code', isTurnRunning },
+ { id: 'other-task', agentKind: 'claude-code', isTurnRunning: () => true },
+ ], closeSession,
+ };
+ const pending = new PendingCredentialSwitchService({ maker });
+ try {
+ const result = await applyRuntimeSetModelChange({ maker, sessionId, model: 'claude-opus-5', providerId: to,
+ registerPendingCredentialSwitch: (id, target) => pending.register(id, target) });
+ if (busy) {
+ expect(result.status).toBe('deferred');
+ expect(getSessionProvider(sessionId)).toBe(from);
+ expect(closeSession).not.toHaveBeenCalled();
+ await pending.onTurnSettled(sessionId);
+ expect(closeSession).not.toHaveBeenCalled();
+ running = false;
+ closeSession.mockRejectedValueOnce(new Error('process still alive'));
+ await pending.onTurnSettled(sessionId);
+ expect(getSessionProvider(sessionId)).toBe(from);
+ expect(pending.has(sessionId)).toBe(true);
+ await pending.onTurnSettled(sessionId);
+ expect(pending.has(sessionId)).toBe(false);
+ } else {
+ expect(result.status).toBe('applied');
+ }
+ expect(getSessionProvider(sessionId)).toBe(to);
+ expect(closeSession).toHaveBeenLastCalledWith(sessionId);
+ expect(setModel).not.toHaveBeenCalled();
+ expect(cleanup).not.toHaveBeenCalled();
+ } finally { pending.clear(sessionId); }
+ },
+ );
+ it('keeps the same native account process for model-only changes', async () => {
+ const original = BUNDLED_CATALOG.providers.find(p => p.id === 'anthropic')!;
+ setCustomProviders([{ ...original, id: 'claude-a', auth: { method: 'oauth', native: 'claude' }, source: 'user' }]);
+ const sessionId = rememberSession('claude-same-account');
+ setSessionProvider(sessionId, 'claude-a');
+ const setModel = vi.fn(async () => {}), closeSession = vi.fn(async () => {});
+ await applyRuntimeSetModelChange({ sessionId, model: 'claude-fable-5',
+ maker: { getSession: () => ({ agentKind: 'claude-code', model: 'claude-opus-5', setModel }),
+ listActiveSessions: () => [{ id: sessionId, agentKind: 'claude-code', isTurnRunning: () => true }], closeSession } });
+ expect(setModel).toHaveBeenCalled();
+ expect(closeSession).not.toHaveBeenCalled();
+ });
+});
+
describe('Pi native OpenAI account switching', () => {
it.each([
['openai', 'account-b'], ['account-b', 'openai'], ['account-b', 'account-c'],
diff --git a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
index 00aecd8664..1b8e4fcad8 100644
--- a/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
+++ b/apps/desktop/src/main/maker-ipc/runtimeSetModel.ts
@@ -266,10 +266,12 @@ export async function applyRuntimeSetModelChange(
if (sess && (shouldCloseSession || requiresCodexThreadRelink)) {
input.assertSessionCloseSupported?.();
if (isSelfBusy() && input.registerPendingCredentialSwitch) {
+ // A required credential rebuild must also survive close failure: keeping
+ // the old process alive cannot be treated as applying the new account.
await input.registerPendingCredentialSwitch(sessionId, {
model,
providerId: nextProviderId,
- ...((input.forceSessionRebuild || modelSwitchRequiresRebuild) ? { forceSessionRebuild: true } : {}),
+ ...(shouldCloseSession ? { forceSessionRebuild: true } : {}),
});
logger?.info('set-model: session rebuild deferred until turn end', {
sessionId,
@@ -319,7 +321,7 @@ export async function applyRuntimeSetModelChange(
input.registerPendingCredentialSwitch(sessionId, {
model,
providerId: nextProviderId,
- ...((input.forceSessionRebuild || modelSwitchRequiresRebuild) ? { forceSessionRebuild: true } : {}),
+ ...(shouldCloseSession ? { forceSessionRebuild: true } : {}),
});
logger?.info('set-model: credential switch deferred after busy race', {
sessionId,