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(auth): preserve Codex account grants across settings saves

Chrisd1c688d10fce
diff --git a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
index 15fee7f144..4f1bc393bb 100644
--- a/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/custom-provider-store.test.ts
@@ -4,7 +4,7 @@
import Database from 'better-sqlite3';
import { drizzle } from 'drizzle-orm/better-sqlite3';
-import { afterEach, describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
import type { DbClient } from '../../localDb/client/DbClient.js';
import { createDbClient } from '../../localDb/client/DbClient.js';
@@ -16,6 +16,7 @@ import {
deleteCustomProvider,
getCustomProvider,
listCustomProviders,
+ revokeCodexAccountUltrafast,
updateCustomProvider,
updateCustomProviderIfUnchanged,
validateCustomProviderConfig,
@@ -102,6 +103,8 @@ describe('custom provider updates through the runtime database proxy', () => {
expect(await updateCustomProviderIfUnchanged(native.id, before, next)).toBe(true);
const restored = (await getCustomProvider(native.id))!;
expect(restored.runtimes.codex!.models[0].supportsUltrafastMode).toBe(true);
+ // Saving a pre-discovery settings snapshot must not revoke a freshly learned grant.
+ expect((await updateCustomProvider(native.id, before))!.runtimes.codex!.models[0].supportsUltrafastMode).toBe(true);
expect(buildUserProvider(restored).models.codex![0].supportsUltrafastMode).toBe(true);
expect(buildUserProvider((await getCustomProvider('openai-two'))!).models.codex![0].supportsUltrafastMode).toBe(false);
for (const agent of ['codex', 'claude-code', 'pi'] as const) {
@@ -112,7 +115,7 @@ describe('custom provider updates through the runtime database proxy', () => {
// A real refresh without the entitlement must replace the saved true. The
// descriptive name/effort metadata may still use the existing sparse merge.
for (const fields of [{ service_tiers: [{ id: 'priority' }] }, {}]) {
- await updateCustomProvider(native.id, restored);
+ await updateCustomProviderIfUnchanged(native.id, (await getCustomProvider(native.id))!, restored);
const current = (await getCustomProvider(native.id))!;
const refreshed = mergeDiscoveredRuntimeModels(current.runtimes.codex!.models,
parseModelsListResponse({ models: [{ slug: 'gpt-6.1-sol', ...fields }] })!);
@@ -122,7 +125,7 @@ describe('custom provider updates through the runtime database proxy', () => {
}
// Accepted replacement login clears before best-effort discovery. A failed
// refresh writes nothing, so a reload must still expose no old entitlement.
- await updateCustomProvider(native.id, restored);
+ await updateCustomProviderIfUnchanged(native.id, (await getCustomProvider(native.id))!, restored);
expect(await updateCustomProviderIfUnchanged(native.id, restored,
clearCodexAccountUltrafast(restored))).toBe(true);
const replaced = (await getCustomProvider(native.id))!;
@@ -133,6 +136,46 @@ describe('custom provider updates through the runtime database proxy', () => {
} } }).ok).toBe(false);
});
+ it('merges a concurrent revocation before saving native account settings', async () => {
+ mountDb();
+ const config: CustomProviderConfig = { ...valid,
+ auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { ...valid.runtimes.codex!,
+ models: [{ id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', supportsUltrafastMode: true }],
+ } },
+ };
+ await createCustomProvider(config);
+ let resume!: () => void;
+ let ready!: () => void;
+ const paused = new Promise<void>(resolve => { ready = resolve; });
+ const release = new Promise<void>(resolve => { resume = resolve; });
+ const update = client!.drizzle.update.bind(client!.drizzle);
+ const spy = vi.spyOn(client!.drizzle, 'update').mockImplementationOnce((...args: any[]) => {
+ const builder = (update as any)(...args);
+ const set = builder.set.bind(builder);
+ builder.set = (...values: any[]) => {
+ const query = set(...values);
+ const run = query.run.bind(query);
+ query.run = async () => { ready(); await release; return run(); };
+ return query;
+ };
+ return builder;
+ });
+ try {
+ const saving = updateCustomProvider(config.id, { ...config, name: 'Rename kept' });
+ await paused;
+ expect(await revokeCodexAccountUltrafast(config.id, () => true)).toBe(true);
+ resume();
+ const saved = await saving;
+ expect(saved?.name).toBe('Rename kept');
+ expect(saved?.runtimes.codex!.models[0].supportsUltrafastMode).toBe(false);
+ expect(buildUserProvider((await getCustomProvider(config.id))!).models.codex![0].supportsUltrafastMode).toBe(false);
+ } finally {
+ resume();
+ spy.mockRestore();
+ }
+ });
+
it('reports an applied model update and rejects a stale snapshot', async () => {
const worker = await createDbClient({ useInlineWorker: true });
try {
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index a3af957b04..073d1f47f2 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -980,22 +980,38 @@ export async function updateCustomProvider(
now: number = Date.now(),
): Promise<CustomProviderConfig | null> {
const db = getDbClient().drizzle;
- const existing = await db.select().from(customProviders).where(eq(customProviders.id, id)).get();
- if (!existing) return null;
- const c = invalidateEditedProviderMetadata(
- rowToConfig(existing),
- normalizeConfig({ ...config, id }),
- );
- await db
- .update(customProviders)
- .set({
- name: c.name,
- runtimes: JSON.stringify(c.runtimes),
- auth: c.auth ? JSON.stringify(c.auth) : null,
- updatedAt: nextUpdatedAt(now, existing.updatedAt),
- })
- .where(eq(customProviders.id, id));
- return c;
+ for (let attempt = 0; attempt < 3; attempt++) {
+ const existing = await db.select().from(customProviders).where(eq(customProviders.id, id)).get();
+ if (!existing) return null;
+ const previous = rowToConfig(existing);
+ const c = invalidateEditedProviderMetadata(previous, normalizeConfig({ ...config, id }));
+ const nativeAccount = previous.auth?.native === 'codex' || c.auth?.native === 'codex';
+ if (nativeAccount && c.runtimes.codex) {
+ // Settings snapshots cannot grant or revoke account-discovered capabilities.
+ // Only the main-owned discovery/revocation CAS path may change this field.
+ const models = new Map(previous.runtimes.codex?.models.map(model => [model.id, model]));
+ c.runtimes.codex.models = c.runtimes.codex.models.map(model => ({
+ ...model,
+ supportsUltrafastMode: previous.auth?.native === 'codex' && c.auth?.native === 'codex'
+ && models.get(model.id)?.supportsUltrafastMode === true,
+ }));
+ }
+ const result = await db
+ .update(customProviders)
+ .set({
+ name: c.name,
+ runtimes: JSON.stringify(c.runtimes),
+ auth: c.auth ? JSON.stringify(c.auth) : null,
+ updatedAt: nextUpdatedAt(now, existing.updatedAt),
+ })
+ .where(nativeAccount
+ ? and(eq(customProviders.id, id), eq(customProviders.updatedAt, existing.updatedAt))
+ : eq(customProviders.id, id))
+ .run();
+ if (!nativeAccount || result.changes === 1) return c;
+ // A discovery/revocation raced this write. Merge against the latest grant.
+ }
+ throw new Error('Provider changed while saving settings; retry the update');
}
/**
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 3f5bb74b0d..29a155a0a8 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -3,6 +3,7 @@ import { drizzle } from 'drizzle-orm/better-sqlite3';
import { afterEach, describe, it, expect, vi } from 'vitest';
import type { AgentKind, CustomProviderConfig, ProviderView } from '@cindy/model-providers';
+import { buildUserProvider } from '@cindy/model-providers';
import type { ProviderImportPreview } from '../../../shared/providerImport.js';
import { BUILTIN_REFRESHABLE_PROVIDER_IDS } from '../../../shared/providerModelRefresh.js';
@@ -4302,6 +4303,77 @@ describe('provider:oauth mutation ordering', () => {
expect(saved.name).toBe(interleaving === 'settings-edit' ? 'Edited while logging in' : config.name);
});
+ it('does not restore an old account grant when a stale settings dialog saves after login acceptance', async () => {
+ mountDb();
+ const initial: CustomProviderConfig = { ...validConfig,
+ auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { ...validConfig.runtimes.codex!,
+ baseUrl: 'https://chatgpt.com/backend-api/codex', wireProtocol: 'openai-responses',
+ models: [{ id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', supportsUltrafastMode: true }],
+ } },
+ };
+ await createCustomProvider(initial);
+ const harness = new IpcHarness();
+ registerProviderHandlers(harness, makeDeps({
+ oauthLogin: async () => ({ ok: true,
+ commitAccountCapabilities: () => revokeCodexAccountUltrafast(initial.id, () => true),
+ }),
+ }));
+ await expect(harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, initial.id)).resolves.toEqual({ ok: true });
+ // Same payload as the native connection dialog's captured { ...initial, name }.
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, { ...initial, name: 'Renamed after login' });
+ const saved = (await getCustomProvider(initial.id))!;
+ expect(saved.name).toBe('Renamed after login');
+ expect(saved.runtimes.codex!.models[0].supportsUltrafastMode).toBe(false);
+ expect(buildUserProvider(saved).models.codex![0].supportsUltrafastMode).toBe(false);
+ });
+
+ it.each(['cancel', 'release', 'destroy'] as const)('finishes account acceptance when %s arrives during capability commit', async (action) => {
+ mountDb();
+ const config: CustomProviderConfig = { ...validConfig,
+ auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { ...validConfig.runtimes.codex!,
+ baseUrl: 'https://chatgpt.com/backend-api/codex', wireProtocol: 'openai-responses',
+ models: [{ id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', supportsUltrafastMode: true }],
+ } },
+ };
+ await createCustomProvider(config);
+ let release!: () => void;
+ let started!: () => void;
+ const paused = new Promise<void>(resolve => { started = resolve; });
+ const resume = new Promise<void>(resolve => { release = resolve; });
+ const rollbackCredentials = vi.fn(() => true);
+ const afterCommit = vi.fn(async () => {});
+ const oauthCancel = vi.fn();
+ let isCurrent!: () => boolean;
+ const harness = new IpcHarness();
+ registerProviderHandlers(harness, makeDeps({ oauthCancel,
+ oauthLogin: async (_id, current) => {
+ isCurrent = current;
+ return { ok: true, rollbackCredentials,
+ afterCommit: async () => { if (current()) await afterCommit(); },
+ commitAccountCapabilities: async () => {
+ started();
+ await resume;
+ return revokeCodexAccountUltrafast(config.id, () => true);
+ },
+ };
+ },
+ }));
+ const login = harness.invokeFrom(101, MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, config.id, { ownerId: 'accepting-login' });
+ await paused;
+ if (action === 'destroy') harness.destroySender(101);
+ else await harness.invokeFrom(101, MAKER_INVOKE.PROVIDER_OAUTH_CANCEL, config.id,
+ action === 'release' ? { releaseOwner: true, ownerId: 'accepting-login' } : undefined);
+ expect(isCurrent()).toBe(true);
+ expect(oauthCancel).not.toHaveBeenCalled();
+ release();
+ await expect(login).resolves.toEqual({ ok: true });
+ expect(rollbackCredentials).not.toHaveBeenCalled();
+ expect(afterCommit).toHaveBeenCalledOnce();
+ expect((await getCustomProvider(config.id))!.runtimes.codex!.models[0].supportsUltrafastMode).toBe(false);
+ });
+
it.each([false, true])('publishes login identity only after acceptance (cancelled=%s)', async (cancelled) => {
const harness = new IpcHarness();
type LoginResult = Awaited<ReturnType<ProviderHandlerDeps['oauthLogin']>>;
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index d2eec38c50..7518fb3c38 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -596,6 +596,7 @@ export function registerProviderHandlers(
deps: ProviderHandlerDeps,
): void {
const oauthMutationGeneration = new Map<string, symbol>();
+ const acceptingOAuthGenerations = new Set<symbol>();
const beginOAuthMutation = (providerId: string): symbol => {
// Unique token avoids ABA when a completed entry is deleted and the same provider starts again.
const generation = Symbol(providerId);
@@ -643,6 +644,7 @@ export function registerProviderHandlers(
};
const cancelOwnedProviderOAuth = (owner: ProviderOAuthOwner): void => {
if (!isOAuthMutationCurrent(owner.providerId, owner.generation)) return;
+ if (acceptingOAuthGenerations.has(owner.generation)) return;
const cancellationGeneration = beginOAuthMutation(owner.providerId);
try {
deps.oauthCancel(owner.providerId);
@@ -2485,6 +2487,9 @@ export function registerProviderHandlers(
if (isOAuthMutationCurrent(id, generation)) {
if (result.ok) {
if (result.commitAccountCapabilities) {
+ // Credentials are installed: close cancellation before committing their
+ // capabilities so cancellation cannot split the accepted account state.
+ acceptingOAuthGenerations.add(generation);
let committed = false;
try { committed = await result.commitAccountCapabilities(); } catch { /* Roll back below. */ }
if (!committed) {
@@ -2519,6 +2524,7 @@ export function registerProviderHandlers(
if (isIpcError(err)) throw err;
throwIpcError('INVALID_PARAMS', err instanceof Error ? err.message : String(err));
} finally {
+ acceptingOAuthGenerations.delete(generation);
if (codexHostPrepared) deps.cancelCodexCustomProviderHostChange?.();
if (ownerId && owner) removeProviderOAuthOwner(ownerId, sender ?? undefined, owner);
finishOAuthMutation(id, generation);
@@ -2633,6 +2639,8 @@ export function registerProviderHandlers(
if (owner) cancelOwnedProviderOAuth(owner);
return { ok: true };
}
+ const currentGeneration = oauthMutationGeneration.get(id);
+ if (currentGeneration && acceptingOAuthGenerations.has(currentGeneration)) return { ok: true };
clearProviderOAuthOwners(id);
const generation = beginOAuthMutation(id);
try {
diff --git a/docs/product-rules/model-metadata-precedence.md b/docs/product-rules/model-metadata-precedence.md
index 5c0c10945c..628d5c9629 100644
--- a/docs/product-rules/model-metadata-precedence.md
+++ b/docs/product-rules/model-metadata-precedence.md
@@ -109,6 +109,8 @@ Codex 超快是账号发现能力:`service_tiers` / `additional_speed_tiers`
CAS 冲突、所属用户切换或写入失败时回滚登录,不把撤权放进可忽略失败的展示刷新。
原生模型缓存先于凭证提交清除,删除失败保留原身份;取消登录回滚凭证与缓存。
凭证回滚后,仍属于当前用户的连接重新发布账号切换与就绪通知,废弃替换身份的在途额度读取。
+普通设置保存保留数据库中最新的超快资格,旧窗口快照不能授予或撤回资格;并发撤权时重新合并。
+原生登录进入资格提交阶段前仍可取消;进入后关闭取消入口,资格提交失败仍回滚凭证。
仅原生 Codex 账号的 Codex 入口可用,API 同名模型及其它引擎不继承。
回归见 `custom-provider-store.test.ts` 与 `modelDiscoveryChannels.test.ts`。