mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(settings): harden config directory replace and consolidate upload plumbing
Validate the config before any filesystem work and persist the default row only after the directory swap succeeds; reject oversize uploads before buffering and stream parts to staging; re-ensure AGENTS.md after a replace. Consolidate the upload contract in shared, unify the default-config upsert, single-own the browser directory-upload and restart state, and drop dead code.
This commit is contained in:
1 parent
b1bccb3dd5
commit
39d2b98370
36 files changed
+1098
-510
No files matched your search
@@ -14,7 +14,7 @@ import type {
|
||||
InstallSkillFromGithubRequest,
|
||||
InstallSkillResponse,
|
||||
OpenCodeDirectoryFileInfo,
|
||||
ReplaceOpenCodeConfigDirectoryResponse,
|
||||
ReplaceOpenCodeConfigDirectoryResult,
|
||||
} from './types/settings'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { fetchWrapper, FetchError } from './fetchWrapper'
|
||||
@@ -385,7 +385,7 @@ export const settingsApi = {
|
||||
|
||||
replaceOpenCodeConfigDirectory: async (
|
||||
items: DirectoryUploadItem[],
|
||||
): Promise<ReplaceOpenCodeConfigDirectoryResponse> => {
|
||||
): Promise<ReplaceOpenCodeConfigDirectoryResult> => {
|
||||
const formData = new FormData()
|
||||
appendUploadItemsWithManifest(formData, items)
|
||||
return fetchWrapper(`${API_BASE_URL}/api/settings/opencode-config-directory/replace`, {
|
||||
|
||||
@@ -18,9 +18,9 @@ import {
|
||||
type InstallSkillFromGithubRequest,
|
||||
type InstallSkillResponse,
|
||||
} from '@opencode-manager/shared'
|
||||
import type { NotificationPreferences } from '@opencode-manager/shared/types'
|
||||
import type { NotificationPreferences, ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse }
|
||||
export type { TTSConfig, STTConfig, OpenCodeConfigContent, ModelConfig, ProviderConfig, NotificationPreferences, SkillFileInfo, CreateSkillRequest, UpdateSkillRequest, SkillScope, InstallSkillFromGithubRequest, InstallSkillResponse, ReplaceOpenCodeConfigDirectoryResult }
|
||||
export { DEFAULT_TTS_CONFIG, DEFAULT_STT_CONFIG, DEFAULT_KEYBOARD_SHORTCUTS, DEFAULT_USER_PREFERENCES, DEFAULT_LEADER_KEY, BLOCKED_SERVER_ENV_KEYS, DEFAULT_SERVER_ENV_VARS }
|
||||
|
||||
export interface CustomCommand {
|
||||
@@ -147,13 +147,3 @@ export interface OpenCodeDirectoryFileInfo {
|
||||
name: string
|
||||
relativePath: string
|
||||
}
|
||||
|
||||
export interface ReplaceOpenCodeConfigDirectoryResponse {
|
||||
configDirectory: string
|
||||
configSourceFilename: string
|
||||
filesInstalled: string[]
|
||||
skippedPaths: string[]
|
||||
preservedEntries: string[]
|
||||
executablesRestored: string[]
|
||||
restartRequired: boolean
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { getFileApiUrl, useFile } from '@/api/files'
|
||||
import { getUploadItemsFromDataTransfer, getUploadItemsFromFileList, type DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
import { useDirectoryDropZone, getUploadItemsFromFileList, type DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
|
||||
export interface FileBrowserHandle {
|
||||
goBack: () => void
|
||||
@@ -54,11 +54,9 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct
|
||||
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 [uploadProgress, setUploadProgress] = useState<UploadProgress | null>(null)
|
||||
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const uploadCancelledRef = useRef(false)
|
||||
const isMobile = useMobile()
|
||||
|
||||
@@ -273,6 +271,10 @@ useEffect(() => {
|
||||
await handleUploadItems(items)
|
||||
}, [handleUploadItems])
|
||||
|
||||
const { dropZoneRef, isDragging, dropHandlers } = useDirectoryDropZone({
|
||||
onItems: handleUploadItems,
|
||||
})
|
||||
|
||||
const cancelUpload = useCallback(() => {
|
||||
uploadCancelledRef.current = true
|
||||
}, [])
|
||||
@@ -330,36 +332,6 @@ useEffect(() => {
|
||||
}
|
||||
}, [currentPath, loadFiles])
|
||||
|
||||
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 items = await getUploadItemsFromDataTransfer(e.dataTransfer)
|
||||
if (items.length > 0) {
|
||||
await handleUploadItems(items)
|
||||
}
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
loadFiles(basePath)
|
||||
}, [basePath, loadFiles])
|
||||
@@ -476,10 +448,7 @@ useEffect(() => {
|
||||
<div
|
||||
className="h-full flex flex-col bg-background"
|
||||
ref={dropZoneRef}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop}
|
||||
{...dropHandlers}
|
||||
>
|
||||
{isDragging && (
|
||||
<div className="absolute inset-0 z-50 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center">
|
||||
@@ -569,10 +538,7 @@ useEffect(() => {
|
||||
<div
|
||||
className="h-full flex flex-col"
|
||||
ref={dropZoneRef}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDragOver={handleDragOver}
|
||||
onDrop={handleDrop}
|
||||
{...dropHandlers}
|
||||
>
|
||||
<Card className="flex-1 relative">
|
||||
{isDragging && (
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { FileInfo } from '@/types/files'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
|
||||
import { MarkdownRenderer } from './MarkdownRenderer'
|
||||
import { formatBytes } from '@/lib/utils'
|
||||
|
||||
|
||||
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
|
||||
@@ -81,14 +82,6 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
}
|
||||
}, [initialLineNumber, shouldVirtualize, file.content])
|
||||
|
||||
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()
|
||||
}
|
||||
@@ -369,7 +362,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
</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="truncate flex-shrink-0">{formatBytes(file.size)}</span>
|
||||
<span className="hidden sm:inline truncate flex-shrink-0">{formatDate(file.lastModified)}</span>
|
||||
{shouldVirtualize && (
|
||||
<span className="text-xs text-blue-500 flex-shrink-0">Virtualized</span>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { FILE_LIMITS } from '@/config'
|
||||
import { OpenCodeConfigDirectoryUpload } from './OpenCodeConfigDirectoryUpload'
|
||||
import type { DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResponse } from '@/api/types/settings'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
|
||||
const {
|
||||
mockReplaceOpenCodeConfigDirectory,
|
||||
@@ -43,18 +43,34 @@ vi.mock('@/lib/directoryUpload', () => ({
|
||||
DIRECTORY_INPUT_PROPS: { webkitdirectory: '', directory: '' },
|
||||
getUploadItemsFromDataTransfer: mockGetUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList: mockGetUploadItemsFromFileList,
|
||||
openPicker: vi.fn(),
|
||||
readUploadItemsFromInput: () => mockGetUploadItemsFromFileList(),
|
||||
useDirectoryDropZone: (options: {
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean
|
||||
onItems: (items: DirectoryUploadItem[]) => void | Promise<void>
|
||||
}) => ({
|
||||
dropZoneRef: { current: null },
|
||||
isDragging: false,
|
||||
dropHandlers: {
|
||||
onDragEnter: vi.fn(),
|
||||
onDragOver: vi.fn(),
|
||||
onDragLeave: vi.fn(),
|
||||
onDrop: async (e: React.DragEvent) => {
|
||||
const items = await mockGetUploadItemsFromDataTransfer(e.dataTransfer)
|
||||
await options.onItems(items)
|
||||
},
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
const IMPORT_STATUS = { workspaceConfigDirectory: '/workspace/.config/opencode' }
|
||||
|
||||
const RESULT: ReplaceOpenCodeConfigDirectoryResponse = {
|
||||
configDirectory: '/workspace/.config/opencode',
|
||||
const RESULT: ReplaceOpenCodeConfigDirectoryResult = {
|
||||
configSourceFilename: 'opencode.jsonc',
|
||||
filesInstalled: ['opencode.json', 'skills/x/SKILL.md', 'plugin/p.js'],
|
||||
skippedPaths: ['node_modules/pkg/index.js'],
|
||||
preservedEntries: ['node_modules'],
|
||||
executablesRestored: ['scripts/run.sh'],
|
||||
restartRequired: true,
|
||||
}
|
||||
|
||||
function makeItem(relativePath: string, size = 10): DirectoryUploadItem {
|
||||
@@ -62,11 +78,11 @@ function makeItem(relativePath: string, size = 10): DirectoryUploadItem {
|
||||
return { file: new File([new Uint8Array(size)], name), relativePath }
|
||||
}
|
||||
|
||||
function renderComponent() {
|
||||
function renderComponent(props?: { onReplaced?: () => void }) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<OpenCodeConfigDirectoryUpload />
|
||||
<OpenCodeConfigDirectoryUpload {...props} />
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
}
|
||||
@@ -96,7 +112,7 @@ describe('OpenCodeConfigDirectoryUpload', () => {
|
||||
await dropItems(items)
|
||||
|
||||
expect(screen.getByText('/workspace/.config/opencode')).toBeInTheDocument()
|
||||
expect(screen.getByText('3 files (30 B)')).toBeInTheDocument()
|
||||
expect(screen.getByText('3 files (30 Bytes)')).toBeInTheDocument()
|
||||
expect(screen.getByText('opencode.jsonc')).toBeInTheDocument()
|
||||
expect(screen.getByText('plugin')).toBeInTheDocument()
|
||||
expect(screen.getByText('skills')).toBeInTheDocument()
|
||||
@@ -204,7 +220,7 @@ describe('OpenCodeConfigDirectoryUpload', () => {
|
||||
fireEvent.change(input, { target: { files: [] } })
|
||||
|
||||
await screen.findByText('Replace OpenCode Config Directory?')
|
||||
expect(screen.getByText('2 files (20 B)')).toBeInTheDocument()
|
||||
expect(screen.getByText('2 files (20 Bytes)')).toBeInTheDocument()
|
||||
expect(screen.getByText('opencode.jsonc')).toBeInTheDocument()
|
||||
expect(screen.getByText('skills')).toBeInTheDocument()
|
||||
expect(screen.queryByText('node_modules')).not.toBeInTheDocument()
|
||||
@@ -231,6 +247,18 @@ describe('OpenCodeConfigDirectoryUpload', () => {
|
||||
expect(screen.queryByText('Replace OpenCode Config Directory?')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('invokes onReplaced after a successful replace so the parent refetches configs', async () => {
|
||||
const user = userEvent.setup()
|
||||
const onReplaced = vi.fn()
|
||||
renderComponent({ onReplaced })
|
||||
|
||||
await dropItems([makeItem('opencode/opencode.jsonc')])
|
||||
|
||||
await user.click(screen.getByRole('button', { name: 'Replace and Restart' }))
|
||||
|
||||
await waitFor(() => expect(onReplaced).toHaveBeenCalledTimes(1))
|
||||
})
|
||||
|
||||
it('surfaces a failed replace through an error toast', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockReplaceOpenCodeConfigDirectory.mockRejectedValue(new Error('boom'))
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { FolderUp, UploadCloud, Loader2 } from 'lucide-react'
|
||||
import {
|
||||
EXCLUDED_OPENCODE_CONFIG_UPLOAD_FILENAMES,
|
||||
EXCLUDED_OPENCODE_CONFIG_UPLOAD_SEGMENTS,
|
||||
MAX_OPENCODE_CONFIG_DIRECTORY_FILES,
|
||||
OPENCODE_CONFIG_UPLOAD_ERRORS,
|
||||
PRESERVED_OPENCODE_CONFIG_ENTRIES,
|
||||
getCommonUploadRootDirectory,
|
||||
isExcludedOpenCodeConfigUploadPath,
|
||||
isOpenCodeConfigUploadPath,
|
||||
stripUploadRootDirectory,
|
||||
} from '@opencode-manager/shared/utils'
|
||||
import { FILE_LIMITS } from '@/config'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { cn, formatBytes } from '@/lib/utils'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog'
|
||||
@@ -17,33 +23,31 @@ import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { getOpenCodeApiErrorMessage } from '@/lib/opencode-errors'
|
||||
import {
|
||||
DIRECTORY_INPUT_PROPS,
|
||||
getUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList,
|
||||
openPicker,
|
||||
readUploadItemsFromInput,
|
||||
useDirectoryDropZone,
|
||||
type DirectoryUploadItem,
|
||||
} from '@/lib/directoryUpload'
|
||||
import type { OpenCodeImportStatus, ReplaceOpenCodeConfigDirectoryResponse } from '@/api/types/settings'
|
||||
import type { OpenCodeImportStatus } from '@/api/types/settings'
|
||||
import type { ReplaceOpenCodeConfigDirectoryResult } from '@opencode-manager/shared/types'
|
||||
|
||||
const MAX_CONFIG_DIRECTORY_FILES = 5000
|
||||
const MAX_CONFIG_UPLOAD_BYTES = FILE_LIMITS.MAX_UPLOAD_SIZE_BYTES
|
||||
const EXCLUDED_ENTRIES_DISPLAY = [
|
||||
...EXCLUDED_OPENCODE_CONFIG_UPLOAD_SEGMENTS,
|
||||
...EXCLUDED_OPENCODE_CONFIG_UPLOAD_FILENAMES,
|
||||
].join(', ')
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
|
||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
interface OpenCodeConfigDirectoryUploadProps {
|
||||
onReplaced?: () => void
|
||||
}
|
||||
|
||||
function stripCommonRoot(relativePath: string, commonRoot: string | null): string {
|
||||
return commonRoot ? relativePath.slice(commonRoot.length + 1) : relativePath
|
||||
}
|
||||
|
||||
export function OpenCodeConfigDirectoryUpload() {
|
||||
export function OpenCodeConfigDirectoryUpload({ onReplaced }: OpenCodeConfigDirectoryUploadProps) {
|
||||
const queryClient = useQueryClient()
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [stagedItems, setStagedItems] = useState<DirectoryUploadItem[] | null>(null)
|
||||
const [isConfirmOpen, setIsConfirmOpen] = useState(false)
|
||||
const [lastResult, setLastResult] = useState<ReplaceOpenCodeConfigDirectoryResponse | null>(null)
|
||||
const [lastResult, setLastResult] = useState<ReplaceOpenCodeConfigDirectoryResult | null>(null)
|
||||
const deferredConfigInvalidationRef = useRef(false)
|
||||
|
||||
const { data: importStatus } = useQuery<OpenCodeImportStatus>({
|
||||
queryKey: ['opencode-import-status'],
|
||||
@@ -54,8 +58,10 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
const replaceMutation = useMutation({
|
||||
mutationFn: (items: DirectoryUploadItem[]) => settingsApi.replaceOpenCodeConfigDirectory(items),
|
||||
onSuccess: (result) => {
|
||||
invalidateConfigCaches(queryClient)
|
||||
onReplaced?.()
|
||||
deferredConfigInvalidationRef.current = true
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-import-status'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['health'] })
|
||||
setLastResult(result)
|
||||
setStagedItems(null)
|
||||
setIsConfirmOpen(false)
|
||||
@@ -68,6 +74,18 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
const unsubscribe = queryClient.getQueryCache().subscribe((event) => {
|
||||
if (event.type !== 'updated') return
|
||||
if (event.query.queryKey[0] !== 'health') return
|
||||
const health = queryClient.getQueryData<{ opencode?: 'healthy' | 'unhealthy' }>(['health'])
|
||||
if (!deferredConfigInvalidationRef.current || health?.opencode !== 'healthy') return
|
||||
deferredConfigInvalidationRef.current = false
|
||||
invalidateConfigCaches(queryClient)
|
||||
})
|
||||
return unsubscribe
|
||||
}, [queryClient])
|
||||
|
||||
const stageItems = (items: DirectoryUploadItem[]) => {
|
||||
if (items.length === 0) {
|
||||
showToast.error('No files were provided. Drop a folder containing opencode.json or opencode.jsonc at its root.')
|
||||
@@ -76,21 +94,21 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
|
||||
const commonRoot = getCommonUploadRootDirectory(items.map((item) => item.relativePath))
|
||||
const hasRootConfig = items.some((item) =>
|
||||
isOpenCodeConfigUploadPath(stripCommonRoot(item.relativePath, commonRoot)),
|
||||
isOpenCodeConfigUploadPath(stripUploadRootDirectory(item.relativePath, commonRoot)),
|
||||
)
|
||||
if (!hasRootConfig) {
|
||||
showToast.error('Uploaded directory must contain opencode.json or opencode.jsonc at its root')
|
||||
showToast.error(OPENCODE_CONFIG_UPLOAD_ERRORS.MISSING_ROOT_CONFIG)
|
||||
return
|
||||
}
|
||||
|
||||
if (items.length > MAX_CONFIG_DIRECTORY_FILES) {
|
||||
showToast.error(`Uploaded config directory contains too many files (max ${MAX_CONFIG_DIRECTORY_FILES})`)
|
||||
if (items.length > MAX_OPENCODE_CONFIG_DIRECTORY_FILES) {
|
||||
showToast.error(OPENCODE_CONFIG_UPLOAD_ERRORS.TOO_MANY_FILES)
|
||||
return
|
||||
}
|
||||
|
||||
const totalBytes = items.reduce((sum, item) => sum + item.file.size, 0)
|
||||
if (totalBytes > MAX_CONFIG_UPLOAD_BYTES) {
|
||||
showToast.error('Uploaded config directory files exceed maximum upload size')
|
||||
showToast.error(OPENCODE_CONFIG_UPLOAD_ERRORS.EXCEEDS_MAX_UPLOAD_SIZE)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -99,56 +117,35 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
setIsConfirmOpen(true)
|
||||
}
|
||||
|
||||
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 items = await getUploadItemsFromDataTransfer(e.dataTransfer, {
|
||||
shouldSkip: (relativePath) => isExcludedOpenCodeConfigUploadPath(relativePath),
|
||||
})
|
||||
stageItems(items)
|
||||
}
|
||||
|
||||
const openFolderPicker = () => {
|
||||
requestAnimationFrame(() => folderInputRef.current?.click())
|
||||
}
|
||||
const { dropZoneRef, isDragging, dropHandlers } = useDirectoryDropZone({
|
||||
shouldSkip: (relativePath) => isExcludedOpenCodeConfigUploadPath(relativePath),
|
||||
onItems: stageItems,
|
||||
})
|
||||
|
||||
const handleFolderChange = (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const fileList = event.target.files
|
||||
const items = fileList
|
||||
? getUploadItemsFromFileList(fileList).filter((item) => !isExcludedOpenCodeConfigUploadPath(item.relativePath))
|
||||
: []
|
||||
event.target.value = ''
|
||||
const items = readUploadItemsFromInput(event).filter((item) =>
|
||||
!isExcludedOpenCodeConfigUploadPath(item.relativePath),
|
||||
)
|
||||
stageItems(items)
|
||||
}
|
||||
|
||||
const stagedRoot = stagedItems ? getCommonUploadRootDirectory(stagedItems.map((item) => item.relativePath)) : null
|
||||
const topLevelEntries = stagedItems
|
||||
? Array.from(new Set(
|
||||
stagedItems.map((item) => stripCommonRoot(item.relativePath, stagedRoot).split('/')[0]),
|
||||
)).sort()
|
||||
: []
|
||||
const stagedTotalBytes = stagedItems?.reduce((sum, item) => sum + item.file.size, 0) ?? 0
|
||||
const stagedRoot = useMemo(
|
||||
() => (stagedItems ? getCommonUploadRootDirectory(stagedItems.map((item) => item.relativePath)) : null),
|
||||
[stagedItems],
|
||||
)
|
||||
const topLevelEntries = useMemo(
|
||||
() =>
|
||||
stagedItems
|
||||
? Array.from(new Set(
|
||||
stagedItems.map((item) => stripUploadRootDirectory(item.relativePath, stagedRoot).split('/')[0]),
|
||||
)).sort()
|
||||
: [],
|
||||
[stagedItems, stagedRoot],
|
||||
)
|
||||
const stagedTotalBytes = useMemo(
|
||||
() => stagedItems?.reduce((sum, item) => sum + item.file.size, 0) ?? 0,
|
||||
[stagedItems],
|
||||
)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
@@ -164,10 +161,7 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
<div
|
||||
ref={dropZoneRef}
|
||||
data-testid="config-directory-drop-zone"
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
{...dropHandlers}
|
||||
className={cn(
|
||||
'flex flex-col items-center justify-center gap-2 rounded-lg border-2 border-dashed p-6 text-center',
|
||||
isDragging ? 'border-primary bg-primary/5' : 'border-border',
|
||||
@@ -176,14 +170,14 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
<UploadCloud className="h-8 w-8 text-muted-foreground" />
|
||||
<p className="text-sm font-medium">Drag and drop your OpenCode config folder here</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The folder must contain opencode.json or opencode.jsonc at its root. node_modules, .git and .DS_Store
|
||||
entries are excluded automatically.
|
||||
The folder must contain opencode.json or opencode.jsonc at its root. {EXCLUDED_ENTRIES_DISPLAY} entries are
|
||||
excluded automatically.
|
||||
</p>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={openFolderPicker}
|
||||
onClick={() => openPicker(folderInputRef)}
|
||||
disabled={replaceMutation.isPending}
|
||||
>
|
||||
{replaceMutation.isPending ? (
|
||||
@@ -264,7 +258,7 @@ export function OpenCodeConfigDirectoryUpload() {
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
warning="Every file currently in the destination directory except node_modules will be deleted."
|
||||
warning={`Every file currently in the destination directory except ${PRESERVED_OPENCODE_CONFIG_ENTRIES.join(', ')} will be deleted.`}
|
||||
confirmLabel="Replace and Restart"
|
||||
pendingLabel="Replacing..."
|
||||
isPending={replaceMutation.isPending}
|
||||
|
||||
@@ -4,6 +4,7 @@ import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeConfigManager } from './OpenCodeConfigManager'
|
||||
import type { OpenCodeConfig } from '@/api/types/settings'
|
||||
import type { DirectoryUploadItem } from '@/lib/directoryUpload'
|
||||
|
||||
const {
|
||||
mockGetOpenCodeConfigs,
|
||||
@@ -11,12 +12,16 @@ const {
|
||||
mockGetOpenCodeImportStatus,
|
||||
mockListManagedSkills,
|
||||
mockListOpenCodeDirectoryFiles,
|
||||
mockReplaceOpenCodeConfigDirectory,
|
||||
mockGetUploadItemsFromDataTransfer,
|
||||
} = vi.hoisted(() => ({
|
||||
mockGetOpenCodeConfigs: vi.fn(),
|
||||
mockUpdateOpenCodeConfig: vi.fn(),
|
||||
mockGetOpenCodeImportStatus: vi.fn(),
|
||||
mockListManagedSkills: vi.fn(),
|
||||
mockListOpenCodeDirectoryFiles: vi.fn(),
|
||||
mockReplaceOpenCodeConfigDirectory: vi.fn(),
|
||||
mockGetUploadItemsFromDataTransfer: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
@@ -31,9 +36,34 @@ vi.mock('@/api/settings', () => ({
|
||||
listManagedSkills: mockListManagedSkills,
|
||||
listOpenCodeDirectoryFiles: mockListOpenCodeDirectoryFiles,
|
||||
syncOpenCodeImport: vi.fn(),
|
||||
replaceOpenCodeConfigDirectory: mockReplaceOpenCodeConfigDirectory,
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/directoryUpload', () => ({
|
||||
DIRECTORY_INPUT_PROPS: { webkitdirectory: '', directory: '' },
|
||||
getUploadItemsFromDataTransfer: mockGetUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList: vi.fn(),
|
||||
openPicker: vi.fn(),
|
||||
readUploadItemsFromInput: vi.fn(),
|
||||
useDirectoryDropZone: (options: {
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean
|
||||
onItems: (items: DirectoryUploadItem[]) => void | Promise<void>
|
||||
}) => ({
|
||||
dropZoneRef: { current: null },
|
||||
isDragging: false,
|
||||
dropHandlers: {
|
||||
onDragEnter: vi.fn(),
|
||||
onDragOver: vi.fn(),
|
||||
onDragLeave: vi.fn(),
|
||||
onDrop: async (e: React.DragEvent) => {
|
||||
const items = await mockGetUploadItemsFromDataTransfer(e.dataTransfer)
|
||||
await options.onItems(items)
|
||||
},
|
||||
},
|
||||
}),
|
||||
}))
|
||||
|
||||
const defaultConfig: OpenCodeConfig = {
|
||||
id: 1,
|
||||
name: 'default',
|
||||
@@ -183,4 +213,30 @@ describe('OpenCodeConfigManager', () => {
|
||||
resolveRefresh()
|
||||
await waitFor(() => expect(screen.queryByText('Edit Config: default')).not.toBeInTheDocument())
|
||||
})
|
||||
|
||||
it('refetches the imperative config list after a config-directory replace', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockReplaceOpenCodeConfigDirectory.mockResolvedValue({
|
||||
configSourceFilename: 'opencode.json',
|
||||
filesInstalled: ['opencode.json'],
|
||||
skippedPaths: [],
|
||||
preservedEntries: [],
|
||||
executablesRestored: [],
|
||||
})
|
||||
mockGetUploadItemsFromDataTransfer.mockResolvedValue([
|
||||
{ file: new File(['{}'], 'opencode.json'), relativePath: 'opencode/opencode.json' },
|
||||
])
|
||||
|
||||
renderWithQuery(<OpenCodeConfigManager />)
|
||||
|
||||
await screen.findByText('GPT-4o')
|
||||
expect(mockGetOpenCodeConfigs).toHaveBeenCalledTimes(1)
|
||||
|
||||
fireEvent.drop(screen.getByTestId('config-directory-drop-zone'), { dataTransfer: { items: [] } })
|
||||
await screen.findByText('Replace OpenCode Config Directory?')
|
||||
await user.click(screen.getByRole('button', { name: 'Replace and Restart' }))
|
||||
|
||||
await waitFor(() => expect(mockReplaceOpenCodeConfigDirectory).toHaveBeenCalledTimes(1))
|
||||
await waitFor(() => expect(mockGetOpenCodeConfigs).toHaveBeenCalledTimes(2))
|
||||
})
|
||||
})
|
||||
@@ -418,7 +418,7 @@ export function OpenCodeConfigManager() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<OpenCodeConfigDirectoryUpload />
|
||||
<OpenCodeConfigDirectoryUpload onReplaced={() => void fetchConfigs(true)} />
|
||||
|
||||
|
||||
<CreateConfigDialog
|
||||
|
||||
@@ -1,16 +1,11 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { OpenCodeRestartPendingNotice } from './OpenCodeRestartPendingNotice'
|
||||
|
||||
const {
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
healthState: { data: { opencode: 'healthy', opencodeRestartPending: false } as Record<string, unknown> },
|
||||
}))
|
||||
|
||||
@@ -18,107 +13,84 @@ vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: () => healthState,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/toast', () => ({
|
||||
showToast: { success: vi.fn(), error: vi.fn(), info: vi.fn(), loading: vi.fn(), warning: vi.fn(), dismiss: vi.fn() },
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
settingsApi: {
|
||||
restartOpenCodeServer: mockRestartOpenCodeServer,
|
||||
getActiveOpenCodeSessions: mockGetActiveOpenCodeSessions,
|
||||
},
|
||||
}))
|
||||
|
||||
const NOTICE_TEXT = 'Configuration changes are saved but require a server restart to take effect.'
|
||||
|
||||
function renderWithQuery(ui: React.ReactElement) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(ui, {
|
||||
wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>,
|
||||
})
|
||||
interface NoticeProps {
|
||||
hasAutoPromptedRef: { current: boolean }
|
||||
openRestartPrompt: () => Promise<void>
|
||||
requestRestart: () => Promise<void>
|
||||
restartIsPending: boolean
|
||||
}
|
||||
|
||||
function renderNotice(overrides: Partial<NoticeProps> = {}) {
|
||||
const props: NoticeProps = {
|
||||
hasAutoPromptedRef: { current: false },
|
||||
openRestartPrompt: vi.fn().mockResolvedValue(undefined),
|
||||
requestRestart: vi.fn().mockResolvedValue(undefined),
|
||||
restartIsPending: false,
|
||||
...overrides,
|
||||
}
|
||||
const result = render(<OpenCodeRestartPendingNotice {...props} />)
|
||||
return { ...result, props }
|
||||
}
|
||||
|
||||
describe('OpenCodeRestartPendingNotice', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
})
|
||||
|
||||
it('renders nothing when no restart is pending', () => {
|
||||
renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
const { props } = renderNotice()
|
||||
|
||||
expect(screen.queryByText(NOTICE_TEXT)).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: /restart now/i })).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('auto-opens the restart dialog when the pending flag flips to true', async () => {
|
||||
const { rerender } = renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
it('auto-opens the restart prompt when the pending flag flips to true', async () => {
|
||||
const { props, rerender } = renderNotice()
|
||||
expect(props.openRestartPrompt).not.toHaveBeenCalled()
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
rerender(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
expect(await screen.findByText('Restart OpenCode Server?')).toBeInTheDocument()
|
||||
expect(screen.getByText(/2 sessions are currently working/i)).toBeInTheDocument()
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('closes the dialog with "Later" without issuing a restart', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
rerender(<OpenCodeRestartPendingNotice {...props} />)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('restarts exactly once via the notice button plus dialog confirmation', async () => {
|
||||
it('does not re-prompt on re-render while the shared flag stays set', async () => {
|
||||
const { props, rerender } = renderNotice()
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const user = userEvent.setup()
|
||||
renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
rerender(<OpenCodeRestartPendingNotice {...props} />)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /restart now/i }))
|
||||
expect(await screen.findByText('Restart OpenCode Server?')).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(2)
|
||||
rerender(<OpenCodeRestartPendingNotice {...props} />)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /restart now/i }))
|
||||
await waitFor(() => {
|
||||
expect(mockRestartOpenCodeServer).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not re-open a dismissed dialog on re-render while the flag stays true', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const user = userEvent.setup()
|
||||
const { rerender } = renderWithQuery(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
rerender(<OpenCodeRestartPendingNotice />)
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(props.openRestartPrompt).toHaveBeenCalledTimes(1)
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('requests a restart via the notice button', async () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
const { props } = renderNotice()
|
||||
|
||||
expect(screen.getByText(NOTICE_TEXT)).toBeInTheDocument()
|
||||
await userEvent.setup().click(screen.getByRole('button', { name: /restart now/i }))
|
||||
|
||||
expect(props.requestRestart).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('disables the restart button while a restart is in flight', () => {
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
renderNotice({ restartIsPending: true })
|
||||
|
||||
expect(screen.getByRole('button', { name: /restart now/i })).toBeDisabled()
|
||||
})
|
||||
})
|
||||
@@ -1,33 +1,29 @@
|
||||
import { useEffect, useRef } from 'react'
|
||||
import { useEffect, type RefObject } from 'react'
|
||||
import { AlertTriangle, Loader2, RotateCcw } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
|
||||
export function OpenCodeRestartPendingNotice() {
|
||||
interface OpenCodeRestartPendingNoticeProps {
|
||||
hasAutoPromptedRef: RefObject<boolean>
|
||||
openRestartPrompt: () => void
|
||||
requestRestart: () => void
|
||||
restartIsPending: boolean
|
||||
}
|
||||
|
||||
export function OpenCodeRestartPendingNotice({
|
||||
hasAutoPromptedRef,
|
||||
openRestartPrompt,
|
||||
requestRestart,
|
||||
restartIsPending,
|
||||
}: OpenCodeRestartPendingNoticeProps) {
|
||||
const { data: health } = useServerHealth()
|
||||
const {
|
||||
restartServerMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
openRestartPrompt,
|
||||
} = useOpenCodeServerActions()
|
||||
const hasPromptedRef = useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
if (health?.opencodeRestartPending) {
|
||||
if (!hasPromptedRef.current) {
|
||||
hasPromptedRef.current = true
|
||||
void openRestartPrompt()
|
||||
}
|
||||
} else {
|
||||
hasPromptedRef.current = false
|
||||
if (health?.opencodeRestartPending && !hasAutoPromptedRef.current) {
|
||||
hasAutoPromptedRef.current = true
|
||||
void openRestartPrompt()
|
||||
}
|
||||
}, [health?.opencodeRestartPending, openRestartPrompt])
|
||||
}, [health?.opencodeRestartPending, hasAutoPromptedRef, openRestartPrompt])
|
||||
|
||||
if (!health?.opencodeRestartPending) {
|
||||
return null
|
||||
@@ -45,10 +41,10 @@ export function OpenCodeRestartPendingNotice() {
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
disabled={restartIsPending}
|
||||
className="shrink-0"
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
{restartIsPending ? (
|
||||
<Loader2 className="h-3 w-3 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 mr-1" />
|
||||
@@ -56,14 +52,6 @@ export function OpenCodeRestartPendingNotice() {
|
||||
Restart Now
|
||||
</Button>
|
||||
</div>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -3,25 +3,23 @@ import { Button } from '@/components/ui/button'
|
||||
import { Card, CardContent } from '@/components/ui/card'
|
||||
import { Loader2, ArrowUpCircle, RotateCcw, History } from 'lucide-react'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
import { RestartServerDialog } from './RestartServerDialog'
|
||||
|
||||
interface ServerHealthStatusProps {
|
||||
onOpenVersionDialog?: () => void
|
||||
requestRestart: () => void
|
||||
restartIsPending: boolean
|
||||
performUpgrade: () => void
|
||||
upgradeIsPending: boolean
|
||||
}
|
||||
|
||||
export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusProps) {
|
||||
export function ServerHealthStatus({
|
||||
onOpenVersionDialog,
|
||||
requestRestart,
|
||||
restartIsPending,
|
||||
performUpgrade,
|
||||
upgradeIsPending,
|
||||
}: ServerHealthStatusProps) {
|
||||
const { data: health } = useServerHealth()
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
|
||||
if (!health) {
|
||||
return (
|
||||
@@ -68,9 +66,9 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={performUpgrade}
|
||||
disabled={upgradeOpenCodeMutation.isPending}
|
||||
disabled={upgradeIsPending}
|
||||
>
|
||||
{upgradeOpenCodeMutation.isPending ? (
|
||||
{upgradeIsPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<ArrowUpCircle className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
@@ -81,9 +79,9 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={requestRestart}
|
||||
disabled={restartServerMutation.isPending}
|
||||
disabled={restartIsPending}
|
||||
>
|
||||
{restartServerMutation.isPending ? (
|
||||
{restartIsPending ? (
|
||||
<Loader2 className="h-3 w-3 sm:h-4 sm:w-4 mr-1 animate-spin" />
|
||||
) : (
|
||||
<RotateCcw className="h-3 w-3 sm:h-4 sm:w-4 mr-1" />
|
||||
@@ -101,14 +99,6 @@ export function ServerHealthStatus({ onOpenVersionDialog }: ServerHealthStatusPr
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -9,13 +9,15 @@ import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
|
||||
const {
|
||||
mockRestartOpenCodeServer,
|
||||
mockGetActiveOpenCodeSessions,
|
||||
healthState,
|
||||
} = vi.hoisted(() => ({
|
||||
mockRestartOpenCodeServer: vi.fn(),
|
||||
mockGetActiveOpenCodeSessions: vi.fn(),
|
||||
healthState: { data: { opencode: 'healthy', opencodeRestartPending: true } as Record<string, unknown> },
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useServerHealth', () => ({
|
||||
useServerHealth: () => ({ data: { opencode: 'healthy', opencodeRestartPending: true } }),
|
||||
useServerHealth: () => healthState,
|
||||
}))
|
||||
|
||||
vi.mock('@/api/settings', () => ({
|
||||
@@ -92,10 +94,18 @@ vi.mock('@/hooks/useMobile', () => ({
|
||||
describe('SettingsDialog', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
mockRestartOpenCodeServer.mockResolvedValue({ success: true, message: 'ok' })
|
||||
mockGetActiveOpenCodeSessions.mockResolvedValue({ count: 2, sessions: [] })
|
||||
})
|
||||
|
||||
function renderWithSettingsContext(ui: React.ReactElement) {
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
return render(ui, {
|
||||
wrapper: ({ children }) => <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>,
|
||||
})
|
||||
}
|
||||
|
||||
it('resets to menu state when dialog closes and reopens', () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
@@ -114,7 +124,7 @@ describe('SettingsDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
@@ -147,7 +157,7 @@ describe('SettingsDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
@@ -182,10 +192,10 @@ describe('SettingsDialog', () => {
|
||||
)
|
||||
}
|
||||
|
||||
render(
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/?settings=open']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>,
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
@@ -197,7 +207,89 @@ describe('SettingsDialog', () => {
|
||||
expect(screen.getByTestId('settings-open')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('mounts a single restart-pending notice and dialog on the OpenCode tab', async () => {
|
||||
it('mounts a single restart-pending dialog on the OpenCode tab', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const isOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate('?settings=open')}>Open Settings</button>
|
||||
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByText('Open Settings'))
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
expect(screen.getAllByText('Restart OpenCode Server?')).toHaveLength(1)
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(2)
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByText('Restart OpenCode Server?')).toHaveLength(0)
|
||||
})
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(2)
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does not re-open the auto-prompted dialog after Later when switching tabs away and back', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const isOpen = new URLSearchParams(location.search).get('settings') === 'open'
|
||||
|
||||
return (
|
||||
<>
|
||||
<button onClick={() => navigate('?settings=open')}>Open Settings</button>
|
||||
{isOpen && <span data-testid="dialog-open">Dialog Open</span>}
|
||||
<SettingsDialog />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
renderWithSettingsContext(
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
)
|
||||
|
||||
const user = userEvent.setup()
|
||||
await user.click(screen.getByText('Open Settings'))
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByText('Restart OpenCode Server?')).toHaveLength(0)
|
||||
})
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Git' }))
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
expect(screen.queryByText('Restart OpenCode Server?')).not.toBeInTheDocument()
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(2)
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(1)
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('re-prompts when a new pending restart arrives after the previous one cleared', async () => {
|
||||
function TestWrapper() {
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
@@ -214,7 +306,7 @@ describe('SettingsDialog', () => {
|
||||
}
|
||||
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
|
||||
render(
|
||||
const { rerender } = render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
@@ -227,14 +319,30 @@ describe('SettingsDialog', () => {
|
||||
await user.click(screen.getByRole('tab', { name: 'OpenCode' }))
|
||||
|
||||
await screen.findByText('Restart OpenCode Server?')
|
||||
expect(screen.getAllByText('Restart OpenCode Server?')).toHaveLength(1)
|
||||
expect(screen.getAllByText('Configuration changes are saved but require a server restart to take effect.')).toHaveLength(1)
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /later/i }))
|
||||
await waitFor(() => {
|
||||
expect(screen.queryAllByText('Restart OpenCode Server?')).toHaveLength(0)
|
||||
})
|
||||
expect(screen.getByText('Configuration changes are saved but require a server restart to take effect.')).toBeInTheDocument()
|
||||
expect(mockRestartOpenCodeServer).not.toHaveBeenCalled()
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: false }
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
healthState.data = { opencode: 'healthy', opencodeRestartPending: true }
|
||||
rerender(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<MemoryRouter initialEntries={['/']}>
|
||||
<TestWrapper />
|
||||
</MemoryRouter>
|
||||
</QueryClientProvider>
|
||||
)
|
||||
|
||||
expect(await screen.findByText('Restart OpenCode Server?')).toBeInTheDocument()
|
||||
expect(mockGetActiveOpenCodeSessions).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react'
|
||||
import { useState, useEffect, useCallback, useRef } from 'react'
|
||||
import { GeneralSettings } from '@/components/settings/GeneralSettings'
|
||||
import { GitSettings } from '@/components/settings/GitSettings'
|
||||
import { KeyboardShortcuts } from '@/components/settings/KeyboardShortcuts'
|
||||
@@ -6,6 +6,7 @@ import { OpenCodeConfigManager } from '@/components/settings/OpenCodeConfigManag
|
||||
import { OpenCodeRestartPendingNotice } from '@/components/settings/OpenCodeRestartPendingNotice'
|
||||
import { OpenCodeServerAuthSettings } from '@/components/settings/OpenCodeServerAuthSettings'
|
||||
import { ManagerTokenSettings } from '@/components/settings/ManagerTokenSettings'
|
||||
import { RestartServerDialog } from '@/components/settings/RestartServerDialog'
|
||||
import { ServerEnvVarsSettings } from '@/components/settings/ServerEnvVarsSettings'
|
||||
import { ServerHealthStatus } from '@/components/settings/ServerHealthStatus'
|
||||
import { ProviderSettings } from '@/components/settings/ProviderSettings'
|
||||
@@ -18,17 +19,38 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import { Settings2, Keyboard, Code, ChevronLeft, Key, GitBranch, User, Volume2, Bell, X } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { useSettingsDialog } from '@/hooks/useSettingsDialog'
|
||||
import { useServerHealth } from '@/hooks/useServerHealth'
|
||||
import { useOpenCodeServerActions } from '@/hooks/useOpenCodeServerActions'
|
||||
|
||||
type SettingsView = 'menu' | 'general' | 'git' | 'shortcuts' | 'opencode' | 'providers' | 'account' | 'voice' | 'notifications'
|
||||
|
||||
export function SettingsDialog() {
|
||||
const { isOpen, close, activeTab, setActiveTab } = useSettingsDialog()
|
||||
const { data: health } = useServerHealth()
|
||||
const {
|
||||
restartServerMutation,
|
||||
upgradeOpenCodeMutation,
|
||||
confirmOpen,
|
||||
setConfirmOpen,
|
||||
activeSessionCount,
|
||||
requestRestart,
|
||||
confirmRestart,
|
||||
openRestartPrompt,
|
||||
performUpgrade,
|
||||
} = useOpenCodeServerActions()
|
||||
const hasAutoPromptedRef = useRef(false)
|
||||
const [mobileView, setMobileView] = useState<SettingsView>('menu')
|
||||
const [isVersionDialogOpen, setIsVersionDialogOpen] = useState(false)
|
||||
const [sectionHistory, setSectionHistory] = useState<SettingsView[]>([])
|
||||
const [authSectionsOpen, setAuthSectionsOpen] = useState(true)
|
||||
const toggleAuthSections = useCallback(() => setAuthSectionsOpen((open) => !open), [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!health?.opencodeRestartPending) {
|
||||
hasAutoPromptedRef.current = false
|
||||
}
|
||||
}, [health?.opencodeRestartPending])
|
||||
|
||||
const pushSectionHistory = useCallback((view: SettingsView) => {
|
||||
if (view === 'menu') return
|
||||
setSectionHistory((history) => {
|
||||
@@ -119,7 +141,6 @@ export function SettingsDialog() {
|
||||
data-settings-dialog
|
||||
>
|
||||
<DialogTitle className="sr-only">Settings</DialogTitle>
|
||||
{activeTab === 'opencode' && <OpenCodeRestartPendingNotice />}
|
||||
<div className="hidden sm:flex sm:flex-col sm:h-full sm:min-h-0">
|
||||
<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 flex items-center justify-between">
|
||||
<h2 className="text-2xl font-semibold bg-gradient-to-r from-foreground to-muted-foreground bg-clip-text text-transparent">
|
||||
@@ -133,7 +154,15 @@ export function SettingsDialog() {
|
||||
>
|
||||
<X className="w-5 h-5" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{activeTab === 'opencode' && (
|
||||
<OpenCodeRestartPendingNotice
|
||||
hasAutoPromptedRef={hasAutoPromptedRef}
|
||||
openRestartPrompt={openRestartPrompt}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
<Tabs defaultValue="account" value={activeTab} onValueChange={handleTabChange} 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-8 bg-card p-1">
|
||||
@@ -174,7 +203,13 @@ export function SettingsDialog() {
|
||||
<TabsContent key="shortcuts" value="shortcuts" className="mt-0"><KeyboardShortcuts /></TabsContent>
|
||||
<TabsContent key="opencode" value="opencode" className="mt-0">
|
||||
<div className="space-y-6">
|
||||
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
<ServerHealthStatus
|
||||
onOpenVersionDialog={() => setIsVersionDialogOpen(true)}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
performUpgrade={performUpgrade}
|
||||
upgradeIsPending={upgradeOpenCodeMutation.isPending}
|
||||
/>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<OpenCodeServerAuthSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
<ManagerTokenSettings isOpen={authSectionsOpen} onToggle={toggleAuthSections} />
|
||||
@@ -216,6 +251,15 @@ export function SettingsDialog() {
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{mobileView === 'opencode' && (
|
||||
<OpenCodeRestartPendingNotice
|
||||
hasAutoPromptedRef={hasAutoPromptedRef}
|
||||
openRestartPrompt={openRestartPrompt}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div className="flex-1 min-h-0 overflow-y-auto p-3 pb-[calc(env(safe-area-inset-bottom)+1rem)]">
|
||||
{mobileView === 'menu' && (
|
||||
<div className="space-y-3">
|
||||
@@ -247,7 +291,13 @@ export function SettingsDialog() {
|
||||
{mobileView === 'shortcuts' && <div key="shortcuts"><KeyboardShortcuts /></div>}
|
||||
{mobileView === 'opencode' && (
|
||||
<div key="opencode" className="space-y-4">
|
||||
<ServerHealthStatus onOpenVersionDialog={() => setIsVersionDialogOpen(true)} />
|
||||
<ServerHealthStatus
|
||||
onOpenVersionDialog={() => setIsVersionDialogOpen(true)}
|
||||
requestRestart={requestRestart}
|
||||
restartIsPending={restartServerMutation.isPending}
|
||||
performUpgrade={performUpgrade}
|
||||
upgradeIsPending={upgradeOpenCodeMutation.isPending}
|
||||
/>
|
||||
<OpenCodeServerAuthSettings />
|
||||
<ManagerTokenSettings />
|
||||
<ServerEnvVarsSettings />
|
||||
@@ -263,6 +313,14 @@ export function SettingsDialog() {
|
||||
open={isVersionDialogOpen}
|
||||
onOpenChange={setIsVersionDialogOpen}
|
||||
/>
|
||||
<RestartServerDialog
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
activeSessionCount={activeSessionCount}
|
||||
isRestarting={restartServerMutation.isPending}
|
||||
onCancel={() => setConfirmOpen(false)}
|
||||
onConfirm={confirmRestart}
|
||||
/>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu'
|
||||
import { settingsApi } from '@/api/settings'
|
||||
import { invalidateConfigCaches } from '@/lib/queryInvalidation'
|
||||
import { DIRECTORY_INPUT_PROPS, getUploadItemsFromFileList } from '@/lib/directoryUpload'
|
||||
import { DIRECTORY_INPUT_PROPS, openPicker, readUploadItemsFromInput } from '@/lib/directoryUpload'
|
||||
|
||||
const KIND_NOUN: Record<'agents' | 'commands', string> = {
|
||||
agents: 'agent',
|
||||
@@ -29,14 +29,8 @@ export function UploadFolderButton({ kind }: UploadFolderButtonProps) {
|
||||
const folderInputRef = useRef<HTMLInputElement>(null)
|
||||
const noun = KIND_NOUN[kind]
|
||||
|
||||
const openPicker = (inputRef: React.RefObject<HTMLInputElement | null>) => {
|
||||
requestAnimationFrame(() => inputRef.current?.click())
|
||||
}
|
||||
|
||||
const handleChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const fileList = event.target.files
|
||||
const items = fileList ? getUploadItemsFromFileList(fileList) : []
|
||||
event.target.value = ''
|
||||
const items = readUploadItemsFromInput(event)
|
||||
if (items.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -78,17 +78,20 @@ export function useOpenCodeServerActions() {
|
||||
}
|
||||
}, [])
|
||||
|
||||
const openRestartPrompt = useCallback(async () => {
|
||||
const count = await probeActiveSessionCount()
|
||||
const showRestartConfirmation = useCallback((count: number) => {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
}, [probeActiveSessionCount, setActiveSessionCount, setConfirmOpen])
|
||||
}, [setActiveSessionCount, setConfirmOpen])
|
||||
|
||||
const openRestartPrompt = useCallback(async () => {
|
||||
const count = await probeActiveSessionCount()
|
||||
showRestartConfirmation(count)
|
||||
}, [probeActiveSessionCount, showRestartConfirmation])
|
||||
|
||||
const requestRestart = async () => {
|
||||
const count = await probeActiveSessionCount()
|
||||
if (count > 0) {
|
||||
setActiveSessionCount(count)
|
||||
setConfirmOpen(true)
|
||||
showRestartConfirmation(count)
|
||||
return
|
||||
}
|
||||
await performRestart()
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { getUploadItemsFromDataTransfer, getUploadItemsFromFileList } from './directoryUpload'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { renderHook, act } from '@testing-library/react'
|
||||
import type { DragEvent } from 'react'
|
||||
import { isExcludedOpenCodeConfigUploadPath } from '@opencode-manager/shared/utils'
|
||||
import {
|
||||
getUploadItemsFromDataTransfer,
|
||||
getUploadItemsFromFileList,
|
||||
useDirectoryDropZone,
|
||||
type DirectoryUploadItem,
|
||||
} from './directoryUpload'
|
||||
|
||||
interface StubFileEntry {
|
||||
name: string
|
||||
@@ -44,6 +52,15 @@ function createDirReader(children: FileSystemEntry[]): FileSystemDirectoryReader
|
||||
} as unknown as FileSystemDirectoryReader
|
||||
}
|
||||
|
||||
function createBatchedDirReader(batches: FileSystemEntry[][]): FileSystemDirectoryReader {
|
||||
let index = 0
|
||||
return {
|
||||
readEntries: (successCallback: (entries: FileSystemEntry[]) => void) => {
|
||||
successCallback(index < batches.length ? batches[index++] : [])
|
||||
},
|
||||
} as unknown as FileSystemDirectoryReader
|
||||
}
|
||||
|
||||
function createDirectoryEntry(name: string, children: FileSystemEntry[]): { entry: FileSystemDirectoryEntry; readerCreated: () => number } {
|
||||
let readerCreated = 0
|
||||
const entry = {
|
||||
@@ -58,6 +75,20 @@ function createDirectoryEntry(name: string, children: FileSystemEntry[]): { entr
|
||||
return { entry, readerCreated: () => readerCreated }
|
||||
}
|
||||
|
||||
function createBatchedDirectoryEntry(name: string, batches: FileSystemEntry[][]): { entry: FileSystemDirectoryEntry; readerCreated: () => number } {
|
||||
let readerCreated = 0
|
||||
const entry = {
|
||||
name,
|
||||
isFile: false,
|
||||
isDirectory: true,
|
||||
createReader: () => {
|
||||
readerCreated++
|
||||
return createBatchedDirReader(batches)
|
||||
},
|
||||
} as StubDirectoryEntry as unknown as FileSystemDirectoryEntry
|
||||
return { entry, readerCreated: () => readerCreated }
|
||||
}
|
||||
|
||||
function createDataTransfer(entries: FileSystemEntry[]): DataTransfer {
|
||||
return {
|
||||
items: entries.map((entry) => ({ webkitGetAsEntry: () => entry })),
|
||||
@@ -92,6 +123,77 @@ describe('getUploadItemsFromDataTransfer', () => {
|
||||
expect(junk.readCount()).toBe(0)
|
||||
expect(nodeModules.readerCreated()).toBe(0)
|
||||
})
|
||||
|
||||
it('returns the complete file set across readEntries batches while pruning skipped subtrees', async () => {
|
||||
const files: FileSystemEntry[] = []
|
||||
const expectedPaths: string[] = []
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const file = createFileEntry(`file${i}.md`)
|
||||
files.push(file.entry)
|
||||
expectedPaths.push(`root/file${i}.md`)
|
||||
}
|
||||
const junk = createFileEntry('junk.js')
|
||||
const nodeModules = createDirectoryEntry('node_modules', [junk.entry])
|
||||
const root = createBatchedDirectoryEntry('root', [files.slice(0, 100), files.slice(100), [nodeModules.entry]])
|
||||
|
||||
const items = await getUploadItemsFromDataTransfer(createDataTransfer([root.entry]), {
|
||||
shouldSkip: (relativePath) => relativePath.split('/').includes('node_modules'),
|
||||
})
|
||||
|
||||
expect(items.map((item) => item.relativePath)).toEqual(expectedPaths)
|
||||
expect(items).toHaveLength(120)
|
||||
expect(junk.readCount()).toBe(0)
|
||||
expect(nodeModules.readerCreated()).toBe(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useDirectoryDropZone', () => {
|
||||
function dropOnZone(handlers: ReturnType<typeof useDirectoryDropZone>['dropHandlers'], entries: FileSystemEntry[]) {
|
||||
return act(async () => {
|
||||
await handlers.onDrop({
|
||||
preventDefault: vi.fn(),
|
||||
stopPropagation: vi.fn(),
|
||||
dataTransfer: createDataTransfer(entries),
|
||||
} as unknown as DragEvent)
|
||||
})
|
||||
}
|
||||
|
||||
it('passes the traversed items to onItems without applying skips, as the file browser consumes it', async () => {
|
||||
const onItems = vi.fn()
|
||||
const { result } = renderHook(() => useDirectoryDropZone({ onItems }))
|
||||
const keep = createFileEntry('keep.md')
|
||||
const junk = createFileEntry('junk.js')
|
||||
const nodeModules = createDirectoryEntry('node_modules', [junk.entry])
|
||||
const root = createDirectoryEntry('root', [keep.entry, nodeModules.entry])
|
||||
|
||||
await dropOnZone(result.current.dropHandlers, [root.entry])
|
||||
|
||||
expect(onItems).toHaveBeenCalledTimes(1)
|
||||
const items = onItems.mock.calls[0][0] as DirectoryUploadItem[]
|
||||
expect(items.map((item) => item.relativePath)).toEqual(['root/keep.md', 'root/node_modules/junk.js'])
|
||||
})
|
||||
|
||||
it('applies the shouldSkip filter for the config-directory consumer', async () => {
|
||||
const onItems = vi.fn()
|
||||
const { result } = renderHook(() =>
|
||||
useDirectoryDropZone({
|
||||
shouldSkip: (relativePath) => isExcludedOpenCodeConfigUploadPath(relativePath),
|
||||
onItems,
|
||||
}),
|
||||
)
|
||||
const keep = createFileEntry('keep.md')
|
||||
const junk = createFileEntry('junk.js')
|
||||
const dotGit = createFileEntry('config')
|
||||
const nodeModules = createDirectoryEntry('node_modules', [junk.entry])
|
||||
const gitDir = createDirectoryEntry('.git', [dotGit.entry])
|
||||
const root = createDirectoryEntry('root', [keep.entry, nodeModules.entry, gitDir.entry])
|
||||
|
||||
await dropOnZone(result.current.dropHandlers, [root.entry])
|
||||
|
||||
expect(onItems).toHaveBeenCalledTimes(1)
|
||||
const items = onItems.mock.calls[0][0] as DirectoryUploadItem[]
|
||||
expect(items.map((item) => item.relativePath)).toEqual(['root/keep.md'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('getUploadItemsFromFileList', () => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { InputHTMLAttributes } from 'react'
|
||||
import { useRef, useState } from 'react'
|
||||
import type { ChangeEvent, DragEvent, InputHTMLAttributes, RefObject } from 'react'
|
||||
|
||||
export interface DirectoryUploadItem {
|
||||
file: File
|
||||
@@ -11,6 +12,8 @@ export const DIRECTORY_INPUT_PROPS = {
|
||||
mozdirectory: '',
|
||||
} as InputHTMLAttributes<HTMLInputElement>
|
||||
|
||||
const DIRECTORY_TRAVERSAL_CONCURRENCY = 25
|
||||
|
||||
async function readFileEntry(entry: FileSystemFileEntry): Promise<File> {
|
||||
return new Promise((resolve, reject) => {
|
||||
entry.file(resolve, reject)
|
||||
@@ -23,7 +26,7 @@ async function readDirectoryEntries(dirReader: FileSystemDirectoryReader): Promi
|
||||
})
|
||||
}
|
||||
|
||||
export async function traverseFileSystemEntry(
|
||||
async function traverseFileSystemEntry(
|
||||
entry: FileSystemEntry,
|
||||
basePath: string = '',
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean,
|
||||
@@ -48,9 +51,14 @@ export async function traverseFileSystemEntry(
|
||||
entries = entries.concat(batch)
|
||||
} while (batch.length > 0)
|
||||
|
||||
for (const childEntry of entries) {
|
||||
const childItems = await traverseFileSystemEntry(childEntry, relativePath, shouldSkip)
|
||||
items.push(...childItems)
|
||||
for (let i = 0; i < entries.length; i += DIRECTORY_TRAVERSAL_CONCURRENCY) {
|
||||
const childBatch = entries.slice(i, i + DIRECTORY_TRAVERSAL_CONCURRENCY)
|
||||
const childBatchItems = await Promise.all(
|
||||
childBatch.map((childEntry) => traverseFileSystemEntry(childEntry, relativePath, shouldSkip)),
|
||||
)
|
||||
for (const childItems of childBatchItems) {
|
||||
items.push(...childItems)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,3 +105,63 @@ export function getUploadItemsFromFileList(fileList: FileList): DirectoryUploadI
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
export function openPicker(inputRef: RefObject<HTMLInputElement | null>): void {
|
||||
requestAnimationFrame(() => inputRef.current?.click())
|
||||
}
|
||||
|
||||
export function readUploadItemsFromInput(event: ChangeEvent<HTMLInputElement>): DirectoryUploadItem[] {
|
||||
const fileList = event.target.files
|
||||
const items = fileList ? getUploadItemsFromFileList(fileList) : []
|
||||
event.target.value = ''
|
||||
return items
|
||||
}
|
||||
|
||||
interface DirectoryDropZoneOptions {
|
||||
shouldSkip?: (relativePath: string, isDirectory: boolean) => boolean
|
||||
onItems: (items: DirectoryUploadItem[]) => void | Promise<void>
|
||||
}
|
||||
|
||||
export function useDirectoryDropZone(options: DirectoryDropZoneOptions) {
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const { shouldSkip, onItems } = options
|
||||
|
||||
const handleDragEnter = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(true)
|
||||
}
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
if (e.currentTarget === dropZoneRef.current) {
|
||||
setIsDragging(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
}
|
||||
|
||||
const handleDrop = async (e: DragEvent) => {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
setIsDragging(false)
|
||||
const items = await getUploadItemsFromDataTransfer(e.dataTransfer, shouldSkip ? { shouldSkip } : undefined)
|
||||
await onItems(items)
|
||||
}
|
||||
|
||||
return {
|
||||
dropZoneRef,
|
||||
isDragging,
|
||||
dropHandlers: {
|
||||
onDragEnter: handleDragEnter,
|
||||
onDragOver: handleDragOver,
|
||||
onDragLeave: handleDragLeave,
|
||||
onDrop: handleDrop,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ export function invalidateConfigCaches(queryClient: QueryClient) {
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['managed-skills'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['opencode-directory-files'] })
|
||||
queryClient.invalidateQueries({ queryKey: ['agents-md'] })
|
||||
invalidateProviderCaches(queryClient)
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,14 @@ export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
const k = 1024
|
||||
const sizes = ['Bytes', 'KB', 'MB', 'GB'] as const
|
||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`
|
||||
}
|
||||
|
||||
export function randomId(): string {
|
||||
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
|
||||
return crypto.randomUUID()
|
||||
|
||||
Reference in new issue
Block a user