Add GitHub integration for PRs, issues and AI PR description (#205)
* feat: integrate GitHub OAuth device flow across runtimes Add GitHub OAuth device flow endpoints across runtimes Introduce GitHubSettings UI panel and sidebar entry Persist GitHub auth state in per-runtime storage * feat: add GitHub PR status and PR description generation Show PR status for the current branch in the Git view Generate a pull request description from the diff between base and head Expose prStatus, prCreate, and prMerge APIs in web and desktop clients * feat: add GitHub PR ready for review Add API to mark pull requests as ready for review Show a Ready button for draft PRs and reflect status in UI Handle token expiration and GraphQL errors when marking ready
This commit is contained in:
committed by
GitHub
parent
0e715be7d6
commit
463e9ec4e3
@@ -0,0 +1,332 @@
|
||||
import React from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { toast } from 'sonner';
|
||||
import { getRegisteredRuntimeAPIs } from '@/contexts/runtimeAPIRegistry';
|
||||
import { RiGithubFill } from '@remixicon/react';
|
||||
|
||||
type GitHubUser = {
|
||||
login: string;
|
||||
id?: number;
|
||||
avatarUrl?: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
type AuthStatusResponse = {
|
||||
connected: boolean;
|
||||
user?: GitHubUser | null;
|
||||
scope?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type DeviceFlowStartResponse = {
|
||||
deviceCode: string;
|
||||
userCode: string;
|
||||
verificationUri: string;
|
||||
verificationUriComplete?: string;
|
||||
expiresIn: number;
|
||||
interval: number;
|
||||
scope?: string;
|
||||
};
|
||||
|
||||
type DeviceFlowCompleteResponse =
|
||||
| { connected: true; user: GitHubUser; scope?: string }
|
||||
| { connected: false; status?: string; error?: string };
|
||||
|
||||
export const GitHubSettings: React.FC = () => {
|
||||
const runtimeGitHub = getRegisteredRuntimeAPIs()?.github;
|
||||
|
||||
const openExternal = React.useCallback(async (url: string) => {
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const desktop = (window as typeof window & { opencodeDesktop?: { openExternal?: (url: string) => Promise<unknown> } }).opencodeDesktop;
|
||||
if (desktop?.openExternal) {
|
||||
try {
|
||||
await desktop.openExternal(url);
|
||||
return;
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}, []);
|
||||
|
||||
const [isLoading, setIsLoading] = React.useState(true);
|
||||
const [isBusy, setIsBusy] = React.useState(false);
|
||||
const [status, setStatus] = React.useState<AuthStatusResponse | null>(null);
|
||||
const [flow, setFlow] = React.useState<DeviceFlowStartResponse | null>(null);
|
||||
const [pollIntervalMs, setPollIntervalMs] = React.useState<number | null>(null);
|
||||
const pollTimerRef = React.useRef<number | null>(null);
|
||||
|
||||
const stopPolling = React.useCallback(() => {
|
||||
if (pollTimerRef.current != null) {
|
||||
window.clearInterval(pollTimerRef.current);
|
||||
pollTimerRef.current = null;
|
||||
}
|
||||
setPollIntervalMs(null);
|
||||
}, []);
|
||||
|
||||
const refreshStatus = React.useCallback(async () => {
|
||||
if (runtimeGitHub) {
|
||||
const payload = await runtimeGitHub.authStatus();
|
||||
setStatus(payload as AuthStatusResponse);
|
||||
return payload as AuthStatusResponse;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/github/auth/status', {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
const payload = (await response.json().catch(() => null)) as AuthStatusResponse | null;
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error(payload?.error || response.statusText || 'Failed to load GitHub status');
|
||||
}
|
||||
setStatus(payload);
|
||||
return payload;
|
||||
}, [runtimeGitHub]);
|
||||
|
||||
React.useEffect(() => {
|
||||
let mounted = true;
|
||||
(async () => {
|
||||
try {
|
||||
await refreshStatus();
|
||||
} catch (error) {
|
||||
console.warn('Failed to load GitHub auth status:', error);
|
||||
} finally {
|
||||
if (mounted) setIsLoading(false);
|
||||
}
|
||||
})();
|
||||
return () => {
|
||||
mounted = false;
|
||||
stopPolling();
|
||||
};
|
||||
}, [refreshStatus, stopPolling]);
|
||||
|
||||
const startConnect = React.useCallback(async () => {
|
||||
setIsBusy(true);
|
||||
try {
|
||||
const payload = runtimeGitHub
|
||||
? await runtimeGitHub.authStart()
|
||||
: await (async () => {
|
||||
const response = await fetch('/api/github/auth/start', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const body = (await response.json().catch(() => null)) as DeviceFlowStartResponse | { error?: string } | null;
|
||||
if (!response.ok || !body || !('deviceCode' in body)) {
|
||||
throw new Error((body as { error?: string } | null)?.error || response.statusText);
|
||||
}
|
||||
return body;
|
||||
})();
|
||||
|
||||
setFlow(payload);
|
||||
setPollIntervalMs(Math.max(1, payload.interval) * 1000);
|
||||
|
||||
const url = payload.verificationUriComplete || payload.verificationUri;
|
||||
void openExternal(url);
|
||||
} catch (error) {
|
||||
console.error('Failed to start GitHub connect:', error);
|
||||
toast.error('Failed to start GitHub connect');
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
}
|
||||
}, [openExternal, runtimeGitHub]);
|
||||
|
||||
const pollOnce = React.useCallback(async (deviceCode: string) => {
|
||||
if (runtimeGitHub) {
|
||||
return runtimeGitHub.authComplete(deviceCode) as Promise<DeviceFlowCompleteResponse>;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/github/auth/complete', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ deviceCode }),
|
||||
});
|
||||
|
||||
const payload = (await response.json().catch(() => null)) as DeviceFlowCompleteResponse | { error?: string } | null;
|
||||
if (!response.ok || !payload) {
|
||||
throw new Error((payload as { error?: string } | null)?.error || response.statusText);
|
||||
}
|
||||
return payload as DeviceFlowCompleteResponse;
|
||||
}, [runtimeGitHub]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!flow?.deviceCode || !pollIntervalMs) {
|
||||
return;
|
||||
}
|
||||
if (pollTimerRef.current != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
pollTimerRef.current = window.setInterval(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const result = await pollOnce(flow.deviceCode);
|
||||
if (result.connected) {
|
||||
toast.success('GitHub connected');
|
||||
setFlow(null);
|
||||
stopPolling();
|
||||
await refreshStatus();
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === 'slow_down') {
|
||||
setPollIntervalMs((prev) => (prev ? prev + 5000 : 5000));
|
||||
}
|
||||
|
||||
if (result.status === 'expired_token' || result.status === 'access_denied') {
|
||||
toast.error(result.error || 'GitHub authorization failed');
|
||||
setFlow(null);
|
||||
stopPolling();
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('GitHub polling failed:', error);
|
||||
}
|
||||
})();
|
||||
}, pollIntervalMs);
|
||||
|
||||
return () => {
|
||||
if (pollTimerRef.current != null) {
|
||||
window.clearInterval(pollTimerRef.current);
|
||||
pollTimerRef.current = null;
|
||||
}
|
||||
};
|
||||
}, [flow, pollIntervalMs, pollOnce, refreshStatus, stopPolling]);
|
||||
|
||||
const disconnect = React.useCallback(async () => {
|
||||
setIsBusy(true);
|
||||
try {
|
||||
stopPolling();
|
||||
setFlow(null);
|
||||
if (runtimeGitHub) {
|
||||
await runtimeGitHub.authDisconnect();
|
||||
} else {
|
||||
const response = await fetch('/api/github/auth', {
|
||||
method: 'DELETE',
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(response.statusText);
|
||||
}
|
||||
}
|
||||
toast.success('GitHub disconnected');
|
||||
await refreshStatus();
|
||||
} catch (error) {
|
||||
console.error('Failed to disconnect GitHub:', error);
|
||||
toast.error('Failed to disconnect GitHub');
|
||||
} finally {
|
||||
setIsBusy(false);
|
||||
}
|
||||
}, [refreshStatus, stopPolling, runtimeGitHub]);
|
||||
|
||||
if (isLoading) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const connected = Boolean(status?.connected);
|
||||
const user = status?.user;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<div className="space-y-1">
|
||||
<h3 className="typography-ui-header font-semibold text-foreground">GitHub</h3>
|
||||
<p className="typography-meta text-muted-foreground">
|
||||
Connect a GitHub account for in-app PR and issue workflows.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{connected ? (
|
||||
<div className="flex items-center justify-between gap-4 rounded-lg border bg-background/50 px-4 py-3">
|
||||
<div className="flex min-w-0 items-center gap-4">
|
||||
{user?.avatarUrl ? (
|
||||
<img
|
||||
src={user.avatarUrl}
|
||||
alt={user.login ? `${user.login} avatar` : 'GitHub avatar'}
|
||||
className="h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted object-cover"
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-14 w-14 shrink-0 rounded-full border border-border/60 bg-muted" />
|
||||
)}
|
||||
|
||||
<div className="min-w-0">
|
||||
<div className="typography-ui-header font-semibold text-foreground truncate">
|
||||
{user?.name?.trim() || user?.login || 'GitHub'}
|
||||
</div>
|
||||
{user?.email ? (
|
||||
<div className="typography-body text-muted-foreground truncate">{user.email}</div>
|
||||
) : null}
|
||||
<div className="mt-1 flex items-center gap-2 typography-meta text-muted-foreground truncate">
|
||||
<RiGithubFill className="h-4 w-4" />
|
||||
<span className="font-mono">{user?.login || 'unknown'}</span>
|
||||
</div>
|
||||
{status?.scope ? (
|
||||
<div className="typography-micro text-muted-foreground truncate">Scopes: {status.scope}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Button variant="outline" onClick={disconnect} disabled={isBusy}>
|
||||
Disconnect
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center justify-between gap-3 rounded-lg border bg-background/50 px-3 py-2">
|
||||
<div className="typography-ui-label text-foreground">Not connected</div>
|
||||
<Button onClick={startConnect} disabled={isBusy}>
|
||||
Connect
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{flow ? (
|
||||
<div className="space-y-3 rounded-lg border bg-background/50 p-3">
|
||||
<div className="space-y-1">
|
||||
<div className="typography-ui-label text-foreground">Authorize OpenChamber</div>
|
||||
<div className="typography-meta text-muted-foreground">
|
||||
In GitHub, enter this code:
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<div className="font-mono text-lg tracking-widest text-foreground">{flow.userCode}</div>
|
||||
<Button variant="outline" asChild>
|
||||
<a
|
||||
href={flow.verificationUriComplete || flow.verificationUri}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Open GitHub
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="typography-micro text-muted-foreground">
|
||||
Waiting for approval… (auto-refresh)
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<Button variant="ghost" disabled={isBusy} onClick={() => {
|
||||
stopPolling();
|
||||
setFlow(null);
|
||||
}}>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -7,6 +7,7 @@ import { DefaultsSettings } from './DefaultsSettings';
|
||||
import { GitSettings } from './GitSettings';
|
||||
import { WorktreeSectionContent } from './WorktreeSectionContent';
|
||||
import { NotificationSettings } from './NotificationSettings';
|
||||
import { GitHubSettings } from './GitHubSettings';
|
||||
import { ScrollableOverlay } from '@/components/ui/ScrollableOverlay';
|
||||
import { useDeviceInfo } from '@/lib/device';
|
||||
import { isWebRuntime } from '@/lib/desktop';
|
||||
@@ -56,6 +57,8 @@ export const OpenChamberPage: React.FC<OpenChamberPageProps> = ({ section }) =>
|
||||
return <SessionsSectionContent />;
|
||||
case 'git':
|
||||
return <GitSectionContent />;
|
||||
case 'github':
|
||||
return <GitHubSectionContent />;
|
||||
case 'notifications':
|
||||
return <NotificationSectionContent />;
|
||||
default:
|
||||
@@ -117,6 +120,11 @@ const GitSectionContent: React.FC = () => {
|
||||
);
|
||||
};
|
||||
|
||||
// GitHub section: Connect account for PR/issue workflows
|
||||
const GitHubSectionContent: React.FC = () => {
|
||||
return <GitHubSettings />;
|
||||
};
|
||||
|
||||
// Notifications section: Native browser notifications
|
||||
const NotificationSectionContent: React.FC = () => {
|
||||
return <NotificationSettings />;
|
||||
|
||||
@@ -5,7 +5,7 @@ import { isVSCodeRuntime, isWebRuntime } from '@/lib/desktop';
|
||||
import { AboutSettings } from './AboutSettings';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
export type OpenChamberSection = 'visual' | 'chat' | 'sessions' | 'git' | 'notifications';
|
||||
export type OpenChamberSection = 'visual' | 'chat' | 'sessions' | 'git' | 'github' | 'notifications';
|
||||
|
||||
interface OpenChamberSidebarProps {
|
||||
selectedSection: OpenChamberSection;
|
||||
@@ -42,6 +42,11 @@ const OPENCHAMBER_SECTION_GROUPS: SectionGroup[] = [
|
||||
items: ['Commit Messages', 'Worktree'],
|
||||
hideInVSCode: true,
|
||||
},
|
||||
{
|
||||
id: 'github',
|
||||
label: 'GitHub',
|
||||
items: ['Connect', 'PRs', 'Issues'],
|
||||
},
|
||||
{
|
||||
id: 'notifications',
|
||||
label: 'Notifications',
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useFireworksCelebration } from '@/contexts/FireworksContext';
|
||||
import type { GitIdentityProfile, CommitFileEntry } from '@/lib/api/types';
|
||||
import { useGitIdentitiesStore } from '@/stores/useGitIdentitiesStore';
|
||||
import { useDirectoryStore } from '@/stores/useDirectoryStore';
|
||||
import { useProjectsStore } from '@/stores/useProjectsStore';
|
||||
import {
|
||||
useGitStore,
|
||||
useGitStatus,
|
||||
@@ -39,6 +40,7 @@ import { GitEmptyState } from './git/GitEmptyState';
|
||||
import { ChangesSection } from './git/ChangesSection';
|
||||
import { CommitSection } from './git/CommitSection';
|
||||
import { HistorySection } from './git/HistorySection';
|
||||
import { PullRequestSection } from './git/PullRequestSection';
|
||||
|
||||
type SyncAction = 'fetch' | 'pull' | 'push' | null;
|
||||
type CommitAction = 'commit' | 'commitAndPush' | null;
|
||||
@@ -231,6 +233,15 @@ export const GitView: React.FC = () => {
|
||||
|
||||
const settingsGitmojiEnabled = useConfigStore((state) => state.settingsGitmojiEnabled);
|
||||
|
||||
const activeProject = useProjectsStore((state) => state.getActiveProject());
|
||||
const baseBranch = React.useMemo(() => {
|
||||
const fromProject = activeProject?.worktreeDefaults?.baseBranch;
|
||||
if (typeof fromProject === 'string' && fromProject.trim().length > 0) {
|
||||
return fromProject.trim();
|
||||
}
|
||||
return 'main';
|
||||
}, [activeProject?.worktreeDefaults?.baseBranch]);
|
||||
|
||||
const [commitMessage, setCommitMessage] = React.useState(
|
||||
initialSnapshot?.commitMessage ?? ''
|
||||
);
|
||||
@@ -1038,6 +1049,14 @@ export const GitView: React.FC = () => {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{currentDirectory && status?.current ? (
|
||||
<PullRequestSection
|
||||
directory={currentDirectory}
|
||||
branch={status.current}
|
||||
baseBranch={baseBranch}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{/* History below, constrained width */}
|
||||
<HistorySection
|
||||
log={log}
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
} from '@/components/ui/collapsible';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ButtonLarge } from '@/components/ui/button-large';
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { CommitInput } from './CommitInput';
|
||||
import { AIHighlightsBox } from './AIHighlightsBox';
|
||||
|
||||
@@ -97,32 +96,25 @@ export const CommitSection: React.FC<CommitSectionProps> = ({
|
||||
)}
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Tooltip delayDuration={1000}>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="h-8 w-8"
|
||||
onClick={onGenerateMessage}
|
||||
disabled={
|
||||
isGeneratingMessage ||
|
||||
commitAction !== null ||
|
||||
selectedCount === 0 ||
|
||||
isBusy
|
||||
}
|
||||
aria-label="Generate commit message"
|
||||
>
|
||||
{isGeneratingMessage ? (
|
||||
<RiLoader4Line className="size-4 animate-spin" />
|
||||
) : (
|
||||
<RiAiGenerate2 className="size-4 text-primary" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent sideOffset={8}>
|
||||
Generate commit message with AI
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={onGenerateMessage}
|
||||
disabled={
|
||||
isGeneratingMessage ||
|
||||
commitAction !== null ||
|
||||
selectedCount === 0 ||
|
||||
isBusy
|
||||
}
|
||||
type="button"
|
||||
>
|
||||
{isGeneratingMessage ? (
|
||||
<RiLoader4Line className="size-4 animate-spin" />
|
||||
) : (
|
||||
<RiAiGenerate2 className="size-4 text-primary" />
|
||||
)}
|
||||
Generate
|
||||
</Button>
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
|
||||
@@ -0,0 +1,440 @@
|
||||
import React from 'react';
|
||||
import {
|
||||
RiAiGenerate2,
|
||||
RiCheckboxBlankLine,
|
||||
RiCheckboxLine,
|
||||
RiExternalLinkLine,
|
||||
RiGitPullRequestLine,
|
||||
RiLoader4Line,
|
||||
} from '@remixicon/react';
|
||||
import { toast } from '@/components/ui';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
Collapsible,
|
||||
CollapsibleContent,
|
||||
CollapsibleTrigger,
|
||||
} from '@/components/ui/collapsible';
|
||||
import { generatePullRequestDescription } from '@/lib/gitApi';
|
||||
import { useRuntimeAPIs } from '@/hooks/useRuntimeAPIs';
|
||||
import type {
|
||||
GitHubPullRequest,
|
||||
GitHubPullRequestStatus,
|
||||
} from '@/lib/api/types';
|
||||
|
||||
type MergeMethod = 'merge' | 'squash' | 'rebase';
|
||||
|
||||
const statusColor = (state: string | undefined | null): string => {
|
||||
switch (state) {
|
||||
case 'success':
|
||||
return 'bg-[color:var(--status-success)]';
|
||||
case 'failure':
|
||||
return 'bg-[color:var(--status-error)]';
|
||||
case 'pending':
|
||||
return 'bg-[color:var(--status-warning)]';
|
||||
default:
|
||||
return 'bg-muted-foreground/40';
|
||||
}
|
||||
};
|
||||
|
||||
const branchToTitle = (branch: string): string => {
|
||||
return branch
|
||||
.replace(/^refs\/heads\//, '')
|
||||
.replace(/[-_]+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
};
|
||||
|
||||
const openExternal = async (url: string) => {
|
||||
if (typeof window === 'undefined') return;
|
||||
const desktop = (window as typeof window & { opencodeDesktop?: { openExternal?: (url: string) => Promise<unknown> } }).opencodeDesktop;
|
||||
if (desktop?.openExternal) {
|
||||
try {
|
||||
await desktop.openExternal(url);
|
||||
return;
|
||||
} catch {
|
||||
// fall through
|
||||
}
|
||||
}
|
||||
try {
|
||||
window.open(url, '_blank', 'noopener,noreferrer');
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
export const PullRequestSection: React.FC<{
|
||||
directory: string;
|
||||
branch: string;
|
||||
baseBranch: string;
|
||||
}> = ({ directory, branch, baseBranch }) => {
|
||||
const { github } = useRuntimeAPIs();
|
||||
|
||||
const [isOpen, setIsOpen] = React.useState(true);
|
||||
const [isLoading, setIsLoading] = React.useState(false);
|
||||
const [status, setStatus] = React.useState<GitHubPullRequestStatus | null>(null);
|
||||
const [error, setError] = React.useState<string | null>(null);
|
||||
|
||||
const [title, setTitle] = React.useState(() => branchToTitle(branch));
|
||||
const [body, setBody] = React.useState('');
|
||||
const [draft, setDraft] = React.useState(false);
|
||||
const [mergeMethod, setMergeMethod] = React.useState<MergeMethod>('squash');
|
||||
|
||||
const [isGenerating, setIsGenerating] = React.useState(false);
|
||||
const [isCreating, setIsCreating] = React.useState(false);
|
||||
const [isMerging, setIsMerging] = React.useState(false);
|
||||
const [isMarkingReady, setIsMarkingReady] = React.useState(false);
|
||||
|
||||
const canShow = Boolean(directory && branch && baseBranch && branch !== baseBranch);
|
||||
|
||||
const refresh = React.useCallback(async () => {
|
||||
if (!canShow) return;
|
||||
if (!github?.prStatus) {
|
||||
setStatus(null);
|
||||
setError('GitHub runtime API unavailable');
|
||||
return;
|
||||
}
|
||||
setIsLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const next = await github.prStatus(directory, branch);
|
||||
setStatus(next);
|
||||
if (next.connected === false) {
|
||||
setError(null);
|
||||
}
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
setError(message || 'Failed to load PR status');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [branch, canShow, directory, github]);
|
||||
|
||||
React.useEffect(() => {
|
||||
setTitle(branchToTitle(branch));
|
||||
setBody('');
|
||||
setDraft(false);
|
||||
void refresh();
|
||||
}, [branch, refresh]);
|
||||
|
||||
const generateDescription = React.useCallback(async () => {
|
||||
if (isGenerating) return;
|
||||
if (!directory) return;
|
||||
setIsGenerating(true);
|
||||
try {
|
||||
const generated = await generatePullRequestDescription(directory, {
|
||||
base: baseBranch,
|
||||
head: branch,
|
||||
});
|
||||
|
||||
if (generated.title?.trim()) {
|
||||
setTitle(generated.title.trim());
|
||||
}
|
||||
if (generated.body?.trim()) {
|
||||
setBody(generated.body.trim());
|
||||
}
|
||||
toast.success('PR description generated');
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
toast.error('Failed to generate description', { description: message });
|
||||
} finally {
|
||||
setIsGenerating(false);
|
||||
}
|
||||
}, [baseBranch, branch, directory, isGenerating]);
|
||||
|
||||
const createPr = React.useCallback(async () => {
|
||||
if (!github?.prCreate) {
|
||||
toast.error('GitHub runtime API unavailable');
|
||||
return;
|
||||
}
|
||||
const trimmedTitle = title.trim();
|
||||
if (!trimmedTitle) {
|
||||
toast.error('Title is required');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsCreating(true);
|
||||
try {
|
||||
const pr = await github.prCreate({
|
||||
directory,
|
||||
title: trimmedTitle,
|
||||
head: branch,
|
||||
base: baseBranch,
|
||||
...(body.trim() ? { body } : {}),
|
||||
draft,
|
||||
});
|
||||
toast.success('PR created');
|
||||
setStatus((prev) => (prev ? { ...prev, pr } : prev));
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
toast.error('Failed to create PR', { description: message });
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
}, [baseBranch, body, branch, directory, draft, github, refresh, title]);
|
||||
|
||||
const mergePr = React.useCallback(async (pr: GitHubPullRequest) => {
|
||||
if (!github?.prMerge) {
|
||||
toast.error('GitHub runtime API unavailable');
|
||||
return;
|
||||
}
|
||||
setIsMerging(true);
|
||||
try {
|
||||
const result = await github.prMerge({ directory, number: pr.number, method: mergeMethod });
|
||||
if (result.merged) {
|
||||
toast.success('PR merged');
|
||||
} else {
|
||||
toast.message('PR not merged', { description: result.message || 'Not mergeable' });
|
||||
}
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
toast.error('Merge failed', { description: message });
|
||||
if (pr.url) {
|
||||
void openExternal(pr.url);
|
||||
}
|
||||
} finally {
|
||||
setIsMerging(false);
|
||||
}
|
||||
}, [directory, github, mergeMethod, refresh]);
|
||||
|
||||
const markReady = React.useCallback(async (pr: GitHubPullRequest) => {
|
||||
if (!github?.prReady) {
|
||||
toast.error('GitHub runtime API unavailable');
|
||||
return;
|
||||
}
|
||||
setIsMarkingReady(true);
|
||||
try {
|
||||
await github.prReady({ directory, number: pr.number });
|
||||
toast.success('Marked ready for review');
|
||||
await refresh();
|
||||
} catch (e) {
|
||||
const message = e instanceof Error ? e.message : String(e);
|
||||
toast.error('Failed to mark ready', { description: message });
|
||||
if (pr.url) {
|
||||
void openExternal(pr.url);
|
||||
}
|
||||
} finally {
|
||||
setIsMarkingReady(false);
|
||||
}
|
||||
}, [directory, github, refresh]);
|
||||
|
||||
if (!canShow) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pr = status?.pr ?? null;
|
||||
const repoUrl = status?.repo?.url || null;
|
||||
const checks = status?.checks ?? null;
|
||||
const canMerge = Boolean(status?.canMerge);
|
||||
const isConnected = Boolean(status?.connected);
|
||||
|
||||
return (
|
||||
<Collapsible
|
||||
open={isOpen}
|
||||
onOpenChange={setIsOpen}
|
||||
className="rounded-xl border border-border/60 bg-background/70 overflow-hidden"
|
||||
>
|
||||
<CollapsibleTrigger className="flex w-full items-center justify-between px-3 h-10 hover:bg-transparent">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<RiGitPullRequestLine className="size-4 text-muted-foreground" />
|
||||
<h3 className="typography-ui-header font-semibold text-foreground truncate">Pull Request</h3>
|
||||
{pr ? (
|
||||
<span className="typography-meta text-muted-foreground truncate">#{pr.number}</span>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isLoading ? <RiLoader4Line className="size-4 animate-spin text-muted-foreground" /> : null}
|
||||
{checks ? (
|
||||
<span className="inline-flex items-center gap-2 typography-micro text-muted-foreground">
|
||||
<span className={`h-2 w-2 rounded-full ${statusColor(checks.state)}`} />
|
||||
{checks.total > 0 ? `${checks.success}/${checks.total}` : checks.state}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</CollapsibleTrigger>
|
||||
|
||||
<CollapsibleContent>
|
||||
<div className="border-t border-border/40">
|
||||
<div className="flex flex-col gap-3 p-3">
|
||||
{!isConnected ? (
|
||||
<div className="typography-meta text-muted-foreground">
|
||||
GitHub not connected. Connect in Settings to create and merge PRs.
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? (
|
||||
<div className="space-y-2">
|
||||
<div className="typography-ui-label text-foreground">PR status unavailable</div>
|
||||
<div className="typography-meta text-muted-foreground break-words">{error}</div>
|
||||
{repoUrl ? (
|
||||
<Button variant="outline" size="sm" asChild className="w-fit">
|
||||
<a href={repoUrl} target="_blank" rel="noopener noreferrer">
|
||||
<RiExternalLinkLine className="size-4" />
|
||||
Open Repo
|
||||
</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{pr ? (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="typography-ui-label text-foreground truncate">{pr.title}</div>
|
||||
<div className="typography-micro text-muted-foreground truncate">
|
||||
{pr.state}{pr.draft ? ' (draft)' : ''}
|
||||
{pr.mergeable === false ? ' · not mergeable' : ''}
|
||||
{typeof pr.mergeableState === 'string' && pr.mergeableState ? ` · ${pr.mergeableState}` : ''}
|
||||
</div>
|
||||
{canMerge && pr.draft ? (
|
||||
<div className="typography-micro text-muted-foreground">
|
||||
Draft PRs must be marked ready before merge.
|
||||
</div>
|
||||
) : null}
|
||||
{!canMerge ? (
|
||||
<div className="typography-micro text-muted-foreground">No merge permission; use Open in GitHub.</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={pr.url} target="_blank" rel="noopener noreferrer">
|
||||
<RiExternalLinkLine className="size-4" />
|
||||
Open
|
||||
</a>
|
||||
</Button>
|
||||
{canMerge && pr.draft && pr.state === 'open' ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => markReady(pr)}
|
||||
disabled={isMarkingReady || isMerging}
|
||||
>
|
||||
{isMarkingReady ? <RiLoader4Line className="size-4 animate-spin" /> : null}
|
||||
Ready
|
||||
</Button>
|
||||
) : null}
|
||||
{canMerge ? (
|
||||
<>
|
||||
<select
|
||||
className="h-8 rounded-md border border-border bg-background px-2 typography-meta"
|
||||
value={mergeMethod}
|
||||
onChange={(e) => setMergeMethod(e.target.value as MergeMethod)}
|
||||
disabled={isMerging || pr.state !== 'open'}
|
||||
>
|
||||
<option value="squash">Squash</option>
|
||||
<option value="merge">Merge</option>
|
||||
<option value="rebase">Rebase</option>
|
||||
</select>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => mergePr(pr)}
|
||||
disabled={isMerging || isMarkingReady || pr.state !== 'open' || pr.draft}
|
||||
>
|
||||
{isMerging ? <RiLoader4Line className="size-4 animate-spin" /> : null}
|
||||
Merge
|
||||
</Button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="min-w-0">
|
||||
<div className="typography-ui-label text-foreground">Create PR</div>
|
||||
<div className="typography-micro text-muted-foreground truncate">
|
||||
{branch} → {baseBranch}
|
||||
</div>
|
||||
</div>
|
||||
{repoUrl ? (
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<a href={repoUrl} target="_blank" rel="noopener noreferrer">
|
||||
<RiExternalLinkLine className="size-4" />
|
||||
Repo
|
||||
</a>
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<label className="space-y-1">
|
||||
<div className="typography-micro text-muted-foreground">Title</div>
|
||||
<Input
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="PR title"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="space-y-1">
|
||||
<div className="typography-micro text-muted-foreground">Description</div>
|
||||
<Textarea
|
||||
value={body}
|
||||
onChange={(e) => setBody(e.target.value)}
|
||||
className="min-h-[110px] bg-background/80"
|
||||
placeholder="What changed and why"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<div
|
||||
className="flex items-center gap-2 cursor-pointer"
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
aria-pressed={draft}
|
||||
onClick={() => setDraft((v) => !v)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === ' ' || e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
setDraft((v) => !v);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setDraft((v) => !v);
|
||||
}}
|
||||
aria-label="Toggle draft PR"
|
||||
className="flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
||||
>
|
||||
{draft ? (
|
||||
<RiCheckboxLine className="size-4 text-primary" />
|
||||
) : (
|
||||
<RiCheckboxBlankLine className="size-4" />
|
||||
)}
|
||||
</button>
|
||||
<span className="typography-ui-label text-foreground select-none">Draft</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={generateDescription}
|
||||
disabled={isGenerating || isCreating}
|
||||
>
|
||||
{isGenerating ? <RiLoader4Line className="size-4 animate-spin" /> : <RiAiGenerate2 className="size-4 text-primary" />}
|
||||
Generate
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<Button size="sm" onClick={createPr} disabled={isCreating || !isConnected}>
|
||||
{isCreating ? <RiLoader4Line className="size-4 animate-spin" /> : null}
|
||||
Create PR
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
);
|
||||
};
|
||||
@@ -269,6 +269,11 @@ export interface GeneratedCommitMessage {
|
||||
highlights: string[];
|
||||
}
|
||||
|
||||
export interface GeneratedPullRequestDescription {
|
||||
title: string;
|
||||
body: string;
|
||||
}
|
||||
|
||||
export interface GitAPI {
|
||||
checkIsGitRepository(directory: string): Promise<boolean>;
|
||||
getGitStatus(directory: string): Promise<GitStatus>;
|
||||
@@ -280,6 +285,10 @@ export interface GitAPI {
|
||||
deleteGitBranch(directory: string, payload: GitDeleteBranchPayload): Promise<{ success: boolean }>;
|
||||
deleteRemoteBranch(directory: string, payload: GitDeleteRemoteBranchPayload): Promise<{ success: boolean }>;
|
||||
generateCommitMessage(directory: string, files: string[]): Promise<{ message: GeneratedCommitMessage }>;
|
||||
generatePullRequestDescription(
|
||||
directory: string,
|
||||
payload: { base: string; head: string }
|
||||
): Promise<GeneratedPullRequestDescription>;
|
||||
listGitWorktrees(directory: string): Promise<GitWorktreeInfo[]>;
|
||||
addGitWorktree(directory: string, payload: GitAddWorktreePayload): Promise<{ success: boolean; path: string; branch: string }>;
|
||||
removeGitWorktree(directory: string, payload: GitRemoveWorktreePayload): Promise<{ success: boolean }>;
|
||||
@@ -478,6 +487,112 @@ export interface PushAPI {
|
||||
setVisibility(payload: { visible: boolean }): Promise<{ ok: true } | null>;
|
||||
}
|
||||
|
||||
export type GitHubUserSummary = {
|
||||
login: string;
|
||||
id?: number;
|
||||
avatarUrl?: string;
|
||||
name?: string;
|
||||
email?: string;
|
||||
};
|
||||
|
||||
export type GitHubRepoRef = {
|
||||
owner: string;
|
||||
repo: string;
|
||||
url: string;
|
||||
};
|
||||
|
||||
export type GitHubChecksSummary = {
|
||||
state: 'success' | 'failure' | 'pending' | 'unknown';
|
||||
total: number;
|
||||
success: number;
|
||||
failure: number;
|
||||
pending: number;
|
||||
};
|
||||
|
||||
export type GitHubPullRequest = {
|
||||
number: number;
|
||||
title: string;
|
||||
url: string;
|
||||
state: 'open' | 'closed' | 'merged';
|
||||
draft: boolean;
|
||||
base: string;
|
||||
head: string;
|
||||
headSha?: string;
|
||||
mergeable?: boolean | null;
|
||||
mergeableState?: string | null;
|
||||
};
|
||||
|
||||
export type GitHubPullRequestStatus = {
|
||||
connected: boolean;
|
||||
repo?: GitHubRepoRef | null;
|
||||
branch?: string;
|
||||
pr?: GitHubPullRequest | null;
|
||||
checks?: GitHubChecksSummary | null;
|
||||
canMerge?: boolean;
|
||||
};
|
||||
|
||||
export type GitHubPullRequestCreateInput = {
|
||||
directory: string;
|
||||
title: string;
|
||||
head: string;
|
||||
base: string;
|
||||
body?: string;
|
||||
draft?: boolean;
|
||||
};
|
||||
|
||||
export type GitHubPullRequestMergeInput = {
|
||||
directory: string;
|
||||
number: number;
|
||||
method: 'merge' | 'squash' | 'rebase';
|
||||
};
|
||||
|
||||
export type GitHubPullRequestReadyInput = {
|
||||
directory: string;
|
||||
number: number;
|
||||
};
|
||||
|
||||
export type GitHubPullRequestReadyResult = {
|
||||
ready: boolean;
|
||||
};
|
||||
|
||||
export type GitHubPullRequestMergeResult = {
|
||||
merged: boolean;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export type GitHubAuthStatus = {
|
||||
connected: boolean;
|
||||
user?: GitHubUserSummary | null;
|
||||
scope?: string;
|
||||
};
|
||||
|
||||
export type GitHubDeviceFlowStart = {
|
||||
deviceCode: string;
|
||||
userCode: string;
|
||||
verificationUri: string;
|
||||
verificationUriComplete?: string;
|
||||
expiresIn: number;
|
||||
interval: number;
|
||||
scope?: string;
|
||||
};
|
||||
|
||||
export type GitHubDeviceFlowComplete =
|
||||
| { connected: true; user: GitHubUserSummary; scope?: string }
|
||||
| { connected: false; status?: string; error?: string };
|
||||
|
||||
export interface GitHubAPI {
|
||||
authStatus(): Promise<GitHubAuthStatus>;
|
||||
authStart(): Promise<GitHubDeviceFlowStart>;
|
||||
authComplete(deviceCode: string): Promise<GitHubDeviceFlowComplete>;
|
||||
authDisconnect(): Promise<{ removed: boolean }>;
|
||||
me?(): Promise<GitHubUserSummary>;
|
||||
|
||||
prStatus(directory: string, branch: string): Promise<GitHubPullRequestStatus>;
|
||||
prCreate(payload: GitHubPullRequestCreateInput): Promise<GitHubPullRequest>;
|
||||
prMerge(payload: GitHubPullRequestMergeInput): Promise<GitHubPullRequestMergeResult>;
|
||||
prReady(payload: GitHubPullRequestReadyInput): Promise<GitHubPullRequestReadyResult>;
|
||||
}
|
||||
|
||||
export interface RuntimeAPIs {
|
||||
runtime: RuntimeDescriptor;
|
||||
terminal: TerminalAPI;
|
||||
@@ -486,6 +601,7 @@ export interface RuntimeAPIs {
|
||||
settings: SettingsAPI;
|
||||
permissions: PermissionsAPI;
|
||||
notifications: NotificationsAPI;
|
||||
github?: GitHubAPI;
|
||||
push?: PushAPI;
|
||||
diagnostics?: DiagnosticsAPI;
|
||||
tools: ToolsAPI;
|
||||
|
||||
@@ -104,6 +104,17 @@ export async function generateCommitMessage(
|
||||
return gitHttp.generateCommitMessage(directory, files);
|
||||
}
|
||||
|
||||
export async function generatePullRequestDescription(
|
||||
directory: string,
|
||||
payload: { base: string; head: string }
|
||||
): Promise<import('./api/types').GeneratedPullRequestDescription> {
|
||||
const runtime = getRuntimeGit();
|
||||
if (runtime?.generatePullRequestDescription) {
|
||||
return runtime.generatePullRequestDescription(directory, payload);
|
||||
}
|
||||
return gitHttp.generatePullRequestDescription(directory, payload);
|
||||
}
|
||||
|
||||
export async function listGitWorktrees(directory: string): Promise<import('./api/types').GitWorktreeInfo[]> {
|
||||
const runtime = getRuntimeGit();
|
||||
if (runtime) return runtime.listGitWorktrees(directory);
|
||||
|
||||
@@ -248,6 +248,35 @@ export async function generateCommitMessage(
|
||||
};
|
||||
}
|
||||
|
||||
export async function generatePullRequestDescription(
|
||||
directory: string,
|
||||
payload: { base: string; head: string }
|
||||
): Promise<{ title: string; body: string }> {
|
||||
const { base, head } = payload;
|
||||
if (!base || !head) {
|
||||
throw new Error('base and head are required');
|
||||
}
|
||||
|
||||
const response = await fetch(buildUrl(`${API_BASE}/pr-description`, directory), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ base, head }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: response.statusText }));
|
||||
throw new Error(error.error || 'Failed to generate PR description');
|
||||
}
|
||||
|
||||
const data = await response.json().catch(() => null);
|
||||
const title = typeof data?.title === 'string' ? data.title : '';
|
||||
const body = typeof data?.body === 'string' ? data.body : '';
|
||||
if (!title && !body) {
|
||||
throw new Error('Malformed PR description response');
|
||||
}
|
||||
return { title, body };
|
||||
}
|
||||
|
||||
export async function listGitWorktrees(directory: string): Promise<GitWorktreeInfo[]> {
|
||||
const response = await fetch(buildUrl(`${API_BASE}/worktrees`, directory));
|
||||
if (!response.ok) {
|
||||
|
||||
Reference in New Issue
Block a user