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 after #6058: preserve known credential recovery on login back and skip

MagicLizid0d9e9f8fdfd
diff --git a/apps/desktop/src/main/__tests__/authLoginBack.test.ts b/apps/desktop/src/main/__tests__/authLoginBack.test.ts
index e5ed8a0616..d8c14a0e0b 100644
--- a/apps/desktop/src/main/__tests__/authLoginBack.test.ts
+++ b/apps/desktop/src/main/__tests__/authLoginBack.test.ts
@@ -31,7 +31,7 @@ function deferred<T>() {
return { promise, resolve, reject };
}
-function setup({ cached = false, sealed = false } = {}) {
+function setup({ cached = false, sealed = false, credentialStoreUnavailable = false } = {}) {
const getProviders = vi.fn<() => Promise<ProviderConfig>>();
const cancelActive = vi.fn();
const deps = {
@@ -43,6 +43,8 @@ function setup({ cached = false, sealed = false } = {}) {
awaitLoginProvidersWithPreparingGate: (promise: Promise<ProviderConfig>) => promise,
browserAuthorizationSlot: { cancelActive },
isLoginFlowCommitSealed: () => sealed,
+ isOwnerChangeShellPending: () => false,
+ credentialStoreUnavailable,
log: { warn: vi.fn() },
cachedProviders: cached ? providers : null,
};
@@ -52,13 +54,14 @@ function setup({ cached = false, sealed = false } = {}) {
let providerConfig = cachedProviders, sessionInvalidationPromise = null;
let loginActionPromise = null, loginActionPromiseEpoch = null, accessToken = null;
const AUTH_REGION = 'global', activeAuthRealm = 'global';
- const credentialStoreHealth = { unavailable: false };
+ const credentialStoreHealth = { unavailable: credentialStoreUnavailable };
let handledLoginEmail = null, pendingPersonalLogin = null, discoveredMethods = [];
let pendingAccountToken = null, pendingAccountRefreshToken = null, pendingAccountMemberships = [];
let pendingLoginTicket = 'old-ticket', pendingBindTicket = null, pendingSsoVerificationTicket = null;
let pendingAuthRealm = null, pendingAccountDeletionRestored = false;
${functionSource('function resetLoginFlowState()', 'function sealLoginFlowCommit(')}
${functionSource('async function loadLoginProviders(', 'async function discoverOrganizationRealm(')}
+ ${functionSource('export async function getLoginState()', 'async function completeLogin(')}
${functionSource('async function runLoginAction(', 'export async function refresh(')}
return {
dispatch: dispatchLoginAction,
@@ -75,6 +78,19 @@ function setup({ cached = false, sealed = false } = {}) {
}
describe('login Back without an auth-server round trip', () => {
+ it.each([false, true])('preserves credential recovery and private progress (cached=%s)', async (cached) => {
+ const main = setup({ cached, credentialStoreUnavailable: true });
+ expect(await main.dispatch({ type: 'back' })).toEqual({
+ success: false,
+ code: 'CREDENTIAL_STORE_UNAVAILABLE',
+ state: { step: 'error', code: 'CREDENTIAL_STORE_UNAVAILABLE', recoverTo: 'identifier' },
+ });
+ expect(main.snapshot().ticket).toBe('old-ticket');
+ expect(main.snapshot().epoch).toBe(1);
+ expect(main.cancelActive).not.toHaveBeenCalled();
+ expect(main.getProviders).not.toHaveBeenCalled();
+ });
+
it.each([false, true])(
'returns locally and clears private progress (cached=%s)',
async (cached) => {
diff --git a/apps/desktop/src/main/authManager.ts b/apps/desktop/src/main/authManager.ts
index f07261faab..26dddebfd9 100644
--- a/apps/desktop/src/main/authManager.ts
+++ b/apps/desktop/src/main/authManager.ts
@@ -5685,6 +5685,7 @@ export async function dispatchLoginAction(action: unknown): Promise<DesktopLogin
if (isLoginFlowCommitSealed(loginFlowEpoch)) {
return { success: false, code: 'LOGIN_BUSY', state: loginFlowState };
}
+ if (!accessToken && credentialStoreHealth.unavailable) return getLoginState();
const providers = providerConfig;
loginFlowEpoch += 1;
browserAuthorizationSlot.cancelActive();
diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsx
index fdff529107..0b60947923 100644
--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx
+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx
@@ -130,6 +130,7 @@ export function LoginPage({
errorCode,
retryAt,
loginState,
+ credentialStoreUnavailable = false,
hasAccountDeletionReceipt = false,
getAccountDeletionStatus,
clearAccountDeletionReceipt,
@@ -141,6 +142,7 @@ export function LoginPage({
const { t, i18n } = useTranslation();
const [credentialHelpOpen, setCredentialHelpOpen] = useState(false);
const credentialStoreFailed =
+ credentialStoreUnavailable ||
errorCode === 'CREDENTIAL_STORE_UNAVAILABLE' ||
(loginState?.step === 'error' && loginState.code === 'CREDENTIAL_STORE_UNAVAILABLE');
const rateLimited =
@@ -195,7 +197,12 @@ export function LoginPage({
* 面板内入口仍由按钮 disabled 与协议门的 busy 复验挡住 in-flight。
*/
const openLocalMode = async () => {
- if ((isLoading && !canLeaveProviderLoad) || localModePendingRef.current || !enterLocalMode) return;
+ if (
+ credentialStoreFailed ||
+ (isLoading && !canLeaveProviderLoad) ||
+ localModePendingRef.current ||
+ !enterLocalMode
+ ) return;
markLocalModeTransition(true);
try {
// 必须走 AuthContext.enterLocalMode():它调同一条 IPC,并用返回值立刻改
@@ -1286,49 +1293,10 @@ export function LoginPage({
if (isAddAccount && onClose) onClose();
else void dispatch({ type: 'back' });
};
- if (loginState?.step === 'entry') {
- // No provider config has arrived yet. Offer an explicit retry without
- // inventing server-enabled login methods or automatically starting a load.
- return {
- ssoOrgGroupY: false,
- node: (
- <LoginPanel testId="login-panel-entry">
- {isLoading && (
- <LoginBackButton
- label={t('login.back')}
- disabled={localModePending}
- onClick={backToEntry}
- />
- )}
- <LoginTitleBlock title={t('login.title')} subtitle={t('login.subtitle')} />
- <LoginPrimaryButton loading={isLoading} onClick={reset} testId="login-entry-continue">
- {t(isLoading ? 'login.working' : 'login.continue')}
- </LoginPrimaryButton>
- </LoginPanel>
- ),
- };
- }
- // preparing 伪态(loginState 尚未就绪;figma 5.2 准备态:loading 64 @(308,193))
- if (!loginState) {
- return {
- ssoOrgGroupY: false,
- node: (
- <LoginPanel testId="login-panel-preparing">
- <LoginBackButton
- label={t('login.back')}
- disabled={localModePending}
- onClick={backToEntry}
- />
- <LoginTitleBlock title={t('login.preparing')} subtitle={t('login.preparingSubtitle')} />
- <LoginLoadingRing y={LOADING_RING.yPreparing} label={t('login.working')} />
- </LoginPanel>
- ),
- };
- }
- if (loginState.step === 'error' || credentialStoreFailed || rateLimited) {
+ if (loginState?.step === 'error' || credentialStoreFailed || rateLimited) {
// A rate limit can cover a still-valid form. Dismiss only the notice:
// resetting main's flow would discard its ticket and require another code.
- const resumeForm = rateLimited && loginState.step !== 'error';
+ const resumeForm = rateLimited && loginState !== null && !canLeaveProviderLoad;
const returnFromError = () => {
if (localModePendingRef.current) return;
if (isAddAccount && onClose) {
@@ -1397,7 +1365,7 @@ export function LoginPage({
`login.errors.${
credentialStoreFailed
? 'CREDENTIAL_STORE_UNAVAILABLE'
- : loginState.step === 'error'
+ : loginState?.step === 'error'
? loginState.code
: errorCode
}`,
@@ -1410,6 +1378,45 @@ export function LoginPage({
),
};
}
+ if (loginState?.step === 'entry') {
+ // No provider config has arrived yet. Offer an explicit retry without
+ // inventing server-enabled login methods or automatically starting a load.
+ return {
+ ssoOrgGroupY: false,
+ node: (
+ <LoginPanel testId="login-panel-entry">
+ {isLoading && (
+ <LoginBackButton
+ label={t('login.back')}
+ disabled={localModePending}
+ onClick={backToEntry}
+ />
+ )}
+ <LoginTitleBlock title={t('login.title')} subtitle={t('login.subtitle')} />
+ <LoginPrimaryButton loading={isLoading} onClick={reset} testId="login-entry-continue">
+ {t(isLoading ? 'login.working' : 'login.continue')}
+ </LoginPrimaryButton>
+ </LoginPanel>
+ ),
+ };
+ }
+ // preparing 伪态(loginState 尚未就绪;figma 5.2 准备态:loading 64 @(308,193))
+ if (!loginState) {
+ return {
+ ssoOrgGroupY: false,
+ node: (
+ <LoginPanel testId="login-panel-preparing">
+ <LoginBackButton
+ label={t('login.back')}
+ disabled={localModePending}
+ onClick={backToEntry}
+ />
+ <LoginTitleBlock title={t('login.preparing')} subtitle={t('login.preparingSubtitle')} />
+ <LoginLoadingRing y={LOADING_RING.yPreparing} label={t('login.working')} />
+ </LoginPanel>
+ ),
+ };
+ }
if (loginState.step === 'browser-redirect') {
return {
ssoOrgGroupY: false,
diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx
index 6026ab216c..6c8eeea8f7 100644
--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx
+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.initialization.test.tsx
@@ -17,6 +17,8 @@ const auth = vi.hoisted(() => ({
loadLoginState: vi.fn<() => Promise<DesktopLoginActionResult>>(),
beginAddAccount: vi.fn<() => Promise<DesktopLoginActionResult>>(),
cancelAddAccount: vi.fn(async () => undefined),
+ enterLocalMode: vi.fn(async () => undefined),
+ acceptPrivacyConsent: vi.fn(async () => undefined),
dispatchLoginAction: vi.fn<(action: DesktopLoginAction) => Promise<DesktopLoginActionResult>>(),
}));
@@ -37,14 +39,24 @@ let identifierState: AuthFlowState;
let publishState: (state: DesktopLoginState | null) => void;
let epoch: number;
-function Harness({ addAccount = false }: { addAccount?: boolean }) {
- const [loginState, setLoginState] = useState<DesktopLoginState | null>(null);
+function Harness({
+ addAccount = false,
+ credentialStoreUnavailable = false,
+ initialState = null,
+}: {
+ addAccount?: boolean;
+ credentialStoreUnavailable?: boolean;
+ initialState?: DesktopLoginState | null;
+}) {
+ const [loginState, setLoginState] = useState<DesktopLoginState | null>(initialState);
publishState = setLoginState;
auth.value = {
loginState,
+ credentialStoreUnavailable,
loadLoginState: auth.loadLoginState,
beginAddAccount: auth.beginAddAccount,
cancelAddAccount: auth.cancelAddAccount,
+ enterLocalMode: auth.enterLocalMode,
dispatchLoginAction: auth.dispatchLoginAction,
};
return (
@@ -58,7 +70,7 @@ beforeEach(async () => {
epoch = 0;
Object.defineProperty(window, 'electronAPI', {
configurable: true,
- value: { platform: 'darwin' },
+ value: { platform: 'darwin', acceptPrivacyConsent: auth.acceptPrivacyConsent },
});
const providers = await new CindyAuthClient({
baseUrl: 'https://auth.scenario.invalid',
@@ -92,6 +104,37 @@ afterEach(() => {
});
describe('login initialization ownership', () => {
+ it.each([null, { step: 'entry' } as const])(
+ 'shows known credential recovery before a login response arrives from %j',
+ (initialState) => {
+ auth.loadLoginState.mockImplementation(() => new Promise(() => undefined));
+ render(<Harness credentialStoreUnavailable initialState={initialState} />);
+
+ expect(screen.getByTestId('login-panel-error')).toBeTruthy();
+ expect(screen.getByText('credentialStore.dialog.title')).toBeTruthy();
+ expect(screen.queryByTestId('login-panel-preparing')).toBeNull();
+ expect(screen.queryByTestId('login-panel-entry')).toBeNull();
+ expect(screen.queryByTestId('login-local-mode')).toBeNull();
+ expect(auth.enterLocalMode).not.toHaveBeenCalled();
+ expect(auth.acceptPrivacyConsent).not.toHaveBeenCalled();
+ },
+ );
+
+ it('withdraws pending skip consent when credential health fails before the login response', () => {
+ auth.loadLoginState.mockImplementation(() => new Promise(() => undefined));
+ const view = render(<Harness />);
+ fireEvent.click(screen.getByTestId('login-local-mode'));
+ expect(screen.getByTestId('login-consent-dialog')).toBeTruthy();
+
+ view.rerender(<Harness credentialStoreUnavailable />);
+
+ expect(screen.getByTestId('login-panel-error')).toBeTruthy();
+ expect(screen.queryByTestId('login-consent-dialog')).toBeNull();
+ expect(screen.queryByTestId('login-local-mode')).toBeNull();
+ expect(auth.enterLocalMode).not.toHaveBeenCalled();
+ expect(auth.acceptPrivacyConsent).not.toHaveBeenCalled();
+ });
+
it.each([false, true])(
'leaves an initialization error without requesting providers (addAccount=%s)',
async (addAccount) => {
diff --git a/apps/desktop/src/renderer/hooks/useLogin.ts b/apps/desktop/src/renderer/hooks/useLogin.ts
index 80140d0611..5013e431d4 100644
--- a/apps/desktop/src/renderer/hooks/useLogin.ts
+++ b/apps/desktop/src/renderer/hooks/useLogin.ts
@@ -8,6 +8,7 @@ interface UseLoginReturn {
errorCode: string | null;
retryAt: number | undefined;
loginState: ReturnType<typeof useAuth>['loginState'];
+ credentialStoreUnavailable: ReturnType<typeof useAuth>['credentialStoreUnavailable'];
hasAccountDeletionReceipt: boolean;
getAccountDeletionStatus: ReturnType<typeof useAuth>['getAccountDeletionStatus'];
clearAccountDeletionReceipt: ReturnType<typeof useAuth>['clearAccountDeletionReceipt'];
@@ -35,6 +36,7 @@ interface UseLoginReturn {
export function useLogin({ autoLoad = true }: { autoLoad?: boolean } = {}): UseLoginReturn {
const {
loginState,
+ credentialStoreUnavailable,
loadLoginState,
dispatchLoginAction,
hasAccountDeletionReceipt,
@@ -130,6 +132,7 @@ export function useLogin({ autoLoad = true }: { autoLoad?: boolean } = {}): UseL
? loginState?.retryAt
: undefined,
loginState,
+ credentialStoreUnavailable,
hasAccountDeletionReceipt,
getAccountDeletionStatus,
clearAccountDeletionReceipt,