🤯 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(agent-quota): add usage calendar and burnout projection (#18117)
Arvin Xu2345aa1f3779
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 503657f5376..85db7b1950c 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -1111,6 +1111,44 @@ every `[startAt, endAt)` from that. When a day view comes back empty, diff theclient's real request window (fetch wrapper on the batch URL) against the seededtimestamps before suspecting the query.+### An `ActionIcon` is not a `<button>` — select it by its lucide class, click through agent-browser++**Situation:** driving an icon-only affordance inside a popover or panel (`ActionIcon`+from `@lobehub/ui`: refresh, calendar, more, …).++**Doesn't work:** three separate near-misses, each of which reads as "the affordance+does not exist" rather than as a driving error:++- `pop.querySelectorAll('button')` misses it. `ActionIcon` renders a `div`/`span`+ wrapper (`class="lobe-flex …"` around `span.anticon`), so a button-only sweep of a+ popover reports zero controls and invites the wrong conclusion that the entry was+ never rendered.+- `el.click()` on that wrapper `div` resolves and returns, but no handler runs — the+ React `onClick` sits on an inner node, so the tab-clicking recipe above does not+ transfer to icon buttons.+- `agent-browser click --x <n> --y <n>` is not a thing; `click` only takes a CSS+ selector, XPath, or an `@eN` snapshot ref, and coordinates fail with the generic+ `Element not found`, which reads as a missing element rather than a bad invocation.++**Works:** find the icon by its lucide class, tag it, and let agent-browser do the+real click:++```bash+agent-browser --cdp 9222 eval '(() => {+ const pop = [...document.querySelectorAll("[role=dialog]")].pop();+ pop.querySelector("svg.lucide-calendar-days").setAttribute("data-qc", "entry");+ return "tagged";+})()'+agent-browser --cdp 9222 click "[data-qc=entry]"+```++Enumerate candidates with `pop.querySelectorAll("button,[role=button],span[role]")`+and read each node's `svg` class when the icon's identity is unknown. Two follow-ons+worth knowing: a stray click on a tagged text node can dismiss the popover (re-open+and re-tag rather than assuming the control vanished), and a `Tooltip`-wrapped cell+needs a real pointer move (`Input.dispatchMouseEvent` over several coordinates, or a+dispatched `pointerover`+`mouseover` pair) before its content mounts.+## Detailed references- [Probe field notes](./references/probe-field-notes.md) — all historicaldiff --git a/apps/server/src/routers/lambda/agentQuota.ts b/apps/server/src/routers/lambda/agentQuota.tsindex ea7c0c3e928..318084a54d1 100644--- a/apps/server/src/routers/lambda/agentQuota.ts+++ b/apps/server/src/routers/lambda/agentQuota.ts@@ -180,6 +180,33 @@ export const agentQuotaRouter = router({.input(z.object({ accountId: z.string() })).query(async ({ ctx, input }) => ctx.quotaService.listLatestReadings(input.accountId)),+ /**+ * Full reading time series (oldest first) for the usage calendar's daily+ * burn heat and per-window burn-down curve.+ */+ listSnapshots: quotaProcedure+ .input(z.object({ accountId: z.string(), sinceDays: z.number().min(1).max(90).optional() }))+ .query(async ({ ctx, input }) =>+ ctx.quotaService.listSnapshotSeries(+ input.accountId,+ new Date(Date.now() - (input.sinceDays ?? 42) * 24 * 60 * 60 * 1000),+ ),+ ),++ /**+ * Per-turn token + cost spend (oldest first) for the usage calendar. Kept+ * separate from `listSnapshots`: utilization is the provider's authority on+ * "how much quota is left", the ledger is ours on "what it was spent on".+ */+ listUsageTurns: quotaProcedure+ .input(z.object({ accountId: z.string(), sinceDays: z.number().min(1).max(90).optional() }))+ .query(async ({ ctx, input }) =>+ ctx.quotaService.listUsageTurns(+ input.accountId,+ new Date(Date.now() - (input.sinceDays ?? 42) * 24 * 60 * 60 * 1000),+ ),+ ),+// ── load balancing ───────────────────────────────────────────────────────resolveAccountLoads: quotaProcedure.input(z.object({ accountIds: z.array(z.string()) }))diff --git a/apps/server/src/services/agentQuota/index.ts b/apps/server/src/services/agentQuota/index.tsindex fabc3a6cff7..f6e19906cd2 100644--- a/apps/server/src/services/agentQuota/index.ts+++ b/apps/server/src/services/agentQuota/index.ts@@ -39,6 +39,16 @@ export interface AccountLoadView extends AccountLoad {label?: string | null;}+/** One assistant turn's spend, as the usage calendar consumes it. */+export interface QuotaUsageTurn {+ /** USD, or null when the model bank has no price for the model. */+ cost: number | null;+ model: string | null;+ occurredAt: number;+ /** All token classes summed — what "tokens burned" means to the user. */+ tokens: number;+}+/*** Server-side orchestration for the quota data layer: turns the append-only* snapshot + ledger facts into windows and calibrated capacity, and resolves@@ -268,6 +278,46 @@ export class AgentQuotaService {}));};+ /**+ * The full reading series since `since`, oldest first — the burn-down /+ * usage-calendar read model. Same plain-number mapping as+ * `listLatestReadings`.+ */+ listSnapshotSeries = async (accountId: string, since: Date): Promise<QuotaLimitReading[]> => {+ const rows = await this.snapshots.listRange(accountId, since);++ return rows.map((row) => ({+ capturedAt: row.capturedAt.getTime(),+ isActive: row.isActive ?? undefined,+ limitType: row.limitType,+ resetsAt: row.resetsAt?.getTime() ?? null,+ scopeKey: row.scopeKey,+ severity: row.severity ?? undefined,+ utilization: row.utilization,+ }));+ };++ /**+ * Per-turn spend since `since`, oldest first — the token/cost half of the+ * usage calendar. Returned as flat turns rather than pre-bucketed days: the+ * calendar groups by the *viewer's* local day, which the server cannot know.+ */+ listUsageTurns = async (accountId: string, since: Date): Promise<QuotaUsageTurn[]> => {+ const rows = await this.ledger.listSince(accountId, since);++ return rows.map((row) => ({+ cost: row.costUsd == null ? null : Number(row.costUsd),+ model: row.model,+ occurredAt: row.occurredAt.getTime(),+ tokens:+ (row.inputTokens ?? 0) ++ (row.outputTokens ?? 0) ++ (row.cacheReadTokens ?? 0) ++ (row.cacheWriteTokens ?? 0) ++ (row.reasoningTokens ?? 0),+ }));+ };+/** Build the LB load view for a set of accounts from their latest readings. */resolveAccountLoads = async (accountIds: string[],diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 597a47eab97..949747af6e3 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -499,6 +499,38 @@"heteroAgent.claudeQuota.accountActive": "In use","heteroAgent.claudeQuota.accountSwitch": "Switch","heteroAgent.claudeQuota.accounts": "Accounts",+ "heteroAgent.claudeQuota.calendar.accountUnavailable": "The quota account for this snapshot is unavailable",+ "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}}",+ "heteroAgent.claudeQuota.calendar.empty": "Not enough usage history yet — run a few tasks and check back.",+ "heteroAgent.claudeQuota.calendar.entry": "Usage calendar",+ "heteroAgent.claudeQuota.calendar.legendLess": "Light",+ "heteroAgent.claudeQuota.calendar.legendMore": "Heavy",+ "heteroAgent.claudeQuota.calendar.legendReset": "Window reset",+ "heteroAgent.claudeQuota.calendar.monthSpend": "Daily spend",+ "heteroAgent.claudeQuota.calendar.noLedgerSpend": "No token usage recorded in this window",+ "heteroAgent.claudeQuota.calendar.noLedgerSpendHint": "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.pace": "Even pace",+ "heteroAgent.claudeQuota.calendar.partialCost": "at least {{cost}}",+ "heteroAgent.claudeQuota.calendar.pastWindow": "Last observed window",+ "heteroAgent.claudeQuota.calendar.rateLimited": "Rate limited",+ "heteroAgent.claudeQuota.calendar.resetAt": "Window resets at {{time}}",+ "heteroAgent.claudeQuota.calendar.sessionHistory": "5-hour windows",+ "heteroAgent.claudeQuota.calendar.sessionHistoryHint": "Recent 7 days · each cell is one window",+ "heteroAgent.claudeQuota.calendar.sessionWindow": "Session (5h)",+ "heteroAgent.claudeQuota.calendar.title": "Claude Code usage calendar",+ "heteroAgent.claudeQuota.calendar.unpricedCost": "cost unavailable",+ "heteroAgent.claudeQuota.calendar.usedOfWindow": "of this window used",+ "heteroAgent.claudeQuota.calendar.weeklyHistory": "Weekly windows",+ "heteroAgent.claudeQuota.calendar.weeklyHistoryHint": "Recent windows",+ "heteroAgent.claudeQuota.calendar.windowSpend": "{{tokens}} tokens · {{cost}} this window",+ "heteroAgent.claudeQuota.calendar.windowUtilization": "{{percent}}% used","heteroAgent.claudeQuota.errorGeneric": "Couldn't reach the quota service. Tap refresh to retry.","heteroAgent.claudeQuota.errorRateLimited": "Claude Code quota is temporarily rate limited. Please try again later.","heteroAgent.claudeQuota.manage.addHint": "Sign in to the Claude Code CLI and the account shows up here automatically.",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex c6e9b353839..77030b9338e 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -499,6 +499,38 @@"heteroAgent.claudeQuota.accountActive": "使用中","heteroAgent.claudeQuota.accountSwitch": "切换","heteroAgent.claudeQuota.accounts": "账号",+ "heteroAgent.claudeQuota.calendar.accountUnavailable": "当前快照对应的额度账号不可用",+ "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}}",+ "heteroAgent.claudeQuota.calendar.empty": "用量数据还不够,先跑几轮任务再来看看。",+ "heteroAgent.claudeQuota.calendar.entry": "用量日历",+ "heteroAgent.claudeQuota.calendar.legendLess": "少",+ "heteroAgent.claudeQuota.calendar.legendMore": "多",+ "heteroAgent.claudeQuota.calendar.legendReset": "窗口重置",+ "heteroAgent.claudeQuota.calendar.monthSpend": "每日开销",+ "heteroAgent.claudeQuota.calendar.noLedgerSpend": "本窗口暂无 token 用量记录",+ "heteroAgent.claudeQuota.calendar.noLedgerSpendHint": "token 历史只记录启用用量追踪后、由 LobeHub 发起的运行;更早的用量以及直接从终端发起的运行无法回填。",+ "heteroAgent.claudeQuota.calendar.noLedgerSpendShort": "历史未记录",+ "heteroAgent.claudeQuota.calendar.pace": "匀速参考",+ "heteroAgent.claudeQuota.calendar.partialCost": "至少 {{cost}}",+ "heteroAgent.claudeQuota.calendar.pastWindow": "最近一个观测窗口",+ "heteroAgent.claudeQuota.calendar.rateLimited": "已限流",+ "heteroAgent.claudeQuota.calendar.resetAt": "{{time}} 窗口重置",+ "heteroAgent.claudeQuota.calendar.sessionHistory": "5 小时窗口",+ "heteroAgent.claudeQuota.calendar.sessionHistoryHint": "最近 7 天 · 每格一个窗口",+ "heteroAgent.claudeQuota.calendar.sessionWindow": "会话(5 小时)",+ "heteroAgent.claudeQuota.calendar.title": "Claude Code 用量日历",+ "heteroAgent.claudeQuota.calendar.unpricedCost": "费用未知",+ "heteroAgent.claudeQuota.calendar.usedOfWindow": "本窗口已用",+ "heteroAgent.claudeQuota.calendar.weeklyHistory": "周限额窗口",+ "heteroAgent.claudeQuota.calendar.weeklyHistoryHint": "最近窗口",+ "heteroAgent.claudeQuota.calendar.windowSpend": "本窗口 {{tokens}} tokens · {{cost}}",+ "heteroAgent.claudeQuota.calendar.windowUtilization": "已用 {{percent}}%","heteroAgent.claudeQuota.errorGeneric": "无法连接额度服务,点击刷新重试。","heteroAgent.claudeQuota.errorRateLimited": "Claude Code 额度查询暂时被限流,请稍后再试。","heteroAgent.claudeQuota.manage.addHint": "在 Claude Code CLI 中登录后,账号会自动出现在这里。",diff --git a/packages/database/src/models/agentQuota.ts b/packages/database/src/models/agentQuota.tsindex 13f7be93671..c8b0d0c0be1 100644--- a/packages/database/src/models/agentQuota.ts+++ b/packages/database/src/models/agentQuota.ts@@ -316,6 +316,20 @@ export class AgentQuotaSnapshotModel {.returning();};+ /** Full reading series for an account since an instant, oldest first. */+ listRange = async (accountId: string, since: Date) =>+ this.db+ .select()+ .from(agentQuotaSnapshots)+ .where(+ and(+ this.mine(),+ eq(agentQuotaSnapshots.accountId, accountId),+ gte(agentQuotaSnapshots.capturedAt, since),+ ),+ )+ .orderBy(agentQuotaSnapshots.capturedAt);+/** The most recent reading per (limitType, scopeKey) for an account. */latestPerBucket = async (accountId: string) =>this.db@@ -362,6 +376,33 @@ export class AgentQuotaUsageLedgerModel {}).returning();+ /**+ * Per-turn token + cost rows for an account since an instant, oldest first.+ * The calendar aggregates these by local day, so the bucketing has to happen+ * in the client's timezone rather than the database's.+ */+ listSince = async (accountId: string, since: Date) =>+ this.db+ .select({+ cacheReadTokens: agentQuotaUsageLedger.cacheReadTokens,+ cacheWriteTokens: agentQuotaUsageLedger.cacheWriteTokens,+ costUsd: agentQuotaUsageLedger.costUsd,+ inputTokens: agentQuotaUsageLedger.inputTokens,+ model: agentQuotaUsageLedger.model,+ occurredAt: agentQuotaUsageLedger.occurredAt,+ outputTokens: agentQuotaUsageLedger.outputTokens,+ reasoningTokens: agentQuotaUsageLedger.reasoningTokens,+ })+ .from(agentQuotaUsageLedger)+ .where(+ and(+ this.mine(),+ eq(agentQuotaUsageLedger.accountId, accountId),+ gte(agentQuotaUsageLedger.occurredAt, since),+ ),+ )+ .orderBy(agentQuotaUsageLedger.occurredAt);+/** 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/chat.ts b/packages/locales/src/default/chat.tsindex ca7280a483d..00a5e26c086 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -321,6 +321,43 @@ export default {'heteroAgent.claudeQuota.accountActive': 'In use','heteroAgent.claudeQuota.accountSwitch': 'Switch','heteroAgent.claudeQuota.accounts': 'Accounts',+ '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.dayShare': 'Used {{percent}}% of this window',+ 'heteroAgent.claudeQuota.calendar.dayTokens': '{{tokens}} tokens · {{cost}}',+ 'heteroAgent.claudeQuota.calendar.accountUnavailable':+ 'The quota account for this snapshot is unavailable',+ 'heteroAgent.claudeQuota.calendar.currentWindow': 'Current window',+ 'heteroAgent.claudeQuota.calendar.empty':+ 'Not enough usage history yet — run a few tasks and check back.',+ 'heteroAgent.claudeQuota.calendar.entry': 'Usage calendar',+ 'heteroAgent.claudeQuota.calendar.legendLess': 'Light',+ 'heteroAgent.claudeQuota.calendar.legendMore': 'Heavy',+ 'heteroAgent.claudeQuota.calendar.legendReset': 'Window reset',+ 'heteroAgent.claudeQuota.calendar.monthSpend': 'Daily spend',+ 'heteroAgent.claudeQuota.calendar.noLedgerSpend': 'No token usage recorded in this window',+ 'heteroAgent.claudeQuota.calendar.noLedgerSpendHint':+ '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.pace': 'Even pace',+ 'heteroAgent.claudeQuota.calendar.pastWindow': 'Last observed window',+ 'heteroAgent.claudeQuota.calendar.rateLimited': 'Rate limited',+ 'heteroAgent.claudeQuota.calendar.resetAt': 'Window resets at {{time}}',+ 'heteroAgent.claudeQuota.calendar.sessionWindow': 'Session (5h)',+ 'heteroAgent.claudeQuota.calendar.sessionHistory': '5-hour windows',+ 'heteroAgent.claudeQuota.calendar.sessionHistoryHint': 'Recent 7 days · each cell is one window',+ 'heteroAgent.claudeQuota.calendar.title': 'Claude Code usage calendar',+ 'heteroAgent.claudeQuota.calendar.usedOfWindow': 'of this window used',+ 'heteroAgent.claudeQuota.calendar.weeklyHistory': 'Weekly windows',+ 'heteroAgent.claudeQuota.calendar.weeklyHistoryHint': 'Recent windows',+ 'heteroAgent.claudeQuota.calendar.windowSpend': '{{tokens}} tokens · {{cost}} this window',+ 'heteroAgent.claudeQuota.calendar.unpricedCost': 'cost unavailable',+ 'heteroAgent.claudeQuota.calendar.windowUtilization': '{{percent}}% used','heteroAgent.claudeQuota.manage.addHint':'Sign in to the Claude Code CLI and the account shows up here automatically.','heteroAgent.claudeQuota.manage.autoNoAccount': 'No eligible account — enable one below.',diff --git a/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsxnew file mode 100644index 00000000000..65bb40a8d2b--- /dev/null+++ b/src/features/AgentQuotaCalendar/QuotaCalendarModal.tsx@@ -0,0 +1,1003 @@+'use client';++import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';+import { ActionIcon, Flexbox, Icon, Skeleton, Text, Tooltip } from '@lobehub/ui';+import { createModal, type ModalInstance, Segmented } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import dayjs from 'dayjs';+import type { TFunction } from 'i18next';+import { t as i18nT } from 'i18next';+import { BanIcon, ChevronLeftIcon, ChevronRightIcon, InfoIcon, RotateCcwIcon } from 'lucide-react';+import { memo, useEffect, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { agentQuotaService } from '@/services/agentQuota';++import {+ buildBurnSeries,+ buildDailyBurn,+ buildDailyHeatLevels,+ buildDailySpend,+ buildMonthGrid,+ buildSessionGrid,+ buildWindowStats,+ currentWindow,+ dayKeyOf,+ type DaySpend,+ formatCost,+ formatTokens,+ isCalendarMonthAvailable,+ projectBurnout,+ type QuotaSeriesKey,+ type QuotaWindowSpan,+ selectQuotaAccount,+ seriesId,+ SESSION_SERIES,+ shouldShowHeatDot,+ spendInWindow,+ trackedCostOf,+ type UsageTurn,+ utilizationStatusOf,+ type WindowStat,+} from './quotaCalendarModel';++const styles = createStaticStyles(({ css }) => ({+ calendarGrid: css`+ display: grid;+ grid-template-columns: repeat(7, 1fr);+ gap: 4px;+ `,+ chartFrame: css`+ padding: 4px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillQuaternary};+ `,+ cost: css`+ align-self: flex-start;++ padding-block: 1px;+ padding-inline: 4px;+ border-radius: ${cssVar.borderRadiusSM};++ font-size: 10px;+ font-weight: 500;+ line-height: 14px;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorBgContainer};+ `,+ /** Keep the content surface neutral; intensity is carried by the corner dot. */+ dayCell: css`+ position: relative;++ display: flex;+ flex-direction: column;+ justify-content: space-between;++ height: 58px;+ padding-block: 4px;+ padding-inline: 6px;+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;++ background: ${cssVar.colorFillQuaternary};++ &[data-in-month='false'] {+ opacity: 0.35;+ }++ /* Rate limited: the provider refused work that day — an error state, not heat. */+ &[data-rate-limited='true'] {+ color: ${cssVar.colorErrorText};+ background: ${cssVar.colorErrorBg};+ }++ &[data-today='true'] {+ box-shadow: inset 0 0 0 1.5px ${cssVar.colorPrimary};+ }+ `,+ dayFooter: css`+ display: flex;+ gap: 4px;+ align-items: flex-end;+ justify-content: space-between;++ min-height: 14px;+ `,+ heatDot: css`+ position: absolute;+ inset-block-start: 6px;+ inset-inline-end: 6px;++ width: 4px;+ height: 4px;+ border-radius: 50%;++ opacity: 0.45;+ background: ${cssVar.colorSuccess};++ &[data-heat='2'] {+ width: 6px;+ height: 6px;+ opacity: 0.65;+ }++ &[data-heat='3'] {+ width: 8px;+ height: 8px;+ opacity: 0.82;+ }++ &[data-heat='4'] {+ width: 10px;+ height: 10px;+ opacity: 1;+ }++ &[data-legend='true'] {+ position: relative;+ inset: auto;+ flex: none;+ }+ `,+ legendSwatch: css`+ width: 10px;+ height: 10px;+ border-radius: 3px;+ background: ${cssVar.colorFillQuaternary};++ &[data-rate-limited='true'] {+ background: ${cssVar.colorErrorBg};+ }+ `,+ capacityRing: css`+ position: relative;++ display: grid;+ flex: none;+ place-items: center;++ width: 54px;+ height: 54px;++ color: ${cssVar.colorSuccess};++ &[data-status='warning'] {+ color: ${cssVar.colorWarning};+ }++ &[data-status='error'] {+ color: ${cssVar.colorError};+ }+ `,+ capacityRingLabel: css`+ position: absolute;++ font-size: 13px;+ font-weight: 600;+ font-variant-numeric: tabular-nums;+ color: currentcolor;+ `,+ capacityRingSvg: css`+ transform: rotate(-90deg);+ display: block;+ width: 100%;+ height: 100%;+ `,+ statusExhausted: css`+ font-size: 12px;+ color: ${cssVar.colorErrorText};+ `,+ /* A forecast is a warning, not a failure — the quota has not run out yet. */+ statusForecast: css`+ font-size: 12px;+ color: ${cssVar.colorWarningText};+ `,+ statusSafe: css`+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ tokens: css`+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ `,+ capacityFill: css`+ height: 100%;+ border-radius: inherit;+ background: ${cssVar.colorSuccess};++ &[data-status='warning'] {+ background: ${cssVar.colorWarning};+ }++ &[data-status='error'] {+ background: ${cssVar.colorError};+ }+ `,+ capacityTrack: css`+ overflow: hidden;++ width: 100%;+ height: 5px;+ border-radius: 999px;++ background: ${cssVar.colorFillSecondary};+ `,+ windowCell: css`+ display: flex;+ flex-direction: column;+ gap: 3px;++ min-width: 0;+ height: 54px;+ padding: 4px;+ border-radius: ${cssVar.borderRadiusSM};++ font-size: 10px;+ font-variant-numeric: tabular-nums;+ line-height: 1.2;+ color: ${cssVar.colorTextSecondary};++ background: ${cssVar.colorBgContainer};++ &[data-rate-limited='true'] {+ color: ${cssVar.colorErrorText};+ background: ${cssVar.colorErrorBg};+ }+ `,+ windowGrid: css`+ display: grid;+ grid-template-columns: repeat(7, minmax(0, 1fr));+ gap: 4px;+ `,+ windowListRow: css`+ display: grid;+ grid-template-columns: minmax(0, 1.25fr) minmax(120px, 1fr) minmax(0, 1fr);+ gap: 12px;+ align-items: center;++ min-height: 36px;+ padding-block: 6px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};++ background: ${cssVar.colorFillQuaternary};+ `,+ windowSection: css`+ padding: 10px;+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorFillQuaternary};+ `,+ windowSpend: css`+ overflow: hidden;++ font-size: 9px;+ color: ${cssVar.colorTextTertiary};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ weekday: css`+ font-size: 11px;+ color: ${cssVar.colorTextQuaternary};+ text-align: center;+ `,+}));++type WindowRow = Awaited<ReturnType<typeof agentQuotaService.getWindows>>[number];++const toMs = (value: Date | number | string | null | undefined): number | null =>+ value == null ? null : new Date(value).getTime();++interface NormalizedWindow extends QuotaWindowSpan {+ seriesId: string;+}++const normalizeWindows = (rows: WindowRow[]): NormalizedWindow[] =>+ rows.map((row) => ({+ peakUtilization: row.peakUtilization,+ rateLimitedAt: toMs(row.rateLimitedAt),+ resetsAt: toMs(row.resetsAt)!,+ seriesId: row.limitType.startsWith('weekly') ? `weekly:${row.scopeKey || ''}` : 'session:',+ windowStartAt: toMs(row.windowStartAt)!,+ }));++const CHART_W = 640;+const CHART_H = 120;+const HISTORY_DAYS = 90;+const RING_RADIUS = 22;+const RING_CIRCUMFERENCE = 2 * Math.PI * RING_RADIUS;++const xOf = (time: number, window: QuotaWindowSpan) =>+ ((time - window.windowStartAt) / (window.resetsAt - window.windowStartAt)) * CHART_W;+const yOf = (utilization: number) => CHART_H * (1 - utilization / 100);++const formatTrackedCost = (+ spend: Pick<DaySpend, 'cost' | 'hasUnpricedTurn'>,+ t: TFunction<'chat'>,+) => {+ 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 formatCost(trackedCost.cost);+};++/**+ * Burn-down curve for one window: actual utilization against the even-pace+ * diagonal, extended by a dashed projection at the current pace, plus what the+ * window actually cost in tokens and dollars.+ */+const BurnChart = memo<{+ now: number;+ readings: QuotaLimitReading[];+ series: QuotaSeriesKey;+ turns: UsageTurn[];+ window: QuotaWindowSpan;+}>(({ now, readings, series, turns, window }) => {+ const { t } = useTranslation('chat');++ const points = useMemo(+ () => buildBurnSeries(readings, series, window),+ [readings, series, window],+ );+ const isLive = window.resetsAt > now;+ const projection = useMemo(() => projectBurnout(points, window), [points, window]);+ const spend = useMemo(() => spendInWindow(turns, window), [turns, window]);++ const last = points.at(-1)!;+ const polyline = points.map((p) => `${xOf(p.time, window)},${yOf(p.utilization)}`).join(' ');+ const area = `M0,${CHART_H} L${polyline.replaceAll(' ', ' L')} L${xOf(last.time, window)},${CHART_H} Z`;++ const projectionEnd =+ projection.kind === 'exhaust'+ ? { time: projection.exhaustAt, utilization: 100 }+ : projection.kind === 'safe'+ ? { time: window.resetsAt, utilization: projection.projectedEndUtilization }+ : null;+ const willExhaust = projection.kind === 'exhaust';+ const exhausted = projection.kind === 'exhausted';+ const timeFormat = series.type === 'session' ? 'HH:mm' : 'M/D HH:mm';++ const statusText = !isLive+ ? t('heteroAgent.claudeQuota.calendar.pastWindow')+ : exhausted+ ? t('heteroAgent.claudeQuota.calendar.burnout.exhausted', {+ time: dayjs(window.resetsAt).format(timeFormat),+ })+ : willExhaust+ ? t('heteroAgent.claudeQuota.calendar.burnout.willExhaust', {+ time: dayjs(projection.exhaustAt).format(timeFormat),+ })+ : t('heteroAgent.claudeQuota.calendar.burnout.safe', {+ percent: Math.round(projection.projectedEndUtilization),+ });++ return (+ <Flexbox gap={8}>+ <Flexbox horizontal align={'flex-end'} gap={12} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={10}>+ <CapacityRing utilization={last.utilization} />+ <Flexbox gap={2}>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {t('heteroAgent.claudeQuota.calendar.usedOfWindow')}+ </Text>+ <Text style={{ fontSize: 12 }} type={'secondary'}>+ {spend.tokens > 0+ ? t('heteroAgent.claudeQuota.calendar.windowSpend', {+ cost: formatTrackedCost(spend, t),+ tokens: formatTokens(spend.tokens),+ })+ : t('heteroAgent.claudeQuota.calendar.noLedgerSpend')}+ </Text>+ </Flexbox>+ </Flexbox>+ <span+ className={+ exhausted+ ? styles.statusExhausted+ : willExhaust+ ? styles.statusForecast+ : styles.statusSafe+ }+ >+ {statusText}+ </span>+ </Flexbox>++ <div className={styles.chartFrame}>+ <svg+ height={CHART_H}+ preserveAspectRatio={'none'}+ style={{ display: 'block' }}+ viewBox={`0 0 ${CHART_W} ${CHART_H}`}+ width={'100%'}+ >+ {[25, 50, 75].map((u) => (+ <line+ key={u}+ stroke={cssVar.colorBorderSecondary}+ strokeWidth={1}+ x1={0}+ x2={CHART_W}+ y1={yOf(u)}+ y2={yOf(u)}+ />+ ))}+ {/* even pace: exactly exhausting the window at its reset */}+ <line+ stroke={cssVar.colorTextQuaternary}+ strokeDasharray={'4 4'}+ strokeWidth={1}+ x1={0}+ x2={CHART_W}+ y1={CHART_H}+ y2={0}+ />+ <path d={area} fill={cssVar.colorSuccess} opacity={0.12} />+ <polyline fill={'none'} points={polyline} stroke={cssVar.colorSuccess} strokeWidth={2} />+ {isLive && projectionEnd && (+ <line+ stroke={willExhaust ? cssVar.colorWarning : cssVar.colorTextTertiary}+ strokeDasharray={'4 4'}+ strokeWidth={1.5}+ x1={xOf(last.time, window)}+ x2={xOf(projectionEnd.time, window)}+ y1={yOf(last.utilization)}+ y2={yOf(projectionEnd.utilization)}+ />+ )}+ {isLive && willExhaust && (+ <circle+ cx={xOf(projection.exhaustAt, window)}+ cy={yOf(100)}+ fill={cssVar.colorWarning}+ r={3.5}+ />+ )}+ <circle+ cx={xOf(last.time, window)}+ cy={yOf(last.utilization)}+ fill={cssVar.colorSuccess}+ r={3.5}+ />+ </svg>+ </div>++ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {dayjs(window.windowStartAt).format(timeFormat)}+ </Text>+ <Text style={{ color: cssVar.colorTextQuaternary, fontSize: 11 }}>+ {t('heteroAgent.claudeQuota.calendar.pace')}+ </Text>+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {dayjs(window.resetsAt).format(timeFormat)}+ </Text>+ </Flexbox>+ </Flexbox>+ );+});++BurnChart.displayName = 'BurnChart';++const CapacityRing = memo<{ utilization: number }>(({ utilization }) => {+ const value = Math.min(100, Math.max(0, utilization));++ return (+ <div+ aria-label={`${Math.round(utilization)}%`}+ aria-valuemax={100}+ aria-valuemin={0}+ aria-valuenow={Math.round(utilization)}+ className={styles.capacityRing}+ data-status={utilizationStatusOf(utilization)}+ role={'meter'}+ >+ <svg className={styles.capacityRingSvg} viewBox={'0 0 54 54'}>+ <circle+ cx={27}+ cy={27}+ fill={'none'}+ r={RING_RADIUS}+ stroke={cssVar.colorFillSecondary}+ strokeWidth={5}+ />+ <circle+ cx={27}+ cy={27}+ fill={'none'}+ r={RING_RADIUS}+ stroke={'currentColor'}+ strokeDasharray={RING_CIRCUMFERENCE}+ strokeDashoffset={RING_CIRCUMFERENCE * (1 - value / 100)}+ strokeLinecap={'round'}+ strokeWidth={5}+ />+ </svg>+ <span className={styles.capacityRingLabel}>{Math.round(utilization)}%</span>+ </div>+ );+});++CapacityRing.displayName = 'CapacityRing';++const CapacityMeter = memo<{ utilization: number }>(({ utilization }) => (+ <div+ aria-label={`${Math.round(utilization)}%`}+ aria-valuemax={100}+ aria-valuemin={0}+ aria-valuenow={Math.round(utilization)}+ className={styles.capacityTrack}+ role={'meter'}+ >+ <div+ className={styles.capacityFill}+ data-status={utilizationStatusOf(utilization)}+ style={{ width: `${Math.min(100, Math.max(0, utilization))}%` }}+ />+ </div>+));++CapacityMeter.displayName = 'CapacityMeter';++const windowTooltip = (stat: WindowStat, t: TFunction<'chat'>) =>+ [+ `${dayjs(stat.windowStartAt).format('M/D HH:mm')} – ${dayjs(stat.resetsAt).format('M/D HH:mm')}`,+ t('heteroAgent.claudeQuota.calendar.windowUtilization', {+ percent: Math.round(stat.peakUtilization),+ }),+ stat.tokens > 0 &&+ t('heteroAgent.claudeQuota.calendar.windowSpend', {+ cost: formatTrackedCost(stat, t),+ tokens: formatTokens(stat.tokens),+ }),+ stat.rateLimitedAt && t('heteroAgent.claudeQuota.calendar.rateLimited'),+ ].filter(Boolean) as string[];++const WindowHistory = memo<{+ series: QuotaSeriesKey;+ stats: WindowStat[];+}>(({ series, stats }) => {+ const { t } = useTranslation('chat');++ if (stats.length === 0) return null;++ if (series.type === 'session') {+ const latestDay = dayjs(Math.max(...stats.map((stat) => stat.windowStartAt)));+ const grid = buildSessionGrid(stats, latestDay);++ return (+ <Flexbox className={styles.windowSection} gap={8}>+ <Flexbox horizontal align={'baseline'} justify={'space-between'}>+ <Text strong style={{ fontSize: 13 }}>+ {t('heteroAgent.claudeQuota.calendar.sessionHistory')}+ </Text>+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {t('heteroAgent.claudeQuota.calendar.sessionHistoryHint')}+ </Text>+ </Flexbox>+ <div className={styles.windowGrid}>+ {grid.columns.map((column) => (+ <div className={styles.weekday} key={column.key}>+ {column.date.format('dd M/D')}+ </div>+ ))}+ {Array.from({ length: grid.rowCount }, (_, row) =>+ grid.columns.map((column) => {+ const stat = column.slots[row];+ if (!stat) return <div className={styles.windowCell} key={`${column.key}-${row}`} />;++ const cell = (+ <div+ className={styles.windowCell}+ data-rate-limited={stat.rateLimitedAt != null}+ key={`${column.key}-${stat.resetsAt}`}+ >+ <Flexbox+ horizontal+ justify={'space-between'}+ style={{ minWidth: 0, width: '100%' }}+ >+ <span>{dayjs(stat.windowStartAt).format('HH:mm')}</span>+ <strong>{Math.round(stat.peakUtilization)}%</strong>+ </Flexbox>+ <CapacityMeter utilization={stat.peakUtilization} />+ <span className={styles.windowSpend}>+ {stat.tokens > 0+ ? `${formatTokens(stat.tokens)} · ${formatTrackedCost(stat, t)}`+ : t('heteroAgent.claudeQuota.calendar.noLedgerSpendShort')}+ </span>+ </div>+ );++ return (+ <Tooltip+ key={`${column.key}-${stat.resetsAt}`}+ title={windowTooltip(stat, t).join(' · ')}+ >+ {cell}+ </Tooltip>+ );+ }),+ )}+ </div>+ </Flexbox>+ );+ }++ return (+ <Flexbox className={styles.windowSection} gap={6}>+ <Flexbox horizontal align={'baseline'} justify={'space-between'}>+ <Text strong style={{ fontSize: 13 }}>+ {t('heteroAgent.claudeQuota.calendar.weeklyHistory')}+ </Text>+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {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')}+ </Text>+ <Text strong style={{ fontSize: 13 }}>+ {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')}+ </Text>+ </Flexbox>+ </Tooltip>+ )}+ </div>+ ))}+ </Flexbox>+ );+});++WindowHistory.displayName = 'WindowHistory';++interface QuotaCalendarProps {+ externalAccountId?: string;+}++const QuotaCalendar = memo<QuotaCalendarProps>(({ externalAccountId }) => {+ const { t } = useTranslation('chat');+ const [accountUnavailable, setAccountUnavailable] = useState(false);+ const [loading, setLoading] = useState(true);+ const [readings, setReadings] = useState<QuotaLimitReading[]>([]);+ const [turns, setTurns] = useState<UsageTurn[]>([]);+ const [windows, setWindows] = useState<NormalizedWindow[]>([]);+ const [series, setSeries] = useState<QuotaSeriesKey>(SESSION_SERIES);+ const [month, setMonth] = useState(() => dayjs().startOf('month'));+ const now = Date.now();++ useEffect(() => {+ let cancelled = false;+ (async () => {+ const accounts = await agentQuotaService.listAccounts().catch(() => []);+ const claude = accounts.filter((a) => a.provider === 'claude-code');+ const account = selectQuotaAccount(claude, externalAccountId);+ if (!account) {+ if (!cancelled) setAccountUnavailable(true);+ return;+ }+ setAccountUnavailable(false);++ const [windowRows, snapshotSeries, usageTurns] = await Promise.all([+ agentQuotaService.getWindows(account.id, 200).catch(() => [] as WindowRow[]),+ agentQuotaService+ .listSnapshots(account.id, HISTORY_DAYS)+ .catch(() => [] as QuotaLimitReading[]),+ agentQuotaService.listUsageTurns(account.id, HISTORY_DAYS).catch(() => [] as UsageTurn[]),+ ]);+ if (cancelled) return;+ setWindows(normalizeWindows(windowRows));+ setReadings(snapshotSeries);+ setTurns(usageTurns);+ })().finally(() => setLoading(false));++ return () => {+ cancelled = true;+ };+ }, [externalAccountId]);++ // The 5-hour session window comes first: it is the window an agent actually+ // works inside, and the one that stops a run mid-task.+ const seriesOptions = useMemo(() => {+ const scoped = [+ ...new Set(+ readings+ .filter((r) => r.limitType.startsWith('weekly') && r.scopeKey)+ .map((r) => r.scopeKey),+ ),+ ].sort();++ return [+ { label: t('heteroAgent.claudeQuota.calendar.sessionWindow'), value: 'session:' },+ { label: t('heteroAgent.quota.weekly'), value: 'weekly:' },+ ...scoped.map((key) => ({+ label: t('heteroAgent.claudeQuota.scopedWeekly', { model: key }),+ value: `weekly:${key}`,+ })),+ ];+ }, [readings, t]);++ const dailySpend = useMemo(() => buildDailySpend(turns), [turns]);+ const dailyBurn = useMemo(() => buildDailyBurn(readings, series), [readings, series]);+ const dailyHeatLevels = useMemo(+ () => buildDailyHeatLevels(dailySpend, dailyBurn),+ [dailyBurn, dailySpend],+ );++ const chartWindow = useMemo(() => {+ const live = currentWindow(readings, series, now);+ if (live) return live;+ const past = windows.filter((w) => w.seriesId === seriesId(series));+ return past.length > 0 ? past.reduce((a, b) => (a.resetsAt > b.resetsAt ? a : b)) : null;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [readings, series, windows]);++ const windowStats = useMemo(() => {+ const history = windows.filter((window) => window.seriesId === seriesId(series));+ return buildWindowStats(history, chartWindow, turns, now, series.type === 'session' ? 40 : 8);+ // `now` is intentionally captured when the modal opens, matching chartWindow.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [windows, chartWindow, turns, series]);++ // A 5-hour window resets several times a day, so a per-day reset badge would+ // fire on every cell — only the weekly windows get one.+ const resetsByDay = useMemo(() => {+ if (series.type === 'session') return new Map<string, number>();+ const map = new Map<string, number>();+ for (const w of windows) {+ if (w.seriesId !== seriesId(series)) continue;+ map.set(dayKeyOf(w.resetsAt), w.resetsAt);+ }+ if (chartWindow && chartWindow.resetsAt > now) {+ map.set(dayKeyOf(chartWindow.resetsAt), chartWindow.resetsAt);+ }+ return map;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [windows, series, chartWindow]);++ const rateLimitedDays = useMemo(+ () =>+ new Set(+ windows+ .filter((w) => w.seriesId === seriesId(series) && w.rateLimitedAt != null)+ .map((w) => dayKeyOf(w.rateLimitedAt!)),+ ),+ [windows, series],+ );++ const grid = useMemo(() => buildMonthGrid(month), [month]);+ const weekdayLabels = useMemo(+ () =>+ Array.from({ length: 7 }, (_, index) =>+ dayjs()+ .day((index + 1) % 7)+ .format('dd'),+ ),+ [],+ );+ const todayKey = dayKeyOf(now);+ const previousMonth = month.subtract(1, 'month');+ const nextMonth = month.add(1, 'month');++ if (loading)+ return (+ <Flexbox gap={12}>+ <Skeleton.Button active block style={{ height: 170 }} />+ <Skeleton.Button active block style={{ height: 320 }} />+ </Flexbox>+ );++ if (readings.length === 0 && windows.length === 0)+ return (+ <Text style={{ paddingBlock: 24, textAlign: 'center' }} type={'secondary'}>+ {t(+ accountUnavailable+ ? 'heteroAgent.claudeQuota.calendar.accountUnavailable'+ : 'heteroAgent.claudeQuota.calendar.empty',+ )}+ </Text>+ );++ const dayLabel = (spend: DaySpend | undefined, burn: number) => {+ if (spend && spend.tokens > 0) return formatTokens(spend.tokens);+ // No ledger row (usage burned outside LobeHub) but the meter still moved.+ if (burn > 0) return `${Math.round(burn)}%`;+ return '';+ };++ return (+ <Flexbox gap={16}>+ <Segmented+ options={seriesOptions}+ size={'small'}+ style={{ alignSelf: 'flex-start' }}+ value={seriesId(series)}+ onChange={(value) => {+ const [type, scopeKey = ''] = String(value).split(':');+ setSeries({ scopeKey, type: type === 'session' ? 'session' : 'weekly' });+ }}+ />++ {chartWindow && (+ <BurnChart+ now={now}+ readings={readings}+ series={series}+ turns={turns}+ window={chartWindow}+ />+ )}++ <WindowHistory series={series} stats={windowStats} />++ <Flexbox gap={8}>+ <Flexbox horizontal align={'center'} gap={4} justify={'space-between'}>+ <Flexbox horizontal align={'baseline'} gap={8}>+ <Text strong style={{ fontSize: 13 }}>+ {t('heteroAgent.claudeQuota.calendar.monthSpend')}+ </Text>+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {month.format('YYYY/MM')}+ </Text>+ </Flexbox>+ <Flexbox horizontal gap={2}>+ <ActionIcon+ disabled={!isCalendarMonthAvailable(previousMonth, now)}+ icon={ChevronLeftIcon}+ size={'small'}+ onClick={() => setMonth((m) => m.subtract(1, 'month'))}+ />+ <ActionIcon+ disabled={!isCalendarMonthAvailable(nextMonth, now)}+ icon={ChevronRightIcon}+ size={'small'}+ onClick={() => setMonth((m) => m.add(1, 'month'))}+ />+ </Flexbox>+ </Flexbox>++ <div className={styles.calendarGrid}>+ {weekdayLabels.map((label) => (+ <div className={styles.weekday} key={label}>+ {label}+ </div>+ ))}+ {grid.map((cell) => {+ const spend = dailySpend.get(cell.key);+ const burn = dailyBurn.get(cell.key) ?? 0;+ 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 tooltipParts = [+ spend &&+ spend.tokens > 0 &&+ t('heteroAgent.claudeQuota.calendar.dayTokens', {+ cost: formatTrackedCost(spend, t),+ tokens: formatTokens(spend.tokens),+ }),+ burn > 0 &&+ t('heteroAgent.claudeQuota.calendar.dayShare', { percent: Math.round(burn) }),+ resetsAt &&+ t('heteroAgent.claudeQuota.calendar.resetAt', {+ time: dayjs(resetsAt).format('HH:mm'),+ }),+ rateLimited && t('heteroAgent.claudeQuota.calendar.rateLimited'),+ ].filter(Boolean) as string[];++ const day = (+ <div+ className={styles.dayCell}+ data-in-month={cell.inMonth}+ data-rate-limited={rateLimited}+ data-today={cell.key === todayKey}+ key={cell.key}+ >+ <span>{cell.date.date()}</span>+ {shouldShowHeatDot(heatLevel, rateLimited) && (+ <span aria-hidden className={styles.heatDot} data-heat={heatLevel} />+ )}+ <span className={styles.dayFooter}>+ <span className={styles.tokens}>{label}</span>+ <span style={{ display: 'inline-flex', alignItems: 'center', gap: 2 }}>+ {rateLimited && <Icon color={cssVar.colorError} icon={BanIcon} size={12} />}+ {resetsAt && (+ <Icon color={cssVar.colorTextSecondary} icon={RotateCcwIcon} size={11} />+ )}+ </span>+ </span>+ {spend && (spend.cost > 0 || spend.hasUnpricedTurn) && (+ <span className={styles.cost}>{formatTrackedCost(spend, t)}</span>+ )}+ </div>+ );++ return tooltipParts.length > 0 ? (+ <Tooltip key={cell.key} title={tooltipParts.join(' · ')}>+ {day}+ </Tooltip>+ ) : (+ day+ );+ })}+ </div>++ <Flexbox horizontal align={'center'} gap={12} style={{ fontSize: 11 }}>+ <Flexbox horizontal align={'center'} gap={4}>+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {t('heteroAgent.claudeQuota.calendar.legendLess')}+ </Text>+ {[1, 2, 3, 4].map((level) => (+ <span className={styles.heatDot} data-heat={level} data-legend={'true'} key={level} />+ ))}+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {t('heteroAgent.claudeQuota.calendar.legendMore')}+ </Text>+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={4}>+ <span className={styles.legendSwatch} data-rate-limited={'true'} />+ <Icon color={cssVar.colorError} icon={BanIcon} size={11} />+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {t('heteroAgent.claudeQuota.calendar.rateLimited')}+ </Text>+ </Flexbox>+ {series.type !== 'session' && (+ <Flexbox horizontal align={'center'} gap={4}>+ <Icon color={cssVar.colorTextSecondary} icon={RotateCcwIcon} size={11} />+ <Text style={{ fontSize: 11 }} type={'secondary'}>+ {t('heteroAgent.claudeQuota.calendar.legendReset')}+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ </Flexbox>+ </Flexbox>+ );+});++QuotaCalendar.displayName = 'QuotaCalendar';++/** Calling this opens the modal — `createModal` mounts immediately. */+export const openQuotaCalendarModal = (+ params: { externalAccountId?: string } = {},+): ModalInstance =>+ createModal({+ content: <QuotaCalendar externalAccountId={params.externalAccountId} />,+ footer: null,+ title: i18nT('heteroAgent.claudeQuota.calendar.title', { ns: 'chat' }),+ width: 620,+ });++export default QuotaCalendar;diff --git a/src/features/AgentQuotaCalendar/index.ts b/src/features/AgentQuotaCalendar/index.tsnew file mode 100644index 00000000000..1d6f72c37c2--- /dev/null+++ b/src/features/AgentQuotaCalendar/index.ts@@ -0,0 +1 @@+export { openQuotaCalendarModal } from './QuotaCalendarModal';diff --git a/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts b/src/features/AgentQuotaCalendar/quotaCalendarModel.test.tsnew file mode 100644index 00000000000..3d49e4184e3--- /dev/null+++ b/src/features/AgentQuotaCalendar/quotaCalendarModel.test.ts@@ -0,0 +1,183 @@+import dayjs from 'dayjs';+import { describe, expect, it } from 'vitest';++import {+ buildDailyHeatLevels,+ buildDailySpend,+ buildSessionGrid,+ buildWindowStats,+ isCalendarMonthAvailable,+ type QuotaWindowSpan,+ selectQuotaAccount,+ shouldShowHeatDot,+ trackedCostOf,+ utilizationLevelOf,+ utilizationStatusOf,+} from './quotaCalendarModel';++const hour = 60 * 60 * 1000;+const at = (value: string) => dayjs(value).valueOf();++const windowAt = (+ start: string,+ utilization: number,+ rateLimitedAt: number | null = null,+): QuotaWindowSpan => ({+ peakUtilization: utilization,+ rateLimitedAt,+ resetsAt: at(start) + 5 * hour,+ windowStartAt: at(start),+});++describe('quota calendar window statistics', () => {+ it('merges the live reading into history and attributes spend to each window', () => {+ const historical = windowAt('2026-08-08T08:00:00', 60, at('2026-08-08T10:00:00'));+ const storedLive = windowAt('2026-08-09T08:00:00', 35);+ const live = windowAt('2026-08-09T08:00:00', 72);++ const stats = buildWindowStats(+ [historical, storedLive],+ live,+ [+ { cost: 1.25, occurredAt: at('2026-08-08T09:00:00'), tokens: 1000 },+ { cost: 2.5, occurredAt: at('2026-08-09T09:00:00'), tokens: 2000 },+ { cost: null, occurredAt: at('2026-08-09T09:30:00'), tokens: 500 },+ ],+ at('2026-08-09T10:00:00'),+ );++ expect(stats).toHaveLength(2);+ expect(stats[0]).toMatchObject({+ cost: 2.5,+ hasUnpricedTurn: true,+ isLive: true,+ peakUtilization: 72,+ tokens: 2500,+ });+ expect(stats[1]).toMatchObject({+ cost: 1.25,+ hasUnpricedTurn: false,+ isLive: false,+ rateLimitedAt: at('2026-08-08T10:00:00'),+ tokens: 1000,+ });+ });++ it('deduplicates provider reset jitter within one logical window', () => {+ const first = windowAt('2026-08-09T08:00:00', 35);+ const jittered = {+ ...windowAt('2026-08-09T08:00:00', 68),+ rateLimitedAt: at('2026-08-09T10:00:00'),+ resetsAt: first.resetsAt + 90_000,+ };++ const stats = buildWindowStats([first, jittered], null, [], at('2026-08-10T00:00:00'));++ expect(stats).toHaveLength(1);+ expect(stats[0]).toMatchObject({+ peakUtilization: 68,+ rateLimitedAt: at('2026-08-09T10:00:00'),+ resetsAt: jittered.resetsAt,+ });+ });++ it('lays session windows out by local day and chronological slot', () => {+ const stats = buildWindowStats(+ [+ windowAt('2026-08-08T13:00:00', 80),+ windowAt('2026-08-08T07:00:00', 20),+ windowAt('2026-08-09T08:00:00', 50),+ ],+ null,+ [],+ at('2026-08-10T00:00:00'),+ );+ const grid = buildSessionGrid(stats, dayjs('2026-08-09'), 2);++ expect(grid.rowCount).toBe(2);+ expect(grid.columns.map((column) => column.key)).toEqual(['2026-08-08', '2026-08-09']);+ expect(grid.columns[0].slots.map((slot) => slot?.peakUtilization)).toEqual([20, 80]);+ expect(grid.columns[1].slots.map((slot) => slot?.peakUtilization ?? null)).toEqual([50, null]);+ });++ it.each([+ [0, 0],+ [1, 1],+ [24, 1],+ [25, 2],+ [49, 2],+ [50, 3],+ [79, 3],+ [80, 4],+ [100, 4],+ ])('maps %s%% utilization to level %s', (utilization, level) => {+ expect(utilizationLevelOf(utilization)).toBe(level);+ });++ it('shows a heat dot only for positive, non-rate-limited days', () => {+ expect(shouldShowHeatDot(0, false)).toBe(false);+ expect(shouldShowHeatDot(1, false)).toBe(true);+ expect(shouldShowHeatDot(4, false)).toBe(true);+ expect(shouldShowHeatDot(4, true)).toBe(false);+ });++ it('falls back to provider burn per day when ledger exists only on other days', () => {+ const spend = buildDailySpend([+ { cost: 2, occurredAt: at('2026-08-08T09:00:00'), tokens: 2000 },+ ]);+ const burn = new Map([+ ['2026-08-08', 20],+ ['2026-08-09', 60],+ ]);++ expect(buildDailyHeatLevels(spend, burn)).toEqual(+ new Map([+ ['2026-08-08', 4],+ ['2026-08-09', 4],+ ]),+ );+ });++ it('does not fall back to a different quota account', () => {+ const accounts = [+ { externalAccountId: 'account-a', id: 'a' },+ { externalAccountId: 'account-b', id: 'b' },+ ];++ expect(selectQuotaAccount(accounts, 'missing')).toBeUndefined();+ expect(selectQuotaAccount(accounts)).toBeUndefined();+ expect(selectQuotaAccount([accounts[0]])).toEqual(accounts[0]);+ });++ it('limits calendar navigation to the two fully loaded months', () => {+ const now = at('2026-08-09T12:00:00');++ expect(isCalendarMonthAvailable(dayjs('2026-08-01'), now)).toBe(true);+ expect(isCalendarMonthAvailable(dayjs('2026-07-01'), now)).toBe(true);+ expect(isCalendarMonthAvailable(dayjs('2026-06-01'), now)).toBe(false);+ expect(isCalendarMonthAvailable(dayjs('2026-09-01'), now)).toBe(false);+ });++ it('distinguishes exact, lower-bound, and unknown costs', () => {+ expect(trackedCostOf({ cost: 2, hasUnpricedTurn: false })).toEqual({+ cost: 2,+ kind: 'exact',+ });+ expect(trackedCostOf({ cost: 2, hasUnpricedTurn: true })).toEqual({+ cost: 2,+ kind: 'lower-bound',+ });+ expect(trackedCostOf({ cost: 0, hasUnpricedTurn: true })).toEqual({ kind: 'unknown' });+ });++ it.each([+ [0, 'safe'],+ [79, 'safe'],+ [80, 'warning'],+ [99, 'warning'],+ [100, 'error'],+ [120, 'error'],+ ] as const)('maps %s%% utilization to %s pressure', (utilization, status) => {+ expect(utilizationStatusOf(utilization)).toBe(status);+ });+});diff --git a/src/features/AgentQuotaCalendar/quotaCalendarModel.ts b/src/features/AgentQuotaCalendar/quotaCalendarModel.tsnew file mode 100644index 00000000000..b355db06d4d--- /dev/null+++ b/src/features/AgentQuotaCalendar/quotaCalendarModel.ts@@ -0,0 +1,470 @@+import type { QuotaLimitReading } from '@lobechat/heterogeneous-agents/quota';+import {+ CLAUDE_SESSION_WINDOW_SECONDS,+ CLAUDE_WEEKLY_WINDOW_SECONDS,+} from '@lobechat/heterogeneous-agents/quota';+import dayjs from 'dayjs';++/**+ * Pure read-model helpers for the quota usage calendar: daily token/cost spend+ * from the usage ledger, quota headroom from the snapshot time series, and the+ * burn-down curve plus exhaustion projection for one window. No React, no+ * fetching — kept apart so the shapes are unit-testable.+ *+ * Two limit windows matter to a coding agent and both are first-class here: the+ * 5-hour session window it actually works in, and the 7-day weekly window that+ * caps the week.+ */++export const WEEKLY_WINDOW_MS = CLAUDE_WEEKLY_WINDOW_SECONDS * 1000;+export const SESSION_WINDOW_MS = CLAUDE_SESSION_WINDOW_SECONDS * 1000;++/** Two provider-reported reset instants for the same window may jitter a bit. */+const RESET_MATCH_TOLERANCE_MS = 5 * 60 * 1000;++export const dayKeyOf = (time: number) => dayjs(time).format('YYYY-MM-DD');++/** Which limit series a calendar view is reading. */+export interface QuotaSeriesKey {+ /** `''` for the account-wide weekly; a model name for a scoped weekly. */+ scopeKey: string;+ type: 'session' | 'weekly';+}++export const SESSION_SERIES: QuotaSeriesKey = { scopeKey: '', type: 'session' };++export const seriesId = (series: QuotaSeriesKey) => `${series.type}:${series.scopeKey}`;++export const windowMsOf = (series: QuotaSeriesKey) =>+ series.type === 'session' ? SESSION_WINDOW_MS : WEEKLY_WINDOW_MS;++export interface BurnPoint {+ time: number;+ utilization: number;+}++export interface QuotaWindowSpan {+ peakUtilization: number;+ rateLimitedAt: number | null;+ resetsAt: number;+ windowStartAt: number;+}++/** One assistant turn's spend, as returned by `agentQuota.listUsageTurns`. */+export interface UsageTurn {+ cost: number | null;+ model?: string | null;+ occurredAt: number;+ tokens: number;+}++export interface DaySpend {+ cost: number;+ /** Turns whose model the price bank did not know — cost is a lower bound. */+ hasUnpricedTurn: boolean;+ tokens: number;+}++export type TrackedCost =+ { cost: number; kind: 'exact' } | { cost: number; kind: 'lower-bound' } | { kind: 'unknown' };++export const trackedCostOf = (spend: Pick<DaySpend, 'cost' | 'hasUnpricedTurn'>): TrackedCost => {+ if (!spend.hasUnpricedTurn) return { cost: spend.cost, kind: 'exact' };+ if (spend.cost > 0) return { cost: spend.cost, kind: 'lower-bound' };+ return { kind: 'unknown' };+};++interface QuotaAccountCandidate {+ externalAccountId?: string | null;+}++export const selectQuotaAccount = <T extends QuotaAccountCandidate>(+ accounts: T[],+ externalAccountId?: string,+): T | undefined => {+ if (externalAccountId)+ return accounts.find((candidate) => candidate.externalAccountId === externalAccountId);+ return accounts.length === 1 ? accounts[0] : undefined;+};++/** The 90-day query guarantees complete data for the current and previous month. */+export const isCalendarMonthAvailable = (month: dayjs.Dayjs, now: number) => {+ const current = dayjs(now).startOf('month');+ return month.isSame(current, 'month') || month.isSame(current.subtract(1, 'month'), 'month');+};++const isSessionReading = (reading: QuotaLimitReading) =>+ reading.limitType === 'session' || reading.limitType === 'five_hour';++/** Does this reading belong to the series a view is showing? */+export const matchesSeries = (reading: QuotaLimitReading, series: QuotaSeriesKey) =>+ series.type === 'session'+ ? isSessionReading(reading)+ : reading.limitType.startsWith('weekly') && (reading.scopeKey || '') === series.scopeKey;++const sortByCapturedAt = (readings: QuotaLimitReading[]) =>+ [...readings].sort((a, b) => a.capturedAt - b.capturedAt);++const sameWindow = (a: QuotaLimitReading, b: QuotaLimitReading) =>+ a.resetsAt != null && b.resetsAt != null+ ? Math.abs(a.resetsAt - b.resetsAt) < RESET_MATCH_TOLERANCE_MS+ : b.utilization >= a.utilization;++/**+ * Tokens and cost burned per local day, from the usage ledger. This is what the+ * calendar shows: how much was actually spent on a day, not how fast quota was+ * being consumed relative to a window.+ */+export const buildDailySpend = (turns: UsageTurn[]): Map<string, DaySpend> => {+ const byDay = new Map<string, DaySpend>();++ for (const turn of turns) {+ const key = dayKeyOf(turn.occurredAt);+ const day = byDay.get(key) ?? { cost: 0, hasUnpricedTurn: false, tokens: 0 };++ day.tokens += turn.tokens;+ if (turn.cost == null) day.hasUnpricedTurn = true;+ else day.cost += turn.cost;++ byDay.set(key, day);+ }++ return byDay;+};++/**+ * Percentage points of a window burned per local day, from consecutive snapshot+ * deltas. No longer what the calendar cells show — it drives the heat shading,+ * which still has to answer "how hard did this day lean on the quota".+ *+ * A rollover between two samples restarts the meter, so the new sample's+ * utilization *is* the burn since reset. Negative deltas inside one window (a+ * provider correction) count as zero rather than negative burn.+ */+export const buildDailyBurn = (+ readings: QuotaLimitReading[],+ series: QuotaSeriesKey,+): Map<string, number> => {+ const list = sortByCapturedAt(readings.filter((r) => matchesSeries(r, series)));+ const windowMs = windowMsOf(series);+ const burnByDay = new Map<string, number>();++ for (const [index, current] of list.entries()) {+ if (index === 0) continue;+ const previous = list[index - 1];+ // A gap longer than one full window can hide entire windows — attributing+ // its delta to one day would paint a false spike.+ if (current.capturedAt - previous.capturedAt > windowMs) continue;++ const burn = sameWindow(previous, current)+ ? Math.max(0, current.utilization - previous.utilization)+ : current.utilization;+ if (burn <= 0) continue;++ const key = dayKeyOf(current.capturedAt);+ burnByDay.set(key, (burnByDay.get(key) ?? 0) + burn);+ }++ return burnByDay;+};++/**+ * Heat level for a day, ranked against the busiest day in view rather than+ * against a fixed pace target: the calendar's job is to show which days were+ * heavy relative to this user's own month, and an absolute threshold flagged+ * almost every working day at once.+ */+export const heatLevelOf = (value: number, max: number): 0 | 1 | 2 | 3 | 4 => {+ if (value <= 0 || max <= 0) return 0;+ const ratio = value / max;+ if (ratio <= 0.25) return 1;+ if (ratio <= 0.5) return 2;+ if (ratio <= 0.75) return 3;+ return 4;+};++/**+ * Resolve calendar intensity per day without mixing incomparable units.+ * LobeHub-owned days rank by tokens; days without a ledger row fall back to+ * provider-reported quota burn and rank against the other burn-only days.+ */+export const buildDailyHeatLevels = (+ spendByDay: Map<string, DaySpend>,+ burnByDay: Map<string, number>,+): Map<string, 0 | 1 | 2 | 3 | 4> => {+ const tokenMax = Math.max(0, ...[...spendByDay.values()].map((spend) => spend.tokens));+ const externalBurn = [...burnByDay].filter(([key]) => (spendByDay.get(key)?.tokens ?? 0) === 0);+ const burnMax = Math.max(0, ...externalBurn.map(([, burn]) => burn));+ const levels = new Map<string, 0 | 1 | 2 | 3 | 4>();++ for (const [key, spend] of spendByDay) {+ if (spend.tokens > 0) levels.set(key, heatLevelOf(spend.tokens, tokenMax));+ }+ for (const [key, burn] of externalBurn) levels.set(key, heatLevelOf(burn, burnMax));++ return levels;+};++/** A rate-limit alarm owns the corner; otherwise positive heat gets a dot. */+export const shouldShowHeatDot = (level: 0 | 1 | 2 | 3 | 4, rateLimited: boolean) =>+ level > 0 && !rateLimited;++/** The window of this series that is live right now. */+export const currentWindow = (+ readings: QuotaLimitReading[],+ series: QuotaSeriesKey,+ now: number,+): QuotaWindowSpan | null => {+ let newest: QuotaLimitReading | null = null;+ for (const reading of readings) {+ if (!matchesSeries(reading, series)) continue;+ if (reading.resetsAt == null || reading.resetsAt <= now) continue;+ if (!newest || reading.capturedAt > newest.capturedAt) newest = reading;+ }+ if (!newest) return null;++ return {+ peakUtilization: newest.utilization,+ rateLimitedAt: null,+ resetsAt: newest.resetsAt!,+ windowStartAt: newest.resetsAt! - windowMsOf(series),+ };+};++/**+ * The burn-down polyline for one window: its snapshot readings in capture+ * order, anchored at (windowStart, 0) — a window is refilled by definition at+ * its start instant.+ */+export const buildBurnSeries = (+ readings: QuotaLimitReading[],+ series: QuotaSeriesKey,+ window: QuotaWindowSpan,+): BurnPoint[] => {+ const points = sortByCapturedAt(+ readings.filter(+ (r) =>+ matchesSeries(r, series) &&+ r.capturedAt >= window.windowStartAt &&+ r.capturedAt <= window.resetsAt &&+ (r.resetsAt == null || Math.abs(r.resetsAt - window.resetsAt) < RESET_MATCH_TOLERANCE_MS),+ ),+ ).map((r) => ({ time: r.capturedAt, utilization: Math.min(100, Math.max(0, r.utilization)) }));++ return [{ time: window.windowStartAt, utilization: 0 }, ...points];+};++/** Tokens and cost spent inside one concrete window. */+export const spendInWindow = (turns: UsageTurn[], window: QuotaWindowSpan): DaySpend =>+ turns+ .filter((t) => t.occurredAt >= window.windowStartAt && t.occurredAt <= window.resetsAt)+ .reduce<DaySpend>(+ (acc, turn) => ({+ cost: acc.cost + (turn.cost ?? 0),+ hasUnpricedTurn: acc.hasUnpricedTurn || turn.cost == null,+ tokens: acc.tokens + turn.tokens,+ }),+ { cost: 0, hasUnpricedTurn: false, tokens: 0 },+ );++export type BurnProjection =+ | { exhaustAt: number; kind: 'exhaust' }+ | { kind: 'exhausted' }+ | { kind: 'safe'; projectedEndUtilization: number };++/**+ * How far back "current pace" looks before falling back to the whole window.+ * Scaled to the window: a day of history is meaningless inside a 5-hour window.+ */+const paceLookbackMs = (window: QuotaWindowSpan) => (window.resetsAt - window.windowStartAt) / 5;++/**+ * Project where the current pace lands. The reference sample is the newest+ * point at least one lookback old (so an idle stretch flattens the pace instead+ * of the whole window's average hiding a hot streak), falling back to the+ * window anchor when the window is younger than that.+ */+export const projectBurnout = (points: BurnPoint[], window: QuotaWindowSpan): BurnProjection => {+ const last = points.at(-1);+ if (!last || points.length < 2) return { kind: 'safe', projectedEndUtilization: 0 };+ if (last.utilization >= 100) return { kind: 'exhausted' };++ const lookback = paceLookbackMs(window);+ let reference = points[0];+ for (const point of points) {+ if (point.time <= last.time - lookback) reference = point;+ }+ const elapsed = last.time - reference.time;+ const slope = elapsed > 0 ? (last.utilization - reference.utilization) / elapsed : 0;+ if (slope <= 0) return { kind: 'safe', projectedEndUtilization: last.utilization };++ const exhaustAt = last.time + (100 - last.utilization) / slope;+ if (exhaustAt <= window.resetsAt) return { exhaustAt, kind: 'exhaust' };++ return {+ kind: 'safe',+ projectedEndUtilization: Math.min(+ 100,+ last.utilization + slope * (window.resetsAt - last.time),+ ),+ };+};++/**+ * One concrete window with what it cost. This is the middle zoom level of the+ * panel: the burn chart is one window in detail, the month grid is calendar+ * days, and this is the window itself as a countable unit — which is the unit+ * the provider actually enforces.+ */+export interface WindowStat extends QuotaWindowSpan {+ cost: number;+ hasUnpricedTurn: boolean;+ isLive: boolean;+ tokens: number;+}++const withSpend = (window: QuotaWindowSpan, turns: UsageTurn[], now: number): WindowStat => {+ const spend = spendInWindow(turns, window);++ return {+ ...window,+ cost: spend.cost,+ hasUnpricedTurn: spend.hasUnpricedTurn,+ isLive: window.resetsAt > now,+ tokens: spend.tokens,+ };+};++/**+ * Recent windows of one series, newest first, each with its spend. The live+ * window is merged in from the readings: it has no `agent_quota_windows` row+ * until it closes, and leaving "now" out of a window list is exactly the gap+ * that makes the list feel disconnected from the chart above it.+ */+export const buildWindowStats = (+ windows: QuotaWindowSpan[],+ live: QuotaWindowSpan | null,+ turns: UsageTurn[],+ now: number,+ limit = 8,+): WindowStat[] => {+ const merged: QuotaWindowSpan[] = [];+ for (const window of [...windows, ...(live ? [live] : [])].sort(+ (a, b) => a.resetsAt - b.resetsAt,+ )) {+ const existingIndex = merged.findIndex(+ (candidate) => Math.abs(candidate.resetsAt - window.resetsAt) < RESET_MATCH_TOLERANCE_MS,+ );+ if (existingIndex < 0) {+ merged.push(window);+ continue;+ }++ const existing = merged[existingIndex];+ merged[existingIndex] = {+ peakUtilization: Math.max(existing.peakUtilization, window.peakUtilization),+ rateLimitedAt: existing.rateLimitedAt ?? window.rateLimitedAt,+ // Keep the widest observed boundary pair for spend attribution.+ resetsAt: Math.max(existing.resetsAt, window.resetsAt),+ windowStartAt: Math.min(existing.windowStartAt, window.windowStartAt),+ };+ }++ return merged+ .sort((a, b) => b.resetsAt - a.resetsAt)+ .slice(0, limit)+ .map((window) => withSpend(window, turns, now));+};++export interface SessionGridColumn {+ date: dayjs.Dayjs;+ key: string;+ /** Windows that started on this local day, earliest first. */+ slots: (WindowStat | null)[];+}++export interface SessionGrid {+ columns: SessionGridColumn[];+ rowCount: number;+}++/**+ * Session windows laid out as slot × weekday. A 5-hour window is a *slot in a+ * day*, not a day — so the natural shape is a grid whose columns are days and+ * whose rows are the successive windows within each day. Columns are the seven+ * days ending on `endDay`, which keeps this block navigation-free: it reads as+ * "the last week of working windows" beside the month grid's longer arc.+ */+export const buildSessionGrid = (+ stats: WindowStat[],+ endDay: dayjs.Dayjs,+ days = 7,+): SessionGrid => {+ const byDay = new Map<string, WindowStat[]>();+ for (const stat of stats) {+ const key = dayKeyOf(stat.windowStartAt);+ byDay.set(key, [...(byDay.get(key) ?? []), stat]);+ }+ for (const list of byDay.values()) list.sort((a, b) => a.windowStartAt - b.windowStartAt);++ const start = endDay.startOf('day').subtract(days - 1, 'day');+ const columns = Array.from({ length: days }, (_, index) => {+ const date = start.add(index, 'day');+ const key = date.format('YYYY-MM-DD');+ return { date, key, slots: byDay.get(key) ?? [] };+ });+ const rowCount = Math.max(1, ...columns.map((c) => c.slots.length));++ return {+ columns: columns.map((c) => ({+ ...c,+ slots: Array.from({ length: rowCount }, (_, row) => c.slots[row] ?? null),+ })),+ rowCount,+ };+};++/** Utilization ramp for a window cell — absolute, since 0–100 already means something. */+export const utilizationLevelOf = (utilization: number): 0 | 1 | 2 | 3 | 4 => {+ if (utilization <= 0) return 0;+ if (utilization < 25) return 1;+ if (utilization < 50) return 2;+ if (utilization < 80) return 3;+ return 4;+};++/** Semantic quota pressure: comfortable, nearly full, or exhausted. */+export const utilizationStatusOf = (utilization: number): 'error' | 'safe' | 'warning' => {+ if (utilization >= 100) return 'error';+ if (utilization >= 80) return 'warning';+ return 'safe';+};++export interface CalendarDayCell {+ date: dayjs.Dayjs;+ inMonth: boolean;+ key: string;+}++/** Six Monday-start weeks covering the given month. */+export const buildMonthGrid = (month: dayjs.Dayjs): CalendarDayCell[] => {+ const firstOfMonth = month.startOf('month');+ // dayjs day(): 0 = Sunday. Shift so the grid starts on Monday.+ const offset = (firstOfMonth.day() + 6) % 7;+ const gridStart = firstOfMonth.subtract(offset, 'day');++ return Array.from({ length: 42 }, (_, index) => {+ const date = gridStart.add(index, 'day');+ return { date, inMonth: date.month() === month.month(), key: date.format('YYYY-MM-DD') };+ });+};++/** Compact token count for a calendar cell: 1.2M / 340K / 820. */+export const formatTokens = (tokens: number): string => {+ 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));+};++/** Cost for a summary line: $12.40 / $0.83. */+export const formatCost = (cost: number): string => `$${cost.toFixed(cost >= 10 ? 0 : 2)}`;diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountSwitcher.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountSwitcher.tsxindex b1c9af88296..1917d2195e0 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountSwitcher.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaAccountSwitcher.tsx@@ -1,12 +1,14 @@'use client';import type { ClaudeCodeQuotaSnapshot } from '@lobechat/electron-client-ipc';-import { Flexbox, Text } from '@lobehub/ui';+import { ActionIcon, Flexbox, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';+import { CalendarDaysIcon } from 'lucide-react';import { memo, useCallback } from 'react';import { useTranslation } from 'react-i18next';+import { openQuotaCalendarModal } from '@/features/AgentQuotaCalendar';import { useAgentId } from '@/features/ChatInput/hooks/useAgentId';import { openQuotaAccountManagerModal } from './QuotaAccountManagerModal';@@ -59,6 +61,13 @@ const QuotaAccountSwitcher = memo<{{identity.planTier}</Text>)}+ <ActionIcon+ icon={CalendarDaysIcon}+ size={'small'}+ style={{ flex: 'none' }}+ title={t('heteroAgent.claudeQuota.calendar.entry')}+ onClick={() => openQuotaCalendarModal({ externalAccountId: identity?.externalAccountId })}+ /></Flexbox><Button size={'small'} style={{ flex: 'none' }} onClick={openManager}>{t('heteroAgent.claudeQuota.manage.entry')}diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsxindex 06d7556ba7f..0fff765ab9a 100644--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/QuotaMenu/QuotaMenu.test.tsx@@ -135,8 +135,22 @@ vi.mock('@lobehub/ui', async () => {const { useState } = await import('react');return {- ActionIcon: ({ disabled, onClick }: { disabled?: boolean; onClick?: () => void }) => (- <button data-testid="refresh" disabled={disabled} type="button" onClick={onClick} />+ ActionIcon: ({+ disabled,+ onClick,+ title,+ }: {+ disabled?: boolean;+ onClick?: () => void;+ title?: string;+ }) => (+ <button+ aria-label={title}+ data-testid={title ? 'calendar' : 'refresh'}+ disabled={disabled}+ type="button"+ onClick={onClick}+ />),Collapse: ({defaultActiveKey = [],diff --git a/src/services/agentQuota.ts b/src/services/agentQuota.tsindex 2fd97e87e15..f8ff11f3fea 100644--- a/src/services/agentQuota.ts+++ b/src/services/agentQuota.ts@@ -34,6 +34,18 @@ class AgentQuotaService {getLatestReadings = async (accountId: string) =>lambdaClient.agentQuota.getLatestReadings.query({ accountId });+ /** Recent concrete windows (weekly + session), newest reset first — calendar read model. */+ getWindows = async (accountId: string, limit?: number) =>+ lambdaClient.agentQuota.getWindows.query({ accountId, limit });++ /** Full reading series (oldest first) for the burn-down chart / calendar heat. */+ listSnapshots = async (accountId: string, sinceDays?: number) =>+ lambdaClient.agentQuota.listSnapshots.query({ accountId, sinceDays });++ /** Per-turn token + cost spend (oldest first) for the calendar's daily totals. */+ listUsageTurns = async (accountId: string, sinceDays?: number) =>+ lambdaClient.agentQuota.listUsageTurns.query({ accountId, sinceDays });+listBindings = async (agentId: string) => lambdaClient.agentQuota.listBindings.query({ agentId });/** UI "switch account": pin one account for an agent (Manual mode). */