Skip to content

🤯 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.

💄 style(quota-calendar): flatten the window list and lead each day with its cost (#18735)

Arvin Xu464dc28aa633
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 649972a6cc6..568ad9b29ca 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -385,6 +385,54 @@ skips AI generation of the acceptance criteria (required when there is no local
key); the criteria editor and budget field are ordinary inputs, while the goal
description is contenteditable (use `fill`; `type` does not support contenteditable).
+#### Reaching the Claude Code usage calendar: a local-execution agent, a live-CLI identity, and a four-table ledger fixture
+
+**Situation:** verifying the quota usage calendar (`AgentQuotaCalendar`), which needs
+both a way to open it and quota history to render.
+
+**Doesn't work:** three separate dead ends.
+
+- Opening the conversation of a heterogeneous agent whose `executionTarget` is
+ `device`. A bound-but-offline device renders the 设备未连接 state and the composer
+ never shows the quota badge, so the panel that owns the calendar entry does not
+ exist. Reads as "this build has no quota UI".
+- Seeding only `agent_quota_windows`. The window rows carry `observed_tokens`, but
+ the UI does not read them: `buildWindowStats` sums the **usage ledger** turns that
+ fall inside each window, and the day cells come from the same ledger. Windows
+ without ledger rows render as 历史未记录,which looks like a broken read model.
+- Assuming the DB account is the one the modal opens. The composer badge reads the
+ **live** identity from the local Claude Code CLI over Electron IPC and passes its
+ `externalAccountId` down; the modal then resolves that against
+ `agent_provider_accounts`. A fixture account whose `external_account_id` differs
+ from the machine's real Claude login yields 账号不可用 with no other signal.
+
+**Works:** set the agent to local execution, then seed four tables against the
+account row the app itself created when it first ingested the live snapshot.
+
+```bash
+# 1. the composer only mounts the quota panel for a local-execution hetero agent
+update agents set agency_config = '{"executionTarget":"local","heterogeneousProvider":{"type":"claude-code","command":"claude"}}'::jsonb where id='<agentId>';
+# 2. reuse the existing account row — its external_account_id already matches the live CLI identity
+select id, external_account_id from agent_provider_accounts where provider='claude-code';
+```
+
+Then insert `agent_quota_usage_ledger` turns (they drive both the day cells and the
+per-window totals), `agent_quota_windows` rows for the concrete reset windows, and
+`agent_quota_snapshots` readings — a reading whose `resets_at` is in the future is
+what makes a window "live" and draws the burn-down curve, and a model-scoped
+`weekly_scoped` reading is what adds the third segment. Derive every timestamp from
+the browser's own timezone, since the calendar groups by local day. After the agent
+config write, clear the SWR cache tiers before reloading or the composer keeps the
+previous execution target.
+
+One seeded value does not survive: opening the composer's quota panel makes the app
+ingest the machine's **live** CLI reading into the same account row. A seeded current
+window is therefore replaced by the real utilization (and the real `resets_at`, which
+merges with a seeded window inside the five-minute tolerance) as soon as the panel
+renders. Seed the history and the ledger, but never assert on the live window's own
+percentage — read it back from `agent_quota_snapshots` and report what the run
+actually rendered.
+
### Driving the UI
#### The composer's slash menu needs real key events — `keyboard type` never opens it
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 0dfa5f613e5..e4c490a6382 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -557,7 +557,6 @@
"heteroAgent.claudeQuota.calendar.burnout.exhausted": "Exhausted — resets {{time}}",
"heteroAgent.claudeQuota.calendar.burnout.safe": "On current pace this window ends around {{percent}}%",
"heteroAgent.claudeQuota.calendar.burnout.willExhaust": "On current pace, quota runs out around {{time}}",
- "heteroAgent.claudeQuota.calendar.capacityUsed": "Capacity used",
"heteroAgent.claudeQuota.calendar.currentWindow": "Current window",
"heteroAgent.claudeQuota.calendar.dayShare": "Used {{percent}}% of this window",
"heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} tokens · {{cost}}",
@@ -572,6 +571,7 @@
"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "History not recorded",
"heteroAgent.claudeQuota.calendar.pace": "Even pace",
"heteroAgent.claudeQuota.calendar.partialCost": "at least {{cost}}",
+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+",
"heteroAgent.claudeQuota.calendar.pastWindow": "Last observed window",
"heteroAgent.claudeQuota.calendar.rateLimited": "Rate limited",
"heteroAgent.claudeQuota.calendar.resetAt": "Window resets at {{time}}",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 1e94d3b3197..fee77a0dd9e 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -557,7 +557,6 @@
"heteroAgent.claudeQuota.calendar.burnout.exhausted": "已耗尽,{{time}} 重置",
"heteroAgent.claudeQuota.calendar.burnout.safe": "按当前速度,本窗口结束时约用到 {{percent}}%",
"heteroAgent.claudeQuota.calendar.burnout.willExhaust": "按当前速度,预计 {{time}} 前后耗尽",
- "heteroAgent.claudeQuota.calendar.capacityUsed": "容量已用",
"heteroAgent.claudeQuota.calendar.currentWindow": "当前窗口",
"heteroAgent.claudeQuota.calendar.dayShare": "占本窗口 {{percent}}%",
"heteroAgent.claudeQuota.calendar.dayTokens": "{{tokens}} tokens · {{cost}}",
@@ -572,6 +571,7 @@
"heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "历史未记录",
"heteroAgent.claudeQuota.calendar.pace": "匀速参考",
"heteroAgent.claudeQuota.calendar.partialCost": "至少 {{cost}}",
+ "heteroAgent.claudeQuota.calendar.partialCostCompact": "{{cost}}+",
"heteroAgent.claudeQuota.calendar.pastWindow": "最近一个观测窗口",
"heteroAgent.claudeQuota.calendar.rateLimited": "已限流",
"heteroAgent.claudeQuota.calendar.resetAt": "{{time}} 窗口重置",
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 1767e7dea64..e82f6153cc7 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -341,7 +341,6 @@ export default {
'On current pace this window ends around {{percent}}%',
'heteroAgent.claudeQuota.calendar.burnout.willExhaust':
'On current pace, quota runs out around {{time}}',
- 'heteroAgent.claudeQuota.calendar.capacityUsed': 'Capacity used',
'heteroAgent.claudeQuota.calendar.dayShare': 'Used {{percent}}% of this window',
'heteroAgent.claudeQuota.calendar.dayTokens': '{{tokens}} tokens · {{cost}}',
'heteroAgent.claudeQuota.calendar.accountUnavailable':
@@ -359,6 +358,7 @@ export default {
'Token history is only recorded for runs started in LobeHub after usage tracking was enabled. Earlier usage and runs started directly from the terminal cannot be backfilled.',
'heteroAgent.claudeQuota.calendar.noLedgerSpendShort': 'History not recorded',
'heteroAgent.claudeQuota.calendar.partialCost': 'at least {{cost}}',
+ 'heteroAgent.claudeQuota.calendar.partialCostCompact': '{{cost}}+',
'heteroAgent.claudeQuota.calendar.pace': 'Even pace',
'heteroAgent.claudeQuota.calendar.pastWindow': 'Last observed window',
'heteroAgent.claudeQuota.calendar.rateLimited': 'Rate limited',
diff --git a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx
index 9243ce605c1..6ca0ea1aabf 100644
--- a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx
+++ b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx
@@ -77,22 +77,18 @@ const styles = createStaticStyles(({ css }) => ({
border-radius: ${cssVar.borderRadiusLG};
background: ${cssVar.colorFillQuaternary};
`,
+ /** The lead number of a day cell: what the day cost. */
cost: css`
- align-self: flex-start;
-
- padding-block: 1px;
- padding-inline: 4px;
- border-radius: ${cssVar.borderRadiusSM};
+ overflow: hidden;
- font-size: 10px;
- font-weight: 500;
- line-height: 14px;
- color: ${cssVar.colorTextSecondary};
+ font-size: 12px;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ line-height: 16px;
+ text-overflow: ellipsis;
/* "at least $404" must stay one line — a wrap pushes it out of the cell. */
white-space: nowrap;
-
- background: ${cssVar.colorBgContainer};
`,
/** Keep the content surface neutral; intensity is carried by the corner dot. */
dayCell: css`
@@ -126,8 +122,9 @@ const styles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorErrorBg};
}
- /* A refused day states itself in one colour, date included. */
- &[data-rate-limited='true'] [data-day-number] {
+ /* A refused day states itself in one colour, date and volume included. */
+ &[data-rate-limited='true'] [data-day-number],
+ &[data-rate-limited='true'] [data-day-secondary] {
color: inherit;
}
@@ -237,9 +234,13 @@ const styles = createStaticStyles(({ css }) => ({
font-size: 12px;
color: ${cssVar.colorTextSecondary};
`,
+ /** Backs up the cost with the volume behind it. */
tokens: css`
- font-size: 11px;
+ font-size: 10px;
font-variant-numeric: tabular-nums;
+ line-height: 14px;
+ color: ${cssVar.colorTextTertiary};
+ white-space: nowrap;
`,
capacityFill: css`
height: 100%;
@@ -293,18 +294,24 @@ const styles = createStaticStyles(({ css }) => ({
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: 4px;
`,
+ /**
+ * One line per window — the row is a scannable comparison, not a card. The
+ * panel around them is the only card; a fill per row would stack a second
+ * surface on it for six rows running, so they are separated by rules instead.
+ */
windowListRow: css`
display: grid;
- grid-template-columns: minmax(0, 1.25fr) minmax(120px, 1fr) minmax(0, 1fr);
+ grid-template-columns: minmax(0, 1.1fr) minmax(110px, 1fr) minmax(0, 1fr);
gap: 12px;
align-items: center;
- min-height: 36px;
- padding-block: 6px;
- padding-inline: 8px;
- border-radius: ${cssVar.borderRadius};
+ min-height: 30px;
+ padding-block: 5px;
+ padding-inline: 2px;
- background: ${cssVar.colorFillQuaternary};
+ &:not(:last-child) {
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ }
`,
sectionPanel: css`
padding: 10px;
@@ -358,13 +365,22 @@ const yOf = (utilization: number) => CHART_H * (1 - utilization / 100);
const formatTrackedCost = (
spend: Pick<DaySpend, 'cost' | 'hasUnpricedTurn'>,
t: TFunction<'chat'>,
+ /**
+ * A day cell is one seventh of the panel: "at least $836" does not fit it as
+ * the lead number, so the cell wears the bound as a suffix and keeps every
+ * amount starting on the `$`.
+ */
+ compact = false,
) => {
const trackedCost = trackedCostOf(spend);
if (trackedCost.kind === 'unknown') return t('heteroAgent.claudeQuota.calendar.unpricedCost');
if (trackedCost.kind === 'lower-bound')
- return t('heteroAgent.claudeQuota.calendar.partialCost', {
- cost: formatCost(trackedCost.cost),
- });
+ return t(
+ compact
+ ? 'heteroAgent.claudeQuota.calendar.partialCostCompact'
+ : 'heteroAgent.claudeQuota.calendar.partialCost',
+ { cost: formatCost(trackedCost.cost) },
+ );
return formatCost(trackedCost.cost);
};
@@ -430,7 +446,9 @@ const BurnChart = memo<{
<Text style={{ fontSize: 12 }} type={'secondary'}>
{spend.tokens > 0
? t('heteroAgent.claudeQuota.calendar.windowSpend', {
- cost: formatTrackedCost(spend, t),
+ // One convention for every amount on this surface; the
+ // spelled-out bound lives in the tooltips.
+ cost: formatTrackedCost(spend, t, true),
tokens: formatTokens(spend.tokens),
})
: t('heteroAgent.claudeQuota.calendar.noLedgerSpend')}
@@ -677,45 +695,49 @@ const WindowHistory = memo<{
{t('heteroAgent.claudeQuota.calendar.weeklyHistoryHint')}
</Text>
</Flexbox>
- {stats.map((stat) => (
- <div className={styles.windowListRow} key={stat.resetsAt}>
- <Flexbox gap={1}>
- <Text style={{ fontSize: 11 }}>
- {dayjs(stat.windowStartAt).format('M/D')} – {dayjs(stat.resetsAt).format('M/D')}
- </Text>
- <Text style={{ fontSize: 10 }} type={'secondary'}>
- {stat.isLive
- ? t('heteroAgent.claudeQuota.calendar.currentWindow')
- : t('heteroAgent.claudeQuota.calendar.pastWindow')}
- </Text>
- </Flexbox>
- <Flexbox gap={4}>
- <Flexbox horizontal align={'center'} justify={'space-between'}>
- <Text style={{ fontSize: 10 }} type={'secondary'}>
- {t('heteroAgent.claudeQuota.calendar.capacityUsed')}
+ <Flexbox>
+ {stats.map((stat) => (
+ <div className={styles.windowListRow} key={stat.resetsAt}>
+ <Flexbox horizontal align={'baseline'} gap={6}>
+ <Text style={{ fontSize: 11, whiteSpace: 'nowrap' }}>
+ {dayjs(stat.windowStartAt).format('M/D')} – {dayjs(stat.resetsAt).format('M/D')}
</Text>
- <Text strong style={{ fontSize: 13 }}>
+ {/* Only the live window needs naming; the rest are read as history. */}
+ {stat.isLive && (
+ <Text style={{ fontSize: 10, whiteSpace: 'nowrap' }} type={'secondary'}>
+ {t('heteroAgent.claudeQuota.calendar.currentWindow')}
+ </Text>
+ )}
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Flexbox flex={1} style={{ minWidth: 0 }}>
+ <CapacityMeter utilization={stat.peakUtilization} />
+ </Flexbox>
+ <Text strong style={{ flex: 'none', fontSize: 12, textAlign: 'right', width: 34 }}>
{Math.round(stat.peakUtilization)}%
</Text>
</Flexbox>
- <CapacityMeter utilization={stat.peakUtilization} />
- </Flexbox>
- {stat.tokens > 0 ? (
- <Text style={{ fontSize: 11, textAlign: 'right' }} type={'secondary'}>
- {formatTokens(stat.tokens)} · {formatTrackedCost(stat, t)}
- </Text>
- ) : (
- <Tooltip title={t('heteroAgent.claudeQuota.calendar.noLedgerSpendHint')}>
- <Flexbox horizontal align={'center'} gap={4} justify={'flex-end'}>
- <Icon color={cssVar.colorTextTertiary} icon={InfoIcon} size={11} />
- <Text style={{ fontSize: 11 }} type={'secondary'}>
- {t('heteroAgent.claudeQuota.calendar.noLedgerSpendShort')}
+ {stat.tokens > 0 ? (
+ /* The `+` is the compact bound; hovering spells it out, the way
+ the session grid already explains its own cells. */
+ <Tooltip title={windowTooltip(stat, t).join(' · ')}>
+ <Text style={{ fontSize: 11, textAlign: 'right' }} type={'secondary'}>
+ {formatTokens(stat.tokens)} · {formatTrackedCost(stat, t, true)}
</Text>
- </Flexbox>
- </Tooltip>
- )}
- </div>
- ))}
+ </Tooltip>
+ ) : (
+ <Tooltip title={t('heteroAgent.claudeQuota.calendar.noLedgerSpendHint')}>
+ <Flexbox horizontal align={'center'} gap={4} justify={'flex-end'}>
+ <Icon color={cssVar.colorTextTertiary} icon={InfoIcon} size={11} />
+ <Text style={{ fontSize: 11 }} type={'secondary'}>
+ {t('heteroAgent.claudeQuota.calendar.noLedgerSpendShort')}
+ </Text>
+ </Flexbox>
+ </Tooltip>
+ )}
+ </div>
+ ))}
+ </Flexbox>
</Flexbox>
);
});
@@ -876,11 +898,18 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {
</Text>
);
- const dayLabel = (spend: DaySpend | undefined, burn: number) => {
- if (spend && spend.tokens > 0) return formatTokens(spend.tokens);
+ /**
+ * A day is read as money first: the cost leads, the token count backs it up.
+ * With no priced turn the strongest number left takes the lead instead.
+ */
+ const dayLabels = (spend: DaySpend | undefined, burn: number) => {
+ const cost =
+ spend && (spend.cost > 0 || spend.hasUnpricedTurn) ? formatTrackedCost(spend, t, true) : '';
+ const tokens = spend && spend.tokens > 0 ? formatTokens(spend.tokens) : '';
// No ledger row (usage burned outside LobeHub) but the meter still moved.
- if (burn > 0) return `${Math.round(burn)}%`;
- return '';
+ const share = !tokens && burn > 0 ? `${Math.round(burn)}%` : '';
+ const fallback = tokens || share;
+ return cost ? { primary: cost, secondary: fallback } : { primary: fallback, secondary: '' };
};
const hasWindowColumn = Boolean(chartWindow) || windowStats.length > 0;
@@ -953,7 +982,7 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {
const resetsAt = resetsByDay.get(cell.key);
const rateLimited = rateLimitedDays.has(cell.key);
const heatLevel = dailyHeatLevels.get(cell.key) ?? 0;
- const label = dayLabel(spend, burn);
+ const { primary, secondary } = dayLabels(spend, burn);
const tooltipParts = [
spend &&
spend.tokens > 0 &&
@@ -983,7 +1012,7 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {
<span aria-hidden className={styles.heatDot} data-heat={heatLevel} />
)}
<span className={styles.dayFooter}>
- <span className={styles.tokens}>{label}</span>
+ <span className={styles.cost}>{primary}</span>
<span style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}>
{rateLimited && <Icon color={cssVar.colorError} icon={BanIcon} size={12} />}
{resetsAt && (
@@ -991,8 +1020,10 @@ const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {
)}
</span>
</span>
- {spend && (spend.cost > 0 || spend.hasUnpricedTurn) && (
- <span className={styles.cost}>{formatTrackedCost(spend, t)}</span>
+ {secondary && (
+ <span data-day-secondary className={styles.tokens}>
+ {secondary}
+ </span>
)}
</div>
);
diff --git a/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts b/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts
index 3d49e4184e3..f2cbc3771de 100644
--- a/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts
+++ b/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts
@@ -6,6 +6,7 @@ import {
buildDailySpend,
buildSessionGrid,
buildWindowStats,
+ formatTokens,
isCalendarMonthAvailable,
type QuotaWindowSpan,
selectQuotaAccount,
@@ -181,3 +182,20 @@ describe('quota calendar window statistics', () => {
expect(utilizationStatusOf(utilization)).toBe(status);
});
});
+
+describe('formatTokens', () => {
+ it('keeps sub-billion counts in K and M', () => {
+ expect(formatTokens(820)).toBe('820');
+ expect(formatTokens(340_000)).toBe('340K');
+ expect(formatTokens(1_200_000)).toBe('1.2M');
+ expect(formatTokens(585_000_000)).toBe('585M');
+ expect(formatTokens(999_400_000)).toBe('999M');
+ });
+
+ it('steps up to B past a billion instead of printing four-digit M', () => {
+ expect(formatTokens(1_000_000_000)).toBe('1.0B');
+ expect(formatTokens(1_319_000_000)).toBe('1.3B');
+ expect(formatTokens(3_136_000_000)).toBe('3.1B');
+ expect(formatTokens(12_500_000_000)).toBe('13B');
+ });
+});
diff --git a/src/features/AgentQuotaCalendar/quotaCalendarModel.ts b/src/features/AgentQuotaCalendar/quotaCalendarModel.ts
index b355db06d4d..5f645c83731 100644
--- a/src/features/AgentQuotaCalendar/quotaCalendarModel.ts
+++ b/src/features/AgentQuotaCalendar/quotaCalendarModel.ts
@@ -459,8 +459,10 @@ export const buildMonthGrid = (month: dayjs.Dayjs): CalendarDayCell[] => {
});
};
-/** Compact token count for a calendar cell: 1.2M / 340K / 820. */
+/** Compact token count for a calendar cell: 1.3B / 585M / 340K / 820. */
export const formatTokens = (tokens: number): string => {
+ if (tokens >= 1_000_000_000)
+ return `${(tokens / 1_000_000_000).toFixed(tokens >= 10_000_000_000 ? 0 : 1)}B`;
if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(tokens >= 10_000_000 ? 0 : 1)}M`;
if (tokens >= 1000) return `${Math.round(tokens / 1000)}K`;
return String(Math.round(tokens));