🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(settings): add Resources group with a subscription accounts list (#21547)
Arvin Xue6274a16f5ec
diff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex 3a403598610..1e3143c558e 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -330,6 +330,11 @@ export const agentQuotaRouter = router({),),+ /** Agent runs in flight on an account — who is spending it right now. */+ listActiveRuns: quotaProcedure+ .input(z.object({ accountId: z.string() }))+ .query(async ({ ctx, input }) => ctx.quotaService.listActiveRuns(input.accountId)),+// ── load balancing ───────────────────────────────────────────────────────resolveAccountLoads: quotaProcedure.input(z.object({ accountIds: z.array(z.string()) }))diff --git a/apps/server/src/services/agentQuota/__tests__/index.test.ts b/apps/server/src/services/agentQuota/__tests__/index.test.tsindex 6a4502ff6dc..38ed865022a 100644--- a/apps/server/src/services/agentQuota/__tests__/index.test.ts+++ b/apps/server/src/services/agentQuota/__tests__/index.test.ts@@ -10,7 +10,7 @@ import {AgentQuotaUsageLedgerModel,AgentQuotaWindowModel,} from '@/database/models/agentQuota';-import { agents, users } from '@/database/schemas';+import { agentOperations, agents, users } from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';import { QuotaBindingRole } from '@/database/types/agentQuota';@@ -441,6 +441,35 @@ describe('AgentQuotaService.recordUsage', () => {});});+describe('AgentQuotaService.listActiveRuns', () => {+ it('only counts runs that billed the account within the last six hours', async () => {+ const now = Date.parse('2026-07-12T12:00:00Z');+ const account = await new AgentProviderAccountModel(serverDB, userId).create({+ provider: 'claude-code',+ });+ await serverDB.insert(agents).values({ id: 'active-run-agent', userId });+ await serverDB.insert(agentOperations).values([+ { agentId: 'active-run-agent', id: 'op-fresh', status: 'running', userId },+ // Left `running` by a client that never reported back.+ { agentId: 'active-run-agent', id: 'op-stale', status: 'running', userId },+ ]);+ const turn = (operationId: string, at: number) =>+ ledger.append({+ accountId: account.id,+ occurredAt: new Date(at),+ operationId,+ provider: 'claude-code',+ });+ await turn('op-fresh', now - HOUR);+ await turn('op-stale', now - 7 * HOUR);++ const runs = await service.listActiveRuns(account.id, now);++ expect(runs.map((run) => run.operationId)).toEqual(['op-fresh']);+ expect(runs[0].lastTurnAt).toBe(now - HOUR);+ });+});+describe('Codex quota persistence', () => {it('preserves provider bucket names and monthly durations through DB reads and projection', async () => {const capturedAt = Date.now();diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.tsindex cfa0fd9aac9..b937e5948f5 100644--- a/apps/server/src/services/agentQuota/index.ts+++ b/apps/server/src/services/agentQuota/index.ts@@ -79,6 +79,9 @@ interface SelectAccountOptions {runnableExternalAccountIds?: string[];}+/** How recently a run must have billed an account to count as running on it. */+const ACTIVE_RUN_WINDOW_MS = 6 * 60 * 60 * 1000;+export class AgentQuotaService {private accounts: AgentProviderAccountModel;private bindings: AgentAccountBindingModel;@@ -364,6 +367,21 @@ export class AgentQuotaService {}));};+ /**+ * Agent runs still in flight on an account. Only runs that billed it within+ * the last few hours count: an operation left `running` by a crashed client+ * would otherwise stay listed forever.+ */+ listActiveRuns = async (accountId: string, now: number = Date.now()) => {+ const rows = await this.ledger.listActiveRuns(accountId, new Date(now - ACTIVE_RUN_WINDOW_MS));++ return rows.map((row) => ({+ ...row,+ lastTurnAt: row.lastTurnAt.getTime(),+ startedAt: row.startedAt?.getTime() ?? null,+ }));+ };+/** Build the LB load view for a set of accounts from their latest readings. */resolveAccountLoads = async (accountIds: string[],diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex bff0d592042..8750fcc5762 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1768,6 +1768,39 @@"storageOverage.usage.estimatedCharge": "Est. Cycle Charge","storageOverage.usage.incurredCharge": "Incurred This Cycle","storageOverage.usage.overage": "Overage",+ "subscriptionAccounts.actions.rename": "Rename",+ "subscriptionAccounts.actions.viewDetails": "Details",+ "subscriptionAccounts.activeRuns.empty": "No agent is using this account right now.",+ "subscriptionAccounts.activeRuns.loadFailed": "Couldn't load the agents using this account.",+ "subscriptionAccounts.activeRuns.running": "Running",+ "subscriptionAccounts.activeRuns.title": "Agents using it now",+ "subscriptionAccounts.activeRuns.untitledAgent": "Untitled agent",+ "subscriptionAccounts.activeRuns.untitledTopic": "Untitled topic",+ "subscriptionAccounts.activeRuns.waiting": "Waiting",+ "subscriptionAccounts.columns.account": "Account",+ "subscriptionAccounts.columns.plan": "Plan",+ "subscriptionAccounts.columns.quota": "Quota",+ "subscriptionAccounts.columns.rotation": "Balancing",+ "subscriptionAccounts.columns.status": "Status",+ "subscriptionAccounts.empty.desc": "Sign in to Claude Code, Codex or Kimi Code on a connected device. The account appears here once it reports its quota.",+ "subscriptionAccounts.empty.title": "No subscription accounts yet",+ "subscriptionAccounts.filter.all": "All",+ "subscriptionAccounts.filterEmpty": "No account matches the filter.",+ "subscriptionAccounts.loadFailed": "Couldn't load subscription accounts",+ "subscriptionAccounts.meter.session": "5-hour",+ "subscriptionAccounts.meter.weekly": "Weekly",+ "subscriptionAccounts.refresh": "Refresh",+ "subscriptionAccounts.renamePlaceholder": "Account name",+ "subscriptionAccounts.rotationTooltip": "Include in automatic balancing",+ "subscriptionAccounts.searchPlaceholder": "Search accounts…",+ "subscriptionAccounts.status.available": "Available · updated {{time}}",+ "subscriptionAccounts.status.disabled": "Out of rotation",+ "subscriptionAccounts.status.exhausted": "Used up · resets {{time}}",+ "subscriptionAccounts.status.exhaustedNoReset": "Used up",+ "subscriptionAccounts.status.noData": "No quota reported yet",+ "subscriptionAccounts.summary": "{{inRotation}} of {{count}} in rotation",+ "subscriptionAccounts.updateFailed": "Couldn't update the account. Try again.",+ "subscriptionAccounts.usageTitle": "Usage history","sync.device.deviceName.hint": "Add a name for easy identification","sync.device.deviceName.placeholder": "Enter device name","sync.device.deviceName.title": "Device Name",@@ -1899,6 +1932,7 @@"tab.skillIntegration": "Integration","tab.stats": "Analytics","tab.storage": "Storage",+ "tab.subscriptionAccounts": "Subscription Accounts","tab.sync": "Cloud Sync","tab.systemTools": "System Tools","tab.tools": "Tools",@@ -3677,6 +3711,7 @@"workspaceSetting.devices.unknownEnroller": "an unknown member","workspaceSetting.group.admin": "Admin","workspaceSetting.group.agent": "Agent",+ "workspaceSetting.group.resource": "Resources","workspaceSetting.group.workspace": "Workspace","workspaceSetting.labels.actions.archive": "Archive","workspaceSetting.labels.actions.create": "New label",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 10bf054c50f..00e80cc96ab 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1768,6 +1768,39 @@"storageOverage.usage.estimatedCharge": "预计本账期费用","storageOverage.usage.incurredCharge": "本账期已产生费用","storageOverage.usage.overage": "超额",+ "subscriptionAccounts.actions.rename": "重命名",+ "subscriptionAccounts.actions.viewDetails": "查看详情",+ "subscriptionAccounts.activeRuns.empty": "当前没有助理在使用这个账号",+ "subscriptionAccounts.activeRuns.loadFailed": "正在使用的助理加载失败",+ "subscriptionAccounts.activeRuns.running": "执行中",+ "subscriptionAccounts.activeRuns.title": "正在使用的助理",+ "subscriptionAccounts.activeRuns.untitledAgent": "未命名助理",+ "subscriptionAccounts.activeRuns.untitledTopic": "未命名话题",+ "subscriptionAccounts.activeRuns.waiting": "等待中",+ "subscriptionAccounts.columns.account": "账号",+ "subscriptionAccounts.columns.plan": "套餐",+ "subscriptionAccounts.columns.quota": "额度",+ "subscriptionAccounts.columns.rotation": "参与分配",+ "subscriptionAccounts.columns.status": "状态",+ "subscriptionAccounts.empty.desc": "在已连接的设备上登录 Claude Code、Codex 或 Kimi Code,账号上报额度后会出现在这里。",+ "subscriptionAccounts.empty.title": "还没有订阅账号",+ "subscriptionAccounts.filter.all": "全部",+ "subscriptionAccounts.filterEmpty": "没有符合筛选条件的账号",+ "subscriptionAccounts.loadFailed": "订阅账号加载失败",+ "subscriptionAccounts.meter.session": "5 小时",+ "subscriptionAccounts.meter.weekly": "本周",+ "subscriptionAccounts.refresh": "刷新",+ "subscriptionAccounts.renamePlaceholder": "账号名称",+ "subscriptionAccounts.rotationTooltip": "参与自动均衡",+ "subscriptionAccounts.searchPlaceholder": "搜索账号…",+ "subscriptionAccounts.status.available": "可用 · {{time}}更新",+ "subscriptionAccounts.status.disabled": "已停用,不参与分配",+ "subscriptionAccounts.status.exhausted": "已用尽 · {{time}}恢复",+ "subscriptionAccounts.status.exhaustedNoReset": "已用尽",+ "subscriptionAccounts.status.noData": "暂无额度数据",+ "subscriptionAccounts.summary": "共 {{count}} 个账号 · {{inRotation}} 个参与分配",+ "subscriptionAccounts.updateFailed": "账号更新失败,请重试",+ "subscriptionAccounts.usageTitle": "用量记录","sync.device.deviceName.hint": "添加名称以便于识别","sync.device.deviceName.placeholder": "请输入设备名称","sync.device.deviceName.title": "设备名称",@@ -1899,6 +1932,7 @@"tab.skillIntegration": "集成","tab.stats": "数据统计","tab.storage": "数据存储",+ "tab.subscriptionAccounts": "订阅账号","tab.sync": "云端同步","tab.systemTools": "系统工具","tab.tools": "工具",@@ -3677,6 +3711,7 @@"workspaceSetting.devices.unknownEnroller": "未知成员","workspaceSetting.group.admin": "管理","workspaceSetting.group.agent": "智能体",+ "workspaceSetting.group.resource": "资源","workspaceSetting.group.workspace": "工作区","workspaceSetting.labels.actions.archive": "归档","workspaceSetting.labels.actions.create": "新建标签",diff --git a/packages/database/src/models/__tests__/agentQuota.test.ts b/packages/database/src/models/__tests__/agentQuota.test.tsindex f1a1c3cb61e..2c54ad71a42 100644--- a/packages/database/src/models/__tests__/agentQuota.test.ts+++ b/packages/database/src/models/__tests__/agentQuota.test.ts@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';import { getTestDB } from '../../core/getTestDB';-import { agentProviderAccounts, agents, users } from '../../schemas';+import { agentOperations, agentProviderAccounts, agents, topics, users } from '../../schemas';import type { LobeChatDatabase } from '../../type';import {AgentAccountBindingModel,@@ -420,6 +420,45 @@ describe('quota data tables — range reads', () => {expect(Number(rows[0].costUsd)).toBe(2);});+ it('listActiveRuns lists in-flight runs that billed the account, once each, newest first', async () => {+ const account = await accounts.create({ provider: 'claude-code' });+ const other = await accounts.create({ provider: 'claude-code' });+ await serverDB.update(agents).set({ title: 'Builder' }).where(eq(agents.id, agentId));+ await serverDB.insert(topics).values({ id: 'quota-topic', title: 'Fix login', userId });+ await serverDB.insert(agentOperations).values([+ { agentId, id: 'op-running', status: 'running', topicId: 'quota-topic', userId },+ { agentId, id: 'op-waiting', status: 'waiting_for_human', userId },+ { agentId, id: 'op-done', status: 'done', userId },+ { agentId, id: 'op-old', status: 'running', userId },+ { agentId, id: 'op-other', status: 'running', userId },+ ]);+ const turn = (operationId: string, at: string, accountId = account.id) =>+ ledger.append({+ accountId,+ occurredAt: new Date(at),+ operationId,+ provider: 'claude-code',+ });+ await turn('op-running', '2026-07-12T10:00:00Z');+ await turn('op-running', '2026-07-12T11:00:00Z');+ await turn('op-waiting', '2026-07-12T10:30:00Z');+ await turn('op-done', '2026-07-12T10:45:00Z'); // settled+ await turn('op-old', '2026-07-11T10:00:00Z'); // before the cutoff+ await turn('op-other', '2026-07-12T10:50:00Z', other.id); // another account++ const runs = await ledger.listActiveRuns(account.id, new Date('2026-07-12T00:00:00Z'));++ expect(runs.map((r) => r.operationId)).toEqual(['op-running', 'op-waiting']);+ expect(runs[0]).toMatchObject({+ agentId,+ agentTitle: 'Builder',+ status: 'running',+ topicId: 'quota-topic',+ topicTitle: 'Fix login',+ });+ expect(runs[0].lastTurnAt).toEqual(new Date('2026-07-12T11:00:00Z'));+ });+it('sumCostUsd returns 0 when nothing matches', async () => {expect(await ledger.sumCostUsd('00000000-0000-0000-0000-000000000000', new Date(0), new Date()),diff --git a/packages/database/src/models/agentQuota.ts b/packages/database/src/models/agentQuota.tsindex c8b0d0c0be1..64dcc0e842c 100644--- a/packages/database/src/models/agentQuota.ts+++ b/packages/database/src/models/agentQuota.ts@@ -1,4 +1,4 @@-import { and, desc, eq, gte, lte, sql } from 'drizzle-orm';+import { and, desc, eq, gte, inArray, lte, sql } from 'drizzle-orm';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';@@ -12,11 +12,14 @@ import type {} from '../schemas';import {agentAccountBindings,+ agentOperations,agentProviderAccounts,agentQuotaCalibrations,agentQuotaSnapshots,agentQuotaUsageLedger,agentQuotaWindows,+ agents,+ topics,} from '../schemas';import type { LobeChatDatabase } from '../type';import {@@ -403,6 +406,50 @@ export class AgentQuotaUsageLedgerModel {).orderBy(agentQuotaUsageLedger.occurredAt);+ /**+ * Agent runs still in flight that billed this account since `since` — who is+ * spending it right now. A run is listed once, under its newest turn. `idle`+ * is left out: a run that has not started has not billed anything.+ */+ listActiveRuns = async (accountId: string, since: Date) => {+ const lastTurnAt = sql`max(${agentQuotaUsageLedger.occurredAt})`.mapWith(+ agentQuotaUsageLedger.occurredAt,+ );++ return this.db+ .select({+ agentAvatar: agents.avatar,+ agentBackgroundColor: agents.backgroundColor,+ agentId: agentOperations.agentId,+ agentTitle: agents.title,+ lastTurnAt,+ operationId: agentOperations.id,+ startedAt: agentOperations.startedAt,+ status: agentOperations.status,+ topicId: agentOperations.topicId,+ topicTitle: topics.title,+ })+ .from(agentQuotaUsageLedger)+ .innerJoin(agentOperations, eq(agentQuotaUsageLedger.operationId, agentOperations.id))+ .leftJoin(agents, eq(agentOperations.agentId, agents.id))+ .leftJoin(topics, eq(agentOperations.topicId, topics.id))+ .where(+ and(+ this.mine(),+ eq(agentQuotaUsageLedger.accountId, accountId),+ gte(agentQuotaUsageLedger.occurredAt, since),+ inArray(agentOperations.status, [+ 'running',+ 'waiting_for_async_tool',+ 'waiting_for_client',+ 'waiting_for_human',+ ]),+ ),+ )+ .groupBy(agentOperations.id, agents.id, topics.id)+ .orderBy(desc(lastTurnAt));+ };+/** Total USD spent on an account within [from, to). */sumCostUsd = async (accountId: string, from: Date, to: Date): Promise<number> => {const [r] = await this.dbdiff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex fd906b41c4b..db398bb4c84 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4602,4 +4602,40 @@ When I am ___, I need ___'This directory is on the public drive. Rebuild it on your personal drive first.','environments.instances.rebuildPersonalTag': 'Needs rebuild on personal drive','environments.instances.rebuildPersonalTagHint': 'Hidden on the public drive and no longer used.',+ 'subscriptionAccounts.actions.rename': 'Rename',+ 'subscriptionAccounts.actions.viewDetails': 'Details',+ 'subscriptionAccounts.activeRuns.empty': 'No agent is using this account right now.',+ 'subscriptionAccounts.activeRuns.loadFailed': "Couldn't load the agents using this account.",+ 'subscriptionAccounts.activeRuns.running': 'Running',+ 'subscriptionAccounts.activeRuns.title': 'Agents using it now',+ 'subscriptionAccounts.activeRuns.untitledAgent': 'Untitled agent',+ 'subscriptionAccounts.activeRuns.untitledTopic': 'Untitled topic',+ 'subscriptionAccounts.activeRuns.waiting': 'Waiting',+ 'subscriptionAccounts.filterEmpty': 'No account matches the filter.',+ 'subscriptionAccounts.searchPlaceholder': 'Search accounts…',+ 'subscriptionAccounts.usageTitle': 'Usage history',+ 'subscriptionAccounts.columns.account': 'Account',+ 'subscriptionAccounts.columns.plan': 'Plan',+ 'subscriptionAccounts.columns.quota': 'Quota',+ 'subscriptionAccounts.columns.rotation': 'Balancing',+ 'subscriptionAccounts.columns.status': 'Status',+ 'subscriptionAccounts.empty.desc':+ 'Sign in to Claude Code, Codex or Kimi Code on a connected device. The account appears here once it reports its quota.',+ 'subscriptionAccounts.empty.title': 'No subscription accounts yet',+ 'subscriptionAccounts.filter.all': 'All',+ 'subscriptionAccounts.loadFailed': "Couldn't load subscription accounts",+ 'subscriptionAccounts.meter.session': '5-hour',+ 'subscriptionAccounts.meter.weekly': 'Weekly',+ 'subscriptionAccounts.refresh': 'Refresh',+ 'subscriptionAccounts.renamePlaceholder': 'Account name',+ 'subscriptionAccounts.rotationTooltip': 'Include in automatic balancing',+ 'subscriptionAccounts.status.available': 'Available · updated {{time}}',+ 'subscriptionAccounts.status.disabled': 'Out of rotation',+ 'subscriptionAccounts.status.exhausted': 'Used up · resets {{time}}',+ 'subscriptionAccounts.status.exhaustedNoReset': 'Used up',+ 'subscriptionAccounts.status.noData': 'No quota reported yet',+ 'subscriptionAccounts.summary': '{{inRotation}} of {{count}} in rotation',+ 'subscriptionAccounts.updateFailed': "Couldn't update the account. Try again.",+ 'tab.subscriptionAccounts': 'Subscription Accounts',+ 'workspaceSetting.group.resource': 'Resources',};diff --git a/src/features/SubscriptionAccounts/AccountDetailPanel.tsx b/src/features/SubscriptionAccounts/AccountDetailPanel.tsxnew file mode 100644index 00000000000..1a3ef894e16--- /dev/null+++ b/src/features/SubscriptionAccounts/AccountDetailPanel.tsx@@ -0,0 +1,190 @@+'use client';++import { DEFAULT_AVATAR } from '@lobechat/const';+import { ActionIcon, Avatar, Empty, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { XIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import SkeletonBar from '@/components/Skeleton/Bar';+import QuotaCalendar from '@/features/AgentQuotaCalendar/QuotaCalendarModal';+import RunningGlyph from '@/features/Home/components/RunningGlyph';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useClientDataSWR } from '@/libs/swr';+import { agentQuotaService } from '@/services/agentQuota';+import type { QuotaAccount } from '@/store/agentQuota';++import { accountDisplayName } from './AccountRow';+import type { SubscriptionProvider } from './accountView';++/** Runs move on quickly; poll while the panel is open so the list stays current. */+const ACTIVE_RUNS_REFRESH_MS = 15_000;++const styles = stylex.create({+ avatar: { position: 'relative', display: 'flex', flex: 'none' },+ runningBadge: {+ position: 'absolute',+ insetInlineEnd: '-3px',+ insetBlockEnd: '-3px',+ display: 'flex',+ padding: '1px',+ borderRadius: '50%',+ backgroundColor: cssVar.colorBgContainer,+ },+ // Sits beside the list and squeezes it rather than covering it, and stays in+ // view while the list scrolls under the settings header.+ panel: {+ position: 'sticky',+ top: 0,+ alignSelf: 'flex-start',+ flexShrink: 0,+ width: 'min(480px, 40%)',+ maxHeight: 'calc(100vh - 120px)',+ overflowY: 'auto',+ paddingInlineStart: '20px',+ borderInlineStartWidth: '1px',+ borderInlineStartStyle: 'solid',+ borderInlineStartColor: cssVar.colorBorderSecondary,+ },+ run: {+ paddingBlock: '8px',+ paddingInline: '8px',+ borderRadius: cssVar.borderRadius,+ cursor: 'pointer',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ },+});++type Account = QuotaAccount & { provider: SubscriptionProvider };++const ActiveRuns = ({ accountId }: { accountId: string }) => {+ const { t } = useTranslation('setting');+ const navigate = useWorkspaceAwareNavigate();+ const { data, error, isLoading } = useClientDataSWR(+ ['agentQuota.activeRuns', accountId],+ () => agentQuotaService.listActiveRuns(accountId),+ { refreshInterval: ACTIVE_RUNS_REFRESH_MS },+ );++ if (isLoading)+ return (+ <Flexbox gap={4}>+ <SkeletonBar height={44} />+ <SkeletonBar height={44} />+ </Flexbox>+ );+ if (error && !data)+ return (+ <Text fontSize={13} type={'secondary'}>+ {t('subscriptionAccounts.activeRuns.loadFailed')}+ </Text>+ );+ if (!data?.length)+ return (+ <Text fontSize={13} type={'secondary'}>+ {t('subscriptionAccounts.activeRuns.empty')}+ </Text>+ );++ return (+ <Flexbox gap={2}>+ {data.map((run) => (+ <Flexbox+ horizontal+ align={'center'}+ gap={12}+ key={run.operationId}+ role={'link'}+ tabIndex={0}+ {...stylex.props(styles.run)}+ onClick={() =>+ run.agentId &&+ navigate(run.topicId ? `/agent/${run.agentId}/${run.topicId}` : `/agent/${run.agentId}`)+ }+ >+ {/* A run that is executing carries the shared running ring on its+ avatar; a waiting one says so in text on the right. */}+ <span {...stylex.props(styles.avatar)}>+ <Avatar+ avatar={run.agentAvatar || DEFAULT_AVATAR}+ background={run.agentBackgroundColor ?? undefined}+ size={24}+ />+ {run.status === 'running' && (+ <span+ aria-label={t('subscriptionAccounts.activeRuns.running')}+ role={'img'}+ {...stylex.props(styles.runningBadge)}+ >+ <RunningGlyph size={10} />+ </span>+ )}+ </span>+ {/* One line, agent · topic: the pair is what identifies a run. */}+ <Flexbox horizontal align={'baseline'} flex={1} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis style={{ flex: 'none', maxWidth: '50%' }} weight={500}>+ {run.agentTitle || t('subscriptionAccounts.activeRuns.untitledAgent')}+ </Text>+ <Text style={{ flex: 'none' }} type={'secondary'}>+ ·+ </Text>+ <Text ellipsis type={'secondary'}>+ {run.topicTitle || t('subscriptionAccounts.activeRuns.untitledTopic')}+ </Text>+ </Flexbox>+ {run.status !== 'running' && (+ <Text fontSize={12} style={{ flex: 'none' }} type={'secondary'}>+ {t('subscriptionAccounts.activeRuns.waiting')}+ </Text>+ )}+ </Flexbox>+ ))}+ </Flexbox>+ );+};++interface AccountDetailPanelProps {+ account: Account;+ onClose: () => void;+}++/**+ * The account's side panel: which agents are spending it right now, then its+ * usage history. It sits beside the list and narrows it instead of covering+ * it, so the admin can step through accounts with the list still in view.+ */+const AccountDetailPanel = ({ account, onClose }: AccountDetailPanelProps) => {+ const { t } = useTranslation('setting');+ const { t: tCommon } = useTranslation('common');++ return (+ <aside {...stylex.props(styles.panel)}>+ <Flexbox gap={20}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Text ellipsis fontSize={16} weight={600}>+ {accountDisplayName(account)}+ </Text>+ <ActionIcon icon={XIcon} size={'small'} title={tCommon('close')} onClick={onClose} />+ </Flexbox>+ <Flexbox gap={8}>+ <Text weight={500}>{t('subscriptionAccounts.activeRuns.title')}</Text>+ <ActiveRuns accountId={account.id} />+ </Flexbox>+ <Flexbox gap={8}>+ <Text weight={500}>{t('subscriptionAccounts.usageTitle')}</Text>+ {account.externalAccountId ? (+ <QuotaCalendar+ externalAccountId={account.externalAccountId}+ provider={account.provider}+ />+ ) : (+ <Empty description={t('subscriptionAccounts.status.noData')} />+ )}+ </Flexbox>+ </Flexbox>+ </aside>+ );+};++export default AccountDetailPanel;diff --git a/src/features/SubscriptionAccounts/AccountRow.tsx b/src/features/SubscriptionAccounts/AccountRow.tsxnew file mode 100644index 00000000000..d27b65f3dc5--- /dev/null+++ b/src/features/SubscriptionAccounts/AccountRow.tsx@@ -0,0 +1,380 @@+'use client';++import { ClaudeCode, Codex, Kimi } from '@lobehub/icons';+import {+ ActionIcon,+ DropdownMenu,+ Flexbox,+ Icon,+ Input,+ Switch,+ Text,+ toast,+ Tooltip,+} from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import dayjs from 'dayjs';+import { CheckIcon, MoreHorizontalIcon, PanelRightOpenIcon, PencilIcon, XIcon } from 'lucide-react';+import { type CSSProperties, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { formatPercent, usageLevel } from '@/features/DeviceManager/DeviceHealth/format';+import { usageTextColor } from '@/features/DeviceManager/DeviceHealth/shared';+import { UsageBar } from '@/features/DeviceManager/DeviceHealth/UsageMeter';+import { type QuotaAccount, useAgentQuotaStore } from '@/store/agentQuota';++import { type AccountStatus, deriveAccountView, type SubscriptionProvider } from './accountView';++/** Column widths shared by {@link AccountRow} and {@link AccountListHeader}. */+export const COLUMN_WIDTH = {+ account: 140,+ actions: 28,+ plan: 72,+ quota: 190,+ // Wider than the switch so it sits centered with clear space after the quota bars.+ rotation: 88,+ status: 120,+} as const;++/**+ * Narrowest the list may get before it scrolls sideways instead: every+ * column at its minimum, the 16px gaps between the seven columns and the row+ * padding. Below this the rotation switch and menu would clip.+ */+export const LIST_MIN_WIDTH =+ COLUMN_WIDTH.plan ++ COLUMN_WIDTH.quota ++ COLUMN_WIDTH.status ++ COLUMN_WIDTH.rotation ++ COLUMN_WIDTH.actions ++ COLUMN_WIDTH.account ++ 16 * 6 ++ 12 * 2;++const styles = stylex.create({+ presence: (color: string) => ({+ flex: 'none',+ width: '8px',+ height: '8px',+ borderRadius: '50%',+ backgroundColor: color,+ }),+ row: {+ display: 'flex',+ alignItems: 'center',+ gap: '16px',+ paddingBlock: '12px',+ paddingInline: '12px',+ borderRadius: cssVar.borderRadius,+ cursor: 'pointer',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ outline: { 'default': 'none', ':focus-visible': `2px solid ${cssVar.colorPrimary}` },+ },+ // The account whose panel is open.+ rowActive: { backgroundColor: cssVar.colorFillSecondary },+});++const PROVIDER_META: Record<+ SubscriptionProvider,+ { icon: (size: number) => ReactNode; name: string }+> = {+ 'claude-code': { icon: (size) => <ClaudeCode.Avatar size={size} />, name: 'Claude Code' },+ 'codex': { icon: (size) => <Codex.Avatar size={size} />, name: 'Codex' },+ 'kimi-code': { icon: (size) => <Kimi.Avatar size={size} />, name: 'Kimi Code' },+};++export const PROVIDER_NAME = Object.fromEntries(+ Object.entries(PROVIDER_META).map(([key, meta]) => [key, meta.name]),+) as Record<SubscriptionProvider, string>;++const STATUS_COLOR: Record<AccountStatus, string> = {+ available: cssVar.colorSuccess,+ disabled: cssVar.colorTextQuaternary,+ exhausted: cssVar.colorError,+ noData: cssVar.colorTextQuaternary,+};++export const accountDisplayName = (account: QuotaAccount) =>+ account.label || account.email || account.externalAccountId || account.id;++/** One window's usage: its label, the device page's segmented bar and the percentage, `—` before any reading. */+const WindowMeter = ({ label, value }: { label: string; value?: number }) => {+ const level = usageLevel(value);+ return (+ <Flexbox horizontal align={'center'} gap={8}>+ <Text+ fontSize={12}+ style={{ flex: 'none', whiteSpace: 'nowrap', width: 40 }}+ type={'secondary'}+ >+ {label}+ </Text>+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ <UsageBar height={8} value={value} />+ </Flexbox>+ <Text+ fontSize={12}+ type={level ? undefined : 'secondary'}+ style={{+ color: usageTextColor(level),+ flex: 'none',+ textAlign: 'end',+ whiteSpace: 'nowrap',+ width: 36,+ }}+ >+ {formatPercent(value)}+ </Text>+ </Flexbox>+ );+};++/** Column labels, aligned with {@link AccountRow} through {@link COLUMN_WIDTH}. */+export const AccountListHeader = () => {+ const { t } = useTranslation('setting');+ // Account and status share the spare width (2:1); the rest keep fixed widths.+ const label = (text: string, style: CSSProperties) => (+ <Text ellipsis fontSize={12} style={style} type={'secondary'}>+ {text}+ </Text>+ );++ return (+ <Flexbox horizontal align={'center'} gap={16} paddingInline={12} style={{ paddingBlock: 4 }}>+ {label(t('subscriptionAccounts.columns.account'), {+ flex: 2,+ minWidth: COLUMN_WIDTH.account,+ })}+ {label(t('subscriptionAccounts.columns.plan'), { flex: 'none', width: COLUMN_WIDTH.plan })}+ {label(t('subscriptionAccounts.columns.status'), { flex: 1, minWidth: COLUMN_WIDTH.status })}+ {label(t('subscriptionAccounts.columns.quota'), { flex: 'none', width: COLUMN_WIDTH.quota })}+ {label(t('subscriptionAccounts.columns.rotation'), {+ flex: 'none',+ textAlign: 'center',+ width: COLUMN_WIDTH.rotation,+ })}+ <span style={{ flex: 'none', width: COLUMN_WIDTH.actions }} />+ </Flexbox>+ );+};++interface AccountRowProps {+ account: QuotaAccount & { provider: SubscriptionProvider };+ /** This account's side panel is open. */+ active?: boolean;+ /** Open this account's side panel. */+ onOpen: () => void;+}++const AccountRow = ({ account, active, onOpen }: AccountRowProps) => {+ const { t } = useTranslation('setting');+ const { t: tCommon } = useTranslation('common');+ const [useFetchQuotaReadings, renameQuotaAccount, setQuotaAccountEnabled] = useAgentQuotaStore(+ (s) => [s.useFetchQuotaReadings, s.renameQuotaAccount, s.setQuotaAccountEnabled],+ );+ useFetchQuotaReadings(account.id);+ const readings = useAgentQuotaStore((s) => s.quotaReadingsMap[account.id]);+ const [busy, setBusy] = useState(false);+ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState('');++ const view = deriveAccountView(account, readings, Date.now());+ const meta = PROVIDER_META[account.provider];+ const name = accountDisplayName(account);+ // With a label set, the email moves to the subtitle so the account stays identifiable.+ const subtitle = [meta.name, account.label ? account.email : undefined]+ .filter(Boolean)+ .join(' · ');++ const run = async (fn: () => Promise<void>) => {+ setBusy(true);+ try {+ await fn();+ return true;+ } catch {+ toast.error(t('subscriptionAccounts.updateFailed'));+ return false;+ } finally {+ setBusy(false);+ }+ };++ const startEdit = () => {+ setDraft(account.label ?? '');+ setEditing(true);+ };+ const saveEdit = async () => {+ if (await run(() => renameQuotaAccount(account.id, draft.trim() || undefined)))+ setEditing(false);+ };++ const statusText = (() => {+ switch (view.status) {+ case 'disabled': {+ return t('subscriptionAccounts.status.disabled');+ }+ case 'exhausted': {+ return view.recoversAt+ ? t('subscriptionAccounts.status.exhausted', { time: dayjs(view.recoversAt).fromNow() })+ : t('subscriptionAccounts.status.exhaustedNoReset');+ }+ case 'noData': {+ return t('subscriptionAccounts.status.noData');+ }+ default: {+ return t('subscriptionAccounts.status.available', {+ time: dayjs(view.lastSyncedAt).fromNow(),+ });+ }+ }+ })();++ // Controls inside the row keep their clicks from opening the side panel.+ const stop = {+ onClick: (e: { stopPropagation: () => void }) => e.stopPropagation(),+ onKeyDown: (e: { stopPropagation: () => void }) => e.stopPropagation(),+ };++ return (+ <div+ {...stylex.props(styles.row, active && styles.rowActive)}+ aria-current={active || undefined}+ role={'button'}+ tabIndex={0}+ onClick={editing ? undefined : onOpen}+ onKeyDown={(e) => {+ if (e.key === 'Enter' && e.target === e.currentTarget) {+ e.preventDefault();+ onOpen();+ }+ }}+ >+ <Flexbox+ horizontal+ align={'center'}+ gap={12}+ // Out of rotation reads as dimmed, not hidden: the admin still sees what it holds.+ style={{+ flex: 2,+ minWidth: COLUMN_WIDTH.account,+ opacity: view.status === 'disabled' ? 0.55 : undefined,+ }}+ >+ <span style={{ display: 'flex', flex: 'none' }}>{meta.icon(28)}</span>+ <Flexbox gap={2} style={{ minWidth: 0 }}>+ {editing ? (+ <Flexbox horizontal align={'center'} gap={4} {...stop}>+ <Input+ autoFocus+ placeholder={account.email || t('subscriptionAccounts.renamePlaceholder')}+ size={'small'}+ style={{ flex: 1 }}+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onPressEnter={() => void saveEdit()}+ onKeyDown={(e) => {+ if (e.key === 'Escape') setEditing(false);+ }}+ />+ <ActionIcon+ disabled={busy}+ icon={CheckIcon}+ size={'small'}+ title={tCommon('save')}+ onClick={() => void saveEdit()}+ />+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={tCommon('cancel')}+ onClick={() => setEditing(false)}+ />+ </Flexbox>+ ) : (+ <Text ellipsis title={name} weight={500}>+ {name}+ </Text>+ )}+ <Text ellipsis fontSize={12} type={'secondary'}>+ {subtitle}+ </Text>+ </Flexbox>+ </Flexbox>++ <Text+ ellipsis+ fontSize={13}+ style={{ flex: 'none', width: COLUMN_WIDTH.plan }}+ type={account.planTier ? undefined : 'secondary'}+ >+ {account.planTier || '—'}+ </Text>++ <Flexbox+ horizontal+ align={'center'}+ gap={8}+ style={{ flex: 1, minWidth: COLUMN_WIDTH.status }}+ >+ <span aria-hidden {...stylex.props(styles.presence(STATUS_COLOR[view.status]))} />+ <Text ellipsis fontSize={12} title={statusText} type={'secondary'}>+ {statusText}+ </Text>+ </Flexbox>++ {/* Both windows stacked in one column, so the pair reads as one quota. */}+ <Flexbox gap={6} style={{ flex: 'none', width: COLUMN_WIDTH.quota }}>+ <WindowMeter+ label={t('subscriptionAccounts.meter.session')}+ value={view.session?.usedPercent}+ />+ <WindowMeter+ label={t('subscriptionAccounts.meter.weekly')}+ value={view.weekly?.usedPercent}+ />+ </Flexbox>++ <Flexbox+ horizontal+ justify={'center'}+ style={{ flex: 'none', width: COLUMN_WIDTH.rotation }}+ {...stop}+ >+ <Tooltip title={t('subscriptionAccounts.rotationTooltip')}>+ <Switch+ aria-label={t('subscriptionAccounts.rotationTooltip')}+ checked={account.enabled !== false}+ disabled={busy}+ size={'small'}+ onChange={(checked) => void run(() => setQuotaAccountEnabled(account.id, checked))}+ />+ </Tooltip>+ </Flexbox>++ <Flexbox horizontal style={{ flex: 'none', width: COLUMN_WIDTH.actions }} {...stop}>+ <DropdownMenu+ placement={'bottomRight'}+ items={[+ {+ icon: <Icon icon={PanelRightOpenIcon} />,+ key: 'details',+ label: t('subscriptionAccounts.actions.viewDetails'),+ onClick: onOpen,+ },+ {+ icon: <Icon icon={PencilIcon} />,+ key: 'rename',+ label: t('subscriptionAccounts.actions.rename'),+ onClick: startEdit,+ },+ ]}+ >+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={tCommon('more')} />+ </DropdownMenu>+ </Flexbox>+ </div>+ );+};++export default AccountRow;diff --git a/src/features/SubscriptionAccounts/accountView.test.ts b/src/features/SubscriptionAccounts/accountView.test.tsnew file mode 100644index 00000000000..884b7304999--- /dev/null+++ b/src/features/SubscriptionAccounts/accountView.test.ts@@ -0,0 +1,102 @@+import { describe, expect, it } from 'vitest';++import { deriveAccountView, matchesKeyword, sortAccounts } from './accountView';++const NOW = Date.UTC(2026, 9, 24, 12);+const HOUR = 60 * 60 * 1000;++const reading = (limitType: string, utilization: number, resetsAt: number | null, at = NOW) => ({+ capturedAt: at,+ limitType,+ resetsAt,+ scopeKey: '',+ utilization,+});++describe('deriveAccountView', () => {+ it('reports both windows and the newest sync time for an available account', () => {+ const view = deriveAccountView(+ { enabled: true },+ [+ reading('session', 30, NOW + HOUR, NOW - 2 * HOUR),+ reading('weekly_all', 40, NOW + 48 * HOUR),+ ],+ NOW,+ );++ expect(view.status).toBe('available');+ expect(view.session).toEqual({ resetsAt: NOW + HOUR, usedPercent: 30 });+ expect(view.weekly).toEqual({ resetsAt: NOW + 48 * HOUR, usedPercent: 40 });+ expect(view.lastSyncedAt).toBe(NOW);+ });++ it('marks a used-up window as exhausted and recovers at the latest blocking reset', () => {+ const view = deriveAccountView(+ { enabled: true },+ [reading('session', 100, NOW + HOUR), reading('weekly_all', 100, NOW + 24 * HOUR)],+ NOW,+ );++ expect(view.status).toBe('exhausted');+ expect(view.recoversAt).toBe(NOW + 24 * HOUR);+ });++ it('treats a used-up window that already rolled over as refilled', () => {+ const view = deriveAccountView(+ { enabled: true },+ [reading('weekly_all', 100, NOW - HOUR, NOW - 3 * HOUR)],+ NOW,+ );++ expect(view.status).toBe('available');+ expect(view.weekly).toEqual({ resetsAt: null, usedPercent: 0 });+ });++ it('keeps a disabled account disabled whatever its readings say', () => {+ const view = deriveAccountView(+ { enabled: false },+ [reading('weekly_all', 100, NOW + HOUR)],+ NOW,+ );++ expect(view.status).toBe('disabled');+ expect(view.weekly?.usedPercent).toBe(100);+ });++ it('reports no data before the account has any reading', () => {+ expect(deriveAccountView({ enabled: true }, undefined, NOW)).toEqual({+ lastSyncedAt: undefined,+ session: undefined,+ status: 'noData',+ weekly: undefined,+ });+ });+});++describe('sortAccounts', () => {+ it('lists accounts in rotation first, then by provider and name', () => {+ const sorted = sortAccounts([+ { email: '[email protected]', enabled: true, provider: 'codex' },+ { email: '[email protected]', enabled: false, provider: 'claude-code' },+ { email: '[email protected]', enabled: true, provider: 'claude-code' },+ { email: '[email protected]', enabled: true, label: null, provider: 'claude-code' },+ ]);++ expect(sorted.map((a) => a.email)).toEqual(['[email protected]', '[email protected]', '[email protected]', '[email protected]']);+ });+});++describe('matchesKeyword', () => {+ const account = { email: '[email protected]', label: 'Team Max', planTier: 'max' };++ it('matches the label, email or plan regardless of case', () => {+ expect(matchesKeyword(account, 'team')).toBe(true);+ expect(matchesKeyword(account, 'dev@example')).toBe(true);+ expect(matchesKeyword(account, 'MAX')).toBe(true);+ });++ it('keeps every account for a blank keyword and drops non-matches', () => {+ expect(matchesKeyword(account, ' ')).toBe(true);+ expect(matchesKeyword(account, 'codex')).toBe(false);+ });+});diff --git a/src/features/SubscriptionAccounts/accountView.ts b/src/features/SubscriptionAccounts/accountView.tsnew file mode 100644index 00000000000..3a8b2d7e490--- /dev/null+++ b/src/features/SubscriptionAccounts/accountView.ts@@ -0,0 +1,124 @@+import {+ isSessionLimit,+ isWeeklyAllLimit,+ type QuotaDisplayReading,+ toQuotaWindow,+} from '@lobechat/heterogeneous-agents/quota';++export type SubscriptionProvider = 'claude-code' | 'codex' | 'kimi-code';++export const SUBSCRIPTION_PROVIDERS: SubscriptionProvider[] = ['claude-code', 'codex', 'kimi-code'];++export const isSubscriptionProvider = (provider: string): provider is SubscriptionProvider =>+ (SUBSCRIPTION_PROVIDERS as string[]).includes(provider);++/** A limit is used up at this utilization — the load balancer's own threshold. */+const EXHAUSTED_PERCENT = 100;++export interface AccountWindowView {+ /** Window boundary of the live window; null once it rolled over or when unreported. */+ resetsAt: number | null;+ usedPercent: number;+}++export type AccountStatus = 'available' | 'disabled' | 'exhausted' | 'noData';++export interface AccountView {+ /** Newest reading time, so the card can say how fresh its numbers are. */+ lastSyncedAt?: number;+ /** When an exhausted account gets capacity back: the latest reset among its used-up windows. */+ recoversAt?: number;+ session?: AccountWindowView;+ status: AccountStatus;+ weekly?: AccountWindowView;+}++const newest = <T extends QuotaDisplayReading>(+ readings: T[],+ match: (reading: T) => boolean,+): T | undefined =>+ readings.reduce<T | undefined>(+ (found, reading) =>+ match(reading) && (!found || reading.capturedAt > found.capturedAt) ? reading : found,+ undefined,+ );++const windowOf = (reading: QuotaDisplayReading | undefined, now: number) => {+ if (!reading) return undefined;+ const window = toQuotaWindow(reading, now);+ return { resetsAt: window.resetsAt, usedPercent: window.usedPercent };+};++/**+ * One account card's state from its newest per-bucket readings. A window that+ * already rolled over reads as refilled, the same rule the chat quota panel and+ * the load balancer apply, so the card never paints an exhausted meter over a+ * quota that is free again.+ */+export const deriveAccountView = (+ account: { enabled?: boolean | null },+ readings: QuotaDisplayReading[] | undefined,+ now: number,+): AccountView => {+ const list = readings ?? [];+ const sessionReading = newest(list, isSessionLimit);+ const weeklyReading = newest(list, isWeeklyAllLimit);+ const session = windowOf(sessionReading, now);+ const weekly = windowOf(weeklyReading, now);+ const lastSyncedAt = list.length+ ? list.reduce((max, reading) => Math.max(max, reading.capturedAt), 0)+ : undefined;++ // A rolled-over window already reads 0% here, so only a live window can be used up.+ const exhausted = [session, weekly].filter(+ (window): window is AccountWindowView => !!window && window.usedPercent >= EXHAUSTED_PERCENT,+ );++ const base = { lastSyncedAt, session, weekly };++ if (account.enabled === false) return { ...base, status: 'disabled' };+ if (exhausted.length > 0) {+ const resets = exhausted+ .map((window) => window.resetsAt)+ .filter((value): value is number => value != null);+ return {+ ...base,+ recoversAt: resets.length ? Math.max(...resets) : undefined,+ status: 'exhausted',+ };+ }+ if (!session && !weekly) return { ...base, status: 'noData' };+ return { ...base, status: 'available' };+};++const PROVIDER_ORDER: Record<string, number> = { 'claude-code': 0, 'codex': 1, 'kimi-code': 2 };++/** Accounts in rotation first, then grouped by provider, then by name. */+export const sortAccounts = <+ T extends {+ email?: string | null;+ enabled?: boolean | null;+ label?: string | null;+ provider: string;+ },+>(+ accounts: T[],+): T[] =>+ [...accounts].sort(+ (a, b) =>+ Number(b.enabled !== false) - Number(a.enabled !== false) ||+ (PROVIDER_ORDER[a.provider] ?? 99) - (PROVIDER_ORDER[b.provider] ?? 99) ||+ (a.label || a.email || '').localeCompare(b.label || b.email || ''),+ );++/** Whether an account matches the search box: name, email or plan, case-insensitive. */+export const matchesKeyword = (+ account: { email?: string | null; label?: string | null; planTier?: string | null },+ keyword: string,+): boolean => {+ const needle = keyword.trim().toLowerCase();+ if (!needle) return true;+ return [account.label, account.email, account.planTier].some((field) =>+ field?.toLowerCase().includes(needle),+ );+};diff --git a/src/features/SubscriptionAccounts/index.tsx b/src/features/SubscriptionAccounts/index.tsxnew file mode 100644index 00000000000..2e68176515e--- /dev/null+++ b/src/features/SubscriptionAccounts/index.tsx@@ -0,0 +1,172 @@+'use client';++import { ActionIcon, Button, Empty, Flexbox, SearchBar, Select, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { RefreshCwIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import SkeletonBar from '@/components/Skeleton/Bar';+import { cacheScope } from '@/libs/replica';+import { agentQuotaSelectors, type QuotaAccount, useAgentQuotaStore } from '@/store/agentQuota';++import AccountDetailPanel from './AccountDetailPanel';+import AccountRow, { AccountListHeader, LIST_MIN_WIDTH, PROVIDER_NAME } from './AccountRow';+import {+ isSubscriptionProvider,+ matchesKeyword,+ sortAccounts,+ SUBSCRIPTION_PROVIDERS,+ type SubscriptionProvider,+} from './accountView';++type ProviderAccount = QuotaAccount & { provider: SubscriptionProvider };++const ALL = 'all';++/**+ * Every coding-agent subscription the workspace's devices have reported, as a+ * list with their live quota — the shared capacity agents are balanced onto.+ * Accounts register themselves when a CLI login reports quota; this page only+ * decides which of them stay in rotation and what they are called.+ */+const SubscriptionAccounts = () => {+ const { t } = useTranslation('setting');+ const useFetchQuotaAccounts = useAgentQuotaStore((s) => s.useFetchQuotaAccounts);+ const readQuotaReadings = useAgentQuotaStore((s) => s.readQuotaReadings);+ const { error, isValidating, revalidate } = useFetchQuotaAccounts();+ const [refreshing, setRefreshing] = useState(false);+ const scope = cacheScope.use();+ const confirmed = useAgentQuotaStore(agentQuotaSelectors.isAccountsConfirmed(scope));+ const loaded = useAgentQuotaStore(agentQuotaSelectors.accounts);+ const [provider, setProvider] = useState<SubscriptionProvider | typeof ALL>(ALL);+ const [keyword, setKeyword] = useState('');+ const [openId, setOpenId] = useState<string>();++ const accounts = sortAccounts(+ (loaded ?? []).filter((a): a is ProviderAccount => isSubscriptionProvider(a.provider)),+ );+ const present = SUBSCRIPTION_PROVIDERS.filter((p) => accounts.some((a) => a.provider === p));+ // A provider filter that no longer has accounts falls back to everything.+ const active = provider !== ALL && present.includes(provider) ? provider : ALL;+ const visible = accounts.filter(+ (a) => (active === ALL || a.provider === active) && matchesKeyword(a, keyword),+ );+ const openAccount = accounts.find((a) => a.id === openId);+ const inRotation = accounts.filter((a) => a.enabled !== false).length;++ // The meters read each account's own readings, which the list sync does not+ // touch: refreshing re-reads them too, or a newer sample would never show.+ const refresh = async () => {+ setRefreshing(true);+ try {+ await Promise.allSettled([+ revalidate(),+ ...accounts.map((account) => readQuotaReadings(account.id, { fresh: true })),+ ]);+ } finally {+ setRefreshing(false);+ }+ };++ // A hydrated empty list may be stale: only the server's answer settles "none yet".+ const settling = !confirmed && !error && accounts.length === 0;++ const body = settling ? (+ <Flexbox gap={4}>+ {Array.from({ length: 5 }, (_, i) => (+ <SkeletonBar height={56} key={i} radius={cssVar.borderRadius} />+ ))}+ </Flexbox>+ ) : error && accounts.length === 0 ? (+ // A failed load must not read as "no accounts" — they would look identical.+ <Flexbox align={'center'} gap={12} paddingBlock={40}>+ <Empty description={t('subscriptionAccounts.loadFailed')} />+ <Button onClick={() => void revalidate()}>{t('retry', { ns: 'common' })}</Button>+ </Flexbox>+ ) : accounts.length === 0 ? (+ <Empty+ description={t('subscriptionAccounts.empty.desc')}+ style={{ paddingBlock: 40 }}+ title={t('subscriptionAccounts.empty.title')}+ />+ ) : (+ // The settings pane hides horizontal overflow, so a narrow pane scrolls the+ // list sideways rather than clipping the switch and menu off the row.+ <div style={{ overflowX: 'auto' }}>+ <Flexbox gap={2} style={{ minWidth: LIST_MIN_WIDTH }}>+ <AccountListHeader />+ {visible.map((account) => (+ <AccountRow+ account={account}+ active={account.id === openId}+ key={account.id}+ onOpen={() => setOpenId(account.id)}+ />+ ))}+ {visible.length === 0 && (+ <Empty description={t('subscriptionAccounts.filterEmpty')} style={{ paddingBlock: 40 }} />+ )}+ </Flexbox>+ </div>+ );++ return (+ <Flexbox gap={16} width={'100%'}>+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'} wrap={'wrap'}>+ <Text fontSize={13} type={'secondary'}>+ {accounts.length > 0 &&+ t('subscriptionAccounts.summary', { count: accounts.length, inRotation })}+ </Text>+ {/* Filters sit on the right as a dropdown: the provider list grows with+ every coding plan we support, which a segmented control cannot hold. */}+ <Flexbox horizontal align={'center'} gap={8}>+ <SearchBar+ allowClear+ placeholder={t('subscriptionAccounts.searchPlaceholder')}+ style={{ width: 240 }}+ value={keyword}+ variant={'filled'}+ onChange={(e) => setKeyword(e.target.value)}+ />+ <Select+ style={{ minWidth: 168 }}+ value={active}+ variant={'filled'}+ options={[+ {+ label: `${t('subscriptionAccounts.filter.all')} · ${accounts.length}`,+ value: ALL,+ },+ ...present.map((p) => ({+ label: `${PROVIDER_NAME[p]} · ${accounts.filter((a) => a.provider === p).length}`,+ value: p,+ })),+ ]}+ onChange={(value) => setProvider(value as SubscriptionProvider | typeof ALL)}+ />+ <ActionIcon+ icon={RefreshCwIcon}+ loading={isValidating || refreshing}+ title={t('subscriptionAccounts.refresh')}+ onClick={() => void refresh()}+ />+ </Flexbox>+ </Flexbox>+ <Flexbox horizontal gap={20} style={{ minWidth: 0 }}>+ <Flexbox flex={1} style={{ minWidth: 0 }}>+ {body}+ </Flexbox>+ {openAccount && (+ <AccountDetailPanel+ account={openAccount}+ key={openAccount.id}+ onClose={() => setOpenId(undefined)}+ />+ )}+ </Flexbox>+ </Flexbox>+ );+};++export default SubscriptionAccounts;diff --git a/src/features/Workspace/workspaceAwarePath.ts b/src/features/Workspace/workspaceAwarePath.tsindex c8792d5c33e..12cf33644db 100644--- a/src/features/Workspace/workspaceAwarePath.ts+++ b/src/features/Workspace/workspaceAwarePath.ts@@ -75,6 +75,7 @@ export const WORKSPACE_SETTINGS_TABS: ReadonlySet<string> = new Set([// deep-links still land on `/:slug/settings/statistics`.'stats','storage',+ 'subscription-accounts','teams','usage',]);diff --git a/src/features/WorkspaceSetting/Layout.tsx b/src/features/WorkspaceSetting/Layout.tsxindex eb00624fcd3..db8d3333f81 100644--- a/src/features/WorkspaceSetting/Layout.tsx+++ b/src/features/WorkspaceSetting/Layout.tsx@@ -39,15 +39,20 @@ const COMPACT_HEADER_TABS = new Set<string>([WorkspaceSettingsTabs.ServiceModel,WorkspaceSettingsTabs.Stats,WorkspaceSettingsTabs.Storage,+ WorkspaceSettingsTabs.SubscriptionAccounts,WorkspaceSettingsTabs.Teams,WorkspaceSettingsTabs.Usage,]);/*** Tabs whose content spans the full pane instead of the centered 1024 column —- * card grids that add columns as the pane widens (Devices).+ * card grids that add columns as the pane widens (Devices), and the+ * subscription account list, whose usage columns need the room.*/-const FULL_WIDTH_TABS = new Set<string>([WorkspaceSettingsTabs.Devices]);+const FULL_WIDTH_TABS = new Set<string>([+ WorkspaceSettingsTabs.Devices,+ WorkspaceSettingsTabs.SubscriptionAccounts,+]);const outletContainerStyle: CSSProperties = { overflow: 'hidden', position: 'relative' };diff --git a/src/features/WorkspaceSetting/SideBar/Body.tsx b/src/features/WorkspaceSetting/SideBar/Body.tsxindex 7259a81d718..c3d5eaa9ed5 100644--- a/src/features/WorkspaceSetting/SideBar/Body.tsx+++ b/src/features/WorkspaceSetting/SideBar/Body.tsx@@ -46,6 +46,7 @@ const Body = memo(() => {defaultValue={[WorkspaceSettingsGroupKey.Account,WorkspaceSettingsGroupKey.General,+ WorkspaceSettingsGroupKey.Resource,WorkspaceSettingsGroupKey.Subscription,WorkspaceSettingsGroupKey.Agent,WorkspaceSettingsGroupKey.Admin,diff --git a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx b/src/features/WorkspaceSetting/hooks/useCategory.test.tsxindex 530ce701cfc..9cc4b3cf983 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.test.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.test.tsx@@ -108,6 +108,38 @@ describe('workspace settings useCategory', () => {]);});+ it('groups devices, subscription accounts and environments under Resources', () => {+ const { result } = renderHook(() => useWorkspaceSettingCategory(), { wrapper });+ const keys = result.current.map((group) => group.key);+ const resourceGroup = result.current.find(+ (group) => group.key === WorkspaceSettingsGroupKey.Resource,+ );+ const generalGroup = result.current.find(+ (group) => group.key === WorkspaceSettingsGroupKey.General,+ );++ expect(keys.indexOf(WorkspaceSettingsGroupKey.Resource)).toBe(+ keys.indexOf(WorkspaceSettingsGroupKey.General) + 1,+ );+ expect(resourceGroup?.items.map((item) => item.key)).toEqual([+ WorkspaceSettingsTabs.Devices,+ WorkspaceSettingsTabs.SubscriptionAccounts,+ WorkspaceSettingsTabs.Environments,+ ]);+ expect(generalGroup?.items.map((item) => item.key)).not.toContain(+ WorkspaceSettingsTabs.Devices,+ );+ });++ // Accounts are shared capacity every agent routes onto, so managing them is+ // an admin task like the other workspace infrastructure.+ it('hides Subscription Accounts below Admin', () => {+ mocks.canManageWorkspace = false;++ expect(getItemKeys()).not.toContain(WorkspaceSettingsTabs.SubscriptionAccounts);+ expect(getItemKeys()).toContain(WorkspaceSettingsTabs.Devices);+ });+it('hides OAuth Apps by default', () => {expect(getItemKeys()).not.toContain(WorkspaceSettingsTabs.OAuthApps);});diff --git a/src/features/WorkspaceSetting/hooks/useCategory.tsx b/src/features/WorkspaceSetting/hooks/useCategory.tsxindex e049c215e5b..5e9bb6ef9df 100644--- a/src/features/WorkspaceSetting/hooks/useCategory.tsx+++ b/src/features/WorkspaceSetting/hooks/useCategory.tsx@@ -15,6 +15,7 @@ import {Database,EllipsisIcon,FlaskConical,+ GaugeIcon,HandCoins,HardDriveIcon,Info,@@ -49,6 +50,7 @@ export enum WorkspaceSettingsGroupKey {Agent = 'agent',Developer = 'developer',General = 'general',+ Resource = 'resource',Subscription = 'subscription',System = 'system',}@@ -172,11 +174,37 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.Teams,label: t('workspaceSetting.tab.teams'),},+ {+ icon: BellIcon,+ key: WorkspaceSettingsTabs.Notification,+ label: t('tab.notification'),+ },+ {+ icon: ChartColumnBigIcon,+ key: WorkspaceSettingsTabs.Stats,+ label: tAuth('tab.stats'),+ },+ ].filter(Boolean) as WorkspaceSettingCategoryItem[],+ key: WorkspaceSettingsGroupKey.General,+ title: t('workspaceSetting.group.workspace'),+ },+ // What the workspace's agents run on and spend: machines, coding-agent+ // subscriptions, code environments and the drive. Each item keeps its+ // own gate; the group only puts the shared capacity in one place.+ {+ items: [{icon: MonitorSmartphoneIcon,key: WorkspaceSettingsTabs.Devices,label: t('tab.devices'),},+ // The coding-agent accounts are shared capacity every agent routes+ // onto, so taking one in or out of rotation is an admin decision.+ canManageWorkspace && {+ icon: GaugeIcon,+ key: WorkspaceSettingsTabs.SubscriptionAccounts,+ label: t('tab.subscriptionAccounts'),+ },// Always there: a code environment is a definition, written down before// anything runs it, and useful with or without a drive to run it on.{@@ -191,19 +219,9 @@ export const useWorkspaceSettingCategory = (): WorkspaceSettingCategoryGroup[] =key: WorkspaceSettingsTabs.Drive,label: t('tab.drive'),},- {- icon: BellIcon,- key: WorkspaceSettingsTabs.Notification,- label: t('tab.notification'),- },- {- icon: ChartColumnBigIcon,- key: WorkspaceSettingsTabs.Stats,- label: tAuth('tab.stats'),- },].filter(Boolean) as WorkspaceSettingCategoryItem[],- key: WorkspaceSettingsGroupKey.General,- title: t('workspaceSetting.group.workspace'),+ key: WorkspaceSettingsGroupKey.Resource,+ title: t('workspaceSetting.group.resource'),},{items: [diff --git a/src/routes/(main)/[workspaceSlug]/settings/subscription-accounts/index.tsx b/src/routes/(main)/[workspaceSlug]/settings/subscription-accounts/index.tsxnew file mode 100644index 00000000000..1d586f7a659--- /dev/null+++ b/src/routes/(main)/[workspaceSlug]/settings/subscription-accounts/index.tsx@@ -0,0 +1,14 @@+'use client';++import SubscriptionAccounts from '@/features/SubscriptionAccounts';+import { WorkspaceAdminOnly } from '@/features/WorkspaceSetting';++const WorkspaceSubscriptionAccountsSetting = () => (+ <WorkspaceAdminOnly>+ <SubscriptionAccounts />+ </WorkspaceAdminOnly>+);++WorkspaceSubscriptionAccountsSetting.displayName = 'WorkspaceSubscriptionAccountsSetting';++export default WorkspaceSubscriptionAccountsSetting;diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.tsindex 30ec3eba9a0..ab47591c7f2 100644--- a/src/services/agentQuota.ts+++ b/src/services/agentQuota.ts@@ -79,6 +79,10 @@ class AgentQuotaService {listUsageTurns = async (accountId: string, sinceDays?: number) =>lambdaClient.agentQuota.listUsageTurns.query({ accountId, sinceDays });+ /** Agent runs in flight on an account, newest turn first. */+ listActiveRuns = async (accountId: string) =>+ lambdaClient.agentQuota.listActiveRuns.query({ accountId });+listBindings = async (agentId: string) => lambdaClient.agentQuota.listBindings.query({ agentId });/** UI "switch account": pin one account for an agent (Manual mode). */diff --git a/src/spa/router/workspaceSettingsRoutes.tsx b/src/spa/router/workspaceSettingsRoutes.tsxindex f6a9c1a83a0..1ad12d593af 100644--- a/src/spa/router/workspaceSettingsRoutes.tsx+++ b/src/spa/router/workspaceSettingsRoutes.tsx@@ -216,6 +216,14 @@ export const workspaceSettingsContentRoute: RouteObject = {handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('detail') }) },path: 'devices/:sub',},+ {+ element: dynamicElement(+ () => import('@/routes/(main)/[workspaceSlug]/settings/subscription-accounts'),+ 'Desktop > Workspace > Settings > Subscription Accounts',+ ),+ handle: { meta: routeMeta({ Skeleton: createSurfaceSkeleton('list') }) },+ path: 'subscription-accounts',+ },{element: dynamicElement(() => import('@/routes/(main)/[workspaceSlug]/settings/environments'),diff --git a/src/store/agentQuota/action.ts b/src/store/agentQuota/action.tsindex df26bea46e4..04b5196b5a2 100644--- a/src/store/agentQuota/action.ts+++ b/src/store/agentQuota/action.ts@@ -307,6 +307,20 @@ export class ActionImpl {await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);};+ /**+ * Take an account in or out of the workspace's rotation. A disabled account+ * stays listed (and keeps its history) but the load balancer skips it.+ */+ setQuotaAccountEnabled = async (accountId: string, enabled: boolean): Promise<void> => {+ await this.#accounts.optimistic(+ QUOTA_ACCOUNTS_KEY,+ (accounts) =>+ accounts.map((account) => (account.id === accountId ? { ...account, enabled } : account)),+ () => agentQuotaService.updateAccount(accountId, { enabled }),+ );+ await this.#refresh(this.#accounts, QUOTA_ACCOUNTS_KEY);+ };+// ---- local Claude Code logins (desktop) ----/**diff --git a/src/store/agentQuota/agentQuota.replica.test.ts b/src/store/agentQuota/agentQuota.replica.test.tsindex fe63e4510bb..fae0deb6dc9 100644--- a/src/store/agentQuota/agentQuota.replica.test.ts+++ b/src/store/agentQuota/agentQuota.replica.test.ts@@ -368,6 +368,24 @@ describe('agent quota replicas', () => {).toBe('Work'),);});++ it('takes an account out of rotation in the replica and on the server', async () => {+ vi.spyOn(agentQuotaService, 'listAccounts')+ .mockResolvedValueOnce([account('a1', { enabled: true })])+ .mockRejectedValue(new Error('offline'));+ const updateAccount = vi+ .spyOn(agentQuotaService, 'updateAccount')+ .mockResolvedValue(undefined as never);+ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaAccounts(), { wrapper });+ await waitFor(() =>+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())).toBeDefined(),+ );++ await act(() => useAgentQuotaStore.getState().setQuotaAccountEnabled('a1', false));++ expect(updateAccount).toHaveBeenCalledWith('a1', { enabled: false });+ expect(agentQuotaSelectors.accounts(useAgentQuotaStore.getState())?.[0]?.enabled).toBe(false);+ });});describe('user-data reset', () => {diff --git a/src/types/workspaceSettings.ts b/src/types/workspaceSettings.tsindex 6cfc838f7ea..f751f8f4bd8 100644--- a/src/types/workspaceSettings.ts+++ b/src/types/workspaceSettings.ts@@ -36,6 +36,7 @@ export enum WorkspaceSettingsTabs {Skill = 'skill',Stats = 'statistics',Storage = 'storage',+ SubscriptionAccounts = 'subscription-accounts',Teams = 'teams',Usage = 'usage',}