Add local repository support and permission request handling

This commit is contained in:
Chris Scott committed 2025-11-28 10:26:03 -05:00
1 parent 9a2ebc9652
commit 83834e7ed7
22 files changed
+685 -120

No files matched your search

+46 -1
View File
@@ -4,6 +4,41 @@ import { logger } from '../utils/logger'
export function runMigrations(db: Database): void {
try {
const tableInfo = db.prepare("PRAGMA table_info(repos)").all() as any[]
const repoUrlColumn = tableInfo.find((col: any) => col.name === 'repo_url')
if (repoUrlColumn && repoUrlColumn.notnull === 1) {
logger.info('Migrating repos table to allow nullable repo_url for local repos')
db.run('BEGIN TRANSACTION')
try {
db.run(`
CREATE TABLE repos_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
clone_status TEXT NOT NULL,
cloned_at INTEGER NOT NULL,
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
is_local BOOLEAN DEFAULT FALSE
)
`)
db.run(`
INSERT INTO repos_new (id, repo_url, local_path, branch, default_branch, clone_status, cloned_at, last_pulled, opencode_config_name, is_worktree, is_local)
SELECT id, repo_url, local_path, branch, default_branch, clone_status, cloned_at, last_pulled, opencode_config_name, is_worktree, is_local FROM repos
`)
db.run('DROP TABLE repos')
db.run('ALTER TABLE repos_new RENAME TO repos')
db.run('COMMIT')
logger.info('Successfully migrated repos table to allow nullable repo_url')
} catch (migrationError) {
db.run('ROLLBACK')
throw migrationError
}
}
const hasBranchColumn = tableInfo.some(col => col.name === 'branch')
if (!hasBranchColumn) {
@@ -21,13 +56,23 @@ export function runMigrations(db: Database): void {
logger.debug('Index already exists or could not be created', error)
}
try {
db.run(`
CREATE UNIQUE INDEX IF NOT EXISTS idx_local_path
ON repos(local_path)
`)
} catch (error) {
logger.debug('Local path index already exists or could not be created', error)
}
const requiredColumns = [
{ name: 'default_branch', sql: 'ALTER TABLE repos ADD COLUMN default_branch TEXT' },
{ name: 'clone_status', sql: 'ALTER TABLE repos ADD COLUMN clone_status TEXT NOT NULL DEFAULT "cloning"' },
{ name: 'cloned_at', sql: 'ALTER TABLE repos ADD COLUMN cloned_at INTEGER NOT NULL DEFAULT 0' },
{ name: 'last_pulled', sql: 'ALTER TABLE repos ADD COLUMN last_pulled INTEGER' },
{ name: 'opencode_config_name', sql: 'ALTER TABLE repos ADD COLUMN opencode_config_name TEXT' },
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' }
{ name: 'is_worktree', sql: 'ALTER TABLE repos ADD COLUMN is_worktree BOOLEAN DEFAULT FALSE' },
{ name: 'is_local', sql: 'ALTER TABLE repos ADD COLUMN is_local BOOLEAN DEFAULT FALSE' }
]
for (const column of requiredColumns) {
+54 -22
View File
@@ -5,7 +5,7 @@ import path from 'path'
export interface RepoRow {
id: number
repo_url: string
repo_url?: string
local_path: string
branch?: string
default_branch: string
@@ -14,6 +14,7 @@ export interface RepoRow {
last_pulled?: number
opencode_config_name?: string
is_worktree?: number
is_local?: number
}
function rowToRepo(row: RepoRow): Repo {
@@ -29,35 +30,59 @@ function rowToRepo(row: RepoRow): Repo {
lastPulled: row.last_pulled,
openCodeConfigName: row.opencode_config_name,
isWorktree: row.is_worktree ? Boolean(row.is_worktree) : undefined,
isLocal: row.is_local ? Boolean(row.is_local) : undefined,
}
}
export function createRepo(db: Database, repo: CreateRepoInput): Repo {
const stmt = db.prepare(`
INSERT OR IGNORE INTO repos (repo_url, local_path, branch, default_branch, clone_status, cloned_at, is_worktree)
VALUES (?, ?, ?, ?, ?, ?, ?)
`)
const normalizedPath = repo.localPath.replace(/\/+$/, '')
const result = stmt.run(
repo.repoUrl,
repo.localPath,
repo.branch || null,
repo.defaultBranch,
repo.cloneStatus,
repo.clonedAt,
repo.isWorktree ? 1 : 0
)
const existing = repo.isLocal
? getRepoByLocalPath(db, normalizedPath)
: getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch)
if (result.changes === 0) {
const existing = getRepoByUrlAndBranch(db, repo.repoUrl, repo.branch)
if (existing) {
return existing
}
throw new Error('Failed to create repo and no existing repo found')
if (existing) {
return existing
}
const newRepo = getRepoById(db, Number(result.lastInsertRowid))!
return newRepo
const stmt = db.prepare(`
INSERT INTO repos (repo_url, local_path, branch, default_branch, clone_status, cloned_at, is_worktree, is_local)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
`)
try {
const result = stmt.run(
repo.repoUrl || null,
normalizedPath,
repo.branch || null,
repo.defaultBranch,
repo.cloneStatus,
repo.clonedAt,
repo.isWorktree ? 1 : 0,
repo.isLocal ? 1 : 0
)
const newRepo = getRepoById(db, Number(result.lastInsertRowid))
if (!newRepo) {
throw new Error(`Failed to retrieve newly created repo with id ${result.lastInsertRowid}`)
}
return newRepo
} catch (error: any) {
if (error.message?.includes('UNIQUE constraint failed') || error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
const conflictRepo = repo.isLocal
? getRepoByLocalPath(db, normalizedPath)
: getRepoByUrlAndBranch(db, repo.repoUrl!, repo.branch)
if (conflictRepo) {
return conflictRepo
}
const identifier = repo.isLocal ? `path '${normalizedPath}'` : `url '${repo.repoUrl}' branch '${repo.branch || 'default'}'`
throw new Error(`Repository with ${identifier} already exists but could not be retrieved. This may indicate database corruption.`)
}
throw new Error(`Failed to create repository: ${error.message}`)
}
}
export function getRepoById(db: Database, id: number): Repo | null {
@@ -87,6 +112,13 @@ export function getRepoByUrlAndBranch(db: Database, repoUrl: string, branch?: st
return row ? rowToRepo(row) : null
}
export function getRepoByLocalPath(db: Database, localPath: string): Repo | null {
const stmt = db.prepare('SELECT * FROM repos WHERE local_path = ?')
const row = stmt.get(localPath) as RepoRow | undefined
return row ? rowToRepo(row) : null
}
export function listRepos(db: Database): Repo[] {
const stmt = db.prepare('SELECT * FROM repos ORDER BY cloned_at DESC')
const rows = stmt.all() as RepoRow[]
+2 -3
View File
@@ -11,7 +11,7 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
db.run(`
CREATE TABLE IF NOT EXISTS repos (
id INTEGER PRIMARY KEY AUTOINCREMENT,
repo_url TEXT NOT NULL,
repo_url TEXT,
local_path TEXT NOT NULL,
branch TEXT,
default_branch TEXT,
@@ -20,8 +20,7 @@ export function initializeDatabase(dbPath: string = './data/opencode.db'): Datab
last_pulled INTEGER,
opencode_config_name TEXT,
is_worktree BOOLEAN DEFAULT FALSE,
UNIQUE(repo_url, branch)
is_local BOOLEAN DEFAULT FALSE
);
CREATE INDEX IF NOT EXISTS idx_repo_clone_status ON repos(clone_status);
+18 -9
View File
@@ -17,18 +17,27 @@ export function createRepoRoutes(database: Database) {
app.post('/', async (c) => {
try {
const body = await c.req.json()
const { repoUrl, branch, openCodeConfigName, useWorktree } = body
const { repoUrl, localPath, branch, openCodeConfigName, useWorktree } = body
if (!repoUrl) {
return c.json({ error: 'repoUrl is required' }, 400)
if (!repoUrl && !localPath) {
return c.json({ error: 'Either repoUrl or localPath is required' }, 400)
}
const repo = await repoService.cloneRepo(
database,
repoUrl,
branch,
useWorktree
)
let repo
if (localPath) {
repo = await repoService.initLocalRepo(
database,
localPath,
branch
)
} else {
repo = await repoService.cloneRepo(
database,
repoUrl!,
branch,
useWorktree
)
}
if (openCodeConfigName) {
const settingsService = new SettingsService(database)
+116 -14
View File
@@ -8,6 +8,86 @@ import { SettingsService } from './settings'
import { getReposPath } from '@opencode-webui/shared'
import path from 'path'
export async function initLocalRepo(
database: Database,
localPath: string,
branch?: string
): Promise<Repo> {
const normalizedPath = localPath.replace(/\/+$/, '')
const fullPath = path.resolve(getReposPath(), normalizedPath)
const existing = db.getRepoByLocalPath(database, normalizedPath)
if (existing) {
logger.info(`Local repo already exists in database: ${normalizedPath}`)
return existing
}
const createRepoInput: CreateRepoInput = {
localPath: normalizedPath,
branch: branch || undefined,
defaultBranch: branch || 'main',
cloneStatus: 'cloning',
clonedAt: Date.now(),
isLocal: true,
}
let repo: Repo
let directoryCreated = false
try {
repo = db.createRepo(database, createRepoInput)
logger.info(`Created database record for local repo: ${normalizedPath} (id: ${repo.id})`)
} catch (error: any) {
logger.error(`Failed to create database record for local repo: ${normalizedPath}`, error)
throw new Error(`Failed to register local repository '${normalizedPath}': ${error.message}`)
}
try {
await ensureDirectoryExists(fullPath)
directoryCreated = true
logger.info(`Created directory for local repo: ${fullPath}`)
logger.info(`Initializing git repository: ${fullPath}`)
await executeCommand(['git', 'init'], fullPath)
if (branch && branch !== 'main') {
await executeCommand(['git', '-C', fullPath, 'checkout', '-b', branch])
}
const isGitRepo = await executeCommand(['git', '-C', fullPath, 'rev-parse', '--git-dir'])
.then(() => true)
.catch(() => false)
if (!isGitRepo) {
throw new Error(`Git initialization failed - directory exists but is not a valid git repository`)
}
db.updateRepoStatus(database, repo.id, 'ready')
logger.info(`Local git repo ready: ${normalizedPath}`)
return { ...repo, cloneStatus: 'ready' }
} catch (error: any) {
logger.error(`Failed to initialize local repo, rolling back: ${normalizedPath}`, error)
try {
db.deleteRepo(database, repo.id)
logger.info(`Rolled back database record for repo id: ${repo.id}`)
} catch (dbError: any) {
logger.error(`Failed to rollback database record for repo id ${repo.id}:`, dbError)
}
if (directoryCreated) {
try {
await executeCommand(['rm', '-rf', normalizedPath], getReposPath())
logger.info(`Rolled back directory: ${normalizedPath}`)
} catch (fsError: any) {
logger.error(`Failed to rollback directory ${normalizedPath}:`, fsError)
}
}
throw new Error(`Failed to initialize local repository '${normalizedPath}': ${error.message}`)
}
}
export async function cloneRepo(
database: Database,
repoUrl: string,
@@ -229,13 +309,18 @@ export async function cloneRepo(
}
export async function getCurrentBranch(repo: Repo): Promise<string | null> {
const repoPath = path.resolve(getReposPath(), repo.localPath)
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
const currentBranch = await executeCommand(['git', '-C', repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'])
return currentBranch.trim()
} catch (error: any) {
logger.warn(`Failed to get current branch for repo ${repo.id}:`, error.message)
return null
} catch {
try {
const symbolicRef = await executeCommand(['git', '-C', repoPath, 'symbolic-ref', '--short', 'HEAD'])
return symbolicRef.trim()
} catch {
return repo.branch || repo.defaultBranch || null
}
}
}
@@ -243,15 +328,25 @@ export async function listBranches(repo: Repo): Promise<{ local: string[], remot
try {
const repoPath = path.resolve(getReposPath(), repo.localPath)
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'])
if (!repo.isLocal) {
await executeCommand(['git', '-C', repoPath, 'fetch', '--all'])
}
const localBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '--format=%(refname:short)'])
const localBranches = localBranchesOutput.trim().split('\n').filter(b => b.trim())
const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)'])
const remoteBranches = remoteBranchesOutput.trim().split('\n')
.filter(b => b.trim() && !b.includes('HEAD'))
.map(b => b.replace('origin/', ''))
let remoteBranches: string[] = []
if (!repo.isLocal) {
try {
const remoteBranchesOutput = await executeCommand(['git', '-C', repoPath, 'branch', '-r', '--format=%(refname:short)'])
remoteBranches = remoteBranchesOutput.trim().split('\n')
.filter(b => b.trim() && !b.includes('HEAD'))
.map(b => b.replace('origin/', ''))
} catch (error) {
logger.warn(`Failed to get remote branches for repo ${repo.id}:`, error)
remoteBranches = []
}
}
const current = await getCurrentBranch(repo)
@@ -321,6 +416,11 @@ export async function pullRepo(database: Database, repoId: number): Promise<void
throw new Error(`Repo not found: ${repoId}`)
}
if (repo.isLocal) {
logger.info(`Skipping pull for local repo: ${repo.localPath}`)
return
}
try {
logger.info(`Pulling repo: ${repo.repoUrl}`)
await executeCommand(['git', '-C', path.resolve(getReposPath(), repo.localPath), 'pull'])
@@ -339,15 +439,17 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
throw new Error(`Repo not found: ${repoId}`)
}
const repoIdentifier = repo.repoUrl || repo.localPath
try {
logger.info(`Deleting repo files: ${repo.repoUrl}`)
logger.info(`Deleting repo files: ${repoIdentifier}`)
// Extract just the directory name from the localPath
const dirName = repo.localPath.split('/').pop() || repo.localPath
const fullPath = path.resolve(getReposPath(), dirName)
// If this is a worktree, properly remove it from git first
if (repo.isWorktree && repo.branch) {
if (repo.isWorktree && repo.branch && repo.repoUrl) {
const repoName = extractRepoName(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
@@ -391,7 +493,7 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
}
// If this was a worktree, also prune the base repo to clean up any remaining references
if (repo.isWorktree && repo.branch) {
if (repo.isWorktree && repo.branch && repo.repoUrl) {
const repoName = extractRepoName(repo.repoUrl)
const baseRepoPath = path.resolve(getReposPath(), repoName)
@@ -404,9 +506,9 @@ export async function deleteRepoFiles(database: Database, repoId: number): Promi
}
db.deleteRepo(database, repoId)
logger.info(`Repo deleted successfully: ${repo.repoUrl}`)
logger.info(`Repo deleted successfully: ${repoIdentifier}`)
} catch (error: any) {
logger.error(`Failed to delete repo: ${repo.repoUrl}`, error)
logger.error(`Failed to delete repo: ${repoIdentifier}`, error)
throw error
}
}
+2 -1
View File
@@ -7,11 +7,12 @@ export interface Repo extends BaseRepo {
}
export interface CreateRepoInput {
repoUrl: string
repoUrl?: string
localPath: string
branch?: string
defaultBranch: string
cloneStatus: 'cloning' | 'ready' | 'error'
clonedAt: number
isWorktree?: boolean
isLocal?: boolean
}
+20 -7
View File
@@ -30,6 +30,10 @@ describe('Database Queries', () => {
isWorktree: false
}
const existingCheckStmt = {
get: vi.fn().mockReturnValue(undefined)
}
const insertStmt = {
run: vi.fn().mockReturnValue({ changes: 1, lastInsertRowid: 1 })
}
@@ -48,6 +52,7 @@ describe('Database Queries', () => {
}
mockDb.prepare
.mockReturnValueOnce(existingCheckStmt)
.mockReturnValueOnce(insertStmt)
.mockReturnValueOnce(selectStmt)
@@ -61,7 +66,8 @@ describe('Database Queries', () => {
repo.defaultBranch,
repo.cloneStatus,
repo.clonedAt,
repo.isWorktree ? 1 : 0
repo.isWorktree ? 1 : 0,
0
)
expect(result.id).toBe(1)
})
@@ -69,6 +75,7 @@ describe('Database Queries', () => {
describe('getRepoById', () => {
it('should retrieve repo by ID', () => {
const clonedAt = Date.now()
const repoRow = {
id: 1,
repo_url: 'https://github.com/test/repo',
@@ -76,10 +83,11 @@ describe('Database Queries', () => {
branch: 'main',
default_branch: 'main',
clone_status: 'ready',
cloned_at: Date.now(),
last_pulled: undefined,
opencode_config_name: undefined,
is_worktree: 0
cloned_at: clonedAt,
last_pulled: null,
opencode_config_name: null,
is_worktree: 0,
is_local: 0
}
const stmt = {
@@ -89,14 +97,19 @@ describe('Database Queries', () => {
const result = db.getRepoById(mockDb, 1)
expect(result).toMatchObject({
expect(result).toEqual({
id: 1,
repoUrl: 'https://github.com/test/repo',
localPath: 'repos/test-repo',
fullPath: expect.stringContaining('repos/test-repo'),
branch: 'main',
defaultBranch: 'main',
cloneStatus: 'ready',
clonedAt: repoRow.cloned_at
clonedAt: clonedAt,
lastPulled: null,
openCodeConfigName: null,
isWorktree: undefined,
isLocal: undefined
})
})
+5
View File
@@ -111,6 +111,11 @@ export class OpenCodeClient {
return response.data
}
async respondToPermission(sessionID: string, permissionID: string, response: 'once' | 'always' | 'reject') {
const result = await this.client.post(`/session/${sessionID}/permissions/${permissionID}`, { response })
return result.data
}
getEventSourceURL() {
const base = this.baseURL.startsWith('http')
? this.baseURL
+3 -2
View File
@@ -2,7 +2,8 @@ import type { Repo } from './types'
import { API_BASE_URL } from '@/config'
export async function createRepo(
repoUrl: string,
repoUrl?: string,
localPath?: string,
branch?: string,
openCodeConfigName?: string,
useWorktree?: boolean
@@ -10,7 +11,7 @@ export async function createRepo(
const response = await fetch(`${API_BASE_URL}/api/repos`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ repoUrl, branch, openCodeConfigName, useWorktree }),
body: JSON.stringify({ repoUrl, localPath, branch, openCodeConfigName, useWorktree }),
})
if (!response.ok) {
+18 -2
View File
@@ -18,6 +18,8 @@ import type { components } from './opencode-types'
export type Message = components['schemas']['Message']
export type Part = components['schemas']['Part']
export type Session = components['schemas']['Session']
export type Permission = components['schemas']['Permission']
export type PermissionResponse = 'once' | 'always' | 'reject'
export type MessageWithParts = {
info: Message
@@ -86,6 +88,20 @@ export interface SSETodoUpdatedEvent {
}
}
export interface SSEPermissionUpdatedEvent {
type: 'permission.updated'
properties: Permission
}
export interface SSEPermissionRepliedEvent {
type: 'permission.replied'
properties: {
sessionID: string
permissionID: string
response: string
}
}
export type SSEEvent =
| SSEMessagePartUpdatedEvent
| SSEMessageUpdatedEvent
@@ -95,8 +111,8 @@ export type SSEEvent =
| SSESessionDeletedEvent
| SSESessionCompactedEvent
| SSETodoUpdatedEvent
| { type: 'permission.updated'; properties: Record<string, unknown> }
| { type: 'permission.replied'; properties: Record<string, unknown> }
| SSEPermissionUpdatedEvent
| SSEPermissionRepliedEvent
export type ContentPart =
| { type: 'text', content: string }
@@ -28,7 +28,7 @@ export function AddBranchWorkspaceDialog({
const mutation = useMutation({
mutationFn: () =>
createRepo(repoUrl, branch || undefined, undefined, useWorktree),
createRepo(repoUrl, undefined, branch || undefined, undefined, useWorktree),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setBranch("");
+74 -14
View File
@@ -12,23 +12,33 @@ interface AddRepoDialogProps {
}
export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
const [repoType, setRepoType] = useState<'remote' | 'local'>('remote')
const [repoUrl, setRepoUrl] = useState('')
const [localPath, setLocalPath] = useState('')
const [branch, setBranch] = useState('')
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: () => createRepo(repoUrl, branch || undefined, undefined, false),
mutationFn: () => {
if (repoType === 'local') {
return createRepo(undefined, localPath, branch || undefined, undefined, false)
} else {
return createRepo(repoUrl, undefined, branch || undefined, undefined, false)
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repos'] })
setRepoUrl('')
setLocalPath('')
setBranch('')
setRepoType('remote')
onOpenChange(false)
},
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (repoUrl) {
if ((repoType === 'remote' && repoUrl) || (repoType === 'local' && localPath)) {
mutation.mutate()
}
}
@@ -43,15 +53,61 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-4">
<div className="space-y-2">
<label className="text-sm text-zinc-400">Repository URL</label>
<Input
placeholder="https://github.com/user/repo.git"
value={repoUrl}
onChange={(e) => setRepoUrl(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
<label className="text-sm text-zinc-400">Repository Type</label>
<div className="flex gap-4">
<label className="flex items-center space-x-2 cursor-pointer">
<input
type="radio"
name="repoType"
value="remote"
checked={repoType === 'remote'}
onChange={(e) => setRepoType(e.target.value as 'remote')}
disabled={mutation.isPending}
className="text-blue-600 bg-[#1a1a1a] border-[#2a2a2a]"
/>
<span className="text-sm text-white">Remote Repository</span>
</label>
<label className="flex items-center space-x-2 cursor-pointer">
<input
type="radio"
name="repoType"
value="local"
checked={repoType === 'local'}
onChange={(e) => setRepoType(e.target.value as 'local')}
disabled={mutation.isPending}
className="text-blue-600 bg-[#1a1a1a] border-[#2a2a2a]"
/>
<span className="text-sm text-white">Local Repository</span>
</label>
</div>
</div>
{repoType === 'remote' ? (
<div className="space-y-2">
<label className="text-sm text-zinc-400">Repository URL</label>
<Input
placeholder="https://github.com/user/repo.git"
value={repoUrl}
onChange={(e) => setRepoUrl(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
</div>
) : (
<div className="space-y-2">
<label className="text-sm text-zinc-400">Local Path</label>
<Input
placeholder="my-local-project"
value={localPath}
onChange={(e) => setLocalPath(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
<p className="text-xs text-zinc-500">
Directory name will be created in the repos folder
</p>
</div>
)}
<div className="space-y-2">
<label className="text-sm text-zinc-400">Branch</label>
@@ -64,21 +120,25 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
/>
<p className="text-xs text-zinc-500">
{branch
? `Clones repository directly to '${branch}' branch`
: "Clones repository to default branch"
? repoType === 'remote'
? `Clones repository directly to '${branch}' branch`
: `Initializes repository with '${branch}' branch`
: repoType === 'remote'
? "Clones repository to default branch"
: "Initializes repository with 'main' branch"
}
</p>
</div>
<Button
type="submit"
disabled={!repoUrl || mutation.isPending}
disabled={(!repoUrl && repoType === 'remote') || (!localPath && repoType === 'local') || mutation.isPending}
className="w-full bg-blue-600 hover:bg-blue-700 text-white"
>
{mutation.isPending ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Cloning...
{repoType === 'local' ? 'Initializing...' : 'Cloning...'}
</>
) : (
'Add Repository'
+17 -11
View File
@@ -18,7 +18,7 @@ interface BranchSwitcherProps {
repoId: number;
currentBranch: string;
isWorktree?: boolean;
repoUrl: string;
repoUrl?: string | null;
repoLocalPath?: string;
}
@@ -28,7 +28,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
const queryClient = useQueryClient();
const { data: gitStatus } = useGitStatus(repoId);
const { data: branches } = useQuery({
const { data: branches, isLoading: branchesLoading } = useQuery({
queryKey: ["branches", repoId],
queryFn: () => listBranches(repoId),
enabled: !!repoId,
@@ -60,8 +60,12 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="bg-card border-border min-w-[200px]">
{branches?.remote && branches.remote.length > 0 ? (
branches.remote.map((branch: string) => (
{branchesLoading ? (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
</DropdownMenuItem>
) : branches?.local && branches.local.length > 0 ? (
branches.local.map((branch: string) => (
<DropdownMenuItem
key={branch}
onClick={() => switchBranchMutation.mutate(branch)}
@@ -77,7 +81,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
))
) : (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
No branches available
</DropdownMenuItem>
)}
<DropdownMenuSeparator />
@@ -95,7 +99,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
)}
</div>
</DropdownMenuItem>
{!isWorktree && (
{!isWorktree && repoUrl && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
@@ -112,11 +116,13 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep
</DropdownMenuContent>
</DropdownMenu>
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repoUrl}
/>
{repoUrl && (
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repoUrl}
/>
)}
<GitChangesSheet
isOpen={gitChangesOpen}
+27 -19
View File
@@ -8,11 +8,13 @@ import { AddBranchWorkspaceDialog } from "./AddBranchWorkspaceDialog";
interface RepoCardProps {
repo: {
id: number;
repoUrl: string;
repoUrl?: string | null;
localPath?: string;
branch?: string;
currentBranch?: string;
cloneStatus: string;
isWorktree?: boolean;
isLocal?: boolean;
};
onDelete: (id: number) => void;
isDeleting: boolean;
@@ -29,7 +31,9 @@ export function RepoCard({
}: RepoCardProps) {
const navigate = useNavigate();
const [addBranchOpen, setAddBranchOpen] = useState(false);
const repoName = repo.repoUrl.split("/").slice(-1)[0].replace(".git", "");
const repoName = repo.repoUrl
? repo.repoUrl.split("/").slice(-1)[0].replace(".git", "")
: repo.localPath || "Local Repo";
const branchToDisplay = repo.currentBranch || repo.branch;
const isReady = repo.cloneStatus === "ready";
@@ -115,18 +119,20 @@ export function RepoCard({
<ExternalLink className="w-4 h-4 mr-2" />
Open
</Button>
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.stopPropagation();
setAddBranchOpen(true);
}}
disabled={!isReady}
className="h-10 sm:h-9 w-10 p-0"
>
<GitBranch className="w-4 h-4" />
</Button>
{repo.repoUrl && (
<Button
size="sm"
variant="outline"
onClick={(e) => {
e.stopPropagation();
setAddBranchOpen(true);
}}
disabled={!isReady}
className="h-10 sm:h-9 w-10 p-0"
>
<GitBranch className="w-4 h-4" />
</Button>
)}
<Button
size="sm"
@@ -148,11 +154,13 @@ export function RepoCard({
</div>
</div>
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repo.repoUrl}
/>
{repo.repoUrl && (
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repo.repoUrl}
/>
)}
</div>
);
}
+7 -4
View File
@@ -76,8 +76,8 @@ export function RepoList() {
if (repo.isWorktree) {
acc.push(repo);
} else {
const key = repo.repoUrl;
const existing = acc.find(r => r.repoUrl === key && !r.isWorktree);
const key = repo.repoUrl || repo.localPath;
const existing = acc.find(r => (r.repoUrl || r.localPath) === key && !r.isWorktree);
if (!existing) {
acc.push(repo);
@@ -88,10 +88,13 @@ export function RepoList() {
}, [] as typeof repos);
const filteredRepos = dedupedRepos.filter((repo) => {
const repoName = repo.repoUrl.split("/").slice(-1)[0].replace(".git", "");
const repoName = repo.repoUrl
? repo.repoUrl.split("/").slice(-1)[0].replace(".git", "")
: repo.localPath;
const searchTarget = repo.repoUrl || repo.localPath || "";
return (
repoName.toLowerCase().includes(searchQuery.toLowerCase()) ||
repo.repoUrl.toLowerCase().includes(searchQuery.toLowerCase())
searchTarget.toLowerCase().includes(searchQuery.toLowerCase())
);
});
@@ -0,0 +1,164 @@
import { useState } from 'react'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import type { Permission, PermissionResponse } from '@/api/types'
import { cn } from '@/lib/utils'
interface PermissionRequestDialogProps {
permission: Permission | null
pendingCount: number
onRespond: (permissionID: string, sessionID: string, response: PermissionResponse) => Promise<void>
onDismiss: (permissionID: string) => void
}
function getPermissionTypeLabel(type: string): string {
switch (type) {
case 'bash':
return 'Run Command'
case 'edit':
return 'Edit File'
case 'webfetch':
return 'Fetch URL'
default:
return type.charAt(0).toUpperCase() + type.slice(1)
}
}
function getPermissionDescription(permission: Permission): string {
const patterns = Array.isArray(permission.pattern)
? permission.pattern
: permission.pattern
? [permission.pattern]
: []
if (patterns.length > 0) {
return patterns.join('\n')
}
if (permission.metadata?.command) {
return String(permission.metadata.command)
}
if (permission.metadata?.path) {
return String(permission.metadata.path)
}
if (permission.metadata?.url) {
return String(permission.metadata.url)
}
return ''
}
export function PermissionRequestDialog({
permission,
pendingCount,
onRespond,
onDismiss,
}: PermissionRequestDialogProps) {
const [isLoading, setIsLoading] = useState(false)
const [loadingAction, setLoadingAction] = useState<PermissionResponse | null>(null)
if (!permission) return null
const handleResponse = async (response: PermissionResponse) => {
setIsLoading(true)
setLoadingAction(response)
try {
await onRespond(permission.id, permission.sessionID, response)
} catch (error) {
console.error('Failed to respond to permission:', error)
onDismiss(permission.id)
} finally {
setIsLoading(false)
setLoadingAction(null)
}
}
const typeLabel = getPermissionTypeLabel(permission.type)
const description = getPermissionDescription(permission)
const hasMultiple = pendingCount > 1
return (
<Dialog open={true} onOpenChange={() => {}}>
<DialogContent hideCloseButton className="sm:max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
Permission Request
{hasMultiple && (
<span className="text-xs font-normal text-muted-foreground bg-muted px-2 py-0.5 rounded-full">
+{pendingCount - 1} more
</span>
)}
</DialogTitle>
<DialogDescription>
{permission.title || `Allow ${typeLabel.toLowerCase()}?`}
</DialogDescription>
</DialogHeader>
<div className="space-y-3">
<div className="flex items-center gap-2">
<span className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
{typeLabel}
</span>
</div>
{description && (
<div className="bg-muted/50 border rounded-md p-3 max-h-32 overflow-y-auto">
<pre className="text-sm font-mono whitespace-pre-wrap break-all">
{description}
</pre>
</div>
)}
<div className="text-xs text-muted-foreground">
Session: <span className="font-mono">{permission.sessionID.slice(0, 12)}...</span>
</div>
</div>
<DialogFooter className="flex-row gap-2 sm:justify-between">
<Button
variant="outline"
onClick={() => handleResponse('reject')}
disabled={isLoading}
className={cn(
"flex-1",
loadingAction === 'reject' && "opacity-70"
)}
>
{loadingAction === 'reject' ? 'Denying...' : 'Deny'}
</Button>
<Button
variant="secondary"
onClick={() => handleResponse('once')}
disabled={isLoading}
className={cn(
"flex-1",
loadingAction === 'once' && "opacity-70"
)}
>
{loadingAction === 'once' ? 'Allowing...' : 'Allow Once'}
</Button>
<Button
variant="default"
onClick={() => handleResponse('always')}
disabled={isLoading}
className={cn(
"flex-1",
loadingAction === 'always' && "opacity-70"
)}
>
{loadingAction === 'always' ? 'Allowing...' : 'Allow Always'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -7,11 +7,12 @@ import { useState } from "react";
interface Repo {
id: number;
repoUrl: string;
repoUrl?: string | null;
fullPath: string;
localPath: string;
currentBranch?: string;
isWorktree?: boolean;
isLocal?: boolean;
cloneStatus: 'ready' | 'cloning' | 'error';
}
@@ -56,7 +57,7 @@ export function SessionDetailHeader({
);
}
const repoName = repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository";
const repoName = repo.repoUrl?.split("/").pop()?.replace(".git", "") || repo.localPath || "Repository";
const currentBranch = repo.currentBranch || "main";
const handleTitleClick = () => {
@@ -0,0 +1,62 @@
import { useState, useEffect, useCallback } from 'react'
import type { Permission } from '@/api/types'
type PermissionEventType = 'add' | 'remove'
interface PermissionEvent {
type: PermissionEventType
permission?: Permission
permissionID?: string
}
type PermissionListener = (event: PermissionEvent) => void
const listeners = new Set<PermissionListener>()
export const permissionEvents = {
emit: (event: PermissionEvent) => {
listeners.forEach(listener => listener(event))
},
subscribe: (listener: PermissionListener) => {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
}
}
export function usePermissionRequests() {
const [permissions, setPermissions] = useState<Permission[]>([])
useEffect(() => {
const unsubscribe = permissionEvents.subscribe((event) => {
if (event.type === 'add' && event.permission) {
setPermissions(prev => {
const exists = prev.some(p => p.id === event.permission!.id)
if (exists) return prev
return [...prev, event.permission!]
})
} else if (event.type === 'remove' && event.permissionID) {
setPermissions(prev => prev.filter(p => p.id !== event.permissionID))
}
})
return unsubscribe
}, [])
const currentPermission = permissions[0] || null
const dismissPermission = useCallback((permissionID: string) => {
setPermissions(prev => prev.filter(p => p.id !== permissionID))
}, [])
const clearAllPermissions = useCallback(() => {
setPermissions([])
}, [])
return {
currentPermission,
pendingCount: permissions.length,
dismissPermission,
clearAllPermissions
}
}
+9
View File
@@ -2,6 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { useOpenCodeClient } from './useOpenCode'
import type { SSEEvent, MessageListResponse } from '@/api/types'
import { permissionEvents } from './usePermissionRequests'
export const useSSE = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory)
@@ -231,7 +232,15 @@ case 'message.updated':
}
case 'permission.updated':
if ('id' in event.properties) {
permissionEvents.emit({ type: 'add', permission: event.properties })
}
break
case 'permission.replied':
if ('permissionID' in event.properties) {
permissionEvents.emit({ type: 'remove', permissionID: event.properties.permissionID })
}
break
case 'todo.updated':
+3 -2
View File
@@ -82,8 +82,9 @@ export function RepoDetail() {
);
}
const repoName =
repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository";
const repoName = repo.repoUrl
? repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository"
: repo.localPath || "Local Repository";
const branchToDisplay = repo.currentBranch || repo.branch;
const displayName = branchToDisplay ? `${repoName} (${branchToDisplay})` : repoName;
const isNotMainBranch = branchToDisplay && branchToDisplay !== repo.defaultBranch;
+23 -3
View File
@@ -7,16 +7,19 @@ import { PromptInput } from "@/components/message/PromptInput";
import { ModelSelectDialog } from "@/components/model/ModelSelectDialog";
import { SessionDetailHeader } from "@/components/session/SessionDetailHeader";
import { SessionList } from "@/components/session/SessionList";
import { PermissionRequestDialog } from "@/components/session/PermissionRequestDialog";
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import { useSession, useAbortSession, useUpdateSession } from "@/hooks/useOpenCode";
import { useSession, useAbortSession, useUpdateSession, useOpenCodeClient } from "@/hooks/useOpenCode";
import { OPENCODE_API_ENDPOINT } from "@/config";
import { useSSE } from "@/hooks/useSSE";
import { useSettings } from "@/hooks/useSettings";
import { useKeyboardShortcuts } from "@/hooks/useKeyboardShortcuts";
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
import { usePermissionRequests } from "@/hooks/usePermissionRequests";
import { useEffect, useRef, useCallback } from "react";
import { Loader2 } from "lucide-react";
import type { PermissionResponse } from "@/api/types";
export function SessionDetail() {
const { id, sessionId } = useParams<{ id: string; sessionId: string }>();
@@ -35,9 +38,10 @@ export function SessionDetail() {
enabled: !!repoId,
});
const { currentPermission, pendingCount, dismissPermission } = usePermissionRequests();
const opcodeUrl = OPENCODE_API_ENDPOINT;
const openCodeClient = useOpenCodeClient(opcodeUrl, repo?.fullPath);
const repoDirectory = repo?.fullPath;
@@ -107,6 +111,15 @@ export function SessionDetail() {
setSelectedFilePath(undefined)
}, []);
const handlePermissionResponse = useCallback(async (
permissionID: string,
permissionSessionID: string,
response: PermissionResponse
) => {
if (!openCodeClient) return
await openCodeClient.respondToPermission(permissionSessionID, permissionID, response)
}, [openCodeClient]);
if (repoLoading || sessionLoading) {
return (
<div className="flex items-center justify-center min-h-screen bg-gradient-to-br from-background via-background to-background">
@@ -215,9 +228,16 @@ export function SessionDetail() {
isOpen={fileBrowserOpen}
onClose={handleFileBrowserClose}
basePath={repo.localPath}
repoName={repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository"}
repoName={repo.repoUrl?.split("/").pop()?.replace(".git", "") || repo.localPath || "Repository"}
initialSelectedFile={selectedFilePath}
/>
<PermissionRequestDialog
permission={currentPermission}
pendingCount={pendingCount}
onRespond={handlePermissionResponse}
onDismiss={dismissPermission}
/>
</div>
);
}
+11 -3
View File
@@ -4,7 +4,7 @@ export const RepoStatusSchema = z.enum(['cloning', 'ready', 'error'])
export const RepoSchema = z.object({
id: z.number(),
repoUrl: z.string().url(),
repoUrl: z.string().url().optional(),
localPath: z.string(),
fullPath: z.string(),
branch: z.string().optional(),
@@ -14,11 +14,19 @@ export const RepoSchema = z.object({
lastPulled: z.number().optional(),
openCodeConfigName: z.string().optional(),
isWorktree: z.boolean().optional(),
isLocal: z.boolean().optional(),
})
export const CreateRepoRequestSchema = z.object({
repoUrl: z.string().url(),
repoUrl: z.string().url().optional(),
localPath: z.string().optional(),
branch: z.string().optional(),
openCodeConfigName: z.string().optional(),
useWorktree: z.boolean().optional(),
})
}).refine(
(data) => data.repoUrl || data.localPath,
{
message: "Either repoUrl or localPath must be provided",
path: ["repoUrl"],
}
)