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
// @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";
// ── Mocks ─────────────────────────────────────────────────────────────────────
// next-intl: no local mock — falls through to the real-EN-text default mock in
// tests/_setup/vitestUiPolyfills.ts. Every check below (button text "Send"/
// "Regenerate", "Start a conversation" empty state) already expects real production
// copy, which the previous `(key) => key` mock never rendered.
vi.mock("@/lib/playground/types", () => ({
getModelPricing: () => null,
}));
vi.mock("@/lib/playground/streamMetrics", () => ({
computeMetrics: (_args: unknown) => ({
ttftMs: 100,
totalMs: 500,
tokensIn: 10,
tokensOut: 20,
tps: 40,
costUsd: 0.001,
}),
}));
vi.mock("remark-gfm", () => ({ default: () => {} }));
vi.mock("react-markdown", () => ({
default: ({ children }: { children: React.ReactNode }) => (
<div data-testid="markdown-content">{children}</div>
),
}));
// ── Setup ──────────────────────────────────────────────────────────────────────
// jsdom does not implement scrollIntoView — mock it globally
if (typeof Element.prototype.scrollIntoView === "undefined") {
Object.defineProperty(Element.prototype, "scrollIntoView", {
value: () => {},
writable: true,
configurable: true,
});
}
// ── Helpers ────────────────────────────────────────────────────────────────────
/**
* Set value on a controlled React textarea/input and fire React synthetic events.
* React 19 requires using the native prototype setter + dispatching events.
*/
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: ChatTab } =
await import("../../../src/app/(dashboard)/dashboard/playground/components/tabs/ChatTab");
function makeConfig(
systemPrompt = "You are a helpful assistant.",
endpoint: "chat.completions" | "images" = "chat.completions"
) {
return {
endpoint,
baseUrl: "http://localhost:20128",
model: "openai/gpt-4o",
systemPrompt,
params: { ...DEFAULT_PARAMS },
};
}
function buildImageResultResponse(status: number, body: string): Response {
const payload = JSON.stringify({
status,
body,
headers: { "content-type": "application/json" },
});
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(
new TextEncoder().encode(
`: keepalive\n\nevent: playground.image.result\ndata: ${payload}\n\n`
)
);
controller.close();
},
}),
{ status: 200, headers: { "content-type": "text/event-stream" } }
);
}
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;
const stream = new ReadableStream({
pull(controller) {
if (idx < chunks.length) {
controller.enqueue(encoder.encode(chunks[idx++]));
} else {
controller.close();
}
},
});
return new Response(stream, {
status: 200,
headers: { "content-type": "text/event-stream" },
});
}
const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];
function renderChatTab(
config = makeConfig(),
onMetricsUpdate?: (m: unknown) => void
): HTMLDivElement {
const el = document.createElement("div");
document.body.appendChild(el);
const root = createRoot(el);
act(() => {
root.render(<ChatTab configState={config} onMetricsUpdate={onMetricsUpdate} />);
});
containers.push({ root, el });
return el;
}
async function waitFor(fn: () => boolean, timeout = 3000): Promise<void> {
const start = Date.now();
while (!fn()) {
if (Date.now() - start > timeout) throw new Error("waitFor timed out");
await new Promise((r) => setTimeout(r, 20));
}
}
// ── Tests ──────────────────────────────────────────────────────────────────────
describe("ChatTab", () => {
beforeEach(() => {
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
});
afterEach(() => {
for (const { root, el } of containers.splice(0)) {
act(() => root.unmount());
el.remove();
}
document.body.innerHTML = "";
vi.restoreAllMocks();
});
it("renders the chat input and send button", () => {
const el = renderChatTab();
const textarea = el.querySelector("textarea");
const sendBtn = el.querySelector("button");
expect(textarea).toBeTruthy();
expect(sendBtn).toBeTruthy();
});
it("shows empty state message when no messages", () => {
const el = renderChatTab();
expect(el.textContent).toContain("Start a conversation");
});
it("warns when no model is configured", () => {
const config = makeConfig();
config.model = "";
const el = renderChatTab(config);
expect(el.textContent).toContain("model");
});
it("sends message and renders assistant response with markdown", async () => {
const fetchSpy = vi
.spyOn(globalThis, "fetch")
.mockResolvedValue(buildSseResponse("Hello from assistant!"));
const el = renderChatTab();
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => {
setInputValue(textarea, "Hello!");
});
// Find and click send button
const sendBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Send")
) as HTMLButtonElement | undefined;
await act(async () => {
sendBtn?.click();
});
await waitFor(() => el.querySelector("[data-testid='markdown-content']") !== null);
const markdown = el.querySelector("[data-testid='markdown-content']");
expect(markdown).toBeTruthy();
fetchSpy.mockRestore();
});
it("opts image requests into the bounded stream and restores the JSON body", async () => {
let capturedHeaders: Record<string, string> | undefined;
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
capturedHeaders = init?.headers as Record<string, string>;
return buildImageResultResponse(
200,
JSON.stringify({ data: [{ url: "https://cdn.example.com/chat-image.png" }] })
);
});
const config = makeConfig("You are a helpful assistant.", "images");
config.model = "openai/gpt-image-2";
const el = renderChatTab(config);
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => setInputValue(textarea, "Draw a lighthouse"));
const sendBtn = Array.from(el.querySelectorAll("button")).find((button) =>
button.textContent?.includes("Send")
);
await act(async () => sendBtn?.click());
// #16006 renders image results inline as <img>, not as JSON text.
await waitFor(() => el.querySelector("img") !== null);
expect((el.querySelector("img") as HTMLImageElement).getAttribute("src")).toBe(
"https://cdn.example.com/chat-image.png"
);
expect(capturedHeaders?.["X-OmniRoute-Playground-Stream"]).toBe("1");
expect(el.textContent).not.toContain("playground.image.result");
fetchSpy.mockRestore();
});
it("uses the restored image status for existing error handling", async () => {
const fetchSpy = vi
.spyOn(globalThis, "fetch")
.mockResolvedValue(
buildImageResultResponse(
422,
JSON.stringify({ error: { message: "Image prompt was rejected" } })
)
);
const config = makeConfig("You are a helpful assistant.", "images");
config.model = "openai/gpt-image-2";
const el = renderChatTab(config);
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => setInputValue(textarea, "Rejected prompt"));
const sendBtn = Array.from(el.querySelectorAll("button")).find((button) =>
button.textContent?.includes("Send")
);
await act(async () => sendBtn?.click());
await waitFor(() => el.textContent?.includes("Image prompt was rejected") === true);
expect(el.textContent).toContain("Image prompt was rejected");
fetchSpy.mockRestore();
});
it("uses native Responses protocol for ChatGPT Web Codex models", async () => {
let capturedUrl = "";
let capturedInit: RequestInit | undefined;
const encoder = new TextEncoder();
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
capturedUrl = String(url);
capturedInit = init;
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ type: "response.output_text.delta", delta: "Native response" })}\n\n`
)
);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ type: "response.completed", response: { usage: { input_tokens: 2, output_tokens: 3 } } })}\n\n`
)
);
controller.close();
},
}),
{ status: 200, headers: { "content-type": "text/event-stream" } }
);
});
const config = makeConfig();
config.model = "cgpt-codex/luna";
const el = renderChatTab(config);
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => setInputValue(textarea, "Test native Codex"));
const sendBtn = Array.from(el.querySelectorAll("button")).find((button) =>
button.textContent?.includes("Send")
);
await act(async () => sendBtn?.click());
await waitFor(() => el.textContent?.includes("Native response") === true);
expect(capturedUrl).toBe("/api/v1/responses");
expect((capturedInit?.headers as Record<string, string>).Originator).toBe(
"codex_omniroute_playground"
);
const body = JSON.parse(String(capturedInit?.body)) as Record<string, any>;
expect(body.model).toBe("cgpt-codex/luna");
expect(body.input.at(-1).internal_chat_message_metadata_passthrough.turn_id).toBeTruthy();
const turn = JSON.parse(body.client_metadata["x-codex-turn-metadata"]);
expect(turn.thread_id).toBeTruthy();
expect(turn.turn_id).toBe(body.input.at(-1).internal_chat_message_metadata_passthrough.turn_id);
fetchSpy.mockRestore();
});
it("keeps native Codex Responses traffic out of the image stream protocol", async () => {
let capturedHeaders: Record<string, string> | undefined;
const encoder = new TextEncoder();
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
capturedHeaders = init?.headers as Record<string, string>;
return new Response(
new ReadableStream({
start(controller) {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ type: "response.output_text.delta", delta: "Native image model response" })}\n\n`
)
);
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
controller.close();
},
}),
{ status: 200, headers: { "content-type": "text/event-stream" } }
);
});
const config = makeConfig("You are a helpful assistant.", "images");
config.model = "cgpt-codex/luna";
const el = renderChatTab(config);
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => setInputValue(textarea, "Use the native route"));
const sendBtn = Array.from(el.querySelectorAll("button")).find((button) =>
button.textContent?.includes("Send")
);
await act(async () => sendBtn?.click());
await waitFor(() => el.textContent?.includes("Native image model response") === true);
expect(capturedHeaders?.["X-OmniRoute-Playground-Stream"]).toBeUndefined();
fetchSpy.mockRestore();
});
it("sends system prompt from config pane in the request", async () => {
const config = makeConfig("Be concise and helpful.");
let capturedBody: string | null = null;
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async (_, init) => {
capturedBody = (init as RequestInit)?.body as string;
return buildSseResponse("Response");
});
const el = renderChatTab(config);
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => {
setInputValue(textarea, "Test message");
});
const sendBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Send")
) as HTMLButtonElement | undefined;
await act(async () => {
sendBtn?.click();
});
await waitFor(() => capturedBody !== null);
expect(capturedBody).toContain("Be concise and helpful.");
expect(capturedBody).toContain("system");
fetchSpy.mockRestore();
});
it("calls onMetricsUpdate after stream completes", async () => {
const fetchSpy = vi
.spyOn(globalThis, "fetch")
.mockResolvedValue(buildSseResponse("Some response text"));
const onMetricsUpdate = vi.fn();
const el = renderChatTab(makeConfig(), onMetricsUpdate);
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => {
setInputValue(textarea, "Hello");
});
const sendBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Send")
) as HTMLButtonElement | undefined;
await act(async () => {
sendBtn?.click();
});
await waitFor(() => onMetricsUpdate.mock.calls.length > 0, 3000);
expect(onMetricsUpdate).toHaveBeenCalled();
fetchSpy.mockRestore();
});
it("shows regenerate button after first response", async () => {
const fetchSpy = vi
.spyOn(globalThis, "fetch")
.mockResolvedValue(buildSseResponse("Assistant response"));
const el = renderChatTab();
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => {
setInputValue(textarea, "Generate something");
});
const sendBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Send")
) as HTMLButtonElement | undefined;
await act(async () => {
sendBtn?.click();
});
await waitFor(() => el.querySelector("[data-testid='markdown-content']") !== null);
const regenBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Regenerate")
);
expect(regenBtn).toBeTruthy();
fetchSpy.mockRestore();
});
it("regenerate dispatches a new fetch request", async () => {
let fetchCount = 0;
const fetchSpy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => {
fetchCount++;
return buildSseResponse("Response");
});
const el = renderChatTab();
const textarea = el.querySelector("textarea") as HTMLTextAreaElement;
act(() => {
setInputValue(textarea, "Hello");
});
const sendBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Send")
) as HTMLButtonElement | undefined;
await act(async () => {
sendBtn?.click();
});
await waitFor(() => el.querySelector("[data-testid='markdown-content']") !== null);
const countBefore = fetchCount;
const regenBtn = Array.from(el.querySelectorAll("button")).find((b) =>
b.textContent?.includes("Regenerate")
) as HTMLButtonElement | undefined;
await act(async () => {
regenBtn?.click();
});
await waitFor(() => fetchCount > countBefore);
expect(fetchCount).toBeGreaterThan(countBefore);
fetchSpy.mockRestore();
});
});