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, { act } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import EndpointPageClient from "../EndpointPageClient";
type Deferred<T> = {
promise: Promise<T>;
resolve: (value: T) => void;
reject: (error: unknown) => void;
};
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<T>((res, rej) => {
resolve = res;
reject = rej;
});
return { promise, resolve, reject };
}
function jsonResponse(data: unknown) {
return {
ok: true,
json: async () => data,
} as Response;
}
function getRequestPath(input: RequestInfo | URL) {
return typeof input === "string" ? input : input instanceof URL ? input.pathname : input.url;
}
const cleanupCallbacks: Array<() => void> = [];
function installLocalStorageStub() {
const store = new Map<string, string>();
vi.stubGlobal("localStorage", {
getItem: vi.fn((key: string) => store.get(key) ?? null),
setItem: vi.fn((key: string, value: string) => {
store.set(key, value);
}),
removeItem: vi.fn((key: string) => {
store.delete(key);
}),
clear: vi.fn(() => {
store.clear();
}),
});
}
async function waitForText(text: string) {
const startedAt = Date.now();
while (!document.body.textContent?.includes(text)) {
if (Date.now() - startedAt > 1000) {
throw new Error(`Timed out waiting for text: ${text}`);
}
await new Promise((resolve) => setTimeout(resolve, 10));
}
}
function renderEndpointPage() {
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
let mounted = true;
act(() => {
root.render(<EndpointPageClient machineId="" />);
});
const unmount = () => {
if (!mounted) {
return;
}
act(() => {
root.unmount();
});
container.remove();
mounted = false;
};
cleanupCallbacks.push(unmount);
return {
unmount,
};
}
vi.mock("next/link", () => ({
default: ({ href, children, ...props }: React.AnchorHTMLAttributes<HTMLAnchorElement>) => (
<a href={String(href)} {...props}>
{children}
</a>
),
}));
vi.mock("next-intl", () => ({
useTranslations: (namespace?: string) => {
const messages: Record<string, string> = {
"endpoint.title": "Endpoint",
"endpoint.available": "Available endpoints",
"endpoint.loadingModels": "Loading available models...",
"endpoint.modelsAcrossEndpoints": "{models} models across {endpoints} endpoints",
"endpoint.modelsCount": "{count} models",
"endpoint.chatCompletions": "Chat Completions",
"endpoint.chatDesc": "Chat endpoint",
"endpoint.responses": "Responses API",
"endpoint.responsesDesc": "Responses endpoint",
"endpoint.completionsLegacy": "Completions",
"endpoint.completionsLegacyDesc": "Completions endpoint",
"endpoint.embeddings": "Embeddings",
"endpoint.embeddingsDesc": "Embedding endpoint",
"endpoint.imageGeneration": "Image Generation",
"endpoint.imageDesc": "Image endpoint",
"endpoint.audioTranscription": "Audio Transcription",
"endpoint.audioTranscriptionDesc": "Audio transcription endpoint",
"endpoint.textToSpeech": "Text to Speech",
"endpoint.textToSpeechDesc": "Speech endpoint",
"endpoint.musicGeneration": "Music Generation",
"endpoint.musicDesc": "Music endpoint",
"endpoint.videoGeneration": "Video Generation",
"endpoint.videoDesc": "Video endpoint",
"endpoint.rerank": "Rerank",
"endpoint.rerankDesc": "Rerank endpoint",
"endpoint.moderations": "Moderations",
"endpoint.moderationsDesc": "Moderation endpoint",
"endpoint.listModels": "List Models",
"endpoint.listModelsDesc": "List model endpoint",
"endpoint.overviewTitle": "Endpoint overview",
"endpoint.overviewDescription": "Endpoint overview description",
"endpoint.tabApis": "APIs",
"endpoint.tabProtocols": "Protocols",
"endpoint.categoryCore": "Core APIs",
"endpoint.categoryMedia": "Media APIs",
"endpoint.categoryUtility": "Utility APIs",
"endpoint.vscodeAliasTitle": "VS Code Token Alias",
"endpoint.vscodeAliasDescriptionReady":
"Ready-to-paste compatibility URLs using the /api/v1/vscode/{token}/... endpoint.",
"endpoint.vscodeAliasDescriptionError":
"Showing placeholder URLs because CLI keys could not be loaded in this session.",
"endpoint.vscodeAliasDescriptionLoading":
"Loading CLI keys. Placeholder URLs are shown until a key is available.",
"endpoint.vscodeAliasDescriptionPlaceholder":
"Showing placeholder URLs. Create or activate an API key in CLI Tools to replace {token}.",
"endpoint.vscodeAliasManage": "CLI Tools",
"endpoint.vscodeAliasBaseLabel": "VS Code base",
"endpoint.vscodeAliasModelsLabel": "VS Code models",
"endpoint.vscodeAliasChatLabel": "VS Code chat",
"endpoint.machineId": "Machine {id}",
"endpoint.usingLocalServer": "Using local server",
"common.copy": "Copy",
"common.cancel": "Cancel",
};
const translate = (key: string, values?: Record<string, unknown>) => {
const fullKey = namespace ? `${namespace}.${key}` : key;
let message = messages[fullKey] ?? key;
if (values) {
for (const [name, value] of Object.entries(values)) {
message = message.replace(`{${name}}`, String(value));
}
}
return message;
};
return translate;
},
}));
describe("EndpointPageClient", () => {
it("requires credential-upload consent before enabling cloud sync", async () => {
fetchMock.mockImplementation((input: RequestInfo | URL) => {
if (getRequestPath(input) === "/api/settings")
return Promise.resolve(
jsonResponse({
cloudEnabled: false,
cloudConfigured: true,
cloudUrl: "https://cloud.example",
hideEndpointCloudflaredTunnel: true,
hideEndpointTailscaleFunnel: true,
hideEndpointNgrokTunnel: true,
})
);
return Promise.resolve(jsonResponse({ data: [], providers: [], keys: [] }));
});
renderEndpointPage();
await waitForText("https://cloud.example");
const enable = Array.from(document.querySelectorAll("button")).find((b) =>
b.textContent?.includes("enableCloud")
);
expect(enable).toBeDefined();
act(() => enable!.click());
expect(document.body.textContent).toContain("OAuth access/refresh tokens");
const consent = document.querySelector<HTMLInputElement>("input[type=checkbox]")!;
expect(consent.checked).toBe(false);
const submit = Array.from(document.querySelectorAll("button")).find(
(b) => b.getAttribute("class")?.includes("w-full") && b.textContent?.includes("enable")
);
expect(submit).toBeDefined();
expect(submit!.disabled).toBe(true);
act(() => consent.click());
expect(submit!.disabled).toBe(false);
});
const fetchMock = vi.fn();
beforeEach(() => {
fetchMock.mockReset();
(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
vi.stubGlobal("fetch", fetchMock);
installLocalStorageStub();
});
afterEach(() => {
while (cleanupCallbacks.length > 0) {
cleanupCallbacks.pop()?.();
}
document.body.innerHTML = "";
vi.unstubAllEnvs();
vi.unstubAllGlobals();
});
it("shows the public browser endpoint before the runtime local endpoint", async () => {
vi.stubEnv("NEXT_PUBLIC_BASE_URL", "http://localhost:20128");
vi.stubGlobal("location", { origin: "https://api.example.com" });
fetchMock.mockImplementation((input: RequestInfo | URL) => {
const path = getRequestPath(input);
if (path === "/api/settings") {
return Promise.resolve(
jsonResponse({
cloudEnabled: false,
cloudConfigured: false,
hideEndpointCloudflaredTunnel: true,
hideEndpointTailscaleFunnel: true,
hideEndpointNgrokTunnel: true,
})
);
}
if (path === "/api/network/info") {
return Promise.resolve(
jsonResponse({
localUrl: "http://localhost:20131/v1",
lanUrls: [],
tailscaleIpUrl: null,
})
);
}
if (path === "/v1/models") return Promise.resolve(jsonResponse({ data: [] }));
if (path === "/api/mcp/status") return Promise.resolve(jsonResponse({ online: false }));
if (path === "/api/a2a/status") {
return Promise.resolve(jsonResponse({ status: "ok", tasks: { activeStreams: 0 } }));
}
if (path === "/api/search/providers") {
return Promise.resolve(jsonResponse({ providers: [] }));
}
if (path === "/api/cli-tools/keys") return Promise.resolve(jsonResponse({ keys: [] }));
throw new Error(`Unexpected request: ${path}`);
});
renderEndpointPage();
await waitForText("https://api.example.com/v1");
await waitForText("http://localhost:20131/v1");
const displayedUrls = Array.from(document.body.querySelectorAll("code")).map(
(element) => element.textContent
);
expect(displayedUrls.indexOf("https://api.example.com/v1")).toBeLessThan(
displayedUrls.indexOf("http://localhost:20131/v1")
);
});
it("renders the endpoint shell before models finish and skips hidden tunnel probes", async () => {
const modelsDeferred = createDeferred<Response>();
fetchMock.mockImplementation((input: RequestInfo | URL) => {
const path = getRequestPath(input);
if (path === "/api/settings") {
return Promise.resolve(
jsonResponse({
cloudEnabled: false,
cloudConfigured: false,
hideEndpointCloudflaredTunnel: true,
hideEndpointTailscaleFunnel: true,
hideEndpointNgrokTunnel: true,
machineId: "machine-12345678",
})
);
}
if (path === "/v1/models") {
return modelsDeferred.promise;
}
if (path === "/api/mcp/status") {
return Promise.resolve(jsonResponse({ online: false }));
}
if (path === "/api/a2a/status") {
return Promise.resolve(jsonResponse({ status: "ok", tasks: { activeStreams: 0 } }));
}
if (path === "/api/search/providers") {
return Promise.resolve(jsonResponse({ providers: [] }));
}
if (path === "/api/cli-tools/keys") {
return Promise.resolve(
jsonResponse({
keys: [
{
id: "key-1",
key: "sk-test-1234",
rawKey: "sk-test-1234",
isActive: true,
},
],
})
);
}
if (path === "/api/settings/compression") {
return Promise.resolve(
jsonResponse({
enabled: true,
cavemanConfig: { enabled: true, intensity: "full" },
cavemanOutputMode: { enabled: false, intensity: "full" },
rtkConfig: { enabled: true, intensity: "standard" },
})
);
}
throw new Error(`Unexpected request: ${path}`);
});
renderEndpointPage();
await waitForText("Endpoint");
expect(document.body.textContent).toContain("Loading available models...");
expect(fetchMock).toHaveBeenCalledWith("/v1/models");
expect(fetchMock).not.toHaveBeenCalledWith("/api/tunnels/cloudflared", expect.anything());
expect(fetchMock).not.toHaveBeenCalledWith("/api/tunnels/tailscale", expect.anything());
expect(fetchMock).not.toHaveBeenCalledWith("/api/tunnels/ngrok", expect.anything());
modelsDeferred.resolve(
jsonResponse({
data: [
{
id: "openai/gpt-4o",
owned_by: "openai",
root: "gpt-4o",
},
{
id: "openai/text-embedding-3-small",
owned_by: "openai",
root: "text-embedding-3-small",
type: "embedding",
},
],
})
);
await waitForText("2 models across");
await waitForText("/api/v1/vscode/sk-test-1234/models");
expect(document.body.textContent).toContain("VS Code Token Alias");
expect(document.body.textContent).toContain("/api/v1/vscode/sk-test-1234/models");
});
it("does not start background endpoint requests after unmounting during settings load", async () => {
const settingsDeferred = createDeferred<Response>();
fetchMock.mockImplementation((input: RequestInfo | URL) => {
const path = getRequestPath(input);
if (path === "/api/settings") {
return settingsDeferred.promise;
}
throw new Error(`Unexpected request after unmount: ${path}`);
});
const { unmount } = renderEndpointPage();
unmount();
await act(async () => {
settingsDeferred.resolve(
jsonResponse({
cloudEnabled: false,
cloudConfigured: false,
hideEndpointCloudflaredTunnel: false,
hideEndpointTailscaleFunnel: false,
hideEndpointNgrokTunnel: false,
})
);
await settingsDeferred.promise;
});
const requestPaths = fetchMock.mock.calls.map(([input]) => getRequestPath(input));
expect(requestPaths.length).toBeGreaterThan(0);
expect(requestPaths.every((path) => path === "/api/settings")).toBe(true);
});
it("does not load compression settings on the Endpoint page", async () => {
fetchMock.mockImplementation((input: RequestInfo | URL) => {
const path = getRequestPath(input);
if (path === "/api/settings") {
return Promise.resolve(
jsonResponse({
cloudEnabled: false,
cloudConfigured: false,
hideEndpointCloudflaredTunnel: true,
hideEndpointTailscaleFunnel: true,
hideEndpointNgrokTunnel: true,
})
);
}
if (path === "/v1/models") {
return Promise.resolve(jsonResponse({ data: [] }));
}
if (path === "/api/mcp/status") {
return Promise.resolve(jsonResponse({ online: false }));
}
if (path === "/api/a2a/status") {
return Promise.resolve(jsonResponse({ status: "ok", tasks: { activeStreams: 0 } }));
}
if (path === "/api/search/providers") {
return Promise.resolve(jsonResponse({ providers: [] }));
}
if (path === "/api/cli-tools/keys") {
return Promise.resolve(jsonResponse({ keys: [] }));
}
throw new Error(`Unexpected request: ${path}`);
});
renderEndpointPage();
await waitForText("Endpoint");
await waitForText("0 models across");
const requestPaths = fetchMock.mock.calls.map(([input]) => getRequestPath(input));
expect(document.body.textContent).not.toContain("Token Saver");
expect(requestPaths).not.toContain("/api/settings/compression");
});
});