Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(auth): expose saved accounts after session expiry

xd-boboc716666b2af6
diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsx
index dd2f225219..c5d1281d01 100644
--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx
+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx
@@ -1,4 +1,6 @@
import {
+ lazy,
+ Suspense,
useEffect,
useLayoutEffect,
useMemo,
@@ -103,6 +105,11 @@ const REGION_PILL_KEY: Partial<Record<typeof CURRENT_CINDY_REGION, string>> = {
};
const log = createLogger('LoginPage');
+const AccountSwitcherDialog = lazy(() =>
+ import('@/components/sidebar/AccountSwitcherDialog').then((module) => ({
+ default: module.AccountSwitcherDialog,
+ })),
+);
/**
* LoginPage — 桌面登录(wave4 白底体系 + figma §4 组件库)。
@@ -128,6 +135,7 @@ export function LoginPage({
hasAccountDeletionReceipt = false,
getAccountDeletionStatus,
clearAccountDeletionReceipt,
+ listAccounts,
dispatch,
dispatchWithResult,
clearError,
@@ -136,6 +144,27 @@ export function LoginPage({
const { t } = useTranslation();
const handoff = useLoginHandoff();
const isAddAccount = intent === 'add-account';
+ const accountSwitcherTriggerRef = useRef<HTMLButtonElement>(null);
+ const [accountSwitcherOpen, setAccountSwitcherOpen] = useState(false);
+ const [hasSavedAccounts, setHasSavedAccounts] = useState(false);
+
+ useEffect(() => {
+ if (isAddAccount || !listAccounts) {
+ setHasSavedAccounts(false);
+ return;
+ }
+ let active = true;
+ void listAccounts()
+ .then((snapshot) => {
+ if (active) setHasSavedAccounts(snapshot.accounts.length > 0);
+ })
+ .catch(() => {
+ if (active) setHasSavedAccounts(false);
+ });
+ return () => {
+ active = false;
+ };
+ }, [isAddAccount, listAccounts]);
// 主题跟随(DESIGN.md §16.5):首次打开 Cindy → 亮色登录界面(默认);第二次起
// → 跟随用户上一次使用的主题。首启亮色门在 bootstrap 已生效(品牌舞台首帧即
@@ -1281,29 +1310,52 @@ export function LoginPage({
? `opacity ${LOGIN_HANDOFF_TIMINGS.panelMs}ms ${LOGIN_HANDOFF_TIMINGS.panelEasing}, transform ${LOGIN_HANDOFF_TIMINGS.panelMs}ms ${LOGIN_HANDOFF_TIMINGS.panelEasing}`
: undefined,
};
- const localModeFooter = showLocalModeFooter ? (
- <>
+ const accountSwitcherEntry =
+ !isAddAccount && hasSavedAccounts && loginState?.step !== 'browser-redirect' ? (
<button
- data-testid="login-local-mode"
+ ref={accountSwitcherTriggerRef}
+ data-testid="login-account-switcher"
type="button"
- disabled={localModePending || isLoading}
- // error 步逃生入口与面板内文字按钮同口径:过协议门(2026-07-29 拍板)
- onClick={() => requireConsent(() => void openLocalMode(), { deferConsentPersist: true })}
- aria-describedby="login-local-mode-description"
- className="select-none rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-6 py-2.5 text-13 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:cursor-not-allowed disabled:opacity-60"
+ onClick={() => setAccountSwitcherOpen(true)}
+ className="select-none rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-6 py-2.5 text-13 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)]"
style={{ minHeight: 40 }}
>
- {localModePending ? t('login.localModeOpening') : t('login.localModeEntry')}
+ {t('sidebar.accountSwitcher.title')}
</button>
- <span
- id="login-local-mode-description"
- className="mt-2 line-clamp-2 max-w-full text-12 text-[var(--text-secondary)]"
- style={{ lineHeight: `${LOGIN_LOCAL_MODE.descriptionLineHeight}px` }}
- >
- {t('login.localModeDescription')}
- </span>
- </>
- ) : null;
+ ) : null;
+ const loginFooter =
+ showLocalModeFooter || accountSwitcherEntry ? (
+ <>
+ <div className="flex items-center justify-center gap-3">
+ {accountSwitcherEntry}
+ {showLocalModeFooter ? (
+ <button
+ data-testid="login-local-mode"
+ type="button"
+ disabled={localModePending || isLoading}
+ // error 步逃生入口与面板内文字按钮同口径:过协议门(2026-07-29 拍板)
+ onClick={() =>
+ requireConsent(() => void openLocalMode(), { deferConsentPersist: true })
+ }
+ aria-describedby="login-local-mode-description"
+ className="select-none rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-6 py-2.5 text-13 font-medium text-[var(--text-primary)] transition-colors hover:bg-[var(--surface-hover)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring-soft)] disabled:cursor-not-allowed disabled:opacity-60"
+ style={{ minHeight: 40 }}
+ >
+ {localModePending ? t('login.localModeOpening') : t('login.localModeEntry')}
+ </button>
+ ) : null}
+ </div>
+ {showLocalModeFooter ? (
+ <span
+ id="login-local-mode-description"
+ className="mt-2 line-clamp-2 max-w-full text-12 text-[var(--text-secondary)]"
+ style={{ lineHeight: `${LOGIN_LOCAL_MODE.descriptionLineHeight}px` }}
+ >
+ {t('login.localModeDescription')}
+ </span>
+ ) : null}
+ </>
+ ) : null;
return (
// 根级 z-[9990] 建立 LoginPage 自己的 stacking context:整体压过品牌 overlay
@@ -1313,11 +1365,24 @@ export function LoginPage({
<LoginStage
ssoOrgGroupY={ssoOrgGroupY}
groupStyle={groupStyle}
- footer={localModeFooter}
+ footer={loginFooter}
bottomReserve={panelBottomReserve}
>
{node}
</LoginStage>
+ {accountSwitcherOpen ? (
+ <Suspense fallback={null}>
+ <AccountSwitcherDialog
+ open
+ onOpenChange={setAccountSwitcherOpen}
+ onAddAccount={() => {
+ setAccountSwitcherOpen(false);
+ reset();
+ }}
+ triggerRef={accountSwitcherTriggerRef}
+ />
+ </Suspense>
+ ) : null}
{/* 注销状态提示气泡(figma 678:1075「注销状态」组件集):浮层——不占文档流、
不推挤下方内容,z-30 盖过 stage 全部内容(低于拖拽条 z-40 与协议弹窗 z-50);
窗口顶 72px 恒定、水平窗口居中、宽 670 恒定,均不随 loginScale 缩放。
diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx
index 238cde734e..3434edf02f 100644
--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx
+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.browserRedirect.test.tsx
@@ -13,6 +13,7 @@ const loginHook = vi.hoisted(() => ({
dispatch: vi.fn(),
dispatchWithResult: vi.fn(),
clearError: vi.fn(),
+ listAccounts: vi.fn(),
},
}));
@@ -40,6 +41,11 @@ vi.mock('@/components/title-bar/WindowControls', () => ({
WindowControls: () => null,
}));
+vi.mock('@/components/sidebar/AccountSwitcherDialog', () => ({
+ AccountSwitcherDialog: ({ open }: { open: boolean }) =>
+ open ? <div data-testid="account-switcher-dialog" /> : null,
+}));
+
import { LoginPage } from '../LoginPage';
describe('LoginPage browser redirect waiting state', () => {
@@ -53,6 +59,10 @@ describe('LoginPage browser redirect waiting state', () => {
dispatch: loginHook.dispatch,
dispatchWithResult: loginHook.dispatchWithResult,
clearError: vi.fn(),
+ listAccounts: vi.fn().mockResolvedValue({
+ accounts: [],
+ mutationAllowed: true,
+ }),
};
Object.defineProperty(window, 'electronAPI', {
configurable: true,
@@ -96,6 +106,38 @@ describe('LoginPage browser redirect waiting state', () => {
expect(screen.getByText('login.localModeDescription')).toBeTruthy();
});
+ it('makes retained accounts reachable from the signed-out error screen', async () => {
+ const listAccounts = vi.fn().mockResolvedValue({
+ accounts: [{ accountKey: 'saved-account' }],
+ mutationAllowed: true,
+ });
+ loginHook.value = {
+ isLoading: false,
+ errorCode: 'NETWORK_ERROR',
+ loginState: { step: 'error', code: 'NETWORK_ERROR', recoverTo: 'identifier' },
+ dispatch: loginHook.dispatch,
+ dispatchWithResult: loginHook.dispatchWithResult,
+ clearError: vi.fn(),
+ listAccounts,
+ } as unknown as typeof loginHook.value;
+
+ render(<LoginPage />);
+
+ const trigger = await screen.findByRole('button', {
+ name: 'sidebar.accountSwitcher.title',
+ });
+ expect(listAccounts).toHaveBeenCalledOnce();
+ fireEvent.click(trigger);
+ expect(await screen.findByTestId('account-switcher-dialog')).toBeTruthy();
+ });
+
+ it('does not advertise account switching when no reusable account remains', async () => {
+ render(<LoginPage />);
+
+ await vi.waitFor(() => expect(loginHook.value.listAccounts).toHaveBeenCalledOnce());
+ expect(screen.queryByRole('button', { name: 'sidebar.accountSwitcher.title' })).toBeNull();
+ });
+
it('disables local entry while a login request is pending', () => {
loginHook.value = {
isLoading: true,
@@ -108,8 +150,7 @@ describe('LoginPage browser redirect waiting state', () => {
render(<LoginPage />);
expect(
- (screen.getByRole('button', { name: 'login.localModeEntry' }) as HTMLButtonElement)
- .disabled,
+ (screen.getByRole('button', { name: 'login.localModeEntry' }) as HTMLButtonElement).disabled,
).toBe(true);
});
});
diff --git a/apps/desktop/src/renderer/hooks/useLogin.ts b/apps/desktop/src/renderer/hooks/useLogin.ts
index eb7662854c..1d7808d4f1 100644
--- a/apps/desktop/src/renderer/hooks/useLogin.ts
+++ b/apps/desktop/src/renderer/hooks/useLogin.ts
@@ -10,6 +10,7 @@ interface UseLoginReturn {
hasAccountDeletionReceipt: boolean;
getAccountDeletionStatus: ReturnType<typeof useAuth>['getAccountDeletionStatus'];
clearAccountDeletionReceipt: ReturnType<typeof useAuth>['clearAccountDeletionReceipt'];
+ listAccounts: ReturnType<typeof useAuth>['listAccounts'];
dispatch: (action: DesktopLoginAction) => Promise<boolean>;
/**
* 与 dispatch 同一条链路,但把失败码返回给调用方——captcha 兜底重试需要在
@@ -38,6 +39,7 @@ export function useLogin(): UseLoginReturn {
hasAccountDeletionReceipt,
getAccountDeletionStatus,
clearAccountDeletionReceipt,
+ listAccounts,
enterLocalMode,
} = useAuth();
const [isLoading, setIsLoading] = useState(false);
@@ -98,6 +100,7 @@ export function useLogin(): UseLoginReturn {
hasAccountDeletionReceipt,
getAccountDeletionStatus,
clearAccountDeletionReceipt,
+ listAccounts,
dispatch,
dispatchWithResult,
clearError: () => setErrorCode(null),
diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx
index 256a4429a4..a6ab74cd1a 100644
--- a/apps/mobile/app/(auth)/login.tsx
+++ b/apps/mobile/app/(auth)/login.tsx
@@ -76,6 +76,7 @@ import {
LoginSocialGlyph,
LoginSocialRow,
LoginSsoOrgHistoryList,
+ LoginTextAction,
LoginTextLinkSlot,
LoginTitleBlock,
AppleLogoGlyph,
@@ -86,6 +87,11 @@ import {
} from '@/components/MobileLoginHandoffStage';
import { AUTH_REGION, BUILD_AUTH_REGION, getMobileConfigIssues } from '@/config/env';
import { resolveIdentifierMethod } from '@/auth/loginIdentifierMethod';
+import { AccountSwitcherSheet } from '@/session/AccountSwitcherSheet';
+import {
+ remoteSessionStore,
+ useRemoteSessionStoreVersion,
+} from '@/session/remoteSessionStore';
import { fontWeight, iconSize, iconStroke, lineHeight, loginPalettes, loginSizes, radius, spacing, typeScale } from '@/theme/tokens';
/**
@@ -108,6 +114,14 @@ export function LoginScreen({
// 手动语言 override 恢复/切换时本屏跟着重渲(P2-a:不依赖 auth 重渲兜底)。
const { t } = useTranslation();
const auth = useAuth();
+ const remoteSessionStoreVersion = useRemoteSessionStoreVersion();
+ const hasRunningTasks = useMemo(
+ () =>
+ remoteSessionStore
+ .getSessions()
+ .some((session) => remoteSessionStore.isSessionRunning(session.id)),
+ [remoteSessionStoreVersion],
+ );
const stage = useLoginSurface();
const insets = useSafeAreaInsets();
// 舞台有效主题(首启亮色门可强制 light,与系统主题可能不一致):状态栏样式
@@ -263,6 +277,7 @@ export function LoginScreen({
const [resendDeadline, setResendDeadline] = useState<number | null>(null);
const [accountDeletionStatus, setAccountDeletionStatus] =
useState<AccountDeletionStatus | null>(null);
+ const [accountSwitcherVisible, setAccountSwitcherVisible] = useState(false);
const styles = useThemedStyles(makeStyles);
const configIssues = getMobileConfigIssues();
const disabled = auth.isBusy || !auth.initialized || configIssues.length > 0;
@@ -303,6 +318,11 @@ export function LoginScreen({
void auth.dispatchLoginAction({ type: 'reset' });
}, [additionalAccount, auth]);
+ useEffect(() => {
+ if (additionalAccount || !auth.initialized || auth.isAuthenticated) return;
+ void auth.syncSavedAccounts().catch(() => undefined);
+ }, [additionalAccount, auth.initialized, auth.isAuthenticated, auth.syncSavedAccounts]);
+
useEffect(() => {
if (auth.loginState?.step !== 'identifier') return;
setSsoOrgMode(false);
@@ -417,6 +437,15 @@ export function LoginScreen({
const errorNode = error ? (
<LoginErrorText testID="login.error">{error}</LoginErrorText>
) : null;
+ const accountRecoveryNode =
+ !additionalAccount && auth.savedAccounts.length > 0 ? (
+ <LoginTextAction
+ disabled={auth.isBusy}
+ label={t('devices.list.accounts.title')}
+ onPress={() => setAccountSwitcherVisible(true)}
+ testID="login.accountSwitcher"
+ />
+ ) : null;
const backNode = backAction ? (
<LoginBackButton
disabled={auth.isBusy}
@@ -649,6 +678,7 @@ export function LoginScreen({
onPress={submit}
testID="login.continueButton"
/>
+ {accountRecoveryNode}
{identifierErrorNode}
</LoginPanel>
{/* Apple 入口为圆钮行第一颗:iOS 走原生 Sign in with Apple,
@@ -1129,6 +1159,7 @@ export function LoginScreen({
onPress={reset}
testID="login.errorRetryButton"
/>
+ {accountRecoveryNode}
<LoginErrorText testID="login.error">
{authErrorText(state.code) ?? loginText('errorFallback')}
</LoginErrorText>
@@ -1182,6 +1213,7 @@ export function LoginScreen({
onPress={reset}
testID="login.retryButton"
/>
+ {accountRecoveryNode}
{errorNode}
</LoginPanel>
);
@@ -1408,6 +1440,15 @@ export function LoginScreen({
</Animated.View>
</View>
</View>
+ <AccountSwitcherSheet
+ hasRunningTasks={hasRunningTasks}
+ onAddAccount={() => {
+ setAccountSwitcherVisible(false);
+ reset();
+ }}
+ onClose={() => setAccountSwitcherVisible(false)}
+ visible={accountSwitcherVisible}
+ />
{accountDeletionStatus && deletionBubbleFrame ? (
// 入场门(PR #464 review,与桌面同口径):opacity 结构性跟随面板入场的
// Animated 值(splash=0 → handoff 渐显 → done=1,同一 usePanelEntrance 输出,
diff --git a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
index 01192bf6fe..36d87e29b7 100644
--- a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
@@ -49,6 +49,21 @@ function makeClient(scenario: string, region: AuthRegion = 'cn') {
}
describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {
+ it('keeps retained accounts reachable after the active session expires', () => {
+ expect(loginSource).toContain(
+ "import { AccountSwitcherSheet } from '@/session/AccountSwitcherSheet';",
+ );
+ expect(loginSource).toContain(
+ 'void auth.syncSavedAccounts().catch(() => undefined);',
+ );
+ expect(loginSource).toContain('auth.savedAccounts.length > 0');
+ expect(loginSource).toContain('testID="login.accountSwitcher"');
+ expect(loginSource).toContain("label={t('devices.list.accounts.title')}");
+ expect(loginSource).toContain('<AccountSwitcherSheet');
+ expect(loginSource).toContain('hasRunningTasks={hasRunningTasks}');
+ expect(loginSource).toContain('remoteSessionStore.isSessionRunning(session.id)');
+ });
+
it('identifier:providers 真链加载→identifier 步骤,区域定形态(无 tabs)/输入/主按钮/圆钮行接线', async () => {
const client = makeClient('providers:both');
const providers = await client.getProviders();
diff --git a/apps/mobile/src/components/LoginSkinControls.tsx b/apps/mobile/src/components/LoginSkinControls.tsx
index 78de9272af..e7690e9f19 100644
--- a/apps/mobile/src/components/LoginSkinControls.tsx
+++ b/apps/mobile/src/components/LoginSkinControls.tsx
@@ -1170,17 +1170,42 @@ export function LoginResendCountdown({
</View>
);
}
+ return (
+ <LoginTextAction
+ disabled={disabled}
+ label={resendLabel}
+ onPress={onResend}
+ testID={testID}
+ />
+ );
+}
+
+/** 登录面板内的次要文字动作,与验证码重发共用同一定位和视觉。 */
+export function LoginTextAction({
+ disabled,
+ label,
+ onPress,
+ testID,
+ top,
+}: {
+ disabled?: boolean;
+ label: string;
+ onPress: () => void;
+ testID?: string;
+ top?: number;
+}) {
+ const styles = useThemedStyles(makeStyles);
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ disabled }}
disabled={disabled}
- onPress={onResend}
- style={styles.textLinkSlotBox}
+ onPress={onPress}
+ style={[styles.textLinkSlotBox, top != null && { top }]}
testID={testID}
>
<Text numberOfLines={1} style={styles.resendLinkText}>
- {resendLabel}
+ {label}
</Text>
</Pressable>
);