feat(github): browse and work on repository issues (#8077)

* feat(github): browse and work on repository issues

* fix(github): fix issue browse assignee filter, list keyboard navigation, and edge cases
Цей коміт міститься в:
l0ng-ai authored and GitHub committed 2026-12-05 00:54:51 +08:00
1 джерело 1e6ab2ecff
коміт 71bfc70996
19 files changed
+1415 -303

No files matched your search

+18
Переглянути файл
@@ -24,6 +24,8 @@ import {
T,
type MenuItem,
} from "@/ui";
import { connectedRoot } from "../data/repository";
import { hasClosingReference, issueForBranch } from "../issues/input";
import { openPullRequest } from "../toolwindow/open";
import { ChangesPanel } from "./ChangesPanel";
import { DirectionSelector } from "./DirectionSelector";
@@ -106,6 +108,13 @@ function TextPanel() {
const title = useCreatePr((s) => s.title);
const description = useCreatePr((s) => s.description);
const templateLoading = useCreatePr((s) => s.templateLoading);
const direction = useCreatePr((s) => s.direction);
const head = direction?.headBranch;
const number =
direction && head?.kind === "local"
? issueForBranch({ ...direction.baseRepo, root: direction.baseRepo.root ?? connectedRoot() }, head.name)
: null;
const closing = number ? `Closes #${number}` : null;
return (
<div className={styles.text}>
<Input
@@ -115,6 +124,15 @@ function TextPanel() {
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
{closing && number && !templateLoading && !hasClosingReference(description, number) && (
<Button
size="small"
variant="ghost"
onClick={() => setDescription([description.trimEnd(), closing].filter(Boolean).join("\n\n"))}
>
{tx`Add “${closing}” to description`}
</Button>
)}
<div className={styles.descriptionBox}>
<textarea
className={styles.description}
+38
Переглянути файл
@@ -9,12 +9,14 @@
* and `.refresh` are the Git › GitHub menu's.
*/
import "./ui/palette.css";
import { ISSUE_KIND, issueData } from "./issues/input";
import { registerActions, type Action } from "@/platform/actions";
import { setContext } from "@/platform/context";
import { whileGitEnabled } from "@/platform/gitEnabled";
import { lazyComponent } from "@/ui";
import { githubCloneSource } from "./clone/source";
import {
maybeEditorService,
registerCloneSource,
registerEditorKind,
registerGitLogChecks,
@@ -58,6 +60,23 @@ type ActionSpec = Omit<Action, "run"> & { run?: Action["run"] };
function actions(): ActionSpec[] {
return [
{
id: "github.issue.create",
title: "New Issue on GitHub…",
category: "GitHub",
icon: "plus",
when: CONNECTED,
run: async () => (await import("./issues/actions")).newIssue(),
},
{
id: "github.issue.createBranch",
title: "Create Branch from Issue…",
category: "GitHub",
icon: "branch",
when: CONNECTED,
enabled: ({ arg }) => Boolean(arg) || maybeEditorService()?.activeInput?.()?.kind === ISSUE_KIND,
run: async ({ arg }) => (await import("./issues/actions")).createIssueBranch(arg),
},
// Git › GitHub
{
// Github.View.Pull.Request
@@ -351,6 +370,25 @@ export function activate(): () => void {
headerActions: lazyView("PullRequestsHeaderActions"),
headerMenu: useHeaderMenu,
}),
registerEditorKind({
kind: ISSUE_KIND,
component: lazyComponent(() => import("./issues/IssueEditor").then((m) => m.IssueEditor)),
title: (input) => {
const d = issueData(input);
return d ? `${d.title} #${d.number}` : "GitHub Issues";
},
icon: (input) => (issueData(input)?.state === "CLOSED" ? "issue-closed" : "issue-open"),
}),
registerToolWindow({
id: "githubIssues",
title: "GitHub Issues",
icon: "toolwindow-github-issues",
anchor: "left",
order: 3,
stripe: "onUse",
component: lazyComponent(() => import("./issues/IssuesToolWindow").then((m) => m.IssuesToolWindow)),
headerMenu: useHeaderMenu,
}),
registerToolWindow({
id: ACTIONS_WINDOW,
title: "GitHub Actions",
+142
Переглянути файл
@@ -0,0 +1,142 @@
import { useCallback, useState } from "react";
import { tx } from "@/platform/i18n";
import type { EditorInput } from "@/workbench/contributions";
import { Button, EmptyState, IconButton, Spinner, T } from "@/ui";
import { executeAction } from "@/platform/actions";
import { currentUserHasPermission, repositoryKey, useGhRepository, type GHConnection } from "../data/repository";
import { openInBrowser } from "../data/local";
import { CommentEditor, CommentItem, submitShortcut } from "../timeline/comments";
import { LabelChip } from "../ui/chips";
import timeline from "../timeline/Timeline.module.css";
import { issueDetails, postIssueComment, type IssueComment } from "./api";
import { issueData } from "./input";
import { usePages } from "./usePages";
import styles from "./Issues.module.css";
export function IssueEditor({ input }: { input: EditorInput }) {
const data = issueData(input);
const connection = useGhRepository((s) => s.connection);
if (!connection || !data || repositoryKey(connection.coordinates) !== data.repository)
return <EmptyState title="Connect GitHub Issues to this repository" />;
return <Discussion key={input.key + connection.currentUser.login} connection={connection} number={data.number} />;
}
function Discussion({ connection, number }: { connection: GHConnection; number: number }) {
const fetchPage = useCallback(
(cursor: string | null) => issueDetails(connection.coordinates, number, cursor),
[connection, number],
);
const page = usePages(fetchPage);
const [posted, setPosted] = useState<IssueComment[]>([]);
const issue = page.items[0];
const retry = (
<Button size="small" onClick={() => void page.more()}>
<T>Retry</T>
</Button>
);
if (!issue)
return (
<div className={timeline.placeholder}>
{page.loading ? (
<Spinner />
) : (
<EmptyState title="Could not load issue" actions={retry}>
{page.error}
</EmptyState>
)}
</div>
);
const seen = new Set<string>();
const comments: IssueComment[] = [];
for (const item of page.items) {
for (const c of item.comments.nodes) {
if (seen.has(c.id)) continue;
seen.add(c.id);
comments.push(c);
}
}
return (
<div className={timeline.scroll}>
<div className={timeline.column}>
<h2 className={timeline.title}>
{issue.title}{" "}
<a
className={timeline.link}
href={issue.url}
onClick={(e) => {
e.preventDefault();
void openInBrowser(issue.url);
}}
>
#{number}
</a>
</h2>
<div className={styles.metadata}>
<T>{issue.state === "OPEN" ? "Open" : "Closed"}</T>
{issue.labels.nodes.map((l) => (
<LabelChip key={l.name} label={l} />
))}
{issue.assignees.nodes.map((u) => (
<span key={u.login}>@{u.login}</span>
))}
<Button
size="small"
icon="branch"
onClick={() =>
void executeAction("github.issue.createBranch", {
repository: repositoryKey(connection.coordinates),
number: issue.number,
title: issue.title,
state: issue.state,
})
}
>
<T>Create Branch…</T>
</Button>
<IconButton size="small" title="Refresh" icon="refresh" onClick={() => void page.refresh()} />
</div>
<CommentItem
author={issue.author}
createdAt={issue.createdAt}
body={issue.body}
emptyText="No description provided"
/>
{comments.map((c) => (
<CommentItem key={c.id} {...c} />
))}
{page.error && (
<div className={timeline.status} role="alert">
{page.error}
{retry}
</div>
)}
{page.next && !page.error && (
<div className={timeline.status}>
<Button size="small" disabled={page.loading} onClick={() => void page.more()}>
<T>Load more comments</T>
</Button>
</div>
)}
{posted
.filter((c) => !seen.has(c.id))
.map((c) => (
<CommentItem key={c.id} {...c} />
))}
{(!issue.locked || currentUserHasPermission("WRITE")) && (
<div className={timeline.composer}>
<CommentEditor
showAvatar
clearOnSubmit
submitLabel="Comment"
submitHint={tx`${submitShortcut()} to comment`}
onSubmit={async (text) => {
const comment = await postIssueComment(issue.id, text);
setPosted((prev) => [...prev, comment]);
}}
/>
</div>
)}
</div>
</div>
);
}
+63
Переглянути файл
@@ -0,0 +1,63 @@
.panel {
display: flex;
flex-direction: column;
height: 100%;
min-height: 0;
gap: var(--space-1);
padding: var(--space-1) var(--space-2);
}
.toolbar,
.filters,
.row,
.metadata {
display: flex;
align-items: center;
gap: var(--space-1);
min-width: 0;
}
.repo {
flex: 1;
min-width: 0;
overflow: hidden;
color: var(--fg-secondary);
text-overflow: ellipsis;
white-space: nowrap;
}
.filters,
.metadata {
flex-wrap: wrap;
}
.list {
flex: 1;
min-height: 0;
}
.row {
width: 100%;
gap: var(--space-1-5);
}
.subject {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
white-space: normal;
overflow-wrap: anywhere;
}
.row > svg {
flex: none;
}
.number {
color: var(--fg-secondary);
font-size: var(--fs-small);
}
.metadata {
margin: 0 var(--space-4) var(--space-2);
gap: var(--space-2);
color: var(--fg-secondary);
overflow-wrap: anywhere;
}
.error {
color: var(--danger);
font-size: var(--fs-small);
overflow-wrap: anywhere;
}
+123
Переглянути файл
@@ -0,0 +1,123 @@
import { useCallback, useState, type MouseEvent } from "react";
import { useRowHeight } from "@/ui/density";
import { editorService } from "@/workbench/contributions";
import { tx } from "@/platform/i18n";
import { isImeKey } from "@/platform/ime";
import { Button, EmptyState, Icon, IconButton, List, SearchField, Select, T } from "@/ui";
import { nameWithOwner, repositoryKey, useGhRepository, type GHConnection } from "../data/repository";
import { GithubConnectionGate } from "../toolwindow/GithubConnectionGate";
import { issueList, type IssueRow, type IssueStateFilter } from "./api";
import { issueInput } from "./input";
import { usePages } from "./usePages";
import styles from "./Issues.module.css";
const issueKey = (item: IssueRow) => item.number;
export function IssuesToolWindow() {
const connection = useGhRepository((s) => s.connection);
return (
<GithubConnectionGate issues>
{connection && (
<IssuesList
key={repositoryKey(connection.coordinates) + connection.currentUser.login}
connection={connection}
/>
)}
</GithubConnectionGate>
);
}
function IssuesList({ connection }: { connection: GHConnection }) {
const [text, setText] = useState("");
const [term, setTerm] = useState("");
const [state, setState] = useState<IssueStateFilter>("OPEN");
const [mine, setMine] = useState(false);
const [selectedNumber, setSelectedNumber] = useState<number | null>(null);
const fetchPage = useCallback(
(cursor: string | null) =>
issueList(connection.coordinates, term, state, mine ? connection.currentUser.login : null, cursor),
[connection, term, state, mine],
);
const page = usePages(fetchPage, issueKey);
const rowHeight = useRowHeight(44);
const exact = /^#\d+$/.test(term);
const activeIndex = page.items.length
? Math.max(
0,
page.items.findIndex((i) => i.number === selectedNumber),
)
: -1;
return (
<div className={styles.panel}>
<div className={styles.toolbar}>
<span className={styles.repo} title={nameWithOwner(connection.coordinates)}>
{nameWithOwner(connection.coordinates)}
</span>
<IconButton icon="plus" action="github.issue.create" size="small" />
<IconButton title="Refresh" icon="refresh" size="small" onClick={() => void page.refresh()} />
</div>
<SearchField
value={text}
aria-label="Search issues"
placeholder="Title or #number"
onChange={(v) => {
setText(v);
if (!v.trim()) setTerm("");
}}
onKeyDown={(e) => {
if (e.key === "Enter" && !isImeKey(e.nativeEvent)) setTerm(text.trim());
}}
/>
<div className={styles.filters}>
<Select<IssueStateFilter>
aria-label="Issue state"
variant="chip"
value={state}
disabled={exact}
options={[
{ value: "OPEN", label: "Open" },
{ value: "CLOSED", label: "Closed" },
{ value: "ALL", label: "All" },
]}
onChange={setState}
/>
<Button size="small" variant="ghost" aria-pressed={mine} disabled={exact} onClick={() => setMine((v) => !v)}>
{mine && <Icon name="check" size={12} />}
<T>Assigned to me</T>
</Button>
</div>
<List
rowHeight={rowHeight}
items={page.items}
getKey={(i) => String(i.number)}
activeIndex={activeIndex}
onActiveChange={(i) => setSelectedNumber(page.items[i]?.number ?? null)}
className={styles.list}
aria-label="GitHub Issues"
onActivate={(row, _i, event) => {
if (event.type === "click" && (event as MouseEvent).detail !== 2) return;
void editorService().openInput(issueInput(repositoryKey(connection.coordinates), row), { focus: true });
}}
renderItem={(row) => (
<span className={styles.row} title={row.title}>
<Icon name={row.state === "OPEN" ? "issue-open" : "issue-closed"} size={16} />
<span className={styles.subject}>
<span className={styles.number}>#{row.number}</span> {row.title}
</span>
</span>
)}
empty={page.error ? null : <EmptyState title={page.loading ? "Loading…" : "No matching issues"} />}
/>
{page.error && (
<div className={styles.error} role="alert">
{page.error}
</div>
)}
{(page.next || page.error) && (
<Button size="small" disabled={page.loading} onClick={() => void page.more()}>
{tx(page.error ? "Retry" : "Load more")}
</Button>
)}
</div>
);
}
+48
Переглянути файл
@@ -0,0 +1,48 @@
import { executeAction } from "@/platform/actions";
import { call, commands } from "@/platform/ipc";
import { maybeEditorService } from "@/workbench/contributions";
import { pickItems } from "@/workbench/inputDialogs";
import { useGhRepository, repositoryKey } from "../data/repository";
import { openInBrowser } from "../data/local";
import { issueBranchName, issueData, rememberIssueBranch, type IssueInput } from "./input";
export function newIssue() {
const connection = useGhRepository.getState().connection;
if (connection) return openInBrowser(`${connection.repository.url}/issues/new/choose`);
}
function asIssueInput(arg: unknown): IssueInput | null {
if (!arg || typeof arg !== "object") return null;
const d = arg as Partial<IssueInput>;
return typeof d.number === "number" && typeof d.repository === "string" && typeof d.title === "string"
? (d as IssueInput)
: null;
}
export async function createIssueBranch(arg?: unknown) {
const input = maybeEditorService()?.activeInput?.();
const issue = asIssueInput(arg) ?? (input && issueData(input));
const connection = useGhRepository.getState().connection;
if (!connection || !issue || repositoryKey(connection.coordinates) !== issue.repository) return;
const branches = await call(commands.vcsBranches(connection.root));
if (connection !== useGhRepository.getState().connection) return;
const choices = branches
.filter((b) => !b.remote || !b.name.endsWith("/HEAD"))
.sort((a, b) => Number(b.current) - Number(a.current));
if (!choices.length) return;
const picked = await pickItems({
title: "Choose Base Branch",
multiple: false,
filter: true,
items: choices.map((b, i) => ({ key: String(i), label: b.name })),
});
if (!picked?.length || connection !== useGhRepository.getState().connection) return;
const base = choices[Number(picked[0])]!;
await executeAction("vcs.newBranch", {
repo: connection.root,
from: { name: base.name, remote: base.remote },
suggestedName: issueBranchName(issue),
onCreated: (branch: string) =>
rememberIssueBranch({ ...connection.coordinates, root: connection.root }, branch, issue.number),
});
}
+167
Переглянути файл
@@ -0,0 +1,167 @@
import { graphql, repoVariables } from "../api/client";
import type { GHActor, GHConnection, GHRepositoryCoordinates } from "../api/types";
import { nameWithOwner } from "../data/repository";
export interface IssueRow {
number: number;
title: string;
state: "OPEN" | "CLOSED";
}
export interface IssueComment {
id: string;
author: GHActor | null;
body: string;
createdAt: string;
}
interface Issue extends IssueRow, IssueComment {
url: string;
locked: boolean;
labels: { nodes: { name: string; color: string }[] };
assignees: { nodes: { login: string }[] };
comments: GHConnection<IssueComment>;
}
const rowFields = "number title state";
const pageInfo = "pageInfo { hasNextPage endCursor }";
const numbered = `query($repoOwner:String!, $repoName:String!, $number:Int!) {
repository(owner:$repoOwner,name:$repoName) {
issueOrPullRequest(number:$number) { __typename ... on Issue { ${rowFields} } }
}
}`;
const browse = `query($repoOwner:String!, $repoName:String!, $states:[IssueState!], $filter:IssueFilters, $cursor:String) {
repository(owner:$repoOwner,name:$repoName) {
issues(first:50, after:$cursor, states:$states, filterBy:$filter, orderBy:{field:UPDATED_AT,direction:DESC}) {
nodes { ${rowFields} }
${pageInfo}
}
}
}`;
const search = `query($query:String!, $cursor:String) {
search(first:50, after:$cursor, type:ISSUE, query:$query) {
nodes { ... on Issue { ${rowFields} } }
${pageInfo}
}
}`;
export type IssueStateFilter = "OPEN" | "CLOSED" | "ALL";
export async function issueList(
repo: GHRepositoryCoordinates,
text: string,
state: IssueStateFilter,
assigned: string | null,
cursor: string | null,
) {
const term = text.trim();
const vars = repoVariables(repo);
if (/^#\d+$/.test(term)) {
const number = Number(term.slice(1));
if (!number || number > 2147483647) return { items: [], next: null };
const data = await graphql<{
repository: { issueOrPullRequest: (IssueRow & { __typename: string }) | null } | null;
}>(numbered, { ...vars, number });
const row = data.repository?.issueOrPullRequest;
return { items: row?.__typename === "Issue" ? [row] : [], next: null };
}
let page: GHConnection<IssueRow | null> | null;
if (term) {
const query = [
`repo:${nameWithOwner(repo)}`,
"is:issue",
"in:title",
"sort:updated-desc",
state !== "ALL" && `is:${state.toLowerCase()}`,
assigned && `assignee:${assigned}`,
JSON.stringify(term),
]
.filter(Boolean)
.join(" ");
page = (await graphql<{ search: GHConnection<IssueRow | null> }>(search, { query, cursor })).search;
} else {
page =
(
await graphql<{ repository: { issues: GHConnection<IssueRow | null> } | null }>(browse, {
...vars,
states: state === "ALL" ? null : [state],
filter: assigned ? { assignee: assigned } : null,
cursor,
})
).repository?.issues ?? null;
}
return {
items: (page?.nodes ?? []).filter((row): row is IssueRow => Boolean(row?.number)),
next: page?.pageInfo.hasNextPage && page.pageInfo.endCursor ? page.pageInfo.endCursor : null,
};
}
const details = `query($repoOwner:String!, $repoName:String!, $number:Int!, $cursor:String) {
repository(owner:$repoOwner,name:$repoName) {
issue(number:$number) {
${rowFields} id url body createdAt locked
author {
...actorInfo
}
labels(first:100) { nodes { name color } }
assignees(first:100) { nodes { login } }
comments(first:50, after:$cursor) {
nodes {
id body createdAt
author {
...actorInfo
}
}
${pageInfo}
}
}
}
}`;
export async function issueDetails(repo: GHRepositoryCoordinates, number: number, cursor: string | null) {
const data = await graphql<{ repository: { issue: Issue | null } | null }>(details, {
...repoVariables(repo),
number,
cursor,
});
const raw = data.repository?.issue;
const issue = raw
? {
...raw,
comments: {
...raw.comments,
nodes: raw.comments.nodes.filter((comment): comment is IssueComment => Boolean(comment?.id)),
},
}
: null;
return {
items: issue ? [issue] : [],
next:
issue?.comments.pageInfo.hasNextPage && issue.comments.pageInfo.endCursor
? issue.comments.pageInfo.endCursor
: null,
};
}
export async function postIssueComment(id: string, body: string) {
const result = await graphql<{ addComment: { commentEdge: { node: IssueComment } } }>(
`
mutation ($id: ID!, $body: String!) {
addComment(input: { subjectId: $id, body: $body }) {
commentEdge {
node {
id
body
createdAt
author {
...actorInfo
}
}
}
}
}
`,
{ id, body },
);
return result.addComment.commentEdge.node;
}
+67
Переглянути файл
@@ -0,0 +1,67 @@
import { useProject } from "@/platform/project";
import type { EditorInput } from "@/workbench/contributions";
import type { GHRepositoryCoordinates } from "../api/types";
import type { IssueRow } from "./api";
export const ISSUE_KIND = "github.issue";
export interface IssueInput extends IssueRow {
repository: string;
}
export function issueInput(repository: string, row: IssueRow): EditorInput {
const data: IssueInput = { repository, number: row.number, title: row.title, state: row.state };
return { kind: ISSUE_KIND, key: `${ISSUE_KIND}:${repository}#${row.number}`, data };
}
export function issueData(input: EditorInput): IssueInput | null {
const d = input.data as Partial<IssueInput> | undefined;
return input.kind === ISSUE_KIND &&
typeof d?.number === "number" &&
typeof d.repository === "string" &&
typeof d.title === "string"
? (d as IssueInput)
: null;
}
export function issueBranchName(issue: IssueRow) {
const normalized = issue.title
.normalize("NFC")
.toLowerCase()
.replace(/[^\p{L}\p{N}]+/gu, "-")
.replace(/^-+/, "");
const slug = [...normalized].slice(0, 48).join("").replace(/-+$/, "");
return [`issue-${issue.number}`, slug].filter(Boolean).join("-");
}
export function hasClosingReference(description: string, number: number): boolean {
return new RegExp(`(?:^|[\\s(])(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?):?\\s+#${number}(?:$|[^\\d])`, "i").test(
description,
);
}
type Checkout = GHRepositoryCoordinates & { root?: string | null };
function branchKey(repo: Checkout, branch: string) {
const root = repo.root ?? useProject.getState().project?.root ?? "";
const host = (repo.host ?? "github.com").toLowerCase();
const owner = repo.owner.toLowerCase();
const name = repo.name.toLowerCase();
return `openidea.github.issueBranch.v1:${root}:${host}/${owner}/${name}:${branch}`;
}
export function rememberIssueBranch(repo: Checkout, branch: string, number: number) {
try {
localStorage.setItem(branchKey(repo, branch), String(number));
} catch {
/* storage unavailable */
}
}
export function issueForBranch(repo: Checkout, branch: string): number | null {
try {
return Number(localStorage.getItem(branchKey(repo, branch))) || null;
} catch {
return null;
}
}
+281
Переглянути файл
@@ -0,0 +1,281 @@
import { afterEach, expect, it, vi } from "vitest";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import * as actions from "@/platform/actions";
import { maybeEditorService, provideEditorService, type EditorService } from "@/workbench/contributions";
import * as client from "../api/client";
import type { GHRepository, GHUser } from "../api/types";
import { resetConnection, useGhRepository } from "../data/repository";
import * as api from "./api";
import { IssueEditor } from "./IssueEditor";
import { IssuesToolWindow } from "./IssuesToolWindow";
import { hasClosingReference, issueBranchName, issueForBranch, issueInput, rememberIssueBranch } from "./input";
const repo = { owner: "acme", name: "app", host: "code.example" };
const row = { title: "Fix editor focus", number: 7, state: "OPEN" as const };
const input = issueInput("code.example/acme/app", row);
function connectRepo() {
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",
},
},
connection: {
coordinates: repo,
root: "/one",
repository: { viewerPermission: "READ", url: "https://code.example/acme/app" } as GHRepository,
currentUser: { login: "me" } as GHUser,
remotes: [],
},
});
}
afterEach(() => {
vi.restoreAllMocks();
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("omits assignee filter when browsing all issues and passes IssueFilters when filtering by assignee", async () => {
const gql = vi.spyOn(client, "graphql").mockResolvedValue({
repository: {
issues: {
nodes: [row, null],
pageInfo: { hasNextPage: true, endCursor: "c1" },
},
},
});
const all = await api.issueList(repo, "", "OPEN", null, null);
expect(all).toEqual({ items: [row], next: "c1" });
expect(gql).toHaveBeenCalledWith(
expect.stringContaining("$filter:IssueFilters"),
expect.objectContaining({ filter: null, states: ["OPEN"], cursor: null }),
);
await api.issueList(repo, "", "ALL", "me", "c1");
expect(gql).toHaveBeenLastCalledWith(
expect.stringContaining("filterBy:$filter"),
expect.objectContaining({ filter: { assignee: "me" }, states: null, cursor: "c1" }),
);
});
it("filters out pull requests on exact #number lookup and safely quotes search queries", async () => {
const gql = vi
.spyOn(client, "graphql")
.mockResolvedValueOnce({ repository: { issueOrPullRequest: { __typename: "PullRequest" } } })
.mockResolvedValueOnce({
search: {
nodes: [null, {}, row],
pageInfo: { hasNextPage: false, endCursor: null },
},
});
expect(await api.issueList(repo, "#0", "OPEN", null, null)).toEqual({ items: [], next: null });
expect(await api.issueList(repo, "#9999999999", "OPEN", null, null)).toEqual({ items: [], next: null });
expect(gql).not.toHaveBeenCalled();
expect(await api.issueList(repo, "#12", "OPEN", null, null)).toEqual({ items: [], next: null });
expect(await api.issueList(repo, 'foo "is:pr"', "CLOSED", "me", null)).toEqual({ items: [row], next: null });
expect(gql).toHaveBeenLastCalledWith(expect.any(String), {
query: 'repo:acme/app is:issue in:title sort:updated-desc is:closed assignee:me "foo \\"is:pr\\""',
cursor: null,
});
});
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(<IssueEditor input={input} />);
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(<IssueEditor input={input} />);
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("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 = [
{ number: 10, title: "First issue", state: "OPEN" as const },
{ number: 9, title: "Second issue", state: "OPEN" as const },
{ number: 8, title: "Third issue", state: "OPEN" as const },
];
const page2 = [
{ number: 8, title: "Third issue", state: "OPEN" as const },
{ number: 7, title: "Fourth issue", state: "OPEN" as const },
];
vi.spyOn(api, "issueList").mockImplementation(async (_r, term, _state, _assigned, cursor) => {
if (term === "#7") return { items: [row], next: null };
if (cursor === "c1") return { items: page2, next: null };
return { items: page1, next: "c1" };
});
render(<IssuesToolWindow />);
const loadMore = await screen.findByRole("button", { name: "Load more" });
fireEvent.click(loadMore);
await waitFor(() => expect(screen.queryByRole("button", { name: "Load more" })).toBeNull());
// 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" } });
fireEvent.keyDown(search, { key: "Enter" });
await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, "#7", "OPEN", null, null));
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", 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;
});
vi.spyOn(api, "issueList").mockImplementation((_r, _term, _state, assigned) => {
if (assigned === "me")
return Promise.resolve({ items: [{ number: 42, title: "Mine", state: "OPEN" }], next: null });
return first;
});
render(<IssuesToolWindow />);
const mineBtn = await screen.findByRole("button", { name: "Assigned to me" });
fireEvent.click(mineBtn);
await waitFor(() => expect(api.issueList).toHaveBeenCalledWith(repo, "", "OPEN", "me", null));
// Resolve the stale unfiltered request after the filtered request already completed.
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: "Mine", state: "OPEN" }),
{ focus: true },
);
} finally {
provideEditorService(previousEditor);
}
});
+71
Переглянути файл
@@ -0,0 +1,71 @@
import { useEffect, useMemo } from "react";
import { createStore, useStore } from "zustand";
import { errorMessage } from "../api/client";
interface Page<T> {
items: T[];
next: string | null;
}
function mergeItems<T>(previous: T[], incoming: T[], keyOf?: (item: T) => string | number) {
if (!keyOf) return [...previous, ...incoming];
const seen = new Set(previous.map(keyOf));
const out = [...previous];
for (const item of incoming) {
const key = keyOf(item);
if (seen.has(key)) continue;
seen.add(key);
out.push(item);
}
return out;
}
function pagesFor<T>(fetchPage: (cursor: string | null) => Promise<Page<T>>, keyOf?: (item: T) => string | number) {
const store = createStore(() => ({
items: [] as T[],
next: null as string | null,
loading: true,
error: "",
retryCursor: null as string | null,
}));
let sequence = 0;
async function load(cursor: string | null) {
const request = ++sequence;
store.setState({ loading: true, error: "", retryCursor: cursor });
try {
const result = await fetchPage(cursor);
if (request === sequence)
store.setState((previous) => ({
items: cursor ? mergeItems(previous.items, result.items, keyOf) : mergeItems([], result.items, keyOf),
next: result.next,
loading: false,
}));
} catch (e) {
if (request === sequence) store.setState({ loading: false, error: errorMessage(e) });
}
}
return {
store,
load,
cancel: () => {
sequence++;
},
};
}
export function usePages<T>(
fetchPage: (cursor: string | null) => Promise<Page<T>>,
keyOf?: (item: T) => string | number,
) {
const pages = useMemo(() => pagesFor(fetchPage, keyOf), [fetchPage, keyOf]);
const state = useStore(pages.store);
useEffect(() => {
void pages.load(null);
return pages.cancel;
}, [pages]);
return {
...state,
more: () => pages.load(state.error ? state.retryCursor : state.next),
refresh: () => pages.load(null),
};
}
+309
Переглянути файл
@@ -0,0 +1,309 @@
import { useEffect, useRef, useState, type ReactNode } from "react";
import type { GhAvailability } from "@/platform/ipc";
import { isCancelled } from "@/platform/ipc";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
import { tx } from "@/platform/i18n";
import { Button, EmptyState, Select, Spinner, T } from "@/ui";
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
import {
loadProjectGithubAccount,
projectAccountOptions,
refreshAfterGithubSignIn,
setProjectGithubAccount,
useGhProjectAccount,
} from "../data/account";
import { connect, repositoryKey, refreshConnection, sameRepository, useGhRepository } from "../data/repository";
import { repositoryDisplayName } from "../data/model";
import { openInBrowser } from "../data/local";
import styles from "./ToolWindow.module.css";
export function useGhSignIn() {
const [open, setOpen] = useState(false);
const prevLoginsRef = useRef<Set<string>>(new Set());
const start = () => {
prevLoginsRef.current = new Set((useGhProjectAccount.getState().status?.accounts ?? []).map((a) => a.login));
setOpen(true);
};
const dialog = open ? (
<CliSignInDialog
target={{ kind: "gh" }}
onClose={() => setOpen(false)}
onCompleted={() => {
const beforeRev = useGhProjectAccount.getState().revision;
void refreshAfterGithubSignIn(prevLoginsRef.current).finally(() => {
// `setProjectGithubAccount` already bumps `revision` (which triggers `refreshConnection` in runtime.ts);
// refresh explicitly when the active account changed under `Automatic` without changing `revision`.
if (useGhProjectAccount.getState().revision === beforeRev) {
void refreshConnection();
}
});
}}
/>
) : null;
return { start, dialog };
}
function ProjectAccountInline({ onAddAccount }: { onAddAccount?: () => void }) {
const status = useGhProjectAccount((s) => s.status);
const saving = useGhProjectAccount((s) => s.saving);
if (!status || (status.accounts.length === 0 && !(onAddAccount && status.ghInstalled))) return null;
const suggested = !status.configuredAccount ? status.suggestedAccount : null;
return (
<div className={styles.accountInline}>
{suggested && (
<Button
size="small"
variant="primary"
disabled={saving}
onClick={() => void setProjectGithubAccount(suggested)}
>
{tx`Use ${suggested} for this project`}
</Button>
)}
<div className={styles.accountInlineRow}>
{status.accounts.length > 0 && (
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={saving}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
)}
{onAddAccount && status.ghInstalled && (
<Button size="small" disabled={saving} onClick={onAddAccount}>
<T>{status.accounts.length > 0 ? "Add account…" : "Sign In…"}</T>
</Button>
)}
</div>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and run
configurations).
</T>
</div>
)}
</div>
);
}
function Unavailable({
availability,
onSignIn,
issues,
}: {
issues: boolean;
availability: GhAvailability;
onSignIn: () => void;
}) {
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
const installGh = () => {
if (installingGh) return;
setInstallingGh(true);
setInstallError(null);
void installGhTool()
.promise.then((installed) => {
if (installed) {
void loadProjectGithubAccount();
void refreshConnection();
}
})
.catch((e: unknown) => {
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
})
.finally(() => setInstallingGh(false));
};
const retry = (
<Button size="small" onClick={() => void refreshConnection()}>
<T>Retry</T>
</Button>
);
switch (availability.kind) {
case "notInstalled":
return (
<EmptyState
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
{installingGh ? (
<>
<Spinner size={12} /> <T>Installing…</T>
</>
) : (
<T>Install GitHub CLI</T>
)}
</Button>
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
<T>Download manually…</T>
</Button>
{retry}
</>
}
>
<T>{issues ? "GitHub Issues uses the" : "Pull requests use the"}</T> <code>gh</code>{" "}
<T>command line tool. Install it, then run</T> <code>gh auth login</code>.
{installError && <div className={styles.hint}>{installError}</div>}
</EmptyState>
);
case "notLoggedIn":
return (
<EmptyState
title="Not logged in to GitHub"
actions={
<>
<Button size="small" variant="primary" onClick={onSignIn}>
<T>Sign In…</T>
</Button>
{retry}
</>
}
>
<T>
{issues
? "Sign in with GitHub CLI to view issues."
: "Sign in with GitHub CLI to view and review pull requests."}
</T>
<ProjectAccountInline />
</EmptyState>
);
case "notGitHub":
return (
<EmptyState title="No GitHub repository" actions={retry}>
<div>
<T>This project has no remote on GitHub.</T>
</div>
<div className={styles.hint}>{availability.message}</div>
</EmptyState>
);
case "error":
return (
<EmptyState title="Could not reach GitHub" actions={retry}>
<div>{availability.message}</div>
<ProjectAccountInline onAddAccount={onSignIn} />
</EmptyState>
);
default:
return null;
}
}
/** IntelliJ's repository selector: the repositories (owner always shown), project account, and "View Pull Requests". */
function RepositorySelector({ onSignIn, connectLabel }: { onSignIn: () => void; connectLabel: string }) {
const remotes = useGhRepository((s) => s.remotes);
const defaultRemote = useGhRepository((s) => s.defaultRemote);
const connecting = useGhRepository((s) => s.connecting);
const error = useGhRepository((s) => s.connectionError);
const status = useGhProjectAccount((s) => s.status);
const savingAccount = useGhProjectAccount((s) => s.saving);
const [chosen, setChosen] = useState<string | null>(null);
const value =
chosen ??
repositoryKey(remotes.find((r) => sameRepository(r, defaultRemote)) ?? remotes[0] ?? { owner: "", name: "" });
const target = remotes.find((r) => repositoryKey(r) === value);
// Remotes on more than one host (an Enterprise server and github.com) say which.
const hosts = new Set(remotes.map((r) => r.host ?? "github.com")).size > 1;
return (
<div className={styles.selector}>
{status && (status.accounts.length > 0 || status.ghInstalled) && (
<>
<div className={styles.selectorRow}>
{status.accounts.length > 0 && (
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={savingAccount}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
)}
{status.ghInstalled && (
<Button size="small" disabled={savingAccount} onClick={onSignIn}>
<T>{status.accounts.length > 0 ? "Add account…" : "Sign In…"}</T>
</Button>
)}
{!status.configuredAccount && status.suggestedAccount && (
<Button
size="small"
disabled={savingAccount}
onClick={() => void setProjectGithubAccount(status.suggestedAccount!)}
>
{tx`Use ${status.suggestedAccount} for this project`}
</Button>
)}
</div>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and
run configurations).
</T>
</div>
)}
</>
)}
<div className={styles.selectorRow}>
<Select
value={value}
options={remotes.map((r) => ({
value: repositoryKey(r),
verbatim: true,
label: `${repositoryDisplayName(remotes, r, true)}${hosts ? ` · ${r.host ?? "github.com"}` : ""}`,
}))}
onChange={setChosen}
aria-label="Repository"
/>
<Button
size="small"
variant="primary"
disabled={!target || connecting}
onClick={() => target && void connect(target)}
>
<T>{connectLabel}</T>
</Button>
{connecting && <Spinner size={14} />}
</div>
{error && <div className={styles.error}>{error}</div>}
</div>
);
}
export function GithubConnectionGate({ children, issues = false }: { children: ReactNode; issues?: boolean }) {
const availability = useGhRepository((s) => s.availability);
const checking = useGhRepository((s) => s.checking);
const connected = useGhRepository((s) => !!s.connection);
const connecting = useGhRepository((s) => s.connecting);
const signIn = useGhSignIn();
useEffect(() => {
if (!useGhProjectAccount.getState().status) void loadProjectGithubAccount();
if (!useGhRepository.getState().availability) void refreshConnection();
}, []);
if (!availability)
return (
<div className={styles.loading}>
{checking && <Spinner size={14} />} {tx("Connecting to GitHub…")}
</div>
);
if (availability.kind !== "ready")
return (
<>
<Unavailable issues={issues} availability={availability} onSignIn={signIn.start} />
{signIn.dialog}
</>
);
if (connected) return <>{children}</>;
if (connecting)
return (
<div className={styles.loading}>
<Spinner size={14} /> {tx("Connecting to GitHub…")}
</div>
);
return (
<>
<RepositorySelector connectLabel={issues ? "View GitHub Issues" : "View Pull Requests"} onSignIn={signIn.start} />
{signIn.dialog}
</>
);
}
+9 -296
Переглянути файл
@@ -4,281 +4,24 @@
* (projects with several GitHub remotes), then the content tabs — the list tab named after
* the repository, `#N` tabs and "New Pull Request at {repo}" — in the header.
*/
import { useEffect, useRef, useState, type RefObject } from "react";
import { useEffect, useRef, type RefObject } from "react";
import type { GhProjectAccountStatus } from "@/bindings";
import type { GhAvailability } from "@/platform/ipc";
import { executeAction } from "@/platform/actions";
import { GH_MANUAL_INSTALL_URL, installGhTool } from "@/platform/ghTool";
import { isCancelled } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { Button, EmptyState, IconButton, Select, Spinner, Tabs, T, showContextMenu, type MenuItem } from "@/ui";
import { CliSignInDialog } from "@/workbench/CliSignInDialog";
import { IconButton, Spinner, Tabs, showContextMenu, type MenuItem } from "@/ui";
import { CreatePanel } from "../create/CreatePanel";
import { DetailsPanel } from "../details/DetailsPanel";
import { ListPanel } from "../list/ListPanel";
import {
loadProjectGithubAccount,
projectAccountOptions,
refreshAfterGithubSignIn,
setProjectGithubAccount,
useGhProjectAccount,
} from "../data/account";
import { setProjectGithubAccount, useGhProjectAccount } from "../data/account";
import { reloadList, useGhPrList } from "../data/list";
import { cancelBusy, openInBrowser, useGhBusy } from "../data/local";
import { cancelBusy, useGhBusy } from "../data/local";
import { repositoryDisplayName } from "../data/model";
import { cachedDetails } from "../data/pullRequest";
import {
connect,
disconnect,
nameWithOwner,
repositoryKey,
refreshConnection,
sameRepository,
useGhRepository,
} from "../data/repository";
import { disconnect, nameWithOwner, useGhRepository } from "../data/repository";
import { closeTab, selectTab, tabId, useGhTabs, type GhTabId } from "./store";
import { GithubConnectionGate, useGhSignIn } from "./GithubConnectionGate";
import styles from "./ToolWindow.module.css";
function useGhSignIn() {
const [open, setOpen] = useState(false);
const prevLoginsRef = useRef<Set<string>>(new Set());
const start = () => {
prevLoginsRef.current = new Set((useGhProjectAccount.getState().status?.accounts ?? []).map((a) => a.login));
setOpen(true);
};
const dialog = open ? (
<CliSignInDialog
target={{ kind: "gh" }}
onClose={() => setOpen(false)}
onCompleted={() => {
const beforeRev = useGhProjectAccount.getState().revision;
void refreshAfterGithubSignIn(prevLoginsRef.current).finally(() => {
// `setProjectGithubAccount` already bumps `revision` (which triggers `refreshConnection` in runtime.ts);
// refresh explicitly when the active account changed under `Automatic` without changing `revision`.
if (useGhProjectAccount.getState().revision === beforeRev) {
void refreshConnection();
}
});
}}
/>
) : null;
return { start, dialog };
}
function ProjectAccountInline({ onAddAccount }: { onAddAccount?: () => void }) {
const status = useGhProjectAccount((s) => s.status);
const saving = useGhProjectAccount((s) => s.saving);
if (!status || (status.accounts.length === 0 && !(onAddAccount && status.ghInstalled))) return null;
const suggested = !status.configuredAccount ? status.suggestedAccount : null;
return (
<div className={styles.accountInline}>
{suggested && (
<Button
size="small"
variant="primary"
disabled={saving}
onClick={() => void setProjectGithubAccount(suggested)}
>
{tx`Use ${suggested} for this project`}
</Button>
)}
<div className={styles.accountInlineRow}>
{status.accounts.length > 0 && (
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={saving}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
)}
{onAddAccount && status.ghInstalled && (
<Button size="small" disabled={saving} onClick={onAddAccount}>
<T>{status.accounts.length > 0 ? "Add account…" : "Sign In…"}</T>
</Button>
)}
</div>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and run
configurations).
</T>
</div>
)}
</div>
);
}
function Unavailable({ availability, onSignIn }: { availability: GhAvailability; onSignIn: () => void }) {
const [installingGh, setInstallingGh] = useState(false);
const [installError, setInstallError] = useState<string | null>(null);
const installGh = () => {
if (installingGh) return;
setInstallingGh(true);
setInstallError(null);
void installGhTool()
.promise.then((installed) => {
if (installed) {
void loadProjectGithubAccount();
void refreshConnection();
}
})
.catch((e: unknown) => {
if (!isCancelled(e)) setInstallError(e instanceof Error ? e.message : String(e));
})
.finally(() => setInstallingGh(false));
};
const retry = (
<Button size="small" onClick={() => void refreshConnection()}>
<T>Retry</T>
</Button>
);
switch (availability.kind) {
case "notInstalled":
return (
<EmptyState
title="GitHub CLI is not installed"
actions={
<>
<Button size="small" variant="primary" disabled={installingGh} onClick={installGh}>
{installingGh ? (
<>
<Spinner size={12} /> <T>Installing…</T>
</>
) : (
<T>Install GitHub CLI</T>
)}
</Button>
<Button size="small" onClick={() => void openInBrowser(GH_MANUAL_INSTALL_URL)}>
<T>Download manually…</T>
</Button>
{retry}
</>
}
>
<T>Pull requests use the</T> <code>gh</code> <T>command line tool. Install it, then run</T>{" "}
<code>gh auth login</code>.{installError && <div className={styles.hint}>{installError}</div>}
</EmptyState>
);
case "notLoggedIn":
return (
<EmptyState
title="Not logged in to GitHub"
actions={
<>
<Button size="small" variant="primary" onClick={onSignIn}>
<T>Sign In…</T>
</Button>
{retry}
</>
}
>
<T>Sign in with GitHub CLI to view and review pull requests.</T>
<ProjectAccountInline />
</EmptyState>
);
case "notGitHub":
return (
<EmptyState title="No GitHub repository" actions={retry}>
<div>
<T>This project has no remote on GitHub.</T>
</div>
<div className={styles.hint}>{availability.message}</div>
</EmptyState>
);
case "error":
return (
<EmptyState title="Could not reach GitHub" actions={retry}>
<div>{availability.message}</div>
<ProjectAccountInline onAddAccount={onSignIn} />
</EmptyState>
);
default:
return null;
}
}
/** IntelliJ's repository selector: the repositories (owner always shown), project account, and "View Pull Requests". */
function RepositorySelector({ onSignIn }: { onSignIn: () => void }) {
const remotes = useGhRepository((s) => s.remotes);
const defaultRemote = useGhRepository((s) => s.defaultRemote);
const connecting = useGhRepository((s) => s.connecting);
const error = useGhRepository((s) => s.connectionError);
const status = useGhProjectAccount((s) => s.status);
const savingAccount = useGhProjectAccount((s) => s.saving);
const [chosen, setChosen] = useState<string | null>(null);
const value =
chosen ??
repositoryKey(remotes.find((r) => sameRepository(r, defaultRemote)) ?? remotes[0] ?? { owner: "", name: "" });
const target = remotes.find((r) => repositoryKey(r) === value);
// Remotes on more than one host (an Enterprise server and github.com) say which.
const hosts = new Set(remotes.map((r) => r.host ?? "github.com")).size > 1;
return (
<div className={styles.selector}>
{status && (status.accounts.length > 0 || status.ghInstalled) && (
<>
<div className={styles.selectorRow}>
{status.accounts.length > 0 && (
<Select
aria-label="GitHub account"
value={status.configuredAccount}
disabled={savingAccount}
options={projectAccountOptions(status)}
onChange={(next) => void setProjectGithubAccount(next)}
/>
)}
{status.ghInstalled && (
<Button size="small" disabled={savingAccount} onClick={onSignIn}>
<T>{status.accounts.length > 0 ? "Add account…" : "Sign In…"}</T>
</Button>
)}
{!status.configuredAccount && status.suggestedAccount && (
<Button
size="small"
disabled={savingAccount}
onClick={() => void setProjectGithubAccount(status.suggestedAccount!)}
>
{tx`Use ${status.suggestedAccount} for this project`}
</Button>
)}
</div>
{status.configuredAccount && (
<div className={styles.hint}>
<T>
Passes this account&apos;s GH_TOKEN to processes started in this project (terminals, agents, Git, and
run configurations).
</T>
</div>
)}
</>
)}
<div className={styles.selectorRow}>
<Select
value={value}
options={remotes.map((r) => ({
value: repositoryKey(r),
verbatim: true,
label: `${repositoryDisplayName(remotes, r, true)}${hosts ? ` · ${r.host ?? "github.com"}` : ""}`,
}))}
onChange={setChosen}
aria-label="Repository"
/>
<Button
size="small"
variant="primary"
disabled={!target || connecting}
onClick={() => target && void connect(target)}
>
<T>View Pull Requests</T>
</Button>
{connecting && <Spinner size={14} />}
</div>
{error && <div className={styles.error}>{error}</div>}
</div>
);
}
function BusyBanner() {
const busy = useGhBusy((s) => s.busy);
if (!busy) return null;
@@ -343,40 +86,10 @@ function Connected() {
/** The tool window's content. */
export function PullRequestsToolWindow() {
const availability = useGhRepository((s) => s.availability);
const checking = useGhRepository((s) => s.checking);
const connected = useGhRepository((s) => !!s.connection);
const connecting = useGhRepository((s) => s.connecting);
const signIn = useGhSignIn();
useEffect(() => {
if (!useGhProjectAccount.getState().status) void loadProjectGithubAccount();
if (!useGhRepository.getState().availability) void refreshConnection();
}, []);
if (!availability)
return (
<div className={styles.loading}>
{checking && <Spinner size={14} />} {tx("Connecting to GitHub…")}
</div>
);
if (availability.kind !== "ready")
return (
<>
<Unavailable availability={availability} onSignIn={signIn.start} />
{signIn.dialog}
</>
);
if (connected) return <Connected />;
if (connecting)
return (
<div className={styles.loading}>
<Spinner size={14} /> {tx("Connecting to GitHub…")}
</div>
);
return (
<>
<RepositorySelector onSignIn={signIn.start} />
{signIn.dialog}
</>
<GithubConnectionGate>
<Connected />
</GithubConnectionGate>
);
}