'use client' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { Download, FolderInput, RefreshCw } from 'lucide-react' import { apiFetch, apiUrl } from '@/lib/api' import { useChatWorkspaces } from '@/hooks/useChatWorkspaces' import { activeWorkspaceId } from '@/lib/workspace-scope' type Feature = { feature: string label: string path: string files: number bytes: number sessions?: number error: string } type Discovery = { features: Feature[]; historical: { path: string }[]; session_backend: string } type Preview = { features: string[] dependencies: string[] sessions: number files: number bytes: number blockers: string[] } type Operation = { id: string status: string created_at: string error?: string download_url?: string recovery_path?: string } const endpoint = '/api/settings/workspace/data' const labels: Record = { chat: ['Conversations', '对话'], book: ['Books', '书籍'], learning: ['Mastery Path', '掌握路径'], reading: ['Immersive Reading', '沉浸式阅读'], timed_media: ['Immersive Watching', '沉浸式观看'], notebook: ['Notebooks', '笔记本'], 'co-writer': ['Writing', '协作写作'], learning_journal: ['Learning journal', '学习日志'], files: ['File library', '文件库'], knowledge_bases: ['Knowledge bases', '知识库'], parse_cache: ['Document cache', '文档解析缓存'], outputs: ['Generated outputs', '生成产物'], presentations: ['Presented files', '已展示文件'], attachments: ['Conversation attachments', '对话附件'], historical_chat: ['Historical conversation database', '历史对话数据库'], historical_agent: ['Historical agent outputs', '历史智能体产物'], historical_output: ['Historical output folder', '历史输出目录'], historical_archive: ['Historical archives', '历史归档'], } async function request(path: string, body?: object): Promise { const response = await apiFetch( apiUrl(`${endpoint}${path}`), body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), } : undefined ) const value = await response.json() if (!response.ok) throw new Error(value.detail || `Request failed (${response.status})`) return value as T } export default function DataMigrationSettingsSection() { const { t, i18n } = useTranslation() const zh = i18n.language.startsWith('zh') const text = (en: string, cn: string) => (zh ? cn : t(en)) const counted = (count: number, en: string, cn: string) => zh ? `${count} ${cn}` : t(en, { count }) const { workspaces } = useChatWorkspaces() const [source, setSource] = useState(activeWorkspaceId) const [target, setTarget] = useState('') const [discovery, setDiscovery] = useState(null) const [selected, setSelected] = useState([]) const [preview, setPreview] = useState(null) const [operations, setOperations] = useState([]) const [busy, setBusy] = useState(false) const [error, setError] = useState('') const [historical, setHistorical] = useState(false) const [conversationIds, setConversationIds] = useState('') const label = (key: string) => (labels[key] ? text(...labels[key]) : key) const statusLabel = (key: string) => ({ preparing: text('Preparing', '准备中'), copying: text('Copying', '复制中'), transferring: text('Transferring', '迁移中'), committed: text('Finishing', '收尾中'), completed: text('Completed', '已完成'), exported: text('Exported', '已导出'), recovered: text('Recovered', '已恢复'), failed: text('Failed; source retained', '失败,来源数据已保留'), cleanup_required: text('Cleanup required', '需要完成清理'), recovery_required: text('Recovery required', '需要恢复'), }[key] || key) const input = { source_workspace_id: source, target_workspace_id: target, features: selected, include_historical: historical, ...(selected.includes('chat') && conversationIds.trim() ? { session_ids: conversationIds.trim().split(/[\s,]+/) } : {}), } useEffect(() => { setPreview(null) }, [source, target, selected, conversationIds]) useEffect(() => { let alive = true const timer = window.setInterval(() => { request<{ operations: Operation[] }>('/operations') .then(value => { if (alive) setOperations(value.operations) }) .catch(() => {}) }, 5000) return () => { alive = false window.clearInterval(timer) } }, []) useEffect(() => { let alive = true setDiscovery(null) setSelected([]) setConversationIds('') setError('') request(`/discover?source_workspace_id=${encodeURIComponent(source)}`) .then(value => { if (alive) setDiscovery(value) }) .catch(err => { if (alive) setError(String(err.message)) }) request<{ operations: Operation[] }>('/operations') .then(value => { if (alive) setOperations(value.operations) }) .catch(() => {}) return () => { alive = false } }, [source]) async function run(action: 'preview' | 'migrate' | 'export') { setBusy(true) setError('') try { if (action === 'preview') setPreview(await request('/preview', input)) else { const result = await request(`/${action}`, input) setOperations(old => [result, ...old]) if (action === 'migrate') { setPreview(null) setSelected([]) setDiscovery( await request(`/discover?source_workspace_id=${encodeURIComponent(source)}`) ) } } } catch (err) { setError(err instanceof Error ? err.message : String(err)) } finally { setBusy(false) } } async function recover(id: string) { setBusy(true) setError('') try { const result = await request(`/operations/${id}/recover`, {}) setOperations(old => old.map(row => (row.id === id ? result : row))) } catch (err) { setError(err instanceof Error ? err.message : String(err)) } finally { setBusy(false) } } const options = ( <> {workspaces .filter(row => !row.archived) .map(row => ( ))} ) return (

{text('Data migration', '数据迁移')}

{text( 'Discover stored learning data, move it with its related conversations, or download an archive. Verified recovery copies are retained after migration.', '查找已有学习数据,将资料和关联对话一并迁移,或下载备份。迁移后会保留经过校验的恢复副本。' )}

{text( 'Learning data moves as a complete feature bundle. Preview includes related sources and conversations. Choose a destination with no existing data for these features.', '学习数据按功能整体迁移,预览会列出关联资料和对话。目标工作区中对应功能应为空,以免覆盖已有学习记录。' )}

{selected.some(key => key.startsWith('historical_')) ? (

{text( 'Historical data is retained as an archive inside the destination workspace. It is not automatically merged into current learning records.', '历史数据将作为档案保存在目标工作区内,不会自动合并到当前学习记录。' )}

) : null}
{selected.includes('chat') && }
{!discovery ? (

{text('Searching stored data…', '正在查找已有数据…')}

) : ( discovery.features.map(row => ( )) )}
{discovery?.historical.length ? (
{text('Additional historical data', '其他历史数据')} ({discovery.historical.length})

{text( 'Historical archives can be included in exports for recovery and inspection.', '可在导出中包含这些历史目录,便于检查和恢复。' )}

{discovery.historical.map(row => (

{row.path}

))}
) : null}
{preview ? (

{counted(preview.sessions, '{{count}} conversations', '个对话')} ·{' '} {counted(preview.files, '{{count}} files', '个文件')} · {(preview.bytes / 1024 / 1024).toFixed(1)} MB

{text('Included features', '包含功能')}: {preview.features.map(label).join(zh ? '、' : ', ')}

{preview.dependencies.length ? (

{text( 'Related source data included to preserve references', '为保留引用,额外包含关联来源数据' )} : {preview.dependencies.map(label).join('、')}

) : null} {preview.blockers.map((reason, i) => (

{reason}

))}
) : null}
{busy ? (

{text( 'Processing. You can return to this page to view the result.', '正在处理。可以稍后回到此页查看结果。' )}

) : null} {error ? (

{error}

) : null} {operations.length ? (

{text('Recent operations', '最近操作')}

{operations.slice(0, 10).map(row => (

{statusLabel(row.status)} · {new Date(row.created_at).toLocaleString()}

{row.error ?

{row.error}

: null} {row.download_url ? ( {text('Download archive', '下载备份')} ) : null} {!['completed', 'exported', 'recovered'].includes(row.status) ? ( ) : null} {row.recovery_path ? (

{text('Recovery copy', '恢复副本')}: {row.recovery_path}

) : null}
))}
) : null}
) }