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。

feat(auth): 记住组织 SSO 登录标识 (#3187)

klcb648cfdc264
diff --git a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
index de90cae559..e12966a19d 100644
--- a/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/authContextSessionBoundary.test.tsx
@@ -94,6 +94,7 @@ import {
addModelFavorite,
listModelFavorites,
} from '@/state/modelFavorites';
+import { __testing as ssoOrgHistoryTesting } from '@/state/ssoOrgHistory';
function user(id: string) {
return {
@@ -157,6 +158,7 @@ describe('AuthContext session cache boundaries', () => {
restoredToast.mockClear();
mocks.confirm.mockClear();
mocks.service.initialize.mockResolvedValue(authState('account-a'));
+ mocks.service.dispatchLoginAction.mockReset();
mocks.service.logout.mockResolvedValue(undefined);
mocks.service.enterLocalMode.mockResolvedValue(localAuthState());
mocks.service.exitLocalMode.mockResolvedValue(authState(null));
@@ -165,6 +167,8 @@ describe('AuthContext session cache boundaries', () => {
).electronAPI = {
onAuthSessionExpired: mocks.registerExpired,
};
+ window.localStorage.clear();
+ ssoOrgHistoryTesting.reset();
});
afterEach(() => {
@@ -375,6 +379,91 @@ describe('AuthContext session cache boundaries', () => {
expect(view.result.current.loginState).toBeNull();
});
+ it('remembers successful organization discovery before sole-SSO browser auth settles', async () => {
+ const providers = { email: true, phone: false, social: [] };
+ const identifierState = { step: 'identifier' as const, providers };
+ const methodChoiceState = {
+ step: 'method-choice' as const,
+ email: '',
+ methods: [
+ {
+ type: 'sso' as const,
+ connectionId: 'conn-1',
+ protocol: 'oidc' as const,
+ orgName: 'Example Corp',
+ connectionName: 'Example SSO',
+ ssoRequired: false,
+ },
+ ],
+ };
+ let resolveBrowser!: (result: unknown) => void;
+ mocks.service.initialize.mockResolvedValue(authState(null));
+ mocks.service.dispatchLoginAction
+ .mockResolvedValueOnce({ success: true, state: methodChoiceState })
+ .mockReturnValueOnce(
+ new Promise((resolve) => {
+ resolveBrowser = resolve;
+ }),
+ );
+
+ const view = renderHook(() => useAuth(), { wrapper });
+ await waitFor(() => expect(view.result.current.mode).toBe('signed-out'));
+
+ let pending!: ReturnType<typeof view.result.current.dispatchLoginAction>;
+ act(() => {
+ pending = view.result.current.dispatchLoginAction({
+ type: 'discover-sso-org',
+ org: 'Example-Corp',
+ });
+ });
+ await waitFor(() =>
+ expect(mocks.service.dispatchLoginAction).toHaveBeenCalledTimes(2),
+ );
+ expect(
+ JSON.parse(
+ window.localStorage.getItem(ssoOrgHistoryTesting.storageKey) ?? '{}',
+ ),
+ ).toEqual({
+ version: 1,
+ entries: ['Example-Corp'],
+ });
+
+ await act(async () => {
+ resolveBrowser({
+ success: false,
+ code: 'USER_CANCELLED',
+ state: identifierState,
+ });
+ await expect(pending).resolves.toMatchObject({
+ success: false,
+ code: 'USER_CANCELLED',
+ });
+ });
+ });
+
+ it('does not remember an organization when discovery itself fails', async () => {
+ const providers = { email: true, phone: false, social: [] };
+ mocks.service.initialize.mockResolvedValue(authState(null));
+ mocks.service.dispatchLoginAction.mockResolvedValueOnce({
+ success: false,
+ code: 'ORG_SSO_NOT_FOUND',
+ state: { step: 'identifier', providers },
+ });
+
+ const view = renderHook(() => useAuth(), { wrapper });
+ await waitFor(() => expect(view.result.current.mode).toBe('signed-out'));
+ await act(async () => {
+ await view.result.current.dispatchLoginAction({
+ type: 'discover-sso-org',
+ org: 'missing-corp',
+ });
+ });
+
+ expect(
+ window.localStorage.getItem(ssoOrgHistoryTesting.storageKey),
+ ).toBeNull();
+ });
+
/**
* 本地模式也是一次 dataOwnerId 切换。enterLocalMode / exitLocalMode 必须走完整
* applyIncomingState,不能自己拼半套 setter —— 漏接任一 owner 分区都会让本地模式
diff --git a/apps/desktop/src/renderer/components/login/LoginControls.tsx b/apps/desktop/src/renderer/components/login/LoginControls.tsx
index 4402bbf949..434488a9c8 100644
--- a/apps/desktop/src/renderer/components/login/LoginControls.tsx
+++ b/apps/desktop/src/renderer/components/login/LoginControls.tsx
@@ -1,5 +1,11 @@
import { useEffect, useRef, useState } from 'react';
-import type { CSSProperties, KeyboardEvent as ReactKeyboardEvent, ReactNode } from 'react';
+import type {
+ CSSProperties,
+ FocusEvent as ReactFocusEvent,
+ KeyboardEvent as ReactKeyboardEvent,
+ MouseEvent as ReactMouseEvent,
+ ReactNode,
+} from 'react';
import { cn } from '@/lib/utils';
@@ -18,6 +24,7 @@ import {
SKIP_ENTRY,
SOCIAL,
SPINNER,
+ SSO_ORG_HISTORY,
SUBTITLE,
TEXT_LINK,
TITLE,
@@ -204,6 +211,14 @@ export function LoginInput({
top = CONTROL.inputY,
prefix,
testId,
+ onFocus,
+ onBlur,
+ onClick,
+ onKeyDown,
+ role,
+ ariaControls,
+ ariaExpanded,
+ ariaActiveDescendant,
}: {
value: string;
onChange: (next: string) => void;
@@ -222,6 +237,14 @@ export function LoginInput({
/** 固定前缀块文本(仅左对齐形态;undefined = 无前缀,布局与旧版逐字节一致)。 */
prefix?: string;
testId?: string;
+ onFocus?: (event: ReactFocusEvent<HTMLInputElement>) => void;
+ onBlur?: (event: ReactFocusEvent<HTMLInputElement>) => void;
+ onClick?: (event: ReactMouseEvent<HTMLInputElement>) => void;
+ onKeyDown?: (event: ReactKeyboardEvent<HTMLInputElement>) => void;
+ role?: 'combobox';
+ ariaControls?: string;
+ ariaExpanded?: boolean;
+ ariaActiveDescendant?: string;
}) {
const filled = value.length > 0;
const prefixNode = prefix != null && !center && (
@@ -256,7 +279,14 @@ export function LoginInput({
pattern={pattern}
value={value}
onChange={(event) => onChange(event.target.value)}
+ onClick={onClick}
+ onKeyDown={onKeyDown}
placeholder={placeholder}
+ role={role}
+ aria-autocomplete={role === 'combobox' ? 'list' : undefined}
+ aria-controls={ariaControls}
+ aria-expanded={ariaExpanded}
+ aria-activedescendant={ariaActiveDescendant}
className={cn(
'absolute box-border appearance-none overflow-hidden whitespace-nowrap outline-none',
'login-skin-input transition-none',
@@ -299,6 +329,7 @@ export function LoginInput({
if (!error) event.currentTarget.style.borderColor = LOGIN_COLORS.controlBorderActive;
event.currentTarget.style.fontWeight = '700';
event.currentTarget.style.color = LOGIN_COLORS.controlText;
+ onFocus?.(event);
}}
onBlur={(event) => {
const nowFilled = event.currentTarget.value.length > 0;
@@ -311,12 +342,95 @@ export function LoginInput({
event.currentTarget.style.color = nowFilled
? LOGIN_COLORS.controlText
: LOGIN_COLORS.controlPlaceholder;
+ onBlur?.(event);
}}
/>
</>
);
}
+export function ssoOrgHistoryOptionId(index: number): string {
+ return `login-sso-org-history-option-${index}`;
+}
+
+/** Visual-only listbox for recent successful organization identifiers. */
+export function LoginSsoOrgHistoryList({
+ entries,
+ value,
+ activeIndex,
+ onActiveIndexChange,
+ onSelect,
+ listId,
+}: {
+ entries: readonly string[];
+ value: string;
+ activeIndex: number;
+ onActiveIndexChange: (index: number) => void;
+ onSelect: (entry: string) => void;
+ listId: string;
+}) {
+ const selectedKey = value.trim().toLowerCase();
+ const optionRefs = useRef<Array<HTMLButtonElement | null>>([]);
+ useEffect(() => {
+ if (activeIndex < 0) return;
+ optionRefs.current[activeIndex]?.scrollIntoView({ block: 'nearest' });
+ }, [activeIndex]);
+ return (
+ <div
+ id={listId}
+ data-testid="login-sso-org-history-list"
+ role="listbox"
+ className="absolute z-[4] box-border overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
+ style={{
+ left: SSO_ORG_HISTORY.x,
+ top: SSO_ORG_HISTORY.y,
+ width: SSO_ORG_HISTORY.width,
+ maxHeight: SSO_ORG_HISTORY.maxHeight,
+ borderRadius: SSO_ORG_HISTORY.radius,
+ background: LOGIN_COLORS.panelBg,
+ border: `1px solid ${LOGIN_COLORS.controlBorder}`,
+ }}
+ >
+ {entries.map((entry, index) => {
+ const highlighted = activeIndex === index || entry.toLowerCase() === selectedKey;
+ return (
+ <button
+ id={ssoOrgHistoryOptionId(index)}
+ key={entry.toLowerCase()}
+ ref={(node) => {
+ optionRefs.current[index] = node;
+ }}
+ type="button"
+ role="option"
+ aria-selected={entry.toLowerCase() === selectedKey}
+ data-testid={`login-sso-org-history-option-${index}`}
+ tabIndex={-1}
+ className="flex w-full items-center border-0 text-left hover:bg-[var(--login-action-control-bg)]"
+ style={{
+ minHeight: SSO_ORG_HISTORY.rowMinHeight,
+ paddingLeft: SSO_ORG_HISTORY.paddingX,
+ paddingRight: SSO_ORG_HISTORY.paddingX,
+ paddingTop: SSO_ORG_HISTORY.paddingY,
+ paddingBottom: SSO_ORG_HISTORY.paddingY,
+ borderRadius: SSO_ORG_HISTORY.rowRadius,
+ background: highlighted ? LOGIN_COLORS.actionControlBg : 'transparent',
+ color: LOGIN_COLORS.controlText,
+ fontSize: SSO_ORG_HISTORY.fontSize,
+ lineHeight: `${SSO_ORG_HISTORY.lineHeight}px`,
+ overflowWrap: 'anywhere',
+ }}
+ onMouseEnter={() => onActiveIndexChange(index)}
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => onSelect(entry)}
+ >
+ {entry}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
/**
* 主按钮(§4.3 五态:normal/hover 白 8%/pressed 黑 50%/loading spinner 24@(487,27)/
* disabled 白 70% 叠层+边 #B4B4B4+文字 80%)。文字保持居中,spinner 绝对定位。
diff --git a/apps/desktop/src/renderer/components/login/LoginPage.tsx b/apps/desktop/src/renderer/components/login/LoginPage.tsx
index aa21d771f2..ab4261f262 100644
--- a/apps/desktop/src/renderer/components/login/LoginPage.tsx
+++ b/apps/desktop/src/renderer/components/login/LoginPage.tsx
@@ -6,6 +6,7 @@ import {
useState,
type CSSProperties,
type FormEvent,
+ type KeyboardEvent as ReactKeyboardEvent,
type ReactNode,
} from 'react';
import { useTranslation } from 'react-i18next';
@@ -49,8 +50,10 @@ import {
LoginSkipEntry,
LoginSocialButton,
LoginSocialRow,
+ LoginSsoOrgHistoryList,
LoginTextLink,
LoginTitleBlock,
+ ssoOrgHistoryOptionId,
} from './LoginControls';
import { useResendCountdown } from './useResendCountdown';
import { CURRENT_CINDY_REGION } from '../../../shared/brandRegion';
@@ -67,6 +70,7 @@ import {
} from './loginDesignTokens';
import { PANEL_FIXED_SCALE } from './loginScale';
import { canResumePendingConsent, makeConsentStamp, type ConsentStamp } from './consentGate';
+import { getSsoOrgHistory } from '@/state/ssoOrgHistory';
/**
* 标题旁区域徽标的 i18n key(2026-07-27 拍板)。
@@ -342,7 +346,10 @@ export function LoginPage() {
// (规则 9:能代码化的格式校验不甩给 server 往返);与 server errorCode 互斥展示
// (本地错误优先),输入变更即清除。null = 无本地格式错误。
const [identifierFormatError, setIdentifierFormatError] = useState<VerificationKind | null>(null);
- const [ssoOrg, setSsoOrg] = useState('');
+ const [ssoOrgHistory, setSsoOrgHistory] = useState(() => getSsoOrgHistory());
+ const [ssoOrg, setSsoOrg] = useState(() => ssoOrgHistory[0] ?? '');
+ const [ssoOrgHistoryOpen, setSsoOrgHistoryOpen] = useState(false);
+ const [ssoOrgHistoryActiveIndex, setSsoOrgHistoryActiveIndex] = useState(-1);
const [verificationCode, setVerificationCode] = useState('');
const [ssoVerificationCode, setSsoVerificationCode] = useState('');
const [bindingContact, setBindingContact] = useState('');
@@ -602,9 +609,51 @@ export function LoginPage() {
if (localModePendingRef.current) return;
const value = ssoOrg.trim();
if (!value) return;
+ setSsoOrgHistoryOpen(false);
+ setSsoOrgHistoryActiveIndex(-1);
// 组织区域先静默发现;仅当结果与安装包区域不一致时,main 状态机进入
// realm-confirmation,由下方弹窗在继续 SSO 前向用户确认。
- void dispatch({ type: 'discover-sso-org', org: value });
+ void dispatch({ type: 'discover-sso-org', org: value }).finally(() => {
+ setSsoOrgHistory(getSsoOrgHistory());
+ });
+ };
+
+ const openSsoOrgHistory = () => {
+ if (ssoOrgHistory.length <= 1) return;
+ setSsoOrgHistoryOpen(true);
+ setSsoOrgHistoryActiveIndex(-1);
+ };
+
+ const selectSsoOrgHistory = (entry: string) => {
+ setSsoOrg(entry);
+ setSsoOrgHistoryOpen(false);
+ setSsoOrgHistoryActiveIndex(-1);
+ clearError();
+ };
+
+ const handleSsoOrgHistoryKeyDown = (event: ReactKeyboardEvent<HTMLInputElement>) => {
+ if (ssoOrgHistory.length <= 1) return;
+ if (event.key === 'Escape') {
+ setSsoOrgHistoryOpen(false);
+ setSsoOrgHistoryActiveIndex(-1);
+ return;
+ }
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
+ event.preventDefault();
+ setSsoOrgHistoryOpen(true);
+ setSsoOrgHistoryActiveIndex((current) => {
+ if (event.key === 'ArrowDown') {
+ return current < ssoOrgHistory.length - 1 ? current + 1 : 0;
+ }
+ return current > 0 ? current - 1 : ssoOrgHistory.length - 1;
+ });
+ return;
+ }
+ if (event.key === 'Enter' && ssoOrgHistoryOpen && ssoOrgHistoryActiveIndex >= 0) {
+ event.preventDefault();
+ const selected = ssoOrgHistory[ssoOrgHistoryActiveIndex];
+ if (selected) selectSsoOrgHistory(selected);
+ }
};
/* ── identifier 主视图(680×620 组:面板 680×500 + 第三方圆钮行) ── */
@@ -715,6 +764,11 @@ export function LoginPage() {
// 期间要自己挡:那道 guard 在 requireConsent 里,这条路径绕过了它。
if (isLoading || localModePendingRef.current) return;
clearError();
+ const nextHistory = getSsoOrgHistory();
+ setSsoOrgHistory(nextHistory);
+ if (!ssoOrg.trim()) setSsoOrg(nextHistory[0] ?? '');
+ setSsoOrgHistoryOpen(false);
+ setSsoOrgHistoryActiveIndex(-1);
setSsoOrgMode(true);
}}
>
@@ -736,54 +790,86 @@ export function LoginPage() {
/* ── 企业 SSO 入口子视图(sso-org empty/filled;面板 680×500,无跳过入口) ── */
const renderSsoOrg = () => (
- <LoginPanel testId="login-panel-sso-org">
- <form onSubmit={submitSsoOrg} noValidate>
- <LoginBackButton
- disabled={isLoading}
- label={t('login.back')}
- onClick={() => {
- clearError();
- setSsoOrgMode(false);
- }}
- />
- <LoginTitleBlock title={t('login.ssoOrgTitle')} subtitle={t('login.ssoOrgSubtitle')} />
- <LoginInput
- autoFocus
- disabled={isLoading}
- maxLength={253}
- autoComplete="off"
+ <>
+ <LoginPanel testId="login-panel-sso-org">
+ <form onSubmit={submitSsoOrg} noValidate>
+ <LoginBackButton
+ disabled={isLoading}
+ label={t('login.back')}
+ onClick={() => {
+ clearError();
+ setSsoOrgHistoryOpen(false);
+ setSsoOrgHistoryActiveIndex(-1);
+ setSsoOrgMode(false);
+ }}
+ />
+ <LoginTitleBlock title={t('login.ssoOrgTitle')} subtitle={t('login.ssoOrgSubtitle')} />
+ <LoginInput
+ autoFocus={ssoOrgHistory.length <= 1}
+ disabled={isLoading}
+ maxLength={253}
+ autoComplete="off"
+ value={ssoOrg}
+ onChange={(value) => {
+ setSsoOrg(value);
+ setSsoOrgHistoryActiveIndex(-1);
+ }}
+ onFocus={openSsoOrgHistory}
+ onClick={openSsoOrgHistory}
+ onBlur={() => {
+ setSsoOrgHistoryOpen(false);
+ setSsoOrgHistoryActiveIndex(-1);
+ }}
+ onKeyDown={handleSsoOrgHistoryKeyDown}
+ role="combobox"
+ ariaControls="login-sso-org-history-list"
+ ariaExpanded={ssoOrgHistoryOpen}
+ ariaActiveDescendant={
+ ssoOrgHistoryOpen && ssoOrgHistoryActiveIndex >= 0
+ ? ssoOrgHistoryOptionId(ssoOrgHistoryActiveIndex)
+ : undefined
+ }
+ placeholder={t('login.ssoOrgPlaceholder')}
+ error={!!errorCode}
+ testId="login-sso-org-input"
+ />
+ {/* 帮助行(无下划线、次级色;顶对齐 ≤2 行,DESIGN.md §16.2 折行分级 2) */}
+ <span
+ className="absolute line-clamp-2 text-center"
+ style={{
+ left: SSO_ORG_HINT.x,
+ top: SSO_ORG_HINT.y,
+ width: SSO_ORG_HINT.width,
+ height: SSO_ORG_HINT.lineHeight * SSO_ORG_HINT.maxLines,
+ lineHeight: `${SSO_ORG_HINT.lineHeight}px`,
+ fontSize: SSO_ORG_HINT.fontSize,
+ color: LOGIN_COLORS.secondaryText,
+ }}
+ >
+ {t('login.ssoOrgHint')}
+ </span>
+ <LoginPrimaryButton
+ type="submit"
+ disabled={!ssoOrg.trim()}
+ loading={isLoading}
+ testId="login-sso-org-continue"
+ >
+ {isLoading ? t('login.working') : t('login.continue')}
+ </LoginPrimaryButton>
+ {errorMessage && <LoginErrorText>{errorMessage}</LoginErrorText>}
+ </form>
+ </LoginPanel>
+ {ssoOrgHistoryOpen && ssoOrgHistory.length > 1 && (
+ <LoginSsoOrgHistoryList
+ entries={ssoOrgHistory}
value={ssoOrg}
- onChange={setSsoOrg}
- placeholder={t('login.ssoOrgPlaceholder')}
- error={!!errorCode}
- testId="login-sso-org-input"
+ activeIndex={ssoOrgHistoryActiveIndex}
+ onActiveIndexChange={setSsoOrgHistoryActiveIndex}
+ onSelect={selectSsoOrgHistory}
+ listId="login-sso-org-history-list"
/>
- {/* 帮助行(无下划线、次级色;顶对齐 ≤2 行,DESIGN.md §16.2 折行分级 2) */}
- <span
- className="absolute line-clamp-2 text-center"
- style={{
- left: SSO_ORG_HINT.x,
- top: SSO_ORG_HINT.y,
- width: SSO_ORG_HINT.width,
- height: SSO_ORG_HINT.lineHeight * SSO_ORG_HINT.maxLines,
- lineHeight: `${SSO_ORG_HINT.lineHeight}px`,
- fontSize: SSO_ORG_HINT.fontSize,
- color: LOGIN_COLORS.secondaryText,
- }}
- >
- {t('login.ssoOrgHint')}
- </span>
- <LoginPrimaryButton
- type="submit"
- disabled={!ssoOrg.trim()}
- loading={isLoading}
- testId="login-sso-org-continue"
- >
- {isLoading ? t('login.working') : t('login.continue')}
- </LoginPrimaryButton>
- {errorMessage && <LoginErrorText>{errorMessage}</LoginErrorText>}
- </form>
- </LoginPanel>
+ )}
+ </>
);
/* ── method-choice(含 sso-org-list 来源变体) ── */
diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsx
index 62836dbe41..0fe4cb4f8a 100644
--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsx
+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.captcha.harness.test.tsx
@@ -293,7 +293,8 @@ describe('LoginPage captcha 前置闸(providers 主动触发)', () => {
const duplicate = gate!();
await expect(duplicate).resolves.toBeNull();
await screen.findByTestId('login-captcha-overlay');
- expect(document.querySelectorAll('webview')).toHaveLength(1);
+ // overlay 先提交,WebView 再由 effect 插入;Windows CI 上两步可能跨 tick。
+ await waitFor(() => expect(document.querySelectorAll('webview')).toHaveLength(1));
await emitCaptchaResult('cindy-captcha=ok.single-flight-token');
await expect(first).resolves.toBe('single-flight-token');
diff --git a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx
index 03614d191c..3cecfa3180 100644
--- a/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx
+++ b/apps/desktop/src/renderer/components/login/__tests__/LoginPage.harness.test.tsx
@@ -1,6 +1,6 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { vi } from 'vitest';
@@ -11,6 +11,7 @@ import {
type AuthFlowState,
} from '@cindy/auth-client';
import { createScenarioFetch } from '@cindy/auth-client/fixtures';
+import { __testing as ssoOrgHistoryTesting } from '@/state/ssoOrgHistory';
/**
* PR1 harness 场景驱动渲染单测(implementation-plan Step 2 WHAT3 + 附录 A)。
@@ -31,6 +32,7 @@ const loginHook = vi.hoisted(() => ({
clearError: vi.fn(),
},
}));
+const scrollIntoViewMock = vi.hoisted(() => vi.fn());
vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key }),
@@ -113,6 +115,13 @@ function mount(state: AuthFlowState | null, extra?: Partial<typeof loginHook.val
}
beforeEach(() => {
+ window.localStorage.clear();
+ ssoOrgHistoryTesting.reset();
+ scrollIntoViewMock.mockClear();
+ Object.defineProperty(HTMLElement.prototype, 'scrollIntoView', {
+ configurable: true,
+ value: scrollIntoViewMock,
+ });
Object.defineProperty(window, 'electronAPI', {
configurable: true,
// acceptPrivacyConsent:协议门放行时记录「已同意」(TapDB 采集的前置条件)。
@@ -328,6 +337,7 @@ describe('ssoOrgMode 子视图', () => {
expect(screen.getByText('login.ssoOrgTitle')).toBeTruthy();
const input = screen.getByTestId('login-sso-org-input') as HTMLInputElement;
expect(input.placeholder).toBe('login.ssoOrgPlaceholder');
+ expect(document.activeElement).toBe(input);
expect((screen.getByTestId('login-sso-org-continue') as HTMLButtonElement).disabled).toBe(true);
expect(screen.getByText('login.ssoOrgHint')).toBeTruthy();
});
@@ -339,7 +349,9 @@ describe('ssoOrgMode 子视图', () => {
fireEvent.change(input, { target: { value: 'example-corp' } });
const continueBtn = screen.getByTestId('login-sso-org-continue') as HTMLButtonElement;
expect(continueBtn.disabled).toBe(false);
- fireEvent.click(continueBtn);
+ await act(async () => {
+ fireEvent.click(continueBtn);
+ });
expect(loginHook.value.dispatch).toHaveBeenCalledWith({
type: 'discover-sso-org',
org: 'example-corp',
@@ -347,6 +359,113 @@ describe('ssoOrgMode 子视图', () => {
expect(screen.queryByText('login.realmConsent.title')).toBeNull();
});
+ it('单条成功历史进入 SSO 子视图时直接回填', async () => {
+ window.localStorage.setItem(
+ ssoOrgHistoryTesting.storageKey,
+ JSON.stringify({ version: 1, entries: ['remembered-corp'] }),
+ );
+ ssoOrgHistoryTesting.reset();
+ mount(await identifierState('providers:both'));
+ fireEvent.click(screen.getByTestId('login-social-sso'));
+ expect((screen.getByTestId('login-sso-org-input') as HTMLInputElement).value).toBe(
+ 'remembered-corp',
+ );
+ expect(screen.queryByTestId('login-sso-org-history-list')).toBeNull();
+ });
+
+ it('多条成功历史默认折叠,激活输入框后展示列表并支持选择', async () => {
+ window.localStorage.setItem(
+ ssoOrgHistoryTesting.storageKey,
+ JSON.stringify({
+ version: 1,
+ entries: ['recent-corp', 'older.example'],
+ }),
+ );
+ ssoOrgHistoryTesting.reset();
+ mount(await identifierState('providers:both'));
+ fireEvent.click(screen.getByTestId('login-social-sso'));
+ const input = screen.getByTestId('login-sso-org-input') as HTMLInputElement;
+ expect(input.value).toBe('recent-corp');
+ expect(document.activeElement).not.toBe(input);
+ expect(screen.queryByTestId('login-sso-org-history-list')).toBeNull();
+ fireEvent.focus(input);
+ const historyList = screen.getByTestId('login-sso-org-history-list');
+ const panel = screen.getByTestId('login-panel-sso-org');
+ expect(panel.contains(historyList)).toBe(false);
+ expect(Number.parseFloat(historyList.style.left)).toBe(
+ Number.parseFloat(input.style.left),
+ );
+ expect(Number.parseFloat(historyList.style.width)).toBe(
+ Number.parseFloat(input.style.width),
+ );
+ expect(Number.parseFloat(historyList.style.top)).toBe(
+ Number.parseFloat(input.style.top) + Number.parseFloat(input.style.height) + 8,
+ );
+ expect(
+ Number.parseFloat(historyList.style.top) + Number.parseFloat(historyList.style.maxHeight),
+ ).toBeLessThanOrEqual(
+ Number.parseFloat(panel.style.height),
+ );
+ expect(historyList.className).toContain('overflow-y-auto');
+ expect(historyList.className).toContain('[scrollbar-width:none]');
+ expect(historyList.className).toContain('[&::-webkit-scrollbar]:hidden');
+ fireEvent.click(screen.getByTestId('login-sso-org-history-option-1'));
+ expect(input.value).toBe('older.example');
+ expect(screen.queryByTestId('login-sso-org-history-list')).toBeNull();
+ });
+
+ it('action 结束后刷新 AuthContext 在 discovery 成功点写入的历史', async () => {
+ const dispatch = vi.fn(async () => {
+ window.localStorage.setItem(
+ ssoOrgHistoryTesting.storageKey,
+ JSON.stringify({
+ version: 1,
+ entries: ['Example-Corp', 'older-corp'],
+ }),
+ );
+ return false;
+ });
+ mount(await identifierState('providers:both'), { dispatch });
+ fireEvent.click(screen.getByTestId('login-social-sso'));
+ fireEvent.change(screen.getByTestId('login-sso-org-input'), {
+ target: { value: 'Example-Corp' },
+ });
+ fireEvent.click(screen.getByTestId('login-sso-org-continue'));
+ await waitFor(() => {
+ fireEvent.focus(screen.getByTestId('login-sso-org-input'));
+ expect(screen.getByTestId('login-sso-org-history-option-0').textContent).toBe(
+ 'Example-Corp',
+ );
+ });
+ });
+
+ it('多条历史支持方向键选择、保持高亮项可见并用 Escape 关闭', async () => {
+ window.localStorage.setItem(
+ ssoOrgHistoryTesting.storageKey,
+ JSON.stringify({
+ version: 1,
+ entries: ['recent-corp', 'older.example', 'third-corp', 'fourth-corp'],
+ }),
+ );
+ ssoOrgHistoryTesting.reset();
+ mount(await identifierState('providers:both'));
+ fireEvent.click(screen.getByTestId('login-social-sso'));
+ const input = screen.getByTestId('login-sso-org-input') as HTMLInputElement;
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ fireEvent.keyDown(input, { key: 'ArrowDown' });
+ expect(scrollIntoViewMock).toHaveBeenLastCalledWith({ block: 'nearest' });
+ expect(scrollIntoViewMock.mock.instances.at(-1)).toBe(
+ screen.getByTestId('login-sso-org-history-option-2'),
+ );
+ fireEvent.keyDown(input, { key: 'Enter' });
+ expect(input.value).toBe('third-corp');
+ fireEvent.focus(input);
+ expect(screen.getByTestId('login-sso-org-history-list')).toBeTruthy();
+ fireEvent.keyDown(input, { key: 'Escape' });
+ expect(screen.queryByTestId('login-sso-org-history-list')).toBeNull();
+ });
+
it('组织区域与安装区域不一致时才显示确认,确认或取消走独立 action', async () => {
mount(await realmConfirmationState('global'));
expect(screen.getByText('login.realmConsent.title')).toBeTruthy();
diff --git a/apps/desktop/src/renderer/components/login/__tests__/loginScale.test.ts b/apps/desktop/src/renderer/components/login/__tests__/loginScale.test.ts
index 1c10707f29..cd0b719461 100644
--- a/apps/desktop/src/renderer/components/login/__tests__/loginScale.test.ts
+++ b/apps/desktop/src/renderer/components/login/__tests__/loginScale.test.ts
@@ -7,6 +7,7 @@ import {
PANEL_FIXED_SCALE,
sloganShiftX,
} from '../loginScale';
+import { CONTROL, PANEL, SSO_ORG_HISTORY } from '../loginDesignTokens';
/**
* 缩放公式行为单测(implementation-plan Step 2 WHAT1 锚点数值,demo v3.1 拍板)。
@@ -84,6 +85,22 @@ describe('panelPlacement(面板恒定 1x,用户拍板 2026-07-23,design.md §11)
it('水平中心 = 视口中线 + 组中心偏移 0.5 设计px × 0.5', () => {
expect(panelPlacement(1280, 800, 1229).centerX).toBeCloseTo(640.25, 6);
});
+
+ it.each([
+ ['小窗口', 800, 600],
+ ['16 寸级大窗口', 1728, 1117],
+ ])('%s下 SSO 候选层都锚定输入框下沿并收在面板内', (_label, width, height) => {
+ const placement = panelPlacement(width, height, 1227);
+ const inputBottom =
+ placement.topY + (CONTROL.inputY + CONTROL.height) * placement.scale;
+ const historyTop = placement.topY + SSO_ORG_HISTORY.y * placement.scale;
+ const historyBottom =
+ historyTop + SSO_ORG_HISTORY.maxHeight * placement.scale;
+ const panelBottom = placement.topY + PANEL.height * placement.scale;
+
+ expect(historyTop - inputBottom).toBe(8 * placement.scale);
+ expect(historyBottom).toBeLessThanOrEqual(panelBottom);
+ });
});
describe('brandPlacement(品牌块整体让位,用户拍板 2026-07-23 第二轮,design.md §11)', () => {
diff --git a/apps/desktop/src/renderer/components/login/loginDesignTokens.ts b/apps/desktop/src/renderer/components/login/loginDesignTokens.ts
index 2aef91fab4..62de46c9c0 100644
--- a/apps/desktop/src/renderer/components/login/loginDesignTokens.ts
+++ b/apps/desktop/src/renderer/components/login/loginDesignTokens.ts
@@ -167,6 +167,25 @@ export const SKIP_ENTRY = {
} as const;
/** sso-org 帮助行:顶对齐 ≤2 行,y=输入框底 238+6,两行至 290 < 主按钮 300(DESIGN.md §16.2 折行分级 2)。 */
export const SSO_ORG_HINT = { x: 70, y: 244, width: 540, fontSize: 20, lineHeight: 23, maxLines: 2 } as const;
+/**
+ * 最近组织浮层:紧贴输入框下沿并与输入框等宽,作为浮层覆盖后续提示与主按钮。
+ * 它与输入框同处登录组坐标系,因此大小窗口共享同一个锚点与缩放,不再依赖
+ * 面板下方是否还有视口空间。最大高度收在面板内,88 设计px 的最小行高经
+ * 0.5 桌面缩放后得到 44px 可点击行,其余条目在无可见滚动条的自身滚动区内访问。
+ */
+export const SSO_ORG_HISTORY = {
+ x: CONTROL.x,
+ y: CONTROL.inputY + CONTROL.height + 8,
+ width: CONTROL.width,
+ maxHeight: PANEL.height - (CONTROL.inputY + CONTROL.height + 8) - 10,
+ rowMinHeight: 88,
+ radius: 22,
+ rowRadius: 16,
+ fontSize: 20,
+ lineHeight: 23,
+ paddingX: CONTROL.textPadLeft,
+ paddingY: 16,
+} as const;
/**
* 协议同意行(figma 600:660「服务条款」行:680×40,radio 24 @x156 + 文字 20 @x186.5)。
diff --git a/apps/desktop/src/renderer/contexts/AuthContext.tsx b/apps/desktop/src/renderer/contexts/AuthContext.tsx
index de3dd90ad5..64efb24ca9 100644
--- a/apps/desktop/src/renderer/contexts/AuthContext.tsx
+++ b/apps/desktop/src/renderer/contexts/AuthContext.tsx
@@ -43,6 +43,7 @@ import { setNewMakerDraftOwner } from '@/state/newMakerDraft';
import { setModelVisibilityOwner } from '@/state/modelVisibilityPrefs';
import { setComposerDraftOwner } from '@/lib/composerDraftStore';
import { setPendingHandoffOwner } from '@/state/pendingFirstMessage';
+import { rememberSsoOrgIdentifier } from '@/state/ssoOrgHistory';
import { setDeferredUiAssignmentOwner } from '@/features/cc-agent/deferredUiAssignment';
import { invalidateProvidersSnapshot } from '@/lib/providersSnapshotStore';
import { preloadLocalCatalogSnapshot } from '@/lib/localCatalogSnapshot';
@@ -347,6 +348,12 @@ export function AuthProvider({
setLoginState({ step: 'browser-redirect', label: action.label });
}
const result = await authServiceRef.current!.dispatchLoginAction(action);
+ // Org discovery can auto-start a sole SSO browser flow below. Persist at
+ // the successful discovery boundary so a later browser cancel/timeout
+ // does not erase a valid organization from local history.
+ if (action.type === 'discover-sso-org' && result.success) {
+ rememberSsoOrgIdentifier(action.org);
+ }
// 没有真正选择时不停留 method-choice:唯一 SSO 改派 start-browser
//(确认窗立刻消失、露出等待态);唯一邮箱验证码直接发码进输码页。
if (result.success && result.state.step === 'method-choice') {
diff --git a/apps/desktop/src/renderer/state/__tests__/ssoOrgHistory.test.ts b/apps/desktop/src/renderer/state/__tests__/ssoOrgHistory.test.ts
new file mode 100644
index 0000000000..80c14e4efd
--- /dev/null
+++ b/apps/desktop/src/renderer/state/__tests__/ssoOrgHistory.test.ts
@@ -0,0 +1,38 @@
+// @vitest-environment jsdom
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { __testing, getSsoOrgHistory, rememberSsoOrgIdentifier } from '../ssoOrgHistory';
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __testing.reset();
+ vi.restoreAllMocks();
+});
+
+describe('desktop SSO organization history', () => {
+ it('reads the versioned record and persists MRU updates', () => {
+ window.localStorage.setItem(
+ __testing.storageKey,
+ JSON.stringify({ version: 1, entries: ['older.example'] }),
+ );
+ expect(getSsoOrgHistory()).toEqual(['older.example']);
+ expect(rememberSsoOrgIdentifier('new-corp')).toEqual(['new-corp', 'older.example']);
+ expect(JSON.parse(window.localStorage.getItem(__testing.storageKey) ?? '{}')).toEqual({
+ version: 1,
+ entries: ['new-corp', 'older.example'],
+ });
+ });
+
+ it('falls back to the in-memory history when localStorage throws', () => {
+ rememberSsoOrgIdentifier('memory-corp');
+ vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
+ throw new Error('storage unavailable');
+ });
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('storage unavailable');
+ });
+ expect(getSsoOrgHistory()).toEqual(['memory-corp']);
+ expect(rememberSsoOrgIdentifier('next-corp')).toEqual(['next-corp', 'memory-corp']);
+ });
+});
diff --git a/apps/desktop/src/renderer/state/ssoOrgHistory.ts b/apps/desktop/src/renderer/state/ssoOrgHistory.ts
new file mode 100644
index 0000000000..490108e8c2
--- /dev/null
+++ b/apps/desktop/src/renderer/state/ssoOrgHistory.ts
@@ -0,0 +1,48 @@
+import {
+ parseSsoOrgHistory,
+ rememberSsoOrgIdentifier as mergeSsoOrgIdentifier,
+ serializeSsoOrgHistory,
+} from '@cindy/auth-client';
+
+const STORAGE_KEY = 'cindy.desktop.auth.sso-org-history.v1';
+
+let volatileHistory: string[] = [];
+
+function readCurrentHistory(): string[] {
+ if (typeof window === 'undefined') return [...volatileHistory];
+ try {
+ const entries = parseSsoOrgHistory(window.localStorage.getItem(STORAGE_KEY));
+ volatileHistory = entries;
+ return [...entries];
+ } catch {
+ return [...volatileHistory];
+ }
+}
+
+export function getSsoOrgHistory(): string[] {
+ return readCurrentHistory();
+}
+
+/**
+ * Re-reads localStorage before merging so another renderer's recent write is not
+ * overwritten by a stale in-memory snapshot.
+ */
+export function rememberSsoOrgIdentifier(identifier: string): string[] {
+ const next = mergeSsoOrgIdentifier(readCurrentHistory(), identifier);
+ volatileHistory = next;
+ if (typeof window !== 'undefined') {
+ try {
+ window.localStorage.setItem(STORAGE_KEY, serializeSsoOrgHistory(next));
+ } catch {
+ // Keep the current renderer's memory useful when persistence is unavailable.
+ }
+ }
+ return [...next];
+}
+
+export const __testing = {
+ storageKey: STORAGE_KEY,
+ reset(): void {
+ volatileHistory = [];
+ },
+};
diff --git a/apps/mobile/app/(auth)/login.tsx b/apps/mobile/app/(auth)/login.tsx
index e2d90dab38..6b63916ee6 100644
--- a/apps/mobile/app/(auth)/login.tsx
+++ b/apps/mobile/app/(auth)/login.tsx
@@ -8,6 +8,10 @@ import type { AccountDeletionStatus, SocialProvider, VerificationKind } from '@c
import { useAuth } from '@/auth/AuthContext';
import { LoginCaptchaWebView } from '@/auth/LoginCaptchaWebView';
import { useLoginFirstLaunchLight } from '@/auth/loginFirstLaunchGate';
+import {
+ getSsoOrgHistorySnapshot,
+ hydrateSsoOrgHistory,
+} from '@/auth/ssoOrgHistory';
import { resolveStartupSplashHandoff } from '@/auth/startupSplashContinuity';
import {
CN_PHONE_PREFIX,
@@ -44,6 +48,7 @@ import {
LOGIN_GROUP,
LOGIN_LOADING_RING,
LOGIN_METHOD_ROW,
+ LOGIN_SSO_ORG_HISTORY,
LOGIN_SSO_ORG_HINT_TOP,
LOGIN_SUBTITLE,
LOGIN_TITLE,
@@ -69,6 +74,7 @@ import {
LoginSocialButton,
LoginSocialGlyph,
LoginSocialRow,
+ LoginSsoOrgHistoryList,
LoginTextLinkSlot,
LoginTitleBlock,
AppleLogoGlyph,
@@ -131,6 +137,12 @@ export default function LoginScreen() {
// 企业 SSO 入口子视图:在 identifier 步骤内输入组织标识(本地展示态)
const [ssoOrgMode, setSsoOrgMode] = useState(false);
const [ssoOrg, setSsoOrg] = useState('');
+ const [ssoOrgHistory, setSsoOrgHistory] = useState(() =>
+ getSsoOrgHistorySnapshot(),
+ );
+ const [ssoOrgHistoryOpen, setSsoOrgHistoryOpen] = useState(false);
+ const ssoOrgEditedRef = useRef(false);
+ const ssoOrgHistoryBlurTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const realmConfirmation =
auth.loginState?.step === 'realm-confirmation'
? auth.loginState
@@ -225,6 +237,31 @@ export default function LoginScreen() {
const configIssues = getMobileConfigIssues();
const disabled = auth.isBusy || !auth.initialized || configIssues.length > 0;
+ useEffect(() => {
+ let cancelled = false;
+ void hydrateSsoOrgHistory().then((entries) => {
+ if (!cancelled) setSsoOrgHistory(entries);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ useEffect(() => {
+ if (!ssoOrgMode || ssoOrgEditedRef.current || ssoOrgHistory.length === 0)
+ return;
+ setSsoOrg((current) => current || ssoOrgHistory[0] || '');
+ }, [ssoOrgHistory, ssoOrgMode]);
+
+ useEffect(
+ () => () => {
+ if (ssoOrgHistoryBlurTimerRef.current) {
+ clearTimeout(ssoOrgHistoryBlurTimerRef.current);
+ }
+ },
+ [],
+ );
+
useEffect(() => {
if (
!auth.initialized ||
@@ -336,6 +373,7 @@ export default function LoginScreen() {
? ssoOrgMode
? () => {
auth.clearAuthError();
+ setSsoOrgHistoryOpen(false);
setSsoOrgMode(false);
}
: null
@@ -385,50 +423,98 @@ export default function LoginScreen() {
const submitSsoOrg = () => {
const value = ssoOrg.trim();
if (!value) return;
+ setSsoOrgHistoryOpen(false);
// 先静默发现组织区域;只有跨出安装包区域时 AuthContext 才进入
// realm-confirmation,并由页面底部弹窗在继续 SSO 前确认。
- void auth.dispatchLoginAction({
- type: 'discover-sso-org',
- org: value,
- });
+ void auth
+ .dispatchLoginAction({
+ type: 'discover-sso-org',
+ org: value,
+ })
+ .finally(() => {
+ setSsoOrgHistory(getSsoOrgHistorySnapshot());
+ });
+ };
+ const openSsoOrgHistory = () => {
+ if (ssoOrgHistoryBlurTimerRef.current) {
+ clearTimeout(ssoOrgHistoryBlurTimerRef.current);
+ ssoOrgHistoryBlurTimerRef.current = null;
+ }
+ if (ssoOrgHistory.length > 1) setSsoOrgHistoryOpen(true);
+ };
+ const closeSsoOrgHistorySoon = () => {
+ if (ssoOrgHistoryBlurTimerRef.current) {
+ clearTimeout(ssoOrgHistoryBlurTimerRef.current);
+ }
+ ssoOrgHistoryBlurTimerRef.current = setTimeout(() => {
+ ssoOrgHistoryBlurTimerRef.current = null;
+ setSsoOrgHistoryOpen(false);
+ }, 120);
+ };
+ const selectSsoOrgHistory = (entry: string) => {
+ if (ssoOrgHistoryBlurTimerRef.current) {
+ clearTimeout(ssoOrgHistoryBlurTimerRef.current);
+ ssoOrgHistoryBlurTimerRef.current = null;
+ }
+ ssoOrgEditedRef.current = true;
+ setSsoOrg(entry);
+ setSsoOrgHistoryOpen(false);
+ auth.clearAuthError();
+ Keyboard.dismiss();
};
return (
- <LoginPanel testID="login.panel.ssoOrg">
- {backNode}
- <LoginTitleBlock
- title={loginText('ssoOrgTitle')}
- subtitle={loginText('ssoOrgSubtitle')}
- />
- <LoginSkinInput
- autoCapitalize="none"
- autoComplete="off"
- autoCorrect={false}
- editable={!disabled}
- error={!!error}
- maxLength={253}
- onChangeText={setSsoOrg}
- onSubmitEditing={submitSsoOrg}
- placeholder={loginText('ssoOrgPlaceholder')}
- returnKeyType="go"
- testID="login.ssoOrgInput"
- value={ssoOrg}
- />
- <LoginTextLinkSlot
- align="top"
- tone="secondary"
- top={LOGIN_SSO_ORG_HINT_TOP}
- >
- {loginText('ssoOrgHint')}
- </LoginTextLinkSlot>
- <LoginPrimaryButton
- busy={auth.isBusy}
- disabled={disabled || !ssoOrg.trim()}
- label={loginText('continue')}
- onPress={submitSsoOrg}
- testID="login.ssoOrgContinueButton"
- />
- {errorNode}
- </LoginPanel>
+ <>
+ <LoginPanel testID="login.panel.ssoOrg">
+ {backNode}
+ <LoginTitleBlock
+ title={loginText('ssoOrgTitle')}
+ subtitle={loginText('ssoOrgSubtitle')}
+ />
+ <LoginSkinInput
+ autoCapitalize="none"
+ autoComplete="off"
+ autoCorrect={false}
+ accessibilityRole="combobox"
+ accessibilityState={{ expanded: ssoOrgHistoryOpen }}
+ editable={!disabled}
+ error={!!error}
+ maxLength={253}
+ onBlur={closeSsoOrgHistorySoon}
+ onChangeText={(value) => {
+ ssoOrgEditedRef.current = true;
+ setSsoOrg(value);
+ }}
+ onFocus={openSsoOrgHistory}
+ onSubmitEditing={submitSsoOrg}
+ placeholder={loginText('ssoOrgPlaceholder')}
+ returnKeyType="go"
+ testID="login.ssoOrgInput"
+ value={ssoOrg}
+ />
+ <LoginTextLinkSlot
+ align="top"
+ tone="secondary"
+ top={LOGIN_SSO_ORG_HINT_TOP}
+ >
+ {loginText('ssoOrgHint')}
+ </LoginTextLinkSlot>
+ <LoginPrimaryButton
+ busy={auth.isBusy}
+ disabled={disabled || !ssoOrg.trim()}
+ label={loginText('continue')}
+ onPress={submitSsoOrg}
+ testID="login.ssoOrgContinueButton"
+ />
+ {errorNode}
+ </LoginPanel>
+ {ssoOrgHistoryOpen && ssoOrgHistory.length > 1 ? (
+ <LoginSsoOrgHistoryList
+ entries={ssoOrgHistory}
+ onSelect={selectSsoOrgHistory}
+ value={ssoOrg}
+ />
+ ) : null}
+ </>
);
}
const submit = () => {
@@ -607,6 +693,12 @@ export default function LoginScreen() {
// SC-SOC-7: in-flight 期间 no-op(行为层 guard,无 disabled 视觉回填)。
if (disabled) return;
auth.clearAuthError();
+ const history = getSsoOrgHistorySnapshot();
+ setSsoOrgHistory(history);
+ if (!ssoOrgEditedRef.current && !ssoOrg.trim()) {
+ setSsoOrg(history[0] ?? '');
+ }
+ setSsoOrgHistoryOpen(false);
setSsoOrgMode(true);
}}
testID="login.ssoEntryButton"
@@ -1134,6 +1226,14 @@ export default function LoginScreen() {
stage.viewportHeight > prev ? stage.viewportHeight : prev,
);
}, [stage.viewportHeight]);
+ const ssoOrgHistoryBottom =
+ ssoOrgMode && ssoOrgHistoryOpen && ssoOrgHistory.length > 1
+ ? LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight
+ : LOGIN_CONTROL.buttonY + LOGIN_CONTROL.height;
+ const controlsUnionBottom = Math.max(
+ LOGIN_CONTROL.buttonY + LOGIN_CONTROL.height,
+ ssoOrgHistoryBottom,
+ );
const shiftResult = useMemo(() => {
if (groupBaseline == null) {
return { shift: 0, mode: 'hidden' as const };
@@ -1142,18 +1242,15 @@ export default function LoginScreen() {
platform: Platform.OS === 'android' ? 'android' : 'ios',
visible: keyboard.visible,
keyboard: keyboard.rect,
- // 停靠贴附锚 = 面板底(Step 5b.1:panelBottom + 10 - keyboardTop)
+ // 候选层已收在面板内,停靠锚始终保持面板底;不同屏幕尺寸只通过
+ // groupScale 与基线测量适配,避免展开列表时整组额外跳动。
panelBottomY: groupBaseline.y + loginSizes.panelHeight * groupScale,
- // 悬浮相交判定锚 = 当前输入框 ∪ 主按钮(U-8b;输入框顶到主按钮底)
+ // 悬浮相交判定锚仍覆盖输入框、主按钮与展开后的候选层并集。
controlsUnion: {
x: groupBaseline.x + LOGIN_CONTROL.x * groupScale,
y: groupBaseline.y + LOGIN_CONTROL.inputY * groupScale,
width: LOGIN_CONTROL.width * groupScale,
- height:
- (LOGIN_CONTROL.buttonY +
- LOGIN_CONTROL.height -
- LOGIN_CONTROL.inputY) *
- groupScale,
+ height: (controlsUnionBottom - LOGIN_CONTROL.inputY) * groupScale,
},
viewportWidth: stage.viewportWidth,
viewportHeight: stage.viewportHeight,
@@ -1165,6 +1262,8 @@ export default function LoginScreen() {
groupBaseline,
keyboard,
groupScale,
+ ssoOrgHistoryBottom,
+ controlsUnionBottom,
stage.viewportWidth,
stage.viewportHeight,
insets.top,
diff --git a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
index ff6641540b..bf5a856b12 100644
--- a/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
+++ b/apps/mobile/src/__tests__/mobileAuthServerLogin.test.ts
@@ -211,6 +211,34 @@ describe('mobile auth-server login', () => {
expect(authSource).toContain("sole?.type === 'email_code'");
});
+ it('remembers successful organization discovery before sole-SSO browser auth starts', () => {
+ const authSource = readFileSync(
+ resolve(process.cwd(), 'src/auth/AuthContext.tsx'),
+ 'utf8',
+ );
+ const discoveryStart = authSource.indexOf(
+ "if (action.type === 'discover-sso-org') {",
+ );
+ const discoveryEnd = authSource.indexOf(
+ "if (action.type === 'request-code') {",
+ discoveryStart,
+ );
+ const discoveryBody = authSource.slice(discoveryStart, discoveryEnd);
+ const methodsAt = discoveryBody.indexOf(
+ 'const methods = ssoOrgDiscoveryToMethods(discovery);',
+ );
+ const rememberAt = discoveryBody.indexOf(
+ 'await rememberSsoOrgIdentifier(action.org);',
+ );
+ const autoStartAt = discoveryBody.indexOf(
+ 'return startBrowserAuthorization({',
+ );
+
+ expect(methodsAt).toBeGreaterThanOrEqual(0);
+ expect(rememberAt).toBeGreaterThan(methodsAt);
+ expect(autoStartAt).toBeGreaterThan(rememberAt);
+ });
+
it('keeps account tokens inside membership selection and private tickets off screen', () => {
const authSource = readFileSync(
resolve(process.cwd(), 'src/auth/AuthContext.tsx'),
diff --git a/apps/mobile/src/auth/AuthContext.tsx b/apps/mobile/src/auth/AuthContext.tsx
index b54dbc84e5..6915c135d3 100644
--- a/apps/mobile/src/auth/AuthContext.tsx
+++ b/apps/mobile/src/auth/AuthContext.tsx
@@ -71,6 +71,7 @@ import {
} from '@/auth/xdOrgBetaDefault';
import { getAuthLocale, getLoginLanguage } from '@/auth/loginMessages';
import { acquireNativeSocialCredential } from '@/auth/nativeSocial';
+import { rememberSsoOrgIdentifier } from '@/auth/ssoOrgHistory';
import {
matchesOAuthCallbackUrl,
parseOAuthCallbackUrl,
@@ -1393,6 +1394,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
).discoverSsoOrg(org);
}
const methods = ssoOrgDiscoveryToMethods(discovery);
+ // A sole same-region connection auto-starts browser authorization
+ // below. Persist the successful discovery first so cancel/timeout
+ // does not lose a valid organization identifier.
+ await rememberSsoOrgIdentifier(action.org);
const currentState = loginStateRef.current;
if (discovery.region !== BUILD_AUTH_REGION) {
if (currentState?.step !== 'identifier') {
diff --git a/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts b/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts
index 1bb8aeffb8..febbf8fac0 100644
--- a/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginKeyboardAvoidance.test.ts
@@ -251,8 +251,16 @@ describe('loginKeyboard 接线(hook 订阅拓扑 + 登录页测量拓扑,读源
expect(loginSource).toContain('外层未变换测量 wrapper');
expect(loginSource).toContain('translateY: -keyboardShift');
expect(loginSource).toContain('computeLoginKeyboardShift');
- // 停靠贴附锚 = 面板底;union = 输入框顶到主按钮底
- expect(loginSource).toContain('loginSizes.panelHeight * groupScale');
+ // 候选层收在面板内:停靠锚恒为面板底,悬浮键盘 union 仍纳入候选层。
+ expect(loginSource).toContain(
+ 'LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight',
+ );
+ expect(loginSource).toContain(
+ 'panelBottomY: groupBaseline.y + loginSizes.panelHeight * groupScale',
+ );
+ expect(loginSource).toContain(
+ 'height: (controlsUnionBottom - LOGIN_CONTROL.inputY) * groupScale',
+ );
expect(loginSource).toContain('LOGIN_CONTROL.inputY * groupScale');
// Android 未缩窗兜底:page 跟踪全高 + 传系统栏底(computeDockedKeyboardTop)
expect(loginSource).toContain('fullViewportHeight');
diff --git a/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts b/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts
index 4969577309..e709c089d0 100644
--- a/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginSkinLayout.test.ts
@@ -12,11 +12,13 @@ vi.mock("expo-localization", () => ({
import {
createResendDeadline,
formatResendCountdown,
+ LOGIN_CONTROL,
LOGIN_DELETION_BUBBLE,
LOGIN_PAD_LANDSCAPE_STAGE,
LOGIN_PAD_PORTRAIT_STAGE,
LOGIN_STAGE_LONG,
LOGIN_STAGE_SHORT,
+ LOGIN_SSO_ORG_HISTORY,
PAD_LANDSCAPE_MIN_SCALE,
RESEND_COUNTDOWN_SECONDS,
resendCountdownRemaining,
@@ -28,6 +30,7 @@ import {
type LoginStageBox,
} from "@/auth/loginSkinLayout";
import { loginMessages } from "@/auth/loginMessages";
+import { loginSizes } from "@/theme/tokens";
function expectBox(actual: LoginStageBox, expected: LoginStageBox) {
expect(actual.x).toBeCloseTo(expected.x, 6);
@@ -47,6 +50,23 @@ describe("loginSkin 750 stage 布局引擎", () => {
expect(resolveLoginStage(750, 2000).designHeight).toBe(1800);
});
+ it.each([
+ ["phone 短屏", 375, 667],
+ ["phone 长屏", 375, 812],
+ ["pad 竖屏", 744, 1133],
+ ["pad 横屏", 1180, 820],
+ ])("%s 下 SSO 候选层都随输入框锚定并收在面板内", (_label, width, height) => {
+ const surface = resolveLoginSurface(width, height);
+ const groupScale = surface.scale * surface.loginGroupScale;
+ const inputBottom = (LOGIN_CONTROL.inputY + LOGIN_CONTROL.height) * groupScale;
+ const historyTop = LOGIN_SSO_ORG_HISTORY.y * groupScale;
+ const historyBottom =
+ (LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight) * groupScale;
+
+ expect(historyTop - inputBottom).toBeCloseTo(8 * groupScale, 6);
+ expect(historyBottom).toBeLessThanOrEqual(loginSizes.panelHeight * groupScale);
+ });
+
it("短屏档 1334:品牌簇 + 功能区落位逐字段等于登录改版新稿 figma 705:915 实测值(loginY 622)", () => {
const layout = resolveLoginStage(375, 667); // scale 0.5 → dh 1334
expect(layout.designHeight).toBe(1334);
diff --git a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
index 0d0a566213..01192bf6fe 100644
--- a/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
+++ b/apps/mobile/src/auth/__tests__/loginSkinStates.test.ts
@@ -10,6 +10,11 @@ import {
type AuthRegion,
} from '@cindy/auth-client';
import { createScenarioFetch } from '@cindy/auth-client/fixtures';
+import {
+ LOGIN_CONTROL,
+ LOGIN_SSO_ORG_HISTORY,
+} from '../loginSkinLayout';
+import { loginSizes } from '../../theme/tokens';
/**
* PR4a 全登录态测试(SC-1 harness 真链 + SC-7 slice pr4a 状态行)。
@@ -161,15 +166,30 @@ describe('loginSkin 全登录态(harness 真链 + 渲染层接线)', () => {
it('sso-org-empty:企业 ID 子视图空态接线(placeholder/hint/返回)', () => {
expect(loginSource).toContain('testID="login.ssoOrgInput"');
+ expect(loginSource).toContain('hydrateSsoOrgHistory()');
+ expect(loginSource).toContain('<LoginSsoOrgHistoryList');
+ expect(loginSource).toContain('accessibilityRole="combobox"');
+ expect(loginSource).not.toContain('setSsoOrgHistoryOpen(history.length > 1)');
+ expect(loginSource).not.toContain('setSsoOrgHistoryOpen(ssoOrgHistory.length > 1)');
expect(loginSource).toContain("loginText('ssoOrgTitle')");
expect(loginSource).toContain("loginText('ssoOrgPlaceholder')");
expect(loginSource).toContain("loginText('ssoOrgHint')");
+ expect(LOGIN_SSO_ORG_HISTORY.y).toBe(
+ LOGIN_CONTROL.inputY + LOGIN_CONTROL.height + 8,
+ );
+ expect(
+ LOGIN_SSO_ORG_HISTORY.y + LOGIN_SSO_ORG_HISTORY.maxHeight,
+ ).toBeLessThanOrEqual(loginSizes.panelHeight);
+ expect(controlsSource).toContain('showsVerticalScrollIndicator={false}');
// 返回钮:子视图退回首屏输入(不整体 reset)
expect(loginSource).toContain('setSsoOrgMode(false);');
});
it('sso-org-filled:企业 ID 直接发现,仅在状态机判定跨区后确认', () => {
expect(loginSource).toContain("type: 'discover-sso-org'");
+ expect(loginSource).toContain(
+ 'setSsoOrgHistory(getSsoOrgHistorySnapshot())',
+ );
expect(loginSource).toContain("auth.loginState?.step === 'realm-confirmation'");
expect(loginSource).toContain("type: 'confirm-sso-realm'");
expect(loginSource).toContain("type: 'cancel-sso-realm'");
diff --git a/apps/mobile/src/auth/__tests__/ssoOrgHistory.test.ts b/apps/mobile/src/auth/__tests__/ssoOrgHistory.test.ts
new file mode 100644
index 0000000000..b987aa415d
--- /dev/null
+++ b/apps/mobile/src/auth/__tests__/ssoOrgHistory.test.ts
@@ -0,0 +1,88 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const storage = vi.hoisted(() => {
+ const values = new Map<string, string>();
+ return {
+ values,
+ getItem: vi.fn(async (key: string) => values.get(key) ?? null),
+ setItem: vi.fn(async (key: string, value: string) => {
+ values.set(key, value);
+ }),
+ };
+});
+
+vi.mock("@react-native-async-storage/async-storage", () => ({
+ default: {
+ getItem: storage.getItem,
+ setItem: storage.setItem,
+ },
+}));
+
+import {
+ __testing,
+ getSsoOrgHistorySnapshot,
+ hydrateSsoOrgHistory,
+ rememberSsoOrgIdentifier,
+} from "../ssoOrgHistory";
+
+beforeEach(() => {
+ storage.values.clear();
+ storage.getItem.mockClear();
+ storage.setItem.mockClear();
+ __testing.reset();
+});
+
+describe("mobile SSO organization history", () => {
+ it("hydrates a versioned AsyncStorage record", async () => {
+ storage.values.set(
+ __testing.storageKey,
+ JSON.stringify({ version: 1, entries: ["remembered-corp"] }),
+ );
+ await expect(hydrateSsoOrgHistory()).resolves.toEqual(["remembered-corp"]);
+ expect(getSsoOrgHistorySnapshot()).toEqual(["remembered-corp"]);
+ });
+
+ it("serializes concurrent MRU writes without losing an entry", async () => {
+ await Promise.all([
+ rememberSsoOrgIdentifier("first-corp"),
+ rememberSsoOrgIdentifier("second-corp"),
+ ]);
+ expect(getSsoOrgHistorySnapshot()).toEqual(["second-corp", "first-corp"]);
+ expect(
+ JSON.parse(storage.values.get(__testing.storageKey) ?? "{}"),
+ ).toEqual({
+ version: 1,
+ entries: ["second-corp", "first-corp"],
+ });
+ });
+
+ it("retries a failed read before persisting a new identifier", async () => {
+ storage.values.set(
+ __testing.storageKey,
+ JSON.stringify({ version: 1, entries: ["saved-corp"] }),
+ );
+ storage.getItem.mockRejectedValueOnce(new Error("storage unavailable"));
+
+ await expect(rememberSsoOrgIdentifier("new-corp")).resolves.toEqual([]);
+ expect(storage.setItem).not.toHaveBeenCalled();
+ expect(
+ JSON.parse(storage.values.get(__testing.storageKey) ?? "{}"),
+ ).toEqual({
+ version: 1,
+ entries: ["saved-corp"],
+ });
+
+ await expect(rememberSsoOrgIdentifier("new-corp")).resolves.toEqual([
+ "new-corp",
+ "saved-corp",
+ ]);
+ });
+
+ it("keeps the in-memory result when persistence fails", async () => {
+ storage.setItem.mockRejectedValueOnce(new Error("storage unavailable"));
+ await expect(rememberSsoOrgIdentifier("memory-corp")).resolves.toEqual([
+ "memory-corp",
+ ]);
+ expect(getSsoOrgHistorySnapshot()).toEqual(["memory-corp"]);
+ });
+});
diff --git a/apps/mobile/src/auth/loginSkinLayout.ts b/apps/mobile/src/auth/loginSkinLayout.ts
index 1d3282b920..5c77d2afff 100644
--- a/apps/mobile/src/auth/loginSkinLayout.ts
+++ b/apps/mobile/src/auth/loginSkinLayout.ts
@@ -447,6 +447,28 @@ export const LOGIN_LOADING_RING = { x: 308, yBrowser: 158, yPreparing: 193, size
export const LOGIN_TEXT_LINK = { x: 70, y: 238, width: 540, height: 50, font: 20, lineHeight: LOGIN_COPY_LINE_HEIGHT } as const;
/** sso-org 帮助行槽顶:输入框底 238+6 呼吸间距,两行至 290 < 主按钮 300(DESIGN.md §16.2 折行分级 2,与桌面 SSO_ORG_HINT 同值)。 */
export const LOGIN_SSO_ORG_HINT_TOP = 244;
+/**
+ * 最近组织浮层:紧贴输入框下沿并与输入框等宽,作为浮层覆盖后续提示与主按钮。
+ * 它与输入框同处登录组坐标系,phone 短屏/长屏与 pad 都随各自 surface scale
+ * 一起移动;最大高度收在手机 440 高面板内,其余条目在无可见滚动条的浮层内滚动。
+ */
+export const LOGIN_SSO_ORG_HISTORY = {
+ x: LOGIN_CONTROL.x,
+ y: LOGIN_CONTROL.inputY + LOGIN_CONTROL.height + 8,
+ width: LOGIN_CONTROL.width,
+ maxHeight:
+ LOGIN_ERROR_TEXT.y +
+ LOGIN_ERROR_TEXT.height -
+ (LOGIN_CONTROL.inputY + LOGIN_CONTROL.height + 8) -
+ 10,
+ rowMinHeight: 88,
+ radius: 22,
+ rowRadius: 16,
+ font: 20,
+ lineHeight: LOGIN_COPY_LINE_HEIGHT,
+ paddingX: LOGIN_CONTROL.textPadLeft,
+ paddingY: 16,
+} as const;
/**
* 协议同意行(consent PR;figma 600:660「服务条款」行,与桌面 CONSENT_ROW 同参数源):
diff --git a/apps/mobile/src/auth/ssoOrgHistory.ts b/apps/mobile/src/auth/ssoOrgHistory.ts
new file mode 100644
index 0000000000..a8b31d7c98
--- /dev/null
+++ b/apps/mobile/src/auth/ssoOrgHistory.ts
@@ -0,0 +1,69 @@
+import AsyncStorage from "@react-native-async-storage/async-storage";
+import {
+ parseSsoOrgHistory,
+ rememberSsoOrgIdentifier as mergeSsoOrgIdentifier,
+ serializeSsoOrgHistory,
+} from "@cindy/auth-client";
+
+const STORAGE_KEY = "cindy.mobile.auth.sso-org-history.v1";
+
+let cache: string[] = [];
+let hydrated = false;
+let hydrating: Promise<string[]> | null = null;
+let writeChain: Promise<void> = Promise.resolve();
+
+export function getSsoOrgHistorySnapshot(): string[] {
+ return [...cache];
+}
+
+export function hydrateSsoOrgHistory(): Promise<string[]> {
+ if (hydrated) return Promise.resolve(getSsoOrgHistorySnapshot());
+ if (hydrating) return hydrating;
+ hydrating = AsyncStorage.getItem(STORAGE_KEY)
+ .then((raw) => {
+ cache = parseSsoOrgHistory(raw);
+ hydrated = true;
+ return getSsoOrgHistorySnapshot();
+ })
+ .catch(() => {
+ return getSsoOrgHistorySnapshot();
+ })
+ .finally(() => {
+ hydrating = null;
+ });
+ return hydrating;
+}
+
+/** Serializes writes so concurrent successful discoveries cannot overwrite one another. */
+export function rememberSsoOrgIdentifier(
+ identifier: string,
+): Promise<string[]> {
+ let result: string[] = [];
+ const operation = writeChain.then(async () => {
+ await hydrateSsoOrgHistory();
+ // A failed read leaves hydration retryable and must not turn an empty cache
+ // into an authoritative record that overwrites previously saved entries.
+ if (!hydrated) {
+ result = getSsoOrgHistorySnapshot();
+ return;
+ }
+ cache = mergeSsoOrgIdentifier(cache, identifier);
+ result = getSsoOrgHistorySnapshot();
+ await AsyncStorage.setItem(
+ STORAGE_KEY,
+ serializeSsoOrgHistory(cache),
+ ).catch(() => undefined);
+ });
+ writeChain = operation.catch(() => undefined);
+ return operation.then(() => result);
+}
+
+export const __testing = {
+ storageKey: STORAGE_KEY,
+ reset(): void {
+ cache = [];
+ hydrated = false;
+ hydrating = null;
+ writeChain = Promise.resolve();
+ },
+};
diff --git a/apps/mobile/src/components/LoginSkinControls.tsx b/apps/mobile/src/components/LoginSkinControls.tsx
index 70d32433a6..78de9272af 100644
--- a/apps/mobile/src/components/LoginSkinControls.tsx
+++ b/apps/mobile/src/components/LoginSkinControls.tsx
@@ -4,6 +4,7 @@ import {
BackHandler,
Easing,
Pressable,
+ ScrollView,
StyleSheet,
View,
type TextInputProps,
@@ -23,6 +24,7 @@ import {
LOGIN_METHOD_ROW,
LOGIN_SOCIAL,
LOGIN_SPINNER,
+ LOGIN_SSO_ORG_HISTORY,
LOGIN_SUBTITLE,
LOGIN_TEXT_LINK,
LOGIN_TITLE,
@@ -501,6 +503,8 @@ export function LoginSkinInput({
center,
top = LOGIN_CONTROL.inputY,
testID,
+ onFocus: onInputFocus,
+ onBlur: onInputBlur,
...inputProps
}: {
value: string;
@@ -525,9 +529,15 @@ export function LoginSkinInput({
<TextInput
{...inputProps}
editable={editable}
- onBlur={() => setFocused(false)}
+ onBlur={(event) => {
+ setFocused(false);
+ onInputBlur?.(event);
+ }}
onChangeText={onChangeText}
- onFocus={() => setFocused(true)}
+ onFocus={(event) => {
+ setFocused(true);
+ onInputFocus?.(event);
+ }}
placeholder={placeholder}
placeholderTextColor={colors.login.controlPlaceholder}
style={[
@@ -552,6 +562,79 @@ export function LoginSkinInput({
);
}
+/** Visual-only recent organization menu used by the SSO identifier field. */
+export function LoginSsoOrgHistoryList({
+ entries,
+ value,
+ onSelect,
+}: {
+ entries: readonly string[];
+ value: string;
+ onSelect: (entry: string) => void;
+}) {
+ const { colors } = useTheme();
+ const selectedKey = value.trim().toLowerCase();
+ return (
+ <View
+ accessibilityRole="menu"
+ style={{
+ backgroundColor: colors.login.panelBg,
+ borderColor: colors.login.controlBorder,
+ borderRadius: LOGIN_SSO_ORG_HISTORY.radius,
+ borderWidth: 1,
+ left: LOGIN_SSO_ORG_HISTORY.x,
+ maxHeight: LOGIN_SSO_ORG_HISTORY.maxHeight,
+ overflow: 'hidden',
+ position: 'absolute',
+ top: LOGIN_SSO_ORG_HISTORY.y,
+ width: LOGIN_SSO_ORG_HISTORY.width,
+ zIndex: 4,
+ }}
+ testID="login.ssoOrgHistoryList"
+ >
+ <ScrollView
+ keyboardShouldPersistTaps="handled"
+ showsVerticalScrollIndicator={false}
+ >
+ {entries.map((entry, index) => {
+ const selected = entry.toLowerCase() === selectedKey;
+ return (
+ <Pressable
+ accessibilityRole="menuitem"
+ accessibilityState={{ selected }}
+ key={entry.toLowerCase()}
+ onPress={() => onSelect(entry)}
+ style={({ pressed }) => ({
+ backgroundColor:
+ selected || pressed
+ ? colors.login.actionControlBg
+ : 'transparent',
+ borderRadius: LOGIN_SSO_ORG_HISTORY.rowRadius,
+ justifyContent: 'center',
+ minHeight: LOGIN_SSO_ORG_HISTORY.rowMinHeight,
+ paddingHorizontal: LOGIN_SSO_ORG_HISTORY.paddingX,
+ paddingVertical: LOGIN_SSO_ORG_HISTORY.paddingY,
+ })}
+ testID={`login.ssoOrgHistoryOption.${index}`}
+ >
+ <Text
+ style={{
+ color: colors.login.controlText,
+ fontSize: LOGIN_SSO_ORG_HISTORY.font,
+ fontWeight: fontWeight.medium,
+ lineHeight: LOGIN_SSO_ORG_HISTORY.lineHeight,
+ }}
+ >
+ {entry}
+ </Text>
+ </Pressable>
+ );
+ })}
+ </ScrollView>
+ </View>
+ );
+}
+
/**
* 固定国家码手机号输入。外层视觉沿用 LoginSkinInput,左侧纯文本前缀不可点击,
* 输入框只承载本地 11 位号码。
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index 77e887392b..a1a5577973 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -1321,6 +1321,7 @@ The execution rulebook for subsequent desktop / mobile UI updates. Sources: the
| 登录整体组 | 680×**620**(面板 500 + gap 40 + 圆钮行 80)——2026-07-27 面板增高改版,原 560 作废 | figma §5.1(新稿 `700:783`) |
| 面板 | 680×**500**,r36,`#FBFBFB` + inset 1px `--login-panel-border` —— 2026-07-27 改版,原 440 作废;增的 60 = 面板内新增的「跳过登录」槽,**面板内其余元素 y 坐标一律不动**。面板高度对登录全步骤恒定(步骤间不得跳变);**Splash 借用同款面板时保持 440**(无该入口,见 §16.3 `LoginPanel`) | figma §4 / §5.1(新稿 `700:791` / `705:886` / `705:1062`) |
| 输入框 / 主按钮 | 540×80,r40,@(70, 158 / 300) | figma §4.1 / §4.3 |
+| SSO 最近组织候选层 | 与输入框同宽同 x,顶边恒为输入框底 + 8;作为浮层覆盖后续 hint / 主按钮,不参与文档流。最大高度收在当前端登录面板内并自行滚动(桌面面板 500、手机面板 440),不得再定位到面板下方。候选层与输入框必须处于同一登录组坐标系,随桌面窗口 placement、phone 短/长屏、pad surface scale 与手机键盘避让整体移动,不另写按设备尺寸分支 | 2026-08-22 小屏实机修正 |
| 方式行 | 540×100,r60,@(70, 158 / 278),左图标 24@(27,37),右图标 @(490,40) | figma §4.9 |
| 返回钮 | 60×60,r40,@(20,20) | figma §4.6 |
| 重发 / Text_link 槽 | 540×50,20px,@(70,238) | figma §4.7 |
diff --git a/packages/auth-client/src/__tests__/ssoOrgHistory.test.ts b/packages/auth-client/src/__tests__/ssoOrgHistory.test.ts
new file mode 100644
index 0000000000..3eb22b08e2
--- /dev/null
+++ b/packages/auth-client/src/__tests__/ssoOrgHistory.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ MAX_SSO_ORG_HISTORY_ENTRIES,
+ MAX_SSO_ORG_IDENTIFIER_LENGTH,
+ parseSsoOrgHistory,
+ rememberSsoOrgIdentifier,
+ serializeSsoOrgHistory,
+} from "../index.js";
+
+describe("SSO organization history", () => {
+ it("parses a valid versioned record and rejects malformed input", () => {
+ expect(
+ parseSsoOrgHistory(
+ JSON.stringify({
+ version: 1,
+ entries: [" Example-Corp ", "", 42, "example.com"],
+ }),
+ ),
+ ).toEqual(["Example-Corp", "example.com"]);
+ expect(parseSsoOrgHistory("{")).toEqual([]);
+ expect(
+ parseSsoOrgHistory(JSON.stringify({ version: 2, entries: ["corp"] })),
+ ).toEqual([]);
+ expect(parseSsoOrgHistory(JSON.stringify(["corp"]))).toEqual([]);
+ });
+
+ it("deduplicates case-insensitively while preserving the newest display value", () => {
+ expect(
+ rememberSsoOrgIdentifier(
+ ["Example-Corp", "other.example"],
+ " example-corp ",
+ ),
+ ).toEqual(["example-corp", "other.example"]);
+ });
+
+ it("moves reused entries to the MRU head and caps the list", () => {
+ let history: string[] = [];
+ for (let index = 0; index < MAX_SSO_ORG_HISTORY_ENTRIES + 2; index += 1) {
+ history = rememberSsoOrgIdentifier(history, `corp-${index}`);
+ }
+ expect(history).toHaveLength(MAX_SSO_ORG_HISTORY_ENTRIES);
+ expect(history[0]).toBe(`corp-${MAX_SSO_ORG_HISTORY_ENTRIES + 1}`);
+ expect(history).not.toContain("corp-0");
+
+ expect(rememberSsoOrgIdentifier(history, history[2])).toEqual([
+ history[2],
+ history[0],
+ history[1],
+ ...history.slice(3),
+ ]);
+ });
+
+ it("drops empty and overlong identifiers during writes and serialization", () => {
+ const overlong = "x".repeat(MAX_SSO_ORG_IDENTIFIER_LENGTH + 1);
+ expect(rememberSsoOrgIdentifier(["corp"], " ")).toEqual(["corp"]);
+ expect(rememberSsoOrgIdentifier(["corp"], overlong)).toEqual(["corp"]);
+ expect(
+ parseSsoOrgHistory(serializeSsoOrgHistory(["corp", overlong, "CORP"])),
+ ).toEqual(["corp"]);
+ });
+});
diff --git a/packages/auth-client/src/index.ts b/packages/auth-client/src/index.ts
index 9fec35cef9..aefe6fce1e 100644
--- a/packages/auth-client/src/index.ts
+++ b/packages/auth-client/src/index.ts
@@ -1,5 +1,13 @@
export { AuthApiError, CindyAuthClient } from "./client.js";
export { discoverSsoOrgRealm } from "./orgRealmDiscovery.js";
+export {
+ MAX_SSO_ORG_HISTORY_ENTRIES,
+ MAX_SSO_ORG_IDENTIFIER_LENGTH,
+ parseSsoOrgHistory,
+ rememberSsoOrgIdentifier,
+ serializeSsoOrgHistory,
+ SSO_ORG_HISTORY_VERSION,
+} from "./ssoOrgHistory.js";
export {
accountDeletionReceiptRecordSchema,
authSessionRecordSchema,
diff --git a/packages/auth-client/src/ssoOrgHistory.ts b/packages/auth-client/src/ssoOrgHistory.ts
new file mode 100644
index 0000000000..c163a6a359
--- /dev/null
+++ b/packages/auth-client/src/ssoOrgHistory.ts
@@ -0,0 +1,74 @@
+export const SSO_ORG_HISTORY_VERSION = 1;
+export const MAX_SSO_ORG_HISTORY_ENTRIES = 5;
+export const MAX_SSO_ORG_IDENTIFIER_LENGTH = 253;
+
+interface SsoOrgHistoryRecord {
+ version: typeof SSO_ORG_HISTORY_VERSION;
+ entries: string[];
+}
+
+function normalizeIdentifier(value: unknown): string | null {
+ if (typeof value !== "string") return null;
+ const normalized = value.trim();
+ if (!normalized || normalized.length > MAX_SSO_ORG_IDENTIFIER_LENGTH)
+ return null;
+ return normalized;
+}
+
+function dedupeKey(value: string): string {
+ return value.toLowerCase();
+}
+
+function normalizeEntries(values: unknown): string[] {
+ if (!Array.isArray(values)) return [];
+ const seen = new Set<string>();
+ const entries: string[] = [];
+ for (const value of values) {
+ const normalized = normalizeIdentifier(value);
+ if (!normalized) continue;
+ const key = dedupeKey(normalized);
+ if (seen.has(key)) continue;
+ seen.add(key);
+ entries.push(normalized);
+ if (entries.length >= MAX_SSO_ORG_HISTORY_ENTRIES) break;
+ }
+ return entries;
+}
+
+/** Parses the device-local, non-credential organization sign-in history. */
+export function parseSsoOrgHistory(raw: string | null | undefined): string[] {
+ if (!raw) return [];
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
+ return [];
+ const record = parsed as Partial<SsoOrgHistoryRecord>;
+ if (record.version !== SSO_ORG_HISTORY_VERSION) return [];
+ return normalizeEntries(record.entries);
+ } catch {
+ return [];
+ }
+}
+
+export function serializeSsoOrgHistory(entries: readonly string[]): string {
+ const record: SsoOrgHistoryRecord = {
+ version: SSO_ORG_HISTORY_VERSION,
+ entries: normalizeEntries(entries),
+ };
+ return JSON.stringify(record);
+}
+
+/** Moves a successful organization identifier to the MRU head. */
+export function rememberSsoOrgIdentifier(
+ entries: readonly string[],
+ identifier: string,
+): string[] {
+ const normalized = normalizeIdentifier(identifier);
+ const current = normalizeEntries(entries);
+ if (!normalized) return current;
+ const key = dedupeKey(normalized);
+ return [
+ normalized,
+ ...current.filter((entry) => dedupeKey(entry) !== key),
+ ].slice(0, MAX_SSO_ORG_HISTORY_ENTRIES);
+}