Skip to content

The open-source app everyone uses to manage agents at work

35.0 KB
Raw Blame
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
  defaultGitHubReviewPolicy,
  buildSkillMentionHref,
  type GitHubChatConfiguration,
  type GitHubTaskReview,
  type ChatExecutionDefaults,
} from "@paperclipai/shared";
import { ChatEndpointDetail } from "./ChatEndpointDetail";
import { GitHubReviewList, orderedGitHubReviews } from "./GitHubBotManagement";
import { GitHubPolicyEditor } from "./GitHubBotConfiguration";
import { conversationDestination } from "./ChatConversationList";
import { queryKeys } from "@/lib/queryKeys";
import { TooltipProvider } from "@/components/ui/tooltip";
import { gitHubAppSettingsUrl, gitHubBotMention } from "./GitHubAppIdentity";
import type { ChatEndpoint } from "@/api/chatEndpoints";

const mocks = vi.hoisted(() => ({
  tab: "settings",
  reviewId: undefined as string | undefined,
  get: vi.fn(),
  config: vi.fn(),
  save: vi.fn(),
  resources: vi.fn(),
  repositoryPage: vi.fn(),
  toggleAll: vi.fn(),
  updateResources: vi.fn(),
  projects: vi.fn(),
  workspaces: vi.fn(),
  reviews: vi.fn(),
  review: vi.fn(),
  members: vi.fn(),
  links: vi.fn(),
  setBreadcrumbs: vi.fn(),
}));
vi.mock("@/api/githubChat", () => ({
  githubChatApi: {
    configuration: mocks.config,
    save: mocks.save,
    reviews: mocks.reviews,
    review: mocks.review,
    repositories: mocks.repositoryPage,
    toggleAllRepositories: mocks.toggleAll,
  },
}));
vi.mock("@/api/chatEndpoints", () => ({
  chatEndpointsApi: {
    get: mocks.get,
    listResources: mocks.resources,
    updateResources: mocks.updateResources,
    listPrincipals: mocks.links,
  },
}));
vi.mock("@/api/projects", () => ({ projectsApi: { list: mocks.projects } }));
vi.mock("@/api/execution-workspaces", () => ({ executionWorkspacesApi: { listSummaries: mocks.workspaces } }));
vi.mock("@/api/access", () => ({ accessApi: { listMembers: mocks.members } }));
vi.mock("@/api/agents", () => ({ agentsApi: { get: vi.fn() } }));
vi.mock("@/context/BreadcrumbContext", () => ({
  useBreadcrumbs: () => ({ setBreadcrumbs: mocks.setBreadcrumbs }),
}));
vi.mock("@/context/CompanyContext", () => ({
  useOptionalCompany: () => ({ companies: [{ id: "company", name: "Acme Research" }], selectedCompany: { id: "other", name: "Wrong company" } }),
}));
vi.mock("@/context/ToastContext", () => ({
  useToast: () => ({ pushToast: vi.fn() }),
}));
vi.mock("@/components/MarkdownBody", () => ({
  MarkdownBody: ({ children }: { children: React.ReactNode }) => (
    <div>{children}</div>
  ),
}));
// Exercise settings persistence through the shared editor contract. The editor's
// rich rendering and slash picker have their own tests and a live walkthrough.
vi.mock("@/components/MarkdownEditor", () => ({
  MarkdownEditor: ({ value, onChange, ariaLabel, placeholder, readOnly }: {
    value: string; onChange: (value: string) => void; ariaLabel: string; placeholder?: string; readOnly?: boolean;
  }) => <textarea aria-label={ariaLabel} placeholder={placeholder} value={value} readOnly={readOnly}
    onChange={(event) => onChange(event.target.value)} />,
}));
vi.mock("@/lib/router", () => ({
  useParams: () => ({
    endpointId: "bot",
    tab: mocks.tab,
    reviewId: mocks.reviewId,
  }),
  useNavigate: () => vi.fn(),
  useLocation: () => ({ state: null }),
  Link: ({
    children,
    to,
    ...props
  }: React.ComponentProps<"a"> & { to: string }) => (
    <a href={to} {...props}>
      {children}
    </a>
  ),
  Navigate: () => null,
}));
const endpoint = {
  id: "bot",
  companyId: "company",
  provider: "github",
  assignedAgentId: "agent",
  assignedAgentName: "Maya",
  status: "active",
  allowUnlinkedPeople: false,
  setup: { step: "complete" },
};
const base: GitHubChatConfiguration = {
  version: 1,
  toolsEnabled: true,
  responsibleUserId: "member",
  memberAccess: "selected",
  people: [
    {
      kind: "member",
      userId: "member",
      githubUserId: "42",
      login: "maya",
      automaticReviews: true,
    },
  ],
  defaults: {
    ...defaultGitHubReviewPolicy(),
    instructions: "Keep existing instructions",
    issueOpened: true,
  },
  repositories: {},
};

describe("GitHub bot management", () => {
  let root: Root;
  let container: HTMLDivElement;
  let client: QueryClient;
  beforeEach(() => {
    vi.clearAllMocks();
    mocks.tab = "settings";
    mocks.reviewId = undefined;
    mocks.get.mockResolvedValue(endpoint);
    mocks.projects.mockResolvedValue([]);
    mocks.workspaces.mockResolvedValue([]);
    mocks.config.mockResolvedValue({
      revision: 4,
      configuration: structuredClone(base),
    });
    mocks.resources.mockResolvedValue([
      {
        id: "repo",
        type: "repository",
        label: "acme/web",
        enabled: true,
        availability: "available",
        metadata: { providerRepositoryId: "100" },
      },
    ]);
    mocks.repositoryPage.mockImplementation(async () => ({
      items: await mocks.resources(), nextOffset: null, totalCount: 1, enabledCount: 1, availableCount: 1,
    }));
    mocks.toggleAll.mockResolvedValue({ success: true });
    mocks.links.mockResolvedValue([
      {
        id: "link",
        principalId: "identity",
        status: "linked",
        githubUserId: "42",
        githubLogin: "maya",
        paperclipUserId: "member",
        paperclipUserLabel: "Maya",
      },
    ]);
    mocks.members.mockResolvedValue({
      members: [
        {
          principalId: "member",
          status: "active",
          membershipRole: "owner",
          user: { name: "Maya" },
        },
      ],
    });
    mocks.reviews.mockResolvedValue([]);
    mocks.save.mockImplementation(async (_id, revision, configuration) => ({
      revision: revision + 1,
      configuration,
    }));
    mocks.updateResources.mockResolvedValue([]);
    client = new QueryClient({
      defaultOptions: { queries: { retry: false, staleTime: Infinity } },
    });
    client.setQueryData(queryKeys.agents.detail("agent"), {
      id: "agent",
      name: "Maya",
    });
    container = document.createElement("div");
    document.body.append(container);
    root = createRoot(container);
  });
  afterEach(async () => {
    await act(async () => root.unmount());
    client.clear();
    container.remove();
    vi.unstubAllGlobals();
  });
  async function render(tab = mocks.tab) {
    mocks.tab = tab;
    await act(async () =>
      root.render(
        <QueryClientProvider client={client}>
          <TooltipProvider>
            <ChatEndpointDetail />
          </TooltipProvider>
        </QueryClientProvider>,
      ),
    );
    await vi.waitFor(() =>
      expect(
        container.querySelector(
          'textarea[placeholder="What should this agent do on GitHub?"]',
        ) || container.querySelector('[aria-label="Allow mentions from all linked members"]'),
      ).not.toBeNull(),
    );
  }
  async function click(name: string) {
    const target = [...container.querySelectorAll("button")].find(
      (b) =>
        b.getAttribute("aria-label") === name || b.textContent?.trim() === name,
    );
    expect(target).toBeDefined();
    await act(async () => target!.click());
  }
  async function input(
    element: HTMLTextAreaElement | HTMLSelectElement | HTMLInputElement,
    value: string,
  ) {
    await act(async () => {
      Object.getOwnPropertyDescriptor(
        element instanceof HTMLTextAreaElement
          ? HTMLTextAreaElement.prototype
          : element instanceof HTMLSelectElement ? HTMLSelectElement.prototype : HTMLInputElement.prototype,
        "value",
      )!.set!.call(element, value);
      element.dispatchEvent(
        new Event(element instanceof HTMLSelectElement ? "change" : "input", {
          bubbles: true,
        }),
      );
    });
  }
  it("loads repositories 20 at a time, searches all pages, and toggles the full connection", async () => {
    let enabled = true;
    const all = Array.from({ length: 1000 }, (_, index) => ({
      id: `repo-${index}`, type: "repository", providerResourceId: `acme/repo-${index}`,
      label: `acme/repo-${String(index).padStart(4, "0")}`, availability: "available", enabled: true,
    }));
    mocks.repositoryPage.mockImplementation(async (_id, { offset, search, limit }) => {
      const filtered = all.filter((row) => row.label.includes(search));
      return { items: filtered.slice(offset, offset + limit).map((row) => ({ ...row, enabled })),
        nextOffset: offset + limit < filtered.length ? offset + limit : null,
        totalCount: 1000, enabledCount: enabled ? 1000 : 0, availableCount: 1000 };
    });
    mocks.toggleAll.mockImplementation(async (_id, value) => { enabled = value; return { success: true }; });
    await render("access");
    await vi.waitFor(() => expect(container.querySelectorAll('[role="region"] [role="switch"]')).toHaveLength(20));
    expect(mocks.repositoryPage).toHaveBeenCalledWith("bot", { offset: 0, limit: 20, search: "" });
    await click("Load more repositories");
    await vi.waitFor(() => expect(container.querySelectorAll('[role="region"] [role="switch"]')).toHaveLength(40));
    const search = container.querySelector('input[aria-label="Search repositories"]') as HTMLInputElement;
    await input(search, "0999");
    await vi.waitFor(() => expect(container.querySelectorAll('[role="region"] [role="switch"]')).toHaveLength(1));
    expect(container.textContent).toContain("acme/repo-0999");
    expect(container.textContent).toContain("1000 of 1000 repositories enabled");
    await click("Disable all repositories");
    await vi.waitFor(() => expect(container.textContent).toContain("0 of 1000 repositories enabled"));
    expect(mocks.toggleAll).toHaveBeenCalledWith("bot", false);
    expect(mocks.updateResources).not.toHaveBeenCalled();
    await click("Enable all repositories");
    await vi.waitFor(() => expect(container.textContent).toContain("1000 of 1000 repositories enabled"));
    expect(mocks.toggleAll).toHaveBeenLastCalledWith("bot", true);
    await input(search, "does-not-exist");
    await vi.waitFor(() => expect(container.textContent).toContain("No repositories match your search"));
    expect(container.querySelector('button[aria-label="Disable all repositories"]')?.hasAttribute("disabled")).toBe(false);
  });
  it("keeps repository failures visible and allows a retry", async () => {
    mocks.repositoryPage.mockRejectedValueOnce(new Error("Unavailable"));
    await render("access");
    await vi.waitFor(() => expect(container.textContent).toContain("Could not load repositories"));
    await click("Try again");
    await vi.waitFor(() => expect(container.querySelectorAll('[role="region"] [role="switch"]')).toHaveLength(1));
    expect(container.textContent).not.toContain("Could not load repositories");
  });
  it("saves repository task defaults with explicit, cleared, and inherited values without changing access", async () => {
    let executionDefaults: ChatExecutionDefaults | null = null;
    mocks.projects.mockResolvedValue([{ id: "project", name: "Website", workspaces: [] }]);
    mocks.workspaces.mockResolvedValue([{ id: "workspace", name: "Shared website" }]);
    mocks.resources.mockImplementation(async () => [{
      id: "repo", label: "acme/web", type: "repository", enabled: false,
      availability: "available", executionDefaults,
    }]);
    mocks.updateResources.mockImplementation(async (_id, [update]) => {
      executionDefaults = update.executionDefaults;
      return mocks.resources();
    });
    await render("access");
    await vi.waitFor(() => expect(container.querySelector('[role="region"] summary')).not.toBeNull());
    await act(async () => (container.querySelector('[role="region"] summary') as HTMLElement).click());
    const editor = container.querySelector('[role="region"] form')!;
    const [project, workspace] = [...editor.querySelectorAll("select")];
    await vi.waitFor(() => expect(workspace.disabled).toBe(false));
    expect(mocks.projects).toHaveBeenCalledWith("company");
    expect(mocks.workspaces).toHaveBeenCalledWith("company", { selectableForTask: true });
    expect(project.value).toBe("inherit");
    expect(workspace.value).toBe("inherit");
    expect(editor.textContent).toContain("Use connection defaults");

    const save = async (expected: ChatExecutionDefaults | null) => {
      const calls = mocks.updateResources.mock.calls.length;
      await click("Save defaults");
      await vi.waitFor(() => {
        expect(mocks.updateResources).toHaveBeenCalledTimes(calls + 1);
        expect(editor.textContent).toContain("Saved for new tasks.");
      });
      expect(mocks.updateResources).toHaveBeenLastCalledWith("bot", [{ id: "repo", executionDefaults: expected }]);
      expect(container.querySelector('[role="region"] [role="switch"]')?.getAttribute("aria-checked")).toBe("false");
    };
    await input(project, "project");
    await input(workspace, "existing:workspace");
    await save({ projectId: "project", workspace: { kind: "existing", workspaceId: "workspace" } });
    expect(project.value).toBe("project");
    expect(workspace.value).toBe("existing:workspace");
    await input(project, "none");
    await input(workspace, "clear");
    await save({ projectId: null, workspace: null });
    await input(project, "inherit");
    await save({ workspace: null });
    await input(workspace, "inherit");
    await save(null);
    await vi.waitFor(() => {
      expect(project.value).toBe("inherit");
      expect(workspace.value).toBe("inherit");
    });
    expect(mocks.save).not.toHaveBeenCalled();
    expect(mocks.toggleAll).not.toHaveBeenCalled();
  });
  it("keeps a rejected repository task-defaults draft visible for retry", async () => {
    mocks.updateResources.mockRejectedValueOnce(new Error("Workspace access denied"));
    await render("access");
    await vi.waitFor(() => expect(container.querySelector('[role="region"] summary')).not.toBeNull());
    await act(async () => (container.querySelector('[role="region"] summary') as HTMLElement).click());
    const editor = container.querySelector('[role="region"] form')!;
    const workspace = editor.querySelectorAll("select")[1];
    await vi.waitFor(() => expect(workspace.disabled).toBe(false));
    await input(workspace, "task");
    await click("Save defaults");
    await vi.waitFor(() => expect(editor.querySelector('[role="alert"]')?.textContent).toBe("Workspace access denied"));
    expect(workspace.value).toBe("task");
    expect(container.querySelector('[role="region"] [role="switch"]')?.getAttribute("aria-checked")).toBe("true");
    await click("Cancel");
    expect(workspace.value).toBe("inherit");
    expect(editor.querySelector('[role="alert"]')).toBeNull();
  });
  it("automatically loads the next 20 repositories when the scroll sentinel becomes visible", async () => {
    let intersect!: IntersectionObserverCallback;
    vi.stubGlobal("IntersectionObserver", class {
      constructor(callback: IntersectionObserverCallback) { intersect = callback; }
      observe() {}
      disconnect() {}
    });
    mocks.repositoryPage.mockImplementation(async (_id, { offset }) => ({
      items: Array.from({ length: 20 }, (_, index) => ({
        id: `repo-${offset + index}`, label: `acme/repo-${offset + index}`,
        enabled: true, availability: "available", type: "repository",
      })),
      nextOffset: offset === 0 ? 20 : null, totalCount: 40, enabledCount: 40, availableCount: 40,
    }));
    await render("access");
    await vi.waitFor(() => expect(intersect).toBeDefined());
    await act(async () => intersect([{ isIntersecting: true } as IntersectionObserverEntry], {} as IntersectionObserver));
    await vi.waitFor(() => expect(container.querySelectorAll('[role="region"] [role="switch"]')).toHaveLength(40));
    expect(mocks.repositoryPage).toHaveBeenLastCalledWith("bot", { offset: 20, limit: 20, search: "" });
  });
  it("shows the verified custom App mention and its own organization branding settings", async () => {
    const branded: ChatEndpoint = {
      ...endpoint,
      provider: "github",
      status: "active",
      botLabel: "Maya Reviews",
      botUsername: "maya-reviews[bot]",
      providerAccountLabel: "acme",
      setup: {
        step: "complete",
        github: {
          stage: "verify",
          appOwnerType: "organization",
          appOwnerLogin: "acme",
          appSlug: "old-draft-name",
        },
      },
    };
    mocks.get.mockResolvedValue(branded);
    await render();
    expect(
      container.querySelector('button[aria-label="Copy GitHub mention"]')
        ?.textContent,
    ).toBe("@maya-reviews");
    expect(container.textContent).toContain("Maya Reviews");
    const branding = [...container.querySelectorAll("a")].find((a) =>
      a.getAttribute("aria-label") === "Edit App name and logo on GitHub",
    );
    expect(branding?.href).toBe(
      "https://github.com/organizations/acme/settings/apps/maya-reviews",
    );
    expect(
      container.querySelector("a[download]")?.getAttribute("download"),
    ).toBe("Maya-Reviews-avatar.png");
    expect(mocks.save).not.toHaveBeenCalled();
    expect(
      gitHubAppSettingsUrl({
        ...branded,
        setup: {
          step: "complete",
          github: { stage: "verify", appOwnerType: "personal" },
        },
      }),
    ).toBe("https://github.com/settings/apps/maya-reviews");
    expect(
      gitHubAppSettingsUrl({ ...branded, setup: { step: "complete" } }),
    ).toBe("https://github.com/settings/apps");
    expect(gitHubBotMention({ botUsername: null })).toBeNull();
  });
  it("keeps one draft across Settings, Access, and read-only tabs, then saves with the original revision", async () => {
    await render();
    await input(container.querySelector("textarea")!, "Edited instructions");
    await render("access");
    await click("Allow mentions from all linked members");
    await render("reviews");
    await render("settings");
    expect(container.querySelector("textarea")?.value).toBe(
      "Edited instructions",
    );
    expect(mocks.save).not.toHaveBeenCalled();
    await click("Save changes");
    await vi.waitFor(() => expect(mocks.save).toHaveBeenCalledTimes(1));
    const [id, revision, saved] = mocks.save.mock.calls[0];
    expect(id).toBe("bot");
    expect(revision).toBe(4);
    expect(saved).toEqual({
      ...base,
      defaults: { ...base.defaults, instructions: "Edited instructions" },
      memberAccess: "all_linked",
    });
    await vi.waitFor(() =>
      expect(container.textContent).toContain("Changes saved."),
    );
    expect(
      [...container.querySelectorAll("button")].some(
        (b) => b.textContent === "Save changes",
      ),
    ).toBe(false);
  });
  it("retains a rejected draft and lets the user discard it", async () => {
    mocks.save.mockRejectedValue(
      new Error("Configuration changed. Reload before saving."),
    );
    await render();
    await input(container.querySelector("textarea")!, "Unsaved");
    await click("Save changes");
    await vi.waitFor(() =>
      expect(container.querySelector('[role="alert"]')?.textContent).toContain(
        "Configuration changed",
      ),
    );
    expect(container.querySelector("textarea")?.value).toBe("Unsaved");
    await click("Discard changes");
    expect(container.querySelector("textarea")?.value).toBe(
      base.defaults.instructions,
    );
    expect(container.querySelector('[role="alert"]')).toBeNull();
  });
  it("saves repository restrictions separately without touching the behavior draft", async () => {
    await render();
    await input(container.querySelector("textarea")!, "Unsaved behavior");
    await render("access");
    await vi.waitFor(() => expect(container.querySelector('button[aria-label="acme/web"]')).not.toBeNull());
    await click("acme/web");
    await vi.waitFor(() =>
      expect(mocks.updateResources).toHaveBeenCalledWith("bot", [
        { id: "repo", enabled: false },
      ]),
    );
    expect(mocks.save).not.toHaveBeenCalled();
    await render("settings");
    expect(container.querySelector("textarea")?.value).toBe("Unsaved behavior");
  });
  it("hides repository overrides while preserving saved overrides when other settings change", async () => {
    const overrides = { "100": { instructions: "Retain repository guidance", events: ["opened"] } };
    mocks.config.mockResolvedValue({
      revision: 4,
      configuration: { ...base, repositories: overrides },
    });
    await render();
    expect(container.textContent).not.toContain("Repository overrides");
    expect(container.querySelector("#github-policy-repository")).toBeNull();
    expect(mocks.resources).not.toHaveBeenCalled();
    await input(container.querySelector("textarea")!, "Updated default instructions");
    await click("Save changes");
    await vi.waitFor(() => expect(mocks.save).toHaveBeenCalled());
    const saved = mocks.save.mock.calls[0][2];
    expect(saved.defaults.instructions).toBe("Updated default instructions");
    expect(saved.repositories).toEqual(overrides);
  });
  it("names the endpoint company and omits per-person automatic switches", async () => {
    mocks.config.mockResolvedValue({ revision: 4, configuration: { ...base, memberAccess: "all_linked", people: [] } });
    await render("access");
    await vi.waitFor(() => expect(container.textContent).toContain("@maya"));
    expect(container.textContent).toContain("Includes members from Acme Research who link their GitHub account later.");
    expect(container.textContent).not.toContain("Wrong company");
    expect(container.querySelector('[aria-label="Run automatically for @maya"]')).toBeNull();
    await click("Allow mentions from all linked members");
    await click("Allow mentions from @maya");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].people).toEqual([{ kind: "member", userId: "member", githubUserId: "42", login: "maya" }]);
  });
  it("does not show an off switch or silently enable a retained disabled bot", async () => {
    mocks.config.mockResolvedValue({
      revision: 4,
      configuration: { ...base, toolsEnabled: false },
    });
    await render("access");
    expect(
      container.querySelector('[aria-label="Use this bot’s GitHub tools"]'),
    ).toBeNull();
    expect(container.textContent).toContain("cannot start work or respond");
    await render("settings");
    await input(container.querySelector("textarea")!, "Edited instructions");
    await click("Save changes");
    await vi.waitFor(() => expect(mocks.save).toHaveBeenCalled());
    expect(mocks.save.mock.calls[0][2].toolsEnabled).toBe(false);
  });
  it("loads a direct review URL and keeps unknown reviews within the current connection", async () => {
    mocks.reviewId = "review-1";
    mocks.reviews.mockResolvedValue([]);
    mocks.review.mockImplementation(async (_endpoint, id) => {
      if (id !== "review-1") throw new Error("not found");
      return review("review-1", "repo", 1, "2026-10-07T10:00:00Z");
    });
    await render("reviews");
    await vi.waitFor(() =>
      expect(container.textContent).toContain(
        "No assessment has been submitted yet.",
      ),
    );
    expect(
      container.querySelector('a[href="/apps/chat/bot/reviews"]')?.textContent,
    ).toContain("All reviews");
    mocks.reviewId = "foreign";
    await render("reviews");
    await vi.waitFor(() =>
      expect(container.textContent).toContain("not found in this connection"),
    );
    expect(container.textContent).not.toContain(
      "No assessment has been submitted yet.",
    );
  });
  it("keeps saved automatic triggers when changing to mentions-only", async () => {
    const change = vi.fn();
    await act(async () =>
      root.render(
        <TooltipProvider>
          <GitHubPolicyEditor policy={base.defaults} onChange={change} />
        </TooltipProvider>,
      ),
    );
    await click("Run automatically");
    expect(change.mock.calls[0][0]).toEqual({
      ...base.defaults,
      invocation: "mentions_only",
    });
  });
  it("keeps external-author mode and event choices when automatic runs are switched off and back on", async () => {
    mocks.config.mockResolvedValue({ revision: 4, configuration: { ...base, defaults: { ...base.defaults, invocation: "allowed_authors" } } });
    await render();
    await click("Run automatically");
    await click("Run automatically");
    expect(container.querySelector('[aria-label="Save changes"]')).toBeNull();
    await input(container.querySelector("textarea")!, "Still keep the same audience");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults).toEqual({ ...base.defaults, invocation: "allowed_authors", instructions: "Still keep the same audience" });
  });
  it("preserves an invalid score across Access and Settings without saving a stale value", async () => {
    await render();
    await input(container.querySelector('input[type="number"]')!, "6");
    await render("access");
    expect([...container.querySelectorAll("button")].find(b => b.textContent === "Save changes")?.disabled).toBe(true);
    await render("settings");
    expect(container.querySelector<HTMLInputElement>('input[type="number"]')!.value).toBe("6");
    await click("Discard changes");
    expect(container.querySelector<HTMLInputElement>('input[type="number"]')!.value).toBe("5");
    expect(mocks.save).not.toHaveBeenCalled();
  });
  it("remembers external-author automation across tab changes", async () => {
    mocks.config.mockResolvedValue({ revision: 4, configuration: { ...base, defaults: { ...base.defaults, invocation: "allowed_authors" } } });
    await render(); await click("Run automatically");
    await render("access"); await render("settings"); await click("Run automatically");
    await input(container.querySelector("textarea")!, "Updated");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults.invocation).toBe("allowed_authors");
  });
  it("makes common and event instruction editors read-only throughout a pending save", async () => {
    let finish!: (value: unknown) => void;
    mocks.save.mockImplementation(() => new Promise(resolve => { finish = resolve; }));
    await render();
    await input(container.querySelector("textarea")!, "Saved instructions");
    await act(async () => [...container.querySelectorAll("summary")].find(s => s.textContent?.includes("Event-specific instructions"))!.click());
    await click("Save changes");
    expect([...container.querySelectorAll<HTMLTextAreaElement>("textarea[aria-label]")].every(editor => editor.readOnly)).toBe(true);
    await act(async () => { finish({ revision: 5, configuration: { ...base, defaults: { ...base.defaults, instructions: "Saved instructions" } } }); });
    expect(container.querySelector("textarea")!.readOnly).toBe(false);
  });
  it("defaults to a typed score of 5 and preserves report-only and other review decisions", async () => {
    await render();
    const score = container.querySelector<HTMLInputElement>('input[type="number"]')!;
    expect(score.value).toBe("5");
    expect(container.querySelector('input[type="range"]')).toBeNull();
    await input(score, "3");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults).toEqual({ ...base.defaults, ratingThreshold: 3 });
    await click("Report only");
    await click("Save changes");
    expect(mocks.save.mock.calls[1][2].defaults.ratingThreshold).toBeNull();
    expect(score.disabled).toBe(true);
    await click("Report only");
    expect(score.value).toBe("5");
  });
  it.each(["", "0", "6", "2.5"])("does not save an invalid score %s and allows correction or discard", async (value) => {
    await render();
    const score = container.querySelector<HTMLInputElement>('input[type="number"]')!;
    await input(score, value);
    expect(container.textContent).toContain("Enter a whole number from 1 to 5.");
    await click("Save changes");
    expect(mocks.save).not.toHaveBeenCalled();
    await input(score, "4");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults.ratingThreshold).toBe(4);
    await input(score, value);
    await click("Discard changes");
    expect(container.querySelector<HTMLInputElement>('input[type="number"]')?.value).toBe("4");
    expect(container.querySelector('[role="alert"]')).toBeNull();
  });
  it("retains a saved report-only policy until the user changes it", async () => {
    mocks.config.mockResolvedValue({ revision: 4, configuration: { ...base, defaults: { ...base.defaults, ratingThreshold: null } } });
    await render();
    expect(container.querySelector<HTMLInputElement>('input[type="number"]')?.disabled).toBe(true);
    await input(container.querySelector("textarea")!, "Updated guidance");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults.ratingThreshold).toBeNull();
  });
  it("turns off selected member access without retaining an authorization entry", async () => {
    await render("access");
    await vi.waitFor(() => expect(container.querySelector('[aria-label="Allow mentions from @maya"]')?.hasAttribute("disabled")).toBe(false));
    await click("Allow mentions from @maya");
    expect(container.querySelector('[aria-label="Run automatically for @maya"]')).toBeNull();
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].people).toEqual([]);
    expect(mocks.save.mock.calls[0][2].memberAccess).toBe("selected");
  });
  it("keeps automatic runs off when editing member access", async () => {
    mocks.config.mockResolvedValue({ revision: 4, configuration: { ...base, defaults: { ...base.defaults, invocation: "mentions_only" } } });
    await render("access");
    await click("Allow mentions from all linked members");
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults.invocation).toBe("mentions_only");
  });
  it("keeps newlines and commas while editing filters, saves separate entries, and restores discarded values", async () => {
    await render();
    const paths = container.querySelector<HTMLTextAreaElement>('textarea[id$="github-ignoredPaths"]')!;
    await input(paths, "dist/**\n");
    expect(paths.value).toBe("dist/**\n");
    await input(paths, `${paths.value}vendor/**`);
    const categories = container.querySelector<HTMLInputElement>('input[id$="github-categories"]')!;
    await input(categories, "security, ");
    expect(categories.value).toBe("security, ");
    await input(categories, `${categories.value}correctness`);
    await click("Save changes");
    expect(mocks.save.mock.calls[0][2].defaults.ignoredPaths).toEqual(["dist/**", "vendor/**"]);
    expect(mocks.save.mock.calls[0][2].defaults.findingCategories).toEqual(["security", "correctness"]);
    await input(paths, "tmp/**");
    await click("Discard changes");
    expect(container.querySelector<HTMLTextAreaElement>('textarea[id$="github-ignoredPaths"]')?.value).toBe("dist/**\nvendor/**");
  });
  it("saves skill links in general and event instructions without resetting other guidance", async () => {
    await render();
    const skill = `[/review](${buildSkillMentionHref("11111111-1111-4111-8111-111111111111", "review")})`;
    await input(container.querySelector('textarea[aria-label="Agent instructions"]')!, `Use ${skill}.`);
    await input(container.querySelector('select[id$="github-prompt-event"]')!, "mention");
    await input(container.querySelector('textarea[aria-label="Mention instructions"]')!, `For mentions, use ${skill}.`);
    await input(container.querySelector('select[id$="github-prompt-event"]')!, "issue_opened");
    await input(container.querySelector('textarea[aria-label="New issue instructions"]')!, `For issues, use ${skill}.`);
    await click("Save changes");
    const saved = mocks.save.mock.calls[0][2];
    expect(saved.defaults.instructions).toBe(`Use ${skill}.`);
    expect(saved.defaults.prompts.mention).toBe(`For mentions, use ${skill}.`);
    expect(saved.defaults.issueOpenedInstructions).toBe(`For issues, use ${skill}.`);
    expect(saved.defaults.prompts.opened).toBe(base.defaults.prompts.opened);
    expect(saved.people).toEqual(base.people);
  });
  it.each(["mentions_only", "linked_authors", "allowed_authors"] as const)(
    "makes mentions explicit in the selected %s mode", async (invocation) => {
      await act(async () => root.render(<TooltipProvider>
        <GitHubPolicyEditor policy={{ ...base.defaults, invocation }} onChange={() => {}} />
      </TooltipProvider>));
      expect(container.querySelector('[aria-label="Run automatically"]')?.getAttribute("aria-checked")).toBe(String(invocation !== "mentions_only"));
      expect(container.textContent).toContain("Authorized people can always @mention this bot.");
    },
  );
});

function review(
  id: string,
  repositoryId: string,
  pullNumber: number,
  createdAt: string,
  updatedAt = createdAt,
) {
  return {
    id,
    repositoryId,
    pullNumber,
    createdAt,
    updatedAt,
    repository: "acme/web",
    headSha: id,
    issueId: "task",
    event: { title: "Review focus handling" },
    state: "queued",
    assessment: null,
    conclusion: null,
  } as GitHubTaskReview;
}
describe("review history and thread labels", () => {
  it("keeps every review in creation order, independent of late updates to an older head", () => {
    const old = review(
      "old",
      "repo",
      1,
      "2026-10-07T10:00:00Z",
      "2026-10-07T14:00:00Z",
    );
    const current = review("current", "repo", 1, "2026-10-07T11:00:00Z");
    const other = review("other", "another-repo", 1, "2026-10-07T12:00:00Z");
    expect(orderedGitHubReviews([old, current, other])).toEqual([
      other,
      current,
      old,
    ]);
  });
  it("does not present a previous passing score as the pending current commit’s result", async () => {
    const old = review("old", "repo", 1, "2026-10-07T10:00:00Z");
    old.state = "completed";
    old.conclusion = "success";
    old.assessment = {
      reviewedCommit: "old",
      score: 5,
      complete: true,
      summary: "Previous result",
      rationale: "Complete",
      findings: [],
      coverage: { reviewedPaths: [], omittedPaths: [], limitations: [] },
    };
    const current = review("current", "repo", 1, "2026-10-07T11:00:00Z");
    const container = document.createElement("div");
    const root = createRoot(container);
    try {
      await act(async () =>
        root.render(
          <GitHubReviewList endpointId="bot" reviews={[old, current]} />,
        ),
      );
      const rows = [...container.querySelectorAll("li")];
      expect(rows).toHaveLength(2);
      expect(rows[0].textContent).toContain("Queued");
      expect(rows[0].textContent).not.toContain("5/5");
      expect(rows[0].querySelector("a")?.getAttribute("href")).toBe(
        "/apps/chat/bot/reviews/current",
      );
      expect(rows[1].textContent).toContain("5/5 · Passed");
      expect(rows[1].querySelector("a")?.getAttribute("href")).toBe(
        "/apps/chat/bot/reviews/old",
      );
      expect(container.querySelector("details")).toBeNull();
    } finally {
      await act(async () => root.unmount());
    }
  });
  it("identifies GitHub thread numbers while preserving labels for other providers and invalid URLs", () => {
    const row = {
      externalLabel: "acme/web",
      externalUrl: "https://github.com/acme/web/issues/42#issuecomment-1",
    } as any;
    expect(conversationDestination(row, "github")).toBe("acme/web #42");
    expect(conversationDestination(row, "slack")).toBe("acme/web");
    expect(
      conversationDestination({ ...row, externalUrl: "invalid" }, "github"),
    ).toBe("acme/web");
  });
});