Skip to content

Commit 7b90456

Browse files
feat(app-shell): the ChatDock AI usage ring shows a paid plan's personal allowance and team pool from the optional usage tiers (#38166)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4Uu8kvQsncv3LostTj6PCZc7E)_ Fixes #38034 repo:objectstack#2 · os-sales · session_01L6bhgUwzku2SuraR6YUBVi Clause-②: no Metadata-protocol: none ## 维护者速读 - 付费版成员打开聊天框右上角的 AI 额度环,弹层里会分两行显示「个人额度」和「团队共享额度」各用了多少、何时重置;个人额度用完、开始用团队额度时,弹层里多一条服务端给的提示(按界面语言显示中文、日文、西班牙文或英文)。免费版、私有部署和旧后端没有这项数据,额度环和弹层保持现在的样子。 - 这是云端「AI 两层额度:个人额度加团队共享池」的界面半边,让用了团队额度的人看得见、团队也知道是谁的额度快用完了。 - 只改聊天框的读数和弹层,不动服务端、不动额度判断;服务端给的这项数据格式不对时只丢这一项,额度环照常显示。有问题可直接撤回。 - 无 ## What changes - `ui/packages/app-shell/src/hooks/useAiUsage.ts`: `parseUsage` reads the optional `tiers` of `GET /api/v1/ai/usage` (cloud#5159, cloud PR #5163) in exactly its declared shape: `personal` (a tier or `null` for a pool-only caller), `teamPool`, `usingTeamPool`, `notice` (`{ en, zh, ja, es }` or `null`). Each tier is `{ fraction, resetsAt }`, copied to those fields only. A `tiers` of any other shape is dropped on its own and the `{ pool, breakdown }` reading stands, so the ring still renders (the card's acceptance item). `pool` and `breakdown` parse exactly as before, including the strict refusal of a malformed `breakdown`. - `ui/packages/app-shell/src/layout/AiUsageIndicator.tsx`: when `tiers` is present the popover shows one row per tier (label, the existing qualitative status word, the used share as one percentage, the tier's own reset countdown from its `resetsAt`) and the notice when it is non-null. `personal: null` shows the team pool row alone. The ring, the trigger's status word, the popover's status, reset line and call to action keep reading `pool`, the binding reading. Without `tiers` nothing renders differently. - `ui/packages/i18n/src/locales/*.ts`: two new keys, `console.ai.usage.tierPersonal` and `console.ai.usage.tierTeamPool`, in all 11 packs (zh-Hant regenerated with `gen:zh-hant`, not hand-written). - `.changeset/38034-ai-usage-tiers.md`: patch for `@object-ui/app-shell` and `@object-ui/i18n`. ### Small calls this PR made (listed for review) 1. **The pool's own "N% used" line gives way to the two tier rows when `tiers` is present.** Otherwise the popover would carry three percentages, two of which are usually the same number (the pool reads the personal share while it lasts). The pool's status word, reset line and CTA stay, because `pool` can be the 5-hour pace, which neither tier shows. The card says the popover "widens to two only when `tiers` is present"; this reads that as two figures. 2. **Notice language:** every Chinese script (`zh-Hans`, `zh-Hant`) reads `zh`; `ja` and `es` read their own; every other console language reads `en`, as the card says. 3. **A tier's reset** has no window kind on the wire, so it counts down from its own `resetsAt` the way the weekly window does (days, then hours inside the final day); `resetsAt: null` shows no line, never a guess (objectui#7371). 4. The notice is shown whenever it is non-null; the hook does not cross-check it against `usingTeamPool` (the wire says the two agree; the reader does not second-guess the producer). 5. The new tier types are not added to the package's public `hooks/index.ts` exports (the existing `AiUsageBreakdown` is not exported either); `AiUsageResponse.tiers` carries them structurally. ## Read first 1. `ui/packages/app-shell/src/hooks/useAiUsage.ts`, `readTiers` and the new `parseUsage`: the one place a malformed answer could blank the ring. Risky hunk: the `personal` / `notice` null-versus-malformed branches. 2. `ui/packages/app-shell/src/layout/AiUsageIndicator.tsx`, the `tiers ? null : (…pool-used…)` swap and the tier rows block. 3. `ui/packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx`, `describe('the paid plan tiers')`. ## Tests <details><summary>Targeted vitest (local, head 40f5639)</summary> ``` cd ui && pnpm exec vitest run --maxWorkers=2 packages/app-shell/src/hooks/__tests__/useAiUsage.test.ts packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx packages/app-shell/src/layout/__tests__/AiUsageIndicator.aiOff-11799.test.tsx packages/i18n/ Test Files 112 passed (112) Tests 1935 passed | 13 skipped (1948) os-verify-lock: VERDICT command-exit 0 ``` The `packages/i18n/` run includes `all-locales-key-parity.test.ts` and `zh-hant-generated.test.ts`. </details> <details><summary>Ablation (behaviour pinned by the new tests)</summary> `parseUsage` mutated on disk to never attach `tiers` (`if (read && false) out.tiers = read;`), same two files re-run: 4 failed / 55 passed (`reads a valid tiers…`, `reads personal: null…`, `copies tiers to its declared fields only`, `renders the tier rows for an answer that carries tiers`), exit 1. Restored with `git checkout`; the green run above is on the restored file. </details> <details><summary>Type-check and lint</summary> - `pnpm --filter @object-ui/app-shell run type-check && pnpm --filter @object-ui/i18n run type-check`: VERDICT command-exit 0 (both `tsc --noEmit` and `tsc -p tsconfig.test.json` for each). - `eslint --no-inline-config` on the four changed app-shell files and `en.ts`: exit 0, 0 errors; 2 `react-hooks/set-state-in-effect` warnings, both on lines this PR does not touch (the existing fetch effect in `useAiUsage.ts` and `setNow` mount effect in `AiUsageIndicator.tsx`). - Dependency closure built first: `turbo run build --filter='@object-ui/app-shell^...'`, 72/72 tasks, exit 0. </details> <details><summary>Derived gate families (local)</summary> `node scripts/pm/dispatch-gates.mjs --commands` at head 40f5639 derived 41 families; each run locally with its exit code captured before any pipe: ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-sdui-manifest.mjs :: exit 0 node scripts/check-sdui-manifest.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/pm/check-governed-queue-guard.mjs --self-test :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --dir ui exec vitest run scripts/ :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm check:adr-anchors :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:engine-double-contract :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:merge-driver :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:pm-expected-skips :: exit 0 pnpm check:published-files :: exit 0 pnpm check:query-options-erasure :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:role-word :: exit 0 pnpm check:skill-identifier-liveness :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:type-check-coverage :: exit 0 pnpm check:type-check-debt :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:watch-hint-literal :: exit 0 pnpm check:where-matcher :: exit 0 ``` `dispatch-gates --ran`: `41 derived famil(ies) accounted for — 41 run, 0 NOT-MEASURED`. Also run (outside the derived list): `pnpm --dir ui run check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys`, each exit 0. </details> ## Acceptance notes - The card named `ui/packages/app-shell` only; the console strings live in `ui/packages/i18n`, and key parity needs each new `en` key in every pack. The claim's `Premise:` line records the corrected file surface; the goal is unchanged. - No reach until cloud PR #5163 ships `tiers`; until then every answer takes the unchanged no-`tiers` path. - `test:repo` (vitest `repo` project) not run locally: this diff touches none of its tests; CI's `Test Core` runs it. ## Verification Two minutes: run `cd ui && pnpm exec vitest run packages/app-shell/src/layout/__tests__/AiUsageIndicator.test.tsx -t "paid plan tiers"`; expect 12 passing tests, including the notice in each console language. --- _Generated by [Claude Code](https://claude.ai/code/session_01L6bhgUwzku2SuraR6YUBVi)_ <!-- signed: repo:objectstack#2 · os-sales · session_01L6bhgUwzku2SuraR6YUBVi --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7d6692e commit 7b90456

16 files changed

Lines changed: 395 additions & 13 deletions

File tree

‎.changeset/38034-ai-usage-tiers.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@object-ui/app-shell': patch
3+
'@object-ui/i18n': patch
4+
---
5+
6+
feat(app-shell): the ChatDock AI usage ring shows a paid plan's personal allowance and team pool, and the notice once turns draw on the team pool
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
`GET /api/v1/ai/usage` may now carry an optional `tiers` on a paid plan: the caller's personal share, the team pool it overflows into, whether turns draw on the pool, and a notice in four languages. The usage hook reads it in exactly that shape; a `tiers` of any other shape is dropped on its own and the `{ pool, breakdown }` reading stands, so the ring still renders. When `tiers` is present, the popover shows one row per tier (its status, its used share as a percentage, its reset) in place of the pool's single figure, and the notice in the console language (Chinese scripts read `zh`; `ja` and `es` read their own; every other language reads `en`). A caller with no personal share sees the team pool alone. The ring, the popover's status and reset line and the call to action keep reading `pool`. Without `tiers` (Free, self-hosted, an older backend) nothing changes. Two new console strings, `console.ai.usage.tierPersonal` and `console.ai.usage.tierTeamPool`, ship in every locale pack.

‎ui/packages/app-shell/src/hooks/__tests__/useAiUsage.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,55 @@ describe('useAiUsage', () => {
9191
expect(result.current.usage).toBeNull();
9292
});
9393

94+
// cloud#5159 — a paid plan's answer may carry the two allowance tiers.
95+
describe('optional `tiers`', () => {
96+
const TIERS = {
97+
personal: { fraction: 1, resetsAt: '2026-12-01T00:00:00.000Z' },
98+
teamPool: { fraction: 0.25, resetsAt: null },
99+
usingTeamPool: true,
100+
notice: { en: 'Using the team pool.', zh: '正在使用团队共享额度。', ja: 'チーム枠を使用中。', es: 'Usando el fondo del equipo.' },
101+
};
102+
103+
async function read(body: unknown) {
104+
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(okResponse(body)));
105+
const { result } = renderHook(() => useAiUsage({ apiBase: '/api/v1/ai' }));
106+
await waitFor(() => expect(result.current.usage !== null || result.current.error !== undefined).toBe(true));
107+
return result.current;
108+
}
109+
110+
it('reads a valid `tiers` beside the pool and its split', async () => {
111+
const r = await read({ ...RESP, tiers: TIERS });
112+
expect(r.usage).toEqual({ ...RESP, tiers: TIERS });
113+
expect(r.error).toBeUndefined();
114+
});
115+
116+
it('reads `personal: null` (a pool-only caller) and `notice: null` as a normal reading', async () => {
117+
const tiers = { ...TIERS, personal: null, usingTeamPool: false, notice: null };
118+
const r = await read({ pool: POOL, tiers });
119+
expect(r.usage).toEqual({ pool: POOL, tiers });
120+
expect(r.error).toBeUndefined();
121+
});
122+
123+
it('copies `tiers` to its declared fields only', async () => {
124+
const r = await read({ pool: POOL, tiers: { ...TIERS, tokens: 123, teamPool: { ...TIERS.teamPool, used: 999 } } });
125+
expect(r.usage?.tiers).toEqual(TIERS);
126+
});
127+
128+
it.each([
129+
['a string', 'paid'],
130+
['no teamPool', { ...TIERS, teamPool: undefined }],
131+
['a token count for a fraction', { ...TIERS, teamPool: { fraction: '25%', resetsAt: null } }],
132+
['a personal tier that is not one', { ...TIERS, personal: { fraction: 0.5 } }],
133+
['no usingTeamPool', { ...TIERS, usingTeamPool: undefined }],
134+
['a notice missing a language', { ...TIERS, notice: { en: 'x', zh: 'x', ja: 'x' } }],
135+
])('drops a malformed `tiers` (%s) on its own — the pool and its split still stand', async (_label, tiers) => {
136+
const r = await read({ ...RESP, tiers });
137+
expect(r.usage).toEqual(RESP);
138+
expect(r.usage).not.toHaveProperty('tiers');
139+
expect(r.error).toBeUndefined();
140+
});
141+
});
142+
94143
it('fails soft on a non-2xx (endpoint absent on an older backend) — usage stays null', async () => {
95144
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 404 } as unknown as Response);
96145
vi.stubGlobal('fetch', fetchMock);

‎ui/packages/app-shell/src/hooks/useAiUsage.ts‎

Lines changed: 93 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
* endpoint speaks a D5-SAFE shape — FRACTIONS of the pool's cap, never a raw
1111
* token count — so nothing here (or downstream) can leak a token number.
1212
*
13-
* Wire shape: `{ pool, breakdown }`. `pool` is the one reading that gates;
13+
* Wire shape: `{ pool, breakdown, tiers }`. `pool` is the one reading that gates;
1414
* `breakdown` is an observation-only split of that same pool into app-building
1515
* vs data Q&A (cloud ADR-0015). The reader is strict: it reads this shape and no
1616
* other — the retired per-meter `{ meters: { build, dataChat } }` answer parses
@@ -19,6 +19,14 @@
1919
* it, it does not require it), so its ABSENCE is a normal reading and never a
2020
* parse failure.
2121
*
22+
* `tiers` (cloud#5159) is optional the same way: a paid plan with a known caller
23+
* also reports the two tiers of its allowance — the caller's personal share and
24+
* the team pool it overflows into — plus the notice to show once turns draw on
25+
* the pool. Free, self-hosted and older backends omit it. A `tiers` that is not
26+
* the declared shape is dropped on its own and the `{ pool, breakdown }` reading
27+
* stands: the ring is drawn from `pool` alone, so a bad tier answer costs the
28+
* two-tier detail, never the ring.
29+
*
2230
* Refetch triggers, cheap and event-driven (no busy polling):
2331
* - on mount / apiBase change,
2432
* - on the `AI_USAGE_REFRESH_EVENT` the chat engine fires after a turn finishes
@@ -84,11 +92,45 @@ export interface AiUsageBreakdown {
8492
dataChat: number | null;
8593
}
8694

95+
/** One tier of a paid plan's allowance: a fraction of THAT tier's cap. Never tokens. */
96+
export interface AiUsageTier {
97+
/** 0..1 of this tier's cap. */
98+
fraction: number;
99+
/** Best-effort reset instant (ISO); null when unknown — never guessed client-side. */
100+
resetsAt: string | null;
101+
}
102+
103+
/** The server's notice, in the four languages the cloud endpoint writes. */
104+
export interface AiUsageTierNotice {
105+
en: string;
106+
zh: string;
107+
ja: string;
108+
es: string;
109+
}
110+
111+
/**
112+
* The two tiers of a paid plan's allowance (cloud#5159): the caller's personal
113+
* share, and the team pool it overflows into once that share is used up.
114+
* Observation only — `pool` stays the reading that blocks.
115+
*/
116+
export interface AiUsageTiers {
117+
/** The caller's personal share; null for a pool-only caller (an AI service account). */
118+
personal: AiUsageTier | null;
119+
/** The team pool, credit packs included. */
120+
teamPool: AiUsageTier;
121+
/** The personal share is used up and turns draw on the team pool. */
122+
usingTeamPool: boolean;
123+
/** Non-null exactly when `usingTeamPool`: the notice to show the caller. */
124+
notice: AiUsageTierNotice | null;
125+
}
126+
87127
export interface AiUsageResponse {
88128
/** The one metered pool — this is what blocks. */
89129
pool: AiMeterUsage;
90130
/** Read-only split of the same pool. Absent when the runtime does not report it. */
91131
breakdown?: AiUsageBreakdown;
132+
/** The paid plan's two allowance tiers. Absent on Free, self-hosted and older backends. */
133+
tiers?: AiUsageTiers;
92134
}
93135

94136
export interface UseAiUsageOptions {
@@ -135,20 +177,63 @@ function isBreakdown(v: unknown): v is AiUsageBreakdown {
135177
return isFractionOrNull(b.build) && isFractionOrNull(b.dataChat);
136178
}
137179

180+
/** A tier, copied to exactly its declared fields; null when `v` is not one. */
181+
function readTier(v: unknown): AiUsageTier | null {
182+
if (!v || typeof v !== 'object') return null;
183+
const t = v as Record<string, unknown>;
184+
if (typeof t.fraction !== 'number' || !Number.isFinite(t.fraction)) return null;
185+
if (t.resetsAt !== null && typeof t.resetsAt !== 'string') return null;
186+
return { fraction: t.fraction, resetsAt: t.resetsAt };
187+
}
188+
189+
/** The notice, copied to exactly its four languages; null when `v` is not one. */
190+
function readNotice(v: unknown): AiUsageTierNotice | null {
191+
if (!v || typeof v !== 'object') return null;
192+
const n = v as Record<string, unknown>;
193+
if (typeof n.en !== 'string' || typeof n.zh !== 'string' || typeof n.ja !== 'string' || typeof n.es !== 'string')
194+
return null;
195+
return { en: n.en, zh: n.zh, ja: n.ja, es: n.es };
196+
}
197+
198+
/**
199+
* `tiers` in exactly its declared shape, or `undefined` when it is anything else
200+
* (see the file header: a bad `tiers` drops on its own).
201+
*/
202+
function readTiers(v: unknown): AiUsageTiers | undefined {
203+
if (!v || typeof v !== 'object') return undefined;
204+
const t = v as Record<string, unknown>;
205+
const teamPool = readTier(t.teamPool);
206+
if (!teamPool || typeof t.usingTeamPool !== 'boolean') return undefined;
207+
const personal = t.personal === null ? null : readTier(t.personal);
208+
if (personal === null && t.personal !== null) return undefined;
209+
const notice = t.notice === null ? null : readNotice(t.notice);
210+
if (notice === null && t.notice !== null) return undefined;
211+
return { personal, teamPool, usingTeamPool: t.usingTeamPool, notice };
212+
}
213+
138214
/**
139-
* Read the wire payload as `{ pool, breakdown? }` — and only as that. `null`
140-
* means the answer is not this shape (see the file header for why no second
141-
* shape is read).
215+
* Read the wire payload as `{ pool, breakdown?, tiers? }` — and only as that.
216+
* `null` means the answer is not this shape (see the file header for why no
217+
* second shape is read).
142218
*/
143219
function parseUsage(payload: unknown): AiUsageResponse | null {
144220
if (!payload || typeof payload !== 'object') return null;
145-
const { pool, breakdown } = payload as { pool?: unknown; breakdown?: unknown };
221+
const { pool, breakdown, tiers } = payload as { pool?: unknown; breakdown?: unknown; tiers?: unknown };
146222
if (!isPool(pool)) return null;
223+
const out: AiUsageResponse = { pool };
147224
// Absent `breakdown` is a normal reading (optional upstream, cloud#2133), never
148225
// a parse failure: the pool alone is everything the ring needs.
149-
if (breakdown === undefined) return { pool };
150-
if (!isBreakdown(breakdown)) return null;
151-
return { pool, breakdown: { build: breakdown.build, dataChat: breakdown.dataChat } };
226+
if (breakdown !== undefined) {
227+
if (!isBreakdown(breakdown)) return null;
228+
out.breakdown = { build: breakdown.build, dataChat: breakdown.dataChat };
229+
}
230+
// Absent `tiers` is the Free / self-hosted / older-backend reading. A
231+
// malformed one drops alone; the pool and its split still stand.
232+
if (tiers !== undefined) {
233+
const read = readTiers(tiers);
234+
if (read) out.tiers = read;
235+
}
236+
return out;
152237
}
153238

154239
/**

‎ui/packages/app-shell/src/layout/AiUsageIndicator.tsx‎

Lines changed: 82 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@
2626
* whole indicator renders nothing — a missing endpoint degrades to no widget, never
2727
* a broken one.
2828
*
29+
* cloud#5159 — a paid plan's answer may carry `tiers`: the caller's personal
30+
* share and the team pool it overflows into. Then, and only then, the popover
31+
* widens from one figure to two: one row per tier (its status word, its used
32+
* share and its reset), in place of the pool's own figure, and the server's
33+
* notice once turns draw on the team pool. The ring and the popover's status,
34+
* reset line and CTA keep reading `pool` — the binding reading. With no `tiers`
35+
* (Free, self-hosted, an older backend) nothing here changes.
36+
*
2937
* objectui#11799 — and with AI off it asks nothing. AI is on for this viewer when
3038
* the access-filtered agent catalog at the same base (`GET {apiBase}/agents`)
3139
* lists an agent: the signal `useAiSurfaceEnabled` gates every AI entry point
@@ -38,7 +46,7 @@ import * as React from 'react';
3846
import { cn, Button, Popover, PopoverTrigger, PopoverContent } from '@object-ui/components';
3947
import { formatNumber, useObjectTranslation } from '@object-ui/i18n';
4048
import { useAgents } from '@object-ui/plugin-chatbot/core';
41-
import { useAiUsage, type AiMeterUsage } from '../hooks/useAiUsage.js';
49+
import { useAiUsage, type AiMeterUsage, type AiUsageTier, type AiUsageTierNotice } from '../hooks/useAiUsage.js';
4250
import { cloudConsoleUrl } from '../console/marketplace/marketplaceApi.js';
4351
import { getUpgradeUrl } from '../runtime-config.js';
4452

@@ -126,6 +134,18 @@ function MeterGauge({ fraction, tone, size = 16 }: { fraction: number; tone: Ton
126134
);
127135
}
128136

137+
/**
138+
* The notice in the console's language. The cloud endpoint writes four
139+
* (en, zh, ja, es); every Chinese script reads `zh`, every other language `en`.
140+
*/
141+
function noticeForLanguage(notice: AiUsageTierNotice, language: string | undefined): string {
142+
const lang = (language ?? '').toLowerCase();
143+
if (lang.startsWith('zh')) return notice.zh;
144+
if (lang.startsWith('ja')) return notice.ja;
145+
if (lang.startsWith('es')) return notice.es;
146+
return notice.en;
147+
}
148+
129149
export interface AiUsageIndicatorProps {
130150
/** Resolved AI service base (e.g. `/api/v1/ai`). Falsy → the hook stays inert. */
131151
apiBase?: string;
@@ -222,6 +242,26 @@ export function AiUsageIndicator({ apiBase, enabled = true, className }: AiUsage
222242
const showCta = tone !== 'ok' && (pool.upgrade || pool.topUp) && !!ctaUrl;
223243
const reset = resetLabel(pool);
224244

245+
// cloud#5159 — the paid plan's two tiers. A tier carries no window kind, so
246+
// its reset counts down from its own `resetsAt` (days, then hours inside the
247+
// final day); null ⇒ no line, never guessed client-side.
248+
const tiers = usage.tiers;
249+
const tierRows: Array<{ id: 'personal' | 'team-pool'; label: string; tier: AiUsageTier }> = [];
250+
if (tiers) {
251+
if (tiers.personal)
252+
tierRows.push({
253+
id: 'personal',
254+
label: t('console.ai.usage.tierPersonal', { defaultValue: 'Personal allowance' }),
255+
tier: tiers.personal,
256+
});
257+
tierRows.push({
258+
id: 'team-pool',
259+
label: t('console.ai.usage.tierTeamPool', { defaultValue: 'Team pool' }),
260+
tier: tiers.teamPool,
261+
});
262+
}
263+
const notice = tiers?.notice ? noticeForLanguage(tiers.notice, language) : null;
264+
225265
return (
226266
<Popover>
227267
<PopoverTrigger asChild>
@@ -251,9 +291,11 @@ export function AiUsageIndicator({ apiBase, enabled = true, className }: AiUsage
251291
<MeterGauge fraction={fraction} tone={tone} size={22} />
252292
<div className="min-w-0 flex-1">
253293
<div className={cn('text-sm font-medium', statusColorClass(tone))}>{statusLabel(tone)}</div>
254-
<div className="text-xs tabular-nums text-foreground" data-testid="ai-usage-pool-used">
255-
{t('console.ai.usage.poolUsed', { percent: usedPercent, defaultValue: '{{percent}} used' })}
256-
</div>
294+
{tiers ? null : (
295+
<div className="text-xs tabular-nums text-foreground" data-testid="ai-usage-pool-used">
296+
{t('console.ai.usage.poolUsed', { percent: usedPercent, defaultValue: '{{percent}} used' })}
297+
</div>
298+
)}
257299
{reset ? <div className="text-xs text-muted-foreground">{reset}</div> : null}
258300
{showCta ? (
259301
<Button
@@ -270,6 +312,42 @@ export function AiUsageIndicator({ apiBase, enabled = true, className }: AiUsage
270312
) : null}
271313
</div>
272314
</div>
315+
{tierRows.length > 0 ? (
316+
<div className="mt-3 space-y-2 border-t pt-2" data-testid="ai-usage-tiers">
317+
{tierRows.map(({ id, label, tier }) => {
318+
const tierTone = toneFor(tier.fraction);
319+
const tierReset = tier.resetsAt && now !== null ? weeklyResetLabel(tier.resetsAt, now) : null;
320+
return (
321+
<div key={id} className="min-w-0" data-testid={`ai-usage-tier-${id}`}>
322+
<div className="flex items-baseline justify-between gap-2">
323+
<span className="truncate text-xs font-medium text-foreground/80">{label}</span>
324+
<span className={cn('shrink-0 text-xs', statusColorClass(tierTone))}>{statusLabel(tierTone)}</span>
325+
</div>
326+
<div className="text-xs tabular-nums text-foreground" data-testid={`ai-usage-tier-${id}-used`}>
327+
{t('console.ai.usage.poolUsed', {
328+
percent: formatNumber(tier.fraction, {
329+
locale: language,
330+
style: 'percent',
331+
maximumFractionDigits: 0,
332+
}),
333+
defaultValue: '{{percent}} used',
334+
})}
335+
</div>
336+
{tierReset ? <div className="text-xs text-muted-foreground">{tierReset}</div> : null}
337+
</div>
338+
);
339+
})}
340+
</div>
341+
) : null}
342+
{notice ? (
343+
<div
344+
className="mt-2 rounded-md bg-muted px-2 py-1.5 text-xs text-foreground"
345+
role="status"
346+
data-testid="ai-usage-tier-notice"
347+
>
348+
{notice}
349+
</div>
350+
) : null}
273351
</PopoverContent>
274352
</Popover>
275353
);

0 commit comments

Comments
 (0)