Files
grok2api/app/statics/admin/config.html
T

1148 lines
53 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title data-i18n="config.pageTitle">Grok2API - 配置管理</title>
<link rel="icon" href="/favicon.ico?v={{APP_VERSION}}">
<link href="https://cdn.jsdelivr.net/npm/geist@1.0.0/dist/fonts/geist-sans/style.css" rel="stylesheet">
<link href="/static/css/app.css?v={{APP_VERSION}}" rel="stylesheet">
<style>
body { background: #FAF9F5 }
/* Page header */
.page-hd { display:flex; align-items:flex-start; justify-content:space-between; margin-bottom:20px }
.page-title{ font-size:22px; font-weight:700; line-height:1.2 }
.page-sub { font-size:13px; color:var(--fg-muted); margin-top:5px }
.page-actions { display:flex; gap:8px; align-items:center; flex-shrink:0 }
.page-action-btn {
height:32px; padding:0 14px; border-radius:999px;
display:inline-flex; align-items:center; justify-content:center; gap:6px;
font-size:13px; font-weight:600;
border:1px solid #e6e6e6; background:#fafafa; color:#444;
}
.page-action-btn:hover { background:#f3f3f3; border-color:#dcdcdc }
.page-action-btn-primary { background:#111; border-color:#111; color:#fff }
.page-action-btn-primary:hover { background:#222; border-color:#222 }
.page-action-btn:disabled { opacity:.4; pointer-events:none }
/* Section nav tabs */
.cfg-nav {
display:flex;
align-items:center;
gap:6px;
flex-wrap:wrap;
margin-bottom:16px;
padding:0;
}
.cfg-tab {
height:30px;
padding:0 12px;
border-radius:999px;
font-size:12px;
font-weight:500;
color:#8f8f8f;
background:#f5f5f5;
transition:color .15s, background .15s;
cursor:pointer;
}
.cfg-tab:hover { color:#555; background:#f1f1f1 }
.cfg-tab.active {
background:#111;
color:#fff;
font-weight:600;
}
.cfg-tab .dot {
display:none;
width:6px;
height:6px;
border-radius:50%;
background:currentColor;
margin-left:5px;
vertical-align:middle;
opacity:.45;
}
.cfg-tab.dirty .dot { display:inline-block }
/* Section panels */
.cfg-panel { display:none }
.cfg-panel.active { display:block }
/* Field rows */
.cfg-group {
background:#fff;
border:none;
border-radius:12px;
overflow:hidden;
margin-bottom:12px;
}
.cfg-group-title {
font-size:11px;
font-weight:700;
color:#8d8d8d;
text-transform:uppercase;
letter-spacing:.08em;
padding:12px 16px 6px;
background:#fff;
border-bottom:none;
}
.cfg-row {
display:grid;
grid-template-columns:minmax(0, 2fr) minmax(300px, 1fr);
gap:18px;
align-items:center;
padding:11px 16px;
border-bottom:1px solid #f5f5f5;
transition:background .15s;
}
.cfg-row:last-child { border-bottom:none }
.cfg-row:hover { background:#fcfcfc }
.cfg-row.modified { background:#fffaf0 }
.cfg-row.modified:hover { background:#fff6e7 }
.cfg-label-col { min-width:0; display:grid; gap:3px; align-content:start }
.cfg-label {
display:inline-flex;
align-items:center;
gap:6px;
font-size:12px;
font-weight:600;
color:#222;
line-height:1.35;
}
.cfg-desc { max-width:520px; font-size:11px; color:#9a9a9a; line-height:1.45 }
.cfg-input-col { min-width:0; display:flex; align-items:center; justify-content:flex-start; gap:8px }
.cfg-input-col.is-bool { justify-content:flex-end }
.cfg-inline-action {
width:16px;
height:16px;
display:inline-flex;
align-items:center;
justify-content:center;
padding:0;
color:#9a9a9a;
border:0;
background:transparent;
cursor:pointer;
flex-shrink:0;
transition:color .15s, opacity .15s, transform .15s;
}
.cfg-inline-action:hover { color:#222; transform:translateY(-.5px) }
.cfg-inline-action:disabled {
opacity:.32;
cursor:not-allowed;
pointer-events:none;
}
.cfg-inline-action svg { width:14px; height:14px; display:block }
/* Inputs */
.cfg-text {
width:100%;
max-width:none;
height:32px;
padding:0 10px;
font-size:13px;
border-radius:8px;
border:1px solid #ececec;
background:#fbfbfb;
transition:border-color .15s, background .15s;
font-family: inherit; text-align:right;
}
.cfg-text:focus { border-color:#d7d7d7; background:#fff; outline:none; box-shadow:none }
.cfg-text.wide { max-width:none }
.cfg-textarea {
width:100%;
max-width:none;
min-height:72px;
padding:8px 10px;
font-size:12px;
border-radius:10px;
border:1px solid #ececec;
background:#fbfbfb;
resize:vertical;
transition:border-color .15s, background .15s;
font-family: 'Geist Mono', 'Courier New', monospace; line-height:1.5; text-align:right;
}
.cfg-textarea:focus { border-color:#d7d7d7; background:#fff; outline:none }
.cfg-number {
width:100%;
max-width:none;
height:32px;
padding:0 10px;
font-size:13px;
border-radius:8px;
border:1px solid #ececec;
background:#fbfbfb;
text-align:right;
}
.cfg-number:focus { border-color:#d7d7d7; background:#fff; outline:none }
.cfg-select {
width:100%;
height:32px;
padding:0 28px 0 10px;
font-size:13px;
border-radius:8px;
border:1px solid #ececec;
background:#fbfbfb;
appearance:none; background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24'%3E%3Cpath d='M6 9l6 6 6-6' stroke='%23666' stroke-width='2' fill='none'/%3E%3C/svg%3E");
background-repeat:no-repeat; background-position:right 8px center;
cursor:pointer; text-align:right;
}
.cfg-select:focus { border-color:#d7d7d7; background:#fff; outline:none }
/* Toggle switch */
.toggle {
position:relative; display:inline-block; width:36px; height:20px; flex-shrink:0;
}
.toggle input { opacity:0; width:0; height:0 }
.toggle-track {
position:absolute; cursor:pointer; inset:0;
background:#ddd; border-radius:20px; transition:background .2s;
}
.toggle-track::before {
content:''; position:absolute; width:14px; height:14px;
left:3px; bottom:3px; background:#fff; border-radius:50%;
transition:transform .2s; box-shadow:0 1px 2px rgba(0,0,0,.15);
}
.toggle input:checked + .toggle-track { background:#111 }
.toggle input:checked + .toggle-track::before { transform:translateX(16px) }
/* Modified badge */
.cfg-modified-dot {
display:inline-block; width:6px; height:6px; border-radius:50%;
background:#f59e0b; margin-left:6px; vertical-align:middle;
visibility:hidden;
}
.cfg-row.modified .cfg-modified-dot { visibility:visible }
/* Random button */
.cfg-rand-btn {
width:30px; height:30px; border-radius:999px;
display:inline-flex; align-items:center; justify-content:center;
color:#6a6a6a; border:1px solid #ececec; background:#fafafa;
cursor:pointer; flex-shrink:0; transition:background .15s, border-color .15s;
}
.cfg-rand-btn:hover { background:#f3f3f3; border-color:#dddddd; color:#222 }
/* Save bar */
.save-bar {
position:fixed;
left:50%;
bottom:18px;
z-index:50;
width:min(calc(100% - 56px), 1280px);
transform:translate(-50%, calc(100% + 20px));
background:rgba(255,255,255,.96);
border:1px solid #efefef;
border-radius:16px;
padding:12px 16px;
display:flex;
align-items:center;
justify-content:space-between;
gap:12px;
transition:transform .25s ease;
}
.save-bar.visible { transform:translate(-50%, 0) }
.save-bar-msg { font-size:13px; color:var(--fg-muted) }
.save-bar-actions { display:flex; gap:8px }
.save-bar-btn {
height:32px;
padding:0 14px;
border-radius:999px;
font-size:13px;
font-weight:600;
border:1px solid transparent;
cursor:pointer;
}
.save-bar-btn-cancel { border-color:#e6e6e6; background:#fafafa; color:#444 }
.save-bar-btn-cancel:hover { background:#f3f3f3; border-color:#dcdcdc }
.save-bar-btn-save { background:#111; color:#fff }
.save-bar-btn-save:hover { background:#222 }
@media (max-width:640px) {
.cfg-row { grid-template-columns:1fr; gap:8px; align-items:flex-start }
.cfg-input-col { justify-content:flex-start }
.cfg-nav { gap:8px }
.save-bar {
width:calc(100% - 24px);
bottom:12px;
padding:12px;
flex-direction:column;
align-items:stretch;
}
.save-bar-actions { justify-content:flex-end }
}
</style>
</head>
<body>
<!-- ── Header ─────────────────────────────────────────────────────────────── -->
<div id="admin-header" data-active="/admin/config"></div>
<!-- ── Main ───────────────────────────────────────────────────────────────── -->
<main class="admin-main" style="padding-bottom:80px">
<div class="page-hd">
<div>
<div class="page-title" data-i18n="config.pageHeading">配置管理</div>
<div class="page-sub" data-i18n="config.pageSubtitle">统一管理运行时参数与服务行为。保存后即时生效,部分配置需重启服务。</div>
</div>
<div class="page-actions">
<button id="btn-reset" onclick="doReset()" class="page-action-btn">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 1 0 3-6.708"/><path d="M3 4v5h5"/></svg>
<span data-i18n="config.resetShort">重置</span>
</button>
<button id="btn-save" onclick="doSave()" class="page-action-btn page-action-btn-primary" disabled>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m5 12 4.2 4.2L19 6.5"/></svg>
<span data-i18n="config.saveShort">保存</span>
</button>
</div>
</div>
<!-- Section tabs -->
<div class="cfg-nav" id="cfg-nav"></div>
<!-- Section panels, rendered by JS -->
<div id="cfg-panels"></div>
</main>
<!-- ── Save bar (bottom) ──────────────────────────────────────────────────── -->
<div class="save-bar" id="save-bar">
<div class="save-bar-msg" id="save-bar-msg" data-i18n="config.unsavedDefault">存在未保存的更改</div>
<div class="save-bar-actions">
<button class="save-bar-btn save-bar-btn-cancel" onclick="doReset()" data-i18n="config.discardShort">撤销</button>
<button class="save-bar-btn save-bar-btn-save" onclick="doSave()" data-i18n="config.saveBarShort">保存</button>
</div>
</div>
<script src="/static/js/i18n.js?v={{APP_VERSION}}"></script>
<script src="/static/js/auth.js?v={{APP_VERSION}}"></script>
<script src="/static/js/admin-header.js?v={{APP_VERSION}}"></script>
<script src="/static/js/toast.js?v={{APP_VERSION}}"></script>
<script src="/static/js/footer.js?v={{APP_VERSION}}"></script>
<script>
// ── Config schema ──────────────────────────────────────────────────────────
// Each group has a `section` (full dotted TOML path, e.g. "proxy.egress").
// Each field has a `key` (leaf key within that section).
// Full config path = section + '.' + key.
const SCHEMA_DEF = [
{
id: 'system', label: '系统配置', labelKey: 'config.schema.tabs.system',
groups: [
{
title: '基础访问控制', titleKey: 'config.schema.groups.baseAccess',
section: 'app',
fields: [
{ key: 'app_url', label: 'APP 访问地址', labelKey: 'config.schema.fields.appUrl.label', type: 'text', desc: '应用对外提供服务的根 URL,格式如 https://your-domain.com。本地代理模式必须配置。', descKey: 'config.schema.fields.appUrl.desc', wide: true },
{ key: 'app_key', label: 'APP 访问密码', labelKey: 'config.schema.fields.appKey.label', type: 'password', desc: '管理后台鉴权密码。修改后已有 Session 将立即失效,需重新登录。', descKey: 'config.schema.fields.appKey.desc', rand: true },
{ key: 'api_key', label: 'API 调用密钥', labelKey: 'config.schema.fields.apiKey.label', type: 'text', desc: 'OpenAI 兼容 API 的鉴权密钥。多个值请使用英文逗号分隔;留空则禁用鉴权。', descKey: 'config.schema.fields.apiKey.desc', rand: true },
{ key: 'webui_enabled', label: '启用 WebUI', labelKey: 'config.schema.fields.webuiEnabled.label', type: 'bool', desc: '开放 WebUI 功能入口。关闭后相关路由将返回 404。', descKey: 'config.schema.fields.webuiEnabled.desc' },
{ key: 'webui_key', label: 'WebUI 访问密码', labelKey: 'config.schema.fields.webuiKey.label', type: 'password', desc: 'WebUI 的访问鉴权密码。配置后访问时必须提供。', descKey: 'config.schema.fields.webuiKey.desc', rand: true, showIf: 'app.webui_enabled' },
]
},
{
title: '日志配置', titleKey: 'config.schema.groups.logging',
section: 'logging',
fields: [
{
key: 'file_level',
label: '文件日志等级',
labelKey: 'config.schema.fields.fileLogLevel.label',
type: 'select',
options: [
{ value: 'DEBUG', label: 'DEBUG' },
{ value: 'INFO', label: 'INFO' },
{ value: 'WARNING', label: 'WARNING' },
{ value: 'ERROR', label: 'ERROR' },
],
desc: '日志文件写入的最低等级,可独立于控制台配置。默认 INFO。',
descKey: 'config.schema.fields.fileLogLevel.desc',
},
{
key: 'max_files',
label: '日志保留天数',
labelKey: 'config.schema.fields.logMaxFiles.label',
type: 'number',
desc: '按天轮转时最多保留的日志文件数量。默认 7。',
descKey: 'config.schema.fields.logMaxFiles.desc',
},
]
},
]
},
{
id: 'features', label: '应用功能', labelKey: 'config.schema.tabs.features',
groups: [
{
title: '基本功能设置', titleKey: 'config.schema.groups.features',
section: 'features',
fields: [
{ key: 'temporary', label: '临时会话', labelKey: 'config.schema.fields.temporary.label', type: 'bool', desc: '启用后请求不会写入 Grok 会话历史,等同于无痕对话。', descKey: 'config.schema.fields.temporary.desc' },
{ key: 'memory', label: '开启会话记忆', labelKey: 'config.schema.fields.memory.label', type: 'bool', desc: '启用 Grok Memory,允许模型跨会话记忆用户偏好与上下文。', descKey: 'config.schema.fields.memory.desc' },
{ key: 'stream', label: '默认流式输出', labelKey: 'config.schema.fields.stream.label', type: 'bool', desc: '请求未显式指定 stream 参数时所采用的默认值。', descKey: 'config.schema.fields.stream.desc' },
{ key: 'thinking', label: '默认思考输出', labelKey: 'config.schema.fields.thinking.label', type: 'bool', desc: '请求未显式指定 thinking 参数时所采用的默认值。启用后将在 reasoning_content 字段返回思考过程。', descKey: 'config.schema.fields.thinking.desc' },
{ key: 'thinking_summary', label: '思考精简输出', labelKey: 'config.schema.fields.thinkingSummary.label', type: 'bool', desc: '启用后将思考过程提炼为结构化摘要。关闭时输出完整的原始推理过程,支持多 Agent 模型的协作详情与工具调用展示。', descKey: 'config.schema.fields.thinkingSummary.desc' },
{ key: 'dynamic_statsig', label: '动态 Statsig', labelKey: 'config.schema.fields.dynamicStatsig.label', type: 'bool', desc: '为每次请求动态生成 Statsig 设备指纹,以降低风控拦截概率。', descKey: 'config.schema.fields.dynamicStatsig.desc' },
{ key: 'enable_nsfw', label: '允许 NSFW 生成', labelKey: 'config.schema.fields.enableNsfw.label', type: 'bool', desc: '允许图像生成接口绕过 NSFW 内容过滤。', descKey: 'config.schema.fields.enableNsfw.desc' },
{ key: 'custom_instruction', label: '全局附加指令', labelKey: 'config.schema.fields.customInstruction.label', type: 'textarea', desc: '为每次请求注入统一的 system 消息,用于约束模型行为或固定角色设定。', descKey: 'config.schema.fields.customInstruction.desc' },
]
},
{
title: '媒体返回格式', titleKey: 'config.schema.groups.mediaFormat',
section: 'features',
fields: [
{
key: 'image_format',
label: '图片返回格式',
labelKey: 'config.schema.fields.imageFormat.label',
type: 'select',
options: [
{ value: 'grok_url', label: 'URL(Grok 原生)', labelKey: 'config.schema.options.imageFormat.grokUrl' },
{ value: 'local_url', label: 'URL(本地代理)', labelKey: 'config.schema.options.imageFormat.localUrl', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
{ value: 'grok_md', label: 'Markdown(Grok 原生)', labelKey: 'config.schema.options.imageFormat.grokMarkdown' },
{ value: 'local_md', label: 'Markdown(本地代理)', labelKey: 'config.schema.options.imageFormat.localMarkdown', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
{ value: 'base64', label: 'Base64(内嵌)', labelKey: 'config.schema.options.imageFormat.base64' },
],
desc: 'grok_url / grok_md 直接返回 Grok CDN 地址,客户端需具备 CDN 访问能力;local_* 模式会先下载到服务端,再通过本地 URL 代理分发;base64 会以内嵌 Data URI 返回。',
descKey: 'config.schema.fields.imageFormat.desc',
},
{
key: 'video_format',
label: '视频返回格式',
labelKey: 'config.schema.fields.videoFormat.label',
type: 'select',
options: [
{ value: 'grok_url', label: 'URL(Grok 原生)', labelKey: 'config.schema.options.videoFormat.grokUrl' },
{ value: 'local_url', label: 'URL(本地代理)', labelKey: 'config.schema.options.videoFormat.localUrl', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
{ value: 'grok_html', label: 'HTML(Grok 原生)', labelKey: 'config.schema.options.videoFormat.grokHtml' },
{ value: 'local_html', label: 'HTML(本地代理)', labelKey: 'config.schema.options.videoFormat.localHtml', disabledWhen: 'no_app_url', disabledTip: '请先填写 APP 访问地址', disabledTipKey: 'config.disabledTip.appUrlRequired' },
],
desc: 'local_* 模式会先将视频下载至服务端,再通过本地 URL 代理分发;请确保已配置 APP 访问地址,并评估出站带宽消耗。',
descKey: 'config.schema.fields.videoFormat.desc',
},
]
},
]
},
{
id: 'schedule', label: '任务调度', labelKey: 'config.schema.tabs.schedule',
groups: [
{
title: '配额刷新调度', titleKey: 'config.schema.groups.refreshSchedule',
section: 'account.refresh',
fields: [
{ key: 'basic_interval_sec', label: 'Basic 刷新周期(秒)', labelKey: 'config.schema.fields.basicInterval.label', type: 'number', desc: 'basic 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 36000 s / 10 h)。', descKey: 'config.schema.fields.basicInterval.desc' },
{ key: 'super_interval_sec', label: 'Super 刷新周期(秒)', labelKey: 'config.schema.fields.superInterval.label', type: 'number', desc: 'super 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 7200 s / 2 h)。', descKey: 'config.schema.fields.superInterval.desc' },
{ key: 'heavy_interval_sec', label: 'Heavy 刷新周期(秒)', labelKey: 'config.schema.fields.heavyInterval.label', type: 'number', desc: 'heavy 号池额度的定时刷新间隔,建议与配额窗口对齐(默认 7200 s / 2 h)。', descKey: 'config.schema.fields.heavyInterval.desc' },
{ key: 'on_demand_min_interval_sec', label: '按需刷新最小间隔(秒)', labelKey: 'config.schema.fields.onDemandMinInterval.label', type: 'number', desc: '请求链路触发刷新(例如收到 429)时的节流间隔。N 秒内重复触发只执行一次,避免批量打爆配额接口。', descKey: 'config.schema.fields.onDemandMinInterval.desc' },
{ key: 'usage_concurrency', label: '刷新并发数', labelKey: 'config.schema.fields.usageConcurrency.label', type: 'number', desc: '并发调用 usage 接口刷新额度时允许的最大并行数。', descKey: 'config.schema.fields.usageConcurrency.desc' },
]
},
{
title: '批量操作并发', titleKey: 'config.schema.groups.batchConcurrency',
section: 'batch',
fields: [
{ key: 'nsfw_concurrency', label: '开启 NSFW 并发数', labelKey: 'config.schema.fields.nsfwConcurrency.label', type: 'number', desc: '批量开启 NSFW 时的 token 级并发数;每个 token 需经历三步网络请求。', descKey: 'config.schema.fields.nsfwConcurrency.desc' },
{ key: 'refresh_concurrency', label: '刷新 Usage 并发数', labelKey: 'config.schema.fields.refreshConcurrency.label', type: 'number', desc: '批量刷新账户额度时的 token 级并发数。', descKey: 'config.schema.fields.refreshConcurrency.desc' },
{ key: 'asset_upload_concurrency', label: '上传 Asset 并发数', labelKey: 'config.schema.fields.assetUploadConcurrency.label', type: 'number', desc: 'API 接收文件附件后触发的 Asset 上传任务,全局最大并发数,跨所有请求共享。', descKey: 'config.schema.fields.assetUploadConcurrency.desc' },
{ key: 'asset_list_concurrency', label: '查询 Asset 并发数', labelKey: 'config.schema.fields.assetListConcurrency.label', type: 'number', desc: 'list_assets 接口的全局最大并发数,跨所有请求共享。', descKey: 'config.schema.fields.assetListConcurrency.desc' },
{ key: 'asset_delete_concurrency', label: '删除 Asset 并发数', labelKey: 'config.schema.fields.assetDeleteConcurrency.label', type: 'number', desc: 'delete_asset 接口的全局最大并发数,同时作为管理后台批量清理的 token 级默认并发值。', descKey: 'config.schema.fields.assetDeleteConcurrency.desc' },
]
},
]
},
{
id: 'proxy', label: '网络代理', labelKey: 'config.schema.tabs.proxy',
groups: [
{
title: '出站代理设置', titleKey: 'config.schema.groups.egressProxy',
section: 'proxy.egress',
fields: [
{
key: 'mode',
label: '代理模式',
labelKey: 'config.schema.fields.proxyMode.label',
type: 'select',
options: [
{ value: 'direct', label: '直连', labelKey: 'config.schema.options.proxyMode.direct' },
{ value: 'single_proxy', label: '代理(固定)', labelKey: 'config.schema.options.proxyMode.singleProxy' },
{ value: 'proxy_pool', label: '代理(轮转)', labelKey: 'config.schema.options.proxyMode.proxyPool' },
],
desc: '控制出站流量代理策略。direct 为直连;single_proxy 使用固定代理;proxy_pool 在代理池中轮转。',
descKey: 'config.schema.fields.proxyMode.desc',
},
{
key: 'proxy_url',
label: '基础代理 URL',
labelKey: 'config.schema.fields.proxyUrl.label',
type: 'text',
wide: true,
desc: 'API 流量的出站代理地址,支持 http、https、socks5 协议。',
descKey: 'config.schema.fields.proxyUrl.desc',
showIf: { path: 'proxy.egress.mode', values: ['single_proxy'] },
},
{
key: 'resource_proxy_url',
label: '资源代理 URL',
labelKey: 'config.schema.fields.resourceProxyUrl.label',
type: 'text',
wide: true,
desc: '图片、视频等媒体资源下载的专用代理地址;留空时回落至基础代理。',
descKey: 'config.schema.fields.resourceProxyUrl.desc',
showIf: { path: 'proxy.egress.mode', values: ['single_proxy'] },
},
{
key: 'proxy_pool',
label: '基础代理池',
labelKey: 'config.schema.fields.proxyPool.label',
type: 'textarea',
desc: 'API 流量代理池,每行一个代理 URL,请求时轮转使用。',
descKey: 'config.schema.fields.proxyPool.desc',
showIf: { path: 'proxy.egress.mode', values: ['proxy_pool'] },
},
{
key: 'resource_proxy_pool',
label: '资源代理池',
labelKey: 'config.schema.fields.resourceProxyPool.label',
type: 'textarea',
desc: '媒体资源下载专用代理池,每行一个代理 URL;留空时回落至基础代理池。',
descKey: 'config.schema.fields.resourceProxyPool.desc',
showIf: { path: 'proxy.egress.mode', values: ['proxy_pool'] },
},
{
key: 'skip_ssl_verify',
label: '跳过 SSL 校验',
labelKey: 'config.schema.fields.skipSslVerify.label',
type: 'bool',
desc: '跳过代理服务器 TLS 证书校验,仅在使用自签名证书的代理时启用。',
descKey: 'config.schema.fields.skipSslVerify.desc',
showIf: { path: 'proxy.egress.mode', values: ['single_proxy', 'proxy_pool'] },
},
]
},
{
title: 'Cloudflare Clearance', titleKey: 'config.schema.groups.clearance',
section: 'proxy.clearance',
fields: [
{
key: 'mode',
label: 'Clearance 校准',
labelKey: 'config.schema.fields.clearanceMode.label',
type: 'select',
options: [
{ value: 'none', label: '关闭', labelKey: 'config.schema.options.clearanceMode.none' },
{ value: 'manual', label: '手动', labelKey: 'config.schema.options.clearanceMode.manual' },
{ value: 'flaresolverr', label: 'FlareSolverr', labelKey: 'config.schema.options.clearanceMode.flaresolverr' },
],
desc: '控制 Cloudflare Clearance 的获取方式。',
descKey: 'config.schema.fields.clearanceMode.desc',
},
{
key: 'browser',
label: '浏览器指纹',
labelKey: 'config.schema.fields.browserFingerprint.label',
type: 'text',
desc: 'curl_cffi 浏览器指纹标识,需与 Cloudflare 期望的 JA3 指纹匹配,例如 chrome136。',
descKey: 'config.schema.fields.browserFingerprint.desc',
showIf: { path: 'proxy.clearance.mode', values: ['manual', 'flaresolverr'] },
},
{
key: 'user_agent',
label: 'User-Agent',
labelKey: 'config.schema.fields.userAgent.label',
type: 'text',
wide: true,
desc: '请求头中的 User-Agent,需与 Cloudflare 校验 Cookie 时所使用的浏览器保持一致。',
descKey: 'config.schema.fields.userAgent.desc',
showIf: { path: 'proxy.clearance.mode', values: ['manual'] },
},
{
key: 'cf_cookies',
label: 'Cloudflare Cookies',
labelKey: 'config.schema.fields.cfCookies.label',
type: 'text',
wide: true,
desc: 'Cloudflare 下发的完整 Cookie 字符串,应包含 cf_clearance 等字段。',
descKey: 'config.schema.fields.cfCookies.desc',
showIf: { path: 'proxy.clearance.mode', values: ['manual'] },
},
{
key: 'flaresolverr_url',
label: 'FlareSolverr URL',
labelKey: 'config.schema.fields.flaresolverrUrl.label',
type: 'text',
wide: true,
desc: 'FlareSolverr 实例的 HTTP 服务地址。',
descKey: 'config.schema.fields.flaresolverrUrl.desc',
showIf: { path: 'proxy.clearance.mode', values: ['flaresolverr'] },
},
{
key: 'timeout_sec',
label: '挑战超时(秒)',
labelKey: 'config.schema.fields.challengeTimeout.label',
type: 'number',
desc: 'FlareSolverr 完成 Cloudflare 挑战允许的最长等待时长。',
descKey: 'config.schema.fields.challengeTimeout.desc',
showIf: { path: 'proxy.clearance.mode', values: ['flaresolverr'] },
},
{
key: 'refresh_interval',
label: '刷新间隔(秒)',
labelKey: 'config.schema.fields.refreshInterval.label',
type: 'number',
desc: 'Clearance Cookie 预热刷新任务的调度间隔。',
descKey: 'config.schema.fields.refreshInterval.desc',
showIf: { path: 'proxy.clearance.mode', values: ['flaresolverr'] },
},
]
},
{
title: '重试策略', titleKey: 'config.schema.groups.retry',
section: 'retry',
fields: [
{ key: 'max_retries', label: '应用层重试上限', labelKey: 'config.schema.fields.maxRetries.label', type: 'number', desc: '请求失败后的应用层最大重试次数;0 表示不重试。适用于 chat.completions 与 responses 端点。', descKey: 'config.schema.fields.maxRetries.desc' },
{ key: 'on_codes', label: '应用层重试触发状态码', labelKey: 'config.schema.fields.retryCodes.label', type: 'text', desc: '收到指定 HTTP 状态码时触发应用层重试,多个值请使用英文逗号分隔,例如 429,503。', descKey: 'config.schema.fields.retryCodes.desc' },
{ key: 'reset_session_status_codes', label: '传输层会话重建状态码', labelKey: 'config.schema.fields.resetSessionCodes.label', type: 'text', desc: '收到指定 HTTP 状态码时自动重建传输层代理会话(Transport Session),多个值请使用英文逗号分隔。', descKey: 'config.schema.fields.resetSessionCodes.desc' },
]
},
{
title: '请求超时设置', titleKey: 'config.schema.groups.timeouts',
section: 'chat',
fields: [
{ key: 'timeout', section: 'chat', label: '对话请求超时(秒)', labelKey: 'config.schema.fields.chatTimeout.label', type: 'number', desc: '对话与图像编辑请求的 HTTP 连接超时时间。', descKey: 'config.schema.fields.chatTimeout.desc' },
{ key: 'timeout', section: 'image', label: '图像请求超时(秒)', labelKey: 'config.schema.fields.imageTimeout.label', type: 'number', desc: '图像生成 WebSocket 请求的总超时时间。', descKey: 'config.schema.fields.imageTimeout.desc' },
{ key: 'stream_timeout', section: 'image', label: '图像流式空闲超时(秒)', type: 'number', desc: '图像生成 WebSocket 在流式接收阶段允许的最长连续空闲等待时长。' },
{ key: 'timeout', section: 'video', label: '视频请求超时(秒)', labelKey: 'config.schema.fields.videoTimeout.label', type: 'number', desc: '视频生成请求的统一超时时间。', descKey: 'config.schema.fields.videoTimeout.desc' },
{ key: 'timeout', section: 'voice', label: '语音请求超时(秒)', labelKey: 'config.schema.fields.voiceTimeout.label', type: 'number', desc: '语音请求的统一超时时间。', descKey: 'config.schema.fields.voiceTimeout.desc' },
{ key: 'timeout', section: 'nsfw', label: 'NSFW 处理超时(秒)', labelKey: 'config.schema.fields.nsfwTimeout.label', type: 'number', desc: 'set_birth_date 与 enable_nsfw 接口调用的超时时间。', descKey: 'config.schema.fields.nsfwTimeout.desc' },
{ key: 'upload_timeout', section: 'asset', label: '资产上传超时(秒)', labelKey: 'config.schema.fields.assetUploadTimeout.label', type: 'number', desc: 'Asset 上传接口的超时时间。', descKey: 'config.schema.fields.assetUploadTimeout.desc' },
{ key: 'download_timeout', section: 'asset', label: '资产下载超时(秒)', labelKey: 'config.schema.fields.assetDownloadTimeout.label', type: 'number', desc: 'Asset 下载接口的超时时间。', descKey: 'config.schema.fields.assetDownloadTimeout.desc' },
{ key: 'list_timeout', section: 'asset', label: '资产查询超时(秒)', labelKey: 'config.schema.fields.assetListTimeout.label', type: 'number', desc: 'Asset 查询接口的超时时间。', descKey: 'config.schema.fields.assetListTimeout.desc' },
{ key: 'delete_timeout', section: 'asset', label: '资产删除超时(秒)', labelKey: 'config.schema.fields.assetDeleteTimeout.label', type: 'number', desc: 'Asset 删除接口的超时时间。', descKey: 'config.schema.fields.assetDeleteTimeout.desc' },
]
},
]
},
];
// ── State ──────────────────────────────────────────────────────────────────
let SCHEMA = [];
let _cfg = {}; // loaded config (nested)
let _dirty = {}; // { "section.key": newValue }
let _activeTab = SCHEMA_DEF[0].id;
let _configLoaded = false;
let _rowRefs = new Map();
let _tabButtons = new Map();
let _tabDirtyCounts = new Map();
let _tabFieldIndex = new Map();
let _conditionalRows = [];
let _selectRefs = [];
let _showIfDeps = new Map();
let _disabledSelectDeps = new Map();
function tr(key, params, fallback) {
if (!key) return fallback ?? '';
const value = t(key, params);
return value === key ? (fallback ?? key) : value;
}
function waitI18n() {
return new Promise((resolve) => I18n.onReady(resolve));
}
function _addDependency(depMap, path, target) {
if (!path || !target) return;
if (!depMap.has(path)) depMap.set(path, []);
depMap.get(path).push(target);
}
function _showIfPaths(showIf) {
if (!showIf) return [];
return [typeof showIf === 'string' ? showIf : showIf.path].filter(Boolean);
}
function _disabledWhenPaths(condition) {
if (condition === 'no_app_url') return ['app.app_url'];
return [];
}
function _collectDependentTargets(paths, depMap) {
if (!Array.isArray(paths) || !paths.length) return [];
const seen = new Set();
const items = [];
paths.forEach((path) => {
(depMap.get(path) || []).forEach((target) => {
if (seen.has(target)) return;
seen.add(target);
items.push(target);
});
});
return items;
}
function _syncTabDirtyState(tabId) {
const btn = _tabButtons.get(tabId);
if (!btn) return;
btn.classList.toggle('dirty', (_tabDirtyCounts.get(tabId) || 0) > 0);
}
function _updateDirtyCount(fp, delta) {
const tabId = _tabFieldIndex.get(fp);
if (!tabId || !delta) return;
const next = Math.max(0, (_tabDirtyCounts.get(tabId) || 0) + delta);
_tabDirtyCounts.set(tabId, next);
_syncTabDirtyState(tabId);
}
function _resetRenderCaches() {
_rowRefs = new Map();
_tabButtons = new Map();
_tabDirtyCounts = new Map();
_tabFieldIndex = new Map();
_conditionalRows = [];
_selectRefs = [];
_showIfDeps = new Map();
_disabledSelectDeps = new Map();
}
function _localizeOption(opt) {
if (typeof opt !== 'object') return opt;
return {
...opt,
label: tr(opt.labelKey, null, opt.label ?? opt.value),
...(opt.disabledTipKey ? { disabledTip: tr(opt.disabledTipKey, null, opt.disabledTip ?? '') } : {}),
};
}
function _localizeField(field) {
return {
...field,
label: field.labelKey ? tr(field.labelKey, null, field.label ?? field.key) : (field.label ?? field.key),
desc: field.descKey ? tr(field.descKey, null, field.desc ?? '') : (field.desc ?? ''),
options: field.options ? field.options.map(_localizeOption) : field.options,
};
}
function buildSchema() {
return SCHEMA_DEF.map((tab) => ({
...tab,
label: tr(tab.labelKey, null, tab.label ?? tab.id),
groups: tab.groups.map((group) => ({
...group,
title: group.titleKey ? tr(group.titleKey, null, group.title ?? '') : (group.title ?? ''),
fields: group.fields.map(_localizeField),
})),
}));
}
function applyConfigI18n() {
document.title = tr('config.pageTitle', null, 'Grok2API - 配置管理');
SCHEMA = buildSchema();
if (!_configLoaded) return;
renderAll();
_refreshDirtyState({ autoNormalizeSelects: false });
}
// ── API ────────────────────────────────────────────────────────────────────
async function _api(method, path, body) {
const key = await adminKey.get();
const r = await fetch(ADMIN_API + path, {
method,
headers: { ...(body != null && { 'Content-Type': 'application/json' }), Authorization: `Bearer ${key}` },
...(body != null && { body: JSON.stringify(body) }),
});
if (!r.ok) { const d = await r.json().catch(() => ({})); throw new Error(d.detail || r.status); }
return r.json();
}
// ── Schema helpers ─────────────────────────────────────────────────────────
// Navigate a nested object by dotted path. Returns undefined if any segment is missing.
function _getByPath(obj, dottedPath) {
return dottedPath.split('.').reduce((node, k) =>
(node != null && typeof node === 'object') ? node[k] : undefined, obj);
}
// Set a value at a dotted path, creating intermediate objects as needed.
function _setByPath(obj, dottedPath, value) {
const keys = dottedPath.split('.');
let cur = obj;
for (let i = 0; i < keys.length - 1; i++) {
if (cur[keys[i]] == null || typeof cur[keys[i]] !== 'object') cur[keys[i]] = {};
cur = cur[keys[i]];
}
cur[keys[keys.length - 1]] = value;
}
// Evaluate a disabledWhen condition on a select option.
// Currently supported: 'no_app_url' — true when app.app_url is empty.
function _evalDisabledWhen(condition) {
if (condition === 'no_app_url') {
const v = 'app.app_url' in _dirty ? _dirty['app.app_url'] : _getByPath(_cfg, 'app.app_url');
return !v || String(v).trim() === '';
}
return false;
}
// Evaluate a showIf condition.
// String form: truthy check on config path. "app.webui_enabled"
// Object form: value-in-list check. { path: "proxy.egress.mode", values: ["single_proxy"] }
function _evalShowIf(showIf) {
if (!showIf) return true;
const path = typeof showIf === 'string' ? showIf : showIf.path;
const cur = path in _dirty ? _dirty[path] : _getByPath(_cfg, path);
if (typeof showIf === 'string') return !!cur;
return showIf.values.includes(cur);
}
// Full dotted config path for a field: "proxy.egress.mode"
function _fullPath(section, key) { return `${section}.${key}`; }
// Get the current value of a field from loaded config.
function _getValue(section, key) { return _getByPath(_cfg, _fullPath(section, key)); }
function _getCurrentValue(section, key) {
const fp = _fullPath(section, key);
return fp in _dirty ? _dirty[fp] : _getValue(section, key);
}
// ── Render ──────────────────────────────────────────────────────────────────
function _el(tag, attrs, ...children) {
const el = document.createElement(tag);
Object.entries(attrs || {}).forEach(([k, v]) => {
if (k === 'class') el.className = v;
else if (k.startsWith('on')) el.addEventListener(k.slice(2), v);
else el.setAttribute(k, v);
});
children.flat().forEach(c => {
if (c == null) return;
el.appendChild(typeof c === 'string' ? document.createTextNode(c) : c);
});
return el;
}
function renderInput(field, section, value) {
const fp = _fullPath(section, field.key);
const onChange = (v) => {
const wasDirty = fp in _dirty;
const orig = _getValue(section, field.key);
const same = String(orig) === String(v) || orig === v;
if (same) delete _dirty[fp]; else _dirty[fp] = v;
const isDirty = fp in _dirty;
if (wasDirty !== isDirty) _updateDirtyCount(fp, isDirty ? 1 : -1);
_refreshRow(section, field.key);
_refreshDirtyState({ changedPaths: [fp] });
};
if (field.type === 'bool') {
const chk = document.createElement('input');
chk.type = 'checkbox';
chk.checked = Boolean(value);
chk.id = `field-${section}-${field.key}`;
chk.addEventListener('change', () => onChange(chk.checked));
const track = _el('span', { class: 'toggle-track' });
const label = _el('label', { class: 'toggle', for: chk.id }, chk, track);
return label;
}
if (field.type === 'select') {
const sel = _el('select', { class: 'cfg-select', id: `field-${section}-${field.key}` });
const deps = new Set();
(field.options || []).forEach(opt => {
const o = document.createElement('option');
o.value = (typeof opt === 'object') ? opt.value : opt;
o.textContent = (typeof opt === 'object') ? opt.label : opt;
if (o.value === value) o.selected = true;
if (typeof opt === 'object' && opt.disabledWhen) {
o.dataset.disabledWhen = opt.disabledWhen;
if (opt.disabledTip) o.dataset.disabledTip = opt.disabledTip;
const isDisabled = _evalDisabledWhen(opt.disabledWhen);
o.disabled = isDisabled;
if (isDisabled && opt.disabledTip) o.title = opt.disabledTip;
_disabledWhenPaths(opt.disabledWhen).forEach((path) => deps.add(path));
}
sel.appendChild(o);
});
if (deps.size) {
_selectRefs.push(sel);
deps.forEach((path) => _addDependency(_disabledSelectDeps, path, sel));
}
sel.addEventListener('change', () => onChange(sel.value));
return sel;
}
if (field.type === 'textarea') {
const ta = _el('textarea', { class: 'cfg-textarea', id: `field-${section}-${field.key}`,
rows: '3', placeholder: '' });
ta.value = value ?? '';
ta.addEventListener('input', () => onChange(ta.value));
return ta;
}
if (field.type === 'number') {
const inp = _el('input', { class: 'cfg-number', type: 'number',
id: `field-${section}-${field.key}`, value: value ?? '' });
inp.addEventListener('input', () => {
const n = inp.value === '' ? '' : Number(inp.value);
onChange(n);
});
return inp;
}
// text / password
const inp = _el('input', {
class: `cfg-text${field.wide ? ' wide' : ''}`,
type: field.type === 'password' ? 'password' : 'text',
id: `field-${section}-${field.key}`,
value: value ?? '',
autocomplete: 'off',
});
inp.addEventListener('input', () => onChange(inp.value));
if (field.rand) {
const btn = _el('button', { class: 'cfg-rand-btn', type: 'button', title: tr('config.randomize', null, '随机生成'), onclick: () => {
const uuid = crypto.randomUUID().replace(/-/g, '').slice(0, 24);
inp.value = uuid;
inp.type = 'text';
onChange(uuid);
}});
btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="20" height="20" rx="3"/><circle cx="8" cy="8" r="1.5" fill="currentColor" stroke="none"/><circle cx="16" cy="8" r="1.5" fill="currentColor" stroke="none"/><circle cx="8" cy="16" r="1.5" fill="currentColor" stroke="none"/><circle cx="16" cy="16" r="1.5" fill="currentColor" stroke="none"/><circle cx="12" cy="12" r="1.5" fill="currentColor" stroke="none"/></svg>';
const wrap = _el('div', { style: 'display:flex;align-items:center;gap:6px;flex:1;min-width:0' }, inp, btn);
return wrap;
}
return inp;
}
function renderRow(field, section, tabId) {
const fp = _fullPath(section, field.key);
const value = _getValue(section, field.key);
const isDirty = fp in _dirty;
const dot = _el('span', { class: 'cfg-modified-dot' });
const input = renderInput(field, section, isDirty ? _dirty[fp] : value);
const labelChildren = [field.label];
if (section === 'app' && field.key === 'webui_enabled') {
const btn = _el('button', {
class: 'cfg-inline-action',
type: 'button',
title: '打开 WebUI',
'aria-label': '打开 WebUI',
'data-webui-link': 'true',
onclick: () => window.open('/webui/login', '_blank', 'noopener,noreferrer'),
});
btn.innerHTML = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 5h5v5"/><path d="M10 14 19 5"/><path d="M19 14v5h-14v-14h5"/></svg>';
btn.disabled = !Boolean(_getCurrentValue(section, field.key));
labelChildren.push(btn);
}
labelChildren.push(dot);
const labelCol = _el('div', { class: 'cfg-label-col' },
_el('div', { class: 'cfg-label' }, labelChildren),
field.desc ? _el('div', { class: 'cfg-desc' }, field.desc) : null,
);
const inputCol = _el('div', { class: `cfg-input-col${field.type === 'bool' ? ' is-bool' : ''}` }, input);
const row = _el('div', {
class: `cfg-row${isDirty ? ' modified' : ''}`,
'data-section': section,
'data-key': field.key,
}, labelCol, inputCol);
_rowRefs.set(fp, row);
_tabFieldIndex.set(fp, tabId);
if (isDirty) _tabDirtyCounts.set(tabId, (_tabDirtyCounts.get(tabId) || 0) + 1);
// Conditional visibility
if (field.showIf) {
row._showIfSpec = field.showIf;
row.style.display = _evalShowIf(field.showIf) ? '' : 'none';
_conditionalRows.push(row);
_showIfPaths(field.showIf).forEach((path) => _addDependency(_showIfDeps, path, row));
}
return row;
}
function renderGroup(group, tabId) {
const section = group.section;
const rows = group.fields.map(f => renderRow(f, f.section || section, tabId));
const titleEl = _el('div', { class: 'cfg-group-title' }, group.title || '');
const wrap = _el('div', { class: 'cfg-group' }, titleEl, ...rows);
return wrap;
}
function renderPanel(tab) {
const panel = _el('div', { class: `cfg-panel${tab.id === _activeTab ? ' active' : ''}`,
id: `panel-${tab.id}` });
tab.groups.forEach(g => panel.appendChild(renderGroup(g, tab.id)));
return panel;
}
function renderAll() {
const nav = document.getElementById('cfg-nav');
const panels = document.getElementById('cfg-panels');
_resetRenderCaches();
nav.innerHTML = ''; panels.innerHTML = '';
SCHEMA.forEach(tab => {
// Tab button
const btn = _el('button', {
class: `cfg-tab${tab.id === _activeTab ? ' active' : ''}`,
onclick: () => switchTab(tab.id),
'data-tab': tab.id,
}, tab.label, _el('span', { class: 'dot' }));
_tabButtons.set(tab.id, btn);
nav.appendChild(btn);
// Panel
panels.appendChild(renderPanel(tab));
});
_tabButtons.forEach((_, tabId) => _syncTabDirtyState(tabId));
}
function switchTab(id) {
_activeTab = id;
document.querySelectorAll('.cfg-tab').forEach(b =>
b.classList.toggle('active', b.dataset.tab === id));
document.querySelectorAll('.cfg-panel').forEach(p =>
p.classList.toggle('active', p.id === `panel-${id}`));
}
// ── Dirty state helpers ────────────────────────────────────────────────────
function _refreshRow(section, key) {
const row = _rowRefs.get(_fullPath(section, key));
if (row) row.classList.toggle('modified', _fullPath(section, key) in _dirty);
}
function _refreshConditionalRows(changedPaths = null) {
const rows = changedPaths ? _collectDependentTargets(changedPaths, _showIfDeps) : _conditionalRows;
rows.forEach((row) => {
row.style.display = _evalShowIf(row._showIfSpec) ? '' : 'none';
});
}
function _refreshSelectStates(changedPaths = null, { autoNormalizeSelects = true } = {}) {
const selects = changedPaths ? _collectDependentTargets(changedPaths, _disabledSelectDeps) : _selectRefs;
selects.forEach((sel) => {
let anyChanged = false;
[...sel.options].forEach(o => {
if (!o.dataset.disabledWhen) return;
const isDisabled = _evalDisabledWhen(o.dataset.disabledWhen);
o.disabled = isDisabled;
o.title = isDisabled ? (o.dataset.disabledTip || '') : '';
if (autoNormalizeSelects && isDisabled && o.selected) anyChanged = true;
});
if (anyChanged) {
const firstEnabled = [...sel.options].find(o => !o.disabled);
if (firstEnabled) {
firstEnabled.selected = true;
sel.dispatchEvent(new Event('change'));
}
}
});
}
function _refreshDirtyState({ autoNormalizeSelects = true, changedPaths = null } = {}) {
const n = Object.keys(_dirty).length;
document.getElementById('btn-save').disabled = n === 0;
document.getElementById('btn-reset').disabled = n === 0;
const bar = document.getElementById('save-bar');
bar.classList.toggle('visible', n > 0);
document.getElementById('save-bar-msg').textContent =
n === 0
? tr('config.unsavedDefault', null, '存在未保存的更改')
: n === 1
? tr('config.unsavedSingle', { n }, '存在 1 项未保存的更改')
: tr('config.unsavedMultiple', { n }, `存在 ${n} 项未保存的更改`);
const webuiLinkBtn = document.querySelector('[data-webui-link="true"]');
if (webuiLinkBtn) {
const enabled = Boolean(_getCurrentValue('app', 'webui_enabled'));
webuiLinkBtn.disabled = !enabled;
webuiLinkBtn.title = enabled ? '打开 WebUI' : '启用 WebUI 后可打开';
webuiLinkBtn.setAttribute('aria-label', webuiLinkBtn.title);
}
_refreshConditionalRows(changedPaths);
_refreshSelectStates(changedPaths, { autoNormalizeSelects });
if (!changedPaths) _tabButtons.forEach((_, tabId) => _syncTabDirtyState(tabId));
}
// ── Load config ────────────────────────────────────────────────────────────
async function load() {
try {
_cfg = await _api('GET', '/config');
_dirty = {};
_configLoaded = true;
if (!SCHEMA.length) SCHEMA = buildSchema();
renderAll();
_refreshDirtyState({ autoNormalizeSelects: false });
} catch (e) {
showToast(tr('config.loadFailed', { message: e.message }, `配置加载失败: ${e.message}`), 'error');
}
}
// ── Save ──────────────────────────────────────────────────────────────────
async function doSave() {
if (!Object.keys(_dirty).length) return;
// Build a properly nested patch from full dotted paths.
// "proxy.egress.mode" → {proxy:{egress:{mode:v}}}
const patch = {};
Object.entries(_dirty).forEach(([fp, v]) => _setByPath(patch, fp, v));
try {
showToast(tr('config.saving', null, '正在保存更改…'), 'info');
await _api('POST', '/config', patch);
// Merge into local _cfg so re-render shows correct values.
Object.entries(_dirty).forEach(([fp, v]) => _setByPath(_cfg, fp, v));
_dirty = {};
// Re-render to clear modified state
renderAll();
_refreshDirtyState({ autoNormalizeSelects: false });
showToast(tr('config.saveSuccess', null, '更改已保存'), 'success');
} catch (e) {
showToast(tr('config.saveFailed', { message: e.message }, `保存更改失败: ${e.message}`), 'error');
}
}
// ── Reset ─────────────────────────────────────────────────────────────────
function doReset() {
if (!Object.keys(_dirty).length) return;
_dirty = {};
renderAll();
_refreshDirtyState({ autoNormalizeSelects: false });
showToast(tr('config.resetSuccess', null, '未保存的更改已撤销'), 'info');
}
// ── Boot ──────────────────────────────────────────────────────────────────
(async () => {
try {
SCHEMA = buildSchema();
waitI18n().then(() => {
applyConfigI18n();
}).catch((e) => {
console.error('i18n init failed', e);
});
await renderAdminHeader?.();
await renderSiteFooter?.();
const key = await adminKey.get();
if (!key || !await verifyKey(ADMIN_API + '/verify', key).catch(() => false))
return location.href = '/admin/login';
await load();
} catch (e) {
console.error('config page boot failed', e);
showToast(tr('config.loadFailed', { message: e.message }, `配置页初始化失败: ${e.message}`), 'error');
}
})();
</script>
</body>
</html>