Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
16.6 KB
Raw Blame
import React from "react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { fireEvent, screen, within } from "@testing-library/react";
import type { Agent } from "@multica/core/types";
import type { AgentActivity } from "@multica/core/agents";
import type { SupportedLocale } from "@multica/core/i18n";
import { renderWithI18n } from "../../test/i18n";
import { NavigationProvider, type NavigationAdapter } from "../../navigation";
import { AgentsPage } from "./agents-page";

// These tests pin the `listReady` render gate (MUL-4511): the Agents list must
// not paint real rows until the auxiliary queries the active sort field /
// filter depends on have landed, or it sorts on placeholder values
// (lastActiveDays null→Infinity, runCount 0) and visibly re-orders when each
// query resolves. The gate waits per need — nothing for name/created,
// run-counts for runs, activity + run-counts for the default lastActive,
// presence when an availability filter is active — and never blocks the empty
// state on those queries.

const mocks = vi.hoisted(() => ({
  agents: [] as Agent[],
  agentsLoading: false,
  runCounts: [] as Array<{ agent_id: string; run_count: number }>,
  runCountsPending: false,
  activity: {
    byAgent: new Map<string, AgentActivity>(),
    loading: false,
  },
  presence: {
    byAgent: new Map<string, unknown>(),
    loading: false,
  },
  viewState: {
    scope: "all",
    sortField: "lastActive" as string,
    sortDirection: "desc" as string,
    hiddenColumns: ["created"] as string[],
    filters: {
      availability: [] as string[],
      runtimes: [] as string[],
      owners: [] as string[],
      models: [] as string[],
      access: [] as string[],
    },
    search: "",
    setSearch: vi.fn(),
    setScope: vi.fn(),
    toggleSort: vi.fn(),
    setSortField: vi.fn(),
    setSortDirection: vi.fn(),
    toggleColumn: vi.fn(),
    toggleFilter: vi.fn(),
    clearFilters: vi.fn(),
  },
}));

vi.mock("@tanstack/react-query", () => ({
  useQuery: (options: { queryKey?: readonly unknown[] }) => {
    const key = options.queryKey?.[0];
    if (key === "agents") {
      return {
        data: mocks.agents,
        isLoading: mocks.agentsLoading,
        error: null,
        refetch: vi.fn(),
      };
    }
    if (key === "agent-run-counts") {
      return { data: mocks.runCounts, isPending: mocks.runCountsPending };
    }
    return { data: [], isLoading: false, isPending: false, isSuccess: true };
  },
  useQueryClient: () => ({ invalidateQueries: vi.fn() }),
  queryOptions: <T,>(options: T) => options,
}));

// The list virtualizes; render every row so DOM order reflects sort order.
vi.mock("@tanstack/react-virtual", () => ({
  useVirtualizer: ({ count }: { count: number }) => ({
    getVirtualItems: () =>
      Array.from({ length: count }, (_, index) => ({
        index,
        key: index,
        start: index * 64,
        end: (index + 1) * 64,
        size: 64,
      })),
    getTotalSize: () => count * 64,
  }),
}));

vi.mock("sonner", () => ({
  toast: { success: vi.fn(), error: vi.fn() },
}));

vi.mock("@multica/core/agents", () => ({
  isAgentRuntimeBound: (agent: { runtime_id: string; runtime_bound?: boolean }) =>
    agent.runtime_bound !== false && agent.runtime_id.length > 0,
  agentRunCounts30dOptions: () => ({ queryKey: ["agent-run-counts"] }),
  useWorkspaceActivityMap: () => mocks.activity,
  useWorkspacePresenceMap: () => mocks.presence,
  VISIBILITY_TOOLTIP: { private: "Private", workspace: "Workspace" },
  effectiveAccessScope: (pm: unknown, it: unknown) => {
    if (pm !== "public_to") return "owner-only";
    if ((Array.isArray(it) ? it : []).some((t) => (t as {target_type?: string})?.target_type === "workspace")) return "workspace";
    return "specific-people";
  },
  ALL_ACCESS_SCOPES: ["workspace", "specific-people", "owner-only"],
}));

vi.mock("@multica/core/agents/stores", () => ({
  useAgentsViewStore: (selector: (state: unknown) => unknown) =>
    selector(mocks.viewState),
  AGENT_DEFAULT_HIDDEN_COLUMNS: ["created"],
  AGENT_SCOPES: ["mine", "all", "archived"],
}));

vi.mock("@multica/core/api", () => ({
  api: { archiveAgent: vi.fn(), restoreAgent: vi.fn() },
}));

vi.mock("@multica/core/auth", () => ({
  useAuthStore: (selector: (state: unknown) => unknown) =>
    selector({ user: { id: "user-1" } }),
}));

vi.mock("@multica/core/hooks", () => ({
  useWorkspaceId: () => "workspace-1",
}));

vi.mock("@multica/core/paths", () => ({
  useWorkspacePaths: () => ({
    newAgent: () => "/test-workspace/agents/new",
    newAgentManual: () => "/test-workspace/agents/new/manual",
    agentDetail: (id: string) => `/test-workspace/agents/${id}`,
    runtimes: () => "/test-workspace/runtimes",
  }),
}));

vi.mock("@multica/core/workspace/queries", () => ({
  agentListOptions: () => ({ queryKey: ["agents"] }),
  memberListOptions: () => ({ queryKey: ["members"] }),
  workspaceKeys: { agents: (wsId: string) => ["agents", wsId] },
}));

vi.mock("@multica/core/runtimes", () => ({
  runtimeListOptions: () => ({ queryKey: ["runtimes"] }),
}));

// View-layer children with heavy / portal deps — stub to keep the test focused
// on the gate, not on avatars, row menus, the filter/display menus, or
// tooltip portals.
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => null }));
vi.mock("./agent-row-actions", () => ({ AgentRowActions: () => null }));
vi.mock("./agent-list-toolbar", () => ({
  AgentListFilterMenu: () => <div data-testid="agent-list-filter" />,
  countActiveFilterDimensions: (filters: Record<string, unknown[]>) =>
    Object.values(filters).filter((values) => values.length > 0).length,
}));
vi.mock("../presence", () => ({ availabilityConfig: {} }));
vi.mock("@multica/ui/components/ui/skeleton", () => ({
  Skeleton: (props: Record<string, unknown>) => (
    <div data-testid="skeleton" {...props} />
  ),
}));
vi.mock("@multica/ui/components/ui/tooltip", () => ({
  Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
  TooltipTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,
  TooltipContent: ({ children }: { children: React.ReactNode }) => (
    <div role="tooltip">{children}</div>
  ),
}));

const BASE_AGENT: Agent = {
  id: "agent-base",
  workspace_id: "workspace-1",
  runtime_id: "runtime-1",
  name: "Base Agent",
  description: "",
  instructions: "",
  avatar_url: null,
  runtime_mode: "cloud",
  runtime_config: {},
  custom_args: [],
  visibility: "workspace",
  permission_mode: "private",
  invocation_targets: [],
  status: "idle",
  max_concurrent_tasks: 1,
  model: "claude",
  owner_id: "user-1",
  skills: [],
  created_at: "2026-06-01T00:00:00Z",
  updated_at: "2026-06-01T00:00:00Z",
  archived_at: null,
  archived_by: null,
};

function makeAgent(over: Partial<Agent>): Agent {
  return { ...BASE_AGENT, ...over };
}

// Build a 30-bucket activity series whose most-recent bucket with runs is
// `daysAgo` days back — `lastActiveDaysAgo` reads exactly this.
function activityLastActive(daysAgo: number): AgentActivity {
  const buckets = Array.from({ length: 30 }, () => ({ total: 0, failed: 0, completed: 0, cancelled: 0 }));
  buckets[29 - daysAgo] = { total: 1, failed: 0, completed: 1, cancelled: 0 };
  return { buckets, daysSinceCreated: 30 };
}

const ALPHA = makeAgent({ id: "a-alpha", name: "Alpha Agent" });
const BETA = makeAgent({ id: "a-beta", name: "Beta Agent" });

function makeAdapter(
  overrides: Partial<NavigationAdapter> = {},
): NavigationAdapter {
  return {
    push: vi.fn(),
    replace: vi.fn(),
    back: vi.fn(),
    pathname: "/test-workspace/agents",
    searchParams: new URLSearchParams(),
    hash: "",
    getShareableUrl: (p) => p,
    ...overrides,
  };
}

function renderPage(locale?: SupportedLocale) {
  const adapter = makeAdapter();
  renderWithI18n(
    <NavigationProvider value={adapter}>
      <AgentsPage />
    </NavigationProvider>,
    { locale },
  );
  return adapter;
}

/** Beta before Alpha in document order? */
function betaPrecedesAlpha(): boolean {
  const alpha = screen.getByText("Alpha Agent");
  const beta = screen.getByText("Beta Agent");
  return Boolean(
    beta.compareDocumentPosition(alpha) & Node.DOCUMENT_POSITION_FOLLOWING,
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  mocks.agents = [ALPHA, BETA];
  mocks.agentsLoading = false;
  mocks.runCounts = [];
  mocks.runCountsPending = false;
  mocks.activity = { byAgent: new Map(), loading: false };
  mocks.presence = { byAgent: new Map(), loading: false };
  mocks.viewState.scope = "all";
  mocks.viewState.sortField = "lastActive";
  mocks.viewState.sortDirection = "desc";
  mocks.viewState.hiddenColumns = ["created"];
  mocks.viewState.search = "";
  mocks.viewState.filters = {
    availability: [],
    runtimes: [],
    owners: [],
    models: [],
    access: [],
  };
});

describe("AgentsPage listReady gate", () => {
  it("shows only a skeleton (no real rows) while lastActive deps are pending", () => {
    // Default lastActive sort depends on activity + run-counts.
    mocks.activity = { byAgent: new Map(), loading: true };
    mocks.runCountsPending = true;

    renderPage();

    expect(screen.queryByText("Alpha Agent")).not.toBeInTheDocument();
    expect(screen.queryByText("Beta Agent")).not.toBeInTheDocument();
    expect(screen.getAllByTestId("skeleton").length).toBeGreaterThan(0);
  });

  it("renders rows in the resolved lastActive order once deps land", () => {
    // Alpha active 5d ago, Beta active today → lastActive desc puts Beta first,
    // the opposite of the name-order fallback the ungated list would show.
    mocks.activity = {
      byAgent: new Map<string, AgentActivity>([
        [ALPHA.id, activityLastActive(5)],
        [BETA.id, activityLastActive(0)],
      ]),
      loading: false,
    };
    mocks.runCounts = [
      { agent_id: ALPHA.id, run_count: 0 },
      { agent_id: BETA.id, run_count: 0 },
    ];
    mocks.runCountsPending = false;

    renderPage();

    expect(screen.getByText("Alpha Agent")).toBeInTheDocument();
    expect(screen.getByText("Beta Agent")).toBeInTheDocument();
    expect(betaPrecedesAlpha()).toBe(true);
  });

  it("renders rows immediately for name sort without waiting on activity/run-counts", () => {
    mocks.viewState.sortField = "name";
    mocks.viewState.sortDirection = "asc";
    // Auxiliary queries are still in flight — name sort must not wait on them.
    mocks.activity = { byAgent: new Map(), loading: true };
    mocks.runCountsPending = true;
    mocks.presence = { byAgent: new Map(), loading: true };

    renderPage();

    expect(screen.getByText("Alpha Agent")).toBeInTheDocument();
    expect(screen.getByText("Beta Agent")).toBeInTheDocument();
    // name asc → Alpha before Beta.
    expect(betaPrecedesAlpha()).toBe(false);
  });

  it("shows a skeleton (not a false empty/false result) while an availability filter waits on presence", () => {
    // Availability filter needs presence; sort by name so ONLY presence gates.
    // Ungated, presence-null rows would all be filtered out → a false "no
    // matches" state. Gated, we hold on a skeleton instead.
    mocks.viewState.sortField = "name";
    mocks.viewState.filters.availability = ["online"];
    mocks.presence = { byAgent: new Map(), loading: true };

    renderPage();

    expect(screen.queryByText("Alpha Agent")).not.toBeInTheDocument();
    expect(screen.queryByText("Beta Agent")).not.toBeInTheDocument();
    expect(screen.getAllByTestId("skeleton").length).toBeGreaterThan(0);
  });

  it("keeps the header tools above the skeleton while the agent list loads", () => {
    // Tools that only mount once rows land shift the page mid-navigation
    // (MUL-8337).
    mocks.agents = [];
    mocks.agentsLoading = true;

    renderPage();

    const header = screen.getByRole("banner");
    expect(within(header).getByTestId("agent-list-filter")).toBeInTheDocument();
    expect(screen.getAllByTestId("skeleton").length).toBeGreaterThan(0);
    expect(
      screen.queryByRole("heading", { name: "Hire your first AI teammate" }),
    ).not.toBeInTheDocument();
  });

  it("introduces agents without blocking on auxiliary queries when there are none", () => {
    mocks.agents = [];
    // All auxiliary queries pending — the empty state must not wait on them.
    mocks.activity = { byAgent: new Map(), loading: true };
    mocks.runCountsPending = true;
    mocks.presence = { byAgent: new Map(), loading: true };

    renderPage();

    const intro = screen.getByRole("region", { name: "Hire your first AI teammate" });
    expect(within(intro).getByRole("button", { name: "New agent" })).toBeInTheDocument();
    expect(within(intro).getByRole("link", { name: /Read the docs/ })).toHaveAttribute(
      "href",
      "https://multica.ai/docs/agents",
    );
    const steps = within(intro).getByRole("list", { name: "Setup steps" });
    expect(within(steps).getByRole("link", { name: "Connect" })).toHaveAttribute(
      "href",
      "/test-workspace/runtimes",
    );
    expect(screen.queryByTestId("skeleton")).not.toBeInTheDocument();
  });
});

describe("AgentsPage header", () => {
  it("titles the page with the scope and switches scope from its menu", () => {
    renderPage();

    const header = screen.getByRole("banner");
    const title = within(header).getByRole("heading", { level: 1 });
    expect(title).toHaveTextContent("All agents");
    expect(within(header).queryByText(/\d/)).not.toBeInTheDocument();
    expect(screen.queryByRole("link", { name: /Learn more/ })).not.toBeInTheDocument();

    fireEvent.click(within(title).getByRole("button"));
    const options = screen.getAllByRole("menuitemradio");
    expect(options.map((option) => option.textContent)).toEqual([
      "My agents2",
      "All agents2",
      "Archived agents0",
    ]);
    fireEvent.click(options[0]!);
    expect(mocks.viewState.setScope).toHaveBeenCalledWith("mine");
  });

  it("localizes the scope title", () => {
    mocks.viewState.scope = "archived";
    renderPage("fr");

    expect(
      within(screen.getByRole("banner")).getByRole("heading", { level: 1 }),
    ).toHaveTextContent("Agents archivés");
  });

  it("offers Reset only while a filter narrows the list", () => {
    renderPage();
    expect(screen.queryByRole("button", { name: "Reset" })).not.toBeInTheDocument();
  });

  it("resets the filters", () => {
    mocks.viewState.filters.access = ["workspace"];
    renderPage();

    fireEvent.click(screen.getByRole("button", { name: "Reset" }));
    expect(mocks.viewState.clearFilters).toHaveBeenCalled();
  });

  it("puts display and create on the right, with create opening the new-agent flow", () => {
    const adapter = renderPage();

    const header = screen.getByRole("banner");
    expect(
      within(header).getByRole("button", { name: "Display settings" }),
    ).toBeInTheDocument();
    fireEvent.click(within(header).getByRole("button", { name: "New agent" }));
    expect(adapter.push).toHaveBeenCalledWith("/test-workspace/agents/new");
  });
});

describe("AgentsPage search (MUL-8490)", () => {
  it("opens the search from an icon beside the filter and writes the query to the store", () => {
    renderPage();
    const header = screen.getByRole("banner");
    expect(within(header).queryByRole("textbox")).not.toBeInTheDocument();

    fireEvent.click(within(header).getByRole("button", { name: "Search agents" }));
    const field = within(header).getByRole("textbox", { name: "Search agents" });
    expect(field).toHaveFocus();

    fireEvent.change(field, { target: { value: "beta" } });
    expect(mocks.viewState.setSearch).toHaveBeenCalledWith("beta");
  });

  it("narrows the list by the store's query, so it is still applied on return", () => {
    mocks.viewState.sortField = "name";
    mocks.viewState.search = "beta";

    renderPage();

    expect(screen.getByRole("textbox", { name: "Search agents" })).toHaveValue("beta");
    expect(screen.getByText("Beta Agent")).toBeInTheDocument();
    expect(screen.queryByText("Alpha Agent")).not.toBeInTheDocument();
  });

  it("names the query when nothing matches", () => {
    mocks.viewState.sortField = "name";
    mocks.viewState.search = "zeta";

    renderPage();

    expect(screen.getByText('No agents match "zeta".')).toBeInTheDocument();
  });

  it("clears the search together with the filters on Reset", () => {
    mocks.viewState.search = "beta";
    renderPage();

    fireEvent.click(screen.getByRole("button", { name: "Reset" }));
    expect(mocks.viewState.clearFilters).toHaveBeenCalled();
    expect(mocks.viewState.setSearch).toHaveBeenCalledWith("");
  });
});

describe("AgentsPage model column (GitHub #9500)", () => {
  it("renders the model column by default", () => {
    mocks.viewState.sortField = "name";

    renderPage();

    expect(screen.getByText("Model")).toBeInTheDocument();
    expect(screen.getAllByText("claude").length).toBeGreaterThan(0);
  });
});