feat(repo): add graphical folder picker for adding local repositories (#324)

* feat(repo): add graphical folder picker for adding local repositories

Previously, adding a local repository or scanning a folder in the
"Add Repository" dialog required typing an absolute filesystem path by
hand. This adds a navigable directory browser so users can select a
folder graphically instead.

Backend
- New shared Zod schemas (DirectoryEntry, BrowseDirectoryResponse,
  BrowseDirectoryRequest) exported via shared/types and shared/schemas.
- New env var REPO_BROWSE_ROOT plus getBrowseRootPath() helper. It is
  intentionally NOT defaulted to WORKSPACE_PATH: folder browsing is
  opt-in and only works when an administrator explicitly configures a
  root directory.
- New filesystem service (browseDirectory) that lists only directories
  (hidden entries filtered), flags Git repositories, and confines all
  access to the configured root:
    - 501 when REPO_BROWSE_ROOT is not configured
    - 403 on path traversal outside the root
    - 404 for missing directories, 400 when the target is a file
- New authenticated route GET /api/filesystem/browse, registered under
  the protected API group.

Frontend
- New api client browseDirectory() (uses fetchWrapper, so auth cookies
  are sent).
- New DirectoryPickerDialog: navigate into subfolders, go up a level,
  Git repos marked with an icon, and a "Select This Folder" action.
  Retries are disabled so a configuration error is not polled
  repeatedly.
- When browsing is disabled (501), the dialog shows a clear, actionable
  message telling the user to set REPO_BROWSE_ROOT and to enter the
  path manually in the meantime, instead of a generic error.
- AddRepoDialog gains a "Browse" button next to both the Local and
  Folder path inputs; the chosen path is written back into the active
  field.

Tests
- Service and route tests covering listing, Git-repo detection, hidden
  filtering, parent navigation, and the 400/403/404/501 error paths.

Security note: because there is no default root, the picker is inert
until REPO_BROWSE_ROOT is set, and it can never escape that root.

* fix(fs): reject symlink escapes in directory browse

Canonicalize root and requested path with fs.realpath() and gate on
path.relative() so symlinks inside REPO_BROWSE_ROOT pointing outside
are rejected with 403 before fs.stat/fs.readdir follow them. Handles
root '/' correctly. Adds regression test for symlink escape.

* fix(ui): make directory picker fill dialog height

Replace grid content-start packing with explicit grid-rows tracks so
the directory list grows to fill the dialog and scrolls while the
header, path, and footer stay fixed. Drops the ineffective flex-1
from the grid child on the scroll container.

---------

Co-authored-by: Chris Scott <99081550+chriswritescode-dev@users.noreply.github.com>
This commit is contained in:
Alexander DrewekeandChris Scott authored and GitHub committed 2026-07-26 21:12:13 -04:00
1 parent 8d5102dc90
commit f8e361c0b8
12 files changed
+536 -37

No files matched your search

+3 -1
View File
@@ -12,6 +12,7 @@ import { createHealthRoutes } from './routes/health'
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts';
import { createSTTRoutes } from './routes/stt'
import { createFileRoutes } from './routes/files'
import { createFilesystemRoutes } from './routes/filesystem'
import { createScheduleRoutes } from './routes/schedules'
async function getAppVersion(): Promise<string> {
@@ -357,7 +358,8 @@ protectedApi.use('/*', requireAuth)
protectedApi.route('/repos', createRepoRoutes(db, gitAuthService, scheduleService, openCodeClient, openCodeSupervisor))
protectedApi.route('/settings', createSettingsRoutes(db, gitAuthService, openCodeClient, openCodeSupervisor))
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/files', createFileRoutes())
protectedApi.route('/filesystem', createFilesystemRoutes())
protectedApi.route('/providers', createProvidersRoutes(db, openCodeClient, openCodeSupervisor))
protectedApi.route('/oauth', createOAuthRoutes(openCodeClient, openCodeSupervisor))
protectedApi.route('/tts', createTTSRoutes(db))
+60
View File
@@ -0,0 +1,60 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { Hono } from 'hono'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { createFilesystemRoutes } from './filesystem'
let tmpRoot: string
let app: Hono
const originalBrowseRoot = process.env.REPO_BROWSE_ROOT
beforeEach(async () => {
tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-fs-route-'))
process.env.REPO_BROWSE_ROOT = tmpRoot
app = new Hono()
app.route('/filesystem', createFilesystemRoutes())
})
afterEach(async () => {
if (originalBrowseRoot === undefined) {
delete process.env.REPO_BROWSE_ROOT
} else {
process.env.REPO_BROWSE_ROOT = originalBrowseRoot
}
await fs.rm(tmpRoot, { recursive: true, force: true })
})
describe('GET /api/filesystem/browse', () => {
it('returns the directory listing for the root', async () => {
await fs.mkdir(path.join(tmpRoot, 'projects'))
const res = await app.request('/filesystem/browse')
expect(res.status).toBe(200)
const body = await res.json() as { isRoot: boolean; entries: { name: string }[] }
expect(body.isRoot).toBe(true)
expect(body.entries.map((e) => e.name)).toEqual(['projects'])
})
it('returns 403 for a path outside the root', async () => {
const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-fs-outside-'))
try {
const res = await app.request(`/filesystem/browse?path=${encodeURIComponent(outside)}`)
expect(res.status).toBe(403)
} finally {
await fs.rm(outside, { recursive: true, force: true })
}
})
it('returns 404 for a missing directory', async () => {
const res = await app.request(`/filesystem/browse?path=${encodeURIComponent(path.join(tmpRoot, 'missing'))}`)
expect(res.status).toBe(404)
})
it('returns 501 when browsing is not configured', async () => {
delete process.env.REPO_BROWSE_ROOT
const res = await app.request('/filesystem/browse')
expect(res.status).toBe(501)
})
})
+22
View File
@@ -0,0 +1,22 @@
import { Hono } from 'hono'
import type { ContentfulStatusCode } from 'hono/utils/http-status'
import * as filesystemService from '../services/filesystem'
import { logger } from '../utils/logger'
import { getErrorMessage, getStatusCode } from '../utils/error-utils'
export function createFilesystemRoutes() {
const app = new Hono()
app.get('/browse', async (c) => {
try {
const requestedPath = c.req.query('path')
const result = await filesystemService.browseDirectory(requestedPath)
return c.json(result)
} catch (error: unknown) {
logger.error('Failed to browse directory:', error)
return c.json({ error: getErrorMessage(error) || 'Failed to browse directory' }, getStatusCode(error) as ContentfulStatusCode)
}
})
return app
}
+113
View File
@@ -0,0 +1,113 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import { promises as fs } from 'node:fs'
import path from 'node:path'
import os from 'node:os'
import { browseDirectory } from './filesystem'
let tmpRoot: string
const originalBrowseRoot = process.env.REPO_BROWSE_ROOT
beforeEach(async () => {
tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-browse-'))
process.env.REPO_BROWSE_ROOT = tmpRoot
})
afterEach(async () => {
if (originalBrowseRoot === undefined) {
delete process.env.REPO_BROWSE_ROOT
} else {
process.env.REPO_BROWSE_ROOT = originalBrowseRoot
}
await fs.rm(tmpRoot, { recursive: true, force: true })
})
describe('browseDirectory', () => {
it('lists only directories at the browse root and marks the root', async () => {
await fs.mkdir(path.join(tmpRoot, 'projects'))
await fs.mkdir(path.join(tmpRoot, 'archive'))
await fs.writeFile(path.join(tmpRoot, 'readme.txt'), 'ignored file')
const result = await browseDirectory()
expect(result.isRoot).toBe(true)
expect(result.parentPath).toBeNull()
expect(result.path).toBe(path.resolve(tmpRoot))
expect(result.entries.map((e) => e.name)).toEqual(['archive', 'projects'])
})
it('marks git repositories', async () => {
const repoDir = path.join(tmpRoot, 'my-repo')
await fs.mkdir(repoDir)
await fs.mkdir(path.join(repoDir, '.git'))
await fs.mkdir(path.join(tmpRoot, 'plain'))
const result = await browseDirectory()
const repo = result.entries.find((e) => e.name === 'my-repo')
const plain = result.entries.find((e) => e.name === 'plain')
expect(repo?.isGitRepo).toBe(true)
expect(plain?.isGitRepo).toBe(false)
})
it('ignores hidden directories', async () => {
await fs.mkdir(path.join(tmpRoot, '.hidden'))
await fs.mkdir(path.join(tmpRoot, 'visible'))
const result = await browseDirectory()
expect(result.entries.map((e) => e.name)).toEqual(['visible'])
})
it('navigates into a subdirectory and exposes the parent path', async () => {
const sub = path.join(tmpRoot, 'level1')
await fs.mkdir(sub)
await fs.mkdir(path.join(sub, 'level2'))
const result = await browseDirectory(sub)
expect(result.isRoot).toBe(false)
expect(result.parentPath).toBe(path.resolve(tmpRoot))
expect(result.entries.map((e) => e.name)).toEqual(['level2'])
})
it('rejects paths outside the browse root with 403', async () => {
const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-outside-'))
try {
await expect(browseDirectory(outside)).rejects.toMatchObject({ statusCode: 403 })
} finally {
await fs.rm(outside, { recursive: true, force: true })
}
})
it('rejects traversal above the root with 403', async () => {
await expect(browseDirectory(path.join(tmpRoot, '..'))).rejects.toMatchObject({ statusCode: 403 })
})
it('rejects a symlink inside the root that escapes the root with 403', async () => {
const outside = await fs.mkdtemp(path.join(os.tmpdir(), 'ocm-outside-'))
try {
const linkPath = path.join(tmpRoot, 'escape-link')
await fs.symlink(outside, linkPath)
await expect(browseDirectory(linkPath)).rejects.toMatchObject({ statusCode: 403 })
} finally {
await fs.rm(outside, { recursive: true, force: true })
}
})
it('returns 404 for a non-existent directory', async () => {
await expect(browseDirectory(path.join(tmpRoot, 'nope'))).rejects.toMatchObject({ statusCode: 404 })
})
it('returns 400 when the path is a file', async () => {
const filePath = path.join(tmpRoot, 'file.txt')
await fs.writeFile(filePath, 'data')
await expect(browseDirectory(filePath)).rejects.toMatchObject({ statusCode: 400 })
})
it('returns 501 when REPO_BROWSE_ROOT is not configured', async () => {
delete process.env.REPO_BROWSE_ROOT
await expect(browseDirectory()).rejects.toMatchObject({ statusCode: 501 })
})
})
+89
View File
@@ -0,0 +1,89 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { getBrowseRootPath } from '@opencode-manager/shared/config/env'
import type { BrowseDirectoryResponse, DirectoryEntry } from '@opencode-manager/shared/types'
function getRoot(): string {
const configured = getBrowseRootPath()
if (!configured) {
throw {
message: 'Folder browsing is disabled. Set REPO_BROWSE_ROOT in the server environment to enable it.',
statusCode: 501,
}
}
return path.resolve(configured)
}
async function resolveWithinRoot(root: string, requestedPath?: string): Promise<string> {
const resolved = (!requestedPath || requestedPath.trim() === '') ? root : path.resolve(requestedPath)
const realRoot = await fs.realpath(root)
let realResolved: string
try {
realResolved = await fs.realpath(resolved)
} catch (err: unknown) {
const code = (err as NodeJS.ErrnoException | undefined)?.code
if (code === 'ENOENT' || code === 'ENOTDIR') {
throw { message: 'Directory not found', statusCode: 404 }
}
throw err
}
const rel = path.relative(realRoot, realResolved)
if (rel === '..' || rel.startsWith(`..${path.sep}`)) {
throw { message: 'Path is outside the allowed browse root', statusCode: 403 }
}
return resolved
}
async function isGitRepo(entryPath: string): Promise<boolean> {
try {
const stats = await fs.lstat(path.join(entryPath, '.git'))
return stats.isDirectory() || stats.isFile()
} catch {
return false
}
}
export async function browseDirectory(requestedPath?: string): Promise<BrowseDirectoryResponse> {
const root = getRoot()
const targetPath = await resolveWithinRoot(root, requestedPath)
let stats
try {
stats = await fs.stat(targetPath)
} catch {
throw { message: 'Directory not found', statusCode: 404 }
}
if (!stats.isDirectory()) {
throw { message: 'Path is not a directory', statusCode: 400 }
}
const dirEntries = await fs.readdir(targetPath, { withFileTypes: true })
const directories = dirEntries.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
const entries: DirectoryEntry[] = await Promise.all(
directories.map(async (entry) => {
const entryPath = path.join(targetPath, entry.name)
return {
name: entry.name,
path: entryPath,
isGitRepo: await isGitRepo(entryPath),
}
})
)
entries.sort((a, b) => a.name.localeCompare(b.name))
const isRoot = targetPath === root
const parentPath = isRoot ? null : path.dirname(targetPath)
return {
path: targetPath,
parentPath,
isRoot,
entries,
}
}
+9
View File
@@ -0,0 +1,9 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { BrowseDirectoryResponse } from '@opencode-manager/shared/types'
export async function browseDirectory(path?: string): Promise<BrowseDirectoryResponse> {
return fetchWrapper(`${API_BASE_URL}/api/filesystem/browse`, {
params: { path },
})
}
+74 -36
View File
@@ -5,7 +5,8 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Loader2 } from 'lucide-react'
import { DirectoryPickerDialog } from './DirectoryPickerDialog'
import { Loader2, FolderSearch } from 'lucide-react'
import { showToast } from '@/lib/toast'
import { invalidateRepoListCaches } from '@/lib/queryInvalidation'
import { getRepoBaseDirectoryName, getRepoDirectoryNameError, getRepoNameFromUrl, normalizeRepoUrlForCompare, sanitizeRepoDirectoryName } from '@opencode-manager/shared/utils'
@@ -25,6 +26,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
const [directoryName, setDirectoryName] = useState('')
const [branch, setBranch] = useState('')
const [skipSSHVerification, setSkipSSHVerification] = useState(false)
const [pickerOpen, setPickerOpen] = useState(false)
const directoryTouched = useRef(false)
const queryClient = useQueryClient()
@@ -143,17 +145,17 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen mobileSwipeToClose className="content-start gap-0 sm:max-w-[500px] sm:max-h-[80vh] sm:h-auto sm:top-[50%] sm:translate-y-[-50%] bg-[#141414] border-[#2a2a2a]">
<DialogContent mobileFullscreen mobileSwipeToClose className="content-start gap-0 sm:max-w-[500px] sm:max-h-[80vh] sm:h-auto sm:top-[50%] sm:translate-y-[-50%] bg-card border-border">
<DialogHeader className="px-4 sm:px-6 pt-2 sm:pt-6 pb-2 sm:pb-3 h-fit">
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
<DialogTitle className="text-xl text-foreground">
Add Repository
</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 px-4 sm:px-6">
<div className="space-y-2">
<label className="text-sm text-zinc-400">Repository Type</label>
<label className="text-sm text-muted-foreground">Repository Type</label>
<Tabs value={repoType} onValueChange={(value) => setRepoType(value as 'remote' | 'local' | 'folder')}>
<TabsList className="grid w-full grid-cols-3 bg-[#1a1a1a]">
<TabsList className="grid w-full grid-cols-3 bg-muted">
<TabsTrigger value="remote">Remote</TabsTrigger>
<TabsTrigger value="local">Local</TabsTrigger>
<TabsTrigger value="folder">Folder</TabsTrigger>
@@ -163,43 +165,67 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
{repoType === 'remote' ? (
<div className="space-y-2">
<label className="text-sm text-zinc-400">Repository URL</label>
<label className="text-sm text-muted-foreground">Repository URL</label>
<Input
placeholder="owner/repo or https://github.com/user/repo.git"
value={repoUrl}
onChange={(e) => handleRepoUrlChange(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500 min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
/>
<p className="text-xs text-zinc-500">
<p className="text-xs text-muted-foreground">
Full URL or shorthand format (owner/repo for GitHub)
</p>
</div>
) : repoType === 'local' ? (
<div className="space-y-2">
<label className="text-sm text-zinc-400">Local Path</label>
<Input
placeholder="my-local-project OR /absolute/path/to/git-repo"
value={localPath}
onChange={(e) => setLocalPath(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500 min-h-[44px] text-base"
/>
<p className="text-xs text-zinc-500">
<label className="text-sm text-muted-foreground">Local Path</label>
<div className="flex gap-2">
<Input
placeholder="my-local-project OR /absolute/path/to/git-repo"
value={localPath}
onChange={(e) => setLocalPath(e.target.value)}
disabled={mutation.isPending}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
/>
<Button
type="button"
variant="outline"
onClick={() => setPickerOpen(true)}
disabled={mutation.isPending}
className="min-h-[44px] shrink-0 border-border bg-muted px-3 text-muted-foreground hover:bg-accent"
aria-label="Browse for folder"
>
<FolderSearch className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Directory name for a new repo, or an absolute path to link an existing Git repo
</p>
</div>
) : (
<div className="space-y-2">
<label className="text-sm text-zinc-400">Folder Path</label>
<Input
placeholder="/absolute/path/to/projects"
value={folderPath}
onChange={(e) => setFolderPath(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500 min-h-[44px] text-base"
/>
<p className="text-xs text-zinc-500">
<label className="text-sm text-muted-foreground">Folder Path</label>
<div className="flex gap-2">
<Input
placeholder="/absolute/path/to/projects"
value={folderPath}
onChange={(e) => setFolderPath(e.target.value)}
disabled={mutation.isPending}
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
/>
<Button
type="button"
variant="outline"
onClick={() => setPickerOpen(true)}
disabled={mutation.isPending}
className="min-h-[44px] shrink-0 border-border bg-muted px-3 text-muted-foreground hover:bg-accent"
aria-label="Browse for folder"
>
<FolderSearch className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
Scans the folder for nested Git repositories and links each one
</p>
</div>
@@ -207,13 +233,13 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
{showDirectoryName && (
<div className="space-y-2">
<label className="text-sm text-zinc-400">Directory Name</label>
<label className="text-sm text-muted-foreground">Directory Name</label>
<Input
placeholder="Auto-detected from URL"
value={directoryName}
onChange={(e) => handleDirectoryNameChange(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500 min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
/>
{directoryNameError ? (
<p className="text-xs text-amber-400">
@@ -229,7 +255,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
{' '}Choose a different directory name to clone this fork.
</p>
) : (
<p className="text-xs text-zinc-500">
<p className="text-xs text-muted-foreground">
Custom directory name for the cloned repository
</p>
)}
@@ -237,15 +263,15 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
)}
<div className="space-y-2">
<label className="text-sm text-zinc-400">Branch (optional)</label>
<label className="text-sm text-muted-foreground">Branch (optional)</label>
<Input
placeholder="Uses default if empty"
value={branch}
onChange={(e) => setBranch(e.target.value)}
disabled={mutation.isPending || repoType === 'folder'}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500 min-h-[44px] text-base"
className="bg-muted border-border text-foreground placeholder:text-muted-foreground min-h-[44px] text-base"
/>
<p className="text-xs text-zinc-500">
<p className="text-xs text-muted-foreground">
{repoType === 'folder'
? 'Links each repository on its current branch'
: branch
@@ -263,13 +289,13 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
checked={skipSSHVerification}
onChange={(e) => setSkipSSHVerification(e.target.checked)}
disabled={mutation.isPending}
className="mt-1 h-5 w-5 rounded border-[#2a2a2a] bg-[#1a1a1a] text-blue-600 focus:ring-blue-600"
className="mt-1 h-5 w-5 rounded border-border bg-muted text-primary focus:ring-primary"
/>
<div className="flex-1">
<label htmlFor="skip-ssh-verification" className="cursor-pointer text-sm text-white">
<label htmlFor="skip-ssh-verification" className="cursor-pointer text-sm text-foreground">
Skip SSH host key verification
</label>
<p className="text-xs text-zinc-500">
<p className="text-xs text-muted-foreground">
Auto-accept the SSH host key for self-hosted or internal servers
</p>
</div>
@@ -279,7 +305,7 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
<Button
type="submit"
disabled={(!repoUrl && repoType === 'remote') || (!localPath && repoType === 'local') || (!folderPath && repoType === 'folder') || mutation.isPending || (showDirectoryName && (!!directoryNameError || !!directoryCollision))}
className="w-full min-h-[48px] bg-blue-600 hover:bg-blue-700 text-white text-base font-medium"
className="w-full min-h-[48px] bg-primary hover:bg-primary-hover text-primary-foreground text-base font-medium"
>
{mutation.isPending ? (
<>
@@ -297,6 +323,18 @@ export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
)}
</form>
</DialogContent>
<DirectoryPickerDialog
open={pickerOpen}
onOpenChange={setPickerOpen}
title={repoType === 'folder' ? 'Select Folder to Scan' : 'Select Local Repository'}
onSelect={(path) => {
if (repoType === 'folder') {
setFolderPath(path)
} else {
setLocalPath(path)
}
}}
/>
</Dialog>
)
}
@@ -0,0 +1,125 @@
import { useState, useCallback, useEffect } from 'react'
import { useQuery } from '@tanstack/react-query'
import { browseDirectory } from '@/api/filesystem'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { FetchError } from '@/api/fetchWrapper'
import { Folder, FolderGit2, ChevronUp, Loader2, FolderX } from 'lucide-react'
interface DirectoryPickerDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onSelect: (path: string) => void
title?: string
}
export function DirectoryPickerDialog({ open, onOpenChange, onSelect, title = 'Select Folder' }: DirectoryPickerDialogProps) {
const [currentPath, setCurrentPath] = useState<string | undefined>(undefined)
useEffect(() => {
if (open) {
setCurrentPath(undefined)
}
}, [open])
const { data, isLoading, isError, error } = useQuery({
queryKey: ['filesystem-browse', currentPath],
queryFn: () => browseDirectory(currentPath),
enabled: open,
retry: false,
})
const isDisabled = error instanceof FetchError && error.statusCode === 501
const navigateTo = useCallback((path: string) => {
setCurrentPath(path)
}, [])
const handleSelect = useCallback(() => {
if (data?.path) {
onSelect(data.path)
onOpenChange(false)
}
}, [data?.path, onSelect, onOpenChange])
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent mobileFullscreen className="grid-rows-[auto_auto_minmax(0,1fr)_auto] gap-0 sm:max-w-[560px] sm:max-h-[80vh]">
<DialogHeader className="px-4 sm:px-6 pt-4 sm:pt-6 pb-2 h-fit">
<DialogTitle className="text-lg">{title}</DialogTitle>
</DialogHeader>
<div className="px-4 sm:px-6 pb-2">
<p className="truncate rounded bg-muted px-3 py-2 text-xs text-muted-foreground" title={data?.path}>
{data?.path ?? 'Loading...'}
</p>
</div>
<div className="mx-4 sm:mx-6 mb-4 min-h-0 overflow-y-auto rounded border border-border bg-muted">
{isLoading ? (
<div className="flex h-[240px] items-center justify-center text-muted-foreground">
<Loader2 className="h-5 w-5 animate-spin" />
</div>
) : isDisabled ? (
<div className="flex h-[240px] flex-col items-center justify-center gap-3 px-6 text-center">
<FolderX className="h-8 w-8 text-muted-foreground" />
<p className="text-sm text-foreground">Folder browsing is not enabled</p>
<p className="text-xs text-muted-foreground">
Ask your administrator to set <code className="rounded bg-accent px-1 py-0.5 text-foreground">REPO_BROWSE_ROOT</code> in the
server environment, then enter the path manually for now.
</p>
</div>
) : isError ? (
<div className="flex h-[240px] items-center justify-center px-4 text-center text-sm text-destructive">
{error instanceof Error ? error.message : 'Failed to load directory'}
</div>
) : (
<ul className="divide-y divide-border">
{data && !data.isRoot && data.parentPath !== null && (
<li>
<button
type="button"
onClick={() => navigateTo(data.parentPath!)}
className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-sm text-muted-foreground hover:bg-accent"
>
<ChevronUp className="h-4 w-4 shrink-0 text-muted-foreground" />
..
</button>
</li>
)}
{data?.entries.length === 0 && (
<li className="px-3 py-4 text-center text-sm text-muted-foreground">No subfolders</li>
)}
{data?.entries.map((entry) => (
<li key={entry.path}>
<button
type="button"
onClick={() => navigateTo(entry.path)}
className="flex w-full items-center gap-2 px-3 py-2.5 text-left text-sm text-foreground hover:bg-accent"
>
{entry.isGitRepo ? (
<FolderGit2 className="h-4 w-4 shrink-0 text-primary" />
) : (
<Folder className="h-4 w-4 shrink-0 text-muted-foreground" />
)}
<span className="truncate">{entry.name}</span>
{entry.isGitRepo && <span className="ml-auto text-xs text-primary">git</span>}
</button>
</li>
))}
</ul>
)}
</div>
<DialogFooter className="px-4 sm:px-6 pb-4 sm:pb-6 gap-2">
<Button type="button" variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button type="button" onClick={handleSelect} disabled={!data?.path}>
Select This Folder
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+13
View File
@@ -36,6 +36,17 @@ const resolveWorkspacePath = (): string => {
return path.resolve(DEFAULTS.WORKSPACE.BASE_PATH)
}
const resolveBrowseRoot = (): string => {
const envPath = process.env.REPO_BROWSE_ROOT
if (!envPath) {
return ''
}
if (envPath.startsWith('~')) {
return path.join(os.homedir(), envPath.slice(1))
}
return path.resolve(envPath)
}
const generateDefaultSecret = (): string => {
return randomBytes(32).toString('base64').slice(0, 32)
}
@@ -69,6 +80,7 @@ export const ENV = {
WORKSPACE: {
get BASE_PATH() { return resolveWorkspacePath() },
get BROWSE_ROOT() { return resolveBrowseRoot() },
REPOS_DIR: DEFAULTS.WORKSPACE.REPOS_DIR,
SCHEDULE_WORKTREES_DIR: DEFAULTS.WORKSPACE.SCHEDULE_WORKTREES_DIR,
CONFIG_DIR: DEFAULTS.WORKSPACE.CONFIG_DIR,
@@ -119,6 +131,7 @@ export const ENV = {
} as const
export const getWorkspacePath = () => ENV.WORKSPACE.BASE_PATH
export const getBrowseRootPath = () => ENV.WORKSPACE.BROWSE_ROOT
export const getReposPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.REPOS_DIR)
export const getScheduleWorktreesPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.SCHEDULE_WORKTREES_DIR)
export const getConfigPath = () => path.join(ENV.WORKSPACE.BASE_PATH, ENV.WORKSPACE.CONFIG_DIR)
+18
View File
@@ -0,0 +1,18 @@
import { z } from 'zod'
export const DirectoryEntrySchema = z.object({
name: z.string(),
path: z.string(),
isGitRepo: z.boolean(),
})
export const BrowseDirectoryResponseSchema = z.object({
path: z.string(),
parentPath: z.string().nullable(),
isRoot: z.boolean(),
entries: z.array(DirectoryEntrySchema),
})
export const BrowseDirectoryRequestSchema = z.object({
path: z.string().optional(),
})
+1
View File
@@ -1,6 +1,7 @@
export * from './settings'
export * from './repo'
export * from './files'
export * from './filesystem'
export * from './opencode'
export * from './auth'
export * from './sse'
+9
View File
@@ -36,6 +36,11 @@ import {
SessionSchema,
MessageSchema,
} from '../schemas/opencode'
import {
DirectoryEntrySchema,
BrowseDirectoryResponseSchema,
BrowseDirectoryRequestSchema,
} from '../schemas/filesystem'
import {
NotificationPreferencesSchema,
PushSubscriptionRequestSchema,
@@ -82,6 +87,10 @@ export type FilePatchRequest = z.infer<typeof FilePatchRequestSchema>
export type Session = z.infer<typeof SessionSchema>
export type Message = z.infer<typeof MessageSchema>
export type DirectoryEntry = z.infer<typeof DirectoryEntrySchema>
export type BrowseDirectoryResponse = z.infer<typeof BrowseDirectoryResponseSchema>
export type BrowseDirectoryRequest = z.infer<typeof BrowseDirectoryRequestSchema>
export type NotificationPreferences = z.infer<typeof NotificationPreferencesSchema>
export type PushSubscriptionRequest = z.infer<typeof PushSubscriptionRequestSchema>
export type PushSubscriptionRecord = z.infer<typeof PushSubscriptionRecordSchema>