Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): scope Codex auth transition signals
Anyer Qie59ba484e92b
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.tsindex 7b49ec31f2..75f39f41eb 100644--- a/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts@@ -37,6 +37,10 @@ vi.mock('../codex-global-rules.js', () => ({ prepareCodexGlobalRulesCopy: vi.fn(vi.mock('../codex-global-plugins.js', () => ({prepareCodexGlobalPluginsBridge: async () => ({ routingFailures: [] }),}));+vi.mock('../../usageBroadcaster.js', () => ({+ broadcastCodexAccountAuthStarted: vi.fn(),+ broadcastCodexAccountAuthReady: vi.fn(),+}));vi.mock('../codex-auth-state.js', () => ({terminateCodexLoginProcess: (child: EventEmitter) => child.emit('exit', 1),}));@@ -70,6 +74,7 @@ import {prepareCodexAccountHome,setCodexAccountRetirement,} from '../codex-account-auth';+import { broadcastCodexAccountAuthReady, broadcastCodexAccountAuthStarted } from '../../usageBroadcaster.js';function credential(subject: string, account = 'workspace') {const claims = Buffer.from(@@ -97,6 +102,14 @@ afterEach(() => {});describe('native Codex account credentials', () => {+ it('signals explicit auth replacement before retirement and readiness immediately after commit', async () => {+ const result = await loginCodexAccount('account-a', () => true);+ expect(result.ok).toBe(true);+ expect(broadcastCodexAccountAuthStarted).toHaveBeenCalledExactlyOnceWith('account-a');+ expect(broadcastCodexAccountAuthReady).toHaveBeenCalledExactlyOnceWith('account-a');+ expect(codexAccountState('account-a').authenticated).toBe(true);+ });+it('mounts private built-in and plugin skills in every independent account home', async () => {const real = await vi.importActual<typeof import('../codex-global-skills.js')>('../codex-global-skills.js');vi.mocked(prepareCodexGlobalSkillsLinks).mockImplementationOnce((home, options) =>@@ -254,6 +267,8 @@ describe('native Codex account credentials', () => {});expect(codexAccountState('account-a').authenticated).toBe(false);expect(fs.existsSync(path.join(codexAccountHome('account-a'), 'auth.json'))).toBe(false);+ expect(broadcastCodexAccountAuthStarted).toHaveBeenLastCalledWith('account-a');+ expect(broadcastCodexAccountAuthReady).toHaveBeenLastCalledWith('account-a');});it('rolls back a committed login when its IPC owner cancels', async () => {const result = await loginCodexAccount('account-a', () => true);diff --git a/apps/desktop/src/main/maker-host/codex-account-auth.ts b/apps/desktop/src/main/maker-host/codex-account-auth.tsindex 3b61cd98b4..05665ea56d 100644--- a/apps/desktop/src/main/maker-host/codex-account-auth.ts+++ b/apps/desktop/src/main/maker-host/codex-account-auth.ts@@ -13,6 +13,10 @@ import { prepareCodexGlobalSkillsLinks } from './codex-global-skills.js';import { prepareCodexGlobalRulesCopy } from './codex-global-rules.js';import { prepareCodexGlobalPluginsBridge } from './codex-global-plugins.js';import { DESKTOP_CAPABILITY_ROUTING_POLICY } from './capability-routing.js';+import {+ broadcastCodexAccountAuthReady,+ broadcastCodexAccountAuthStarted,+} from '../usageBroadcaster.js';/** Native account homes never participate in system Codex credential reconciliation. */export function isCodexAccountProvider(providerId?: string | null): boolean {@@ -182,6 +186,8 @@ export async function loginCodexAccount(const current = () =>!cancelled && isCurrent() && getActiveAppSession().generation === owner.generation;const staging = path.join(home, `login-${randomUUID()}`);+ let accountAuthTransitionStarted = false;+ let accountAuthReadySent = false;try {await fsp.mkdir(staging, { recursive: true, mode: 0o700 });await fsp.writeFile(@@ -253,6 +259,8 @@ export async function loginCodexAccount(}// An explicit login may replace this connection's account or workspace.// Retire its old runtime before committing the newly authorized identity.+ broadcastCodexAccountAuthStarted(providerId);+ accountAuthTransitionStarted = true;await retireAccount(providerId);if (!current()) return { ok: false, reason: 'login_cancelled' };const files = ['auth.json', 'account.json', 'config.toml', 'disconnected', 'invalidated'];@@ -285,6 +293,8 @@ export async function loginCodexAccount(fs.renameSync(path.join(staging, 'auth.json'), path.join(home, 'auth.json'));fs.rmSync(path.join(home, 'disconnected'), { force: true });fs.rmSync(path.join(home, 'invalidated'), { force: true });+ broadcastCodexAccountAuthReady(providerId);+ accountAuthReadySent = true;return { ok: true, firstLogin: previous === null, previousIdentity: previous?.label, rollbackCredentials };} finally {onBrowserUrl?.(null);@@ -292,6 +302,11 @@ export async function loginCodexAccount(try {await fsp.rm(staging, { recursive: true, force: true });} finally {+ // If login was cancelled or failed after retirement, resume reads from the+ // credentials that remain on disk. A successful commit already signaled above.+ if (accountAuthTransitionStarted && !accountAuthReadySent) {+ broadcastCodexAccountAuthReady(providerId);+ }finish();}}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 5194668509..63e2282a1d 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -85,7 +85,7 @@ import { resolveBotAuthorizationDelivery, buildBotAuthorizationContinuation, comimport { registerSessionSetModelHandler } from './sessionSetModelHandler.js';import { refreshSubscriptionAccountModels } from '../maker-host/subscription-account-models.js';import { syncSubscriptionAccountUsage } from '../usage/subscriptionAccountUsage.js';-import { broadcastCodexAccountAuthReady, clearXaiRateLimitSnapshot } from '../usageBroadcaster.js';+import { clearXaiRateLimitSnapshot } from '../usageBroadcaster.js';import { subscriptionAccountKind, subscriptionAccountState, loginSubscriptionAccount, logoutSubscriptionAccount, cancelSubscriptionAccountLogin, removeSubscriptionAccountCredentialsReversibly } from '../maker-host/subscription-account-auth.js';import { isCodexAccountProvider, codexAccountState, codexAccountLoginName, loginCodexAccount, logoutCodexAccount, cancelCodexAccountLogin, removeCodexAccountCredentialsReversibly, retireCodexAccount } from '../maker-host/codex-account-auth.js';import { projectRemoteBotDelegations } from './remoteBotDelegations.js';@@ -6701,7 +6701,6 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)try { await maker.refreshAgentLocalModels('codex', { credentialMode: 'oauth-bearer', providerId }); }catch { /* Login remains valid; model refresh can be retried without changing credentials. */ }if (!current()) return;- broadcastCodexAccountAuthReady(providerId);broadcastToAllWindows(MAKER_PUSH.PROVIDER_CHANGED, {});} };}diff --git a/apps/desktop/src/main/usageBroadcaster.ts b/apps/desktop/src/main/usageBroadcaster.tsindex 1a41eece13..28c5c3914c 100644--- a/apps/desktop/src/main/usageBroadcaster.ts+++ b/apps/desktop/src/main/usageBroadcaster.ts@@ -55,6 +55,8 @@ export const USAGE_TODAY_SPEND_CHANGED = 'usage:today-spend-changed';export const USAGE_TODAY_TOKENS_CHANGED = 'usage:today-tokens-changed';/** IPC channel: main → renderer 推 Codex 账号订阅用量变化。 */export const USAGE_CODEX_ACCOUNT_CHANGED = 'usage:codex-account-changed';+/** Provider-scoped signal emitted when an independent Codex account is about to be replaced. */+export const USAGE_CODEX_ACCOUNT_AUTH_STARTED = 'usage:codex-account-auth-started';/** Provider-scoped signal emitted only after a Codex account login commit completes. */export const USAGE_CODEX_ACCOUNT_AUTH_READY = 'usage:codex-account-auth-ready';/** IPC channel: main → renderer 推 xAI(SuperGrok bridge)上游限流快照变化。 */@@ -565,6 +567,13 @@ export function broadcastCodexAccountAuthReady(providerId: string): void {if (!win.isDestroyed()) win.webContents.send(USAGE_CODEX_ACCOUNT_AUTH_READY, payload);}}+/** Mark only explicit account replacement as a reason to pause quota reads. */+export function broadcastCodexAccountAuthStarted(providerId: string): void {+ const payload = { providerId };+ for (const win of BrowserWindow.getAllWindows()) {+ if (!win.isDestroyed()) win.webContents.send(USAGE_CODEX_ACCOUNT_AUTH_STARTED, payload);+ }+}export function readCodexAccountUsageSnapshot(providerId?: string): Promise<CodexAccountUsagePayload | null> {return codexUsageStore(providerId).read();}diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 669bd67520..989f51391b 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -816,6 +816,9 @@ const fanOutMakerUsageCodexProviderAccount = createIpcFanOut(const fanOutMakerUsageCodexAccountAuthReady = createIpcFanOut('usage:codex-account-auth-ready',);+const fanOutMakerUsageCodexAccountAuthStarted = createIpcFanOut(+ 'usage:codex-account-auth-started',+);const fanOutSubscriptionProviderAccount = createIpcFanOut('usage:subscription-provider-account-changed',);@@ -7799,6 +7802,12 @@ contextBridge.exposeInMainWorld('electronAPI', {const scoped = payload as { providerId?: string };if (scoped?.providerId === providerId) cb();}),+ /** Fires for one Codex account when explicit credential replacement begins. */+ onCodexAccountAuthStarted: (cb: () => void, providerId: string) =>+ fanOutMakerUsageCodexAccountAuthStarted((payload: unknown) => {+ const scoped = payload as { providerId?: string };+ if (scoped?.providerId === providerId) cb();+ }),/** xAI(SuperGrok bridge)限流快照推送 (bridge 每个成功上游响应解析 x-ratelimit-* 后推送)。 */onXaiRateLimitChanged: (cb: (payload: unknown) => void, providerId = 'xai') =>providerId === 'xai'diff --git a/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.ts b/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.tsindex 20ea44104e..8a06038584 100644--- a/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.ts+++ b/apps/desktop/src/renderer/__tests__/useCodexRateLimits.test.ts@@ -125,6 +125,7 @@ describe('useCodexRateLimits', () => {const refreshedA = { ...result, providerId: 'openai-a', primary: { usedPercent: 18, resetsAt: 'later' } };const b = { ...result, providerId: 'openai-b' };const accountChanges = new Map<string, (payload: unknown) => void>();+ const authStarted = new Map<string, () => void>();const authReady = new Map<string, () => void>();const catalogChanges: Array<() => void> = [];let resolveOldRead!: (value: MobileCodexRateLimitsResult) => void;@@ -141,6 +142,10 @@ describe('useCodexRateLimits', () => {accountChanges.set(providerId, callback);return () => accountChanges.delete(providerId);},+ onCodexAccountAuthStarted: (callback: () => void, providerId: string) => {+ authStarted.set(providerId, callback);+ return () => authStarted.delete(providerId);+ },onCodexAccountAuthReady: (callback: () => void, providerId: string) => {authReady.set(providerId, callback);return () => authReady.delete(providerId);@@ -162,6 +167,7 @@ describe('useCodexRateLimits', () => {// A read started with the old credentials remains in flight when re-login retires them.act(() => accountA.result.current.refresh());expect(reader).toHaveBeenCalledTimes(3);+ act(() => authStarted.get('openai-a')?.());act(() => accountChanges.get('openai-a')?.(null));expect(accountA.result.current.snapshot).toBeNull();@@ -186,6 +192,27 @@ describe('useCodexRateLimits', () => {expect(accountB.result.current.snapshot).toBe(b);});+ it('does not treat an unrelated scoped clear as a credential replacement', async () => {+ const accountChanges = new Map<string, (payload: unknown) => void>();+ const accountA = { ...result, providerId: 'openai-a' };+ const resultAfterClear = { ...accountA, rateLimitResetCredits: { availableCount: 1, credits: [] } };+ const reader = vi.fn().mockResolvedValueOnce(accountA).mockResolvedValueOnce(resultAfterClear);+ vi.stubGlobal('electronAPI', { maker: { usage: {+ getCodexRateLimits: reader,+ onCodexAccountChanged: (callback: (payload: unknown) => void, providerId: string) => {+ accountChanges.set(providerId, callback);+ return () => accountChanges.delete(providerId);+ },+ } } });+ const hook = renderHook(() => useCodexRateLimits(true, 'openai-a'));+ await waitFor(() => expect(hook.result.current.snapshot).toBe(accountA));+ act(() => accountChanges.get('openai-a')?.(null));+ expect(hook.result.current.snapshot).toBeNull();+ act(() => hook.result.current.refresh());+ await waitFor(() => expect(hook.result.current.snapshot).toBe(resultAfterClear));+ expect(reader).toHaveBeenCalledTimes(2);+ });+it('isolates Cindy owner changes and late responses', async () => {let resolveOld!: (value: MobileCodexRateLimitsResult) => void;const reader = vi.fn().mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; }))diff --git a/apps/desktop/src/renderer/hooks/useCodexRateLimits.ts b/apps/desktop/src/renderer/hooks/useCodexRateLimits.tsindex 887c97eb93..53fadece1d 100644--- a/apps/desktop/src/renderer/hooks/useCodexRateLimits.ts+++ b/apps/desktop/src/renderer/hooks/useCodexRateLimits.ts@@ -110,10 +110,7 @@ function cachedRateLimits(providerId: string): CachedRateLimits {// Stay subscribed while panels are unmounted, so a replaced account cannot// seed the next panel with the previous identity's cached quota.const usageUnsubscribe = window.electronAPI?.maker?.usage?.onCodexAccountChanged?.(payload => {- if (payload === null) {- entry.awaitingAuthCompletion = true;- clear();- }+ if (payload === null) clear();// The authoritative read itself emits a usage push. Suppress those echoes// while any read is pending rather than scheduling a recursive refresh.else if (!entry.awaitingAuthCompletion && entry.listeners.size > 0 && entry.pendingReads === 0@@ -121,6 +118,11 @@ function cachedRateLimits(providerId: string): CachedRateLimits {}, providerId);if (usageUnsubscribe) entry.unsubscribe.push(usageUnsubscribe);if (providerId !== 'openai') {+ const authStartedUnsubscribe = window.electronAPI?.maker?.usage?.onCodexAccountAuthStarted?.(() => {+ entry.awaitingAuthCompletion = true;+ clear();+ }, providerId);+ if (authStartedUnsubscribe) entry.unsubscribe.push(authStartedUnsubscribe);const authReadyUnsubscribe = window.electronAPI?.maker?.usage?.onCodexAccountAuthReady?.(() => {// Main emits this provider-scoped signal only after the new auth.json commits.if (!entry.awaitingAuthCompletion) return;diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 1dfb79ed29..603d6ce63f 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -6919,6 +6919,7 @@ interface ElectronAPI {}) => void,) => () => void;onCodexAccountAuthReady: (cb: () => void, providerId: string) => () => void;+ onCodexAccountAuthStarted: (cb: () => void, providerId: string) => () => void;onCodexAccountChanged: (cb: (p: {limitId?: string | null;