-
+
@@ -1300,6 +1377,10 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
Chart.defaults.font.size = 13;
Chart.defaults.plugins.tooltip.usePointStyle = true;
Chart.defaults.devicePixelRatio = window.devicePixelRatio || 1;
+ // 系统开启「减少动态效果」时关掉画布动画(页面下方的 CSS 规则管不到 canvas)
+ if (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
+ Chart.defaults.animation = false;
+ }
}
const COMMON_SCALE_X = { grid: { display: false }, ticks: { maxTicksLimit: 10, font: { size: 12 } } };
@@ -1533,10 +1614,25 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
ctx.canvas.style.display = 'none';
const note = document.createElement('div');
note.className = 'empty';
- note.innerHTML = '
📭
暂无数据';
+ note.textContent = '暂无数据';
ctx.canvas.parentElement.appendChild(note);
}
+// ── 图表的读屏摘要 ────────────────────────────────────────
+// canvas 里的图形与 Chart.js 自绘的图例读屏都读不到:建图时给 canvas 一句文字摘要,作为 role=img 的可访问名称
+function setChartSummary(canvas, text) {
+ canvas.setAttribute('role', 'img');
+ canvas.setAttribute('aria-label', text);
+}
+
+// 堆叠趋势图的摘要:区间、合计、单日最高
+function trendSummary(name, fmt, unit, dates, datasets) {
+ const dayTotals = dates.map((_, i) => datasets.reduce((sum, ds) => sum + (Number(ds.data[i]) || 0), 0));
+ const peak = dayTotals.indexOf(Math.max(...dayTotals));
+ return name + ',' + rangeLabel(overviewDays) + ':合计 ' + fmt(dayTotals.reduce((s, v) => s + v, 0)) + unit
+ + ',单日最高 ' + fmt(dayTotals[peak]) + unit + '(' + dates[peak] + ')';
+}
+
// ── 数据拉取 ──────────────────────────────────────────────
async function fetchJSON(url) {
const r = await fetch(url);
@@ -1545,47 +1641,68 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
}
// ── KPI 更新 ──────────────────────────────────────────────
-function updateKPI(summary) {
+// 费用串形如「¥298.96 + $412.37」:按「 + 」拆段,每段是一个整体(放不下时在段之间换行)
+function costParts(cost) {
+ const parts = String(cost || '–').split(' + ');
+ return parts.map((part, i) => (i ? '+\u00a0' : '') + part);
+}
+
+// days:这批 summary 实际取数的天数,区间标签由它生成
+function updateKPI(summary, days) {
const t = summary.today, r = summary.range;
- const lbl = currentRangeLabel;
+ const lbl = rangeLabel(days);
+ // 副行 = 区间标签 + 若干数值段,用 DOM API 写入(文案来自接口)
+ const sub = (id, label, ...values) => {
+ const node = document.getElementById(id);
+ if (!node) return;
+ node.replaceChildren();
+ const tag = document.createElement('span');
+ tag.className = 'kpi-sub-label';
+ tag.textContent = label;
+ node.appendChild(tag);
+ values.forEach((value) => {
+ const val = document.createElement('span');
+ val.className = 'kpi-sub-val';
+ val.textContent = value;
+ node.appendChild(val);
+ });
+ };
+ const text = (id, value) => {
+ const node = document.getElementById(id);
+ if (node) node.textContent = value;
+ };
+ const parts = (id, values) => {
+ const node = document.getElementById(id);
+ if (!node) return;
+ node.replaceChildren();
+ values.forEach((value) => {
+ const val = document.createElement('span');
+ val.textContent = value;
+ node.appendChild(val);
+ });
+ };
- document.getElementById('kpi-req-today').textContent = fmtNum(t.requests);
- document.getElementById('kpi-req-week').textContent = lbl + ' ' + fmtNum(r.requests);
+ text('kpi-req-today', fmtNum(t.requests));
+ sub('kpi-req-week', lbl, fmtNum(r.requests));
const tokT = t.tokens, tokR = r.tokens;
const totalT = tokT.input + tokT.output + tokT.cache_creation + tokT.cache_read;
const totalR = tokR.input + tokR.output + tokR.cache_creation + tokR.cache_read;
- document.getElementById('kpi-tok-today').textContent = fmtTokens(totalT);
- document.getElementById('kpi-tok-week').textContent = lbl + ' ' + fmtTokens(totalR);
-
- document.getElementById('kpi-out-today').textContent = fmtTokens(tokT.output);
- document.getElementById('kpi-out-week').textContent = lbl + ' ' + fmtTokens(tokR.output);
-
- document.getElementById('kpi-cost-today').textContent = t.cost || '–';
- document.getElementById('kpi-cost-week').textContent = lbl + ' ' + (r.cost || '–');
+ text('kpi-tok-today', fmtTokens(totalT));
+ sub('kpi-tok-week', lbl, fmtTokens(totalR));
+ text('kpi-out-today', fmtTokens(tokT.output));
+ sub('kpi-out-week', lbl, fmtTokens(tokR.output));
- document.getElementById('kpi-fo-today').textContent = fmtNum(t.failovers);
- document.getElementById('kpi-fo-week').textContent = lbl + ' ' + fmtNum(r.failovers);
+ parts('kpi-cost-today', costParts(t.cost));
+ sub('kpi-cost-week', lbl, ...costParts(r.cost));
- document.getElementById('kpi-lat-today').textContent = t.avg_duration_ms ? t.avg_duration_ms + 'ms' : '–';
- document.getElementById('kpi-lat-week').textContent = lbl + ' ' + (r.avg_duration_ms ? r.avg_duration_ms + 'ms' : '–');
+ text('kpi-fo-today', fmtNum(t.failovers));
+ sub('kpi-fo-week', lbl, fmtNum(r.failovers));
+ text('kpi-lat-today', t.avg_duration_ms ? t.avg_duration_ms + 'ms' : '–');
+ sub('kpi-lat-week', lbl, r.avg_duration_ms ? r.avg_duration_ms + 'ms' : '–');
}
-// ── 订阅状态:路由区(熔断 / 配额守卫 / 限速)────────────────
-function cbStateClass(state) {
- if (!state) return 'sb-ok';
- const s = state.toUpperCase();
- if (s === 'OPEN') return 'sb-err';
- if (s === 'HALF_OPEN') return 'sb-warn';
- return 'sb-ok';
-}
-function cbStateLabel(state) {
- if (!state) return 'CLOSED';
- const s = state.toUpperCase();
- if (s === 'OPEN') return '熔断';
- if (s === 'HALF_OPEN') return '半开';
- return '正常';
-}
+// ── 订阅状态:用量格(订阅窗口共用)─────────────────────────
// 用量格严重度(同时决定格底色与进度条填充色):≥ 90% 红 / ≥ 70% 黄 / 其余绿
function quotaClass(pct) {
if (pct >= 90) return 'q-err';
@@ -1609,12 +1726,6 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
(reset ? `
${RESET_ICON}${escapeHtml(reset)}` : '') +
``;
}
-function renderQuotaBar(qg) {
- if (!qg || qg.usage_percent == null) return '';
- const pct = Math.round(qg.usage_percent);
- const label = quotaWindowLabel(qg.window_hours);
- return renderQuotaCell(label, pct, '', '本代理 ' + label + ' 滑动窗口配额守卫:已用 ' + pct + '%');
-}
// 供应商行头像首字母(撞字母时取前两个字母,见 SUB_INITIALS)
function _tierInitial(name) {
@@ -1622,16 +1733,47 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
return SUB_INITIALS.has(text.charAt(0).toUpperCase()) ? text.charAt(0).toUpperCase() + text.charAt(1) : text.charAt(0).toUpperCase();
}
-// 路由区:[状态徽章] [配额守卫用量格](本 proxy 的滑动窗口用量,与订阅区上游额度不同源)
-function _tierZoneHTML(tier) {
+// 路由区的可用状态:该 tier 现在能不能正常接请求。条件按熔断器、限速、配额守卫排列,多个并存时全部列出
+// (各自是独立的不可用原因);没有异常返回 null,由调用方渲染成「圆点 + 正常」
+function tierAvailability(tier) {
const cb = tier.circuit_breaker || {};
const rlInfo = tier.rate_limit || {};
+ const state = String(cb.state || '').toUpperCase();
// 失败次数来自载荷:转成数字再拼,非数字一律当作 0
const failures = Number(cb.failure_count) || 0;
- return `
${cbStateLabel(cb.state)}${failures ? ' ×' + failures : ''}` +
- (rlInfo.is_rate_limited ? `
限速中` : '') +
- (tier.quota_guard ? renderQuotaBar(tier.quota_guard) : '') +
- (tier.weekly_quota_guard ? renderQuotaBar(tier.weekly_quota_guard) : '');
+ const exceeded = (g) => String((g && g.state) || '').toUpperCase() === 'QUOTA_EXCEEDED';
+ const out = [];
+ if (state === 'OPEN') out.push({ cls: 'sb-err', text: failures ? '熔断 ×' + failures : '熔断' });
+ if (state === 'HALF_OPEN') out.push({ cls: 'sb-warn', text: '半开' });
+ if (rlInfo.is_rate_limited) out.push({ cls: 'sb-warn', text: '限速中' });
+ if (exceeded(tier.quota_guard) || exceeded(tier.weekly_quota_guard)) out.push({ cls: 'sb-err', text: '配额超限' });
+ return out.length ? out : null;
+}
+
+// 悬停详情:不再常驻的 tier 名、熔断失败次数、限速剩余时间与配额守卫用量
+// (配额守卫是本 proxy 的滑动窗口预算,与订阅区上游额度不同源)
+function tierAvailabilityTitle(tier) {
+ const cb = tier.circuit_breaker || {};
+ const rlInfo = tier.rate_limit || {};
+ const state = String(cb.state || '').toUpperCase();
+ const failures = Number(cb.failure_count) || 0;
+ const parts = [String(tier.name || '') + ' 的路由状态'];
+ parts.push('熔断器 ' + ({ OPEN: '熔断', HALF_OPEN: '半开' }[state] || '正常') + (failures ? '(失败 ' + failures + ' 次)' : ''));
+ if (rlInfo.is_rate_limited) parts.push('限速中,剩余 ' + Math.ceil(Number(rlInfo.remaining_seconds) || 0) + ' 秒');
+ [tier.quota_guard, tier.weekly_quota_guard].forEach((g) => {
+ if (!g || g.usage_percent == null) return;
+ parts.push('配额守卫 ' + quotaWindowLabel(g.window_hours) + ' 窗口已用 ' + Math.round(g.usage_percent) + '%(阈值 ' + Math.round(Number(g.threshold_percent) || 0) + '%)');
+ });
+ return parts.join(';');
+}
+
+// 路由区只留可用状态:无异常是「圆点 + 正常」,异常才是彩色胶囊,整列里异常一眼可见
+function _tierZoneHTML(tier) {
+ const states = tierAvailability(tier);
+ const inner = states
+ ? states.map((s) => `
${s.text}`).join('')
+ : '
正常';
+ return `
${inner}`;
}
let _tierStatus = { tiers: [] }; // 最近一次 /api/status 载荷
@@ -1777,7 +1919,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
const handle = reorderable ? `
` : '';
const routeHTML = _tierZoneHTML(tier);
if (!meta) {
- // 无订阅对应的 tier 行:路由区加「供应商状态」标注,避免在订阅卡片里被读成订阅行
+ // 无订阅对应的 tier 行:只有路由区(可用状态),不出订阅区
const initial = escapeHtml(_tierInitial(tier.name));
return `
@@ -1786,16 +1928,13 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
${safeName}
- 供应商状态
${routeHTML}
`;
}
- // 同一实体合并为一行:[标识] [订阅区] │ [路由区];显示名取订阅名,订阅数据缺失时也不跳变
+ // 同一实体合并为一行:[标识] [订阅区] [路由区];显示名取订阅名,订阅数据缺失时也不跳变
const v = subByTier[tier.name];
const subHTML = v ? _subZoneHTML(v) : '';
- // 订阅显示名与 tier 名仅大小写不同时不重复标注
- const tag = meta.label.toLowerCase() === tier.name ? '' : `
${safeName}`;
return `
${handle}
@@ -1803,7 +1942,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
${escapeHtml(meta.label)}
${subHTML ? `
${subHTML}
` : ''}
-
${tag}${routeHTML}
+
${routeHTML}
`;
}).join('');
tierList.innerHTML = (tiers.length ? '' : '
') + tierRows;
@@ -1869,6 +2008,29 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
if (handle) handle.focus({ preventScroll: true });
}
+// ── 订阅区放不下的提示:右缘渐隐 ──────────────────────────
+// 行重绘由多处触发(刷新、拖拽、复位),用 MutationObserver 统一收口,不去改渲染函数
+function syncZoneCues() {
+ document.querySelectorAll('#subscription-card .vendor-badges').forEach(function (zone) {
+ zone.classList.toggle('has-more', zone.scrollWidth - zone.clientWidth - zone.scrollLeft > 1);
+ });
+}
+(function initZoneCues() {
+ const card = document.getElementById('subscription-card');
+ if (!card) return;
+ if (window.MutationObserver) {
+ const observer = new MutationObserver(syncZoneCues);
+ ['vendor-list', 'subscription-list'].forEach(function (id) {
+ const list = document.getElementById(id);
+ if (list) observer.observe(list, { childList: true, subtree: true });
+ });
+ }
+ card.addEventListener('scroll', function (e) {
+ if (e.target.closest && e.target.closest('.vendor-badges')) syncZoneCues();
+ }, true);
+ window.addEventListener('resize', syncZoneCues);
+})();
+
// ── 订阅状态:拖拽调整优先级(Pointer Events 重排,运行时生效,不重置配额) ────
// 采用 Pointer Events 而非原生 HTML5 DnD:后者触屏不支持、跨浏览器易「拿不起来」,
// 是业界公认脆弱的重排序方案(故 SortableJS / dnd-kit 等均改用指针事件)。
@@ -2101,74 +2263,136 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
});
}
-// ── Model Calling 实时状态 ────────────────────────────────
+// ── Model Calling 实时状态:对齐成列的 meter list ──────────
+// 行节点按 vendor/model 键复用,只改文字与条宽,不整体重建 DOM:轮询不闪,编辑并行度时也不打断输入
+const _mcRows = new Map(); // key → 行节点引用
+var _mcEditing = false; // 正在编辑并行度
+var _mcPendingEdit = null; // 编辑期间点了另一行的上限:当前编辑结束后接着打开那一行
+
+function _mcRowKey(vendor, model) { return vendor + '/' + model; }
+
+function _mcEl(tag, cls, text) {
+ const node = document.createElement(tag);
+ if (cls) node.className = cls;
+ if (text != null) node.textContent = text;
+ return node;
+}
+
+function _mcBuildRow(m) {
+ const row = _mcEl('div', 'mc-row');
+ row.setAttribute('role', 'listitem');
+ row.dataset.key = _mcRowKey(m.vendor, m.model);
+ const vendor = _mcEl('span', 'mc-vendor', m.vendor);
+ vendor.title = m.vendor;
+ const model = _mcEl('span', 'mc-model-name', m.model);
+ model.title = _mcRowKey(m.vendor, m.model);
+ const meter = _mcEl('div', 'mc-meter');
+ meter.setAttribute('aria-hidden', 'true');
+ const fill = _mcEl('i', 'mc-fill');
+ fill.style.width = '0%';
+ meter.appendChild(fill);
+ const meterNote = _mcEl('span', 'mc-meter-note');
+ meterNote.appendChild(_mcEl('span', 'mc-note-wide', '仅监控 · 不限并行度'));
+ meterNote.appendChild(_mcEl('span', 'mc-note-narrow', '仅监控'));
+ // 上限是一个真按钮:键盘可达(Tab 聚焦、Enter / 空格触发),点击后原地变成数字输入
+ const limit = _mcEl('button', 'mc-limit-editable');
+ limit.type = 'button';
+ limit.title = '点击修改并行度';
+ limit.appendChild(_mcEl('span', 'mc-limit-val'));
+ limit.insertAdjacentHTML('beforeend', '
');
+ const use = _mcEl('span', 'mc-use');
+ const inUse = _mcEl('b', 'mc-in', '0');
+ const sep = _mcEl('span', 'mc-sep', '/');
+ const unit = _mcEl('span', 'mc-use-unit', '进行中');
+ use.append(inUse, sep, limit, unit);
+ const queue = _mcEl('span', 'mc-queue');
+ row.append(vendor, model, meter, meterNote, use, queue);
+ return { row, vendor, model, meter, fill, meterNote, use, inUse, sep, limit, unit, queue, m: null };
+}
+
+function _mcUpdateRow(r, m) {
+ r.m = m; // 行缓存最近一次载荷:并行度改成功后用它就地重算,不等下一轮轮询
+ const monitor = m.mode === 'monitor';
+ r.row.classList.toggle('mc-monitor', monitor);
+ r.vendor.textContent = m.vendor;
+ r.model.textContent = m.model;
+ r.model.title = _mcRowKey(m.vendor, m.model);
+ if (monitor) {
+ r.inUse.textContent = m.in_use;
+ r.sep.style.display = 'none';
+ r.limit.style.display = 'none';
+ r.unit.style.display = '';
+ } else {
+ const limit = m.limit || 0;
+ const pct = limit > 0 ? Math.round((m.in_use / limit) * 100) : 0;
+ r.fill.style.width = Math.min(pct, 100) + '%';
+ r.fill.className = 'mc-fill ' + (pct <= 50 ? 'mc-low' : (pct <= 80 ? 'mc-mid' : 'mc-high'));
+ r.meter.title = '并行度 ' + m.in_use + ' / ' + limit;
+ r.inUse.textContent = m.in_use;
+ r.sep.style.display = '';
+ r.limit.style.display = '';
+ r.unit.style.display = 'none';
+ r.limit.querySelector('.mc-limit-val').textContent = limit;
+ r.limit.setAttribute('aria-label', m.vendor + '/' + m.model + ' 的并行度上限,当前 ' + limit + ',点击修改');
+ r.limit.setAttribute('data-limit', limit);
+ r.limit.setAttribute('data-tier', m.vendor);
+ r.limit.setAttribute('data-model', m.model);
+ }
+ const peak = m.peak_pending_recent || 0;
+ if (m.pending > 0) r.queue.replaceChildren(_mcEl('span', 'mc-badge mc-badge-pending', '排队 ' + m.pending));
+ else if (peak > 0) r.queue.replaceChildren(_mcEl('span', 'mc-peak', '曾排队 ' + peak));
+ else r.queue.replaceChildren();
+}
+
function updateModelCalling(status) {
- var wrap = document.getElementById('model-calling-wrap');
+ const wrap = document.getElementById('model-calling-wrap');
if (!wrap) return;
- var tiers = status.tiers || [];
-
- // 收集所有带 concurrency 诊断的模型
- var models = [];
- for (var i = 0; i < tiers.length; i++) {
- var tier = tiers[i];
- var diag = tier.diagnostics || {};
- var conc = diag.concurrency;
+ // 正在编辑并行度时不碰 DOM:输入框、焦点与已输入的内容都原样保留,编辑结束后由下一轮轮询同步
+ if (_mcEditing) return;
+ const tiers = status.tiers || [];
+
+ const models = [];
+ for (const tier of tiers) {
+ const conc = (tier.diagnostics || {}).concurrency;
if (!conc) continue;
- var names = Object.keys(conc);
- for (var j = 0; j < names.length; j++) {
- var model = names[j];
- var d = conc[model];
+ for (const model of Object.keys(conc)) {
+ const d = conc[model] || {};
models.push({
- vendor: tier.name,
- model: model,
- mode: d.mode || 'limited',
- limit: d.limit,
- in_use: d.in_use || 0,
- available: d.available,
- pending: d.pending || 0,
+ vendor: tier.name, model, mode: d.mode || 'limited', limit: d.limit,
+ in_use: d.in_use || 0, available: d.available, pending: d.pending || 0,
peak_pending_recent: d.peak_pending_recent || 0,
});
}
}
if (!models.length) {
- wrap.innerHTML = '
无活跃模型调用
';
+ wrap.replaceChildren(_mcEl('div', 'mc-empty', '无活跃模型调用'));
+ _mcRows.clear();
return;
}
-
- var html = '
';
- for (var k = 0; k < models.length; k++) {
- var m = models[k];
-
- if (m.mode === 'monitor') {
- // monitor 模式:纯计数徽章,无 limit/进度条
- html += '
'
- + '
' + escapeHtml(m.vendor + '/' + m.model) + ''
- + '
'
- + '
'
- + '' + m.in_use + ''
- + '
'
- + '
';
- } else {
- // limited 模式:保留现有渲染(进度条 + limit 编辑)
- var limit = m.limit || 0;
- var pct = limit > 0 ? Math.round((m.in_use / limit) * 100) : 0;
- var barClass = pct <= 50 ? 'mc-low' : (pct <= 80 ? 'mc-mid' : 'mc-high');
-
- html += '
'
- + '
' + escapeHtml(m.vendor + '/' + m.model) + ''
- + '
'
- + '
'
- + '' + m.in_use
- + '/' + limit + ''
- + (m.pending > 0 ? '⏳ ' + m.pending + '' : '')
- + (m.pending === 0 && m.peak_pending_recent > 0 ? '🕘 曾排队 ' + m.peak_pending_recent + '' : '')
- + '
'
- + '
';
- }
+ let list = wrap.querySelector('.mc-list');
+ if (!list) {
+ wrap.replaceChildren();
+ list = _mcEl('div', 'mc-list');
+ list.setAttribute('role', 'list');
+ wrap.appendChild(list);
+ }
+ const seen = new Set();
+ models.forEach(function (m, idx) {
+ const key = _mcRowKey(m.vendor, m.model);
+ seen.add(key);
+ let r = _mcRows.get(key);
+ if (!r || !r.row.parentNode) {
+ r = _mcBuildRow(m);
+ _mcRows.set(key, r);
+ }
+ if (list.children[idx] !== r.row) list.insertBefore(r.row, list.children[idx] || null);
+ _mcUpdateRow(r, m);
+ });
+ for (const [key, r] of _mcRows) {
+ if (!seen.has(key)) { r.row.remove(); _mcRows.delete(key); }
}
- html += '
';
- wrap.innerHTML = html;
+ list.classList.toggle('mc-cols-2', models.length >= 3);
}
// Model Calling 独立短间隔轮询
@@ -2188,77 +2412,120 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
}
// ── 并行度运行时编辑 ──────────────────────────────────────
-var _mcEditing = false;
-document.addEventListener('click', function(e) {
- if (_mcEditing) return;
- var el = e.target.closest('.mc-limit-editable');
- if (!el) return;
+// 输入只接受 1 到 20 的整数:7.5、1e2 这类输入按非法处理,不截断后提交
+function limitValue(raw) {
+ const text = String(raw == null ? '' : raw).trim();
+ if (!/^\\d{1,2}$/.test(text)) return NaN;
+ const value = Number(text);
+ return value >= 1 && value <= 20 ? value : NaN;
+}
+
+// 事件委托接管上限按钮的点击。编辑期间(含提交在途)_mcEditing 为真、轮询不重绘:这时点了另一行的上限,
+// 先记入 _mcPendingEdit,由当前编辑的 restore 接着打开,这次点击不被吞掉。
+// 提交带在途守卫与 8 秒超时,请求悬住时也能解除编辑态;结束编辑后焦点回到按钮;
+// 结果用静态色标并写进 role=status 节点供读屏播报
+document.addEventListener('click', function (e) {
+ const btn = e.target.closest('.mc-limit-editable');
+ if (!btn) return;
+ if (_mcEditing) { _mcPendingEdit = btn; return; }
e.preventDefault();
+ startLimitEdit(btn);
+});
+
+// 播报节点 #mc-live 写在模板里:动态插入的 live region,首条内容可能被读屏漏掉
+function _mcAnnounce(text) {
+ const live = document.getElementById('mc-live');
+ if (!live) return;
+ live.textContent = '';
+ setTimeout(function () { live.textContent = text; }, 30);
+}
+
+function startLimitEdit(btn) {
_mcEditing = true;
- var oldVal = el.getAttribute('data-limit');
- var tier = el.getAttribute('data-tier');
- var model = el.getAttribute('data-model');
- var input = document.createElement('input');
- input.type = 'number';
+ const oldVal = btn.getAttribute('data-limit');
+ const tier = btn.getAttribute('data-tier');
+ const model = btn.getAttribute('data-model');
+ const input = document.createElement('input');
+ input.type = 'text';
+ input.inputMode = 'numeric';
input.className = 'mc-limit-input';
- input.min = '1';
- input.max = '20';
+ input.setAttribute('aria-label', tier + '/' + model + ' 的并行度上限(1 到 20 的整数)');
input.value = oldVal;
- el.style.display = 'none';
- el.parentNode.insertBefore(input, el.nextSibling);
+ btn.style.display = 'none';
+ btn.parentNode.insertBefore(input, btn.nextSibling);
input.focus();
input.select();
- var _cancelled = false;
-
- function restore() {
+ let done = false;
+ let inFlight = false; // PUT 未决期间不再接受第二次提交
+ const restore = function () {
+ if (done) return;
+ const hadFocus = document.activeElement === input;
+ done = true; // 先落标记再移除输入框:移除引发的 blur 不会再提交
_mcEditing = false;
- if (input.parentNode) input.parentNode.removeChild(input);
- el.style.display = '';
- }
-
- function flash(cls) {
- el.classList.add(cls);
- setTimeout(function() { el.classList.remove(cls); }, 600);
- }
-
- input.addEventListener('keydown', function(ev) {
- if (ev.key === 'Escape') { _cancelled = true; restore(); return; }
+ input.remove();
+ btn.style.display = '';
+ // 编辑期间点了另一行的上限:接着编辑那一行。期间焦点已被用户移到别处就作罢,不抢焦点
+ const next = _mcPendingEdit;
+ _mcPendingEdit = null;
+ const idle = document.activeElement === next || document.activeElement === document.body;
+ if (next && next.isConnected && idle) { startLimitEdit(next); return; }
+ if (hadFocus) btn.focus(); // 回车 / Esc 结束后焦点回到上限按钮,键盘用户不用从头 Tab
+ };
+ let markTimer = null;
+ const mark = function (cls) {
+ btn.classList.remove('mc-limit-ok', 'mc-limit-err');
+ clearTimeout(markTimer);
+ btn.classList.add(cls);
+ markTimer = setTimeout(function () { btn.classList.remove(cls); }, 1500);
+ };
+ const submit = function () {
+ if (done || inFlight) return;
+ const value = limitValue(input.value);
+ if (isNaN(value)) { restore(); mark('mc-limit-err'); _mcAnnounce('并行度须是 1 到 20 的整数'); return; }
+ if (String(value) === oldVal) { restore(); return; }
+ inFlight = true;
+ // 8 秒兜底:请求悬住(网络挂起、fetch 不响应 abort)时也解除编辑态,不让整张表停在「编辑中」
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
+ let timeoutId = null;
+ const timeout = new Promise(function (_, reject) {
+ timeoutId = setTimeout(function () { reject(new Error('timeout')); if (controller) controller.abort(); }, 8000);
+ });
+ const request = fetch('/api/concurrency', {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ tier: tier, model: model, limit: value }),
+ signal: controller ? controller.signal : undefined,
+ });
+ Promise.race([request, timeout]).then(function (res) {
+ if (!res.ok) throw new Error(String(res.status));
+ btn.querySelector('.mc-limit-val').textContent = value;
+ btn.setAttribute('data-limit', value);
+ // 就地重算这一行(条形、可访问名称立刻自洽),再拉一次状态对齐服务端
+ const row = _mcRows.get(_mcRowKey(tier, model));
+ if (row && row.m && row.m.mode !== 'monitor') { row.m.limit = value; _mcUpdateRow(row, row.m); }
+ mark('mc-limit-ok');
+ _mcAnnounce(tier + '/' + model + ' 的并行度已更新为 ' + value);
+ fetchJSON('/api/status').then(function (status) { updateModelCalling(status); }).catch(function () {});
+ }).catch(function () {
+ mark('mc-limit-err');
+ _mcAnnounce(tier + '/' + model + ' 的并行度更新失败');
+ }).finally(function () {
+ clearTimeout(timeoutId);
+ inFlight = false;
+ restore();
+ });
+ };
+ input.addEventListener('keydown', function (ev) {
+ if (ev.key === 'Escape') { restore(); return; }
if (ev.key !== 'Enter') return;
ev.preventDefault();
submit();
});
-
- input.addEventListener('blur', function() {
- setTimeout(function() { if (!_cancelled) submit(); }, 50);
+ input.addEventListener('blur', function () {
+ setTimeout(function () { if (!done) submit(); }, 50);
});
-
- function submit() {
- if (_cancelled) return;
- var v = parseInt(input.value, 10);
- if (isNaN(v) || v < 1 || v > 20) { restore(); flash('mc-limit-flash-err'); return; }
- if (String(v) === oldVal) { restore(); return; }
- fetch('/api/concurrency', {
- method: 'PUT',
- headers: {'Content-Type': 'application/json'},
- body: JSON.stringify({tier: tier, model: model, limit: v})
- }).then(function(res) {
- if (res.ok) {
- return res.json().then(function() {
- el.textContent = v;
- el.setAttribute('data-limit', v);
- flash('mc-limit-flash-ok');
- });
- } else {
- flash('mc-limit-flash-err');
- }
- }).catch(function() {
- flash('mc-limit-flash-err');
- }).finally(function() {
- restore();
- });
- }
-});
+}
// ── 按 tiers 顺序排序 vendor 列表 ─────────────────────────
function sortByTierOrder(vendors, tierOrder) {
@@ -2287,8 +2554,12 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
const dates = [...allDates].sort();
const vendors = sortByTierOrder(Object.keys(vendorDateMap), tierOrder);
- if (chartTimeline) chartTimeline.destroy();
- const ctx = document.getElementById('chart-timeline').getContext('2d');
+ if (chartTimeline) { chartTimeline.destroy(); chartTimeline = null; }
+ const ctx = chartContext('chart-timeline');
+ if (!dates.length) {
+ chartEmpty(ctx);
+ return;
+ }
const datasets = vendors.map((v, i) => {
const color = VENDOR_COLORS[i % VENDOR_COLORS.length];
return {
@@ -2297,9 +2568,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
data: dates.map(d => vendorDateMap[v][d] || 0),
borderColor: color,
backgroundColor: color + '30',
- fill: true,
+ // 真堆叠面积:每条线填充到上一条堆叠线,首条填到底;各自填到底会叠成灰褐色
+ fill: i === 0 ? 'start' : '-1',
};
});
+ setChartSummary(ctx.canvas, trendSummary('请求量趋势', fmtNum, ' 次', dates, datasets));
chartTimeline = new Chart(ctx, {
type: 'line',
@@ -2324,6 +2597,18 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
}
// ── 供应商分布环形图 ──────────────────────────────────────
+// 图例位置:Chart.js 给右侧图例最多一半画布宽,最长的标签(「agy | antigravity」实测约 130px)放不下时会被裁掉。
+// 并排右列在约 1210px 视口以下放不下,这时图例移到下方自动换行。宽度用 Chart.js 自己的字体量出来,不另抄一份
+function distLegendPosition(ctx, labels, canvasWidth) {
+ const opts = COMMON_LEGEND.labels;
+ const font = Chart.helpers.toFont(opts.font);
+ ctx.save();
+ ctx.font = font.string;
+ const widest = labels.reduce((w, text) => Math.max(w, opts.boxWidth + font.size / 2 + ctx.measureText(text).width), 0);
+ ctx.restore();
+ return canvasWidth >= 2 * (opts.padding + widest) ? 'right' : 'bottom';
+}
+
function buildVendorDist(rows, tierOrder) {
const vendorTotals = {};
for (const r of rows) {
@@ -2340,10 +2625,14 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
chartEmpty(ctx);
return;
}
+ const total = data.reduce((s, v) => s + v, 0);
+ const legendLabels = labels.map(formatVendorLabel);
+ setChartSummary(ctx.canvas, '供应商请求分布,' + rangeLabel(overviewDays) + ':共 ' + fmtNum(total) + ' 次请求;'
+ + legendLabels.map((text, i) => text + ' ' + (total ? Math.round((data[i] / total) * 100) : 0) + '%').join(','));
chartVendorDist = new Chart(ctx, {
type: 'doughnut',
data: {
- labels: labels.map(formatVendorLabel),
+ labels: legendLabels,
datasets: [{
data,
backgroundColor: labels.map((_,i) => VENDOR_COLORS[i % VENDOR_COLORS.length]),
@@ -2354,9 +2643,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
options: {
responsive: true, maintainAspectRatio: false,
cutout: '55%',
+ // 建图与每次尺寸变化都会经过这里:跨过并排 / 堆叠断点、右列变宽变窄时图例位置跟着走
+ onResize: function (chart, size) { chart.options.plugins.legend.position = distLegendPosition(chart.ctx, chart.data.labels, size.width); },
plugins: {
legend: {
- position: 'right',
+ position: distLegendPosition(ctx, legendLabels, ctx.canvas.parentElement.clientWidth),
onClick: legendOnClick,
labels: {
...COMMON_LEGEND.labels,
@@ -2404,7 +2695,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
const dates = [...allDates].sort();
const vendors = sortByTierOrder(Object.keys(vendorDateMap), tierOrder);
- if (chartTokenTimeline) chartTokenTimeline.destroy();
+ if (chartTokenTimeline) { chartTokenTimeline.destroy(); chartTokenTimeline = null; }
const ctx = chartContext('chart-token-timeline');
if (!dates.length) {
chartEmpty(ctx);
@@ -2419,9 +2710,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
data: dates.map(d => vendorDateMap[v][d] || 0),
borderColor: color,
backgroundColor: color + '30',
- fill: true,
+ // 真堆叠面积:每条线填充到上一条堆叠线,首条填到底;各自填到底会叠成灰褐色
+ fill: i === 0 ? 'start' : '-1',
};
});
+ setChartSummary(ctx.canvas, trendSummary('Token 量趋势(按供应商)', fmtTokens, ' Token', dates, datasets));
chartTokenTimeline = new Chart(ctx, {
type: 'line',
@@ -2469,7 +2762,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
return sumB - sumA;
});
- if (chartModelTokenTimeline) chartModelTokenTimeline.destroy();
+ if (chartModelTokenTimeline) { chartModelTokenTimeline.destroy(); chartModelTokenTimeline = null; }
const ctx = chartContext('chart-model-token-timeline');
// 清理 HTML Legend 容器
@@ -2494,7 +2787,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
data: dates.map(d => modelDateMap[key][d] || 0),
borderColor: color,
backgroundColor: color + '30',
- fill: true,
+ // 真堆叠面积:每条线填充到上一条堆叠线,首条填到底;各自填到底会叠成灰褐色
+ fill: i === 0 ? 'start' : '-1',
};
});
@@ -2514,6 +2808,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
},
};
+ setChartSummary(ctx.canvas, trendSummary('Token 用量趋势(Vendor / 模型)', fmtTokens, ' Token', dates, datasets));
+
chartModelTokenTimeline = new Chart(ctx, {
type: 'line',
data: { labels: dates, datasets },
@@ -2548,12 +2844,24 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
// ── 时间区间控制 ──────────────────────────────────────────
let currentDays = 7;
-let currentRangeLabel = '本周';
+let overviewDays = 0; // Overview 最近一次成功取数用的天数(0 = 尚未取数)
+// 与服务端 summary / timeline 接口的天数上限一致:接口只收 days,超出部分不取数
+const MAX_RANGE_DAYS = 90;
+
+// 本地日期的 YYYY-MM-DD(toISOString 给的是 UTC 日期:东八区 0 到 8 点会写成昨天)
+function localDateStr(d) {
+ return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
+}
+
+// 区间标签:KPI 副行、趋势页签说明、分布图标题共用同一口径,一律「近 N 天」。入参是这次取数实际用的天数,
+// 不是页面当前选中的区间:刷新途中改了区间,已上屏的数据仍属于旧区间,标签要跟数据走。
+// 自选区间也只折算成天数:接口取的是截至今天的最近 N 天,区间栏里选的起止日期不是取数窗口,写成起止日期会和横轴对不上
+function rangeLabel(days) {
+ return '近 ' + days + ' 天';
+}
function setTimeRange(days, btn) {
currentDays = days;
- if (days === 7) currentRangeLabel = '本周';
- else if (days === 30) currentRangeLabel = '本月';
// 仅限时间区间栏:Config 页的 section pills 复用 .range-btn
document.querySelectorAll('.time-range-bar .range-btn').forEach(b => b.classList.remove('active'));
if (btn) btn.classList.add('active');
@@ -2563,8 +2871,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
const today = new Date();
const weekAgo = new Date(today);
weekAgo.setDate(weekAgo.getDate() - 6);
- document.getElementById('range-end').value = today.toISOString().slice(0, 10);
- document.getElementById('range-start').value = weekAgo.toISOString().slice(0, 10);
+ document.getElementById('range-end').value = localDateStr(today);
+ document.getElementById('range-start').value = localDateStr(weekAgo);
applyCustomRange();
} else {
customEl.classList.remove('visible');
@@ -2579,23 +2887,77 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
const startMs = new Date(s).getTime();
const endMs = new Date(e).getTime();
if (endMs < startMs) return;
- currentDays = Math.ceil((endMs - startMs) / 86400000) + 1;
- currentRangeLabel = s + '—' + e;
+ currentDays = Math.min(MAX_RANGE_DAYS, Math.ceil((endMs - startMs) / 86400000) + 1);
refresh();
}
+// 区间说明同步到分布图标题与趋势页签行(三张趋势图的标题就是页签文案,不带区间)
function updateChartTitles(days) {
- const label = days <= 7 ? '近 7 天' : (days <= 30 ? '近 30 天' : '近 ' + days + ' 天');
- const tl = document.getElementById('title-timeline');
- const tt = document.getElementById('title-token-timeline');
+ const label = rangeLabel(days);
const vd = document.getElementById('title-vendor-dist');
- const mt = document.getElementById('title-model-token-timeline');
- if (tl) tl.textContent = label + ' 请求量趋势';
- if (tt) tt.textContent = label + ' Token 量趋势(按供应商)';
if (vd) vd.textContent = '供应商请求分布(' + label + ')';
- if (mt) mt.textContent = label + ' Token 用量(按 Vendor / 模型)';
+ const range = document.getElementById('trend-range');
+ if (range) range.textContent = label;
+}
+
+// ── 趋势页签:三张图共用一个图位 ──────────────────────────
+// 三张图在刷新时一并重建,非当前页签 hidden;切换只改显示,不做懒建。
+// 类名另起 trend- 前缀:applyTabState / switchTab 按 .tab-btn / .tab-pane 全文档匹配,借用量会被主页签逻辑误伤
+const TREND_CHARTS = {
+ requests: 'chart-timeline',
+ tokens: 'chart-token-timeline',
+ models: 'chart-model-token-timeline',
+};
+
+// 面板由隐藏变可见后让 Chart.js 按容器尺寸重算并直接出终帧:它在 resize 里会先建一段 attach 动画,
+// 只调 update('none') 取消不了在途动画,要先 stop
+function showTrendChart(key) {
+ const instance = window.Chart ? Chart.getChart(TREND_CHARTS[key]) : null;
+ if (instance) { instance.resize(); instance.stop(); instance.update('none'); }
}
+function setTrendTab(key, focus) {
+ document.querySelectorAll('.trend-tab').forEach(function (tab) {
+ const on = tab.dataset.trend === key;
+ tab.setAttribute('aria-selected', on ? 'true' : 'false');
+ tab.tabIndex = on ? 0 : -1;
+ });
+ document.querySelectorAll('.trend-panel').forEach(function (panel) {
+ const on = panel.id === 'trend-panel-' + key;
+ panel.hidden = !on;
+ if (on) showTrendChart(key);
+ });
+ if (focus) {
+ const tab = document.getElementById('trend-tab-' + key);
+ if (tab) tab.focus();
+ }
+}
+
+(function initTrendTabs() {
+ const tablist = document.querySelector('.trend-tabs');
+ if (!tablist) return;
+ tablist.addEventListener('click', function (e) {
+ const tab = e.target.closest('.trend-tab');
+ if (tab) setTrendTab(tab.dataset.trend, false);
+ });
+ // 方向键在页签间循环,Home / End 到首尾;焦点移到哪个页签就选中哪个
+ // (automatic activation:面板内容都已在 DOM 里,切换没有延迟)
+ tablist.addEventListener('keydown', function (e) {
+ const tab = e.target.closest('.trend-tab');
+ if (!tab) return;
+ const keys = Array.from(tablist.querySelectorAll('.trend-tab'), function (t) { return t.dataset.trend; });
+ const i = keys.indexOf(tab.dataset.trend);
+ let next = null;
+ if (e.key === 'ArrowRight') next = keys[(i + 1) % keys.length];
+ else if (e.key === 'ArrowLeft') next = keys[(i - 1 + keys.length) % keys.length];
+ else if (e.key === 'Home') next = keys[0];
+ else if (e.key === 'End') next = keys[keys.length - 1];
+ if (next == null) return;
+ e.preventDefault();
+ setTrendTab(next, true);
+ });
+})();
+
// ── Sessions Panel ──────────────────────────────────────────────
function relativeTime(tsStr) {
if (!tsStr) return '–';
@@ -2854,11 +3216,14 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
fetchJSON('/api/dashboard/subscriptions').catch(function () { return { vendors: [] }; }),
]);
+ // 这批数据实际取数的天数:区间标签与图表摘要读它,不读页面当前选中的区间
+ overviewDays = days;
+
if (summary.version) {
document.getElementById('version-badge').textContent = 'v' + summary.version;
}
- updateKPI(summary);
+ updateKPI(summary, days);
// 行数据与随后的订阅数据到齐后只重绘一次:连续替换行节点会让键盘焦点环闪烁
updateVendorStatus(status, true);
updateModelCalling(status);
@@ -2882,9 +3247,11 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
if (refreshing) return;
refreshing = true;
try {
- // 循环:若 await 期间用户切到了尚未加载的另一页签,补一次刷新,避免 tabLoaded 错位。
+ // 循环:若 await 期间用户切到了尚未加载的另一页签,或改了时间区间,补一次刷新,
+ // 避免 tabLoaded 错位、或新区间的点击被在途标记挡掉后没有下文。
while (true) {
const tab = currentTab;
+ let ok = false;
document.getElementById('refresh-time').textContent = '刷新中…';
try {
if (tab === 'config') {
@@ -2895,6 +3262,7 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
await refreshOverview();
}
tabLoaded[tab] = true;
+ ok = true;
if (tab === currentTab) {
document.getElementById('refresh-time').textContent =
'上次刷新: ' + now() + '(' + TAB_LABELS[tab] + ')';
@@ -2904,6 +3272,8 @@ def file_response(self, *args: Any, **kwargs: Any) -> Response:
document.getElementById('refresh-time').textContent = '刷新失败 ' + now();
}
if (currentTab !== tab && !tabLoaded[currentTab]) continue;
+ // 取数成功但区间已在途中改掉:按新区间再取一次(取数失败不重试,否则接口不可达时会空转)
+ if (ok && tab === 'overview' && overviewDays !== currentDays) continue;
break;
}
} finally {
diff --git a/src/coding/proxy/server/generations.py b/src/coding/proxy/server/generations.py
index ba09409f..447594f3 100644
--- a/src/coding/proxy/server/generations.py
+++ b/src/coding/proxy/server/generations.py
@@ -671,7 +671,7 @@ def _migrate_bindings(
)
catalog = {
str(entry.get("model"))
- for entry in (router.get_bindable_models() if router else [])
+ for entry in (router.get_known_models() if router else [])
}
dropped = 0
model_dropped = 0
diff --git a/src/coding/proxy/server/routes.py b/src/coding/proxy/server/routes.py
index 061256cf..3a219217 100644
--- a/src/coding/proxy/server/routes.py
+++ b/src/coding/proxy/server/routes.py
@@ -477,7 +477,13 @@ async def bind_session_vendor(request: Request) -> Response:
if model is not None:
model = model.strip()
if not any(m.get("model") == model for m in bindable):
- if not bindable:
+ known = {str(m.get("model")) for m in router.get_known_models()}
+ if model in known:
+ message = (
+ f"model is offline (pricing online=false): {model}; "
+ "set the pricing row online to re-enable binding"
+ )
+ elif not bindable:
message = (
"model binding is disabled: "
"session_policies.bindable_models is empty or unset in "
diff --git a/src/coding/proxy/server/static/config/config.css b/src/coding/proxy/server/static/config/config.css
index 57d469cc..fe9b2712 100644
--- a/src/coding/proxy/server/static/config/config.css
+++ b/src/coding/proxy/server/static/config/config.css
@@ -1,6 +1,7 @@
/* Dashboard → Config 页样式(深色主题,复用 dashboard :root token).
* 规范:表格固定列宽(同属性同宽 token)、单行 + 省略号 + tooltip;
- * 表单行 label 恰占 1/12、ⓘ 独占右侧 20px、控件同一行。
+ * 表单行 label 占行宽 1/12(下限 104px,窗口变窄时不截断)、ⓘ 独占右侧 20px、控件同一行;
+ * 视口 ≤640px 时 label 与控件分两行。
*/
/* 列宽 token(--col-*)定义在 dashboard :root,与 Sessions 表共用 */
#config-root { color-scheme: dark; --cfg-control-bg: rgba(48,54,61,.4); }
@@ -27,6 +28,9 @@
/* ── 卡片与分组 ── */
.cfg-body { margin-bottom: 72px; }
+/* 表单卡每次 rerender 都会重建:不重放入场动画,也不做 hover 抬升 */
+.card.cfg-body, .card.cfg-lock { animation: none; }
+.card.cfg-body:hover { box-shadow: var(--shadow); }
.cfg-body[inert] { opacity: .65; pointer-events: none; } /* 保存进行中冻结表单(pointer-events 兜底不支持 inert 的浏览器) */
.cfg-section-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin: 4px 0 12px; }
.cfg-section-title {
@@ -48,7 +52,7 @@
/* ── 表单行:[label 恰占行宽 1/12][ⓘ 20px][control] 同一行(详情卡内同样适用) ── */
.cfg-row {
- display: grid; grid-template-columns: calc(100% / 12) 20px minmax(0, 1fr);
+ display: grid; grid-template-columns: minmax(104px, calc(100% / 12)) 20px minmax(0, 1fr);
align-items: center; min-height: 36px; padding: 3px 0;
}
.cfg-label { font-size: 13px; color: var(--text-secondary); padding-right: 6px; cursor: default; }
@@ -69,7 +73,7 @@
.cfg-info:hover, .cfg-info:focus-visible { color: var(--accent-blue); outline: none; background: rgba(88,166,255,.1); }
.cfg-tip {
display: none; position: absolute; left: 22px; top: 50%; transform: translateY(-50%); z-index: 20;
- width: max-content; max-width: 360px; padding: 8px 10px; white-space: normal;
+ width: max-content; max-width: min(360px, calc(100vw - 3rem)); padding: 8px 10px; white-space: normal;
font-size: 12px; font-weight: 400; line-height: 1.5; color: var(--text-primary); text-transform: none; letter-spacing: 0;
background: rgba(10,14,20,.97); border: 1px solid rgba(255,255,255,.1); border-radius: var(--radius-sm);
box-shadow: var(--shadow-md);
@@ -121,6 +125,13 @@ span.cfg-map-key { color: var(--text-secondary); }
.cfg-btn-primary { background: rgba(88,166,255,.16); border-color: rgba(88,166,255,.35); color: var(--accent-blue); }
.cfg-btn-primary:hover:not(:disabled) { background: rgba(88,166,255,.24); color: #fff; }
.cfg-btn-danger:hover:not(:disabled) { color: var(--accent-red); border-color: rgba(248,81,73,.4); }
+/* 大范围操作的入口降权:透明底,hover 才显形 */
+.cfg-btn-ghost { background: transparent; border-color: transparent; }
+.cfg-btn-ghost:hover:not(:disabled) { background: rgba(255,255,255,.06); border-color: transparent; color: var(--text-primary); }
+.cfg-vendor-head .cfg-actions .cfg-btn-danger { margin-left: 8px; }
+/* 确认框的主按钮在破坏性操作上用 danger */
+.cfg-btn-primary.cfg-btn-danger-solid { background: rgba(248,81,73,.16); border-color: rgba(248,81,73,.45); color: var(--accent-red); }
+.cfg-btn-primary.cfg-btn-danger-solid:hover:not(:disabled) { background: rgba(248,81,73,.24); border-color: var(--accent-red); color: #fff; }
.cfg-link {
border: none; background: none; padding: 0; max-width: 100%; cursor: pointer; font: inherit; color: var(--accent-blue);
text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
@@ -140,6 +151,10 @@ span.cfg-map-key { color: var(--text-secondary); }
.cfg-row-open > td { background: rgba(88,166,255,.05); }
.cfg-detail-row > td { padding: 0 0 6px; white-space: normal; overflow: visible; }
.cfg-detail { margin: 4px 0 0; padding: 12px 16px; }
+@media (prefers-reduced-motion: no-preference) {
+ .cfg-list-row.cfg-row-new > td { animation: cfg-row-new 2s ease-out; }
+}
+@keyframes cfg-row-new { from { background: rgba(88,166,255,.24); } to { background: rgba(88,166,255,.05); } }
/* ── Banner / 保存栏 / 对话框 ── */
.cfg-banner {
@@ -159,6 +174,25 @@ span.cfg-map-key { color: var(--text-secondary); }
}
.cfg-savebar[hidden] { display: none; }
.cfg-savebar-msg { flex: 1; min-width: 0; font-size: 13px; color: var(--text-secondary); }
+.cfg-savebar-msg > * + * { margin-top: 2px; }
+.cfg-savebar-ok { border-color: rgba(63,185,80,.35); }
+.cfg-savebar-warn { border-color: rgba(210,153,34,.45); }
+.cfg-savebar-err { border-color: rgba(248,81,73,.45); }
+.cfg-result { display: flex; align-items: baseline; flex-wrap: wrap; gap: 2px 8px; color: var(--text-primary); }
+.cfg-result:focus { outline: none; }
+.cfg-result:focus-visible { outline: 2px solid var(--accent-blue); outline-offset: 2px; }
+.cfg-result-dot { flex: none; align-self: center; width: 8px; height: 8px; border-radius: 50%; background: var(--text-tertiary); }
+.cfg-savebar-ok .cfg-result-dot { background: var(--accent-green); }
+.cfg-savebar-warn .cfg-result-dot { background: var(--accent-yellow); }
+.cfg-savebar-err .cfg-result-dot { background: var(--accent-red); }
+.cfg-result .cfg-note { flex-basis: 100%; margin: 0; max-height: 72px; overflow-y: auto; }
+.cfg-undo { display: flex; align-items: center; gap: 8px; min-width: 0; }
+.cfg-undo .cfg-link { flex: none; }
+.cfg-scope { color: var(--text-secondary); }
+/* 保存栏常驻时,键盘焦点不被它盖住 */
+html:has(#config-root .cfg-savebar:not([hidden])) { scroll-padding-bottom: 120px; }
+#config-root [data-focus-ring]:focus { outline: 2px solid var(--accent-blue); outline-offset: 2px; }
+.cfg-live { position: absolute; width: 1px; height: 1px; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.cfg-savebar-errors { list-style: none; margin: 4px 0 0; padding: 0; max-height: 120px; overflow-y: auto; }
.cfg-savebar-errors .cfg-link { color: var(--accent-red); font-size: 12px; }
.cfg-lock { max-width: 720px; }
@@ -173,9 +207,28 @@ span.cfg-map-key { color: var(--text-secondary); }
.cfg-dialog-block { margin: 12px 0; font-size: 13px; }
.cfg-dialog-block ul { margin: 0; padding-left: 18px; color: var(--text-secondary); }
.cfg-dialog-block li { overflow-wrap: anywhere; }
+.cfg-dialog-text { margin: 8px 0 2px; font-size: 13px; line-height: 1.55; color: var(--text-secondary); }
+.cfg-dialog-impact li { padding: 1px 0; }
+.cfg-diff-group-title { margin-top: 6px; font-size: 12px; color: var(--text-tertiary); }
+.cfg-diff-row { display: grid; grid-template-columns: minmax(120px, 34%) minmax(0, 1fr); gap: 8px; padding: 1px 0; font-size: 13px; color: var(--text-secondary); }
+.cfg-diff-val { font-family: 'JetBrains Mono', monospace; font-size: 12px; color: var(--text-primary); min-width: 0; overflow-wrap: anywhere; }
+.cfg-diff-val del { color: var(--text-tertiary); }
+.cfg-diff-val ins { color: var(--accent-blue); text-decoration: none; }
+.cfg-dialog details > summary { cursor: pointer; color: var(--accent-blue); }
+.cfg-dialog details[open] > summary { margin-bottom: 4px; }
.cfg-dialog-warn .cfg-group-title, .cfg-dialog-warn li { color: var(--accent-yellow); }
.cfg-dialog .cfg-actions { margin-top: 16px; }
@media (max-width: 960px) {
.cfg-input, .cfg-secret-input, .cfg-lock-row .cfg-input { width: 100%; }
}
+@media (max-width: 640px) {
+ .cfg-row { grid-template-columns: minmax(0, max-content) 20px; justify-content: start; row-gap: 4px; }
+ .cfg-control { grid-column: 1 / -1; padding-left: 0; }
+ .cfg-control > .cfg-input { flex: 1 1 140px; width: auto; }
+ .cfg-control > .cfg-unit { flex: none; }
+ /* 说明气泡改为贴着行的左缘展开,停在视口内(ⓘ 在两行布局下位于 label 右侧,向右展开会出屏) */
+ .cfg-row { position: relative; }
+ .cfg-row .cfg-info-wrap { position: static; }
+ .cfg-row .cfg-tip { left: 0; top: 100%; transform: none; max-width: calc(100vw - 5rem); } /* 展开在行的下方,不盖住自己的 ⓘ */
+}
diff --git a/src/coding/proxy/server/static/config/config.js b/src/coding/proxy/server/static/config/config.js
index 4b4dd3a1..a0d092a9 100644
--- a/src/coding/proxy/server/static/config/config.js
+++ b/src/coding/proxy/server/static/config/config.js
@@ -204,6 +204,89 @@
return newDefaultRows(work, newDefaultRows(base, defaults));
}
+ // 字段级 diff(保存确认框用):对象按路径递归;vendors 按 vendor 名配对;列表型 section 按行键配对
+ var ROW_KEY = {
+ pricing: ['vendor', 'model'], model_mapping: ['pattern'], 'session_policies.policies': ['name'],
+ 'session_policies.bindable_models': ['label'], 'session_policies.title_vendor_bindings': ['prefix'],
+ };
+ function rowKeyOf(sec, row) {
+ var ks = ROW_KEY[sec];
+ return ks && isObj(row) ? ks.map(function (k) { return String(row[k]); }).join('/') : JSON.stringify(row);
+ }
+ function shortVal(v) {
+ var s = Array.isArray(v) ? (v.length ? v.map(String).join(' → ') : '[]') : fmtVal(v);
+ return s.length > 60 ? s.slice(0, 57) + '…' : s;
+ }
+ function maskUrl(v) { return typeof v === 'string' ? v.replace(/\/\/[^/@\s]+@/, '//***@') : v; }
+ function diffLeaves(a, b, path, out, o) {
+ if (deepEqual(a, b)) return;
+ if (Array.isArray(a) && Array.isArray(b) && ROW_KEY[path]) { diffRows(path, a, b, out, o); return; }
+ if (isObj(a) && isObj(b)) {
+ Object.keys(a).concat(Object.keys(b).filter(function (k) { return !(k in a); }))
+ .forEach(function (k) { if (!o.skip(path + '.' + k)) diffLeaves(a[k], b[k], path + '.' + k, out, o); });
+ return;
+ }
+ out.push({ path: path, label: o.label(path), before: maskUrl(shortVal(a)), after: maskUrl(shortVal(b)) });
+ }
+ function diffRows(sec, a, b, out, o) {
+ var pool = {}, hit = {};
+ (b || []).forEach(function (r, j) { var k = rowKeyOf(sec, r); (pool[k] = pool[k] || []).push(j); });
+ (a || []).forEach(function (r, i) {
+ var q = pool[rowKeyOf(sec, r)];
+ if (q && q.length) { var j = q.shift(); hit[j] = true; diffLeaves(r, b[j], sec + '.' + j, out, o); }
+ else out.push({ path: sec + '.' + i, label: o.rowTitle(sec, r), before: '', after: '', removed: true });
+ });
+ (b || []).forEach(function (r, j) { if (!hit[j]) out.push({ path: sec + '.' + j, label: o.rowTitle(sec, r), before: '', after: '', added: true }); });
+ }
+ // 返回按 section 分组的差异行;数组型 section 只给「新增 / 移除 / 同键条目的字段变化」
+ function changedRows(base, work, o) {
+ var groups = [], open = function (title) { var g = { title: title, rows: [] }; groups.push(g); return g.rows; };
+ dirtySections(base, work).forEach(function (s) {
+ if (s === 'vendors') {
+ var a = vendorMap(base.vendors), b = vendorMap(work.vendors);
+ var oa = (base.vendors || []).map(function (v) { return v.vendor; }), ob = (work.vendors || []).map(function (v) { return v.vendor; });
+ if (oa.join('\u0000') !== ob.join('\u0000') && oa.slice().sort().join('\u0000') === ob.slice().sort().join('\u0000')) {
+ open(o.sectionLabel(s)).push({ path: 'vendors', label: '顺序', before: oa.join(' → '), after: ob.join(' → ') });
+ }
+ Object.keys(a).concat(Object.keys(b).filter(function (t) { return !(t in a); })).forEach(function (t) {
+ var rows = open(o.sectionLabel(s) + ' › ' + t);
+ if (!a[t]) rows.push({ path: 'vendors.' + t, label: t, before: '', after: '', added: true });
+ else if (!b[t]) rows.push({ path: 'vendors.' + t, label: t, before: '', after: '', removed: true });
+ else diffLeaves(a[t], b[t], 'vendors.' + t, rows, o);
+ });
+ return;
+ }
+ var rows = open(o.sectionLabel(s));
+ if (Array.isArray(base[s]) || Array.isArray(work[s])) diffRows(s, base[s] || [], work[s] || [], rows, o);
+ else diffLeaves(base[s], work[s], s, rows, o);
+ });
+ return groups.filter(function (g) { return g.rows.length; });
+ }
+ // 保存后果清单(非空才弹确认框):只返回原因码与数据,文案由界面层生成
+ function saveImpact(o) {
+ var out = [], p = o.payload, v = o.view, st = o.status || {}, tiers = st.tiers || [];
+ var names = function (pred) { return tiers.filter(pred).map(function (t) { return t.name; }); };
+ var ops = Object.keys(p.secret_ops);
+ if (ops.length) out.push({ code: 'secrets', danger: ops.some(function (x) { return p.secret_ops[x].op === 'clear'; }), paths: ops });
+ if (o.cleared.length) out.push({ code: 'cleared', danger: true, paths: o.cleared });
+ if (st.in_flight > 0) out.push({ code: 'inflight', n: st.in_flight });
+ var cb = names(function (t) { return t.circuit_breaker && t.circuit_breaker.state && t.circuit_breaker.state !== 'closed'; });
+ var rl = names(function (t) { return t.rate_limit && t.rate_limit.is_rate_limited; });
+ var qx = names(function (t) { return [t.quota_guard, t.weekly_quota_guard].some(function (q) { return q && q.state === 'quota_exceeded'; }); });
+ if (cb.length) out.push({ code: 'breaker', names: cb });
+ if (rl.length) out.push({ code: 'ratelimit', names: rl });
+ if (qx.length) out.push({ code: 'quota', names: qx });
+ var running = v.running && v.running.tiers;
+ if (Array.isArray(running) && (p.sections.vendors || p.sections.tiers) && !deepEqual(running, o.chain)) out.push({ code: 'tiers' });
+ var boot = (v.running && v.running.boot_revisions) || {};
+ var pend = Object.keys(p.sections).filter(function (s) { return s in boot && boot[s] !== v.revisions[s]; });
+ if (pend.length) out.push({ code: 'pending', sections: pend });
+ var before = vendorMap(o.base.vendors), after = vendorMap(o.work.vendors);
+ var gone = Object.keys(before).filter(function (t) { return !after[t]; });
+ if (gone.length && p.sections.vendors) out.push({ code: 'removed', vendors: gone });
+ return out;
+ }
+
var helpers = {
deepEqual: deepEqual, clone: clone, isTmpl: isTmpl, validToken: validToken, assignField: assignField,
parsePrice: parsePrice, entryCurrency: entryCurrency, priceText: priceText, withCurrency: withCurrency,
@@ -211,6 +294,7 @@
countChangedFields: countChangedFields, buildPayload: buildPayload, predictClearedSecrets: predictClearedSecrets,
movedOpenIndex: movedOpenIndex,
effectiveChain: effectiveChain, newDefaultRows: newDefaultRows, pricingMergeRows: pricingMergeRows,
+ changedRows: changedRows, saveImpact: saveImpact,
};
if (typeof module !== 'undefined' && module.exports) module.exports = helpers;
if (typeof window === 'undefined' || typeof document === 'undefined') return;
@@ -232,6 +316,7 @@
pill: 'vendors', vendor: null, expanded: {}, loaded: false, saving: false, readonly: false,
specs: [], specMap: {}, schema: { fields: {}, groups: {} },
retryOnly: null, fatalText: null,
+ confirming: false, focus: null, focusTo: null, focusRemap: null, newRow: null, undo: null, live: null,
};
var uid = 0;
@@ -331,8 +416,10 @@
['mode', 'errors', 'notices', 'overridden', 'vendor_overrides', 'secrets', 'sources', 'running', 'apply_supported']
.forEach(function (k) { prev[k] = view[k]; });
prev.values.absent_vendors = view.values.absent_vendors;
+ clearUndo(only); // 冲突 section 的工作副本已被服务器值替换
} else {
S.view = view;
+ S.undo = null;
S.base = {};
S.work = {};
S.ops = {};
@@ -346,8 +433,95 @@
}
// ── 渲染骨架 ──────────────────────────────────────────────
+ // ── 焦点找回:rerender 整体重建 DOM,按「容器路径 + 控件角色」把焦点还给同一控件 ──
+ var ROLE_CLASS = /^(cfg-(input|num|check|info|chip-add|chip-x|link|secret-menu|secret-input|map-key|btn-icon|btn-sm|btn-primary)|range-btn)$/;
+ function roleOf(el) {
+ if (!el || !el.getAttribute) return null;
+ var aria = el.getAttribute('aria-label');
+ if (aria) return el.tagName + '@' + aria;
+ if (/^(BUTTON|A|SUMMARY)$/.test(el.tagName)) return el.tagName + ':' + String(el.textContent || '').trim().slice(0, 24);
+ var cls = String(el.className || '').split(/\s+/).filter(function (c) { return ROLE_CLASS.test(c); });
+ return el.tagName + '.' + (cls[0] || '');
+ }
+ // :focus-visible 在旧浏览器是未知伪类,matches() 会抛 SyntaxError
+ function visibleRing(el) {
+ if (!el || !el.matches) return false;
+ try { return el.matches(':focus-visible'); } catch (e) { return false; }
+ }
+ function captureFocus() {
+ S.focus = null;
+ var a = document.activeElement;
+ if (!a || a === document.body || !S.root) return;
+ if (S.root.contains && !S.root.contains(a)) return;
+ var host = a.closest && a.closest('[data-path], [data-pill], [data-vendor]');
+ if (!host) return;
+ var attr = host.hasAttribute('data-path') ? 'data-path' : host.hasAttribute('data-pill') ? 'data-pill' : 'data-vendor';
+ var loose = looseRole(a);
+ S.focus = { attr: attr, val: host.getAttribute(attr), role: roleOf(a), loose: loose, li: sameLoose(host, loose).indexOf(a), ring: visibleRing(a) };
+ }
+ // 容器内与某控件同属一类的控件(文档序),用于按钮文案变化后按序号找回
+ function sameLoose(host, loose) {
+ return [host].concat(Array.prototype.slice.call(host.querySelectorAll('*'))).filter(function (n) { return looseRole(n) === loose; });
+ }
+ // 按钮文案会变(编辑 ↔ 收起),用「标签 + 首个按钮类」做第二级匹配
+ function looseRole(el) {
+ if (!/^(BUTTON|A|SUMMARY)$/.test(el.tagName)) return roleOf(el);
+ var c = String(el.className || '').split(/\s+/).filter(function (x) { return /^(cfg-btn|range-btn)/.test(x); });
+ return el.tagName + '.' + (c[c.length - 1] || '');
+ }
+ function focusable(n) {
+ return !!(n && n.focus && !n.disabled && n.getAttribute('tabindex') !== '-1');
+ }
+ // 落点优先级:调用方指定的 S.focusTo > 同容器内同角色 > 同容器内同类按钮 > 同容器内首个控件 > 当前激活的 pill;
+ // 目标必须可聚焦(如上移到首行后「上移」已禁用,落到同行的「下移」)
+ function restoreFocus() {
+ // focusRemap 无条件取走:鼠标点 ↑/↓ 不聚焦按钮的浏览器不会带 key,不能让它留到下一次重绘
+ var pick = S.focusTo, key = S.focus, remap = S.focusRemap;
+ S.focusTo = null; S.focus = null; S.focusRemap = null;
+ if (!S.root) return;
+ var target = null, ring = !!(key && key.ring);
+ // 调用方的落点:返回 false 表示「不聚焦」(如撤销目标已不在当前页),不走回退
+ if (pick) { try { target = pick(); } catch (e) { target = null; } if (target === false) return; }
+ if (!target && key && key.val !== null && key.role) {
+ var val = remap && remap.from === key.val ? remap.to : key.val;
+ var host = S.root.querySelector('[' + key.attr + '="' + val + '"]');
+ if (host) {
+ var first = function (list, f) { for (var i = 0; i < list.length; i++) if (f(list[i]) && focusable(list[i])) return list[i]; return null; };
+ var all = [host].concat(Array.prototype.slice.call(host.querySelectorAll('*')));
+ target = first(all, function (n) { return roleOf(n) === key.role; });
+ if (!target) {
+ // 按钮文案会变(编辑 ↔ 收起、下线 ↔ 上线):按它在同类按钮里的序号找回同一位置的那颗
+ var peers = sameLoose(host, key.loose);
+ target = first([peers[Math.min(key.li, peers.length - 1)]], function () { return true; }) || first(peers, function () { return true; });
+ }
+ if (!target) target = first(all, function (n) { return /^(BUTTON|INPUT|SELECT|TEXTAREA|A)$/.test(n.tagName) && n.type !== 'hidden'; });
+ }
+ if (!target) target = S.root.querySelector('.cfg-pills .range-btn.active');
+ }
+ if (!focusable(target)) return;
+ // 焦点原由键盘而来时,重绘后脚本聚焦不触发 :focus-visible,用属性补回焦点环,失焦即撤
+ if (ring && target.setAttribute) {
+ target.setAttribute('data-focus-ring', '1');
+ target.addEventListener('blur', function () { target.removeAttribute('data-focus-ring'); });
+ }
+ // 不用 preventScroll:控件被常驻保存栏盖住时,让浏览器按 scroll-padding-bottom 把它滚出来;
+ // 控件本来就在视口内时 focus() 不会滚动
+ target.focus();
+ }
+ // 「添加」后的新行:高亮 2 秒,并把展开的编辑表单滚到视口中部
+ function flashNewRow() {
+ var key = S.newRow;
+ S.newRow = null;
+ if (!key || !S.root) return;
+ var row = S.root.querySelector('.cfg-list-row[data-path="' + key + '"]');
+ if (!row) return;
+ row.classList.add('cfg-row-new');
+ if (row.nextElementSibling && row.nextElementSibling.scrollIntoView) row.nextElementSibling.scrollIntoView({ block: 'center' });
+ setTimeout(function () { row.classList.remove('cfg-row-new'); }, 2000);
+ }
function rerender() {
if (!S.root || !S.view) return;
+ captureFocus();
var nodes = [renderToolbar()].concat(renderBanners());
var body = h('div', { class: 'card cfg-body', 'data-path': S.pill === 'system' ? null : S.pill });
RENDER[S.pill](body);
@@ -355,7 +529,10 @@
clear(S.root);
add(S.root, nodes);
applyErrors();
+ syncTruncTitles();
updateDirty();
+ restoreFocus();
+ flashNewRow();
}
function renderToolbar() {
// pills 为按钮组(非 tabs 模式):当前项以 aria-current 标注
@@ -368,17 +545,21 @@
});
return h('div', { class: 'cfg-toolbar' }, [
pills,
- btn('锁定', function () {
- if (isDirty() && !window.confirm('锁定会丢弃未保存的修改,继续?')) return;
- forgetToken();
- renderLocked();
- }, 'cfg-btn-sm', { title: '清除本浏览器保存的管理 token' }),
+ btn('锁定', lockNow, 'cfg-btn-sm', { title: '清除本浏览器保存的管理 token' }),
]);
}
+ function lockNow() {
+ var run = function () { forgetToken(); S.undo = null; renderLocked(); };
+ if (!isDirty()) { run(); return; }
+ askConfirm({ title: '锁定并丢弃修改?', body: '锁定会丢弃全部未保存的修改,已保存的配置不受影响。', confirmText: '丢弃并锁定', danger: true }, run);
+ }
function goPill(name, vendor) {
S.pill = name;
if (vendor) S.vendor = vendor;
syncUrl();
+ // 整页重绘后焦点落到新的激活项,而不是掉回 body
+ var sel = vendor ? '.cfg-subpills .range-btn[data-vendor="' + vendor + '"]' : '.cfg-pills .range-btn[data-pill="' + name + '"]';
+ S.focusTo = function () { return S.root.querySelector(sel); };
rerender();
}
function syncUrl() {
@@ -404,7 +585,6 @@
}
function renderBanners() {
var out = [], v = S.view;
- if (S.notice) out.push(noticeBanner());
if (v.mode !== 'store') out.push(banner(v.mode === 'defaults' ? 'info' : 'err', MODE_TEXT[v.mode] || v.mode));
if (!v.apply_supported && !S.readonly) out.push(banner('info', '当前实例不支持在线生效:保存会写入 config.db,需重启 coding-proxy 后生效'));
var boot = (v.running && v.running.boot_revisions) || {};
@@ -417,6 +597,7 @@
S.loaded = false;
S.view = null; // 丢弃工作副本(含待设置的密钥明文)
S.ops = {};
+ S.undo = null;
updateDirty(); // 清除 Config 页签上的 dirty 点
var input = h('input', {
type: 'password', class: 'cfg-input', autocomplete: 'off', 'aria-label': 'Admin token',
@@ -459,13 +640,13 @@
}
// ── 表单行与控件 ──────────────────────────────────────────
- function infoTip(label, desc) {
+ function infoTip(label, desc, withLabel) {
var id = 'cfg-tip' + (++uid);
// Esc 隐藏全部说明;再次悬停或聚焦某个 ⓘ 时恢复该项
var rearm = function (e) { e.currentTarget.classList.remove('cfg-tip-off'); };
return h('span', { class: 'cfg-info-wrap', onmouseenter: rearm, onfocusin: rearm }, [
h('button', { type: 'button', class: 'cfg-info', 'aria-label': 'Help: ' + label, 'aria-describedby': id, text: 'ⓘ' }),
- h('span', { class: 'cfg-tip', role: 'tooltip', id: id, text: desc || label }),
+ h('span', { class: 'cfg-tip', role: 'tooltip', id: id, text: withLabel && desc ? label + ':' + desc : (desc || label) }),
]);
}
var LABELABLE = ['INPUT', 'SELECT', 'TEXTAREA', 'BUTTON', 'OUTPUT', 'METER', 'PROGRESS'];
@@ -479,7 +660,7 @@
labelable
? h('label', { class: 'cfg-label cfg-trunc', for: id, text: sp.label })
: h('span', { class: 'cfg-label cfg-trunc', id: lid, text: sp.label }),
- infoTip(sp.label, sp.description),
+ infoTip(sp.label, sp.description, true),
h('div', { class: 'cfg-control', role: labelable ? null : 'group', 'aria-labelledby': labelable ? null : lid },
[ctrl, sp.unit ? h('span', { class: 'cfg-unit', text: sp.unit }) : null].concat(extras || [])),
]);
@@ -586,7 +767,16 @@
type: 'number', class: 'cfg-input cfg-num', value: String(cur()[k]), disabled: dis, 'aria-label': k,
oninput: function (e) { var n = cur(); n[k] = numVal(e.target.value); b.set(n); },
}),
- dis ? null : btn('删除', function () { var n = cur(); delete n[k]; b.set(n); redraw(); }, 'cfg-btn-sm'),
+ dis ? null : btn('移除', function () {
+ var n = cur(), old = n[k];
+ delete n[k];
+ // 先记撤销再写工作副本(b.set 会立刻重建保存栏);b.path 只是展示路径(vendors 是数组),撤销用闭包回写
+ S.undo = { kind: 'fn', section: b.path.split('.')[0], path: b.path, label: '已移除 ' + sp.label + ' 中的 ' + k, run: function () { var m = cur(); m[k] = old; b.set(m); } };
+ b.set(n);
+ redraw();
+ var add = wrap.querySelector('[data-map-add]');
+ if (add && add.focus) add.focus();
+ }, 'cfg-btn-sm'),
]));
});
if (dis) return;
@@ -596,7 +786,9 @@
var k = key.value.trim();
if (!k || val.value === '') return;
var n = cur(); n[k] = numVal(val.value); b.set(n); redraw();
- }, 'cfg-btn-sm')]));
+ var first = wrap.querySelector('.cfg-map-key[type="text"]');
+ if (first && first.focus) first.focus();
+ }, 'cfg-btn-sm', { 'data-map-add': '1' })]));
}
redraw();
return wrap;
@@ -625,16 +817,17 @@
if (!kind || kind === 'keep') delete S.ops[path];
else S.ops[path] = kind === 'set' ? { op: 'set', value: '' } : { op: kind };
changed();
+ S.focusTo = function () {
+ return S.root.querySelector(kind === 'set' ? '.cfg-secret-input[data-for="' + path + '"]' : 'select.cfg-secret-menu[data-for="' + path + '"]');
+ };
rerender();
- var input = kind === 'set' && S.root.querySelector('.cfg-secret-input[data-for="' + path + '"]');
- if (input) input.focus();
}
function secretWidget(sp, path, id) {
var st = (S.view.secrets || {})[path] || { kind: 'empty' }, op = S.ops[path];
var wrap = h('div', { class: 'cfg-secret' }, [secretPill(st, op, sp)]);
if (S.readonly || sp.readonly) return wrap;
wrap.appendChild(h('select', {
- id: id, class: 'cfg-input cfg-secret-menu', onchange: function (e) { var k = e.target.value; e.target.value = ''; if (k) setOp(path, k); },
+ id: id, class: 'cfg-input cfg-secret-menu', 'data-for': path, onchange: function (e) { var k = e.target.value; e.target.value = ''; if (k) setOp(path, k); },
}, [
h('option', { value: '', text: '更改 ▾' }),
h('option', { value: 'set', text: '设置新值' }),
@@ -660,10 +853,28 @@
h('div', { class: 'cfg-actions' }, actions || []),
]);
}
+ // 「恢复默认」:vendors 的入口重置全部 vendor,改名并降权;会替换已保存值或波及当前对象之外时先确认
function resetBtn(section) {
if (S.readonly) return null;
- return btn('恢复默认', function () { S.work[section] = clone(S.view.defaults[section]); changed(); rerender(); }, 'cfg-btn-sm',
- { title: '把本 section 改回包内默认值(保存后生效)' });
+ var all = section === 'vendors';
+ var n = ((S.view.defaults || {}).vendors || S.work.vendors || []).length;
+ return btn(all ? '全部恢复默认' : '恢复默认', function () { resetSection(section); }, 'cfg-btn-sm' + (all ? ' cfg-btn-ghost' : ''), all
+ ? { title: '把全部 ' + n + ' 个 vendor 改回包内默认值,其他 vendor 上未保存的修改也会丢弃(保存后生效)', 'aria-label': '全部恢复默认(所有 vendor)' }
+ : { title: '把本 section 改回包内默认值(保存后生效)' });
+ }
+ function resetSection(section) {
+ var dflt = S.view.defaults[section];
+ if (deepEqual(S.work[section], dflt)) return;
+ var all = section === 'vendors';
+ var saved = (S.view.overridden || []).indexOf(section) >= 0;
+ var run = function () { S.work[section] = clone(dflt); S.undo = null; changed(); rerender(); };
+ if (!all && !saved) { run(); return; }
+ var name = all ? '全部 ' + ((S.view.defaults.vendors || S.work.vendors || []).length) + ' 个 vendor' : sectionLabel(section);
+ askConfirm({
+ title: (all ? '全部' : '') + '恢复默认?',
+ body: '以下范围将改回包内默认值:' + name + '。' + (saved ? '已保存的自定义值会在保存后被替换。' : '') + (all ? '其他 vendor 上未保存的修改也会丢弃。' : ''),
+ confirmText: all ? '全部恢复默认' : '恢复默认', danger: true,
+ }, run);
}
// ── 表格 ──────────────────────────────────────────────────
@@ -682,27 +893,53 @@
]);
}
// 列表 section:固定列宽表格 + 展开行编辑 +(可选)↑/↓ 排序
+ // 被移除行在保存栏里的名字:取前两列;刚「添加」还没填的空行统一叫「空行」
+ function rowName(o, item) {
+ var name = o.cols.slice(0, 2).map(function (c) { return fmtVal(c.text(item)); }).join(' / ');
+ return name === '— / —' ? '空行' : name;
+ }
+ // o.deletable(item, i):行级移除开关(返回 false 不出「移除」);o.rowActions(item, i):行内额外按钮
function listBlock(o) {
var arr = function () { var a = getIn(S.work, o.parts); return Array.isArray(a) ? a : []; };
var setArr = function (a, open) { setIn(S.work, o.parts, a); S.expanded[o.key] = open; changed(); rerender(); };
var prefix = o.parts.join('.');
+ var canDelete = o.deletable || function () { return true; };
var cols = (o.ordered ? [{ label: 'Order', w: '--col-order' }] : []).concat(o.cols, [{ label: 'Actions', w: '--col-actions' }]);
var move = function (from, to) {
var a = arr().slice(), item = a.splice(from, 1)[0];
a.splice(to, 0, item);
+ S.focusRemap = { from: prefix + '.' + from, to: prefix + '.' + to };
+ S.undo = null; // 撤销按下标插回,行序变了就不再是原位
setArr(a, movedOpenIndex(S.expanded[o.key], from, to));
};
+ // 移除一行:不弹确认,保存栏给单级「撤销」(插回原位,不影响其后的其它编辑)
+ var removeRow = function (i) {
+ var a = arr().slice(), item = a.splice(i, 1)[0];
+ S.undo = { kind: 'row', section: o.parts[0], key: o.key, label: '已移除 ' + o.title + ' 的「' + rowName(o, item) + '」', parts: o.parts, index: i, item: clone(item) };
+ S.focusTo = function () {
+ var wrap = S.root.querySelector('.ft-table-wrap[data-path="' + prefix + '"]');
+ var rs = wrap.querySelectorAll('.cfg-list-row');
+ if (!rs.length) { // 表已空:落到该表的「添加」
+ var acts = wrap.parentNode.querySelector('.cfg-section-head .cfg-actions');
+ return acts && acts.children.length ? acts.children[acts.children.length - 1] : false;
+ }
+ var r = rs[Math.min(i, rs.length - 1)];
+ return r.querySelector('.cfg-btn-sm') || false;
+ };
+ setArr(a, null);
+ };
var rows = [];
arr().forEach(function (item, i) {
var open = S.expanded[o.key] === i;
var cells = o.cols.map(function (c) { return cell(c.text(item), c.mono ? 'cfg-mono' : ''); });
var refresh = function () { var it = arr()[i]; o.cols.forEach(function (c, k) { cells[k].textContent = fmtVal(c.text(it)); }); };
- var toggle = function () { S.expanded[o.key] = open ? null : i; rerender(); };
+ var toggle = function () { if (window.getSelection && String(window.getSelection())) return; S.expanded[o.key] = open ? null : i; rerender(); };
rows.push(h('tr', { class: 'cfg-list-row' + (open ? ' cfg-row-open' : ''), 'data-path': prefix + '.' + i, onclick: toggle },
(o.ordered ? [orderCell(arr(), i, move)] : []).concat(cells, [h('td', { class: 'cfg-cell-actions' }, [
btn(open ? '收起' : '编辑', function (e) { e.stopPropagation(); toggle(); }, 'cfg-btn-sm', { 'aria-expanded': open ? 'true' : 'false' }),
- S.readonly ? null : btn('删除', function (e) { e.stopPropagation(); var a = arr().slice(); a.splice(i, 1); setArr(a, null); }, 'cfg-btn-sm cfg-btn-danger'),
- ]), h('td')])));
+ ].concat(o.rowActions ? (o.rowActions(item, i) || []) : [], [
+ S.readonly || !canDelete(item, i) ? null : btn('移除', function (e) { e.stopPropagation(); removeRow(i); }, 'cfg-btn-sm cfg-btn-danger'),
+ ])), h('td')])));
if (!open) return;
var fields = o.fields(i).map(function (f) {
var b = f.bind, set = b.set;
@@ -712,7 +949,19 @@
rows.push(h('tr', { class: 'cfg-detail-row' }, h('td', { colspan: String(cols.length + 1) }, h('div', { class: 'detail-card cfg-detail' }, fields))));
});
if (!rows.length) rows.push(h('tr', {}, h('td', { colspan: String(cols.length + 1), class: 'empty', text: '暂无条目' })));
- var actions = (o.actions || []).concat(S.readonly ? [] : [btn('添加', function () { var a = arr().slice(); a.push(o.blank()); setArr(a, a.length - 1); }, 'cfg-btn-sm')]);
+ var actions = (o.actions || []).concat(S.readonly ? [] : [btn('添加', function () {
+ var a = arr().slice(); a.push(o.blank());
+ S.undo = null;
+ var at = a.length - 1;
+ S.newRow = prefix + '.' + at;
+ // 落点限定在「新行自己的展开表单」:别的行可能也处于展开状态
+ S.focusTo = function () {
+ var row = S.root.querySelector('.cfg-list-row[data-path="' + prefix + '.' + at + '"]');
+ var detail = row && row.nextElementSibling;
+ return detail ? detail.querySelector('.cfg-control input, .cfg-control select') : null;
+ };
+ setArr(a, a.length - 1);
+ }, 'cfg-btn-sm')]);
return h('div', { class: 'cfg-list' }, [sectionHead(o.title, spec(o.specPath), actions)].concat(o.before || [], [table(cols, rows, prefix)]));
}
function itemBind(parts, i, rel, specPath) {
@@ -805,8 +1054,8 @@
if (t !== 'anthropic' && !scoped) badges.push(badge('No scoped mapping', 'warn', '没有仅作用于该 vendor 的 model_mapping 规则,请求模型名可能被通用规则映射'));
return h('div', { class: 'cfg-vendor-head' }, [
sectionHead(t, null, S.readonly ? [] : [
- btn('恢复默认', function () { replaceVendor(t, clone(findVendor(S.view.defaults.vendors, t)) || { vendor: t }); }, 'cfg-btn-sm', { title: '把该 vendor 改回包内默认参数(保存后生效)' }),
- btn('移除', function () { removeVendor(t); }, 'cfg-btn-sm cfg-btn-danger', { title: '从配置中移除该 vendor(同时移出 tiers)' }),
+ btn('恢复默认', function () { resetVendor(t); }, 'cfg-btn-sm', { title: '把该 vendor 改回包内默认参数(保存后生效)', 'aria-label': '恢复默认(' + t + ')' }),
+ btn('移除', function () { removeVendor(t); }, 'cfg-btn-sm cfg-btn-danger', { title: '从配置中移除该 vendor(同时移出 tiers)', 'aria-label': '移除 ' + t }),
]),
h('div', { class: 'cfg-badges' }, badges),
]);
@@ -814,6 +1063,7 @@
function addVendor(t) {
var v = clone(findVendor(S.base.vendors, t) || findVendor(S.view.defaults.vendors, t)) || { vendor: t };
S.work.vendors = (S.work.vendors || []).concat([v]);
+ S.undo = null;
changed();
rerender();
}
@@ -822,11 +1072,31 @@
changed();
rerender();
}
+ // vendor 级恢复默认:只在会替换已保存的自定义值时确认
+ function resetVendor(t) {
+ var v = clone(findVendor(S.view.defaults.vendors, t)) || { vendor: t };
+ if (deepEqual(findVendor(S.work.vendors, t), v)) return;
+ var run = function () { replaceVendor(t, v); };
+ if ((S.view.vendor_overrides || []).indexOf(t) < 0) { run(); return; }
+ askConfirm({ title: '恢复默认?', body: t + ' 有已保存的自定义参数,恢复默认后会在保存时被替换(保存前可用「放弃修改」找回)。', confirmText: '恢复默认', danger: true }, run);
+ }
+ // 移除 vendor:总是确认(会同时移出 tiers 链路);保存栏给单级「撤销」
function removeVendor(t) {
- S.work.vendors = (S.work.vendors || []).filter(function (x) { return x.vendor !== t; });
- if (Array.isArray(S.work.tiers)) S.work.tiers = S.work.tiers.filter(function (x) { return x !== t; });
- changed();
- rerender();
+ var pos = effectiveChain(S.work.tiers, S.work.vendors).indexOf(t);
+ askConfirm({
+ title: '移除 ' + t + '?',
+ body: '将从配置中移除 ' + t + (pos >= 0 ? ',并移出 Tiers 链路(当前 Tier #' + (pos + 1) + ')' : '') + '。已保存的密钥不会删除,重新添加后仍可用。',
+ confirmText: '移除', danger: true,
+ }, function () {
+ var list = S.work.vendors || [], i = -1;
+ list.forEach(function (x, k) { if (x.vendor === t) i = k; });
+ if (i < 0) return;
+ S.undo = { kind: 'vendor', section: 'vendors', label: '已移除 vendor ' + t, index: i, vendor: clone(list[i]), tierIndex: Array.isArray(S.work.tiers) ? S.work.tiers.indexOf(t) : -1 };
+ S.work.vendors = list.filter(function (x) { return x.vendor !== t; });
+ if (Array.isArray(S.work.tiers)) S.work.tiers = S.work.tiers.filter(function (x) { return x !== t; });
+ changed();
+ rerender();
+ });
}
RENDER.tiers = function (body) {
@@ -890,20 +1160,48 @@
RENDER.pricing = function (body) {
var fresh = pricingMergeRows(S.view.overridden, S.base.pricing, S.work.pricing, S.view.defaults.pricing);
- var before = [h('p', { class: 'cfg-note', text: '单价单位为每百万 token;修改后历史用量成本按新价格重算。' })];
+ var before = [h('p', { class: 'cfg-note', text: '单价单位为每百万 token;修改后历史用量成本按新价格重算。定价行不可删除:退役模型请下线(不进 Model Bind 下拉,已绑会话保留,成本照常计价)。' })];
if (fresh.length && !S.readonly) {
before.push(banner('info', '包内默认定价中有 ' + fresh.length + ' 行不在已保存的定价表中(定价表已覆盖默认值,不会自动合入)',
[btn('合并', function () { S.work.pricing = (S.work.pricing || []).concat(clone(fresh)); changed(); rerender(); }, 'cfg-btn-sm')]));
}
var price = function (f) { return function (r) { return r[f] === undefined ? '0' : fmtVal(r[f]); }; };
var curSpec = { label: 'Currency', description: '整行单价的币种:$ 为 USD,¥ 为 CNY', widget: 'enum', enum: ['USD', 'CNY'] };
+ var savedRow = function (i) { return i < (S.base.pricing || []).length; };
+ // pricing 行不可删除(Model Bind 目录派生与下线的锚):已保存行只可下线/上线,vendor/model 不可改名
+ var restoreBtn = btn('恢复默认价格', function () {
+ var defaults = S.view.defaults.pricing || [];
+ var merged = (S.work.pricing || []).map(function (row) {
+ var hit = defaults.filter(function (d) { return pricingKey(d) === pricingKey(row); })[0];
+ return hit ? clone(hit) : row;
+ });
+ defaults.forEach(function (d) {
+ if (!merged.some(function (row) { return pricingKey(row) === pricingKey(d); })) merged.push(clone(d));
+ });
+ S.work.pricing = merged;
+ changed();
+ rerender();
+ }, 'cfg-btn-sm', { title: '默认行恢复包内默认价格,自定义行保留(pricing 行不可删除)' });
body.appendChild(listBlock({
key: 'pricing', parts: ['pricing'], specPath: 'pricing', title: 'Pricing', ordered: false, before: before,
- actions: [resetBtn('pricing')],
+ actions: S.readonly ? [] : [restoreBtn],
+ deletable: function (item, i) { return !savedRow(i); },
+ rowActions: function (item, i) {
+ if (S.readonly || !savedRow(i)) return null;
+ var off = item.online === false;
+ return [btn(off ? '上线' : '下线', function (e) {
+ e.stopPropagation();
+ var row = S.work.pricing[i];
+ if (off) delete row.online; else row.online = false;
+ changed();
+ rerender();
+ }, 'cfg-btn-sm', { title: off ? '重新进入 Model Bind 下拉,新绑定可用' : '不进 Model Bind 下拉;已绑会话保留,成本照常计价' })];
+ },
cols: [
{ label: 'Vendor', w: '--col-vendor', text: function (r) { return r.vendor; } },
{ label: 'Model', w: '--col-model', mono: true, text: function (r) { return r.model; } },
{ label: 'Currency', w: '--col-currency', text: entryCurrency },
+ { label: 'Status', w: '--col-bool', text: function (r) { return r.online === false ? 'Offline' : 'Online'; } },
{ label: 'Input', w: '--col-price', mono: true, text: price(PRICE_FIELDS[0]) },
{ label: 'Output', w: '--col-price', mono: true, text: price(PRICE_FIELDS[1]) },
{ label: 'Cache W', w: '--col-price', mono: true, text: price(PRICE_FIELDS[2]) },
@@ -922,7 +1220,13 @@
changed();
},
};
- return itemFields(['pricing'], i, ['vendor', 'model']).concat([{ spec: curSpec, bind: cur }], PRICE_FIELDS.map(function (f) {
+ var baseFields = itemFields(['pricing'], i, ['vendor', 'model']);
+ if (savedRow(i)) {
+ baseFields = baseFields.map(function (f, k) {
+ return { spec: f.spec, bind: f.bind, row: function (b) { return field(spec('pricing.*.' + ['vendor', 'model'][k]), b, true); } };
+ });
+ }
+ return baseFields.concat([{ spec: curSpec, bind: cur }], PRICE_FIELDS.map(function (f) {
return {
spec: spec('pricing.*.' + f),
bind: {
@@ -1032,7 +1336,7 @@
// ── Dirty / 错误 / 保存 ───────────────────────────────────
function isDirty() { return !!S.view && (dirtySections(S.base, S.work).length > 0 || activeOps(S.ops).length > 0); }
- function changed() { updateDirty(); }
+ function changed() { if (S.notice && S.notice.kind === 'ok') S.notice = null; updateDirty(); }
function affectedSections() {
var set = {};
dirtySections(S.base, S.work).forEach(function (s) { set[s] = true; });
@@ -1063,26 +1367,96 @@
var bar = S.root.querySelector('.cfg-savebar');
if (bar) fillSaveBar(bar);
}
+ function sectionLabel(s) {
+ for (var i = 0; i < PILLS.length; i++) if (PILLS[i][0] === s) return PILLS[i][1];
+ return s;
+ }
+ // 待保存范围的可读名称:vendors 细到具体 vendor,其余用 pill 名
+ function scopeText() {
+ return affectedSections().map(function (s) {
+ if (s !== 'vendors') return sectionLabel(s);
+ var seen = {};
+ var vs = (S.base.vendors || []).concat(S.work.vendors || []).map(function (v) { return v.vendor; })
+ .filter(function (t) { return !seen[t] && (seen[t] = true) && vendorDirty(t); });
+ activeOps(S.ops).forEach(function (p) { var m = /^vendors\.([^.]+)\./.exec(p); if (m && vs.indexOf(m[1]) < 0) vs.push(m[1]); });
+ return vs.length ? 'Vendors › ' + vs.slice(0, 3).join('、') + (vs.length > 3 ? ' 等 ' + vs.length + ' 个' : '') : 'Vendors';
+ }).join('、');
+ }
function renderSaveBar() { var bar = h('div', { class: 'cfg-savebar', role: 'region', 'aria-label': 'Save changes' }); fillSaveBar(bar); return bar; }
+ // 保存栏是唯一的保存结果反馈面(顶部 Banner 只留模式类提示);结果不自动消失,由用户关闭或在下一次编辑时清除
function fillSaveBar(bar) {
- var dirty = isDirty(), n = countChangedFields(S.base, S.work, S.ops), k = affectedSections().length;
- bar.hidden = !dirty && !S.errors.length;
+ var dirty = isDirty(), n = countChangedFields(S.base, S.work, S.ops);
+ var hadFocus = !!(document.activeElement && bar.contains && bar.contains(document.activeElement));
+ bar.hidden = !dirty && !S.errors.length && !S.notice && !S.undo;
+ bar.className = 'cfg-savebar' + (S.notice ? ' cfg-savebar-' + S.notice.kind : '');
clear(bar);
- var msg = h('div', { class: 'cfg-savebar-msg' }, [h('div', { text: dirty ? n + ' 个字段待保存(' + k + ' 个 section)' : '没有未保存的修改' })]);
+ var msg = h('div', { class: 'cfg-savebar-msg' });
+ if (S.notice) {
+ msg.appendChild(h('div', { class: 'cfg-result', tabindex: '-1' }, [h('span', { class: 'cfg-result-dot', 'aria-hidden': 'true' }), h('span', { text: S.notice.text })]
+ .concat((S.notice.lines || []).map(function (l) { return h('div', { class: 'cfg-note cfg-trunc', text: l, title: l }); }))));
+ }
+ if (S.undo) msg.appendChild(h('div', { class: 'cfg-undo' }, [h('span', { class: 'cfg-trunc', text: S.undo.label, title: S.undo.label }), h('button', { type: 'button', class: 'cfg-link', text: '撤销', onclick: undoLast, disabled: S.saving })]));
+ if (dirty) msg.appendChild(h('div', { class: 'cfg-scope', text: '待保存:' + scopeText() + '(' + n + ' 处)' }));
if (S.errors.length) {
msg.appendChild(h('ul', { class: 'cfg-savebar-errors' }, S.errors.slice(0, 8).map(function (e) {
var p = locToPath(e.loc);
- return h('li', { class: 'cfg-trunc' }, h('button', { type: 'button', class: 'cfg-link', text: (p || '
') + ':' + e.msg, onclick: function () { focusError(p); } }));
+ return h('li', { class: 'cfg-trunc' }, h('button', { type: 'button', class: 'cfg-link', text: (p ? labelOf(p) : '') + ':' + e.msg, title: p, onclick: function () { focusError(p); } }));
}).concat(S.errors.length > 8 ? [h('li', { text: '…共 ' + S.errors.length + ' 个错误' })] : [])));
}
- add(bar, [msg, btn('放弃修改', discard, '', { disabled: !dirty || S.saving }),
- btn(S.saving ? '保存中…' : '保存 ' + n + ' 个字段(' + k + ' 个 section)', onSave, 'cfg-btn-primary', { disabled: !dirty || S.saving || S.readonly })]);
+ var acts = [];
+ if (S.notice && !dirty) acts.push(btn('关闭', function () { S.notice = null; updateDirty(); }, 'cfg-btn-sm'));
+ if (dirty || S.errors.length) {
+ acts.push(btn('放弃修改', discard, '', { disabled: !dirty || S.saving }));
+ acts.push(btn(S.confirming ? '等待确认…' : S.saving ? '保存中…' : '保存', onSave, 'cfg-btn-primary', { disabled: !dirty || S.saving || S.readonly }));
+ }
+ add(bar, [msg].concat(acts));
+ // 保存栏每次整体重建:原先落在栏内的焦点(通常是「保存」按钮)跟着回来;
+ // 栏里已没有可聚焦控件(如点「关闭」后隐藏)时落到当前激活的 pill,而不是掉回 body
+ if (hadFocus) {
+ var b = bar.querySelector('.cfg-btn-primary') || bar.querySelector('.cfg-btn');
+ if (b && b.focus) b.focus();
+ else if (S.root) { var p = S.root.querySelector('.cfg-pills .range-btn.active'); if (p && p.focus) p.focus(); }
+ }
}
function discard() {
- if (!window.confirm('放弃全部未保存的修改?')) return;
- EDITABLE.forEach(function (s) { S.work[s] = clone(S.base[s]); });
- S.ops = {};
- S.errors = [];
+ askConfirm({ title: '放弃修改?', body: '将丢弃全部未保存的修改,已保存的配置不受影响。', confirmText: '放弃修改', danger: true }, function () {
+ EDITABLE.forEach(function (s) { S.work[s] = clone(S.base[s]); });
+ S.ops = {};
+ S.errors = [];
+ S.undo = null;
+ S.focusTo = function () { return S.root.querySelector('.cfg-pills .range-btn.active'); };
+ rerender();
+ });
+ }
+ // 撤销快照指向工作副本里的位置:重载替换了它所在的 section 就作废
+ function clearUndo(sections) {
+ if (S.undo && (!sections || sections.indexOf(S.undo.section) >= 0)) S.undo = null;
+ }
+ // 单级撤销:只恢复被移除的对象本身并插回原位,不影响其后的其它编辑
+ function undoLast() {
+ var u = S.undo;
+ if (!u || S.saving) return; // 保存进行中载荷已定稿,此时撤销会被随后的重载覆盖
+ S.undo = null;
+ if (u.kind === 'row') {
+ var a = getIn(S.work, u.parts);
+ if (!Array.isArray(a)) { a = []; setIn(S.work, u.parts, a); }
+ a.splice(Math.min(u.index, a.length), 0, clone(u.item));
+ if (typeof S.expanded[u.key] === 'number' && S.expanded[u.key] >= u.index) S.expanded[u.key] += 1; // 展开行跟着后移
+ S.focusTo = function () {
+ var rs = S.root.querySelectorAll('.ft-table-wrap[data-path="' + u.parts.join('.') + '"] .cfg-list-row');
+ return rs[u.index] ? rs[u.index].querySelector('.cfg-btn-sm') : false;
+ };
+ } else if (u.kind === 'fn') {
+ u.run();
+ S.focusTo = function () { return S.root.querySelector('.cfg-row[data-path="' + u.path + '"] [data-map-add]'); };
+ } else if (u.kind === 'vendor') {
+ if (findVendor(S.work.vendors, u.vendor.vendor)) { changed(); rerender(); return; } // 期间已重新添加,不再插入
+ S.work.vendors = S.work.vendors || [];
+ S.work.vendors.splice(Math.min(u.index, S.work.vendors.length), 0, clone(u.vendor));
+ if (u.tierIndex >= 0 && Array.isArray(S.work.tiers) && S.work.tiers.indexOf(u.vendor.vendor) < 0) S.work.tiers.splice(Math.min(u.tierIndex, S.work.tiers.length), 0, u.vendor.vendor);
+ S.focusTo = function () { return S.root.querySelector('.cfg-subpills .range-btn[data-vendor="' + u.vendor.vendor + '"]'); };
+ }
+ changed();
rerender();
}
function focusError(path) {
@@ -1116,25 +1490,28 @@
function fetchStatus() {
return fetch('/api/status', { cache: 'no-store' }).then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; });
}
- function runtimeLines(status) {
- if (!S.view.apply_supported) return ['当前实例不支持在线生效:保存后需重启,运行时状态不受影响。'];
- var tiers = (status && status.tiers) || [], lines = [];
- var names = function (pred) { return tiers.filter(pred).map(function (t) { return t.name; }); };
- var cb = names(function (t) { return t.circuit_breaker && t.circuit_breaker.state && t.circuit_breaker.state !== 'closed'; });
- var rl = names(function (t) { return t.rate_limit && t.rate_limit.is_rate_limited; });
- var qx = names(function (t) { return [t.quota_guard, t.weekly_quota_guard].some(function (q) { return q && q.state === 'quota_exceeded'; }); });
- if (status && typeof status.in_flight === 'number') lines.push('进行中的请求:' + status.in_flight + ' 个(在旧实例上继续完成)');
- if (cb.length) lines.push('熔断状态将重置:' + cb.join('、'));
- if (rl.length) lines.push('限流状态将重置:' + rl.join('、'));
- if (qx.length) lines.push('配额超限状态按用量数据库重建:' + qx.join('、'));
- lines.push('运行时调整的并发上限恢复为配置值;配额窗口按用量数据库重建。');
- var running = S.view.running && S.view.running.tiers;
- if (Array.isArray(running) && !deepEqual(running, enabledChain())) {
- lines.push('运行中的优先级(含 Overview 拖拽)与保存的 tiers 不同,保存后以 tiers 为准。');
+ // 具体路径 → 注册表 spec(vendors 的 vendor 段与列表下标泛化为 *)
+ function specFor(path) {
+ var parts = String(path).split('.');
+ if (S.specMap[path]) return S.specMap[path];
+ for (var i = 1; i < parts.length; i++) {
+ if (parts[0] === 'vendors' ? i !== 1 : !/^\d+$/.test(parts[i])) continue;
+ var hit = S.specMap[parts.slice(0, i).concat(['*'], parts.slice(i + 1)).join('.')];
+ if (hit) return hit;
}
- return lines;
+ return null;
}
- function confirmSave(payload, status) {
+ function labelOf(path) {
+ var parts = String(path).split('.'), sp = specFor(path);
+ if (parts[0] === 'vendors') return (sp ? sp.label : parts[parts.length - 1]) + '(' + parts[1] + ')';
+ return sp ? sp.label : parts[parts.length - 1];
+ }
+ function rowTitleOf(sec, row) {
+ var ks = ROW_KEY[sec] || [], sub = sec.split('.').slice(1);
+ return (sub.length ? sub.join(' › ') + ' › ' : '') + (ks.length ? ks.map(function (k) { return String(row[k]); }).join(' / ') : fmtVal(row));
+ }
+ // 保存后果清单:每一项都来自可预判的运行时状态或本次载荷;非空才弹确认框
+ function saveImpactList(payload, status) {
var secretFields = {};
S.specs.forEach(function (sp) {
if (sp.widget !== 'secret' || !sp.vendors) return;
@@ -1144,26 +1521,85 @@
base: S.base, work: S.work, defaults: S.view.defaults, secrets: S.view.secrets, ops: S.ops, secretFields: secretFields,
targetDefaults: { base_url: dflt('vendors.*.base_url'), token_url: dflt('vendors.*.token_url') },
});
- var blocks = [
- ['修改的 section', Object.keys(payload.sections)],
- ['密钥操作', Object.keys(payload.secret_ops).map(function (p) { return p + ':' + payload.secret_ops[p].op; })],
- ['目标地址已变更,以下密钥将被清空(需重新设置)', cleared],
- ['运行时影响', runtimeLines(status)],
- ].filter(function (b) { return b[1].length; });
- var text = blocks.map(function (b) { return b[0] + ':\n- ' + b[1].join('\n- '); }).join('\n\n');
- if (typeof window.HTMLDialogElement !== 'function') return Promise.resolve(window.confirm('确认保存?\n\n' + text));
- return new Promise(function (resolve) {
- var dlg = h('dialog', { class: 'cfg-dialog', 'aria-label': '确认保存' });
- var close = function (ok) { dlg.close(); dlg.remove(); resolve(ok); };
- add(dlg, [h('div', { class: 'cfg-section-title', text: '确认保存' })].concat(blocks.map(function (b, i) {
- return h('div', { class: 'cfg-dialog-block' + (b[1] === cleared ? ' cfg-dialog-warn' : '') }, [
- h('div', { class: 'cfg-group-title', text: b[0] }),
- h('ul', {}, b[1].map(function (l) { return h('li', { text: l }); })),
- ]);
- }), [h('div', { class: 'cfg-actions' }, [btn('取消', function () { close(false); }), btn('确认保存', function () { close(true); }, 'cfg-btn-primary')])]));
- dlg.addEventListener('cancel', function (e) { e.preventDefault(); close(false); });
- document.body.appendChild(dlg);
- dlg.showModal();
+ return saveImpact({ payload: payload, base: S.base, work: S.work, view: S.view, status: status, cleared: cleared, chain: enabledChain() });
+ }
+ function impactLines(impact, payload) {
+ var l = function (a) { return a.join('、'); };
+ return impact.map(function (it) {
+ if (it.code === 'secrets') return '密钥:' + l(it.paths.map(function (p) { var op = payload.secret_ops[p]; return op.op === 'set' ? '设置 ' + labelOf(p) : op.op === 'clear' ? '清空 ' + labelOf(p) : labelOf(p) + ' 改用环境变量 ' + ((S.view.secrets[p] || {}).default_env || ''); }));
+ if (it.code === 'cleared') return '目标地址已变更,保存后将清空密钥(需重新设置):' + l(it.paths.map(labelOf));
+ if (it.code === 'inflight') return it.n + ' 个请求正在进行,会在旧实例上完成后切到新配置';
+ if (it.code === 'breaker') return '熔断状态将重置:' + l(it.names);
+ if (it.code === 'ratelimit') return '限流状态将重置:' + l(it.names);
+ if (it.code === 'quota') return '配额超限状态将按用量数据库重建:' + l(it.names);
+ if (it.code === 'tiers') return '运行中的优先级与保存的 Tiers 不同,保存后以 Tiers 为准';
+ if (it.code === 'pending') return '上次保存后尚未生效的 section 会一并生效:' + l(it.sections.map(sectionLabel));
+ if (it.code === 'removed') return '移除 vendor(同时移出 Tiers 链路):' + l(it.vendors);
+ return it.code;
+ });
+ }
+ function diffBlock(groups) {
+ var rows = [];
+ groups.forEach(function (g) {
+ rows.push(h('div', { class: 'cfg-diff-group-title', text: g.title }));
+ g.rows.forEach(function (r) {
+ rows.push(h('div', { class: 'cfg-diff-row' }, [h('span', { class: 'cfg-diff-label cfg-trunc', text: r.label, title: r.label }),
+ h('span', { class: 'cfg-diff-val' }, r.added ? [h('ins', { text: '新增' })] : r.removed ? [h('del', { text: '移除' })] : [h('del', { text: r.before }), ' → ', h('ins', { text: r.after })])]));
+ });
+ });
+ var block = h('div', { class: 'cfg-dialog-block cfg-dialog-diff' }, [h('div', { class: 'cfg-group-title', text: '将保存的修改' })]);
+ if (rows.length > 8) block.appendChild(h('details', {}, [h('summary', { text: '共 ' + groups.reduce(function (n, g) { return n + g.rows.length; }, 0) + ' 处,展开查看' })].concat(rows)));
+ else rows.forEach(function (r) { block.appendChild(r); });
+ return block;
+ }
+ // 页面内确认框;不支持