Skip to content

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

14.6 KB
Raw Blame
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import { ensureDirs, instanceConfigs } from "../../config.ts";
import type { ProviderInstance } from "../../contracts.ts";
import { removeTempDir } from "../../testing/cleanup.ts";
import { recordEvents, type EventRecorder } from "../../testing/events.ts";
import { BUILT_IN_DRIVERS } from "../builtIn.ts";
import { keychain, MistralVibeAgentDriver, removeMistralVibeSignIn, resolveMistralVibeModels, vibeSignedIn } from "./mistral-vibe.ts";

const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");
const MODELS = "mistral-medium-3.5,zai-glm-5-3-flash,Mistral Large,Codestral";

describe("Mistral (Vibe) ACP driver", () => {
  let scratch: string;
  let instance: ProviderInstance | undefined;
  let recorder: EventRecorder | undefined;

  beforeEach(() => {
    ensureDirs();
    scratch = mkdtempSync(join(tmpdir(), "omb-mistral-vibe-contract-"));
  });

  afterEach(async () => {
    recorder?.stop();
    await instance?.dispose();
    instance = undefined;
    recorder = undefined;
    await removeTempDir(scratch);
  });

  async function create(environment: Record<string, string> = {}) {
    instance = await MistralVibeAgentDriver.create({
      instanceId: `mistral-vibe-contract-${Math.random().toString(36).slice(2)}`,
      displayName: "Mistral (Vibe)",
      enabled: true,
      environment: {
        VIBE_HOME: join(scratch, "vibe-home"),
        VIBE_KEYCHAIN_SERVICE: "omb-test-no-such-entry",
        FAKE_ACP_AUTH_METHOD: "browser-auth",
        FAKE_ACP_IMAGE_CAPABILITY: "1",
        FAKE_ACP_AGENT_NAME: "@mistralai/mistral-vibe",
        FAKE_ACP_VERSION: "vibe-acp 3.1.1",
        FAKE_ACP_MODELS: MODELS,
        FAKE_ACP_DUMP: join(scratch, "launch.json"),
        FAKE_ACP_RPC_DUMP: join(scratch, "rpc.json"),
        ...environment,
      },
      config: { cli: FAKE_CLI, fullAuto: false },
    });
    recorder = recordEvents(instance.adapter);
    return { instance, recorder };
  }

  it("is a built-in engine in fresh and existing fleets", () => {
    expect(BUILT_IN_DRIVERS.some((driver) => driver.driverKind === "mistralVibeAgent")).toBe(true);
    expect(instanceConfigs({}).mistralVibe?.driver).toBe("mistralVibeAgent");
    expect(instanceConfigs({ instances: { claude: { driver: "claudeAgent" } } }).mistralVibe?.driver).toBe("mistralVibeAgent");
    expect(MistralVibeAgentDriver.metadata).toMatchObject({ displayName: "Mistral (Vibe)", access: "subscription" });
  });

  it("treats a populated whoami_cache.json or MISTRAL_API_KEY as signed in", () => {
    const home = join(scratch, "vibe-home");
    mkdirSync(home, { recursive: true });
    // A negative keychain probe: the entry (if any) is global to the machine, while this test's marker
    // lives in a temporary VIBE_HOME — the two must not decide each other's answer.
    const probe = () => false;
    expect(vibeSignedIn({ VIBE_HOME: home, HOME: scratch }, probe)).toBe(false);
    writeFileSync(join(home, "whoami_cache.json"), JSON.stringify({ customer_id: "cus-fixture" }));
    expect(vibeSignedIn({ VIBE_HOME: home, HOME: scratch }, probe)).toBe(true);
    expect(vibeSignedIn({ VIBE_HOME: join(scratch, "absent"), MISTRAL_API_KEY: "fixture-key" }, probe)).toBe(true);
  });

  it("reports a pasted key as an API-key account and keeps sign-out from removing the CLI's own sign-in", async () => {
    const home = join(scratch, "vibe-home");
    mkdirSync(home, { recursive: true });
    writeFileSync(join(home, "whoami_cache.json"), JSON.stringify({ customer_id: "cus-fixture" }));
    const keyed = await create({ MISTRAL_API_KEY: "fixture-key" });
    expect(await keyed.instance.snapshot()).toMatchObject({ state: "available", authenticated: true, account: { method: "api-key" } });
    await expect(keyed.instance.signOut!()).rejects.toThrow("signed in by an API key");
    expect(existsSync(join(home, "whoami_cache.json"))).toBe(true);
    await keyed.instance.dispose();
    instance = undefined;
    const own = await create();
    const snapshot = await own.instance.snapshot();
    expect(snapshot).toMatchObject({ state: "available", authenticated: true });
    expect(snapshot.account).toBeUndefined();
  });

  it("treats an injected keychain probe as a sign-in marker (orchestration of the fresh sign-in)", () => {
    const env = { VIBE_HOME: join(scratch, "absent") };
    expect(vibeSignedIn(env, () => false)).toBe(false);
    expect(vibeSignedIn(env, () => true)).toBe(true);
  });

  it("reads live models from a throwaway discovery session that sets no model itself", async () => {
    const rpc = join(scratch, "discovery-rpc.json");
    const dump = join(scratch, "discovery.json");
    const catalog = await resolveMistralVibeModels({
      ...process.env,
      VIBE_HOME: join(scratch, "vibe-home"),
      FAKE_ACP_AUTH_METHOD: "browser-auth",
      FAKE_ACP_MODELS: MODELS,
      FAKE_ACP_VERSION: "vibe-acp 3.1.1",
      FAKE_ACP_DUMP: dump,
      FAKE_ACP_RPC_DUMP: rpc,
    }, { cli: FAKE_CLI });

    expect(catalog.default).toBe("mistral-medium-3.5");
    expect(catalog.options.map((option) => option.id)).toEqual(MODELS.split(","));
    expect(JSON.parse(readFileSync(rpc, "utf8"))).not.toContain("session/set_config_option");
    expect(JSON.parse(readFileSync(dump, "utf8")).argv).toEqual([]);
  });

  it("starts nothing when the instance is created", async () => {
    await create();
    expect(existsSync(join(scratch, "launch.json"))).toBe(false);
  });

  it("runs `vibe-acp` with no arguments, the workspace key, and the picked model", async () => {
    const { instance, recorder } = await create({ MISTRAL_API_KEY: "engine-fixture-key", OPENAI_COMPAT_API_KEY: "other-engine-key" });
    const { turnId } = await instance.adapter.sendTurn({
      threadId: "mistral-vibe-chat", text: "hello", model: "zai-glm-5-3-flash", approvalMode: "ask",
    });
    await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);

    expect(recorder.events.every((event) => event.provider === "mistralVibeAgent")).toBe(true);
    // Signed in through the key: the browser sign-in is not asked for on a turn.
    expect(JSON.parse(readFileSync(join(scratch, "rpc.json"), "utf8"))).not.toContain("authenticate");
    const launch = JSON.parse(readFileSync(join(scratch, "launch.json"), "utf8"));
    expect(launch.argv).toEqual([]);
    expect(launch.env.MISTRAL_API_KEY).toBe("engine-fixture-key");
    expect(launch.env.OPENAI_COMPAT_API_KEY).toBeUndefined();
    const promptRows = readFileSync(join(scratch, "launch.json.prompts.jsonl"), "utf8").trim().split("\n");
    expect(JSON.parse(promptRows.at(-1)!)).toMatchObject({ model: "zai-glm-5-3-flash" });
  });

  it("surfaces Vibe's thinking levels as model variants and applies the chosen one", async () => {
    const { instance, recorder } = await create({
      MISTRAL_API_KEY: "engine-fixture-key",
      FAKE_ACP_VARIANTS: JSON.stringify({
        "mistral-medium-3.5": {
          id: "thinking",
          currentValue: "max",
          options: [
            { value: "off", name: "Off" },
            { value: "low", name: "Low" },
            { value: "high", name: "High" },
            { value: "xhigh", name: "Xhigh" },
            { value: "max", name: "Max" },
          ],
        },
      }),
    });
    expect(instance.adapter.capabilities.modelVariants).toBe(true);
    const { turnId } = await instance.adapter.sendTurn({
      threadId: "mistral-vibe-effort", text: "hello", model: "mistral-medium-3.5",
      variant: "low", approvalMode: "ask",
    });
    await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);

    expect(recorder.events).toContainEqual(expect.objectContaining({
      type: "session.model-variants",
      model: "mistral-medium-3.5",
      variants: {
        options: [
          { id: "off", label: "Off" },
          { id: "low", label: "Low" },
          { id: "high", label: "High" },
          { id: "xhigh", label: "Xhigh" },
          { id: "max", label: "Max" },
        ],
        currentValue: "max",
      },
    }));
    expect(JSON.parse(readFileSync(join(scratch, "launch.json.config.json"), "utf8"))).toContainEqual({
      method: "session/set_config_option",
      params: { sessionId: "fake-acp-session", configId: "thinking", value: "low" },
    });
  });

  // A close that fails re-loads in a fresh process instead: one more launch per new bearer.
  it.each([["1", 1], ["error", 3]])("closes the live session before re-loading it with a new MCP bearer, so vibe-acp streams each reply once (close: %s)", async (close, processes) => {
    const launches = join(scratch, "launches");
    const { instance, recorder } = await create({
      MISTRAL_API_KEY: "engine-fixture-key", FAKE_ACP_LAUNCH_COUNT_FILE: launches,
      FAKE_ACP_SESSION_CLOSE: String(close), FAKE_ACP_COPY_LIVE_LOAD: "1", FAKE_ACP_TEXT_REPLY: "hello",
    });
    const agents = (token: string) => ({
      command: process.execPath,
      args: ["/app/dist-server/agents-proxy.js"],
      env: { OMB_HARNESS_URL: "http://127.0.0.1:8799", OMB_COMMS_TOKEN: token, OMB_BOT_ID: "sprout", OMB_THREAD_ID: "mistral-vibe-bearer" },
    });
    const reply = async (text: string, token: string, resume: boolean) => {
      const { turnId } = await instance.adapter.sendTurn({
        threadId: "mistral-vibe-bearer", text, model: "mistral-medium-3.5", approvalMode: "ask",
        ...(resume ? { resumeCursor: "fake-acp-session" } : {}), integrations: { agents: agents(token) },
      });
      await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
      return recorder.events.find((event) => event.turnId === turnId && event.type === "item.completed" && event.itemType === "assistant_text");
    };
    expect(await reply("one", "token-one", false)).toMatchObject({ text: "hello" });
    expect(await reply("two", "token-two", true)).toMatchObject({ text: "hello" });
    expect(await reply("three", "token-three", true)).toMatchObject({ text: "hello" });
    expect(Number(readFileSync(launches, "utf8"))).toBe(processes);
  });

  it("forgets a closed live session when its re-load is refused, so the next turn loads it instead of prompting the closed copy", async () => {
    const reject = join(scratch, "reject");
    const rpc = join(scratch, "rpc.jsonl");
    const { instance, recorder } = await create({
      MISTRAL_API_KEY: "engine-fixture-key", FAKE_ACP_COPY_LIVE_LOAD: "1", FAKE_ACP_TEXT_REPLY: "hello",
      FAKE_ACP_REJECT_LIVE_LOAD_FILE: reject, FAKE_ACP_REJECT_LIVE_LOAD_DSH: "1", FAKE_ACP_RPC_APPEND_FILE: rpc,
    });
    const agents = (token: string) => ({
      command: process.execPath,
      args: ["/app/dist-server/agents-proxy.js"],
      env: { OMB_HARNESS_URL: "http://127.0.0.1:8799", OMB_COMMS_TOKEN: token, OMB_BOT_ID: "sprout", OMB_THREAD_ID: "mistral-vibe-refused" },
    });
    const run = async (text: string, token: string, resume: boolean) => {
      const { turnId } = await instance.adapter.sendTurn({
        threadId: "mistral-vibe-refused", text, model: "mistral-medium-3.5", approvalMode: "ask",
        ...(resume ? { resumeCursor: "fake-acp-session" } : {}), integrations: { agents: agents(token) },
      });
      return recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
    };
    const methods = () => readFileSync(rpc, "utf8").trim().split("\n").map((line) => (JSON.parse(line) as { method: string }).method);
    expect(await run("one", "token-one", false)).toMatchObject({ ok: true });
    writeFileSync(reject, "1");
    expect(await run("two", "token-two", true)).toMatchObject({ ok: false });
    expect(methods().slice(-2)).toEqual(["session/close", "session/load"]);
    const before = methods().length;
    rmSync(reject);
    expect(await run("three", "token-one", true)).toMatchObject({ ok: true });
    expect(methods().slice(before)).toContain("session/load");
  });

  it("turns Vibe's session/request_permission into an approval card and answers with the person's choice", async () => {
    const answer = join(scratch, "permission.txt");
    const { instance, recorder } = await create({ FAKE_ACP_MODE: "permission", FAKE_ACP_PERMISSION_ANSWER: answer });
    const { turnId } = await instance.adapter.sendTurn({
      threadId: "mistral-vibe-permission", text: "edit", model: "mistral-medium-3.5", approvalMode: "ask",
    });
    const ask = await recorder.until((event) => event.type === "request.opened");
    expect(ask.provider).toBe("mistralVibeAgent");
    expect(await instance.adapter.respondToRequest("mistral-vibe-permission", ask.requestId!, { behavior: "deny" })).toBe("rejected");
    await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);
    expect(readFileSync(answer, "utf8")).toBe("reject");
    // Not signed in anywhere: the turn asks for the engine's browser sign-in.
    expect(JSON.parse(readFileSync(join(scratch, "rpc.json"), "utf8"))).toContain("authenticate");
  });

  describe("sign-out cleanup of Vibe's fallback .env", () => {
    const originalDelete = keychain.delete;
    let deletedServices: string[];

    beforeEach(() => {
      // a developer's real `vibe` / `vibe-acp` login items stay put while the filesystem cleanup stays real
      deletedServices = [];
      keychain.delete = (service: string) => { deletedServices.push(service); return Promise.resolve(); };
    });

    afterEach(() => { keychain.delete = originalDelete; });
    it("strips bare and exported MISTRAL_API_KEY lines and keeps unrelated ones", async () => {
      const home = join(scratch, "vibe-home");
      mkdirSync(home, { recursive: true });
      const envFile = join(home, ".env");
      writeFileSync(envFile, ["ONE=1", "MISTRAL_API_KEY='fixture'", 'export MISTRAL_API_KEY="second"', "TWO=2"].join("\n"));
      await removeMistralVibeSignIn({ VIBE_HOME: home });
      expect(readFileSync(envFile, "utf8")).toBe(["ONE=1", "TWO=2"].join("\n"));
      expect(deletedServices.sort()).toEqual(
        process.platform === "darwin" ? ["ai.mistral.vibe", "vibe"] : [],
      );
    });

    it("resolves without a .env and rejects when one cannot be rewritten", async () => {
      const fresh = join(scratch, "no-env-home");
      mkdirSync(fresh, { recursive: true });
      await expect(removeMistralVibeSignIn({ VIBE_HOME: fresh })).resolves.toBeUndefined();
      const blocked = join(scratch, "blocked-env-home");
      mkdirSync(join(blocked, ".env"), { recursive: true });
      await expect(removeMistralVibeSignIn({ VIBE_HOME: blocked })).rejects.toThrow();
    });
  });
});