Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
feat(desktop): 显示百炼 Token Plan 个人版月度余量 (makecindy#15896)
Signed-off-by: xuzini-xzn <xuzini@xd.com>
  • Loading branch information
xuzini-xzn authored Dec 5, 2026
commit 8549fc7371bcbdf94a5527049484eb7b2de03492
15 changes: 15 additions & 0 deletions apps/desktop/scripts/fixtures/unified-model-rail/ui-page.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export default {
cases: {
'uploaded-icon': { about: 'Uploaded SVG palette follows the selected source background and the idle theme', data: { customIcon } },
default: { about: '「全部」视图:联合列表 + 侧栏 rail 全格' },
'bailian-personal': { about: 'Bailian Personal monthly quota and countdown in the picker source details and rail' },
'custom-ids': { about: '#10253: custom models with near-identical names and long IDs differing only at the end' },
'custom-ids-legacy': { about: '#10253: the same custom IDs in the single-engine provider list' },
recent: { about: '「最近」视图:三态 Fast 载体(`ultrafast`/`true`)的条目后缀原样保留' },
Expand All @@ -21,6 +22,20 @@ export default {
},
async check(page, ui) {
await page.getByRole('listbox', { name: await ui.t('newChat.modelSelector.modelListAria') }).waitFor();
if (ui.case === 'bailian-personal') {
const rail = page.locator('[data-rail-item="provider:fixture-bailian"]');
await rail.locator('[data-weekly-remaining="77"]').waitFor();
await page.locator('[data-rail-item="all"]').click();
const details = page.locator('[data-model-source-details]').filter({ hasText: '77%' });
await details.waitFor();
const duration = `12${await ui.t('todaySpend.unit.day')} 3${await ui.t('todaySpend.unit.hour')}`;
assert.ok((await details.textContent()).includes(duration));
assert.ok((await rail.getAttribute('aria-description')).includes(await ui.t('quotaCard.monthlyLabel')));
await rail.hover();
await page.getByRole('tooltip').getByText(await ui.t('quotaCard.resetIn', { duration }), { exact: true }).waitFor({ state: 'attached' });
await ui.capture('monthly-quota');
return;
}
if (ui.case === 'cindy-brands') {
// 2026-11-30 user decision: a source holding models of many makers gets a second-level menu on top of its list —
// pills, icons only, the chosen one spelled out. Maker pills appear only inside that source's cell;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,28 @@ function SharedFavoritesFixture() {
/></main>;
}

const bailianProvider: ProviderView = {
id: 'fixture-bailian', name: '阿里云百炼 Token Plan', source: 'user',
agents: ['codex'], auth: { method: 'apiKey' }, access: { kind: 'api' }, connected: true,
routing: { codex: {
upstream: 'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
authStrategy: 'api-key-header',
catalogPresetId: 'aliyun-bailian-token-plan-cn', usagePresetId: 'aliyun-bailian-token-plan-cn',
} },
models: { codex: [{ id: 'qwen4-max', name: 'Qwen4 Max', contextWindow: 200000, efforts: [] }] },
};

function BailianQuotaFixture() {
return <main className="p-4"><UnifiedModelPanel
providers={[bailianProvider]} scope="draft" providerUsage={{ deviceId: null }}
query="" sourceVersion="fixture" isVisible={() => true}
selected={{ providerId: bailianProvider.id, modelId: 'qwen4-max' }}
liveAgentKind="codex" agentFastModeCapable={() => false} priceOf={() => null}
providerLabel={() => bailianProvider.name} effortLabelOf={(_agent, effort) => effort}
onSelect={() => {}}
/></main>;
}

function Fixture({ scenario }: { scenario: string }) {
const { t } = useTranslation();
const gateway = scenario.startsWith('cindy-');
Expand Down Expand Up @@ -251,6 +273,15 @@ void mountPage({
return { maker: {
getModelContextLimit: async () => ({ limit: 272000, isCustomized: false }),
onProvidersChanged: subscription('providersChanged'),
...(ctx.case === 'bailian-personal' ? {
fetchProviderAccountUsage: async () => ({
status: 'ready', stale: false,
snapshot: {
kind: 'bailian-personal-quota', usedPercent: 23,
resetsAt: Date.now() + (12 * 24 + 3) * 3_600_000, fetchedAt: Date.now(),
},
}),
} : {}),
// agent 级 Fast 能力:useAgentCapabilities → electronAPI.maker.getCapabilities;
// 缺了它 unifiedAgentFastCapable 恒 false,行速度同样会被折掉。
getCapabilities: async () => ({
Expand All @@ -274,5 +305,6 @@ void mountPage({
},
} } : {}) };
},
render: ctx => ctx.case === 'share-favorite-recovery' ? <SharedFavoritesFixture /> : <Fixture scenario={ctx.case} />,
render: ctx => ctx.case === 'share-favorite-recovery' ? <SharedFavoritesFixture />
: ctx.case === 'bailian-personal' ? <BailianQuotaFixture /> : <Fixture scenario={ctx.case} />,
});
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ vi.mock('react-i18next', () => ({
? '每周'
: key === 'todaySpend.unit.hour'
? '小时'
: key === 'quotaCard.monthlyLabel'
? '月度配额'
: key,
i18n: { language: 'en' },
}),
Expand Down Expand Up @@ -95,6 +97,84 @@ afterEach(() => {
});

describe('provider weekly quota identity and windows', () => {
// Unit/jsdom: the IPC snapshot reaches both picker surfaces, without treating
// a monthly reset as a week or borrowing the local account on a remote device.
it('shows Bailian Personal monthly quota in the source details and rail only while current and local', async () => {
vi.useFakeTimers();
const now = Date.UTC(2026, 11, 6);
vi.setSystemTime(now);
reads.codex.mockReturnValue({ snapshot: null });
const preset = 'aliyun-bailian-token-plan-cn';
const personal = provider('bailian-picker-test', {
source: 'user', auth: { method: 'apiKey' }, access: { kind: 'api' },
routing: { codex: {
upstream: 'https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1',
authStrategy: 'api-key-header', catalogPresetId: preset, usagePresetId: preset,
} },
});
const fetchProviderAccountUsage = vi.fn().mockResolvedValue({
status: 'ready', stale: false,
snapshot: { kind: 'bailian-personal-quota', usedPercent: 23, resetsAt: now + 2 * 3_600_000, fetchedAt: now },
});
vi.stubGlobal('electronAPI', { maker: { fetchProviderAccountUsage } });
const picker = (p: ProviderView, deviceId: string | null) => (
<ModelSourceUsageProvider providers={[p]} scope={{ deviceId }}>
<UnifiedModelRail items={[{ kind: 'provider', providerId: p.id }]} active={{ kind: 'all' }}
providers={[p]} providerLabel={() => 'Bailian'} onSelect={() => {}} providerUsage={{ deviceId }} />
<ModelSourceDetails providerId={p.id} label="Bailian" modelId="qwen" />
</ModelSourceUsageProvider>
);
try {
const view = render(picker(personal, 'self-a'));
await act(async () => {});
// Each surface reads the existing IPC. The host shares one pending/cache entry.
expect(fetchProviderAccountUsage.mock.calls).toEqual(Array(2).fill([{
providerId: personal.id, forceRefresh: false,
}]));
const details = () => view.container.querySelector('[data-model-source-details]');
const rail = () => view.container.querySelector('[data-rail-item="provider:bailian-picker-test"]');
expect(details()?.textContent).toBe('Bailian·2小时 77%');
expect(rail()?.querySelector('[data-weekly-remaining="77"]')).not.toBeNull();
expect(rail()?.getAttribute('aria-description')).toBe('月度配额 · 剩余 77%');

vi.setSystemTime(now + 2 * 3_600_000);
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
expect(details()?.textContent).toBe('Bailian');
expect(rail()?.querySelector('[data-weekly-remaining]')).toBeNull();

fetchProviderAccountUsage.mockClear();
view.rerender(picker(personal, 'remote-peer'));
await act(async () => {});
expect(fetchProviderAccountUsage).not.toHaveBeenCalled();
expect(details()?.textContent).toBe('Bailian');
expect(rail()?.querySelector('[data-weekly-remaining]')).toBeNull();

const team = 'aliyun-bailian-token-plan-team-cn';
view.rerender(picker({ ...personal, routing: { codex: {
...personal.routing.codex!, catalogPresetId: team, usagePresetId: team,
} } }, null));
await act(async () => {});
expect(fetchProviderAccountUsage).not.toHaveBeenCalled();
expect(rail()?.querySelector('[data-weekly-remaining]')).toBeNull();

view.unmount();
const routeId = 'sroute:auto:bailian-picker-test';
const route = render(<UnifiedModelRail
items={[{ kind: 'provider', providerId: routeId }]} active={{ kind: 'all' }}
providers={[{ ...personal, id: routeId }]}
providerLabel={() => 'Automatic route'} onSelect={() => {}} providerUsage={{ deviceId: null }}
routeUsageMember={() => ({ provider: personal, agentDeviceId: null })}
/>);
await act(async () => {});
expect(fetchProviderAccountUsage).not.toHaveBeenCalled();
expect(route.container.querySelector('[data-weekly-remaining]')).toBeNull();
} finally {
cleanup();
vi.unstubAllGlobals();
vi.useRealTimers();
}
});

// User report / unit: created OpenAI providers lost rail and summary quotas
// when the connection ID was treated as the account kind. Existing pool
// fixtures carry both Claude and Codex windows, hiding that mismatch;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
import { QUOTA_TEXT_COLOR_CLASSES, quotaSeverity } from '../status/QuotaBar';
import { useOptionalAuthDeviceId } from '@/contexts/AuthContext';
import { providerAccountLabel } from '@/lib/providerDisplayName';
import { isBailianPersonalProviderView } from '@/lib/providerAccountUsageView';
import { ModelPickerAccountProvider, useModelPickerAccount } from './ModelPickerAccount';

type SourceUsage = ProviderUsageSnapshots & {
Expand All @@ -57,17 +58,17 @@ function SourceUsageProvider({
children: ReactNode;
}) {
const parent = useContext(UsageContext);
const { source, codex, claude, xai, kimi, opencodeGo, stepFunPlan, mimoTokenPlan } = useProviderUsageSnapshots(
const { source, codex, claude, xai, kimi, opencodeGo, stepFunPlan, mimoTokenPlan, bailianPersonal } = useProviderUsageSnapshots(
provider,
scope,
{ web: true },
);
const value = useMemo(() => {
if (!source) return parent;
const next = new Map(parent);
next.set(usageKey, { source, codex, claude, xai, kimi, opencodeGo, stepFunPlan, mimoTokenPlan });
next.set(usageKey, { source, codex, claude, xai, kimi, opencodeGo, stepFunPlan, mimoTokenPlan, bailianPersonal });
return next;
}, [parent, usageKey, source, codex, claude, xai, kimi, opencodeGo, stepFunPlan, mimoTokenPlan]);
}, [parent, usageKey, source, codex, claude, xai, kimi, opencodeGo, stepFunPlan, mimoTokenPlan, bailianPersonal]);
return <UsageContext.Provider value={value}>{children}</UsageContext.Provider>;
}

Expand Down Expand Up @@ -127,9 +128,10 @@ export function ModelSourceUsageProvider({
const source = providerWeeklyQuotaSource(provider);
const stepFun = isStepFunPlanProvider(provider);
const mimo = isMimoTokenPlanUsageProviderView(provider);
if (provider.auth?.method !== 'oauth' && source !== 'kimi' && source !== 'opencode-go' && !stepFun && !mimo)
const bailian = (readerDeviceId === null || readerDeviceId === selfDeviceId) && isBailianPersonalProviderView(provider);
if (provider.auth?.method !== 'oauth' && source !== 'kimi' && source !== 'opencode-go' && !stepFun && !mimo && !bailian)
return content;
if ((!source && !stepFun && !mimo) || provider.subscriptionAccount?.reconnectRequired) return content;
if ((!source && !stepFun && !mimo && !bailian) || provider.subscriptionAccount?.reconnectRequired) return content;
return (
<SourceUsageProvider
key={`${readerDeviceId ?? ''}:${provider.id}:${row.id}`}
Expand Down Expand Up @@ -209,6 +211,19 @@ function modelSourceQuota(
: [],
};
}
if (usage.source === 'bailian-personal') {
const snapshot = usage.bailianPersonal;
return {
plan: null,
windows: snapshot && (snapshot.resetsAt === null || snapshot.resetsAt > nowMs)
? [{
labelKey: 'quotaCard.monthlyLabel',
usedPercent: snapshot.usedPercent,
resetsAt: snapshot.resetsAt === null ? null : snapshot.resetsAt / 1000,
}]
: [],
};
}
if (usage.source === 'opencode-go')
return {
plan: null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,7 @@ export function UnifiedModelRail({
onClick={() => onSelect(item)}
disabled={interactionDisabled}
provider={providerUsage ? (isSourceRoute ? (routeMember && !routeMemberShare ? routeMember.provider : undefined) : usageProvider) : undefined}
routeQuota={isSourceRoute}
pluginEngine={pluginEngineQuotaTarget}
usageDeviceId={
routeMember
Expand Down Expand Up @@ -361,6 +362,7 @@ interface RailButtonProps {
onClick: () => void;
disabled: boolean;
provider?: ProviderView;
routeQuota?: boolean;
pluginEngine?: { key: string; deviceId: string | null };
usageDeviceId: string | null;
shareDeviceId?: string | null;
Expand Down Expand Up @@ -523,7 +525,9 @@ function SharedProviderQuotaButton(props: RailButtonProps & { shareDeviceId: str
function ProviderQuotaButton(props: RailButtonProps & { provider: ProviderView }) {
const { t } = useTranslation();
const pickerAccount = useModelPickerAccount(props.provider.id, props.usageDeviceId);
const usage = useProviderUsageSnapshots(props.provider, { deviceId: props.usageDeviceId ?? null });
const usage = useProviderUsageSnapshots(props.provider, { deviceId: props.usageDeviceId ?? null }, {
allowBailianPersonal: !props.routeQuota,
});
const quota = useWeeklyQuotaFromSnapshots(usage);
const pool = useModelPoolQuota(props.provider.id, props.usageDeviceId, usage);
const identity = pool?.isPool
Expand Down Expand Up @@ -591,13 +595,16 @@ function RailButtonView({
mixed?.left != null
? mixed.pool?.shortThrottled === true
: pool?.shortThrottled === true || ownQuota?.shortThrottled === true;
const quotaLabelKey = mixed?.left == null && ownQuota?.monthly
? 'quotaCard.monthlyLabel'
: ownQuota?.planAllowance && mixed?.left == null ? 'providerAccountUsage.stepFunPlan.allowance' : 'quotaCard.weeklyLabel';
const quotaLabel = pool?.hasAccountDetails
? pool.label
: remaining === null
? null
: showDualLayer && isShortThrottled
? `${t('quotaCard.remainingPercent', { percent: remaining })} · ${t('modelGroups.balance.cycleRemaining', { percent: cycleRemaining })}`
: `${t(ownQuota?.planAllowance && mixed?.left == null ? 'providerAccountUsage.stepFunPlan.allowance' : 'quotaCard.weeklyLabel')} · ${t('quotaCard.remainingPercent', { percent: remaining })}`;
: `${t(quotaLabelKey)} · ${t('quotaCard.remainingPercent', { percent: remaining })}`;
const reset = formatQuotaResetCountdown(quota?.resetsAt, nowMs, t);
// 供应商组:组名不带某一台的账号,账号跟在「当前在 {电脑} 上运行」后面。
const displayLabel = groupNote ? label : providerAccountLabel(label, accountIdentity, t, customProviderName);
Expand Down
Loading