Initial release v0.2.5

This commit is contained in:
Chris Scott committed 2025-11-23 23:25:27 -05:00
commit bbf66c259b
158 files changed
+37115

No files matched your search

@@ -0,0 +1,98 @@
import { useEffect, useRef } from 'react'
import { Command } from 'lucide-react'
import type { components } from '@/api/opencode-types'
type CommandType = components['schemas']['Command']
interface CommandSuggestionsProps {
isOpen: boolean
query: string
commands: CommandType[]
onSelect: (command: CommandType) => void
onClose: () => void
position: { bottom: number; left: number; width: number }
selectedIndex?: number
}
export function CommandSuggestions({
isOpen,
query,
commands,
onSelect,
position,
selectedIndex = 0
}: CommandSuggestionsProps) {
const containerRef = useRef<HTMLDivElement>(null)
const filteredCommands = commands.filter(command =>
command.name.toLowerCase().includes(query.toLowerCase()) ||
command.description?.toLowerCase().includes(query.toLowerCase())
)
// Scroll selected item into view
useEffect(() => {
if (!isOpen || !containerRef.current) return
const selectedItem = containerRef.current.querySelector(`[data-selected="true"]`) as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest', behavior: 'smooth' })
}
}, [selectedIndex, isOpen])
if (!isOpen || filteredCommands.length === 0) {
return null
}
return (
<div
ref={containerRef}
className="fixed z-50 bg-[#1a1a1a] border border-[#333] rounded-lg shadow-lg max-h-64 overflow-y-auto"
style={{
bottom: `${position.bottom}px`, // Position from bottom
left: `${position.left}px`,
width: `${position.width}px`
}}
>
<div className="p-1">
{filteredCommands.map((command, index) => {
const isSelected = index === selectedIndex
const displayName = `/${command.name}`
return (
<div
key={command.name}
data-selected={isSelected}
className={`px-3 py-2 cursor-pointer rounded-md transition-colors flex items-center gap-2 ${
isSelected
? 'bg-blue-600/20 text-white'
: 'hover:bg-[#2a2a2a] text-zinc-300'
}`}
onClick={() => onSelect(command)}
>
<Command className="h-4 w-4 text-zinc-400 flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="font-medium text-sm truncate">{displayName}</div>
{command.description && (
<div className="text-xs text-zinc-500 truncate">{command.description}</div>
)}
</div>
</div>
)
})}
</div>
<div className="px-3 py-2 border-t border-[#333] text-xs text-zinc-500">
<div className="flex items-center gap-4">
<span>↑↓ Navigate</span>
<span>↵ Select</span>
<span>Esc Close</span>
</div>
</div>
</div>
)
}
@@ -0,0 +1,515 @@
import { useState, useEffect, useRef, useCallback } from 'react'
import { FileTree } from './FileTree'
import { FileOperations } from './FileOperations'
import { FilePreview } from './FilePreview'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
import type { FileInfo } from '@/types/files'
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:5001'
// Hook to detect mobile screens
const useIsMobile = () => {
const [isMobile, setIsMobile] = useState(false)
useEffect(() => {
const checkIsMobile = () => {
setIsMobile(window.innerWidth < 768)
}
checkIsMobile()
window.addEventListener('resize', checkIsMobile)
return () => window.removeEventListener('resize', checkIsMobile)
}, [])
return isMobile
}
interface FileBrowserProps {
basePath?: string
onFileSelect?: (file: FileInfo) => void
embedded?: boolean
initialSelectedFile?: string
}
export function FileBrowser({ basePath = '', onFileSelect, embedded = false, initialSelectedFile }: FileBrowserProps) {
const [currentPath, setCurrentPath] = useState(basePath)
const [files, setFiles] = useState<FileInfo | null>(null)
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null)
const [searchQuery, setSearchQuery] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
const [isDragging, setIsDragging] = useState(false)
const [isPreviewModalOpen, setIsPreviewModalOpen] = useState(false)
const dropZoneRef = useRef<HTMLDivElement>(null)
const isMobile = useIsMobile()
useEffect(() => {
if (initialSelectedFile) {
const loadInitialFile = async () => {
try {
const url = `${API_BASE}/api/files/${initialSelectedFile}`
const response = await fetch(url)
if (response.ok) {
const fileData = await response.json()
setSelectedFile(fileData)
if (isMobile) {
setIsPreviewModalOpen(true)
}
} else {
const errorText = await response.text()
console.error('[FileBrowser] Failed to load file:', errorText)
setError(`Failed to load file: ${errorText}`)
}
} catch (err) {
console.error('[FileBrowser] Failed to load initial file:', err)
setError(err instanceof Error ? err.message : 'Failed to load file')
}
}
loadInitialFile()
}
}, [initialSelectedFile, isMobile, basePath])
const loadFiles = async (path: string) => {
setLoading(true)
setError(null)
try {
const response = await fetch(`${API_BASE}/api/files/${path}`)
if (!response.ok) {
throw new Error(`Failed to load files: ${response.statusText}`)
}
const data = await response.json()
setFiles(data)
setCurrentPath(path)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load files')
} finally {
setLoading(false)
}
}
const handleFileSelect = useCallback(async (file: FileInfo) => {
if (file.isDirectory) {
setSelectedFile(null)
return
}
// Fetch the full file content when selecting a file
setLoading(true)
try {
const response = await fetch(`${API_BASE}/api/files/${file.path}`)
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
const fullFileData = await response.json()
setSelectedFile(fullFileData)
onFileSelect?.(fullFileData)
// On mobile, open preview in modal
if (isMobile) {
setIsPreviewModalOpen(true)
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load file')
setSelectedFile(null)
} finally {
setLoading(false)
}
}, [onFileSelect, isMobile])
const handleCloseModal = () => {
setIsPreviewModalOpen(false)
setSelectedFile(null)
}
const handleTouchStart = (e: React.TouchEvent) => {
e.preventDefault()
}
const handleTouchEnd = (e: React.TouchEvent) => {
e.preventDefault()
}
const handleDirectoryClick = (path: string) => {
loadFiles(path)
}
const handleRefresh = () => {
loadFiles(currentPath)
}
const handleUpload = async (files: FileList) => {
const formData = new FormData()
formData.append('file', files[0])
try {
const response = await fetch(`${API_BASE}/api/files/${currentPath}`, {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error(`Upload failed: ${response.statusText}`)
}
await loadFiles(currentPath)
} catch (err) {
setError(err instanceof Error ? err.message : 'Upload failed')
}
}
const handleCreateFile = async (name: string, type: 'file' | 'folder') => {
try {
const response = await fetch(`${API_BASE}/api/files/${currentPath}/${name}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type, content: type === 'file' ? '' : undefined }),
})
if (!response.ok) {
throw new Error(`Create failed: ${response.statusText}`)
}
await loadFiles(currentPath)
} catch (err) {
setError(err instanceof Error ? err.message : 'Create failed')
}
}
const handleDelete = async (path: string) => {
try {
const response = await fetch(`${API_BASE}/api/files/${path}`, {
method: 'DELETE',
})
if (!response.ok) {
throw new Error(`Delete failed: ${response.statusText}`)
}
await loadFiles(currentPath)
setSelectedFile(null)
} catch (err) {
setError(err instanceof Error ? err.message : 'Delete failed')
}
}
const handleRename = async (oldPath: string, newPath: string) => {
try {
const response = await fetch(`${API_BASE}/api/files/${oldPath}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ newPath }),
})
if (!response.ok) {
throw new Error(`Rename failed: ${response.statusText}`)
}
await loadFiles(currentPath)
} catch (err) {
setError(err instanceof Error ? err.message : 'Rename failed')
}
}
const handleDragEnter = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(true)
}
const handleDragLeave = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
if (e.currentTarget === dropZoneRef.current) {
setIsDragging(false)
}
}
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
}
const handleDrop = async (e: React.DragEvent) => {
e.preventDefault()
e.stopPropagation()
setIsDragging(false)
const droppedFiles = e.dataTransfer.files
if (droppedFiles.length > 0) {
await handleUpload(droppedFiles)
}
}
useEffect(() => {
loadFiles(basePath)
}, [basePath])
useEffect(() => {
const handleFileSaved = (event: CustomEvent<{ path: string; content: string }>) => {
if (selectedFile && selectedFile.path === event.detail.path) {
handleFileSelect(selectedFile)
}
}
window.addEventListener('fileSaved', handleFileSaved as EventListener)
return () => window.removeEventListener('fileSaved', handleFileSaved as EventListener)
}, [selectedFile, handleFileSelect])
// Handle escape key to close modal
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape' && isPreviewModalOpen) {
handleCloseModal()
}
}
if (isPreviewModalOpen) {
document.addEventListener('keydown', handleEscape)
return () => document.removeEventListener('keydown', handleEscape)
}
}, [isPreviewModalOpen])
const filteredFiles = files?.children?.filter(file =>
file.name.toLowerCase().includes(searchQuery.toLowerCase())
)
if (embedded) {
return (
<div
className="h-full flex flex-col bg-background"
ref={dropZoneRef}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
{isDragging && (
<div className="absolute inset-0 z-50 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center">
<div className="text-center">
<Upload className="w-12 h-12 mx-auto mb-2 text-primary" />
<p className="text-lg font-semibold text-primary">Drop files here to upload</p>
</div>
</div>
)}
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className="flex-1 flex overflow-hidden">
<div className={`${isMobile ? 'w-full' : 'w-1/2'} border-r border-border px-4 flex flex-col`}>
<div className="flex items-center gap-2 mb-4 mt-4 flex-shrink-0">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={handleRefresh}>
<RefreshCw className="w-4 h-4" />
</Button>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{error && (
<div className="text-sm text-destructive bg-destructive/10 p-2 rounded mb-4 flex-shrink-0">
{error}
</div>
)}
<div className="flex-1 overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center h-64">
<RefreshCw className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : (
<FileTree
files={filteredFiles || []}
onFileSelect={handleFileSelect}
onDirectoryClick={handleDirectoryClick}
selectedFile={selectedFile}
onDelete={handleDelete}
onRename={handleRename}
currentPath={currentPath}
basePath={basePath}
/>
)}
</div>
</div>
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 pl-4 overflow-y-auto">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Select a file to preview
</div>
)}
</div>
)}
</div>
{/* Mobile: File Preview Modal */}
{isMobile && selectedFile && !selectedFile.isDirectory && (
<Dialog open={isPreviewModalOpen} onOpenChange={(open) => !open && handleCloseModal()}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col [&>button:last-child]:hidden"
>
<div className="flex-1 overflow-hidden min-h-0">
<FilePreview file={selectedFile} hideHeader={false} isMobileModal={true} onCloseModal={handleCloseModal} />
</div>
</DialogContent>
</Dialog>
)}
</div>
)
}
return (
<div
className="h-full flex flex-col"
ref={dropZoneRef}
onDragEnter={handleDragEnter}
onDragLeave={handleDragLeave}
onDragOver={handleDragOver}
onDrop={handleDrop}
>
<Card className="flex-1 relative">
{isDragging && (
<div className="absolute inset-0 z-50 bg-blue-50/90 border-2 border-dashed border-blue-500 rounded-lg flex items-center justify-center">
<div className="text-center">
<Upload className="w-12 h-12 mx-auto mb-2 text-blue-500" />
<p className="text-lg font-semibold text-blue-600">Drop files here to upload</p>
</div>
</div>
)}
<CardHeader>
<div className="flex items-center justify-between">
<CardTitle className="flex items-center gap-2">
<FolderOpen className="w-5 h-5" />
File Browser
</CardTitle>
<Button variant="outline" size="sm" onClick={handleRefresh}>
<RefreshCw className="w-4 h-4" />
</Button>
</div>
<div className="flex items-center gap-2">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{error && (
<div className="text-sm text-destructive bg-destructive/10 p-2 rounded">
{error}
</div>
)}
</CardHeader>
<CardContent className="flex-1 flex overflow-hidden">
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className={`${isMobile ? 'w-full' : 'w-1/3'} border-r pr-4 flex flex-col`}>
<div className="flex items-center gap-2 mb-4 flex-shrink-0">
<Input
placeholder="Search files..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="flex-1"
/>
<FileOperations
onUpload={handleUpload}
onCreate={handleCreateFile}
/>
</div>
{loading ? (
<div className="flex items-center justify-center h-64">
<RefreshCw className="w-6 h-6 animate-spin" />
</div>
) : (
<div className="flex-1 overflow-y-auto">
<FileTree
files={filteredFiles || []}
onFileSelect={handleFileSelect}
onDirectoryClick={handleDirectoryClick}
selectedFile={selectedFile}
onDelete={handleDelete}
onRename={handleRename}
currentPath={currentPath}
basePath={basePath}
/>
</div>
)}
</div>
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 pl-4 overflow-y-auto">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
<div className="flex items-center justify-center h-64 text-muted-foreground">
Select a file to preview
</div>
)}
</div>
)}
</CardContent>
</Card>
{/* Mobile: File Preview Modal */}
{isMobile && selectedFile && !selectedFile.isDirectory && (
<Dialog open={isPreviewModalOpen} onOpenChange={(open) => !open && handleCloseModal()}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col"
onTouchStart={handleTouchStart}
onTouchEnd={handleTouchEnd}
>
<DialogHeader className="p-4 border-b border-border flex-shrink-0 relative bg-background z-10">
<div className="flex justify-center mb-2">
<div className="w-8 h-1 bg-muted rounded-full"></div>
</div>
<DialogTitle className="text-foreground text-lg pr-12">
{selectedFile.name}
</DialogTitle>
<button
onClick={handleCloseModal}
className="absolute right-4 top-4 p-2 rounded-md hover:bg-muted text-foreground transition-colors touch-manipulation bg-muted border border-border"
aria-label="Close modal"
>
<X className="w-6 h-6" />
</button>
</DialogHeader>
<div className="flex-1 overflow-hidden min-h-0">
<FilePreview file={selectedFile} hideHeader={true} />
</div>
</DialogContent>
</Dialog>
)}
</div>
)
}
@@ -0,0 +1,74 @@
import { useEffect } from 'react'
import { FileBrowser } from './FileBrowser'
import { Button } from '@/components/ui/button'
import { X } from 'lucide-react'
interface FileBrowserSheetProps {
isOpen: boolean
onClose: () => void
basePath?: string
repoName?: string
initialSelectedFile?: string
}
export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, initialSelectedFile }: FileBrowserSheetProps) {
useEffect(() => {
const handleEscape = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
onClose()
}
}
if (isOpen) {
document.addEventListener('keydown', handleEscape)
document.body.style.overflow = 'hidden'
}
return () => {
document.removeEventListener('keydown', handleEscape)
document.body.style.overflow = 'unset'
}
}, [isOpen, onClose])
if (!isOpen) return null
return (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm">
<div className="absolute inset-0 bg-background">
{/* Header */}
<div className="sticky top-0 z-10 border-b border-border bg-background backdrop-blur-sm px-4 py-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<h1 className="text-lg font-semibold text-foreground">
{repoName ? `${repoName} - Files` : 'Workspace Files'}
</h1>
{basePath && (
<span className="text-sm text-muted-foreground bg-muted px-2 py-1 rounded">
{basePath}
</span>
)}
</div>
<Button
variant="ghost"
size="icon"
onClick={onClose}
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-all duration-200"
>
<X className="w-5 h-5" />
</Button>
</div>
</div>
{/* File Browser Content */}
<div className="h-[calc(100vh-73px)] overflow-hidden">
<FileBrowser
basePath={basePath}
embedded={true}
initialSelectedFile={initialSelectedFile}
/>
</div>
</div>
</div>
)
}
@@ -0,0 +1,106 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Upload, Plus, FolderPlus, FilePlus } from 'lucide-react'
interface FileOperationsProps {
onUpload: (files: FileList) => void
onCreate: (name: string, type: 'file' | 'folder') => void
}
export function FileOperations({ onUpload, onCreate }: FileOperationsProps) {
const [createDialogOpen, setCreateDialogOpen] = useState(false)
const [createType, setCreateType] = useState<'file' | 'folder'>('file')
const [createName, setCreateName] = useState('')
const handleFileSelect = (event: React.ChangeEvent<HTMLInputElement>) => {
const files = event.target.files
if (files && files.length > 0) {
onUpload(files)
}
event.target.value = ''
}
const handleCreate = () => {
if (createName.trim()) {
onCreate(createName.trim(), createType)
setCreateName('')
setCreateDialogOpen(false)
}
}
return (
<div className="flex items-center gap-2">
<div className="relative">
<input
type="file"
id="file-upload"
className="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
onChange={handleFileSelect}
multiple
/>
<Button variant="outline" size="sm" asChild>
<label htmlFor="file-upload" className="cursor-pointer flex items-center gap-2">
<Upload className="w-4 h-4" />
Upload
</label>
</Button>
</div>
<Dialog open={createDialogOpen} onOpenChange={setCreateDialogOpen}>
<DialogTrigger asChild>
<Button variant="outline" size="sm">
<Plus className="w-4 h-4" />
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>
<DialogTitle>Create New</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<Select value={createType} onValueChange={(value: 'file' | 'folder') => setCreateType(value)}>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="file">
<div className="flex items-center gap-2">
<FilePlus className="w-4 h-4" />
File
</div>
</SelectItem>
<SelectItem value="folder">
<div className="flex items-center gap-2">
<FolderPlus className="w-4 h-4" />
Folder
</div>
</SelectItem>
</SelectContent>
</Select>
<Input
placeholder={`${createType === 'file' ? 'File' : 'Folder'} name`}
value={createName}
onChange={(e) => setCreateName(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') handleCreate()
}}
/>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={!createName.trim()}>
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,224 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Download, Copy, X, Edit3, Save, X as XIcon } from 'lucide-react'
import type { FileInfo } from '@/types/files'
const API_BASE = import.meta.env.VITE_API_URL || 'http://localhost:5001'
interface FilePreviewProps {
file: FileInfo
hideHeader?: boolean
isMobileModal?: boolean
onCloseModal?: () => void
}
export function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal }: FilePreviewProps) {
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
const [editContent, setEditContent] = useState('')
const [isSaving, setIsSaving] = useState(false)
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const formatDate = (date: Date) => {
return new Date(date).toLocaleString()
}
const handleDownload = () => {
const link = document.createElement('a')
link.href = `${API_BASE}/api/files/${file.path}?download=true`
link.download = file.name
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
const decodeBase64 = (base64: string): string => {
try {
const binaryString = atob(base64)
const bytes = new Uint8Array(binaryString.length)
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i)
}
return new TextDecoder('utf-8').decode(bytes)
} catch {
throw new Error('Failed to decode base64 content')
}
}
const handleCopyContent = async () => {
if (file.content) {
try {
const content = decodeBase64(file.content)
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
}
const handleEdit = () => {
if (file.content) {
try {
const content = decodeBase64(file.content)
setEditContent(content)
setViewMode('edit')
} catch (err) {
console.error('Failed to load content for editing:', err)
}
}
}
const handleSave = async () => {
setIsSaving(true)
try {
const response = await fetch(`${API_BASE}/api/files/${file.path}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ type: 'file', content: editContent }),
})
if (!response.ok) {
throw new Error(`Save failed: ${response.statusText}`)
}
setViewMode('preview')
const event = new CustomEvent('fileSaved', { detail: { path: file.path, content: editContent } })
window.dispatchEvent(event)
} catch (err) {
console.error('Failed to save file:', err)
} finally {
setIsSaving(false)
}
}
const handleCancel = () => {
setEditContent('')
setViewMode('preview')
}
const isTextFile = file.mimeType?.startsWith('text/') ||
['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '')
const renderContent = () => {
if (!file.content) return null
if (file.mimeType?.startsWith('image/')) {
return (
<div className="flex justify-center p-4">
<img
src={`${API_BASE}/api/files/${file.path}?raw=true`}
alt={file.name}
className="max-w-full h-auto object-contain rounded"
/>
</div>
)
}
if (isTextFile) {
if (viewMode === 'edit') {
return (
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
className="text-sm bg-muted text-foreground p-4 rounded whitespace-pre-wrap font-mono break-words w-full resize-none focus:outline-none focus:ring-0 border-none block"
style={{ minHeight: '95vh' }}
placeholder="Edit file content..."
autoFocus
data-file-editor="true"
/>
)
}
try {
const textContent = decodeBase64(file.content)
return (
<pre className="text-sm bg-muted text-foreground p-4 rounded whitespace-pre-wrap font-mono break-words overflow-x-hidden">
<code>{textContent}</code>
</pre>
)
} catch {
return (
<div className="text-center text-muted-foreground py-8">
Cannot preview this file - content may be corrupted
</div>
)
}
}
return (
<div className="text-center text-muted-foreground py-8">
Binary file - download to view content
</div>
)
}
return (
<div className="h-full flex flex-col bg-background">
{!hideHeader && (
<>
<div className={`flex items-start gap-2 px-3 py-2 border-b border-border flex-shrink-0 overflow-hidden ${isMobileModal ? 'pt-3' : ''}`}>
<div className="flex-1 min-w-0 overflow-hidden">
<h3 className="text-foreground text-sm font-medium break-all leading-tight">
{file.name}
</h3>
<div className="flex items-center gap-2 text-xs text-muted-foreground mt-1 flex-wrap">
<span className="bg-muted px-1.5 py-0.5 rounded text-xs truncate max-w-[80px] flex-shrink-0">{file.mimeType || 'Unknown'}</span>
<span className="truncate flex-shrink-0">{formatFileSize(file.size)}</span>
<span className="hidden sm:inline truncate flex-shrink-0">{formatDate(file.lastModified)}</span>
</div>
</div>
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
{isMobileModal && onCloseModal && (
<Button variant="outline" size="sm" onClick={onCloseModal} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<X className="w-3 h-3" />
</Button>
)}
{isTextFile && viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleEdit} className="h-7 w-7 p-0">
<Edit3 className="w-3 h-3" />
</Button>
)}
{viewMode === 'edit' && (
<>
<Button variant="outline" size="sm" onClick={handleSave} disabled={isSaving} className="border-green-600 bg-green-600/10 text-green-600 hover:bg-green-600/20 h-7 w-7 p-0">
<Save className="w-3 h-3" />
</Button>
<Button variant="outline" size="sm" onClick={handleCancel} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<XIcon className="w-3 h-3" />
</Button>
</>
)}
{isTextFile && viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleCopyContent} className="h-7 w-7 p-0">
<Copy className="w-3 h-3" />
</Button>
)}
{viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleDownload} className="h-7 w-7 p-0">
<Download className="w-3 h-3" />
</Button>
)}
</div>
</div>
</>
)}
<div className={`flex-1 ${viewMode === 'edit' ? 'overflow-hidden' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}>
<div className="p-2 min-w-0">
{renderContent()}
</div>
</div>
</div>
)
}
@@ -0,0 +1,265 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import {
File,
Folder,
FolderOpen,
ChevronRight,
ChevronDown,
MoreHorizontal,
Trash2,
Edit3
} from 'lucide-react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import type { FileInfo } from '@/types/files'
interface FileTreeProps {
files: FileInfo[]
onFileSelect: (file: FileInfo) => void
onDirectoryClick: (path: string) => void
selectedFile: FileInfo | null
onDelete: (path: string) => void
onRename: (oldPath: string, newPath: string) => void
currentPath?: string
basePath?: string
}
interface TreeNodeProps {
file: FileInfo
level: number
onFileSelect: (file: FileInfo) => void
onDirectoryClick: (path: string) => void
selectedFile?: FileInfo | null
onDelete?: (path: string) => void
onRename?: (oldPath: string, newPath: string) => void
}
function TreeNode({ file, level, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename }: TreeNodeProps) {
const [expanded, setExpanded] = useState(false)
const [editing, setEditing] = useState(false)
const [editName, setEditName] = useState(file.name)
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false)
const handleClick = () => {
if (file.isDirectory) {
onDirectoryClick(file.path)
} else {
onFileSelect(file)
}
}
const handleDelete = () => {
setDeleteDialogOpen(true)
}
const handleDeleteConfirm = () => {
onDelete?.(file.path)
setDeleteDialogOpen(false)
}
const handleDeleteCancel = () => {
setDeleteDialogOpen(false)
}
const handleRename = () => {
setEditing(true)
setEditName(file.name)
}
const handleRenameSubmit = () => {
if (editName && editName !== file.name) {
const newPath = file.path.replace(/\/[^/]+$/, `/${editName}`)
onRename?.(file.path, newPath)
}
setEditing(false)
}
const handleRenameCancel = () => {
setEditing(false)
setEditName(file.name)
}
const getFileIcon = () => {
if (file.isDirectory) {
return expanded ? <FolderOpen className="w-4 h-4" /> : <Folder className="w-4 h-4" />
}
const ext = file.name.split('.').pop()?.toLowerCase()
const iconMap: Record<string, string> = {
'js': '🟨',
'ts': '🔷',
'jsx': '🟨',
'tsx': '🔷',
'json': '📋',
'md': '📝',
'html': '🌐',
'css': '🎨',
'png': '🖼️',
'jpg': '🖼️',
'jpeg': '🖼️',
'gif': '🖼️',
'svg': '🖼️',
'pdf': '📄',
'zip': '📦',
}
return (
<span className="w-4 h-4 flex items-center justify-center text-xs">
{iconMap[ext || ''] || <File className="w-4 h-4" />}
</span>
)
}
return (
<div>
<div
className={`flex items-center gap-1 px-2 py-1 hover:bg-muted rounded cursor-pointer group ${
selectedFile?.path === file.path ? 'bg-muted' : ''
}`}
style={{ paddingLeft: `${level * 16 + 8}px` }}
>
{file.isDirectory && (
<Button
variant="ghost"
size="sm"
className="w-4 h-4 p-0"
onClick={(e) => {
e.stopPropagation()
setExpanded(!expanded)
if (!expanded) {
onDirectoryClick(file.path)
}
}}
>
{expanded ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
</Button>
)}
<div className="flex items-center gap-1 flex-1" onClick={handleClick}>
{getFileIcon()}
{editing ? (
<Input
value={editName}
onChange={(e) => setEditName(e.target.value)}
onBlur={handleRenameSubmit}
onKeyDown={(e) => {
if (e.key === 'Enter') handleRenameSubmit()
if (e.key === 'Escape') handleRenameCancel()
}}
className="h-6 text-sm"
autoFocus
/>
) : (
<span className="text-sm truncate">{file.name}</span>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="w-6 h-6 p-0 opacity-0 group-hover:opacity-100"
>
<MoreHorizontal className="w-3 h-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem onClick={handleRename}>
<Edit3 className="w-4 h-4 mr-2" />
Rename
</DropdownMenuItem>
<DropdownMenuItem onClick={handleDelete} className="text-red-600">
<Trash2 className="w-4 h-4 mr-2" />
Delete
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{file.isDirectory && expanded && file.children && (
<div>
{file.children.map((child) => (
<TreeNode
key={child.path}
file={child}
level={level + 1}
onFileSelect={onFileSelect}
onDirectoryClick={onDirectoryClick}
selectedFile={selectedFile}
onDelete={onDelete}
onRename={onRename}
/>
))}
</div>
)}
<DeleteDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onConfirm={handleDeleteConfirm}
onCancel={handleDeleteCancel}
title={`Delete ${file.isDirectory ? 'Folder' : 'File'}`}
description={`Are you sure you want to delete this ${file.isDirectory ? 'folder' : 'file'}?`}
itemName={file.name}
/>
</div>
)
}
export function FileTree({ files, onFileSelect, onDirectoryClick, selectedFile, onDelete, onRename, currentPath = '', basePath = '' }: FileTreeProps) {
const handleGoUp = () => {
// If currentPath has content and is different from basePath, go up
if (currentPath !== basePath) {
const pathParts = currentPath.split('/').filter(p => p)
pathParts.pop()
const parentPath = pathParts.join('/')
onDirectoryClick(parentPath)
}
}
// Show ".." if we're not at the base path (empty string means root)
const showGoUp = currentPath && currentPath !== basePath
return (
<div className="overflow-y-auto">
{showGoUp && (
<div
className="flex items-center gap-1 px-2 py-1 hover:bg-muted rounded cursor-pointer"
onClick={handleGoUp}
>
<span className="w-4 h-4 flex items-center justify-center text-sm">↩️</span>
<span className="text-sm text-muted-foreground">..</span>
</div>
)}
{files.length === 0 ? (
<div className="text-center text-muted-foreground py-8">
No files in this directory
</div>
) : (
files.map((file) => (
<TreeNode
key={file.path}
file={file}
level={0}
onFileSelect={onFileSelect}
onDirectoryClick={onDirectoryClick}
selectedFile={selectedFile}
onDelete={onDelete}
onRename={onRename}
/>
))
)}
</div>
)
}
+41
View File
@@ -0,0 +1,41 @@
import { Settings } from "lucide-react";
import { Button } from "@/components/ui/button";
import { BackButton } from "@/components/ui/back-button";
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
import type { ReactNode } from "react";
interface HeaderProps {
title: string;
backTo?: string;
action?: ReactNode;
}
export function Header({ title, backTo, action }: HeaderProps) {
const { open: openSettings } = useSettingsDialog();
return (
<header className="sticky top-0 z-10 bg-gradient-to-b from-background via-background to-background border-b border-border backdrop-blur-sm">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<div className="flex items-center gap-4">
{backTo && <BackButton to={backTo} />}
<h1 className="text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate">
{title}
</h1>
</div>
<div className="flex items-center gap-2">
{action && <div>{action}</div>}
<Button
variant="ghost"
size="icon"
onClick={openSettings}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200"
>
<Settings className="w-10 h-10" />
</Button>
</div>
</div>
</div>
</header>
);
}
@@ -0,0 +1,83 @@
import { useEffect, useRef } from 'react'
interface FileSuggestionsProps {
isOpen: boolean
query: string
files: string[]
onSelect: (file: string) => void
onClose: () => void
position: { bottom: number, left: number, width: number }
selectedIndex?: number
}
export function FileSuggestions({
isOpen,
files,
onSelect,
onClose,
position,
selectedIndex = 0
}: FileSuggestionsProps) {
const listRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!isOpen) return
const handleClickOutside = (e: MouseEvent) => {
if (listRef.current && !listRef.current.contains(e.target as Node)) {
onClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, onClose])
useEffect(() => {
if (!isOpen || !listRef.current) return
const selectedItem = listRef.current.children[selectedIndex] as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest' })
}
}, [selectedIndex, isOpen])
if (!isOpen || files.length === 0) return null
const getFilename = (path: string) => path.split('/').pop() || path
const getDirectory = (path: string) => {
const parts = path.split('/')
return parts.slice(0, -1).join('/') || '.'
}
return (
<div
ref={listRef}
className="fixed bg-zinc-900 border border-zinc-700 rounded-lg shadow-xl z-50 max-h-64 overflow-y-auto"
style={{
bottom: `${position.bottom}px`,
left: `${position.left}px`,
width: `${position.width}px`
}}
>
{files.map((file, idx) => (
<button
key={file}
onClick={() => onSelect(file)}
className={`w-full px-3 py-2 text-left transition-colors ${
idx === selectedIndex
? 'bg-blue-600 text-white'
: 'hover:bg-zinc-800 text-zinc-100'
}`}
>
<div className="font-mono text-sm font-medium">
{getFilename(file)}
</div>
<div className="text-xs opacity-70 mt-0.5">
{getDirectory(file)}
</div>
</button>
))}
</div>
)
}
@@ -0,0 +1,146 @@
import type { components } from '@/api/opencode-types'
import { Copy } from 'lucide-react'
import { TextPart } from './TextPart'
import { PatchPart } from './PatchPart'
import { ToolCallPart } from './ToolCallPart'
type Part = components['schemas']['Part']
interface MessagePartProps {
part: Part
role?: string
allParts?: Part[]
partIndex?: number
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function getCopyableContent(part: Part, allParts?: Part[]): string {
switch (part.type) {
case 'text':
return part.text || ''
case 'patch':
return `Patch: ${part.hash}\nFiles: ${part.files.join(', ')}`
case 'tool':
if (part.state.status === 'completed' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
} else if (part.state.status === 'running' && part.state.input) {
return JSON.stringify(part.state.input, null, 2)
}
return `Tool: ${part.tool} (${part.state.status})`
case 'reasoning':
return part.text || ''
case 'snapshot':
return part.snapshot || ''
case 'agent':
return `Agent: ${part.name}`
case 'step-start':
return 'Starting step...'
case 'step-finish':
if (allParts) {
return allParts
.filter(p => p.type === 'text')
.map(p => p.text || '')
.join('\n\n')
.trim()
}
return ''
case 'file':
return part.filename || part.url || 'File'
default:
return ''
}
}
function CopyButton({ content, title, className = "" }: { content: string; title: string; className?: string }) {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
if (!content.trim()) {
return null
}
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
>
<Copy className="w-4 h-4" />
</button>
)
}
export function MessagePart({ part, role, allParts, partIndex, onFileClick }: MessagePartProps) {
const copyableContent = getCopyableContent(part, allParts)
switch (part.type) {
case 'text':
if (role === 'user' && allParts && partIndex !== undefined) {
const nextPart = allParts[partIndex + 1]
if (nextPart && nextPart.type === 'file') {
return null
}
}
return <TextPart part={part} />
case 'patch':
return <PatchPart part={part} />
case 'tool':
return <ToolCallPart part={part} onFileClick={onFileClick} />
case 'reasoning':
return (
<details className="border border-zinc-800 rounded-lg my-2">
<summary className="px-4 py-2 bg-zinc-900 hover:bg-zinc-800 cursor-pointer text-sm font-medium">
Reasoning
</summary>
<div className="p-4 bg-zinc-950 text-sm text-zinc-300 whitespace-pre-wrap">
{part.text}
</div>
</details>
)
case 'snapshot':
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500 font-mono">Snapshot: {part.snapshot}</div>
</div>
)
case 'agent':
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-sm font-medium text-blue-400">Agent: {part.name}</div>
</div>
)
case 'step-start':
return (
<div className="text-xs text-muted-foreground my-1">
→ Starting step...
</div>
)
case 'step-finish':
return (
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
<span>✓ Step complete • ${part.cost.toFixed(4)} • {part.tokens.input + part.tokens.output} tokens</span>
<CopyButton content={copyableContent} title="Copy step complete" />
</div>
)
case 'file':
return (
<span className="inline-flex items-center gap-1 px-2 py-1 rounded bg-zinc-800 border border-zinc-700 text-sm text-zinc-300">
<span className="text-blue-400">@</span>
<span className="font-medium">{part.filename || 'File'}</span>
</span>
)
default:
return (
<div className="border border-zinc-800 rounded-lg p-4 my-2 bg-zinc-950">
<div className="text-xs text-zinc-500">Unknown part type</div>
</div>
)
}
}
@@ -0,0 +1,109 @@
import { useMessages } from '@/hooks/useOpenCode'
import { MessagePart } from './MessagePart'
import type { MessageWithParts } from '@/api/types'
interface MessageThreadProps {
opcodeUrl: string
sessionID: string
directory?: string
onFileClick?: (filePath: string, lineNumber?: number) => void
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const isMessageThinking = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return msg.parts.length === 0 && isMessageStreaming(msg)
}
export function MessageThread({ opcodeUrl, sessionID, directory, onFileClick }: MessageThreadProps) {
const { data: messages, isLoading, error } = useMessages(opcodeUrl, sessionID, directory)
if (isLoading) {
return (
<div className="flex items-center justify-center h-full text-zinc-500">
Loading messages...
</div>
)
}
if (error) {
return (
<div className="flex items-center justify-center h-full text-red-400">
Error loading messages: {error instanceof Error ? error.message : 'Unknown error'}
</div>
)
}
if (!messages || messages.length === 0) {
return (
<div className="flex items-center justify-center h-full text-zinc-600">
No messages yet. Start a conversation below.
</div>
)
}
return (
<div className="flex flex-col space-y-2 p-4">
{messages.map((msg) => {
const streaming = isMessageStreaming(msg)
const thinking = isMessageThinking(msg)
return (
<div
key={msg.info.id}
className="flex flex-col"
>
<div
className={`w-full rounded-lg p-2 ${
msg.info.role === 'user'
? 'bg-blue-600/20 border border-blue-600/30'
: 'bg-card/50 border border-border'
} ${streaming ? 'animate-pulse-subtle' : ''}`}
>
<div className="flex items-center gap-2 mb-1">
<span className="text-xs font-medium text-zinc-400">
{msg.info.role === 'user' ? 'You' : (msg.info.role === 'assistant' && 'modelID' in msg.info ? msg.info.modelID : 'Assistant')}
</span>
{msg.info.time && (
<span className="text-xs text-muted-foreground">
{new Date(msg.info.time.created).toLocaleTimeString()}
</span>
)}
{streaming && (
<span className="text-xs text-blue-400 flex items-center gap-1">
<span className="animate-pulse">●</span> <span className="shine-loading">Generating...</span>
</span>
)}
</div>
{thinking ? (
<div className="flex items-center gap-2 text-zinc-500">
<span className="animate-pulse">▋</span>
<span className="text-sm shine-loading">Thinking...</span>
</div>
) : (
<div className="space-y-2">
{msg.parts.map((part, index) => (
<div key={`${msg.info.id}-${part.id}-${index}`}>
<MessagePart
part={part}
role={msg.info.role}
allParts={msg.parts}
partIndex={index}
onFileClick={onFileClick}
/>
</div>
))}
</div>
)}
</div>
</div>
)
})}
</div>
)
}
@@ -0,0 +1,38 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
type PatchPart = components['schemas']['PatchPart']
interface PatchPartProps {
part: PatchPart
}
export function PatchPart({ part }: PatchPartProps) {
const [expanded, setExpanded] = useState(true)
return (
<div className="border border-zinc-800 rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-zinc-900 hover:bg-zinc-800 text-left flex items-center justify-between text-sm"
>
<span className="font-medium">
File Changes ({part.files.length} file{part.files.length !== 1 ? 's' : ''})
</span>
<span className="text-zinc-400 text-xs font-mono">{part.hash.slice(0, 8)}</span>
</button>
{expanded && (
<div className="bg-zinc-950 p-4">
<div className="space-y-2">
{part.files.map((file, index) => (
<div key={index} className="text-sm">
<div className="font-mono text-zinc-400 mb-1">{file}</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
@@ -0,0 +1,605 @@
import { useState, useRef, useEffect, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell } from '@/hooks/useOpenCode'
import { useSettings } from '@/hooks/useSettings'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
import { useMobile } from '@/hooks/useMobile'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { FileSuggestions } from './FileSuggestions'
import { detectMentionTrigger, parsePromptToParts, getFilename } from '@/lib/promptParser'
import { getModel, formatModelName } from '@/api/providers'
import type { components } from '@/api/opencode-types'
import type { MessageWithParts, FileInfo } from '@/api/types'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
type CommandType = components['schemas']['Command']
interface PromptInputProps {
opcodeUrl: string
directory?: string
sessionID: string
disabled?: boolean
onShowSessionsDialog?: () => void
onShowModelsDialog?: () => void
onShowHelpDialog?: () => void
}
export function PromptInput({
opcodeUrl,
directory,
sessionID,
disabled,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
}: PromptInputProps) {
const [prompt, setPrompt] = useState('')
const [modelName, setModelName] = useState<string>('')
const [isBashMode, setIsBashMode] = useState(false)
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
const [suggestionPosition, setSuggestionPosition] = useState({ bottom: 0, left: 0, width: 0 })
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileInfo>())
const [showFileSuggestions, setShowFileSuggestions] = useState(false)
const [fileQuery, setFileQuery] = useState('')
const [fileSuggestionPosition, setFileSuggestionPosition] = useState({ bottom: 0, left: 0, width: 0 })
const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null)
const [selectedFileIndex, setSelectedFileIndex] = useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const isMobile = useMobile()
const textareaRef = useRef<HTMLTextAreaElement>(null)
const sendPrompt = useSendPrompt(opcodeUrl, directory)
const sendShell = useSendShell(opcodeUrl, directory)
const abortSession = useAbortSession(opcodeUrl, directory)
const { data: messages } = useMessages(opcodeUrl, sessionID, directory)
const { preferences, updateSettings } = useSettings()
const { filterCommands } = useCommands(opcodeUrl)
const { executeCommand } = useCommandHandler({
opcodeUrl,
sessionID,
directory,
onShowSessionsDialog,
onShowModelsDialog,
onShowHelpDialog
})
const { files: searchResults } = useFileSearch(
opcodeUrl,
fileQuery,
showFileSuggestions,
directory
)
const handleSubmit = () => {
if (!prompt.trim() || disabled) return
if (isBashMode) {
const command = prompt.startsWith('!') ? prompt.slice(1) : prompt
sendShell.mutate({
sessionID,
command,
agent: currentMode
})
setPrompt('')
setIsBashMode(false)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
return
}
const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/)
if (commandMatch) {
const [, commandName] = commandMatch
const command = filterCommands(commandName)[0]
if (command) {
executeCommand(command)
setPrompt('')
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
return
}
}
const parts = parsePromptToParts(prompt, attachedFiles)
sendPrompt.mutate({
sessionID,
parts,
model: currentModel,
agent: currentMode
})
setPrompt('')
setAttachedFiles(new Map())
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
}
const handleStop = () => {
abortSession.mutate(sessionID)
}
const handleCommandSelect = async (command: CommandType) => {
if (!textareaRef.current) return
setShowSuggestions(false)
setSuggestionQuery('')
const cursorPosition = textareaRef.current.selectionStart
const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const beforeCommand = prompt.slice(0, commandMatch.index)
const afterCommand = prompt.slice(cursorPosition)
const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand
setPrompt(newPrompt)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeCommand.length + command.name.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
}
const handleFileSelect = (filePath: string) => {
if (!mentionRange || !textareaRef.current) return
const filename = getFilename(filePath)
const beforeMention = prompt.slice(0, mentionRange.start)
const afterMention = prompt.slice(mentionRange.end)
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = filePath.startsWith('/')
? filePath
: directory
? `${directory}/${filePath}`
: filePath
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
})
return next
})
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
const handleModeToggle = () => {
const newMode = currentMode === 'plan' ? 'build' : 'plan'
updateSettings({ mode: newMode })
}
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (isBashMode && e.key === 'Escape') {
e.preventDefault()
setIsBashMode(false)
setPrompt('')
return
}
if (showFileSuggestions && searchResults.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedFileIndex(prev =>
prev < searchResults.length - 1 ? prev + 1 : prev
)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedFileIndex(prev => prev > 0 ? prev - 1 : 0)
return
}
if (e.key === 'Enter') {
e.preventDefault()
if (searchResults[selectedFileIndex]) {
handleFileSelect(searchResults[selectedFileIndex])
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
return
}
}
if (showSuggestions) {
const filteredCommands = filterCommands(suggestionQuery)
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedCommandIndex(prev => (prev + 1) % filteredCommands.length)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedCommandIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length)
return
}
if (e.key === 'Enter') {
e.preventDefault()
const selectedCommand = filteredCommands[selectedCommandIndex]
if (selectedCommand) {
handleCommandSelect(selectedCommand)
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowSuggestions(false)
setSuggestionQuery('')
setSelectedCommandIndex(0)
return
}
}
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
e.preventDefault()
handleSubmit()
} else if (e.key === 'Escape') {
setShowSuggestions(false)
setSuggestionQuery('')
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
setPrompt('')
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
}
}
const handleInput = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const value = e.target.value
if (value === '!' && prompt === '') {
setIsBashMode(true)
setPrompt(value)
return
}
if (isBashMode && value === '') {
setIsBashMode(false)
}
setPrompt(value)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
textareaRef.current.style.height = `${textareaRef.current.scrollHeight}px`
}
if (isBashMode) {
return
}
const cursorPosition = e.target.selectionStart
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
if (mentionTrigger) {
setFileQuery(mentionTrigger.query)
setMentionRange({ start: mentionTrigger.start, end: mentionTrigger.end })
setShowFileSuggestions(true)
setSelectedFileIndex(0)
if (textareaRef.current) {
const rect = textareaRef.current.getBoundingClientRect()
setFileSuggestionPosition({
bottom: window.innerHeight - rect.top + window.scrollY + 4,
left: rect.left + window.scrollX,
width: rect.width
})
}
} else {
const commandMatch = value.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
if (commandMatch) {
const query = commandMatch[2]
setSuggestionQuery(query)
setShowSuggestions(true)
setSelectedCommandIndex(0)
if (textareaRef.current) {
const rect = textareaRef.current.getBoundingClientRect()
setSuggestionPosition({
bottom: window.innerHeight - rect.top + window.scrollY + 4,
left: rect.left + window.scrollX,
width: rect.width
})
}
} else {
setShowSuggestions(false)
setSuggestionQuery('')
}
if (showFileSuggestions) {
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
}
}
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
if (msg.info.role !== 'assistant') return false
return !('completed' in msg.info.time && msg.info.time.completed)
}
const hasActiveStream = messages?.some(msg => isMessageStreaming(msg)) || false
const currentMode = preferences?.mode || 'build'
const currentModel = preferences?.defaultModel || ''
const modeColor = currentMode === 'plan' ? 'text-yellow-600 dark:text-yellow-500' : 'text-green-600 dark:text-green-500'
const modeBg = currentMode === 'plan' ? 'bg-yellow-500/10 border-yellow-500/30' : 'bg-green-500/10 border-green-500/30'
useEffect(() => {
const loadModelName = async () => {
if (currentModel) {
try {
const [providerId, modelId] = currentModel.split('/')
if (providerId && modelId) {
const model = await getModel(providerId, modelId)
if (model) {
setModelName(formatModelName(model))
} else {
setModelName(currentModel)
}
} else {
setModelName(currentModel)
}
} catch {
setModelName(currentModel)
}
} else {
setModelName('No model selected')
}
}
loadModelName()
}, [currentModel])
useEffect(() => {
if (textareaRef.current && !disabled && !hasActiveStream) {
textareaRef.current.focus()
}
}, [disabled, hasActiveStream])
return (
<div className="border-t border-border bg-background p-2 sm:p-3">
{isMobile ? (
<>
<div className="mb-2">
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Message..."
}
disabled={disabled || hasActiveStream}
className="w-full bg-background border rounded-lg px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed"
rows={1}
/>
</div>
<div className="flex gap-2 items-center justify-between mx-2">
<div className="flex gap-2 items-center">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName}
</button>
)}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
title="Help"
>
?
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-3 py-1 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? 'Stop' : 'Send'}
</button>
</div>
</>
) : (
<>
<div className="flex gap-2 items-end mb-2 justify-between">
<div className="flex gap-2 items-end">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()} MODE
</button>
{isBashMode && (
<div className="px-2 py-1 rounded-md text-xs font-medium border bg-purple-500/10 border-purple-500/30 text-purple-600 dark:text-purple-400">
BASH MODE
</div>
)}
{modelName && (
<button
onClick={onShowModelsDialog}
className="px-2 py-1 rounded-md text-xs font-medium border bg-muted border-border text-muted-foreground hover:bg-muted-foreground/10 transition-colors cursor-pointer"
>
{modelName}
</button>
)}
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button
className="w-6 h-6 rounded-full border-2 border-foreground text-foreground hover:bg-foreground hover:text-background transition-colors flex items-center justify-center text-sm font-medium"
title="Help"
>
?
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-64">
<DropdownMenuItem disabled className="text-xs text-muted-foreground font-medium">
Keyboard Shortcuts
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
<div className="flex gap-2 items-end">
<textarea
ref={textareaRef}
value={prompt}
onChange={handleInput}
onKeyDown={handleKeyDown}
placeholder={
isBashMode
? "Enter bash command... (Esc to exit)"
: "Send a message... (Cmd/Ctrl+Enter)"
}
disabled={disabled || hasActiveStream}
className={`flex-1 bg-background border rounded-lg px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none focus:ring-2 resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm ${
isBashMode
? 'border-purple-500/50 focus:ring-purple-500/50 bg-purple-500/5'
: 'border-border focus:ring-primary/50'
}`}
rows={1}
/>
<button
data-submit-prompt
onClick={hasActiveStream ? handleStop : handleSubmit}
disabled={(!prompt.trim() && !hasActiveStream) || disabled}
className={`px-3 py-2 rounded-lg text-sm font-medium transition-colors ${
hasActiveStream
? 'bg-destructive hover:bg-destructive/90 text-destructive-foreground'
: 'bg-primary hover:bg-primary/90 disabled:bg-muted disabled:text-muted-foreground disabled:cursor-not-allowed text-primary-foreground'
}`}
title={hasActiveStream ? 'Stop' : 'Send'}
>
{hasActiveStream ? '■' : '↑'}
</button>
</div>
</>
)}
<CommandSuggestions
isOpen={showSuggestions}
query={suggestionQuery}
commands={filterCommands(suggestionQuery)}
onSelect={handleCommandSelect}
onClose={() => {
setShowSuggestions(false)
setSuggestionQuery('')
}}
position={suggestionPosition}
selectedIndex={selectedCommandIndex}
/>
<FileSuggestions
isOpen={showFileSuggestions}
query={fileQuery}
files={searchResults}
onSelect={handleFileSelect}
onClose={() => {
setShowFileSuggestions(false)
setFileQuery('')
setMentionRange(null)
}}
position={fileSuggestionPosition}
selectedIndex={selectedFileIndex}
/>
</div>
)
}
@@ -0,0 +1,121 @@
import React from 'react'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import rehypeHighlight from 'rehype-highlight'
import rehypeRaw from 'rehype-raw'
import { Copy, Check } from 'lucide-react'
import type { components } from '@/api/opencode-types'
import 'highlight.js/styles/github-dark.css'
type TextPart = components['schemas']['TextPart']
interface TextPartProps {
part: TextPart
}
interface CodeBlockProps {
children?: React.ReactNode
className?: string
[key: string]: unknown
}
function CodeBlock({ children, className, ...props }: CodeBlockProps) {
const [copied, setCopied] = React.useState(false)
const extractTextContent = (node: React.ReactNode): string => {
if (typeof node === 'string') return node
if (typeof node === 'number') return node.toString()
if (Array.isArray(node)) return node.map(extractTextContent).join('')
if (React.isValidElement(node)) {
const element = node as React.ReactElement<any, any>
if (element.props.children) {
return extractTextContent(element.props.children as React.ReactNode)
}
}
return ''
}
const codeContent = extractTextContent(children)
const handleCopyCode = async () => {
try {
await navigator.clipboard.writeText(codeContent)
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (error) {
console.error('Failed to copy code:', error)
}
}
return (
<div className="relative">
<pre className={`bg-accent p-4 rounded-lg overflow-x-auto border border-border my-4 ${className || ''}`} {...props}>
{children}
</pre>
<button
onClick={handleCopyCode}
className="absolute top-2 right-2 p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground"
title="Copy code"
>
{copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
</button>
</div>
)
}
export function TextPart({ part }: TextPartProps) {
if (!part.text || part.text.trim() === '') {
return (
<div className="text-muted-foreground italic text-sm">
[Empty message content]
</div>
)
}
return (
<div className="prose prose-invert prose-enhanced max-w-none text-foreground">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight, rehypeRaw]}
components={{
code({ className, children, ...props }) {
const isInline = !className || !className.includes('language-')
if (isInline) {
return (
<code className={className || "bg-accent px-1.5 py-0.5 rounded text-sm text-foreground"} {...props}>
{children}
</code>
)
}
return (
<code className={className} {...props}>
{children}
</code>
)
},
pre({ children }) {
return (
<CodeBlock>
{children}
</CodeBlock>
)
},
p({ children }) {
return <p className="text-foreground">{children}</p>
},
strong({ children }) {
return <strong className="font-semibold text-foreground">{children}</strong>
},
ul({ children }) {
return <ul className="list-disc text-foreground">{children}</ul>
},
ol({ children }) {
return <ol className="list-decimal text-foreground">{children}</ol>
}
}}
>
{part.text}
</ReactMarkdown>
</div>
)
}
@@ -0,0 +1,181 @@
import { useState } from 'react'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
import { detectFileReferences } from '@/lib/fileReferences'
type ToolPart = components['schemas']['ToolPart']
interface ToolCallPartProps {
part: ToolPart
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
const jsonString = JSON.stringify(json, null, 2)
const references = detectFileReferences(jsonString)
if (references.length === 0) {
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{jsonString}</pre>
}
const parts: React.ReactNode[] = []
let lastIndex = 0
references.forEach((ref, index) => {
if (ref.startIndex > lastIndex) {
parts.push(jsonString.slice(lastIndex, ref.startIndex))
}
parts.push(
<span
key={`ref-${index}`}
onClick={(e) => {
e.stopPropagation()
onFileClick?.(ref.filePath)
}}
className="text-blue-300 hover:text-blue-200 cursor-pointer underline decoration-dotted"
title={`Click to open ${ref.filePath}`}
>
{ref.fullMatch}
</span>
)
lastIndex = ref.endIndex
})
if (lastIndex < jsonString.length) {
parts.push(jsonString.slice(lastIndex))
}
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{parts}</pre>
}
export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const defaultExpanded = preferences?.expandToolCalls ?? false
const [expanded, setExpanded] = useState(defaultExpanded)
const getStatusColor = () => {
switch (part.state.status) {
case 'completed':
return 'text-green-400'
case 'error':
return 'text-red-400'
case 'running':
return 'text-yellow-400'
default:
return 'text-zinc-400'
}
}
const getStatusIcon = () => {
switch (part.state.status) {
case 'completed':
return '✓'
case 'error':
return '✗'
case 'running':
return '⟳'
default:
return '○'
}
}
const getPreviewText = () => {
if (part.state.status === 'pending') return null
const input = part.state.input as Record<string, unknown>
if (!input) return null
switch (part.tool) {
case 'read':
case 'write':
case 'edit':
return (input.filePath as string) || null
case 'bash':
return (input.command as string) || null
case 'glob':
return (input.pattern as string) || null
case 'grep':
return (input.pattern as string) || null
case 'list':
return (input.path as string) || '.'
case 'task':
return (input.description as string) || null
default:
return null
}
}
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-card hover:bg-card-hover text-left flex items-center gap-2 text-sm"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.tool}</span>
{previewText && isFileTool ? (
<span
onClick={(e) => {
e.stopPropagation()
if (onFileClick) {
onFileClick(previewText)
}
}}
className="text-blue-300 text-xs truncate hover:text-blue-200 cursor-pointer underline decoration-dotted"
title={`Click to open ${previewText}`}
>
{previewText}
</span>
) : previewText ? (
<span className="text-zinc-400 text-xs truncate">{previewText}</span>
) : null}
<span className="text-muted-foreground text-xs ml-auto">({part.state.status})</span>
</button>
{expanded && (
<div className="bg-card p-4 space-y-2">
{part.state.status === 'running' && (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
{part.state.status === 'completed' && (
<>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
<div className="text-sm">
<div className="text-zinc-400 mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">
{part.state.output}
</pre>
</div>
{part.state.time && (
<div className="text-xs text-zinc-500">
Duration: {((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
</div>
)}
</>
)}
{part.state.status === 'error' && (
<div className="text-sm">
<div className="text-red-400 mb-1">Error:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto text-red-300">
{part.state.error}
</pre>
</div>
)}
</div>
)}
</div>
)
}
@@ -0,0 +1,296 @@
import { useState, useEffect, useCallback } from "react";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Badge } from "@/components/ui/badge";
import { Loader2, Search, Check } from "lucide-react";
import {
getProvidersWithModels,
formatModelName,
formatProviderName,
} from "@/api/providers";
import { useSettings } from "@/hooks/useSettings";
import { useOpenCodeClient } from "@/hooks/useOpenCode";
import { useParams } from "react-router-dom";
import type { ProviderWithModels, Model } from "@/api/providers";
interface ModelSelectDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
opcodeUrl?: string | null;
}
export function ModelSelectDialog({
open,
onOpenChange,
opcodeUrl,
}: ModelSelectDialogProps) {
const [providers, setProviders] = useState<ProviderWithModels[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState("");
const [selectedProvider, setSelectedProvider] = useState<string>("");
const { preferences, updateSettings } = useSettings();
const client = useOpenCodeClient(opcodeUrl);
const { sessionID } = useParams<{ sessionID: string }>();
const currentModel = preferences?.defaultModel || "";
const loadProviders = useCallback(async () => {
try {
setLoading(true);
const data = await getProvidersWithModels();
setProviders(data);
if (currentModel) {
const [providerId] = currentModel.split("/");
setSelectedProvider(providerId);
}
} catch {
// Ignore errors when loading providers
} finally {
setLoading(false);
}
}, [opcodeUrl, currentModel]);
useEffect(() => {
if (open) {
loadProviders();
}
}, [open, loadProviders]);
const filteredProviders = providers.filter((provider) => {
const matchesSearch =
provider.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
provider.models.some(
(model) =>
model.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
model.id.toLowerCase().includes(searchQuery.toLowerCase()),
);
const matchesProvider =
!selectedProvider || provider.id === selectedProvider;
return matchesSearch && matchesProvider;
});
const handleModelSelect = async (providerId: string, modelId: string) => {
const newModel = `${providerId}/${modelId}`;
// Update settings for future sessions
updateSettings({ defaultModel: newModel });
// If we're in a session, try to update the current session's model
if (sessionID && client) {
try {
await client.sendCommand(sessionID, {
command: "model",
arguments: newModel,
model: newModel,
});
} catch {
// Ignore errors when updating session model
}
}
onOpenChange(false);
};
const handleProviderChange = (providerId: string) => {
setSelectedProvider(providerId);
};
const getStatusBadge = (model: Model) => {
if (model.experimental)
return <Badge variant="secondary">Experimental</Badge>;
if (model.status === "alpha")
return <Badge variant="destructive">Alpha</Badge>;
if (model.status === "beta") return <Badge variant="secondary">Beta</Badge>;
return null;
};
const getModelCapabilities = (model: Model) => {
const capabilities = [];
if (model.reasoning) capabilities.push("Reasoning");
if (model.tool_call) capabilities.push("Tools");
if (model.attachment) capabilities.push("Files");
return capabilities;
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-4xl max-h-[80vh] bg-[#1a1a1a] border-[#333] text-white">
<DialogHeader>
<DialogTitle className="text-xl font-semibold">
Select Model
</DialogTitle>
</DialogHeader>
<div className="space-y-4">
{/* Search */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-zinc-400" />
<Input
placeholder="Search models or providers..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10 bg-[#0a0a0a] border-[#333] text-white placeholder-zinc-500"
/>
</div>
{/* Provider Filter */}
<div className="flex gap-2 flex-wrap">
<Button
variant={!selectedProvider ? "default" : "outline"}
size="sm"
onClick={() => handleProviderChange("")}
className={
!selectedProvider
? "bg-blue-600 text-white"
: "bg-[#2a2a2a] border-[#333] text-zinc-300 hover:bg-[#333]"
}
>
All Providers
</Button>
{providers.map((provider) => (
<Button
key={provider.id}
variant={
selectedProvider === provider.id ? "default" : "outline"
}
size="sm"
onClick={() => handleProviderChange(provider.id)}
className={
selectedProvider === provider.id
? "bg-blue-600 text-white"
: "bg-[#2a2a2a] border-[#333] text-zinc-300 hover:bg-[#333]"
}
>
{formatProviderName(provider)}
</Button>
))}
</div>
{/* Models List */}
<div className="min-h-[300px] max-h-[400px] overflow-y-auto">
{loading ? (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-zinc-500" />
</div>
) : filteredProviders.length === 0 ? (
<div className="text-center py-12 text-zinc-500">
No providers or models found
</div>
) : (
<div className="space-y-4">
{filteredProviders.map((provider) => (
<div key={provider.id} className="space-y-2">
<h3 className="font-medium text-zinc-200 flex items-center gap-2">
{formatProviderName(provider)}
{provider.api && (
<Badge variant="outline" className="text-xs">
API
</Badge>
)}
</h3>
<div className="grid gap-2 pl-4">
{provider.models.map((model) => {
const modelKey = `${provider.id}/${model.id}`;
const isSelected = currentModel === modelKey;
const capabilities = getModelCapabilities(model);
return (
<div
key={model.id}
className={`p-3 rounded-lg border cursor-pointer transition-colors ${
isSelected
? "bg-blue-600/20 border-blue-500"
: "bg-[#0a0a0a] border-[#333] hover:bg-[#1a1a1a] hover:border-[#444]"
}`}
onClick={() =>
handleModelSelect(provider.id, model.id)
}
>
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-1">
<h4 className="font-medium text-white">
{formatModelName(model)}
</h4>
{isSelected && (
<Check className="h-4 w-4 text-blue-400" />
)}
{getStatusBadge(model)}
</div>
<p className="text-sm text-zinc-400 mb-2">
{model.id}
</p>
{/* Capabilities */}
{capabilities.length > 0 && (
<div className="flex gap-1 flex-wrap mb-2">
{capabilities.map((cap) => (
<Badge
key={cap}
variant="secondary"
className="text-xs"
>
{cap}
</Badge>
))}
</div>
)}
{/* Model Info */}
<div className="text-xs text-zinc-500 space-y-1">
<div>
Context:{" "}
{model.limit?.context?.toLocaleString() ||
"N/A"}{" "}
tokens
</div>
<div>
Output:{" "}
{model.limit?.output?.toLocaleString() ||
"N/A"}{" "}
tokens
</div>
{model.cost && (
<div>
Cost: ${model.cost.input.toFixed(6)}
/input, ${model.cost.output.toFixed(6)}
/output
</div>
)}
</div>
</div>
</div>
</div>
);
})}
</div>
</div>
))}
</div>
)}
</div>
{/* Current Selection */}
{currentModel && (
<div className="pt-4 border-t border-[#333]">
<p className="text-sm text-zinc-400">
Current model:{" "}
<span className="text-white font-medium">{currentModel}</span>
</p>
</div>
)}
</div>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,130 @@
import { useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { createRepo } from "@/api/repos";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Loader2 } from "lucide-react";
interface AddBranchWorkspaceDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
repoUrl: string;
}
export function AddBranchWorkspaceDialog({
open,
onOpenChange,
repoUrl,
}: AddBranchWorkspaceDialogProps) {
const [branch, setBranch] = useState("");
const [useWorktree, setUseWorktree] = useState(true);
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: () =>
createRepo(repoUrl, branch || undefined, undefined, useWorktree),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setBranch("");
setUseWorktree(true);
onOpenChange(false);
},
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (branch.trim()) {
mutation.mutate();
}
};
const handleCheckboxChange = (e: React.ChangeEvent<HTMLInputElement>) => {
e.stopPropagation();
setUseWorktree(e.target.checked);
};
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-[90%] sm:max-w-[500px] bg-[#141414] border-[#2a2a2a]">
<DialogHeader>
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
Add Branch Workspace
</DialogTitle>
<p className="text-sm text-zinc-400 mt-1">
Create a new workspace for{" "}
{repoUrl.split("/").pop()?.replace(".git", "")}
</p>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 mt-4">
<div className="space-y-2">
<label className="text-sm text-zinc-400">Branch *</label>
<Input
placeholder="feature-branch, main, etc."
value={branch}
onChange={(e) => setBranch(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
</div>
<div className="space-y-2">
<div className="flex items-center gap-2">
<input
type="checkbox"
id="worktree-checkbox"
checked={useWorktree}
onChange={handleCheckboxChange}
disabled={mutation.isPending}
className="w-4 h-4 rounded border-gray-600 bg-gray-800 text-blue-600 focus:ring-blue-600 focus:ring-2 cursor-pointer accent-blue-600"
onClick={(e) => e.stopPropagation()}
/>
<label
htmlFor="worktree-checkbox"
className="text-sm text-zinc-400 cursor-pointer select-none"
onClick={(e) => {
e.preventDefault();
if (!mutation.isPending) {
setUseWorktree(!useWorktree);
}
}}
>
Create as worktree
</label>
</div>
<p className="text-xs text-zinc-500">
{useWorktree
? "Creates a git worktree - shares git history with base repo (recommended, faster)"
: "Creates a full clone - independent copy of the repository (slower, more disk space)"}
</p>
</div>
<Button
type="submit"
disabled={!branch || 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" />
{useWorktree ? "Creating worktree..." : "Cloning..."}
</>
) : useWorktree ? (
"Create Worktree"
) : (
"Clone Branch"
)}
</Button>
{mutation.isError && (
<p className="text-sm text-red-400">{mutation.error.message}</p>
)}
</form>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,96 @@
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { createRepo } from '@/api/repos'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Loader2 } from 'lucide-react'
interface AddRepoDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
export function AddRepoDialog({ open, onOpenChange }: AddRepoDialogProps) {
const [repoUrl, setRepoUrl] = useState('')
const [branch, setBranch] = useState('')
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: () => createRepo(repoUrl, branch || undefined, undefined, false),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['repos'] })
setRepoUrl('')
setBranch('')
onOpenChange(false)
},
})
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (repoUrl) {
mutation.mutate()
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[500px] bg-[#141414] border-[#2a2a2a]">
<DialogHeader>
<DialogTitle className="text-xl bg-gradient-to-r from-white to-gray-300 bg-clip-text text-transparent">
Add Repository
</DialogTitle>
</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"
/>
</div>
<div className="space-y-2">
<label className="text-sm text-zinc-400">Branch</label>
<Input
placeholder="Optional - uses default if empty"
value={branch}
onChange={(e) => setBranch(e.target.value)}
disabled={mutation.isPending}
className="bg-[#1a1a1a] border-[#2a2a2a] text-white placeholder:text-zinc-500"
/>
<p className="text-xs text-zinc-500">
{branch
? `Clones repository directly to '${branch}' branch`
: "Clones repository to default branch"
}
</p>
</div>
<Button
type="submit"
disabled={!repoUrl || 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...
</>
) : (
'Add Repository'
)}
</Button>
{mutation.isError && (
<p className="text-sm text-red-400">
{mutation.error.message}
</p>
)}
</form>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,102 @@
import { useState } from "react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { GitBranch, Check, Plus } from "lucide-react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { listBranches, switchBranch } from "@/api/repos";
import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog";
interface BranchSwitcherProps {
repoId: number;
currentBranch: string;
isWorktree?: boolean;
repoUrl: string;
}
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: BranchSwitcherProps) {
const [addBranchOpen, setAddBranchOpen] = useState(false);
const queryClient = useQueryClient();
const { data: branches } = useQuery({
queryKey: ["branches", repoId],
queryFn: () => listBranches(repoId),
enabled: !!repoId,
});
const switchBranchMutation = useMutation({
mutationFn: (branch: string) => switchBranch(repoId, branch),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repo", repoId] });
queryClient.invalidateQueries({ queryKey: ["branches", repoId] });
},
});
if (isWorktree) {
return null;
}
return (
<>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="h-6 px-1 sm:px-2 text-[10px] sm:text-xs text-blue-400 hover:text-blue-300 hover:bg-accent gap-1 border border-blue-500/20"
>
<GitBranch className="w-3 h-3" />
<span className="hidden sm:inline">{currentBranch}</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="bg-card border-border min-w-[200px]">
{branches?.remote && branches.remote.length > 0 ? (
branches.remote.map((branch: string) => (
<DropdownMenuItem
key={branch}
onClick={() => switchBranchMutation.mutate(branch)}
disabled={switchBranchMutation.isPending}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<GitBranch className="w-3 h-3" />
<span className="flex-1">{branch}</span>
{branch === currentBranch && <Check className="w-3 h-3 text-green-500" />}
</div>
</DropdownMenuItem>
))
) : (
<DropdownMenuItem disabled className="text-muted-foreground">
Loading branches...
</DropdownMenuItem>
)}
{!isWorktree && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setAddBranchOpen(true)}
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
>
<div className="flex items-center gap-2 w-full">
<Plus className="w-3 h-3" />
<span className="flex-1">Add Branch</span>
</div>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repoUrl}
/>
</>
);
}
+162
View File
@@ -0,0 +1,162 @@
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Loader2, Trash2, GitBranch, ExternalLink } from "lucide-react";
import { useNavigate } from "react-router-dom";
import { useState } from "react";
import { AddBranchWorkspaceDialog } from "./AddBranchWorkspaceDialog";
interface RepoCardProps {
repo: {
id: number;
repoUrl: string;
branch?: string;
currentBranch?: string;
cloneStatus: string;
isWorktree?: boolean;
};
onDelete: (id: number) => void;
isDeleting: boolean;
isSelected?: boolean;
onSelect?: (id: number, selected: boolean) => void;
}
export function RepoCard({
repo,
onDelete,
isDeleting,
isSelected = false,
onSelect,
}: RepoCardProps) {
const navigate = useNavigate();
const [addBranchOpen, setAddBranchOpen] = useState(false);
const repoName = repo.repoUrl.split("/").slice(-1)[0].replace(".git", "");
const branchToDisplay = repo.currentBranch || repo.branch;
const displayName = branchToDisplay ? `${repoName} (${branchToDisplay})` : repoName;
const isReady = repo.cloneStatus === "ready";
return (
<div
className={`group relative bg-gradient-to-br from-card to-card-hover border rounded-xl overflow-hidden transition-all duration-200 hover:shadow-lg w-full ${
isSelected
? "border-blue-500 shadow-lg shadow-blue-900/30"
: "border-border hover:border-border hover:shadow-blue-900/20"
}`}
>
<div className="p-4 sm:p-6">
<div className="mb-4">
<div className="flex items-center gap-2 mb-2">
{onSelect && (
<input
type="checkbox"
id="select-repo"
checked={isSelected}
onChange={(e) => {
e.stopPropagation();
onSelect(repo.id, e.target.checked);
}}
onClick={(e) => {
e.stopPropagation();
}}
className="w-5 h-5 rounded border-gray-600 accent-blue-500 cursor-pointer"
/>
)}
<h3
onClick={(e) => {
e.stopPropagation();
if (isReady) {
navigate(`/repos/${repo.id}`);
}
}}
className={`font-semibold text-lg text-foreground truncate group-hover:text-blue-400 transition-colors ${
isReady ? "cursor-pointer" : "cursor-not-allowed opacity-60"
}`}
>
{displayName}
</h3>
{repo.isWorktree && (
<Badge
className="text-xs px-2.5 py-0.5 bg-purple-600/20 text-purple-400 border-purple-600/40"
>
worktree
</Badge>
)}
{repo.cloneStatus && (
<Badge
className={`text-xs px-2.5 py-0.5 ${
isReady
? "bg-green-600/20 text-green-400 border-green-600/40"
: repo.cloneStatus === "cloning"
? "bg-blue-600/20 text-blue-400 border-blue-600/40"
: "bg-red-600/20 text-red-400 border-red-600/40"
}`}
>
{repo.cloneStatus}
</Badge>
)}
</div>
<p className="text-sm text-muted-foreground truncate">{repo.repoUrl}</p>
</div>
<div className="flex flex-col gap-2">
{repo.cloneStatus === "cloning" && (
<div className="text-sm text-muted-foreground flex items-center gap-2">
<Loader2 className="w-3 h-3 animate-spin text-blue-400" />
<span>Cloning repository...</span>
</div>
)}
<div className="flex gap-2">
<Button
size="sm"
onClick={(e) => {
e.stopPropagation();
navigate(`/repos/${repo.id}`);
}}
disabled={!isReady}
className="cursor-pointer flex-1 h-10 sm:h-9 px-3"
>
<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>
<Button
size="sm"
variant="destructive"
onClick={(e) => {
e.stopPropagation();
onDelete(repo.id);
}}
disabled={isDeleting}
className="h-10 sm:h-9 w-10 p-0"
>
{isDeleting ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Trash2 className="w-4 h-4" />
)}
</Button>
</div>
</div>
</div>
<AddBranchWorkspaceDialog
open={addBranchOpen}
onOpenChange={setAddBranchOpen}
repoUrl={repo.repoUrl}
/>
</div>
);
}
+229
View File
@@ -0,0 +1,229 @@
import { useState } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { listRepos, deleteRepo } from "@/api/repos";
import { DeleteDialog } from "@/components/ui/delete-dialog";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Loader2, GitBranch, Search, Trash2 } from "lucide-react";
import { RepoCard } from "./RepoCard";
export function RepoList() {
const queryClient = useQueryClient();
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [repoToDelete, setRepoToDelete] = useState<number | null>(null);
const [selectedRepos, setSelectedRepos] = useState<Set<number>>(new Set());
const [searchQuery, setSearchQuery] = useState("");
const {
data: repos,
isLoading,
error,
} = useQuery({
queryKey: ["repos"],
queryFn: listRepos,
});
const deleteMutation = useMutation({
mutationFn: deleteRepo,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setDeleteDialogOpen(false);
setRepoToDelete(null);
},
});
const batchDeleteMutation = useMutation({
mutationFn: async (repoIds: number[]) => {
await Promise.all(repoIds.map((id) => deleteRepo(id)));
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["repos"] });
setDeleteDialogOpen(false);
setSelectedRepos(new Set());
},
});
if (isLoading && !repos) {
return (
<div className="flex items-center justify-center p-8">
<Loader2 className="w-6 h-6 animate-spin" />
</div>
);
}
if (error) {
return (
<div className="text-center p-8 text-destructive">
Failed to load repositories:{" "}
{error instanceof Error ? error.message : "Unknown error"}
</div>
);
}
if (!repos || repos.length === 0) {
return (
<div className="text-center p-12">
<GitBranch className="w-12 h-12 mx-auto mb-4 text-zinc-600" />
<p className="text-zinc-500">
No repositories yet. Add one to get started.
</p>
</div>
);
}
const dedupedRepos = repos.reduce((acc, repo) => {
if (repo.isWorktree) {
acc.push(repo);
} else {
const key = repo.repoUrl;
const existing = acc.find(r => r.repoUrl === key && !r.isWorktree);
if (!existing) {
acc.push(repo);
}
}
return acc;
}, [] as typeof repos);
const filteredRepos = dedupedRepos.filter((repo) => {
const repoName = repo.repoUrl.split("/").slice(-1)[0].replace(".git", "");
return (
repoName.toLowerCase().includes(searchQuery.toLowerCase()) ||
repo.repoUrl.toLowerCase().includes(searchQuery.toLowerCase())
);
});
const handleSelectRepo = (id: number, selected: boolean) => {
const newSelected = new Set(selectedRepos);
if (selected) {
newSelected.add(id);
} else {
newSelected.delete(id);
}
setSelectedRepos(newSelected);
};
const handleSelectAll = () => {
const allFilteredSelected = filteredRepos.every((repo) =>
selectedRepos.has(repo.id),
);
if (allFilteredSelected) {
setSelectedRepos(new Set());
} else {
const filteredIds = filteredRepos.map((repo) => repo.id);
setSelectedRepos(new Set([...selectedRepos, ...filteredIds]));
}
};
const handleBatchDelete = () => {
if (selectedRepos.size > 0) {
setDeleteDialogOpen(true);
}
};
return (
<>
<div className="p-2 md:p-4">
<div className="flex items-center gap-3 mb-6">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-zinc-400" />
<Input
placeholder="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
{filteredRepos.length > 0 && (
<Button
onClick={handleSelectAll}
variant={selectedRepos.size > 0 ? "default" : "outline"}
className="whitespace-nowrap"
>
{filteredRepos.every((repo) => selectedRepos.has(repo.id))
? "Deselect All"
: "Select All"}
</Button>
)}
<Button
onClick={handleBatchDelete}
variant="destructive"
disabled={selectedRepos.size === 0}
className="hidden md:flex whitespace-nowrap"
>
<Trash2 className="w-4 h-4 mr-2" />
Delete ({selectedRepos.size})
</Button>
<Button
onClick={handleBatchDelete}
variant="destructive"
disabled={selectedRepos.size === 0}
size="icon"
className="md:hidden"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
<div className="h-[calc(100vh-200px)] overflow-y-auto">
{filteredRepos.length === 0 ? (
<div className="text-center p-12">
<Search className="w-12 h-12 mx-auto mb-4 text-zinc-600" />
<p className="text-zinc-500">
No repositories found matching "{searchQuery}"
</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 gap-4 w-full">
{filteredRepos.map((repo) => (
<RepoCard
key={repo.id}
repo={repo}
onDelete={(id) => {
setRepoToDelete(id);
setDeleteDialogOpen(true);
}}
isDeleting={
deleteMutation.isPending && repoToDelete === repo.id
}
isSelected={selectedRepos.has(repo.id)}
onSelect={handleSelectRepo}
/>
))}
</div>
)}
</div>
</div>
<DeleteDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onConfirm={() => {
if (repoToDelete) {
deleteMutation.mutate(repoToDelete);
} else if (selectedRepos.size > 0) {
batchDeleteMutation.mutate(Array.from(selectedRepos));
}
}}
onCancel={() => {
setDeleteDialogOpen(false);
setRepoToDelete(null);
}}
title={
selectedRepos.size > 0
? "Delete Multiple Repositories"
: "Delete Repository"
}
description={
selectedRepos.size > 0
? `Are you sure you want to delete ${selectedRepos.size} repositor${selectedRepos.size === 1 ? "y" : "ies"}? This will remove all local files. This action cannot be undone.`
: "Are you sure you want to delete this repository? This will remove all local files. This action cannot be undone."
}
isDeleting={deleteMutation.isPending || batchDeleteMutation.isPending}
/>
</>
);
}
@@ -0,0 +1,153 @@
import { useState, useEffect } from 'react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { AlertCircle, Loader2 } from 'lucide-react'
import { settingsApi } from '@/api/settings'
import * as reposApi from '@/api/repos'
import type { OpenCodeConfig } from '@/api/types/settings'
interface SwitchConfigDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
repoId: number
currentConfigName?: string
onConfigSwitched: (configName: string) => void
}
export function SwitchConfigDialog({
open,
onOpenChange,
repoId,
currentConfigName,
onConfigSwitched,
}: SwitchConfigDialogProps) {
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
const [selectedConfig, setSelectedConfig] = useState<string>('')
const [loading, setLoading] = useState(true)
const [switching, setSwitching] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!open) return
const fetchConfigs = async () => {
try {
setLoading(true)
setError(null)
const response = await settingsApi.getOpenCodeConfigs()
setConfigs(response.configs || [])
setSelectedConfig(currentConfigName || '')
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load configs')
} finally {
setLoading(false)
}
}
fetchConfigs()
}, [open, currentConfigName])
const handleSwitch = async () => {
if (!selectedConfig) {
setError('Please select a config')
return
}
if (selectedConfig === currentConfigName) {
onOpenChange(false)
return
}
try {
setSwitching(true)
setError(null)
await reposApi.switchRepoConfig(repoId, selectedConfig)
onConfigSwitched(selectedConfig)
onOpenChange(false)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to switch config')
} finally {
setSwitching(false)
}
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Switch Config</DialogTitle>
<DialogDescription>
Select a different OpenCode configuration for this repository
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{currentConfigName && (
<div className="text-sm text-zinc-400">
Current config: <span className="text-white font-semibold">{currentConfigName}</span>
</div>
)}
{loading ? (
<div className="flex items-center justify-center py-6">
<Loader2 className="w-4 h-4 animate-spin text-blue-400" />
<span className="ml-2 text-sm text-zinc-400">Loading configs...</span>
</div>
) : configs.length === 0 ? (
<div className="text-sm text-zinc-400">No configs available</div>
) : (
<Select value={selectedConfig} onValueChange={setSelectedConfig}>
<SelectTrigger className="bg-[#1a1a1a] border-[#2a2a2a] text-white">
<SelectValue placeholder="Select a config" />
</SelectTrigger>
<SelectContent className="bg-[#1a1a1a] border-[#2a2a2a]">
{configs.map((config) => (
<SelectItem key={config.id} value={config.name}>
<div className="flex items-center gap-2">
{config.name}
{config.isDefault && (
<span className="text-xs text-blue-400 ml-2">(default)</span>
)}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
)}
{error && (
<div className="flex items-start gap-2 bg-red-900/20 border border-red-800/50 rounded p-3">
<AlertCircle className="w-4 h-4 text-red-400 mt-0.5 flex-shrink-0" />
<p className="text-sm text-red-400">{error}</p>
</div>
)}
<div className="flex gap-2 justify-end">
<Button
variant="outline"
onClick={() => onOpenChange(false)}
className="border-[#2a2a2a] hover:bg-[#1a1a1a]"
>
Cancel
</Button>
<Button
onClick={handleSwitch}
disabled={!selectedConfig || switching || selectedConfig === currentConfigName}
className="bg-blue-600 hover:bg-blue-700 disabled:opacity-50"
>
{switching ? (
<>
<Loader2 className="w-4 h-4 mr-2 animate-spin" />
Switching...
</>
) : (
'Switch Config'
)}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,96 @@
import { useContextUsage } from '@/hooks/useContextUsage'
import { getModel, formatModelName } from '@/api/providers'
import { useSettings } from '@/hooks/useSettings'
import { useState, useEffect } from 'react'
interface ContextUsageIndicatorProps {
opcodeUrl: string | null
sessionID: string | undefined
directory?: string
}
export function ContextUsageIndicator({ opcodeUrl, sessionID, directory }: ContextUsageIndicatorProps) {
const { totalTokens, contextLimit, usagePercentage, currentModel, isLoading } = useContextUsage(opcodeUrl, sessionID, directory)
const { preferences } = useSettings()
const [modelName, setModelName] = useState<string>('')
const displayModel = preferences?.defaultModel || currentModel || ''
useEffect(() => {
const loadModelName = async () => {
if (displayModel) {
try {
const [providerId, modelId] = displayModel.split('/')
if (providerId && modelId) {
const model = await getModel(providerId, modelId)
if (model) {
setModelName(formatModelName(model))
} else {
setModelName(displayModel)
}
} else {
setModelName(displayModel)
}
} catch {
setModelName(displayModel)
}
} else {
setModelName('')
}
}
loadModelName()
}, [displayModel, opcodeUrl])
if (isLoading) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">Loading...</span>
</div>
)
}
if (!modelName) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">No model</span>
</div>
)
}
const getUsageColor = (percentage: number) => {
if (percentage < 50) return 'bg-green-700 dark:bg-green-400'
if (percentage < 80) return 'bg-yellow-700 dark:bg-yellow-400'
return 'bg-red-700 dark:bg-red-400'
}
const getUsageTextColor = (percentage: number) => {
if (percentage < 50) return 'text-green-700 dark:text-green-400'
if (percentage < 80) return 'text-yellow-700 dark:text-yellow-400'
return 'text-red-700 dark:text-red-400'
}
if (!contextLimit) {
return (
<div className="flex items-center gap-2">
<span className="text-xs text-muted-foreground">{modelName}</span>
</div>
)
}
return (
<div className="flex items-center gap-2">
<div className="flex items-center gap-2 min-w-0">
<div className="w-16 h-2 bg-muted rounded-full overflow-hidden border border-border">
<div
className={`h-full transition-all duration-300 ${getUsageColor(usagePercentage || 0)}`}
style={{ width: `${Math.min(usagePercentage || 0, 100)}%` }}
/>
</div>
<span className={`text-xs font-medium whitespace-nowrap ${getUsageTextColor(usagePercentage || 0)}`}>
{totalTokens.toLocaleString()} / {contextLimit.toLocaleString()}
</span>
</div>
</div>
)
}
@@ -0,0 +1,30 @@
import { DeleteDialog } from '@/components/ui/delete-dialog'
interface DeleteSessionDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
isDeleting?: boolean
sessionCount?: number
}
export function DeleteSessionDialog({ open, onOpenChange, onConfirm, onCancel, isDeleting = false, sessionCount = 1 }: DeleteSessionDialogProps) {
const isMultiple = sessionCount > 1
const title = isMultiple ? "Delete Sessions" : "Delete Session"
const description = isMultiple
? `Are you sure you want to delete ${sessionCount} sessions? This action cannot be undone.`
: "Are you sure you want to delete this session? This action cannot be undone."
return (
<DeleteDialog
open={open}
onOpenChange={onOpenChange}
onConfirm={onConfirm}
onCancel={onCancel}
title={title}
description={description}
isDeleting={isDeleting}
/>
)
}
@@ -0,0 +1,116 @@
import { BackButton } from "@/components/ui/back-button";
import { ContextUsageIndicator } from "@/components/session/ContextUsageIndicator";
import { BranchSwitcher } from "@/components/repo/BranchSwitcher";
import { Button } from "@/components/ui/button";
import { Loader2, Settings, FolderOpen } from "lucide-react";
interface Repo {
id: number;
repoUrl: string;
fullPath: string;
localPath: string;
currentBranch?: string;
isWorktree?: boolean;
cloneStatus: 'ready' | 'cloning' | 'error';
}
interface SessionDetailHeaderProps {
repo: Repo;
sessionId: string;
sessionTitle: string;
repoId: number;
isConnected: boolean;
opcodeUrl: string | null;
repoDirectory: string | undefined;
onFileBrowserOpen: () => void;
onSettingsOpen: () => void;
onShowModelsDialog?: () => void;
}
export function SessionDetailHeader({
repo,
sessionId,
sessionTitle,
repoId,
isConnected,
opcodeUrl,
repoDirectory,
onFileBrowserOpen,
onSettingsOpen,
}: SessionDetailHeaderProps) {
if (repo.cloneStatus !== 'ready') {
return (
<div className="sticky top-0 z-10 border-b border-border bg-gradient-to-b from-background via-background to-background backdrop-blur-sm px-2 sm:px-4 py-1.5 sm:py-2">
<div className="flex items-center justify-center">
<Loader2 className="w-4 h-4 animate-spin text-muted-foreground mr-2" />
<span className="text-sm text-muted-foreground">
{repo.cloneStatus === 'cloning' ? 'Cloning repository...' : 'Repository not ready'}
</span>
</div>
</div>
);
}
const repoName = repo.repoUrl.split("/").pop()?.replace(".git", "") || "Repository";
const currentBranch = repo.currentBranch || "main";
return (
<div className="sticky top-0 z-10 border-b border-border bg-gradient-to-b from-background via-background to-background backdrop-blur-sm px-2 sm:px-4 py-1.5 sm:py-2">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5 sm:gap-3 min-w-0 flex-1">
<BackButton to={`/repos/${repoId}`} className="text-xs sm:text-sm" />
<div className="min-w-0 flex-1">
<h1 className="text-xs sm:text-base font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent truncate">
{sessionTitle}
</h1>
<div className="flex items-center gap-2">
<p className="text-[10px] sm:text-xs text-muted-foreground truncate">
{repoName}
</p>
<BranchSwitcher
repoId={repoId}
currentBranch={currentBranch}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
/>
</div>
</div>
</div>
<div className="flex items-center gap-2 sm:gap-4 flex-shrink-0">
<div className="hidden sm:block">
<ContextUsageIndicator
opcodeUrl={opcodeUrl}
sessionID={sessionId}
directory={repoDirectory}
/>
</div>
<div className="flex items-center gap-1 sm:gap-2">
<div
className={`w-1.5 h-1.5 sm:w-2 sm:h-2 rounded-full ${isConnected ? "bg-green-500" : "bg-red-500"}`}
/>
<span className="text-xs text-muted-foreground hidden sm:inline">
{isConnected ? "Connected" : "Disconnected"}
</span>
</div>
<Button
variant="ghost"
size="icon"
onClick={onFileBrowserOpen}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
>
<FolderOpen className="w-4 h-4" />
</Button>
<Button
variant="ghost"
size="icon"
onClick={onSettingsOpen}
className="text-muted-foreground hover:text-foreground hover:bg-accent transition-all duration-200 h-8 w-8"
>
<Settings className="w-4 h-4" />
</Button>
</div>
</div>
</div>
);
}
@@ -0,0 +1,237 @@
import { useState, useMemo } from "react";
import { useSessions, useDeleteSession } from "@/hooks/useOpenCode";
import { Card } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { Trash2, GitBranch, Clock, Search } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
interface SessionListProps {
opcodeUrl: string;
directory?: string;
activeSessionID?: string;
onSelectSession: (sessionID: string) => void;
}
export const SessionList = ({
opcodeUrl,
directory,
activeSessionID,
onSelectSession,
}: SessionListProps) => {
const { data: sessions, isLoading } = useSessions(opcodeUrl, directory);
const deleteSession = useDeleteSession(opcodeUrl, directory);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [sessionToDelete, setSessionToDelete] = useState<
string | string[] | null
>(null);
const [searchQuery, setSearchQuery] = useState("");
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(
new Set(),
);
const filteredSessions = useMemo(() => {
if (!sessions) return [];
if (!searchQuery.trim()) return sessions;
const query = searchQuery.toLowerCase();
return sessions.filter((session) =>
(session.title || "Untitled Session").toLowerCase().includes(query),
);
}, [sessions, searchQuery]);
if (isLoading) {
return <div className="p-4 text-sm text-gray-400">Loading sessions...</div>;
}
if (!sessions || sessions.length === 0) {
return (
<div className="p-4 text-sm text-gray-400">
No sessions yet. Create one to get started.
</div>
);
}
const handleDelete = (
sessionId: string,
e: React.MouseEvent<HTMLButtonElement>,
) => {
e.stopPropagation();
setSessionToDelete(sessionId);
setDeleteDialogOpen(true);
};
const confirmDelete = async () => {
if (sessionToDelete) {
await deleteSession.mutateAsync(sessionToDelete);
setDeleteDialogOpen(false);
setSessionToDelete(null);
setSelectedSessions(new Set());
}
};
const cancelDelete = () => {
setDeleteDialogOpen(false);
setSessionToDelete(null);
};
const toggleSessionSelection = (sessionId: string, selected: boolean) => {
const newSelected = new Set(selectedSessions);
if (selected) {
newSelected.add(sessionId);
} else {
newSelected.delete(sessionId);
}
setSelectedSessions(newSelected);
};
const toggleSelectAll = () => {
if (!filteredSessions || filteredSessions.length === 0) return;
const allFilteredSelected = filteredSessions.every((session) =>
selectedSessions.has(session.id),
);
if (allFilteredSelected) {
setSelectedSessions(new Set());
} else {
const filteredIds = filteredSessions.map((s) => s.id);
setSelectedSessions(new Set([...selectedSessions, ...filteredIds]));
}
};
const handleBulkDelete = () => {
if (selectedSessions.size > 0) {
setSessionToDelete(Array.from(selectedSessions));
setDeleteDialogOpen(true);
}
};
return (
<div className="flex flex-col h-full">
<div className="p-4 flex-shrink-0">
<div className="flex items-center gap-3 mb-3">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<Input
type="text"
placeholder="Search"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-10"
/>
</div>
{filteredSessions && filteredSessions.length > 0 && (
<Button
onClick={toggleSelectAll}
variant={selectedSessions.size > 0 ? "default" : "outline"}
className="whitespace-nowrap"
>
{filteredSessions.every((session) =>
selectedSessions.has(session.id),
)
? "Deselect All"
: "Select All"}
</Button>
)}
<Button
onClick={handleBulkDelete}
variant="destructive"
disabled={selectedSessions.size === 0}
className="hidden md:flex whitespace-nowrap"
>
<Trash2 className="w-4 h-4 mr-2" />
Delete ({selectedSessions.size})
</Button>
<Button
onClick={handleBulkDelete}
variant="destructive"
disabled={selectedSessions.size === 0}
size="icon"
className="md:hidden"
>
<Trash2 className="w-4 h-4" />
</Button>
</div>
</div>
<div className="flex-1 overflow-y-auto px-4 pb-4">
<div className="flex flex-col gap-2">
{filteredSessions.length === 0 ? (
<div className="text-sm text-gray-400 text-center py-4">
No sessions found
</div>
) : (
filteredSessions.map((session) => (
<Card
key={session.id}
className={`p-3 cursor-pointer transition-all ${
selectedSessions.has(session.id)
? "border-blue-500 shadow-lg shadow-blue-900/30 bg-[#2a2a2a]"
: activeSessionID === session.id
? "bg-[#333333] border-[#5a5a5a]"
: "bg-[#2a2a2a] border-[#4a4a4a] hover:bg-[#333333] hover:border-[#5a5a5a]"
} hover:shadow-lg`}
onClick={() => onSelectSession(session.id)}
>
<div className="flex items-start justify-between gap-2">
<div className="flex items-start gap-2 flex-1 min-w-0">
<input
type="checkbox"
checked={selectedSessions.has(session.id)}
onChange={(e) => {
e.stopPropagation();
toggleSessionSelection(session.id, e.target.checked);
}}
onClick={(e) => {
e.stopPropagation();
}}
className="w-5 h-5 rounded border-gray-600 accent-blue-500 cursor-pointer flex-shrink-0 mt-0.5"
/>
<div className="flex-1 min-w-0">
<h3 className="text-sm font-medium text-white truncate">
{session.title || "Untitled Session"}
</h3>
<div className="flex items-center gap-3 mt-1 text-xs text-gray-400">
{session.parentID && (
<span className="flex items-center gap-1">
<GitBranch className="w-3 h-3" />
Forked
</span>
)}
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{formatDistanceToNow(new Date(session.time.updated), {
addSuffix: true,
})}
</span>
</div>
</div>
</div>
<button
className="h-6 w-6 p-0 text-gray-400 hover:text-red-400 bg-transparent border-none cursor-pointer"
onClick={(e) => handleDelete(session.id, e)}
>
<Trash2 className="w-4 h-4" />
</button>
</div>
</Card>
))
)}
</div>
</div>
<DeleteSessionDialog
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
onConfirm={confirmDelete}
onCancel={cancelDelete}
isDeleting={deleteSession.isPending}
sessionCount={
Array.isArray(sessionToDelete) ? sessionToDelete.length : 1
}
/>
</div>
);
};
@@ -0,0 +1,222 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Card, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'
import { Loader2, ExternalLink } from 'lucide-react'
import { PROVIDER_TEMPLATES, type ProviderTemplate } from '@/lib/providerTemplates'
import { settingsApi } from '@/api/settings'
import { useMutation, useQueryClient } from '@tanstack/react-query'
interface AddProviderDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
export function AddProviderDialog({ open, onOpenChange }: AddProviderDialogProps) {
const [step, setStep] = useState<'select' | 'customize'>('select')
const [selectedTemplate, setSelectedTemplate] = useState<ProviderTemplate | null>(null)
const [providerId, setProviderId] = useState('')
const [providerName, setProviderName] = useState('')
const [baseURL, setBaseURL] = useState('')
const queryClient = useQueryClient()
const addProviderMutation = useMutation({
mutationFn: async () => {
const config = await settingsApi.getDefaultOpenCodeConfig()
const currentProvider = config?.content?.provider || {}
const newProvider = {
npm: selectedTemplate?.npm || '@ai-sdk/openai-compatible',
name: providerName || selectedTemplate?.name,
...(baseURL && {
options: {
baseURL,
},
}),
...(selectedTemplate?.models && {
models: selectedTemplate.models,
}),
}
const updatedConfig = {
...config?.content,
provider: {
...currentProvider,
[providerId]: newProvider,
},
}
await settingsApi.updateOpenCodeConfig(
config?.name || 'default',
{ content: updatedConfig }
)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['opencode-config'] })
queryClient.invalidateQueries({ queryKey: ['opencode-providers'] })
handleClose()
},
})
const handleSelectTemplate = (template: ProviderTemplate) => {
setSelectedTemplate(template)
setProviderId(template.id)
setProviderName(template.name)
setBaseURL(template.options?.baseURL || '')
setStep('customize')
}
const handleAdd = () => {
if (providerId && selectedTemplate) {
addProviderMutation.mutate()
}
}
const handleClose = () => {
setStep('select')
setSelectedTemplate(null)
setProviderId('')
setProviderName('')
setBaseURL('')
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-3xl max-h-[80vh] bg-card border-border overflow-y-auto">
{step === 'select' && (
<>
<DialogHeader>
<DialogTitle>Add Provider</DialogTitle>
<DialogDescription>
Choose a provider template to get started quickly
</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 py-4">
{PROVIDER_TEMPLATES.map((template) => (
<Card
key={template.id}
className="cursor-pointer hover:border-blue-500 transition-colors bg-background border-border"
onClick={() => handleSelectTemplate(template)}
>
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex-1">
<CardTitle className="text-base flex items-center gap-2">
{template.name}
{!template.requiresApiKey && (
<Badge variant="secondary" className="text-xs">
Local
</Badge>
)}
</CardTitle>
<CardDescription className="text-sm mt-1">
{template.description}
</CardDescription>
<p className="text-xs text-muted-foreground mt-2">
{template.npm}
</p>
</div>
</div>
</CardHeader>
</Card>
))}
</div>
</>
)}
{step === 'customize' && selectedTemplate && (
<>
<DialogHeader>
<DialogTitle>Configure {selectedTemplate.name}</DialogTitle>
<DialogDescription>
Customize the provider settings before adding
{selectedTemplate.docsUrl && (
<a
href={selectedTemplate.docsUrl}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-1 text-blue-500 hover:underline ml-2"
>
View docs <ExternalLink className="h-3 w-3" />
</a>
)}
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="providerId">Provider ID</Label>
<Input
id="providerId"
value={providerId}
onChange={(e) => setProviderId(e.target.value)}
placeholder="e.g., anthropic, openai, my-provider"
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
Unique identifier for this provider (lowercase, no spaces)
</p>
</div>
<div className="space-y-2">
<Label htmlFor="providerName">Display Name</Label>
<Input
id="providerName"
value={providerName}
onChange={(e) => setProviderName(e.target.value)}
placeholder={selectedTemplate.name}
className="bg-background border-border"
/>
</div>
{selectedTemplate.options?.baseURL && (
<div className="space-y-2">
<Label htmlFor="baseURL">Base URL</Label>
<Input
id="baseURL"
value={baseURL}
onChange={(e) => setBaseURL(e.target.value)}
placeholder={selectedTemplate.options.baseURL}
className="bg-background border-border"
/>
<p className="text-xs text-muted-foreground">
API endpoint for this provider
</p>
</div>
)}
<div className="bg-muted p-3 rounded-md">
<p className="text-xs text-muted-foreground">
<strong>NPM Package:</strong> {selectedTemplate.npm}
</p>
{selectedTemplate.models && (
<p className="text-xs text-muted-foreground mt-1">
<strong>Models:</strong> {Object.keys(selectedTemplate.models).length} pre-configured
</p>
)}
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setStep('select')}>
Back
</Button>
<Button
onClick={handleAdd}
disabled={!providerId || addProviderMutation.isPending}
>
{addProviderMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Add Provider
</Button>
</DialogFooter>
</>
)}
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,717 @@
import { useState } from 'react'
import { Plus, Trash2, Edit } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
interface Agent {
prompt?: string
description?: string
mode?: 'subagent' | 'primary' | 'all'
temperature?: number
topP?: number
model?: {
modelID: string
providerID: string
}
tools?: Record<string, boolean>
permission?: {
edit?: 'ask' | 'allow' | 'deny'
bash?: 'ask' | 'allow' | 'deny' | Record<string, 'ask' | 'allow' | 'deny'>
webfetch?: 'ask' | 'allow' | 'deny'
}
disable?: boolean
[key: string]: unknown
}
interface AgentsEditorProps {
agents: Record<string, Agent>
onChange: (agents: Record<string, Agent>) => void
}
export function AgentsEditor({ agents, onChange }: AgentsEditorProps) {
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [editingAgent, setEditingAgent] = useState<{ name: string; agent: Agent } | null>(null)
const [newAgentName, setNewAgentName] = useState('')
const [newAgent, setNewAgent] = useState<Agent>({
prompt: '',
description: '',
mode: 'subagent',
temperature: 0.7,
topP: 1,
disable: false,
tools: {},
permission: {}
})
const createAgent = () => {
if (!newAgentName.trim()) return
const updatedAgents = {
...agents,
[newAgentName]: {
prompt: newAgent.prompt || undefined,
description: newAgent.description || undefined,
mode: newAgent.mode,
temperature: newAgent.temperature,
topP: newAgent.topP,
disable: newAgent.disable
}
}
onChange(updatedAgents)
setNewAgentName('')
setNewAgent({
prompt: '',
description: '',
mode: 'subagent',
temperature: 0.7,
topP: 1,
disable: false,
tools: {},
permission: {}
})
setIsCreateDialogOpen(false)
}
const updateAgent = () => {
if (!editingAgent) return
const updatedAgents = { ...agents }
delete updatedAgents[editingAgent.name]
updatedAgents[editingAgent.name] = editingAgent.agent
onChange(updatedAgents)
setEditingAgent(null)
}
const deleteAgent = (name: string) => {
const updatedAgents = { ...agents }
delete updatedAgents[name]
onChange(updatedAgents)
}
const startEdit = (name: string, agent: Agent) => {
setEditingAgent({ name, agent })
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Agents</h3>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Agent
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create Agent</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div className='space-y-1'>
<Label htmlFor="agent-name">Agent Name</Label>
<Input
id="agent-name"
value={newAgentName}
onChange={(e) => setNewAgentName(e.target.value)}
placeholder="my-agent"
/>
</div>
<div className="space-y-1">
<Label htmlFor="agent-description">Description</Label>
<Input
id="agent-description"
value={newAgent.description}
onChange={(e) => setNewAgent({ ...newAgent, description: e.target.value })}
placeholder="Brief description of what the agent does"
/>
</div>
<div className="space-y-1">
<Label htmlFor="agent-prompt">Prompt</Label>
<Textarea
id="agent-prompt"
value={newAgent.prompt}
onChange={(e) => setNewAgent({ ...newAgent, prompt: e.target.value })}
placeholder="The system prompt that defines the agent's behavior and role"
rows={6}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div className="space-y-1">
<Label htmlFor="agent-mode">Mode</Label>
<Select
value={newAgent.mode}
onValueChange={(value: 'subagent' | 'primary' | 'all') =>
setNewAgent({ ...newAgent, mode: value })
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="subagent">Subagent</SelectItem>
<SelectItem value="primary">Primary</SelectItem>
<SelectItem value="all">All</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor="agent-temperature">Temperature</Label>
<Input
id="agent-temperature"
type="number"
min="0"
max="2"
step="0.1"
value={newAgent.temperature}
onChange={(e) => setNewAgent({ ...newAgent, temperature: parseFloat(e.target.value) })}
/>
</div>
<div className="space-y-1">
<Label htmlFor="agent-top-p">Top P</Label>
<Input
id="agent-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={newAgent.topP}
onChange={(e) => setNewAgent({ ...newAgent, topP: parseFloat(e.target.value) })}
/>
</div>
</div>
<div className="space-y-2">
<Label>Model Configuration</Label>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="agent-model-id">Model ID</Label>
<Input
id="agent-model-id"
value={newAgent.model?.modelID || ''}
onChange={(e) => setNewAgent({
...newAgent,
model: { ...newAgent.model, modelID: e.target.value, providerID: newAgent.model?.providerID || '' }
})}
placeholder="claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="agent-provider-id">Provider ID</Label>
<Input
id="agent-provider-id"
value={newAgent.model?.providerID || ''}
onChange={(e) => setNewAgent({
...newAgent,
model: { ...newAgent.model, providerID: e.target.value, modelID: newAgent.model?.modelID || '' }
})}
placeholder="anthropic"
/>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Tools Configuration</Label>
<div className="grid grid-cols-2 gap-2 text-sm">
<div className="flex items-center space-x-2">
<Switch
id="tool-write"
checked={newAgent.tools?.write ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, write: checked }
})}
/>
<Label htmlFor="tool-write">Write</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="tool-edit"
checked={newAgent.tools?.edit ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, edit: checked }
})}
/>
<Label htmlFor="tool-edit">Edit</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="tool-bash"
checked={newAgent.tools?.bash ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, bash: checked }
})}
/>
<Label htmlFor="tool-bash">Bash</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="tool-webfetch"
checked={newAgent.tools?.webfetch ?? true}
onCheckedChange={(checked) => setNewAgent({
...newAgent,
tools: { ...newAgent.tools, webfetch: checked }
})}
/>
<Label htmlFor="tool-webfetch">Web Fetch</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Permissions</Label>
<div className="grid grid-cols-3 gap-2 text-sm">
<div>
<Label className="text-xs">Edit</Label>
<Select
value={newAgent.permission?.edit ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setNewAgent({
...newAgent,
permission: { ...newAgent.permission, edit: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Bash</Label>
<Select
value={typeof newAgent.permission?.bash === 'string' ? newAgent.permission.bash : 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setNewAgent({
...newAgent,
permission: { ...newAgent.permission, bash: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Web Fetch</Label>
<Select
value={newAgent.permission?.webfetch ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setNewAgent({
...newAgent,
permission: { ...newAgent.permission, webfetch: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="agent-disable"
checked={newAgent.disable}
onCheckedChange={(checked) => setNewAgent({ ...newAgent, disable: checked })}
/>
<Label htmlFor="agent-disable">Disable agent</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={createAgent} disabled={!newAgentName.trim()}>
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{Object.keys(agents).length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No agents configured. Add your first agent to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{Object.entries(agents).map(([name, agent]) => (
<Card key={name}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">{name}</CardTitle>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(name, agent)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => deleteAgent(name)}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{agent.description && (
<p className="text-sm text-muted-foreground">{agent.description}</p>
)}
<div className="text-xs text-muted-foreground space-y-1">
<p>Mode: {agent.mode}</p>
{agent.temperature !== undefined && <p>Temperature: {agent.temperature}</p>}
{agent.topP !== undefined && <p>Top P: {agent.topP}</p>}
{agent.model?.modelID && <p>Model: {agent.model.providerID}/{agent.model.modelID}</p>}
{agent.disable && <p>Status: Disabled</p>}
</div>
{agent.prompt && (
<div className="mt-2 p-2 bg-muted rounded text-xs font-mono max-h-20 overflow-y-auto">
{agent.prompt}
</div>
)}
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Edit Dialog */}
<Dialog open={!!editingAgent} onOpenChange={() => setEditingAgent(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Edit Agent</DialogTitle>
</DialogHeader>
{editingAgent && (
<div className="space-y-4">
<div className="space-y-1">
<Label htmlFor="edit-agent-name">Agent Name</Label>
<Input
id="edit-agent-name"
value={editingAgent.name}
disabled
className="bg-muted"
/>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-description">Description</Label>
<Input
id="edit-agent-description"
value={editingAgent.agent.description || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, description: e.target.value }
})}
placeholder="Brief description of what the agent does"
/>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-prompt">Prompt</Label>
<Textarea
id="edit-agent-prompt"
value={editingAgent.agent.prompt || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, prompt: e.target.value }
})}
placeholder="The system prompt that defines the agent's behavior and role"
rows={6}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div className='space-y-1'>
<Label htmlFor="edit-agent-mode">Mode</Label>
<Select
value={editingAgent.agent.mode || 'subagent'}
onValueChange={(value: 'subagent' | 'primary' | 'all') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, mode: value }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="subagent">Subagent</SelectItem>
<SelectItem value="primary">Primary</SelectItem>
<SelectItem value="all">All</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-temperature">Temperature</Label>
<Input
id="edit-agent-temperature"
type="number"
min="0"
max="2"
step="0.1"
value={editingAgent.agent.temperature ?? 0.7}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, temperature: parseFloat(e.target.value) }
})}
/>
</div>
<div className="space-y-1">
<Label htmlFor="edit-agent-top-p">Top P</Label>
<Input
id="edit-agent-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={editingAgent.agent.topP ?? 1}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, topP: parseFloat(e.target.value) }
})}
/>
</div>
</div>
<div className="space-y-2">
<Label>Model Configuration</Label>
<div className="grid grid-cols-2 gap-4">
<div>
<Label htmlFor="edit-agent-model-id">Model ID</Label>
<Input
id="edit-agent-model-id"
value={editingAgent.agent.model?.modelID || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: {
...editingAgent.agent,
model: {
...editingAgent.agent.model,
modelID: e.target.value,
providerID: editingAgent.agent.model?.providerID || ''
}
}
})}
placeholder="claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="edit-agent-provider-id">Provider ID</Label>
<Input
id="edit-agent-provider-id"
value={editingAgent.agent.model?.providerID || ''}
onChange={(e) => setEditingAgent({
...editingAgent,
agent: {
...editingAgent.agent,
model: {
...editingAgent.agent.model,
providerID: e.target.value,
modelID: editingAgent.agent.model?.modelID || ''
}
}
})}
placeholder="anthropic"
/>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Tools Configuration</Label>
<div className="grid grid-cols-2 gap-2 text-sm">
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-write"
checked={editingAgent.agent.tools?.write ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, write: checked } }
})}
/>
<Label htmlFor="edit-tool-write">Write</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-edit"
checked={editingAgent.agent.tools?.edit ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, edit: checked } }
})}
/>
<Label htmlFor="edit-tool-edit">Edit</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-bash"
checked={editingAgent.agent.tools?.bash ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, bash: checked } }
})}
/>
<Label htmlFor="edit-tool-bash">Bash</Label>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-tool-webfetch"
checked={editingAgent.agent.tools?.webfetch ?? true}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, tools: { ...editingAgent.agent.tools, webfetch: checked } }
})}
/>
<Label htmlFor="edit-tool-webfetch">Web Fetch</Label>
</div>
</div>
</div>
<div className="space-y-2">
<Label>Permissions</Label>
<div className="grid grid-cols-3 gap-2 text-sm">
<div>
<Label className="text-xs">Edit</Label>
<Select
value={editingAgent.agent.permission?.edit ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, permission: { ...editingAgent.agent.permission, edit: value } }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Bash</Label>
<Select
value={typeof editingAgent.agent.permission?.bash === 'string' ? editingAgent.agent.permission.bash : 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, permission: { ...editingAgent.agent.permission, bash: value } }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
<div>
<Label className="text-xs">Web Fetch</Label>
<Select
value={editingAgent.agent.permission?.webfetch ?? 'allow'}
onValueChange={(value: 'ask' | 'allow' | 'deny') =>
setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, permission: { ...editingAgent.agent.permission, webfetch: value } }
})
}
>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="ask">Ask</SelectItem>
<SelectItem value="allow">Allow</SelectItem>
<SelectItem value="deny">Deny</SelectItem>
</SelectContent>
</Select>
</div>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-agent-disable"
checked={editingAgent.agent.disable || false}
onCheckedChange={(checked) => setEditingAgent({
...editingAgent,
agent: { ...editingAgent.agent, disable: checked }
})}
/>
<Label htmlFor="edit-agent-disable">Disable agent</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setEditingAgent(null)}>
Cancel
</Button>
<Button onClick={updateAgent}>
Update
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,369 @@
import { useState } from 'react'
import { Plus, Trash2, Edit } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Switch } from '@/components/ui/switch'
interface Command {
template: string
description?: string
agent?: string
model?: string
subtask?: boolean
topP?: number
}
interface CommandsEditorProps {
commands: Record<string, Command>
onChange: (commands: Record<string, Command>) => void
}
export function CommandsEditor({ commands, onChange }: CommandsEditorProps) {
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [editingCommand, setEditingCommand] = useState<{ name: string; command: Command } | null>(null)
const [newCommandName, setNewCommandName] = useState('')
const [newCommand, setNewCommand] = useState<Command>({
template: '',
description: '',
agent: '',
model: '',
subtask: false,
topP: 1
})
const createCommand = () => {
if (!newCommandName.trim() || !newCommand.template.trim()) return
const updatedCommands = {
...commands,
[newCommandName]: {
template: newCommand.template,
description: newCommand.description,
agent: newCommand.agent || undefined,
model: newCommand.model || undefined,
subtask: newCommand.subtask || undefined,
topP: newCommand.topP || undefined
}
}
onChange(updatedCommands)
setNewCommandName('')
setNewCommand({
template: '',
description: '',
agent: '',
model: '',
subtask: false,
topP: 1
})
setIsCreateDialogOpen(false)
}
const updateCommand = () => {
if (!editingCommand) return
const updatedCommands = { ...commands }
delete updatedCommands[editingCommand.name]
updatedCommands[editingCommand.name] = {
template: editingCommand.command.template,
description: editingCommand.command.description,
agent: editingCommand.command.agent || undefined,
model: editingCommand.command.model || undefined,
subtask: editingCommand.command.subtask || undefined,
topP: editingCommand.command.topP || undefined
}
onChange(updatedCommands)
setEditingCommand(null)
}
const deleteCommand = (name: string) => {
const updatedCommands = { ...commands }
delete updatedCommands[name]
onChange(updatedCommands)
}
const startEdit = (name: string, command: Command) => {
setEditingCommand({ name, command })
}
return (
<div className="space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Commands</h3>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
Add Command
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create Command</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="command-name">Command Name</Label>
<Input
id="command-name"
value={newCommandName}
onChange={(e) => setNewCommandName(e.target.value)}
placeholder="my-command"
/>
</div>
<div>
<Label htmlFor="command-description">Description</Label>
<Input
id="command-description"
value={newCommand.description}
onChange={(e) => setNewCommand({ ...newCommand, description: e.target.value })}
placeholder="Brief description of what the command does"
/>
</div>
<div>
<Label htmlFor="command-template">Template</Label>
<Textarea
id="command-template"
value={newCommand.template}
onChange={(e) => setNewCommand({ ...newCommand, template: e.target.value })}
placeholder="The prompt template that will be sent to the LLM. Use $ARGUMENTS or $1, $2, etc. for parameters."
rows={8}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div>
<Label htmlFor="command-agent">Agent (optional)</Label>
<Input
id="command-agent"
value={newCommand.agent}
onChange={(e) => setNewCommand({ ...newCommand, agent: e.target.value })}
placeholder="build"
/>
</div>
<div>
<Label htmlFor="command-model">Model (optional)</Label>
<Input
id="command-model"
value={newCommand.model}
onChange={(e) => setNewCommand({ ...newCommand, model: e.target.value })}
placeholder="anthropic/claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="command-top-p">Top P (optional)</Label>
<Input
id="command-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={newCommand.topP}
onChange={(e) => setNewCommand({ ...newCommand, topP: parseFloat(e.target.value) })}
/>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="command-subtask"
checked={newCommand.subtask}
onCheckedChange={(checked) => setNewCommand({ ...newCommand, subtask: checked })}
/>
<Label htmlFor="command-subtask">Run as subtask</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={createCommand} disabled={!newCommandName.trim() || !newCommand.template.trim()}>
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{Object.keys(commands).length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No commands configured. Add your first command to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{Object.entries(commands).map(([name, command]) => (
<Card key={name}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<CardTitle className="text-base">/{name}</CardTitle>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(name, command)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => deleteCommand(name)}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="space-y-2">
{command.description && (
<p className="text-sm text-muted-foreground">{command.description}</p>
)}
<div className="text-xs text-muted-foreground space-y-1">
{command.agent && <p>Agent: {command.agent}</p>}
{command.model && <p>Model: {command.model}</p>}
{command.topP !== undefined && <p>Top P: {command.topP}</p>}
{command.subtask && <p>Subtask: Yes</p>}
</div>
<div className="mt-2 p-2 bg-muted rounded text-xs font-mono max-h-20 overflow-y-auto">
{command.template}
</div>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Edit Dialog */}
<Dialog open={!!editingCommand} onOpenChange={() => setEditingCommand(null)}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Edit Command</DialogTitle>
</DialogHeader>
{editingCommand && (
<div className="space-y-4">
<div>
<Label htmlFor="edit-command-name">Command Name</Label>
<Input
id="edit-command-name"
value={editingCommand.name}
disabled
className="bg-muted"
/>
</div>
<div>
<Label htmlFor="edit-command-description">Description</Label>
<Input
id="edit-command-description"
value={editingCommand.command.description || ''}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, description: e.target.value }
})}
placeholder="Brief description of what the command does"
/>
</div>
<div>
<Label htmlFor="edit-command-template">Template</Label>
<Textarea
id="edit-command-template"
value={editingCommand.command.template}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, template: e.target.value }
})}
placeholder="The prompt template that will be sent to the LLM. Use $ARGUMENTS or $1, $2, etc. for parameters."
rows={8}
className="font-mono text-sm"
/>
</div>
<div className="grid grid-cols-3 gap-4">
<div>
<Label htmlFor="edit-command-agent">Agent (optional)</Label>
<Input
id="edit-command-agent"
value={editingCommand.command.agent || ''}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, agent: e.target.value }
})}
placeholder="build"
/>
</div>
<div>
<Label htmlFor="edit-command-model">Model (optional)</Label>
<Input
id="edit-command-model"
value={editingCommand.command.model || ''}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, model: e.target.value }
})}
placeholder="anthropic/claude-3-5-sonnet-20241022"
/>
</div>
<div>
<Label htmlFor="edit-command-top-p">Top P (optional)</Label>
<Input
id="edit-command-top-p"
type="number"
min="0"
max="1"
step="0.1"
value={editingCommand.command.topP ?? 1}
onChange={(e) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, topP: parseFloat(e.target.value) }
})}
/>
</div>
</div>
<div className="flex items-center space-x-2">
<Switch
id="edit-command-subtask"
checked={editingCommand.command.subtask || false}
onCheckedChange={(checked) => setEditingCommand({
...editingCommand,
command: { ...editingCommand.command, subtask: checked }
})}
/>
<Label htmlFor="edit-command-subtask">Run as subtask</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setEditingCommand(null)}>
Cancel
</Button>
<Button onClick={updateCommand}>
Update
</Button>
</div>
</div>
)}
</DialogContent>
</Dialog>
</div>
)
}
@@ -0,0 +1,129 @@
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { Label } from '@/components/ui/label'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { Input } from '@/components/ui/input'
export function GeneralSettings() {
const { preferences, isLoading, updateSettings, isUpdating } = useSettings()
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">General Preferences</h2>
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="theme">Theme</Label>
<Select
value={preferences?.theme || 'dark'}
onValueChange={(value) => updateSettings({ theme: value as 'dark' | 'light' | 'system' })}
>
<SelectTrigger id="theme">
<SelectValue placeholder="Select a theme" />
</SelectTrigger>
<SelectContent>
<SelectItem value="dark">Dark</SelectItem>
<SelectItem value="light">Light</SelectItem>
<SelectItem value="system">System</SelectItem>
</SelectContent>
</Select>
<p className="text-sm text-muted-foreground">
Choose your preferred color scheme
</p>
</div>
<div className="space-y-2">
<Label htmlFor="mode">Mode</Label>
<Select
value={preferences?.mode || 'build'}
onValueChange={(value) => updateSettings({ mode: value as 'plan' | 'build' })}
>
<SelectTrigger id="mode">
<SelectValue placeholder="Select a mode" />
</SelectTrigger>
<SelectContent>
<SelectItem value="plan">Plan</SelectItem>
<SelectItem value="build">Build</SelectItem>
</SelectContent>
</Select>
<p className="text-sm text-muted-foreground">
Plan mode: Read-only. Build mode: File changes enabled
</p>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="autoScroll" className="text-base">Auto-scroll</Label>
<p className="text-sm text-muted-foreground">
Automatically scroll to bottom when new messages arrive
</p>
</div>
<Switch
id="autoScroll"
checked={preferences?.autoScroll ?? true}
onCheckedChange={(checked) => updateSettings({ autoScroll: checked })}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="showReasoning" className="text-base">Show reasoning</Label>
<p className="text-sm text-muted-foreground">
Display model reasoning and thought process
</p>
</div>
<Switch
id="showReasoning"
checked={preferences?.showReasoning ?? false}
onCheckedChange={(checked) => updateSettings({ showReasoning: checked })}
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="expandToolCalls" className="text-base">Expand tool calls</Label>
<p className="text-sm text-muted-foreground">
Automatically expand tool call details by default
</p>
</div>
<Switch
id="expandToolCalls"
checked={preferences?.expandToolCalls ?? false}
onCheckedChange={(checked) => updateSettings({ expandToolCalls: checked })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="gitToken">GitHub Personal Access Token</Label>
<Input
id="gitToken"
type="password"
placeholder="ghp_..."
value={preferences?.gitToken || ''}
onChange={(e) => updateSettings({ gitToken: e.target.value })}
className="bg-background border-border text-foreground placeholder:text-muted-foreground"
/>
<p className="text-sm text-muted-foreground">
Required for cloning private repos. Get one at github.com/settings/tokens
</p>
</div>
{isUpdating && (
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Saving...</span>
</div>
)}
</div>
</div>
)
}
@@ -0,0 +1,158 @@
import { useState, useEffect } from 'react'
import { useSettings } from '@/hooks/useSettings'
import { Loader2 } from 'lucide-react'
import { DEFAULT_KEYBOARD_SHORTCUTS } from '@/api/types/settings'
const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0
const CMD_KEY = isMac ? 'Cmd' : 'Ctrl'
const normalizeShortcut = (shortcut: string): string => {
return shortcut.replace(/Cmd/g, CMD_KEY)
}
export function KeyboardShortcuts() {
const { preferences, isLoading, updateSettings } = useSettings()
const [recordingKey, setRecordingKey] = useState<string | null>(null)
const [tempShortcuts, setTempShortcuts] = useState<Record<string, string>>({})
const [currentKeys, setCurrentKeys] = useState<string>('')
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
const shortcuts = { ...DEFAULT_KEYBOARD_SHORTCUTS, ...preferences?.keyboardShortcuts, ...tempShortcuts }
const handleKeyDown = (e: KeyboardEvent, action: string) => {
e.preventDefault()
const keys = []
if (e.ctrlKey) keys.push('Ctrl')
if (e.metaKey) keys.push('Cmd')
if (e.altKey) keys.push('Alt')
if (e.shiftKey) keys.push('Shift')
// Get the actual key pressed (excluding modifier keys)
const mainKey = e.key
if (!['Control', 'Meta', 'Alt', 'Shift'].includes(mainKey)) {
// Handle special keys
let displayKey = mainKey
if (mainKey === ' ') displayKey = 'Space'
else if (mainKey === 'ArrowUp') displayKey = 'Up'
else if (mainKey === 'ArrowDown') displayKey = 'Down'
else if (mainKey === 'ArrowLeft') displayKey = 'Left'
else if (mainKey === 'ArrowRight') displayKey = 'Right'
else if (mainKey === 'Enter') displayKey = 'Return'
else if (mainKey === 'Escape') displayKey = 'Esc'
else if (mainKey === 'Tab') displayKey = 'Tab'
else if (mainKey === 'Backspace') displayKey = 'Backspace'
else if (mainKey === 'Delete') displayKey = 'Delete'
else if (mainKey.length === 1) displayKey = mainKey.toUpperCase()
keys.push(displayKey)
// Only complete recording if we have a non-modifier key
if (keys.length > 0) {
const shortcut = keys.join('+')
setTempShortcuts(prev => ({ ...prev, [action]: shortcut }))
setRecordingKey(null)
setCurrentKeys('')
updateSettings({
keyboardShortcuts: { ...shortcuts, [action]: shortcut }
})
}
} else {
// Show current modifier keys being held
setCurrentKeys(keys.join('+'))
}
}
const handleKeyUp = (e: KeyboardEvent) => {
// Clear current keys display when modifiers are released
if (['Control', 'Meta', 'Alt', 'Shift'].includes(e.key)) {
setCurrentKeys('')
}
}
const startRecording = (action: string) => {
setRecordingKey(action)
setCurrentKeys('')
}
const stopRecording = () => {
setRecordingKey(null)
setCurrentKeys('')
}
useEffect(() => {
if (recordingKey) {
const handleGlobalKeyDown = (e: KeyboardEvent) => {
handleKeyDown(e, recordingKey)
}
const handleGlobalKeyUp = (e: KeyboardEvent) => {
handleKeyUp(e)
}
document.addEventListener('keydown', handleGlobalKeyDown)
document.addEventListener('keyup', handleGlobalKeyUp)
return () => {
document.removeEventListener('keydown', handleGlobalKeyDown)
document.removeEventListener('keyup', handleGlobalKeyUp)
}
}
}, [recordingKey])
return (
<div className="bg-card border border-border rounded-lg p-6">
<h2 className="text-lg font-semibold text-foreground mb-6">Keyboard Shortcuts</h2>
<div className="space-y-4">
{Object.entries(shortcuts).map(([action, keys]) => (
<div key={action} className="flex items-center justify-between py-3 border-b border-border last:border-0">
<div className="space-y-1">
<p className="text-foreground font-medium capitalize">
{action.replace(/([A-Z])/g, ' $1').trim()}
</p>
</div>
{recordingKey === action ? (
<div className="flex items-center gap-2">
<input
type="text"
className="px-3 py-1.5 bg-accent border border-primary rounded text-sm text-foreground font-mono outline-none"
placeholder="Press keys..."
value={currentKeys || ''}
autoFocus
onBlur={stopRecording}
readOnly
/>
<button
onClick={stopRecording}
className="px-2 py-1 text-xs text-muted-foreground hover:text-foreground"
>
Cancel
</button>
</div>
) : (
<button
onClick={() => startRecording(action)}
className="px-3 py-1.5 bg-accent border border-border hover:border-border rounded text-sm text-foreground font-mono transition-colors"
>
{normalizeShortcut(keys)}
</button>
)}
</div>
))}
</div>
<p className="mt-6 text-sm text-muted-foreground">
Click on any shortcut to record a new key combination
</p>
</div>
)
}
@@ -0,0 +1,124 @@
import { useState, useRef, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Loader2 } from 'lucide-react'
import type { OpenCodeConfig } from '@/api/types/settings'
interface OpenCodeConfigEditorProps {
config: OpenCodeConfig | null
isOpen: boolean
onClose: () => void
onUpdate: (content: Record<string, unknown>) => Promise<void>
isUpdating: boolean
}
export function OpenCodeConfigEditor({
config,
isOpen,
onClose,
onUpdate,
isUpdating
}: OpenCodeConfigEditorProps) {
const [editConfigContent, setEditConfigContent] = useState('')
const [editError, setEditError] = useState('')
const [editErrorLine, setEditErrorLine] = useState<number | null>(null)
const editTextareaRef = useRef<HTMLTextAreaElement>(null)
useEffect(() => {
if (config && isOpen) {
setEditConfigContent(JSON.stringify(config.content, null, 2))
setEditError('')
setEditErrorLine(null)
}
}, [config, isOpen])
useEffect(() => {
if (isOpen && editTextareaRef.current) {
editTextareaRef.current.focus()
}
}, [isOpen])
const updateConfig = async () => {
if (!config) return
try {
const parsedContent = JSON.parse(editConfigContent)
const forbiddenFields = ['id', 'createdAt', 'updatedAt']
const foundForbidden = forbiddenFields.filter(field => field in parsedContent)
if (foundForbidden.length > 0) {
throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`)
}
await onUpdate(parsedContent)
onClose()
} catch (error) {
if (error instanceof SyntaxError) {
const match = error.message.match(/line (\d+)/i)
const line = match ? parseInt(match[1]) : null
setEditErrorLine(line)
setEditError('Invalid JSON format')
} else {
setEditError(error instanceof Error ? error.message : 'Failed to update config')
}
}
}
if (!isOpen || !config) return null
return (
<div className="fixed inset-0 z-50 bg-background/80 backdrop-blur-sm">
<div className="fixed inset-0 z-50 flex items-center justify-center p-4">
<div className="relative w-full max-w-6xl h-[90vh] bg-background border rounded-lg shadow-lg">
<div className="flex flex-col h-full">
<div className="flex items-center justify-between p-6 border-b">
<div>
<h2 className="text-lg font-semibold">Edit Config: {config.name}</h2>
</div>
<div className="flex gap-2">
<Button variant="outline" onClick={onClose}>
Cancel
</Button>
<Button
onClick={updateConfig}
disabled={isUpdating || !editConfigContent.trim()}
>
{isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Update
</Button>
</div>
</div>
<div className="flex-1 p-6 overflow-hidden">
<div className="h-full flex flex-col">
<Label htmlFor="edit-config-content" className="mb-2">
Config Content (JSON)
</Label>
<Textarea
id="edit-config-content"
ref={editTextareaRef}
value={editConfigContent}
onChange={(e) => {
setEditConfigContent(e.target.value)
setEditError('')
setEditErrorLine(null)
}}
className="flex-1 font-mono text-sm resize-none"
/>
{editError && (
<p className="text-sm text-red-500 mt-2">
{editError}
{editErrorLine && (
<span className="ml-2 text-xs">(Line {editErrorLine})</span>
)}
</p>
)}
</div>
</div>
</div>
</div>
</div>
</div>
)
}
@@ -0,0 +1,469 @@
import { useState, useEffect, useRef } from 'react'
import { Loader2, Plus, Trash2, Edit, Star, StarOff, Download } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Badge } from '@/components/ui/badge'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Switch } from '@/components/ui/switch'
import { DeleteDialog } from '@/components/ui/delete-dialog'
import { OpenCodeConfigEditor } from './OpenCodeConfigEditor'
import { CommandsEditor } from './CommandsEditor'
import { AgentsEditor } from './AgentsEditor'
import { settingsApi } from '@/api/settings'
interface OpenCodeConfig {
id: number
name: string
content: Record<string, unknown>
isDefault: boolean
createdAt: number
updatedAt: number
}
export function OpenCodeConfigManager() {
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isUpdating, setIsUpdating] = useState(false)
const [editingConfig, setEditingConfig] = useState<OpenCodeConfig | null>(null)
const [selectedConfig, setSelectedConfig] = useState<OpenCodeConfig | null>(null)
const [newConfigName, setNewConfigName] = useState('')
const [newConfigContent, setNewConfigContent] = useState('')
const [newConfigIsDefault, setNewConfigIsDefault] = useState(false)
const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
const [isEditDialogOpen, setIsEditDialogOpen] = useState(false)
const [deleteConfirmConfig, setDeleteConfirmConfig] = useState<OpenCodeConfig | null>(null)
const [createError, setCreateError] = useState('')
const [createErrorLine, setCreateErrorLine] = useState<number | null>(null)
const createTextareaRef = useRef<HTMLTextAreaElement>(null)
const fetchConfigs = async () => {
try {
setIsLoading(true)
const data = await settingsApi.getOpenCodeConfigs()
setConfigs(data.configs)
} catch (error) {
console.error('Failed to fetch configs:', error)
} finally {
setIsLoading(false)
}
}
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>) => {
try {
setIsUpdating(true)
await settingsApi.updateOpenCodeConfig(configName, { content: newContent })
// Update the local state
setConfigs(prev => prev.map(config =>
config.name === configName
? { ...config, content: newContent, updatedAt: Date.now() }
: config
))
// Update selected config if it's the one being edited
if (selectedConfig && selectedConfig.name === configName) {
setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: Date.now() })
}
} catch (error) {
console.error('Failed to update config:', error)
} finally {
setIsUpdating(false)
}
}
useEffect(() => {
fetchConfigs()
}, [])
const createConfig = async () => {
if (!newConfigName.trim() || !newConfigContent.trim()) return
try {
setIsUpdating(true)
setCreateError('')
const content = JSON.parse(newConfigContent)
const forbiddenFields = ['id', 'createdAt', 'updatedAt']
const foundForbidden = forbiddenFields.filter(field => field in content)
if (foundForbidden.length > 0) {
throw new Error(`Invalid fields found: ${foundForbidden.join(', ')}. These fields are managed automatically.`)
}
await settingsApi.createOpenCodeConfig({
name: newConfigName.trim(),
content,
isDefault: newConfigIsDefault,
})
setNewConfigName('')
setNewConfigContent('')
setNewConfigIsDefault(false)
setIsCreateDialogOpen(false)
fetchConfigs()
} catch (error) {
if (error instanceof SyntaxError) {
const match = error.message.match(/line (\d+)/i)
const line = match ? parseInt(match[1]) : null
setCreateErrorLine(line)
setCreateError(`JSON Error: ${error.message}`)
if (line && createTextareaRef.current) {
highlightErrorLine(createTextareaRef.current, line)
}
} else if (error instanceof Error) {
setCreateError(error.message)
setCreateErrorLine(null)
} else {
setCreateError('Failed to create configuration')
setCreateErrorLine(null)
}
console.error('Failed to create config:', error)
} finally {
setIsUpdating(false)
}
}
const deleteConfig = async (config: OpenCodeConfig) => {
try {
setIsUpdating(true)
await settingsApi.deleteOpenCodeConfig(config.name)
setDeleteConfirmConfig(null)
fetchConfigs()
} catch (error) {
console.error('Failed to delete config:', error)
} finally {
setIsUpdating(false)
}
}
const setDefaultConfig = async (config: OpenCodeConfig) => {
try {
setIsUpdating(true)
await settingsApi.setDefaultOpenCodeConfig(config.name)
fetchConfigs()
} catch (error) {
console.error('Failed to set default config:', error)
} finally {
setIsUpdating(false)
}
}
const uploadConfig = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
if (!file) return
const reader = new FileReader()
reader.onload = (e) => {
const content = e.target?.result as string
try {
JSON.parse(content)
setNewConfigContent(content)
setNewConfigName(file.name.replace('.json', '').replace('.jsonc', ''))
} catch {
window.alert('Invalid JSON file')
}
}
reader.readAsText(file)
}
const downloadConfig = (config: OpenCodeConfig) => {
const blob = new Blob([JSON.stringify(config.content, null, 2)], { type: 'application/json' })
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `${config.name}.json`
a.click()
URL.revokeObjectURL(url)
}
const highlightErrorLine = (textarea: HTMLTextAreaElement, line: number) => {
const lines = textarea.value.split('\n')
if (line > lines.length) return
let charIndex = 0
for (let i = 0; i < line - 1; i++) {
charIndex += lines[i].length + 1
}
textarea.focus()
textarea.setSelectionRange(charIndex, charIndex + lines[line - 1].length)
}
const startEdit = (config: OpenCodeConfig) => {
setEditingConfig(config)
setIsEditDialogOpen(true)
}
if (isLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-6 overflow-y-auto">
<div className="flex items-center justify-between">
<h2 className="text-lg font-semibold text-foreground">OpenCode Configurations</h2>
<Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
<DialogTrigger asChild>
<Button>
<Plus className="h-4 w-4 mr-2" />
New Config
</Button>
</DialogTrigger>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Create OpenCode Config</DialogTitle>
</DialogHeader>
<div className="space-y-4">
<div>
<Label htmlFor="config-name">Config Name</Label>
<Input
id="config-name"
value={newConfigName}
onChange={(e) => setNewConfigName(e.target.value)}
placeholder="my-config"
/>
</div>
<div>
<Label htmlFor="config-upload">Upload JSON File</Label>
<Input
id="config-upload"
type="file"
accept=".json,.jsonc"
onChange={uploadConfig}
/>
</div>
<div>
<Label htmlFor="config-content">Config Content (JSON)</Label>
<Textarea
id="config-content"
ref={createTextareaRef}
value={newConfigContent}
onChange={(e) => {
setNewConfigContent(e.target.value)
setCreateError('')
setCreateErrorLine(null)
}}
placeholder='{"$schema": "https://opencode.ai/config.json", "theme": "dark"}'
rows={20}
className="font-mono text-sm"
/>
{createError && (
<p className="text-sm text-red-500 mt-2">
{createError}
{createErrorLine && (
<span className="ml-2 text-xs">(Line {createErrorLine})</span>
)}
</p>
)}
</div>
<div className="flex items-center space-x-2">
<Switch
id="config-default"
checked={newConfigIsDefault}
onCheckedChange={setNewConfigIsDefault}
/>
<Label htmlFor="config-default">Set as default configuration</Label>
</div>
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={() => setIsCreateDialogOpen(false)}>
Cancel
</Button>
<Button onClick={createConfig} disabled={isUpdating || !newConfigName.trim() || !newConfigContent.trim()}>
{isUpdating && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Create
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</div>
{configs.length === 0 ? (
<Card>
<CardContent className="p-8 text-center">
<p className="text-muted-foreground">No OpenCode configurations found. Create your first config to get started.</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{configs.map((config) => (
<Card key={config.id}>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<CardTitle className="text-base">{config.name}</CardTitle>
{config.isDefault && (
<Badge variant="default" className="text-xs">
<Star className="h-3 w-3 mr-1" />
Default
</Badge>
)}
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => downloadConfig(config)}
>
<Download className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => startEdit(config)}
>
<Edit className="h-4 w-4" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDefaultConfig(config)}
disabled={config.isDefault || isUpdating}
>
{config.isDefault ? (
<StarOff className="h-4 w-4" />
) : (
<Star className="h-4 w-4" />
)}
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setDeleteConfirmConfig(config)}
className="text-red-500 hover:text-red-600"
>
<Trash2 className="h-4 w-4" />
</Button>
</div>
</div>
</CardHeader>
<CardContent>
<div className="text-sm text-muted-foreground">
<p>Updated: {new Date(config.updatedAt).toLocaleString()}</p>
<p>Created: {new Date(config.createdAt).toLocaleString()}</p>
</div>
</CardContent>
</Card>
))}
</div>
)}
{/* Edit Dialog */}
<OpenCodeConfigEditor
config={editingConfig}
isOpen={isEditDialogOpen}
onClose={() => setIsEditDialogOpen(false)}
onUpdate={async (content) => {
if (!editingConfig) return
await settingsApi.updateOpenCodeConfig(editingConfig.name, { content })
await fetchConfigs()
}}
isUpdating={isUpdating}
/>
{/* Commands and Agents Section */}
<div className="mt-8 space-y-6">
<div className="border-t border-border pt-6">
<h3 className="text-lg font-semibold mb-4">Configure Commands & Agents</h3>
<p className="text-sm text-muted-foreground mb-6">
Add custom commands and agents to your OpenCode configurations. Select a configuration below to edit its commands and agents.
</p>
{configs.length > 0 && (
<div className="space-y-6">
<div className='px-1'>
<Label className="text-base font-medium">Select Configuration to Edit</Label>
<Select
onValueChange={(value) => {
const config = configs.find(c => c.name === value)
setSelectedConfig(config || null)
}}
value={selectedConfig?.name || ""}
>
<SelectTrigger className="mt-2 w-full">
<SelectValue placeholder="Select a configuration..." />
</SelectTrigger>
<SelectContent>
{configs.map(config => (
<SelectItem key={config.id} value={config.name}>
{config.name} {config.isDefault && '(Default)'}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="space-y-8 pb-20">
{selectedConfig ? (
<>
<div className="bg-card border border-border rounded-lg p-6">
<h4 className="text-md font-medium mb-4">Editing: {selectedConfig.name}</h4>
<div className="max-h-[60vh] overflow-y-auto">
<CommandsEditor
commands={(selectedConfig.content.command as Record<string, any>) || {}}
onChange={(commands) => {
const updatedContent = {
...selectedConfig.content,
command: commands
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
</div>
</div>
<div className="bg-card border border-border rounded-lg p-6">
<div className="max-h-[60vh] overflow-y-auto">
<AgentsEditor
agents={(selectedConfig.content.agent as Record<string, any>) || {}}
onChange={(agents) => {
const updatedContent = {
...selectedConfig.content,
agent: agents
}
updateConfigContent(selectedConfig.name, updatedContent)
}}
/>
</div>
</div>
</>
) : (
<div className="bg-card border border-border rounded-lg p-6">
<p className="text-muted-foreground text-center">Select a configuration to edit its commands and agents.</p>
</div>
)}
</div>
</div>
)}
</div>
</div>
{/* Delete Confirmation Dialog */}
<DeleteDialog
open={!!deleteConfirmConfig}
onOpenChange={() => setDeleteConfirmConfig(null)}
onConfirm={() => deleteConfirmConfig && deleteConfig(deleteConfirmConfig)}
onCancel={() => setDeleteConfirmConfig(null)}
title="Delete Configuration"
description="Any repositories using this configuration will continue to work but won't receive updates."
itemName={deleteConfirmConfig?.name}
isDeleting={isUpdating}
/>
</div>
)
}
@@ -0,0 +1,207 @@
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
import { Badge } from '@/components/ui/badge'
import { Loader2, Key, Check, X, Plus } from 'lucide-react'
import { providerCredentialsApi } from '@/api/providers'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { AddProviderDialog } from './AddProviderDialog'
import { useProviders } from '@/hooks/useProviders'
export function ProviderSettings() {
const [selectedProvider, setSelectedProvider] = useState<string | null>(null)
const [apiKey, setApiKey] = useState('')
const [showApiKey, setShowApiKey] = useState(false)
const [addDialogOpen, setAddDialogOpen] = useState(false)
const queryClient = useQueryClient()
const { data: providers, isLoading: providersLoading } = useProviders()
const { data: credentialsList, isLoading: credentialsLoading } = useQuery({
queryKey: ['provider-credentials'],
queryFn: () => providerCredentialsApi.list(),
})
const setCredentialMutation = useMutation({
mutationFn: ({ providerId, apiKey }: { providerId: string; apiKey: string }) =>
providerCredentialsApi.set(providerId, apiKey),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
setSelectedProvider(null)
setApiKey('')
},
})
const deleteCredentialMutation = useMutation({
mutationFn: (providerId: string) => providerCredentialsApi.delete(providerId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['provider-credentials'] })
},
})
const handleSetCredential = () => {
if (selectedProvider && apiKey) {
setCredentialMutation.mutate({ providerId: selectedProvider, apiKey })
}
}
const handleDeleteCredential = (providerId: string) => {
if (confirm(`Remove credentials for ${providerId}?`)) {
deleteCredentialMutation.mutate(providerId)
}
}
const hasCredentials = (providerId: string) => {
return credentialsList?.includes(providerId) || false
}
if (providersLoading || credentialsLoading) {
return (
<div className="flex items-center justify-center py-12">
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
</div>
)
}
return (
<div className="space-y-4">
<div className="flex items-start justify-between">
<div>
<h2 className="text-lg font-semibold text-foreground mb-2">Provider Credentials</h2>
<p className="text-sm text-muted-foreground">
Manage API keys for AI providers. Keys are stored securely in your workspace.
</p>
</div>
<Button onClick={() => setAddDialogOpen(true)}>
<Plus className="h-4 w-4 mr-2" />
Add Provider
</Button>
</div>
{!providers || providers.length === 0 ? (
<Card className="bg-card border-border">
<CardContent className="pt-6">
<p className="text-sm text-muted-foreground text-center">
No providers configured. Add providers in your OpenCode config.
</p>
</CardContent>
</Card>
) : (
<div className="grid gap-4">
{providers.map((provider) => {
const hasKey = hasCredentials(provider.id)
const modelCount = Object.keys(provider.models || {}).length
return (
<Card key={provider.id} className="bg-card border-border">
<CardHeader>
<div className="flex items-start justify-between">
<div className="flex-1">
<CardTitle className="text-base flex items-center gap-2">
{provider.name || provider.id}
{hasKey ? (
<Badge variant="default" className="bg-green-600 hover:bg-green-700">
<Check className="h-3 w-3 mr-1" />
Configured
</Badge>
) : (
<Badge variant="secondary">
<X className="h-3 w-3 mr-1" />
No Key
</Badge>
)}
</CardTitle>
<CardDescription className="mt-1">
{provider.npm && <span className="text-xs">Package: {provider.npm}</span>}
{provider.options?.baseURL && (
<span className="text-xs block">{provider.options.baseURL}</span>
)}
{modelCount > 0 && (
<span className="text-xs block">{modelCount} model{modelCount !== 1 ? 's' : ''}</span>
)}
</CardDescription>
</div>
<div className="flex gap-2">
<Button
size="sm"
variant={hasKey ? 'outline' : 'default'}
onClick={() => setSelectedProvider(provider.id)}
>
<Key className="h-4 w-4 mr-1" />
{hasKey ? 'Update' : 'Add'} Key
</Button>
{hasKey && (
<Button
size="sm"
variant="destructive"
onClick={() => handleDeleteCredential(provider.id)}
disabled={deleteCredentialMutation.isPending}
>
Remove
</Button>
)}
</div>
</div>
</CardHeader>
</Card>
)
})}
</div>
)}
<Dialog open={!!selectedProvider} onOpenChange={(open) => !open && setSelectedProvider(null)}>
<DialogContent className="bg-card border-border">
<DialogHeader>
<DialogTitle>Set API Key for {selectedProvider}</DialogTitle>
<DialogDescription>
Enter your API key. It will be stored securely in your workspace.
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
<div className="space-y-2">
<Label htmlFor="apiKey">API Key</Label>
<div className="relative">
<Input
id="apiKey"
type={showApiKey ? 'text' : 'password'}
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
placeholder="sk-..."
className="bg-background border-border pr-20"
/>
<Button
type="button"
variant="ghost"
size="sm"
className="absolute right-1 top-1/2 -translate-y-1/2 h-7"
onClick={() => setShowApiKey(!showApiKey)}
>
{showApiKey ? 'Hide' : 'Show'}
</Button>
</div>
</div>
</div>
<DialogFooter>
<Button variant="outline" onClick={() => setSelectedProvider(null)}>
Cancel
</Button>
<Button
onClick={handleSetCredential}
disabled={!apiKey || setCredentialMutation.isPending}
>
{setCredentialMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
Save
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
<AddProviderDialog open={addDialogOpen} onOpenChange={setAddDialogOpen} />
</div>
)
}
@@ -0,0 +1,131 @@
import { useState } from 'react'
import { GeneralSettings } from '@/components/settings/GeneralSettings'
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManager'
import { ProviderSettings } from '@/components/settings/ProviderSettings'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { Settings2, Keyboard, Code, ChevronLeft, X, Key } from 'lucide-react'
import { Button } from '@/components/ui/button'
interface SettingsDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
}
type SettingsView = 'menu' | 'general' | 'shortcuts' | 'opencode' | 'providers'
export function SettingsDialog({ open, onOpenChange }: SettingsDialogProps) {
const [mobileView, setMobileView] = useState<SettingsView>('menu')
const menuItems = [
{ id: 'general', icon: Settings2, label: 'General Settings', description: 'App preferences and behavior' },
{ id: 'shortcuts', icon: Keyboard, label: 'Keyboard Shortcuts', description: 'Customize keyboard shortcuts' },
{ id: 'opencode', icon: Code, label: 'OpenCode Config', description: 'Manage OpenCode configurations, commands, and agents' },
{ id: 'providers', icon: Key, label: 'Providers', description: 'Manage AI provider API keys' },
]
const handleClose = () => {
setMobileView('menu')
onOpenChange(false)
}
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="max-w-4xl w-full h-[100vh] sm:h-auto sm:w-[95vw] sm:max-h-[90vh] bg-gradient-to-br from-background via-background to-background border-border p-0 sm:rounded-lg overflow-hidden !flex !flex-col left-0 top-0 translate-x-0 translate-y-0 max-h-[100vh] sm:left-[50%] sm:top-[50%] sm:translate-x-[-50%] sm:translate-y-[-50%] [&>button:last-child]:hidden">
<div className="hidden sm:flex sm:flex-col sm:h-[90vh]">
<div className="sticky top-0 z-10 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-6 py-4 flex-shrink-0">
<h2 className="text-2xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
Settings
</h2>
</div>
<Tabs defaultValue="general" className="w-full flex flex-col flex-1 min-h-0">
<div className="px-6 pt-6 pb-4 flex-shrink-0">
<TabsList className="grid w-full grid-cols-4 bg-card border border-border p-1">
<TabsTrigger value="general" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
General
</TabsTrigger>
<TabsTrigger value="shortcuts" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Shortcuts
</TabsTrigger>
<TabsTrigger value="opencode" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
OpenCode
</TabsTrigger>
<TabsTrigger value="providers" className="data-[state=active]:bg-blue-600 data-[state=active]:text-white text-muted-foreground transition-all duration-200">
Providers
</TabsTrigger>
</TabsList>
</div>
<div className="flex-1 overflow-y-auto">
<div className="px-6 pb-6">
<TabsContent value="general" className="mt-0"><GeneralSettings /></TabsContent>
<TabsContent value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
<TabsContent value="opencode" className="mt-0"><OpenCodeConfigManager /></TabsContent>
<TabsContent value="providers" className="mt-0"><ProviderSettings /></TabsContent>
</div>
</div>
</Tabs>
</div>
<div className="sm:hidden flex flex-col h-full min-h-0">
<div className="flex-shrink-0 bg-gradient-to-b from-background via-background to-transparent border-b border-border backdrop-blur-sm px-4 py-4 flex items-center justify-between">
<div className="flex items-center gap-2 flex-1">
{mobileView !== 'menu' && (
<Button
variant="ghost"
size="icon"
onClick={() => setMobileView('menu')}
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px]"
>
<ChevronLeft className="w-6 h-6" />
</Button>
)}
<h2 className="text-xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
{mobileView === 'menu' ? 'Settings' : menuItems.find(item => item.id === mobileView)?.label}
</h2>
</div>
<Button
variant="ghost"
size="icon"
onClick={handleClose}
className="text-muted-foreground hover:text-foreground min-w-[44px] min-h-[44px] flex-shrink-0"
>
<X className="w-6 h-6" />
</Button>
</div>
<div className="flex-1 min-h-0 overflow-y-auto p-4 pb-32">
{mobileView === 'menu' && (
<div className="space-y-3">
{menuItems.map((item) => (
<button
key={item.id}
onClick={() => setMobileView(item.id as SettingsView)}
className="w-full bg-gradient-to-br from-card to-card-hover border border-border rounded-xl p-4 hover:border-border transition-all duration-200 text-left"
>
<div className="flex items-center gap-4">
<div className="p-3 bg-accent rounded-lg">
<item.icon className="w-6 h-6 text-blue-400" />
</div>
<div className="flex-1 min-w-0">
<h3 className="font-semibold text-foreground mb-1">{item.label}</h3>
<p className="text-sm text-muted-foreground">{item.description}</p>
</div>
</div>
</button>
))}
</div>
)}
{mobileView === 'general' && <GeneralSettings />}
{mobileView === 'shortcuts' && <KeyboardShortcuts />}
{mobileView === 'opencode' && <OpenCodeConfigManager />}
{mobileView === 'providers' && <ProviderSettings />}
</div>
</div>
</DialogContent>
</Dialog>
)
}
+59
View File
@@ -0,0 +1,59 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border p-4 [&>svg~*]:pl-7 [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground",
{
variants: {
variant: {
default: "bg-background text-foreground",
destructive:
"border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
},
},
defaultVariants: {
variant: "default",
},
}
)
const Alert = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof alertVariants>
>(({ className, variant, ...props }, ref) => (
<div
ref={ref}
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
))
Alert.displayName = "Alert"
const AlertTitle = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLHeadingElement>
>(({ className, ...props }, ref) => (
<h5
ref={ref}
className={cn("mb-1 font-medium leading-none tracking-tight", className)}
{...props}
/>
))
AlertTitle.displayName = "AlertTitle"
const AlertDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm [&_p]:leading-relaxed", className)}
{...props}
/>
))
AlertDescription.displayName = "AlertDescription"
export { Alert, AlertTitle, AlertDescription }
@@ -0,0 +1,20 @@
import { useNavigate } from "react-router-dom";
import { ArrowLeft } from "lucide-react";
interface BackButtonProps {
to?: string;
className?: string;
}
export function BackButton({ to = "/", className = "" }: BackButtonProps) {
const navigate = useNavigate();
return (
<button
onClick={() => navigate(to)}
className={`text-zinc-400 hover:text-zinc-100 transition-all duration-200 hover:scale-105 text-sm md:text-md border border-zinc-700 rounded-md px-2 py-1 hover ${className}`}
>
<ArrowLeft className="w-4 h-4" />
</button>
);
}
+36
View File
@@ -0,0 +1,36 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
{
variants: {
variant: {
default:
"border-transparent bg-primary text-primary-foreground hover:bg-primary/80",
secondary:
"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
destructive:
"border-transparent bg-destructive text-destructive-foreground hover:bg-destructive/80",
outline: "text-foreground",
},
},
defaultVariants: {
variant: "default",
},
}
)
export interface BadgeProps
extends React.HTMLAttributes<HTMLDivElement>,
VariantProps<typeof badgeVariants> {}
function Badge({ className, variant, ...props }: BadgeProps) {
return (
<div className={cn(badgeVariants({ variant }), className)} {...props} />
)
}
export { Badge, badgeVariants }
+60
View File
@@ -0,0 +1,60 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant,
size,
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot : "button"
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }
+79
View File
@@ -0,0 +1,79 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Card = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"rounded-lg border bg-card text-card-foreground shadow-sm",
className
)}
{...props}
/>
))
Card.displayName = "Card"
const CardHeader = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex flex-col space-y-1.5 p-6", className)}
{...props}
/>
))
CardHeader.displayName = "CardHeader"
const CardTitle = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn(
"text-2xl font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
CardTitle.displayName = "CardTitle"
const CardDescription = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
CardDescription.displayName = "CardDescription"
const CardContent = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"
const CardFooter = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("flex items-center p-6 pt-0", className)}
{...props}
/>
))
CardFooter.displayName = "CardFooter"
export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
@@ -0,0 +1,63 @@
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Alert, AlertDescription } from '@/components/ui/alert'
import { AlertTriangle } from 'lucide-react'
interface DeleteDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
title: string
description: string
itemName?: string
isDeleting?: boolean
}
export function DeleteDialog({
open,
onOpenChange,
onConfirm,
onCancel,
title,
description,
itemName,
isDeleting = false
}: DeleteDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className='max-w-[90%] sm:max-w-sm '>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
<DialogDescription>
{description}
</DialogDescription>
</DialogHeader>
{itemName && (
<Alert>
<AlertTriangle className="h-4 w-4" />
<AlertDescription>
This will permanently delete "{itemName}". This action cannot be undone.
</AlertDescription>
</Alert>
)}
<DialogFooter className='gap-2'>
<Button variant="outline" onClick={onCancel} disabled={isDeleting}>
Cancel
</Button>
<Button
variant="destructive"
onClick={onConfirm}
disabled={isDeleting}
className="bg-red-600 hover:bg-red-700 text-white font-semibold border-red-600"
>
{isDeleting && 'Deleting...'}
{!isDeleting && (title.includes('Configuration') ? 'Delete Configuration' : 'Delete')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+120
View File
@@ -0,0 +1,120 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"
import { cn } from "@/lib/utils"
const Dialog = DialogPrimitive.Root
const DialogTrigger = DialogPrimitive.Trigger
const DialogPortal = DialogPrimitive.Portal
const DialogClose = DialogPrimitive.Close
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-[90%] max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg [&.w-screen]:left-0 [&.w-screen]:top-0 [&.w-screen]:translate-x-0 [&.w-screen]:translate-y-0",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName
const DialogHeader = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col space-y-1.5 text-center sm:text-left",
className
)}
{...props}
/>
)
DialogHeader.displayName = "DialogHeader"
const DialogFooter = ({
className,
...props
}: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn(
"flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
className
)}
{...props}
/>
)
DialogFooter.displayName = "DialogFooter"
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn(
"text-lg font-semibold leading-none tracking-tight",
className
)}
{...props}
/>
))
DialogTitle.displayName = DialogPrimitive.Title.displayName
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
))
DialogDescription.displayName = DialogPrimitive.Description.displayName
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogClose,
DialogTrigger,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
}
@@ -0,0 +1,195 @@
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { cn } from "@/lib/utils"
const DropdownMenu = DropdownMenuPrimitive.Root
const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
const DropdownMenuGroup = DropdownMenuPrimitive.Group
const DropdownMenuPortal = DropdownMenuPrimitive.Portal
const DropdownMenuSub = DropdownMenuPrimitive.Sub
const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
const DropdownMenuSubTrigger = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}
>(({ className, inset, children, ...props }, ref) => (
<DropdownMenuPrimitive.SubTrigger
ref={ref}
className={cn(
"flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-[#1a1a1a] data-[state=open]:bg-[#1a1a1a]",
inset && "pl-8",
className
)}
{...props}
>
{children}
</DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
DropdownMenuPrimitive.SubTrigger.displayName
const DropdownMenuSubContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.SubContent
ref={ref}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border border-[#262626] bg-[#141414] p-1 text-white shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
))
DropdownMenuSubContent.displayName =
DropdownMenuPrimitive.SubContent.displayName
const DropdownMenuContent = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
ref={ref}
sideOffset={sideOffset}
className={cn(
"z-50 min-w-[8rem] overflow-hidden rounded-md border border-[#262626] bg-[#141414] p-1 text-white shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
const DropdownMenuItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Item
ref={ref}
className={cn(
"relative flex cursor-pointer select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-[#1a1a1a] focus:text-white data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
const DropdownMenuCheckboxItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
<DropdownMenuPrimitive.CheckboxItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-[#1a1a1a] focus:text-white data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
checked={checked}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<span className="h-4 w-4">✓</span>
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
DropdownMenuPrimitive.CheckboxItem.displayName
const DropdownMenuRadioItem = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
<DropdownMenuPrimitive.RadioItem
ref={ref}
className={cn(
"relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-[#1a1a1a] focus:text-white data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<span className="h-2 w-2 rounded-full bg-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
const DropdownMenuLabel = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}
>(({ className, inset, ...props }, ref) => (
<DropdownMenuPrimitive.Label
ref={ref}
className={cn(
"px-2 py-1.5 text-sm font-semibold text-gray-400",
inset && "pl-8",
className
)}
{...props}
/>
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
const DropdownMenuSeparator = React.forwardRef<
React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
<DropdownMenuPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-[#262626]", className)}
{...props}
/>
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
const DropdownMenuShortcut = ({
className,
...props
}: React.HTMLAttributes<HTMLSpanElement>) => {
return (
<span
className={cn("ml-auto text-xs tracking-widest text-gray-500", className)}
{...props}
/>
)
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
export {
DropdownMenu,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuGroup,
DropdownMenuPortal,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuRadioGroup,
}
+178
View File
@@ -0,0 +1,178 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue | null>(null)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
if (!itemContext) {
throw new Error("useFormField should be used within <FormItem>")
}
const fieldState = getFieldState(fieldContext.name, formState)
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue | null>(null)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-sm font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import { cn } from "@/lib/utils"
const Input = React.forwardRef<HTMLInputElement, React.ComponentProps<"input">>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Input.displayName = "Input"
export { Input }
+22
View File
@@ -0,0 +1,22 @@
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }
+160
View File
@@ -0,0 +1,160 @@
"use client"
import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"
import { cn } from "@/lib/utils"
const Select = SelectPrimitive.Root
const SelectGroup = SelectPrimitive.Group
const SelectValue = SelectPrimitive.Value
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-[16px] ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1 md:text-sm",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-[--radix-select-content-available-height] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border border-border bg-popover text-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-select-content-transform-origin]",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
{...props}
/>
))
SelectLabel.displayName = SelectPrimitive.Label.displayName
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 text-foreground",
className
)}
{...props}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-muted", className)}
{...props}
/>
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
}
+27
View File
@@ -0,0 +1,27 @@
import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"
import { cn } from "@/lib/utils"
const Switch = React.forwardRef<
React.ElementRef<typeof SwitchPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
<SwitchPrimitives.Root
className={cn(
"peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
className
)}
{...props}
ref={ref}
>
<SwitchPrimitives.Thumb
className={cn(
"pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName
export { Switch }
+55
View File
@@ -0,0 +1,55 @@
"use client"
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"
import { cn } from "@/lib/utils"
const Tabs = TabsPrimitive.Root
const TabsList = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.List>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
<TabsPrimitive.List
ref={ref}
className={cn(
"inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",
className
)}
{...props}
/>
))
TabsList.displayName = TabsPrimitive.List.displayName
const TabsTrigger = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Trigger
ref={ref}
className={cn(
"inline-flex items-center justify-center whitespace-nowrap rounded-sm px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow-sm",
className
)}
{...props}
/>
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
const TabsContent = React.forwardRef<
React.ElementRef<typeof TabsPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
<TabsPrimitive.Content
ref={ref}
className={cn(
"mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
className
)}
{...props}
/>
))
TabsContent.displayName = TabsPrimitive.Content.displayName
export { Tabs, TabsList, TabsTrigger, TabsContent }
+23
View File
@@ -0,0 +1,23 @@
import * as React from "react"
import { cn } from "@/lib/utils"
type TextareaProps = React.TextareaHTMLAttributes<HTMLTextAreaElement>
const Textarea = React.forwardRef<HTMLTextAreaElement, TextareaProps>(
({ className, ...props }, ref) => {
return (
<textarea
className={cn(
"flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-[16px] placeholder:text-muted-foreground focus-visible:outline-none focus-visible:border-primary disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
ref={ref}
{...props}
/>
)
}
)
Textarea.displayName = "Textarea"
export { Textarea }