Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

16.4 KB
Raw Blame
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Controller, ManagedAgent, ProviderInfo } from "../../data/management";
import MachinesPage from "./MachinesPage";

const laptop: Controller = {
  id: "c1",
  name: "laptop",
  description: null,
  kind: "daemon",
  platform: { os: "linux", arch: "x64", os_version: "6.1" },
  version: "0.1.0",
  state: "online",
  last_seen_at: new Date().toISOString(),
  connection: {
    connected_at: new Date().toISOString(),
    disconnected_at: null,
    disconnect_reason: null,
  },
  assignment_revision: 3,
  created_at: "2026-10-01T00:00:00Z",
  revoked_at: null,
  release: null,
  can_edit: true,
  can_remove: true,
  status: {
    seq: 1,
    observed_at: new Date().toISOString(),
    controller: { version: "0.1.0", protocol: 1, assignment_revision: 3 },
    machine: {
      platform: { os: "linux", arch: "x64", os_version: "6.1" },
      disk_free_bytes: 1,
      disk_total_bytes: 2,
      mem_free_bytes: 1,
      mem_total_bytes: 2,
      sessions_running: 0,
      sessions_max: 0,
    },
    providers: [
      {
        provider: "claude",
        installed: true,
        version: "2.0",
        auth: "ok",
        auth_source: "local",
        checked_at: new Date().toISOString(),
      },
      {
        provider: "codex",
        installed: true,
        version: "0.9",
        auth: "expired",
        auth_source: "local",
        checked_at: new Date().toISOString(),
        reason: "provider_login_expired",
      },
    ],
    tools: [],
    agents: [
      {
        agent_id: "a1",
        applied_revision: 2,
        process: "failed",
        attached: false,
        sessions: { active: 0, ids: [] },
        restarts_10m: 0,
        oom_kills: 0,
        since: new Date().toISOString(),
        reason: "invalid_credential",
        detail: "Switch refused the agent key",
      },
    ],
  },
};

const pmAgent: ManagedAgent = {
  agent_id: "a1",
  name: "pm-agent",
  display_name: null,
  icon_url: null,
  description: "Writes PRDs",
  controller_id: "c1",
  controller_state: "online",
  desired_state: "running",
  revision: 2,
  definition: {
    provider: "claude",
    model: null,
    instructions: "",
    auto_mode: false,
    auto_approve: false,
    directory: null,
    isolation: "shared",
    advanced_config: {},
  },
  status: laptop.status!.agents[0],
  created_at: "2026-10-01T00:00:00Z",
  updated_at: "2026-10-01T00:00:00Z",
  can_edit: true,
  can_delete: true,
};

const servedProviders: ProviderInfo[] = [
  { id: "claude", label: "Claude Code", advanced_fields: [] },
  { id: "codex", label: "Codex", advanced_fields: [] },
];

type Call = { path: string; method: string; body: unknown };

/** The management routes, answering GET /providers with `servedProviders` unless `routes` says otherwise. */
function mockManagement(routes: Record<string, [number, unknown]>) {
  routes = { "GET /providers": [200, { providers: servedProviders }], ...routes };
  const calls: Call[] = [];
  vi.stubGlobal(
    "fetch",
    vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
      const path = String(input).replace(/^\/gateway\/management/, "");
      const method = init?.method ?? "GET";
      calls.push({ path, method, body: init?.body ? JSON.parse(String(init.body)) : null });
      const [status, body] = routes[`${method} ${path}`] ?? [404, { detail: "Not Found" }];
      return new Response(JSON.stringify(body), { status });
    }),
  );
  return calls;
}

describe("MachinesPage", () => {
  afterEach(() => {
    cleanup();
    vi.unstubAllGlobals();
  });

  it("shows machines with their provider state and agents with what they reported", async () => {
    mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect((await screen.findAllByText("laptop")).length).toBe(2);
    expect(screen.getByText("Codex: login expired")).toBeTruthy();
    expect(screen.getByText("pm-agent")).toBeTruthy();
    expect(screen.getByText("failed: invalid_credential")).toBeTruthy();
  });

  it("offers each action on a device only where the server says it may be taken", async () => {
    mockManagement({
      "GET /controllers": [
        200,
        [
          laptop,
          { ...laptop, id: "c2", name: "theirs", can_edit: false, can_remove: false },
        ],
      ],
      "GET /agents": [
        200,
        [pmAgent, { ...pmAgent, agent_id: "a2", name: "their-agent", can_edit: false, can_delete: false }],
      ],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByRole("button", { name: "Edit device laptop" })).toBeTruthy();
    expect(screen.getByRole("button", { name: "Revoke laptop" })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "Edit device theirs" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Revoke theirs" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Re-check providers on theirs" })).toBeNull();

    expect(screen.getByRole("button", { name: "Edit pm-agent" })).toBeTruthy();
    expect(screen.getByRole("button", { name: "Stop managing pm-agent" })).toBeTruthy();
    expect(screen.queryByRole("button", { name: "Edit their-agent" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Stop their-agent" })).toBeNull();
    expect(screen.queryByRole("button", { name: "Stop managing their-agent" })).toBeNull();
  });

  it("says why an agent on no machine cannot be started", async () => {
    mockManagement({
      "GET /controllers": [200, []],
      "GET /agents": [200, [{ ...pmAgent, controller_id: null, controller_state: null }]],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    const start = await screen.findByRole("button", { name: "Stop pm-agent" });
    expect((start as HTMLButtonElement).disabled).toBe(true);
    expect(
      screen.getByLabelText("Not on a device: move it to one to start or stop it"),
    ).toBeTruthy();
  });

  it("shows the controller's version against the release Switch names", async () => {
    const wanted = { wanted: "0.31.0", running: "0.1.0", current: false };
    const machines: Controller[] = [
      { ...laptop, id: "c1", name: "on-it", version: "0.31.0", release: { ...wanted, running: "0.31.0", current: true } },
      { ...laptop, id: "c2", name: "waiting", release: wanted, status: { ...laptop.status!, update: { target: "0.31.0", state: "waiting_idle" } } },
      {
        ...laptop,
        id: "c3",
        name: "stuck",
        release: wanted,
        status: { ...laptop.status!, update: { target: "0.31.0", state: "failed", problem: "SHA-256 mismatch" } },
      },
      { ...laptop, id: "c4", name: "silent", release: wanted },
    ];
    mockManagement({
      "GET /controllers": [200, machines],
      "GET /agents": [200, []],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText("0.31.0")).toBeTruthy();
    expect(screen.getByText("updating when idle")).toBeTruthy();
    expect(screen.getByText("update failed")).toBeTruthy();
    expect(screen.getByText("behind")).toBeTruthy();
    expect(screen.getAllByText("0.1.0")).toHaveLength(3);
  });

  it("shows a revoked machine's agents as not running, whatever it last reported", async () => {
    const revoked: Controller = {
      ...laptop,
      state: "revoked",
      revoked_at: new Date().toISOString(),
      status: {
        ...laptop.status!,
        agents: [{ ...laptop.status!.agents[0]!, process: "running", reason: undefined, detail: undefined }],
      },
    };
    mockManagement({
      "GET /controllers": [200, [revoked]],
      "GET /agents": [
        200,
        [{ ...pmAgent, controller_state: "revoked", status: revoked.status!.agents[0] }],
      ],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText("None (revoked)")).toBeTruthy();
    expect(screen.getByText("not running: device revoked")).toBeTruthy();
    expect(screen.queryByText("1 / 1")).toBeNull();
    // Only what is wanted says running; nothing claims the agent actually is.
    expect(screen.getAllByText("running")).toHaveLength(1);
  });

  it("shows a machine that stopped as offline, and its agents as unreachable", async () => {
    const stopped: Controller = {
      ...laptop,
      state: "offline",
      connection: {
        ...laptop.connection!,
        disconnected_at: new Date().toISOString(),
        disconnect_reason: "socket_closed",
      },
    };
    mockManagement({
      "GET /controllers": [200, [stopped]],
      "GET /agents": [200, [{ ...pmAgent, controller_state: "offline" }]],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText("offline")).toBeTruthy();
    expect(screen.getByText("Not connected")).toBeTruthy();
    expect(screen.getByText("device offline")).toBeTruthy();
    expect(screen.queryByText("failed: invalid_credential")).toBeNull();
  });

  it("shows a machine that never connected as unknown", async () => {
    mockManagement({
      "GET /controllers": [200, [{ ...laptop, state: "unknown", connection: null, status: null }]],
      "GET /agents": [200, []],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText("unknown")).toBeTruthy();
    expect(screen.getByText("Unknown")).toBeTruthy();
  });

  it("describes revoking without per-agent keys", async () => {
    mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    fireEvent.click(await screen.findByLabelText("Revoke laptop"));
    const text = (await screen.findByText(/loses access to Switch immediately/)).textContent ?? "";
    expect(text).not.toMatch(/key/);
    expect(text).toMatch(/stay placed, and offline, until you move them/);
  });

  it("stops a running agent by changing what is wanted", async () => {
    const calls = mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
      "PATCH /agents/a1": [200, { ...pmAgent, desired_state: "stopped" }],
    });
    render(<MachinesPage />);
    fireEvent.click(await screen.findByLabelText("Stop pm-agent"));
    await waitFor(() =>
      expect(calls.find((c) => c.method === "PATCH")).toEqual({
        path: "/agents/a1",
        method: "PATCH",
        body: { desired_state: "stopped" },
      }),
    );
  });

  it("renames a machine and describes it, sending only what changed", async () => {
    const calls = mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
      "PATCH /controllers/c1": [
        200,
        { ...laptop, name: "build-box", description: "Under the desk" },
      ],
    });
    render(<MachinesPage />);
    fireEvent.click(await screen.findByLabelText("Edit device laptop"));
    const name = await screen.findByLabelText(/^Name/);
    fireEvent.change(name, { target: { value: "  build-box " } });
    fireEvent.change(screen.getByLabelText("Description"), {
      target: { value: "Under the desk" },
    });
    fireEvent.click(screen.getByRole("button", { name: "Save" }));
    await waitFor(() =>
      expect(calls.find((c) => c.method === "PATCH")).toEqual({
        path: "/controllers/c1",
        method: "PATCH",
        body: { name: "build-box", description: "Under the desk" },
      }),
    );
    expect(await screen.findByText("Saved build-box")).toBeTruthy();
  });

  it("will not save a machine without a name", async () => {
    const calls = mockManagement({
      "GET /controllers": [200, [{ ...laptop, description: "Old note" }]],
      "GET /agents": [200, []],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText("Old note")).toBeTruthy();
    fireEvent.click(await screen.findByLabelText("Edit device laptop"));
    fireEvent.change(await screen.findByLabelText(/^Name/), { target: { value: "   " } });
    expect(screen.getByText("A device needs a name.")).toBeTruthy();
    expect((screen.getByRole("button", { name: "Save" }) as HTMLButtonElement).disabled).toBe(
      true,
    );
    expect(calls.some((c) => c.method === "PATCH")).toBe(false);
  });

  it("shows a refusal from the server in words", async () => {
    mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
      "POST /operations": [
        409,
        {
          error: {
            code: "controller_offline",
            message: "The machine laptop has not reported recently.",
            retryable: true,
          },
        },
      ],
    });
    render(<MachinesPage />);
    fireEvent.click(await screen.findByLabelText("Restart pm-agent"));
    expect(
      await screen.findByText("The machine laptop has not reported recently."),
    ).toBeTruthy();
  });

  it("labels and offers the providers the server lists", async () => {
    mockManagement({
      "GET /providers": [
        200,
        {
          providers: [
            ...servedProviders,
            { id: "newcli", label: "New CLI", advanced_fields: [] },
          ],
        },
      ],
      "GET /controllers": [
        200,
        [
          {
            ...laptop,
            status: {
              ...laptop.status!,
              providers: [{ ...laptop.status!.providers[0]!, provider: "newcli" }],
            },
          },
        ],
      ],
      "GET /agents": [200, []],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText("New CLI")).toBeTruthy();
    fireEvent.click(screen.getByRole("button", { name: "New managed agent" }));
    fireEvent.mouseDown(await screen.findByRole("combobox", { name: "Provider" }));
    const options = (await screen.findAllByRole("option")).map((o) => o.textContent);
    expect(options).toEqual(["Claude Code", "Codex", "New CLI"]);
  });

  it("creates a new agent in auto mode, with bypass off, unless told otherwise", async () => {
    const calls = mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, []],
      "GET /operations": [200, []],
      "POST /agents": [201, pmAgent],
    });
    render(<MachinesPage />);
    fireEvent.click(await screen.findByRole("button", { name: "New managed agent" }));
    const autoMode = (await screen.findByLabelText(/^Auto mode/)) as HTMLInputElement;
    const bypass = screen.getByLabelText(/^Bypass permissions/) as HTMLInputElement;
    expect(autoMode.checked).toBe(true);
    expect(bypass.checked).toBe(false);
    fireEvent.change(screen.getByLabelText(/^Name/), { target: { value: "pm-agent" } });
    fireEvent.change(screen.getByLabelText(/^Description/), { target: { value: "Writes PRDs" } });
    fireEvent.click(screen.getByRole("button", { name: "Create" }));
    await waitFor(() =>
      expect(calls.find((c) => c.method === "POST")?.body).toMatchObject({
        definition: { auto_mode: true, auto_approve: false },
      }),
    );
  });

  it("keeps an agent's auto mode as it is and greys it out under bypass", async () => {
    const calls = mockManagement({
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
      "PATCH /agents/a1": [200, pmAgent],
    });
    render(<MachinesPage />);
    fireEvent.click(await screen.findByLabelText("Edit pm-agent"));
    const autoMode = (await screen.findByLabelText(/^Auto mode/)) as HTMLInputElement;
    expect(autoMode.checked).toBe(false);
    fireEvent.click(screen.getByLabelText(/^Bypass permissions/));
    expect(autoMode.disabled).toBe(true);
    fireEvent.click(screen.getByRole("button", { name: "Save" }));
    await waitFor(() =>
      expect(calls.find((c) => c.method === "PATCH")?.body).toMatchObject({
        definition: { auto_mode: false, auto_approve: true },
      }),
    );
  });

  it("says when the provider list cannot load, and shows providers by id", async () => {
    mockManagement({
      "GET /providers": [500, { detail: "boom" }],
      "GET /controllers": [200, [laptop]],
      "GET /agents": [200, [pmAgent]],
      "GET /operations": [200, []],
    });
    render(<MachinesPage />);
    expect(await screen.findByText(/Could not load the list of providers/)).toBeTruthy();
    expect(await screen.findByText("codex: login expired")).toBeTruthy();
  });
});