Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

31.4 KB
Raw Blame
// A finished sign-in step changes what an engine reports: the next engine list probes its CLI again.
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { afterEach, describe, expect, it } from "vitest";

import { instanceConfigs, type AppConfig } from "../config.ts";
import type { ProviderAuthenticationStart, ProviderAuthenticationStatus } from "../contracts.ts";
import { ENGINE_LIST_REUSE_MS, ProviderRegistry } from "../harness/registry.ts";
import { json, readBody } from "../harness/http.ts";
import { ProviderAuthSessions } from "../provider-auth-sessions.ts";
import type { RequestAuth } from "../request-auth.ts";
import { makeFakeDriver } from "../testing/fake-driver.ts";
import { createInstanceRoutes, type InstanceRouteDeps } from "./instances.ts";
import { dispatchRoutes } from "./table.ts";

const servers: Server[] = [];
afterEach(async () => {
  await Promise.all(servers.splice(0).map((server) => new Promise((done) => server.close(done))));
});

async function serve(extra: Partial<InstanceRouteDeps> = {}, auth: RequestAuth = { kind: "loopback", scopes: ["admin"] }) {
  const fake = makeFakeDriver();
  const registry = new ProviderRegistry([fake.driver]);
  await registry.load({ a: { driver: "fake" } });
  const sign = {
    start: { phase: "waiting", flowId: "flow-1", authorizationUrl: "https://example.test/sign-in", expiresAt: null } as ProviderAuthenticationStart,
    status: { phase: "waiting", flowId: "flow-1", authorizationUrl: null, expiresAt: null } as ProviderAuthenticationStatus,
  };
  Object.assign(registry.get("a")!, {
    startAuthentication: async () => ({ ...sign.start }),
    getAuthentication: async () => ({ ...sign.status }),
    completeAuthentication: async () => {},
    cancelAuthentication: async () => {},
    signOut: async () => {},
  });
  const deps = {
    store: { bots: [], tasks: () => [] },
    cfg: { instances: { a: { driver: "fake" } } } as unknown as AppConfig,
    registry,
    sessions: { isLive: () => true },
    providerAuthSessions: new ProviderAuthSessions(),
    hostedModels: false,
    providerConfigBusy: { get: () => false, set: () => {} },
    providerInstancesChanging: new Set<string>(),
    describeInstances: () => registry.describe({ reuse: { ms: ENGINE_LIST_REUSE_MS, changed: () => {} } }),
    threadBusy: () => false,
    botForThread: () => null,
    activeGroupTurnForBot: () => null,
    ...extra,
  } as unknown as InstanceRouteDeps;
  const routes = [createInstanceRoutes(deps)];
  const server = createServer(async (req, res) => {
    const url = new URL(req.url ?? "/", "http://localhost");
    try {
      const handled = await dispatchRoutes(routes, {
        req, res, url, path: url.pathname, method: req.method ?? "GET",
        auth, json, readBody,
      });
      if (!handled) json(res, 404, { from: "inline routes" });
    } catch (error) {
      const status = (error as { status?: unknown })?.status;
      json(res, typeof status === "number" ? status : 500, { error: error instanceof Error ? error.message : String(error) });
    }
  });
  servers.push(server);
  await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
  const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
  const call = async (method: string, path: string, body?: unknown) => {
    const response = await fetch(`${base}${path}`, {
      method, headers: { "content-type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body),
    });
    expect(response.status, `${method} ${path}`).toBe(200);
    return response.json() as Promise<any>;
  };
  const probesAfterList = async () => {
    await call("GET", "/api/instances");
    return fake.probes.length;
  };
  return { sign, call, probesAfterList, base, fake, registry };
}

describe("engine sign-in routes", () => {
  it("probe the engine again after a sign-in that finished at once, a device sign-in, a pasted code or a sign-out", async () => {
    const { sign, call, probesAfterList } = await serve();
    expect(await probesAfterList()).toBe(1);
    expect(await probesAfterList()).toBe(1);

    // Still waiting: nothing changed yet.
    expect((await call("POST", "/api/instances/a/auth/start", {})).auth).toMatchObject({ phase: "waiting" });
    expect((await call("GET", "/api/instances/a/auth/status?flowId=flow-1")).auth).toMatchObject({ phase: "waiting" });
    expect(await probesAfterList()).toBe(1);

    sign.status.phase = "succeeded";
    expect((await call("GET", "/api/instances/a/auth/status?flowId=flow-1")).auth).toMatchObject({ phase: "succeeded" });
    expect(await probesAfterList()).toBe(2);

    sign.start.flowId = "flow-2";
    await call("POST", "/api/instances/a/auth/start", {});
    expect(await probesAfterList()).toBe(2);
    await call("POST", "/api/instances/a/auth/complete", { flowId: "flow-2", code: "pasted-code" });
    expect(await probesAfterList()).toBe(3);

    sign.start.phase = "succeeded";
    expect((await call("POST", "/api/instances/a/auth/start", {})).auth).toMatchObject({ phase: "succeeded" });
    expect(await probesAfterList()).toBe(4);

    await call("POST", "/api/instances/a/auth/sign-out", {});
    expect(await probesAfterList()).toBe(5);
  });
});

const phoneHeaders = { "x-openmausbot-companion": "1", "x-openmausbot-companion-device": "phone-1" };

describe("browser sign-in from a paired phone", () => {
  const start = (base: string, headers: Record<string, string> = {}) =>
    fetch(`${base}/api/instances/a/auth/start`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: "{}" });

  it("is refused with the instruction to use the computer, while a code sign-in and the desktop itself are not", async () => {
    const phone: RequestAuth = { kind: "loopback", scopes: ["admin", "client"], companionDevice: "phone-1" };
    const onPhone = await serve({}, phone);
    const desktop = await serve();
    const instance = (served: typeof onPhone) => served.registry.get("a") as { authenticationMethod?: string };

    instance(onPhone).authenticationMethod = "browser";
    const refused = await start(onPhone.base);
    expect(refused.status).toBe(403);
    expect(((await refused.json()) as { error: string }).error).toMatch(/happens in a browser on the computer/);

    instance(onPhone).authenticationMethod = "browser-pkce";
    const pkce = await start(onPhone.base);
    expect(pkce.status).toBe(403);
    const pkceError = ((await pkce.json()) as { error: string }).error;
    expect(pkceError).toMatch(/Continue with ChatGPT on the computer/);
    expect(pkceError).not.toMatch(/hosted-app approval/);

    // A Cloud's added ChatGPT account signs in by device code (no browser callback), from any browser.
    instance(onPhone).authenticationMethod = undefined;
    expect((await start(onPhone.base)).status).toBe(200);

    instance(onPhone).authenticationMethod = "code";
    expect((await start(onPhone.base)).status).toBe(200);

    instance(desktop).authenticationMethod = "browser";
    // The standalone companion has no desktop token: its phone is plain loopback carrying only the companion's mark.
    expect((await start(desktop.base, phoneHeaders)).status).toBe(403);
    expect((await start(desktop.base)).status).toBe(200);
  });
});

describe("whose sign-in it is", () => {
  it("gives a phone its own, so it never resumes or cancels the computer's", async () => {
    const { base } = await serve();
    const start = (headers: Record<string, string> = {}) =>
      fetch(`${base}/api/instances/a/auth/start`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: "{}" });
    const cancel = (headers: Record<string, string> = {}) =>
      fetch(`${base}/api/instances/a/auth/cancel`, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify({ flowId: "flow-1" }) });

    expect((await start()).status).toBe(200);
    expect((await start(phoneHeaders)).status).toBe(409);
    expect((await cancel(phoneHeaders)).status).toBe(404);
    expect((await start()).status).toBe(200);
    expect((await cancel()).status).toBe(200);
  });
});

describe("the engine list", () => {
  it("answers again from the last status read, and reads every engine again when asked for fresh", async () => {
    const { call, probesAfterList, fake } = await serve();
    expect(await probesAfterList()).toBe(1);
    expect(await probesAfterList()).toBe(1);
    await call("GET", "/api/instances?fresh=1");
    expect(fake.probes).toHaveLength(2);
    expect(await probesAfterList()).toBe(2);
  });

  it("shows a member names, models and capabilities only, and never reads the engines afresh for one", async () => {
    const member = { kind: "session", via: "cookie", scopes: ["client"], session: {} } as unknown as RequestAuth;
    const describeInstances = async () => [{ instanceId: "a", driverKind: "fake", displayName: "Fake", models: { default: "m", options: [{ id: "m", label: "M" }] },
      capabilities: { queueing: true }, cli: "/home/owner/bin/fake", cliCandidates: ["/home/owner/bin/fake"], url: "https://llm.internal.example",
      claudeAccount: { configDir: "/home/owner/.claude" }, snapshot: { state: "available", authenticated: true, account: { email: "[email protected]" } } }];
    const { call, fake } = await serve({ describeInstances } as Partial<InstanceRouteDeps>, member);
    const { instances } = await call("GET", "/api/instances?fresh=1");
    expect(instances).toEqual([{ instanceId: "a", driverKind: "fake", displayName: "Fake", readOnly: true, models: { default: "m", options: [{ id: "m", label: "M" }] },
      capabilities: { queueing: true }, snapshot: { state: "available", authenticated: true } }]);
    expect(fake.probes).toHaveLength(0);
  });
});

describe("whether the server can start a bot", () => {
  it("counts the engines that are available and names none of them", async () => {
    const { call } = await serve({
      describeInstances: async () => [
        { instanceId: "claude", snapshot: { state: "available" } },
        { instanceId: "codex", snapshot: { state: "needs-login" } },
        { instanceId: "custom-1", snapshot: { state: "available" } },
        { instanceId: "broken" },
      ],
    });
    expect(await call("GET", "/api/health/engines")).toEqual({ app: "openmausbot", engines: 2 });
    const none = await serve({ describeInstances: async () => [{ instanceId: "codex", snapshot: { state: "unavailable" } }] });
    expect(await none.call("GET", "/api/health/engines")).toEqual({ app: "openmausbot", engines: 0 });
  });
});

describe("an engine's check", () => {
  it("goes through the server's tested-AI record, so the welcome's test also settles the new-bot default", async () => {
    const asked: string[] = [];
    const { call } = await serve({ checkInstance: async (instance) => { asked.push(instance.instanceId); return { ok: false, error: "no answer" }; } });
    expect(await call("POST", "/api/instances/a/check", {})).toEqual({ ok: false, error: "no answer" });
    expect(asked).toEqual(["a"]);
  });
});

describe("installing an engine's own build from Settings", () => {
  async function serveInstall(options: { useCli?: string; busy?: boolean }) {
    const persisted: Array<{ instanceId: string; instances: unknown }> = [];
    const deps = {
      store: { bots: [], tasks: () => [] },
      cfg: { instances: { opencode: { driver: "opencodeGo" } } } as unknown as AppConfig,
      registry: {
        installRuntime: async () => options.useCli ? { useCli: options.useCli } : true,
        get: () => null,
        forgetSnapshots: () => {},
        refreshModels: async () => true,
        cliTarget: () => null,
      },
      sessions: { isLive: () => true },
      providerAuthSessions: new ProviderAuthSessions(),
      hostedModels: false,
      providerConfigBusy: { get: () => options.busy === true, set: () => {} },
      providerInstancesChanging: new Set<string>(),
      describeInstances: async () => [],
      persistProviderInstance: async (instanceId: string, instances: unknown) => { persisted.push({ instanceId, instances }); },
      threadBusy: () => false,
      botForThread: () => null,
      activeGroupTurnForBot: () => null,
    } as unknown as InstanceRouteDeps;
    const routes = [createInstanceRoutes(deps)];
    const server = createServer(async (req, res) => {
      const url = new URL(req.url ?? "/", "http://localhost");
      await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth: { kind: "loopback", scopes: ["admin"] }, json, readBody });
    });
    servers.push(server);
    await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));
    const response = await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}/api/instances/opencode/install`, {
      method: "POST", headers: { "content-type": "application/json" }, body: "{}",
    });
    return { status: response.status, body: await response.json() as Record<string, unknown>, persisted };
  }

  it("points the engine at the app's own copy, as Set CLI would, and says so", async () => {
    const appCopy = "/data/tools/standalone/opencode/bin/opencode";
    const { status, body, persisted } = await serveInstall({ useCli: appCopy });
    expect(status).toBe(200);
    expect(body.usingAppCopy).toBe(true);
    expect(persisted).toEqual([{ instanceId: "opencode", instances: { opencode: { driver: "opencodeGo", config: { cli: appCopy } } } }]);
  });

  it("changes nothing while provider settings are being saved", async () => {
    const { body, persisted } = await serveInstall({ useCli: "/data/tools/standalone/opencode/bin/opencode", busy: true });
    expect(body.usingAppCopy).toBeUndefined();
    expect(persisted).toEqual([]);
  });

  it("changes nothing when the CLI already starts", async () => {
    const { body, persisted } = await serveInstall({});
    expect(body.usingAppCopy).toBeUndefined();
    expect(persisted).toEqual([]);
  });
});

describe("an added server's model IDs", () => {
  it("replaces the list, goes back to detecting models with an empty list, and refuses other servers", async () => {
    const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
    const cfg = { instances: {
      a: { driver: "fake" },
      openaiCompat: { driver: "openai-compat", config: { url: "http://127.0.0.1:11434/v1" } },
      "openai-compat-1": { driver: "openai-compat", config: { url: "https://api.example.com/v1", key: "k", managedModels: ["glm-4.6"] } },
    } };
    const { call, base } = await serve({
      cfg: cfg as unknown as AppConfig,
      persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
        persisted.push(structuredClone(instances));
        (cfg as { instances: unknown }).instances = instances;
      },
    });
    await call("PATCH", "/api/instances/openai-compat-1", { models: ["glm-5", " qwen3 ", "glm-5"] });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://api.example.com/v1", key: "k", managedModels: ["glm-5", "qwen3"] });
    await call("PATCH", "/api/instances/openai-compat-1", { models: [] });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://api.example.com/v1", key: "k" });
    const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {
      method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
    })).status;
    expect(await status("openaiCompat", { models: ["m"] })).toBe(400);
    expect(await status("a", { models: ["m"] })).toBe(400);
    for (const bad of [[""], ["x".repeat(201)], "glm-5", Array.from({ length: 65 }, (_, i) => `m${i}`)]) {
      expect(await status("openai-compat-1", { models: bad })).toBe(400);
    }
    expect(persisted).toHaveLength(2);
  });

  it("refuses to drop the default model from the list, and allows going back to detecting models", async () => {
    const persisted: unknown[] = [];
    const cfg = {
      defaultModelSelection: { instanceId: "openai-compat-1", model: "glm-4.6" },
      instances: { "openai-compat-1": { driver: "openai-compat", config: { url: "https://api.example.com/v1", key: "k", managedModels: ["glm-4.6"] } } },
    };
    const { base } = await serve({
      cfg: cfg as unknown as AppConfig,
      persistProviderInstance: async (_id: string, instances: unknown) => { persisted.push(structuredClone(instances)); },
    });
    const patch = (models: string[]) => fetch(`${base}/api/instances/openai-compat-1`, {
      method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify({ models }),
    });
    const refused = await patch(["glm-5"]);
    expect(refused.status).toBe(409);
    expect(await refused.json()).toMatchObject({ errorKey: "serverError.instance.defaultModelRemoved", errorParams: { model: "glm-4.6" } });
    expect(persisted).toHaveLength(0);
    expect((await patch(["glm-5", "glm-4.6"])).status).toBe(200);
    expect((await patch([])).status).toBe(200);
    expect(persisted).toHaveLength(2);
  });

  it("lists the IDs entered for an added server so they can be edited", async () => {
    const cfg = { instances: { "openai-compat-1": { driver: "openai-compat", config: { url: "https://api.example.com/v1", key: "k", managedModels: ["glm-4.6", "glm-5"] } } } };
    const { base } = await serve({
      cfg: cfg as unknown as AppConfig,
      describeInstances: async () => [{ instanceId: "openai-compat-1", driverKind: "openai-compat" }, { instanceId: "a", driverKind: "fake" }],
    });
    const body = await (await fetch(`${base}/api/instances`)).json() as { instances: Array<Record<string, unknown>> };
    expect(body.instances).toEqual([
      { instanceId: "openai-compat-1", driverKind: "openai-compat", url: "https://api.example.com/v1", managedModels: ["glm-4.6", "glm-5"] },
      { instanceId: "a", driverKind: "fake" },
    ]);
  });
});

describe("a server's reply wait", () => {
  it("saves minutes for an OpenAI-compatible server, clears them with null, and refuses other engines or bad values", async () => {
    const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
    const cfg = { instances: { a: { driver: "fake" }, "openai-compat-1": { driver: "openai-compat", config: { url: "http://127.0.0.1:11434/v1", key: "k" } } } };
    const { call, base } = await serve({
      cfg: cfg as unknown as AppConfig,
      persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
        persisted.push(structuredClone(instances));
        (cfg as { instances: unknown }).instances = instances;
      },
    });
    await call("PATCH", "/api/instances/openai-compat-1", { replyWaitMinutes: 20 });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "http://127.0.0.1:11434/v1", key: "k", replyWaitMinutes: 20 });
    await call("PATCH", "/api/instances/openai-compat-1", { replyWaitMinutes: null });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "http://127.0.0.1:11434/v1", key: "k" });
    const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {
      method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
    })).status;
    expect(await status("a", { replyWaitMinutes: 20 })).toBe(400);
    for (const bad of [0, 61, 2.5, "10"]) expect(await status("openai-compat-1", { replyWaitMinutes: bad })).toBe(400);
    expect(persisted).toHaveLength(2);
  });

  it("saves minutes for the built-in OpenAI-compatible server, such as a local Ollama set by its base URL", async () => {
    const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
    const cfg = { openaiCompat: { url: "http://127.0.0.1:11434/v1" } };
    const { call } = await serve({
      cfg: cfg as unknown as AppConfig,
      persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
        persisted.push(structuredClone(instances));
        (cfg as { instances?: unknown }).instances = instances;
      },
    });
    await call("PATCH", "/api/instances/openaiCompat", { replyWaitMinutes: 30 });
    expect(persisted.at(-1)!.openaiCompat).toEqual({ driver: "openai-compat", config: { replyWaitMinutes: 30 } });
    expect(instanceConfigs(cfg as unknown as AppConfig).openaiCompat!.config).toMatchObject({ url: "http://127.0.0.1:11434/v1", replyWaitMinutes: 30 });
  });

  it("saves custom request headers per OpenAI-compatible instance, preserves existing secret values, masks summaries, and enforces validation + owner/admin access", async () => {
    const persisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
    const cfg = {
      instances: {
        a: { driver: "fake" },
        "openai-compat-1": { driver: "openai-compat", config: { url: "https://gw.example/v1", key: "k" } },
      },
    };
    const { call, base } = await serve({
      cfg: cfg as unknown as AppConfig,
      describeInstances: async () => [
        { instanceId: "a", driverKind: "fake" },
        { instanceId: "openai-compat-1", driverKind: "openai-compat" },
      ],
      persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
        persisted.push(structuredClone(instances));
        (cfg as { instances: unknown }).instances = instances;
      },
    });
    const saved = await call("PATCH", "/api/instances/openai-compat-1", {
      customHeaders: {
        enabled: true,
        headers: [
          { name: "X-Maus-Thread-ID", value: "{threadId}", required: true },
          { name: "X-Gateway-Token", value: "gw-secret-value-123", secret: true },
        ],
      },
    });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toMatchObject({
      customHeaders: {
        enabled: true,
        headers: [
          { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
          { name: "X-Gateway-Token", value: "gw-secret-value-123", required: true, secret: true },
        ],
      },
    });
    const listText = JSON.stringify(saved);
    expect(listText).not.toContain("gw-secret-value-123");
    const updated = await call("PATCH", "/api/instances/openai-compat-1", {
      customHeaders: {
        enabled: true,
        headers: [
          { name: "X-Maus-Thread-ID", value: "{threadId}", required: true },
          { name: "X-Gateway-Token", keepExisting: true, secret: true },
        ],
      },
    });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toMatchObject({
      customHeaders: {
        enabled: true,
        headers: [
          { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
          { name: "X-Gateway-Token", value: "gw-secret-value-123", required: true, secret: true },
        ],
      },
    });
    expect(JSON.stringify(updated)).not.toContain("gw-secret-value-123");

    const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {
      method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
    })).status;
    expect(await status("a", { customHeaders: { enabled: true, headers: [{ name: "X-Ok", value: "1" }] } })).toBe(400);
    expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "Authorization", value: "Bearer bad" }] } })).toBe(400);
    expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Bad", value: "line1\r\nline2" }] } })).toBe(400);
    expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "s3cr3t", secret: true }] } })).toBe(400);
    expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Api-Key", value: "short" }] } })).toBe(400);
    expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [{ name: "X-Client-Tag", value: "short", secret: false }] } })).toBe(200);

    await call("PATCH", "/api/instances/openai-compat-1", {
      customHeaders: { enabled: true, headers: [{ name: "X-Tenant-Pin", value: "pin-987654", secret: true }] },
    });
    expect(await status("openai-compat-1", {
      customHeaders: { enabled: true, headers: [{ name: "X-Tenant-Pin", keepExisting: true, secret: false }] },
    })).toBe(400);

    await call("PATCH", "/api/instances/openai-compat-1", { customHeaders: null });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toEqual({ url: "https://gw.example/v1", key: "k" });

    (cfg.instances["openai-compat-1"] as { config: Record<string, unknown> }).config = {
      url: "https://gw.example/v1", key: "k",
      customHeaders: { enabled: true, headers: { "X-Gateway-Token": "gw-map-secret-999" } },
    };
    await call("PATCH", "/api/instances/openai-compat-1", {
      customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", keepExisting: true, secret: true }] },
    });
    expect(persisted.at(-1)!["openai-compat-1"]!.config).toMatchObject({
      customHeaders: { enabled: true, headers: [{ name: "X-Gateway-Token", value: "gw-map-secret-999", required: true, secret: true }] },
    });
    (cfg.instances["openai-compat-1"] as { config: Record<string, unknown> }).config = {
      url: "https://gw.example/v1", key: "k", customHeaders: { enabled: "bad", headers: 42 },
    };
    expect(await status("openai-compat-1", { customHeaders: { enabled: true, headers: [] } })).toBe(400);
    await call("PATCH", "/api/instances/openai-compat-1", { customHeaders: null });

    const nonOwner = await serve(
      { cfg: cfg as unknown as AppConfig, persistProviderInstance: async () => {} },
      { kind: "loopback", scopes: ["admin"], trust: "service" },
    );
    expect((await fetch(`${nonOwner.base}/api/instances/openai-compat-1`, {
      method: "PATCH", headers: { "content-type": "application/json" },
      body: JSON.stringify({ customHeaders: { enabled: true, headers: [] } }),
    })).status).toBe(403);

    const inheritedCfg = {
      openaiCompat: {
        url: "https://gw.example/v1",
        customHeaders: {
          enabled: true,
          headers: [{ name: "X-Workspace-Secret", value: "ws-secret-value-123", required: true, secret: true }],
        },
      },
      instances: { openaiCompat: { driver: "openai-compat", config: {} } },
    };
    const inheritedPersisted: Array<Record<string, { driver: string; config?: Record<string, unknown> }>> = [];
    const inheritedSrv = await serve({
      cfg: inheritedCfg as unknown as AppConfig,
      persistProviderInstance: async (_id: string, instances: typeof inheritedPersisted[number]) => {
        inheritedPersisted.push(structuredClone(instances));
        (inheritedCfg as { instances: unknown }).instances = instances;
      },
    });
    await inheritedSrv.call("PATCH", "/api/instances/openaiCompat", { replyWaitMinutes: 15 });
    expect(inheritedPersisted.at(-1)!.openaiCompat!.config).toEqual({ replyWaitMinutes: 15 });
    await inheritedSrv.call("PATCH", "/api/instances/openaiCompat", {
      customHeaders: {
        enabled: true,
        headers: [
          { name: "X-Workspace-Secret", keepExisting: true, secret: true },
          { name: "X-Maus-Thread-ID", value: "{threadId}" },
        ],
      },
    });
    expect(inheritedPersisted.at(-1)!.openaiCompat!.config).toMatchObject({
      replyWaitMinutes: 15,
      customHeaders: {
        enabled: true,
        headers: [
          { name: "X-Workspace-Secret", value: "ws-secret-value-123", required: true, secret: true },
          { name: "X-Maus-Thread-ID", value: "{threadId}", required: true, secret: false },
        ],
      },
    });
  });
});

describe("hiding a provider", () => {
  it("hides a built-in provider, lists it apart, refuses while a bot uses it, and unhides", async () => {
    const persisted: Array<Record<string, { driver: string; hidden?: boolean }>> = [];
    const cfg = { instances: { a: { driver: "fake" }, hermes: { driver: "fake", displayName: "Hermes" } } };
    const bots = [{ id: "pen", modelSelection: { instanceId: "a", model: "m" } }];
    const { call, base } = await serve({
      cfg: cfg as unknown as AppConfig,
      store: { bots, tasks: () => [] } as never,
      persistProviderInstance: async (_id: string, instances: typeof persisted[number]) => {
        persisted.push(structuredClone(instances));
        (cfg as { instances: unknown }).instances = instances;
      },
    });
    const status = async (id: string, body: unknown) => (await fetch(`${base}/api/instances/${id}`, {
      method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body),
    })).status;
    expect(await status("a", { hidden: true })).toBe(409);
    await call("PATCH", "/api/instances/hermes", { hidden: true });
    expect(persisted.at(-1)!.hermes).toMatchObject({ driver: "fake", hidden: true });
    expect((await call("GET", "/api/instances/hidden")).instances).toEqual([{ instanceId: "hermes", driverKind: "fake", displayName: "Hermes" }]);
    await call("PATCH", "/api/instances/hermes", { hidden: false });
    expect(persisted.at(-1)!.hermes).not.toHaveProperty("hidden");
    expect((await call("GET", "/api/instances/hidden")).instances).toEqual([]);
  });
});


describe("looking for Ollama", () => {
  it("answers what one address said, and refuses an address that is not one", async () => {
    const ollama = createServer((request, response) => {
      response.setHeader("content-type", "application/json");
      if (request.url === "/api/tags") return response.end(JSON.stringify({ models: [{ name: "qwen3:4b", size: 2_500_000_000, details: { parameter_size: "4.0B" } }] }));
      if (request.url === "/api/version") return response.end(JSON.stringify({ version: "0.12.6" }));
      response.statusCode = 404;
      response.end("{}");
    });
    servers.push(ollama);
    await new Promise<void>((ready) => ollama.listen(0, "127.0.0.1", ready));
    const address = `http://127.0.0.1:${(ollama.address() as AddressInfo).port}`;
    const { call, base } = await serve();
    expect(await call("GET", `/api/instances/ollama?url=${encodeURIComponent(`${address}/v1`)}`)).toEqual({
      status: { state: "ready", url: address, version: "0.12.6", models: [{ name: "qwen3:4b", bytes: 2_500_000_000, parameters: "4.0B" }] },
    });
    const refused = await fetch(`${base}/api/instances/ollama?url=${encodeURIComponent("ftp://127.0.0.1:11434")}`);
    expect(refused.status).toBe(400);
    expect(await refused.json()).toEqual({ error: "Enter an http or https address, such as http://127.0.0.1:11434." });
  });

  it("is only for the owner: a shared server's bot shell or a hosted workspace can't make this server ask an address", async () => {
    const shell = await serve({}, { kind: "loopback", scopes: ["admin"], trust: "service" });
    expect((await fetch(`${shell.base}/api/instances/ollama?url=${encodeURIComponent("http://127.0.0.1:9")}`)).status).toBe(403);
    const hosted = await serve({ hostedModels: true });
    expect((await fetch(`${hosted.base}/api/instances/ollama`)).status).toBe(403);
  });
});

describe("the body a route reads", () => {
  const post = (base: string, path: string, size: number) =>
    fetch(`${base}${path}`, {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({ payload: "x".repeat(size) }),
    });

  it("is capped on the sign-in completion, CLI probe and Claude update routes", async () => {
    const { base } = await serve();
    for (const [path, size] of [
      ["/api/instances/a/auth/complete", 9_000],
      ["/api/cli-test", 5_000],
      ["/api/instances/a/claude-update", 5_000],
    ] as const) {
      const response = await post(base, path, size);
      expect(response.status, path).toBe(413);
      expect(((await response.json()) as { error?: string }).error, path).toBe("body too large");
    }
  });
});