Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): name quota plans and keep exact reset times in a tooltip (#2195)
Call White6d464094b2a7
diff --git a/core/handlers/model_hub/pricing.py b/core/handlers/model_hub/pricing.pyindex 7d80f246c..3ead15e43 100644--- a/core/handlers/model_hub/pricing.py+++ b/core/handlers/model_hub/pricing.py@@ -59,12 +59,18 @@ MODEL_ALIASES: Final[Mapping[str, str]] = {"haiku": "claude-haiku-4-5",}-# Monthly fee per plan, USD. Keys are what `plan_key` publishes.+# Monthly fee per plan, USD, at the vendors' published individual monthly prices.+# Keys are what `plan_key` publishes. Sources:+# - Claude: https://claude.com/pricing (Pro $20, Max 5x $100, Max 20x $200).+# - ChatGPT: https://learn.chatgpt.com/docs/pricing (Plus $20, Pro "from $100/month"+# with 5x or 20x Plus usage); the $100 tier is Pro 5x and $200 remains Pro 20x+# (https://techcrunch.com/2026/04/09/chatgpt-pro-plan-100-month-codex/).PLAN_FEES_USD: Final[Mapping[str, float]] = {"claude_pro": 20.0,"claude_max_5x": 100.0,"claude_max_20x": 200.0,"chatgpt_plus": 20.0,+ "chatgpt_pro_5x": 100.0,"chatgpt_pro": 200.0,}@@ -80,6 +86,9 @@ _PLAN_KEYS: Final[Mapping[tuple[str, str], str]] = {("openai", "chatgpt_plus"): "chatgpt_plus",("openai", "pro"): "chatgpt_pro",("openai", "chatgpt_pro"): "chatgpt_pro",+ # Codex reports the $100 Pro 5x tier as `prolite` (openai/codex#17419).+ ("openai", "prolite"): "chatgpt_pro_5x",+ ("openai", "chatgpt_pro_5x"): "chatgpt_pro_5x",}# Vendors whose subscriptions have built-in plan names. Any other vendor's plandiff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 13976d282..e0bde1203 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1422,7 +1422,8 @@ as "not reported", never as zero.Pro, and `claude_max` with `rate_limit_tier` `default_claude_max_5x` or`default_claude_max_20x` is Max 5x or 20x; Team, Enterprise, and unknown tiersare no plan. Built-in fees: `claude_pro` 20, `claude_max_5x`- 100, `claude_max_20x` 200, `chatgpt_plus` 20, `chatgpt_pro` 200 (USD / month). An+ 100, `claude_max_20x` 200, `chatgpt_plus` 20, `chatgpt_pro_5x` 100 (Codex+ reports it as `prolite`), `chatgpt_pro` 200 (USD / month). Anunknown plan leaves `plan_key`, `fee_usd`, and `multiple` null: the page stillshows the API value but no payback figure.- `multiple` is `period.api_cost_usd / fee_usd`. When `period.api_cost_lower_bound`diff --git a/docs/plans/model-hub-contracts/quota-summary.schema.json b/docs/plans/model-hub-contracts/quota-summary.schema.jsonindex 44aae61f9..dbc84e3ed 100644--- a/docs/plans/model-hub-contracts/quota-summary.schema.json+++ b/docs/plans/model-hub-contracts/quota-summary.schema.json@@ -331,7 +331,7 @@]},"plan_key": {- "description": "Fee-table key the plan resolved to (built-in: claude_pro, claude_max_5x, claude_max_20x, chatgpt_plus, chatgpt_pro; or a key the local override file defines), or null when the plan is unknown.",+ "description": "Fee-table key the plan resolved to (built-in: claude_pro, claude_max_5x, claude_max_20x, chatgpt_plus, chatgpt_pro_5x, chatgpt_pro; or a key the local override file defines), or null when the plan is unknown.","type": ["string","null"diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 9c6c80b6b..9dde9b7c8 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -802,6 +802,8 @@ scenarios:kind: observationlayer: unittest: tests/test_model_hub_quota.py::test_codex_quota_parser_reads_primary_secondary_and_additional_limits+ related_tests:+ - tests/test_model_hub_quota.py::test_codex_quota_parser_classifies_a_lone_weekly_primary_by_length- id: MH-QUOTA-004name: A malformed or hostile quota body is one Source's sanitized failure with bounded valuesstatus: covered@@ -948,6 +950,26 @@ scenarios:kind: observationlayer: unittest: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-026+ - id: MH-QUOTA-027+ name: A reported plan id reads as its display name, and an unknown id as title-cased words+ status: covered+ kind: observation+ layer: unit+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-027+ - id: MH-QUOTA-028+ name: A countdown drops its zero second part+ status: covered+ kind: observation+ layer: unit+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-028+ - id: MH-QUOTA-029+ name: A countdown shows only the duration; its exact local moment opens on hover, focus, or tap and is in its accessible name+ status: covered+ kind: observation+ layer: unit+ test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-029+ related_tests:+ - ui/e2e/model-catalog/quota-layout.spec.ts- id: MH-PRICE-001name: A models.dev price fills a missing cache price from input and a one-hour cache write from twice inputstatus: covered@@ -1003,6 +1025,7 @@ scenarios:test: tests/test_model_hub_pricing.py::test_reported_plans_resolve_to_fee_table_keysrelated_tests:- tests/test_model_hub_pricing.py::test_override_file_sets_a_sources_plan_fee_and_renewal_day+ - tests/test_model_hub_pricing.py::test_pro_5x_is_priced_apart_from_pro- id: MH-PRICE-009name: The value period is the current billing cycle when a renewal day is known, else the trailing 30 daysstatus: covereddiff --git a/tests/test_model_hub_pricing.py b/tests/test_model_hub_pricing.pyindex fdc729dbd..ecfcde673 100644--- a/tests/test_model_hub_pricing.py+++ b/tests/test_model_hub_pricing.py@@ -281,6 +281,8 @@ def test_rows_written_before_cache_writes_read_as_uncaptured(tmp_path):("anthropic", "pro", "claude_pro"),("openai", "plus", "chatgpt_plus"),("openai", "pro", "chatgpt_pro"),+ ("openai", "prolite", "chatgpt_pro_5x"),+ ("codex", "ProLite", "chatgpt_pro_5x"),("openai", "team", None),("codex", "pro", "chatgpt_pro"),("gemini", "pro", None),@@ -294,6 +296,14 @@ def test_reported_plans_resolve_to_fee_table_keys(vendor, reported, key):assert plan_key(vendor, reported) == key+def test_pro_5x_is_priced_apart_from_pro():+ """MH-PRICE-008: `prolite` is the $100 Pro 5x tier; `pro` stays the $200 tier."""++ table = _table()+ assert table.fee(plan_key("openai", "prolite")) == 100.0+ assert table.fee(plan_key("openai", "pro")) == 200.0++def test_override_file_sets_a_sources_plan_fee_and_renewal_day():"""MH-PRICE-008: A per-Source plan wins over the reported one, and an override fee wins over the table."""diff --git a/tests/test_model_hub_quota.py b/tests/test_model_hub_quota.pyindex 85316e8fe..6073c1eb9 100644--- a/tests/test_model_hub_quota.py+++ b/tests/test_model_hub_quota.py@@ -191,6 +191,26 @@ def test_codex_quota_parser_reads_primary_secondary_and_additional_limits():assert windows[2]["scope_model"] == "Spark"+def test_codex_quota_parser_classifies_a_lone_weekly_primary_by_length():+ """MH-QUOTA-003: Pro 5x (`prolite`) reports only a weekly window, in the primary slot."""++ report = {+ "plan_type": "prolite",+ "rate_limit": {+ "allowed": True,+ "limit_reached": False,+ "primary_window": {"used_percent": 31, "limit_window_seconds": 604800,+ "reset_after_seconds": 400000, "reset_at": 1790400000},+ "secondary_window": None,+ },+ "additional_rate_limits": None,+ }+ parsed = parse_codex_quota(json.dumps(report))+ _validate_windows(parsed)+ assert parsed["plan"] == "prolite"+ assert [(window["id"], window["kind"]) for window in parsed["windows"]] == [("primary_window", "weekly")]++@pytest.mark.parametrize(("parser", "body"),[diff --git a/ui/e2e/model-catalog/quota-layout.spec.ts b/ui/e2e/model-catalog/quota-layout.spec.tsindex 997773122..248685a01 100644--- a/ui/e2e/model-catalog/quota-layout.spec.ts+++ b/ui/e2e/model-catalog/quota-layout.spec.ts@@ -1,4 +1,4 @@-import { expect, test, type Locator } from '@playwright/test';+import { expect, test, type Locator, type Page } from '@playwright/test';const box = async (locator: Locator) => {await expect(locator).toBeVisible();@@ -6,9 +6,34 @@ const box = async (locator: Locator) => {};const fits = (locator: Locator) => locator.evaluate((element) => element.scrollWidth <= element.clientWidth + 1);-for (const lang of ['en', 'zh'] as const) {- test(`MH-QUOTA-015: holds the narrow layout at 360px — one account per line, stacked footers, wrapping labels (${lang})`, async ({ page }, testInfo) => {- await page.setViewportSize({ width: 360, height: 844 });+const overlaps = (a: Box, b: Box) =>+ a.x < b.x + b.width && b.x < a.x + a.width && a.y < b.y + b.height && b.y < a.y + a.height;+type Box = { x: number; y: number; width: number; height: number };++/**+ * MH-QUOTA-029: a tap (or, without touch, a click) on the weekly countdown opens+ * its exact moment inside the viewport, clear of its own row's remaining figure+ * and pace line. Briefly covering the next row is fine for a transient hint.+ */+const openHintClear = async (page: Page, width: number, touch: boolean) => {+ const row = page.locator('[data-quota-window="seven_day"]').first();+ const countdown = row.locator('.model-hub-quota-reset button');+ await (touch ? countdown.tap() : countdown.click());+ const hint = page.getByRole('dialog');+ await expect(hint).toContainText(/\d{1,2}:\d{2}/);+ // Measure where it settles, not mid slide-in.+ await hint.evaluate((el) => Promise.all(el.getAnimations({ subtree: true }).map((a) => a.finished)));+ const hintBox = await box(hint);+ expect(hintBox.x).toBeGreaterThanOrEqual(0);+ expect(hintBox.x + hintBox.width).toBeLessThanOrEqual(width);+ expect(overlaps(hintBox, await box(countdown))).toBe(false);+ expect(overlaps(hintBox, await box(row.locator('.model-hub-quota-pace')))).toBe(false);+ expect(overlaps(hintBox, await box(row.locator('.model-hub-quota-left')))).toBe(false);+};++for (const [lang, width] of [['en', 360], ['zh', 360], ['en', 390], ['zh', 390]] as const) {+ test(`MH-QUOTA-015: holds the narrow layout at ${width}px — one account per line, stacked footers, wrapping labels (${lang})`, async ({ page }, testInfo) => {+ await page.setViewportSize({ width, height: 844 });await page.goto(`/e2e/model-catalog/fixture.html?view=quota&lang=${lang}`);const cards = page.getByRole('article');await expect(cards).toHaveCount(2);@@ -19,7 +44,7 @@ for (const lang of ['en', 'zh'] as const) {// One account per line: the second card starts below the first, in the same column.expect(second.y).toBeGreaterThanOrEqual(first.y + first.height);expect(Math.abs(second.x - first.x)).toBeLessThanOrEqual(1);- for (const card of [first, second]) expect(card.x + card.width).toBeLessThanOrEqual(360);+ for (const card of [first, second]) expect(card.x + card.width).toBeLessThanOrEqual(width);// Each footer stacks its reset line under the pace line.for (const row of await page.locator('[data-quota-window]').all()) {@@ -53,7 +78,7 @@ for (const lang of ['en', 'zh'] as const) {const statBoxes = await Promise.all((await stats.all()).map(box));expect(Math.abs(statBoxes[0].y - statBoxes[1].y)).toBeLessThanOrEqual(1);expect(statBoxes[2].y).toBeGreaterThanOrEqual(statBoxes[0].y + statBoxes[0].height - 1);- for (const stat of statBoxes) expect(stat.x + stat.width).toBeLessThanOrEqual(360);+ for (const stat of statBoxes) expect(stat.x + stat.width).toBeLessThanOrEqual(width);const strips = page.locator('[data-quota-value]');await expect(strips).toHaveCount(2);for (let index = 0; index < 2; index += 1) {@@ -63,7 +88,28 @@ for (const lang of ['en', 'zh'] as const) {}await expect(page.locator('[data-quota-payback]').first()).toBeVisible();+ // MH-QUOTA-029: the reset line is the countdown alone, and the plan badge a name, not the upstream id.+ for (const reset of await page.locator('.model-hub-quota-reset').all()) {+ await expect(reset).not.toContainText(/\d{1,2}:\d{2}/);+ }+ await expect(page.locator('.model-hub-quota-plan')).toHaveText(['Max', 'Pro 5x']);++ await openHintClear(page, width, Boolean(testInfo.project.use.hasTouch));+ await page.screenshot({ path: testInfo.outputPath('quota-reset-hint.png') });+ await page.keyboard.press('Escape');+ await expect(page.getByRole('dialog')).toBeHidden();+expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true);await page.screenshot({ path: testInfo.outputPath('quota-layout.png'), fullPage: true });});}++for (const lang of ['en', 'zh'] as const) {+ test(`MH-QUOTA-029: at desktop width the exact moment opens clear of its own row's figure and pace line (${lang})`, async ({ page }, testInfo) => {+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.goto(`/e2e/model-catalog/fixture.html?view=quota&lang=${lang}`);+ await expect(page.getByRole('article')).toHaveCount(2);+ await openHintClear(page, 1280, Boolean(testInfo.project.use.hasTouch));+ await page.screenshot({ path: testInfo.outputPath('quota-reset-hint-desktop.png') });+ });+}diff --git a/ui/e2e/model-catalog/quotaFixture.tsx b/ui/e2e/model-catalog/quotaFixture.tsxindex 5f9d94f49..1d696c80b 100644--- a/ui/e2e/model-catalog/quotaFixture.tsx+++ b/ui/e2e/model-catalog/quotaFixture.tsx@@ -42,14 +42,14 @@ const sources: SourceQuota[] = [}),},{- source_id: 'src_codex', vendor: 'openai', display_name: 'ChatGPT Pro', account_label: null,- plan: 'pro', fetched_at: iso(NOW - 60_000), state: 'ok',+ source_id: 'src_codex', vendor: 'openai', display_name: 'ChatGPT', account_label: null,+ plan: 'prolite', fetched_at: iso(NOW - 60_000), state: 'ok',windows: [limit({ id: 'primary_window', label: 'primary_window', used_pct: 70, resets_at: iso(NOW + 47 * 60_000) }),limit({ id: 'secondary_window', label: 'secondary_window', used_pct: 45, ...weekly }),],value: valued({- plan_key: 'chatgpt_pro', fee_usd: 200, multiple: 0.6125, week: priced(38.2, 12_400),+ plan_key: 'chatgpt_pro_5x', fee_usd: 100, multiple: 1.225, week: priced(38.2, 12_400),period: { basis: 'rolling_30d', from_day: '2026-08-27', to_day: '2026-09-25', renews_on: null, ...priced(122.5, 12_400) },}),},@@ -57,7 +57,7 @@ const sources: SourceQuota[] = [const value: QuotaValueTotals = {currency: 'USD', price_table_date: '2026-09-23', week: priced(450.57, 12_400),- period: { sources: 2, fee_usd: 400, multiple: 3.5163, ...priced(1406.52, 12_400) },+ period: { sources: 2, fee_usd: 300, multiple: 4.6884, ...priced(1406.52, 12_400) },};export function QuotaFixture() {diff --git a/ui/src/components/settings/models/QuotaTab.test.tsx b/ui/src/components/settings/models/QuotaTab.test.tsxindex ed0a9887c..c092944dd 100644--- a/ui/src/components/settings/models/QuotaTab.test.tsx+++ b/ui/src/components/settings/models/QuotaTab.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdom// What the 订阅额度 tab says about a quota report: the windows it names, the pace// it claims, and what it admits about a reading that is not current.-import { cleanup, render, screen, within } from '@testing-library/react';+import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { createInstance } from 'i18next';import { I18nextProvider, initReactI18next } from 'react-i18next';@@ -101,16 +101,16 @@ describe('QuotaTab', () => {expect(within(card).getByText('单独计算的模型额度')).toBeTruthy();expect(within(card).getByText('这些模型也会同时扣每周额度,任一项用完就会暂停')).toBeTruthy();expect(within(card).getByText('可用')).toBeTruthy();- expect(within(card).getByText('max')).toBeTruthy();+ expect(within(card).getByText('Max')).toBeTruthy();expect(within(card).getByText('[email protected]')).toBeTruthy();// Fable at 86% four days before a 7-day reset is spending faster than time.const fable = card.querySelector('[data-quota-window="fable"]') as HTMLElement;- expect(fable.textContent).toMatch(/用得偏快,预计 .+ 用完/);+ expect(fable.textContent).toMatch(/用得偏快,预计 .+后用完/);expect(within(fable).getByRole('meter', { name: 'Fable 每周额度 已用 86%' })).toBeTruthy();expect(fable.textContent).toContain('14%');const session = card.querySelector('[data-quota-window="five_hour"]') as HTMLElement;- expect(session.textContent).toContain('2 小时 0 分后重置');+ expect(session.textContent).toContain('2 小时后重置');expect(session.querySelector('.model-hub-quota-time-mark')).not.toBeNull();// A spent window names itself in the status pill and says when it returns.@@ -271,6 +271,118 @@ describe('QuotaTab', () => {}});+ it('MH-QUOTA-027: names a reported plan in words, never as a bare upstream id', async () => {+ const badge = (vendor: string, plan: string) => {+ cleanup();+ draw(readyRegion(summary([codex({ vendor, plan, display_name: 'Account' })])));+ return screen.getByRole('article').querySelector('.model-hub-quota-plan')!.textContent;+ };+ // Known ids, whatever their casing or separators, and with or without the vendor's prefix.+ expect(badge('openai', 'prolite')).toBe('Pro 5x');+ expect(badge('codex', 'ProLite')).toBe('Pro 5x');+ expect(badge('openai', 'chatgpt_pro_5x')).toBe('Pro 5x');+ expect(badge('openai', 'pro')).toBe('Pro');+ expect(badge('openai', 'business')).toBe('Business');+ expect(badge('anthropic', 'claude_max_20x')).toBe('Max 20x');+ expect(badge('anthropic', 'max-5x')).toBe('Max 5x');+ // An id another vendor's table names is not borrowed; an unknown id reads as words.+ expect(badge('anthropic', 'prolite')).toBe('Prolite');+ expect(badge('anthropic', 'chatgpt_pro')).toBe('Chatgpt Pro');+ expect(badge('openai', 'claude_pro')).toBe('Claude Pro');+ expect(badge('openai', 'team_plus-annual')).toBe('Team Plus Annual');+ expect(badge('xai', 'supergrok')).toBe('Supergrok');+ // An unknown id still drops the vendor prefix the badge never repeats.+ expect(badge('openai', 'chatgpt_team_plus')).toBe('Team Plus');+ await i18n.changeLanguage('en');+ try {+ expect(badge('openai', 'prolite')).toBe('Pro 5x');+ } finally {+ await i18n.changeLanguage('zh');+ }+ });++ it('MH-QUOTA-028: a countdown drops its zero second part', async () => {+ const reset = (ms: number) => {+ cleanup();+ draw(readyRegion(summary([claude({ windows: [window({ used_pct: 1, window_seconds: 604_800, kind: 'weekly', resets_at: iso(NOW + ms) })] })])));+ return screen.getByRole('article').querySelector('.model-hub-quota-reset')!.textContent;+ };+ expect(reset(5 * 24 * HOUR)).toBe('5 天后重置');+ expect(reset(5 * 24 * HOUR + 3 * HOUR)).toBe('5 天 3 小时后重置');+ expect(reset(HOUR)).toBe('1 小时后重置');+ expect(reset(HOUR + 20 * 60_000)).toBe('1 小时 20 分后重置');+ expect(reset(20 * 60_000)).toBe('20 分钟后重置');+ await i18n.changeLanguage('en');+ try {+ expect(reset(5 * 24 * HOUR)).toBe('Resets in 5d');+ expect(reset(HOUR)).toBe('Resets in 1h');+ expect(reset(HOUR + 20 * 60_000)).toBe('Resets in 1h 20m');+ } finally {+ await i18n.changeLanguage('zh');+ }+ });++ it('MH-QUOTA-029: shows a countdown alone and keeps its exact moment in a tooltip and the accessible name', async () => {+ const resetAt = NOW + 5 * 24 * HOUR + 7 * 60 * 60_000;+ const stamp = (at: number) => new Intl.DateTimeFormat('zh', {+ weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',+ }).format(at);+ const exact = stamp(resetAt);+ const { container } = draw(readyRegion(summary([+ claude({ windows: [window({ id: 'seven_day', kind: 'weekly', used_pct: 20, window_seconds: 604_800, resets_at: iso(resetAt) })] }),+ codex(),+ ])));+ const row = container.querySelector('[data-quota-window="seven_day"]') as HTMLElement;+ const reset = row.querySelector('.model-hub-quota-reset') as HTMLElement;+ // The line reads the countdown alone; the clock is not drawn beside it.+ expect(reset.textContent).toBe('5 天 7 小时后重置');+ expect(container.querySelector('.model-hub-quota-reset em')).toBeNull();+ const trigger = within(reset).getByRole('button', { name: `5 天 7 小时后重置 (${exact})` });+ expect(document.body.textContent).not.toContain(exact);++ // Keyboard focus opens it and blur closes it; a tap toggles it.+ fireEvent.focus(trigger);+ expect((await screen.findByRole('dialog')).textContent).toBe(exact);+ fireEvent.blur(trigger);+ expect(screen.queryByRole('dialog')).toBeNull();+ fireEvent.pointerDown(trigger, { pointerType: 'touch' });+ fireEvent.focus(trigger);+ expect(screen.queryByRole('dialog')).toBeNull();+ fireEvent.click(trigger);+ expect(screen.getByRole('dialog').textContent).toBe(exact);+ fireEvent.pointerDown(trigger, { pointerType: 'touch' });+ fireEvent.click(trigger);+ expect(screen.queryByRole('dialog')).toBeNull();+ // A mouse hover opens it too.+ fireEvent.pointerEnter(trigger, { pointerType: 'mouse' });+ expect(screen.getByRole('dialog').textContent).toBe(exact);+ fireEvent.pointerLeave(trigger, { pointerType: 'mouse' });+ expect(screen.queryByRole('dialog')).toBeNull();++ // Every other countdown takes the same form: the upcoming-reset chips, the+ // spent-limit note, and the fast-pace forecast.+ const chips = within(screen.getByLabelText('即将重置')).getAllByRole('button');+ expect(chips.map((chip) => chip.textContent)).toContain('47 分钟');+ expect(chips.find((chip) => chip.textContent === '47 分钟')!.getAttribute('aria-label')).toBe(`47 分钟 (${stamp(NOW + 47 * 60_000)})`);+ expect(screen.getByRole('button', { name: `ChatGPT Pro · 47 分钟后恢复 (${stamp(NOW + 47 * 60_000)})` })).toBeTruthy();+ cleanup();+ draw(readyRegion(summary([claude()])));+ const fable = document.querySelector('[data-quota-window="fable"] .model-hub-quota-pace') as HTMLElement;+ expect(fable.textContent).toMatch(/^用得偏快,预计 .+后用完$/);+ expect(within(fable).getByRole('button').getAttribute('aria-label')).toMatch(/^用得偏快,预计 .+后用完 \(.+\)$/);+ });++ it('keeps the exact time of a retained reading behind its 「ago」 banner', () => {+ const fetchedAt = NOW - 3 * HOUR - 12 * 60_000;+ draw(readyRegion(summary([codex({ state: 'stale', fetched_at: iso(fetchedAt) })])));+ const banner = within(screen.getByRole('article')).getByRole('status');+ expect(banner.textContent).toBe('暂时读不到最新额度,下面是 3 小时 12 分前的数据');+ const stamp = new Intl.DateTimeFormat('zh', {+ weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',+ }).format(fetchedAt);+ expect(within(banner).getByRole('button').getAttribute('aria-label')).toBe(`${banner.textContent} (${stamp})`);+ });+describe('API-price value', () => {const priced = (api_cost_usd: number, over: Partial<PricedUsage> = {}): PricedUsage => ({api_cost_usd, excluded_tokens: 0, api_cost_lower_bound: false, ...over,@@ -335,7 +447,8 @@ describe('QuotaTab', () => {expect(claudeCard.textContent).toContain('回本 2.0 倍');// Counted between host-calendar days (2026-09-25 → 2026-10-05), whatever the browser's zone.expect(claudeCard.textContent).toContain('距下次续费10 天');- expect(claudeCard.textContent).toContain('2026-10-05');+ // The renewal day is a host-calendar day: its weekday is that day's, whatever the browser's zone.+ expect(within(claudeCard).getByRole('button', { name: '10 天 (2026/10/5周一)' })).toBeTruthy();expect(codexCard.textContent).toContain('还差 $182.00 回本');const foot = container.querySelector('.model-hub-quota-foot')!.textContent!;expect(foot).toContain('进度条是已用的部分');diff --git a/ui/src/components/settings/models/QuotaTab.tsx b/ui/src/components/settings/models/QuotaTab.tsxindex 74f9b79e1..276c747da 100644--- a/ui/src/components/settings/models/QuotaTab.tsx+++ b/ui/src/components/settings/models/QuotaTab.tsx@@ -18,6 +18,7 @@ import { cn } from '@/lib/utils';import { atLeast, formatCost, formatCount, formatUsd } from './format';import { foldRegionRead, regionFailed, type RegionRead } from './regionRead';import type { PricedUsage, QuotaSummary, QuotaWindow, SourceQuota, SourceQuotaValue } from './types';+import { TimeHint } from './TimeHint';import { VendorGlyph } from './vendorGlyph';import {DAY_MS,@@ -28,7 +29,9 @@ import {quotaIsLive,quotaIsRetained,quotaPayback,+ quotaPlanId,sourceStatus,+ titleCasePlan,tightestWindow,upcomingResets,windowIsExhausted,@@ -46,20 +49,39 @@ const useQuotaText = (now: number) => {const { t, i18n } = useTranslation();const duration = React.useCallback((ms: number) => {const d = quotaDuration(ms);- if (d.unit === 'days') return t('settings.models.quota.duration.days', { days: d.days, hours: d.hours }) as string;- if (d.unit === 'hours') return t('settings.models.quota.duration.hours', { hours: d.hours, minutes: d.minutes }) as string;+ // A zero second part says nothing: 「5 天」, not 「5 天 0 小时」.+ if (d.unit === 'days') {+ return d.hours+ ? t('settings.models.quota.duration.days', { days: d.days, hours: d.hours }) as string+ : t('settings.models.quota.duration.daysOnly', { days: d.days }) as string;+ }+ if (d.unit === 'hours') {+ return d.minutes+ ? t('settings.models.quota.duration.hours', { hours: d.hours, minutes: d.minutes }) as string+ : t('settings.models.quota.duration.hoursOnly', { hours: d.hours }) as string;+ }return t('settings.models.quota.duration.minutes', { minutes: d.minutes }) as string;}, [t]);- const clock = React.useCallback((at: number) => {- const time = new Intl.DateTimeFormat(i18n.language, { hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(at);- const startOfDay = (ms: number) => { const day = new Date(ms); day.setHours(0, 0, 0, 0); return day.getTime(); };- const dayDiff = Math.round((startOfDay(at) - startOfDay(now)) / DAY_MS);- if (dayDiff === 0) return t('settings.models.quota.clock.today', { time }) as string;- if (dayDiff === 1) return t('settings.models.quota.clock.tomorrow', { time }) as string;- return new Intl.DateTimeFormat(i18n.language, {- weekday: 'short', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',+ /** The exact local moment, weekday included, for the tooltip behind a countdown. */+ const exact = React.useCallback((at: number) => new Intl.DateTimeFormat(i18n.language, {+ weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit', hourCycle: 'h23',+ }).format(at), [i18n.language]);+ /** A host-calendar day (`YYYY-MM-DD`) with its weekday, read as that day wherever the browser is. */+ const exactDay = React.useCallback((day: string) => {+ const at = Date.parse(`${day}T00:00:00Z`);+ return Number.isNaN(at) ? day : new Intl.DateTimeFormat(i18n.language, {+ weekday: 'short', year: 'numeric', month: 'numeric', day: 'numeric', timeZone: 'UTC',}).format(at);- }, [i18n.language, now, t]);+ }, [i18n.language]);+ /**+ * A plan's display name. The badge sits beside the account's own name, which+ * already says whose plan it is, so the name is the tier alone (「Pro 5x」).+ */+ const planLabel = React.useCallback((vendor: string, plan: string) => {+ const { family, id } = quotaPlanId(vendor, plan);+ const key = family ? `settings.models.quota.plan.${family}.${id}` : null;+ return key && i18n.exists(key) ? t(key as never) as string : titleCasePlan(id);+ }, [i18n, t]);const ago = React.useCallback((at: number) => {const ms = Math.max(0, now - at);return ms < HOUR_MS@@ -85,11 +107,11 @@ const useQuotaText = (now: number) => {case 'exhausted': return pace.remainingMs !== null? t('settings.models.quota.pace.exhausted', { duration: duration(pace.remainingMs) }) as string: t('settings.models.quota.pace.exhaustedUnknown') as string;- case 'fast': return t('settings.models.quota.pace.fast', { time: clock(pace.runsOutAt) }) as string;+ case 'fast': return t('settings.models.quota.pace.fast', { duration: duration(Math.max(0, pace.runsOutAt - now)) }) as string;case 'slightly_fast': return t('settings.models.quota.pace.slightlyFast') as string;default: return t('settings.models.quota.pace.ok') as string;}- }, [clock, duration, t]);+ }, [duration, now, t]);/** Plain dollars, for a figure only shown when its period is exact (a shortfall). */const dollars = React.useCallback((amount: number) => formatUsd(amount, i18n.language), [i18n.language]);/** A priced figure, 「≥」 whenever the server marks it a floor. */@@ -101,7 +123,7 @@ const useQuotaText = (now: number) => {const multiple = React.useCallback((value: number) => new Intl.NumberFormat(i18n.language, {minimumFractionDigits: 1, maximumFractionDigits: 1,}).format(Math.floor(value * 10) / 10), [i18n.language]);- return { duration, clock, ago, windowLabel, windowHint, paceText, dollars, usd, tokens, multiple };+ return { duration, exact, exactDay, planLabel, ago, windowLabel, windowHint, paceText, dollars, usd, tokens, multiple };};type QuotaText = ReturnType<typeof useQuotaText>;@@ -146,13 +168,15 @@ const WindowRow: React.FC<{ window: QuotaWindow; now: number; retained: boolean;<div className="model-hub-quota-row-foot"><span className={cn('model-hub-quota-pace flex items-center gap-[5px]', toneClass(reading.tone))}>{alarm ? <AlertTriangle className="size-[11px]" aria-hidden /> : <span className="model-hub-quota-dot" aria-hidden />}- {text.paceText(reading.pace)}+ {reading.pace.kind === 'fast'+ ? <TimeHint text={text.paceText(reading.pace)} exact={text.exact(reading.pace.runsOutAt)} />+ : text.paceText(reading.pace)}</span>{untilReset !== null && (<span className="model-hub-quota-reset flex items-center gap-[5px]"><TimerReset className="size-[11px]" aria-hidden />{untilReset > 0- ? <>{t('settings.models.quota.reset.in', { duration: text.duration(untilReset) })}<em>{text.clock(resetAt as number)}</em></>+ ? <TimeHint text={t('settings.models.quota.reset.in', { duration: text.duration(untilReset) }) as string} exact={text.exact(resetAt as number)} />: t('settings.models.quota.reset.done')}</span>)}@@ -216,8 +240,7 @@ const ValueStrip: React.FC<{ value: SourceQuotaValue; text: QuotaText }> = ({ va<div><span>{t('settings.models.quota.value.renews')}</span><b>- {t('settings.models.quota.value.renewsIn', { count: Math.max(0, renewsIn) })}- <em>{value.period.renews_on}</em>+ <TimeHint text={t('settings.models.quota.value.renewsIn', { count: Math.max(0, renewsIn) }) as string} exact={text.exactDay(value.period.renews_on as string)} /></b></div>)}@@ -259,7 +282,7 @@ const AccountCard: React.FC<{<div className="min-w-0 flex-1"><strong className="model-hub-quota-account flex min-w-0 items-center gap-2 font-semibold text-foreground"><span className="truncate">{source.display_name}</span>- {source.plan && <span className="model-hub-quota-plan shrink-0">{source.plan}</span>}+ {source.plan && <span className="model-hub-quota-plan shrink-0">{text.planLabel(source.vendor, source.plan)}</span>}</strong>{source.account_label && <small className="model-hub-quota-account-label block truncate">{source.account_label}</small>}</div>@@ -271,7 +294,10 @@ const AccountCard: React.FC<{<div className="model-hub-quota-stale flex items-center gap-2" role="status"><AlertTriangle className="size-[13px] shrink-0" aria-hidden /><span className="min-w-0 flex-1">- {t(expired ? 'settings.models.quota.stale.authExpired' : 'settings.models.quota.stale.retained', { ago: text.ago(fetchedAt) })}+ <TimeHint+ text={t(expired ? 'settings.models.quota.stale.authExpired' : 'settings.models.quota.stale.retained', { ago: text.ago(fetchedAt) }) as string}+ exact={text.exact(fetchedAt)}+ /></span>{expired && onRequestReauth && (<Button variant="outline" size="sm" className="shrink-0" onClick={() => onRequestReauth(source.source_id)}>@@ -408,11 +434,10 @@ export const QuotaTab: React.FC<{note={tightest? (() => {const resetAt = windowResetAt(tightest.window);- return [- tightest.source.display_name,- text.windowLabel(tightest.window),- resetAt !== null && resetAt > now ? t('settings.models.quota.stat.resetsIn', { duration: text.duration(resetAt - now) }) : null,- ].filter(Boolean).join(' · ');+ const named = `${tightest.source.display_name} · ${text.windowLabel(tightest.window)}`;+ return resetAt !== null && resetAt > now+ ? <>{named} · <TimeHint text={t('settings.models.quota.stat.resetsIn', { duration: text.duration(resetAt - now) }) as string} exact={text.exact(resetAt)} /></>+ : named;})()// Like 「every account is usable」 below, 「every limit is used up」 is a// claim about all accounts: make it only when each has a current reading.@@ -425,8 +450,11 @@ export const QuotaTab: React.FC<{note={exhausted.length? (() => {const resetAt = windowResetAt(exhausted[0].window);- return resetAt !== null- ? t('settings.models.quota.stat.exhaustedNote', { name: exhausted[0].source.display_name, time: text.clock(resetAt) })+ return resetAt !== null && resetAt > now+ ? <TimeHint+ text={t('settings.models.quota.stat.exhaustedNote', { name: exhausted[0].source.display_name, duration: text.duration(resetAt - now) }) as string}+ exact={text.exact(resetAt)}+ />: exhausted[0].source.display_name;})()// 「every account is usable」 is a claim about accounts; make it only@@ -474,7 +502,9 @@ export const QuotaTab: React.FC<{<span className="model-hub-quota-timeline-title flex items-center gap-1.5"><TimerReset className="size-[13px]" aria-hidden />{t('settings.models.quota.upcoming')}</span>{upcoming.map(({ source, window }) => (<span key={`${source.source_id}:${window.id}`} className={cn('model-hub-quota-chip flex min-w-0 max-w-full items-baseline gap-1.5', windowIsExhausted(window, now) && toneClass('danger'))}>- <b className="shrink-0 whitespace-nowrap">{text.duration((windowResetAt(window) as number) - now)}</b>+ <b className="shrink-0 whitespace-nowrap">+ <TimeHint text={text.duration((windowResetAt(window) as number) - now)} exact={text.exact(windowResetAt(window) as number)} />+ </b><span className="min-w-0 truncate" title={`${source.display_name} · ${text.windowLabel(window)}`}>{source.display_name} · {text.windowLabel(window)}</span></span>))}diff --git a/ui/src/components/settings/models/TimeHint.tsx b/ui/src/components/settings/models/TimeHint.tsxnew file mode 100644index 000000000..62d0beda8--- /dev/null+++ b/ui/src/components/settings/models/TimeHint.tsx@@ -0,0 +1,60 @@+import * as React from 'react';++import { Popover, PopoverAnchor, PopoverContent } from '@/components/ui/popover';+import { cn } from '@/lib/utils';++/**+ * A relative time ("in 5 days") that reveals its exact moment on mouse hover,+ * keyboard focus, or a tap — a phone has no hover, so a tap toggles it. The+ * exact moment is also part of the accessible name, so a screen reader hears+ * both without opening anything.+ */+export const TimeHint: React.FC<{+ /** What the line shows: the countdown. */+ text: string;+ /** The exact local date and time, as the panel and the accessible name state it. */+ exact: string;+ className?: string;+}> = ({ text, exact, className }) => {+ const [open, setOpen] = React.useState(false);+ const anchor = React.useRef<HTMLButtonElement>(null);+ // A pointer press focuses the button before its click; only keyboard focus+ // opens on focus, so a tap is one clean toggle rather than open-then-close.+ const pointer = React.useRef<string | null>(null);+ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverAnchor asChild>+ <button+ ref={anchor}+ type="button"+ aria-label={`${text} (${exact})`}+ className={cn('model-hub-quota-time', className)}+ onPointerDown={(event) => { pointer.current = event.pointerType; }}+ onPointerEnter={(event) => { if (event.pointerType === 'mouse') setOpen(true); }}+ onPointerLeave={(event) => { if (event.pointerType === 'mouse') setOpen(false); }}+ onFocus={() => { if (pointer.current === null) setOpen(true); }}+ onBlur={() => { pointer.current = null; setOpen(false); }}+ onClick={() => {+ // The mouse already opened it on hover; a click keeps it open.+ if (pointer.current === 'mouse') setOpen(true);+ else setOpen((prev) => !prev);+ }}+ >+ {text}+ </button>+ </PopoverAnchor>+ <PopoverContent+ // Below, end-aligned: clear of its own row's figure; Radix flips it on collision.+ side="bottom"+ align="end"+ sideOffset={6}+ onOpenAutoFocus={(event) => event.preventDefault()}+ // The anchor is not a Radix trigger, so its own tap would read as outside.+ onInteractOutside={(event) => { if (anchor.current?.contains(event.target as Node)) event.preventDefault(); }}+ className="w-auto whitespace-nowrap px-2.5 py-1.5 text-[12px] font-normal text-foreground"+ >+ {exact}+ </PopoverContent>+ </Popover>+ );+};diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.cssindex 645f53edd..824aad37f 100644--- a/ui/src/components/settings/models/modelHubSurface.css+++ b/ui/src/components/settings/models/modelHubSurface.css@@ -3113,10 +3113,22 @@.model-hub-quota-pace.model-hub-quota-tone--warn,.model-hub-quota-pace.model-hub-quota-tone--danger { color: var(--model-hub-quota-tone); }.model-hub-quota-reset { white-space: nowrap; }-.model-hub-quota-reset em {- margin-left: 6px;- color: var(--model-hub-usage-note-ink);- font-style: normal;+/* A countdown whose exact moment opens on hover, focus, or tap. */+.model-hub-quota-time {+ padding: 0;+ border: 0;+ background: none;+ color: inherit;+ font: inherit;+ text-align: inherit;+ text-decoration: underline dotted color-mix(in srgb, currentColor 45%, transparent);+ text-underline-offset: 3px;+ cursor: help;+}+.model-hub-quota-time:focus-visible {+ outline: 2px solid var(--ring);+ outline-offset: 2px;+ border-radius: 2px;}.model-hub-quota-scoped {margin: 2px 0 -4px;diff --git a/ui/src/components/settings/models/quotaProjection.ts b/ui/src/components/settings/models/quotaProjection.tsindex 8b4c0e74b..257a93074 100644--- a/ui/src/components/settings/models/quotaProjection.ts+++ b/ui/src/components/settings/models/quotaProjection.ts@@ -28,6 +28,31 @@ export function quotaDuration(ms: number): QuotaDuration {return { unit: 'minutes', minutes };}+/** Vendor families whose plan ids have a display name. */+const PLAN_FAMILIES: Record<string, 'openai' | 'anthropic'> = { openai: 'openai', codex: 'openai', anthropic: 'anthropic' };+/** Each family's own plan-id prefix; another vendor's prefix is kept, so it cannot borrow a name. */+const PLAN_PREFIX: Record<'openai' | 'anthropic', string> = { openai: 'chatgpt_', anthropic: 'claude_' };++/**+ * A reported plan id, read for its display name: the family whose names apply+ * and the id with case, separators, and the vendor's own prefix folded away+ * (`claude_max_20x` and `Max 20x` are both `max_20x`).+ */+export function quotaPlanId(vendor: string, plan: string): { family: 'openai' | 'anthropic' | null; id: string } {+ const family = PLAN_FAMILIES[vendor.trim().toLowerCase()] ?? null;+ const folded = plan.trim().toLowerCase().replace(/[\s-]+/g, '_');+ const prefix = family ? PLAN_PREFIX[family] : null;+ const id = prefix && folded.startsWith(prefix) ? folded.slice(prefix.length) : folded;+ return { family, id };+}++/** An unknown plan id in words: `team_plus-annual` → 「Team Plus Annual」. */+export function titleCasePlan(plan: string): string {+ return plan.trim().split(/[\s_-]+/).filter(Boolean)+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))+ .join(' ');+}+const instant = (value: string | null): number | null => {if (value === null) return null;const ms = Date.parse(value);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1048556ed..b4d233d36 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1355,7 +1355,7 @@"pace": {"ok": "Lasts until reset","slightlyFast": "A little fast, still lasts until reset",- "fast": "Running fast, expected to run out {{time}}",+ "fast": "Running fast, expected to run out in {{duration}}","exhausted": "Used up, back in {{duration}}","exhaustedUnknown": "Used up","paused": "Updates paused",@@ -1389,13 +1389,11 @@},"duration": {"days": "{{days}}d {{hours}}h",+ "daysOnly": "{{days}}d","hours": "{{hours}}h {{minutes}}m",+ "hoursOnly": "{{hours}}h","minutes": "{{minutes}}m"},- "clock": {- "today": "today {{time}}",- "tomorrow": "tomorrow {{time}}"- },"stat": {"tightest": "Lowest remaining limit","tightestAllSpent": "Every limit is used up",@@ -1404,7 +1402,7 @@"exhaustedUnit": "limits","exhaustedNone": "Every account is usable","exhaustedNoneObserved": "None used up in current readings",- "exhaustedNote": "{{name}} · back {{time}}",+ "exhaustedNote": "{{name}} · back in {{duration}}","resetsIn": "resets in {{duration}}","weekValue": "Last 7 days at API price","weekValueNote": "All subscription use, at the vendors’ published API prices",@@ -1440,6 +1438,27 @@"renewsIn_one": "in {{count}} day","renewsIn_other": "in {{count}} days","excluded": "{{tokens}} tokens have no price and are left out"+ },+ "plan": {+ "openai": {+ "free": "Free",+ "go": "Go",+ "plus": "Plus",+ "pro": "Pro",+ "prolite": "Pro 5x",+ "pro_5x": "Pro 5x",+ "team": "Team",+ "business": "Business",+ "enterprise": "Enterprise",+ "edu": "Edu"+ },+ "anthropic": {+ "pro": "Pro",+ "max_5x": "Max 5x",+ "max_20x": "Max 20x",+ "team": "Team",+ "enterprise": "Enterprise"+ }}},"usage": {diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 17589d590..271219e3f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1355,7 +1355,7 @@"pace": {"ok": "够用到重置","slightlyFast": "稍快,仍够用到重置",- "fast": "用得偏快,预计 {{time}} 用完",+ "fast": "用得偏快,预计 {{duration}}后用完","exhausted": "已用完,{{duration}}后恢复","exhaustedUnknown": "已用完","paused": "暂停更新",@@ -1389,13 +1389,11 @@},"duration": {"days": "{{days}} 天 {{hours}} 小时",+ "daysOnly": "{{days}} 天","hours": "{{hours}} 小时 {{minutes}} 分",+ "hoursOnly": "{{hours}} 小时","minutes": "{{minutes}} 分钟"},- "clock": {- "today": "今天 {{time}}",- "tomorrow": "明天 {{time}}"- },"stat": {"tightest": "余量最少的额度","tightestAllSpent": "所有额度都已用完",@@ -1404,7 +1402,7 @@"exhaustedUnit": "项额度","exhaustedNone": "所有账号都能正常使用","exhaustedNoneObserved": "已读到的额度都没用完",- "exhaustedNote": "{{name}} · {{time}} 恢复",+ "exhaustedNote": "{{name}} · {{duration}}后恢复","resetsIn": "{{duration}}后重置","weekValue": "近 7 天按 API 价格","weekValueNote": "所有订阅账号的用量,按官方 API 标价计算",@@ -1440,6 +1438,27 @@"renewsIn_one": "{{count}} 天","renewsIn_other": "{{count}} 天","excluded": "{{tokens}} tokens 暂无价格,未计入"+ },+ "plan": {+ "openai": {+ "free": "Free",+ "go": "Go",+ "plus": "Plus",+ "pro": "Pro",+ "prolite": "Pro 5x",+ "pro_5x": "Pro 5x",+ "team": "Team",+ "business": "Business",+ "enterprise": "Enterprise",+ "edu": "Edu"+ },+ "anthropic": {+ "pro": "Pro",+ "max_5x": "Max 5x",+ "max_20x": "Max 20x",+ "team": "Team",+ "enterprise": "Enterprise"+ }}},"usage": {