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
@@ -0,0 +1,617 @@
/**
* @fileoverview Decoupled Metric Registry (`metricRegistry.js`).
* Centralizes presentation & option metadata for:
* 1. Topbar / Composer Capsule Slots (1..5 items out of 13 metrics)
* 2. Live Overview / Hover First-Row Metric Matrix (1..4 items out of 9 metrics)
*/
import {
formatMetric,
formatTokens,
formatUsd,
resolveModelDisplayInfo,
sampleSummary,
speedReasonText,
} from '../core/formatters.js';
import { isEnglishLocale, t } from '../i18n/index.js';
export const CAPSULE_METRIC_KEYS = Object.freeze([
'context',
'tps',
'ttft',
'avg_tps',
'cost',
'session_cost',
'cache_hit',
'session_tokens',
'quota_auto',
'gemini_5h',
'gemini_weekly',
'claude_5h',
'claude_weekly',
]);
export const OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
export function getCapsuleMetricOptions() {
return CAPSULE_METRIC_KEYS.map((key) => ({
value: key,
label: t(`capMetric.${key}`),
}));
}
export function getOverviewMetricOptions() {
return OVERVIEW_METRIC_KEYS.map((key) => ({
value: key,
label: t(`ovMetric.${key}`),
}));
}
export function resolveQuotaCapsuleSummary(quotas) {
if (!quotas) return null;
const activePool = quotas.activePool;
const weekly = quotas.weekly;
const candidates = [];
const defaultPoolName = isEnglishLocale() ? 'Active Pool' : '当前池';
const wkTag = isEnglishLocale() ? 'Wk' : '周';
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
candidates.push({
pct: Number(activePool.remainingPct),
label: activePool.poolLabel || activePool.family || defaultPoolName,
windowTag: '5h',
});
}
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
candidates.push({
pct: Number(activePool.weeklyRemainingPct),
label: activePool.poolLabel || activePool.family || defaultPoolName,
windowTag: wkTag,
});
}
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
candidates.push({
pct: Number(weekly.remainingPct),
label: weekly.poolFamily || (isEnglishLocale() ? 'Weekly' : '周限额'),
windowTag: wkTag,
});
}
if (!candidates.length) return null;
candidates.sort((a, b) => a.pct - b.pct);
const tightest = candidates[0];
const rounded = Math.max(0, Math.min(100, Math.round(tightest.pct)));
return {
roundedPct: rounded,
shortText: t('capsule.quotaLeft', { pct: rounded }),
detailText: candidates
.map((c) => {
const cPct = Math.max(0, Math.min(100, Math.round(c.pct)));
return `${c.label} ${c.windowTag} ${t('capsule.quotaLeft', { pct: cPct })}`;
})
.join(' · '),
};
}
/**
* 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。
*
* @param {object|null|undefined} quotas
* @param {'gemini_5h'|'gemini_weekly'|'claude_5h'|'claude_weekly'} slotKey
* @returns {{ roundedPct: number, shortText: string } | null}
*/
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
if (!quotas) return null;
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
const activePool = quotas.activePool || null;
const isClaude = slotKey.startsWith('claude_');
const isWeekly = slotKey.endsWith('_weekly');
let rawPct = null;
if (isClaude) {
const claudePool =
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || '')));
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
if (cand != null && Number.isFinite(Number(cand))) {
rawPct = Number(cand);
} else if (
activePool &&
THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
) {
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
if (fb != null && Number.isFinite(Number(fb))) {
rawPct = Number(fb);
}
}
} else {
const stdGemini =
pools.find((p) => p?.poolKey === 'Gemini') ||
pools.find(
(p) =>
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
!/carbon|argon/i.test(String(p?.poolKey || ''))
);
const geminiFamilyPools = pools.filter((p) =>
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
);
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
rawPct = Number(primaryCand);
} else {
const familyVals = geminiFamilyPools
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
.filter((v) => v != null && Number.isFinite(Number(v)))
.map(Number);
if (familyVals.length > 0) {
rawPct = Math.min(...familyVals);
} else if (
activePool &&
!THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
) {
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
if (fb != null && Number.isFinite(Number(fb))) {
rawPct = Number(fb);
}
}
if (
rawPct == null &&
isWeekly &&
quotas.weekly &&
!THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) &&
quotas.weekly.remainingPct != null &&
Number.isFinite(Number(quotas.weekly.remainingPct))
) {
rawPct = Number(quotas.weekly.remainingPct);
}
}
}
if (rawPct == null || !Number.isFinite(rawPct)) return null;
const rounded = Math.max(0, Math.min(100, Math.round(rawPct)));
return {
roundedPct: rounded,
shortText: t('capsule.quotaLeft', { pct: rounded }),
};
}
export function formatCompactCapsuleCost(costUsd) {
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
const val = Math.max(0, Number(costUsd));
if (val === 0) return '$0.00';
if (val < 0.001) return '<$0.001';
if (val < 1) return `$${val.toFixed(3)}`;
if (val < 100) return `$${val.toFixed(2)}`;
return `$${Math.round(val)}`;
}
export function formatCompactCapsuleTtft(ttftSec) {
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
const val = Number(ttftSec);
if (val < 1) return `${val.toFixed(2)}s`;
if (val < 100) return `${val.toFixed(1)}s`;
return `${Math.round(val)}s`;
}
/**
* 解析顶栏/输入框精简胶囊单槽位展示结构。
*
* @param {string} metricKey
* @param {object} slotCtx
* @param {number} ringCircumference
*/
export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) {
if (!metricKey || metricKey === 'none') {
return {
hidden: true,
metric: 'none',
segClass: 'wm-cap-slot',
textClass: 'wm-slot-text',
showRing: false,
dashOffset: ringCircumference,
text: '',
running: false,
warn: false,
danger: false,
};
}
if (metricKey === 'context') {
if (!slotCtx.hasTelemetry) {
return {
hidden: false,
metric: 'context',
segClass: 'wm-cap-slot wm-ctx-seg',
textClass: 'wm-slot-text wm-ctx-pct',
showRing: true,
dashOffset: ringCircumference,
text: '--%',
running: false,
warn: false,
danger: false,
};
}
const isDanger = slotCtx.usedPct >= 88;
const isWarn = !isDanger && slotCtx.usedPct >= 70;
return {
hidden: false,
metric: 'context',
segClass: 'wm-cap-slot wm-ctx-seg',
textClass: 'wm-slot-text wm-ctx-pct',
showRing: true,
dashOffset: slotCtx.dashOffset,
text: `${Math.round(slotCtx.usedPct)}%`,
running: false,
warn: isWarn,
danger: isDanger,
};
}
if (metricKey === 'tps') {
if (!slotCtx.hasTelemetry) {
return {
hidden: false,
metric: 'tps',
segClass: 'wm-cap-slot wm-seg-speed',
textClass: 'wm-slot-text wm-speed-text',
showRing: false,
dashOffset: ringCircumference,
text: '-- t/s',
running: false,
warn: false,
danger: false,
};
}
const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0;
const tpsText = hasValidTps
? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s`
: slotCtx.isRunning
? t('capsule.tpsRunning')
: t('capsule.tpsIdle');
return {
hidden: false,
metric: 'tps',
segClass: 'wm-cap-slot wm-seg-speed',
textClass: 'wm-slot-text wm-speed-text',
showRing: false,
dashOffset: ringCircumference,
text: tpsText,
running: Boolean(slotCtx.isRunning),
warn: false,
danger: false,
};
}
if (metricKey === 'avg_tps') {
const avgVal = slotCtx.hasTelemetry ? slotCtx.avgTps : null;
const valid = Number.isFinite(avgVal) && avgVal > 0;
return {
hidden: false,
metric: 'avg_tps',
segClass: 'wm-cap-slot wm-seg-speed',
textClass: 'wm-slot-text wm-speed-text',
showRing: false,
dashOffset: ringCircumference,
text: valid ? `${avgVal >= 100 ? Math.round(avgVal) : avgVal.toFixed(1)} t/s` : '-- t/s',
running: false,
warn: false,
danger: false,
};
}
if (metricKey === 'ttft') {
const val = slotCtx.hasTelemetry ? slotCtx.ttft : null;
const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0;
const numVal = valid ? Number(val) : 0;
const isDanger = valid && numVal >= 30;
const isWarn = valid && !isDanger && numVal >= 15;
return {
hidden: false,
metric: 'ttft',
segClass: 'wm-cap-slot wm-seg-ttft',
textClass: 'wm-slot-text wm-ttft-text',
showRing: false,
dashOffset: ringCircumference,
text: valid ? formatCompactCapsuleTtft(numVal) : '--s',
running: false,
warn: isWarn,
danger: isDanger,
};
}
if (metricKey === 'cost' || metricKey === 'session_cost') {
const costVal = !slotCtx.hasTelemetry
? null
: metricKey === 'session_cost'
? slotCtx.sessionCost
: slotCtx.stepCost;
return {
hidden: false,
metric: metricKey,
segClass: 'wm-cap-slot wm-seg-cost',
textClass: 'wm-slot-text wm-cost-text',
showRing: false,
dashOffset: ringCircumference,
text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--',
running: false,
warn: false,
danger: false,
};
}
if (metricKey === 'cache_hit') {
const cachePct = slotCtx.hasTelemetry ? slotCtx.cacheHitPct : null;
const valid = cachePct != null && Number.isFinite(Number(cachePct));
return {
hidden: false,
metric: 'cache_hit',
segClass: 'wm-cap-slot wm-seg-cache',
textClass: 'wm-slot-text wm-cache-text',
showRing: false,
dashOffset: ringCircumference,
text: valid ? `${Math.round(Number(cachePct))}%` : '--%',
running: false,
warn: false,
danger: false,
};
}
if (metricKey === 'session_tokens') {
const tokVal = slotCtx.hasTelemetry ? slotCtx.sessionTokens : null;
const valid = tokVal != null && Number.isFinite(Number(tokVal)) && Number(tokVal) >= 0;
return {
hidden: false,
metric: 'session_tokens',
segClass: 'wm-cap-slot wm-seg-tokens',
textClass: 'wm-slot-text wm-tokens-text',
showRing: false,
dashOffset: ringCircumference,
text: valid ? formatTokens(Number(tokVal)) : '--',
running: false,
warn: false,
danger: false,
};
}
const quotaSum = !slotCtx.hasTelemetry
? null
: metricKey === 'quota_auto'
? resolveQuotaCapsuleSummary(slotCtx.quotas)
: resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey);
const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15);
const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30);
return {
hidden: false,
metric: metricKey,
segClass: 'wm-cap-slot wm-seg-quota',
textClass: 'wm-slot-text wm-quota-text',
showRing: false,
dashOffset: ringCircumference,
text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'),
running: false,
warn: isWarn,
danger: isDanger,
};
}
function translateRawAgentBadge(rawBadge) {
if (!rawBadge) return '';
if (!isEnglishLocale()) return String(rawBadge);
const str = String(rawBadge).trim();
if (str === '主') return t('fmt.mainBadge');
const m = str.match(/^子(\d+)$/);
if (m) return t('fmt.subBadge', { index: m[1] });
if (str === '子') return t('fmt.subBadgeShort');
return str;
}
/**
* 解析实时监控第一行矩阵单个单元格的展示数据。
*
* @param {string} metricKey
* @param {{ active?: object, ctx?: object, quotas?: object, settings?: object, hasSubagents?: boolean }} cellCtx
*/
export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
const active = cellCtx.active || {};
const ctx = cellCtx.ctx || active.context || {};
const quotas = cellCtx.quotas || {};
const settings = cellCtx.settings || {};
const hasSubagents = Boolean(cellCtx.hasSubagents);
const hasAnySteps = Number(active.stepCount || 0) > 0;
if (metricKey === 'tps') {
const activeModelDisplay = resolveModelDisplayInfo(active, settings, {
fallback: t('fmt.unknownModel'),
}).text;
const reason = speedReasonText(active.latestSpeedReason);
const badgeStr = translateRawAgentBadge(active.activeAgentBadge);
const modelAndAgent =
hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay;
return {
key: 'tps',
label: t('ovMetric.tps'),
icon: 'dot',
iconSize: 10,
isPulsing: Boolean(active.isRunning),
valueText: formatMetric(active.latestTokPerSec, ' tok/s'),
valueClass: 'cell-value accent-speed',
subText: reason ? `${modelAndAgent} · ${reason}` : modelAndAgent,
subClass: 'cell-sub',
};
}
if (metricKey === 'ttft') {
return {
key: 'ttft',
label: t('ovMetric.ttft'),
icon: 'clock',
iconSize: 11,
isPulsing: false,
valueText: formatMetric(active.latestTtftSec, 's'),
valueClass: 'cell-value',
subText: t('ovMetric.subAvgTtft', {
val: formatMetric(active.ttftSummary?.avgSec, 's'),
}),
subClass: 'cell-sub',
};
}
if (metricKey === 'avg_tps') {
return {
key: 'avg_tps',
label: t('ovMetric.avg_tps'),
icon: 'pulse',
iconSize: 11,
isPulsing: false,
valueText: formatMetric(active.avgTokPerSec, ' tok/s'),
valueClass: 'cell-value',
subText: t('ovMetric.subValidSamples', {
samples: sampleSummary(active.speedSummary),
}),
subClass: 'cell-sub',
};
}
if (metricKey === 'step_cost') {
const stepCost = active.latestStepCostUsd;
return {
key: 'step_cost',
label: t('ovMetric.step_cost'),
icon: 'bolt',
iconSize: 11,
isPulsing: false,
valueText: !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }),
valueClass: 'cell-value',
subText: t('ovMetric.subCacheAndTotal', {
cache: active.latestCacheHitPct ?? 0,
cost: formatUsd(active.sessionCostUsd || 0),
}),
subClass: 'cell-sub accent-ok',
};
}
if (metricKey === 'session_cost') {
const sessCost = Number(active.sessionCostUsd || 0);
const stepCnt = Number(active.stepCount || 0);
const isAllUnpriced =
stepCnt > 0 && Number(active.sessionUnpricedCalls || 0) >= stepCnt && !(sessCost > 0);
return {
key: 'session_cost',
label: t('ovMetric.session_cost'),
icon: 'bolt',
iconSize: 11,
isPulsing: false,
valueText:
!hasAnySteps && active.sessionCostUsd == null
? '—'
: formatUsd(isAllUnpriced ? null : sessCost, {
precise: sessCost > 0 && sessCost < 0.1,
}),
valueClass: 'cell-value',
subText: t('ovMetric.subStepsAndCache', {
steps: stepCnt,
cache: Math.round(Number(active.sessionCacheHitPct ?? active.latestCacheHitPct ?? 0)),
}),
subClass: 'cell-sub accent-ok',
};
}
if (metricKey === 'cache_hit') {
const avgCache = Number(active.sessionCacheHitPct ?? active.latestCacheHitPct ?? 0);
const latestCache = Number(active.latestCacheHitPct ?? 0);
return {
key: 'cache_hit',
label: t('ovMetric.cache_hit'),
icon: 'layers',
iconSize: 11,
isPulsing: false,
valueText: !hasAnySteps ? '—' : `${Math.round(avgCache)}%`,
valueClass: 'cell-value accent-ok',
subText: t('ovMetric.subPromptHit', {
latest: Math.round(latestCache),
avg: Math.round(avgCache),
}),
subClass: 'cell-sub',
};
}
if (metricKey === 'session_tokens') {
const inTok = Math.max(0, Number(active.inputTokens || 0));
const cacheTok = Math.max(0, Number(active.cacheReadTokens || 0));
const outTok = Math.max(0, Number(active.outputTokens || 0));
const totalTok = Math.max(0, Number(active.totalTokens ?? inTok + cacheTok + outTok));
return {
key: 'session_tokens',
label: t('ovMetric.session_tokens'),
icon: 'chart-bar',
iconSize: 11,
isPulsing: false,
valueText: !hasAnySteps && !totalTok ? '—' : formatTokens(totalTok),
valueClass: 'cell-value',
subText: t('ovMetric.subInOutTokens', {
inTok: formatTokens(inTok + cacheTok),
outTok: formatTokens(outTok),
}),
subClass: 'cell-sub',
};
}
if (metricKey === 'context_usage') {
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
const totalTokens = Number(ctx.totalTokens || 0);
const usedPct =
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
const toneCls =
usedPct >= 88
? 'cell-value tone-danger'
: usedPct >= 70
? 'cell-value tone-warn'
: 'cell-value';
return {
key: 'context_usage',
label: t('ovMetric.context_usage'),
icon: 'layers',
iconSize: 11,
isPulsing: false,
valueText: `${usedPct}%`,
valueClass: toneCls,
subText: t('ovMetric.subCtxRatio', {
used: formatTokens(totalTokens),
limit: formatTokens(limitTokens),
}),
subClass: 'cell-sub',
};
}
const quotaSum = resolveQuotaCapsuleSummary(quotas);
const quotaToneCls =
quotaSum && quotaSum.roundedPct <= 15
? 'cell-value tone-danger'
: quotaSum && quotaSum.roundedPct <= 30
? 'cell-value tone-warn'
: 'cell-value';
return {
key: 'quota_tightest',
label: t('ovMetric.quota_tightest'),
icon: 'pulse',
iconSize: 11,
isPulsing: false,
valueText: quotaSum ? quotaSum.shortText : '—',
valueClass: quotaToneCls,
subText: quotaSum
? t('ovMetric.subQuotaPool', { label: quotaSum.detailText })
: t('ovMetric.subQuotaPending'),
subClass: 'cell-sub',
};
}
@@ -0,0 +1,330 @@
/**
* @fileoverview Decoupled Step Table Column Registry (`stepColumnRegistry.js`).
* Defines all 12 customizable columns for `StepsDetailView` ("按步查看"),
* preserving 100% of the 7 out-of-the-box default columns, clickable agent filter badges,
* speed reason sub-lines, token combo tooltips, and high-cost highlights.
*/
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
import {
formatMetric,
formatTokens,
formatUsd,
resolveModelDisplayInfo,
speedReasonText,
} from '../core/formatters.js';
import { isEnglishLocale, t } from '../i18n/index.js';
import {
formatAgentBadgeText,
formatAgentLabel,
getAgentBadgeClass,
} from '../store/telemetryStore.js';
export const STEP_COLUMN_KEYS = Object.freeze([
'step',
'time',
'model',
'tps',
'ttft',
'duration',
'tokens_combo',
'input_tokens',
'cache_tokens',
'output_tokens',
'cache',
'cost',
]);
export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([
'step',
'model',
'tps',
'ttft',
'tokens_combo',
'cache',
'cost',
]);
function formatStepClockTime(createdAtMs) {
const ms = Number(createdAtMs || 0);
if (!(ms > 0) || !Number.isFinite(ms)) {
return { text: '—', title: '' };
}
const d = new Date(ms);
const pad = (n) => String(n).padStart(2, '0');
const hhmmss = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
const full = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hhmmss}`;
return { text: hhmmss, title: full };
}
export const STEP_COLUMN_REGISTRY = Object.freeze({
step: {
key: 'step',
thLabel: () => t('stepCol.step.th'),
optLabel: () => t('stepCol.step.opt'),
sigPart: (st, ctx) =>
`${ctx.hasSubagents}:${ctx.scopeSigKey}:${st.agentId || 'main'}:${st.stepIndex}:${st.agentBadge || ''}:${st.agentLabel || ''}`,
createCell: () => {
const agentBadgeEl = h('span', {
className: 'agent-badge is-clickable',
hidden: true,
style: 'margin-right: 4px;',
});
const stepNumText = h('span');
const td = h('td', {}, [agentBadgeEl, stepNumText]);
return { td, refs: { agentBadgeEl, stepNumText } };
},
updateCell: (refs, st, ctx) => {
const { hasSubagents, effectiveScopes, onSelectAgentScopes } = ctx;
patchAttr(refs.agentBadgeEl, 'hidden', !hasSubagents);
if (hasSubagents) {
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
patchAttr(refs.agentBadgeEl, 'class', `agent-badge is-clickable ${badgeCls}`);
const badgeText = isEnglishLocale()
? formatAgentBadgeText({
isMain: !st.isSubagent,
index: st.agentIndex || 0,
badgeText: st.agentBadge,
})
: st.agentBadge || (st.isSubagent ? '子' : '主');
patchText(refs.agentBadgeEl, badgeText);
const targetScope = st.agentId || 'main';
const isSoleTarget =
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
const agentName = isEnglishLocale()
? formatAgentLabel({
isMain: !st.isSubagent,
index: st.agentIndex || 0,
role: st.agentRole || '',
})
: st.agentLabel || t('steps.unitAgent');
patchAttr(
refs.agentBadgeEl,
'title',
isSoleTarget
? t('steps.badgeBackAll')
: t('steps.badgeFilterAgent', { agent: agentName })
);
refs.agentBadgeEl.onclick = (e) => {
if (typeof onSelectAgentScopes !== 'function') return;
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
const next = effectiveScopes.includes(targetScope)
? effectiveScopes.filter((id) => id !== targetScope)
: [...effectiveScopes, targetScope];
onSelectAgentScopes(next.length > 0 ? next : ['all']);
} else {
onSelectAgentScopes(isSoleTarget ? ['all'] : [targetScope]);
}
};
}
patchText(refs.stepNumText, `#${Number(st.stepIndex)}`);
},
},
time: {
key: 'time',
thLabel: () => t('stepCol.time.th'),
optLabel: () => t('stepCol.time.opt'),
sigPart: (st) => `${st.createdAtMs || 0}`,
createCell: () => {
const td = h('td', { className: 'text-muted' });
return { td, refs: { td } };
},
updateCell: (refs, st) => {
const { text, title } = formatStepClockTime(st.createdAtMs);
patchText(refs.td, text);
patchAttr(refs.td, 'title', title || null);
},
},
model: {
key: 'model',
thLabel: () => t('stepCol.model.th'),
optLabel: () => t('stepCol.model.opt'),
sigPart: (st, ctx) => {
const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
return `${disp.text}:${disp.title}`;
},
createCell: () => {
const td = h('td', {
style: 'max-width: 120px; overflow: hidden; text-overflow: ellipsis;',
});
return { td, refs: { td } };
},
updateCell: (refs, st, ctx) => {
const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
patchText(refs.td, modelDisplay.text);
patchAttr(refs.td, 'title', modelDisplay.title);
},
},
tps: {
key: 'tps',
thLabel: () => t('stepCol.tps.th'),
optLabel: () => t('stepCol.tps.opt'),
sigPart: (st) => `${st.tokPerSec}:${st.selectedSpeedReason || ''}`,
createCell: () => {
const speedMain = h('strong', {
className: 'cell-value accent-speed',
style: 'font-size: var(--fs-base-sm);',
});
const speedReason = h('div', {
className: 'text-muted',
style: 'font-size: var(--fs-2xs);',
});
const td = h('td', {}, [speedMain, speedReason]);
return { td, refs: { speedMain, speedReason } };
},
updateCell: (refs, st) => {
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
const reason = speedReasonText(st.selectedSpeedReason);
patchText(refs.speedReason, reason);
patchAttr(refs.speedReason, 'hidden', !reason);
},
},
ttft: {
key: 'ttft',
thLabel: () => t('stepCol.ttft.th'),
optLabel: () => t('stepCol.ttft.opt'),
sigPart: (st) => `${st.ttftSec}`,
createCell: () => {
const td = h('td');
return { td, refs: { td } };
},
updateCell: (refs, st) => {
patchText(refs.td, formatMetric(st.ttftSec, 's'));
},
},
duration: {
key: 'duration',
thLabel: () => t('stepCol.duration.th'),
optLabel: () => t('stepCol.duration.opt'),
sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`,
createCell: () => {
const td = h('td');
return { td, refs: { td } };
},
updateCell: (refs, st) => {
const dur = st.totalDurationSec ?? st.streamDurationSec ?? null;
patchText(refs.td, formatMetric(dur, 's'));
},
},
tokens_combo: {
key: 'tokens_combo',
thLabel: () => t('stepCol.tokens_combo.th'),
optLabel: () => t('stepCol.tokens_combo.opt'),
sigPart: (st) =>
`${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`,
createCell: () => {
const td = h('td');
return { td, refs: { td } };
},
updateCell: (refs, st) => {
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.td,
`${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}`
);
patchAttr(
refs.td,
'title',
t('steps.ctxTitle', {
ctx: Math.round(Number(st.contextTokens || 0)),
think: Math.round(thinkTok),
resp: Math.round(respTok),
})
);
},
},
input_tokens: {
key: 'input_tokens',
thLabel: () => t('stepCol.input_tokens.th'),
optLabel: () => t('stepCol.input_tokens.opt'),
sigPart: (st) => `${st.inputTokens || 0}`,
createCell: () => {
const td = h('td');
return { td, refs: { td } };
},
updateCell: (refs, st) => {
patchText(refs.td, formatTokens(st.inputTokens || 0));
},
},
cache_tokens: {
key: 'cache_tokens',
thLabel: () => t('stepCol.cache_tokens.th'),
optLabel: () => t('stepCol.cache_tokens.opt'),
sigPart: (st) => `${st.cacheReadTokens || 0}`,
createCell: () => {
const td = h('td');
return { td, refs: { td } };
},
updateCell: (refs, st) => {
patchText(refs.td, formatTokens(st.cacheReadTokens || 0));
},
},
output_tokens: {
key: 'output_tokens',
thLabel: () => t('stepCol.output_tokens.th'),
optLabel: () => t('stepCol.output_tokens.opt'),
sigPart: (st) => `${st.outputTokens || 0}`,
createCell: () => {
const td = h('td');
return { td, refs: { td } };
},
updateCell: (refs, st) => {
patchText(refs.td, formatTokens(st.outputTokens || 0));
},
},
cache: {
key: 'cache',
thLabel: () => t('stepCol.cache.th'),
optLabel: () => t('stepCol.cache.opt'),
sigPart: (st) => `${st.cacheHitPct ?? 0}`,
createCell: () => {
const td = h('td', {
className: 'cell-value accent-ok',
style: 'font-size: var(--fs-base-sm);',
});
return { td, refs: { td } };
},
updateCell: (refs, st) => {
patchText(refs.td, `${Number(st.cacheHitPct ?? 0)}%`);
},
},
cost: {
key: 'cost',
thLabel: () => t('stepCol.cost.th'),
optLabel: () => t('stepCol.cost.opt'),
sigPart: (st) => `${st.costUsd}`,
createCell: () => {
const td = h('td', { style: 'font-weight: 600;' });
return { td, refs: { td } };
},
updateCell: (refs, st) => {
const costVal = st.costUsd;
patchText(refs.td, formatUsd(costVal, { precise: true }));
patchClasses(refs.td, { 'accent-speed': costVal >= 0.15 });
},
},
});
export function getStepColumnOptions() {
return STEP_COLUMN_KEYS.map((key) => ({
value: key,
label: STEP_COLUMN_REGISTRY[key].optLabel(),
}));
}
@@ -0,0 +1,186 @@
/**
* @fileoverview Decoupled Overview & Hover Widget Registry (`widgetRegistry.js`).
* Maps module keys (`metrics`, `context`, `quotas`, `live_tasks`) to standalone
* widget components and provides `createDynamicWidgetHost` for zero-hardcode mounting,
* live reordering, and clean instance disposal.
*/
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
import { t } from '../i18n/index.js';
export const OVERVIEW_WIDGET_KEYS = Object.freeze([
'metrics',
'context',
'quotas',
'live_tasks',
]);
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
metrics: {
key: 'metrics',
labelKey: 'module.metrics',
create: ({ mode, isVisibleFn }) => MetricMatrixWidget({ mode, isVisibleFn }),
},
context: {
key: 'context',
labelKey: 'module.context',
create: ({ mode, isVisibleFn }) =>
ContextWindowWidget({
interactiveInspector: mode !== 'hover',
isVisibleFn,
}),
},
quotas: {
key: 'quotas',
labelKey: 'module.quotas',
create: ({ mode }) =>
QuotaPoolsWidget({
compactHover: mode === 'hover',
}),
},
live_tasks: {
key: 'live_tasks',
labelKey: 'module.live_tasks',
create: ({ mode, isVisibleFn }) =>
LiveActivityWidget({
interactive: mode !== 'hover',
isVisibleFn,
}),
},
});
export function getOverviewModuleOptions() {
return OVERVIEW_WIDGET_KEYS.map((key) => ({
value: key,
label: t(`module.${key}`),
}));
}
/**
* Create a dynamic container host that mounts, reorders, updates, and disposes
* standalone telemetry widgets based on user-configured module keys.
*
* @param {{
* containerEl: HTMLElement,
* mode?: 'overview' | 'hover',
* isVisibleFn?: () => boolean,
* initialModuleKeys?: string[]
* }} options
*/
export function createDynamicWidgetHost({
containerEl,
mode = 'overview',
isVisibleFn = () => true,
initialModuleKeys = [],
}) {
const instances = new Map();
let currentKeys = [];
function syncModules(nextKeys) {
const validKeys = [];
const seen = new Set();
for (const rawKey of Array.isArray(nextKeys) ? nextKeys : []) {
const k = String(rawKey || '').trim();
if (!k || seen.has(k) || !OVERVIEW_WIDGET_REGISTRY[k]) continue;
seen.add(k);
validKeys.push(k);
}
// Remove and destroy widgets no longer present
for (const [existingKey, inst] of [...instances.entries()]) {
if (!seen.has(existingKey)) {
try {
inst.el?.remove?.();
} catch {}
try {
inst.destroy?.();
} catch {}
instances.delete(existingKey);
}
}
// Instantiate newly added widgets
for (const key of validKeys) {
if (!instances.has(key)) {
const inst = OVERVIEW_WIDGET_REGISTRY[key].create({ mode, isVisibleFn });
instances.set(key, inst);
}
}
// Reorder DOM nodes in containerEl only where needed
const orderChanged =
validKeys.length !== currentKeys.length ||
validKeys.some((k, idx) => currentKeys[idx] !== k) ||
(containerEl.children && containerEl.children.length !== validKeys.length);
if (orderChanged) {
for (let i = 0; i < validKeys.length; i += 1) {
const targetEl = instances.get(validKeys[i]).el;
const curChild = containerEl.children ? containerEl.children[i] : null;
if (curChild !== targetEl) {
if (curChild && typeof containerEl.insertBefore === 'function') {
containerEl.insertBefore(targetEl, curChild);
} else {
containerEl.appendChild(targetEl);
}
}
}
currentKeys = [...validKeys];
}
return validKeys;
}
function update({ moduleKeys = [], data = null, minuteTick = undefined } = {}) {
const validKeys = syncModules(moduleKeys);
for (const key of validKeys) {
const inst = instances.get(key);
inst?.refs?.update?.({ data, minuteTick });
}
}
function pauseTickers() {
for (const inst of instances.values()) {
inst?.refs?.pauseTicker?.();
}
}
function resumeTickers() {
for (const inst of instances.values()) {
inst?.refs?.resumeTicker?.();
}
}
function getInstance(key) {
return instances.get(key) || null;
}
function destroy() {
for (const inst of instances.values()) {
try {
inst.el?.remove?.();
} catch {}
try {
inst.destroy?.();
} catch {}
}
instances.clear();
currentKeys = [];
}
if (Array.isArray(initialModuleKeys) && initialModuleKeys.length > 0) {
syncModules(initialModuleKeys);
}
return {
update,
pauseTickers,
resumeTickers,
getInstance,
getActiveKeys: () => [...currentKeys],
destroy,
};
}