diff --git a/backend/src/db/migrations.ts b/backend/src/db/migrations.ts index e9b2ec47..83a05eac 100644 --- a/backend/src/db/migrations.ts +++ b/backend/src/db/migrations.ts @@ -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) { diff --git a/backend/src/db/queries.ts b/backend/src/db/queries.ts index 3f10ebd2..f710c06b 100644 --- a/backend/src/db/queries.ts +++ b/backend/src/db/queries.ts @@ -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[] diff --git a/backend/src/db/schema.ts b/backend/src/db/schema.ts index 98727400..e84e0c26 100644 --- a/backend/src/db/schema.ts +++ b/backend/src/db/schema.ts @@ -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); diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index e6b81108..3a2c7c9c 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -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) diff --git a/backend/src/services/repo.ts b/backend/src/services/repo.ts index 5d30fc16..f1e576e2 100644 --- a/backend/src/services/repo.ts +++ b/backend/src/services/repo.ts @@ -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 { + 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 { + 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 { 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 }) }) diff --git a/frontend/src/api/opencode.ts b/frontend/src/api/opencode.ts index 0888ecb3..86ed1325 100644 --- a/frontend/src/api/opencode.ts +++ b/frontend/src/api/opencode.ts @@ -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 diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index 9b0b6b7e..b3d4ecbf 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -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) { diff --git a/frontend/src/api/types.ts b/frontend/src/api/types.ts index d5090889..e4a14f3e 100644 --- a/frontend/src/api/types.ts +++ b/frontend/src/api/types.ts @@ -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 } - | { type: 'permission.replied'; properties: Record } + | SSEPermissionUpdatedEvent + | SSEPermissionRepliedEvent export type ContentPart = | { type: 'text', content: string } diff --git a/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx b/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx index fb79d6a4..44acd5bd 100644 --- a/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx +++ b/frontend/src/components/repo/AddBranchWorkspaceDialog.tsx @@ -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(""); diff --git a/frontend/src/components/repo/AddRepoDialog.tsx b/frontend/src/components/repo/AddRepoDialog.tsx index 4ef3d0f0..d81b8ede 100644 --- a/frontend/src/components/repo/AddRepoDialog.tsx +++ b/frontend/src/components/repo/AddRepoDialog.tsx @@ -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) {
- - setRepoUrl(e.target.value)} - disabled={mutation.isPending} - className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" - /> + +
+ + +
+ + {repoType === 'remote' ? ( +
+ + setRepoUrl(e.target.value)} + disabled={mutation.isPending} + className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" + /> +
+ ) : ( +
+ + setLocalPath(e.target.value)} + disabled={mutation.isPending} + className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500" + /> +

+ Directory name will be created in the repos folder +

+
+ )}
@@ -64,21 +120,25 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) { />

{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" }

- {branches?.remote && branches.remote.length > 0 ? ( - branches.remote.map((branch: string) => ( + {branchesLoading ? ( + + Loading branches... + + ) : branches?.local && branches.local.length > 0 ? ( + branches.local.map((branch: string) => ( switchBranchMutation.mutate(branch)} @@ -77,7 +81,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep )) ) : ( - Loading branches... + No branches available )} @@ -95,7 +99,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, rep )} - {!isWorktree && ( + {!isWorktree && repoUrl && ( <> - + {repoUrl && ( + + )} 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({ Open - + {repo.repoUrl && ( + + )} + + + + + + ) +} diff --git a/frontend/src/components/session/SessionDetailHeader.tsx b/frontend/src/components/session/SessionDetailHeader.tsx index 6da25250..8e0d4bd8 100644 --- a/frontend/src/components/session/SessionDetailHeader.tsx +++ b/frontend/src/components/session/SessionDetailHeader.tsx @@ -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 = () => { diff --git a/frontend/src/hooks/usePermissionRequests.ts b/frontend/src/hooks/usePermissionRequests.ts new file mode 100644 index 00000000..a20205e4 --- /dev/null +++ b/frontend/src/hooks/usePermissionRequests.ts @@ -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() + +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([]) + + 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 + } +} diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 6a08e023..28bc6978 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -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': diff --git a/frontend/src/pages/RepoDetail.tsx b/frontend/src/pages/RepoDetail.tsx index f6977ad1..a5f17ef9 100644 --- a/frontend/src/pages/RepoDetail.tsx +++ b/frontend/src/pages/RepoDetail.tsx @@ -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; diff --git a/frontend/src/pages/SessionDetail.tsx b/frontend/src/pages/SessionDetail.tsx index c2387517..835a574b 100644 --- a/frontend/src/pages/SessionDetail.tsx +++ b/frontend/src/pages/SessionDetail.tsx @@ -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 (
@@ -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} /> + +
); } diff --git a/shared/src/schemas/repo.ts b/shared/src/schemas/repo.ts index 0110fa2e..f54fe666 100644 --- a/shared/src/schemas/repo.ts +++ b/shared/src/schemas/repo.ts @@ -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"], + } +)