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

test(playground): UI coverage for advanced tabs + modals

diegosouzapw9c475f0a25cf
diff --git a/tests/unit/ui/playground-build-tab.test.tsx b/tests/unit/ui/playground-build-tab.test.tsx
new file mode 100644
index 0000000000..9e170546e8
--- /dev/null
+++ b/tests/unit/ui/playground-build-tab.test.tsx
@@ -0,0 +1,221 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("remark-gfm", () => ({ default: () => {} }));
+vi.mock("react-markdown", () => ({
+ default: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="markdown-content">{children}</div>
+ ),
+}));
+
+function setInputValue(
+ el: HTMLTextAreaElement | HTMLInputElement,
+ value: string,
+): void {
+ const nativeSetter =
+ el instanceof HTMLTextAreaElement
+ ? Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")?.set
+ : Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
+ nativeSetter?.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
+const { DEFAULT_PARAMS } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ParamSliders"
+);
+const { default: BuildTab } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/tabs/BuildTab"
+);
+
+const BASE_CONFIG = {
+ endpoint: "chat.completions" as const,
+ baseUrl: "http://localhost:20128",
+ model: "openai/gpt-4o",
+ systemPrompt: "You are helpful.",
+ params: { ...DEFAULT_PARAMS },
+};
+
+if (typeof Element.prototype.scrollIntoView === "undefined") {
+ Object.defineProperty(Element.prototype, "scrollIntoView", {
+ value: () => {},
+ writable: true,
+ configurable: true,
+ });
+}
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderBuildTab(config = BASE_CONFIG): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(<BuildTab configState={config} />);
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ vi.restoreAllMocks();
+});
+
+describe("BuildTab", () => {
+ it("renders Run button", () => {
+ const el = renderBuildTab();
+ const runBtn = el.querySelector("[class*='bg-primary']");
+ expect(runBtn?.textContent).toContain("Run");
+ });
+
+ it("renders Function calling section", () => {
+ const el = renderBuildTab();
+ expect(el.textContent).toContain("Function calling");
+ expect(el.textContent).toContain("Add tool");
+ });
+
+ it("renders Structured output section", () => {
+ const el = renderBuildTab();
+ expect(el.textContent).toContain("Structured output");
+ expect(el.textContent).toContain("JSON mode");
+ });
+
+ it("adds a tool and shows it in function calling UI", async () => {
+ const el = renderBuildTab();
+
+ // Find add tool form inputs in the right panel
+ const allInputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ // The first or second input should be the function name
+ const nameInput = allInputs[0];
+ act(() => setInputValue(nameInput, "search_web"));
+
+ const addBtns = el.querySelectorAll("button");
+ const addToolBtn = Array.from(addBtns).find(
+ (b) => b.textContent?.trim() === "+ Add tool",
+ ) as HTMLButtonElement;
+ expect(addToolBtn).not.toBeNull();
+
+ await act(async () => { addToolBtn.click(); });
+
+ expect(el.textContent).toContain("search_web");
+ expect(el.textContent).toContain("Tools (1)");
+ });
+
+ it("shows validation error for invalid JSON in tool params", async () => {
+ const el = renderBuildTab();
+
+ const allInputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ act(() => setInputValue(allInputs[0], "bad_tool"));
+
+ // The parameters textarea is in the Add tool form section — it has default valid JSON.
+ // We need to find the textarea labeled "JSON schema for parameters" in the add form.
+ const paramsTextareas = Array.from(el.querySelectorAll("textarea")).filter(
+ (t) => t.getAttribute("aria-label") === "JSON schema for parameters",
+ );
+ // The last one is in the Add tool form (the first may be the message prompt textarea)
+ const paramsTextarea = paramsTextareas[paramsTextareas.length - 1] as HTMLTextAreaElement;
+ act(() => setInputValue(paramsTextarea, "NOT JSON {{{"));
+
+ const addBtns = el.querySelectorAll("button");
+ const addToolBtn = Array.from(addBtns).find(
+ (b) => b.textContent?.trim() === "+ Add tool",
+ ) as HTMLButtonElement;
+
+ await act(async () => { addToolBtn.click(); });
+
+ expect(el.textContent).toContain("valid JSON");
+ });
+
+ it("enables JSON mode toggle and shows schema editor", async () => {
+ const el = renderBuildTab();
+
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+ expect(toggle).not.toBeNull();
+
+ await act(async () => { toggle.click(); });
+
+ // JSON mode should be enabled
+ expect(toggle.getAttribute("aria-checked")).toBe("true");
+ expect(el.textContent).toContain("JSON schema");
+ });
+
+ it("shows tool badge in toolbar when tools are added", async () => {
+ const el = renderBuildTab();
+
+ const allInputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ act(() => setInputValue(allInputs[0], "my_tool"));
+
+ const addBtns = el.querySelectorAll("button");
+ const addToolBtn = Array.from(addBtns).find(
+ (b) => b.textContent?.trim() === "+ Add tool",
+ ) as HTMLButtonElement;
+ await act(async () => { addToolBtn.click(); });
+
+ // Badge "1 tool" should appear in toolbar
+ expect(el.textContent).toContain("1 tool");
+ });
+
+ it("calls /v1/chat/completions with tools array when Run is clicked", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() =>
+ Promise.resolve(
+ new Response(
+ JSON.stringify({
+ choices: [{ message: { content: "Result", role: "assistant" } }],
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ ),
+ ) as typeof fetch,
+ );
+
+ const el = renderBuildTab();
+
+ // Add a tool
+ const allInputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ act(() => setInputValue(allInputs[0], "tool_one"));
+ const addBtns = el.querySelectorAll("button");
+ const addToolBtn = Array.from(addBtns).find(
+ (b) => b.textContent?.trim() === "+ Add tool",
+ ) as HTMLButtonElement;
+ await act(async () => { addToolBtn.click(); });
+
+ // Type a prompt
+ const promptTextarea = el.querySelector("textarea[placeholder*='message']") as HTMLTextAreaElement;
+ act(() => setInputValue(promptTextarea, "Run this tool"));
+
+ // Click Run
+ const runBtns = el.querySelectorAll("button");
+ const runBtn = Array.from(runBtns).find(
+ (b) => b.textContent?.includes("Run") && !b.textContent?.includes("Clear"),
+ ) as HTMLButtonElement;
+ await act(async () => { runBtn.click(); });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // fetch should be called
+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
+ const [, opts] = (vi.mocked(fetch) as ReturnType<typeof vi.fn>).mock.calls[0] as [string, RequestInit];
+ const body = JSON.parse(opts.body as string) as Record<string, unknown>;
+ expect(body["tools"]).toBeDefined();
+ expect(Array.isArray(body["tools"])).toBe(true);
+ });
+
+ it("shows JSON mode badge in toolbar when JSON mode is enabled", async () => {
+ const el = renderBuildTab();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+ await act(async () => { toggle.click(); });
+ expect(el.textContent).toContain("JSON mode");
+ });
+});
diff --git a/tests/unit/ui/playground-compare-column.test.tsx b/tests/unit/ui/playground-compare-column.test.tsx
new file mode 100644
index 0000000000..894926c1ca
--- /dev/null
+++ b/tests/unit/ui/playground-compare-column.test.tsx
@@ -0,0 +1,158 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { vi } from "vitest";
+
+vi.mock("remark-gfm", () => ({ default: () => {} }));
+vi.mock("react-markdown", () => ({
+ default: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="markdown-content">{children}</div>
+ ),
+}));
+
+const { default: CompareColumn } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/CompareColumn"
+);
+
+type ColumnStatus = "idle" | "streaming" | "done" | "error";
+
+const BASE_METRICS = {
+ ttftMs: null,
+ totalMs: null,
+ tokensIn: 0,
+ tokensOut: 0,
+ tps: null,
+ costUsd: null,
+};
+
+function makeColumn(overrides: Partial<{
+ id: string;
+ model: string;
+ status: ColumnStatus;
+ metrics: typeof BASE_METRICS;
+ response: string;
+ errorMessage: string;
+}> = {}) {
+ return {
+ id: "col-1",
+ model: "openai/gpt-4o",
+ status: "idle" as ColumnStatus,
+ metrics: { ...BASE_METRICS },
+ response: "",
+ ...overrides,
+ };
+}
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderColumn(
+ column: ReturnType<typeof makeColumn>,
+ onCancel = vi.fn(),
+ onRemove = vi.fn(),
+): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(
+ <CompareColumn column={column} onCancel={onCancel} onRemove={onRemove} />,
+ );
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+beforeEach(() => {
+ if (typeof Element.prototype.scrollIntoView === "undefined") {
+ Object.defineProperty(Element.prototype, "scrollIntoView", {
+ value: () => {},
+ writable: true,
+ configurable: true,
+ });
+ }
+});
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+});
+
+describe("CompareColumn", () => {
+ it("renders model name in header", () => {
+ const el = renderColumn(makeColumn({ model: "anthropic/claude-3-opus" }));
+ expect(el.textContent).toContain("anthropic/claude-3-opus");
+ });
+
+ it("shows idle state with ready message", () => {
+ const el = renderColumn(makeColumn({ status: "idle" }));
+ expect(el.textContent).toContain("Ready to run");
+ });
+
+ it("shows streaming skeleton when status=streaming and response empty", () => {
+ const el = renderColumn(makeColumn({ status: "streaming", response: "" }));
+ expect(el.textContent).toContain("Waiting for response");
+ });
+
+ it("renders markdown response when streaming and response is non-empty", () => {
+ const el = renderColumn(
+ makeColumn({ status: "streaming", response: "Hello from model" }),
+ );
+ const markdown = el.querySelector("[data-testid='markdown-content']");
+ expect(markdown).not.toBeNull();
+ expect(markdown?.textContent).toContain("Hello from model");
+ });
+
+ it("shows error message when status=error", () => {
+ const el = renderColumn(
+ makeColumn({ status: "error", errorMessage: "Rate limit exceeded" }),
+ );
+ expect(el.textContent).toContain("Rate limit exceeded");
+ });
+
+ it("shows ProviderMetrics bar when streaming or done", () => {
+ const metrics = {
+ ttftMs: 234,
+ totalMs: 1200,
+ tokensIn: 142,
+ tokensOut: 38,
+ tps: 31.6,
+ costUsd: 0.002,
+ };
+ const el = renderColumn(makeColumn({ status: "done", metrics, response: "Done." }));
+ // Should show estimated
+ expect(el.textContent).toContain("estimated");
+ // Should show TTFT
+ expect(el.textContent).toContain("TTFT");
+ });
+
+ it("calls onCancel when cancel button clicked during streaming", () => {
+ const onCancel = vi.fn();
+ const el = renderColumn(makeColumn({ status: "streaming" }), onCancel);
+ const cancelBtn = el.querySelector("[aria-label='Cancel stream']") as HTMLButtonElement;
+ expect(cancelBtn).not.toBeNull();
+ act(() => cancelBtn.click());
+ expect(onCancel).toHaveBeenCalledWith("col-1");
+ });
+
+ it("calls onRemove when remove button clicked", () => {
+ const onRemove = vi.fn();
+ const el = renderColumn(makeColumn(), vi.fn(), onRemove);
+ const removeBtn = el.querySelector("[aria-label='Remove column for openai/gpt-4o']") as HTMLButtonElement;
+ expect(removeBtn).not.toBeNull();
+ act(() => removeBtn.click());
+ expect(onRemove).toHaveBeenCalledWith("col-1");
+ });
+
+ it("updates metrics displayed when metrics change (TTFT after first chunk)", () => {
+ const metricsWithTtft = { ...BASE_METRICS, ttftMs: 187 };
+ const el = renderColumn(
+ makeColumn({ status: "streaming", metrics: metricsWithTtft, response: "Hi" }),
+ );
+ expect(el.textContent).toContain("187ms");
+ });
+});
diff --git a/tests/unit/ui/playground-compare-tab.test.tsx b/tests/unit/ui/playground-compare-tab.test.tsx
new file mode 100644
index 0000000000..bbb12ebe53
--- /dev/null
+++ b/tests/unit/ui/playground-compare-tab.test.tsx
@@ -0,0 +1,261 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+vi.mock("remark-gfm", () => ({ default: () => {} }));
+vi.mock("react-markdown", () => ({
+ default: ({ children }: { children: React.ReactNode }) => (
+ <div data-testid="markdown-content">{children}</div>
+ ),
+}));
+
+// crypto.randomUUID polyfill for jsdom
+let _uuidCounter = 0;
+if (typeof crypto === "undefined" || !crypto.randomUUID) {
+ Object.defineProperty(globalThis, "crypto", {
+ value: {
+ randomUUID: () => `test-uuid-${++_uuidCounter}`,
+ },
+ configurable: true,
+ });
+} else {
+ vi.spyOn(crypto, "randomUUID").mockImplementation(() => `test-uuid-${++_uuidCounter}` as `${string}-${string}-${string}-${string}-${string}`);
+}
+
+// Mock AbortController to track abort calls — use real AbortController but spy on abort()
+const abortCallTracker = { calls: 0 };
+const OriginalAbortController = globalThis.AbortController;
+class MockAbortController extends OriginalAbortController {
+ abort() {
+ abortCallTracker.calls++;
+ super.abort();
+ }
+}
+vi.stubGlobal("AbortController", MockAbortController);
+
+const { DEFAULT_PARAMS } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ParamSliders"
+);
+const { default: CompareTab } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/tabs/CompareTab"
+);
+
+const BASE_CONFIG = {
+ endpoint: "chat.completions" as const,
+ baseUrl: "http://localhost:20128",
+ model: "openai/gpt-4o",
+ systemPrompt: "You are helpful.",
+ params: { ...DEFAULT_PARAMS },
+};
+
+function buildSseResponse(content: string) {
+ const encoder = new TextEncoder();
+ const chunks = [
+ `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n\n`,
+ "data: [DONE]\n\n",
+ ];
+ let idx = 0;
+ return new Response(
+ new ReadableStream({
+ pull(controller) {
+ if (idx < chunks.length) {
+ controller.enqueue(encoder.encode(chunks[idx++]));
+ } else {
+ controller.close();
+ }
+ },
+ }),
+ { status: 200, headers: { "content-type": "text/event-stream" } },
+ );
+}
+
+if (typeof Element.prototype.scrollIntoView === "undefined") {
+ Object.defineProperty(Element.prototype, "scrollIntoView", {
+ value: () => {},
+ writable: true,
+ configurable: true,
+ });
+}
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderCompareTab(config = BASE_CONFIG): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(<CompareTab configState={config} />);
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+function setInputValue(el: HTMLInputElement, value: string) {
+ const nativeSetter = Object.getOwnPropertyDescriptor(
+ window.HTMLInputElement.prototype,
+ "value",
+ )?.set;
+ nativeSetter?.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ _uuidCounter = 0;
+ abortCallTracker.calls = 0;
+ vi.restoreAllMocks();
+});
+
+describe("CompareTab", () => {
+ it("renders initial column with model from configState", () => {
+ const el = renderCompareTab();
+ expect(el.textContent).toContain("openai/gpt-4o");
+ });
+
+ it("shows Run all button initially", () => {
+ const el = renderCompareTab();
+ const btn = el.querySelector("[aria-label='Run all columns']");
+ expect(btn).not.toBeNull();
+ });
+
+ it("shows Add model button", () => {
+ const el = renderCompareTab();
+ const btn = el.querySelector("[aria-label='Add model column']");
+ expect(btn).not.toBeNull();
+ });
+
+ it("adds a second column when Add model is clicked", async () => {
+ const el = renderCompareTab();
+
+ const input = el.querySelector("[aria-label='Model name for new column']") as HTMLInputElement;
+ const addBtn = el.querySelector("[aria-label='Add model column']") as HTMLButtonElement;
+
+ act(() => {
+ setInputValue(input, "anthropic/claude-3");
+ });
+
+ await act(async () => {
+ addBtn.click();
+ });
+
+ // Should show 2/4 columns
+ expect(el.textContent).toContain("2/4 columns");
+ expect(el.textContent).toContain("anthropic/claude-3");
+ });
+
+ it("disables Add model button after 4 columns", async () => {
+ const el = renderCompareTab();
+
+ const input = el.querySelector("[aria-label='Model name for new column']") as HTMLInputElement;
+ const addBtn = el.querySelector("[aria-label='Add model column']") as HTMLButtonElement;
+
+ // Add 3 more columns (already have 1)
+ for (let i = 0; i < 3; i++) {
+ act(() => setInputValue(input, `model-${i}`));
+ await act(async () => { addBtn.click(); });
+ }
+
+ // Now at 4/4
+ expect(el.textContent).toContain("4/4 columns");
+
+ // Button should be disabled
+ const disabledAddBtn = el.querySelector("[aria-label='Add model column']") as HTMLButtonElement;
+ expect(disabledAddBtn.disabled).toBe(true);
+ });
+
+ it("removes a column when remove button is clicked", async () => {
+ const el = renderCompareTab();
+
+ const input = el.querySelector("[aria-label='Model name for new column']") as HTMLInputElement;
+ const addBtn = el.querySelector("[aria-label='Add model column']") as HTMLButtonElement;
+
+ // Add a second column
+ act(() => setInputValue(input, "to-remove"));
+ await act(async () => { addBtn.click(); });
+ expect(el.textContent).toContain("2/4 columns");
+
+ // Remove the second column
+ const removeBtn = el.querySelector("[aria-label='Remove column for to-remove']") as HTMLButtonElement;
+ expect(removeBtn).not.toBeNull();
+ await act(async () => { removeBtn.click(); });
+
+ expect(el.textContent).toContain("1/4 columns");
+ expect(el.textContent).not.toContain("to-remove");
+ });
+
+ it("runs all streams in parallel when Run all is clicked", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => Promise.resolve(buildSseResponse("Hello"))) as typeof fetch,
+ );
+
+ const el = renderCompareTab();
+
+ // Add a second column
+ const input = el.querySelector("[aria-label='Model name for new column']") as HTMLInputElement;
+ const addBtn = el.querySelector("[aria-label='Add model column']") as HTMLButtonElement;
+ act(() => setInputValue(input, "model-2"));
+ await act(async () => { addBtn.click(); });
+
+ const runBtn = el.querySelector("[aria-label='Run all columns']") as HTMLButtonElement;
+ await act(async () => { runBtn.click(); });
+
+ // fetch should have been called twice (once per column)
+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(2);
+ });
+
+ it("shows Cancel all when streams are running", async () => {
+ // Make fetch hang until aborted
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => new Promise<Response>(() => {})) as typeof fetch,
+ );
+
+ const el = renderCompareTab();
+ const runBtn = el.querySelector("[aria-label='Run all columns']") as HTMLButtonElement;
+
+ act(() => { runBtn.click(); });
+
+ // Need to flush promises to get to streaming state
+ await act(async () => {
+ await Promise.resolve();
+ });
+
+ const cancelBtn = el.querySelector("[aria-label='Cancel all streams']");
+ expect(cancelBtn).not.toBeNull();
+ });
+
+ it("cancel all calls abort on all controllers", async () => {
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => new Promise<Response>(() => {})) as typeof fetch,
+ );
+
+ const el = renderCompareTab();
+
+ // Add a second column
+ const input = el.querySelector("[aria-label='Model name for new column']") as HTMLInputElement;
+ const addBtn = el.querySelector("[aria-label='Add model column']") as HTMLButtonElement;
+ act(() => setInputValue(input, "model-2"));
+ await act(async () => { addBtn.click(); });
+
+ const runBtn = el.querySelector("[aria-label='Run all columns']") as HTMLButtonElement;
+ act(() => { runBtn.click(); });
+
+ await act(async () => { await Promise.resolve(); });
+
+ const cancelBtn = el.querySelector("[aria-label='Cancel all streams']") as HTMLButtonElement | null;
+ if (cancelBtn) {
+ act(() => { cancelBtn.click(); });
+ // AbortController.abort should have been called
+ expect(abortCallTracker.calls).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/tests/unit/ui/playground-export-modal.test.tsx b/tests/unit/ui/playground-export-modal.test.tsx
new file mode 100644
index 0000000000..1f7f5df880
--- /dev/null
+++ b/tests/unit/ui/playground-export-modal.test.tsx
@@ -0,0 +1,151 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { API_KEY_PLACEHOLDER } from "../../../src/lib/playground/codeExport";
+
+const { default: ExportCodeModal } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ExportCodeModal"
+);
+
+const BASE_STATE = {
+ endpoint: "chat.completions" as const,
+ baseUrl: "http://localhost:20128",
+ model: "openai/gpt-4o",
+ systemPrompt: "You are helpful.",
+ messages: [{ role: "user" as const, content: "Hello" }],
+ stream: true,
+};
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderModal(state = BASE_STATE, onClose = vi.fn()): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(<ExportCodeModal state={state} onClose={onClose} />);
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ vi.restoreAllMocks();
+});
+
+describe("ExportCodeModal", () => {
+ it("renders 3 language tabs: curl, Python, TypeScript", () => {
+ const el = renderModal();
+ const tabs = el.querySelectorAll("[role='tab']");
+ const labels = Array.from(tabs).map((t) => t.textContent?.trim());
+ expect(labels).toContain("curl");
+ expect(labels).toContain("Python");
+ expect(labels).toContain("TypeScript");
+ });
+
+ it("shows Export code title", () => {
+ const el = renderModal();
+ expect(el.textContent).toContain("Export code");
+ });
+
+ it("shows curl code with $OMNIROUTE_API_KEY placeholder", () => {
+ const el = renderModal();
+ const pre = el.querySelector("pre");
+ expect(pre?.textContent).toContain(API_KEY_PLACEHOLDER);
+ expect(pre?.textContent).toContain("$OMNIROUTE_API_KEY");
+ });
+
+ it("never contains a real API key pattern (sk-...) in any tab", async () => {
+ const el = renderModal();
+ const tabs = el.querySelectorAll("[role='tab']") as NodeListOf<HTMLButtonElement>;
+
+ for (const tab of Array.from(tabs)) {
+ await act(async () => { tab.click(); });
+ const pre = el.querySelector("pre");
+ const code = pre?.textContent ?? "";
+ // Real key regex — must not match
+ expect(code).not.toMatch(/sk-[A-Za-z0-9_-]{16,}/);
+ }
+ });
+
+ it("Copy button calls navigator.clipboard.writeText with code containing API_KEY_PLACEHOLDER", async () => {
+ const writeTextMock = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, "clipboard", {
+ value: { writeText: writeTextMock },
+ writable: true,
+ configurable: true,
+ });
+
+ const el = renderModal();
+ const copyBtn = el.querySelector("[aria-label='Copy curl code']") as HTMLButtonElement;
+ expect(copyBtn).not.toBeNull();
+
+ await act(async () => { copyBtn.click(); });
+
+ expect(writeTextMock).toHaveBeenCalledTimes(1);
+ const copiedText = writeTextMock.mock.calls[0][0] as string;
+ expect(copiedText).toContain(API_KEY_PLACEHOLDER);
+ // Must NOT contain a real key pattern
+ expect(copiedText).not.toMatch(/sk-[A-Za-z0-9_-]{16,}/);
+ });
+
+ it("switching tab to Python shows different code snippet", async () => {
+ const el = renderModal();
+
+ // Get initial curl code
+ const initialPre = el.querySelector("pre");
+ const curlCode = initialPre?.textContent ?? "";
+
+ // Click Python tab
+ const tabs = el.querySelectorAll("[role='tab']") as NodeListOf<HTMLButtonElement>;
+ const pythonTab = Array.from(tabs).find((t) => t.textContent?.trim() === "Python");
+ expect(pythonTab).not.toBeNull();
+
+ await act(async () => { pythonTab!.click(); });
+
+ const newPre = el.querySelector("pre");
+ const pythonCode = newPre?.textContent ?? "";
+
+ // Python code should differ from curl
+ expect(pythonCode).not.toBe(curlCode);
+ // Python code should also have the placeholder
+ expect(pythonCode).toContain(API_KEY_PLACEHOLDER);
+ });
+
+ it("switching tab to TypeScript shows TS-specific code", async () => {
+ const el = renderModal();
+
+ const tabs = el.querySelectorAll("[role='tab']") as NodeListOf<HTMLButtonElement>;
+ const tsTab = Array.from(tabs).find((t) => t.textContent?.trim() === "TypeScript");
+ await act(async () => { tsTab!.click(); });
+
+ const pre = el.querySelector("pre");
+ const code = pre?.textContent ?? "";
+ // TypeScript code should contain OMNIROUTE_API_KEY
+ expect(code).toContain(API_KEY_PLACEHOLDER);
+ expect(code).not.toMatch(/sk-[A-Za-z0-9_-]{16,}/);
+ });
+
+ it("calls onClose when backdrop is clicked", () => {
+ const onClose = vi.fn();
+ const el = renderModal(BASE_STATE, onClose);
+ const backdrop = el.querySelector("[role='dialog']") as HTMLDivElement;
+ act(() => backdrop.click());
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+
+ it("calls onClose when Close button is clicked", () => {
+ const onClose = vi.fn();
+ const el = renderModal(BASE_STATE, onClose);
+ const closeBtn = el.querySelector("[aria-label='Close export modal']") as HTMLButtonElement;
+ act(() => closeBtn.click());
+ expect(onClose).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/tests/unit/ui/playground-improve-prompt-button.test.tsx b/tests/unit/ui/playground-improve-prompt-button.test.tsx
new file mode 100644
index 0000000000..f86793dbb4
--- /dev/null
+++ b/tests/unit/ui/playground-improve-prompt-button.test.tsx
@@ -0,0 +1,163 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const { DEFAULT_PARAMS } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ParamSliders"
+);
+const { default: ImprovePromptButton } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ImprovePromptButton"
+);
+
+const BASE_CONFIG = {
+ endpoint: "chat.completions" as const,
+ baseUrl: "http://localhost:20128",
+ model: "openai/gpt-4o",
+ systemPrompt: "You are helpful.",
+ params: { ...DEFAULT_PARAMS },
+};
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderButton(config = BASE_CONFIG, setConfig = vi.fn()): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(
+ <ImprovePromptButton configState={config} setConfigState={setConfig} />,
+ );
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ vi.restoreAllMocks();
+});
+
+describe("ImprovePromptButton", () => {
+ it("renders the Improve prompt button", () => {
+ const el = renderButton();
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']");
+ expect(btn).not.toBeNull();
+ expect(btn?.textContent).toContain("Improve prompt");
+ });
+
+ it("button is disabled when model is empty", () => {
+ const config = { ...BASE_CONFIG, model: "" };
+ const el = renderButton(config);
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+ expect(btn.disabled).toBe(true);
+ });
+
+ it("button is enabled when model is set", () => {
+ const el = renderButton();
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+ expect(btn.disabled).toBe(false);
+ });
+
+ it("shows confirmation modal when button is clicked", async () => {
+ const el = renderButton();
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+
+ await act(async () => { btn.click(); });
+
+ const modal = el.querySelector("[role='dialog']");
+ expect(modal).not.toBeNull();
+ expect(modal?.textContent).toContain("Improve prompt");
+ });
+
+ it("confirmation modal shows quota warning message", async () => {
+ const el = renderButton();
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+
+ await act(async () => { btn.click(); });
+
+ const modal = el.querySelector("[role='dialog']");
+ expect(modal?.textContent).toContain("quota");
+ });
+
+ it("confirmation modal shows the configured model name", async () => {
+ const el = renderButton();
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+
+ await act(async () => { btn.click(); });
+
+ const modal = el.querySelector("[role='dialog']");
+ expect(modal?.textContent).toContain("openai/gpt-4o");
+ });
+
+ it("cancels modal without calling API when Cancel is clicked", async () => {
+ vi.stubGlobal("fetch", vi.fn());
+ const el = renderButton();
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+
+ await act(async () => { btn.click(); });
+
+ const cancelBtn = el.querySelector("[role='dialog'] button:first-child") as HTMLButtonElement;
+ await act(async () => { cancelBtn.click(); });
+
+ // Modal should close
+ expect(el.querySelector("[role='dialog']")).toBeNull();
+ expect(vi.mocked(fetch)).not.toHaveBeenCalled();
+ });
+
+ it("calls useImprovePrompt.improve (POST /api/playground/improve-prompt) on confirm", async () => {
+ const mockResponse = {
+ improvedSystem: "You are a highly specialized assistant.",
+ tokensIn: 50,
+ tokensOut: 30,
+ };
+
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() =>
+ Promise.resolve(
+ new Response(JSON.stringify(mockResponse), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ ),
+ ) as typeof fetch,
+ );
+
+ const setConfig = vi.fn();
+ const el = renderButton(BASE_CONFIG, setConfig);
+
+ const btn = el.querySelector("[aria-label='Improve prompt using AI']") as HTMLButtonElement;
+ await act(async () => { btn.click(); });
+
+ // Click confirm (Improve button)
+ const modal = el.querySelector("[role='dialog']");
+ const allBtns = modal?.querySelectorAll("button") ?? [];
+ const improveBtn = Array.from(allBtns).find(
+ (b) => b.textContent?.includes("Improve") && !b.textContent?.includes("Improve prompt"),
+ ) as HTMLButtonElement;
+ expect(improveBtn).not.toBeNull();
+
+ await act(async () => { improveBtn.click(); });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // fetch should have been called with POST to improve-prompt
+ expect(vi.mocked(fetch)).toHaveBeenCalledTimes(1);
+ const [url, opts] = (vi.mocked(fetch) as ReturnType<typeof vi.fn>).mock.calls[0] as [string, RequestInit];
+ expect(url).toContain("improve-prompt");
+ expect(opts.method).toBe("POST");
+
+ // setConfigState should have been called with improved system prompt
+ expect(setConfig).toHaveBeenCalledTimes(1);
+ const updatedConfig = setConfig.mock.calls[0][0] as typeof BASE_CONFIG;
+ expect(updatedConfig.systemPrompt).toBe("You are a highly specialized assistant.");
+ });
+});
diff --git a/tests/unit/ui/playground-preset-picker.test.tsx b/tests/unit/ui/playground-preset-picker.test.tsx
new file mode 100644
index 0000000000..073b537d78
--- /dev/null
+++ b/tests/unit/ui/playground-preset-picker.test.tsx
@@ -0,0 +1,206 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const { DEFAULT_PARAMS } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ParamSliders"
+);
+const { default: PresetPicker } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/PresetPicker"
+);
+
+function setInputValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {
+ const nativeSetter =
+ el instanceof HTMLTextAreaElement
+ ? Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")?.set
+ : Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
+ nativeSetter?.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
+const BASE_CONFIG = {
+ endpoint: "chat.completions" as const,
+ baseUrl: "http://localhost:20128",
+ model: "openai/gpt-4o",
+ systemPrompt: "You are helpful.",
+ params: { ...DEFAULT_PARAMS },
+};
+
+const MOCK_PRESETS = [
+ {
+ id: "preset-1",
+ name: "My preset",
+ endpoint: "chat.completions",
+ model: "anthropic/claude-3-opus",
+ system: "Act as an expert.",
+ params: { temperature: 0.5 },
+ created_at: new Date().toISOString(),
+ },
+];
+
+function buildFetchMock(presets = MOCK_PRESETS) {
+ return vi.fn((url: string, opts?: RequestInit) => {
+ const method = opts?.method ?? "GET";
+
+ if (typeof url === "string" && url.includes("/api/playground/presets") && method === "GET") {
+ return Promise.resolve(
+ new Response(JSON.stringify({ presets }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ }
+
+ if (typeof url === "string" && url.includes("/api/playground/presets") && method === "POST") {
+ const newPreset = {
+ id: "preset-new",
+ name: "New",
+ endpoint: "chat.completions",
+ model: "test",
+ system: null,
+ params: {},
+ created_at: new Date().toISOString(),
+ };
+ return Promise.resolve(
+ new Response(JSON.stringify(newPreset), {
+ status: 201,
+ headers: { "content-type": "application/json" },
+ }),
+ );
+ }
+
+ if (typeof url === "string" && url.includes("/presets/") && method === "DELETE") {
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }
+
+ return Promise.resolve(new Response(JSON.stringify({ presets: [] }), { status: 200 }));
+ }) as typeof fetch;
+}
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderPicker(
+ config = BASE_CONFIG,
+ setConfig = vi.fn(),
+): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(<PresetPicker configState={config} setConfigState={setConfig} />);
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ vi.restoreAllMocks();
+});
+
+describe("PresetPicker", () => {
+ it("renders Load preset dropdown and Save button", () => {
+ vi.stubGlobal("fetch", buildFetchMock([]));
+ const el = renderPicker();
+ expect(el.textContent).toContain("Presets");
+ const saveBtn = el.querySelector("[aria-label='Save current config as preset']");
+ expect(saveBtn).not.toBeNull();
+ });
+
+ it("shows preset names after fetch succeeds", async () => {
+ vi.stubGlobal("fetch", buildFetchMock(MOCK_PRESETS));
+ const el = renderPicker();
+
+ // Wait for fetch to resolve
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ expect(el.textContent).toContain("My preset");
+ });
+
+ it("loads a preset and calls setConfigState when a preset button is clicked", async () => {
+ vi.stubGlobal("fetch", buildFetchMock(MOCK_PRESETS));
+ const setConfig = vi.fn();
+ const el = renderPicker(BASE_CONFIG, setConfig);
+
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // Find and click the preset load button
+ const loadBtn = el.querySelector("[aria-label='Load preset \"My preset\"']") as HTMLButtonElement;
+ if (loadBtn) {
+ await act(async () => { loadBtn.click(); });
+ expect(setConfig).toHaveBeenCalledTimes(1);
+ const newConfig = setConfig.mock.calls[0][0] as typeof BASE_CONFIG;
+ expect(newConfig.model).toBe("anthropic/claude-3-opus");
+ }
+ });
+
+ it("opens save modal when Save button is clicked", async () => {
+ vi.stubGlobal("fetch", buildFetchMock([]));
+ const el = renderPicker();
+
+ const saveBtn = el.querySelector("[aria-label='Save current config as preset']") as HTMLButtonElement;
+ await act(async () => { saveBtn.click(); });
+
+ // Modal should appear
+ const modal = el.querySelector("[role='dialog']");
+ expect(modal).not.toBeNull();
+ expect(modal?.textContent).toContain("Save preset");
+ });
+
+ it("calls create hook (POST to /api/playground/presets) when saving", async () => {
+ const fetchMock = buildFetchMock([]);
+ vi.stubGlobal("fetch", fetchMock);
+ const el = renderPicker();
+
+ // Open modal
+ const saveBtn = el.querySelector("[aria-label='Save current config as preset']") as HTMLButtonElement;
+ await act(async () => { saveBtn.click(); });
+
+ // Enter name
+ const nameInput = el.querySelector("input[type='text']") as HTMLInputElement;
+ act(() => setInputValue(nameInput, "Test preset"));
+
+ // Submit
+ const submitBtn = el.querySelector("[role='dialog'] button:last-child") as HTMLButtonElement;
+ await act(async () => { submitBtn.click(); });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+
+ // POST should have been called
+ const calls = (fetchMock as ReturnType<typeof vi.fn>).mock.calls;
+ const postCall = calls.find((c: unknown[]) => {
+ const [, opts] = c as [string, RequestInit?];
+ return opts?.method === "POST";
+ });
+ expect(postCall).toBeDefined();
+ });
+
+ it("shows error when saving with empty name", async () => {
+ vi.stubGlobal("fetch", buildFetchMock([]));
+ const el = renderPicker();
+
+ const saveBtn = el.querySelector("[aria-label='Save current config as preset']") as HTMLButtonElement;
+ await act(async () => { saveBtn.click(); });
+
+ // Submit without entering a name
+ const submitBtn = el.querySelector("[role='dialog'] button:last-child") as HTMLButtonElement;
+ await act(async () => { submitBtn.click(); });
+
+ expect(el.textContent).toContain("Name is required");
+ });
+});
diff --git a/tests/unit/ui/playground-structured-output-editor.test.tsx b/tests/unit/ui/playground-structured-output-editor.test.tsx
new file mode 100644
index 0000000000..fb6d01a4ca
--- /dev/null
+++ b/tests/unit/ui/playground-structured-output-editor.test.tsx
@@ -0,0 +1,156 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const { useStructuredOutput } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/hooks/useStructuredOutput"
+);
+const { default: StructuredOutputEditor } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/StructuredOutputEditor"
+);
+
+function setInputValue(
+ el: HTMLTextAreaElement | HTMLInputElement,
+ value: string,
+): void {
+ const nativeSetter =
+ el instanceof HTMLTextAreaElement
+ ? Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")?.set
+ : Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
+ nativeSetter?.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
+function StructuredOutputEditorWrapper({ onReady }: {
+ onReady?: (so: ReturnType<typeof useStructuredOutput>) => void;
+}) {
+ const so = useStructuredOutput();
+ React.useEffect(() => { onReady?.(so); });
+ return <StructuredOutputEditor structuredOutput={so} />;
+}
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderEditor(onReady?: (so: ReturnType<typeof useStructuredOutput>) => void): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(<StructuredOutputEditorWrapper onReady={onReady} />);
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ vi.restoreAllMocks();
+});
+
+describe("StructuredOutputEditor", () => {
+ it("renders JSON mode toggle off by default", () => {
+ const el = renderEditor();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+ expect(toggle.getAttribute("aria-checked")).toBe("false");
+ });
+
+ it("shows schema editor when toggle is enabled", async () => {
+ const el = renderEditor();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+
+ await act(async () => { toggle.click(); });
+
+ // Should now show schema name field and textarea
+ const textareas = el.querySelectorAll("textarea");
+ expect(textareas.length).toBeGreaterThan(0);
+ expect(el.textContent).toContain("JSON schema");
+ });
+
+ it("hides schema editor when toggle is disabled", async () => {
+ const el = renderEditor();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+
+ // Enable
+ await act(async () => { toggle.click(); });
+ // Disable
+ await act(async () => { toggle.click(); });
+
+ // Should not show textarea
+ const textareas = el.querySelectorAll("textarea");
+ expect(textareas.length).toBe(0);
+ });
+
+ it("validates a valid JSON schema successfully", async () => {
+ const el = renderEditor();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+ await act(async () => { toggle.click(); });
+
+ // Set valid schema
+ const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
+ const validSchema = JSON.stringify({ type: "object", properties: { name: { type: "string" } }, required: ["name"] });
+ act(() => setInputValue(textarea, validSchema));
+
+ // Click Validate
+ const validateBtn = el.querySelector("button:last-child") as HTMLButtonElement;
+ // Find the validate button specifically
+ const allBtns = el.querySelectorAll("button");
+ const validateBtnActual = Array.from(allBtns).find(
+ (b) => b.textContent?.includes("Validate"),
+ ) as HTMLButtonElement;
+ expect(validateBtnActual).not.toBeNull();
+
+ await act(async () => { validateBtnActual.click(); });
+
+ // Should show validated status
+ expect(el.textContent).toContain("validated");
+ });
+
+ it("shows error for invalid JSON in schema textarea", async () => {
+ const el = renderEditor();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+ await act(async () => { toggle.click(); });
+
+ const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
+ act(() => setInputValue(textarea, "not valid json {{{"));
+
+ const allBtns = el.querySelectorAll("button");
+ const validateBtn = Array.from(allBtns).find(
+ (b) => b.textContent?.includes("Validate"),
+ ) as HTMLButtonElement;
+ await act(async () => { validateBtn.click(); });
+
+ expect(el.textContent).toContain("Invalid JSON");
+ });
+
+ it("shows Zod error when schema name is empty after validation", async () => {
+ const el = renderEditor();
+ const toggle = el.querySelector("[role='switch']") as HTMLButtonElement;
+ await act(async () => { toggle.click(); });
+
+ // Clear the name field
+ const inputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ act(() => setInputValue(inputs[0], "")); // empty name
+
+ // Set valid JSON
+ const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
+ act(() => setInputValue(textarea, JSON.stringify({ type: "object", properties: {} })));
+
+ const allBtns = el.querySelectorAll("button");
+ const validateBtn = Array.from(allBtns).find(
+ (b) => b.textContent?.includes("Validate"),
+ ) as HTMLButtonElement;
+ await act(async () => { validateBtn.click(); });
+
+ // Empty name should use fallback "my_schema" which is valid, so no error expected
+ // (the component uses nameField.trim() || "my_schema")
+ // So it should actually succeed
+ expect(el.textContent).toContain("validated");
+ });
+});
diff --git a/tests/unit/ui/playground-tools-builder.test.tsx b/tests/unit/ui/playground-tools-builder.test.tsx
new file mode 100644
index 0000000000..ad24c35cae
--- /dev/null
+++ b/tests/unit/ui/playground-tools-builder.test.tsx
@@ -0,0 +1,163 @@
+// @vitest-environment jsdom
+import React from "react";
+import { act } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const { useToolsBuilder } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/hooks/useToolsBuilder"
+);
+const { default: ToolsBuilder } = await import(
+ "../../../src/app/(dashboard)/dashboard/playground/components/ToolsBuilder"
+);
+
+if (typeof Element.prototype.scrollIntoView === "undefined") {
+ Object.defineProperty(Element.prototype, "scrollIntoView", {
+ value: () => {},
+ writable: true,
+ configurable: true,
+ });
+}
+
+function setInputValue(
+ el: HTMLTextAreaElement | HTMLInputElement,
+ value: string,
+): void {
+ const nativeSetter =
+ el instanceof HTMLTextAreaElement
+ ? Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value")?.set
+ : Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")?.set;
+ nativeSetter?.call(el, value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+ el.dispatchEvent(new Event("change", { bubbles: true }));
+}
+
+// Wrapper component to expose the useToolsBuilder hook
+function ToolsBuilderWrapper({ onReady }: { onReady?: (builder: ReturnType<typeof useToolsBuilder>) => void }) {
+ const builder = useToolsBuilder();
+ React.useEffect(() => {
+ onReady?.(builder);
+ });
+ return <ToolsBuilder toolsBuilder={builder} />;
+}
+
+const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
+
+function renderToolsBuilder(onReady?: (b: ReturnType<typeof useToolsBuilder>) => void): HTMLDivElement {
+ const el = document.createElement("div");
+ document.body.appendChild(el);
+ const root = createRoot(el);
+ act(() => {
+ root.render(<ToolsBuilderWrapper onReady={onReady} />);
+ });
+ containers.push({ root, el });
+ return el;
+}
+
+afterEach(() => {
+ for (const { root, el } of containers) {
+ act(() => root.unmount());
+ el.remove();
+ }
+ containers.length = 0;
+ vi.restoreAllMocks();
+});
+
+describe("ToolsBuilder", () => {
+ it("renders Add tool form by default", () => {
+ const el = renderToolsBuilder();
+ expect(el.textContent).toContain("Add tool");
+ });
+
+ it("shows error when name is empty and Add is clicked", async () => {
+ const el = renderToolsBuilder();
+
+ const addBtn = el.querySelector("button[class*='bg-primary']") as HTMLButtonElement;
+ expect(addBtn?.textContent?.trim()).toBe("+ Add tool");
+
+ await act(async () => { addBtn.click(); });
+
+ // Zod validation should show error
+ expect(el.textContent).toMatch(/String must contain at least 1 character|Too small|name|required/i);
+ });
+
+ it("adds a valid tool to the list", async () => {
+ const el = renderToolsBuilder();
+
+ // Fill out the form
+ const inputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ const nameInput = inputs[0]; // first input = function name
+ const descInput = inputs[1]; // second input = description
+
+ act(() => {
+ setInputValue(nameInput, "get_weather");
+ setInputValue(descInput, "Get current weather");
+ });
+
+ // Parameters textarea already has valid JSON by default
+ const addBtn = el.querySelector("button[class*='bg-primary']") as HTMLButtonElement;
+ await act(async () => { addBtn.click(); });
+
+ // Should show the tool in the list
+ expect(el.textContent).toContain("get_weather");
+ // Should show "1" in the Tools count
+ expect(el.textContent).toContain("Tools (1)");
+ });
+
+ it("shows Zod error for invalid JSON in parameters", async () => {
+ const el = renderToolsBuilder();
+
+ const nameInput = el.querySelector("input[type='text']") as HTMLInputElement;
+ act(() => setInputValue(nameInput, "my_func"));
+
+ // Find the parameters textarea and set invalid JSON
+ const textareas = el.querySelectorAll("textarea");
+ const paramsTextarea = textareas[0]; // parameters textarea
+ act(() => setInputValue(paramsTextarea, "not valid json"));
+
+ const addBtn = el.querySelector("button[class*='bg-primary']") as HTMLButtonElement;
+ await act(async () => { addBtn.click(); });
+
+ // Should show JSON parse error
+ expect(el.textContent).toContain("valid JSON");
+ });
+
+ it("removes a tool from the list", async () => {
+ const el = renderToolsBuilder();
+
+ // Add a tool first
+ const inputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ act(() => setInputValue(inputs[0], "to_remove"));
+ const addBtn = el.querySelector("button[class*='bg-primary']") as HTMLButtonElement;
+ await act(async () => { addBtn.click(); });
+
+ expect(el.textContent).toContain("to_remove");
+
+ // Click delete button
+ const deleteBtn = el.querySelector("[aria-label='Remove tool to_remove']") as HTMLButtonElement;
+ expect(deleteBtn).not.toBeNull();
+ await act(async () => { deleteBtn.click(); });
+
+ expect(el.textContent).not.toContain("to_remove");
+ expect(el.textContent).not.toContain("Tools (1)");
+ });
+
+ it("shows edit mode for an existing tool", async () => {
+ const el = renderToolsBuilder();
+
+ // Add a tool
+ const inputs = el.querySelectorAll("input[type='text']") as NodeListOf<HTMLInputElement>;
+ act(() => setInputValue(inputs[0], "edit_me"));
+ const addBtn = el.querySelector("button[class*='bg-primary']") as HTMLButtonElement;
+ await act(async () => { addBtn.click(); });
+
+ // Click edit button
+ const editBtn = el.querySelector("[aria-label='Edit tool edit_me']") as HTMLButtonElement;
+ expect(editBtn).not.toBeNull();
+ await act(async () => { editBtn.click(); });
+
+ // Should show Save/Cancel buttons
+ expect(el.textContent).toContain("Save");
+ expect(el.textContent).toContain("Cancel");
+ });
+});