Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
feat(quota): 3-step pool wizard unifying connection, plan and key allocation (Phase C1)
diegosouzapw62de5a83b870
diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsxindex 38cbaf2876..ccc84c505d 100644--- a/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx+++ b/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx@@ -11,7 +11,7 @@ import { useLocalStoragePoolMigration } from "./hooks/useLocalStoragePoolMigratiimport { usePoolsUsageAggregate } from "./hooks/usePoolsUsageAggregate";import QuotaConceptCard from "./components/QuotaConceptCard";import PoolCard from "./components/PoolCard";-import CreatePoolModal from "./components/CreatePoolModal";+import PoolWizard from "./components/PoolWizard";import EditAllocationsModal from "./components/EditAllocationsModal";// ────────────────────────────────────────────────────────────────────────────@@ -204,18 +204,6 @@ export default function QuotaSharePageClient() {// ── Mutations ─────────────────────────────────────────────────────────────- const handleCreate = useCallback(- async (poolData: Omit<QuotaPool, "id" | "createdAt">) => {- await fetch("/api/quota/pools", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(poolData),- });- await mutate();- },- [mutate]- );-const handleSaveAllocations = useCallback(async (pool: QuotaPool, allocations: PoolAllocation[]) => {await fetch(`/api/quota/pools/${pool.id}`, {@@ -307,15 +295,15 @@ export default function QuotaSharePageClient() {)}{/* Modals */}- {createOpen && (- <CreatePoolModal- connections={connections}- plans={plans}- existingPools={pools}- onClose={() => setCreateOpen(false)}- onCreate={handleCreate}- />- )}+ <PoolWizard+ open={createOpen}+ onClose={() => setCreateOpen(false)}+ onSaved={() => void mutate()}+ connections={connections}+ apiKeys={apiKeys}+ plans={plans}+ existingPoolConnectionIds={new Set(pools.map((p) => p.connectionId))}+ />{editing && (<EditAllocationsModaldiff --git a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsxnew file mode 100644index 0000000000..55ff9440e4--- /dev/null+++ b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx@@ -0,0 +1,761 @@+"use client";++/**+ * PoolWizard — 3-step guided pool creation wizard.+ *+ * Step 1 · Conta — connection picker + pool name + default policy+ * Step 2 · Limite — editable plan dimensions for the chosen connection (PUT /api/quota/plans/[id])+ * Step 3 · Chaves — allocation rows + "exclusive" checkbox + quotaModelName preview+ *+ * On finish:+ * 1. POST /api/quota/pools → get new pool id+ * 2. PUT /api/quota/plans/[connId] → only when user edited dimensions+ * 3. PATCH /api/quota/pools/[id] → allocations + exclusive flag+ *+ * Visually mirrors BuildWizard's Stepper from the Playground.+ *+ * Phase C1 — Quota Share Redesign.+ */++import { useEffect, useMemo, useState } from "react";+import { useTranslations } from "next-intl";+import { Button, Modal } from "@/shared/components";+import { getKnownPlan } from "@/lib/quota/planRegistry";+import { quotaModelName } from "@/lib/quota/quotaModelNaming";+import type { Policy, PoolAllocation, QuotaDimension, QuotaUnit, QuotaWindow } from "@/lib/quota/dimensions";++// ────────────────────────────────────────────────────────────────────────────+// Types (mirror what CreatePoolModal/EditAllocationsModal expect)+// ────────────────────────────────────────────────────────────────────────────++interface Connection {+ id: string;+ provider: string;+ name?: string;+ displayName?: string;+ email?: string;+}++interface ApiKey {+ id: string;+ name?: string;+}++interface PlanInfo {+ dimensions: QuotaDimension[];+ source: "auto" | "manual";+}++export interface PoolWizardProps {+ open: boolean;+ onClose: () => void;+ onSaved: () => void;+ connections: Connection[];+ apiKeys: ApiKey[];+ plans: Record<string, PlanInfo>;+ existingPoolConnectionIds: Set<string>;+}++// ────────────────────────────────────────────────────────────────────────────+// Constants+// ────────────────────────────────────────────────────────────────────────────++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"],+ anthropic: ["claude-opus-4-5", "claude-sonnet-4-5", "claude-haiku-3-5"],+ gemini: ["gemini-2.5-pro", "gemini-2.5-flash", "gemini-2.0-flash"],+ cx: ["gpt-5.4-mini", "gpt-5.4", "o3"],+ codex: ["codex-mini-latest", "codex-latest"],+ glm: ["glm-4", "glm-4v", "glm-z1-airx"],+ minimax: ["minimax-m1", "minimax-text-01"],+ kimi: ["moonshot-v1-8k", "moonshot-v1-32k"],+ default: ["model-a", "model-b", "model-c"],+};++function getPreviewModels(provider: string): string[] {+ return PREVIEW_MODELS_BY_PROVIDER[provider] ?? PREVIEW_MODELS_BY_PROVIDER["default"];+}++// ────────────────────────────────────────────────────────────────────────────+// Stepper header (mirrors BuildWizard's Stepper)+// ────────────────────────────────────────────────────────────────────────────++function Stepper({ currentStep }: { currentStep: 1 | 2 | 3 }) {+ const t = useTranslations("quotaShare");++ const steps: Array<{ num: 1 | 2 | 3; label: string }> = [+ { num: 1, label: t("wizardStep1Label") },+ { num: 2, label: t("wizardStep2Label") },+ { num: 3, label: t("wizardStep3Label") },+ ];++ return (+ <div className="flex items-center gap-0 px-4 py-3 border-b border-border bg-bg-alt shrink-0">+ {steps.map((step, idx) => (+ <div key={step.num} className="flex items-center">+ {idx > 0 && (+ <div+ className={`h-px w-8 mx-2 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 ${+ currentStep === step.num+ ? "bg-primary text-white"+ : currentStep > step.num+ ? "bg-primary/20 text-primary"+ : "bg-border text-text-muted"+ }`}+ >+ {currentStep > step.num ? (+ <span className="material-symbols-outlined text-[12px]">check</span>+ ) : (+ step.num+ )}+ </span>+ <span+ className={`text-xs font-medium transition-colors ${+ currentStep === step.num ? "text-text-main" : "text-text-muted"+ }`}+ >+ {step.label}+ </span>+ </div>+ </div>+ ))}+ </div>+ );+}++// ────────────────────────────────────────────────────────────────────────────+// Main component+// ────────────────────────────────────────────────────────────────────────────++export default function PoolWizard({+ open,+ onClose,+ onSaved,+ connections,+ apiKeys,+ plans,+ existingPoolConnectionIds,+}: PoolWizardProps) {+ const t = useTranslations("quotaShare");+ const tPlans = useTranslations("quotaPlans");++ // ── Wizard step ───────────────────────────────────────────────────────────+ const [step, setStep] = useState<1 | 2 | 3>(1);++ // ── Step 1 state ──────────────────────────────────────────────────────────+ const [connectionId, setConnectionId] = useState("");+ const [poolName, setPoolName] = useState("");+ const [defaultPolicy, setDefaultPolicy] = useState<Policy>("hard");++ // ── Step 2 state ──────────────────────────────────────────────────────────+ const [editDimensions, setEditDimensions] = useState<QuotaDimension[]>([]);+ const [dimensionsEdited, setDimensionsEdited] = useState(false);++ // ── Step 3 state ──────────────────────────────────────────────────────────+ const [allocations, setAllocations] = useState<PoolAllocation[]>([]);+ const [exclusive, setExclusive] = useState(false);++ // ── Saving ────────────────────────────────────────────────────────────────+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);++ // ── Helpers ───────────────────────────────────────────────────────────────++ const connLabel = (c: Connection) =>+ `${c.provider} / ${c.name || c.email || c.displayName || c.id.slice(0, 12)}`;++ const selectedConn = useMemo(+ () => connections.find((c) => c.id === connectionId),+ [connections, connectionId]+ );++ const availableConnections = useMemo(+ () => connections.filter((c) => !existingPoolConnectionIds.has(c.id)),+ [connections, existingPoolConnectionIds]+ );++ // ── Load dimensions when connection changes ───────────────────────────────++ useEffect(() => {+ if (!connectionId) {+ setEditDimensions([]);+ setDimensionsEdited(false);+ return;+ }+ const existingPlan = plans[connectionId];+ if (existingPlan && existingPlan.dimensions.length > 0) {+ setEditDimensions([...existingPlan.dimensions]);+ } else {+ const catalogPlan = selectedConn ? getKnownPlan(selectedConn.provider) : null;+ setEditDimensions(catalogPlan ? [...catalogPlan.dimensions] : []);+ }+ setDimensionsEdited(false);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [connectionId]);++ // ── Reset wizard on open/close ────────────────────────────────────────────++ useEffect(() => {+ if (!open) {+ setStep(1);+ setConnectionId("");+ setPoolName("");+ setDefaultPolicy("hard");+ setEditDimensions([]);+ setDimensionsEdited(false);+ setAllocations([]);+ setExclusive(false);+ setError(null);+ setSaving(false);+ }+ }, [open]);++ // ── Step 2 — dimension editors ────────────────────────────────────────────++ const addDimension = () => {+ setEditDimensions((prev) => [...prev, { unit: "percent", window: "daily", limit: 100 }]);+ setDimensionsEdited(true);+ };++ const removeDimension = (i: number) => {+ setEditDimensions((prev) => prev.filter((_, idx) => idx !== i));+ setDimensionsEdited(true);+ };++ const updateDimension = (i: number, patch: Partial<QuotaDimension>) => {+ setEditDimensions((prev) => prev.map((d, idx) => (idx === i ? { ...d, ...patch } : d)));+ setDimensionsEdited(true);+ };++ // ── Step 3 — allocation editors ───────────────────────────────────────────++ const totalWeight = allocations.reduce(+ (s, a) => s + (Number.isFinite(a.weight) ? a.weight : 0),+ 0+ );++ const availableKeys = apiKeys.filter((k) => !allocations.some((a) => a.apiKeyId === k.id));++ const keyLabel = (id: string) =>+ apiKeys.find((k) => k.id === id)?.name || id.slice(0, 12) + "…";++ const addKey = (id: string) => {+ setAllocations((prev) => [...prev, { apiKeyId: id, weight: 0, policy: defaultPolicy }]);+ };++ const updateWeight = (id: string, value: number) => {+ setAllocations((prev) =>+ prev.map((a) =>+ a.apiKeyId === id ? { ...a, weight: Math.max(0, Math.min(100, value)) } : a+ )+ );+ };++ const updateAllocationPolicy = (id: string, policy: Policy) => {+ setAllocations((prev) => prev.map((a) => (a.apiKeyId === id ? { ...a, policy } : a)));+ };++ const updateCapValue = (id: string, capValue: number | undefined) => {+ setAllocations((prev) => prev.map((a) => (a.apiKeyId === id ? { ...a, capValue } : a)));+ };++ const removeAllocation = (id: string) => {+ setAllocations((prev) => prev.filter((a) => a.apiKeyId !== id));+ };++ const equalSplit = () => {+ if (allocations.length === 0) return;+ const each = Math.floor(100 / allocations.length);+ const remainder = 100 - each * allocations.length;+ setAllocations((prev) =>+ prev.map((a, i) => ({ ...a, weight: each + (i < remainder ? 1 : 0) }))+ );+ };++ // ── Preview model names ───────────────────────────────────────────────────++ const previewNames = useMemo(() => {+ if (!selectedConn || !poolName.trim()) return [];+ const models = getPreviewModels(selectedConn.provider);+ const MAX = 6;+ return models.slice(0, MAX).map((m) =>+ quotaModelName(poolName.trim(), selectedConn.provider, m)+ );+ }, [selectedConn, poolName]);++ const effectivePoolName = poolName.trim() || (selectedConn ? connLabel(selectedConn) : "");++ // ── Save sequence ─────────────────────────────────────────────────────────++ const handleFinish = async () => {+ if (!selectedConn) return;+ setSaving(true);+ setError(null);++ try {+ // 1. POST /api/quota/pools → get new pool id+ const createRes = await fetch("/api/quota/pools", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ connectionId,+ name: effectivePoolName,+ allocations: [],+ }),+ });+ if (!createRes.ok) {+ const errBody = await createRes.json().catch(() => null);+ throw new Error(+ errBody?.error?.message || `POST /api/quota/pools failed: HTTP ${createRes.status}`+ );+ }+ const createData = (await createRes.json()) as { pool: { id: string } };+ const newPoolId = createData.pool.id;++ // 2. PUT /api/quota/plans/[connectionId] — only when user edited dimensions+ if (dimensionsEdited && editDimensions.length > 0) {+ const planRes = await fetch(`/api/quota/plans/${connectionId}`, {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ dimensions: editDimensions }),+ });+ if (!planRes.ok) {+ const errBody = await planRes.json().catch(() => null);+ throw new Error(+ errBody?.error?.message || `PUT /api/quota/plans failed: HTTP ${planRes.status}`+ );+ }+ }++ // 3. PATCH /api/quota/pools/[id] — allocations + exclusive flag+ const patchRes = await fetch(`/api/quota/pools/${newPoolId}`, {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ allocations, exclusive }),+ });+ if (!patchRes.ok) {+ const errBody = await patchRes.json().catch(() => null);+ throw new Error(+ errBody?.error?.message || `PATCH /api/quota/pools failed: HTTP ${patchRes.status}`+ );+ }++ onSaved();+ onClose();+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to create pool");+ } finally {+ setSaving(false);+ }+ };++ // ── Render ────────────────────────────────────────────────────────────────++ if (!open) return null;++ return (+ <Modal isOpen onClose={onClose} title={t("wizardTitle")} size="lg">+ <div className="flex flex-col" style={{ minHeight: 420 }}>+ <Stepper currentStep={step} />++ {/* ── Step 1: Conta ───────────────────────────────────────────── */}+ {step === 1 && (+ <div className="flex-1 p-4 space-y-4 overflow-y-auto">+ <div>+ <h2 className="text-sm font-semibold text-text-main mb-0.5">+ {t("wizardStep1Title")}+ </h2>+ <p className="text-[11px] text-text-muted">{t("wizardStep1Subtitle")}</p>+ </div>++ {/* Connection selector */}+ <div>+ <label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">+ {t("providerConnection")}+ </label>+ <select+ value={connectionId}+ onChange={(e) => {+ setConnectionId(e.target.value);+ setPoolName("");+ }}+ className="w-full px-3 py-2 rounded border border-border bg-bg-base text-sm"+ >+ <option value="">{t("selectConnection")}</option>+ {availableConnections.map((c) => (+ <option key={c.id} value={c.id}>+ {connLabel(c)}+ </option>+ ))}+ {connections+ .filter((c) => existingPoolConnectionIds.has(c.id))+ .map((c) => (+ <option key={c.id} value={c.id} disabled>+ {connLabel(c)} {t("alreadyUsedSuffix")}+ </option>+ ))}+ </select>+ {connections.length === 0 && (+ <p className="text-[10px] text-amber-400 mt-1">{t("noEligibleConnections")}</p>+ )}+ </div>++ {/* Pool name */}+ {connectionId && (+ <div>+ <label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">+ {t("wizardPoolNameLabel")}+ </label>+ <input+ type="text"+ value={poolName}+ onChange={(e) => setPoolName(e.target.value)}+ placeholder={selectedConn ? connLabel(selectedConn) : t("wizardPoolNamePlaceholder")}+ className="w-full px-3 py-2 rounded border border-border bg-bg-base text-sm"+ />+ </div>+ )}++ {/* Default policy */}+ {connectionId && (+ <div>+ <label className="text-[11px] uppercase tracking-wide text-text-muted font-semibold block mb-1">+ {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" ? t("policyHard") : p === "soft" ? t("policySoft") : t("policyBurst")}+ </button>+ ))}+ </div>+ </div>+ )}++ <div className="flex justify-end pt-2">+ <button+ onClick={() => setStep(2)}+ disabled={!connectionId}+ className="flex items-center gap-1.5 text-sm px-4 py-2 rounded-lg bg-primary text-white hover:bg-primary/90 transition-colors disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {t("wizardNext")}+ <span className="material-symbols-outlined text-[16px]">arrow_forward</span>+ </button>+ </div>+ </div>+ )}++ {/* ── Step 2: Limite ──────────────────────────────────────────── */}+ {step === 2 && (+ <div className="flex-1 p-4 space-y-4 overflow-y-auto">+ <div>+ <h2 className="text-sm font-semibold text-text-main mb-0.5">+ {t("wizardStep2Title")}+ </h2>+ <p className="text-[11px] text-text-muted">{t("wizardStep2Subtitle")}</p>+ </div>++ {/* Dimensions editor (ported from ProviderPlanConfigClient) */}+ <div className="rounded-lg border border-border/40 bg-bg-subtle/10 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>+ {tPlans("addDimension")}+ </button>+ </div>++ {editDimensions.length === 0 && (+ <div className="text-[11px] text-text-muted italic py-3 text-center">+ {tPlans("unconfiguredLabel")} — {tPlans("addDimension")}+ </div>+ )}++ <div className="space-y-2">+ {editDimensions.map((dim, i) => (+ <div+ key={i}+ className="grid items-center gap-2"+ style={{ gridTemplateColumns: "1fr 1fr 90px 24px" }}+ >+ <select+ 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"+ >+ {UNIT_OPTIONS.map((u) => (+ <option key={u} value={u}>+ {tPlans(`unitOptions.${u}`)}+ </option>+ ))}+ </select>+ <select+ 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"+ >+ {WINDOW_OPTIONS.map((w) => (+ <option key={w} value={w}>+ {tPlans(`windowOptions.${w}`)}+ </option>+ ))}+ </select>+ <input+ type="number"+ min={0}+ 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"+ />+ <button+ type="button"+ onClick={() => removeDimension(i)}+ className="p-0.5 rounded hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"+ >+ <span className="material-symbols-outlined text-[16px]">close</span>+ </button>+ </div>+ ))}+ </div>+ </div>++ {dimensionsEdited && (+ <p className="text-[10px] text-amber-400">{t("wizardDimensionsEditedNotice")}</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>+ {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-white hover:bg-primary/90 transition-colors"+ >+ {t("wizardNext")}+ <span className="material-symbols-outlined text-[16px]">arrow_forward</span>+ </button>+ </div>+ </div>+ )}++ {/* ── Step 3: Chaves ──────────────────────────────────────────── */}+ {step === 3 && (+ <div className="flex-1 p-4 space-y-4 overflow-y-auto">+ <div>+ <h2 className="text-sm font-semibold text-text-main mb-0.5">+ {t("wizardStep3Title")}+ </h2>+ <p className="text-[11px] text-text-muted">{t("wizardStep3Subtitle")}</p>+ </div>++ {/* 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">+ {t("noKeysAdded")}+ </div>+ ) : (+ <div className="space-y-2">+ {allocations.map((a, i) => {+ const color = SLICE_PALETTE[i % SLICE_PALETTE.length];+ return (+ <div+ key={a.apiKeyId}+ className="grid items-center gap-2"+ style={{ gridTemplateColumns: "12px minmax(0,1fr) 70px 80px 90px 24px" }}+ >+ <span+ className="inline-block w-3 h-3 rounded-sm"+ style={{ background: color }}+ />+ <span className="text-[12px] font-mono truncate">{keyLabel(a.apiKeyId)}</span>+ <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"+ title="Weight %"+ />+ <input+ type="number"+ min={0}+ value={a.capValue ?? ""}+ onChange={(e) =>+ updateCapValue(+ a.apiKeyId,+ e.target.value ? Number(e.target.value) : undefined+ )+ }+ placeholder={t("policyCapAbsolutePlaceholder")}+ className="px-2 py-1 rounded border border-border bg-bg-base text-xs tabular-nums"+ title={t("policyCapAbsoluteLabel")}+ />+ <select+ 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"+ >+ <option value="hard">{t("policyHard")}</option>+ <option value="soft">{t("policySoft")}</option>+ <option value="burst">{t("policyBurst")}</option>+ </select>+ <button+ type="button"+ onClick={() => removeAllocation(a.apiKeyId)}+ className="p-0.5 rounded hover:bg-red-500/10 text-text-muted hover:text-red-400 cursor-pointer"+ >+ <span className="material-symbols-outlined text-[16px]">close</span>+ </button>+ </div>+ );+ })}+ </div>+ )}++ {/* Add key + equal split controls */}+ <div className="flex items-center justify-between text-[11px] pt-1 border-t border-border/40">+ <span+ className={`font-bold tabular-nums ${+ totalWeight === 100+ ? "text-emerald-400"+ : totalWeight > 100+ ? "text-red-400"+ : "text-amber-400"+ }`}+ >+ {t("totalLabel", { percent: totalWeight })}{" "}+ {totalWeight > 100 && t("totalExceeded")}+ </span>+ <div className="flex items-center gap-2">+ {availableKeys.length > 0 && (+ <select+ value=""+ onChange={(e) => e.target.value && addKey(e.target.value)}+ className="px-2 py-1 rounded border border-border bg-bg-base text-xs"+ >+ <option value="">{t("addKey")}</option>+ {availableKeys.map((k) => (+ <option key={k.id} value={k.id}>+ {k.name || k.id.slice(0, 12) + "…"}+ </option>+ ))}+ </select>+ )}+ <Button+ variant="secondary"+ size="sm"+ onClick={equalSplit}+ disabled={allocations.length === 0}+ >+ {t("equalSplit")}+ </Button>+ </div>+ </div>++ {/* Exclusive checkbox */}+ <label className="flex items-start gap-2 cursor-pointer select-none pt-1 border-t border-border/40">+ <input+ type="checkbox"+ checked={exclusive}+ onChange={(e) => setExclusive(e.target.checked)}+ className="mt-0.5 accent-primary w-4 h-4"+ />+ <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>++ {/* quotaModelName preview */}+ {previewNames.length > 0 && (+ <div className="rounded-md border border-border/40 bg-bg-subtle/30 p-3 text-[11px]">+ <div className="font-semibold text-text-muted uppercase tracking-wide mb-1.5 text-[10px]">+ {t("wizardPreviewLabel")}+ </div>+ <div className="space-y-0.5">+ {previewNames.map((name) => (+ <div key={name} className="font-mono text-text-main truncate">+ {name}+ </div>+ ))}+ </div>+ </div>+ )}++ {error && (+ <p className="text-[11px] text-red-400 bg-red-500/10 px-3 py-2 rounded">{error}</p>+ )}++ <div className="flex items-center justify-between pt-2 border-t border-border/40">+ <button+ 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+ variant="primary"+ size="sm"+ onClick={() => void handleFinish()}+ disabled={totalWeight > 100 || saving}+ >+ {saving ? t("loading") : t("wizardCreatePool")}+ </Button>+ </div>+ </div>+ )}+ </div>+ </Modal>+ );+}diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex cdf202d968..0bab3d17bd 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -7866,7 +7866,26 @@"policyCapAbsolutePlaceholder": "Numeric limit (optional)","multiDimensionLabel": "Multi-dimension","stackedBarTitle": "Slices by API key",- "usedSuffix": "used {percent}%"+ "usedSuffix": "used {percent}%",+ "wizardTitle": "New quota pool",+ "wizardStep1Label": "Account",+ "wizardStep2Label": "Limit",+ "wizardStep3Label": "Keys",+ "wizardStep1Title": "Choose provider connection",+ "wizardStep1Subtitle": "Select the provider account this pool will share quota for, set a name and default policy.",+ "wizardStep2Title": "Configure quota dimensions",+ "wizardStep2Subtitle": "Define the quota plan dimensions (unit, window, limit) for the chosen connection. Leave unchanged to keep current settings.",+ "wizardStep3Title": "Allocate API keys",+ "wizardStep3Subtitle": "Assign API keys to this pool with weight % allocations and optional caps.",+ "wizardPoolNameLabel": "Pool name",+ "wizardPoolNamePlaceholder": "My quota pool",+ "wizardNext": "Next",+ "wizardBack": "Back",+ "wizardCreatePool": "Create pool",+ "wizardDimensionsEditedNotice": "Dimensions edited — will be saved as a manual override when the pool is created.",+ "wizardExclusiveLabel": "Exclusive quota",+ "wizardExclusiveHint": "When enabled, these API keys will only be allowed to use this pool's virtual models (allowedQuotas reconciliation is applied on save).",+ "wizardPreviewLabel": "Virtual model names preview"},"plugins": {"title": "Plugins",diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.jsonindex 5dcfa9391f..c4b9e6f010 100644--- a/src/i18n/messages/pt-BR.json+++ b/src/i18n/messages/pt-BR.json@@ -5376,7 +5376,26 @@"policyCapAbsolutePlaceholder": "Limite numérico (opcional)","multiDimensionLabel": "Multi-dimensão","stackedBarTitle": "Fatias por API key",- "usedSuffix": "usou {percent}%"+ "usedSuffix": "usou {percent}%",+ "wizardTitle": "Novo pool de cota",+ "wizardStep1Label": "Conta",+ "wizardStep2Label": "Limite",+ "wizardStep3Label": "Chaves",+ "wizardStep1Title": "Escolha a conexão de provider",+ "wizardStep1Subtitle": "Selecione a conta do provider cuja cota este pool compartilhará, defina um nome e a política padrão.",+ "wizardStep2Title": "Configure as dimensões de cota",+ "wizardStep2Subtitle": "Defina as dimensões do plano de cota (unidade, janela, limite) para a conexão escolhida. Deixe sem alteração para manter as configurações atuais.",+ "wizardStep3Title": "Aloque API keys",+ "wizardStep3Subtitle": "Atribua API keys a este pool com alocações de peso % e caps opcionais.",+ "wizardPoolNameLabel": "Nome do pool",+ "wizardPoolNamePlaceholder": "Meu pool de cota",+ "wizardNext": "Avançar",+ "wizardBack": "Voltar",+ "wizardCreatePool": "Criar pool",+ "wizardDimensionsEditedNotice": "Dimensões editadas — serão salvas como override manual quando o pool for criado.",+ "wizardExclusiveLabel": "Cota exclusiva",+ "wizardExclusiveHint": "Quando ativado, estas API keys só poderão usar os modelos virtuais deste pool (reconciliação de allowedQuotas aplicada ao salvar).",+ "wizardPreviewLabel": "Prévia dos nomes de modelos virtuais"},"requestLogger": {"recording": "Recording",diff --git a/tests/unit/quota-pool-wizard.test.ts b/tests/unit/quota-pool-wizard.test.tsnew file mode 100644index 0000000000..ebb7015e42--- /dev/null+++ b/tests/unit/quota-pool-wizard.test.ts@@ -0,0 +1,201 @@+/**+ * Structure tests for the 3-step Pool Wizard (Phase C1).+ *+ * These assertions intentionally read the source files as text to verify:+ * - PoolWizard.tsx contains all 3 wizard steps+ * - The PATCH body includes the `exclusive` flag+ * - quotaModelName is imported for the preview+ * - QuotaSharePageClient mounts <PoolWizard+ *+ * Node native test runner (no JSdom needed — pure source analysis).+ */++import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "..");++const WIZARD_PATH = path.join(+ ROOT,+ "src",+ "app",+ "(dashboard)",+ "dashboard",+ "costs",+ "quota-share",+ "components",+ "PoolWizard.tsx"+);++const PAGE_CLIENT_PATH = path.join(+ ROOT,+ "src",+ "app",+ "(dashboard)",+ "dashboard",+ "costs",+ "quota-share",+ "QuotaSharePageClient.tsx"+);++const wizardSrc = fs.readFileSync(WIZARD_PATH, "utf-8");+const pageClientSrc = fs.readFileSync(PAGE_CLIENT_PATH, "utf-8");++// ── PoolWizard.tsx assertions ─────────────────────────────────────────────────++test("PoolWizard.tsx: step 1 (Conta) is present", () => {+ assert.ok(+ wizardSrc.includes("step === 1"),+ "Expected step === 1 block for Conta step"+ );+});++test("PoolWizard.tsx: step 2 (Limite) is present", () => {+ assert.ok(+ wizardSrc.includes("step === 2"),+ "Expected step === 2 block for Limite step"+ );+});++test("PoolWizard.tsx: step 3 (Chaves) is present", () => {+ assert.ok(+ wizardSrc.includes("step === 3"),+ "Expected step === 3 block for Chaves step"+ );+});++test("PoolWizard.tsx: PATCH body includes the exclusive flag", () => {+ assert.ok(+ wizardSrc.includes("exclusive"),+ "Expected 'exclusive' to appear in PoolWizard (PATCH body)"+ );+ // More specifically, the PATCH body object literal must pass exclusive+ assert.ok(+ wizardSrc.includes("body: JSON.stringify({ allocations, exclusive })"),+ "Expected PATCH body to serialize { allocations, exclusive }"+ );+});++test("PoolWizard.tsx: quotaModelName is imported from quotaModelNaming", () => {+ assert.ok(+ wizardSrc.includes("quotaModelName"),+ "Expected quotaModelName import in PoolWizard"+ );+ assert.ok(+ wizardSrc.includes("from \"@/lib/quota/quotaModelNaming\"") ||+ wizardSrc.includes("from '@/lib/quota/quotaModelNaming'"),+ "Expected import from @/lib/quota/quotaModelNaming"+ );+});++test("PoolWizard.tsx: preview section renders quotaModelName output", () => {+ assert.ok(+ wizardSrc.includes("previewNames"),+ "Expected previewNames variable used in the preview section"+ );+});++test("PoolWizard.tsx: save sequence does POST then conditional PUT then PATCH", () => {+ const postIdx = wizardSrc.indexOf('method: "POST"');+ const putIdx = wizardSrc.indexOf('method: "PUT"');+ const patchIdx = wizardSrc.indexOf('method: "PATCH"');++ assert.ok(postIdx !== -1, "Expected POST /api/quota/pools in PoolWizard");+ assert.ok(putIdx !== -1, "Expected PUT /api/quota/plans/[id] in PoolWizard");+ assert.ok(patchIdx !== -1, "Expected PATCH /api/quota/pools/[id] in PoolWizard");++ // POST must come before PUT and PATCH in the file+ assert.ok(postIdx < putIdx, "POST must appear before PUT in handleFinish");+ assert.ok(putIdx < patchIdx, "PUT must appear before PATCH in handleFinish");+});++test("PoolWizard.tsx: Stepper renders 3-step header", () => {+ assert.ok(+ wizardSrc.includes("Stepper"),+ "Expected a Stepper component in PoolWizard"+ );+ assert.ok(+ wizardSrc.includes("wizardStep1Label"),+ "Expected wizardStep1Label i18n key used"+ );+ assert.ok(+ wizardSrc.includes("wizardStep2Label"),+ "Expected wizardStep2Label i18n key used"+ );+ assert.ok(+ wizardSrc.includes("wizardStep3Label"),+ "Expected wizardStep3Label i18n key used"+ );+});++test("PoolWizard.tsx: plan dimensions editor uses UNIT_OPTIONS and WINDOW_OPTIONS", () => {+ assert.ok(+ wizardSrc.includes("UNIT_OPTIONS"),+ "Expected UNIT_OPTIONS constant for the dimensions unit select"+ );+ assert.ok(+ wizardSrc.includes("WINDOW_OPTIONS"),+ "Expected WINDOW_OPTIONS constant for the dimensions window select"+ );+});++test("PoolWizard.tsx: dimensions are only saved when user edited them (dimensionsEdited flag)", () => {+ assert.ok(+ wizardSrc.includes("dimensionsEdited"),+ "Expected dimensionsEdited guard before PUT /api/quota/plans"+ );+});++test("PoolWizard.tsx: exclusive checkbox is rendered in step 3", () => {+ assert.ok(+ wizardSrc.includes('type="checkbox"'),+ "Expected a checkbox input for exclusive flag in step 3"+ );+ assert.ok(+ wizardSrc.includes("wizardExclusiveLabel"),+ "Expected wizardExclusiveLabel i18n key for the exclusive checkbox"+ );+});++// ── QuotaSharePageClient.tsx assertions ───────────────────────────────────────++test("QuotaSharePageClient.tsx: imports PoolWizard (not CreatePoolModal)", () => {+ assert.ok(+ pageClientSrc.includes("import PoolWizard"),+ "Expected PoolWizard import in QuotaSharePageClient"+ );+ assert.ok(+ !pageClientSrc.includes("import CreatePoolModal"),+ "CreatePoolModal should no longer be imported in QuotaSharePageClient"+ );+});++test("QuotaSharePageClient.tsx: mounts <PoolWizard", () => {+ assert.ok(+ pageClientSrc.includes("<PoolWizard"),+ "Expected <PoolWizard mount in QuotaSharePageClient JSX"+ );+});++test("QuotaSharePageClient.tsx: passes open/onClose/onSaved/connections/apiKeys/plans/existingPoolConnectionIds to PoolWizard", () => {+ assert.ok(pageClientSrc.includes("open={createOpen}"), "Expected open prop");+ assert.ok(pageClientSrc.includes("onClose="), "Expected onClose prop");+ assert.ok(pageClientSrc.includes("onSaved="), "Expected onSaved prop");+ assert.ok(pageClientSrc.includes("connections={connections}"), "Expected connections prop");+ assert.ok(pageClientSrc.includes("apiKeys={apiKeys}"), "Expected apiKeys prop");+ assert.ok(pageClientSrc.includes("plans={plans}"), "Expected plans prop");+ assert.ok(+ pageClientSrc.includes("existingPoolConnectionIds="),+ "Expected existingPoolConnectionIds prop"+ );+});++test("QuotaSharePageClient.tsx: EditAllocationsModal is still present for editing existing pools", () => {+ assert.ok(+ pageClientSrc.includes("EditAllocationsModal"),+ "Expected EditAllocationsModal to remain for editing existing pools"+ );+});