Spaces:
Runtime error
Runtime error
File size: 23,177 Bytes
cd8bd0a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | import { expect, test, type Page, type Route } from "@playwright/test";
import { gotoDashboardRoute } from "./helpers/dashboardAuth";
const NAVIGATION_TIMEOUT_MS = 300_000;
const UI_STABILITY_TIMEOUT_MS = 120_000;
type ApiKeyRecord = {
id: string;
name: string;
key: string;
fullKey: string;
allowedModels: string[] | null;
allowedConnections: string[] | null;
createdAt: string;
};
async function fulfillJson(route: Route, body: unknown, status = 200) {
await route.fulfill({
status,
contentType: "application/json",
body: JSON.stringify(body),
});
}
async function installClipboardMock(page: Page) {
await page.addInitScript(() => {
let clipboardValue = "";
Object.defineProperty(window, "__clipboardValue", {
configurable: true,
get: () => clipboardValue,
set: (value) => {
clipboardValue = typeof value === "string" ? value : String(value ?? "");
},
});
Object.defineProperty(navigator, "clipboard", {
configurable: true,
value: {
writeText: async (value: string) => {
(window as Window & { __clipboardValue?: string }).__clipboardValue = value;
},
readText: async () => clipboardValue,
},
});
});
}
async function readClipboard(page: Page) {
return page.evaluate(() => (window as Window & { __clipboardValue?: string }).__clipboardValue);
}
async function waitForPageToSettle(page: Page) {
try {
await page.waitForLoadState("networkidle", { timeout: 15_000 });
} catch {
// Some dashboard pages keep background requests alive; visibility assertions below
// are the authoritative readiness check for these E2E flows.
}
}
async function waitForNextDevCompileToFinish(page: Page) {
const nextDevToolsButton = page.getByRole("button", { name: /open next\.js dev tools/i });
if ((await nextDevToolsButton.count()) === 0) return;
await expect(nextDevToolsButton).not.toContainText(/compiling/i, { timeout: 120_000 });
}
test.describe("API keys flow", () => {
test.setTimeout(600_000);
test("creates, copies, reveals, revokes, and returns to the empty state", async ({ page }) => {
const state: {
keys: ApiKeyRecord[];
nextId: number;
revealCalls: number;
deleteCalls: number;
} = {
keys: [],
nextId: 1,
revealCalls: 0,
deleteCalls: 0,
};
await installClipboardMock(page);
await page.route("**/v1/models", async (route) => {
await fulfillJson(route, { data: [] });
});
await page.route("**/api/settings", async (route) => {
await fulfillJson(route, {});
});
await page.route("**/api/providers", async (route) => {
await fulfillJson(route, {
connections: [
{ id: "conn-openai", name: "OpenAI Main", provider: "openai", isActive: true },
],
});
});
await page.route(/\/api\/usage\/call-logs(?:\?.*)?$/, async (route) => {
await fulfillJson(route, []);
});
await page.route("**/api/sessions", async (route) => {
await fulfillJson(route, { byApiKey: {} });
});
await page.route(/\/api\/keys\/[^/]+\/reveal$/, async (route) => {
state.revealCalls += 1;
const keyId = route.request().url().split("/").slice(-2)[0];
const record = state.keys.find((key) => key.id === keyId);
await fulfillJson(route, { key: record?.fullKey ?? "" });
});
await page.route(/\/api\/keys\/[^/]+$/, async (route) => {
if (route.request().method() === "DELETE") {
state.deleteCalls += 1;
const keyId = route.request().url().split("/").pop() || "";
state.keys = state.keys.filter((key) => key.id !== keyId);
await fulfillJson(route, { success: true });
return;
}
if (route.request().method() === "PATCH") {
const keyId = route.request().url().split("/").pop() || "";
const payload = (await route.request().postDataJSON()) as { name?: string };
const record = state.keys.find((key) => key.id === keyId);
if (!record) {
await fulfillJson(route, { error: "Key not found" }, 404);
return;
}
if (payload.name) {
record.name = payload.name;
}
await fulfillJson(route, { message: "API key settings updated successfully", ...payload });
return;
}
await fulfillJson(route, { error: "Method not allowed in api key detail stub" }, 405);
});
await page.route("**/api/keys", async (route) => {
const method = route.request().method();
if (method === "GET") {
await fulfillJson(route, {
keys: state.keys.map(({ fullKey, ...record }) => record),
allowKeyReveal: true,
});
return;
}
if (method === "POST") {
const payload = (route.request().postDataJSON() as { name?: string }) || {};
const id = `key-${state.nextId++}`;
const suffix = String(1000 + state.nextId);
const fullKey = `sk-live-${suffix}-demo-secret`;
const maskedKey = `sk-live-****${suffix}`;
state.keys.push({
id,
name: payload.name || "New Key",
key: maskedKey,
fullKey,
allowedModels: null,
allowedConnections: null,
createdAt: new Date("2026-04-05T20:00:00.000Z").toISOString(),
});
await fulfillJson(route, { key: fullKey, id });
return;
}
await fulfillJson(route, { error: "Method not allowed in api keys stub" }, 405);
});
await gotoDashboardRoute(page, "/dashboard/api-manager", {
timeoutMs: NAVIGATION_TIMEOUT_MS,
});
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
const createFirstKeyButton = page.getByRole("button", {
name: /create (your )?first key/i,
});
await expect(createFirstKeyButton).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
await createFirstKeyButton.click();
const createDialog = page.getByRole("dialog", { name: /create api key/i });
await expect(createDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await createDialog.locator("input").first().fill("Team Key");
const createKeyButton = createDialog.getByRole("button", { name: /create api key/i });
await expect(createKeyButton).toBeEnabled({ timeout: UI_STABILITY_TIMEOUT_MS });
await createKeyButton.click({ force: true });
await expect.poll(() => state.keys.length).toBe(1);
const createdDialog = page.getByRole("dialog", { name: /api key created/i });
const createdKeyInput = createdDialog.locator("input[readonly]").first();
await expect(createdKeyInput).toHaveValue(/sk-live-/);
await createdDialog.getByRole("button", { name: /copy/i }).click();
await expect.poll(() => readClipboard(page)).toBeTruthy();
const createdClipboardValue = await readClipboard(page);
await expect(createdKeyInput).toHaveValue(createdClipboardValue || "");
await createdDialog.getByRole("button", { name: /done/i }).click();
await expect(page.getByText("Team Key")).toBeVisible();
await expect(page.getByText("sk-live-****1002")).toBeVisible();
const keyRow = page
.locator("div")
.filter({ has: page.getByText("Team Key", { exact: true }) })
.filter({ has: page.getByText("sk-live-****1002", { exact: true }) })
.first();
await keyRow.getByRole("button", { name: /copy/i }).click();
await expect.poll(() => state.revealCalls).toBe(1);
await expect.poll(() => readClipboard(page)).toBe("sk-live-1002-demo-secret");
page.once("dialog", async (dialog) => {
await dialog.accept();
});
await keyRow.locator("button[title]").last().click({ force: true });
await expect.poll(() => state.deleteCalls).toBe(1);
await expect(page.getByText("Team Key")).toHaveCount(0);
await expect(createFirstKeyButton).toBeVisible();
});
test("renames a key through the permissions modal", async ({ page }) => {
const state: {
keys: ApiKeyRecord[];
nextId: number;
} = {
keys: [],
nextId: 1,
};
await page.route("**/v1/models", async (route) => {
await fulfillJson(route, { data: [] });
});
await page.route("**/api/settings", async (route) => {
await fulfillJson(route, {});
});
await page.route("**/api/providers", async (route) => {
await fulfillJson(route, {
connections: [
{ id: "conn-openai", name: "OpenAI Main", provider: "openai", isActive: true },
],
});
});
await page.route(/\/api\/usage\/call-logs(?:\?.*)?$/, async (route) => {
await fulfillJson(route, []);
});
await page.route("**/api/sessions", async (route) => {
await fulfillJson(route, { byApiKey: {} });
});
await page.route(/\/api\/keys\/[^/]+$/, async (route) => {
if (route.request().method() === "PATCH") {
const keyId = route.request().url().split("/").pop() || "";
const payload = (await route.request().postDataJSON()) as { name?: string };
const record = state.keys.find((key) => key.id === keyId);
if (!record) {
await fulfillJson(route, { error: "Key not found" }, 404);
return;
}
if (payload.name) {
record.name = payload.name;
}
await fulfillJson(route, { message: "API key settings updated successfully", ...payload });
return;
}
await fulfillJson(route, { error: "Method not allowed" }, 405);
});
await page.route("**/api/keys", async (route) => {
const method = route.request().method();
if (method === "GET") {
await fulfillJson(route, {
keys: state.keys.map(({ fullKey, ...record }) => record),
allowKeyReveal: true,
});
return;
}
if (method === "POST") {
const payload = (route.request().postDataJSON() as { name?: string }) || {};
const id = `key-${state.nextId++}`;
const suffix = String(1000 + state.nextId);
const fullKey = `sk-live-${suffix}-demo-secret`;
const maskedKey = `sk-live-****${suffix}`;
state.keys.push({
id,
name: payload.name || "New Key",
key: maskedKey,
fullKey,
allowedModels: null,
allowedConnections: null,
createdAt: new Date("2026-04-05T20:00:00.000Z").toISOString(),
});
await fulfillJson(route, { key: fullKey, id });
return;
}
await fulfillJson(route, { error: "Method not allowed" }, 405);
});
await gotoDashboardRoute(page, "/dashboard/api-manager", {
timeoutMs: NAVIGATION_TIMEOUT_MS,
});
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
// --- Create a key ---
const createFirstKeyButton = page.getByRole("button", {
name: /create (your )?first key/i,
});
await expect(createFirstKeyButton).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
await createFirstKeyButton.click();
const createDialog = page.getByRole("dialog", { name: /create api key/i });
await expect(createDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await createDialog.locator("input").first().fill("Original Name");
const createKeyButton = createDialog.getByRole("button", { name: /create api key/i });
await expect(createKeyButton).toBeEnabled({ timeout: UI_STABILITY_TIMEOUT_MS });
await createKeyButton.click({ force: true });
await expect.poll(() => state.keys.length).toBe(1);
// Dismiss the "key created" dialog
const createdDialog = page.getByRole("dialog", { name: /api key created/i });
await createdDialog.getByRole("button", { name: /done/i }).click();
// Wait for the key list to settle after re-fetch
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
// Verify the key appears in the list
await expect(page.getByText("Original Name")).toBeVisible({
timeout: UI_STABILITY_TIMEOUT_MS,
});
// --- Open the permissions modal ---
// The edit-permissions button is opacity-0 until hover; use title attribute locator
const keyRow = page
.locator("div")
.filter({ has: page.getByText("Original Name", { exact: true }) })
.first();
await keyRow.locator('button[title="Edit permissions"]').click({ force: true });
// --- Rename the key ---
const permissionsDialog = page.getByRole("dialog", { name: /permissions: original name/i });
await expect(permissionsDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
// The key name input is inside the permissions modal
const nameInput = permissionsDialog.locator("input").first();
await expect(nameInput).toHaveValue("Original Name");
await nameInput.clear();
await nameInput.fill("Renamed Key");
// Save
await permissionsDialog
.getByRole("button", { name: /save permissions/i })
.click({ force: true });
// Verify the mock state was updated
await expect.poll(() => state.keys[0]?.name).toBe("Renamed Key");
// Verify the dialog closes and the list reflects the new name
await expect(permissionsDialog).not.toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await expect(page.getByText("Renamed Key")).toBeVisible();
});
test("validation error appears inside the create key modal, not behind the backdrop", async ({
page,
}) => {
const state = {
keys: [] as ApiKeyRecord[],
nextId: 1,
};
// Stub all API routes
await page.route("**/v1/models", async (route) => {
await fulfillJson(route, { data: [] });
});
await page.route("**/api/connections", async (route) => {
await fulfillJson(route, {
connections: [
{ id: "conn-openai", name: "OpenAI Main", provider: "openai", isActive: true },
],
});
});
await page.route(/\/api\/usage\/call-logs(?:\?.*)?$/, async (route) => {
await fulfillJson(route, []);
});
await page.route("**/api/sessions", async (route) => {
await fulfillJson(route, { byApiKey: {} });
});
await page.route("**/api/keys", async (route) => {
const method = route.request().method();
if (method === "GET") {
await fulfillJson(route, {
keys: state.keys.map(({ fullKey, ...record }) => record),
allowKeyReveal: true,
});
return;
}
if (method === "POST") {
const payload = (route.request().postDataJSON() as { name?: string }) || {};
const id = `key-${state.nextId++}`;
const suffix = String(1000 + state.nextId);
const fullKey = `sk-live-${suffix}-demo-secret`;
const maskedKey = `sk-live-****${suffix}`;
state.keys.push({
id,
name: payload.name || "New Key",
key: maskedKey,
fullKey,
allowedModels: null,
allowedConnections: null,
createdAt: new Date().toISOString(),
});
await fulfillJson(route, { key: fullKey, id });
return;
}
await fulfillJson(route, { error: "Method not allowed" }, 405);
});
await page.route(/\/api\/keys\/[^/]+$/, async (route) => {
await fulfillJson(route, { error: "Not found" }, 404);
});
await page.route(/\/api\/keys\/[^/]+\/reveal$/, async (route) => {
await fulfillJson(route, { key: "" });
});
await gotoDashboardRoute(page, "/dashboard/api-manager", {
timeoutMs: NAVIGATION_TIMEOUT_MS,
});
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
// Open the create key modal
const createFirstKeyButton = page.getByRole("button", {
name: /create (your )?first key/i,
});
await expect(createFirstKeyButton).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await createFirstKeyButton.click();
const createDialog = page.getByRole("dialog", { name: /create api key/i });
await expect(createDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
// Fill an invalid name (special characters) and submit
const nameInput = createDialog.locator("input").first();
await nameInput.fill("bad@name!");
const createKeyButton = createDialog.getByRole("button", { name: /create api key/i });
await createKeyButton.click({ force: true });
// The validation error must appear as an inline <p role="alert"> INSIDE the modal
const inlineError = createDialog.locator("p[role='alert']");
await expect(inlineError).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
// The error must be visible — i.e. not obscured by the backdrop.
// A covered element has box visibility but fails the check below because
// pointer events and paint are blocked by the overlay div.
await expect(inlineError).toBeInViewport();
// No page-level error banner should appear behind the modal
const pageErrorBanner = page.locator('.flex.flex-col.gap-8 > [class~="bg-red-500/10"]');
await expect(pageErrorBanner).not.toBeVisible();
// Typing should clear the error
await nameInput.fill("valid-name");
await expect(inlineError).not.toBeVisible();
// A valid name should succeed without errors
await createKeyButton.click({ force: true });
await expect.poll(() => state.keys.length).toBe(1);
});
test("validation error appears inside the permissions modal when renaming, not behind the backdrop", async ({
page,
}) => {
const state: {
keys: ApiKeyRecord[];
nextId: number;
} = {
keys: [],
nextId: 1,
};
// Stub all API routes
await page.route("**/v1/models", async (route) => {
await fulfillJson(route, { data: [] });
});
await page.route("**/api/settings", async (route) => {
await fulfillJson(route, {});
});
await page.route("**/api/providers", async (route) => {
await fulfillJson(route, {
connections: [
{ id: "conn-openai", name: "OpenAI Main", provider: "openai", isActive: true },
],
});
});
await page.route(/\/api\/usage\/call-logs(?:\?.*)?$/, async (route) => {
await fulfillJson(route, []);
});
await page.route("**/api/sessions", async (route) => {
await fulfillJson(route, { byApiKey: {} });
});
await page.route(/\/api\/keys\/[^/]+$/, async (route) => {
if (route.request().method() === "PATCH") {
const keyId = route.request().url().split("/").pop() || "";
const payload = (await route.request().postDataJSON()) as { name?: string };
const record = state.keys.find((key) => key.id === keyId);
if (!record) {
await fulfillJson(route, { error: "Key not found" }, 404);
return;
}
if (payload.name) {
record.name = payload.name;
}
await fulfillJson(route, { message: "API key settings updated successfully", ...payload });
return;
}
await fulfillJson(route, { error: "Method not allowed" }, 405);
});
await page.route("**/api/keys", async (route) => {
const method = route.request().method();
if (method === "GET") {
await fulfillJson(route, {
keys: state.keys.map(({ fullKey, ...record }) => record),
allowKeyReveal: true,
});
return;
}
if (method === "POST") {
const payload = (route.request().postDataJSON() as { name?: string }) || {};
const id = `key-${state.nextId++}`;
const suffix = String(1000 + state.nextId);
const fullKey = `sk-live-${suffix}-demo-secret`;
const maskedKey = `sk-live-****${suffix}`;
state.keys.push({
id,
name: payload.name || "New Key",
key: maskedKey,
fullKey,
allowedModels: null,
allowedConnections: null,
createdAt: new Date("2026-04-05T20:00:00.000Z").toISOString(),
});
await fulfillJson(route, { key: fullKey, id });
return;
}
await fulfillJson(route, { error: "Method not allowed" }, 405);
});
await gotoDashboardRoute(page, "/dashboard/api-manager", {
timeoutMs: NAVIGATION_TIMEOUT_MS,
});
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
// Create a key first
const createFirstKeyButton = page.getByRole("button", {
name: /create (your )?first key/i,
});
await expect(createFirstKeyButton).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await createFirstKeyButton.click();
const createDialog = page.getByRole("dialog", { name: /create api key/i });
await expect(createDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await createDialog.locator("input").first().fill("Original Name");
await createDialog.getByRole("button", { name: /create api key/i }).click({ force: true });
// Dismiss the created dialog
const createdDialog = page.getByRole("dialog", { name: /api key created/i });
await createdDialog.getByRole("button", { name: /done/i }).click();
await waitForPageToSettle(page);
await waitForNextDevCompileToFinish(page);
await expect(page.getByText("Original Name")).toBeVisible({
timeout: UI_STABILITY_TIMEOUT_MS,
});
// Open the permissions modal
const keyRow = page
.locator("div")
.filter({ has: page.getByText("Original Name", { exact: true }) })
.first();
await keyRow.locator('button[title="Edit permissions"]').click({ force: true });
const permissionsDialog = page.getByRole("dialog", {
name: /permissions: original name/i,
});
await expect(permissionsDialog).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
// --- Try to save with an invalid name (empty) ---
const nameInput = permissionsDialog.locator("input").first();
await nameInput.clear();
await nameInput.fill(" ");
const saveButton = permissionsDialog.getByRole("button", { name: /save permissions/i });
await saveButton.click({ force: true });
// Inline error should appear inside the permissions modal
const inlineError = permissionsDialog.locator('[id$="-error"]');
await expect(inlineError).toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
// No page-level error banner should appear behind the modal
const pageErrorBanner = page.locator('.flex.flex-col.gap-8 > [class~="bg-red-500/10"]');
await expect(pageErrorBanner).not.toBeVisible();
// Typing a valid name should clear the error
await nameInput.fill("Renamed Key");
await expect(inlineError).not.toBeVisible();
// Save should succeed now
await saveButton.click({ force: true });
await expect.poll(() => state.keys[0]?.name).toBe("Renamed Key");
await expect(permissionsDialog).not.toBeVisible({ timeout: UI_STABILITY_TIMEOUT_MS });
await expect(page.getByText("Renamed Key")).toBeVisible();
});
});
|