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
test(playground): add test coverage for codeExport, promptImprover, schemas, markdown
diegosouzapw6c7242cca373
diff --git a/tests/unit/playground-code-export.test.ts b/tests/unit/playground-code-export.test.tsnew file mode 100644index 0000000000..64770017b2--- /dev/null+++ b/tests/unit/playground-code-export.test.ts@@ -0,0 +1,303 @@+import test from "node:test";+import assert from "node:assert/strict";++const { exportCode, exportAllLanguages, endpointToPath, API_KEY_PLACEHOLDER } = await import(+ "../../src/lib/playground/codeExport.ts"+);++// ── Helpers ────────────────────────────────────────────────────────────────────++/** Assert security invariants on every generated snippet. */+function assertSecurityInvariants(generated: string, label: string) {+ assert.ok(generated.includes(API_KEY_PLACEHOLDER), `${label}: must include $OMNIROUTE_API_KEY`);+ assert.ok(generated.length > 0, `${label}: must not be empty`);+ assert.doesNotMatch(+ generated,+ /sk-[A-Za-z0-9_\-]{16,}/,+ `${label}: must not contain real API keys`,+ );+ assert.doesNotMatch(+ generated,+ /Bearer\s+[A-Za-z0-9_\-]{20,}\s/,+ `${label}: must not contain real Bearer tokens`,+ );+}++// ── endpointToPath ─────────────────────────────────────────────────────────────++test("endpointToPath: maps all 10 endpoints correctly", () => {+ assert.equal(endpointToPath("chat.completions"), "/v1/chat/completions");+ assert.equal(endpointToPath("completions"), "/v1/completions");+ assert.equal(endpointToPath("embeddings"), "/v1/embeddings");+ assert.equal(endpointToPath("images"), "/v1/images/generations");+ assert.equal(endpointToPath("audio.transcriptions"), "/v1/audio/transcriptions");+ assert.equal(endpointToPath("audio.speech"), "/v1/audio/speech");+ assert.equal(endpointToPath("moderations"), "/v1/moderations");+ assert.equal(endpointToPath("rerank"), "/v1/rerank");+ assert.equal(endpointToPath("search"), "/v1/search");+ assert.equal(endpointToPath("web.fetch"), "/v1/web/fetch");+});++// ── API_KEY_PLACEHOLDER ───────────────────────────────────────────────────────++test("API_KEY_PLACEHOLDER is $OMNIROUTE_API_KEY", () => {+ assert.equal(API_KEY_PLACEHOLDER, "$OMNIROUTE_API_KEY");+});++// ── Table-driven tests for chat.completions ────────────────────────────────────++const baseState = {+ endpoint: "chat.completions" as const,+ baseUrl: "http://localhost:20128",+ model: "gpt-4o-mini",+ stream: false,+};++test("chat.completions × curl: contains required elements", () => {+ const generated = exportCode(baseState, "curl");+ assertSecurityInvariants(generated, "chat.completions/curl");+ assert.ok(generated.includes("/v1/chat/completions"), "path present");+ assert.ok(generated.includes("Authorization: Bearer"), "auth header present");+ assert.ok(generated.includes("gpt-4o-mini"), "model present");+});++test("chat.completions × python: contains required elements", () => {+ const generated = exportCode(baseState, "python");+ assertSecurityInvariants(generated, "chat.completions/python");+ assert.ok(generated.includes("import requests"), "imports requests");+ assert.ok(generated.includes('os.environ["OMNIROUTE_API_KEY"]'), "uses os.environ");+ assert.ok(generated.includes("gpt-4o-mini"), "model present");+});++test("chat.completions × typescript: contains required elements", () => {+ const generated = exportCode(baseState, "typescript");+ assertSecurityInvariants(generated, "chat.completions/typescript");+ assert.ok(generated.includes("await fetch("), "uses fetch");+ assert.ok(generated.includes("process.env.OMNIROUTE_API_KEY"), "uses process.env");+ assert.ok(generated.includes("gpt-4o-mini"), "model present");+});++// ── chat.completions with systemPrompt ────────────────────────────────────────++test("chat.completions: uses systemPrompt when messages is empty", () => {+ const state = { ...baseState, systemPrompt: "You are helpful.", messages: [] };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assert.ok(generated.includes("You are helpful."), `${lang}: systemPrompt in output`);+ }+});++test("chat.completions: uses messages when provided", () => {+ const state = {+ ...baseState,+ messages: [+ { role: "user" as const, content: "My custom message" },+ ],+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assert.ok(generated.includes("My custom message"), `${lang}: message in output`);+ }+});++// ── completions ────────────────────────────────────────────────────────────────++test("completions × all languages: security + path", () => {+ const state = {+ endpoint: "completions" as const,+ baseUrl: "http://localhost:20128",+ model: "gpt-3.5-turbo-instruct",+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `completions/${lang}`);+ assert.ok(generated.includes("/v1/completions"), `${lang}: correct path`);+ }+});++// ── embeddings ─────────────────────────────────────────────────────────────────++test("embeddings × all languages: security + path", () => {+ const state = {+ endpoint: "embeddings" as const,+ baseUrl: "http://localhost:20128",+ model: "text-embedding-3-small",+ prompt: "Hello world",+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `embeddings/${lang}`);+ assert.ok(generated.includes("/v1/embeddings"), `${lang}: correct path`);+ }+});++// ── images ─────────────────────────────────────────────────────────────────────++test("images × all languages: security + path", () => {+ const state = {+ endpoint: "images" as const,+ baseUrl: "http://localhost:20128",+ model: "dall-e-3",+ prompt: "A beautiful sunset",+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `images/${lang}`);+ assert.ok(generated.includes("/v1/images/generations"), `${lang}: correct path`);+ }+});++// ── search ─────────────────────────────────────────────────────────────────────++test("search × all languages: security + path + query", () => {+ const state = {+ endpoint: "search" as const,+ baseUrl: "http://localhost:20128",+ query: "AI news today",+ searchProvider: "tavily",+ searchType: "web" as const,+ maxResults: 5,+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `search/${lang}`);+ assert.ok(generated.includes("/v1/search"), `${lang}: correct path`);+ assert.ok(generated.includes("AI news today"), `${lang}: query present`);+ }+});++// ── web.fetch ─────────────────────────────────────────────────────────────────++test("web.fetch × all languages: security + path + url", () => {+ const state = {+ endpoint: "web.fetch" as const,+ baseUrl: "http://localhost:20128",+ url: "https://example.com",+ fetchProvider: "firecrawl" as const,+ fetchFormat: "markdown" as const,+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `web.fetch/${lang}`);+ assert.ok(generated.includes("/v1/web/fetch"), `${lang}: correct path`);+ assert.ok(generated.includes("https://example.com"), `${lang}: url present`);+ }+});++// ── rerank ─────────────────────────────────────────────────────────────────────++test("rerank × all languages: security + path + query", () => {+ const state = {+ endpoint: "rerank" as const,+ baseUrl: "http://localhost:20128",+ query: "find relevant docs",+ rerankModel: "rerank-english-v3.0",+ documents: ["Doc 1", "Doc 2"],+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `rerank/${lang}`);+ assert.ok(generated.includes("/v1/rerank"), `${lang}: correct path`);+ }+});++// ── audio.transcriptions ──────────────────────────────────────────────────────++test("audio.transcriptions × all languages: security + path", () => {+ const state = {+ endpoint: "audio.transcriptions" as const,+ baseUrl: "http://localhost:20128",+ model: "whisper-1",+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `audio.transcriptions/${lang}`);+ assert.ok(generated.includes("/v1/audio/transcriptions"), `${lang}: correct path`);+ }+});++// ── audio.speech ──────────────────────────────────────────────────────────────++test("audio.speech × all languages: security + path", () => {+ const state = {+ endpoint: "audio.speech" as const,+ baseUrl: "http://localhost:20128",+ model: "tts-1",+ prompt: "Hello world",+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `audio.speech/${lang}`);+ assert.ok(generated.includes("/v1/audio/speech"), `${lang}: correct path`);+ }+});++// ── moderations ───────────────────────────────────────────────────────────────++test("moderations × all languages: security + path", () => {+ const state = {+ endpoint: "moderations" as const,+ baseUrl: "http://localhost:20128",+ model: "text-moderation-latest",+ prompt: "Hello world",+ };+ for (const lang of ["curl", "python", "typescript"] as const) {+ const generated = exportCode(state, lang);+ assertSecurityInvariants(generated, `moderations/${lang}`);+ assert.ok(generated.includes("/v1/moderations"), `${lang}: correct path`);+ }+});++// ── exportAllLanguages ─────────────────────────────────────────────────────────++test("exportAllLanguages returns all 3 snippets with valid content", () => {+ const state = { ...baseState, model: "gpt-4o" };+ const result = exportAllLanguages(state);++ assert.ok(typeof result.curl === "string" && result.curl.length > 0, "curl non-empty");+ assert.ok(typeof result.python === "string" && result.python.length > 0, "python non-empty");+ assert.ok(+ typeof result.typescript === "string" && result.typescript.length > 0,+ "typescript non-empty",+ );++ for (const [lang, snippet] of Object.entries(result)) {+ assertSecurityInvariants(snippet, `exportAll/${lang}`);+ }+});++// ── JSON formatting (pretty-printed bodies) ───────────────────────────────────++test("curl: body is present (JSON.stringify used)", () => {+ const state = {+ endpoint: "embeddings" as const,+ baseUrl: "http://localhost:20128",+ model: "text-embedding-3-small",+ prompt: "Test input",+ };+ const generated = exportCode(state, "curl");+ // The body should contain the model name in JSON form+ assert.ok(generated.includes("text-embedding-3-small"), "model in JSON body");+});++test("python: body uses json.loads for JSON parsing", () => {+ const state = {+ endpoint: "embeddings" as const,+ baseUrl: "http://localhost:20128",+ model: "text-embedding-3-small",+ prompt: "Test input",+ };+ const generated = exportCode(state, "python");+ assert.ok(generated.includes("json.loads"), "uses json.loads");+});++test("typescript: body uses JSON object literal", () => {+ const state = {+ endpoint: "embeddings" as const,+ baseUrl: "http://localhost:20128",+ model: "text-embedding-3-small",+ prompt: "Test input",+ };+ const generated = exportCode(state, "typescript");+ assert.ok(generated.includes("const body ="), "uses const body =");+});diff --git a/tests/unit/playground-prompt-improver.test.ts b/tests/unit/playground-prompt-improver.test.tsnew file mode 100644index 0000000000..a19cb24254--- /dev/null+++ b/tests/unit/playground-prompt-improver.test.ts@@ -0,0 +1,219 @@+import test from "node:test";+import assert from "node:assert/strict";++const { buildImproveChatBody, parseImprovedContent, META_SYSTEM_PROMPT, ImprovePromptRequestSchema } =+ await import("../../src/lib/playground/promptImprover.ts");++// ── META_SYSTEM_PROMPT ────────────────────────────────────────────────────────++test("META_SYSTEM_PROMPT is a non-empty string", () => {+ assert.ok(typeof META_SYSTEM_PROMPT === "string", "is string");+ assert.ok(META_SYSTEM_PROMPT.length > 0, "is non-empty");+ assert.ok(META_SYSTEM_PROMPT.includes("<<SYSTEM>>"), "contains <<SYSTEM>> marker");+ assert.ok(META_SYSTEM_PROMPT.includes("<<PROMPT>>"), "contains <<PROMPT>> marker");+ assert.ok(META_SYSTEM_PROMPT.includes("prompt engineer"), "mentions prompt engineer");+});++// ── buildImproveChatBody ──────────────────────────────────────────────────────++// Scenario 1: only system, concise tone+test("buildImproveChatBody: only system, concise tone", () => {+ const body = buildImproveChatBody({+ system: "You are a helpful assistant.",+ model: "gpt-4o-mini",+ tone: "concise",+ });++ assert.equal(body.model, "gpt-4o-mini");+ assert.equal(body.temperature, 0.3);+ assert.equal(body.max_tokens, 2048);+ assert.equal(body.stream, false);+ assert.equal(body.messages.length, 2);+ assert.equal(body.messages[0].role, "system");+ assert.equal(body.messages[0].content, META_SYSTEM_PROMPT);+ assert.equal(body.messages[1].role, "user");+ assert.ok(body.messages[1].content.includes("Be concise and direct."), "concise prefix");+ assert.ok(body.messages[1].content.includes("<<SYSTEM>>"), "system marker in user msg");+ assert.ok(+ body.messages[1].content.includes("You are a helpful assistant."),+ "system content present",+ );+ // Must NOT include <<PROMPT>> when no prompt was given+ assert.ok(!body.messages[1].content.includes("<<PROMPT>>"), "no prompt marker when no prompt");+});++// Scenario 2: only prompt, detailed tone+test("buildImproveChatBody: only prompt, detailed tone", () => {+ const body = buildImproveChatBody({+ prompt: "Fix this code for me please.",+ model: "claude-sonnet-4-6",+ tone: "detailed",+ });++ assert.equal(body.model, "claude-sonnet-4-6");+ assert.equal(body.temperature, 0.3);+ assert.equal(body.max_tokens, 2048);+ assert.equal(body.stream, false);+ assert.ok(+ body.messages[1].content.includes("Be detailed and explicit in the rewrite."),+ "detailed prefix",+ );+ assert.ok(body.messages[1].content.includes("<<PROMPT>>"), "prompt marker present");+ assert.ok(+ body.messages[1].content.includes("Fix this code for me please."),+ "prompt content present",+ );+ // Must NOT include <<SYSTEM>> when no system was given+ assert.ok(!body.messages[1].content.includes("<<SYSTEM>>"), "no system marker when no system");+});++// Scenario 3: both system and prompt, concise tone+test("buildImproveChatBody: both system and prompt, concise tone", () => {+ const body = buildImproveChatBody({+ system: "You are a coder.",+ prompt: "Write hello world.",+ model: "gpt-4o",+ tone: "concise",+ });++ assert.ok(body.messages[1].content.includes("<<SYSTEM>>"), "system marker present");+ assert.ok(body.messages[1].content.includes("<<PROMPT>>"), "prompt marker present");+ assert.ok(body.messages[1].content.includes("You are a coder."), "system content");+ assert.ok(body.messages[1].content.includes("Write hello world."), "prompt content");+ assert.ok(body.messages[1].content.includes("Be concise and direct."), "concise prefix");+});++// Scenario 4: both, detailed tone+test("buildImproveChatBody: both system and prompt, detailed tone", () => {+ const body = buildImproveChatBody({+ system: "You are expert.",+ prompt: "Summarize this.",+ model: "gpt-4o",+ tone: "detailed",+ });++ assert.ok(+ body.messages[1].content.includes("Be detailed and explicit in the rewrite."),+ "detailed prefix",+ );+});++// Scenario 5: only system, detailed tone+test("buildImproveChatBody: only system, detailed tone", () => {+ const body = buildImproveChatBody({+ system: "You are a researcher.",+ model: "gpt-4o-mini",+ tone: "detailed",+ });++ assert.ok(+ body.messages[1].content.includes("Be detailed and explicit in the rewrite."),+ "detailed prefix",+ );+ assert.ok(body.messages[1].content.includes("<<SYSTEM>>"), "system marker");+});++// Scenario 6: only prompt, concise tone+test("buildImproveChatBody: only prompt, concise tone", () => {+ const body = buildImproveChatBody({+ prompt: "Explain quantum computing.",+ model: "gemini-2.0-flash",+ tone: "concise",+ });++ assert.ok(body.messages[1].content.includes("Be concise and direct."), "concise prefix");+ assert.ok(body.messages[1].content.includes("<<PROMPT>>"), "prompt marker");+});++// ── parseImprovedContent ──────────────────────────────────────────────────────++test("parseImprovedContent: only system marker present, hadSystem=true", () => {+ const raw = "<<SYSTEM>>\nYou are a professional assistant.";+ const result = parseImprovedContent(raw, true, false);+ assert.equal(result.improvedSystem, "You are a professional assistant.");+ assert.equal(result.improvedPrompt, undefined);+});++test("parseImprovedContent: only prompt marker present, hadPrompt=true", () => {+ const raw = "<<PROMPT>>\nWrite clean code with comments.";+ const result = parseImprovedContent(raw, false, true);+ assert.equal(result.improvedPrompt, "Write clean code with comments.");+ assert.equal(result.improvedSystem, undefined);+});++test("parseImprovedContent: both markers present, hadSystem+hadPrompt", () => {+ const raw = "<<SYSTEM>>\nYou are a professional assistant.\n\n<<PROMPT>>\nWrite clean code.";+ const result = parseImprovedContent(raw, true, true);+ assert.equal(result.improvedSystem, "You are a professional assistant.");+ assert.equal(result.improvedPrompt, "Write clean code.");+});++test("parseImprovedContent: no markers, hadSystem only", () => {+ const raw = "You are a professional assistant.";+ const result = parseImprovedContent(raw, true, false);+ assert.equal(result.improvedSystem, "You are a professional assistant.");+ assert.equal(result.improvedPrompt, undefined);+});++test("parseImprovedContent: no markers, hadPrompt only", () => {+ const raw = "Write clean code with good comments.";+ const result = parseImprovedContent(raw, false, true);+ assert.equal(result.improvedPrompt, "Write clean code with good comments.");+ assert.equal(result.improvedSystem, undefined);+});++test("parseImprovedContent: no markers, both had — fallback to prompt", () => {+ const raw = "Some improved content.";+ const result = parseImprovedContent(raw, true, true);+ // Fallback: entire content goes to prompt+ assert.equal(result.improvedPrompt, "Some improved content.");+});++test("parseImprovedContent: empty raw string returns empty object", () => {+ const result = parseImprovedContent("", true, true);+ assert.equal(result.improvedSystem, undefined);+ assert.equal(result.improvedPrompt, undefined);+});++test("parseImprovedContent: trims whitespace", () => {+ const raw = "<<SYSTEM>>\n You are an assistant. \n\n<<PROMPT>>\n Fix this code. ";+ const result = parseImprovedContent(raw, true, true);+ assert.equal(result.improvedSystem, "You are an assistant.");+ assert.equal(result.improvedPrompt, "Fix this code.");+});++// ── ImprovePromptRequestSchema validation ─────────────────────────────────────++test("ImprovePromptRequestSchema: valid with system only", () => {+ const parsed = ImprovePromptRequestSchema.safeParse({+ system: "You are helpful.",+ model: "gpt-4o",+ tone: "concise",+ });+ assert.ok(parsed.success, "valid request with system only");+});++test("ImprovePromptRequestSchema: valid with prompt only", () => {+ const parsed = ImprovePromptRequestSchema.safeParse({+ prompt: "Tell me about AI.",+ model: "gpt-4o",+ });+ assert.ok(parsed.success, "valid request with prompt only");+});++test("ImprovePromptRequestSchema: invalid when both system and prompt are empty", () => {+ const parsed = ImprovePromptRequestSchema.safeParse({+ system: " ",+ prompt: " ",+ model: "gpt-4o",+ });+ assert.ok(!parsed.success, "should fail when both are empty/whitespace");+});++test("ImprovePromptRequestSchema: invalid when model is empty", () => {+ const parsed = ImprovePromptRequestSchema.safeParse({+ prompt: "Tell me something",+ model: "",+ });+ assert.ok(!parsed.success, "should fail with empty model");+});diff --git a/tests/unit/playground-schemas.test.ts b/tests/unit/playground-schemas.test.tsnew file mode 100644index 0000000000..4744ecd0b0--- /dev/null+++ b/tests/unit/playground-schemas.test.ts@@ -0,0 +1,316 @@+import test from "node:test";+import assert from "node:assert/strict";+import { ZodError } from "zod";++const {+ PlaygroundPresetRowSchema,+ PlaygroundPresetCreateSchema,+ PlaygroundPresetUpdateSchema,+ PlaygroundPresetListItemSchema,+ ToolDefinitionSchema,+ StructuredOutputSchema,+ StreamMetricsSchema,+} = await import("../../src/shared/schemas/playground.ts");++// ── PlaygroundPresetRowSchema ──────────────────────────────────────────────────++test("PlaygroundPresetRowSchema: valid row parses correctly", () => {+ const row = {+ id: "123e4567-e89b-12d3-a456-426614174000",+ name: "My Preset",+ endpoint: "chat.completions",+ model: "gpt-4o-mini",+ system: "You are helpful.",+ params_json: '{"temperature":0.7}',+ created_at: "2025-01-01T00:00:00.000Z",+ };+ const result = PlaygroundPresetRowSchema.safeParse(row);+ assert.ok(result.success, "valid row should parse");+ if (result.success) {+ assert.equal(result.data.id, row.id);+ assert.equal(result.data.name, row.name);+ assert.equal(result.data.system, "You are helpful.");+ }+});++test("PlaygroundPresetRowSchema: null system is valid", () => {+ const row = {+ id: "123e4567-e89b-12d3-a456-426614174000",+ name: "Minimal Preset",+ endpoint: "embeddings",+ model: "text-embedding-3-small",+ system: null,+ params_json: "{}",+ created_at: "2025-01-01T00:00:00.000Z",+ };+ const result = PlaygroundPresetRowSchema.safeParse(row);+ assert.ok(result.success, "null system should be valid");+});++test("PlaygroundPresetRowSchema: invalid — missing required fields", () => {+ const result = PlaygroundPresetRowSchema.safeParse({ id: "not-a-uuid" });+ assert.ok(!result.success, "missing fields should fail");+ if (!result.success) {+ assert.ok(result.error instanceof ZodError);+ }+});++test("PlaygroundPresetRowSchema: invalid — id is not UUID", () => {+ const row = {+ id: "not-a-uuid",+ name: "My Preset",+ endpoint: "chat.completions",+ model: "gpt-4o",+ system: null,+ params_json: "{}",+ created_at: "2025-01-01T00:00:00.000Z",+ };+ const result = PlaygroundPresetRowSchema.safeParse(row);+ assert.ok(!result.success, "non-UUID id should fail");+});++test("PlaygroundPresetRowSchema: invalid — name empty string", () => {+ const row = {+ id: "123e4567-e89b-12d3-a456-426614174000",+ name: "",+ endpoint: "chat.completions",+ model: "gpt-4o",+ system: null,+ params_json: "{}",+ created_at: "2025-01-01T00:00:00.000Z",+ };+ const result = PlaygroundPresetRowSchema.safeParse(row);+ assert.ok(!result.success, "empty name should fail");+});++// ── PlaygroundPresetCreateSchema ──────────────────────────────────────────────++test("PlaygroundPresetCreateSchema: valid payload parses", () => {+ const payload = {+ name: "My new preset",+ endpoint: "chat.completions",+ model: "gpt-4o-mini",+ system: "Be helpful.",+ params: { temperature: 0.7, max_tokens: 1000 },+ };+ const result = PlaygroundPresetCreateSchema.safeParse(payload);+ assert.ok(result.success, "valid create payload should parse");+ if (result.success) {+ assert.deepEqual(result.data.params, { temperature: 0.7, max_tokens: 1000 });+ }+});++test("PlaygroundPresetCreateSchema: params defaults to {}", () => {+ const payload = {+ name: "Minimal preset",+ endpoint: "embeddings",+ model: "text-embedding-3-small",+ };+ const result = PlaygroundPresetCreateSchema.safeParse(payload);+ assert.ok(result.success, "minimal payload should parse");+ if (result.success) {+ assert.deepEqual(result.data.params, {});+ }+});++test("PlaygroundPresetCreateSchema: invalid — name too long", () => {+ const result = PlaygroundPresetCreateSchema.safeParse({+ name: "a".repeat(101),+ endpoint: "chat.completions",+ model: "gpt-4o",+ });+ assert.ok(!result.success, "name >100 chars should fail");+});++// ── PlaygroundPresetUpdateSchema ──────────────────────────────────────────────++test("PlaygroundPresetUpdateSchema: partial update is valid", () => {+ const result = PlaygroundPresetUpdateSchema.safeParse({ name: "Updated name" });+ assert.ok(result.success, "partial update with just name should parse");+});++test("PlaygroundPresetUpdateSchema: empty object is valid (all fields optional)", () => {+ const result = PlaygroundPresetUpdateSchema.safeParse({});+ assert.ok(result.success, "empty patch should parse");+});++// ── PlaygroundPresetListItemSchema ────────────────────────────────────────────++test("PlaygroundPresetListItemSchema: round-trip", () => {+ const item = {+ id: "123e4567-e89b-12d3-a456-426614174000",+ name: "Test",+ endpoint: "chat.completions",+ model: "gpt-4o",+ system: null,+ params: { temperature: 0.5 },+ created_at: "2025-01-01T00:00:00.000Z",+ };+ const result = PlaygroundPresetListItemSchema.safeParse(item);+ assert.ok(result.success, "list item round-trip");+ if (result.success) {+ assert.deepEqual(result.data.params, { temperature: 0.5 });+ }+});++// ── ToolDefinitionSchema ──────────────────────────────────────────────────────++test("ToolDefinitionSchema: valid tool definition parses", () => {+ const tool = {+ type: "function",+ function: {+ name: "get_weather",+ description: "Get current weather for a location.",+ parameters: {+ type: "object",+ properties: {+ location: { type: "string", description: "City name" },+ },+ required: ["location"],+ },+ },+ };+ const result = ToolDefinitionSchema.safeParse(tool);+ assert.ok(result.success, "valid tool definition should parse");+});++test("ToolDefinitionSchema: invalid — type is not 'function'", () => {+ const tool = {+ type: "other",+ function: {+ name: "my_tool",+ parameters: {},+ },+ };+ const result = ToolDefinitionSchema.safeParse(tool);+ assert.ok(!result.success, "type not 'function' should fail");+});++test("ToolDefinitionSchema: invalid — name empty", () => {+ const tool = {+ type: "function",+ function: {+ name: "",+ parameters: {},+ },+ };+ const result = ToolDefinitionSchema.safeParse(tool);+ assert.ok(!result.success, "empty name should fail");+});++test("ToolDefinitionSchema: invalid — missing function key", () => {+ const tool = { type: "function" };+ const result = ToolDefinitionSchema.safeParse(tool);+ assert.ok(!result.success, "missing function key should fail");+});++// ── StructuredOutputSchema ────────────────────────────────────────────────────++test("StructuredOutputSchema: valid structured output parses", () => {+ const so = {+ type: "json_schema",+ json_schema: {+ name: "my_schema",+ schema: {+ type: "object",+ properties: {+ answer: { type: "string" },+ },+ },+ strict: true,+ },+ };+ const result = StructuredOutputSchema.safeParse(so);+ assert.ok(result.success, "valid structured output should parse");+});++test("StructuredOutputSchema: without strict field (optional)", () => {+ const so = {+ type: "json_schema",+ json_schema: {+ name: "simple",+ schema: { type: "object" },+ },+ };+ const result = StructuredOutputSchema.safeParse(so);+ assert.ok(result.success, "strict field is optional");+});++test("StructuredOutputSchema: invalid — type not 'json_schema'", () => {+ const so = {+ type: "json_object",+ json_schema: { name: "test", schema: {} },+ };+ const result = StructuredOutputSchema.safeParse(so);+ assert.ok(!result.success, "wrong type should fail");+});++test("StructuredOutputSchema: invalid — name empty", () => {+ const so = {+ type: "json_schema",+ json_schema: {+ name: "",+ schema: {},+ },+ };+ const result = StructuredOutputSchema.safeParse(so);+ assert.ok(!result.success, "empty name should fail");+});++// ── StreamMetricsSchema ───────────────────────────────────────────────────────++test("StreamMetricsSchema: valid metrics with all values", () => {+ const metrics = {+ ttftMs: 250,+ totalMs: 3500,+ tokensOut: 150,+ tokensIn: 50,+ tps: 42.8,+ costUsd: 0.00023,+ };+ const result = StreamMetricsSchema.safeParse(metrics);+ assert.ok(result.success, "valid metrics should parse");+ if (result.success) {+ assert.equal(result.data.ttftMs, 250);+ assert.equal(result.data.tps, 42.8);+ }+});++test("StreamMetricsSchema: valid — nullable fields can be null", () => {+ const metrics = {+ ttftMs: null,+ totalMs: null,+ tokensOut: 0,+ tokensIn: 0,+ tps: null,+ costUsd: null,+ };+ const result = StreamMetricsSchema.safeParse(metrics);+ assert.ok(result.success, "null metrics should parse");+});++test("StreamMetricsSchema: invalid — negative tokensOut", () => {+ const metrics = {+ ttftMs: 100,+ totalMs: 500,+ tokensOut: -1,+ tokensIn: 10,+ tps: 2.0,+ costUsd: 0.001,+ };+ const result = StreamMetricsSchema.safeParse(metrics);+ assert.ok(!result.success, "negative tokensOut should fail");+});++test("StreamMetricsSchema: invalid — tokensOut is float (not int)", () => {+ const metrics = {+ ttftMs: 100,+ totalMs: 500,+ tokensOut: 1.5,+ tokensIn: 10,+ tps: 2.0,+ costUsd: 0.001,+ };+ const result = StreamMetricsSchema.safeParse(metrics);+ assert.ok(!result.success, "float tokensOut should fail int check");+});diff --git a/tests/unit/search-tools-schemas.test.ts b/tests/unit/search-tools-schemas.test.tsnew file mode 100644index 0000000000..e58651450f--- /dev/null+++ b/tests/unit/search-tools-schemas.test.ts@@ -0,0 +1,246 @@+import test from "node:test";+import assert from "node:assert/strict";+import { ZodError } from "zod";++const { SearchProviderCatalogItemSchema, SearchProviderCatalogResponseSchema, ScrapeResultSchema } =+ await import("../../src/shared/schemas/searchTools.ts");++// ── SearchProviderCatalogItemSchema ───────────────────────────────────────────++test("SearchProviderCatalogItemSchema: valid search provider parses", () => {+ const item = {+ id: "tavily",+ name: "Tavily",+ kind: "search",+ costPerQuery: 0.001,+ freeMonthlyQuota: 1000,+ searchTypes: ["web", "news"],+ status: "configured",+ configureHref: "/dashboard/providers",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(result.success, "valid search item should parse");+ if (result.success) {+ assert.equal(result.data.kind, "search");+ assert.equal(result.data.id, "tavily");+ assert.equal(result.data.status, "configured");+ }+});++test("SearchProviderCatalogItemSchema: valid fetch provider parses", () => {+ const item = {+ id: "firecrawl",+ name: "Firecrawl",+ kind: "fetch",+ costPerQuery: 0.002,+ freeMonthlyQuota: 500,+ fetchFormats: ["markdown", "html", "links"],+ status: "configured",+ configureHref: "/dashboard/providers",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(result.success, "valid fetch item should parse");+ if (result.success) {+ assert.equal(result.data.kind, "fetch");+ assert.deepEqual(result.data.fetchFormats, ["markdown", "html", "links"]);+ }+});++test("SearchProviderCatalogItemSchema: status 'missing' is valid", () => {+ const item = {+ id: "bing",+ name: "Bing",+ kind: "search",+ costPerQuery: 0.005,+ freeMonthlyQuota: 0,+ status: "missing",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(result.success, "status=missing should parse");+ if (result.success) {+ // configureHref has a default value+ assert.equal(result.data.configureHref, "/dashboard/providers");+ }+});++test("SearchProviderCatalogItemSchema: status 'rate_limited' is valid", () => {+ const item = {+ id: "serper",+ name: "Serper",+ kind: "search",+ costPerQuery: 0.001,+ freeMonthlyQuota: 100,+ status: "rate_limited",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(result.success, "status=rate_limited should parse");+});++test("SearchProviderCatalogItemSchema: invalid — kind not in enum", () => {+ const item = {+ id: "custom",+ name: "Custom",+ kind: "unknown",+ costPerQuery: 0.001,+ freeMonthlyQuota: 0,+ status: "configured",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(!result.success, "invalid kind should fail");+ if (!result.success) {+ assert.ok(result.error instanceof ZodError);+ }+});++test("SearchProviderCatalogItemSchema: invalid — negative costPerQuery", () => {+ const item = {+ id: "test",+ name: "Test",+ kind: "search",+ costPerQuery: -0.001,+ freeMonthlyQuota: 0,+ status: "configured",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(!result.success, "negative costPerQuery should fail");+});++test("SearchProviderCatalogItemSchema: invalid — status not in enum", () => {+ const item = {+ id: "test",+ name: "Test",+ kind: "search",+ costPerQuery: 0,+ freeMonthlyQuota: 0,+ status: "active",+ };+ const result = SearchProviderCatalogItemSchema.safeParse(item);+ assert.ok(!result.success, "invalid status should fail");+});++// ── SearchProviderCatalogResponseSchema ───────────────────────────────────────++test("SearchProviderCatalogResponseSchema: valid response with multiple providers", () => {+ const response = {+ providers: [+ {+ id: "tavily",+ name: "Tavily",+ kind: "search",+ costPerQuery: 0.001,+ freeMonthlyQuota: 1000,+ status: "configured",+ },+ {+ id: "firecrawl",+ name: "Firecrawl",+ kind: "fetch",+ costPerQuery: 0.002,+ freeMonthlyQuota: 500,+ status: "configured",+ },+ ],+ };+ const result = SearchProviderCatalogResponseSchema.safeParse(response);+ assert.ok(result.success, "valid response should parse");+ if (result.success) {+ assert.equal(result.data.providers.length, 2);+ assert.equal(result.data.providers[0].kind, "search");+ assert.equal(result.data.providers[1].kind, "fetch");+ }+});++test("SearchProviderCatalogResponseSchema: empty providers array is valid", () => {+ const result = SearchProviderCatalogResponseSchema.safeParse({ providers: [] });+ assert.ok(result.success, "empty providers array should parse");+});++test("SearchProviderCatalogResponseSchema: invalid — providers not array", () => {+ const result = SearchProviderCatalogResponseSchema.safeParse({ providers: "not-array" });+ assert.ok(!result.success, "non-array providers should fail");+});++// ── ScrapeResultSchema ────────────────────────────────────────────────────────++test("ScrapeResultSchema: valid scrape result parses", () => {+ const result_data = {+ provider: "firecrawl",+ url: "https://example.com",+ content: "# Hello\n\nThis is the content.",+ links: ["https://example.com/page1", "https://example.com/page2"],+ metadata: {+ title: "Example Domain",+ description: "An example page.",+ },+ screenshot_url: null,+ };+ const result = ScrapeResultSchema.safeParse(result_data);+ assert.ok(result.success, "valid scrape result should parse");+ if (result.success) {+ assert.equal(result.data.provider, "firecrawl");+ assert.equal(result.data.links.length, 2);+ assert.equal(result.data.metadata?.title, "Example Domain");+ }+});++test("ScrapeResultSchema: null metadata is valid", () => {+ const result_data = {+ provider: "jina-reader",+ url: "https://example.com",+ content: "Content here.",+ links: [],+ metadata: null,+ screenshot_url: null,+ };+ const result = ScrapeResultSchema.safeParse(result_data);+ assert.ok(result.success, "null metadata should parse");+});++test("ScrapeResultSchema: with screenshot_url as string", () => {+ const result_data = {+ provider: "firecrawl",+ url: "https://example.com",+ content: "Content.",+ links: [],+ metadata: { title: null, description: null },+ screenshot_url: "https://screenshots.example.com/abc123.png",+ };+ const result = ScrapeResultSchema.safeParse(result_data);+ assert.ok(result.success, "screenshot_url as string should parse");+ if (result.success) {+ assert.equal(result.data.screenshot_url, "https://screenshots.example.com/abc123.png");+ }+});++test("ScrapeResultSchema: null metadata title/description is valid", () => {+ const result_data = {+ provider: "tavily-search",+ url: "https://example.com",+ content: "Content.",+ links: [],+ metadata: { title: null, description: null },+ screenshot_url: null,+ };+ const result = ScrapeResultSchema.safeParse(result_data);+ assert.ok(result.success, "null title/description in metadata should parse");+});++test("ScrapeResultSchema: invalid — missing required fields", () => {+ const result = ScrapeResultSchema.safeParse({ provider: "firecrawl" });+ assert.ok(!result.success, "missing required fields should fail");+ if (!result.success) {+ assert.ok(result.error instanceof ZodError);+ }+});++test("ScrapeResultSchema: invalid — links must be array of strings", () => {+ const result = ScrapeResultSchema.safeParse({+ provider: "firecrawl",+ url: "https://example.com",+ content: "Content.",+ links: [42, 43], // non-strings+ metadata: null,+ screenshot_url: null,+ });+ assert.ok(!result.success, "non-string links should fail");+});diff --git a/tests/unit/ui/markdown-message.test.tsx b/tests/unit/ui/markdown-message.test.tsxnew file mode 100644index 0000000000..1f403b26f6--- /dev/null+++ b/tests/unit/ui/markdown-message.test.tsx@@ -0,0 +1,153 @@+// @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 ─────────────────────────────────────────────────────────────────────++vi.mock("next-intl", () => ({+ useTranslations: () => (key: string) => key,+}));++// ── Import component at module level (after mocks) ────────────────────────────++const { default: MarkdownMessage } = await import(+ "../../../src/app/(dashboard)/dashboard/playground/components/MarkdownMessage"+);++// ── Helpers ───────────────────────────────────────────────────────────────────++const containers: Array<{ root: ReturnType<typeof createRoot>; el: HTMLDivElement }> = [];++function renderMarkdown(content: string, className?: string): HTMLDivElement {+ const el = document.createElement("div");+ document.body.appendChild(el);+ const root = createRoot(el);+ act(() => {+ root.render(<MarkdownMessage content={content} className={className} />);+ });+ containers.push({ root, el });+ return el;+}++async function waitForCondition(fn: () => boolean, timeoutMs = 3000): Promise<void> {+ const start = Date.now();+ while (!fn()) {+ if (Date.now() - start > timeoutMs) throw new Error("waitForCondition timed out");+ await new Promise((r) => setTimeout(r, 20));+ }+}++// ── Tests ─────────────────────────────────────────────────────────────────────++describe("MarkdownMessage", () => {+ 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.unstubAllGlobals();+ });++ it("renders a code block as <pre><code>", async () => {+ const el = renderMarkdown("```js\nconsole.log(1)\n```");+ // Wait for the component to render+ await waitForCondition(() => el.innerHTML.length > 0);++ const pre = el.querySelector("pre");+ const code = el.querySelector("code");+ expect(pre || code).toBeTruthy();+ expect(el.innerHTML).toContain("console.log");+ });++ it("renders a markdown table as <table>", async () => {+ const tableMarkdown = `+| Name | Age |+|------|-----|+| Alice | 30 |+| Bob | 25 |+`;+ const el = renderMarkdown(tableMarkdown);+ await waitForCondition(() => el.innerHTML.length > 0);++ const table = el.querySelector("table");+ expect(table).toBeTruthy();++ const cells = el.querySelectorAll("td");+ expect(cells.length).toBeGreaterThan(0);+ });++ it("renders a markdown list as <ul><li>", async () => {+ const listMarkdown = `+- Item one+- Item two+- Item three+`;+ const el = renderMarkdown(listMarkdown);+ await waitForCondition(() => el.querySelector("ul") !== null);++ const ul = el.querySelector("ul");+ expect(ul).toBeTruthy();++ const listItems = el.querySelectorAll("li");+ expect(listItems.length).toBe(3);+ });++ it("renders a markdown link as <a href>", async () => {+ const el = renderMarkdown("[Click here](https://example.com)");+ await waitForCondition(() => el.querySelector("a") !== null);++ const anchor = el.querySelector("a");+ expect(anchor).toBeTruthy();+ expect(anchor?.getAttribute("href")).toBe("https://example.com");+ });++ it("security: <script> tags appear as literal text, not executed", () => {+ const xssContent = "<script>alert(1)</script>";+ const el = renderMarkdown(xssContent);++ // Should NOT contain a <script> element in the DOM+ const scriptEl = el.querySelector("script");+ expect(scriptEl).toBeNull();++ // react-markdown by default does not render raw HTML+ // The content should not create a <script> tag+ const innerHTML = el.innerHTML;+ expect(innerHTML).not.toContain("<script>");+ });++ it("renders plain text content", async () => {+ const el = renderMarkdown("Hello, world!");+ await waitForCondition(() => el.textContent !== null && el.textContent.includes("Hello"));++ expect(el.textContent).toContain("Hello, world!");+ });++ it("accepts optional className prop", () => {+ const el = renderMarkdown("Text", "my-custom-class");++ // The wrapper div should have the class+ const wrapper = el.firstElementChild;+ expect(wrapper).toBeTruthy();+ expect(wrapper?.classList.contains("my-custom-class")).toBe(true);+ });++ it("renders strong and emphasis formatting", async () => {+ const el = renderMarkdown("**bold text** and _italic text_");+ await waitForCondition(+ () => el.querySelector("strong") !== null || el.querySelector("em") !== null,+ );++ const strong = el.querySelector("strong");+ const em = el.querySelector("em");+ expect(strong).toBeTruthy();+ expect(em).toBeTruthy();+ });+});