Skip to content

The platform for continuously improving AI agents.

7.2 KB
Raw Blame
// @vitest-environment jsdom
// covers: console-logic
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";

import api from "@/client";
import { TooltipProvider } from "@/components/ui/tooltip";
import { BenchmarkModels } from "./benchmark-models";
import { BenchmarkOverview } from "./benchmark-overview";
import { benchmarkRows } from "./benchmark-rows";
import type { ExperimentBlock, ExperimentDocument } from "./document";

const node = (id: string, kind: ExperimentBlock["kind"], config = {}): ExperimentBlock => ({
  config,
  id,
  kind,
  notes: "",
  operation: null,
  position: { x: 0, y: 0 },
  title: id,
});
const benchmark = (id: string, model: string): ExperimentBlock => ({
  ...node(id, "evaluate"),
  operation: {
    arguments: {
      generation: { kind: "rouge", max_new_tokens: 256 },
      participants: [{ key: "reference", kind: "foundation", model }],
    },
    tool: "benchmark",
  },
});
const nodes = [
  benchmark("benchmark-a", "Qwen/Qwen3-0.6B"),
  benchmark("benchmark-b", "Qwen/Qwen3-1.7B"),
  node("final", "qualify"),
];
const document: ExperimentDocument = {
  edges: [
    { input: "data", output: "data", source: "Medical QA", target: "split" },
    ...nodes.flatMap((node) => [
      { input: "model", output: "model", source: "trained", target: node.id },
      {
        input: "data",
        output: node.kind === "qualify" ? "final" : "development",
        source: "split",
        target: node.id,
      },
    ]),
  ],
  nodes: [
    node("Medical QA", "data"),
    node("split", "split"),
    {
      ...node("trained", "train", { model: "meta-llama/Llama-3.2-1B-Instruct" }),
      operation: {
        arguments: {
          arguments: { qualification: { kind: "rouge", max_new_tokens: 256 } },
          operation: "create",
        },
        tool: "training",
      },
    },
    ...nodes,
  ],
};
afterEach(cleanup);

it("groups each model once and retains the connected eval set for each test", () => {
  const configured = structuredClone(document);
  const evaluation = configured.nodes.find((node) => node.id === "benchmark-b")!;
  evaluation.operation = { ...evaluation.operation!, tool: "score" };
  configured.nodes.push(node("Medical-answer suite", "suite"));
  configured.edges.push(
    { input: "suite", output: "suite", source: "Medical-answer suite", target: "benchmark-a" },
    { input: "suite", output: "suite", source: "Medical-answer suite", target: "benchmark-b" }
  );
  const rows = benchmarkRows(
    configured,
    configured.nodes.filter((node) => nodes.some(({ id }) => node.id === id))
  );
  expect(rows).toHaveLength(2);
  const trained = rows.find((row) => row.candidate?.kind === "trained");
  expect(
    trained?.tests.map(({ dataset, evalSet, node }) => [dataset.partition, evalSet?.title, node])
  ).toEqual([
    ["development", "Medical-answer suite", "benchmark-a"],
    ["development", "Medical-answer suite", "benchmark-b"],
    ["final", undefined, "final"],
  ]);
});

it("shows three chips per model with dataset and eval set navigation on the chips", async () => {
  const select = vi.fn(),
    edit = vi.fn();
  const client = new QueryClient();
  render(
    <QueryClientProvider client={client}>
      <TooltipProvider>
        <BenchmarkOverview document={document} nodes={nodes} onEdit={edit} onSelect={select} />
      </TooltipProvider>
    </QueryClientProvider>
  );
  const list = screen.getByRole("list", { name: "Benchmark entries" });
  const rows = within(list).getAllByRole("listitem");
  expect(rows).toHaveLength(3);
  expect(rows.every((row) => row.children.length === 3)).toBe(true);
  expect(within(list).queryByRole("button", { name: "Settings" })).toBeNull();
  fireEvent.click(within(rows[2]).getByRole("button", { name: "Eval set: No eval set" }));
  expect(edit).toHaveBeenCalledWith("benchmark-b");
  const trained = rows[0];
  fireEvent.keyDown(within(trained).getByRole("button", { name: "Eval set: No eval set" }), {
    key: "Enter",
  });
  fireEvent.click(
    await screen.findByRole("menuitem", { name: "No eval set · Medical QA · Final holdout" })
  );
  expect(edit).toHaveBeenLastCalledWith("final");
  fireEvent.keyDown(
    within(trained).getByRole("button", { name: "Dataset: Medical QA · 2 splits" }),
    { key: "Enter" }
  );
  fireEvent.click(await screen.findByRole("menuitem", { name: "Medical QA · Development" }));
  expect(select).toHaveBeenLastCalledWith("split");
  client.clear();
});

it("adds exact OpenRouter and trained-job identities from the benchmark catalogue", async () => {
  vi.stubGlobal(
    "ResizeObserver",
    class {
      observe() {}
      unobserve() {}
      disconnect() {}
    }
  );
  const scrollIntoView = Element.prototype.scrollIntoView;
  Element.prototype.scrollIntoView = () => {};
  const catalogue = vi.spyOn(api.models, "modelsCatalogRetrieve").mockResolvedValue({
    models: [{ id: "openai/gpt-4o-mini", name: "OpenAI GPT-4o mini" }],
    upstreamAvailable: true,
  } as Awaited<ReturnType<typeof api.models.modelsCatalogRetrieve>>);
  const jobs = vi.spyOn(api.finetuningJobs, "finetuningJobsList").mockResolvedValue({
    results: [
      {
        baseModel: "meta-llama/Llama-3.2-1B-Instruct",
        id: "saved-job",
        name: "Trained support model",
        trainingContract: { evaluation: "chat_generation" },
      },
    ],
  } as Awaited<ReturnType<typeof api.finetuningJobs.finetuningJobsList>>);
  const select = vi.fn();
  const client = new QueryClient();
  try {
    render(
      <QueryClientProvider client={client}>
        <BenchmarkModels locked={false} onChange={select} projectId="project" settings={{}} />
      </QueryClientProvider>
    );
    fireEvent.click(screen.getByRole("button", { name: "Add benchmark model" }));
    expect(await screen.findByRole("option", { name: /OpenAI GPT-4o mini/ })).toBeTruthy();
    expect(screen.queryByRole("option", { name: /Training catalogue entry/ })).toBeNull();
    fireEvent.click(screen.getByRole("option", { name: /OpenAI GPT-4o mini/ }));
    expect(select).toHaveBeenCalledWith({
      baseline: expect.any(String),
      participants: [expect.objectContaining({ kind: "external", model: "openai/gpt-4o-mini" })],
    });
    fireEvent.click(screen.getByRole("button", { name: "Add benchmark model" }));
    fireEvent.click(screen.getByRole("option", { name: /Trained support model/ }));
    expect(select).toHaveBeenLastCalledWith({
      baseline: expect.any(String),
      participants: [expect.objectContaining({ job: "saved-job", kind: "trained" })],
    });
  } finally {
    cleanup();
    catalogue.mockRestore();
    jobs.mockRestore();
    vi.unstubAllGlobals();
    Element.prototype.scrollIntoView = scrollIntoView;
    client.clear();
  }
});

it("shows an event-bound model before its model ID is known", () => {
  const release = benchmark("release", "unused");
  release.operation!.arguments.participants = [
    {
      key: "release",
      kind: "external",
      model: { $parameter: "release_model" },
      name: { $parameter: "release_model" },
    },
  ];
  const rows = benchmarkRows({ edges: [], nodes: [release] }, [release]);
  expect(rows[0].candidate?.model).toBeUndefined();
  expect(rows[0].candidate?.title).toBe("New OpenRouter model");
});