litellm/tests/e2e/ui/tests/proxy-admin/keyBudgetWindow.spec.ts
yuneng-jiang 37b3a697c7
fix(ui): preserve key settings drafts during background refreshes (#41350)
* fix(ui): preserve key settings drafts during background refreshes

* fix(ui): refresh untouched key settings while preserving edits

* fix(ui): keep team-change MCP clears across key refreshes

clearMcpGrants now marks the MCP fields dirty, so a background refresh with
keepDirtyValues no longer restores the grants a team change just cleared.
Also adapts the draft tests to the onSubmit(values, dirtyFields) signature
on main and asserts a refresh does not mark untouched fields dirty, since the
team admin member-key path rejects saves with non-budget dirty fields.
KeyEditView becomes a one-line arrow to stay under the max-lines limit.

* fix(ui): keep MCP tool defaults out of a key's edited fields

MCPToolPermissions writes non-delete tool defaults for unrestricted servers
on mount. Marking that write dirty made a team admin's budget-only save on a
member key get rejected for editing mcp_tool_permissions. onChange now says
whether a write is a default or a user edit, and the key editor dirties only
edits.

The edit session is now keyed by token or token_id, matching the form's own
fallback, so switching between keys that only carry token_id starts fresh.

* fix(ui): keep a new MCP server's default tool limits across refreshes

Default tool writes for a server the user just added in this edit session
are part of that edit, so they are marked dirty and survive a background
refresh. Defaults written for an already saved server stay clean, so a team
admin's budget-only save on a member key is still accepted.
2026-10-16 17:20:46 -07:00

135 lines
6.2 KiB
TypeScript

import { test as base, expect } from "@playwright/test";
import { ADMIN_STORAGE_PATH, E2E_TEAM_CRUD_ID } from "../../constants";
import { Page } from "../../fixtures/pages";
import { dismissFeedbackPopup, navigateToPage, openKeyDetail } from "../../helpers/navigation";
import { captureRequestBody } from "../../helpers/roundTrip";
import { CHAT_MODEL_A, createVirtualKey, deleteVirtualKey, readKeyInfo, uniqueSuffix } from "../../helpers/traffic";
interface ScopedKey {
alias: string;
token: string;
}
const test = base.extend<{ scopedKey: ScopedKey }>({
scopedKey: async ({ page }, use) => {
const alias = `e2e-budget-window-${uniqueSuffix()}`;
const created = await createVirtualKey(page.request, {
key_alias: alias,
team_id: E2E_TEAM_CRUD_ID,
models: [CHAT_MODEL_A],
});
try {
await use({ alias, token: created.token });
} finally {
await deleteVirtualKey(page.request, created.token);
}
},
});
test.describe("Proxy Admin - Key budget window", () => {
// TODO: drop once https://github.com/BerriAI/litellm/pull/41350 lands, a background refresh can wipe the edit draft
test.describe.configure({ retries: 2 });
test.use({ storageState: ADMIN_STORAGE_PATH });
test("a monthly spend cap survives a reload, and clearing the window keeps the cap", async ({ page, scopedKey }) => {
const { alias, token } = scopedKey;
const before = await readKeyInfo(page.request, token);
expect(before.max_budget, "a freshly generated key starts with no budget").toBeNull();
await navigateToPage(page, Page.ApiKeys);
await dismissFeedbackPopup(page);
// The initial, unfiltered list must already contain this newly created key.
// useKeys keeps that list visible while the filtered search is pending.
await expect(page.getByRole("row").filter({ hasText: alias })).toBeVisible({ timeout: 15_000 });
// Deliver the real search result after editing starts: replacing the list's
// key object must not reset the open form and erase its unsaved budget.
const searchReceived = Promise.withResolvers<void>();
const releaseSearch = Promise.withResolvers<void>();
const isAliasSearch = (url: string) => {
const parsed = new URL(url);
return parsed.pathname.endsWith("/key/list") && parsed.searchParams.get("search") === alias;
};
await page.route("**/key/list?**", async (route) => {
if (!isAliasSearch(route.request().url())) return route.continue();
const response = await route.fetch();
searchReceived.resolve();
await releaseSearch.promise;
await route.fulfill({ response });
});
try {
await openKeyDetail(page, alias);
await page.getByRole("tab", { name: "Settings" }).click();
await page.getByRole("button", { name: "Edit Settings" }).click();
await page.getByRole("spinbutton", { name: "Max Budget (USD)" }).fill("12.5");
await searchReceived.promise;
const refreshed = page.waitForResponse((response) => isAliasSearch(response.url()));
releaseSearch.resolve();
await refreshed;
} finally {
releaseSearch.resolve();
await page.unrouteAll({ behavior: "wait" });
}
await page.getByLabel("Reset Budget", { exact: true }).click();
await page.getByRole("option", { name: "monthly", exact: true }).click();
const saved = await captureRequestBody(page, { method: "POST", urlIncludes: "/key/update" }, async () => {
await page.getByRole("button", { name: "Save Changes" }).click();
});
expect(saved.max_budget, "a delayed search response must not erase the budget draft").toBe("12.5");
expect(saved.budget_duration).toBe("30d");
await expect
.poll(async () => (await readKeyInfo(page.request, token)).max_budget, {
message: "the $12.50 cap never reached /key/info",
timeout: 20_000,
})
.toBe(12.5);
await expect
.poll(async () => (await readKeyInfo(page.request, token)).budget_duration, {
message: "the monthly reset window never reached /key/info",
timeout: 20_000,
})
.toBe("30d");
const capped = await readKeyInfo(page.request, token);
const resetAt = new Date(capped.budget_reset_at ?? "");
expect(Number.isNaN(resetAt.getTime()), "a monthly window left the key with no budget_reset_at").toBe(false);
expect(resetAt.getTime(), "budget_reset_at was set in the past").toBeGreaterThan(Date.now());
expect(resetAt.getUTCDate(), "a monthly window resets on the 1st, a daily one would not").toBe(1);
await page.reload();
await expect(
page.getByRole("paragraph").filter({ hasText: "of $12.50" }),
"the reloaded key detail does not render the $12.50 cap",
).toBeVisible({ timeout: 15_000 });
await page.getByRole("tab", { name: "Settings" }).click();
await expect(
page.getByTestId("budget-reset-value"),
"the reloaded key detail does not name the 30d reset window",
).toHaveText(/Every 30d/, { timeout: 15_000 });
await page.getByRole("button", { name: "Edit Settings" }).click();
await page.getByLabel("Reset Budget", { exact: true }).click();
await page.getByRole("option", { name: "Never resets", exact: true }).click();
const cleared = await captureRequestBody(page, { method: "POST", urlIncludes: "/key/update" }, async () => {
await page.getByRole("button", { name: "Save Changes" }).click();
});
expect(cleared).toHaveProperty("budget_duration");
expect(cleared.budget_duration, "clearing the window must send budget_duration: null explicitly").toBeNull();
await expect
.poll(async () => (await readKeyInfo(page.request, token)).budget_duration, {
message: "the reset window was never cleared on /key/info",
timeout: 20_000,
})
.toBeNull();
const after = await readKeyInfo(page.request, token);
expect(after.budget_reset_at, "clearing the reset window left a stale next-reset timestamp").toBeNull();
expect(after.max_budget, "clearing the reset window also wiped the spend cap").toBe(12.5);
expect(after.models, "editing the budget left the key's models untouched").toEqual(before.models);
expect(after.team_id, "editing the budget left the key's team untouched").toEqual(before.team_id);
});
});