🤯 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(home): show subscription capacity as 5-hour windows on the team tab (#22734)
Arvin Xubf3d75e876be
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 2c1868c7f58..19187cec174 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1931,6 +1931,33 @@"subscriptionAccounts.activeRuns.untitledAgent": "Untitled agent","subscriptionAccounts.activeRuns.untitledTopic": "Untitled topic","subscriptionAccounts.activeRuns.waiting": "Waiting",+ "subscriptionAccounts.calendar.desc": "Next 7 days, one square per 5-hour window: grey is unused, blue is in use.",+ "subscriptionAccounts.calendar.failed": "Couldn't load",+ "subscriptionAccounts.calendar.failedNote": "Couldn't load this account's quota",+ "subscriptionAccounts.calendar.summary.failed": "{{count}} couldn't load",+ "subscriptionAccounts.calendar.idle": "Refilled · not started",+ "subscriptionAccounts.calendar.latest": "by {{time}}",+ "subscriptionAccounts.calendar.legend.blocked": "Used up",+ "subscriptionAccounts.calendar.legend.idle": "Unused",+ "subscriptionAccounts.calendar.legend.tight": "Nearly used up",+ "subscriptionAccounts.calendar.legend.used": "In use",+ "subscriptionAccounts.calendar.manage": "Manage accounts",+ "subscriptionAccounts.calendar.now": "Now",+ "subscriptionAccounts.calendar.state.blocked": "{{window}} used up, back {{time}}",+ "subscriptionAccounts.calendar.state.idle": "Unused",+ "subscriptionAccounts.calendar.state.tight": "Nearly used up: {{window}} {{percent}} used, resets {{time}}",+ "subscriptionAccounts.calendar.state.used": "{{percent}} used",+ "subscriptionAccounts.calendar.summary.available": "{{count}} available",+ "subscriptionAccounts.calendar.summary.exhausted": "{{count}} used up",+ "subscriptionAccounts.calendar.summary.nextRecovery": "next one back {{time}}",+ "subscriptionAccounts.calendar.summary.nextReset": "next reset {{time}}",+ "subscriptionAccounts.calendar.teamCell": "{{count}} of {{total}} accounts available",+ "subscriptionAccounts.calendar.teamRow": "Available accounts",+ "subscriptionAccounts.calendar.title": "Subscription capacity",+ "subscriptionAccounts.calendar.today": "Today {{time}}",+ "subscriptionAccounts.calendar.todayDay": "Today",+ "subscriptionAccounts.calendar.tomorrow": "Tomorrow {{time}}",+ "subscriptionAccounts.calendar.tomorrowDay": "Tomorrow","subscriptionAccounts.columns.account": "Account","subscriptionAccounts.columns.plan": "Plan","subscriptionAccounts.columns.quota": "Quota",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 2b9df968757..ab8405d2165 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1931,6 +1931,33 @@"subscriptionAccounts.activeRuns.untitledAgent": "未命名助理","subscriptionAccounts.activeRuns.untitledTopic": "未命名话题","subscriptionAccounts.activeRuns.waiting": "等待中",+ "subscriptionAccounts.calendar.desc": "未来 7 天,每格是一个 5 小时窗口:灰色未使用,蓝色已占用。",+ "subscriptionAccounts.calendar.failed": "读取失败",+ "subscriptionAccounts.calendar.failedNote": "额度读取失败",+ "subscriptionAccounts.calendar.summary.failed": "{{count}} 个读取失败",+ "subscriptionAccounts.calendar.idle": "已恢复 · 未开始计时",+ "subscriptionAccounts.calendar.latest": "最晚{{time}}",+ "subscriptionAccounts.calendar.legend.blocked": "已用尽",+ "subscriptionAccounts.calendar.legend.idle": "未使用",+ "subscriptionAccounts.calendar.legend.tight": "快用完",+ "subscriptionAccounts.calendar.legend.used": "已占用",+ "subscriptionAccounts.calendar.manage": "管理账号",+ "subscriptionAccounts.calendar.now": "现在",+ "subscriptionAccounts.calendar.state.blocked": "{{window}}额度已用尽,{{time}} 恢复",+ "subscriptionAccounts.calendar.state.idle": "未使用",+ "subscriptionAccounts.calendar.state.tight": "快用完:{{window}}额度已用 {{percent}},{{time}} 重置",+ "subscriptionAccounts.calendar.state.used": "已用 {{percent}}",+ "subscriptionAccounts.calendar.summary.available": "{{count}} 个可用",+ "subscriptionAccounts.calendar.summary.exhausted": "{{count}} 个已用尽",+ "subscriptionAccounts.calendar.summary.nextRecovery": "最早 {{time}}恢复",+ "subscriptionAccounts.calendar.summary.nextReset": "下次 {{time}}重置",+ "subscriptionAccounts.calendar.teamCell": "{{total}} 个账号中 {{count}} 个可用",+ "subscriptionAccounts.calendar.teamRow": "可用账号",+ "subscriptionAccounts.calendar.title": "订阅额度",+ "subscriptionAccounts.calendar.today": "今天 {{time}}",+ "subscriptionAccounts.calendar.todayDay": "今天",+ "subscriptionAccounts.calendar.tomorrow": "明天 {{time}}",+ "subscriptionAccounts.calendar.tomorrowDay": "明天","subscriptionAccounts.columns.account": "账号","subscriptionAccounts.columns.plan": "套餐","subscriptionAccounts.columns.quota": "额度",diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex a7b2ba43156..13c6e4c4e2a 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -4940,6 +4940,35 @@ When I am ___, I need ___'subscriptionAccounts.status.exhausted': 'Used up · resets {{time}}','subscriptionAccounts.status.exhaustedNoReset': 'Used up','subscriptionAccounts.status.noData': 'No quota reported yet',+ 'subscriptionAccounts.calendar.failed': "Couldn't load",+ 'subscriptionAccounts.calendar.failedNote': "Couldn't load this account's quota",+ 'subscriptionAccounts.calendar.summary.failed': "{{count}} couldn't load",+ 'subscriptionAccounts.calendar.idle': 'Refilled · not started',+ 'subscriptionAccounts.calendar.manage': 'Manage accounts',+ 'subscriptionAccounts.calendar.state.blocked': '{{window}} used up, back {{time}}',+ 'subscriptionAccounts.calendar.desc':+ 'Next 7 days, one square per 5-hour window: grey is unused, blue is in use.',+ 'subscriptionAccounts.calendar.latest': 'by {{time}}',+ 'subscriptionAccounts.calendar.legend.blocked': 'Used up',+ 'subscriptionAccounts.calendar.legend.idle': 'Unused',+ 'subscriptionAccounts.calendar.legend.tight': 'Nearly used up',+ 'subscriptionAccounts.calendar.legend.used': 'In use',+ 'subscriptionAccounts.calendar.now': 'Now',+ 'subscriptionAccounts.calendar.state.idle': 'Unused',+ 'subscriptionAccounts.calendar.state.tight':+ 'Nearly used up: {{window}} {{percent}} used, resets {{time}}',+ 'subscriptionAccounts.calendar.state.used': '{{percent}} used',+ 'subscriptionAccounts.calendar.summary.available': '{{count}} available',+ 'subscriptionAccounts.calendar.summary.exhausted': '{{count}} used up',+ 'subscriptionAccounts.calendar.summary.nextRecovery': 'next one back {{time}}',+ 'subscriptionAccounts.calendar.summary.nextReset': 'next reset {{time}}',+ 'subscriptionAccounts.calendar.teamCell': '{{count}} of {{total}} accounts available',+ 'subscriptionAccounts.calendar.teamRow': 'Available accounts',+ 'subscriptionAccounts.calendar.title': 'Subscription capacity',+ 'subscriptionAccounts.calendar.today': 'Today {{time}}',+ 'subscriptionAccounts.calendar.todayDay': 'Today',+ 'subscriptionAccounts.calendar.tomorrow': 'Tomorrow {{time}}',+ 'subscriptionAccounts.calendar.tomorrowDay': 'Tomorrow','subscriptionAccounts.summary': '{{inRotation}} of {{count}} in rotation','subscriptionAccounts.updateFailed': "Couldn't update the account. Try again.",'tab.subscriptionAccounts': 'Subscription Accounts',diff --git a/src/features/HomeTeamBoard/QuotaCapacity.tsx b/src/features/HomeTeamBoard/QuotaCapacity.tsxnew file mode 100644index 00000000000..bbcf5484ddf--- /dev/null+++ b/src/features/HomeTeamBoard/QuotaCapacity.tsx@@ -0,0 +1,49 @@+import { Button } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import {+ isSubscriptionProvider,+ sortAccounts,+ type SubscriptionProvider,+} from '@/features/SubscriptionAccounts/accountView';+import QuotaCalendar from '@/features/SubscriptionAccounts/QuotaCalendar';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { usePermission } from '@/hooks/usePermission';+import { agentQuotaSelectors, type QuotaAccount, useAgentQuotaStore } from '@/store/agentQuota';++type ProviderAccount = QuotaAccount & { provider: SubscriptionProvider };++/**+ * The team's coding-agent subscriptions as a capacity calendar, under the run+ * board: what the team can hand work to over the coming days. A workspace with+ * no subscription accounts has nothing to plan against, so it shows nothing.+ */+const QuotaCapacity = () => {+ const { t } = useTranslation('setting');+ const useFetchQuotaAccounts = useAgentQuotaStore((s) => s.useFetchQuotaAccounts);+ useFetchQuotaAccounts();+ const loaded = useAgentQuotaStore(agentQuotaSelectors.accounts);+ // Taking accounts in or out of rotation is an admin decision, as on the settings page.+ const { allowed: canManage } = usePermission('manage_settings');+ const navigate = useWorkspaceAwareNavigate();++ const accounts = sortAccounts(+ (loaded ?? []).filter((a): a is ProviderAccount => isSubscriptionProvider(a.provider)),+ );+ if (accounts.length === 0) return null;++ return (+ <QuotaCalendar+ accounts={accounts}+ extra={+ canManage && (+ <Button size={'small'} onClick={() => navigate('/settings/subscription-accounts')}>+ {t('subscriptionAccounts.calendar.manage')}+ </Button>+ )+ }+ />+ );+};++export default QuotaCapacity;diff --git a/src/features/HomeTeamBoard/index.tsx b/src/features/HomeTeamBoard/index.tsxindex e0a934af06a..da7a3af14e5 100644--- a/src/features/HomeTeamBoard/index.tsx+++ b/src/features/HomeTeamBoard/index.tsx@@ -16,6 +16,7 @@ import ActivityPanel from './ActivityPanel';import AttentionList from './AttentionList';import BoardFilters from './BoardFilters';import DayCalendar from './DayCalendar';+import QuotaCapacity from './QuotaCapacity';import Timeline from './Timeline';// Matches the other overview pages; the gateway only streams a user's own runs.@@ -154,6 +155,8 @@ const HomeTeamBoard = () => {</div></Flexbox>)}+ {/* Independent of the run board: it loads, polls and fails on its own. */}+ <QuotaCapacity /></Flexbox>);};diff --git a/src/features/SubscriptionAccounts/AccountRow.tsx b/src/features/SubscriptionAccounts/AccountRow.tsxindex 8e0033538e7..2d58dc0fd13 100644--- a/src/features/SubscriptionAccounts/AccountRow.tsx+++ b/src/features/SubscriptionAccounts/AccountRow.tsx@@ -90,6 +90,10 @@ const PROVIDER_META: Record<'kimi-code': { icon: (size) => <Kimi.Avatar size={size} />, name: 'Kimi Code' },};+/** The provider's avatar, as the list row draws it. */+export const providerAvatar = (provider: SubscriptionProvider, size: number) =>+ PROVIDER_META[provider].icon(size);+export const PROVIDER_NAME = Object.fromEntries(Object.entries(PROVIDER_META).map(([key, meta]) => [key, meta.name]),) as Record<SubscriptionProvider, string>;diff --git a/src/features/SubscriptionAccounts/QuotaCalendar.tsx b/src/features/SubscriptionAccounts/QuotaCalendar.tsxnew file mode 100644index 00000000000..1e138740e28--- /dev/null+++ b/src/features/SubscriptionAccounts/QuotaCalendar.tsx@@ -0,0 +1,656 @@+'use client';++import { Button, Flexbox, Text, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import dayjs from 'dayjs';+import relativeTime from 'dayjs/plugin/relativeTime';+import type { TFunction } from 'i18next';+import { type ReactNode, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { formatPercent } from '@/features/DeviceManager/DeviceHealth/format';+import { agentQuotaSelectors, type QuotaAccount, useAgentQuotaStore } from '@/store/agentQuota';++import { accountDisplayName, providerAvatar } from './AccountRow';+import {+ type AccountView,+ type AccountWindowKey,+ deriveAccountView,+ type SubscriptionProvider,+} from './accountView';+import {+ accountWindows,+ axisMidnights,+ buildQuotaAxis,+ isUsableAt,+ type QuotaAxis,+ type QuotaWindow,+ resetDayOf,+ summarizeQuota,+ teamBuckets,+ WINDOW_MS,+} from './quotaWindows';++dayjs.extend(relativeTime);++type ProviderAccount = QuotaAccount & { provider: SubscriptionProvider };++/** Windows move with the clock; a minute is finer than any change the grid shows. */+const TICK_MS = 60_000;+/**+ * Teammates spend the accounts while the calendar sits open, and the Team tab+ * has no refresh button: re-read every account's readings on the same beat.+ */+const READINGS_REFRESH_MS = 60_000;++/** Every 5-hour window is one square of this size, plus the gap before the next. */+// Cells are 26px squares (keep in sync with styles.cell).+const STEP_PX = 28;+const PX_PER_MS = STEP_PX / WINDOW_MS;+const x = (at: number, axis: QuotaAxis) => `${Math.round((at - axis.start) * PX_PER_MS)}px`;++const HATCH = (color: string) =>+ `repeating-linear-gradient(-45deg, ${color} 0 3px, color-mix(in srgb, ${color} 35%, transparent) 3px 6px)`;+/** Blue deepens with how much of the window is spent. */+const usedColor = (percent: number) =>+ `color-mix(in srgb, ${cssVar.colorInfo} ${Math.round(35 + Math.min(percent, 100) * 0.5)}%, transparent)`;++const styles = stylex.create({+ card: {+ display: 'flex',+ flexDirection: 'column',+ gap: '12px',+ paddingBlock: '16px',+ paddingInline: '16px',+ backgroundColor: cssVar.colorBgContainer,+ borderWidth: '1px',+ borderStyle: 'solid',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: '12px',+ },+ // The whole grid scrolls sideways; windows keep their size instead of squeezing.+ scroller: { overflowX: 'auto', overflowY: 'hidden', paddingBlockEnd: '4px' },+ row: {+ display: 'flex',+ alignItems: 'center',+ width: 'max-content',+ minWidth: '100%',+ paddingBlock: '3px',+ borderRadius: cssVar.borderRadius,+ },+ rowClickable: {+ cursor: 'pointer',+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },+ outline: { 'default': 'none', ':focus-visible': `2px solid ${cssVar.colorPrimary}` },+ },+ rowActive: { backgroundColor: cssVar.colorFillSecondary },+ rowDisabled: { opacity: 0.55 },+ // Name and reset times stay put while the windows scroll under them.+ lead: {+ position: 'sticky',+ insetInlineStart: 0,+ zIndex: 1,+ display: 'flex',+ alignItems: 'center',+ flexShrink: 0,+ alignSelf: 'stretch',+ paddingInline: '8px',+ backgroundColor: cssVar.colorBgContainer,+ },+ // Paints the row's hover / active fill over the opaque lead.+ leadHover: {+ backgroundImage: {+ default: 'none',+ [stylex.when.ancestor(':hover')]:+ `linear-gradient(${cssVar.colorFillTertiary}, ${cssVar.colorFillTertiary})`,+ },+ },+ leadActive: {+ backgroundImage: `linear-gradient(${cssVar.colorFillSecondary}, ${cssVar.colorFillSecondary})`,+ },+ name: { display: 'flex', alignItems: 'center', gap: '8px', width: '160px', minWidth: 0 },+ // A narrow screen drops the reset times; the windows and their tooltips carry them.+ resets: {+ display: { 'default': 'flex', '@media (max-width: 1100px)': 'none' },+ flexDirection: 'column',+ justifyContent: 'center',+ gap: '2px',+ width: '164px',+ minHeight: '40px',+ paddingInlineStart: '8px',+ },+ track: (width: string) => ({+ position: 'relative',+ flexShrink: 0,+ width,+ height: '34px',+ marginInlineEnd: '8px',+ }),+ dayLine: (left: string) => ({+ position: 'absolute',+ insetBlock: 0,+ insetInlineStart: left,+ width: '1px',+ backgroundColor: cssVar.colorBorderSecondary,+ }),+ nowLine: (left: string) => ({+ position: 'absolute',+ insetBlock: 0,+ insetInlineStart: left,+ width: '2px',+ borderRadius: '1px',+ backgroundColor: cssVar.colorPrimary,+ zIndex: 1,+ }),+ dayLabel: (left: string) => ({+ position: 'absolute',+ insetBlockStart: '8px',+ insetInlineStart: left,+ paddingInlineStart: '4px',+ whiteSpace: 'nowrap',+ fontSize: '12px',+ color: cssVar.colorTextSecondary,+ }),+ cell: (left: string, color: string, image: string) => ({+ position: 'absolute',+ insetBlockStart: '4px',+ insetInlineStart: left,+ width: '26px',+ height: '26px',+ borderRadius: '5px',+ backgroundColor: color,+ backgroundImage: image,+ }),+ count: (color: string) => ({+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ fontSize: '11px',+ fontVariantNumeric: 'tabular-nums',+ color,+ }),+ // Nearly used up: a small dot on the window's corner.+ dot: {+ position: 'absolute',+ insetBlockStart: '-3px',+ insetInlineEnd: '-3px',+ width: '8px',+ height: '8px',+ borderRadius: '50%',+ backgroundColor: cssVar.colorWarning,+ boxShadow: `0 0 0 2px ${cssVar.colorBgContainer}`,+ },+ note: (left: string) => ({+ position: 'absolute',+ insetBlockStart: '9px',+ insetInlineStart: left,+ paddingInlineStart: '8px',+ whiteSpace: 'nowrap',+ fontSize: '12px',+ color: cssVar.colorTextTertiary,+ }),+ // A failed read: what went wrong, and a way to try again.+ failure: (left: string) => ({+ position: 'absolute',+ insetBlockStart: '4px',+ insetInlineStart: left,+ display: 'flex',+ alignItems: 'center',+ gap: '4px',+ paddingInlineStart: '8px',+ whiteSpace: 'nowrap',+ fontSize: '12px',+ color: cssVar.colorError,+ }),+ swatch: { position: 'relative', width: '14px', height: '14px', borderRadius: '4px' },+});++/** Re-render every minute, so windows move on and resets come due. */+const useNow = () => {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ const id = setInterval(() => setNow(Date.now()), TICK_MS);+ return () => clearInterval(id);+ }, []);+ return now;+};++const dayName = (at: number, now: number, t: TFunction<'setting'>) => {+ switch (resetDayOf(at, now)) {+ case 'today': {+ return t('subscriptionAccounts.calendar.todayDay');+ }+ case 'tomorrow': {+ return t('subscriptionAccounts.calendar.tomorrowDay');+ }+ default: {+ return dayjs(at).format('ddd');+ }+ }+};++/** `Today 14:20` / `Tomorrow 09:00` / `Fri 09:00`: the day matters more than the date within a week. */+const formatTime = (at: number, now: number, t: TFunction<'setting'>) => {+ const day = resetDayOf(at, now);+ const time = dayjs(at).format('HH:mm');+ if (day === 'today') return t('subscriptionAccounts.calendar.today', { time });+ if (day === 'tomorrow') return t('subscriptionAccounts.calendar.tomorrow', { time });+ return dayjs(at).format('ddd HH:mm');+};++/** `Today 12:06–17:06`, naming the end's day too when the window crosses midnight. */+const formatRange = (start: number, end: number, now: number, t: TFunction<'setting'>) =>+ dayjs(start).isSame(end, 'day')+ ? `${formatTime(start, now, t)}–${dayjs(end).format('HH:mm')}`+ : `${formatTime(start, now, t)}–${formatTime(end, now, t)}`;++const windowLabel = (key: AccountWindowKey | undefined, t: TFunction<'setting'>) =>+ key === 'weekly'+ ? t('subscriptionAccounts.meter.weekly')+ : t('subscriptionAccounts.meter.session');++const windowStyle = (window: QuotaWindow, left: string) => {+ switch (window.state) {+ case 'blocked': {+ return styles.cell(left, 'transparent', HATCH(cssVar.colorError));+ }+ case 'used': {+ return styles.cell(left, usedColor(window.usedPercent ?? 0), 'none');+ }+ default: {+ return styles.cell(left, cssVar.colorFillSecondary, 'none');+ }+ }+};++const windowText = (window: QuotaWindow, now: number, t: TFunction<'setting'>) => {+ const limit = window.blockedBy ?? window.tightBy;+ const values = {+ percent: formatPercent(limit?.usedPercent),+ // An unreported reset is only known as a bound: say "by" rather than "at".+ time: limit+ ? limit.estimated+ ? t('subscriptionAccounts.calendar.latest', { time: formatTime(limit.until, now, t) })+ : formatTime(limit.until, now, t)+ : '',+ window: windowLabel(limit?.key, t),+ };+ const state =+ window.state === 'blocked'+ ? t('subscriptionAccounts.calendar.state.blocked', values)+ : window.state === 'used'+ ? t('subscriptionAccounts.calendar.state.used', {+ percent: formatPercent(window.usedPercent),+ })+ : t('subscriptionAccounts.calendar.state.idle');+ return window.tightBy+ ? `${state} · ${t('subscriptionAccounts.calendar.state.tight', values)}`+ : state;+};++interface RowProps {+ account: ProviderAccount;+ active?: boolean;+ axis: QuotaAxis;+ loaded: boolean;+ now: number;+ onOpen?: () => void;+ trackWidth: string;+ view: AccountView;+ windows: QuotaWindow[];+}++const DayLines = ({ axis, midnights }: { axis: QuotaAxis; midnights: number[] }) => (+ <>+ {midnights.map((at) => (+ <span aria-hidden key={at} {...stylex.props(styles.dayLine(x(at, axis)))} />+ ))}+ </>+);++const AccountWindowsRow = ({+ account,+ active,+ axis,+ loaded,+ now,+ onOpen,+ trackWidth,+ view,+ windows,+}: RowProps) => {+ const { t } = useTranslation('setting');+ const useFetchQuotaReadings = useAgentQuotaStore((s) => s.useFetchQuotaReadings);+ const { isValidating, revalidate } = useFetchQuotaReadings(account.id, {+ refreshInterval: READINGS_REFRESH_MS,+ });+ // A read that failed with nothing to show must not look like one still loading.+ const failed = useAgentQuotaStore(agentQuotaSelectors.readingsFailed(account.id)) && !loaded;+ const name = accountDisplayName(account);+ const midnights = axisMidnights(axis);++ const resets = (['session', 'weekly'] as const).flatMap((key) => {+ const window = view[key];+ const at = window?.resetsAt ?? window?.latestResetAt;+ if (!window || at == null || at <= now) return [];+ return [+ {+ estimated: window.resetsAt == null,+ exhausted: window.usedPercent >= 100,+ key,+ resetsAt: at,+ },+ ];+ });+ // Before the readings arrive the row says nothing rather than "no data".+ const idleText = failed+ ? t('subscriptionAccounts.calendar.failed')+ : !loaded+ ? '—'+ : view.status === 'noData'+ ? t('subscriptionAccounts.status.noData')+ : t('subscriptionAccounts.calendar.idle');+ // Out of rotation or never reported: there are no windows to draw, only why.+ // A failed read says so instead; the two notes would overlap.+ const note = failed+ ? undefined+ : view.status === 'disabled'+ ? t('subscriptionAccounts.status.disabled')+ : view.status === 'noData' && loaded+ ? t('subscriptionAccounts.status.noData')+ : undefined;+ const drawWindows = loaded && !note;++ const clickable = onOpen+ ? {+ 'aria-current': active || undefined,+ 'onClick': onOpen,+ 'onKeyDown': (e: React.KeyboardEvent) => {+ if (e.key === 'Enter' && e.target === e.currentTarget) {+ e.preventDefault();+ onOpen();+ }+ },+ 'role': 'button',+ 'tabIndex': 0,+ }+ : { role: 'group' };++ return (+ <div+ {...stylex.props(+ styles.row,+ stylex.defaultMarker(),+ onOpen && styles.rowClickable,+ active && styles.rowActive,+ view.status === 'disabled' && styles.rowDisabled,+ )}+ aria-label={name}+ data-account-row={account.id}+ {...clickable}+ >+ <div {...stylex.props(styles.lead, onOpen && styles.leadHover, active && styles.leadActive)}>+ <div {...stylex.props(styles.name)}>+ <span style={{ display: 'flex', flex: 'none' }}>+ {providerAvatar(account.provider, 20)}+ </span>+ <Text ellipsis fontSize={13} title={name}>+ {name}+ </Text>+ </div>+ {/* The reset times stay in text, not only in the tooltips: touch has no hover. */}+ <div data-resets {...stylex.props(styles.resets)}>+ {resets.length === 0 ? (+ <Text+ fontSize={12}+ style={{ color: failed ? cssVar.colorError : undefined }}+ type={failed ? undefined : 'secondary'}+ >+ {idleText}+ </Text>+ ) : (+ resets.map((reset) => (+ <Text+ ellipsis+ fontSize={12}+ key={reset.key}+ type={reset.exhausted ? undefined : 'secondary'}+ style={{+ color: reset.exhausted ? cssVar.colorError : undefined,+ whiteSpace: 'nowrap',+ }}+ >+ {windowLabel(reset.key, t)} ·{' '}+ {reset.estimated+ ? t('subscriptionAccounts.calendar.latest', {+ time: formatTime(reset.resetsAt, now, t),+ })+ : formatTime(reset.resetsAt, now, t)}+ </Text>+ ))+ )}+ </div>+ </div>++ <div {...stylex.props(styles.track(trackWidth))}>+ <DayLines axis={axis} midnights={midnights} />+ <span aria-hidden {...stylex.props(styles.nowLine(x(now, axis)))} />+ {note && <span {...stylex.props(styles.note(x(now, axis)))}>{note}</span>}+ {failed && (+ <span data-read-failed {...stylex.props(styles.failure(x(now, axis)))}>+ {t('subscriptionAccounts.calendar.failedNote')}+ <Button+ loading={isValidating}+ size={'small'}+ type={'link'}+ onClick={(e) => {+ // The row itself opens the account; retrying must not.+ e.stopPropagation();+ void revalidate();+ }}+ >+ {t('retry', { ns: 'common' })}+ </Button>+ </span>+ )}+ {drawWindows &&+ windows.map((window) => {+ const text = `${name} · ${formatRange(window.start, window.end, now, t)} · ${windowText(window, now, t)}`;+ return (+ <Tooltip key={window.start} title={text}>+ <span+ aria-label={text}+ data-start={window.start}+ data-tight={window.tightBy ? true : undefined}+ data-window={window.state}+ role={'img'}+ {...stylex.props(windowStyle(window, x(window.start, axis)))}+ >+ {window.tightBy && <span aria-hidden {...stylex.props(styles.dot)} />}+ </span>+ </Tooltip>+ );+ })}+ </div>+ </div>+ );+};++interface QuotaCalendarProps {+ accounts: ProviderAccount[];+ /** The account whose side panel is open. */+ activeId?: string;+ /** Extra controls on the header's right, e.g. a link to manage the accounts. */+ extra?: ReactNode;+ /** Rows open the account when given; on their own they only inform. */+ onOpen?: (accountId: string) => void;+}++/**+ * Every subscription's 5-hour windows on one 7-day axis: the window under way+ * where it really is, then the ones after it. Grey windows are unused, blue+ * ones partly spent, hatched ones blocked; a dot marks one nearly used up. The+ * top row counts the accounts that can take work in each 5 hours from now.+ */+const QuotaCalendar = ({ accounts, activeId, extra, onOpen }: QuotaCalendarProps) => {+ const { t } = useTranslation('setting');+ const now = useNow();+ const readings = useAgentQuotaStore((s) => accounts.map((a) => s.quotaReadingsMap[a.id]));+ const axis = buildQuotaAxis(now);+ const trackWidth = x(axis.end, axis);+ const midnights = axisMidnights(axis);+ const views = accounts.map((account, index) => deriveAccountView(account, readings[index], now));+ const windowsByAccount = views.map((view) => accountWindows(view, axis, now));+ const summary = summarizeQuota(views, now);+ const failed = useAgentQuotaStore((s) =>+ accounts.map((a) => !!s.quotaReadingsFailed[a.id] && !s.quotaReadingsMap[a.id]),+ );+ // Counting before every account has answered would flash "0 available"; an+ // account whose read failed has answered, and is counted as unavailable.+ const allSettled = readings.every((entry, index) => entry !== undefined || failed[index]);+ const failedCount = failed.filter(Boolean).length;+ // Accounts that can take work at all: in rotation and reporting.+ const countable = views+ .map((view, index) => ({ view, windows: windowsByAccount[index] }))+ .filter(({ view }) => view.status !== 'disabled' && view.status !== 'noData');+ const inRotation = views.filter((view) => view.status !== 'disabled').length;++ const summaryParts = [+ t('subscriptionAccounts.calendar.summary.available', { count: summary.available }),+ summary.exhausted > 0 &&+ t('subscriptionAccounts.calendar.summary.exhausted', { count: summary.exhausted }),+ summary.nextRecoveryAt+ ? t('subscriptionAccounts.calendar.summary.nextRecovery', {+ time: dayjs(summary.nextRecoveryAt).from(now),+ })+ : summary.nextResetAt &&+ t('subscriptionAccounts.calendar.summary.nextReset', {+ time: dayjs(summary.nextResetAt).from(now),+ }),+ failedCount > 0 && t('subscriptionAccounts.calendar.summary.failed', { count: failedCount }),+ ].filter(Boolean);++ const legend = [+ { key: 'idle', style: styles.cell('0', cssVar.colorFillSecondary, 'none') },+ { key: 'used', style: styles.cell('0', usedColor(50), 'none') },+ { dot: true, key: 'tight', style: styles.cell('0', usedColor(85), 'none') },+ { key: 'blocked', style: styles.cell('0', 'transparent', HATCH(cssVar.colorError)) },+ ] as const;++ return (+ <section aria-label={t('subscriptionAccounts.calendar.title')} {...stylex.props(styles.card)}>+ <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'} wrap={'wrap'}>+ <Flexbox gap={2}>+ <Text weight={500}>{t('subscriptionAccounts.calendar.title')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('subscriptionAccounts.calendar.desc')}+ </Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={12}>+ <Text aria-live={'polite'} fontSize={13}>+ {allSettled && summaryParts.join(' · ')}+ </Text>+ {extra}+ </Flexbox>+ </Flexbox>++ <Flexbox horizontal align={'center'} gap={16} wrap={'wrap'}>+ {legend.map((item) => (+ <Flexbox horizontal align={'center'} gap={6} key={item.key}>+ <span {...stylex.props(item.style, styles.swatch)}>+ {'dot' in item && <span aria-hidden {...stylex.props(styles.dot)} />}+ </span>+ <Text fontSize={12} type={'secondary'}>+ {t(`subscriptionAccounts.calendar.legend.${item.key}`)}+ </Text>+ </Flexbox>+ ))}+ </Flexbox>++ <div data-quota-scroller {...stylex.props(styles.scroller)}>+ {/* Day headers at each midnight, and "Now". */}+ <div {...stylex.props(styles.row)}>+ <div {...stylex.props(styles.lead)}>+ <div {...stylex.props(styles.name)} />+ <div {...stylex.props(styles.resets)} />+ </div>+ <div {...stylex.props(styles.track(trackWidth))}>+ <span {...stylex.props(styles.dayLabel(x(now, axis)))}>+ {t('subscriptionAccounts.calendar.now')}+ </span>+ {midnights.map((at) => (+ <span+ data-day-label+ key={at}+ title={dayjs(at).format('YYYY-MM-DD ddd')}+ {...stylex.props(styles.dayLabel(x(at, axis)))}+ >+ {dayName(at, now, t)}+ </span>+ ))}+ </div>+ </div>++ {/* How many accounts can take work in each 5 hours from now. */}+ <div {...stylex.props(styles.row)} data-team-row>+ <div {...stylex.props(styles.lead)}>+ <div {...stylex.props(styles.name)}>+ <Text fontSize={12} type={'secondary'}>+ {t('subscriptionAccounts.calendar.teamRow')}+ </Text>+ </div>+ <div {...stylex.props(styles.resets)} />+ </div>+ <div {...stylex.props(styles.track(trackWidth))}>+ <DayLines axis={axis} midnights={midnights} />+ {allSettled &&+ teamBuckets(now, axis).map((bucket) => {+ const middle = (bucket.start + bucket.end) / 2;+ const usable = countable.filter(({ windows }) =>+ isUsableAt(windows, middle),+ ).length;+ const share = inRotation ? usable / inRotation : 0;+ const label = `${formatRange(bucket.start, bucket.end, now, t)} · ${t('subscriptionAccounts.calendar.teamCell', { count: usable, total: inRotation })}`;+ return (+ <Tooltip key={bucket.start} title={label}>+ <span+ aria-label={label}+ data-usable={usable}+ {...stylex.props(+ styles.cell(+ x(bucket.start, axis),+ `color-mix(in srgb, ${cssVar.colorInfo} ${Math.round(8 + share * 30)}%, transparent)`,+ 'none',+ ),+ styles.count(usable ? cssVar.colorText : cssVar.colorTextQuaternary),+ )}+ >+ {usable}+ </span>+ </Tooltip>+ );+ })}+ </div>+ </div>++ {accounts.map((account, index) => (+ <AccountWindowsRow+ account={account}+ active={account.id === activeId}+ axis={axis}+ key={account.id}+ loaded={readings[index] !== undefined}+ now={now}+ trackWidth={trackWidth}+ view={views[index]}+ windows={windowsByAccount[index]}+ onOpen={onOpen ? () => onOpen(account.id) : undefined}+ />+ ))}+ </div>+ </section>+ );+};++export default QuotaCalendar;diff --git a/src/features/SubscriptionAccounts/accountView.test.ts b/src/features/SubscriptionAccounts/accountView.test.tsindex 710e6a29a3c..72d94f13cd5 100644--- a/src/features/SubscriptionAccounts/accountView.test.ts+++ b/src/features/SubscriptionAccounts/accountView.test.ts@@ -14,6 +14,31 @@ const reading = (limitType: string, utilization: number, resetsAt: number | null});describe('deriveAccountView', () => {+ it('bounds a used window whose provider reported no reset by one window from its capture', () => {+ const view = deriveAccountView(+ { enabled: true },+ [{ ...reading('session', 100, null, NOW - HOUR), windowMinutes: 300 }],+ NOW,+ );++ expect(view.status).toBe('exhausted');+ expect(view.session).toEqual({+ latestResetAt: NOW + 4 * HOUR,+ resetsAt: null,+ usedPercent: 100,+ });+ });++ it('sets no bound once such a window has aged out', () => {+ const view = deriveAccountView(+ { enabled: true },+ [{ ...reading('session', 100, null, NOW - 6 * HOUR), windowMinutes: 300 }],+ NOW,+ );++ expect(view.session).toEqual({ resetsAt: null, usedPercent: 0 });+ });+it('reports both windows and the newest sync time for an available account', () => {const view = deriveAccountView({ enabled: true },diff --git a/src/features/SubscriptionAccounts/accountView.ts b/src/features/SubscriptionAccounts/accountView.tsindex c865c91d904..836b5a30a5c 100644--- a/src/features/SubscriptionAccounts/accountView.ts+++ b/src/features/SubscriptionAccounts/accountView.ts@@ -17,6 +17,11 @@ export const isSubscriptionProvider = (provider: string): provider is Subscripticonst EXHAUSTED_PERCENT = 100;export interface AccountWindowView {+ /**+ * The latest the window can reset when the provider did not say: a reading+ * holds for one window from its capture. Only set for a live window with usage.+ */+ latestResetAt?: number;/** Window boundary of the live window; null once it rolled over or when unreported. */resetsAt: number | null;usedPercent: number;@@ -44,10 +49,17 @@ const newest = <T extends QuotaDisplayReading>(undefined,);-const windowOf = (reading: QuotaDisplayReading | undefined, now: number) => {+const windowOf = (+ reading: QuotaDisplayReading | undefined,+ now: number,+): AccountWindowView | undefined => {if (!reading) return undefined;const window = toQuotaWindow(reading, now);- return { resetsAt: window.resetsAt, usedPercent: window.usedPercent };+ const view: AccountWindowView = { resetsAt: window.resetsAt, usedPercent: window.usedPercent };+ // A rolled-over window reads 0%, so usage with no reset means an unreported one.+ if (window.resetsAt == null && window.usedPercent > 0)+ view.latestResetAt = reading.capturedAt + window.windowMinutes * 60_000;+ return view;};/**diff --git a/src/features/SubscriptionAccounts/index.tsx b/src/features/SubscriptionAccounts/index.tsxindex 2e68176515e..9ee36c932af 100644--- a/src/features/SubscriptionAccounts/index.tsx+++ b/src/features/SubscriptionAccounts/index.tsx@@ -19,6 +19,7 @@ import {SUBSCRIPTION_PROVIDERS,type SubscriptionProvider,} from './accountView';+import QuotaCalendar from './QuotaCalendar';type ProviderAccount = QuotaAccount & { provider: SubscriptionProvider };@@ -91,24 +92,32 @@ const SubscriptionAccounts = () => {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>+ <Flexbox gap={16}>+ {visible.length > 0 && (+ <QuotaCalendar accounts={visible} activeId={openId} onOpen={setOpenId} />+ )}+ {/* 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>+ </Flexbox>);return (diff --git a/src/features/SubscriptionAccounts/quotaWindows.test.ts b/src/features/SubscriptionAccounts/quotaWindows.test.tsnew file mode 100644index 00000000000..9c5f812adc6--- /dev/null+++ b/src/features/SubscriptionAccounts/quotaWindows.test.ts@@ -0,0 +1,210 @@+import dayjs from 'dayjs';+import { describe, expect, it } from 'vitest';++import type { AccountView } from './accountView';+import {+ accountWindows,+ axisMidnights,+ buildQuotaAxis,+ isUsableAt,+ resetDayOf,+ summarizeQuota,+ teamBuckets,+ WINDOW_MS,+} from './quotaWindows';++// Local 11:00, so midnights fall on local days whatever the test TZ.+const NOW = dayjs('2026-11-10T11:00:00').valueOf();+const HOUR = 60 * 60 * 1000;+const axis = buildQuotaAxis(NOW);++const view = (patch: Partial<AccountView>): AccountView => ({ status: 'available', ...patch });++describe('buildQuotaAxis', () => {+ it('starts one window back and looks seven days ahead', () => {+ expect(axis).toEqual({ end: NOW + 7 * 24 * HOUR, start: NOW - 5 * HOUR });+ });++ it('marks each local midnight inside the axis', () => {+ const midnights = axisMidnights(axis);++ expect(midnights).toHaveLength(7);+ expect(dayjs(midnights[0]).format('YYYY-MM-DD HH:mm')).toBe('2026-11-11 00:00');+ });+});++describe('accountWindows', () => {+ it('places the window under way at its real reset, then lays 5-hour windows back to back', () => {+ const windows = accountWindows(+ view({ session: { resetsAt: NOW + 2 * HOUR, usedPercent: 35 } }),+ axis,+ NOW,+ );++ expect(windows[0]).toEqual({+ blockedBy: undefined,+ end: NOW + 2 * HOUR,+ start: NOW - 3 * HOUR,+ state: 'used',+ tightBy: undefined,+ usedPercent: 35,+ });+ expect(windows[1]).toMatchObject({ end: NOW + 7 * HOUR, start: NOW + 2 * HOUR, state: 'idle' });+ expect(windows.every((w, i) => i === 0 || w.start === windows[i - 1].end)).toBe(true);+ expect(windows.at(-1)!.start).toBeLessThan(axis.end);+ expect(windows.at(-1)!.end).toBeGreaterThanOrEqual(axis.end);+ });++ it('starts from now when no window is under way', () => {+ const windows = accountWindows(+ view({ session: { resetsAt: null, usedPercent: 0 } }),+ axis,+ NOW,+ );++ expect(windows[0]).toMatchObject({ start: NOW, state: 'idle' });+ });++ it('blocks a used-up session window and leaves the next one idle', () => {+ const windows = accountWindows(+ view({ session: { resetsAt: NOW + HOUR, usedPercent: 100 }, status: 'exhausted' }),+ axis,+ NOW,+ );++ expect(windows[0]).toMatchObject({+ blockedBy: { key: 'session', until: NOW + HOUR, usedPercent: 100 },+ state: 'blocked',+ });+ expect(windows[1]).toMatchObject({ blockedBy: undefined, state: 'idle' });+ });++ it('blocks every window that starts before a used-up weekly limit resets', () => {+ const windows = accountWindows(+ view({+ session: { resetsAt: NOW + HOUR, usedPercent: 20 },+ status: 'exhausted',+ weekly: { resetsAt: NOW + 12 * HOUR, usedPercent: 100 },+ }),+ axis,+ NOW,+ );++ // Starts at -4h, +1h, +6h are before the +12h reset; +11h too; +16h is after.+ expect(windows.slice(0, 4).map((w) => w.state)).toEqual([+ 'blocked',+ 'blocked',+ 'blocked',+ 'blocked',+ ]);+ expect(windows[0].blockedBy?.key).toBe('weekly');+ expect(windows[4]).toMatchObject({ start: NOW + 16 * HOUR, state: 'idle' });+ });++ it('keeps a used-up limit with no reported reset, bounded by its latest reset', () => {+ // Kimi-style reading: 100% used, no reset time, still within its window.+ const session = accountWindows(+ view({+ session: { latestResetAt: NOW + 2 * HOUR, resetsAt: null, usedPercent: 100 },+ status: 'exhausted',+ }),+ axis,+ NOW,+ );+ expect(session[0]).toMatchObject({+ blockedBy: { estimated: true, key: 'session', until: NOW + 2 * HOUR },+ start: NOW - 3 * HOUR,+ state: 'blocked',+ });+ expect(isUsableAt(session, NOW)).toBe(false);+ expect(session[1]).toMatchObject({ start: NOW + 2 * HOUR, state: 'idle' });++ const weekly = accountWindows(+ view({+ status: 'exhausted',+ weekly: { latestResetAt: NOW + 12 * HOUR, resetsAt: null, usedPercent: 100 },+ }),+ axis,+ NOW,+ );+ expect(weekly.filter((w) => w.state === 'blocked').map((w) => w.start)).toEqual([+ NOW,+ NOW + 5 * HOUR,+ NOW + 10 * HOUR,+ ]);+ expect(weekly[0].blockedBy?.estimated).toBe(true);+ });++ it('flags a nearly used-up window, and every window a tight weekly limit covers', () => {+ const session = accountWindows(+ view({ session: { resetsAt: NOW + HOUR, usedPercent: 85 } }),+ axis,+ NOW,+ );+ expect(session[0]).toMatchObject({ state: 'used', tightBy: { key: 'session' } });+ expect(session[1].tightBy).toBeUndefined();++ const weekly = accountWindows(+ view({+ session: { resetsAt: NOW + HOUR, usedPercent: 30 },+ weekly: { resetsAt: NOW + 5 * HOUR, usedPercent: 88 },+ }),+ axis,+ NOW,+ );+ expect(weekly.slice(0, 3).map((w) => w.tightBy?.key)).toEqual(['weekly', 'weekly', undefined]);+ });+});++describe('isUsableAt / teamBuckets', () => {+ it('counts an account as usable wherever a window holds it and is not blocked', () => {+ const windows = accountWindows(+ view({ session: { resetsAt: NOW + HOUR, usedPercent: 100 }, status: 'exhausted' }),+ axis,+ NOW,+ );++ expect(isUsableAt(windows, NOW)).toBe(false);+ expect(isUsableAt(windows, NOW + 2 * HOUR)).toBe(true);+ });++ it('cuts the axis ahead of now into 5-hour buckets', () => {+ const buckets = teamBuckets(NOW, axis);++ expect(buckets[0]).toEqual({ end: NOW + WINDOW_MS, start: NOW });+ expect(buckets).toHaveLength(Math.ceil((7 * 24) / 5));+ });+});++describe('summarizeQuota', () => {+ it('counts accounts in rotation and finds the soonest reset and recovery', () => {+ const summary = summarizeQuota(+ [+ view({ session: { resetsAt: NOW + 3 * HOUR, usedPercent: 20 } }),+ view({+ recoversAt: NOW + 5 * HOUR,+ session: { resetsAt: NOW + 5 * HOUR, usedPercent: 100 },+ status: 'exhausted',+ }),+ view({ session: { resetsAt: NOW + HOUR, usedPercent: 10 }, status: 'disabled' }),+ view({ status: 'noData' }),+ ],+ NOW,+ );++ expect(summary).toEqual({+ available: 1,+ exhausted: 1,+ nextRecoveryAt: NOW + 5 * HOUR,+ nextResetAt: NOW + 3 * HOUR,+ });+ });+});++describe('resetDayOf', () => {+ it('words a time by the local day it falls on', () => {+ expect(resetDayOf(NOW + 12 * HOUR, NOW)).toBe('today');+ expect(resetDayOf(NOW + 14 * HOUR, NOW)).toBe('tomorrow');+ expect(resetDayOf(NOW + 40 * HOUR, NOW)).toBe('later');+ });+});diff --git a/src/features/SubscriptionAccounts/quotaWindows.ts b/src/features/SubscriptionAccounts/quotaWindows.tsnew file mode 100644index 00000000000..93b8b226a31--- /dev/null+++ b/src/features/SubscriptionAccounts/quotaWindows.ts@@ -0,0 +1,177 @@+import dayjs from 'dayjs';++import type { AccountView, AccountWindowKey } from './accountView';++const HOUR = 60 * 60 * 1000;++/** One coding-agent session window: the unit work is handed out in. */+export const WINDOW_MS = 5 * HOUR;+/** How far ahead the calendar looks. A weekly window resets at most 7 days out. */+export const HORIZON_MS = 7 * 24 * HOUR;++/** A window at or above this share is used up — the load balancer's threshold. */+const EXHAUSTED_PERCENT = 100;+/** A window at or above this share has little left to hand out. */+const TIGHT_PERCENT = 80;++export interface QuotaAxis {+ end: number;+ /** One window before now, so a window under way is drawn whole. */+ start: number;+}++export const buildQuotaAxis = (now: number): QuotaAxis => ({+ end: now + HORIZON_MS,+ start: now - WINDOW_MS,+});++/** A limit that colours a window: which one, how far it is used, and when it resets. */+export interface WindowLimit {+ /** The provider gave no reset time: `until` is the latest it can be. */+ estimated?: boolean;+ key: AccountWindowKey;+ until: number;+ usedPercent: number;+}++export type WindowState =+ /** Nothing spent in it yet. */+ | 'idle'+ /** Partly spent. */+ | 'used'+ /** A used-up limit blocks it. */+ | 'blocked';++export interface QuotaWindow {+ /** The used-up limit behind a `blocked` window. */+ blockedBy?: WindowLimit;+ end: number;+ start: number;+ state: WindowState;+ /** A limit over the tight threshold covers this window. */+ tightBy?: WindowLimit;+ /** Only the window under way has a reading of its own. */+ usedPercent?: number;+}++const liveLimit = (+ view: Pick<AccountView, AccountWindowKey>,+ key: AccountWindowKey,+ now: number,+): WindowLimit | undefined => {+ const window = view[key];+ if (!window) return undefined;+ if (window.resetsAt != null)+ return window.resetsAt > now+ ? { key, until: window.resetsAt, usedPercent: window.usedPercent }+ : undefined;+ // No reported reset: the reading still binds until it ages out, so keep it, marked as a bound.+ if (window.latestResetAt != null && window.latestResetAt > now)+ return { estimated: true, key, until: window.latestResetAt, usedPercent: window.usedPercent };+ return undefined;+};++/**+ * One account's 5-hour windows from the one under way to the end of the axis.+ * Only the current window is known; the ones after it are laid back to back,+ * because a new window starts the moment someone uses the account again. A+ * used-up weekly limit blocks every window that starts before it resets.+ */+export const accountWindows = (+ view: Pick<AccountView, AccountWindowKey>,+ axis: QuotaAxis,+ now: number,+): QuotaWindow[] => {+ const session = liveLimit(view, 'session', now);+ const weekly = liveLimit(view, 'weekly', now);++ const windows: QuotaWindow[] = [];+ // The window under way ends at its reset; with none live, the next one starts now.+ let start = session ? session.until - WINDOW_MS : now;+ for (; start < axis.end; start += WINDOW_MS) {+ const current = !!session && start === session.until - WINDOW_MS;+ const used = current ? session.usedPercent : 0;++ let blockedBy: WindowLimit | undefined;+ if (current && used >= EXHAUSTED_PERCENT) blockedBy = session;+ if (weekly && weekly.usedPercent >= EXHAUSTED_PERCENT && start < weekly.until)+ blockedBy = weekly;++ let tightBy: WindowLimit | undefined;+ if (!blockedBy) {+ if (current && used >= TIGHT_PERCENT) tightBy = session;+ else if (weekly && weekly.usedPercent >= TIGHT_PERCENT && start < weekly.until)+ tightBy = weekly;+ }++ windows.push({+ blockedBy,+ end: start + WINDOW_MS,+ start,+ state: blockedBy ? 'blocked' : used > 0 ? 'used' : 'idle',+ tightBy,+ usedPercent: current ? used : undefined,+ });+ }+ return windows;+};++/** Whether the account can take work at `at`: some window holds it, and it is not blocked. */+export const isUsableAt = (windows: QuotaWindow[], at: number) =>+ windows.some((window) => window.start <= at && at < window.end && window.state !== 'blocked');++/** Fixed 5-hour buckets from now, for counting how many accounts can take work in each. */+export const teamBuckets = (now: number, axis: QuotaAxis) => {+ const buckets: { end: number; start: number }[] = [];+ for (let start = now; start < axis.end; start += WINDOW_MS)+ buckets.push({ end: start + WINDOW_MS, start });+ return buckets;+};++/** Local midnights strictly inside the axis: where one day hands over to the next. */+export const axisMidnights = (axis: QuotaAxis): number[] => {+ const days: number[] = [];+ let day = dayjs(axis.start).startOf('day').add(1, 'day');+ while (day.valueOf() < axis.end) {+ days.push(day.valueOf());+ day = day.add(1, 'day');+ }+ return days;+};++export interface QuotaSummary {+ available: number;+ exhausted: number;+ /** Soonest a used-up account gets capacity back. */+ nextRecoveryAt?: number;+ /** Soonest reset of any window on an account in rotation. */+ nextResetAt?: number;+}++/** The header line: how many accounts can take work now, and when the next one frees up. */+export const summarizeQuota = (views: AccountView[], now: number): QuotaSummary => {+ const soonest = (values: (number | null | undefined)[]) => {+ const ahead = values.filter((value): value is number => value != null && value > now);+ return ahead.length ? Math.min(...ahead) : undefined;+ };+ const inRotation = views.filter((view) => view.status !== 'disabled');+ const exhausted = inRotation.filter((view) => view.status === 'exhausted');++ return {+ available: inRotation.filter((view) => view.status === 'available').length,+ exhausted: exhausted.length,+ nextRecoveryAt: soonest(exhausted.map((view) => view.recoversAt)),+ nextResetAt: soonest(+ inRotation.flatMap((view) => [view.session?.resetsAt, view.weekly?.resetsAt]),+ ),+ };+};++export type ResetDay = 'today' | 'tomorrow' | 'later';++/** Which local day a time falls on, relative to now — how it is worded. */+export const resetDayOf = (at: number, now: number): ResetDay => {+ if (dayjs(at).isSame(now, 'day')) return 'today';+ if (dayjs(at).isSame(dayjs(now).add(1, 'day'), 'day')) return 'tomorrow';+ return 'later';+};diff --git a/src/store/agentQuota/action.ts b/src/store/agentQuota/action.tsindex 6b66667f562..8803a0da676 100644--- a/src/store/agentQuota/action.ts+++ b/src/store/agentQuota/action.ts@@ -142,7 +142,14 @@ export class ActionImpl {});this.#readings = createReplicaSlice(quotaReadingsResource, {actionPrefix: 'quotaReadings',- effects: confirmOn('readings'),+ // Track failures per account: an entry that never loads must not read as "still loading".+ effects: {+ onApplied: (_data, accountId, context) => {+ this.#markApplied('readings', context);+ this.#setReadingsFailed(accountId, false);+ },+ onError: (_error, accountId) => this.#setReadingsFailed(accountId, true),+ },fetcher: (accountId) => agentQuotaService.getLatestReadings(accountId),get,merge: sameValue,@@ -215,8 +222,19 @@ export class ActionImpl {return this.#deviceAccount.useSync(key, this.#syncOptions('deviceAccount', key));};- useFetchQuotaReadings = (accountId?: string | null): ReplicaSyncResult =>- this.#readings.useSync(accountId || null, this.#syncOptions('readings', accountId));+ /**+ * Sync one account's newest readings. A view that stays open while others+ * spend the account (the team capacity calendar) passes a `refreshInterval`+ * so it keeps up; SWR pauses the polling while the tab is hidden.+ */+ useFetchQuotaReadings = (+ accountId?: string | null,+ schedule?: { refreshInterval?: number },+ ): ReplicaSyncResult =>+ this.#readings.useSync(accountId || null, {+ ...this.#syncOptions('readings', accountId),+ ...schedule,+ });useFetchQuotaHistory = (accountId?: string | null): ReplicaSyncResult =>this.#history.useSync(accountId || null, this.#syncOptions('history', accountId));@@ -473,6 +491,17 @@ export class ActionImpl {// ---- internals ----+ #setReadingsFailed = (accountId: string, failed: boolean) => {+ const current = this.#get().quotaReadingsFailed;+ if (!!current[accountId] === failed) return;+ const { [accountId]: _cleared, ...rest } = current;+ this.#set(+ { quotaReadingsFailed: failed ? { ...rest, [accountId]: true } : rest },+ false,+ 'quotaReadingsFailed',+ );+ };+#syncClaudeLocalAccounts = async (): Promise<ClaudeCodeLocalAccount[]> => {const accounts = await heterogeneousAgentService.listClaudeCodeAccounts();const ingested = await Promise.all(diff --git a/src/store/agentQuota/agentQuota.replica.test.ts b/src/store/agentQuota/agentQuota.replica.test.tsindex fae0deb6dc9..e71ae0d2aea 100644--- a/src/store/agentQuota/agentQuota.replica.test.ts+++ b/src/store/agentQuota/agentQuota.replica.test.ts@@ -726,4 +726,69 @@ describe('agent quota replicas', () => {expect(agentQuotaSelectors.history('a1')(useAgentQuotaStore.getState())).toEqual(history);});});++ describe('readings', () => {+ const MINUTE = 60_000;++ it('re-reads on the given interval, so an open view tracks teammates spending the account', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const getLatestReadings = vi+ .spyOn(agentQuotaService, 'getLatestReadings')+ .mockResolvedValue([]);++ renderHook(+ () =>+ useAgentQuotaStore.getState().useFetchQuotaReadings('a1', { refreshInterval: MINUTE }),+ { wrapper },+ );+ await waitFor(() => expect(getLatestReadings).toHaveBeenCalledTimes(1));++ await act(async () => {+ vi.advanceTimersByTime(MINUTE + 1);+ });+ await waitFor(() => expect(getLatestReadings).toHaveBeenCalledTimes(2));+ });++ it('marks an account whose read failed, and clears it once a retry answers', async () => {+ const getLatestReadings = vi+ .spyOn(agentQuotaService, 'getLatestReadings')+ .mockRejectedValueOnce(new Error('network down'))+ .mockResolvedValue([]);++ const { result } = renderHook(+ () => useAgentQuotaStore.getState().useFetchQuotaReadings('a1'),+ { wrapper },+ );+ await waitFor(() =>+ expect(agentQuotaSelectors.readingsFailed('a1')(useAgentQuotaStore.getState())).toBe(true),+ );+ // Only the account that failed is marked.+ expect(agentQuotaSelectors.readingsFailed('a2')(useAgentQuotaStore.getState())).toBe(false);++ await act(async () => {+ await result.current.revalidate();+ });+ await waitFor(() =>+ expect(agentQuotaSelectors.readingsFailed('a1')(useAgentQuotaStore.getState())).toBe(false),+ );+ expect(agentQuotaSelectors.readings('a1')(useAgentQuotaStore.getState())).toEqual([]);+ expect(getLatestReadings).toHaveBeenCalledTimes(2);+ });++ it('reads once without an interval', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ const getLatestReadings = vi+ .spyOn(agentQuotaService, 'getLatestReadings')+ .mockResolvedValue([]);++ renderHook(() => useAgentQuotaStore.getState().useFetchQuotaReadings('a1'), { wrapper });+ await waitFor(() => expect(getLatestReadings).toHaveBeenCalledTimes(1));++ await act(async () => {+ vi.advanceTimersByTime(MINUTE + 1);+ });+ await tick();+ expect(getLatestReadings).toHaveBeenCalledTimes(1);+ });+ });});diff --git a/src/store/agentQuota/initialState.ts b/src/store/agentQuota/initialState.tsindex cd406f9a3df..da90f462fcc 100644--- a/src/store/agentQuota/initialState.ts+++ b/src/store/agentQuota/initialState.ts@@ -46,6 +46,11 @@ export interface State {quotaPanelMap: Record<string, QuotaPanelSnapshot>;/** Replica bookkeeping of `quotaPanelMap`. */quotaPanelReplica: ReplicaState<QuotaPanelSnapshot>;+ /**+ * Accounts whose last readings request failed, keyed by account id. Cleared+ * by the next answer, so a view can tell a failed read from one in flight.+ */+ quotaReadingsFailed: Record<string, true>;/** Replica view of each account's newest readings, keyed by account id. */quotaReadingsMap: Record<string, QuotaLatestReading[]>;/** Replica bookkeeping of `quotaReadingsMap`. */@@ -68,4 +73,5 @@ export const initialState: State = {quotaPanelReplica: createReplicaState(),quotaReadingsMap: {},quotaReadingsReplica: createReplicaState(),+ quotaReadingsFailed: {},};diff --git a/src/store/agentQuota/selectors.ts b/src/store/agentQuota/selectors.tsindex 868e94bb30d..566efcb621c 100644--- a/src/store/agentQuota/selectors.ts+++ b/src/store/agentQuota/selectors.ts@@ -14,6 +14,10 @@ const deviceAccount = (agentId?: string | null, deviceId?: string | null) => (s:const readings = (accountId?: string | null) => (s: Store) =>accountId ? s.quotaReadingsMap[accountId] : undefined;+/** The account's last readings request failed (and nothing has answered since). */+const readingsFailed = (accountId?: string | null) => (s: Store) =>+ !!accountId && !!s.quotaReadingsFailed[accountId];+const history = (accountId?: string | null) => (s: Store) =>accountId ? s.quotaHistoryMap[accountId] : undefined;@@ -51,4 +55,5 @@ export const agentQuotaSelectors = {isHistoryConfirmed,panel,readings,+ readingsFailed,};