feat(KB-262): add Pull Requests tab to GitHub Import modal

- Add listPullRequests and getPullRequest methods to GitHubClient
- Add /github/pulls/fetch and /github/pulls/import API endpoints
- Add apiFetchGitHubPulls and apiImportGitHubPull frontend API functions
- Add tabbed UI for Issues and Pull Requests in GitHubImportModal
- Add comprehensive PR tab tests (14 new tests)
- Include changeset for the new PR tab feature
This commit is contained in:
gsxdsm
2026-03-31 06:03:45 -07:00
parent dc1cdcd3aa
commit de094990a9
7 changed files with 1096 additions and 69 deletions

View File

@@ -411,6 +411,38 @@ export function apiBatchImportGitHubIssues(
});
}
// --- GitHub Pull Request Import API ---
/** GitHub pull request returned by the fetch endpoint */
export interface GitHubPull {
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
}
/** Fetch open GitHub pull requests from a repository */
export function apiFetchGitHubPulls(
owner: string,
repo: string,
limit?: number
): Promise<GitHubPull[]> {
return api<GitHubPull[]>("/github/pulls/fetch", {
method: "POST",
body: JSON.stringify({ owner, repo, limit }),
});
}
/** Import a specific GitHub pull request as a kb review task */
export function apiImportGitHubPull(owner: string, repo: string, prNumber: number): Promise<Task> {
return api<Task>("/github/pulls/import", {
method: "POST",
body: JSON.stringify({ owner, repo, prNumber }),
});
}
// --- Git Remote Detection API ---
/** Git remote info returned by the remotes endpoint */

View File

@@ -1,7 +1,16 @@
import { useState, useEffect, useCallback, useRef } from "react";
import type { Task } from "@kb/core";
import { apiFetchGitHubIssues, apiImportGitHubIssue, fetchGitRemotes, type GitHubIssue, type GitRemote } from "../api";
import { Loader2, RefreshCw, ArrowLeft } from "lucide-react";
import {
apiFetchGitHubIssues,
apiImportGitHubIssue,
apiFetchGitHubPulls,
apiImportGitHubPull,
fetchGitRemotes,
type GitHubIssue,
type GitHubPull,
type GitRemote,
} from "../api";
import { Loader2, RefreshCw, ArrowLeft, GitPullRequest, CircleDot } from "lucide-react";
interface GitHubImportModalProps {
isOpen: boolean;
@@ -13,13 +22,25 @@ interface GitHubImportModalProps {
// Mobile breakpoint in pixels
const MOBILE_BREAKPOINT = 640;
type TabType = "issues" | "pulls";
export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubImportModalProps) {
const [owner, setOwner] = useState("");
const [repo, setRepo] = useState("");
const [labels, setLabels] = useState("");
const [loading, setLoading] = useState(false);
// Tab state
const [activeTab, setActiveTab] = useState<TabType>("issues");
// Issues state
const [issues, setIssues] = useState<GitHubIssue[]>([]);
const [selectedIssueNumber, setSelectedIssueNumber] = useState<number | null>(null);
// Pulls state
const [pulls, setPulls] = useState<GitHubPull[]>([]);
const [selectedPullNumber, setSelectedPullNumber] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const [importing, setImporting] = useState(false);
@@ -28,20 +49,26 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
const [loadingRemotes, setLoadingRemotes] = useState(false);
const [selectedRemoteName, setSelectedRemoteName] = useState<string>("");
const mountedRef = useRef(false);
// Mobile view state
const [isMobile, setIsMobile] = useState(false);
const [mobileView, setMobileView] = useState<'list' | 'preview'>('list');
const [mobileView, setMobileView] = useState<"list" | "preview">("list");
// Track which owner/repo we've already auto-loaded to prevent duplicate loads
const autoLoadedRef = useRef<{ owner: string; repo: string; labels: string } | null>(null);
const autoLoadedRef = useRef<{ owner: string; repo: string; labels: string; tab: TabType } | null>(null);
// Build set of already imported URLs from existing tasks
const importedUrls = new Set<string>();
for (const task of tasks) {
const match = task.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);
if (match) {
importedUrls.add(match[1]);
// Check for issue URLs
const issueMatch = task.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);
if (issueMatch) {
importedUrls.add(issueMatch[1]);
}
// Check for PR URLs
const prMatch = task.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);
if (prMatch) {
importedUrls.add(prMatch[1]);
}
}
@@ -53,6 +80,9 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
setLabels("");
setIssues([]);
setSelectedIssueNumber(null);
setPulls([]);
setSelectedPullNumber(null);
setActiveTab("issues");
setError(null);
setImporting(false);
setRemotes([]);
@@ -140,26 +170,56 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
}
}, [owner, repo, labels]);
// Auto-load issues when owner and repo are set and valid
// Handle load pull requests
const handleLoadPulls = useCallback(async () => {
if (!owner.trim() || !repo.trim()) {
setError("Repository must be selected");
return;
}
setLoading(true);
setError(null);
setPulls([]);
setSelectedPullNumber(null);
try {
const fetchedPulls = await apiFetchGitHubPulls(owner.trim(), repo.trim(), 30);
setPulls(fetchedPulls);
if (fetchedPulls.length === 0) {
setError("No open pull requests found");
}
} catch (err: any) {
setError(err.message || "Failed to fetch pull requests");
} finally {
setLoading(false);
}
}, [owner, repo]);
// Auto-load data when owner and repo are set and valid
useEffect(() => {
if (!isOpen) return;
if (!owner.trim() || !repo.trim()) return;
if (loading || importing) return;
// Check if we've already auto-loaded for this exact combination
const currentKey = { owner: owner.trim(), repo: repo.trim(), labels: labels.trim() };
const currentKey = { owner: owner.trim(), repo: repo.trim(), labels: labels.trim(), tab: activeTab };
if (
autoLoadedRef.current?.owner === currentKey.owner &&
autoLoadedRef.current?.repo === currentKey.repo &&
autoLoadedRef.current?.labels === currentKey.labels
autoLoadedRef.current?.labels === currentKey.labels &&
autoLoadedRef.current?.tab === currentKey.tab
) {
return;
}
// Mark as auto-loaded and trigger the load
autoLoadedRef.current = currentKey;
handleLoad();
}, [owner, repo, labels, isOpen, loading, importing, handleLoad]);
if (activeTab === "issues") {
handleLoad();
} else {
handleLoadPulls();
}
}, [owner, repo, labels, activeTab, isOpen, loading, importing, handleLoad, handleLoadPulls]);
// Handle escape key
useEffect(() => {
@@ -195,35 +255,63 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
}
}, [isMobile]);
// Handle pull request selection - switch to preview view on mobile
const handlePullSelect = useCallback((pullNumber: number) => {
setSelectedPullNumber(pullNumber);
if (isMobile) {
setMobileView('preview');
}
}, [isMobile]);
// Handle back button - return to list view on mobile
const handleBackToList = useCallback(() => {
setMobileView('list');
// Optionally clear selection when going back
// setSelectedIssueNumber(null);
}, []);
const handleImport = useCallback(async () => {
if (selectedIssueNumber === null) return;
if (activeTab === "issues") {
if (selectedIssueNumber === null) return;
setImporting(true);
setError(null);
setImporting(true);
setError(null);
try {
const task = await apiImportGitHubIssue(owner.trim(), repo.trim(), selectedIssueNumber);
onImport(task);
onClose();
} catch (err: any) {
if (err.message?.includes("already imported")) {
setError(err.message);
} else {
setError(err.message || "Failed to import issue");
try {
const task = await apiImportGitHubIssue(owner.trim(), repo.trim(), selectedIssueNumber);
onImport(task);
onClose();
} catch (err: any) {
if (err.message?.includes("already imported")) {
setError(err.message);
} else {
setError(err.message || "Failed to import issue");
}
} finally {
setImporting(false);
}
} else {
if (selectedPullNumber === null) return;
setImporting(true);
setError(null);
try {
const task = await apiImportGitHubPull(owner.trim(), repo.trim(), selectedPullNumber);
onImport(task);
onClose();
} catch (err: any) {
if (err.message?.includes("already imported")) {
setError(err.message);
} else {
setError(err.message || "Failed to import pull request");
}
} finally {
setImporting(false);
}
} finally {
setImporting(false);
}
}, [selectedIssueNumber, owner, repo, onImport, onClose]);
}, [activeTab, selectedIssueNumber, selectedPullNumber, owner, repo, onImport, onClose]);
const selectedIssue = issues.find((i) => i.number === selectedIssueNumber);
const selectedPull = pulls.find((p) => p.number === selectedPullNumber);
if (!isOpen) return null;
@@ -231,11 +319,30 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
const hasRemotes = remotes.length > 0;
const singleRemote = remotes.length === 1;
const multipleRemotes = remotes.length > 1;
// Tab-specific counts
const importedIssueCount = issues.filter((issue) => importedUrls.has(issue.html_url)).length;
const isEmptyState = error === "No open issues found";
const isResultsError = Boolean(error) && !isEmptyState && issues.length === 0 && !loading;
const hasResultsContent = loading || issues.length > 0 || isEmptyState || isResultsError;
const showInlineErrorBanner = Boolean(error) && issues.length > 0 && !isEmptyState;
const importedPullCount = pulls.filter((pull) => importedUrls.has(pull.html_url)).length;
// Empty states
const isIssuesEmpty = error === "No open issues found";
const isPullsEmpty = error === "No open pull requests found";
const isEmptyState = activeTab === "issues" ? isIssuesEmpty : isPullsEmpty;
// Results error state
const isIssuesError = Boolean(error) && !isIssuesEmpty && issues.length === 0 && !loading;
const isPullsError = Boolean(error) && !isPullsEmpty && pulls.length === 0 && !loading;
const isResultsError = activeTab === "issues" ? isIssuesError : isPullsError;
// Results content
const hasIssuesContent = loading || issues.length > 0 || isIssuesEmpty || isIssuesError;
const hasPullsContent = loading || pulls.length > 0 || isPullsEmpty || isPullsError;
const hasResultsContent = activeTab === "issues" ? hasIssuesContent : hasPullsContent;
// Inline error
const showIssuesError = Boolean(error) && issues.length > 0 && !isIssuesEmpty;
const showPullsError = Boolean(error) && pulls.length > 0 && !isPullsEmpty;
const showInlineErrorBanner = activeTab === "issues" ? showIssuesError : showPullsError;
return (
<div className="modal-overlay open" onClick={(e) => e.target === e.currentTarget && onClose()}>
@@ -244,7 +351,7 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
<div>
<h3>Import from GitHub</h3>
<p className="github-import-modal__subtitle">
Choose a detected remote, load open issues, and import one into the board.
Choose a detected remote, load open issues or pull requests, and import one into the board.
</p>
</div>
<button className="modal-close" onClick={onClose} aria-label="Close import modal">
@@ -253,6 +360,38 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
</div>
<div className="modal-body github-import-modal__body">
{/* Tab Navigation */}
<div className="github-import-tabs" role="tablist" aria-label="Import type">
<button
role="tab"
aria-selected={activeTab === "issues"}
aria-controls="github-import-list-pane"
className={`github-import-tab ${activeTab === "issues" ? "active" : ""}`}
onClick={() => {
setActiveTab("issues");
setSelectedPullNumber(null);
}}
disabled={loading || importing}
>
<CircleDot size={16} />
<span>Issues</span>
</button>
<button
role="tab"
aria-selected={activeTab === "pulls"}
aria-controls="github-import-list-pane"
className={`github-import-tab ${activeTab === "pulls" ? "active" : ""}`}
onClick={() => {
setActiveTab("pulls");
setSelectedIssueNumber(null);
}}
disabled={loading || importing}
>
<GitPullRequest size={16} />
<span>Pull Requests</span>
</button>
</div>
{/* Compact Toolbar */}
<div className="github-import-toolbar" data-testid="github-import-toolbar" role="toolbar" aria-label="GitHub import controls">
{/* Left: Remote selector */}
@@ -290,19 +429,27 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
)}
</div>
{/* Center: Labels filter */}
{/* Center: Labels filter (only for issues) */}
<div className="github-import-toolbar__zone github-import-toolbar__zone--filter">
<label htmlFor="gh-labels" className="visually-hidden">Filter by labels</label>
<input
id="gh-labels"
type="text"
placeholder="Filter: bug,enhancement…"
value={labels}
onChange={(e) => setLabels(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleLoad()}
disabled={loading || importing || !hasRemotes}
aria-label="Filter issues by labels"
/>
{activeTab === "issues" ? (
<>
<label htmlFor="gh-labels" className="visually-hidden">Filter by labels</label>
<input
id="gh-labels"
type="text"
placeholder="Filter: bug,enhancement…"
value={labels}
onChange={(e) => setLabels(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleLoad()}
disabled={loading || importing || !hasRemotes}
aria-label="Filter issues by labels"
/>
</>
) : (
<span className="github-import-filter-hint">
Open pull requests from {owner || "selected remote"}
</span>
)}
</div>
{/* Right: Load button */}
@@ -310,10 +457,10 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
<button
id="gh-load"
className="btn btn-primary github-import-load-button"
onClick={handleLoad}
onClick={activeTab === "issues" ? handleLoad : handleLoadPulls}
disabled={loading || importing || !owner.trim() || !repo.trim()}
aria-label={loading ? "Loading issues" : "Load issues from repository"}
title={loading ? "Loading…" : "Load issues"}
aria-label={loading ? `Loading ${activeTab}` : `Load ${activeTab} from repository`}
title={loading ? "Loading…" : `Load ${activeTab}`}
>
{loading ? <Loader2 size={14} className="spin" /> : <RefreshCw size={14} />}
<span>{loading ? "Loading…" : "Load"}</span>
@@ -342,20 +489,28 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
{/* Two-pane workspace */}
<div className="github-import-workspace">
{/* Left pane: Issue list */}
{/* Left pane: Issue/PR list */}
<section
className={`github-import-list-pane ${isMobile ? 'mobile' : ''} ${mobileView === 'list' ? 'active' : ''}`}
data-testid="github-import-list-pane"
aria-labelledby="github-import-results-heading"
>
<div className="github-import-pane-header">
<h4 id="github-import-results-heading">Issues</h4>
{issues.length > 0 && (
<h4 id="github-import-results-heading">
{activeTab === "issues" ? "Issues" : "Pull Requests"}
</h4>
{activeTab === "issues" && issues.length > 0 && (
<div className="github-import-results-meta" aria-live="polite">
<span>{issues.length} issue{issues.length === 1 ? "" : "s"}</span>
<span>{importedIssueCount} imported</span>
</div>
)}
{activeTab === "pulls" && pulls.length > 0 && (
<div className="github-import-results-meta" aria-live="polite">
<span>{pulls.length} pull request{pulls.length === 1 ? "" : "s"}</span>
<span>{importedPullCount} imported</span>
</div>
)}
</div>
<div className="github-import-pane-content">
@@ -363,7 +518,7 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
<div className="github-import-state github-import-state--idle" data-testid="github-import-results-idle">
<div>
<strong>Nothing loaded yet</strong>
<span>Select a repository and load issues to start reviewing import candidates.</span>
<span>Select a repository and click Load to start reviewing import candidates.</span>
</div>
</div>
)}
@@ -372,8 +527,8 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
<div className="github-import-state github-import-state--loading" role="status" aria-live="polite">
<Loader2 size={16} className="spin" />
<div>
<strong>Loading open issues</strong>
<span>Fetching the latest issue list from GitHub.</span>
<strong>Loading open {activeTab === "issues" ? "issues" : "pull requests"}</strong>
<span>Fetching the latest list from GitHub.</span>
</div>
</div>
)}
@@ -381,7 +536,7 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
{isResultsError && (
<div className="github-import-state github-import-state--error" role="alert">
<div>
<strong>Could not load issues</strong>
<strong>Could not load {activeTab === "issues" ? "issues" : "pull requests"}</strong>
<span>{error}</span>
</div>
</div>
@@ -390,13 +545,14 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
{isEmptyState && (
<div className="github-import-state github-import-state--empty" role="status">
<div>
<strong>No open issues found</strong>
<span>Try a different label filter or choose another repository.</span>
<strong>No open {activeTab === "issues" ? "issues" : "pull requests"} found</strong>
<span>{activeTab === "issues" ? "Try a different label filter or choose another repository." : "Choose another repository."}</span>
</div>
</div>
)}
{issues.length > 0 && (
{/* Issues list */}
{activeTab === "issues" && issues.length > 0 && (
<div className="issues-list" aria-live="polite">
{issues.map((issue) => {
const isImported = importedUrls.has(issue.html_url);
@@ -435,6 +591,41 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
})}
</div>
)}
{/* Pulls list */}
{activeTab === "pulls" && pulls.length > 0 && (
<div className="issues-list" aria-live="polite">
{pulls.map((pull) => {
const isImported = importedUrls.has(pull.html_url);
return (
<div
key={pull.number}
className={`issue-item ${selectedPullNumber === pull.number ? "selected" : ""} ${isImported ? "imported" : ""}`}
onClick={() => !isImported && handlePullSelect(pull.number)}
>
<input
type="radio"
name="pull"
checked={selectedPullNumber === pull.number}
onChange={() => handlePullSelect(pull.number)}
disabled={isImported}
aria-label={`Select pull request #${pull.number}`}
/>
<div className="issue-main">
<div className="issue-heading-row">
<span className="issue-number">#{pull.number}</span>
<span className="issue-title">{pull.title}</span>
</div>
<span className="pull-branch-info">
{pull.headBranch} {pull.baseBranch}
</span>
</div>
{isImported && <span className="imported-badge">Imported</span>}
</div>
);
})}
</div>
)}
</div>
</section>
@@ -450,7 +641,7 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
className="github-import-back-button"
onClick={handleBackToList}
data-testid="github-import-back-button"
aria-label="Back to issues list"
aria-label={`Back to ${activeTab === "issues" ? "issues" : "pull requests"} list`}
>
<ArrowLeft size={16} />
<span>Back</span>
@@ -460,7 +651,8 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
</div>
<div className="github-import-pane-content">
{selectedIssue ? (
{/* Issue preview */}
{activeTab === "issues" && selectedIssue ? (
<div className="issue-preview" data-testid="github-import-preview-card">
<div className="preview-meta">Issue #{selectedIssue.number}</div>
<div className="preview-title">{selectedIssue.title}</div>
@@ -470,14 +662,37 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
: "(no description)"}
</div>
</div>
) : (
) : activeTab === "issues" ? (
<div className="github-import-state github-import-state--idle" data-testid="github-import-preview-empty">
<div>
<strong>No issue selected</strong>
<span>Choose an issue from the list to inspect its title and description.</span>
</div>
</div>
)}
) : null}
{/* Pull request preview */}
{activeTab === "pulls" && selectedPull ? (
<div className="issue-preview" data-testid="github-import-preview-card">
<div className="preview-meta">Pull Request #{selectedPull.number}</div>
<div className="preview-title">{selectedPull.title}</div>
<div className="preview-branch">
<strong>Branch:</strong> {selectedPull.headBranch} {selectedPull.baseBranch}
</div>
<div className="preview-body">
{selectedPull.body
? selectedPull.body.slice(0, 200) + (selectedPull.body.length > 200 ? "…" : "")
: "(no description)"}
</div>
</div>
) : activeTab === "pulls" ? (
<div className="github-import-state github-import-state--idle" data-testid="github-import-preview-empty">
<div>
<strong>No pull request selected</strong>
<span>Choose a pull request from the list to inspect its details.</span>
</div>
</div>
) : null}
</div>
</section>
</div>
@@ -490,7 +705,9 @@ export function GitHubImportModal({ isOpen, onClose, onImport, tasks }: GitHubIm
<button
className="btn btn-primary"
onClick={handleImport}
disabled={selectedIssueNumber === null || importing}
disabled={
(activeTab === "issues" ? selectedIssueNumber === null : selectedPullNumber === null) || importing
}
>
{importing ? <Loader2 size={14} className="spin" /> : "Import"}
</button>

View File

@@ -1,7 +1,13 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
import { GitHubImportModal } from "../GitHubImportModal";
import { apiFetchGitHubIssues, apiImportGitHubIssue, fetchGitRemotes } from "../../api";
import {
apiFetchGitHubIssues,
apiImportGitHubIssue,
apiFetchGitHubPulls,
apiImportGitHubPull,
fetchGitRemotes,
} from "../../api";
import type { Task } from "@kb/core";
import type { GitRemote } from "../../api";
@@ -12,6 +18,8 @@ vi.mock("../../api", async (importOriginal) => {
...actual,
apiFetchGitHubIssues: vi.fn(),
apiImportGitHubIssue: vi.fn(),
apiFetchGitHubPulls: vi.fn(),
apiImportGitHubPull: vi.fn(),
fetchGitRemotes: vi.fn(),
};
});
@@ -29,6 +37,19 @@ const mockTask: Task = {
updatedAt: "2024-01-01T00:00:00Z",
};
const mockPRTask: Task = {
id: "KB-002",
title: "Review PR #1: Test PR",
description: "Review and address any issues in this pull request.\n\nPR: https://github.com/owner/repo/pull/1\nBranch: feature → main\n\nPR body",
column: "triage",
dependencies: [],
steps: [],
currentStep: 0,
log: [],
createdAt: "2024-01-01T00:00:00Z",
updatedAt: "2024-01-01T00:00:00Z",
};
const singleRemote: GitRemote[] = [
{ name: "origin", owner: "dustinbyrne", repo: "kb", url: "https://github.com/dustinbyrne/kb.git" },
];
@@ -38,6 +59,11 @@ const multipleRemotes: GitRemote[] = [
{ name: "upstream", owner: "upstream", repo: "kb", url: "https://github.com/upstream/kb.git" },
];
const mockPulls = [
{ number: 1, title: "Test PR", body: "PR body", html_url: "https://github.com/owner/repo/pull/1", headBranch: "feature", baseBranch: "main" },
{ number: 2, title: "Another PR", body: "Another PR body", html_url: "https://github.com/owner/repo/pull/2", headBranch: "bugfix", baseBranch: "main" },
];
describe("GitHubImportModal", () => {
const onClose = vi.fn();
const onImport = vi.fn();
@@ -47,8 +73,11 @@ describe("GitHubImportModal", () => {
vi.mocked(fetchGitRemotes).mockReset();
vi.mocked(apiFetchGitHubIssues).mockReset();
vi.mocked(apiImportGitHubIssue).mockReset();
vi.mocked(apiFetchGitHubPulls).mockReset();
vi.mocked(apiImportGitHubPull).mockReset();
// Set default mock for apiFetchGitHubIssues to return empty array (prevents undefined issues state)
vi.mocked(apiFetchGitHubIssues).mockResolvedValue([]);
vi.mocked(apiFetchGitHubPulls).mockResolvedValue([]);
onClose.mockReset();
onImport.mockReset();
});
@@ -583,4 +612,274 @@ describe("GitHubImportModal", () => {
expect(onClose).toHaveBeenCalled();
});
});
// ============================================================================
// PULL REQUEST TAB TESTS
// ============================================================================
describe("PR tab", () => {
it("renders Issues and Pull Requests tabs", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce([]);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
await waitFor(() => {
expect(screen.getByRole("tab", { name: /Issues/i })).toBeTruthy();
expect(screen.getByRole("tab", { name: /Pull Requests/i })).toBeTruthy();
});
});
it("switches to Pull Requests tab when clicked", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
await waitFor(() => {
expect(screen.getByRole("tab", { name: /Pull Requests/i })).toBeTruthy();
});
// Click on Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
// Should show Pull Requests heading
await waitFor(() => {
expect(screen.getByRole("heading", { name: "Pull Requests" })).toBeTruthy();
});
});
it("shows filter input for Issues tab, hint text for Pulls tab", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
await waitFor(() => {
// Default is Issues tab, should show filter input
expect(screen.getByPlaceholderText(/Filter:/)).toBeTruthy();
});
// Click on Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
// Should show hint text instead of filter input
expect(screen.queryByPlaceholderText(/Filter:/)).toBeNull();
expect(screen.getByText(/Open pull requests from/i)).toBeTruthy();
});
});
it("auto-loads pull requests when switching to Pulls tab with remote selected", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
await waitFor(() => {
expect(screen.getByRole("tab", { name: /Pull Requests/i })).toBeTruthy();
});
// Click on Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
// Should auto-load PRs
await waitFor(() => {
expect(apiFetchGitHubPulls).toHaveBeenCalledWith("dustinbyrne", "kb", 30);
expect(screen.getByText("Test PR")).toBeTruthy();
});
});
it("displays PR list with branch info", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Test PR")).toBeTruthy();
// Check for branch info
expect(screen.getByText(/feature → main/)).toBeTruthy();
});
});
it("selects PR and shows preview with branch info", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Test PR")).toBeTruthy();
});
// Select the PR
fireEvent.click(screen.getByRole("radio", { name: /Select pull request #1/i }));
// Preview should show with branch info
const previewCard = await screen.findByTestId("github-import-preview-card");
expect(within(previewCard).getByText("Test PR")).toBeTruthy();
expect(within(previewCard).getByText(/feature → main/)).toBeTruthy();
});
it("disables Import button when no PR is selected", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Test PR")).toBeTruthy();
});
// Import button should be disabled
const importButton = screen.getByRole("button", { name: /Import$/i }) as HTMLButtonElement;
expect(importButton.disabled).toBe(true);
});
it("calls apiImportGitHubPull when Import is clicked on PRs tab", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
vi.mocked(apiImportGitHubPull).mockResolvedValueOnce(mockPRTask);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Test PR")).toBeTruthy();
});
// Select the PR
fireEvent.click(screen.getByRole("radio", { name: /Select pull request #1/i }));
// Click Import
fireEvent.click(screen.getByRole("button", { name: /Import$/i }));
await waitFor(() => {
expect(apiImportGitHubPull).toHaveBeenCalledWith("dustinbyrne", "kb", 1);
expect(onImport).toHaveBeenCalledWith(mockPRTask);
expect(onClose).toHaveBeenCalled();
});
});
it("shows 'Imported' badge for already imported PRs", async () => {
const existingTask: Task = {
...mockPRTask,
description: "Review and address any issues in this pull request.\n\nPR: https://github.com/owner/repo/pull/1",
};
vi.mocked(fetchGitRemotes).mockResolvedValueOnce([{ name: "origin", owner: "owner", repo: "repo", url: "" }]);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[existingTask]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Imported")).toBeTruthy();
});
});
it("disables radio buttons for already imported PRs", async () => {
const existingTask: Task = {
...mockPRTask,
description: "Review and address any issues in this pull request.\n\nPR: https://github.com/owner/repo/pull/1",
};
vi.mocked(fetchGitRemotes).mockResolvedValueOnce([{ name: "origin", owner: "owner", repo: "repo", url: "" }]);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[existingTask]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
const radio = screen.getByRole("radio", { name: /Select pull request #1/i }) as HTMLInputElement;
expect(radio.disabled).toBe(true);
});
});
it("shows empty state when no open pull requests found", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce([]);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("No open pull requests found")).toBeTruthy();
});
});
it("clears selection when switching tabs", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubIssues).mockResolvedValueOnce([
{ number: 1, title: "Issue 1", body: "Body", html_url: "https://github.com/dustinbyrne/kb/issues/1", labels: [] },
]);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Wait for issues to load
await waitFor(() => {
expect(screen.getByText("Issue 1")).toBeTruthy();
});
// Select an issue
fireEvent.click(screen.getByRole("radio", { name: /Select issue #1/i }));
// Verify selection
let previewCard = await screen.findByTestId("github-import-preview-card");
expect(within(previewCard).getByText("Issue 1")).toBeTruthy();
// Switch to PR tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Test PR")).toBeTruthy();
});
// Should show empty preview (issue selection cleared)
previewCard = screen.getByTestId("github-import-preview-empty");
expect(previewCard).toBeTruthy();
});
it("displays error state on PR fetch failure", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockRejectedValueOnce(new Error("Repository not found"));
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
expect(screen.getByText("Could not load pull requests")).toBeTruthy();
expect(screen.getByText("Repository not found")).toBeTruthy();
});
});
it("shows PR count and imported count in header", async () => {
vi.mocked(fetchGitRemotes).mockResolvedValueOnce(singleRemote);
vi.mocked(apiFetchGitHubPulls).mockResolvedValueOnce(mockPulls);
render(<GitHubImportModal isOpen={true} onClose={onClose} onImport={onImport} tasks={[]} />);
// Switch to Pull Requests tab
fireEvent.click(screen.getByRole("tab", { name: /Pull Requests/i }));
await waitFor(() => {
// Should show 2 pull requests, 0 imported
expect(screen.getByText("2 pull requests")).toBeTruthy();
expect(screen.getByText("0 imported")).toBeTruthy();
});
});
});
});

View File

@@ -3023,6 +3023,74 @@ body {
align-items: center;
}
/* Tab styles for GitHub Import Modal */
.github-import-tabs {
display: flex;
gap: var(--space-xs);
padding: var(--space-sm) var(--space-md);
border-bottom: 1px solid var(--border);
background: var(--surface);
}
.github-import-tab {
display: flex;
align-items: center;
gap: var(--space-xs);
padding: var(--space-sm) var(--space-md);
border: 1px solid transparent;
border-radius: var(--radius-md);
background: transparent;
color: var(--text-muted);
font-size: 13px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s ease;
}
.github-import-tab:hover:not(:disabled) {
background: var(--surface-hover);
color: var(--text);
}
.github-import-tab.active {
background: var(--card);
border-color: var(--border);
color: var(--text);
}
.github-import-tab:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.github-import-filter-hint {
color: var(--text-muted);
font-size: 13px;
font-style: italic;
}
.pull-branch-info {
display: block;
margin-top: 2px;
color: var(--text-muted);
font-size: 12px;
font-family: var(--font-mono, monospace);
}
.preview-branch {
margin-bottom: var(--space-sm);
padding: var(--space-sm);
background: var(--surface);
border-radius: var(--radius-sm);
font-size: 12px;
font-family: var(--font-mono, monospace);
}
.preview-branch strong {
color: var(--text-muted);
font-weight: 500;
}
/* Legacy section styles - kept for compatibility */
.github-import-section {
display: flex;

View File

@@ -1705,6 +1705,256 @@ export class GitHubClient {
};
}
/**
* List open pull requests from a repository.
* Uses gh CLI if available, otherwise falls back to REST API.
*/
async listPullRequests(
owner: string,
repo: string,
options?: { limit?: number }
): Promise<Array<{
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
}>> {
if (this.hasGhAuth()) {
try {
return await this.listPullRequestsWithGh(owner, repo, options);
} catch (err) {
if (this.token) {
return this.listPullRequestsWithApi(owner, repo, options);
}
throw new Error(getGhErrorMessage(err));
}
}
if (this.token) {
return this.listPullRequestsWithApi(owner, repo, options);
}
throw new Error("GitHub CLI (gh) is not available or not authenticated, and no GITHUB_TOKEN provided. Run 'gh auth login' to authenticate.");
}
private async listPullRequestsWithGh(
owner: string,
repo: string,
options?: { limit?: number }
): Promise<Array<{
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
}>> {
const limit = options?.limit ?? 30;
const pulls = await runGhJsonAsync<Array<{
number: number;
title: string;
body: string;
url: string;
headRefName: string;
baseRefName: string;
}>>([
"pr", "list",
"--repo", `${owner}/${repo}`,
"--state", "open",
"--limit", String(Math.min(limit, 100)),
"--json", "number,title,body,url,headRefName,baseRefName",
]);
return pulls.map((pr) => ({
number: pr.number,
title: pr.title,
body: pr.body,
html_url: pr.url,
headBranch: pr.headRefName,
baseBranch: pr.baseRefName,
}));
}
private async listPullRequestsWithApi(
owner: string,
repo: string,
options?: { limit?: number }
): Promise<Array<{
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
}>> {
const limit = options?.limit ?? 30;
const params = new URLSearchParams();
params.append("state", "open");
params.append("per_page", String(Math.min(limit, 100)));
const url = `${this.baseUrl}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls?${params}`;
const headers = this.buildHeaders();
const response = await fetch(url, { headers });
if (!response.ok) {
if (response.status === 404) {
throw new Error(`Repository not found: ${owner}/${repo}`);
}
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
}
const data = (await response.json()) as Array<{
number: number;
title: string;
body: string | null;
html_url: string;
head: { ref: string };
base: { ref: string };
}>;
return data.slice(0, limit).map((pr) => ({
number: pr.number,
title: pr.title,
body: pr.body,
html_url: pr.html_url,
headBranch: pr.head.ref,
baseBranch: pr.base.ref,
}));
}
/**
* Fetch a single pull request by number.
* Uses gh CLI if available, otherwise falls back to REST API.
* Returns null if the pull request is not found.
*/
async getPullRequest(
owner: string,
repo: string,
number: number,
): Promise<{
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
state: "open" | "closed" | "merged";
} | null> {
if (this.hasGhAuth()) {
try {
return await this.getPullRequestWithGh(owner, repo, number);
} catch (err) {
if (this.token) {
return this.getPullRequestWithApi(owner, repo, number);
}
throw new Error(getGhErrorMessage(err));
}
}
if (this.token) {
return this.getPullRequestWithApi(owner, repo, number);
}
throw new Error("GitHub CLI (gh) is not available or not authenticated, and no GITHUB_TOKEN provided. Run 'gh auth login' to authenticate.");
}
private async getPullRequestWithGh(
owner: string,
repo: string,
number: number,
): Promise<{
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
state: "open" | "closed" | "merged";
} | null> {
try {
const pr = await runGhJsonAsync<{
number: number;
title: string;
body: string;
url: string;
headRefName: string;
baseRefName: string;
state: "OPEN" | "CLOSED" | "MERGED";
mergedAt?: string | null;
}>([
"pr", "view", String(number),
"--repo", `${owner}/${repo}`,
"--json", "number,title,body,url,headRefName,baseRefName,state,mergedAt",
]);
return {
number: pr.number,
title: pr.title,
body: pr.body,
html_url: pr.url,
headBranch: pr.headRefName,
baseBranch: pr.baseRefName,
state: pr.mergedAt ? "merged" : this.mapGhPrState(pr.state),
};
} catch (err) {
// gh pr view returns error if the PR doesn't exist
if (err instanceof Error && err.message.includes("not found")) {
return null;
}
throw err;
}
}
private async getPullRequestWithApi(
owner: string,
repo: string,
number: number,
): Promise<{
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
state: "open" | "closed" | "merged";
} | null> {
const url = `${this.baseUrl}/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${number}`;
const headers = this.buildHeaders();
const response = await fetch(url, { headers });
if (!response.ok) {
if (response.status === 404) {
return null;
}
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
}
const data = (await response.json()) as {
number: number;
title: string;
body: string | null;
html_url: string;
state: string;
merged: boolean;
head: { ref: string };
base: { ref: string };
};
return {
number: data.number,
title: data.title,
body: data.body,
html_url: data.html_url,
headBranch: data.head.ref,
baseBranch: data.base.ref,
state: data.merged ? "merged" : this.mapPrState(data.state) === "open" ? "open" : "closed",
};
}
// ==========================================
// GitHub App Installation Auth Methods
// ==========================================

View File

@@ -2403,6 +2403,162 @@ export function createApiRoutes(store: TaskStore, options?: ServerOptions): Rout
}
});
/**
* POST /api/github/pulls/fetch
* Fetch open pull requests from a GitHub repository.
* Body: { owner: string, repo: string, limit?: number }
* Returns: Array of GitHubPull objects
*/
router.post("/github/pulls/fetch", async (req, res) => {
try {
const { owner, repo, limit = 30 } = req.body;
if (!owner || typeof owner !== "string") {
res.status(400).json({ error: "owner is required" });
return;
}
if (!repo || typeof repo !== "string") {
res.status(400).json({ error: "repo is required" });
return;
}
// Check gh authentication
if (!isGhAuthenticated()) {
res.status(401).json({
error: "Not authenticated with GitHub. Run `gh auth login`.",
});
return;
}
const client = new GitHubClient();
try {
const pulls = await client.listPullRequests(owner, repo, { limit });
res.json(pulls);
} catch (err: any) {
// Handle specific error cases from gh CLI
const errorMessage = err instanceof Error ? err.message : String(err);
if (errorMessage.includes("not found") || errorMessage.includes("404")) {
res.status(404).json({ error: `Repository not found: ${owner}/${repo}` });
return;
}
if (errorMessage.includes("authentication") || errorMessage.includes("401") || errorMessage.includes("403")) {
res.status(401).json({
error: "Not authenticated with GitHub. Run `gh auth login`.",
});
return;
}
res.status(502).json({ error: `GitHub CLI error: ${errorMessage}` });
}
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
/**
* POST /api/github/pulls/import
* Import a specific GitHub pull request as a kb review task.
* Body: { owner: string, repo: string, prNumber: number }
* Returns: Created Task object
*/
router.post("/github/pulls/import", async (req, res) => {
try {
const { owner, repo, prNumber } = req.body;
if (!owner || typeof owner !== "string") {
res.status(400).json({ error: "owner is required" });
return;
}
if (!repo || typeof repo !== "string") {
res.status(400).json({ error: "repo is required" });
return;
}
if (!prNumber || typeof prNumber !== "number" || prNumber < 1) {
res.status(400).json({ error: "prNumber is required and must be a positive number" });
return;
}
// Check gh authentication
if (!isGhAuthenticated()) {
res.status(401).json({
error: "Not authenticated with GitHub. Run `gh auth login`.",
});
return;
}
const client = new GitHubClient();
let pr: {
number: number;
title: string;
body: string | null;
html_url: string;
headBranch: string;
baseBranch: string;
state: "open" | "closed" | "merged";
} | null;
try {
pr = await client.getPullRequest(owner, repo, prNumber);
if (pr === null) {
res.status(404).json({ error: `PR #${prNumber} not found in ${owner}/${repo}` });
return;
}
} catch (err: any) {
const errorMessage = err instanceof Error ? err.message : String(err);
if (errorMessage.includes("not found") || errorMessage.includes("404")) {
res.status(404).json({ error: `PR #${prNumber} not found in ${owner}/${repo}` });
return;
}
if (errorMessage.includes("authentication") || errorMessage.includes("401") || errorMessage.includes("403")) {
res.status(401).json({
error: "Not authenticated with GitHub. Run `gh auth login`.",
});
return;
}
res.status(502).json({ error: `GitHub CLI error: ${errorMessage}` });
return;
}
// Check if already imported
const existingTasks = await store.listTasks();
const sourceUrl = pr.html_url;
for (const existingTask of existingTasks) {
if (existingTask.description.includes(sourceUrl)) {
res.status(409).json({
error: `PR #${prNumber} already imported as ${existingTask.id}`,
existingTaskId: existingTask.id,
});
return;
}
}
// Create the task with "Review PR:" prefix
const title = `Review PR #${pr.number}: ${pr.title.slice(0, 180)}`;
const body = pr.body?.trim() || "(no description)";
const description = `Review and address any issues in this pull request.\n\nPR: ${sourceUrl}\nBranch: ${pr.headBranch}${pr.baseBranch}\n\n${body}`;
const task = await store.createTask({
title: title || undefined,
description,
column: "triage",
dependencies: [],
});
// Log the import action
await store.logEntry(task.id, "Imported PR from GitHub", sourceUrl);
res.status(201).json(task);
} catch (err: any) {
res.status(500).json({ error: err.message });
}
});
// ---------- Auth routes ----------
registerAuthRoutes(router, options?.authStorage);