refactor(dashboard): /dashboard/costs/quota-share on the CI UI Kit (KEA-7886, lote 6)

This commit is contained in:
diegosouzapw
2026-10-21 10:51:21 -03:00
parent fdd881492f
commit cba008334b
25 changed files with 785 additions and 771 deletions

View File

@@ -2,7 +2,14 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Alert } from "@omniroute/ui-kit/alert";
import { PageHeader } from "@omniroute/ui-kit/page-header";
import { Button } from "@/shared/components";
import EmptyState from "@/shared/components/EmptyState";
import Input from "@/shared/components/Input";
import { Skeleton } from "@/shared/components/Loading";
import Select from "@/shared/components/Select";
import Icon from "@/shared/components/Icon";
import useEmailPrivacyStore from "@/store/emailPrivacyStore";
import { maskEmailLikeValue } from "@/shared/utils/maskEmail";
import type { QuotaPool } from "@/lib/quota/dimensions";
@@ -65,14 +72,14 @@ function StatCard({
}) {
const color =
tone === "amber"
? "text-amber-400"
? "text-warning"
: tone === "red"
? "text-red-400"
? "text-error"
: tone === "green"
? "text-emerald-400"
? "text-success"
: "text-text-main";
return (
<div className="rounded-lg border border-border/40 bg-bg-subtle/30 px-4 py-3">
<div className="rounded-lg border border-border bg-bg-subtle px-4 py-3">
<div className="text-[10px] uppercase tracking-wide text-text-muted font-semibold">
{label}
</div>
@@ -413,69 +420,64 @@ export default function QuotaSharePageClient() {
<div className="flex flex-col gap-4">
{/* Falha ao remover: dispensável, mas nunca silenciosa. */}
{removeError && (
<div
role="alert"
className="flex items-start gap-2 rounded-lg border border-red-500/40 bg-red-500/10 px-3 py-2 text-[12px] text-red-700 dark:text-red-200"
>
<span className="material-symbols-outlined text-[16px] text-red-500 shrink-0">error</span>
<span className="flex-1">{removeError}</span>
<button
type="button"
onClick={() => setRemoveError(null)}
aria-label={t("dismiss")}
className="shrink-0 text-red-500 hover:text-red-400 cursor-pointer"
>
<span className="material-symbols-outlined text-[16px]">close</span>
</button>
</div>
<Alert
variant="critical"
icon={<Icon name="error" size={16} />}
dismissLabel={t("dismiss")}
onDismiss={() => setRemoveError(null)}
description={removeError}
/>
)}
{/* Header */}
<div className="flex items-start justify-between flex-wrap gap-3">
<div>
<h1 className="text-xl font-bold text-text-main flex items-center gap-2">
<span className="material-symbols-outlined text-[24px] text-primary">pie_chart</span>
<PageHeader
compact
title={
<span className="flex items-center gap-2">
<Icon name="pie_chart" size={24} className="text-primary" />
{t("title")}
</h1>
<p className="text-sm text-text-muted mt-0.5">{t("description")}</p>
</div>
<div className="flex items-center gap-2">
<Button variant="primary" size="sm" onClick={() => setCreateOpen(true)}>
<span className="material-symbols-outlined text-[14px] mr-1">add</span>
</span>
}
description={t("description")}
actions={
<Button variant="primary" size="sm" icon="add" onClick={() => setCreateOpen(true)}>
{t("newPool")}
</Button>
</div>
</div>
}
/>
{/* Beta banner — scoped to this page only */}
<div className="flex items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-700 dark:text-amber-200">
<span className="material-symbols-outlined text-[16px] text-amber-500 shrink-0">
science
</span>
<span className="flex-1">
<span className="font-semibold">{t("betaTitle")}</span> — {t("betaText")}
</span>
<a
href="https://github.com/diegosouzapw/OmniRoute/issues/new?labels=quota-share,beta&title=%5Bquota-share%5D%20"
target="_blank"
rel="noopener noreferrer"
className="shrink-0 inline-flex items-center gap-1 font-medium text-amber-600 dark:text-amber-300 hover:underline"
>
<span className="material-symbols-outlined text-[14px]">bug_report</span>
{t("betaReportLink")}
</a>
</div>
{/* Beta banner — scoped to this page only (always shown: no dismiss) */}
<Alert
variant="warning"
icon={<Icon name="science" size={16} />}
className="[&>.ci-alert__dismiss]:hidden"
description={
<span>
<span className="font-semibold">{t("betaTitle")}</span> — {t("betaText")}
</span>
}
actions={
<a
href="https://github.com/diegosouzapw/OmniRoute/issues/new?labels=quota-share,beta&title=%5Bquota-share%5D%20"
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 font-medium underline-offset-2 hover:underline"
>
<Icon name="bug_report" size={14} />
{t("betaReportLink")}
</a>
}
/>
{/* Group bar */}
<div className="flex items-center gap-2 flex-wrap rounded-lg border border-border/40 bg-bg-subtle/20 px-3 py-2">
<span className="text-[11px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("groupLabel")}
</span>
<select
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-border bg-bg-subtle px-3 py-2">
<Select
compact
label={t("groupLabel")}
value={selectedGroupId}
onChange={(e) => setSelectedGroupId(e.target.value)}
title={t("groupSelectHint")}
className="px-2 py-1 rounded border border-border bg-bg-base text-sm text-text-main min-w-[120px]"
selectClassName="min-w-[120px]"
>
<option value="all">{t("allGroups")}</option>
{groups.map((g) => (
@@ -483,11 +485,12 @@ export default function QuotaSharePageClient() {
{g.name}
</option>
))}
</select>
</Select>
{showNewGroupInput ? (
<div className="flex items-center gap-1">
<input
<Input
type="text"
aria-label={t("groupNamePrompt")}
value={newGroupInput}
onChange={(e) => setNewGroupInput(e.target.value)}
onKeyDown={(e) => {
@@ -499,57 +502,53 @@ export default function QuotaSharePageClient() {
}}
placeholder={t("groupNamePrompt")}
autoFocus
className="px-2 py-1 rounded border border-border bg-bg-base text-sm w-36"
inputClassName="h-8 min-h-8 w-36"
/>
<button
type="button"
<Button
variant="secondary"
size="sm"
onClick={() => void handleCreateGroup()}
disabled={!newGroupInput.trim()}
className="text-xs px-2 py-1 rounded bg-primary/15 text-primary hover:bg-primary/25 transition-colors disabled:opacity-40"
>
{t("newGroup")}
</button>
<button
type="button"
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => {
setShowNewGroupInput(false);
setNewGroupInput("");
}}
className="text-xs px-2 py-1 rounded border border-border text-text-muted hover:text-text-main transition-colors"
>
{t("cancel")}
</button>
</Button>
</div>
) : (
<button
type="button"
onClick={() => setShowNewGroupInput(true)}
className="flex items-center gap-1 text-xs text-text-muted hover:text-text-main transition-colors"
>
<span className="material-symbols-outlined text-[14px]">add</span>
<Button variant="ghost" size="sm" icon="add" onClick={() => setShowNewGroupInput(true)}>
{t("newGroup")}
</button>
</Button>
)}
{selectedGroupId !== "all" && (
<button
type="button"
<Button
variant="ghost"
size="sm"
icon="edit"
onClick={() => void handleRenameGroup()}
disabled={renaming}
className="flex items-center gap-1 text-xs text-text-muted hover:text-text-main transition-colors ml-1 disabled:opacity-40"
>
<span className="material-symbols-outlined text-[14px]">edit</span>
{t("renameGroup")}
</button>
</Button>
)}
{selectedGroupId !== "all" && selectedGroupId !== "group-demo" && (
<button
type="button"
<Button
variant="ghost"
size="sm"
icon="delete"
onClick={() => void handleDeleteGroup()}
className="flex items-center gap-1 text-xs text-text-muted hover:text-red-400 transition-colors"
className="hover:text-error"
>
<span className="material-symbols-outlined text-[14px]">delete</span>
{t("deleteGroup")}
</button>
</Button>
)}
</div>
@@ -582,19 +581,18 @@ export default function QuotaSharePageClient() {
{/* Pool list */}
{loading ? (
<div className="text-text-muted text-sm py-10 text-center animate-pulse">
{t("loading")}
<div className="flex flex-col gap-3" aria-busy="true">
<span className="ci-sr-only">{t("loading")}</span>
<Skeleton className="h-40 w-full" />
</div>
) : pools.length === 0 ? (
<div className="rounded-xl border border-border bg-surface py-16 text-center">
<span className="material-symbols-outlined text-[64px] opacity-15">pie_chart</span>
<h3 className="mt-3 text-base font-semibold text-text-main">{t("emptyTitle")}</h3>
<p className="mt-1 text-sm text-text-muted max-w-md mx-auto">{t("emptyDescription")}</p>
<Button variant="primary" size="sm" className="mt-4" onClick={() => setCreateOpen(true)}>
<span className="material-symbols-outlined text-[14px] mr-1">add</span>
{t("newPool")}
</Button>
</div>
<EmptyState
icon="pie_chart"
title={t("emptyTitle")}
description={t("emptyDescription")}
actionLabel={t("newPool")}
onAction={() => setCreateOpen(true)}
/>
) : (
<>
{groupsToRender.length === 0 ? (
@@ -604,9 +602,9 @@ export default function QuotaSharePageClient() {
variant="primary"
size="sm"
className="mt-3"
icon="add"
onClick={() => setCreateOpen(true)}
>
<span className="material-symbols-outlined text-[14px] mr-1">add</span>
{t("newPool")}
</Button>
</div>
@@ -619,9 +617,7 @@ export default function QuotaSharePageClient() {
<div key={g.id} className="flex flex-col gap-3">
{/* Per-group heading */}
<div className="flex items-center gap-2">
<span className="material-symbols-outlined text-[16px] text-text-muted">
folder
</span>
<Icon name="folder" size={16} className="text-text-muted" />
<span className="text-sm font-semibold text-text-main">{g.name}</span>
<span className="text-[11px] text-text-muted">({groupPools.length})</span>
</div>
@@ -632,9 +628,9 @@ export default function QuotaSharePageClient() {
variant="primary"
size="sm"
className="mt-3"
icon="add"
onClick={() => setCreateOpen(true)}
>
<span className="material-symbols-outlined text-[14px] mr-1">add</span>
{t("newPool")}
</Button>
</div>
@@ -669,13 +665,11 @@ export default function QuotaSharePageClient() {
{selectedGroupId === "all" && orphanPools.length > 0 && (
<div className="flex flex-col gap-3">
<div className="flex items-center gap-2">
<span className="material-symbols-outlined text-[16px] text-amber-400">
folder_off
</span>
<Icon name="folder_off" size={16} className="text-warning" />
<span className="text-sm font-semibold text-text-main">{t("ungroupedTitle")}</span>
<span className="text-[11px] text-text-muted">({orphanPools.length})</span>
</div>
<p className="text-[11px] text-amber-400/80">{t("ungroupedHint")}</p>
<p className="text-[11px] text-warning">{t("ungroupedHint")}</p>
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3">
{orphanPools.map((pool) => (
<PoolCardWithUsage

View File

@@ -59,10 +59,8 @@ function summarizeQuotas(provider: string, raw: unknown): QuotaSummary | null {
}
function PctDot({ pct }: { pct: number }) {
const color =
pct <= 20 ? "bg-red-500" : pct <= 50 ? "bg-yellow-500" : "bg-emerald-500";
const textColor =
pct <= 20 ? "text-red-500" : pct <= 50 ? "text-yellow-500" : "text-emerald-500";
const color = pct <= 20 ? "bg-error" : pct <= 50 ? "bg-warning" : "bg-success";
const textColor = pct <= 20 ? "text-error" : pct <= 50 ? "text-warning" : "text-success";
return (
<span className={`inline-flex items-center gap-1 tabular-nums text-[11px] ${textColor}`}>
<span className={`w-1.5 h-1.5 rounded-full shrink-0 ${color}`} aria-hidden />
@@ -109,20 +107,15 @@ export default function AccountQuotaRow({
}, []);
// Resolve the effective connection list to display
const ids: string[] = Array.isArray(connectionIds) && connectionIds.length > 0
? connectionIds
: [];
const ids: string[] =
Array.isArray(connectionIds) && connectionIds.length > 0 ? connectionIds : [];
// Resolve provider for each connection (providers[i] matches connectionIds[i])
const providerFor = (index: number): string =>
Array.isArray(providers) && providers[index] != null
? (providers[index] as string)
: provider;
Array.isArray(providers) && providers[index] != null ? (providers[index] as string) : provider;
const renderFallback = () => (
<span className="text-[11px] text-text-muted tabular-nums">
{t("accountQuotaNone")}
</span>
<span className="text-[11px] text-text-muted tabular-nums">{t("accountQuotaNone")}</span>
);
if (error || caches === null) {
@@ -165,15 +158,16 @@ export default function AccountQuotaRow({
<span className="shrink-0">
<ProviderIcon providerId={prov} size={14} />
</span>
<span className="text-text-muted truncate max-w-[90px]" title={emailsVisible ? connId : maskEmailLikeValue(connId)}>
<span
className="text-text-muted truncate max-w-[90px]"
title={emailsVisible ? connId : maskEmailLikeValue(connId)}
>
{emailsVisible ? `${connId.slice(0, 8)}…` : maskEmailLikeValue(connId)}
</span>
{summary ? (
<>
<PctDot pct={summary.pct} />
{reset ? (
<span className="text-text-muted">· {reset}</span>
) : null}
{reset ? <span className="text-text-muted">· {reset}</span> : null}
</>
) : (
<span className="text-text-muted">{t("accountQuotaNone")}</span>

View File

@@ -3,6 +3,16 @@
import { useTranslations } from "next-intl";
import type { PoolAllocation } from "@/lib/quota/dimensions";
import type { PoolUsageSnapshot } from "@/lib/quota/types";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@omniroute/ui-kit/table";
import Badge from "@/shared/components/Badge";
import { getSeriesColor } from "@/shared/components/analytics/chartColors";
interface AllocationTableProps {
allocations: PoolAllocation[];
@@ -11,23 +21,12 @@ interface AllocationTableProps {
keyLabels: Record<string, string>;
}
const SLICE_PALETTE = [
"#a78bfa",
"#60a5fa",
"#34d399",
"#fbbf24",
"#f87171",
"#22d3ee",
"#f472b6",
"#94a3b8",
];
export default function AllocationTable({ allocations, usage, keyLabels }: AllocationTableProps) {
const t = useTranslations("quotaShare");
if (allocations.length === 0) {
return (
<div className="text-[11px] text-text-muted italic py-3 text-center bg-bg-subtle/40 rounded-md">
<div className="rounded-md bg-bg-subtle py-3 text-center text-[11px] italic text-text-muted">
{t("noAllocations")}
</div>
);
@@ -37,94 +36,96 @@ export default function AllocationTable({ allocations, usage, keyLabels }: Alloc
const primaryDim = usage?.dimensions?.[0];
return (
<div className="overflow-x-auto">
<table className="w-full text-[11px]">
<thead>
<tr className="text-[10px] uppercase tracking-wide text-text-muted border-b border-border/40">
<th className="text-left py-1 pr-2 font-semibold">{t("apiKeyColumn")}</th>
<th className="text-right py-1 pr-2 font-semibold">{t("weightColumn")}</th>
<th className="text-right py-1 pr-2 font-semibold">{t("realConsumedColumn")}</th>
<th className="text-right py-1 pr-2 font-semibold">{t("deficitColumn")}</th>
<th className="text-right py-1 font-semibold">{t("policy")}</th>
</tr>
</thead>
<tbody>
{allocations.map((alloc, i) => {
const color = SLICE_PALETTE[i % SLICE_PALETTE.length];
const label = keyLabels[alloc.apiKeyId] || alloc.apiKeyId.slice(0, 12) + "…";
<Table scrollbarLabel={t("apiKeyColumn")} className="min-w-0 text-[11px]">
<TableHeader>
<TableRow>
<TableHead className="h-8 px-2">{t("apiKeyColumn")}</TableHead>
<TableHead className="h-8 px-2 text-right">{t("weightColumn")}</TableHead>
<TableHead className="h-8 px-2 text-right">{t("realConsumedColumn")}</TableHead>
<TableHead className="h-8 px-2 text-right">{t("deficitColumn")}</TableHead>
<TableHead className="h-8 px-2 text-right">{t("policy")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{allocations.map((alloc, i) => {
// Same categorical series as StackedAllocationBar (kit chart tokens).
const color = getSeriesColor(i);
const label = keyLabels[alloc.apiKeyId] || alloc.apiKeyId.slice(0, 12) + "…";
const perKeyData = primaryDim?.perKey?.find((k) => k.apiKeyId === alloc.apiKeyId);
const consumed = perKeyData?.consumed ?? null;
const fairShare = perKeyData?.fairShare ?? null;
const deficit = perKeyData !== undefined ? perKeyData.deficit : null;
const borrowing = perKeyData?.borrowing ?? false;
const perKeyData = primaryDim?.perKey?.find((k) => k.apiKeyId === alloc.apiKeyId);
const consumed = perKeyData?.consumed ?? null;
const fairShare = perKeyData?.fairShare ?? null;
const deficit = perKeyData !== undefined ? perKeyData.deficit : null;
const borrowing = perKeyData?.borrowing ?? false;
return (
<tr key={alloc.apiKeyId} className="border-b border-border/20 last:border-0">
<td className="py-1.5 pr-2">
<div className="flex items-center gap-1.5 min-w-0">
<span
className="inline-block w-2.5 h-2.5 rounded-sm shrink-0"
style={{ background: color }}
/>
<span className="font-mono truncate text-text-main">{label}</span>
{borrowing && (
<span
className="text-[9px] px-1 py-0.5 rounded bg-amber-500/15 text-amber-400 font-bold shrink-0"
title={t("borrowingIndicator")}
>
{t("borrowingIndicator")}
</span>
)}
</div>
</td>
<td className="py-1.5 pr-2 text-right font-bold tabular-nums" style={{ color }}>
{alloc.weight}%
</td>
<td className="py-1.5 pr-2 text-right tabular-nums text-text-muted">
{consumed !== null ? consumed.toLocaleString() : "—"}
</td>
<td className="py-1.5 pr-2 text-right tabular-nums">
{deficit !== null ? (
<span
className={
deficit > 0
? "text-red-400"
: deficit < 0
? "text-emerald-400"
: "text-text-muted"
}
>
{deficit > 0 ? "+" : ""}
{deficit.toLocaleString()}
</span>
) : (
<span className="text-text-muted">—</span>
)}
{fairShare !== null && (
<span className="text-[9px] text-text-muted ml-1">
({t("fairShareShort")}: {fairShare.toLocaleString()})
</span>
)}
</td>
<td className="py-1.5 text-right">
return (
<TableRow key={alloc.apiKeyId}>
<TableCell className="h-auto px-2 py-1.5">
<div className="flex items-center gap-1.5 min-w-0">
<span
className={`text-[9px] px-1.5 py-0.5 rounded font-semibold ${
alloc.policy === "hard"
? "bg-red-500/10 text-red-400"
: alloc.policy === "soft"
? "bg-amber-500/10 text-amber-400"
: "bg-emerald-500/10 text-emerald-400"
}`}
className="inline-block w-2.5 h-2.5 rounded-sm shrink-0"
style={{ background: color }}
/>
<span className="font-mono truncate text-text-main">{label}</span>
{borrowing && (
<Badge
size="sm"
variant="warning"
className="shrink-0 text-[9px] font-bold"
title={t("borrowingIndicator")}
>
{t("borrowingIndicator")}
</Badge>
)}
</div>
</TableCell>
<TableCell
className="h-auto px-2 py-1.5 text-right font-bold tabular-nums"
style={{ color }}
>
{alloc.weight}%
</TableCell>
<TableCell className="h-auto px-2 py-1.5 text-right tabular-nums text-text-muted">
{consumed !== null ? consumed.toLocaleString() : "—"}
</TableCell>
<TableCell className="h-auto px-2 py-1.5 text-right tabular-nums">
{deficit !== null ? (
<span
className={
deficit > 0 ? "text-error" : deficit < 0 ? "text-success" : "text-text-muted"
}
>
{t(`policy${alloc.policy[0].toUpperCase()}${alloc.policy.slice(1)}`)}
{deficit > 0 ? "+" : ""}
{deficit.toLocaleString()}
</span>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
) : (
<span className="text-text-muted">—</span>
)}
{fairShare !== null && (
<span className="text-[9px] text-text-muted ml-1">
({t("fairShareShort")}: {fairShare.toLocaleString()})
</span>
)}
</TableCell>
<TableCell className="h-auto px-2 py-1.5 text-right">
<Badge
size="sm"
variant={
alloc.policy === "hard"
? "error"
: alloc.policy === "soft"
? "warning"
: "success"
}
className="text-[9px] font-semibold"
>
{t(`policy${alloc.policy[0].toUpperCase()}${alloc.policy.slice(1)}`)}
</Badge>
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
);
}

View File

@@ -56,7 +56,7 @@ export default function BurnRateChartInner({ usage }: BurnRateChartInnerProps) {
<div className="space-y-1">
<div className="flex items-center justify-between text-[10px] text-text-muted">
<span className="font-semibold uppercase tracking-wide">{t("burnRateTitle")}</span>
{exhaustionLabel && <span className="text-amber-400 font-semibold">{exhaustionLabel}</span>}
{exhaustionLabel && <span className="text-warning font-semibold">{exhaustionLabel}</span>}
</div>
<div className="h-24">
<ResponsiveContainer width="100%" height="100%">
@@ -65,15 +65,15 @@ export default function BurnRateChartInner({ usage }: BurnRateChartInnerProps) {
<YAxis hide />
<Tooltip
contentStyle={{
background: "var(--bg-surface, #1e1e2e)",
border: "1px solid var(--border)",
background: "var(--color-surface)",
border: "1px solid var(--color-border)",
fontSize: 10,
}}
/>
<Line
type="monotone"
dataKey="consumed"
stroke="#a78bfa"
stroke="var(--color-chart-3)"
strokeWidth={2}
dot={false}
strokeDasharray="4 2"

View File

@@ -26,15 +26,9 @@ export default function DimensionBar({ dimension, consumedTotal, resetAt }: Dime
const t = useTranslations("quotaShare");
// Capture mount time once — avoids impure Date.now() call on every render
const [now] = useState(() => Date.now());
const usedPct =
dimension.limit > 0 ? Math.min((consumedTotal / dimension.limit) * 100, 100) : 0;
const usedPct = dimension.limit > 0 ? Math.min((consumedTotal / dimension.limit) * 100, 100) : 0;
const barColor =
usedPct >= 90
? "bg-red-500"
: usedPct >= 70
? "bg-amber-400"
: "bg-primary";
const barColor = usedPct >= 90 ? "bg-error" : usedPct >= 70 ? "bg-warning" : "bg-primary";
const resetMs = resetAt ? new Date(resetAt).getTime() - now : null;
const countdown = resetMs !== null && resetMs > 0 ? fmtCountdown(resetMs) : null;
@@ -45,12 +39,19 @@ export default function DimensionBar({ dimension, consumedTotal, resetAt }: Dime
<span className="font-semibold uppercase tracking-wide">
{dimension.unit} / {dimension.window}
</span>
<span className="tabular-nums font-bold" style={{ color: usedPct >= 90 ? "#f87171" : usedPct >= 70 ? "#fbbf24" : undefined }}>
<span
className={`tabular-nums font-bold ${
usedPct >= 90 ? "text-error" : usedPct >= 70 ? "text-warning" : ""
}`}
>
{Math.round(usedPct)}%
</span>
</div>
<div className="h-1.5 rounded-sm bg-black/6 dark:bg-white/6 overflow-hidden">
<div className={`h-full rounded-sm transition-all ${barColor}`} style={{ width: `${usedPct}%` }} />
<div className="h-1.5 overflow-hidden rounded-sm bg-border/60" aria-hidden="true">
<div
className={`h-full rounded-sm transition-all ${barColor}`}
style={{ width: `${usedPct}%` }}
/>
</div>
{countdown && (
<div className="text-[10px] text-text-muted">

View File

@@ -1,7 +1,9 @@
"use client";
import { useTranslations } from "next-intl";
import Button from "@/shared/components/Button";
import Card from "@/shared/components/Card";
import Icon from "@/shared/components/Icon";
import ProviderIcon from "@/shared/components/ProviderIcon";
import useEmailPrivacyStore from "@/store/emailPrivacyStore";
import { maskEmailLikeValue } from "@/shared/utils/maskEmail";
@@ -43,9 +45,9 @@ function computeStatus(usage: PoolUsageSnapshot | null): "green" | "amber" | "re
}
const STATUS_ICONS = {
green: { icon: "check_circle", cls: "text-emerald-400" },
amber: { icon: "warning", cls: "text-amber-400" },
red: { icon: "error", cls: "text-red-400" },
green: { icon: "check_circle", cls: "text-success" },
amber: { icon: "warning", cls: "text-warning" },
red: { icon: "error", cls: "text-error" },
};
export default function PoolCard({
@@ -101,9 +103,7 @@ export default function PoolCard({
)}
<div className="min-w-0">
<div className="flex items-center gap-1.5">
<span className={`material-symbols-outlined text-[16px] shrink-0 ${statusCls}`}>
{statusIcon}
</span>
<Icon name={statusIcon} size={16} className={statusCls} />
<span className="text-sm font-bold text-text-main truncate">
{displayName} · {displayConnectionLabel}
</span>
@@ -115,22 +115,26 @@ export default function PoolCard({
</div>
</div>
<div className="flex items-center gap-1">
<button
type="button"
<Button
variant="ghost"
size="icon-sm"
onClick={onEdit}
title={t("editAllocations")}
className="p-1.5 rounded-md hover:bg-bg-subtle text-text-muted hover:text-text-main cursor-pointer"
aria-label={t("editAllocations")}
className="text-text-muted"
>
<span className="material-symbols-outlined text-[16px]">edit</span>
</button>
<button
type="button"
<Icon name="edit" size={16} />
</Button>
<Button
variant="ghost"
size="icon-sm"
onClick={onRemove}
title={t("removePool")}
className="p-1.5 rounded-md hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"
aria-label={t("removePool")}
className="text-text-muted hover:bg-error/10 hover:text-error"
>
<span className="material-symbols-outlined text-[16px]">delete</span>
</button>
<Icon name="delete" size={16} />
</Button>
</div>
</div>
@@ -162,7 +166,7 @@ export default function PoolCard({
{/* Allocation table */}
<div className="mb-3">
<h4 className="text-[10px] uppercase tracking-wide font-bold text-text-muted mb-1.5">
Allocations
{t("allocationsHeading")}
</h4>
<AllocationTable allocations={pool.allocations} usage={usage} keyLabels={keyLabels} />
</div>
@@ -172,7 +176,7 @@ export default function PoolCard({
{/* Burn rate chart */}
{usage && (
<div className="pt-2 border-t border-border/30">
<div className="pt-2 border-t border-border">
<BurnRateChart usage={usage} />
</div>
)}

View File

@@ -2,6 +2,11 @@
import { useCallback, useEffect, useState } from "react";
import { useTranslations, useLocale } from "next-intl";
import Button from "@/shared/components/Button";
import Checkbox from "@/shared/components/Checkbox";
import Icon from "@/shared/components/Icon";
import Input from "@/shared/components/Input";
import Select from "@/shared/components/Select";
import type { QuotaSchedule, ReserveRule } from "@/lib/quota/schedules";
export interface PoolSchedulesCardProps {
@@ -191,26 +196,29 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
}
}, [rows, poolId, t]);
const inputCls =
"bg-bg-subtle border border-border/50 rounded px-1.5 py-0.5 text-[11px] text-text-main";
// Dense inline editor rows: kit controls at a compact height.
const inputCls = "h-7 min-h-7 px-1.5 text-[11px]";
const selectCls = "ci-select-native--sm h-7 min-h-7 text-[11px]";
return (
<div className="mt-2 pt-2 border-t border-border/30">
<button
type="button"
<div className="mt-2 pt-2 border-t border-border">
<Button
variant="ghost"
size="sm"
onClick={() => setOpen((prev) => !prev)}
className="flex items-center gap-1 text-[10px] uppercase tracking-wide font-bold text-text-muted hover:text-text-main w-full text-left cursor-pointer"
aria-expanded={open}
className="h-7 min-h-7 w-full justify-start gap-1 px-1 text-[10px] font-bold uppercase tracking-wide text-text-muted"
>
<span
className={`material-symbols-outlined text-[13px] transition-transform ${open ? "rotate-90" : ""}`}
>
chevron_right
</span>
<Icon
name="chevron_right"
size={13}
className={`transition-transform ${open ? "rotate-90" : ""}`}
/>
{t("schedulesTitle")}
{rows.length > 0 && (
<span className="ml-1 text-text-muted/60 normal-case font-normal">({rows.length})</span>
)}
</button>
</Button>
{open && (
<div className="mt-1.5 flex flex-col gap-2">
@@ -225,53 +233,51 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
{rows.map((row, index) => (
<div
key={row.id}
className={`rounded-md border border-border/40 p-2 flex flex-col gap-1.5 ${
className={`rounded-md border border-border p-2 flex flex-col gap-1.5 ${
row.enabled ? "" : "opacity-50"
}`}
>
{/* Row 1 — when */}
<div className="flex flex-wrap items-center gap-1.5">
<input
type="checkbox"
<Checkbox
checked={row.enabled}
onChange={(e) => patchRow(index, { enabled: e.target.checked })}
aria-label={t("schedulesEnabled")}
className="cursor-pointer"
/>
<select
<Select
value={row.mode}
onChange={(e) =>
patchRow(index, { mode: e.target.value as DraftSchedule["mode"] })
}
aria-label={t("schedulesMode")}
className={`${inputCls} cursor-pointer`}
selectClassName={selectCls}
>
<option value="allow">{t("schedulesModeAllow")}</option>
<option value="block">{t("schedulesModeBlock")}</option>
</select>
</Select>
<div className="flex items-center gap-0.5">
{initials.map((initial, day) => (
<button
<Button
key={day}
type="button"
variant={row.days.includes(day) ? "secondary" : "ghost"}
size="icon-sm"
onClick={() => toggleDay(index, day)}
aria-pressed={row.days.includes(day)}
title={initial}
className={`w-5 h-5 rounded text-[10px] font-bold cursor-pointer ${
row.days.includes(day)
? "bg-accent/20 text-accent"
: "bg-bg-subtle text-text-muted"
className={`size-6 min-h-6 text-[10px] font-bold ${
row.days.includes(day) ? "text-primary" : "text-text-muted"
}`}
>
{initial}
</button>
</Button>
))}
</div>
<input
<Input
type="time"
inputClassName={inputCls}
value={minutesToTime(row.startMinute)}
onChange={(e) =>
patchRow(index, {
@@ -279,54 +285,57 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
})
}
aria-label={t("schedulesFrom")}
className={inputCls}
/>
<span className="text-[11px] text-text-muted">→</span>
<input
<Input
type="time"
inputClassName={inputCls}
value={minutesToTime(row.endMinute)}
onChange={(e) =>
patchRow(index, { endMinute: timeToMinutes(e.target.value, row.endMinute) })
}
aria-label={t("schedulesTo")}
className={inputCls}
/>
<button
type="button"
<Button
variant="ghost"
size="icon-sm"
onClick={() => {
setRows((prev) => prev.filter((_, i) => i !== index));
setMessage(null);
}}
title={t("schedulesRemove")}
className="ml-auto p-1 rounded hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"
aria-label={t("schedulesRemove")}
className="ml-auto text-text-muted hover:bg-error/10 hover:text-error"
>
<span className="material-symbols-outlined text-[14px]">delete</span>
</button>
<Icon name="delete" size={14} />
</Button>
</div>
{/* Row 2a — how much must be left, one floor per metered window */}
{row.mode === "allow" && (
<div className="flex flex-col gap-1">
<div className="flex flex-wrap items-center gap-1.5">
<label
<span
className="text-[11px] text-text-muted"
title={t("schedulesReserveHint")}
>
{t("schedulesReserve")}
</label>
</span>
{row.reserves.length === 0 && (
<span className="text-[11px] text-text-muted/60 italic">
{t("schedulesReserveNone")}
</span>
)}
<button
type="button"
<Button
variant="outline"
size="sm"
icon="add"
onClick={() => addReserve(index)}
className="text-[11px] px-1.5 py-0.5 rounded bg-bg-subtle hover:bg-bg-subtle/70 text-text-main cursor-pointer"
className="h-7 min-h-7 px-2 text-[11px]"
>
+ {t("schedulesReserveAdd")}
</button>
{t("schedulesReserveAdd")}
</Button>
</div>
{row.reserves.map((rule, ruleIndex) => (
@@ -334,7 +343,8 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
key={`${rule.window}-${ruleIndex}`}
className="flex flex-wrap items-center gap-1.5 pl-3"
>
<select
<Select
selectClassName={selectCls}
value={rule.window}
onChange={(e) =>
patchReserve(index, ruleIndex, {
@@ -343,15 +353,14 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
})
}
aria-label={t("schedulesReserveWindow")}
className={`${inputCls} cursor-pointer`}
>
{RESERVE_WINDOWS.map((w) => (
<option key={w} value={w}>
{w === "any" ? t("schedulesReserveWindowAny") : w}
</option>
))}
</select>
<input
</Select>
<Input
type="number"
min={0}
max={100}
@@ -364,17 +373,19 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
})
}
aria-label={t("schedulesReserve")}
className={`${inputCls} w-16`}
inputClassName={`${inputCls} w-16`}
/>
<span className="text-[11px] text-text-muted">%</span>
<button
type="button"
<Button
variant="ghost"
size="icon-sm"
onClick={() => patchReserve(index, ruleIndex, null)}
title={t("schedulesReserveRemove")}
className="p-0.5 rounded hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"
aria-label={t("schedulesReserveRemove")}
className="size-6 min-h-6 text-text-muted hover:bg-error/10 hover:text-error"
>
<span className="material-symbols-outlined text-[13px]">close</span>
</button>
<Icon name="close" size={13} />
</Button>
</div>
))}
</div>
@@ -383,14 +394,15 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
{/* Row 2b — how much OmniRoute itself may spend */}
{row.mode === "allow" && (
<div className="flex flex-wrap items-center gap-1.5">
<label
<span
className="text-[11px] text-text-muted"
title={t("schedulesBudgetHint")}
>
{t("schedulesBudget")}
</label>
<input
</span>
<Input
type="number"
aria-label={t("schedulesBudget")}
min={0}
value={row.budgetValue ?? ""}
placeholder="—"
@@ -403,9 +415,10 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
e.target.value === "" ? undefined : (row.budgetUnit ?? "tokens"),
})
}
className={`${inputCls} w-24`}
inputClassName={`${inputCls} w-24`}
/>
<select
<Select
selectClassName={selectCls}
value={row.budgetUnit ?? ""}
disabled={row.budgetValue === undefined}
onChange={(e) =>
@@ -415,7 +428,6 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
})
}
aria-label={t("schedulesBudgetUnit")}
className={`${inputCls} cursor-pointer disabled:opacity-40`}
>
<option value="">—</option>
{BUDGET_UNITS.map((unit) => (
@@ -423,8 +435,9 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
{unit}
</option>
))}
</select>
<select
</Select>
<Select
selectClassName={selectCls}
value={row.budgetWindow}
disabled={row.budgetValue === undefined}
onChange={(e) =>
@@ -433,37 +446,38 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
})
}
aria-label={t("schedulesBudgetWindow")}
className={`${inputCls} cursor-pointer disabled:opacity-40`}
>
{BUDGET_WINDOWS.map((w) => (
<option key={w} value={w}>
{w}
</option>
))}
</select>
</Select>
</div>
)}
{/* Row 3 — zone and precedence */}
<div className="flex flex-wrap items-center gap-1.5">
<label className="text-[11px] text-text-muted">{t("schedulesTimezone")}</label>
<input
<span className="text-[11px] text-text-muted">{t("schedulesTimezone")}</span>
<Input
type="text"
aria-label={t("schedulesTimezone")}
value={row.timezone ?? ""}
placeholder="Europe/Rome"
onChange={(e) => patchRow(index, { timezone: e.target.value.trim() || null })}
className={`${inputCls} w-40`}
inputClassName={`${inputCls} w-40`}
/>
<label className="text-[11px] text-text-muted ml-1">
<span className="ml-1 text-[11px] text-text-muted">
{t("schedulesPriority")}
</label>
<input
</span>
<Input
type="number"
aria-label={t("schedulesPriority")}
min={0}
max={1000}
value={row.priority}
onChange={(e) => patchRow(index, { priority: Number(e.target.value) || 0 })}
className={`${inputCls} w-14`}
inputClassName={`${inputCls} w-14`}
/>
</div>
</div>
@@ -472,27 +486,24 @@ export default function PoolSchedulesCard({ poolId }: PoolSchedulesCardProps) {
)}
<div className="flex items-center gap-2">
<button
type="button"
<Button
variant="outline"
size="sm"
icon="add"
onClick={() => {
setRows((prev) => [...prev, newDraft()]);
setMessage(null);
}}
className="text-[11px] px-2 py-1 rounded bg-bg-subtle hover:bg-bg-subtle/70 text-text-main cursor-pointer"
>
+ {t("schedulesAdd")}
</button>
<button
type="button"
onClick={save}
disabled={saving || !loaded}
className="text-[11px] px-2 py-1 rounded bg-accent/20 text-accent hover:bg-accent/30 disabled:opacity-40 cursor-pointer"
>
{t("schedulesAdd")}
</Button>
<Button size="sm" onClick={save} loading={saving} disabled={saving || !loaded}>
{saving ? t("loading") : t("save")}
</button>
</Button>
{message && (
<span
className={`text-[11px] ${message.kind === "ok" ? "text-emerald-400" : "text-red-400"}`}
role="status"
className={`text-[11px] ${message.kind === "ok" ? "text-success" : "text-error"}`}
>
{message.text}
</span>

View File

@@ -20,6 +20,13 @@
import { useMemo, useState, type Dispatch, type SetStateAction } from "react";
import { useTranslations } from "next-intl";
import { Button, Modal } from "@/shared/components";
import Badge from "@/shared/components/Badge";
import Checkbox from "@/shared/components/Checkbox";
import Input from "@/shared/components/Input";
import SegmentedControl from "@/shared/components/SegmentedControl";
import Select from "@/shared/components/Select";
import { getSeriesColor } from "@/shared/components/analytics/chartColors";
import Icon from "@/shared/components/Icon";
import useEmailPrivacyStore from "@/store/emailPrivacyStore";
import { maskEmailLikeValue } from "@/shared/utils/maskEmail";
import { getKnownPlan } from "@/lib/quota/planRegistry";
@@ -86,17 +93,6 @@ export interface PoolWizardProps {
const UNIT_OPTIONS: QuotaUnit[] = ["percent", "requests", "tokens", "usd"];
const WINDOW_OPTIONS: QuotaWindow[] = ["5h", "hourly", "daily", "weekly", "monthly"];
const SLICE_PALETTE = [
"#a78bfa",
"#60a5fa",
"#34d399",
"#fbbf24",
"#f87171",
"#22d3ee",
"#f472b6",
"#94a3b8",
];
/** A few representative model names to show in the preview. */
const PREVIEW_MODELS_BY_PROVIDER: Record<string, string[]> = {
openai: ["gpt-4o", "gpt-4o-mini", "o3", "gpt-4-turbo"],
@@ -127,20 +123,31 @@ function Stepper({ currentStep }: { currentStep: 1 | 2 | 3 }) {
{ num: 3, label: t("wizardStep3Label") },
];
// Built from kit tokens, not the kit Wizard: its step/back/skip/save copy is hard-coded
// English and it always renders a Skip action (see the lote 6 pendências).
return (
<div className="flex items-center gap-0 px-4 py-3 border-b border-border bg-bg-alt shrink-0">
<ol
aria-label={t("wizardTitle")}
className="flex shrink-0 flex-wrap items-center gap-y-2 border-b border-border bg-bg-subtle px-4 py-3"
>
{steps.map((step, idx) => (
<div key={step.num} className="flex items-center">
<li
key={step.num}
className="flex items-center"
aria-current={currentStep === step.num ? "step" : undefined}
>
{idx > 0 && (
<div
className={`h-px w-8 mx-2 transition-colors ${
aria-hidden="true"
className={`mx-2 h-px w-8 transition-colors ${
currentStep > step.num ? "bg-primary" : "bg-border"
}`}
/>
)}
<div className="flex items-center gap-1.5">
<span
className={`flex items-center justify-center w-5 h-5 rounded-full text-[11px] font-semibold transition-colors ${
aria-hidden="true"
className={`flex size-5 items-center justify-center rounded-full text-[11px] font-semibold transition-colors ${
currentStep === step.num
? "bg-primary text-accent-foreground"
: currentStep > step.num
@@ -148,11 +155,7 @@ function Stepper({ currentStep }: { currentStep: 1 | 2 | 3 }) {
: "bg-border text-text-muted"
}`}
>
{currentStep > step.num ? (
<span className="material-symbols-outlined text-[12px]">check</span>
) : (
step.num
)}
{currentStep > step.num ? <Icon name="check" size={12} /> : step.num}
</span>
<span
className={`text-xs font-medium transition-colors ${
@@ -162,9 +165,9 @@ function Stepper({ currentStep }: { currentStep: 1 | 2 | 3 }) {
{step.label}
</span>
</div>
</div>
</li>
))}
</div>
</ol>
);
}
@@ -186,7 +189,7 @@ function pickWizardDimensions(
}
// Pure predicate hoisted out of the component to keep its cognitive budget flat
// (check:cognitive-complexity new-code mode): snap the group <select> to a real,
// (check:cognitive-complexity new-code mode): snap the group Select to a real,
// selectable option in create mode once groups load.
function poolWizardNeedsGroupSnap(
open: boolean,
@@ -399,7 +402,7 @@ export default function PoolWizard({
setSaving,
setGroupId,
});
// Keep the group <select> on a real, selectable option (create mode) — self-
// Keep the group Select on a real, selectable option (create mode) — self-
// extinguishing state adjustment during render (react-hooks/set-state-in-effect).
if (poolWizardNeedsGroupSnap(open, Boolean(editPool), groups, groupId)) {
setGroupId(groups[0].id);
@@ -644,88 +647,87 @@ export default function PoolWizard({
{/* Connection multi-select (checkboxes) */}
<div>
<label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">
<span
id="pool-wizard-connections-label"
className="mb-1 block text-[11px] font-semibold uppercase tracking-wide text-text-muted"
>
{t("wizardConnectionsLabel")}
</label>
</span>
{lockedProvider && (
<p className="text-[10px] text-amber-400 mb-1.5">
<p className="text-[10px] text-warning mb-1.5">
{t("wizardSingleProviderNote")} ({lockedProvider})
</p>
)}
<div className="space-y-1.5 rounded border border-border bg-bg-base px-3 py-2 max-h-48 overflow-y-auto">
<div
role="group"
aria-labelledby="pool-wizard-connections-label"
className="max-h-48 space-y-1.5 overflow-y-auto rounded border border-border bg-bg px-3 py-2"
>
{availableConnections.map((c) => {
const checked = connectionIds.includes(c.id);
const isPrimary = connectionIds[0] === c.id;
return (
<label
<Checkbox
key={c.id}
className="flex items-center gap-2 cursor-pointer select-none py-0.5"
>
<input
type="checkbox"
checked={checked}
onChange={() => {
setConnectionIds((prev) => {
if (prev.includes(c.id)) {
const next = prev.filter((id) => id !== c.id);
if (next.length === 0) setPoolName("");
return next;
} else {
return [...prev, c.id];
}
});
}}
className="accent-primary w-3.5 h-3.5 shrink-0"
/>
<span className="text-sm truncate">{connLabel(c)}</span>
{isPrimary && (
<span className="text-[10px] font-semibold text-primary bg-primary/10 px-1.5 py-0.5 rounded shrink-0">
{t("wizardPrimaryBadge")}
checked={checked}
onChange={() => {
setConnectionIds((prev) => {
if (prev.includes(c.id)) {
const next = prev.filter((id) => id !== c.id);
if (next.length === 0) setPoolName("");
return next;
} else {
return [...prev, c.id];
}
});
}}
label={
<span className="flex min-w-0 items-center gap-2">
<span className="truncate text-sm">{connLabel(c)}</span>
{isPrimary && (
<Badge size="sm" variant="primary" className="shrink-0">
{t("wizardPrimaryBadge")}
</Badge>
)}
</span>
)}
</label>
}
/>
);
})}
{connections
.filter((c) => existingPoolConnectionIds.has(c.id))
.map((c) => (
<label
<Checkbox
key={c.id}
className="flex items-center gap-2 cursor-not-allowed select-none py-0.5 opacity-40"
>
<input
type="checkbox"
disabled
checked={false}
readOnly
className="w-3.5 h-3.5 shrink-0"
/>
<span className="text-sm truncate">
{connLabel(c)} {t("alreadyUsedSuffix")}
{connectionPoolName[c.id] ? ` — ${connectionPoolName[c.id]}` : ""}
</span>
</label>
disabled
checked={false}
readOnly
className="opacity-60"
label={
<span className="truncate text-sm">
{connLabel(c)} {t("alreadyUsedSuffix")}
{connectionPoolName[c.id] ? ` — ${connectionPoolName[c.id]}` : ""}
</span>
}
/>
))}
</div>
{connections.length === 0 && (
<p className="text-[10px] text-amber-400 mt-1">{t("noEligibleConnections")}</p>
<p className="text-[10px] text-warning mt-1">{t("noEligibleConnections")}</p>
)}
</div>
{/* Pool name */}
{connectionIds.length > 0 && (
<div>
<label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">
{t("wizardPoolNameLabel")}
</label>
<input
<Input
type="text"
label={t("wizardPoolNameLabel")}
value={poolName}
onChange={(e) => setPoolName(e.target.value)}
placeholder={
selectedConn ? selectedConn.provider : t("wizardPoolNamePlaceholder")
}
className="w-full px-3 py-2 rounded border border-border bg-bg-base text-sm"
/>
</div>
)}
@@ -733,61 +735,52 @@ export default function PoolWizard({
{/* Group picker */}
{connectionIds.length > 0 && groups.length > 0 && (
<div>
<label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">
{t("wizardGroupLabel")}
</label>
<select
<Select
label={t("wizardGroupLabel")}
value={groupId}
onChange={(e) => setGroupId(e.target.value)}
className="w-full px-3 py-2 rounded border border-border bg-bg-base text-sm"
>
{groups.map((g) => (
<option key={g.id} value={g.id}>
{g.name}
</option>
))}
</select>
</Select>
</div>
)}
{/* Default policy */}
{connectionIds.length > 0 && (
<div>
<label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">
<span className="mb-1 block text-[11px] font-semibold uppercase tracking-wide text-text-muted">
{t("policyLabel")}
</label>
<div className="flex gap-1">
{(["hard", "soft", "burst"] as Policy[]).map((p) => (
<button
key={p}
type="button"
onClick={() => setDefaultPolicy(p)}
className={`px-3 py-1.5 rounded-md border text-xs cursor-pointer transition-colors ${
defaultPolicy === p
? "bg-primary/15 border-primary/40 text-primary font-semibold"
: "border-border text-text-muted hover:text-text-main"
}`}
>
{p === "hard"
</span>
<SegmentedControl
aria-label={t("policyLabel")}
size="sm"
value={defaultPolicy}
onChange={(value) => setDefaultPolicy(value as Policy)}
options={(["hard", "soft", "burst"] as Policy[]).map((p) => ({
value: p,
label:
p === "hard"
? t("policyHard")
: p === "soft"
? t("policySoft")
: t("policyBurst")}
</button>
))}
</div>
: t("policyBurst"),
}))}
/>
</div>
)}
<div className="flex justify-end pt-2">
<button
<Button
onClick={() => setStep(2)}
disabled={connectionIds.length === 0}
className="flex items-center gap-1.5 text-sm px-4 py-2 rounded-lg bg-primary text-accent-foreground hover:bg-primary/90 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"
iconRight="arrow_forward"
>
{t("wizardNext")}
<span className="material-symbols-outlined text-[16px]">arrow_forward</span>
</button>
</Button>
</div>
</div>
)}
@@ -803,19 +796,14 @@ export default function PoolWizard({
</div>
{/* Dimensions editor (ported from ProviderPlanConfigClient) */}
<div className="rounded-lg border border-border/40 bg-bg-subtle/10 p-3">
<div className="rounded-lg border border-border bg-bg-subtle p-3">
<div className="flex items-center justify-between mb-2">
<span className="text-[11px] uppercase tracking-wide font-bold text-text-muted">
{tPlans("dimensionLabel")}
</span>
<button
type="button"
onClick={addDimension}
className="text-[11px] text-primary hover:underline cursor-pointer flex items-center gap-1"
>
<span className="material-symbols-outlined text-[14px]">add</span>
<Button variant="ghost" size="sm" icon="add" onClick={addDimension}>
{tPlans("addDimension")}
</button>
</Button>
</div>
{editDimensions.length === 0 && (
@@ -831,76 +819,73 @@ export default function PoolWizard({
className="grid items-center gap-2"
style={{ gridTemplateColumns: "1fr 1fr 90px 24px" }}
>
<select
<Select
aria-label={tPlans("dimensionLabel")}
value={dim.unit}
onChange={(e) => updateDimension(i, { unit: e.target.value as QuotaUnit })}
className="px-2 py-1.5 rounded border border-border bg-bg-base text-xs"
selectClassName="ci-select-native--sm text-xs"
>
{UNIT_OPTIONS.map((u) => (
<option key={u} value={u}>
{tPlans(`unitOptions.${u}`)}
</option>
))}
</select>
<select
</Select>
<Select
aria-label={tPlans(`windowOptions.${dim.window}`)}
value={dim.window}
onChange={(e) =>
updateDimension(i, { window: e.target.value as QuotaWindow })
}
className="px-2 py-1.5 rounded border border-border bg-bg-base text-xs"
selectClassName="ci-select-native--sm text-xs"
>
{WINDOW_OPTIONS.map((w) => (
<option key={w} value={w}>
{tPlans(`windowOptions.${w}`)}
</option>
))}
</select>
<input
</Select>
<Input
type="number"
min={0}
aria-label={tPlans("limitLabel")}
value={dim.limit}
onChange={(e) => updateDimension(i, { limit: Number(e.target.value) })}
placeholder={tPlans("limitLabel")}
className="px-2 py-1.5 rounded border border-border bg-bg-base text-xs tabular-nums text-right"
inputClassName="h-8 min-h-8 text-right text-xs tabular-nums"
/>
<button
type="button"
<Button
variant="ghost"
size="icon-sm"
onClick={() => removeDimension(i)}
className="p-0.5 rounded hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"
aria-label={t("wizardRemoveDimension")}
className="size-6 min-h-6 text-text-muted hover:bg-error/10 hover:text-error"
>
<span className="material-symbols-outlined text-[16px]">close</span>
</button>
<Icon name="close" size={16} />
</Button>
</div>
))}
</div>
</div>
{dimensionsEdited && (
<p className="text-[10px] text-amber-400">{t("wizardDimensionsEditedNotice")}</p>
<p className="text-[10px] text-warning">{t("wizardDimensionsEditedNotice")}</p>
)}
{/* Helper note when pool has multiple connections */}
{connectionIds.length > 1 && (
<p className="text-[10px] text-text-muted bg-bg-subtle/40 px-3 py-2 rounded border border-border/40">
<p className="rounded border border-border bg-bg-subtle px-3 py-2 text-[10px] text-text-muted">
{t("wizardAdditionalConnectionsNote")}
</p>
)}
<div className="flex items-center justify-between pt-2">
<button
onClick={() => setStep(1)}
className="flex items-center gap-1.5 text-sm px-4 py-2 rounded-lg border border-border text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5 transition-colors"
>
<span className="material-symbols-outlined text-[16px]">arrow_back</span>
<Button variant="outline" icon="arrow_back" onClick={() => setStep(1)}>
{t("wizardBack")}
</button>
<button
onClick={() => setStep(3)}
className="flex items-center gap-1.5 text-sm px-4 py-2 rounded-lg bg-primary text-accent-foreground hover:bg-primary/90 transition-colors"
>
</Button>
<Button iconRight="arrow_forward" onClick={() => setStep(3)}>
{t("wizardNext")}
<span className="material-symbols-outlined text-[16px]">arrow_forward</span>
</button>
</Button>
</div>
</div>
)}
@@ -917,13 +902,13 @@ export default function PoolWizard({
{/* Allocation rows (ported from EditAllocationsModal) */}
{allocations.length === 0 ? (
<div className="text-[12px] text-text-muted italic py-4 text-center bg-bg-subtle/40 rounded-md">
<div className="rounded-md bg-bg-subtle py-4 text-center text-[12px] italic text-text-muted">
{t("noKeysAdded")}
</div>
) : (
<div className="space-y-2">
{allocations.map((a, i) => {
const color = SLICE_PALETTE[i % SLICE_PALETTE.length];
const color = getSeriesColor(i);
return (
<div
key={a.apiKeyId}
@@ -935,16 +920,17 @@ export default function PoolWizard({
style={{ background: color }}
/>
<span className="text-[12px] font-mono truncate">{keyLabel(a.apiKeyId)}</span>
<input
<Input
type="number"
min={0}
max={100}
value={a.weight}
onChange={(e) => updateWeight(a.apiKeyId, Number(e.target.value))}
className="px-2 py-1 rounded border border-border bg-bg-base text-sm text-right tabular-nums"
inputClassName="h-8 min-h-8 px-2 text-right tabular-nums"
title={t("weightPercent")}
aria-label={t("weightPercent")}
/>
<input
<Input
type="number"
min={0}
value={a.capValue ?? ""}
@@ -955,27 +941,31 @@ export default function PoolWizard({
)
}
placeholder={t("policyCapAbsolutePlaceholder")}
className="px-2 py-1 rounded border border-border bg-bg-base text-xs tabular-nums"
inputClassName="h-8 min-h-8 px-2 text-xs tabular-nums"
title={t("policyCapAbsoluteLabel")}
aria-label={t("policyCapAbsoluteLabel")}
/>
<select
<Select
aria-label={t("policyLabel")}
value={a.policy}
onChange={(e) =>
updateAllocationPolicy(a.apiKeyId, e.target.value as Policy)
}
className="px-1 py-1 rounded border border-border bg-bg-base text-xs"
selectClassName="ci-select-native--sm text-xs"
>
<option value="hard">{t("policyHard")}</option>
<option value="soft">{t("policySoft")}</option>
<option value="burst">{t("policyBurst")}</option>
</select>
<button
type="button"
</Select>
<Button
variant="ghost"
size="icon-sm"
onClick={() => removeAllocation(a.apiKeyId)}
className="p-0.5 rounded hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"
aria-label={t("wizardRemoveKey")}
className="size-6 min-h-6 text-text-muted hover:bg-error/10 hover:text-error"
>
<span className="material-symbols-outlined text-[16px]">close</span>
</button>
<Icon name="close" size={16} />
</Button>
</div>
);
})}
@@ -983,14 +973,14 @@ export default function PoolWizard({
)}
{/* Add key + equal split controls */}
<div className="flex items-center justify-between text-[11px] pt-1 border-t border-border/40">
<div className="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-1 text-[11px]">
<span
className={`font-bold tabular-nums ${
totalWeight === 100
? "text-emerald-400"
? "text-success"
: totalWeight > 100
? "text-red-400"
: "text-amber-400"
? "text-error"
: "text-warning"
}`}
>
{t("totalLabel", { percent: totalWeight })}{" "}
@@ -998,10 +988,11 @@ export default function PoolWizard({
</span>
<div className="flex items-center gap-2">
{availableKeys.length > 0 && (
<select
<Select
aria-label={t("addKey")}
value=""
onChange={(e) => e.target.value && addKey(e.target.value)}
className="px-2 py-1 rounded border border-border bg-bg-base text-xs"
selectClassName="ci-select-native--sm text-xs"
>
<option value="">{t("addKey")}</option>
{availableKeys.map((k) => (
@@ -1009,7 +1000,7 @@ export default function PoolWizard({
{k.name || k.id.slice(0, 12) + "…"}
</option>
))}
</select>
</Select>
)}
<Button
variant="secondary"
@@ -1023,24 +1014,26 @@ export default function PoolWizard({
</div>
{/* Exclusive checkbox */}
<label className="flex items-start gap-2 cursor-pointer select-none pt-1 border-t border-border/40">
<input
type="checkbox"
<div className="border-t border-border pt-2">
<Checkbox
checked={exclusive}
onChange={(e) => setExclusive(e.target.checked)}
className="mt-0.5 accent-primary w-4 h-4"
label={
<span className="flex flex-col">
<span className="text-sm font-semibold text-text-main">
{t("wizardExclusiveLabel")}
</span>
<span className="mt-0.5 text-[11px] text-text-muted">
{t("wizardExclusiveHint")}
</span>
</span>
}
/>
<div>
<span className="text-sm font-semibold text-text-main">
{t("wizardExclusiveLabel")}
</span>
<p className="text-[11px] text-text-muted mt-0.5">{t("wizardExclusiveHint")}</p>
</div>
</label>
</div>
{/* quotaModelName preview — grouped by provider */}
{previewByProvider.length > 0 && (
<div className="rounded-md border border-border/40 bg-bg-subtle/30 p-3 text-[11px]">
<div className="rounded-md border border-border bg-bg-subtle p-3 text-[11px]">
<div className="font-semibold text-text-muted uppercase tracking-wide mb-1.5 text-[10px]">
{t("wizardPreviewLabel")}
</div>
@@ -1074,22 +1067,24 @@ export default function PoolWizard({
)}
{error && (
<p className="text-[11px] text-red-400 bg-red-500/10 px-3 py-2 rounded">{error}</p>
<p role="alert" className="rounded bg-error/10 px-3 py-2 text-[11px] text-error">
{error}
</p>
)}
<div className="flex items-center justify-between pt-2 border-t border-border/40">
<button
<div className="flex items-center justify-between border-t border-border pt-2">
<Button
variant="outline"
icon="arrow_back"
onClick={() => setStep(2)}
disabled={saving}
className="flex items-center gap-1.5 text-sm px-4 py-2 rounded-lg border border-border text-text-muted hover:text-text-main hover:bg-black/5 dark:hover:bg-white/5 transition-colors disabled:opacity-40"
>
<span className="material-symbols-outlined text-[16px]">arrow_back</span>
{t("wizardBack")}
</button>
</Button>
<Button
variant="primary"
size="sm"
onClick={() => void handleFinish()}
loading={saving}
disabled={totalWeight > 100 || saving}
>
{saving ? t("loading") : editPool ? t("saveChanges") : t("wizardCreatePool")}

View File

@@ -1,34 +1,19 @@
"use client";
import { useState } from "react";
import { useTranslations } from "next-intl";
import Card from "@/shared/components/Card";
import Collapsible from "@/shared/components/Collapsible";
import Icon from "@/shared/components/Icon";
export default function QuotaConceptCard() {
const t = useTranslations("quotaShare");
const [expanded, setExpanded] = useState(false);
// Kit Accordion (Collapsible adapter): collapsed by default, as before.
return (
<Card padding="md">
<button
type="button"
className="w-full flex items-center justify-between gap-2 cursor-pointer"
onClick={() => setExpanded((p) => !p)}
aria-expanded={expanded}
>
<div className="flex items-center gap-2">
<span className="material-symbols-outlined text-[20px] text-primary">info</span>
<span className="text-sm font-semibold text-text-main">{t("conceptTitle")}</span>
</div>
<span className="material-symbols-outlined text-[18px] text-text-muted">
{expanded ? "expand_less" : "expand_more"}
</span>
</button>
{expanded && (
<div className="mt-3 space-y-2 text-xs text-text-muted leading-relaxed">
<div data-testid="quota-concept-card">
<Collapsible title={t("conceptTitle")} icon="info">
<div className="space-y-2 text-xs leading-relaxed text-text-muted">
<p>{t("conceptIntro")}</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2 pt-1">
<div className="grid grid-cols-1 gap-2 pt-1 sm:grid-cols-2">
<ConceptItem icon="balance" text={t("conceptFairShare")} />
<ConceptItem icon="trending_up" text={t("conceptBorrowing")} />
<ConceptItem icon="lock" text={t("conceptGlobalCap")} />
@@ -45,17 +30,15 @@ export default function QuotaConceptCard() {
/>
</div>
</div>
)}
</Card>
</Collapsible>
</div>
);
}
function ConceptItem({ icon, text }: { icon: string; text: string }) {
return (
<div className="flex items-start gap-1.5 rounded-md bg-bg-subtle/40 p-2">
<span className="material-symbols-outlined text-[16px] text-primary shrink-0 mt-0.5">
{icon}
</span>
<div className="flex items-start gap-1.5 rounded-md bg-bg-subtle p-2">
<Icon name={icon} size={16} className="text-primary mt-0.5" />
<span>{text}</span>
</div>
);
@@ -63,10 +46,8 @@ function ConceptItem({ icon, text }: { icon: string; text: string }) {
function ConceptItemWithDesc({ icon, title, desc }: { icon: string; title: string; desc: string }) {
return (
<div className="flex items-start gap-1.5 rounded-md bg-bg-subtle/40 p-2">
<span className="material-symbols-outlined text-[16px] text-primary shrink-0 mt-0.5">
{icon}
</span>
<div className="flex items-start gap-1.5 rounded-md bg-bg-subtle p-2">
<Icon name={icon} size={16} className="text-primary mt-0.5" />
<div className="flex flex-col gap-0.5">
<span className="font-semibold text-text-main">{title}</span>
<span className="text-text-muted">{desc}</span>

View File

@@ -4,7 +4,10 @@ import { useState, useMemo, useEffect } from "react";
import { useTranslations } from "next-intl";
import useEmailPrivacyStore from "@/store/emailPrivacyStore";
import { maskEmailLikeValue } from "@/shared/utils/maskEmail";
import Button from "@/shared/components/Button";
import Card from "@/shared/components/Card";
import Icon from "@/shared/components/Icon";
import Select from "@/shared/components/Select";
import {
quotaModelName,
quotaGroupSlug,
@@ -206,9 +209,10 @@ export default function QuotaEndpointsCard({
}, [groups, pools, connections]);
// Real qtSd combos grouped by group → provider (preferred over placeholders).
const realByGroup = useMemo<
Array<{ group: QuotaGroup; entries: Array<{ provider: string; models: string[] }> }> | null
>(() => {
const realByGroup = useMemo<Array<{
group: QuotaGroup;
entries: Array<{ provider: string; models: string[] }>;
}> | null>(() => {
if (!realCombos || realCombos.length === 0) return null;
const byGroupSlug = new Map<string, Map<string, string[]>>();
for (const name of realCombos) {
@@ -269,9 +273,7 @@ export default function QuotaEndpointsCard({
// ── Compute the combined default model count across all groups ────────────────
const hasAnyDefaultModels = viewByGroup.some((g) =>
g.entries.some((e) => e.models.length > 0)
);
const hasAnyDefaultModels = viewByGroup.some((g) => g.entries.some((e) => e.models.length > 0));
// ── Render ───────────────────────────────────────────────────────────────────
@@ -282,9 +284,7 @@ export default function QuotaEndpointsCard({
{/* Header row */}
<div className="flex items-start justify-between gap-3 flex-wrap">
<div className="flex items-start gap-2">
<span className="material-symbols-outlined text-[18px] text-primary shrink-0 mt-0.5">
api
</span>
<Icon name="api" size={18} className="text-primary mt-0.5" />
<div>
<span className="text-sm font-semibold text-text-main">{t("endpointsTitle")}</span>
<p className="text-xs text-text-muted mt-0.5 max-w-lg">{t("endpointsHint")}</p>
@@ -295,13 +295,12 @@ export default function QuotaEndpointsCard({
<div className="flex items-center gap-2 shrink-0">
{apiKeys.length > 0 && (
<>
<label className="text-xs text-text-muted whitespace-nowrap">
{t("previewForKey")}
</label>
<select
<Select
compact
label={t("previewForKey")}
value={selectedKeyId}
onChange={(e) => void handleKeyChange(e.target.value)}
className="px-2 py-1 rounded border border-border bg-bg-base text-xs text-text-main min-w-[140px]"
selectClassName="min-w-[140px]"
>
<option value="">{t("previewKeyNone")}</option>
{apiKeys.map((k) => (
@@ -309,145 +308,145 @@ export default function QuotaEndpointsCard({
{keyLabel(k)}
</option>
))}
</select>
</Select>
</>
)}
<button
type="button"
<Button
variant="ghost"
size="icon-sm"
onClick={() => setCollapsed((c) => !c)}
title={collapsed ? t("endpointsExpand") : t("endpointsCollapse")}
aria-label={collapsed ? t("endpointsExpand") : t("endpointsCollapse")}
className="p-1 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-text-main transition-colors cursor-pointer"
aria-expanded={!collapsed}
className="text-text-muted"
>
<span className="material-symbols-outlined text-[18px]">
{collapsed ? "expand_more" : "expand_less"}
</span>
</button>
<Icon name={collapsed ? "expand_more" : "expand_less"} size={18} />
</Button>
</div>
</div>
{!collapsed && (
<>
{/* Base URL line(s) */}
<div className="mt-3 rounded-md bg-bg-subtle/50 border border-border/40 px-3 py-2 space-y-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">POST /v1/chat/completions</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/&lt;provider&gt;/&lt;model&gt;&quot;
</code>
</div>
{hasAnthropic && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">POST /v1/messages</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/&lt;provider&gt;/&lt;model&gt;&quot;
</code>
<span className="text-[10px] text-text-muted">({t("endpointsAnthropicNote")})</span>
</div>
)}
{hasResponses && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">POST /v1/responses</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/&lt;provider&gt;/&lt;model&gt;&quot;
</code>
<span className="text-[10px] text-text-muted">({t("endpointsResponsesNote")})</span>
</div>
)}
{hasCodex && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">WS /v1/responses</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/codex/&lt;model&gt;&quot;
</code>
<span className="text-[10px] text-text-muted">({t("endpointsWsNote")})</span>
</div>
)}
</div>
{/* Model listing */}
<div className="mt-3">
{loadingPreview ? (
<div className="text-xs text-text-muted animate-pulse py-2">{t("loading")}</div>
) : previewModels !== null ? (
// Per-key preview from the API
<div>
{previewModels.length === 0 ? (
<p className="text-xs text-text-muted italic">{t("noAllocations")}</p>
) : (
<ul className="space-y-0.5">
{previewModels.map((m) => (
<li key={m}>
<code className="text-[11px] font-mono text-text-main bg-bg-subtle/40 rounded px-1.5 py-0.5 inline-block">
{m}
</code>
</li>
))}
</ul>
{/* Base URL line(s) */}
<div className="mt-3 rounded-md bg-bg-subtle border border-border px-3 py-2 space-y-1">
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">POST /v1/chat/completions</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/&lt;provider&gt;/&lt;model&gt;&quot;
</code>
</div>
{hasAnthropic && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">POST /v1/messages</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/&lt;provider&gt;/&lt;model&gt;&quot;
</code>
<span className="text-[10px] text-text-muted">({t("endpointsAnthropicNote")})</span>
</div>
)}
{hasResponses && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">POST /v1/responses</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/&lt;provider&gt;/&lt;model&gt;&quot;
</code>
<span className="text-[10px] text-text-muted">({t("endpointsResponsesNote")})</span>
</div>
)}
{hasCodex && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] uppercase tracking-wide text-text-muted font-semibold shrink-0">
{t("endpointsBaseUrl")}
</span>
<code className="text-xs text-primary font-mono">WS /v1/responses</code>
<span className="text-xs text-text-muted mx-1">·</span>
<code className="text-xs text-text-muted font-mono">
model: &quot;qtSd/&lt;group&gt;/codex/&lt;model&gt;&quot;
</code>
<span className="text-[10px] text-text-muted">({t("endpointsWsNote")})</span>
</div>
)}
</div>
) : hasData && hasAnyDefaultModels ? (
// Default view: grouped by group → provider → real qtSd model ids
<div className="space-y-3">
{viewByGroup.map(({ group, entries }) => {
if (entries.length === 0) return null;
return (
<div key={group.id}>
<div className="flex items-center gap-1.5 mb-1">
<span className="material-symbols-outlined text-[13px] text-text-muted">
folder
</span>
<span className="text-[11px] font-semibold text-text-muted uppercase tracking-wide">
{quotaGroupSlug(group.name)}
</span>
</div>
<div className="space-y-1 pl-4">
{entries.map(({ provider, models }) => (
<div key={provider} className="space-y-0.5">
<span className="text-[10px] text-text-muted font-medium">{provider}</span>
<ul className="space-y-0.5">
{models.map((m) => (
<li key={m}>
<code className="text-[11px] font-mono text-text-main bg-bg-subtle/40 rounded px-1.5 py-0.5 inline-block">
{m}
</code>
</li>
))}
</ul>
</div>
{/* Model listing */}
<div className="mt-3">
{loadingPreview ? (
<div className="text-xs text-text-muted animate-pulse py-2">{t("loading")}</div>
) : previewModels !== null ? (
// Per-key preview from the API
<div>
{previewModels.length === 0 ? (
<p className="text-xs text-text-muted italic">{t("noAllocations")}</p>
) : (
<ul className="space-y-0.5">
{previewModels.map((m) => (
<li key={m}>
<code className="text-[11px] font-mono text-text-main bg-bg-subtle/40 rounded px-1.5 py-0.5 inline-block">
{m}
</code>
</li>
))}
</div>
</div>
);
})}
</ul>
)}
</div>
) : hasData && hasAnyDefaultModels ? (
// Default view: grouped by group → provider → real qtSd model ids
<div className="space-y-3">
{viewByGroup.map(({ group, entries }) => {
if (entries.length === 0) return null;
return (
<div key={group.id}>
<div className="flex items-center gap-1.5 mb-1">
<Icon name="folder" size={13} className="text-text-muted" />
<span className="text-[11px] font-semibold text-text-muted uppercase tracking-wide">
{quotaGroupSlug(group.name)}
</span>
</div>
<div className="space-y-1 pl-4">
{entries.map(({ provider, models }) => (
<div key={provider} className="space-y-0.5">
<span className="text-[10px] text-text-muted font-medium">
{provider}
</span>
<ul className="space-y-0.5">
{models.map((m) => (
<li key={m}>
<code className="text-[11px] font-mono text-text-main bg-bg-subtle/40 rounded px-1.5 py-0.5 inline-block">
{m}
</code>
</li>
))}
</ul>
</div>
))}
</div>
</div>
);
})}
</div>
) : (
// No pools yet — show the format placeholder
<div className="text-xs text-text-muted italic">
<code className="font-mono text-[11px]">
qtSd/&lt;groupSlug&gt;/&lt;provider&gt;/&lt;model&gt;
</code>
{" — "}
{t("emptyDescription")}
</div>
)}
</div>
) : (
// No pools yet — show the format placeholder
<div className="text-xs text-text-muted italic">
<code className="font-mono text-[11px]">
qtSd/&lt;groupSlug&gt;/&lt;provider&gt;/&lt;model&gt;
</code>
{" — "}
{t("emptyDescription")}
</div>
)}
</div>
</>
)}
</Card>

View File

@@ -3,6 +3,7 @@
import { useTranslations } from "next-intl";
import type { PoolAllocation } from "@/lib/quota/dimensions";
import type { PoolUsageSnapshot } from "@/lib/quota/types";
import { getSeriesColor } from "@/shared/components/analytics/chartColors";
export interface StackedAllocationBarProps {
allocations: PoolAllocation[];
@@ -13,17 +14,6 @@ export interface StackedAllocationBarProps {
dimensionIndex?: number;
}
const PALETTE = [
"#a78bfa",
"#60a5fa",
"#34d399",
"#fbbf24",
"#f87171",
"#22d3ee",
"#f472b6",
"#94a3b8",
];
export default function StackedAllocationBar({
allocations,
usage,
@@ -56,7 +46,7 @@ export default function StackedAllocationBar({
{/* Stacked bar */}
<div className="flex h-3 rounded overflow-hidden w-full mb-2">
{allocations.map((alloc, i) => {
const color = PALETTE[i % PALETTE.length];
const color = getSeriesColor(i);
const keyUsage = perKeyMap[alloc.apiKeyId];
let consumedPercent: number | null = null;
if (keyUsage && keyUsage.fairShare > 0) {
@@ -81,7 +71,7 @@ export default function StackedAllocationBar({
{/* Labels */}
<div className="flex flex-wrap gap-x-3 gap-y-1">
{allocations.map((alloc, i) => {
const color = PALETTE[i % PALETTE.length];
const color = getSeriesColor(i);
const keyUsage = perKeyMap[alloc.apiKeyId];
let consumedPercent: number | null = null;
if (keyUsage && keyUsage.fairShare > 0) {

View File

@@ -2,6 +2,8 @@
import { useState, useEffect } from "react";
import { useTranslations } from "next-intl";
import Button from "@/shared/components/Button";
import Icon from "@/shared/components/Icon";
import type { ConsumptionEvent } from "@/lib/db/quotaConsumption";
export interface UsageLogCardProps {
@@ -46,7 +48,7 @@ export default function UsageLogCard({ poolId, keyLabels }: UsageLogCardProps) {
.then((data) => {
if (!alive) return;
const raw: unknown = data?.events;
setEvents(Array.isArray(raw) ? (raw as ConsumptionEvent[]) : [] ?? []);
setEvents(Array.isArray(raw) ? (raw as ConsumptionEvent[]) : ([] ?? []));
setLoaded(true);
})
.catch(() => {
@@ -64,19 +66,21 @@ export default function UsageLogCard({ poolId, keyLabels }: UsageLogCardProps) {
keyLabels?.[apiKeyId] ?? apiKeyId.slice(0, 10) + "…";
return (
<div className="mt-2 pt-2 border-t border-border/30">
<button
type="button"
<div className="mt-2 pt-2 border-t border-border">
<Button
variant="ghost"
size="sm"
onClick={() => setOpen((prev) => !prev)}
className="flex items-center gap-1 text-[10px] uppercase tracking-wide font-bold text-text-muted hover:text-text-main w-full text-left cursor-pointer"
aria-expanded={open}
className="h-7 min-h-7 w-full justify-start gap-1 px-1 text-[10px] font-bold uppercase tracking-wide text-text-muted"
>
<span
className={`material-symbols-outlined text-[13px] transition-transform ${open ? "rotate-90" : ""}`}
>
chevron_right
</span>
<Icon
name="chevron_right"
size={13}
className={`transition-transform ${open ? "rotate-90" : ""}`}
/>
{t("logTitle")}
</button>
</Button>
{open && (
<div className="mt-1.5">

View File

@@ -34,14 +34,9 @@ interface PoolCreate {
export function adaptLsPoolToApiSchema(lsPool: LsPool): PoolCreate {
const connectionId = lsPool.connectionId || "";
const name =
lsPool.accountLabel ||
lsPool.provider ||
lsPool.connectionId?.slice(0, 12) ||
"Migrated pool";
lsPool.accountLabel || lsPool.provider || lsPool.connectionId?.slice(0, 12) || "Migrated pool";
const policy: Policy =
lsPool.policy === "soft" || lsPool.policy === "burst"
? (lsPool.policy as Policy)
: "hard";
lsPool.policy === "soft" || lsPool.policy === "burst" ? (lsPool.policy as Policy) : "hard";
const allocations: PoolAllocation[] = (lsPool.allocations || [])
.filter((a) => a.apiKeyId)

View File

@@ -32,10 +32,14 @@ export function usePoolsUsageAggregate(pools: QuotaPool[]): PoolsUsageAggregate
const fetchAll = async () => {
try {
const snapshots = await Promise.all(
ids.map((id) => fetch(`/api/quota/pools/${id}/usage`).then((r) => (r.ok ? r.json() : null)))
ids.map((id) =>
fetch(`/api/quota/pools/${id}/usage`).then((r) => (r.ok ? r.json() : null))
)
);
if (!mounted) return;
const valid = snapshots.filter((s): s is { usage: PoolUsageSnapshot } => s !== null && !!s.usage);
const valid = snapshots.filter(
(s): s is { usage: PoolUsageSnapshot } => s !== null && !!s.usage
);
let totalUtil = 0;
let utilCount = 0;
let borrowing = 0;
@@ -58,7 +62,11 @@ export function usePoolsUsageAggregate(pools: QuotaPool[]): PoolsUsageAggregate
});
} catch (err) {
if (mounted) {
setState((s) => ({ ...s, loading: false, error: err instanceof Error ? err.message : "fetch failed" }));
setState((s) => ({
...s,
loading: false,
error: err instanceof Error ? err.message : "fetch failed",
}));
}
}
};

View File

@@ -12381,7 +12381,10 @@
"ungroupedTitle": "Ungrouped",
"ungroupedHint": "These pools are not assigned to a known group. Edit a pool to move it into a real group.",
"removeFailed": "Could not remove this pool.",
"dismiss": "Dismiss"
"dismiss": "Dismiss",
"allocationsHeading": "Allocations",
"wizardRemoveDimension": "Remove dimension",
"wizardRemoveKey": "Remove key"
},
"plugins": {
"title": "Plugins",

View File

@@ -12381,7 +12381,10 @@
"ungroupedTitle": "Sem grupo",
"ungroupedHint": "Estes pools não estão atribuídos a um grupo conhecido. Edite um pool para movê-lo para um grupo real.",
"removeFailed": "Não foi possível remover este pool.",
"dismiss": "Dispensar"
"dismiss": "Dispensar",
"allocationsHeading": "Alocações",
"wizardRemoveDimension": "Remover dimensão",
"wizardRemoveKey": "Remover chave"
},
"plugins": {
"title": "Plugins",

View File

@@ -12381,7 +12381,10 @@
"ungroupedTitle": "Chưa phân nhóm",
"ungroupedHint": "Các pool này chưa được gán cho một nhóm mà hệ thống nhận diện. Hãy chỉnh sửa một pool để chuyển pool đó vào một nhóm hợp lệ.",
"removeFailed": "Không thể xóa nhóm này.",
"dismiss": "Đóng"
"dismiss": "Đóng",
"allocationsHeading": "Phân bổ",
"wizardRemoveDimension": "Xóa chiều hạn mức",
"wizardRemoveKey": "Xóa khóa"
},
"plugins": {
"title": "Plugin",

View File

@@ -95,7 +95,7 @@ export function ComboCompressionModeSelect({
return (
// Kit-styled native select (adapter `Select` with <option> children). A caller's
// `className` still lands on the control itself, as with the legacy <select>.
// `className` still lands on the control itself, as with the legacy native select.
<Select
compact
value={compressionOverride}

View File

@@ -74,6 +74,7 @@ import {
Flame,
FlaskConical,
Folder,
FolderX,
GalleryVerticalEnd,
Gauge,
Globe,
@@ -438,7 +439,7 @@ export const ICON_MAP: Record<string, LucideIcon | null> = {
fingerprint: Fingerprint,
flight: null,
flutter_dash: null,
folder_off: null,
folder_off: FolderX,
folder_open: null,
folder_zip: null,
function: null,

View File

@@ -60,23 +60,24 @@ test("QuotaEndpointsCard: references quotaModelName or qtSd/ prefix", () => {
test("QuotaEndpointsCard: has a <select> for API key preview", () => {
assert.ok(
cardSrc.includes("<select"),
// KEA-7886: the kit-styled Select adapter (native <select> children).
/<select|<Select/.test(cardSrc),
"QuotaEndpointsCard must render a <select> for API key selection"
);
});
test("QuotaEndpointsCard: has a previewKeyNone leading option", () => {
assert.ok(
cardSrc.includes('previewKeyNone') || cardSrc.includes("previewKeyNone"),
cardSrc.includes("previewKeyNone") || cardSrc.includes("previewKeyNone"),
"QuotaEndpointsCard must use the t('previewKeyNone') i18n key for the empty/all option"
);
});
test("QuotaEndpointsCard: has a leading option with value=\"\" for no-key selection", () => {
test('QuotaEndpointsCard: has a leading option with value="" for no-key selection', () => {
// The leading option must have value="" so that on reset it reverts to all-endpoints view
assert.ok(
cardSrc.includes('value=""') || cardSrc.includes("value=''"),
"QuotaEndpointsCard must have a leading <option value=\"\"> for (all endpoints)"
'QuotaEndpointsCard must have a leading <option value=""> for (all endpoints)'
);
});
@@ -134,22 +135,14 @@ const ENDPOINTS_KEYS = [
test("i18n: all 5 endpoint keys present in en.json quotaShare namespace", () => {
const en = JSON.parse(readFileSync(EN_PATH, "utf8")) as Record<string, Record<string, string>>;
for (const k of ENDPOINTS_KEYS) {
assert.equal(
typeof en["quotaShare"]?.[k],
"string",
`en.json missing quotaShare.${k}`
);
assert.equal(typeof en["quotaShare"]?.[k], "string", `en.json missing quotaShare.${k}`);
}
});
test("i18n: all 5 endpoint keys present in pt-BR.json quotaShare namespace", () => {
const pt = JSON.parse(readFileSync(PT_PATH, "utf8")) as Record<string, Record<string, string>>;
for (const k of ENDPOINTS_KEYS) {
assert.equal(
typeof pt["quotaShare"]?.[k],
"string",
`pt-BR.json missing quotaShare.${k}`
);
assert.equal(typeof pt["quotaShare"]?.[k], "string", `pt-BR.json missing quotaShare.${k}`);
}
});

View File

@@ -95,7 +95,8 @@ test("QuotaSharePageClient: renders a group <select>", () => {
"QuotaSharePageClient must track selectedGroupId state"
);
assert.ok(
pageSrc.includes("<select") && pageSrc.includes("selectedGroupId"),
// KEA-7886: the group picker is the kit-styled Select adapter (native <select> children).
/<select|<Select/.test(pageSrc) && pageSrc.includes("selectedGroupId"),
"QuotaSharePageClient must render a <select> for groups"
);
});
@@ -161,17 +162,16 @@ test("PoolWizard: includes groupId in the POST /api/quota/pools body", () => {
const postIdx = wizardSrc.indexOf('method: "POST"');
assert.ok(postIdx >= 0, "POST method call must exist in PoolWizard");
const postSection = wizardSrc.slice(postIdx, postIdx + 400);
assert.ok(
postSection.includes("groupId"),
"groupId must be in the POST body JSON.stringify"
);
assert.ok(postSection.includes("groupId"), "groupId must be in the POST body JSON.stringify");
});
// ── PoolWizard: group picker UI in step 1 ────────────────────────────────────
test("PoolWizard: accepts groups prop in PoolWizardProps", () => {
assert.ok(
wizardSrc.includes("groups?:") || wizardSrc.includes("groups ?: ") || wizardSrc.includes("groups?: "),
wizardSrc.includes("groups?:") ||
wizardSrc.includes("groups ?: ") ||
wizardSrc.includes("groups?: "),
"PoolWizardProps must include optional groups prop"
);
});
@@ -184,7 +184,7 @@ test("PoolWizard: renders a group picker <select> in step 1", () => {
assert.ok(step2Idx > step1Idx, "step === 2 block must come after step === 1");
const step1Block = wizardSrc.slice(step1Idx, step2Idx);
assert.ok(
step1Block.includes("groupId") && step1Block.includes("<select"),
step1Block.includes("groupId") && /<select|<Select/.test(step1Block),
"step 1 must include a group picker <select> with groupId binding"
);
});
@@ -250,22 +250,14 @@ const GROUP_KEYS = [
test("i18n: all group keys present in en.json quotaShare namespace", () => {
const en = JSON.parse(readFileSync(EN_PATH, "utf8")) as Record<string, Record<string, string>>;
for (const k of GROUP_KEYS) {
assert.equal(
typeof en["quotaShare"]?.[k],
"string",
`en.json missing quotaShare.${k}`
);
assert.equal(typeof en["quotaShare"]?.[k], "string", `en.json missing quotaShare.${k}`);
}
});
test("i18n: all group keys present in pt-BR.json quotaShare namespace", () => {
const pt = JSON.parse(readFileSync(PT_PATH, "utf8")) as Record<string, Record<string, string>>;
for (const k of GROUP_KEYS) {
assert.equal(
typeof pt["quotaShare"]?.[k],
"string",
`pt-BR.json missing quotaShare.${k}`
);
assert.equal(typeof pt["quotaShare"]?.[k], "string", `pt-BR.json missing quotaShare.${k}`);
}
});
@@ -284,5 +276,9 @@ test("i18n: no group keys are present in en but missing from pt-BR (full parity)
const enKeys = new Set(Object.keys(en["quotaShare"] ?? {}));
const ptKeys = new Set(Object.keys(pt["quotaShare"] ?? {}));
const missingInPt = GROUP_KEYS.filter((k) => enKeys.has(k) && !ptKeys.has(k));
assert.deepEqual(missingInPt, [], `pt-BR.json missing quotaShare keys: ${missingInPt.join(", ")}`);
assert.deepEqual(
missingInPt,
[],
`pt-BR.json missing quotaShare keys: ${missingInPt.join(", ")}`
);
});

View File

@@ -61,7 +61,11 @@ test("PoolCreateSchema rejects when primary connectionId is NOT in connectionIds
name: "x",
allocations: [],
});
assert.equal(result.success, false, "Expected refine to reject when primary not in connectionIds");
assert.equal(
result.success,
false,
"Expected refine to reject when primary not in connectionIds"
);
const msg = result.error?.issues[0]?.message ?? "";
assert.ok(
msg.includes("primary connectionId must be one of connectionIds"),
@@ -101,10 +105,7 @@ test("PoolCreateSchema accepts connectionIds with single element matching connec
// ── PoolWizard.tsx structural assertions ──────────────────────────────────────
test("PoolWizard.tsx: connectionIds state is defined (multi-select)", () => {
assert.ok(
wizardSrc.includes("connectionIds"),
"Expected connectionIds state in PoolWizard"
);
assert.ok(wizardSrc.includes("connectionIds"), "Expected connectionIds state in PoolWizard");
assert.ok(
wizardSrc.includes("useState<string[]>([])"),
"Expected connectionIds initialized as string[] state"
@@ -113,7 +114,8 @@ test("PoolWizard.tsx: connectionIds state is defined (multi-select)", () => {
test("PoolWizard.tsx: renders checkboxes for connection selection in step 1", () => {
assert.ok(
wizardSrc.includes('type="checkbox"'),
// KEA-7886: connections are kit Checkbox adapters (a native input[type=checkbox]).
wizardSrc.includes("<Checkbox"),
"Expected checkbox inputs in step 1 for multi-connection selection"
);
});
@@ -130,10 +132,7 @@ test("PoolWizard.tsx: POST body sends both connectionId and connectionIds", () =
wizardSrc.includes("connectionId: primaryConnectionId"),
"Expected connectionId: primaryConnectionId in POST body"
);
assert.ok(
wizardSrc.includes("connectionIds,"),
"Expected connectionIds spread in POST body"
);
assert.ok(wizardSrc.includes("connectionIds,"), "Expected connectionIds spread in POST body");
});
test("PoolWizard.tsx: step-3 preview maps over connectionIds (previewByProvider)", () => {
@@ -185,7 +184,11 @@ for (const key of NEW_KEYS) {
Object.prototype.hasOwnProperty.call(en.quotaShare, key),
`en.json missing quotaShare.${key}`
);
assert.equal(typeof en.quotaShare[key], "string", `quotaShare.${key} must be a string in en.json`);
assert.equal(
typeof en.quotaShare[key],
"string",
`quotaShare.${key} must be a string in en.json`
);
assert.ok(en.quotaShare[key].length > 0, `quotaShare.${key} must not be empty in en.json`);
});
@@ -194,7 +197,11 @@ for (const key of NEW_KEYS) {
Object.prototype.hasOwnProperty.call(pt.quotaShare, key),
`pt-BR.json missing quotaShare.${key}`
);
assert.equal(typeof pt.quotaShare[key], "string", `quotaShare.${key} must be a string in pt-BR.json`);
assert.equal(
typeof pt.quotaShare[key],
"string",
`quotaShare.${key} must be a string in pt-BR.json`
);
assert.ok(pt.quotaShare[key].length > 0, `quotaShare.${key} must not be empty in pt-BR.json`);
});
}

View File

@@ -2,7 +2,17 @@
import React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi, beforeAll } from "vitest";
// The kit Table (KEA-7886) mounts a persistent horizontal scrollbar that measures the table
// with ResizeObserver, which jsdom does not implement.
beforeAll(() => {
globalThis.ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
} as unknown as typeof ResizeObserver;
});
// next-intl: no local mock — falls through to the real-EN-text default mock in
// tests/_setup/vitestUiPolyfills.ts. The previous `(key) => key` mock rendered
@@ -10,9 +20,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
// lowercase "hard"/"soft" check below (case mismatch: "policyHard" vs "hard"). The real
// en.json copy for both keys is the plain lowercase word.
const { default: AllocationTable } = await import(
"../../../src/app/(dashboard)/dashboard/costs/quota-share/components/AllocationTable"
);
const { default: AllocationTable } =
await import("../../../src/app/(dashboard)/dashboard/costs/quota-share/components/AllocationTable");
const ALLOCATIONS = [
{ apiKeyId: "key_1", weight: 60, policy: "hard" as const },
@@ -25,8 +34,9 @@ let container: HTMLDivElement | null = null;
let root: ReturnType<typeof createRoot> | null = null;
async function render(props: Parameters<typeof AllocationTable>[0]) {
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT =
true;
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
container = document.createElement("div");
document.body.appendChild(container);
await act(async () => {

View File

@@ -18,7 +18,17 @@
import React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi, beforeAll } from "vitest";
// The kit Table (KEA-7886) mounts a persistent horizontal scrollbar that measures the table
// with ResizeObserver, which jsdom does not implement.
beforeAll(() => {
globalThis.ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
} as unknown as typeof ResizeObserver;
});
vi.mock("next-intl", () => ({
useTranslations: () => (key: string) => key,
@@ -107,7 +117,8 @@ async function renderComponent() {
/** Clicks the delete button of the first pool card. */
async function clickDelete() {
const btn = [...document.querySelectorAll("button")].find(
(b) => b.querySelector("span.material-symbols-outlined")?.textContent?.trim() === "delete"
// KEA-7886: icons are Lucide <svg class="oi-icon" data-icon="…"> via <Icon>.
(b) => b.querySelector('svg.oi-icon[data-icon="delete"]') !== null
);
if (!btn) throw new Error("delete button not rendered");
await act(async () => {

View File

@@ -2,7 +2,17 @@
import React from "react";
import { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi, beforeAll } from "vitest";
// The kit Table (KEA-7886) mounts a persistent horizontal scrollbar that measures the table
// with ResizeObserver, which jsdom does not implement.
beforeAll(() => {
globalThis.ResizeObserver ??= class {
observe() {}
unobserve() {}
disconnect() {}
} as unknown as typeof ResizeObserver;
});
// ── i18n stub ──────────────────────────────────────────────────────────────
vi.mock("next-intl", () => ({