feat(panel): modularize 3-tab preferences, add model context windows, and optimize telemetry

- Refactor Preferences into decoupled General, Structure, and Other tabs with unified settings schema, factory reset, and trajectory cache rebuild endpoints
- Extract standalone widget, metric, and step-table column registries to customize topbar/composer slots, hover popup modules, live overview layout, and step detail columns
- Add bilingual zh-CN/en-US i18n dictionaries, theme accent presets, and font scale controls across Shadow DOM overlay and sidebar views
- Support per-model host-advertised context window rules across App and IDE transports
- Preserve CLEARED step generation timings, memoize per-poll model resolution, optimize LOESS sorted-x fitting, and update bilingual READMEs and test suites
This commit is contained in:
fish
2026-11-15 01:18:29 +09:00
parent ad33e9cc62
commit 18c608ae63
63 changed files with 16614 additions and 5873 deletions
+159 -58
View File
@@ -26,6 +26,7 @@ import {
mergeModelsByDisplayName,
normalizeOrchestratorIdDisplayMode,
} from '../core/formatters.js';
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
import { createSvgIcon } from '../icons/SvgIcon.js';
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js';
@@ -39,15 +40,17 @@ import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
/** 消耗统计顶栏支持的时间范围预设项 */
const TIME_RANGE_OPTIONS = [
{ value: 'today', label: '今天' },
{ value: '24h', label: '1天' },
{ value: '7d', label: '7天' },
{ value: '14d', label: '14天' },
{ value: '30d', label: '30天' },
{ value: 'all', label: '全部' },
{ value: 'custom', label: '自定义' },
];
function getConsumptionTimeRangeOptions() {
return [
{ value: 'today', label: t('cons.rangeToday') },
{ value: '24h', label: t('cons.range24h') },
{ value: '7d', label: t('cons.range7d') },
{ value: '14d', label: t('cons.range14d') },
{ value: '30d', label: t('cons.range30d') },
{ value: 'all', label: t('cons.rangeAll') },
{ value: 'custom', label: t('cons.rangeCustom') },
];
}
export const ConsumptionView = defineComponent({
name: 'ConsumptionView',
@@ -58,9 +61,9 @@ export const ConsumptionView = defineComponent({
let hasUncommittedCustomDraft = false;
const timeFilterSwitch = SegmentedControl({
ariaLabel: '消耗统计时间范围',
ariaLabel: t('cons.rangeAria'),
modelValue: telemetryStore.getState().selectedTimeRange,
options: TIME_RANGE_OPTIONS,
options: getConsumptionTimeRangeOptions(),
onUpdateModelValue: (nextRange) => {
if (nextRange === 'custom') {
const st = telemetryStore.getState();
@@ -95,6 +98,7 @@ export const ConsumptionView = defineComponent({
},
});
const applyCustomBtnLabel = h('span', { text: t('cons.applyFilter') });
const applyCustomBtn = h(
'button',
{
@@ -119,9 +123,10 @@ export const ConsumptionView = defineComponent({
fetchTelemetry({ force: true });
},
},
[createSvgIcon('check', { size: 12 }), h('span', { text: '筛选' })]
[createSvgIcon('check', { size: 12 }), applyCustomBtnLabel]
);
const rangeToSpan = h('span', { className: 'text-muted', text: t('cons.rangeTo') });
const customRangeBar = h(
'div',
{
@@ -131,7 +136,7 @@ export const ConsumptionView = defineComponent({
},
[
startPicker.el,
h('span', { className: 'text-muted', text: '至' }),
rangeToSpan,
endPicker.el,
applyCustomBtn,
]
@@ -140,31 +145,38 @@ export const ConsumptionView = defineComponent({
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' });
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' });
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) });
const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' });
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' });
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '≈ ¥0' });
const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' });
const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '命中 0' });
const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.cacheHitTokens', { tokens: 0 }) });
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' });
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '未命中缓存输入' });
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.uncachedInput') });
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' });
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' });
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.savedCost', { cost: '$0.00' }) });
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' });
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '回复 0 · 思考 0' });
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.replyAndThink', { resp: 0, think: 0 }) });
const overviewSegBar = createFourSegmentBar();
const overviewTitleSpan = h('span', { text: t('cons.overviewTitle') });
const totalTokensLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.totalTokens') });
const estCostLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.estCost') });
const cacheHitRateLabel = h('span', { text: t('cons.cacheHitRate') });
const newInputLabel = h('span', { text: t('cons.newInput') });
const cacheReadLabel = h('span', { text: t('cons.cacheRead') });
const outputUsageLabel = h('span', { text: t('cons.outputUsage') });
const overviewPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header cons-overview-head' }, [
h('span', { className: 'panel-title' }, [
h('span', { text: '用量总览' }),
overviewTitleSpan,
dateSpanBadge,
]),
timeFilterSwitch.el,
@@ -173,17 +185,17 @@ export const ConsumptionView = defineComponent({
h('div', { className: 'cons-box cons-unified-matrix' }, [
h('div', { className: 'cons-split-3' }, [
h('div', { className: 'cons-col' }, [
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token' }),
totalTokensLabel,
h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]),
]),
h('div', { className: 'cons-col is-bordered-col' }, [
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '预估费用' }),
estCostLabel,
h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]),
]),
h('div', { className: 'cons-col is-bordered-col' }, [
h('span', { className: 'legend-left', style: 'font-size: 11px;' }, [
h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [
h('span', { className: 'dot-swatch seg-cached' }),
h('span', { text: '缓存命中率' }),
cacheHitRateLabel,
]),
h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]),
]),
@@ -193,7 +205,7 @@ export const ConsumptionView = defineComponent({
h('div', { className: 'cons-sub-head' }, [
h('span', { className: 'legend-left cons-sub-label' }, [
h('span', { className: 'dot-swatch seg-input' }),
h('span', { text: '新输入' }),
newInputLabel,
]),
inputSharePct,
]),
@@ -204,7 +216,7 @@ export const ConsumptionView = defineComponent({
h('div', { className: 'cons-sub-head' }, [
h('span', { className: 'legend-left cons-sub-label' }, [
h('span', { className: 'dot-swatch seg-cached' }),
h('span', { text: '缓存读取' }),
cacheReadLabel,
]),
cacheSharePct,
]),
@@ -215,7 +227,7 @@ export const ConsumptionView = defineComponent({
h('div', { className: 'cons-sub-head' }, [
h('span', { className: 'legend-left cons-sub-label' }, [
h('span', { className: 'dot-swatch seg-output' }),
h('span', { text: '输出用量' }),
outputUsageLabel,
]),
outputSharePct,
]),
@@ -228,18 +240,19 @@ export const ConsumptionView = defineComponent({
]);
// --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 多刻度时间轴) ---
const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' });
const trendTitleSpan = h('span', { text: t('cons.trendTitle') });
const trendRangeBadge = h('span', { className: 'cons-badge', text: t('cons.allTime') });
const trendGranularityHint = h('span', {
className: 'text-muted text-mono',
style: 'font-size: 10.5px;',
text: '按小时 · 悬停查看明细',
style: 'font-size: var(--fs-sm);',
text: t('cons.trendPointsHintHourly', { points: 0 }),
});
const trendChart = createTrendAreaChart();
const trendPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
h('span', { text: '用量趋势' }),
trendTitleSpan,
trendRangeBadge,
]),
trendGranularityHint,
@@ -248,24 +261,27 @@ export const ConsumptionView = defineComponent({
]);
// --- Section 3: 模型排行列表 ---
const modelsTitleSpan = h('span', { className: 'panel-title', text: t('cons.topModels') });
const modelsListEl = h('div', { className: 'cons-item-list' });
const modelsPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title', text: '模型排行' }),
modelsTitleSpan,
]),
modelsListEl,
]);
// --- Section 4: 客户端来源列表 ---
const sourcesTitleSpan = h('span', { className: 'panel-title', text: t('cons.clientSources') });
const sourcesListEl = h('div', { className: 'cons-item-list' });
const sourcesPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title', text: '客户端来源' }),
sourcesTitleSpan,
]),
sourcesListEl,
]);
// --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) ---
const monthlyTitleSpan = h('span', { className: 'panel-title', text: t('cons.monthlyTitle') });
const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' });
const monthlyCols = Array.from({ length: 12 }, (_, idx) => {
const costText = h('span', { className: 'month-cost text-mono', text: '' });
@@ -280,7 +296,7 @@ export const ConsumptionView = defineComponent({
barIn,
]);
const zeroDot = h('span', { className: 'month-zero-dot' });
const monthLabel = h('span', { className: 'month-label', text: `${idx + 1}月` });
const monthLabel = h('span', { className: 'month-label', text: t('cons.monthLabel', { m: idx + 1 }) });
const tokText = h('span', { className: 'month-tok text-mono', text: '' });
const colEl = h('div', { className: 'month-col' }, [
@@ -303,9 +319,14 @@ export const ConsumptionView = defineComponent({
};
});
const legInputSpan = h('span', { text: t('cons.legInput') });
const legCacheSpan = h('span', { text: t('cons.legCache') });
const legOutputSpan = h('span', { text: t('cons.legOutput') });
const legThinkingSpan = h('span', { text: t('cons.legThinking') });
const monthlyPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title', text: '月度统计' }),
monthlyTitleSpan,
monthlyYearBadge,
]),
h(
@@ -316,19 +337,19 @@ export const ConsumptionView = defineComponent({
h('div', { className: 'monthly-legend' }, [
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-input' }),
h('span', { text: '输入' }),
legInputSpan,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-cached' }),
h('span', { text: '缓存' }),
legCacheSpan,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-output' }),
h('span', { text: '输出' }),
legOutputSpan,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-thinking' }),
h('span', { text: '思考' }),
legThinkingSpan,
]),
]),
]);
@@ -362,6 +383,12 @@ export const ConsumptionView = defineComponent({
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
const segBar = createFourSegmentBar();
const inLbl = h('span', { text: t('cons.footInput') });
const cacheLbl = h('span', { text: t('cons.footCache') });
const outLbl = h('span', { text: t('cons.footOutput') });
const thinkLbl = h('span', { text: t('cons.footThinking') });
const callsLbl = h('span', { text: t('cons.footCalls') });
const inVal = h('strong', { className: 'text-mono' });
const cacheVal = h('strong', { className: 'text-mono' });
const outVal = h('strong', { className: 'text-mono' });
@@ -381,26 +408,26 @@ export const ConsumptionView = defineComponent({
h('div', { className: 'cons-item-foot' }, [
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-input' }),
h('span', { text: '输入 ' }),
inLbl,
inVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-cached' }),
h('span', { text: '缓存 ' }),
cacheLbl,
cacheVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-output' }),
h('span', { text: '输出 ' }),
outLbl,
outVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { className: 'dot-swatch seg-thinking' }),
h('span', { text: '思考 ' }),
thinkLbl,
thinkVal,
]),
h('span', { className: 'legend-left' }, [
h('span', { text: '调用 ' }),
callsLbl,
callsVal,
]),
]),
@@ -408,7 +435,23 @@ export const ConsumptionView = defineComponent({
return {
el: rowEl,
refs: { nameEl, pctBadge, totalTokEl, costEl, segBar, inVal, cacheVal, outVal, thinkVal, callsVal },
refs: {
nameEl,
pctBadge,
totalTokEl,
costEl,
segBar,
inLbl,
cacheLbl,
outLbl,
thinkLbl,
callsLbl,
inVal,
cacheVal,
outVal,
thinkVal,
callsVal,
},
};
}
@@ -416,6 +459,11 @@ export const ConsumptionView = defineComponent({
* 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。
*/
function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) {
patchText(refs.inLbl, t('cons.footInput'));
patchText(refs.cacheLbl, t('cons.footCache'));
patchText(refs.outLbl, t('cons.footOutput'));
patchText(refs.thinkLbl, t('cons.footThinking'));
patchText(refs.callsLbl, t('cons.footCalls'));
const displayLabel = item.label || item.name || item.shortName || '—';
patchText(refs.nameEl, displayLabel);
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
@@ -492,12 +540,12 @@ export const ConsumptionView = defineComponent({
const savedCostUsd = Number(acct.savedCostUsd || 0);
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
patchText(heroTotalCalls, t('cons.callsCount', { calls: acct.calls || 0 }));
patchText(heroCostUsd, formatUsd(costUsd));
patchText(heroCostCny, formatCnyApprox(costUsd));
patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`);
patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`);
patchText(cacheTokensEl, t('cons.cacheHitTokens', { tokens: formatTokensPrecise(cacheTokens) }));
let inPct = 0;
let cachePct = 0;
@@ -523,20 +571,25 @@ export const ConsumptionView = defineComponent({
patchText(inputSharePct, `${inPct}%`);
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
patchText(inputSubText, '未命中缓存输入');
patchText(inputSubText, t('cons.uncachedInput'));
patchText(cacheSharePct, `${cachePct}%`);
patchText(cacheMainTokens, formatTokensPrecise(cacheTokens));
patchText(
cacheSubText,
`节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}`
t('cons.savedCost', {
cost: formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 }),
})
);
patchText(outputSharePct, `${outPct}%`);
patchText(outputMainTokens, formatTokensPrecise(outputTokens));
patchText(
outputSubText,
`回复 ${formatTokensPrecise(responseTokens)} · 思考 ${formatTokensPrecise(thinkingTokens)}`
t('cons.replyAndThink', {
resp: formatTokensPrecise(responseTokens),
think: formatTokensPrecise(thinkingTokens),
})
);
overviewSegBar.update({
@@ -547,7 +600,11 @@ export const ConsumptionView = defineComponent({
});
// 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与粒度提示
patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间');
const rangeBadgeText = isEnglishLocale()
? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label ||
t('cons.allTime')
: preset?.label || rangeInfo.label || t('cons.allTime');
patchText(trendRangeBadge, rangeBadgeText);
const trendSeries = cons.trendSeries || [];
const isHourlyTrend =
trendSeries[0]?.granularity === 'hour' ||
@@ -556,12 +613,15 @@ export const ConsumptionView = defineComponent({
patchText(
trendGranularityHint,
isHeatmapTrend
? `按日 (${trendSeries.length}天) · 悬停查看`
: `${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看`
? t('cons.trendHeatmapHint', { days: trendSeries.length })
: isHourlyTrend
? t('cons.trendPointsHintHourly', { points: trendSeries.length || 0 })
: t('cons.trendPointsHintDaily', { points: trendSeries.length || 0 })
);
trendChart.update(trendSeries);
// 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账)
const localeSig = i18nStore.getState().locale;
const displaySettings = {
showUpstreamModel: Boolean(slice.showUpstreamModel),
orchestratorIdMode: slice.orchestratorIdMode,
@@ -574,7 +634,7 @@ export const ConsumptionView = defineComponent({
patchKeyedList(modelsListEl, models, {
keyFn: (m) => m.displayText || m.label || m.shortName,
sigFn: (m) =>
`${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
`${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
createRow: createBreakdownItemRow,
updateRow: (refs, m) =>
updateBreakdownItemRow(
@@ -590,7 +650,7 @@ export const ConsumptionView = defineComponent({
const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0);
patchKeyedList(sourcesListEl, sources, {
keyFn: (s) => s.name,
sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`,
sigFn: (s) => `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`,
createRow: createBreakdownItemRow,
updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true),
});
@@ -679,9 +739,50 @@ export const ConsumptionView = defineComponent({
}
);
function syncStaticLocaleLabels() {
timeFilterSwitch.setProps({
ariaLabel: t('cons.rangeAria'),
options: getConsumptionTimeRangeOptions(),
});
patchText(applyCustomBtnLabel, t('cons.applyFilter'));
patchText(rangeToSpan, t('cons.rangeTo'));
patchText(overviewTitleSpan, t('cons.overviewTitle'));
patchText(totalTokensLabel, t('cons.totalTokens'));
patchText(estCostLabel, t('cons.estCost'));
patchText(cacheHitRateLabel, t('cons.cacheHitRate'));
patchText(newInputLabel, t('cons.newInput'));
patchText(cacheReadLabel, t('cons.cacheRead'));
patchText(outputUsageLabel, t('cons.outputUsage'));
patchText(trendTitleSpan, t('cons.trendTitle'));
patchText(modelsTitleSpan, t('cons.topModels'));
patchText(sourcesTitleSpan, t('cons.clientSources'));
patchText(monthlyTitleSpan, t('cons.monthlyTitle'));
for (let i = 0; i < 12; i++) {
patchText(monthlyCols[i].monthLabel, t('cons.monthLabel', { m: i + 1 }));
}
patchText(legInputSpan, t('cons.legInput'));
patchText(legCacheSpan, t('cons.legCache'));
patchText(legOutputSpan, t('cons.legOutput'));
patchText(legThinkingSpan, t('cons.legThinking'));
}
const unsubI18n = i18nStore.subscribe(
(st) => st.locale,
() => {
syncStaticLocaleLabels();
if (uiStore.getState().activeView === 'consumption' && latestSlice) {
isDirty = false;
renderConsumptionData(latestSlice);
} else {
isDirty = true;
}
}
);
onCleanup(() => {
unsub();
unsubView();
unsubI18n();
trendChart.destroy?.();
timeFilterSwitch.destroy();
startPicker.destroy();
File diff suppressed because it is too large Load Diff
+116 -642
View File
@@ -1,695 +1,169 @@
/**
* @fileoverview View 4: SettingsView (系统设置视图).
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)、模型名称格式(精简代号 / 原始模型 ID)与 Orchestrator 系列 ID 格式;
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
* @fileoverview View 4: Modular 3-Tab `SettingsView.js` ("常规" / "结构" / "其他").
* Orchestrates `SettingsGeneralTab`, `SettingsStructureTab`, and `SettingsOtherTab`
* with top sub-navigation and a shared `CustomScrollbar` viewport.
*/
import { defineComponent } from '../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
import { createSvgIcon } from '../icons/SvgIcon.js';
import {
DEFAULT_CLIENT_TOPBAR_SLOTS,
normalizeClientOrchestratorIdMode,
normalizeClientTopbarSlots,
normalizeClientUpdateMode,
normalizeClientWindowMountMode,
saveSettingsPatch,
telemetryStore,
triggerCloudSync,
triggerPluginUpdate,
} from '../store/telemetryStore.js';
import { h, patchAttr } from '../core/domPatch.js';
import { i18nStore, t } from '../i18n/index.js';
import { telemetryStore } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { CustomSelect } from '../components/ui/CustomSelect.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
/** 步骤明细表中的模型名称显示方式可选项 */
const STEP_MODEL_DISPLAY_OPTIONS = [
{ value: 'short', label: '精简代号 (如 argon-4-high)' },
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
];
/** Orchestrator 系列模型 ID 显示方式可选项(独立于普通模型名称格式) */
const ORCHESTRATOR_ID_DISPLAY_OPTIONS = [
{ value: 'compact', label: '精简代号 (如 orchestrator-argon)' },
{ value: 'full', label: '原始完整 ID (如 gemini-pro-orchestrator)' },
];
/** 面板挂载模式可选项(顶部栏 + 侧边栏 / 输入框 + 侧边栏 / 仅侧边栏) */
const WINDOW_MOUNT_OPTIONS = [
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
{ value: 'composer', label: '输入框挂载 (输入框 + 侧边栏)' },
{ value: 'sidebar', label: '仅侧边栏' },
];
/** 顶栏左侧实时运行会话入口显隐选项 */
const TOPBAR_MULTI_TOGGLE_OPTIONS = [
{ value: 'show', label: '显示' },
{ value: 'hide', label: '隐藏' },
];
/** 顶栏右侧精简胶囊三槽位可选指标项 */
const TOPBAR_SLOT_OPTIONS = [
{ value: 'context', label: '上下文占用 (%)' },
{ value: 'tps', label: '输出速度 (TPS)' },
{ value: 'ttft', label: '首字延迟 (TTFT)' },
{ value: 'cost', label: '本次费用 ($)' },
{ value: 'quota_auto', label: '自动紧俏额度' },
{ value: 'gemini_5h', label: 'Gemini 5h 额度' },
{ value: 'gemini_weekly', label: 'Gemini 周额度' },
{ value: 'claude_5h', label: 'Claude 5h 额度' },
{ value: 'claude_weekly', label: 'Claude 周额度' },
{ value: 'none', label: '不显示' },
];
/** 插件版本更新策略可选项(默认仅提示新版本、手动更新) */
const AUTO_UPDATE_OPTIONS = [
{ value: 'manual', label: '仅提示新版本,手动更新' },
{ value: 'auto', label: '自动更新' },
{ value: 'off', label: '关闭更新' },
];
/**
* 格式化云端价格目录的最近同步时间或版本日期文本。
*/
function formatSyncTimeText(tsMs, updatedAt) {
if (Number(tsMs) > 0) {
const d = new Date(Number(tsMs));
const pad = (n) => String(n).padStart(2, '0');
return `更新于 ${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
if (updatedAt) {
return `发布于 ${String(updatedAt).slice(0, 10)}`;
}
return '默认价格';
function getSettingsSubTabOptions() {
return [
{ value: 'general', label: t('settings.subTab.general') },
{ value: 'structure', label: t('settings.subTab.structure') },
{ value: 'other', label: t('settings.subTab.other') },
];
}
export const SettingsView = defineComponent({
name: 'SettingsView',
setup({ onCleanup }) {
let draftShowUpstreamModel = false;
let draftOrchestratorIdMode = 'compact';
let draftPluginUpdateMode = 'manual';
let draftWindowMountMode = 'dual';
let draftEnableWindowOverlay = true;
let draftShowTopbarMulti = true;
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
let statusTimer = null;
let topbarTimer = null;
let cloudTimer = null;
const initialSubTab = uiStore.getState().settingsSubTab || 'general';
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
/** 在常规设置面板右上角展示短暂的保存状态提示 */
function showSaveFeedback(text) {
if (statusTimer) {
clearTimeout(statusTimer);
statusTimer = null;
}
patchText(saveStatusText, text);
if (text === '已保存' || text === '保存失败') {
statusTimer = setTimeout(() => {
statusTimer = null;
patchText(saveStatusText, '');
}, text === '保存失败' ? 2500 : 1500);
}
}
/** 在顶部栏定制面板右上角展示短暂的状态提示 */
function showTopbarFeedback(text, autoClearMs = 1500) {
if (topbarTimer) {
clearTimeout(topbarTimer);
topbarTimer = null;
}
patchText(topbarStatusText, text);
if (autoClearMs > 0) {
topbarTimer = setTimeout(() => {
topbarTimer = null;
patchText(topbarStatusText, '');
}, autoClearMs);
}
}
/** 在云端同步面板右上角展示同步或更新进度提示 */
function showCloudFeedback(text, autoClearMs = 3500) {
if (cloudTimer) {
clearTimeout(cloudTimer);
cloudTimer = null;
}
patchText(cloudStatusMsg, text);
if (autoClearMs > 0) {
cloudTimer = setTimeout(() => {
cloudTimer = null;
patchText(cloudStatusMsg, '');
}, autoClearMs);
}
}
// --- 面板 1:常规设置 ---
const windowMountSelect = CustomSelect({
modelValue: 'dual',
icon: 'dock',
options: WINDOW_MOUNT_OPTIONS,
onUpdateModelValue: async (val) => {
const nextMode = normalizeClientWindowMountMode(val);
const nextEnable = nextMode !== 'sidebar';
draftWindowMountMode = nextMode;
draftEnableWindowOverlay = nextEnable;
windowMountSelect.setValue(nextMode);
showSaveFeedback('保存中…');
try {
await saveSettingsPatch({
windowMountMode: nextMode,
enableWindowOverlay: nextEnable,
});
showSaveFeedback('已保存');
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
showSaveFeedback('保存失败');
}
const subNavSwitch = SegmentedControl({
ariaLabel: t('settings.subTab.aria'),
modelValue: initialSubTab,
options: getSettingsSubTabOptions(),
onUpdateModelValue: (nextSubTab) => {
uiStore.setState({ settingsSubTab: nextSubTab });
},
});
const stepModelSelect = CustomSelect({
modelValue: 'short',
icon: 'table',
options: STEP_MODEL_DISPLAY_OPTIONS,
onUpdateModelValue: async (val) => {
const nextUpstream = val === 'upstream';
draftShowUpstreamModel = nextUpstream;
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
showSaveFeedback('保存中…');
try {
await saveSettingsPatch({
showUpstreamModel: nextUpstream,
});
showSaveFeedback('已保存');
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
showSaveFeedback('保存失败');
}
},
});
const subNavBar = h('div', { className: 'settings-subnav-bar' }, [subNavSwitch.el]);
const orchestratorIdSelect = CustomSelect({
modelValue: 'compact',
icon: 'layers',
options: ORCHESTRATOR_ID_DISPLAY_OPTIONS,
onUpdateModelValue: async (val) => {
const nextMode = normalizeClientOrchestratorIdMode(val);
draftOrchestratorIdMode = nextMode;
orchestratorIdSelect.setValue(nextMode);
showSaveFeedback('保存中…');
try {
await saveSettingsPatch({
orchestratorIdMode: nextMode,
});
showSaveFeedback('已保存');
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
showSaveFeedback('保存失败');
}
},
});
const generalPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('sliders', { size: 13 }),
h('span', { text: '常规设置' }),
]),
saveStatusText,
]),
h('div', { className: 'form-row' }, [
h('span', { className: 'form-label', text: '面板挂载方式' }),
windowMountSelect.el,
]),
h('div', { className: 'form-row' }, [
h('span', { className: 'form-label', text: '模型名称格式' }),
stepModelSelect.el,
]),
h('div', { className: 'form-row' }, [
h('span', { className: 'form-label', text: 'Orchestrator 系列 ID' }),
orchestratorIdSelect.el,
]),
]);
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
const multiSessionToggle = SegmentedControl({
ariaLabel: '实时运行会话开关',
modelValue: 'show',
options: TOPBAR_MULTI_TOGGLE_OPTIONS,
onUpdateModelValue: async (val) => {
const nextShow = val !== 'hide';
draftShowTopbarMulti = nextShow;
syncTopbarControls();
showTopbarFeedback('保存中…', 0);
try {
await saveSettingsPatch({
showTopbarMultiSession: nextShow,
});
showTopbarFeedback('已保存', 1500);
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
showTopbarFeedback('保存失败', 2500);
}
},
});
async function persistTopbarSlots(nextRawSlots, noticeText = '') {
const normalized = normalizeClientTopbarSlots(nextRawSlots);
draftTopbarSlots = normalized;
syncTopbarControls();
showTopbarFeedback(noticeText || '保存中…', 0);
try {
await saveSettingsPatch({
topbarCapsuleSlots: normalized,
});
showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500);
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
showTopbarFeedback('保存失败', 2500);
let viewScrollbar = null;
const refreshScroll = () => {
if (viewScrollbar) {
viewScrollbar.refresh();
}
};
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
function applyActiveSubTab(subTab) {
const target =
subTab === 'structure' || subTab === 'other' ? subTab : 'general';
subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure');
patchAttr(otherTab.el, 'hidden', target !== 'other');
refreshScroll();
}
function handleSlotMetricChange(slotIndex, nextVal) {
const candidate = [...draftTopbarSlots];
candidate[slotIndex] = nextVal;
const wouldAllBeHidden = candidate.every((item) => item === 'none');
void persistTopbarSlots(
candidate,
wouldAllBeHidden ? '至少保留 1 项显示' : ''
);
}
function swapTopbarSlots(idxA, idxB) {
if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return;
const candidate = [...draftTopbarSlots];
const temp = candidate[idxA];
candidate[idxA] = candidate[idxB];
candidate[idxB] = temp;
void persistTopbarSlots(candidate);
}
const slotSelects = [0, 1, 2].map((idx) =>
CustomSelect({
modelValue: draftTopbarSlots[idx],
options: TOPBAR_SLOT_OPTIONS,
onUpdateModelValue: (val) => handleSlotMetricChange(idx, val),
})
);
const slotRows = [0, 1, 2].map((idx) => {
const upBtn = h(
'button',
{
type: 'button',
className: 'slot-move-btn',
disabled: idx === 0,
'aria-label': `槽位 ${idx + 1} 左移`,
title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)',
onClick: (e) => {
e.stopPropagation();
swapTopbarSlots(idx, idx - 1);
},
},
[createSvgIcon('chevron-up', { size: 12 })]
);
const downBtn = h(
'button',
{
type: 'button',
className: 'slot-move-btn',
disabled: idx === 2,
'aria-label': `槽位 ${idx + 1} 右移`,
title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)',
onClick: (e) => {
e.stopPropagation();
swapTopbarSlots(idx, idx + 1);
},
},
[createSvgIcon('chevron-down', { size: 12 })]
);
return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [
h('span', { className: 'slot-index-badge', text: String(idx + 1) }),
slotSelects[idx].el,
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]),
]);
});
const resetTopbarBtn = h(
'button',
{
type: 'button',
className: 'btn-ghost-sm',
disabled: true,
onClick: async () => {
draftShowTopbarMulti = true;
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
syncTopbarControls();
showTopbarFeedback('保存中…', 0);
try {
await saveSettingsPatch({
showTopbarMultiSession: true,
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
});
showTopbarFeedback('已恢复默认', 1600);
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
showTopbarFeedback('保存失败', 2500);
}
},
},
[h('span', { text: '恢复默认' })]
);
function syncTopbarControls() {
multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide');
for (let i = 0; i < 3; i += 1) {
slotSelects[i].setValue(draftTopbarSlots[i]);
}
const isDefault =
draftShowTopbarMulti === true &&
draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] &&
draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] &&
draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2];
patchAttr(resetTopbarBtn, 'disabled', isDefault);
}
const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('dock', { size: 13 }),
h('span', { text: '顶部栏定制' }),
]),
h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]),
]),
h('div', { className: 'settings-inline-row' }, [
h('span', { className: 'form-label', text: '实时运行会话' }),
multiSessionToggle.el,
]),
h('div', { className: 'form-row' }, [
h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }),
h('div', { className: 'topbar-slot-list' }, slotRows),
]),
]);
// --- 面板 3:版本更新面板 ---
const autoUpdateSelect = CustomSelect({
modelValue: 'manual',
icon: 'refresh',
options: AUTO_UPDATE_OPTIONS,
onUpdateModelValue: async (val) => {
const nextMode = normalizeClientUpdateMode(val);
draftPluginUpdateMode = nextMode;
autoUpdateSelect.setValue(nextMode);
if (latestCloudStatus) {
renderCloudStatus(latestCloudStatus);
}
showCloudFeedback('保存中…', 0);
try {
await saveSettingsPatch({
pluginUpdateMode: nextMode,
autoUpdatePlugin: nextMode === 'auto',
});
showCloudFeedback('已保存', 1800);
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
if (latestCloudStatus) {
renderCloudStatus(latestCloudStatus);
}
showCloudFeedback('保存失败', 2500);
}
},
});
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' });
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
const syncPricingBtnText = h('span', { text: '更新价格表' });
const syncPricingBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
patchAttr(syncPricingBtn, 'disabled', true);
patchText(syncPricingBtnText, '更新中…');
showCloudFeedback('正在同步价格表…', 0);
try {
const res = await triggerCloudSync();
const cs = res?.cloudStatus;
if (res?.ok && cs) {
showCloudFeedback(`价格表已更新 (${cs.modelCount} 个模型)`, 3500);
} else {
showCloudFeedback(cs?.lastSyncError || '连接超时,使用本地价格表', 4500);
}
} catch (err) {
showCloudFeedback(err?.message || '同步失败,使用本地价格表', 4500);
} finally {
patchAttr(syncPricingBtn, 'disabled', false);
patchText(syncPricingBtnText, '更新价格表');
}
},
},
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
);
const updatePluginBtnText = h('span', { text: '检查更新' });
const updatePluginBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
patchAttr(updatePluginBtn, 'disabled', true);
try {
if (!latestCloudStatus?.updateAvailable) {
patchText(updatePluginBtnText, '检查中…');
showCloudFeedback('正在检查新版本…', 0);
const syncRes = await triggerCloudSync();
const cs = syncRes?.cloudStatus || latestCloudStatus;
if (cs) {
latestCloudStatus = cs;
renderCloudStatus(cs);
}
if (!syncRes?.ok && cs?.lastSyncError) {
showCloudFeedback(`检查失败:${cs.lastSyncError}`, 5000);
return;
}
if (!cs?.updateAvailable) {
const curVer = cs?.currentPluginVersion || '1.4.4';
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
return;
}
}
patchText(updatePluginBtnText, '更新中…');
showCloudFeedback('正在下载更新…', 0);
const res = await triggerPluginUpdate();
if (res?.cloudStatus) {
latestCloudStatus = res.cloudStatus;
}
if (res?.ok) {
showCloudFeedback(res.message || '更新完成,正在重启面板…', 5000);
} else {
showCloudFeedback(res?.message || '未执行更新', 5500);
}
} catch (err) {
showCloudFeedback(err?.message || '更新失败', 5000);
} finally {
patchAttr(updatePluginBtn, 'disabled', false);
renderCloudStatus(latestCloudStatus);
}
},
},
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
);
const cloudPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('bolt', { size: 13 }),
h('span', { text: '版本更新' }),
]),
cloudStatusMsg,
]),
h('div', { className: 'form-row' }, [
h('span', { className: 'form-label', text: '更新方式' }),
autoUpdateSelect.el,
]),
h('div', { className: 'dual-grid' }, [
h('div', { className: 'matrix-cell' }, [
h('span', { className: 'cell-label', text: '价格表' }),
pricingCountVal,
pricingSyncSub,
]),
h('div', { className: 'matrix-cell' }, [
h('span', { className: 'cell-label', text: '当前版本' }),
versionVal,
versionSub,
]),
]),
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
]);
const settingsInner = h(
'div',
{
style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;',
},
[generalPanel, topbarPanel, cloudPanel]
);
const viewScrollbar = CustomScrollbar({
contentEl: settingsInner,
const contentContainer = h('div', {}, [generalTab.el, structureTab.el, otherTab.el]);
viewScrollbar = CustomScrollbar({
contentEl: contentContainer,
className: 'view-pane',
});
applyActiveSubTab(initialSubTab);
const rootEl = h('div', { className: 'settings-view-root' }, [
subNavBar,
viewScrollbar.el,
]);
let latestSettings = null;
let latestCloudStatus = null;
let latestContextWindowModels = [];
/** 将后端返回的最新设置同步至表单控件 */
function renderSettings(settings) {
if (!settings) return;
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
draftPluginUpdateMode = normalizeClientUpdateMode(
settings.pluginUpdateMode,
settings.autoUpdatePlugin
);
draftWindowMountMode = normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
draftEnableWindowOverlay = draftWindowMountMode !== 'sidebar';
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
windowMountSelect.setValue(draftWindowMountMode);
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
orchestratorIdSelect.setValue(draftOrchestratorIdMode);
autoUpdateSelect.setValue(draftPluginUpdateMode);
syncTopbarControls();
viewScrollbar.refresh();
function syncAllTabs(settings, cloudStatus) {
if (settings) {
generalTab.refs.renderSettings(settings);
structureTab.refs.renderSettings(settings);
otherTab.refs.renderSettings(settings, latestContextWindowModels);
}
if (cloudStatus) {
generalTab.refs.renderCloudStatus(cloudStatus);
}
refreshScroll();
}
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
function renderCloudStatus(cs) {
if (!cs) return;
const srcLabel =
cs.source === 'remote'
? '云端同步'
: cs.source === 'local'
? '本地文件'
: '内置默认';
patchText(pricingCountVal, `${cs.modelCount || 0} 个模型`);
patchText(
pricingSyncSub,
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
);
const curVer = cs.currentPluginVersion || '1.4.4';
const latVer = cs.latestPluginVersion || curVer;
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
patchText(versionVal, `v${curVer}`);
if (cs.updateAvailable && draftPluginUpdateMode !== 'off') {
patchText(versionSub, `可升级至 v${latVer} (${modeTag})`);
patchClasses(versionSub, { 'accent-ok': true });
patchText(updatePluginBtnText, `升级至 v${latVer}`);
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
} else if (draftPluginUpdateMode === 'off') {
patchText(versionSub, `已关闭更新提醒 (${modeTag})`);
patchClasses(versionSub, { 'accent-ok': false });
patchText(updatePluginBtnText, cs.updateAvailable ? `手动升级 v${latVer}` : '检查更新');
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
} else {
patchText(versionSub, `已是最新 (${modeTag})`);
patchClasses(versionSub, { 'accent-ok': false });
patchText(updatePluginBtnText, '检查更新');
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
}
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
}
viewScrollbar.refresh();
}
const unsub = telemetryStore.subscribe(
const unsubTelemetry = telemetryStore.subscribe(
(st) => ({
settings: st.telemetry?.settings,
cloudStatus: st.telemetry?.cloudStatus,
contextWindowModels: st.telemetry?.contextWindowModels,
}),
(slice) => {
latestSettings = slice.settings;
latestCloudStatus = slice.cloudStatus;
renderSettings(slice.settings);
if (uiStore.getState().activeView === 'settings') {
renderCloudStatus(slice.cloudStatus);
latestContextWindowModels = slice.contextWindowModels || [];
if (slice.settings) {
generalTab.refs.renderSettings(slice.settings);
structureTab.refs.renderSettings(slice.settings);
otherTab.refs.renderSettings(slice.settings, latestContextWindowModels);
}
if (uiStore.getState().activeView === 'settings' && slice.cloudStatus) {
generalTab.refs.renderCloudStatus(slice.cloudStatus);
}
refreshScroll();
}
);
const unsubUi = uiStore.subscribe(
(st) => ({
activeView: st.activeView,
settingsSubTab: st.settingsSubTab,
}),
(slice) => {
applyActiveSubTab(slice.settingsSubTab);
if (slice.activeView === 'settings') {
syncAllTabs(latestSettings, latestCloudStatus);
}
}
);
const unsubView = uiStore.subscribe(
(st) => st.activeView,
(activeView) => {
if (activeView === 'settings') {
if (latestSettings) renderSettings(latestSettings);
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
viewScrollbar.refresh();
}
const unsubI18n = i18nStore.subscribe(
(st) => st.locale,
() => {
subNavSwitch.setProps({
modelValue: uiStore.getState().settingsSubTab || 'general',
options: getSettingsSubTabOptions(),
});
generalTab.refs.refreshLabels();
structureTab.refs.refreshLabels();
otherTab.refs.refreshLabels();
refreshScroll();
}
);
onCleanup(() => {
if (statusTimer) clearTimeout(statusTimer);
if (topbarTimer) clearTimeout(topbarTimer);
if (cloudTimer) clearTimeout(cloudTimer);
unsub();
unsubView();
windowMountSelect.destroy();
stepModelSelect.destroy();
orchestratorIdSelect.destroy();
multiSessionToggle.destroy();
for (const sel of slotSelects) {
sel.destroy();
}
autoUpdateSelect.destroy();
unsubTelemetry();
unsubUi();
unsubI18n();
subNavSwitch.destroy();
generalTab.destroy();
structureTab.destroy();
otherTab.destroy();
viewScrollbar.destroy();
});
return {
el: viewScrollbar.el,
el: rootEl,
refs: {
windowMountSelect,
stepModelSelect,
orchestratorIdSelect,
multiSessionToggle,
slotSelects,
resetTopbarBtn,
autoUpdateSelect,
subNavSwitch,
generalTab,
structureTab,
otherTab,
viewScrollbar,
// Convenience aliases for external callers / tests
windowMountSelect: structureTab.refs.windowMountSelect,
multiSessionToggle: structureTab.refs.multiSessionToggle,
topbarSlotsList: structureTab.refs.topbarSlotsList,
stepModelSelect: otherTab.refs.stepModelSelect,
orchestratorIdSelect: otherTab.refs.orchestratorIdSelect,
autoUpdateSelect: generalTab.refs.autoUpdateSelect,
},
};
},
+305 -281
View File
@@ -1,10 +1,8 @@
/**
* @fileoverview View 3: StepsDetailView (步骤明细与总汇总分析视图).
* 提供“按步查看”与“总汇总”双子视图切换:
* - 单步测速表采用 `patchKeyedList` 实现行级 DOM 增量对账与就地复用,支持多代理与多模型复选过滤;
* - 总汇总视图在顶部提供当前会话线性走势图(总Token / 上下文 / TPS / 首字 / 费用)与趋势拟合曲线图(TPS / 首字 / 缓存 / 费用),
* 单模型时自动隐藏模型下拉框,多模型时支持独立多选(趋势拟合勾选多模型时同图绘制多条独立颜色回归曲线对比);
* - 底部以极简高密度模型卡片表达各模型总数据,全链路支持主代理 / 子代理多选汇总筛选。
* - 单步测速表通过 `stepColumnRegistry.js` 动态渲染用户自选的 2..12 个字段列,并支持行级增量对账;
* - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。
*/
import { defineComponent } from '../core/component.js';
@@ -22,12 +20,16 @@ import {
mergeModelsByDisplayName,
normalizeOrchestratorIdDisplayMode,
resolveModelDisplayInfo,
speedReasonText,
} from '../core/formatters.js';
import { createSvgIcon } from '../icons/SvgIcon.js';
import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
import {
DEFAULT_STEP_COLUMN_KEYS,
STEP_COLUMN_REGISTRY,
} from '../registries/stepColumnRegistry.js';
import {
formatAgentLabel,
getAgentBadgeClass,
normalizeClientStepColumns,
resolveScopedConversation,
telemetryStore,
} from '../store/telemetryStore.js';
@@ -44,9 +46,6 @@ import { CustomSelect } from '../components/ui/CustomSelect.js';
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
/**
* 当多选勾选了部分代理子集(>=2 个且非全选)时,动态合并所选代理的步骤列表与模型汇总。
*/
function mergeSelectedAgentUnits(units) {
const combinedSteps = [];
const modelMap = new Map();
@@ -67,7 +66,9 @@ function mergeSelectedAgentUnits(units) {
shortName: m.shortName || gk,
rawModel: m.rawModel || '',
upstreamName: m.upstreamName || m.upstreamModel || '',
upstreamSet: new Set(Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : []),
upstreamSet: new Set(
Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : []
),
calls: 0,
inputTokens: 0,
cacheReadTokens: 0,
@@ -122,7 +123,11 @@ function mergeSelectedAgentUnits(units) {
acc._speedWeightedSum += Number(m.avgTokPerSec) * w;
acc._speedWeight += w;
}
if (m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0) {
if (
m.avgTtftSec != null &&
Number.isFinite(Number(m.avgTtftSec)) &&
Number(m.avgTtftSec) >= 0
) {
const w = Math.max(1, calls || 1);
acc._ttftWeightedSum += Number(m.avgTtftSec) * w;
acc._ttftWeight += w;
@@ -167,6 +172,25 @@ function mergeSelectedAgentUnits(units) {
return { steps: combinedSteps, models: mergedModels };
}
function getLineMetricSwitchOptions() {
return [
{ value: 'totalTokens', label: t('steps.metricTotalTokens') },
{ value: 'context', label: t('steps.metricContext') },
{ value: 'tps', label: t('steps.metricTps') },
{ value: 'ttft', label: t('steps.metricTtft') },
{ value: 'cost', label: t('steps.metricCost') },
];
}
function getFitMetricSwitchOptions() {
return [
{ value: 'tps', label: t('steps.metricTps') },
{ value: 'ttft', label: t('steps.metricTtft') },
{ value: 'cache', label: t('steps.metricCache') },
{ value: 'cost', label: t('steps.metricCost') },
];
}
export const StepsDetailView = defineComponent({
name: 'StepsDetailView',
setup({ onCleanup }) {
@@ -191,17 +215,16 @@ export const StepsDetailView = defineComponent({
}
}
// 明细面板标题栏内嵌代理多选筛选下拉框(单选时与顶栏代理切换条双向同步,支持多代理组合筛选)
const inlineScopeSelect = CustomSelect({
multiple: true,
allValue: 'all',
collapseAll: true,
multiUnit: '代理',
multiUnit: t('steps.unitAgent'),
modelValue: selectedAgentScopes,
icon: 'layers',
placeholder: '全部汇总',
placeholder: t('steps.allAgents'),
className: 'steps-inline-scope-select',
options: [{ value: 'all', label: '全部汇总' }],
options: [{ value: 'all', label: t('steps.allAgents') }],
onUpdateModelValue: (nextScopes) => {
if (!Array.isArray(nextScopes) || nextScopes.length === 0) return;
applyAgentScopesSelection(nextScopes);
@@ -209,16 +232,15 @@ export const StepsDetailView = defineComponent({
});
inlineScopeSelect.el.setAttribute('hidden', '');
// “按步查看”标题栏内嵌模型多选筛选下拉框(仅在多模型且处于“按步查看”时展示)
const stepsModelSelect = CustomSelect({
multiple: true,
allValue: '__all__',
collapseAll: false,
multiUnit: '模型',
multiUnit: t('steps.unitModel'),
modelValue: selectedTableModels,
placeholder: '全部模型',
placeholder: t('steps.allModels'),
className: 'steps-inline-model-select',
options: [{ value: '__all__', label: '全部模型' }],
options: [{ value: '__all__', label: t('steps.allModels') }],
onUpdateModelValue: (nextModels) => {
if (!Array.isArray(nextModels) || nextModels.length === 0) return;
selectedTableModels = nextModels;
@@ -227,34 +249,42 @@ export const StepsDetailView = defineComponent({
});
stepsModelSelect.el.setAttribute('hidden', '');
// 顶部子表分段切换器:在“按步查看”与“总汇总”之间切换
const subTabSwitch = SegmentedControl({
ariaLabel: '明细表视图切换',
ariaLabel: t('steps.title'),
modelValue: uiStore.getState().stepsSubTab,
options: [
{ value: 'steps', label: '按步查看 (0)' },
{ value: 'models', label: '总汇总' },
{ value: 'steps', label: t('steps.tabSteps', { count: 0 }) },
{ value: 'models', label: t('steps.tabModels') },
],
onUpdateModelValue: (nextTab) => {
uiStore.setState({ stepsSubTab: nextTab });
},
});
// --- 子视图 1:单步明细表(步序、模型、吞吐速度、首字延迟、上下文/思考/正文、缓存命中率、单步费用) ---
// --- 子视图 1:单步明细表(动态表头与行内列插槽由 `stepColumnRegistry.js` 驱动) ---
const stepsTheadRow = h('tr');
const stepsTbody = h('tbody');
const stepsTablePane = h('div', { className: 'table-viewport' }, [
function syncTableHeaderColumns(colKeys) {
const locale = getEffectiveLocale();
patchKeyedList(stepsTheadRow, colKeys, {
keyFn: (colKey) => colKey,
sigFn: (colKey) => `${locale}:${colKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel()}`,
createRow: (colKey) => {
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel() });
return { el: th, refs: { th } };
},
updateRow: (refs, colKey) => {
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel());
},
});
}
syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS);
const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [
h('table', { className: 'data-table' }, [
h('thead', {}, [
h('tr', {}, [
h('th', { text: '步序' }),
h('th', { text: '模型' }),
h('th', { text: '速度' }),
h('th', { text: '首字' }),
h('th', { text: '上下文 / 思考 / 正文' }),
h('th', { text: '缓存' }),
h('th', { text: '费用' }),
]),
]),
h('thead', {}, [stepsTheadRow]),
stepsTbody,
]),
]);
@@ -263,26 +293,29 @@ export const StepsDetailView = defineComponent({
className: 'table-scroll-host',
});
// --- 子视图 2:总汇总分析面板(顶部会话线性图 + 顶部趋势拟合图 + 底部极简模型总览) ---
// --- 子视图 2:总汇总分析面板 ---
let selectedLineMetric = 'totalTokens';
let selectedFitMetric = 'tps';
// 拟合模型锁定状态机:进入“总汇总”时默认锚定当前调用模型,停留在视图内期间绝不随轮询跳变
let fitLockedCascadeId = null;
let fitLockedModelKeys = [];
let fitPinnedWhileVisible = false;
let fitUserPicked = false;
const lineSummaryBadge = h('span', { className: 'cons-badge text-mono', text: '0 步' });
const lineTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.lineTitle') });
const lineSummaryBadge = h('span', {
className: 'cons-badge text-mono',
text: t('header.convMetaSteps', { count: 0 }),
});
const lineModelSelect = CustomSelect({
multiple: true,
allValue: '__all__',
collapseAll: false,
multiUnit: '模型',
multiUnit: t('steps.unitModel'),
modelValue: selectedLineModels,
placeholder: '全部模型',
placeholder: t('steps.allModels'),
className: 'sstep-fit-model-select sstep-line-model-select',
options: [{ value: '__all__', label: '全部模型' }],
options: [{ value: '__all__', label: t('steps.allModels') }],
onUpdateModelValue: (nextModels) => {
if (!Array.isArray(nextModels) || nextModels.length === 0) return;
selectedLineModels = nextModels;
@@ -292,15 +325,9 @@ export const StepsDetailView = defineComponent({
lineModelSelect.el.setAttribute('hidden', '');
const lineMetricSwitch = SegmentedControl({
ariaLabel: '会话线性图指标切换',
ariaLabel: t('steps.lineTitle'),
modelValue: selectedLineMetric,
options: [
{ value: 'totalTokens', label: '总Token' },
{ value: 'context', label: '上下文' },
{ value: 'tps', label: 'TPS' },
{ value: 'ttft', label: '首字' },
{ value: 'cost', label: '费用' },
],
options: getLineMetricSwitchOptions(),
onUpdateModelValue: (nextMetric) => {
selectedLineMetric = nextMetric;
if (latestSlice) renderStepsData(latestSlice);
@@ -309,10 +336,7 @@ export const StepsDetailView = defineComponent({
const sessionLineChart = createSessionLineChart();
const sessionLineCard = h('div', { className: 'sstep-card sstep-line-card' }, [
h('div', { className: 'sstep-card-head' }, [
h('div', { className: 'sstep-card-title-group' }, [
h('span', { className: 'sstep-card-title', text: '会话走势' }),
lineSummaryBadge,
]),
h('div', { className: 'sstep-card-title-group' }, [lineTitleEl, lineSummaryBadge]),
h('div', { className: 'sstep-fit-controls' }, [
lineModelSelect.el,
lineMetricSwitch.el,
@@ -321,16 +345,20 @@ export const StepsDetailView = defineComponent({
sessionLineChart.el,
]);
const fitSummaryBadge = h('span', { className: 'cons-badge text-mono', text: '0 样本' });
const fitTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.fitTitle') });
const fitSummaryBadge = h('span', {
className: 'cons-badge text-mono',
text: t('header.convMetaSteps', { count: 0 }),
});
const fitModelSelect = CustomSelect({
multiple: true,
allValue: '__all__',
collapseAll: false,
multiUnit: '模型',
multiUnit: t('steps.unitModel'),
modelValue: ['__all__'],
placeholder: '选择模型',
placeholder: t('steps.selectModel'),
className: 'sstep-fit-model-select',
options: [{ value: '__all__', label: '全部模型' }],
options: [{ value: '__all__', label: t('steps.allModels') }],
onUpdateModelValue: (nextModelKeys) => {
if (!Array.isArray(nextModelKeys) || nextModelKeys.length === 0) return;
fitLockedModelKeys = nextModelKeys;
@@ -342,14 +370,9 @@ export const StepsDetailView = defineComponent({
fitModelSelect.el.setAttribute('hidden', '');
const fitMetricSwitch = SegmentedControl({
ariaLabel: '趋势拟合指标切换',
ariaLabel: t('steps.fitTitle'),
modelValue: selectedFitMetric,
options: [
{ value: 'tps', label: 'TPS' },
{ value: 'ttft', label: '首字' },
{ value: 'cache', label: '缓存' },
{ value: 'cost', label: '费用' },
],
options: getFitMetricSwitchOptions(),
onUpdateModelValue: (nextMetric) => {
selectedFitMetric = nextMetric;
if (latestSlice) renderStepsData(latestSlice);
@@ -358,29 +381,27 @@ export const StepsDetailView = defineComponent({
const modelFitChart = createModelFitChart();
const modelFitCard = h('div', { className: 'sstep-card sstep-fit-card' }, [
h('div', { className: 'sstep-card-head' }, [
h('div', { className: 'sstep-card-title-group' }, [
h('span', { className: 'sstep-card-title', text: '趋势拟合' }),
fitSummaryBadge,
]),
h('div', { className: 'sstep-fit-controls' }, [
fitModelSelect.el,
fitMetricSwitch.el,
]),
h('div', { className: 'sstep-card-title-group' }, [fitTitleEl, fitSummaryBadge]),
h('div', { className: 'sstep-fit-controls' }, [fitModelSelect.el, fitMetricSwitch.el]),
]),
modelFitChart.el,
]);
const modelsSummaryMeta = h('span', { className: 'cons-badge text-mono', text: '0 次' });
const modelsSectionTitleEl = h('span', {
className: 'sstep-card-title',
text: t('steps.modelsTitle'),
});
const modelsSummaryMeta = h('span', {
className: 'cons-badge text-mono',
text: t('cons.callsCount', { calls: 0 }),
});
const modelsEmptyEl = h('div', {
className: 'smodel-empty text-muted',
text: '当前范围暂无模型调用记录',
text: t('steps.modelsEmpty'),
});
const modelsListEl = h('div', { className: 'smodel-list' });
const modelsSummarySection = h('div', { className: 'smodel-section' }, [
h('div', { className: 'smodel-section-head' }, [
h('span', { className: 'sstep-card-title', text: '模型总览' }),
modelsSummaryMeta,
]),
h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]),
modelsEmptyEl,
modelsListEl,
]);
@@ -396,6 +417,7 @@ export const StepsDetailView = defineComponent({
});
modelsScroll.el.setAttribute('hidden', '');
const panelTitleTextEl = h('span', { text: t('steps.title') });
const panelEl = h(
'section',
{
@@ -406,7 +428,7 @@ export const StepsDetailView = defineComponent({
h('div', { className: 'panel-header steps-panel-header' }, [
h('span', { className: 'panel-title steps-panel-title' }, [
createSvgIcon('table', { size: 13 }),
h('span', { text: '调用记录' }),
panelTitleTextEl,
]),
h('div', { className: 'steps-header-controls' }, [
inlineScopeSelect.el,
@@ -424,15 +446,17 @@ export const StepsDetailView = defineComponent({
let latestSlice = null;
let isDirty = false;
/**
* 解析当前会话/代理作用域下的默认活跃调用模型分组键。
*/
function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) {
const activeCand = getStepModelGroupKey({
modelLabel: scopedConv?.activeModelLabel,
modelShort: scopedConv?.activeModelShort,
});
if (activeCand && activeCand !== '模型未知' && availableModelKeys.has(activeCand)) {
if (
activeCand &&
activeCand !== '模型未知' &&
activeCand !== t('fmt.unknownModel') &&
availableModelKeys.has(activeCand)
) {
return activeCand;
}
for (let i = chronoSteps.length - 1; i >= 0; i--) {
@@ -452,9 +476,6 @@ export const StepsDetailView = defineComponent({
return '__all__';
}
/**
* 归一化模型多选列表(支持同时勾选 2..N 个具体模型以独立分色对比,仅在明确点击“全部模型”或无有效项时回到 `['__all__']`)。
*/
function normalizeMultiModelSelection(rawSelection, availableModelKeys) {
if (availableModelKeys.size <= 1) return ['__all__'];
const arr = Array.isArray(rawSelection) ? rawSelection : [];
@@ -464,12 +485,102 @@ export const StepsDetailView = defineComponent({
return valid;
}
/**
* 对单步测速表、顶部会话走势图、顶部趋势拟合图及底部极简模型列表执行增量更新。
*/
function refreshStaticLocaleLabels() {
patchText(panelTitleTextEl, t('steps.title'));
patchText(lineTitleEl, t('steps.lineTitle'));
patchText(fitTitleEl, t('steps.fitTitle'));
patchText(modelsSectionTitleEl, t('steps.modelsTitle'));
patchText(modelsEmptyEl, t('steps.modelsEmpty'));
lineMetricSwitch.setProps({
modelValue: selectedLineMetric,
options: getLineMetricSwitchOptions(),
});
fitMetricSwitch.setProps({
modelValue: selectedFitMetric,
options: getFitMetricSwitchOptions(),
});
const colKeys = normalizeClientStepColumns(latestSlice?.stepTableColumns);
syncTableHeaderColumns(colKeys);
if (!latestSlice) {
subTabSwitch.setProps({
modelValue: uiStore.getState().stepsSubTab,
options: [
{ value: 'steps', label: t('steps.tabSteps', { count: 0 }) },
{ value: 'models', label: t('steps.tabModels') },
],
});
}
}
function renderStepTable(tableSteps, cascadeId, colKeys, locale, {
effectiveScopes,
hasSubagents,
displaySettings,
}) {
const colOrderSig = colKeys.join(',');
const wantedSet = new Set(colKeys);
syncTableHeaderColumns(colKeys);
const cellCtx = {
hasSubagents,
effectiveScopes,
scopeSigKey: effectiveScopes.join(','),
displaySettings,
onSelectAgentScopes: applyAgentScopesSelection,
};
patchKeyedList(stepsTbody, tableSteps, {
keyFn: (st) => `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
sigFn: (st) => {
const parts = colKeys
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
.join('|');
return `${locale}:${colOrderSig}:${parts}`;
},
createRow: () => {
const tr = h('tr');
return {
el: tr,
refs: {
cellMap: new Map(),
colOrderSig: '',
},
};
},
updateRow: (refs, st, _idx, tr) => {
if (refs.colOrderSig !== colOrderSig) {
for (const [oldColKey, entry] of refs.cellMap) {
if (!wantedSet.has(oldColKey)) {
tr.removeChild(entry.td);
refs.cellMap.delete(oldColKey);
}
}
for (const [i, colKey] of colKeys.entries()) {
if (!refs.cellMap.has(colKey)) {
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell());
}
const targetTd = refs.cellMap.get(colKey).td;
const currentTd = tr.children[i] || null;
if (currentTd !== targetTd) {
tr.insertBefore(targetTd, currentTd);
}
}
refs.colOrderSig = colOrderSig;
}
for (const colKey of colKeys) {
const cellEntry = refs.cellMap.get(colKey);
STEP_COLUMN_REGISTRY[colKey].updateCell(cellEntry.refs, st, cellCtx);
}
},
});
}
function renderStepsData(slice) {
if (!slice) return;
const uiSt = uiStore.getState();
const locale = getEffectiveLocale();
const currentCid = String(slice.cascadeId || slice.activeConversation?.cascadeId || '');
if (currentCid !== fitLockedCascadeId) {
@@ -516,23 +627,25 @@ export const StepsDetailView = defineComponent({
const scopeOpts = [
{
value: 'all',
label: '全部汇总',
meta: `${aggregated?.stepCount ?? 0}步`,
label: t('steps.allAgents'),
meta: t('header.convMetaSteps', { count: aggregated?.stepCount ?? 0 }),
},
{
value: 'main',
label: '主代理',
meta: `${mainAgent?.stepCount ?? 0}步`,
label: t('fmt.mainAgent'),
meta: t('header.convMetaSteps', { count: mainAgent?.stepCount ?? 0 }),
},
...subagents.map((s) => ({
value: s.agentId,
label: formatAgentLabel(s),
meta: `${s.stepCount || 0}步`,
meta: t('header.convMetaSteps', { count: s.stepCount || 0 }),
})),
];
inlineScopeSelect.setProps({
modelValue: effectiveScopes,
options: scopeOpts,
placeholder: t('steps.allAgents'),
multiUnit: t('steps.unitAgent'),
});
if (effectiveScopes[0] === 'all') {
@@ -573,8 +686,8 @@ export const StepsDetailView = defineComponent({
orchestratorIdMode: slice.orchestratorIdMode,
};
// 提取当前代理作用域下的时间升序步骤与全量可选模型列表
const showAgentPrefix = isMergedMultiAgents;
const showModels = uiSt.stepsSubTab === 'models';
const chronoSteps = toChronologicalSteps(steps, isMergedMultiAgents);
const stepTtftFallbackMap = new Map();
@@ -584,13 +697,13 @@ export const StepsDetailView = defineComponent({
if (!stepModelOptionMap.has(gk)) {
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
stepModelOptionMap.set(gk, {
label: disp.text.replace(/·压缩\s*$/u, '').trim() || gk,
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk,
calls: 0,
});
}
stepModelOptionMap.get(gk).calls += 1;
if (!st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) {
if (showModels && !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) {
const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 };
prev.sum += Number(st.ttftSec);
prev.count += 1;
@@ -615,8 +728,8 @@ export const StepsDetailView = defineComponent({
});
perModelOptions.push({
value: gk,
label: disp.text.replace(/·压缩\s*$/u, '').trim() || gk,
meta: `${Number(m.calls || 0)}步`,
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk,
meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }),
});
}
for (const [gk, info] of stepModelOptionMap.entries()) {
@@ -629,7 +742,7 @@ export const StepsDetailView = defineComponent({
perModelOptions.push({
value: gk,
label: info.label,
meta: `${info.calls}步`,
meta: t('header.convMetaSteps', { count: info.calls }),
});
}
}
@@ -638,13 +751,13 @@ export const StepsDetailView = defineComponent({
const modelSelectOptions = [
{
value: '__all__',
label: '全部模型',
meta: `${chronoSteps.length}步`,
label: t('steps.allModels'),
meta: t('header.convMetaSteps', { count: steps.length }),
},
...perModelOptions,
];
// 1. “按步查看”模型多选过滤与表格增量对账
// 1. “按步查看”动态列头同步与表格行级增量对账
selectedTableModels = normalizeMultiModelSelection(
selectedTableModels,
availableModelKeys
@@ -655,6 +768,8 @@ export const StepsDetailView = defineComponent({
stepsModelSelect.setProps({
modelValue: selectedTableModels,
options: modelSelectOptions,
placeholder: t('steps.allModels'),
multiUnit: t('steps.unitModel'),
});
if (!showStepsModelFilter) stepsModelSelect.close();
} else {
@@ -670,143 +785,64 @@ export const StepsDetailView = defineComponent({
const stepsTabLabel =
tableSteps.length !== steps.length
? `按步查看 (${tableSteps.length}/${steps.length})`
: `按步查看 (${steps.length})`;
? t('steps.tabStepsFiltered', {
filtered: tableSteps.length,
total: steps.length,
})
: t('steps.tabSteps', { count: steps.length });
subTabSwitch.setProps({
options: [
{ value: 'steps', label: stepsTabLabel },
{ value: 'models', label: '总汇总' },
{ value: 'models', label: t('steps.tabModels') },
],
});
const scopeSigKey = effectiveScopes.join(',');
patchKeyedList(stepsTbody, tableSteps, {
keyFn: (st) => `${st.agentCascadeId || slice.cascadeId || 'conv'}-${st.stepIndex}`,
sigFn: (st) => {
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '—' });
const outTok = Math.max(0, Number(st.outputTokens || 0));
const thinkTok = Math.max(0, Number(st.thinkingTokens || 0));
const respTok =
st.responseTokens != null
? Math.max(0, Number(st.responseTokens))
: Math.max(0, outTok - thinkTok);
return `${hasSubagents}:${scopeSigKey}:${st.agentId || 'main'}:${st.stepIndex}:${disp.text}:${disp.title}:${st.tokPerSec}:${st.ttftSec}:${st.contextTokens}:${outTok}:${thinkTok}:${respTok}:${st.cacheHitPct}:${st.costUsd}:${st.selectedSpeedReason}`;
},
createRow: () => {
const agentBadgeEl = h('span', {
className: 'agent-badge is-clickable',
hidden: true,
style: 'margin-right: 4px;',
});
const stepNumText = h('span');
const tdStep = h('td', {}, [agentBadgeEl, stepNumText]);
if (!showModels) {
const colKeys = normalizeClientStepColumns(slice.stepTableColumns);
renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, {
effectiveScopes,
hasSubagents,
displaySettings,
});
stepsScroll.refresh();
}
const tdModel = h('td', {
style: 'max-width: 120px; overflow: hidden; text-overflow: ellipsis;',
});
const speedMain = h('strong', {
className: 'cell-value accent-speed',
style: 'font-size: 11px;',
});
const speedReason = h('div', { className: 'text-muted', style: 'font-size: 9.5px;' });
const tdSpeed = h('td', {}, [speedMain, speedReason]);
const tdTtft = h('td');
const tdCtx = h('td');
const tdCache = h('td', {
className: 'cell-value accent-ok',
style: 'font-size: 11px;',
});
const tdCost = h('td', { style: 'font-weight: 600;' });
const tr = h('tr', {}, [tdStep, tdModel, tdSpeed, tdTtft, tdCtx, tdCache, tdCost]);
return {
el: tr,
refs: {
agentBadgeEl,
stepNumText,
tdModel,
speedMain,
speedReason,
tdTtft,
tdCtx,
tdCache,
tdCost,
},
};
},
updateRow: (refs, st) => {
patchAttr(refs.agentBadgeEl, 'hidden', !hasSubagents);
if (hasSubagents) {
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
patchAttr(refs.agentBadgeEl, 'class', `agent-badge is-clickable ${badgeCls}`);
patchText(refs.agentBadgeEl, st.agentBadge || (st.isSubagent ? '子' : '主'));
const targetScope = st.agentId || 'main';
const isSoleTarget =
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
patchAttr(
refs.agentBadgeEl,
'title',
isSoleTarget
? '点击切回全部汇总'
: `点击仅过滤查看 ${st.agentLabel || '该代理'}(按住 Ctrl/Shift 可加减多选)`
);
refs.agentBadgeEl.onclick = (e) => {
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
const next = effectiveScopes.includes(targetScope)
? effectiveScopes.filter((id) => id !== targetScope)
: [...effectiveScopes, targetScope];
applyAgentScopesSelection(next.length > 0 ? next : ['all']);
} else {
applyAgentScopesSelection(isSoleTarget ? ['all'] : [targetScope]);
}
};
}
patchText(refs.stepNumText, `#${Number(st.stepIndex)}`);
const modelDisplay = resolveModelDisplayInfo(st, displaySettings, { fallback: '—' });
patchText(refs.tdModel, modelDisplay.text);
patchAttr(refs.tdModel, 'title', modelDisplay.title);
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
const reason = speedReasonText(st.selectedSpeedReason);
patchText(refs.speedReason, reason);
patchAttr(refs.speedReason, 'hidden', !reason);
patchText(refs.tdTtft, formatMetric(st.ttftSec, 's'));
const outTok = Math.max(0, Number(st.outputTokens || 0));
const thinkTok = Math.max(0, Number(st.thinkingTokens || 0));
const respTok =
st.responseTokens != null
? Math.max(0, Number(st.responseTokens))
: Math.max(0, outTok - thinkTok);
patchText(
refs.tdCtx,
`${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}`
);
patchAttr(
refs.tdCtx,
'title',
`上下文 ${Math.round(Number(st.contextTokens || 0))} · 思考 ${Math.round(thinkTok)} · 正文 ${Math.round(respTok)}`
);
patchText(refs.tdCache, `${Number(st.cacheHitPct ?? 0)}%`);
const costVal = st.costUsd;
patchText(refs.tdCost, formatUsd(costVal, { precise: true }));
patchClasses(refs.tdCost, { 'accent-speed': costVal >= 0.15 });
},
});
// 2. 顶部“会话走势”多选模型对比与图表更新(单模型时隐藏下拉框)
// 2. 顶部“会话走势”更新
selectedLineModels = normalizeMultiModelSelection(
selectedLineModels,
availableModelKeys
);
// 3. 顶部“趋势拟合”模型锁定随当前会话与代理范围更新。
const defaultActiveModelKey = resolveDefaultActiveModelKey(
activeModelSource,
chronoSteps,
models,
availableModelKeys
);
const sanitizedLocked = fitLockedModelKeys.includes('__all__')
? ['__all__']
: Array.from(new Set(fitLockedModelKeys.filter((k) => availableModelKeys.has(k))));
if (!showModels) {
fitPinnedWhileVisible = false;
}
if ((!fitPinnedWhileVisible && !fitUserPicked) || sanitizedLocked.length === 0) {
fitLockedModelKeys = [defaultActiveModelKey];
} else {
fitLockedModelKeys = sanitizedLocked;
}
if (!showModels) return;
if (availableModelKeys.size > 0) fitPinnedWhileVisible = true;
patchAttr(lineModelSelect.el, 'hidden', !hasMultipleModels);
if (hasMultipleModels) {
lineModelSelect.setProps({
modelValue: selectedLineModels,
options: modelSelectOptions,
placeholder: t('steps.allModels'),
multiUnit: t('steps.unitModel'),
});
} else {
lineModelSelect.close();
@@ -823,46 +859,6 @@ export const StepsDetailView = defineComponent({
});
patchText(lineSummaryBadge, lineRes.summaryBadge);
// 3. 顶部“趋势拟合”多选模型对比与锁定状态机更新(单模型时隐藏下拉框)
const defaultActiveModelKey = resolveDefaultActiveModelKey(
activeModelSource,
chronoSteps,
models,
availableModelKeys
);
const sanitizeFitSelection = (keys) => {
if (!Array.isArray(keys) || keys.length === 0) return [];
if (keys.includes('__all__')) return ['__all__'];
return Array.from(new Set(keys.filter((k) => availableModelKeys.has(k))));
};
const isModelsViewVisible =
uiSt.activeView === 'steps' && uiSt.stepsSubTab === 'models';
const sanitizedLocked = sanitizeFitSelection(fitLockedModelKeys);
if (!isModelsViewVisible) {
fitPinnedWhileVisible = false;
if (!fitUserPicked || sanitizedLocked.length === 0) {
fitLockedModelKeys = [defaultActiveModelKey];
} else {
fitLockedModelKeys = sanitizedLocked;
}
} else if (!fitPinnedWhileVisible) {
if (!fitUserPicked || sanitizedLocked.length === 0) {
fitLockedModelKeys = [defaultActiveModelKey];
} else {
fitLockedModelKeys = sanitizedLocked;
}
if (availableModelKeys.size > 0) {
fitPinnedWhileVisible = true;
}
} else if (sanitizedLocked.length === 0) {
fitLockedModelKeys = [defaultActiveModelKey];
} else {
fitLockedModelKeys = sanitizedLocked;
}
const effectiveFitModelKeys =
availableModelKeys.size === 0
? ['__all__']
@@ -877,6 +873,8 @@ export const StepsDetailView = defineComponent({
fitModelSelect.setProps({
modelValue: effectiveFitModelKeys,
options: modelSelectOptions,
placeholder: t('steps.selectModel'),
multiUnit: t('steps.unitModel'),
});
} else {
fitModelSelect.close();
@@ -893,7 +891,7 @@ export const StepsDetailView = defineComponent({
});
patchText(fitSummaryBadge, fitRes.summaryBadge);
// 4. 极简模型总览列表增量对账(按最终展示名去重归并,一卡表达调用、Token 4 段占比、均速/首字/缓存与费用)
// 4. 极简模型总览列表增量对账
const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' });
let sumCalls = 0;
let sumTokens = 0;
@@ -909,13 +907,16 @@ export const StepsDetailView = defineComponent({
}
if (displayModels.length === 0) {
patchText(modelsSummaryMeta, '0 次');
patchText(modelsSummaryMeta, t('cons.callsCount', { calls: 0 }));
} else {
const modelCountPart = displayModels.length > 1 ? `${displayModels.length} 模型 · ` : '';
const modelCountPart =
displayModels.length > 1
? t('steps.modelsSummaryPrefix', { count: displayModels.length })
: '';
const isAllUnpricedSum = sumCalls > 0 && sumUnpriced >= sumCalls && !(sumCost > 0);
patchText(
modelsSummaryMeta,
`${modelCountPart}${sumCalls} 次 · ${formatTokens(sumTokens)} · ${formatUsd(
`${modelCountPart}${t('cons.callsCount', { calls: sumCalls })} · ${formatTokens(sumTokens)} · ${formatUsd(
isAllUnpricedSum ? null : sumCost,
{
precise: sumCost > 0 && sumCost < 0.1,
@@ -946,7 +947,7 @@ export const StepsDetailView = defineComponent({
: [gk];
const isActiveFit =
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
return `${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`;
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`;
},
createRow: () => {
const nameEl = h('strong', { className: 'smodel-name' });
@@ -977,7 +978,9 @@ export const StepsDetailView = defineComponent({
const gk = getStepModelGroupKey(m);
const cardGroupKeys =
Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0
? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl }))))
? Array.from(
new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl })))
)
: [gk];
const dispText = m.displayText || '—';
const dispTitle = m.displayTitle || dispText;
@@ -988,7 +991,9 @@ export const StepsDetailView = defineComponent({
const callSharePct = sumCalls > 0 ? Math.round((calls / sumCalls) * 100) : 0;
patchText(
refs.callsPillEl,
displayModels.length > 1 ? `${calls}次 · ${callSharePct}%` : `${calls}次`
displayModels.length > 1
? t('steps.modelCallsShare', { calls, pct: callSharePct })
: t('steps.modelCallsOnly', { calls })
);
const inTok = Math.max(0, Number(m.inputTokens || 0));
@@ -1033,11 +1038,20 @@ export const StepsDetailView = defineComponent({
patchText(
refs.perfEl,
`均速 ${formatMetric(m.avgTokPerSec, ' tok/s')} · 首字 ${formatMetric(resolvedAvgTtft, 's')} · 缓存 ${resolvedCachePct}%`
t('steps.modelPerfFoot', {
tps: formatMetric(m.avgTokPerSec, ' tok/s'),
ttft: formatMetric(resolvedAvgTtft, 's'),
cache: resolvedCachePct,
})
);
patchText(
refs.splitEl,
`入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 思 ${formatTokens(thinkTok)} · 正 ${formatTokens(respTok)}`
t('steps.modelSplitFoot', {
inTok: formatTokens(inTok),
cacheTok: formatTokens(cacheTok),
thinkTok: formatTokens(thinkTok),
respTok: formatTokens(respTok),
})
);
const isActiveFit =
@@ -1049,8 +1063,8 @@ export const StepsDetailView = defineComponent({
!hasMultipleModels
? dispTitle
: isActiveFit
? `${dispTitle}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)`
: `点击在上方拟合图查看 ${dispText}(按住 Ctrl/Shift 点击可多选同图对比)`
? t('steps.fitActiveCardTitle', { title: dispTitle })
: t('steps.fitInactiveCardTitle', { text: dispText })
);
cardEl.onclick = (e) => {
if (!hasMultipleModels) return;
@@ -1079,11 +1093,7 @@ export const StepsDetailView = defineComponent({
},
});
if (uiSt.stepsSubTab === 'models') {
modelsScroll.refresh();
} else {
stepsScroll.refresh();
}
modelsScroll.refresh();
}
const unsubUi = uiStore.subscribe(
@@ -1108,11 +1118,11 @@ export const StepsDetailView = defineComponent({
cascadeId: st.telemetry?.activeConversation?.cascadeId,
recentSteps: st.telemetry?.activeConversation?.recentSteps,
sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown,
modelBreakdown: st.telemetry?.modelBreakdown,
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
st.telemetry?.settings?.orchestratorIdMode
),
stepTableColumns: st.telemetry?.settings?.stepTableColumns,
}),
(slice) => {
latestSlice = slice;
@@ -1157,10 +1167,23 @@ export const StepsDetailView = defineComponent({
}
);
const unsubI18n = i18nStore.subscribe(
(st) => st.locale,
() => {
refreshStaticLocaleLabels();
if (uiStore.getState().activeView === 'steps' && latestSlice) {
renderStepsData(latestSlice);
} else {
isDirty = true;
}
}
);
onCleanup(() => {
unsubUi();
unsubTelemetry();
unsubView();
unsubI18n();
sessionLineChart.destroy?.();
modelFitChart.destroy?.();
inlineScopeSelect.destroy();
@@ -1177,6 +1200,7 @@ export const StepsDetailView = defineComponent({
return {
el: rootEl,
refs: {
stepsTheadRow,
stepsTbody,
modelsListEl,
inlineScopeSelect,
@@ -0,0 +1,479 @@
/**
* @fileoverview Preferences Tab 1: `SettingsGeneralTab.js` ("常规").
* Manages UI Language (`zh-CN` / `en-US` / `auto`), Theme Accent (`host` + 6 swatches),
* Panel Font Scale (`sm` / `md` / `lg` / `xl`), Pricing Sync, and Plugin Updates.
*/
import { defineComponent } from '../../core/component.js';
import {
normalizeClientFontScale,
normalizeClientThemeAccent,
} from '../../core/appearance.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { normalizeI18nLanguage, setI18nLanguage, t } from '../../i18n/index.js';
import {
normalizeClientUpdateMode,
saveSettingsPatch,
triggerCloudSync,
triggerPluginUpdate,
} from '../../store/telemetryStore.js';
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
import { CustomSelect } from '../../components/ui/CustomSelect.js';
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
function getLanguageOptions() {
return [
{ value: 'zh-CN', label: t('settings.gen.langZh') },
{ value: 'en-US', label: t('settings.gen.langEn') },
{ value: 'auto', label: t('settings.gen.langAuto') },
];
}
function getFontScaleOptions() {
return [
{ value: 'sm', label: t('settings.gen.fontSm') },
{ value: 'md', label: t('settings.gen.fontMd') },
{ value: 'lg', label: t('settings.gen.fontLg') },
{ value: 'xl', label: t('settings.gen.fontXl') },
];
}
function getUpdateModeOptions() {
return [
{ value: 'manual', label: t('settings.gen.updateManual') },
{ value: 'auto', label: t('settings.gen.updateAuto') },
{ value: 'off', label: t('settings.gen.updateOff') },
];
}
function formatCloudSyncTimeText(tsMs, updatedAt) {
if (Number(tsMs) > 0) {
const d = new Date(Number(tsMs));
const pad = (n) => String(n).padStart(2, '0');
const timeStr = `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
return t('settings.gen.syncAt', { time: timeStr });
}
if (updatedAt) {
return t('settings.gen.pubAt', { date: String(updatedAt).slice(0, 10) });
}
return t('settings.gen.defaultPricing');
}
export const SettingsGeneralTab = defineComponent({
name: 'SettingsGeneralTab',
setup({ props, onCleanup }) {
let draftLanguage = 'zh-CN';
let draftThemeAccent = 'host';
let draftFontScale = 'md';
let draftPluginUpdateMode = 'manual';
let latestSettings = null;
let latestCloudStatus = null;
let appearanceTimer = null;
let cloudTimer = null;
const appearanceStatusText = h('span', {
className: 'text-muted',
style: 'font-size: var(--fs-md);',
text: '',
});
const cloudStatusMsg = h('span', {
className: 'text-muted',
style: 'font-size: var(--fs-md);',
text: '',
});
function showAppearanceFeedback(text, autoClearMs = 1500) {
if (appearanceTimer) {
clearTimeout(appearanceTimer);
appearanceTimer = null;
}
patchText(appearanceStatusText, text);
if (text && autoClearMs > 0) {
appearanceTimer = setTimeout(() => {
appearanceTimer = null;
patchText(appearanceStatusText, '');
}, autoClearMs);
}
}
function showCloudFeedback(text, autoClearMs = 3500) {
if (cloudTimer) {
clearTimeout(cloudTimer);
cloudTimer = null;
}
patchText(cloudStatusMsg, text);
if (text && autoClearMs > 0) {
cloudTimer = setTimeout(() => {
cloudTimer = null;
patchText(cloudStatusMsg, '');
}, autoClearMs);
}
}
// --- Card 1: 界面与外观 ---
const appearanceTitleEl = h('span', { text: t('settings.gen.appearanceTitle') });
const langLabelEl = h('span', { className: 'form-label', text: t('settings.gen.language') });
const accentLabelEl = h('span', {
className: 'form-label',
text: t('settings.gen.themeAccent'),
});
const fontLabelEl = h('span', { className: 'form-label', text: t('settings.gen.fontScale') });
const fontHintEl = h('span', {
className: 'settings-hint-text',
text: t('settings.gen.fontHint'),
});
const languageSwitch = SegmentedControl({
ariaLabel: t('settings.gen.language'),
modelValue: draftLanguage,
options: getLanguageOptions(),
onUpdateModelValue: async (val) => {
const nextLang = normalizeI18nLanguage(val);
draftLanguage = nextLang;
setI18nLanguage(nextLang);
languageSwitch.setValue(nextLang);
showAppearanceFeedback(t('settings.saving'), 0);
try {
await saveSettingsPatch({ language: nextLang });
showAppearanceFeedback(t('settings.saved'), 1500);
} catch {
if (latestSettings) renderSettings(latestSettings);
showAppearanceFeedback(t('settings.saveFailed'), 2500);
}
},
});
const themeColorPicker = ThemeColorPicker({
modelValue: draftThemeAccent,
onUpdateModelValue: async (val) => {
const nextAccent = normalizeClientThemeAccent(val);
draftThemeAccent = nextAccent;
themeColorPicker.refs.setValue(nextAccent);
showAppearanceFeedback(t('settings.saving'), 0);
try {
await saveSettingsPatch({ themeAccent: nextAccent });
showAppearanceFeedback(t('settings.saved'), 1500);
} catch {
if (latestSettings) renderSettings(latestSettings);
showAppearanceFeedback(t('settings.saveFailed'), 2500);
}
},
});
const fontScaleSwitch = SegmentedControl({
ariaLabel: t('settings.gen.fontScale'),
modelValue: draftFontScale,
options: getFontScaleOptions(),
onUpdateModelValue: async (val) => {
const nextScale = normalizeClientFontScale(val);
draftFontScale = nextScale;
fontScaleSwitch.setValue(nextScale);
showAppearanceFeedback(t('settings.saving'), 0);
try {
await saveSettingsPatch({ fontScale: nextScale });
showAppearanceFeedback(t('settings.saved'), 1500);
props.onLayoutChange?.();
} catch {
if (latestSettings) renderSettings(latestSettings);
showAppearanceFeedback(t('settings.saveFailed'), 2500);
}
},
});
const appearancePanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('sliders', { size: 13 }),
appearanceTitleEl,
]),
appearanceStatusText,
]),
h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]),
h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]),
h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]),
]);
// --- Card 2: 版本更新 ---
const updateTitleEl = h('span', { text: t('settings.gen.updateTitle') });
const updateModeLabelEl = h('span', {
className: 'form-label',
text: t('settings.gen.updateMode'),
});
const pricingCellLabelEl = h('span', {
className: 'cell-label',
text: t('settings.gen.pricingLabel'),
});
const versionCellLabelEl = h('span', {
className: 'cell-label',
text: t('settings.gen.versionLabel'),
});
const autoUpdateSelect = CustomSelect({
modelValue: 'manual',
icon: 'refresh',
options: getUpdateModeOptions(),
onUpdateModelValue: async (val) => {
const nextMode = normalizeClientUpdateMode(val);
draftPluginUpdateMode = nextMode;
autoUpdateSelect.setValue(nextMode);
if (latestCloudStatus) {
renderCloudStatus(latestCloudStatus);
}
showCloudFeedback(t('settings.saving'), 0);
try {
await saveSettingsPatch({
pluginUpdateMode: nextMode,
autoUpdatePlugin: nextMode === 'auto',
});
showCloudFeedback(t('settings.saved'), 1800);
} catch {
if (latestSettings) renderSettings(latestSettings);
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
showCloudFeedback(t('settings.saveFailed'), 2500);
}
},
});
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
const pricingSyncSub = h('span', { className: 'cell-sub', text: t('quota.loading') });
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' });
const versionSub = h('span', { className: 'cell-sub', text: t('settings.gen.checkingBtn') });
const syncPricingBtnText = h('span', { text: t('settings.gen.syncBtn') });
const syncPricingBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
patchAttr(syncPricingBtn, 'disabled', true);
patchText(syncPricingBtnText, t('settings.gen.syncingBtn'));
showCloudFeedback(t('settings.gen.syncingMsg'), 0);
try {
const res = await triggerCloudSync();
const cs = res?.cloudStatus;
if (res?.ok && cs) {
showCloudFeedback(t('settings.gen.syncedMsg', { count: cs.modelCount }), 3500);
} else {
showCloudFeedback(cs?.lastSyncError || t('settings.gen.syncFallbackMsg'), 4500);
}
} catch (err) {
showCloudFeedback(err?.message || t('settings.gen.syncFallbackMsg'), 4500);
} finally {
patchAttr(syncPricingBtn, 'disabled', false);
patchText(syncPricingBtnText, t('settings.gen.syncBtn'));
}
},
},
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
);
const updatePluginBtnText = h('span', { text: t('settings.gen.checkUpdateBtn') });
const updatePluginBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
patchAttr(updatePluginBtn, 'disabled', true);
try {
if (!latestCloudStatus?.updateAvailable) {
patchText(updatePluginBtnText, t('settings.gen.checkingBtn'));
showCloudFeedback(t('settings.gen.checkingMsg'), 0);
const syncRes = await triggerCloudSync();
const cs = syncRes?.cloudStatus || latestCloudStatus;
if (cs) {
latestCloudStatus = cs;
renderCloudStatus(cs);
}
if (!syncRes?.ok && cs?.lastSyncError) {
showCloudFeedback(
t('settings.gen.checkFailedMsg', { err: cs.lastSyncError }),
5000
);
return;
}
if (!cs?.updateAvailable) {
const curVer = cs?.currentPluginVersion || '1.4.4';
showCloudFeedback(t('settings.gen.upToDateMsg', { ver: curVer }), 4500);
return;
}
}
patchText(updatePluginBtnText, t('capsule.updating'));
showCloudFeedback(t('settings.gen.downloadingMsg'), 0);
const res = await triggerPluginUpdate();
if (res?.cloudStatus) {
latestCloudStatus = res.cloudStatus;
}
if (res?.ok) {
showCloudFeedback(res.message || t('settings.gen.updatedRestartMsg'), 5000);
} else {
showCloudFeedback(res?.message || t('settings.gen.updateSkippedMsg'), 5500);
}
} catch (err) {
showCloudFeedback(err?.message || t('settings.gen.updateFailedMsg'), 5000);
} finally {
patchAttr(updatePluginBtn, 'disabled', false);
renderCloudStatus(latestCloudStatus);
}
},
},
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
);
const cloudPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('bolt', { size: 13 }),
updateTitleEl,
]),
cloudStatusMsg,
]),
h('div', { className: 'form-row' }, [updateModeLabelEl, autoUpdateSelect.el]),
h('div', { className: 'dual-grid' }, [
h('div', { className: 'matrix-cell' }, [
pricingCellLabelEl,
pricingCountVal,
pricingSyncSub,
]),
h('div', { className: 'matrix-cell' }, [versionCellLabelEl, versionVal, versionSub]),
]),
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
]);
const rootEl = h('div', { className: 'settings-tab-stack' }, [appearancePanel, cloudPanel]);
function renderSettings(settings) {
if (!settings) return;
latestSettings = settings;
draftLanguage = normalizeI18nLanguage(settings.language);
draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent);
draftFontScale = normalizeClientFontScale(settings.fontScale);
draftPluginUpdateMode = normalizeClientUpdateMode(
settings.pluginUpdateMode,
settings.autoUpdatePlugin
);
languageSwitch.setProps({
modelValue: draftLanguage,
options: getLanguageOptions(),
});
themeColorPicker.refs.setValue(draftThemeAccent);
fontScaleSwitch.setProps({
modelValue: draftFontScale,
options: getFontScaleOptions(),
});
autoUpdateSelect.setProps({
modelValue: draftPluginUpdateMode,
options: getUpdateModeOptions(),
});
}
function renderCloudStatus(cs) {
if (!cs) return;
latestCloudStatus = cs;
const srcLabel =
cs.source === 'remote'
? t('settings.gen.srcRemote')
: cs.source === 'local'
? t('settings.gen.srcLocal')
: t('settings.gen.srcDefault');
patchText(pricingCountVal, t('settings.gen.modelCount', { count: cs.modelCount || 0 }));
patchText(
pricingSyncSub,
`${srcLabel} · ${formatCloudSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
);
const curVer = cs.currentPluginVersion || '1.4.4';
const latVer = cs.latestPluginVersion || curVer;
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
patchText(versionVal, `v${curVer}`);
if (cs.updateAvailable && draftPluginUpdateMode !== 'off') {
patchText(versionSub, t('settings.gen.canUpgradeSub', { ver: latVer, mode: modeTag }));
patchClasses(versionSub, { 'accent-ok': true });
patchText(updatePluginBtnText, t('settings.gen.upgradeToBtn', { ver: latVer }));
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
} else if (draftPluginUpdateMode === 'off') {
patchText(versionSub, t('settings.gen.updateOffSub', { mode: modeTag }));
patchClasses(versionSub, { 'accent-ok': false });
patchText(
updatePluginBtnText,
cs.updateAvailable
? t('settings.gen.manualUpgradeBtn', { ver: latVer })
: t('settings.gen.checkUpdateBtn')
);
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
} else {
patchText(versionSub, t('settings.gen.latestSub', { mode: modeTag }));
patchClasses(versionSub, { 'accent-ok': false });
patchText(updatePluginBtnText, t('settings.gen.checkUpdateBtn'));
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
}
if (
!cloudTimer &&
(cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))
) {
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
}
}
function refreshLabels() {
patchText(appearanceTitleEl, t('settings.gen.appearanceTitle'));
patchText(langLabelEl, t('settings.gen.language'));
patchText(accentLabelEl, t('settings.gen.themeAccent'));
patchText(fontLabelEl, t('settings.gen.fontScale'));
patchText(fontHintEl, t('settings.gen.fontHint'));
patchText(updateTitleEl, t('settings.gen.updateTitle'));
patchText(updateModeLabelEl, t('settings.gen.updateMode'));
patchText(pricingCellLabelEl, t('settings.gen.pricingLabel'));
patchText(versionCellLabelEl, t('settings.gen.versionLabel'));
if (!syncPricingBtn.hasAttribute('disabled')) {
patchText(syncPricingBtnText, t('settings.gen.syncBtn'));
}
languageSwitch.setProps({
modelValue: draftLanguage,
options: getLanguageOptions(),
});
themeColorPicker.refs.refreshLabels();
fontScaleSwitch.setProps({
modelValue: draftFontScale,
options: getFontScaleOptions(),
});
autoUpdateSelect.setProps({
modelValue: draftPluginUpdateMode,
options: getUpdateModeOptions(),
});
if (latestCloudStatus) {
renderCloudStatus(latestCloudStatus);
} else {
patchText(pricingSyncSub, t('quota.loading'));
}
}
onCleanup(() => {
if (appearanceTimer) clearTimeout(appearanceTimer);
if (cloudTimer) clearTimeout(cloudTimer);
languageSwitch.destroy();
themeColorPicker.destroy();
fontScaleSwitch.destroy();
autoUpdateSelect.destroy();
});
return {
el: rootEl,
refs: {
languageSwitch,
themeColorPicker,
fontScaleSwitch,
autoUpdateSelect,
syncPricingBtn,
updatePluginBtn,
renderSettings,
renderCloudStatus,
refreshLabels,
},
};
},
});
@@ -0,0 +1,480 @@
/**
* @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他").
* Houses Model Identifier Formatting, Per-Model Context Windows,
* Local Trajectory Cache Rebuild, and Two-Step Factory Preference Reset.
*/
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
import { setI18nLanguage, t } from '../../i18n/index.js';
import {
normalizeClientOrchestratorIdMode,
rebuildTrajectoryCache,
resetAllSettings,
saveModelContextWindow,
saveSettingsPatch,
} from '../../store/telemetryStore.js';
import { CustomSelect } from '../../components/ui/CustomSelect.js';
function getStepModelDisplayOptions() {
return [
{ value: 'short', label: t('settings.oth.modelShort') },
{ value: 'upstream', label: t('settings.oth.modelUpstream') },
];
}
function getOrchestratorIdDisplayOptions() {
return [
{ value: 'compact', label: t('settings.oth.orchCompact') },
{ value: 'full', label: t('settings.oth.orchFull') },
];
}
export const SettingsOtherTab = defineComponent({
name: 'SettingsOtherTab',
setup({ onCleanup, getProps }) {
let draftShowUpstreamModel = false;
let draftOrchestratorIdMode = 'compact';
let latestSettings = null;
let contextWindowModels = [];
let contextModelId = '';
let savingContextWindow = false;
let contextFeedback = '';
let modelTimer = null;
let maintTimer = null;
let resetConfirmTimer = null;
let resetConfirmArmed = false;
let isRebuilding = false;
let isResetting = false;
const modelStatusText = h('span', {
className: 'text-muted',
style: 'font-size: var(--fs-md);',
text: '',
});
const maintStatusText = h('span', {
className: 'text-muted',
style: 'font-size: var(--fs-md);',
text: '',
});
function showModelFeedback(text, autoClearMs = 1500) {
if (modelTimer) {
clearTimeout(modelTimer);
modelTimer = null;
}
patchText(modelStatusText, text);
if (text && autoClearMs > 0) {
modelTimer = setTimeout(() => {
modelTimer = null;
patchText(modelStatusText, '');
}, autoClearMs);
}
}
function showMaintFeedback(text, autoClearMs = 2500) {
if (maintTimer) {
clearTimeout(maintTimer);
maintTimer = null;
}
patchText(maintStatusText, text);
if (text && autoClearMs > 0) {
maintTimer = setTimeout(() => {
maintTimer = null;
patchText(maintStatusText, '');
}, autoClearMs);
}
}
// --- Card 1: 模型标识显示 ---
const modelCardTitleEl = h('span', { text: t('settings.oth.modelTitle') });
const modelFormatLabelEl = h('span', {
className: 'form-label',
text: t('settings.oth.modelFormat'),
});
const orchFormatLabelEl = h('span', {
className: 'form-label',
text: t('settings.oth.orchFormat'),
});
const stepModelSelect = CustomSelect({
modelValue: 'short',
icon: 'table',
options: getStepModelDisplayOptions(),
onUpdateModelValue: async (val) => {
const nextUpstream = val === 'upstream';
draftShowUpstreamModel = nextUpstream;
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
showModelFeedback(t('settings.saving'), 0);
try {
await saveSettingsPatch({ showUpstreamModel: nextUpstream });
showModelFeedback(t('settings.saved'), 1500);
} catch {
if (latestSettings) renderSettings(latestSettings);
showModelFeedback(t('settings.saveFailed'), 2500);
}
},
});
const orchestratorIdSelect = CustomSelect({
modelValue: 'compact',
icon: 'layers',
options: getOrchestratorIdDisplayOptions(),
onUpdateModelValue: async (val) => {
const nextMode = normalizeClientOrchestratorIdMode(val);
draftOrchestratorIdMode = nextMode;
orchestratorIdSelect.setValue(nextMode);
showModelFeedback(t('settings.saving'), 0);
try {
await saveSettingsPatch({ orchestratorIdMode: nextMode });
showModelFeedback(t('settings.saved'), 1500);
} catch {
if (latestSettings) renderSettings(latestSettings);
showModelFeedback(t('settings.saveFailed'), 2500);
}
},
});
const modelPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('sliders', { size: 13 }),
modelCardTitleEl,
]),
modelStatusText,
]),
h('div', { className: 'form-row' }, [modelFormatLabelEl, stepModelSelect.el]),
h('div', { className: 'form-row' }, [orchFormatLabelEl, orchestratorIdSelect.el]),
]);
// --- Card 2: 按模型设置上下文窗口 ---
const baselineTitleEl = h('span', { text: t('settings.oth.baselineTitle') });
const ctxModelLabel = h('span', { className: 'form-label' });
const ctxWindowLabel = h('span', { className: 'form-label' });
const ctxHint = h('span', { className: 'settings-hint-text' });
const ctxStatus = h('span', { className: 'text-muted', role: 'status' });
const ctxModelSelect = CustomSelect({
className: 'settings-context-model',
options: [],
onUpdateModelValue: (id) => {
if (savingContextWindow) return;
contextModelId = id;
contextFeedback = '';
renderContextWindows();
},
});
const ctxWindowSelect = CustomSelect({
options: [],
onUpdateModelValue: async (value) => {
if (savingContextWindow || !contextModelId) return;
savingContextWindow = true;
contextFeedback = 'settings.saving';
renderContextWindows();
try {
const modelContextWindows = await saveModelContextWindow(contextModelId, value || null);
latestSettings = { ...latestSettings, modelContextWindows };
contextFeedback = 'settings.saved';
} catch {
contextFeedback = 'settings.saveFailed';
} finally {
savingContextWindow = false;
renderContextWindows();
}
},
});
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
function renderContextWindows() {
const saved = latestSettings?.modelContextWindows || {};
const models = new Map(contextWindowModels.map((model) => [model.id, model]));
const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members]));
for (const id of Object.keys(saved)) {
if (!knownIds.has(id)) models.set(id, { id, label: id.replace(/^model:/, ''), options: [] });
}
if (!models.has(contextModelId)) contextModelId = '';
const mixed = '\u0000mixed';
const getSelection = ({ id, members = [] }) => {
const legacy = new Set(members.map((member) => saved[member]).filter(Boolean));
return saved[id] || (legacy.size > 1 ? mixed : legacy.values().next().value) || '';
};
const formatLimit = (value) => /^\d+$/.test(value) ? t('settings.oth.ctxTokens', { count: Number(value).toLocaleString() }) : value;
const isAvailable = (model, value) => model.options.some(({ name }) => name === value) ||
(/^[1-9]\d*$/.test(value) && Number(value) <= model.capacity);
const current = models.get(contextModelId);
const options = current?.options || [];
const selected = current ? getSelection(current) : '';
const choices = [
{ value: '', label: t('settings.oth.ctxDefault') },
...options.map(({ name, expensive, tokens }) => ({
value: name,
label: tokens ? formatLimit(name) :
(expensive ? t('settings.oth.ctxExpensive', { name }) : name),
})),
];
if (selected && !choices.some((item) => item.value === selected)) {
let label = t('settings.oth.ctxMixed');
if (selected !== mixed) {
const name = formatLimit(selected);
label = isAvailable(current, selected) ? name : t('settings.oth.ctxUnavailable', { name });
}
choices.push({ value: selected, label, disabled: true });
}
ctxModelSelect.setProps({
modelValue: contextModelId,
options: [
{ value: '', label: t('settings.oth.ctxChooseModel') },
...[...models.values()].map((model) => {
const value = getSelection(model);
let meta = t('settings.oth.ctxDefault');
if (value === mixed) meta = t('settings.oth.ctxMixed');
else if (value) {
const name = formatLimit(value);
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
meta = t('settings.oth.ctxConfiguredReported', {
name,
reported: formatLimit(String(model.reportedLimitTokens)),
});
} else meta = t('settings.oth.ctxConfigured', { name });
}
else if (model.reportedLimitTokens) meta = t('settings.oth.ctxDefaultReported', { name: formatLimit(String(model.reportedLimitTokens)) });
return { value: model.id, label: model.label, meta };
}),
],
});
ctxWindowSelect.setProps({ modelValue: selected, options: choices });
patchAttr(ctxModelSelect.refs.triggerBtn, 'disabled', savingContextWindow);
patchAttr(ctxWindowSelect.refs.triggerBtn, 'disabled', savingContextWindow || (!options.length && !selected));
patchAttr(ctxModelSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxModel'));
patchAttr(ctxWindowSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxBaselineLabel'));
patchAttr(ctxModelRow, 'hidden', !models.size);
patchAttr(ctxWindowRow, 'hidden', !contextModelId);
patchText(ctxModelLabel, t('settings.oth.ctxModel'));
patchText(ctxWindowLabel, t('settings.oth.ctxBaselineLabel'));
const hint = !models.size ? 'ctxNoModels' : selected === mixed ? 'ctxMixedHint' :
contextModelId && !options.length ? 'ctxNoOptions' : 'ctxBaselineHint';
const reported = current?.reportedLimitTokens;
patchText(ctxHint, [t(`settings.oth.${hint}`), reported &&
t('settings.oth.ctxReported', { name: formatLimit(String(reported)) })].filter(Boolean).join(' '));
patchText(ctxStatus, contextFeedback ? t(contextFeedback) : '');
getProps().onLayoutChange?.();
}
const baselinePanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('layers', { size: 13 }),
baselineTitleEl,
]),
ctxStatus,
]),
ctxModelRow,
ctxWindowRow,
h('div', { className: 'form-row' }, [ctxHint]),
]);
renderContextWindows();
// --- Card 3: 缓存与重置 ---
const maintTitleEl = h('span', { text: t('settings.oth.maintTitle') });
const cacheLabelEl = h('span', {
className: 'settings-action-title',
text: t('settings.oth.cacheLabel'),
});
const cacheDescEl = h('span', {
className: 'settings-action-desc',
text: t('settings.oth.cacheDesc'),
});
const rebuildBtnText = h('span', { text: t('settings.oth.rebuildBtn') });
const rebuildCacheBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isRebuilding) return;
isRebuilding = true;
patchAttr(rebuildCacheBtn, 'disabled', true);
patchText(rebuildBtnText, t('settings.oth.rebuildingBtn'));
showMaintFeedback(t('settings.oth.rebuildingBtn'), 0);
try {
const res = await rebuildTrajectoryCache();
if (res?.ok !== false) {
showMaintFeedback(t('settings.oth.rebuildDone'), 2800);
} else {
showMaintFeedback(t('settings.oth.rebuildFailed'), 3000);
}
} catch {
showMaintFeedback(t('settings.oth.rebuildFailed'), 3000);
} finally {
isRebuilding = false;
patchAttr(rebuildCacheBtn, 'disabled', false);
patchText(rebuildBtnText, t('settings.oth.rebuildBtn'));
}
},
},
[createSvgIcon('refresh', { size: 12 }), rebuildBtnText]
);
const resetLabelEl = h('span', {
className: 'settings-action-title',
text: t('settings.oth.resetLabel'),
});
const resetDescEl = h('span', {
className: 'settings-action-desc',
text: t('settings.oth.resetDesc'),
});
const resetBtnText = h('span', { text: t('settings.oth.resetAllBtn') });
function disarmResetConfirm() {
resetConfirmArmed = false;
if (resetConfirmTimer) {
clearTimeout(resetConfirmTimer);
resetConfirmTimer = null;
}
patchClasses(resetAllBtn, { 'btn-danger-confirm': false });
if (!isResetting) {
patchText(resetBtnText, t('settings.oth.resetAllBtn'));
}
}
const resetAllBtn = h(
'button',
{
type: 'button',
className: 'btn-secondary',
onClick: async () => {
if (isResetting) return;
if (!resetConfirmArmed) {
resetConfirmArmed = true;
patchClasses(resetAllBtn, { 'btn-danger-confirm': true });
patchText(resetBtnText, t('settings.oth.resetConfirmBtn'));
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
resetConfirmTimer = setTimeout(() => {
disarmResetConfirm();
}, 3000);
return;
}
disarmResetConfirm();
isResetting = true;
patchAttr(resetAllBtn, 'disabled', true);
patchText(resetBtnText, t('settings.oth.resettingBtn'));
showMaintFeedback(t('settings.oth.resettingBtn'), 0);
try {
const res = await resetAllSettings();
setI18nLanguage(res?.settings?.language || 'zh-CN');
showMaintFeedback(t('settings.oth.resetAllDone'), 2800);
} catch {
showMaintFeedback(t('settings.saveFailed'), 2800);
} finally {
isResetting = false;
patchAttr(resetAllBtn, 'disabled', false);
patchText(resetBtnText, t('settings.oth.resetAllBtn'));
}
},
},
[resetBtnText]
);
const maintPanel = h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [
h('span', { className: 'panel-title' }, [
createSvgIcon('refresh', { size: 13 }),
maintTitleEl,
]),
maintStatusText,
]),
h('div', { className: 'settings-action-block' }, [
h('div', { className: 'settings-action-info' }, [cacheLabelEl, cacheDescEl]),
rebuildCacheBtn,
]),
h('div', { className: 'settings-action-block' }, [
h('div', { className: 'settings-action-info' }, [resetLabelEl, resetDescEl]),
resetAllBtn,
]),
]);
const rootEl = h('div', { className: 'settings-tab-stack' }, [
modelPanel,
baselinePanel,
maintPanel,
]);
function renderSettings(settings, models = contextWindowModels) {
if (!settings) return;
latestSettings = settings;
contextWindowModels = models;
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
stepModelSelect.setProps({
modelValue: draftShowUpstreamModel ? 'upstream' : 'short',
options: getStepModelDisplayOptions(),
});
orchestratorIdSelect.setProps({
modelValue: draftOrchestratorIdMode,
options: getOrchestratorIdDisplayOptions(),
});
renderContextWindows();
}
function refreshLabels() {
patchText(modelCardTitleEl, t('settings.oth.modelTitle'));
patchText(modelFormatLabelEl, t('settings.oth.modelFormat'));
patchText(orchFormatLabelEl, t('settings.oth.orchFormat'));
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
renderContextWindows();
patchText(maintTitleEl, t('settings.oth.maintTitle'));
patchText(cacheLabelEl, t('settings.oth.cacheLabel'));
patchText(cacheDescEl, t('settings.oth.cacheDesc'));
patchText(resetLabelEl, t('settings.oth.resetLabel'));
patchText(resetDescEl, t('settings.oth.resetDesc'));
if (!isRebuilding) {
patchText(rebuildBtnText, t('settings.oth.rebuildBtn'));
}
if (!isResetting) {
patchText(
resetBtnText,
resetConfirmArmed ? t('settings.oth.resetConfirmBtn') : t('settings.oth.resetAllBtn')
);
}
stepModelSelect.setProps({
modelValue: draftShowUpstreamModel ? 'upstream' : 'short',
options: getStepModelDisplayOptions(),
});
orchestratorIdSelect.setProps({
modelValue: draftOrchestratorIdMode,
options: getOrchestratorIdDisplayOptions(),
});
}
onCleanup(() => {
if (modelTimer) clearTimeout(modelTimer);
if (maintTimer) clearTimeout(maintTimer);
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
stepModelSelect.destroy();
orchestratorIdSelect.destroy();
ctxModelSelect.destroy();
ctxWindowSelect.destroy();
});
return {
el: rootEl,
refs: {
stepModelSelect,
orchestratorIdSelect,
ctxModelSelect,
ctxWindowSelect,
rebuildCacheBtn,
resetAllBtn,
renderSettings,
refreshLabels,
},
};
},
});
@@ -0,0 +1,507 @@
/**
* @fileoverview Preferences Tab 2: `SettingsStructureTab.js` ("结构").
* Provides 4 collapsible customization sections with `+` / `-` / `↑` / `↓`:
* 1. 挂载与胶囊栏 (`windowMountMode`, `showTopbarMultiSession`, `topbarCapsuleSlots` 1..5)
* 2. 鼠标悬浮窗 (`hoverModules` 0..4)
* 3. 实时监控布局 (`overviewModules` 1..4 + `overviewMetrics` 1..4)
* 4. 调用明细字段 (`stepTableColumns` 2..12)
*/
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchText } from '../../core/domPatch.js';
import { t } from '../../i18n/index.js';
import {
getCapsuleMetricOptions,
getOverviewMetricOptions,
} from '../../registries/metricRegistry.js';
import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js';
import { getOverviewModuleOptions } from '../../registries/widgetRegistry.js';
import {
DEFAULT_CLIENT_HOVER_MODULES,
DEFAULT_CLIENT_OVERVIEW_METRICS,
DEFAULT_CLIENT_OVERVIEW_MODULES,
DEFAULT_CLIENT_STEP_COLUMNS,
DEFAULT_CLIENT_TOPBAR_SLOTS,
normalizeClientHoverModules,
normalizeClientOverviewMetrics,
normalizeClientOverviewModules,
normalizeClientStepColumns,
normalizeClientTopbarSlots,
normalizeClientWindowMountMode,
saveSettingsPatch,
} from '../../store/telemetryStore.js';
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
import { CustomSelect } from '../../components/ui/CustomSelect.js';
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
function getMountModeOptions() {
return [
{ value: 'dual', label: t('settings.str.mountDual') },
{ value: 'composer', label: t('settings.str.mountComposer') },
{ value: 'sidebar', label: t('settings.str.mountSidebar') },
];
}
function getMultiToggleOptions() {
return [
{ value: 'show', label: t('settings.str.show') },
{ value: 'hide', label: t('settings.str.hide') },
];
}
function isSameList(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
for (let i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) return false;
}
return true;
}
export const SettingsStructureTab = defineComponent({
name: 'SettingsStructureTab',
setup({ props, onCleanup }) {
let draftWindowMountMode = 'dual';
let draftShowTopbarMulti = true;
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
let draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
let latestSettings = null;
async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') {
sectionComp.refs.showStatus(t('settings.saving'), 0);
try {
await saveSettingsPatch(patchObj);
sectionComp.refs.showStatus(t(successKey), 1500);
} catch {
if (latestSettings) {
renderSettings(latestSettings);
}
sectionComp.refs.showStatus(t('settings.saveFailed'), 2500);
}
}
// --- Section 1: 挂载与胶囊栏 (defaultExpanded: true) ---
const mountModeLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.mountMode'),
});
const multiToggleLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.multiToggle'),
});
const capsuleSlotsLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.capsuleSlotsLabel'),
});
const windowMountSelect = CustomSelect({
modelValue: draftWindowMountMode,
icon: 'dock',
options: getMountModeOptions(),
onUpdateModelValue: (val) => {
const nextMode = normalizeClientWindowMountMode(val);
draftWindowMountMode = nextMode;
syncMountSectionMeta();
void persistStructurePatch(mountSection, {
windowMountMode: nextMode,
enableWindowOverlay: nextMode !== 'sidebar',
});
},
});
const multiSessionToggle = SegmentedControl({
ariaLabel: t('settings.str.multiToggle'),
modelValue: 'show',
options: getMultiToggleOptions(),
onUpdateModelValue: (val) => {
draftShowTopbarMulti = val !== 'hide';
syncMountSectionMeta();
void persistStructurePatch(mountSection, {
showTopbarMultiSession: draftShowTopbarMulti,
});
},
});
const topbarSlotsList = EditableSlotList({
items: draftTopbarSlots,
options: getCapsuleMetricOptions(),
minItems: 1,
maxItems: 5,
addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }),
onChange: (nextItems) => {
draftTopbarSlots = normalizeClientTopbarSlots(nextItems);
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(mountSection, {
topbarCapsuleSlots: draftTopbarSlots,
});
},
});
const mountSection = CollapsibleSection({
icon: 'dock',
title: t('settings.str.mountSection'),
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
defaultExpanded: true,
onToggle: () => props.onLayoutChange?.(),
onReset: () => {
draftWindowMountMode = 'dual';
draftShowTopbarMulti = true;
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
syncMountSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(
mountSection,
{
windowMountMode: 'dual',
enableWindowOverlay: true,
showTopbarMultiSession: true,
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
},
'settings.resetDone'
);
},
children: [
h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]),
h('div', { className: 'settings-inline-row' }, [
multiToggleLabelEl,
multiSessionToggle.el,
]),
h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]),
],
});
function syncMountSectionMeta() {
windowMountSelect.setProps({
modelValue: draftWindowMountMode,
options: getMountModeOptions(),
});
multiSessionToggle.setProps({
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
options: getMultiToggleOptions(),
});
topbarSlotsList.refs.setProps({
items: draftTopbarSlots,
options: getCapsuleMetricOptions(),
addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }),
});
mountSection.refs.setBadge(
t('settings.str.mountBadge', { count: draftTopbarSlots.length })
);
const isDefault =
draftWindowMountMode === 'dual' &&
draftShowTopbarMulti === true &&
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
mountSection.refs.setResetDisabled(isDefault);
}
// --- Section 2: 鼠标悬浮窗 (0..4 items) ---
const hoverModulesLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.hoverModulesLabel'),
});
const hoverModulesList = EditableSlotList({
items: draftHoverModules,
options: getOverviewModuleOptions(),
minItems: 0,
maxItems: 4,
emptyHintText: t('settings.str.hoverEmptyHint'),
addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }),
onChange: (nextItems) => {
draftHoverModules = normalizeClientHoverModules(nextItems);
syncHoverSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(hoverSection, {
hoverModules: draftHoverModules,
});
},
});
const hoverSection = CollapsibleSection({
icon: 'layers',
title: t('settings.str.hoverSection'),
badgeText: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }),
defaultExpanded: false,
onToggle: () => props.onLayoutChange?.(),
onReset: () => {
draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
syncHoverSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(
hoverSection,
{ hoverModules: [...DEFAULT_CLIENT_HOVER_MODULES] },
'settings.resetDone'
);
},
children: [h('div', { className: 'form-row' }, [hoverModulesLabelEl, hoverModulesList.el])],
});
function syncHoverSectionMeta() {
hoverModulesList.refs.setProps({
items: draftHoverModules,
options: getOverviewModuleOptions(),
emptyHintText: t('settings.str.hoverEmptyHint'),
addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }),
});
hoverSection.refs.setBadge(
draftHoverModules.length === 0
? t('settings.str.hoverBadgeOff')
: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length })
);
hoverSection.refs.setResetDisabled(isSameList(draftHoverModules, DEFAULT_CLIENT_HOVER_MODULES));
}
// --- Section 3: 实时监控布局 (Modules 1..4 + First-Row Metrics 1..4) ---
const overviewModulesLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.overviewModulesLabel'),
});
const overviewMetricsLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.overviewMetricsLabel'),
});
const overviewMetricsHintEl = h('span', {
className: 'settings-hint-text',
hidden: true,
text: t('settings.str.overviewMetricsInactiveHint'),
});
const overviewModulesList = EditableSlotList({
items: draftOverviewModules,
options: getOverviewModuleOptions(),
minItems: 1,
maxItems: 4,
addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }),
onChange: (nextItems) => {
draftOverviewModules = normalizeClientOverviewModules(nextItems);
syncOverviewSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(overviewSection, {
overviewModules: draftOverviewModules,
});
},
});
const overviewMetricsList = EditableSlotList({
items: draftOverviewMetrics,
options: getOverviewMetricOptions(),
minItems: 1,
maxItems: 4,
addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }),
onChange: (nextItems) => {
draftOverviewMetrics = normalizeClientOverviewMetrics(nextItems);
syncOverviewSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(overviewSection, {
overviewMetrics: draftOverviewMetrics,
});
},
});
const overviewSection = CollapsibleSection({
icon: 'pulse',
title: t('settings.str.overviewSection'),
badgeText: t('settings.str.overviewBadge', {
modCount: draftOverviewModules.length,
metCount: draftOverviewMetrics.length,
}),
defaultExpanded: false,
onToggle: () => props.onLayoutChange?.(),
onReset: () => {
draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
syncOverviewSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(
overviewSection,
{
overviewModules: [...DEFAULT_CLIENT_OVERVIEW_MODULES],
overviewMetrics: [...DEFAULT_CLIENT_OVERVIEW_METRICS],
},
'settings.resetDone'
);
},
children: [
h('div', { className: 'form-row' }, [overviewModulesLabelEl, overviewModulesList.el]),
h('div', { className: 'settings-divider' }),
h('div', { className: 'form-row' }, [
overviewMetricsLabelEl,
overviewMetricsHintEl,
overviewMetricsList.el,
]),
],
});
function syncOverviewSectionMeta() {
overviewModulesList.refs.setProps({
items: draftOverviewModules,
options: getOverviewModuleOptions(),
addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }),
});
overviewMetricsList.refs.setProps({
items: draftOverviewMetrics,
options: getOverviewMetricOptions(),
addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }),
});
const metricsModuleActive = draftOverviewModules.includes('metrics');
patchAttr(overviewMetricsHintEl, 'hidden', metricsModuleActive);
overviewSection.refs.setBadge(
t('settings.str.overviewBadge', {
modCount: draftOverviewModules.length,
metCount: draftOverviewMetrics.length,
})
);
const isDefault =
isSameList(draftOverviewModules, DEFAULT_CLIENT_OVERVIEW_MODULES) &&
isSameList(draftOverviewMetrics, DEFAULT_CLIENT_OVERVIEW_METRICS);
overviewSection.refs.setResetDisabled(isDefault);
}
// --- Section 4: 调用明细字段 (Step Table Columns 2..12) ---
const stepColsLabelEl = h('span', {
className: 'form-label',
text: t('settings.str.stepsColsLabel'),
});
const stepColumnsList = EditableSlotList({
items: draftStepColumns,
options: getStepColumnOptions(),
minItems: 2,
maxItems: 12,
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
onChange: (nextItems) => {
draftStepColumns = normalizeClientStepColumns(nextItems);
syncStepsSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(stepsSection, {
stepTableColumns: draftStepColumns,
});
},
});
const stepsSection = CollapsibleSection({
icon: 'table',
title: t('settings.str.stepsSection'),
badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }),
defaultExpanded: false,
onToggle: () => props.onLayoutChange?.(),
onReset: () => {
draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
syncStepsSectionMeta();
props.onLayoutChange?.();
void persistStructurePatch(
stepsSection,
{ stepTableColumns: [...DEFAULT_CLIENT_STEP_COLUMNS] },
'settings.resetDone'
);
},
children: [h('div', { className: 'form-row' }, [stepColsLabelEl, stepColumnsList.el])],
});
function syncStepsSectionMeta() {
stepColumnsList.refs.setProps({
items: draftStepColumns,
options: getStepColumnOptions(),
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
});
stepsSection.refs.setBadge(t('settings.str.stepsBadge', { count: draftStepColumns.length }));
stepsSection.refs.setResetDisabled(isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS));
}
const rootEl = h('div', { className: 'settings-tab-stack' }, [
mountSection.el,
hoverSection.el,
overviewSection.el,
stepsSection.el,
]);
function renderSettings(settings) {
if (!settings) return;
latestSettings = settings;
draftWindowMountMode = normalizeClientWindowMountMode(
settings.windowMountMode,
settings.enableWindowOverlay
);
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
draftHoverModules = normalizeClientHoverModules(settings.hoverModules);
draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules);
draftOverviewMetrics = normalizeClientOverviewMetrics(settings.overviewMetrics);
draftStepColumns = normalizeClientStepColumns(settings.stepTableColumns);
syncMountSectionMeta();
syncHoverSectionMeta();
syncOverviewSectionMeta();
syncStepsSectionMeta();
}
function refreshLabels() {
mountSection.refs.setTitle(t('settings.str.mountSection'));
mountSection.refs.setResetLabel(t('settings.resetBtn'));
patchText(mountModeLabelEl, t('settings.str.mountMode'));
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
hoverSection.refs.setTitle(t('settings.str.hoverSection'));
hoverSection.refs.setResetLabel(t('settings.resetBtn'));
patchText(hoverModulesLabelEl, t('settings.str.hoverModulesLabel'));
overviewSection.refs.setTitle(t('settings.str.overviewSection'));
overviewSection.refs.setResetLabel(t('settings.resetBtn'));
patchText(overviewModulesLabelEl, t('settings.str.overviewModulesLabel'));
patchText(overviewMetricsLabelEl, t('settings.str.overviewMetricsLabel'));
patchText(overviewMetricsHintEl, t('settings.str.overviewMetricsInactiveHint'));
stepsSection.refs.setTitle(t('settings.str.stepsSection'));
stepsSection.refs.setResetLabel(t('settings.resetBtn'));
patchText(stepColsLabelEl, t('settings.str.stepsColsLabel'));
syncMountSectionMeta();
syncHoverSectionMeta();
syncOverviewSectionMeta();
syncStepsSectionMeta();
}
syncMountSectionMeta();
syncHoverSectionMeta();
syncOverviewSectionMeta();
syncStepsSectionMeta();
onCleanup(() => {
windowMountSelect.destroy();
multiSessionToggle.destroy();
topbarSlotsList.destroy();
hoverModulesList.destroy();
overviewModulesList.destroy();
overviewMetricsList.destroy();
stepColumnsList.destroy();
mountSection.destroy();
hoverSection.destroy();
overviewSection.destroy();
stepsSection.destroy();
});
return {
el: rootEl,
refs: {
windowMountSelect,
multiSessionToggle,
topbarSlotsList,
hoverModulesList,
overviewModulesList,
overviewMetricsList,
stepColumnsList,
mountSection,
hoverSection,
overviewSection,
stepsSection,
renderSettings,
refreshLabels,
},
};
},
});