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): 改进 ChatGPT 登录失效恢复 (#1372)

Dash2ebddb629538
diff --git a/apps/desktop/src/main/__tests__/chatgptApp.test.ts b/apps/desktop/src/main/__tests__/chatgptApp.test.ts
new file mode 100644
index 0000000000..1eb005629e
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/chatgptApp.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { CHATGPT_APP_URL, handleOpenChatGPTApp, openChatGPTApp } from '../chatgpt-app.js';
+
+describe('openChatGPTApp', () => {
+ it('uses the fixed ChatGPT Desktop protocol and reports success', async () => {
+ const openExternal = vi.fn(async () => undefined);
+
+ await expect(openChatGPTApp(openExternal)).resolves.toEqual({ success: true });
+ expect(CHATGPT_APP_URL).toBe('codex://');
+ expect(openExternal).toHaveBeenCalledWith('codex://');
+ });
+
+ it('reports failure without exposing an arbitrary renderer URL surface', async () => {
+ const openExternal = vi.fn(async () => {
+ throw new Error('protocol is not registered');
+ });
+
+ await expect(openChatGPTApp(openExternal)).resolves.toEqual({ success: false });
+ expect(openExternal).toHaveBeenCalledOnce();
+ });
+
+ it('rejects an untrusted IPC sender before opening the protocol', async () => {
+ const openExternal = vi.fn(async () => undefined);
+ const event = { senderFrame: 'untrusted' };
+
+ await expect(handleOpenChatGPTApp(event, {
+ assertTrustedSender: () => {
+ throw new Error('untrusted sender');
+ },
+ openExternal,
+ })).rejects.toThrow('untrusted sender');
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/__tests__/codexAuthInvalidation.test.ts
index fe059aaf1c..e901506ddd 100644
--- a/apps/desktop/src/main/__tests__/codexAuthInvalidation.test.ts
+++ b/apps/desktop/src/main/__tests__/codexAuthInvalidation.test.ts
@@ -8,11 +8,11 @@
* 覆盖:
* - 标记读写与指纹匹配:写入后能读回、系统文件被改写(指纹变化)后不再匹配、损坏标记自愈删除
* - settleInvalidationMarkerAfterLogin(核心回归):系统文件未变 → keepSuppressed=true 且
- * 标记保留;系统文件已变 / 已删 / 无标记 → keepSuppressed=false 且标记被清
+ * 标记保留;系统文件已变 / 已删 → keepSuppressed=false,但标记保留到账号 RPC 验证成功
* - restoreInvalidationStateOnStartup:标记匹配 + 本地 auth.json 缺失 / 仍是坏 token
* → 恢复失效态;标记匹配 + 本地 auth.json 存在且是新 token(重启前已重新登录)
* → 只 suppress 不进失效态;
- * 标记过期 → 全清
+ * 标记过期 → 允许 reconcile,但保留待验证恢复原因
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
@@ -138,7 +138,7 @@ describe('settleInvalidationMarkerAfterLogin (2026-07-03 回归)', () => {
expect(readInvalidatedSystemCodexAuthMarker(codexHome)).not.toBeNull();
});
- it('clears the marker and allows reconcile once the system auth.json changed', () => {
+ it('allows reconcile but retains recovery evidence once the system auth.json changed', () => {
invalidateWithSystemAuthPresent();
rewriteSystemAuth();
fs.writeFileSync(localAuth, FRESH_LOCAL_CONTENT, 'utf-8');
@@ -146,17 +146,17 @@ describe('settleInvalidationMarkerAfterLogin (2026-07-03 回归)', () => {
const { keepSuppressed } = settleInvalidationMarkerAfterLogin(codexHome, systemAuth);
expect(keepSuppressed).toBe(false);
- expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)?.reason).toBe('token_invalidated');
});
- it('clears the marker when the system auth.json was deleted', () => {
+ it('allows reconcile but retains recovery evidence when the system auth.json was deleted', () => {
invalidateWithSystemAuthPresent();
fs.rmSync(systemAuth);
const { keepSuppressed } = settleInvalidationMarkerAfterLogin(codexHome, systemAuth);
expect(keepSuppressed).toBe(false);
- expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)?.reason).toBe('token_invalidated');
});
it('is a no-op pass-through when no marker exists', () => {
@@ -204,19 +204,20 @@ describe('restoreInvalidationStateOnStartup', () => {
expect(restored.invalidatedReason).toBe('token_invalidated');
});
- it('suppresses reconcile but stays authenticated when a fresh local auth.json exists', () => {
+ it('suppresses reconcile and requires account verification when a fresh local auth.json exists', () => {
invalidateWithSystemAuthPresent();
// 上次运行里用户已重新授权成功 (settle 保留了标记), 然后重启应用。
fs.writeFileSync(localAuth, FRESH_LOCAL_CONTENT, 'utf-8');
const restored = restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth);
- // 不能把已重新登录的用户重新打回「已失效」展示态; 但坏 token 仍要挡住。
+ // 不重新使用坏 token;但 fresh 文件只算候选,不能在账号 RPC 前宣称恢复。
expect(restored.suppressReconcile).toBe(true);
expect(restored.invalidatedReason).toBeNull();
+ expect(restored.recoveryRequiredReason).toBe('token_invalidated');
});
- it('clears everything when the system auth.json changed since invalidation', () => {
+ it('allows reconcile but retains a recovery requirement when system auth changed', () => {
invalidateWithSystemAuthPresent();
rewriteSystemAuth();
@@ -224,7 +225,8 @@ describe('restoreInvalidationStateOnStartup', () => {
expect(restored.suppressReconcile).toBe(false);
expect(restored.invalidatedReason).toBeNull();
- expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(restored.recoveryRequiredReason).toBe('token_invalidated');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)?.reason).toBe('token_invalidated');
});
it('returns a clean state when no marker exists', () => {
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 40e392f767..84f6c2037d 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -37,6 +37,7 @@ import {
markDesktopDevWindowReady,
} from './devStartupStatus';
import { prewarmMacComputerPermissionGuideHelper } from './computer-permission-guide/MacComputerPermissionGuideNativeHost.js';
+import { handleOpenChatGPTApp } from './chatgpt-app.js';
const PROCESS_STARTED_AT_MS = Date.now();
// Official Linux binaries total hundreds of MB. Keep one shared deadline for
@@ -4228,6 +4229,17 @@ const registerIpcHandlers = () => {
},
);
+ // ChatGPT Desktop 当前注册 `codex:` 协议(macOS bundle id com.openai.codex;
+ // Windows 安装包也由系统协议注册表接管)。独立无参 IPC 保持最小权限,不能借此
+ // 打开 renderer 提供的任意自定义 scheme / deep link。
+ ipcMain.handle(
+ 'shell:open-chatgpt-app',
+ async (event): Promise<{ success: boolean }> => handleOpenChatGPTApp(event, {
+ assertTrustedSender: assertTrustedAppRendererEvent,
+ openExternal: (url) => shell.openExternal(url),
+ }),
+ );
+
// Show native directory picker dialog
ipcMain.handle(
'show-open-directory-dialog',
diff --git a/apps/desktop/src/main/chatgpt-app.ts b/apps/desktop/src/main/chatgpt-app.ts
new file mode 100644
index 0000000000..f4ae42af7a
--- /dev/null
+++ b/apps/desktop/src/main/chatgpt-app.ts
@@ -0,0 +1,27 @@
+/** ChatGPT Desktop 注册的受限协议入口;不得由 renderer 传入自定义 deep link。 */
+export const CHATGPT_APP_URL = 'codex://';
+
+type OpenChatGPTAppDeps<TEvent> = {
+ assertTrustedSender: (event: TEvent) => void;
+ openExternal: (url: string) => Promise<void>;
+};
+
+export async function openChatGPTApp(
+ openExternal: (url: string) => Promise<void>,
+): Promise<{ success: boolean }> {
+ try {
+ await openExternal(CHATGPT_APP_URL);
+ return { success: true };
+ } catch {
+ return { success: false };
+ }
+}
+
+/** IPC 业务体:先验证 Cindy 顶层 Renderer,再执行固定协议副作用。 */
+export async function handleOpenChatGPTApp<TEvent>(
+ event: TEvent,
+ deps: OpenChatGPTAppDeps<TEvent>,
+): Promise<{ success: boolean }> {
+ deps.assertTrustedSender(event);
+ return openChatGPTApp(deps.openExternal);
+}
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
index fd9e225f54..4aa4e97a58 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
@@ -5,14 +5,22 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
import {
CODEX_USER_DISCONNECT_REASON,
+ getCodexAuthInvalidationMarkerPath,
getActiveInvalidatedSystemCodexAuthMarker,
+ readInvalidatedSystemCodexAuthMarker,
restoreInvalidationStateOnStartup,
+ settleInvalidationMarkerAfterLogin,
shouldSuppressLocalCodexAuth,
writeInvalidatedSystemCodexAuthMarker,
} from '../codex-auth-invalidation.js';
const dirs: string[] = [];
-const h = vi.hoisted(() => ({ userDataDir: '' }));
+const h = vi.hoisted(() => ({
+ userDataDir: '',
+ dataOwnerId: null as string | null,
+ sessionGeneration: 1,
+ sessionBoundaryPending: false,
+}));
vi.mock('electron', () => ({
app: {
@@ -25,6 +33,21 @@ vi.mock('electron', () => ({
vi.mock('@cindy/maker-core', () => ({}));
+vi.mock('../../appSessionState.js', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('../../appSessionState.js')>();
+ return {
+ ...actual,
+ getActiveAppSession: () => ({
+ mode: h.dataOwnerId ? ('cloud' as const) : ('signed-out' as const),
+ dataOwnerId: h.dataOwnerId,
+ generation: h.sessionGeneration,
+ }),
+ activeOwnerScopeKey: () =>
+ `${h.dataOwnerId ? 'cloud' : 'signed-out'}:${h.dataOwnerId ?? 'none'}:${h.sessionGeneration}`,
+ isAppSessionBoundaryPending: () => h.sessionBoundaryPending,
+ };
+});
+
function fixture() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-auth-marker-'));
dirs.push(root);
@@ -40,8 +63,67 @@ function idToken(claims: Record<string, unknown>): string {
return `header.${Buffer.from(JSON.stringify(claims)).toString('base64url')}.signature`;
}
+function deferred<T = void>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ const promise = new Promise<T>((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+async function createRecoveryCandidate(
+ credentialScope: 'system-shared' | 'instance-isolated' | 'unknown',
+) {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-recovery-proof-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'expired-system-token', account_id: 'acct-1' } }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'expired-local-token', account_id: 'acct-1' } }),
+ );
+ if (
+ !writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ credentialScope,
+ credentialScope === 'system-shared' ? 'owner-a' : undefined,
+ )
+ ) {
+ throw new Error('failed to create Codex recovery marker fixture');
+ }
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'replacement-token', account_id: 'acct-1' } }),
+ );
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ return {
+ adapter: new DesktopCodexAuthAdapter(),
+ codexHome,
+ localAuth,
+ markerPath: getCodexAuthInvalidationMarkerPath(codexHome),
+ systemAuth,
+ };
+}
+
afterEach(() => {
vi.restoreAllMocks();
+ h.dataOwnerId = null;
+ h.sessionGeneration = 1;
+ h.sessionBoundaryPending = false;
for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
});
@@ -111,12 +193,7 @@ describe('Codex system credential suppression marker', () => {
// 用户在 XDMaker 内显式重登得到隔离 token,之后该 token 又被服务端判失效。
fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'local-token' } }));
expect(
- writeInvalidatedSystemCodexAuthMarker(
- codexHome,
- systemAuth,
- 'token_invalidated',
- localAuth,
- ),
+ writeInvalidatedSystemCodexAuthMarker(codexHome, systemAuth, 'token_invalidated', localAuth),
).toBe(true);
fs.rmSync(localAuth);
fs.writeFileSync(systemAuth, JSON.stringify({ tokens: { access_token: 'new-system-token' } }));
@@ -154,20 +231,518 @@ describe('Codex system credential suppression marker', () => {
const { codexHome, systemAuth, localAuth } = fixture();
fs.mkdirSync(codexHome, { recursive: true });
fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'invalid-token' } }));
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(codexHome, systemAuth, 'token_invalidated', localAuth),
+ ).toBe(true);
+
+ expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(true);
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-token' } }));
+ expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(false);
+ });
+
+ it('persists an isolated invalidation without system auth and ignores unrelated system changes', () => {
+ const { codexHome, systemAuth, localAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'invalid-local' } }));
+ fs.rmSync(systemAuth);
+
expect(
writeInvalidatedSystemCodexAuthMarker(
codexHome,
systemAuth,
- 'token_invalidated',
+ 'token_revoked',
localAuth,
+ 'instance-isolated',
),
).toBe(true);
+ expect(restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth)).toEqual({
+ suppressReconcile: true,
+ invalidatedReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
- expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(true);
- fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-token' } }));
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.writeFileSync(systemAuth, JSON.stringify({ tokens: { access_token: 'unrelated-system' } }));
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('persists an unknown-source invalidation without system auth until Cindy writes a new token', () => {
+ const { codexHome, systemAuth, localAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'legacy-local' } }));
+ fs.rmSync(systemAuth);
+
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ 'unknown',
+ ),
+ ).toBe(true);
+ expect(restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth)).toEqual({
+ suppressReconcile: true,
+ invalidatedReason: 'token_revoked',
+ credentialScope: 'unknown',
+ });
+
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-cindy-token' } }));
+ expect(restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth)).toEqual({
+ suppressReconcile: true,
+ invalidatedReason: null,
+ recoveryRequiredReason: 'token_revoked',
+ credentialScope: 'unknown',
+ });
+ expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(false);
+ });
+
+ it('keeps system reconcile suppressed after a new isolated local credential replaces it', () => {
+ const { codexHome, systemAuth, localAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'invalid-local' } }));
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ 'instance-isolated',
+ ),
+ ).toBe(true);
+
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-local' } }));
+ expect(restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth)).toEqual({
+ suppressReconcile: true,
+ invalidatedReason: null,
+ recoveryRequiredReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(false);
});
+ it('keeps an isolated suppression marker in the successful-login finalizer', () => {
+ const { codexHome, systemAuth, localAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'invalid-local' } }));
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ 'instance-isolated',
+ ),
+ ).toBe(true);
+
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-local' } }));
+ expect(settleInvalidationMarkerAfterLogin(codexHome, systemAuth)).toEqual({
+ keepSuppressed: true,
+ });
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(false);
+ });
+
+ it('preserves a durable disconnect while a replacement isolated token clears the error', () => {
+ const { codexHome, systemAuth, localAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'old-local' } }));
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ CODEX_USER_DISCONNECT_REASON,
+ localAuth,
+ ),
+ ).toBe(true);
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ 'instance-isolated',
+ ),
+ ).toBe(true);
+
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-local' } }));
+ expect(settleInvalidationMarkerAfterLogin(codexHome, systemAuth)).toEqual({
+ keepSuppressed: true,
+ });
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ durableDisconnect: true,
+ });
+ expect(restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth)).toEqual({
+ suppressReconcile: true,
+ invalidatedReason: null,
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('does not relink a successful isolated login to a same-account system credential', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-isolated-finalize-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'expired-local', account_id: 'acct-1' },
+ }),
+ );
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ 'instance-isolated',
+ ),
+ ).toBe(true);
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ });
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'new-local-token', account_id: 'acct-1' },
+ }),
+ );
+
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{ authenticated: boolean }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+ await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({ authenticated: true });
+ expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);
+ expect(JSON.parse(fs.readFileSync(localAuth, 'utf8'))).toMatchObject({
+ tokens: { access_token: 'new-local-token', account_id: 'acct-1' },
+ });
+ });
+
+ it('reclassifies a shared invalidation as isolated after an explicit Cindy login', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-to-isolated-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'expired-system-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-a' }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'system-shared',
+ });
+ await expect(adapter.invalidate('token_revoked')).resolves.toBeUndefined();
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'new-cindy-token', account_id: 'acct-1' },
+ }),
+ );
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{
+ authenticated: boolean;
+ credentialScope?: string;
+ recoveryRequiredReason?: string;
+ }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+
+ await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({
+ authenticated: true,
+ recoveryRequiredReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+
+ await adapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ credentialScope: 'instance-isolated',
+ durableDisconnect: true,
+ });
+
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ credentialScope: 'instance-isolated',
+ });
+ expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);
+ expect(JSON.parse(fs.readFileSync(localAuth, 'utf8'))).toMatchObject({
+ tokens: { access_token: 'new-cindy-token' },
+ });
+ });
+
+ it('does not confirm an account probe after the active owner generation changes', async () => {
+ const { adapter, codexHome } = await createRecoveryCandidate('instance-isolated');
+ const accountRpc = deferred<string>();
+ const verification = adapter.verifyRecoveryWithAccountRpc(() => accountRpc.promise);
+
+ h.sessionGeneration += 1;
+ accountRpc.resolve('usage-result');
+
+ await expect(verification).resolves.toBe('usage-result');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('does not confirm an account probe after the local credential changes', async () => {
+ const { adapter, codexHome, localAuth } = await createRecoveryCandidate('instance-isolated');
+ const accountRpc = deferred<string>();
+ const verification = adapter.verifyRecoveryWithAccountRpc(() => accountRpc.promise);
+
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'newer-token', account_id: 'acct-1' } }),
+ );
+ accountRpc.resolve('usage-result');
+
+ await expect(verification).resolves.toBe('usage-result');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('does not confirm an account probe while a new tracked login is pending', async () => {
+ const { adapter, codexHome } = await createRecoveryCandidate('instance-isolated');
+ const accountRpc = deferred<string>();
+ const verification = adapter.verifyRecoveryWithAccountRpc(() => accountRpc.promise);
+ const loginBarrier = deferred<void>();
+ const startTrackedLogin = (
+ adapter as unknown as {
+ startTrackedLogin(
+ opts?: undefined,
+ waitFor?: Promise<unknown>,
+ ): Promise<{ authenticated: boolean; errorReason?: string }>;
+ }
+ ).startTrackedLogin.bind(adapter);
+ const login = startTrackedLogin(undefined, loginBarrier.promise);
+
+ accountRpc.resolve('usage-result');
+
+ await expect(verification).resolves.toBe('usage-result');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+
+ adapter.cancelLogin();
+ loginBarrier.resolve();
+ await expect(login).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'login_cancelled',
+ });
+ });
+
+ it('does not confirm an account probe while an app-session boundary is pending', async () => {
+ const { adapter, codexHome } = await createRecoveryCandidate('instance-isolated');
+ const accountRpc = deferred<string>();
+ const verification = adapter.verifyRecoveryWithAccountRpc(() => accountRpc.promise);
+
+ h.sessionBoundaryPending = true;
+ accountRpc.resolve('usage-result');
+
+ await expect(verification).resolves.toBe('usage-result');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('does not consume a recovery marker created after an account probe starts', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-late-recovery-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(systemAuth, JSON.stringify({ tokens: { access_token: 'system-token' } }));
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'local-token' } }));
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const accountRpc = deferred<string>();
+ const verification = adapter.verifyRecoveryWithAccountRpc(() => accountRpc.promise);
+
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_revoked',
+ localAuth,
+ 'instance-isolated',
+ ),
+ ).toBe(true);
+ accountRpc.resolve('usage-result');
+
+ await expect(verification).resolves.toBe('usage-result');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('returns account usage but keeps isolated recovery pending when sentinel persistence fails', async () => {
+ const { adapter, codexHome, markerPath } = await createRecoveryCandidate('instance-isolated');
+ const realRenameSync = fs.renameSync.bind(fs);
+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ if (String(to) === markerPath) throw new Error('EIO: marker rename failed');
+ return realRenameSync(from, to);
+ });
+
+ await expect(adapter.verifyRecoveryWithAccountRpc(async () => 'usage-result')).resolves.toBe(
+ 'usage-result',
+ );
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('returns account usage but keeps shared recovery pending when marker removal fails', async () => {
+ const { adapter, codexHome, markerPath } = await createRecoveryCandidate('system-shared');
+ const realUnlinkSync = fs.unlinkSync.bind(fs);
+ vi.spyOn(fs, 'unlinkSync').mockImplementation((file) => {
+ if (String(file) === markerPath) throw new Error('EPERM: marker is locked');
+ return realUnlinkSync(file);
+ });
+
+ await expect(adapter.verifyRecoveryWithAccountRpc(async () => 'usage-result')).resolves.toBe(
+ 'usage-result',
+ );
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ });
+
+ it('fails login finalization before rebinding when the recovered scope cannot be persisted', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-scope-persist-fail-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const markerPath = getCodexAuthInvalidationMarkerPath(codexHome);
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({ tokens: { access_token: 'expired-system-token', account_id: 'acct-1' } }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ openai: 'owner-a' }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await adapter.getState({ credentialMode: 'oauth-bearer' });
+ await adapter.invalidate('token_revoked');
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'new-cindy-token', account_id: 'acct-1' } }),
+ );
+
+ const realRenameSync = fs.renameSync.bind(fs);
+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ if (String(to) === markerPath) throw new Error('EIO: marker rename failed');
+ return realRenameSync(from, to);
+ });
+ const finishSuccessfulCodexLogin = (
+ adapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{ authenticated: boolean; errorReason?: string }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(adapter);
+
+ await expect(finishSuccessfulCodexLogin()).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'login_finalize_error:failed_to_persist_auth_boundary',
+ });
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty('openai');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ });
+
it('blocks every token read when a Windows lock leaves the disconnected local file behind', async () => {
const { codexHome: fixtureCodexHome, systemAuth } = fixture();
h.userDataDir = path.join(path.dirname(fixtureCodexHome), 'user-data');
@@ -219,23 +794,29 @@ describe('Codex system credential suppression marker', () => {
const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
const adapter = new DesktopCodexAuthAdapter();
- fs.writeFileSync(localAuth, JSON.stringify({
- tokens: {
- access_token: 'local-token',
- id_token: idToken({ sub: 'user-subject' }),
- },
- }));
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ tokens: {
+ access_token: 'local-token',
+ id_token: idToken({ sub: 'user-subject' }),
+ },
+ }),
+ );
await expect(adapter.getAccountId()).resolves.toBeNull();
- fs.writeFileSync(localAuth, JSON.stringify({
- tokens: {
- access_token: 'local-token',
- id_token: idToken({
- sub: 'user-subject',
- 'https://api.openai.com/auth': { chatgpt_account_id: 'workspace-actual' },
- }),
- },
- }));
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ tokens: {
+ access_token: 'local-token',
+ id_token: idToken({
+ sub: 'user-subject',
+ 'https://api.openai.com/auth': { chatgpt_account_id: 'workspace-actual' },
+ }),
+ },
+ }),
+ );
await expect(adapter.getAccountId()).resolves.toBe('workspace-actual');
});
@@ -261,7 +842,9 @@ describe('Codex system credential suppression marker', () => {
const adapter = new DesktopCodexAuthAdapter();
const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
adapter.setOnLogoutSuccess(onLogoutSuccess);
- const rmSpy = vi.spyOn(fs.promises, 'rm').mockRejectedValueOnce(new Error('EPERM: file is locked'));
+ const rmSpy = vi
+ .spyOn(fs.promises, 'rm')
+ .mockRejectedValueOnce(new Error('EPERM: file is locked'));
await expect(adapter.logout()).resolves.toBeUndefined();
expect(onLogoutSuccess).toHaveBeenCalledTimes(1);
@@ -281,6 +864,47 @@ describe('Codex system credential suppression marker', () => {
expect(fs.existsSync(localAuth)).toBe(false);
});
+ it('clears a pending recovery state when the user explicitly logs out', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-recovery-logout-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({ openai: 'owner-a', selfAuthorized: { openai: 'owner-a' } }),
+ );
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'expired-token' } }));
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ path.join(root, 'empty-home', '.codex', 'auth.json'),
+ 'token_revoked',
+ localAuth,
+ 'instance-isolated',
+ ),
+ ).toBe(true);
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'replacement-token' } }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ recoveryRequiredReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+
+ await expect(adapter.logout()).resolves.toBeUndefined();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toEqual({
+ authenticated: false,
+ errorReason: 'no_oauth',
+ });
+ });
+
it('removes an unowned model cache before login and fails closed while it is locked', async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-model-cache-login-'));
dirs.push(root);
@@ -303,10 +927,19 @@ describe('Codex system credential suppression marker', () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-invalidation-finalizer-'));
dirs.push(root);
h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));
const codexHome = path.join(h.userDataDir, 'codex-home');
const localAuth = path.join(codexHome, 'auth.json');
const cachePath = path.join(codexHome, 'models_cache.json');
fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({
+ openai: 'owner-a',
+ selfAuthorized: { openai: 'owner-a' },
+ }),
+ );
fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'expired-token' } }));
fs.writeFileSync(cachePath, JSON.stringify({ models: [{ slug: 'old-account-model' }] }));
@@ -330,7 +963,9 @@ describe('Codex system credential suppression marker', () => {
adapter.setOnInvalidatedBroadcast(finalizer);
const invalidation = adapter.invalidate('token_invalidated');
- await vi.waitFor(() => expect(finalizer).toHaveBeenCalledWith('token_invalidated'));
+ await vi.waitFor(() =>
+ expect(finalizer).toHaveBeenCalledWith('token_invalidated', 'instance-isolated'),
+ );
expect(order).toEqual(['host-disposed', 'finalizer-start']);
expect(fs.existsSync(localAuth)).toBe(false);
expect(fs.existsSync(cachePath)).toBe(false);
@@ -347,13 +982,404 @@ describe('Codex system credential suppression marker', () => {
expect(order).toEqual(['host-disposed', 'finalizer-start', 'finalizer-end']);
});
+ it('keeps invalidation recovery actionable when auth.json remains locked', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-invalidation-locked-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const cachePath = path.join(codexHome, 'models_cache.json');
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({ openai: 'owner-a', selfAuthorized: { openai: 'owner-a' } }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({ tokens: { access_token: 'expired-token', account_id: 'acct-1' } }),
+ );
+ fs.writeFileSync(cachePath, JSON.stringify({ models: [{ slug: 'old-account-model' }] }));
+
+ const { DesktopCodexAuthAdapter, readCodexOneShotCreds } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const onLogoutSuccess = vi.fn().mockResolvedValue(undefined);
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(onLogoutSuccess);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+ const realRm = fs.promises.rm.bind(fs.promises);
+ vi.spyOn(fs.promises, 'rm').mockImplementation(async (target, options) => {
+ if (String(target) === localAuth) throw new Error('EPERM: auth is locked');
+ return realRm(target, options);
+ });
+
+ await expect(adapter.invalidate('token_revoked')).resolves.toBeUndefined();
+ expect(onLogoutSuccess).toHaveBeenCalledOnce();
+ expect(broadcast).toHaveBeenCalledWith('token_revoked', 'instance-isolated');
+ expect(fs.existsSync(localAuth)).toBe(true);
+ expect(fs.existsSync(cachePath)).toBe(false);
+ await expect(adapter.getAccessToken()).resolves.toBeNull();
+ expect(readCodexOneShotCreds()).toBeNull();
+ });
+
+ it('fails closed when the invalidation marker cannot be committed and restores suppression after login', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-invalidation-marker-fail-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const markerPath = path.join(codexHome, 'auth-invalidated-system.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'system-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'expired-local', account_id: 'acct-1' },
+ }),
+ );
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({ openai: 'owner-a', selfAuthorized: { openai: 'owner-a' } }),
+ );
+
+ const realRenameSync = fs.renameSync.bind(fs);
+ let failMarkerCommit = true;
+ vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => {
+ if (failMarkerCommit && String(to) === markerPath) {
+ failMarkerCommit = false;
+ throw new Error('EIO: marker rename failed');
+ }
+ return realRenameSync(from, to);
+ });
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await expect(adapter.invalidate('token_revoked')).resolves.toBeUndefined();
+ expect(broadcast).toHaveBeenCalledWith('token_revoked', 'unknown');
+ expect(fs.existsSync(markerPath)).toBe(false);
+ expect(
+ JSON.parse(fs.readFileSync(path.join(h.userDataDir, 'native-provider-auth.json'), 'utf8')),
+ ).toMatchObject({ revoked: { openai: 'owner-a' } });
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'unknown',
+ });
+
+ // Simulate a process restart: the coarse provider revocation must still block system reclaim
+ // even though the richer codex-home marker never committed. A later explicit Cindy login then
+ // proves that the replacement credential is instance-isolated.
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(restartedAdapter.getAccessToken()).resolves.toBeNull();
+ expect(fs.existsSync(localAuth)).toBe(false);
+
+ fs.writeFileSync(
+ localAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'new-local-token', account_id: 'acct-1' },
+ }),
+ );
+ const finishSuccessfulCodexLogin = (
+ restartedAdapter as unknown as {
+ finishSuccessfulCodexLogin(): Promise<{ authenticated: boolean }>;
+ }
+ ).finishSuccessfulCodexLogin.bind(restartedAdapter);
+ await expect(finishSuccessfulCodexLogin()).resolves.toMatchObject({
+ authenticated: true,
+ recoveryRequiredReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ await expect(restartedAdapter.getAccessToken()).resolves.toBe('new-local-token');
+ await restartedAdapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ expect(getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuth)).toMatchObject({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ credentialScope: 'instance-isolated',
+ durableDisconnect: true,
+ });
+ });
+
+ it('lets explicit logout upgrade an invalidation already in progress', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-invalidation-logout-race-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({ openai: 'owner-a', selfAuthorized: { openai: 'owner-a' } }),
+ );
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'expired-token' } }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const cleanupGate = deferred();
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(() => cleanupGate.promise);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ const invalidation = adapter.invalidate('token_invalidated');
+ await vi.waitFor(() => expect(fs.existsSync(localAuth)).toBe(false));
+ const explicitLogout = adapter.logout();
+ cleanupGate.resolve();
+
+ await expect(invalidation).resolves.toBeUndefined();
+ await expect(explicitLogout).resolves.toBeUndefined();
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(
+ getActiveInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ path.join(root, 'empty-home', '.codex', 'auth.json'),
+ ),
+ ).toMatchObject({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ durableDisconnect: true,
+ });
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ revoked: { openai: 'owner-a' },
+ });
+ });
+
+ it('keeps explicit logout authoritative when invalidation arrives during cleanup', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-logout-invalidation-race-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({ openai: 'owner-a', selfAuthorized: { openai: 'owner-a' } }),
+ );
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'active-token' } }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const cleanupGate = deferred();
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnLogoutSuccess(() => cleanupGate.promise);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ const explicitLogout = adapter.logout();
+ await vi.waitFor(() => expect(fs.existsSync(localAuth)).toBe(false));
+ const invalidation = adapter.invalidate('token_invalidated');
+ cleanupGate.resolve();
+
+ await expect(explicitLogout).resolves.toBeUndefined();
+ await expect(invalidation).resolves.toBeUndefined();
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(
+ getActiveInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ path.join(root, 'empty-home', '.codex', 'auth.json'),
+ ),
+ ).toMatchObject({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ durableDisconnect: true,
+ });
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ revoked: { openai: 'owner-a' },
+ });
+ });
+
+ it('ignores a stale invalidation after explicit logout has already completed', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-logout-stale-invalidation-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ vi.spyOn(os, 'homedir').mockReturnValue(path.join(root, 'empty-home'));
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ path.join(h.userDataDir, 'native-provider-auth.json'),
+ JSON.stringify({ openai: 'owner-a', selfAuthorized: { openai: 'owner-a' } }),
+ );
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'active-token' } }));
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const broadcast = vi.fn().mockResolvedValue(undefined);
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await expect(adapter.logout()).resolves.toBeUndefined();
+ await expect(adapter.invalidate('token_invalidated')).resolves.toBeUndefined();
+ expect(broadcast).not.toHaveBeenCalled();
+ expect(
+ getActiveInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ path.join(root, 'empty-home', '.codex', 'auth.json'),
+ ),
+ ).toMatchObject({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ durableDisconnect: true,
+ });
+ });
+
+ it('keeps a legacy reason-only disconnect authoritative over a late invalidation', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-legacy-disconnect-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-a';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(systemAuth, JSON.stringify({ tokens: { access_token: 'old-token' } }));
+ fs.linkSync(systemAuth, localAuth);
+ const stat = fs.statSync(systemAuth);
+ fs.writeFileSync(
+ getCodexAuthInvalidationMarkerPath(codexHome),
+ JSON.stringify({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ dev: stat.dev,
+ ino: stat.ino,
+ size: stat.size,
+ mtimeMs: stat.mtimeMs,
+ }),
+ );
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ const broadcast = vi.fn();
+ adapter.setOnInvalidatedBroadcast(broadcast);
+
+ await expect(adapter.invalidate('token_revoked')).resolves.toBeUndefined();
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ reason: CODEX_USER_DISCONNECT_REASON,
+ });
+ expect(broadcast).not.toHaveBeenCalled();
+ });
+
+ it('remembers a shared source across atomic system replacement and reclaims the renewed login', async () => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'xdt-codex-shared-recovery-'));
+ dirs.push(root);
+ h.userDataDir = path.join(root, 'user-data');
+ h.dataOwnerId = 'owner-b';
+ const home = path.join(root, 'home');
+ const systemAuth = path.join(home, '.codex', 'auth.json');
+ const codexHome = path.join(h.userDataDir, 'codex-home');
+ const localAuth = path.join(codexHome, 'auth.json');
+ const bindingFile = path.join(h.userDataDir, 'native-provider-auth.json');
+ vi.spyOn(os, 'homedir').mockReturnValue(home);
+ fs.mkdirSync(path.dirname(systemAuth), { recursive: true });
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(
+ systemAuth,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'expired-system-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.linkSync(systemAuth, localAuth);
+ fs.mkdirSync(h.userDataDir, { recursive: true });
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({ legacyClaimOwner: 'owner-a', openai: 'owner-b' }),
+ );
+
+ const { DesktopCodexAuthAdapter } = await import('../auth-adapters.js');
+ const adapter = new DesktopCodexAuthAdapter();
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+
+ const replacement = path.join(path.dirname(systemAuth), 'auth.replacement.json');
+ fs.writeFileSync(
+ replacement,
+ JSON.stringify({
+ account: { email: '[email protected]' },
+ tokens: { access_token: 'renewed-system-token', account_id: 'acct-1' },
+ }),
+ );
+ fs.renameSync(replacement, systemAuth);
+ expect(fs.statSync(localAuth).ino).not.toBe(fs.statSync(systemAuth).ino);
+
+ const broadcast = vi.fn();
+ adapter.setOnInvalidatedBroadcast(broadcast);
+ await expect(adapter.invalidate('token_revoked')).resolves.toBeUndefined();
+ expect(broadcast).toHaveBeenCalledWith('token_revoked', 'system-shared');
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ credentialScope: 'system-shared',
+ recoveryOwnerId: 'owner-b',
+ });
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty('revoked.openai');
+
+ await expect(adapter.getState({ credentialMode: 'oauth-bearer' })).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'token_revoked',
+ });
+ await expect(adapter.getAccessToken()).resolves.toBe('renewed-system-token');
+
+ const restartedAdapter = new DesktopCodexAuthAdapter();
+ await expect(
+ restartedAdapter.getState({ credentialMode: 'oauth-bearer' }),
+ ).resolves.toMatchObject({
+ authenticated: true,
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'token_revoked',
+ });
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toMatchObject({
+ recoveryOwnerId: 'owner-b',
+ });
+
+ await restartedAdapter.verifyRecoveryWithAccountRpc(async () => undefined);
+ expect(readInvalidatedSystemCodexAuthMarker(codexHome)).toBeNull();
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ legacyClaimOwner: 'owner-a',
+ openai: 'owner-b',
+ });
+ });
+
it('real token invalidation still surfaces its reason when no replacement local credential exists', () => {
const { codexHome, systemAuth, localAuth } = fixture();
- writeInvalidatedSystemCodexAuthMarker(codexHome, systemAuth, 'token_invalidated', localAuth);
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_invalidated',
+ localAuth,
+ 'system-shared',
+ );
expect(restoreInvalidationStateOnStartup(codexHome, systemAuth, localAuth)).toEqual({
suppressReconcile: true,
invalidatedReason: 'token_invalidated',
+ credentialScope: 'system-shared',
});
});
});
diff --git a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
index 02dfb1f5dd..9c7a72e490 100644
--- a/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/nativeProviderAuthBinding.test.ts
@@ -23,8 +23,10 @@ import {
bindNativeProviderAuth,
claimDetectedNativeProviderAuth,
isNativeProviderAuthBound,
+ isNativeProviderAuthRevoked,
isNativeProviderAuthSelfAuthorized,
migrateLegacyNativeProviderAuthBindings,
+ restoreNativeProviderAuthForRecovery,
unbindNativeProviderAuth,
} from '../nativeProviderAuthBinding.js';
@@ -152,6 +154,14 @@ describe('claimDetectedNativeProviderAuth', () => {
expect(claimDetectedNativeProviderAuth('anthropic', () => true)).toBe(false);
});
+ it('撤销标记在还没有 active owner 的启动阶段也会阻断凭证', () => {
+ unbindNativeProviderAuth('openai', { revoked: true });
+ expect(isNativeProviderAuthRevoked('openai')).toBe(true);
+
+ session.dataOwnerId = null;
+ expect(isNativeProviderAuthBound('openai')).toBe(false);
+ });
+
it('一次性 legacy 迁移同样尊重撤销标记', () => {
unbindNativeProviderAuth('anthropic', { revoked: true });
session.dataOwnerId = 'owner-b';
@@ -285,6 +295,48 @@ describe('claimDetectedNativeProviderAuth', () => {
});
});
+describe('restoreNativeProviderAuthForRecovery', () => {
+ it('restores the invalidated owner even when another owner won the legacy claim', () => {
+ fs.mkdirSync(userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: 'owner-a' }));
+ session.dataOwnerId = 'owner-b';
+
+ expect(restoreNativeProviderAuthForRecovery('openai', 'owner-b', () => true)).toBe(true);
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toMatchObject({
+ legacyClaimOwner: 'owner-a',
+ openai: 'owner-b',
+ });
+ });
+
+ it('does not restore after the active owner changes', () => {
+ fs.mkdirSync(userDataDir, { recursive: true });
+ fs.writeFileSync(bindingFile, JSON.stringify({ legacyClaimOwner: 'owner-a' }));
+ session.dataOwnerId = 'owner-c';
+
+ expect(restoreNativeProviderAuthForRecovery('openai', 'owner-b', () => true)).toBe(false);
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).toEqual({
+ legacyClaimOwner: 'owner-a',
+ });
+ });
+
+ it('keeps explicit revocation and session boundaries fail-closed', () => {
+ fs.mkdirSync(userDataDir, { recursive: true });
+ fs.writeFileSync(
+ bindingFile,
+ JSON.stringify({
+ legacyClaimOwner: 'owner-a',
+ revoked: { openai: 'owner-b' },
+ }),
+ );
+ session.dataOwnerId = 'owner-b';
+
+ expect(restoreNativeProviderAuthForRecovery('openai', 'owner-b', () => true)).toBe(false);
+ session.boundaryPending = true;
+ expect(restoreNativeProviderAuthForRecovery('openai', 'owner-b', () => true)).toBe(false);
+ expect(JSON.parse(fs.readFileSync(bindingFile, 'utf8'))).not.toHaveProperty('openai');
+ });
+});
+
describe('凭证来路(selfAuthorized)—— 显式授权 vs 自动继承', () => {
// 存在的理由:两者结果相同(绑到当前 owner、凭证可用),但用户可见文案的依据不同 ——
// 「已沿用这台电脑上登录的账号」只对继承成立(PR #1076 review 第三轮)。
diff --git a/apps/desktop/src/main/maker-host/auth-adapters.ts b/apps/desktop/src/main/maker-host/auth-adapters.ts
index 14792c0fe1..fe6f336f92 100644
--- a/apps/desktop/src/main/maker-host/auth-adapters.ts
+++ b/apps/desktop/src/main/maker-host/auth-adapters.ts
@@ -14,6 +14,7 @@
*/
import { app, safeStorage } from 'electron';
+import { createHash } from 'node:crypto';
import os from 'node:os';
import path from 'node:path';
import fs from 'node:fs';
@@ -40,11 +41,13 @@ import { claudeOAuthSpawnEnv } from './claude-oauth-spawn-env.js';
import {
CODEX_USER_DISCONNECT_REASON,
clearInvalidatedSystemCodexAuthMarker,
- markerMatchesCurrentSystemCodexAuth,
+ getActiveInvalidatedSystemCodexAuthMarker,
+ isDurableDisconnectMarker,
readInvalidatedSystemCodexAuthMarker,
restoreInvalidationStateOnStartup,
settleInvalidationMarkerAfterLogin,
shouldSuppressLocalCodexAuth,
+ updateInvalidatedSystemCodexAuthMarkerCredentialScope,
writeInvalidatedSystemCodexAuthMarker,
} from './codex-auth-invalidation.js';
import {
@@ -54,7 +57,10 @@ import {
resolveCodexLoginExitState,
terminateCodexLoginProcess,
} from './codex-auth-state.js';
-import { CODEX_GATEWAY_ENV_KEY, CODEX_PROVIDER_OAUTH_PLACEHOLDER_KEY } from './codex-gateway-config.js';
+import {
+ CODEX_GATEWAY_ENV_KEY,
+ CODEX_PROVIDER_OAUTH_PLACEHOLDER_KEY,
+} from './codex-gateway-config.js';
import { CLAUDE_PROVIDER_AUTH_PLACEHOLDER_KEY } from './claude-gateway-config.js';
import {
clearClaudeAiOAuth,
@@ -73,6 +79,7 @@ import { claudeUpstreamEndpoint } from './runtime-configs.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
import { getAppCapabilities } from '../appCapabilities.js';
import {
+ activeOwnerScopeKey,
getActiveAppSession,
isAppSessionBoundaryPending,
type ActiveAppSession,
@@ -81,6 +88,9 @@ import {
bindNativeProviderAuth,
claimDetectedNativeProviderAuth,
isNativeProviderAuthBound,
+ isNativeProviderAuthRevoked,
+ isNativeProviderAuthSelfAuthorized,
+ restoreNativeProviderAuthForRecovery,
unbindNativeProviderAuth,
} from './nativeProviderAuthBinding.js';
import { getGhostSetupChangeBus } from '../cindy-brain/ghostSetupChangeBus.js';
@@ -120,6 +130,15 @@ function getSystemCodexAuthPath(): string {
async function readCodexAccountId(authPath: string): Promise<string | null> {
try {
const raw = await fsp.readFile(authPath, 'utf-8');
+ return codexAccountIdFromAuthJson(raw);
+ } catch {
+ /* 解析失败 → null */
+ }
+ return null;
+}
+
+function codexAccountIdFromAuthJson(raw: string): string | null {
+ try {
const obj = JSON.parse(raw) as { tokens?: { account_id?: unknown; id_token?: unknown } };
if (typeof obj.tokens?.account_id === 'string' && obj.tokens.account_id.length > 0) {
return obj.tokens.account_id;
@@ -133,6 +152,29 @@ async function readCodexAccountId(authPath: string): Promise<string | null> {
return null;
}
+type CodexRecoveryVerificationProof = {
+ ownerScopeKey: string;
+ reason: string;
+ credentialScope: NonNullable<AuthState['credentialScope']>;
+ markerFingerprint: string;
+ credentialSha256: string;
+ accountId: string | null;
+};
+
+function readCodexRecoveryCredentialProof(
+ authPath: string,
+): Pick<CodexRecoveryVerificationProof, 'credentialSha256' | 'accountId'> | null {
+ try {
+ const raw = fs.readFileSync(authPath, 'utf-8');
+ return {
+ credentialSha256: createHash('sha256').update(raw).digest('hex'),
+ accountId: codexAccountIdFromAuthJson(raw),
+ };
+ } catch {
+ return null;
+ }
+}
+
interface ChatgptIdTokenClaims {
chatgpt_account_id?: unknown;
sub?: unknown;
@@ -235,6 +277,53 @@ export function isCodexAuthInheritedFromSystemCli(): boolean {
}
}
+/**
+ * 检测 Cindy 当前 Codex OAuth auth.json 能够被**当场证明**的来源。
+ *
+ * 同 inode 可以证明仍与系统登录共享;Cindy 显式授权记录可以证明是实例隔离。除此之外
+ * 一律 unknown:系统 auth.json 原子替换后留下的旧硬链、历史版本没有 provenance 的本地
+ * 凭证、绑定文件不可读,都不能仅凭「两个文件现在不同」武断地说成 Cindy 独立登录。
+ */
+function detectCodexCredentialScope(codexHome: string): NonNullable<AuthState['credentialScope']> {
+ try {
+ const localAuth = path.join(codexHome, 'auth.json');
+ if (!existsSync(localAuth)) return 'unknown';
+ const systemAuth = getSystemCodexAuthPath();
+ if (existsSync(systemAuth)) {
+ const localStat = fs.statSync(localAuth);
+ const systemStat = fs.statSync(systemAuth);
+ if (localStat.ino === systemStat.ino && localStat.dev === systemStat.dev) {
+ return 'system-shared';
+ }
+ }
+ if (isNativeProviderAuthBound('openai') && isNativeProviderAuthSelfAuthorized('openai')) {
+ return 'instance-isolated';
+ }
+ return 'unknown';
+ } catch {
+ return 'unknown';
+ }
+}
+
+/**
+ * Cindy 发起的 OAuth 登录完成后,重新判定这份新凭证是否仍与系统 auth.json 共享。
+ * 同 inode 才能证明是 system-shared;否则这次显式登录本身足以证明它是实例隔离凭证。
+ */
+function detectFinalizedCodexLoginCredentialScope(
+ codexHome: string,
+): NonNullable<AuthState['credentialScope']> {
+ try {
+ const localStat = fs.statSync(path.join(codexHome, 'auth.json'));
+ const systemStat = fs.statSync(getSystemCodexAuthPath());
+ if (localStat.ino === systemStat.ino && localStat.dev === systemStat.dev) {
+ return 'system-shared';
+ }
+ } catch {
+ /* 显式登录已证明来源;无法证明同 inode 时按实例隔离处理。 */
+ }
+ return 'instance-isolated';
+}
+
/** 删除 Cindy 自管且无法按账号归属的 Codex 模型 cache。 */
async function removeDesktopCodexModelsCache(codexHome: string): Promise<boolean> {
const cachePath = path.join(codexHome, 'models_cache.json');
@@ -256,9 +345,10 @@ async function removeDesktopCodexModelsCache(codexHome: string): Promise<boolean
*/
export async function clearCodexAuthBoundaryStateBeforeLogin(
codexHome: string = getCodexHome(),
+ options?: { forceRemoveAuth?: boolean },
): Promise<boolean> {
const authPath = path.join(codexHome, 'auth.json');
- if (shouldSuppressLocalCodexAuth(codexHome, authPath)) {
+ if (options?.forceRemoveAuth || shouldSuppressLocalCodexAuth(codexHome, authPath)) {
try {
await fsp.rm(authPath, { force: true });
} catch (err) {
@@ -267,7 +357,9 @@ export async function clearCodexAuthBoundaryStateBeforeLogin(
});
}
}
- const authReady = !shouldSuppressLocalCodexAuth(codexHome, authPath);
+ const authReady = options?.forceRemoveAuth
+ ? !existsSync(authPath)
+ : !shouldSuppressLocalCodexAuth(codexHome, authPath);
const cacheReady = await removeDesktopCodexModelsCache(codexHome);
return authReady && cacheReady;
}
@@ -428,9 +520,7 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
}
// 未连订阅 → gateway-spawn:鉴权前提 = XD 网关 key 存在(现状,字节级不变)。
const apiKey = readClaudeApiKey();
- return apiKey
- ? { authenticated: true }
- : { authenticated: false, errorReason: 'no_key' };
+ return apiKey ? { authenticated: true } : { authenticated: false, errorReason: 'no_key' };
}
async triggerLogin(): Promise<AuthState> {
@@ -504,11 +594,7 @@ export class DesktopClaudeAuthAdapter implements AuthAdapter {
// 仅 dev(非 packaged)生效,生产忽略;auth 走 ANTHROPIC_API_KEY,重定向 config
// dir 不影响鉴权。process.env 路线行不通(CLAUDE_CONFIG_DIR 在 boot 期被
// stripSensitiveAnthropicEnv 清掉),故经 getAuthEnv 注入子进程 env(覆盖优先)。
- if (
- process.env.XDT_USER_DATA_DIR &&
- !app.isPackaged &&
- !process.env.CLAUDE_CONFIG_DIR
- ) {
+ if (process.env.XDT_USER_DATA_DIR && !app.isPackaged && !process.env.CLAUDE_CONFIG_DIR) {
env.CLAUDE_CONFIG_DIR = path.join(app.getPath('userData'), 'claude-home');
}
return env;
@@ -572,6 +658,17 @@ type PendingCodexLogin = {
cancelled: boolean;
};
+type CodexDisconnectIntent = {
+ /** 显式 logout / 用户取消是单调升级意图;后到的 server invalidation 不能把它降级。 */
+ explicitRequested: boolean;
+ /** 当前磁盘 marker 已足以抑制残留 local auth;unlink 失败时仍可继续安全收口。 */
+ invalidationMarkerCommitted: boolean;
+ /** 显式 durable sentinel 是否已在最后一次 marker 改写之后提交。 */
+ explicitBoundaryCommitted: boolean;
+ /** async cleanup 完成后关闭合并窗口;迟到意图会同步重申最终边界,不能改坏 settle 结果。 */
+ acceptingIntent: boolean;
+};
+
const MAX_COALESCED_LOGIN_PROGRESS_CHARS = 64 * 1024;
export class DesktopCodexAuthAdapter implements AuthAdapter {
@@ -580,6 +677,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
private pendingLogin: PendingCodexLogin | null = null;
/** logout 全流程的线性化点;其间新登录排队到凭证清理和解绑全部完成之后。 */
private logoutOperation: Promise<void> | null = null;
+ /** 在途 logout/invalidation 的可升级意图;显式断开永远不能被 preserve 路径降级。 */
+ private logoutIntent: CodexDisconnectIntent | null = null;
private loginAborted = false;
/** CLI 和凭证 finalize 都未收口时接受取消;成功结果返回后才关闭窗口。 */
private loginCancellationOpen = false;
@@ -608,7 +707,10 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
* invalidate() 触发时收口 host 侧鉴权派生状态,再把 auth state 推给 renderer。
* 由 maker-host 注入并允许 async — 适配层不直接 import IPC channel 常量,保持单向依赖。
*/
- private onInvalidatedBroadcast?: (reason: string) => void | Promise<void>;
+ private onInvalidatedBroadcast?: (
+ reason: string,
+ credentialScope: NonNullable<AuthState['credentialScope']>,
+ ) => void | Promise<void>;
/**
* 「本机已有的 Codex OAuth 凭证刚被认领到当前 owner」的收口回调(由 maker-host 注入)。
@@ -621,7 +723,13 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
*/
private onOAuthBindingClaimed?: () => void | Promise<void>;
private oauthInvalidatedReason: string | null = null;
+ private oauthInvalidatedCredentialScope: AuthState['credentialScope'] = undefined;
+ /** Replacement token exists but has not yet passed an account-level app-server RPC. */
+ private oauthRecoveryRequiredReason: string | null = null;
+ private oauthRecoveryCredentialScope: AuthState['credentialScope'] = undefined;
private suppressSystemCodexReconcile = false;
+ /** 运行期最近一次能够被文件/授权记录明确证明的来源,兜住系统 auth 原子替换后的旧硬链。 */
+ private lastKnownCodexCredentialScope: AuthState['credentialScope'] = undefined;
/**
* 进行中的 ensureGlobalCodexAssets 调用 —— 同一时刻并发进入直接复用同一 Promise,
@@ -677,6 +785,22 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
);
this.suppressSystemCodexReconcile = restored.suppressReconcile;
this.oauthInvalidatedReason = restored.invalidatedReason;
+ this.oauthInvalidatedCredentialScope = restored.invalidatedReason
+ ? (restored.credentialScope ?? 'unknown')
+ : undefined;
+ this.oauthRecoveryRequiredReason = restored.recoveryRequiredReason ?? null;
+ this.oauthRecoveryCredentialScope = restored.recoveryRequiredReason
+ ? (restored.credentialScope ?? 'unknown')
+ : undefined;
+ if (restored.credentialScope && restored.credentialScope !== 'unknown') {
+ this.lastKnownCodexCredentialScope = restored.credentialScope;
+ }
+ // If the primary invalidation marker could not be written, invalidate() persists a provider
+ // revocation as the cross-restart fallback. Keep system reconcile suppressed even though the
+ // richer reason/scope marker is unavailable.
+ if (!this.suppressSystemCodexReconcile && isNativeProviderAuthRevoked('openai')) {
+ this.suppressSystemCodexReconcile = true;
+ }
}
/**
@@ -756,10 +880,34 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (this.oauthInvalidatedReason) return;
const authPath = path.join(this.codexHome, 'auth.json');
if (shouldSuppressLocalCodexAuth(this.codexHome, authPath)) return;
+ const recoveryMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ const recoveryOwnerId =
+ recoveryMarker?.credentialScope === 'system-shared' &&
+ typeof recoveryMarker.recoveryOwnerId === 'string'
+ ? recoveryMarker.recoveryOwnerId
+ : null;
let claimed = false;
try {
- claimed = claimDetectedNativeProviderAuth('openai', () => this.hasCodexOAuthLoginUnbound());
- if (claimed) log.info('codex OAuth credential auto-bound to current owner after reconcile');
+ if (recoveryOwnerId) {
+ // The renewed system credential is recovery of the owner relationship captured at
+ // invalidation time. Never let generic legacy auto-claim hand it to a different Cindy
+ // owner, but also do not let an older legacyClaimOwner strand the original owner.
+ if (
+ getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, getSystemCodexAuthPath()) !==
+ null
+ ) {
+ return;
+ }
+ claimed = restoreNativeProviderAuthForRecovery('openai', recoveryOwnerId, () =>
+ this.hasCodexOAuthLoginUnbound(),
+ );
+ if (claimed) {
+ log.info('renewed shared Codex OAuth credential restored to invalidated owner');
+ }
+ } else {
+ claimed = claimDetectedNativeProviderAuth('openai', () => this.hasCodexOAuthLoginUnbound());
+ if (claimed) log.info('codex OAuth credential auto-bound to current owner after reconcile');
+ }
} catch (err) {
log.warn('codex OAuth binding claim failed', {
error: err instanceof Error ? err.message : String(err),
@@ -800,10 +948,16 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
this.ensureInvalidationMarkerLoaded();
if (this.suppressSystemCodexReconcile) {
const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
- if (marker && markerMatchesCurrentSystemCodexAuth(marker, getSystemCodexAuthPath())) return;
+ // marker 丢失时保持本进程 fail-closed;磁盘写失败不能变成下一次调用立刻回灌坏 token。
+ if (!marker) return;
+ if (getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, getSystemCodexAuthPath())) {
+ return;
+ }
this.suppressSystemCodexReconcile = false;
this.oauthInvalidatedReason = null;
- clearInvalidatedSystemCodexAuthMarker(this.codexHome);
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.oauthRecoveryRequiredReason = marker.reason;
+ this.oauthRecoveryCredentialScope = marker.credentialScope ?? 'unknown';
}
const systemAuth = getSystemCodexAuthPath();
@@ -816,7 +970,10 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
try {
const sysStat = await fsp.stat(systemAuth);
const myStat = await fsp.stat(myAuth);
- if (sysStat.ino === myStat.ino && sysStat.dev === myStat.dev) return;
+ if (sysStat.ino === myStat.ino && sysStat.dev === myStat.dev) {
+ this.lastKnownCodexCredentialScope = 'system-shared';
+ return;
+ }
} catch {
/* stat 失败走完整流程 */
}
@@ -844,6 +1001,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
const { kind, error } = await relinkSharedCodexAuth(systemAuth, myAuth);
switch (kind) {
case 'linked':
+ this.lastKnownCodexCredentialScope = 'system-shared';
log.info('codex auth.json linked with ~/.codex (shared)');
break;
case 'link-unsupported':
@@ -950,7 +1108,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
}
/** maker-host 注入: invalidate() 触发后收口派生状态并给 renderer push auth state。 */
- setOnInvalidatedBroadcast(cb: (reason: string) => void | Promise<void>): void {
+ setOnInvalidatedBroadcast(
+ cb: (
+ reason: string,
+ credentialScope: NonNullable<AuthState['credentialScope']>,
+ ) => void | Promise<void>,
+ ): void {
this.onInvalidatedBroadcast = cb;
}
@@ -987,7 +1150,11 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
await this.clearStaleInvalidationIfSystemCodexChanged();
}
if (this.oauthInvalidatedReason) {
- return { authenticated: false, errorReason: this.oauthInvalidatedReason };
+ return {
+ authenticated: false,
+ errorReason: this.oauthInvalidatedReason,
+ credentialScope: this.oauthInvalidatedCredentialScope ?? 'unknown',
+ };
}
// 先 reconcile —— 新用户首次打开 xdt-maker 时, 如果本机已登过 codex,
@@ -997,14 +1164,23 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
await this.reconcileWithSystemCodex();
}
if (options?.credentialMode === 'oauth-bearer') {
- const localState = await this.readLocalCodexAuthState();
+ const rawLocalState = await this.readLocalCodexAuthState();
+ const localState =
+ rawLocalState.authSource === 'oauth'
+ ? { ...rawLocalState, credentialScope: this.readCodexCredentialScope() }
+ : rawLocalState;
if (localState.authenticated) {
const accessToken = await this.getAccessToken();
- if (accessToken) return localState;
+ if (accessToken) return this.withCodexRecoveryRequirement(localState);
}
+ if (this.oauthRecoveryRequiredReason) return this.codexRecoveryRequiredErrorState();
return { authenticated: false, errorReason: localState.errorReason ?? 'no_oauth' };
}
- const localState = await this.readLocalCodexAuthState();
+ const rawLocalState = await this.readLocalCodexAuthState();
+ const localState =
+ rawLocalState.authSource === 'oauth'
+ ? { ...rawLocalState, credentialScope: this.readCodexCredentialScope() }
+ : rawLocalState;
// 绑定 gate(与 provider 目录 connected / getAccessToken 同口径,对齐 Anthropic 侧
// readClaudeAiOAuth 的读取层校验):auth.json 是与系统 CLI 共享的存储,凭证在、但
// openai 未绑定到当前 owner 时,不得以 OAuth 已连接示人 —— 否则设置页显示「已连接」
@@ -1030,8 +1206,9 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (!localState.authSource && readClaudeApiKey()) {
return { ...localState, authSource: 'api-key' };
}
- return localState;
+ return this.withCodexRecoveryRequirement(localState);
}
+ if (this.oauthRecoveryRequiredReason) return this.codexRecoveryRequiredErrorState();
// proxy 路线: 无 OAuth 登录但配了 api key → 仍放行 codex 进程(折扣模型经 proxy 走 gateway 可用)。
// 单条 model 的可用性由 ModelSelector + proxy 路由把关, 不在这道全局 gate 上拦。
if (readClaudeApiKey()) {
@@ -1044,13 +1221,123 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (!this.oauthInvalidatedReason) return;
const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
if (!marker) return;
- if (markerMatchesCurrentSystemCodexAuth(marker, getSystemCodexAuthPath())) return;
+ if (getActiveInvalidatedSystemCodexAuthMarker(this.codexHome, getSystemCodexAuthPath())) {
+ return;
+ }
this.oauthInvalidatedReason = null;
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.oauthRecoveryRequiredReason = marker.reason;
+ this.oauthRecoveryCredentialScope = marker.credentialScope ?? 'unknown';
this.suppressSystemCodexReconcile = false;
- clearInvalidatedSystemCodexAuthMarker(this.codexHome);
await this.reconcileWithSystemCodex();
}
+ private withCodexRecoveryRequirement(state: AuthState): AuthState {
+ if (!this.oauthRecoveryRequiredReason || state.authSource !== 'oauth') return state;
+ return {
+ ...state,
+ recoveryRequiredReason: this.oauthRecoveryRequiredReason,
+ credentialScope: this.oauthRecoveryCredentialScope ?? state.credentialScope ?? 'unknown',
+ };
+ }
+
+ private codexRecoveryRequiredErrorState(): AuthState {
+ return {
+ authenticated: false,
+ errorReason: this.oauthRecoveryRequiredReason ?? 'token_revoked',
+ credentialScope: this.oauthRecoveryCredentialScope ?? 'unknown',
+ };
+ }
+
+ /**
+ * Capture the exact owner, recovery marker and local OAuth credential that an account RPC is
+ * about to verify. Everything is read synchronously so no account/session transition can
+ * interleave halfway through the proof.
+ */
+ private captureRecoveryVerificationProof(): CodexRecoveryVerificationProof | null {
+ this.ensureInvalidationMarkerLoaded();
+ if (
+ !this.oauthRecoveryRequiredReason ||
+ this.pendingLogin !== null ||
+ this.logoutOperation !== null ||
+ isAppSessionBoundaryPending()
+ ) {
+ return null;
+ }
+ const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ const credential = readCodexRecoveryCredentialProof(path.join(this.codexHome, 'auth.json'));
+ if (!marker || !credential) return null;
+ const credentialScope =
+ this.oauthRecoveryCredentialScope ?? marker?.credentialScope ?? 'unknown';
+ return {
+ ownerScopeKey: activeOwnerScopeKey(),
+ reason: this.oauthRecoveryRequiredReason,
+ credentialScope,
+ markerFingerprint: JSON.stringify(marker),
+ ...credential,
+ };
+ }
+
+ /**
+ * A successful account-level RPC proves only the credential captured before that RPC. Compare
+ * the proof again before mutating the durable recovery boundary so a late response cannot clear
+ * a newer login, invalidation or Cindy owner. Persistence failures are fail-soft for the usage
+ * read but fail-closed for recovery: the pending reason remains authoritative.
+ */
+ private confirmRecoveryVerified(proof: CodexRecoveryVerificationProof): boolean {
+ const current = this.captureRecoveryVerificationProof();
+ if (!current || JSON.stringify(current) !== JSON.stringify(proof)) return false;
+
+ const credentialScope = proof.credentialScope;
+ if (credentialScope === 'system-shared') {
+ if (!clearInvalidatedSystemCodexAuthMarker(this.codexHome)) {
+ log.error('failed to clear verified Codex recovery marker');
+ return false;
+ }
+ this.suppressSystemCodexReconcile = false;
+ } else {
+ const persisted = writeInvalidatedSystemCodexAuthMarker(
+ this.codexHome,
+ getSystemCodexAuthPath(),
+ CODEX_USER_DISCONNECT_REASON,
+ undefined,
+ credentialScope,
+ );
+ if (!persisted) {
+ log.error('failed to persist verified Codex isolation boundary', { credentialScope });
+ return false;
+ }
+ this.suppressSystemCodexReconcile = true;
+ }
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ return true;
+ }
+
+ /** Bracket one account-level RPC with compare-and-commit recovery confirmation. */
+ async verifyRecoveryWithAccountRpc<T>(read: () => Promise<T>): Promise<T> {
+ const proof = this.captureRecoveryVerificationProof();
+ const result = await read();
+ if (!proof) return result;
+ try {
+ this.confirmRecoveryVerified(proof);
+ } catch (err) {
+ log.error('failed to confirm verified Codex recovery', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ return result;
+ }
+
+ private readCodexCredentialScope(): NonNullable<AuthState['credentialScope']> {
+ const detected = detectCodexCredentialScope(this.codexHome);
+ if (detected !== 'unknown') {
+ this.lastKnownCodexCredentialScope = detected;
+ return detected;
+ }
+ return this.lastKnownCodexCredentialScope ?? 'unknown';
+ }
+
private async readLocalCodexAuthState(): Promise<AuthState> {
const authPath = path.join(this.codexHome, 'auth.json');
if (!existsSync(authPath)) return { authenticated: false };
@@ -1128,8 +1415,8 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
operation.progressHistory.push(message);
operation.progressHistoryChars += message.length;
while (
- operation.progressHistoryChars > MAX_COALESCED_LOGIN_PROGRESS_CHARS
- && operation.progressHistory.length > 1
+ operation.progressHistoryChars > MAX_COALESCED_LOGIN_PROGRESS_CHARS &&
+ operation.progressHistory.length > 1
) {
operation.progressHistoryChars -= operation.progressHistory.shift()?.length ?? 0;
}
@@ -1150,9 +1437,7 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
() => operation.cancelled,
);
};
- const execution = waitFor
- ? waitFor.catch(() => undefined).then(start)
- : start();
+ const execution = waitFor ? waitFor.catch(() => undefined).then(start) : start();
const run = execution.finally(() => {
if (this.pendingLogin?.promise !== run) return;
this.pendingLogin = null;
@@ -1185,7 +1470,12 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// 交给 codex login(CLI 可能按“已有登录”直接退出而不重写);锁仍在时本轮 fail-closed,
// 用户重试会再次清理。
const cleanupFailure = await resolveCodexLoginCleanupPreflight(
- () => clearCodexAuthBoundaryStateBeforeLogin(this.codexHome),
+ () =>
+ clearCodexAuthBoundaryStateBeforeLogin(this.codexHome, {
+ forceRemoveAuth:
+ this.suppressSystemCodexReconcile &&
+ readInvalidatedSystemCodexAuthMarker(this.codexHome) === null,
+ }),
() => this.loginAborted,
);
if (cleanupFailure) return cleanupFailure;
@@ -1315,14 +1605,69 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (!localOAuthState.authenticated) return noOAuthFallback ?? localOAuthState;
// 系统文件仍是被判坏 / 被用户主动断开的原凭证时继续 suppress,避免覆盖新登录。
+ const priorRecoveryRequiredReason =
+ this.oauthInvalidatedReason ?? this.oauthRecoveryRequiredReason;
+ const finalizedCredentialScope = detectFinalizedCodexLoginCredentialScope(this.codexHome);
+ // marker 写盘失败时内存 suppress 是唯一安全边界。登录成功不能因为磁盘上恰好没有
+ // marker 就自动把同账号系统 token 链回来,覆盖刚拿到的 Cindy 凭证。
+ const missingMarkerFailClosed =
+ this.suppressSystemCodexReconcile &&
+ readInvalidatedSystemCodexAuthMarker(this.codexHome) === null;
+ const recoveryRequiredReason =
+ priorRecoveryRequiredReason ?? (missingMarkerFailClosed ? 'token_revoked' : null);
+ if (missingMarkerFailClosed) {
+ // 不记录新 local auth 的 fingerprint:这份 sentinel 只挡系统回灌,不能把刚登录成功的
+ // Cindy token 自己也标成失效。来源改为 unknown,因为 marker IO 失败后已无法证明这次
+ // 新凭证仍与原系统登录共享。
+ const restored = writeInvalidatedSystemCodexAuthMarker(
+ this.codexHome,
+ getSystemCodexAuthPath(),
+ recoveryRequiredReason ?? 'token_revoked',
+ undefined,
+ 'unknown',
+ );
+ if (!restored) {
+ log.error('failed to persist Codex reconcile-suppression sentinel after login');
+ return {
+ authenticated: false,
+ errorReason: 'login_finalize_error:failed_to_persist_auth_boundary',
+ };
+ }
+ }
+ if (recoveryRequiredReason) {
+ const marker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ if (
+ marker?.credentialScope !== finalizedCredentialScope &&
+ !updateInvalidatedSystemCodexAuthMarkerCredentialScope(
+ this.codexHome,
+ finalizedCredentialScope,
+ )
+ ) {
+ log.error('failed to persist finalized Codex recovery credential scope', {
+ credentialScope: finalizedCredentialScope,
+ });
+ return {
+ authenticated: false,
+ errorReason: 'login_finalize_error:failed_to_persist_auth_boundary',
+ };
+ }
+ }
this.oauthInvalidatedReason = null;
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.lastKnownCodexCredentialScope = finalizedCredentialScope;
+ if (recoveryRequiredReason) {
+ this.oauthRecoveryRequiredReason = recoveryRequiredReason;
+ this.oauthRecoveryCredentialScope = finalizedCredentialScope;
+ }
const { keepSuppressed } = settleInvalidationMarkerAfterLogin(
this.codexHome,
getSystemCodexAuthPath(),
);
- this.suppressSystemCodexReconcile = keepSuppressed;
- if (keepSuppressed) {
- log.warn('system codex auth.json marker still active; keeping reconcile suppressed after login');
+ this.suppressSystemCodexReconcile = keepSuppressed || missingMarkerFailClosed;
+ if (this.suppressSystemCodexReconcile) {
+ log.warn(
+ 'system codex auth.json marker still active; keeping reconcile suppressed after login',
+ );
} else {
await this.reconcileWithSystemCodexAfterLogin();
}
@@ -1360,21 +1705,65 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
if (this.currentLoginProc) terminateCodexLoginProcess(this.currentLoginProc);
}
- logout(opts?: { preserveInvalidatedReason?: boolean }): Promise<void> {
+ logout(opts?: {
+ preserveInvalidatedReason?: boolean;
+ invalidationMarkerCommitted?: boolean;
+ }): Promise<void> {
+ const explicitRequested = !opts?.preserveInvalidatedReason;
if (this.logoutOperation) {
// 登录可能在第一次 logout 之后排队、等待同一个 barrier。后来的 logout 仍代表更新的
// 用户意图,必须把这份 queued login 标成 cancelled,不能只复用旧 Promise 后让它启动。
this.cancelLogin();
+ if (this.logoutIntent) {
+ if (explicitRequested) {
+ this.logoutIntent.explicitRequested = true;
+ this.logoutIntent.explicitBoundaryCommitted = false;
+ }
+ if (opts?.preserveInvalidatedReason) {
+ // invalidate() has just replaced the in-memory reason and may also have rewritten the
+ // marker. An already-committed explicit boundary must be re-applied at the final
+ // synchronous settle point so user logout remains the winning intent.
+ if (this.logoutIntent.explicitRequested) {
+ this.logoutIntent.explicitBoundaryCommitted = false;
+ }
+ if (opts.invalidationMarkerCommitted) {
+ this.logoutIntent.invalidationMarkerCommitted = true;
+ }
+ }
+ if (!this.logoutIntent.acceptingIntent && this.logoutIntent.explicitRequested) {
+ // runLogout 的 async cleanup 已经结束,但 Promise.finally 还没清掉 operation。此时
+ // 迟到的 invalidation 可能刚改写 marker;同步重申 durable 边界,避免微任务顺序让
+ // server reason 覆盖已经完成的用户显式退出。
+ this.commitExplicitCodexDisconnectBoundary(this.logoutIntent);
+ try {
+ unbindNativeProviderAuth('openai', { revoked: true });
+ } catch (err) {
+ log.warn('late Codex logout intent upgrade failed to revoke provider binding', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ }
return this.logoutOperation;
}
- const run = this.runLogout(opts).finally(() => {
- if (this.logoutOperation === run) this.logoutOperation = null;
+ const intent: CodexDisconnectIntent = {
+ explicitRequested,
+ invalidationMarkerCommitted: opts?.invalidationMarkerCommitted === true,
+ explicitBoundaryCommitted: false,
+ acceptingIntent: true,
+ };
+ this.logoutIntent = intent;
+ const run = this.runLogout(intent).finally(() => {
+ if (this.logoutOperation === run) {
+ this.logoutOperation = null;
+ this.logoutIntent = null;
+ }
});
this.logoutOperation = run;
return run;
}
- private async runLogout(opts?: { preserveInvalidatedReason?: boolean }): Promise<void> {
+ private async runLogout(intent: CodexDisconnectIntent): Promise<void> {
this.ensureInvalidationMarkerLoaded();
// 登出与在途登录串行:先取消并等它完全收口,防迟到的 auth.json 在登出后复活账号。
const pendingLogin = this.pendingLogin?.promise;
@@ -1382,35 +1771,43 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
this.cancelLogin();
await pendingLogin.catch(() => undefined);
}
- await this.disconnectCodexOAuth(opts);
+ await this.disconnectCodexOAuth(intent);
+ }
+
+ private commitExplicitCodexDisconnectBoundary(intent: CodexDisconnectIntent): boolean {
+ if (!intent.explicitRequested || intent.explicitBoundaryCommitted) return false;
+ const persisted = writeInvalidatedSystemCodexAuthMarker(
+ this.codexHome,
+ getSystemCodexAuthPath(),
+ CODEX_USER_DISCONNECT_REASON,
+ path.join(this.codexHome, 'auth.json'),
+ );
+ if (!persisted) {
+ throw new Error('failed to persist Codex disconnect state');
+ }
+ intent.explicitBoundaryCommitted = true;
+ intent.invalidationMarkerCommitted = true;
+ this.oauthInvalidatedReason = null;
+ this.oauthInvalidatedCredentialScope = undefined;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
+ this.lastKnownCodexCredentialScope = undefined;
+ this.suppressSystemCodexReconcile = true;
+ return true;
}
/**
* 建立 durable Codex 断开边界并清理 host/cache。
* 调用方负责先处理 pendingLogin;登录 finalize 自身取消时不能等待自己的 Promise。
*/
- private async disconnectCodexOAuth(
- opts?: { preserveInvalidatedReason?: boolean },
- ): Promise<void> {
- let durableDisconnectCommitted = false;
- if (!opts?.preserveInvalidatedReason) {
- const systemAuthPath = getSystemCodexAuthPath();
- this.oauthInvalidatedReason = null;
- // 先持久化 durable 用户断开 sentinel,再删本地 auth;否则下一次 provider refetch
- // 会立刻从 ~/.codex 重建硬链。即使系统 auth 当前不存在也必须写:用户之后在 CLI
- // 登录仍不应绕过这里的显式断开。写失败时 fail-closed,不假报登出成功。
- const persisted = writeInvalidatedSystemCodexAuthMarker(
- this.codexHome,
- systemAuthPath,
- CODEX_USER_DISCONNECT_REASON,
- path.join(this.codexHome, 'auth.json'),
- );
- if (!persisted) {
- throw new Error('failed to persist Codex disconnect state');
- }
- durableDisconnectCommitted = true;
- this.suppressSystemCodexReconcile = true;
- }
+ private async disconnectCodexOAuth(intent?: CodexDisconnectIntent): Promise<void> {
+ const activeIntent: CodexDisconnectIntent = intent ?? {
+ explicitRequested: true,
+ invalidationMarkerCommitted: false,
+ explicitBoundaryCommitted: false,
+ acceptingIntent: true,
+ };
+ this.commitExplicitCodexDisconnectBoundary(activeIntent);
const authPath = path.join(this.codexHome, 'auth.json');
try {
await fsp.rm(authPath, { force: true });
@@ -1418,11 +1815,16 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// 显式 logout 已在 durable marker 处完成线性化:即使 Windows 文件锁让旧文件
// 暂时删不掉,所有 token 读取也会被 marker 抑制。继续做 host/cache/broadcast
// 收尾,避免仍在跑的 app-server 或 bridge 内存缓存继续持有旧凭证。
- // invalidate() 的 preserve 路径没有在本方法内证明 marker 已提交,保持原有抛错语义。
- if (!durableDisconnectCommitted) throw err;
- log.warn('remove Codex auth.json after durable disconnect failed; credential remains suppressed', {
- error: err instanceof Error ? err.message : String(err),
- });
+ // server invalidation 只要 marker 已提交,同样能安全抑制锁住的旧文件;marker 写失败时
+ // 仍继续收割 host/cache/binding 并广播引导,但本进程保持 suppress fail-closed。
+ log.warn(
+ activeIntent.invalidationMarkerCommitted
+ ? 'remove Codex auth.json after committed disconnect failed; credential remains suppressed'
+ : 'remove Codex auth.json after uncommitted invalidation failed; keeping process fail-closed',
+ {
+ error: err instanceof Error ? err.message : String(err),
+ },
+ );
}
// ⚠️ 不删 sessions/ —— 历史上这里会 `rm -rf sessions/` 清空所有 thread 的 rollout
// .jsonl(那是 resume 功能还不存在的年代留下的"登出即清本地状态"清理)。后来加了
@@ -1445,8 +1847,33 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
// 降低 Windows 文件锁概率;删失败仍由 disconnect marker + 内存快照清空保证 fail-closed,
// 下次登录前会再次清理并在锁未释放时拒绝继续。
await removeDesktopCodexModelsCache(this.codexHome);
- // 用户显式登出:除既有的 disconnect marker 外,再留一道跨 provider 统一的撤销标记。
- unbindNativeProviderAuth('openai', { revoked: true });
+ // invalidation 可能在显式 logout 进行中改写 marker;结束前再提交一次显式边界,保证
+ // 后到的用户意图永久胜出。该 helper 无 await,因此这里之后不会再接受竞态升级。
+ activeIntent.acceptingIntent = false;
+ const explicitBoundaryCommittedNow = this.commitExplicitCodexDisconnectBoundary(activeIntent);
+ if (explicitBoundaryCommittedNow && existsSync(authPath)) {
+ try {
+ await fsp.rm(authPath, { force: true });
+ } catch (err) {
+ // 升级后的 durable marker 已记录当前残留 local fingerprint;锁住时 token reads 仍被
+ // 抑制,删除可以继续 fail-soft。
+ log.warn('remove Codex auth.json after late explicit disconnect upgrade failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ // 只有用户显式登出才留下跨 provider 的 revoked 标记。服务端 token invalidation 只是
+ // 清掉当前坏凭证,不能阻止用户在 ChatGPT App 重新登录后被 Cindy 自动认领。
+ try {
+ unbindNativeProviderAuth(
+ 'openai',
+ activeIntent.explicitRequested ? { revoked: true } : undefined,
+ );
+ } catch (err) {
+ log.warn('unbind Codex OAuth provider after disconnect failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
}
async getAuthEnv(options?: AuthAdapterOptions): Promise<Record<string, string>> {
@@ -1509,7 +1936,9 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
try {
const raw = fs.readFileSync(path.join(this.codexHome, 'auth.json'), 'utf-8');
const parsed = JSON.parse(raw) as { tokens?: { access_token?: unknown } };
- return typeof parsed.tokens?.access_token === 'string' && parsed.tokens.access_token.length > 0;
+ return (
+ typeof parsed.tokens?.access_token === 'string' && parsed.tokens.access_token.length > 0
+ );
} catch {
return false;
}
@@ -1578,20 +2007,94 @@ export class DesktopCodexAuthAdapter implements AuthAdapter {
async invalidate(reason: string): Promise<void> {
this.ensureInvalidationMarkerLoaded();
log.warn('codex auth invalidated', { reason });
+ const localAuthPath = path.join(this.codexHome, 'auth.json');
+ const existingMarker = readInvalidatedSystemCodexAuthMarker(this.codexHome);
+ if (
+ existingMarker !== null &&
+ isDurableDisconnectMarker(existingMarker) &&
+ (!existsSync(localAuthPath) || shouldSuppressLocalCodexAuth(this.codexHome, localAuthPath))
+ ) {
+ // 显式 logout 已经完成后,旧 host/request 的迟到 401 不能重新弹“请登录”。新一次
+ // Cindy 登录会写入不同的 local auth,届时 shouldSuppressLocal=false,真实的新凭证
+ // invalidation 仍会正常进入下面的收口。
+ log.info('ignoring stale Codex invalidation after explicit disconnect', { reason });
+ return;
+ }
// 服务端已经明确判定 OAuth 凭证失效时, 不能再从 ~/.codex 自动 reconcile 回来。
// 否则 app-server 会拿同一份坏 token 继续 spawn/retry, 用户也看不到明确的重登录入口。
+ const credentialScope = this.readCodexCredentialScope();
+ const activeOwnerId = getActiveAppSession().dataOwnerId;
+ const recoveryOwnerId =
+ credentialScope === 'system-shared' && activeOwnerId && isNativeProviderAuthBound('openai')
+ ? activeOwnerId
+ : undefined;
this.oauthInvalidatedReason = reason;
+ this.oauthInvalidatedCredentialScope = credentialScope;
+ this.oauthRecoveryRequiredReason = null;
+ this.oauthRecoveryCredentialScope = undefined;
this.suppressSystemCodexReconcile = true;
- writeInvalidatedSystemCodexAuthMarker(
+ const markerCommitted = writeInvalidatedSystemCodexAuthMarker(
this.codexHome,
getSystemCodexAuthPath(),
reason,
- path.join(this.codexHome, 'auth.json'),
+ localAuthPath,
+ credentialScope,
+ recoveryOwnerId,
);
- await this.logout({ preserveInvalidatedReason: true });
+ let durableFallbackCommitted = false;
+ let effectiveCredentialScope = credentialScope;
+ if (!markerCommitted) {
+ log.error('failed to persist Codex invalidation marker; keeping process fail-closed', {
+ reason,
+ credentialScope,
+ });
+ try {
+ // Without the fingerprint marker we cannot safely auto-claim a future system credential:
+ // persist the existing provider revocation as a coarser cross-restart boundary instead.
+ // Recovery then requires an explicit Cindy login, so the user-facing source becomes unknown.
+ unbindNativeProviderAuth('openai', { revoked: true });
+ durableFallbackCommitted = isNativeProviderAuthRevoked('openai');
+ if (durableFallbackCommitted) {
+ effectiveCredentialScope = 'unknown';
+ this.oauthInvalidatedCredentialScope = effectiveCredentialScope;
+ }
+ } catch (err) {
+ log.error('failed to persist fallback Codex provider revocation', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ }
+ // Stop synchronous one-shot/provider reads before async file/host cleanup. The marker normally
+ // suppresses the old local file too; early unbind is the fail-closed fallback when marker IO
+ // failed or Windows keeps auth.json locked.
+ try {
+ unbindNativeProviderAuth('openai');
+ } catch (err) {
+ log.warn('early unbind after Codex invalidation failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ try {
+ await this.logout({
+ preserveInvalidatedReason: true,
+ invalidationMarkerCommitted: markerCommitted || durableFallbackCommitted,
+ });
+ } catch (err) {
+ // A concurrent explicit logout may fail to commit its durable sentinel. The server-proven
+ // invalidation still needs to reach the renderer instead of disappearing behind that failure.
+ log.warn('Codex invalidation cleanup did not fully settle', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ if (
+ this.oauthInvalidatedReason !== reason ||
+ this.oauthInvalidatedCredentialScope !== effectiveCredentialScope
+ ) {
+ return;
+ }
if (this.onInvalidatedBroadcast) {
try {
- await this.onInvalidatedBroadcast(reason);
+ await this.onInvalidatedBroadcast(reason, effectiveCredentialScope);
} catch (e) {
log.warn('onInvalidatedBroadcast threw', { error: (e as Error).message });
}
diff --git a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
index 8e3fd0ba74..c691f6a261 100644
--- a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
+++ b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
@@ -5,10 +5,11 @@
* 从 auth-adapters 拆出来, 不依赖 Electron, 路径显式注入, 可单测。
*
* 标记语义: 服务端判定某份 OAuth token 失效 (refresh_token reuse / 401 reauth_required) 时,
- * 把当时 ~/.codex/auth.json 的文件指纹 (dev/ino/size/mtimeMs) 落盘。只要该指纹和当前系统
- * 文件仍然一致, 就说明 ~/.codex 里躺着的还是那份被判坏的 token —— reconcile 绝不能把它
- * 硬链回 codex-home 覆盖有效凭证。普通失效标记在指纹变化 (用户在本机 CLI 重登) 后过期;
- * 用户显式断开产生的 durable marker 是例外,系统 CLI 后续任何变化都不能自动接回。
+ * 把失效凭证的文件指纹 (dev/ino/size/mtimeMs + sha256) 落盘。系统共享凭证在本机
+ * ChatGPT/Codex 重新登录、系统 auth.json 换成另一份内容后过期;系统文件暂时缺失时继续
+ * 保持失效提示。实例隔离凭证则完全不受系统 auth.json 变化影响:Cindy 写入新凭证后只解除
+ * 错误展示,marker 继续阻止系统凭证回灌。用户显式断开产生的 durable marker 是例外,系统
+ * CLI 后续任何变化都不能自动接回。
*
* 背景 (2026-07-03 线上实踩):
* token 失效 → 用户在 Cindy 里重新授权成功 → 旧实现无条件清掉标记和 suppress →
@@ -18,6 +19,9 @@
import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';
+import type { AuthState } from '@cindy/maker-core';
+
+type CodexCredentialScope = NonNullable<AuthState['credentialScope']>;
/**
* 用户主动断开 Cindy 内的 Codex OAuth;这是 durable sentinel:系统 CLI 后续刷新 / 重登
@@ -28,6 +32,10 @@ export const CODEX_USER_DISCONNECT_REASON = 'user_disconnected';
/** 失效标记文件内容: 失效原因 + 当时 ~/.codex/auth.json 的文件指纹。 */
export type InvalidatedSystemCodexAuthMarker = {
reason: string;
+ /** 失效前 Cindy 使用的是系统共享凭证、实例隔离凭证,还是无法判断。 */
+ credentialScope?: CodexCredentialScope;
+ /** 系统共享凭证失效时所属的 Cindy data owner;只允许该 owner 恢复原绑定。 */
+ recoveryOwnerId?: string;
/** 用户曾在 Cindy 显式断开;后续 transient token invalidation 不得解除这道永久抑制。 */
durableDisconnect?: boolean;
dev: number;
@@ -63,18 +71,27 @@ export function readInvalidatedSystemCodexAuthMarker(
parsed.localSize !== undefined ||
parsed.localMtimeMs !== undefined ||
parsed.localSha256 !== undefined;
- const validLocalFingerprint = !hasLocalFingerprint || (
- typeof parsed.localDev === 'number' &&
- typeof parsed.localIno === 'number' &&
- typeof parsed.localSize === 'number' &&
- typeof parsed.localMtimeMs === 'number' &&
- (parsed.localSha256 === undefined || typeof parsed.localSha256 === 'string')
- );
+ const validLocalFingerprint =
+ !hasLocalFingerprint ||
+ (typeof parsed.localDev === 'number' &&
+ typeof parsed.localIno === 'number' &&
+ typeof parsed.localSize === 'number' &&
+ typeof parsed.localMtimeMs === 'number' &&
+ (parsed.localSha256 === undefined || typeof parsed.localSha256 === 'string'));
const validDurableDisconnect =
parsed.durableDisconnect === undefined || typeof parsed.durableDisconnect === 'boolean';
+ const validCredentialScope =
+ parsed.credentialScope === undefined ||
+ parsed.credentialScope === 'system-shared' ||
+ parsed.credentialScope === 'instance-isolated' ||
+ parsed.credentialScope === 'unknown';
+ const validRecoveryOwnerId =
+ parsed.recoveryOwnerId === undefined || typeof parsed.recoveryOwnerId === 'string';
if (
typeof parsed.reason === 'string' &&
validDurableDisconnect &&
+ validCredentialScope &&
+ validRecoveryOwnerId &&
typeof parsed.dev === 'number' &&
typeof parsed.ino === 'number' &&
typeof parsed.size === 'number' &&
@@ -96,7 +113,7 @@ export function readInvalidatedSystemCodexAuthMarker(
}
/** 兼容最初只靠 reason 表示的 user_disconnected marker。 */
-function isDurableDisconnectMarker(marker: InvalidatedSystemCodexAuthMarker): boolean {
+export function isDurableDisconnectMarker(marker: InvalidatedSystemCodexAuthMarker): boolean {
return marker.reason === CODEX_USER_DISCONNECT_REASON || marker.durableDisconnect === true;
}
@@ -126,10 +143,33 @@ function currentAuthFileFingerprint(authPath: string): {
export function currentSystemCodexAuthMarker(
systemAuthPath: string,
reason: string,
+ credentialScope?: CodexCredentialScope,
): InvalidatedSystemCodexAuthMarker | null {
const fingerprint = currentAuthFileFingerprint(systemAuthPath);
if (!fingerprint) return null;
- return { reason, ...fingerprint };
+ return { reason, ...(credentialScope ? { credentialScope } : {}), ...fingerprint };
+}
+
+function persistInvalidatedSystemCodexAuthMarker(
+ codexHome: string,
+ marker: InvalidatedSystemCodexAuthMarker,
+): boolean {
+ const file = getCodexAuthInvalidationMarkerPath(codexHome);
+ const tempFile = `${file}.${process.pid}.${Date.now()}.tmp`;
+ try {
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ // Same-directory temp + rename: a crash or failed write cannot truncate an existing marker.
+ fs.writeFileSync(tempFile, JSON.stringify(marker, null, 2), 'utf-8');
+ fs.renameSync(tempFile, file);
+ return true;
+ } catch {
+ try {
+ fs.unlinkSync(tempFile);
+ } catch {
+ /* no-op */
+ }
+ return false;
+ }
}
function fileMatchesInvalidatedMarker(
@@ -208,8 +248,23 @@ export function getActiveInvalidatedSystemCodexAuthMarker(
): InvalidatedSystemCodexAuthMarker | null {
const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
if (!marker) return null;
+ // 实例隔离或来源不明的凭证都不能靠 ~/.codex 变化证明已经恢复;UI 会引导用户在 Cindy
+ // 重新登录。新的 local auth 不再匹配坏凭证 fingerprint,但 marker 仍负责抑制系统回灌。
+ if (marker.credentialScope === 'instance-isolated' || marker.credentialScope === 'unknown') {
+ return marker;
+ }
+ // 系统共享凭证被删除通常意味着 ChatGPT App 已退出登录,而不是已经恢复。继续保留
+ // 指引,直到 App/CLI 写入一份与坏 token 不同的新 auth.json。
+ if (
+ marker.credentialScope === 'system-shared' &&
+ currentAuthFileFingerprint(systemAuthPath) === null
+ ) {
+ return marker;
+ }
if (markerMatchesCurrentSystemCodexAuth(marker, systemAuthPath)) return marker;
- clearInvalidatedSystemCodexAuthMarker(codexHome);
+ // The system credential changed, so this marker no longer blocks reconcile. Keep the raw marker
+ // until an account-level RPC confirms the replacement token: it is the durable evidence that a
+ // fresh renderer mount must not expose "recovered" from file presence alone.
return null;
}
@@ -222,22 +277,59 @@ export function writeInvalidatedSystemCodexAuthMarker(
systemAuthPath: string,
reason: string,
localAuthPath?: string,
+ credentialScope?: CodexCredentialScope,
+ recoveryOwnerId?: string,
): boolean {
const previous = readInvalidatedSystemCodexAuthMarker(codexHome);
const durableDisconnect =
reason === CODEX_USER_DISCONNECT_REASON ||
(previous !== null && isDurableDisconnectMarker(previous));
+ const localFingerprint = localAuthPath ? currentAuthFileFingerprint(localAuthPath) : null;
// 主动断开不依赖系统文件当前是否存在,也不随其指纹变化失效;零值只是兼容既有 marker schema
// 的 durable sentinel。已有 durable sentinel 后的普通 token invalidation 也继承该属性,
// 即使系统文件暂时不存在也要把新的失败原因落盘,不能退回可自动 reconcile 的普通 marker。
- const marker = currentSystemCodexAuthMarker(systemAuthPath, reason) ?? (
- durableDisconnect
- ? { reason, dev: 0, ino: 0, size: 0, mtimeMs: 0 }
- : null
- );
+ // system-shared 的 local auth 可能因 ChatGPT App 原子替换系统文件而成为旧硬链。此时真正
+ // 被服务端判坏的是 local 指向的旧 inode,不是系统路径上已经换新的凭证;优先记录 local
+ // 指纹,让下一次检测能立即认出系统登录已经更新并安全 relink。
+ const sharedInvalidatedCredential: InvalidatedSystemCodexAuthMarker | null =
+ credentialScope === 'system-shared' && localFingerprint
+ ? {
+ reason,
+ credentialScope,
+ dev: localFingerprint.dev,
+ ino: localFingerprint.ino,
+ size: localFingerprint.size,
+ mtimeMs: localFingerprint.mtimeMs,
+ sha256: localFingerprint.sha256,
+ }
+ : null;
+ const marker: InvalidatedSystemCodexAuthMarker | null =
+ sharedInvalidatedCredential ??
+ currentSystemCodexAuthMarker(systemAuthPath, reason, credentialScope) ??
+ (durableDisconnect
+ ? {
+ reason,
+ ...(credentialScope ? { credentialScope } : {}),
+ dev: 0,
+ ino: 0,
+ size: 0,
+ mtimeMs: 0,
+ }
+ : credentialScope === 'instance-isolated' || credentialScope === 'unknown'
+ ? {
+ reason,
+ credentialScope,
+ dev: 0,
+ ino: 0,
+ size: 0,
+ mtimeMs: 0,
+ }
+ : null);
if (!marker) return false;
+ if (credentialScope === 'system-shared' && recoveryOwnerId) {
+ marker.recoveryOwnerId = recoveryOwnerId;
+ }
if (durableDisconnect) marker.durableDisconnect = true;
- const localFingerprint = localAuthPath ? currentAuthFileFingerprint(localAuthPath) : null;
if (localFingerprint) {
marker.localDev = localFingerprint.dev;
marker.localIno = localFingerprint.ino;
@@ -245,39 +337,36 @@ export function writeInvalidatedSystemCodexAuthMarker(
marker.localMtimeMs = localFingerprint.mtimeMs;
marker.localSha256 = localFingerprint.sha256;
}
- const file = getCodexAuthInvalidationMarkerPath(codexHome);
- const tempFile = `${file}.${process.pid}.${Date.now()}.tmp`;
- try {
- fs.mkdirSync(path.dirname(file), { recursive: true });
- // 同目录临时文件 + rename:崩溃 / 磁盘写失败不能把已有 durable marker 截断成坏 JSON。
- fs.writeFileSync(tempFile, JSON.stringify(marker, null, 2), 'utf-8');
- fs.renameSync(tempFile, file);
- return true;
- } catch {
- try {
- fs.unlinkSync(tempFile);
- } catch {
- /* no-op */
- }
- return false;
- }
+ return persistInvalidatedSystemCodexAuthMarker(codexHome, marker);
}
-/** marker 记录的正是当前残留 local auth 时,该文件属于已断开或已失效的旧凭证。 */
-export function shouldSuppressLocalCodexAuth(
+/** Preserve the invalidated fingerprint while recording the proven scope of a replacement login. */
+export function updateInvalidatedSystemCodexAuthMarkerCredentialScope(
codexHome: string,
- localAuthPath: string,
+ credentialScope: CodexCredentialScope,
): boolean {
const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
- return Boolean(marker && localFileMatchesInvalidatedMarker(marker, localAuthPath));
+ if (!marker) return false;
+ return persistInvalidatedSystemCodexAuthMarker(codexHome, { ...marker, credentialScope });
}
-/** 删标记 (幂等)。 */
-export function clearInvalidatedSystemCodexAuthMarker(codexHome: string): void {
+/** marker 记录的正是当前残留 local auth 时,该文件属于已断开或已失效的旧凭证。 */
+export function shouldSuppressLocalCodexAuth(codexHome: string, localAuthPath: string): boolean {
+ const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
+ return Boolean(
+ marker &&
+ (localFileMatchesInvalidatedMarker(marker, localAuthPath) ||
+ fileMatchesInvalidatedMarker(marker, localAuthPath)),
+ );
+}
+
+/** 删标记 (幂等);返回持久化边界是否已确认清除。 */
+export function clearInvalidatedSystemCodexAuthMarker(codexHome: string): boolean {
try {
fs.unlinkSync(getCodexAuthInvalidationMarkerPath(codexHome));
- } catch {
- /* no-op */
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException | null)?.code === 'ENOENT';
}
}
@@ -296,6 +385,15 @@ export function settleInvalidationMarkerAfterLogin(
codexHome: string,
systemAuthPath: string,
): { keepSuppressed: boolean } {
+ const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
+ if (marker?.credentialScope === 'instance-isolated' || marker?.credentialScope === 'unknown') {
+ // 新 local OAuth 已经替换掉 marker 记录的坏凭证,所以错误展示可以由调用方清掉;但这
+ // 份登录本来就是 Cindy 内的隔离登录(或来路无法证明),不能紧接着恢复 system
+ // reconcile。否则同账号的 ~/.codex/auth.json 会立刻重新硬链回来,把刚写入的新 token
+ // 覆盖掉。marker 留作 durable suppression sentinel;local fingerprint 已不同,因此不会
+ // 抑制这份新凭证。已有 durableDisconnect 也必须原样保留。
+ return { keepSuppressed: true };
+ }
return {
keepSuppressed: getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuthPath) != null,
};
@@ -307,38 +405,71 @@ export function settleInvalidationMarkerAfterLogin(
* → 恢复「已失效」展示态 (invalidatedReason) + suppress reconcile。
* - 标记指纹匹配 + 本地 auth.json 仍是被判坏的系统 auth.json (硬链或相同内容)
* → 恢复「已失效」展示态 + suppress reconcile。
- * - 标记指纹匹配 + 本地 auth.json 存在且不同于坏系统 auth.json (上次运行里已重新登录成功)
- * → 只 suppress (继续挡住坏 token), 不进失效态 —— 用户重启后应直接是已授权,
- * 标记只负责阻止 ~/.codex 里的坏 token 被 reconcile 回来。
- * - 标记指纹不匹配 (系统文件已变) → 清标记, 一切正常。
+ * - 标记指纹匹配 + 本地 auth.json 已替换 → 继续 suppress 坏系统 token,并持久返回
+ * recoveryRequiredReason,直到账号级 RPC 确认新凭证。
+ * - 标记指纹不匹配 (系统文件已变) → 允许 reconcile 新文件,但保留标记作为
+ * 待验证恢复证据。
* - 用户主动断开 sentinel → 始终只 suppress、不展示错误,也不随系统文件变化自动失效。
*/
export function restoreInvalidationStateOnStartup(
codexHome: string,
systemAuthPath: string,
localAuthPath: string,
-): { suppressReconcile: boolean; invalidatedReason: string | null } {
+): {
+ suppressReconcile: boolean;
+ invalidatedReason: string | null;
+ recoveryRequiredReason?: string;
+ credentialScope?: CodexCredentialScope;
+} {
+ const persistedMarker = readInvalidatedSystemCodexAuthMarker(codexHome);
+ if (!persistedMarker) {
+ return { suppressReconcile: false, invalidatedReason: null };
+ }
const marker = getActiveInvalidatedSystemCodexAuthMarker(codexHome, systemAuthPath);
if (!marker) {
- return { suppressReconcile: false, invalidatedReason: null };
+ // A changed system auth.json is only a recovery candidate. Reconcile may consume it, but the
+ // renderer must perform an account RPC before replacing the actionable invalidation prompt.
+ return {
+ suppressReconcile: false,
+ invalidatedReason: null,
+ ...(persistedMarker.credentialScope
+ ? { credentialScope: persistedMarker.credentialScope }
+ : {}),
+ ...(isDurableDisconnectMarker(persistedMarker)
+ ? {}
+ : { recoveryRequiredReason: persistedMarker.reason }),
+ };
}
// marker 是 logout 的提交点。若进程在「写 marker → unlink auth」之间崩溃,启动时按
// local fingerprint 识别并清掉旧凭证;即使删除失败,readLocalCodexAuthState 也会忽略它。
- if (isDurableDisconnectMarker(marker) && localFileMatchesInvalidatedMarker(marker, localAuthPath)) {
+ if (
+ isDurableDisconnectMarker(marker) &&
+ localFileMatchesInvalidatedMarker(marker, localAuthPath)
+ ) {
try {
fs.unlinkSync(localAuthPath);
} catch {
/* read path 仍会按 marker fingerprint 抑制,不能让残留文件复活登录态。 */
}
}
+ const localExists = fs.existsSync(localAuthPath);
+ const hasReplacementLocalCredential =
+ localExists &&
+ !fileMatchesInvalidatedMarker(marker, localAuthPath) &&
+ !localFileMatchesInvalidatedMarker(marker, localAuthPath);
+ const recoveryRequiredReason =
+ !isDurableDisconnectMarker(marker) && hasReplacementLocalCredential
+ ? marker.reason
+ : undefined;
return {
suppressReconcile: true,
- invalidatedReason: marker.reason === CODEX_USER_DISCONNECT_REASON
- ? null
- : fs.existsSync(localAuthPath) &&
- !fileMatchesInvalidatedMarker(marker, localAuthPath) &&
- !localFileMatchesInvalidatedMarker(marker, localAuthPath)
+ ...(marker.credentialScope ? { credentialScope: marker.credentialScope } : {}),
+ ...(recoveryRequiredReason ? { recoveryRequiredReason } : {}),
+ invalidatedReason:
+ marker.reason === CODEX_USER_DISCONNECT_REASON
? null
- : marker.reason,
+ : hasReplacementLocalCredential
+ ? null
+ : marker.reason,
};
}
diff --git a/apps/desktop/src/main/maker-host/codex-model-discovery.ts b/apps/desktop/src/main/maker-host/codex-model-discovery.ts
index 2ca0898f00..c9713a6e21 100644
--- a/apps/desktop/src/main/maker-host/codex-model-discovery.ts
+++ b/apps/desktop/src/main/maker-host/codex-model-discovery.ts
@@ -20,6 +20,7 @@ import type { CatalogModel } from '@cindy/model-providers';
import type { CodexModelListItem } from '@cindy/maker-core';
import { shouldSuppressLocalCodexAuth } from './codex-auth-invalidation.js';
+import { isNativeProviderAuthBound } from './nativeProviderAuthBinding.js';
interface CodexModelRaw {
slug?: unknown;
@@ -208,6 +209,7 @@ function desktopCodexHome(): string {
/** 仅在 Cindy 当前确有未被 disconnect marker 抑制的 OAuth token 时读取模型 cache。 */
async function hasActiveDesktopCodexOAuth(codexHome: string): Promise<boolean> {
+ if (!isNativeProviderAuthBound('openai')) return false;
const authPath = path.join(codexHome, 'auth.json');
if (shouldSuppressLocalCodexAuth(codexHome, authPath)) return false;
try {
diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.ts
index d7b2ad6589..0f6078682b 100644
--- a/apps/desktop/src/main/maker-host/index.ts
+++ b/apps/desktop/src/main/maker-host/index.ts
@@ -1250,7 +1250,7 @@ export function getMaker(): Maker {
// logout + 这里这个 broadcast, 让 useCodexAuth hook 立刻进 'unauthenticated' 状态,
// UI 弹 "请重新登录" — 否则错误只会反复埋在后台日志里。payload 字段对齐
// maker-ipc/auth.ts logout handler 的 broadcast 形态。
- desktopCodexAuthAdapter.setOnInvalidatedBroadcast(async (reason) => {
+ desktopCodexAuthAdapter.setOnInvalidatedBroadcast(async (reason, credentialScope) => {
resetProviderModelAutoRefreshCooldowns('openai');
resetCodexModelBackfillState();
// 运行中 401/token invalidation 不经过 maker:auth:logout IPC,必须在这里做同一套
@@ -1278,6 +1278,7 @@ export function getMaker(): Maker {
agentKind: 'codex' as const,
authenticated: false,
errorReason: reason,
+ credentialScope,
};
for (const win of BrowserWindow.getAllWindows()) {
if (win.isDestroyed()) continue;
diff --git a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
index ad8a59884c..34a0feb3c9 100644
--- a/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
+++ b/apps/desktop/src/main/maker-host/nativeProviderAuthBinding.ts
@@ -88,11 +88,6 @@ function readBindingsOrFail(): BindingRead {
}
}
-function readBindings(): BindingFile {
- const read = readBindingsOrFail();
- return read.ok ? read.bindings : {};
-}
-
function writeBindings(value: BindingFile): void {
const file = bindingPath();
fs.mkdirSync(path.dirname(file), { recursive: true });
@@ -103,12 +98,25 @@ function writeBindings(value: BindingFile): void {
/** Return true only when the native OAuth credential is explicitly bound to this owner. */
export function isNativeProviderAuthBound(provider: NativeProviderId): boolean {
+ const read = readBindingsOrFail();
+ if (!read.ok) return false;
+ const bindings = read.bindings;
+ // Revocation describes the credential itself, not the current app owner. It must therefore
+ // remain authoritative during signed-out/bootstrap reads too; otherwise a residual local token
+ // can be treated as bound before an owner session has committed.
+ if (bindings.revoked && provider in bindings.revoked) return false;
const owner = getActiveAppSession().dataOwnerId;
// During unit/bootstrap code paths there may be no committed owner yet.
// Owner-bound sessions are fail-closed; pre-session callers retain legacy
// behavior until authentication commits an owner boundary.
if (!owner) return true;
- return readBindings()[provider] === owner;
+ return bindings[provider] === owner;
+}
+
+/** Whether an explicit durable revocation currently suppresses this provider credential. */
+export function isNativeProviderAuthRevoked(provider: NativeProviderId): boolean {
+ const read = readBindingsOrFail();
+ return Boolean(read.ok && read.bindings.revoked && provider in read.bindings.revoked);
}
/** Bind newly completed native OAuth to the current data owner. */
@@ -279,3 +287,26 @@ export function claimDetectedNativeProviderAuth(
writeBindings({ ...bindings, [provider]: owner });
return true;
}
+
+/**
+ * Restore a provider binding only for the owner that was using the credential when it was
+ * invalidated. This is intentionally narrower than generic auto-claim: a renewed shared system
+ * credential is recovery of an existing owner relationship, so `legacyClaimOwner` must not strand
+ * that owner, while account switches and explicit revocation still fail closed.
+ */
+export function restoreNativeProviderAuthForRecovery(
+ provider: NativeProviderId,
+ expectedOwner: string,
+ hasCredential: () => boolean,
+): boolean {
+ const owner = getActiveAppSession().dataOwnerId;
+ if (!owner || owner !== expectedOwner || isAppSessionBoundaryPending()) return false;
+ const read = readBindingsOrFail();
+ if (!read.ok) return false;
+ const bindings = read.bindings;
+ if (bindings.revoked && provider in bindings.revoked) return false;
+ if (!hasCredential()) return false;
+ if (provider in bindings) return bindings[provider] === expectedOwner;
+ writeBindings({ ...bindings, [provider]: expectedOwner });
+ return true;
+}
diff --git a/apps/desktop/src/main/maker-ipc/usage.ts b/apps/desktop/src/main/maker-ipc/usage.ts
index adb4f4bb49..2c986b2973 100644
--- a/apps/desktop/src/main/maker-ipc/usage.ts
+++ b/apps/desktop/src/main/maker-ipc/usage.ts
@@ -100,7 +100,10 @@ function fingerprintClaudeToken(token: string): string {
}
/** 读订阅凭证 + 顺手刷新「当前凭证」内存缓存(headers listener 消费)。 */
-function readClaudeCredentialsInfo(): { accessToken: string; subscriptionType: string | null } | null {
+function readClaudeCredentialsInfo(): {
+ accessToken: string;
+ subscriptionType: string | null;
+} | null {
const oauth = readClaudeAiOAuth();
_claudeCredentialsKnown = true;
if (!oauth) {
@@ -118,11 +121,12 @@ function readClaudeCredentialsInfo(): { accessToken: string; subscriptionType: s
const claudeSubscriptionUsageReader = createClaudeSubscriptionUsageReader({
readCredentials: readClaudeCredentialsInfo,
- fetchSnapshot: (credentials) => fetchClaudeSubscriptionUsageSnapshot({
- accessToken: credentials.accessToken,
- subscriptionType: credentials.subscriptionType,
- claudeCodeVersion: readClaudeCodeVersionBestEffort(),
- }),
+ fetchSnapshot: (credentials) =>
+ fetchClaudeSubscriptionUsageSnapshot({
+ accessToken: credentials.accessToken,
+ subscriptionType: credentials.subscriptionType,
+ claudeCodeVersion: readClaudeCodeVersionBestEffort(),
+ }),
recordSnapshot: recordClaudeSubscriptionUsageSnapshot,
clearSnapshot: clearClaudeSubscriptionUsageSnapshot,
readCachedSnapshot: readClaudeSubscriptionUsageSnapshot,
@@ -191,17 +195,13 @@ export function registerMakerUsageIpc(maker: Maker): void {
const codexRateLimitResetService = createCodexRateLimitResetService({
readRateLimits: () => maker.readAgentAccountRateLimits('codex'),
- consumeResetCredit: (params) => (
- maker.consumeAgentAccountRateLimitResetCredit('codex', params)
- ),
+ consumeResetCredit: (params) => maker.consumeAgentAccountRateLimitResetCredit('codex', params),
readAccountIdentity: async () => {
const state = await maker.getAgentAuthState('codex');
- const accountId = state.authSource === 'oauth'
- ? await desktopCodexAuthAdapter.getAccountId()
- : null;
- const identity = state.authSource === 'oauth' && state.identity?.includes('@')
- ? state.identity
- : null;
+ const accountId =
+ state.authSource === 'oauth' ? await desktopCodexAuthAdapter.getAccountId() : null;
+ const identity =
+ state.authSource === 'oauth' && state.identity?.includes('@') ? state.identity : null;
return { email: identity, accountId };
},
recordRateLimitSnapshot: recordCodexAccountUsageSnapshot,
@@ -210,7 +210,11 @@ export function registerMakerUsageIpc(maker: Maker): void {
registerMakerUsageHandlers(createElectronIpcHandlerRegistry(), {
readAgentTodayUsage,
readCodexAccountUsageSnapshot: readCodexAccountUsageSnapshotWithWebRefresh,
- readCodexRateLimits: codexRateLimitResetService.read,
+ // Bind recovery confirmation to the exact owner, marker and OAuth credential observed before
+ // this account-level RPC. A stale response still returns its usage payload but cannot consume a
+ // newer recovery state.
+ readCodexRateLimits: () =>
+ desktopCodexAuthAdapter.verifyRecoveryWithAccountRpc(() => codexRateLimitResetService.read()),
consumeCodexRateLimitReset: codexRateLimitResetService.consume,
readClaudeSubscriptionUsageSnapshot: () => claudeSubscriptionUsageReader.read(),
readClaudeAccountUsageSnapshot,
@@ -234,7 +238,7 @@ export function registerMakerUsageIpc(maker: Maker): void {
if (currentToken) {
if (requestBearerToken !== currentToken) {
currentToken = readClaudeCredentialsInfo()?.accessToken ?? null;
- if (requestBearerToken !== currentToken) return false; // 归属不符 (换号尾巴), 丢弃
+ if (requestBearerToken !== currentToken) return false; // 归属不符 (换号尾巴), 丢弃
}
const fingerprint = _currentClaudeFingerprint;
void recordClaudeSubscriptionUsageSnapshot(
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 4745a8889c..6e92ac37be 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -2629,6 +2629,9 @@ contextBridge.exposeInMainWorld('electronAPI', {
// Open URL in system default browser
openExternal: (url: string): Promise<{ success: boolean }> =>
ipcRenderer.invoke('shell:open-external', url),
+ /** 打开本机 ChatGPT Desktop;main 端固定使用受限的 codex: 协议,不接收 URL。 */
+ openChatGPTApp: (): Promise<{ success: boolean }> =>
+ ipcRenderer.invoke('shell:open-chatgpt-app'),
// file-chip 右键菜单 "在浏览器中查看": 把本地文件用 file:// 喂给系统
// 默认浏览器(或 .html/.pdf/.svg 等扩展名的默认 handler)。main 端会再做
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index 3733875bc0..ff577c0dc7 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -15,10 +15,24 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { ProviderView } from '@cindy/model-providers';
-const { wizardSpy, providersState } = vi.hoisted(() => ({
- wizardSpy: vi.fn(),
- providersState: { providers: [] as unknown[], order: [] as string[] },
-}));
+const { wizardSpy, providersState, codexAuthState, codexAuthActions, toastError } = vi.hoisted(
+ () => ({
+ wizardSpy: vi.fn(),
+ providersState: { providers: [] as unknown[], order: [] as string[] },
+ codexAuthState: {
+ state: { kind: 'unauthenticated' } as Record<string, unknown>,
+ reconnectCredentialScope: undefined as string | undefined,
+ recoveryCheck: 'idle' as 'idle' | 'checking' | 'failed',
+ },
+ codexAuthActions: {
+ refresh: vi.fn(async () => undefined),
+ triggerLogin: vi.fn(async () => 'authenticated'),
+ cancelLogin: vi.fn(async () => undefined),
+ logout: vi.fn(async () => undefined),
+ },
+ toastError: vi.fn(),
+ }),
+);
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }),
@@ -41,10 +55,8 @@ vi.mock('@/contexts/AuthContext', () => ({
vi.mock('@/hooks/useCodexAuth', () => ({
isChatGptConnectionConnected: () => false,
useCodexAuth: () => ({
- state: { kind: 'unauthenticated' },
- triggerLogin: vi.fn(),
- cancelLogin: vi.fn(),
- logout: vi.fn(),
+ ...codexAuthState,
+ ...codexAuthActions,
}),
}));
@@ -61,7 +73,7 @@ vi.mock('@/components/ui/confirm-dialog-provider', () => ({
}));
vi.mock('@/lib/toast', () => ({
- toast: { error: vi.fn(), success: vi.fn() },
+ toast: { error: toastError, success: vi.fn() },
}));
vi.mock('@/lib/customProviders', () => ({
@@ -137,6 +149,10 @@ function renderAt(search: string) {
}
beforeEach(() => {
+ codexAuthState.state = { kind: 'unauthenticated' };
+ codexAuthState.reconnectCredentialScope = undefined;
+ codexAuthState.recoveryCheck = 'idle';
+ providersState.order = [];
providersState.providers = [
makeProvider('anthropic', { name: 'Anthropic' }),
makeProvider('xd', {
@@ -152,6 +168,7 @@ beforeEach(() => {
requestProviderModelsAutoRefresh: vi.fn(async () => ({ ok: true })),
setProviderOrder: vi.fn(async () => ({ ok: true })),
},
+ openChatGPTApp: vi.fn(async () => ({ success: true })),
};
});
@@ -161,6 +178,64 @@ afterEach(() => {
});
describe('ProvidersSection — 深链定位', () => {
+ it('ChatGPT 系统共享登录失效时显示来源说明并打开 ChatGPT App', async () => {
+ codexAuthState.state = {
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ };
+ codexAuthState.reconnectCredentialScope = 'system-shared';
+ providersState.providers = [
+ makeProvider('openai', {
+ name: 'OpenAI',
+ agents: ['codex', 'claude-code'],
+ connected: false,
+ models: { codex: [], 'claude-code': [] },
+ }),
+ ];
+ renderAt('?tab=providers&connect=openai');
+
+ const openAiListRow = await screen.findByRole('button', { name: /OpenAI/ });
+ expect(openAiListRow.textContent).toContain('settings.providers.openai.reconnectRequired');
+ expect((openAiListRow.lastElementChild as HTMLElement).style.backgroundColor).toBe(
+ 'var(--remote-status-failed)',
+ );
+ expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).not.toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
+
+ await waitFor(() => expect(window.electronAPI.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(codexAuthActions.triggerLogin).not.toHaveBeenCalled();
+ });
+
+ it('ChatGPT App 打开失败时保留恢复入口并提示用户', async () => {
+ codexAuthState.state = {
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ };
+ codexAuthState.reconnectCredentialScope = 'system-shared';
+ providersState.providers = [
+ makeProvider('openai', {
+ name: 'OpenAI',
+ agents: ['codex', 'claude-code'],
+ connected: false,
+ models: { codex: [], 'claude-code': [] },
+ }),
+ ];
+ vi.mocked(window.electronAPI.openChatGPTApp).mockRejectedValueOnce(
+ new Error('bridge unavailable'),
+ );
+ renderAt('?tab=providers&connect=openai');
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
+
+ await waitFor(() =>
+ expect(toastError).toHaveBeenCalledWith('chatgptAuthRecovery.openAppFailed'),
+ );
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' })).not.toBeNull();
+ expect(codexAuthActions.triggerLogin).not.toHaveBeenCalled();
+ });
+
it('connect=anthropic(未占行内置渠道)→ 向导 builtin 直达;参数消费后清除', async () => {
renderAt('?tab=providers&connect=anthropic');
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 5b5b22aff9..f5fd993b0f 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -181,10 +181,26 @@ export function ErrorBanner({
// AUTH_STATE_CHANGED 都会让现存横幅同步恢复 Retry;后续失效 / 登出广播也会撤销恢复态。
// 非连接错误期间暂停订阅时 hook 会同时清掉旧快照;下次失效先保持“需重连”,直到
// 新 getState() 或广播确认已恢复,避免跨 error 复用过期的 authenticated 状态。
- const { state: openAiAuthState } = useCodexAuth({ enabled: isOpenAiConnectionExpired });
+ const {
+ state: openAiAuthState,
+ reconnectCredentialScope,
+ recoveryCheck: openAiRecoveryCheck,
+ refresh: refreshOpenAiAuth,
+ } = useCodexAuth({
+ enabled: isOpenAiConnectionExpired,
+ recoveryHint: isOpenAiConnectionExpired ? { reason: error } : undefined,
+ });
const openAiConnectionRecoveredSinceError =
isOpenAiConnectionExpired && isChatGptConnectionConnected(openAiAuthState, false);
const openAiReconnectRequired = isOpenAiConnectionExpired && !openAiConnectionRecoveredSinceError;
+ const openAiAuthLoading = openAiAuthState.kind === 'loading';
+ const openAiLoginPending = openAiAuthState.kind === 'login-pending';
+ const openAiRecoveryBusy =
+ openAiAuthLoading || openAiRecoveryCheck === 'checking' || openAiLoginPending;
+ const openAiCredentialScope =
+ openAiAuthState.kind === 'reconnect-required'
+ ? (openAiAuthState.credentialScope ?? 'unknown')
+ : (reconnectCredentialScope ?? 'unknown');
// 网络类错误(502/连接失败/fetch failed 等):友好文案 + 原始错误折叠可查。
// Codex `Reconnecting... N/M` 额外解析次数,让 recoverable 状态持续更新而非裸英文。
const reconnectAttempt = parseReconnectAttemptMessage(error);
@@ -236,8 +252,14 @@ export function ErrorBanner({
: t('chat.errorBanner.codexAuthMissing');
} else if (isOpenAiConnectionExpired) {
displayError = openAiConnectionRecoveredSinceError
- ? t('chat.errorBanner.codexSessionReconnected')
- : t('chat.errorBanner.codexSessionExpired');
+ ? t('chatgptAuthRecovery.recovered')
+ : t(
+ openAiCredentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.systemSharedInvalidated'
+ : openAiCredentialScope === 'instance-isolated'
+ ? 'chatgptAuthRecovery.instanceIsolatedInvalidated'
+ : 'chatgptAuthRecovery.unknownInvalidated',
+ );
} else if (isCodexLocalOAuthAuthMissing) {
displayError = t('chat.errorBanner.codexAuthMissingLocal');
} else if (isClaudeGatewayOpusPlanMismatch) {
@@ -256,11 +278,7 @@ export function ErrorBanner({
attempt: overloadRetryProgress.attempt,
maxAttempts: overloadRetryProgress.maxAttempts,
})
- : t(
- safeRetryText
- ? 'chat.errorBanner.overloadBusy'
- : 'chat.errorBanner.overloadBusyNoRetry',
- );
+ : t(safeRetryText ? 'chat.errorBanner.overloadBusy' : 'chat.errorBanner.overloadBusyNoRetry');
} else if (isNetworkishError) {
// 网络类错误:原始英文报错(502/ECONNREFUSED/fetch failed 等)对用户没有
// 行动价值,换成友好文案;原始错误折叠可查(下方「查看原始错误」)。
@@ -313,6 +331,24 @@ export function ErrorBanner({
}
};
+ const handleOpenAiRecovery = async (): Promise<void> => {
+ if (openAiRecoveryBusy) return;
+ if (openAiRecoveryCheck === 'failed') {
+ await refreshOpenAiAuth();
+ return;
+ }
+ if (openAiCredentialScope === 'system-shared') {
+ try {
+ const result = await window.electronAPI.openChatGPTApp();
+ if (!result.success) toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ } catch {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ return;
+ }
+ promptCodexSessionExpired(error);
+ };
+
// 走跟 Settings/RemoteHostDetail 同款的 check → confirm → sync 三步:
// 1. checkCodexAuth: 探远端是否已有 auth.json (有则要 confirm 覆盖)
// 2. 弹 confirm dialog: 显安全警告 + "共享 SSH 账号 = 凭证可能被偷"
@@ -430,20 +466,38 @@ export function ErrorBanner({
)}
</div>
{openAiReconnectRequired && (
- // OAuth 更新是低打扰的内联恢复入口:错误出现时不抢焦点,用户明确点击后
- // 才打开浏览器连接。历史尾部与当前错误使用同一行为。
+ // 系统共享凭证必须回 ChatGPT App 修复;Cindy 独立凭证才启动 Cindy OAuth。
+ // 登录候选出现后先走账号级服务端探测,探测成功前继续隐藏请求 Retry。
<button
type="button"
- onClick={() => promptCodexSessionExpired(error)}
+ onClick={() => void handleOpenAiRecovery()}
+ disabled={openAiRecoveryBusy}
className={cn(
'shrink-0 flex select-none items-center gap-1 text-xs font-medium',
'text-[var(--text-primary)]',
'hover:opacity-70 transition-opacity',
+ 'disabled:cursor-not-allowed disabled:opacity-50',
+ )}
+ title={t(
+ openAiRecoveryCheck === 'failed'
+ ? 'chatgptAuthRecovery.recheck'
+ : openAiRecoveryBusy
+ ? 'chatgptAuthRecovery.checking'
+ : openAiCredentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.openApp'
+ : 'chatgptAuthRecovery.relogin',
)}
- title={t('chat.errorBanner.codexSessionExpiredLogin')}
>
- <RefreshCw size={12} />
- {t('chat.errorBanner.codexSessionExpiredLogin')}
+ <Spinner icon={RefreshCw} size={12} spinning={openAiRecoveryBusy} />
+ {t(
+ openAiRecoveryBusy
+ ? 'chatgptAuthRecovery.checking'
+ : openAiRecoveryCheck === 'failed'
+ ? 'chatgptAuthRecovery.recheck'
+ : openAiCredentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.openApp'
+ : 'chatgptAuthRecovery.relogin',
+ )}
</button>
)}
{isClaudeGatewayOpusPlanMismatch && onSwitchToClaudeSubscription && (
diff --git a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
index 6c5047a277..247d038016 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -15,6 +15,8 @@ type AuthStateChangedPayload = {
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ recoveryRequiredReason?: string;
};
const mocks = vi.hoisted(() => ({
@@ -25,6 +27,8 @@ const mocks = vi.hoisted(() => ({
logout: vi.fn(),
onStateChanged: vi.fn(),
onLoginProgress: vi.fn(),
+ getCodexRateLimits: vi.fn(),
+ openChatGPTApp: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn(),
runtimeRoute: vi.fn(() => ({ authInjection: 'env-key' as const })),
@@ -77,11 +81,14 @@ describe('ErrorBanner OpenAI connection recovery', () => {
identity: '[email protected]',
authSource: 'oauth' as const,
};
+ mocks.getState.mockResolvedValue(result);
emitCodexStateChanged(result);
return result;
});
mocks.cancelLogin.mockResolvedValue(undefined);
mocks.logout.mockResolvedValue(undefined);
+ mocks.getCodexRateLimits.mockResolvedValue({ rateLimits: null, resetOffer: null });
+ mocks.openChatGPTApp.mockResolvedValue({ success: true });
mocks.onStateChanged.mockImplementation(
(listener: (payload: AuthStateChangedPayload) => void) => {
mocks.stateChangedListeners.add(listener);
@@ -101,7 +108,9 @@ describe('ErrorBanner OpenAI connection recovery', () => {
onStateChanged: typeof mocks.onStateChanged;
onLoginProgress: typeof mocks.onLoginProgress;
};
+ usage: { getCodexRateLimits: typeof mocks.getCodexRateLimits };
};
+ openChatGPTApp: typeof mocks.openChatGPTApp;
};
}
).electronAPI = {
@@ -114,10 +123,191 @@ describe('ErrorBanner OpenAI connection recovery', () => {
onStateChanged: mocks.onStateChanged,
onLoginProgress: mocks.onLoginProgress,
},
+ usage: { getCodexRateLimits: mocks.getCodexRateLimits },
},
+ openChatGPTApp: mocks.openChatGPTApp,
};
});
+ it('opens the ChatGPT App for an invalidated system-shared login', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ render(
+ <ErrorBanner
+ error="token_revoked"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ modelId="gpt-5.4"
+ providerId="openai"
+ />,
+ );
+
+ expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
+
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
+ });
+
+ it('keeps the recovery action disabled until the credential source is known', async () => {
+ const initialState = deferred<AuthStateChangedPayload>();
+ mocks.getState.mockImplementationOnce(() => initialState.promise);
+ render(
+ <ErrorBanner
+ error="token_revoked"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ modelId="gpt-5.4"
+ providerId="openai"
+ />,
+ );
+
+ const checkingButton = screen.getByRole('button', {
+ name: 'chatgptAuthRecovery.checking',
+ }) as HTMLButtonElement;
+ expect(checkingButton.disabled).toBe(true);
+ fireEvent.click(checkingButton);
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
+
+ await act(async () => {
+ initialState.resolve({
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ await initialState.promise;
+ });
+ expect(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' })).toBeTruthy();
+ });
+
+ it('does not restore retry on a fresh mount until the replacement account probe succeeds', async () => {
+ const verification = deferred<{ rateLimits: null; resetOffer: null }>();
+ mocks.getState
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'token_revoked',
+ })
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ mocks.getCodexRateLimits.mockImplementationOnce(() => verification.promise);
+ render(
+ <ErrorBanner
+ error="token_revoked"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ modelId="gpt-5.4"
+ providerId="openai"
+ />,
+ );
+
+ expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).toBeTruthy();
+ expect(screen.queryByText('chatgptAuthRecovery.recovered')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
+
+ await act(async () => {
+ verification.resolve({ rateLimits: null, resetOffer: null });
+ await verification.promise;
+ });
+ expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
+ });
+
+ it('keeps the recovery action available when the ChatGPT App cannot be opened', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ mocks.openChatGPTApp.mockResolvedValueOnce({ success: false });
+ render(
+ <ErrorBanner
+ error="token_revoked"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ modelId="gpt-5.4"
+ providerId="openai"
+ />,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
+
+ await waitFor(() => {
+ expect(mocks.toastError).toHaveBeenCalledWith('chatgptAuthRecovery.openAppFailed');
+ });
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
+ });
+
+ it('keeps the recovery action available when opening the ChatGPT App rejects', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ mocks.openChatGPTApp.mockRejectedValueOnce(new Error('bridge unavailable'));
+ render(
+ <ErrorBanner
+ error="token_revoked"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ modelId="gpt-5.4"
+ providerId="openai"
+ />,
+ );
+
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
+
+ await waitFor(() => {
+ expect(mocks.toastError).toHaveBeenCalledWith('chatgptAuthRecovery.openAppFailed');
+ });
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' })).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
+ });
+
+ it('uses Cindy OAuth for an invalidated instance-isolated login', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ render(
+ <ErrorBanner
+ error="token_revoked"
+ retryText="retry this turn"
+ onRetry={vi.fn()}
+ agentKind="codex"
+ modelId="gpt-5.4"
+ providerId="openai"
+ />,
+ );
+
+ expect(await screen.findByText('chatgptAuthRecovery.instanceIsolatedInvalidated')).toBeTruthy();
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
+
+ await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
+ expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
+ });
+
it('waits for an explicit inline action and restores retry after success', async () => {
const { rerender } = render(
<ErrorBanner
@@ -130,14 +320,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
expect(mocks.confirm).not.toHaveBeenCalled();
expect(mocks.triggerLogin).not.toHaveBeenCalled();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
- fireEvent.click(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- );
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
await waitFor(() =>
expect(mocks.triggerLogin).toHaveBeenCalledWith(
@@ -146,8 +334,10 @@ describe('ErrorBanner OpenAI connection recovery', () => {
),
);
expect(mocks.confirm).not.toHaveBeenCalled();
- expect(mocks.toastSuccess).toHaveBeenCalledWith('logic.toasts.codexConnected');
- expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
+ await waitFor(() =>
+ expect(mocks.toastSuccess).toHaveBeenCalledWith('logic.toasts.codexConnected'),
+ );
+ expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
act(() => {
@@ -163,8 +353,8 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
});
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
- expect(screen.queryByText('chat.errorBanner.codexSessionReconnected')).toBeNull();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
+ expect(screen.queryByText('chatgptAuthRecovery.recovered')).toBeNull();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -183,9 +373,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- );
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
await waitFor(() =>
expect(mocks.triggerLogin).toHaveBeenCalledWith(
@@ -194,10 +382,8 @@ describe('ErrorBanner OpenAI connection recovery', () => {
),
);
expect(mocks.toastError).not.toHaveBeenCalled();
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
- expect(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- ).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -216,17 +402,13 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- );
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
await waitFor(() => {
expect(mocks.toastError).toHaveBeenCalledWith('settings.connections.codex.toast.loginFailed');
});
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
- expect(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- ).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -241,11 +423,9 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
expect(mocks.confirm).not.toHaveBeenCalled();
- fireEvent.click(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- );
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
await waitFor(() =>
expect(mocks.triggerLogin).toHaveBeenCalledWith(
@@ -253,11 +433,11 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect.objectContaining({ ownerId: expect.any(String) }),
),
);
- expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
+ expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
});
- it('classifies the wrapped thread/resume refresh-token failure as reconnect, not retry', () => {
+ it('classifies the wrapped thread/resume refresh-token failure as reconnect, not retry', async () => {
render(
<ErrorBanner
error="LAZY_CREATE_FAILED: Failed to resume Codex thread: Error: codex app-server thread/resume error -32600: failed to load configuration: Your access token could not be refreshed because your refresh token was revoked. Please log out and sign in again."
@@ -269,10 +449,8 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
- expect(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- ).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
+ expect(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -289,9 +467,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
);
expect(screen.getByText('token_revoked')).toBeTruthy();
- expect(
- screen.queryByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeNull();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
expect(mocks.getState).not.toHaveBeenCalled();
expect(mocks.stateChangedListeners.size).toBe(0);
@@ -310,9 +486,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
);
expect(screen.getByText('token_revoked')).toBeTruthy();
- expect(
- screen.queryByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeNull();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
expect(mocks.getState).not.toHaveBeenCalled();
expect(mocks.stateChangedListeners.size).toBe(0);
@@ -347,9 +521,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
render(<ErrorBanner {...props} retryText="retry this turn" onRetry={vi.fn()} />);
expect(screen.getByText(props.error)).toBeTruthy();
- expect(
- screen.queryByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- ).toBeNull();
+ expect(screen.queryByRole('button', { name: 'chatgptAuthRecovery.relogin' })).toBeNull();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
expect(mocks.getState).not.toHaveBeenCalled();
expect(mocks.stateChangedListeners.size).toBe(0);
@@ -371,14 +543,14 @@ describe('ErrorBanner OpenAI connection recovery', () => {
);
await waitFor(() => expect(settingsAuth.result.current.state.kind).toBe('reconnect-required'));
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
expect(mocks.triggerLogin).not.toHaveBeenCalled();
await act(async () => {
await expect(settingsAuth.result.current.triggerLogin()).resolves.toBe('authenticated');
});
- expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
+ expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
expect(mocks.triggerLogin).toHaveBeenCalledOnce();
});
@@ -386,6 +558,11 @@ describe('ErrorBanner OpenAI connection recovery', () => {
it('does not reuse recovered state after auth observation was disabled by another error', async () => {
const refreshedState = deferred<AuthStateChangedPayload>();
mocks.getState
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ })
.mockResolvedValueOnce({
authenticated: true,
identity: '[email protected]',
@@ -402,7 +579,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
+ expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
rerender(
@@ -427,8 +604,8 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
- expect(screen.queryByText('chat.errorBanner.codexSessionReconnected')).toBeNull();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
+ expect(screen.queryByText('chatgptAuthRecovery.recovered')).toBeNull();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
await act(async () => {
@@ -439,7 +616,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
await refreshedState.promise;
});
- expect(screen.getByText('chat.errorBanner.codexSessionExpired')).toBeTruthy();
+ expect(screen.getByText('chatgptAuthRecovery.unknownInvalidated')).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -463,18 +640,17 @@ describe('ErrorBanner OpenAI connection recovery', () => {
modelId="gpt-5.4"
/>,
);
- fireEvent.click(
- screen.getByRole('button', { name: 'chat.errorBanner.codexSessionExpiredLogin' }),
- );
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.relogin' }));
await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
await act(async () => {
+ mocks.getState.mockResolvedValue({ authenticated: true, authSource: 'oauth' });
emitCodexStateChanged({ authenticated: true, authSource: 'oauth' });
login.resolve({ authenticated: true, authSource: 'oauth' });
await expect(settingsOutcome).resolves.toBe('authenticated');
});
- expect(await screen.findByText('chat.errorBanner.codexSessionReconnected')).toBeTruthy();
+ expect(await screen.findByText('chatgptAuthRecovery.recovered')).toBeTruthy();
expect(mocks.triggerLogin).toHaveBeenCalledWith(
'codex',
expect.objectContaining({ ownerId: expect.any(String) }),
@@ -484,9 +660,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
it('cancels an owned reconnect when its prompt owner unmounts', async () => {
const login = deferred<AuthStateChangedPayload>();
mocks.triggerLogin.mockImplementation(() => login.promise);
- const prompt = renderHook(() =>
- useCodexSessionExpiredPrompt({ confirmBeforeLogin: false }),
- );
+ const prompt = renderHook(() => useCodexSessionExpiredPrompt({ confirmBeforeLogin: false }));
act(() => {
expect(prompt.result.current('token_revoked')).toBe(true);
@@ -535,6 +709,61 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(mocks.cancelLogin).not.toHaveBeenCalled();
});
+ it('uses the system-shared voice recovery copy and opens the ChatGPT App', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ mocks.confirm.mockResolvedValueOnce(true);
+ const prompt = renderHook(() => useCodexSessionExpiredPrompt());
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
+ });
+
+ await waitFor(() =>
+ expect(mocks.confirm).toHaveBeenCalledWith({
+ title: 'chatgptAuthRecovery.title',
+ description: 'chatgptAuthRecovery.systemSharedInvalidated',
+ confirmText: 'chatgptAuthRecovery.openApp',
+ cancelText: 'chatgptAuthRecovery.later',
+ autoFocusConfirm: true,
+ }),
+ );
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ });
+
+ it('keeps the original shared recovery flow when an authenticated hint cannot be verified', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ mocks.getCodexRateLimits.mockRejectedValueOnce(new Error('network unavailable'));
+ mocks.confirm.mockResolvedValueOnce(true);
+ const prompt = renderHook(() => useCodexSessionExpiredPrompt());
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
+ });
+
+ await waitFor(() =>
+ expect(mocks.confirm).toHaveBeenCalledWith({
+ title: 'chatgptAuthRecovery.title',
+ description: 'chatgptAuthRecovery.systemSharedInvalidated',
+ confirmText: 'chatgptAuthRecovery.openApp',
+ cancelText: 'chatgptAuthRecovery.later',
+ autoFocusConfirm: true,
+ }),
+ );
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.toastSuccess).not.toHaveBeenCalled();
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ });
+
it('exposes the explicit Continue After Reset action only when provided', () => {
const onContinueAfterUsageReset = vi.fn();
const { rerender } = render(
@@ -546,9 +775,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(
- screen.getByRole('button', { name: 'chat.errorBanner.continueAfterReset' }),
- );
+ fireEvent.click(screen.getByRole('button', { name: 'chat.errorBanner.continueAfterReset' }));
expect(onContinueAfterUsageReset).toHaveBeenCalledOnce();
rerender(
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index 6f51bc9bcd..81f3b043c9 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -20,15 +20,7 @@
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import {
- Check,
- GripVertical,
- MoreHorizontal,
- Pencil,
- Plus,
- RefreshCw,
- Trash2,
-} from 'lucide-react';
+import { Check, GripVertical, MoreHorizontal, Pencil, Plus, RefreshCw, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { useProviders } from '@/hooks/useProviders';
@@ -305,9 +297,7 @@ function DetailHeader({
})}
/>
)}
- {provider?.suspended && (
- <CustomTag label={t('settings.providers.pill.suspended')} />
- )}
+ {provider?.suspended && <CustomTag label={t('settings.providers.pill.suspended')} />}
{badge}
</div>
<span
@@ -463,7 +453,15 @@ function AnthropicHeader({
function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged: () => void }) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
- const { state, triggerLogin, cancelLogin, logout } = useCodexAuth();
+ const {
+ state,
+ reconnectCredentialScope,
+ recoveryCheck,
+ refresh,
+ triggerLogin,
+ cancelLogin,
+ logout,
+ } = useCodexAuth();
// 图像 API key 行(2026-07 图像多来源):ChatGPT 订阅 OAuth 调不了平台 images API
// (实测缺 scope),图像通道用独立的平台 key。仅当目录给 openai 声明了 imageModels
// 才渲染(远端目录可能撤掉该能力)。
@@ -473,6 +471,9 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
const reconnectRequired = state.kind === 'reconnect-required';
const loggingIn = state.kind === 'login-pending';
const connected = isChatGptConnectionConnected(state, provider?.connected ?? false);
+ const credentialScope = reconnectRequired
+ ? (state.credentialScope ?? 'unknown')
+ : (reconnectCredentialScope ?? 'unknown');
const handleLogout = useCallback(async () => {
const confirmed = await confirm({
@@ -496,11 +497,43 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
const outcome = await triggerLogin();
if (outcome === 'authenticated') {
onChanged();
+ } else if (outcome === 'unverified') {
+ toast.error(t('chatgptAuthRecovery.verificationFailed'));
} else if (outcome === 'failed') {
toast.error(t('settings.connections.codex.toast.loginFailed'));
}
}, [triggerLogin, onChanged, t]);
+ const handleRecovery = useCallback(async () => {
+ if (recoveryCheck === 'checking' || loggingIn) return;
+ if (recoveryCheck === 'failed') {
+ await refresh();
+ return;
+ }
+ if (credentialScope === 'system-shared') {
+ try {
+ const result = await window.electronAPI.openChatGPTApp();
+ if (!result.success) toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ } catch {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ return;
+ }
+ await handleLogin();
+ }, [credentialScope, handleLogin, loggingIn, recoveryCheck, refresh, t]);
+
+ const recoveryDetail = reconnectRequired ? (
+ <p className="text-12 leading-relaxed text-[var(--settings-integration-subtitle)]">
+ {t(
+ credentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.systemSharedInvalidated'
+ : credentialScope === 'instance-isolated'
+ ? 'chatgptAuthRecovery.instanceIsolatedInvalidated'
+ : 'chatgptAuthRecovery.unknownInvalidated',
+ )}
+ </p>
+ ) : null;
+
const trailing = connected ? (
<div className="flex shrink-0 items-center gap-2.5">
<ConnectedPill />
@@ -513,8 +546,17 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
<div className="flex shrink-0 items-center gap-2.5">
<ReconnectRequiredPill />
<PillButton
- label={t('settings.providers.openai.reconnect')}
- onClick={() => void handleLogin()}
+ label={t(
+ recoveryCheck === 'checking' || loggingIn
+ ? 'chatgptAuthRecovery.checking'
+ : recoveryCheck === 'failed'
+ ? 'chatgptAuthRecovery.recheck'
+ : credentialScope === 'system-shared'
+ ? 'chatgptAuthRecovery.openApp'
+ : 'chatgptAuthRecovery.relogin',
+ )}
+ onClick={() => void handleRecovery()}
+ disabled={recoveryCheck === 'checking' || loggingIn}
/>
</div>
) : (
@@ -538,7 +580,14 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
subtitle={t('settings.providers.openai.subtitle')}
trailing={trailing}
provider={provider}
- detail={imagesKeyRow || undefined}
+ detail={
+ recoveryDetail || imagesKeyRow ? (
+ <div className="flex flex-col gap-3">
+ {recoveryDetail}
+ {imagesKeyRow}
+ </div>
+ ) : undefined
+ }
/>
);
}
@@ -751,10 +800,8 @@ function GenericOAuthHeader({
const [loggingIn, setLoggingIn] = useState(false);
const connected = provider.connected;
const deviceFlow = provider.auth.oauth?.flow === 'device-code';
- const { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } = useProviderOAuthDeviceCode(
- provider.id,
- { observeProgress: deviceFlow },
- );
+ const { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } =
+ useProviderOAuthDeviceCode(provider.id, { observeProgress: deviceFlow });
const handleLogin = useCallback(async () => {
clearDeviceCode();
@@ -1168,10 +1215,8 @@ function CustomProviderHeader({
const [loggingIn, setLoggingIn] = useState(false);
const isOAuth = provider.auth.method === 'oauth' && !!provider.auth.oauth;
const deviceFlow = provider.auth.oauth?.flow === 'device-code';
- const { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } = useProviderOAuthDeviceCode(
- isOAuth ? provider.id : null,
- { observeProgress: deviceFlow },
- );
+ const { deviceCode, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } =
+ useProviderOAuthDeviceCode(isOAuth ? provider.id : null, { observeProgress: deviceFlow });
const handleOAuthClick = useCallback(async () => {
if (provider.connected) {
try {
@@ -1212,7 +1257,16 @@ function CustomProviderHeader({
ownedLogin.finish();
setLoggingIn(false);
}
- }, [beginOwnedLogin, cancelOwnedLogin, clearDeviceCode, loggingIn, provider.connected, provider.id, provider.name, t]);
+ }, [
+ beginOwnedLogin,
+ cancelOwnedLogin,
+ clearDeviceCode,
+ loggingIn,
+ provider.connected,
+ provider.id,
+ provider.name,
+ t,
+ ]);
const trailing = (
<div className="flex shrink-0 items-center gap-1">
@@ -1252,9 +1306,7 @@ function CustomProviderHeader({
trailing={trailing}
provider={provider}
badge={<CustomTag label={t('settings.providers.custom.tag')} />}
- detail={
- loggingIn && deviceFlow ? <OAuthDeviceCodeCard deviceCode={deviceCode} /> : undefined
- }
+ detail={loggingIn && deviceFlow ? <OAuthDeviceCodeCard deviceCode={deviceCode} /> : undefined}
/>
);
}
@@ -1314,6 +1366,7 @@ function CindySigninRow({ selected, onSelect }: { selected: boolean; onSelect: (
function ListRow({
provider,
selected,
+ reconnectRequired = false,
onSelect,
position,
total,
@@ -1322,6 +1375,7 @@ function ListRow({
}: {
provider: ProviderView;
selected: boolean;
+ reconnectRequired?: boolean;
onSelect: () => void;
position: number;
total: number;
@@ -1381,21 +1435,29 @@ function ListRow({
<span
className="min-w-0 flex-1 truncate text-13 font-medium"
style={{
- color: provider.suspended
- ? 'var(--text-tertiary)'
- : 'var(--settings-section-title)',
+ color: provider.suspended ? 'var(--text-tertiary)' : 'var(--settings-section-title)',
}}
>
{title}
</span>
- {provider.suspended ? (
+ {reconnectRequired ? (
+ <span
+ className="shrink-0 select-none text-11"
+ style={{ color: 'var(--settings-integration-warning)' }}
+ >
+ {t('settings.providers.openai.reconnectRequired')}
+ </span>
+ ) : provider.suspended ? (
// 已停用比模型数更要紧:窄栏(224px)只放得下一个注记,停用时以状态取代计数。
<span className="shrink-0 select-none text-11" style={{ color: 'var(--text-tertiary)' }}>
{t('settings.providers.pill.suspended')}
</span>
) : (
modelCount !== null && (
- <span className="shrink-0 text-11 tabular-nums" style={{ color: 'var(--text-tertiary)' }}>
+ <span
+ className="shrink-0 text-11 tabular-nums"
+ style={{ color: 'var(--text-tertiary)' }}
+ >
{t('settings.providers.models.modelCount', { count: modelCount })}
</span>
)
@@ -1403,8 +1465,9 @@ function ListRow({
<span
className="h-1.5 w-1.5 shrink-0 rounded-full"
style={{
- backgroundColor:
- provider.connected && !provider.suspended
+ backgroundColor: reconnectRequired
+ ? 'var(--remote-status-failed)'
+ : provider.connected && !provider.suspended
? 'var(--remote-status-ready)'
: 'var(--border-default)',
}}
@@ -1612,12 +1675,12 @@ export function ProvidersSection() {
// 每次权威快照都会携带新的 providerOrder 数组引用。写结束后首个新快照无论顺序
// 是否仍等于本窗口目标,都要结束 pending:另一窗口可能已经成为最后写入者。
const hasSnapshotAfterMutation =
- pendingProviderOrder?.providerOrderAtMutationEnd !== undefined
- && providerOrder !== pendingProviderOrder.providerOrderAtMutationEnd;
+ pendingProviderOrder?.providerOrderAtMutationEnd !== undefined &&
+ providerOrder !== pendingProviderOrder.providerOrderAtMutationEnd;
if (
- !sameCatalog
- || incomingIds.every((id, index) => id === pendingProviderOrderIds[index])
- || hasSnapshotAfterMutation
+ !sameCatalog ||
+ incomingIds.every((id, index) => id === pendingProviderOrderIds[index]) ||
+ hasSnapshotAfterMutation
) {
setPendingProviderOrder(null);
}
@@ -1646,9 +1709,9 @@ export function ProvidersSection() {
if (unrecordedIds.length === 0 || ownerGeneration === null) return;
void Promise.all(
unrecordedIds.map((id) =>
- window.electronAPI.maker.setProviderOrder(dataOwnerId, ownerGeneration, [id])),
- )
- .catch(() => toast.error(t('settings.providers.order.saveFailed')));
+ window.electronAPI.maker.setProviderOrder(dataOwnerId, ownerGeneration, [id]),
+ ),
+ ).catch(() => toast.error(t('settings.providers.order.saveFailed')));
}, [dataOwnerId, listProviders, ownerGeneration, providerOrder, t]);
const persistVisibleProviderOrder = useCallback(
@@ -1704,7 +1767,7 @@ export function ProvidersSection() {
provider:
provider?.id === 'xd'
? t('settings.providers.xd.title')
- : provider?.name ?? providerId,
+ : (provider?.name ?? providerId),
position: nextIndex + 1,
total: currentIds.length,
}),
@@ -1813,11 +1876,8 @@ export function ProvidersSection() {
const rt = config.runtimes[agent];
if (!rt?.baseUrl) continue;
const authMethod =
- p.auth.method === 'none' ? 'none'
- : p.auth.method === 'oauth' ? 'oauth'
- : 'apiKey';
- const apiKey =
- authMethod === 'apiKey' ? await readCustomProviderKey(p.id, agent) : null;
+ p.auth.method === 'none' ? 'none' : p.auth.method === 'oauth' ? 'oauth' : 'apiKey';
+ const apiKey = authMethod === 'apiKey' ? await readCustomProviderKey(p.id, agent) : null;
// 鉴权请求头是 main-only 密文,renderer 不回读;交由 main 按 savedProviderId
// 注入已存请求头(否则仅靠请求头鉴权的端点刷新会因缺头 401,codex review)。
const r = await window.electronAPI.maker.fetchProviderModels({
@@ -1907,7 +1967,11 @@ export function ProvidersSection() {
if (p.id === 'anthropic') return <AnthropicHeader provider={p} onChanged={refetch} />;
if (p.id === 'openai') return <OpenAiHeader provider={p} onChanged={refetch} />;
if (p.id === 'xai') return <XaiHeader provider={p} onChanged={refetch} />;
- if (p.source === 'builtin' && p.auth.method === 'apiKey' && (PROVIDER_SECRET_IDS as readonly string[]).includes(p.id)) {
+ if (
+ p.source === 'builtin' &&
+ p.auth.method === 'apiKey' &&
+ (PROVIDER_SECRET_IDS as readonly string[]).includes(p.id)
+ ) {
return <BuiltinApiKeyHeader provider={p} onChanged={refetch} />;
}
if (p.source === 'builtin') return <GenericOAuthHeader provider={p} onChanged={refetch} />;
@@ -1973,6 +2037,7 @@ export function ProvidersSection() {
<ListRow
provider={provider}
selected={!cindySigninActive && effectiveSelected?.id === provider.id}
+ reconnectRequired={provider.id === 'openai' && openaiReconnectRequired}
onSelect={() => setSelectedId(provider.id)}
position={index + 1}
total={listProviders.length}
@@ -2102,98 +2167,98 @@ export function ProvidersSection() {
{!effectiveSelected.suspended &&
effectiveSelected.modelDiscoveryFailure &&
providerHasModels(effectiveSelected) && (
- <div
- className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-t px-5 py-3 text-13"
- style={{ borderColor: 'var(--settings-theme-card-border)' }}
- >
- <span style={{ color: 'var(--text-tertiary)' }}>
- {/* 有清单时必须换一套措辞:空态那套说的是「拿不到模型列表」,而列表就
+ <div
+ className="flex shrink-0 flex-wrap items-center justify-between gap-3 border-t px-5 py-3 text-13"
+ style={{ borderColor: 'var(--settings-theme-card-border)' }}
+ >
+ <span style={{ color: 'var(--text-tertiary)' }}>
+ {/* 有清单时必须换一套措辞:空态那套说的是「拿不到模型列表」,而列表就
显示在这条横幅下面 —— 照搬等于当着用户的面说一句他能一眼看穿的假话。
这里讲的是「没能刷新,你看到的是上次的结果」,每个归因各自的处置建议
照旧保留(DESIGN.md「Errors = what happened + what to do」)。 */}
- {t(
- `settings.providers.detail.discoveryFailedStale.${effectiveSelected.modelDiscoveryFailure.kind}`,
- )}
- </span>
- <PillButton
- label={t(
- rediscovering
- ? 'settings.providers.button.retrying'
- : 'settings.providers.button.retry',
- )}
- onClick={() => void handleRediscoverModels(effectiveSelected)}
- disabled={rediscovering}
- />
- </div>
- )}
+ {t(
+ `settings.providers.detail.discoveryFailedStale.${effectiveSelected.modelDiscoveryFailure.kind}`,
+ )}
+ </span>
+ <PillButton
+ label={t(
+ rediscovering
+ ? 'settings.providers.button.retrying'
+ : 'settings.providers.button.retry',
+ )}
+ onClick={() => void handleRediscoverModels(effectiveSelected)}
+ disabled={rediscovering}
+ />
+ </div>
+ )}
{!effectiveSelected.suspended &&
(providerHasModels(effectiveSelected) ||
(isBuiltinRefreshableProviderId(effectiveSelected.id) &&
!effectiveSelected.modelDiscoveryFailure)) && (
- <>
- <div
- className="border-t"
- style={{ borderColor: 'var(--settings-theme-card-border)' }}
- />
- <UnifiedModelList
- provider={effectiveSelected}
- emptyMessage={t(
- effectiveSelected.connected
- ? 'settings.providers.detail.emptyModelsConnected'
- : 'settings.providers.detail.emptyModels',
- )}
- {...(isBuiltinRefreshableProviderId(effectiveSelected.id)
- ? {
- onRefresh: () => void handleRefreshBuiltinModels(effectiveSelected),
- refreshing: refreshingProviderId === effectiveSelected.id,
- refreshDisabled: refreshingProviderId !== null,
- refreshIdleLabel: t('settings.providers.models.refreshBuiltinAria'),
- }
- : effectiveSelected.source === 'user' &&
- effectiveSelected.auth.method !== 'oauth'
+ <>
+ <div
+ className="border-t"
+ style={{ borderColor: 'var(--settings-theme-card-border)' }}
+ />
+ <UnifiedModelList
+ provider={effectiveSelected}
+ emptyMessage={t(
+ effectiveSelected.connected
+ ? 'settings.providers.detail.emptyModelsConnected'
+ : 'settings.providers.detail.emptyModels',
+ )}
+ {...(isBuiltinRefreshableProviderId(effectiveSelected.id)
? {
- onRefresh: () => void handleRefreshModels(effectiveSelected),
+ onRefresh: () => void handleRefreshBuiltinModels(effectiveSelected),
refreshing: refreshingProviderId === effectiveSelected.id,
refreshDisabled: refreshingProviderId !== null,
+ refreshIdleLabel: t('settings.providers.models.refreshBuiltinAria'),
}
- : {})}
- />
- </>
- )}
+ : effectiveSelected.source === 'user' &&
+ effectiveSelected.auth.method !== 'oauth'
+ ? {
+ onRefresh: () => void handleRefreshModels(effectiveSelected),
+ refreshing: refreshingProviderId === effectiveSelected.id,
+ refreshDisabled: refreshingProviderId !== null,
+ }
+ : {})}
+ />
+ </>
+ )}
{!effectiveSelected.suspended &&
!providerHasModels(effectiveSelected) &&
(Boolean(effectiveSelected.modelDiscoveryFailure) ||
!isBuiltinRefreshableProviderId(effectiveSelected.id)) && (
- <div className="flex flex-1 flex-col items-center justify-center gap-3 px-8 text-center text-13">
- {/* 已连接却无模型(如 Codex 刚登录、models_cache 未生成;或网关清单拉取失败)
+ <div className="flex flex-1 flex-col items-center justify-center gap-3 px-8 text-center text-13">
+ {/* 已连接却无模型(如 Codex 刚登录、models_cache 未生成;或网关清单拉取失败)
不能沿用未连接的「授权后…」文案——那对已连接供应商自相矛盾。
动态发现明确失败时更进一步:讲清**发生了什么 + 下一步**并给出重试入口
(DESIGN.md「Errors = what happened + what to do」)——被地域拒绝或凭证
被拒的用户不会等来任何自动恢复,继续说「正在发现」就是假话。 */}
- <span style={{ color: 'var(--text-tertiary)' }}>
- {effectiveSelected.modelDiscoveryFailure
- ? t(
- `settings.providers.detail.discoveryFailed.${effectiveSelected.modelDiscoveryFailure.kind}`,
- )
- : t(
- effectiveSelected.connected
- ? 'settings.providers.detail.emptyModelsConnected'
- : 'settings.providers.detail.emptyModels',
+ <span style={{ color: 'var(--text-tertiary)' }}>
+ {effectiveSelected.modelDiscoveryFailure
+ ? t(
+ `settings.providers.detail.discoveryFailed.${effectiveSelected.modelDiscoveryFailure.kind}`,
+ )
+ : t(
+ effectiveSelected.connected
+ ? 'settings.providers.detail.emptyModelsConnected'
+ : 'settings.providers.detail.emptyModels',
+ )}
+ </span>
+ {effectiveSelected.modelDiscoveryFailure && (
+ <PillButton
+ label={t(
+ rediscovering
+ ? 'settings.providers.button.retrying'
+ : 'settings.providers.button.retry',
)}
- </span>
- {effectiveSelected.modelDiscoveryFailure && (
- <PillButton
- label={t(
- rediscovering
- ? 'settings.providers.button.retrying'
- : 'settings.providers.button.retry',
- )}
- onClick={() => void handleRediscoverModels(effectiveSelected)}
- disabled={rediscovering}
- />
- )}
- </div>
- )}
+ onClick={() => void handleRediscoverModels(effectiveSelected)}
+ disabled={rediscovering}
+ />
+ )}
+ </div>
+ )}
</>
) : (
<div
diff --git a/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts b/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts
index 41c2dfb211..3cf30e2995 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/codexAuthLogin.test.ts
@@ -18,9 +18,7 @@ describe('triggerCodexLoginOnce', () => {
it('coalesces only the same mode and serializes a conflicting mode after cancellation', async () => {
const browser = deferred<{ authenticated: boolean }>();
const triggerLogin = vi.fn((_: string, options?: { mode?: string; ownerId?: string }) =>
- options?.mode === 'device-code'
- ? Promise.resolve({ authenticated: true })
- : browser.promise,
+ options?.mode === 'device-code' ? Promise.resolve({ authenticated: true }) : browser.promise,
);
const cancelLogin = vi.fn(async () => undefined);
Object.assign(window, {
@@ -77,12 +75,33 @@ describe('triggerCodexLoginOnce', () => {
expect(triggerLogin).toHaveBeenCalledTimes(1);
});
+ it('isolates login-start listener failures from later listeners and the login IPC', async () => {
+ const triggerLogin = vi.fn(async () => ({ authenticated: true }));
+ const cancelLogin = vi.fn(async () => undefined);
+ Object.assign(window, {
+ electronAPI: {
+ maker: { auth: { triggerLogin, cancelLogin } },
+ },
+ });
+ const { onCodexLoginStarted, triggerCodexLoginOnce } = await import('../codexAuthLogin');
+ const laterListener = vi.fn();
+ const offThrowing = onCodexLoginStarted(() => {
+ throw new Error('observer failed');
+ });
+ const offLater = onCodexLoginStarted(laterListener);
+
+ await expect(triggerCodexLoginOnce('browser')).resolves.toEqual({ authenticated: true });
+
+ expect(laterListener).toHaveBeenCalledOnce();
+ expect(triggerLogin).toHaveBeenCalledOnce();
+ offThrowing();
+ offLater();
+ });
+
it('continues a mode switch when cancellation throws synchronously', async () => {
const browser = deferred<{ authenticated: boolean }>();
const triggerLogin = vi.fn((_: string, options?: { mode?: string; ownerId?: string }) =>
- options?.mode === 'device-code'
- ? Promise.resolve({ authenticated: true })
- : browser.promise,
+ options?.mode === 'device-code' ? Promise.resolve({ authenticated: true }) : browser.promise,
);
const cancelLogin = vi.fn(() => {
throw new Error('bridge unavailable');
diff --git a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
index 36e738e7d7..59a4eb4e7a 100644
--- a/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
+++ b/apps/desktop/src/renderer/hooks/__tests__/useCodexAuth.test.ts
@@ -4,6 +4,7 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { isChatGptConnectionConnected, useCodexAuth } from '../useCodexAuth';
+import { acquireCodexLogin } from '../codexAuthLogin';
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -18,6 +19,8 @@ type TestAuthState = {
identity?: string;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ recoveryRequiredReason?: string;
};
function deferred<T>() {
@@ -29,6 +32,7 @@ function deferred<T>() {
}
function installAuthApi(logout: () => Promise<void>) {
+ const getCodexRateLimits = vi.fn(async () => ({ rateLimits: null, resetOffer: null }));
const auth = {
getState: vi.fn(async (): Promise<TestAuthState> => ({
authenticated: true,
@@ -40,32 +44,47 @@ function installAuthApi(logout: () => Promise<void>) {
logout: vi.fn(logout),
onStateChanged: vi.fn(() => () => undefined),
onLoginProgress: vi.fn(() => () => undefined),
+ getCodexRateLimits,
};
- (window as unknown as { electronAPI: { maker: { auth: typeof auth } } }).electronAPI = {
- maker: { auth },
+ (
+ window as unknown as {
+ electronAPI: {
+ maker: { auth: typeof auth; usage: { getCodexRateLimits: typeof getCodexRateLimits } };
+ };
+ }
+ ).electronAPI = {
+ maker: { auth, usage: { getCodexRateLimits } },
};
return auth;
}
function stateChangedListener(auth: ReturnType<typeof installAuthApi>) {
const calls = auth.onStateChanged.mock.calls as unknown as Array<
- [(payload: { agentKind: string; authenticated: boolean; errorReason?: string }) => void]
+ [
+ (payload: {
+ agentKind: string;
+ authenticated: boolean;
+ errorReason?: string;
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ recoveryRequiredReason?: string;
+ }) => void,
+ ]
>;
return calls[0][0];
}
function loginProgressListener(auth: ReturnType<typeof installAuthApi>) {
const calls = auth.onLoginProgress.mock.calls as unknown as Array<
- [(
- payload: {
+ [
+ (payload: {
agentKind: string;
phase: string;
mode?: 'browser' | 'device-code';
detail?: string;
verificationUrl?: string;
userCode?: string;
- },
- ) => void]
+ }) => void,
+ ]
>;
return calls[0][0];
}
@@ -176,6 +195,7 @@ describe('useCodexAuth lifecycle', () => {
authenticated: false,
errorReason: 'refresh_token_reused',
authSource: 'oauth' as const,
+ credentialScope: 'system-shared' as const,
});
const { result } = renderHook(() => useCodexAuth());
@@ -183,7 +203,398 @@ describe('useCodexAuth lifecycle', () => {
expect(result.current.state).toEqual({
kind: 'reconnect-required',
reason: 'refresh_token_reused',
+ credentialScope: 'system-shared',
+ });
+ });
+ });
+
+ it('verifies a fresh-mount authenticated recovery candidate before exposing connected', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const verification = deferred<{ rateLimits: null; resetOffer: null }>();
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ recoveryRequiredReason: 'token_revoked',
+ })
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ auth.getCodexRateLimits.mockImplementationOnce(() => verification.promise);
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(auth.getCodexRateLimits).toHaveBeenCalledOnce());
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ expect(result.current.recoveryCheck).toBe('checking');
+
+ await act(async () => {
+ verification.resolve({ rateLimits: null, resetOffer: null });
+ await verification.promise;
+ });
+ await waitFor(() => expect(result.current.state.kind).toBe('authenticated'));
+ });
+
+ it('keeps recovery pending when the account probe succeeds but main has not committed it', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const pendingRecovery = {
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth' as const,
+ credentialScope: 'system-shared' as const,
+ recoveryRequiredReason: 'token_revoked',
+ };
+ auth.getState.mockResolvedValue(pendingRecovery);
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.recoveryCheck).toBe('failed'));
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ expect(auth.getCodexRateLimits).toHaveBeenCalledOnce();
+ expect(auth.getState).toHaveBeenCalledTimes(2);
+ });
+
+ it('keeps a hinted recovery loading until the authoritative snapshot is known', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const initialState = deferred<TestAuthState>();
+ const verification = deferred<{ rateLimits: null; resetOffer: null }>();
+ auth.getState.mockImplementationOnce(() => initialState.promise);
+ auth.getCodexRateLimits.mockImplementationOnce(() => verification.promise);
+ const { result } = renderHook(() =>
+ useCodexAuth({ recoveryHint: { reason: 'token_revoked' } }),
+ );
+
+ expect(result.current.state).toEqual({ kind: 'loading' });
+ expect(result.current.recoveryCheck).toBe('idle');
+
+ await act(async () => {
+ initialState.resolve({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
});
+ await initialState.promise;
+ });
+ await waitFor(() => expect(auth.getCodexRateLimits).toHaveBeenCalledOnce());
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ expect(result.current.recoveryCheck).toBe('checking');
+
+ await act(async () => {
+ verification.resolve({ rateLimits: null, resetOffer: null });
+ await verification.promise;
+ });
+ await waitFor(() => expect(result.current.state.kind).toBe('authenticated'));
+ });
+
+ it('shares one credential probe across observers with different recovery hints', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const verification = deferred<{ rateLimits: null; resetOffer: null }>();
+ auth.getState.mockResolvedValue({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ auth.getCodexRateLimits.mockImplementation(() => verification.promise);
+ const { result } = renderHook(() => ({
+ first: useCodexAuth({ recoveryHint: { reason: 'token_revoked' } }),
+ second: useCodexAuth({ recoveryHint: { reason: 'refresh_token_reused' } }),
+ }));
+
+ await waitFor(() => {
+ expect(result.current.first.recoveryCheck).toBe('checking');
+ expect(result.current.second.recoveryCheck).toBe('checking');
+ });
+ expect(auth.getCodexRateLimits).toHaveBeenCalledOnce();
+
+ await act(async () => {
+ verification.resolve({ rateLimits: null, resetOffer: null });
+ await verification.promise;
+ });
+
+ await waitFor(() => {
+ expect(result.current.first.state.kind).toBe('authenticated');
+ expect(result.current.second.state.kind).toBe('authenticated');
+ });
+ expect(auth.getCodexRateLimits).toHaveBeenCalledOnce();
+ });
+
+ it('keeps a fresh-mount recovery candidate actionable when its account probe fails', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState.mockResolvedValue({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'instance-isolated',
+ recoveryRequiredReason: 'token_revoked',
+ });
+ auth.getCodexRateLimits.mockRejectedValueOnce(new Error('network unavailable'));
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.recoveryCheck).toBe('failed'));
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+
+ it('refreshes on window focus and exposes authenticated only after a server probe', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ })
+ .mockResolvedValue({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('reconnect-required'));
+ act(() => window.dispatchEvent(new Event('focus')));
+
+ await waitFor(() => expect(auth.getCodexRateLimits).toHaveBeenCalledOnce());
+ await waitFor(() => expect(result.current.state.kind).toBe('authenticated'));
+ expect(result.current.recoveryCheck).toBe('idle');
+ });
+
+ it('keeps reconnect-required and offers a manual recheck when verification is unavailable', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ })
+ .mockResolvedValue({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'instance-isolated',
+ });
+ auth.getCodexRateLimits.mockRejectedValueOnce(new Error('network unavailable'));
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('reconnect-required'));
+ act(() => window.dispatchEvent(new Event('focus')));
+
+ await waitFor(() => expect(result.current.recoveryCheck).toBe('failed'));
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+
+ await act(async () => {
+ await result.current.refresh();
+ });
+ expect(result.current.state.kind).toBe('authenticated');
+ expect(result.current.recoveryCheck).toBe('idle');
+ });
+
+ it('leaves login-pending and restores recheck after a successful OAuth result cannot be verified', async () => {
+ const auth = installAuthApi(async () => undefined);
+ auth.getState.mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ auth.triggerLogin.mockResolvedValue({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'instance-isolated',
+ });
+ auth.getCodexRateLimits.mockRejectedValueOnce(new Error('network unavailable'));
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('reconnect-required'));
+ await act(async () => {
+ await expect(result.current.triggerLogin()).resolves.toBe('unverified');
+ });
+
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ expect(result.current.recoveryCheck).toBe('failed');
+ });
+
+ it('ignores a recovery probe that settles after the observer is disabled and re-enabled', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const verification = deferred<{ rateLimits: null; resetOffer: null }>();
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ })
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ })
+ .mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ auth.getCodexRateLimits.mockImplementationOnce(() => verification.promise);
+ const hook = renderHook(({ enabled }) => useCodexAuth({ enabled }), {
+ initialProps: { enabled: true },
+ });
+
+ await waitFor(() => expect(hook.result.current.state.kind).toBe('reconnect-required'));
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(auth.getCodexRateLimits).toHaveBeenCalledOnce());
+
+ hook.rerender({ enabled: false });
+ hook.rerender({ enabled: true });
+ await waitFor(() => expect(auth.getState).toHaveBeenCalledTimes(3));
+ await waitFor(() =>
+ expect(hook.result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ }),
+ );
+
+ await act(async () => {
+ verification.resolve({ rateLimits: null, resetOffer: null });
+ await verification.promise;
+ });
+ expect(hook.result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ });
+
+ it('settles the current recovery check when another login makes its probe stale', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const verification = deferred<{ rateLimits: null; resetOffer: null }>();
+ const login = deferred<TestAuthState>();
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ })
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'system-shared',
+ });
+ auth.getCodexRateLimits.mockImplementationOnce(() => verification.promise);
+ auth.triggerLogin.mockImplementationOnce(() => login.promise);
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('reconnect-required'));
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(result.current.recoveryCheck).toBe('checking'));
+
+ const lease = acquireCodexLogin();
+ await waitFor(() => expect(auth.triggerLogin).toHaveBeenCalledOnce());
+ await act(async () => {
+ verification.resolve({ rateLimits: null, resetOffer: null });
+ await verification.promise;
+ });
+ await waitFor(() => expect(result.current.recoveryCheck).toBe('idle'));
+ expect(result.current.state).toEqual({
+ kind: 'reconnect-required',
+ reason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+
+ login.resolve({ authenticated: false, errorReason: 'login_cancelled' });
+ await lease.promise;
+ lease.release();
+ });
+
+ it('does not reuse a prior credential probe after same-reason invalidation and relogin', async () => {
+ const auth = installAuthApi(async () => undefined);
+ const firstProbe = deferred<{ rateLimits: null; resetOffer: null }>();
+ const secondProbe = deferred<{ rateLimits: null; resetOffer: null }>();
+ auth.getState
+ .mockResolvedValueOnce({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ })
+ .mockResolvedValueOnce({
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth',
+ credentialScope: 'instance-isolated',
+ });
+ auth.getCodexRateLimits
+ .mockImplementationOnce(() => firstProbe.promise)
+ .mockImplementationOnce(() => secondProbe.promise);
+ const loginResult = {
+ authenticated: true,
+ identity: '[email protected]',
+ authSource: 'oauth' as const,
+ credentialScope: 'instance-isolated' as const,
+ };
+ auth.triggerLogin.mockResolvedValue(loginResult);
+ const { result } = renderHook(() => useCodexAuth());
+
+ await waitFor(() => expect(result.current.state.kind).toBe('reconnect-required'));
+ act(() => window.dispatchEvent(new Event('focus')));
+ await waitFor(() => expect(auth.getCodexRateLimits).toHaveBeenCalledTimes(1));
+
+ act(() => {
+ stateChangedListener(auth)({
+ agentKind: 'codex',
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'instance-isolated',
+ });
+ });
+ let loginOutcome!: Promise<string>;
+ act(() => {
+ loginOutcome = result.current.triggerLogin();
+ });
+ await waitFor(() => expect(auth.getCodexRateLimits).toHaveBeenCalledTimes(2));
+
+ await act(async () => {
+ firstProbe.resolve({ rateLimits: null, resetOffer: null });
+ await firstProbe.promise;
+ });
+ expect(result.current.state.kind).not.toBe('authenticated');
+ expect(result.current.recoveryCheck).toBe('checking');
+
+ await act(async () => {
+ secondProbe.resolve({ rateLimits: null, resetOffer: null });
+ await expect(loginOutcome).resolves.toBe('authenticated');
+ });
+ expect(result.current.state).toMatchObject({
+ kind: 'authenticated',
+ identity: '[email protected]',
});
});
@@ -197,12 +608,14 @@ describe('useCodexAuth lifecycle', () => {
agentKind: 'codex',
authenticated: false,
errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
});
});
expect(result.current.state).toEqual({
kind: 'reconnect-required',
reason: 'token_revoked',
+ credentialScope: 'system-shared',
});
});
@@ -287,6 +700,7 @@ describe('useCodexAuth lifecycle', () => {
authenticated: false,
errorReason: 'refresh_token_reused',
authSource: 'oauth',
+ credentialScope: 'system-shared',
});
await initialState.promise;
});
@@ -298,6 +712,7 @@ describe('useCodexAuth lifecycle', () => {
expect(result.current.state).toEqual({
kind: 'reconnect-required',
reason: 'refresh_token_reused',
+ credentialScope: 'system-shared',
});
});
diff --git a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
index 65e6d3afac..728154e489 100644
--- a/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
+++ b/apps/desktop/src/renderer/hooks/codexAuthLogin.ts
@@ -1,12 +1,20 @@
/** Renderer 内共享的 Codex OAuth 登录结果。 */
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('codexAuthLogin');
+
export type CodexLoginResult = {
authenticated: boolean;
identity?: string;
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ recoveryRequiredReason?: string;
};
+type CodexLoginStartedListener = () => void;
+
type PendingCodexLogin = {
mode: 'browser' | 'device-code';
ownerId: string;
@@ -28,6 +36,7 @@ let pendingCodexLogin: PendingCodexLogin | null = null;
let loginGeneration = 0;
let loginOwnerSequence = 0;
const loginOwnership = new Map<Promise<CodexLoginResult>, CodexLoginOwnership>();
+const loginStartedListeners = new Set<CodexLoginStartedListener>();
const loginOwnerPrefix = (() => {
try {
const uuid = globalThis.crypto?.randomUUID?.();
@@ -54,6 +63,22 @@ function nextLoginOwnerId(): string {
return `${loginOwnerPrefix}:${loginOwnerSequence}`;
}
+function notifyCodexLoginStarted(): void {
+ for (const listener of loginStartedListeners) {
+ try {
+ listener();
+ } catch (error) {
+ log.warn('Codex login-start listener failed', error);
+ }
+ }
+}
+
+/** 凭证恢复验证订阅真实登录启动点;同一 shared login 只通知一次。 */
+export function onCodexLoginStarted(listener: CodexLoginStartedListener): () => void {
+ loginStartedListeners.add(listener);
+ return () => loginStartedListeners.delete(listener);
+}
+
function invokeCodexLogin(
mode: 'browser' | 'device-code',
ownerId: string,
@@ -70,9 +95,7 @@ function invokeCodexLogin(
* main adapter 也会复用正在运行的 CLI 登录,但在 renderer 先合并可以避免设置页、
* 会话横幅等入口重复发 IPC,并避免同一结果重复执行 main handler 的刷新与广播收尾。
*/
-function getOrStartCodexLogin(
- mode: 'browser' | 'device-code' = 'browser',
-): PendingCodexLogin {
+function getOrStartCodexLogin(mode: 'browser' | 'device-code' = 'browser'): PendingCodexLogin {
if (pendingCodexLogin) {
if (pendingCodexLogin.mode === mode) return pendingCodexLogin;
@@ -89,9 +112,11 @@ function getOrStartCodexLogin(
}
const queued: Promise<CodexLoginResult> = previous
.catch(() => undefined)
- .then(() =>
- generation === loginGeneration ? invokeCodexLogin(mode, ownerId) : cancelledLoginResult(),
- )
+ .then(() => {
+ if (generation !== loginGeneration) return cancelledLoginResult();
+ notifyCodexLoginStarted();
+ return invokeCodexLogin(mode, ownerId);
+ })
.finally(() => {
if (pendingCodexLogin?.promise === queued) pendingCodexLogin = null;
});
@@ -100,6 +125,7 @@ function getOrStartCodexLogin(
}
++loginGeneration;
+ notifyCodexLoginStarted();
const ownerId = nextLoginOwnerId();
const run: Promise<CodexLoginResult> = invokeCodexLogin(mode, ownerId).finally(() => {
if (pendingCodexLogin?.promise === run) pendingCodexLogin = null;
@@ -120,9 +146,7 @@ export function triggerCodexLoginOnce(
* 同一 renderer 内多个显式入口会复用一个登录 promise;组件卸载时只有最后一个 owner
* 才能取消它。lease 绑定具体 promise,因此旧模式的 cleanup 不会误杀已排队的新模式。
*/
-export function acquireCodexLogin(
- mode: 'browser' | 'device-code' = 'browser',
-): CodexLoginLease {
+export function acquireCodexLogin(mode: 'browser' | 'device-code' = 'browser'): CodexLoginLease {
const pending = getOrStartCodexLogin(mode);
const { ownerId, promise } = pending;
let ownership = loginOwnership.get(promise);
diff --git a/apps/desktop/src/renderer/hooks/useCodexAuth.ts b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
index 3760a50cf3..ca4e874e33 100644
--- a/apps/desktop/src/renderer/hooks/useCodexAuth.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexAuth.ts
@@ -13,6 +13,7 @@ import { toast } from '@/lib/toast';
import {
acquireCodexLogin,
invalidatePendingCodexLogin,
+ onCodexLoginStarted,
type CodexLoginLease,
type CodexLoginResult,
} from './codexAuthLogin';
@@ -31,15 +32,22 @@ export type CodexUiState =
identity?: string;
expiresAt?: number;
authSource?: 'oauth' | 'api-key';
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ }
+ | {
+ kind: 'reconnect-required';
+ reason: string;
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
}
- | { kind: 'reconnect-required'; reason: string }
| { kind: 'error'; message: string };
-export type CodexLoginOutcome = 'authenticated' | 'cancelled' | 'failed';
+export type CodexLoginOutcome = 'authenticated' | 'cancelled' | 'failed' | 'unverified';
+export type CodexRecoveryCheck = 'idle' | 'checking' | 'failed';
type CodexAuthMachineState = {
ui: CodexUiState;
reconnectReason: string | null;
+ reconnectCredentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
/** 成功登录、明确断开或失效广播等持久认证变化的序号。 */
authRevision: number;
/** 登录进度和暂时失败也会推进,用于判断初始快照能否替换当前显示。 */
@@ -52,6 +60,11 @@ type CodexAuthMachineEvent =
| { type: 'initial-state'; result: CodexLoginResult; requestedAt: InitialSnapshotRevision }
| { type: 'initial-state-failed'; requestedAt: InitialSnapshotRevision }
| { type: 'observer-disabled' }
+ | {
+ type: 'recovery-hint';
+ reason: string;
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ }
| { type: 'state-changed'; result: CodexLoginResult }
| {
type: 'login-pending';
@@ -61,6 +74,7 @@ type CodexAuthMachineEvent =
| { type: 'login-progress-error'; message: string }
| { type: 'login-result'; result: CodexLoginResult }
| { type: 'login-threw'; message: string }
+ | { type: 'recovery-verification-failed' }
| { type: 'cancelled' }
| { type: 'logout-success' }
| { type: 'refreshed-state'; result: CodexLoginResult };
@@ -77,17 +91,29 @@ function createInitialMachineState(): CodexAuthMachineState {
}
function toCodexUiState(raw: CodexLoginResult, preserveGenericError = false): CodexUiState {
+ if (raw.authenticated && raw.recoveryRequiredReason) {
+ return {
+ kind: 'reconnect-required',
+ reason: raw.recoveryRequiredReason,
+ ...(raw.credentialScope ? { credentialScope: raw.credentialScope } : {}),
+ };
+ }
if (raw.authenticated) {
return {
kind: 'authenticated',
identity: raw.identity,
expiresAt: raw.expiresAt,
authSource: raw.authSource,
+ ...(raw.credentialScope ? { credentialScope: raw.credentialScope } : {}),
};
}
const reason = raw.errorReason;
if (reason && isCodexOAuthReconnectRequired(reason)) {
- return { kind: 'reconnect-required', reason };
+ return {
+ kind: 'reconnect-required',
+ reason,
+ ...(raw.credentialScope ? { credentialScope: raw.credentialScope } : {}),
+ };
}
if (preserveGenericError && reason) {
return { kind: 'error', message: reason };
@@ -101,12 +127,20 @@ function replaceUi(
revision: 'snapshot' | 'event' | 'auth',
): CodexAuthMachineState {
let reconnectReason = machine.reconnectReason;
- if (ui.kind === 'reconnect-required') reconnectReason = ui.reason;
- if (ui.kind === 'authenticated' || ui.kind === 'unauthenticated') reconnectReason = null;
+ let reconnectCredentialScope = machine.reconnectCredentialScope;
+ if (ui.kind === 'reconnect-required') {
+ reconnectReason = ui.reason;
+ reconnectCredentialScope = ui.credentialScope;
+ }
+ if (ui.kind === 'authenticated' || ui.kind === 'unauthenticated') {
+ reconnectReason = null;
+ reconnectCredentialScope = undefined;
+ }
return {
ui,
reconnectReason,
+ ...(reconnectCredentialScope ? { reconnectCredentialScope } : {}),
authRevision: machine.authRevision + (revision === 'auth' ? 1 : 0),
eventRevision: machine.eventRevision + (revision === 'snapshot' ? 0 : 1),
};
@@ -119,7 +153,13 @@ function restoreReconnectOr(
return replaceUi(
machine,
machine.reconnectReason
- ? { kind: 'reconnect-required', reason: machine.reconnectReason }
+ ? {
+ kind: 'reconnect-required',
+ reason: machine.reconnectReason,
+ ...(machine.reconnectCredentialScope
+ ? { credentialScope: machine.reconnectCredentialScope }
+ : {}),
+ }
: fallback,
'event',
);
@@ -144,21 +184,47 @@ function reduceCodexAuthMachine(
if (
machine.ui.kind === 'loading' &&
machine.reconnectReason === null &&
+ machine.reconnectCredentialScope === undefined &&
machine.authRevision === 0 &&
machine.eventRevision === 0
) {
return machine;
}
return createInitialMachineState();
+ case 'recovery-hint': {
+ const reconnectCredentialScope = event.credentialScope ?? machine.reconnectCredentialScope;
+ if (machine.ui.kind === 'loading' || machine.ui.kind === 'login-pending') {
+ return {
+ ...machine,
+ reconnectReason: event.reason,
+ ...(reconnectCredentialScope ? { reconnectCredentialScope } : {}),
+ eventRevision: machine.eventRevision + 1,
+ };
+ }
+ return replaceUi(
+ machine,
+ {
+ kind: 'reconnect-required',
+ reason: event.reason,
+ ...(reconnectCredentialScope ? { credentialScope: reconnectCredentialScope } : {}),
+ },
+ 'event',
+ );
+ }
case 'initial-state': {
if (machine.authRevision !== event.requestedAt.authRevision) return machine;
const snapshot = toCodexUiState(event.result);
if (snapshot.kind === 'reconnect-required') {
const withReason =
- machine.reconnectReason === snapshot.reason
+ machine.reconnectReason === snapshot.reason &&
+ machine.reconnectCredentialScope === snapshot.credentialScope
? machine
- : { ...machine, reconnectReason: snapshot.reason };
+ : {
+ ...machine,
+ reconnectReason: snapshot.reason,
+ reconnectCredentialScope: snapshot.credentialScope,
+ };
if (machine.ui.kind === 'login-pending') return withReason;
return replaceUi(withReason, snapshot, 'snapshot');
}
@@ -222,6 +288,8 @@ function reduceCodexAuthMachine(
machine,
toCodexUiState({ authenticated: false, errorReason: event.message }, true),
);
+ case 'recovery-verification-failed':
+ return restoreReconnectOr(machine, { kind: 'unauthenticated' });
case 'cancelled':
return restoreReconnectOr(machine, { kind: 'unauthenticated' });
case 'logout-success':
@@ -240,6 +308,105 @@ export function isChatGptConnectionConnected(
return state.kind === 'authenticated' && state.authSource === 'oauth';
}
+export type CodexRecoveryVerification =
+ | { status: 'verified' }
+ | { status: 'invalid'; state: CodexLoginResult }
+ | { status: 'failed' }
+ | { status: 'stale' };
+
+type CodexRecoveryVerificationFlight = {
+ epoch: number;
+ promise: Promise<CodexRecoveryVerification>;
+};
+
+let codexCredentialEpoch = 0;
+let codexRecoveryVerificationInFlight: CodexRecoveryVerificationFlight | null = null;
+const observedCodexAuthEvents = new WeakSet<object>();
+let lastObservedCodexAuthFingerprint: string | null = null;
+
+function codexAuthFingerprint(result: CodexLoginResult): string {
+ return JSON.stringify([
+ result.authenticated,
+ result.identity ?? null,
+ result.expiresAt ?? null,
+ result.errorReason ?? null,
+ result.authSource ?? null,
+ result.credentialScope ?? null,
+ result.recoveryRequiredReason ?? null,
+ ]);
+}
+
+function observeCodexAuthSnapshot(result: CodexLoginResult): void {
+ const fingerprint = codexAuthFingerprint(result);
+ if (lastObservedCodexAuthFingerprint === fingerprint) return;
+ lastObservedCodexAuthFingerprint = fingerprint;
+ codexCredentialEpoch += 1;
+}
+
+/** 新登录动作产生新的凭证候选;旧账号级探测即使随后成功也不能证明这次登录已恢复。 */
+function beginCodexAuthCredentialAttempt(): void {
+ codexCredentialEpoch += 1;
+}
+
+onCodexLoginStarted(beginCodexAuthCredentialAttempt);
+
+/** preload 会把同一个 payload fan-out 给多个 hook;按对象去重,只推进一次全局凭证代次。 */
+function observeCodexAuthStateEvent(payload: object, result: CodexLoginResult): void {
+ if (observedCodexAuthEvents.has(payload)) return;
+ observedCodexAuthEvents.add(payload);
+ if (result.authenticated || !isCodexOAuthReconnectRequired(result.errorReason)) {
+ observeCodexAuthSnapshot(result);
+ return;
+ }
+ lastObservedCodexAuthFingerprint = codexAuthFingerprint(result);
+ codexCredentialEpoch += 1;
+}
+
+/**
+ * 用账号级 app-server RPC 验证 ChatGPT 登录真的可用;本地 auth.json 存在只算候选,
+ * 不能直接把失效横幅切成“已恢复”。并发的设置页/横幅观察者共用一次探测。
+ */
+export function verifyCodexAuthRecovery(
+ candidate: CodexLoginResult,
+): Promise<CodexRecoveryVerification> {
+ observeCodexAuthSnapshot(candidate);
+ const epoch = codexCredentialEpoch;
+ if (codexRecoveryVerificationInFlight?.epoch === epoch) {
+ return codexRecoveryVerificationInFlight.promise;
+ }
+ const run = (async (): Promise<CodexRecoveryVerification> => {
+ let accountRpcVerified = false;
+ try {
+ await window.electronAPI.maker.usage.getCodexRateLimits();
+ accountRpcVerified = true;
+ } catch {
+ // 继续读取 authoritative auth state:明确再次失效时应立刻返回 invalid;其它失败保留
+ // 原提示与手动“重新检测”入口。
+ }
+ try {
+ const state = (await window.electronAPI.maker.auth.getState(AGENT_KIND)) as CodexLoginResult;
+ if (epoch !== codexCredentialEpoch) return { status: 'stale' };
+ if (!state.authenticated && isCodexOAuthReconnectRequired(state.errorReason)) {
+ return { status: 'invalid', state };
+ }
+ // Main 只有在账号 RPC 对应的 owner / marker / credential 仍未变化,且恢复边界成功
+ // 持久化后才会清掉 recoveryRequiredReason。RPC resolve 本身不等于恢复已提交。
+ if (accountRpcVerified && state.authenticated && !state.recoveryRequiredReason) {
+ return { status: 'verified' };
+ }
+ } catch {
+ // 状态也读不到时仍归为检测失败,保留原失效提示与手动“重新检测”入口。
+ }
+ return epoch === codexCredentialEpoch ? { status: 'failed' } : { status: 'stale' };
+ })().finally(() => {
+ if (codexRecoveryVerificationInFlight?.promise === run) {
+ codexRecoveryVerificationInFlight = null;
+ }
+ });
+ codexRecoveryVerificationInFlight = { epoch, promise: run };
+ return run;
+}
+
/**
* 将共享 Codex 登录绑定到真实发起它的 React owner。
*
@@ -274,9 +441,7 @@ export function useOwnedCodexLogin(): (
return lease.promise
.then(
(result) =>
- mountedRef.current
- ? result
- : { authenticated: false, errorReason: 'login_cancelled' },
+ mountedRef.current ? result : { authenticated: false, errorReason: 'login_cancelled' },
(error) => {
if (!mountedRef.current) {
return { authenticated: false, errorReason: 'login_cancelled' };
@@ -291,11 +456,27 @@ export function useOwnedCodexLogin(): (
}, []);
}
-export function useCodexAuth(options?: { enabled?: boolean }) {
+export function useCodexAuth(options?: {
+ enabled?: boolean;
+ /** 已经被会话错误证明失效,但 Main 的本地快照可能尚未带 marker。 */
+ recoveryHint?: {
+ reason: string;
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ };
+}) {
const enabled = options?.enabled ?? true;
+ const recoveryHintReason = isCodexOAuthReconnectRequired(options?.recoveryHint?.reason)
+ ? options?.recoveryHint?.reason
+ : undefined;
+ const recoveryHintCredentialScope = options?.recoveryHint?.credentialScope;
const { t } = useTranslation();
const [machine, setMachine] = useState<CodexAuthMachineState>(createInitialMachineState);
+ const [recoveryCheck, setRecoveryCheck] = useState<CodexRecoveryCheck>('idle');
const machineRef = useRef(machine);
+ const verificationGenerationRef = useRef(0);
+ const refreshInFlightRef = useRef<Promise<void> | null>(null);
+ const observerEpochRef = useRef(0);
+ const observerEnabledRef = useRef(enabled);
const triggerOwnedLogin = useOwnedCodexLogin();
const transition = useCallback((event: CodexAuthMachineEvent) => {
@@ -306,29 +487,204 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
setMachine(next);
}, []);
+ const isObserverActive = useCallback(
+ (epoch: number): boolean => observerEnabledRef.current && observerEpochRef.current === epoch,
+ [],
+ );
+
+ const applyRecoveryHint = useCallback(
+ (result: CodexLoginResult): CodexLoginResult => {
+ if (
+ !recoveryHintReason ||
+ result.recoveryRequiredReason ||
+ isCodexOAuthReconnectRequired(result.errorReason)
+ ) {
+ return result;
+ }
+ if (result.authenticated) {
+ return {
+ ...result,
+ recoveryRequiredReason: recoveryHintReason,
+ credentialScope: result.credentialScope ?? recoveryHintCredentialScope ?? 'unknown',
+ };
+ }
+ return {
+ ...result,
+ errorReason: recoveryHintReason,
+ credentialScope: result.credentialScope ?? recoveryHintCredentialScope ?? 'unknown',
+ };
+ },
+ [recoveryHintCredentialScope, recoveryHintReason],
+ );
+
+ const verifyRecoveredState = useCallback(
+ async (
+ result: CodexLoginResult,
+ credentialCandidate: CodexLoginResult = result,
+ ): Promise<CodexRecoveryVerification['status']> => {
+ const observerEpoch = observerEpochRef.current;
+ if (!isObserverActive(observerEpoch)) return 'failed';
+ const reconnectReason =
+ result.recoveryRequiredReason ?? machineRef.current.reconnectReason ?? null;
+ const reconnectCredentialScope =
+ result.credentialScope ?? machineRef.current.reconnectCredentialScope;
+ if (
+ result.authenticated &&
+ reconnectReason &&
+ (machineRef.current.ui.kind !== 'reconnect-required' ||
+ machineRef.current.reconnectReason !== reconnectReason ||
+ machineRef.current.reconnectCredentialScope !== reconnectCredentialScope)
+ ) {
+ transition({
+ type: 'state-changed',
+ result: {
+ ...result,
+ recoveryRequiredReason: reconnectReason,
+ ...(reconnectCredentialScope ? { credentialScope: reconnectCredentialScope } : {}),
+ },
+ });
+ }
+ if (!result.authenticated || !reconnectReason) {
+ transition({ type: 'state-changed', result });
+ setRecoveryCheck('idle');
+ return result.authenticated ? 'verified' : 'invalid';
+ }
+
+ const generation = verificationGenerationRef.current + 1;
+ verificationGenerationRef.current = generation;
+ setRecoveryCheck('checking');
+ // recoveryHint 只负责把已知的会话错误投影到当前 observer 的 UI,不能参与全局凭证
+ // epoch。多个横幅可能携带不同错误字符串,但它们仍在验证同一份 Main auth snapshot。
+ const verification = await verifyCodexAuthRecovery(credentialCandidate);
+ if (
+ !isObserverActive(observerEpoch) ||
+ verificationGenerationRef.current !== generation ||
+ machineRef.current.reconnectReason !== reconnectReason
+ ) {
+ return verification.status;
+ }
+ if (verification.status === 'stale') {
+ setRecoveryCheck('idle');
+ return verification.status;
+ }
+ if (verification.status === 'verified') {
+ transition({
+ type: 'state-changed',
+ result: { ...result, recoveryRequiredReason: undefined },
+ });
+ setRecoveryCheck('idle');
+ } else if (verification.status === 'invalid') {
+ transition({ type: 'state-changed', result: verification.state });
+ setRecoveryCheck('idle');
+ } else {
+ transition({ type: 'recovery-verification-failed' });
+ setRecoveryCheck('failed');
+ }
+ return verification.status;
+ },
+ [isObserverActive, transition],
+ );
+
+ const refresh = useCallback((): Promise<void> => {
+ if (!observerEnabledRef.current) return Promise.resolve();
+ if (refreshInFlightRef.current) return refreshInFlightRef.current;
+ const observerEpoch = observerEpochRef.current;
+ const requestedAt = {
+ authRevision: machineRef.current.authRevision,
+ eventRevision: machineRef.current.eventRevision,
+ };
+ const run = window.electronAPI.maker.auth
+ .getState(AGENT_KIND)
+ .then(async (raw) => {
+ if (!isObserverActive(observerEpoch)) return;
+ if (
+ machineRef.current.authRevision !== requestedAt.authRevision ||
+ machineRef.current.eventRevision !== requestedAt.eventRevision
+ ) {
+ return;
+ }
+ const rawResult = raw as CodexLoginResult;
+ observeCodexAuthSnapshot(rawResult);
+ const result = applyRecoveryHint(rawResult);
+ if (
+ result.authenticated &&
+ (machineRef.current.reconnectReason || result.recoveryRequiredReason)
+ ) {
+ await verifyRecoveredState(result, rawResult);
+ return;
+ }
+ verificationGenerationRef.current += 1;
+ setRecoveryCheck('idle');
+ transition({ type: 'refreshed-state', result });
+ })
+ .catch(() => {
+ if (isObserverActive(observerEpoch) && machineRef.current.reconnectReason) {
+ setRecoveryCheck('failed');
+ }
+ })
+ .finally(() => {
+ if (refreshInFlightRef.current === run) refreshInFlightRef.current = null;
+ });
+ refreshInFlightRef.current = run;
+ return run;
+ }, [applyRecoveryHint, isObserverActive, transition, verifyRecoveredState]);
+
useEffect(() => {
- if (!enabled) transition({ type: 'observer-disabled' });
+ observerEnabledRef.current = enabled;
+ observerEpochRef.current += 1;
+ const observerEpoch = observerEpochRef.current;
+ if (!enabled) {
+ verificationGenerationRef.current += 1;
+ refreshInFlightRef.current = null;
+ setRecoveryCheck('idle');
+ transition({ type: 'observer-disabled' });
+ }
+ return () => {
+ if (observerEpochRef.current === observerEpoch) observerEpochRef.current += 1;
+ observerEnabledRef.current = false;
+ verificationGenerationRef.current += 1;
+ refreshInFlightRef.current = null;
+ };
}, [enabled, transition]);
+ useEffect(() => {
+ if (!enabled || !recoveryHintReason) return;
+ verificationGenerationRef.current += 1;
+ setRecoveryCheck('idle');
+ transition({
+ type: 'recovery-hint',
+ reason: recoveryHintReason,
+ ...(recoveryHintCredentialScope ? { credentialScope: recoveryHintCredentialScope } : {}),
+ });
+ }, [enabled, recoveryHintCredentialScope, recoveryHintReason, transition]);
+
// 必须先订阅、再读取初始快照,避免两者之间出现漏事件窗口。
useEffect(() => {
if (!enabled) return undefined;
const off = window.electronAPI.maker.auth.onStateChanged((payload) => {
if (payload.agentKind !== AGENT_KIND) return;
- transition({ type: 'state-changed', result: payload as CodexLoginResult });
+ const rawResult = payload as CodexLoginResult;
+ observeCodexAuthStateEvent(payload, rawResult);
+ const result = applyRecoveryHint(rawResult);
+ if (
+ result.authenticated &&
+ (machineRef.current.reconnectReason || result.recoveryRequiredReason)
+ ) {
+ void verifyRecoveredState(result, rawResult);
+ return;
+ }
+ verificationGenerationRef.current += 1;
+ setRecoveryCheck('idle');
+ transition({ type: 'state-changed', result });
});
return off;
- }, [enabled, transition]);
+ }, [applyRecoveryHint, enabled, transition, verifyRecoveredState]);
useEffect(() => {
if (!enabled) return undefined;
const off = window.electronAPI.maker.auth.onLoginProgress((progress) => {
if (progress.agentKind !== AGENT_KIND) return;
- if (
- progress.phase === 'device-code' &&
- progress.verificationUrl &&
- progress.userCode
- ) {
+ if (progress.phase === 'device-code' && progress.verificationUrl && progress.userCode) {
transition({
type: 'login-pending',
mode: 'device-code',
@@ -351,6 +707,7 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
useEffect(() => {
if (!enabled) return undefined;
+ const observerEpoch = observerEpochRef.current;
let disposed = false;
const requestedAt = {
authRevision: machineRef.current.authRevision,
@@ -359,41 +716,84 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
window.electronAPI.maker.auth
.getState(AGENT_KIND)
.then((raw) => {
- if (!disposed) {
- transition({ type: 'initial-state', result: raw as CodexLoginResult, requestedAt });
+ if (!disposed && isObserverActive(observerEpoch)) {
+ const rawResult = raw as CodexLoginResult;
+ observeCodexAuthSnapshot(rawResult);
+ const result = applyRecoveryHint(rawResult);
+ if (machineRef.current.authRevision !== requestedAt.authRevision) return;
+ if (
+ result.authenticated &&
+ (machineRef.current.reconnectReason || result.recoveryRequiredReason)
+ ) {
+ void verifyRecoveredState(result, rawResult);
+ } else {
+ transition({ type: 'initial-state', result, requestedAt });
+ }
}
})
.catch(() => {
- if (!disposed) transition({ type: 'initial-state-failed', requestedAt });
+ if (!disposed && isObserverActive(observerEpoch)) {
+ transition({ type: 'initial-state-failed', requestedAt });
+ }
});
return () => {
disposed = true;
};
- }, [enabled, transition]);
+ }, [applyRecoveryHint, enabled, isObserverActive, transition, verifyRecoveredState]);
- const triggerLogin = useCallback(async (
- mode: 'browser' | 'device-code' = 'browser',
- ): Promise<CodexLoginOutcome> => {
- transition({ type: 'login-pending', mode });
- try {
- const result = await triggerOwnedLogin(mode);
- transition({ type: 'login-result', result });
- if (result.authenticated) {
- toast.success(t('logic.toasts.codexConnected'));
- return 'authenticated';
+ useEffect(() => {
+ if (!enabled || machine.ui.kind !== 'reconnect-required') return undefined;
+ const onVisible = () => {
+ if (document.visibilityState === 'hidden') return;
+ void refresh();
+ };
+ window.addEventListener('focus', onVisible);
+ document.addEventListener('visibilitychange', onVisible);
+ return () => {
+ window.removeEventListener('focus', onVisible);
+ document.removeEventListener('visibilitychange', onVisible);
+ };
+ }, [enabled, machine.ui.kind, refresh]);
+
+ const triggerLogin = useCallback(
+ async (mode: 'browser' | 'device-code' = 'browser'): Promise<CodexLoginOutcome> => {
+ const observerEpoch = observerEpochRef.current;
+ if (!isObserverActive(observerEpoch)) return 'cancelled';
+ transition({ type: 'login-pending', mode });
+ try {
+ const result = await triggerOwnedLogin(mode);
+ if (!isObserverActive(observerEpoch)) return 'cancelled';
+ if (result.authenticated) {
+ if (machineRef.current.reconnectReason || result.recoveryRequiredReason) {
+ const verification = await verifyRecoveredState(result);
+ if (!isObserverActive(observerEpoch)) return 'cancelled';
+ if (verification === 'stale') return 'cancelled';
+ if (verification !== 'verified') {
+ return verification === 'failed' ? 'unverified' : 'failed';
+ }
+ } else {
+ transition({ type: 'login-result', result });
+ }
+ toast.success(t('logic.toasts.codexConnected'));
+ return 'authenticated';
+ }
+ transition({ type: 'login-result', result });
+ return result.errorReason === 'login_cancelled' ? 'cancelled' : 'failed';
+ } catch (error) {
+ if (!isObserverActive(observerEpoch)) return 'cancelled';
+ const message = error instanceof Error ? error.message : 'login_failed';
+ transition({ type: 'login-threw', message });
+ return message.includes('login_cancelled') ? 'cancelled' : 'failed';
}
- return result.errorReason === 'login_cancelled' ? 'cancelled' : 'failed';
- } catch (error) {
- const message = error instanceof Error ? error.message : 'login_failed';
- transition({ type: 'login-threw', message });
- return message.includes('login_cancelled') ? 'cancelled' : 'failed';
- }
- }, [t, transition, triggerOwnedLogin]);
+ },
+ [isObserverActive, t, transition, triggerOwnedLogin, verifyRecoveredState],
+ );
const cancelLogin = useCallback(async () => {
invalidatePendingCodexLogin();
try {
await window.electronAPI.maker.auth.cancelLogin(AGENT_KIND);
+ setRecoveryCheck('idle');
transition({ type: 'cancelled' });
} catch (error) {
// Cancel may race with a just-persisted OAuth token. If durable cleanup failed,
@@ -401,31 +801,50 @@ export function useCodexAuth(options?: { enabled?: boolean }) {
// the account disconnected.
try {
const raw = await window.electronAPI.maker.auth.getState(AGENT_KIND);
- transition({ type: 'refreshed-state', result: raw as CodexLoginResult });
+ const result = raw as CodexLoginResult;
+ observeCodexAuthSnapshot(result);
+ transition({ type: 'refreshed-state', result });
+ if (result.authenticated && result.recoveryRequiredReason) {
+ void verifyRecoveredState(result);
+ }
} catch {
const message = error instanceof Error ? error.message : 'cancel_login_failed';
transition({ type: 'login-threw', message });
}
}
- }, [transition]);
+ }, [transition, verifyRecoveredState]);
const logout = useCallback(async () => {
invalidatePendingCodexLogin();
try {
await window.electronAPI.maker.auth.logout(AGENT_KIND);
+ setRecoveryCheck('idle');
transition({ type: 'logout-success' });
} catch (error) {
// main 可能在 marker 提交前失败(仍已连接),也可能在 marker 提交后的文件清理阶段
// 失败(已权威断开)。重读一次状态,避免 UI 假报成功或永久停在过期连接态。
try {
const raw = await window.electronAPI.maker.auth.getState(AGENT_KIND);
- transition({ type: 'refreshed-state', result: raw as CodexLoginResult });
+ const result = raw as CodexLoginResult;
+ observeCodexAuthSnapshot(result);
+ transition({ type: 'refreshed-state', result });
+ if (result.authenticated && result.recoveryRequiredReason) {
+ void verifyRecoveredState(result);
+ }
} catch {
// 状态查询也失败时保留当前 UI;原始 logout 错误仍交给调用方展示。
}
throw error;
}
- }, [transition]);
+ }, [transition, verifyRecoveredState]);
- return { state: machine.ui, triggerLogin, cancelLogin, logout };
+ return {
+ state: machine.ui,
+ reconnectCredentialScope: machine.reconnectCredentialScope,
+ recoveryCheck,
+ refresh,
+ triggerLogin,
+ cancelLogin,
+ logout,
+ };
}
diff --git a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
index 0fd2530bbe..97c3cb9604 100644
--- a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
@@ -3,11 +3,33 @@ import { useTranslation } from 'react-i18next';
import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { toast } from '@/lib/toast';
-import { useOwnedCodexLogin } from './useCodexAuth';
+import { useOwnedCodexLogin, verifyCodexAuthRecovery } from './useCodexAuth';
+import type { CodexLoginResult } from './codexAuthLogin';
import { isCodexOAuthReconnectRequired } from './codexAuthRecovery';
export const isCodexSessionExpiredError = isCodexOAuthReconnectRequired;
+type CodexCredentialScope = NonNullable<CodexLoginResult['credentialScope']>;
+
+function reconnectCopyForScope(scope: CodexCredentialScope): {
+ description: string;
+ confirmText: string;
+} {
+ if (scope === 'system-shared') {
+ return {
+ description: 'chatgptAuthRecovery.systemSharedInvalidated',
+ confirmText: 'chatgptAuthRecovery.openApp',
+ };
+ }
+ return {
+ description:
+ scope === 'instance-isolated'
+ ? 'chatgptAuthRecovery.instanceIsolatedInvalidated'
+ : 'chatgptAuthRecovery.unknownInvalidated',
+ confirmText: 'chatgptAuthRecovery.relogin',
+ };
+}
+
export function useCodexSessionExpiredPrompt(options?: {
onAuthenticated?: (recoveredError: string) => void;
onPromptClosed?: () => void;
@@ -48,12 +70,40 @@ export function useCodexSessionExpiredPrompt(options?: {
};
void (async () => {
+ let credentialScope: CodexCredentialScope = 'unknown';
+ try {
+ const state = (await window.electronAPI.maker.auth.getState('codex')) as CodexLoginResult;
+ if (!mountedRef.current) return;
+ if (state.authenticated) {
+ const verification = await verifyCodexAuthRecovery(state);
+ if (!mountedRef.current) return;
+ if (verification.status === 'verified') {
+ onAuthenticatedRef.current?.(error);
+ toast.success(t('logic.toasts.codexConnected'));
+ closePrompt();
+ return;
+ }
+ if (verification.status === 'stale') {
+ closePrompt();
+ return;
+ }
+ if (verification.status === 'invalid') {
+ credentialScope = verification.state.credentialScope ?? 'unknown';
+ }
+ }
+ if (credentialScope === 'unknown') {
+ credentialScope = state.credentialScope ?? 'unknown';
+ }
+ } catch {
+ // 无法读取来源时按 unknown 引导,避免误称沿用了系统登录。
+ }
+ const copy = reconnectCopyForScope(credentialScope);
if (options?.confirmBeforeLogin !== false) {
const shouldReconnect = await confirm({
- title: t('chat.errorBanner.codexSessionExpiredDialog.title'),
- description: t('chat.errorBanner.codexSessionExpiredDialog.description'),
- confirmText: t('chat.errorBanner.codexSessionExpiredDialog.confirm'),
- cancelText: t('chat.errorBanner.codexSessionExpiredDialog.cancel'),
+ title: t('chatgptAuthRecovery.title'),
+ description: t(copy.description),
+ confirmText: t(copy.confirmText),
+ cancelText: t('chatgptAuthRecovery.later'),
autoFocusConfirm: true,
});
if (!mountedRef.current) return;
@@ -63,12 +113,36 @@ export function useCodexSessionExpiredPrompt(options?: {
}
}
+ if (credentialScope === 'system-shared') {
+ try {
+ const result = await window.electronAPI.openChatGPTApp();
+ if (mountedRef.current && !result.success) {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ } catch {
+ if (mountedRef.current) {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ } finally {
+ if (mountedRef.current) closePrompt();
+ }
+ return;
+ }
+
try {
const result = await triggerOwnedLogin();
if (!mountedRef.current) return;
if (result.authenticated) {
- onAuthenticatedRef.current?.(error);
- toast.success(t('logic.toasts.codexConnected'));
+ const verification = await verifyCodexAuthRecovery(result);
+ if (!mountedRef.current) return;
+ if (verification.status === 'verified') {
+ onAuthenticatedRef.current?.(error);
+ toast.success(t('logic.toasts.codexConnected'));
+ } else if (verification.status === 'failed') {
+ toast.error(t('chatgptAuthRecovery.verificationFailed'));
+ } else if (verification.status === 'invalid') {
+ toast.error(t('settings.connections.codex.toast.loginFailed'));
+ }
} else if (result.errorReason !== 'login_cancelled') {
toast.error(t('settings.connections.codex.toast.loginFailed'));
}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 60d608ff99..4650ad7dfc 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5334,6 +5334,20 @@
"transcriptKept": "{{message}} The text recognized so far was kept — you can edit it directly.",
"transcriptKeptOverlay": "{{message}} The text recognized so far was kept — copy it to continue."
},
+ "chatgptAuthRecovery": {
+ "title": "ChatGPT Sign-In Is No Longer Valid",
+ "systemSharedInvalidated": "Cindy is currently using this computer’s ChatGPT sign-in. That sign-in is no longer valid. Open the ChatGPT App, sign in again, then retry.",
+ "instanceIsolatedInvalidated": "Cindy is currently using a separately signed-in ChatGPT account. That sign-in is no longer valid. Sign in again in Cindy, then retry.",
+ "unknownInvalidated": "Cindy’s current ChatGPT sign-in is no longer valid. Sign in again, then retry.",
+ "recovered": "ChatGPT sign-in has been restored. Please retry.",
+ "openApp": "Open ChatGPT App",
+ "relogin": "Sign In to ChatGPT Again",
+ "checking": "Checking…",
+ "recheck": "Check Again",
+ "later": "Later",
+ "openAppFailed": "Couldn’t open the ChatGPT App. Open it manually and sign in again.",
+ "verificationFailed": "Cindy couldn’t confirm whether the ChatGPT sign-in has recovered. Check again."
+ },
"chat": {
"askUserQuestion": {
"skippedAnswer": "Skipped"
@@ -5456,12 +5470,6 @@
"codexAuthMissing": "Remote Codex hasn't been signed in yet (401 Unauthorized). Click \"Sync auth\" to push your local Codex credentials to the remote Cindy Codex home, then retry.",
"codexAuthMissingLocal": "Codex credentials missing or expired (401 Unauthorized). Re-login in {{appName}} Settings → Codex (the app-server will auto-restart on login), or run `codex login` in your terminal and toggle the auth mode in Settings once to restart the app-server. Then start a new session.",
"codexSessionExpired": "The OpenAI connection needs an update. Reconnect ChatGPT to continue; {{appName}} won’t sign your system Codex CLI out or ask you to reconnect other model sources.",
- "codexSessionExpiredDialog": {
- "title": "OpenAI Connection Needs an Update",
- "description": "{{appName}} temporarily can’t use your ChatGPT account. Reconnecting restores OpenAI access for both Codex and Claude; {{appName}} won’t sign your system Codex CLI out or ask you to reconnect other model sources.",
- "confirm": "Reconnect ChatGPT",
- "cancel": "Later"
- },
"codexAuthSynced": "Auth synced. Click \"Retry\" to resend.",
"syncAuth": "Sync auth",
"syncAuthSyncing": "Syncing…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index df0d873e36..99cefe5703 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5332,6 +5332,20 @@
"transcriptKept": "{{message}}(ここまで認識したテキストは保持しており、そのまま編集できます)",
"transcriptKeptOverlay": "{{message}}(ここまで認識したテキストは保持しており、コピーして続けられます)"
},
+ "chatgptAuthRecovery": {
+ "title": "ChatGPT のログインが無効になりました",
+ "systemSharedInvalidated": "Cindy は現在、このコンピューターの ChatGPT ログインを使用しています。このログインは無効になりました。ChatGPT App を開いて再度ログインしてから、再試行してください。",
+ "instanceIsolatedInvalidated": "Cindy は現在、個別にログインした ChatGPT アカウントを使用しています。このログインは無効になりました。Cindy で再度ログインしてから、再試行してください。",
+ "unknownInvalidated": "Cindy の現在の ChatGPT ログインは無効になりました。再度ログインしてから、再試行してください。",
+ "recovered": "ChatGPT ログインが復旧しました。再試行してください。",
+ "openApp": "ChatGPT App を開く",
+ "relogin": "ChatGPT に再ログイン",
+ "checking": "確認中…",
+ "recheck": "再確認",
+ "later": "後で",
+ "openAppFailed": "ChatGPT App を開けませんでした。手動で開いて再度ログインしてください。",
+ "verificationFailed": "ChatGPT ログインが復旧したか確認できませんでした。再確認してください。"
+ },
"chat": {
"askUserQuestion": {
"skippedAnswer": "スキップ済み"
@@ -5454,12 +5468,6 @@
"codexAuthMissing": "リモートの Codex がまだサインインしていません(401 Unauthorized)。「認証情報を同期」をクリックしてローカルの Codex 認証情報をリモートの Cindy Codex home にプッシュし、再試行してください。",
"codexAuthMissingLocal": "Codex 認証情報がないか期限切れです(401 Unauthorized)。{{appName}} Settings → Codex から再ログインする(ログイン時に app-server が自動再起動)か、ターミナルで `codex login` 実行後 Settings で認証モードを一度切り替えて app-server を再起動してから、新しいセッションを開始してください。",
"codexSessionExpired": "OpenAI 接続の更新が必要です。ChatGPT に再接続すると続行できます。{{appName}} がシステムの Codex CLI からサインアウトしたり、他のモデルソースへの再接続を求めたりすることはありません。",
- "codexSessionExpiredDialog": {
- "title": "OpenAI 接続の更新が必要です",
- "description": "{{appName}} は現在 ChatGPT アカウントを使用できません。再接続すると、Codex と Claude の OpenAI 機能が復旧します。{{appName}} がシステムの Codex CLI からサインアウトしたり、他のモデルソースへの再接続を求めたりすることはありません。",
- "confirm": "ChatGPT に再接続",
- "cancel": "後で"
- },
"codexAuthSynced": "認証情報が同期されました。「再試行」をクリックして再送信してください。",
"syncAuth": "認証情報を同期",
"syncAuthSyncing": "同期中…",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index fb04a38bda..1419845cdc 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5332,6 +5332,20 @@
"transcriptKept": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 바로 이어서 편집할 수 있습니다.",
"transcriptKeptOverlay": "{{message}} 지금까지 인식된 텍스트는 유지했습니다. 복사해서 이어가세요."
},
+ "chatgptAuthRecovery": {
+ "title": "ChatGPT 로그인이 더 이상 유효하지 않습니다",
+ "systemSharedInvalidated": "Cindy는 현재 이 컴퓨터의 ChatGPT 로그인을 사용하고 있습니다. 이 로그인이 만료되었습니다. ChatGPT App을 열어 다시 로그인한 후 재시도하세요.",
+ "instanceIsolatedInvalidated": "Cindy는 현재 별도로 로그인한 ChatGPT 계정을 사용하고 있습니다. 이 로그인이 만료되었습니다. Cindy에서 다시 로그인한 후 재시도하세요.",
+ "unknownInvalidated": "Cindy의 현재 ChatGPT 로그인이 만료되었습니다. 다시 로그인한 후 재시도하세요.",
+ "recovered": "ChatGPT 로그인이 복구되었습니다. 다시 시도하세요.",
+ "openApp": "ChatGPT App 열기",
+ "relogin": "ChatGPT 다시 로그인",
+ "checking": "확인 중…",
+ "recheck": "다시 확인",
+ "later": "나중에",
+ "openAppFailed": "ChatGPT App을 열 수 없습니다. 직접 열어 다시 로그인해 주세요.",
+ "verificationFailed": "ChatGPT 로그인이 복구되었는지 확인할 수 없습니다. 다시 확인해 주세요."
+ },
"chat": {
"askUserQuestion": {
"skippedAnswer": "건너뜀"
@@ -5454,12 +5468,6 @@
"codexAuthMissing": "원격 Codex가 아직 로그인되지 않았습니다(401 Unauthorized). 「인증 동기화」를 클릭하여 로컬 Codex 자격 증명을 원격 Cindy Codex home으로 푸시한 후 다시 시도하세요.",
"codexAuthMissingLocal": "Codex 자격 증명이 없거나 만료되었습니다(401 Unauthorized). {{appName}} Settings → Codex에서 다시 로그인하거나(로그인 시 app-server가 자동 재시작) 터미널에서 `codex login` 실행 후 Settings에서 인증 모드를 한 번 전환하여 app-server를 재시작한 다음 새 세션을 시작하세요.",
"codexSessionExpired": "OpenAI 연결을 업데이트해야 합니다. ChatGPT를 다시 연결하면 계속할 수 있습니다. {{appName}}에서 시스템 Codex CLI를 로그아웃하거나 다른 모델 소스의 재연결을 요구하지 않습니다.",
- "codexSessionExpiredDialog": {
- "title": "OpenAI 연결 업데이트 필요",
- "description": "{{appName}}에서 현재 ChatGPT 계정을 사용할 수 없습니다. 다시 연결하면 Codex와 Claude의 OpenAI 기능이 함께 복구됩니다. {{appName}}에서 시스템 Codex CLI를 로그아웃하거나 다른 모델 소스의 재연결을 요구하지 않습니다.",
- "confirm": "ChatGPT 다시 연결",
- "cancel": "나중에"
- },
"codexAuthSynced": "인증이 동기화되었습니다. 「다시 시도」를 클릭하여 다시 보내세요.",
"syncAuth": "인증 동기화",
"syncAuthSyncing": "동기화 중…",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 4961d8ce3e..01adc62087 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5332,6 +5332,20 @@
"transcriptKept": "{{message}}(识别出的文字已经保留,可以直接编辑)",
"transcriptKeptOverlay": "{{message}}(识别出的文字已经保留,可以复制后继续用)"
},
+ "chatgptAuthRecovery": {
+ "title": "ChatGPT 登录已失效",
+ "systemSharedInvalidated": "Cindy 当前沿用了本机的 ChatGPT 登录。该登录已失效。请打开 ChatGPT App 重新登录后重试。",
+ "instanceIsolatedInvalidated": "Cindy 当前使用的是单独登录的 ChatGPT 账号。该登录已失效。请在 Cindy 中重新登录后重试。",
+ "unknownInvalidated": "Cindy 当前的 ChatGPT 登录已失效。请重新登录后重试。",
+ "recovered": "ChatGPT 登录已恢复,请重试。",
+ "openApp": "打开 ChatGPT App",
+ "relogin": "重新登录 ChatGPT",
+ "checking": "正在检测…",
+ "recheck": "重新检测",
+ "later": "稍后处理",
+ "openAppFailed": "无法打开 ChatGPT App,请手动打开后重新登录。",
+ "verificationFailed": "暂时无法确认 ChatGPT 登录是否已恢复,请重新检测。"
+ },
"chat": {
"askUserQuestion": {
"skippedAnswer": "已跳过"
@@ -5454,12 +5468,6 @@
"codexAuthMissing": "远端 Codex 还没同步登录态(401 Unauthorized)。点击右侧「同步登录态」把本机 Codex 凭证推到远端 Cindy Codex home,然后重试发送。",
"codexAuthMissingLocal": "Codex 凭证缺失或失效(401 Unauthorized)。请在 {{appName}} Settings → Codex 重新登录(登录后会自动重启 Codex app-server),或在终端跑 `codex login` + 在 Settings 切换一次鉴权模式来重启 app-server,然后新建任务再发。",
"codexSessionExpired": "OpenAI 连接需要更新。重新连接 ChatGPT 后即可继续;{{appName}} 不会退出系统 Codex CLI,也不会要求你重新连接其他模型来源。",
- "codexSessionExpiredDialog": {
- "title": "OpenAI 连接需要更新",
- "description": "{{appName}} 暂时无法使用你的 ChatGPT 账号。重新连接会同时恢复 Codex 和 Claude 的 OpenAI 能力;{{appName}} 不会退出系统 Codex CLI,也不会要求你重新连接其他模型来源。",
- "confirm": "重新连接 ChatGPT",
- "cancel": "稍后处理"
- },
"codexAuthSynced": "登录态已同步,请点击「重试」重新发送。",
"syncAuth": "同步登录态",
"syncAuthSyncing": "同步中…",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index f1b39ff4b9..705d441e75 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -576,6 +576,8 @@ interface CodexAuthState {
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ recoveryRequiredReason?: string;
}
/** Codex progress event payload (binary download + login phases) */
@@ -2179,6 +2181,7 @@ interface ElectronAPI {
};
showOpenDirectoryDialog: () => Promise<{ canceled: boolean; path?: string }>;
openExternal: (url: string) => Promise<{ success: boolean }>;
+ openChatGPTApp: () => Promise<{ success: boolean }>;
// file-chip 右键菜单 "在浏览器中查看": 把本地文件用 file:// 喂给系统
// 默认浏览器(或 .html/.pdf/.svg 等扩展名的默认 handler)。
diff --git a/packages/maker-core/src/agents/codex/app-server/client.test.ts b/packages/maker-core/src/agents/codex/app-server/client.test.ts
index 87f6adb52d..d86e78512a 100644
--- a/packages/maker-core/src/agents/codex/app-server/client.test.ts
+++ b/packages/maker-core/src/agents/codex/app-server/client.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import { AppServerClient, detectAuthInvalidationReason } from './client.js';
import type { Logger } from '../../../interfaces/logger.js';
import type { Transport, LineHandler, StderrHandler, CloseHandler } from './transport.js';
+import { Method } from './protocol.js';
class FakeTransport implements Transport {
readonly lines: string[] = [];
@@ -60,6 +61,11 @@ const logger: Logger = {
};
describe('detectAuthInvalidationReason', () => {
+ const revokedRateLimitsError = {
+ code: -32603,
+ message:
+ 'failed to fetch codex rate limits: GET https://chatgpt.com/backend-api/wham/usage failed: 401 Unauthorized; content-type=text/plain; body={"error":{"message":"Encountered invalidated oauth token for user, failing request","code":"token_revoked"},"status":401}',
+ };
const cloudAuthError = (message: string, data: Record<string, unknown> = {}) => ({
code: -32000,
message,
@@ -191,6 +197,20 @@ describe('detectAuthInvalidationReason', () => {
}),
).toBeNull();
});
+
+ it('accepts an explicit 401 token error only for correlated account auth RPCs', () => {
+ expect(
+ detectAuthInvalidationReason(revokedRateLimitsError, Method.AccountRateLimitsRead),
+ ).toBe('token_revoked');
+ expect(
+ detectAuthInvalidationReason(
+ revokedRateLimitsError,
+ Method.AccountRateLimitResetCreditConsume,
+ ),
+ ).toBe('token_revoked');
+ expect(detectAuthInvalidationReason(revokedRateLimitsError, Method.ModelList)).toBeNull();
+ expect(detectAuthInvalidationReason(revokedRateLimitsError)).toBeNull();
+ });
});
describe('AppServerClient auth invalidation', () => {
@@ -245,6 +265,31 @@ describe('AppServerClient auth invalidation', () => {
expect(onAuthInvalidated).toHaveBeenCalledWith('refresh_token_reused');
});
+ it('notifies for the account rate-limit 401 shape emitted by current codex-rs', async () => {
+ const transport = new FakeTransport();
+ const onAuthInvalidated = vi.fn();
+ const client = new AppServerClient({
+ createTransport: () => transport,
+ logger,
+ onAuthInvalidated,
+ });
+ client.start();
+
+ const request = client.request(Method.AccountRateLimitsRead);
+ transport.emitLine({
+ id: 1,
+ error: {
+ code: -32603,
+ message:
+ 'failed to fetch codex rate limits: GET https://chatgpt.com/backend-api/wham/usage failed: 401 Unauthorized; content-type=text/plain; body={"error":{"message":"Encountered invalidated oauth token for user, failing request","code":"token_revoked"},"status":401}',
+ },
+ });
+
+ await expect(request).rejects.toThrow(/account\/rateLimits\/read.*401 Unauthorized/i);
+ expect(onAuthInvalidated).toHaveBeenCalledTimes(1);
+ expect(onAuthInvalidated).toHaveBeenCalledWith('token_revoked');
+ });
+
it('keeps auth correlation when an accepted write rejects before its response arrives', async () => {
const transport = new FakeTransport();
const onAuthInvalidated = vi.fn();
diff --git a/packages/maker-core/src/agents/codex/app-server/client.ts b/packages/maker-core/src/agents/codex/app-server/client.ts
index 5f15e6825d..c66ec6064f 100644
--- a/packages/maker-core/src/agents/codex/app-server/client.ts
+++ b/packages/maker-core/src/agents/codex/app-server/client.ts
@@ -90,7 +90,10 @@ function isRecord(value: unknown): value is Record<string, unknown> {
* narrowly-matched config-load wrapper around codex-rs' permanent token
* refresh failure.
*/
-export function detectAuthInvalidationReason(error: JsonRpcErrorObject): string | null {
+export function detectAuthInvalidationReason(
+ error: JsonRpcErrorObject,
+ method?: string,
+): string | null {
const data = isRecord(error.data) ? error.data : null;
// 两种结构化 provenance 都是 app-server 主动声明的鉴权失效:
// - cloudRequirements: turn 级 cloud 依赖检查失败 (Auth/relogin)。
@@ -108,7 +111,25 @@ export function detectAuthInvalidationReason(error: JsonRpcErrorObject): string
!hasStructuredAuthSignal &&
/failed to load configuration:/i.test(error.message) &&
/access token could not be refreshed/i.test(error.message);
- if (!hasStructuredAuthSignal && !isTextualConfigLoadRefreshFailure) {
+ // account/rateLimits/read 与 reset-credit consume 是明确绑定 ChatGPT OAuth 账号的
+ // 控制面 RPC。codex-rs 当前会把 wham/usage 的 401 包成普通 -32603,既没有
+ // cloudRequirements provenance,也没有 config-load 包装;但 method 已由 request id
+ // 可靠关联。只对这两个账号级 RPC 放行「401 + 机器可读 token 原因」窄门,避免工具
+ // 输出或 model/list 偶然回显 token_revoked 时误清凭证。
+ const isAccountAuthRpc =
+ method === Method.AccountRateLimitsRead ||
+ method === Method.AccountRateLimitResetCreditConsume;
+ const isCorrelatedAccountAuthFailure =
+ isAccountAuthRpc &&
+ /\b401\b|Unauthorized/i.test(error.message) &&
+ /token_revoked|token_invalidated|refresh token (?:was|has been) revoked|refresh token was already used|refresh_token.*already used/i.test(
+ error.message,
+ );
+ if (
+ !hasStructuredAuthSignal &&
+ !isTextualConfigLoadRefreshFailure &&
+ !isCorrelatedAccountAuthFailure
+ ) {
return null;
}
@@ -457,7 +478,7 @@ export class AppServerClient {
method: failedWriteMethod,
hasError: error !== null,
});
- if (error) this.notifyAuthInvalidated(error);
+ if (error) this.notifyAuthInvalidated(error, failedWriteMethod);
return;
}
this.logger.warn('response for unknown id', { id });
@@ -466,7 +487,7 @@ export class AppServerClient {
this.pending.delete(id);
if (pending.timeoutId) clearTimeout(pending.timeoutId);
if (error) {
- this.notifyAuthInvalidated(error);
+ this.notifyAuthInvalidated(error, pending.method);
const err = new Error(`codex app-server ${pending.method} error ${error.code}: ${error.message}`);
// 把 code/data 挂上, 上层想区分 OVERLOADED 等可以判 (err as any).code。
Object.assign(err, { code: error.code, data: error.data });
@@ -487,8 +508,8 @@ export class AppServerClient {
}
/** Notify the host once, but only after the caller has correlated the response. */
- private notifyAuthInvalidated(error: JsonRpcErrorObject): void {
- const authInvalidationReason = detectAuthInvalidationReason(error);
+ private notifyAuthInvalidated(error: JsonRpcErrorObject, method?: string): void {
+ const authInvalidationReason = detectAuthInvalidationReason(error, method);
if (this.authInvalidatedFired || !this.onAuthInvalidated || !authInvalidationReason) return;
this.authInvalidatedFired = true;
try {
diff --git a/packages/maker-core/src/types/common.ts b/packages/maker-core/src/types/common.ts
index ca64f82735..c08fb40ebc 100644
--- a/packages/maker-core/src/types/common.ts
+++ b/packages/maker-core/src/types/common.ts
@@ -60,4 +60,19 @@ export interface AuthState {
expiresAt?: number;
errorReason?: string;
authSource?: 'oauth' | 'api-key';
+ /**
+ * Codex OAuth 凭证当前的物理存储范围。
+ *
+ * - system-shared: Cindy 的 auth.json 与本机 ChatGPT/Codex App 共用同一文件。
+ * - instance-isolated: Cindy 使用自己的独立 auth.json。
+ * - unknown: 凭证已失效/丢失,无法可靠回推失效前的范围。
+ *
+ * 其它 agent 不返回该字段。
+ */
+ credentialScope?: 'system-shared' | 'instance-isolated' | 'unknown';
+ /**
+ * A replacement Codex OAuth credential exists locally but must pass an account-level RPC before
+ * UI may declare the previous invalidation recovered.
+ */
+ recoveryRequiredReason?: string;
}