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): edit button opens full PoolWizard (exclusive-preserving); retire EditAllocationsModal
diegosouzapw684863635186
diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsxindex e5d9069b07..9c28789aff 100644--- a/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx+++ b/src/app/(dashboard)/dashboard/costs/quota-share/QuotaSharePageClient.tsx@@ -6,7 +6,7 @@ import { Button } from "@/shared/components";import EmailPrivacyToggle from "@/shared/components/EmailPrivacyToggle";import useEmailPrivacyStore from "@/store/emailPrivacyStore";import { maskEmailLikeValue } from "@/shared/utils/maskEmail";-import type { QuotaPool, PoolAllocation } from "@/lib/quota/dimensions";+import type { QuotaPool } from "@/lib/quota/dimensions";import { usePools } from "./hooks/usePools";import { usePoolUsage } from "./hooks/usePoolUsage";@@ -15,7 +15,6 @@ import { usePoolsUsageAggregate } from "./hooks/usePoolsUsageAggregate";import QuotaConceptCard from "./components/QuotaConceptCard";import PoolCard from "./components/PoolCard";import PoolWizard from "./components/PoolWizard";-import EditAllocationsModal from "./components/EditAllocationsModal";// ────────────────────────────────────────────────────────────────────────────// Local types (display layer only)@@ -304,20 +303,25 @@ export default function QuotaSharePageClient() {[groups, selectedGroupId]);- // ── Mutations ─────────────────────────────────────────────────────────────+ // ── Computed exclusivity for the pool being edited ───────────────────────+ //+ // A pool is exclusive when it has ≥1 allocation AND every allocated key+ // currently has the pool id in its allowedQuotas array.- const handleSaveAllocations = useCallback(- async (pool: QuotaPool, allocations: PoolAllocation[]) => {- await fetch(`/api/quota/pools/${pool.id}`, {- method: "PATCH",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ allocations }),- });- await mutate();- },- [mutate]+ const editingExclusive = useMemo(+ () =>+ !!editing &&+ editing.allocations.length > 0 &&+ editing.allocations.every((a) => {+ const k = apiKeys.find((kk) => kk.id === a.apiKeyId);+ const aq = (k as { allowedQuotas?: string[] } | undefined)?.allowedQuotas;+ return Array.isArray(aq) && aq.includes(editing.id);+ }),+ [editing, apiKeys]);+ // ── Mutations ─────────────────────────────────────────────────────────────+const handleRemovePool = useCallback(async (id: string) => {if (!confirm(t("removeConfirm"))) return;@@ -534,14 +538,23 @@ export default function QuotaSharePageClient() {selectedGroupId={selectedGroupId}/>- {editing && (- <EditAllocationsModal- pool={editing}- apiKeys={apiKeys}- onClose={() => setEditing(null)}- onSave={(allocations) => handleSaveAllocations(editing, allocations)}- />- )}+ {/* Edit wizard — separate instance from create to avoid shared state */}+ <PoolWizard+ open={!!editing}+ onClose={() => setEditing(null)}+ onSaved={() => {+ void mutate();+ setEditing(null);+ }}+ editPool={editing ?? undefined}+ editPoolExclusive={editingExclusive}+ connections={connections}+ apiKeys={apiKeys}+ plans={plans}+ existingPoolConnectionIds={new Set(pools.filter((p) => p.id !== editing?.id).map((p) => p.connectionId))}+ groups={groups}+ selectedGroupId={selectedGroupId}+ /></div>);}diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/components/EditAllocationsModal.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/components/EditAllocationsModal.tsxdeleted file mode 100644index ebe1a03028..0000000000--- a/src/app/(dashboard)/dashboard/costs/quota-share/components/EditAllocationsModal.tsx+++ /dev/null@@ -1,244 +0,0 @@-"use client";--import { useState } from "react";-import { useTranslations } from "next-intl";-import { Button, Modal } from "@/shared/components";-import useEmailPrivacyStore from "@/store/emailPrivacyStore";-import { maskEmailLikeValue } from "@/shared/utils/maskEmail";-import type { QuotaPool, PoolAllocation, Policy } from "@/lib/quota/dimensions";--interface ApiKey {- id: string;- name?: string;-}--interface EditAllocationsModalProps {- pool: QuotaPool;- apiKeys: ApiKey[];- onClose: () => void;- onSave: (allocations: PoolAllocation[]) => Promise<void>;-}--function shortId(id: string, max = 12) {- return id.length > max ? `${id.slice(0, max)}…` : id;-}--const SLICE_PALETTE = [- "#a78bfa",- "#60a5fa",- "#34d399",- "#fbbf24",- "#f87171",- "#22d3ee",- "#f472b6",- "#94a3b8",-];--export default function EditAllocationsModal({- pool,- apiKeys,- onClose,- onSave,-}: EditAllocationsModalProps) {- const t = useTranslations("quotaShare");- const emailsVisible = useEmailPrivacyStore((s) => s.emailsVisible);- const [drafts, setDrafts] = useState<PoolAllocation[]>(pool.allocations);- const [saving, setSaving] = useState(false);- const [error, setError] = useState<string | null>(null);-- const totalWeight = drafts.reduce(- (s, a) => s + (Number.isFinite(a.weight) ? a.weight : 0),- 0- );-- const availableKeys = apiKeys.filter((k) => !drafts.some((a) => a.apiKeyId === k.id));-- const keyLabel = (id: string) => apiKeys.find((k) => k.id === id)?.name || shortId(id);-- const addKey = (id: string) => {- setDrafts((prev) => {- const next = [...prev, { apiKeyId: id, weight: 0, policy: "hard" as Policy }];- // Equal-split: after adding, recompute weights so no key starts at 0.- const n = next.length;- const each = Math.floor(100 / n);- const remainder = 100 - each * n;- return next.map((a, i) => ({ ...a, weight: each + (i < remainder ? 1 : 0) }));- });- };-- const updateWeight = (id: string, value: number) => {- setDrafts((prev) =>- prev.map((a) =>- a.apiKeyId === id ? { ...a, weight: Math.max(0, Math.min(100, value)) } : a- )- );- };-- const updatePolicy = (id: string, policy: Policy) => {- setDrafts((prev) => prev.map((a) => (a.apiKeyId === id ? { ...a, policy } : a)));- };-- const updateCapValue = (id: string, capValue: number | undefined) => {- setDrafts((prev) => prev.map((a) => (a.apiKeyId === id ? { ...a, capValue } : a)));- };-- const removeKey = (id: string) => {- setDrafts((prev) => prev.filter((a) => a.apiKeyId !== id));- };-- const equalSplit = () => {- if (drafts.length === 0) return;- const each = Math.floor(100 / drafts.length);- const remainder = 100 - each * drafts.length;- setDrafts((prev) => prev.map((a, i) => ({ ...a, weight: each + (i < remainder ? 1 : 0) })));- };-- const handleSave = async () => {- setSaving(true);- setError(null);- try {- await onSave(drafts);- onClose();- } catch (err) {- setError(err instanceof Error ? err.message : "Failed to save");- } finally {- setSaving(false);- }- };-- return (- <Modal isOpen onClose={onClose} title={t("editTitle")} size="lg">- <div className="space-y-3">- <div className="text-xs text-text-muted">- {t("pool")}: <strong className="text-text-main">{emailsVisible ? pool.name : maskEmailLikeValue(pool.name)}</strong>- </div>-- {/* Group allocation note */}- <p className="text-[11px] text-text-muted bg-bg-subtle/40 px-3 py-2 rounded border border-border/40">- <span className="material-symbols-outlined text-[13px] align-middle mr-1 text-primary/70">info</span>- {t("groupAllocationNote")}- </p>-- {drafts.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">- {drafts.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 %"- />- {/* Cap absolute */}- <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")}- />- {/* Policy per key */}- <select- value={a.policy}- onChange={(e) => updatePolicy(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={() => removeKey(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>- )}-- <div className="flex items-center justify-between text-[11px] pt-2 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 || shortId(k.id)}- </option>- ))}- </select>- )}- <Button- variant="secondary"- size="sm"- onClick={equalSplit}- disabled={drafts.length === 0}- >- {t("equalSplit")}- </Button>- </div>- </div>-- {error && (- <p className="text-[11px] text-red-400 bg-red-500/10 px-3 py-2 rounded">{error}</p>- )}-- <div className="flex justify-end gap-2 pt-2 border-t border-border/40">- <Button variant="secondary" size="sm" onClick={onClose} disabled={saving}>- {t("cancel")}- </Button>- <Button- variant="primary"- size="sm"- onClick={handleSave}- disabled={totalWeight > 100 || saving}- >- {saving ? t("loading") : t("save")}- </Button>- </div>- </div>- </Modal>- );-}diff --git a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsxindex 8f6c7b07e6..25803653e1 100644--- a/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx+++ b/src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx@@ -67,6 +67,8 @@ export interface PoolWizardProps {selectedGroupId?: string;/** When provided, the wizard enters edit mode — pre-fills from the pool and PATCHes instead of POSTing. */editPool?: QuotaPool;+ /** Whether the pool being edited is currently exclusive. Used to pre-fill the exclusive checkbox in edit mode. */+ editPoolExclusive?: boolean;}// ────────────────────────────────────────────────────────────────────────────@@ -173,6 +175,7 @@ export default function PoolWizard({groups = [],selectedGroupId: initialGroupId = "group-demo",editPool,+ editPoolExclusive,}: PoolWizardProps) {const t = useTranslations("quotaShare");const tPlans = useTranslations("quotaPlans");@@ -281,9 +284,9 @@ export default function PoolWizard({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);+ // Preserve the pool's current exclusivity state so editing an exclusive pool+ // doesn't silently un-exclusive it. Falls back to false only when not provided.+ setExclusive(editPoolExclusive ?? 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];diff --git a/tests/unit/quota-edit-opens-wizard.test.ts b/tests/unit/quota-edit-opens-wizard.test.tsnew file mode 100644index 0000000000..7ed89dec1e--- /dev/null+++ b/tests/unit/quota-edit-opens-wizard.test.ts@@ -0,0 +1,132 @@+/**+ * tests/unit/quota-edit-opens-wizard.test.ts+ *+ * Task 6 — source-scan assertions for:+ * 1. QuotaSharePageClient no longer imports or renders EditAllocationsModal.+ * 2. The `editing` pool is wired to a <PoolWizard via editPool prop.+ * 3. editPoolExclusive is computed from apiKeys.allowedQuotas and passed through.+ * 4. PoolWizard pre-fill uses editPoolExclusive (not a hard-coded false).+ *+ * Node native test runner — pure source analysis, no DOM needed.+ */++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 PAGE_CLIENT_PATH = path.join(+ ROOT,+ "src",+ "app",+ "(dashboard)",+ "dashboard",+ "costs",+ "quota-share",+ "QuotaSharePageClient.tsx"+);++const WIZARD_PATH = path.join(+ ROOT,+ "src",+ "app",+ "(dashboard)",+ "dashboard",+ "costs",+ "quota-share",+ "components",+ "PoolWizard.tsx"+);++const pageSrc = fs.readFileSync(PAGE_CLIENT_PATH, "utf-8");+const wizardSrc = fs.readFileSync(WIZARD_PATH, "utf-8");++// ── QuotaSharePageClient: EditAllocationsModal must be gone ───────────────────++test("QuotaSharePageClient: does NOT import EditAllocationsModal", () => {+ assert.ok(+ !pageSrc.includes("EditAllocationsModal"),+ "EditAllocationsModal must not appear in QuotaSharePageClient (retired Task 6)"+ );+});++// ── QuotaSharePageClient: editing pool wired to PoolWizard ────────────────────++test("QuotaSharePageClient: passes editing pool as editPool= to PoolWizard", () => {+ assert.ok(+ pageSrc.includes("editPool={editing"),+ "Expected editPool={editing...} prop on the edit PoolWizard instance"+ );+});++test("QuotaSharePageClient: opens edit wizard when editing is set (open={!!editing})", () => {+ assert.ok(+ pageSrc.includes("open={!!editing}"),+ "Expected open={!!editing} on the edit PoolWizard instance"+ );+});++// ── QuotaSharePageClient: editingExclusive computed and passed ────────────────++test("QuotaSharePageClient: computes editingExclusive from allowedQuotas", () => {+ assert.ok(+ pageSrc.includes("editingExclusive"),+ "Expected editingExclusive to be defined in QuotaSharePageClient"+ );+ assert.ok(+ pageSrc.includes("allowedQuotas"),+ "Expected allowedQuotas referenced in editingExclusive computation"+ );+});++test("QuotaSharePageClient: passes editPoolExclusive={editingExclusive} to edit PoolWizard", () => {+ assert.ok(+ pageSrc.includes("editPoolExclusive={editingExclusive}"),+ "Expected editPoolExclusive={editingExclusive} on the edit PoolWizard instance"+ );+});++test("QuotaSharePageClient: editingExclusive requires >=1 allocation", () => {+ // The guard `editing.allocations.length > 0` must be present+ assert.ok(+ pageSrc.includes("allocations.length > 0"),+ "Expected allocations.length > 0 guard in editingExclusive"+ );+});++test("QuotaSharePageClient: editingExclusive checks every allocated key has pool id in allowedQuotas", () => {+ assert.ok(+ pageSrc.includes("aq.includes(editing.id)"),+ "Expected aq.includes(editing.id) check in editingExclusive"+ );+});++// ── PoolWizard: editPoolExclusive prop declared and used ─────────────────────++test("PoolWizard.tsx: declares editPoolExclusive prop in PoolWizardProps", () => {+ assert.ok(+ wizardSrc.includes("editPoolExclusive?"),+ "Expected editPoolExclusive? field in PoolWizardProps"+ );+});++test("PoolWizard.tsx: pre-fill uses editPoolExclusive ?? false (not setExclusive(false))", () => {+ // The old hard-coded false must be replaced by the prop+ assert.ok(+ wizardSrc.includes("editPoolExclusive ?? false"),+ "Expected setExclusive(editPoolExclusive ?? false) in PoolWizard pre-fill"+ );+ // The literal `setExclusive(false)` must NOT appear in the edit-mode pre-fill block+ // (it may still appear in the close-reset block, which is correct)+ const editFillIdx = wizardSrc.indexOf("} else if (editPool)");+ assert.ok(editFillIdx >= 0, "Expected '} else if (editPool)' block in PoolWizard");+ const closingBrace = wizardSrc.indexOf("\n }", editFillIdx);+ const editFillBlock = wizardSrc.slice(editFillIdx, closingBrace > 0 ? closingBrace + 6 : editFillIdx + 1200);+ assert.ok(+ !editFillBlock.includes("setExclusive(false)"),+ "setExclusive(false) must not appear in the editPool pre-fill block — must use editPoolExclusive"+ );+});diff --git a/tests/unit/quota-email-privacy.test.ts b/tests/unit/quota-email-privacy.test.tsindex fddebbe416..7cdfcc051f 100644--- a/tests/unit/quota-email-privacy.test.ts+++ b/tests/unit/quota-email-privacy.test.ts@@ -33,7 +33,6 @@ const pageClientSrc = readSrc(`${quotaShareDir}/QuotaSharePageClient.tsx`);const poolCardSrc = readSrc(`${quotaShareDir}/components/PoolCard.tsx`);const accountQuotaRowSrc = readSrc(`${quotaShareDir}/components/AccountQuotaRow.tsx`);const poolWizardSrc = readSrc(`${quotaShareDir}/components/PoolWizard.tsx`);-const editAllocationsModalSrc = readSrc(`${quotaShareDir}/components/EditAllocationsModal.tsx`);// ── QuotaSharePageClient ──────────────────────────────────────────────────────@@ -177,36 +176,9 @@ test("PoolWizard connLabel masks detail with emailsVisible gate", () => {);});-// ── EditAllocationsModal ──────────────────────────────────────────────────────--test("EditAllocationsModal imports useEmailPrivacyStore", () => {- assert.ok(- editAllocationsModalSrc.includes('import useEmailPrivacyStore from "@/store/emailPrivacyStore"'),- "Expected useEmailPrivacyStore import in EditAllocationsModal"- );-});--test("EditAllocationsModal imports maskEmailLikeValue", () => {- assert.ok(- editAllocationsModalSrc.includes("maskEmailLikeValue"),- "Expected maskEmailLikeValue import/usage in EditAllocationsModal"- );-});--test("EditAllocationsModal consumes emailsVisible from store", () => {- assert.ok(- editAllocationsModalSrc.includes("emailsVisible"),- "Expected emailsVisible usage in EditAllocationsModal"- );-});--test("EditAllocationsModal masks pool.name display", () => {- // pool.name can contain an email (e.g. "codex / [email protected]")- assert.ok(- editAllocationsModalSrc.includes("maskEmailLikeValue(pool.name)"),- "Expected maskEmailLikeValue(pool.name) in EditAllocationsModal"- );-});+// ── EditAllocationsModal retired (Task 6) ────────────────────────────────────+// EditAllocationsModal was retired in Task 6 — edit mode now opens the full+// PoolWizard (which already has comprehensive email-privacy coverage above).// ── maskEmailLikeValue helper behaviour (regression) ─────────────────────────diff --git a/tests/unit/quota-groups-ui.test.ts b/tests/unit/quota-groups-ui.test.tsindex 8502b6c628..1ddbb48c50 100644--- a/tests/unit/quota-groups-ui.test.ts+++ b/tests/unit/quota-groups-ui.test.ts@@ -29,17 +29,11 @@ const WIZARD_PATH = join("src/app/(dashboard)/dashboard/costs/quota-share/components/PoolWizard.tsx");-const MODAL_PATH = join(- ROOT,- "src/app/(dashboard)/dashboard/costs/quota-share/components/EditAllocationsModal.tsx"-);-const EN_PATH = join(ROOT, "src/i18n/messages/en.json");const PT_PATH = join(ROOT, "src/i18n/messages/pt-BR.json");const pageSrc = readFileSync(PAGE_CLIENT_PATH, "utf8");const wizardSrc = readFileSync(WIZARD_PATH, "utf8");-const modalSrc = readFileSync(MODAL_PATH, "utf8");// ── QuotaSharePageClient: group fetch ─────────────────────────────────────────@@ -237,14 +231,9 @@ test("PoolWizard: pool name placeholder uses provider, not connLabel", () => {);});-// ── EditAllocationsModal: group allocation note ────────────────────────────────--test("EditAllocationsModal: renders groupAllocationNote i18n key", () => {- assert.ok(- modalSrc.includes("groupAllocationNote"),- "EditAllocationsModal must render t('groupAllocationNote') helper text"- );-});+// ── PoolWizard: group allocation note (EditAllocationsModal retired Task 6) ───+// EditAllocationsModal was retired in Task 6. The groupAllocationNote key is kept+// in the i18n bundle for backwards compat but the wizard covers allocation editing.// ── i18n parity ───────────────────────────────────────────────────────────────diff --git a/tests/unit/quota-pool-wizard.test.ts b/tests/unit/quota-pool-wizard.test.tsindex ebb7015e42..95b55a8fba 100644--- a/tests/unit/quota-pool-wizard.test.ts+++ b/tests/unit/quota-pool-wizard.test.ts@@ -193,9 +193,15 @@ test("QuotaSharePageClient.tsx: passes open/onClose/onSaved/connections/apiKeys/);});-test("QuotaSharePageClient.tsx: EditAllocationsModal is still present for editing existing pools", () => {+test("QuotaSharePageClient.tsx: EditAllocationsModal is NOT present (retired Task 6 — edit uses PoolWizard)", () => {+ // Task 6 replaced EditAllocationsModal with a second PoolWizard instance for editing.assert.ok(- pageClientSrc.includes("EditAllocationsModal"),- "Expected EditAllocationsModal to remain for editing existing pools"+ !pageClientSrc.includes("EditAllocationsModal"),+ "EditAllocationsModal must not appear in QuotaSharePageClient — edit mode uses PoolWizard"+ );+ // The editing pool must be wired to a PoolWizard via editPool prop+ assert.ok(+ pageClientSrc.includes("editPool={editing"),+ "Expected editPool={editing...} passed to PoolWizard for edit mode");});