'use client' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { Button } from '@/components/ui/Button' import { Dialog } from '@/shared/ui/Dialog' import { createWorkspaceFolder, formatFileSize, getWorkspaceFileGrant, grantWorkspaceFiles, listWorkspaceFiles, listWorkspaceTrash, previewWorkspaceFile, renameWorkspaceEntry, restoreWorkspaceEntry, revokeWorkspaceFiles, trashWorkspaceEntry, uploadWorkspaceFile, WorkspaceUploadConflictError, type WorkspaceFileEntry, type WorkspaceFileGrant, type WorkspaceTrashBatch, } from '@/lib/workspace-files-api' /** * Admin-only browser for the files inside one registered workspace. * * Writes require an explicit, per-workspace grant: the first mutating action * opens the grant dialog, and the backend enforces the same rule (a missing * grant is a 403, not a server error). DeepTutor's own state — `.deeptutor/`, * SQLite files and `skills/` — is filtered out by the backend and cannot be * reached from here. * * Deletes are soft: entries move into the workspace trash and the panel keeps * a restore view, because a mis-click on a question bank must be reversible * without shell access. */ export interface WorkspaceFileManagerProps { workspaceId: string workspaceName: string open: boolean onClose: () => void } type View = 'files' | 'trash' export function WorkspaceFileManager({ workspaceId, workspaceName, open, onClose, }: WorkspaceFileManagerProps) { const { t } = useTranslation() const [view, setView] = useState('files') const [path, setPath] = useState('.') const [entries, setEntries] = useState([]) const [truncated, setTruncated] = useState(false) const [grant, setGrant] = useState(null) const [trash, setTrash] = useState([]) const [loading, setLoading] = useState(false) const [busy, setBusy] = useState(false) const [error, setError] = useState(null) const [notice, setNotice] = useState(null) const [preview, setPreview] = useState<{ path: string; content: string } | null>(null) const [renaming, setRenaming] = useState(null) const [renameValue, setRenameValue] = useState('') const [creatingFolder, setCreatingFolder] = useState(false) const [folderName, setFolderName] = useState('') const [confirmGrant, setConfirmGrant] = useState(false) // After the user accepts the grant dialog, re-run the action that was // blocked. Keeping it here means a first upload is not silently dropped. const pendingAction = useRef<(() => Promise) | null>(null) const fileInputRef = useRef(null) const granted = grant?.granted === true const parentPath = useMemo(() => { if (path === '.' || !path.includes('/')) return '.' return path.slice(0, path.lastIndexOf('/')) }, [path]) const refresh = useCallback(async () => { if (!open) return setLoading(true) setError(null) try { const [listing, grantState] = await Promise.all([ listWorkspaceFiles(workspaceId, path), getWorkspaceFileGrant(workspaceId), ]) setEntries(listing.entries) setTruncated(listing.truncated) setGrant(grantState) if (view === 'trash') { setTrash(await listWorkspaceTrash(workspaceId)) } } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)) } finally { setLoading(false) } }, [open, workspaceId, path, view]) useEffect(() => { if (!open) return setPath('.') setView('files') setPreview(null) setNotice(null) }, [open, workspaceId]) useEffect(() => { void refresh() }, [refresh]) useEffect(() => { if (!notice) return const timer = window.setTimeout(() => setNotice(null), 4000) return () => window.clearTimeout(timer) }, [notice]) const withGrant = async (action: () => Promise) => { if (!granted) { pendingAction.current = action setConfirmGrant(true) return } setBusy(true) setError(null) try { await action() } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)) } finally { setBusy(false) } } const handleGrant = async () => { setConfirmGrant(false) setBusy(true) setError(null) const next = pendingAction.current pendingAction.current = null try { setGrant(await grantWorkspaceFiles(workspaceId)) setNotice(t('File management enabled for this workspace.')) } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)) return } finally { setBusy(false) } // Run the blocked action directly: `withGrant` closed over the pre-grant // `granted` value, so calling it here would reopen the same dialog. if (next) { setBusy(true) try { await next() } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)) } finally { setBusy(false) } } } const cancelGrant = () => { pendingAction.current = null setConfirmGrant(false) } const handleRevoke = async () => { setBusy(true) setError(null) try { setGrant(await revokeWorkspaceFiles(workspaceId)) setNotice(t('File management disabled for this workspace.')) } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)) } finally { setBusy(false) } } const handleUpload = async (input: HTMLInputElement) => { const files = Array.from(input.files ?? []) if (files.length === 0) return input.value = '' await withGrant(async () => { setNotice(null) const uploaded: string[] = [] try { for (const file of files) { let saved: WorkspaceFileEntry try { saved = await uploadWorkspaceFile(workspaceId, path, file) } catch (exc) { if (!(exc instanceof WorkspaceUploadConflictError)) throw exc if (!window.confirm(t('Replace the existing file "{{name}}"?', { name: file.name }))) { continue } saved = await uploadWorkspaceFile(workspaceId, path, file, true) setPreview(current => current?.path === saved.path ? null : current) } uploaded.push(saved.name) } } finally { if (uploaded.length > 0) { setNotice( uploaded.length === 1 ? t('Uploaded {{name}}.', { name: uploaded[0] }) : t('Uploaded {{count}} files.', { count: uploaded.length }) ) await refresh() } } }) } const handleCreateFolder = async () => { const name = folderName.trim() if (!name) return const target = path === '.' ? name : `${path}/${name}` // Close this dialog before running the action: an ungranted workspace // routes through `withGrant` to the grant dialog, and leaving this one open // would stack two modals. The action is remembered and re-run after the // grant is accepted, so the name is not lost. setCreatingFolder(false) await withGrant(async () => { await createWorkspaceFolder(workspaceId, target) setFolderName('') setNotice(t('Created {{name}}.', { name })) await refresh() }) } const handleRename = async () => { if (!renaming) return const name = renameValue.trim() if (!name || name === renaming.name) { setRenaming(null) return } // Close first, same reason as the folder dialog: an ungranted workspace // opens the grant modal and two stacked dialogs are unreachable. const target = renaming.path setRenaming(null) await withGrant(async () => { await renameWorkspaceEntry(workspaceId, target, name) setNotice(t('Renamed to {{name}}.', { name })) await refresh() }) } const handleTrash = async (entry: WorkspaceFileEntry) => { await withGrant(async () => { await trashWorkspaceEntry(workspaceId, entry.path) setNotice(t('{{name}} moved to trash.', { name: entry.name })) await refresh() }) } const handleRestore = async ( batch: WorkspaceTrashBatch, item: WorkspaceTrashBatch['items'][number] ) => { await withGrant(async () => { // Empty destination restores to the exact folder it was deleted from, // recreating parents that the same delete took with it. The slot // identifies the delete operation, so a folder comes back whole. await restoreWorkspaceEntry(workspaceId, batch.batch, item.slot) setNotice(t('Restored {{name}}.', { name: item.original })) await refresh() }) } const handlePreview = async (entry: WorkspaceFileEntry) => { setError(null) try { const payload = await previewWorkspaceFile(workspaceId, entry.path) setPreview({ path: entry.path, content: payload.content }) } catch (exc) { setError(exc instanceof Error ? exc.message : String(exc)) } } const breadcrumb = useMemo(() => { const parts = path === '.' ? [] : path.split('/') return [{ label: workspaceName, target: '.' }].concat( parts.map((part, index) => ({ label: part, target: parts.slice(0, index + 1).join('/'), })) ) }, [path, workspaceName]) return ( <> } >

{t('Deleted files go to trash first and can be restored at any time.')}

setCreatingFolder(false)} size="sm" closeLabel={t('Close')} closeTooltip={false} footer={
} > setFolderName(event.target.value)} onKeyDown={event => { if (event.key === 'Enter' && folderName.trim() && !busy) { event.preventDefault() void handleCreateFolder() } }} placeholder={t('Folder name')} />
setRenaming(null)} size="sm" closeLabel={t('Close')} closeTooltip={false} footer={
} > setRenameValue(event.target.value)} onKeyDown={event => { if (event.key === 'Enter' && renameValue.trim() && !busy) { event.preventDefault() void handleRename() } }} />
) } export default WorkspaceFileManager