Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

10.0 KB
Raw Blame
/**
 * Handing a Project's plugin list to its machines, strict parity.
 *
 * The rule the operator chose: the Project's list is the truth, so a machine ends with
 * exactly it — extras removed. The cost is the point of the "removes what the machine has
 * beyond the list" case: a platform-specific sandbox backend is not in the other platform's
 * list, so keeping one means listing it fleet-wide.
 */
import { describe, expect, it } from "vitest";
import type { MachineApi } from "../src/machines/machine-api.js";
import type { InstalledPluginsResponse } from "../src/api/types.js";
import { syncPluginsToMachine } from "../src/machines/plugins-sync.js";

/** A machine whose list is whatever was last written to it. */
function fakeMachine(
  initial: Record<string, string[]>,
  opts: {
    restartPending?: boolean;
    shipped?: string[];
    /** Packages npm cannot fetch over there. */
    unfetchable?: string[];
    /** Rows that machine's own `[plugins.<id>]` tables add, per Project. */
    ownRows?: Record<string, string[]>;
  } = {},
) {
  const state = new Map(Object.entries(initial));
  const calls: { method: string; path: string; body?: unknown }[] = [];
  const body = (list: string[]): InstalledPluginsResponse => ({
    plugins: list.map((specifier) => ({
      specifier,
      // "unresolvable there" is spelled the way the far side spells it: a row with a reason.
      active: !specifier.includes("not-there"),
      builtin: true,
      modules: [],
      replaces: [],
      ...(specifier.includes("not-there") ? { error: "not installed on this machine" } : {}),
      everywhere: true,
      machines: [],
      here: true,
    })),
    shipped: opts.shipped ?? [],
    file: ".project_config.toml",
    machineId: "Theirs0000000000",
    restartPending: opts.restartPending === true,
  });
  const api: MachineApi = {
    request: async (method: string, path: string, payload?: unknown) => {
      calls.push({ method, path, ...(payload === undefined ? {} : { body: payload }) });
      if (path === "/api/projects") {
        return {
          status: 200,
          text: JSON.stringify({ projects: [...state.keys()].map((projectId) => ({ projectId })) }),
        };
      }
      const projectId = decodeURIComponent(path.split("/")[3] ?? "");
      const has = state.get(projectId);
      if (has === undefined) return { status: 404, text: "no such Project" };
      if (method === "PUT") {
        state.set(projectId, [...((payload as { plugins: string[] }).plugins ?? [])]);
      }
      if (method === "POST") {
        const specifier = (payload as { specifier: string }).specifier;
        if (opts.unfetchable?.includes(specifier)) {
          return { status: 400, text: "npm: 404 Not Found" };
        }
        const name = specifier.replace(/(.)@.*$/, "$1");
        state.set(projectId, [...(state.get(projectId) ?? []), name]);
      }
      const reply = body(state.get(projectId) ?? []);
      for (const specifier of opts.ownRows?.[projectId] ?? []) {
        reply.plugins.push({
          specifier,
          active: true,
          builtin: false,
          modules: [],
          replaces: [],
          everywhere: false,
          machines: ["Theirs0000000000"],
          here: true,
        });
      }
      return { status: 200, text: JSON.stringify(reply) };
    },
    postBytes: async () => ({ status: 500, text: "unused" }),
  };
  return { api, calls, state };
}

const local =
  (lists: Record<string, (string | { name: string; version: string })[]>) => (projectId: string) =>
    Promise.resolve((lists[projectId] ?? []).map((p) => (typeof p === "string" ? { name: p } : p)));

describe("syncPluginsToMachine", () => {
  it("writes what the Project asks for, and removes what the machine has beyond it", async () => {
    const m = fakeMachine({ p1: ["@acme/keep", "@acme/theirs"] });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/keep", "@acme/ours"] }),
      projects: ["p1"],
    });
    expect(out).toMatchObject({ kind: "synced", projects: ["p1"] });
    if (out.kind !== "synced") throw new Error("unreachable");
    expect(out.added).toEqual(["@acme/ours"]);
    // Strict parity: what the machine had and this Project does not ask for is taken away.
    expect(out.removed).toEqual(["@acme/theirs"]);
    expect(m.state.get("p1")).toEqual(["@acme/keep", "@acme/ours"]);
  });

  it("writes nothing when the machine is already in parity", async () => {
    const m = fakeMachine({ p1: ["@acme/same"] });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/same"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.projects).toEqual([]);
    // A connect must not rewrite a machine that already agrees.
    expect(m.calls.some((c) => c.method === "PUT")).toBe(false);
  });

  it("reports a specifier the machine cannot resolve instead of dropping it", async () => {
    // Most often a machine still on a build that does not ship the plugin: the operator's
    // choice is not taking effect there, and silence would read as success.
    const m = fakeMachine({ p1: [] });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/not-there"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.unresolved).toEqual(["@acme/not-there"]);
    expect(m.state.get("p1")).toEqual(["@acme/not-there"]);
  });

  it("reports a machine that still has to restart to finish loading", async () => {
    const m = fakeMachine({ p1: [] }, { restartPending: true });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/one"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.restartPending).toBe(true);
  });

  it("refuses a Project the machine does not have, rather than creating one", async () => {
    // A Project exists to hold work; creating one over there to carry a plugin list would
    // invent a workspace nobody asked for.
    const m = fakeMachine({});
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/one"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.refused).toEqual([
      { projectId: "p1", detail: "that machine has no such Project" },
    ]);
    expect(m.calls.some((c) => c.method === "PUT")).toBe(false);
  });

  it("tells a machine that lacks the ROUTE from one that lacks the Project", async () => {
    // The same 404 means two opposite things, and the operator reads the difference. A
    // machine on an older build listed the Project it was refused for, in the line right
    // after the models sync had written that very Project.
    const older = fakeMachine({});
    older.api.request = async (method, path) => {
      if (path === "/api/projects") {
        return { status: 200, text: JSON.stringify({ projects: [{ projectId: "p1" }] }) };
      }
      return {
        status: 404,
        text: '{"error":{"code":"not_found","message":"Endpoint does not exist."}}',
      };
    };
    const out = await syncPluginsToMachine({
      api: older.api,
      loadLocal: local({ p1: ["@acme/one"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.refused).toEqual([
      {
        projectId: "p1",
        detail:
          "that machine's build is older than the Project plugin list — update it, then sync again",
      },
    ]);
  });

  it("carries on to the next Project when one is refused", async () => {
    const m = fakeMachine({ p2: [] });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/one"], p2: ["@acme/two"] }),
      projects: ["p1", "p2"],
    });
    expect(out.kind === "synced" && out.projects).toEqual(["p2"]);
    expect(out.kind === "synced" && out.refused.map((r) => r.projectId)).toEqual(["p1"]);
    expect(m.state.get("p2")).toEqual(["@acme/two"]);
  });
  it("installs over there only what that machine is asked for and lacks, pinned as asked", async () => {
    // A plugin listed for other machines never reaches this one's loadLocal, so nothing
    // fetches it here; what does reach it is fetched by the machine's own POST.
    const m = fakeMachine({ p1: ["@acme/had"] });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/had", { name: "@acme/new", version: "1.2.3" }] }),
      projects: ["p1"],
    });
    expect(m.calls.filter((c) => c.method === "POST").map((c) => c.body)).toEqual([
      { specifier: "@acme/[email protected]" },
    ]);
    expect(out.kind === "synced" && out.added).toEqual(["@acme/new"]);
    expect(m.state.get("p1")).toEqual(["@acme/had", "@acme/new"]);
  });

  it("lists a plugin the machine's build ships without a download", async () => {
    const m = fakeMachine({ p1: [] }, { shipped: ["@acme/builtin"] });
    await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/builtin"] }),
      projects: ["p1"],
    });
    expect(m.calls.some((c) => c.method === "POST")).toBe(false);
    expect(m.state.get("p1")).toEqual(["@acme/builtin"]);
  });

  it("reports a package that machine cannot fetch and still delivers the rest", async () => {
    const m = fakeMachine({ p1: [] }, { unfetchable: ["@acme/gone"] });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/gone", "@acme/ok"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.refused.map((r) => r.detail)).toEqual([
      "installing @acme/gone → 400: npm: 404 Not Found",
    ]);
    expect(m.state.get("p1")).toEqual(["@acme/ok"]);
  });

  it("leaves rows the machine's own tables add out of the comparison", async () => {
    const m = fakeMachine({ p1: ["@acme/same"] }, { ownRows: { p1: ["@acme/its-own"] } });
    const out = await syncPluginsToMachine({
      api: m.api,
      loadLocal: local({ p1: ["@acme/same"] }),
      projects: ["p1"],
    });
    expect(out.kind === "synced" && out.removed).toEqual([]);
    expect(m.calls.some((c) => c.method === "PUT")).toBe(false);
  });
});