Skip to content

The platform for continuously improving AI agents.

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

import { RunFlow } from "./run-flow";

const api = vi.hoisted(() => ({ plan: vi.fn(), start: vi.fn() }));
const scrollIntoView = Element.prototype.scrollIntoView;
beforeEach(() => {
  api.plan.mockImplementation(async ({ experimentPlanInputRequest: input }) => ({
    ...input,
    costNote: "",
    costUsd: null,
    entries: [],
    fingerprint: "reviewed-fingerprint",
    inputs: [],
    jobNote: "",
    nodeAttempts: 2,
    resources: {},
  }));
  Element.prototype.scrollIntoView = vi.fn();
  vi.stubGlobal(
    "ResizeObserver",
    class {
      observe() {}
      unobserve() {}
      disconnect() {}
    }
  );
});
vi.mock("@/client", () => ({
  default: {
    researchExperiments: {
      researchExperimentsPlanCreate: api.plan,
      researchExperimentsRunCreate: api.start,
    },
  },
}));
afterEach(() => {
  cleanup();
  vi.clearAllMocks();
  vi.unstubAllGlobals();
  Element.prototype.scrollIntoView = scrollIntoView;
});

it("retries an uncertain run with the same key and selects its receipt instead of another user's newer run", async () => {
  const onStarted = vi.fn();
  api.start.mockRejectedValueOnce(new Error("Connection interrupted"));
  api.start.mockImplementationOnce(async (request) => ({
    record: {
      runs: [
        { id: "another-run", request_key: "unrelated" },
        { id: "our-run", request_key: `flow:flow:${request.experimentRunInputRequest.requestKey}` },
      ],
    },
  }));
  const client = new QueryClient({ defaultOptions: { mutations: { retry: false } } });
  render(
    <QueryClientProvider client={client}>
      <RunFlow
        disabled={false}
        document={{ edges: [], nodes: [] }}
        experiment="flow"
        onStarted={onStarted}
        save={async () => 3}
      />
    </QueryClientProvider>
  );
  fireEvent.click(screen.getByRole("button", { name: "Run" }));
  expect(api.start).not.toHaveBeenCalled();
  fireEvent.click(screen.getByRole("button", { name: "Review run" }));
  fireEvent.click(await screen.findByRole("button", { name: "Start reviewed run" }));
  await screen.findByText("Connection interrupted");
  fireEvent.click(screen.getByRole("button", { name: "Start reviewed run" }));
  await waitFor(() => expect(onStarted).toHaveBeenCalledWith(expect.anything(), "our-run"));
  expect(api.start.mock.calls[0][0].experimentRunInputRequest).toEqual(
    api.start.mock.calls[1][0].experimentRunInputRequest
  );
});

it("rejects invalid structured parameters before saving or starting", async () => {
  const save = vi.fn();
  const client = new QueryClient();
  render(
    <QueryClientProvider client={client}>
      <RunFlow
        disabled={false}
        document={{ edges: [], nodes: [], parameters: { seed: { type: "integer" } } }}
        experiment="flow"
        onStarted={vi.fn()}
        save={save}
      />
    </QueryClientProvider>
  );
  fireEvent.click(screen.getByRole("button", { name: "Run" }));
  fireEvent.change(screen.getByLabelText("seed"), { target: { value: "not-a-number" } });
  fireEvent.click(screen.getByRole("button", { name: "Review run" }));
  await screen.findByText("seed: enter a valid integer");
  expect(save).not.toHaveBeenCalled();
  expect(api.start).not.toHaveBeenCalled();
});

it("reuses recorded results only when selected and sends the requested restart boundary", async () => {
  api.start.mockImplementation(async (request) => ({
    record: {
      runs: [
        { id: "replay", request_key: `flow:flow:${request.experimentRunInputRequest.requestKey}` },
      ],
    },
  }));
  const onStarted = vi.fn();
  render(
    <QueryClientProvider client={new QueryClient()}>
      <RunFlow
        disabled={false}
        document={{
          edges: [],
          nodes: [
            {
              config: {},
              id: "changed",
              kind: "compare",
              notes: "",
              operation: null,
              position: { x: 0, y: 0 },
              title: "Select model",
            },
          ],
        }}
        experiment="flow"
        onStarted={onStarted}
        previous={{
          artifacts: [],
          budget: {},
          completed_at: "2026-11-17T00:01:00Z",
          created_at: "2026-11-17T00:00:00Z",
          current_revision: 3,
          execution: "flow",
          id: "measured",
          nodes: [
            {
              action: "measurement",
              arguments: {},
              completed_at: null,
              current: true,
              identity: "measured",
              node: "evaluate",
              outputs: { scores: { kind: "scores" } },
              result: {},
              revision: 3,
              started_at: null,
              state: "completed",
              tool: "benchmark",
            },
          ],
          result: {},
          revision: 3,
          state: "completed",
        }}
        save={async () => 4}
      />
    </QueryClientProvider>
  );
  fireEvent.click(screen.getByRole("button", { name: "Run" }));
  expect(api.start).not.toHaveBeenCalled();
  const choice = screen.getByRole("checkbox", { name: "Reuse recorded development results" });
  expect(choice.getAttribute("aria-checked")).toBe("false");
  fireEvent.click(choice);
  fireEvent.keyDown(screen.getByRole("combobox", { name: "Monitoring" }), { key: "ArrowDown" });
  fireEvent.click(await screen.findByRole("option", { name: "Apply permitted corrections" }));
  fireEvent.keyDown(screen.getByRole("combobox", { name: "Rerun from" }), { key: "ArrowDown" });
  fireEvent.click(await screen.findByRole("option", { name: "Select model" }));
  fireEvent.click(screen.getByRole("button", { name: "Review run" }));
  expect(api.start).not.toHaveBeenCalled();
  fireEvent.click(await screen.findByRole("button", { name: "Start reviewed run" }));
  await waitFor(() => expect(onStarted).toHaveBeenCalled());
  expect(api.start.mock.calls[0][0].experimentRunInputRequest).toMatchObject({
    operator: "remediate",
    rerunFrom: ["changed"],
    reuseRun: "measured",
    revision: 4,
  });
});