// ==================== 配置 Tab 组件 (拆分版) ==================== window.ConfigTab = { name: 'ConfigTab', props: { currentDomain: { type: String, default: null }, currentConfig: { type: Object, default: null } }, emits: [ 'add-selector', 'remove-selector', 'update-selector-key', 'test-selector', 'add-step', 'remove-step', 'move-step', 'action-change', 'show-templates', 'update-image-config', 'reload-config' ], // 注册子组件(确保模板可解析) components: { 'selector-panel': window.SelectorPanel, 'image-config-panel': window.ImageConfigPanel, 'stream-config-panel': window.StreamConfigPanel, 'workflow-panel': window.WorkflowPanel, 'file-paste-panel': window.FilePastePanel, 'prompt-padding-panel': window.PromptPaddingPanel, 'preset-transfer': window.PresetTransfer, 'adapter-panel': window.AdapterPanel }, data() { return { // 🆕 预设管理 selectedPreset: '主预设', defaultPreset: '主预设', availablePresets: [], presetLoading: false, newPresetName: '', showNewPresetInput: false, renamePresetName: '', showRenamePresetInput: false, pendingPresetTransfer: 0, // 当前配置分类 activeWorkspaceSection: 'selectors', // 各配置面板折叠状态(默认展开) collapsedPanels: { selectors: false, media: false, response: false, filePaste: false, promptPadding: false }, presetSectionDrafts: { file_paste: [], prompt_padding: [] }, advancedConfigSaving: false, isolatedTabCreating: false, sharedTabCreating: false, showConfigCompareDialog: false, compareMainLoading: false, compareMainError: '', compareMainPresetName: '', compareMainMatchMode: '', compareMainPath: '', compareMainSource: {}, compareLocalOriginalText: '', compareLocalDraft: '', compareMainOriginalText: '', compareMainDraft: '', compareSavingLocal: false, advancedConfigSaveSeq: 0, advancedConfigSaveQueue: null, streamConfigSaveSeq: 0, streamConfigSaveQueue: null, // 默认配置 defaultImageConfig: { enabled: false, modalities: { image: { enabled: false, run_policy: 'disabled', quick_probe_timeout_seconds: 1.0, late_wait_timeout_seconds: 45.0, blind_wait_timeout_seconds: 1.0 }, audio: { enabled: false, run_policy: 'disabled', quick_probe_timeout_seconds: 1.0, capture_timeout_seconds: 12.0 }, video: { enabled: false, run_policy: 'disabled', quick_probe_timeout_seconds: 1.0, late_wait_timeout_seconds: 90.0 } }, selector: 'img', audio_selector: 'audio, audio source', video_selector: 'video, video source', container_selector: null, debounce_seconds: 2.0, wait_for_load: true, load_timeout_seconds: 5.0, download_blobs: true, audio_capture_enabled: true, src_allow_patterns: [], max_size_mb: 10, canvas_export_mime: 'image/jpeg', canvas_export_quality: 0.88, audio_network_capture: { enabled: false, timeout_seconds: 2.5, transport: 'page_websocket_probe', url_patterns: ['voicegenie', 'speech', 'audio', 'tts'], extractor: 'voicegenie_ogg_pages', settle_seconds: 0.35, max_payload_bytes: 10 * 1024 * 1024 }, mode: 'all' }, defaultStreamConfig: { mode: 'dom', request_transport: { mode: 'workflow', profile: '', options: {} }, send_confirmation: { attachment_sensitivity: 'medium', post_click_observe_window: 1.8, pre_retry_probe_window: 0.12, retry_observe_window: 0.9, attachment_observe_window: 6.0, max_retry_count: 2, retry_interval: 0.6, retry_cooldown_window: 1.5, retry_action: 'click_send_btn', retry_key_combo: 'Enter', retry_on_unconfirmed_send: true, accept_attachment_change: false, accept_attachment_disappear: false, accept_probe_confirmation: true, retry_block_on_stop_button: true, retry_block_if_generating: true, trust_network_activity: true, trust_generating_indicator: true, trust_send_disabled_with_input_shrink: true }, hard_timeout: 300, network: null } }; }, computed: { workspaceSections() { return [ { id: 'selectors', title: '元素选择器', subtitle: '定位关键网页元素', heading: '定义网页的关键位置', description: '先配置输入框、发送按钮和回复容器,再按需补充辅助元素。' }, { id: 'input', title: '输入处理', subtitle: '附件与长文本', heading: '你要给 AI 发送什么?', description: '普通文字无需额外设置。发文件、发长文时,再开启相应能力。' }, { id: 'response', title: '响应解析', subtitle: '提取与流式输出', heading: '把网页回复转换为 API 响应', description: '配置响应提取与流式输出策略,匹配当前站点的生成方式。' }, { id: 'media', title: '媒体提取', subtitle: '图片、音频与视频', heading: '你想收到什么内容?', description: '接收 AI 回复里的媒体内容。上传文件请到「输入处理」。' }, { id: 'workflow', title: '请求工作流', subtitle: '编排自动化步骤', heading: '串起一次完整的请求', description: '编排输入、发送、等待与提取动作,为当前预设定义执行顺序。' }, { id: 'advanced', title: '高级功能', subtitle: '会话隔离与自愈', heading: '遇到问题,再按需开启', description: '登录互相影响、输入不稳定、消息没发出?只处理你正在遇到的那一项。' }, { id: 'maintenance', title: '维护与巡检', subtitle: '健康检查与更新', heading: '站点适配器维护', description: '检查选择器是否还能命中、写法是否稳健,并同步官方最新的站点配置。' }, ]; }, activeWorkspaceMeta() { return this.workspaceSections.find(s => s.id === this.activeWorkspaceSection) || this.workspaceSections[0]; }, // 🆕 当前预设的配置数据 presetConfig() { if (!this.currentConfig) return null; const presets = this.currentConfig.presets; if (!presets) return this.currentConfig; // 兼容旧格式 return presets[this.selectedPreset] || presets[this.defaultPreset] || presets['主预设'] || Object.values(presets)[0] || null; }, imageConfig() { if (!this.presetConfig) return this.defaultImageConfig; const current = this.presetConfig.image_extraction || {}; const currentModalities = (current && current.modalities) || {}; const mergeModality = (type) => { const defaults = ((this.defaultImageConfig.modalities || {})[type]) || {}; const value = currentModalities[type]; const enabledRunPolicy = type === 'audio' ? 'probe_if_trigger_found' : 'on_signal'; if (value && typeof value === 'object' && !Array.isArray(value)) { const enabled = !!value.enabled; const hasRunPolicy = Object.prototype.hasOwnProperty.call(value, 'run_policy') && !!value.run_policy; return { ...defaults, ...value, enabled, run_policy: hasRunPolicy ? value.run_policy : (enabled ? enabledRunPolicy : 'disabled') }; } return { ...defaults, enabled: !!value, run_policy: value ? enabledRunPolicy : 'disabled' }; }; return { ...this.defaultImageConfig, ...current, modalities: { image: mergeModality('image'), audio: mergeModality('audio'), video: mergeModality('video') }, audio_network_capture: { ...(this.defaultImageConfig.audio_network_capture || {}), ...((current && current.audio_network_capture) || {}) } }; }, streamConfig() { if (!this.presetConfig) return this.defaultStreamConfig; const streamConfig = this.presetConfig.stream_config || {}; return { ...this.defaultStreamConfig, ...streamConfig, mode: streamConfig.mode || this.defaultStreamConfig.mode, request_transport: { ...(this.defaultStreamConfig.request_transport || {}), ...((streamConfig && streamConfig.request_transport) || {}), options: { ...((this.defaultStreamConfig.request_transport && this.defaultStreamConfig.request_transport.options) || {}), ...((streamConfig && streamConfig.request_transport && streamConfig.request_transport.options) || {}) } }, send_confirmation: { ...(this.defaultStreamConfig.send_confirmation || {}), // 修复:send_confirmation 的权威存储已迁移到 file_paste(后端 engine.py 会把 // stream_config 里的同名键剥离并 merge 进 file_paste),此处只从 stream_config // 读会恒为默认值,并在用户改动时把默认值整份写回、覆盖真实配置。 ...((streamConfig && streamConfig.send_confirmation) || {}), ...(((this.presetConfig && this.presetConfig.file_paste) || {}).send_confirmation || {}) }, hard_timeout: streamConfig.hard_timeout || this.defaultStreamConfig.hard_timeout, network: streamConfig.network || this.defaultStreamConfig.network }; }, filePasteConfigRef() { return this.getPresetMutableSection('file_paste'); }, promptPaddingConfigRef() { return this.getPresetMutableSection('prompt_padding'); }, siteAdvancedConfig() { if (!this.currentConfig) { return { independent_cookies: false, independent_cookies_auto_takeover: false, input_box_stability_wait_enabled: false, input_box_stability_wait_after_new_chat_only: true, input_box_stability_wait_timeout: 1.5, url_transition_wait_on_new_chat: false, url_transition_wait_patterns: [], send_confirmation_check_enabled: false, send_confirmation_check_timeout: 1.5, skip_new_chat_on_retry: false }; } const siteAdvanced = (this.currentConfig.advanced && typeof this.currentConfig.advanced === 'object') ? this.currentConfig.advanced : {}; const presetAdvanced = (this.presetConfig && this.presetConfig.advanced && typeof this.presetConfig.advanced === 'object') ? this.presetConfig.advanced : {}; const timingAdvanced = { input_box_stability_wait_enabled: false, input_box_stability_wait_after_new_chat_only: true, input_box_stability_wait_timeout: 1.5, url_transition_wait_on_new_chat: false, url_transition_wait_patterns: [], send_confirmation_check_enabled: false, send_confirmation_check_timeout: 1.5, skip_new_chat_on_retry: false, ...siteAdvanced, ...presetAdvanced }; return { independent_cookies: !!siteAdvanced.independent_cookies, independent_cookies_auto_takeover: !!siteAdvanced.independent_cookies_auto_takeover, input_box_stability_wait_enabled: !!timingAdvanced.input_box_stability_wait_enabled, input_box_stability_wait_after_new_chat_only: !!timingAdvanced.input_box_stability_wait_after_new_chat_only, input_box_stability_wait_timeout: this.sanitizeInputStabilityWaitTimeout( timingAdvanced.input_box_stability_wait_timeout ), url_transition_wait_on_new_chat: !!timingAdvanced.url_transition_wait_on_new_chat, url_transition_wait_patterns: this.sanitizeUrlTransitionWaitPatterns( timingAdvanced.url_transition_wait_patterns ), send_confirmation_check_enabled: !!timingAdvanced.send_confirmation_check_enabled, send_confirmation_check_timeout: this.sanitizeSendConfirmationCheckTimeout( timingAdvanced.send_confirmation_check_timeout ), skip_new_chat_on_retry: !!timingAdvanced.skip_new_chat_on_retry }; }, compareLocalParsed() { return this.parseConfigCompareDraft(this.compareLocalDraft); }, compareMainParsed() { return this.parseConfigCompareDraft(this.compareMainDraft); }, compareLocalDirty() { return this.compareLocalDraft !== this.compareLocalOriginalText; }, compareMainDirty() { return this.compareMainDraft !== this.compareMainOriginalText; }, compareLocalSummaryItems() { if (!this.compareLocalParsed.valid) return []; return this.buildConfigCompareSummaryItems(this.compareLocalParsed.value); }, compareMainSummaryItems() { if (!this.compareMainParsed.valid) return []; return this.buildConfigCompareSummaryItems(this.compareMainParsed.value); }, compareFieldDiffs() { if (!this.compareLocalParsed.valid || !this.compareMainParsed.valid) return []; return this.buildConfigCompareFieldDiffs( this.compareLocalParsed.value, this.compareMainParsed.value ); }, compareDifferentCount() { return this.compareFieldDiffs.filter(item => item.status !== 'same').length; }, compareSameCount() { return this.compareFieldDiffs.filter(item => item.status === 'same').length; } }, methods: { stagePresetOperation(kind, name) { if (!this.pendingPresetTransfer) return false; const presets = this.currentConfig.presets, old = this.selectedPreset; if (['create','rename'].includes(kind) && (!window.PresetTransferSupport.safeName(name) || Object.hasOwn(presets,name))) { alert('请输入有效且未使用的预设名称。'); return true; } this.flushMutableSectionDrafts(); if (kind === 'create') { presets[name] = JSON.parse(JSON.stringify(presets[old])); this.selectedPreset = name; } if (kind === 'rename') { presets[name] = presets[old]; delete presets[old]; this.selectedPreset = name; } if (kind === 'delete') { delete presets[old]; this.selectedPreset = Object.keys(presets)[0]; } if (kind === 'default' || (['rename','delete'].includes(kind) && this.defaultPreset === old)) { this.defaultPreset = this.selectedPreset; this.currentConfig.default_preset = this.selectedPreset; } this.pendingPresetTransfer++; this.availablePresets = Object.keys(presets); this.ensurePresetMutableSections(); this.showNewPresetInput = false; this.showRenamePresetInput = false; this.newPresetName = ''; this.renamePresetName = ''; alert('预设草稿已更新,请点击「保存配置」完成保存。'); return true; }, beginPresetRename() { this.showRenamePresetInput = true; this.renamePresetName = this.selectedPreset; this.showNewPresetInput = false; this.newPresetName = ''; this.$nextTick(() => { this.$refs.renamePresetInput?.focus(); this.$refs.renamePresetInput?.select(); }); }, applyPresetTransfer(payload) { if (payload.domain !== this.currentDomain) return; this.flushMutableSectionDrafts(); this.pendingPresetTransfer++; if (!this.currentConfig.presets) { const legacy = JSON.parse(JSON.stringify(this.currentConfig)); Object.keys(this.currentConfig).forEach(k => delete this.currentConfig[k]); this.currentConfig.presets = { [this.selectedPreset || '主预设']: legacy }; this.currentConfig.default_preset = this.selectedPreset || '主预设'; } Object.entries(payload.presets).forEach(([name, config]) => { this.currentConfig.presets[name] = config; }); if (payload.settings) Object.entries(payload.settings).forEach(([key,value]) => { this.currentConfig[key] = value; }); this.availablePresets = Object.keys(this.currentConfig.presets); if (payload.select) this.selectedPreset = payload.select; this.ensurePresetMutableSections(); }, // R2-8:维护面板使用的请求函数(带鉴权;检查全部站点更新可能较慢,超时放宽到 30 秒) adapterRequest(url, options = {}) { return this.fetchJson(url, { ...options, headers: this.buildAuthHeaders(options.headers || {}) }, { timeoutMs: 30000 }); }, onAdapterUpdated() { this.$emit('reload-config'); }, buildAuthHeaders(extraHeaders = {}) { const token = String(window.getDashboardAuthToken ? window.getDashboardAuthToken() : '').trim(); const headers = { ...extraHeaders }; if (token) { headers['Authorization'] = 'Bearer ' + token; } return headers; }, async fetchJson(url, options = {}, requestOptions = {}) { const timeoutMs = Number(requestOptions.timeoutMs || 10000); const fetchOptions = { ...options }; let timeoutId = null; let controller = null; if (timeoutMs > 0 && typeof AbortController !== 'undefined') { controller = new AbortController(); fetchOptions.signal = controller.signal; timeoutId = setTimeout(() => controller.abort(), timeoutMs); } try { const response = await fetch(url, fetchOptions); const data = await response.json().catch(() => ({})); if (!response.ok) { throw new Error(data.detail || ('HTTP ' + response.status)); } return data; } catch (error) { if (error && error.name === 'AbortError') { throw new Error('请求超时,请稍后重试'); } throw error; } finally { if (timeoutId) { clearTimeout(timeoutId); } } }, isPlainConfigObject(value) { return !!value && typeof value === 'object' && !Array.isArray(value); }, canAssignObjectProperty(target, key) { if (!this.isPlainConfigObject(target)) return false; try { const descriptor = Object.getOwnPropertyDescriptor(target, key); if (!descriptor) { return Object.isExtensible(target); } if (Object.prototype.hasOwnProperty.call(descriptor, 'writable')) { return !!descriptor.writable; } return typeof descriptor.set === 'function'; } catch (_) { return false; } }, cloneConfigSection(value) { if (Array.isArray(value)) { return value.map(item => this.cloneConfigSection(item)); } if (this.isPlainConfigObject(value)) { return Object.keys(value).reduce((result, key) => { result[key] = this.cloneConfigSection(value[key]); return result; }, {}); } return value; }, getPresetSectionDraftSlots(sectionKey) { let slots = this.presetSectionDrafts[sectionKey]; if (!Array.isArray(slots)) { slots = slots && typeof slots === 'object' ? [slots] : []; this.presetSectionDrafts[sectionKey] = slots; } return slots; }, getPresetSectionDraft(sectionKey, preset, source) { const slots = this.getPresetSectionDraftSlots(sectionKey); let slot = slots.find(item => item && item.preset === preset); if (!slot) { slot = { preset, source: null, value: {} }; slots.push(slot); } if (slot.source !== source) { slot.preset = preset; slot.source = source; slot.value = this.isPlainConfigObject(source) ? this.cloneConfigSection(source) : {}; } return slot.value; }, getPresetMutableSection(sectionKey) { const pc = this.presetConfig; if (!this.isPlainConfigObject(pc)) { return this.getPresetSectionDraft(sectionKey, null, null); } return this.getPresetSectionDraft(sectionKey, pc, pc[sectionKey]); }, ensurePresetMutableSections() { this.getPresetMutableSection('file_paste'); this.getPresetMutableSection('prompt_padding'); }, isPresetSectionDraftDirty(source, draft) { if (!this.isPlainConfigObject(source)) { return this.isPlainConfigObject(draft) && Object.keys(draft).length > 0; } try { return JSON.stringify(source) !== JSON.stringify(draft); } catch (_) { return true; } }, shouldFlushPresetSectionDraft(sectionKey, preset, source, draft) { if (!this.isPlainConfigObject(preset) || !this.isPlainConfigObject(draft)) { return false; } if (!Object.prototype.hasOwnProperty.call(preset, sectionKey)) { return Object.keys(draft).length > 0; } return this.isPresetSectionDraftDirty(source, draft); }, flushPresetSectionDraft(sectionKey, slot) { const preset = slot && slot.preset; if (!slot || !this.shouldFlushPresetSectionDraft(sectionKey, preset, slot.source, slot.value)) { return false; } if (!this.canAssignObjectProperty(preset, sectionKey)) { return false; } const nextValue = this.cloneConfigSection(slot.value); preset[sectionKey] = nextValue; slot.source = nextValue; slot.value = this.cloneConfigSection(nextValue); return true; }, flushMutableSectionDrafts() { let changed = false; ['file_paste', 'prompt_padding'].forEach(sectionKey => { this.getPresetSectionDraftSlots(sectionKey).forEach(slot => { changed = this.flushPresetSectionDraft(sectionKey, slot) || changed; }); }); return changed; }, notifyCompare(message, type = 'info') { if (this.$parent && typeof this.$parent.notify === 'function') { this.$parent.notify(message, type); return; } if (type === 'error') { alert(message); } else { console.info(message); } }, sortConfigCompareValue(value) { if (Array.isArray(value)) { return value.map(item => this.sortConfigCompareValue(item)); } if (value && typeof value === 'object') { const sorted = {}; Object.keys(value) .sort((left, right) => String(left).localeCompare(String(right), 'zh-CN')) .forEach(key => { sorted[key] = this.sortConfigCompareValue(value[key]); }); return sorted; } return value; }, getConfigCompareStableText(value) { return JSON.stringify(this.sortConfigCompareValue(value)); }, formatConfigCompareJson(value) { const normalized = (value && typeof value === 'object' && !Array.isArray(value)) ? value : {}; return JSON.stringify(this.sortConfigCompareValue(normalized), null, 2); }, validateConfigCompareObject(parsed) { if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { throw new Error('JSON 顶层必须是对象'); } if ( parsed.presets !== undefined || parsed.default_preset !== undefined ) { throw new Error('这里只接受单个预设配置对象,不要包含 presets/default_preset'); } if ( parsed.selectors !== undefined && ( parsed.selectors === null || typeof parsed.selectors !== 'object' || Array.isArray(parsed.selectors) ) ) { throw new Error('selectors 必须是对象'); } if (parsed.workflow !== undefined && !Array.isArray(parsed.workflow)) { throw new Error('workflow 必须是数组'); } if ( parsed.advanced !== undefined && ( parsed.advanced === null || typeof parsed.advanced !== 'object' || Array.isArray(parsed.advanced) ) ) { throw new Error('advanced 必须是对象'); } }, parseConfigCompareDraft(rawText) { const text = String(rawText || '').trim(); if (!text) { return { valid: false, error: 'JSON 不能为空', value: null }; } try { const parsed = JSON.parse(text); this.validateConfigCompareObject(parsed); return { valid: true, error: '', value: parsed }; } catch (error) { return { valid: false, error: error && error.message ? error.message : 'JSON 解析失败', value: null }; } }, buildConfigCompareSummaryItems(config) { const selectors = (config && config.selectors && typeof config.selectors === 'object' && !Array.isArray(config.selectors)) ? Object.keys(config.selectors).length : 0; const workflowSteps = Array.isArray(config && config.workflow) ? config.workflow.length : 0; const rawStreamMode = String((config && config.stream_config && config.stream_config.mode) || 'dom').trim().toLowerCase(); const streamMode = rawStreamMode === 'network' ? '网络模式' : (rawStreamMode === 'dom' ? 'DOM 模式' : (rawStreamMode || 'DOM 模式')); const imageEnabled = !!(config && config.image_extraction && config.image_extraction.enabled); const filePasteEnabled = !!(config && config.file_paste && config.file_paste.enabled); const promptPaddingEnabled = !!(config && config.prompt_padding && config.prompt_padding.enabled); return [ { label: '选择器', value: String(selectors) }, { label: '工作流', value: workflowSteps + ' 步' }, { label: '流式', value: streamMode, compact: true }, { label: '图片提取', value: imageEnabled ? '开启' : '关闭' }, { label: '文件粘贴', value: filePasteEnabled ? '开启' : '关闭' }, { label: '开头注入', value: promptPaddingEnabled ? '开启' : '关闭' } ]; }, buildConfigCompareFieldDiffs(localConfig, mainConfig) { const labelMap = { selectors: '选择器', workflow: '工作流', stream_config: '流式配置', image_extraction: '图片提取', file_paste: '文件粘贴', prompt_padding: '开头注入', advanced: '高级配置', stealth: '低熵模式', extractor_id: '提取器', extractor_verified: '提取器验证' }; const priorityKeys = [ 'selectors', 'workflow', 'stream_config', 'image_extraction', 'file_paste', 'prompt_padding', 'advanced', 'stealth', 'extractor_id', 'extractor_verified' ]; const local = localConfig || {}; const main = mainConfig || {}; const restKeys = new Set([ ...Object.keys(local), ...Object.keys(main) ]); const orderedKeys = []; priorityKeys.forEach(key => { if (restKeys.has(key)) { orderedKeys.push(key); restKeys.delete(key); } }); Array.from(restKeys) .sort((left, right) => String(left).localeCompare(String(right), 'zh-CN')) .forEach(key => orderedKeys.push(key)); return orderedKeys.map(key => { const hasLocal = Object.prototype.hasOwnProperty.call(local, key); const hasMain = Object.prototype.hasOwnProperty.call(main, key); let status = 'same'; if (hasLocal && hasMain) { status = this.getConfigCompareStableText(local[key]) === this.getConfigCompareStableText(main[key]) ? 'same' : 'different'; } else if (hasLocal) { status = 'local_only'; } else if (hasMain) { status = 'main_only'; } return { key, label: labelMap[key] || key, status }; }); }, getConfigCompareDiffClass(status) { if (status === 'same') { return 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300'; } if (status === 'different') { return 'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-800 dark:bg-amber-900/30 dark:text-amber-300'; } if (status === 'main_only') { return 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-300'; } return 'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-800 dark:bg-rose-900/30 dark:text-rose-300'; }, getConfigCompareDiffText(status) { if (status === 'same') return '一致'; if (status === 'different') return '内容不同'; if (status === 'main_only') return '仅 main 有'; return '仅本地有'; }, getConfigCompareMatchLabel(matchMode) { if (matchMode === 'exact') return '已命中同名预设'; if (matchMode === 'default') return 'main 默认预设回退'; if (matchMode === 'main_preset') return 'main 主预设回退'; if (matchMode === 'first') return 'main 首个预设回退'; if (matchMode === 'legacy_flat') return 'main 旧版扁平配置'; return ''; }, syncConfigCompareLocalDraft(force = false) { const nextText = this.formatConfigCompareJson(this.presetConfig || {}); this.compareLocalOriginalText = nextText; if (force || !this.compareLocalDirty) { this.compareLocalDraft = nextText; } }, resetConfigCompareState() { this.showConfigCompareDialog = false; this.compareMainLoading = false; this.compareMainError = ''; this.compareMainPresetName = ''; this.compareMainMatchMode = ''; this.compareMainPath = ''; this.compareMainSource = {}; this.compareLocalOriginalText = ''; this.compareLocalDraft = ''; this.compareMainOriginalText = ''; this.compareMainDraft = ''; this.compareSavingLocal = false; }, closeConfigCompareDialog() { if ( (this.compareLocalDirty || this.compareMainDirty) && !window.confirm('关闭后未保存的比对草稿会丢失,确定关闭吗?') ) { return; } this.resetConfigCompareState(); }, async openConfigCompare() { if (!this.currentDomain || !this.currentConfig) return; if (!this.presetConfig && this.availablePresets.length) { this.selectedPreset = this.selectedPreset || this.defaultPreset || this.availablePresets[0] || '主预设'; } this.showConfigCompareDialog = true; this.compareMainError = ''; this.compareMainPresetName = ''; this.compareMainMatchMode = ''; this.compareMainPath = ''; this.compareMainSource = {}; this.compareMainOriginalText = ''; this.compareMainDraft = ''; this.syncConfigCompareLocalDraft(true); this.$nextTick(() => { const root = this.$el && this.$el.querySelector ? this.$el.querySelector('[data-config-compare-root]') : null; if (root) { root.style.display = 'flex'; } }); await this.loadMainBranchCompareConfig(); }, async openConfigCompareForPreset(presetName) { const targetPreset = String(presetName || '').trim(); if (targetPreset) { if (!this.availablePresets.length) { await this.loadPresets(); } if (this.availablePresets.includes(targetPreset)) { this.selectedPreset = targetPreset; } } await this.openConfigCompare(); }, formatGitCompareErrorMessage(error) { if (typeof window.formatGitCompareErrorText === 'function') { return window.formatGitCompareErrorText(error); } const raw = String((error && error.message) || error || '').trim(); return raw || '读取官方配置失败'; }, formatOfficialConfigSourceTime(value) { const raw = String(value || '').trim(); if (!raw) return ''; const timestamp = new Date(raw); if (Number.isNaN(timestamp.getTime())) return raw; return timestamp.toLocaleString('zh-CN', { hour12: false }); }, async loadMainBranchCompareConfig() { if (!this.currentDomain) return; const domain = this.currentDomain; const preset = this.selectedPreset || ''; this.compareMainLoading = true; this.compareMainError = ''; try { const queryPreset = encodeURIComponent(preset); const data = await this.fetchJson( '/api/sites/' + encodeURIComponent(domain) + '/main-branch-config?preset_name=' + queryPreset, { headers: this.buildAuthHeaders() }, { timeoutMs: 22000 } ); if (domain !== this.currentDomain || preset !== (this.selectedPreset || '')) return; const formatted = this.formatConfigCompareJson(data.config || {}); this.compareMainPresetName = String(data.preset_name || '').trim() || '主预设'; this.compareMainMatchMode = String(data.match_mode || '').trim(); this.compareMainPath = String(data.path || 'config/sites/index.json').trim() || 'config/sites/index.json'; this.compareMainSource = { ...(data.source || {}) }; this.compareMainOriginalText = formatted; this.compareMainDraft = formatted; } catch (error) { if (domain !== this.currentDomain || preset !== (this.selectedPreset || '')) return; console.error('加载 main 分支配置失败:', error); this.compareMainError = this.formatGitCompareErrorMessage(error); this.compareMainPresetName = ''; this.compareMainMatchMode = ''; this.compareMainPath = ''; this.compareMainSource = {}; this.compareMainOriginalText = ''; this.compareMainDraft = ''; } finally { if (domain === this.currentDomain && preset === (this.selectedPreset || '')) { this.compareMainLoading = false; } } }, resetConfigCompareLocalDraft() { const changed = this.compareLocalDirty; this.compareLocalDraft = this.compareLocalOriginalText; this.notifyCompare(changed ? '已撤销左侧草稿更改' : '左侧没有可撤销的改动', changed ? 'success' : 'info'); }, resetConfigCompareMainDraft() { const changed = this.compareMainDirty; this.compareMainDraft = this.compareMainOriginalText; this.notifyCompare(changed ? '已恢复右侧参考草稿' : '右侧没有可恢复的改动', changed ? 'success' : 'info'); }, async saveConfigCompareLocalDraft() { if (!this.currentDomain || !this.selectedPreset) return; if (!this.compareLocalParsed.valid) { this.notifyCompare('左侧本地草稿 JSON 无效,不能保存', 'warning'); return; } const domain = this.currentDomain; const preset = this.selectedPreset; const parsedValue = this.compareLocalParsed.value; this.compareSavingLocal = true; try { const data = await this.fetchJson( '/api/sites/' + encodeURIComponent(domain) + '/preset-config', { method: 'PUT', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify({ preset_name: preset, config: parsedValue }) }, { timeoutMs: 12000 } ); if (domain !== this.currentDomain || preset !== this.selectedPreset) return; const resolvedPreset = String(data.preset_name || preset).trim() || preset; const savedConfig = data.config || parsedValue; const cloned = JSON.parse(JSON.stringify(savedConfig)); if (this.currentConfig) { if (this.currentConfig.presets && typeof this.currentConfig.presets === 'object') { this.currentConfig.presets[resolvedPreset] = cloned; } else { Object.keys(this.currentConfig).forEach(key => { delete this.currentConfig[key]; }); Object.assign(this.currentConfig, cloned); } } this.selectedPreset = resolvedPreset; this.compareLocalOriginalText = this.formatConfigCompareJson(savedConfig); this.compareLocalDraft = this.compareLocalOriginalText; this.notifyCompare('当前预设已保存', 'success'); } catch (error) { if (domain !== this.currentDomain || preset !== this.selectedPreset) return; console.error('保存当前预设失败:', error); this.notifyCompare('保存失败: ' + error.message, 'error'); } finally { if (domain === this.currentDomain && preset === this.selectedPreset) { this.compareSavingLocal = false; } } }, async applyMainDraftToCurrentPreset() { if (!this.compareMainParsed.valid) { this.notifyCompare('右侧 main 配置 JSON 无效,不能覆盖当前预设', 'warning'); return; } this.compareLocalDraft = this.formatConfigCompareJson(this.compareMainParsed.value); await this.saveConfigCompareLocalDraft(); }, copyMainToLocalDraft() { this.compareLocalDraft = this.compareMainDraft; }, copyLocalToMainDraft() { this.compareMainDraft = this.compareLocalDraft; }, // 选择器值更新 updateSelectorValue(key, value) { const pc = this.presetConfig; if (pc && pc.selectors) { pc.selectors[key] = value; } }, // 流式配置保存 async saveStreamConfig(config) { if (!this.currentDomain) return; const domain = this.currentDomain; const preset = this.selectedPreset; const nextConfig = this.cloneConfigSection(config || {}); const saveSeq = Number(this.streamConfigSaveSeq || 0) + 1; this.streamConfigSaveSeq = saveSeq; const pc = this.presetConfig; if (pc) { pc.stream_config = nextConfig; // 修复:后端 set_site_stream_config 会把 send_confirmation 从 stream_config 剥离、 // merge 进 file_paste(engine.py:2826-2840),而 streamConfig computed 又以 // file_paste 为权威。若这里只写 stream_config,用户在「流式配置 → 发送确认」 // 的改动会在下一次重算时被旧的 file_paste 值盖回去,看起来像"没保存成功"。 if (nextConfig && nextConfig.send_confirmation && typeof nextConfig.send_confirmation === 'object') { if (!pc.file_paste || typeof pc.file_paste !== 'object') pc.file_paste = {}; pc.file_paste.send_confirmation = { ...(pc.file_paste.send_confirmation || {}), ...nextConfig.send_confirmation }; } } const previousSave = this.streamConfigSaveQueue || Promise.resolve(); const saveRequest = previousSave .catch(() => undefined) .then(() => { const payload = { ...nextConfig, preset_name: preset }; return this.fetchJson( '/api/sites/' + encodeURIComponent(domain) + '/stream-config', { method: 'PUT', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify(payload) }, { timeoutMs: 12000 } ); }); this.streamConfigSaveQueue = saveRequest; try { await saveRequest; if ( saveSeq !== this.streamConfigSaveSeq || domain !== this.currentDomain || preset !== this.selectedPreset ) return; } catch (e) { if ( saveSeq !== this.streamConfigSaveSeq || domain !== this.currentDomain || preset !== this.selectedPreset ) return; console.error('保存流式配置失败:', e); alert('保存失败: ' + e.message); this.$emit('reload-config'); } finally { if (this.streamConfigSaveQueue === saveRequest) { this.streamConfigSaveQueue = null; } } }, updateModelCatalog(value) { // 模型目录已独立持久化存储至 config/arena_model_catalog.local.json,不再污染主预设对象 }, sanitizeInputStabilityWaitTimeout(value) { const parsed = Number(value); if (!Number.isFinite(parsed)) { return 1.5; } return Math.min(10, Math.max(0.1, parsed)); }, sanitizeSendConfirmationCheckTimeout(value) { const parsed = Number(value); if (!Number.isFinite(parsed)) { return 1.5; } return Math.min(10, Math.max(0.1, parsed)); }, sanitizeUrlTransitionWaitPatterns(value) { const seen = new Set(); const items = Array.isArray(value) ? value : (typeof value === 'string' ? value.replace(/\r\n/g, '\n').replace(/;/g, '\n').split('\n') : []); const result = []; items.forEach(item => { const text = String(item || '').trim(); if (!text || seen.has(text)) return; seen.add(text); result.push(text); }); return result; }, formatUrlTransitionWaitPatterns(value) { return this.sanitizeUrlTransitionWaitPatterns(value).join('\n'); }, buildSiteAdvancedPayload(overrides = {}) { const siteAdvanced = { independent_cookies: false, independent_cookies_auto_takeover: false, ...((this.currentConfig && this.currentConfig.advanced) || {}), ...overrides }; return { independent_cookies: !!siteAdvanced.independent_cookies, independent_cookies_auto_takeover: !!siteAdvanced.independent_cookies_auto_takeover, }; }, buildPresetAdvancedPayload(overrides = {}, options = {}) { const nextAdvanced = { input_box_stability_wait_enabled: !!this.siteAdvancedConfig.input_box_stability_wait_enabled, input_box_stability_wait_after_new_chat_only: !!this.siteAdvancedConfig.input_box_stability_wait_after_new_chat_only, input_box_stability_wait_timeout: this.sanitizeInputStabilityWaitTimeout( this.siteAdvancedConfig.input_box_stability_wait_timeout ), url_transition_wait_on_new_chat: !!this.siteAdvancedConfig.url_transition_wait_on_new_chat, send_confirmation_check_enabled: !!this.siteAdvancedConfig.send_confirmation_check_enabled, send_confirmation_check_timeout: this.sanitizeSendConfirmationCheckTimeout( this.siteAdvancedConfig.send_confirmation_check_timeout ), skip_new_chat_on_retry: !!this.siteAdvancedConfig.skip_new_chat_on_retry, ...overrides }; const payload = { preset_name: this.selectedPreset, input_box_stability_wait_enabled: !!nextAdvanced.input_box_stability_wait_enabled, input_box_stability_wait_after_new_chat_only: !!nextAdvanced.input_box_stability_wait_after_new_chat_only, input_box_stability_wait_timeout: this.sanitizeInputStabilityWaitTimeout( nextAdvanced.input_box_stability_wait_timeout ), url_transition_wait_on_new_chat: !!nextAdvanced.url_transition_wait_on_new_chat, send_confirmation_check_enabled: !!nextAdvanced.send_confirmation_check_enabled, send_confirmation_check_timeout: this.sanitizeSendConfirmationCheckTimeout( nextAdvanced.send_confirmation_check_timeout ), skip_new_chat_on_retry: !!nextAdvanced.skip_new_chat_on_retry }; const shouldSendPatterns = ( options.includeUrlTransitionWaitPatterns || Object.prototype.hasOwnProperty.call(overrides, 'url_transition_wait_patterns') ); if (shouldSendPatterns) { payload.url_transition_wait_patterns = this.sanitizeUrlTransitionWaitPatterns( nextAdvanced.url_transition_wait_patterns ); } return payload; }, filterPresetAdvancedFields(config = {}) { const keys = [ 'input_box_stability_wait_enabled', 'input_box_stability_wait_after_new_chat_only', 'input_box_stability_wait_timeout', 'url_transition_wait_on_new_chat', 'url_transition_wait_patterns', 'send_confirmation_check_enabled', 'send_confirmation_check_timeout', 'skip_new_chat_on_retry' ]; const result = {}; keys.forEach(key => { if (Object.prototype.hasOwnProperty.call(config, key)) { if (key === 'input_box_stability_wait_timeout') { result[key] = this.sanitizeInputStabilityWaitTimeout(config[key]); } else if (key === 'send_confirmation_check_timeout') { result[key] = this.sanitizeSendConfirmationCheckTimeout(config[key]); } else if (key === 'url_transition_wait_patterns') { result[key] = this.sanitizeUrlTransitionWaitPatterns(config[key]); } else { result[key] = !!config[key]; } } }); return result; }, filterSiteAdvancedFields(config = {}) { const keys = [ 'independent_cookies', 'independent_cookies_auto_takeover' ]; const result = {}; keys.forEach(key => { if (Object.prototype.hasOwnProperty.call(config, key)) { result[key] = !!config[key]; } }); return result; }, assignConfigSection(target, key, value) { if (!this.canAssignObjectProperty(target, key)) { return false; } target[key] = this.cloneConfigSection(value); return true; }, assignCurrentConfigAdvanced(value) { if (!this.currentConfig) { return false; } return this.assignConfigSection(this.currentConfig, 'advanced', value); }, assignPresetAdvanced(value) { if (!this.presetConfig) { return false; } return this.assignConfigSection(this.presetConfig, 'advanced', value); }, startAdvancedConfigSave() { const saveSeq = Number(this.advancedConfigSaveSeq || 0) + 1; this.advancedConfigSaveSeq = saveSeq; this.advancedConfigSaving = true; return saveSeq; }, finishAdvancedConfigSave(saveSeq) { if (saveSeq === this.advancedConfigSaveSeq) { this.advancedConfigSaving = false; } }, async persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, options = {}) { const presetScoped = !!options.presetScoped; const saveSeq = Number(options.saveSeq || 0); const previousTarget = previousAdvanced || {}; const domain = this.currentDomain; const preset = this.selectedPreset; let saveRequest = null; try { const previousSave = this.advancedConfigSaveQueue || Promise.resolve(); saveRequest = previousSave .catch(() => undefined) .then(() => this.fetchJson( '/api/sites/' + encodeURIComponent(domain) + '/advanced-config', { method: 'PUT', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify(nextAdvanced) }, { timeoutMs: 12000 } )); this.advancedConfigSaveQueue = saveRequest; const data = await saveRequest; if ( domain !== this.currentDomain || (presetScoped && preset !== this.selectedPreset) || (saveSeq && saveSeq !== this.advancedConfigSaveSeq) ) { return false; } if (presetScoped && this.presetConfig) { this.assignPresetAdvanced(this.filterPresetAdvancedFields(data.advanced || nextAdvanced)); } else { this.assignCurrentConfigAdvanced({ ...previousTarget, ...this.filterSiteAdvancedFields(data.advanced || nextAdvanced) }); } this.$emit('reload-config'); return true; } catch (error) { if ( domain !== this.currentDomain || (presetScoped && preset !== this.selectedPreset) || (saveSeq && saveSeq !== this.advancedConfigSaveSeq) ) { return false; } if (presetScoped && this.presetConfig) { this.assignPresetAdvanced(previousTarget); } else if (this.currentConfig) { this.assignCurrentConfigAdvanced(previousTarget); } throw error; } finally { if (saveRequest && this.advancedConfigSaveQueue === saveRequest) { this.advancedConfigSaveQueue = null; } } }, async updateIndependentCookies(enabled, event) { if (!this.currentDomain || !this.currentConfig) return; const nextEnabled = !!enabled; const currentEnabled = !!this.siteAdvancedConfig.independent_cookies; if (nextEnabled && !currentEnabled) { const confirmed = window.confirm( [ '开启“独立 Cookie 标签页”后,可能带来这些影响:', '', '1. 新开的该站点独立会话通常不会继承当前受控浏览器里的登录态、Cookie 和 localStorage,可能表现为未登录。', '2. 独立会话通常会以单独窗口出现,并且内存占用会明显高于普通标签页。', '', '确认仍要开启吗?' ].join('\n') ); if (!confirmed) { // 用户取消:把 checkbox 视觉状态还原 if (event && event.target) event.target.checked = currentEnabled; return; } } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.currentConfig.advanced || {}) }; const nextAdvanced = this.buildSiteAdvancedPayload({ independent_cookies: nextEnabled, independent_cookies_auto_takeover: !!previousAdvanced.independent_cookies_auto_takeover }); this.assignCurrentConfigAdvanced({ ...previousAdvanced, ...this.filterSiteAdvancedFields(nextAdvanced) }); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { saveSeq }); } catch (e) { console.error('保存站点高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateIndependentCookiesAutoTakeover(enabled) { if (!this.currentDomain || !this.currentConfig) return; const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.currentConfig.advanced || {}) }; const nextAdvanced = this.buildSiteAdvancedPayload({ independent_cookies_auto_takeover: !!enabled }); this.assignCurrentConfigAdvanced({ ...previousAdvanced, ...this.filterSiteAdvancedFields(nextAdvanced) }); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { saveSeq }); } catch (e) { console.error('保存站点高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateInputStabilityWaitEnabled(enabled) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ input_box_stability_wait_enabled: !!enabled }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateInputStabilityWaitAfterNewChatOnly(enabled) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ input_box_stability_wait_after_new_chat_only: !!enabled }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateInputStabilityWaitTimeout(value) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ input_box_stability_wait_timeout: this.sanitizeInputStabilityWaitTimeout(value) }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateUrlTransitionWaitOnNewChat(enabled) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ url_transition_wait_on_new_chat: !!enabled }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateUrlTransitionWaitPatterns(value) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ url_transition_wait_patterns: this.sanitizeUrlTransitionWaitPatterns(value) }, { includeUrlTransitionWaitPatterns: true }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateSendConfirmationCheckEnabled(enabled) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ send_confirmation_check_enabled: !!enabled }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateSendConfirmationCheckTimeout(value) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ send_confirmation_check_timeout: this.sanitizeSendConfirmationCheckTimeout(value) }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async updateSkipNewChatOnRetry(enabled) { // 修复:切站点时 selectedPreset 会被短暂置空,空预设名会被后端当作站点级配置写入,污染该站点全部预设 if (!this.currentDomain || !this.currentConfig || !this.presetConfig || !this.selectedPreset) { if (this.currentDomain && !this.selectedPreset) { this.notifyCompare('预设尚未加载完成,请稍后重试', 'warning'); } return; } const saveSeq = this.startAdvancedConfigSave(); const previousAdvanced = { ...(this.presetConfig.advanced || {}) }; const nextAdvanced = this.buildPresetAdvancedPayload({ skip_new_chat_on_retry: !!enabled }); this.assignPresetAdvanced(this.filterPresetAdvancedFields(nextAdvanced)); try { await this.persistSiteAdvancedConfig(nextAdvanced, previousAdvanced, { presetScoped: true, saveSeq }); } catch (e) { console.error('保存预设高级配置失败:', e); alert('保存失败: ' + e.message); } finally { this.finishAdvancedConfigSave(saveSeq); } }, async createIsolatedCookieTab() { if (!this.currentDomain) return; const domain = this.currentDomain; this.isolatedTabCreating = true; try { const result = await this.fetchJson( '/api/sites/' + encodeURIComponent(domain) + '/isolated-tab', { method: 'POST', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }) }, { timeoutMs: 12000 } ); if (domain !== this.currentDomain) return; alert(result.message || ('已为 ' + domain + ' 新建独立 Cookie 标签页')); } catch (e) { if (domain !== this.currentDomain) return; console.error('新建独立 Cookie 标签页失败:', e); alert('新建失败: ' + e.message); } finally { if (domain === this.currentDomain) { this.isolatedTabCreating = false; } } }, async createSharedCookieTab() { if (!this.currentDomain) return; const domain = this.currentDomain; this.sharedTabCreating = true; try { const result = await this.fetchJson( '/api/sites/' + encodeURIComponent(domain) + '/shared-tab', { method: 'POST', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }) }, { timeoutMs: 12000 } ); if (domain !== this.currentDomain) return; alert(result.message || ('已为 ' + domain + ' 打开共享 Cookie 受控窗口')); } catch (e) { if (domain !== this.currentDomain) return; console.error('打开共享 Cookie 受控窗口失败:', e); alert('打开失败: ' + e.message); } finally { if (domain === this.currentDomain) { this.sharedTabCreating = false; } } }, // ===== 🆕 预设管理方法 ===== async loadPresets() { if (!this.currentDomain) return; const domain = this.currentDomain; this.presetLoading = true; try { const data = await this.fetchJson( '/api/presets/' + encodeURIComponent(domain), { headers: this.buildAuthHeaders() }, { timeoutMs: 10000 } ); if (domain !== this.currentDomain) return; this.availablePresets = [...new Set([...(data.presets || ['主预设']), ...Object.keys(this.currentConfig?.presets || {})])]; const apiDefault = data.default_preset; if (apiDefault && this.availablePresets.includes(apiDefault)) { this.defaultPreset = apiDefault; } else if (this.availablePresets.includes('主预设')) { this.defaultPreset = '主预设'; } else { this.defaultPreset = this.availablePresets[0] || '主预设'; } // 确保选中的预设仍然有效 if (!this.availablePresets.includes(this.selectedPreset)) { this.selectedPreset = this.defaultPreset || this.availablePresets[0] || '主预设'; } } catch (e) { if (domain !== this.currentDomain) return; console.error('加载预设列表失败:', e); if (!this.availablePresets.length) { this.availablePresets = ['主预设']; this.defaultPreset = '主预设'; } // 修复:切站点时 selectedPreset 会先被同步清空。若此处只在 availablePresets // 为空时才纠正,上一个站点的列表还在(非空)就会让 selectedPreset 永久卡在 '', // 导致所有预设级开关一直被守卫拒绝,且用户无从察觉。 if (!this.selectedPreset) { this.selectedPreset = this.defaultPreset || this.availablePresets[0] || '主预设'; } } finally { if (domain === this.currentDomain) { this.presetLoading = false; } } }, switchPreset(presetName) { this.selectedPreset = presetName; // All preset drafts already belong to currentConfig; fetching here loses unsaved imports. this.ensurePresetMutableSections(); }, async setDefaultPreset() { if (!this.currentDomain || !this.selectedPreset) return; const domain = this.currentDomain; const preset = this.selectedPreset; if (this.stagePresetOperation('default')) return; try { await this.fetchJson( '/api/presets/' + encodeURIComponent(domain) + '/default', { method: 'PUT', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify({ preset_name: preset }) }, { timeoutMs: 10000 } ); if (domain !== this.currentDomain || preset !== this.selectedPreset) return; this.defaultPreset = preset; this.currentConfig.default_preset = preset; alert('✅ 默认预设已设置为 "' + preset + '"(仅本地覆盖)'); } catch (e) { if (domain !== this.currentDomain || preset !== this.selectedPreset) return; alert('❌ 设置默认预设失败: ' + e.message); } }, async createPreset() { const name = this.newPresetName.trim(); if (!name) return; if (!this.currentDomain) return; const domain = this.currentDomain; const sourcePreset = this.selectedPreset; if (this.stagePresetOperation('create', name)) return; this.flushMutableSectionDrafts(); const sourceDraft = JSON.parse(JSON.stringify(this.presetConfig)); try { await this.fetchJson( '/api/presets/' + encodeURIComponent(domain), { method: 'POST', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify({ new_name: name, source_name: sourcePreset }) }, { timeoutMs: 12000 } ); if (domain !== this.currentDomain) return; this.newPresetName = ''; this.showNewPresetInput = false; this.currentConfig.presets[name] = sourceDraft; this.availablePresets = Object.keys(this.currentConfig.presets); this.selectedPreset = name; alert('✅ 预设 "' + name + '" 已创建(克隆自 "' + sourcePreset + '")'); } catch (e) { if (domain !== this.currentDomain) return; alert('❌ 创建失败: ' + e.message); } }, async renamePreset() { const newName = this.renamePresetName.trim(); if (!newName) return; if (!this.currentDomain) return; if (!this.selectedPreset) return; if (newName === this.selectedPreset) { this.showRenamePresetInput = false; this.renamePresetName = ''; return; } const domain = this.currentDomain; const oldName = this.selectedPreset; if (this.stagePresetOperation('rename', newName)) return; try { await this.fetchJson( '/api/presets/' + encodeURIComponent(domain) + '/rename', { method: 'PUT', headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }), body: JSON.stringify({ old_name: oldName, new_name: newName }) }, { timeoutMs: 12000 } ); if (domain !== this.currentDomain || oldName !== this.selectedPreset) return; this.showRenamePresetInput = false; this.renamePresetName = ''; this.flushMutableSectionDrafts(); if (this.currentConfig.presets && Object.hasOwn(this.currentConfig.presets, oldName)) { this.currentConfig.presets[newName] = this.currentConfig.presets[oldName]; delete this.currentConfig.presets[oldName]; } if (this.currentConfig.default_preset === oldName) this.currentConfig.default_preset = newName; if (this.defaultPreset === oldName) this.defaultPreset = newName; this.availablePresets = this.availablePresets.map(n => n === oldName ? newName : n); this.selectedPreset = newName; alert('✅ 预设已重命名为 "' + newName + '"'); } catch (e) { if (domain !== this.currentDomain || oldName !== this.selectedPreset) return; alert('❌ 重命名失败: ' + e.message); } }, async deletePreset() { if (this.availablePresets.length <= 1) { alert('不能删除最后一个预设'); return; } if (!confirm('确定要删除预设 "' + this.selectedPreset + '" 吗?此操作不可撤销。')) { return; } const domain = this.currentDomain; const preset = this.selectedPreset; if (this.stagePresetOperation('delete')) return; try { await this.fetchJson( '/api/presets/' + encodeURIComponent(domain) + '/' + encodeURIComponent(preset), { method: 'DELETE', headers: this.buildAuthHeaders() }, { timeoutMs: 12000 } ); if (domain !== this.currentDomain || preset !== this.selectedPreset) return; this.flushMutableSectionDrafts(); delete this.currentConfig.presets[preset]; await this.loadPresets(); if (domain !== this.currentDomain) return; this.currentConfig.default_preset = this.defaultPreset; this.selectedPreset = this.defaultPreset || this.availablePresets[0] || '主预设'; alert('✅ 预设已删除'); } catch (e) { if (domain !== this.currentDomain || preset !== this.selectedPreset) return; alert('❌ 删除失败: ' + e.message); } } }, watch: { currentDomain: { handler(newDomain) { this.resetConfigCompareState(); this.pendingPresetTransfer = 0; if (newDomain) { // 切换站点时强制按站点默认预设初始化 this.selectedPreset = ''; this.defaultPreset = '主预设'; this.showNewPresetInput = false; this.showRenamePresetInput = false; this.newPresetName = ''; this.renamePresetName = ''; this.loadPresets(); } else { this.availablePresets = []; this.selectedPreset = '主预设'; this.defaultPreset = '主预设'; this.showNewPresetInput = false; this.showRenamePresetInput = false; this.newPresetName = ''; this.renamePresetName = ''; } }, immediate: true }, selectedPreset(newValue, oldValue) { this.ensurePresetMutableSections(); if (newValue === oldValue || !this.showConfigCompareDialog) return; this.syncConfigCompareLocalDraft(true); this.loadMainBranchCompareConfig(); }, currentConfig: { handler() { this.ensurePresetMutableSections(); if (!this.showConfigCompareDialog) return; this.syncConfigCompareLocalDraft(false); }, deep: true, immediate: true } }, template: `
📝
请选择或新增站点配置
当前预设 {{ presetLoading ? '读取中…' : '共 ' + availablePresets.length + ' 个' }} 默认 · {{ defaultPreset || '主预设' }}
{{ String(workspaceSections.findIndex(s => s.id === activeWorkspaceSection) + 1).padStart(2, '0') }} / 配置预设

{{ activeWorkspaceMeta.heading }}

{{ activeWorkspaceMeta.description }}

这里的修改会自动保存。

隔离登录会话

整个站点

让不同标签页各用各的登录状态,避免多个账号互相影响。

开启后,新会话不继承原登录状态,可能需要重新登录。

管理会话与接管规则需要多账号或匿名环境时使用。
查看说明

开启后,可以为这个站点创建独立 Cookie 会话。

说明:Chromium 的独立上下文通常会显示为单独窗口。这不是新起一个完全独立的浏览器进程,而是同一浏览器里的隔离会话。

注意:开启后,新开的该站点标签页不会继承当前浏览器里已有的登录态、Cookie 或 localStorage。原本已登录的共享标签页如果重新进入并被转换为独立标签页,通常会表现为未登录。

单标签页清 Cookie 不会影响同站点的其它独立标签页。

默认不会自动接管你手动新开的普通标签页,避免原标签页被关闭;只有点下面的按钮才会新建独立会话。

等待输入框就绪

当前预设

新建对话后输入框会重建?等它稳定下来,再填写消息。

调整等待规则只有偶发填入失败、输入位置丢失时再调整。

这里的规则会作为旧会话 URL 的兜底匹配;留空则只用启发式判断。

发送失败时自动恢复

当前预设

消息没有真正发出时,确认状态并尝试恢复。

调整确认与重试设置确认超时,以及重试时是否新建对话。
Main Compare {{ currentDomain }}

配置对比与合并

当前预设: {{ selectedPreset || defaultPreset || '主预设' }} 官方来源: {{ compareMainSource.repository || '官方仓库' }}/{{ compareMainSource.branch || 'main' }} · {{ compareMainPath || 'config/sites.json' }} {{ compareMainSource.stale ? '缓存回退' : (compareMainSource.status === 'validated_cache' ? '已确认最新' : '刚刚获取') }} main 预设: {{ compareMainPresetName }} {{ getConfigCompareMatchLabel(compareMainMatchMode) }}
{{ compareDifferentCount }} 项不同 {{ compareSameCount }} 项一致
{{ item.label }} · {{ getConfigCompareDiffText(item.status) }}
{{ compareMainSource.warning }}
{{ compareMainError }}
本地预设草稿
保存后会直接写入当前工作区。
{{ item.label }} {{ item.value }}
JSON 有误: {{ compareLocalParsed.error }}
main 分支参考
右侧是参考草稿,不会回写到远端仓库。
{{ item.label }} {{ item.value }}
JSON 有误: {{ compareMainParsed.error }}
` };