Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): name unrecognised quota limits in words on one line (#2199)

Call Whiteb7404abf1473
diff --git a/core/handlers/model_hub/quota.py b/core/handlers/model_hub/quota.py
index 2e05bedcf..0f384712f 100644
--- a/core/handlers/model_hub/quota.py
+++ b/core/handlers/model_hub/quota.py
@@ -137,6 +137,7 @@ def _window(
window_seconds: Optional[int],
resets_at: Optional[str],
scope_model: Optional[str] = None,
+ label_is_key: bool = False,
) -> dict[str, Any]:
window: dict[str, Any] = {
"id": window_id[:128],
@@ -149,6 +150,9 @@ def _window(
}
if scope_model is not None:
window["scope_model"] = scope_model
+ # Only the parser knows whether `label` is an upstream key or display text.
+ if label_is_key:
+ window["label_is_key"] = True
return window
@@ -186,6 +190,7 @@ def _claude_limit_rows(rows: list[object]) -> list[dict[str, Any]]:
scope_model = _label(model.get("display_name"))
resets_at = _iso_timestamp(row.get("resets_at"))
# Classify on the server's `kind`, never on its display text.
+ label_is_key = False
if upstream_kind == "session":
kind: QuotaWindowKind = "session"
seconds: Optional[int] = SESSION_WINDOW_SECONDS
@@ -196,9 +201,11 @@ def _claude_limit_rows(rows: list[object]) -> list[dict[str, Any]]:
kind, seconds, label = "model_weekly", WEEKLY_WINDOW_SECONDS, scope_model
else:
surface = scope.get("surface") if isinstance(scope.get("surface"), dict) else {}
- generic = scope_model or _label(surface.get("display_name")) or _label(upstream_kind)
+ display = scope_model or _label(surface.get("display_name"))
+ generic = display or _label(upstream_kind)
if generic is None:
continue
+ label_is_key = display is None
kind = "other"
seconds = WEEKLY_WINDOW_SECONDS if row.get("group") == "weekly" else None
label = generic
@@ -211,6 +218,7 @@ def _claude_limit_rows(rows: list[object]) -> list[dict[str, Any]]:
window_seconds=seconds,
resets_at=resets_at,
scope_model=scope_model if kind == "model_weekly" else None,
+ label_is_key=label_is_key,
)
)
return windows
@@ -245,6 +253,7 @@ def _claude_top_level(payload: Mapping[str, Any]) -> list[dict[str, Any]]:
window_seconds=seconds,
resets_at=_iso_timestamp(value.get("resets_at")),
scope_model=scope_model,
+ label_is_key=kind == "other",
)
)
return windows
@@ -367,9 +376,11 @@ def parse_codex_quota(body: object) -> dict[str, Any]:
if not isinstance(item, dict) or not isinstance(item.get("rate_limit"), dict):
continue
feature = item.get("metered_feature")
- scope_model = (
+ named = (
_CODEX_FEATURE_LABELS.get(feature) if isinstance(feature, str) else None
- ) or _label(item.get("limit_name")) or _label(feature)
+ ) or _label(item.get("limit_name"))
+ # Named by `metered_feature` alone, the label is that feature's id.
+ scope_model = named or _label(feature)
if scope_model is None:
continue
for slot in ("primary_window", "secondary_window"):
@@ -388,6 +399,7 @@ def parse_codex_quota(body: object) -> dict[str, Any]:
window_seconds=seconds,
resets_at=resets_at,
scope_model=scope_model if weekly else None,
+ label_is_key=named is None,
)
)
plan = _label(payload.get("plan_type"))
diff --git a/docs/plans/model-hub-contracts/quota-summary.schema.json b/docs/plans/model-hub-contracts/quota-summary.schema.json
index dbc84e3ed..1d14cedde 100644
--- a/docs/plans/model-hub-contracts/quota-summary.schema.json
+++ b/docs/plans/model-hub-contracts/quota-summary.schema.json
@@ -172,6 +172,10 @@
"minLength": 1,
"maxLength": 64
},
+ "label_is_key": {
+ "description": "Present (true) when `label` (and `scope_model`, if any) is an upstream identifier rather than display text, so the UI may read it as words. Absent means show it as written.",
+ "const": true
+ },
"used_pct": {
"type": "number",
"minimum": 0,
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 9dde9b7c8..8249a43a6 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -871,7 +871,7 @@ scenarios:
layer: unit
test: ui/src/components/settings/models/QuotaTab.test.tsx::MH-QUOTA-014
- id: MH-QUOTA-015
- name: The quota tab stays within a narrow viewport
+ name: The quota tab stays within a narrow viewport and names an unrecognised limit in words on one line
status: covered
kind: observation
layer: unit
diff --git a/tests/test_model_hub_quota.py b/tests/test_model_hub_quota.py
index 6073c1eb9..8be4d3c45 100644
--- a/tests/test_model_hub_quota.py
+++ b/tests/test_model_hub_quota.py
@@ -160,6 +160,42 @@ def test_claude_quota_parser_prefers_server_limits_and_keeps_unknown_rows():
assert "scope_model" not in other
+def test_quota_windows_mark_exactly_the_labels_that_are_upstream_keys():
+ """MH-QUOTA-002/003: `label_is_key` marks a label taken from an upstream key, never a display name."""
+
+ def flagged(windows):
+ return {window["label"]: window.get("label_is_key", False) for window in windows}
+
+ # Claude top level: an unknown key is its own label; known keys carry product copy.
+ legacy = {**CLAUDE_LEGACY, "seven_day_cowork": {"utilization": 5, "resets_at": None}}
+ windows = parse_claude_quota(json.dumps(legacy))["windows"]
+ _validate_windows({"windows": windows})
+ assert flagged(windows) == {"five_hour": False, "seven_day": False, "Sonnet": False, "Fable": False,
+ "seven_day_cowork": True}
+ # Claude `limits[]`: only the `kind` fallback is a key; model and surface display names are text.
+ limits = {"limits": [
+ {"kind": "monthly_surface", "percent": 1, "scope": {"surface": {"display_name": "claude-code"}}},
+ {"kind": "monthly_model", "percent": 2, "scope": {"model": {"display_name": "Claude_Code"}}},
+ {"kind": "seven_day_cowork", "percent": 3, "scope": {}},
+ ]}
+ windows = parse_claude_quota(json.dumps(limits))["windows"]
+ _validate_windows({"windows": windows})
+ assert flagged(windows) == {"claude-code": False, "Claude_Code": False, "seven_day_cowork": True}
+ # Codex: `limit_name` is display text; a lone `metered_feature` is the feature's id.
+ window = {"used_percent": 3, "limit_window_seconds": 3600, "reset_after_seconds": 10, "reset_at": 1790000100}
+ weekly = {**window, "limit_window_seconds": 604800}
+ report = {"additional_rate_limits": [
+ {"limit_name": "gpt_5_codex", "metered_feature": "x_feature", "rate_limit": {"primary_window": window}},
+ {"metered_feature": "future_feature", "rate_limit": {"primary_window": window, "secondary_window": weekly}},
+ {"metered_feature": "codex_bengalfox", "rate_limit": {"primary_window": weekly}},
+ ]}
+ windows = parse_codex_quota(json.dumps(report))["windows"]
+ _validate_windows({"windows": windows})
+ assert flagged(windows) == {"gpt_5_codex · 1h": False, "future_feature · 1h": True, "future_feature": True,
+ "Spark": False}
+ assert next(w for w in windows if w["label"] == "future_feature")["scope_model"] == "future_feature"
+
+
@pytest.mark.parametrize(
("seconds", "label"),
[(60, "1m"), (1800, "30m"), (3600, "1h"), (5400, "1h 30m"), (18000, "5h"), (86400, "1d"),
diff --git a/ui/e2e/model-catalog/quota-layout.spec.ts b/ui/e2e/model-catalog/quota-layout.spec.ts
index 248685a01..d6ba910b8 100644
--- a/ui/e2e/model-catalog/quota-layout.spec.ts
+++ b/ui/e2e/model-catalog/quota-layout.spec.ts
@@ -10,6 +10,32 @@ 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 };
+const SPAN = { en: '7-day Cowork', zh: '7 天 Cowork' } as const;
+
+/**
+ * MH-QUOTA-015: an unrecognised upstream id reads as words, and every row title
+ * holds one line beside its remaining figure — a name longer than the row
+ * ellipsizes, keeping its full text as the title and the meter's name.
+ */
+const titlesHold = async (page: Page, lang: 'en' | 'zh') => {
+ await expect(page.locator('[data-quota-window="seven_day_cowork"] .model-hub-quota-row-title strong')).toHaveText(SPAN[lang]);
+ for (const title of await page.locator('.model-hub-quota-row-title').all()) await expect(title).not.toContainText(/_/);
+ const stress = page.locator('[data-quota-window="x"] .model-hub-quota-row-title strong');
+ const name = 'Unrecognised Upstream Limit Name Unrecognised Upstream Limit Name';
+ await expect(stress).toHaveAttribute('title', name);
+ await expect(page.locator('[data-quota-window="x"] [role="meter"]')).toHaveAccessibleName(new RegExp(`^${name}`));
+ expect(await stress.evaluate((el) => el.scrollWidth > el.clientWidth && getComputedStyle(el).textOverflow === 'ellipsis')).toBe(true);
+ for (const row of await page.locator('[data-quota-window]').all()) {
+ const title = row.locator('.model-hub-quota-row-title');
+ const [titleBox, leftBox, rowBox] = await Promise.all([box(title), box(row.locator('.model-hub-quota-left')), box(row)]);
+ const lineHeight = await title.locator('strong').evaluate((el) => parseFloat(getComputedStyle(el).lineHeight));
+ expect(titleBox.height).toBeLessThanOrEqual(lineHeight + 1);
+ expect(overlaps(titleBox, leftBox)).toBe(false);
+ expect(titleBox.x + titleBox.width).toBeLessThanOrEqual(leftBox.x);
+ expect(leftBox.x + leftBox.width).toBeLessThanOrEqual(rowBox.x + rowBox.width + 1);
+ }
+};
+
/**
* 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
@@ -32,7 +58,7 @@ const openHintClear = async (page: Page, width: number, touch: boolean) => {
};
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) => {
+ test(`MH-QUOTA-015: holds the narrow layout at ${width}px — one account per line, stacked footers, one-line 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');
@@ -55,12 +81,7 @@ for (const [lang, width] of [['en', 360], ['zh', 360], ['en', 390], ['zh', 390]]
expect(await fits(row)).toBe(true);
}
- // A long upstream name wraps inside its card instead of widening it.
- const title = page.locator('[data-quota-window="x"] .model-hub-quota-row-title');
- const [titleBox, cardBox] = await Promise.all([box(title), box(cards.nth(0))]);
- expect(titleBox.x + titleBox.width).toBeLessThanOrEqual(cardBox.x + cardBox.width);
- expect(await fits(title)).toBe(true);
- expect(titleBox.height).toBeGreaterThan(20);
+ await titlesHold(page, lang);
// Each upcoming-reset chip stays inside the list; a long window name
// truncates rather than pushing the chip, or its time, past the edge.
@@ -109,6 +130,7 @@ for (const lang of ['en', 'zh'] as const) {
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 titlesHold(page, lang);
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.tsx
index 1d696c80b..0dc76f0b9 100644
--- a/ui/e2e/model-catalog/quotaFixture.tsx
+++ b/ui/e2e/model-catalog/quotaFixture.tsx
@@ -21,7 +21,8 @@ const valued = (over: Partial<SourceQuotaValue>): SourceQuotaValue => ({
...over,
});
-// Two accounts, one with an unrecognised window whose upstream name is one long word;
+// Two accounts, one with unrecognised windows — a realistic new upstream id and a
+// stress-case identifier far longer than its row;
// one paid off many times over on a known cycle, one short on the trailing 30 days.
const sources: SourceQuota[] = [
@@ -31,7 +32,8 @@ const sources: SourceQuota[] = [
windows: [
limit({}),
limit({ id: 'seven_day', label: 'seven_day', used_pct: 61, ...weekly }),
- limit({ ...weekly, id: 'x', kind: 'other', label: 'unrecognised_upstream_limit_name_'.repeat(2), used_pct: 12 }),
+ limit({ ...weekly, id: 'x', kind: 'other', label: 'unrecognised_upstream_limit_name_'.repeat(2), label_is_key: true, used_pct: 12 }),
+ limit({ ...weekly, id: 'seven_day_cowork', kind: 'other', label: 'seven_day_cowork', label_is_key: true, used_pct: 27 }),
],
value: valued({
plan_key: 'claude_max_20x', fee_usd: 200, multiple: 6.4201, week: priced(412.37),
diff --git a/ui/src/components/settings/models/QuotaTab.test.tsx b/ui/src/components/settings/models/QuotaTab.test.tsx
index c092944dd..4b7dfc956 100644
--- a/ui/src/components/settings/models/QuotaTab.test.tsx
+++ b/ui/src/components/settings/models/QuotaTab.test.tsx
@@ -258,6 +258,35 @@ describe('QuotaTab', () => {
expect(screen.getByRole('article').querySelector('[data-quota-window="x"] small')).toBeNull();
});
+ it('names an unrecognised identifier in words, its span in the window wording, with the full name as its title', async () => {
+ const title = () => screen.getByRole('article').querySelector('[data-quota-window="x"] strong')!;
+ draw(readyRegion(summary([claude({ windows: [window({ id: 'x', kind: 'other', label: 'seven_day_cowork', label_is_key: true })] })])));
+ expect(title().textContent).toBe('7 天 Cowork');
+ expect(title().getAttribute('title')).toBe('7 天 Cowork');
+ expect(screen.queryByText(/seven_day/)).toBeNull();
+ await i18n.changeLanguage('en');
+ try {
+ cleanup();
+ draw(readyRegion(summary([claude({ windows: [
+ window({ id: 'x', kind: 'other', label: 'seven_day_cowork', label_is_key: true }),
+ window({ id: 'y', kind: 'model_weekly', label: 'claude_opus', scope_model: 'claude_opus', label_is_key: true }),
+ window({ id: 'z', kind: 'other', label: 'future_feature · 1h', label_is_key: true }),
+ ] })])));
+ expect(title().textContent).toBe('7-day Cowork');
+ expect(screen.getByText('Claude Opus weekly limit')).toBeTruthy();
+ expect(screen.getByRole('meter', { name: '7-day Cowork: 38% used' })).toBeTruthy();
+ expect(screen.getByText('Future Feature · 1h')).toBeTruthy();
+ } finally {
+ await i18n.changeLanguage('zh');
+ }
+ });
+
+ it('shows an upstream display name as written unless the server marks it an id', () => {
+ const labels = ['Claude_Code', 'claude-code', 'seven_day_cowork', 'GPT-5 Codex'];
+ draw(readyRegion(summary([claude({ windows: labels.map((label, index) => window({ id: `o${index}`, kind: 'other', label })) })])));
+ for (const label of labels) expect(screen.getByText(label)).toBeTruthy();
+ });
+
it('renders the English copy through the same keys', async () => {
await i18n.changeLanguage('en');
try {
diff --git a/ui/src/components/settings/models/QuotaTab.tsx b/ui/src/components/settings/models/QuotaTab.tsx
index 276c747da..02d3f0a86 100644
--- a/ui/src/components/settings/models/QuotaTab.tsx
+++ b/ui/src/components/settings/models/QuotaTab.tsx
@@ -25,6 +25,7 @@ import {
HOUR_MS,
MINUTE_MS,
exhaustedWindows,
+ limitLabelParts,
quotaDuration,
quotaIsLive,
quotaIsRetained,
@@ -88,18 +89,32 @@ const useQuotaText = (now: number) => {
? t('settings.models.quota.ago.minutes', { count: Math.max(1, Math.round(ms / MINUTE_MS)) }) as string
: t('settings.models.quota.ago.long', { duration: duration(ms) }) as string;
}, [duration, now, t]);
+ /**
+ * An upstream name as shown. Display text stays as written; a name the server
+ * marks as an upstream id (`seven_day_cowork`) reads as words, its spans in this
+ * product's window wording (「7-day Cowork」). A composed name (`feature_id · 1h`)
+ * reads each id in it the same way.
+ */
+ const upstreamName = React.useCallback((label: string, isKey: boolean) => (isKey
+ ? label.split(/(\s+)/).map((token) => {
+ const parts = limitLabelParts(token);
+ return parts ? parts.map((part) => ('span' in part
+ ? t(`settings.models.quota.window.span.${part.span}`, { [part.span]: part.count }) as string
+ : part.word)).join(' ') : token;
+ }).join('')
+ : label), [t]);
/** A window's name: the vendor's own model name, framed in this product's words. */
const windowLabel = React.useCallback((window: QuotaWindow) => {
if (window.kind === 'session') return t('settings.models.quota.window.session') as string;
if (window.kind === 'weekly') return t('settings.models.quota.window.weekly') as string;
- if (window.kind === 'model_weekly') return t('settings.models.quota.window.model', { model: window.scope_model ?? window.label }) as string;
- return window.label;
- }, [t]);
+ if (window.kind === 'model_weekly') return t('settings.models.quota.window.model', { model: upstreamName(window.scope_model ?? window.label, Boolean(window.label_is_key)) }) as string;
+ return upstreamName(window.label, Boolean(window.label_is_key));
+ }, [t, upstreamName]);
const windowHint = React.useCallback((window: QuotaWindow) => {
- if (window.kind === 'model_weekly') return t('settings.models.quota.hint.model', { model: window.scope_model ?? window.label }) as string;
+ if (window.kind === 'model_weekly') return t('settings.models.quota.hint.model', { model: upstreamName(window.scope_model ?? window.label, Boolean(window.label_is_key)) }) as string;
if (window.kind === 'session' || window.kind === 'weekly') return t('settings.models.quota.hint.shared') as string;
return null;
- }, [t]);
+ }, [t, upstreamName]);
const paceText = React.useCallback((pace: QuotaPace) => {
switch (pace.kind) {
case 'paused': return t('settings.models.quota.pace.paused') as string;
@@ -143,9 +158,9 @@ const WindowRow: React.FC<{ window: QuotaWindow; now: number; retained: boolean;
return (
<div className={cn('model-hub-quota-row', nested && 'model-hub-quota-row--nested')} data-quota-window={window.id}>
<div className="flex items-end justify-between gap-2.5">
- <div className="model-hub-quota-row-title min-w-0">
- <strong className="font-medium text-foreground">{label}</strong>
- {hint && <small>{hint}</small>}
+ <div className="model-hub-quota-row-title flex min-w-0 items-baseline">
+ <strong className="min-w-0 truncate font-medium text-foreground" title={label}>{label}</strong>
+ {hint && <small title={hint}>{hint}</small>}
</div>
<div className={cn('model-hub-quota-left flex shrink-0 items-baseline gap-1', toneClass(reading.tone))}>
<b>{windowLeftPct(window, now)}%</b>
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index 824aad37f..fabef4def 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -3058,11 +3058,16 @@
padding-left: var(--model-hub-quota-nested-indent);
border-left: 2px solid var(--border);
}
+/* One line beside the remaining figure: a long name ellipsizes, never wraps under it. */
.model-hub-quota-row-title {
font-size: var(--model-hub-usage-cell-size);
- overflow-wrap: anywhere;
+ white-space: nowrap;
}
.model-hub-quota-row-title small {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ flex-shrink: 4;
margin-left: 8px;
color: var(--model-hub-usage-note-ink);
font-size: var(--model-hub-quota-hint-size);
diff --git a/ui/src/components/settings/models/quotaProjection.test.ts b/ui/src/components/settings/models/quotaProjection.test.ts
new file mode 100644
index 000000000..aae46df91
--- /dev/null
+++ b/ui/src/components/settings/models/quotaProjection.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { limitLabelParts } from './quotaProjection';
+
+describe('limitLabelParts', () => {
+ it('reads an identifier as words, its spans as counts', () => {
+ expect(limitLabelParts('seven_day_cowork')).toEqual([{ span: 'days', count: 7 }, { word: 'Cowork' }]);
+ expect(limitLabelParts('five_hour')).toEqual([{ span: 'hours', count: 5 }]);
+ expect(limitLabelParts('30_day-opus')).toEqual([{ span: 'days', count: 30 }, { word: 'Opus' }]);
+ expect(limitLabelParts('codex_12_hours')).toEqual([{ word: 'Codex' }, { span: 'hours', count: 12 }]);
+ expect(limitLabelParts('primary_window')).toEqual([{ word: 'Primary' }, { word: 'Window' }]);
+ expect(limitLabelParts('Seven_Day')).toEqual([{ span: 'days', count: 7 }]);
+ expect(limitLabelParts('seven-day-cowork')).toEqual([{ span: 'days', count: 7 }, { word: 'Cowork' }]);
+ });
+
+ it('reads a compound number word as one count', () => {
+ expect(limitLabelParts('twenty_four_hour')).toEqual([{ span: 'hours', count: 24 }]);
+ expect(limitLabelParts('twenty_eight_day_opus')).toEqual([{ span: 'days', count: 28 }, { word: 'Opus' }]);
+ expect(limitLabelParts('thirty_day')).toEqual([{ span: 'days', count: 30 }]);
+ expect(limitLabelParts('fourteen_day')).toEqual([{ span: 'days', count: 14 }]);
+ expect(limitLabelParts('twenty_twelve_day')).toEqual([{ word: 'Twenty' }, { span: 'days', count: 12 }]);
+ });
+
+ it('keeps a count or unit that does not form a span as a word', () => {
+ expect(limitLabelParts('day_pass')).toEqual([{ word: 'Day' }, { word: 'Pass' }]);
+ expect(limitLabelParts('gpt_5_mini')).toEqual([{ word: 'Gpt' }, { word: '5' }, { word: 'Mini' }]);
+ expect(limitLabelParts('0_day')).toEqual([{ word: '0' }, { word: 'Day' }]);
+ });
+
+ it('declines a token that is not id-shaped', () => {
+ for (const label of ['Opus', 'fable', 'Code review', '非常长的上游额度名称', 'GPT-5 Codex', 'seven day', '', '__', 'a.b_c']) {
+ expect(limitLabelParts(label)).toBeNull();
+ }
+ });
+});
diff --git a/ui/src/components/settings/models/quotaProjection.ts b/ui/src/components/settings/models/quotaProjection.ts
index 257a93074..543d91d30 100644
--- a/ui/src/components/settings/models/quotaProjection.ts
+++ b/ui/src/components/settings/models/quotaProjection.ts
@@ -201,3 +201,51 @@ export function quotaPayback(costUsd: number, feeUsd: number): QuotaPayback | nu
if (multiple >= 1) return { kind: 'even', multiple, surplusUsd: costUsd - feeUsd };
return { kind: 'short', multiple, shortfallUsd: feeUsd - costUsd };
}
+
+/** One piece of an upstream limit id read as words: a span the copy names, or a plain word. */
+export type LimitLabelPart = { span: 'hours' | 'days'; count: number } | { word: string };
+
+const SPAN_ONES: Record<string, number> = {
+ one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10,
+ eleven: 11, twelve: 12, thirteen: 13, fourteen: 14, fifteen: 15, sixteen: 16, seventeen: 17,
+ eighteen: 18, nineteen: 19,
+};
+const SPAN_TENS: Record<string, number> = { twenty: 20, thirty: 30, forty: 40, fifty: 50, sixty: 60, seventy: 70, eighty: 80, ninety: 90 };
+const SPAN_UNITS: Record<string, 'hours' | 'days'> = { hour: 'hours', hours: 'hours', day: 'days', days: 'days' };
+
+/** The count starting at `index` — digits, or number words such as `twenty_four` — and the tokens it spans. */
+const spanCount = (tokens: string[], index: number): { count: number; length: number } | null => {
+ const [first, second] = [tokens[index]?.toLowerCase(), tokens[index + 1]?.toLowerCase()];
+ if (/^\d+$/.test(first)) return { count: Number(first), length: 1 };
+ const tens = SPAN_TENS[first];
+ if (tens !== undefined) {
+ const ones = SPAN_ONES[second];
+ return ones !== undefined && ones < 10 ? { count: tens + ones, length: 2 } : { count: tens, length: 1 };
+ }
+ return SPAN_ONES[first] !== undefined ? { count: SPAN_ONES[first], length: 1 } : null;
+};
+
+/**
+ * An upstream limit id (`seven_day_cowork`), read as words: a count followed by
+ * `hour`/`day` becomes a span, every other token a word. Whether a name is an id
+ * is the server's call (`label_is_key`); this only declines a token that is not
+ * id-shaped — spaces, CJK, or a single bare word — with `null`.
+ */
+export function limitLabelParts(label: string): LimitLabelPart[] | null {
+ if (!/^[A-Za-z0-9_-]+$/.test(label) || !/[_-]/.test(label)) return null;
+ const tokens = label.split(/[_-]+/).filter(Boolean);
+ if (!tokens.length) return null;
+ const parts: LimitLabelPart[] = [];
+ for (let index = 0; index < tokens.length; index += 1) {
+ const counted = spanCount(tokens, index);
+ const unit = counted && SPAN_UNITS[tokens[index + counted.length]?.toLowerCase() ?? ''];
+ if (counted && counted.count > 0 && unit) {
+ parts.push({ span: unit, count: counted.count });
+ index += counted.length;
+ } else {
+ const token = tokens[index];
+ parts.push({ word: token.charAt(0).toUpperCase() + token.slice(1) });
+ }
+ }
+ return parts;
+}
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 8462d41b3..e6990c37c 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -891,6 +891,8 @@ export type QuotaWindow = {
label: string;
/** Present on `model_weekly`: the model the window alone counts. */
scope_model?: string;
+ /** Present when `label` (and `scope_model`) is an upstream id, not display text. */
+ label_is_key?: true;
used_pct: number;
window_seconds: number | null;
resets_at: string | null;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b4d233d36..c6fa26bad 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -1342,7 +1342,11 @@
"window": {
"session": "5-hour limit",
"weekly": "Weekly limit",
- "model": "{{model}} weekly limit"
+ "model": "{{model}} weekly limit",
+ "span": {
+ "hours": "{{hours}}-hour",
+ "days": "{{days}}-day"
+ }
},
"hint": {
"shared": "Shared by all models",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 271219e3f..98e68dfec 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -1342,7 +1342,11 @@
"window": {
"session": "5 小时额度",
"weekly": "每周额度",
- "model": "{{model}} 每周额度"
+ "model": "{{model}} 每周额度",
+ "span": {
+ "hours": "{{hours}} 小时",
+ "days": "{{days}} 天"
+ }
},
"hint": {
"shared": "所有模型共用",