This commit is contained in:
Timothy Jaeryang Baek committed 2026-08-13 15:54:43 -06:00
1 parent 9451874f17
commit 7745cb7205
10 files changed
+2233 -104

No files matched your search

+178 -4
View File
@@ -56,6 +56,61 @@ export interface GitOperationResult {
message: string;
}
export interface GitPrAuthor {
login?: string;
name?: string;
}
export interface GitPr {
number: number;
title: string;
url: string;
state?: string;
isDraft?: boolean;
reviewDecision?: string;
statusCheckRollup?: unknown[];
headRefName?: string;
baseRefName?: string;
author?: GitPrAuthor;
assignees?: GitPrAuthor[];
labels?: { name?: string; color?: string; description?: string }[];
milestone?: { title?: string } | null;
reviewRequests?: unknown[];
latestReviews?: unknown[];
mergeable?: string;
mergeStateStatus?: string;
maintainerCanModify?: boolean;
createdAt?: string;
updatedAt?: string;
additions?: number;
deletions?: number;
changedFiles?: number;
body?: string;
comments?: unknown[];
reviews?: unknown[];
commits?: unknown[];
files?: unknown[];
}
export interface GitPrCapabilities {
is_github: boolean;
gh_installed: boolean;
authenticated: boolean;
default_branch?: string;
message?: string;
}
export interface GitPrCheck {
name?: string;
workflow?: string;
state?: string;
bucket?: 'pass' | 'fail' | 'pending' | 'skipping' | 'cancel' | string;
description?: string;
link?: string;
startedAt?: string;
completedAt?: string;
}
// Deduplicate concurrent getGitStatus calls.
// Multiple components (layout, GitBar, FileEditor × N) all fetch on mount;
// this ensures they share a single in-flight request and a brief result cache.
@@ -110,9 +165,7 @@ export const getGitStashes = (root: string) =>
fetchJSON(`/api/git/stashes?root=${encodeURIComponent(root)}`);
export const getGitConfig = (root?: string) =>
fetchJSON<GitSettingsConfig>(
`/api/git/config${root ? `?root=${encodeURIComponent(root)}` : ''}`
);
fetchJSON<GitSettingsConfig>(`/api/git/config${root ? `?root=${encodeURIComponent(root)}` : ''}`);
export const startGhLogin = (hostname = 'github.com', git_protocol = 'https') =>
fetchJSON<GhLoginStatus>('/api/git/gh/login/start', jsonBody({ hostname, git_protocol }));
@@ -132,6 +185,126 @@ export const ghSwitch = (hostname: string, user: string) =>
export const ghSetupGit = (hostname = 'github.com') =>
fetchJSON('/api/git/gh/setup-git', jsonBody({ hostname }));
export const getGitPrCapabilities = (root: string) =>
fetchJSON<GitPrCapabilities>(`/api/git/pr/capabilities?root=${encodeURIComponent(root)}`);
export const getGitCurrentPr = (root: string) =>
fetchJSON<{ found: boolean; pr?: GitPr | null }>(
`/api/git/pr/current?root=${encodeURIComponent(root)}`
);
export const getGitPrList = (
root: string,
state = 'open',
scope = 'all',
search = '',
limit = 30
) =>
fetchJSON<{ items: GitPr[] }>(
`/api/git/pr/list?root=${encodeURIComponent(root)}&state=${encodeURIComponent(state)}&scope=${encodeURIComponent(scope)}&search=${encodeURIComponent(search)}&limit=${limit}`
);
export const getGitPrView = (root: string, number: number) =>
fetchJSON<GitPr>(
`/api/git/pr/view?root=${encodeURIComponent(root)}&number=${encodeURIComponent(number)}`
);
export const getGitPrDiff = (root: string, number: number, ignoreWhitespace = false) =>
fetchJSON(
`/api/git/pr/diff?root=${encodeURIComponent(root)}&number=${encodeURIComponent(number)}&ignore_whitespace=${ignoreWhitespace}`
);
export const getGitCompareDiff = (
root: string,
base: string,
head: string,
ignoreWhitespace = false
) =>
fetchJSON(
`/api/git/compare/diff?root=${encodeURIComponent(root)}&base=${encodeURIComponent(base)}&head=${encodeURIComponent(head)}&ignore_whitespace=${ignoreWhitespace}`
);
export const getGitPrChecks = (root: string, number: number) =>
fetchJSON<{ items: GitPrCheck[] }>(
`/api/git/pr/checks?root=${encodeURIComponent(root)}&number=${encodeURIComponent(number)}`
);
export const gitPrCheckout = (root: string, number: number) =>
fetchJSON<GitOperationResult>('/api/git/pr/checkout', jsonBody({ root, number }));
export const gitPrCreate = (
root: string,
body: {
title: string;
body?: string;
repo?: string;
base?: string;
head?: string;
draft?: boolean;
reviewers?: string[];
assignees?: string[];
labels?: string[];
milestone?: string;
project?: string;
maintainer_edit?: boolean;
}
) => fetchJSON<{ ok: boolean; url?: string }>('/api/git/pr/create', jsonBody({ root, ...body }));
export const gitPrEdit = (
root: string,
number: number,
body: {
title?: string;
body?: string;
base?: string;
add_reviewers?: string[];
remove_reviewers?: string[];
add_assignees?: string[];
remove_assignees?: string[];
add_labels?: string[];
remove_labels?: string[];
milestone?: string;
remove_milestone?: boolean;
}
) => fetchJSON<GitOperationResult>('/api/git/pr/edit', jsonBody({ root, number, ...body }));
export const gitPrReady = (root: string, number: number, draft = false) =>
fetchJSON<GitOperationResult>('/api/git/pr/ready', jsonBody({ root, number, draft }));
export const gitPrClose = (
root: string,
number: number,
{ comment = '', delete_branch = false }: { comment?: string; delete_branch?: boolean } = {}
) => fetchJSON<GitOperationResult>('/api/git/pr/close', jsonBody({ root, number, comment, delete_branch }));
export const gitPrReopen = (root: string, number: number) =>
fetchJSON<GitOperationResult>('/api/git/pr/reopen', jsonBody({ root, number }));
export const gitPrUpdateBranch = (root: string, number: number, rebase = false) =>
fetchJSON<GitOperationResult>('/api/git/pr/update-branch', jsonBody({ root, number, rebase }));
export const gitPrMerge = (
root: string,
number: number,
body: {
strategy?: 'merge' | 'squash' | 'rebase';
auto?: boolean;
delete_branch?: boolean;
subject?: string;
body?: string;
} = {}
) => fetchJSON<GitOperationResult>('/api/git/pr/merge', jsonBody({ root, number, ...body }));
export const gitPrComment = (root: string, number: number, body: string) =>
fetchJSON<GitOperationResult>('/api/git/pr/comment', jsonBody({ root, number, body }));
export const gitPrReview = (
root: string,
number: number,
event: 'approve' | 'comment' | 'request_changes',
body = ''
) => fetchJSON<GitOperationResult>('/api/git/pr/review', jsonBody({ root, number, event, body }));
export const stageFiles = (root: string, files: string[]) =>
fetchJSON('/api/git/stage', jsonBody({ root, files }));
@@ -163,7 +336,8 @@ export const gitPush = (
set_upstream = false,
branch
}: { force?: boolean; set_upstream?: boolean; branch?: string } = {}
) => fetchJSON<GitOperationResult>('/api/git/push', jsonBody({ root, force, set_upstream, branch }));
) =>
fetchJSON<GitOperationResult>('/api/git/push', jsonBody({ root, force, set_upstream, branch }));
export const gitUncommit = (root: string) => fetchJSON('/api/git/uncommit', jsonBody({ root }));
File diff suppressed because it is too large. Load diff
+224 -26
View File
@@ -1,6 +1,13 @@
<script lang="ts">
import { activeWorkspace, openFileTab, gitReviewOpen } from '$lib/stores';
import { getGitDiff } from '$lib/apis/git';
import { activeWorkspace, openChatTab, openFileTab, gitReviewOpen } from '$lib/stores';
import {
getGitDiff,
getGitPrDiff,
getGitPrView,
gitPrComment,
gitPrReview,
type GitPr
} from '$lib/apis/git';
import { diffDisplayMode, hideWhitespaceChanges } from '$lib/stores/gitDiffSettings';
import { gitStatusStore, type GitStatus, type GitFile } from '$lib/stores/gitStatus.svelte';
@@ -31,6 +38,7 @@
let error = $state('');
let showDiffSettings = $state(false);
let diffSettingsButtonEl = $state<HTMLButtonElement | undefined>();
let pr = $state<GitPr | null>(null);
let loadSeq = 0;
const workspacePath = $derived($activeWorkspace?.path ?? '');
@@ -39,21 +47,45 @@
const totalDeletions = $derived(reviewFiles.reduce((sum, file) => sum + file.deletions, 0));
const anyExpanded = $derived(reviewFiles.some((file) => file.expanded));
// React to git status changes from centralized store
const reviewTarget = $derived($gitReviewOpen);
const isPrReview = $derived(reviewTarget?.kind === 'pr');
// React to git status/target changes from centralized store
let _prevStatusRef: GitStatus | null = null;
let _prevHideWhitespace = false;
let _prevTargetKey = '';
$effect(() => {
const status = gitStatus;
const hideWhitespace = $hideWhitespaceChanges;
if (!workspacePath || !status) {
const target = reviewTarget;
const targetKey = target ? `${target.kind}:${target.kind === 'pr' ? target.number : ''}` : '';
if (!workspacePath || !target) {
reviewFiles = [];
return;
}
// Only re-fetch diffs when status actually changes
if (status !== _prevStatusRef || hideWhitespace !== _prevHideWhitespace) {
if (target.kind === 'pr') {
if (targetKey !== _prevTargetKey || hideWhitespace !== _prevHideWhitespace) {
const isInitial = _prevTargetKey !== targetKey;
_prevTargetKey = targetKey;
_prevHideWhitespace = hideWhitespace;
fetchPrDiffs(target.number, isInitial);
}
return;
}
if (!status) {
reviewFiles = [];
return;
}
if (
status !== _prevStatusRef ||
hideWhitespace !== _prevHideWhitespace ||
targetKey !== _prevTargetKey
) {
const isInitial = _prevStatusRef === null;
_prevStatusRef = status;
_prevHideWhitespace = hideWhitespace;
_prevTargetKey = targetKey;
pr = null;
fetchDiffs(status, isInitial);
}
});
@@ -122,7 +154,57 @@
}
}
async function fetchPrDiffs(number: number, initial = false) {
const seq = ++loadSeq;
const root = workspacePath;
if (!root) return;
if (initial) loading = true;
else refreshing = true;
error = '';
try {
const [details, diff] = await Promise.all([
getGitPrView(root, number),
getGitPrDiff(root, number, $hideWhitespaceChanges) as Promise<{ files?: DiffFile[] }>
]);
const previousExpansion = new Map(reviewFiles.map((file) => [file.key, file.expanded]));
const nextFiles = (diff.files ?? []).map((diffFile) => {
const counts = countDiffStats([diffFile]);
return {
key: `pr:${number}:${diffFile.path}`,
path: diffFile.path,
status: 'modified',
staged: false,
binary: diffFile.hunks.length === 0,
diffFiles: [diffFile],
additions: counts.additions,
deletions: counts.deletions,
expanded: previousExpansion.get(`pr:${number}:${diffFile.path}`) ?? true
};
});
if (seq !== loadSeq || root !== workspacePath) return;
pr = details;
reviewFiles = nextFiles;
} catch (e) {
if (seq !== loadSeq) return;
error = e instanceof Error ? e.message : $t('git.loadChangesFailed');
pr = null;
reviewFiles = [];
} finally {
if (seq === loadSeq) {
loading = false;
refreshing = false;
}
}
}
async function refreshReview(initial = false) {
const target = reviewTarget;
if (target?.kind === 'pr') {
await fetchPrDiffs(target.number, initial);
return;
}
await gitStatusStore.refresh({ force: true });
}
@@ -144,7 +226,52 @@
function openFile(path: string) {
const fullPath = workspacePath.replace(/\/$/, '') + '/' + path;
openFileTab(fullPath);
gitReviewOpen.set(false);
gitReviewOpen.set(null);
}
function closeReview() {
gitReviewOpen.set(null);
}
async function commentOnPr(event: 'comment' | 'request_changes' | 'approve') {
if (!pr) return;
const defaultBody =
event === 'approve'
? 'Looks good.'
: event === 'request_changes'
? 'Please address this.'
: '';
const body = window.prompt(
event === 'approve'
? 'Approval note'
: event === 'request_changes'
? 'Changes requested'
: 'Comment',
defaultBody
);
if (body === null) return;
try {
if (event === 'comment') await gitPrComment(workspacePath, pr.number, body);
else await gitPrReview(workspacePath, pr.number, event, body);
await refreshReview(false);
} catch (e) {
error = e instanceof Error ? e.message : 'GitHub CLI action failed';
}
}
function askCodexAboutPr() {
if (!pr || !workspacePath) return;
const draft = [
`Review this pull request and help me decide what to do next.`,
``,
`PR: #${pr.number} ${pr.title}`,
`URL: ${pr.url}`,
`Branch: ${pr.headRefName || '?'} -> ${pr.baseRefName || '?'}`,
`Files: ${pr.changedFiles ?? totalChanges}, +${pr.additions ?? totalAdditions}/-${pr.deletions ?? totalDeletions}`
].join('\n');
sessionStorage.setItem(`cptr:intent:chatDraft:${workspacePath}`, draft);
openChatTab();
closeReview();
}
function pathParts(path: string): { dir: string; name: string } {
@@ -168,11 +295,11 @@
<div
class="flex h-full flex-col overflow-hidden bg-white text-gray-900 dark:bg-black dark:text-gray-100"
>
{#if loading && !gitStatus}
{#if loading && !gitStatus && !isPrReview}
<div class="flex h-full items-center justify-center">
<Spinner size={16} />
</div>
{:else if error && !gitStatus}
{:else if error && !gitStatus && !isPrReview}
<div class="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
<Icon name="git-diff" size={24} class="text-gray-300 dark:text-gray-700" />
<p class="text-xs font-medium text-gray-700 dark:text-gray-300">
@@ -180,7 +307,7 @@
</p>
<p class="max-w-sm text-[0.6875rem] text-gray-400 dark:text-gray-600">{error}</p>
</div>
{:else if !gitStatus?.is_repo}
{:else if !isPrReview && !gitStatus?.is_repo}
<div class="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
<Icon name="git-branch" size={24} class="text-gray-300 dark:text-gray-700" />
<p class="text-xs text-gray-400 dark:text-gray-600">{$t('git.notARepo')}</p>
@@ -190,22 +317,36 @@
class="flex h-9 shrink-0 items-center gap-2 border-b border-gray-200 px-3 dark:border-white/6"
>
<div class="flex min-w-0 flex-1 items-center gap-1.5">
<Icon name="git-branch" size={14} class="shrink-0 text-gray-400 dark:text-gray-600" />
<span class="truncate font-mono text-xs font-medium text-gray-700 dark:text-gray-300"
>{gitStatus.branch || 'HEAD'}</span
>
{#if gitStatus.upstream}
<Icon
name={isPrReview ? 'git-diff' : 'git-branch'}
size={14}
class="shrink-0 text-gray-400 dark:text-gray-600"
/>
<span class="truncate font-mono text-xs font-medium text-gray-700 dark:text-gray-300">
{#if isPrReview}
{pr ? `#${pr.number}` : 'Pull request'}
{:else}
{gitStatus?.branch || 'HEAD'}
{/if}
</span>
{#if isPrReview && pr}
<span class="truncate text-xs text-gray-600 dark:text-gray-300">{pr.title}</span>
<span
class="hidden sm:inline truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
>{pr.headRefName} → {pr.baseRefName}</span
>
{:else if gitStatus?.upstream}
<Icon name="chevron-right" size={12} class="shrink-0 text-gray-300 dark:text-gray-700" />
<span class="truncate font-mono text-[0.6875rem] text-gray-400 dark:text-gray-600"
>{gitStatus.upstream}</span
>
{/if}
{#if gitStatus.ahead > 0}
{#if !isPrReview && gitStatus && gitStatus.ahead > 0}
<span class="font-mono text-[0.625rem] text-gray-400 dark:text-gray-600"
>+{gitStatus.ahead}</span
>
{/if}
{#if gitStatus.behind > 0}
{#if !isPrReview && gitStatus && gitStatus.behind > 0}
<span class="font-mono text-[0.625rem] text-gray-400 dark:text-gray-600"
>-{gitStatus.behind}</span
>
@@ -225,6 +366,41 @@
{/if}
</div>
{#if isPrReview && pr}
<button
class="hidden sm:flex h-6 items-center rounded-md px-2 text-[0.6875rem] text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/6 dark:hover:text-gray-200"
onclick={askCodexAboutPr}
>
Draft chat
</button>
<button
class="hidden sm:flex h-6 items-center rounded-md px-2 text-[0.6875rem] text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/6 dark:hover:text-gray-200"
onclick={() => commentOnPr('comment')}
>
Comment
</button>
<button
class="hidden sm:flex h-6 items-center rounded-md px-2 text-[0.6875rem] text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/6 dark:hover:text-gray-200"
onclick={() => commentOnPr('approve')}
>
Approve
</button>
<button
class="hidden sm:flex h-6 items-center rounded-md px-2 text-[0.6875rem] text-gray-500 transition-colors hover:bg-gray-100 hover:text-gray-700 dark:text-gray-400 dark:hover:bg-white/6 dark:hover:text-gray-200"
onclick={() => commentOnPr('request_changes')}
>
Request changes
</button>
<a
href={pr.url}
target="_blank"
rel="noopener noreferrer"
class="flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300"
use:tooltip={'Open on GitHub'}
>
<Icon name="external-link" size={12} />
</a>
{/if}
<button
bind:this={diffSettingsButtonEl}
class="flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300"
@@ -235,6 +411,14 @@
<Icon name="settings" size={13} />
</button>
<button
class="flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300"
onclick={closeReview}
aria-label={$t('common.close')}
use:tooltip={$t('common.close')}
>
<Icon name="xmark" size={12} />
</button>
<button
class="flex h-6 w-6 items-center justify-center rounded-md text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-white/6 dark:hover:text-gray-300"
onclick={() => refreshReview(false)}
@@ -262,7 +446,7 @@
<span>{anyExpanded ? $t('git.collapseAll') : $t('git.expandAll')}</span>
</button>
<span class="text-[0.6875rem] text-gray-500 dark:text-gray-400">
{$t('git.uncommittedChanges')}
{isPrReview ? 'Pull request changes' : $t('git.uncommittedChanges')}
</span>
<span class="ml-auto text-[0.6875rem] text-gray-400 dark:text-gray-600"
>{$t('git.change', { count: totalChanges })}</span
@@ -279,7 +463,19 @@
{/if}
<div class="min-h-0 flex-1 overflow-y-auto">
{#if totalChanges === 0}
{#if loading}
<div class="flex h-full items-center justify-center">
<Spinner size={16} />
</div>
{:else if error}
<div class="flex h-full flex-col items-center justify-center gap-2 px-6 text-center">
<Icon name="git-diff" size={24} class="text-gray-300 dark:text-gray-700" />
<p class="text-xs font-medium text-gray-700 dark:text-gray-300">
{$t('git.unableToLoadChanges')}
</p>
<p class="max-w-sm text-[0.6875rem] text-gray-400 dark:text-gray-600">{error}</p>
</div>
{:else if totalChanges === 0}
<div class="flex h-full items-center justify-center px-6">
<div class="flex -translate-y-8 flex-col items-center gap-2 text-center">
<Icon
@@ -289,10 +485,10 @@
class="text-gray-300 dark:text-gray-700"
/>
<h2 class="text-sm font-medium text-gray-700 dark:text-gray-300">
{$t('git.noFileChangesYet')}
{isPrReview ? 'No pull request changes' : $t('git.noFileChangesYet')}
</h2>
<p class="text-xs text-gray-400 dark:text-gray-600">
{$t('git.projectChangesHint')}
{isPrReview ? 'GitHub returned an empty diff.' : $t('git.projectChangesHint')}
</p>
</div>
</div>
@@ -345,11 +541,13 @@
>
{/if}
<span
class="shrink-0 rounded px-1.5 py-0.5 text-[0.625rem] font-medium text-rose-500 bg-rose-50 dark:bg-rose-500/10 dark:text-rose-300"
>
{file.staged ? $t('git.staged') : $t('git.uncommittedChanges')}
</span>
{#if !isPrReview}
<span
class="shrink-0 rounded px-1.5 py-0.5 text-[0.625rem] font-medium text-rose-500 bg-rose-50 dark:bg-rose-500/10 dark:text-rose-300"
>
{file.staged ? $t('git.staged') : $t('git.uncommittedChanges')}
</span>
{/if}
</button>
{#if file.expanded}
@@ -93,7 +93,7 @@
type TabDragPayload = { tabId: string; groupId: string };
const displayTabs = $derived((group?.tabs ?? []).filter((t) => t.type !== 'git'));
const displayTabs = $derived(group?.tabs ?? []);
const isActiveGroup = $derived(home ? homeActive : $activeWorkspace?.activeGroupId === group?.id);
@@ -107,8 +107,6 @@
return 'terminal';
case 'file':
return 'page';
case 'git':
return 'git-diff';
case 'chat':
return 'chat-bubble';
case 'preview':
+34 -12
View File
@@ -55,7 +55,7 @@ export interface FileSearchTarget {
export interface Tab {
id: string;
type: 'home' | 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
type: 'home' | 'files' | 'terminal' | 'file' | 'chat' | 'preview' | 'browser'; // preview is migrated on load
label: string;
filePath?: string;
edit?: boolean;
@@ -69,6 +69,20 @@ export interface Tab {
searchTarget?: FileSearchTarget;
}
const SUPPORTED_TAB_TYPES = new Set([
'home',
'files',
'terminal',
'file',
'chat',
'preview',
'browser'
]);
function isSupportedTab(tab: { type?: unknown }): tab is Tab {
return typeof tab.type === 'string' && SUPPORTED_TAB_TYPES.has(tab.type);
}
export type SplitDirection = 'horizontal' | 'vertical';
export interface EditorGroup {
@@ -327,7 +341,8 @@ export const showChangelog = writable(false);
export const showUpdateToastPref = writable(true);
export const showSearch = writable(false);
export const stateLoaded = writable(false);
export const gitReviewOpen = writable(false);
export type GitReviewTarget = { kind: 'local' } | { kind: 'pr'; number: number };
export const gitReviewOpen = writable<GitReviewTarget | null>(null);
export const isGitRepo = writable(false);
export type StreamingBehavior = 'queue' | 'interrupt';
export const streamingBehavior = writable<StreamingBehavior>('queue');
@@ -570,19 +585,23 @@ export async function loadPreferences(): Promise<void> {
const aliveBrowsers = new Set(browserIds);
let groups = savedHomeState.groups
.map((group) => {
const tabs = group.tabs.filter(
(tab) =>
tab.type !== 'terminal' ||
(tab.sessionId !== undefined && aliveTerminals.has(tab.sessionId))
);
const liveTabs = tabs.filter(
(tab) =>
tab.type !== 'browser' ||
(tab.browserSessionId !== undefined && aliveBrowsers.has(tab.browserSessionId))
);
const tabs = group.tabs.filter((tab): tab is Tab => isSupportedTab(tab));
const liveTabs = tabs
.filter(
(tab) =>
tab.type !== 'terminal' ||
(tab.sessionId !== undefined && aliveTerminals.has(tab.sessionId))
)
.filter(
(tab) =>
tab.type !== 'browser' ||
(tab.browserSessionId !== undefined && aliveBrowsers.has(tab.browserSessionId))
);
const liveIds = new Set(liveTabs.map((tab) => tab.id));
return {
...group,
tabs: liveTabs,
tabHistory: (group.tabHistory ?? []).filter((id) => liveIds.has(id)),
activeTabId: liveTabs.some((tab) => tab.id === group.activeTabId)
? group.activeTabId
: (liveTabs[0]?.id ?? '')
@@ -676,6 +695,7 @@ export async function loadWorkspace(path: string): Promise<void> {
tabs: (
await Promise.all(
group.tabs.map(async (tab) => {
if (!isSupportedTab(tab)) return null;
if (tab.type !== 'preview' || !tab.port) return tab;
try {
const previewUrl = `http://localhost:${tab.port}/`;
@@ -713,10 +733,12 @@ export async function loadWorkspace(path: string): Promise<void> {
}
return true;
});
const liveIds = new Set(filteredTabs.map((t) => t.id));
const activeStillExists = filteredTabs.some((t: Tab) => t.id === g.activeTabId);
return {
...g,
tabs: filteredTabs,
tabHistory: (g.tabHistory ?? []).filter((id) => liveIds.has(id)),
activeTabId: activeStillExists ? g.activeTabId : (filteredTabs[0]?.id ?? 'files')
};
})
+3 -4
View File
@@ -309,12 +309,11 @@ export function executeAction(
}
const g = get(activeGroup);
if (!g || g.tabs.length < 2) return true;
const visibleTabs = g.tabs.filter((t) => t.type !== 'git');
const currentIdx = visibleTabs.findIndex((t) => t.id === g.activeTabId);
const currentIdx = g.tabs.findIndex((t) => t.id === g.activeTabId);
if (currentIdx === -1) return true;
const dir = action === 'nextTab' ? 1 : -1;
const nextIdx = (currentIdx + dir + visibleTabs.length) % visibleTabs.length;
setActiveTab(visibleTabs[nextIdx].id, g.id);
const nextIdx = (currentIdx + dir + g.tabs.length) % g.tabs.length;
setActiveTab(g.tabs[nextIdx].id, g.id);
return true;
}
+19 -3
View File
@@ -54,6 +54,7 @@
let { children } = $props();
let showSettings = $state(false);
let settingsTab = $state('general');
let showUpdateToast = $state(false);
let showSetup = $state(false);
let gitSettingsAvailable = $state(false);
@@ -115,6 +116,12 @@
}
window.addEventListener('offline', showOfflineToast);
window.addEventListener('online', showOnlineToast);
const openSettings = (event: Event) => {
const detail = (event as CustomEvent<{ tab?: string }>).detail;
settingsTab = detail?.tab || 'general';
showSettings = true;
};
window.addEventListener('cptr:open-settings', openSettings as EventListener);
return () => {
clearInterval(healthCheck);
@@ -124,6 +131,7 @@
vv?.removeEventListener('scroll', syncKeyboardInset);
window.removeEventListener('offline', showOfflineToast);
window.removeEventListener('online', showOnlineToast);
window.removeEventListener('cptr:open-settings', openSettings as EventListener);
};
});
@@ -354,6 +362,7 @@
showSearch.update((v) => !v);
},
toggleSettings: () => {
settingsTab = 'general';
showSettings = !showSettings;
},
toggleSearch: () => {
@@ -398,7 +407,7 @@
if (!ws) {
gitStatusStore.clear();
isGitRepo.set(false);
gitReviewOpen.set(false);
gitReviewOpen.set(null);
return;
}
gitStatusStore.setRoot(ws.path);
@@ -474,7 +483,7 @@
class="app-theme h-screen max-h-[100dvh] flex overflow-hidden font-sans antialiased text-gray-900 bg-white dark:text-gray-100 dark:bg-black"
style="background: var(--app-bg); color: var(--app-fg);"
>
<Sidebar gitSettingsAvailable={gitSettingsAvailable} />
<Sidebar {gitSettingsAvailable} />
<div
id="main-col"
@@ -497,7 +506,14 @@
<SearchModal onclose={() => showSearch.set(false)} />
{#if showSettings}
<SettingsModal {gitSettingsAvailable} onclose={() => (showSettings = false)} />
<SettingsModal
{gitSettingsAvailable}
initialTab={settingsTab}
onclose={() => {
showSettings = false;
settingsTab = 'general';
}}
/>
{/if}
<ChangelogModal />
{#if $updateAvailable && showUpdateToast}
+555 -3
View File
@@ -6,10 +6,11 @@ All endpoints require a `root` path (the workspace directory).
from __future__ import annotations
from typing import List, Optional
import json
from typing import Any, List, Optional
from fastapi import APIRouter, HTTPException, Request
from pydantic import BaseModel
from pydantic import BaseModel, Field
from cptr.models import UserStates
from cptr.utils.ai import generate_text
@@ -23,9 +24,11 @@ from cptr.utils import gh
from cptr.utils.json_parser import extract_json
from cptr.utils.git import (
GitError,
_parse_diff,
branches,
checkout,
commit,
compare_diff,
create_branch,
create_worktree,
delete_branch,
@@ -165,7 +168,12 @@ async def git_config(request: Request, root: str | None = None):
"root": root,
"git": git_data,
"app_identity": await _user_git_identity(identity),
"gh": {"installed": False, "version": None, "hosts": {}, "message": "Git is not installed."},
"gh": {
"installed": False,
"version": None,
"hosts": {},
"message": "Git is not installed.",
},
"permissions": {
"can_manage_gh": identity.is_pam or _is_admin(request),
"can_manage_commit_model": _is_admin(request),
@@ -231,6 +239,27 @@ async def git_show(request: Request, root: str, ref: str, ignore_whitespace: boo
_handle_git_error(e)
@router.get("/compare/diff")
async def git_compare_diff(
request: Request,
root: str,
base: str,
head: str,
ignore_whitespace: bool = False,
):
"""Show a base...head comparison with its diff."""
root, identity = await _root_identity(request, root)
await _require_repo(root, identity)
base = base.strip()
head = head.strip()
if not base or not head:
raise HTTPException(status_code=400, detail="base and head are required")
try:
return await compare_diff(root, base, head, ignore_whitespace, identity)
except GitError as e:
_handle_git_error(e)
@router.get("/branches")
async def git_branches(request: Request, root: str):
"""List local and remote branches."""
@@ -370,6 +399,194 @@ class GhUserHostRequest(GhHostRequest):
user: Optional[str] = None
class PrNumberRequest(BaseModel):
root: str
number: int
class PrCreateRequest(BaseModel):
root: str
title: str
body: str = ""
repo: Optional[str] = None
base: Optional[str] = None
head: Optional[str] = None
draft: bool = False
reviewers: List[str] = Field(default_factory=list)
assignees: List[str] = Field(default_factory=list)
labels: List[str] = Field(default_factory=list)
milestone: Optional[str] = None
project: Optional[str] = None
maintainer_edit: bool = True
class PrCommentRequest(PrNumberRequest):
body: str
class PrReviewRequest(PrNumberRequest):
event: str
body: str = ""
class PrEditRequest(PrNumberRequest):
title: Optional[str] = None
body: Optional[str] = None
base: Optional[str] = None
add_reviewers: List[str] = Field(default_factory=list)
remove_reviewers: List[str] = Field(default_factory=list)
add_assignees: List[str] = Field(default_factory=list)
remove_assignees: List[str] = Field(default_factory=list)
add_labels: List[str] = Field(default_factory=list)
remove_labels: List[str] = Field(default_factory=list)
milestone: Optional[str] = None
remove_milestone: bool = False
class PrReadyRequest(PrNumberRequest):
draft: bool = False
class PrCloseRequest(PrNumberRequest):
comment: str = ""
delete_branch: bool = False
class PrUpdateBranchRequest(PrNumberRequest):
rebase: bool = False
class PrMergeRequest(PrNumberRequest):
strategy: str = "squash"
auto: bool = False
delete_branch: bool = False
subject: Optional[str] = None
body: Optional[str] = None
PR_JSON_FIELDS = ",".join(
[
"number",
"title",
"url",
"state",
"isDraft",
"reviewDecision",
"statusCheckRollup",
"headRefName",
"baseRefName",
"author",
"assignees",
"labels",
"milestone",
"reviewRequests",
"latestReviews",
"mergeable",
"mergeStateStatus",
"maintainerCanModify",
"createdAt",
"updatedAt",
"additions",
"deletions",
"changedFiles",
]
)
PR_DETAIL_JSON_FIELDS = PR_JSON_FIELDS + ",body,comments,reviews,commits,files"
PR_CHECK_FIELDS = "bucket,completedAt,description,event,link,name,startedAt,state,workflow"
def _remote_is_github(url: str) -> bool:
return "github.com" in url.lower()
def _gh_has_login(auth: dict[str, Any]) -> bool:
for accounts in (auth.get("hosts") or {}).values():
if isinstance(accounts, list) and accounts:
return True
if isinstance(accounts, dict):
users = accounts.get("users")
if isinstance(users, list) and users:
return True
if accounts:
return True
return False
async def _pr_json(
root: str,
identity: ExecutionIdentity,
args: list[str],
*,
check: bool = True,
) -> Any:
code, out, err = await gh.run_gh(args, identity=identity, cwd=root, check=False)
if code != 0:
if check:
raise gh.GhError((err or out).strip() or "GitHub CLI command failed", code)
return None
try:
return json.loads(out) if out.strip() else None
except json.JSONDecodeError as exc:
raise gh.GhError("GitHub CLI returned invalid JSON") from exc
def _head_owner_login(pr: dict[str, Any]) -> str:
owner = pr.get("headRepositoryOwner")
if isinstance(owner, dict):
login = owner.get("login")
return login if isinstance(login, str) else ""
return owner if isinstance(owner, str) else ""
async def _github_repo_owner(root: str, identity: ExecutionIdentity) -> str:
repo = await _pr_json(root, identity, ["repo", "view", "--json", "nameWithOwner"])
name_with_owner = repo.get("nameWithOwner") if isinstance(repo, dict) else ""
if not isinstance(name_with_owner, str) or "/" not in name_with_owner:
return ""
return name_with_owner.split("/", 1)[0]
async def _current_branch_pr(root: str, identity: ExecutionIdentity) -> dict[str, Any] | None:
git_status = await status(root, identity)
branch = str(git_status.get("branch") or "").strip()
if not branch or branch in {"HEAD", "(detached)"}:
return None
owner = await _github_repo_owner(root, identity)
if not owner:
return None
items = await _pr_json(
root,
identity,
[
"pr",
"list",
"--search",
f"head:{owner}:{branch} state:open",
"--limit",
"10",
"--json",
PR_JSON_FIELDS,
],
)
if not isinstance(items, list):
return None
for item in items:
if not isinstance(item, dict):
continue
if str(item.get("state") or "").lower() != "open":
continue
if item.get("headRefName") != branch:
continue
if _head_owner_login(item) != owner:
continue
return item
return None
@router.post("/stage")
async def git_stage(request: Request, body: StageRequest):
"""Stage files for commit."""
@@ -564,6 +781,341 @@ async def git_stash_pop(request: Request, body: StashPopRequest):
_handle_git_error(e)
@router.get("/pr/capabilities")
async def git_pr_capabilities(request: Request, root: str):
root, identity = await _root_identity(request, root)
if not await is_repo(root, identity):
return {"is_github": False, "gh_installed": False, "authenticated": False}
config = await effective_config(root, identity)
remote_url = str(config.get("remote_url") or "")
is_github = _remote_is_github(remote_url)
if not is_github:
return {"is_github": False, "gh_installed": False, "authenticated": False}
try:
auth = await gh.auth_status(identity)
except gh.GhError as e:
return {
"is_github": True,
"gh_installed": False,
"authenticated": False,
"message": str(e),
}
default_branch = ""
if bool(auth.get("installed")) and _gh_has_login(auth):
try:
repo = await _pr_json(root, identity, ["repo", "view", "--json", "defaultBranchRef"])
branch_ref = repo.get("defaultBranchRef") if isinstance(repo, dict) else None
if isinstance(branch_ref, dict):
default_branch = str(branch_ref.get("name") or "")
except gh.GhError:
default_branch = ""
return {
"is_github": True,
"gh_installed": bool(auth.get("installed")),
"authenticated": _gh_has_login(auth),
"default_branch": default_branch,
"message": auth.get("message"),
}
@router.get("/pr/current")
async def git_pr_current(request: Request, root: str):
root, identity = await _root_identity(request, root)
await _require_repo(root, identity)
try:
result = await _current_branch_pr(root, identity)
return {"found": bool(result), "pr": result}
except gh.GhError as e:
_handle_gh_error(e)
@router.get("/pr/list")
async def git_pr_list(
request: Request,
root: str,
state: str = "open",
scope: str = "all",
search: str = "",
limit: int = 30,
):
root, identity = await _root_identity(request, root)
await _require_repo(root, identity)
state = state if state in {"open", "closed", "merged", "all"} else "open"
try:
if scope == "current":
item = await _current_branch_pr(root, identity)
return {"items": [item] if item else []}
limit = max(1, min(limit, 200))
args = ["pr", "list", "--state", state, "--limit", str(limit), "--json", PR_JSON_FIELDS]
query = search.strip()
if scope == "authored":
args.extend(["--author", "@me"])
elif scope == "reviewing":
query = f"review-requested:@me {query}".strip()
if query:
args.extend(["--search", query])
items = await _pr_json(
root,
identity,
args,
)
return {"items": items or []}
except gh.GhError as e:
_handle_gh_error(e)
@router.get("/pr/view")
async def git_pr_view(request: Request, root: str, number: int):
root, identity = await _root_identity(request, root)
await _require_repo(root, identity)
try:
return await _pr_json(
root,
identity,
["pr", "view", str(number), "--comments", "--json", PR_DETAIL_JSON_FIELDS],
)
except gh.GhError as e:
_handle_gh_error(e)
@router.get("/pr/diff")
async def git_pr_diff(
request: Request,
root: str,
number: int,
ignore_whitespace: bool = False,
):
root, identity = await _root_identity(request, root)
await _require_repo(root, identity)
args = ["pr", "diff", str(number), "--patch", "--color", "never"]
try:
_, out, _ = await gh.run_gh(args, identity=identity, cwd=root)
return _parse_diff(out)
except gh.GhError as e:
_handle_gh_error(e)
@router.get("/pr/checks")
async def git_pr_checks(request: Request, root: str, number: int):
root, identity = await _root_identity(request, root)
await _require_repo(root, identity)
try:
code, out, err = await gh.run_gh(
["pr", "checks", str(number), "--json", PR_CHECK_FIELDS],
identity=identity,
cwd=root,
check=False,
)
if code not in {0, 1, 8}:
raise gh.GhError((err or out).strip() or "GitHub CLI command failed", code)
return {"items": json.loads(out) if out.strip() else []}
except json.JSONDecodeError as e:
raise HTTPException(status_code=400, detail="GitHub CLI returned invalid JSON") from e
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/checkout")
async def git_pr_checkout(request: Request, body: PrNumberRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
try:
code, out, err = await gh.run_gh(
["pr", "checkout", str(body.number)],
identity=identity,
cwd=root,
check=False,
)
return {"ok": code == 0, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/create")
async def git_pr_create(request: Request, body: PrCreateRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
if not body.title.strip():
raise HTTPException(status_code=400, detail="title is required")
args = ["pr", "create", "--title", body.title.strip(), "--body", body.body]
if body.repo and body.repo.strip():
args.extend(["--repo", body.repo.strip()])
if body.base:
args.extend(["--base", body.base.strip()])
if body.head:
args.extend(["--head", body.head.strip()])
if body.draft:
args.append("--draft")
if body.reviewers:
args.extend(["--reviewer", ",".join(r.strip() for r in body.reviewers if r.strip())])
if body.assignees:
args.extend(["--assignee", ",".join(a.strip() for a in body.assignees if a.strip())])
if body.labels:
args.extend(["--label", ",".join(l.strip() for l in body.labels if l.strip())])
if body.milestone and body.milestone.strip():
args.extend(["--milestone", body.milestone.strip()])
if body.project and body.project.strip():
args.extend(["--project", body.project.strip()])
if not body.maintainer_edit:
args.append("--no-maintainer-edit")
try:
_, out, _ = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "url": out.strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/edit")
async def git_pr_edit(request: Request, body: PrEditRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
args = ["pr", "edit", str(body.number)]
if body.title is not None:
args.extend(["--title", body.title])
if body.body is not None:
args.extend(["--body", body.body])
if body.base:
args.extend(["--base", body.base.strip()])
for value, flag in [
(body.add_reviewers, "--add-reviewer"),
(body.remove_reviewers, "--remove-reviewer"),
(body.add_assignees, "--add-assignee"),
(body.remove_assignees, "--remove-assignee"),
(body.add_labels, "--add-label"),
(body.remove_labels, "--remove-label"),
]:
cleaned = [item.strip() for item in value if item.strip()]
if cleaned:
args.extend([flag, ",".join(cleaned)])
if body.milestone:
args.extend(["--milestone", body.milestone.strip()])
if body.remove_milestone:
args.append("--remove-milestone")
if len(args) == 3:
raise HTTPException(status_code=400, detail="no edits provided")
try:
_, out, err = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/ready")
async def git_pr_ready(request: Request, body: PrReadyRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
args = ["pr", "ready", str(body.number)]
if body.draft:
args.append("--undo")
try:
_, out, err = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/close")
async def git_pr_close(request: Request, body: PrCloseRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
args = ["pr", "close", str(body.number)]
if body.comment.strip():
args.extend(["--comment", body.comment])
if body.delete_branch:
args.append("--delete-branch")
try:
_, out, err = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/reopen")
async def git_pr_reopen(request: Request, body: PrNumberRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
try:
_, out, err = await gh.run_gh(
["pr", "reopen", str(body.number)], identity=identity, cwd=root
)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/update-branch")
async def git_pr_update_branch(request: Request, body: PrUpdateBranchRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
args = ["pr", "update-branch", str(body.number)]
if body.rebase:
args.append("--rebase")
try:
_, out, err = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/merge")
async def git_pr_merge(request: Request, body: PrMergeRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
strategy = body.strategy if body.strategy in {"merge", "squash", "rebase"} else "squash"
args = ["pr", "merge", str(body.number), f"--{strategy}"]
if body.auto:
args.append("--auto")
if body.delete_branch:
args.append("--delete-branch")
if body.subject:
args.extend(["--subject", body.subject])
if body.body:
args.extend(["--body", body.body])
try:
_, out, err = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/comment")
async def git_pr_comment(request: Request, body: PrCommentRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
if not body.body.strip():
raise HTTPException(status_code=400, detail="body is required")
try:
_, out, err = await gh.run_gh(
["pr", "comment", str(body.number), "--body", body.body],
identity=identity,
cwd=root,
)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/pr/review")
async def git_pr_review(request: Request, body: PrReviewRequest):
root, identity = await _root_identity(request, body.root)
await _require_repo(root, identity)
event_flag = {
"approve": "--approve",
"comment": "--comment",
"request_changes": "--request-changes",
}.get(body.event)
if not event_flag:
raise HTTPException(status_code=400, detail="invalid review event")
args = ["pr", "review", str(body.number), event_flag]
if body.body.strip():
args.extend(["--body", body.body])
try:
_, out, err = await gh.run_gh(args, identity=identity, cwd=root)
return {"ok": True, "message": (out + err).strip()}
except gh.GhError as e:
_handle_gh_error(e)
@router.post("/gh/login/start")
async def gh_login_start(request: Request, body: GhLoginStartRequest):
identity = await _identity(request)
+1
View File
@@ -56,6 +56,7 @@ async def run_gh(
raise GhError("GitHub CLI is not installed")
work_dir = cwd or identity.home
env = env_for(identity, work_dir) if identity.is_pam else os.environ.copy()
env["GH_PROMPT_DISABLED"] = "1"
proc = await asyncio.create_subprocess_exec(
gh,
*args,
+16
View File
@@ -324,6 +324,22 @@ async def diff(
return _parse_diff(out)
async def compare_diff(
root: str,
base: str,
head: str,
ignore_whitespace: bool = False,
identity: ExecutionIdentity | None = None,
) -> dict[str, Any]:
"""Get a structured diff for a base...head comparison."""
args = ["diff", "--unified=3", "--color=never"]
if ignore_whitespace:
args.append("--ignore-all-space")
args.append(f"{base}...{head}")
_, out, _ = await _run(*args, cwd=root, identity=identity)
return _parse_diff(out)
async def staged_diff(
root: str, max_chars: int = 30000, identity: ExecutionIdentity | None = None
) -> str: