Skip to content

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

Go
32.9 KB
Raw Blame
import { act, cleanup, fireEvent, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { ReactNode } from "react";
import { api } from "@multica/core/api";
import { chatKeys } from "@multica/core/chat/queries";
import { issueKeys } from "@multica/core/issues/queries";
import { TooltipProvider } from "@multica/ui/components/ui/tooltip";
import type { AgentTask, TimelineEntry } from "@multica/core/types";
import type { TaskMessagePayload } from "@multica/core/types/events";
import { renderWithI18n } from "../../test/i18n";
import { InlineCommentRun, PlacedInlineCommentRun, REPLY_PENDING_CALL_NOTICE_MS } from "./inline-comment-run";

const dispatchReasonCodeMock = vi.hoisted(() => vi.fn());

vi.mock("@multica/core/api", () => ({ api: {
  getIssue: vi.fn(), listTaskMessages: vi.fn(), cancelTask: vi.fn(), rerunIssue: vi.fn(),
  listTasksByIssue: vi.fn(),
}, dispatchReasonCode: dispatchReasonCodeMock }));
vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace" }));
vi.mock("@multica/core/workspace/hooks", () => ({ useActorName: () => ({ getActorName: () => "Reviewer" }) }));
vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span /> }));
vi.mock("../../editor", () => ({ ReadonlyContent: ({ content }: { content: string }) => <div>{content}</div> }));
vi.mock("../../common/task-transcript/agent-transcript-dialog", () => ({
  AgentTranscriptDialog: ({ contentState, isLive }: { contentState?: ReactNode; isLive?: boolean }) => <div role="dialog" data-live={isLive}>{contentState ?? "Full transcript"}</div>,
  StepBody: ({ item }: { item: { content?: string; output?: string } }) => <div data-testid="step-body">{item.content ?? item.output}</div>,
}));

const id = "4a2e8d1c-7f9b-4e2a-9c1d-123456789abc";
function task(overrides: Partial<AgentTask> = {}): AgentTask {
  return { id, agent_id: "agent", runtime_id: "runtime", issue_id: "issue", status: "running", priority: 0,
    created_at: "2026-09-07T00:00:00Z", started_at: "2026-09-07T00:00:00Z", dispatched_at: null,
    completed_at: null, result: null, error: null, ...overrides };
}
const messages: TaskMessagePayload[] = [
  { task_id: id, issue_id: "issue", seq: 1, type: "text", content: "Checking navigation." },
  { task_id: id, issue_id: "issue", seq: 2, type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },
];
afterEach(() => {
  cleanup();
  vi.clearAllMocks();
});

function setup(initialTask: AgentTask, hasReply = false, presentation: "inline" | "header" = "inline") {
  const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
  const view = (current: AgentTask, reply = hasReply) => <TooltipProvider>
    <QueryClientProvider client={client}>
      <InlineCommentRun run={{ task: current, commentId: "comment", hasReply: reply }} presentation={presentation} />
    </QueryClientProvider>
  </TooltipProvider>;
  const rendered = renderWithI18n(view(initialTask));
  return { client, rerender: (current: AgentTask, reply = hasReply) => rendered.rerender(view(current, reply)) };
}

describe("InlineCommentRun", () => {
  it("shows a clipped tool name and its summary when the activity step is focused", async () => {
    const tool = "mcp__company-knowledge-base__search_documents_with_filters";
    vi.mocked(api.listTaskMessages).mockResolvedValue([
      { task_id: id, issue_id: "issue", seq: 1, type: "tool_use", tool, input: { query: "release checklist" } },
    ]);
    setup(task());
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    const label = await screen.findByText(tool);
    label.style.overflowX = "hidden";
    Object.defineProperties(label, {
      scrollWidth: { value: 360 },
      clientWidth: { value: 120 },
    });

    const step = label.closest("summary");
    expect(step).not.toBeNull();
    await act(async () => { step?.focus(); });
    expect(step).toHaveFocus();

    expect(document.querySelector("[data-slot='tooltip-content']")).toHaveTextContent(`${tool} · release checklist`);
  });

  it("places a delivered steer between the steps it arrived between", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue([
      { task_id: id, issue_id: "issue", seq: 1, type: "tool_use", tool: "exec_command", input: { command: "cat login.tsx" }, created_at: "2026-09-07T00:00:05Z" },
      { task_id: id, issue_id: "issue", seq: 2, type: "tool_result", tool: "exec_command", output: "ok", created_at: "2026-09-07T00:00:06Z" },
      { task_id: id, issue_id: "issue", seq: 3, type: "text", content: "Only touching web now.", created_at: "2026-09-07T00:00:20Z" },
    ]);
    const { client } = setup(task());
    client.setQueryData<TimelineEntry[]>(issueKeys.timeline("issue"), [{
      id: "steer", type: "comment", actor_type: "member", actor_id: "user",
      content: "Leave desktop alone.", created_at: "2026-09-07T00:00:08Z",
      supplements: [{ task_id: id, agent_id: "agent", status: "delivered", delivered_at: "2026-09-07T00:00:10Z" }],
    }]);
    await screen.findByText("Only touching web now.");
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    const steer = await screen.findByText("Message added by Reviewer");
    const row = steer.closest("[data-steer-comment]")!;
    expect(row).toHaveTextContent("Leave desktop alone.");
    const before = screen.getAllByText("cat login.tsx").find((node) => node.closest("summary"))!;
    const after = screen.getAllByText("Only touching web now.").find((node) => node.closest("summary"))!;
    expect(before.compareDocumentPosition(row) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
    expect(row.compareDocumentPosition(after) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
  });

  it("offers no run-level message box: messages go through the thread composer", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    setup(task({ supplement_capability: "task-supplement-v1", can_supplement: true }));
    await screen.findByText("pnpm test");
    expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /message/i })).not.toBeInTheDocument();
  });

  it("previews streamed agent messages in collapsed steps and expands the full body", async () => {
    const message: TaskMessagePayload = {
      task_id: id, issue_id: "issue", seq: 1, type: "text", content: "Checking the PR",
    };
    vi.mocked(api.listTaskMessages).mockResolvedValue([message]);
    const { client } = setup(task());
    await screen.findByText("Checking the PR");
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    const preview = screen.getAllByText("Checking the PR").find((node) => node.closest("summary"))!;
    expect(screen.queryByTestId("step-body")).not.toBeInTheDocument();
    act(() => client.setQueryData(chatKeys.taskMessages(id), [
      message,
      { ...message, seq: 2, content: " changes.\nReviewing migration safety." },
    ]));
    await waitFor(() => expect(preview).toHaveTextContent("Checking the PR changes."));
    fireEvent.click(preview.closest("summary")!, { detail: 0 });
    expect(await screen.findByTestId("step-body")).toHaveTextContent("Checking the PR changes. Reviewing migration safety.");
  });

  it("shows the first file in a collapsed Grok read_file group and retains its step count", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(
      ["queries.sql", "models.go", "schema.sql", "migrations.go"].flatMap((file, index) => [
        { task_id: id, issue_id: "issue", seq: index * 2 + 1, type: "tool_use" as const,
          tool: "read_file", input: { path: `/workdir/multica/server/db/${file}` } },
        { task_id: id, issue_id: "issue", seq: index * 2 + 2, type: "tool_result" as const,
          tool: "read_file", output: `Contents of ${file}` },
      ]),
    );
    setup(task());
    await screen.findByText(".../db/migrations.go");
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    const preview = screen.getByText("read_file · .../db/queries.sql");
    const summary = preview.closest("summary")!;
    expect(summary).toHaveTextContent("4 steps");
    fireEvent.click(summary, { detail: 0 });
    expect(await screen.findByText(".../db/queries.sql")).toBeInTheDocument();
    expect(screen.getByText(".../db/models.go")).toBeInTheDocument();
    expect(screen.getByText(".../db/schema.sql")).toBeInTheDocument();
  });

  it("redacts message previews and keeps a label for empty messages", async () => {
    const secret = `ghp_${"x".repeat(36)}`;
    vi.mocked(api.listTaskMessages).mockResolvedValue([
      { task_id: id, issue_id: "issue", seq: 1, type: "text", content: `Checking ${secret}` },
      { task_id: id, issue_id: "issue", seq: 2, type: "thinking", content: "Checking logs" },
      { task_id: id, issue_id: "issue", seq: 3, type: "text", content: " \n " },
    ]);
    setup(task());
    await screen.findByText("Checking logs");
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    expect(screen.getByText("Checking [REDACTED GITHUB TOKEN]").closest("summary")).not.toBeNull();
    expect(screen.getByText("Agent message").closest("summary")).not.toBeNull();
    expect(document.body.innerHTML).not.toContain(secret);
  });

  it("previews streamed thinking in the header and collapsed steps, and expands its body", async () => {
    const thought: TaskMessagePayload = {
      task_id: id, issue_id: "issue", seq: 1, type: "thinking", content: "Checking the runtime",
    };
    vi.mocked(api.listTaskMessages).mockResolvedValue([thought]);
    const { client } = setup(task());
    const header = await screen.findByText("Checking the runtime");
    const textNode = header.firstChild;
    act(() => client.setQueryData(chatKeys.taskMessages(id), [
      thought,
      { ...thought, seq: 2, content: " logs.\nThe reasoning is present." },
    ]));
    await waitFor(() => expect(header).toHaveTextContent("Checking the runtime logs."));
    expect(header.firstChild).toBe(textNode);
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    const preview = screen.getAllByText("Checking the runtime logs.").find((node) => node.closest("summary"))!;
    const details = preview.closest("details")!;
    expect(details).not.toHaveAttribute("open");
    expect(screen.queryByTestId("step-body")).not.toBeInTheDocument();
    fireEvent.click(preview.closest("summary")!, { detail: 0 });
    expect(await screen.findByTestId("step-body")).toHaveTextContent("Checking the runtime logs. The reasoning is present.");
  });

  it("redacts thinking before clipping its preview and tooltip", async () => {
    const prefix = "Reviewing ".repeat(18);
    const secret = `ghp_${"x".repeat(36)}`;
    vi.mocked(api.listTaskMessages).mockResolvedValue([
      { task_id: id, issue_id: "issue", seq: 1, type: "thinking", content: `${prefix}${secret}` },
    ]);
    setup(task());
    await screen.findByText(/REDACTED/);
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    const preview = screen.getAllByText(/REDACTED/).find((node) => node.closest("summary"))!;
    expect(preview.textContent).toContain("REDACTED");
    expect(document.body.innerHTML).not.toContain("ghp_");
    expect(preview.textContent!.length).toBeLessThanOrEqual(201);
  });

  it("keeps a Thinking label when the runtime supplies no preview text", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue([
      { task_id: id, issue_id: "issue", seq: 1, type: "thinking", content: " \n " },
    ]);
    setup(task());
    await screen.findByText("Thinking");
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    expect(screen.getAllByText("Thinking").some((node) => node.closest("summary"))).toBe(true);
  });

  it("opens completed reply logs from a compact header button and loads only on demand", async () => {
    let resolve!: (value: TaskMessagePayload[]) => void;
    vi.mocked(api.listTaskMessages).mockImplementation(() => new Promise((done) => { resolve = done; }));
    setup(task({ status: "completed", completed_at: "2026-09-07T00:01:23Z" }), true, "header");
    expect(screen.queryByText("Completed")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
    expect(api.listTaskMessages).not.toHaveBeenCalled();
    const trigger = screen.getByRole("button", { name: "Open full log" });
    expect(trigger).toHaveAttribute("aria-haspopup", "dialog");
    fireEvent.click(trigger);
    expect(screen.getByRole("dialog")).toHaveTextContent("Loading activity");
    await act(async () => resolve(messages));
    await screen.findByText("Full transcript");
    expect(api.listTaskMessages).toHaveBeenCalledTimes(1);
  });

  it("keeps published replies visually settled while their full log remains live", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    const current = task();
    const { rerender } = setup(current, true, "header");
    expect(screen.queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
    expect(screen.queryByRole("status")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
    const trigger = screen.getByRole("button", { name: "Open full log" });
    const icon = trigger.querySelector("svg");
    expect(icon).not.toHaveClass("animate-spin");
    fireEvent.click(trigger);
    await screen.findByText("Full transcript");
    expect(screen.getByRole("dialog")).toHaveAttribute("data-live", "true");
    rerender({ ...current, status: "completed", completed_at: "2026-09-07T00:01:23Z" });
    expect(screen.getByRole("button", { name: "Open full log" })).toBe(trigger);
    expect(screen.getByRole("dialog")).toHaveTextContent("Full transcript");
    expect(screen.getByRole("dialog")).toHaveAttribute("data-live", "false");
    expect(trigger.querySelector("svg")).toBe(icon);
    expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
  });

  it("lets a completed header log recover when its initial fetch fails", async () => {
    vi.mocked(api.listTaskMessages).mockRejectedValueOnce(new Error("offline"));
    setup(task({ status: "completed" }), true, "header");
    fireEvent.click(screen.getByRole("button", { name: "Open full log" }));
    await screen.findByRole("alert");
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    fireEvent.click(screen.getByRole("button", { name: "Try again" }));
    await screen.findByText("Full transcript");
    expect(screen.queryByRole("alert")).not.toBeInTheDocument();
  });

  it("uses a readable issue identifier in live progress and expanded activity", async () => {
    const issueId = "01a07eca-8e82-775e-be06-e4a97ccfa299";
    vi.mocked(api.getIssue).mockResolvedValue({ id: issueId, identifier: "DEV-17" } as Awaited<ReturnType<typeof api.getIssue>>);
    vi.mocked(api.listTaskMessages).mockResolvedValue([
      { task_id: id, issue_id: issueId, seq: 1, type: "tool_use", tool: "exec_command", input: { command: `multica issue get ${issueId} --output json` } },
    ]);
    setup(task({ issue_id: issueId }));
    await screen.findByText("multica issue get DEV-17 --output json");
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    expect(screen.getAllByText("multica issue get DEV-17 --output json")).toHaveLength(2);
    expect(api.getIssue).toHaveBeenCalledTimes(1);
  });

  it.each(["completed", "queued"] as const)("keeps the same focused disclosure button for a %s run", async (status) => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    setup(task({ status }));
    const before = screen.getByRole("button", { name: /View activity/ });
    before.focus();
    fireEvent.click(before, { detail: 0 });
    const expanded = screen.getByRole("button", { name: /View activity/ });
    expect(expanded).toBe(before);
    expect(expanded).toHaveFocus();
    expect(expanded).toHaveAttribute("aria-expanded", "true");
    await screen.findByText("pnpm test");
    fireEvent.click(expanded, { detail: 0 });
    expect(screen.getByRole("button", { name: /View activity/ })).toHaveFocus();
    expect(screen.getByRole("button", { name: /View activity/ })).toHaveAttribute("aria-expanded", "false");
  });
  it.each(["running", "completed", "failed"] as const)("opens the full log from the %s run row without expanding it", async (status) => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    setup(task({ status, completed_at: status === "running" ? null : "2026-09-07T00:01:23Z" }));
    const trigger = screen.getByRole("button", { name: "Open full log" });
    expect(trigger).toHaveAttribute("aria-haspopup", "dialog");
    fireEvent.click(trigger);
    await waitFor(() => expect(screen.getByRole("dialog")).toHaveTextContent("Full transcript"));
    expect(screen.getByRole("button", { name: /View activity/ })).toHaveAttribute("aria-expanded", "false");
  });

  it.each(["queued", "dispatched", "waiting_local_directory"] as const)("offers no full log before a %s run starts", (status) => {
    vi.mocked(api.listTaskMessages).mockResolvedValue([]);
    setup(task({ status }));
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    expect(screen.queryByRole("button", { name: "Open full log" })).not.toBeInTheDocument();
  });

  it("shows real activity, expands in place, follows WS data and retains the open transcript at completion", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    const current = task();
    const { client, rerender } = setup(current);
    await screen.findByText("pnpm test");
    const progress = screen.getByText("pnpm test");
    expect(progress).not.toHaveClass("shimmer-text");
    expect(progress.closest("[data-run-summary]")).toHaveClass("h-[1lh]", "overflow-hidden");
    expect(document.querySelector("[data-run-loading-indicator]")).toHaveClass(
      "motion-safe:animate-spin",
      "motion-safe:[animation-duration:900ms]",
    );
    expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
    const toggle = screen.getByRole("button", { name: /View activity/ });
    expect(toggle).toHaveAttribute("aria-expanded", "false");
    fireEvent.click(toggle);
    expect(toggle).toHaveAttribute("aria-expanded", "true");
    const tail: TaskMessagePayload = { task_id: id, issue_id: "issue", seq: 3, type: "tool_result", tool: "exec_command", output: "12 passed" };
    act(() => client.setQueryData(chatKeys.taskMessages(id), [...messages, tail]));
    await waitFor(() => expect(screen.queryByText("Waiting for the agent to respond.")).not.toBeInTheDocument());
    vi.mocked(api.listTaskMessages).mockResolvedValue([...messages, tail]);
    rerender({ ...current, status: "completed", completed_at: "2026-09-07T00:01:23Z" }, true);
    await screen.findByText("Completed");
    expect(screen.getByRole("button", { name: /View activity/ })).toHaveAttribute("aria-expanded", "true");
    expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
    fireEvent.click(screen.getByRole("button", { name: "Open full log" }));
    expect(screen.getByRole("dialog")).toHaveTextContent("Full transcript");
  });

  it("updates streamed summaries without replacing their DOM nodes", async () => {
    const events: TaskMessagePayload[] = [...messages,
      { task_id: id, issue_id: "issue", seq: 3, type: "tool_result", tool: "exec_command", output: "Passed" },
    ];
    vi.mocked(api.listTaskMessages).mockResolvedValue([...events]);
    const { client } = setup(task());
    const summary = await screen.findByText("pnpm test");
    const text = summary.firstChild;
    const container = summary.closest("[data-run-summary]")!;
    const mutations: MutationRecord[] = [];
    const observer = new MutationObserver((records) => mutations.push(...records));
    observer.observe(container, { childList: true, subtree: true });
    try {
      // Cover a new seq with the same label, a changed tool argument, and prose.
      for (const next of [
        { type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } },
        { type: "tool_use", tool: "exec_command", input: { command: "pnpm lint" } },
        { type: "text", content: "Reviewing the results." },
      ] as const) {
        events.push({ task_id: id, issue_id: "issue", seq: events.length + 1, ...next });
        if (next.type === "tool_use") events.push({
          task_id: id, issue_id: "issue", seq: events.length + 1,
          type: "tool_result", tool: next.tool, output: "Passed",
        });
        await act(async () => {
          client.setQueryData(chatKeys.taskMessages(id), [...events]);
          await new Promise((resolve) => setTimeout(resolve, 0));
        });
        const label = next.type === "text" ? next.content : next.input.command;
        await waitFor(() => expect(summary).toHaveTextContent(label));
        expect(summary.isConnected).toBe(true);
        expect(summary.firstChild).toBe(text);
        expect(container).toHaveAttribute("title", label);
      }
      expect([...mutations, ...observer.takeRecords()]).toHaveLength(0);
    } finally {
      observer.disconnect();
    }
  });

  it("retains the last meaningful activity between tool results and the next agent message", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue([]);
    const { client } = setup(task());
    await screen.findByText("Waiting for the agent to respond.");
    await waitFor(() => expect(client.isFetching()).toBe(0));
    const events: TaskMessagePayload[] = [];
    async function receive(event: Omit<TaskMessagePayload, "task_id" | "issue_id" | "seq">) {
      events.push({ task_id: id, issue_id: "issue", seq: events.length + 1, ...event });
      await act(async () => {
        client.setQueryData(chatKeys.taskMessages(id), [...events]);
        await new Promise((resolve) => setTimeout(resolve, 0));
      });
    }
    await receive({ type: "text", content: "Checking navigation." });
    await screen.findByText("Checking navigation.");
    await receive({ type: "tool_use", tool: "exec_command", input: { command: "pnpm test" } });
    await screen.findByText("pnpm test");
    await receive({ type: "tool_result", tool: "exec_command", output: "12 passed" });
    expect(screen.getByText("pnpm test")).toBeInTheDocument();
    await waitFor(() => expect(screen.queryByText("Waiting for the agent to respond.")).not.toBeInTheDocument());
    await receive({ type: "text", content: "  " });
    expect(screen.getByText("pnpm test")).toBeInTheDocument();
    await receive({ type: "text", content: "Tests passed. Reviewing the changes." });
    await screen.findByText("Tests passed. Reviewing the changes.");
    await waitFor(() =>
      expect(screen.queryByText("pnpm test")).not.toBeInTheDocument(),
    );
  });

  it("keeps completed replies readable without fetching or duplicating their deliverable", () => {
    setup(task({ status: "completed", result: { comment: "Already posted" } }), true);
    expect(api.listTaskMessages).not.toHaveBeenCalled();
    expect(screen.queryByText("Already posted")).not.toBeInTheDocument();
    expect(screen.getByText("Completed")).toBeInTheDocument();
  });

  it("shows a completed deliverable if the corresponding comment is missing", () => {
    setup(task({ status: "completed", result: { comment: "Review complete." } }));
    expect(screen.getByText("Review complete.")).toBeInTheDocument();
    expect(screen.getByText("Review complete.").closest('[data-slot="card"]')).toBeNull();
    expect(screen.getByText("Completed").closest('[data-slot="card"]')).toBeNull();
    expect(api.listTaskMessages).not.toHaveBeenCalled();
  });

  it.each(["queued", "running"] as const)("confirms stopping the specific %s run before its reply", async (state) => {
    vi.mocked(api.cancelTask).mockResolvedValue(task({ status: "cancelled" }));
    setup(task({ status: state }));
    if (state === "queued") {
      expect(screen.getByText("Waiting for an available agent.")).toBeInTheDocument();
      expect(api.listTaskMessages).not.toHaveBeenCalled();
      vi.mocked(api.listTaskMessages).mockResolvedValue([]);
      fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
      await screen.findByText("No activity recorded yet.");
      expect(screen.queryByText("Waiting for the agent to respond.")).not.toBeInTheDocument();
    }
    fireEvent.click(screen.getByRole("button", { name: "Stop" }));
    expect(api.cancelTask).not.toHaveBeenCalled();
    fireEvent.click(screen.getByRole("button", { name: "Stop run" }));
    await waitFor(() => expect(api.cancelTask).toHaveBeenCalledWith("issue", id));
  });

  it("keeps a failed transcript fetch recoverable inside the comment", async () => {
    vi.mocked(api.listTaskMessages).mockRejectedValueOnce(new Error("offline"));
    setup(task({ status: "failed" }));
    fireEvent.click(screen.getByRole("button", { name: /View activity/ }));
    await screen.findByRole("alert");
    vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
    fireEvent.click(screen.getByRole("button", { name: "Try again" }));
    await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
  });

  it("states how a failed run ended once and keeps the raw error on hover", async () => {
    setup(task({ status: "failed", failure_reason: "cancelled", error: "task cancelled by server",
      completed_at: "2026-09-07T00:12:56Z" }));
    const label = screen.getByText("Cancelled by the system");
    expect(screen.queryByText("Failed")).not.toBeInTheDocument();
    expect(screen.queryByText("task cancelled by server")).not.toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Retry run" })).toBeInTheDocument();
    await userEvent.hover(label);
    expect(await screen.findByText("task cancelled by server")).toBeInTheDocument();
  });

  it("keeps the raw error in view when recovery needs a configuration change", () => {
    setup(task({ status: "failed", failure_reason: "agent_error.provider_auth_or_access",
      error: "Invalid API key · Please run /login", completed_at: "2026-09-07T00:00:06Z" }));
    expect(screen.getByText("Provider auth failed")).toBeInTheDocument();
    expect(screen.getByText("Invalid API key · Please run /login")).toBeInTheDocument();
  });

  it("offers retry beside a reply only when that reply is the run's failure notice", () => {
    const client = new QueryClient();
    const failed = task({ status: "failed", failure_reason: "timeout", error: "run timed out" });
    const view = (replacesFailureNotice: boolean) => <QueryClientProvider client={client}>
      <InlineCommentRun run={{ task: failed, commentId: "comment", hasReply: true }} replacesFailureNotice={replacesFailureNotice} />
    </QueryClientProvider>;
    const { rerender } = renderWithI18n(view(false));
    expect(screen.queryByRole("button", { name: "Retry run" })).not.toBeInTheDocument();
    rerender(view(true));
    expect(screen.getByRole("button", { name: "Retry run" })).toBeInTheDocument();
  });

  it("shows who cancelled the run and keeps legacy rows readable", () => {
    const { rerender } = setup(task({
      status: "cancelled",
      completed_at: "2026-09-07T00:01:23Z",
      cancelled_by: { type: "member", id: "user-1", name: "Jiayuan" },
    }));
    expect(screen.getByText("Cancelled by Jiayuan")).toBeInTheDocument();

    rerender(task({ status: "cancelled", completed_at: "2026-09-07T00:01:23Z" }));
    expect(screen.getByText("Cancelled")).toBeInTheDocument();
  });

  describe("cut-off status text", () => {
    // jsdom has no layout or Tailwind: make every `truncate` element report
    // clipped overflow, as the sr-only status line does while a run is live.
    const originalComputedStyle = window.getComputedStyle;
    const descriptors = {
      scrollWidth: Object.getOwnPropertyDescriptor(Element.prototype, "scrollWidth"),
      clientWidth: Object.getOwnPropertyDescriptor(Element.prototype, "clientWidth"),
    };
    const clipped = (el: Element) => el.classList.contains("truncate");
    beforeEach(() => {
      Object.defineProperty(Element.prototype, "scrollWidth", {
        configurable: true,
        get(this: Element) { return clipped(this) ? 200 : 0; },
      });
      Object.defineProperty(Element.prototype, "clientWidth", {
        configurable: true,
        get(this: Element) { return clipped(this) ? 1 : 0; },
      });
      vi.spyOn(window, "getComputedStyle").mockImplementation((el, pseudo) => {
        const style = originalComputedStyle(el, pseudo);
        if (!clipped(el)) return style;
        return { overflowX: "hidden", overflowY: "hidden" } as CSSStyleDeclaration;
      });
    });
    afterEach(() => {
      vi.mocked(window.getComputedStyle).mockRestore();
      for (const [key, descriptor] of Object.entries(descriptors)) {
        if (descriptor) Object.defineProperty(Element.prototype, key, descriptor);
      }
    });

    it("keeps a live run's hidden status out of the tab order and adds it once the run ends", async () => {
      vi.mocked(api.listTaskMessages).mockResolvedValue(messages);
      const user = userEvent.setup();
      const current = task();
      const { rerender } = setup(current);
      await screen.findByText("pnpm test");
      const status = () => document.querySelector("[data-run-status] .truncate")!;
      expect(status()).not.toHaveAttribute("tabindex");

      await user.tab();
      expect(screen.getByRole("button", { name: /View activity/ })).toHaveFocus();

      rerender({ ...current, status: "completed", completed_at: "2026-09-07T00:01:23Z" }, true);
      await screen.findByText("Completed");
      expect(status()).toHaveAttribute("tabindex", "0");

      (document.activeElement as HTMLElement).blur();
      await user.tab();
      expect(status()).toHaveFocus();
      await user.tab();
      expect(screen.getByRole("button", { name: /View activity/ })).toHaveFocus();
    });
  });
});

describe("PlacedInlineCommentRun below a published reply", () => {
  const startedAt = Date.parse("2026-09-07T00:10:00Z");
  const pendingCommand: TaskMessagePayload[] = [
    { task_id: id, issue_id: "issue", seq: 1, type: "tool_use", tool: "run_command", call_id: "a",
      input: { command: "./scripts/build.sh" }, created_at: "2026-09-07T00:10:00Z" },
    { task_id: id, issue_id: "issue", seq: 2, type: "tool_use", tool: "run_command", call_id: "b",
      input: { command: "multica issue comment add" }, created_at: "2026-09-07T00:10:01Z" },
    { task_id: id, issue_id: "issue", seq: 3, type: "tool_result", tool: "run_command", call_id: "b",
      output: "posted", created_at: "2026-09-07T00:10:02Z" },
  ];
  function placed(current: AgentTask) {
    const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } });
    return renderWithI18n(<QueryClientProvider client={client}>
      <PlacedInlineCommentRun run={{ task: current, commentId: "comment", hasReply: true }} />
    </QueryClientProvider>);
  }
  beforeEach(() => vi.useFakeTimers({ shouldAdvanceTime: true, now: startedAt + 5_000 }));
  afterEach(() => vi.useRealTimers());

  it("names the unfinished call once the reply has waited on it, and stops the run from there", async () => {
    vi.mocked(api.listTaskMessages).mockResolvedValue(pendingCommand);
    vi.mocked(api.cancelTask).mockResolvedValue(undefined as never);
    placed(task());
    await waitFor(() => expect(api.listTaskMessages).toHaveBeenCalled());
    expect(screen.queryByRole("status")).not.toBeInTheDocument();

    await act(async () => { vi.setSystemTime(startedAt + REPLY_PENDING_CALL_NOTICE_MS); await vi.advanceTimersByTimeAsync(1_000); });
    expect(await screen.findByRole("status")).toHaveTextContent("Still running: waiting for ./scripts/build.sh to finish");
    expect(screen.getByText("1m 01s")).toBeInTheDocument();

    fireEvent.click(screen.getByRole("button", { name: "Stop" }));
    fireEvent.click(await screen.findByRole("button", { name: "Stop run" }));
    await waitFor(() => expect(api.cancelTask).toHaveBeenCalledWith("issue", id));
  });

  it("stays settled when every call has returned or the run has ended", async () => {
    vi.setSystemTime(startedAt + 10 * REPLY_PENDING_CALL_NOTICE_MS);
    vi.mocked(api.listTaskMessages).mockResolvedValue([...pendingCommand,
      { task_id: id, issue_id: "issue", seq: 4, type: "tool_result", tool: "run_command", call_id: "a", output: "ok", created_at: "2026-09-07T00:11:00Z" }]);
    placed(task());
    await waitFor(() => expect(api.listTaskMessages).toHaveBeenCalled());
    await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });
    expect(screen.queryByRole("status")).not.toBeInTheDocument();
    cleanup();

    vi.mocked(api.listTaskMessages).mockResolvedValue(pendingCommand);
    placed(task({ status: "completed", completed_at: "2026-09-07T00:20:00Z" }));
    await act(async () => { await vi.advanceTimersByTimeAsync(1_000); });
    expect(screen.queryByRole("status")).not.toBeInTheDocument();
    expect(screen.queryByRole("button", { name: "Stop" })).not.toBeInTheDocument();
  });
});