const WORKFLOW_KEY_PRESETS = [ { value: 'Enter', label: 'Enter' }, { value: 'Ctrl+Enter', label: 'Ctrl+Enter' }, { value: 'Shift+Enter', label: 'Shift+Enter' }, { value: 'Alt+Enter', label: 'Alt+Enter' }, { value: 'Escape', label: 'Escape' }, { value: 'Tab', label: 'Tab' }, { value: 'Backspace', label: 'Backspace' }, { value: 'Delete', label: 'Delete' }, { value: 'ArrowUp', label: 'ArrowUp' }, { value: 'ArrowDown', label: 'ArrowDown' }, { value: 'ArrowLeft', label: 'ArrowLeft' }, { value: 'ArrowRight', label: 'ArrowRight' }, { value: 'Ctrl+A', label: 'Ctrl+A' }, { value: 'Ctrl+C', label: 'Ctrl+C' }, { value: 'Ctrl+V', label: 'Ctrl+V' }, { value: 'Ctrl+X', label: 'Ctrl+X' }, { value: 'Ctrl+L', label: 'Ctrl+L' }, ]; window.WorkflowPanel = { name: 'WorkflowPanel', components: { WorkflowStudio: window.WorkflowStudioComponent }, props: { workflow: { type: Array, required: true }, selectors: { type: Object, required: true }, modelCatalog: { type: Object, default: () => ({}) }, currentDomain: { type: String, default: null }, selectedPreset: { type: String, default: '主预设' }, collapsed: { type: Boolean, default: true } }, emits: ['update:collapsed', 'update:modelCatalog', 'add-step', 'remove-step', 'move-step', 'action-change', 'show-templates'], data() { return { legacyDetails: false, editorInjecting: false, editorBridgePolling: false, editorBridgeInFlight: false, editorBridgeTimer: null, editorBridgeIdleDelay: 250, keyPresets: WORKFLOW_KEY_PRESETS, expandedJsEditors: {}, jsExecutionModes: {}, availableScripts: [], loadingScripts: false, expandedJsPreviews: {}, scriptPreviewContents: {}, loadingScriptPreviews: {}, customKeyModes: {}, expandedHintEditors: {}, expandedExecutionMenus: {}, hintToneOptions: [ { value: 'info', label: '提示' }, { value: 'success', label: '成功' }, { value: 'warning', label: '警告' }, { value: 'danger', label: '注意' } ], jsonParamPlaceholder: '{\n "target_endpoint": "/nextjs-api/stream/create-evaluation",\n "override_model": "{{context.model}}"\n}', catalogCollapsed: false, darkPoolCollapsed: false, expandedSteps: {}, localCatalog: { enabled: false, source: 'arena_direct', modality: 'text', include_keywords: [], exclude_keywords: [], enable_dark_pool: false, dark_pool_since: '', dark_pool_whitelist_keywords: [], dark_pool_blacklist_keywords: [] }, catalogLoading: false, catalogSaveTimer: null, draggedIndex: null, dragOverIndex: null, dragOverPosition: null, catalogKeywordsDraft: { include_keywords: '', exclude_keywords: '', dark_pool_whitelist_keywords: '', dark_pool_blacklist_keywords: '' } }; }, computed: { hasStructuredFlow() { return this.workflow.some(s => ['SET','CAPTURE','IF','SWITCH','GROUP','GUARD','TRY','LABEL'].includes(s.action)); }, isArenaPreset() { const domain = String(this.currentDomain || '').trim().toLowerCase(); return domain === 'arena.ai' || domain.endsWith('.arena.ai'); } }, watch: { workflow: { handler() { this.syncHintEditorState(); }, deep: true, immediate: true }, selectedPreset: { handler() { if (this.catalogSaveTimer) { clearTimeout(this.catalogSaveTimer); this.catalogSaveTimer = null; } this.expandedHintEditors = {}; this.expandedExecutionMenus = {}; this.customKeyModes = {}; this.expandedJsEditors = {}; this.expandedJsPreviews = {}; this.expandedSteps = {}; this.draggedIndex = null; this.dragOverIndex = null; this.dragOverPosition = null; this.syncHintEditorState(); this.loadModelCatalog(); }, immediate: true }, currentDomain: { handler() { if (this.catalogSaveTimer) { clearTimeout(this.catalogSaveTimer); this.catalogSaveTimer = null; } this.loadModelCatalog(); }, immediate: true } }, mounted() { this.loadAvailableScripts(false); this.loadModelCatalog(); }, beforeUnmount() { this.stopEditorBridgePolling(); if (this.catalogSaveTimer) { clearTimeout(this.catalogSaveTimer); this.catalogSaveTimer = null; } }, methods: { addStudioStep() { const studio = this.$refs.flowStudio?.studio; if (studio) { studio.palette = 'root'; studio.tab = 'flow'; studio.render(); } else this.$emit('add-step'); }, replaceStudioWorkflow(value) { this.workflow.splice(0, this.workflow.length, ...value); }, replaceStudioSelectors(value) { Object.keys(this.selectors).forEach(k => delete this.selectors[k]); Object.assign(this.selectors, value); }, toggle() { this.$emit('update:collapsed', !this.collapsed); }, hasStepDetail(step, index = null) { if (!step) return false; if (step.action === 'KEY_PRESS') { return index !== null && this.isCustomKeyPreset(index, step); } return ['JS_EXEC', 'COORD_CLICK', 'COORD_SCROLL', 'READONLY_HINT', 'PAGE_FETCH'].includes(step.action); }, isStepExpanded(index, step = null) { if (step && !this.hasStepDetail(step, index)) return false; return !!this.expandedSteps[index]; }, toggleStepExpand(index, step = null) { if (step && !this.hasStepDetail(step, index)) return; this.expandedSteps = { ...this.expandedSteps, [index]: !this.isStepExpanded(index, step) }; }, expandAllSteps() { const next = {}; (this.workflow || []).forEach((step, idx) => { if (this.hasStepDetail(step, idx)) { next[idx] = true; } }); this.expandedSteps = next; }, collapseAllSteps() { this.expandedSteps = {}; }, reorderIndexMap(map, fromIndex, toIndex) { if (!map || typeof map !== 'object') return {}; const newMap = {}; Object.entries(map).forEach(([key, val]) => { const idx = Number(key); if (isNaN(idx)) return; let nextIdx = idx; if (idx === fromIndex) { nextIdx = toIndex; } else if (fromIndex < toIndex && idx > fromIndex && idx <= toIndex) { nextIdx = idx - 1; } else if (fromIndex > toIndex && idx >= toIndex && idx < fromIndex) { nextIdx = idx + 1; } newMap[nextIdx] = val; }); return newMap; }, removeIndexFromMap(map, removeIndex) { if (!map || typeof map !== 'object') return {}; const newMap = {}; Object.entries(map).forEach(([key, val]) => { const idx = Number(key); if (isNaN(idx) || idx === removeIndex) return; const nextIdx = idx > removeIndex ? idx - 1 : idx; newMap[nextIdx] = val; }); return newMap; }, handleMoveStep(index, direction) { const newIndex = index + direction; if (newIndex < 0 || !this.workflow || newIndex >= this.workflow.length) return; this.reorderWorkflowStep(index, newIndex, direction > 0 ? 'after' : 'before'); }, handleRemoveStep(index) { if (Array.isArray(this.workflow)) { this.workflow.splice(index, 1); } this.expandedSteps = this.removeIndexFromMap(this.expandedSteps, index); this.expandedJsEditors = this.removeIndexFromMap(this.expandedJsEditors, index); this.expandedHintEditors = this.removeIndexFromMap(this.expandedHintEditors, index); this.expandedExecutionMenus = this.removeIndexFromMap(this.expandedExecutionMenus, index); this.customKeyModes = this.removeIndexFromMap(this.customKeyModes, index); this.expandedJsPreviews = this.removeIndexFromMap(this.expandedJsPreviews, index); }, handleDragStart(index, event) { this.draggedIndex = index; this.dragOverIndex = null; this.dragOverPosition = null; if (event && event.dataTransfer) { event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', String(index)); } }, handleDragOver(index, event) { if (this.draggedIndex === null || this.draggedIndex === index) { this.dragOverIndex = null; this.dragOverPosition = null; return; } event.preventDefault(); if (event.dataTransfer) { event.dataTransfer.dropEffect = 'move'; } const rect = event.currentTarget.getBoundingClientRect(); const midY = rect.top + rect.height / 2; const pos = event.clientY < midY ? 'before' : 'after'; this.dragOverIndex = index; this.dragOverPosition = pos; }, handleDragLeave(index, event) { if (event.currentTarget && !event.currentTarget.contains(event.relatedTarget)) { if (this.dragOverIndex === index) { this.dragOverIndex = null; this.dragOverPosition = null; } } }, handleDrop(targetIndex, event) { event.preventDefault(); const fromIndex = this.draggedIndex; const position = this.dragOverPosition || 'before'; this.draggedIndex = null; this.dragOverIndex = null; this.dragOverPosition = null; if (fromIndex === null || fromIndex === undefined || fromIndex === targetIndex) { return; } this.reorderWorkflowStep(fromIndex, targetIndex, position); }, handleDragEnd() { this.draggedIndex = null; this.dragOverIndex = null; this.dragOverPosition = null; }, reorderWorkflowStep(fromIndex, targetIndex, position) { if (!Array.isArray(this.workflow)) return; if (fromIndex === targetIndex) return; const [movedItem] = this.workflow.splice(fromIndex, 1); let insertIndex = targetIndex; if (fromIndex < targetIndex) { insertIndex = position === 'after' ? targetIndex : targetIndex - 1; } else { insertIndex = position === 'after' ? targetIndex + 1 : targetIndex; } if (insertIndex < 0) insertIndex = 0; if (insertIndex > this.workflow.length) insertIndex = this.workflow.length; this.workflow.splice(insertIndex, 0, movedItem); this.expandedSteps = this.reorderIndexMap(this.expandedSteps, fromIndex, insertIndex); this.expandedJsEditors = this.reorderIndexMap(this.expandedJsEditors, fromIndex, insertIndex); this.expandedHintEditors = this.reorderIndexMap(this.expandedHintEditors, fromIndex, insertIndex); this.expandedExecutionMenus = this.reorderIndexMap(this.expandedExecutionMenus, fromIndex, insertIndex); this.customKeyModes = this.reorderIndexMap(this.customKeyModes, fromIndex, insertIndex); this.expandedJsPreviews = this.reorderIndexMap(this.expandedJsPreviews, fromIndex, insertIndex); }, getStepSummary(step) { if (!step) return ''; switch (step.action) { case 'FILL_INPUT': return step.target ? `填入目标: ${step.target}` : '未选择目标输入框'; case 'SELECT_MODEL': return step.target ? `选择模型器: ${step.target}` : '未选择模型选择器'; case 'PAGE_FETCH': return '页面直发 prompt 请求'; case 'CLICK': return step.target ? `点击: ${step.target}` : '未选择点击目标'; case 'COORD_CLICK': return `坐标 (${step.value?.x ?? 0}, ${step.value?.y ?? 0})`; case 'COORD_SCROLL': return `滑动 (${step.value?.start_x ?? 0}, ${step.value?.start_y ?? 0}) → (${step.value?.end_x ?? 0}, ${step.value?.end_y ?? 0})`; case 'STREAM_WAIT': case 'STREAM_OUTPUT': return step.target ? `等待流式容器: ${step.target}` : '流式等待'; case 'WAIT': return `等待 ${step.value ?? 0} 秒`; case 'KEY_PRESS': return `按键: ${step.target || '未设置'}`; case 'JS_EXEC': { const mode = this.getJsMode(-1, step); if (mode === 'file') { const file = this.normalizeScriptTarget(step.target); return file ? `脚本: ${file.split('/').pop()}` : '未选择脚本文件'; } const code = String(step.value || '').trim(); return code ? `内联: ${code.slice(0, 30)}${code.length > 30 ? '...' : ''}` : '空 JS 代码'; } case 'READONLY_HINT': { const hint = this.normalizeHintStepValue(step); return `提示: ${hint.title || '无标题'}`; } default: return ''; } }, normalizeCatalogKeywords(value) { const items = Array.isArray(value) ? value : String(value || '').split(/[\n,]+/); return [...new Set(items.map(item => String(item || '').trim()).filter(Boolean))]; }, catalogKeywordsText(key) { return this.normalizeCatalogKeywords(this.localCatalog && this.localCatalog[key]).join('\n'); }, syncCatalogKeywordsDraft(force = false) { if (!this.catalogKeywordsDraft) { this.catalogKeywordsDraft = { include_keywords: '', exclude_keywords: '', dark_pool_whitelist_keywords: '', dark_pool_blacklist_keywords: '' }; } ['include_keywords', 'exclude_keywords', 'dark_pool_whitelist_keywords', 'dark_pool_blacklist_keywords'].forEach(key => { const propArr = this.normalizeCatalogKeywords(this.localCatalog && this.localCatalog[key]); const draftArr = this.normalizeCatalogKeywords(this.catalogKeywordsDraft[key]); const isSame = JSON.stringify(propArr) === JSON.stringify(draftArr); if (force || !isSame || this.catalogKeywordsDraft[key] === undefined) { this.catalogKeywordsDraft[key] = propArr.join('\n'); } }); }, handleCatalogKeywordsInput(key, rawText) { if (!this.catalogKeywordsDraft) { this.catalogKeywordsDraft = { include_keywords: '', exclude_keywords: '', dark_pool_whitelist_keywords: '', dark_pool_blacklist_keywords: '' }; } this.catalogKeywordsDraft[key] = rawText; if (this.catalogSaveTimer) { clearTimeout(this.catalogSaveTimer); this.catalogSaveTimer = null; } const targetDomain = this.currentDomain; const targetPreset = this.selectedPreset || '主预设'; this.catalogSaveTimer = setTimeout(() => { this.catalogSaveTimer = null; if (this.currentDomain !== targetDomain || (this.selectedPreset || '主预设') !== targetPreset) { return; } this.saveModelCatalog({ [key]: this.normalizeCatalogKeywords(rawText) }, targetPreset, targetDomain); }, 300); }, async loadModelCatalog() { if (!this.isArenaPreset || !this.currentDomain) return; this.catalogLoading = true; try { const domain = this.currentDomain; const preset = this.selectedPreset || '主预设'; const res = await this.authJsonRequest( '/api/sites/' + encodeURIComponent(domain) + '/model-catalog?preset_name=' + encodeURIComponent(preset) ); if (res && res.catalog && domain === this.currentDomain && preset === (this.selectedPreset || '主预设')) { this.localCatalog = { enabled: false, source: 'arena_direct', modality: 'text', include_keywords: [], exclude_keywords: [], enable_dark_pool: false, dark_pool_since: '', dark_pool_whitelist_keywords: [], dark_pool_blacklist_keywords: [], ...res.catalog }; this.syncCatalogKeywordsDraft(true); } } catch (e) { console.warn('[WorkflowPanel] 加载独立模型目录配置失败:', e); } finally { this.catalogLoading = false; } }, async saveModelCatalog(patch = {}, targetPreset = null, targetDomain = null) { const domain = targetDomain || this.currentDomain; const preset = targetPreset || this.selectedPreset || '主预设'; if (!this.isArenaPreset || !domain) return; const isCurrent = domain === this.currentDomain && preset === (this.selectedPreset || '主预设'); if (isCurrent) { this.localCatalog = { enabled: false, source: 'arena_direct', include_keywords: [], exclude_keywords: [], enable_dark_pool: false, dark_pool_since: '', dark_pool_whitelist_keywords: [], dark_pool_blacklist_keywords: [], ...(this.localCatalog || {}), ...(patch || {}) }; this.syncCatalogKeywordsDraft(false); } try { const payloadCatalog = isCurrent ? this.localCatalog : { enabled: false, source: 'arena_direct', include_keywords: [], exclude_keywords: [], enable_dark_pool: false, dark_pool_since: '', dark_pool_whitelist_keywords: [], dark_pool_blacklist_keywords: [], ...(patch || {}) }; await this.authJsonRequest('/api/sites/' + encodeURIComponent(domain) + '/model-catalog', { method: 'PUT', body: JSON.stringify({ preset_name: preset, catalog: payloadCatalog }) }); if (isCurrent) { this.$emit('update:modelCatalog', { ...this.localCatalog }); } } catch (e) { console.error('[WorkflowPanel] 保存模型目录配置失败:', e); } }, async authJsonRequest(url, options = {}) { const token = window.getDashboardAuthToken ? window.getDashboardAuthToken() : ''; const headers = { 'Content-Type': 'application/json', ...(options.headers || {}) }; if (token) { headers['Authorization'] = 'Bearer ' + token; } const response = await fetch(url, { ...options, headers }); const payload = await response.json().catch(() => ({})); if (!response.ok) { const message = payload.detail || payload.message || ('HTTP ' + response.status); const error = new Error(message); error.status = response.status; // 修复:挂载业务负载,便于调用方区分「后端业务失败」与「真正的传输异常」 error.payload = payload; error.isBusinessError = (response.status >= 400 && response.status < 500) || response.status === 503; throw error; } return payload; }, startEditorBridgePolling() { if (this.editorBridgePolling || this.editorBridgeTimer) return; this.editorBridgePolling = true; this.editorBridgeIdleDelay = 250; console.debug('[WorkflowPanel] start editor bridge polling'); this.scheduleEditorBridgePolling(0); }, stopEditorBridgePolling() { this.editorBridgePolling = false; if (this.editorBridgeTimer) { window.clearTimeout(this.editorBridgeTimer); this.editorBridgeTimer = null; } console.debug('[WorkflowPanel] stop editor bridge polling'); }, scheduleEditorBridgePolling(delay = this.editorBridgeIdleDelay) { if (!this.editorBridgePolling || this.editorBridgeTimer) return; this.editorBridgeTimer = window.setTimeout(async () => { this.editorBridgeTimer = null; await this.consumeEditorBridgeActions(); }, Math.max(0, Number(delay) || 0)); }, async consumeEditorBridgeActions() { if (this.editorBridgeInFlight) { this.scheduleEditorBridgePolling(this.editorBridgeIdleDelay); return; } this.editorBridgeInFlight = true; try { const result = await this.authJsonRequest('/api/workflow-editor/consume-actions', { method: 'POST', body: '{}' }); const executedCount = Number(result && result.executed_count || 0); if (executedCount > 0) { this.editorBridgeIdleDelay = 250; console.debug('[WorkflowPanel] consumed editor bridge actions:', result); } else { this.editorBridgeIdleDelay = Math.min(2000, Math.max(250, this.editorBridgeIdleDelay * 2)); } } catch (e) { this.editorBridgeIdleDelay = Math.min(2000, Math.max(500, this.editorBridgeIdleDelay * 2)); console.debug('[WorkflowPanel] consume editor bridge actions failed:', e); } finally { this.editorBridgeInFlight = false; this.scheduleEditorBridgePolling(this.editorBridgeIdleDelay); } }, async launchVisualEditor() { if (this.editorInjecting) return; this.editorInjecting = true; try { console.debug('[WorkflowPanel] launch visual editor', { domain: this.currentDomain, preset: this.selectedPreset }); const result = await this.authJsonRequest('/api/workflow-editor/inject', { method: 'POST', body: JSON.stringify({ target_domain: this.currentDomain, preset_name: this.selectedPreset }) }); if (result.success) { this.startEditorBridgePolling(); console.debug('[WorkflowPanel] visual editor launch result:', result); alert(result.already_existed ? '编辑器已激活,请切换到浏览器窗口查看。' : '编辑器已注入,请切换到浏览器窗口,使用右下角工具栏编辑工作流。'); } else { alert('注入失败: ' + (result.message || '未知错误')); } } catch (e) { // 修复:后端所有失败路径都用非 2xx 承载 success:false(浏览器未连接/域名不匹配等), // 会被 authJsonRequest 抛出,此前一律提示「网络错误」,误导用户去排查网络 const hasBusinessPayload = e && e.payload && typeof e.payload === 'object' && Object.keys(e.payload).length > 0; if (e && (e.isBusinessError || hasBusinessPayload)) { alert('注入失败: ' + (e.message || '未知错误')); } else { alert('网络错误: ' + ((e && e.message) || '未知错误')); } } finally { this.editorInjecting = false; } }, isJsExpanded(index) { return !!this.expandedJsEditors[index]; }, toggleJsExpand(index) { this.expandedJsEditors = { ...this.expandedJsEditors, [index]: !this.expandedJsEditors[index] }; }, applyKeyPreset(index, step, value) { if (value === '__custom__') { this.customKeyModes = { ...this.customKeyModes, [index]: true }; this.expandedSteps = { ...this.expandedSteps, [index]: true }; if (!step.target || this.keyPresets.some(item => item.value === step.target)) { step.target = ''; } return; } if (value) { this.customKeyModes = { ...this.customKeyModes, [index]: false }; this.expandedSteps = { ...this.expandedSteps, [index]: false }; step.target = value; } }, isCustomKeyPreset(index, step) { if (this.customKeyModes[index] === true) return true; return this.getKeyPresetValue(index, step) === '__custom__'; }, getKeyPresetValue(index, step) { if (this.customKeyModes[index] === true) return '__custom__'; const target = String(step.target || '').trim(); if (!target) return ''; return this.keyPresets.some(item => item.value === target) ? target : '__custom__'; }, isExecutionExpanded(index, step = null) { const expanded = !!this.expandedExecutionMenus[index]; if (expanded && step) { this.ensureStepExecution(step); } return expanded; }, ensureStepExecution(step) { if (!step.execution || typeof step.execution !== 'object' || Array.isArray(step.execution)) { step.execution = {}; } if (!step.execution.retry || typeof step.execution.retry !== 'object') { step.execution.retry = { enabled: false, max_attempts: 2, interval: 0.3 }; } if (!step.execution.verification || typeof step.execution.verification !== 'object') { step.execution.verification = { enabled: false, match: 'any', timeout: 2, poll_interval: 0.1, conditions: [] }; } if (!Array.isArray(step.execution.verification.conditions)) { step.execution.verification.conditions = []; } if (!step.execution.click_mode) step.execution.click_mode = 'inherit'; return step.execution; }, toggleExecutionMenu(index, step) { this.ensureStepExecution(step); this.expandedExecutionMenus = { ...this.expandedExecutionMenus, [index]: !this.isExecutionExpanded(index) }; }, addVerificationCondition(step) { const execution = this.ensureStepExecution(step); execution.verification.conditions.push({ target: step.target || '', state: 'absent' }); }, setVerificationEnabled(step, enabled) { const execution = this.ensureStepExecution(step); execution.verification.enabled = !!enabled; if (enabled && execution.verification.conditions.length === 0) { this.addVerificationCondition(step); } }, removeVerificationCondition(step, conditionIndex) { const execution = this.ensureStepExecution(step); execution.verification.conditions.splice(conditionIndex, 1); }, getExecutionSummary(step) { const execution = step.execution && typeof step.execution === 'object' ? step.execution : {}; const parts = []; if (execution.click_mode === 'dom_safe') parts.push('后台 DOM'); if (execution.click_mode === 'cdp_mouse') parts.push('CDP 鼠标'); if (execution.retry?.enabled) parts.push(`最多 ${Number(execution.retry.max_attempts || 2)} 次`); if (execution.verification?.enabled) parts.push('结果验证'); return parts.join(' · ') || '默认'; }, normalizeHintStepValue(step) { const current = (step && step.value && typeof step.value === 'object' && !Array.isArray(step.value)) ? step.value : {}; const tone = String(current.tone || '').trim().toLowerCase(); return { title: String(current.title || '提示'), text: String(current.text || ''), tone: ['info', 'success', 'warning', 'danger'].includes(tone) ? tone : 'info' }; }, isDefaultHintStepValue(step) { const normalized = this.normalizeHintStepValue(step); return ( normalized.title === '提示' && normalized.text === '这是一条只读提示,不会在执行时触发页面操作。' && normalized.tone === 'info' ); }, syncHintEditorState() { const next = { ...this.expandedHintEditors }; (this.workflow || []).forEach((step, index) => { if (step.action !== 'READONLY_HINT') { delete next[index]; return; } if (!Object.prototype.hasOwnProperty.call(next, index)) { next[index] = this.isDefaultHintStepValue(step); } }); Object.keys(next).forEach(key => { const idx = Number(key); if (!Number.isInteger(idx) || !(this.workflow || [])[idx] || (this.workflow || [])[idx].action !== 'READONLY_HINT') { delete next[key]; } }); const prevKeys = Object.keys(this.expandedHintEditors); const nextKeys = Object.keys(next); if ( prevKeys.length === nextKeys.length && nextKeys.every(key => this.expandedHintEditors[key] === next[key]) ) { return; } this.expandedHintEditors = next; }, isHintExpanded(index) { return !!this.expandedHintEditors[index]; }, toggleHintExpand(index) { this.expandedHintEditors = { ...this.expandedHintEditors, [index]: !this.isHintExpanded(index) }; }, getHintToneClasses(step) { const tone = this.normalizeHintStepValue(step).tone; // 语气配色统一走 uwa 主题层(dashboard-reference.css / dashboard-dark.css) const toneMap = { info: 'uwa-wf-hint is-info', success: 'uwa-wf-hint is-success', warning: 'uwa-wf-hint is-warning', danger: 'uwa-wf-hint is-danger' }; return toneMap[tone] || toneMap.info; }, getHintStepClasses(step) { return 'shadow-none ' + this.getHintToneClasses(step); }, normalizeScriptTarget(target) { return String(target || '').trim().replace(/^file:\/+/i, '').replace(/^scripts:\/+/i, 'scripts/'); }, getJsMode(index, step) { const clean = this.normalizeScriptTarget(step?.target); if (clean) { return 'file'; } if (step?.value && typeof step.value === 'object' && !Array.isArray(step.value)) { return 'file'; } return 'inline'; }, setJsMode(index, step, mode) { if (mode === 'file') { if (!step.target && this.availableScripts.length > 0) { step.target = this.availableScripts[0].path; } if (typeof step.value === 'string' && step.value.trim().startsWith('{')) { try { step.value = JSON.parse(step.value); } catch (_) {} } else if (!step.value || typeof step.value === 'string') { step.value = {}; } } else { step.target = ''; if (typeof step.value !== 'string') { step.value = 'return document.title;'; } } }, getJsLifecycle(step) { const execution = step && step.execution && typeof step.execution === 'object' ? step.execution : {}; const value = String(execution.lifecycle || execution.script_lifecycle || 'workflow').toLowerCase(); return ['workflow', 'resident', 'step'].includes(value) ? value : 'workflow'; }, setJsLifecycle(step, lifecycle) { if (!step) return; if (!step.execution || typeof step.execution !== 'object') step.execution = {}; step.execution.lifecycle = ['workflow', 'resident', 'step'].includes(lifecycle) ? lifecycle : 'workflow'; }, async loadAvailableScripts(force = false) { if (this.availableScripts.length > 0 && !force) return; this.loadingScripts = true; try { const res = await this.authJsonRequest('/api/config/workflow/scripts'); this.availableScripts = Array.isArray(res?.scripts) ? res.scripts : []; } catch (e) { console.error('[WorkflowPanel] 获取脚本列表失败:', e); } finally { this.loadingScripts = false; } }, isJsPreviewExpanded(index) { return !!this.expandedJsPreviews[index]; }, async toggleJsPreview(index, step) { const next = !this.isJsPreviewExpanded(index); this.expandedJsPreviews = { ...this.expandedJsPreviews, [index]: next }; if (next && step.target) { await this.fetchScriptPreviewContent(step.target); } }, async fetchScriptPreviewContent(target) { const cleanPath = this.normalizeScriptTarget(target); if (!cleanPath || this.scriptPreviewContents[cleanPath]) return; this.loadingScriptPreviews = { ...this.loadingScriptPreviews, [cleanPath]: true }; try { const res = await this.authJsonRequest('/api/config/workflow/script-content?path=' + encodeURIComponent(cleanPath)); if (res && res.content !== undefined) { this.scriptPreviewContents = { ...this.scriptPreviewContents, [cleanPath]: res }; } } catch (e) { console.warn('[WorkflowPanel] 获取脚本内容预览失败:', e); this.scriptPreviewContents = { ...this.scriptPreviewContents, [cleanPath]: { content: '// 无法加载脚本内容: ' + (e.message || e), description: '' } }; } finally { this.loadingScriptPreviews = { ...this.loadingScriptPreviews, [cleanPath]: false }; } }, getScriptPreviewData(step) { const cleanPath = this.normalizeScriptTarget(step?.target); return this.scriptPreviewContents[cleanPath] || null; }, insertMacro(index, step, macroText) { const textarea = document.getElementById('wf-js-param-' + index) || document.getElementById('wf-js-inline-' + index); if (textarea) { const start = textarea.selectionStart ?? textarea.value.length; const end = textarea.selectionEnd ?? textarea.value.length; const text = textarea.value || ''; const next = text.slice(0, start) + macroText + text.slice(end); textarea.value = next; textarea.dispatchEvent(new Event('input')); this.$nextTick(() => { textarea.focus(); const newPos = start + macroText.length; textarea.setSelectionRange(newPos, newPos); }); } else { if (typeof step.value === 'string') { step.value = (step.value ? step.value + ' ' : '') + macroText; } else if (step.value && typeof step.value === 'object') { step.value = { ...step.value, macro: macroText }; } } }, formatJsStepValue(step) { if (typeof step.value === 'string') return step.value; if (step.value && typeof step.value === 'object') { try { return JSON.stringify(step.value, null, 2); } catch (_) { return '{}'; } } return ''; }, updateJsStepParamValue(step, rawText) { const trimmed = String(rawText || '').trim(); if (trimmed.startsWith('{') && trimmed.endsWith('}')) { try { step.value = JSON.parse(trimmed); return; } catch (_) {} } step.value = rawText; }, getCoordProp(step, key, defaultVal = '') { if (!step || !step.value || typeof step.value !== 'object') { return defaultVal; } const val = step.value[key]; return (val !== undefined && val !== null) ? val : defaultVal; }, updateCoordValue(step, key, val) { const base = (step.value && typeof step.value === 'object' && !Array.isArray(step.value)) ? step.value : {}; const num = val === '' ? '' : Number(val); step.value = { ...base, [key]: isNaN(num) ? val : num }; } }, template: `
{{ (getScriptPreviewData(step) || {}).content || '// 点击上方预览按钮加载脚本内容' }}