Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

10.8 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from "vitest";
import userEvent, { PointerEventsCheckLevel } from "@testing-library/user-event";
import { fireEvent, renderWithProviders, screen, waitFor, within } from "../../../../../../tests/test-utils";
import { AccessGroupEditModal } from "./AccessGroupEditModal";
import { AccessGroupResponse } from "@/app/(dashboard)/hooks/accessGroups/useAccessGroups";
import * as networking from "@/components/networking";

const mutate = vi.fn();

vi.mock("@/app/(dashboard)/hooks/accessGroups/useEditAccessGroup", () => ({
  useEditAccessGroup: () => ({ mutate, isPending: false }),
}));

vi.mock("@/app/(dashboard)/hooks/agents/useAgents", () => ({
  useAgents: () => ({ data: { agents: [{ agent_id: "agent-1", agent_name: "Support Bot" }] } }),
}));

const manyServers = Array.from({ length: 20 }, (_, i) => ({
  server_id: `srv-${i + 1}`,
  server_name: `Server ${i + 1}`,
}));

vi.mock("@/app/(dashboard)/hooks/mcpServers/useMCPServers", () => ({
  useMCPServers: () => ({ data: [{ server_id: "srv-1", server_name: "Files" }, ...manyServers.slice(1)] }),
}));

vi.mock("@/components/ModelSelect/ModelSelect", () => ({
  ModelSelect: ({ value, onChange }: { value: string[]; onChange: (next: string[]) => void }) => (
    <button type="button" aria-label="model-select" onClick={() => onChange([...(value ?? []), "gpt-4"])}>
      {(value ?? []).join(",")}
    </button>
  ),
}));

vi.mock("@/components/networking");

vi.mock("@/components/skills/SkillSelector", () => ({
  default: ({ value, onChange }: { value?: string[]; onChange: (next: string[]) => void }) => (
    <div>
      <button type="button" aria-label="skill-select" onClick={() => onChange([...(value ?? []), "private-plugin"])}>
        {(value ?? []).join(",")}
      </button>
      <button type="button" aria-label="skill-clear" onClick={() => onChange([])} />
    </div>
  ),
}));

vi.mock("@/lib/toast", () => ({
  toast: { success: vi.fn(), fromError: vi.fn(), error: vi.fn() },
}));

const setup = () => userEvent.setup({ pointerEventsCheck: PointerEventsCheckLevel.Never });
type User = ReturnType<typeof setup>;

const accessGroup: AccessGroupResponse = {
  access_group_id: "ag-1",
  access_group_name: "Engineering",
  description: "Engineers",
  access_model_names: ["gpt-4"],
  access_mcp_server_ids: ["srv-1"],
  mcp_tool_permissions: { "srv-1": ["read_file"] },
  access_agent_ids: ["agent-1"],
  access_skill_names: ["old-plugin"],
  assigned_team_ids: [],
  assigned_key_ids: [],
  access_mcp_servers: [{ id: "srv-1", name: "Server One" }],
  access_agents: [{ id: "agent-1", name: "Agent One" }],
  assigned_teams: [],
  assigned_keys: [],
  created_at: "2024-01-01T00:00:00Z",
  created_by: "user-1",
  updated_at: "2024-01-02T00:00:00Z",
  updated_by: "user-1",
};

const renderModal = (data: AccessGroupResponse = accessGroup) =>
  renderWithProviders(<AccessGroupEditModal visible accessGroup={data} onCancel={vi.fn()} />);

const save = async (user: User) => user.click(screen.getByRole("button", { name: "Save Changes" }));

const variables = () => mutate.mock.calls.at(-1)?.[0] as { accessGroupId: string; params: Record<string, unknown> };

describe("AccessGroupEditModal submit payload", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    vi.mocked(networking.fetchMCPToolsets).mockResolvedValue([]);
    vi.mocked(networking.fetchMCPAccessGroups).mockResolvedValue([]);
    vi.mocked(networking.fetchMCPServers).mockResolvedValue([
      { server_id: "srv-1", server_name: "Files", alias: "Files" },
    ]);
    vi.mocked(networking.listMCPTools).mockResolvedValue({
      tools: [
        { name: "read_file", description: "Read a file" },
        { name: "write_file", description: "Write a file" },
      ],
      error: false,
    });
  });

  it("sends exactly the antd payload for an untouched save", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());

    expect(mutate).toHaveBeenCalledTimes(1);
    expect(variables().accessGroupId).toBe("ag-1");
    expect(variables().params).toStrictEqual({
      access_group_name: "Engineering",
      description: "Engineers",
      access_model_names: undefined,
      access_mcp_server_ids: undefined,
      access_agent_ids: undefined,
      access_skill_names: undefined,
    });
  });

  it("sends the skills picked on the Skills tab", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /Skills/ }));
    await user.click(screen.getByLabelText("skill-select"));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.access_skill_names).toStrictEqual(["old-plugin", "private-plugin"]);
    expect(variables().params.access_agent_ids).toBeUndefined();
  });

  it("sends an empty list when every skill is removed on the Skills tab", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /Skills/ }));
    await user.click(screen.getByLabelText("skill-clear"));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.access_skill_names).toStrictEqual([]);
  });

  it("sends a tab's field only once that tab has been visited", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /MCP Servers/ }));
    await user.click(screen.getByRole("tab", { name: /Agents/ }));
    await user.click(screen.getByRole("tab", { name: /General Info/ }));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params).toStrictEqual({
      access_group_name: "Engineering",
      description: "Engineers",
      access_model_names: undefined,
      access_mcp_server_ids: ["srv-1"],
      access_agent_ids: ["agent-1"],
      access_skill_names: undefined,
    });
  });

  it("coerces a null description to an empty string", async () => {
    const user = setup();
    renderModal({ ...accessGroup, description: null });
    await screen.findByDisplayValue("Engineering");

    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.description).toBe("");
  });

  it("does not trim surrounding whitespace from the group name", async () => {
    const user = setup();
    renderModal();
    const nameInput = await screen.findByDisplayValue("Engineering");

    await user.clear(nameInput);
    fireEvent.change(nameInput, { target: { value: "  Padded  " } });
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.access_group_name).toBe("  Padded  ");
  });

  it("never sends server-only fields from the loaded record", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params).not.toHaveProperty("access_group_id");
    expect(variables().params).not.toHaveProperty("created_at");
    expect(variables().params).not.toHaveProperty("assigned_team_ids");
    expect(variables().params).not.toHaveProperty("assigned_key_ids");
  });

  it("does not submit when the group name is cleared", async () => {
    const user = setup();
    renderModal();
    const nameInput = await screen.findByDisplayValue("Engineering");

    await user.clear(nameInput);
    await save(user);

    expect(await screen.findByText("Please enter the access group name")).toBeInTheDocument();
    expect(mutate).not.toHaveBeenCalled();
  });

  it("does not save when Enter is pressed in the name field", async () => {
    const user = setup();
    renderModal();
    const nameInput = await screen.findByDisplayValue("Engineering");

    await user.type(nameInput, "{Enter}");

    expect(mutate).not.toHaveBeenCalled();
  });

  it("sends the edited tool checklist as mcp_tool_permissions, an emptied one as an explicit []", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /MCP Servers/ }));
    await user.click(await screen.findByRole("radio", { name: "Flat List" }));
    await user.click(await screen.findByRole("checkbox", { name: "read_file" }));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.mcp_tool_permissions).toStrictEqual({ "srv-1": [] });
  });

  it("renders each selected MCP server as its own removable chip and drops one on remove", async () => {
    const user = setup();
    renderModal();
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /MCP Servers/ }));
    const chip = await screen.findByLabelText("Files");
    expect(chip).toHaveAttribute("data-slot", "combobox-chip");
    expect(screen.queryByText("srv-1")).not.toBeInTheDocument();

    await user.click(within(chip).getByRole("button"));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.access_mcp_server_ids).toStrictEqual([]);
  });

  it("keeps 20 selected MCP servers as separate chips instead of one joined string", async () => {
    const user = setup();
    renderModal({ ...accessGroup, access_mcp_server_ids: manyServers.map((s) => s.server_id) });
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /MCP Servers/ }));
    await screen.findByLabelText("Server 20");
    const chips = screen.getAllByLabelText(/^(Files|Server \d+)$/);
    expect(chips).toHaveLength(20);
    expect(chips.map((chip) => chip.textContent)).toStrictEqual([
      "Files",
      ...manyServers.slice(1).map((s) => s.server_name),
    ]);
    expect(screen.queryByText(/Server 2, Server 3/)).not.toBeInTheDocument();

    await user.click(within(screen.getByLabelText("Server 7")).getByRole("button"));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.access_mcp_server_ids).toStrictEqual(
      manyServers.map((s) => s.server_id).filter((id) => id !== "srv-7"),
    );
  });

  it("sends models chosen on the Models tab", async () => {
    const user = setup();
    renderModal({ ...accessGroup, access_model_names: [] });
    await screen.findByDisplayValue("Engineering");

    await user.click(screen.getByRole("tab", { name: /Models/ }));
    await user.click(await screen.findByLabelText("model-select"));
    await save(user);

    await waitFor(() => expect(mutate).toHaveBeenCalled());
    expect(variables().params.access_model_names).toStrictEqual(["gpt-4"]);
  });
});