Git Source Control Integration (#74)

* feat(source-control): add commits and file management components

- Introduced `CommitsTab` for displaying commit history with relative time formatting.
- Added `GitFlatFileItem` and `GitFlatFileList` for managing file statuses in the source control panel.
- Implemented `SourceControlPanel` to encapsulate source control functionalities including changes, commits, and branches.
- Enhanced `useGit` hook to manage git operations such as fetch, pull, push, commit, stage, and unstage files with appropriate error handling and toast notifications.
- Updated `RepoDetail` to integrate the new source control panel and provide a user interface for source control actions.
- Defined `GitCommit` type for better type safety in commit-related operations.

* refactor: streamline error handling in Git operations and update error imports

* feat: enhance Git services and ESLint configuration for improved functionality

* refactor: update method signatures for consistency and clarity in Git services

* feat: refactor git services and improve error handling

- Remove unused imports and clean up code in repos.ts and git-operations.ts.
- Simplify error handling in repo.ts by enforcing message property in ErrorWithMessage interface.
- Update GitPushService to remove unnecessary database parameter in methods.
- Enhance executeCommand function to better handle command execution results.
- Update tests to use mocked functions for better isolation and clarity.
- Add specific ESLint rules for test files to accommodate common testing patterns.
- Introduce tsconfig.test.json for better TypeScript configuration in tests.
- Update vitest.config.ts to use the new test TypeScript configuration.

* refactor: remove esbuild configuration from Vitest setup

* feat: enhance Source Control Panel with branch management and integrate into RepoDetail and SessionDetail pages

* feat: implement Git authentication service and refactor related services

- Add GitAuthService to handle Git environment setup with credentials.
- Refactor GitBranchService, GitCommitService, GitFetchPullService, GitPushService, GitStatusService, and GitLogService to utilize the new GitAuthService.
- Remove GitCommandUtils and related error handling for Git operations.
- Delete git-operations.ts and associated tests as functionality is now integrated into other services.
- Update TypeScript configuration to enable composite projects for better build management.

* feat: refactor Git services to improve structure and update imports

* refactor: simplify error utility functions and update test cases for Git services

* feat: refactor GitAuthService and update related tests for improved credential handling

* feat: implement GitDiffService and related endpoints for file diff functionality

* feat: add emitDeclarationOnly option to TypeScript configuration files

* feat: enhance GitLogService to fetch remote branches and improve error handling in repo commands

* feat: update Git command execution to remove fallback and enhance environment variable handling

* feat: add repository authentication tracking

- Add `requires_auth` column to repos table
- Implement auth check in GitAuthService
- Update cloneRepo to detect public/private repos
- Add test coverage for auth-related functionality
- Improve UI styling for auth-related indicators

* feat(git): implement interactive Git authentication with askpass

- Add GitAskpassService to handle credential requests from Git
- Implement askpass script that communicates with backend
- Update GitAuthService to use askpass instead of direct credential
  injection
- Add new endpoint for branch listing and status
- Improve branch name handling in GitBranchService
- Enhance error handling in GitDiffService for untracked files
- Add upstream branch checking and setup in GitFetchPullService
- Update UI components for better visual consistency
- Fix various minor UI styling issues

* feat(git): enhance Git authentication with improved askpass support

- Update askpass endpoint to handle hostname parameter and return full
  credential object
- Replace `createNoPromptGitEnv` with `createSilentGitEnv` for better
  VSCode compatibility
- Add compiled Node.js askpass script for broader compatibility
- Enhance GitBranchService to return detailed branch information with
  upstream tracking
- Improve branch listing UI with better sorting and display
- Update GitAuthService to use askpass for all operations with proper
  credential handling
- Fix various UI styling issues in diff view and source control panel
- Update test mocks to use new silent environment function
- Add proper error handling and credential caching in GitAskpassService

* feat(git-auth): implement IPC-based Git authentication system

- Add new IPC server infrastructure for handling Git credential requests
- Implement AskpassHandler to manage Git authentication through IPC
- Replace previous HTTP-based askpass system with local IPC
  communication
- Remove deprecated GitAskpassService and related HTTP endpoints
- Update GitAuthService to use IPC-based authentication flow
- Add new shell scripts for Git askpass integration (askpass.sh,
  askpass-main.js)
- Remove database column 'requires_auth' as it's no longer needed
- Update all Git service classes to use new authentication approach
- Improve error handling and credential caching
- Add proper cleanup for IPC server on shutdown

* fix(frontend): correct GitBranch type usage in BranchesTab and BranchSwitcher

* fix(ipc): handle empty responses and add logging for askpass handler

- Handle empty response bodies in askpass-main.ts to prevent JSON parse errors
- Add logging to IPC server for debugging request/response issues
- Add logging to AskpassHandler for credential lookup visibility

* fix(ipc): return empty credentials for silent fetches instead of failing

Silent fetch operations (used when fetching commit history on repo open)
should return empty credentials gracefully rather than failing, allowing
git to proceed without credentials for public repos or cached credentials.

* chore(ipc): add detailed logging for debugging askpass requests

- Log handler registration and lookup paths
- Log incoming request details
- Log handler response results

* chore(askpass): add comprehensive debugging to trace IPC communication

- Add detailed stderr logging to askpass-main.ts for all steps
- Log environment variables and paths at initialization
- Log IPC connection attempts and responses
- Log JSON parsing results

This will help trace where the IPC communication fails.

* chore(debug): add comprehensive logging to trace git environment and IPC requests

- Log GIT_ASKPASS, VSCODE_GIT_IPC_HANDLE, GIT_TERMINAL_PROMPT env vars when executing git
- Log all incoming IPC requests with URL and body
- Log handler registration status

* Integrate GitAuthService throughout repo operations

- Add GitAuthService parameter to all repo service functions
- Replace direct git env creation with GitAuthService.getGitEnvironment()
- Update route handlers to pass GitAuthService to service calls
- Remove createSilentGitEnv utility in favor of centralized auth
- Ensure consistent git authentication across all operations

* refactor: consolidate git services and remove duplicate fetch service

- Remove GitFetchService and consolidate into GitFetchPullService
- Clean up duplicate git authentication logic across services
- Simplify repo service by removing redundant environment handling
- Update tests to reflect consolidated service structure
- Remove unused imports and streamline API endpoints
- Reduce codebase complexity by eliminating service duplication

* refactor: clean up unnecessary config changes and improve git API types

* feat(git): add GitCommit interface and fix push mutation

* feat(git): fix source control panel issues

- Fix unstaged file diff showing all changes instead of working directory only
- Remove auto-refresh (10s) to reduce git command spam
- Add reset/revert mutation for unpushed local commits
- Fix branch creation/switching to update database
- Add unpushed commit detection and visual indicator in commits tab
- Handle no-upstream branch status gracefully

* fix(git): improve branch listing and remove regex parsing issue

- Fix branch name parsing to use full name instead of regex capturing only first word
- Add refresh button for branches
- Show remote branches with Globe icon and make them non-clickable
- Add 'local' label for branches without upstream tracking
- Handle remotes/ prefix properly in branch detection

* fix(git): remove duplicate refresh button

* fix(git): properly extract branch name from git output

- Extract branch name before whitespace/bracket in git branch -vv -a output
- When clicking remote branch, checkout local tracking branch instead of remote reference

* fix(git): remove duplicate refresh button from branches tab

* fix: improve source control panel mobile layout

- Set full height on mobile for better screen utilization
- Add larger centered close button on mobile
- Hide default close button when custom one is shown on mobile

* Remove git credential test feature

The test credential button in settings was broken because it tried to test
authentication against just the host URL (e.g., https://github.com/) instead
of a repository path. Since git credentials are already handled correctly
through the askpass mechanism when cloning repositories, the test button
was redundant and has been removed.

Changes:
- Remove /test-credential endpoint from settings routes
- Remove testGitCredential API from frontend
- Remove TestCredentialRequest/Response types
- Remove test button and related state from GitSettings component

* fix: resolve Copilot review issues

- Remove duplicate GitCommit interface definition
- Fix CSS typos: bg-linear-to-br -> bg-gradient-to-br
- Fix typo: /sessflex-shrink-0 -> flex-shrink-0
- Add *.test.js to .gitignore and remove compiled test files
- Fix missing closing brace in useGit.test.tsx
- Remove unused maskToken function

* fix(git): correct ahead/behind count order and add renamed file path parsing

- Fix git rev-list output parsing: ahead comes first, behind second
- Add oldPath extraction for renamed (R) and copied (C) files in status
- Refactor git service tests to use consistent mocking patterns
- Add missing Database and SettingsService mocks to prevent test failures

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
theepicsaxguyandChris Scott authored and GitHub committed 2026-01-19 22:03:42 -05:00
1 parent 524ce018dc
commit e91c54ba20
64 files changed
+6214 -1915

No files matched your search

@@ -1,142 +1,237 @@
import { useFileDiff } from '@/api/git'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, Plus, Minus, ArrowLeft, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { CopyButton } from '@/components/ui/copy-button'
import { cn } from '@/lib/utils'
import type { GitFileStatusType } from '@/types/git'
import { useFileDiff } from "@/api/git";
import {
Loader2,
FileText,
FilePlus,
FileX,
FileEdit,
File,
Plus,
Minus,
ArrowLeft,
ExternalLink,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { CopyButton } from "@/components/ui/copy-button";
import { cn } from "@/lib/utils";
import type { GitFileStatusType } from "@/types/git";
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from "@/lib/git-status-styles";
interface FileDiffViewProps {
repoId: number
filePath: string
onBack?: () => void
onOpenFile?: (path: string, lineNumber?: number) => void
isMobile?: boolean
repoId: number;
filePath: string;
includeStaged?: boolean;
onBack?: () => void;
onOpenFile?: (path: string, lineNumber?: number) => void;
isMobile?: boolean;
}
interface DiffLine {
type: 'add' | 'remove' | 'context' | 'header' | 'hunk'
content: string
oldLineNumber?: number
newLineNumber?: number
type: "add" | "remove" | "context" | "header" | "hunk";
content: string;
oldLineNumber?: number;
newLineNumber?: number;
}
function parseDiff(diff: string): DiffLine[] {
const lines = diff.split('\n')
const result: DiffLine[] = []
let oldLine = 0
let newLine = 0
const lines = diff.split("\n");
const result: DiffLine[] = [];
let oldLine = 0;
let newLine = 0;
for (const line of lines) {
if (line.startsWith('diff --git') || line.startsWith('index ') || line.startsWith('---') || line.startsWith('+++')) {
result.push({ type: 'header', content: line })
} else if (line.startsWith('@@')) {
const match = line.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/)
if (
line.startsWith("diff --git") ||
line.startsWith("index ") ||
line.startsWith("---") ||
line.startsWith("+++")
) {
result.push({ type: "header", content: line });
} else if (line.startsWith("@@")) {
const match = line.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (match) {
oldLine = parseInt(match[1], 10)
newLine = parseInt(match[2], 10)
oldLine = parseInt(match[1], 10);
newLine = parseInt(match[2], 10);
}
result.push({ type: 'hunk', content: line })
} else if (line.startsWith('+')) {
result.push({ type: 'add', content: line.substring(1), newLineNumber: newLine })
newLine++
} else if (line.startsWith('-')) {
result.push({ type: 'remove', content: line.substring(1), oldLineNumber: oldLine })
oldLine++
} else if (line.startsWith(' ') || line === '') {
result.push({ type: 'context', content: line.substring(1) || '', oldLineNumber: oldLine, newLineNumber: newLine })
oldLine++
newLine++
result.push({ type: "hunk", content: line });
} else if (line.startsWith("+")) {
result.push({
type: "add",
content: line.substring(1),
newLineNumber: newLine,
});
newLine++;
} else if (line.startsWith("-")) {
result.push({
type: "remove",
content: line.substring(1),
oldLineNumber: oldLine,
});
oldLine++;
} else if (line.startsWith(" ") || line === "") {
result.push({
type: "context",
content: line.substring(1) || "",
oldLineNumber: oldLine,
newLineNumber: newLine,
});
oldLine++;
newLine++;
}
}
return result
return result;
}
const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: string; bgColor: string; label: string }> = {
modified: { icon: FileEdit, color: 'text-yellow-500', bgColor: 'bg-yellow-500/10', label: 'Modified' },
added: { icon: FilePlus, color: 'text-green-500', bgColor: 'bg-green-500/10', label: 'Added' },
deleted: { icon: FileX, color: 'text-red-500', bgColor: 'bg-red-500/10', label: 'Deleted' },
renamed: { icon: FileText, color: 'text-blue-500', bgColor: 'bg-blue-500/10', label: 'Renamed' },
untracked: { icon: File, color: 'text-muted-foreground', bgColor: 'bg-muted/50', label: 'Untracked' },
copied: { icon: FileText, color: 'text-purple-500', bgColor: 'bg-purple-500/10', label: 'Copied' },
}
const statusConfig: Record<
GitFileStatusType,
{ icon: typeof FileText; color: string; bgColor: string; label: string }
> = {
modified: {
icon: FileEdit,
color: GIT_STATUS_COLORS.modified,
bgColor: "bg-amber-500/10",
label: GIT_STATUS_LABELS.modified,
},
added: {
icon: FilePlus,
color: GIT_STATUS_COLORS.added,
bgColor: "bg-emerald-500/10",
label: GIT_STATUS_LABELS.added,
},
deleted: {
icon: FileX,
color: GIT_STATUS_COLORS.deleted,
bgColor: "bg-rose-500/10",
label: GIT_STATUS_LABELS.deleted,
},
renamed: {
icon: FileText,
color: GIT_STATUS_COLORS.renamed,
bgColor: "bg-blue-500/10",
label: GIT_STATUS_LABELS.renamed,
},
untracked: {
icon: File,
color: GIT_STATUS_COLORS.untracked,
bgColor: "bg-muted/50",
label: GIT_STATUS_LABELS.untracked,
},
copied: {
icon: FileText,
color: GIT_STATUS_COLORS.copied,
bgColor: "bg-emerald-500/10",
label: GIT_STATUS_LABELS.copied,
},
};
function DiffLineComponent({ line, showLineNumbers, onLineClick }: { line: DiffLine; showLineNumbers: boolean; onLineClick?: (lineNumber: number) => void }) {
if (line.type === 'header') {
function DiffLineComponent({
line,
showLineNumbers,
onLineClick,
}: {
line: DiffLine;
showLineNumbers: boolean;
onLineClick?: (lineNumber: number) => void;
}) {
if (line.type === "header") {
return (
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate">
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate border-b border-border/30">
{line.content}
</div>
)
);
}
if (line.type === 'hunk') {
if (line.type === "hunk") {
return (
<div className="px-4 py-1 bg-blue-500/10 text-blue-600 dark:text-blue-400 text-xs font-mono">
<div className="px-4 py-1 bg-accent/20 text-accent-foreground text-xs font-mono border-b border-border/20">
{line.content}
</div>
)
);
}
const bgClass = line.type === 'add'
? 'bg-green-500/10'
: line.type === 'remove'
? 'bg-red-500/10'
: ''
const bgClass =
line.type === "add"
? "bg-emerald-500/10"
: line.type === "remove"
? "bg-rose-500/10"
: "";
const textClass = line.type === 'add'
? 'text-green-600 dark:text-green-400'
: line.type === 'remove'
? 'text-red-600 dark:text-red-400'
: 'text-foreground'
const textClass =
line.type === "add"
? "text-emerald-700 dark:text-emerald-300"
: line.type === "remove"
? "text-rose-700 dark:text-rose-300"
: "text-foreground";
const lineNumber = line.newLineNumber ?? line.oldLineNumber
const isClickable = onLineClick && lineNumber !== undefined
const lineNumber = line.newLineNumber ?? line.oldLineNumber;
const isClickable = onLineClick && lineNumber !== undefined;
return (
<div
<div
className={cn(
'flex font-mono text-sm',
"flex font-mono text-sm border-l-2 transition-colors",
bgClass,
isClickable && 'cursor-pointer hover:bg-accent/50 transition-colors'
line.type === "add" && "border-l-emerald-500",
line.type === "remove" && "border-l-rose-500",
line.type === "context" && "border-l-transparent",
isClickable && "cursor-pointer hover:bg-accent/30",
)}
onClick={() => isClickable && lineNumber !== undefined && onLineClick(lineNumber)}
onClick={() =>
isClickable && lineNumber !== undefined && onLineClick(lineNumber)
}
>
{showLineNumbers && (
<div className="flex-shrink-0 w-20 flex text-xs text-muted-foreground select-none">
<div className="flex-shrink-0 w-20 flex text-xs text-muted-foreground bg-muted/30 select-none">
<span className="w-10 px-2 text-right border-r border-border/50">
{line.oldLineNumber || ''}
{line.oldLineNumber || ""}
</span>
<span className="w-10 px-2 text-right border-r border-border/50">
{line.newLineNumber || ''}
{line.newLineNumber || ""}
</span>
</div>
)}
<div className="w-6 flex-shrink-0 flex items-center justify-center">
{line.type === 'add' && <Plus className="w-3 h-3 text-green-500" />}
{line.type === 'remove' && <Minus className="w-3 h-3 text-red-500" />}
<div className="w-6 flex-shrink-0 flex items-center justify-center bg-muted/20">
{line.type === "add" && (
<Plus className="w-3 h-3 text-emerald-600 dark:text-emerald-400" />
)}
{line.type === "remove" && (
<Minus className="w-3 h-3 text-rose-600 dark:text-rose-400" />
)}
</div>
<pre className={cn('flex-1 px-2 py-0.5 whitespace-pre-wrap break-all', textClass)}>
{line.content || ' '}
<pre
className={cn(
"flex-1 px-2 py-0.5 whitespace-pre-wrap break-words",
textClass,
)}
>
{line.content || " "}
</pre>
</div>
)
);
}
export function FileDiffView({ repoId, filePath, onBack, onOpenFile, isMobile = false }: FileDiffViewProps) {
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath)
export function FileDiffView({
repoId,
filePath,
includeStaged,
onBack,
onOpenFile,
isMobile = false,
}: FileDiffViewProps) {
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath, includeStaged);
const fileName = filePath.split('/').pop() || filePath
const dirPath = filePath.includes('/') ? filePath.substring(0, filePath.lastIndexOf('/')) : ''
const fileName = filePath.split("/").pop() || filePath;
const dirPath = filePath.includes("/")
? filePath.substring(0, filePath.lastIndexOf("/"))
: "";
if (isLoading) {
return (
<div className="flex items-center justify-center h-full py-8">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
)
);
}
if (error) {
@@ -152,26 +247,36 @@ export function FileDiffView({ repoId, filePath, onBack, onOpenFile, isMobile =
</Button>
)}
</div>
)
);
}
if (!diffData) {
return null
return null;
}
const config = statusConfig[diffData.status]
const Icon = config.icon
const diffLines = diffData.diff ? parseDiff(diffData.diff) : []
const config = statusConfig[diffData.status];
const Icon = config.icon;
const diffLines = diffData.diff ? parseDiff(diffData.diff) : [];
return (
<div className="flex flex-col h-full bg-background">
<div className={cn('flex items-center gap-2 px-3 py-2 border-b border-border flex-shrink-0', config.bgColor)}>
<div
className={cn(
"flex items-center gap-2 px-3 py-2 border-b border-border flex-shrink-0",
config.bgColor,
)}
>
{onBack && (
<Button variant="ghost" size="sm" onClick={onBack} className="h-7 w-7 p-0 mr-1">
<Button
variant="ghost"
size="sm"
onClick={onBack}
className="h-7 w-7 p-0 mr-1"
>
<ArrowLeft className="w-4 h-4" />
</Button>
)}
<Icon className={cn('w-4 h-4 flex-shrink-0', config.color)} />
<Icon className={cn("w-4 h-4 flex-shrink-0", config.color)} />
<div className="flex-1 min-w-0">
{onOpenFile ? (
<button
@@ -182,17 +287,33 @@ export function FileDiffView({ repoId, filePath, onBack, onOpenFile, isMobile =
{fileName}
<ExternalLink className="w-3 h-3 opacity-0 group-hover:opacity-100 transition-opacity" />
</div>
{dirPath && <div className="text-xs text-muted-foreground truncate">{dirPath}</div>}
{dirPath && (
<div className="text-xs text-muted-foreground truncate">
{dirPath}
</div>
)}
</button>
) : (
<>
<div className="text-sm font-medium text-foreground truncate">{fileName}</div>
{dirPath && <div className="text-xs text-muted-foreground truncate">{dirPath}</div>}
<div className="text-sm font-medium text-foreground truncate">
{fileName}
</div>
{dirPath && (
<div className="text-xs text-muted-foreground truncate">
{dirPath}
</div>
)}
</>
)}
</div>
<div className="flex items-center gap-2 text-xs flex-shrink-0">
<span className={cn('px-1.5 py-0.5 rounded', config.bgColor, config.color)}>
<span
className={cn(
"px-1.5 py-0.5 rounded",
config.bgColor,
config.color,
)}
>
{config.label}
</span>
{!diffData.isBinary && (
@@ -201,32 +322,44 @@ export function FileDiffView({ repoId, filePath, onBack, onOpenFile, isMobile =
<span className="text-red-500">-{diffData.deletions}</span>
</>
)}
{diffData.diff && <CopyButton content={diffData.diff || ''} title="Copy diff" iconSize="sm" variant="ghost" className="flex-shrink-0" />}
{diffData.diff && (
<CopyButton
content={diffData.diff || ""}
title="Copy diff"
iconSize="sm"
variant="ghost"
className="flex-shrink-0"
/>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto min-h-0 ">
<div className="flex-1 overflow-y-auto min-h-0">
{diffData.isBinary ? (
<div className="flex items-center justify-center h-full text-muted-foreground">
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
<p className="text-sm">Binary file - cannot display diff</p>
</div>
) : !diffData.diff ? (
<div className="flex items-center justify-center h-full text-muted-foreground">
<div className="flex items-center justify-center h-full text-muted-foreground bg-muted/20">
<p className="text-sm">No changes to display</p>
</div>
) : (
<div className="divide-y divide-border/30 pb-32">
<div className="border-t border-border/30">
{diffLines.map((line, index) => (
<DiffLineComponent
key={index}
line={line}
<DiffLineComponent
key={index}
line={line}
showLineNumbers={!isMobile}
onLineClick={onOpenFile ? (lineNum) => onOpenFile(filePath, lineNum) : undefined}
onLineClick={
onOpenFile
? (lineNum) => onOpenFile(filePath, lineNum)
: undefined
}
/>
))}
</div>
)}
</div>
</div>
)
);
}
@@ -0,0 +1,74 @@
import { GitBranch, Loader2 } from 'lucide-react'
import { cn } from '@/lib/utils'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
interface GitBranchSelectorProps {
repoId: number | undefined
branch: string | null
branches: string[]
onBranchChange: (branch: string) => void
isLoading?: boolean
error?: Error | null
ahead?: number
behind?: number
}
export function GitBranchSelector({ branch, branches, onBranchChange, isLoading, error, ahead, behind }: GitBranchSelectorProps) {
if (isLoading) {
return (
<div className="flex items-center gap-2 px-3 py-2">
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground" />
<span className="text-sm text-muted-foreground">Loading branches...</span>
</div>
)
}
if (error) {
return (
<div className="flex items-center gap-2 px-3 py-2">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<span className="text-sm text-red-500">Failed to load branches</span>
</div>
)
}
if (!branch || branches.length === 0) {
return (
<div className="flex items-center gap-2 px-3 py-2">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<span className="text-sm text-muted-foreground">No branches available</span>
</div>
)
}
const getBranchLabel = (branchName: string, isCurrent: boolean) => {
if (!isCurrent) return branchName
const parts = [branchName]
if (ahead && ahead > 0) parts.push(`${ahead} ahead`)
if (behind && behind > 0) parts.push(`${behind} behind`)
return parts.join(' ')
}
return (
<Select value={branch} onValueChange={onBranchChange}>
<SelectTrigger className="w-full h-auto py-1.5">
<div className="flex items-center gap-2 flex-1">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<SelectValue placeholder="Select branch" />
</div>
</SelectTrigger>
<SelectContent>
{branches.map((branchName) => (
<SelectItem key={branchName} value={branchName}>
<div className="flex items-center gap-2">
<GitBranch className="w-3 h-3 text-muted-foreground" />
<span className={cn(branchName === branch && 'font-medium')}>
{getBranchLabel(branchName, branchName === branch)}
</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)
}
@@ -1,357 +0,0 @@
import { useState, useMemo } from 'react'
import { useGitStatus } from '@/api/git'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, ChevronRight, ChevronDown, ArrowUp, ArrowDown, Folder, FolderOpen } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { GitFileStatus, GitFileStatusType } from '@/types/git'
interface GitChangesPanelProps {
repoId: number
onFileSelect: (path: string) => void
selectedFile?: string
}
interface GitTreeNode {
name: string
path: string
isDirectory: boolean
children: GitTreeNode[]
file?: GitFileStatus
fileCount: number
statusCounts: Partial<Record<GitFileStatusType, number>>
}
const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: string; label: string }> = {
modified: { icon: FileEdit, color: 'text-yellow-500', label: 'Modified' },
added: { icon: FilePlus, color: 'text-green-500', label: 'Added' },
deleted: { icon: FileX, color: 'text-red-500', label: 'Deleted' },
renamed: { icon: FileText, color: 'text-blue-500', label: 'Renamed' },
untracked: { icon: File, color: 'text-muted-foreground', label: 'Untracked' },
copied: { icon: FileText, color: 'text-purple-500', label: 'Copied' },
}
function buildTree(files: GitFileStatus[]): GitTreeNode[] {
const root: GitTreeNode[] = []
const nodeMap = new Map<string, GitTreeNode>()
for (const file of files) {
const isDirectoryPath = file.path.endsWith('/')
const cleanPath = isDirectoryPath ? file.path.slice(0, -1) : file.path
const parts = cleanPath.split('/').filter(p => p)
if (parts.length === 0) continue
let currentPath = ''
let currentLevel = root
for (let i = 0; i < parts.length; i++) {
const part = parts[i]
const isLast = i === parts.length - 1
currentPath = currentPath ? `${currentPath}/${part}` : part
let node = nodeMap.get(currentPath)
if (!node) {
const isDir = !isLast || isDirectoryPath
node = {
name: part,
path: currentPath,
isDirectory: isDir,
children: [],
file: (isLast && !isDirectoryPath) ? file : undefined,
fileCount: 0,
statusCounts: isDirectoryPath && isLast ? { [file.status]: 1 } : {},
}
nodeMap.set(currentPath, node)
currentLevel.push(node)
} else if (isLast && isDirectoryPath) {
node.statusCounts[file.status] = (node.statusCounts[file.status] || 0) + 1
}
if (isLast && !isDirectoryPath) {
node.file = file
node.isDirectory = false
}
currentLevel = node.children
}
}
function aggregateCounts(node: GitTreeNode): void {
if (node.isDirectory) {
const existingCounts = { ...node.statusCounts }
node.fileCount = 0
node.statusCounts = {}
if (node.children.length === 0) {
node.statusCounts = existingCounts
node.fileCount = Object.values(existingCounts).reduce((a, b) => a + (b || 0), 0) || 1
} else {
for (const child of node.children) {
aggregateCounts(child)
node.fileCount += child.isDirectory ? child.fileCount : 1
for (const [status, count] of Object.entries(child.statusCounts)) {
node.statusCounts[status as GitFileStatusType] =
(node.statusCounts[status as GitFileStatusType] || 0) + (count as number)
}
if (child.file) {
node.statusCounts[child.file.status] =
(node.statusCounts[child.file.status] || 0) + 1
}
}
}
}
}
function sortNodes(nodes: GitTreeNode[]): GitTreeNode[] {
return nodes.sort((a, b) => {
if (a.isDirectory && !b.isDirectory) return -1
if (!a.isDirectory && b.isDirectory) return 1
return a.name.localeCompare(b.name)
}).map(node => ({
...node,
children: sortNodes(node.children)
}))
}
for (const node of root) {
aggregateCounts(node)
}
return sortNodes(root)
}
function filterTree(nodes: GitTreeNode[], filter: GitFileStatusType | 'all'): GitTreeNode[] {
if (filter === 'all') return nodes
return nodes
.map(node => {
if (node.isDirectory) {
const filteredChildren = filterTree(node.children, filter)
if (filteredChildren.length === 0) return null
return { ...node, children: filteredChildren }
}
return node.file?.status === filter ? node : null
})
.filter((node): node is GitTreeNode => node !== null)
}
interface GitTreeNodeItemProps {
node: GitTreeNode
level: number
selectedFile?: string
expandedPaths: Set<string>
onToggle: (path: string) => void
onSelect: (path: string) => void
}
function GitTreeNodeItem({ node, level, selectedFile, expandedPaths, onToggle, onSelect }: GitTreeNodeItemProps) {
const isExpanded = expandedPaths.has(node.path)
const isSelected = selectedFile === node.path
if (node.isDirectory) {
const statusEntries = Object.entries(node.statusCounts) as [GitFileStatusType, number][]
const dominantStatus = statusEntries.length > 0
? statusEntries.reduce((a, b) => a[1] > b[1] ? a : b)[0]
: null
return (
<div>
<button
onClick={() => onToggle(node.path)}
className={cn(
'w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-accent/50 transition-colors rounded-md'
)}
style={{ paddingLeft: `${level * 12 + 12}px` }}
>
<span className="w-4 h-4 flex items-center justify-center flex-shrink-0">
{isExpanded ? (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
)}
</span>
{isExpanded ? (
<FolderOpen className="w-4 h-4 text-muted-foreground flex-shrink-0" />
) : (
<Folder className="w-4 h-4 text-muted-foreground flex-shrink-0" />
)}
<span className="text-sm text-foreground truncate flex-1">{node.name}</span>
<div className="flex items-center gap-1 flex-shrink-0">
{dominantStatus && (
<span className={cn('text-[10px] px-1 py-0.5 rounded', statusConfig[dominantStatus].color)}>
{node.fileCount}
</span>
)}
</div>
</button>
{isExpanded && (
<div>
{node.children.map(child => (
<GitTreeNodeItem
key={child.path}
node={child}
level={level + 1}
selectedFile={selectedFile}
expandedPaths={expandedPaths}
onToggle={onToggle}
onSelect={onSelect}
/>
))}
</div>
)}
</div>
)
}
const file = node.file!
const config = statusConfig[file.status]
const Icon = config.icon
return (
<button
onClick={() => onSelect(node.path)}
className={cn(
'w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-accent/50 transition-colors rounded-md',
isSelected && 'bg-accent'
)}
style={{ paddingLeft: `${level * 12 + 12}px` }}
>
<span className="w-4 h-4 flex-shrink-0" />
<Icon className={cn('w-4 h-4 flex-shrink-0', config.color)} />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1">
<span className="text-sm text-foreground truncate">{node.name}</span>
{file.staged && (
<span className="text-[10px] px-1 py-0.5 bg-green-500/20 text-green-500 rounded">staged</span>
)}
</div>
{file.oldPath && (
<span className="text-xs text-muted-foreground truncate block">← {file.oldPath}</span>
)}
</div>
<ChevronRight className="w-4 h-4 text-muted-foreground flex-shrink-0" />
</button>
)
}
export function GitChangesPanel({ repoId, onFileSelect, selectedFile }: GitChangesPanelProps) {
const { data: status, isLoading, error } = useGitStatus(repoId)
const [filter, setFilter] = useState<GitFileStatusType | 'all'>('all')
const [expandedPaths, setExpandedPaths] = useState<Set<string>>(new Set())
const tree = useMemo(() => {
if (!status?.files) return []
return buildTree(status.files)
}, [status?.files])
const filteredTree = useMemo(() => {
return filterTree(tree, filter)
}, [tree, filter])
const handleToggle = (path: string) => {
setExpandedPaths(prev => {
const next = new Set(prev)
if (next.has(path)) {
next.delete(path)
} else {
next.add(path)
}
return next
})
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-8">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="text-center py-8 text-muted-foreground">
<p className="text-sm">Failed to load git status</p>
<p className="text-xs mt-1">{error.message}</p>
</div>
)
}
if (!status || !status.hasChanges) {
return (
<div className="text-center py-8 text-muted-foreground">
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No uncommitted changes</p>
</div>
)
}
const statusCounts = status.files.reduce((acc, file) => {
acc[file.status] = (acc[file.status] || 0) + 1
return acc
}, {} as Record<string, number>)
return (
<div className="flex flex-col h-full">
<div className="px-3 py-2 border-b border-border flex-shrink-0">
<div className="flex items-center justify-between mb-2">
<span className="text-sm font-medium text-foreground">{status.branch}</span>
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{status.ahead > 0 && (
<span className="flex items-center gap-0.5">
<ArrowUp className="w-3 h-3" />
{status.ahead}
</span>
)}
{status.behind > 0 && (
<span className="flex items-center gap-0.5">
<ArrowDown className="w-3 h-3" />
{status.behind}
</span>
)}
</div>
</div>
<div className="flex flex-wrap gap-1">
<button
onClick={() => setFilter('all')}
className={cn(
'text-xs px-2 py-0.5 rounded transition-colors',
filter === 'all' ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/50'
)}
>
All ({status.files.length})
</button>
{Object.entries(statusCounts).map(([statusKey, count]) => {
const config = statusConfig[statusKey as GitFileStatusType]
return (
<button
key={statusKey}
onClick={() => setFilter(statusKey as GitFileStatusType)}
className={cn(
'text-xs px-2 py-0.5 rounded transition-colors',
filter === statusKey ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/50'
)}
>
<span className={config.color}>{config.label}</span> ({count})
</button>
)
})}
</div>
</div>
<div className="flex-1 overflow-y-auto p-2">
<div className="space-y-0.5 pb-8">
{filteredTree.map((node) => (
<GitTreeNodeItem
key={node.path}
node={node}
level={0}
selectedFile={selectedFile}
expandedPaths={expandedPaths}
onToggle={handleToggle}
onSelect={onFileSelect}
/>
))}
</div>
</div>
</div>
)
}
@@ -1,183 +0,0 @@
import { useState, useEffect, useRef } from 'react'
import { createPortal } from 'react-dom'
import { GitChangesPanel } from './GitChangesPanel'
import { FileDiffView } from './FileDiffView'
import { FilePreviewDialog } from './FilePreviewDialog'
import { FullscreenSheet, FullscreenSheetHeader, FullscreenSheetContent } from '@/components/ui/fullscreen-sheet'
import { Button } from '@/components/ui/button'
import { X, GitBranch } from 'lucide-react'
import { useMobile, useSwipeBack } from '@/hooks/useMobile'
import { useQueryClient } from '@tanstack/react-query'
import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from '@/lib/utils'
interface GitChangesSheetProps {
isOpen: boolean
onClose: () => void
repoId: number
currentBranch: string
repoLocalPath?: string
}
export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch, repoLocalPath }: GitChangesSheetProps) {
const [selectedFile, setSelectedFile] = useState<string | undefined>()
const [previewFilePath, setPreviewFilePath] = useState<string | null>(null)
const [previewLineNumber, setPreviewLineNumber] = useState<number | undefined>()
const isMobile = useMobile()
const queryClient = useQueryClient()
const contentRef = useRef<HTMLDivElement>(null)
const { bind: bindSwipe, swipeStyles } = useSwipeBack(
selectedFile ? () => setSelectedFile(undefined) : onClose,
{ enabled: isOpen && !previewFilePath }
)
useEffect(() => {
return bindSwipe(contentRef.current)
}, [bindSwipe])
useEffect(() => {
if (!isOpen) {
setSelectedFile(undefined)
setPreviewFilePath(null)
}
}, [isOpen])
const handleFileSelect = (path: string) => {
setSelectedFile(path)
}
const handleBack = () => {
setSelectedFile(undefined)
}
const handleOpenFile = (path: string, lineNumber?: number) => {
setPreviewFilePath(path)
setPreviewLineNumber(lineNumber)
}
const handleClosePreview = () => {
setPreviewFilePath(null)
setPreviewLineNumber(undefined)
}
const handleFileSaved = () => {
queryClient.invalidateQueries({ queryKey: ['gitStatus'] })
queryClient.invalidateQueries({ queryKey: ['fileDiff'] })
}
const [shouldRender, setShouldRender] = useState(false)
useEffect(() => {
if (isOpen) {
setShouldRender(true)
document.body.style.overflow = 'hidden'
} else {
const timer = setTimeout(() => setShouldRender(false), MODAL_TRANSITION_MS)
document.body.style.overflow = 'unset'
return () => clearTimeout(timer)
}
return () => {
document.body.style.overflow = 'unset'
}
}, [isOpen])
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isOpen) {
onClose()
}
}
document.addEventListener('keydown', handleEscape)
return () => document.removeEventListener('keydown', handleEscape)
}, [isOpen, onClose])
if (!isOpen && !shouldRender) return null
return createPortal(
<div
ref={contentRef}
className="fixed inset-0 z-50"
style={{
opacity: isOpen ? 1 : 0,
pointerEvents: isOpen ? 'auto' : 'none',
transition: 'opacity 150ms ease-out',
}}
>
<FullscreenSheet style={{ ...GPU_ACCELERATED_STYLE, ...swipeStyles }}>
<FullscreenSheetHeader className="px-4 py-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4 text-foreground" />
<h2 className="text-sm font-semibold text-foreground">
{selectedFile ? 'File Changes' : 'Git Changes'}
</h2>
<span className="text-xs text-muted-foreground">({currentBranch})</span>
</div>
<Button
variant="ghost"
size="icon"
onClick={onClose}
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-all duration-200 h-8 w-8"
>
<X className="w-4 h-4" />
</Button>
</div>
</FullscreenSheetHeader>
<FullscreenSheetContent>
{isMobile ? (
selectedFile ? (
<FileDiffView
repoId={repoId}
filePath={selectedFile}
onBack={handleBack}
onOpenFile={handleOpenFile}
isMobile={true}
/>
) : (
<GitChangesPanel
repoId={repoId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
)
) : (
<div className="flex h-full">
<div className="w-[280px] border-r border-border overflow-hidden flex-shrink-0">
<GitChangesPanel
repoId={repoId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
<div className="flex-1 overflow-hidden min-w-0">
{selectedFile ? (
<FileDiffView
repoId={repoId}
filePath={selectedFile}
onOpenFile={handleOpenFile}
isMobile={false}
/>
) : (
<div className="flex items-center justify-center h-full text-muted-foreground">
<p className="text-sm">Select a file to view changes</p>
</div>
)}
</div>
</div>
)}
</FullscreenSheetContent>
<FilePreviewDialog
isOpen={!!previewFilePath}
onClose={handleClosePreview}
filePath={previewFilePath || ''}
repoBasePath={repoLocalPath}
onFileSaved={handleFileSaved}
initialLineNumber={previewLineNumber}
/>
</FullscreenSheet>
</div>,
document.body
)
}
+17 -50
View File
@@ -7,11 +7,10 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { GitBranch, Check, Plus, GitCommit, Loader2 } from "lucide-react";
import { GitBranch, Check, Plus, Loader2 } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { listBranches, switchBranch, GitAuthError } from "@/api/repos";
import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog";
import { GitChangesSheet } from "@/components/file-browser/GitChangesSheet";
import { showToast } from "@/lib/toast";
interface BranchSwitcherProps {
@@ -19,14 +18,12 @@ interface BranchSwitcherProps {
currentBranch: string;
isWorktree?: boolean;
repoUrl?: string | null;
repoLocalPath?: string;
className?: string;
iconOnly?: boolean;
}
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, repoLocalPath, className, iconOnly }: BranchSwitcherProps) {
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, className, iconOnly }: BranchSwitcherProps) {
const [addBranchOpen, setAddBranchOpen] = useState(false);
const [gitChangesOpen, setGitChangesOpen] = useState(false);
const queryClient = useQueryClient();
const { data: branches, isLoading: branchesLoading, refetch: refetchBranches } = useQuery({
@@ -36,7 +33,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
staleTime: Infinity,
});
const activeBranch = branches?.current ?? currentBranch;
const activeBranch = branches?.branches?.find(b => b.current)?.name ?? currentBranch;
const handleDropdownOpenChange = useCallback((open: boolean) => {
if (open && repoId) {
@@ -81,40 +78,18 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
{!iconOnly && <span className="truncate">{activeBranch}</span>}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent sideOffset={0} align="end" className="bg-card border-border min-w-[200px] max-w-[95vw] sm:max-w-none">
<DropdownMenuContent sideOffset={0} align="end" className="bg-card border-border min-w-50 max-w-[95vw] sm:max-w-none">
{isWorktree ? (
<>
<DropdownMenuItem disabled className="text-muted-foreground">
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">Worktree: {activeBranch}</span>
</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setGitChangesOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitCommit className="w-3 h-3" />
<span className="flex-1">View Changes</span>
</div>
</DropdownMenuItem>
</>
<DropdownMenuItem disabled className="text-muted-foreground">
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">Worktree: {activeBranch}</span>
</div>
</DropdownMenuItem>
) : (
<>
<DropdownMenuItem
onClick={() => setGitChangesOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitCommit className="w-3 h-3" />
<span className="flex-1">View Changes</span>
</div>
</DropdownMenuItem>
{repoUrl && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setAddBranchOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
@@ -124,26 +99,26 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
<span className="flex-1">Add Branch</span>
</div>
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
<DropdownMenuSeparator />
<div className="max-h-[60vh] overflow-y-auto w-full">
{branchesLoading && !branches ? (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
</DropdownMenuItem>
) : branches?.all && branches.all.length > 0 ? (
branches.all.map((branch: string) => (
) : branches?.branches && branches.branches.length > 0 ? (
branches.branches.filter(b => b.type === 'local').map((branch) => (
<DropdownMenuItem
key={branch}
onClick={() => switchBranchMutation.mutate(branch)}
key={branch.name}
onClick={() => switchBranchMutation.mutate(branch.name)}
disabled={switchBranchMutation.isPending}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">{branch}</span>
{branch === activeBranch && <Check className="w-3 h-3 text-green-500" />}
<span className="flex-1">{branch.name}</span>
{branch.name === activeBranch && <Check className="w-3 h-3 text-green-500" />}
</div>
</DropdownMenuItem>
))
@@ -166,14 +141,6 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
repoId={repoId}
/>
)}
<GitChangesSheet
isOpen={gitChangesOpen}
onClose={() => setGitChangesOpen(false)}
repoId={repoId}
currentBranch={activeBranch}
repoLocalPath={repoLocalPath}
/>
</>
);
}
+33 -3
View File
@@ -2,10 +2,11 @@ import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Checkbox } from "@/components/ui/checkbox";
import { Loader2, Trash2, Download, GitBranch, FolderOpen } from "lucide-react";
import { Loader2, Trash2, Download, GitBranch, FolderOpen, AlertCircle } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { downloadRepo } from "@/api/repos";
import { showToast } from "@/lib/toast";
import type { GitStatusResponse } from "@/types/git";
import { BranchSwitcher } from "./BranchSwitcher";
@@ -24,6 +25,7 @@ interface RepoCardProps {
isDeleting: boolean;
isSelected?: boolean;
onSelect?: (id: number, selected: boolean) => void;
gitStatus?: GitStatusResponse;
}
export function RepoCard({
@@ -32,6 +34,7 @@ export function RepoCard({
isDeleting,
isSelected = false,
onSelect,
gitStatus,
}: RepoCardProps) {
const navigate = useNavigate();
const [isDownloading, setIsDownloading] = useState(false);
@@ -39,10 +42,16 @@ export function RepoCard({
const repoName = repo.repoUrl
? repo.repoUrl.split("/").slice(-1)[0].replace(".git", "")
: repo.localPath || "Local Repo";
const branchToDisplay = repo.currentBranch || repo.branch;
const branchToDisplay = gitStatus?.branch || repo.currentBranch || repo.branch;
const isReady = repo.cloneStatus === "ready";
const isCloning = repo.cloneStatus === "cloning";
const isDirty = gitStatus?.hasChanges || false;
const ahead = gitStatus?.ahead || 0;
const behind = gitStatus?.behind || 0;
const stagedCount = gitStatus?.files.filter((f) => f.staged).length || 0;
const unstagedCount = gitStatus?.files.filter((f) => !f.staged).length || 0;
const handleCardClick = () => {
if (isReady) {
navigate(`/repos/${repo.id}`);
@@ -84,6 +93,9 @@ export function RepoCard({
<h3 className="font-semibold text-base text-foreground truncate">
{repoName}
</h3>
{isReady && (
<div className={`w-2 h-2 rounded-full shrink-0 ${isDirty ? 'bg-orange-500' : 'bg-green-500'}`} />
)}
{repo.isWorktree && (
<Badge variant="secondary" className="text-xs px-1.5 py-0 shrink-0">
worktree
@@ -105,6 +117,25 @@ export function RepoCard({
<GitBranch className="w-3.5 h-3.5" />
{branchToDisplay || "main"}
</span>
{isDirty && (
<span className="flex items-center gap-1.5 text-orange-600 dark:text-orange-400">
<AlertCircle className="w-3.5 h-3.5" />
<span className="text-xs">
{unstagedCount > 0 && `${unstagedCount} unstaged`}
{unstagedCount > 0 && stagedCount > 0 && ", "}
{stagedCount > 0 && `${stagedCount} staged`}
</span>
</span>
)}
{(ahead > 0 || behind > 0) && (
<span className="flex items-center gap-1.5 text-blue-600 dark:text-blue-400">
<span className="text-xs">
{ahead > 0 && `${ahead} ahead`}
{ahead > 0 && behind > 0 && ", "}
{behind > 0 && `${behind} behind`}
</span>
</span>
)}
{repo.isLocal && (
<span className="flex items-center gap-1">
<FolderOpen className="w-3.5 h-3.5" />
@@ -121,7 +152,6 @@ export function RepoCard({
currentBranch={branchToDisplay || ""}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
repoLocalPath={repo.localPath}
iconOnly={true}
className="h-8 w-8"
/>
+14
View File
@@ -4,10 +4,12 @@ import { DndContext, closestCenter, KeyboardSensor, PointerSensor, TouchSensor,
import { arrayMove, SortableContext, sortableKeyboardCoordinates, verticalListSortingStrategy, useSortable } from "@dnd-kit/sortable"
import { CSS } from "@dnd-kit/utilities"
import { listRepos, deleteRepo, updateRepoOrder } from "@/api/repos"
import { fetchReposGitStatus } from "@/api/git"
import { DeleteDialog } from "@/components/ui/delete-dialog"
import { ListToolbar } from "@/components/ui/list-toolbar"
import { GitBranch, Search, GripVertical } from "lucide-react"
import type { Repo } from "@/api/types"
import type { GitStatusResponse } from "@/types/git"
import { RepoCard } from "./RepoCard"
import { RepoCardSkeleton } from "./RepoCardSkeleton"
@@ -17,12 +19,14 @@ function SortableRepoCard({
isDeleting,
isSelected,
onSelect,
gitStatus,
}: {
repo: Repo
onDelete: (id: number) => void
isDeleting: boolean
isSelected: boolean
onSelect: (id: number, selected: boolean) => void
gitStatus?: GitStatusResponse
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: repo.id })
@@ -45,6 +49,7 @@ function SortableRepoCard({
isDeleting={isDeleting}
isSelected={isSelected}
onSelect={onSelect}
gitStatus={gitStatus}
/>
</div>
</div>
@@ -68,6 +73,14 @@ export function RepoList() {
queryFn: listRepos,
})
const repoIds = repos?.map((repo) => repo.id) || []
const { data: gitStatuses } = useQuery({
queryKey: ["reposGitStatus", repoIds],
queryFn: () => fetchReposGitStatus(repoIds),
enabled: repoIds.length > 0,
})
const deleteMutation = useMutation({
mutationFn: deleteRepo,
onSuccess: () => {
@@ -297,6 +310,7 @@ export function RepoList() {
}
isSelected={selectedRepos.has(repo.id)}
onSelect={handleSelectRepo}
gitStatus={gitStatuses?.get(repo.id)}
/>
))}
</div>
@@ -0,0 +1,137 @@
import { useState, useEffect } from 'react'
import { Loader2 } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { showToast } from '@/lib/toast'
import type { GitCredential } from '@/api/types/settings'
interface GitCredentialDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSave: (credential: GitCredential) => Promise<void>
credential?: GitCredential
isSaving: boolean
}
export function GitCredentialDialog({ open, onOpenChange, onSave, credential, isSaving }: GitCredentialDialogProps) {
const [formData, setFormData] = useState<GitCredential>({
name: '',
host: '',
token: '',
username: '',
})
const maskToken = (token: string) => {
if (!token) return ''
if (token.length <= 8) return '•'.repeat(token.length)
return token.slice(0, 8) + '...'
}
useEffect(() => {
if (open) {
if (credential) {
setFormData({
...credential,
token: maskToken(credential.token)
})
} else {
setFormData({ name: '', host: '', token: '', username: '' })
}
}
}, [open, credential])
const handleSubmit = async (event?: React.MouseEvent) => {
event?.preventDefault()
event?.stopPropagation()
if (!formData.name.trim() || !formData.host.trim() || !formData.token.trim()) {
showToast.error('Please fill in all required fields')
return
}
try {
await onSave(formData)
setFormData({ name: '', host: '', token: '', username: '' })
onOpenChange(false)
} catch {
showToast.error('Failed to save credential')
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle>{credential ? 'Edit Git Credential' : 'Add Git Credential'}</DialogTitle>
</DialogHeader>
<form onSubmit={(e) => { e.preventDefault(); handleSubmit(); }} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="cred-name">Name *</Label>
<Input
id="cred-name"
placeholder="GitHub Personal, Work GitLab"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
disabled={isSaving}
/>
</div>
<div className="space-y-2">
<Label htmlFor="cred-host">Host URL *</Label>
<Input
id="cred-host"
placeholder="https://github.com/"
value={formData.host}
onChange={(e) => setFormData({ ...formData, host: e.target.value })}
disabled={isSaving}
/>
</div>
<div className="space-y-2">
<Label htmlFor="cred-token">Access Token *</Label>
<Input
id="cred-token"
type="password"
placeholder="Personal access token"
value={formData.token}
onChange={(e) => setFormData({ ...formData, token: e.target.value })}
disabled={isSaving}
/>
</div>
<div className="space-y-2">
<Label htmlFor="cred-username">Username (optional)</Label>
<Input
id="cred-username"
placeholder="Auto-detected if empty"
value={formData.username || ''}
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
disabled={isSaving}
/>
</div>
<div className="flex justify-end gap-2 pt-4">
<Button
type="button"
variant="outline"
onClick={() => onOpenChange(false)}
disabled={isSaving}
>
Cancel
</Button>
<Button
type="submit"
disabled={isSaving || !formData.name.trim() || !formData.host.trim() || !formData.token.trim()}
>
{isSaving && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{credential ? 'Update' : 'Add'}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
)
}
+203 -201
View File
@@ -1,10 +1,11 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2, Plus, Trash2, Save } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Button } from '@/components/ui/button'
import { Loader2, Plus, Trash2, Save, ChevronDown, ChevronRight, User, Key, Pencil } from 'lucide-react'
import { showToast } from '@/lib/toast'
import { GitCredentialDialog } from './GitCredentialDialog'
import { Label } from '@/components/ui/label'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import type { GitCredential, GitIdentity } from '@/api/types/settings'
export function GitSettings() {
@@ -12,82 +13,73 @@ export function GitSettings() {
const [gitCredentials, setGitCredentials] = useState<GitCredential[]>([])
const [gitIdentity, setGitIdentity] = useState<GitIdentity>({ name: '', email: '' })
const [isSaving, setIsSaving] = useState(false)
const [hasCredentialChanges, setHasCredentialChanges] = useState(false)
const [hasIdentityChanges, setHasIdentityChanges] = useState(false)
const [hasChanges, setHasChanges] = useState(false)
const [isCredentialDialogOpen, setIsCredentialDialogOpen] = useState(false)
const [editingCredentialIndex, setEditingCredentialIndex] = useState<number | null>(null)
const [identityExpanded, setIdentityExpanded] = useState(true)
const [credentialsExpanded, setCredentialsExpanded] = useState(true)
useEffect(() => {
if (preferences) {
setGitCredentials(preferences.gitCredentials || [])
setGitIdentity(preferences.gitIdentity || { name: '', email: '' })
setHasCredentialChanges(false)
setHasIdentityChanges(false)
setHasChanges(false)
}
}, [preferences])
const checkForCredentialChanges = (newCredentials: GitCredential[]) => {
const checkForChanges = (newCredentials: GitCredential[], newIdentity: GitIdentity) => {
const currentCreds = JSON.stringify(preferences?.gitCredentials || [])
const newCreds = JSON.stringify(newCredentials)
setHasCredentialChanges(currentCreds !== newCreds)
}
const checkForIdentityChanges = (newIdentity: GitIdentity) => {
const currentIdentity = preferences?.gitIdentity || { name: '', email: '' }
setHasIdentityChanges(
currentIdentity.name !== newIdentity.name ||
currentIdentity.email !== newIdentity.email
)
const identityChanged = currentIdentity.name !== newIdentity.name || currentIdentity.email !== newIdentity.email
setHasChanges(currentCreds !== newCreds || identityChanged)
}
const addCredential = () => {
const newCredentials = [...gitCredentials, { name: '', host: '', token: '', username: '' }]
setGitCredentials(newCredentials)
checkForCredentialChanges(newCredentials)
const openAddCredentialDialog = () => {
setEditingCredentialIndex(null)
setIsCredentialDialogOpen(true)
}
const updateCredential = (index: number, field: keyof GitCredential, value: string) => {
const newCredentials = [...gitCredentials]
newCredentials[index] = { ...newCredentials[index], [field]: value }
const openEditCredentialDialog = (index: number) => {
setEditingCredentialIndex(index)
setIsCredentialDialogOpen(true)
}
const saveCredential = async (credential: GitCredential) => {
let newCredentials: GitCredential[]
if (editingCredentialIndex !== null) {
newCredentials = [...gitCredentials]
newCredentials[editingCredentialIndex] = credential
} else {
newCredentials = [...gitCredentials, credential]
}
setGitCredentials(newCredentials)
checkForCredentialChanges(newCredentials)
checkForChanges(newCredentials, gitIdentity)
}
const removeCredential = (index: number) => {
const newCredentials = gitCredentials.filter((_, i) => i !== index)
setGitCredentials(newCredentials)
checkForCredentialChanges(newCredentials)
checkForChanges(newCredentials, gitIdentity)
}
const updateIdentity = (field: keyof GitIdentity, value: string) => {
const newIdentity = { ...gitIdentity, [field]: value }
setGitIdentity(newIdentity)
checkForIdentityChanges(newIdentity)
checkForChanges(gitCredentials, newIdentity)
}
const saveCredentials = async () => {
const validCredentials = gitCredentials.filter(cred => cred.name && cred.host && cred.token)
const saveAll = async () => {
setIsSaving(true)
try {
showToast.loading('Saving credentials and restarting server...', { id: 'git-credentials' })
await updateSettingsAsync({ gitCredentials: validCredentials })
setHasCredentialChanges(false)
showToast.success('Git credentials updated', { id: 'git-credentials' })
showToast.loading('Saving git configuration...', { id: 'git-config' })
await updateSettingsAsync({ gitCredentials, gitIdentity })
setHasChanges(false)
showToast.success('Git configuration saved', { id: 'git-config' })
} catch {
showToast.error('Failed to update git credentials', { id: 'git-credentials' })
} finally {
setIsSaving(false)
}
}
const saveIdentity = async () => {
setIsSaving(true)
try {
showToast.loading('Saving git identity...', { id: 'git-identity' })
await updateSettingsAsync({ gitIdentity })
setHasIdentityChanges(false)
showToast.success('Git identity updated', { id: 'git-identity' })
} catch {
showToast.error('Failed to update git identity', { id: 'git-identity' })
showToast.error('Failed to save git configuration', { id: 'git-config' })
} finally {
setIsSaving(false)
}
@@ -102,177 +94,187 @@ export function GitSettings() {
}
return (
<div className="space-y-6">
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Git Identity</h2>
<div className="space-y-4">
<div className="bg-card border border-border rounded-lg">
<div className="flex items-center justify-between px-6 py-4 border-b border-border">
<div>
<h2 className="text-lg font-semibold text-foreground">Git Configuration</h2>
<p className="text-sm text-muted-foreground">
Configure the default author identity used for git commits in local repositories.
Leave empty to use system defaults.
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="git-name">Name</Label>
<Input
id="git-name"
placeholder="Your Name"
value={gitIdentity.name}
onChange={(e) => updateIdentity('name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-2">
<Label htmlFor="git-email">Email</Label>
<Input
id="git-email"
type="email"
placeholder="you@example.com"
value={gitIdentity.email}
onChange={(e) => updateIdentity('email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
{hasIdentityChanges && (
<div className="flex justify-end">
<Button
type="button"
variant="default"
size="sm"
onClick={saveIdentity}
disabled={isSaving}
>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
Save Identity
</Button>
</div>
)}
<p className="text-xs text-muted-foreground">
If not configured, defaults to "OpenCode User" and "opencode@localhost" for new local repositories.
Manage your git identity and credentials for repository operations
</p>
</div>
{hasChanges && (
<Button
type="button"
variant="default"
size="sm"
onClick={saveAll}
disabled={isSaving || isUpdating}
>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
Save Changes
</Button>
)}
</div>
<div className="bg-card border border-border rounded-lg p-6">
<div className="flex items-center justify-between mb-6">
<div>
<h2 className="text-lg font-semibold text-foreground">Git Credentials</h2>
<p className="text-sm text-muted-foreground">
Add credentials for cloning private repositories from any Git host
</p>
</div>
<div className="flex gap-2">
{hasCredentialChanges && (
<Button
type="button"
variant="default"
size="sm"
onClick={saveCredentials}
disabled={isSaving}
>
{isSaving ? <Loader2 className="h-4 w-4 animate-spin mr-2" /> : <Save className="h-4 w-4 mr-2" />}
Save
</Button>
<div className="divide-y divide-border">
<div>
<button
className="w-full flex items-center gap-3 px-6 py-3 hover:bg-accent/30 transition-colors"
onClick={() => setIdentityExpanded(!identityExpanded)}
>
{identityExpanded ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
)}
<Button
type="button"
variant="outline"
size="sm"
onClick={addCredential}
disabled={isSaving}
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
</div>
<User className="w-4 h-4 text-muted-foreground" />
<span className="font-medium">Identity</span>
<span className="text-xs text-muted-foreground ml-auto">
{gitIdentity.name || gitIdentity.email ? `${gitIdentity.name || 'No name'} <${gitIdentity.email || 'No email'}>` : 'Not configured'}
</span>
</button>
{gitCredentials.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-6 text-center">
<p className="text-sm text-muted-foreground">
No git credentials configured. Click "Add" to add credentials for GitHub, GitLab, Gitea, or other Git hosts.
</p>
</div>
) : (
<div className="space-y-4">
{gitCredentials.map((cred, index) => (
<div key={index} className="rounded-lg border border-border p-4 space-y-3">
<div className="flex items-center justify-between">
{identityExpanded && (
<div className="px-6 pb-4 pt-2 space-y-4 ml-7">
<p className="text-sm text-muted-foreground">
Author identity used for git commits. Leave empty to use system defaults.
</p>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="git-name">Name</Label>
<Input
placeholder="Credential name (e.g., GitHub Personal, Work GitLab)"
value={cred.name}
onChange={(e) => updateCredential(index, 'name', e.target.value)}
id="git-name"
placeholder="Your Name"
value={gitIdentity.name}
onChange={(e) => updateIdentity('name', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground font-medium"
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => removeCredential(index)}
disabled={isSaving}
className="ml-2 text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Host URL</Label>
<Input
placeholder="https://github.com/"
value={cred.host}
onChange={(e) => updateCredential(index, 'host', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Username (optional)</Label>
<Input
placeholder="Auto-detected if empty"
value={cred.username || ''}
onChange={(e) => updateCredential(index, 'username', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Access Token</Label>
<div className="space-y-2">
<Label htmlFor="git-email">Email</Label>
<Input
type="password"
placeholder="Personal access token"
value={cred.token}
onChange={(e) => updateCredential(index, 'token', e.target.value)}
id="git-email"
type="email"
placeholder="you@example.com"
value={gitIdentity.email}
onChange={(e) => updateIdentity('email', e.target.value)}
disabled={isSaving}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
</div>
</div>
))}
</div>
)}
<p className="text-xs text-muted-foreground mt-4">
Username defaults: github.com uses "x-access-token", gitlab.com uses "oauth2". For other hosts, specify your username if required.
</p>
</div>
)}
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground mt-4">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</div>
)}
<div>
<button
className="w-full flex items-center gap-3 px-6 py-3 hover:bg-accent/30 transition-colors"
onClick={() => setCredentialsExpanded(!credentialsExpanded)}
>
{credentialsExpanded ? (
<ChevronDown className="w-4 h-4 text-muted-foreground" />
) : (
<ChevronRight className="w-4 h-4 text-muted-foreground" />
)}
<Key className="w-4 h-4 text-muted-foreground" />
<span className="font-medium">Credentials</span>
<span className="text-xs text-muted-foreground ml-auto">
{gitCredentials.length} configured
</span>
</button>
{credentialsExpanded && (
<div className="px-6 pb-4 pt-2 space-y-4 ml-7">
<div className="flex items-center justify-between">
<p className="text-sm text-muted-foreground">
Credentials for cloning private repositories
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={openAddCredentialDialog}
disabled={isSaving}
>
<Plus className="h-4 w-4 mr-2" />
Add
</Button>
</div>
{gitCredentials.length === 0 ? (
<div className="rounded-lg border border-dashed border-border p-4 text-center">
<p className="text-sm text-muted-foreground">
No credentials configured. Click "Add" to add credentials.
</p>
</div>
) : (
<div className="border border-border rounded-lg overflow-hidden">
<table className="w-full text-sm">
<thead className="bg-muted/50">
<tr>
<th className="px-3 py-2 text-left font-medium text-muted-foreground">Name</th>
<th className="px-3 py-2 text-left font-medium text-muted-foreground hidden sm:table-cell">Host</th>
<th className="px-3 py-2 text-right font-medium text-muted-foreground">Actions</th>
</tr>
</thead>
<tbody className="divide-y divide-border">
{gitCredentials.map((cred, index) => (
<tr key={index} className="hover:bg-accent/30 transition-colors">
<td className="px-3 py-2">
<div>
<span className="font-medium">{cred.name || 'Unnamed'}</span>
<div className="text-xs text-muted-foreground sm:hidden">{cred.host}</div>
</div>
</td>
<td className="px-3 py-2 text-muted-foreground hidden sm:table-cell">
{cred.host}
</td>
<td className="px-3 py-2">
<div className="flex items-center justify-end gap-1">
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 w-7 p-0"
onClick={() => openEditCredentialDialog(index)}
disabled={isSaving}
title="Edit"
>
<Pencil className="h-3.5 w-3.5" />
</Button>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 w-7 p-0 text-destructive hover:text-destructive"
onClick={() => removeCredential(index)}
disabled={isSaving}
title="Delete"
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)}
</div>
</div>
<GitCredentialDialog
open={isCredentialDialogOpen}
onOpenChange={setIsCredentialDialogOpen}
onSave={saveCredential}
credential={editingCredentialIndex !== null ? gitCredentials[editingCredentialIndex] : undefined}
isSaving={isSaving}
/>
</div>
)
}
@@ -0,0 +1,211 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { listBranches, switchBranch, GitAuthError } from '@/api/repos'
import { useGitStatus } from '@/api/git'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Loader2, GitBranch, Check, Plus, AlertCircle, ArrowUp, ArrowDown, Globe } from 'lucide-react'
import { cn } from '@/lib/utils'
import { showToast } from '@/lib/toast'
import { useGit } from '@/hooks/useGit'
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
interface BranchesTabProps {
repoId: number
currentBranch: string
}
export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) {
const queryClient = useQueryClient()
const [newBranchName, setNewBranchName] = useState('')
const [isCreating, setIsCreating] = useState(false)
const git = useGit(repoId)
const { data: status } = useGitStatus(repoId)
const { data: branches, isLoading, error, refetch } = useQuery({
queryKey: ['branches', repoId],
queryFn: () => listBranches(repoId),
staleTime: 30000,
})
const switchBranchMutation = useMutation({
mutationFn: (branch: string) => switchBranch(repoId, branch),
onSuccess: (updatedRepo) => {
queryClient.setQueryData(['repo', repoId], updatedRepo)
queryClient.invalidateQueries({ queryKey: ['repos'] })
queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] })
refetch()
showToast.success(`Switched to branch: ${updatedRepo.currentBranch}`)
},
onError: (error) => {
if (error instanceof GitAuthError) {
showToast.error('Authentication failed. Please update your Git token in Settings.')
} else {
showToast.error(error.message || 'Failed to switch branch')
}
},
})
const handleCreateBranch = async () => {
if (!newBranchName.trim()) return
try {
await git.createBranch.mutateAsync(newBranchName.trim())
setNewBranchName('')
setIsCreating(false)
refetch()
} catch {
// Error handled by mutation
}
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="text-center py-12 text-muted-foreground">
<AlertCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Failed to load branches</p>
<p className="text-xs mt-1">{error.message}</p>
</div>
)
}
const activeBranch = branches?.branches?.find(b => b.current)?.name || currentBranch
return (
<div className="flex flex-col h-full">
<div className="p-3 border-b border-border space-y-3 flex-shrink-0">
<div className="flex items-center gap-2">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">Current: {activeBranch}</span>
{status && (status.ahead > 0 || status.behind > 0) && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
{status.ahead > 0 && (
<span className="flex items-center gap-0.5">
<ArrowUp className="w-3 h-3" />{status.ahead}
</span>
)}
{status.behind > 0 && (
<span className="flex items-center gap-0.5">
<ArrowDown className="w-3 h-3" />{status.behind}
</span>
)}
</div>
)}
</div>
{isCreating ? (
<div className="flex items-center gap-2">
<Input
placeholder="New branch name..."
value={newBranchName}
onChange={(e) => setNewBranchName(e.target.value)}
className="h-8 text-sm"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreateBranch()
if (e.key === 'Escape') {
setIsCreating(false)
setNewBranchName('')
}
}}
/>
<Button
size="sm"
className="h-8"
onClick={handleCreateBranch}
disabled={!newBranchName.trim() || git.createBranch.isPending}
>
{git.createBranch.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
'Create'
)}
</Button>
<Button
size="sm"
variant="ghost"
className="h-8"
onClick={() => {
setIsCreating(false)
setNewBranchName('')
}}
>
Cancel
</Button>
</div>
) : (
<Button
size="sm"
variant="outline"
className="w-full h-8"
onClick={() => setIsCreating(true)}
>
<Plus className="w-4 h-4 mr-2" />
Create New Branch
</Button>
)}
</div>
<div className="flex-1 overflow-y-auto">
{branches?.branches && branches.branches.length > 0 ? (
<div className="py-1">
{branches.branches.map((branch) => {
const isCurrent = branch.name === activeBranch || branch.name === `remotes/${activeBranch}`
const isRemote = branch.type === 'remote'
const handleClick = () => {
if (isCurrent) return
let branchToCheckout = branch.name
if (isRemote) {
branchToCheckout = branch.name.replace(/^remotes\/[^/]+\//, '')
}
switchBranchMutation.mutate(branchToCheckout)
}
return (
<button
key={branch.name}
className={cn(
'flex items-center gap-2 px-3 py-2 w-full text-left hover:bg-accent/50 transition-colors',
isCurrent && 'bg-accent'
)}
onClick={handleClick}
disabled={isCurrent || switchBranchMutation.isPending}
>
{isRemote ? (
<Globe className="w-4 h-4 text-blue-500" />
) : (
<GitBranch className={cn('w-4 h-4', isCurrent ? GIT_UI_COLORS.current : 'text-muted-foreground')} />
)}
<span className="flex-1 text-sm truncate">{branch.name}</span>
{branch.type === 'local' && !branch.upstream && (
<span className="text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground">local</span>
)}
{isCurrent && <Check className={`w-4 h-4 ${GIT_UI_COLORS.current}`} />}
{switchBranchMutation.isPending && switchBranchMutation.variables === branch.name && (
<Loader2 className="w-4 h-4 animate-spin" />
)}
</button>
)
})}
</div>
) : (
<div className="text-center py-12 text-muted-foreground">
<GitBranch className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No branches found</p>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,241 @@
import { useState } from 'react'
import { useGitStatus, getApiErrorMessage } from '@/api/git'
import { useGit } from '@/hooks/useGit'
import { GitFlatFileList } from './GitFlatFileList'
import { Button } from '@/components/ui/button'
import { Textarea } from '@/components/ui/textarea'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { Loader2, GitCommit, FileText, AlertCircle, X } from 'lucide-react'
interface ChangesTabProps {
repoId: number
onFileSelect: (path: string, staged: boolean) => void
selectedFile?: {path: string, staged: boolean}
isMobile: boolean
}
export function ChangesTab({ repoId, onFileSelect, selectedFile, isMobile }: ChangesTabProps) {
const { data: status, isLoading, error } = useGitStatus(repoId)
const git = useGit(repoId)
const [commitMessage, setCommitMessage] = useState('')
const [apiError, setApiError] = useState<string | null>(null)
const stagedFiles = status?.files.filter(f => f.staged) || []
const unstagedFiles = status?.files.filter(f => !f.staged) || []
const canCommit = commitMessage.trim() && stagedFiles.length > 0 && !git.commit.isPending
const handleGitAction = async (action: () => Promise<unknown>) => {
try {
setApiError(null)
await action()
} catch (error: unknown) {
const message = getApiErrorMessage(error)
setApiError(message)
}
}
const handleStage = (paths: string[]) => {
handleGitAction(() => git.stageFiles.mutateAsync(paths))
}
const handleUnstage = (paths: string[]) => {
handleGitAction(() => git.unstageFiles.mutateAsync(paths))
}
const handleCommit = () => {
handleGitAction(async () => {
await git.commit.mutateAsync({ message: commitMessage.trim() })
setCommitMessage('')
})
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="text-center py-12 text-muted-foreground">
<AlertCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Failed to load git status</p>
<p className="text-xs mt-1">{error.message}</p>
</div>
)
}
if (!status) return null
if (isMobile && selectedFile) {
return (
<div className="flex flex-col h-full">
{apiError && (
<div className="mx-3 mt-3 p-2 rounded border bg-destructive/10 border-destructive/20 flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-destructive flex-shrink-0" />
<span className="text-sm text-destructive flex-1">{apiError}</span>
<Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={() => setApiError(null)}>
<X className="w-3 h-3" />
</Button>
</div>
)}
<Tabs defaultValue="files" className="flex flex-col h-full">
<TabsList className="flex-shrink-0">
<TabsTrigger value="files">Files ({stagedFiles.length + unstagedFiles.length})</TabsTrigger>
<TabsTrigger value="diff">{selectedFile.path.split('/').pop() || selectedFile.path}</TabsTrigger>
</TabsList>
<TabsContent value="files" className="flex-1 overflow-hidden mt-0">
<div className="flex flex-col h-full">
<div className="flex-1 overflow-y-auto p-3 space-y-4">
{status.hasChanges ? (
<>
{stagedFiles.length > 0 && (
<GitFlatFileList
files={status.files}
staged={true}
onSelect={onFileSelect}
onUnstage={handleUnstage}
selectedFile={selectedFile?.path}
/>
)}
{unstagedFiles.length > 0 && (
<GitFlatFileList
files={status.files}
staged={false}
onSelect={onFileSelect}
onStage={handleStage}
selectedFile={selectedFile?.path}
/>
)}
</>
) : (
<div className="text-center py-12 text-muted-foreground">
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No uncommitted changes</p>
</div>
)}
</div>
{status.hasChanges && (
<div className="p-3 border-t border-border space-y-2 flex-shrink-0">
<Textarea
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
}
}}
/>
<Button
onClick={handleCommit}
disabled={!canCommit}
className="w-full h-9"
>
{git.commit.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<GitCommit className="w-4 h-4 mr-2" />
)}
Commit {stagedFiles.length > 0 && `(${stagedFiles.length} staged)`}
</Button>
<p className="text-[10px] text-muted-foreground text-center">
{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}+Enter to commit
</p>
</div>
)}
</div>
</TabsContent>
<TabsContent value="diff" className="flex-1 overflow-hidden mt-0">
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
</TabsContent>
</Tabs>
</div>
)
} else {
return (
<div className="flex flex-col h-full">
{apiError && (
<div className="mx-3 mt-3 p-2 rounded border bg-destructive/10 border-destructive/20 flex items-center gap-2">
<AlertCircle className="w-4 h-4 text-destructive flex-shrink-0" />
<span className="text-sm text-destructive flex-1">{apiError}</span>
<Button variant="ghost" size="sm" className="h-6 w-6 p-0" onClick={() => setApiError(null)}>
<X className="w-3 h-3" />
</Button>
</div>
)}
<div className="flex-1 overflow-y-auto p-3 space-y-4">
{status.hasChanges ? (
<>
{stagedFiles.length > 0 && (
<GitFlatFileList
files={status.files}
staged={true}
onSelect={onFileSelect}
onUnstage={handleUnstage}
selectedFile={selectedFile?.path}
/>
)}
{unstagedFiles.length > 0 && (
<GitFlatFileList
files={status.files}
staged={false}
onSelect={onFileSelect}
onStage={handleStage}
selectedFile={selectedFile?.path}
/>
)}
</>
) : (
<div className="text-center py-12 text-muted-foreground">
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No uncommitted changes</p>
</div>
)}
</div>
{status.hasChanges && (
<div className="p-3 border-t border-border space-y-2 flex-shrink-0">
<Textarea
placeholder="Commit message..."
value={commitMessage}
onChange={(e) => setCommitMessage(e.target.value)}
className="min-h-[80px] text-sm resize-none"
onKeyDown={(e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && canCommit) {
handleCommit()
}
}}
/>
<Button
onClick={handleCommit}
disabled={!canCommit}
className="w-full h-9"
>
{git.commit.isPending ? (
<Loader2 className="w-4 h-4 animate-spin mr-2" />
) : (
<GitCommit className="w-4 h-4 mr-2" />
)}
Commit {stagedFiles.length > 0 && `(${stagedFiles.length} staged)`}
</Button>
<p className="text-[10px] text-muted-foreground text-center">
{navigator.platform.includes('Mac') ? '⌘' : 'Ctrl'}+Enter to commit
</p>
</div>
)}
</div>
)
}
}
@@ -0,0 +1,91 @@
import { useGitLog } from '@/api/git'
import { Loader2, GitCommit, AlertCircle, ArrowUp } from 'lucide-react'
import { cn } from '@/lib/utils'
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
interface CommitsTabProps {
repoId: number
onSelectCommit?: (hash: string) => void
}
function formatRelativeTime(dateString: string): string {
const date = new Date(dateString)
const now = new Date()
const diffMs = now.getTime() - date.getTime()
const diffSeconds = Math.floor(diffMs / 1000)
const diffMinutes = Math.floor(diffSeconds / 60)
const diffHours = Math.floor(diffMinutes / 60)
const diffDays = Math.floor(diffHours / 24)
const diffWeeks = Math.floor(diffDays / 7)
const diffMonths = Math.floor(diffDays / 30)
if (diffSeconds < 60) return 'just now'
if (diffMinutes < 60) return `${diffMinutes}m ago`
if (diffHours < 24) return `${diffHours}h ago`
if (diffDays < 7) return `${diffDays}d ago`
if (diffWeeks < 4) return `${diffWeeks}w ago`
return `${diffMonths}mo ago`
}
export function CommitsTab({ repoId, onSelectCommit }: CommitsTabProps) {
const { data, isLoading, error } = useGitLog(repoId, 50)
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
</div>
)
}
if (error) {
return (
<div className="text-center py-12 text-muted-foreground">
<AlertCircle className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">Failed to load commits</p>
<p className="text-xs mt-1">{error.message}</p>
</div>
)
}
if (!data?.commits || data.commits.length === 0) {
return (
<div className="text-center py-12 text-muted-foreground">
<GitCommit className="w-8 h-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">No commits found</p>
</div>
)
}
return (
<div className="flex flex-col h-full overflow-y-auto">
{data.commits.map((commit) => (
<button
key={commit.hash}
className="flex items-start gap-3 px-3 py-2 text-left hover:bg-accent/50 transition-colors border-b border-border last:border-0"
onClick={() => onSelectCommit?.(commit.hash)}
>
<div className="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center mt-0.5">
<GitCommit className="w-4 h-4 text-muted-foreground" />
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-medium truncate">{commit.message}</p>
<div className="flex items-center gap-2 mt-1 text-xs text-muted-foreground">
<span className="font-mono">{commit.hash.substring(0, 7)}</span>
<span>·</span>
<span className="truncate">{commit.authorName}</span>
<span>·</span>
<span className="flex-shrink-0">{formatRelativeTime(commit.date)}</span>
{commit.unpushed && (
<span className={cn('flex items-center gap-0.5 px-1 rounded', GIT_UI_COLORS.unpushed)}>
<ArrowUp className="w-3 h-3" />
Local
</span>
)}
</div>
</div>
</button>
))}
</div>
)
}
@@ -0,0 +1,76 @@
import { Button } from '@/components/ui/button'
import { Plus, Minus, FileText, FilePlus, FileX, FileSearch, CircleDot } from 'lucide-react'
import { cn } from '@/lib/utils'
import type { GitFileStatus } from '@/types/git'
import { GIT_STATUS_COLORS, GIT_UI_COLORS } from '@/lib/git-status-styles'
interface GitFlatFileItemProps {
file: GitFileStatus
isSelected: boolean
onSelect: (path: string, staged: boolean) => void
onStage?: (path: string) => void
onUnstage?: (path: string) => void
}
const statusIcons = {
modified: FileSearch,
added: FilePlus,
deleted: FileX,
renamed: FileSearch,
untracked: CircleDot,
copied: FilePlus,
}
export function GitFlatFileItem({ file, isSelected, onSelect, onStage, onUnstage }: GitFlatFileItemProps) {
const StatusIcon = statusIcons[file.status] || FileText
const statusColor = GIT_STATUS_COLORS[file.status] || 'text-muted-foreground'
const fileName = file.path.split('/').pop() || file.path
const dirPath = file.path.includes('/') ? file.path.substring(0, file.path.lastIndexOf('/')) : ''
const handleAction = (e: React.MouseEvent) => {
e.stopPropagation()
if (file.staged && onUnstage) {
onUnstage(file.path)
} else if (!file.staged && onStage) {
onStage(file.path)
}
}
return (
<div
className={cn(
'group flex items-center gap-2 px-2 py-1 rounded cursor-pointer hover:bg-accent transition-colors',
isSelected && 'bg-accent'
)}
onClick={() => onSelect(file.path, file.staged)}
>
<StatusIcon className={cn('w-4 h-4 flex-shrink-0', statusColor)} />
<div className="flex-1 min-w-0 flex items-center gap-1">
<span className="text-sm truncate">{fileName}</span>
{dirPath && (
<span className="text-xs text-muted-foreground truncate">
{dirPath}
</span>
)}
</div>
{file.staged && (
<span className={cn('text-[10px] px-1.5 py-0.5 rounded flex-shrink-0', GIT_UI_COLORS.stagedBadge)}>
staged
</span>
)}
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity flex-shrink-0"
onClick={handleAction}
>
{file.staged ? (
<Minus className={cn('w-3 h-3', GIT_UI_COLORS.unstage)} />
) : (
<Plus className={cn('w-3 h-3', GIT_UI_COLORS.stage)} />
)}
</Button>
</div>
)
}
@@ -0,0 +1,157 @@
import { useMemo, useState } from 'react'
import { ChevronDown, ChevronRight, Plus, Minus } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { GitFlatFileItem } from './GitFlatFileItem'
import { cn } from '@/lib/utils'
import type { GitFileStatus, GitFileStatusType } from '@/types/git'
import { GIT_STATUS_COLORS, GIT_STATUS_LABELS } from '@/lib/git-status-styles'
interface GitFlatFileListProps {
files: GitFileStatus[]
staged: boolean
onSelect: (path: string, staged: boolean) => void
onStage?: (paths: string[]) => void
onUnstage?: (paths: string[]) => void
selectedFile?: string
}
interface GroupedFiles {
status: GitFileStatusType
files: GitFileStatus[]
}
const statusOrder: GitFileStatusType[] = ['modified', 'added', 'deleted', 'renamed', 'copied', 'untracked']
export function GitFlatFileList({
files,
staged,
onSelect,
onStage,
onUnstage,
selectedFile,
}: GitFlatFileListProps) {
const [collapsedGroups, setCollapsedGroups] = useState<Set<GitFileStatusType>>(new Set())
const filteredFiles = useMemo(() => {
return files.filter(f => f.staged === staged)
}, [files, staged])
const groupedFiles = useMemo(() => {
const groups: GroupedFiles[] = []
for (const status of statusOrder) {
const statusFiles = filteredFiles.filter(f => f.status === status)
if (statusFiles.length > 0) {
groups.push({ status, files: statusFiles })
}
}
return groups
}, [filteredFiles])
const toggleGroup = (status: GitFileStatusType) => {
setCollapsedGroups(prev => {
const next = new Set(prev)
if (next.has(status)) {
next.delete(status)
} else {
next.add(status)
}
return next
})
}
const handleStageFile = (path: string) => {
onStage?.([path])
}
const handleUnstageFile = (path: string) => {
onUnstage?.([path])
}
const handleStageAll = (e: React.MouseEvent) => {
e.stopPropagation()
if (onStage) {
onStage(filteredFiles.map(f => f.path))
}
}
const handleUnstageAll = (e: React.MouseEvent) => {
e.stopPropagation()
if (onUnstage) {
onUnstage(filteredFiles.map(f => f.path))
}
}
if (filteredFiles.length === 0) {
return null
}
return (
<div className="space-y-1">
<div className="flex items-center justify-between px-2 py-1">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">
{staged ? 'Staged Changes' : 'Changes'} ({filteredFiles.length})
</span>
<Button
variant="ghost"
size="sm"
className="h-6 px-2 text-xs"
onClick={staged ? handleUnstageAll : handleStageAll}
>
{staged ? (
<>
<Minus className="w-3 h-3 mr-1" />
Unstage All
</>
) : (
<>
<Plus className="w-3 h-3 mr-1" />
Stage All
</>
)}
</Button>
</div>
{groupedFiles.map(({ status, files: groupFiles }) => {
const isCollapsed = collapsedGroups.has(status)
return (
<div key={status}>
<button
className="flex items-center gap-1 px-2 py-1 w-full text-left hover:bg-accent rounded transition-colors"
onClick={() => toggleGroup(status)}
>
{isCollapsed ? (
<ChevronRight className="w-3 h-3 text-muted-foreground" />
) : (
<ChevronDown className="w-3 h-3 text-muted-foreground" />
)}
<span className={cn('text-xs font-medium', GIT_STATUS_COLORS[status])}>
{GIT_STATUS_LABELS[status]}
</span>
<span className="text-xs text-muted-foreground">
({groupFiles.length})
</span>
</button>
{!isCollapsed && (
<div className="ml-4">
{groupFiles.map(file => (
<GitFlatFileItem
key={file.path}
file={file}
isSelected={selectedFile === file.path}
onSelect={onSelect}
onStage={handleStageFile}
onUnstage={handleUnstageFile}
/>
))}
</div>
)}
</div>
)
})}
</div>
)
}
@@ -0,0 +1,282 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { useGitStatus, getApiErrorMessage } from '@/api/git'
import { listBranches, switchBranch } from '@/api/repos'
import { useGit } from '@/hooks/useGit'
import { ChangesTab } from './ChangesTab'
import { CommitsTab } from './CommitsTab'
import { BranchesTab } from './BranchesTab'
import { FileDiffView } from '@/components/file-browser/FileDiffView'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'
import { GIT_UI_COLORS } from '@/lib/git-status-styles'
import {
Loader2,
GitBranch,
FileCode,
History,
Upload,
ArrowUp,
ArrowDown,
RefreshCw,
ArrowDownFromLine,
X,
ChevronDown,
Check,
} from 'lucide-react'
import { cn } from '@/lib/utils'
import { useMobile } from '@/hooks/useMobile'
import { showToast } from '@/lib/toast'
interface SourceControlPanelProps {
repoId: number
isOpen: boolean
onClose: () => void
currentBranch: string
}
type Tab = 'changes' | 'commits' | 'branches'
export function SourceControlPanel({
repoId,
isOpen,
onClose,
currentBranch,
}: SourceControlPanelProps) {
const [activeTab, setActiveTab] = useState<Tab>('changes')
const [selectedFile, setSelectedFile] = useState<{path: string, staged: boolean} | undefined>()
const { data: status } = useGitStatus(repoId)
const { data: branches } = useQuery({
queryKey: ['branches', repoId],
queryFn: () => listBranches(repoId),
staleTime: 30000,
})
const git = useGit(repoId)
const queryClient = useQueryClient()
const isMobile = useMobile()
const switchBranchMutation = useMutation({
mutationFn: (branch: string) => switchBranch(repoId, branch),
onSuccess: (updatedRepo) => {
queryClient.setQueryData(['repo', repoId], updatedRepo)
queryClient.invalidateQueries({ queryKey: ['repos'] })
queryClient.invalidateQueries({ queryKey: ['gitStatus', repoId] })
queryClient.invalidateQueries({ queryKey: ['branches', repoId] })
},
onError: (error) => {
showToast.error(getApiErrorMessage(error))
},
})
const handleGitAction = async (action: () => Promise<unknown>) => {
try {
await action()
} catch (error: unknown) {
const message = getApiErrorMessage(error)
showToast.error(message)
}
}
const tabs: { id: Tab; label: string; icon: React.ElementType }[] = [
{ id: 'changes', label: 'Changes', icon: FileCode },
{ id: 'commits', label: 'Commits', icon: History },
{ id: 'branches', label: 'Branches', icon: GitBranch },
]
const changesCount = status?.files.length || 0
const stagedCount = status?.files.filter(f => f.staged).length || 0
const content = (
<div className="flex flex-col h-full">
<div className="flex items-center justify-between px-3 py-2 border-b border-border flex-shrink-0">
<div className="flex items-center gap-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="flex items-center gap-2 hover:bg-accent rounded px-1 py-0.5 transition-colors">
<GitBranch className="w-4 h-4 text-muted-foreground" />
<span className="text-sm font-medium">{currentBranch}</span>
<ChevronDown className="w-3 h-3 text-muted-foreground" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-48">
{branches?.branches?.filter(b => b.type === 'local')?.map((branch) => (
<DropdownMenuItem
key={branch.name}
onClick={() => branch.name !== currentBranch && switchBranchMutation.mutate(branch.name)}
disabled={branch.name === currentBranch || switchBranchMutation.isPending}
className="flex items-center gap-2"
>
<GitBranch className="w-4 h-4" />
<span className="flex-1 truncate">{branch.name}</span>
{branch.name === currentBranch && <Check className={`w-4 h-4 ${GIT_UI_COLORS.current}`} />}
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{status && (status.ahead > 0 || status.behind > 0) && (
<div className="flex items-center gap-1 text-xs text-muted-foreground">
{status.ahead > 0 && (
<span className={`flex items-center gap-0.5 ${GIT_UI_COLORS.ahead}`}>
<ArrowUp className="w-3 h-3" />{status.ahead}
</span>
)}
{status.behind > 0 && (
<span className={`flex items-center gap-0.5 ${GIT_UI_COLORS.behind}`}>
<ArrowDown className="w-3 h-3" />{status.behind}
</span>
)}
</div>
)}
</div>
<div className="flex items-center gap-1">
<Button
size="sm"
variant="ghost"
onClick={() => handleGitAction(() => git.fetch.mutateAsync())}
disabled={git.fetch.isPending}
className="h-7 w-7 p-0"
title="Fetch from remote"
>
{git.fetch.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<RefreshCw className="w-4 h-4" />
)}
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => handleGitAction(() => git.pull.mutateAsync())}
disabled={git.pull.isPending}
className="h-7 w-7 p-0"
title="Pull"
>
{git.pull.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<ArrowDownFromLine className="w-4 h-4" />
)}
</Button>
<Button
size="sm"
variant="ghost"
onClick={() => handleGitAction(() => git.push.mutateAsync(undefined))}
disabled={git.push.isPending}
className="h-7 w-7 p-0"
title="Push"
>
{git.push.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Upload className="w-4 h-4" />
)}
</Button>
</div>
</div>
<div className="flex border-b border-border flex-shrink-0">
{tabs.map((tab) => {
const Icon = tab.icon
return (
<button
key={tab.id}
className={cn(
'flex items-center gap-1.5 px-3 py-2 text-sm transition-colors border-b-2 -mb-px',
activeTab === tab.id
? 'border-primary text-foreground'
: 'border-transparent text-muted-foreground hover:text-foreground hover:bg-accent'
)}
onClick={() => setActiveTab(tab.id)}
>
<Icon className="w-4 h-4" />
<span>{tab.label}</span>
{tab.id === 'changes' && changesCount > 0 && (
<span className="text-xs px-1.5 py-0.5 rounded-full bg-accent">
{stagedCount > 0 ? `${stagedCount}/${changesCount}` : changesCount}
</span>
)}
</button>
)
})}
</div>
<div className={cn('flex-1 min-h-0', isMobile ? 'flex flex-col' : 'flex')}>
<div className={cn(
'overflow-hidden',
isMobile ? 'flex-1' : selectedFile ? 'w-[35%] border-r border-border' : 'flex-1'
)}>
{activeTab === 'changes' && (
<ChangesTab
repoId={repoId}
onFileSelect={(path, staged) => setSelectedFile({ path, staged })}
selectedFile={selectedFile}
isMobile={isMobile}
/>
)}
{activeTab === 'commits' && (
<CommitsTab repoId={repoId} />
)}
{activeTab === 'branches' && (
<BranchesTab repoId={repoId} currentBranch={currentBranch} />
)}
</div>
{selectedFile && !isMobile && (
<div className="flex-1 overflow-hidden flex flex-col">
<div className="flex items-center justify-between px-3 py-2 border-b border-border">
<span className="text-sm font-medium truncate">{selectedFile.path}</span>
<Button
variant="ghost"
size="sm"
className="h-6 w-6 p-0"
onClick={() => setSelectedFile(undefined)}
>
<X className="w-4 h-4" />
</Button>
</div>
<div className="flex-1 overflow-auto">
<FileDiffView repoId={repoId} filePath={selectedFile.path} includeStaged={selectedFile.staged} />
</div>
</div>
)}
</div>
</div>
)
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent
mobileFullscreen
hideCloseButton={isMobile}
className={cn(
'p-0 flex flex-col bg-card border-border',
isMobile ? 'h-full' : 'w-[90vw] sm:max-w-6xl h-[90vh]'
)}
>
<DialogHeader className={cn(
'px-4 py-3 border-b border-border flex-shrink-0',
isMobile && 'relative'
)}>
<DialogTitle className="flex items-center gap-2">
<GitBranch className="w-5 h-5" />
Source Control
</DialogTitle>
{isMobile && (
<Button
variant="ghost"
size="sm"
onClick={onClose}
className="absolute right-2 top-1/2 -translate-y-1/2 h-10 w-10 p-0"
>
<X className="h-6 w-6" />
</Button>
)}
</DialogHeader>
<div className="flex-1 overflow-hidden">
{content}
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,6 @@
export { SourceControlPanel } from './SourceControlPanel'
export { ChangesTab } from './ChangesTab'
export { CommitsTab } from './CommitsTab'
export { BranchesTab } from './BranchesTab'
export { GitFlatFileList } from './GitFlatFileList'
export { GitFlatFileItem } from './GitFlatFileItem'