feat:优化使用体验1

v3.2-refact
panyy 2026-11-06 14:05:34 +08:00
parent 5434504f9b
commit 96a81496be
9 changed files with 394 additions and 61 deletions

View File

@ -152,12 +152,24 @@ def serialize(obj, detail=False, user=None):
from system_manage.ai_hub_progress import task_progress
data.update(status=obj.status, steps=obj.steps, error=obj.error, attempt=obj.attempt,
started_at=obj.started_at, finished_at=obj.finished_at)
if 'snapshot' not in obj.get_deferred_fields():
data['artifact_id'] = (obj.snapshot.get('workbench_artifact') or {}).get('id')
if detail:
data.update(snapshot=obj.snapshot, result=obj.result, progress=task_progress(obj))
if any(n.get('type') == 'organize' for n in obj.snapshot.get('nodes', [])):
data['summary_input'] = {key: obj.input_data[key] for key in ('markdown', 'heading_structure') if key in obj.input_data}
elif isinstance(obj, AIArtifact):
data.update(revision=obj.revision, layout=obj.layout, task_id=str(obj.task_id) if obj.task_id else None)
data.update(revision=obj.revision, layout=obj.layout, task_id=str(obj.task_id) if obj.task_id else None,
task_status=obj.task.status if obj.task_id else None, task_error=obj.task.error if obj.task_id else '')
meta = next((x for x in reversed(obj.history or []) if isinstance(x, dict) and x.get('_type') == 'workbench_tasks_v1'), {})
task_ids = [meta.get('parse_task_id'), meta.get('summary_task_id')]
states = {str(pk): status for pk, status in AITask.objects.filter(
id__in=[x for x in task_ids if x]).values_list('id', 'status')}
conflict = bool(obj.task_id and meta.get('conflict_task_id') == str(obj.task_id))
if conflict:
states[str(obj.task_id)] = 'CONFLICT'
data.update(file_name=meta.get('file_name', ''), parse_status=states.get(task_ids[0]),
summary_status=states.get(task_ids[1]), task_result_conflict=conflict)
if detail:
from system_manage.heading_structure import artifact_state, version_history, summary_state
data.update(original=obj.original, markdown=obj.markdown, history=version_history(obj), heading_structure=artifact_state(obj), summary_state=summary_state(obj))
@ -401,12 +413,49 @@ def submit(workspace, user, data, upload=None, service=None, request=None):
except ValueError as exc:
raise ValidationError(str(exc)) from None
resource_slots[key] = slots
return AITask.objects.create(workspace_id=workspace, owner_id=user.id,
task = AITask.objects.create(workspace_id=workspace, owner_id=user.id,
name=text(data.get('name') or (upload.name if upload else '导图任务'), '名称', limit=128), service=service,
snapshot={'nodes': snapshot, 'resources': required, 'resource_slots': resource_slots, 'priority': priority, 'flow_id': str(service.flow_id) if service else data.get('flow_id'),
'flow_revision': service.flow.revision if service else None},
input_data={'markdown': markdown, **heading_input}, file_name=upload.name[:255] if upload else '',
file_data=upload.read() if upload else None)
if 'workbench_artifact' in data:
spec = data['workbench_artifact']
if not isinstance(spec, dict) or set(spec) - {'id', 'revision', 'layout'}:
raise ValidationError('导图任务参数无效')
if spec.get('id'):
from rest_framework.serializers import UUIDField
artifact_id = UUIDField().run_validation(spec['id'])
artifact = AIArtifact.objects.select_for_update().filter(
pk=artifact_id, workspace_id=workspace, owner_id=user.id).first()
if not artifact:
raise ValidationError('导图不存在或无权访问')
if type(spec.get('revision')) is not int or spec['revision'] != artifact.revision:
raise ValidationError('内容已更新,请重新打开')
else:
from users.models import User
from system_manage.artifact_settings import limit
User.objects.select_for_update().get(pk=user.id)
maximum = limit()
if AIArtifact.objects.filter(workspace_id=workspace, owner_id=user.id).count() >= maximum:
raise ValidationError(f'已达到导图保存上限({maximum}条),请删除后再保存')
layout = spec.get('layout', 'tree')
if layout not in ('tree', 'radial', 'horizontal', 'vertical'):
raise ValidationError('布局无效')
artifact = AIArtifact.objects.create(workspace_id=workspace, owner_id=user.id,
name=task.name, layout=layout, original=heading_input.get('original', markdown), markdown=markdown)
artifact.task = task
meta = next((x.copy() for x in reversed(artifact.history or []) if isinstance(x, dict) and x.get('_type') == 'workbench_tasks_v1'), {'_type': 'workbench_tasks_v1'})
meta.pop('conflict_task_id', None)
is_summary = any(node['type'] == 'organize' for node in snapshot)
meta['summary_task_id' if is_summary else 'parse_task_id'] = str(task.id)
if upload:
meta['file_name'] = upload.name[:255]
artifact.history = [x for x in (artifact.history or []) if not isinstance(x, dict) or x.get('_type') != 'workbench_tasks_v1'] + [meta]
artifact.save(update_fields=['task', 'history', 'updated_at'])
task.snapshot['workbench_artifact'] = {'id': str(artifact.id), 'revision': artifact.revision}
task.save(update_fields=['snapshot', 'updated_at'])
return task
@transaction.atomic

View File

@ -20,12 +20,16 @@ def parser_progress(task):
def task_progress(task):
elapsed = max(0, int(((task.finished_at or timezone.now()) - (task.started_at or task.created_at)).total_seconds()))
section_detail = next((step.get('progress', {}) for step in reversed(task.steps or [])
if 'partial_markdown' in (step.get('progress') or {})), {})
section_fields = {key: section_detail[key] for key in
('partial_markdown', 'completed_sections', 'total_sections') if key in section_detail}
if task.status == 'SUCCESS':
return {'stage': '完成', 'percent': 100, 'elapsed_seconds': elapsed}
return {'stage': '完成', 'percent': 100, 'elapsed_seconds': elapsed, **section_fields}
if task.status == 'PENDING':
return {'stage': '等待任务处理', 'percent': None, 'elapsed_seconds': elapsed}
if task.status == 'FAILED':
return {'stage': '处理失败', 'percent': None, 'elapsed_seconds': elapsed}
return {'stage': '处理失败', 'percent': None, 'elapsed_seconds': elapsed, **section_fields}
current = next((step for step in task.steps if step.get('status') == 'RUNNING'), {})
detail = current.get('progress') or {}
percent = detail.get('percent')
@ -35,4 +39,4 @@ def task_progress(task):
percent = min(99, int((complete_steps * 100 + percent) / total_steps))
return {'stage': detail.get('stage') or LABELS.get(current.get('type'), '处理中'),
'percent': percent, 'elapsed_seconds': elapsed,
**({'plan': detail['plan']} if isinstance(detail.get('plan'), dict) else {})}
**section_fields, **({'plan': detail['plan']} if isinstance(detail.get('plan'), dict) else {})}

View File

@ -131,6 +131,8 @@ def execute(task):
task.refresh_from_db(fields=['result'])
task.result.update(original=original, markdown=markdown, source=source, tree=tree)
task.save(update_fields=['steps', 'result', 'updated_at'])
if task.snapshot.get('workbench_artifact') and not markdown.strip():
raise ValueError('处理结果为空,请检查文档内容后重试')
task.status = 'SUCCESS'
except Exception as exc:
if steps:
@ -147,5 +149,45 @@ def execute(task):
task.status = 'FAILED'
task.steps = steps
task.finished_at = timezone.now()
task.save(update_fields=['status', 'error', 'steps', 'finished_at', 'updated_at'])
with transaction.atomic():
task.save(update_fields=['status', 'error', 'steps', 'finished_at', 'updated_at'])
if task.status == 'SUCCESS':
persist_workbench_result(task)
return task
def persist_workbench_result(task):
"""Publish only to the unchanged artifact that still points at this task."""
from system_manage.models.ai_hub import AIArtifact
from system_manage.heading_structure import store_artifact_state, store_summary_state
spec = task.snapshot.get('workbench_artifact') or {}
if not spec.get('id'):
return
artifact = AIArtifact.objects.select_for_update().filter(
pk=spec['id'], workspace_id=task.workspace_id, owner_id=task.owner_id,
task_id=task.id).first()
if not artifact:
return
if artifact.revision != spec.get('revision'):
meta = next((x.copy() for x in reversed(artifact.history or []) if isinstance(x, dict)
and x.get('_type') == 'workbench_tasks_v1'), {'_type': 'workbench_tasks_v1'})
meta['conflict_task_id'] = str(task.id)
artifact.history = [x for x in (artifact.history or []) if not isinstance(x, dict)
or x.get('_type') != 'workbench_tasks_v1'] + [meta]
artifact.save(update_fields=['history', 'updated_at'])
return
result = task.result or {}
markdown = result.get('markdown', '')
if not markdown:
return
is_summary = any(n.get('type') == 'organize' for n in task.snapshot.get('nodes', []))
if is_summary:
store_summary_state(artifact, {'source_markdown': task.input_data.get('markdown', ''),
'smart_markdown': markdown, 'mode': 'smart'})
artifact.original = result.get('original', artifact.original)
artifact.markdown = markdown
structure = (result.get('source') or {}).get('heading_structure')
if structure:
store_artifact_state(artifact, structure)
artifact.revision += 1
artifact.save(update_fields=['original', 'markdown', 'history', 'revision', 'updated_at'])

View File

@ -75,7 +75,8 @@ class HubView(APIView):
query = query.filter(Q(snapshot__engine__isnull=True) | Q(snapshot__engine=False))
query = query.defer('file_data', 'input_data', 'snapshot', 'result')
elif kind == 'artifacts':
query = query.defer('original', 'markdown', 'history')
query = query.select_related('task').defer('original', 'markdown', 'task__file_data',
'task__input_data', 'task__snapshot', 'task__result', 'task__steps')
if any(key in request.query_params for key in ('mine', 'current_page', 'page_size', 'name')):
mine = request.query_params.get('mine', 'false')
if mine not in ('true', 'false'):

View File

@ -19,6 +19,7 @@ export interface ParseParams {
export interface ParseResult {
task_id?: string
artifact_id?: string
backend: string
version: string
results: Record<
@ -44,6 +45,9 @@ export interface ParseProgress {
}
export interface MindmapOrganizeProgress extends ParseProgress {
partial_markdown?: string
completed_sections?: number
total_sections?: number
plan?: Record<string, any>
task_id?: string
result_md?: string | null
@ -83,6 +87,9 @@ async function progress(taskId: string): Promise<MindmapOrganizeProgress> {
file_names: task.name,
task_id: task.id,
result_md: task.result?.markdown,
partial_markdown: task.progress?.partial_markdown,
completed_sections: task.progress?.completed_sections,
total_sections: task.progress?.total_sections,
heading_structure: task.result?.source?.heading_structure,
original_md: task.result?.original,
plan: task.progress?.plan || task.result?.source?.organization || task.result?.summary_state?.metrics,
@ -115,7 +122,7 @@ export const documentApi = {
async previewSummary(markdown: string, node: Record<string, unknown>) {
return hubCall('summary_preview', 'post', { markdown, nodes: [node, { type: 'render' }] })
},
async parseDocument(params: ParseParams, taskId: string = uuid()): Promise<ParseResult> {
async parseDocument(params: ParseParams, taskId: string = uuid(), onCreated?: (task: any) => void, isCancelled?: () => boolean): Promise<ParseResult> {
const results: ParseResult['results'] = {}
for (const file of params.files) {
const native = ['doc', 'docx', 'xls', 'xlsx', 'csv', 'html', 'htm', 'md', 'txt'].includes(
@ -135,15 +142,23 @@ export const documentApi = {
const task = await hubCall(
'tasks',
'post',
{ name: file.name.slice(0, 128), nodes: [node, { type: 'render' }] },
{ name: file.name.slice(0, 128), nodes: [node, { type: 'render' }], workbench_artifact: {} },
undefined,
file,
)
ids.set(taskId, task.id)
const until = Date.now() + 30 * 60 * 1000
onCreated?.(task)
if (isCancelled?.()) return { backend: 'shared', version: '1', results }
let completed = false
while (Date.now() < until) {
const current = await hubCall('tasks', 'get', undefined, task.id)
while (!isCancelled?.()) {
if (isCancelled?.()) return { backend: 'shared', version: '1', results }
let current
try { current = await hubCall('tasks', 'get', undefined, task.id) }
catch {
await new Promise((resolve) => setTimeout(resolve, 1500))
continue
}
if (isCancelled?.()) return { backend: 'shared', version: '1', results }
if (current.status === 'FAILED') throw new Error(current.error || '解析失败')
if (current.status === 'SUCCESS') {
results[file.name] = {
@ -171,7 +186,7 @@ export const documentApi = {
_mode = 'smart',
prompt?: string,
config?: { model_id: string; temperature?: number | null; options?: SummaryOptions },
context?: { heading_structure?: any; original?: string },
context?: { heading_structure?: any; original?: string; workbench_artifact?: { id: string; revision: number } },
): Promise<MindmapOrganizeProgress> {
if (!config?.model_id) throw new Error('请选择总结模型')
const node: Record<string, unknown> = { type: 'organize', model_id: config.model_id, prompt }

View File

@ -16,9 +16,14 @@ export async function hubCall(kind: string, method = 'get', data?: any, id?: str
export function onOpenArtifact(callback: (artifact: any) => void) {
const route = useRoute()
return watch(() => route.query.artifact, async id => {
let generation = 0
const stop = watch(() => route.query.artifact, async id => {
const current = ++generation
if (typeof id !== 'string' || !/^[a-f0-9-]{36}$/i.test(id)) return
try { callback(await hubCall('artifacts', 'get', undefined, id)) }
catch { ElMessage.error('导图不存在或无权访问') }
try {
const artifact = await hubCall('artifacts', 'get', undefined, id)
if (generation === current) callback(artifact)
} catch { if (generation === current) ElMessage.error('导图不存在或无权访问') }
}, { immediate: true })
return () => { generation++; stop() }
}

View File

@ -26,6 +26,7 @@
><el-select v-model="draft.mindmapModelId" clearable placeholder="请选择" @change="draft.summaryOptions.top_p = null"
><el-option v-for="m in models" :key="m.id" :label="m.name" :value="m.id" /></el-select
></el-form-item>
<slot name="platform-controls" />
<el-collapse v-model="advancedPanels">
<el-collapse-item title="高级参数" name="advanced">
<span class="export-hint">长度单位为 Token,留空使用默认值。</span>

View File

@ -327,21 +327,21 @@ export function useDocumentProcessor() {
}
// 处理文档转换
const processDocument = async () => {
let processGeneration = 0
const cancelProcessing = () => {
processGeneration++
stopProgressPolling()
isProcessing.value = false
processingStage.value = ''
}
const processDocument = async (onCreated?: (task: any, current: boolean) => void) => {
const generation = ++processGeneration
error.value = null
if (uploadedFiles.value.length === 0) {
error.value = '请先上传文件'
return
}
const firstFileName = uploadedFiles.value[0]?.name.toLowerCase() || ''
if (firstFileName.endsWith('.md')) {
if (!results.value) {
error.value = 'Markdown 文件内容为空,请重新上传'
}
return
}
isProcessing.value = true
error.value = null
processingStage.value = '准备提交解析任务'
@ -351,6 +351,7 @@ export function useDocumentProcessor() {
try {
await documentApi.createParseTask(taskId)
if (generation !== processGeneration) return
startProgressPolling(taskId)
processingStage.value = '提交文档到解析服务'
progressStage.value = '提交文档'
@ -376,7 +377,10 @@ export function useDocumentProcessor() {
}
processingStage.value = '解析文档'
const response = await documentApi.parseDocument(params, taskId)
const response = await documentApi.parseDocument(params, taskId, (task) => {
onCreated?.(task, generation === processGeneration)
}, () => generation !== processGeneration)
if (generation !== processGeneration) return
if (response.results) {
stopProgressPolling()
@ -399,11 +403,14 @@ export function useDocumentProcessor() {
}
} catch (err: any) {
if (generation !== processGeneration) return
error.value = err.message || '转换失败'
} finally {
stopProgressPolling()
processingStage.value = ''
isProcessing.value = false
if (generation === processGeneration) {
stopProgressPolling()
processingStage.value = ''
isProcessing.value = false
}
}
}
@ -456,6 +463,7 @@ export function useDocumentProcessor() {
initializeManualResult,
clearAll,
processDocument,
cancelProcessing,
getFormulaLabel,
getFormulaInfo
}

View File

@ -11,9 +11,9 @@
<header class="top-header">
<h2 class="ellipsis" title="思维导图工作台">思维导图工作台</h2>
<div class="header-actions">
<el-button :disabled="isProcessing || isSmartOrganizing || savingArtifact" @click="myMindmapsVisible = true">我的导图</el-button>
<el-button :disabled="savingArtifact" @click="stopPendingArtifactRecovery(); myMindmapsVisible = true">我的导图</el-button>
<el-button :loading="savingArtifact" :disabled="!results || isProcessing || isSmartOrganizing" @click="saveArtifact">保存导图</el-button>
<el-button type="text" :disabled="!configReady" @click="toggleSettings" class="settings-button">
<el-button type="text" :disabled="!configReady || isSmartOrganizing" @click="toggleSettings" class="settings-button">
设置
</el-button>
</div>
@ -29,7 +29,7 @@
@dragleave="isDragging = false"
@click="triggerUpload"
>
<div class="upload-content" v-if="uploadedFiles.length === 0">
<div class="upload-content" v-if="uploadedDisplayFiles.length === 0 && !openedArtifact?.file_name">
<el-icon class="upload-icon"><Folder /></el-icon>
<div class="upload-copy">
<div class="upload-text">文件导入</div>
@ -38,6 +38,7 @@
</div>
<div class="uploaded-files" v-else>
<div v-if="!uploadedDisplayFiles.length && openedArtifact?.file_name" class="file-item"><el-icon class="file-icon"><Document /></el-icon><span class="file-name">{{ openedArtifact.file_name }}</span></div>
<div class="file-item" v-for="(file, index) in uploadedDisplayFiles" :key="index">
<el-icon class="file-icon"><Document /></el-icon>
<span class="file-name">{{ file.name }}</span>
@ -77,6 +78,7 @@
</div>
<div class="result-section">
<el-alert v-if="openedArtifact?.task_result_conflict" title="结果未应用,内容已被修改" type="warning" :closable="false" show-icon />
<el-tabs v-model="activeTab" class="result-tabs">
<el-tab-pane name="markdown">
<template #label>
@ -135,7 +137,7 @@
<div v-else-if="!results" class="empty-state">
<div class="empty-icon"></div>
<p class="empty-text">暂无转换结果</p>
<p class="empty-text">{{ error || '暂无转换结果' }}</p>
</div>
<div v-else class="result-tab-content result-fade-in">
@ -174,6 +176,7 @@
</span>
</div>
<div class="content-toolbar-actions">
<el-select v-if="sourceContentMode === 'smart'" v-model="smartDetail" size="small" :disabled="isSmartOrganizing" class="smart-detail-select"><el-option label="精简" value="brief" /><el-option label="标准" value="standard" /><el-option label="详细" value="detailed" /></el-select>
<el-button v-if="canShowSmartSources" @click="summarySourcesVisible = true">原文对照</el-button>
<el-button v-if="smartMarkdownContent || smartOrganizeError" :disabled="isSmartOrganizing" @click="startSmartOrganize(true)">重新总结</el-button>
<el-button v-if="smartTaskFailed && !smartResultStale" :disabled="isSmartOrganizing" @click="retrySmartOrganize">继续处理</el-button>
@ -192,7 +195,7 @@
v-model="sourcePanelContent"
type="textarea"
:rows="20"
:readonly="sourceViewMode === 'ast'"
:readonly="sourceViewMode === 'ast' || isSmartOrganizing"
:placeholder="sourceViewMode === 'markdown' ? '请在这里粘贴 Markdown 模板源码' : 'AST 内容将根据替换后的 Markdown 自动生成'"
class="source-textarea"
/>
@ -201,14 +204,15 @@
<div v-show="activeTab === 'mindmap'" class="mindmap-content">
<div class="mindmap-box">
<MindMapRenderer
<div v-if="isSmartOrganizing && !smartMarkdownContent" class="smart-summary-skeleton"><el-skeleton :rows="4" animated /></div>
<MindMapRenderer v-else
:content="renderedMarkdownContent"
:title="documentTitle"
:source-name="exportSourceName"
v-model:layout="graphLayout"
:editable="!hasActiveReplacementRules"
:editable="!hasActiveReplacementRules && !isSmartOrganizing"
:excluded-lines="activeHeadingStructure?.excluded_lines || []"
:document-key="mindmapDocumentKey"
:document-key="mindmapRenderKey"
:export-resolution="config.exportResolution"
@node-edit="handleMindmapNodeEdit"
@heading-edit="headingPanelVisible = true"
@ -338,7 +342,8 @@ const {
clearAll,
initializeManualResult,
handleFileUpload,
processDocument
processDocument,
cancelProcessing
} = useDocumentProcessor()
const showSettings = ref(false)
@ -364,6 +369,12 @@ const isMobileDialog = ref(false)
const replacementRules = ref<ReplacementRule[]>([])
const draftReplacementRules = ref<ReplacementRule[]>([])
const smartMarkdownContent = ref('')
const smartDetail = computed({
get: () => config.summaryOptions.detail,
set: (value: 'brief' | 'standard' | 'detailed') => { config.summaryOptions.detail = value }
})
const smartCompletedSections = ref(0)
const smartTotalSections = ref(0)
const smartHeadingStructure = ref<any>()
const smartHeadingMarkdown = ref('')
const headingPanelVisible = ref(false)
@ -401,7 +412,7 @@ watch(sourceViewMode, (value) => storeValue(SOURCE_VIEW_MODE_KEY, value))
const manualMarkdownContent = computed(() => results.value?.source || '')
const currentSmartRequest = computed(() => JSON.stringify([manualMarkdownContent.value,
config.mindmapModelId, config.mindmapPrompt, config.mindmapLlmTemperature,
config.summaryOptions, results.value?.headingStructure]))
{ ...config.summaryOptions, detail: smartDetail.value }, results.value?.headingStructure]))
const smartResultStale = computed(() => !!smartRequestSnapshot.value && smartRequestSnapshot.value !== currentSmartRequest.value)
const activeHeadingStructure = computed(() => {
const state = sourceContentMode.value === 'smart' ? smartHeadingStructure.value : results.value?.headingStructure
@ -421,7 +432,7 @@ function applyHeadingStructure(value: any) {
inspectHeadingStructure(value)
}
const activeSourceMarkdownContent = computed(() => {
if (sourceContentMode.value === 'smart' && smartMarkdownContent.value) {
if (sourceContentMode.value === 'smart' && (smartMarkdownContent.value || isSmartOrganizing.value || smartTaskFailed.value)) {
return smartMarkdownContent.value
}
return manualMarkdownContent.value
@ -432,9 +443,12 @@ const renderedMarkdownContent = computed(() => templateRenderResult.value.markdo
const openedArtifact = ref<any>(null)
const graphLayout = ref('tree')
const mindmapDocumentKey = ref(`document-${Date.now()}`)
const mindmapRenderKey = computed(() => sourceContentMode.value === 'smart'
? `${mindmapDocumentKey.value}:summary:${smartOrganizeTaskId.value}:${isSmartOrganizing.value ? 'generating' : 'result'}`
: mindmapDocumentKey.value)
watch(mindmapDocumentKey, () => { if (!openedArtifact.value) graphLayout.value = 'tree' })
const exportSourceName = computed(() => uploadedDisplayFiles.value[0]?.name || openedArtifact.value?.name || '未命名文档')
const documentTitle = computed(() => documentTitleFromName(uploadedDisplayFiles.value[0]?.name || openedArtifact.value?.name || '思维导图'))
const exportSourceName = computed(() => uploadedDisplayFiles.value[0]?.name || openedArtifact.value?.file_name || openedArtifact.value?.name || '未命名文档')
const documentTitle = computed(() => documentTitleFromName(uploadedDisplayFiles.value[0]?.name || openedArtifact.value?.file_name || openedArtifact.value?.name || '思维导图'))
const renderedMindmapContent = computed(() => buildMindmapMarkdown(renderedMarkdownContent.value, documentTitle.value))
const templateRenderError = computed(() => templateRenderResult.value.error)
const activeReplacementRuleCount = computed(() => replacementRules.value.filter((rule) => rule.search.trim()).length)
@ -487,6 +501,8 @@ const resetSmartOrganizeState = () => {
stopSmartOrganizePolling()
sourceContentMode.value = 'source'
smartMarkdownContent.value = ''
smartCompletedSections.value = 0
smartTotalSections.value = 0
smartHeadingStructure.value = undefined
smartHeadingMarkdown.value = ''
headingPanelVisible.value = false
@ -518,6 +534,14 @@ const startSmartOrganizePolling = (taskId: string) => {
if (data.plan) smartPlan.value = data.plan
smartOrganizeProgress.value = data.progress
smartOrganizeStage.value = data.stage
smartCompletedSections.value = data.completed_sections ?? 0
smartTotalSections.value = data.total_sections ?? 0
if (data.status !== 'completed' && data.partial_markdown) {
smartMarkdownContent.value = data.partial_markdown
smartHeadingStructure.value = undefined
smartHeadingMarkdown.value = ''
showSmartResult()
}
if (data.status === 'completed') {
stopSmartOrganizePolling()
isSmartOrganizing.value = false
@ -529,14 +553,16 @@ const startSmartOrganizePolling = (taskId: string) => {
if (results.value && data.task_id) results.value.taskId = data.task_id
smartOrganizeError.value = ''
showSmartResult()
if (data.warnings?.length) ElMessage.warning('总结完成,部分章节待核对')
const artifact = await refreshCurrentArtifact()
if (artifact?.task_result_conflict) ElMessage.warning('结果未应用,内容已被修改')
else if (data.warnings?.length) ElMessage.warning('总结完成,部分章节待核对')
else ElMessage.success('智能总结完成')
} else if (data.status === 'failed') {
stopSmartOrganizePolling()
isSmartOrganizing.value = false
sourceContentMode.value = 'source'
smartOrganizeError.value = data.error || '智能总结失败'
smartTaskFailed.value = true
void refreshCurrentArtifact(false)
ElMessage.error(smartOrganizeError.value)
}
} catch (err) {
@ -551,6 +577,7 @@ const startSmartOrganizePolling = (taskId: string) => {
const startSmartOrganize = async (force = false) => {
if (isSmartOrganizing.value) return
if (showSettings.value) closeSettings()
const markdown = manualMarkdownContent.value.trim()
if (!markdown) {
sourceContentMode.value = 'source'
@ -562,30 +589,40 @@ const startSmartOrganize = async (force = false) => {
return
}
if (!openedArtifact.value) {
await saveArtifact(true)
if (!openedArtifact.value) return
}
const taskId = `mindmap-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
smartOrganizeTaskId.value = taskId
smartRequestSnapshot.value = currentSmartRequest.value
smartPlan.value = null
smartTaskFailed.value = false
smartMarkdownContent.value = ''
smartHeadingStructure.value = undefined
smartHeadingMarkdown.value = ''
smartCompletedSections.value = 0
smartTotalSections.value = 0
isSmartOrganizing.value = true
showSmartResult()
activeTab.value = 'mindmap'
smartOrganizeProgress.value = 0
smartOrganizeStage.value = '创建智能总结任务'
smartOrganizeError.value = ''
const generation = smartPollingGeneration
try {
const options = Object.fromEntries(Object.entries(config.summaryOptions).filter(([, value]) => value != null))
const node: Record<string, unknown> = {type: 'organize', model_id: config.mindmapModelId, prompt: config.mindmapPrompt, ...options}
if (config.mindmapLlmTemperature != null) node.temperature = config.mindmapLlmTemperature
smartPlan.value = await documentApi.previewSummary(markdown, node)
const created = await documentApi.createMindmapTask(taskId, markdown, 'hybrid', config.mindmapPrompt, {
model_id: config.mindmapModelId,
temperature: config.mindmapLlmTemperature,
options: config.summaryOptions,
}, { heading_structure: results.value?.headingStructure, original: originalRecognized.value || results.value?.original || markdown })
options: { ...config.summaryOptions, detail: smartDetail.value },
}, { heading_structure: results.value?.headingStructure, original: originalRecognized.value || results.value?.original || markdown, workbench_artifact: { id: openedArtifact.value.id, revision: openedArtifact.value.revision } })
if (generation !== smartPollingGeneration) return
smartOrganizeTaskId.value = created.task_id || taskId
if (created.task_id) rememberSummaryTask(created.task_id)
startSmartOrganizePolling(smartOrganizeTaskId.value)
} catch (err) {
if (generation !== smartPollingGeneration) return
isSmartOrganizing.value = false
sourceContentMode.value = 'source'
smartOrganizeError.value = (err as Error).message || '智能总结任务创建失败'
@ -609,6 +646,7 @@ async function restoreSummaryTask() {
if (node[key] != null) (taskOptions as any)[key] = node[key]
else if (['context_tokens', 'max_input_tokens', 'max_output_tokens', 'input_tokens', 'output_tokens', 'safety_tokens', 'top_p'].includes(key)) (taskOptions as any)[key] = null
}
smartDetail.value = taskOptions.detail
originalRecognized.value = data.original_md || source
results.value = { markdown: source, source, original: data.original_md || source,
headingStructure: data.summary_input?.heading_structure, headingMarkdown: source,
@ -618,7 +656,10 @@ async function restoreSummaryTask() {
taskOptions, data.summary_input?.heading_structure])
smartPlan.value = data.plan || null
smartSources.value = data.sources || []
activeTab.value = 'source'
activeTab.value = 'mindmap'
smartCompletedSections.value = data.completed_sections ?? 0
smartTotalSections.value = data.total_sections ?? 0
if (data.status !== 'completed' && data.partial_markdown) { smartMarkdownContent.value = data.partial_markdown; showSmartResult() }
if (data.status === 'completed') {
smartMarkdownContent.value = data.result_md || ''
smartSourceSnapshot.value = smartMarkdownContent.value
@ -630,6 +671,7 @@ async function restoreSummaryTask() {
smartOrganizeError.value = data.error || '总结失败,可继续处理'
} else {
isSmartOrganizing.value = true
showSmartResult()
startSmartOrganizePolling(taskId)
}
} catch { forgetSummaryTask() }
@ -639,6 +681,8 @@ const retrySmartOrganize = async () => {
if (isSmartOrganizing.value || smartResultStale.value) return
isSmartOrganizing.value = true
smartOrganizeError.value = ''
showSmartResult()
activeTab.value = 'mindmap'
try {
await documentApi.retryMindmapTask(smartOrganizeTaskId.value)
smartTaskFailed.value = false
@ -654,9 +698,10 @@ watch(sourceContentMode, (value) => {
if (value === 'smart') {
startSmartOrganize()
}
})
}, { flush: 'sync' })
const toggleSettings = () => {
stopPendingArtifactRecovery()
if (showSettings.value) {
const settingsPanel = document.querySelector('.settings-panel')
if (settingsPanel) {
@ -715,21 +760,46 @@ const applyConfig = (nextConfig: typeof config) => {
}
const router = useRouter()
function clearArtifactRoute() {
if (!router.currentRoute.value.query.artifact) return
const query = { ...router.currentRoute.value.query }
delete query.artifact
void router.replace({ query })
}
const handleProcessDocument = async () => {
if (isProcessing.value || isSmartOrganizing.value) return
mindmapDocumentKey.value = `parse-${Date.now()}`
openedArtifact.value = null
originalRecognized.value = ''
resetSmartOrganizeState()
await processDocument()
const generation = artifactLoadGeneration
const recoveryKey = artifactRecoveryKey()
const intentKey = `${recoveryKey}:intent`
const intent = `${Date.now()}-${Math.random().toString(36).slice(2)}`
try {
localStorage.removeItem(recoveryKey)
localStorage.setItem(intentKey, intent)
} catch { /* Optional recovery storage. */ }
let createdArtifact: Promise<void> | undefined
await processDocument((task, current) => {
if (!task.artifact_id) return
try {
if (localStorage.getItem(intentKey) === intent) localStorage.setItem(recoveryKey, task.artifact_id)
} catch { /* Optional recovery storage. */ }
if (current && componentActive) createdArtifact = loadArtifact(task.artifact_id, false).catch(() => {})
})
await createdArtifact
if (!componentActive || generation !== artifactLoadGeneration) return
if (error.value) {
ElMessage.error(error.value)
return
}
const artifact = openedArtifact.value?.id ? await refreshCurrentArtifact() : undefined
if (results.value) {
activeTab.value = 'mindmap'
sourceViewMode.value = 'markdown'
ElMessage.success('转换完成')
if (artifact?.task_result_conflict) ElMessage.warning('结果未应用,内容已被修改')
else ElMessage.success('转换完成')
}
}
@ -792,7 +862,8 @@ const handleMindmapNodeEdit = ({ start, end, original, newText }: { start: numbe
}
const triggerUpload = () => {
if (isProcessing.value || isSmartOrganizing.value) return
if (isProcessing.value || isSmartOrganizing.value || savingArtifact.value) return
stopPendingArtifactRecovery()
fileInput.value?.click()
}
@ -801,6 +872,8 @@ const handleFileInputChange = async (event: Event) => {
if (input.files) {
mindmapDocumentKey.value = `upload-${Date.now()}`
openedArtifact.value = null
forgetArtifact()
clearArtifactRoute()
originalRecognized.value = ''
await handleFileUpload(input.files)
input.value = ''
@ -819,12 +892,15 @@ const handleFileInputChange = async (event: Event) => {
const handleDrop = async (event: DragEvent) => {
event.preventDefault()
stopPendingArtifactRecovery()
isDragging.value = false
if (isProcessing.value || isSmartOrganizing.value) return
if (event.dataTransfer?.files) {
mindmapDocumentKey.value = `upload-${Date.now()}`
openedArtifact.value = null
forgetArtifact()
clearArtifactRoute()
originalRecognized.value = ''
await handleFileUpload(event.dataTransfer.files)
if (uploadedFiles.value.length > 0) {
@ -856,10 +932,72 @@ const clearAllFiles = () => {
}
const originalRecognized = ref('')
const artifactRecoveryKey = () => `mindmap.artifact.v1:${useStore().user.userInfo?.id || ''}:${useStore().user.getWorkspaceId()}`
function rememberArtifact(id: string) {
if (!useStore().user.userInfo?.id) return
try {
localStorage.setItem(`${artifactRecoveryKey()}:intent`, `${Date.now()}-${Math.random()}`)
localStorage.setItem(artifactRecoveryKey(), id)
} catch { /* Optional recovery storage. */ }
}
function forgetArtifact() { try { localStorage.removeItem(artifactRecoveryKey()); localStorage.removeItem(`${artifactRecoveryKey()}:intent`) } catch { /* Optional recovery storage. */ } }
let artifactTimer: ReturnType<typeof setInterval> | null = null
let pendingArtifactTimer: ReturnType<typeof setInterval> | null = null
function stopPendingArtifactRecovery() {
if (pendingArtifactTimer) clearInterval(pendingArtifactTimer)
pendingArtifactTimer = null
}
function waitForPendingArtifact() {
stopPendingArtifactRecovery()
const key = artifactRecoveryKey()
let intent = ''
try { intent = localStorage.getItem(`${key}:intent`) || '' } catch { return }
if (!intent) return
const deadline = Date.now() + 5 * 60 * 1000
const stillWaiting = () => componentActive && artifactRecoveryKey() === key && Date.now() < deadline && !results.value &&
!openedArtifact.value && !uploadedFiles.value.length && !isProcessing.value &&
!myMindmapsVisible.value && !showSettings.value && !router.currentRoute.value.query.artifact &&
localStorage.getItem(`${key}:intent`) === intent
pendingArtifactTimer = setInterval(async () => {
try {
if (!stillWaiting()) { stopPendingArtifactRecovery(); return }
const id = localStorage.getItem(key)
if (!id) return
stopPendingArtifactRecovery()
const artifact = await hubCall('artifacts', 'get', undefined, id)
if (stillWaiting()) applySavedArtifact(artifact)
} catch { stopPendingArtifactRecovery() }
}, 1000)
}
function stopArtifactPolling() { if (artifactTimer) clearInterval(artifactTimer); artifactTimer = null }
async function loadArtifact(id: string, apply = true) {
const artifact = await hubCall('artifacts', 'get', undefined, id)
if (!componentActive) return
if (apply) applySavedArtifact(artifact)
else if (!openedArtifact.value || openedArtifact.value.id === id) openedArtifact.value = artifact
}
async function refreshCurrentArtifact(apply = true) {
const id = openedArtifact.value?.id
if (!id) return
const generation = artifactLoadGeneration
try {
const artifact = await hubCall('artifacts', 'get', undefined, id)
if (!componentActive || generation !== artifactLoadGeneration || openedArtifact.value?.id !== id) return
if (apply && !artifact.task_result_conflict) applySavedArtifact(artifact)
else openedArtifact.value = artifact
return artifact
} catch { /* Retry when reopened. */ }
}
let artifactLoadGeneration = 0
function applySavedArtifact(artifact: any) {
const generation = ++artifactLoadGeneration
stopPendingArtifactRecovery()
cancelProcessing()
stopArtifactPolling()
resetSmartOrganizeState()
isProcessing.value = false
error.value = null
rememberArtifact(artifact.id)
replacementRules.value = []
draftReplacementRules.value = []
showReplacementDialog.value = false
@ -870,17 +1008,67 @@ function applySavedArtifact(artifact: any) {
uploadedDisplayFiles.value = []
originalRecognized.value = artifact.original || ''
const savedSummary = artifact.summary_state || {}
const source = savedSummary.source_markdown || artifact.markdown
const source = savedSummary.source_markdown ?? artifact.markdown ?? ''
smartMarkdownContent.value = savedSummary.smart_markdown || ''
const restoreSmart = savedSummary.mode === 'smart' && !!smartMarkdownContent.value
if (restoreSmart) {
applyingSmartResult = true
sourceContentMode.value = 'smart'
smartHeadingStructure.value = artifact.heading_structure
smartHeadingMarkdown.value = smartMarkdownContent.value
}
results.value = { markdown: source, source, original: artifact.original, headingStructure: sourceContentMode.value === 'source' ? artifact.heading_structure : undefined, headingMarkdown: source, mindmap: buildMindmapMarkdown(artifact.markdown), taskId: artifact.task_id || undefined }
results.value = { markdown: source, source, original: artifact.original, headingStructure: sourceContentMode.value === 'source' ? artifact.heading_structure : undefined, headingMarkdown: source, mindmap: buildMindmapMarkdown(artifact.markdown || ''), taskId: artifact.task_id || undefined }
if (artifact.task_status === 'PENDING' || artifact.task_status === 'RUNNING') {
const summary = artifact.summary_status === 'PENDING' || artifact.summary_status === 'RUNNING'
if (summary) {
isSmartOrganizing.value = true
smartOrganizeTaskId.value = artifact.task_id
showSmartResult()
startSmartOrganizePolling(artifact.task_id)
} else {
isProcessing.value = true
progressStage.value = '解析文档'
artifactTimer = setInterval(async () => {
try {
const data = await documentApi.getParseProgress(artifact.task_id)
if (generation !== artifactLoadGeneration) return
progressStage.value = data.stage
if (data.progress !== null) progressPercent.value = data.progress
if (data.status === 'completed' || data.status === 'failed') {
stopArtifactPolling()
await refreshCurrentArtifact()
}
} catch { /* Keep retrying after a transient failure. */ }
}, 1500)
}
} else if (artifact.task_status === 'FAILED') {
if (artifact.summary_status === 'FAILED') {
smartOrganizeTaskId.value = artifact.task_id
smartTaskFailed.value = true
smartOrganizeError.value = artifact.task_error || '智能总结失败'
showSmartResult()
} else { error.value = artifact.task_error || '解析失败'; results.value = null }
}
if (artifact.task_id) documentApi.getMindmapProgress(artifact.task_id).then(data => {
if (generation === artifactLoadGeneration && openedArtifact.value?.id === artifact.id && data.status === 'completed' && data.result_md === artifact.markdown) {
if (generation !== artifactLoadGeneration || openedArtifact.value?.id !== artifact.id) return
if (data.summary_node) {
const node = data.summary_node
if (node.model_id) config.mindmapModelId = node.model_id
if (node.prompt != null) config.mindmapPrompt = node.prompt
config.mindmapLlmTemperature = node.temperature ?? null
for (const key of Object.keys(config.summaryOptions)) {
if (node[key] != null) (config.summaryOptions as any)[key] = node[key]
}
if (data.summary_input?.markdown && (artifact.task_status === 'PENDING' || artifact.task_status === 'RUNNING' || artifact.task_status === 'FAILED') && results.value) {
const submitted = data.summary_input.markdown
results.value.source = submitted
results.value.markdown = submitted
results.value.headingStructure = data.summary_input.heading_structure
results.value.headingMarkdown = submitted
}
smartRequestSnapshot.value = currentSmartRequest.value
}
if (data.status === 'completed' && data.result_md === artifact.markdown) {
smartSources.value = data.sources || []
smartSourceSnapshot.value = data.result_md || ''
smartPlan.value = data.plan || null
@ -896,6 +1084,7 @@ async function openSavedArtifact(artifact: any) {
await router.replace({path: '/mindmap', query: {...router.currentRoute.value.query, artifact: artifact.id}})
}
async function confirmOpenSavedArtifact() {
if (isProcessing.value || isSmartOrganizing.value) return true
const current = openedArtifact.value
const changed = !!activeSourceMarkdownContent.value.trim() && (!current || current.markdown !== activeSourceMarkdownContent.value || current.layout !== graphLayout.value)
if (!changed) return true
@ -907,6 +1096,7 @@ function renameSavedArtifact(artifact: any) {
async function deleteSavedArtifact(id: string) {
if (openedArtifact.value?.id !== id) return
openedArtifact.value = null
forgetArtifact()
const query = {...router.currentRoute.value.query}
delete query.artifact
await router.replace({query})
@ -914,7 +1104,7 @@ async function deleteSavedArtifact(id: string) {
watch(() => results.value?.markdown, (value) => {
if (!openedArtifact.value && value) originalRecognized.value = results.value?.original || originalRecognized.value || value
})
async function saveArtifact() {
async function saveArtifact(silent = false) {
if (savingArtifact.value) return
savingArtifact.value = true
try {
@ -929,11 +1119,12 @@ async function saveArtifact() {
layout: graphLayout.value
}, current?.id)
openedArtifact.value = saved
rememberArtifact(saved.id)
originalRecognized.value = saved.original || ''
const source = saved.summary_state?.source_markdown || saved.markdown
results.value = { markdown: source, source, original: saved.original, headingStructure: sourceContentMode.value === 'source' ? saved.heading_structure : undefined, headingMarkdown: source, mindmap: buildMindmapMarkdown(saved.markdown), taskId: saved.task_id || undefined }
await router.replace({path: '/mindmap', query: {...router.currentRoute.value.query, artifact: saved.id}})
ElMessage.success('已保存')
if (!silent) ElMessage.success('已保存')
} catch (e: any) { ElMessage.error(e.message || '保存失败') }
finally { savingArtifact.value = false }
}
@ -945,18 +1136,35 @@ onMounted(async () => {
const loaded = await loadWorkbenchDefaults()
if (!componentActive) return
if (!loaded) ElMessage.warning('工作台默认设置加载失败,请检查网络')
await restoreSummaryTask()
const routeId = router.currentRoute.value.query.artifact
let lastId = typeof routeId === 'string' ? routeId : ''
if (!lastId && useStore().user.userInfo?.id) { try { lastId = localStorage.getItem(artifactRecoveryKey()) || '' } catch { /* Optional recovery storage. */ } }
if (lastId) {
try { await loadArtifact(lastId) } catch { forgetArtifact() }
} else {
let pending = false
try { pending = !!localStorage.getItem(`${artifactRecoveryKey()}:intent`) } catch { /* Optional recovery storage. */ }
if (pending) waitForPendingArtifact()
else await restoreSummaryTask()
}
})
onUnmounted(() => {
componentActive = false
stopArtifactListener()
stopSmartOrganizePolling()
stopArtifactPolling()
stopPendingArtifactRecovery()
cancelProcessing()
artifactLoadGeneration++
window.removeEventListener('resize', updateViewportState)
})
</script>
<style scoped>
.smart-summary-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; padding: 8px 0; }
.smart-detail-select { width: 100px; }
.smart-summary-skeleton { max-width: 480px; margin: 80px auto; padding: 0 24px; }
.summary-source-columns { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
.summary-source-columns > div { min-width: 0; }
.summary-source-columns pre { white-space: pre-wrap; overflow-wrap: anywhere; max-height: 55vh; overflow: auto; font: inherit; }