Skip to content

πŸ™Œ OpenHands: AI-Driven Development

test: strengthen mock settings and auth contracts (#17367)

aivong-openhands87082030828a
diff --git a/__tests__/api/mock-auth-http-contracts.test.ts b/__tests__/api/mock-auth-http-contracts.test.ts
new file mode 100644
index 0000000000..de627d0e87
--- /dev/null
+++ b/__tests__/api/mock-auth-http-contracts.test.ts
@@ -0,0 +1,72 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { http, HttpResponse } from "msw";
+
+import { server } from "#/mocks/node";
+import type { GitUser } from "#/types/git";
+
+const API_ORIGIN = "http://auth.test";
+
+beforeEach(async () => {
+ vi.resetModules();
+ const { AUTH_HANDLERS } = await import("#/mocks/auth-handlers");
+ server.resetHandlers(
+ ...AUTH_HANDLERS,
+ http.all("*", () => new HttpResponse(null, { status: 599 })),
+ );
+});
+
+describe("mock authentication HTTP contracts", () => {
+ it("reports that the cloud proxy is unavailable in mock mode", async () => {
+ const response = await fetch(`${API_ORIGIN}/api/cloud-proxy`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ host: "https://runtime.example.test",
+ method: "GET",
+ path: "/api/status",
+ }),
+ });
+
+ expect(response.status).toBe(503);
+ expect(response.headers.get("content-type")).toContain("application/json");
+ await expect(response.json()).resolves.toEqual({
+ error: "cloud proxy not available in mock mode",
+ });
+ });
+
+ it("returns the mock Git user profile", async () => {
+ const response = await fetch(`${API_ORIGIN}/api/user/info`);
+ const user = (await response.json()) as GitUser;
+
+ expect(response.status).toBe(200);
+ expect(user).toEqual({
+ id: "1",
+ login: "octocat",
+ avatar_url: "https://avatars.githubusercontent.com/u/583231?v=4",
+ company: "GitHub",
+ email: "[email protected]",
+ name: "monalisa octocat",
+ });
+ });
+
+ it("acknowledges authentication", async () => {
+ const response = await fetch(`${API_ORIGIN}/api/authenticate`, {
+ method: "POST",
+ });
+
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({
+ message: "Authenticated",
+ });
+ });
+
+ it("acknowledges logout with a JSON null body", async () => {
+ const response = await fetch(`${API_ORIGIN}/api/logout`, {
+ method: "POST",
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("content-type")).toContain("application/json");
+ await expect(response.json()).resolves.toBeNull();
+ });
+});
diff --git a/__tests__/api/mock-profile-lifecycle.test.ts b/__tests__/api/mock-profile-lifecycle.test.ts
new file mode 100644
index 0000000000..6c46839b08
--- /dev/null
+++ b/__tests__/api/mock-profile-lifecycle.test.ts
@@ -0,0 +1,332 @@
+/* eslint-disable local/no-direct-agent-server-fetch -- HTTP contract tests intentionally exercise mock handlers, including malformed requests. */
+import { http, HttpResponse } from "msw";
+import { server } from "#/mocks/node";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const BASE_URL = "http://localhost:3000";
+
+const jsonRequest = (body: unknown, method = "POST"): RequestInit => ({
+ method,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+});
+
+const saveProfile = (name: string, llm: Record<string, unknown>) =>
+ fetch(`${BASE_URL}/api/profiles/${encodeURIComponent(name)}`, {
+ ...jsonRequest({ llm }),
+ });
+
+const getProfile = (name: string, exposeSecrets?: string) =>
+ fetch(`${BASE_URL}/api/profiles/${encodeURIComponent(name)}`, {
+ headers: exposeSecrets ? { "X-Expose-Secrets": exposeSecrets } : {},
+ });
+
+beforeEach(async () => {
+ vi.resetModules();
+ const handlers = await import("#/mocks/settings-handlers");
+ server.resetHandlers(
+ ...handlers.SETTINGS_HANDLERS,
+ http.all("*", () => new HttpResponse(null, { status: 599 })),
+ );
+});
+
+describe("mock LLM profile lifecycle", () => {
+ it("rejects empty requests and profiles without a usable model", async () => {
+ const empty = await fetch(
+ `${BASE_URL}/api/profiles/empty`,
+ jsonRequest(null),
+ );
+ expect(empty.status).toBe(400);
+ await expect(empty.json()).resolves.toEqual({ detail: "Empty body" });
+
+ const missingLlm = await fetch(
+ `${BASE_URL}/api/profiles/invalid`,
+ jsonRequest({}),
+ );
+ expect(missingLlm.status).toBe(400);
+
+ for (const llm of [{}, { model: 42 }, { model: " " }]) {
+ const response = await saveProfile("invalid", llm);
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toEqual({
+ detail: "Profile requires llm.model",
+ });
+ }
+ });
+
+ it("lists profiles with normalized optional summary fields", async () => {
+ const saved = await saveProfile("model only", {
+ model: "openai/gpt-4o",
+ base_url: "https://api.openai.com/v1",
+ });
+ expect(saved.status).toBe(201);
+ await expect(saved.json()).resolves.toEqual({
+ name: "model only",
+ message: "Profile 'model only' saved",
+ });
+ expect(
+ (
+ await saveProfile("non-string fields", {
+ model: "anthropic/claude-3.5",
+ base_url: 42,
+ api_key: " ",
+ })
+ ).status,
+ ).toBe(201);
+
+ const response = await fetch(`${BASE_URL}/api/profiles`);
+ await expect(response.json()).resolves.toEqual({
+ profiles: [
+ {
+ name: "model only",
+ model: "openai/gpt-4o",
+ base_url: "https://api.openai.com/v1",
+ api_key_set: false,
+ },
+ {
+ name: "non-string fields",
+ model: "anthropic/claude-3.5",
+ base_url: null,
+ api_key_set: false,
+ },
+ ],
+ active_profile: null,
+ });
+ });
+
+ it("returns not found for an unknown profile", async () => {
+ const response = await getProfile("missing profile");
+ expect(response.status).toBe(404);
+ await expect(response.json()).resolves.toEqual({
+ detail: "Profile 'missing profile' not found",
+ });
+ });
+
+ it("redacts, encrypts, or exposes a configured API key", async () => {
+ await saveProfile("secret profile", {
+ model: "openai/gpt-4o",
+ base_url: "https://api.openai.com/v1",
+ api_key: "sk-plaintext",
+ });
+
+ const redacted = await getProfile("secret profile");
+ await expect(redacted.json()).resolves.toMatchObject({
+ name: "secret profile",
+ config: { api_key: null },
+ api_key_set: true,
+ });
+
+ const plaintext = await getProfile("secret profile", "plaintext");
+ await expect(plaintext.json()).resolves.toMatchObject({
+ config: { api_key: "sk-plaintext" },
+ });
+
+ const encrypted = await getProfile("secret profile", "encrypted");
+ await expect(encrypted.json()).resolves.toMatchObject({
+ config: { api_key: "gAAAAA_mock_encrypted_secret profile" },
+ });
+ });
+
+ it("leaves a non-configured API key unchanged in profile details", async () => {
+ await saveProfile("blank key", {
+ model: "openai/gpt-4o",
+ api_key: " ",
+ });
+
+ const response = await getProfile("blank key");
+ await expect(response.json()).resolves.toMatchObject({
+ config: { api_key: " " },
+ api_key_set: false,
+ });
+ });
+
+ it("rejects activation of an unknown profile", async () => {
+ const response = await fetch(`${BASE_URL}/api/profiles/missing/activate`, {
+ method: "POST",
+ });
+ expect(response.status).toBe(404);
+ await expect(response.json()).resolves.toEqual({
+ detail: "Profile 'missing' not found",
+ });
+ });
+
+ it("applies an activated profile and reapplies later saves", async () => {
+ const preserved = {
+ agent_settings: {
+ verification: { critic_enabled: true },
+ condenser: { enable_default_condenser: false, condenser_max_size: 321 },
+ },
+ conversation_settings: { max_iterations: 17 },
+ misc_settings: { app_preferences: { language: "fr" } },
+ };
+ const initialUpdate = await fetch(
+ `${BASE_URL}/api/settings`,
+ jsonRequest(
+ {
+ agent_settings_diff: preserved.agent_settings,
+ conversation_settings_diff: preserved.conversation_settings,
+ misc_settings_diff: preserved.misc_settings,
+ },
+ "PATCH",
+ ),
+ );
+ expect(initialUpdate.status).toBe(200);
+ await saveProfile("active", {
+ model: "openai/gpt-4o",
+ api_key: "first-key",
+ });
+ const activation = await fetch(`${BASE_URL}/api/profiles/active/activate`, {
+ method: "POST",
+ });
+ expect(activation.status).toBe(200);
+ await expect(activation.json()).resolves.toEqual({
+ name: "active",
+ message: "Profile 'active' activated and applied to current settings",
+ llm_applied: true,
+ });
+
+ await saveProfile("inactive", { model: "openhands/minimax-m2.7" });
+ const unchangedSettings = await fetch(`${BASE_URL}/api/settings`);
+ const activatedSettings = await unchangedSettings.json();
+ expect(activatedSettings).toMatchObject(preserved);
+ expect(activatedSettings).toMatchObject({
+ agent_settings: { llm: { model: "openai/gpt-4o" } },
+ llm_api_key_is_set: true,
+ });
+
+ await saveProfile("active", {
+ model: "anthropic/claude-opus-4-8",
+ });
+
+ const settings = await fetch(`${BASE_URL}/api/settings`);
+ const updatedSettings = await settings.json();
+ expect(updatedSettings).toMatchObject(preserved);
+ expect(updatedSettings).toMatchObject({
+ agent_settings: {
+ llm: { model: "anthropic/claude-opus-4-8" },
+ },
+ llm_api_key_is_set: false,
+ });
+ });
+
+ it("validates rename requests and prevents collisions", async () => {
+ const missing = await fetch(
+ `${BASE_URL}/api/profiles/missing/rename`,
+ jsonRequest({ new_name: "new" }),
+ );
+ expect(missing.status).toBe(404);
+ await expect(missing.json()).resolves.toEqual({
+ detail: "Profile 'missing' not found",
+ });
+
+ await saveProfile("first", { model: "openai/gpt-4o" });
+ await saveProfile("second", { model: "openai/gpt-5.5" });
+
+ for (const body of [null, {}, { new_name: " " }]) {
+ const invalid = await fetch(
+ `${BASE_URL}/api/profiles/first/rename`,
+ jsonRequest(body),
+ );
+ expect(invalid.status).toBe(400);
+ await expect(invalid.json()).resolves.toEqual({
+ detail: "new_name is required",
+ });
+ }
+
+ const collision = await fetch(
+ `${BASE_URL}/api/profiles/first/rename`,
+ jsonRequest({ new_name: "second" }),
+ );
+ expect(collision.status).toBe(409);
+ await expect(collision.json()).resolves.toEqual({
+ detail: "Profile 'second' already exists",
+ });
+ });
+
+ it("supports no-op and inactive profile renames", async () => {
+ await saveProfile("unchanged", { model: "openai/gpt-4o" });
+
+ const sameName = await fetch(
+ `${BASE_URL}/api/profiles/unchanged/rename`,
+ jsonRequest({ new_name: " unchanged " }),
+ );
+ expect(sameName.status).toBe(200);
+ await expect(sameName.json()).resolves.toEqual({
+ name: "unchanged",
+ message: "Profile 'unchanged' renamed to 'unchanged'",
+ });
+
+ const renamed = await fetch(
+ `${BASE_URL}/api/profiles/unchanged/rename`,
+ jsonRequest({ new_name: "renamed" }),
+ );
+ expect(renamed.status).toBe(200);
+ await expect(renamed.json()).resolves.toEqual({
+ name: "renamed",
+ message: "Profile 'unchanged' renamed to 'renamed'",
+ });
+
+ const list = await fetch(`${BASE_URL}/api/profiles`);
+ await expect(list.json()).resolves.toMatchObject({ active_profile: null });
+ });
+
+ it("keeps an active profile active when it is renamed", async () => {
+ await saveProfile("active", {
+ model: "openai/gpt-4o",
+ api_key: "sk-test",
+ });
+ await fetch(`${BASE_URL}/api/profiles/active/activate`, { method: "POST" });
+
+ const response = await fetch(
+ `${BASE_URL}/api/profiles/active/rename`,
+ jsonRequest({ new_name: "renamed active" }),
+ );
+ expect(response.status).toBe(200);
+
+ const list = await fetch(`${BASE_URL}/api/profiles`);
+ await expect(list.json()).resolves.toMatchObject({
+ profiles: [expect.objectContaining({ name: "renamed active" })],
+ active_profile: "renamed active",
+ });
+ const settings = await fetch(`${BASE_URL}/api/settings`);
+ await expect(settings.json()).resolves.toMatchObject({
+ agent_settings: { llm: { model: "openai/gpt-4o" } },
+ llm_api_key_is_set: true,
+ });
+ });
+
+ it("deletes inactive and active profiles", async () => {
+ await saveProfile("inactive", { model: "openai/gpt-4o" });
+ await saveProfile("active", { model: "openai/gpt-5.5" });
+ await fetch(`${BASE_URL}/api/profiles/active/activate`, { method: "POST" });
+
+ const inactiveDelete = await fetch(`${BASE_URL}/api/profiles/inactive`, {
+ method: "DELETE",
+ });
+ expect(inactiveDelete.status).toBe(200);
+ await expect(inactiveDelete.json()).resolves.toEqual({
+ name: "inactive",
+ message: "Profile 'inactive' deleted",
+ });
+
+ const afterInactiveDelete = await fetch(`${BASE_URL}/api/profiles`);
+ await expect(afterInactiveDelete.json()).resolves.toMatchObject({
+ active_profile: "active",
+ });
+
+ const activeDelete = await fetch(`${BASE_URL}/api/profiles/active`, {
+ method: "DELETE",
+ });
+ expect(activeDelete.status).toBe(200);
+ await expect(activeDelete.json()).resolves.toEqual({
+ name: "active",
+ message: "Profile 'active' deleted",
+ });
+
+ const list = await fetch(`${BASE_URL}/api/profiles`);
+ await expect(list.json()).resolves.toEqual({
+ profiles: [],
+ active_profile: null,
+ });
+ });
+});
diff --git a/__tests__/api/mock-secrets-api.test.ts b/__tests__/api/mock-secrets-api.test.ts
new file mode 100644
index 0000000000..d30dd6bb8a
--- /dev/null
+++ b/__tests__/api/mock-secrets-api.test.ts
@@ -0,0 +1,143 @@
+import { http, HttpResponse } from "msw";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { server } from "#/mocks/node";
+
+const SECRETS_URL = "http://localhost:3000/api/settings/secrets";
+const UNEXPECTED_REQUEST_HANDLER = http.all(
+ "*",
+ () => new HttpResponse(null, { status: 599 }),
+);
+
+const secretUrl = (name: string) =>
+ `${SECRETS_URL}/${encodeURIComponent(name)}`;
+
+beforeEach(async () => {
+ vi.resetModules();
+ const { SECRETS_HANDLERS } = await import("#/mocks/secrets-handlers");
+ server.resetHandlers(...SECRETS_HANDLERS, UNEXPECTED_REQUEST_HANDLER);
+});
+
+describe("mock secrets API", () => {
+ it("declines a secret-list request outside the supported API root", async () => {
+ const response = await fetch(SECRETS_URL.replace("/api/", "/extra/api/"));
+ expect(response.status).toBe(599);
+ });
+
+ it("lists secret metadata without exposing stored values", async () => {
+ const response = await fetch(SECRETS_URL);
+ const body = (await response.json()) as {
+ secrets: Array<Record<string, unknown>>;
+ };
+
+ expect(response.status).toBe(200);
+ expect(body).toEqual({
+ secrets: [
+ { name: "OpenAI_API_Key", description: "OpenAI API Key" },
+ {
+ name: "Google_Maps_API_Key",
+ description: "Google Maps API Key",
+ },
+ ],
+ });
+ expect(body.secrets.every((secret) => !("value" in secret))).toBe(true);
+ });
+
+ it("returns a stored value as plain text and reports an unknown name", async () => {
+ const found = await fetch(secretUrl("OpenAI_API_Key"));
+
+ expect(found.status).toBe(200);
+ expect(found.headers.get("content-type")).toBe("text/plain");
+ await expect(found.text()).resolves.toBe("test-123");
+
+ const secondSeed = await fetch(secretUrl("Google_Maps_API_Key"));
+
+ expect(secondSeed.status).toBe(200);
+ await expect(secondSeed.text()).resolves.toBe("test-123");
+
+ const missing = await fetch(secretUrl("unknown-secret"));
+
+ expect(missing.status).toBe(404);
+ await expect(missing.json()).resolves.toEqual({
+ detail: "Secret not found",
+ });
+ });
+
+ it("persists create, update, list, read, and delete transitions", async () => {
+ const name = "Coverage_API_Key";
+
+ try {
+ const created = await fetch(SECRETS_URL, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name,
+ value: "initial-value",
+ description: "Coverage secret",
+ }),
+ });
+
+ expect(created.status).toBe(200);
+ await expect(created.json()).resolves.toEqual({
+ name,
+ description: "Coverage secret",
+ });
+
+ const listed = await fetch(SECRETS_URL);
+ const listedBody = (await listed.json()) as {
+ secrets: Array<Record<string, unknown>>;
+ };
+ expect(listedBody.secrets).toContainEqual({
+ name,
+ description: "Coverage secret",
+ });
+ expect(
+ listedBody.secrets.find((secret) => secret.name === name),
+ ).not.toHaveProperty("value");
+
+ const firstRead = await fetch(secretUrl(name));
+ await expect(firstRead.text()).resolves.toBe("initial-value");
+
+ const updated = await fetch(SECRETS_URL, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name, value: "updated-value" }),
+ });
+ await expect(updated.json()).resolves.toEqual({ name });
+
+ const secondRead = await fetch(secretUrl(name));
+ await expect(secondRead.text()).resolves.toBe("updated-value");
+
+ const deleted = await fetch(secretUrl(name), { method: "DELETE" });
+ expect(deleted.status).toBe(200);
+ await expect(deleted.json()).resolves.toEqual({ deleted: true });
+
+ const afterDelete = await fetch(secretUrl(name));
+ expect(afterDelete.status).toBe(404);
+
+ const deleteAgain = await fetch(secretUrl(name), { method: "DELETE" });
+ expect(deleteAgain.status).toBe(404);
+ await expect(deleteAgain.json()).resolves.toEqual({
+ detail: "Secret not found",
+ });
+ } finally {
+ await fetch(secretUrl(name), { method: "DELETE" });
+ }
+ });
+
+ it.each([
+ ["null body", null],
+ ["missing name", { value: "secret-value" }],
+ ["missing value", { name: "Incomplete_Secret" }],
+ ])("rejects an upsert with a %s", async (_case, payload) => {
+ const response = await fetch(SECRETS_URL, {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(payload),
+ });
+
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toEqual({
+ detail: "name and value are required",
+ });
+ });
+});
diff --git a/__tests__/api/mock-settings-catalog.test.ts b/__tests__/api/mock-settings-catalog.test.ts
new file mode 100644
index 0000000000..084e4e2af1
--- /dev/null
+++ b/__tests__/api/mock-settings-catalog.test.ts
@@ -0,0 +1,359 @@
+import { http, HttpResponse } from "msw";
+import { server } from "#/mocks/node";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ OPENAI_SUBSCRIPTION_DEVICE_POLL_PATH,
+ OPENAI_SUBSCRIPTION_DEVICE_START_PATH,
+ OPENAI_SUBSCRIPTION_LOGOUT_PATH,
+ OPENAI_SUBSCRIPTION_MODELS_PATH,
+ OPENAI_SUBSCRIPTION_STATUS_PATH,
+} from "#/constants/llm-subscription";
+let createMockWebClientConfig: typeof import("#/mocks/settings-handlers").createMockWebClientConfig;
+
+const BASE_URL = "http://localhost:3000";
+
+const fetchJson = async <T>(path: string, init?: RequestInit) => {
+ const response = await fetch(`${BASE_URL}${path}`, init);
+ expect(response.ok).toBe(true);
+ return (await response.json()) as T;
+};
+
+beforeEach(async () => {
+ vi.resetModules();
+ const handlers = await import("#/mocks/settings-handlers");
+ createMockWebClientConfig = handlers.createMockWebClientConfig;
+ server.resetHandlers(
+ ...handlers.SETTINGS_HANDLERS,
+ http.all("*", () => new HttpResponse(null, { status: 599 })),
+ );
+});
+
+describe("mock agent-server discovery", () => {
+ it("builds a complete web-client config with optional overrides", () => {
+ const defaults = createMockWebClientConfig();
+ expect(defaults).toEqual({
+ feature_flags: {
+ hide_llm_settings: false,
+ hide_users_page: false,
+ },
+ providers_configured: [],
+ maintenance_start_time: null,
+ recaptcha_site_key: null,
+ faulty_models: [],
+ error_message: null,
+ updated_at: expect.any(String),
+ });
+
+ expect(
+ createMockWebClientConfig({
+ feature_flags: {
+ hide_llm_settings: true,
+ hide_users_page: false,
+ },
+ updated_at: "2030-01-01T00:00:00.000Z",
+ }),
+ ).toEqual({
+ ...defaults,
+ feature_flags: {
+ hide_llm_settings: true,
+ hide_users_page: false,
+ },
+ updated_at: "2030-01-01T00:00:00.000Z",
+ });
+ });
+
+ it("publishes server metadata and the legacy model catalog", async () => {
+ const serverInfo = await fetchJson<{
+ version: string;
+ usable_tools: string[];
+ agents: string[];
+ default_agent: string;
+ models: string[];
+ security_analyzers: string[];
+ }>("/server_info");
+ expect(serverInfo).toMatchObject({
+ version: "1.36.1",
+ usable_tools: [
+ "terminal",
+ "file_editor",
+ "task_tracker",
+ "browser_tool_set",
+ ],
+ agents: ["CodeActAgent"],
+ default_agent: "CodeActAgent",
+ security_analyzers: ["llm", "none"],
+ });
+ expect(serverInfo.models).toContain("openhands/glm-5.2");
+
+ const options = await fetchJson<{
+ models: string[];
+ verified_models: string[];
+ verified_providers: string[];
+ default_model: string;
+ }>("/api/options/models");
+ expect(options.default_model).toBe("openai/gpt-5.6-sol");
+ expect(options.models).toEqual(serverInfo.models);
+ expect(options.verified_models).toEqual([
+ "claude-opus-4-5-20251101",
+ "claude-sonnet-4-5-20250929",
+ ]);
+ expect(options.verified_providers).toContain("openai");
+ expect(
+ options.verified_providers.every(
+ (provider) => provider.trim().length > 0,
+ ),
+ ).toBe(true);
+ expect(new Set(options.verified_providers).size).toBe(
+ options.verified_providers.length,
+ );
+
+ await expect(
+ fetchJson<string[]>("/api/options/security-analyzers"),
+ ).resolves.toEqual(["llm", "none"]);
+ });
+
+ it("publishes normalized model and provider endpoints", async () => {
+ const modelCatalog = await fetchJson<{ models: string[] }>(
+ "/api/llm/models",
+ );
+ expect(modelCatalog.models).toContain("openai/gpt-4o");
+ expect(
+ modelCatalog.models.every((model) => /^[^/]+\/.+$/.test(model)),
+ ).toBe(true);
+
+ const verified = await fetchJson<{
+ models: Record<string, string[]>;
+ }>("/api/llm/models/verified");
+ expect(verified.models.openai).toEqual([
+ "gpt-5.5",
+ "gpt-5.6-sol",
+ "gpt-6-astra",
+ ]);
+ expect(verified.models.anthropic).toHaveLength(3);
+ expect(verified.models.anthropic).toEqual(
+ expect.arrayContaining([
+ "claude-opus-4-5-20251101",
+ "claude-opus-4-8",
+ "claude-sonnet-4-5-20250929",
+ ]),
+ );
+ expect(verified.models.openhands).toEqual([
+ "claude-sonnet-4-5-20250929",
+ "claude-opus-4-5-20251101",
+ "deepseek-v4-flash",
+ "glm-5.2",
+ ]);
+
+ const providers = await fetchJson<{ providers: string[] }>(
+ "/api/llm/providers",
+ );
+ expect(providers.providers).toEqual([
+ "anthropic",
+ "openai",
+ "openhands",
+ "sambanova",
+ ]);
+ });
+
+ it("searches providers case-insensitively and filters verification", async () => {
+ const all = await fetchJson<{
+ items: { name: string; verified: boolean }[];
+ next_page_id: null;
+ }>("/api/v1/config/providers/search");
+ expect(all.next_page_id).toBeNull();
+ expect(all.items).toEqual([
+ { name: "anthropic", verified: true },
+ { name: "openai", verified: true },
+ { name: "openhands", verified: true },
+ { name: "sambanova", verified: false },
+ ]);
+
+ const matching = await fetchJson<{ items: { name: string }[] }>(
+ "/api/v1/config/providers/search?query=OPEN&verified__eq=true",
+ );
+ expect(matching.items.map(({ name }) => name)).toEqual([
+ "openai",
+ "openhands",
+ ]);
+
+ const unverified = await fetchJson<{
+ items: { name: string; verified: boolean }[];
+ }>("/api/v1/config/providers/search?verified__eq=false");
+ expect(unverified.items).toEqual([{ name: "sambanova", verified: false }]);
+ });
+
+ it("searches models by provider, name, and verification", async () => {
+ const all = await fetchJson<{
+ items: {
+ provider: string | null;
+ name: string;
+ verified: boolean;
+ free: boolean;
+ default: boolean;
+ }[];
+ }>("/api/v1/config/models/search");
+ expect(all.items).toContainEqual({
+ provider: "openai",
+ name: "gpt-4o",
+ verified: false,
+ free: false,
+ default: false,
+ });
+ expect(all.items).toContainEqual({
+ provider: "anthropic",
+ name: "claude-opus-4-8",
+ verified: true,
+ free: false,
+ default: false,
+ });
+
+ const matching = await fetchJson<{ items: unknown[] }>(
+ "/api/v1/config/models/search?provider__eq=anthropic&query=OPUS&verified__eq=true",
+ );
+ expect(matching.items).toEqual([
+ {
+ provider: "anthropic",
+ name: "claude-opus-4-5-20251101",
+ verified: true,
+ free: false,
+ default: false,
+ },
+ {
+ provider: "anthropic",
+ name: "claude-opus-4-8",
+ verified: true,
+ free: false,
+ default: false,
+ },
+ ]);
+
+ const unverified = await fetchJson<{ items: unknown[] }>(
+ "/api/v1/config/models/search?provider__eq=openai&verified__eq=false",
+ );
+ expect(unverified.items).toEqual([
+ {
+ provider: "openai",
+ name: "gpt-3.5-turbo",
+ verified: false,
+ free: false,
+ default: false,
+ },
+ {
+ provider: "openai",
+ name: "gpt-4o",
+ verified: false,
+ free: false,
+ default: false,
+ },
+ {
+ provider: "openai",
+ name: "gpt-4o-mini",
+ verified: false,
+ free: false,
+ default: false,
+ },
+ ]);
+ });
+
+ it("publishes the web-client configuration endpoint", async () => {
+ const config = await fetchJson<{
+ feature_flags: Record<string, boolean>;
+ updated_at: string;
+ }>("/api/v1/web-client/config");
+ expect(config).toMatchObject({
+ feature_flags: {
+ hide_llm_settings: false,
+ hide_users_page: false,
+ },
+ providers_configured: [],
+ faulty_models: [],
+ updated_at: expect.any(String),
+ });
+ });
+
+ it("marks the free default OpenHands model as available and verified", async () => {
+ const result = await fetchJson<{ items: unknown[] }>(
+ "/api/v1/config/models/search?provider__eq=openhands&query=glm-5.2",
+ );
+ expect(result.items).toEqual([
+ {
+ provider: "openhands",
+ name: "glm-5.2",
+ verified: true,
+ free: true,
+ default: true,
+ },
+ ]);
+ });
+
+ it("falls back to deterministic settings when shared defaults omit optional sections", async () => {
+ vi.resetModules();
+ vi.doMock("#/services/settings", () => ({ DEFAULT_SETTINGS: {} }));
+
+ try {
+ const { MOCK_DEFAULT_USER_SETTINGS: settings } =
+ await import("#/mocks/settings-handlers");
+
+ expect(settings).toMatchObject({
+ agent_settings: {
+ llm: { model: "openhands/claude-opus-4-5-20251101" },
+ },
+ conversation_settings: {},
+ });
+ } finally {
+ vi.doUnmock("#/services/settings");
+ vi.resetModules();
+ }
+ });
+});
+
+describe("mock OpenAI subscription", () => {
+ it("offers models and a deterministic device-login challenge", async () => {
+ await expect(fetchJson(OPENAI_SUBSCRIPTION_MODELS_PATH)).resolves.toEqual({
+ vendor: "openai",
+ models: ["gpt-5.2", "gpt-5.3-codex"],
+ });
+
+ await expect(
+ fetchJson(OPENAI_SUBSCRIPTION_DEVICE_START_PATH, { method: "POST" }),
+ ).resolves.toEqual({
+ device_code: "mock-device-code",
+ user_code: "MOCK-CODE",
+ verification_uri: "https://auth.openai.com/activate",
+ verification_uri_complete:
+ "https://auth.openai.com/activate?user_code=MOCK-CODE",
+ interval: 1,
+ expires_in: 900,
+ });
+ });
+
+ it("moves through disconnected, connected, and logged-out states", async () => {
+ await expect(fetchJson(OPENAI_SUBSCRIPTION_STATUS_PATH)).resolves.toEqual({
+ connected: false,
+ account_email: null,
+ expires_at: null,
+ });
+
+ await expect(
+ fetchJson(OPENAI_SUBSCRIPTION_DEVICE_POLL_PATH, { method: "POST" }),
+ ).resolves.toEqual({
+ connected: true,
+ account_email: "[email protected]",
+ expires_at: null,
+ });
+ await expect(fetchJson(OPENAI_SUBSCRIPTION_STATUS_PATH)).resolves.toEqual({
+ connected: true,
+ account_email: "[email protected]",
+ expires_at: null,
+ });
+
+ await expect(
+ fetchJson(OPENAI_SUBSCRIPTION_LOGOUT_PATH, { method: "POST" }),
+ ).resolves.toEqual({ connected: false });
+ await expect(fetchJson(OPENAI_SUBSCRIPTION_STATUS_PATH)).resolves.toEqual({
+ connected: false,
+ account_email: null,
+ expires_at: null,
+ });
+ });
+});
diff --git a/__tests__/api/mock-settings-persistence.test.ts b/__tests__/api/mock-settings-persistence.test.ts
new file mode 100644
index 0000000000..98fa8e3603
--- /dev/null
+++ b/__tests__/api/mock-settings-persistence.test.ts
@@ -0,0 +1,811 @@
+/* eslint-disable local/no-direct-agent-server-fetch -- HTTP contract tests intentionally exercise mock handlers, including malformed requests. */
+let resetTestHandlersMockSettings: typeof import("#/mocks/settings-handlers").resetTestHandlersMockSettings;
+import { http, HttpResponse } from "msw";
+import { server } from "#/mocks/node";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { SettingsSchema } from "#/types/settings";
+import {
+ OPENAI_SUBSCRIPTION_DEVICE_POLL_PATH,
+ OPENAI_SUBSCRIPTION_STATUS_PATH,
+} from "#/constants/llm-subscription";
+
+const BASE_URL = "http://localhost:3000";
+
+const jsonRequest = (body: unknown, method: "PATCH" | "POST"): RequestInit => ({
+ method,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+});
+
+const getJson = async <T>(path: string, init?: RequestInit) => {
+ const response = await fetch(`${BASE_URL}${path}`, init);
+ return { response, body: (await response.json()) as T };
+};
+
+beforeEach(async () => {
+ vi.resetModules();
+ const handlers = await import("#/mocks/settings-handlers");
+ resetTestHandlersMockSettings = handlers.resetTestHandlersMockSettings;
+ server.resetHandlers(
+ ...handlers.SETTINGS_HANDLERS,
+ http.all("*", () => new HttpResponse(null, { status: 599 })),
+ );
+});
+
+describe("mock settings schemas and state", () => {
+ it("declines settings requests outside the supported API root", async () => {
+ expect((await fetch(`${BASE_URL}/extra/api/settings`)).status).toBe(599);
+ });
+
+ it("replaces an existing array with an object patch without retaining array indexes", async () => {
+ await getJson(
+ "/api/settings",
+ jsonRequest(
+ { agent_settings_diff: { llm: { stop: ["old", "other"] } } },
+ "PATCH",
+ ),
+ );
+ const result = await getJson<{
+ agent_settings: { llm: { stop: unknown } };
+ }>(
+ "/api/settings",
+ jsonRequest(
+ { agent_settings_diff: { llm: { stop: { mode: "new" } } } },
+ "PATCH",
+ ),
+ );
+ expect(result.response.status).toBe(200);
+ expect(result.body.agent_settings.llm.stop).toEqual({ mode: "new" });
+ });
+
+ it("resets mutated settings, active profiles, and subscription state in the same module instance", async () => {
+ const initial = await getJson("/api/settings");
+ const updated = await getJson(
+ "/api/settings",
+ jsonRequest(
+ {
+ conversation_settings_diff: { max_iterations: 7 },
+ misc_settings_diff: { app_preferences: { language: "fr" } },
+ },
+ "PATCH",
+ ),
+ );
+ expect(updated.response.status).toBe(200);
+ expect(
+ (
+ await getJson(
+ "/api/profiles/reset-me",
+ jsonRequest({ llm: { model: "openai/gpt-4o" } }, "POST"),
+ )
+ ).response.status,
+ ).toBe(201);
+ expect(
+ (await getJson("/api/profiles/reset-me/activate", { method: "POST" }))
+ .response.status,
+ ).toBe(200);
+ const profilesBefore = await getJson("/api/profiles");
+ expect(profilesBefore.body).toMatchObject({
+ active_profile: "reset-me",
+ profiles: [{ name: "reset-me" }],
+ });
+ expect(
+ (await getJson(OPENAI_SUBSCRIPTION_DEVICE_POLL_PATH, { method: "POST" }))
+ .body,
+ ).toMatchObject({ connected: true });
+ resetTestHandlersMockSettings();
+ expect((await getJson("/api/settings")).body).toEqual(initial.body);
+ expect((await getJson("/api/profiles")).body).toEqual({
+ profiles: [],
+ active_profile: null,
+ });
+ expect((await getJson(OPENAI_SUBSCRIPTION_STATUS_PATH)).body).toEqual({
+ connected: false,
+ account_email: null,
+ expires_at: null,
+ });
+ });
+ it("serves field contracts that control defaults, masking, validation, and conditional settings", async () => {
+ const contract = (
+ section: string,
+ value_type: string,
+ defaultValue: unknown,
+ prominence: string,
+ overrides: Record<string, unknown> = {},
+ ) => ({
+ section,
+ value_type,
+ default: defaultValue,
+ prominence,
+ secret: false,
+ required: false,
+ choices: [],
+ depends_on: [],
+ ...overrides,
+ });
+ const critic = { depends_on: ["verification.critic_enabled"] };
+ const refinement = {
+ depends_on: [
+ "verification.critic_enabled",
+ "verification.enable_iterative_refinement",
+ ],
+ };
+ const expectedAgent = {
+ enable_sub_agents: contract("general", "boolean", false, "major"),
+ enable_switch_llm_tool: contract("general", "boolean", true, "major"),
+ tool_concurrency_limit: contract("general", "integer", 1, "major"),
+ "llm.model": contract("llm", "string", "openai/gpt-5.6-sol", "critical", {
+ required: true,
+ }),
+ "llm.api_key": contract("llm", "string", null, "critical", {
+ secret: true,
+ }),
+ "llm.base_url": contract("llm", "string", null, "critical"),
+ "llm.temperature": contract("llm", "number", null, "minor"),
+ "verification.critic_enabled": contract(
+ "verification",
+ "boolean",
+ false,
+ "critical",
+ ),
+ "verification.critic_mode": contract(
+ "verification",
+ "string",
+ "finish_and_message",
+ "major",
+ {
+ ...critic,
+ choices: ["finish_and_message", "all_actions"],
+ },
+ ),
+ "verification.enable_iterative_refinement": contract(
+ "verification",
+ "boolean",
+ false,
+ "critical",
+ critic,
+ ),
+ "verification.critic_api_key": contract(
+ "verification",
+ "string",
+ null,
+ "critical",
+ { ...critic, secret: true },
+ ),
+ "verification.critic_threshold": contract(
+ "verification",
+ "number",
+ 0.6,
+ "minor",
+ refinement,
+ ),
+ "verification.max_refinement_iterations": contract(
+ "verification",
+ "integer",
+ 3,
+ "minor",
+ refinement,
+ ),
+ "verification.critic_server_url": contract(
+ "verification",
+ "string",
+ null,
+ "minor",
+ critic,
+ ),
+ "verification.critic_model_name": contract(
+ "verification",
+ "string",
+ null,
+ "minor",
+ critic,
+ ),
+ "condenser.enable_default_condenser": contract(
+ "condenser",
+ "boolean",
+ true,
+ "critical",
+ { required: true },
+ ),
+ "condenser.condenser_max_size": contract(
+ "condenser",
+ "integer",
+ null,
+ "major",
+ ),
+ "agent_context.load_memory": contract(
+ "agent_context",
+ "boolean",
+ false,
+ "major",
+ ),
+ };
+ const expectedConversation = {
+ max_iterations: contract("general", "integer", 500, "major", {
+ required: true,
+ }),
+ confirmation_mode: contract("verification", "boolean", false, "major", {
+ required: true,
+ }),
+ security_analyzer: contract("verification", "string", "llm", "major", {
+ choices: ["llm", "none"],
+ depends_on: ["confirmation_mode"],
+ }),
+ };
+ for (const version of ["", "/v1"]) {
+ for (const [schema, expected] of [
+ ["agent", expectedAgent],
+ ["conversation", expectedConversation],
+ ] as const) {
+ const { response, body } = await getJson<SettingsSchema>(
+ `/api${version}/settings/${schema}-schema`,
+ );
+ expect(response.status).toBe(200);
+ const fields = body.sections.flatMap(
+ ({ key: sectionKey, fields: sectionFields }) =>
+ sectionFields.map(
+ ({
+ key,
+ section,
+ value_type,
+ default: defaultValue,
+ prominence,
+ secret,
+ required,
+ choices,
+ depends_on,
+ }) => {
+ expect(section).toBe(sectionKey);
+ return [
+ key,
+ {
+ section,
+ value_type,
+ default: defaultValue,
+ prominence,
+ secret,
+ required,
+ choices: choices.map(({ value }) => value),
+ depends_on,
+ },
+ ];
+ },
+ ),
+ );
+ expect(Object.fromEntries(fields)).toEqual(expected);
+ }
+ }
+ });
+
+ it("serves both supported versions of each settings schema", async () => {
+ for (const path of [
+ "/api/settings/agent-schema",
+ "/api/v1/settings/agent-schema",
+ ]) {
+ const { response, body } = await getJson<{
+ model_name: string;
+ sections: { key: string }[];
+ }>(path);
+ expect(response.ok).toBe(true);
+ expect(body.model_name).toBe("AgentSettings");
+ expect(body.sections.map(({ key }) => key)).toEqual([
+ "general",
+ "llm",
+ "verification",
+ "condenser",
+ "agent_context",
+ ]);
+ }
+
+ for (const path of [
+ "/api/settings/conversation-schema",
+ "/api/v1/settings/conversation-schema",
+ ]) {
+ const { response, body } = await getJson<{
+ model_name: string;
+ sections: { key: string }[];
+ }>(path);
+ expect(response.ok).toBe(true);
+ expect(body).toMatchObject({
+ model_name: "ConversationSettings",
+ sections: [{ key: "general" }, { key: "verification" }],
+ });
+ }
+ });
+
+ it("returns deterministic defaults from both settings APIs", async () => {
+ const modern = await getJson<{
+ agent_settings: { llm: { model: string } };
+ conversation_settings: { confirmation_mode: boolean };
+ llm_api_key_is_set: boolean;
+ misc_settings: { app_preferences: Record<string, unknown> };
+ }>("/api/settings");
+ expect(modern.response.ok).toBe(true);
+ expect(modern.body).toMatchObject({
+ agent_settings: {
+ llm: { model: "openai/gpt-5.6-sol" },
+ condenser: { enable_default_condenser: true, condenser_max_size: null },
+ enable_sub_agents: false,
+ tool_concurrency_limit: 1,
+ },
+ conversation_settings: { confirmation_mode: false },
+ llm_api_key_is_set: false,
+ misc_settings: {
+ app_preferences: {
+ language: null,
+ user_consents_to_analytics: null,
+ enable_sound_notifications: null,
+ git_user_name: null,
+ git_user_email: null,
+ disabled_skills: [],
+ },
+ },
+ });
+
+ const legacy = await getJson<{ agent_settings: unknown }>(
+ "/api/v1/settings",
+ );
+ expect(legacy.response.ok).toBe(true);
+ expect(legacy.body.agent_settings).toEqual(
+ expect.objectContaining({
+ llm: expect.objectContaining({ model: "openai/gpt-5.6-sol" }),
+ }),
+ );
+ });
+
+ it("rejects empty and no-op incremental updates", async () => {
+ const nullBody = await getJson<{ error: string }>(
+ "/api/settings",
+ jsonRequest(null, "PATCH"),
+ );
+ expect(nullBody.response.status).toBe(400);
+ expect(nullBody.body).toEqual({ error: "Empty body" });
+
+ for (const body of [
+ {},
+ {
+ agent_settings_diff: null,
+ conversation_settings_diff: null,
+ misc_settings_diff: null,
+ },
+ ]) {
+ const result = await getJson<{ error: string }>(
+ "/api/settings",
+ jsonRequest(body, "PATCH"),
+ );
+ expect(result.response.status).toBe(400);
+ expect(result.body.error).toContain("At least one of");
+ }
+ });
+
+ it("deep-merges agent settings and persists all supported diff groups", async () => {
+ const update = await getJson<{
+ agent_settings: Record<string, unknown>;
+ conversation_settings: Record<string, unknown>;
+ llm_api_key_is_set: boolean;
+ misc_settings: { app_preferences: Record<string, unknown> };
+ }>(
+ "/api/settings",
+ jsonRequest(
+ {
+ agent_settings_diff: {
+ llm: {
+ api_key: "sk-secret",
+ base_url: "https://api.example.test/v1",
+ stop: ["DONE"],
+ parameters: { reasoning: "high" },
+ },
+ verification: { critic_enabled: true },
+ mcp_config: null,
+ },
+ conversation_settings_diff: {
+ max_iterations: 12,
+ confirmation_mode: true,
+ },
+ misc_settings_diff: {
+ app_preferences: {
+ language: "fr",
+ disabled_skills: ["legacy-skill"],
+ },
+ },
+ },
+ "PATCH",
+ ),
+ );
+ expect(update.response.ok).toBe(true);
+ expect(update.body).toMatchObject({
+ agent_settings: {
+ llm: {
+ model: "openai/gpt-5.6-sol",
+ api_key: "sk-secret",
+ base_url: "https://api.example.test/v1",
+ stop: ["DONE"],
+ parameters: { reasoning: "high" },
+ },
+ verification: {
+ critic_enabled: true,
+ enable_iterative_refinement: false,
+ },
+ mcp_config: null,
+ },
+ conversation_settings: {
+ max_iterations: 12,
+ confirmation_mode: true,
+ },
+ llm_api_key_is_set: true,
+ misc_settings: {
+ app_preferences: {
+ language: "fr",
+ disabled_skills: ["legacy-skill"],
+ },
+ },
+ });
+ });
+
+ it("replaces incompatible nested values without leaking their previous shape", async () => {
+ const result = await getJson<{
+ agent_settings: {
+ verification: unknown;
+ llm: { model: unknown };
+ };
+ }>(
+ "/api/settings",
+ jsonRequest(
+ {
+ agent_settings_diff: {
+ verification: "disabled",
+ llm: { model: { family: "custom" } },
+ },
+ },
+ "PATCH",
+ ),
+ );
+
+ expect(result.body.agent_settings.verification).toBe("disabled");
+ expect(result.body.agent_settings.llm.model).toEqual({ family: "custom" });
+ });
+
+ it("redacts, encrypts, or exposes persisted settings secrets", async () => {
+ await fetch(
+ `${BASE_URL}/api/settings`,
+ jsonRequest(
+ { agent_settings_diff: { llm: { api_key: "sk-abcdefghijk" } } },
+ "PATCH",
+ ),
+ );
+
+ const redacted = await getJson<{
+ agent_settings: { llm: { api_key: string } };
+ }>("/api/settings");
+ expect(redacted.body.agent_settings.llm.api_key).toBe("**********");
+
+ const plaintext = await getJson<{
+ agent_settings: { llm: { api_key: string } };
+ }>("/api/settings", { headers: { "X-Expose-Secrets": "plaintext" } });
+ expect(plaintext.body.agent_settings.llm.api_key).toBe("sk-abcdefghijk");
+
+ const encrypted = await getJson<{
+ agent_settings: { llm: { api_key: string } };
+ }>("/api/settings", { headers: { "X-Expose-Secrets": "encrypted" } });
+ expect(encrypted.body.agent_settings.llm.api_key).toBe(
+ "gAAAAA_mock_encrypted_sk-abcde",
+ );
+ });
+
+ it("does not mark blank or non-string API keys as configured", async () => {
+ for (const apiKey of ["", " ", 42]) {
+ resetTestHandlersMockSettings();
+ const result = await getJson<{ llm_api_key_is_set: boolean }>(
+ "/api/settings",
+ jsonRequest(
+ { agent_settings_diff: { llm: { api_key: apiKey } } },
+ "PATCH",
+ ),
+ );
+ expect(result.body.llm_api_key_is_set).toBe(false);
+ }
+ });
+
+ it("handles absent LLM settings and independent API-key signals", async () => {
+ const withoutLlm = await getJson<{
+ agent_settings: { llm: null };
+ llm_api_key_is_set: boolean;
+ }>(
+ "/api/settings",
+ jsonRequest({ agent_settings_diff: { llm: null } }, "PATCH"),
+ );
+ expect(withoutLlm.body).toMatchObject({
+ agent_settings: { llm: null },
+ llm_api_key_is_set: false,
+ });
+ const fetchedWithoutLlm = await getJson<{
+ agent_settings: { llm: null };
+ llm_api_key_is_set: boolean;
+ }>("/api/settings");
+ expect(fetchedWithoutLlm.body).toMatchObject({
+ agent_settings: { llm: null },
+ llm_api_key_is_set: false,
+ });
+
+ resetTestHandlersMockSettings();
+ await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest(
+ {
+ llm_api_key_set: true,
+ agent_settings_diff: { llm: { api_key: null } },
+ },
+ "POST",
+ ),
+ );
+ const flagOnly = await getJson<{ llm_api_key_is_set: boolean }>(
+ "/api/settings",
+ );
+ expect(flagOnly.body.llm_api_key_is_set).toBe(true);
+
+ resetTestHandlersMockSettings();
+ await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest(
+ {
+ llm_api_key_set: false,
+ agent_settings_diff: { llm: { api_key: "nested-key" } },
+ },
+ "POST",
+ ),
+ );
+ const nestedOnly = await getJson<{ llm_api_key_is_set: boolean }>(
+ "/api/settings",
+ );
+ expect(nestedOnly.body.llm_api_key_is_set).toBe(true);
+ });
+
+ it("merges app preferences across incremental updates", async () => {
+ const emptyMisc = await getJson<{ misc_settings: unknown }>(
+ "/api/settings",
+ jsonRequest({ misc_settings_diff: {} }, "PATCH"),
+ );
+ expect(emptyMisc.body.misc_settings).toEqual({});
+
+ await fetch(
+ `${BASE_URL}/api/settings`,
+ jsonRequest(
+ {
+ misc_settings_diff: {
+ app_preferences: { language: "de", git_user_name: "Ada" },
+ },
+ },
+ "PATCH",
+ ),
+ );
+ const second = await getJson<{
+ misc_settings: { app_preferences: Record<string, unknown> };
+ }>(
+ "/api/settings",
+ jsonRequest(
+ {
+ misc_settings_diff: {
+ app_preferences: {
+ language: "es",
+ disabled_skills: ["skill-a"],
+ },
+ },
+ },
+ "PATCH",
+ ),
+ );
+ expect(second.body.misc_settings.app_preferences).toEqual({
+ language: "es",
+ git_user_name: "Ada",
+ disabled_skills: ["skill-a"],
+ });
+
+ const persisted = await getJson<{
+ misc_settings: { app_preferences: Record<string, unknown> };
+ }>("/api/settings");
+ expect(persisted.body.misc_settings.app_preferences).toMatchObject({
+ language: "es",
+ git_user_name: "Ada",
+ git_user_email: null,
+ disabled_skills: ["skill-a"],
+ });
+ });
+
+ it("preserves unrelated persisted misc settings while merging preferences", async () => {
+ await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest(
+ {
+ misc_settings: {
+ marker: "keep-me",
+ app_preferences: { language: "en" },
+ },
+ },
+ "POST",
+ ),
+ );
+
+ const updated = await getJson<{
+ misc_settings: {
+ marker: string;
+ app_preferences: Record<string, unknown>;
+ };
+ }>(
+ "/api/settings",
+ jsonRequest(
+ {
+ misc_settings_diff: {
+ app_preferences: { git_user_name: "Ada" },
+ },
+ },
+ "PATCH",
+ ),
+ );
+
+ expect(updated.body.misc_settings).toEqual({
+ marker: "keep-me",
+ app_preferences: { language: "en", git_user_name: "Ada" },
+ });
+ });
+
+ it("supports independent conversation-settings updates", async () => {
+ const result = await getJson<{
+ agent_settings: Record<string, unknown>;
+ conversation_settings: Record<string, unknown>;
+ misc_settings: { app_preferences: Record<string, unknown> };
+ }>(
+ "/api/settings",
+ jsonRequest(
+ { conversation_settings_diff: { max_iterations: 99 } },
+ "PATCH",
+ ),
+ );
+ expect(result.body.conversation_settings).toMatchObject({
+ confirmation_mode: false,
+ max_iterations: 99,
+ });
+ expect(result.body.agent_settings).toMatchObject({
+ llm: { model: "openai/gpt-5.6-sol" },
+ verification: { critic_enabled: false },
+ });
+ expect(result.body.misc_settings).toEqual({ app_preferences: {} });
+ });
+
+ it("normalizes a persisted null API-key flag in update responses", async () => {
+ await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest({ llm_api_key_set: null }, "POST"),
+ );
+
+ const result = await getJson<{ llm_api_key_is_set: boolean }>(
+ "/api/settings",
+ jsonRequest(
+ { conversation_settings_diff: { max_iterations: 3 } },
+ "PATCH",
+ ),
+ );
+ expect(result.body.llm_api_key_is_set).toBe(false);
+ });
+
+ it("reports successful MCP connectivity with a mock tool", async () => {
+ const result = await getJson<{ ok: boolean; tools: string[] }>(
+ "/api/mcp/test",
+ { method: "POST" },
+ );
+ expect(result.response.ok).toBe(true);
+ expect(result.body).toEqual({ ok: true, tools: ["mock_tool"] });
+ });
+});
+
+describe("legacy settings persistence", () => {
+ it("rejects direct nested settings and identifies offending keys", async () => {
+ const both = await getJson<{ error: string; keys: string[] }>(
+ "/api/v1/settings",
+ jsonRequest({ agent_settings: {}, conversation_settings: {} }, "POST"),
+ );
+ expect(both.response.status).toBe(422);
+ expect(both.body).toEqual({
+ error: "Use *_diff nested settings payloads",
+ keys: ["agent_settings", "conversation_settings"],
+ });
+
+ const one = await getJson<{ keys: string[] }>(
+ "/api/v1/settings",
+ jsonRequest({ agent_settings: {} }, "POST"),
+ );
+ expect(one.response.status).toBe(422);
+ expect(one.body.keys).toEqual(["agent_settings"]);
+
+ const conversationOnly = await getJson<{ error: string; keys: string[] }>(
+ "/api/v1/settings",
+ jsonRequest({ conversation_settings: {} }, "POST"),
+ );
+ expect(conversationOnly.response.status).toBe(422);
+ expect(conversationOnly.body).toEqual({
+ error: "Use *_diff nested settings payloads",
+ keys: ["conversation_settings"],
+ });
+ });
+
+ it("accepts nested diffs and independent top-level settings", async () => {
+ const response = await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest(
+ {
+ agent_settings_diff: {
+ llm: { model: "openai/gpt-5.5" },
+ verification: { critic_enabled: true },
+ },
+ conversation_settings_diff: {
+ max_iterations: 7,
+ },
+ agent_settings_schema: { ignored: true },
+ conversation_settings_schema: { ignored: true },
+ language: "ja",
+ llm_api_key_set: true,
+ },
+ "POST",
+ ),
+ );
+ expect(response.status).toBe(200);
+
+ const persisted = await getJson<{
+ agent_settings: Record<string, unknown>;
+ conversation_settings: Record<string, unknown>;
+ agent_settings_schema: { model_name: string };
+ conversation_settings_schema: { model_name: string };
+ language: string;
+ llm_api_key_set: boolean;
+ }>("/api/v1/settings");
+ expect(persisted.body).toMatchObject({
+ agent_settings: {
+ llm: { model: "openai/gpt-5.5" },
+ verification: {
+ critic_enabled: true,
+ enable_iterative_refinement: false,
+ },
+ },
+ conversation_settings: {
+ confirmation_mode: false,
+ max_iterations: 7,
+ },
+ language: "ja",
+ llm_api_key_set: true,
+ });
+ expect(persisted.body).not.toHaveProperty("agent_settings_diff");
+ expect(persisted.body).not.toHaveProperty("conversation_settings_diff");
+ expect(persisted.body.agent_settings_schema).toMatchObject({
+ model_name: "AgentSettings",
+ });
+ expect(persisted.body.conversation_settings_schema).toMatchObject({
+ model_name: "ConversationSettings",
+ });
+ const scalarUpdate = await getJson(
+ "/api/v1/settings",
+ jsonRequest({ language: "ko" }, "POST"),
+ );
+ expect(scalarUpdate.response.status).toBe(200);
+ expect((await getJson("/api/v1/settings")).body).toMatchObject({
+ agent_settings: {
+ llm: { model: "openai/gpt-5.5" },
+ verification: { critic_enabled: true },
+ },
+ conversation_settings: { max_iterations: 7 },
+ language: "ko",
+ });
+ });
+
+ it("accepts an empty object but rejects a null body", async () => {
+ const empty = await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest({}, "POST"),
+ );
+ expect(empty.status).toBe(200);
+
+ const nullBody = await fetch(
+ `${BASE_URL}/api/v1/settings`,
+ jsonRequest(null, "POST"),
+ );
+ expect(nullBody.status).toBe(400);
+ await expect(nullBody.json()).resolves.toBeNull();
+ });
+});