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): keep Codex auth recovery inline (#3809)

Chris Zhang1fee70ac9bf0
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 71395666c8..976424aad6 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -459,6 +459,7 @@ import {
import {
assertTrustedAppRendererEvent,
isTrustedAppRendererEvent,
+ isTrustedCindyRendererWindow,
isTrustedAppRendererWindow,
} from './security/trustedAppRenderer.js';
import { isMainShellWindowUrl } from './cindy-brain/scheduleSlot.js';
@@ -807,6 +808,7 @@ import {
} from './sessionDragPreviewHtml.js';
import {
isGlobalVoiceInputOverlayVisible,
+ isGlobalVoiceInputOverlaySender,
releaseActiveGlobalVoiceInputShortcut,
registerGlobalVoiceInputIpc,
} from './voice-input/global.js';
@@ -6096,7 +6098,18 @@ const registerIpcHandlers = () => {
// 打开 renderer 提供的任意自定义 scheme / deep link。
ipcMain.handle('shell:open-chatgpt-app', async (event): Promise<{ success: boolean }> =>
handleOpenChatGPTApp(event, {
- assertTrustedSender: assertTrustedAppRendererEvent,
+ assertTrustedSender: (candidate) => {
+ // The cached global overlay is a trusted Cindy renderer but deliberately
+ // not app-content: it needs this fixed, no-argument capability to keep
+ // auth recovery visible without activating the main window.
+ const overlayWindow = BrowserWindow.fromWebContents(candidate.sender);
+ if (
+ isGlobalVoiceInputOverlaySender(candidate.sender) &&
+ candidate.senderFrame === candidate.sender.mainFrame &&
+ isTrustedCindyRendererWindow(overlayWindow)
+ ) return;
+ assertTrustedAppRendererEvent(candidate);
+ },
openExternal: (url) => shell.openExternal(url),
}),
);
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index 5a3eb1b4a5..08e5aaf2ce 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -20,29 +20,25 @@ const {
providersState,
codexAuthState,
codexAuthActions,
- promptCodexSessionExpired,
toastError,
setModelVisibilitiesSpy,
-} = 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),
- },
- promptCodexSessionExpired: vi.fn(() => true),
- toastError: vi.fn(),
- setModelVisibilitiesSpy: vi.fn(() => true),
- }),
-);
+} = 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(),
+ setModelVisibilitiesSpy: vi.fn(() => true),
+}));
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }),
@@ -70,10 +66,6 @@ vi.mock('@/hooks/useCodexAuth', () => ({
}),
}));
-vi.mock('@/hooks/useCodexSessionExpiredPrompt', () => ({
- useCodexSessionExpiredPrompt: () => promptCodexSessionExpired,
-}));
-
vi.mock('@/hooks/useApiKey', () => ({
useApiKey: () => ({ key: '', hasSavedKey: false, clearKey: vi.fn() }),
}));
@@ -192,7 +184,7 @@ afterEach(() => {
});
describe('ProvidersSection — 深链定位', () => {
- it('ChatGPT 系统共享登录失效时显示来源说明并进入受保护恢复流程', async () => {
+ it('ChatGPT 系统共享登录失效时显示来源说明并打开 ChatGPT App', async () => {
codexAuthState.state = {
kind: 'reconnect-required',
reason: 'token_revoked',
@@ -215,14 +207,13 @@ describe('ProvidersSection — 深链定位', () => {
'var(--remote-status-failed)',
);
expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).not.toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
+ fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
- await waitFor(() => expect(promptCodexSessionExpired).toHaveBeenCalledWith('token_revoked'));
+ await waitFor(() => expect(window.electronAPI.openChatGPTApp).toHaveBeenCalledOnce());
expect(codexAuthActions.triggerLogin).not.toHaveBeenCalled();
- expect(window.electronAPI.openChatGPTApp).not.toHaveBeenCalled();
});
- it('ChatGPT 系统共享重新登录被取消时保留恢复入口', async () => {
+ it('ChatGPT 系统共享打开 App 后保留恢复入口', async () => {
codexAuthState.state = {
kind: 'reconnect-required',
reason: 'token_revoked',
@@ -239,12 +230,11 @@ describe('ProvidersSection — 深链定位', () => {
];
renderAt('?tab=providers&connect=openai');
- fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
- await waitFor(() => expect(promptCodexSessionExpired).toHaveBeenCalledWith('token_revoked'));
+ await waitFor(() => expect(window.electronAPI.openChatGPTApp).toHaveBeenCalledOnce());
expect(toastError).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' })).not.toBeNull();
- expect(window.electronAPI.openChatGPTApp).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' })).not.toBeNull();
});
it('connect=anthropic(未占行内置渠道)→ 向导 builtin 直达;参数消费后清除', async () => {
@@ -356,9 +346,7 @@ describe('ProvidersSection — 深链定位', () => {
],
false,
);
- expect(toastError).toHaveBeenCalledWith(
- 'settings.providers.models.visibilityWriteFailed',
- );
+ expect(toastError).toHaveBeenCalledWith('settings.providers.models.visibilityWriteFailed');
});
it('authorization-code 自定义供应商登录期间卸载时取消本视图拥有的授权', async () => {
diff --git a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
index 294bb2c424..f526e57c72 100644
--- a/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
+++ b/apps/desktop/src/renderer/components/chat/ErrorBanner.tsx
@@ -38,6 +38,7 @@ import {
isCodexSessionExpiredError,
useCodexSessionExpiredPrompt,
} from '@/hooks/useCodexSessionExpiredPrompt';
+import { codexRecoveryActionKey, codexRecoveryDescriptionKey } from '@/hooks/codexAuthRecovery';
import { cn } from '@/lib/utils';
import { isInvalidEncryptedContentError } from '@/utils/encryptedContentError';
import { isNetworkishErrorMessage, parseReconnectAttemptMessage } from '@/utils/networkError';
@@ -144,8 +145,7 @@ export function ErrorBanner({
const { t, i18n } = useTranslation();
const { confirm } = useConfirmDialog();
const promptCodexSessionExpired = useCodexSessionExpiredPrompt({
- // 非共享凭证已有横幅说明,可直接重连;system-shared 始终由 hook 强制走
- // “打开 ChatGPT App / 风险确认后由 Cindy 登录”的保护分支。
+ // 非共享凭证沿用原有确认/登录流程;共享凭证由横幅内联动作直接唤起 App。
confirmBeforeLogin: false,
});
// SSH 与 device-link 是两种互斥的远端来源,但都不能读取或修复控制端本机认证。
@@ -369,13 +369,7 @@ export function ErrorBanner({
} else if (isOpenAiConnectionExpired) {
displayError = openAiConnectionRecoveredSinceError
? t('chatgptAuthRecovery.recovered')
- : t(
- openAiCredentialScope === 'system-shared'
- ? 'chatgptAuthRecovery.systemSharedInvalidated'
- : openAiCredentialScope === 'instance-isolated'
- ? 'chatgptAuthRecovery.instanceIsolatedInvalidated'
- : 'chatgptAuthRecovery.unknownInvalidated',
- );
+ : t(codexRecoveryDescriptionKey(openAiCredentialScope));
} else if (isCodexLocalOAuthAuthMissing) {
displayError = t('chat.errorBanner.codexAuthMissingLocal');
} else if (isClaudeGatewayOpusPlanMismatch) {
@@ -491,6 +485,15 @@ export function ErrorBanner({
await refreshOpenAiAuth();
return;
}
+ if (openAiCredentialScope === 'system-shared') {
+ try {
+ const opened = await window.electronAPI.openChatGPTApp();
+ if (!opened.success) toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ } catch {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ return;
+ }
promptCodexSessionExpired(error);
};
@@ -614,8 +617,7 @@ export function ErrorBanner({
)}
</div>
{openAiReconnectRequired && (
- // 先走账号级服务端探测;共享凭证由恢复弹窗优先引导到 ChatGPT App,
- // 不直接产生第二条可 refresh 的 OAuth 凭证链。
+ // 共享凭证直接唤起 ChatGPT App;返回 Cindy 后由 useCodexAuth 自动复检。
<button
type="button"
onClick={() => void handleOpenAiRecovery()}
@@ -627,24 +629,18 @@ export function ErrorBanner({
'disabled:cursor-not-allowed disabled:opacity-50',
)}
title={t(
- openAiRecoveryCheck === 'failed'
- ? 'chatgptAuthRecovery.recheck'
- : openAiRecoveryBusy
- ? 'chatgptAuthRecovery.checking'
- : openAiCredentialScope === 'system-shared'
- ? 'chatgptAuthRecovery.recheck'
- : 'chatgptAuthRecovery.relogin',
+ codexRecoveryActionKey(
+ openAiCredentialScope,
+ openAiRecoveryBusy ? 'checking' : openAiRecoveryCheck,
+ ),
)}
>
<Spinner icon={RefreshCw} size={12} spinning={openAiRecoveryBusy} />
{t(
- openAiRecoveryBusy
- ? 'chatgptAuthRecovery.checking'
- : openAiRecoveryCheck === 'failed'
- ? 'chatgptAuthRecovery.recheck'
- : openAiCredentialScope === 'system-shared'
- ? 'chatgptAuthRecovery.recheck'
- : 'chatgptAuthRecovery.relogin',
+ codexRecoveryActionKey(
+ openAiCredentialScope,
+ openAiRecoveryBusy ? 'checking' : openAiRecoveryCheck,
+ ),
)}
</button>
)}
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 adae390a0b..987d3b1aec 100644
--- a/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
+++ b/apps/desktop/src/renderer/components/chat/__tests__/ErrorBannerCodexOAuth.test.tsx
@@ -78,7 +78,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
vi.clearAllMocks();
mocks.stateChangedListeners.clear();
mocks.confirm.mockResolvedValue(true);
- mocks.confirmThree.mockResolvedValue('tertiary');
+ mocks.confirmThree.mockResolvedValue('confirm');
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'refresh_token_reused',
@@ -196,7 +196,6 @@ describe('ErrorBanner OpenAI connection recovery', () => {
errorReason: 'token_revoked',
credentialScope: 'system-shared',
});
- mocks.confirmThree.mockResolvedValueOnce('confirm');
render(
<ErrorBanner
error="token_revoked"
@@ -209,7 +208,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
);
expect(await screen.findByText('chatgptAuthRecovery.systemSharedInvalidated')).toBeTruthy();
- fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
+ fireEvent.click(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
expect(mocks.triggerLogin).not.toHaveBeenCalled();
@@ -247,7 +246,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
await initialState.promise;
});
- expect(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' })).toBeTruthy();
+ 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 () => {
@@ -290,16 +289,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(screen.getByRole('button', { name: 'chat.errorBanner.retry' })).toBeTruthy();
});
- it('keeps the system-shared recovery action after user cancellation', async () => {
+ it('opens the ChatGPT App instead of starting Cindy OAuth for system-shared recovery', async () => {
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'token_revoked',
credentialScope: 'system-shared',
});
- mocks.triggerLogin.mockResolvedValueOnce({
- authenticated: false,
- errorReason: 'login_cancelled',
- });
render(
<ErrorBanner
error="token_revoked"
@@ -311,25 +306,21 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
expect(mocks.toastError).not.toHaveBeenCalled();
- expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' })).toBeTruthy();
+ 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 system-shared recovery action after login failure', async () => {
+ it('does not start Cindy OAuth after opening ChatGPT App for system-shared recovery', async () => {
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'token_revoked',
credentialScope: 'system-shared',
});
- mocks.triggerLogin.mockResolvedValueOnce({
- authenticated: false,
- errorReason: 'login_timeout',
- });
render(
<ErrorBanner
error="token_revoked"
@@ -341,14 +332,12 @@ describe('ErrorBanner OpenAI connection recovery', () => {
/>,
);
- fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.recheck' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'chatgptAuthRecovery.openApp' }));
- await waitFor(() => {
- expect(mocks.toastError).toHaveBeenCalledWith('settings.connections.codex.toast.loginFailed');
- });
- expect(mocks.triggerLogin).toHaveBeenCalledOnce();
- expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
- expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.recheck' })).toBeTruthy();
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ expect(screen.getByRole('button', { name: 'chatgptAuthRecovery.openApp' })).toBeTruthy();
expect(screen.queryByRole('button', { name: 'chat.errorBanner.retry' })).toBeNull();
});
@@ -777,7 +766,7 @@ describe('ErrorBanner OpenAI connection recovery', () => {
expect(mocks.cancelLogin).not.toHaveBeenCalled();
});
- it('requires a second risk confirmation before system-shared voice recovery starts Cindy login', async () => {
+ it('uses the existing single confirmation before opening ChatGPT App for voice recovery', async () => {
mocks.getState.mockResolvedValue({
authenticated: false,
errorReason: 'token_revoked',
@@ -800,14 +789,39 @@ describe('ErrorBanner OpenAI connection recovery', () => {
autoFocusConfirm: true,
}),
);
- expect(mocks.confirm).toHaveBeenCalledWith({
- title: 'chatgptAuthRecovery.reloginRiskTitle',
- description: 'chatgptAuthRecovery.reloginRiskDescription',
- confirmText: 'chatgptAuthRecovery.reloginRiskConfirm',
- cancelText: 'chatgptAuthRecovery.later',
- confirmVariant: 'destructive',
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
+ });
+
+ it('cleans the inline lease so the same voice error can recover again', async () => {
+ mocks.getState.mockResolvedValue({
+ authenticated: false,
+ errorReason: 'token_revoked',
+ credentialScope: 'system-shared',
+ });
+ const onInlineRecoveryRequired = vi.fn();
+ const onPromptClosed = vi.fn();
+ const prompt = renderHook(() => useCodexSessionExpiredPrompt({
+ onInlineRecoveryRequired,
+ onPromptClosed,
+ }));
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
+ });
+
+ await waitFor(() =>
+ expect(onInlineRecoveryRequired).toHaveBeenCalledWith('token_revoked', 'system-shared'),
+ );
+ expect(onPromptClosed).toHaveBeenCalledOnce();
+
+ act(() => {
+ expect(prompt.result.current('token_revoked')).toBe(true);
});
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
+ await waitFor(() => expect(onInlineRecoveryRequired).toHaveBeenCalledTimes(2));
+ expect(onPromptClosed).toHaveBeenCalledTimes(2);
+ expect(mocks.confirm).not.toHaveBeenCalled();
+ expect(mocks.confirmThree).not.toHaveBeenCalled();
expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
});
@@ -825,7 +839,6 @@ describe('ErrorBanner OpenAI connection recovery', () => {
});
await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
- expect(mocks.confirmThree).not.toHaveBeenCalled();
expect(mocks.triggerLogin).not.toHaveBeenCalled();
});
@@ -854,11 +867,8 @@ describe('ErrorBanner OpenAI connection recovery', () => {
autoFocusConfirm: true,
}),
);
- await waitFor(() => expect(mocks.triggerLogin).toHaveBeenCalledOnce());
- expect(mocks.openChatGPTApp).not.toHaveBeenCalled();
- await waitFor(() =>
- expect(mocks.toastSuccess).toHaveBeenCalledWith('logic.toasts.codexConnected'),
- );
+ await waitFor(() => expect(mocks.openChatGPTApp).toHaveBeenCalledOnce());
+ expect(mocks.triggerLogin).not.toHaveBeenCalled();
});
it('localizes event-loop terminal errors from the stable reason key', () => {
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index cbab6b7481..c0ccf27e83 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -37,7 +37,7 @@ import {
import { cn } from '@/lib/utils';
import { useProviders } from '@/hooks/useProviders';
import { isChatGptConnectionConnected, useCodexAuth } from '@/hooks/useCodexAuth';
-import { useCodexSessionExpiredPrompt } from '@/hooks/useCodexSessionExpiredPrompt';
+import { codexRecoveryActionKey, codexRecoveryDescriptionKey } from '@/hooks/codexAuthRecovery';
import { useApiKey } from '@/hooks/useApiKey';
import { extractIpcError } from '@/utils/ipcError';
import { useModelAccessStatus } from '@/hooks/useModelAccessStatus';
@@ -587,11 +587,6 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
? (state.credentialScope ?? 'unknown')
: (reconnectCredentialScope ?? 'unknown');
const oauthWritesBlocked = state.oauthWritesBlocked === true;
- const promptCodexSessionExpired = useCodexSessionExpiredPrompt({
- onAuthenticated: () => onChanged(),
- confirmBeforeLogin: false,
- });
-
const handleLogout = useCallback(async () => {
const confirmed = await confirm({
title: t('settings.connections.codex.logoutConfirm.title'),
@@ -629,18 +624,21 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
await refresh();
return;
}
- if (reconnectRequired) promptCodexSessionExpired(state.reason);
- }, [loggingIn, promptCodexSessionExpired, reconnectRequired, recoveryCheck, refresh, state]);
+ if (reconnectRequired && credentialScope === 'system-shared') {
+ try {
+ const opened = await window.electronAPI.openChatGPTApp();
+ if (!opened.success) toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ } catch {
+ toast.error(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ return;
+ }
+ if (reconnectRequired) await handleLogin();
+ }, [credentialScope, handleLogin, loggingIn, reconnectRequired, 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',
- )}
+ {t(codexRecoveryDescriptionKey(credentialScope))}
</p>
) : null;
@@ -656,15 +654,7 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
<div className="flex shrink-0 items-center gap-2.5">
<ReconnectRequiredPill />
<PillButton
- label={t(
- recoveryCheck === 'checking' || loggingIn
- ? 'chatgptAuthRecovery.checking'
- : recoveryCheck === 'failed'
- ? 'chatgptAuthRecovery.recheck'
- : credentialScope === 'system-shared'
- ? 'chatgptAuthRecovery.recheck'
- : 'chatgptAuthRecovery.relogin',
- )}
+ label={t(codexRecoveryActionKey(credentialScope, loggingIn ? 'checking' : recoveryCheck))}
onClick={() => void handleRecovery()}
disabled={
recoveryCheck === 'checking' ||
diff --git a/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx b/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx
index 00bc9a82b1..2811241e6b 100644
--- a/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx
+++ b/apps/desktop/src/renderer/components/ui/__tests__/confirmDialogScroll.test.tsx
@@ -162,6 +162,29 @@ describe('ConfirmDialog 长内容布局', () => {
expect(flashScrollbar).not.toHaveBeenCalled();
});
+ it('三按钮长文案保持单行,空间不足时整组换行', () => {
+ render(
+ <ConfirmDialog
+ open
+ onOpenChange={() => {}}
+ title="连接恢复"
+ description="说明"
+ confirmText="打开 ChatGPT App"
+ tertiaryText="重新登录 ChatGPT"
+ cancelText="稍后处理"
+ />,
+ );
+ const dialog = screen.getByRole('alertdialog');
+ const actionRow = screen.getByRole('button', { name: '打开 ChatGPT App' })
+ .parentElement as HTMLElement;
+ expect(actionRow.className).toContain('flex-wrap');
+ for (const label of ['打开 ChatGPT App', '重新登录 ChatGPT', '稍后处理']) {
+ expect(screen.getByRole('button', { name: label }).className).toContain('whitespace-nowrap');
+ expect(screen.getByRole('button', { name: label }).className).toContain('shrink-0');
+ }
+ expect(dialog).toBeTruthy();
+ });
+
it('手输确认逐字匹配且正文可选择,前后空格不能绕过 id 核对', () => {
const onConfirm = vi.fn();
render(
diff --git a/apps/desktop/src/renderer/hooks/codexAuthRecovery.ts b/apps/desktop/src/renderer/hooks/codexAuthRecovery.ts
index ed20319f35..fee7e0ccee 100644
--- a/apps/desktop/src/renderer/hooks/codexAuthRecovery.ts
+++ b/apps/desktop/src/renderer/hooks/codexAuthRecovery.ts
@@ -13,3 +13,20 @@ export function isCodexOAuthReconnectRequired(reason: string | undefined): boole
reason,
);
}
+
+export type CodexCredentialScope = 'system-shared' | 'instance-isolated' | 'unknown';
+
+export function codexRecoveryDescriptionKey(scope: CodexCredentialScope): string {
+ if (scope === 'system-shared') return 'chatgptAuthRecovery.systemSharedInvalidated';
+ if (scope === 'instance-isolated') return 'chatgptAuthRecovery.instanceIsolatedInvalidated';
+ return 'chatgptAuthRecovery.unknownInvalidated';
+}
+
+export function codexRecoveryActionKey(
+ scope: CodexCredentialScope,
+ check: 'idle' | 'checking' | 'failed',
+): string {
+ if (check === 'checking') return 'chatgptAuthRecovery.checking';
+ if (check === 'failed') return 'chatgptAuthRecovery.recheck';
+ return scope === 'system-shared' ? 'chatgptAuthRecovery.openApp' : 'chatgptAuthRecovery.relogin';
+}
diff --git a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
index 22b9b69f54..a17fac6640 100644
--- a/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
+++ b/apps/desktop/src/renderer/hooks/useCodexSessionExpiredPrompt.ts
@@ -5,12 +5,10 @@ import { useConfirmDialog } from '@/components/ui/confirm-dialog-provider';
import { toast } from '@/lib/toast';
import { useOwnedCodexLogin, verifyCodexAuthRecovery } from './useCodexAuth';
import type { CodexLoginResult } from './codexAuthLogin';
-import { isCodexOAuthReconnectRequired } from './codexAuthRecovery';
+import { isCodexOAuthReconnectRequired, type CodexCredentialScope } from './codexAuthRecovery';
export const isCodexSessionExpiredError = isCodexOAuthReconnectRequired;
-type CodexCredentialScope = NonNullable<CodexLoginResult['credentialScope']>;
-
function reconnectCopyForScope(scope: CodexCredentialScope): {
description: string;
confirmText: string;
@@ -32,7 +30,10 @@ function reconnectCopyForScope(scope: CodexCredentialScope): {
export function useCodexSessionExpiredPrompt(options?: {
onAuthenticated?: (recoveredError: string) => void;
+ onPromptStarted?: (error: string) => void;
onPromptClosed?: () => void;
+ /** 交给独立入口内联呈现恢复动作,避免在辅助窗口里丢失恢复状态。 */
+ onInlineRecoveryRequired?: (error: string, scope: CodexCredentialScope) => void;
/** 已有内联说明和显式按钮时可跳过二次确认,直接进入浏览器连接流程。 */
confirmBeforeLogin?: boolean;
}): (error: string) => boolean {
@@ -43,9 +44,13 @@ export function useCodexSessionExpiredPrompt(options?: {
const promptActiveRef = useRef(false);
const mountedRef = useRef(true);
const onAuthenticatedRef = useRef(options?.onAuthenticated);
+ const onPromptStartedRef = useRef(options?.onPromptStarted);
const onPromptClosedRef = useRef(options?.onPromptClosed);
+ const onInlineRecoveryRequiredRef = useRef(options?.onInlineRecoveryRequired);
onAuthenticatedRef.current = options?.onAuthenticated;
+ onPromptStartedRef.current = options?.onPromptStarted;
onPromptClosedRef.current = options?.onPromptClosed;
+ onInlineRecoveryRequiredRef.current = options?.onInlineRecoveryRequired;
useEffect(() => {
mountedRef.current = true;
@@ -62,6 +67,7 @@ export function useCodexSessionExpiredPrompt(options?: {
if (promptedForErrorRef.current === error) return promptActiveRef.current;
promptedForErrorRef.current = error;
promptActiveRef.current = true;
+ onPromptStartedRef.current?.(error);
const closePrompt = () => {
promptedForErrorRef.current = null;
@@ -100,6 +106,11 @@ export function useCodexSessionExpiredPrompt(options?: {
// 无法读取来源时按 unknown 引导,避免误称沿用了系统登录。
}
const copy = reconnectCopyForScope(credentialScope);
+ if (credentialScope === 'system-shared' && onInlineRecoveryRequiredRef.current) {
+ closePrompt();
+ onInlineRecoveryRequiredRef.current(error, credentialScope);
+ return;
+ }
const openChatGptAppAndClose = async () => {
try {
const opened = await window.electronAPI.openChatGPTApp();
@@ -162,6 +173,10 @@ export function useCodexSessionExpiredPrompt(options?: {
toast.error(t('chatgptAuthRecovery.devWriteBlocked'));
closePrompt();
return;
+ } else if (onInlineRecoveryRequiredRef.current) {
+ closePrompt();
+ onInlineRecoveryRequiredRef.current(error, credentialScope);
+ return;
} else if (options?.confirmBeforeLogin !== false) {
const shouldReconnect = await confirm({
title: t('chatgptAuthRecovery.title'),
diff --git a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx
index a32f0b27ac..17188f2116 100644
--- a/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx
+++ b/apps/desktop/src/renderer/voice-input/VoiceInputOverlay.tsx
@@ -25,6 +25,8 @@ import {
isCodexSessionExpiredError,
useCodexSessionExpiredPrompt,
} from '@/hooks/useCodexSessionExpiredPrompt';
+import { isChatGptConnectionConnected, useCodexAuth } from '@/hooks/useCodexAuth';
+import { codexRecoveryActionKey, type CodexCredentialScope } from '@/hooks/codexAuthRecovery';
import {
recordVoiceInputHistory,
updateVoiceInputHistoryEntry,
@@ -96,12 +98,21 @@ type StartReadyState = {
};
type GlobalOverlayCommand = { type: 'start' | 'submit' | 'cancel' };
type CloseOverlayOptions = { preservePasteTarget?: boolean };
+type CodexRecoveryPromptAttempt = { attemptId: number; reason: string };
// 'retained' is not a paste failure: the dictation session itself died and the
// recognized text was kept for copying. It reuses the paste-error layout but
// carries the session's own error text instead of a paste hint.
type PasteErrorCode = 'empty' | 'unavailable' | 'unconfirmed' | 'permission' | 'failed' | 'retained';
type PermissionPromptKind = 'microphone' | 'accessibility';
+export function isCurrentCodexRecoveryPromptAttempt(
+ pending: CodexRecoveryPromptAttempt | null,
+ attemptId: number,
+ reason: string,
+): boolean {
+ return pending?.attemptId === attemptId && pending.reason === reason;
+}
+
function resetOverlayFocus(): void {
const activeElement = document.activeElement;
if (activeElement instanceof HTMLElement) activeElement.blur();
@@ -156,10 +167,58 @@ function getPasteErrorHintKey(errorCode: PasteErrorCode | null): string {
export function VoiceInputOverlay() {
const { t, i18n } = useTranslation();
+ const [codexRecovery, setCodexRecovery] = useState<{
+ reason: string;
+ scope: CodexCredentialScope;
+ } | null>(null);
+ const [codexRecoveryPromptPending, setCodexRecoveryPromptPending] = useState(false);
const codexSessionPromptActiveRef = useRef(false);
+ const codexRecoveryPromptAttemptRef = useRef<CodexRecoveryPromptAttempt | null>(null);
+ const codexPromptCloseTimerRef = useRef<number | null>(null);
+ const invalidateCodexRecoveryPrompt = useCallback(() => {
+ if (codexPromptCloseTimerRef.current !== null) {
+ window.clearTimeout(codexPromptCloseTimerRef.current);
+ codexPromptCloseTimerRef.current = null;
+ }
+ codexRecoveryPromptAttemptRef.current = null;
+ codexSessionPromptActiveRef.current = false;
+ setCodexRecoveryPromptPending(false);
+ }, []);
const promptCodexSessionExpired = useCodexSessionExpiredPrompt({
+ onPromptStarted: (reason) => {
+ codexRecoveryPromptAttemptRef.current = {
+ attemptId: startAttemptIdRef.current,
+ reason,
+ };
+ setCodexRecoveryPromptPending(true);
+ },
onPromptClosed: () => {
codexSessionPromptActiveRef.current = false;
+ if (codexPromptCloseTimerRef.current !== null) {
+ window.clearTimeout(codexPromptCloseTimerRef.current);
+ }
+ codexPromptCloseTimerRef.current = window.setTimeout(() => {
+ codexPromptCloseTimerRef.current = null;
+ codexRecoveryPromptAttemptRef.current = null;
+ setCodexRecoveryPromptPending(false);
+ }, 0);
+ },
+ onInlineRecoveryRequired: (reason, scope) => {
+ // The prompt hook closes its own de-duplication lease before handing off.
+ // Keep the voice flow gated separately until useCodexAuth verifies recovery.
+ if (codexPromptCloseTimerRef.current !== null) {
+ window.clearTimeout(codexPromptCloseTimerRef.current);
+ codexPromptCloseTimerRef.current = null;
+ }
+ if (!isCurrentCodexRecoveryPromptAttempt(
+ codexRecoveryPromptAttemptRef.current,
+ startAttemptIdRef.current,
+ reason,
+ )) return;
+ codexRecoveryPromptAttemptRef.current = null;
+ setCodexRecoveryPromptPending(false);
+ codexSessionPromptActiveRef.current = true;
+ setCodexRecovery({ reason, scope });
},
});
const [state, setState] = useState<VoiceInputState>('idle');
@@ -211,6 +270,23 @@ export function VoiceInputOverlay() {
const settingsRecoveryTabRef = useRef<VoiceInputRecoverySettingsTab | null>(null);
const openSettingsInFlightRef = useRef(false);
+ const {
+ state: codexAuthState,
+ reconnectCredentialScope,
+ recoveryCheck: codexRecoveryCheck,
+ refresh: refreshCodexAuth,
+ triggerLogin: triggerCodexLogin,
+ } = useCodexAuth({
+ enabled: Boolean(codexRecovery),
+ recoveryHint: codexRecovery
+ ? { reason: codexRecovery.reason, credentialScope: codexRecovery.scope }
+ : undefined,
+ });
+
+ const requestCodexSessionExpiredPrompt = useCallback((reason: string) => {
+ return promptCodexSessionExpired(reason);
+ }, [promptCodexSessionExpired]);
+
const setVoiceState = useCallback((next: VoiceInputState) => {
stateRef.current = next;
if (next === 'error') terminalOutcomeRef.current = 'failed';
@@ -233,6 +309,8 @@ export function VoiceInputOverlay() {
const resetHiddenOverlaySession = useCallback(() => {
setError(null);
+ setCodexRecovery(null);
+ invalidateCodexRecoveryPrompt();
setMicrophoneNotice(null);
setHasPasteError(false);
setPasteErrorCode(null);
@@ -259,7 +337,7 @@ export function VoiceInputOverlay() {
setStopInFlight(false);
setVoiceState('idle');
resetOverlayInteraction();
- }, [clearErrorCloseTimer, resetOverlayInteraction, setVoiceState]);
+ }, [clearErrorCloseTimer, invalidateCodexRecoveryPrompt, resetOverlayInteraction, setVoiceState]);
const enableActionTips = useCallback(() => {
setActionTipsDisabled(false);
@@ -532,7 +610,7 @@ export function VoiceInputOverlay() {
: null;
if (startAttemptIdRef.current !== failureAttemptId) return;
const promptReason = authErrorReason ?? message;
- const shouldPromptCodexSessionExpired = promptCodexSessionExpired(promptReason);
+ const shouldPromptCodexSessionExpired = requestCodexSessionExpiredPrompt(promptReason);
if (shouldPromptCodexSessionExpired) {
codexSessionPromptActiveRef.current = true;
}
@@ -555,7 +633,7 @@ export function VoiceInputOverlay() {
}, [
closeOverlay,
formatVoiceInputStartError,
- promptCodexSessionExpired,
+ requestCodexSessionExpiredPrompt,
resetOverlayInteraction,
restoreSystemAudioForRecording,
scheduleErrorClose,
@@ -589,6 +667,7 @@ export function VoiceInputOverlay() {
// commits to a paste (i.e. throughout submitting + refining). The user
// expects cancel to remain available until the overlay is actually gone.
if (cancelRequestedRef.current) return;
+ invalidateCodexRecoveryPrompt();
cancelRequestedRef.current = true;
suppressedStartErrorAttemptsRef.current.add(startAttemptIdRef.current);
closingRef.current = true;
@@ -614,6 +693,7 @@ export function VoiceInputOverlay() {
resolveDoneWaiters,
restoreSystemAudioForRecording,
stopEngine,
+ invalidateCodexRecoveryPrompt,
]);
const failRecording = useCallback(async (message: string) => {
@@ -703,6 +783,7 @@ export function VoiceInputOverlay() {
if (stateRef.current === 'listening' || stateRef.current === 'submitting' || stateRef.current === 'refining') {
return;
}
+ invalidateCodexRecoveryPrompt();
clearErrorCloseTimer();
resetOverlayInteraction();
const attemptId = startAttemptIdRef.current + 1;
@@ -718,6 +799,7 @@ export function VoiceInputOverlay() {
const elapsedMs = () => Math.round(performance.now() - bootstrapStartedAt);
setError(null);
+ setCodexRecovery(null);
setMicrophoneNotice(null);
setHasPasteError(false);
setPasteErrorCode(null);
@@ -923,17 +1005,51 @@ export function VoiceInputOverlay() {
formatMicrophoneStartError,
showStartFailure,
isActiveStartAttempt,
+ invalidateCodexRecoveryPrompt,
muteSystemAudioForRecording,
- promptCodexSessionExpired,
+ requestCodexSessionExpiredPrompt,
resetOverlayInteraction,
resolveStartReadyState,
restoreSystemAudioForRecording,
scheduleErrorClose,
+ setCodexRecovery,
setVoiceState,
stopEngine,
t,
]);
+ const codexRecoveryScope = codexAuthState.kind === 'reconnect-required'
+ ? (codexAuthState.credentialScope ?? 'unknown')
+ : (reconnectCredentialScope ?? codexRecovery?.scope ?? 'unknown');
+ const codexRecoveryRecovered = Boolean(codexRecovery) && isChatGptConnectionConnected(codexAuthState, false);
+ const codexRecoveryBusy =
+ codexAuthState.kind === 'loading' ||
+ codexAuthState.kind === 'login-pending' ||
+ codexRecoveryCheck === 'checking';
+ const handleCodexRecovery = useCallback(async () => {
+ if (codexRecoveryBusy) return;
+ if (codexRecoveryRecovered) {
+ codexSessionPromptActiveRef.current = false;
+ setCodexRecovery(null);
+ void startRecording();
+ return;
+ }
+ if (codexRecoveryCheck === 'failed') {
+ await refreshCodexAuth();
+ return;
+ }
+ if (codexRecoveryScope === 'system-shared') {
+ try {
+ const opened = await window.electronAPI.openChatGPTApp();
+ if (!opened.success) setError(t('chatgptAuthRecovery.openAppFailed'));
+ } catch {
+ setError(t('chatgptAuthRecovery.openAppFailed'));
+ }
+ return;
+ }
+ await triggerCodexLogin();
+ }, [codexRecoveryBusy, codexRecoveryCheck, codexRecoveryRecovered, codexRecoveryScope, refreshCodexAuth, startRecording, t, triggerCodexLogin]);
+
const waitForDone = useCallback(() => {
return new Promise<void>((resolve) => {
doneWaitersRef.current.add(resolve);
@@ -1210,7 +1326,7 @@ export function VoiceInputOverlay() {
)) return;
switch (event.type) {
case 'auth-required':
- codexSessionPromptActiveRef.current = promptCodexSessionExpired(event.reason);
+ codexSessionPromptActiveRef.current = requestCodexSessionExpiredPrompt(event.reason);
break;
case 'state':
if (event.outcome) terminalOutcomeRef.current = event.outcome;
@@ -1277,7 +1393,7 @@ export function VoiceInputOverlay() {
log.warn('global voice input error:', event.message);
terminalOutcomeRef.current = 'failed';
const formattedMessage = formatVoiceInputError(event.message, event.code, event.transcriptKept);
- if (promptCodexSessionExpired(formattedMessage)) {
+ if (requestCodexSessionExpiredPrompt(formattedMessage)) {
codexSessionPromptActiveRef.current = true;
}
// Preserve already-recognized text for the user to copy, reusing the
@@ -1329,12 +1445,12 @@ export function VoiceInputOverlay() {
event.event.type === 'refine_rejected' &&
isCodexSessionExpiredError(event.event.reason)
) {
- codexSessionPromptActiveRef.current = promptCodexSessionExpired(event.event.reason);
+ codexSessionPromptActiveRef.current = requestCodexSessionExpiredPrompt(event.event.reason);
}
break;
}
});
- }, [formatVoiceInputError, promptCodexSessionExpired, resolveDoneWaiters, setVoiceState]);
+ }, [formatVoiceInputError, requestCodexSessionExpiredPrompt, resolveDoneWaiters, setVoiceState]);
useEffect(() => {
const unsubscribe = window.electronAPI.voiceInput.onGlobalOverlayCommand((command: GlobalOverlayCommand) => {
@@ -1345,6 +1461,12 @@ export function VoiceInputOverlay() {
if (command.type === 'submit') {
if (stateRef.current === 'error') {
if (stopInFlightRef.current) return;
+ if (codexRecoveryPromptPending) return;
+ if (codexRecovery) {
+ void handleCodexRecovery();
+ return;
+ }
+ codexSessionPromptActiveRef.current = false;
void startRecording();
return;
}
@@ -1357,7 +1479,7 @@ export function VoiceInputOverlay() {
});
window.electronAPI.voiceInput.notifyGlobalOverlayReady();
return unsubscribe;
- }, [cancelAndClose, startRecording, stopAndPaste]);
+ }, [cancelAndClose, codexRecovery, codexRecoveryPromptPending, handleCodexRecovery, startRecording, stopAndPaste]);
// Mount-time prewarm. The overlay is now pre-created at app idle (see
// prewarmGlobalVoiceInputOverlay in main/voice-input/global.ts) so this
@@ -1540,12 +1662,21 @@ export function VoiceInputOverlay() {
onFocus={preventOverlayButtonFocus}
onPointerDown={(event) => {
beginOverlayButtonAction(event);
- void startRecording();
+ void (codexRecovery ? handleCodexRecovery() : startRecording());
}}
onClick={suppressOverlayButtonClick}
- disabled={stopInFlight}
+ // The stop IPC gate remains the primary retry guard (disabled={stopInFlight});
+ // auth recovery adds its own busy state while focus/visibility rechecks run.
+ disabled={stopInFlight || codexRecoveryBusy || codexRecoveryPromptPending}
>
- {t('voiceInputOverlay.retry')}
+ {codexRecovery
+ ? codexRecoveryRecovered
+ ? t('voiceInputOverlay.retry')
+ : t(codexRecoveryActionKey(
+ codexRecoveryScope,
+ codexRecoveryBusy ? 'checking' : codexRecoveryCheck,
+ ))
+ : t('voiceInputOverlay.retry')}
</button>
</div>
) : displayText ? (
diff --git a/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts b/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts
index 8b8bc9dd0b..656899bdb1 100644
--- a/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts
+++ b/apps/desktop/src/renderer/voice-input/__tests__/overlayRetryGate.test.ts
@@ -6,6 +6,10 @@ const overlaySource = readFileSync(
resolve(__dirname, '..', 'VoiceInputOverlay.tsx'),
'utf8',
).replace(/\r\n?/g, '\n');
+const bootstrapSource = readFileSync(
+ resolve(__dirname, '../../../main/bootstrap-electron.ts'),
+ 'utf8',
+).replace(/\r\n?/g, '\n');
describe('voice input overlay retry gate', () => {
it('keeps retry disabled until the stop IPC promise settles', () => {
@@ -26,4 +30,53 @@ describe('voice input overlay retry gate', () => {
expect(overlaySource).toContain('resolveVoiceInputReadinessRecovery(readiness, readiness.serviceMode)');
expect(overlaySource).not.toContain('window.electronAPI.voiceInput.getModelSelection()');
});
+
+ it('keeps inline auth recovery visible and routes the global submit back through recovery', () => {
+ expect(overlaySource).toContain("if (!opened.success) setError(t('chatgptAuthRecovery.openAppFailed'));");
+ expect(overlaySource).toContain("if (codexRecovery) {\n void handleCodexRecovery();");
+ expect(overlaySource).toContain('codexSessionPromptActiveRef.current = false;\n void startRecording();');
+ expect(overlaySource).toContain('if (codexRecoveryPromptPending) return;');
+ expect(overlaySource).toContain('disabled={stopInFlight || codexRecoveryBusy || codexRecoveryPromptPending}');
+ expect(overlaySource).toContain('onPromptStarted: (reason) => {');
+ });
+
+ it('drops a delayed handoff after an immediate retry and leaves the paste gate open', async () => {
+ Object.assign(globalThis, { window: { location: { href: 'http://localhost/' } } });
+ const { isCurrentCodexRecoveryPromptAttempt } = await import('../VoiceInputOverlay');
+ let currentAttemptId = 41;
+ let pending: { attemptId: number; reason: string } | null = {
+ attemptId: currentAttemptId,
+ reason: 'token_revoked',
+ };
+ let gate = true;
+ let recoveryEstablished = false;
+ let resolveState!: (reason: string) => void;
+ const delayedState = new Promise<string>((resolve) => {
+ resolveState = resolve;
+ });
+ const delayedHandoff = delayedState.then((reason) => {
+ if (!isCurrentCodexRecoveryPromptAttempt(pending, currentAttemptId, reason)) return;
+ gate = true;
+ recoveryEstablished = true;
+ });
+
+ pending = null;
+ gate = false;
+ currentAttemptId += 1;
+ resolveState('token_revoked');
+ await delayedHandoff;
+
+ expect(recoveryEstablished).toBe(false);
+ expect(gate).toBe(false);
+ expect(!gate).toBe(true);
+ expect(overlaySource).toContain('codexRecoveryPromptAttemptRef.current = null;');
+ expect(overlaySource).toContain('invalidateCodexRecoveryPrompt();');
+ });
+
+ it('keeps the overlay ChatGPT App capability narrowly trusted', () => {
+ expect(bootstrapSource).toContain('isGlobalVoiceInputOverlaySender(candidate.sender)');
+ expect(bootstrapSource).toContain('candidate.senderFrame === candidate.sender.mainFrame');
+ expect(bootstrapSource).toContain('isTrustedCindyRendererWindow(overlayWindow)');
+ expect(bootstrapSource).toContain('assertTrustedAppRendererEvent(candidate);');
+ });
});