Initial commit
This commit is contained in:
commit
57fc3525eb
7311 files changed
+1291398
No files matched your search
@@ -0,0 +1,194 @@
|
||||
// ==================== 命令管理组件 ====================
|
||||
window.CommandsTabComponent = {
|
||||
name: 'CommandsTabComponent',
|
||||
props: {
|
||||
darkMode: { type: Boolean, default: false }
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
commands: [],
|
||||
loading: false,
|
||||
// action_id -> 上一次的动作类型;用于切换类型时判断 selector/timeout 等
|
||||
// 同名字段的语义分组是否变化(仅组件内部状态,不写入命令 JSON)
|
||||
actionTypeSnapshots: {},
|
||||
meta: { trigger_types: {}, action_types: {} },
|
||||
availableDomains: [],
|
||||
availableTabs: [],
|
||||
availablePresets: [],
|
||||
presetLoading: false,
|
||||
showHelpTip: false,
|
||||
currentPage: 1,
|
||||
pageSize: 16,
|
||||
pageSizeOptions: [8, 16, 24, 32, 48, 64],
|
||||
reordering: false,
|
||||
selectedCommandIds: [],
|
||||
pendingGroupName: '',
|
||||
selectedExistingGroupName: '',
|
||||
groupWorking: false,
|
||||
duplicatingCommandId: '',
|
||||
includeDisabledWhenRunGroup: false,
|
||||
runGroupAcquirePolicy: 'inherit_session',
|
||||
showGroupTools: false,
|
||||
collapsedGroups: {},
|
||||
bulkActionMenuOpen: false,
|
||||
groupActionMenuOpen: '',
|
||||
commandActionMenuOpen: '',
|
||||
draggingCommandId: '',
|
||||
dragOverGroupName: '',
|
||||
dragOverCommandId: '',
|
||||
dragOverCommandPosition: '',
|
||||
triggerTypePickerOpen: false,
|
||||
triggerTypeTooltipType: '',
|
||||
sourceCommandPickerOpen: false,
|
||||
sourceCommandSearch: '',
|
||||
sourcePickerExpandedGroups: {},
|
||||
sourcePickerShowUngrouped: false,
|
||||
pageProbeExpanded: false,
|
||||
|
||||
// 编辑弹窗
|
||||
showEditor: false,
|
||||
editingCommand: null,
|
||||
isNew: false,
|
||||
|
||||
// 高级模式编辑器高度
|
||||
scriptEditorHeight: '300px',
|
||||
advancedEditorMode: 'ui',
|
||||
commandResults: [],
|
||||
commandResultsLoading: false,
|
||||
commandResultsTimer: null,
|
||||
commandResultsRequestSeq: 0,
|
||||
selectedAdvancedRuleIndex: 0,
|
||||
|
||||
// 代理切换默认配置
|
||||
proxyDefaults: {
|
||||
clash_api: 'http://127.0.0.1:9090',
|
||||
clash_secret: '',
|
||||
selector: 'Proxy',
|
||||
mode: 'random',
|
||||
node_name: '',
|
||||
exclude_keywords: 'DIRECT,REJECT,GLOBAL,自动选择,故障转移',
|
||||
refresh_after: true
|
||||
},
|
||||
webhookDefaults: {
|
||||
method: 'POST',
|
||||
url: '',
|
||||
payload: '{"msg":"标签页#{{tab_index}} 在 {{domain}} 命中异常状态码 {{network_status}}"}',
|
||||
headers: '{"Content-Type":"application/json"}',
|
||||
timeout: 8,
|
||||
raise_for_status: false
|
||||
},
|
||||
napcatDefaults: {
|
||||
base_url: 'http://127.0.0.1:3000',
|
||||
target_type: 'private',
|
||||
user_id: '',
|
||||
group_id: '',
|
||||
message: '命令通知:{{source_command_name}}\\n{{command_result_summary}}',
|
||||
access_token: '',
|
||||
timeout: 8,
|
||||
raise_for_status: true
|
||||
},
|
||||
releaseLockDefaults: {
|
||||
reason: 'release_tab_lock_action',
|
||||
clear_page: true,
|
||||
stop_actions: true
|
||||
},
|
||||
automationWriteDefaults: {
|
||||
selector: '',
|
||||
write_mode: 'replace',
|
||||
clear_first: true,
|
||||
value_source: 'literal',
|
||||
text: '',
|
||||
template: '',
|
||||
variable_name: '',
|
||||
random_kind: 'alnum',
|
||||
random_length: 8,
|
||||
prefix: '',
|
||||
suffix: '',
|
||||
preset_name: 'name_cn',
|
||||
date_format: 'YYYY-MM-DD',
|
||||
min_age: 18,
|
||||
max_age: 35,
|
||||
save_as: '',
|
||||
timeout_sec: 6
|
||||
},
|
||||
automationReadDefaults: {
|
||||
selector: '',
|
||||
read_mode: 'auto',
|
||||
attr_name: '',
|
||||
trim: true,
|
||||
save_as: '',
|
||||
timeout_sec: 6
|
||||
},
|
||||
httpRequestDefaults: {
|
||||
method: 'GET',
|
||||
url: '',
|
||||
request_profile: '',
|
||||
headers: '{"Accept":"application/json"}',
|
||||
prompt: '',
|
||||
body: '',
|
||||
body_mode: 'json',
|
||||
response_mode: 'text',
|
||||
credentials: 'include',
|
||||
model_type: 'auto',
|
||||
search_enabled: 'auto',
|
||||
thinking_enabled: 'auto',
|
||||
client_version: '2.0.0',
|
||||
app_version: '2.0.0',
|
||||
timeout_sec: 15,
|
||||
fail_on_http_error: true,
|
||||
save_as: ''
|
||||
},
|
||||
appendFileDefaults: {
|
||||
file_path: '',
|
||||
content: '',
|
||||
append_newline: true,
|
||||
create_dirs: true,
|
||||
encoding: 'utf-8'
|
||||
},
|
||||
runJsFileDefaults: {
|
||||
file_path: 'js/arena-stream-hard-stop.user.js',
|
||||
encoding: 'utf-8-sig',
|
||||
inject_on_new_document: true,
|
||||
apply_now: true,
|
||||
fail_on_falsy: false
|
||||
},
|
||||
fetchCommandsSeq: 0,
|
||||
commandsResponseSignature: '',
|
||||
presetOptionsRequestSeq: 0
|
||||
};
|
||||
},
|
||||
computed: window.CommandsTabComputed,
|
||||
|
||||
methods: window.CommandsTabMethods,
|
||||
|
||||
watch: {
|
||||
'editingCommand.mode'(nextMode, prevMode) {
|
||||
if (nextMode === 'advanced' && prevMode !== 'advanced') {
|
||||
this.advancedEditorMode = 'ui';
|
||||
}
|
||||
},
|
||||
showEditor(nextValue) {
|
||||
if (!nextValue) {
|
||||
this.advancedEditorMode = 'ui';
|
||||
this.commandResultsRequestSeq += 1;
|
||||
this.commandResults = [];
|
||||
this.commandResultsLoading = false;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
mounted() {
|
||||
this.fetchMeta();
|
||||
this.fetchCommands();
|
||||
this.fetchBindingMeta();
|
||||
this.commandResultsTimer = window.setInterval(() => {
|
||||
if (this.showEditor && this.editingCommand && this.advancedUiResultsEnabled) {
|
||||
this.loadCommandResults(true);
|
||||
}
|
||||
}, 5000);
|
||||
},
|
||||
beforeUnmount() {
|
||||
if (this.commandResultsTimer) window.clearInterval(this.commandResultsTimer);
|
||||
},
|
||||
template: window.CommandsTabTemplate
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,822 @@
|
||||
// ==================== 所有弹窗组件 ====================
|
||||
|
||||
// -------------------- JSON 预览弹窗 --------------------
|
||||
window.JsonPreviewDialog = {
|
||||
name: 'JsonPreviewDialog',
|
||||
props: {
|
||||
show: { type: Boolean, default: false },
|
||||
jsonData: { type: Object, default: () => ({}) },
|
||||
title: { type: String, default: '配置 JSON' }
|
||||
},
|
||||
emits: ['close', 'copy', 'save'],
|
||||
data() {
|
||||
return {
|
||||
draft: ''
|
||||
};
|
||||
},
|
||||
watch: {
|
||||
show: {
|
||||
handler(value) {
|
||||
if (value) {
|
||||
this.draft = JSON.stringify(this.jsonData || {}, null, 2);
|
||||
}
|
||||
},
|
||||
immediate: true
|
||||
},
|
||||
jsonData: {
|
||||
handler() {
|
||||
if (this.show) {
|
||||
this.draft = JSON.stringify(this.jsonData || {}, null, 2);
|
||||
}
|
||||
},
|
||||
deep: true
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div v-if="show"
|
||||
class="fixed inset-0 bg-black/50 flex items-center justify-center z-40"
|
||||
@click.self="$emit('close')">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-[96vw] max-w-[1600px] h-[90vh] flex flex-col shadow-2xl">
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
<h3 class="font-semibold dark:text-white">{{ title }}</h3>
|
||||
<button @click="$emit('close')"
|
||||
class="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300">
|
||||
<span v-html="$icons.xMark"></span>
|
||||
</button>
|
||||
</div>
|
||||
<textarea v-model="draft"
|
||||
spellcheck="false"
|
||||
class="flex-1 min-h-0 overflow-auto bg-gray-50 dark:bg-gray-900 p-4 rounded text-sm font-mono border dark:border-gray-700 dark:text-gray-300 resize-none focus:outline-none focus:ring-2 focus:ring-blue-400"></textarea>
|
||||
<div class="mt-4 flex justify-end gap-2">
|
||||
<button @click="$emit('copy', draft)"
|
||||
class="border dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-2 py-0.5 text-sm">
|
||||
复制到剪贴板
|
||||
</button>
|
||||
<button @click="$emit('save', draft)"
|
||||
class="border rounded transition-colors bg-blue-500 text-white hover:bg-blue-600 border-blue-500 px-3 py-1 text-sm">
|
||||
保存修改
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
// -------------------- 控制面板访问密钥弹窗 --------------------
|
||||
window.TokenDialog = {
|
||||
name: 'TokenDialog',
|
||||
props: {
|
||||
show: { type: Boolean, default: false },
|
||||
modelValue: { type: String, default: '' }
|
||||
},
|
||||
emits: ['close', 'save', 'update:modelValue'],
|
||||
computed: {
|
||||
tempToken: {
|
||||
get() { return this.modelValue; },
|
||||
set(val) { this.$emit('update:modelValue', val); }
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div v-if="show"
|
||||
class="fixed inset-0 bg-black/50 flex items-center justify-center z-40"
|
||||
@click.self="$emit('close')">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-96">
|
||||
<h3 class="font-semibold dark:text-white mb-4">配置控制面板访问密钥</h3>
|
||||
<div class="mb-4">
|
||||
<label class="text-sm text-gray-600 dark:text-gray-400 mb-2 block">
|
||||
控制面板访问密钥(留空则清除)
|
||||
</label>
|
||||
<input v-model="tempToken"
|
||||
type="password"
|
||||
placeholder="dashboard-secret"
|
||||
class="border dark:border-gray-700 px-2 py-1 rounded focus:outline-none focus:border-blue-400 w-full bg-white dark:bg-gray-700 dark:text-white">
|
||||
</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mb-4">
|
||||
仅用于访问控制面板管理接口,不等同于对外服务 API Key
|
||||
</div>
|
||||
<div class="flex justify-end gap-2">
|
||||
<button @click="$emit('close')"
|
||||
class="border dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-2 py-0.5 text-sm">
|
||||
取消
|
||||
</button>
|
||||
<button @click="$emit('save')"
|
||||
class="border rounded transition-colors bg-blue-500 text-white hover:bg-blue-600 border-blue-500 px-2 py-0.5 text-sm">
|
||||
保存
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
// -------------------- 步骤模板弹窗 --------------------
|
||||
window.StepTemplatesDialog = {
|
||||
name: 'StepTemplatesDialog',
|
||||
props: {
|
||||
show: { type: Boolean, default: false }
|
||||
},
|
||||
emits: ['close', 'apply'],
|
||||
template: `
|
||||
<div v-if="show"
|
||||
class="fixed inset-0 bg-black/50 flex items-center justify-center z-40"
|
||||
@click.self="$emit('close')">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-[500px]">
|
||||
<h3 class="font-semibold dark:text-white mb-4">工作流模板</h3>
|
||||
<div class="space-y-2 mb-4">
|
||||
<button @click="$emit('apply', 'default')"
|
||||
class="w-full text-left p-3 border dark:border-gray-700 rounded hover:border-blue-400 dark:hover:border-blue-500 transition-colors">
|
||||
<div class="font-semibold text-sm dark:text-white">标准对话流程</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
点击新建 → 填入 → 点击发送 → 等待 → 流式监听
|
||||
</div>
|
||||
</button>
|
||||
<button @click="$emit('apply', 'simple')"
|
||||
class="w-full text-left p-3 border dark:border-gray-700 rounded hover:border-blue-400 dark:hover:border-blue-500 transition-colors">
|
||||
<div class="font-semibold text-sm dark:text-white">简化流程</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
填入 → 回车 → 流式监听
|
||||
</div>
|
||||
</button>
|
||||
<button @click="$emit('apply', 'battle_winner')"
|
||||
class="w-full text-left p-3 border dark:border-gray-700 rounded hover:border-amber-400 dark:hover:border-amber-500 transition-colors">
|
||||
<div class="font-semibold text-sm dark:text-white">Battle 赢家优先</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
填入 → 点圆形重试 → 点方形发送 → 等待两侧结束,输出先完成的一侧
|
||||
</div>
|
||||
</button>
|
||||
<button @click="$emit('apply', 'battle_left')"
|
||||
class="w-full text-left p-3 border dark:border-gray-700 rounded hover:border-amber-400 dark:hover:border-amber-500 transition-colors">
|
||||
<div class="font-semibold text-sm dark:text-white">Battle 左侧</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
填入 → 点圆形重试 → 点方形发送 → 流式输出左侧,等待两侧结束
|
||||
</div>
|
||||
</button>
|
||||
<button @click="$emit('apply', 'battle_right')"
|
||||
class="w-full text-left p-3 border dark:border-gray-700 rounded hover:border-amber-400 dark:hover:border-amber-500 transition-colors">
|
||||
<div class="font-semibold text-sm dark:text-white">Battle 右侧</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
填入 → 点圆形重试 → 点方形发送 → 流式输出右侧,等待两侧结束
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex justify-end">
|
||||
<button @click="$emit('close')"
|
||||
class="border dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-2 py-0.5 text-sm">
|
||||
关闭
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
// -------------------- 选择器测试弹窗 --------------------
|
||||
window.TestDialog = {
|
||||
name: 'TestDialog',
|
||||
props: {
|
||||
show: { type: Boolean, default: false },
|
||||
selector: { type: String, default: '' },
|
||||
selectorKey: { type: String, default: '' },
|
||||
timeoutValue: { type: Number, default: 2 },
|
||||
highlightEnabled: { type: Boolean, default: false },
|
||||
result: { type: Object, default: null },
|
||||
testing: { type: Boolean, default: false }
|
||||
},
|
||||
emits: ['close', 'test', 'apply-selector'],
|
||||
data() {
|
||||
return {
|
||||
selectorInput: '',
|
||||
timeout: 3,
|
||||
highlight: false,
|
||||
copyFeedback: ''
|
||||
};
|
||||
},
|
||||
watch: {
|
||||
show: {
|
||||
handler(value) {
|
||||
if (value) {
|
||||
this.syncFromProps();
|
||||
}
|
||||
},
|
||||
immediate: true
|
||||
},
|
||||
selector(value) {
|
||||
if (this.show) {
|
||||
this.selectorInput = value || '';
|
||||
}
|
||||
},
|
||||
timeoutValue(value) {
|
||||
if (this.show && Number.isFinite(value)) {
|
||||
this.timeout = value;
|
||||
}
|
||||
},
|
||||
highlightEnabled(value) {
|
||||
if (this.show) {
|
||||
this.highlight = !!value;
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
diagnosis() {
|
||||
return this.result && this.result.diagnosis ? this.result.diagnosis : null;
|
||||
},
|
||||
topCandidates() {
|
||||
return Array.isArray(this.result && this.result.top_candidates) ? this.result.top_candidates : [];
|
||||
},
|
||||
resultElements() {
|
||||
return Array.isArray(this.result && this.result.elements) ? this.result.elements : [];
|
||||
},
|
||||
selectorLabel() {
|
||||
const key = String(this.selectorKey || '').trim();
|
||||
const labelMap = {
|
||||
input_box: '输入框',
|
||||
send_btn: '发送按钮',
|
||||
result_container: '回复容器',
|
||||
new_chat_btn: '新建对话按钮',
|
||||
message_wrapper: '消息外层',
|
||||
generating_indicator: '生成中指示器',
|
||||
retry_send_btn: '重试/重新运行按钮',
|
||||
upload_btn: '上传按钮',
|
||||
file_input: '原生文件输入框',
|
||||
drop_zone: '拖拽区域'
|
||||
};
|
||||
return labelMap[key] || '当前字段';
|
||||
},
|
||||
canApplyCurrent() {
|
||||
return !!String(this.selectorInput || '').trim() && !!String(this.selectorKey || '').trim();
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
syncFromProps() {
|
||||
this.selectorInput = this.selector || '';
|
||||
this.timeout = Number.isFinite(this.timeoutValue) ? this.timeoutValue : 3;
|
||||
this.highlight = !!this.highlightEnabled;
|
||||
this.copyFeedback = '';
|
||||
},
|
||||
async copyText(value) {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
this.copyFeedback = '已复制到剪贴板';
|
||||
window.setTimeout(() => {
|
||||
if (this.copyFeedback === '已复制到剪贴板') {
|
||||
this.copyFeedback = '';
|
||||
}
|
||||
}, 1600);
|
||||
} catch (error) {
|
||||
this.copyFeedback = '复制失败';
|
||||
window.setTimeout(() => {
|
||||
if (this.copyFeedback === '复制失败') {
|
||||
this.copyFeedback = '';
|
||||
}
|
||||
}, 1600);
|
||||
}
|
||||
},
|
||||
useCandidate(selector) {
|
||||
this.selectorInput = String(selector || '').trim();
|
||||
},
|
||||
retestCandidate(selector) {
|
||||
this.selectorInput = String(selector || '').trim();
|
||||
if (!this.selectorInput) return;
|
||||
this.$emit('test', {
|
||||
selector: this.selectorInput,
|
||||
timeout: this.timeout,
|
||||
highlight: this.highlight
|
||||
});
|
||||
},
|
||||
applyCandidate(selector, rerun = false) {
|
||||
const value = String(selector || '').trim();
|
||||
if (!value) return;
|
||||
this.selectorInput = value;
|
||||
this.$emit('apply-selector', {
|
||||
selector: value,
|
||||
rerun
|
||||
});
|
||||
},
|
||||
applyCurrentSelector(rerun = false) {
|
||||
if (!this.canApplyCurrent) return;
|
||||
this.$emit('apply-selector', {
|
||||
selector: this.selectorInput,
|
||||
rerun
|
||||
});
|
||||
},
|
||||
resultToneClass() {
|
||||
const status = this.diagnosis && this.diagnosis.status;
|
||||
if (status === 'unique') {
|
||||
return 'bg-emerald-50 dark:bg-emerald-900/20 border-emerald-200 dark:border-emerald-800';
|
||||
}
|
||||
if (status === 'multiple') {
|
||||
return 'bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800';
|
||||
}
|
||||
return 'bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800';
|
||||
},
|
||||
uniqueBadgeClass(candidate) {
|
||||
return candidate && candidate.unique
|
||||
? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300'
|
||||
: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300';
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div v-if="show"
|
||||
class="fixed inset-0 bg-black/50 flex items-center justify-center z-40"
|
||||
@click.self="$emit('close')">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-[92vw] max-w-[980px] max-h-[88vh] overflow-hidden flex flex-col shadow-2xl">
|
||||
<div class="flex justify-between items-start gap-4 mb-4">
|
||||
<div>
|
||||
<h3 class="font-semibold dark:text-white text-lg">选择器测试工作台</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
不只是看“找到了没”,还会给出候选写法、风险提示和回填入口。
|
||||
</p>
|
||||
</div>
|
||||
<button @click="$emit('close')"
|
||||
class="text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300">
|
||||
<span v-html="$icons.xMark"></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 lg:grid-cols-[minmax(0,1.15fr)_minmax(320px,0.85fr)] gap-4 min-h-0 flex-1">
|
||||
<div class="min-h-0 overflow-auto pr-1 space-y-4">
|
||||
<div class="rounded-xl border border-slate-200 dark:border-slate-700 p-4 bg-slate-50/70 dark:bg-slate-900/30">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-3">
|
||||
<span v-if="selectorKey"
|
||||
class="inline-flex items-center rounded-full bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 px-2.5 py-1 text-xs font-medium text-blue-700 dark:text-blue-300">
|
||||
当前字段:{{ selectorKey }} · {{ selectorLabel }}
|
||||
</span>
|
||||
<span v-if="copyFeedback"
|
||||
class="inline-flex items-center rounded-full bg-emerald-50 dark:bg-emerald-900/30 border border-emerald-200 dark:border-emerald-800 px-2.5 py-1 text-xs font-medium text-emerald-700 dark:text-emerald-300">
|
||||
{{ copyFeedback }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<label class="text-sm text-gray-600 dark:text-gray-400 mb-2 block">测试选择器</label>
|
||||
<textarea v-model="selectorInput"
|
||||
rows="3"
|
||||
spellcheck="false"
|
||||
class="border dark:border-gray-700 px-3 py-2 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent w-full font-mono text-sm bg-white dark:bg-gray-700 dark:text-white resize-none"
|
||||
placeholder='例如: button[data-testid="send-button"]'></textarea>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center gap-4">
|
||||
<label class="flex items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
|
||||
<span>超时</span>
|
||||
<input v-model.number="timeout"
|
||||
type="number"
|
||||
min="1"
|
||||
max="10"
|
||||
class="border dark:border-gray-700 px-2 py-1 rounded w-20 bg-white dark:bg-gray-700 dark:text-white">
|
||||
<span class="text-xs text-gray-400">秒</span>
|
||||
</label>
|
||||
<label class="flex items-center text-sm cursor-pointer">
|
||||
<input type="checkbox" v-model="highlight" class="mr-2">
|
||||
<span class="dark:text-gray-300">🎨 高亮浏览器中的命中元素</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-wrap gap-2">
|
||||
<button @click="$emit('test', { selector: selectorInput, timeout, highlight })"
|
||||
:disabled="!selectorInput.trim() || testing"
|
||||
class="border rounded-lg transition-colors bg-blue-500 text-white hover:bg-blue-600 border-blue-500 px-3 py-1.5 text-sm font-medium"
|
||||
:class="{'opacity-50 cursor-not-allowed': !selectorInput.trim() || testing}">
|
||||
{{ testing ? '测试中...' : '开始测试' }}
|
||||
</button>
|
||||
<button @click="applyCurrentSelector(false)"
|
||||
:disabled="!canApplyCurrent"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1.5 text-sm"
|
||||
:class="{'opacity-50 cursor-not-allowed': !canApplyCurrent}">
|
||||
回填当前字段
|
||||
</button>
|
||||
<button @click="applyCurrentSelector(true)"
|
||||
:disabled="!canApplyCurrent || testing"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1.5 text-sm"
|
||||
:class="{'opacity-50 cursor-not-allowed': !canApplyCurrent || testing}">
|
||||
回填并重测
|
||||
</button>
|
||||
<button @click="copyText(selectorInput)"
|
||||
:disabled="!selectorInput.trim()"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1.5 text-sm"
|
||||
:class="{'opacity-50 cursor-not-allowed': !selectorInput.trim()}">
|
||||
复制当前写法
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="result"
|
||||
class="rounded-xl border p-4"
|
||||
:class="resultToneClass()">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-2">
|
||||
<span class="text-sm font-semibold dark:text-white">
|
||||
{{ result.success ? (result.count === 1 ? '✅ 唯一命中' : '⚠️ 命中多个元素') : '❌ 没有命中元素' }}
|
||||
</span>
|
||||
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs bg-white/70 dark:bg-slate-800/70 text-slate-700 dark:text-slate-200">
|
||||
匹配数量:{{ result.count }}
|
||||
</span>
|
||||
<span v-if="result.locator_used"
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-xs bg-white/70 dark:bg-slate-800/70 text-slate-700 dark:text-slate-200">
|
||||
实际查询:{{ result.locator_used }}
|
||||
</span>
|
||||
<span v-if="result.tabs_tested"
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-xs bg-white/70 dark:bg-slate-800/70 text-slate-700 dark:text-slate-200">
|
||||
已测试 {{ result.tabs_tested }} 个页面,{{ result.matched_tabs }} 个页面命中
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<p v-if="diagnosis" class="text-sm leading-6 text-slate-700 dark:text-slate-200">
|
||||
{{ diagnosis.summary }}
|
||||
</p>
|
||||
<p v-else-if="result.message" class="text-sm leading-6 text-slate-700 dark:text-slate-200">
|
||||
{{ result.message }}
|
||||
</p>
|
||||
|
||||
<div v-if="diagnosis && diagnosis.warnings && diagnosis.warnings.length" class="mt-3 space-y-2">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400">风险提示</div>
|
||||
<div v-for="(warning, idx) in diagnosis.warnings" :key="'warn-' + idx"
|
||||
class="rounded-lg bg-white/70 dark:bg-slate-800/70 border border-white/80 dark:border-slate-700 px-3 py-2 text-sm text-amber-700 dark:text-amber-300">
|
||||
{{ warning }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="diagnosis && diagnosis.tips && diagnosis.tips.length" class="mt-3 space-y-2">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400">下一步建议</div>
|
||||
<div v-for="(tip, idx) in diagnosis.tips" :key="'tip-' + idx"
|
||||
class="rounded-lg bg-white/70 dark:bg-slate-800/70 border border-white/80 dark:border-slate-700 px-3 py-2 text-sm text-slate-700 dark:text-slate-200">
|
||||
{{ tip }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="result.tabs && result.tabs.length" class="mt-3 space-y-2">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-400">逐页结果</div>
|
||||
<div v-for="tab in result.tabs"
|
||||
:key="tab.tab_id || tab.session_id || tab.url"
|
||||
class="rounded-lg bg-white/70 dark:bg-slate-800/70 border border-white/80 dark:border-slate-700 px-3 py-2 text-sm text-slate-700 dark:text-slate-200">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium">{{ tab.tab_index ? '页面 #' + tab.tab_index : '浏览器页面' }}</span>
|
||||
<span :class="tab.count > 0 ? 'text-emerald-600 dark:text-emerald-300' : 'text-red-600 dark:text-red-300'">
|
||||
{{ tab.count > 0 ? '命中 ' + tab.count + ' 个' : '未命中' }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="tab.url" class="mt-1 text-xs text-slate-500 dark:text-slate-400 truncate" :title="tab.url">{{ tab.url }}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="result.skipped_busy_tabs"
|
||||
class="mt-3 rounded-lg bg-amber-50/80 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 px-3 py-2 text-sm text-amber-700 dark:text-amber-300">
|
||||
另有 {{ result.skipped_busy_tabs }} 个同站点页面正在执行任务,本次未打断它们。
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="topCandidates.length"
|
||||
class="rounded-xl border border-slate-200 dark:border-slate-700 p-4 bg-white dark:bg-slate-900/20">
|
||||
<div class="flex items-center justify-between gap-3 mb-3">
|
||||
<div>
|
||||
<div class="text-sm font-semibold text-slate-900 dark:text-white">推荐候选选择器</div>
|
||||
<div class="text-xs text-slate-500 dark:text-slate-400">优先把更稳、更容易唯一命中的写法拿去复测。</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-3">
|
||||
<div v-for="(candidate, idx) in topCandidates"
|
||||
:key="candidate.selector + '-' + idx"
|
||||
class="rounded-xl border border-slate-200 dark:border-slate-700 p-3 bg-slate-50/70 dark:bg-slate-800/60">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-2">
|
||||
<span class="text-xs font-semibold text-slate-400 dark:text-slate-500">候选 {{ idx + 1 }}</span>
|
||||
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs font-medium"
|
||||
:class="uniqueBadgeClass(candidate)">
|
||||
{{ candidate.unique ? '唯一命中' : '匹配 ' + candidate.count + ' 个' }}
|
||||
</span>
|
||||
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300">
|
||||
{{ candidate.reason }}
|
||||
</span>
|
||||
</div>
|
||||
<code class="block whitespace-pre-wrap break-all rounded-lg bg-slate-950 px-3 py-2 text-xs leading-6 text-slate-100">{{ candidate.selector }}</code>
|
||||
<div class="mt-3 flex flex-wrap gap-2">
|
||||
<button @click="useCandidate(candidate.selector)"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1 text-xs">
|
||||
代入输入框
|
||||
</button>
|
||||
<button @click="retestCandidate(candidate.selector)"
|
||||
:disabled="testing"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1 text-xs"
|
||||
:class="{'opacity-50 cursor-not-allowed': testing}">
|
||||
代入并重测
|
||||
</button>
|
||||
<button v-if="selectorKey"
|
||||
@click="applyCandidate(candidate.selector, false)"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1 text-xs">
|
||||
回填字段
|
||||
</button>
|
||||
<button @click="copyText(candidate.selector)"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1 text-xs">
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="min-h-0 overflow-auto pl-1 space-y-4">
|
||||
<div class="rounded-xl border border-slate-200 dark:border-slate-700 p-4 bg-white dark:bg-slate-900/20">
|
||||
<div class="text-sm font-semibold text-slate-900 dark:text-white mb-2">命中详情</div>
|
||||
<div class="text-xs text-slate-500 dark:text-slate-400 mb-3">
|
||||
{{ result ? '已展开 ' + resultElements.length + ' 个元素详情' + (result.truncated ? '(其余命中已省略)' : '') : '先跑一次测试,这里会显示命中的元素摘要和属性。' }}
|
||||
</div>
|
||||
|
||||
<div v-if="!result" class="rounded-lg border border-dashed border-slate-300 dark:border-slate-700 px-3 py-6 text-sm text-slate-500 dark:text-slate-400 text-center">
|
||||
暂无测试结果
|
||||
</div>
|
||||
|
||||
<div v-else-if="!resultElements.length" class="rounded-lg border border-dashed border-slate-300 dark:border-slate-700 px-3 py-6 text-sm text-slate-500 dark:text-slate-400 text-center">
|
||||
这次没有拿到可展示的元素摘要
|
||||
</div>
|
||||
|
||||
<div v-else class="space-y-3">
|
||||
<div v-for="element in resultElements"
|
||||
:key="'element-' + element.index"
|
||||
class="rounded-xl border border-slate-200 dark:border-slate-700 p-3 bg-slate-50/70 dark:bg-slate-800/60">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-2">
|
||||
<span class="text-xs font-semibold text-slate-400 dark:text-slate-500">#{{ element.index + 1 }}</span>
|
||||
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs bg-slate-100 text-slate-700 dark:bg-slate-700 dark:text-slate-200">
|
||||
<{{ element.tag || 'unknown' }}>
|
||||
</span>
|
||||
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-xs"
|
||||
:class="element.visible ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300' : 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300'">
|
||||
{{ element.visible ? '可见' : '不可见/尺寸为 0' }}
|
||||
</span>
|
||||
<span v-if="element.rect"
|
||||
class="inline-flex items-center rounded-full px-2 py-0.5 text-xs bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300">
|
||||
{{ element.rect.width }}×{{ element.rect.height }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div v-if="element.text"
|
||||
class="text-sm leading-6 text-slate-700 dark:text-slate-200 mb-2">
|
||||
{{ element.text }}
|
||||
</div>
|
||||
|
||||
<div v-if="element.attributes && Object.keys(element.attributes).length"
|
||||
class="flex flex-wrap gap-2 mb-2">
|
||||
<span v-for="(value, key) in element.attributes"
|
||||
:key="key"
|
||||
class="inline-flex max-w-full items-center rounded-full border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/70 px-2.5 py-1 text-[11px] text-slate-600 dark:text-slate-300">
|
||||
<strong class="mr-1">{{ key }}</strong>
|
||||
<span class="truncate">{{ value }}</span>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<details v-if="element.html_preview" class="mb-2">
|
||||
<summary class="cursor-pointer text-xs font-medium text-blue-600 dark:text-blue-300">查看 HTML 摘要</summary>
|
||||
<pre class="mt-2 whitespace-pre-wrap break-all rounded-lg bg-slate-950 px-3 py-2 text-[11px] leading-5 text-slate-100">{{ element.html_preview }}</pre>
|
||||
</details>
|
||||
|
||||
<div v-if="element.warnings && element.warnings.length" class="space-y-1 mb-2">
|
||||
<div v-for="(warning, idx) in element.warnings"
|
||||
:key="'element-warning-' + element.index + '-' + idx"
|
||||
class="rounded-lg bg-amber-50 dark:bg-amber-900/20 border border-amber-200 dark:border-amber-800 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
|
||||
{{ warning }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="element.candidate_selectors && element.candidate_selectors.length" class="space-y-2">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.14em] text-slate-400 dark:text-slate-500">这个元素的候选</div>
|
||||
<div v-for="candidate in element.candidate_selectors"
|
||||
:key="candidate.selector"
|
||||
class="rounded-lg border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/70 p-2">
|
||||
<div class="flex flex-wrap items-center gap-2 mb-1">
|
||||
<span class="inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium"
|
||||
:class="uniqueBadgeClass(candidate)">
|
||||
{{ candidate.unique ? '唯一命中' : '匹配 ' + candidate.count + ' 个' }}
|
||||
</span>
|
||||
<span class="text-[11px] text-slate-500 dark:text-slate-400">{{ candidate.reason }}</span>
|
||||
</div>
|
||||
<code class="block whitespace-pre-wrap break-all text-[11px] leading-5 text-slate-700 dark:text-slate-100">{{ candidate.selector }}</code>
|
||||
<div class="mt-2 flex flex-wrap gap-2">
|
||||
<button @click="useCandidate(candidate.selector)"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-2.5 py-1 text-[11px]">
|
||||
代入
|
||||
</button>
|
||||
<button @click="copyText(candidate.selector)"
|
||||
class="border dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-2.5 py-1 text-[11px]">
|
||||
复制
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex justify-end gap-2">
|
||||
<button @click="$emit('close')"
|
||||
class="border dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1.5 text-sm">
|
||||
关闭
|
||||
</button>
|
||||
<button @click="$emit('test', { selector: selectorInput, timeout, highlight })"
|
||||
:disabled="!selectorInput.trim() || testing"
|
||||
class="border rounded transition-colors bg-blue-500 text-white hover:bg-blue-600 border-blue-500 px-3 py-1.5 text-sm font-medium"
|
||||
:class="{'opacity-50 cursor-not-allowed': !selectorInput.trim() || testing}">
|
||||
{{ testing ? '测试中...' : '重新测试' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
// -------------------- 导入确认弹窗 --------------------
|
||||
window.ImportDialog = {
|
||||
name: 'ImportDialog',
|
||||
props: {
|
||||
show: { type: Boolean, default: false },
|
||||
fileName: { type: String, default: '' },
|
||||
importType: { type: String, default: 'full' },
|
||||
suggestedDomain: { type: String, default: '' },
|
||||
importedConfig: { type: Object, default: null }
|
||||
},
|
||||
emits: ['close', 'confirm'],
|
||||
data() {
|
||||
return {
|
||||
mode: 'merge',
|
||||
singleDomain: ''
|
||||
};
|
||||
},
|
||||
watch: {
|
||||
show(val) {
|
||||
if (val) {
|
||||
this.mode = 'merge';
|
||||
this.singleDomain = this.suggestedDomain || '';
|
||||
}
|
||||
},
|
||||
suggestedDomain(val) {
|
||||
if (this.show && !this.singleDomain.trim()) {
|
||||
this.singleDomain = val || '';
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
singleImportHint() {
|
||||
if (this.suggestedDomain) {
|
||||
return '已从导入文件推断站点名,直接确认即可,也可以手动修改。';
|
||||
}
|
||||
return '未识别出站点名时,再手动补充即可。';
|
||||
},
|
||||
mergeDescription() {
|
||||
if (this.importType === 'single') {
|
||||
return '保留当前站点里未导入的预设;导入文件中的同名预设会被覆盖。';
|
||||
}
|
||||
return '只导入文件里的站点;同名站点整站覆盖,未出现在文件中的站点会保留。';
|
||||
},
|
||||
replaceDescription() {
|
||||
if (this.importType === 'single') {
|
||||
return '用导入文件完整替换这个站点,当前站点已有预设和设置都会被清掉。';
|
||||
}
|
||||
return '先清空当前全部站点配置,再写入导入文件中的站点。';
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div v-if="show"
|
||||
class="fixed inset-0 bg-black/50 flex items-center justify-center z-40"
|
||||
@click.self="$emit('close')">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-[450px]">
|
||||
<h3 class="font-semibold dark:text-white mb-4">导入配置</h3>
|
||||
|
||||
<div class="mb-4 p-3 bg-gray-50 dark:bg-gray-900 rounded border dark:border-gray-700">
|
||||
<div class="text-sm dark:text-gray-300">
|
||||
<span class="text-gray-600 dark:text-gray-400">文件:</span> {{ fileName }}
|
||||
</div>
|
||||
<div class="text-sm dark:text-gray-300 mt-1">
|
||||
<span class="text-gray-600 dark:text-gray-400">类型:</span>
|
||||
{{ importType === 'single' ? '单站点配置' : '全量配置 (' + Object.keys(importedConfig || {}).length + ' 个站点)' }}
|
||||
</div>
|
||||
<div v-if="importType === 'full' && importedConfig"
|
||||
class="text-xs text-gray-500 dark:text-gray-400 mt-2 max-h-24 overflow-auto">
|
||||
{{ Object.keys(importedConfig).join(', ') }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 单站点导入时需要输入域名 -->
|
||||
<div v-if="importType === 'single'" class="mb-4">
|
||||
<label class="text-sm text-gray-600 dark:text-gray-400 mb-2 block">站点名</label>
|
||||
<input v-model="singleDomain"
|
||||
placeholder="例如: chat.openai.com"
|
||||
class="border dark:border-gray-700 px-3 py-2 rounded w-full text-sm bg-white dark:bg-gray-700 dark:text-white">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ singleImportHint }}</p>
|
||||
</div>
|
||||
|
||||
<div class="mb-4">
|
||||
<label class="text-sm text-gray-600 dark:text-gray-400 mb-2 block">导入模式</label>
|
||||
<div class="space-y-2">
|
||||
<label class="flex items-center cursor-pointer">
|
||||
<input type="radio" v-model="mode" value="merge" class="mr-2">
|
||||
<span class="dark:text-gray-300">合并导入</span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 ml-2">({{ mergeDescription }})</span>
|
||||
</label>
|
||||
<label class="flex items-center cursor-pointer">
|
||||
<input type="radio" v-model="mode" value="replace" class="mr-2">
|
||||
<span class="dark:text-gray-300">完全替换</span>
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 ml-2">({{ replaceDescription }})</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2">
|
||||
<button @click="$emit('close')"
|
||||
class="border dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-3 py-1 text-sm">
|
||||
取消
|
||||
</button>
|
||||
<button @click="$emit('confirm', { mode, domain: singleDomain })"
|
||||
:disabled="importType === 'single' && !singleDomain.trim()"
|
||||
:class="['border rounded transition-colors px-3 py-1 text-sm',
|
||||
importType === 'single' && !singleDomain.trim()
|
||||
? 'bg-blue-400 cursor-not-allowed opacity-70 text-white border-blue-400'
|
||||
: 'bg-blue-500 text-white hover:bg-blue-600 border-blue-500']">
|
||||
确认导入
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
// -------------------- 新增/编辑元素定义弹窗 --------------------
|
||||
window.DefinitionDialog = {
|
||||
name: 'DefinitionDialog',
|
||||
props: {
|
||||
show: { type: Boolean, default: false },
|
||||
editIndex: { type: Number, default: null },
|
||||
definition: { type: Object, default: () => ({ key: '', description: '', enabled: true }) }
|
||||
},
|
||||
emits: ['close', 'save'],
|
||||
data() {
|
||||
return {
|
||||
form: { key: '', description: '', enabled: true }
|
||||
};
|
||||
},
|
||||
watch: {
|
||||
show(val) {
|
||||
if (val) {
|
||||
this.form = { ...this.definition };
|
||||
}
|
||||
}
|
||||
},
|
||||
computed: {
|
||||
isEdit() {
|
||||
return this.editIndex !== null;
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div v-if="show"
|
||||
class="fixed inset-0 bg-black/50 flex items-center justify-center z-40"
|
||||
@click.self="$emit('close')">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-[500px]">
|
||||
<h3 class="font-semibold dark:text-white mb-4">
|
||||
{{ isEdit ? '编辑元素定义' : '新增元素定义' }}
|
||||
</h3>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="text-sm text-gray-600 dark:text-gray-400 mb-2 block">关键词 (key)</label>
|
||||
<input v-model="form.key"
|
||||
:disabled="isEdit && definition.required"
|
||||
placeholder="例如: temp_chat_btn"
|
||||
class="border dark:border-gray-700 px-3 py-2 rounded w-full font-mono text-sm bg-white dark:bg-gray-700 dark:text-white disabled:opacity-50">
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
用于工作流配置中引用此元素
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="text-sm text-gray-600 dark:text-gray-400 mb-2 block">描述 (发送给 AI)</label>
|
||||
<textarea v-model="form.description"
|
||||
placeholder="例如: 临时对话/隐私模式的切换按钮"
|
||||
rows="3"
|
||||
class="border dark:border-gray-700 px-3 py-2 rounded w-full text-sm bg-white dark:bg-gray-700 dark:text-white resize-none"></textarea>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
AI 会根据这个描述在页面中查找对应的元素
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between">
|
||||
<span class="text-sm dark:text-gray-300">默认启用</span>
|
||||
<label class="toggle-label">
|
||||
<input type="checkbox" v-model="form.enabled" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex justify-end gap-2 mt-6">
|
||||
<button @click="$emit('close')"
|
||||
class="border dark:border-gray-700 rounded hover:bg-gray-100 dark:hover:bg-gray-700 dark:text-white transition-colors px-4 py-2 text-sm">
|
||||
取消
|
||||
</button>
|
||||
<button @click="$emit('save', form)"
|
||||
class="border rounded transition-colors bg-blue-500 text-white hover:bg-blue-600 border-blue-500 px-4 py-2 text-sm">
|
||||
{{ isEdit ? '保存' : '添加' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,276 @@
|
||||
// ==================== 提取器管理 Tab 组件 ====================
|
||||
window.ExtractorTab = {
|
||||
name: 'ExtractorTab',
|
||||
props: {
|
||||
extractors: { type: Array, default: () => [] },
|
||||
defaultExtractorId: { type: String, default: '' },
|
||||
sites: { type: Object, default: () => ({}) },
|
||||
isLoading: { type: Boolean, default: false }
|
||||
},
|
||||
emits: [
|
||||
'set-default',
|
||||
'export-config',
|
||||
'import-config',
|
||||
'set-site-extractor',
|
||||
'open-verify-dialog',
|
||||
'refresh'
|
||||
],
|
||||
data() {
|
||||
return {
|
||||
activeSection: 'extractors', // 'extractors' | 'bindings'
|
||||
searchQuery: '',
|
||||
showImportDialog: false,
|
||||
importText: '',
|
||||
importError: ''
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
// 过滤后的站点列表
|
||||
filteredSites() {
|
||||
const domains = Object.keys(this.sites);
|
||||
if (!this.searchQuery) return domains;
|
||||
const query = this.searchQuery.toLowerCase();
|
||||
return domains.filter(d => d.toLowerCase().includes(query));
|
||||
},
|
||||
|
||||
// 获取站点的提取器信息
|
||||
getSiteExtractorInfo() {
|
||||
return (domain) => {
|
||||
const site = this.sites[domain];
|
||||
const extractorId = site?.extractor_id || this.defaultExtractorId;
|
||||
const extractor = this.extractors.find(e => e.id === extractorId);
|
||||
return {
|
||||
id: extractorId,
|
||||
name: extractor?.name || extractorId,
|
||||
verified: site?.extractor_verified || false,
|
||||
isDefault: !site?.extractor_id
|
||||
};
|
||||
};
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
handleImport() {
|
||||
this.importError = '';
|
||||
try {
|
||||
const config = JSON.parse(this.importText);
|
||||
if (!config.extractors) {
|
||||
this.importError = '无效的配置格式:缺少 extractors 字段';
|
||||
return;
|
||||
}
|
||||
this.$emit('import-config', config);
|
||||
this.showImportDialog = false;
|
||||
this.importText = '';
|
||||
} catch (e) {
|
||||
this.importError = 'JSON 解析失败: ' + e.message;
|
||||
}
|
||||
},
|
||||
|
||||
openImportDialog() {
|
||||
this.importText = '';
|
||||
this.importError = '';
|
||||
this.showImportDialog = true;
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="h-full flex flex-col">
|
||||
<!-- 顶部标签切换 -->
|
||||
<div class="border-b dark:border-gray-700 bg-white dark:bg-gray-800 px-4">
|
||||
<div class="flex gap-4">
|
||||
<button @click="activeSection = 'extractors'"
|
||||
:class="['py-3 px-1 border-b-2 font-medium text-sm transition-colors',
|
||||
activeSection === 'extractors'
|
||||
? 'border-blue-500 text-blue-600 dark:text-blue-400'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200']">
|
||||
📦 提取器列表
|
||||
</button>
|
||||
<button @click="activeSection = 'bindings'"
|
||||
:class="['py-3 px-1 border-b-2 font-medium text-sm transition-colors',
|
||||
activeSection === 'bindings'
|
||||
? 'border-blue-500 text-blue-600 dark:text-blue-400'
|
||||
: 'border-transparent text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200']">
|
||||
🔗 站点绑定
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容区域 -->
|
||||
<div class="flex-1 overflow-auto p-4">
|
||||
<!-- 加载状态 -->
|
||||
<div v-if="isLoading" class="flex items-center justify-center h-full">
|
||||
<div class="text-gray-500 dark:text-gray-400">
|
||||
<span class="animate-spin inline-block mr-2">⏳</span> 加载中...
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 提取器列表 -->
|
||||
<div v-else-if="activeSection === 'extractors'" class="space-y-4">
|
||||
<!-- 操作栏 -->
|
||||
<div class="flex justify-between items-center">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">
|
||||
可用提取器 ({{ extractors.length }})
|
||||
</h3>
|
||||
<div class="flex gap-2">
|
||||
<button @click="$emit('refresh')"
|
||||
class="px-3 py-1.5 text-sm border dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 transition-colors">
|
||||
🔄 刷新
|
||||
</button>
|
||||
<button @click="openImportDialog"
|
||||
class="px-3 py-1.5 text-sm border dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 transition-colors">
|
||||
📥 导入
|
||||
</button>
|
||||
<button @click="$emit('export-config')"
|
||||
class="px-3 py-1.5 text-sm border dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-200 transition-colors">
|
||||
📤 导出
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 提取器卡片列表 -->
|
||||
<div class="grid gap-4">
|
||||
<div v-for="extractor in extractors" :key="extractor.id"
|
||||
class="bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg p-4 hover:shadow-md transition-shadow">
|
||||
<div class="flex justify-between items-start">
|
||||
<div class="flex-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-semibold text-gray-900 dark:text-white">
|
||||
{{ extractor.name }}
|
||||
</span>
|
||||
<span v-if="extractor.id === defaultExtractorId"
|
||||
class="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded-full">
|
||||
默认
|
||||
</span>
|
||||
<span v-if="!extractor.enabled"
|
||||
class="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded-full">
|
||||
已禁用
|
||||
</span>
|
||||
</div>
|
||||
<div class="text-sm text-gray-500 dark:text-gray-400 mt-1">
|
||||
ID: <code class="bg-gray-100 dark:bg-gray-700 px-1 rounded">{{ extractor.id }}</code>
|
||||
</div>
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300 mt-2">
|
||||
{{ extractor.description || '暂无描述' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex gap-2 ml-4">
|
||||
<button v-if="extractor.id !== defaultExtractorId"
|
||||
@click="$emit('set-default', extractor.id)"
|
||||
class="px-3 py-1 text-sm text-blue-600 dark:text-blue-400 border border-blue-300 dark:border-blue-600 rounded hover:bg-blue-50 dark:hover:bg-blue-900/30 transition-colors">
|
||||
设为默认
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="extractors.length === 0"
|
||||
class="text-center py-12 text-gray-400 dark:text-gray-500">
|
||||
暂无可用的提取器
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 站点绑定 -->
|
||||
<div v-else-if="activeSection === 'bindings'" class="space-y-4">
|
||||
<!-- 搜索和说明 -->
|
||||
<div class="flex justify-between items-center">
|
||||
<div>
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white">站点提取器绑定</h3>
|
||||
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
|
||||
为每个站点指定使用的提取算法
|
||||
</p>
|
||||
</div>
|
||||
<input v-model="searchQuery"
|
||||
type="search"
|
||||
placeholder="搜索站点..."
|
||||
class="border dark:border-gray-600 px-3 py-1.5 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-400">
|
||||
</div>
|
||||
|
||||
<!-- 站点列表 -->
|
||||
<div class="space-y-2">
|
||||
<div v-for="domain in filteredSites" :key="domain"
|
||||
class="bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex-1">
|
||||
<div class="font-medium text-gray-900 dark:text-white">{{ domain }}</div>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">
|
||||
当前: {{ getSiteExtractorInfo(domain).name }}
|
||||
</span>
|
||||
<span v-if="getSiteExtractorInfo(domain).isDefault"
|
||||
class="text-xs text-gray-400 dark:text-gray-500">
|
||||
(使用默认)
|
||||
</span>
|
||||
<span v-if="getSiteExtractorInfo(domain).verified"
|
||||
class="px-1.5 py-0.5 text-xs bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 rounded">
|
||||
✓ 已验证
|
||||
</span>
|
||||
<span v-else
|
||||
class="px-1.5 py-0.5 text-xs bg-yellow-100 dark:bg-yellow-900/50 text-yellow-700 dark:text-yellow-300 rounded">
|
||||
⚠ 未验证
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<select @change="$emit('set-site-extractor', domain, $event.target.value)"
|
||||
:value="getSiteExtractorInfo(domain).id"
|
||||
class="border dark:border-gray-600 px-2 py-1.5 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-400">
|
||||
<option v-for="ext in extractors" :key="ext.id" :value="ext.id">
|
||||
{{ ext.name }}
|
||||
</option>
|
||||
</select>
|
||||
<button @click="$emit('open-verify-dialog', domain)"
|
||||
class="px-3 py-1.5 text-sm text-blue-600 dark:text-blue-400 border border-blue-300 dark:border-blue-600 rounded hover:bg-blue-50 dark:hover:bg-blue-900/30 transition-colors">
|
||||
测试
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="filteredSites.length === 0"
|
||||
class="text-center py-12 text-gray-400 dark:text-gray-500">
|
||||
{{ searchQuery ? '无匹配结果' : '暂无站点配置' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 导入弹窗 -->
|
||||
<div v-if="showImportDialog"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
|
||||
@click.self="showImportDialog = false">
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-lg mx-4">
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center">
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">导入提取器配置</h3>
|
||||
<button @click="showImportDialog = false"
|
||||
class="text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200">
|
||||
✕
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-4 space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
粘贴 extractors.json 内容
|
||||
</label>
|
||||
<textarea v-model="importText"
|
||||
rows="10"
|
||||
class="w-full border dark:border-gray-600 rounded-md p-2 font-mono text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:outline-none focus:ring-2 focus:ring-blue-400"
|
||||
placeholder='{"extractors": {...}, "default": "..."}'></textarea>
|
||||
</div>
|
||||
<div v-if="importError" class="text-sm text-red-500">
|
||||
{{ importError }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="px-4 py-3 border-t dark:border-gray-700 flex justify-end gap-2">
|
||||
<button @click="showImportDialog = false"
|
||||
class="px-4 py-2 text-sm text-gray-700 dark:text-gray-200 border dark:border-gray-600 rounded-md hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors">
|
||||
取消
|
||||
</button>
|
||||
<button @click="handleImport"
|
||||
class="px-4 py-2 text-sm text-white bg-blue-500 rounded-md hover:bg-blue-600 transition-colors">
|
||||
导入
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,181 @@
|
||||
window.HomeTab = {
|
||||
name: 'HomeTab',
|
||||
props: {
|
||||
sites: { type: Object, default: () => ({}) },
|
||||
browserStatus: { type: Object, default: () => ({ connected: false }) },
|
||||
systemStats: { type: Object, default: () => ({}) },
|
||||
records: { type: Array, default: () => [] }
|
||||
},
|
||||
emits: ['change-tab', 'add-site', 'notify'],
|
||||
computed: {
|
||||
siteCount() {
|
||||
return Object.keys(this.sites || {}).length;
|
||||
},
|
||||
sortedRecords() {
|
||||
return (Array.isArray(this.records) ? this.records : []).slice().sort((a, b) => {
|
||||
return this.recordTimestamp(b) - this.recordTimestamp(a);
|
||||
});
|
||||
},
|
||||
recentRecords() {
|
||||
return this.sortedRecords.slice(0, 3);
|
||||
},
|
||||
totalRequests() {
|
||||
const reported = Number(this.systemStats && this.systemStats.total_requests || 0);
|
||||
return reported > 0 ? reported : this.sortedRecords.length;
|
||||
},
|
||||
averageDurationMs() {
|
||||
const completed = this.sortedRecords.filter(record => {
|
||||
return record && record.success && Number(record.duration_ms || 0) > 0;
|
||||
});
|
||||
if (!completed.length) return 0;
|
||||
return Math.round(completed.reduce((total, record) => total + Number(record.duration_ms || 0), 0) / completed.length);
|
||||
},
|
||||
baseUrl() {
|
||||
const origin = typeof window !== 'undefined' ? window.location.origin : 'http://127.0.0.1:8199';
|
||||
return origin + '/v1';
|
||||
},
|
||||
heroTitle() {
|
||||
return this.browserStatus && this.browserStatus.connected
|
||||
? '本地 API 已准备就绪'
|
||||
: '本地 API 正在等待浏览器';
|
||||
},
|
||||
browserLabel() {
|
||||
if (!(this.browserStatus && this.browserStatus.connected)) return '等待浏览器连接';
|
||||
// 修复:此前读的 tab_title / tab_url 后端从未返回(health_check 只产出
|
||||
// status/connected/port/tab_pool/error),导致这里恒为兜底文案。
|
||||
// 改用 health 里真实存在的 tab_pool 概览。
|
||||
const pool = this.browserStatus.tab_pool;
|
||||
if (pool && typeof pool === 'object') {
|
||||
const total = Number(pool.total || 0);
|
||||
const busy = Number(pool.busy || 0);
|
||||
const idle = Number(pool.idle || 0);
|
||||
if (total > 0) return `受控浏览器已连接 · ${total} 个标签页(忙碌 ${busy} / 空闲 ${idle})`;
|
||||
}
|
||||
return '受控浏览器已连接';
|
||||
},
|
||||
latestRecord() {
|
||||
return this.sortedRecords[0] || null;
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
recordTimestamp(record) {
|
||||
return Number(record && (record.finished_at || record.started_at || record.created_at || record.timestamp) || 0);
|
||||
},
|
||||
recordDomain(record) {
|
||||
return String(record && (record.domain || record.site_domain || record.target_domain || record.model || record.route_group) || '未知站点');
|
||||
},
|
||||
recordStatus(record) {
|
||||
if (record && record.success) return '成功';
|
||||
if (record && record.status === 'cancelled') return '已取消';
|
||||
return '失败';
|
||||
},
|
||||
recordStatusClass(record) {
|
||||
if (record && record.success) return 'is-success';
|
||||
if (record && record.status === 'cancelled') return 'is-cancelled';
|
||||
return 'is-failed';
|
||||
},
|
||||
recordDuration(record) {
|
||||
const value = Number(record && record.duration_ms || 0);
|
||||
if (!value) return '-';
|
||||
return value >= 1000 ? (value / 1000).toFixed(value >= 10000 ? 1 : 2) + 's' : Math.round(value) + 'ms';
|
||||
},
|
||||
recordTime(record) {
|
||||
const timestamp = this.recordTimestamp(record);
|
||||
if (!timestamp) return '-';
|
||||
return new Date(timestamp * 1000).toLocaleTimeString('zh-CN', {
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit'
|
||||
});
|
||||
},
|
||||
averageDurationText() {
|
||||
if (!this.averageDurationMs) return '-';
|
||||
return this.recordDuration({ duration_ms: this.averageDurationMs });
|
||||
},
|
||||
async copyBaseUrl() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(this.baseUrl);
|
||||
this.$emit('notify', { message: 'API 地址已复制', type: 'success' });
|
||||
} catch (error) {
|
||||
this.$emit('notify', { message: '复制失败,请手动复制地址', type: 'error' });
|
||||
}
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<section class="uwa-home-view" aria-labelledby="home-title">
|
||||
<div class="uwa-hero-band">
|
||||
<div class="uwa-hero-copy">
|
||||
<div class="uwa-ready-label"><span v-html="$icons.activity"></span> Web to API, ready</div>
|
||||
<h1 id="home-title">{{ heroTitle }}</h1>
|
||||
<p>连接已登录的 AI 网页,把常用模型作为兼容 OpenAI / Anthropic 的本地接口使用。</p>
|
||||
</div>
|
||||
<div class="uwa-hero-art" aria-hidden="true">
|
||||
<i class="shape-a"></i><i class="shape-b"></i><i class="shape-c"></i>
|
||||
<i class="line-a"></i><i class="line-b"></i>
|
||||
<i class="node-a"></i><i class="node-b"></i><i class="node-c"></i>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="uwa-health-strip" aria-label="服务概览">
|
||||
<div class="uwa-health-item">
|
||||
<span class="uwa-health-icon is-service" v-html="$icons.activity"></span>
|
||||
<div><span>服务状态</span><strong>{{ browserStatus.connected ? '运行正常' : '等待浏览器' }}</strong></div>
|
||||
</div>
|
||||
<div class="uwa-health-item">
|
||||
<span class="uwa-health-icon is-sites" v-html="$icons.globe"></span>
|
||||
<div><span>可用站点</span><strong>{{ siteCount }} 个站点</strong></div>
|
||||
</div>
|
||||
<div class="uwa-health-item">
|
||||
<span class="uwa-health-icon is-requests" v-html="$icons.arrowPathRoundedSquare"></span>
|
||||
<div><span>累计请求</span><strong>{{ totalRequests.toLocaleString('zh-CN') }} 次</strong></div>
|
||||
</div>
|
||||
<div class="uwa-health-item">
|
||||
<span class="uwa-health-icon is-latency" v-html="$icons.timer"></span>
|
||||
<div><span>样本平均响应</span><strong>{{ averageDurationText() }}</strong></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="uwa-section-heading">
|
||||
<div><h2>开始使用</h2><p>选择当前最需要处理的任务。</p></div>
|
||||
<button type="button" class="uwa-text-button" @click="$emit('change-tab', 'monitor')">查看运行详情 <span v-html="$icons.arrowRight"></span></button>
|
||||
</div>
|
||||
|
||||
<div class="uwa-action-grid">
|
||||
<article class="uwa-action-card is-api">
|
||||
<div class="uwa-card-topline"><span class="uwa-feature-icon is-mint" v-html="$icons.arrowPathRoundedSquare"></span><span class="uwa-soft-tag">本机</span></div>
|
||||
<h3>连接 API 客户端</h3>
|
||||
<p>复制当前服务 Base URL,在兼容 OpenAI 的客户端中直接使用。</p>
|
||||
<div class="uwa-endpoint-box"><code>{{ baseUrl }}</code><button type="button" @click="copyBaseUrl" title="复制 API 地址" aria-label="复制 API 地址" v-html="$icons.copy"></button></div>
|
||||
<button type="button" class="uwa-primary-button" @click="copyBaseUrl">复制 API 地址 <span v-html="$icons.arrowRight"></span></button>
|
||||
</article>
|
||||
|
||||
<article class="uwa-action-card is-browser">
|
||||
<div class="uwa-card-topline"><span class="uwa-feature-icon is-olive" v-html="$icons.folderOpen"></span><span class="uwa-soft-tag">{{ browserStatus.connected ? '已连接' : '未连接' }}</span></div>
|
||||
<h3>管理受控浏览器</h3>
|
||||
<p>检查当前浏览器连接与标签页占用情况,快速定位失效会话。</p>
|
||||
<div class="uwa-browser-preview">
|
||||
<div><i></i><i></i><i></i><span>{{ browserStatus.connected ? '浏览器在线' : '浏览器离线' }}</span></div>
|
||||
<strong :title="browserLabel">{{ browserLabel }}</strong>
|
||||
</div>
|
||||
<button type="button" class="uwa-primary-button" @click="$emit('change-tab', 'tabpool')">查看标签页池 <span v-html="$icons.arrowRight"></span></button>
|
||||
</article>
|
||||
|
||||
<article class="uwa-action-card is-monitor">
|
||||
<div class="uwa-card-topline"><span class="uwa-feature-icon is-ochre" v-html="$icons.activity"></span><span class="uwa-soft-tag">实时</span></div>
|
||||
<h3>检查最近请求</h3>
|
||||
<p>查看模型路由、响应耗时与异常详情,定位客户端接入问题。</p>
|
||||
<div class="uwa-request-preview" v-if="recentRecords.length">
|
||||
<div v-for="record in recentRecords" :key="record.id || record.history_key || recordTimestamp(record)">
|
||||
<i :class="recordStatusClass(record)"></i><strong>{{ recordDomain(record) }}</strong><span>{{ recordStatus(record) }}</span><time>{{ recordDuration(record) }}</time>
|
||||
</div>
|
||||
</div>
|
||||
<div class="uwa-empty-preview" v-else>暂无请求记录</div>
|
||||
<button type="button" class="uwa-primary-button" @click="$emit('change-tab', 'monitor')">打开请求监控 <span v-html="$icons.arrowRight"></span></button>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<div class="uwa-activity-band" v-if="latestRecord">
|
||||
<div><span v-html="$icons.arrowPath"></span><div><strong>最近活动</strong><span>{{ recordDomain(latestRecord) }} · {{ recordStatus(latestRecord) }}</span></div></div>
|
||||
<div><span>{{ latestRecord.endpoint || latestRecord.request_type || 'API 请求' }}</span><strong>{{ recordDuration(latestRecord) }}</strong><time>{{ recordTime(latestRecord) }}</time></div>
|
||||
</div>
|
||||
</section>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,476 @@
|
||||
// ==================== 日志 Tab 组件 ====================
|
||||
window.LogsTab = {
|
||||
name: 'LogsTab',
|
||||
props: {
|
||||
logs: { type: Array, required: true },
|
||||
filter: { type: String, default: 'ALL' },
|
||||
paused: { type: Boolean, default: false }
|
||||
},
|
||||
emits: ['clear', 'change-filter', 'toggle-pause'],
|
||||
data() {
|
||||
return {
|
||||
expandedRawLogs: {},
|
||||
collapsedRequestGroups: {},
|
||||
selectedRequestId: 'ALL',
|
||||
viewMode: 'requests',
|
||||
copiedLogId: null
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
filteredLogs() {
|
||||
if (this.filter === 'ALL') {
|
||||
return this.logs;
|
||||
}
|
||||
if (this.filter === 'INFO') {
|
||||
// 修复:normalizeLogLevel 会把带 [AI] / [OK] 标记的 INFO 日志重分类成 'AI' / 'OK',
|
||||
// 此前只按重分类后的 level 过滤,导致 INFO 档漏掉全部 [AI] 日志。
|
||||
// rawLevel 保留了服务端原始级别,用它兜底把 INFO 还原成超集。
|
||||
return this.logs.filter(log =>
|
||||
log.rawLevel === 'INFO' || log.level === 'INFO' || log.level === 'OK'
|
||||
);
|
||||
}
|
||||
return this.logs.filter(log => log.level === this.filter);
|
||||
},
|
||||
|
||||
requestOptions() {
|
||||
const requests = new Map();
|
||||
this.filteredLogs.forEach(log => {
|
||||
const requestId = this.getRequestId(log);
|
||||
const existing = requests.get(requestId);
|
||||
if (existing) {
|
||||
existing.count += 1;
|
||||
existing.lastSeq = Math.max(existing.lastSeq, Number(log.seq || 0));
|
||||
return;
|
||||
}
|
||||
requests.set(requestId, {
|
||||
requestId,
|
||||
requestTag: this.getRequestTag(log),
|
||||
count: 1,
|
||||
firstSeq: Number(log.seq || 0),
|
||||
lastSeq: Number(log.seq || 0)
|
||||
});
|
||||
});
|
||||
return Array.from(requests.values()).sort((left, right) => {
|
||||
if (left.requestId === 'SYSTEM') return 1;
|
||||
if (right.requestId === 'SYSTEM') return -1;
|
||||
return right.firstSeq - left.firstSeq;
|
||||
});
|
||||
},
|
||||
|
||||
requestFilteredLogs() {
|
||||
if (this.selectedRequestId === 'ALL') {
|
||||
return this.filteredLogs;
|
||||
}
|
||||
return this.filteredLogs.filter(log => this.getRequestId(log) === this.selectedRequestId);
|
||||
},
|
||||
|
||||
timelineLogs() {
|
||||
return this.requestFilteredLogs;
|
||||
},
|
||||
|
||||
requestGroups() {
|
||||
const groups = new Map();
|
||||
this.requestFilteredLogs.forEach(log => {
|
||||
const requestId = this.getRequestId(log);
|
||||
let group = groups.get(requestId);
|
||||
if (!group) {
|
||||
group = {
|
||||
requestId,
|
||||
requestTag: this.getRequestTag(log),
|
||||
logs: [],
|
||||
firstTimestamp: log.timestamp || '',
|
||||
lastTimestamp: log.timestamp || '',
|
||||
errorCount: 0,
|
||||
warningCount: 0
|
||||
};
|
||||
groups.set(requestId, group);
|
||||
}
|
||||
group.logs.push(log);
|
||||
group.lastTimestamp = log.timestamp || group.lastTimestamp;
|
||||
if (log.level === 'ERROR') group.errorCount += 1;
|
||||
if (log.level === 'WARN') group.warningCount += 1;
|
||||
});
|
||||
return Array.from(groups.values());
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
logs(nextLogs) {
|
||||
if (
|
||||
this.selectedRequestId !== 'ALL'
|
||||
&& !(nextLogs || []).some(log => this.getRequestId(log) === this.selectedRequestId)
|
||||
) {
|
||||
this.selectedRequestId = 'ALL';
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
getRequestId(log) {
|
||||
return String(log && log.requestId || 'SYSTEM').trim() || 'SYSTEM';
|
||||
},
|
||||
|
||||
getRequestTag(log) {
|
||||
return String(log && (log.requestTag || log.requestId) || 'SYSTEM').trim() || 'SYSTEM';
|
||||
},
|
||||
|
||||
selectRequest(requestId) {
|
||||
this.selectedRequestId = String(requestId || 'ALL');
|
||||
},
|
||||
|
||||
isRequestGroupCollapsed(group) {
|
||||
const key = String(group.requestId);
|
||||
return Object.prototype.hasOwnProperty.call(this.collapsedRequestGroups, key)
|
||||
? Boolean(this.collapsedRequestGroups[key])
|
||||
: true;
|
||||
},
|
||||
|
||||
toggleRequestGroup(group) {
|
||||
const key = String(group.requestId);
|
||||
this.collapsedRequestGroups = {
|
||||
...this.collapsedRequestGroups,
|
||||
[key]: !this.isRequestGroupCollapsed(group)
|
||||
};
|
||||
},
|
||||
|
||||
getRequestGroupStatus(group) {
|
||||
if (group.errorCount > 0) return `${group.errorCount} 条错误`;
|
||||
if (group.warningCount > 0) return `${group.warningCount} 条警告`;
|
||||
return '无异常';
|
||||
},
|
||||
|
||||
getRequestGroupStatusClass(group) {
|
||||
if (group.errorCount > 0) return 'text-red-600 dark:text-red-400';
|
||||
if (group.warningCount > 0) return 'text-yellow-600 dark:text-yellow-400';
|
||||
return 'text-green-600 dark:text-green-400';
|
||||
},
|
||||
|
||||
getLogText(log) {
|
||||
return log.messageText || log.message || '';
|
||||
},
|
||||
|
||||
getRawLogText(log) {
|
||||
return log.originalMessageText || log.message || this.getLogText(log);
|
||||
},
|
||||
|
||||
formatRawLogText(log) {
|
||||
let raw = String(this.getRawLogText(log) || '');
|
||||
if (!raw) return '';
|
||||
|
||||
// 1. 反转义常见控制字符
|
||||
raw = raw.replace(/\\r\\n/g, '\n').replace(/\\n/g, '\n').replace(/\\r/g, '\r').replace(/\\t/g, ' ');
|
||||
|
||||
// 2. 尝试识别并格式化嵌入的 JSON 对象
|
||||
const jsonStartIdx = raw.search(/[\{\[]/);
|
||||
if (jsonStartIdx !== -1) {
|
||||
const prefix = raw.slice(0, jsonStartIdx);
|
||||
const candidate = raw.slice(jsonStartIdx).trim();
|
||||
try {
|
||||
const parsed = JSON.parse(candidate);
|
||||
const pretty = JSON.stringify(parsed, null, 2);
|
||||
return prefix ? `${prefix.trimEnd()}\n${pretty}` : pretty;
|
||||
} catch (e) {
|
||||
// 如果末尾有多余字符,尝试寻找匹配的大括号
|
||||
const lastBraceIdx = Math.max(raw.lastIndexOf('}'), raw.lastIndexOf(']'));
|
||||
if (lastBraceIdx > jsonStartIdx) {
|
||||
try {
|
||||
const subJson = raw.slice(jsonStartIdx, lastBraceIdx + 1);
|
||||
const parsed = JSON.parse(subJson);
|
||||
const pretty = JSON.stringify(parsed, null, 2);
|
||||
const suffix = raw.slice(lastBraceIdx + 1);
|
||||
return `${raw.slice(0, jsonStartIdx).trimEnd()}\n${pretty}${suffix ? '\n' + suffix.trim() : ''}`.trim();
|
||||
} catch (err) {
|
||||
// 降级使用基础反转义文本
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return raw.trim();
|
||||
},
|
||||
|
||||
async copyRawLog(log) {
|
||||
const text = this.formatRawLogText(log);
|
||||
if (!text) return;
|
||||
try {
|
||||
if (navigator && navigator.clipboard && navigator.clipboard.writeText) {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
const textarea = document.createElement('textarea');
|
||||
textarea.value = text;
|
||||
document.body.appendChild(textarea);
|
||||
textarea.select();
|
||||
document.execCommand('copy');
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
this.copiedLogId = String(log.id);
|
||||
setTimeout(() => {
|
||||
if (this.copiedLogId === String(log.id)) {
|
||||
this.copiedLogId = null;
|
||||
}
|
||||
}, 1800);
|
||||
} catch (err) {
|
||||
console.error('复制日志失败:', err);
|
||||
}
|
||||
},
|
||||
|
||||
isCopied(log) {
|
||||
return this.copiedLogId === String(log.id);
|
||||
},
|
||||
|
||||
hasRawLogText(log) {
|
||||
return Boolean(log && log.messageAlias && this.getRawLogText(log));
|
||||
},
|
||||
|
||||
isRawExpanded(log) {
|
||||
return Boolean(this.expandedRawLogs[String(log.id)]);
|
||||
},
|
||||
|
||||
toggleRawLog(log) {
|
||||
const key = String(log.id);
|
||||
this.expandedRawLogs = {
|
||||
...this.expandedRawLogs,
|
||||
[key]: !this.expandedRawLogs[key]
|
||||
};
|
||||
},
|
||||
|
||||
isKeyCmdLog(message) {
|
||||
if (!message || !message.includes('[CMD]')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const keyPatterns = [
|
||||
'[CMD] 执行:',
|
||||
'[CMD] 触发命令:',
|
||||
'[CMD] 链式触发:',
|
||||
'[CMD] 条件分支触发:',
|
||||
'[CMD] 结果事件触发:'
|
||||
];
|
||||
|
||||
return keyPatterns.some(pattern => message.includes(pattern));
|
||||
},
|
||||
|
||||
getLogTone(log) {
|
||||
if (log.level === 'ERROR') return 'ERROR';
|
||||
if (log.level === 'WARN') return 'WARN';
|
||||
if (log.level === 'AI') return 'AI';
|
||||
if (log.level === 'OK') return 'OK';
|
||||
if (log.level === 'DEBUG') return 'DEBUG';
|
||||
if (log.level === 'INFO' && this.isKeyCmdLog(this.getLogText(log))) return 'KEY';
|
||||
return 'INFO';
|
||||
},
|
||||
|
||||
getLogColorClass(log) {
|
||||
const tone = this.getLogTone(log);
|
||||
const colors = {
|
||||
'DEBUG': 'bg-slate-50 dark:bg-slate-900/30',
|
||||
'INFO': 'bg-green-50 dark:bg-green-900/20',
|
||||
'KEY': 'bg-sky-50 dark:bg-sky-900/20',
|
||||
'AI': 'bg-purple-50 dark:bg-purple-900/20',
|
||||
'OK': 'bg-green-50 dark:bg-green-900/20',
|
||||
'WARN': 'bg-yellow-50 dark:bg-yellow-900/20',
|
||||
'ERROR': 'bg-red-50 dark:bg-red-900/20'
|
||||
};
|
||||
return colors[tone] || colors['INFO'];
|
||||
},
|
||||
|
||||
getLogLevelClass(log) {
|
||||
const tone = this.getLogTone(log);
|
||||
const colors = {
|
||||
'DEBUG': 'text-slate-500 dark:text-slate-400',
|
||||
'INFO': 'text-green-600 dark:text-green-400',
|
||||
'KEY': 'text-sky-500 dark:text-sky-300',
|
||||
'AI': 'text-purple-600 dark:text-purple-400',
|
||||
'OK': 'text-green-600 dark:text-green-400',
|
||||
'WARN': 'text-yellow-600 dark:text-yellow-400',
|
||||
'ERROR': 'text-red-600 dark:text-red-400'
|
||||
};
|
||||
return colors[tone] || colors['INFO'];
|
||||
},
|
||||
|
||||
getLogTextClass(log) {
|
||||
// DEBUG 行正文做视觉降噪(灰色弱化),与控制台的暗灰 DEBUG 保持一致
|
||||
return this.getLogTone(log) === 'DEBUG'
|
||||
? 'text-gray-500 dark:text-gray-400'
|
||||
: 'dark:text-gray-200';
|
||||
}
|
||||
},
|
||||
updated() {
|
||||
this.$nextTick(() => {
|
||||
const container = this.$refs.logContainer;
|
||||
if (container) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
});
|
||||
},
|
||||
template: `
|
||||
<div class="logs-workspace h-full flex flex-col bg-white dark:bg-gray-800">
|
||||
<div class="p-3 sm:p-4 border-b dark:border-gray-700 space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="flex flex-wrap gap-2" aria-label="日志级别">
|
||||
<button @click="$emit('change-filter', 'DEBUG')"
|
||||
:class="['px-3 py-1 text-sm rounded',
|
||||
filter === 'DEBUG' ? 'bg-slate-500 text-white' : 'border dark:border-gray-700 dark:text-gray-300']">
|
||||
DEBUG
|
||||
</button>
|
||||
<button @click="$emit('change-filter', 'ALL')"
|
||||
:class="['px-3 py-1 text-sm rounded',
|
||||
filter === 'ALL' ? 'bg-blue-500 text-white' : 'border dark:border-gray-700 dark:text-gray-300']">
|
||||
全部
|
||||
</button>
|
||||
<button @click="$emit('change-filter', 'INFO')"
|
||||
:class="['px-3 py-1 text-sm rounded',
|
||||
filter === 'INFO' ? 'bg-green-500 text-white' : 'border dark:border-gray-700 dark:text-gray-300']">
|
||||
INFO
|
||||
</button>
|
||||
<button @click="$emit('change-filter', 'AI')"
|
||||
:class="['px-3 py-1 text-sm rounded',
|
||||
filter === 'AI' ? 'bg-purple-500 text-white' : 'border dark:border-gray-700 dark:text-gray-300']">
|
||||
AI
|
||||
</button>
|
||||
<button @click="$emit('change-filter', 'WARN')"
|
||||
:class="['px-3 py-1 text-sm rounded',
|
||||
filter === 'WARN' ? 'bg-yellow-500 text-white' : 'border dark:border-gray-700 dark:text-gray-300']">
|
||||
WARN
|
||||
</button>
|
||||
<button @click="$emit('change-filter', 'ERROR')"
|
||||
:class="['px-3 py-1 text-sm rounded',
|
||||
filter === 'ERROR' ? 'bg-red-500 text-white' : 'border dark:border-gray-700 dark:text-gray-300']">
|
||||
ERROR
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button @click="$emit('toggle-pause')"
|
||||
class="inline-flex h-9 items-center gap-1.5 border dark:border-gray-700 rounded px-3 text-sm dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||
<span v-html="paused ? $icons.play : $icons.pause"></span>
|
||||
{{ paused ? '继续' : '暂停' }}
|
||||
</button>
|
||||
<button @click="$emit('clear')"
|
||||
class="inline-flex h-9 items-center gap-1.5 border dark:border-gray-700 rounded px-3 text-sm dark:text-white hover:bg-gray-100 dark:hover:bg-gray-700">
|
||||
<span v-html="$icons.trash"></span> 清除
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center justify-between gap-3">
|
||||
<label class="flex min-w-0 flex-1 items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
|
||||
<span class="shrink-0">请求</span>
|
||||
<select v-model="selectedRequestId"
|
||||
class="h-9 min-w-0 w-full sm:w-72 rounded border border-gray-300 bg-white px-2 text-sm text-gray-800 dark:border-gray-600 dark:bg-gray-900 dark:text-gray-100">
|
||||
<option value="ALL">全部请求({{ requestOptions.length }})</option>
|
||||
<option v-for="option in requestOptions" :key="option.requestId" :value="option.requestId">
|
||||
{{ option.requestTag }} · {{ option.count }} 条
|
||||
</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="inline-flex h-9 shrink-0 rounded border border-gray-300 p-0.5 dark:border-gray-600" aria-label="日志排列方式">
|
||||
<button type="button"
|
||||
@click="viewMode = 'requests'"
|
||||
:class="['rounded px-3 text-sm', viewMode === 'requests' ? 'bg-gray-800 text-white dark:bg-gray-100 dark:text-gray-900' : 'text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700']">
|
||||
按请求
|
||||
</button>
|
||||
<button type="button"
|
||||
@click="viewMode = 'timeline'"
|
||||
:class="['rounded px-3 text-sm', viewMode === 'timeline' ? 'bg-gray-800 text-white dark:bg-gray-100 dark:text-gray-900' : 'text-gray-600 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700']">
|
||||
时间线
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div ref="logContainer" class="flex-1 overflow-auto p-3 sm:p-4 font-mono text-sm">
|
||||
<div v-if="viewMode === 'requests' && requestGroups.length > 0" class="space-y-3">
|
||||
<section v-for="group in requestGroups" :key="group.requestId"
|
||||
class="overflow-hidden rounded border border-gray-200 dark:border-gray-700">
|
||||
<button type="button"
|
||||
@click="toggleRequestGroup(group)"
|
||||
:aria-expanded="!isRequestGroupCollapsed(group)"
|
||||
class="flex w-full flex-wrap items-center justify-between gap-2 bg-gray-50 px-3 py-2 text-left hover:bg-gray-100 dark:bg-gray-900/60 dark:hover:bg-gray-900">
|
||||
<span class="flex min-w-0 items-center gap-2">
|
||||
<span class="text-gray-400" v-html="isRequestGroupCollapsed(group) ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<strong class="text-gray-900 dark:text-gray-100">{{ group.requestTag }}</strong>
|
||||
<span class="truncate text-xs text-gray-500 dark:text-gray-400">{{ group.requestId }}</span>
|
||||
</span>
|
||||
<span class="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<span>{{ group.logs.length }} 条</span>
|
||||
<span>{{ group.firstTimestamp }}<template v-if="group.lastTimestamp && group.lastTimestamp !== group.firstTimestamp"> - {{ group.lastTimestamp }}</template></span>
|
||||
<span :class="getRequestGroupStatusClass(group)">{{ getRequestGroupStatus(group) }}</span>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div v-show="!isRequestGroupCollapsed(group)" class="divide-y divide-gray-200 dark:divide-gray-700">
|
||||
<div v-for="log in group.logs" :key="log.id"
|
||||
:class="['px-3 py-2', getLogColorClass(log)]">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-gray-500 dark:text-gray-300">{{ log.timestamp }}</span>
|
||||
<span :class="['font-bold', getLogLevelClass(log)]">[{{ log.level }}]</span>
|
||||
<span v-if="log.logger" class="px-1.5 py-0.5 rounded bg-white/70 dark:bg-gray-900/40 text-gray-600 dark:text-gray-300">
|
||||
{{ log.logger }}
|
||||
</span>
|
||||
</div>
|
||||
<div :class="['mt-1 break-all whitespace-pre-wrap', getLogTextClass(log)]">
|
||||
<span>{{ getLogText(log) }}</span>
|
||||
<button v-if="hasRawLogText(log)"
|
||||
@click="toggleRawLog(log)"
|
||||
class="ml-2 inline-flex items-center rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-600 hover:bg-white/70 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-900/50">
|
||||
{{ isRawExpanded(log) ? '收起原文' : '展开原文' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="hasRawLogText(log) && isRawExpanded(log)"
|
||||
class="mt-2 overflow-hidden rounded-md border border-gray-700/80 bg-gray-950 text-gray-100 shadow-sm">
|
||||
<div class="flex items-center justify-between border-b border-gray-800 bg-gray-900/90 px-3 py-1.5 text-xs text-gray-400">
|
||||
<span class="font-mono font-medium text-gray-300">技术原文详情 (Raw Log)</span>
|
||||
<button type="button"
|
||||
@click.stop="copyRawLog(log)"
|
||||
class="inline-flex items-center gap-1 rounded bg-gray-800 px-2 py-0.5 text-xs text-gray-200 hover:bg-gray-700 hover:text-white transition-colors">
|
||||
<span>{{ isCopied(log) ? '已复制 ✓' : '复制原文' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<pre class="max-h-72 overflow-auto p-2.5 text-xs font-mono whitespace-pre-wrap break-words select-all leading-relaxed">{{ formatRawLogText(log) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div v-else-if="viewMode === 'timeline' && timelineLogs.length > 0" class="space-y-1">
|
||||
<div v-for="log in timelineLogs" :key="log.id"
|
||||
:class="['p-2 rounded', getLogColorClass(log)]">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-gray-500 dark:text-gray-300">{{ log.timestamp }}</span>
|
||||
<span :class="['font-bold', getLogLevelClass(log)]">[{{ log.level }}]</span>
|
||||
<span v-if="log.logger" class="px-1.5 py-0.5 rounded bg-white/70 dark:bg-gray-900/40 text-gray-600 dark:text-gray-300">
|
||||
{{ log.logger }}
|
||||
</span>
|
||||
<span v-if="log.requestTag || log.requestId" class="px-1.5 py-0.5 rounded bg-white/70 dark:bg-gray-900/40 text-gray-500 dark:text-gray-400">
|
||||
{{ log.requestTag || log.requestId }}
|
||||
</span>
|
||||
</div>
|
||||
<div :class="['mt-1 break-all whitespace-pre-wrap', getLogTextClass(log)]">
|
||||
<span>{{ getLogText(log) }}</span>
|
||||
<button v-if="hasRawLogText(log)"
|
||||
@click="toggleRawLog(log)"
|
||||
class="ml-2 inline-flex items-center rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-600 hover:bg-white/70 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-900/50">
|
||||
{{ isRawExpanded(log) ? '收起原文' : '展开原文' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="hasRawLogText(log) && isRawExpanded(log)"
|
||||
class="mt-2 overflow-hidden rounded-md border border-gray-700/80 bg-gray-950 text-gray-100 shadow-sm">
|
||||
<div class="flex items-center justify-between border-b border-gray-800 bg-gray-900/90 px-3 py-1.5 text-xs text-gray-400">
|
||||
<span class="font-mono font-medium text-gray-300">技术原文详情 (Raw Log)</span>
|
||||
<button type="button"
|
||||
@click.stop="copyRawLog(log)"
|
||||
class="inline-flex items-center gap-1 rounded bg-gray-800 px-2 py-0.5 text-xs text-gray-200 hover:bg-gray-700 hover:text-white transition-colors">
|
||||
<span>{{ isCopied(log) ? '已复制 ✓' : '复制原文' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<pre class="max-h-72 overflow-auto p-2.5 text-xs font-mono whitespace-pre-wrap break-words select-all leading-relaxed">{{ formatRawLogText(log) }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else
|
||||
class="text-center text-gray-400 dark:text-gray-500 py-8">
|
||||
{{ selectedRequestId === 'ALL' ? '暂无日志' : '该请求暂无符合当前级别的日志' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,503 @@
|
||||
// ==================== 首页首次访问引导 ====================
|
||||
(function () {
|
||||
const STORAGE_KEY = 'uwa_onboarding_v1';
|
||||
|
||||
const MODULE_STEPS = [
|
||||
{
|
||||
key: 'config',
|
||||
code: 'Config',
|
||||
title: '站点配置',
|
||||
summary: '定义一个网站如何被转换为稳定的 API。',
|
||||
detail: '在这里管理反代站点规则、CSS / XPath 选择器、数据提取器、响应拦截检测,以及输入与输出转换工作流。'
|
||||
},
|
||||
{
|
||||
key: 'tabpool',
|
||||
code: 'TabPool',
|
||||
title: '标签页池',
|
||||
summary: '掌握受控 Chrome 的实时工作状态。',
|
||||
detail: '查看多标签页并发池、网页匹配状态、会话隔离方式,以及每个 Tab 当前的线程占用情况。'
|
||||
},
|
||||
{
|
||||
key: 'monitor',
|
||||
code: 'Monitor',
|
||||
title: '请求监控',
|
||||
summary: '观察每一次真实请求如何流经系统。',
|
||||
detail: '抓取并检查 HTTP / WebSocket 请求流量,快速核对请求 Payload、目标站点响应与最终提取结果。'
|
||||
},
|
||||
{
|
||||
key: 'commands',
|
||||
code: 'Commands',
|
||||
title: '命令系统',
|
||||
summary: '把重复的浏览器操作编排成自动化流程。',
|
||||
detail: '配置和触发自动登录、点击交互、页面操作等动作序列,构建可重复执行的 UI 工作流。'
|
||||
},
|
||||
{
|
||||
key: 'logs',
|
||||
code: 'Logs',
|
||||
title: '运行日志',
|
||||
summary: '从底层运行信息中快速定位异常。',
|
||||
detail: '实时查看后端 Python 服务和控制台日志,用于追踪请求链路、脚本执行过程与错误原因。'
|
||||
},
|
||||
{
|
||||
key: 'settings',
|
||||
code: 'Settings',
|
||||
title: '设置',
|
||||
summary: '集中管理服务、安全与本地配置。',
|
||||
detail: '调整监听端口、面板 API Token、浏览器启动参数,并完成配置文件的导入导出、备份与恢复。'
|
||||
}
|
||||
];
|
||||
|
||||
const SOP_STEPS = [
|
||||
{
|
||||
key: 'principle',
|
||||
eyebrow: '核心原理',
|
||||
title: '网页交互,如何变成标准 API?',
|
||||
intro: 'Universal Web API 让受控 Chrome 保持真实网页的登录态和交互能力,再把网页会话桥接为 OpenAI 兼容接口。',
|
||||
note: '第三方客户端只需访问本地 API,无需直接理解每个网站的页面结构。'
|
||||
},
|
||||
{
|
||||
key: 'browser',
|
||||
eyebrow: '步骤 1',
|
||||
title: '在受控浏览器中打开目标网页',
|
||||
intro: '运行系统后,在自动弹出的受控 Chrome 中打开需要反代的 AI 网站,并完成正常登录。',
|
||||
note: '例如打开 gemini.google.com。请始终使用系统启动的受控浏览器,而不是另一个普通浏览器窗口。'
|
||||
},
|
||||
{
|
||||
key: 'interactive',
|
||||
eyebrow: '步骤 2 · 关键事项',
|
||||
title: '确保页面元素显性可交互',
|
||||
intro: '工作流要点击或提取的元素必须真实出现在页面中,不能处于折叠、遮挡或语言不匹配的状态。',
|
||||
note: '以 Gemini 为例,开始请求前请完成下面两项检查。'
|
||||
},
|
||||
{
|
||||
key: 'routing',
|
||||
eyebrow: '步骤 3',
|
||||
title: '在标签页池确认网页并选择路由',
|
||||
intro: '登录成功后,标签页池会显示已捕获网页。根据使用场景选择全局、域名路径或 Query 参数路由。',
|
||||
note: '多站点同时运行时,显式指定域名最容易保持请求边界清晰。'
|
||||
},
|
||||
{
|
||||
key: 'client',
|
||||
eyebrow: '步骤 4',
|
||||
title: '连接前端或第三方客户端',
|
||||
intro: '最后在 NextChat、LobeChat、LangChain 等客户端中填写 Base URL 与 API Key。',
|
||||
note: '未在设置中启用 Token 认证时,API Key 可以留空;若客户端强制要求,也可以填写任意值。'
|
||||
}
|
||||
];
|
||||
|
||||
window.OnboardingGuide = {
|
||||
name: 'OnboardingGuide',
|
||||
emits: ['tour-start', 'tour-end'],
|
||||
data() {
|
||||
return {
|
||||
visible: false,
|
||||
view: 'welcome',
|
||||
phase: 'modules',
|
||||
moduleIndex: 0,
|
||||
sopIndex: 0,
|
||||
targetRect: null,
|
||||
cardStyle: {},
|
||||
initialTimer: null,
|
||||
resizeHandler: null,
|
||||
keyHandler: null
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
moduleSteps() {
|
||||
return MODULE_STEPS;
|
||||
},
|
||||
sopSteps() {
|
||||
return SOP_STEPS;
|
||||
},
|
||||
currentModule() {
|
||||
return this.moduleSteps[this.moduleIndex] || this.moduleSteps[0];
|
||||
},
|
||||
currentSop() {
|
||||
return this.sopSteps[this.sopIndex] || this.sopSteps[0];
|
||||
},
|
||||
totalTourSteps() {
|
||||
return this.moduleSteps.length + this.sopSteps.length;
|
||||
},
|
||||
completedTourSteps() {
|
||||
return this.phase === 'modules'
|
||||
? this.moduleIndex + 1
|
||||
: this.moduleSteps.length + this.sopIndex + 1;
|
||||
},
|
||||
progressPercent() {
|
||||
return Math.round((this.completedTourSteps / this.totalTourSteps) * 100);
|
||||
},
|
||||
spotlightStyle() {
|
||||
if (!this.targetRect) {
|
||||
return { display: 'none' };
|
||||
}
|
||||
return {
|
||||
left: this.targetRect.left + 'px',
|
||||
top: this.targetRect.top + 'px',
|
||||
width: this.targetRect.width + 'px',
|
||||
height: this.targetRect.height + 'px'
|
||||
};
|
||||
},
|
||||
shadeStyles() {
|
||||
if (!this.targetRect) {
|
||||
return [{ inset: '0' }];
|
||||
}
|
||||
const rect = this.targetRect;
|
||||
return [
|
||||
{ left: '0', top: '0', right: '0', height: rect.top + 'px' },
|
||||
{ left: '0', top: rect.top + 'px', width: rect.left + 'px', height: rect.height + 'px' },
|
||||
{ left: (rect.left + rect.width) + 'px', top: rect.top + 'px', right: '0', height: rect.height + 'px' },
|
||||
{ left: '0', top: (rect.top + rect.height) + 'px', right: '0', bottom: '0' }
|
||||
];
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.resizeHandler = () => this.schedulePositionUpdate();
|
||||
this.keyHandler = (event) => this.handleKeydown(event);
|
||||
window.addEventListener('resize', this.resizeHandler, { passive: true });
|
||||
window.addEventListener('scroll', this.resizeHandler, true);
|
||||
document.addEventListener('keydown', this.keyHandler);
|
||||
|
||||
this.initialTimer = window.setTimeout(() => {
|
||||
if (!this.hasSavedDecision()) {
|
||||
this.open(false);
|
||||
}
|
||||
}, 650);
|
||||
},
|
||||
beforeUnmount() {
|
||||
window.clearTimeout(this.initialTimer);
|
||||
window.removeEventListener('resize', this.resizeHandler);
|
||||
window.removeEventListener('scroll', this.resizeHandler, true);
|
||||
document.removeEventListener('keydown', this.keyHandler);
|
||||
},
|
||||
methods: {
|
||||
hasSavedDecision() {
|
||||
try {
|
||||
return !!localStorage.getItem(STORAGE_KEY);
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
saveDecision(status) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify({
|
||||
version: 1,
|
||||
status: status,
|
||||
updatedAt: new Date().toISOString()
|
||||
}));
|
||||
} catch (error) {
|
||||
// Storage is optional; the guide remains usable for this session.
|
||||
}
|
||||
},
|
||||
open(startDirectly) {
|
||||
window.clearTimeout(this.initialTimer);
|
||||
this.visible = true;
|
||||
this.view = startDirectly ? 'tour' : 'welcome';
|
||||
this.phase = 'modules';
|
||||
this.moduleIndex = 0;
|
||||
this.sopIndex = 0;
|
||||
this.targetRect = null;
|
||||
if (startDirectly) {
|
||||
this.$emit('tour-start');
|
||||
this.$nextTick(() => this.updateSpotlight());
|
||||
}
|
||||
this.$nextTick(() => this.focusDialog());
|
||||
},
|
||||
startTour() {
|
||||
this.view = 'tour';
|
||||
this.phase = 'modules';
|
||||
this.moduleIndex = 0;
|
||||
this.$emit('tour-start');
|
||||
this.$nextTick(() => {
|
||||
this.updateSpotlight();
|
||||
this.focusDialog();
|
||||
});
|
||||
},
|
||||
dismissWelcome() {
|
||||
this.saveDecision('dismissed');
|
||||
this.close(false);
|
||||
},
|
||||
skipTour() {
|
||||
this.saveDecision('skipped');
|
||||
this.close(true);
|
||||
},
|
||||
finishTour() {
|
||||
this.saveDecision('completed');
|
||||
this.close(true);
|
||||
},
|
||||
close(wasTour) {
|
||||
this.visible = false;
|
||||
this.targetRect = null;
|
||||
if (wasTour || this.view === 'tour') {
|
||||
this.$emit('tour-end');
|
||||
}
|
||||
},
|
||||
previous() {
|
||||
if (this.phase === 'modules') {
|
||||
if (this.moduleIndex > 0) {
|
||||
this.moduleIndex -= 1;
|
||||
this.$nextTick(() => this.updateSpotlight());
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.sopIndex > 0) {
|
||||
this.sopIndex -= 1;
|
||||
return;
|
||||
}
|
||||
this.phase = 'modules';
|
||||
this.moduleIndex = this.moduleSteps.length - 1;
|
||||
this.$nextTick(() => this.updateSpotlight());
|
||||
},
|
||||
next() {
|
||||
if (this.phase === 'modules') {
|
||||
if (this.moduleIndex < this.moduleSteps.length - 1) {
|
||||
this.moduleIndex += 1;
|
||||
this.$nextTick(() => this.updateSpotlight());
|
||||
return;
|
||||
}
|
||||
this.phase = 'sop';
|
||||
this.sopIndex = 0;
|
||||
this.targetRect = null;
|
||||
this.$nextTick(() => this.focusDialog());
|
||||
return;
|
||||
}
|
||||
if (this.sopIndex < this.sopSteps.length - 1) {
|
||||
this.sopIndex += 1;
|
||||
this.$nextTick(() => this.focusDialog());
|
||||
return;
|
||||
}
|
||||
this.finishTour();
|
||||
},
|
||||
goToSop(index) {
|
||||
this.sopIndex = index;
|
||||
this.$nextTick(() => this.focusDialog());
|
||||
},
|
||||
schedulePositionUpdate() {
|
||||
if (!this.visible || this.view !== 'tour' || this.phase !== 'modules') {
|
||||
return;
|
||||
}
|
||||
window.requestAnimationFrame(() => this.updateSpotlight());
|
||||
},
|
||||
updateSpotlight() {
|
||||
if (!this.visible || this.phase !== 'modules') {
|
||||
return;
|
||||
}
|
||||
const selector = '[data-tour-target="' + this.currentModule.key + '"]';
|
||||
const target = document.querySelector(selector);
|
||||
if (!target) {
|
||||
this.targetRect = null;
|
||||
this.cardStyle = {};
|
||||
return;
|
||||
}
|
||||
|
||||
target.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
||||
window.setTimeout(() => {
|
||||
const bounds = target.getBoundingClientRect();
|
||||
const gap = 7;
|
||||
const rect = {
|
||||
left: Math.max(0, bounds.left - gap),
|
||||
top: Math.max(0, bounds.top - gap),
|
||||
width: Math.min(window.innerWidth, bounds.width + gap * 2),
|
||||
height: Math.min(window.innerHeight, bounds.height + gap * 2)
|
||||
};
|
||||
this.targetRect = rect;
|
||||
this.cardStyle = this.getCardStyle(rect);
|
||||
}, 120);
|
||||
},
|
||||
getCardStyle(rect) {
|
||||
const viewportWidth = window.innerWidth;
|
||||
const viewportHeight = window.innerHeight;
|
||||
if (viewportWidth <= 700) {
|
||||
const estimatedHeight = 268;
|
||||
const placeAtTop = rect.top > viewportHeight * 0.48;
|
||||
return {
|
||||
left: '14px',
|
||||
right: '14px',
|
||||
top: placeAtTop ? '14px' : 'auto',
|
||||
bottom: placeAtTop ? 'auto' : '14px'
|
||||
};
|
||||
}
|
||||
|
||||
const cardWidth = 390;
|
||||
const preferredLeft = rect.left + rect.width + 20;
|
||||
const left = preferredLeft + cardWidth <= viewportWidth - 18
|
||||
? preferredLeft
|
||||
: Math.max(18, rect.left - cardWidth - 20);
|
||||
const top = Math.max(18, Math.min(rect.top - 22, viewportHeight - 340));
|
||||
return { left: left + 'px', top: top + 'px', width: cardWidth + 'px' };
|
||||
},
|
||||
focusDialog() {
|
||||
const dialog = this.$el && this.$el.querySelector('[role="dialog"]');
|
||||
if (dialog && typeof dialog.focus === 'function') {
|
||||
dialog.focus({ preventScroll: true });
|
||||
}
|
||||
},
|
||||
handleKeydown(event) {
|
||||
if (!this.visible) {
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.view === 'welcome' ? this.dismissWelcome() : this.skipTour();
|
||||
return;
|
||||
}
|
||||
if (this.view !== 'tour') {
|
||||
return;
|
||||
}
|
||||
if (event.key === 'ArrowLeft') {
|
||||
event.preventDefault();
|
||||
this.previous();
|
||||
} else if (event.key === 'ArrowRight' || event.key === 'Enter') {
|
||||
event.preventDefault();
|
||||
this.next();
|
||||
}
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div v-if="visible" class="uwa-onboarding-root" @click.stop>
|
||||
<template v-if="view === 'welcome'">
|
||||
<div class="uwa-onboarding-backdrop"></div>
|
||||
<section class="uwa-welcome-dialog" role="dialog" aria-modal="true" aria-labelledby="uwa-welcome-title" tabindex="-1">
|
||||
<button type="button" class="uwa-tour-icon-button" @click="dismissWelcome" title="关闭" aria-label="关闭欢迎引导" v-html="$icons.xMark"></button>
|
||||
<div class="uwa-welcome-mark">
|
||||
<img src="/static/images/logo.svg" alt="">
|
||||
<span>首次使用</span>
|
||||
</div>
|
||||
<p class="uwa-tour-kicker">UNIVERSAL WEB API</p>
|
||||
<h2 id="uwa-welcome-title">欢迎来到控制面板</h2>
|
||||
<p class="uwa-welcome-copy">检测到这是您第一次使用。用大约 3 分钟认识核心模块,并完成第一次网页反代配置。</p>
|
||||
<div class="uwa-welcome-preview" aria-hidden="true">
|
||||
<span><i>1</i>认识控制台</span>
|
||||
<b></b>
|
||||
<span><i>2</i>连接目标网页</span>
|
||||
<b></b>
|
||||
<span><i>3</i>接入客户端</span>
|
||||
</div>
|
||||
<div class="uwa-welcome-actions">
|
||||
<button type="button" class="uwa-tour-button is-secondary" @click="dismissWelcome">暂不需要</button>
|
||||
<button type="button" class="uwa-tour-button is-primary" @click="startTour">
|
||||
<span>开始教程</span>
|
||||
<span v-html="$icons.arrowRight"></span>
|
||||
</button>
|
||||
</div>
|
||||
<p class="uwa-welcome-footnote">之后可随时从侧边栏底部的“新手指南”重新打开</p>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else-if="phase === 'modules'">
|
||||
<div v-for="(style, index) in shadeStyles" :key="index" class="uwa-tour-shade" :style="style"></div>
|
||||
<div class="uwa-tour-spotlight" :style="spotlightStyle" aria-hidden="true"></div>
|
||||
<section class="uwa-module-card" :style="cardStyle" role="dialog" aria-modal="true" :aria-label="currentModule.title + '介绍'" tabindex="-1">
|
||||
<header class="uwa-tour-card-header">
|
||||
<div>
|
||||
<span class="uwa-tour-stage">阶段 1 / 2</span>
|
||||
<span class="uwa-tour-step-count">模块 {{ moduleIndex + 1 }} / {{ moduleSteps.length }}</span>
|
||||
</div>
|
||||
<button type="button" class="uwa-tour-icon-button" @click="skipTour" title="退出教程" aria-label="退出教程" v-html="$icons.xMark"></button>
|
||||
</header>
|
||||
<div class="uwa-tour-progress" aria-hidden="true"><i :style="{ width: progressPercent + '%' }"></i></div>
|
||||
<div class="uwa-module-heading">
|
||||
<span class="uwa-module-number">{{ String(moduleIndex + 1).padStart(2, '0') }}</span>
|
||||
<div>
|
||||
<p>{{ currentModule.code }}</p>
|
||||
<h2>{{ currentModule.title }}</h2>
|
||||
</div>
|
||||
</div>
|
||||
<h3>{{ currentModule.summary }}</h3>
|
||||
<p class="uwa-module-detail">{{ currentModule.detail }}</p>
|
||||
<footer class="uwa-tour-footer">
|
||||
<button type="button" class="uwa-tour-skip" @click="skipTour">跳过教程</button>
|
||||
<div>
|
||||
<button type="button" class="uwa-tour-button is-secondary is-compact" @click="previous" :disabled="moduleIndex === 0">上一步</button>
|
||||
<button type="button" class="uwa-tour-button is-primary is-compact" @click="next">
|
||||
<span>{{ moduleIndex === moduleSteps.length - 1 ? '进入实操' : '下一步' }}</span>
|
||||
<span v-html="$icons.arrowRight"></span>
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="uwa-onboarding-backdrop is-strong"></div>
|
||||
<section class="uwa-sop-dialog" role="dialog" aria-modal="true" aria-labelledby="uwa-sop-title" tabindex="-1">
|
||||
<aside class="uwa-sop-rail">
|
||||
<div class="uwa-sop-rail-heading">
|
||||
<span class="uwa-tour-stage">阶段 2 / 2</span>
|
||||
<strong>反代实操</strong>
|
||||
<small>从网页到 API</small>
|
||||
</div>
|
||||
<nav aria-label="实操教程步骤">
|
||||
<button v-for="(step, index) in sopSteps" :key="step.key" type="button"
|
||||
:class="{ 'is-active': sopIndex === index, 'is-done': sopIndex > index }"
|
||||
@click="goToSop(index)" :aria-current="sopIndex === index ? 'step' : null">
|
||||
<i>{{ sopIndex > index ? '✓' : index }}</i>
|
||||
<span>{{ index === 0 ? '工作原理' : '步骤 ' + index }}</span>
|
||||
</button>
|
||||
</nav>
|
||||
<div class="uwa-sop-rail-progress">
|
||||
<span>整体进度</span><strong>{{ progressPercent }}%</strong>
|
||||
<div><i :style="{ width: progressPercent + '%' }"></i></div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="uwa-sop-content">
|
||||
<header class="uwa-sop-topbar">
|
||||
<span>{{ currentSop.eyebrow }}</span>
|
||||
<button type="button" class="uwa-tour-icon-button" @click="skipTour" title="退出教程" aria-label="退出教程" v-html="$icons.xMark"></button>
|
||||
</header>
|
||||
<div class="uwa-sop-scroll">
|
||||
<p class="uwa-tour-kicker">STEP-BY-STEP SOP</p>
|
||||
<h2 id="uwa-sop-title">{{ currentSop.title }}</h2>
|
||||
<p class="uwa-sop-intro">{{ currentSop.intro }}</p>
|
||||
|
||||
<div v-if="currentSop.key === 'principle'" class="uwa-bridge-flow">
|
||||
<div><span v-html="$icons.globe"></span><strong>真实 Web 界面</strong><small>登录态与页面交互</small></div>
|
||||
<i v-html="$icons.arrowRight"></i>
|
||||
<div><span v-html="$icons.server"></span><strong>受控 Chrome</strong><small>执行操作与提取响应</small></div>
|
||||
<i v-html="$icons.arrowRight"></i>
|
||||
<div class="is-accent"><span v-html="$icons.arrowPathRoundedSquare"></span><strong>OpenAI API</strong><small>统一请求与响应格式</small></div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="currentSop.key === 'browser'" class="uwa-browser-example">
|
||||
<div class="uwa-browser-bar"><i></i><i></i><i></i><span>gemini.google.com</span></div>
|
||||
<div class="uwa-browser-body">
|
||||
<span v-html="$icons.globe"></span>
|
||||
<div><strong>在受控浏览器完成登录</strong><small>保持目标网页打开,系统会自动捕获标签页</small></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="currentSop.key === 'interactive'" class="uwa-check-list">
|
||||
<div><i>1</i><span><strong>展开网页侧边栏</strong><small>避免对话切换等按钮因折叠而不可见</small></span></div>
|
||||
<div><i>2</i><span><strong>页面语言设为“汉语(中文)”</strong><small>防止选择器依赖的文案因语言不同而匹配失败</small></span></div>
|
||||
</div>
|
||||
|
||||
<div v-else-if="currentSop.key === 'routing'" class="uwa-route-list">
|
||||
<article><span>全局路由</span><code>/v1/chat/completions</code><p>根据模型名或当前激活 Tab 自动路由。</p></article>
|
||||
<article class="is-recommended"><span>推荐 · 域名路由</span><code>/site/gemini.google.com/v1/chat/completions</code><p>在路径中固定目标域名,多站点运行互不干扰。</p></article>
|
||||
<article><span>Query 路由</span><code>/v1/chat/completions?domain=gemini.google.com</code><p>通过查询参数指定本次请求的目标站点。</p></article>
|
||||
</div>
|
||||
|
||||
<div v-else-if="currentSop.key === 'client'" class="uwa-client-fields">
|
||||
<label><span>Base URL</span><code>http://127.0.0.1:8199/v1</code></label>
|
||||
<label><span>API Key</span><code>留空或任意值</code><small>启用 Token 认证后,请改为设置中的真实 Token</small></label>
|
||||
</div>
|
||||
|
||||
<div class="uwa-sop-note"><span>提示</span><p>{{ currentSop.note }}</p></div>
|
||||
</div>
|
||||
<footer class="uwa-sop-footer">
|
||||
<button type="button" class="uwa-tour-skip" @click="skipTour">退出教程</button>
|
||||
<div>
|
||||
<button type="button" class="uwa-tour-button is-secondary is-compact" @click="previous">上一步</button>
|
||||
<button type="button" class="uwa-tour-button is-primary is-compact" @click="next">
|
||||
<span>{{ sopIndex === sopSteps.length - 1 ? '完成教程' : '下一步' }}</span>
|
||||
<span v-html="$icons.arrowRight"></span>
|
||||
</button>
|
||||
</div>
|
||||
</footer>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
})();
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,600 @@
|
||||
// ==================== 设置 Tab 组件 (修复版) ====================
|
||||
window.SettingsTab = {
|
||||
name: 'SettingsTab',
|
||||
props: {
|
||||
envConfig: { type: Object, required: true },
|
||||
envSchema: { type: Object, required: true },
|
||||
envCollapsed: { type: Object, required: true },
|
||||
envChanged: { type: Boolean, default: false },
|
||||
savingEnv: { type: Boolean, default: false },
|
||||
|
||||
browserConstants: { type: Object, required: true },
|
||||
browserSchema: { type: Object, required: true },
|
||||
browserCollapsed: { type: Object, required: true },
|
||||
browserChanged: { type: Boolean, default: false },
|
||||
savingBrowser: { type: Boolean, default: false },
|
||||
|
||||
updatePreserveOptions: { type: Array, required: true },
|
||||
updatePreserveSelected: { type: Array, required: true },
|
||||
updatePreserveChanged: { type: Boolean, default: false },
|
||||
savingUpdatePreserve: { type: Boolean, default: false },
|
||||
|
||||
selectorDefinitions: { type: Array, required: true },
|
||||
definitionsChanged: { type: Boolean, default: false },
|
||||
savingDefinitions: { type: Boolean, default: false },
|
||||
|
||||
releases: { type: Array, required: true },
|
||||
releasesLoading: { type: Boolean, default: false },
|
||||
releasesError: { type: String, default: '' },
|
||||
releasesCurrentVersion: { type: String, default: '' },
|
||||
switchingTag: { type: String, default: null },
|
||||
updateCheckRefreshing: { type: Boolean, default: false }
|
||||
},
|
||||
emits: [
|
||||
'save-env', 'reset-env', 'toggle-env-group',
|
||||
'save-browser', 'reset-browser', 'toggle-browser-group',
|
||||
'save-update-preserve', 'reset-update-preserve', 'toggle-update-preserve',
|
||||
'save-definitions', 'reset-definitions',
|
||||
'add-definition', 'edit-definition', 'remove-definition',
|
||||
'toggle-definition', 'move-definition',
|
||||
'load-releases', 'switch-to-version', 'show-changelog',
|
||||
'refresh-update-check'
|
||||
],
|
||||
data() {
|
||||
return {
|
||||
selectorDefsCollapsed: true,
|
||||
updatePreserveCollapsed: true,
|
||||
versionCollapsed: false,
|
||||
releasePage: 1,
|
||||
releasePageSize: 5
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
updatePreserveGroups() {
|
||||
const groups = {}
|
||||
for (const item of this.updatePreserveOptions || []) {
|
||||
const key = item.category || '其他'
|
||||
if (!groups[key]) groups[key] = []
|
||||
groups[key].push(item)
|
||||
}
|
||||
return groups
|
||||
},
|
||||
releaseTotalPages() {
|
||||
return Math.max(1, Math.ceil(this.releases.length / this.releasePageSize))
|
||||
},
|
||||
paginatedReleases() {
|
||||
const start = (this.releasePage - 1) * this.releasePageSize
|
||||
return this.releases.slice(start, start + this.releasePageSize)
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
releases() {
|
||||
if (this.releasePage > this.releaseTotalPages) {
|
||||
this.releasePage = this.releaseTotalPages
|
||||
}
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
getEnvApplyScope(field, group) {
|
||||
return field.apply || group.apply || 'service'
|
||||
},
|
||||
getEnvApplyLabel(field, group) {
|
||||
const scope = this.getEnvApplyScope(field, group)
|
||||
if (scope === 'launcher') return '需重启 start.bat'
|
||||
return '保存后服务重启生效'
|
||||
},
|
||||
getEnvApplyClass(field, group) {
|
||||
const scope = this.getEnvApplyScope(field, group)
|
||||
if (scope === 'launcher') {
|
||||
return 'bg-amber-50 text-amber-700 border border-amber-200 dark:bg-amber-900/20 dark:text-amber-300 dark:border-amber-800'
|
||||
}
|
||||
return 'bg-emerald-50 text-emerald-700 border border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-800'
|
||||
},
|
||||
formatReleaseDate(isoStr) {
|
||||
if (!isoStr) return '—';
|
||||
try {
|
||||
var d = new Date(isoStr);
|
||||
var pad = function(n) { return String(n).padStart(2, '0'); };
|
||||
return d.getFullYear() + '/' + pad(d.getMonth()+1) + '/' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
|
||||
} catch (e) {
|
||||
return isoStr;
|
||||
}
|
||||
},
|
||||
goToReleasePage(page) {
|
||||
this.releasePage = Math.min(this.releaseTotalPages, Math.max(1, Number(page) || 1))
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="settings-workspace h-full overflow-auto p-4 md:p-6 bg-gray-50 dark:bg-gray-900">
|
||||
<div class="max-w-7xl mx-auto space-y-6">
|
||||
|
||||
<!-- ========== AI 元素识别 - 放在最上面 ========== -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700">
|
||||
<div class="p-4 border-b border-gray-100 dark:border-gray-700 flex justify-between items-center cursor-pointer"
|
||||
@click="selectorDefsCollapsed = !selectorDefsCollapsed">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<span class="text-xl">🎯</span> AI 元素识别
|
||||
</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">配置 AI 分析页面时需要查找的目标元素</p>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<span class="text-xs px-2 py-1 bg-gray-100 dark:bg-gray-700 rounded-full text-gray-600 dark:text-gray-300">{{ selectorDefinitions.length }} 个定义</span>
|
||||
<div class="h-6 w-px bg-gray-200 dark:bg-gray-600 mx-2"></div>
|
||||
<button @click.stop="$emit('reset-definitions')" title="重置"
|
||||
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
|
||||
<span v-html="$icons.arrowPath"></span>
|
||||
</button>
|
||||
<button @click.stop="$emit('save-definitions')"
|
||||
:disabled="savingDefinitions || !definitionsChanged"
|
||||
:class="['px-3 py-1.5 text-sm font-medium text-white rounded-lg transition-colors flex items-center gap-1 shadow-sm',
|
||||
savingDefinitions || !definitionsChanged
|
||||
? 'bg-blue-400 cursor-not-allowed opacity-60'
|
||||
: 'bg-blue-600 hover:bg-blue-700']">
|
||||
<span v-if="!savingDefinitions" v-html="$icons.arrowDownTray" class="w-4 h-4"></span>
|
||||
{{ savingDefinitions ? '...' : '保存' }}
|
||||
</button>
|
||||
<button class="p-1.5 ml-2 text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
|
||||
v-html="selectorDefsCollapsed ? $icons.chevronDown : $icons.chevronUp">
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!selectorDefsCollapsed" class="p-0">
|
||||
<!-- 表头 -->
|
||||
<div class="grid grid-cols-12 gap-4 px-6 py-3 bg-gray-50 dark:bg-gray-900/50 text-xs font-semibold text-gray-600 dark:text-gray-300 border-b border-gray-200 dark:border-gray-700">
|
||||
<div class="col-span-1 text-center">排序</div>
|
||||
<div class="col-span-3 md:col-span-2">关键词 (Key)</div>
|
||||
<div class="col-span-6 md:col-span-7">描述 (Description)</div>
|
||||
<div class="col-span-1 text-center">启用</div>
|
||||
<div class="col-span-1 text-center">操作</div>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="divide-y divide-gray-100 dark:divide-gray-700">
|
||||
<div v-for="(def, index) in selectorDefinitions" :key="def.key"
|
||||
class="grid grid-cols-12 gap-4 px-6 py-3 items-center hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
|
||||
|
||||
<!-- 排序按钮 - 优化日夜模式显示 -->
|
||||
<div class="col-span-1 flex flex-col items-center gap-0.5">
|
||||
<button @click.stop="$emit('move-definition', index, -1)"
|
||||
:disabled="index === 0"
|
||||
:class="['p-1 rounded-md transition-all duration-150',
|
||||
index === 0
|
||||
? 'text-gray-300 dark:text-gray-600 cursor-not-allowed'
|
||||
: 'text-gray-600 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40 active:scale-95']"
|
||||
title="上移">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M4.5 15.75l7.5-7.5 7.5 7.5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button @click.stop="$emit('move-definition', index, 1)"
|
||||
:disabled="index === selectorDefinitions.length - 1"
|
||||
:class="['p-1 rounded-md transition-all duration-150',
|
||||
index === selectorDefinitions.length - 1
|
||||
? 'text-gray-300 dark:text-gray-600 cursor-not-allowed'
|
||||
: 'text-gray-600 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40 active:scale-95']"
|
||||
title="下移">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 8.25l-7.5 7.5-7.5-7.5"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Key -->
|
||||
<div class="col-span-3 md:col-span-2 flex items-center gap-2 flex-wrap">
|
||||
<code class="px-2 py-1 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded text-xs font-mono text-blue-700 dark:text-blue-300">
|
||||
{{ def.key }}
|
||||
</code>
|
||||
<span v-if="def.required" class="text-[10px] text-red-600 dark:text-red-400 border border-red-300 dark:border-red-700 px-1.5 py-0.5 rounded bg-red-50 dark:bg-red-900/30 font-medium">必需</span>
|
||||
</div>
|
||||
|
||||
<!-- Description -->
|
||||
<div class="col-span-6 md:col-span-7 text-sm text-gray-700 dark:text-gray-200 truncate" :title="def.description">
|
||||
{{ def.description }}
|
||||
</div>
|
||||
|
||||
<!-- 启用开关 -->
|
||||
<div class="col-span-1 flex justify-center">
|
||||
<label class="toggle-label scale-90">
|
||||
<input type="checkbox" :checked="def.enabled"
|
||||
@change="$emit('toggle-definition', index)"
|
||||
:disabled="def.required" class="sr-only peer">
|
||||
<div class="toggle-bg" :class="{'opacity-50 cursor-not-allowed': def.required}"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<!-- 操作按钮 - 优化删除按钮日夜模式显示 -->
|
||||
<div class="col-span-1 flex justify-center gap-1">
|
||||
<button @click.stop="$emit('edit-definition', index)"
|
||||
class="p-1.5 rounded-md transition-all duration-150 text-gray-600 dark:text-gray-300 hover:text-blue-600 dark:hover:text-blue-400 hover:bg-blue-100 dark:hover:bg-blue-900/40 active:scale-95"
|
||||
title="编辑">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button @click.stop="$emit('remove-definition', index)"
|
||||
:disabled="def.required"
|
||||
:class="['p-1.5 rounded-md transition-all duration-150',
|
||||
def.required
|
||||
? 'text-gray-300 dark:text-gray-600 cursor-not-allowed'
|
||||
: 'text-gray-600 dark:text-gray-300 hover:text-red-600 dark:hover:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/40 active:scale-95']"
|
||||
title="删除">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 添加按钮 -->
|
||||
<div class="p-4 bg-gray-50 dark:bg-gray-800/80 border-t border-gray-200 dark:border-gray-700 text-center">
|
||||
<button @click="$emit('add-definition')"
|
||||
class="text-sm text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 font-medium py-2 px-5 border-2 border-dashed border-blue-300 dark:border-blue-600 rounded-lg hover:bg-blue-50 dark:hover:bg-blue-900/30 transition-all duration-150 inline-flex items-center gap-2 active:scale-95">
|
||||
<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"/>
|
||||
</svg>
|
||||
添加新定义
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- ========== 版本管理 ========== -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700">
|
||||
<div class="p-4 border-b border-gray-100 dark:border-gray-700 flex justify-between items-center cursor-pointer"
|
||||
@click="versionCollapsed = !versionCollapsed">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<span class="text-xl">🔄</span> 版本管理
|
||||
</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">手动选择 GitHub 发布的版本进行切换/更新</p>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<span class="text-xs px-2 py-1 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-700 rounded-full text-blue-700 dark:text-blue-300 font-mono font-medium">当前版本: v{{ releasesCurrentVersion || '加载中...' }}</span>
|
||||
<div class="h-6 w-px bg-gray-200 dark:bg-gray-600 mx-2"></div>
|
||||
<!-- 补齐入口:POST /api/update/check 会真正访问 GitHub 重查;GET 只读启动缓存 -->
|
||||
<button @click.stop="$emit('refresh-update-check')" title="立即联网检查最新版本"
|
||||
:disabled="updateCheckRefreshing"
|
||||
:class="['px-2.5 py-1.5 text-xs rounded-lg border transition-colors',
|
||||
updateCheckRefreshing
|
||||
? 'border-gray-200 dark:border-gray-600 text-gray-400 cursor-not-allowed'
|
||||
: 'border-blue-200 dark:border-blue-700 text-blue-700 dark:text-blue-300 hover:bg-blue-50 dark:hover:bg-blue-900/30']">
|
||||
{{ updateCheckRefreshing ? '检查中...' : '立即检查' }}
|
||||
</button>
|
||||
<button @click.stop="$emit('load-releases')" title="刷新版本列表"
|
||||
:disabled="releasesLoading"
|
||||
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors flex items-center justify-center">
|
||||
<svg :class="['w-4 h-4', releasesLoading ? 'animate-spin' : '']" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"/>
|
||||
</svg>
|
||||
</button>
|
||||
<button class="p-1.5 ml-2 text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
|
||||
v-html="versionCollapsed ? $icons.chevronDown : $icons.chevronUp">
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!versionCollapsed" class="p-0">
|
||||
<div v-if="releasesLoading && !releases.length" class="p-8 text-center text-gray-500 dark:text-gray-400">
|
||||
<div class="animate-spin inline-block w-6 h-6 border-[3px] border-current border-t-transparent text-blue-600 rounded-full mb-2" role="status" aria-label="loading"></div>
|
||||
<div>正在加载版本列表...</div>
|
||||
</div>
|
||||
<div v-else-if="releasesError" class="p-8 text-center text-red-500">
|
||||
{{ releasesError }}
|
||||
<button @click="$emit('load-releases')" class="mt-2 block mx-auto px-3 py-1 bg-red-100 hover:bg-red-200 text-red-700 rounded text-xs">重试</button>
|
||||
</div>
|
||||
<div v-else-if="!releases.length" class="p-8 text-center text-gray-500 dark:text-gray-400">
|
||||
暂无版本发布记录
|
||||
</div>
|
||||
<div v-else>
|
||||
<!-- 表头 -->
|
||||
<div class="grid grid-cols-12 gap-4 px-6 py-3 bg-gray-50 dark:bg-gray-900/50 text-xs font-semibold text-gray-600 dark:text-gray-300 border-b border-gray-200 dark:border-gray-700">
|
||||
<div class="col-span-3">版本 (Tag)</div>
|
||||
<div class="col-span-4">发布时间</div>
|
||||
<div class="col-span-2 text-center">更新说明</div>
|
||||
<div class="col-span-3 text-center">操作</div>
|
||||
</div>
|
||||
|
||||
<!-- 列表 -->
|
||||
<div class="divide-y divide-gray-100 dark:divide-gray-700">
|
||||
<div v-for="rel in paginatedReleases" :key="rel.tag"
|
||||
class="grid grid-cols-12 gap-4 px-6 py-3.5 items-center hover:bg-gray-50 dark:hover:bg-gray-700/30 transition-colors">
|
||||
<div class="col-span-3 flex items-center gap-2">
|
||||
<span class="font-mono font-bold text-gray-900 dark:text-white">{{ rel.tag }}</span>
|
||||
<span v-if="rel.tag === 'v' + releasesCurrentVersion || rel.tag === releasesCurrentVersion || rel.is_current" class="px-2 py-0.5 text-[10px] text-green-700 bg-green-50 border border-green-200 rounded dark:bg-green-900/30 dark:text-green-300 dark:border-green-800">当前</span>
|
||||
</div>
|
||||
<div class="col-span-4 text-sm text-gray-500 dark:text-gray-400">
|
||||
{{ formatReleaseDate(rel.published_at) }}
|
||||
</div>
|
||||
<div class="col-span-2 text-center">
|
||||
<button @click="$emit('show-changelog', rel.tag, rel.body)"
|
||||
class="text-xs text-blue-600 dark:text-blue-400 hover:underline">
|
||||
查看说明
|
||||
</button>
|
||||
</div>
|
||||
<div class="col-span-3 text-center">
|
||||
<span v-if="rel.tag === 'v' + releasesCurrentVersion || rel.tag === releasesCurrentVersion || rel.is_current"
|
||||
class="inline-block px-3 py-1 text-xs text-gray-400 bg-gray-100 dark:bg-gray-800 dark:text-gray-600 rounded-lg font-medium">
|
||||
已是当前版本
|
||||
</span>
|
||||
<button v-else-if="switchingTag === rel.tag" disabled
|
||||
class="px-3 py-1 text-xs text-white bg-blue-400 rounded-lg cursor-wait animate-pulse">
|
||||
切换中...
|
||||
</button>
|
||||
<button v-else @click="$emit('switch-to-version', rel.tag)"
|
||||
:disabled="!!switchingTag"
|
||||
:class="['px-3 py-1 text-xs font-medium rounded-lg transition-colors',
|
||||
switchingTag ? 'bg-gray-100 text-gray-400 dark:bg-gray-800 dark:text-gray-600 cursor-not-allowed' : 'bg-blue-600 text-white hover:bg-blue-700 shadow-sm']">
|
||||
切换到此版本
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="releaseTotalPages > 1"
|
||||
class="flex flex-wrap items-center justify-between gap-3 border-t border-gray-200 px-6 py-3 text-xs text-gray-500 dark:border-gray-700 dark:text-gray-400">
|
||||
<span>共 {{ releases.length }} 条 · 第 {{ releasePage }} / {{ releaseTotalPages }} 页</span>
|
||||
<div class="flex items-center gap-1" aria-label="版本列表分页">
|
||||
<button type="button"
|
||||
@click="goToReleasePage(releasePage - 1)"
|
||||
:disabled="releasePage <= 1"
|
||||
title="上一页" aria-label="上一页"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-lg border border-gray-200 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<span class="h-4 w-4 rotate-180" v-html="$icons.arrowRight"></span>
|
||||
</button>
|
||||
<button v-for="page in releaseTotalPages" :key="page"
|
||||
type="button"
|
||||
@click="goToReleasePage(page)"
|
||||
:aria-current="page === releasePage ? 'page' : null"
|
||||
:class="['h-8 min-w-8 rounded-lg border px-2 text-xs font-medium transition-colors',
|
||||
page === releasePage
|
||||
? 'border-blue-600 bg-blue-600 text-white'
|
||||
: 'border-gray-200 text-gray-600 hover:bg-gray-100 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700']">
|
||||
{{ page }}
|
||||
</button>
|
||||
<button type="button"
|
||||
@click="goToReleasePage(releasePage + 1)"
|
||||
:disabled="releasePage >= releaseTotalPages"
|
||||
title="下一页" aria-label="下一页"
|
||||
class="flex h-8 w-8 items-center justify-center rounded-lg border border-gray-200 text-gray-600 transition-colors hover:bg-gray-100 disabled:cursor-not-allowed disabled:opacity-40 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700">
|
||||
<span class="h-4 w-4" v-html="$icons.arrowRight"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ========== 环境配置 和 浏览器常量 ========== -->
|
||||
<div class="grid grid-cols-1 xl:grid-cols-2 gap-6">
|
||||
|
||||
<!-- 环境配置 -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 flex flex-col">
|
||||
<div class="p-4 border-b border-gray-100 dark:border-gray-700 flex justify-between items-start">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<span class="text-xl" v-html="$icons.folderOpen"></span> 环境配置
|
||||
</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">每个字段都会标明是服务重启生效,还是需要重新运行 start.bat</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button @click="$emit('reset-env')" title="重置"
|
||||
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
|
||||
<span v-html="$icons.arrowPath"></span>
|
||||
</button>
|
||||
<button @click="$emit('save-env')"
|
||||
:disabled="savingEnv || !envChanged"
|
||||
:class="['px-3 py-1.5 text-sm font-medium text-white rounded-lg transition-colors flex items-center gap-1 shadow-sm',
|
||||
savingEnv || !envChanged
|
||||
? 'bg-blue-400 cursor-not-allowed opacity-60'
|
||||
: 'bg-blue-600 hover:bg-blue-700']">
|
||||
<span v-if="!savingEnv" v-html="$icons.arrowDownTray" class="w-4 h-4"></span>
|
||||
{{ savingEnv ? '...' : '保存' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-2 space-y-2">
|
||||
<div v-for="(group, groupKey) in envSchema" :key="groupKey" class="rounded-lg border border-gray-100 dark:border-gray-700/50 overflow-hidden">
|
||||
<div class="px-4 py-2 bg-gray-50/50 dark:bg-gray-800/50 flex justify-between items-center cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="$emit('toggle-env-group', groupKey)">
|
||||
<div class="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-200">
|
||||
<span class="opacity-70">{{ group.icon }}</span>
|
||||
<span>{{ group.label }}</span>
|
||||
</div>
|
||||
<span v-html="envCollapsed[groupKey] ? $icons.chevronDown : $icons.chevronUp" class="text-gray-400 w-4 h-4"></span>
|
||||
</div>
|
||||
|
||||
<div v-show="!envCollapsed[groupKey]" class="px-4 py-4 space-y-5 bg-white dark:bg-gray-800">
|
||||
<div v-for="(field, fieldKey) in group.items" :key="fieldKey" class="grid grid-cols-1 gap-1">
|
||||
<div class="flex justify-between items-start gap-3">
|
||||
<div class="min-w-0 space-y-1">
|
||||
<label class="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{{ field.label }}
|
||||
</label>
|
||||
<span :class="['inline-flex rounded-full px-2 py-0.5 text-[10px] font-medium', getEnvApplyClass(field, group)]">
|
||||
{{ getEnvApplyLabel(field, group) }}
|
||||
</span>
|
||||
</div>
|
||||
<span v-if="field.unit" class="text-xs text-gray-400 dark:text-gray-500 font-mono">
|
||||
{{ field.unit }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div v-if="field.type === 'switch'" class="flex items-center h-9">
|
||||
<label class="toggle-label">
|
||||
<input type="checkbox" v-model="envConfig[fieldKey]" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
<select v-else-if="field.type === 'select'" v-model="envConfig[fieldKey]"
|
||||
class="settings-input w-full">
|
||||
<option v-for="opt in field.options"
|
||||
:key="typeof opt === 'object' ? opt.value : opt"
|
||||
:value="typeof opt === 'object' ? opt.value : opt">
|
||||
{{ typeof opt === 'object' ? opt.label : opt }}
|
||||
</option>
|
||||
</select>
|
||||
<input v-else-if="field.type === 'number'" type="number"
|
||||
v-model.number="envConfig[fieldKey]"
|
||||
:min="field.min" :max="field.max" :step="field.step || 1"
|
||||
class="settings-input w-full">
|
||||
<input v-else :type="field.type === 'password' ? 'password' : 'text'"
|
||||
v-model="envConfig[fieldKey]"
|
||||
:placeholder="field.default"
|
||||
class="settings-input w-full">
|
||||
</div>
|
||||
|
||||
<div v-if="field.desc" class="text-xs text-gray-400 dark:text-gray-500 flex items-start gap-1 mt-0.5">
|
||||
<span class="mt-0.5 opacity-70">ℹ️</span>
|
||||
<span>{{ field.desc }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 浏览器常量 -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 flex flex-col">
|
||||
<div class="p-4 border-b border-gray-100 dark:border-gray-700 flex justify-between items-start">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<span class="text-xl">🌐</span> 浏览器常量
|
||||
</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">即时生效</p>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<button @click="$emit('reset-browser')" title="重置"
|
||||
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
|
||||
<span v-html="$icons.arrowPath"></span>
|
||||
</button>
|
||||
<button @click="$emit('save-browser')"
|
||||
:disabled="savingBrowser || !browserChanged"
|
||||
:class="['px-3 py-1.5 text-sm font-medium text-white rounded-lg transition-colors flex items-center gap-1 shadow-sm',
|
||||
savingBrowser || !browserChanged
|
||||
? 'bg-blue-400 cursor-not-allowed opacity-60'
|
||||
: 'bg-blue-600 hover:bg-blue-700']">
|
||||
<span v-if="!savingBrowser" v-html="$icons.arrowDownTray" class="w-4 h-4"></span>
|
||||
{{ savingBrowser ? '...' : '保存' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="p-2 space-y-2">
|
||||
<div v-for="(group, groupKey) in browserSchema" :key="groupKey" class="rounded-lg border border-gray-100 dark:border-gray-700/50 overflow-hidden">
|
||||
<div class="px-4 py-2 bg-gray-50/50 dark:bg-gray-800/50 flex justify-between items-center cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="$emit('toggle-browser-group', groupKey)">
|
||||
<div class="flex items-center gap-2 text-sm font-medium text-gray-700 dark:text-gray-200">
|
||||
<span class="opacity-70">{{ group.icon }}</span>
|
||||
<span>{{ group.label }}</span>
|
||||
</div>
|
||||
<span v-html="browserCollapsed[groupKey] ? $icons.chevronDown : $icons.chevronUp" class="text-gray-400 w-4 h-4"></span>
|
||||
</div>
|
||||
|
||||
<div v-show="!browserCollapsed[groupKey]" class="px-4 py-4 space-y-5 bg-white dark:bg-gray-800">
|
||||
<div v-for="(field, fieldKey) in group.items" :key="fieldKey" class="grid grid-cols-1 gap-1">
|
||||
<div class="flex justify-between">
|
||||
<label class="text-sm font-medium text-gray-700 dark:text-gray-300">
|
||||
{{ field.label }}
|
||||
</label>
|
||||
<span v-if="field.unit" class="text-xs text-gray-400 dark:text-gray-500 font-mono">
|
||||
{{ field.unit }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div v-if="field.type === 'switch'" class="flex items-center h-9">
|
||||
<label class="toggle-label">
|
||||
<input type="checkbox" v-model="browserConstants[fieldKey]" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
<select v-else-if="field.type === 'select'" v-model="browserConstants[fieldKey]"
|
||||
class="settings-input w-full">
|
||||
<option v-for="opt in field.options" :key="opt" :value="opt">{{ opt }}</option>
|
||||
</select>
|
||||
<input v-else-if="field.type === 'number'" type="number"
|
||||
v-model.number="browserConstants[fieldKey]"
|
||||
:min="field.min" :max="field.max" :step="field.step || 1"
|
||||
class="settings-input w-full">
|
||||
<input v-else :type="field.type === 'password' ? 'password' : 'text'"
|
||||
v-model="browserConstants[fieldKey]"
|
||||
:placeholder="field.default"
|
||||
class="settings-input w-full">
|
||||
</div>
|
||||
|
||||
<div v-if="field.desc" class="text-xs text-gray-400 dark:text-gray-500 flex items-start gap-1 mt-0.5">
|
||||
<span class="mt-0.5 opacity-70">ℹ️</span>
|
||||
<span>{{ field.desc }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700">
|
||||
<div class="p-4 border-b border-gray-100 dark:border-gray-700 flex justify-between items-center cursor-pointer"
|
||||
@click="updatePreserveCollapsed = !updatePreserveCollapsed">
|
||||
<div>
|
||||
<h3 class="text-lg font-bold text-gray-900 dark:text-white flex items-center gap-2">
|
||||
<span class="text-xl">🛠️</span> 更新白名单
|
||||
</h3>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">勾选后,下次自动更新会原样保留对应文件或目录</p>
|
||||
</div>
|
||||
<div class="flex gap-2 items-center">
|
||||
<button @click.stop="$emit('reset-update-preserve')" title="重置"
|
||||
class="p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors">
|
||||
<span v-html="$icons.arrowPath"></span>
|
||||
</button>
|
||||
<button @click.stop="$emit('save-update-preserve')"
|
||||
:disabled="savingUpdatePreserve || !updatePreserveChanged"
|
||||
:class="['px-3 py-1.5 text-sm font-medium text-white rounded-lg transition-colors flex items-center gap-1 shadow-sm',
|
||||
savingUpdatePreserve || !updatePreserveChanged
|
||||
? 'bg-blue-400 cursor-not-allowed opacity-60'
|
||||
: 'bg-blue-600 hover:bg-blue-700']">
|
||||
<span v-if="!savingUpdatePreserve" v-html="$icons.arrowDownTray" class="w-4 h-4"></span>
|
||||
{{ savingUpdatePreserve ? '...' : '保存' }}
|
||||
</button>
|
||||
<button class="p-1.5 ml-2 text-gray-500 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded transition-colors"
|
||||
v-html="updatePreserveCollapsed ? $icons.chevronDown : $icons.chevronUp">
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!updatePreserveCollapsed" class="p-4 space-y-4">
|
||||
<div class="rounded-lg bg-amber-50 px-3 py-2 text-xs text-amber-700 dark:bg-amber-900/20 dark:text-amber-300">
|
||||
这里控制的是“更新时是否保留不变”,不是运行时是否启用。目录项会保留整个目录;未勾选的项目会在更新时按新版本内容覆盖或合并。
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div v-for="(items, category) in updatePreserveGroups" :key="category" class="space-y-2">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.14em] text-gray-400 dark:text-gray-500">{{ category }}</div>
|
||||
<div class="grid gap-2 md:grid-cols-2">
|
||||
<label v-for="item in items" :key="item.id"
|
||||
class="flex items-start gap-3 rounded-xl border border-gray-200 bg-gray-50/70 px-3 py-3 text-sm text-gray-700 transition hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-900/40 dark:text-gray-200 dark:hover:bg-gray-900/70">
|
||||
<input type="checkbox"
|
||||
:checked="updatePreserveSelected.includes(item.pattern)"
|
||||
@change="$emit('toggle-update-preserve', item.pattern)"
|
||||
class="mt-0.5 h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
|
||||
<span class="min-w-0">
|
||||
<span class="block font-medium">{{ item.label }}</span>
|
||||
<span class="mt-0.5 block text-xs text-gray-500 dark:text-gray-400">{{ item.description }}</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,226 @@
|
||||
// ==================== 侧边栏组件 ====================
|
||||
window.getDashboardAuthToken = window.getDashboardAuthToken || function () {
|
||||
try {
|
||||
return String(
|
||||
localStorage.getItem('dashboard_token')
|
||||
|| localStorage.getItem('api_token')
|
||||
|| ''
|
||||
).trim();
|
||||
} catch (e) {
|
||||
return '';
|
||||
}
|
||||
};
|
||||
|
||||
window.SidebarComponent = {
|
||||
name: 'SidebarComponent',
|
||||
props: {
|
||||
sites: { type: Object, required: true },
|
||||
currentDomain: { type: String, default: '' },
|
||||
browserStatus: { type: Object, required: true },
|
||||
authEnabled: { type: Boolean, default: false },
|
||||
hasToken: { type: Boolean, default: false },
|
||||
darkMode: { type: Boolean, default: false },
|
||||
activeTab: { type: String, default: 'home' },
|
||||
updateAvailable: { type: Boolean, default: false },
|
||||
systemStats: { type: Object, default: () => ({ memory_mb: 0, disk_status: '未知', total_requests: 0 }) }
|
||||
},
|
||||
emits: [
|
||||
'select-site',
|
||||
'add-site',
|
||||
'delete-site',
|
||||
'export-site',
|
||||
'toggle-dark',
|
||||
'refresh-status',
|
||||
'trigger-import',
|
||||
'export-all',
|
||||
'show-token-dialog',
|
||||
'open-guide',
|
||||
'primary-action',
|
||||
'collapse-change',
|
||||
'change-tab' // ✨ 新增
|
||||
],
|
||||
data() {
|
||||
return {
|
||||
navCollapsed: false,
|
||||
mobileOpen: false,
|
||||
tourNavigationSnapshot: null
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
primaryActionLabel() {
|
||||
return this.activeTab === 'commands' ? '新建命令' : '新增站点';
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
try {
|
||||
this.navCollapsed = localStorage.getItem('dashboard_nav_collapsed') === '1';
|
||||
} catch (e) {
|
||||
this.navCollapsed = false;
|
||||
}
|
||||
this.$emit('collapse-change', this.navCollapsed);
|
||||
},
|
||||
methods: {
|
||||
toggleNavCollapsed() {
|
||||
this.navCollapsed = !this.navCollapsed;
|
||||
this.$emit('collapse-change', this.navCollapsed);
|
||||
try {
|
||||
localStorage.setItem('dashboard_nav_collapsed', this.navCollapsed ? '1' : '0');
|
||||
} catch (e) {
|
||||
// Layout persistence is optional.
|
||||
}
|
||||
},
|
||||
openMobileNav() {
|
||||
this.mobileOpen = true;
|
||||
},
|
||||
closeMobileNav() {
|
||||
this.mobileOpen = false;
|
||||
},
|
||||
beginTourNavigation() {
|
||||
if (!this.tourNavigationSnapshot) {
|
||||
this.tourNavigationSnapshot = {
|
||||
navCollapsed: this.navCollapsed,
|
||||
mobileOpen: this.mobileOpen
|
||||
};
|
||||
}
|
||||
this.navCollapsed = false;
|
||||
this.mobileOpen = window.innerWidth <= 900;
|
||||
this.$emit('collapse-change', false);
|
||||
},
|
||||
endTourNavigation() {
|
||||
const snapshot = this.tourNavigationSnapshot;
|
||||
this.mobileOpen = false;
|
||||
if (snapshot) {
|
||||
this.navCollapsed = snapshot.navCollapsed;
|
||||
this.$emit('collapse-change', this.navCollapsed);
|
||||
}
|
||||
this.tourNavigationSnapshot = null;
|
||||
},
|
||||
selectTab(tab) {
|
||||
this.mobileOpen = false;
|
||||
this.$emit('change-tab', tab);
|
||||
},
|
||||
selectSite(domain) {
|
||||
this.mobileOpen = false;
|
||||
this.$emit('select-site', domain);
|
||||
},
|
||||
runPrimaryAction() {
|
||||
this.mobileOpen = false;
|
||||
this.$emit('primary-action', this.activeTab);
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div :class="['app-sidebar-layer', { 'is-mobile-open': mobileOpen }]">
|
||||
<button type="button" class="app-sidebar-scrim" @click="closeMobileNav" aria-label="关闭导航"></button>
|
||||
<aside :class="['app-sidebar', { 'is-collapsed': navCollapsed }]" aria-label="主导航">
|
||||
<div class="app-brand">
|
||||
<img src="/static/images/logo.svg" alt="Universal Web API logo" class="app-brand-logo">
|
||||
<div class="app-brand-copy">
|
||||
<strong>Universal API</strong>
|
||||
<span>Local AI bridge</span>
|
||||
</div>
|
||||
<button type="button" class="app-nav-collapse" @click="toggleNavCollapsed"
|
||||
:title="navCollapsed ? '展开导航' : '折叠导航'"
|
||||
:aria-label="navCollapsed ? '展开导航' : '折叠导航'">
|
||||
<span v-if="navCollapsed" class="app-collapse-lines" aria-hidden="true"></span>
|
||||
<span v-else v-html="$icons.xMark" aria-hidden="true"></span>
|
||||
</button>
|
||||
<button type="button" class="app-nav-mobile-close" @click="closeMobileNav" title="关闭导航" aria-label="关闭导航" v-html="$icons.xMark"></button>
|
||||
<button type="button" class="app-collapsed-status" @click="$emit('refresh-status')" title="刷新状态" aria-label="刷新服务状态">
|
||||
<i :class="['app-service-dot', { 'is-online': browserStatus.connected }]"></i>
|
||||
<span>{{ browserStatus.connected ? '在线' : '离线' }}</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav class="app-primary-nav" aria-label="功能区">
|
||||
<button type="button" @click="selectTab('home')"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'home' }]"
|
||||
title="首页" aria-label="首页"
|
||||
:aria-current="activeTab === 'home' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.home"></span>
|
||||
<span>首页</span>
|
||||
</button>
|
||||
<button type="button" @click="selectTab('config')"
|
||||
data-tour-target="config"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'config' }]"
|
||||
title="站点配置" aria-label="站点配置"
|
||||
:aria-current="activeTab === 'config' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.clipboardList"></span>
|
||||
<span>站点配置</span>
|
||||
<span class="app-nav-count">{{ Object.keys(sites).length }}</span>
|
||||
</button>
|
||||
<button type="button" @click="selectTab('tabpool')"
|
||||
data-tour-target="tabpool"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'tabpool' }]"
|
||||
title="标签页池" aria-label="标签页池"
|
||||
:aria-current="activeTab === 'tabpool' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.folderOpen"></span>
|
||||
<span>标签页池</span>
|
||||
</button>
|
||||
<button type="button" @click="selectTab('monitor')"
|
||||
data-tour-target="monitor"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'monitor' }]"
|
||||
title="请求监控" aria-label="请求监控"
|
||||
:aria-current="activeTab === 'monitor' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.chartBar"></span>
|
||||
<span>请求监控</span>
|
||||
</button>
|
||||
<button type="button" @click="selectTab('commands')"
|
||||
data-tour-target="commands"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'commands' }]"
|
||||
title="命令系统" aria-label="命令系统"
|
||||
:aria-current="activeTab === 'commands' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.arrowPathRoundedSquare"></span>
|
||||
<span>命令系统</span>
|
||||
</button>
|
||||
<button type="button" @click="selectTab('logs')"
|
||||
data-tour-target="logs"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'logs' }]"
|
||||
title="运行日志" aria-label="运行日志"
|
||||
:aria-current="activeTab === 'logs' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.documentArrowDown"></span>
|
||||
<span>运行日志</span>
|
||||
</button>
|
||||
<button type="button" @click="selectTab('settings')"
|
||||
data-tour-target="settings"
|
||||
:class="['app-nav-item', { 'is-active': activeTab === 'settings' }]"
|
||||
title="设置" aria-label="设置"
|
||||
:aria-current="activeTab === 'settings' ? 'page' : null">
|
||||
<span class="app-nav-icon" v-html="$icons.cog"></span>
|
||||
<span>设置</span>
|
||||
<span v-if="updateAvailable" class="app-update-dot" title="发现新版本"></span>
|
||||
</button>
|
||||
</nav>
|
||||
<div class="app-sidebar-spacer"></div>
|
||||
|
||||
<div class="app-sidebar-footer">
|
||||
<button type="button" class="app-guide-link" @click="$emit('open-guide')" title="重新打开新手指南">
|
||||
<span class="app-footer-icon" v-html="$icons.bookOpen" aria-hidden="true"></span>
|
||||
<span>新手指南</span>
|
||||
</button>
|
||||
<button type="button" class="app-theme-toggle"
|
||||
@click.prevent.stop="$emit('toggle-dark')"
|
||||
:aria-pressed="darkMode"
|
||||
:title="darkMode ? '切换到日间模式' : '切换到夜间模式'">
|
||||
<span class="app-footer-icon" v-html="darkMode ? $icons.sun : $icons.moon" aria-hidden="true"></span>
|
||||
<span>{{ darkMode ? '日间模式' : '夜间模式' }}</span>
|
||||
<i aria-hidden="true"></i>
|
||||
</button>
|
||||
<div class="app-service-row">
|
||||
<span :class="['app-service-dot', { 'is-online': browserStatus.connected }]"></span>
|
||||
<span>{{ browserStatus.connected ? '浏览器已连接' : '浏览器未连接' }}</span>
|
||||
<button type="button" @click="$emit('refresh-status')" title="刷新状态" aria-label="刷新状态" v-html="$icons.arrowPath"></button>
|
||||
</div>
|
||||
<button v-if="authEnabled" type="button" class="app-auth-row" @click.stop="$emit('show-token-dialog')">
|
||||
<span>面板认证</span>
|
||||
<strong>{{ hasToken ? '已配置' : '待配置' }}</strong>
|
||||
</button>
|
||||
<button type="button" class="app-sidebar-primary" @click="runPrimaryAction" :title="primaryActionLabel" :aria-label="primaryActionLabel">
|
||||
<span v-html="$icons.plusCircle"></span>
|
||||
<span>{{ primaryActionLabel }}</span>
|
||||
</button>
|
||||
<div class="app-sidebar-version"><span>本地模式</span><strong>v2.9.5</strong></div>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,357 @@
|
||||
// ==================== CommandsTab Computed ====================
|
||||
window.CommandsTriggerTypeBuiltinMeta = window.CommandsTriggerTypeBuiltinMeta || {
|
||||
request_count: {
|
||||
label: '请求计数',
|
||||
description: '当页面请求次数达到阈值时触发,适合每隔一段交互插入一次动作。'
|
||||
},
|
||||
error_count: {
|
||||
label: '错误计数',
|
||||
description: '当累计错误次数达到阈值时触发,适合自动恢复、告警或切换策略。'
|
||||
},
|
||||
idle_timeout: {
|
||||
label: '空闲超时',
|
||||
description: '当标签页持续空闲超过设定秒数时触发,适合长时间无响应后的兜底处理。'
|
||||
},
|
||||
page_check: {
|
||||
label: '页面特征探测',
|
||||
description: '通过文本检索或 JavaScript 注入自动检测页面状态(支持识别 Cloudflare 拦截、人机验证或 502 等异常)。'
|
||||
},
|
||||
command_check: {
|
||||
label: '命令检查',
|
||||
description: '先执行一条检查命令,再根据它某一步或最终返回值决定是否开始执行当前动作列表。'
|
||||
},
|
||||
command_triggered: {
|
||||
label: '命令已触发',
|
||||
description: '当指定命令刚刚被触发时联动执行,适合做后续补充动作。'
|
||||
},
|
||||
command_result_match: {
|
||||
label: '命令返回结果',
|
||||
description: '监听指定命令某一步或最终返回值,只有满足匹配条件时才触发。'
|
||||
},
|
||||
command_result_event: {
|
||||
label: '命令结果事件',
|
||||
description: '监听命令产生的结果事件,可按来源命令筛选,也可以只接收事件。'
|
||||
},
|
||||
network_request_error: {
|
||||
label: '网络异常',
|
||||
description: '按请求 URL 和状态码检查网络错误,命中后可立刻刷新、切代理或告警。'
|
||||
}
|
||||
};
|
||||
|
||||
window.CommandsTabComputed = {
|
||||
triggerTypeOptions() {
|
||||
const builtins = window.CommandsTriggerTypeBuiltinMeta || {};
|
||||
const backendLabels = this.meta.trigger_types || {};
|
||||
const orderedKeys = Array.from(new Set([
|
||||
...Object.keys(builtins),
|
||||
...Object.keys(backendLabels)
|
||||
]));
|
||||
|
||||
return orderedKeys.map(key => ({
|
||||
value: key,
|
||||
label: backendLabels[key] || builtins[key]?.label || key,
|
||||
description: builtins[key]?.description || '用于在满足指定条件后触发动作。'
|
||||
}));
|
||||
},
|
||||
actionTypeOptions() {
|
||||
return Object.entries(this.meta.action_types || {})
|
||||
.filter(([k]) => k !== 'switch_preset')
|
||||
.map(([k, v]) => ({ value: k, label: v }));
|
||||
},
|
||||
actionTypeGroups() {
|
||||
const categoryOrder = ['页面操作', '自动化', '预设与流程', '通知与集成', '任务控制'];
|
||||
const categoryMap = {
|
||||
clear_cookies: '页面操作',
|
||||
refresh_page: '页面操作',
|
||||
new_chat: '页面操作',
|
||||
run_js: '页面操作',
|
||||
run_js_file: '页面操作',
|
||||
wait: '页面操作',
|
||||
navigate: '页面操作',
|
||||
click_element: '页面操作',
|
||||
click_coordinates: '页面操作',
|
||||
// 补齐遗漏的分类映射,否则该动作会被 categoryMap[...] || '其他' 扔进“其他”分组
|
||||
click_captcha_challenge: '页面操作',
|
||||
write_element: '自动化',
|
||||
read_element: '自动化',
|
||||
http_request: '自动化',
|
||||
append_file: '自动化',
|
||||
execute_preset: '预设与流程',
|
||||
execute_workflow: '预设与流程',
|
||||
execute_command_group: '预设与流程',
|
||||
switch_proxy: '通知与集成',
|
||||
send_webhook: '通知与集成',
|
||||
send_napcat: '通知与集成',
|
||||
abort_task: '任务控制',
|
||||
release_tab_lock: '任务控制'
|
||||
};
|
||||
const grouped = new Map();
|
||||
for (const option of (this.actionTypeOptions || [])) {
|
||||
const category = categoryMap[option.value] || '其他';
|
||||
if (!grouped.has(category)) grouped.set(category, []);
|
||||
grouped.get(category).push(option);
|
||||
}
|
||||
const dynamicOrder = Array.from(grouped.keys()).filter(name => !categoryOrder.includes(name));
|
||||
return [...categoryOrder, ...dynamicOrder]
|
||||
.filter(name => grouped.has(name))
|
||||
.map(name => ({ label: name, options: grouped.get(name) }));
|
||||
},
|
||||
commandLogLevelOptions() {
|
||||
return [
|
||||
{ value: 'GLOBAL', label: '跟随全局' },
|
||||
{ value: 'DEBUG', label: '调试' },
|
||||
{ value: 'INFO', label: '信息' },
|
||||
{ value: 'WARNING', label: '警告' },
|
||||
{ value: 'ERROR', label: '错误' }
|
||||
];
|
||||
},
|
||||
sourceCommandOptions() {
|
||||
const currentId = this.editingCommand?.id;
|
||||
return (this.commands || [])
|
||||
.filter(cmd => cmd?.id && cmd.id !== currentId)
|
||||
.map(cmd => ({
|
||||
value: cmd.id,
|
||||
label: cmd.name || cmd.id,
|
||||
groupName: String(cmd.group_name || '').trim(),
|
||||
enabled: cmd.enabled !== false,
|
||||
searchText: [
|
||||
cmd.name || '',
|
||||
cmd.id || '',
|
||||
String(cmd.group_name || '').trim()
|
||||
].join(' ').toLowerCase()
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
const aGrouped = a.groupName ? 0 : 1;
|
||||
const bGrouped = b.groupName ? 0 : 1;
|
||||
if (aGrouped !== bGrouped) return aGrouped - bGrouped;
|
||||
if (a.groupName !== b.groupName) {
|
||||
return a.groupName.localeCompare(b.groupName, 'zh-CN');
|
||||
}
|
||||
return a.label.localeCompare(b.label, 'zh-CN');
|
||||
});
|
||||
},
|
||||
selectedSourceCommandOptions() {
|
||||
const ids = new Set(
|
||||
Array.isArray(this.editingCommand?.trigger?.command_ids)
|
||||
? this.editingCommand.trigger.command_ids.map(id => String(id || '').trim()).filter(Boolean)
|
||||
: []
|
||||
);
|
||||
return (this.sourceCommandOptions || []).filter(opt => ids.has(opt.value));
|
||||
},
|
||||
selectedSourceCommandOption() {
|
||||
const selectedId = String(this.editingCommand?.trigger?.command_id || '').trim();
|
||||
if (!selectedId) return null;
|
||||
return this.sourceCommandOptions.find(opt => opt.value === selectedId) || null;
|
||||
},
|
||||
filteredSourceCommandSections() {
|
||||
const keyword = String(this.sourceCommandSearch || '').trim().toLowerCase();
|
||||
const groupedMap = new Map();
|
||||
const ungrouped = [];
|
||||
|
||||
for (const option of (this.sourceCommandOptions || [])) {
|
||||
if (keyword && !option.searchText.includes(keyword)) {
|
||||
continue;
|
||||
}
|
||||
if (option.groupName) {
|
||||
if (!groupedMap.has(option.groupName)) {
|
||||
groupedMap.set(option.groupName, []);
|
||||
}
|
||||
groupedMap.get(option.groupName).push(option);
|
||||
} else {
|
||||
ungrouped.push(option);
|
||||
}
|
||||
}
|
||||
|
||||
const groupedSections = Array.from(groupedMap.entries())
|
||||
.sort((a, b) => a[0].localeCompare(b[0], 'zh-CN'))
|
||||
.map(([name, commands]) => ({
|
||||
key: 'group:' + name,
|
||||
name,
|
||||
commands
|
||||
}));
|
||||
|
||||
if (ungrouped.length > 0) {
|
||||
groupedSections.push({
|
||||
key: 'group:__ungrouped__',
|
||||
name: '未分组命令',
|
||||
commands: ungrouped,
|
||||
isUngrouped: true
|
||||
});
|
||||
}
|
||||
|
||||
return groupedSections;
|
||||
},
|
||||
resultSourceActionOptions() {
|
||||
const sourceId = this.editingCommand?.trigger?.command_id;
|
||||
if (!sourceId) return [];
|
||||
return this.getCommandActionOptions(sourceId);
|
||||
},
|
||||
enabledCount() {
|
||||
return (this.commands || []).filter(cmd => cmd.enabled).length;
|
||||
},
|
||||
disabledCount() {
|
||||
return (this.commands || []).filter(cmd => !cmd.enabled).length;
|
||||
},
|
||||
displayRows() {
|
||||
const rows = [];
|
||||
const groupRowMap = {};
|
||||
for (const cmd of (this.commands || [])) {
|
||||
const groupName = String(cmd?.group_name || '').trim();
|
||||
if (!groupName) {
|
||||
rows.push({
|
||||
key: 'cmd_' + cmd.id,
|
||||
isGroup: false,
|
||||
groupName: '',
|
||||
commands: [cmd]
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!groupRowMap[groupName]) {
|
||||
const row = {
|
||||
key: 'group_' + groupName,
|
||||
isGroup: true,
|
||||
groupName,
|
||||
commands: []
|
||||
};
|
||||
groupRowMap[groupName] = row;
|
||||
rows.push(row);
|
||||
}
|
||||
groupRowMap[groupName].commands.push(cmd);
|
||||
}
|
||||
return rows;
|
||||
},
|
||||
totalPages() {
|
||||
return Math.max(1, Math.ceil((this.displayRows || []).length / this.pageSize));
|
||||
},
|
||||
pageStartIndex() {
|
||||
if (!this.displayRows.length) return 0;
|
||||
return (this.currentPage - 1) * this.pageSize + 1;
|
||||
},
|
||||
pageEndIndex() {
|
||||
return Math.min(this.currentPage * this.pageSize, this.displayRows.length);
|
||||
},
|
||||
visiblePageNumbers() {
|
||||
const total = this.totalPages;
|
||||
const current = this.currentPage;
|
||||
const start = Math.max(1, current - 2);
|
||||
const end = Math.min(total, start + 4);
|
||||
const adjustedStart = Math.max(1, end - 4);
|
||||
return Array.from({ length: end - adjustedStart + 1 }, (_, idx) => adjustedStart + idx);
|
||||
},
|
||||
selectedCommands() {
|
||||
if (!Array.isArray(this.selectedCommandIds) || this.selectedCommandIds.length === 0) return [];
|
||||
const selectedSet = new Set(this.selectedCommandIds);
|
||||
return (this.commands || []).filter(cmd => selectedSet.has(cmd.id));
|
||||
},
|
||||
hasSelection() {
|
||||
return this.selectedCommands.length > 0;
|
||||
},
|
||||
commandGroups() {
|
||||
const bucket = {};
|
||||
for (const cmd of (this.commands || [])) {
|
||||
const groupName = String(cmd?.group_name || '').trim();
|
||||
if (!groupName) continue;
|
||||
if (!bucket[groupName]) {
|
||||
bucket[groupName] = {
|
||||
name: groupName,
|
||||
count: 0,
|
||||
enabledCount: 0,
|
||||
commandIds: []
|
||||
};
|
||||
}
|
||||
bucket[groupName].count += 1;
|
||||
bucket[groupName].enabledCount += cmd.enabled ? 1 : 0;
|
||||
bucket[groupName].commandIds.push(cmd.id);
|
||||
}
|
||||
return Object.values(bucket).sort((a, b) => a.name.localeCompare(b.name, 'zh-CN'));
|
||||
},
|
||||
commandGroupOptions() {
|
||||
return this.commandGroups.map(group => ({ value: group.name, label: group.name }));
|
||||
},
|
||||
paginatedDisplayRows() {
|
||||
const start = (this.currentPage - 1) * this.pageSize;
|
||||
return (this.displayRows || []).slice(start, start + this.pageSize);
|
||||
},
|
||||
visiblePageCommandIds() {
|
||||
const ids = [];
|
||||
for (const row of (this.paginatedDisplayRows || [])) {
|
||||
if (row.isGroup && this.isGroupCollapsed(row.groupName)) continue;
|
||||
for (const cmd of (row.commands || [])) {
|
||||
ids.push(cmd.id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
},
|
||||
resolvedPresetDomain() {
|
||||
return this.getBoundDomain(this.editingCommand);
|
||||
},
|
||||
advancedUiConfig() {
|
||||
return this.editingCommand?.advanced_ui || {};
|
||||
},
|
||||
advancedUiFields() {
|
||||
const fields = this.advancedUiConfig.fields;
|
||||
return Array.isArray(fields) ? fields : [];
|
||||
},
|
||||
advancedUiRuleFields() {
|
||||
return this.advancedUiFields.filter(field => field.type === 'rule_list');
|
||||
},
|
||||
advancedUiGlobalFieldGroups() {
|
||||
const fields = this.advancedUiFields.filter(field => field.type !== 'rule_list');
|
||||
const definitions = [
|
||||
{ id: 'execution', label: '执行与内容', keys: ['total_runs', 'prompt_text', 'reference_image', 'random_insert_chars', 'wait_reply_timeout_sec'] },
|
||||
{ id: 'page', label: '页面交互', keys: ['message_selector', 'send_selector', 'new_chat_selector', 'agree_selector', 'redirect_url'] },
|
||||
{ id: 'retry', label: '重试与恢复', keys: ['new_chat_ready_timeout_sec', 'new_chat_retry_attempts', 'new_chat_retry_delay_sec'] },
|
||||
{ id: 'integration', label: '外部集成', keys: ['link_drawer_path', 'controlled_browser_api_url', 'detector_url'] },
|
||||
{ id: 'legacy', label: '兼容设置', keys: ['arena_detector_enabled', 'arena_detector_model_keyword'] },
|
||||
];
|
||||
const assigned = new Set();
|
||||
const groups = definitions.map(definition => {
|
||||
const groupedFields = definition.keys
|
||||
.map(key => fields.find(field => field.key === key))
|
||||
.filter(Boolean);
|
||||
groupedFields.forEach(field => assigned.add(field.key));
|
||||
return { ...definition, fields: groupedFields };
|
||||
}).filter(group => group.fields.length);
|
||||
const remaining = fields.filter(field => !assigned.has(field.key));
|
||||
if (remaining.length) groups.push({ id: 'other', label: '其他设置', fields: remaining });
|
||||
return groups;
|
||||
},
|
||||
hasAdvancedUiForm() {
|
||||
return String(this.advancedUiConfig.kind || '').trim().toLowerCase() === 'form'
|
||||
&& this.advancedUiFields.length > 0;
|
||||
},
|
||||
advancedUiTitle() {
|
||||
return String(this.advancedUiConfig.title || '').trim() || '高级命令配置';
|
||||
},
|
||||
advancedUiDescription() {
|
||||
if (this.advancedUiFields.some(field => field.type === 'rule_list')) {
|
||||
return '同一轮回复会交给所有模板独立筛选;命中 URL 持久化到结果区,并可按模板写入链接抽屉分组。';
|
||||
}
|
||||
return String(this.advancedUiConfig.description || '').trim();
|
||||
},
|
||||
advancedUiResultsEnabled() {
|
||||
return !!this.advancedUiConfig.results_enabled
|
||||
|| this.advancedUiFields.some(field => field.type === 'rule_list');
|
||||
},
|
||||
scriptPlaceholder() {
|
||||
if (!this.editingCommand) return '';
|
||||
if (this.editingCommand.script_lang === 'javascript') {
|
||||
return '// 在页面中执行的 JavaScript\n' +
|
||||
'// 清除 cookies 并刷新页面\n' +
|
||||
'document.cookie.split(";").forEach(c => {\n' +
|
||||
' document.cookie = c.trim().split("=")[0] + "=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/";\n' +
|
||||
'});\n' +
|
||||
'location.reload();';
|
||||
} else {
|
||||
return '# Python 脚本\n' +
|
||||
'# 默认使用受限沙箱;可用变量: tab, session, browser, config_engine, logger, time, json\n' +
|
||||
'# 默认允许导入: json, time, datetime, math, requests, urllib.parse\n\n' +
|
||||
'logger.info(f"当前 URL: {tab.url}")\n' +
|
||||
'logger.info(f"请求次数: {session.request_count}")\n\n' +
|
||||
'# 清除 cookies 并刷新\n' +
|
||||
'tab.run_js("document.cookie.split(\\";\\").forEach(c => document.cookie = c.trim().split(\\"=\\")[0] + \\"=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/\\");")\n' +
|
||||
'time.sleep(0.5)\n' +
|
||||
'tab.refresh()';
|
||||
}
|
||||
}
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,212 @@
|
||||
// R2-8:站点适配器维护面板——健康巡检(R1-6)、选择器脆弱度(R1-7)、适配器在线更新(R1-3)。
|
||||
// 由 ConfigTab 以 <adapter-panel> 使用;request 为带鉴权与超时的请求函数(返回解析后的 JSON,出错抛异常)。
|
||||
window.AdapterPanel = {
|
||||
name: 'AdapterPanel',
|
||||
props: {
|
||||
domain: { type: String, default: '' },
|
||||
presetName: { type: String, default: '' },
|
||||
request: { type: Function, required: true }
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
health: null, healthLoading: false, healthError: '',
|
||||
lint: null, lintLoading: false, lintError: '',
|
||||
updates: null, updatesLoading: false, updatesError: '',
|
||||
applyResult: null, applying: false
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
healthTab() {
|
||||
return (this.health && Array.isArray(this.health.tabs) && this.health.tabs[0]) || null;
|
||||
},
|
||||
lintRows() {
|
||||
const presets = (this.lint && this.lint.presets) || {};
|
||||
const rows = presets[this.presetName] || Object.values(presets)[0] || [];
|
||||
return rows.filter(row => row.score < 100 || (row.issues || []).length);
|
||||
},
|
||||
updateRows() {
|
||||
return ((this.updates && this.updates.sites) || []).filter(row => row.status !== 'up_to_date');
|
||||
},
|
||||
safeUpdateCount() {
|
||||
return this.updateRows.filter(row => row.status === 'update_available' || row.status === 'new_site').length;
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
domain() {
|
||||
this.health = null; this.healthError = '';
|
||||
this.lint = null; this.lintError = '';
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
statusLabel(status) {
|
||||
return ({
|
||||
healthy: '健康', degraded: '部分缺失', broken: '异常', unreachable: '无可用页面',
|
||||
ok: '命中', missing: '未命中', invalid: '语法无效',
|
||||
up_to_date: '已是最新', update_available: '可安全更新', conflict: '本地已修改',
|
||||
new_site: '新站点', local_only: '仅本地', requires_newer_app: '需要更新程序'
|
||||
})[status] || status;
|
||||
},
|
||||
statusClass(status) {
|
||||
if (['healthy', 'ok', 'up_to_date'].includes(status)) return 'adapter-badge is-good';
|
||||
if (['degraded', 'missing', 'update_available', 'new_site', 'conflict'].includes(status)) return 'adapter-badge is-warn';
|
||||
if (['broken', 'invalid', 'requires_newer_app'].includes(status)) return 'adapter-badge is-bad';
|
||||
return 'adapter-badge';
|
||||
},
|
||||
async runHealth() {
|
||||
if (!this.domain) return;
|
||||
this.healthLoading = true; this.healthError = '';
|
||||
try {
|
||||
const query = new URLSearchParams({ site: this.domain });
|
||||
if (this.presetName) query.set('preset', this.presetName);
|
||||
this.health = await this.request('/api/adapters/health?' + query.toString());
|
||||
} catch (error) {
|
||||
this.healthError = error.message || String(error);
|
||||
} finally {
|
||||
this.healthLoading = false;
|
||||
}
|
||||
},
|
||||
async runLint() {
|
||||
if (!this.domain) return;
|
||||
this.lintLoading = true; this.lintError = '';
|
||||
try {
|
||||
this.lint = await this.request('/api/adapters/lint?' + new URLSearchParams({ site: this.domain }).toString());
|
||||
} catch (error) {
|
||||
this.lintError = error.message || String(error);
|
||||
} finally {
|
||||
this.lintLoading = false;
|
||||
}
|
||||
},
|
||||
async checkUpdates(keepApplyResult = false) {
|
||||
// 应用更新后会自动刷新列表:这时要保留“已更新 N 个站点”的结果提示,不能被清掉
|
||||
this.updatesLoading = true; this.updatesError = '';
|
||||
if (!keepApplyResult) this.applyResult = null;
|
||||
try {
|
||||
this.updates = await this.request('/api/adapters/updates');
|
||||
} catch (error) {
|
||||
this.updatesError = error.message || String(error);
|
||||
} finally {
|
||||
this.updatesLoading = false;
|
||||
}
|
||||
},
|
||||
async applyUpdates(sites = null, includeConflicts = false) {
|
||||
if (includeConflicts && !window.confirm('该站点的本地配置改过:将按「本地优先」与官方新版合并(保留你的修改,补入新增字段)。继续?')) {
|
||||
return;
|
||||
}
|
||||
this.applying = true; this.updatesError = '';
|
||||
try {
|
||||
const body = { include_conflicts: includeConflicts };
|
||||
if (sites) body.sites = sites;
|
||||
this.applyResult = await this.request('/api/adapters/updates/apply', {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body)
|
||||
});
|
||||
this.$emit('updated', this.applyResult);
|
||||
await this.checkUpdates(true);
|
||||
} catch (error) {
|
||||
this.updatesError = error.message || String(error);
|
||||
} finally {
|
||||
this.applying = false;
|
||||
}
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="adapter-panel">
|
||||
<section class="cap-card adapter-card" aria-label="健康巡检">
|
||||
<div class="adapter-card-header">
|
||||
<div>
|
||||
<h4>健康巡检</h4>
|
||||
<p>在浏览器里已打开的 {{ domain || '当前站点' }} 页面上检查各选择器能否命中。只读取页面,不会输入、点击或发送消息。</p>
|
||||
</div>
|
||||
<button type="button" class="adapter-btn" :disabled="!domain || healthLoading" @click="runHealth()">
|
||||
{{ healthLoading ? '巡检中…' : '开始巡检' }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="healthError" class="adapter-error">{{ healthError }}</p>
|
||||
<div v-if="health" class="adapter-result">
|
||||
<p>结果:<span :class="statusClass(health.status)">{{ statusLabel(health.status) }}</span>
|
||||
<span v-if="health.preset" class="adapter-muted">预设:{{ health.preset }}</span></p>
|
||||
<ul v-if="health.problems && health.problems.length" class="adapter-problems">
|
||||
<li v-for="problem in health.problems" :key="problem">{{ problem }}</li>
|
||||
</ul>
|
||||
<table v-if="healthTab" class="adapter-table">
|
||||
<thead><tr><th>元素</th><th>状态</th><th>命中数</th><th>稳健度</th><th>说明</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="row in healthTab.selectors" :key="row.key">
|
||||
<td><code>{{ row.key }}</code></td>
|
||||
<td><span :class="statusClass(row.status)">{{ statusLabel(row.status) }}</span></td>
|
||||
<td>{{ row.count }}</td>
|
||||
<td>{{ row.quality ? row.quality.score : '-' }}</td>
|
||||
<td>
|
||||
<span v-if="row.hint">{{ row.hint }}</span>
|
||||
<span v-if="row.suggestions && row.suggestions.length">可尝试:<code>{{ row.suggestions[0].selector }}</code></span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="cap-card adapter-card" aria-label="选择器稳健度">
|
||||
<div class="adapter-card-header">
|
||||
<div>
|
||||
<h4>选择器稳健度</h4>
|
||||
<p>静态检查当前预设的选择器:生成的哈希类名、依赖元素顺序或界面文字的写法,在站点改版时容易失效。</p>
|
||||
</div>
|
||||
<button type="button" class="adapter-btn" :disabled="!domain || lintLoading" @click="runLint()">
|
||||
{{ lintLoading ? '检查中…' : '检查' }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="lintError" class="adapter-error">{{ lintError }}</p>
|
||||
<div v-if="lint" class="adapter-result">
|
||||
<p v-if="!lintRows.length" class="adapter-good">当前预设的选择器没有发现明显问题。</p>
|
||||
<table v-else class="adapter-table">
|
||||
<thead><tr><th>元素</th><th>得分</th><th>问题</th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="row in lintRows" :key="row.key">
|
||||
<td><code>{{ row.key }}</code></td>
|
||||
<td>{{ row.score }}</td>
|
||||
<td>{{ (row.issues || []).map(issue => issue.message).join(';') || '—' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="cap-card adapter-card" aria-label="适配器更新">
|
||||
<div class="adapter-card-header">
|
||||
<div>
|
||||
<h4>适配器更新(全部站点)</h4>
|
||||
<p>与官方仓库的站点配置比较。没改过的站点可以一键更新;改过的站点会单独标出,需要你确认后按「本地优先」合并。</p>
|
||||
</div>
|
||||
<button type="button" class="adapter-btn" :disabled="updatesLoading || applying" @click="checkUpdates()">
|
||||
{{ updatesLoading ? '检查中…' : '检查更新' }}
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="updatesError" class="adapter-error">{{ updatesError }}</p>
|
||||
<div v-if="updates" class="adapter-result">
|
||||
<p v-if="!updateRows.length" class="adapter-good">所有站点配置都是最新的。</p>
|
||||
<template v-else>
|
||||
<table class="adapter-table">
|
||||
<thead><tr><th>站点</th><th>状态</th><th>本地版本</th><th>官方版本</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
<tr v-for="row in updateRows" :key="row.site">
|
||||
<td><code>{{ row.site }}</code></td>
|
||||
<td><span :class="statusClass(row.status)">{{ statusLabel(row.status) }}</span></td>
|
||||
<td>{{ row.local_version || '—' }}</td>
|
||||
<td>{{ row.official_version || '—' }}</td>
|
||||
<td>
|
||||
<button v-if="row.status === 'conflict'" type="button" class="adapter-btn is-small" :disabled="applying"
|
||||
@click="applyUpdates([row.site], true)">合并</button>
|
||||
<span v-else-if="row.status === 'requires_newer_app'" class="adapter-muted">需要 {{ row.min_app_version }}+</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<button type="button" class="adapter-btn" :disabled="applying || !safeUpdateCount" @click="applyUpdates()">
|
||||
{{ applying ? '更新中…' : ('应用 ' + safeUpdateCount + ' 个安全更新') }}
|
||||
</button>
|
||||
</template>
|
||||
<p v-if="applyResult" class="adapter-good">已更新 {{ (applyResult.applied || []).length }} 个站点<span v-if="(applyResult.skipped || []).length">,跳过 {{ applyResult.skipped.length }} 个</span>。</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>`
|
||||
};
|
||||
@@ -0,0 +1,50 @@
|
||||
// ==================== 提取器显示面板 ====================
|
||||
|
||||
window.ExtractorPanel = {
|
||||
name: 'ExtractorPanel',
|
||||
props: {
|
||||
extractorId: { type: String, default: null },
|
||||
extractorVerified: { type: Boolean, default: false },
|
||||
collapsed: { type: Boolean, default: true }
|
||||
},
|
||||
emits: ['update:collapsed'],
|
||||
methods: {
|
||||
toggle() {
|
||||
this.$emit('update:collapsed', !this.collapsed);
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm">
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="toggle">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="w-4 inline-flex justify-center text-gray-500 dark:text-gray-400" v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">🧩 提取器</h3>
|
||||
</div>
|
||||
</div>
|
||||
<div v-show="!collapsed" class="p-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<div class="text-sm text-gray-600 dark:text-gray-300">
|
||||
当前: <span class="font-medium">{{ extractorId || '默认' }}</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2 mt-1">
|
||||
<span v-if="extractorVerified"
|
||||
class="px-2 py-0.5 text-xs bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 rounded">
|
||||
✓ 已验证
|
||||
</span>
|
||||
<span v-else
|
||||
class="px-2 py-0.5 text-xs bg-yellow-100 dark:bg-yellow-900/50 text-yellow-700 dark:text-yellow-300 rounded">
|
||||
⚠ 未验证
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-sm text-gray-500 dark:text-gray-400">
|
||||
前往「提取器」Tab 管理
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
|
||||
@@ -0,0 +1,812 @@
|
||||
// ==================== 文件粘贴 / 附件发送配置面板 ====================
|
||||
|
||||
window.FilePastePanel = {
|
||||
name: 'FilePastePanel',
|
||||
props: {
|
||||
filePasteConfig: { type: Object, required: true },
|
||||
currentDomain: { type: String, default: null },
|
||||
selectedPreset: { type: String, default: null },
|
||||
collapsed: { type: Boolean, default: true }
|
||||
},
|
||||
emits: ['update:collapsed'],
|
||||
data() {
|
||||
return {
|
||||
// 内部分区折叠状态:高级附件规则默认收起,其余默认展开
|
||||
sectionCollapsed: {
|
||||
attachments: false,
|
||||
pasteMode: false,
|
||||
sendConfirm: false,
|
||||
advancedRules: true
|
||||
},
|
||||
defaultAttachments: {
|
||||
enabled: true, max_count: 8, max_file_mb: 20, max_total_mb: 50,
|
||||
allowed_types: [], error_selectors: [], ready_timeout: 30,
|
||||
transport_order: ['file_input', 'cdp_drop', 'js_drop', 'file_clipboard']
|
||||
},
|
||||
transportOptions: [
|
||||
{ value: 'file_input', label: '文件输入框', description: '优先上传原文件;使用 file_input 选择器或自动查找。' },
|
||||
{ value: 'cdp_drop', label: '浏览器原生拖拽', description: '需要 drop_zone;不通过 base64 传输大文件。' },
|
||||
{ value: 'js_drop', label: '网页拖拽事件', description: '需要 drop_zone;仅用于不超过 4 MB 的文件。' },
|
||||
{ value: 'file_clipboard', label: '原生文件剪贴板', description: '需要系统支持与已确认的输入框焦点。' },
|
||||
{ value: 'image_clipboard', label: '图片像素剪贴板(有损)', description: '仅用于图片兼容;可能丢失透明度、动画帧和元数据。' }
|
||||
],
|
||||
defaultFilePaste: {
|
||||
enabled: false,
|
||||
threshold: 50000,
|
||||
temp_file_type: 'txt',
|
||||
hint_text: '完全专注于文件内容',
|
||||
txt_hint_text: '完全专注于文件内容',
|
||||
pdf_hint_text: '完全专注于文件内容',
|
||||
error_hint_text: '输入文本长度超过限制,已中止发送',
|
||||
reacquire_input_after_upload: false,
|
||||
post_upload_input_selector: '',
|
||||
post_upload_settle: 0.0,
|
||||
upload_signal_timeout: 2.5,
|
||||
upload_signal_grace: 3.0,
|
||||
state_probe: {
|
||||
enabled: false,
|
||||
code: ''
|
||||
}
|
||||
},
|
||||
tempFileTypeOptions: [
|
||||
{ value: 'txt', label: 'TXT' },
|
||||
{ value: 'pdf', label: 'PDF' },
|
||||
{ value: 'chunk', label: '分块' },
|
||||
{ value: 'error', label: 'ERROR' }
|
||||
],
|
||||
// 修复:补齐后端 get_default_send_confirmation_config() 的 7 个缺失键,
|
||||
// 否则未配过这些项的预设打开面板时对应输入框为空(如 pre_retry_probe_window)
|
||||
defaultSendConfirmation: {
|
||||
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
|
||||
},
|
||||
defaultAttachmentMonitor: {
|
||||
root_selectors: [],
|
||||
attachment_selectors: [],
|
||||
pending_selectors: [],
|
||||
status_selectors: [],
|
||||
content_exclusion_selectors: [],
|
||||
busy_text_markers: [],
|
||||
ignored_busy_text_markers: [],
|
||||
send_button_disabled_markers: [],
|
||||
require_attachment_present: false,
|
||||
require_upload_signal_before_ready: false,
|
||||
continue_once_on_unconfirmed_send: true,
|
||||
idle_timeout: 8.0,
|
||||
hard_max_wait: 90.0
|
||||
},
|
||||
attachmentSensitivityOptions: [
|
||||
{
|
||||
value: 'low',
|
||||
label: '低',
|
||||
description: '只认更强的发送信号,适合按钮状态经常乱跳的站点。'
|
||||
},
|
||||
{
|
||||
value: 'medium',
|
||||
label: '中',
|
||||
description: '平衡等待时间和识别速度,适合作为大多数站点的默认值。'
|
||||
},
|
||||
{
|
||||
value: 'high',
|
||||
label: '高',
|
||||
description: '更早接受附件发送成功信号,适合附件反馈慢、预览挂得晚的站点。'
|
||||
}
|
||||
],
|
||||
attachmentMonitorDrafts: {}
|
||||
};
|
||||
},
|
||||
watch: {
|
||||
filePasteConfig: {
|
||||
handler() {
|
||||
this.syncAttachmentMonitorDrafts();
|
||||
},
|
||||
deep: true,
|
||||
immediate: true
|
||||
},
|
||||
currentDomain() {
|
||||
this.syncAttachmentMonitorDrafts(true);
|
||||
},
|
||||
selectedPreset() {
|
||||
this.syncAttachmentMonitorDrafts(true);
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.syncAttachmentMonitorDrafts(true);
|
||||
},
|
||||
computed: {
|
||||
resolvedAttachments() {
|
||||
return { ...this.defaultAttachments, ...((this.filePasteConfig || {}).attachments || {}) };
|
||||
},
|
||||
orderedTransports() {
|
||||
return (this.resolvedAttachments.transport_order || [])
|
||||
.map(value => this.transportOptions.find(option => option.value === value)).filter(Boolean);
|
||||
},
|
||||
longTextStrategy() {
|
||||
return ['chunk', 'error'].includes(this.resolvedFilePaste.temp_file_type)
|
||||
? this.resolvedFilePaste.temp_file_type : 'attachment';
|
||||
},
|
||||
resolvedFilePaste() {
|
||||
const raw = this.filePasteConfig || {};
|
||||
return {
|
||||
...this.defaultFilePaste,
|
||||
...raw,
|
||||
send_confirmation: {
|
||||
...this.defaultSendConfirmation,
|
||||
...((raw && raw.send_confirmation) || {})
|
||||
},
|
||||
attachment_monitor: {
|
||||
...this.defaultAttachmentMonitor,
|
||||
...((raw && raw.attachment_monitor) || {})
|
||||
},
|
||||
state_probe: {
|
||||
...(this.defaultFilePaste.state_probe || {}),
|
||||
...((raw && raw.state_probe) || {})
|
||||
},
|
||||
};
|
||||
},
|
||||
currentPresetLabel() {
|
||||
return String(this.selectedPreset || '').trim() || '主预设';
|
||||
},
|
||||
statusText() {
|
||||
return (this.resolvedAttachments.enabled ? '附件允许' : '附件禁止') + ' · ' + (this.resolvedFilePaste.enabled ? '长文本处理开启' : '长文本处理关闭');
|
||||
},
|
||||
attachmentSensitivityMeta() {
|
||||
const value = this.resolvedFilePaste.send_confirmation.attachment_sensitivity;
|
||||
return this.attachmentSensitivityOptions.find(option => option.value === value) || this.attachmentSensitivityOptions[1];
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
updateAttachmentField(key, value) {
|
||||
const config = this.getMutableFilePaste();
|
||||
config.attachments = { ...(config.attachments || {}), [key]: value };
|
||||
},
|
||||
updateAttachmentLimit(key, value, ceiling) {
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number) || value === '') return;
|
||||
this.updateAttachmentField(key, Math.max(1, Math.min(ceiling, Math.trunc(number))));
|
||||
},
|
||||
updateAllowedTypes(value) {
|
||||
this.updateAttachmentField('allowed_types', [...new Set(String(value || '').toLowerCase().split(/[\s,;]+/).filter(Boolean))]);
|
||||
},
|
||||
toggleTransport(value) {
|
||||
const current = [...(this.resolvedAttachments.transport_order || [])];
|
||||
const next = current.includes(value) ? current.filter(item => item !== value) : [...current, value];
|
||||
this.updateAttachmentField('transport_order', next);
|
||||
},
|
||||
moveTransport(index, direction) {
|
||||
const current = [...(this.resolvedAttachments.transport_order || [])];
|
||||
const next = index + direction;
|
||||
if (next < 0 || next >= current.length) return;
|
||||
[current[index], current[next]] = [current[next], current[index]];
|
||||
this.updateAttachmentField('transport_order', current);
|
||||
},
|
||||
updateLongTextStrategy(value) {
|
||||
this.updateTempFileType(value === 'attachment' ? 'txt' : value);
|
||||
},
|
||||
toggle() {
|
||||
this.$emit('update:collapsed', !this.collapsed);
|
||||
},
|
||||
|
||||
toggleSection(key) {
|
||||
this.sectionCollapsed[key] = !this.sectionCollapsed[key];
|
||||
},
|
||||
|
||||
getMutableFilePaste() {
|
||||
return this.filePasteConfig || {};
|
||||
},
|
||||
|
||||
ensureSendConfirmation() {
|
||||
const fp = this.getMutableFilePaste();
|
||||
if (!fp.send_confirmation || typeof fp.send_confirmation !== 'object') {
|
||||
fp.send_confirmation = {};
|
||||
}
|
||||
return fp.send_confirmation;
|
||||
},
|
||||
|
||||
ensureAttachmentMonitor() {
|
||||
const fp = this.getMutableFilePaste();
|
||||
if (!fp.attachment_monitor || typeof fp.attachment_monitor !== 'object') {
|
||||
fp.attachment_monitor = {};
|
||||
}
|
||||
return fp.attachment_monitor;
|
||||
},
|
||||
|
||||
ensureStateProbe() {
|
||||
const fp = this.getMutableFilePaste();
|
||||
if (!fp.state_probe || typeof fp.state_probe !== 'object') {
|
||||
fp.state_probe = {};
|
||||
}
|
||||
return fp.state_probe;
|
||||
},
|
||||
|
||||
toggleEnabled() {
|
||||
const fp = this.getMutableFilePaste();
|
||||
fp.enabled = !this.resolvedFilePaste.enabled;
|
||||
},
|
||||
|
||||
updateThreshold(value) {
|
||||
// 修复:此前 <1000 直接丢弃,DOM 与模型脱节;改为与后端一致的夹取
|
||||
const num = parseInt(value);
|
||||
this.getMutableFilePaste().threshold = Number.isFinite(num)
|
||||
? Math.max(1000, Math.min(num, 10000000))
|
||||
: 50000;
|
||||
},
|
||||
|
||||
updateTempFileType(value) {
|
||||
const normalized = String(value || '').trim().toLowerCase();
|
||||
this.getMutableFilePaste().temp_file_type = ['txt', 'pdf', 'chunk', 'error'].includes(normalized) ? normalized : 'txt';
|
||||
},
|
||||
|
||||
updateHintText(value) {
|
||||
const fp = this.getMutableFilePaste();
|
||||
const type = this.resolvedFilePaste.temp_file_type;
|
||||
if (type === 'txt') {
|
||||
fp.txt_hint_text = value;
|
||||
} else if (type === 'pdf') {
|
||||
fp.pdf_hint_text = value;
|
||||
} else if (type === 'error') {
|
||||
fp.error_hint_text = value;
|
||||
}
|
||||
fp.hint_text = value;
|
||||
},
|
||||
|
||||
updateNumberField(field, value, fallback) {
|
||||
const parsed = parseFloat(value);
|
||||
this.getMutableFilePaste()[field] = Number.isFinite(parsed) ? parsed : fallback;
|
||||
},
|
||||
|
||||
updateBooleanField(field, value) {
|
||||
this.getMutableFilePaste()[field] = !!value;
|
||||
},
|
||||
|
||||
updateTextField(field, value) {
|
||||
this.getMutableFilePaste()[field] = value;
|
||||
},
|
||||
|
||||
updateSendConfirmationField(field, value) {
|
||||
this.ensureSendConfirmation()[field] = value;
|
||||
},
|
||||
|
||||
updateAttachmentMonitorField(field, value) {
|
||||
this.ensureAttachmentMonitor()[field] = value;
|
||||
},
|
||||
|
||||
updateStateProbeField(field, value) {
|
||||
this.ensureStateProbe()[field] = value;
|
||||
},
|
||||
|
||||
normalizeRuleList(value) {
|
||||
const lines = String(value || '')
|
||||
.split(/\r?\n/)
|
||||
.map(item => item.trim())
|
||||
.filter(Boolean);
|
||||
return [...new Set(lines)];
|
||||
},
|
||||
|
||||
syncAttachmentMonitorDrafts(force = false) {
|
||||
const monitor = this.resolvedFilePaste?.attachment_monitor || {};
|
||||
const listFields = [
|
||||
'attachment_selectors',
|
||||
'pending_selectors',
|
||||
'status_selectors',
|
||||
'content_exclusion_selectors',
|
||||
'busy_text_markers',
|
||||
'send_button_disabled_markers',
|
||||
'ignored_busy_text_markers',
|
||||
'root_selectors'
|
||||
];
|
||||
if (!this.attachmentMonitorDrafts) {
|
||||
this.attachmentMonitorDrafts = {};
|
||||
}
|
||||
const nextDrafts = { ...this.attachmentMonitorDrafts };
|
||||
let hasChange = false;
|
||||
for (const field of listFields) {
|
||||
const propArr = Array.isArray(monitor[field]) ? monitor[field] : [];
|
||||
const curDraftArr = this.normalizeRuleList(nextDrafts[field]);
|
||||
if (force || JSON.stringify(propArr) !== JSON.stringify(curDraftArr) || nextDrafts[field] === undefined || nextDrafts[field] === null) {
|
||||
nextDrafts[field] = propArr.join('\n');
|
||||
hasChange = true;
|
||||
}
|
||||
}
|
||||
if (hasChange) {
|
||||
this.attachmentMonitorDrafts = nextDrafts;
|
||||
}
|
||||
},
|
||||
|
||||
updateAttachmentMonitorListField(field, value) {
|
||||
if (!this.attachmentMonitorDrafts) {
|
||||
this.attachmentMonitorDrafts = {};
|
||||
}
|
||||
this.attachmentMonitorDrafts[field] = value;
|
||||
this.updateAttachmentMonitorField(field, this.normalizeRuleList(value));
|
||||
},
|
||||
|
||||
formatRuleList(value) {
|
||||
return Array.isArray(value) ? value.join('\n') : '';
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="cap-panel cap-input-panel bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm">
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="toggle">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="w-4 inline-flex justify-center text-gray-500 dark:text-gray-400" v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">发送内容</h3>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">({{ statusText }})</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!collapsed" class="p-4 space-y-4">
|
||||
|
||||
|
||||
<section class="cap-card" :class="{ 'is-enabled': resolvedAttachments.enabled }" aria-label="发送附件"><div class="cap-card-header"><span class="cap-icon" v-html="$icons.arrowUpTray"></span><div class="cap-copy"><div class="cap-title-row"><h4>发送附件</h4><span class="cap-scope">当前预设</span></div><p>把图片、文档或音视频交给 AI。网站本身也需要支持这些文件。</p></div><label class="cap-switch"><span class="cap-state" :class="{ 'is-on': resolvedAttachments.enabled }">{{ resolvedAttachments.enabled ? '已开启' : '已关闭' }}</span><input role="switch" aria-label="发送附件" type="checkbox" :checked="resolvedAttachments.enabled" @change="updateAttachmentField('enabled', $event.target.checked)" class="cap-switch-input"><i aria-hidden="true"></i></label></div><p class="cap-facts">最多 {{ resolvedAttachments.max_count }} 个文件 <i>·</i> 单个 {{ resolvedAttachments.max_file_mb }} MB <i>·</i> 合计 {{ resolvedAttachments.max_total_mb }} MB</p><p v-if="!resolvedAttachments.enabled" class="cap-warning">已关闭附件上传;长文本也不能转为文件发送。普通文本仍可使用。</p><details class="cap-settings"><summary><span><strong>调整文件限制</strong><small>文件数量、大小与类型</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div class="cap-form-grid">
|
||||
<label class="text-xs text-gray-700 dark:text-gray-300">一次最多几个文件
|
||||
<input type="number" min="1" max="32" :value="resolvedAttachments.max_count" @change="updateAttachmentLimit('max_count', $event.target.value, 32)" class="mt-1 w-full border dark:border-gray-600 rounded-md px-3 py-2 bg-white dark:bg-gray-700">
|
||||
</label>
|
||||
<label class="text-xs text-gray-700 dark:text-gray-300">单个文件大小(MB)
|
||||
<input type="number" min="1" max="100" :value="resolvedAttachments.max_file_mb" @change="updateAttachmentLimit('max_file_mb', $event.target.value, 100)" class="mt-1 w-full border dark:border-gray-600 rounded-md px-3 py-2 bg-white dark:bg-gray-700">
|
||||
</label>
|
||||
<label class="text-xs text-gray-700 dark:text-gray-300">全部文件总大小(MB)
|
||||
<input type="number" min="1" max="200" :value="resolvedAttachments.max_total_mb" @change="updateAttachmentLimit('max_total_mb', $event.target.value, 200)" class="mt-1 w-full border dark:border-gray-600 rounded-md px-3 py-2 bg-white dark:bg-gray-700">
|
||||
</label>
|
||||
|
||||
</div><label class="block text-sm text-gray-700 dark:text-gray-300">允许哪些文件(可选)
|
||||
<input type="text" :value="(resolvedAttachments.allowed_types || []).join(', ')" @change="updateAllowedTypes($event.target.value)" placeholder="例如 .pdf, .docx, image/*" class="mt-1 w-full border dark:border-gray-600 rounded-md px-3 py-2 text-sm font-mono bg-white dark:bg-gray-700">
|
||||
<span class="block mt-1 text-xs text-gray-500 dark:text-gray-400">用逗号分隔文件扩展名或 MIME 类型;留空不额外限制。网站本身仍需支持这些文件。</span>
|
||||
</label><details class="cap-technical"><summary><span><strong>上传兼容与错误识别</strong><small>只有上传失败、需要拖拽或网站提示错误时再调整。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><label class="text-xs text-gray-700 dark:text-gray-300">单附件确认预算(秒)
|
||||
<input type="number" min="1" max="180" :value="resolvedAttachments.ready_timeout" @change="updateAttachmentLimit('ready_timeout', $event.target.value, 180)" class="mt-1 w-full border dark:border-gray-600 rounded-md px-3 py-2 bg-white dark:bg-gray-700">
|
||||
</label>
|
||||
<label class="block text-sm text-gray-700 dark:text-gray-300">网页上的上传错误提示(CSS 选择器)(可选,一行一个)
|
||||
<textarea :value="(resolvedAttachments.error_selectors || []).join('\\n')" @change="updateAttachmentField('error_selectors', $event.target.value.split(/\\n/).map(v => v.trim()).filter(Boolean))" placeholder=".upload-card[data-state=error]" rows="2" class="mt-1 w-full border dark:border-gray-600 rounded-md px-3 py-2 text-sm font-mono bg-white dark:bg-gray-700"></textarea>
|
||||
<span class="block text-xs text-gray-500 dark:text-gray-400">只匹配编辑区内可见的错误节点;命中后立即停止,不把错误预览视为上传成功。</span>
|
||||
</label>
|
||||
<div class="space-y-2">
|
||||
<div class="text-sm font-medium text-gray-800 dark:text-gray-200">尝试上传的顺序 <span class="text-xs font-normal text-gray-500">仅在确认尚未投递时回退</span></div>
|
||||
<div v-for="(transport, index) in orderedTransports" :key="transport.value" class="flex items-center gap-3 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800 p-3">
|
||||
<span class="text-xs text-blue-600 dark:text-blue-400">{{ index + 1 }}</span>
|
||||
<div class="flex-1 min-w-0"><div class="text-sm text-gray-800 dark:text-gray-200">{{ transport.label }}</div><p class="text-xs text-gray-500 dark:text-gray-400 mt-1">{{ transport.description }}</p></div>
|
||||
<button type="button" :disabled="index === 0" @click="moveTransport(index, -1)" :aria-label="transport.label + '上移'" class="px-2 py-1 border rounded disabled:opacity-30">↑</button>
|
||||
<button type="button" :disabled="index === orderedTransports.length - 1" @click="moveTransport(index, 1)" :aria-label="transport.label + '下移'" class="px-2 py-1 border rounded disabled:opacity-30">↓</button>
|
||||
<button type="button" @click="toggleTransport(transport.value)" :aria-label="'停用' + transport.label" class="text-xs text-red-600 dark:text-red-400 px-2 py-1">停用</button>
|
||||
</div>
|
||||
<div v-if="!orderedTransports.length" class="text-xs text-red-600 dark:text-red-400">没有启用上传方式,附件将被明确拒绝,不会自动启用其他方式。</div>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<template v-for="option in transportOptions" :key="option.value">
|
||||
<button v-if="!resolvedAttachments.transport_order.includes(option.value)" type="button" @click="toggleTransport(option.value)" class="border border-dashed border-gray-400 rounded-md text-xs px-3 py-2 text-gray-600 dark:text-gray-300">+ {{ option.label }}</button>
|
||||
</template>
|
||||
</div>
|
||||
<p v-if="resolvedAttachments.transport_order.includes('image_clipboard')" class="text-xs text-amber-700 dark:text-amber-300">已启用有损图片剪贴板兼容。需要原文件保真时,请停用此方式。</p>
|
||||
</div>
|
||||
<details class="text-xs text-gray-600 dark:text-gray-400">
|
||||
<summary class="cursor-pointer font-medium">API 附件格式与兼容说明</summary>
|
||||
<div class="mt-2 space-y-2 leading-5">
|
||||
<p>支持 image_url、OpenAI file / Responses input_file、Anthropic document、input_audio 与音视频 URL。文件 ID、本地路径和 file:// 暂不支持;原始附件内容不会降级为提示词。</p>
|
||||
<pre class="overflow-x-auto p-3 rounded bg-gray-900 text-gray-100">{"type":"file","file":{"filename":"notes.txt","file_data":"data:text/plain;base64,aGVsbG8="}}</pre>
|
||||
<p>通用附件管线的配置存储在当前预设的 file_paste.attachments 中,旧配置无需手动迁移。选择器仍在「元素选择器」,就绪探针在下方「高级附件规则」。MB 按 1024² 字节计算。</p>
|
||||
</div>
|
||||
</details>
|
||||
</div></details></div></details></section>
|
||||
|
||||
<section class="cap-card" :class="{ 'is-enabled': resolvedFilePaste.enabled }" aria-label="长文本处理"><div class="cap-card-header"><span class="cap-icon" v-html="$icons.documentArrowDown"></span><div class="cap-copy"><div class="cap-title-row"><h4>长文本处理</h4><span class="cap-scope">当前预设</span></div><p>文字太长、网页放不下时,选择转成文件、分段发送或中止请求。</p></div><label class="cap-switch"><span class="cap-state" :class="{ 'is-on': resolvedFilePaste.enabled }">{{ resolvedFilePaste.enabled ? '已开启' : '已关闭' }}</span><input role="switch" aria-label="长文本处理" type="checkbox" :checked="resolvedFilePaste.enabled" @change="toggleEnabled" class="cap-switch-input"><i aria-hidden="true"></i></label></div><p class="cap-facts">{{ resolvedFilePaste.enabled ? '超过 ' + resolvedFilePaste.threshold + ' 字符时处理' : '当前不启用额外的长文本处理' }}<template v-if="resolvedFilePaste.enabled"> <i>·</i> {{ longTextStrategy === 'attachment' ? '转成文件' : longTextStrategy === 'chunk' ? '分段发送' : '中止并报错' }}</template></p><details class="cap-settings"><summary><span><strong>设置长文本处理方式</strong><small>长度阈值与超长后的行为</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><p class="cap-inline-help">转成文件需要先允许附件上传。分段发送会逐轮等待,只返回最后一轮回复。</p>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">超过多少字符开始处理</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.threshold"
|
||||
@input="updateThreshold($event.target.value)"
|
||||
min="1000"
|
||||
max="10000000"
|
||||
step="1000"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm text-right bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">字符</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">超长处理方式</label>
|
||||
<select :value="longTextStrategy"
|
||||
@change="updateLongTextStrategy($event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<option value="attachment">转为附件(共用上传管线)</option>
|
||||
<option value="chunk">分块连续发送</option>
|
||||
<option value="error">直接返回错误</option>
|
||||
</select>
|
||||
<label v-if="longTextStrategy === 'attachment'" class="mt-2 block text-xs text-gray-600 dark:text-gray-400">生成格式
|
||||
<select :value="resolvedFilePaste.temp_file_type" @change="updateTempFileType($event.target.value)" class="ml-2 border rounded px-2 py-1 bg-white dark:bg-gray-700">
|
||||
<option value="txt">TXT(推荐,保留原文)</option><option value="pdf">PDF</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label v-if="resolvedFilePaste.temp_file_type !== 'chunk'" class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
{{ resolvedFilePaste.temp_file_type === 'error' ? '错误信息' : '引导文本' }}
|
||||
</label>
|
||||
<input v-if="resolvedFilePaste.temp_file_type !== 'chunk'"
|
||||
type="text"
|
||||
:value="resolvedFilePaste.temp_file_type === 'txt' ? resolvedFilePaste.txt_hint_text : (resolvedFilePaste.temp_file_type === 'pdf' ? resolvedFilePaste.pdf_hint_text : resolvedFilePaste.error_hint_text)"
|
||||
@input="updateHintText($event.target.value)"
|
||||
:placeholder="resolvedFilePaste.temp_file_type === 'error' ? '超过阈值时返回给客户端的错误信息' : '粘贴文件后追加的文字,留空则不追加'"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<div v-else class="min-h-[38px] flex items-center rounded-md border border-blue-200 dark:border-blue-800 bg-blue-50/70 dark:bg-blue-900/20 px-3 py-2 text-xs leading-5 text-blue-700 dark:text-blue-300">
|
||||
自动使用最少块数,并把分块说明计入阈值。
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
|
||||
</div>
|
||||
|
||||
<details class="cap-technical"><summary><span><strong>上传后的输入适配</strong><small>只有文件上传后输入框发生变化时再设置。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">上传后稳定等待</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.post_upload_settle"
|
||||
@input="updateNumberField('post_upload_settle', $event.target.value, 0)"
|
||||
min="0"
|
||||
max="30"
|
||||
step="0.5"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div><label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.reacquire_input_after_upload"
|
||||
@change="updateBooleanField('reacquire_input_after_upload', $event.target.checked)">
|
||||
<span>上传完成后重新定位输入框</span>
|
||||
</label>
|
||||
|
||||
<div >
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">上传后输入框的位置(选择器)</label>
|
||||
<input type="text"
|
||||
:value="resolvedFilePaste.post_upload_input_selector"
|
||||
@input="updateTextField('post_upload_input_selector', $event.target.value)"
|
||||
placeholder=".composer textarea"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
</div>
|
||||
</div></details></div></details></section>
|
||||
|
||||
<details class="cap-troubleshoot"><summary><span><strong>附件上传了,但没有发出去?</strong><small>排查发送确认、重试和网页识别规则。正常发送时无需调整。</small></span><span class="cap-summary-value">敏感度:{{ attachmentSensitivityMeta.label }}</span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><p class="cap-inline-help">这些规则会影响所有附件。先确认网页上是否真的发出了消息,再调整等待或重试。</p>
|
||||
|
||||
<div class="mt-3 grid grid-cols-1 md:grid-cols-3 gap-3 items-start">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">敏感度</label>
|
||||
<select :value="resolvedFilePaste.send_confirmation.attachment_sensitivity"
|
||||
@change="updateSendConfirmationField('attachment_sensitivity', $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<option v-for="option in attachmentSensitivityOptions"
|
||||
:key="option.value"
|
||||
:value="option.value">
|
||||
{{ option.label }}
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="md:col-span-2 text-xs leading-6 text-gray-600 dark:text-gray-300 bg-white/70 dark:bg-gray-900/40 rounded-lg border border-blue-100 dark:border-blue-900/60 px-3 py-2">
|
||||
{{ attachmentSensitivityMeta.description }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-1 md:grid-cols-4 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">最大重试次数</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.send_confirmation.max_retry_count"
|
||||
@input="updateSendConfirmationField('max_retry_count', parseInt($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="10"
|
||||
step="1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">次</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">重试间隔</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.send_confirmation.retry_interval"
|
||||
@input="updateSendConfirmationField('retry_interval', parseFloat($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="30"
|
||||
step="0.1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">最小冷却窗</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.send_confirmation.retry_cooldown_window"
|
||||
@input="updateSendConfirmationField('retry_cooldown_window', parseFloat($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="30"
|
||||
step="0.1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">重试前短探测</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.send_confirmation.pre_retry_probe_window"
|
||||
@input="updateSendConfirmationField('pre_retry_probe_window', parseFloat($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="5"
|
||||
step="0.05"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">自动重试动作</label>
|
||||
<select :value="resolvedFilePaste.send_confirmation.retry_action"
|
||||
@change="updateSendConfirmationField('retry_action', $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<option value="click_send_btn">点击发送按钮</option>
|
||||
<option value="key_press">按键发送</option>
|
||||
</select>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
某些站点二次点击会把“发送”变成“停止”,这时更适合改成按键发送。
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">重试按键组合</label>
|
||||
<input type="text"
|
||||
:value="resolvedFilePaste.send_confirmation.retry_key_combo"
|
||||
@input="updateSendConfirmationField('retry_key_combo', $event.target.value)"
|
||||
placeholder="Enter / Ctrl+Enter"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
仅在“按键发送”时生效,支持 Enter、Ctrl+Enter、Shift+Enter 等组合。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 border-t border-blue-100 dark:border-blue-900/60 pt-4"
|
||||
:class="sectionCollapsed.advancedRules ? '' : 'space-y-4'">
|
||||
<div class="cursor-pointer select-none -m-2 p-2 rounded-md hover:bg-blue-100/50 dark:hover:bg-blue-900/30 transition-colors" role="button" tabindex="0" :aria-expanded="!sectionCollapsed.advancedRules" @keydown.enter.prevent="toggleSection('advancedRules')" @keydown.space.prevent="toggleSection('advancedRules')" @click="toggleSection('advancedRules')">
|
||||
<div class="flex items-center gap-2 text-sm font-medium text-gray-800 dark:text-gray-100">
|
||||
<span class="w-4 inline-flex justify-center text-gray-400 dark:text-gray-500" v-html="sectionCollapsed.advancedRules ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<span>高级附件规则</span>
|
||||
<span v-show="sectionCollapsed.advancedRules" class="text-xs font-normal text-gray-400 dark:text-gray-500">(点击展开)</span>
|
||||
</div>
|
||||
<p v-show="!sectionCollapsed.advancedRules" class="mt-1 text-xs leading-5 text-gray-600 dark:text-gray-300">
|
||||
像 Gemini 这类站点,可以在这里补发送按钮灰态 token、附件预览 selector 和 pending 文案。即使文件粘贴没开,这块也会继续影响图片上传和发送前的附件 gate。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.attachment_monitor.require_attachment_present"
|
||||
@change="updateAttachmentMonitorField('require_attachment_present', $event.target.checked)">
|
||||
<span>发送前必须看到附件已挂上页面</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.attachment_monitor.require_upload_signal_before_ready"
|
||||
@change="updateAttachmentMonitorField('require_upload_signal_before_ready', $event.target.checked)">
|
||||
<span>没有观察到上传启动前,不允许判定 ready</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.attachment_monitor.continue_once_on_unconfirmed_send"
|
||||
@change="updateAttachmentMonitorField('continue_once_on_unconfirmed_send', $event.target.checked)">
|
||||
<span>未确认时仍允许继续点一次发送</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.send_confirmation.retry_on_unconfirmed_send"
|
||||
@change="updateSendConfirmationField('retry_on_unconfirmed_send', $event.target.checked)">
|
||||
<span>发送未确认时允许自动重试</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.send_confirmation.retry_block_on_stop_button"
|
||||
@change="updateSendConfirmationField('retry_block_on_stop_button', $event.target.checked)">
|
||||
<span>发送按钮变成 stop 时禁止重试</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.send_confirmation.retry_block_if_generating"
|
||||
@change="updateSendConfirmationField('retry_block_if_generating', $event.target.checked)">
|
||||
<span>页面进入生成态时禁止重试</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.send_confirmation.accept_attachment_change"
|
||||
@change="updateSendConfirmationField('accept_attachment_change', $event.target.checked)">
|
||||
<span>发送后附件区发生变化时可视为已接受</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.send_confirmation.accept_attachment_disappear"
|
||||
@change="updateSendConfirmationField('accept_attachment_disappear', $event.target.checked)">
|
||||
<span>发送后附件区消失时可视为已接受</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.send_confirmation.accept_probe_confirmation"
|
||||
@change="updateSendConfirmationField('accept_probe_confirmation', $event.target.checked)">
|
||||
<span>允许 JS probe 直接确认发送成功</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">空闲超时</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.attachment_monitor.idle_timeout"
|
||||
@input="updateAttachmentMonitorField('idle_timeout', parseFloat($event.target.value) || 8)"
|
||||
min="0.5"
|
||||
max="60"
|
||||
step="0.5"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">附件最长等待</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedFilePaste.attachment_monitor.hard_max_wait"
|
||||
@input="updateAttachmentMonitorField('hard_max_wait', parseFloat($event.target.value) || 90)"
|
||||
min="1"
|
||||
max="300"
|
||||
step="1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">附件预览 selector</label>
|
||||
<textarea
|
||||
:value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.attachment_selectors ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('attachment_selectors', $event.target.value)"
|
||||
rows="5"
|
||||
placeholder="[class*='attachment'] .upload-preview"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">每行一个 selector,选择独立附件卡片,不要选择包含输入框的大容器;嵌套图片不会重复计数。</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">上传中 selector</label>
|
||||
<textarea
|
||||
:value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.pending_selectors ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('pending_selectors', $event.target.value)"
|
||||
rows="5"
|
||||
placeholder="[aria-busy='true'] .uploading"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">每行一个 selector,命中后会继续等待,不会急着发送。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">忙碌文本 / token</label>
|
||||
<textarea
|
||||
:value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.busy_text_markers ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('busy_text_markers', $event.target.value)"
|
||||
rows="5"
|
||||
placeholder="uploading 处理中 解析中"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">只匹配附件状态提示和发送按钮,不扫描提示词、文件名或文件预览正文。</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">发送按钮灰态 token</label>
|
||||
<textarea
|
||||
:value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.send_button_disabled_markers ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('send_button_disabled_markers', $event.target.value)"
|
||||
rows="5"
|
||||
placeholder="is-disabled cursor-not-allowed upload failed"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">填发送按钮 class / title / aria-label 里会出现的关键字,命中后视为按钮不可发。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300">附件状态提示区域(可选)
|
||||
<textarea :value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.status_selectors ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('status_selectors', $event.target.value)" rows="3" placeholder=".attachment-status"
|
||||
class="mt-1 w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700"></textarea>
|
||||
<span class="block mt-1 text-xs font-normal text-gray-500">只选择显示“读取中 / 上传中”等状态的小区域,不要选择整张卡片或输入框。</span>
|
||||
</label>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300">不参与附件检测的内容区域(可选)
|
||||
<textarea :value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.content_exclusion_selectors ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('content_exclusion_selectors', $event.target.value)" rows="3" placeholder=".document-preview-content"
|
||||
class="mt-1 w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700"></textarea>
|
||||
<span class="block mt-1 text-xs font-normal text-gray-500">补充站点特有的正文镜像或文件内容预览区域;隐藏内容、输入框和常见文件名区域已自动排除。</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">忽略忙碌文本 / token</label>
|
||||
<textarea
|
||||
:value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.ignored_busy_text_markers ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('ignored_busy_text_markers', $event.target.value)"
|
||||
rows="3"
|
||||
placeholder="thinking"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">仅用于排除站点特有的状态词。正文与文件名会自动排除,不需要在这里逐个添加。</p>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">根容器 selector</label>
|
||||
<textarea
|
||||
:value="attachmentMonitorDrafts ? (attachmentMonitorDrafts.root_selectors ?? '') : ''"
|
||||
@input="updateAttachmentMonitorListField('root_selectors', $event.target.value)"
|
||||
rows="4"
|
||||
placeholder=".composer-shell .input-area"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">当通用根容器猜错时再填。这里会限制附件节点和 pending 节点的查找范围。</p>
|
||||
</div>
|
||||
|
||||
<div v-show="!sectionCollapsed.advancedRules" class="border-t border-blue-100 dark:border-blue-900/60 pt-4 space-y-3">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-800 dark:text-gray-100">JS 状态探针</div>
|
||||
<p class="mt-1 text-xs leading-5 text-gray-600 dark:text-gray-300">
|
||||
探针会收到一个参数对象,包含 stage 和 monitorState。返回结构建议包含 uploading、ready、accepted、confirmed、retry、shouldRetry、summary 这些字段。
|
||||
</p>
|
||||
</div>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="resolvedFilePaste.state_probe.enabled"
|
||||
@change="updateStateProbeField('enabled', $event.target.checked)">
|
||||
<span>启用</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">探针代码</label>
|
||||
<textarea
|
||||
:value="resolvedFilePaste.state_probe.code"
|
||||
@input="updateStateProbeField('code', $event.target.value)"
|
||||
rows="10"
|
||||
placeholder="return (() => { const { stage, monitorState } = arguments[0] || {}; return { accepted: false, shouldRetry: false, summary: stage }; })();"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div></details>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,749 @@
|
||||
// ==================== 多模态提取配置面板 ====================
|
||||
|
||||
window.ImageConfigPanel = {
|
||||
name: 'ImageConfigPanel',
|
||||
props: {
|
||||
imageConfig: { type: Object, required: true },
|
||||
currentDomain: { type: String, default: null },
|
||||
collapsed: { type: Boolean, default: true }
|
||||
},
|
||||
emits: ['update:collapsed', 'update-image-config', 'reload-config'],
|
||||
data() {
|
||||
return {
|
||||
showPresetMenu: false,
|
||||
availablePresets: [],
|
||||
currentPreset: null,
|
||||
loadingPresets: false,
|
||||
imagePresetRequestSeq: 0,
|
||||
srcAllowPatternsDraft: '',
|
||||
audioNetworkUrlPatternsDraft: ''
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
modalityPolicies() {
|
||||
return {
|
||||
image: this.normalizeModalityPolicy('image', (this.imageConfig.modalities || {}).image),
|
||||
audio: this.normalizeModalityPolicy('audio', (this.imageConfig.modalities || {}).audio),
|
||||
video: this.normalizeModalityPolicy('video', (this.imageConfig.modalities || {}).video)
|
||||
};
|
||||
},
|
||||
modalities() {
|
||||
return {
|
||||
image: !!this.modalityPolicies.image.enabled,
|
||||
audio: !!this.modalityPolicies.audio.enabled,
|
||||
video: !!this.modalityPolicies.video.enabled
|
||||
};
|
||||
},
|
||||
isEnabled() {
|
||||
return ['image', 'audio', 'video'].some(key => !!this.modalities[key]);
|
||||
},
|
||||
enabledLabels() {
|
||||
const labels = [];
|
||||
if (this.modalities.image) labels.push('图片');
|
||||
if (this.modalities.audio) labels.push('音频');
|
||||
if (this.modalities.video) labels.push('视频');
|
||||
return labels;
|
||||
},
|
||||
srcAllowPatternsText() {
|
||||
const patterns = Array.isArray(this.imageConfig.src_allow_patterns)
|
||||
? this.imageConfig.src_allow_patterns
|
||||
: [];
|
||||
return patterns.join('\n');
|
||||
},
|
||||
audioNetworkCapture() {
|
||||
return {
|
||||
enabled: false,
|
||||
timeout_seconds: 2.5,
|
||||
transport: 'page_websocket_probe',
|
||||
url_patterns: ['voicegenie', 'speech', 'audio', 'tts'],
|
||||
// 修复:默认值与后端 get_default_*(voicegenie_binary_stream)对齐
|
||||
extractor: 'voicegenie_binary_stream',
|
||||
settle_seconds: 0.35,
|
||||
max_payload_bytes: 10 * 1024 * 1024,
|
||||
...((this.imageConfig && this.imageConfig.audio_network_capture) || {})
|
||||
};
|
||||
},
|
||||
audioNetworkMaxPayloadMb() {
|
||||
const raw = Number(this.audioNetworkCapture.max_payload_bytes || 0);
|
||||
const fallback = Number(this.imageConfig.max_size_mb || 10);
|
||||
if (!Number.isFinite(raw) || raw <= 0) return fallback;
|
||||
return Math.round((raw / 1024 / 1024) * 10) / 10;
|
||||
},
|
||||
audioNetworkUrlPatternsText() {
|
||||
const patterns = Array.isArray(this.audioNetworkCapture.url_patterns)
|
||||
? this.audioNetworkCapture.url_patterns
|
||||
: [];
|
||||
return patterns.join('\n');
|
||||
},
|
||||
audioCaptureEnabled() {
|
||||
return this.imageConfig.audio_capture_enabled !== false;
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
imageConfig: {
|
||||
handler() {
|
||||
this.syncDraftsFromProps();
|
||||
},
|
||||
deep: true,
|
||||
immediate: true
|
||||
},
|
||||
currentDomain(newVal) {
|
||||
this.imagePresetRequestSeq += 1;
|
||||
this.currentPreset = null;
|
||||
if (newVal) this.checkCurrentPreset();
|
||||
this.syncDraftsFromProps(true);
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.loadPresets();
|
||||
if (this.currentDomain) this.checkCurrentPreset();
|
||||
this.syncDraftsFromProps(true);
|
||||
},
|
||||
methods: {
|
||||
mediaPolicyLabel(type) {
|
||||
const labels = { disabled: '不提取', generic_only: '读取现成媒体', on_signal: '发现媒体信号时提取', probe_if_trigger_found: '发现播放入口后探测', always_probe: '每次主动探测' };
|
||||
return labels[this.modalityPolicies[type].run_policy] || this.modalityPolicies[type].run_policy;
|
||||
},
|
||||
buildAuthHeaders(extraHeaders = {}) {
|
||||
const token = String(window.getDashboardAuthToken ? window.getDashboardAuthToken() : '').trim();
|
||||
const headers = { ...extraHeaders };
|
||||
if (token) {
|
||||
headers['Authorization'] = 'Bearer ' + token;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
|
||||
toggle() {
|
||||
this.$emit('update:collapsed', !this.collapsed);
|
||||
},
|
||||
|
||||
buildNextConfig(patch = {}) {
|
||||
const nextModalities = {
|
||||
...this.modalityPolicies
|
||||
};
|
||||
if (patch && patch.modalities && typeof patch.modalities === 'object') {
|
||||
for (const type of ['image', 'audio', 'video']) {
|
||||
if (Object.prototype.hasOwnProperty.call(patch.modalities, type)) {
|
||||
nextModalities[type] = this.normalizeModalityPolicy(
|
||||
type,
|
||||
patch.modalities[type],
|
||||
nextModalities[type]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
const next = {
|
||||
...this.imageConfig,
|
||||
...patch,
|
||||
modalities: nextModalities
|
||||
};
|
||||
next.enabled = ['image', 'audio', 'video'].some(key => !!(next.modalities[key] && next.modalities[key].enabled));
|
||||
return next;
|
||||
},
|
||||
|
||||
updateField(field, value) {
|
||||
const newConfig = this.buildNextConfig({ [field]: value });
|
||||
this.$emit('update-image-config', newConfig);
|
||||
},
|
||||
|
||||
numberOrFallback(value, fallback) {
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
},
|
||||
|
||||
defaultModalityPolicy(type, enabled = false) {
|
||||
const base = {
|
||||
enabled: !!enabled,
|
||||
run_policy: enabled ? 'on_signal' : 'disabled',
|
||||
quick_probe_timeout_seconds: 1.0
|
||||
};
|
||||
if (type === 'audio') {
|
||||
return {
|
||||
...base,
|
||||
run_policy: enabled ? 'probe_if_trigger_found' : 'disabled',
|
||||
capture_timeout_seconds: 12.0
|
||||
};
|
||||
}
|
||||
if (type === 'video') {
|
||||
return {
|
||||
...base,
|
||||
late_wait_timeout_seconds: 90.0
|
||||
};
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
late_wait_timeout_seconds: 45.0,
|
||||
blind_wait_timeout_seconds: 1.0
|
||||
};
|
||||
},
|
||||
|
||||
normalizeModalityPolicy(type, value, fallback = null) {
|
||||
const current = fallback || this.defaultModalityPolicy(type, false);
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) {
|
||||
const enabled = !!value.enabled;
|
||||
const allowedPolicies = ['disabled', 'generic_only', 'on_signal', 'probe_if_trigger_found', 'always_probe'];
|
||||
let runPolicy = String(value.run_policy || current.run_policy || '').trim();
|
||||
if (!allowedPolicies.includes(runPolicy)) {
|
||||
runPolicy = enabled ? this.defaultModalityPolicy(type, true).run_policy : 'disabled';
|
||||
}
|
||||
if (!enabled) {
|
||||
runPolicy = 'disabled';
|
||||
}
|
||||
return {
|
||||
...this.defaultModalityPolicy(type, enabled),
|
||||
...current,
|
||||
...value,
|
||||
enabled,
|
||||
run_policy: runPolicy
|
||||
};
|
||||
}
|
||||
return this.defaultModalityPolicy(type, !!value);
|
||||
},
|
||||
|
||||
updateModalityPolicy(type, patch = {}) {
|
||||
const current = this.modalityPolicies[type] || this.defaultModalityPolicy(type, false);
|
||||
const nextPolicy = this.normalizeModalityPolicy(type, { ...current, ...(patch || {}) }, current);
|
||||
this.updateField('modalities', {
|
||||
...this.modalityPolicies,
|
||||
[type]: nextPolicy
|
||||
});
|
||||
},
|
||||
|
||||
parsePatternLines(text) {
|
||||
return String(text || '')
|
||||
.split(/\r?\n/)
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean);
|
||||
},
|
||||
|
||||
syncDraftsFromProps(force = false) {
|
||||
const srcArr = Array.isArray(this.imageConfig?.src_allow_patterns)
|
||||
? this.imageConfig.src_allow_patterns
|
||||
: [];
|
||||
const curSrcArr = this.parsePatternLines(this.srcAllowPatternsDraft);
|
||||
if (force || JSON.stringify(srcArr) !== JSON.stringify(curSrcArr) || this.srcAllowPatternsDraft === undefined || this.srcAllowPatternsDraft === null) {
|
||||
this.srcAllowPatternsDraft = srcArr.join('\n');
|
||||
}
|
||||
|
||||
const audioArr = Array.isArray(this.audioNetworkCapture?.url_patterns)
|
||||
? this.audioNetworkCapture.url_patterns
|
||||
: [];
|
||||
const curAudioArr = this.parsePatternLines(this.audioNetworkUrlPatternsDraft);
|
||||
if (force || JSON.stringify(audioArr) !== JSON.stringify(curAudioArr) || this.audioNetworkUrlPatternsDraft === undefined || this.audioNetworkUrlPatternsDraft === null) {
|
||||
this.audioNetworkUrlPatternsDraft = audioArr.join('\n');
|
||||
}
|
||||
},
|
||||
|
||||
updateSrcAllowPatterns(text) {
|
||||
this.srcAllowPatternsDraft = text;
|
||||
const patterns = this.parsePatternLines(text);
|
||||
this.updateField('src_allow_patterns', patterns);
|
||||
},
|
||||
|
||||
updateAudioNetworkCapture(patch = {}) {
|
||||
const nextConfig = {
|
||||
...this.audioNetworkCapture,
|
||||
...(patch || {})
|
||||
};
|
||||
this.updateField('audio_network_capture', nextConfig);
|
||||
},
|
||||
|
||||
updateAudioNetworkUrlPatterns(text) {
|
||||
this.audioNetworkUrlPatternsDraft = text;
|
||||
const patterns = this.parsePatternLines(text);
|
||||
this.updateAudioNetworkCapture({ url_patterns: patterns });
|
||||
},
|
||||
|
||||
toggleModality(type) {
|
||||
const enabled = !this.modalities[type];
|
||||
this.updateModalityPolicy(type, {
|
||||
enabled,
|
||||
run_policy: enabled ? this.defaultModalityPolicy(type, true).run_policy : 'disabled'
|
||||
});
|
||||
},
|
||||
|
||||
modalityCardClass(type) {
|
||||
return this.modalities[type]
|
||||
? 'border-blue-400 bg-blue-50 dark:bg-blue-900/20 dark:border-blue-500/50'
|
||||
: 'border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-900/40';
|
||||
},
|
||||
|
||||
inputWrapClass(enabled) {
|
||||
return enabled ? '' : 'opacity-50';
|
||||
},
|
||||
|
||||
async loadPresets() {
|
||||
if (this.loadingPresets) return;
|
||||
this.loadingPresets = true;
|
||||
try {
|
||||
const response = await fetch('/api/image-presets', {
|
||||
headers: this.buildAuthHeaders()
|
||||
});
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.detail || ('HTTP ' + response.status));
|
||||
}
|
||||
const data = await response.json();
|
||||
this.availablePresets = data.presets || [];
|
||||
} catch (e) {
|
||||
console.error('加载预设失败:', e);
|
||||
} finally {
|
||||
this.loadingPresets = false;
|
||||
}
|
||||
},
|
||||
|
||||
async checkCurrentPreset() {
|
||||
const domain = String(this.currentDomain || '').trim();
|
||||
const requestSeq = Number(this.imagePresetRequestSeq || 0) + 1;
|
||||
this.imagePresetRequestSeq = requestSeq;
|
||||
if (!domain) {
|
||||
this.currentPreset = null;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/api/sites/' + encodeURIComponent(domain) + '/image-preset', {
|
||||
headers: this.buildAuthHeaders()
|
||||
});
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.detail || ('HTTP ' + response.status));
|
||||
}
|
||||
const data = await response.json();
|
||||
if (requestSeq !== this.imagePresetRequestSeq || String(this.currentDomain || '').trim() !== domain) {
|
||||
return;
|
||||
}
|
||||
this.currentPreset = data.available ? data : null;
|
||||
} catch (e) {
|
||||
if (requestSeq !== this.imagePresetRequestSeq || String(this.currentDomain || '').trim() !== domain) {
|
||||
return;
|
||||
}
|
||||
console.error('读取当前图片预设失败:', e);
|
||||
this.currentPreset = null;
|
||||
}
|
||||
},
|
||||
|
||||
async applyPreset(presetDomain) {
|
||||
if (!this.currentDomain) return;
|
||||
try {
|
||||
const response = await fetch('/api/sites/' + encodeURIComponent(this.currentDomain) + '/apply-image-preset', {
|
||||
method: 'POST',
|
||||
headers: this.buildAuthHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ preset_domain: presetDomain })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.detail || ('HTTP ' + response.status));
|
||||
}
|
||||
|
||||
this.showPresetMenu = false;
|
||||
this.$emit('reload-config');
|
||||
await this.checkCurrentPreset();
|
||||
} catch (e) {
|
||||
alert('应用预设失败: ' + e.message);
|
||||
}
|
||||
},
|
||||
|
||||
togglePresetMenu(e) {
|
||||
e.stopPropagation();
|
||||
this.showPresetMenu = !this.showPresetMenu;
|
||||
if (this.showPresetMenu && this.availablePresets.length === 0) {
|
||||
this.loadPresets();
|
||||
}
|
||||
},
|
||||
|
||||
closeMenu() {
|
||||
this.showPresetMenu = false;
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="cap-panel cap-media-panel bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm" @click="closeMenu">
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="toggle">
|
||||
<div class="flex items-center gap-2 flex-wrap">
|
||||
<span class="w-4 inline-flex justify-center text-gray-500 dark:text-gray-400" v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">更改会自动保存</h3>
|
||||
<span v-if="isEnabled" class="px-2 py-0.5 text-xs bg-green-100 dark:bg-green-900/50 text-green-700 dark:text-green-300 rounded font-medium">已启用</span>
|
||||
<span v-else class="px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 rounded">未启用</span>
|
||||
<span v-for="label in enabledLabels" :key="label"
|
||||
class="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded font-medium">
|
||||
{{ label }}
|
||||
</span>
|
||||
<span v-if="currentPreset && currentPreset.available"
|
||||
class="px-2 py-0.5 text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded font-medium flex items-center gap-1">
|
||||
<svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path d="M10 2a6 6 0 00-6 6v3.586l-.707.707A1 1 0 004 14h12a1 1 0 00.707-1.707L16 11.586V8a6 6 0 00-6-6zM10 18a3 3 0 01-3-3h6a3 3 0 01-3 3z"/></svg>
|
||||
预设
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2" @click.stop>
|
||||
<div class="relative">
|
||||
<button @click="togglePresetMenu"
|
||||
class="px-3 py-1.5 text-sm font-medium text-gray-700 dark:text-gray-200 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center gap-1">
|
||||
<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
|
||||
</svg>
|
||||
站点规则模板
|
||||
</button>
|
||||
|
||||
<div v-if="showPresetMenu" class="absolute right-0 mt-1 w-80 max-h-96 overflow-y-auto bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-lg z-10">
|
||||
<div v-if="currentPreset && currentPreset.available" class="px-3 py-2 bg-blue-50 dark:bg-blue-900/30 border-b dark:border-gray-700 text-xs text-blue-700 dark:text-blue-300">
|
||||
<div class="font-medium">当前使用的媒体规则模板</div>
|
||||
<div class="mt-0.5">{{ currentPreset.name }}</div>
|
||||
</div>
|
||||
<div v-if="loadingPresets" class="px-3 py-6 text-center text-sm text-gray-400">加载中...</div>
|
||||
<div v-else-if="availablePresets.length > 0" class="divide-y dark:divide-gray-700">
|
||||
<div class="px-3 py-1.5 bg-gray-50 dark:bg-gray-900/50 text-xs font-medium text-gray-500">站点预设</div>
|
||||
<button v-for="preset in availablePresets" :key="preset.domain"
|
||||
@click="applyPreset(preset.domain)"
|
||||
class="w-full text-left px-3 py-2.5 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors">
|
||||
<div class="font-medium text-sm text-gray-900 dark:text-white truncate">{{ preset.name }}</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">{{ preset.domain }}</div>
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="px-3 py-6 text-center text-sm text-gray-400">暂无可用预设</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!collapsed" class="p-4 space-y-4">
|
||||
<div>
|
||||
|
||||
<div class="cap-feature-stack">
|
||||
<section class="cap-card" :class="{ 'is-enabled': modalities.image }" aria-label="接收图片"><div class="cap-card-header"><span class="cap-icon" v-html="$icons.photo"></span><div class="cap-copy"><div class="cap-title-row"><h4>接收图片</h4><span class="cap-scope">当前预设</span></div><p>把 AI 回复里的图片带回客户端。</p></div><label class="cap-switch"><span class="cap-state" :class="{ 'is-on': modalities.image }">{{ modalities.image ? '已开启' : '已关闭' }}</span><input role="switch" aria-label="接收图片" type="checkbox" :checked="modalities.image" @change="toggleModality('image')" class="cap-switch-input"><i aria-hidden="true"></i></label></div><p v-if="modalities.image" class="cap-facts">{{ modalities.image ? '当前方式:' + mediaPolicyLabel('image') : '已关闭,不提取这类媒体' }}</p><details class="cap-settings"><summary><span><strong>配置图片提取</strong><small>识别位置与提取时机</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><p class="cap-inline-help">开启上方开关后,可调整识别位置与提取方式。关闭不会清空识别位置和等待参数。</p><div class="cap-form-grid"><div :class="inputWrapClass(modalities.image)">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">图片选择器</label>
|
||||
<input type="text" :value="imageConfig.selector" @input="updateField('selector', $event.target.value)" placeholder="img"
|
||||
:disabled="!modalities.image"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">默认 <code>img</code></p>
|
||||
</div><div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">什么时候提取</label>
|
||||
<select :disabled="!modalities.image" :value="modalityPolicies.image.run_policy"
|
||||
@change="updateModalityPolicy('image', { run_policy: $event.target.value, enabled: $event.target.value !== 'disabled' })"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
|
||||
<option value="disabled">不提取</option>
|
||||
<option value="generic_only">只读取现成的媒体</option>
|
||||
<option value="on_signal">发现媒体信号时提取</option>
|
||||
<!-- 修复:补齐后端 MODALITY_RUN_POLICY_VALUES 的第 5 个枚举 -->
|
||||
<option value="probe_if_trigger_found">发现播放入口后探测</option>
|
||||
<option value="always_probe">每次主动探测</option>
|
||||
</select>
|
||||
</div></div><details class="cap-technical"><summary><span><strong>提取不完整或等待太久?</strong><small>调整等待时间与特殊站点的兼容规则。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div class="cap-form-grid">
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">快速查找时长(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.image.quick_probe_timeout_seconds"
|
||||
@input="updateModalityPolicy('image', { quick_probe_timeout_seconds: numberOrFallback($event.target.value, 1) })"
|
||||
min="0.1" max="10" step="0.1"
|
||||
:disabled="!modalities.image"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">最长等待(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.image.late_wait_timeout_seconds"
|
||||
@input="updateModalityPolicy('image', { late_wait_timeout_seconds: numberOrFallback($event.target.value, 45) })"
|
||||
min="0.2" max="300" step="1"
|
||||
:disabled="!modalities.image || modalityPolicies.image.run_policy === 'generic_only'"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2">
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">没有加载提示时等待(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.image.blind_wait_timeout_seconds"
|
||||
@input="updateModalityPolicy('image', { blind_wait_timeout_seconds: numberOrFallback($event.target.value, 1) })"
|
||||
min="0" max="300" step="0.5"
|
||||
:disabled="!modalities.image || modalityPolicies.image.run_policy === 'generic_only'"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
<div :class="inputWrapClass(modalities.image)">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">图片来源白名单 <span class="text-gray-400 font-normal">(可选)</span></label>
|
||||
<textarea :value="srcAllowPatternsDraft" @input="updateSrcAllowPatterns($event.target.value)" rows="5"
|
||||
placeholder="^data:image/ ^blob: ^https?://[^/]*oaiusercontent\.com/ ^https?://[^/]*oaistatic\.com/ ^https?://cdn\.openai\.com/"
|
||||
:disabled="!modalities.image"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">每行一个正则,仅提取匹配这些 <code>src</code> 的图片。留空表示不过滤。</p>
|
||||
</div><div :class="inputWrapClass(modalities.image)" class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Canvas 导出格式</label>
|
||||
<select :value="imageConfig.canvas_export_mime || 'image/jpeg'"
|
||||
@change="updateField('canvas_export_mime', $event.target.value)"
|
||||
:disabled="!modalities.image"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<option value="image/jpeg">JPEG</option>
|
||||
<option value="image/webp">WebP</option>
|
||||
<option value="image/png">PNG</option>
|
||||
</select>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">用于 blob 图片 Canvas 兜底导出。JPEG/WebP 体积更小。</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Canvas 导出质量</label>
|
||||
<input type="number"
|
||||
:value="imageConfig.canvas_export_quality === undefined ? 0.88 : imageConfig.canvas_export_quality"
|
||||
@input="updateField('canvas_export_quality', numberOrFallback($event.target.value, 0.88))"
|
||||
min="0.1" max="1" step="0.01"
|
||||
:disabled="!modalities.image || (imageConfig.canvas_export_mime || 'image/jpeg') === 'image/png'"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">仅 JPEG/WebP 生效,建议 0.80-0.92。</p>
|
||||
</div>
|
||||
</div></div></details></div></details></section>
|
||||
|
||||
<section class="cap-card" :class="{ 'is-enabled': modalities.audio }" aria-label="接收音频"><div class="cap-card-header"><span class="cap-icon" v-html="$icons.activity"></span><div class="cap-copy"><div class="cap-title-row"><h4>接收音频</h4><span class="cap-scope">当前预设</span></div><p>把 AI 回复里的声音文件带回客户端。</p></div><label class="cap-switch"><span class="cap-state" :class="{ 'is-on': modalities.audio }">{{ modalities.audio ? '已开启' : '已关闭' }}</span><input role="switch" aria-label="接收音频" type="checkbox" :checked="modalities.audio" @change="toggleModality('audio')" class="cap-switch-input"><i aria-hidden="true"></i></label></div><p v-if="modalities.audio" class="cap-facts">{{ modalities.audio ? '当前方式:' + mediaPolicyLabel('audio') : '已关闭,不提取这类媒体' }}</p><details class="cap-settings"><summary><span><strong>配置音频提取</strong><small>识别位置与提取时机</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><p class="cap-inline-help">开启上方开关后,可调整识别位置与提取方式。关闭不会清空识别位置和等待参数。</p><div class="cap-form-grid"><div :class="inputWrapClass(modalities.audio)">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">音频选择器</label>
|
||||
<input type="text" :value="imageConfig.audio_selector" @input="updateField('audio_selector', $event.target.value)" placeholder="audio, audio source"
|
||||
:disabled="!modalities.audio"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">默认 <code>audio, audio source</code></p>
|
||||
</div><div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">什么时候提取</label>
|
||||
<select :disabled="!modalities.audio" :value="modalityPolicies.audio.run_policy"
|
||||
@change="updateModalityPolicy('audio', { run_policy: $event.target.value, enabled: $event.target.value !== 'disabled' })"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
|
||||
<option value="disabled">不提取</option>
|
||||
<option value="generic_only">只读取现成的媒体</option>
|
||||
<option value="on_signal">发现媒体信号时提取</option>
|
||||
<option value="probe_if_trigger_found">发现播放入口后探测</option>
|
||||
<option value="always_probe">每次主动探测</option>
|
||||
</select>
|
||||
</div></div><details class="cap-technical"><summary><span><strong>提取不完整或等待太久?</strong><small>调整等待时间与特殊站点的兼容规则。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div class="cap-form-grid">
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">快速查找时长(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.audio.quick_probe_timeout_seconds"
|
||||
@input="updateModalityPolicy('audio', { quick_probe_timeout_seconds: numberOrFallback($event.target.value, 1) })"
|
||||
min="0.1" max="10" step="0.1"
|
||||
:disabled="!modalities.audio"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">最长录制时间(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.audio.capture_timeout_seconds"
|
||||
@input="updateModalityPolicy('audio', { capture_timeout_seconds: numberOrFallback($event.target.value, 12) })"
|
||||
min="0.2" max="180" step="0.5"
|
||||
:disabled="!modalities.audio || !['probe_if_trigger_found', 'always_probe', 'on_signal'].includes(modalityPolicies.audio.run_policy)"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
</div>
|
||||
<details class="cap-technical"><summary><span><strong>没有音频文件时,尝试捕获声音</strong><small>可能触发页面播放或录音;Gemini 直连提取预设应保持播放录音回退关闭。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div v-if="modalities.audio" class="border-t dark:border-gray-700 pt-4">
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">音频捕获</div>
|
||||
|
||||
<div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg mb-3">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300">页面播放音频捕获回退</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">直接提取不到音频时,允许触发页面播放并录制音频。Gemini 直连提取预设应保持关闭。</div>
|
||||
</div>
|
||||
<label class="toggle-label scale-90">
|
||||
<input type="checkbox" aria-label="允许播放并录制音频" :checked="audioCaptureEnabled" @change="updateField('audio_capture_enabled', $event.target.checked)" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300">启用网络音频捕获</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">优先尝试从页面内 WebSocket / 网络流直接提取音频;是否继续回退到页面录音由上方开关控制。</div>
|
||||
</div>
|
||||
<label class="toggle-label scale-90">
|
||||
<input type="checkbox" aria-label="从网络捕获音频" :checked="audioNetworkCapture.enabled" @change="updateAudioNetworkCapture({ enabled: $event.target.checked })" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div :class="['mt-4 space-y-4', audioNetworkCapture.enabled ? '' : 'opacity-50']">
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">捕获超时 (秒)</label>
|
||||
<input type="number"
|
||||
:value="audioNetworkCapture.timeout_seconds"
|
||||
@input="updateAudioNetworkCapture({ timeout_seconds: numberOrFallback($event.target.value, 2.5) })"
|
||||
min="0.1" max="15" step="0.1"
|
||||
:disabled="!audioNetworkCapture.enabled"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">传输类型</label>
|
||||
<select :value="audioNetworkCapture.transport"
|
||||
@change="updateAudioNetworkCapture({ transport: $event.target.value })"
|
||||
:disabled="!audioNetworkCapture.enabled"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<option value="page_websocket_probe">页面 WebSocket Probe</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">提取器</label>
|
||||
<select :value="audioNetworkCapture.extractor"
|
||||
@change="updateAudioNetworkCapture({ extractor: $event.target.value })"
|
||||
:disabled="!audioNetworkCapture.enabled"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<option value="voicegenie_ogg_pages">voicegenie_ogg_pages</option>
|
||||
<!-- 修复:补齐后端合法枚举,否则已存该值的预设会渲染成空白 -->
|
||||
<option value="voicegenie_binary_stream">voicegenie_binary_stream</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">稳定等待窗口 (秒)</label>
|
||||
<input type="number"
|
||||
:value="audioNetworkCapture.settle_seconds"
|
||||
@input="updateAudioNetworkCapture({ settle_seconds: numberOrFallback($event.target.value, 0.35) })"
|
||||
min="0.05" max="5" step="0.05"
|
||||
:disabled="!audioNetworkCapture.enabled"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">单条载荷上限 (MB)</label>
|
||||
<input type="number"
|
||||
:value="audioNetworkMaxPayloadMb"
|
||||
@input="updateAudioNetworkCapture({ max_payload_bytes: Math.round(numberOrFallback($event.target.value, 10) * 1024 * 1024) })"
|
||||
min="0.1" max="100" step="0.5"
|
||||
:disabled="!audioNetworkCapture.enabled"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">超过上限的二进制帧只记录摘要,不回传 Base64。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">URL 匹配关键字</label>
|
||||
<textarea :value="audioNetworkUrlPatternsDraft"
|
||||
@input="updateAudioNetworkUrlPatterns($event.target.value)"
|
||||
rows="4"
|
||||
:disabled="!audioNetworkCapture.enabled"
|
||||
placeholder="voicegenie speech audio tts"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed"></textarea>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">每行一个关键字,命中对应 WebSocket / 网络请求 URL 时才会参与音频聚合。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div></div></details></div></details></div></details></section>
|
||||
|
||||
<section class="cap-card" :class="{ 'is-enabled': modalities.video }" aria-label="接收视频"><div class="cap-card-header"><span class="cap-icon" v-html="$icons.play"></span><div class="cap-copy"><div class="cap-title-row"><h4>接收视频</h4><span class="cap-scope">当前预设</span></div><p>把 AI 回复里的视频文件带回客户端。</p></div><label class="cap-switch"><span class="cap-state" :class="{ 'is-on': modalities.video }">{{ modalities.video ? '已开启' : '已关闭' }}</span><input role="switch" aria-label="接收视频" type="checkbox" :checked="modalities.video" @change="toggleModality('video')" class="cap-switch-input"><i aria-hidden="true"></i></label></div><p v-if="modalities.video" class="cap-facts">{{ modalities.video ? '当前方式:' + mediaPolicyLabel('video') : '已关闭,不提取这类媒体' }}</p><details class="cap-settings"><summary><span><strong>配置视频提取</strong><small>识别位置与提取时机</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><p class="cap-inline-help">开启上方开关后,可调整识别位置与提取方式。关闭不会清空识别位置和等待参数。</p><div class="cap-form-grid"><div :class="inputWrapClass(modalities.video)">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">视频选择器</label>
|
||||
<input type="text" :value="imageConfig.video_selector" @input="updateField('video_selector', $event.target.value)" placeholder="video, video source"
|
||||
:disabled="!modalities.video"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent disabled:cursor-not-allowed">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">默认 <code>video, video source</code></p>
|
||||
</div><div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">什么时候提取</label>
|
||||
<select :disabled="!modalities.video" :value="modalityPolicies.video.run_policy"
|
||||
@change="updateModalityPolicy('video', { run_policy: $event.target.value, enabled: $event.target.value !== 'disabled' })"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
|
||||
<option value="disabled">不提取</option>
|
||||
<option value="generic_only">只读取现成的媒体</option>
|
||||
<option value="on_signal">发现媒体信号时提取</option>
|
||||
<!-- 修复:补齐后端 MODALITY_RUN_POLICY_VALUES 的第 5 个枚举 -->
|
||||
<option value="probe_if_trigger_found">发现播放入口后探测</option>
|
||||
<option value="always_probe">每次主动探测</option>
|
||||
</select>
|
||||
</div></div><details class="cap-technical"><summary><span><strong>提取不完整或等待太久?</strong><small>调整等待时间与特殊站点的兼容规则。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div class="cap-form-grid">
|
||||
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">快速查找时长(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.video.quick_probe_timeout_seconds"
|
||||
@input="updateModalityPolicy('video', { quick_probe_timeout_seconds: numberOrFallback($event.target.value, 1) })"
|
||||
min="0.1" max="10" step="0.1"
|
||||
:disabled="!modalities.video"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400 mb-1">最长等待(秒)</label>
|
||||
<input type="number"
|
||||
:value="modalityPolicies.video.late_wait_timeout_seconds"
|
||||
@input="updateModalityPolicy('video', { late_wait_timeout_seconds: numberOrFallback($event.target.value, 90) })"
|
||||
min="0.2" max="300" step="1"
|
||||
:disabled="!modalities.video || modalityPolicies.video.run_policy === 'generic_only'"
|
||||
class="w-full border dark:border-gray-600 px-2 py-1.5 rounded-md text-xs bg-white dark:bg-gray-700 text-gray-900 dark:text-white disabled:opacity-50">
|
||||
</div>
|
||||
</div>
|
||||
</div></details></div></details></section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!isEnabled" class="bg-gray-50 dark:bg-gray-900/50 border border-gray-200 dark:border-gray-700 rounded-lg p-3 text-center">
|
||||
<div class="text-gray-500 dark:text-gray-400 text-sm">当前只处理文字回复;需要接收图片、声音或视频时,再开启对应能力。</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<details class="cap-troubleshoot"><summary><span><strong>通用识别与下载规则</strong><small>范围、文件大小和资源转换。现有提取正常时无需改动。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"> <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">容器选择器 <span class="text-gray-400 font-normal">(可选)</span></label>
|
||||
<input type="text" :value="imageConfig.container_selector || ''" @input="updateField('container_selector', $event.target.value || null)" placeholder="留空则使用响应容器"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">统一限定媒体查找范围</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">提取模式</label>
|
||||
<select :value="imageConfig.mode" @change="updateField('mode', $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<option value="all">全部提取</option>
|
||||
<option value="first">仅第一项</option>
|
||||
<option value="last">仅最后一项</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">最大大小 (MB)</label>
|
||||
<!-- 修复:后端取值域是连续区间 1..100,原下拉只有 5/10/20/50,存 100 的预设会渲染空白并被砍到 ≤50 -->
|
||||
<input type="number" :value="imageConfig.max_size_mb"
|
||||
@input="updateField('max_size_mb', numberOrFallback($event.target.value, 10))"
|
||||
min="1" max="100" step="1"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">防抖延迟 (秒)</label>
|
||||
<!-- 修复:parseFloat("0") || 2 恒为 2,用户输 0 关防抖会被写成 2 秒;后端下限是 0 -->
|
||||
<input type="number" :value="imageConfig.debounce_seconds" @input="updateField('debounce_seconds', numberOrFallback($event.target.value, 2))" min="0" max="30" step="0.5"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">加载超时时间 (秒)</label>
|
||||
<input type="number" :value="imageConfig.load_timeout_seconds" @input="updateField('load_timeout_seconds', parseFloat($event.target.value) || 5)"
|
||||
min="1" max="60" step="1" :disabled="!imageConfig.wait_for_load"
|
||||
:class="['w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent', !imageConfig.wait_for_load ? 'opacity-50 cursor-not-allowed' : '']">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="border-t dark:border-gray-700 pt-4">
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">高级选项</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300">等待媒体加载</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">等待音视频或图片完成加载后再提取</div>
|
||||
</div>
|
||||
<label class="toggle-label scale-90">
|
||||
<input type="checkbox" aria-label="等待媒体加载完成" :checked="imageConfig.wait_for_load" @change="updateField('wait_for_load', $event.target.checked)" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
<div class="flex items-center justify-between p-3 bg-gray-50 dark:bg-gray-900/50 rounded-lg">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300">转换 Blob 媒体</div>
|
||||
<div class="text-xs text-gray-500 dark:text-gray-400">将 blob: 资源转为可返回的数据 URI 或本地文件</div>
|
||||
</div>
|
||||
<label class="toggle-label scale-90">
|
||||
<input type="checkbox" aria-label="转换临时媒体资源" :checked="imageConfig.download_blobs" @change="updateField('download_blobs', $event.target.checked)" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div></details> </div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,388 @@
|
||||
/* Scoped transfers: importing never writes the server or touches another site. */
|
||||
(() => {
|
||||
const copy = (x) => JSON.parse(JSON.stringify(x));
|
||||
const object = (x) => !!x && typeof x === "object" && !Array.isArray(x);
|
||||
const safeName = (x) =>
|
||||
typeof x === "string" &&
|
||||
!!x.trim() &&
|
||||
x.length <= 100 &&
|
||||
!["__proto__", "prototype", "constructor"].includes(x);
|
||||
function sources(data, fallbackDomain) {
|
||||
if (!object(data))
|
||||
throw Error("请选择站点或预设 JSON 文件,不是动作数组。");
|
||||
if (data.kind === "workflow")
|
||||
throw Error("这是工作流片段。请在「请求工作流 → 导入工作流」中使用它。");
|
||||
const result = [];
|
||||
const add = (domain, site) => {
|
||||
if (!object(site)) return;
|
||||
const presets = object(site.presets)
|
||||
? site.presets
|
||||
: "workflow" in site || "selectors" in site
|
||||
? { [site.preset_name || "主预设"]: site }
|
||||
: null;
|
||||
if (!presets) return;
|
||||
const clean = {};
|
||||
for (const [name, config] of Object.entries(presets)) {
|
||||
if (!safeName(name) || !object(config))
|
||||
throw Error("文件中存在无效的预设名称或配置对象。");
|
||||
if ("workflow" in config && !Array.isArray(config.workflow))
|
||||
throw Error(name + " 的 workflow 必须是数组。");
|
||||
if ("selectors" in config && !object(config.selectors))
|
||||
throw Error(name + " 的 selectors 必须是对象。");
|
||||
const value = copy(config);
|
||||
if (!object(site.presets)) {
|
||||
delete value.domain;
|
||||
delete value.preset_name;
|
||||
}
|
||||
Object.defineProperty(clean, name, {
|
||||
value,
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
if (Object.keys(clean).length)
|
||||
result.push({
|
||||
domain: domain || fallbackDomain,
|
||||
presets: clean,
|
||||
settings: object(site.presets)
|
||||
? Object.fromEntries(
|
||||
Object.entries(site).filter(
|
||||
([k]) =>
|
||||
![
|
||||
"presets",
|
||||
"default_preset",
|
||||
"domain",
|
||||
"preset_name",
|
||||
"format",
|
||||
"version",
|
||||
].includes(k) &&
|
||||
!k.startsWith("_") &&
|
||||
safeName(k),
|
||||
),
|
||||
)
|
||||
: {},
|
||||
});
|
||||
};
|
||||
if (data.format === "universal-web-api/preset" && object(data.config))
|
||||
add(data.domain, {
|
||||
presets: { [data.preset_name || "主预设"]: data.config },
|
||||
});
|
||||
else if ("presets" in data || "workflow" in data || "selectors" in data)
|
||||
add(data.domain, data);
|
||||
else
|
||||
for (const [domain, site] of Object.entries(data))
|
||||
if (!domain.startsWith("_")) add(domain, site);
|
||||
if (!result.length)
|
||||
throw Error("没有找到可导入的站点预设。请选择站点配置或单预设文件。");
|
||||
return result;
|
||||
}
|
||||
window.PresetTransferSupport = { sources, safeName, copy };
|
||||
window.PresetTransfer = {
|
||||
name: "PresetTransfer",
|
||||
props: {
|
||||
domain: String,
|
||||
site: Object,
|
||||
preset: String,
|
||||
prepare: Function,
|
||||
disabled: Boolean,
|
||||
},
|
||||
emits: ["apply"],
|
||||
data: () => ({
|
||||
open: false,
|
||||
mode: "preset",
|
||||
fileName: "",
|
||||
sourceSites: [],
|
||||
sourceIndex: 0,
|
||||
sourcePreset: "",
|
||||
targetName: "",
|
||||
overwrite: false,
|
||||
includeSettings: false,
|
||||
busy: false,
|
||||
error: "",
|
||||
message: "",
|
||||
generation: 0,
|
||||
requestAbort: null,
|
||||
}),
|
||||
computed: {
|
||||
source() {
|
||||
return this.sourceSites[this.sourceIndex] || null;
|
||||
},
|
||||
names() {
|
||||
return Object.keys(this.source?.presets || {});
|
||||
},
|
||||
existing() {
|
||||
return this.site?.presets || { 主预设: this.site };
|
||||
},
|
||||
conflicts() {
|
||||
return this.names.filter((n) => Object.hasOwn(this.existing, n));
|
||||
},
|
||||
importCount() {
|
||||
return this.mode === "preset"
|
||||
? this.sourcePreset
|
||||
? 1
|
||||
: 0
|
||||
: this.names.filter(
|
||||
(n) => this.overwrite || !Object.hasOwn(this.existing, n),
|
||||
).length;
|
||||
},
|
||||
},
|
||||
beforeUnmount() {
|
||||
this.requestAbort?.abort();
|
||||
this.generation++;
|
||||
},
|
||||
watch: {
|
||||
domain() {
|
||||
this.reset();
|
||||
this.open = false;
|
||||
this.message = "";
|
||||
},
|
||||
sourceIndex() {
|
||||
this.selectSource();
|
||||
},
|
||||
sourcePreset() {
|
||||
if (this.mode === "preset") this.suggestName();
|
||||
},
|
||||
},
|
||||
methods: {
|
||||
trapFocus(e) {
|
||||
const items = [
|
||||
...e.currentTarget.querySelectorAll(
|
||||
"button:not(:disabled),input:not(:disabled),select:not(:disabled)",
|
||||
),
|
||||
].filter((n) => n.offsetParent !== null);
|
||||
if (e.shiftKey && document.activeElement === items[0]) {
|
||||
e.preventDefault();
|
||||
items.at(-1)?.focus();
|
||||
} else if (!e.shiftKey && document.activeElement === items.at(-1)) {
|
||||
e.preventDefault();
|
||||
items[0]?.focus();
|
||||
}
|
||||
},
|
||||
reset() {
|
||||
this.requestAbort?.abort();
|
||||
this.generation++;
|
||||
this.fileName = "";
|
||||
this.sourceSites = [];
|
||||
this.error = "";
|
||||
this.busy = false;
|
||||
this.sourcePreset = "";
|
||||
this.targetName = "";
|
||||
this.overwrite = false;
|
||||
this.includeSettings = false;
|
||||
},
|
||||
launch(mode) {
|
||||
this.reset();
|
||||
this.mode = mode;
|
||||
this.open = true;
|
||||
this.$refs.menu.open = false;
|
||||
this.$nextTick(() => this.$refs.choose.focus());
|
||||
},
|
||||
close() {
|
||||
this.requestAbort?.abort();
|
||||
this.generation++;
|
||||
this.open = false;
|
||||
this.busy = false;
|
||||
this.$nextTick(() => this.$refs.menu.querySelector("summary").focus());
|
||||
},
|
||||
suggestName() {
|
||||
let name = this.sourcePreset || "导入预设";
|
||||
if (Object.hasOwn(this.existing, name)) {
|
||||
const base = name.slice(0, 86) + " · 导入";
|
||||
name = base;
|
||||
let i = 2;
|
||||
while (Object.hasOwn(this.existing, name)) name = base + " " + i++;
|
||||
}
|
||||
this.targetName = name;
|
||||
},
|
||||
selectSource() {
|
||||
this.sourcePreset = this.names[0] || "";
|
||||
this.suggestName();
|
||||
},
|
||||
async read(event) {
|
||||
const file = event.target.files[0];
|
||||
event.target.value = "";
|
||||
if (!file) return;
|
||||
const generation = ++this.generation;
|
||||
this.error = "";
|
||||
try {
|
||||
if (file.size > 4 * 1024 * 1024)
|
||||
throw Error("配置文件不能超过 4 MiB。");
|
||||
const data = JSON.parse(await file.text());
|
||||
if (generation !== this.generation) return;
|
||||
this.sourceSites = sources(data, this.domain);
|
||||
this.sourceIndex = Math.max(
|
||||
0,
|
||||
this.sourceSites.findIndex((s) => s.domain === this.domain),
|
||||
);
|
||||
this.fileName = file.name;
|
||||
this.selectSource();
|
||||
} catch (e) {
|
||||
if (generation === this.generation) {
|
||||
this.sourceSites = [];
|
||||
this.fileName = "";
|
||||
this.error = e.message || "文件无法读取";
|
||||
}
|
||||
}
|
||||
},
|
||||
async validate(config) {
|
||||
const headers = { "Content-Type": "application/json" },
|
||||
token = window.getDashboardAuthToken?.();
|
||||
if (token) headers.Authorization = "Bearer " + token;
|
||||
const controller = new AbortController();
|
||||
this.requestAbort = controller;
|
||||
const timeout = setTimeout(() => controller.abort(), 30000);
|
||||
try {
|
||||
const response = await fetch("/api/workflow/validate", {
|
||||
method: "POST",
|
||||
headers,
|
||||
signal: controller.signal,
|
||||
body: JSON.stringify({ workflow: config.workflow || [] }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok)
|
||||
throw Error(
|
||||
typeof result.detail === "string"
|
||||
? result.detail
|
||||
: "工作流校验失败",
|
||||
);
|
||||
} catch (e) {
|
||||
if (e.name === "AbortError")
|
||||
throw Error("校验已取消或超过 30 秒,请稍后再试。");
|
||||
throw e;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
if (this.requestAbort === controller) this.requestAbort = null;
|
||||
}
|
||||
},
|
||||
async apply() {
|
||||
if (!this.source || this.busy) return;
|
||||
const domain = this.domain,
|
||||
generation = this.generation;
|
||||
this.error = "";
|
||||
try {
|
||||
const updates = {};
|
||||
if (this.mode === "preset") {
|
||||
const name = this.targetName.trim();
|
||||
if (!safeName(name)) throw Error("请输入 1–100 字的有效预设名称。");
|
||||
if (
|
||||
Object.hasOwn(this.existing, name) &&
|
||||
!confirm(
|
||||
"将替换当前站点的「" +
|
||||
name +
|
||||
"」预设。其他预设不变,是否继续?",
|
||||
)
|
||||
)
|
||||
return;
|
||||
updates[name] = copy(this.source.presets[this.sourcePreset]);
|
||||
} else {
|
||||
for (const n of this.names)
|
||||
if (this.overwrite || !Object.hasOwn(this.existing, n))
|
||||
updates[n] = copy(this.source.presets[n]);
|
||||
if (
|
||||
this.overwrite &&
|
||||
this.conflicts.length &&
|
||||
!confirm(
|
||||
"将覆盖 " +
|
||||
this.conflicts.length +
|
||||
" 个同名预设,其他预设保留。继续?",
|
||||
)
|
||||
)
|
||||
return;
|
||||
}
|
||||
if (!Object.keys(updates).length)
|
||||
throw Error(
|
||||
"没有可导入的预设。同名预设默认跳过,可选择覆盖或改为导入单个预设。",
|
||||
);
|
||||
this.busy = true;
|
||||
for (const config of Object.values(updates)) {
|
||||
if (domain !== this.domain || generation !== this.generation)
|
||||
return;
|
||||
await this.validate(config);
|
||||
}
|
||||
if (domain !== this.domain || generation !== this.generation) return;
|
||||
this.prepare?.();
|
||||
this.$emit("apply", {
|
||||
domain,
|
||||
presets: updates,
|
||||
settings:
|
||||
this.mode === "site" && this.includeSettings
|
||||
? copy(this.source.settings)
|
||||
: null,
|
||||
select: this.mode === "preset" ? this.targetName.trim() : null,
|
||||
});
|
||||
this.message =
|
||||
"已导入 " +
|
||||
Object.keys(updates).length +
|
||||
" 个预设为草稿,请点击「保存配置」。";
|
||||
this.close();
|
||||
} catch (e) {
|
||||
if (generation === this.generation) this.error = e.message;
|
||||
} finally {
|
||||
if (generation === this.generation) this.busy = false;
|
||||
}
|
||||
},
|
||||
download(scope) {
|
||||
this.prepare?.();
|
||||
const site = copy(this.site || {}),
|
||||
preset = this.preset;
|
||||
let payload, file;
|
||||
if (scope === "preset") {
|
||||
const config =
|
||||
site.presets?.[preset] || (!site.presets ? site : null);
|
||||
if (!config) {
|
||||
this.message = "当前预设不存在,请重新选择。";
|
||||
return;
|
||||
}
|
||||
payload = {
|
||||
domain: this.domain,
|
||||
default_preset: preset,
|
||||
presets: { [preset]: config },
|
||||
};
|
||||
file = this.domain + "__" + preset + "__preset.json";
|
||||
} else {
|
||||
payload = { ...site, domain: this.domain };
|
||||
file = this.domain + "__site.json";
|
||||
}
|
||||
const url = URL.createObjectURL(
|
||||
new Blob([JSON.stringify(payload, null, 2)], {
|
||||
type: "application/json",
|
||||
}),
|
||||
),
|
||||
a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = file.replace(/[\\/:*?"<>|]/g, "_");
|
||||
a.click();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||
this.$refs.menu.open = false;
|
||||
this.message =
|
||||
scope === "preset"
|
||||
? "已导出当前预设「" + preset + "」,不含其他预设和站点级设置。"
|
||||
: "已导出本站点全部预设与站点级设置。";
|
||||
},
|
||||
},
|
||||
template: `<div class="preset-transfer">
|
||||
<details ref="menu" class="preset-more transfer-menu"><summary class="preset-btn" :aria-disabled="disabled" @click="disabled && $event.preventDefault()"><span v-html="$icons.arrowUpTray"></span>导入 / 导出<span v-html="$icons.chevronDown"></span></summary>
|
||||
<div class="preset-more-pop"><div class="transfer-menu-caption">当前站点 · {{ domain }}</div>
|
||||
<button type="button" @click="launch('preset')"><span v-html="$icons.documentArrowDown"></span><span>导入一个预设<small>新建一份,或明确选择替换</small></span></button>
|
||||
<button type="button" @click="launch('site')"><span v-html="$icons.folderOpen"></span><span>合并站点配置<small>从文件导入本站点的多套预设</small></span></button>
|
||||
<hr class="preset-more-sep">
|
||||
<button type="button" @click="download('preset')"><span v-html="$icons.arrowUpTray"></span><span>导出当前预设<small>仅「{{ preset }}」,方便分享与迁移</small></span></button>
|
||||
<button type="button" @click="download('site')"><span v-html="$icons.globe"></span><span>导出整个站点<small>全部预设 + 站点级设置</small></span></button>
|
||||
</div>
|
||||
</details>
|
||||
<div v-if="message" class="transfer-feedback" role="status">{{ message }}<button type="button" @click="message=''" aria-label="关闭导入导出提示">×</button></div>
|
||||
<teleport to="body"><div v-if="open" class="preset-transfer-overlay" @click.self="close()" @keydown.esc.stop="close()">
|
||||
<section class="preset-transfer-dialog" role="dialog" aria-modal="true" aria-labelledby="preset-transfer-title" @keydown.tab="trapFocus">
|
||||
<header><div><span class="transfer-kicker">导入到当前站点</span><h3 id="preset-transfer-title">{{ mode==='preset'?'导入一个预设':'合并站点配置' }}</h3><p>{{ domain }} · 不会影响其他站点</p></div><button type="button" @click="close" aria-label="关闭导入对话框">×</button></header>
|
||||
<div class="transfer-body"><button ref="choose" type="button" class="transfer-file" @click="$refs.file.click()" :disabled="busy"><span v-html="$icons.documentArrowDown"></span><strong>{{ fileName || '选择配置 JSON 文件' }}</strong><small>支持单预设、单站点和多站点文件 · 最大 4 MiB</small></button><input ref="file" type="file" accept=".json,application/json" hidden @change="read">
|
||||
<template v-if="source"><label v-if="sourceSites.length>1">从文件选择来源站点<select v-model.number="sourceIndex" :disabled="busy"><option v-for="(s,i) in sourceSites" :value="i">{{ s.domain }} · {{ Object.keys(s.presets).length }} 个预设</option></select></label><p v-if="source.domain!==domain" class="transfer-note">来源 {{ source.domain }} → 导入到 {{ domain }}。请确认定位器适用于当前站点。</p>
|
||||
<template v-if="mode==='preset'"><label>文件中的预设<select v-model="sourcePreset" :disabled="busy"><option v-for="n in names" :value="n">{{ n }}</option></select></label><label>在本站点保存为<input v-model="targetName" maxlength="100" :disabled="busy"></label><p class="transfer-note">{{ Object.hasOwn(existing,targetName.trim())?'将替换同名预设;确认时会再次提醒。':'将新建预设;现有预设和默认选择均保持不变。' }}</p></template>
|
||||
<template v-else><div class="transfer-preview"><strong>{{ names.length }} 个来源预设 · {{ conflicts.length }} 个同名</strong><div v-for="n in names"><span>{{ n }}</span><small>{{ conflicts.includes(n)?(overwrite?'将覆盖':'保留已有,跳过'):'新增' }}</small></div></div><label class="transfer-check"><input type="checkbox" v-model="overwrite" :disabled="busy">覆盖同名预设(默认保留已有)</label><label v-if="Object.keys(source.settings).length" class="transfer-check"><input type="checkbox" v-model="includeSettings" :disabled="busy">同时导入站点级设置</label><p class="transfer-note">保留其他已有预设,不改变默认预设。{{ includeSettings?'文件中的站点级字段将替换当前同名字段。':'站点级设置保持不变。' }}</p></template>
|
||||
</template><p v-if="error" class="transfer-error" role="alert">{{ error }}</p>
|
||||
</div><footer><span>先校验并载入草稿,再由你保存。</span><button type="button" @click="close">取消</button><button type="button" class="transfer-primary" @click="apply" :disabled="busy||!source||!importCount">{{ busy?'校验中…':'导入为草稿' }}</button></footer>
|
||||
</section>
|
||||
</div></teleport>
|
||||
</div>`,
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,180 @@
|
||||
// ==================== 提示词开头注入面板 ====================
|
||||
|
||||
window.PromptPaddingPanel = {
|
||||
name: 'PromptPaddingPanel',
|
||||
props: {
|
||||
promptPaddingConfig: { type: Object, required: true },
|
||||
currentDomain: { type: String, default: null },
|
||||
selectedPreset: { type: String, default: null },
|
||||
collapsed: { type: Boolean, default: true }
|
||||
},
|
||||
emits: ['update:collapsed'],
|
||||
data() {
|
||||
return {
|
||||
defaultPromptPadding: {
|
||||
enabled: false,
|
||||
marker_text: '测试号,无实际意义',
|
||||
segments_per_side: 12,
|
||||
random_insert_enabled: false,
|
||||
random_insert_chars: ''
|
||||
}
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
resolvedPromptPadding() {
|
||||
const raw = this.promptPaddingConfig || {};
|
||||
return {
|
||||
...this.defaultPromptPadding,
|
||||
...raw
|
||||
};
|
||||
},
|
||||
currentPresetLabel() {
|
||||
return String(this.selectedPreset || '').trim() || '主预设';
|
||||
},
|
||||
statusText() {
|
||||
return (this.resolvedPromptPadding.enabled || this.resolvedPromptPadding.random_insert_enabled)
|
||||
? '已启用'
|
||||
: '未启用';
|
||||
},
|
||||
markerPreview() {
|
||||
const markerText = String(this.resolvedPromptPadding.marker_text || '').trim();
|
||||
const segmentCount = Math.max(0, parseInt(this.resolvedPromptPadding.segments_per_side, 10) || 0);
|
||||
if (segmentCount === 0) {
|
||||
return markerText || '不注入内容';
|
||||
}
|
||||
if (!markerText) {
|
||||
return '随机片段';
|
||||
}
|
||||
if (markerText.endsWith(':') || markerText.endsWith(':')) {
|
||||
return markerText + '随机片段';
|
||||
}
|
||||
return markerText + ':随机片段';
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
toggle() {
|
||||
this.$emit('update:collapsed', !this.collapsed);
|
||||
},
|
||||
|
||||
getMutablePromptPadding() {
|
||||
return this.promptPaddingConfig || {};
|
||||
},
|
||||
|
||||
toggleEnabled() {
|
||||
const cfg = this.getMutablePromptPadding();
|
||||
cfg.enabled = !this.resolvedPromptPadding.enabled;
|
||||
},
|
||||
|
||||
updateMarkerText(value) {
|
||||
this.getMutablePromptPadding().marker_text = String(value || '');
|
||||
},
|
||||
|
||||
updateSegmentsPerSide(value) {
|
||||
const parsed = parseInt(value, 10);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
return;
|
||||
}
|
||||
this.getMutablePromptPadding().segments_per_side = Math.max(0, Math.min(parsed, 64));
|
||||
},
|
||||
|
||||
toggleRandomInsertEnabled() {
|
||||
const cfg = this.getMutablePromptPadding();
|
||||
cfg.random_insert_enabled = !this.resolvedPromptPadding.random_insert_enabled;
|
||||
},
|
||||
|
||||
updateRandomInsertChars(value) {
|
||||
this.getMutablePromptPadding().random_insert_chars = String(value || '');
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="cap-panel cap-padding-panel bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm">
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="toggle">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="w-4 inline-flex justify-center text-gray-500 dark:text-gray-400" v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">特殊输入适配</h3>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">({{ statusText }})</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="!collapsed" class="p-4"><details class="cap-troubleshoot"><summary><span><strong>特殊站点:调整提示词</strong><small>会在原消息中加入额外内容,普通对话通常无需修改。</small></span><span class="cap-summary-value">{{ resolvedPromptPadding.enabled || resolvedPromptPadding.random_insert_enabled ? '有功能已开启' : '未开启' }}</span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><p class="cap-warning">随机插入字符会改变原文。处理代码、结构化数据或需要精确措辞时请谨慎使用。</p>
|
||||
|
||||
|
||||
<div class="rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50/60 dark:bg-gray-900/30 p-4 space-y-4">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-800 dark:text-gray-100">发送前在开头追加随机占位片段</div>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400 leading-5">
|
||||
开启后,只在提示词开头追加一段随机片段,不改动后面的原始消息主体。修改会跟随当前站点配置一起保存。
|
||||
</p>
|
||||
</div>
|
||||
<label class="toggle-label scale-90 flex-shrink-0">
|
||||
<input type="checkbox" aria-label="启用开头占位片段" :checked="resolvedPromptPadding.enabled" @change="toggleEnabled" class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">开头片段数</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="resolvedPromptPadding.segments_per_side"
|
||||
@input="updateSegmentsPerSide($event.target.value)"
|
||||
min="0"
|
||||
max="64"
|
||||
step="1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm text-right bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">个</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">说明文本</label>
|
||||
<input type="text"
|
||||
:value="resolvedPromptPadding.marker_text"
|
||||
@input="updateMarkerText($event.target.value)"
|
||||
placeholder="留空则只追加随机片段"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg border border-slate-200 dark:border-slate-700 bg-white/80 dark:bg-slate-900/40 px-4 py-3">
|
||||
<div class="text-sm font-medium text-gray-800 dark:text-gray-100">发送效果</div>
|
||||
<p class="mt-1 text-xs leading-5 text-gray-500 dark:text-gray-400">
|
||||
实际发送时,会在提示词开头生成一段类似
|
||||
<code class="font-mono">{{ markerPreview }}</code>
|
||||
的文本。随机片段会混合数字和单字符字母,尽量贴近当前需求的样式。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-gray-200 dark:border-gray-700 pt-4 space-y-3">
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-800 dark:text-gray-100">提示词内随机插入一个字符</div>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400 leading-5">
|
||||
每次发送时,从候选字符中随机选择一个,并插入到用户提示词的随机位置。
|
||||
</p>
|
||||
</div>
|
||||
<label class="toggle-label scale-90 flex-shrink-0">
|
||||
<input type="checkbox"
|
||||
aria-label="在提示词中随机插入字符" :checked="resolvedPromptPadding.random_insert_enabled"
|
||||
@change="toggleRandomInsertEnabled"
|
||||
class="sr-only peer">
|
||||
<div class="toggle-bg"></div>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">候选字符</label>
|
||||
<input type="text"
|
||||
:value="resolvedPromptPadding.random_insert_chars"
|
||||
@input="updateRandomInsertChars($event.target.value)"
|
||||
placeholder="例如:abc123※☆"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">候选框中的每个字符都有机会被选中;留空时不会插入。</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div></details></div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,508 @@
|
||||
// ==================== 选择器管理面板 ====================
|
||||
|
||||
window.SelectorPanel = {
|
||||
name: 'SelectorPanel',
|
||||
props: {
|
||||
selectors: { type: Object, required: true },
|
||||
collapsed: { type: Boolean, default: true }
|
||||
},
|
||||
emits: [
|
||||
'update:collapsed',
|
||||
'add-selector',
|
||||
'remove-selector',
|
||||
'update-selector-key',
|
||||
'update-selector-value',
|
||||
'test-selector'
|
||||
],
|
||||
data() {
|
||||
return {
|
||||
showMenu: false,
|
||||
fieldQuery: '',
|
||||
fieldFilter: 'all',
|
||||
editingSelectorKey: '',
|
||||
expandedField: 'input_box',
|
||||
auxiliaryExpanded: false,
|
||||
guideExpanded: false,
|
||||
openRenameKey: '',
|
||||
renameDrafts: {},
|
||||
coreSelectorKeys: ['input_box', 'send_btn', 'result_container']
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
count() {
|
||||
return Object.keys(this.selectors || {}).length;
|
||||
},
|
||||
|
||||
selectorEntries() {
|
||||
const query = this.fieldQuery.trim().toLowerCase();
|
||||
return Object.entries(this.selectors || {}).filter(([key, value]) => {
|
||||
// Keep the active field mounted while typing, even when its value stops matching.
|
||||
if (key === this.editingSelectorKey) return true;
|
||||
if (this.fieldFilter === 'core' && !this.coreSelectorKeys.includes(key)) return false;
|
||||
if (this.fieldFilter === 'empty' && this.isSelectorFilled(key)) return false;
|
||||
const meta = this.getSelectorMeta(key);
|
||||
return !query || [key, value, meta.title, meta.description].join(' ').toLowerCase().includes(query);
|
||||
});
|
||||
},
|
||||
|
||||
selectorGroups() {
|
||||
return [
|
||||
{ id: 'core', title: '核心定位', note: '一次对话的三个关键位置', entries: this.selectorEntries.filter(([key]) => this.coreSelectorKeys.includes(key)) },
|
||||
{ id: 'auxiliary', title: '辅助与扩展', note: '对话管理、上传入口及自定义字段', entries: this.selectorEntries.filter(([key]) => !this.coreSelectorKeys.includes(key)) }
|
||||
];
|
||||
},
|
||||
coreChecklist() {
|
||||
return this.coreSelectorKeys.map(key => ({
|
||||
key,
|
||||
...this.getSelectorMeta(key),
|
||||
ready: this.isSelectorFilled(key)
|
||||
}));
|
||||
},
|
||||
|
||||
coreReadyCount() {
|
||||
return this.coreChecklist.filter(item => item.ready).length;
|
||||
},
|
||||
|
||||
missingQuickAdds() {
|
||||
return this.coreChecklist.filter(item => !Object.prototype.hasOwnProperty.call(this.selectors || {}, item.key));
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
selectors() {
|
||||
this.fieldQuery = '';
|
||||
this.fieldFilter = 'all';
|
||||
this.editingSelectorKey = '';
|
||||
this.expandedField = Object.prototype.hasOwnProperty.call(this.selectors || {}, 'input_box') ? 'input_box' : Object.keys(this.selectors || {})[0] || '';
|
||||
this.auxiliaryExpanded = false;
|
||||
this.closeRenameEditor();
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
openCoreField(key) {
|
||||
this.fieldFilter = 'all'; this.fieldQuery = '';
|
||||
if (!Object.prototype.hasOwnProperty.call(this.selectors || {}, key)) {
|
||||
this.addSelector(key);
|
||||
return;
|
||||
}
|
||||
this.expandedField = key;
|
||||
this.$nextTick(() => {
|
||||
const field = document.getElementById('selector-expression-' + key);
|
||||
if (field) { field.focus({ preventScroll: true }); field.scrollIntoView({ block: 'nearest' }); }
|
||||
});
|
||||
},
|
||||
toggle() {
|
||||
this.$emit('update:collapsed', !this.collapsed);
|
||||
},
|
||||
|
||||
toggleMenu(e) {
|
||||
e.stopPropagation();
|
||||
this.showMenu = !this.showMenu;
|
||||
},
|
||||
|
||||
addSelector(type) {
|
||||
this.showMenu = false;
|
||||
const previous = Object.keys(this.selectors || {});
|
||||
this.$emit('add-selector', type);
|
||||
this.$nextTick(() => {
|
||||
const key = Object.keys(this.selectors || {}).find(key => !previous.includes(key));
|
||||
if (!key) return;
|
||||
this.fieldFilter = 'all'; this.fieldQuery = '';
|
||||
this.expandedField = key;
|
||||
this.auxiliaryExpanded = !this.coreSelectorKeys.includes(key);
|
||||
});
|
||||
},
|
||||
|
||||
closeMenu() {
|
||||
this.showMenu = false;
|
||||
},
|
||||
|
||||
openInNewTab(url) {
|
||||
const target = String(url || '').trim();
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
window.open(target, '_blank', 'noopener,noreferrer');
|
||||
},
|
||||
|
||||
openTutorial(anchor = 'selector-basics') {
|
||||
this.openInNewTab('/static/tutorial/index.html#' + encodeURIComponent(anchor));
|
||||
},
|
||||
|
||||
openPracticeLab() {
|
||||
this.openInNewTab('/static/selector-practice.html');
|
||||
},
|
||||
|
||||
isSelectorFilled(key) {
|
||||
return String((this.selectors || {})[key] || '').trim().length > 0;
|
||||
},
|
||||
|
||||
isBuiltInSelectorKey(key) {
|
||||
return [
|
||||
'input_box',
|
||||
'send_btn',
|
||||
'result_container',
|
||||
'new_chat_btn',
|
||||
'message_wrapper',
|
||||
'generating_indicator',
|
||||
'retry_send_btn',
|
||||
'upload_btn',
|
||||
'file_input',
|
||||
'drop_zone',
|
||||
'composer_root'
|
||||
].includes(String(key || '').trim());
|
||||
},
|
||||
|
||||
canRenameSelectorKey(key) {
|
||||
return !this.isBuiltInSelectorKey(key);
|
||||
},
|
||||
|
||||
openRenameEditor(key) {
|
||||
this.openRenameKey = key;
|
||||
this.renameDrafts = {
|
||||
...this.renameDrafts,
|
||||
[key]: key
|
||||
};
|
||||
|
||||
this.$nextTick(() => {
|
||||
const ref = this.$refs['renameInput-' + key];
|
||||
const input = Array.isArray(ref) ? ref[0] : ref;
|
||||
if (input && typeof input.focus === 'function') {
|
||||
input.focus();
|
||||
if (typeof input.select === 'function') {
|
||||
input.select();
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
closeRenameEditor() {
|
||||
this.openRenameKey = '';
|
||||
},
|
||||
|
||||
submitRenameKey(key) {
|
||||
const nextKey = String((this.renameDrafts || {})[key] || '').trim();
|
||||
this.openRenameKey = '';
|
||||
if (!nextKey || nextKey === key) {
|
||||
return;
|
||||
}
|
||||
this.$emit('update-selector-key', key, nextKey);
|
||||
this.$nextTick(() => {
|
||||
if (Object.prototype.hasOwnProperty.call(this.selectors || {}, nextKey) && !Object.prototype.hasOwnProperty.call(this.selectors || {}, key)) this.expandedField = nextKey;
|
||||
});
|
||||
},
|
||||
|
||||
getSelectorMeta(key) {
|
||||
const metaMap = {
|
||||
input_box: {
|
||||
title: '输入框',
|
||||
description: '用户真正打字的地方。常见是 textarea、contenteditable 或 role=textbox。',
|
||||
hint: '先右键输入区域点“检查”。看到 textarea,或者看到可编辑的 div,通常就离答案很近了。',
|
||||
required: true,
|
||||
chip: '必填',
|
||||
placeholder: '例如:textarea, div[contenteditable="true"]'
|
||||
},
|
||||
send_btn: {
|
||||
title: '发送按钮',
|
||||
description: '点一下就会把消息发出去的按钮,常见是纸飞机、箭头或“发送”字样。',
|
||||
hint: '优先找 button 上比较稳的属性,比如 type、aria-label、data-testid;只靠一串随机 class 往往不稳。',
|
||||
required: true,
|
||||
chip: '必填',
|
||||
placeholder: '例如:button[type="submit"], button[data-testid="send"]'
|
||||
},
|
||||
result_container: {
|
||||
title: '回复容器',
|
||||
description: '包住 AI 回复正文的区域。尽量选整段回复的外层,不要只选某个 p 或 span。',
|
||||
hint: '看到整条 AI 回复后,先选能完整包住这条内容的外层块。范围太小,后面很容易漏字、漏代码块。',
|
||||
required: true,
|
||||
chip: '必填',
|
||||
placeholder: '例如:main article .markdown-body'
|
||||
},
|
||||
new_chat_btn: {
|
||||
title: '新建对话按钮',
|
||||
description: '每次开始新会话前需要点的按钮,没有也可以先留空。',
|
||||
hint: '如果页面左上角有“新聊天”“新建对话”“清空上下文”之类的入口,这个字段通常就该填它。',
|
||||
required: false,
|
||||
chip: '选填',
|
||||
placeholder: '例如:button[aria-label*="新"], button.new-chat'
|
||||
},
|
||||
message_wrapper: {
|
||||
title: '消息外层容器',
|
||||
description: '一条消息最外层的盒子。长回复、分段节点、复杂样式场景里很有帮助。',
|
||||
hint: '如果一条回复里有很多段落、代码块、图片,给它补上最外层容器,提取结果通常会稳很多。',
|
||||
required: false,
|
||||
chip: '辅助',
|
||||
placeholder: '例如:article[data-role="assistant-message"]'
|
||||
},
|
||||
generating_indicator: {
|
||||
title: '生成中指示器',
|
||||
description: '能表明“模型还在继续输出”的元素,比如停止按钮、转圈、typing 提示。',
|
||||
hint: '有“停止生成”按钮时,这个字段通常很好找。它出现时代表还在生成,消失后通常代表结束。',
|
||||
required: false,
|
||||
chip: '辅助',
|
||||
placeholder: '例如:button[aria-label*="停止"], .typing-indicator'
|
||||
},
|
||||
retry_send_btn: {
|
||||
title: '重试/重新运行按钮',
|
||||
description: '用于重新运行当前回复或把停止后的回复重新拉起,常见是圆形箭头按钮。',
|
||||
hint: 'Battle 或双栏对比模式里,通常需要先点这个按钮,再点右下角发送/停止态按钮完成本轮发送。',
|
||||
required: false,
|
||||
chip: '辅助',
|
||||
placeholder: '例如:button[aria-label="Rerun stopped messages"]'
|
||||
},
|
||||
upload_btn: {
|
||||
title: '上传按钮',
|
||||
description: '点一下会弹出上传面板或系统文件选择窗口的按钮。',
|
||||
hint: '页面里有加号、回形针、图片图标时,先看那个按钮。很多站点把上传入口藏在工具栏里。',
|
||||
required: false,
|
||||
chip: '上传',
|
||||
placeholder: '例如:button[aria-label*="上传"], .toolbar-upload'
|
||||
},
|
||||
file_input: {
|
||||
title: '原生文件输入框',
|
||||
description: '真正的 input[type=file] 元素,适合直接写入文件。',
|
||||
hint: '很多站点会把它藏起来。开发者工具里搜索 type="file" 往往最快。',
|
||||
required: false,
|
||||
chip: '上传',
|
||||
placeholder: '例如:input[type="file"]'
|
||||
},
|
||||
composer_root: {
|
||||
title: '消息编辑区根节点',
|
||||
description: '限定自动查找文件输入框和附件观察的范围,避免匹配页面历史消息。',
|
||||
hint: '通常是包围输入框、附件预览和发送按钮的容器。配置 file_input 时仍优先使用指定入口。',
|
||||
required: false, chip: '上传', placeholder: '例如:.composer, form.chat-input'
|
||||
},
|
||||
drop_zone: {
|
||||
title: '拖拽上传区域',
|
||||
description: '支持把文件拖到页面里的区域,适合不吃粘贴的网站。',
|
||||
hint: '拖一张图到页面上时,哪个区域会高亮、变色、出现提示,那个区域通常就是它。',
|
||||
required: false,
|
||||
chip: '上传',
|
||||
placeholder: '例如:div[data-dropzone="true"]'
|
||||
}
|
||||
};
|
||||
|
||||
const presetMeta = metaMap[key];
|
||||
if (presetMeta) {
|
||||
return presetMeta;
|
||||
}
|
||||
|
||||
return {
|
||||
title: '自定义字段',
|
||||
description: '你自己补的额外选择器,常用于临时按钮、模式切换、弹窗确认之类的操作。',
|
||||
hint: '自定义字段也建议优先用稳定属性。页面每次刷新都会变的随机 class,后面维护起来会很痛苦。',
|
||||
required: false,
|
||||
chip: '自定义',
|
||||
placeholder: '例如:button[data-role="mode-switch"]'
|
||||
};
|
||||
},
|
||||
|
||||
getChipClass(key) {
|
||||
const chip = this.getSelectorMeta(key).chip;
|
||||
if (chip === '必填') {
|
||||
return 'dashboard-field-chip';
|
||||
}
|
||||
if (chip === '自定义') {
|
||||
return 'dashboard-field-chip dashboard-field-chip--custom';
|
||||
}
|
||||
return 'dashboard-field-chip dashboard-field-chip--optional';
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="studio-selector-panel bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm" @click="closeMenu">
|
||||
<!-- 标题栏 -->
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="toggle">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="w-4 inline-flex justify-center text-gray-500 dark:text-gray-400" v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">字段配置</h3>
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">({{ count }})</span>
|
||||
</div>
|
||||
|
||||
<div class="relative" @click.stop>
|
||||
<button @click="toggleMenu"
|
||||
class="selector-add-btn">
|
||||
<span v-html="$icons.plusCircle"></span> 新增 <span v-html="$icons.chevronDown"></span>
|
||||
</button>
|
||||
|
||||
<div v-if="showMenu"
|
||||
class="absolute right-0 mt-1 w-56 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-lg z-10 overflow-hidden">
|
||||
<button @click="addSelector('custom')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-900 dark:text-white text-sm border-b dark:border-gray-700 transition-colors">
|
||||
自定义字段
|
||||
</button>
|
||||
<div class="px-3 py-1.5 text-xs text-gray-500 dark:text-gray-400 bg-gray-50 dark:bg-gray-900/50 font-medium">
|
||||
辅助字段
|
||||
</div>
|
||||
<button @click="addSelector('message_wrapper')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">message_wrapper</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">消息完整容器,适合多节点回复</div>
|
||||
</button>
|
||||
<button @click="addSelector('generating_indicator')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">generating_indicator</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">生成中提示,适合辅助判断结束</div>
|
||||
</button>
|
||||
<button @click="addSelector('retry_send_btn')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">retry_send_btn</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">重新运行或重试当前回复</div>
|
||||
</button>
|
||||
<button @click="addSelector('upload_btn')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">upload_btn</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">打开上传入口的按钮</div>
|
||||
</button>
|
||||
<button @click="addSelector('file_input')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">file_input</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">原生 input[type=file]</div>
|
||||
</button>
|
||||
<button @click="addSelector('composer_root')" class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">composer_root</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">限定附件操作的消息编辑区根节点</div>
|
||||
</button>
|
||||
<button @click="addSelector('drop_zone')"
|
||||
class="w-full text-left px-3 py-2 hover:bg-gray-50 dark:hover:bg-gray-700 text-xs transition-colors">
|
||||
<div class="font-semibold text-gray-900 dark:text-white">drop_zone</div>
|
||||
<div class="text-gray-500 dark:text-gray-400">支持拖拽上传的区域</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容 -->
|
||||
<div v-show="!collapsed" class="p-4 space-y-4 max-h-[44rem] overflow-auto">
|
||||
<div v-if="count === 0" class="dashboard-empty-state text-center text-sm text-slate-500 dark:text-slate-400">
|
||||
<div class="text-3xl mb-3">🧭</div>
|
||||
<p class="leading-6">
|
||||
现在还是空白很正常。先把 <code>input_box</code>、<code>send_btn</code>、<code>result_container</code> 加出来,再开始一项一项测试。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="site-core-path" aria-label="核心字段填写进度">
|
||||
<button type="button" v-for="(item, index) in coreChecklist" :key="item.key" :class="{ 'is-filled': item.ready }" :aria-label="'配置' + item.title" @click="openCoreField(item.key)"><span class="site-path-node" v-html="item.ready ? $icons.check : $icons.minus"></span><span><strong>{{ item.title }}</strong><small>{{ item.ready ? '已填写' : '待配置' }}</small></span><i v-if="index < 2" v-html="$icons.arrowRight"></i></button>
|
||||
</div>
|
||||
<div v-if="missingQuickAdds.length" class="site-missing-fields"><span>缺少核心字段</span><button v-for="item in missingQuickAdds" :key="item.key" type="button" @click="addSelector(item.key)"><span v-html="$icons.plusCircle"></span>添加{{ item.title }}</button></div>
|
||||
<div class="studio-field-toolbar">
|
||||
<div class="studio-field-filters" aria-label="筛选选择器">
|
||||
<button type="button" :class="{ 'is-active': fieldFilter === 'all' }" :aria-pressed="fieldFilter === 'all'" @click="fieldFilter = 'all'">全部字段 <span>{{ count }}</span></button>
|
||||
<button type="button" :class="{ 'is-active': fieldFilter === 'core' }" :aria-pressed="fieldFilter === 'core'" @click="fieldFilter = 'core'">核心字段</button>
|
||||
<button type="button" :class="{ 'is-active': fieldFilter === 'empty' }" :aria-pressed="fieldFilter === 'empty'" @click="fieldFilter = 'empty'">未填写</button>
|
||||
</div>
|
||||
<label class="studio-field-search"><span v-html="$icons.magnifyingGlass"></span><input v-model="fieldQuery" type="search" aria-label="搜索选择器字段" placeholder="搜索字段…" @keyup.escape="fieldQuery = ''"></label>
|
||||
</div>
|
||||
<div v-if="count > 0 && !selectorEntries.length" class="studio-fields-empty"><span v-html="$icons.magnifyingGlass"></span><strong>{{ fieldFilter === 'empty' && !fieldQuery ? '当前字段均已填写' : '没有匹配的字段' }}</strong><p>{{ fieldFilter === 'empty' && !fieldQuery ? '接下来可以逐项测试,确认网页元素能被正确定位。' : '试试其他关键词,或切换到全部字段。' }}</p><button type="button" @click="fieldQuery = ''; fieldFilter = 'all'">查看全部字段</button></div>
|
||||
<section v-for="group in selectorGroups" :key="group.id" v-show="group.entries.length" :class="['site-field-group', 'is-' + group.id]">
|
||||
<div class="site-field-group-heading"><div><h4>{{ group.title }} <span>{{ group.entries.length }}</span></h4><p>{{ group.note }}</p></div><button v-if="group.id === 'auxiliary'" type="button" :aria-expanded="auxiliaryExpanded || !!fieldQuery || fieldFilter !== 'all'" @click="auxiliaryExpanded = !auxiliaryExpanded; fieldQuery = ''; fieldFilter = 'all'">{{ auxiliaryExpanded || fieldQuery || fieldFilter !== 'all' ? '收起' : '展开' }}<span v-html="auxiliaryExpanded ? $icons.chevronUp : $icons.chevronDown"></span></button></div>
|
||||
<div v-show="group.id === 'core' || auxiliaryExpanded || fieldQuery || fieldFilter !== 'all'" class="site-field-group-list">
|
||||
<article v-for="([key, val], index) in group.entries" :key="key" :class="['studio-selector-card', { 'is-expanded': expandedField === key }]">
|
||||
<button type="button" class="site-field-toggle" :aria-label="'编辑字段 ' + key" :aria-expanded="expandedField === key" @click="expandedField = expandedField === key ? '' : key">
|
||||
<span class="site-field-index">{{ String(index + 1).padStart(2, '0') }}</span><span class="site-field-heading"><span><strong>{{ getSelectorMeta(key).title }}</strong><code>{{ key }}</code></span><small v-if="expandedField !== key">{{ val || '尚未填写定位表达式' }}</small></span><span :class="['site-field-state', { 'is-filled': isSelectorFilled(key) }]">{{ isSelectorFilled(key) ? '已填写' : '待填写' }}</span><span class="site-field-chevron" v-html="expandedField === key ? $icons.chevronUp : $icons.chevronDown"></span>
|
||||
</button>
|
||||
<div v-show="expandedField === key" class="site-field-expanded">
|
||||
<div v-if="openRenameKey === key"
|
||||
class="mb-2 flex flex-col md:flex-row gap-2 rounded-xl border border-blue-200/80 dark:border-blue-800/70 bg-blue-50/70 dark:bg-blue-900/20 p-2.5">
|
||||
<input :ref="'renameInput-' + key"
|
||||
v-model="renameDrafts[key]"
|
||||
@keyup.enter="submitRenameKey(key)"
|
||||
@keyup.esc="closeRenameEditor()"
|
||||
class="flex-1 border dark:border-gray-600 px-2.5 py-2 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent font-semibold text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white"
|
||||
placeholder="新的字段键名">
|
||||
<div class="flex items-center gap-2">
|
||||
<button @click="submitRenameKey(key)"
|
||||
type="button"
|
||||
class="px-3 py-1.5 rounded-md text-xs font-medium text-blue-600 dark:text-blue-300 border border-blue-300 dark:border-blue-700 hover:bg-blue-100/80 dark:hover:bg-blue-900/40 transition-colors">
|
||||
保存
|
||||
</button>
|
||||
<button @click="closeRenameEditor()"
|
||||
type="button"
|
||||
class="px-3 py-1.5 rounded-md text-xs font-medium text-slate-500 dark:text-slate-300 border border-slate-200 dark:border-slate-700 hover:bg-white/80 dark:hover:bg-slate-800/70 transition-colors">
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="site-field-edit-row"><div class="site-field-expression"><label :for="'selector-expression-' + key">定位表达式</label><textarea :id="'selector-expression-' + key" rows="3" :value="selectors[key]" :aria-label="getSelectorMeta(key).title + '选择器'" @focus="editingSelectorKey = key" @blur="editingSelectorKey = ''" @input="$emit('update-selector-value', key, $event.target.value)" :placeholder="getSelectorMeta(key).placeholder || '输入选择器'"></textarea></div><aside class="site-field-context"><span>如何定位</span><p>{{ getSelectorMeta(key).description }}</p><small>{{ getSelectorMeta(key).hint }}</small></aside></div>
|
||||
<div class="studio-field-actions"><span>填写后,请在目标网页上验证。</span><button v-if="canRenameSelectorKey(key)" type="button" @click="openRenameEditor(key)" class="site-rename-field"><span v-html="$icons.pencil"></span>改名</button><button type="button" class="site-delete-field" :aria-label="'删除选择器 ' + key" @click="$emit('remove-selector', key)"><span v-html="$icons.trash"></span></button><button type="button" class="site-test-field" @click="$emit('test-selector', key, val)"><span v-html="$icons.play"></span>测试选择器</button></div>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
<div v-if="!guideExpanded" class="studio-guide-entry">
|
||||
<button @click="guideExpanded = true" type="button" class="dashboard-guide-toggle">
|
||||
<span v-html="$icons.bookOpen"></span><span>不知道怎么填写?查看选择器指南</span>
|
||||
<span v-html="$icons.chevronDown"></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-else class="dashboard-guide-card dashboard-guide-card--blue">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<span class="dashboard-guide-badge">零基础也能开始</span>
|
||||
<button @click="guideExpanded = false" type="button" class="dashboard-guide-toggle">
|
||||
<span>收起</span>
|
||||
<span v-html="$icons.chevronUp"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<div class="text-base font-semibold text-slate-900 dark:text-slate-50">
|
||||
先把 3 个核心字段补齐,页面就能有基础可用性
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm leading-6 text-slate-600 dark:text-slate-300">
|
||||
先找输入框、发送按钮、AI 回复容器。上传按钮、消息外层、生成中提示这些字段可以后面再慢慢补。第一轮目标很简单:先让页面能发、能收、能测。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-guide-steps">
|
||||
<div class="dashboard-guide-step">
|
||||
<strong>第 1 步</strong>
|
||||
<span>打开教程章节,先看字段各自负责什么。</span>
|
||||
</div>
|
||||
<div class="dashboard-guide-step">
|
||||
<strong>第 2 步</strong>
|
||||
<span>打开本地选择器工作台,先在模拟页面里练一遍,再直接看候选写法和命中详情。</span>
|
||||
</div>
|
||||
<div class="dashboard-guide-step">
|
||||
<strong>第 3 步</strong>
|
||||
<span>回到真实站点,填一个测一个。测试工作台会直接告诉你命中了几个、为什么不稳、有没有更好的候选。</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-checklist">
|
||||
<div v-for="item in coreChecklist"
|
||||
:key="item.key"
|
||||
:class="['dashboard-checklist-item', item.ready ? 'is-ready' : 'is-missing']">
|
||||
<span>{{ item.ready ? '✓' : '•' }}</span>
|
||||
<span>{{ item.key }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="mt-3 text-xs text-slate-500 dark:text-slate-400">
|
||||
当前核心字段进度:{{ coreReadyCount }}/3
|
||||
</p>
|
||||
|
||||
<div v-if="missingQuickAdds.length" class="mt-3 flex flex-wrap gap-2">
|
||||
<button v-for="item in missingQuickAdds"
|
||||
:key="item.key"
|
||||
@click="addSelector(item.key)"
|
||||
class="px-3 py-1.5 rounded-full text-xs font-medium border border-slate-300 dark:border-slate-600 text-slate-700 dark:text-slate-200 hover:bg-white/80 dark:hover:bg-slate-800/80 transition">
|
||||
新增 {{ item.key }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-guide-actions">
|
||||
<button @click="openTutorial('selector-basics')" class="dashboard-guide-btn">
|
||||
<span v-html="$icons.arrowTopRightOnSquare"></span>
|
||||
打开选择器教程
|
||||
</button>
|
||||
<button @click="openPracticeLab()" class="dashboard-guide-btn dashboard-guide-btn--secondary">
|
||||
<span v-html="$icons.folderOpen"></span>
|
||||
打开选择器工作台
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,772 @@
|
||||
// ==================== 流式配置面板 ====================
|
||||
|
||||
window.StreamConfigPanel = {
|
||||
name: 'StreamConfigPanel',
|
||||
props: {
|
||||
streamConfig: { type: Object, required: true },
|
||||
currentDomain: { type: String, default: null },
|
||||
collapsed: { type: Boolean, default: true }
|
||||
},
|
||||
emits: ['update:collapsed', 'save-stream-config'],
|
||||
data() {
|
||||
return {
|
||||
availableParsers: [],
|
||||
loadingParsers: false,
|
||||
loadingTransportProfiles: false,
|
||||
guideExpanded: false,
|
||||
networkStepsExpanded: false,
|
||||
requestTransportMeta: {
|
||||
defaults: {
|
||||
mode: 'workflow',
|
||||
profile: '',
|
||||
options: {}
|
||||
},
|
||||
mode_options: ['workflow', 'page_fetch'],
|
||||
profiles: []
|
||||
},
|
||||
streamMatchModeOptions: [
|
||||
{
|
||||
value: 'keyword',
|
||||
label: '关键词',
|
||||
description: '直接判断 URL 是否包含指定文本,适合大多数站点。'
|
||||
},
|
||||
{
|
||||
value: 'regex',
|
||||
label: '正则',
|
||||
description: '用正则精确筛选目标 URL,适合需要排除 prepare 之类噪音请求的站点。'
|
||||
}
|
||||
],
|
||||
defaultNetworkConfig: {
|
||||
listen_pattern: '',
|
||||
stream_match_mode: 'keyword',
|
||||
stream_match_pattern: '',
|
||||
parser: '',
|
||||
silence_threshold: 3.0,
|
||||
response_interval: 0.5
|
||||
}
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
isNetworkMode() {
|
||||
return this.streamConfig.mode === 'network';
|
||||
},
|
||||
|
||||
requestTransportConfig() {
|
||||
const defaults = (this.requestTransportMeta && this.requestTransportMeta.defaults) || {
|
||||
mode: 'workflow',
|
||||
profile: '',
|
||||
options: {}
|
||||
};
|
||||
const current = (this.streamConfig && this.streamConfig.request_transport) || {};
|
||||
return {
|
||||
...defaults,
|
||||
...current,
|
||||
options: {
|
||||
...((defaults && defaults.options) || {}),
|
||||
...((current && current.options) || {})
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
requestTransportModeOptions() {
|
||||
const options = (this.requestTransportMeta && this.requestTransportMeta.mode_options) || ['workflow', 'page_fetch'];
|
||||
return options.map(value => ({
|
||||
value,
|
||||
label: value === 'page_fetch' ? '页面直发' : '工作流模拟'
|
||||
}));
|
||||
},
|
||||
|
||||
availableRequestTransportProfiles() {
|
||||
const profiles = (this.requestTransportMeta && this.requestTransportMeta.profiles) || [];
|
||||
const parserId = String(this.networkConfig.parser || '').trim().toLowerCase();
|
||||
const domain = String(this.currentDomain || '').trim().toLowerCase();
|
||||
return profiles.filter(profile => {
|
||||
const supportedParsers = Array.isArray(profile.supported_parsers) ? profile.supported_parsers : [];
|
||||
const supportedDomains = Array.isArray(profile.supported_domains) ? profile.supported_domains : [];
|
||||
const parserOkay = supportedParsers.length === 0 || supportedParsers.includes(parserId);
|
||||
const domainOkay = supportedDomains.length === 0 || supportedDomains.includes(domain);
|
||||
return parserOkay && domainOkay;
|
||||
});
|
||||
},
|
||||
|
||||
selectedRequestTransportProfileMeta() {
|
||||
const currentProfile = String(this.requestTransportConfig.profile || '').trim();
|
||||
return this.availableRequestTransportProfiles.find(profile => profile.id === currentProfile) || null;
|
||||
},
|
||||
|
||||
networkConfig() {
|
||||
return {
|
||||
...this.defaultNetworkConfig,
|
||||
...(this.streamConfig.network || {})
|
||||
};
|
||||
},
|
||||
|
||||
sendConfirmationConfig() {
|
||||
const defaults = {
|
||||
max_retry_count: 2,
|
||||
retry_interval: 0.6,
|
||||
retry_cooldown_window: 1.5,
|
||||
post_click_observe_window: 1.8,
|
||||
pre_retry_probe_window: 0.12,
|
||||
retry_observe_window: 0.9,
|
||||
retry_action: 'click_send_btn',
|
||||
retry_key_combo: 'Enter',
|
||||
retry_on_unconfirmed_send: 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,
|
||||
pre_send_interrupt_existing_generation: true
|
||||
};
|
||||
return {
|
||||
...defaults,
|
||||
...((this.streamConfig && this.streamConfig.send_confirmation) || {})
|
||||
};
|
||||
},
|
||||
|
||||
sendConfirmationSummary() {
|
||||
if (!this.sendConfirmationConfig.retry_on_unconfirmed_send || Number(this.sendConfirmationConfig.max_retry_count) <= 0) {
|
||||
return '不自动补点';
|
||||
}
|
||||
return '最多重试 ' + Number(this.sendConfirmationConfig.max_retry_count || 0) + ' 次';
|
||||
},
|
||||
|
||||
selectedParserMeta() {
|
||||
return this.findParserMeta(this.networkConfig.parser);
|
||||
},
|
||||
|
||||
preferredPattern() {
|
||||
const parserId = String(this.networkConfig.parser || '').trim();
|
||||
if (!parserId) {
|
||||
return '';
|
||||
}
|
||||
return this.getPreferredListenPattern(parserId);
|
||||
},
|
||||
|
||||
selectedStreamMatchModeMeta() {
|
||||
return this.streamMatchModeOptions.find(
|
||||
option => option.value === this.networkConfig.stream_match_mode
|
||||
) || this.streamMatchModeOptions[0];
|
||||
},
|
||||
|
||||
networkChecklist() {
|
||||
return [
|
||||
{
|
||||
label: 'listen_pattern',
|
||||
ready: String(this.networkConfig.listen_pattern || '').trim().length > 0
|
||||
},
|
||||
{
|
||||
label: 'parser',
|
||||
ready: String(this.networkConfig.parser || '').trim().length > 0
|
||||
},
|
||||
{
|
||||
label: '超时参数',
|
||||
ready: Number(this.streamConfig.hard_timeout) > 0 && Number(this.networkConfig.silence_threshold) > 0
|
||||
}
|
||||
];
|
||||
}
|
||||
},
|
||||
watch: {
|
||||
// 修复:组件被 v-show 复用时不会重新 mounted,切到 network 模式的站点后
|
||||
// availableParsers 仍为空,导致已配置的解析器在下拉里匹配不到 option
|
||||
isNetworkMode: {
|
||||
immediate: true,
|
||||
handler(value) {
|
||||
if (value && !(this.availableParsers || []).length && !this.loadingParsers) {
|
||||
this.loadParsers();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.loadTransportProfiles();
|
||||
if (this.isNetworkMode) {
|
||||
this.loadParsers();
|
||||
}
|
||||
},
|
||||
methods: {
|
||||
buildAuthHeaders(extraHeaders = {}) {
|
||||
const token = String(window.getDashboardAuthToken ? window.getDashboardAuthToken() : '').trim();
|
||||
const headers = { ...extraHeaders };
|
||||
if (token) {
|
||||
headers['Authorization'] = 'Bearer ' + token;
|
||||
}
|
||||
return headers;
|
||||
},
|
||||
|
||||
toggle() {
|
||||
this.$emit('update:collapsed', !this.collapsed);
|
||||
},
|
||||
|
||||
updateField(field, value) {
|
||||
const newConfig = { ...this.streamConfig, [field]: value };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
updateRequestTransportField(field, value) {
|
||||
const request_transport = {
|
||||
...this.requestTransportConfig,
|
||||
[field]: value
|
||||
};
|
||||
if (field === 'mode' && value !== 'page_fetch') {
|
||||
request_transport.profile = '';
|
||||
request_transport.options = {};
|
||||
}
|
||||
if (field === 'profile') {
|
||||
const profile = this.availableRequestTransportProfiles.find(item => item.id === value);
|
||||
const nextOptions = {};
|
||||
(profile && Array.isArray(profile.options) ? profile.options : []).forEach(option => {
|
||||
nextOptions[option.key] = option.default;
|
||||
});
|
||||
request_transport.options = nextOptions;
|
||||
}
|
||||
const newConfig = { ...this.streamConfig, request_transport };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
updateRequestTransportOption(key, value) {
|
||||
const request_transport = {
|
||||
...this.requestTransportConfig,
|
||||
options: {
|
||||
...(this.requestTransportConfig.options || {}),
|
||||
[key]: value
|
||||
}
|
||||
};
|
||||
const newConfig = { ...this.streamConfig, request_transport };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
updateNetworkField(field, value) {
|
||||
const network = { ...this.networkConfig, [field]: value };
|
||||
const newConfig = { ...this.streamConfig, network };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
updateSendConfirmationField(field, value) {
|
||||
const send_confirmation = {
|
||||
...this.sendConfirmationConfig,
|
||||
[field]: value
|
||||
};
|
||||
const newConfig = { ...this.streamConfig, send_confirmation };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
openInNewTab(url) {
|
||||
const target = String(url || '').trim();
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
window.open(target, '_blank', 'noopener,noreferrer');
|
||||
},
|
||||
|
||||
openTutorial(anchor = 'non-stream-listener-basics') {
|
||||
this.openInNewTab('/static/tutorial/index.html#' + encodeURIComponent(anchor));
|
||||
},
|
||||
|
||||
findParserMeta(parserId) {
|
||||
return this.availableParsers.find(parser => parser.id === parserId) || null;
|
||||
},
|
||||
|
||||
getPreferredListenPattern(parserId) {
|
||||
const parser = this.findParserMeta(parserId);
|
||||
if (!parser || !Array.isArray(parser.patterns) || parser.patterns.length === 0) {
|
||||
return '';
|
||||
}
|
||||
return String(parser.patterns[0] || '').replace(/^\*\*\//, '');
|
||||
},
|
||||
|
||||
usePreferredPattern() {
|
||||
if (!this.preferredPattern) {
|
||||
return;
|
||||
}
|
||||
this.updateNetworkField('listen_pattern', this.preferredPattern);
|
||||
},
|
||||
|
||||
handleParserChange(parserId) {
|
||||
const currentPattern = (this.networkConfig.listen_pattern || '').trim();
|
||||
const nextPattern = currentPattern || this.getPreferredListenPattern(parserId);
|
||||
const network = {
|
||||
...this.networkConfig,
|
||||
parser: parserId,
|
||||
listen_pattern: nextPattern
|
||||
};
|
||||
const newConfig = { ...this.streamConfig, network };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
autofillListenPatternFromCurrentParser() {
|
||||
const parserId = (this.networkConfig.parser || '').trim();
|
||||
const currentPattern = (this.networkConfig.listen_pattern || '').trim();
|
||||
if (!parserId || currentPattern) {
|
||||
return;
|
||||
}
|
||||
|
||||
const suggestedPattern = this.getPreferredListenPattern(parserId);
|
||||
if (!suggestedPattern) {
|
||||
return;
|
||||
}
|
||||
|
||||
const network = {
|
||||
...this.networkConfig,
|
||||
listen_pattern: suggestedPattern
|
||||
};
|
||||
const newConfig = { ...this.streamConfig, network };
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
},
|
||||
|
||||
toggleNetworkMode() {
|
||||
if (this.isNetworkMode) {
|
||||
this.updateField('mode', 'dom');
|
||||
} else {
|
||||
const newConfig = {
|
||||
...this.streamConfig,
|
||||
mode: 'network',
|
||||
network: this.streamConfig.network || { ...this.defaultNetworkConfig }
|
||||
};
|
||||
this.$emit('save-stream-config', newConfig);
|
||||
if (this.availableParsers.length === 0) {
|
||||
this.loadParsers();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async loadParsers() {
|
||||
if (this.loadingParsers) return;
|
||||
this.loadingParsers = true;
|
||||
try {
|
||||
const response = await fetch('/api/parsers', {
|
||||
headers: this.buildAuthHeaders()
|
||||
});
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.detail || ('HTTP ' + response.status));
|
||||
}
|
||||
const data = await response.json();
|
||||
this.availableParsers = data.parsers || [];
|
||||
this.autofillListenPatternFromCurrentParser();
|
||||
} catch (e) {
|
||||
console.error('加载解析器失败:', e);
|
||||
} finally {
|
||||
this.loadingParsers = false;
|
||||
}
|
||||
},
|
||||
|
||||
async loadTransportProfiles() {
|
||||
if (this.loadingTransportProfiles) return;
|
||||
this.loadingTransportProfiles = true;
|
||||
try {
|
||||
const response = await fetch('/api/settings/stream-config-defaults', {
|
||||
headers: this.buildAuthHeaders()
|
||||
});
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
throw new Error(err.detail || ('HTTP ' + response.status));
|
||||
}
|
||||
const data = await response.json();
|
||||
const requestTransport = data.request_transport || {};
|
||||
this.requestTransportMeta = {
|
||||
defaults: requestTransport.defaults || {
|
||||
mode: 'workflow',
|
||||
profile: '',
|
||||
options: {}
|
||||
},
|
||||
mode_options: requestTransport.mode_options || ['workflow', 'page_fetch'],
|
||||
profiles: requestTransport.profiles || []
|
||||
};
|
||||
} catch (e) {
|
||||
console.error('加载发送方式配置失败:', e);
|
||||
} finally {
|
||||
this.loadingTransportProfiles = false;
|
||||
}
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="cap-panel cap-response-panel bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm">
|
||||
<!-- 标题栏 -->
|
||||
<div class="px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors"
|
||||
@click="toggle">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="w-4 inline-flex justify-center text-gray-500 dark:text-gray-400" v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">从哪里读取回复</h3>
|
||||
<span v-if="isNetworkMode" class="text-xs font-medium px-2 py-0.5 rounded bg-green-100 text-green-700 dark:bg-green-900/40 dark:text-green-400">已启用</span>
|
||||
<span v-else class="text-xs font-medium px-2 py-0.5 rounded bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400">DOM 流式</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容 -->
|
||||
<div v-show="!collapsed" class="p-4 space-y-4"><div class="cap-response-explainer"><span class="cap-icon" v-html="$icons.documentArrowDown"></span><div><h4>{{ isNetworkMode ? '正在读取网络响应' : '正在读取网页上显示的回复' }}</h4><p>{{ isNetworkMode ? '适合保留代码、公式等原始内容,需要正确的请求匹配和解析器。' : '观察页面文字的变化来返回回复。首次适配站点时,可以先沿用这种方式。' }}</p><small>开启开关后读取网络响应,关闭则读取页面内容;切换可能影响现有回复解析。</small></div><label class="cap-switch"><span class="cap-state">{{ isNetworkMode ? '网络读取' : '网页读取' }}</span><input role="switch" type="checkbox" aria-label="从网络读取回复" :checked="isNetworkMode" @change="toggleNetworkMode" class="cap-switch-input"><i aria-hidden="true"></i></label></div>
|
||||
<div v-if="!guideExpanded">
|
||||
<button @click="guideExpanded = true" type="button" class="dashboard-guide-toggle dashboard-guide-toggle--violet">
|
||||
<span>网络模式引导</span>
|
||||
<span v-html="$icons.chevronDown"></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-else class="dashboard-guide-card dashboard-guide-card--violet">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<span class="dashboard-guide-badge">先判断场景,再动开关</span>
|
||||
<button @click="guideExpanded = false" type="button" class="dashboard-guide-toggle dashboard-guide-toggle--violet">
|
||||
<span>收起</span>
|
||||
<span v-html="$icons.chevronUp"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="mt-3">
|
||||
<div class="text-base font-semibold text-slate-900 dark:text-slate-50">
|
||||
DOM 模式与网络监听模式
|
||||
</div>
|
||||
<p class="mt-1.5 text-sm leading-6 text-slate-600 dark:text-slate-300">
|
||||
网络监听会优先读取底层请求响应;如果站点走的是 <strong>fetch/xhr 流式</strong>,现在可以直接增量输出;如果站点本身返回的是整包 JSON / 文本,那它看起来仍会像一次性完成。DOM 模式则是盯着页面展示内容变化来输出。遇到复杂 JSON、代码块或 LaTeX 数学公式时,网络监听通常更容易拿到干净原文。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-checklist">
|
||||
<div v-for="item in networkChecklist"
|
||||
:key="item.label"
|
||||
:class="['dashboard-checklist-item', item.ready ? 'is-ready' : 'is-missing']">
|
||||
<span>{{ item.ready ? '✓' : '•' }}</span>
|
||||
<span>{{ item.label }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="dashboard-guide-actions">
|
||||
<button @click="openTutorial('non-stream-listener-basics')" class="dashboard-guide-btn">
|
||||
<span v-html="$icons.arrowTopRightOnSquare"></span>
|
||||
DOM 和网络监听区别
|
||||
</button>
|
||||
<button @click="openTutorial('non-stream-parser-guide')" class="dashboard-guide-btn dashboard-guide-btn--secondary">
|
||||
<span v-html="$icons.folderOpen"></span>
|
||||
网络解析器教程
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 网络模式配置 -->
|
||||
<details v-if="isNetworkMode" class="cap-settings"><summary><span><strong>配置网络响应识别</strong><small>先指定请求关键词,再选择解析器。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body">
|
||||
<details class="cap-technical"><summary><span><strong>请求发送方式(高级)</strong><small>网页工作流或页面接口直发;仅在明确需要更换发送方式时设置。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div class="rounded-lg border border-slate-200/70 bg-slate-50/80 p-4 dark:border-slate-700 dark:bg-slate-900/40 space-y-4">
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2">
|
||||
<span>🚀</span>
|
||||
<span>发送方式</span>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">发送模式</label>
|
||||
<select :value="requestTransportConfig.mode"
|
||||
@change="updateRequestTransportField('mode', $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<option v-for="option in requestTransportModeOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
</div>
|
||||
<div v-if="requestTransportConfig.mode === 'page_fetch'">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">发送 Profile</label>
|
||||
<select :value="requestTransportConfig.profile"
|
||||
@change="updateRequestTransportField('profile', $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<option value="" disabled>{{ loadingTransportProfiles ? '加载中...' : '选择发送 profile...' }}</option>
|
||||
<option v-for="profile in availableRequestTransportProfiles" :key="profile.id" :value="profile.id">{{ profile.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedRequestTransportProfileMeta" class="space-y-4">
|
||||
<p class="text-xs leading-5 text-slate-500 dark:text-slate-400">
|
||||
{{ selectedRequestTransportProfileMeta.description }}
|
||||
</p>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<template v-for="option in selectedRequestTransportProfileMeta.options" :key="option.key">
|
||||
<div v-if="option.type === 'enum'">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ option.label }}</label>
|
||||
<select :value="requestTransportConfig.options[option.key]"
|
||||
@change="updateRequestTransportOption(option.key, $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<option v-for="choice in option.choices" :key="choice.value" :value="choice.value">{{ choice.label }}</option>
|
||||
</select>
|
||||
<p v-if="option.description" class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ option.description }}</p>
|
||||
</div>
|
||||
<div v-else-if="option.type === 'string'">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">{{ option.label }}</label>
|
||||
<input type="text"
|
||||
:value="requestTransportConfig.options[option.key]"
|
||||
@input="updateRequestTransportOption(option.key, $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<p v-if="option.description" class="mt-1 text-xs text-gray-500 dark:text-gray-400">{{ option.description }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div></div></details>
|
||||
|
||||
<div>
|
||||
<button v-if="!networkStepsExpanded"
|
||||
@click="networkStepsExpanded = true"
|
||||
type="button"
|
||||
class="dashboard-guide-toggle dashboard-guide-toggle--violet">
|
||||
<span>配置步骤</span>
|
||||
<span v-html="$icons.chevronDown"></span>
|
||||
</button>
|
||||
<div v-else class="space-y-3">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="text-xs font-medium uppercase tracking-[0.18em] text-slate-400 dark:text-slate-500">
|
||||
三步看完再填
|
||||
</div>
|
||||
<button @click="networkStepsExpanded = false"
|
||||
type="button"
|
||||
class="dashboard-guide-toggle dashboard-guide-toggle--violet">
|
||||
<span>收起</span>
|
||||
<span v-html="$icons.chevronUp"></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
|
||||
<div class="dashboard-mini-card">
|
||||
<div class="dashboard-mini-card-title">第 1 步:锁定请求关键词</div>
|
||||
<div class="dashboard-mini-card-copy">先找目标请求 URL 里最稳定的一小段路径,填进 <code>listen_pattern</code>。</div>
|
||||
</div>
|
||||
<div class="dashboard-mini-card">
|
||||
<div class="dashboard-mini-card-title">第 2 步:选对解析器</div>
|
||||
<div class="dashboard-mini-card-copy">有内置解析器就直接选;没有时先按教程导出请求,让 AI 帮你写 parser。</div>
|
||||
</div>
|
||||
<div class="dashboard-mini-card">
|
||||
<div class="dashboard-mini-card-title">第 3 步:补超时</div>
|
||||
<div class="dashboard-mini-card-copy">慢站点先把全局硬超时和静默超时调高;流式站点主要看静默超时,整包返回站点则更依赖整体等待窗口。</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center gap-2">
|
||||
<svg class="w-4 h-4 text-purple-500" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M8.288 15.038a5.25 5.25 0 017.424 0M5.106 11.856c3.807-3.808 9.98-3.808 13.788 0M1.924 8.674c5.565-5.565 14.587-5.565 20.152 0M12.53 18.22l-.53.53-.53-.53a.75.75 0 011.06 0z"/>
|
||||
</svg>
|
||||
网络拦截配置
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<div class="flex items-center justify-between gap-3 mb-1">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300">URL 匹配模式 <span class="text-red-500">*</span></label>
|
||||
<button v-if="preferredPattern"
|
||||
@click="usePreferredPattern"
|
||||
type="button"
|
||||
class="text-xs font-medium text-purple-600 dark:text-purple-300 hover:underline">
|
||||
一键填入推荐值
|
||||
</button>
|
||||
</div>
|
||||
<input type="text"
|
||||
:value="networkConfig.listen_pattern"
|
||||
@input="updateNetworkField('listen_pattern', $event.target.value)"
|
||||
placeholder="例如:GenerateContent"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
只要 URL 里包含这段字符串,监听器就会尝试拦截。先写窄一点,调通后再看要不要放宽。
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">响应解析器 <span class="text-red-500">*</span></label>
|
||||
<select :value="networkConfig.parser"
|
||||
@change="handleParserChange($event.target.value)"
|
||||
@focus="loadParsers"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<option value="" disabled>{{ loadingParsers ? '加载解析器中...' : '选择解析器...' }}</option>
|
||||
<option v-for="parser in availableParsers" :key="parser.id" :value="parser.id">{{ parser.name }}</option>
|
||||
</select>
|
||||
<p v-if="selectedParserMeta && Array.isArray(selectedParserMeta.patterns) && selectedParserMeta.patterns.length"
|
||||
class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
这个解析器常见监听关键词:<code>{{ preferredPattern }}</code>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="cap-technical"><summary><span><strong>响应不完整、等待太久或重复发送?</strong><small>流匹配、超时与重试的排查参数。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body"><div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">流目标匹配模式</label>
|
||||
<select :value="networkConfig.stream_match_mode"
|
||||
@change="updateNetworkField('stream_match_mode', $event.target.value)"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<option v-for="option in streamMatchModeOptions" :key="option.value" :value="option.value">{{ option.label }}</option>
|
||||
</select>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
{{ selectedStreamMatchModeMeta.description }}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">流目标匹配表达式</label>
|
||||
<input type="text"
|
||||
:value="networkConfig.stream_match_pattern"
|
||||
@input="updateNetworkField('stream_match_pattern', $event.target.value)"
|
||||
placeholder="留空时默认沿用 listen_pattern"
|
||||
class="w-full border dark:border-gray-600 px-3 py-2 rounded-md text-sm font-mono bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
<code>keyword</code> 模式下填 URL 子串,<code>regex</code> 模式下填正则;留空时回退到 <code>listen_pattern</code>。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">静默超时</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number" :value="networkConfig.silence_threshold" @input="updateNetworkField('silence_threshold', parseFloat($event.target.value) || 3)"
|
||||
min="0.5" max="30" step="0.5" class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">轮询间隔</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number" :value="networkConfig.response_interval" @input="updateNetworkField('response_interval', parseFloat($event.target.value) || 0.5)"
|
||||
min="0.1" max="5" step="0.1" class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-purple-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="rounded-xl border border-amber-200/80 dark:border-amber-800/70 bg-amber-50/70 dark:bg-amber-900/20 p-4">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<div class="text-sm font-medium text-gray-800 dark:text-gray-100">发送确认与重试</div>
|
||||
<p class="mt-1 text-xs leading-5 text-gray-600 dark:text-gray-300">
|
||||
控制点击 <code>send_btn</code> 后,如果没有马上观察到输入框清空、网络活动或生成态,是否自动再点一次。Battle 模式里通常应关闭自动重试,避免第二次点击方形按钮变成中断输出。
|
||||
</p>
|
||||
</div>
|
||||
<span class="px-2 py-0.5 text-xs rounded-full bg-white/80 dark:bg-gray-800/80 text-amber-700 dark:text-amber-300 border border-amber-200 dark:border-amber-700">
|
||||
{{ sendConfirmationSummary }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-1 md:grid-cols-3 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">首次点击观察窗</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="sendConfirmationConfig.post_click_observe_window"
|
||||
@input="updateSendConfirmationField('post_click_observe_window', parseFloat($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="15"
|
||||
step="0.1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">最大重试次数</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="sendConfirmationConfig.max_retry_count"
|
||||
@input="updateSendConfirmationField('max_retry_count', parseInt($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="10"
|
||||
step="1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">次</span>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">重试间隔</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number"
|
||||
:value="sendConfirmationConfig.retry_interval"
|
||||
@input="updateSendConfirmationField('retry_interval', parseFloat($event.target.value) || 0)"
|
||||
min="0"
|
||||
max="30"
|
||||
step="0.1"
|
||||
class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-amber-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="sendConfirmationConfig.retry_on_unconfirmed_send"
|
||||
@change="updateSendConfirmationField('retry_on_unconfirmed_send', $event.target.checked)">
|
||||
<span>发送未确认时允许自动重试</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="sendConfirmationConfig.retry_block_on_stop_button"
|
||||
@change="updateSendConfirmationField('retry_block_on_stop_button', $event.target.checked)">
|
||||
<span>发送按钮变成 stop 时禁止重试</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="sendConfirmationConfig.retry_block_if_generating"
|
||||
@change="updateSendConfirmationField('retry_block_if_generating', $event.target.checked)">
|
||||
<span>页面进入生成态时禁止重试</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="sendConfirmationConfig.trust_generating_indicator"
|
||||
@change="updateSendConfirmationField('trust_generating_indicator', $event.target.checked)">
|
||||
<span>生成态可作为发送成功信号</span>
|
||||
</label>
|
||||
<label class="flex items-center gap-3 text-sm text-gray-700 dark:text-gray-300 cursor-pointer">
|
||||
<input type="checkbox"
|
||||
class="rounded"
|
||||
:checked="sendConfirmationConfig.pre_send_interrupt_existing_generation"
|
||||
@change="updateSendConfirmationField('pre_send_interrupt_existing_generation', $event.target.checked)">
|
||||
<span>发送前主动打断旧生成态 (Arena)</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="!networkConfig.listen_pattern || !networkConfig.parser"
|
||||
class="bg-yellow-50 dark:bg-yellow-900/30 border border-yellow-200 dark:border-yellow-800 rounded-xl p-3">
|
||||
<div class="flex items-start gap-2">
|
||||
<svg class="w-5 h-5 text-yellow-500 flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd"/>
|
||||
</svg>
|
||||
<div class="text-sm text-yellow-700 dark:text-yellow-300">
|
||||
<span class="font-medium">还差关键字段</span>
|
||||
<p class="mt-0.5 text-xs leading-5">
|
||||
先把 <code>listen_pattern</code> 和 <code>parser</code> 补齐,再开始调超时参数。当前直接测试,基本只会得到空结果或回退。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div></details></div></details>
|
||||
|
||||
<!-- DOM 模式说明 -->
|
||||
<div v-else class="dashboard-mini-card">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<div class="dashboard-mini-card-title">DOM 轮询模式</div>
|
||||
<div class="dashboard-mini-card-copy">
|
||||
这个模式会盯着页面元素变化来判断回复是否结束。兼容性最好,第一次适配新站点时也更容易跑通。
|
||||
</div>
|
||||
</div>
|
||||
<button @click="openTutorial('response-detection')"
|
||||
type="button"
|
||||
class="text-xs font-medium text-blue-600 dark:text-blue-300 hover:underline shrink-0">
|
||||
打开章节
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 通用配置 -->
|
||||
<details class="cap-troubleshoot"><summary><span><strong>回复一直不结束?</strong><small>调整一次对话最多允许等待的时间。</small></span><span class="cap-chevron" v-html="$icons.chevronDown"></span></summary><div class="cap-settings-body">
|
||||
<div class="text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">通用配置</div>
|
||||
<div class="grid grid-cols-1 gap-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">全局硬超时</label>
|
||||
<div class="flex items-center gap-2">
|
||||
<input type="number" :value="streamConfig.hard_timeout" @input="updateField('hard_timeout', parseInt($event.target.value) || 300)"
|
||||
min="10" max="600" step="10" class="flex-1 border dark:border-gray-600 px-3 py-2 rounded-md text-sm bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-400 focus:border-transparent">
|
||||
<span class="text-sm text-gray-500 dark:text-gray-400">秒</span>
|
||||
</div>
|
||||
<p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
|
||||
网络监听里,这就是一次完整对话允许等待的最长时间。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div></details>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
// ==================== 通用折叠面板组件 ====================
|
||||
|
||||
window.CollapsiblePanel = {
|
||||
name: 'CollapsiblePanel',
|
||||
props: {
|
||||
title: { type: String, required: true },
|
||||
icon: { type: String, default: '' },
|
||||
badge: { type: [String, Number], default: null },
|
||||
collapsed: { type: Boolean, default: true },
|
||||
headerClass: { type: String, default: '' }
|
||||
},
|
||||
emits: ['toggle'],
|
||||
methods: {
|
||||
toggle() {
|
||||
this.$emit('toggle');
|
||||
},
|
||||
|
||||
stopPropagation(event) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
},
|
||||
template: `
|
||||
<div class="bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-sm">
|
||||
<!-- 标题栏 -->
|
||||
<div :class="[
|
||||
'px-4 py-3 border-b dark:border-gray-700 flex justify-between items-center cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors',
|
||||
headerClass
|
||||
]" @click="toggle">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-gray-500 dark:text-gray-400"
|
||||
v-html="collapsed ? $icons.chevronDown : $icons.chevronUp"></span>
|
||||
<h3 class="font-semibold text-gray-900 dark:text-white">
|
||||
{{ icon }} {{ title }}
|
||||
</h3>
|
||||
<span v-if="badge !== null" class="text-sm text-gray-500 dark:text-gray-400">
|
||||
({{ badge }})
|
||||
</span>
|
||||
<!-- 额外徽章插槽 -->
|
||||
<slot name="badges"></slot>
|
||||
</div>
|
||||
|
||||
<!-- 右侧操作区 -->
|
||||
<div @click.stop="stopPropagation">
|
||||
<slot name="actions"></slot>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容区 -->
|
||||
<div v-show="!collapsed">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</div>
|
||||
`
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
// Dashboard methods 组装器(R2-8 起拆分到 static/js/dashboard/:shared.js 为共享常量与辅助函数,
|
||||
// methods-*.js 为按主题分组的方法;index.html 需在本文件之前按顺序加载它们)。
|
||||
(() => {
|
||||
const parts = window.DashboardMethodParts || [];
|
||||
const merged = {};
|
||||
for (const part of parts) {
|
||||
for (const key of Object.keys(part)) {
|
||||
if (Object.prototype.hasOwnProperty.call(merged, key)) {
|
||||
console.warn('[dashboard] 方法重名,后加载的覆盖先加载的:' + key);
|
||||
}
|
||||
merged[key] = part[key];
|
||||
}
|
||||
}
|
||||
window.DashboardMethods = merged;
|
||||
})();
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,428 @@
|
||||
(() => {
|
||||
const DEFAULT_SELECTOR_DEFINITIONS = window.DEFAULT_SELECTOR_DEFINITIONS || []
|
||||
const BROWSER_CONSTANTS_SCHEMA = window.BROWSER_CONSTANTS_SCHEMA || {}
|
||||
const ENV_CONFIG_SCHEMA = window.ENV_CONFIG_SCHEMA || {}
|
||||
|
||||
const DASHBOARD_SITES_CACHE_STORAGE_KEY = 'dashboard_sites_cache_v1'
|
||||
const DASHBOARD_TOKEN_STORAGE_KEY = 'dashboard_token'
|
||||
const LEGACY_API_TOKEN_STORAGE_KEY = 'api_token'
|
||||
|
||||
function loadStoredDashboardToken() {
|
||||
try {
|
||||
return String(
|
||||
localStorage.getItem(DASHBOARD_TOKEN_STORAGE_KEY)
|
||||
|| localStorage.getItem(LEGACY_API_TOKEN_STORAGE_KEY)
|
||||
|| ''
|
||||
).trim()
|
||||
} catch (error) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function loadStoredSitesCache() {
|
||||
try {
|
||||
const raw = localStorage.getItem(DASHBOARD_SITES_CACHE_STORAGE_KEY)
|
||||
if (!raw) {
|
||||
return null
|
||||
}
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return null
|
||||
}
|
||||
if (!parsed.sites || typeof parsed.sites !== 'object' || Array.isArray(parsed.sites)) {
|
||||
return null
|
||||
}
|
||||
return {
|
||||
sites: parsed.sites,
|
||||
currentDomain: typeof parsed.currentDomain === 'string' ? parsed.currentDomain : null
|
||||
}
|
||||
} catch (error) {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function saveStoredSitesCache(sites, currentDomain) {
|
||||
try {
|
||||
localStorage.setItem(DASHBOARD_SITES_CACHE_STORAGE_KEY, JSON.stringify({
|
||||
sites: sites && typeof sites === 'object' ? sites : {},
|
||||
currentDomain: typeof currentDomain === 'string' ? currentDomain : null,
|
||||
savedAt: Date.now()
|
||||
}))
|
||||
} catch (error) {
|
||||
// ignore storage failures and keep runtime data available
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 元素定义 Schema ==========
|
||||
|
||||
const DashboardState = {
|
||||
data() {
|
||||
return {
|
||||
// 数据
|
||||
sites: {},
|
||||
currentDomain: null,
|
||||
searchQuery: '',
|
||||
|
||||
// UI 状态
|
||||
toasts: [],
|
||||
toastCounter: 0,
|
||||
hasLoadedSettings: false,
|
||||
isSaving: false,
|
||||
studioLastSavedAt: '',
|
||||
isLoading: false,
|
||||
configLoadSeq: 0,
|
||||
imageConfigSaveSeq: 0,
|
||||
imageConfigSaveQueue: null,
|
||||
showJsonPreview: false,
|
||||
showTokenDialog: false,
|
||||
showStepTemplates: false,
|
||||
showTestDialog: false,
|
||||
showSelectorMenu: false,
|
||||
showImportMenu: false,
|
||||
showExportMenu: false,
|
||||
forceSingleSiteImport: false,
|
||||
singleSiteImportTargetDomain: '',
|
||||
darkMode: false,
|
||||
sidebarCollapsed: false,
|
||||
showMainCompareSummaryDialog: false,
|
||||
mainCompareSummaryLoading: false,
|
||||
mainCompareSummaryError: '',
|
||||
mainCompareSummaryItems: [],
|
||||
mainCompareSummaryCounts: {
|
||||
same: 0,
|
||||
different: 0,
|
||||
local_only_preset: 0,
|
||||
local_only_site: 0,
|
||||
main_only_preset: 0,
|
||||
main_only_site: 0
|
||||
},
|
||||
mainCompareSummaryPath: 'config/sites/index.json',
|
||||
mainCompareSummarySource: {
|
||||
repository: '',
|
||||
branch: 'main',
|
||||
status: '',
|
||||
stale: false,
|
||||
fetched_at: '',
|
||||
checked_at: '',
|
||||
warning: ''
|
||||
},
|
||||
mainCompareShowSame: false,
|
||||
|
||||
// Tab 切换(新增 settings)
|
||||
activeTab: 'home',
|
||||
siteConfigView: 'library',
|
||||
siteLibraryFilter: 'all',
|
||||
mountedTabs: {
|
||||
home: true,
|
||||
config: true
|
||||
},
|
||||
|
||||
// 折叠面板状态
|
||||
selectorCollapsed: true,
|
||||
workflowCollapsed: true,
|
||||
|
||||
// 浏览器状态
|
||||
browserStatus: {
|
||||
connected: false,
|
||||
// 后端 health_check 实际返回 status/connected/port/tab_pool/error
|
||||
// (此前这里声明的 tab_url / tab_title 后端从未产出,属假接口,已移除)
|
||||
tab_pool: null
|
||||
},
|
||||
|
||||
// 系统占用统计
|
||||
systemStats: {
|
||||
memory_mb: 0,
|
||||
disk_status: '加载中...',
|
||||
total_requests: 0,
|
||||
total_input_tokens: 0,
|
||||
total_output_tokens: 0,
|
||||
cpu_percent: 0,
|
||||
project_cpu: 0,
|
||||
memory_percent: 0,
|
||||
project_memory_percent: 0,
|
||||
// 实时请求计数(后端 /api/system/stats 提供,请求监控页「正在执行」KPI 使用)
|
||||
running_count: 0,
|
||||
queued_count: 0
|
||||
},
|
||||
|
||||
// 认证
|
||||
authEnabled: false,
|
||||
tempToken: '',
|
||||
hasTokenPresent: (() => {
|
||||
return !!loadStoredDashboardToken()
|
||||
})(),
|
||||
tokenStorageHandler: null,
|
||||
|
||||
// 选择器测试
|
||||
currentTestingSelectorKey: '',
|
||||
testSelectorInput: '',
|
||||
testTimeout: 2,
|
||||
testResult: null,
|
||||
isTesting: false,
|
||||
testHighlight: false,
|
||||
|
||||
// 日志相关
|
||||
logs: [],
|
||||
logLevelFilter: 'ALL',
|
||||
pauseLogs: false,
|
||||
lastLogTimestamp: 0,
|
||||
lastLogSeq: 0,
|
||||
lastBackgroundLogPollAt: 0,
|
||||
logGeneration: 0,
|
||||
logPollingTimer: null,
|
||||
logVisibilityHandler: null,
|
||||
isPollingLogs: false,
|
||||
logPollPending: false,
|
||||
systemStatsTimer: null,
|
||||
systemStatsVisibilityHandler: null,
|
||||
isFetchingSystemStats: false,
|
||||
systemStatsRequestPromise: null,
|
||||
|
||||
// 请求监控
|
||||
requestHistory: [],
|
||||
requestHistoryMaxRecords: 0,
|
||||
requestHistoryLoading: false,
|
||||
requestHistoryError: '',
|
||||
requestHistoryTimer: null,
|
||||
requestHistoryVisibilityHandler: null,
|
||||
requestHistoryRevision: '',
|
||||
requestHistoryFetchedAt: 0,
|
||||
requestHistoryRequestSeq: 0,
|
||||
requestHistoryPendingRefresh: null,
|
||||
requestHistoryDetailLoading: {},
|
||||
|
||||
// ========== 导入功能 ==========
|
||||
showImportDialog: false,
|
||||
importMode: 'merge', // 'merge' | 'replace'
|
||||
importType: 'full', // 'full' | 'single' (新增:导入类型)
|
||||
importedConfig: null,
|
||||
importFileName: '',
|
||||
singleSiteImportDomain: '', // 新增:单站点导入时的域名
|
||||
|
||||
// ========== 系统设置 ==========
|
||||
// 环境配置
|
||||
envConfig: {},
|
||||
envConfigOriginal: {},
|
||||
envCollapsed: {},
|
||||
isSavingEnv: false,
|
||||
isLoadingEnv: false,
|
||||
|
||||
// 浏览器常量
|
||||
browserConstants: {},
|
||||
browserConstantsOriginal: {},
|
||||
browserConstantsRaw: {},
|
||||
browserConstantsCollapsed: {},
|
||||
isSavingConstants: false,
|
||||
isLoadingConstants: false,
|
||||
|
||||
// 更新白名单
|
||||
updatePreserveOptions: [],
|
||||
updatePreserveSelected: [],
|
||||
updatePreserveSelectedOriginal: [],
|
||||
isSavingUpdatePreserve: false,
|
||||
isLoadingUpdatePreserve: false,
|
||||
|
||||
// Schema 引用
|
||||
envSchema: ENV_CONFIG_SCHEMA,
|
||||
browserConstantsSchema: BROWSER_CONSTANTS_SCHEMA,
|
||||
|
||||
// ========== 元素定义管理 ==========
|
||||
selectorDefinitions: [],
|
||||
selectorDefinitionsOriginal: [],
|
||||
isLoadingDefinitions: false,
|
||||
isSavingDefinitions: false,
|
||||
showAddDefinitionDialog: false,
|
||||
newDefinition: {
|
||||
key: '',
|
||||
description: '',
|
||||
enabled: true,
|
||||
required: false
|
||||
},
|
||||
editingDefinitionIndex: null,
|
||||
|
||||
// ========== 版本管理 ==========
|
||||
releases: [],
|
||||
releasesLoading: false,
|
||||
releasesError: '',
|
||||
releasesCurrentVersion: '',
|
||||
updateCheck: {
|
||||
checked: false,
|
||||
checking: false,
|
||||
available: false,
|
||||
current_version: '',
|
||||
latest_version: '',
|
||||
latest_tag: '',
|
||||
error: ''
|
||||
},
|
||||
updateCheckTimer: null,
|
||||
updateCheckRefreshing: false, // 「立即检查」按钮的进行中标记
|
||||
switchingTag: null, // 正在切换的 tag
|
||||
switchStatusPolling: null, // 轮询定时器
|
||||
switchStatusPollingActive: false,
|
||||
switchStatusPollingInFlight: false,
|
||||
showChangelogModal: false,
|
||||
changelogContent: '',
|
||||
changelogTag: '',
|
||||
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
computed: {
|
||||
siteLibraryStats() {
|
||||
const summaries = Object.keys(this.sites).map(domain => this.siteLibrarySummary(domain))
|
||||
return { sites: summaries.length, presets: summaries.reduce((n, s) => n + s.presets, 0), incomplete: summaries.filter(s => s.coreFilled < 3).length }
|
||||
},
|
||||
librarySites() {
|
||||
return this.filteredSites.filter(domain => this.siteLibraryFilter !== 'incomplete' || this.siteLibrarySummary(domain).coreFilled < 3)
|
||||
},
|
||||
filteredSites() {
|
||||
const keys = Object.keys(this.sites).sort()
|
||||
const query = this.searchQuery.trim().toLowerCase()
|
||||
return query
|
||||
? keys.filter(d => (d + ' ' + this.siteDisplayName(d)).toLowerCase().includes(query))
|
||||
: keys
|
||||
},
|
||||
|
||||
currentConfig() {
|
||||
return this.currentDomain ? this.sites[this.currentDomain] : null
|
||||
},
|
||||
|
||||
hasToken() {
|
||||
return !!this.hasTokenPresent
|
||||
},
|
||||
|
||||
// 过滤后的日志
|
||||
filteredLogs() {
|
||||
if (this.logLevelFilter === 'ALL') {
|
||||
return this.logs;
|
||||
}
|
||||
if (this.logLevelFilter === 'INFO') {
|
||||
return this.logs.filter(log => log.level === 'INFO' || log.level === 'OK');
|
||||
}
|
||||
return this.logs.filter(log => log.level === this.logLevelFilter);
|
||||
},
|
||||
|
||||
// 检测环境配置是否有变更
|
||||
envConfigChanged() {
|
||||
return JSON.stringify(this.envConfig) !== JSON.stringify(this.envConfigOriginal);
|
||||
},
|
||||
|
||||
// 检测浏览器常量是否有变更
|
||||
browserConstantsChanged() {
|
||||
return JSON.stringify(this.browserConstants) !== JSON.stringify(this.browserConstantsOriginal);
|
||||
},
|
||||
|
||||
// 检测元素定义是否有变更
|
||||
selectorDefinitionsChanged() {
|
||||
return JSON.stringify(this.selectorDefinitions) !== JSON.stringify(this.selectorDefinitionsOriginal);
|
||||
},
|
||||
|
||||
// 检测更新白名单是否有变更
|
||||
updatePreserveChanged() {
|
||||
return JSON.stringify(this.updatePreserveSelected) !== JSON.stringify(this.updatePreserveSelectedOriginal);
|
||||
},
|
||||
|
||||
updateAvailable() {
|
||||
return !!(this.updateCheck && this.updateCheck.available);
|
||||
},
|
||||
|
||||
mainCompareVisibleItems() {
|
||||
const items = Array.isArray(this.mainCompareSummaryItems) ? this.mainCompareSummaryItems : [];
|
||||
if (this.mainCompareShowSame) {
|
||||
return items;
|
||||
}
|
||||
return items.filter(item => String(item && item.status || '') !== 'same');
|
||||
},
|
||||
|
||||
mainCompareDifferentTotal() {
|
||||
const counts = this.mainCompareSummaryCounts || {};
|
||||
return Number(counts.different || 0)
|
||||
+ Number(counts.local_only_preset || 0)
|
||||
+ Number(counts.local_only_site || 0);
|
||||
}
|
||||
},
|
||||
|
||||
watch: {
|
||||
sidebarCollapsed(collapsed) {
|
||||
const appRoot = document.getElementById('app')
|
||||
if (appRoot) {
|
||||
appRoot.classList.toggle('sidebar-is-collapsed', !!collapsed)
|
||||
}
|
||||
},
|
||||
activeTab(tab) {
|
||||
document.getElementById('app')?.classList.toggle('site-studio-active', tab === 'config')
|
||||
this.markTabAsVisited(tab)
|
||||
this.ensureTabDataLoaded(tab)
|
||||
if (tab === 'logs') {
|
||||
this.pollLogs()
|
||||
}
|
||||
},
|
||||
darkMode() {
|
||||
this.applyDarkMode()
|
||||
}
|
||||
},
|
||||
|
||||
mounted() {
|
||||
document.addEventListener('keydown', this.handleStudioShortcut)
|
||||
document.getElementById('app')?.classList.toggle('site-studio-active', this.activeTab === 'config')
|
||||
// 读取夜间模式设置
|
||||
let savedDarkMode = null
|
||||
try {
|
||||
savedDarkMode = localStorage.getItem('darkMode')
|
||||
} catch (e) {
|
||||
savedDarkMode = null
|
||||
}
|
||||
if (savedDarkMode !== null) {
|
||||
this.darkMode = savedDarkMode === 'true'
|
||||
} else {
|
||||
this.darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
}
|
||||
this.applyDarkMode()
|
||||
|
||||
// 初始化折叠状态
|
||||
this.initCollapsedStates()
|
||||
this.markTabAsVisited(this.activeTab)
|
||||
this.restoreSitesCache()
|
||||
this.syncTokenPresence()
|
||||
this.ensureTokenStorageHandler()
|
||||
|
||||
this.initializeDashboard()
|
||||
|
||||
this._globalClickCloser = (e) => {
|
||||
if (!e.target.closest('.uwa-dropdown')) {
|
||||
this.closeAllMenus();
|
||||
}
|
||||
};
|
||||
document.addEventListener('click', this._globalClickCloser);
|
||||
|
||||
// 启动日志轮询(每 1 秒)
|
||||
|
||||
// 加载系统设置
|
||||
|
||||
// 加载元素定义
|
||||
|
||||
// 加载提取器列表
|
||||
},
|
||||
|
||||
beforeUnmount() {
|
||||
document.removeEventListener('keydown', this.handleStudioShortcut)
|
||||
this.stopLogPolling()
|
||||
this.stopRequestHistoryPolling()
|
||||
this.stopSystemStatsPolling()
|
||||
if (this.updateCheckTimer) {
|
||||
clearTimeout(this.updateCheckTimer)
|
||||
this.updateCheckTimer = null
|
||||
}
|
||||
this.stopSwitchStatusPolling()
|
||||
this.stopTokenStorageHandler()
|
||||
if (this._globalClickCloser) {
|
||||
document.removeEventListener('click', this._globalClickCloser);
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
window.DashboardState = DashboardState
|
||||
window.loadStoredSitesCache = loadStoredSitesCache
|
||||
window.saveStoredSitesCache = saveStoredSitesCache
|
||||
})();
|
||||
@@ -0,0 +1,48 @@
|
||||
const { createApp } = Vue
|
||||
const dashboardState = window.DashboardState || {}
|
||||
|
||||
// ========== Vue App ==========
|
||||
|
||||
const app = createApp({
|
||||
data: dashboardState.data || function () { return {} },
|
||||
computed: dashboardState.computed || {},
|
||||
watch: dashboardState.watch || {},
|
||||
mounted: dashboardState.mounted || function () {},
|
||||
beforeUnmount: dashboardState.beforeUnmount || function () {},
|
||||
|
||||
methods: window.DashboardMethods || {}
|
||||
});
|
||||
|
||||
// ========== 组件注册 ==========
|
||||
app.component('sidebar-component', window.SidebarComponent);
|
||||
app.component('onboarding-guide', window.OnboardingGuide);
|
||||
app.component('home-tab', window.HomeTab);
|
||||
app.component('config-tab', window.ConfigTab);
|
||||
app.component('request-monitor-tab', window.RequestMonitorTab);
|
||||
app.component('tabpool-tab', window.TabPoolTabComponent);
|
||||
app.component('commands-tab', window.CommandsTabComponent); // 🆕 命令系统
|
||||
app.component('logs-tab', window.LogsTab);
|
||||
app.component('settings-tab', window.SettingsTab);
|
||||
app.component('json-preview-dialog', window.JsonPreviewDialog);
|
||||
app.component('token-dialog', window.TokenDialog);
|
||||
app.component('step-templates-dialog', window.StepTemplatesDialog);
|
||||
app.component('test-dialog', window.TestDialog);
|
||||
app.component('import-dialog', window.ImportDialog);
|
||||
app.component('definition-dialog', window.DefinitionDialog);
|
||||
|
||||
// ========== 全局 Mixin (修复图标访问问题) ==========
|
||||
app.mixin({
|
||||
computed: {
|
||||
$icons() {
|
||||
return window.$icons || window.icons || {};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ========== 启动应用 ==========
|
||||
app.mount('#app');
|
||||
document.body.classList.add('app-mounted');
|
||||
const appShell = document.getElementById('app-shell');
|
||||
if (appShell) {
|
||||
appShell.style.display = 'none';
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——API 调用与配置读写。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== API 调用 ==========
|
||||
|
||||
openTokenDialog() {
|
||||
if (this.showTokenDialog) {
|
||||
return
|
||||
}
|
||||
this.tempToken = getStoredDashboardToken()
|
||||
this.showTokenDialog = true
|
||||
},
|
||||
|
||||
async apiRequest(url, options = {}) {
|
||||
const token = getStoredDashboardToken()
|
||||
const timeoutMs = Number(options.timeoutMs || 0)
|
||||
const headers = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers['Authorization'] = 'Bearer ' + token
|
||||
}
|
||||
|
||||
const fetchOptions = { ...options }
|
||||
delete fetchOptions.timeoutMs
|
||||
|
||||
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,
|
||||
headers
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 401) {
|
||||
this.notify('控制面板认证失败,请检查访问密钥', 'error')
|
||||
this.openTokenDialog()
|
||||
throw new Error('UNAUTHORIZED')
|
||||
}
|
||||
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
throw new Error(errorData.detail || '请求失败 (' + response.status + ')')
|
||||
}
|
||||
|
||||
return await response.json()
|
||||
} catch (error) {
|
||||
if (error && error.name === 'AbortError') {
|
||||
throw new Error('REQUEST_TIMEOUT')
|
||||
}
|
||||
if (error.message !== 'UNAUTHORIZED') {
|
||||
console.error('API 请求错误:', error)
|
||||
}
|
||||
throw error
|
||||
} finally {
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async loadConfig(silent) {
|
||||
// 防御:@click="loadConfig" 会传入 Event 对象,需要过滤
|
||||
if (typeof silent !== 'boolean') {
|
||||
silent = false
|
||||
}
|
||||
|
||||
const requestSeq = Number(this.configLoadSeq || 0) + 1
|
||||
this.configLoadSeq = requestSeq
|
||||
this.isLoading = true
|
||||
try {
|
||||
const data = await this.apiRequest('/api/config', { timeoutMs: 5000 })
|
||||
if (requestSeq !== this.configLoadSeq) {
|
||||
return false
|
||||
}
|
||||
|
||||
this.sites = this.normalizeConfig(data)
|
||||
if (!this.currentDomain && Object.keys(this.sites).length > 0) {
|
||||
this.currentDomain = Object.keys(this.sites)[0]
|
||||
}
|
||||
window.saveStoredSitesCache(this.sites, this.currentDomain)
|
||||
|
||||
if (!silent) {
|
||||
this.notify('配置已刷新 (' + Object.keys(this.sites).length + ' 个站点)', 'success')
|
||||
}
|
||||
return true
|
||||
} catch (error) {
|
||||
if (requestSeq !== this.configLoadSeq) {
|
||||
return false
|
||||
}
|
||||
this.notify('加载配置失败: ' + error.message, 'error')
|
||||
if (Object.keys(this.sites || {}).length === 0) {
|
||||
this.sites = {}
|
||||
}
|
||||
return false
|
||||
} finally {
|
||||
if (requestSeq === this.configLoadSeq) {
|
||||
this.isLoading = false
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// 修复:FilePastePanel / PromptPaddingPanel 编辑的是独立草稿,必须 flush 才会回写到
|
||||
// presetConfig。原先只有 saveConfig 调用,导致 JSON 预览既显示旧值也保存旧值。
|
||||
// 抽成方法后在读取/保存配置的各处统一调用。
|
||||
flushConfigTabDrafts() {
|
||||
if (this.$refs && this.$refs.configTab && typeof this.$refs.configTab.flushMutableSectionDrafts === 'function') {
|
||||
this.$refs.configTab.flushMutableSectionDrafts()
|
||||
}
|
||||
},
|
||||
|
||||
async saveConfig() {
|
||||
if (!this.validateConfig()) {
|
||||
return
|
||||
}
|
||||
|
||||
this.isSaving = true
|
||||
try {
|
||||
this.flushConfigTabDrafts()
|
||||
const tab = this.$refs?.configTab, configRef = tab?.currentConfig, transferRevision = tab?.pendingPresetTransfer
|
||||
await this.apiRequest('/api/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: this.sites })
|
||||
})
|
||||
if (tab && tab.currentConfig === configRef && tab.pendingPresetTransfer === transferRevision) tab.pendingPresetTransfer = 0
|
||||
this.studioLastSavedAt = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
this.notify('配置已保存', 'success')
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error')
|
||||
} finally {
|
||||
this.isSaving = false
|
||||
}
|
||||
},
|
||||
|
||||
async checkAuth() {
|
||||
return this.loadHealthStatus({ silent: true })
|
||||
},
|
||||
|
||||
async testSelector(key, selector) {
|
||||
this.currentTestingSelectorKey = key || ''
|
||||
this.testSelectorInput = selector || ''
|
||||
this.showTestDialog = true
|
||||
this.testResult = null
|
||||
|
||||
if (!String(this.testSelectorInput || '').trim()) {
|
||||
this.notify('当前字段还没填,先在测试工作台里输入一个选择器再测。', 'info')
|
||||
return
|
||||
}
|
||||
|
||||
await this.runTest()
|
||||
},
|
||||
|
||||
async runTest() {
|
||||
if (!this.testSelectorInput) return
|
||||
|
||||
this.isTesting = true
|
||||
this.testResult = null
|
||||
|
||||
try {
|
||||
const result = await this.apiRequest('/api/debug/test-selector', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
selector: this.testSelectorInput,
|
||||
timeout: this.testTimeout,
|
||||
highlight: this.testHighlight,
|
||||
route_domain: this.currentDomain || ''
|
||||
})
|
||||
})
|
||||
|
||||
this.testResult = result
|
||||
|
||||
if (result.success) {
|
||||
if (result.count > 1) {
|
||||
this.notify('✅ 找到 ' + result.count + ' 个元素' + (this.testHighlight ? ',已全部高亮' : ''), 'success')
|
||||
} else {
|
||||
this.notify('✅ 选择器有效' + (this.testHighlight ? ',已高亮显示' : ''), 'success')
|
||||
}
|
||||
} else {
|
||||
this.notify('❌ 选择器无效', 'error')
|
||||
}
|
||||
} catch (error) {
|
||||
this.testResult = {
|
||||
success: false,
|
||||
message: error.message
|
||||
}
|
||||
this.notify('测试失败: ' + error.message, 'error')
|
||||
} finally {
|
||||
this.isTesting = false
|
||||
}
|
||||
},
|
||||
|
||||
async applyTestSelectorCandidate(payload) {
|
||||
const selector = String(payload && payload.selector || '').trim()
|
||||
if (!selector) {
|
||||
return
|
||||
}
|
||||
|
||||
this.testSelectorInput = selector
|
||||
|
||||
const key = String(this.currentTestingSelectorKey || '').trim()
|
||||
const preset = this.getActivePresetConfig()
|
||||
if (key && preset && preset.selectors) {
|
||||
preset.selectors[key] = selector
|
||||
this.notify('候选选择器已回填到当前字段', 'success')
|
||||
} else {
|
||||
this.notify('已代入当前测试输入框', 'info')
|
||||
}
|
||||
|
||||
if (payload && payload.rerun) {
|
||||
await this.runTest()
|
||||
}
|
||||
},
|
||||
|
||||
async testCurrentSite() {
|
||||
if (!this.currentConfig || Object.keys(this.currentConfig.selectors).length === 0) {
|
||||
this.notify('当前站点没有选择器', 'warning')
|
||||
return
|
||||
}
|
||||
|
||||
this.notify('开始批量测试...', 'info')
|
||||
|
||||
let successCount = 0
|
||||
let failCount = 0
|
||||
|
||||
for (const [key, selector] of Object.entries(this.currentConfig.selectors)) {
|
||||
if (!selector) continue
|
||||
|
||||
try {
|
||||
const result = await this.apiRequest('/api/debug/test-selector', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
selector: selector,
|
||||
timeout: 2,
|
||||
route_domain: this.currentDomain || ''
|
||||
})
|
||||
})
|
||||
|
||||
if (result.success) {
|
||||
successCount++
|
||||
console.log('✅ ' + key + ': ' + selector)
|
||||
} else {
|
||||
failCount++
|
||||
console.warn('❌ ' + key + ': ' + selector)
|
||||
}
|
||||
} catch (error) {
|
||||
failCount++
|
||||
console.error('❌ ' + key + ': ' + error.message)
|
||||
}
|
||||
}
|
||||
|
||||
this.notify('测试完成: ' + successCount + ' 成功, ' + failCount + ' 失败',
|
||||
failCount > 0 ? 'warning' : 'success')
|
||||
},
|
||||
|
||||
async reanalyzeCurrentSite() {
|
||||
if (!this.currentDomain) return
|
||||
|
||||
if (!confirm('确定要删除 ' + this.currentDomain + ' 的配置并重新分析吗?\n\n重新分析需要浏览器当前正在访问该站点。')) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await this.apiRequest('/api/config/' + this.currentDomain, {
|
||||
method: 'DELETE'
|
||||
})
|
||||
|
||||
this.notify('配置已删除,请刷新页面让 AI 重新分析', 'info')
|
||||
|
||||
delete this.sites[this.currentDomain]
|
||||
this.currentDomain = null
|
||||
} catch (error) {
|
||||
this.notify('删除失败: ' + error.message, 'error')
|
||||
}
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,482 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——基础:站点显示、初始化、夜间模式、菜单。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
siteDisplayName,
|
||||
siteStudioInitial(domain) {
|
||||
const name = this.siteDisplayName(domain)
|
||||
const initials = { 'aistudio.google.com': 'G', 'aistudio.xiaomimimo.com': 'M', 'chat.qwen.ai': 'Q', 'www.doubao.com': '豆', 'chatglm.cn': '智' }
|
||||
return initials[domain] || Array.from(name || '?')[0].toUpperCase()
|
||||
},
|
||||
siteLibrarySummary(domain) {
|
||||
const site = this.sites[domain] || {}
|
||||
const presets = site.presets || null
|
||||
const names = presets ? Object.keys(presets) : []
|
||||
const presetName = presets ? (names.includes(site.default_preset) ? site.default_preset : names.includes('主预设') ? '主预设' : names[0] || '无预设') : '主预设'
|
||||
const config = presets ? presets[presetName] || {} : site
|
||||
const selectors = config.selectors || {}
|
||||
const coreChecks = ['input_box', 'send_btn', 'result_container'].map(key => !!String(selectors[key] || '').trim())
|
||||
return { presetName, presets: presets ? names.length : 1, selectors: Object.keys(selectors).length, coreChecks, coreFilled: coreChecks.filter(Boolean).length }
|
||||
},
|
||||
showSiteLibrary() {
|
||||
this.flushConfigTabDrafts()
|
||||
this.siteConfigView = 'library'
|
||||
this.$nextTick(() => document.querySelector('.dashboard-scroll-region')?.scrollTo({ top: 0 }))
|
||||
},
|
||||
handleStudioShortcut(event) {
|
||||
if (this.activeTab !== 'config' || event.defaultPrevented) return
|
||||
const editing = event.target && (event.target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(event.target.tagName))
|
||||
const visibleDialog = Array.from(document.querySelectorAll('[role="dialog"]')).some(el => el.getClientRects().length)
|
||||
const editingDialog = Object.entries(this.$data || {}).some(([key, value]) => /^show.*(Dialog|Modal|Preview)$/.test(key) && value === true)
|
||||
if (visibleDialog || editingDialog) return
|
||||
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 's') {
|
||||
event.preventDefault()
|
||||
if (!this.isSaving && this.currentConfig && !this.showJsonPreview) this.saveConfig()
|
||||
} else if (event.key === '/' && !editing && !event.ctrlKey && !event.metaKey && !event.altKey) {
|
||||
const field = document.querySelector('.library-search input')
|
||||
if (field && field.getClientRects().length) {
|
||||
event.preventDefault()
|
||||
field.focus()
|
||||
}
|
||||
}
|
||||
},
|
||||
async initializeDashboard() {
|
||||
await this.loadConfig(true)
|
||||
await this.loadBrowserConstants().catch(() => {})
|
||||
|
||||
this.startLogPolling()
|
||||
await this.loadHealthStatus({ silent: true, timeoutMs: 2500 }).catch(() => false)
|
||||
this.loadUpdateCheck({ silent: true })
|
||||
.then((status) => this.scheduleUpdateCheckStatusRefresh(status))
|
||||
.catch(() => {})
|
||||
this.startRequestHistoryPolling()
|
||||
this.ensureTabDataLoaded(this.activeTab)
|
||||
|
||||
this.startSystemStatsPolling()
|
||||
},
|
||||
|
||||
startLogPolling() {
|
||||
this.ensureLogPollingVisibilityHandler()
|
||||
const interval = this.getDashboardPollInterval('DASHBOARD_LOG_POLL_INTERVAL_MS', 1000)
|
||||
if (
|
||||
interval <= 0
|
||||
|| !this.getBrowserConstantBool('LOG_WEB_COLLECTOR_ENABLED', true)
|
||||
|| this.getBrowserConstantNumber('LOG_WEB_MAX_RECORDS', 5000) <= 0
|
||||
) {
|
||||
this.stopLogPollingTimer()
|
||||
this.logs = []
|
||||
return
|
||||
}
|
||||
if (this.logPollingTimer || this.isDocumentHidden()) {
|
||||
return
|
||||
}
|
||||
|
||||
this.pollLogs()
|
||||
this.logPollingTimer = setInterval(() => {
|
||||
this.pollLogs({ background: this.activeTab !== 'logs' })
|
||||
}, interval)
|
||||
},
|
||||
|
||||
stopLogPolling() {
|
||||
this.stopLogPollingTimer()
|
||||
if (
|
||||
this.logVisibilityHandler
|
||||
&& typeof document !== 'undefined'
|
||||
&& typeof document.removeEventListener === 'function'
|
||||
) {
|
||||
document.removeEventListener('visibilitychange', this.logVisibilityHandler)
|
||||
}
|
||||
this.logVisibilityHandler = null
|
||||
},
|
||||
|
||||
stopLogPollingTimer() {
|
||||
if (!this.logPollingTimer) {
|
||||
return
|
||||
}
|
||||
|
||||
clearInterval(this.logPollingTimer)
|
||||
this.logPollingTimer = null
|
||||
},
|
||||
|
||||
ensureLogPollingVisibilityHandler() {
|
||||
if (
|
||||
this.logVisibilityHandler
|
||||
|| typeof document === 'undefined'
|
||||
|| typeof document.addEventListener !== 'function'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
this.logVisibilityHandler = () => {
|
||||
if (this.isDocumentHidden()) {
|
||||
this.stopLogPollingTimer()
|
||||
return
|
||||
}
|
||||
this.startLogPolling()
|
||||
}
|
||||
document.addEventListener('visibilitychange', this.logVisibilityHandler)
|
||||
},
|
||||
|
||||
markTabAsVisited(tab) {
|
||||
const key = String(tab || '').trim()
|
||||
if (!key || this.mountedTabs[key]) {
|
||||
return
|
||||
}
|
||||
this.mountedTabs = {
|
||||
...this.mountedTabs,
|
||||
[key]: true
|
||||
}
|
||||
},
|
||||
|
||||
shouldRenderTab(tab) {
|
||||
return this.activeTab === tab || !!this.mountedTabs[tab]
|
||||
},
|
||||
|
||||
syncTokenPresence() {
|
||||
try {
|
||||
this.hasTokenPresent = !!getStoredDashboardToken()
|
||||
} catch (e) {
|
||||
this.hasTokenPresent = false
|
||||
}
|
||||
},
|
||||
|
||||
ensureTokenStorageHandler() {
|
||||
if (
|
||||
this.tokenStorageHandler
|
||||
|| typeof window === 'undefined'
|
||||
|| typeof window.addEventListener !== 'function'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
this.tokenStorageHandler = (event) => {
|
||||
if (
|
||||
!event
|
||||
|| event.key === DASHBOARD_TOKEN_STORAGE_KEY
|
||||
|| event.key === LEGACY_API_TOKEN_STORAGE_KEY
|
||||
) {
|
||||
this.hasTokenPresent = !!getStoredDashboardToken()
|
||||
}
|
||||
}
|
||||
window.addEventListener('storage', this.tokenStorageHandler)
|
||||
},
|
||||
|
||||
stopTokenStorageHandler() {
|
||||
if (
|
||||
this.tokenStorageHandler
|
||||
&& typeof window !== 'undefined'
|
||||
&& typeof window.removeEventListener === 'function'
|
||||
) {
|
||||
window.removeEventListener('storage', this.tokenStorageHandler)
|
||||
}
|
||||
this.tokenStorageHandler = null
|
||||
},
|
||||
|
||||
startRequestHistoryPolling() {
|
||||
this.ensureRequestHistoryVisibilityHandler()
|
||||
const interval = this.getDashboardPollInterval('DASHBOARD_REQUEST_HISTORY_POLL_INTERVAL_MS', 3000)
|
||||
if (!this.isRequestMonitorEnabled() || interval <= 0) {
|
||||
this.stopRequestHistoryPollingTimer()
|
||||
if (!this.isRequestMonitorEnabled()) {
|
||||
this.requestHistory = []
|
||||
this.requestHistoryRevision = ''
|
||||
this.requestHistoryError = ''
|
||||
}
|
||||
return
|
||||
}
|
||||
if (this.requestHistoryTimer || this.isDocumentHidden()) {
|
||||
return
|
||||
}
|
||||
this.requestHistoryTimer = setInterval(() => {
|
||||
if (this.activeTab === 'monitor' && document.visibilityState !== 'hidden') {
|
||||
this.fetchRequestHistory({ silent: true, ifChanged: true }).catch(() => {})
|
||||
}
|
||||
}, interval)
|
||||
},
|
||||
|
||||
stopRequestHistoryPolling() {
|
||||
this.stopRequestHistoryPollingTimer()
|
||||
if (
|
||||
this.requestHistoryVisibilityHandler
|
||||
&& typeof document !== 'undefined'
|
||||
&& typeof document.removeEventListener === 'function'
|
||||
) {
|
||||
document.removeEventListener('visibilitychange', this.requestHistoryVisibilityHandler)
|
||||
}
|
||||
this.requestHistoryVisibilityHandler = null
|
||||
},
|
||||
|
||||
stopRequestHistoryPollingTimer() {
|
||||
if (!this.requestHistoryTimer) {
|
||||
return
|
||||
}
|
||||
clearInterval(this.requestHistoryTimer)
|
||||
this.requestHistoryTimer = null
|
||||
},
|
||||
|
||||
ensureRequestHistoryVisibilityHandler() {
|
||||
if (
|
||||
this.requestHistoryVisibilityHandler
|
||||
|| typeof document === 'undefined'
|
||||
|| typeof document.addEventListener !== 'function'
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
this.requestHistoryVisibilityHandler = () => {
|
||||
if (this.isDocumentHidden()) {
|
||||
this.stopRequestHistoryPollingTimer()
|
||||
return
|
||||
}
|
||||
this.startRequestHistoryPolling()
|
||||
if (this.activeTab === 'monitor' && this.isRequestMonitorEnabled()) {
|
||||
this.fetchRequestHistory({ silent: true, ifChanged: true }).catch(() => {})
|
||||
}
|
||||
}
|
||||
document.addEventListener('visibilitychange', this.requestHistoryVisibilityHandler)
|
||||
},
|
||||
|
||||
isDocumentHidden() {
|
||||
return typeof document !== 'undefined' && document.visibilityState === 'hidden'
|
||||
},
|
||||
|
||||
getBrowserConstantDefault(key, fallback = null) {
|
||||
const targetKey = String(key || '')
|
||||
for (const group of Object.values(BROWSER_CONSTANTS_SCHEMA || {})) {
|
||||
const items = group && group.items ? group.items : {}
|
||||
if (Object.prototype.hasOwnProperty.call(items, targetKey)) {
|
||||
const field = items[targetKey] || {}
|
||||
return Object.prototype.hasOwnProperty.call(field, 'default') ? field.default : fallback
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
},
|
||||
|
||||
getBrowserConstantValue(key, fallback = null) {
|
||||
const targetKey = String(key || '')
|
||||
const constants = this.browserConstants && typeof this.browserConstants === 'object' ? this.browserConstants : {}
|
||||
if (Object.prototype.hasOwnProperty.call(constants, targetKey)) {
|
||||
return constants[targetKey]
|
||||
}
|
||||
return this.getBrowserConstantDefault(targetKey, fallback)
|
||||
},
|
||||
|
||||
getBrowserConstantNumber(key, fallback = 0, { min = null, max = null } = {}) {
|
||||
const value = Number(this.getBrowserConstantValue(key, fallback))
|
||||
if (!Number.isFinite(value)) {
|
||||
return fallback
|
||||
}
|
||||
let normalized = value
|
||||
if (Number.isFinite(min)) {
|
||||
normalized = Math.max(min, normalized)
|
||||
}
|
||||
if (Number.isFinite(max)) {
|
||||
normalized = Math.min(max, normalized)
|
||||
}
|
||||
return normalized
|
||||
},
|
||||
|
||||
getBrowserConstantBool(key, fallback = true) {
|
||||
const value = this.getBrowserConstantValue(key, fallback)
|
||||
if (typeof value === 'boolean') {
|
||||
return value
|
||||
}
|
||||
if (typeof value === 'number') {
|
||||
return value !== 0
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) {
|
||||
return false
|
||||
}
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return Boolean(fallback)
|
||||
},
|
||||
|
||||
getDashboardPollInterval(key, fallback) {
|
||||
const value = this.getBrowserConstantNumber(key, fallback, { min: 0 })
|
||||
return Number.isFinite(value) ? Math.floor(value) : fallback
|
||||
},
|
||||
|
||||
isRequestMonitorEnabled() {
|
||||
return this.getBrowserConstantBool('REQUEST_MONITOR_ENABLED', true)
|
||||
&& this.getBrowserConstantNumber('REQUEST_MONITOR_MAX_RECORDS', 200, { min: 0 }) > 0
|
||||
},
|
||||
|
||||
isSystemStatsPollingEnabled() {
|
||||
return this.getBrowserConstantBool('DASHBOARD_SYSTEM_STATS_ENABLED', true)
|
||||
&& this.getDashboardPollInterval('DASHBOARD_SYSTEM_STATS_POLL_INTERVAL_MS', 3000) > 0
|
||||
},
|
||||
|
||||
applyDashboardRuntimeSettings() {
|
||||
this.stopLogPollingTimer()
|
||||
this.stopRequestHistoryPollingTimer()
|
||||
this.stopSystemStatsPollingTimer()
|
||||
|
||||
if (
|
||||
!this.getBrowserConstantBool('LOG_WEB_COLLECTOR_ENABLED', true)
|
||||
|| this.getBrowserConstantNumber('LOG_WEB_MAX_RECORDS', 5000, { min: 0 }) <= 0
|
||||
|| this.getDashboardPollInterval('DASHBOARD_LOG_POLL_INTERVAL_MS', 1000) <= 0
|
||||
) {
|
||||
this.logs = []
|
||||
this.lastLogSeq = 0
|
||||
this.lastLogTimestamp = 0
|
||||
this.logPollPending = false
|
||||
}
|
||||
|
||||
if (!this.isRequestMonitorEnabled()) {
|
||||
this.requestHistory = []
|
||||
this.requestHistoryRevision = ''
|
||||
this.requestHistoryError = ''
|
||||
this.requestHistoryPendingRefresh = null
|
||||
}
|
||||
|
||||
this.startLogPolling()
|
||||
this.startRequestHistoryPolling()
|
||||
this.startSystemStatsPolling()
|
||||
|
||||
if (this.activeTab === 'monitor' && this.isRequestMonitorEnabled()) {
|
||||
this.fetchRequestHistory({ silent: true, ifChanged: false, force: true }).catch(() => {})
|
||||
}
|
||||
},
|
||||
|
||||
startSystemStatsPolling() {
|
||||
this.ensureSystemStatsVisibilityHandler()
|
||||
const interval = this.getDashboardPollInterval('DASHBOARD_SYSTEM_STATS_POLL_INTERVAL_MS', 3000)
|
||||
if (!this.getBrowserConstantBool('DASHBOARD_SYSTEM_STATS_ENABLED', true) || interval <= 0) {
|
||||
this.stopSystemStatsPollingTimer()
|
||||
return
|
||||
}
|
||||
if (this.systemStatsTimer || this.isDocumentHidden()) {
|
||||
return
|
||||
}
|
||||
|
||||
this.fetchSystemStats({ timeoutMs: 2500 }).catch(() => {})
|
||||
|
||||
this.systemStatsTimer = setInterval(() => {
|
||||
this.fetchSystemStats({ timeoutMs: 2500 }).catch(() => {})
|
||||
}, interval)
|
||||
},
|
||||
|
||||
stopSystemStatsPollingTimer() {
|
||||
if (!this.systemStatsTimer) {
|
||||
return
|
||||
}
|
||||
|
||||
clearInterval(this.systemStatsTimer)
|
||||
this.systemStatsTimer = null
|
||||
},
|
||||
|
||||
ensureSystemStatsVisibilityHandler() {
|
||||
if (
|
||||
this.systemStatsVisibilityHandler
|
||||
|| typeof document === 'undefined'
|
||||
|| typeof document.addEventListener !== 'function'
|
||||
) {
|
||||
return
|
||||
}
|
||||
this.systemStatsVisibilityHandler = () => {
|
||||
if (this.isDocumentHidden()) {
|
||||
this.stopSystemStatsPollingTimer()
|
||||
return
|
||||
}
|
||||
this.startSystemStatsPolling()
|
||||
}
|
||||
document.addEventListener('visibilitychange', this.systemStatsVisibilityHandler)
|
||||
},
|
||||
|
||||
stopSystemStatsPolling() {
|
||||
this.stopSystemStatsPollingTimer()
|
||||
if (
|
||||
this.systemStatsVisibilityHandler
|
||||
&& typeof document !== 'undefined'
|
||||
&& typeof document.removeEventListener === 'function'
|
||||
) {
|
||||
document.removeEventListener('visibilitychange', this.systemStatsVisibilityHandler)
|
||||
}
|
||||
this.systemStatsVisibilityHandler = null
|
||||
},
|
||||
// ========== 初始化 ==========
|
||||
|
||||
initCollapsedStates() {
|
||||
// 环境配置分组默认折叠
|
||||
for (const key of Object.keys(ENV_CONFIG_SCHEMA)) {
|
||||
this.envCollapsed[key] = true;
|
||||
}
|
||||
// 浏览器常量分组默认折叠
|
||||
for (const [key] of Object.entries(BROWSER_CONSTANTS_SCHEMA)) {
|
||||
this.browserConstantsCollapsed[key] = true;
|
||||
}
|
||||
},
|
||||
|
||||
// ========== 夜间模式 ==========
|
||||
|
||||
applyDarkMode() {
|
||||
const isDark = !!this.darkMode
|
||||
const targets = [
|
||||
document.documentElement,
|
||||
document.body,
|
||||
document.getElementById('app')
|
||||
].filter(Boolean)
|
||||
for (const el of targets) {
|
||||
el.classList.remove('dark', 'light')
|
||||
el.classList.add(isDark ? 'dark' : 'light')
|
||||
el.setAttribute('data-theme', isDark ? 'dark' : 'light')
|
||||
}
|
||||
document.documentElement.style.colorScheme = isDark ? 'dark' : 'light'
|
||||
},
|
||||
|
||||
toggleDarkMode() {
|
||||
this.darkMode = !this.darkMode
|
||||
this.applyDarkMode()
|
||||
try {
|
||||
localStorage.setItem('darkMode', this.darkMode.toString())
|
||||
} catch (e) {
|
||||
// ignore storage failures and keep runtime theme switch available
|
||||
}
|
||||
this.notify('已切换到' + (this.darkMode ? '夜间' : '日间') + '模式', 'success')
|
||||
},
|
||||
|
||||
// ========== 菜单控制 ==========
|
||||
|
||||
toggleSelectorMenu() {
|
||||
this.showSelectorMenu = !this.showSelectorMenu
|
||||
},
|
||||
|
||||
toggleImportMenu(e) {
|
||||
if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
|
||||
this.showImportMenu = !this.showImportMenu;
|
||||
this.showExportMenu = false;
|
||||
},
|
||||
|
||||
toggleExportMenu(e) {
|
||||
if (e && typeof e.stopPropagation === 'function') e.stopPropagation();
|
||||
this.showExportMenu = !this.showExportMenu;
|
||||
this.showImportMenu = false;
|
||||
},
|
||||
|
||||
closeAllMenus() {
|
||||
this.showSelectorMenu = false;
|
||||
this.showImportMenu = false;
|
||||
this.showExportMenu = false;
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,468 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——数据、选择器与工作流操作。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 数据操作 ==========
|
||||
|
||||
normalizeConfig(raw) {
|
||||
const norm = {}
|
||||
// 预设内的字段列表(用于清理顶层残留)
|
||||
const PRESET_FIELDS = [
|
||||
'selectors', 'workflow', 'stealth', 'stream_config',
|
||||
'image_extraction', 'file_paste', 'prompt_padding',
|
||||
'extractor_id', 'extractor_verified', 'model_catalog'
|
||||
]
|
||||
for (const [k, v] of Object.entries(raw || {})) {
|
||||
if (v.presets) {
|
||||
// 新格式:保留 presets 结构,确保每个预设有基本字段
|
||||
const normalizedPresets = {}
|
||||
for (const [presetName, presetData] of Object.entries(v.presets)) {
|
||||
normalizedPresets[presetName] = {
|
||||
...presetData,
|
||||
selectors: presetData.selectors || {},
|
||||
workflow: presetData.workflow || [],
|
||||
stealth: !!presetData.stealth
|
||||
}
|
||||
}
|
||||
const presetKeys = Object.keys(normalizedPresets)
|
||||
const configuredDefault = typeof v.default_preset === 'string'
|
||||
? v.default_preset
|
||||
: null
|
||||
const resolvedDefault = (configuredDefault && normalizedPresets[configuredDefault])
|
||||
? configuredDefault
|
||||
: (normalizedPresets['主预设'] ? '主预设' : (presetKeys[0] || '主预设'))
|
||||
// 构建站点对象,只保留 presets,清理预设外的残留字段
|
||||
const siteObj = {
|
||||
presets: normalizedPresets,
|
||||
default_preset: resolvedDefault
|
||||
}
|
||||
// 保留非预设字段(如未来可能的站点级元数据)
|
||||
for (const [field, value] of Object.entries(v)) {
|
||||
if (field !== 'presets' && field !== 'default_preset' && !PRESET_FIELDS.includes(field)) {
|
||||
siteObj[field] = value
|
||||
}
|
||||
}
|
||||
if (siteObj.domain) {
|
||||
siteObj.domain = k
|
||||
}
|
||||
norm[k] = siteObj
|
||||
} else {
|
||||
// 旧格式兼容:包装为预设(后端迁移后不应再出现,但做兜底)
|
||||
norm[k] = {
|
||||
default_preset: '主预设',
|
||||
presets: {
|
||||
'主预设': {
|
||||
...v,
|
||||
selectors: v.selectors || {},
|
||||
workflow: v.workflow || [],
|
||||
stealth: !!v.stealth
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return norm
|
||||
},
|
||||
|
||||
validateConfig() {
|
||||
if (!this.currentDomain || !this.currentConfig) {
|
||||
this.notify('请选择站点', 'warning')
|
||||
return false
|
||||
}
|
||||
|
||||
// 获取当前活跃预设的配置
|
||||
const presetConfig = this.getActivePresetConfig()
|
||||
if (!presetConfig) {
|
||||
this.notify('无法获取预设配置', 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
const selectors = presetConfig.selectors || {}
|
||||
const workflow = presetConfig.workflow || []
|
||||
const hasSelectorActions = workflow.some(step => ['FILL_INPUT', 'SELECT_MODEL', 'CLICK', 'STREAM_WAIT'].includes(step.action))
|
||||
if (hasSelectorActions && Object.keys(selectors).length === 0) {
|
||||
this.notify('至少需要一个选择器', 'warning')
|
||||
return false
|
||||
}
|
||||
|
||||
for (let i = 0; i < workflow.length; i++) {
|
||||
const step = workflow[i]
|
||||
|
||||
if (!step.action) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 缺少动作类型', 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
if (['FILL_INPUT', 'SELECT_MODEL', 'CLICK', 'STREAM_WAIT'].includes(step.action)) {
|
||||
if (!step.target) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 请选择目标选择器', 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (step.action === 'COORD_CLICK') {
|
||||
const x = Number(step.value?.x)
|
||||
const y = Number(step.value?.y)
|
||||
if (!Number.isFinite(x) || !Number.isFinite(y)) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 请输入有效的 X/Y 坐标', 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (step.action === 'COORD_SCROLL') {
|
||||
const startX = Number(step.value?.start_x)
|
||||
const startY = Number(step.value?.start_y)
|
||||
const endX = Number(step.value?.end_x)
|
||||
const endY = Number(step.value?.end_y)
|
||||
if (![startX, startY, endX, endY].every(Number.isFinite)) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 请输入完整的起点/终点坐标', 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
if (step.action === 'KEY_PRESS' && !step.target) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 请输入按键名称', 'error')
|
||||
return false
|
||||
}
|
||||
|
||||
if (step.action === 'WAIT' && (!step.value || step.value <= 0)) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 等待时间必须大于 0', 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < workflow.length; i++) {
|
||||
const step = workflow[i]
|
||||
if (step.action === 'JS_EXEC' && !String(step.value || '').trim()) {
|
||||
this.notify('步骤 ' + (i + 1) + ': 请输入 JavaScript 代码', 'error')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
},
|
||||
|
||||
selectSite(domain) {
|
||||
if (!domain || !this.sites[domain]) return
|
||||
this.flushConfigTabDrafts()
|
||||
this.currentDomain = domain
|
||||
this.siteConfigView = 'editor'
|
||||
this.searchQuery = ''
|
||||
this.$nextTick(() => document.querySelector('.dashboard-scroll-region')?.scrollTo({ top: 0 }))
|
||||
},
|
||||
|
||||
selectSiteFromSearch(domain) {
|
||||
if (!domain) return
|
||||
this.selectSite(domain)
|
||||
this.searchQuery = ''
|
||||
},
|
||||
|
||||
addNewSite() {
|
||||
const domain = prompt('请输入域名(例如: chat.example.com):')
|
||||
if (!domain) return
|
||||
this.siteConfigView = 'editor'
|
||||
|
||||
if (this.sites[domain]) {
|
||||
this.notify('该站点已存在', 'warning')
|
||||
this.currentDomain = domain
|
||||
return
|
||||
}
|
||||
|
||||
this.sites[domain] = {
|
||||
default_preset: '主预设',
|
||||
presets: {
|
||||
'主预设': {
|
||||
selectors: {},
|
||||
workflow: [],
|
||||
stealth: false
|
||||
}
|
||||
}
|
||||
}
|
||||
this.currentDomain = domain
|
||||
this.notify('已创建站点: ' + domain, 'success')
|
||||
},
|
||||
|
||||
confirmDelete(domain) {
|
||||
if (!confirm('确定要删除 ' + domain + ' 的配置吗?')) {
|
||||
return
|
||||
}
|
||||
|
||||
delete this.sites[domain]
|
||||
|
||||
if (this.currentDomain === domain) {
|
||||
this.currentDomain = Object.keys(this.sites)[0] || null
|
||||
}
|
||||
|
||||
this.notify('已删除: ' + domain, 'info')
|
||||
},
|
||||
|
||||
// ========== 选择器操作 ==========
|
||||
|
||||
addSelector(preset) {
|
||||
this.showSelectorMenu = false
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc) return
|
||||
|
||||
let key
|
||||
if (preset === 'custom') {
|
||||
key = prompt('请输入选择器名称(例如: input_box)')
|
||||
if (!key) return
|
||||
} else {
|
||||
key = preset
|
||||
}
|
||||
|
||||
if (pc.selectors[key]) {
|
||||
this.notify('选择器 "' + key + '" 已存在', 'warning')
|
||||
return
|
||||
}
|
||||
|
||||
pc.selectors[key] = ''
|
||||
this.notify('已添加选择器: ' + key, 'success')
|
||||
},
|
||||
|
||||
removeSelector(key) {
|
||||
if (!confirm('确定删除选择器 ' + key + ' 吗?')) {
|
||||
return
|
||||
}
|
||||
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc) return
|
||||
|
||||
delete pc.selectors[key]
|
||||
|
||||
; (pc.workflow || []).forEach(function (step) {
|
||||
if (step.target === key) {
|
||||
step.target = ''
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
updateSelectorKey(oldKey, newKey) {
|
||||
if (!newKey || oldKey === newKey) return
|
||||
|
||||
newKey = newKey.trim()
|
||||
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc) return
|
||||
|
||||
if (pc.selectors[newKey]) {
|
||||
this.notify('该键名已存在', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
pc.selectors[newKey] = pc.selectors[oldKey]
|
||||
delete pc.selectors[oldKey]
|
||||
|
||||
; (pc.workflow || []).forEach(function (step) {
|
||||
if (step.target === oldKey) {
|
||||
step.target = newKey
|
||||
}
|
||||
})
|
||||
},
|
||||
|
||||
// ========== 工作流操作 ==========
|
||||
|
||||
addStep() {
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc) return
|
||||
|
||||
const defaultStep = {
|
||||
action: 'CLICK',
|
||||
target: '',
|
||||
optional: false,
|
||||
value: null
|
||||
}
|
||||
|
||||
if (!pc.workflow) pc.workflow = []
|
||||
pc.workflow.push(defaultStep)
|
||||
},
|
||||
|
||||
removeStep(index) {
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc || !pc.workflow) return
|
||||
|
||||
pc.workflow.splice(index, 1)
|
||||
},
|
||||
|
||||
moveStep(index, direction) {
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc || !pc.workflow) return
|
||||
|
||||
const arr = pc.workflow
|
||||
const newIndex = index + direction
|
||||
|
||||
if (newIndex < 0 || newIndex >= arr.length) return
|
||||
|
||||
const temp = arr[index]
|
||||
arr[index] = arr[newIndex]
|
||||
arr[newIndex] = temp
|
||||
},
|
||||
|
||||
onActionChange(step) {
|
||||
if (step.action === 'SELECT_MODEL') {
|
||||
if (!step.target) step.target = 'model_select_btn'
|
||||
step.value = { timeout: Number(step.value?.timeout ?? 3) }
|
||||
} else if (['FILL_INPUT', 'CLICK', 'STREAM_WAIT'].includes(step.action)) {
|
||||
step.value = null
|
||||
if (!step.target) step.target = ''
|
||||
} else if (step.action === 'PAGE_FETCH') {
|
||||
step.target = ''
|
||||
step.optional = true
|
||||
step.value = null
|
||||
} else if (step.action === 'READONLY_HINT') {
|
||||
step.target = ''
|
||||
const current = (step.value && typeof step.value === 'object' && !Array.isArray(step.value))
|
||||
? step.value
|
||||
: {}
|
||||
step.value = {
|
||||
title: String(current.title || '提示'),
|
||||
text: String(current.text || '这是一条只读提示,不会在执行时触发页面操作。'),
|
||||
tone: ['info', 'success', 'warning', 'danger'].includes(String(current.tone || '').trim().toLowerCase())
|
||||
? String(current.tone || '').trim().toLowerCase()
|
||||
: 'info'
|
||||
}
|
||||
} else if (step.action === 'COORD_CLICK') {
|
||||
step.target = ''
|
||||
step.value = {
|
||||
x: Number(step.value?.x ?? 0),
|
||||
y: Number(step.value?.y ?? 0),
|
||||
random_radius: Number(step.value?.random_radius ?? 10)
|
||||
}
|
||||
} else if (step.action === 'COORD_SCROLL') {
|
||||
step.target = ''
|
||||
step.value = {
|
||||
start_x: Number(step.value?.start_x ?? 0),
|
||||
start_y: Number(step.value?.start_y ?? 0),
|
||||
end_x: Number(step.value?.end_x ?? 0),
|
||||
end_y: Number(step.value?.end_y ?? 300)
|
||||
}
|
||||
} else if (step.action === 'KEY_PRESS') {
|
||||
step.value = null
|
||||
if (!step.target) step.target = 'Enter'
|
||||
} else if (step.action === 'JS_EXEC') {
|
||||
step.target = ''
|
||||
if (!String(step.value || '').trim()) step.value = 'return document.title;'
|
||||
} else if (step.action === 'WAIT') {
|
||||
step.target = ''
|
||||
if (!step.value) step.value = '1.0'
|
||||
}
|
||||
},
|
||||
|
||||
showTemplates() {
|
||||
this.showStepTemplates = true
|
||||
},
|
||||
|
||||
applyTemplate(type) {
|
||||
const templates = {
|
||||
'default': [
|
||||
{ action: 'CLICK', target: 'new_chat_btn', optional: true, value: null },
|
||||
{ action: 'WAIT', target: '', optional: false, value: '0.5' },
|
||||
{ action: 'FILL_INPUT', target: 'input_box', optional: false, value: null },
|
||||
{ action: 'CLICK', target: 'send_btn', optional: true, value: null },
|
||||
{ action: 'KEY_PRESS', target: 'Enter', optional: true, value: null },
|
||||
{ action: 'STREAM_WAIT', target: 'result_container', optional: false, value: null }
|
||||
],
|
||||
'simple': [
|
||||
{ action: 'FILL_INPUT', target: 'input_box', optional: false, value: null },
|
||||
{ action: 'KEY_PRESS', target: 'Enter', optional: false, value: null },
|
||||
{ action: 'STREAM_WAIT', target: 'result_container', optional: false, value: null }
|
||||
],
|
||||
'experimental_hint': [
|
||||
{ action: 'READONLY_HINT', target: '', optional: false, value: { title: '提示', text: '这是一条只读提示,不会影响执行,只用于说明当前工作流中的特殊行为。', tone: 'info' } },
|
||||
{ action: 'PAGE_FETCH', target: '', optional: true, value: null },
|
||||
{ action: 'FILL_INPUT', target: 'input_box', optional: false, value: null },
|
||||
{ action: 'KEY_PRESS', target: 'Enter', optional: false, value: null },
|
||||
{ action: 'STREAM_WAIT', target: 'result_container', optional: false, value: null }
|
||||
],
|
||||
'battle_winner': [
|
||||
{ action: 'WAIT', target: '', optional: false, value: 2 },
|
||||
{ action: 'FILL_INPUT', target: 'input_box', optional: false, value: null },
|
||||
{ action: 'WAIT', target: '', optional: false, value: 0.5 },
|
||||
{ action: 'CLICK', target: 'retry_send_btn', optional: true, value: null },
|
||||
{ action: 'WAIT', target: '', optional: false, value: 0.2 },
|
||||
{ action: 'CLICK', target: 'send_btn', optional: false, value: null },
|
||||
{ action: 'STREAM_WAIT', target: 'result_container', optional: false, value: null }
|
||||
],
|
||||
'battle_left': [
|
||||
{ action: 'WAIT', target: '', optional: false, value: 1 },
|
||||
{ action: 'FILL_INPUT', target: 'input_box', optional: false, value: null },
|
||||
{ action: 'CLICK', target: 'retry_send_btn', optional: true, value: null },
|
||||
{ action: 'WAIT', target: '', optional: false, value: 0.8 },
|
||||
{ action: 'CLICK', target: 'send_btn', optional: true, value: null },
|
||||
{ action: 'STREAM_WAIT', target: 'result_container', optional: false, value: null }
|
||||
],
|
||||
'battle_right': [
|
||||
{ action: 'WAIT', target: '', optional: false, value: 2 },
|
||||
{ action: 'FILL_INPUT', target: 'input_box', optional: false, value: null },
|
||||
{ action: 'WAIT', target: '', optional: false, value: 0.5 },
|
||||
{ action: 'CLICK', target: 'retry_send_btn', optional: true, value: null },
|
||||
{ action: 'WAIT', target: '', optional: false, value: 0.2 },
|
||||
{ action: 'CLICK', target: 'send_btn', optional: false, value: null },
|
||||
{ action: 'STREAM_WAIT', target: 'result_container', optional: false, value: null }
|
||||
]
|
||||
}
|
||||
|
||||
if (!confirm('这将覆盖当前的工作流配置,确定继续吗?')) {
|
||||
return
|
||||
}
|
||||
|
||||
const pc = this.getActivePresetConfig()
|
||||
if (!pc) return
|
||||
pc.workflow = JSON.parse(JSON.stringify(templates[type]))
|
||||
|
||||
const battleParserMap = {
|
||||
battle_winner: 'lmarena_battle_winner',
|
||||
battle_left: 'lmarena_battle_side_left',
|
||||
battle_right: 'lmarena_battle_side_right'
|
||||
}
|
||||
if (battleParserMap[type]) {
|
||||
pc.selectors = {
|
||||
...(pc.selectors || {}),
|
||||
retry_send_btn: pc.selectors?.retry_send_btn || 'button[aria-label="Rerun stopped messages"], button[data-slot="tooltip-trigger"]:has(svg path[d*="21.8883"])',
|
||||
send_btn: pc.selectors?.send_btn || 'button[aria-label="Send message"][type="submit"]:not(:disabled):not([aria-disabled="true"]), button[aria-label="Stop generation"]',
|
||||
generating_indicator: pc.selectors?.generating_indicator || 'button[aria-label="Stop generation"]'
|
||||
}
|
||||
pc.stream_config = {
|
||||
...((pc && pc.stream_config) || {}),
|
||||
mode: 'network',
|
||||
send_confirmation: {
|
||||
...(((pc && pc.stream_config) || {}).send_confirmation || {}),
|
||||
max_retry_count: 0,
|
||||
retry_on_unconfirmed_send: false,
|
||||
post_click_observe_window: 0.5,
|
||||
pre_retry_probe_window: 0,
|
||||
retry_observe_window: 0,
|
||||
trust_generating_indicator: true,
|
||||
trust_network_activity: true
|
||||
},
|
||||
network: {
|
||||
...(((pc && pc.stream_config) || {}).network || {}),
|
||||
parser: battleParserMap[type],
|
||||
url_pattern: '**/nextjs-api/stream/create-evaluation**',
|
||||
method: 'POST',
|
||||
listen_pattern: '/nextjs-api/stream/create-evaluation',
|
||||
silence_threshold: 10,
|
||||
response_interval: 1
|
||||
}
|
||||
}
|
||||
}
|
||||
this.showStepTemplates = false
|
||||
this.notify('模板已应用', 'success')
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,177 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——日志。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 日志相关 ==========
|
||||
|
||||
async pollLogs(options = {}) {
|
||||
if (this.pauseLogs || document.visibilityState === 'hidden') return;
|
||||
if (
|
||||
!this.getBrowserConstantBool('LOG_WEB_COLLECTOR_ENABLED', true)
|
||||
|| this.getBrowserConstantNumber('LOG_WEB_MAX_RECORDS', 5000, { min: 0 }) <= 0
|
||||
) {
|
||||
this.logs = [];
|
||||
this.lastLogSeq = 0;
|
||||
this.lastLogTimestamp = 0;
|
||||
this.logPollPending = false;
|
||||
return;
|
||||
}
|
||||
if (this.isPollingLogs) {
|
||||
this.logPollPending = true;
|
||||
return;
|
||||
}
|
||||
if (options && options.background) {
|
||||
const now = Date.now();
|
||||
const backgroundInterval = this.getDashboardPollInterval('DASHBOARD_LOG_BACKGROUND_POLL_INTERVAL_MS', 5000)
|
||||
|| this.getDashboardPollInterval('DASHBOARD_LOG_POLL_INTERVAL_MS', 1000);
|
||||
if (this.lastBackgroundLogPollAt && backgroundInterval > 0 && now - this.lastBackgroundLogPollAt < backgroundInterval) {
|
||||
return;
|
||||
}
|
||||
this.lastBackgroundLogPollAt = now;
|
||||
}
|
||||
|
||||
this.isPollingLogs = true;
|
||||
const generation = Number(this.logGeneration || 0);
|
||||
try {
|
||||
const result = await this.apiRequest('/api/logs?after_seq=' + this.lastLogSeq);
|
||||
if (generation !== Number(this.logGeneration || 0)) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
!this.getBrowserConstantBool('LOG_WEB_COLLECTOR_ENABLED', true)
|
||||
|| this.getBrowserConstantNumber('LOG_WEB_MAX_RECORDS', 5000, { min: 0 }) <= 0
|
||||
) {
|
||||
this.logs = [];
|
||||
this.lastLogSeq = 0;
|
||||
this.lastLogTimestamp = 0;
|
||||
this.logPollPending = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.cleared) {
|
||||
this.logs = [];
|
||||
this.lastLogSeq = 0;
|
||||
this.lastLogTimestamp = 0;
|
||||
}
|
||||
|
||||
if (result.logs && result.logs.length > 0) {
|
||||
const nextLogs = result.logs.map(log => {
|
||||
const messageText = log.message_text || log.display_message || log.message || '';
|
||||
const kind = log.kind || log.level;
|
||||
return {
|
||||
id: log.seq || (Date.now() + Math.random()),
|
||||
seq: log.seq || 0,
|
||||
timestamp: new Date(log.timestamp * 1000).toLocaleTimeString() + '.' +
|
||||
String(Math.floor((log.timestamp % 1) * 1000)).padStart(3, '0'),
|
||||
level: this.normalizeLogLevel(kind, messageText),
|
||||
rawLevel: String(log.level || '').toUpperCase(),
|
||||
kind: String(kind || '').toUpperCase(),
|
||||
logger: log.logger || '',
|
||||
requestId: log.request_id || 'SYSTEM',
|
||||
requestTag: log.request_tag || log.request_id || 'SYSTEM',
|
||||
message: log.display_message || log.message || messageText,
|
||||
messageText,
|
||||
originalMessageText: log.original_message_text || messageText,
|
||||
messageAlias: log.message_alias || ''
|
||||
}
|
||||
});
|
||||
const maxLogs = Math.floor(this.getBrowserConstantNumber('LOG_WEB_MAX_RECORDS', 5000, { min: 0, max: 10000 }));
|
||||
this.logs = maxLogs > 0 ? this.logs.concat(nextLogs).slice(-maxLogs) : [];
|
||||
}
|
||||
this.lastLogSeq = Number(result.next_seq || this.lastLogSeq || 0);
|
||||
this.lastLogTimestamp = Number(result.timestamp || this.lastLogTimestamp || 0);
|
||||
} catch (error) {
|
||||
if (generation === Number(this.logGeneration || 0)) {
|
||||
console.debug('日志轮询失败:', error.message);
|
||||
}
|
||||
} finally {
|
||||
if (generation === Number(this.logGeneration || 0)) {
|
||||
this.isPollingLogs = false;
|
||||
if (this.logPollPending && !this.pauseLogs && document.visibilityState !== 'hidden') {
|
||||
this.logPollPending = false;
|
||||
this.pollLogs({ ...(options || {}), background: false }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
normalizeLogLevel(level, message) {
|
||||
const normalized = String(level || '').toUpperCase();
|
||||
if (normalized === 'WARNING') return 'WARN';
|
||||
if (normalized === 'CRITICAL') return 'ERROR';
|
||||
if (normalized === 'SUCCESS') return 'OK';
|
||||
if (normalized === 'DEBUG' || normalized === 'WARN' || normalized === 'ERROR') {
|
||||
return normalized;
|
||||
}
|
||||
|
||||
if (normalized === 'INFO') {
|
||||
if (message.includes('[AI]')) return 'AI';
|
||||
if (message.includes('[OK]') || message.includes('[SUCCESS]') || message.includes('✅')) return 'OK';
|
||||
return 'INFO';
|
||||
}
|
||||
|
||||
if (message.includes('[AI]')) return 'AI';
|
||||
if (message.includes('[ERROR]')) return 'ERROR';
|
||||
if (message.includes('[WARN]') || message.includes('[WARNING]')) return 'WARN';
|
||||
if (message.includes('[OK]') || message.includes('[SUCCESS]') || message.includes('✅')) return 'OK';
|
||||
return 'INFO';
|
||||
},
|
||||
|
||||
getLogColorClass(level) {
|
||||
const colors = {
|
||||
'DEBUG': 'bg-slate-50 dark:bg-slate-900/30',
|
||||
'INFO': 'bg-green-50 dark:bg-green-900/20',
|
||||
'AI': 'bg-purple-50 dark:bg-purple-900/20',
|
||||
'OK': 'bg-green-50 dark:bg-green-900/20',
|
||||
'WARN': 'bg-yellow-50 dark:bg-yellow-900/20',
|
||||
'ERROR': 'bg-red-50 dark:bg-red-900/20',
|
||||
'KEY': 'bg-sky-50 dark:bg-sky-900/20'
|
||||
};
|
||||
return colors[level] || colors['INFO'];
|
||||
},
|
||||
|
||||
getLogLevelClass(level) {
|
||||
const colors = {
|
||||
'DEBUG': 'text-slate-500 dark:text-slate-400',
|
||||
'INFO': 'text-green-600 dark:text-green-400',
|
||||
'AI': 'text-purple-600 dark:text-purple-400',
|
||||
'OK': 'text-green-600 dark:text-green-400',
|
||||
'WARN': 'text-yellow-600 dark:text-yellow-400',
|
||||
'ERROR': 'text-red-600 dark:text-red-400',
|
||||
'KEY': 'text-sky-500 dark:text-sky-300'
|
||||
};
|
||||
return colors[level] || colors['INFO'];
|
||||
},
|
||||
|
||||
clearLogs() {
|
||||
if (confirm('确定清除所有日志吗?')) {
|
||||
this.logGeneration = Number(this.logGeneration || 0) + 1;
|
||||
this.logs = [];
|
||||
this.lastLogSeq = 0;
|
||||
this.lastLogTimestamp = 0;
|
||||
this.isPollingLogs = false;
|
||||
this.logPollPending = false;
|
||||
|
||||
this.apiRequest('/api/logs', { method: 'DELETE' })
|
||||
.catch(() => { });
|
||||
|
||||
this.notify('日志已清除', 'success');
|
||||
}
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,206 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——图片配置。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 图片配置 (新增) ==========
|
||||
|
||||
// 🆕 更新图片配置
|
||||
async updateImageConfig(newConfig) {
|
||||
if (!this.currentDomain || !this.currentConfig) return;
|
||||
|
||||
const domain = this.currentDomain
|
||||
const pc = this.getActivePresetConfig()
|
||||
const presetName = this.getActivePresetName()
|
||||
const nextConfig = JSON.parse(JSON.stringify(newConfig || {}))
|
||||
const saveSeq = Number(this.imageConfigSaveSeq || 0) + 1
|
||||
this.imageConfigSaveSeq = saveSeq
|
||||
|
||||
if (pc) pc.image_extraction = nextConfig;
|
||||
|
||||
const previousSave = this.imageConfigSaveQueue || Promise.resolve()
|
||||
const saveRequest = previousSave
|
||||
.catch(() => undefined)
|
||||
.then(() => {
|
||||
const payload = { ...nextConfig, preset_name: presetName }
|
||||
return this.apiRequest(`/api/sites/${encodeURIComponent(domain)}/image-config`, {
|
||||
method: 'PUT',
|
||||
body: JSON.stringify(payload)
|
||||
})
|
||||
})
|
||||
this.imageConfigSaveQueue = saveRequest
|
||||
|
||||
try {
|
||||
await saveRequest
|
||||
if (
|
||||
saveSeq === this.imageConfigSaveSeq
|
||||
&& domain === this.currentDomain
|
||||
&& presetName === this.getActivePresetName()
|
||||
) {
|
||||
this.notify('多模态提取配置已保存', 'success')
|
||||
}
|
||||
} catch (error) {
|
||||
if (
|
||||
saveSeq === this.imageConfigSaveSeq
|
||||
&& domain === this.currentDomain
|
||||
&& presetName === this.getActivePresetName()
|
||||
) {
|
||||
console.error('保存图片配置失败:', error)
|
||||
this.notify('保存多模态提取配置失败: ' + error.message, 'error')
|
||||
await this.reloadConfig()
|
||||
}
|
||||
} finally {
|
||||
if (this.imageConfigSaveQueue === saveRequest) {
|
||||
this.imageConfigSaveQueue = null
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// 🆕 重新加载当前站点配置(应用预设后调用)
|
||||
async reloadConfig() {
|
||||
if (!this.currentDomain) return;
|
||||
|
||||
try {
|
||||
const data = await this.apiRequest('/api/config/' + encodeURIComponent(this.currentDomain));
|
||||
// 返回的数据已经是预设格式 { presets: { ... } }
|
||||
// 对其进行规范化确保结构完整
|
||||
const normalized = this.normalizeConfig({ [this.currentDomain]: data })
|
||||
if (normalized[this.currentDomain]) {
|
||||
this.sites[this.currentDomain] = normalized[this.currentDomain]
|
||||
}
|
||||
this.notify('配置已重新加载', 'success');
|
||||
} catch (error) {
|
||||
console.error('重新加载配置失败:', error);
|
||||
this.notify('加载失败: ' + error.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
async openMainCompareSummaryDialog() {
|
||||
this.showMainCompareSummaryDialog = true;
|
||||
await this.loadMainCompareSummary();
|
||||
},
|
||||
|
||||
closeMainCompareSummaryDialog() {
|
||||
this.showMainCompareSummaryDialog = false;
|
||||
},
|
||||
|
||||
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 loadMainCompareSummary() {
|
||||
this.mainCompareSummaryLoading = true;
|
||||
this.mainCompareSummaryError = '';
|
||||
try {
|
||||
const data = await this.apiRequest('/api/config/compare-main-summary');
|
||||
this.mainCompareSummaryItems = Array.isArray(data.items) ? data.items : [];
|
||||
this.mainCompareSummaryCounts = {
|
||||
same: 0,
|
||||
different: 0,
|
||||
local_only_preset: 0,
|
||||
local_only_site: 0,
|
||||
main_only_preset: 0,
|
||||
main_only_site: 0,
|
||||
...(data.counts || {})
|
||||
};
|
||||
this.mainCompareSummaryPath = String(data.path || 'config/sites/index.json').trim() || 'config/sites/index.json';
|
||||
this.mainCompareSummarySource = {
|
||||
repository: '',
|
||||
branch: 'main',
|
||||
status: '',
|
||||
stale: false,
|
||||
fetched_at: '',
|
||||
checked_at: '',
|
||||
warning: '',
|
||||
...(data.source || {})
|
||||
};
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.mainCompareSummaryItems = [];
|
||||
this.mainCompareSummarySource = {
|
||||
repository: '',
|
||||
branch: 'main',
|
||||
status: '',
|
||||
stale: false,
|
||||
fetched_at: '',
|
||||
checked_at: '',
|
||||
warning: ''
|
||||
};
|
||||
this.mainCompareSummaryError = formatGitCompareErrorText(error);
|
||||
return false;
|
||||
} finally {
|
||||
this.mainCompareSummaryLoading = false;
|
||||
}
|
||||
},
|
||||
|
||||
getMainCompareStatusClass(status) {
|
||||
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 === 'local_only_preset') {
|
||||
return 'border-blue-200 bg-blue-50 text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-300';
|
||||
}
|
||||
if (status === 'local_only_site') {
|
||||
return 'border-rose-200 bg-rose-50 text-rose-700 dark:border-rose-800 dark:bg-rose-900/30 dark:text-rose-300';
|
||||
}
|
||||
return 'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-800 dark:bg-emerald-900/30 dark:text-emerald-300';
|
||||
},
|
||||
|
||||
getMainCompareStatusText(status) {
|
||||
if (status === 'different') return '字段不同';
|
||||
if (status === 'local_only_preset') return '本地自定义预设';
|
||||
if (status === 'local_only_site') return '本地自定义站点';
|
||||
return '与官方一致';
|
||||
},
|
||||
|
||||
async waitForConfigTabRef() {
|
||||
for (let attempt = 0; attempt < 30; attempt++) {
|
||||
await this.$nextTick();
|
||||
const ref = this.$refs.configTab;
|
||||
if (ref && typeof ref.openConfigCompareForPreset === 'function') {
|
||||
return ref;
|
||||
}
|
||||
await new Promise(resolve => setTimeout(resolve, 60));
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
async openMainCompareDetail(item) {
|
||||
if (!item || !item.domain) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.showMainCompareSummaryDialog = false;
|
||||
this.activeTab = 'config';
|
||||
this.currentDomain = item.domain;
|
||||
this.siteConfigView = 'editor';
|
||||
|
||||
const configTab = await this.waitForConfigTabRef();
|
||||
if (!configTab) {
|
||||
this.notify('配置面板尚未准备好', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const targetPreset = String(item.local_preset_name || '').trim();
|
||||
await configTab.openConfigCompareForPreset(targetPreset);
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,479 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——元素定义与预设辅助。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 元素定义管理方法 ==========
|
||||
|
||||
async loadSelectorDefinitions() {
|
||||
this.isLoadingDefinitions = true;
|
||||
try {
|
||||
const data = await this.apiRequest('/api/settings/selector-definitions');
|
||||
this.selectorDefinitions = data.definitions || DEFAULT_SELECTOR_DEFINITIONS;
|
||||
this.selectorDefinitionsOriginal = JSON.parse(JSON.stringify(this.selectorDefinitions));
|
||||
} catch (error) {
|
||||
console.error('加载元素定义失败:', error);
|
||||
this.selectorDefinitions = JSON.parse(JSON.stringify(DEFAULT_SELECTOR_DEFINITIONS));
|
||||
this.selectorDefinitionsOriginal = JSON.parse(JSON.stringify(this.selectorDefinitions));
|
||||
} finally {
|
||||
this.isLoadingDefinitions = false;
|
||||
}
|
||||
},
|
||||
|
||||
async saveSelectorDefinitions() {
|
||||
this.isSavingDefinitions = true;
|
||||
try {
|
||||
await this.apiRequest('/api/settings/selector-definitions', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ definitions: this.selectorDefinitions })
|
||||
});
|
||||
|
||||
this.selectorDefinitionsOriginal = JSON.parse(JSON.stringify(this.selectorDefinitions));
|
||||
this.notify('元素定义已保存', 'success');
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error');
|
||||
} finally {
|
||||
this.isSavingDefinitions = false;
|
||||
}
|
||||
},
|
||||
|
||||
async resetSelectorDefinitions() {
|
||||
if (!confirm('确定要重置元素定义为默认值吗?')) return;
|
||||
|
||||
try {
|
||||
const data = await this.apiRequest('/api/settings/selector-definitions/reset', {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
this.selectorDefinitions = data.definitions;
|
||||
this.selectorDefinitionsOriginal = JSON.parse(JSON.stringify(this.selectorDefinitions));
|
||||
this.notify('已重置为默认值', 'success');
|
||||
} catch (error) {
|
||||
this.notify('重置失败: ' + error.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
toggleDefinitionEnabled(index) {
|
||||
const def = this.selectorDefinitions[index];
|
||||
|
||||
if (def.required) {
|
||||
this.notify('必需字段不能禁用', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
def.enabled = !def.enabled;
|
||||
},
|
||||
|
||||
openAddDefinitionDialog() {
|
||||
this.newDefinition = {
|
||||
key: '',
|
||||
description: '',
|
||||
enabled: true,
|
||||
required: false
|
||||
};
|
||||
this.editingDefinitionIndex = null;
|
||||
this.showAddDefinitionDialog = true;
|
||||
},
|
||||
|
||||
openEditDefinitionDialog(index) {
|
||||
const def = this.selectorDefinitions[index];
|
||||
this.newDefinition = { ...def };
|
||||
this.editingDefinitionIndex = index;
|
||||
this.showAddDefinitionDialog = true;
|
||||
},
|
||||
|
||||
saveDefinition() {
|
||||
if (!this.newDefinition.key.trim()) {
|
||||
this.notify('请输入关键词', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.newDefinition.description.trim()) {
|
||||
this.notify('请输入描述', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const key = this.newDefinition.key.trim();
|
||||
const existingIndex = this.selectorDefinitions.findIndex(d => d.key === key);
|
||||
|
||||
if (this.editingDefinitionIndex === null) {
|
||||
// 新增模式
|
||||
if (existingIndex !== -1) {
|
||||
this.notify('关键词已存在', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.selectorDefinitions.push({
|
||||
key: key,
|
||||
description: this.newDefinition.description.trim(),
|
||||
enabled: this.newDefinition.enabled,
|
||||
required: false
|
||||
});
|
||||
} else {
|
||||
// 编辑模式
|
||||
if (existingIndex !== -1 && existingIndex !== this.editingDefinitionIndex) {
|
||||
this.notify('关键词已存在', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.selectorDefinitions[this.editingDefinitionIndex] = {
|
||||
...this.selectorDefinitions[this.editingDefinitionIndex],
|
||||
key: key,
|
||||
description: this.newDefinition.description.trim(),
|
||||
enabled: this.newDefinition.enabled
|
||||
};
|
||||
}
|
||||
|
||||
this.showAddDefinitionDialog = false;
|
||||
this.notify('已添加,请点击保存以应用', 'info');
|
||||
},
|
||||
|
||||
removeDefinition(index) {
|
||||
const def = this.selectorDefinitions[index];
|
||||
|
||||
if (def.required) {
|
||||
this.notify('必需字段不能删除', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm('确定要删除 "' + def.key + '" 吗?')) return;
|
||||
|
||||
this.selectorDefinitions.splice(index, 1);
|
||||
this.notify('已删除,请点击保存以应用', 'info');
|
||||
},
|
||||
|
||||
moveDefinition(index, direction) {
|
||||
const newIndex = index + direction;
|
||||
if (newIndex < 0 || newIndex >= this.selectorDefinitions.length) return;
|
||||
|
||||
const temp = this.selectorDefinitions[index];
|
||||
this.selectorDefinitions[index] = this.selectorDefinitions[newIndex];
|
||||
this.selectorDefinitions[newIndex] = temp;
|
||||
},
|
||||
|
||||
changeTab(tab) {
|
||||
this.markTabAsVisited(tab)
|
||||
this.activeTab = tab;
|
||||
},
|
||||
|
||||
handleSidebarPrimaryAction(tab) {
|
||||
if (tab === 'commands') {
|
||||
this.changeTab('commands')
|
||||
this.$nextTick(() => {
|
||||
if (this.$refs.commandsTab && typeof this.$refs.commandsTab.openNewCommand === 'function') {
|
||||
this.$refs.commandsTab.openNewCommand()
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
this.addNewSite()
|
||||
},
|
||||
|
||||
async ensureTabDataLoaded(tab) {
|
||||
if (tab === 'monitor') {
|
||||
const now = Date.now()
|
||||
const stale = now - Number(this.requestHistoryFetchedAt || 0) > 2000
|
||||
const loaders = [];
|
||||
if (this.isRequestMonitorEnabled()) {
|
||||
loaders.push(this.fetchRequestHistory({ silent: true, ifChanged: !stale }));
|
||||
} else {
|
||||
this.requestHistory = [];
|
||||
this.requestHistoryRevision = '';
|
||||
this.requestHistoryError = '';
|
||||
}
|
||||
if (this.isSystemStatsPollingEnabled()) {
|
||||
loaders.push(this.fetchSystemStats({ timeoutMs: 2500 }));
|
||||
}
|
||||
await Promise.all(loaders);
|
||||
return;
|
||||
}
|
||||
if (tab === 'settings' && !this.hasLoadedSettings) {
|
||||
this.hasLoadedSettings = true;
|
||||
await Promise.all([
|
||||
this.loadEnvConfig(),
|
||||
this.loadBrowserConstants(),
|
||||
this.loadUpdatePreserveSettings(),
|
||||
this.loadSelectorDefinitions(),
|
||||
this.loadReleases()
|
||||
]);
|
||||
return;
|
||||
}
|
||||
},
|
||||
|
||||
async fetchRequestHistory({ silent = false, ifChanged = false, force = false } = {}) {
|
||||
if (!this.isRequestMonitorEnabled()) {
|
||||
this.requestHistory = [];
|
||||
this.requestHistoryMaxRecords = 0;
|
||||
this.requestHistoryRevision = '';
|
||||
this.requestHistoryError = '';
|
||||
this.requestHistoryPendingRefresh = null;
|
||||
return this.requestHistory;
|
||||
}
|
||||
if (this.requestHistoryLoading) {
|
||||
this.requestHistoryPendingRefresh = {
|
||||
silent: this.requestHistoryPendingRefresh
|
||||
? (this.requestHistoryPendingRefresh.silent && silent)
|
||||
: silent,
|
||||
ifChanged: this.requestHistoryPendingRefresh
|
||||
? (this.requestHistoryPendingRefresh.ifChanged && ifChanged)
|
||||
: ifChanged,
|
||||
force: Boolean(force || (this.requestHistoryPendingRefresh && this.requestHistoryPendingRefresh.force))
|
||||
};
|
||||
return this.requestHistory;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (!force && ifChanged && now - Number(this.requestHistoryFetchedAt || 0) < 1200) {
|
||||
return this.requestHistory;
|
||||
}
|
||||
this.requestHistoryLoading = true;
|
||||
if (!silent) {
|
||||
this.requestHistoryError = '';
|
||||
}
|
||||
const requestSeq = Number(this.requestHistoryRequestSeq || 0) + 1;
|
||||
this.requestHistoryRequestSeq = requestSeq;
|
||||
try {
|
||||
const maxRecords = this.getBrowserConstantNumber('REQUEST_MONITOR_MAX_RECORDS', 200, { min: 0, max: 2000 });
|
||||
if (maxRecords <= 0) {
|
||||
this.requestHistory = [];
|
||||
this.requestHistoryMaxRecords = 0;
|
||||
this.requestHistoryRevision = '';
|
||||
this.requestHistoryError = '';
|
||||
return this.requestHistory;
|
||||
}
|
||||
const params = new URLSearchParams({ limit: String(Math.max(1, Math.floor(maxRecords))) });
|
||||
if (ifChanged && !force && this.requestHistoryRevision) {
|
||||
params.set('if_revision', String(this.requestHistoryRevision));
|
||||
}
|
||||
const data = await this.apiRequest('/api/system/request-history?' + params.toString(), {
|
||||
timeoutMs: 5000
|
||||
});
|
||||
if (!this.isRequestMonitorEnabled()) {
|
||||
this.requestHistory = [];
|
||||
this.requestHistoryRevision = '';
|
||||
this.requestHistoryFetchedAt = Date.now();
|
||||
this.requestHistoryError = '';
|
||||
return this.requestHistory;
|
||||
}
|
||||
if (requestSeq !== this.requestHistoryRequestSeq) {
|
||||
return this.requestHistory;
|
||||
}
|
||||
if (data && data.enabled === false) {
|
||||
this.requestHistory = [];
|
||||
this.requestHistoryMaxRecords = 0;
|
||||
this.requestHistoryRevision = '';
|
||||
this.requestHistoryFetchedAt = Date.now();
|
||||
this.requestHistoryError = '';
|
||||
return this.requestHistory;
|
||||
}
|
||||
const revision = String(data.revision || '');
|
||||
this.requestHistoryMaxRecords = Math.max(
|
||||
0,
|
||||
Number(data && data.max_records || maxRecords || 0)
|
||||
);
|
||||
if (data.not_modified && revision && revision === this.requestHistoryRevision) {
|
||||
this.requestHistoryFetchedAt = Date.now();
|
||||
this.requestHistoryError = '';
|
||||
return this.requestHistory;
|
||||
}
|
||||
if (!ifChanged || force || !this.requestHistoryRevision || revision !== this.requestHistoryRevision) {
|
||||
const detailCache = new Map(
|
||||
this.requestHistory
|
||||
.filter(item => item && item.detail_loaded && item.id)
|
||||
.map(item => [String(item.history_key || item.id), {
|
||||
prompt: item.prompt,
|
||||
response: item.response,
|
||||
error_stack: item.error_stack,
|
||||
// 修复:这里原本缓存 payload / response_payload,但后端从未产出这两个键,
|
||||
// 每次轮询都会把两个 undefined 键塞进每条记录,已删除。
|
||||
// 同时补上 error_message / summary:不缓存的话,下一次轮询会用列表里的
|
||||
// 截断版本覆盖掉已加载的完整详情。
|
||||
error_message: item.error_message,
|
||||
summary: item.summary,
|
||||
detail_loaded: true,
|
||||
has_detail: true
|
||||
}])
|
||||
);
|
||||
const records = Array.isArray(data.records) ? data.records : [];
|
||||
this.requestHistory = records.map(item => {
|
||||
const cached = detailCache.get(String(item && (item.history_key || item.id) || ''));
|
||||
return cached ? { ...item, ...cached, detail_loaded: true, has_detail: true } : item;
|
||||
});
|
||||
this.requestHistoryRevision = revision;
|
||||
}
|
||||
this.requestHistoryFetchedAt = Date.now();
|
||||
this.requestHistoryError = '';
|
||||
return this.requestHistory;
|
||||
} catch (error) {
|
||||
if (!silent) {
|
||||
this.requestHistoryError = error.message || '请求历史加载失败';
|
||||
}
|
||||
return this.requestHistory;
|
||||
} finally {
|
||||
if (requestSeq === this.requestHistoryRequestSeq) {
|
||||
this.requestHistoryLoading = false;
|
||||
const pending = this.requestHistoryPendingRefresh;
|
||||
this.requestHistoryPendingRefresh = null;
|
||||
if (pending) {
|
||||
this.fetchRequestHistory(pending).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
async fetchRequestHistoryDetail(requestId) {
|
||||
const id = String(requestId || '').trim();
|
||||
if (!id || this.requestHistoryDetailLoading[id]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const matchesRequestHistoryId = (item) => {
|
||||
if (!item) return false;
|
||||
return String(item.history_key || '').trim() === id || String(item.id || '').trim() === id;
|
||||
};
|
||||
const existingIndex = this.requestHistory.findIndex(matchesRequestHistoryId);
|
||||
if (existingIndex >= 0 && this.requestHistory[existingIndex].detail_loaded) {
|
||||
return this.requestHistory[existingIndex];
|
||||
}
|
||||
|
||||
this.requestHistoryDetailLoading = {
|
||||
...this.requestHistoryDetailLoading,
|
||||
[id]: true
|
||||
};
|
||||
try {
|
||||
const detail = await this.apiRequest('/api/system/request-history/' + encodeURIComponent(id), {
|
||||
timeoutMs: 5000
|
||||
});
|
||||
const detailKey = String(detail && detail.history_key || '').trim();
|
||||
const detailId = String(detail && detail.id || '').trim();
|
||||
const index = this.requestHistory.findIndex(item => {
|
||||
if (!item) return false;
|
||||
return String(item.history_key || '').trim() === (detailKey || id)
|
||||
|| String(item.history_key || '').trim() === id
|
||||
|| (
|
||||
!detailKey
|
||||
&& detailId
|
||||
&& String(item.id || '').trim() === detailId
|
||||
)
|
||||
|| String(item.id || '').trim() === id;
|
||||
});
|
||||
if (index >= 0) {
|
||||
const current = this.requestHistory[index];
|
||||
const detailPayload = detail && typeof detail === 'object' ? detail : {};
|
||||
const updated = {
|
||||
...current,
|
||||
prompt: detailPayload.prompt ?? current.prompt,
|
||||
response: detailPayload.response ?? current.response,
|
||||
error_stack: detailPayload.error_stack ?? current.error_stack,
|
||||
// 修复:列表投影会把 error_message 截到 800 字、summary 截到 240 字,
|
||||
// 详情接口返回的才是完整原文;此前白名单漏掉这两个键,详情抽屉永远显示截断版本。
|
||||
error_message: detailPayload.error_message ?? current.error_message,
|
||||
summary: detailPayload.summary ?? current.summary,
|
||||
// 修复:这里原本还合并 payload / response_payload,但后端从未产出这两个键,只会
|
||||
// 给记录塞进两个 undefined 字段,已删除。
|
||||
token_estimate: detailPayload.token_estimate ?? current.token_estimate,
|
||||
detail_text_lengths: detailPayload.detail_text_lengths ?? current.detail_text_lengths,
|
||||
detail_loaded: true,
|
||||
has_detail: true
|
||||
};
|
||||
const nextHistory = this.requestHistory.slice();
|
||||
nextHistory[index] = updated;
|
||||
this.requestHistory = nextHistory;
|
||||
return updated;
|
||||
}
|
||||
return detail || null;
|
||||
} catch (error) {
|
||||
this.notify('加载请求详情失败: ' + error.message, 'error');
|
||||
return null;
|
||||
} finally {
|
||||
const nextLoading = { ...this.requestHistoryDetailLoading };
|
||||
delete nextLoading[id];
|
||||
this.requestHistoryDetailLoading = nextLoading;
|
||||
}
|
||||
},
|
||||
|
||||
downloadDataAsJson(filename, payloadText) {
|
||||
const blob = new Blob([payloadText], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
URL.revokeObjectURL(url);
|
||||
},
|
||||
|
||||
// ========== 预设辅助方法 ==========
|
||||
|
||||
getActivePresetName() {
|
||||
try {
|
||||
if (this.$refs.configTab && this.$refs.configTab.selectedPreset) {
|
||||
return this.$refs.configTab.selectedPreset
|
||||
}
|
||||
} catch (e) { }
|
||||
const presets = this.currentConfig && this.currentConfig.presets
|
||||
if (presets && typeof presets === 'object') {
|
||||
const configuredDefault = this.currentConfig.default_preset
|
||||
if (configuredDefault && presets[configuredDefault]) {
|
||||
return configuredDefault
|
||||
}
|
||||
if (presets['主预设']) {
|
||||
return '主预设'
|
||||
}
|
||||
const keys = Object.keys(presets)
|
||||
if (keys.length > 0) {
|
||||
return keys[0]
|
||||
}
|
||||
}
|
||||
return '主预设'
|
||||
},
|
||||
|
||||
getActivePresetConfig() {
|
||||
if (!this.currentConfig) return null
|
||||
const presets = this.currentConfig.presets
|
||||
if (!presets) return this.currentConfig
|
||||
const name = this.resolveExistingPresetName(this.currentConfig, this.getActivePresetName())
|
||||
const configuredDefault = this.currentConfig.default_preset
|
||||
return presets[name]
|
||||
|| (configuredDefault ? presets[configuredDefault] : null)
|
||||
|| presets['主预设']
|
||||
|| Object.values(presets)[0]
|
||||
|| null
|
||||
},
|
||||
|
||||
resolveExistingPresetName(site, presetName) {
|
||||
const presets = site && site.presets
|
||||
const normalized = String(presetName || '').trim()
|
||||
if (!presets || typeof presets !== 'object' || !normalized) {
|
||||
return normalized
|
||||
}
|
||||
if (presets[normalized]) {
|
||||
return normalized
|
||||
}
|
||||
if (normalized.startsWith('预设_')) {
|
||||
const stripped = normalized.slice(3).trim()
|
||||
if (stripped && presets[stripped]) {
|
||||
return stripped
|
||||
}
|
||||
} else {
|
||||
const prefixed = '预设_' + normalized
|
||||
if (presets[prefixed]) {
|
||||
return prefixed
|
||||
}
|
||||
}
|
||||
return normalized
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,331 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——环境配置、浏览器常量与更新白名单。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 环境配置 ==========
|
||||
|
||||
async loadEnvConfig() {
|
||||
this.isLoadingEnv = true;
|
||||
try {
|
||||
const data = await this.apiRequest('/api/settings/env');
|
||||
const fileConfig = data.config || {};
|
||||
// 修复:DASHBOARD_AUTH_ENABLED 未写进 .env 时,后端运行时语义是「沿用 AUTH_ENABLED」。
|
||||
// 若这里直接用 schema 默认值 false 填充,用户保存任意一项都会把
|
||||
// DASHBOARD_AUTH_ENABLED=false 写进 .env,静默关掉控制面板认证。
|
||||
// 后端在 effective 里给出真实生效值,仅在 .env 确实缺该键时采纳。
|
||||
const effective = (data.effective && typeof data.effective === 'object') ? data.effective : {};
|
||||
const inherited = {};
|
||||
if (!Object.prototype.hasOwnProperty.call(fileConfig, 'DASHBOARD_AUTH_ENABLED')
|
||||
&& Object.prototype.hasOwnProperty.call(effective, 'DASHBOARD_AUTH_ENABLED')) {
|
||||
inherited.DASHBOARD_AUTH_ENABLED = !!effective.DASHBOARD_AUTH_ENABLED;
|
||||
}
|
||||
this.envConfig = {
|
||||
...this.getEnvDefaults(),
|
||||
...inherited,
|
||||
...fileConfig
|
||||
};
|
||||
this.envConfigOriginal = JSON.parse(JSON.stringify(this.envConfig));
|
||||
} catch (error) {
|
||||
console.error('加载环境配置失败:', error);
|
||||
this.envConfig = this.getEnvDefaults();
|
||||
this.envConfigOriginal = JSON.parse(JSON.stringify(this.envConfig));
|
||||
} finally {
|
||||
this.isLoadingEnv = false;
|
||||
}
|
||||
},
|
||||
|
||||
getEnvDefaults() {
|
||||
const defaults = {};
|
||||
for (const group of Object.values(ENV_CONFIG_SCHEMA)) {
|
||||
for (const [key, field] of Object.entries(group.items)) {
|
||||
defaults[key] = field.default;
|
||||
}
|
||||
}
|
||||
return defaults;
|
||||
},
|
||||
|
||||
normalizeEnvCompareValue(value) {
|
||||
if (value === undefined || value === null) return '';
|
||||
if (typeof value === 'boolean') return value ? 'true' : 'false';
|
||||
return String(value);
|
||||
},
|
||||
|
||||
getEnvFieldMeta(fieldKey) {
|
||||
for (const group of Object.values(ENV_CONFIG_SCHEMA)) {
|
||||
if (!group || !group.items || !Object.prototype.hasOwnProperty.call(group.items, fieldKey)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const field = group.items[fieldKey] || {};
|
||||
return {
|
||||
...field,
|
||||
apply: field.apply || group.apply || 'service'
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
|
||||
getEnvChangedKeys() {
|
||||
const current = this.envConfig || {};
|
||||
const original = this.envConfigOriginal || {};
|
||||
const keys = new Set([
|
||||
...Object.keys(current),
|
||||
...Object.keys(original)
|
||||
]);
|
||||
|
||||
return Array.from(keys).filter((key) => {
|
||||
return this.normalizeEnvCompareValue(current[key]) !== this.normalizeEnvCompareValue(original[key]);
|
||||
});
|
||||
},
|
||||
|
||||
async saveEnvConfig() {
|
||||
this.isSavingEnv = true;
|
||||
try {
|
||||
const changedKeys = this.getEnvChangedKeys();
|
||||
await this.apiRequest('/api/settings/env', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: this.envConfig })
|
||||
});
|
||||
|
||||
this.envConfigOriginal = JSON.parse(JSON.stringify(this.envConfig));
|
||||
const launcherKeys = changedKeys.filter((key) => {
|
||||
return (this.getEnvFieldMeta(key)?.apply || 'service') === 'launcher';
|
||||
});
|
||||
const scheduledRestartKeys = launcherKeys.filter((key) => String(key || '').startsWith('SCHEDULED_RESTART_'));
|
||||
const browserRestartKeys = launcherKeys.filter((key) => !String(key || '').startsWith('SCHEDULED_RESTART_'));
|
||||
|
||||
if (browserRestartKeys.length > 0) {
|
||||
const launcherLabels = browserRestartKeys.map((key) => {
|
||||
return this.getEnvFieldMeta(key)?.label || key;
|
||||
}).join(', ');
|
||||
|
||||
this.notify(
|
||||
'环境配置已保存。服务会自动重启,但以下启动型配置要完全生效,请关闭当前浏览器和脚本后重新运行 start.bat:' + launcherLabels,
|
||||
'warning'
|
||||
);
|
||||
} else if (scheduledRestartKeys.length > 0) {
|
||||
this.notify('服务守护配置已保存,后端会自动重启;浏览器和现有标签页保持不变', 'success');
|
||||
} else {
|
||||
this.notify('环境配置已保存,服务将自动重启后生效', 'success');
|
||||
}
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error');
|
||||
} finally {
|
||||
this.isSavingEnv = false;
|
||||
}
|
||||
},
|
||||
|
||||
resetEnvConfig() {
|
||||
if (!confirm('确定要重置环境配置为默认值吗?')) return;
|
||||
|
||||
this.envConfig = this.getEnvDefaults();
|
||||
this.notify('已重置为默认值,请点击保存以应用', 'info');
|
||||
},
|
||||
|
||||
// ========== 浏览器常量 ==========
|
||||
|
||||
normalizeBrowserConstantsForEditor(rawConfig = {}) {
|
||||
const raw = rawConfig && typeof rawConfig === 'object' ? rawConfig : {};
|
||||
const normalized = {};
|
||||
|
||||
for (const group of Object.values(BROWSER_CONSTANTS_SCHEMA)) {
|
||||
for (const [key, field] of Object.entries(group.items || {})) {
|
||||
normalized[key] = field.default;
|
||||
}
|
||||
}
|
||||
|
||||
for (const key of Object.keys(normalized)) {
|
||||
if (key.startsWith('TAB_POOL_')) {
|
||||
continue;
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(raw, key)) {
|
||||
normalized[key] = raw[key];
|
||||
}
|
||||
}
|
||||
|
||||
const tabPool = raw.tab_pool && typeof raw.tab_pool === 'object' ? raw.tab_pool : {};
|
||||
normalized.TAB_POOL_MAX_TABS = raw.TAB_POOL_MAX_TABS ?? tabPool.max_tabs ?? normalized.TAB_POOL_MAX_TABS;
|
||||
normalized.TAB_POOL_MIN_TABS = raw.TAB_POOL_MIN_TABS ?? tabPool.min_tabs ?? normalized.TAB_POOL_MIN_TABS;
|
||||
normalized.TAB_POOL_IDLE_TIMEOUT = raw.TAB_POOL_IDLE_TIMEOUT ?? tabPool.idle_timeout ?? normalized.TAB_POOL_IDLE_TIMEOUT;
|
||||
normalized.TAB_POOL_ACQUIRE_TIMEOUT = raw.TAB_POOL_ACQUIRE_TIMEOUT ?? tabPool.acquire_timeout ?? normalized.TAB_POOL_ACQUIRE_TIMEOUT;
|
||||
normalized.TAB_POOL_STUCK_TIMEOUT = raw.TAB_POOL_STUCK_TIMEOUT ?? tabPool.stuck_timeout ?? normalized.TAB_POOL_STUCK_TIMEOUT;
|
||||
|
||||
return normalized;
|
||||
},
|
||||
|
||||
serializeBrowserConstants(editorConfig = {}, rawBase = {}) {
|
||||
const base = rawBase && typeof rawBase === 'object'
|
||||
? JSON.parse(JSON.stringify(rawBase))
|
||||
: {};
|
||||
const merged = this.normalizeBrowserConstantsForEditor(editorConfig);
|
||||
const obsoleteKeys = [
|
||||
'DEFAULT_PORT',
|
||||
'STREAM_RERENDER_WAIT',
|
||||
'STREAM_MIN_VALID_LENGTH',
|
||||
'STREAM_INITIAL_ELEMENT_WAIT',
|
||||
'STREAM_MAX_ABNORMAL_COUNT',
|
||||
'STREAM_MAX_ELEMENT_MISSING',
|
||||
'STREAM_CONTENT_SHRINK_THRESHOLD'
|
||||
];
|
||||
|
||||
for (const key of obsoleteKeys) {
|
||||
delete base[key];
|
||||
}
|
||||
|
||||
for (const key of Object.keys(merged)) {
|
||||
if (key.startsWith('TAB_POOL_')) {
|
||||
continue;
|
||||
}
|
||||
base[key] = merged[key];
|
||||
}
|
||||
|
||||
const existingTabPool = base.tab_pool && typeof base.tab_pool === 'object' ? base.tab_pool : {};
|
||||
base.tab_pool = {
|
||||
...existingTabPool,
|
||||
max_tabs: merged.TAB_POOL_MAX_TABS,
|
||||
min_tabs: merged.TAB_POOL_MIN_TABS,
|
||||
idle_timeout: merged.TAB_POOL_IDLE_TIMEOUT,
|
||||
acquire_timeout: merged.TAB_POOL_ACQUIRE_TIMEOUT,
|
||||
stuck_timeout: merged.TAB_POOL_STUCK_TIMEOUT
|
||||
};
|
||||
|
||||
return base;
|
||||
},
|
||||
|
||||
async loadBrowserConstants() {
|
||||
this.isLoadingConstants = true;
|
||||
try {
|
||||
const data = await this.apiRequest('/api/settings/browser-constants');
|
||||
this.browserConstantsRaw = JSON.parse(JSON.stringify(data.config || {}));
|
||||
this.browserConstants = this.normalizeBrowserConstantsForEditor(this.browserConstantsRaw);
|
||||
this.browserConstantsOriginal = JSON.parse(JSON.stringify(this.browserConstants));
|
||||
} catch (error) {
|
||||
console.error('加载浏览器常量失败:', error);
|
||||
this.browserConstants = this.getBrowserConstantsDefaults();
|
||||
this.browserConstantsRaw = this.serializeBrowserConstants(this.browserConstants, {});
|
||||
this.browserConstantsOriginal = JSON.parse(JSON.stringify(this.browserConstants));
|
||||
} finally {
|
||||
this.isLoadingConstants = false;
|
||||
}
|
||||
},
|
||||
|
||||
getBrowserConstantsDefaults() {
|
||||
return this.normalizeBrowserConstantsForEditor({});
|
||||
},
|
||||
|
||||
async saveBrowserConstants() {
|
||||
this.isSavingConstants = true;
|
||||
try {
|
||||
// 修复:browserConstantsRaw 只在首屏/首次进设置页加载各一次,期间「标签页池」页签
|
||||
// 可能已通过 PUT /api/tab-pool/config 改过同一个 browser_config.json。用陈旧快照做
|
||||
// merge 基底会把 route_groups / excluded_urls / allocation_mode 等整块回退。
|
||||
// 这里只重新拉取 raw 基底,不调用 loadBrowserConstants(),以免覆盖用户当前未保存的编辑。
|
||||
let rawBase = this.browserConstantsRaw;
|
||||
try {
|
||||
const fresh = await this.apiRequest('/api/settings/browser-constants');
|
||||
if (fresh && fresh.config && typeof fresh.config === 'object') {
|
||||
rawBase = fresh.config;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('刷新浏览器常量基底失败,沿用上次快照:', error);
|
||||
}
|
||||
|
||||
const payload = this.serializeBrowserConstants(this.browserConstants, rawBase);
|
||||
await this.apiRequest('/api/settings/browser-constants', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: payload })
|
||||
});
|
||||
|
||||
this.browserConstantsRaw = JSON.parse(JSON.stringify(payload));
|
||||
this.browserConstants = this.normalizeBrowserConstantsForEditor(payload);
|
||||
this.browserConstantsOriginal = JSON.parse(JSON.stringify(this.browserConstants));
|
||||
this.applyDashboardRuntimeSettings();
|
||||
this.notify('浏览器常量已保存', 'success');
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error');
|
||||
} finally {
|
||||
this.isSavingConstants = false;
|
||||
}
|
||||
},
|
||||
|
||||
resetBrowserConstants() {
|
||||
if (!confirm('确定要重置浏览器常量为默认值吗?')) return;
|
||||
|
||||
this.browserConstants = this.getBrowserConstantsDefaults();
|
||||
this.notify('已重置为默认值,请点击保存以应用', 'info');
|
||||
},
|
||||
|
||||
// ========== 更新白名单 ==========
|
||||
|
||||
async loadUpdatePreserveSettings() {
|
||||
this.isLoadingUpdatePreserve = true;
|
||||
try {
|
||||
const data = await this.apiRequest('/api/settings/update-preserve');
|
||||
this.updatePreserveOptions = Array.isArray(data.options) ? data.options : [];
|
||||
this.updatePreserveSelected = Array.isArray(data.selected_patterns) ? data.selected_patterns.slice() : [];
|
||||
this.updatePreserveSelectedOriginal = JSON.parse(JSON.stringify(this.updatePreserveSelected));
|
||||
} catch (error) {
|
||||
console.error('加载更新白名单失败:', error);
|
||||
this.updatePreserveOptions = [];
|
||||
this.updatePreserveSelected = [];
|
||||
this.updatePreserveSelectedOriginal = [];
|
||||
} finally {
|
||||
this.isLoadingUpdatePreserve = false;
|
||||
}
|
||||
},
|
||||
|
||||
toggleUpdatePreserve(pattern) {
|
||||
const value = String(pattern || '').trim();
|
||||
if (!value) return;
|
||||
const next = new Set(this.updatePreserveSelected || []);
|
||||
if (next.has(value)) {
|
||||
next.delete(value);
|
||||
} else {
|
||||
next.add(value);
|
||||
}
|
||||
this.updatePreserveSelected = Array.from(next);
|
||||
},
|
||||
|
||||
async saveUpdatePreserveSettings() {
|
||||
this.isSavingUpdatePreserve = true;
|
||||
try {
|
||||
const data = await this.apiRequest('/api/settings/update-preserve', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({
|
||||
selected_patterns: this.updatePreserveSelected
|
||||
})
|
||||
});
|
||||
this.updatePreserveSelected = Array.isArray(data.selected_patterns)
|
||||
? data.selected_patterns.slice()
|
||||
: this.updatePreserveSelected;
|
||||
this.updatePreserveSelectedOriginal = JSON.parse(JSON.stringify(this.updatePreserveSelected));
|
||||
this.notify('更新白名单已保存,下次自动更新生效', 'success');
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error');
|
||||
} finally {
|
||||
this.isSavingUpdatePreserve = false;
|
||||
}
|
||||
},
|
||||
|
||||
resetUpdatePreserveSettings() {
|
||||
this.updatePreserveSelected = JSON.parse(JSON.stringify(this.updatePreserveSelectedOriginal));
|
||||
this.notify('已恢复到上次保存的更新白名单', 'info');
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,238 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——工具功能。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 工具功能 ==========
|
||||
|
||||
copyJson(textOverride) {
|
||||
const text = typeof textOverride === 'string'
|
||||
? textOverride
|
||||
: JSON.stringify(this.getJsonPreviewData(), null, 2)
|
||||
navigator.clipboard.writeText(text).then(() => {
|
||||
this.notify('已复制到剪贴板', 'success')
|
||||
}).catch(() => {
|
||||
this.notify('复制失败', 'error')
|
||||
})
|
||||
},
|
||||
|
||||
getJsonPreviewData() {
|
||||
// 修复:先把面板草稿回写到 presetConfig,否则预览显示的是未包含本次编辑的旧值
|
||||
this.flushConfigTabDrafts()
|
||||
const config = this.getActivePresetConfig() || {}
|
||||
return JSON.parse(JSON.stringify(config))
|
||||
},
|
||||
|
||||
async saveJsonPreview(rawText) {
|
||||
// 修复:保存前同样要 flush 面板草稿,否则这条保存路径会静默丢弃用户未回写的编辑
|
||||
this.flushConfigTabDrafts()
|
||||
if (!this.currentDomain) {
|
||||
this.notify('请先选择站点', 'warning')
|
||||
return
|
||||
}
|
||||
|
||||
let parsed
|
||||
try {
|
||||
parsed = JSON.parse(rawText)
|
||||
} catch (error) {
|
||||
this.notify('JSON 解析失败: ' + error.message, 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
this.notify('JSON 顶层必须是对象', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (parsed.selectors !== undefined && (typeof parsed.selectors !== 'object' || Array.isArray(parsed.selectors))) {
|
||||
this.notify('selectors 必须是对象', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (parsed.workflow !== undefined && !Array.isArray(parsed.workflow)) {
|
||||
this.notify('workflow 必须是数组', 'error')
|
||||
return
|
||||
}
|
||||
|
||||
if (parsed.presets && typeof parsed.presets === 'object' && !Array.isArray(parsed.presets)) {
|
||||
const normalized = this.normalizeConfig({ [this.currentDomain]: parsed })
|
||||
if (normalized[this.currentDomain]) {
|
||||
this.sites[this.currentDomain] = normalized[this.currentDomain]
|
||||
}
|
||||
|
||||
try {
|
||||
await this.apiRequest('/api/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: this.sites })
|
||||
})
|
||||
this.showJsonPreview = false
|
||||
this.notify('站点 JSON 已保存', 'success')
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error')
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
const site = JSON.parse(JSON.stringify(this.sites[this.currentDomain] || {}))
|
||||
const presets = site.presets || { '主预设': {} }
|
||||
const activePresetName = this.getActivePresetName()
|
||||
const presetName = this.resolveExistingPresetName(site, activePresetName) || activePresetName
|
||||
const currentPreset = presets[presetName] || presets['主预设'] || {}
|
||||
const { domain, preset_name, timestamp, ...presetPatch } = parsed
|
||||
|
||||
presets[presetName] = {
|
||||
...currentPreset,
|
||||
...presetPatch,
|
||||
selectors: presetPatch.selectors !== undefined ? presetPatch.selectors : (currentPreset.selectors || {}),
|
||||
workflow: presetPatch.workflow !== undefined ? presetPatch.workflow : (currentPreset.workflow || []),
|
||||
stealth: presetPatch.stealth !== undefined ? !!presetPatch.stealth : !!currentPreset.stealth
|
||||
}
|
||||
|
||||
site.presets = presets
|
||||
if (!site.default_preset || !site.presets[site.default_preset]) {
|
||||
site.default_preset = site.presets['主预设'] ? '主预设' : (Object.keys(site.presets)[0] || '主预设')
|
||||
}
|
||||
this.sites[this.currentDomain] = site
|
||||
|
||||
try {
|
||||
await this.apiRequest('/api/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: this.sites })
|
||||
})
|
||||
this.showJsonPreview = false
|
||||
this.notify('JSON 修改已保存', 'success')
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error')
|
||||
}
|
||||
},
|
||||
|
||||
saveToken() {
|
||||
const token = this.tempToken.trim()
|
||||
if (token) {
|
||||
setStoredDashboardToken(token)
|
||||
this.notify('控制面板访问密钥已保存', 'success')
|
||||
} else {
|
||||
setStoredDashboardToken('')
|
||||
this.notify('控制面板访问密钥已清除', 'info')
|
||||
}
|
||||
this.syncTokenPresence()
|
||||
|
||||
this.showTokenDialog = false
|
||||
this.tempToken = ''
|
||||
|
||||
this.loadConfig(true)
|
||||
},
|
||||
|
||||
restoreSitesCache() {
|
||||
const cached = window.loadStoredSitesCache()
|
||||
if (!cached || !cached.sites) {
|
||||
return
|
||||
}
|
||||
this.sites = this.normalizeConfig(cached.sites)
|
||||
const domains = Object.keys(this.sites)
|
||||
if (domains.length === 0) {
|
||||
return
|
||||
}
|
||||
if (cached.currentDomain && this.sites[cached.currentDomain]) {
|
||||
this.currentDomain = cached.currentDomain
|
||||
return
|
||||
}
|
||||
if (!this.currentDomain) {
|
||||
this.currentDomain = domains[0]
|
||||
}
|
||||
},
|
||||
|
||||
async refreshStatus() {
|
||||
const [configOk, healthOk] = await Promise.all([
|
||||
this.loadConfig(true),
|
||||
this.loadHealthStatus({ timeoutMs: 2500 }),
|
||||
this.fetchSystemStats({ timeoutMs: 2500 })
|
||||
])
|
||||
|
||||
if (configOk || healthOk) {
|
||||
this.notify('状态已刷新', 'success')
|
||||
} else {
|
||||
this.notify('刷新失败', 'error')
|
||||
}
|
||||
},
|
||||
|
||||
async fetchSystemStats({ timeoutMs = 0 } = {}) {
|
||||
if (!this.getBrowserConstantBool('DASHBOARD_SYSTEM_STATS_ENABLED', true)) {
|
||||
return this.systemStats
|
||||
}
|
||||
if (this.isFetchingSystemStats) {
|
||||
return this.systemStatsRequestPromise || this.systemStats
|
||||
}
|
||||
this.isFetchingSystemStats = true
|
||||
const requestPromise = this.apiRequest('/api/system/stats', {
|
||||
timeoutMs: timeoutMs || 2500
|
||||
})
|
||||
.then((stats) => {
|
||||
this.systemStats = stats
|
||||
return this.systemStats
|
||||
})
|
||||
.catch(() => this.systemStats)
|
||||
.finally(() => {
|
||||
if (this.systemStatsRequestPromise === requestPromise) {
|
||||
this.systemStatsRequestPromise = null
|
||||
this.isFetchingSystemStats = false
|
||||
}
|
||||
})
|
||||
this.systemStatsRequestPromise = requestPromise
|
||||
return requestPromise
|
||||
},
|
||||
|
||||
async loadHealthStatus({ silent = false, timeoutMs = 0 } = {}) {
|
||||
try {
|
||||
const health = await this.apiRequest('/health', {
|
||||
timeoutMs: timeoutMs || 2500
|
||||
})
|
||||
this.browserStatus = health.browser || {}
|
||||
this.authEnabled = health.config?.dashboard_auth_enabled ?? health.config?.auth_enabled ?? false
|
||||
return true
|
||||
} catch (error) {
|
||||
if (error.message === 'UNAUTHORIZED') {
|
||||
this.authEnabled = true
|
||||
return true
|
||||
}
|
||||
|
||||
console.error('状态检查失败:', error)
|
||||
if (!silent) {
|
||||
this.notify('状态检查失败: ' + error.message, 'error')
|
||||
}
|
||||
return false
|
||||
}
|
||||
},
|
||||
|
||||
notify(message, type) {
|
||||
if (!type) type = 'info'
|
||||
const id = this.toastCounter++
|
||||
this.toasts.push({ id: id, message: message, type: type })
|
||||
|
||||
const self = this
|
||||
setTimeout(function () {
|
||||
self.removeToast(id)
|
||||
}, 3000)
|
||||
},
|
||||
|
||||
removeToast(id) {
|
||||
this.toasts = this.toasts.filter(function (t) {
|
||||
return t.id !== id
|
||||
})
|
||||
}
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,580 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——配置导入与导出。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 导入功能(支持全量和单站点) ==========
|
||||
|
||||
triggerImport() {
|
||||
this.forceSingleSiteImport = false;
|
||||
this.singleSiteImportTargetDomain = '';
|
||||
if (this.$refs.importFileInput) {
|
||||
this.$refs.importFileInput.click();
|
||||
}
|
||||
},
|
||||
|
||||
triggerImportSingleSite() {
|
||||
this.forceSingleSiteImport = true;
|
||||
this.singleSiteImportTargetDomain = this.currentDomain || '';
|
||||
if (this.$refs.importFileInput) {
|
||||
this.$refs.importFileInput.click();
|
||||
}
|
||||
},
|
||||
|
||||
handleImportFile(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const sizeError = importFileSizeError(file, SITE_CONFIG_IMPORT_MAX_BYTES, '配置文件');
|
||||
if (sizeError) {
|
||||
this.notify(sizeError, 'error');
|
||||
this.singleSiteImportTargetDomain = '';
|
||||
this.forceSingleSiteImport = false;
|
||||
event.target.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
this.importFileName = file.name;
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onerror = () => {
|
||||
this.notify('读取导入文件失败', 'error');
|
||||
this.singleSiteImportTargetDomain = '';
|
||||
this.forceSingleSiteImport = false;
|
||||
};
|
||||
reader.onload = (e) => {
|
||||
try {
|
||||
const config = JSON.parse(e.target.result);
|
||||
|
||||
// 检测是单站点还是全量配置
|
||||
const detectResult = this.detectConfigType(config, this.forceSingleSiteImport);
|
||||
|
||||
if (!detectResult.valid) {
|
||||
this.notify('导入文件格式无效', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
this.importType = detectResult.type;
|
||||
this.importedConfig = detectResult.normalizedConfig;
|
||||
this.singleSiteImportDomain = detectResult.suggestedDomain || this.singleSiteImportTargetDomain || this.currentDomain || '';
|
||||
this.singleSiteImportTargetDomain = '';
|
||||
this.forceSingleSiteImport = false;
|
||||
this.showImportDialog = true;
|
||||
} catch (error) {
|
||||
this.notify('JSON 解析失败: ' + error.message, 'error');
|
||||
this.singleSiteImportTargetDomain = '';
|
||||
this.forceSingleSiteImport = false;
|
||||
}
|
||||
};
|
||||
reader.readAsText(file);
|
||||
|
||||
event.target.value = '';
|
||||
},
|
||||
|
||||
// 从配置内容内部提取站点域名标识(优先识别文件内部元数据与单站点包装)
|
||||
extractDomainFromContent(config, knownDomains = []) {
|
||||
if (!config || typeof config !== 'object' || Array.isArray(config)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// 1. 严格限定域名语义字段,避免被通用的 name/id 字段误导
|
||||
const candidateKeys = ['domain', 'site_domain', 'target_domain', 'site', '_domain'];
|
||||
for (const key of candidateKeys) {
|
||||
const val = config[key];
|
||||
if (typeof val === 'string') {
|
||||
let cleanVal = val.trim();
|
||||
if (!cleanVal || cleanVal.startsWith('_')) continue;
|
||||
// 剥离协议头、端口与路径(如 https://chat.deepseek.com/ -> chat.deepseek.com)
|
||||
cleanVal = cleanVal.replace(/^https?:\/\//i, '').split('/')[0].split(':')[0].trim();
|
||||
if (!cleanVal) continue;
|
||||
|
||||
const matched = knownDomains.find(d => d.toLowerCase() === cleanVal.toLowerCase());
|
||||
if (matched) return matched;
|
||||
// 基本域名格式特征:包含点且由合法字符构成
|
||||
if (/^[a-zA-Z0-9][-a-zA-Z0-9.]*\.[a-zA-Z0-9]+$/.test(cleanVal)) {
|
||||
return cleanVal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 检查单站点包装格式(如 { "chat.deepseek.com": { presets: ... } })
|
||||
const validKeys = Object.keys(config).filter(k => k && !k.startsWith('_'));
|
||||
if (validKeys.length === 1 && this.validateSingleSiteConfig(config[validKeys[0]])) {
|
||||
const singleKey = validKeys[0].trim();
|
||||
const matched = knownDomains.find(d => d.toLowerCase() === singleKey.toLowerCase());
|
||||
return matched || singleKey;
|
||||
}
|
||||
|
||||
return '';
|
||||
},
|
||||
|
||||
// 从文件名中清洗并提取站点域名(支持去除 (4)、_1、- 副本、-config 等)
|
||||
extractDomainFromFilename(filename, knownDomains = []) {
|
||||
if (!filename || typeof filename !== 'string') {
|
||||
return '';
|
||||
}
|
||||
|
||||
let name = filename.trim();
|
||||
// 剥离 .json 后缀
|
||||
name = name.replace(/\.json$/i, '').trim();
|
||||
|
||||
// 循环剥离末尾的重复下载序号、括号序号、副本标记与配置后缀
|
||||
const dupSuffixRegex = /(?:\s*\(\s*\d+\s*\)|\s*\[\s*\d+\s*\]|[-_\s]+\d+|[-_\s]*(?:副本|复本|copy)(?:\s*\(\d+\))?)$/i;
|
||||
const configSuffixRegex = /[-_.]*(?:(?:sites?|site|presets?)[-_.]*)?config(?:uration)?$/i;
|
||||
|
||||
let prev = null;
|
||||
let loopCount = 0;
|
||||
while (prev !== name && loopCount < 10) {
|
||||
prev = name;
|
||||
name = name.replace(dupSuffixRegex, '').trim();
|
||||
name = name.replace(configSuffixRegex, '').trim();
|
||||
loopCount++;
|
||||
}
|
||||
|
||||
if (!name) return '';
|
||||
|
||||
// 1. 优先完全匹配已知站点域名(不区分大小写)
|
||||
const exactMatch = knownDomains.find(d => d.toLowerCase() === name.toLowerCase());
|
||||
if (exactMatch) return exactMatch;
|
||||
|
||||
// 2. 若清洗后的 name 本身符合标准域名结构,直接采纳,严禁退化去匹配更短的父域或任意子串
|
||||
if (/^[a-zA-Z0-9][-a-zA-Z0-9.]*\.[a-zA-Z0-9]+$/.test(name)) {
|
||||
return name;
|
||||
}
|
||||
|
||||
// 3. 仅当末尾带有未剥离的连接符后缀时,按最长前缀优先匹配已有站点(如 chat.deepseek.com-v2)
|
||||
const sortedKnown = [...knownDomains].sort((a, b) => b.length - a.length);
|
||||
const lowN = name.toLowerCase();
|
||||
const prefixMatch = sortedKnown.find(d => {
|
||||
const lowD = d.toLowerCase();
|
||||
return lowN.startsWith(lowD + '-') || lowN.startsWith(lowD + '_') || lowN.startsWith(lowD + '.');
|
||||
});
|
||||
if (prefixMatch) return prefixMatch;
|
||||
|
||||
return name;
|
||||
},
|
||||
|
||||
// 检测配置类型:全量配置 or 单站点配置
|
||||
detectConfigType(config, forceSingle = false) {
|
||||
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
const knownDomains = Object.keys(this.sites || {}).filter(k => k && !k.startsWith('_'));
|
||||
// 优先从文件内容内部提取站点域名标识,次选从清洗后的文件名提取
|
||||
const contentDomain = this.extractDomainFromContent(config, knownDomains);
|
||||
const filenameDomain = this.extractDomainFromFilename(this.importFileName, knownDomains);
|
||||
const suggestedDomain = contentDomain || filenameDomain || this.singleSiteImportTargetDomain || '';
|
||||
|
||||
// 检查是否是单站点格式(旧格式 selectors/workflow,或新格式 presets/default_preset)
|
||||
if (
|
||||
config.selectors !== undefined
|
||||
|| config.workflow !== undefined
|
||||
|| (config.presets && typeof config.presets === 'object' && !Array.isArray(config.presets))
|
||||
) {
|
||||
// 单站点格式
|
||||
if (!this.validateSingleSiteConfig(config)) {
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
type: 'single',
|
||||
normalizedConfig: config,
|
||||
suggestedDomain: suggestedDomain || this.singleSiteImportTargetDomain || ''
|
||||
};
|
||||
}
|
||||
|
||||
const keys = Object.keys(config).filter(k => k && !k.startsWith('_'));
|
||||
// 若显式指定单站点导入且文件只包含 1 个站点对象
|
||||
if (forceSingle && keys.length === 1 && this.validateSingleSiteConfig(config[keys[0]])) {
|
||||
return {
|
||||
valid: true,
|
||||
type: 'single',
|
||||
normalizedConfig: config[keys[0]],
|
||||
suggestedDomain: keys[0] || suggestedDomain || this.singleSiteImportTargetDomain || ''
|
||||
};
|
||||
}
|
||||
|
||||
// 检查是否是全量格式(域名 -> 配置)
|
||||
if (!this.validateImportedConfig(config)) {
|
||||
return { valid: false };
|
||||
}
|
||||
|
||||
return {
|
||||
valid: true,
|
||||
type: 'full',
|
||||
normalizedConfig: config
|
||||
};
|
||||
},
|
||||
|
||||
validateSingleSiteConfig(config) {
|
||||
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (config.presets !== undefined) {
|
||||
if (typeof config.presets !== 'object' || config.presets === null || Array.isArray(config.presets)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const presetData of Object.values(config.presets)) {
|
||||
if (typeof presetData !== 'object' || presetData === null || Array.isArray(presetData)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (presetData.selectors !== undefined && (typeof presetData.selectors !== 'object' || Array.isArray(presetData.selectors))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (presetData.workflow !== undefined && !Array.isArray(presetData.workflow)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// selectors 必须是对象(如果存在)
|
||||
if (config.selectors !== undefined && (typeof config.selectors !== 'object' || Array.isArray(config.selectors))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// workflow 必须是数组(如果存在)
|
||||
if (config.workflow !== undefined && !Array.isArray(config.workflow)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
validateImportedConfig(config) {
|
||||
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const [domain, siteConfig] of Object.entries(config)) {
|
||||
if (!domain || typeof domain !== 'string') {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!this.validateSingleSiteConfig(siteConfig)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
mergeSiteConfigs(existingSite, importedSite) {
|
||||
const normalizedImported = this.normalizeConfig({ imported: importedSite || {} }).imported
|
||||
if (!normalizedImported) {
|
||||
return existingSite || null
|
||||
}
|
||||
|
||||
if (!existingSite) {
|
||||
return normalizedImported
|
||||
}
|
||||
|
||||
const normalizedExisting = this.normalizeConfig({ existing: existingSite }).existing || {
|
||||
default_preset: '主预设',
|
||||
presets: {}
|
||||
}
|
||||
|
||||
const mergedPresets = {
|
||||
...(normalizedExisting.presets || {}),
|
||||
...(normalizedImported.presets || {})
|
||||
}
|
||||
|
||||
let mergedDefault = normalizedImported.default_preset
|
||||
if (!mergedDefault || !mergedPresets[mergedDefault]) {
|
||||
mergedDefault = normalizedExisting.default_preset
|
||||
}
|
||||
if (!mergedDefault || !mergedPresets[mergedDefault]) {
|
||||
mergedDefault = mergedPresets['主预设'] ? '主预设' : (Object.keys(mergedPresets)[0] || '主预设')
|
||||
}
|
||||
|
||||
return {
|
||||
...normalizedExisting,
|
||||
...normalizedImported,
|
||||
presets: mergedPresets,
|
||||
default_preset: mergedDefault
|
||||
}
|
||||
},
|
||||
|
||||
async executeImport() {
|
||||
if (!this.importedConfig) return;
|
||||
|
||||
if (this.importType === 'single') {
|
||||
// 单站点导入
|
||||
const domain = this.singleSiteImportDomain.trim();
|
||||
if (!domain) {
|
||||
this.notify('请输入站点域名', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedMap = this.normalizeConfig({ [domain]: this.importedConfig });
|
||||
const normalizedSite = normalizedMap[domain];
|
||||
if (!normalizedSite) {
|
||||
this.notify('导入文件格式无效', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const exists = !!this.sites[domain];
|
||||
if (exists) {
|
||||
const message = this.importMode === 'replace'
|
||||
? '站点 "' + domain + '" 已存在,将完整替换该站点的当前配置,是否继续?'
|
||||
: '站点 "' + domain + '" 已存在,将按预设合并导入,同名预设会被覆盖,是否继续?';
|
||||
if (!confirm(message)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this.sites[domain] = this.importMode === 'replace'
|
||||
? normalizedSite
|
||||
: this.mergeSiteConfigs(this.sites[domain], normalizedSite);
|
||||
this.currentDomain = domain;
|
||||
|
||||
try {
|
||||
await this.apiRequest('/api/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: this.sites })
|
||||
});
|
||||
|
||||
this.notify('成功导入站点: ' + domain, 'success');
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error');
|
||||
}
|
||||
} else {
|
||||
// 全量导入
|
||||
const importCount = Object.keys(this.importedConfig).length;
|
||||
|
||||
if (this.importMode === 'replace') {
|
||||
this.sites = this.normalizeConfig(this.importedConfig);
|
||||
} else {
|
||||
const normalized = this.normalizeConfig(this.importedConfig);
|
||||
this.sites = { ...this.sites, ...normalized };
|
||||
}
|
||||
|
||||
try {
|
||||
await this.apiRequest('/api/config', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ config: this.sites })
|
||||
});
|
||||
|
||||
this.notify('成功导入 ' + importCount + ' 个站点配置', 'success');
|
||||
} catch (error) {
|
||||
this.notify('保存失败: ' + error.message, 'error');
|
||||
}
|
||||
|
||||
if (!this.currentDomain && Object.keys(this.sites).length > 0) {
|
||||
this.currentDomain = Object.keys(this.sites)[0];
|
||||
}
|
||||
}
|
||||
|
||||
// 清理
|
||||
this.showImportDialog = false;
|
||||
this.importedConfig = null;
|
||||
this.importFileName = '';
|
||||
this.singleSiteImportDomain = '';
|
||||
},
|
||||
|
||||
cancelImport() {
|
||||
this.showImportDialog = false;
|
||||
this.importedConfig = null;
|
||||
this.importFileName = '';
|
||||
this.singleSiteImportDomain = '';
|
||||
},
|
||||
|
||||
// ========== 导出功能(支持全量和单站点) ==========
|
||||
|
||||
exportConfig() {
|
||||
this.flushConfigTabDrafts()
|
||||
const dataStr = JSON.stringify(this.sites, null, 2)
|
||||
const blob = new Blob([dataStr], { type: 'application/json' })
|
||||
const url = URL.createObjectURL(blob)
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
a.download = 'sites-config-' + Date.now() + '.json'
|
||||
a.click()
|
||||
URL.revokeObjectURL(url)
|
||||
|
||||
this.notify('全量配置已导出', 'success')
|
||||
},
|
||||
|
||||
// 导出单个站点
|
||||
exportSingleSite(domain) {
|
||||
this.flushConfigTabDrafts()
|
||||
if (!domain || !this.sites[domain]) {
|
||||
this.notify('站点不存在', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// 导出整个站点(含所有预设与站点域名自描述)
|
||||
const siteConfig = this.sites[domain];
|
||||
const exportPayload = {
|
||||
...siteConfig,
|
||||
domain: domain
|
||||
};
|
||||
const dataStr = JSON.stringify(exportPayload, null, 2);
|
||||
const blob = new Blob([dataStr], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = domain + '-config.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
this.notify('站点配置已导出: ' + domain, 'success');
|
||||
},
|
||||
|
||||
// 导出当前站点
|
||||
exportCurrentSite() {
|
||||
if (!this.currentDomain) {
|
||||
this.notify('请先选择站点', 'warning');
|
||||
return;
|
||||
}
|
||||
this.exportSingleSite(this.currentDomain);
|
||||
},
|
||||
|
||||
triggerSettingsBackupImport() {
|
||||
if (this.$refs.backupImportInput) {
|
||||
this.$refs.backupImportInput.click();
|
||||
}
|
||||
},
|
||||
|
||||
handleSettingsBackupImportFile(event) {
|
||||
const file = event.target.files[0];
|
||||
if (!file) return;
|
||||
|
||||
const sizeError = importFileSizeError(file, SETTINGS_BACKUP_IMPORT_MAX_BYTES, '备份文件');
|
||||
if (sizeError) {
|
||||
this.notify('完整备份导入失败: ' + sizeError, 'error');
|
||||
event.target.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onerror = () => {
|
||||
this.notify('完整备份导入失败: 读取文件出错', 'error');
|
||||
};
|
||||
reader.onload = async (e) => {
|
||||
try {
|
||||
const payload = JSON.parse(e.target.result);
|
||||
await this.importSettingsBackup(payload);
|
||||
} catch (error) {
|
||||
this.notify('完整备份导入失败: ' + error.message, 'error');
|
||||
}
|
||||
};
|
||||
reader.readAsText(file, 'utf-8');
|
||||
|
||||
event.target.value = '';
|
||||
},
|
||||
|
||||
getDashboardPreferencesBackup() {
|
||||
// S13:备份文件会被下载/转存/分享,浏览器本地保存的面板令牌不再写入备份。
|
||||
// 旧版备份里的 dashboard_token / api_token 仍可在导入时读取(见下方 apply)。
|
||||
return {
|
||||
dark_mode: !!this.darkMode
|
||||
};
|
||||
},
|
||||
|
||||
applyDashboardPreferencesBackup(preferences) {
|
||||
if (!preferences || typeof preferences !== 'object') return;
|
||||
|
||||
if (typeof preferences.dark_mode === 'boolean') {
|
||||
this.darkMode = preferences.dark_mode;
|
||||
}
|
||||
|
||||
if (typeof preferences.dashboard_token === 'string' || typeof preferences.api_token === 'string') {
|
||||
const token = String(preferences.dashboard_token || preferences.api_token || '').trim();
|
||||
try {
|
||||
setStoredDashboardToken(token);
|
||||
} catch (e) { }
|
||||
this.tempToken = token;
|
||||
this.syncTokenPresence();
|
||||
}
|
||||
},
|
||||
|
||||
async exportSettingsBackup() {
|
||||
try {
|
||||
const payload = await this.apiRequest('/api/settings/backup');
|
||||
const exportPayload = {
|
||||
...payload,
|
||||
dashboard_preferences: this.getDashboardPreferencesBackup()
|
||||
};
|
||||
const dataStr = JSON.stringify(exportPayload, null, 2);
|
||||
const blob = new Blob([dataStr], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = 'settings-backup-' + Date.now() + '.json';
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
const redactedKeys = Array.isArray(payload && payload.redacted_env_keys)
|
||||
? payload.redacted_env_keys
|
||||
: [];
|
||||
this.notify(
|
||||
redactedKeys.length
|
||||
? `完整配置备份已导出(已剔除 ${redactedKeys.length} 项令牌/密钥,导入时保留目标机器现值)`
|
||||
: '完整配置备份已导出',
|
||||
'success'
|
||||
);
|
||||
} catch (error) {
|
||||
this.notify('完整备份导出失败: ' + error.message, 'error');
|
||||
}
|
||||
},
|
||||
|
||||
// 修复:此处原有一份与下方「浏览器常量」区块完全相同的
|
||||
// normalizeBrowserConstantsForEditor / serializeBrowserConstants 重复定义(后定义者生效),
|
||||
// 已删除这份无效的前置副本,只保留下方那份。
|
||||
|
||||
async importSettingsBackup(payload) {
|
||||
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
||||
throw new Error('备份文件格式无效');
|
||||
}
|
||||
|
||||
const result = await this.apiRequest('/api/settings/backup', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
|
||||
this.applyDashboardPreferencesBackup(payload.dashboard_preferences);
|
||||
|
||||
if (!result.will_restart) {
|
||||
await Promise.all([
|
||||
this.loadConfig(true),
|
||||
this.loadEnvConfig(),
|
||||
this.loadBrowserConstants(),
|
||||
this.loadUpdatePreserveSettings(),
|
||||
this.loadSelectorDefinitions()
|
||||
]);
|
||||
}
|
||||
|
||||
const sections = Array.isArray(result.imported_sections)
|
||||
? result.imported_sections.join('、')
|
||||
: '';
|
||||
this.notify(
|
||||
result.will_restart
|
||||
? '完整备份已导入,服务将自动重启' + (sections ? ':' + sections : '')
|
||||
: '完整备份已导入' + (sections ? ':' + sections : ''),
|
||||
result.will_restart ? 'warning' : 'success'
|
||||
);
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,205 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——版本管理。方法原样迁出,由 dashboard-methods.js 统一组装。
|
||||
(() => {
|
||||
const {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
} = window.DashboardShared;
|
||||
(window.DashboardMethodParts = window.DashboardMethodParts || []).push({
|
||||
// ========== 版本管理方法 ==========
|
||||
|
||||
applyUpdateCheck(data) {
|
||||
const current = this.updateCheck && typeof this.updateCheck === 'object'
|
||||
? this.updateCheck
|
||||
: {};
|
||||
// 修复:检查失败时后端会把 latest_* 显式清空,这里若继续用 `||` 回落旧值,
|
||||
// 界面会同时显示"最新版本号"和"检查失败",语义矛盾。
|
||||
// 只有后端确实没带这些键(如轮询中的部分响应)才回落。
|
||||
const hasKey = (key) => !!data && Object.prototype.hasOwnProperty.call(data, key);
|
||||
const pick = (key) => String((hasKey(key) ? data[key] : current[key]) || '');
|
||||
this.updateCheck = {
|
||||
checked: !!(data && data.checked),
|
||||
checking: !!(data && data.checking),
|
||||
available: !!(data && data.available),
|
||||
current_version: String((data && data.current_version) || current.current_version || ''),
|
||||
latest_version: pick('latest_version'),
|
||||
latest_tag: pick('latest_tag'),
|
||||
published_at: pick('published_at'),
|
||||
repo: String((data && data.repo) || current.repo || ''),
|
||||
checked_at: data && data.checked_at ? data.checked_at : (current.checked_at || null),
|
||||
error: String((data && data.error) || '')
|
||||
};
|
||||
if (this.updateCheck.current_version && !this.releasesCurrentVersion) {
|
||||
this.releasesCurrentVersion = this.updateCheck.current_version;
|
||||
}
|
||||
return this.updateCheck;
|
||||
},
|
||||
|
||||
async loadUpdateCheck({ silent = false } = {}) {
|
||||
try {
|
||||
const data = await this.apiRequest('/api/update/check', { timeoutMs: 2500 });
|
||||
return this.applyUpdateCheck(data);
|
||||
} catch (error) {
|
||||
if (!silent) {
|
||||
this.notify('版本检查状态读取失败: ' + error.message, 'error');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async refreshUpdateCheck() {
|
||||
// 补齐入口:后端 POST /api/update/check 会真正访问 GitHub 重查一次,
|
||||
// 而 GET 只读启动时的缓存状态(system.py 注释明确「不会访问 GitHub」)。
|
||||
// 此前前端只调 GET,用户没有任何"立即检查更新"的入口。
|
||||
if (this.updateCheckRefreshing) return;
|
||||
this.updateCheckRefreshing = true;
|
||||
try {
|
||||
const data = await this.apiRequest('/api/update/check', { method: 'POST', timeoutMs: 20000 });
|
||||
const applied = this.applyUpdateCheck(data);
|
||||
if (applied.error) {
|
||||
this.notify('版本检查失败: ' + applied.error, 'error');
|
||||
} else if (applied.available) {
|
||||
this.notify('发现新版本: ' + (applied.latest_tag || applied.latest_version), 'info');
|
||||
} else {
|
||||
this.notify('已是最新版本', 'success');
|
||||
}
|
||||
return applied;
|
||||
} catch (error) {
|
||||
this.notify('版本检查失败: ' + error.message, 'error');
|
||||
} finally {
|
||||
this.updateCheckRefreshing = false;
|
||||
}
|
||||
},
|
||||
|
||||
scheduleUpdateCheckStatusRefresh(status, attempt = 0) {
|
||||
if (this.updateCheckTimer) {
|
||||
clearTimeout(this.updateCheckTimer);
|
||||
this.updateCheckTimer = null;
|
||||
}
|
||||
const stillPending = status && (status.checking || !status.checked);
|
||||
if (!stillPending || attempt >= 12) {
|
||||
return;
|
||||
}
|
||||
this.updateCheckTimer = setTimeout(() => {
|
||||
this.updateCheckTimer = null;
|
||||
this.loadUpdateCheck({ silent: true })
|
||||
.then((nextStatus) => this.scheduleUpdateCheckStatusRefresh(nextStatus, attempt + 1))
|
||||
.catch(() => {});
|
||||
}, 1500);
|
||||
},
|
||||
|
||||
async loadReleases() {
|
||||
this.releasesLoading = true;
|
||||
this.releasesError = '';
|
||||
try {
|
||||
const data = await this.apiRequest('/api/update/releases');
|
||||
this.releases = Array.isArray(data.releases) ? data.releases : [];
|
||||
this.releasesCurrentVersion = data.current_version || '';
|
||||
if (data.update_check) {
|
||||
this.applyUpdateCheck(data.update_check);
|
||||
}
|
||||
} catch (error) {
|
||||
this.releasesError = '加载失败: ' + error.message;
|
||||
this.releases = [];
|
||||
} finally {
|
||||
this.releasesLoading = false;
|
||||
}
|
||||
},
|
||||
|
||||
async switchToVersion(tag) {
|
||||
if (this.switchingTag) {
|
||||
this.notify('已有版本切换任务正在运行,请稍候', 'warning');
|
||||
return;
|
||||
}
|
||||
if (!confirm('确定要切换到 ' + tag + ' 吗?\n切换完成后服务将自动重启,页面需要手动刷新。')) {
|
||||
return;
|
||||
}
|
||||
this.switchingTag = tag;
|
||||
try {
|
||||
await this.apiRequest('/api/update/switch', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ tag: tag })
|
||||
});
|
||||
this.notify('版本切换任务已启动:' + tag + ',下载中...', 'info');
|
||||
this.startSwitchStatusPolling();
|
||||
} catch (error) {
|
||||
this.notify('启动版本切换失败: ' + error.message, 'error');
|
||||
this.switchingTag = null;
|
||||
}
|
||||
},
|
||||
|
||||
startSwitchStatusPolling() {
|
||||
this.stopSwitchStatusPolling();
|
||||
this.switchStatusPollingActive = true;
|
||||
const pollStatus = async () => {
|
||||
if (!this.switchStatusPollingActive || this.switchStatusPollingInFlight) {
|
||||
return;
|
||||
}
|
||||
this.switchStatusPollingInFlight = true;
|
||||
let shouldContinue = true;
|
||||
try {
|
||||
const status = await this.apiRequest('/api/update/status');
|
||||
if (!status.running) {
|
||||
shouldContinue = false;
|
||||
this.stopSwitchStatusPolling();
|
||||
if (status.success === true) {
|
||||
this.notify('版本 ' + status.tag + ' 切换成功,服务正在重启,请稍后刷新页面', 'success');
|
||||
} else if (status.success === false) {
|
||||
var errMsg = status.error ? ':' + status.error : '';
|
||||
this.notify('版本 ' + status.tag + ' 切换失败' + errMsg, 'error');
|
||||
this.switchingTag = null;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// 服务重启中,连接可能断开
|
||||
} finally {
|
||||
this.switchStatusPollingInFlight = false;
|
||||
if (shouldContinue && this.switchStatusPollingActive) {
|
||||
this.switchStatusPolling = setTimeout(() => {
|
||||
this.switchStatusPolling = null;
|
||||
pollStatus();
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
};
|
||||
pollStatus();
|
||||
},
|
||||
|
||||
stopSwitchStatusPolling() {
|
||||
this.switchStatusPollingActive = false;
|
||||
if (this.switchStatusPolling) {
|
||||
clearTimeout(this.switchStatusPolling);
|
||||
this.switchStatusPolling = null;
|
||||
}
|
||||
this.switchStatusPollingInFlight = false;
|
||||
},
|
||||
|
||||
showChangelog(tag, body) {
|
||||
this.changelogTag = tag;
|
||||
this.changelogContent = body || '(无更新说明)';
|
||||
this.showChangelogModal = true;
|
||||
},
|
||||
|
||||
formatReleaseDate(isoStr) {
|
||||
if (!isoStr) return '—';
|
||||
try {
|
||||
var d = new Date(isoStr);
|
||||
var pad = function(n) { return String(n).padStart(2, '0'); };
|
||||
return d.getFullYear() + '/' + pad(d.getMonth()+1) + '/' + pad(d.getDate()) + ' ' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds());
|
||||
} catch (e) {
|
||||
return isoStr;
|
||||
}
|
||||
},
|
||||
});
|
||||
})();
|
||||
@@ -0,0 +1,100 @@
|
||||
// R2-8:由 dashboard-methods.js 拆分——各方法分组共用的常量与辅助函数(原 IIFE 头部,原样迁出)。
|
||||
(() => {
|
||||
const DEFAULT_SELECTOR_DEFINITIONS = window.DEFAULT_SELECTOR_DEFINITIONS || []
|
||||
const BROWSER_CONSTANTS_SCHEMA = window.BROWSER_CONSTANTS_SCHEMA || {}
|
||||
const ENV_CONFIG_SCHEMA = window.ENV_CONFIG_SCHEMA || {}
|
||||
const DASHBOARD_TOKEN_STORAGE_KEY = 'dashboard_token'
|
||||
const LEGACY_API_TOKEN_STORAGE_KEY = 'api_token'
|
||||
// H14:导入文件大小上限(整个文件读进内存再 JSON.parse,超大文件会卡死页面)。
|
||||
// 正常站点配置 / 完整备份都在数百 KB 级,上限留足余量。
|
||||
const SITE_CONFIG_IMPORT_MAX_BYTES = 8 * 1024 * 1024
|
||||
const SETTINGS_BACKUP_IMPORT_MAX_BYTES = 32 * 1024 * 1024
|
||||
|
||||
function importFileSizeError(file, maxBytes, label) {
|
||||
const size = Number(file && file.size) || 0
|
||||
if (size <= maxBytes) return ''
|
||||
const mb = (n) => (n / 1024 / 1024).toFixed(n >= 10 * 1024 * 1024 ? 0 : 1)
|
||||
return `${label}过大(${mb(size)} MiB),上限 ${mb(maxBytes)} MiB`
|
||||
}
|
||||
window.importFileSizeError = importFileSizeError
|
||||
|
||||
function formatGitCompareErrorText(error) {
|
||||
const raw = String((error && error.message) || error || '').trim()
|
||||
return raw || '读取官方配置失败'
|
||||
}
|
||||
window.formatGitCompareErrorText = formatGitCompareErrorText
|
||||
|
||||
function getStoredDashboardToken() {
|
||||
try {
|
||||
return String(
|
||||
localStorage.getItem(DASHBOARD_TOKEN_STORAGE_KEY)
|
||||
|| localStorage.getItem(LEGACY_API_TOKEN_STORAGE_KEY)
|
||||
|| ''
|
||||
).trim()
|
||||
} catch (e) {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
function setStoredDashboardToken(token) {
|
||||
const value = String(token || '').trim()
|
||||
if (value) {
|
||||
localStorage.setItem(DASHBOARD_TOKEN_STORAGE_KEY, value)
|
||||
return
|
||||
}
|
||||
localStorage.removeItem(DASHBOARD_TOKEN_STORAGE_KEY)
|
||||
localStorage.removeItem(LEGACY_API_TOKEN_STORAGE_KEY)
|
||||
}
|
||||
|
||||
// 站点友好名称:解决 "domain.split('.')[0]" 在 chat.deepseek.com / chat.qwen.ai
|
||||
// 或 aistudio.google.com / aistudio.xiaomimimo.com 这类站点上撞出一堆同名(chat、aistudio)的问题
|
||||
const SITE_FRIENDLY_NAMES = {
|
||||
'aistudio.google.com': 'Google AI Studio',
|
||||
'aistudio.xiaomimimo.com': '小米 MiMo AI Studio',
|
||||
'grok.com': 'Grok',
|
||||
'chatgpt.com': 'ChatGPT',
|
||||
'gemini.google.com': 'Gemini',
|
||||
'chat.deepseek.com': 'DeepSeek',
|
||||
'www.doubao.com': '豆包 Doubao',
|
||||
'claude.ai': 'Claude',
|
||||
'arena.ai': 'LMArena',
|
||||
'chat.qwen.ai': '通义千问 Qwen',
|
||||
'www.kimi.com': 'Kimi',
|
||||
'chatglm.cn': '智谱清言 ChatGLM',
|
||||
'ai.google.dev': 'Google AI (ai.google.dev)',
|
||||
'www.google.com': 'Google'
|
||||
}
|
||||
// 域名首段是这些通用词时,单独显示会分不清是哪个站点(比如两个 "chat")
|
||||
const GENERIC_DOMAIN_LABELS = new Set(['www', 'chat', 'ai', 'app', 'api', 'web', 'my', 'portal', 'console', 'platform'])
|
||||
|
||||
function siteDisplayName(domain) {
|
||||
const value = String(domain || '').trim()
|
||||
if (!value) return domain
|
||||
if (SITE_FRIENDLY_NAMES[value]) return SITE_FRIENDLY_NAMES[value]
|
||||
|
||||
const labels = value.replace(/^www\./, '').split('.')
|
||||
const first = labels[0] || value
|
||||
if (GENERIC_DOMAIN_LABELS.has(first.toLowerCase()) && labels.length > 1) {
|
||||
return first + ' · ' + labels[1]
|
||||
}
|
||||
return first
|
||||
}
|
||||
window.siteDisplayName = siteDisplayName
|
||||
|
||||
window.DashboardShared = {
|
||||
DEFAULT_SELECTOR_DEFINITIONS,
|
||||
BROWSER_CONSTANTS_SCHEMA,
|
||||
ENV_CONFIG_SCHEMA,
|
||||
DASHBOARD_TOKEN_STORAGE_KEY,
|
||||
LEGACY_API_TOKEN_STORAGE_KEY,
|
||||
SITE_CONFIG_IMPORT_MAX_BYTES,
|
||||
SETTINGS_BACKUP_IMPORT_MAX_BYTES,
|
||||
importFileSizeError,
|
||||
formatGitCompareErrorText,
|
||||
getStoredDashboardToken,
|
||||
setStoredDashboardToken,
|
||||
SITE_FRIENDLY_NAMES,
|
||||
GENERIC_DOMAIN_LABELS,
|
||||
siteDisplayName,
|
||||
};
|
||||
})();
|
||||
@@ -0,0 +1,84 @@
|
||||
// ==================== SVG 图标定义 ====================
|
||||
window.$icons = {
|
||||
window: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="M3 9h18M7 6.5h.01M10 6.5h.01"/></svg>`,
|
||||
checkCircle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><path d="m8 12 3 3 5-6"/></svg>`,
|
||||
exclamationTriangle: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m10.3 4.4-8 14A1.8 1.8 0 0 0 4 21h16a1.8 1.8 0 0 0 1.6-2.6l-8-14a1.9 1.9 0 0 0-3.3 0Z"/><path d="M12 9v4m0 4h.01"/></svg>`,
|
||||
documentText: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9Z"/><path d="M14 3v6h6M8 13h8M8 17h5"/></svg>`,
|
||||
link: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7 .1l3-3a5 5 0 0 0-7-7l-1.7 1.7M14 11a5 5 0 0 0-7-.1l-3 3a5 5 0 0 0 7 7l1.7-1.7"/></svg>`,
|
||||
minus: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/></svg>`,
|
||||
check: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m5 12 4 4L19 6"/></svg>`,
|
||||
codeBracket: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m8 5-6 7 6 7m8-14 6 7-6 7m-3-15-2 16"/></svg>`,
|
||||
photo: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="3"/><circle cx="8.5" cy="8" r="1.5"/><path d="m3 17 5-5 4 4 4-6 5 7"/></svg>`,
|
||||
cursorArrowRays: `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="m4 3 7 18 3-7 7-3L4 3Z"/><path d="m15 15 5 5"/></svg>`,
|
||||
home: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m3 11 9-8 9 8M5 10v10h14V10M9 20v-6h6v6"/></svg>`,
|
||||
|
||||
activity: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M22 12h-4l-3 9L9 3l-3 9H2"/></svg>`,
|
||||
|
||||
globe: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="9" stroke-width="2"/><path stroke-linecap="round" stroke-width="2" d="M3 12h18M12 3c2.3 2.5 3.5 5.5 3.5 9S14.3 18.5 12 21M12 3c-2.3 2.5-3.5 5.5-3.5 9S9.7 18.5 12 21"/></svg>`,
|
||||
|
||||
timer: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="13" r="8" stroke-width="2"/><path stroke-linecap="round" stroke-width="2" d="M12 9v4l2.5 2M9 2h6"/></svg>`,
|
||||
|
||||
server: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="3" y="4" width="18" height="6" rx="2" stroke-width="2"/><rect x="3" y="14" width="18" height="6" rx="2" stroke-width="2"/><path stroke-linecap="round" stroke-width="2" d="M7 7h.01M7 17h.01"/></svg>`,
|
||||
|
||||
arrowRight: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14m-6-6 6 6-6 6"/></svg>`,
|
||||
|
||||
magnifyingGlass: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7" stroke-width="2"/><path stroke-linecap="round" stroke-width="2" d="m20 20-4-4"/></svg>`,
|
||||
|
||||
beaker: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/></svg>`,
|
||||
|
||||
arrowDownTray: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5M16.5 12L12 16.5m0 0L7.5 12m4.5 4.5V3"/></svg>`,
|
||||
|
||||
arrowPath: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"/></svg>`,
|
||||
|
||||
plusCircle: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`,
|
||||
|
||||
trash: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.74 9l-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 01-2.244 2.077H8.084a2.25 2.25 0 01-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 00-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 013.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 00-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 00-7.5 0"/></svg>`,
|
||||
|
||||
xMark: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>`,
|
||||
|
||||
chevronUp: `<svg class="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.5 15.75l7.5-7.5 7.5 7.5"/></svg>`,
|
||||
|
||||
chevronDown: `<svg class="w-3 h-3 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.5 8.25l-7.5 7.5-7.5-7.5"/></svg>`,
|
||||
|
||||
clipboardList: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/></svg>`,
|
||||
|
||||
bookOpen: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6.042A8.967 8.967 0 006 3.75c-1.052 0-2.062.18-3 .512v14.25A8.987 8.987 0 016 18c2.305 0 4.408.867 6 2.292m0-14.25a8.966 8.966 0 016-2.292c1.052 0 2.062.18 3 .512v14.25A8.987 8.987 0 0018 18a8.967 8.967 0 00-6 2.292m0-14.25v14.25"/></svg>`,
|
||||
|
||||
moon: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21.752 15.002A9.718 9.718 0 0118 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 003 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 009.002-5.998z"/></svg>`,
|
||||
|
||||
sun: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v2.25m6.364.386l-1.591 1.591M21 12h-2.25m-.386 6.364l-1.591-1.591M12 18.75V21m-4.773-4.227l-1.591 1.591M5.25 12H3m4.227-4.773L5.636 5.636M15.75 12a3.75 3.75 0 11-7.5 0 3.75 3.75 0 017.5 0z"/></svg>`,
|
||||
|
||||
chartBar: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 13.125C3 12.504 3.504 12 4.125 12h2.25c.621 0 1.125.504 1.125 1.125v6.75C7.5 20.496 6.996 21 6.375 21h-2.25A1.125 1.125 0 013 19.875v-6.75zM9.75 8.625c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125v11.25c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V8.625zM16.5 4.125c0-.621.504-1.125 1.125-1.125h2.25C20.496 3 21 3.504 21 4.125v15.75c0 .621-.504 1.125-1.125 1.125h-2.25a1.125 1.125 0 01-1.125-1.125V4.125z"/></svg>`,
|
||||
|
||||
arrowUpTray: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"/></svg>`,
|
||||
|
||||
cog: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.343 3.94c.09-.542.56-.94 1.11-.94h1.093c.55 0 1.02.398 1.11.94l.149.894c.07.424.384.764.78.93.398.164.855.142 1.205-.108l.737-.527a1.125 1.125 0 011.45.12l.773.774c.39.389.44 1.002.12 1.45l-.527.737c-.25.35-.272.806-.107 1.204.165.397.505.71.93.78l.893.15c.543.09.94.56.94 1.109v1.094c0 .55-.397 1.02-.94 1.11l-.893.149c-.425.07-.765.383-.93.78-.165.398-.143.854.107 1.204l.527.738c.32.447.269 1.06-.12 1.45l-.774.773a1.125 1.125 0 01-1.449.12l-.738-.527c-.35-.25-.806-.272-1.203-.107-.397.165-.71.505-.781.929l-.149.894c-.09.542-.56.94-1.11.94h-1.094c-.55 0-1.019-.398-1.11-.94l-.148-.894c-.071-.424-.384-.764-.781-.93-.398-.164-.854-.142-1.204.108l-.738.527c-.447.32-1.06.269-1.45-.12l-.773-.774a1.125 1.125 0 01-.12-1.45l.527-.737c.25-.35.273-.806.108-1.204-.165-.397-.505-.71-.93-.78l-.894-.15c-.542-.09-.94-.56-.94-1.109v-1.094c0-.55.398-1.02.94-1.11l.894-.149c.424-.07.765-.383.93-.78.165-.398.143-.854-.107-1.204l-.527-.738a1.125 1.125 0 01.12-1.45l.773-.773a1.125 1.125 0 011.45-.12l.737.527c.35.25.807.272 1.204.107.397-.165.71-.505.78-.929l.15-.894z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/></svg>`,
|
||||
|
||||
folderOpen: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.75 9.776c.112-.017.227-.026.344-.026h15.812c.117 0 .232.009.344.026m-16.5 0a2.25 2.25 0 00-1.883 2.542l.857 6a2.25 2.25 0 002.227 1.932H19.05a2.25 2.25 0 002.227-1.932l.857-6a2.25 2.25 0 00-1.883-2.542m-16.5 0V6A2.25 2.25 0 016 3.75h3.879a1.5 1.5 0 011.06.44l2.122 2.12a1.5 1.5 0 001.06.44H18A2.25 2.25 0 0120.25 9v.776"/></svg>`,
|
||||
|
||||
shoppingBag: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16.5 10.5V6.75a4.5 4.5 0 10-9 0v3.75m-2.625 0h14.25A1.125 1.125 0 0120.25 11.7l-.75 7.5A2.25 2.25 0 0117.262 21H6.738A2.25 2.25 0 014.5 19.2l-.75-7.5A1.125 1.125 0 014.875 10.5z"/></svg>`,
|
||||
|
||||
documentArrowDown: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m.75 12l3 3m0 0l3-3m-3 3v-6m-1.5-9H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"/></svg>`,
|
||||
|
||||
arrowPathRoundedSquare: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.5 12c0-1.232-.046-2.453-.138-3.662a4.006 4.006 0 00-3.7-3.7 48.678 48.678 0 00-7.324 0 4.006 4.006 0 00-3.7 3.7c-.017.22-.032.441-.046.662M19.5 12l3-3m-3 3l-3-3m-12 3c0 1.232.046 2.453.138 3.662a4.006 4.006 0 003.7 3.7 48.656 48.656 0 007.324 0 4.006 4.006 0 003.7-3.7c.017-.22.032-.441.046-.662M4.5 12l3 3m-3-3l-3 3"/></svg>`,
|
||||
|
||||
arrowTopRightOnSquare: `<svg class="w-4 h-4 inline" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.5 6H19.5m0 0V12m0-6L10.5 15m6.75-10.5H8.25A2.25 2.25 0 006 6.75v9A2.25 2.25 0 008.25 18h9A2.25 2.25 0 0019.5 15.75v-9"/></svg>`,
|
||||
|
||||
pencil: `<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>`,
|
||||
|
||||
arrowUp: `<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19V5m0 0-6 6m6-6 6 6"/></svg>`,
|
||||
|
||||
arrowDown: `<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 5v14m0 0 6-6m-6 6-6-6"/></svg>`,
|
||||
|
||||
play: `<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="m8 5 11 7-11 7V5Z"/></svg>`,
|
||||
|
||||
pause: `<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5v14m6-14v14"/></svg>`,
|
||||
|
||||
power: `<svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v9m6.4-6.4a9 9 0 1 1-12.8 0"/></svg>`,
|
||||
|
||||
ellipsisVertical: `<svg class="h-4 w-4" fill="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="5" r="1.75"/><circle cx="12" cy="12" r="1.75"/><circle cx="12" cy="19" r="1.75"/></svg>`,
|
||||
|
||||
copy: `<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="11" height="11" rx="2" stroke-width="2"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h3"/></svg>`,
|
||||
|
||||
gripVertical: `<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 24 24"><circle cx="9" cy="5" r="1.5"/><circle cx="15" cy="5" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="19" r="1.5"/><circle cx="15" cy="19" r="1.5"/></svg>`
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user