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): 换绑订阅账号时清理旧模型快照

Dashc3ca46cba54e
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index a1fd0150e7..d0b7d6d6ba 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1,7 +1,6 @@
import { codexAccountState } from './maker-host/codex-account-auth.js';
import { syncSubscriptionAccountUsage } from './usage/subscriptionAccountUsage.js';
-import { setSubscriptionAccountInvalidatedHandler } from './maker-host/subscription-account-auth.js';
-import { setXaiDiscoveredModels } from './maker-host/active-catalog.js';
+import { clearSubscriptionAccountDiscoveredModels, setSubscriptionAccountInvalidatedHandler } from './maker-host/subscription-account-auth.js';
import { startWorktreeRecycleMaintenance, stopWorktreeRecycleMaintenance, auditRegisteredWorktrees } from './worktree/recycleMaintenance';
import { requestWorktreeRecycle } from './worktree/managedRecycle';
import { recycleSessionWorktreeForStatusChange } from './localDb/ipc/sessions';
@@ -4894,7 +4893,7 @@ const registerIpcHandlers = () => {
});
setXaiAuthInvalidatedHandler((providerId) => {
if (providerId !== 'xai') {
- setXaiDiscoveredModels(null, providerId);
+ void clearSubscriptionAccountDiscoveredModels(providerId);
void syncSubscriptionAccountUsage(providerId).then(broadcastXaiAuthStateChanged, broadcastXaiAuthStateChanged);
return;
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts
index 93d1765fea..44c5f191a8 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeAutoCompactWiring.test.ts
@@ -16,6 +16,11 @@ const state = vi.hoisted(() => ({
capToolchainThreads: true,
}));
+// Account discovery persistence is outside this runtime/route fixture.
+vi.mock('../model-discovery/xai.js', () => ({
+ discardXaiModelsDiskCache: vi.fn(async () => {}),
+}));
+
vi.mock('../agent-resource-settings-store.js', () => ({
readAgentResourceSettings: () => ({ capToolchainThreads: state.capToolchainThreads, processPriority: 'normal' }),
}));
diff --git a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
index 6826da60b6..9d22aa5e0b 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piNativeProviders.test.ts
@@ -9,6 +9,11 @@ import path from 'node:path';
import { BUNDLED_CATALOG, type Catalog } from '@cindy/model-providers';
+// Account discovery persistence is outside this runtime/route fixture.
+vi.mock('../model-discovery/xai.js', () => ({
+ discardXaiModelsDiskCache: vi.fn(async () => {}),
+}));
+
vi.mock('../grok-oauth-login.js', () => ({
hasGrokOAuthLogin: () => true,
}));
diff --git a/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts b/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts
index 4f8cec36cc..953e022ab4 100644
--- a/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/piRosterAssembly.test.ts
@@ -12,6 +12,11 @@ const state = vi.hoisted(() => ({
userDataPath: '',
}));
+// Account discovery persistence is outside this runtime/route fixture.
+vi.mock('../model-discovery/xai.js', () => ({
+ discardXaiModelsDiskCache: vi.fn(async () => {}),
+}));
+
vi.mock('electron', () => ({
app: {
getPath: () => state.userDataPath,
diff --git a/apps/desktop/src/main/maker-host/__tests__/remoteClaudeRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/remoteClaudeRoute.test.ts
index a2fc86e832..8971653946 100644
--- a/apps/desktop/src/main/maker-host/__tests__/remoteClaudeRoute.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/remoteClaudeRoute.test.ts
@@ -11,6 +11,11 @@ const resolveProviderRouteDecision = vi.fn<(...args: unknown[]) => Promise<unkno
const gatewayDefaultRouteDecision = vi.fn<(...args: unknown[]) => unknown>();
const isProviderRouteMutationInProgress = vi.fn<(...args: unknown[]) => boolean>(() => false);
+// Account discovery persistence is outside this runtime/route fixture.
+vi.mock('../model-discovery/xai.js', () => ({
+ discardXaiModelsDiskCache: vi.fn(async () => {}),
+}));
+
vi.mock('../auth-adapters.js', () => ({ readClaudeApiKey: () => readClaudeApiKey() }));
vi.mock('../claude-oauth-refresh.js', () => ({
getClaudeAiOAuthForSpawn: () => getClaudeAiOAuthForSpawn(),
diff --git a/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts b/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts
index 8ed6af4200..1b7ba329bb 100644
--- a/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/subscription-account-auth.test.ts
@@ -1,5 +1,14 @@
-import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import fsp from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { BUNDLED_CATALOG, buildUserProvider } from '@cindy/model-providers';
+import { getActiveCatalog, setActiveCatalog, clearDiscoveredProviderModels } from '../active-catalog.js';
+import { refreshSubscriptionAccountModels } from '../subscription-account-models.js';
+import { waitForXaiDiscoveryIdleForTest } from '../model-discovery/xai.js';
const state = vi.hoisted(() => ({
+ directory: '',
+ fetch: vi.fn(),
scope: 'owner-a:1',
pending: false,
secrets: new Map<string, string>(),
@@ -8,16 +17,12 @@ const state = vi.hoisted(() => ({
revokeDuringRefresh: false,
callbacks: [] as Array<() => void>,
}));
-vi.mock('electron', () => ({ app: { getPath: () => '/tmp/cindy-scoped-auth-test' } }));
+vi.mock('electron', () => ({ app: { getPath: () => state.directory } }));
vi.mock('../../appSessionState.js', () => ({
activeOwnerScopeKey: () => state.scope,
+ ownerScopedUserDataPath: (...parts: string[]) => path.join(state.directory, state.scope.replaceAll(':', '_'), ...parts),
isAppSessionBoundaryPending: () => state.pending,
}));
-vi.mock('../active-catalog.js', () => ({
- getActiveCatalog: () => ({
- providers: ['claude-a', 'claude-b'].map((id) => ({ id, auth: { native: 'claude' } })),
- }),
-}));
vi.mock('../../secrets/providerSecretStore.js', () => ({
genericOAuthSecretIo: {
read: (id: string) => state.secrets.get(`${state.scope}:${id}`) ?? null,
@@ -55,14 +60,16 @@ vi.mock('../claude-oauth-login.js', () => ({
cancelClaudeOAuthLogin: vi.fn(),
}));
vi.mock('../grok-oauth-login.js', () => ({
- runGrokOAuthLogin: vi.fn(),
+ runGrokOAuthLogin: (...args: unknown[]) => state.login(...args),
+ getGrokAccessToken: async (id: string) => JSON.parse(state.secrets.get(`${state.scope}:${id}`) ?? 'null')?.access_token,
+ peekGrokAccessToken: (id: string) => JSON.parse(state.secrets.get(`${state.scope}:${id}`) ?? 'null')?.access_token ?? null,
cancelGrokOAuthLogin: vi.fn(),
- hasGrokOAuthLogin: vi.fn(),
+ hasGrokOAuthLogin: (id: string) => state.secrets.has(`${state.scope}:${id}`),
grokAccountIdentity: vi.fn(),
- logoutGrok: vi.fn(),
+ logoutGrok: (id: string) => { state.secrets.delete(`${state.scope}:${id}`); },
resetGrokOAuthMemoryCache: vi.fn(),
}));
-vi.mock('../outbound-fetch.js', () => ({ outboundFetch: vi.fn() }));
+vi.mock('../outbound-fetch.js', () => ({ outboundFetch: (...args: unknown[]) => state.fetch(...args) }));
import {
loginSubscriptionAccount,
readClaudeAccountOAuth,
@@ -74,7 +81,7 @@ import {
subscriptionAccountState,
} from '../subscription-account-auth.js';
-describe('independent Claude account credentials', () => {
+describe('independent subscription account credentials', () => {
it.each(['result', 'throw'])('restores the previous account if login fails after persistence (%s)', async failure => {
state.secrets.set(`${state.scope}:claude-a`, JSON.stringify({ accessToken: 'fake-original' }));
state.login.mockImplementation(async opts => {
@@ -86,7 +93,15 @@ describe('independent Claude account credentials', () => {
else expect((await loginSubscriptionAccount('claude-a', () => true)).ok).toBe(false);
expect(readClaudeAccountOAuth('claude-a')?.accessToken).toBe('fake-original');
});
- beforeEach(() => {
+ beforeEach(async () => {
+ state.directory = await fsp.mkdtemp(path.join(os.tmpdir(), 'cindy-account-discovery-'));
+ clearDiscoveredProviderModels();
+ setActiveCatalog({ ...BUNDLED_CATALOG, providers: [...BUNDLED_CATALOG.providers,
+ ...['claude-a', 'claude-b', 'grok-a', 'grok-b'].map(id => buildUserProvider({
+ id, name: id, auth: { method: 'oauth', native: id.startsWith('claude') ? 'claude' : 'xai' }, runtimes: {},
+ })),
+ ] });
+ state.fetch.mockReset();
resetSubscriptionAccountCaches();
state.scope = 'owner-a:1';
state.pending = false;
@@ -101,11 +116,16 @@ describe('independent Claude account credentials', () => {
state.secrets.set(`${state.scope}:claude-a`, JSON.stringify({ accessToken: 'fake-a' }));
state.secrets.set(`${state.scope}:claude-b`, JSON.stringify({ accessToken: 'fake-b' }));
await getValidClaudeAccountOAuth('claude-a');
+ respondModels('claude-account-only-old');
+ await refreshSubscriptionAccountModels('claude-a');
+ await refreshSubscriptionAccountModels('claude-b');
const broadcast = vi.fn();
setSubscriptionAccountInvalidatedHandler(broadcast);
state.removeFails = removeFails;
state.callbacks[0]();
expect(broadcast).toHaveBeenCalledWith('claude-a');
+ expect(discoveredIds('claude-a').some(m => m.includes('account-only-old'))).toBe(false);
+ expect(discoveredIds('claude-b').some(m => m.includes('account-only-old'))).toBe(true);
expect(subscriptionAccountState('claude-a').authenticated).toBe(false);
expect(await getValidClaudeAccountOAuth('claude-a')).toBeNull();
expect(readClaudeAccountOAuth('claude-b')?.accessToken).toBe('fake-b');
@@ -167,6 +187,69 @@ describe('independent Claude account credentials', () => {
expect((await loginSubscriptionAccount('claude-a', () => true)).ok).toBe(false);
expect(state.secrets.size).toBe(0);
});
+ it.each(['claude', 'grok'])('%s reports failed credential restoration when cancelled during catalog cleanup', async kind => {
+ const id = `${kind}-a`;
+ let checks = 0;
+ state.login.mockImplementation(async opts => {
+ opts.persist({ accessToken: 'fake-uncommitted', access_token: 'fake-uncommitted' });
+ state.removeFails = true;
+ return { ok: true };
+ });
+ // persist and pre-cleanup checks succeed; cancellation arrives at the post-cleanup check.
+ await expect(loginSubscriptionAccount(id, () => ++checks < 3)).rejects.toThrow('Failed to restore credentials');
+ });
+ afterEach(async () => {
+ await waitForXaiDiscoveryIdleForTest();
+ clearDiscoveredProviderModels();
+ setActiveCatalog(BUNDLED_CATALOG);
+ await fsp.rm(state.directory, { recursive: true, force: true });
+ });
+ it.each(['claude', 'grok'])('%s reconnect failure cannot reuse the previous account models', async kind => {
+ const id = `${kind}-a`, peer = `${kind}-b`;
+ putToken(id, 'fake-old'); putToken(peer, 'fake-peer');
+ respondModels('claude-account-only-old');
+ expect(await refreshSubscriptionAccountModels(id)).toBe(true);
+ expect(await refreshSubscriptionAccountModels(peer)).toBe(true);
+ expect(discoveredIds(id).some(m => m.includes('account-only-old'))).toBe(true);
+ // Start another old-account request before replacing its credentials.
+ let release!: (value: Response) => void;
+ state.fetch.mockImplementation(() => new Promise<Response>(resolve => { release = resolve; }));
+ const stale = refreshSubscriptionAccountModels(id);
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ state.login.mockImplementation(async opts => {
+ opts.persist({ accessToken: 'fake-new', access_token: 'fake-new' }); return { ok: true };
+ });
+ expect((await loginSubscriptionAccount(id, () => true)).ok).toBe(true);
+ state.fetch.mockRejectedValue(new Error('offline'));
+ await refreshSubscriptionAccountModels(id).catch(() => false);
+ release(new Response(JSON.stringify({ userId: 'fake-user', data: [{ id: 'claude-late-old', display_name: 'Late old', type: 'model' }] })));
+ await stale;
+ expect(discoveredIds(id).some(m => /account-only-old|late-old/.test(m))).toBe(false);
+ expect(discoveredIds(peer).some(m => m.includes('account-only-old'))).toBe(true);
+ if (kind === 'grok') {
+ await expect(fsp.stat(path.join(state.directory, state.scope.replaceAll(':', '_'), 'model-discovery', `${id}-models.json`))).rejects.toMatchObject({ code: 'ENOENT' });
+ await expect(fsp.stat(path.join(state.directory, state.scope.replaceAll(':', '_'), 'model-discovery', `${peer}-models.json`))).resolves.toBeDefined();
+ }
+ });
+ it.each(['claude', 'grok'])('%s removal and credential rollback clear only that connection discovery', async kind => {
+ const id = `${kind}-a`, peer = `${kind}-b`;
+ putToken(id, 'fake-old'); putToken(peer, 'fake-peer');
+ respondModels('claude-account-only-old');
+ await refreshSubscriptionAccountModels(id); await refreshSubscriptionAccountModels(peer);
+ const restore = removeSubscriptionAccountCredentialsReversibly(id);
+ expect(discoveredIds(id).some(m => m.includes('account-only-old'))).toBe(false);
+ expect(restore()).toBe(true);
+ state.login.mockImplementation(async opts => {
+ opts.persist({ accessToken: 'fake-new', access_token: 'fake-new' }); return { ok: true };
+ });
+ const login = await loginSubscriptionAccount(id, () => true);
+ respondModels('claude-account-only-new'); await refreshSubscriptionAccountModels(id);
+ expect(discoveredIds(id).some(m => m.includes('account-only-new'))).toBe(true);
+ expect(login.rollbackCredentials?.()).toBe(true);
+ await waitForXaiDiscoveryIdleForTest();
+ expect(discoveredIds(id).some(m => m.includes('account-only-new'))).toBe(false);
+ expect(discoveredIds(peer).some(m => m.includes('account-only-old'))).toBe(true);
+ });
it('credential removal is reversible and cannot replace a newer login', async () => {
state.secrets.set('owner-a:1:claude-a', JSON.stringify({ accessToken: 'fake-a' }));
const restore = removeSubscriptionAccountCredentialsReversibly('claude-a');
@@ -178,3 +261,9 @@ describe('independent Claude account credentials', () => {
expect(readClaudeAccountOAuth('claude-a')?.accessToken).toBe('fake-new');
});
});
+
+const discoveredIds = (id: string) => Object.values(getActiveCatalog().providers.find(p => p.id === id)!.models).flat().map(m => m.id);
+const putToken = (id: string, token: string) => state.secrets.set(`${state.scope}:${id}`, JSON.stringify({ accessToken: token, access_token: token }));
+const respondModels = (model: string) => state.fetch.mockImplementation(async (url: string) => new Response(JSON.stringify(
+ url.includes('/user?') ? { userId: 'fake-user' } : { data: [{ id: model, model, display_name: model, type: 'model' }] },
+)));
diff --git a/apps/desktop/src/main/maker-host/subscription-account-auth.ts b/apps/desktop/src/main/maker-host/subscription-account-auth.ts
index ee778a709b..2e05d3db4e 100644
--- a/apps/desktop/src/main/maker-host/subscription-account-auth.ts
+++ b/apps/desktop/src/main/maker-host/subscription-account-auth.ts
@@ -1,9 +1,10 @@
import { app } from 'electron';
import path from 'node:path';
import { createHash } from 'node:crypto';
-import { activeOwnerScopeKey, isAppSessionBoundaryPending } from '../appSessionState.js';
+import { activeOwnerScopeKey, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
import { genericOAuthSecretIo } from '../secrets/providerSecretStore.js';
-import { getActiveCatalog } from './active-catalog.js';
+import { getActiveCatalog, setDiscoveredProviderModels, setXaiDiscoveredModels } from './active-catalog.js';
+import { discardXaiModelsDiskCache } from './model-discovery/xai.js';
import { createClaudeOAuthRefresher, type GetValidOAuthOptions } from './claude-oauth-refresh.js';
import { type ClaudeAiOAuth, readClaudeAiOAuth } from './claude-credentials-store.js';
import { runClaudeOAuthLogin, cancelClaudeOAuthLogin } from './claude-oauth-login.js';
@@ -36,6 +37,19 @@ export function subscriptionAccountKind(providerId?: string | null): 'claude' |
const native = getActiveCatalog().providers.find((p) => p.id === providerId)?.auth.native;
return native === 'claude' || native === 'xai' ? native : null;
}
+/** Account replacement/removal invalidates membership, never another connection's catalog. */
+export function clearSubscriptionAccountDiscoveredModels(providerId: string): Promise<void> {
+ setDiscoveredProviderModels(providerId, 'claude-code', []);
+ setXaiDiscoveredModels(null, providerId);
+ if (subscriptionAccountKind(providerId) === 'xai') {
+ // Share the discovery writer's queue so an older pending write cannot recreate the LKG.
+ return discardXaiModelsDiskCache({
+ getScopeKey: () => `${activeOwnerScopeKey()}:${providerId}`,
+ cacheFilePath: () => ownerScopedUserDataPath('model-discovery', `${providerId}-models.json`),
+ });
+ }
+ return Promise.resolve();
+}
export function isClaudeSubscriptionProviderId(providerId?: string | null): boolean {
return providerId === 'anthropic' || subscriptionAccountKind(providerId) === 'claude';
}
@@ -83,6 +97,7 @@ function claudeAccount(providerId: string) {
if (!genericOAuthSecretIo.remove(providerId)) {
log.warn('revoked account credential could not be removed; suppressing retained credential', { providerId });
}
+ void clearSubscriptionAccountDiscoveredModels(providerId);
onInvalidated(providerId);
},
});
@@ -170,8 +185,14 @@ export async function loginSubscriptionAccount(
? genericOAuthSecretIo.remove(providerId)
: genericOAuthSecretIo.write(providerId, before);
if (kind === 'xai') resetGrokOAuthMemoryCache(providerId);
+ if (restored) void clearSubscriptionAccountDiscoveredModels(providerId);
return restored;
};
+ const restoreWrittenCredentials = () => {
+ if (written && activeOwnerScopeKey() === scope && genericOAuthSecretIo.readStrict(providerId) === written) {
+ if (!rollbackCredentials()) throw new Error('Failed to restore credentials after unsuccessful login');
+ }
+ };
try {
const persist = (blob: unknown) => {
if (!current()) throw new Error('login_cancelled');
@@ -191,18 +212,23 @@ export async function loginSubscriptionAccount(
})
: await runGrokOAuthLogin({ isCurrent: current, persist }, providerId);
if (!current()) {
- rollbackCredentials();
+ restoreWrittenCredentials();
return { ok: false, reason: 'login_cancelled' };
}
if (!result.ok && written && !rollbackCredentials()) {
throw new Error('Failed to restore credentials after unsuccessful login');
}
+ if (result.ok) {
+ await clearSubscriptionAccountDiscoveredModels(providerId);
+ if (!current()) {
+ restoreWrittenCredentials();
+ return { ok: false, reason: 'login_cancelled' };
+ }
+ }
// Profile backfill is deferred to the account refresher after the login transaction commits.
return { ...result, firstLogin: before === null, rollbackCredentials };
} catch (error) {
- if (written && activeOwnerScopeKey() === scope && genericOAuthSecretIo.readStrict(providerId) === written) {
- if (!rollbackCredentials()) throw new Error('Failed to restore credentials after unsuccessful login');
- }
+ restoreWrittenCredentials();
throw error;
} finally {
if (logins.get(key) === operation) logins.delete(key);
@@ -216,11 +242,13 @@ export function removeSubscriptionAccountCredentialsReversibly(providerId: strin
if (subscriptionAccountKind(providerId) === 'xai') logoutGrok(providerId);
else if (!genericOAuthSecretIo.remove(providerId))
throw new Error('Failed to remove account credentials');
+ void clearSubscriptionAccountDiscoveredModels(providerId);
return () => {
if (activeOwnerScopeKey() !== scope || genericOAuthSecretIo.readStrict(providerId) !== null)
return false;
const restored = previous === null || genericOAuthSecretIo.write(providerId, previous);
if (subscriptionAccountKind(providerId) === 'xai') resetGrokOAuthMemoryCache(providerId);
+ if (restored) void clearSubscriptionAccountDiscoveredModels(providerId);
return restored;
};
}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
index 5fdd13e6ac..f1808b1550 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts
@@ -24,6 +24,11 @@ const effects = vi.hoisted(() => {
}
return { calls, fns, fn };
});
+// Account discovery persistence is outside this runtime/route fixture.
+vi.mock('../../maker-host/model-discovery/xai.js', () => ({
+ discardXaiModelsDiskCache: vi.fn(async () => {}),
+}));
+
vi.mock('../../logger.js', () => ({
createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),
}));