Skip to content

The platform for continuously improving AI agents.

17.9 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, expect, it, vi } from "vitest";

import { TooltipProvider } from "@/components/ui/tooltip";
import {
  type Dataset,
  DatasetFromJSON,
  type ExperimentSource,
  type WorkshopMessage,
} from "@/openapi";
import { ExperimentAgent } from "./agent";
import type { ExperimentRecord } from "./document";

const api = vi.hoisted(() => ({
  change: vi.fn(),
  create: vi.fn(),
  inspectUpload: vi.fn(),
  list: vi.fn(),
  send: vi.fn(),
  sources: vi.fn(),
  stop: vi.fn(),
}));
vi.mock("@/client", () => ({
  default: {
    datasets: { datasetsCreate: api.create, datasetsList: api.list },
    researchExperiments: {
      researchExperimentsMessagesControlCreate: api.change,
      researchExperimentsMessagesCreate: api.send,
      researchExperimentsSourcesList: api.sources,
      researchExperimentsStopCreate: api.stop,
    },
    uploads: {
      uploadsChunkUpdate: ({ body, offset }: { body: Blob; offset: number }) =>
        Promise.resolve({ received: offset + body.size }),
      uploadsCreate: () =>
        Promise.resolve({ chunkBytes: 1024, maxBytes: 4096, uploadId: "upload" }),
      uploadsInspectCreate: api.inspectUpload,
      uploadsRetrieve: () => Promise.resolve({ received: 0 }),
    },
  },
}));
afterEach(() => {
  cleanup();
  vi.unstubAllGlobals();
  vi.clearAllMocks();
});
const record: ExperimentRecord = {
  document: { edges: [], nodes: [] },
  id: "experiment",
  name: "Compare models",
  node_identities: {},
  objective: "Compare models",
  revisions: [],
  runs: [
    {
      artifacts: [],
      budget: {},
      completed_at: null,
      created_at: "2026-11-16T00:00:00Z",
      current_revision: 1,
      id: "run",
      nodes: [],
      result: {},
      revision: 1,
      state: "running",
    },
  ],
  version: 1,
};
const liveMessages: WorkshopMessage[] = [
  { id: "run:user", role: "user", status: "delivered", text: "Compare models" },
  {
    code: "print(1)",
    id: "run:activity",
    role: "activity",
    status: "running",
    text: "Inspecting the source",
    tool: "python",
  },
  {
    id: "run:queued",
    queuePosition: 0,
    revision: 2,
    role: "user",
    status: "pending",
    text: "Also compare latency",
  },
];
function setup(
  shownRecord = record,
  messages = liveMessages,
  datasets: Dataset[] = [],
  sources: ExperimentSource[] = []
) {
  api.list.mockResolvedValue({ next: null, results: datasets });
  api.sources.mockResolvedValue(sources);
  vi.stubGlobal(
    "ResizeObserver",
    class {
      observe() {}
      unobserve() {}
      disconnect() {}
    }
  );
  vi.stubGlobal("matchMedia", () => ({
    addEventListener() {},
    matches: false,
    removeEventListener() {},
  }));
  Element.prototype.scrollIntoView = vi.fn();
  const client = new QueryClient({
    defaultOptions: { mutations: { retry: false }, queries: { retry: false } },
  });
  const beforeSend = vi.fn().mockResolvedValue(1);
  render(
    <QueryClientProvider client={client}>
      <TooltipProvider>
        <ExperimentAgent
          beforeSend={beforeSend}
          messages={messages}
          onAttach={() => {}}
          onSelect={() => {}}
          projectId="project"
          readOnly={false}
          record={shownRecord}
        />
      </TooltipProvider>
    </QueryClientProvider>
  );
  fireEvent.click(screen.getByRole("button", { name: "Open chat" }));
  return { beforeSend, client };
}

it("keeps chat available while a separate flow runs", async () => {
  api.send.mockResolvedValue({ id: "experiment" });
  const { client } = setup(
    {
      ...record,
      runs: [
        { ...record.runs[0], execution: "flow", id: "flow" },
        { ...record.runs[0], state: "completed" },
      ],
    },
    [
      liveMessages[0],
      { id: "run:answer", role: "assistant", status: "completed", text: "Saved the flow." },
      {
        id: "flow:training",
        role: "activity",
        status: "running",
        text: "Fine-tune candidate",
        tool: "training",
      },
    ]
  );
  expect(screen.getByText("Saved the flow.")).toBeTruthy();
  expect(screen.queryByText("Fine-tune candidate")).toBeNull();
  expect(screen.queryByRole("button", { name: "Running tools" })).toBeNull();
  expect(screen.queryByRole("button", { name: "Stop" })).toBeNull();
  fireEvent.change(screen.getByRole("textbox", { name: "Research follow-up" }), {
    target: { value: "Describe the eval criteria" },
  });
  expect(screen.queryByRole("button", { name: "Queue" })).toBeNull();
  fireEvent.keyDown(screen.getByRole("textbox", { name: "Research follow-up" }), { key: "Enter" });
  await waitFor(() =>
    expect(api.send).toHaveBeenCalledWith(
      expect.objectContaining({
        experimentMessageInputRequest: expect.objectContaining({
          text: "Describe the eval criteria",
        }),
      })
    )
  );
  client.clear();
});

it("accepts a progress suggestion with Tab while the experiment is running", async () => {
  const { client } = setup();
  const input = screen.getByRole<HTMLTextAreaElement>("textbox", { name: "Research follow-up" });
  input.focus();
  await screen.findByText("Tab", { exact: true });
  fireEvent.keyDown(input, { key: "Tab" });
  expect(input.value).toBe("Summarize progress and flag anything that needs my input.");
  expect(api.send).not.toHaveBeenCalled();
  client.clear();
});

it("shows selected canvas references in the draft and sends them as links", async () => {
  const { client } = setup({
    ...record,
    document: {
      edges: [],
      nodes: [
        {
          config: {},
          id: "data_1",
          kind: "data",
          notes: "",
          operation: null,
          position: { x: 0, y: 0 },
          title: "Training cases",
        },
      ],
    },
  });
  expect(screen.queryByRole("button", { name: "Reference canvas item" })).toBeNull();
  const input = screen.getByRole<HTMLTextAreaElement>("textbox", { name: "Research follow-up" });
  fireEvent.change(input, { target: { value: "Check @Train" } });
  fireEvent.click(screen.getByRole("option", { name: "Training cases" }));
  expect(input.value).toBe("Check @Training cases ");
  expect(
    screen
      .getAllByText("Training cases")
      .some((node) => node.getAttribute("data-slot") === "chat-inline-citation")
  ).toBe(true);
  expect(api.send).not.toHaveBeenCalled();
  fireEvent.click(screen.getByRole("button", { name: "Add attachment" }));
  expect(screen.getByRole("button", { name: "Attach files" })).toBeTruthy();
  expect(screen.getByRole("button", { name: "Existing dataset" })).toBeTruthy();
  expect(screen.queryByRole("dialog", { name: "Project datasets" })).toBeNull();
  fireEvent.change(input, { target: { value: "Check @Training cases tomorrow" } });
  fireEvent.keyDown(input, { key: "Enter" });
  await waitFor(() =>
    expect(api.send).toHaveBeenCalledWith(
      expect.objectContaining({
        experimentMessageInputRequest: expect.objectContaining({
          text: "Check [@Training cases](#node=data_1) tomorrow",
        }),
      })
    )
  );
  client.clear();
});

it("uses the home attachment menu and tray for project datasets", async () => {
  const dataset = DatasetFromJSON({
    active: "cell",
    cells: [{ fingerprint: "pinned", id: "cell", state: "ok" }],
    id: "dataset",
    name: "Training cases",
    roles: ["source"],
    rows: 40,
    state: "idle",
  });
  const { client } = setup(
    record,
    liveMessages,
    [dataset],
    [
      {
        available: true,
        dataset: "dataset",
        fingerprint: "pinned",
        id: "cell",
        name: "Training cases",
        reason: "",
        title: "Source",
        version: 1,
      },
    ]
  );
  fireEvent.click(screen.getByRole("button", { name: "Add attachment" }));
  fireEvent.click(screen.getByRole("button", { name: "Existing dataset" }));
  const choice = await screen.findByRole("button", { name: "Training cases" });
  fireEvent.click(choice);
  expect(screen.getByRole("list", { name: "Attached data" })).toBeTruthy();
  expect(screen.getByRole("button", { name: "Remove Training cases from chat" })).toBeTruthy();
  client.clear();
});

it.each([
  { label: "Verifying results", phase: "verifying", state: "running" },
  { label: "Request complete", phase: "completed", state: "completed" },
  { label: "Blocked", phase: "blocked", state: "blocked" },
  { label: "Cancelled before execution", phase: "cancelled", state: "cancelled" },
  { label: "Waiting for your answer", phase: "drafting", state: "running", waiting: true },
])("keeps the request status ($label) distinct from finished tools", ({
  label,
  phase,
  state,
  waiting,
}) => {
  const { client } = setup({ ...record, runs: [{ ...record.runs[0], phase, state }] }, [
    liveMessages[0],
    { ...liveMessages[1], status: "completed" },
    waiting
      ? {
          id: "run:question",
          question: "target",
          questions: [
            {
              id: "target",
              multiSelect: false,
              options: ["Outcome", "Label"],
              question: "Which target?",
            },
          ],
          role: "assistant",
          status: "question_pending",
          text: "Questions",
        }
      : {
          id: "run:reply",
          role: "assistant",
          status: "completed",
          text: "I found two candidates.",
        },
  ]);
  const activity = screen.getByRole("region", { name: "Assistant activity" });
  expect(
    activity.querySelector('[data-slot="thinking-state-glyph"][data-status="done"]')
  ).toBeNull();
  fireEvent.click(screen.getByRole("button", { name: "Minimize chat" }));
  expect(
    screen.getByRole("textbox", { name: "Research follow-up" }).getAttribute("placeholder")
  ).toBe(label);
  const status = screen.getByText(label, { exact: true });
  expect(!!status.parentElement?.querySelector('[data-slot="spinner"]')).toBe(
    state === "running" && !waiting
  );
  client.clear();
});
it("shows real activity, restores a rejected follow-up, and stops the run", async () => {
  api.send.mockRejectedValue(new Error("Request could not be saved"));
  api.stop.mockResolvedValue({ id: "experiment" });
  const { client, beforeSend } = setup();
  const inspecting = await screen.findByText("Inspecting the source");
  expect(inspecting.closest("li")?.textContent).toContain("Running");
  expect(
    inspecting.closest("li")?.querySelector('[data-slot="tool-mark"][data-tool="python"]')
  ).toBeTruthy();
  expect(
    screen
      .getByRole("region", { name: "Assistant activity" })
      .querySelector('[data-slot="thinking-state-header"] [data-tool="python"]')
  ).toBeTruthy();
  expect(screen.getByText("Also compare latency")).toBeTruthy();
  fireEvent.change(screen.getByRole("textbox", { name: "Research follow-up" }), {
    target: { value: "Compare accuracy too" },
  });
  fireEvent.click(screen.getByRole("button", { name: "Queue" }));
  await waitFor(() => expect(api.send).toHaveBeenCalledTimes(1));
  expect(beforeSend).toHaveBeenCalledTimes(1);
  await waitFor(() =>
    expect(
      (screen.getByRole("textbox", { name: "Research follow-up" }) as HTMLTextAreaElement).value
    ).toBe("Compare accuracy too")
  );
  expect(screen.getByText("Request could not be saved")).toBeTruthy();
  fireEvent.click(screen.getByRole("button", { name: "Stop" }));
  await waitFor(() =>
    expect(api.stop).toHaveBeenCalledWith({
      experimentStopInputRequest: { run: "run" },
      id: "experiment",
    })
  );
  fireEvent.click(screen.getByRole("button", { name: "Minimize chat" }));
  expect(screen.queryByText("Compare models")).toBeNull();
  fireEvent.click(screen.getByRole("button", { name: "Open chat" }));
  expect(screen.getByText("Compare models")).toBeTruthy();
  client.clear();
});

it("folds one integration's consecutive calls into a row that opens onto each call", async () => {
  const call = (id: string, tool: string, text: string, detail: string): WorkshopMessage => ({
    detail,
    id,
    role: "activity",
    status: "completed",
    text,
    tool,
  });
  const { client } = setup(record, [
    liveMessages[0],
    call("run:a", "huggingface__hub_repo_details", "huggingface · hub repo details", "repo a/b"),
    call("run:b", "huggingface__hf_fs", "huggingface · hf fs", "cat hf://datasets/a/b/README.md"),
    call("run:c", "huggingface__hf_fs", "huggingface · hf fs", "cat hf://datasets/a/b/LICENSE"),
    call("run:d", "artifact", "retain artifact", "kind report"),
  ]);
  const activity = await screen.findByRole("button", { name: /^Ran 4 tools/ });
  expect(activity.getAttribute("aria-expanded")).toBe("false");
  fireEvent.click(activity);
  const row = (await screen.findByText("huggingface · 3 calls")).closest("li")!;
  expect(screen.getByText("retain artifact")).toBeTruthy();
  expect(screen.queryByText(/README\.md/)).toBeNull();
  fireEvent.click(row.querySelector("button")!);
  await waitFor(() => expect(row.textContent).toContain("cat hf://datasets/a/b/README.md"));
  expect(row.textContent).toContain("hub repo details");
  client.clear();
});

it("shows thinking as soon as a sent message has no reply yet", async () => {
  const { client } = setup(record, [liveMessages[0]]);
  expect(await screen.findByRole("region", { name: "Assistant activity" })).toBeTruthy();
  expect(screen.getByLabelText("Overmind response").textContent).toContain("Thinking");
  client.clear();
});

it("keeps output links in the regular chat without a follow-up action on interruption", () => {
  const { client } = setup({ ...record, runs: [{ ...record.runs[0], state: "cancelled" }] }, [
    liveMessages[0],
    { id: "run:progress", role: "assistant", status: "completed", text: "Preparing the data." },
    {
      id: "run:answer",
      role: "assistant",
      status: "completed",
      text: "Prepared 40 rows.\n\n**Outputs**\n\n- [Training data](/datasets/training?cell=prepared)",
    },
    { id: "run:stopped", role: "assistant", status: "cancelled", text: "Stopped." },
  ]);
  expect(screen.getByText("Prepared 40 rows.")).toBeTruthy();
  expect(screen.queryByRole("heading", { name: "Final answer" })).toBeNull();
  expect(screen.queryByRole("button", { name: "Draft follow-up" })).toBeNull();
  expect(screen.getByRole("link", { name: "Training data" }).getAttribute("href")).toBe(
    "/datasets/training?cell=prepared"
  );
  client.clear();
});

it("keeps the controller chat and stop action when its newer child flow is executing", async () => {
  api.stop.mockResolvedValue({ id: "experiment" });
  const { client } = setup({
    ...record,
    runs: [
      { ...record.runs[0], controller: "run", execution: "flow", id: "child", phase: "executing" },
      { ...record.runs[0], flow_run: "child", phase: "executing" },
    ],
  });
  expect(screen.getByText("Also compare latency")).toBeTruthy();
  fireEvent.click(screen.getByRole("button", { name: "Stop" }));
  await waitFor(() =>
    expect(api.stop).toHaveBeenCalledWith({
      experimentStopInputRequest: { run: "run" },
      id: "experiment",
    })
  );
  client.clear();
});
it("edits a queued message using its persisted revision", async () => {
  api.change.mockResolvedValue({ id: "experiment" });
  const { client } = setup();
  fireEvent.click(screen.getByRole("button", { name: "Edit queued message 1" }));
  fireEvent.change(screen.getByRole("textbox", { name: "Edit queued message" }), {
    target: { value: "Compare p95 latency" },
  });
  fireEvent.click(screen.getByRole("button", { name: "Save" }));
  await waitFor(() =>
    expect(api.change).toHaveBeenCalledWith({
      id: "experiment",
      workshopMessageControlRequest: {
        command: "edit",
        message: "queued",
        requestKey: expect.any(String),
        revision: 2,
        text: "Compare p95 latency",
      },
    })
  );
  client.clear();
});
it("keeps request metrics out of the conversation footer", () => {
  setup({
    ...record,
    runs: [
      {
        ...record.runs[0],
        metrics: {
          cached_tokens: null,
          completion_tokens: 300,
          estimated_model_cost_usd: null,
          model_calls: 1,
          model_calls_before_run: 1,
          model_seconds: 2.3,
          prompt_tokens: 25875,
          seconds_to_first_model_call: 0.4,
          seconds_to_run: 7.5,
        },
      },
    ],
  });
  expect(screen.queryByLabelText("Request figures")).toBeNull();
});

it("requires review before an experiment can send an uploaded file", async () => {
  setup();
  api.inspectUpload.mockResolvedValue({
    columns: ["name"],
    preview: [{ name: "Example" }],
    rows: 1,
  });
  api.create.mockRejectedValue(new Error("Retained test stop"));
  const input = screen.getByRole("textbox", { name: "Research follow-up" });
  fireEvent.change(input, { target: { value: "Use the attached data" } });
  fireEvent.change(screen.getByLabelText("Attach files to experiment"), {
    target: { files: [new File(["name\nExample"], "data.csv")] },
  });
  await screen.findByRole("cell", { name: "Example" });
  fireEvent.click(screen.getByRole("button", { name: "Close" }));
  await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
  expect((screen.getByRole("button", { name: "Queue" }) as HTMLButtonElement).disabled).toBe(true);
  expect(api.create).not.toHaveBeenCalled();
  expect(screen.queryByRole("button", { name: "Review files" })).toBeNull();
  fireEvent.click(screen.getByRole("button", { name: "View data.csv" }));
  fireEvent.click(await screen.findByRole("button", { name: "Continue" }));
  await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
  fireEvent.click(screen.getByRole("button", { name: "View data.csv" }));
  await screen.findByRole("cell", { name: "Example" });
  expect(api.inspectUpload).toHaveBeenCalledTimes(1);
  fireEvent.click(screen.getByRole("button", { name: "Close" }));
  await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
  fireEvent.click(screen.getByRole("button", { name: "Queue" }));
  await waitFor(() => expect(api.create).toHaveBeenCalledTimes(1));
});