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(settings): 收紧供应商用量并统一模型滚动 (#4466)

Dash8bafdca92515
diff --git a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
index 4d5004bf94..0fd51c41a0 100644
--- a/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
+++ b/apps/desktop/src/renderer/__tests__/providersSectionDeepLink.test.tsx
@@ -131,6 +131,11 @@ vi.mock('@/components/settings/AddProviderWizard', () => ({
import { updateCustomProvider } from '@/lib/customProviders';
import { ProvidersSection } from '@/components/settings/ProvidersSection';
+import { useProviderSubscriptionCard } from '@/components/settings/useProviderSubscriptionCard';
+
+vi.mock('@/components/settings/useProviderSubscriptionCard', () => ({
+ useProviderSubscriptionCard: vi.fn(() => null),
+}));
vi.mock('@/components/settings/OllamaProviderDetail', () => ({ OllamaProviderDetail: () => null }));
@@ -172,6 +177,7 @@ function renderAt(search: string) {
}
beforeEach(() => {
+ vi.mocked(useProviderSubscriptionCard).mockReset().mockReturnValue(null);
confirmSpy.mockReset().mockResolvedValue(true);
codexAuthState.state = { kind: 'unauthenticated' };
codexAuthState.reconnectCredentialScope = undefined;
@@ -257,6 +263,65 @@ describe('ProvidersSection — 深链定位', () => {
await waitFor(() => expect(screen.getAllByText('My renamed provider').length).toBeGreaterThanOrEqual(2));
});
+ it.each(['openai', 'anthropic', 'xai', 'custom-api', 'custom-oauth'])(
+ 'keeps identity outside the shared model scroll area for %s',
+ async (id) => {
+ providersState.providers = [
+ makeProvider(id, {
+ name: 'Scroll provider',
+ source: id.startsWith('custom') ? 'user' : 'builtin',
+ connected: true,
+ auth: id === 'custom-api' ? { method: 'apiKey' } : { method: 'oauth', native: 'codex' },
+ agents: ['codex'],
+ models: {
+ codex: [
+ {
+ id: 'scroll-model',
+ name: 'Scroll Model',
+ contextWindow: 0,
+ efforts: [],
+ defaultEffort: null,
+ },
+ ],
+ },
+ }),
+ ];
+ renderAt(`?tab=providers&connect=${id}`);
+ const scroll = await screen.findByTestId('provider-detail-scroll');
+ expect(scroll.contains(screen.getByTestId('provider-detail-identity'))).toBe(false);
+ expect(within(scroll).getByText('Scroll Model')).toBeTruthy();
+ expect(
+ within(scroll).getByTestId('provider-model-toolbar').classList.contains('sticky'),
+ ).toBe(true);
+ // No nested scrolling surface may trap wheel input above or below the model list.
+ expect(scroll.querySelector('.overflow-y-auto')).toBeNull();
+ },
+ );
+
+ it.each(['subscriptionAccount', 'openAiAccount'] as const)(
+ 'collapses usage on %s changes but retains expansion on quota refresh',
+ async (identityField) => {
+ const account = { title: 'ChatGPT', windows: [{ key: 'weekly', title: 'Weekly', window: { utilization: 20 }, detail: 'Weekly usage details' }] };
+ vi.mocked(useProviderSubscriptionCard).mockReturnValue(account);
+ const provider = makeProvider('openai', {
+ connected: true,
+ [identityField]: { source: 'oauth', identity: '[email protected]' },
+ });
+ providersState.providers = [provider];
+ const view = render(<MemoryRouter><ProvidersSection /></MemoryRouter>);
+ fireEvent.click(await screen.findByRole('button', { name: 'quotaCard.usageTitle' }));
+ const refresh = () => view.rerender(
+ <MemoryRouter><ProvidersSection /></MemoryRouter>,
+ );
+ vi.mocked(useProviderSubscriptionCard).mockReturnValue({ ...account, updatedAt: Date.now() });
+ refresh();
+ expect(screen.getByRole('button', { name: 'quotaCard.usageTitle' }).getAttribute('aria-expanded')).toBe('true');
+ providersState.providers = [{ ...provider, [identityField]: { source: 'oauth', identity: '[email protected]' } }];
+ refresh();
+ expect(screen.getByRole('button', { name: 'quotaCard.usageTitle' }).getAttribute('aria-expanded')).toBe('false');
+ },
+ );
+
it('added OpenAI shares status and moves rename/delete into the single menu', async () => {
providersState.providers = [
makeProvider('openai-work', {
@@ -370,6 +435,43 @@ describe('ProvidersSection — 深链定位', () => {
expect(within(actions).getByRole('button', { name: 'settings.providers.button.disconnect' })).toBeTruthy();
});
+ it('reveals replacement-key inputs once without resetting scroll while typing', async () => {
+ providersState.providers = [makeProvider('gemini', { connected: true, auth: { method: 'apiKey' } })];
+ renderAt('?tab=providers&connect=gemini');
+ const scroll = await screen.findByTestId('provider-detail-scroll');
+ scroll.scrollTop = 500;
+ fireEvent.pointerDown(screen.getByRole('button', { name: 'settings.providers.detail.moreActionsAria' }), { button: 0, ctrlKey: false });
+ fireEvent.click(await screen.findByText('settings.providers.builtinApiKey.replaceKey'));
+ const input = await screen.findByPlaceholderText('settings.providers.builtinApiKey.keyPlaceholder');
+ expect(scroll.scrollTop).toBe(0);
+ scroll.scrollTop = 100;
+ fireEvent.change(input, { target: { value: 'fixture-key' } });
+ expect(scroll.scrollTop).toBe(100);
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.button.cancel' }));
+ expect(scroll.scrollTop).toBe(100);
+ });
+
+ it('reveals device-code authorization above a scrolled model list', async () => {
+ let complete!: (result: { ok: boolean }) => void;
+ Object.assign(window.electronAPI.maker, {
+ providerOAuthLogin: vi.fn(() => new Promise<{ ok: boolean }>((resolve) => { complete = resolve; })),
+ providerOAuthCancel: vi.fn(async () => ({ ok: true })),
+ });
+ providersState.providers = [makeProvider('device-provider', {
+ source: 'user',
+ auth: { method: 'oauth', oauth: {
+ flow: 'device-code', deviceAuthorizationUrl: 'https://auth.example.test/device',
+ tokenUrl: 'https://auth.example.test/token', clientId: 'fixture', scopes: 'openid',
+ } },
+ })];
+ renderAt('?tab=providers&connect=device-provider');
+ const scroll = await screen.findByTestId('provider-detail-scroll');
+ scroll.scrollTop = 500;
+ fireEvent.click(screen.getByRole('button', { name: 'settings.providers.wizard.authorizeWithDeviceCode' }));
+ expect(scroll.scrollTop).toBe(0);
+ await act(async () => complete({ ok: false }));
+ });
+
it('added OpenAI recovery overrides a stale connected snapshot', async () => {
providersState.providers = [
makeProvider('openai-work', {
diff --git a/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx b/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx
index c8abd6fdf7..c4f75eac00 100644
--- a/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx
+++ b/apps/desktop/src/renderer/components/settings/OllamaProviderDetail.tsx
@@ -425,7 +425,7 @@ export function OllamaProviderDetail({ onChanged }: { onChanged: () => void }) {
return (
<div
- className="flex min-h-0 flex-1 flex-col gap-6 overflow-y-auto border-t px-5 py-5"
+ className="flex flex-col gap-6 border-t px-5 py-5"
style={{ borderColor: 'var(--settings-theme-card-border)' }}
>
{statusKind !== 'ready' && statusKind !== 'pulling' && statusKind !== 'absent' && (
diff --git a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
index bbf54924a9..f71bc85385 100644
--- a/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/ProvidersSection.tsx
@@ -17,7 +17,7 @@
* fetchProviderModels,additions-only 合并进配置(与 OAuth 动态发现同语义)。
*/
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useNavigate, useSearchParams } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
@@ -62,7 +62,10 @@ import {
import { providerDisplayName } from '@/lib/providerDisplayName';
import { providerMonogram } from '@/lib/providerModels';
import { isBuiltinApiKeyProviderId } from '../../../shared/providerSecrets';
-import type { CustomProviderUpdateOptions, CustomProviderUpdateResult } from '../../../shared/customProviderUpdate';
+import type {
+ CustomProviderUpdateOptions,
+ CustomProviderUpdateResult,
+} from '../../../shared/customProviderUpdate';
import {
customProviderSubtitleForDisplay,
@@ -244,28 +247,41 @@ function BetaTag({ label }: { label: string }) {
type ProviderOwnerScope = { dataOwnerId: string | null; ownerGeneration: number };
function supportsBuiltinConnectionManagement(provider: ProviderView): boolean {
- return provider.source === 'builtin' && provider.id !== 'xd' && (
- ['openai', 'anthropic', 'xai'].includes(provider.id) ||
- (provider.auth.method === 'oauth' && !!provider.auth.oauth) ||
- (provider.auth.method === 'apiKey' && isBuiltinApiKeyProviderId(provider.id))
+ return (
+ provider.source === 'builtin' &&
+ provider.id !== 'xd' &&
+ (['openai', 'anthropic', 'xai'].includes(provider.id) ||
+ (provider.auth.method === 'oauth' && !!provider.auth.oauth) ||
+ (provider.auth.method === 'apiKey' && isBuiltinApiKeyProviderId(provider.id)))
);
}
/** Reuse the image Host restart confirmation for settings mutations that remove its source. */
function useProviderChangeConfirmation() {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
- return useCallback(async (change: (options: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult | void>) => {
- const result = await change({ source: 'manual-settings' });
- if (!result || result.ok) return true;
- if (!(await confirm({
- title: t('settings.providers.custom.imageGenerationReload.title'),
- description: t('settings.providers.custom.imageGenerationReload.description'),
- confirmText: t('settings.providers.custom.imageGenerationReload.interrupt'),
- cancelText: t('settings.providers.custom.imageGenerationReload.cancel'),
- }))) return false;
- const retry = await change({ source: 'manual-settings', codexImageGenerationRestartPolicy: 'interrupt' });
- return !retry || retry.ok;
- }, [confirm, t]);
+ return useCallback(
+ async (
+ change: (options: CustomProviderUpdateOptions) => Promise<CustomProviderUpdateResult | void>,
+ ) => {
+ const result = await change({ source: 'manual-settings' });
+ if (!result || result.ok) return true;
+ if (
+ !(await confirm({
+ title: t('settings.providers.custom.imageGenerationReload.title'),
+ description: t('settings.providers.custom.imageGenerationReload.description'),
+ confirmText: t('settings.providers.custom.imageGenerationReload.interrupt'),
+ cancelText: t('settings.providers.custom.imageGenerationReload.cancel'),
+ }))
+ )
+ return false;
+ const retry = await change({
+ source: 'manual-settings',
+ codexImageGenerationRestartPolicy: 'interrupt',
+ });
+ return !retry || retry.ok;
+ },
+ [confirm, t],
+ );
}
async function disconnectProvider(
provider: ProviderView,
@@ -273,7 +289,8 @@ async function disconnectProvider(
options?: CustomProviderUpdateOptions,
): Promise<CustomProviderUpdateResult | void> {
if (provider.source === 'builtin') {
- if (!supportsBuiltinConnectionManagement(provider)) throw new Error('Provider connection management is unavailable');
+ if (!supportsBuiltinConnectionManagement(provider))
+ throw new Error('Provider connection management is unavailable');
// Keep the entry available for reconnect, even when the original source was auto-detected.
await window.electronAPI.maker.setProviderPresentation({
providerId: provider.id,
@@ -283,7 +300,8 @@ async function disconnectProvider(
if (provider.id === 'openai') await window.electronAPI.maker.auth.logout('codex', scope);
else if (provider.id === 'anthropic') await window.electronAPI.maker.claudeOAuthLogout(scope);
else if (provider.id === 'xai') await window.electronAPI.maker.xaiOAuthLogout(scope);
- else if (provider.auth.method === 'oauth') return window.electronAPI.maker.providerOAuthLogout(provider.id, scope, options);
+ else if (provider.auth.method === 'oauth')
+ return window.electronAPI.maker.providerOAuthLogout(provider.id, scope, options);
else await window.electronAPI.builtinApiKeyRemove(provider.id, scope);
} else if (provider.auth.method === 'oauth') {
return window.electronAPI.maker.providerOAuthLogout(provider.id, scope, options);
@@ -350,7 +368,8 @@ function useProviderManagement(provider?: ProviderView) {
)
return;
setBusy(true);
- if (!(await confirmProviderChange(options => disconnectProvider(provider, scope, options)))) return;
+ if (!(await confirmProviderChange((options) => disconnectProvider(provider, scope, options))))
+ return;
// Deleting the whole provider also revokes its legacy image API connection.
// Keep this separate from disconnecting only the ChatGPT subscription.
if (provider.id === 'openai') {
@@ -374,6 +393,7 @@ function useProviderManagement(provider?: ProviderView) {
}
function DetailHeader({
+ children,
icon,
title,
identityBadge,
@@ -389,6 +409,7 @@ function DetailHeader({
menuFooter,
assetModule,
}: {
+ children?: ReactNode;
icon: ReactNode;
title: string;
/** 供应商身份附加标签(如免费套餐)。 */
@@ -406,7 +427,7 @@ function DetailHeader({
/** 菜单末尾的只读信息行(如脱敏 key),自带一条分隔线。 */
menuFooter?: ReactNode;
/**
- * 账户资产模块 —— 标题行下方的固定槽位,用一条 1px 发丝线分隔(不做框中框,
+ * 账户资产模块 —— 标题行下方的滚动内容槽位,用一条 1px 发丝线分隔(不做框中框,
* 见 DESIGN §2 layer rule)。判定见 providerAssetModule.ts。
*/
assetModule?: ReactNode;
@@ -423,6 +444,12 @@ function DetailHeader({
}
: undefined);
const subscription = useProviderSubscriptionCard(provider);
+ const detailScrollRef = useRef<HTMLDivElement>(null);
+ const hasDetail = Boolean(detail);
+ useLayoutEffect(() => {
+ // Reveal newly opened authentication content without resetting on typing or quota refresh.
+ if (hasDetail && detailScrollRef.current) detailScrollRef.current.scrollTop = 0;
+ }, [hasDetail]);
const subscriptionProduct =
provider?.access?.kind === 'subscription' ? provider.access.product : null;
// 单 agent 供应商在头部统一说明(行级不再逐条标注,见 UnifiedModelList 头注释)。
@@ -439,8 +466,8 @@ function DetailHeader({
: null;
return (
- <div className="flex shrink-0 flex-col">
- <div className={cn('flex flex-col px-5 py-4', detail && 'gap-3')}>
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="shrink-0 px-5 py-4">
{/* 可折行:最小窗口(右栏 ~275px)放不下「状态 + 操作」时整组换行,
不被卡片 overflow-hidden 裁掉(PR #1102 review 第三轮)。 */}
<div className="flex flex-wrap items-center gap-3 gap-y-2">
@@ -580,36 +607,51 @@ function DetailHeader({
)}
</div>
</div>
-
- {detail}
</div>
- {assetModule ??
- (subscription && (
- <div
- data-testid="provider-usage-module"
- className="border-t px-1 py-2"
- style={{ borderColor: 'var(--settings-theme-card-border)' }}
- >
- <QuotaHoverCard
- variant="embedded"
- account={subscription}
- dashboardLabel={
- provider?.id === 'anthropic' || provider?.auth.native === 'claude'
- ? t('settings.providers.usage.openClaudeUsage')
- : provider?.id === 'xai' || provider?.auth.native === 'xai'
- ? t('settings.providers.xai.asset.openUsage')
- : undefined
- }
- onOpenDashboard={
- provider?.id === 'anthropic' || provider?.auth.native === 'claude'
- ? () => void window.electronAPI.openExternal('https://claude.ai/settings/usage')
- : provider?.id === 'xai' || provider?.auth.native === 'xai'
- ? () => void window.electronAPI.openExternal('https://grok.com')
- : undefined
- }
- />
- </div>
- ))}
+ <div
+ data-testid="provider-detail-scroll"
+ ref={detailScrollRef}
+ className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden overflow-y-auto overscroll-contain [&>*]:shrink-0"
+ >
+ {detail && <div className="px-5 pb-4">{detail}</div>}
+ {assetModule ??
+ (subscription && (
+ <div
+ data-testid="provider-usage-module"
+ className="border-t px-1 py-2"
+ style={{ borderColor: 'var(--settings-theme-card-border)' }}
+ >
+ <QuotaHoverCard
+ key={JSON.stringify([
+ provider?.id,
+ provider?.connected,
+ provider?.subscriptionAccount?.source,
+ provider?.subscriptionAccount?.identity,
+ provider?.openAiAccount?.source,
+ provider?.openAiAccount?.identity,
+ ])}
+ variant="embedded"
+ hideIdentity={Boolean(subscriptionProduct)}
+ account={subscription}
+ dashboardLabel={
+ provider?.id === 'anthropic' || provider?.auth.native === 'claude'
+ ? t('settings.providers.usage.openClaudeUsage')
+ : provider?.id === 'xai' || provider?.auth.native === 'xai'
+ ? t('settings.providers.xai.asset.openUsage')
+ : undefined
+ }
+ onOpenDashboard={
+ provider?.id === 'anthropic' || provider?.auth.native === 'claude'
+ ? () => void window.electronAPI.openExternal('https://claude.ai/settings/usage')
+ : provider?.id === 'xai' || provider?.auth.native === 'xai'
+ ? () => void window.electronAPI.openExternal('https://grok.com')
+ : undefined
+ }
+ />
+ </div>
+ ))}
+ {children}
+ </div>
</div>
);
}
@@ -619,9 +661,11 @@ function DetailHeader({
// ---------------------------------------------------------------------------
function AnthropicHeader({
+ children,
provider,
onChanged,
}: {
+ children?: ReactNode;
provider?: ProviderView;
onChanged: () => void;
}) {
@@ -659,7 +703,8 @@ function AnthropicHeader({
toast.error(t('settings.connections.claude.toast.loginFailed'));
}
} catch {
- if (loginRef.current === login) toast.error(t('settings.connections.claude.toast.loginFailed'));
+ if (loginRef.current === login)
+ toast.error(t('settings.connections.claude.toast.loginFailed'));
} finally {
if (loginRef.current === login) {
loginRef.current = null;
@@ -719,6 +764,7 @@ function AnthropicHeader({
return (
<DetailHeader
+ children={children}
icon={<AnthropicMark size={18} />}
title={provider?.name ?? t('settings.providers.anthropic.title')}
subtitle={providerSubtitleForDisplay(provider, t('settings.providers.anthropic.modelLabel'), {
@@ -758,7 +804,15 @@ function LocalProviderNameInput({
);
}
-function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged: () => void }) {
+function OpenAiHeader({
+ children,
+ provider,
+ onChanged,
+}: {
+ children?: ReactNode;
+ provider?: ProviderView;
+ onChanged: () => void;
+}) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
const {
@@ -797,7 +851,9 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
}, [confirm, provider, onChanged, t]);
const handleLogin = useCallback(async () => {
- const outcome = await triggerLogin(reconnectRequired && credentialScope !== 'system-shared' ? 'browser' : 'local');
+ const outcome = await triggerLogin(
+ reconnectRequired && credentialScope !== 'system-shared' ? 'browser' : 'local',
+ );
if (outcome === 'authenticated') {
onChanged();
} else if (outcome === 'unverified') {
@@ -865,6 +921,7 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
return (
<DetailHeader
+ children={children}
icon={<OpenAIMark size={18} />}
title={provider?.name ?? t('settings.providers.openai.title')}
subtitle={
@@ -885,7 +942,15 @@ function OpenAiHeader({ provider, onChanged }: { provider?: ProviderView; onChan
);
}
-function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged: () => void }) {
+function XaiHeader({
+ children,
+ provider,
+ onChanged,
+}: {
+ children?: ReactNode;
+ provider?: ProviderView;
+ onChanged: () => void;
+}) {
const { t } = useTranslation();
const { confirm } = useConfirmDialog();
const [busy, setBusy] = useState(false);
@@ -960,6 +1025,7 @@ function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged
return (
<DetailHeader
+ children={children}
icon={<ProviderLogoMark providerId="xai" size={18} />}
title={provider?.name ?? t('settings.providers.xai.title')}
subtitle={providerSubtitleForDisplay(provider, t('settings.providers.xai.modelLabel'), {
@@ -977,11 +1043,13 @@ function XaiHeader({ provider, onChanged }: { provider?: ProviderView; onChanged
// ---------------------------------------------------------------------------
function GenericOAuthHeader({
+ children,
provider,
onChanged,
onEdit,
onDelete,
}: {
+ children?: ReactNode;
provider: ProviderView;
onChanged: () => void;
onEdit?: () => void;
@@ -1002,7 +1070,9 @@ function GenericOAuthHeader({
);
const deviceFlow = provider.auth.oauth?.flow === 'device-code';
const { deviceCode, browserUrl, clearDeviceCode, beginOwnedLogin, cancelOwnedLogin } =
- useProviderOAuthDeviceCode(provider.id, { observeProgress: deviceFlow || provider.auth.native === 'codex' });
+ useProviderOAuthDeviceCode(provider.id, {
+ observeProgress: deviceFlow || provider.auth.native === 'codex',
+ });
const handleLogin = useCallback(async () => {
const attempt = ++loginAttempt.current;
@@ -1048,7 +1118,8 @@ function GenericOAuthHeader({
});
if (!confirmed) return;
setBusy(true);
- if (!(await confirmProviderChange(options => disconnectProvider(provider, scope, options)))) return;
+ if (!(await confirmProviderChange((options) => disconnectProvider(provider, scope, options))))
+ return;
toast.success(t('settings.providers.genericOAuth.toast.loggedOut', { name: provider.name }));
onChanged();
} catch {
@@ -1095,11 +1166,15 @@ function GenericOAuthHeader({
disabled: busy,
};
const detail =
- loggingIn && deviceFlow ? <OAuthDeviceCodeCard deviceCode={deviceCode} />
- : loggingIn && browserUrl ? <OAuthBrowserLink url={browserUrl} /> : undefined;
+ loggingIn && deviceFlow ? (
+ <OAuthDeviceCodeCard deviceCode={deviceCode} />
+ ) : loggingIn && browserUrl ? (
+ <OAuthBrowserLink url={browserUrl} />
+ ) : undefined;
return (
<DetailHeader
+ children={children}
icon={providerIcon(provider, 18)}
title={provider.name}
subtitle={
@@ -1154,9 +1229,11 @@ function GenericOAuthHeader({
* 草稿(草稿本就在 renderer state 里),不构成凭证下放。
*/
function BuiltinApiKeyHeader({
+ children,
provider,
onChanged,
}: {
+ children?: ReactNode;
provider: ProviderView;
onChanged: () => void;
}) {
@@ -1258,6 +1335,7 @@ function BuiltinApiKeyHeader({
return (
<DetailHeader
+ children={children}
icon={providerIcon(provider, 18)}
title={provider.name}
subtitle={t('settings.providers.builtinApiKey.subtitle')}
@@ -1296,9 +1374,11 @@ function maskKey(key: string): string {
}
function XdGatewayHeader({
+ children,
provider,
onChanged,
}: {
+ children?: ReactNode;
provider?: ProviderView;
onChanged: () => void;
}) {
@@ -1566,7 +1646,7 @@ function XdGatewayHeader({
</p>
</div>
{/* 一屏一颗 Black Pill。查看用量始终是次动作;右侧按套餐状态切换。 */}
- <div className="flex shrink-0 items-center gap-3">
+ <div className="flex min-w-0 max-w-full flex-wrap items-center gap-3">
<PillButton
label={t('settings.providers.xd.asset.refresh')}
onClick={refreshAccount}
@@ -1599,6 +1679,7 @@ function XdGatewayHeader({
return (
<DetailHeader
+ children={children}
icon={<XDIncMark size={18} />}
title={t('settings.providers.xd.title')}
identityBadge={
@@ -1621,10 +1702,19 @@ function XdGatewayHeader({
);
}
-function OllamaHeader({ provider, onDelete }: { provider: ProviderView; onDelete: () => void }) {
+function OllamaHeader({
+ children,
+ provider,
+ onDelete,
+}: {
+ children?: ReactNode;
+ provider: ProviderView;
+ onDelete: () => void;
+}) {
const { t } = useTranslation();
return (
<DetailHeader
+ children={children}
icon={providerIcon(provider, 18)}
title={provider.name || t('settings.providers.local.title')}
subtitle={t('settings.providers.local.subtitle')}
@@ -1644,11 +1734,13 @@ function OllamaHeader({ provider, onDelete }: { provider: ProviderView; onDelete
// ---------------------------------------------------------------------------
function CustomProviderHeader({
+ children,
provider,
onEdit,
onDelete,
onChanged,
}: {
+ children?: ReactNode;
provider: ProviderView;
onEdit: () => void;
onDelete: () => void;
@@ -1673,7 +1765,8 @@ function CustomProviderHeader({
)
return;
setDisconnecting(true);
- if (!(await confirmProviderChange(options => disconnectProvider(provider, scope, options)))) return;
+ if (!(await confirmProviderChange((options) => disconnectProvider(provider, scope, options))))
+ return;
} catch {
toast.error(t('settings.providers.genericOAuth.toast.logoutFailed', { name: provider.name }));
} finally {
@@ -1686,6 +1779,7 @@ function CustomProviderHeader({
if (isOAuth)
return (
<GenericOAuthHeader
+ children={children}
key={provider.id}
provider={provider}
onChanged={onChanged}
@@ -1695,6 +1789,7 @@ function CustomProviderHeader({
);
return (
<DetailHeader
+ children={children}
icon={providerIcon(provider, 18)}
title={provider.name}
subtitle={customProviderSubtitleForDisplay(provider)}
@@ -2348,7 +2443,8 @@ export function ProvidersSection() {
cancelText: t('settings.providers.custom.deleteConfirm.cancel'),
});
if (!ok) return;
- if (!(await confirmProviderChange(options => deleteCustomProvider(p.id, scope, options)))) return;
+ if (!(await confirmProviderChange((options) => deleteCustomProvider(p.id, scope, options))))
+ return;
toast.success(t('settings.providers.custom.toast.deleted'));
} catch {
toast.error(t('settings.providers.custom.toast.deleteFailed'));
@@ -2411,8 +2507,13 @@ export function ProvidersSection() {
}
anyOk = true;
const openRouterCatalog = /^https:\/\/openrouter\.ai\/api(?:\/v1)?\/?$/.test(rt.baseUrl)
- ? rt.modelsUrl ?? 'https://openrouter.ai/api/v1/models' : undefined;
- const merged = appendDiscoveredCustomProviderModels(rt.models, r.models, openRouterCatalog);
+ ? (rt.modelsUrl ?? 'https://openrouter.ai/api/v1/models')
+ : undefined;
+ const merged = appendDiscoveredCustomProviderModels(
+ rt.models,
+ r.models,
+ openRouterCatalog,
+ );
rt.models = merged.models;
added += merged.addedIds.length;
}
@@ -2491,27 +2592,42 @@ export function ProvidersSection() {
);
// 详情头部按供应商类型分派(鉴权逻辑与重构前一致)。
- const renderDetailHeader = (p: ProviderView): ReactNode => {
- if (p.id === 'xd') return <XdGatewayHeader provider={p} onChanged={refetch} />;
- if (p.id === 'anthropic') return <AnthropicHeader provider={p} onChanged={refetch} />;
- if (p.id === 'openai') return <OpenAiHeader provider={p} onChanged={refetch} />;
- if (p.id === 'xai') return <XaiHeader provider={p} onChanged={refetch} />;
- if (
- p.source === 'builtin' &&
- p.auth.method === 'apiKey' &&
- isBuiltinApiKeyProviderId(p.id)
- ) {
- return <BuiltinApiKeyHeader key={p.id} provider={p} onChanged={refetch} />;
+ const renderDetailHeader = (p: ProviderView, children: ReactNode): ReactNode => {
+ if (p.id === 'xd')
+ return <XdGatewayHeader children={children} provider={p} onChanged={refetch} />;
+ if (p.id === 'anthropic')
+ return <AnthropicHeader children={children} provider={p} onChanged={refetch} />;
+ if (p.id === 'openai')
+ return <OpenAiHeader children={children} provider={p} onChanged={refetch} />;
+ if (p.id === 'xai') return <XaiHeader children={children} provider={p} onChanged={refetch} />;
+ if (p.source === 'builtin' && p.auth.method === 'apiKey' && isBuiltinApiKeyProviderId(p.id)) {
+ return (
+ <BuiltinApiKeyHeader children={children} key={p.id} provider={p} onChanged={refetch} />
+ );
}
if (p.source === 'builtin') {
- if (supportsBuiltinConnectionManagement(p)) return <GenericOAuthHeader key={p.id} provider={p} onChanged={refetch} />;
- return <DetailHeader icon={providerIcon(p, 18)} title={p.name} subtitle={providerSubtitleForDisplay(p, '')} provider={p} />;
+ if (supportsBuiltinConnectionManagement(p))
+ return (
+ <GenericOAuthHeader children={children} key={p.id} provider={p} onChanged={refetch} />
+ );
+ return (
+ <DetailHeader
+ children={children}
+ icon={providerIcon(p, 18)}
+ title={p.name}
+ subtitle={providerSubtitleForDisplay(p, '')}
+ provider={p}
+ />
+ );
}
if (p.id === MANAGED_OLLAMA_PROVIDER_ID) {
- return <OllamaHeader provider={p} onDelete={() => void handleDeleteOllama()} />;
+ return (
+ <OllamaHeader children={children} provider={p} onDelete={() => void handleDeleteOllama()} />
+ );
}
return (
<CustomProviderHeader
+ children={children}
key={p.id}
provider={p}
onChanged={refetch}
@@ -2640,9 +2756,8 @@ export function ProvidersSection() {
</div>
</div>
- {/* 右栏详情:详情头/条带固定,仅模型列表(UnifiedModelList 内部)滚动 ——
- 长清单滚动时供应商名称、连接状态与工具行不随之滚走(2026-07 定稿)。 */}
- <div className="flex min-w-0 flex-1 flex-col">
+ {/* 右栏身份固定;说明、资产和模型共用 DetailHeader 的滚动区。 */}
+ <div key={effectiveSelected?.id} className="flex min-h-0 min-w-0 flex-1 flex-col">
{cindySigninActive ? (
/* 登录引导是 brand-scale surface(DESIGN §3):48px 标识 → 24px 名字 →
一行价值主张 → 赠送余额徽标 → 黑 CTA,间距走 8px 系统。底部留白比
@@ -2690,8 +2805,8 @@ export function ProvidersSection() {
/>
</div>
) : effectiveSelected ? (
- <>
- {renderDetailHeader(effectiveSelected)}
+ renderDetailHeader(
+ effectiveSelected,
<>
{/* 供应商已停用:条带讲清「发生了什么 + 下一步」并就地给恢复入口。整个
模型区随之收起(2026-07-28 用户反馈:停用了就别再列模型)——停用是
@@ -2775,15 +2890,18 @@ export function ProvidersSection() {
: undefined
}
emptyMessage={
- effectiveSelected.source === 'user' && effectiveSelected.modelDiscoveryFailure
- ? t(`settings.providers.detail.discoveryFailed.${effectiveSelected.modelDiscoveryFailure.kind}`)
- : effectiveSelected.id === MANAGED_OLLAMA_PROVIDER_ID
- ? t('settings.providers.local.emptyInstalled')
- : t(
- effectiveSelected.connected
- ? 'settings.providers.detail.emptyModelsConnected'
- : 'settings.providers.detail.emptyModels',
+ effectiveSelected.source === 'user' &&
+ effectiveSelected.modelDiscoveryFailure
+ ? t(
+ `settings.providers.detail.discoveryFailed.${effectiveSelected.modelDiscoveryFailure.kind}`,
)
+ : effectiveSelected.id === MANAGED_OLLAMA_PROVIDER_ID
+ ? t('settings.providers.local.emptyInstalled')
+ : t(
+ effectiveSelected.connected
+ ? 'settings.providers.detail.emptyModelsConnected'
+ : 'settings.providers.detail.emptyModels',
+ )
}
compactWhenEmpty={effectiveSelected.id === MANAGED_OLLAMA_PROVIDER_ID}
compact={effectiveSelected.id === MANAGED_OLLAMA_PROVIDER_ID}
@@ -2843,8 +2961,8 @@ export function ProvidersSection() {
{effectiveSelected.id === MANAGED_OLLAMA_PROVIDER_ID && (
<OllamaProviderDetail onChanged={refetch} />
)}
- </>
- </>
+ </>,
+ )
) : (
<div
className="flex flex-1 items-center justify-center px-8 text-center text-13"
diff --git a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
index 01e19845f0..b67258ade1 100644
--- a/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
+++ b/apps/desktop/src/renderer/components/settings/UnifiedModelList.tsx
@@ -278,7 +278,9 @@ export function buildUnionRows(provider: ProviderView): UnionModelRow[] {
function rowHasVisibilitySwitch(row: UnionModelRow, userProvider: boolean): boolean {
if (!isCapabilityRow(row, userProvider)) return true;
- return managementKindsOfRow(row, userProvider).some((kind) => kind === 'image' || kind === 'video');
+ return managementKindsOfRow(row, userProvider).some(
+ (kind) => kind === 'image' || kind === 'video',
+ );
}
/** Image/video switches follow media readiness, not the chat OAuth connection. */
@@ -294,13 +296,15 @@ export function canWriteModelVisibility(options: {
}
/** 该行在指定 agent 下的可见性(不可用 → null)。 */
-function rowEnabled(providerId: string, row: UnionModelRow, agent: AgentKind, userProvider: boolean): boolean | null {
+function rowEnabled(
+ providerId: string,
+ row: UnionModelRow,
+ agent: AgentKind,
+ userProvider: boolean,
+): boolean | null {
const m = row.byAgent[agent];
if (!m) return null;
- if (
- isAgentSelectableModel(m, { userProvider }) ||
- rowHasVisibilitySwitch(row, userProvider)
- ) {
+ if (isAgentSelectableModel(m, { userProvider }) || rowHasVisibilitySwitch(row, userProvider)) {
return isModelEnabled(agent, providerId, m);
}
return null;
@@ -327,10 +331,13 @@ export function hasPaymentRequiredDisabledRow(
* `userProvider` = 行来自用户自定义供应商 —— 自定义对话模型的未知 group 不吃 id
* 启发式(`gpt-4o-audio-preview` 是合法对话模型,见 isAgentSelectableModel 注释)。 */
export function isCapabilityRow(row: UnionModelRow, userProvider: boolean): boolean {
- return row.avail.length > 0 && row.avail.every((agent) => {
- const model = row.byAgent[agent];
- return !model || !isAgentSelectableModel(model, { userProvider });
- });
+ return (
+ row.avail.length > 0 &&
+ row.avail.every((agent) => {
+ const model = row.byAgent[agent];
+ return !model || !isAgentSelectableModel(model, { userProvider });
+ })
+ );
}
/** A normal list toggle enables native engines; compatibility engines remain opt-in. */
@@ -349,7 +356,9 @@ export function modelVisibilityTargets(
if (!enabled)
return row.avail.flatMap((agent) => {
const model = row.byAgent[agent];
- return model && isAgentSelectableModel(model, { userProvider }) ? [{ agent, modelId: model.id }] : [];
+ return model && isAgentSelectableModel(model, { userProvider })
+ ? [{ agent, modelId: model.id }]
+ : [];
});
// A model-level enable activates every native engine, not only the recommended one.
// Compatibility engines are untouched; an explicit enable may fall back if none are native.
@@ -363,8 +372,8 @@ export function modelVisibilityTargets(
model.availability !== 'requires_payment'
);
});
- const native = nativeModelAgents(provider, row.byAgent).filter(agent => usable.includes(agent));
- if (native.length) return native.map(agent => ({ agent, modelId: row.byAgent[agent]!.id }));
+ const native = nativeModelAgents(provider, row.byAgent).filter((agent) => usable.includes(agent));
+ if (native.length) return native.map((agent) => ({ agent, modelId: row.byAgent[agent]!.id }));
const defaults = usable.filter((agent) => row.byAgent[agent]?.defaultEnabled !== false);
const agent = pickRecommendedAgent(provider, row.id, defaults.length ? defaults : usable);
const model = agent ? row.byAgent[agent] : undefined;
@@ -398,8 +407,13 @@ export function managementKindsOfRow(row: UnionModelRow, userProvider: boolean):
const model = row.byAgent[agent];
if (!model) continue;
const category = classifyModel(model);
- kinds.add(isAgentSelectableModel(model, { userProvider }) ? 'chat'
- : CAPABILITY_CATEGORIES.has(category) ? category as ManagementKind : 'other');
+ kinds.add(
+ isAgentSelectableModel(model, { userProvider })
+ ? 'chat'
+ : CAPABILITY_CATEGORIES.has(category)
+ ? (category as ManagementKind)
+ : 'other',
+ );
}
return MANAGEMENT_KIND_ORDER.filter((kind) => kinds.has(kind));
}
@@ -706,7 +720,8 @@ export function UnifiedModelList({
const present = new Set<ModelCategory | 'chat'>();
for (const row of unionRows) {
const rep = row.byAgent[row.avail[0]];
- if (rep) for (const kind of managementKindsOfRow(row, provider.source === 'user')) present.add(kind);
+ if (rep)
+ for (const kind of managementKindsOfRow(row, provider.source === 'user')) present.add(kind);
}
return MANAGEMENT_KIND_ORDER.filter((kind) => present.has(kind));
}, [kindOf, unionRows, provider.source]);
@@ -716,12 +731,14 @@ export function UnifiedModelList({
// 分组沿用现有口径:用每行第一个可用 agent 的目录条目作代表参与分组。
const { groups, hiddenRows, disabledRows } = useMemo(() => {
const q = query.trim().toLowerCase();
- const searched = q
- ? unionRows.filter((r) => matchesModelName(r, q, t))
- : unionRows;
+ const searched = q ? unionRows.filter((r) => matchesModelName(r, q, t)) : unionRows;
const matched =
showKindFilter && kindFilter !== 'all'
- ? searched.filter((r) => managementKindsOfRow(r, provider.source === 'user').includes(kindFilter as ManagementKind))
+ ? searched.filter((r) =>
+ managementKindsOfRow(r, provider.source === 'user').includes(
+ kindFilter as ManagementKind,
+ ),
+ )
: searched;
const active = matched.filter((r) => !rowDisabledEffective(r));
const disabled = matched.filter((r) => rowDisabledEffective(r));
@@ -749,7 +766,9 @@ export function UnifiedModelList({
}
return {
groups: groupModelsForManagement(reps, managementView, (model) =>
- showKindFilter && kindFilter !== 'all' ? kindFilter as ManagementKind : kindOf(repByRow.get(model.id)!),
+ showKindFilter && kindFilter !== 'all'
+ ? (kindFilter as ManagementKind)
+ : kindOf(repByRow.get(model.id)!),
).map((g) => ({
key: g.key,
kind: g.kind,
@@ -830,7 +849,7 @@ export function UnifiedModelList({
}
const next = !rowAnyEnabled(provider.id, row, userProvider);
const targets = modelVisibilityTargets(provider, row, next);
- if (await setModelVisibilities(provider.id, targets, next) === false) {
+ if ((await setModelVisibilities(provider.id, targets, next)) === false) {
showVisibilityWriteFailure();
}
},
@@ -940,7 +959,10 @@ export function UnifiedModelList({
<span
className="min-w-0 truncate text-14 font-medium"
style={{
- color: state.ready && (capability || anyOn) ? 'var(--settings-section-title)' : 'var(--text-tertiary)',
+ color:
+ state.ready && (capability || anyOn)
+ ? 'var(--settings-section-title)'
+ : 'var(--text-tertiary)',
}}
>
{localizedModelName(rep.name, t)}
@@ -1025,11 +1047,14 @@ export function UnifiedModelList({
const compactList = Boolean(compact) || compactEmpty;
return (
- <div className={cn('flex min-h-0 flex-col', compactList ? 'shrink-0' : 'flex-1')}>
+ <div className={'flex flex-col'}>
{/* 第一行说明模型选择与管理,第二行仅筛选当前列表。排列和批量配置在菜单里
明确分组,任何筛选或排列操作都不写入模型开关。 */}
{!compactEmpty && (
- <div className="flex flex-col gap-2 px-5 pb-2 pt-2.5">
+ <div
+ data-testid="provider-model-toolbar"
+ className="sticky top-0 z-10 flex flex-col gap-2 bg-[var(--settings-theme-card-bg)] px-5 pb-2 pt-2.5"
+ >
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
<div className="min-w-0 flex-1">
<div className="flex flex-wrap items-baseline gap-x-2">
@@ -1186,12 +1211,9 @@ export function UnifiedModelList({
</div>
)}
- {/* 分组 + 模型行 + 底部「已停用」分区:唯一滚动区,与上方固定工具行以
+ {/* 分组 + 模型行 + 底部「已停用」分区随供应商详情滚动,与吸顶工具行以
1px 细线分隔。视觉左右边距 20px = 容器 px-3 + 行 px-2(行悬停底色要包住内容)。 */}
- <div
- className={cn('min-h-0 overflow-y-auto border-t', compactList ? 'shrink-0' : 'flex-1')}
- style={{ borderColor: 'var(--settings-theme-card-border)' }}
- >
+ <div className={'border-t'} style={{ borderColor: 'var(--settings-theme-card-border)' }}>
<div className={cn('flex flex-col gap-4 px-3 pt-1.5', compactList ? 'pb-2' : 'pb-4')}>
{groups.length === 0 && hiddenRows.length === 0 && disabledRows.length === 0 ? (
<div
@@ -1372,7 +1394,9 @@ export function UnifiedModelList({
className="shrink-0 text-12"
style={{ color: 'var(--text-tertiary)' }}
>
- {modelBrand(rep) ? localizedBrandName(modelBrand(rep)!, t) : t(CATEGORY_LABEL_KEY[rowCategory(row)])}
+ {modelBrand(rep)
+ ? localizedBrandName(modelBrand(rep)!, t)
+ : t(CATEGORY_LABEL_KEY[rowCategory(row)])}
</span>
<span className="min-w-0 flex-1" />
{paymentRequired && (
diff --git a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
index 0fd76bfc64..ecf59cc56c 100644
--- a/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
+++ b/apps/desktop/src/renderer/components/status/QuotaHoverCard.tsx
@@ -10,6 +10,7 @@ import { useTranslation } from 'react-i18next';
import { computeQuotaPace, type QuotaPace } from '@/lib/quotaPace';
import { cn } from '@/lib/utils';
+import { Button } from '@/components/ui/button';
import {
formatQuotaResetCountdown,
formatQuotaResetAt,
@@ -47,6 +48,8 @@ export interface QuotaHoverCardSessionUsage {
export interface QuotaHoverCardProps {
/** Embedded settings surface shares content without a second card frame. */
variant?: 'popover' | 'embedded';
+ /** The settings identity row already names this subscription and plan. */
+ hideIdentity?: boolean;
account: UsageCardAccount;
sessionUsage?: QuotaHoverCardSessionUsage | null;
turnUsage?: QuotaHoverCardTurnUsage | null;
@@ -118,6 +121,8 @@ function WindowBlock({
detail,
breakdown,
showAbsoluteReset = false,
+ compact = false,
+ expanded = false,
nowMs,
paceNowMs,
locale,
@@ -130,6 +135,8 @@ function WindowBlock({
detail?: string;
breakdown?: UsageCardWindow['breakdown'];
showAbsoluteReset?: boolean;
+ compact?: boolean;
+ expanded?: boolean;
nowMs: number;
paceNowMs: number | null;
locale: string | undefined;
@@ -167,60 +174,80 @@ function WindowBlock({
return (
<section data-testid="quota-window" className="px-4 pb-1 pt-2">
- <div
- id={titleId}
- data-severity={severity}
- className={cn(
- 'mb-2 text-14 font-medium tracking-[-0.005em]',
- severity === 'crit' ? 'text-[var(--quota-bar-crit)]' : 'text-[var(--text-primary)]',
- )}
- >
- {title}
- {severityAnnouncement !== null ? (
- // 告警不能只依赖颜色;标题与进度条共用对应级别的屏幕阅读器文案。
- <span className="sr-only">,{severityAnnouncement}</span>
- ) : null}
- </div>
- <QuotaBar
- usedPercent={window.utilization}
- showRemaining={showRemaining}
- severity={severity}
- aria-labelledby={titleId}
- aria-valuetext={percentText}
- />
- <div className="mt-[7px] flex items-baseline justify-between gap-3 tabular-nums">
- <span className="font-medium text-[var(--text-primary)]">{percentText}</span>
- {resetCountdown !== null ? (
- <span className="flex min-w-0 flex-col items-end text-right text-12 text-[var(--text-secondary)]">
- <span>{resetCountdown}</span>
- {showAbsoluteReset && resetAt !== null && (
- <span>{t('quotaCard.resetAt', { at: resetAt })}</span>
- )}
- </span>
- ) : null}
- </div>
- {detail ? <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div> : null}
- {breakdown?.length ? (
- <dl
- data-testid="quota-window-breakdown"
- className="mt-2 space-y-1 text-12 text-[var(--text-secondary)]"
+ <div className={compact ? 'flex flex-wrap items-center gap-x-3 gap-y-1' : undefined}>
+ <div
+ id={titleId}
+ data-severity={severity}
+ className={cn(
+ 'font-medium tracking-[-0.005em]',
+ compact ? 'text-13' : 'mb-2 text-14',
+ severity === 'crit' ? 'text-[var(--quota-bar-crit)]' : 'text-[var(--text-primary)]',
+ )}
>
- {breakdown.map(({ label, value }, index) => (
- <div key={index} className="flex items-baseline justify-between gap-3">
- <dt className="min-w-0 break-words">{label}</dt>
- <dd className="shrink-0 tabular-nums">{value}</dd>
- </div>
- ))}
- </dl>
- ) : null}
- {paceLine !== null ? (
+ {title}
+ {severityAnnouncement !== null ? (
+ // 告警不能只依赖颜色;标题与进度条共用对应级别的屏幕阅读器文案。
+ <span className="sr-only">,{severityAnnouncement}</span>
+ ) : null}
+ </div>
+ <QuotaBar
+ className={compact ? 'w-28 shrink-0' : undefined}
+ usedPercent={window.utilization}
+ showRemaining={showRemaining}
+ severity={severity}
+ aria-labelledby={titleId}
+ aria-valuetext={percentText}
+ />
<div
- data-testid="quota-pace"
- className="mt-[3px] text-12 tabular-nums text-[var(--text-secondary)]"
+ className={cn(
+ 'flex items-baseline justify-between gap-3 tabular-nums',
+ !compact && 'mt-[7px]',
+ )}
>
- {paceLine}
+ <span className="font-medium text-[var(--text-primary)]">{percentText}</span>
+ {resetCountdown !== null ? (
+ <span className="flex min-w-0 flex-col items-end text-right text-12 text-[var(--text-secondary)]">
+ <span>{resetCountdown}</span>
+ {!compact && showAbsoluteReset && resetAt !== null && (
+ <span>{t('quotaCard.resetAt', { at: resetAt })}</span>
+ )}
+ </span>
+ ) : null}
</div>
- ) : null}
+ </div>
+ {(!compact || expanded) && (
+ <>
+ {compact && resetAt !== null && (
+ <div className="mt-1 text-12 text-[var(--text-secondary)]">
+ {t('quotaCard.resetAt', { at: resetAt })}
+ </div>
+ )}
+ {detail ? (
+ <div className="mt-1 text-12 text-[var(--text-secondary)]">{detail}</div>
+ ) : null}
+ {breakdown?.length ? (
+ <dl
+ data-testid="quota-window-breakdown"
+ className="mt-2 space-y-1 text-12 text-[var(--text-secondary)]"
+ >
+ {breakdown.map(({ label, value }, index) => (
+ <div key={index} className="flex items-baseline justify-between gap-3">
+ <dt className="min-w-0 break-words">{label}</dt>
+ <dd className="shrink-0 tabular-nums">{value}</dd>
+ </div>
+ ))}
+ </dl>
+ ) : null}
+ {paceLine !== null ? (
+ <div
+ data-testid="quota-pace"
+ className="mt-[3px] text-12 tabular-nums text-[var(--text-secondary)]"
+ >
+ {paceLine}
+ </div>
+ ) : null}
+ </>
+ )}
</section>
);
}
@@ -401,6 +428,7 @@ function SessionUsageSection({
/** 套餐、配额、任务合计与本轮明细按同一信息层级渲染;供应商差异只来自 account。 */
export function QuotaHoverCard({
variant = 'popover',
+ hideIdentity = false,
account,
sessionUsage = null,
turnUsage = null,
@@ -410,9 +438,19 @@ export function QuotaHoverCard({
nowMs = Date.now(),
}: QuotaHoverCardProps) {
const { t, i18n } = useTranslation();
+ const [expanded, setExpanded] = React.useState(false);
+ const embedded = variant === 'embedded';
+ const detailsId = React.useId();
// 测试可只注入 t;运行时再优先跟随应用当前语言格式化日期。
const locale = i18n?.resolvedLanguage ?? i18n?.language;
const { title, planLabel, windows, details = [], notices = [], emptyText, updatedAt } = account;
+ // Pace also requires a valid reset time; balances and notices are always visible.
+ const hasWindowDetails = windows.some(
+ ({ window, detail, breakdown }) =>
+ formatQuotaResetAt(window.resetsAt, nowMs, locale) !== null ||
+ Boolean(detail) ||
+ Boolean(breakdown?.length),
+ );
// Use observation time for pace so a stale snapshot cannot drift as the card renders.
const paceNowMs = typeof updatedAt === 'number' && Number.isFinite(updatedAt) ? updatedAt : null;
const staleMinutes =
@@ -435,10 +473,14 @@ export function QuotaHoverCard({
data-testid="quota-hover-card-scroll-content"
role="region"
aria-label={t('quotaCard.windowsRegionLabel')}
- tabIndex={0}
- className="min-h-0 overflow-y-auto pt-[6px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]"
+ tabIndex={embedded ? undefined : 0}
+ className={cn(
+ 'min-h-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--focus-ring)]',
+ !embedded && 'overflow-y-auto pt-[6px]',
+ )}
+ id={detailsId}
>
- {title ? (
+ {title && (!embedded || !hideIdentity) ? (
<>
<div className="flex items-center gap-2 px-4 pb-2 pt-3 text-12 text-[var(--text-secondary)]">
<span className="min-w-0 break-words font-medium">{title}</span>
@@ -453,12 +495,13 @@ export function QuotaHoverCard({
</div>
</>
) : null}
- {title && (windows.length > 0 || emptyText) ? <CardDivider /> : null}
+ {!embedded && title && (windows.length > 0 || emptyText) ? <CardDivider /> : null}
{windows.map(({ key, ...displayWindow }) => (
<WindowBlock
key={key}
{...displayWindow}
- showAbsoluteReset={variant === 'embedded'}
+ compact={embedded}
+ expanded={expanded}
nowMs={nowMs}
paceNowMs={paceNowMs}
locale={locale}
@@ -486,8 +529,13 @@ export function QuotaHoverCard({
))}
{details.length ? (
<>
- <CardDivider />
- <section className="space-y-1 px-4 py-2 text-12 tabular-nums text-[var(--text-secondary)]">
+ {!embedded && <CardDivider />}
+ <section
+ className={cn(
+ 'px-4 py-2 text-12 tabular-nums text-[var(--text-secondary)]',
+ embedded ? 'flex flex-wrap gap-x-3 gap-y-1' : 'space-y-1',
+ )}
+ >
{details.map((detail, index) => (
<div key={index}>{detail}</div>
))}
@@ -510,6 +558,19 @@ export function QuotaHoverCard({
) : null}
</div>
+ {embedded && hasWindowDetails && (
+ <Button
+ variant="secondary"
+ type="button"
+ aria-expanded={expanded}
+ aria-controls={detailsId}
+ onClick={() => setExpanded((value) => !value)}
+ className="mx-4 w-fit gap-1"
+ >
+ <span aria-hidden="true">{expanded ? '▾' : '▸'}</span>
+ {t('quotaCard.usageTitle')}
+ </Button>
+ )}
{dashboardLabel ? (
<>
<CardDivider />
diff --git a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
index 8a08e90f22..e4864909e4 100644
--- a/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
+++ b/apps/desktop/src/renderer/components/status/__tests__/QuotaHoverCard.test.tsx
@@ -91,6 +91,44 @@ function weeklyAtProgress(utilization: number, progress: number) {
}
describe('QuotaHoverCard', () => {
+ it.each([undefined, null, 0, NaN, Infinity, 1e20])(
+ 'omits the disclosure when windows have no displayable details (reset=%s)',
+ (resetsAt) => {
+ render(<UsageCard variant="embedded" nowMs={NOW_MS} account={{
+ windows: [{ key: 'weekly', title: 'Weekly', window: { utilization: 20, resetsAt }, breakdown: [] }],
+ details: ['Balance available'],
+ }} />);
+ expect(screen.getByRole('progressbar')).toBeTruthy();
+ expect(screen.getByText('Balance available')).toBeTruthy();
+ expect(screen.queryByRole('button', { name: 'quotaCard.usageTitle' })).toBeNull();
+ },
+ );
+
+ it.each(['detail', 'breakdown'] as const)('discloses %s without a reset date', (kind) => {
+ render(<UsageCard variant="embedded" account={{ windows: [
+ { key: 'plain', title: 'Plain', window: { utilization: 10 } },
+ { key: 'detailed', title: 'Detailed', window: { utilization: 20 },
+ ...(kind === 'detail' ? { detail: 'Extra usage' } : { breakdown: [{ label: 'Extra usage', value: '10' }] }),
+ },
+ ] }} />);
+ expect(screen.queryByText('Extra usage')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'quotaCard.usageTitle' }));
+ expect(screen.getByText('Extra usage')).toBeTruthy();
+ });
+
+ it('hides duplicate identity without windows and only makes the popover region focusable', () => {
+ const account = { title: 'ChatGPT', planLabel: 'Pro', windows: [], emptyText: 'Waiting for usage' };
+ const { rerender } = render(<UsageCard variant="embedded" hideIdentity account={account} />);
+ expect(screen.queryByText('ChatGPT')).toBeNull();
+ expect(screen.queryByText('Pro')).toBeNull();
+ expect(screen.getByText('Waiting for usage')).toBeTruthy();
+ expect(screen.getByRole('region').hasAttribute('tabindex')).toBe(false);
+ rerender(<UsageCard hideIdentity account={account} />);
+ expect(screen.getByText('ChatGPT')).toBeTruthy();
+ expect(screen.getByText('Pro')).toBeTruthy();
+ expect(screen.getByRole('region').tabIndex).toBe(0);
+ });
+
it('keeps the provider header while waiting for quota data', () => {
render(<QuotaHoverCard snapshot={null} nowMs={NOW_MS} />);
@@ -150,12 +188,54 @@ describe('QuotaHoverCard', () => {
expect(screen.getByText('剩余 100%')).toBeTruthy();
expect(screen.getByText('剩余 24%')).toBeTruthy();
expect(screen.getByText('7小时 5分钟后重置')).toBeTruthy();
+ expect(screen.queryByText('17:05 重置')).toBeNull();
+ const detailsButton = screen.getByRole('button', { name: 'quotaCard.usageTitle' });
+ expect(detailsButton.getAttribute('aria-expanded')).toBe('false');
+ fireEvent.click(detailsButton);
+ expect(detailsButton.getAttribute('aria-expanded')).toBe('true');
expect(screen.getByText('17:05 重置')).toBeTruthy();
expect(screen.getByText('8月7日 00:00 重置')).toBeTruthy();
expect(screen.getByText('8月6日 23:59 重置')).toBeTruthy();
expect(screen.getByText('18:30 重置')).toBeTruthy();
});
+ it('keeps balances, alerts and stale data visible while embedded details are collapsed', () => {
+ render(
+ <UsageCard
+ variant="embedded"
+ hideIdentity
+ nowMs={NOW_MS}
+ account={{
+ title: 'ChatGPT',
+ planLabel: 'Pro',
+ updatedAt: NOW_MS - 10 * 60_000,
+ windows: [
+ {
+ key: 'weekly',
+ title: 'Weekly',
+ window: weeklyAtProgress(92, 0.5),
+ paceWindowMinutes: 10_080,
+ },
+ ],
+ details: ['0.00 credits', 'Balance depleted'],
+ notices: [{ text: 'Limit reached', tone: 'crit' }],
+ }}
+ />,
+ );
+ expect(screen.queryByText('ChatGPT')).toBeNull();
+ expect(screen.getByText('0.00 credits')).toBeTruthy();
+ expect(screen.getByText('Balance depleted')).toBeTruthy();
+ expect(screen.getByText('Limit reached')).toBeTruthy();
+ expect(screen.getByText('quotaCard.staleData:10')).toBeTruthy();
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+ expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('8');
+ const button = screen.getByRole('button', { name: 'quotaCard.usageTitle' });
+ fireEvent.click(button);
+ expect(screen.getByTestId('quota-pace')).toBeTruthy();
+ fireEvent.click(button);
+ expect(screen.queryByTestId('quota-pace')).toBeNull();
+ });
+
it('prioritizes countdown in compact cards and updates to pending after reset', () => {
const snapshot = makeSnapshot({
sevenDay: { utilization: 30, resetsAt: (NOW_MS + 65 * 60_000) / 1000 },
diff --git a/docs/design-previews/provider-compact-scroll/README.md b/docs/design-previews/provider-compact-scroll/README.md
new file mode 100644
index 0000000000..525c9db6e5
--- /dev/null
+++ b/docs/design-previews/provider-compact-scroll/README.md
@@ -0,0 +1,16 @@
+# 供应商详情:紧凑摘要与统一滚动
+
+打开 [交互设计稿](./index.html) 查看已确认的布局方向。页面自包含,所有数据均为模拟值,品牌图标为占位符,不连接真实账号。
+
+- 供应商身份固定;用量摘要和模型一起滚动。
+- 模型搜索与筛选工具栏到达滚动区顶部后吸顶。
+- 具体重置日期与趋势按需展开,余额和告警保持可见。
+- 支持深浅色、矮窗口、搜索与模型开关演示。
+
+这是设计参考,不是运行中的客户端。客户端保留原有管理菜单、显示/停用语义、模型分组、定价标记和供应商专属操作;不采用设计稿中的简化批量按钮。
+
+## 客户端验证边界
+
+实际 `ProvidersSection` / `UnifiedModelList` / `QuotaHoverCard` 的渲染结果使用模拟账号和模型在 Chromium 中检查过深浅色与矮窗口:身份留在滚动区外,工具栏吸顶,用量和模型共用滚动位置。此验证不涵盖 Electron 登录、网络刷新或真实账号操作。
+
+组件回归覆盖多个供应商适配器、模型深链、多配额窗口、明细展开/收起、余额、限额告警和过期数据提示。
diff --git a/docs/design-previews/provider-compact-scroll/index.html b/docs/design-previews/provider-compact-scroll/index.html
new file mode 100644
index 0000000000..75add23d2b
--- /dev/null
+++ b/docs/design-previews/provider-compact-scroll/index.html
@@ -0,0 +1,731 @@
+<!doctype html>
+<html lang="zh-CN">
+ <meta charset="utf-8" /><meta
+ name="viewport"
+ content="width=device-width,initial-scale=1"
+ /><title>模型供应商 · 紧凑布局预览</title
+ ><style>
+ :root {
+ color-scheme: light;
+ --surface: #f8f8f6;
+ --card: #fff;
+ --line: #dededb;
+ --text: #262626;
+ --muted: #777773;
+ --chip: #ededeb;
+ --hover: #f2f2ef;
+ --on: #505153;
+ --knob: #fff;
+ --green: #28ac61;
+ --focus: #707070;
+ }
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ margin: 0;
+ background: var(--surface);
+ color: var(--text);
+ font:
+ 14px Inter,
+ -apple-system,
+ BlinkMacSystemFont,
+ "Segoe UI",
+ sans-serif;
+ }
+ body.dark {
+ color-scheme: dark;
+ --surface: #1f1f1e;
+ --card: #2c2c2a;
+ --line: #444441;
+ --text: #e5e5e3;
+ --muted: #aaa9a4;
+ --chip: #3c3c3a;
+ --hover: #353533;
+ --on: #bdbdb8;
+ --knob: #2c2c2a;
+ --green: #55c886;
+ --focus: #bbb;
+ }
+ button,
+ input,
+ select {
+ font: inherit;
+ color: inherit;
+ }
+ button {
+ cursor: pointer;
+ background: transparent;
+ border: 1px solid var(--line);
+ border-radius: 9999px;
+ min-height: 32px;
+ padding: 4px 14px;
+ }
+ button:hover {
+ background: var(--hover);
+ }
+ button:focus-visible,
+ input:focus-visible,
+ summary:focus-visible {
+ outline: 2px solid var(--focus);
+ outline-offset: 3px;
+ }
+ h1 {
+ font-size: 18px;
+ font-weight: 600;
+ margin: 0 0 8px;
+ }
+ h2 {
+ font-size: 14px;
+ font-weight: 600;
+ margin: 0;
+ }
+ .muted {
+ color: var(--muted);
+ }
+ .reviewbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 10px 28px;
+ border-bottom: 1px solid var(--line);
+ font-size: 12px;
+ }
+ .reviewbar strong {
+ font-weight: 600;
+ }
+ .reviewbar .spacer {
+ flex: 1;
+ }
+ .page {
+ padding: 24px 28px 20px;
+ max-width: 1440px;
+ margin: auto;
+ }
+ .intro {
+ margin: 0 0 20px;
+ color: var(--muted);
+ }
+ .panel {
+ display: flex;
+ height: calc(100dvh - 166px);
+ min-height: 380px;
+ background: var(--card);
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ overflow: hidden;
+ }
+ .rail {
+ width: 224px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ border-right: 1px solid var(--line);
+ }
+ .railbody {
+ padding: 12px 8px;
+ overflow: auto;
+ flex: 1;
+ }
+ .railcaption {
+ font-size: 12px;
+ color: var(--muted);
+ padding: 6px 12px 12px;
+ }
+ .provider {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 10px 12px;
+ min-height: 48px;
+ border-radius: 8px;
+ }
+ .provider.active {
+ background: var(--hover);
+ }
+ .provider .name {
+ flex: 1;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-weight: 500;
+ }
+ .provider .count {
+ font-size: 12px;
+ color: var(--muted);
+ white-space: nowrap;
+ }
+ .dot {
+ width: 6px;
+ height: 6px;
+ background: var(--green);
+ border-radius: 50%;
+ }
+ .mark {
+ width: 28px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ font-size: 22px;
+ }
+ .railfoot {
+ padding: 10px;
+ border-top: 1px solid var(--line);
+ }
+ .railfoot button {
+ width: 100%;
+ border-style: dashed;
+ }
+ .detail {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ }
+ .identity {
+ padding: 16px 20px;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-shrink: 0;
+ border-bottom: 1px solid var(--line);
+ min-height: 76px;
+ }
+ .identity .mark {
+ height: 36px;
+ width: 36px;
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ }
+ .identitytext {
+ flex: 1;
+ }
+ .identityname {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 16px;
+ font-weight: 500;
+ }
+ .badge {
+ font-size: 12px;
+ font-weight: 400;
+ border: 1px solid var(--line);
+ border-radius: 9999px;
+ padding: 2px 8px;
+ color: var(--muted);
+ }
+ .subtitle {
+ font-size: 12px;
+ color: var(--muted);
+ margin-top: 4px;
+ }
+ .status {
+ font-size: 12px;
+ color: var(--muted);
+ white-space: nowrap;
+ }
+ .iconbtn {
+ width: 32px;
+ padding: 0;
+ border: 0;
+ }
+ .scroll {
+ overflow: auto;
+ flex: 1;
+ min-height: 0;
+ scrollbar-gutter: stable;
+ overscroll-behavior: contain;
+ }
+ .usage {
+ padding: 16px 20px;
+ border-bottom: 1px solid var(--line);
+ }
+ .usageline {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ flex-wrap: wrap;
+ }
+ .meter {
+ height: 6px;
+ background: var(--chip);
+ border-radius: 9999px;
+ width: 160px;
+ overflow: hidden;
+ }
+ .meter span {
+ display: block;
+ width: 98%;
+ height: 100%;
+ background: var(--muted);
+ border-radius: inherit;
+ }
+ .balance {
+ border-left: 1px solid var(--line);
+ padding-left: 16px;
+ font-size: 12px;
+ color: var(--muted);
+ }
+ .remaining {
+ font-weight: 500;
+ }
+ .reset {
+ font-size: 12px;
+ color: var(--muted);
+ }
+ details {
+ margin-top: 8px;
+ font-size: 12px;
+ color: var(--muted);
+ }
+ summary {
+ cursor: pointer;
+ display: list-item;
+ width: fit-content;
+ min-height: 24px;
+ line-height: 24px;
+ }
+ details p {
+ margin: 8px 0;
+ line-height: 1.6;
+ }
+ .toolbar {
+ position: sticky;
+ top: 0;
+ z-index: 2;
+ background: var(--card);
+ padding: 12px 20px;
+ border-bottom: 1px solid var(--line);
+ }
+ .tooltop,
+ .toolbottom {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .tooltop {
+ margin-bottom: 10px;
+ }
+ .tooltop .muted {
+ font-size: 12px;
+ }
+ .grow {
+ flex: 1;
+ }
+ .tabs {
+ display: flex;
+ gap: 2px;
+ }
+ .tab {
+ border: 0;
+ color: var(--muted);
+ padding: 4px 12px;
+ }
+ .tab.active {
+ background: var(--chip);
+ color: var(--text);
+ font-weight: 500;
+ }
+ .search {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ border: 1px solid var(--line);
+ border-radius: 9999px;
+ padding: 0 12px;
+ width: 210px;
+ height: 32px;
+ color: var(--muted);
+ }
+ input {
+ background: transparent;
+ border: 0;
+ outline: none;
+ width: 100%;
+ min-width: 0;
+ font-size: 13px;
+ }
+ .models {
+ padding: 8px 20px 24px;
+ }
+ .group {
+ padding: 14px 0 6px;
+ font-size: 12px;
+ color: var(--muted);
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ min-height: 48px;
+ border-radius: 8px;
+ padding: 0 8px;
+ }
+ .row:hover {
+ background: var(--hover);
+ }
+ .row .modelname {
+ font-weight: 500;
+ }
+ .row .kind {
+ font-size: 11px;
+ color: var(--muted);
+ border: 1px solid var(--line);
+ border-radius: 9999px;
+ padding: 2px 6px;
+ }
+ .switch {
+ width: 44px;
+ min-width: 44px;
+ height: 32px;
+ border: 0;
+ padding: 6px 3px;
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ }
+ .switch:hover {
+ background: transparent;
+ }
+ .track {
+ width: 36px;
+ height: 20px;
+ border-radius: 9999px;
+ background: var(--muted);
+ padding: 2px;
+ display: block;
+ }
+ .knob {
+ display: block;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: var(--knob);
+ }
+ [aria-checked="true"] .track {
+ background: var(--on);
+ }
+ [aria-checked="true"] .knob {
+ transform: translateX(16px);
+ }
+ .empty {
+ padding: 32px;
+ color: var(--muted);
+ text-align: center;
+ }
+ .hint {
+ font-size: 12px;
+ color: var(--muted);
+ margin-top: 10px;
+ }
+ .short .panel {
+ height: 440px;
+ }
+ .short .page {
+ padding-top: 16px;
+ }
+ @media (max-width: 800px) {
+ .page {
+ padding: 16px;
+ }
+ .rail {
+ width: 180px;
+ }
+ .count {
+ display: none;
+ }
+ .reviewbar {
+ padding: 8px 16px;
+ }
+ .reviewbar .explain {
+ display: none;
+ }
+ .usageline {
+ gap: 8px;
+ }
+ .meter {
+ width: 100px;
+ }
+ .balance {
+ border: 0;
+ padding: 0;
+ }
+ .identity {
+ flex-wrap: wrap;
+ }
+ .search {
+ width: 160px;
+ }
+ .panel {
+ height: calc(100dvh - 158px);
+ }
+ }
+ @media (max-width: 560px) {
+ .rail {
+ width: 60px;
+ }
+ .rail .name,
+ .railcaption,
+ .railfoot,
+ .rail .dot {
+ display: none;
+ }
+ .provider {
+ padding: 10px 0;
+ justify-content: center;
+ }
+ .identity {
+ padding: 12px;
+ }
+ .usage,
+ .toolbar {
+ padding: 12px;
+ }
+ .models {
+ padding: 4px 8px;
+ }
+ .status {
+ display: none;
+ }
+ .toolbottom {
+ flex-wrap: wrap;
+ }
+ .search {
+ width: 100%;
+ }
+ }
+ </style>
+ <body>
+ <div class="reviewbar">
+ <strong>设计预览</strong
+ ><span class="explain muted">紧凑额度 · 统一滚动 · 模型工具栏吸顶</span
+ ><span class="spacer"></span><button id="short">矮窗口</button
+ ><button id="theme">深色模式</button>
+ </div>
+ <main class="page">
+ <h1>模型供应商</h1>
+ <p class="intro">
+ 选择模型时的来源。每个来源提供它支持的模型与计费方式。
+ </p>
+ <div class="panel">
+ <aside class="rail">
+ <div class="railbody">
+ <div class="railcaption">拖动排序</div>
+ <div id="providers"></div>
+ <div class="railcaption" style="margin-top: 20px">
+ 检测到本机 CLI
+ </div>
+ <div class="provider muted">
+ <span class="mark">AⅠ</span><span class="name">Anthropic</span>
+ </div>
+ </div>
+ <div class="railfoot"><button disabled>+ 添加供应商</button></div>
+ </aside>
+ <section class="detail">
+ <header class="identity">
+ <span class="mark">◎</span>
+ <div class="identitytext">
+ <div class="identityname">
+ OpenAI <span class="badge">ChatGPT Pro</span>
+ </div>
+ <div class="subtitle">本机 Codex 账号 · [email protected]</div>
+ </div>
+ <span class="status">✓ 已连接</span><button disabled>断开</button
+ ><button class="iconbtn" disabled aria-label="更多操作">•••</button>
+ </header>
+ <div class="scroll" id="scroll">
+ <section class="usage">
+ <div class="usageline">
+ <span>周限</span><span class="remaining">剩余 98%</span>
+ <div
+ class="meter"
+ role="meter"
+ aria-label="周限剩余"
+ aria-valuenow="98"
+ aria-valuemin="0"
+ aria-valuemax="100"
+ >
+ <span></span>
+ </div>
+ <span class="reset">6天 8小时后重置</span
+ ><span class="grow"></span
+ ><span class="balance">0.00 credits · 余额已耗尽</span>
+ </div>
+ <details>
+ <summary>额度详情</summary>
+ <p>
+ ChatGPT Pro · 周限于 9月22日 00:35 重置<br />按当前平均速度偏慢(粗略趋势)<br />Credits
+ 余额:0.00 · 余额已耗尽
+ </p>
+ </details>
+ </section>
+ <div class="toolbar">
+ <div class="tooltop">
+ <h2>模型</h2>
+ <span class="muted" id="selected"></span
+ ><span class="grow"></span
+ ><button
+ id="reset"
+ class="iconbtn"
+ title="重置演示"
+ aria-label="重置演示"
+ >
+ ↻</button
+ ><button id="manage">全部启用</button>
+ </div>
+ <div class="toolbottom">
+ <div class="tabs" role="tablist" aria-label="模型类型">
+ <button
+ class="tab active"
+ role="tab"
+ aria-selected="true"
+ data-tab="all"
+ >
+ 全部</button
+ ><button
+ class="tab"
+ role="tab"
+ aria-selected="false"
+ data-tab="chat"
+ >
+ 对话</button
+ ><button
+ class="tab"
+ role="tab"
+ aria-selected="false"
+ data-tab="image"
+ >
+ 图像
+ </button>
+ </div>
+ <span class="grow"></span
+ ><label class="search"
+ >⌕
+ <input
+ id="search"
+ type="search"
+ aria-label="搜索模型"
+ placeholder="搜索模型"
+ /></label>
+ </div>
+ </div>
+ <div class="models" id="models"></div>
+ </div>
+ </section>
+ </div>
+ <div class="hint">
+ 演示数据。试试在额度区向下滚动、展开额度详情、搜索模型或切换开关;不会修改真实设置。
+ </div>
+ </main>
+ <script>
+ const providers = [
+ ["◒", "Cindy AI", 72],
+ ["◎", "OpenAI", 13],
+ ["◎", "OpenAI · 工作", 16],
+ ["◎", "OpenAI · 备用", 16],
+ ["◎", "OpenAI · API", 16],
+ ["𝕏", "xAI", 14],
+ ["♧", "Ollama", 1],
+ ];
+ document.querySelector("#providers").innerHTML = providers
+ .map(
+ (p, i) =>
+ `<div class="provider ${i === 1 ? "active" : ""}"><span class="mark">${p[0]}</span><span class="name">${p[1]}</span><span class="count">${p[2]} 个模型</span><i class="dot" ${i === 6 ? 'style="background:var(--line)"' : ""}></i></div>`,
+ )
+ .join("");
+ const names = [
+ "GPT-5.6",
+ "GPT-5.6 Sol",
+ "GPT-5.6 Terra",
+ "GPT-5.6 Luna",
+ "GPT Image 2",
+ "GPT-5.6 Cyber",
+ "GPT-5.5 Pro",
+ "GPT-5.5",
+ "GPT-5.4 Pro",
+ "GPT-5.4-Nano",
+ "GPT-5.4-Mini",
+ "GPT-5.4",
+ "GPT-5.3 Codex Spark",
+ ];
+ let enabled = names.map((_, i) => i < 5),
+ tab = "all";
+ function render() {
+ let q = document.querySelector("#search").value.toLowerCase();
+ let html = "",
+ count = 0;
+ for (const state of [true, false]) {
+ const ids = names
+ .map((n, i) => i)
+ .filter(
+ (i) =>
+ enabled[i] === state &&
+ names[i].toLowerCase().includes(q) &&
+ (tab === "all" || (tab === "image") === (i === 4)),
+ );
+ if (!ids.length) continue;
+ html += `<div class="group">${state ? "已启用" : "未启用"} ${ids.length}</div>`;
+ for (const i of ids) {
+ count++;
+ html += `<div class="row"><span class="mark muted">◎</span><span class="modelname">${names[i]}</span>${i === 4 ? '<span class="kind">图像</span>' : ""}<button class="switch" role="switch" aria-label="${names[i]}" aria-checked="${enabled[i]}" data-i="${i}"><span class="track"><span class="knob"></span></span></button></div>`;
+ }
+ }
+ document.querySelector("#models").innerHTML =
+ html || '<div class="empty">没有匹配的模型</div>';
+ document.querySelector("#selected").textContent =
+ `已选 ${enabled.filter(Boolean).length} 个`;
+ document.querySelector("#manage").textContent = enabled.every(Boolean)
+ ? "全部停用"
+ : "全部启用";
+ }
+ document.querySelector("#models").onclick = (e) => {
+ const b = e.target.closest("[data-i]");
+ if (!b) return;
+ let i = +b.dataset.i;
+ enabled[i] = !enabled[i];
+ render();
+ document
+ .querySelector(`[data-i="${i}"]`)
+ ?.focus({ preventScroll: true });
+ };
+ document.querySelectorAll("[data-tab]").forEach(
+ (b) =>
+ (b.onclick = () => {
+ tab = b.dataset.tab;
+ document.querySelectorAll("[data-tab]").forEach((t) => {
+ t.classList.toggle("active", t === b);
+ t.setAttribute("aria-selected", t === b);
+ });
+ render();
+ }),
+ );
+ document.querySelector("#search").oninput = render;
+ document.querySelector("#manage").onclick = () => {
+ enabled.fill(!enabled.every(Boolean));
+ render();
+ };
+ document.querySelector("#reset").onclick = () => {
+ enabled = names.map((_, i) => i < 5);
+ document.querySelector("#search").value = "";
+ document.querySelector('[data-tab="all"]').click();
+ document.querySelector("#scroll").scrollTop = 0;
+ };
+ document.querySelector("#theme").onclick = (e) => {
+ document.body.classList.toggle("dark");
+ e.target.textContent = document.body.classList.contains("dark")
+ ? "浅色模式"
+ : "深色模式";
+ };
+ document.querySelector("#short").onclick = (e) => {
+ document.body.classList.toggle("short");
+ e.target.textContent = document.body.classList.contains("short")
+ ? "自适应窗口"
+ : "矮窗口";
+ };
+ render();
+ </script>
+ </body>
+</html>
diff --git a/docs/product-rules/provider-settings.md b/docs/product-rules/provider-settings.md
index aee409e59a..3dfae442bb 100644
--- a/docs/product-rules/provider-settings.md
+++ b/docs/product-rules/provider-settings.md
@@ -62,9 +62,9 @@ API 接入、Cindy AI 与本地模型服务。本文定义统一合同;当前
## 4. 用量与扩展区域
-订阅用量或账户资产放在顶部下方固定区域,与身份行分层;各供应商只提供数据和必要的专属操作。
+供应商身份行固定;下方说明、订阅用量、账户资产与模型列表共用一个滚动区域,模型搜索和筛选工具行滚到顶部后吸顶。切换连接后回到新连接顶部;模型深链仍定位目标行。各供应商只提供数据和必要的专属操作。
配额、余额、重置时间保持各自真实含义,不为外观一致而虚构不存在的数据。
-设置页复用用量卡片的嵌入呈现:各窗口分别显示进度条、剩余百分比、重置倒计时与已有趋势提示;设置页面空间充足时额外保留具体重置日期,紧凑用量卡片优先倒计时;不再维护纯文字摘要。只返回周窗口时仍完整显示,套餐已知而窗口缺失时保留套餐信息。
+设置页复用用量卡片的紧凑嵌入呈现:各窗口默认以一行显示名称、进度条、剩余百分比与重置倒计时,窄窗口可换行。具体重置日期、趋势和窗口明细通过「用量明细」展开;余额、限额告警与数据过期提示保持可见。套餐在身份行已有展示时不重复占行;只返回周窗口时仍显示该窗口,套餐已知而窗口缺失时保留套餐信息。浮层用量卡片仍保留原有呈现。
OpenAI、Claude 和 Grok 的订阅连接都按连接 ID 读取,不按品牌名共用账号缓存;套餐名称与用量卡片共用格式化规则,不把模型专属促销额度当成整个账号的额度。
所有限额窗口和供应商摘要统一显示剩余百分比(100 减已用,限制在 0–100),
进度条填充及无障碍数值同步显示剩余;告警与节奏仍依据实际消耗计算。