Skip to content

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

feat(quota): PoolWizard editPool mode (full pool edit via PATCH)

diegosouzapwb64489b3addc
diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx
index 4c1b450ee3..8f6c7b07e6 100644
--- a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx
+++ b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx
@@ -25,6 +25,7 @@ import { maskEmailLikeValue } from "@/shared/utils/maskEmail";
import { getKnownPlan } from "@/lib/quota/planRegistry";
import { quotaModelName } from "@/lib/quota/quotaModelNaming";
import type { Policy, PoolAllocation, QuotaDimension, QuotaUnit, QuotaWindow } from "@/lib/quota/dimensions";
+import type { QuotaPool } from "@/lib/db/quotaPools";
// ────────────────────────────────────────────────────────────────────────────
// Types (mirror what CreatePoolModal/EditAllocationsModal expect)
@@ -64,6 +65,8 @@ export interface PoolWizardProps {
existingPoolConnectionIds: Set<string>;
groups?: QuotaGroup[];
selectedGroupId?: string;
+ /** When provided, the wizard enters edit mode — pre-fills from the pool and PATCHes instead of POSTing. */
+ editPool?: QuotaPool;
}
// ────────────────────────────────────────────────────────────────────────────
@@ -169,6 +172,7 @@ export default function PoolWizard({
existingPoolConnectionIds,
groups = [],
selectedGroupId: initialGroupId = "group-demo",
+ editPool,
}: PoolWizardProps) {
const t = useTranslations("quotaShare");
const tPlans = useTranslations("quotaPlans");
@@ -255,6 +259,7 @@ export default function PoolWizard({
useEffect(() => {
if (!open) {
+ // Closing: always reset to defaults.
setStep(1);
setConnectionIds([]);
setPoolName("");
@@ -266,8 +271,36 @@ export default function PoolWizard({
setError(null);
setSaving(false);
setGroupId(initialGroupId);
+ } else if (editPool) {
+ // Opening in edit mode: pre-fill from the existing pool.
+ const ids =
+ Array.isArray(editPool.connectionIds) && editPool.connectionIds.length > 0
+ ? editPool.connectionIds
+ : [editPool.connectionId];
+ setConnectionIds(ids);
+ setPoolName(editPool.name);
+ setGroupId(editPool.groupId ?? initialGroupId);
+ setAllocations(editPool.allocations ?? []);
+ // `exclusive` is not stored on the QuotaPool type; default to false in edit mode.
+ // The server-side reconcilePoolExclusivity will apply the chosen value on PATCH.
+ setExclusive(false);
+ // Pre-load plan dimensions for the primary connection (same as create path).
+ // dimensionsEdited stays false so the PUT is skipped unless the user actively edits.
+ const primaryId = ids[0];
+ const existingPlan = plans[primaryId];
+ if (existingPlan && existingPlan.dimensions.length > 0) {
+ setEditDimensions([...existingPlan.dimensions]);
+ } else {
+ setEditDimensions([]);
+ }
+ setDimensionsEdited(false);
+ setError(null);
+ setSaving(false);
+ setStep(1);
}
- }, [open, initialGroupId]);
+ // When open && !editPool (create mode): the existing create-reset on close handles defaults.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [open, editPool, initialGroupId]);
// ── Step 2 — dimension editors ────────────────────────────────────────────
@@ -374,53 +407,95 @@ export default function PoolWizard({
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: primaryConnectionId,
- connectionIds,
- name: effectivePoolName,
- allocations: [],
- groupId,
- }),
- });
- 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;
+ if (!editPool) {
+ // ── Create mode: POST → optional PUT → PATCH ──────────────────────
- // 2. PUT /api/quota/plans/[primaryConnectionId] — only when user edited dimensions
- if (dimensionsEdited && editDimensions.length > 0) {
- const planRes = await fetch(`/api/quota/plans/${primaryConnectionId}`, {
- method: "PUT",
+ // 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({ dimensions: editDimensions }),
+ body: JSON.stringify({
+ connectionId: primaryConnectionId,
+ connectionIds,
+ name: effectivePoolName,
+ allocations: [],
+ groupId,
+ }),
});
- if (!planRes.ok) {
- const errBody = await planRes.json().catch(() => null);
+ if (!createRes.ok) {
+ const errBody = await createRes.json().catch(() => null);
throw new Error(
- errBody?.error?.message || `PUT /api/quota/plans failed: HTTP ${planRes.status}`
+ 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/[primaryConnectionId] — only when user edited dimensions
+ if (dimensionsEdited && editDimensions.length > 0) {
+ const planRes = await fetch(`/api/quota/plans/${primaryConnectionId}`, {
+ 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}`
- );
+ // 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}`
+ );
+ }
+ } else {
+ // ── Edit mode: single PATCH (folds name, groupId, connectionIds, allocations, exclusive)
+ // + optional PUT for plan dimensions when user edited them.
+
+ // 1. PATCH /api/quota/pools/[id] — all editable fields in one call
+ const editPatchRes = await fetch(`/api/quota/pools/${editPool.id}`, {
+ method: "PATCH",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: effectivePoolName,
+ groupId,
+ connectionIds,
+ allocations,
+ exclusive,
+ }),
+ });
+ if (!editPatchRes.ok) {
+ const errBody = await editPatchRes.json().catch(() => null);
+ throw new Error(
+ errBody?.error?.message ||
+ `PATCH /api/quota/pools failed: HTTP ${editPatchRes.status}`
+ );
+ }
+
+ // 2. PUT /api/quota/plans/[primaryConnectionId] — only when user actually edited dimensions
+ if (dimensionsEdited && editDimensions.length > 0) {
+ const planRes = await fetch(`/api/quota/plans/${primaryConnectionId}`, {
+ 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}`
+ );
+ }
+ }
}
onSaved();
@@ -437,7 +512,7 @@ export default function PoolWizard({
if (!open) return null;
return (
- <Modal isOpen onClose={onClose} title={t("wizardTitle")} size="lg">
+ <Modal isOpen onClose={onClose} title={editPool ? t("editPoolTitle") : t("wizardTitle")} size="lg">
<div className="flex flex-col" style={{ minHeight: 420 }}>
<Stepper currentStep={step} />
@@ -894,7 +969,7 @@ export default function PoolWizard({
onClick={() => void handleFinish()}
disabled={totalWeight > 100 || saving}
>
- {saving ? t("loading") : t("wizardCreatePool")}
+ {saving ? t("loading") : editPool ? t("saveChanges") : t("wizardCreatePool")}
</Button>
</div>
</div>
diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.json
index 63f61a4a71..6a181a7142 100644
--- a/src/i18n/messages/en.json
+++ b/src/i18n/messages/en.json
@@ -7877,6 +7877,8 @@
"stackedBarTitle": "Slices by API key",
"usedSuffix": "used {percent}%",
"wizardTitle": "New quota pool",
+ "editPoolTitle": "Edit pool",
+ "saveChanges": "Save changes",
"wizardStep1Label": "Account",
"wizardStep2Label": "Limit",
"wizardStep3Label": "Keys",
diff --git a/src/i18n/messages/pt-BR.json b/src/i18n/messages/pt-BR.json
index 77580dc264..6ebd0f7e91 100644
--- a/src/i18n/messages/pt-BR.json
+++ b/src/i18n/messages/pt-BR.json
@@ -5382,6 +5382,8 @@
"stackedBarTitle": "Fatias por API key",
"usedSuffix": "usou {percent}%",
"wizardTitle": "Novo pool de cota",
+ "editPoolTitle": "Editar pool",
+ "saveChanges": "Salvar alterações",
"wizardStep1Label": "Conta",
"wizardStep2Label": "Limite",
"wizardStep3Label": "Chaves",
diff --git a/tests/unit/quota-pool-wizard-edit.test.ts b/tests/unit/quota-pool-wizard-edit.test.ts
new file mode 100644
index 0000000000..1bed430aa6
--- /dev/null
+++ b/tests/unit/quota-pool-wizard-edit.test.ts
@@ -0,0 +1,171 @@
+/**
+ * Structure tests for PoolWizard editPool mode (Task 5 — Phase C1).
+ *
+ * Source-scan style, mirroring quota-pool-wizard.test.ts.
+ * No JSdom needed — pure text analysis of the source file.
+ */
+
+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 EN_JSON_PATH = path.join(ROOT, "src", "i18n", "messages", "en.json");
+const PT_BR_JSON_PATH = path.join(ROOT, "src", "i18n", "messages", "pt-BR.json");
+
+const wizardSrc = fs.readFileSync(WIZARD_PATH, "utf-8");
+const enJson = JSON.parse(fs.readFileSync(EN_JSON_PATH, "utf-8")) as Record<string, unknown>;
+const ptBrJson = JSON.parse(fs.readFileSync(PT_BR_JSON_PATH, "utf-8")) as Record<string, unknown>;
+
+// ── PoolWizardProps: editPool field ───────────────────────────────────────────
+
+test("PoolWizard.tsx: declares editPool in PoolWizardProps", () => {
+ assert.ok(
+ wizardSrc.includes("editPool?"),
+ "Expected optional editPool field in PoolWizardProps"
+ );
+});
+
+test("PoolWizard.tsx: imports QuotaPool type", () => {
+ assert.ok(
+ wizardSrc.includes("QuotaPool"),
+ "Expected QuotaPool type to be referenced in PoolWizard"
+ );
+});
+
+// ── Submit handler branching ──────────────────────────────────────────────────
+
+test("PoolWizard.tsx: submit handler contains a PATCH to /api/quota/pools/ (edit branch)", () => {
+ assert.ok(
+ wizardSrc.includes("PATCH") && wizardSrc.includes("/api/quota/pools/"),
+ "Expected PATCH call to /api/quota/pools/ in PoolWizard"
+ );
+});
+
+test("PoolWizard.tsx: submit handler still contains a POST to /api/quota/pools (create branch)", () => {
+ assert.ok(
+ wizardSrc.includes('method: "POST"') && wizardSrc.includes("/api/quota/pools"),
+ "Expected POST call to /api/quota/pools in PoolWizard (create branch must remain)"
+ );
+});
+
+test("PoolWizard.tsx: submit handler branches on editPool", () => {
+ assert.ok(
+ wizardSrc.includes("editPool"),
+ "Expected editPool to appear in PoolWizard source (branching in submit)"
+ );
+ // The branching condition inside handleFinish
+ assert.ok(
+ wizardSrc.includes("if (editPool)"),
+ "Expected if (editPool) branch in handleFinish"
+ );
+});
+
+// ── Pre-fill references ───────────────────────────────────────────────────────
+
+test("PoolWizard.tsx: pre-fills pool name from editPool.name", () => {
+ assert.ok(
+ wizardSrc.includes("editPool.name"),
+ "Expected editPool.name used for pre-filling pool name"
+ );
+});
+
+test("PoolWizard.tsx: pre-fills allocations from editPool.allocations", () => {
+ assert.ok(
+ wizardSrc.includes("editPool.allocations"),
+ "Expected editPool.allocations used for pre-filling allocations"
+ );
+});
+
+test("PoolWizard.tsx: pre-fills connectionIds using editPool.connectionIds and editPool.connectionId", () => {
+ assert.ok(
+ wizardSrc.includes("editPool.connectionIds"),
+ "Expected editPool.connectionIds referenced in pre-fill logic"
+ );
+ assert.ok(
+ wizardSrc.includes("editPool.connectionId"),
+ "Expected editPool.connectionId referenced as fallback in pre-fill logic"
+ );
+});
+
+test("PoolWizard.tsx: pre-fills groupId from editPool.groupId", () => {
+ assert.ok(
+ wizardSrc.includes("editPool.groupId"),
+ "Expected editPool.groupId used for pre-filling group selector"
+ );
+});
+
+// ── i18n key usage ────────────────────────────────────────────────────────────
+
+test("PoolWizard.tsx: uses t(\"saveChanges\") for the submit button in edit mode", () => {
+ assert.ok(
+ wizardSrc.includes('t("saveChanges")'),
+ "Expected t(\"saveChanges\") used in submit button (edit mode)"
+ );
+});
+
+test("PoolWizard.tsx: uses t(\"editPoolTitle\") for the modal title in edit mode", () => {
+ assert.ok(
+ wizardSrc.includes('t("editPoolTitle")'),
+ "Expected t(\"editPoolTitle\") used in modal title (edit mode)"
+ );
+});
+
+// ── i18n parity: en.json ─────────────────────────────────────────────────────
+
+test("en.json quotaShare namespace: contains editPoolTitle key", () => {
+ const quotaShare = enJson["quotaShare"] as Record<string, unknown> | undefined;
+ assert.ok(quotaShare, "Expected quotaShare namespace in en.json");
+ assert.ok(
+ "editPoolTitle" in quotaShare,
+ "Expected editPoolTitle key in en.json quotaShare namespace"
+ );
+ assert.equal(typeof quotaShare["editPoolTitle"], "string", "editPoolTitle must be a string");
+});
+
+test("en.json quotaShare namespace: contains saveChanges key", () => {
+ const quotaShare = enJson["quotaShare"] as Record<string, unknown> | undefined;
+ assert.ok(quotaShare, "Expected quotaShare namespace in en.json");
+ assert.ok(
+ "saveChanges" in quotaShare,
+ "Expected saveChanges key in en.json quotaShare namespace"
+ );
+ assert.equal(typeof quotaShare["saveChanges"], "string", "saveChanges must be a string");
+});
+
+// ── i18n parity: pt-BR.json ──────────────────────────────────────────────────
+
+test("pt-BR.json quotaShare namespace: contains editPoolTitle key", () => {
+ const quotaShare = ptBrJson["quotaShare"] as Record<string, unknown> | undefined;
+ assert.ok(quotaShare, "Expected quotaShare namespace in pt-BR.json");
+ assert.ok(
+ "editPoolTitle" in quotaShare,
+ "Expected editPoolTitle key in pt-BR.json quotaShare namespace"
+ );
+ assert.equal(typeof quotaShare["editPoolTitle"], "string", "editPoolTitle must be a string");
+});
+
+test("pt-BR.json quotaShare namespace: contains saveChanges key", () => {
+ const quotaShare = ptBrJson["quotaShare"] as Record<string, unknown> | undefined;
+ assert.ok(quotaShare, "Expected quotaShare namespace in pt-BR.json");
+ assert.ok(
+ "saveChanges" in quotaShare,
+ "Expected saveChanges key in pt-BR.json quotaShare namespace"
+ );
+ assert.equal(typeof quotaShare["saveChanges"], "string", "saveChanges must be a string");
+});