"use strict"; // Dashboard assistant model picker (finding M2): the client-selected chat // model is attacker-controlled input, so the service must allowlist it // against the provider's live chat-capable model list before any provider // call, and the picker must finally be wired end to end. // // Three layers are pinned here: // - service (behavioral): resolveChatModelForProvider honors a requested // model only when it is in the live chat-capable list; junk/unknown/ // non-chat/absent values silently fall back to the server resolution // order; an env override pin always wins; getBootstrap reports the // effective model + pin state for admins and non-admins; // - router (behavioral): POST /chat and POST /client-follow-up pass // req.body.model into the service and the requested model reaches the // provider completion call exactly when the allowlist accepts it; // - client (structural): the picker state, the POST bodies, the // modelLocked handling and the DEFAULT_MODELS mirror are locked in // source assertions (the browser file cannot be executed here). // // The provider HTTP layer runs through the shared node:https singleton, so // the fake below monkey-patches https.request to answer the Groq model-list // and chat-completion calls in-process — no network access, and any other // outbound host fails the request loudly. const test = require("node:test"); const assert = require("node:assert"); const express = require("express"); const fs = require("node:fs"); const path = require("node:path"); const https = require("node:https"); const { EventEmitter } = require("node:events"); const createDashboardAssistantRouter = require("../routes/dashboard-assistant.js"); const { createDashboardAssistantService } = require("../utils/dashboard-assistant-service.js"); const ROOT = path.join(__dirname, ".."); const CLIENT_JS = path.join(ROOT, "public", "js", "dashboard-assistant.js"); const ROUTES_JS = path.join(ROOT, "routes", "dashboard-assistant.js"); const SERVICE_JS = path.join(ROOT, "utils", "dashboard-assistant-service.js"); const clientSource = fs.readFileSync(CLIENT_JS, "utf8"); const routesSource = fs.readFileSync(ROUTES_JS, "utf8"); const serviceSource = fs.readFileSync(SERVICE_JS, "utf8"); const ADMIN_EMAIL = "admin@test.local"; // whisper-large-v3 is a live Groq STT model: fetchProviderChatModelIds // filters it out, so requesting it must fall back instead of being honored. const LIVE_GROQ_IDS = ["openai/gpt-oss-120b", "openai/gpt-oss-20b", "llama-3.3-70b-versatile", "whisper-large-v3"]; const DEFAULT_GROQ_MODEL = "openai/gpt-oss-120b"; const DEFAULT_GOOGLE_MODEL = "gemini-2.5-flash-lite"; function countOccurrences(haystack, needle) { return haystack.split(needle).length - 1; } function sliceBetween(source, startMarker, endMarker) { const start = source.indexOf(startMarker); assert.ok(start >= 0, `start marker not found: ${startMarker}`); const end = source.indexOf(endMarker, start + startMarker.length); assert.ok(end > start, `end marker not found after start: ${endMarker}`); return source.slice(start, end + startMarker.length); } function installFakeProviderHttp({ groqModels = [], groqModelsStatus = 200 } = {}) { const chatRequests = []; const modelListRequests = []; const realRequest = https.request; https.request = function fakeRequest(options, callback) { const reqPath = String(options.path || ""); const chunks = []; const req = new EventEmitter(); req.write = (chunk) => chunks.push(String(chunk)); req.end = () => { const respond = (status, body) => { const res = new EventEmitter(); res.statusCode = status; res.setEncoding = () => {}; callback(res); res.emit("data", JSON.stringify(body)); res.emit("end"); }; if (reqPath.startsWith("/openai/v1/models")) { modelListRequests.push(reqPath); if (groqModelsStatus !== 200) { respond(groqModelsStatus, { error: { message: "model list unavailable" } }); return; } respond(200, { data: groqModels.map((id) => ({ id, active: true })) }); return; } if (reqPath.startsWith("/openai/v1/chat/completions")) { let payload = {}; try { payload = JSON.parse(chunks.join("") || "{}"); } catch { payload = { raw: chunks.join("") }; } chatRequests.push(payload); respond(200, { choices: [{ finish_reason: "stop", message: { role: "assistant", content: "Done." } }], }); return; } // Unexpected outbound host/path: fail the request instead of leaking // a test into the network. process.nextTick(() => req.emit("error", new Error(`unexpected provider request: ${options.hostname}${reqPath}`))); }; req.destroy = () => {}; return req; }; return { chatRequests, modelListRequests, restore() { https.request = realRequest; }, }; } // Sets process.env entries for the duration of fn and restores them after, // whatever the outcome. async function withEnv(overrides, fn) { const saved = new Map(); for (const [key, value] of Object.entries(overrides)) { saved.set(key, process.env[key]); if (value === undefined) delete process.env[key]; else process.env[key] = value; } try { return await fn(); } finally { for (const [key, value] of saved.entries()) { if (value === undefined) delete process.env[key]; else process.env[key] = value; } } } function fakeDbQuery(sql) { const s = String(sql); const CHAT_ROW = { id: 7, title: "chat", created_at: 0, updated_at: 0 }; if (s.includes("CREATE TABLE")) return Promise.resolve([]); if (s.includes("WHERE id = ? AND user_email = ?")) return Promise.resolve([CHAT_ROW]); if (s.includes("SELECT COUNT(*)")) return Promise.resolve([{ total: 0 }]); if (s.includes("SELECT title FROM dashboard_assistant_chats")) { // A non-default title keeps maybeUpdateChatTitle from churning an UPDATE. return Promise.resolve([{ title: "chat" }]); } if (s.includes("user_email = ?")) return Promise.resolve([CHAT_ROW]); if (s.includes("WHERE id = ? LIMIT 1")) return Promise.resolve([CHAT_ROW]); return Promise.resolve([]); } test("a requested model is honored only while it is in the live chat-capable list", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); try { await withEnv({ GROQ_API_KEY: "test-key", DASHBOARD_ASSISTANT_GROQ_MODEL: undefined }, async () => { const service = createDashboardAssistantService({}); // Valid live ids are honored verbatim (compound ids included). assert.strictEqual(await service.resolveChatModelForProvider("groq", "openai/gpt-oss-20b"), "openai/gpt-oss-20b"); assert.strictEqual(await service.resolveChatModelForProvider("groq", "openai/gpt-oss-120b"), DEFAULT_GROQ_MODEL); // Live but non-chat-capable: filtered out of the allowlist upstream. assert.strictEqual(await service.resolveChatModelForProvider("groq", "whisper-large-v3"), DEFAULT_GROQ_MODEL); // Unknown id. assert.strictEqual(await service.resolveChatModelForProvider("groq", "totally-made-up-model"), DEFAULT_GROQ_MODEL); // Allowlist membership is exact-match (case-sensitive both sides): a // case-variant id is rejected and degrades to the server resolution. assert.strictEqual(await service.resolveChatModelForProvider("groq", "OPENAI/GPT-OSS-20B"), DEFAULT_GROQ_MODEL); // Invalid charset (spaces, newline, shell metachars). assert.strictEqual(await service.resolveChatModelForProvider("groq", "openai/gpt-oss 20b"), DEFAULT_GROQ_MODEL); assert.strictEqual(await service.resolveChatModelForProvider("groq", "openai/gpt-oss-20b\nDROP TABLE x"), DEFAULT_GROQ_MODEL); assert.strictEqual(await service.resolveChatModelForProvider("groq", "model; rm -rf /"), DEFAULT_GROQ_MODEL); // Over the 128-char cap (charset-valid, so this pins the length gate). assert.strictEqual(await service.resolveChatModelForProvider("groq", "a".repeat(129)), DEFAULT_GROQ_MODEL); // Absent / empty / non-string values fall through silently. assert.strictEqual(await service.resolveChatModelForProvider("groq"), DEFAULT_GROQ_MODEL); assert.strictEqual(await service.resolveChatModelForProvider("groq", ""), DEFAULT_GROQ_MODEL); assert.strictEqual(await service.resolveChatModelForProvider("groq", null), DEFAULT_GROQ_MODEL); assert.strictEqual(await service.resolveChatModelForProvider("groq", 42), DEFAULT_GROQ_MODEL); // Exactly 128 chars is inside the cap (still allowlist-gated). assert.strictEqual(await service.resolveChatModelForProvider("groq", "a".repeat(128)), DEFAULT_GROQ_MODEL); }); } finally { fake.restore(); } }); test("an env model override pins the chat model over any client pick", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); try { await withEnv({ DASHBOARD_ASSISTANT_GROQ_MODEL: "pinned-override-model" }, async () => { const service = createDashboardAssistantService({}); assert.strictEqual(await service.resolveChatModelForProvider("groq", "openai/gpt-oss-20b"), "pinned-override-model"); assert.strictEqual(await service.resolveChatModelForProvider("groq", "junk model!!!"), "pinned-override-model"); assert.strictEqual(await service.resolveChatModelForProvider("groq"), "pinned-override-model"); assert.strictEqual(fake.modelListRequests.length, 0, "the override short-circuits the live list fetch"); }); } finally { fake.restore(); } }); test("an unavailable live list honors no client pick and falls back to the static default", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); try { await withEnv({ GROQ_API_KEY: undefined, DASHBOARD_ASSISTANT_GROQ_MODEL: undefined }, async () => { const service = createDashboardAssistantService({}); assert.strictEqual(await service.resolveChatModelForProvider("groq", "openai/gpt-oss-20b"), DEFAULT_GROQ_MODEL); assert.strictEqual(fake.modelListRequests.length, 0, "no key means no provider call at all"); }); } finally { fake.restore(); } }); test("a pick valid for groq never leaks into the google resolution", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); try { await withEnv({ GROQ_API_KEY: "test-key", GOOGLE_AI_STUDIO_API_KEY: undefined, GOOGLE_AI_KEY: undefined, DASHBOARD_ASSISTANT_GROQ_MODEL: undefined, DASHBOARD_ASSISTANT_GOOGLE_MODEL: undefined, }, async () => { const service = createDashboardAssistantService({}); // The candidate is only ever compared against the resolved provider's // own live list: groq's list must not admit the id into google's call. assert.strictEqual( await service.resolveChatModelForProvider("google", "openai/gpt-oss-20b"), DEFAULT_GOOGLE_MODEL, "a groq-id pick is checked against google's list only and rejected" ); assert.strictEqual(fake.modelListRequests.length, 0, "the google resolve never consults the groq list"); }); } finally { fake.restore(); } }); test("a provider model-list failure inside getBootstrap degrades to the default without failing", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS, groqModelsStatus: 500 }); try { await withEnv({ GROQ_API_KEY: "test-key", DASHBOARD_ASSISTANT_GROQ_MODEL: undefined }, async () => { const deps = { db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin: false }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), }; const service = createDashboardAssistantService(deps); const boot = await service.getBootstrap({ session: { user: "user@test.local" } }); assert.strictEqual(boot.model, DEFAULT_GROQ_MODEL, "a failed list fetch falls back to the static default"); assert.strictEqual(boot.modelLocked, false); assert.strictEqual( await service.resolveChatModelForProvider("groq", "openai/gpt-oss-20b"), DEFAULT_GROQ_MODEL, "an empty live list honors no client pick" ); }); } finally { fake.restore(); } }); test("getBootstrap reports the effective chat model and the pin state in both branches", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); try { await withEnv({ GROQ_API_KEY: "test-key", DASHBOARD_ASSISTANT_GROQ_MODEL: undefined }, async () => { const deps = { db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin: false }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), }; const service = createDashboardAssistantService(deps); // Non-admin branch (non-admins see the picker too). const nonAdmin = await service.getBootstrap({ session: { user: "user@test.local" } }); assert.strictEqual(nonAdmin.canConfigure, false); assert.strictEqual(nonAdmin.model, DEFAULT_GROQ_MODEL); assert.strictEqual(nonAdmin.modelLocked, false); // Admin branch. deps.findUserByEmail = async (email) => ({ email: String(email || "").toLowerCase(), admin: true }); const admin = await service.getBootstrap({ session: { user: ADMIN_EMAIL } }); assert.strictEqual(admin.canConfigure, true); assert.strictEqual(admin.model, DEFAULT_GROQ_MODEL); assert.strictEqual(admin.modelLocked, false); }); await withEnv({ GROQ_API_KEY: "test-key", DASHBOARD_ASSISTANT_GROQ_MODEL: "pinned-override-model" }, async () => { const deps = { db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin: false }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), }; const service = createDashboardAssistantService(deps); const locked = await service.getBootstrap({ session: { user: "user@test.local" } }); assert.strictEqual(locked.model, "pinned-override-model"); assert.strictEqual(locked.modelLocked, true); }); } finally { fake.restore(); } }); function bootChatApp({ admin = true } = {}) { const session = { user: ADMIN_EMAIL }; const deps = { isAuthenticated: async () => true, isAdmin: async () => admin, findUserByEmail: async (email) => ({ id: 7, email: String(email || "").toLowerCase(), admin }), getDashboardAssistantConfig: () => ({ allowNormalUsers: true }), db: require("./helpers/assistant-history-db").assistantHistoryDb(fakeDbQuery), }; const app = express(); app.use(express.json()); app.use((req, res, next) => { req.session = session; req.sessionID = "test-sid-1"; next(); }); app.use("/api/dashboard-assistant", createDashboardAssistantRouter(deps)); const server = app.listen(0); const base = `http://127.0.0.1:${server.address().port}/api/dashboard-assistant`; const post = async (path, body) => fetch(`${base}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); const close = () => new Promise((resolve) => server.close(resolve)); return { post, close }; } // "tell me a story about robots" carries no power/console/navigation intent, // so the power-only pipeline routes it to a plain chat completion — which // records the exact model id the provider was asked to run. const PLAIN_MESSAGE = "tell me a story about robots"; test("POST /chat forwards req.body.model and the allowlisted pick reaches the provider call", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); const env = bootChatApp(); try { await withEnv({ GROQ_API_KEY: "test-key", DASHBOARD_ASSISTANT_GROQ_MODEL: undefined }, async () => { const picked = await env.post("/chat", { chatId: 7, message: PLAIN_MESSAGE, model: "openai/gpt-oss-20b" }); assert.strictEqual(picked.status, 200); const pickedBody = await picked.json(); assert.strictEqual(pickedBody.model, "openai/gpt-oss-20b", "the response reports the actually used model"); assert.strictEqual(fake.chatRequests.length, 1); assert.strictEqual(fake.chatRequests[0].model, "openai/gpt-oss-20b", "the provider was asked to run the picked model"); fake.chatRequests.length = 0; const junk = await env.post("/chat", { chatId: 7, message: PLAIN_MESSAGE, model: "model; rm -rf /" }); assert.strictEqual(junk.status, 200, "a rejected pick degrades silently, never errors"); assert.strictEqual(fake.chatRequests[0].model, DEFAULT_GROQ_MODEL, "an invalid pick falls back to server resolution"); fake.chatRequests.length = 0; const legacy = await env.post("/chat", { chatId: 7, message: PLAIN_MESSAGE }); assert.strictEqual(legacy.status, 200); assert.strictEqual(fake.chatRequests[0].model, DEFAULT_GROQ_MODEL, "absent model keeps the pre-existing behavior"); }); } finally { env.close(); fake.restore(); } }); test("POST /client-follow-up forwards req.body.model to the AI follow-up call", async () => { const fake = installFakeProviderHttp({ groqModels: LIVE_GROQ_IDS }); const env = bootChatApp(); try { await withEnv({ GROQ_API_KEY: "test-key", DASHBOARD_ASSISTANT_GROQ_MODEL: undefined }, async () => { const skip = await env.post("/client-follow-up", { chatId: 7, summary: "The server is running.", skipAi: true, }); assert.strictEqual(skip.status, 200); assert.strictEqual(fake.chatRequests.length, 0, "skipAi follow-ups make no provider call"); const ai = await env.post("/client-follow-up", { chatId: 7, summary: "The server is running.", skipAi: false, model: "openai/gpt-oss-20b", }); assert.strictEqual(ai.status, 200); const aiBody = await ai.json(); assert.strictEqual(aiBody.model, "openai/gpt-oss-20b"); assert.strictEqual(fake.chatRequests.length, 1); assert.strictEqual(fake.chatRequests[0].model, "openai/gpt-oss-20b"); }); } finally { env.close(); fake.restore(); } }); test("the service never resolves a chat model from an unvalidated client string", () => { // Shape gate + allowlist exist and are ordered before any provider call. assert.match(serviceSource, /async function resolveChatModelForProvider\(provider, requestedModel\)/); assert.match(serviceSource, /REQUESTED_MODEL_MAX_LENGTH = 128/); assert.match(serviceSource, /const REQUESTED_MODEL_PATTERN = \/.*\/[a-z]*;/); const resolveBody = sliceBetween( serviceSource, "async function resolveChatModelForProvider(provider, requestedModel) {", "async function loadAccessibleServersForAssistant" ); assert.ok(resolveBody.includes("sanitizeRequestedChatModel(requestedModel)"), "the requested model passes the shape gate"); assert.ok(resolveBody.includes("liveIds.includes(candidate)"), "the shape-checked pick is allowlisted against the live list"); const overrideCheck = resolveBody.indexOf("if (override) return override;"); const allowlistCheck = resolveBody.indexOf("liveIds.includes(candidate)"); assert.ok(overrideCheck !== -1 && overrideCheck < allowlistCheck, "the env pin wins before the client pick is considered"); assert.strictEqual( countOccurrences(serviceSource, "resolveChatModelForProvider(provider)"), 0, "no chat-flow call site may skip the requested-model passthrough" ); assert.strictEqual( countOccurrences(serviceSource, "await resolveChatModelForProvider(provider, requestedModel)"), 5, "tool-result summarizer, lightweight path, both pipeline resolves and the follow-up all thread the pick" ); assert.match(serviceSource, /async function executeAssistantConversation\(\{ userEmail, chat, trimmedMessage, userIp, persistedMessages, requestedModel \}\)/); assert.match(serviceSource, /async function completeChat\(\{ userEmail, chatId, userMessage, userIp, requestedModel \}\)/); assert.match(serviceSource, /async function completeClientFollowUp\(\{ userEmail, chatId, summary, sourceType, context, requestedModel, skipAi = false \}\)/); }); test("the follow-up prompt caps the client-supplied sourceType before embedding", () => { // sourceType is prompt-embedded only (never persisted), so the cap is a // silent slice like context — the ternary keeps empty/absent mapped to "". assert.match(serviceSource, /const ASSISTANT_FOLLOWUP_SOURCETYPE_MAX_CHARS = 200;/); assert.match( serviceSource, /sourceType \? `Action type: \$\{String\(sourceType\)\.trim\(\)\.slice\(0, ASSISTANT_FOLLOWUP_SOURCETYPE_MAX_CHARS\)\}` : ""/ ); }); test("the charset gate accepts provider ids and rejects everything else", () => { // Extract the declared pattern and exercise it: the body contains "/" (it // must, for compound ids like openai/gpt-oss-120b), so it is reconstructed // instead of being matched literally. const declaration = serviceSource.match(/const REQUESTED_MODEL_PATTERN = (\/.*\/[a-z]*);/); assert.ok(declaration, "REQUESTED_MODEL_PATTERN is declared"); const closingSlash = declaration[1].lastIndexOf("/"); const pattern = new RegExp(declaration[1].slice(1, closingSlash), declaration[1].slice(closingSlash + 1)); assert.strictEqual(pattern.test("openai/gpt-oss-120b"), true, "compound provider ids pass"); assert.strictEqual(pattern.test("gemini-2.5-pro"), true, "dotted ids pass"); assert.strictEqual(pattern.test("llama-3.1-8b-instant"), true); assert.strictEqual(pattern.test("openai/gpt-oss 20b"), false, "spaces are rejected"); assert.strictEqual(pattern.test("a\nb"), false, "newlines are rejected"); assert.strictEqual(pattern.test("x;drop"), false, "shell/SQL metachars are rejected"); // Traversal-shaped input passes the charset ("." and "/" are legitimate id // characters) — the live-list allowlist, not the charset, is the boundary // that keeps such a value away from the provider call. assert.strictEqual(pattern.test("../../etc/passwd"), true); assert.strictEqual(pattern.test("a".repeat(500)), true, "the length cap is the separate REQUESTED_MODEL_MAX_LENGTH gate"); }); test("the router passes req.body.model into completeChat and completeClientFollowUp", () => { const chatCall = sliceBetween(routesSource, "service.completeChat({", "userIp:"); assert.ok(chatCall.includes("requestedModel: req.body?.model"), "/chat forwards the raw body field"); const followUpCall = sliceBetween(routesSource, "service.completeClientFollowUp({", "skipAi:"); assert.ok(followUpCall.includes("requestedModel: req.body?.model"), "/client-follow-up forwards the raw body field"); assert.strictEqual( countOccurrences(routesSource, "requestedModel: req.body?.model"), 2, "exactly the two chat endpoints forward the field (validation stays in the service)" ); }); test("the client wires the picker: state, POST bodies, persistence and locking", () => { // Picker state exists next to the provider state (comments allowed between // the three declarations). assert.ok(clientSource.includes(' model: "",'), "state.model is declared"); assert.strictEqual(countOccurrences(clientSource, "modelTouched: false,"), 1, "state.modelTouched is declared once"); assert.strictEqual(countOccurrences(clientSource, "modelLocked: false,"), 1, "state.modelLocked is declared once"); // Both POST bodies send the touched pick only; JSON.stringify drops the // undefined key so absent/untouched stays byte-identical to before. assert.strictEqual( countOccurrences(clientSource, "model: state.modelTouched ? state.model : undefined"), 2, "the chat POST and the client-follow-up POST both carry the pick" ); // The pick is a user gesture: click sets state + persists per provider. const itemClick = clientSource.match( /const val = item\.getAttribute\("data-value"\);\s*\n\s*currentModel = val;\s*\n\s*state\.model = val;\s*\n\s*state\.modelTouched = true;\s*\n\s*writeStoredModelChoice\(currentProvider, val\);/ ); assert.ok(itemClick, "a model click updates state.model, marks it touched and persists it per provider"); // Restore only honors a value that exists in the currently rendered list. assert.match(clientSource, /const stored = state\.modelLocked \? "" : readStoredModelChoice\(currentProvider\);/); assert.match(clientSource, /activeList\.some\(\(m\) => m\.value === stored\)/); assert.ok(clientSource.includes("`adpanel-assistant-model-${provider}`"), "storage is keyed per provider"); // A server-side pin locks the picker: trigger + item clicks guarded. // Count is 3: the two click guards plus the model trigger's keyboard-path // guard, so Enter/Space cannot open the pinned picker either. assert.strictEqual( countOccurrences(clientSource, "if (state.modelLocked) return;"), 3, "the model trigger and the model items refuse clicks while pinned" ); assert.match(clientSource, /hasOwnProperty\.call\(data \|\| {}, "modelLocked"\)/); const lockBranch = sliceBetween(clientSource, "if (state.modelLocked) {", "} else if (!state.modelTouched"); assert.ok(lockBranch.includes("state.modelTouched = false;"), "a pin stops the client from sending model picks"); assert.match(clientSource, /applyModelPickerLock\(\);/, "bootstrap re-applies the lock visuals"); // A bootstrap-driven provider restore resets the pick: picks are // provider-scoped, so the previous provider's id (or its touched flag) must // not leak onto the new provider's list. The reset defers to a server pin. const providerSwitch = sliceBetween( clientSource, "if (provider !== currentProvider) {", "renderProviderItems();" ); assert.ok(providerSwitch.includes('state.model = "";'), "a provider switch clears the previous pick"); assert.ok(providerSwitch.includes("state.modelTouched = false;"), "a provider switch clears the touched flag"); assert.ok(providerSwitch.includes("state.modelLocked"), "the reset defers to a server-side pin"); // The dead static list is gone. assert.strictEqual(countOccurrences(clientSource, "allModels"), 0, "the dead allModels array is removed"); }); test("JSON.stringify drops an undefined model key (backward-compatible bodies)", () => { assert.strictEqual( JSON.stringify({ chatId: 1, message: "m", model: undefined }), '{"chatId":1,"message":"m"}', "an untouched picker sends no model field at all" ); }); test("the client fallback lists mirror the server's DEFAULT_MODELS exactly", () => { const extractPairs = (source, startMarker, endMarker) => { const block = sliceBetween(source, startMarker, endMarker); const pairs = []; const re = /\{\s*value:\s*"([^"]+)",\s*label:\s*"([^"]+)"\s*\}/g; let match; while ((match = re.exec(block))) pairs.push(`${match[1]}|${match[2]}`); assert.ok(pairs.length > 0, `no model pairs found between "${startMarker}" and "${endMarker}"`); return pairs; }; assert.deepStrictEqual( extractPairs(clientSource, "const providerModelsMap = {", "\n };"), extractPairs(serviceSource, "const DEFAULT_MODELS = Object.freeze({", "\n});"), "the static picker fallbacks must equal the fallback the /models endpoint serves" ); });