import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import * as actions from "@/platform/actions"; import { useProject } from "@/platform/project"; import { useContextMenuStore, type MenuItem } from "@/ui"; import { maybeEditorService, provideEditorService, type EditorService } from "@/workbench/contributions"; import * as client from "../api/client"; import type { GHRepository, GHUser } from "../api/types"; import { useGhProjectAccount } from "../data/account"; import { resetConnection, useGhRepository } from "../data/repository"; import * as api from "./api"; import { IssueEditor } from "./IssueEditor"; import { IssuesHeaderActions, IssuesHeaderTabs, IssuesToolWindow } from "./IssuesToolWindow"; import { hasClosingReference, issueBranchName, issueForBranch, issueInput, rememberIssueBranch } from "./input"; import { clearIssues, loadMoreIssues, useGhIssueList } from "./list"; import { isIssueQuickFilterSelected, issueCommentsTooltip, issueQuickFilters, issueSearchHistoryText, issueSearchQuery, } from "./model"; import { loadIssueSearchHistory, loadLastIssueSearch } from "./searchHistory"; const repo = { owner: "acme", name: "app", host: "code.example" }; const user = (login: string, name: string | null = null): GHUser => ({ __typename: "User", id: `id-${login}`, login, url: `https://code.example/${login}`, avatarUrl: "", name, }); const row: api.IssueRow = { id: "I7", url: "https://code.example/acme/app/issues/7", title: "Fix editor focus", number: 7, state: "OPEN", createdAt: "2026-08-01T00:00:00Z", updatedAt: "2026-08-01T00:00:00Z", author: user("ann"), labels: { nodes: [] }, assignees: { nodes: [] }, comments: { totalCount: 0 }, }; const input = issueInput("code.example/acme/app", row); function connectRepo() { useProject.setState({ project: { root: "/one", name: "app" } as never }); useGhRepository.setState({ availability: { kind: "ready", login: "me", repo: { nameWithOwner: "acme/app", url: "https://code.example/acme/app", defaultBranch: "main", mergeCommitAllowed: true, squashMergeAllowed: true, rebaseMergeAllowed: true, viewerPermission: "READ", }, }, remotes: [{ owner: "acme", name: "app", host: "code.example", remote: "origin", url: "" }], connection: { coordinates: repo, root: "/one", repository: { viewerPermission: "READ", url: "https://code.example/acme/app" } as GHRepository, currentUser: user("me"), remotes: [], }, }); } beforeEach(() => { localStorage.clear(); }); afterEach(() => { vi.restoreAllMocks(); clearIssues(); useGhIssueList.setState({ search: {} }); useGhProjectAccount.setState({ status: null, loading: false, saving: false, revision: 0 }); useContextMenuStore.setState({ menu: null }); resetConnection(); localStorage.clear(); }); it("keeps issue editors and branch associations scoped to the repository and checkout", () => { const checkout = { ...repo, root: "/one" }; rememberIssueBranch(checkout, "custom-name", 7); expect(issueForBranch(checkout, "custom-name")).toBe(7); expect(issueForBranch({ owner: "ACME", name: "App", host: "CODE.EXAMPLE", root: "/one" }, "custom-name")).toBe(7); expect(issueForBranch({ ...checkout, root: "/two" }, "custom-name")).toBeNull(); expect(issueForBranch({ ...checkout, host: "github.com" }, "custom-name")).toBeNull(); expect(input.key).not.toBe(issueInput("github.com/acme/app", row).key); expect(input.key).toBe(issueInput("code.example/acme/app", { ...row, title: "Renamed" }).key); }); it("sanitizes issue titles into valid git branch names", () => { expect(issueBranchName({ number: 7, title: "Fix .. @{ ~ ^ : ? * [ \\ / foo.lock", state: "OPEN" })).toBe( "issue-7-fix-foo-lock", ); expect(issueBranchName({ number: 8, title: " !!! 🚀🔥 ", state: "OPEN" })).toBe("issue-8"); expect(issueBranchName({ number: 9, title: "Re\u0301sume\u0301 cafe\u0301", state: "OPEN" })).toBe( "issue-9-résumé-café", ); const astral = "\u{1D400}".repeat(60); const name = issueBranchName({ number: 10, title: astral, state: "OPEN" }); expect(name).toBe(`issue-10-${"\u{1D400}".repeat(48)}`); }); it("detects closing references regardless of line endings, casing, or keyword", () => { expect(hasClosingReference("Closes #7", 7)).toBe(true); expect(hasClosingReference("Summary\r\nCloses #7\r\nMore", 7)).toBe(true); expect(hasClosingReference("fixes #7.", 7)).toBe(true); expect(hasClosingReference("(Resolves: #7)", 7)).toBe(true); expect(hasClosingReference("Closes #70", 7)).toBe(false); expect(hasClosingReference("See #7", 7)).toBe(false); expect(hasClosingReference("Encloses #7", 7)).toBe(false); }); it("builds issue quick filters, search queries, history text, and comment tooltips", () => { const q = issueQuickFilters("me"); expect(q.map((f) => f.title)).toEqual(["Open", "Your issues", "Assigned to you"]); expect(isIssueQuickFilterSelected({ state: "OPEN", author: "me" }, q[1]!)).toBe(true); expect(isIssueQuickFilterSelected({ state: "OPEN", author: "me", sort: "NEWEST" }, q[1]!)).toBe(false); expect( issueSearchQuery(repo, { searchQuery: "crash", state: "CLOSED", author: "ann", label: "good first issue", assignee: "me", sort: "RECENTLY_UPDATED", }), ).toBe( 'type:issue repo:acme/app (crash) is:closed assignee:me author:ann label:"good first issue" sort:updated-desc', ); expect( issueSearchHistoryText({ searchQuery: "crash", state: "OPEN", label: "bug", assignee: "me", author: "ann", sort: "NEWEST", }), ).toBe('"crash" state:"Open" label:bug assignee:me author:ann sort:"Newest"'); expect(issueCommentsTooltip(0)).toBe("No comments"); expect(issueCommentsTooltip(1)).toBe("1 comment"); expect(issueCommentsTooltip(4)).toBe("4 comments"); }); it("filters out pull requests on exact #number lookup and searches issues via GitHub search", async () => { const gql = vi .spyOn(client, "graphql") .mockResolvedValueOnce({ repository: { issueOrPullRequest: { __typename: "PullRequest" } } }) .mockResolvedValueOnce({ search: { nodes: [null, {}, row], pageInfo: { hasNextPage: true, endCursor: "c1" }, }, }); expect(await api.issueList(repo, { searchQuery: "#0", state: "OPEN" }, null)).toEqual({ items: [], next: null }); expect(await api.issueList(repo, { searchQuery: "#9999999999", state: "OPEN" }, null)).toEqual({ items: [], next: null, }); expect(gql).not.toHaveBeenCalled(); expect(await api.issueList(repo, { searchQuery: "#12", state: "OPEN" }, null)).toEqual({ items: [], next: null }); expect( await api.issueList(repo, { searchQuery: "focus", state: "CLOSED", assignee: "me", label: "bug" }, "c0"), ).toEqual({ items: [row], next: "c1" }); expect(gql).toHaveBeenLastCalledWith(expect.any(String), { query: 'type:issue repo:acme/app (focus) is:closed assignee:me label:"bug"', cursor: "c0", }); }); it("keeps a failed comment draft and shows the confirmed comment after retry", async () => { connectRepo(); const issue = { ...row, id: "issue-id", body: "Reproduction steps", locked: false, createdAt: "2026-08-01T00:00:00Z", author: null, url: "https://code.example/acme/app/issues/7", labels: { nodes: [] }, assignees: { nodes: [] }, comments: { nodes: [], pageInfo: { hasNextPage: false, hasPreviousPage: false, startCursor: null, endCursor: null }, }, }; vi.spyOn(api, "issueDetails").mockResolvedValue({ items: [issue], next: null }); const post = vi .spyOn(api, "postIssueComment") .mockRejectedValueOnce(new Error("Network unavailable")) .mockResolvedValueOnce({ id: "comment", body: "Confirmed locally", author: null, createdAt: issue.createdAt }); const { container } = render(); const submit = await screen.findByRole("button", { name: "Comment" }); const field = container.querySelector("textarea")!; fireEvent.change(field, { target: { value: "Confirmed locally" } }); fireEvent.click(submit); await screen.findByText("Network unavailable"); expect(field.value).toBe("Confirmed locally"); fireEvent.click(submit); await waitFor(() => expect(field.value).toBe("")); expect(await screen.findByText("Confirmed locally")).toBeTruthy(); expect(post.mock.calls).toEqual([ ["issue-id", "Confirmed locally"], ["issue-id", "Confirmed locally"], ]); }); it("passes issue metadata when clicking Create Branch in an IssueEditor", async () => { connectRepo(); const issue = { ...row, title: "Updated issue title", id: "issue-id", body: "", locked: false, createdAt: "2026-08-01T00:00:00Z", author: null, url: "https://code.example/acme/app/issues/7", labels: { nodes: [] }, assignees: { nodes: [] }, comments: { nodes: [], pageInfo: { hasNextPage: false, hasPreviousPage: false, startCursor: null, endCursor: null }, }, }; vi.spyOn(api, "issueDetails").mockResolvedValue({ items: [issue], next: null }); const exec = vi.spyOn(actions, "executeAction").mockResolvedValue(true); render(); const button = await screen.findByRole("button", { name: "Create Branch…" }); fireEvent.click(button); expect(exec).toHaveBeenCalledWith("github.issue.createBranch", { repository: "code.example/acme/app", number: 7, title: "Updated issue title", state: "OPEN", }); }); it("renders repository header tab, account badge, two-line issue rows, and context menu matching Pull Requests", async () => { connectRepo(); useGhProjectAccount.setState({ status: { ghInstalled: true, accounts: [ { login: "me", active: true }, { login: "me-work", active: false }, ], configuredAccount: "", effectiveAccount: "me", suggestedAccount: null, }, }); const items: api.IssueRow[] = [ { ...row, number: 7, title: "Fix editor focus", state: "OPEN", labels: { nodes: [{ id: "L1", url: "", name: "bug", color: "ff0000" }] }, assignees: { nodes: [user("a"), user("b"), user("c")] }, comments: { totalCount: 3 }, }, { ...row, id: "I8", number: 8, title: "Already fixed", state: "CLOSED", author: null, comments: { totalCount: 0 }, }, ]; vi.spyOn(api, "issueList").mockResolvedValue({ items, next: null }); await act(async () => { render( <> , ); }); expect(screen.getByRole("tab", { name: "app" })).toBeTruthy(); expect(screen.getByRole("button", { name: "@me" })).toBeTruthy(); const rows = screen.getAllByRole("option"); expect(rows).toHaveLength(2); const first = within(rows[0]!); expect(first.getByText("Fix editor focus")).toBeTruthy(); expect(first.getByText(/^#7 · created .+, by ann$/)).toBeTruthy(); expect(rows[0]!.querySelector("[data-tooltip='3 comments']")?.textContent).toBe("3"); expect(rows[0]!.querySelectorAll("[data-avatar]")).toHaveLength(2); expect(within(rows[1]!).getByText("CLOSED")).toBeTruthy(); expect(within(rows[1]!).getByText(/^#8 · created /).textContent).not.toContain(", by"); expect(loadLastIssueSearch()).toEqual({ state: "OPEN" }); fireEvent.contextMenu(rows[1]!); expect(useGhIssueList.getState().selectedNumber).toBe(8); const menuItems = useContextMenuStore.getState().menu!.items; expect(menuItems.map((i: MenuItem) => ("action" in i ? i.action : i.kind))).toEqual([ "github.issue.show", "github.issue.createBranch", "github.issue.openInBrowser", "github.issue.copyUrl", "separator", "github.issue.refresh", ]); }); it("deduplicates paginated issues and keeps keyboard activation working after filtering", async () => { connectRepo(); const openInput = vi.fn().mockResolvedValue(undefined); const previousEditor = maybeEditorService(); provideEditorService({ openInput } as unknown as EditorService); try { const page1: api.IssueRow[] = [ { number: 10, title: "First issue", state: "OPEN" }, { number: 9, title: "Second issue", state: "OPEN" }, { number: 8, title: "Third issue", state: "OPEN" }, ]; const page2: api.IssueRow[] = [ { number: 8, title: "Third issue", state: "OPEN" }, { number: 7, title: "Fourth issue", state: "OPEN" }, ]; vi.spyOn(api, "issueList").mockImplementation(async (_r, filter, cursor) => { if (filter.searchQuery === "#7") return { items: [row], next: null }; if (cursor === "c1") return { items: page2, next: null }; return { items: page1, next: "c1" }; }); await act(async () => { render(); }); await act(async () => { await loadMoreIssues(); }); // Move selection down to the last item (index 3, #7) — requires 3 ArrowDowns if index 0 is active // and #8 was deduplicated rather than appended twice. const listbox = screen.getByRole("listbox", { name: "GitHub Issues" }); fireEvent.keyDown(listbox, { key: "ArrowDown" }); fireEvent.keyDown(listbox, { key: "ArrowDown" }); fireEvent.keyDown(listbox, { key: "ArrowDown" }); fireEvent.keyDown(listbox, { key: "Enter" }); expect(openInput).toHaveBeenLastCalledWith( issueInput("code.example/acme/app", { number: 7, title: "Fourth issue", state: "OPEN" }), { focus: true }, ); // Filter down to a single item (#7): active index must clamp back to 0 so Enter still works. const search = screen.getByRole("textbox", { name: "Search issues" }); fireEvent.change(search, { target: { value: "#7" } }); await act(async () => { fireEvent.keyDown(search, { key: "Enter" }); }); await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, { state: "OPEN", searchQuery: "#7" }, null)); expect(loadIssueSearchHistory()).toEqual([{ state: "OPEN", searchQuery: "#7" }]); fireEvent.keyDown(listbox, { key: "Enter" }); expect(openInput).toHaveBeenLastCalledWith(issueInput("code.example/acme/app", row), { focus: true }); } finally { provideEditorService(previousEditor); } }); it("ignores stale responses when changing filters mid-fetch and supports chip reset, empty states, and retry", async () => { connectRepo(); let resolveFirst!: (v: { items: api.IssueRow[]; next: string | null }) => void; const first = new Promise<{ items: api.IssueRow[]; next: string | null }>((r) => { resolveFirst = r; }); const spy = vi.spyOn(api, "issueList").mockImplementation((_r, filter) => { if (filter.state === undefined) return Promise.resolve({ items: [{ number: 42, title: "All states", state: "OPEN" }], next: null }); return first; }); render(); await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Reset State" })); }); await waitFor(() => expect(spy).toHaveBeenCalledWith(repo, {}, null)); // Resolve the stale filtered request after the unfiltered request already completed. await act(async () => { resolveFirst({ items: [{ number: 1, title: "Stale issue", state: "OPEN" }], next: null }); await Promise.resolve(); }); const openInput = vi.fn().mockResolvedValue(undefined); const previousEditor = maybeEditorService(); provideEditorService({ openInput } as unknown as EditorService); try { const listbox = screen.getByRole("listbox", { name: "GitHub Issues" }); fireEvent.keyDown(listbox, { key: "Enter" }); expect(openInput).toHaveBeenCalledWith( issueInput("code.example/acme/app", { number: 42, title: "All states", state: "OPEN" }), { focus: true }, ); } finally { provideEditorService(previousEditor); } // Empty state & retry on error. spy.mockResolvedValueOnce({ items: [], next: null }); await act(async () => { fireEvent.click(screen.getByText("Sort")); }); await act(async () => { fireEvent.click(screen.getByText("Newest")); }); expect(screen.getByText("No issues matching filters")).toBeTruthy(); spy.mockRejectedValueOnce(new Error("HTTP 502")); await act(async () => { fireEvent.click(screen.getByText("Clear filters")); }); expect(screen.getByText("Can't load issues")).toBeTruthy(); spy.mockResolvedValueOnce({ items: [row], next: null }); await act(async () => { fireEvent.click(screen.getByText("Retry")); }); expect(screen.getAllByRole("option")).toHaveLength(1); }); it("fetches issues only once when switching the active GitHub account", async () => { connectRepo(); const spy = vi.spyOn(api, "issueList").mockResolvedValue({ items: [row], next: null }); await act(async () => { render(); }); expect(spy).toHaveBeenCalledTimes(1); spy.mockClear(); await act(async () => { const cur = useGhRepository.getState().connection!; useGhRepository.setState({ connection: { ...cur, currentUser: user("me-work") }, }); }); expect(spy).toHaveBeenCalledTimes(1); }); it("hints #number lookup via placeholder and disables ignored filter chips while #number is active", async () => { connectRepo(); vi.spyOn(api, "issueList").mockResolvedValue({ items: [row], next: null }); await act(async () => { render(); }); const search = screen.getByRole("textbox", { name: "Search issues" }); expect(search).toHaveAttribute("placeholder", "Title or #number"); expect(screen.getByRole("button", { name: "Author" })).toBeEnabled(); expect(screen.getByRole("button", { name: "Reset State" })).toBeEnabled(); fireEvent.change(search, { target: { value: "#7" } }); await act(async () => { fireEvent.keyDown(search, { key: "Enter" }); }); for (const label of ["Open", "Reset State", "Author", "Label", "Assignee", "Sort"]) { expect(screen.getByRole("button", { name: label })).toBeDisabled(); } expect(screen.getByRole("button", { name: "Author" }).closest("[data-tooltip]")).toHaveAttribute( "data-tooltip", "Filters are ignored for #number lookup", ); fireEvent.change(search, { target: { value: "" } }); await act(async () => { fireEvent.keyDown(search, { key: "Enter" }); }); expect(screen.getByRole("button", { name: "Author" })).toBeEnabled(); expect(screen.getByRole("button", { name: "Reset State" })).toBeEnabled(); });