Skip to content

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

6.1 KB
Raw Blame
import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";

import { DATA_DIR, engineLaunches, instanceConfigs, loadConfig, type AppConfig } from "./config.ts";
import { jsonErrorMessage, jsonErrorOffset, reloadConfig, RESTART_SECTIONS } from "./config-reload.ts";

const FILE = join(DATA_DIR, "config.json");
const SECRET = "sk-test-do-not-show-9f2c";
const write = (value: unknown) => writeFileSync(FILE, typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`);
const reload = (cfg: AppConfig) => reloadConfig({ cfg, read: () => readFileSync(FILE, "utf8"), load: loadConfig, engines: (config) => engineLaunches(instanceConfigs(config)) });

beforeEach(() => mkdirSync(DATA_DIR, { recursive: true }));
afterEach(() => rmSync(FILE, { force: true }));

describe("reloadConfig", () => {
  it("applies a hand edit to the settings every request reads, in place, and drops a section the file no longer has", () => {
    write({ rooms: { turnTimeoutMinutes: 5 }, everyBotRules: "Be brief.", memory: { tidyHour: 3 } });
    const cfg = loadConfig();
    const same = cfg;
    write({ rooms: { turnTimeoutMinutes: 30 }, memory: { tidyHour: 3 }, threadTitles: { followUp: true } });
    expect(reload(cfg)).toEqual({ ok: true, applied: ["everyBotRules", "rooms", "threadTitles"], restart: [] });
    expect(cfg).toBe(same);
    expect(cfg.rooms?.turnTimeoutMinutes).toBe(30);
    expect(cfg.threadTitles).toEqual({ followUp: true });
    expect(Object.hasOwn(cfg, "everyBotRules")).toBe(false);
    expect(reload(cfg)).toEqual({ ok: true, applied: [], restart: [] });
  });

  it("keeps the running settings when the JSON is broken, and says where in words that never quote the file", () => {
    write({ everyBotRules: "Be brief.", anthropic: { key: SECRET } });
    const cfg = loadConfig();
    const before = structuredClone(cfg);
    // Each of V8's messages for these quotes the file or names no line; the reply must do neither.
    const broken = [
      `{\n  "everyBotRules": "Be brief.",\n  "anthropic": { "key": "${SECRET}" },\n}\n`,
      `{\n  "everyBotRules": "Be brief."\n  "anthropic": { "key": ${SECRET} }\n}\n`,
      `{\n  "anthropic": { "key": "${SECRET}`,
    ];
    const results = broken.map((text) => { write(text); return reload(cfg); });
    expect(results).toEqual([
      { ok: false, code: "json", error: "config.json line 4, column 1: unexpected } (a comma before it may be extra)" },
      { ok: false, code: "json", error: "config.json line 3, column 3: unexpected quote (a comma before it may be missing)" },
      { ok: false, code: "json", error: "config.json line 2, column 50: the file ends before the settings do (a } or ] may be missing)" },
    ]);
    for (const result of results) expect(JSON.stringify(result)).not.toContain(SECRET.slice(3, 10));
    expect(cfg).toEqual(before);
  });

  it("keeps the running settings on a setting the schema refuses, and names the field", () => {
    write({ rooms: { turnTimeoutMinutes: 5 } });
    const cfg = loadConfig();
    write({ rooms: { turnTimeoutMinutes: 99_999 }, anthropic: { key: SECRET } });
    const result = reload(cfg);
    expect(result).toMatchObject({ ok: false, code: "schema" });
    expect(result.ok ? "" : result.error).toMatch(/^config\.json: rooms\.turnTimeoutMinutes /);
    expect(JSON.stringify(result)).not.toContain(SECRET);
    expect(cfg.rooms?.turnTimeoutMinutes).toBe(5);
  });

  it("says when there is no file, and makes none", () => {
    const cfg = loadConfig();
    expect(reload(cfg)).toEqual({ ok: false, code: "missing", error: "There is no config.json on this computer yet." });
    expect(() => readFileSync(FILE)).toThrow();
  });

  it("holds back sections a save changes with more than the value, and the engines, until a restart", () => {
    write({ everyBotRules: "Be brief." });
    const cfg = loadConfig();
    const before = structuredClone(cfg);
    write({
      everyBotRules: "Be kind.",
      signIn: { admins: ["[email protected]"] },
      features: { browser: false },
      instances: { claude: { driver: "claude", enabled: true } },
    });
    expect(reload(cfg)).toEqual({ ok: true, applied: ["everyBotRules"], restart: ["features", "instances", "signIn"] });
    expect(cfg.signIn).toEqual(before.signIn);
    expect(cfg.instances).toEqual(before.instances);
    expect(cfg.features).toEqual(before.features);
    expect(cfg.everyBotRules).toBe("Be kind.");
  });

  it("applies a feature switch that closes nothing", () => {
    write({ features: { browser: true } });
    const cfg = loadConfig();
    write({ features: { browser: true, showToolCalls: true } });
    expect(reload(cfg)).toMatchObject({ ok: true, applied: ["features"], restart: [] });
    expect(cfg.features).toMatchObject({ browser: true, showToolCalls: true });
  });

  it("lists sections the app reads only at start or changes with side effects", () => {
    for (const section of ["instances", "signIn", "browserEngine", "browserProfiles", "localVm", "box", "customDomain", "cliStartup"]) expect(RESTART_SECTIONS.has(section), section).toBe(true);
    for (const section of ["rooms", "everyBotRules", "memory", "threadTitles", "mcpServers"]) expect(RESTART_SECTIONS.has(section), section).toBe(false);
  });
});

describe("jsonErrorOffset", () => {
  it("agrees with JSON.parse on what is valid", () => {
    const samples = [
      "{}", "[]", '{"a":1}', '{"a": [1, 2.5, -3e2, true, false, null, "x\\u00e9\\n"]}', " \n{ }\n ", "0", '"\\/"',
      "", "{", '{"a":1,}', "[1,]", '{"a" 1}', "{a:1}", '{"a":01}', '{"a":1.}', '{"a":"\\x"}', '{"a":"\t"}', '{"a":tru}', '{"a":1} x', "[1 2]", "-", "1e", '{"a":"\\u12"}',
    ];
    for (const text of samples) {
      let valid = true;
      try { JSON.parse(text); } catch { valid = false; }
      expect(jsonErrorOffset(text) === -1, JSON.stringify(text)).toBe(valid);
    }
  });

  it("points at the first character JSON stops at", () => {
    expect(jsonErrorOffset('{"a":1,}')).toBe(7);
    expect(jsonErrorOffset("[1 2]")).toBe(3);
    expect(jsonErrorMessage('{\n  "a": 1\n  "b": 2\n}')).toBe("config.json line 3, column 3: unexpected quote (a comma before it may be missing)");
  });
});