From 2db06050be9f6ef86100390bbf63f820f2430de0 Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Sun, 15 Nov 2026 18:19:36 +0900 Subject: [PATCH] fix(panel): reconcile context window breakdown with API tokens and decouple agent badge from step column --- sidecars/panel/app.js | 231 ++++++++++-------- sidecars/panel/backend/local-scanner.mjs | 34 ++- sidecars/panel/backend/telemetry-builder.mjs | 189 ++++++++++++-- sidecars/panel/index.html | 4 +- sidecars/panel/speed-metrics.mjs | 63 ++++- .../src/registries/stepColumnRegistry.js | 162 +++++------- sidecars/panel/src/views/StepsDetailView.js | 78 +++++- sidecars/panel/test/backend.test.mjs | 174 +++++++++++++ sidecars/panel/test/speed-metrics.test.mjs | 51 +++- sidecars/panel/test/window-bridge.test.mjs | 41 +++- 10 files changed, 784 insertions(+), 243 deletions(-) diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 40ef87d..f5b4bb9 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -10016,65 +10016,14 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ key: 'step', thLabel: () => t('stepCol.step.th'), optLabel: () => t('stepCol.step.opt'), - sigPart: (st, ctx) => - `${Boolean(ctx.showAgentBadge)}:${ctx.scopeSigKey}:${st.agentId || 'main'}:${st.stepIndex}:${st.agentBadge || ''}:${st.agentLabel || ''}`, + sigPart: (st) => `${st.stepIndex}`, 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 } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, - updateCell: (refs, st, ctx) => { - const { showAgentBadge, effectiveScopes, onSelectAgentScopes } = ctx; - patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge); - if (showAgentBadge) { - 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]); - } - }; - } else { - refs.agentBadgeEl.onclick = null; - } - patchText(refs.stepNumText, `#${Number(st.stepIndex)}`); + updateCell: (refs, st) => { + patchText(refs.valEl, `#${Number(st.stepIndex)}`); }, }, @@ -10084,12 +10033,13 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.time.opt'), sigPart: (st) => `${st.createdAtMs || 0}`, createCell: () => { - const td = h('td', { className: 'text-muted' }); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', { className: 'text-muted' }, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const { text, title } = formatStepClockTime(st.createdAtMs); - patchText(refs.td, text); + patchText(refs.valEl, text); patchAttr(refs.td, 'title', title || null); }, }, @@ -10103,14 +10053,16 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ return `${disp.text}:${disp.title}`; }, createCell: () => { - const td = h('td', { - style: 'max-width: 120px; overflow: hidden; text-overflow: ellipsis;', + const valEl = h('span', { + style: + 'display: inline-block; max-width: 120px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom;', }); - return { td, refs: { td } }; + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st, ctx) => { const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); - patchText(refs.td, modelDisplay.text); + patchText(refs.valEl, modelDisplay.text); patchAttr(refs.td, 'title', modelDisplay.title); }, }, @@ -10129,8 +10081,13 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ className: 'text-muted', style: 'font-size: var(--fs-2xs);', }); - const td = h('td', {}, [speedMain, speedReason]); - return { td, refs: { speedMain, speedReason } }; + const wrapEl = h( + 'span', + { style: 'display: inline-block; vertical-align: middle;' }, + [speedMain, speedReason] + ); + const td = h('td', {}, [wrapEl]); + return { td, refs: { td, speedMain, speedReason } }; }, updateCell: (refs, st) => { patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); @@ -10146,11 +10103,12 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.ttft.opt'), sigPart: (st) => `${st.ttftSec}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatMetric(st.ttftSec, 's')); + patchText(refs.valEl, formatMetric(st.ttftSec, 's')); }, }, @@ -10160,12 +10118,13 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.duration.opt'), sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const dur = st.totalDurationSec ?? st.streamDurationSec ?? null; - patchText(refs.td, formatMetric(dur, 's')); + patchText(refs.valEl, formatMetric(dur, 's')); }, }, @@ -10176,8 +10135,9 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ sigPart: (st) => `${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const outTok = Math.max(0, Number(st.outputTokens || 0)); @@ -10187,7 +10147,7 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); patchText( - refs.td, + refs.valEl, `${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}` ); patchAttr( @@ -10208,11 +10168,12 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.input_tokens.opt'), sigPart: (st) => `${st.inputTokens || 0}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatTokens(st.inputTokens || 0)); + patchText(refs.valEl, formatTokens(st.inputTokens || 0)); }, }, @@ -10222,11 +10183,12 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.cache_tokens.opt'), sigPart: (st) => `${st.cacheReadTokens || 0}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatTokens(st.cacheReadTokens || 0)); + patchText(refs.valEl, formatTokens(st.cacheReadTokens || 0)); }, }, @@ -10236,11 +10198,12 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.output_tokens.opt'), sigPart: (st) => `${st.outputTokens || 0}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatTokens(st.outputTokens || 0)); + patchText(refs.valEl, formatTokens(st.outputTokens || 0)); }, }, @@ -10250,14 +10213,19 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ 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 } }; + const valEl = h('span'); + const td = h( + 'td', + { + className: 'cell-value accent-ok', + style: 'font-size: var(--fs-base-sm);', + }, + [valEl] + ); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, `${Number(st.cacheHitPct ?? 0)}%`); + patchText(refs.valEl, `${Number(st.cacheHitPct ?? 0)}%`); }, }, @@ -10267,12 +10235,13 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.cost.opt'), sigPart: (st) => `${st.costUsd}`, createCell: () => { - const td = h('td', { style: 'font-weight: 600;' }); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', { style: 'font-weight: 600;' }, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const costVal = st.costUsd; - patchText(refs.td, formatUsd(costVal, { precise: true })); + patchText(refs.valEl, formatUsd(costVal, { precise: true })); patchClasses(refs.td, { 'accent-speed': costVal >= 0.15 }); }, }, @@ -14341,7 +14310,8 @@ const StepsDetailView = defineComponent({ const parts = colKeys .map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)) .join('|'); - return `${locale}:${colOrderSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const badgeSig = `${showAgentBadge}:${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`; + return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: () => { const tr = h('tr'); @@ -14352,6 +14322,11 @@ const StepsDetailView = defineComponent({ { className: 'turn-rail', 'aria-hidden': 'true', hidden: true }, [railLineEl, railDotEl] ); + const agentBadgeEl = h('span', { + className: 'agent-badge is-clickable', + hidden: true, + style: 'margin-right: 4px;', + }); return { el: tr, refs: { @@ -14360,6 +14335,7 @@ const StepsDetailView = defineComponent({ railEl, railLineEl, railDotEl, + agentBadgeEl, hoverTd: null, }, }; @@ -14379,6 +14355,9 @@ const StepsDetailView = defineComponent({ if (refs.railEl.parentNode === entry.td) { entry.td.removeChild(refs.railEl); } + if (refs.agentBadgeEl.parentNode === entry.td) { + entry.td.removeChild(refs.agentBadgeEl); + } tr.removeChild(entry.td); refs.cellMap.delete(oldColKey); } @@ -14404,8 +14383,59 @@ const StepsDetailView = defineComponent({ const firstColKey = colKeys[0]; const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null; - if (firstTd && refs.railEl.parentNode !== firstTd) { - firstTd.insertBefore(refs.railEl, firstTd.firstChild); + if (firstTd) { + if (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl) { + firstTd.insertBefore(refs.railEl, firstTd.firstChild); + } + const afterRail = refs.railEl.nextSibling ?? firstTd.children[1] ?? null; + if (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) { + firstTd.insertBefore(refs.agentBadgeEl, afterRail); + } + } + + patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge || !firstTd); + if (showAgentBadge && firstTd) { + 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 applyAgentScopesSelection !== '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]; + applyAgentScopesSelection(next.length > 0 ? next : ['all']); + } else { + applyAgentScopesSelection(isSoleTarget ? ['all'] : [targetScope]); + } + }; + } else { + refs.agentBadgeEl.onclick = null; } const showRowRail = Boolean(railActive && hasTurn && firstTd); @@ -14426,8 +14456,7 @@ const StepsDetailView = defineComponent({ }); } - const stepEntry = refs.cellMap.get('step') || null; - const targetHoverTd = stepEntry ? stepEntry.td : firstTd; + const targetHoverTd = firstTd; if (refs.hoverTd && refs.hoverTd !== targetHoverTd) { refs.hoverTd.onmouseenter = null; refs.hoverTd.onmousemove = null; @@ -14436,8 +14465,8 @@ const StepsDetailView = defineComponent({ refs.hoverTd = targetHoverTd; if (targetHoverTd) { - if (stepEntry) { - const badgeEl = stepEntry.refs.agentBadgeEl; + const badgeEl = refs.agentBadgeEl; + if (firstColKey === 'step') { targetHoverTd.onmouseenter = (ev) => { if (!showRowRail || !prompt || ev?.target === badgeEl) { hideTurnTip(); @@ -14454,7 +14483,7 @@ const StepsDetailView = defineComponent({ } else { targetHoverTd.onmouseenter = null; targetHoverTd.onmousemove = (ev) => { - if (!showRowRail || !prompt) { + if (!showRowRail || !prompt || ev?.target === badgeEl) { hideTurnTip(); return; } diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index a0269b1..f6fe4db 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -879,6 +879,7 @@ export async function enumerateAndSyncConversations({ contextLimitTelemetry: true, speedClearedTelemetry: true, turnRailTelemetry: true, + contextGroupsTelemetry: true, steps, subagentRefs, }; @@ -902,6 +903,7 @@ export async function enumerateAndSyncConversations({ !prev.contextLimitTelemetry || !prev.speedClearedTelemetry || !prev.turnRailTelemetry || + !prev.contextGroupsTelemetry || metaChanged || JSON.stringify(prev.steps) !== JSON.stringify(steps); @@ -956,6 +958,27 @@ export async function enumerateAndSyncConversations({ if (!lastCachedStep) return false; return !Object.prototype.hasOwnProperty.call(lastCachedStep, 'turnIndex'); } + function hasDroppedContextGroups(cached) { + if (cached?.contextGroupsTelemetry) return false; + const steps = cached?.steps || []; + for (let i = steps.length - 1; i >= 0; i--) { + const st = steps[i]; + if (!st || st.isCompactionStep) break; + if (st.contextBreakdown) { + const cb = st.contextBreakdown; + const cbSum = + Number(cb.totalTokens || 0) || + Number(cb.messagesTokens || 0) + + Number(cb.systemToolsTokens || 0) + + Number(cb.mcpToolsTokens || 0) + + Number(cb.skillsTokens || 0) + + Number(cb.systemPromptTokens || 0) + + Number(cb.userRulesTokens || 0); + return Number(st.estimatedContextTokens || 0) > cbSum; + } + } + return false; + } let remainingTimingRefreshes = LEGACY_MIGRATION_BATCH_SIZE; const toFetch = rawConversations.filter((conv) => { @@ -969,7 +992,12 @@ export async function enumerateAndSyncConversations({ lowerCid === selectedRootId || Boolean(conv.rootConversationId && conv.rootConversationId.toLowerCase() === selectedRootId); if (!cached.contextLimitTelemetry && lowerCid === contextTelemetryCascadeId) return true; - if ((!cached.turnRailTelemetry || hasMissingTurnRailFields(cached)) && isSelectedFamily) { + if ( + (!cached.turnRailTelemetry || + hasMissingTurnRailFields(cached) || + hasDroppedContextGroups(cached)) && + isSelectedFamily + ) { return true; } const hasCurrentSchema = String(cached.signature || '').startsWith( @@ -1087,7 +1115,9 @@ export async function enumerateAndSyncConversations({ String(existingSubCache.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && !hasMissingStepFields(existingSubCache) && (!isSelectedSubFamily || - (Boolean(existingSubCache.turnRailTelemetry) && !hasMissingTurnRailFields(existingSubCache))); + (Boolean(existingSubCache.turnRailTelemetry) && + !hasMissingTurnRailFields(existingSubCache) && + !hasDroppedContextGroups(existingSubCache))); if (hasValidSubCache) { let subMetaUpdated = false; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index ebcf362..2d4d0c9 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -165,7 +165,7 @@ function enrichActiveConversationSteps( inCostUsd: inCostUsd === null ? null : +inCostUsd.toFixed(4), cacheCostUsd: cacheCostUsd === null ? null : +cacheCostUsd.toFixed(4), outCostUsd: outCostUsd === null ? null : +outCostUsd.toFixed(4), - contextTokens: st.inputTokens + st.cacheReadTokens + st.outputTokens, + contextTokens: st.inputTokens + st.cacheReadTokens + resolveStepOutputTokens(st), }; }); @@ -211,9 +211,78 @@ function enrichActiveConversationSteps( }; } +const CONTEXT_CHANNEL_KEYS = [ + 'userInput', + 'assistant', + 'toolResults', + 'subagent', + 'checkpoint', + 'systemTools', + 'mcpTools', + 'skills', + 'systemPrompt', + 'userRules', +]; + +function resolveStepOutputTokens(st) { + const explicitOut = Number(st?.outputTokens || 0); + if (explicitOut > 0) return explicitOut; + return Number(st?.thinkingTokens || 0) + Number(st?.responseTokens || 0); +} + +/** + * 使用最大余数法(Hamilton 方法)将各非零上下文分桶等比缩放至目标整数总和, + * 保证 0 值通道绝不被凭空分配 Token,且缩放后各分桶之和精确等于 `targetTotal`。 + */ +function scaleBucketsExact(buckets, keys, targetTotal) { + const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0))); + const out = {}; + let currentSum = 0; + for (const k of keys) { + const val = Math.max(0, Number(buckets[k] || 0)); + out[k] = val; + currentSum += val; + } + if (safeTarget === 0 || currentSum <= 0) { + for (const k of keys) out[k] = 0; + return out; + } + if (currentSum === safeTarget) { + for (const k of keys) out[k] = Math.round(out[k]); + return out; + } + const remainders = []; + let assigned = 0; + for (const k of keys) { + const rawVal = out[k]; + if (rawVal <= 0) { + out[k] = 0; + continue; + } + const exact = (rawVal * safeTarget) / currentSum; + const floored = Math.floor(exact); + out[k] = floored; + assigned += floored; + remainders.push({ key: k, rem: exact - floored, orig: rawVal }); + } + let diff = safeTarget - assigned; + if (diff > 0 && remainders.length > 0) { + remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig); + for (let i = 0; i < diff; i++) { + out[remainders[i % remainders.length].key] += 1; + } + } + return out; +} + /** * 从当前活跃会话的最新步骤提取上下文 10 通道拆解、自动压缩水位与缓存命中率。 * + * `chatStartMetadata.contextWindowMetadata` 记录在步骤请求发送前且基于宿主离线估算器: + * 1. 先按该步模型 API 真实计费输入(`inputTokens + cacheReadTokens`)对请求前 10 通道做等比整数对齐,消除离线估算偏差; + * 2. 再将该步自身新生成的输出(`outputTokens`)补入 `assistantTokens`,并滚动推进后续无独立拆解的步骤, + * 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致。 + * * @param {object[]} enrichedActiveSteps * @param {object|null} latestEnriched * @param {number} sessionInputTokens @@ -226,6 +295,7 @@ function extractActiveContextTelemetry( sessionCacheReadTokens ) { let latestBreakdown = latestEnriched?.contextBreakdown || null; + let breakdownIdx = latestBreakdown ? enrichedActiveSteps.length - 1 : -1; if (!latestBreakdown && !latestEnriched?.isCompactionStep) { for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { if (enrichedActiveSteps[i]?.isCompactionStep) { @@ -233,26 +303,92 @@ function extractActiveContextTelemetry( } if (enrichedActiveSteps[i]?.contextBreakdown) { latestBreakdown = enrichedActiveSteps[i].contextBreakdown; + breakdownIdx = i; break; } } } - const ctxMessages = Number(latestBreakdown?.messagesTokens || 0); + const rawMessages = Number(latestBreakdown?.messagesTokens || 0); const hasGranularMsgBreakdown = Boolean(latestBreakdown) && Object.prototype.hasOwnProperty.call(latestBreakdown, 'toolResultsTokens'); - const ctxUserInput = hasGranularMsgBreakdown - ? Number(latestBreakdown?.userInputTokens || 0) - : ctxMessages; - const ctxAssistant = Number(latestBreakdown?.assistantTokens || 0); - const ctxToolResults = Number(latestBreakdown?.toolResultsTokens || 0); - const ctxSubagent = Number(latestBreakdown?.subagentTokens || 0); - const ctxCheckpoint = Number(latestBreakdown?.checkpointTokens || 0); - const ctxSystemTools = Number(latestBreakdown?.systemToolsTokens || 0); - const ctxMcpTools = Number(latestBreakdown?.mcpToolsTokens || 0); - const ctxSkills = Number(latestBreakdown?.skillsTokens || 0); - const ctxSystemPrompt = Number(latestBreakdown?.systemPromptTokens || 0); - const ctxUserRules = Number(latestBreakdown?.userRulesTokens || 0); + let channels = { + userInput: hasGranularMsgBreakdown + ? Number(latestBreakdown?.userInputTokens || 0) + : rawMessages, + assistant: Number(latestBreakdown?.assistantTokens || 0), + toolResults: Number(latestBreakdown?.toolResultsTokens || 0), + subagent: Number(latestBreakdown?.subagentTokens || 0), + checkpoint: Number(latestBreakdown?.checkpointTokens || 0), + systemTools: Number(latestBreakdown?.systemToolsTokens || 0), + mcpTools: Number(latestBreakdown?.mcpToolsTokens || 0), + skills: Number(latestBreakdown?.skillsTokens || 0), + systemPrompt: Number(latestBreakdown?.systemPromptTokens || 0), + userRules: Number(latestBreakdown?.userRulesTokens || 0), + }; + const msgSubtotal = + channels.userInput + + channels.assistant + + channels.toolResults + + channels.subagent + + channels.checkpoint; + if (rawMessages > msgSubtotal) { + channels.userInput += rawMessages - msgSubtotal; + } + const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0); + + if ( + latestBreakdown && + breakdownIdx >= 0 && + !latestEnriched?.isCompactionStep && + rawBreakdownTotal > 0 + ) { + const bdStep = enrichedActiveSteps[breakdownIdx]; + const bdPromptTokens = + Number(bdStep?.inputTokens || 0) + Number(bdStep?.cacheReadTokens || 0); + const bdOutTokens = resolveStepOutputTokens(bdStep); + // 仅当模型 API 返回了完整的请求级输入(排除省略 cacheReadTokens 的残缺网关或极小合成桩数据)时对齐至真实分词口径 + if (bdPromptTokens >= rawBreakdownTotal * 0.5) { + channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, bdPromptTokens); + channels.assistant += bdOutTokens; + let runningTotal = bdPromptTokens + bdOutTokens; + + for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) { + const stepM = enrichedActiveSteps[m]; + if (!stepM || stepM.isCompactionStep) break; + const mPrompt = + Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); + const mOut = resolveStepOutputTokens(stepM); + if (mPrompt >= runningTotal * 0.5) { + if (mPrompt > runningTotal) { + const delta = mPrompt - runningTotal; + if (enrichedActiveSteps[m - 1]?.hasToolCalls) { + channels.toolResults += delta; + } else { + channels.userInput += delta; + } + } else if (mPrompt < runningTotal) { + channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt); + } + channels.assistant += mOut; + runningTotal = mPrompt + mOut; + } + } + } + } + + const ctxUserInput = channels.userInput; + const ctxAssistant = channels.assistant; + const ctxToolResults = channels.toolResults; + const ctxSubagent = channels.subagent; + const ctxCheckpoint = channels.checkpoint; + const ctxMessages = + ctxUserInput + ctxAssistant + ctxToolResults + ctxSubagent + ctxCheckpoint; + const ctxSystemTools = channels.systemTools; + const ctxMcpTools = channels.mcpTools; + const ctxSkills = channels.skills; + const ctxSystemPrompt = channels.systemPrompt; + const ctxUserRules = channels.userRules; const ctxBreakdownTotal = ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules; @@ -260,11 +396,12 @@ function extractActiveContextTelemetry( const ctxFreshInput = latestEnriched?.inputTokens || 0; const ctxThinking = latestEnriched?.thinkingTokens || 0; const ctxResponse = latestEnriched?.responseTokens || 0; + const ctxOut = resolveStepOutputTokens(latestEnriched); const ctxTotal = - ctxBreakdownTotal > 0 ? ctxBreakdownTotal : ctxCached + ctxFreshInput + ctxThinking + ctxResponse; + ctxBreakdownTotal > 0 ? ctxBreakdownTotal : ctxCached + ctxFreshInput + ctxOut; const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000); const compactionUsedTokens = Number( - latestEnriched?.estimatedContextTokens || ctxBreakdownTotal || ctxCached + ctxFreshInput + ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput ); const compactionUsedPct = compactionLimitTokens > 0 @@ -943,13 +1080,21 @@ export async function buildTelemetryPayloadInternal( Number(cb.systemPromptTokens || 0) + Number(cb.userRulesTokens || 0) : 0; - const fallbackTotal = - Number(lastRootStep.inputTokens || 0) + - Number(lastRootStep.cacheReadTokens || 0) + - Number(lastRootStep.thinkingTokens || 0) + - Number(lastRootStep.responseTokens || 0); + const apiPrompt = + Number(lastRootStep.inputTokens || 0) + Number(lastRootStep.cacheReadTokens || 0); + const apiOut = resolveStepOutputTokens(lastRootStep); + const fallbackTotal = apiPrompt + apiOut; + const estTotal = Math.max(cbTotal, Number(lastRootStep.estimatedContextTokens || 0)); + const hasAlignedApiPrompt = + !lastRootStep.isCompactionStep && + apiPrompt > 0 && + (estTotal === 0 || apiPrompt >= estTotal * 0.5); const usedTokens = Number( - cbTotal > 0 ? cbTotal : lastRootStep.estimatedContextTokens || fallbackTotal + hasAlignedApiPrompt + ? fallbackTotal + : cbTotal > 0 + ? cbTotal + : lastRootStep.estimatedContextTokens || fallbackTotal ); contextUsedPct = limitTokens > 0 ? Math.min(100, +((usedTokens / limitTokens) * 100).toFixed(1)) : 0; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index ddd2105..a606a3c 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/speed-metrics.mjs index bc3330e..80ea1c9 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/speed-metrics.mjs @@ -169,15 +169,29 @@ function estimateUtf8Tokens(text) { * @param {unknown} name 分块名称或标题 * @returns {'skills' | 'userRules' | 'mcpTools' | 'systemPrompt'} 归属的上下文分类键名 */ -function classifyPromptSection(name) { - const key = String(name || '').trim().toLowerCase(); +function classifyPromptSection(name, type = '') { + const key = String(name || type || '') + .trim() + .toLowerCase() + .replace(/^token_type_/, '') + .replace(/[\s-]+/g, '_'); if (key === 'skills' || key === 'skill') { return 'skills'; } - if (key === 'user_rules' || key === 'user_rule' || key === 'rules') { + if ( + key === 'user_rules' || + key === 'user_rule' || + key === 'rules' || + key === 'rule' + ) { return 'userRules'; } - if (key === 'mcp_servers' || key === 'mcp' || key.startsWith('mcp_')) { + if ( + key === 'mcp_servers' || + key === 'mcp_tools' || + key === 'mcp' || + key.startsWith('mcp_') + ) { return 'mcpTools'; } return 'systemPrompt'; @@ -328,7 +342,7 @@ export function extractContextBreakdown(chat) { for (const c of children) { const tok = Math.max(0, Number(c?.numTokens || 0)); childSum += tok; - const bucket = classifyPromptSection(c?.name ?? c?.title); + const bucket = classifyPromptSection(c?.name ?? c?.title, c?.type); if (bucket === 'skills') { skillsTokens += tok; } else if (bucket === 'userRules') { @@ -345,6 +359,32 @@ export function extractContextBreakdown(chat) { } else { systemPromptTokens += gTokens; } + } else if ( + gType === 'TOKEN_TYPE_SKILLS' || + gName === 'skills' || + gName === 'skill' + ) { + hasPromptGroup = true; + skillsTokens += gTokens; + } else if ( + gType === 'TOKEN_TYPE_RULES' || + gType === 'TOKEN_TYPE_USER_RULES' || + gName === 'rules' || + gName === 'user rules' || + gName === 'user_rules' + ) { + hasPromptGroup = true; + userRulesTokens += gTokens; + } else if ( + gType === 'TOKEN_TYPE_SUBAGENTS' || + gType === 'TOKEN_TYPE_PLUGINS' || + gName === 'subagents' || + gName === 'plugins' || + gName === 'featured plugins' || + gName === 'featured_plugins' + ) { + hasPromptGroup = true; + systemPromptTokens += gTokens; } else if ( gType === 'TOKEN_TYPE_TOOLS' || gName === 'tools' || @@ -451,6 +491,19 @@ export function extractContextBreakdown(chat) { } else if (gTokens > 0) { userInputTokens += gTokens; } + } else if (gTokens > 0) { + // 兜底接收未来新增的顶层提示词分组,确保 tokenBreakdown.groups 不丢任何分组 + hasPromptGroup = true; + const fallbackBucket = classifyPromptSection(g?.name, g?.type); + if (fallbackBucket === 'skills') { + skillsTokens += gTokens; + } else if (fallbackBucket === 'userRules') { + userRulesTokens += gTokens; + } else if (fallbackBucket === 'mcpTools') { + mcpToolsTokens += gTokens; + } else { + systemPromptTokens += gTokens; + } } } diff --git a/sidecars/panel/src/registries/stepColumnRegistry.js b/sidecars/panel/src/registries/stepColumnRegistry.js index ea59840..5830384 100644 --- a/sidecars/panel/src/registries/stepColumnRegistry.js +++ b/sidecars/panel/src/registries/stepColumnRegistry.js @@ -13,12 +13,7 @@ import { resolveModelDisplayInfo, speedReasonText, } from '../core/formatters.js'; -import { isEnglishLocale, t } from '../i18n/index.js'; -import { - formatAgentBadgeText, - formatAgentLabel, - getAgentBadgeClass, -} from '../store/telemetryStore.js'; +import { t } from '../i18n/index.js'; export const STEP_COLUMN_KEYS = Object.freeze([ 'step', @@ -62,65 +57,14 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ key: 'step', thLabel: () => t('stepCol.step.th'), optLabel: () => t('stepCol.step.opt'), - sigPart: (st, ctx) => - `${Boolean(ctx.showAgentBadge)}:${ctx.scopeSigKey}:${st.agentId || 'main'}:${st.stepIndex}:${st.agentBadge || ''}:${st.agentLabel || ''}`, + sigPart: (st) => `${st.stepIndex}`, 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 } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, - updateCell: (refs, st, ctx) => { - const { showAgentBadge, effectiveScopes, onSelectAgentScopes } = ctx; - patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge); - if (showAgentBadge) { - 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]); - } - }; - } else { - refs.agentBadgeEl.onclick = null; - } - patchText(refs.stepNumText, `#${Number(st.stepIndex)}`); + updateCell: (refs, st) => { + patchText(refs.valEl, `#${Number(st.stepIndex)}`); }, }, @@ -130,12 +74,13 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.time.opt'), sigPart: (st) => `${st.createdAtMs || 0}`, createCell: () => { - const td = h('td', { className: 'text-muted' }); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', { className: 'text-muted' }, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const { text, title } = formatStepClockTime(st.createdAtMs); - patchText(refs.td, text); + patchText(refs.valEl, text); patchAttr(refs.td, 'title', title || null); }, }, @@ -149,14 +94,16 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ return `${disp.text}:${disp.title}`; }, createCell: () => { - const td = h('td', { - style: 'max-width: 120px; overflow: hidden; text-overflow: ellipsis;', + const valEl = h('span', { + style: + 'display: inline-block; max-width: 120px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom;', }); - return { td, refs: { td } }; + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st, ctx) => { const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' }); - patchText(refs.td, modelDisplay.text); + patchText(refs.valEl, modelDisplay.text); patchAttr(refs.td, 'title', modelDisplay.title); }, }, @@ -175,8 +122,13 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ className: 'text-muted', style: 'font-size: var(--fs-2xs);', }); - const td = h('td', {}, [speedMain, speedReason]); - return { td, refs: { speedMain, speedReason } }; + const wrapEl = h( + 'span', + { style: 'display: inline-block; vertical-align: middle;' }, + [speedMain, speedReason] + ); + const td = h('td', {}, [wrapEl]); + return { td, refs: { td, speedMain, speedReason } }; }, updateCell: (refs, st) => { patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s')); @@ -192,11 +144,12 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.ttft.opt'), sigPart: (st) => `${st.ttftSec}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatMetric(st.ttftSec, 's')); + patchText(refs.valEl, formatMetric(st.ttftSec, 's')); }, }, @@ -206,12 +159,13 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.duration.opt'), sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const dur = st.totalDurationSec ?? st.streamDurationSec ?? null; - patchText(refs.td, formatMetric(dur, 's')); + patchText(refs.valEl, formatMetric(dur, 's')); }, }, @@ -222,8 +176,9 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ sigPart: (st) => `${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const outTok = Math.max(0, Number(st.outputTokens || 0)); @@ -233,7 +188,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ ? Math.max(0, Number(st.responseTokens)) : Math.max(0, outTok - thinkTok); patchText( - refs.td, + refs.valEl, `${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}` ); patchAttr( @@ -254,11 +209,12 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.input_tokens.opt'), sigPart: (st) => `${st.inputTokens || 0}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatTokens(st.inputTokens || 0)); + patchText(refs.valEl, formatTokens(st.inputTokens || 0)); }, }, @@ -268,11 +224,12 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.cache_tokens.opt'), sigPart: (st) => `${st.cacheReadTokens || 0}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatTokens(st.cacheReadTokens || 0)); + patchText(refs.valEl, formatTokens(st.cacheReadTokens || 0)); }, }, @@ -282,11 +239,12 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.output_tokens.opt'), sigPart: (st) => `${st.outputTokens || 0}`, createCell: () => { - const td = h('td'); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', {}, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, formatTokens(st.outputTokens || 0)); + patchText(refs.valEl, formatTokens(st.outputTokens || 0)); }, }, @@ -296,14 +254,19 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ 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 } }; + const valEl = h('span'); + const td = h( + 'td', + { + className: 'cell-value accent-ok', + style: 'font-size: var(--fs-base-sm);', + }, + [valEl] + ); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { - patchText(refs.td, `${Number(st.cacheHitPct ?? 0)}%`); + patchText(refs.valEl, `${Number(st.cacheHitPct ?? 0)}%`); }, }, @@ -313,12 +276,13 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ optLabel: () => t('stepCol.cost.opt'), sigPart: (st) => `${st.costUsd}`, createCell: () => { - const td = h('td', { style: 'font-weight: 600;' }); - return { td, refs: { td } }; + const valEl = h('span'); + const td = h('td', { style: 'font-weight: 600;' }, [valEl]); + return { td, refs: { td, valEl } }; }, updateCell: (refs, st) => { const costVal = st.costUsd; - patchText(refs.td, formatUsd(costVal, { precise: true })); + patchText(refs.valEl, formatUsd(costVal, { precise: true })); patchClasses(refs.td, { 'accent-speed': costVal >= 0.15 }); }, }, diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index 629370c..cdd2f51 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -28,7 +28,9 @@ import { STEP_COLUMN_REGISTRY, } from '../registries/stepColumnRegistry.js'; import { + formatAgentBadgeText, formatAgentLabel, + getAgentBadgeClass, normalizeClientStepColumns, resolveScopedConversation, telemetryStore, @@ -635,7 +637,8 @@ export const StepsDetailView = defineComponent({ const parts = colKeys .map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx)) .join('|'); - return `${locale}:${colOrderSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; + const badgeSig = `${showAgentBadge}:${cellCtx.scopeSigKey}:${st.agentId || 'main'}:${st.agentBadge || ''}:${st.agentLabel || ''}`; + return `${locale}:${colOrderSig}:${badgeSig}:${railActive}:${item.hasTurn}:${item.hasUp}:${item.hasDown}:${item.isStart}:${item.isLatest}:${item.prompt}:${parts}`; }, createRow: () => { const tr = h('tr'); @@ -646,6 +649,11 @@ export const StepsDetailView = defineComponent({ { className: 'turn-rail', 'aria-hidden': 'true', hidden: true }, [railLineEl, railDotEl] ); + const agentBadgeEl = h('span', { + className: 'agent-badge is-clickable', + hidden: true, + style: 'margin-right: 4px;', + }); return { el: tr, refs: { @@ -654,6 +662,7 @@ export const StepsDetailView = defineComponent({ railEl, railLineEl, railDotEl, + agentBadgeEl, hoverTd: null, }, }; @@ -673,6 +682,9 @@ export const StepsDetailView = defineComponent({ if (refs.railEl.parentNode === entry.td) { entry.td.removeChild(refs.railEl); } + if (refs.agentBadgeEl.parentNode === entry.td) { + entry.td.removeChild(refs.agentBadgeEl); + } tr.removeChild(entry.td); refs.cellMap.delete(oldColKey); } @@ -698,8 +710,59 @@ export const StepsDetailView = defineComponent({ const firstColKey = colKeys[0]; const firstTd = firstColKey ? refs.cellMap.get(firstColKey)?.td || null : null; - if (firstTd && refs.railEl.parentNode !== firstTd) { - firstTd.insertBefore(refs.railEl, firstTd.firstChild); + if (firstTd) { + if (refs.railEl.parentNode !== firstTd || firstTd.firstChild !== refs.railEl) { + firstTd.insertBefore(refs.railEl, firstTd.firstChild); + } + const afterRail = refs.railEl.nextSibling ?? firstTd.children[1] ?? null; + if (refs.agentBadgeEl.parentNode !== firstTd || afterRail !== refs.agentBadgeEl) { + firstTd.insertBefore(refs.agentBadgeEl, afterRail); + } + } + + patchAttr(refs.agentBadgeEl, 'hidden', !showAgentBadge || !firstTd); + if (showAgentBadge && firstTd) { + 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 applyAgentScopesSelection !== '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]; + applyAgentScopesSelection(next.length > 0 ? next : ['all']); + } else { + applyAgentScopesSelection(isSoleTarget ? ['all'] : [targetScope]); + } + }; + } else { + refs.agentBadgeEl.onclick = null; } const showRowRail = Boolean(railActive && hasTurn && firstTd); @@ -720,8 +783,7 @@ export const StepsDetailView = defineComponent({ }); } - const stepEntry = refs.cellMap.get('step') || null; - const targetHoverTd = stepEntry ? stepEntry.td : firstTd; + const targetHoverTd = firstTd; if (refs.hoverTd && refs.hoverTd !== targetHoverTd) { refs.hoverTd.onmouseenter = null; refs.hoverTd.onmousemove = null; @@ -730,8 +792,8 @@ export const StepsDetailView = defineComponent({ refs.hoverTd = targetHoverTd; if (targetHoverTd) { - if (stepEntry) { - const badgeEl = stepEntry.refs.agentBadgeEl; + const badgeEl = refs.agentBadgeEl; + if (firstColKey === 'step') { targetHoverTd.onmouseenter = (ev) => { if (!showRowRail || !prompt || ev?.target === badgeEl) { hideTurnTip(); @@ -748,7 +810,7 @@ export const StepsDetailView = defineComponent({ } else { targetHoverTd.onmouseenter = null; targetHoverTd.onmousemove = (ev) => { - if (!showRowRail || !prompt) { + if (!showRowRail || !prompt || ev?.target === badgeEl) { hideTurnTip(); return; } diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index d33ba01..f550446 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -959,3 +959,177 @@ test('assigns unified rootTurnIndex across interleaved main and subagent steps s assert.equal(subSteps[1].isTurnStart, true); assert.equal(subSteps[1].turnPrompt, 'Subagent internal brief'); }); + +test('reconciles 8-group context breakdown with real API prompt+output tokens and auto-refreshes cached dropped groups', async () => { + const stepIndex = 2504; + const createdAt = '2026-11-15T07:55:00Z'; + const finishedAt = '2026-11-15T07:55:56Z'; + const raw311b = { + trajectory: { + steps: [ + { + status: 'CORTEX_STEP_STATUS_DONE', + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex }, + createdAt, + finishedGeneratingAt: finishedAt, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M427', + inputTokens: '4989', + cacheReadTokens: '150223', + outputTokens: '3116', + thinkingOutputTokens: '1573', + responseOutputTokens: '1543', + }, + }, + plannerResponse: { response: 'final answer', thinkingDuration: '12s' }, + }, + ], + generatorMetadata: [ + { + stepIndices: [stepIndex], + chatModel: { + responseModel: 'gemini-4-carbon', + timeToFirstToken: '12.1s', + streamingDuration: '44.6s', + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 148852, + maxContextTokens: 256000, + tokenBreakdown: { + totalTokens: 148852, + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', name: 'System Prompt', numTokens: 5505 }, + { type: 'TOKEN_TYPE_MCP_TOOLS', name: 'Mcp Tools', numTokens: 234 }, + { type: 'TOKEN_TYPE_SUBAGENTS', name: 'Subagents', numTokens: 1741 }, + { type: 'TOKEN_TYPE_SKILLS', name: 'Skills', numTokens: 2201 }, + { type: 'TOKEN_TYPE_PLUGINS', name: 'Plugins', numTokens: 1601 }, + { type: 'TOKEN_TYPE_RULES', name: 'Rules', numTokens: 2282 }, + { type: 'TOKEN_TYPE_TOOLS', name: 'Tools', numTokens: 8857 }, + { + type: 'TOKEN_TYPE_CHAT_MESSAGES', + name: 'Chat Messages', + numTokens: 126431, + children: [ + { name: '2449: CHECKPOINT', numTokens: 5087 }, + { name: '2450: USER_INPUT', numTokens: 281 }, + { name: '2455: SYSTEM_MESSAGE', numTokens: 179 }, + { name: '2502: PLANNER_RESPONSE', numTokens: 15017 }, + { name: '2503: GENERIC', numTokens: 105867 }, + ], + }, + ], + }, + }, + }, + }, + }, + ], + }, + }; + + // Simulate legacy cached entry where SKILLS/RULES/SUBAGENTS/PLUGINS were dropped (141027 < 148852) + const staleCacheEntry = { + signature: `v13-clean:2505:${finishedAt}`, + title: '用量图表与调用记录优化建议', + lastModifiedMs: Date.parse(finishedAt), + contextLimitTelemetry: true, + speedClearedTelemetry: true, + turnRailTelemetry: true, + subagentRefs: [], + steps: [ + { + stepIndex, + isCompactionStep: false, + modelKey: 'MODEL_PLACEHOLDER_M427', + modelSource: 'usage.model', + responseModel: 'gemini-4-carbon', + modelIdentityVersion: 5, + createdAt, + createdAtMs: Date.parse(createdAt), + inputTokens: 4989, + cacheReadTokens: 150223, + outputTokens: 3116, + thinkingTokens: 1573, + responseTokens: 1543, + estimatedContextTokens: 148852, + maxContextBudgetTokens: 256000, + reportedContextLimitTokens: 256000, + turnIndex: 1, + isTurnStart: true, + contextBreakdown: { + messagesTokens: 126431, + userInputTokens: 281, + assistantTokens: 15017, + toolResultsTokens: 105867, + subagentTokens: 179, + checkpointTokens: 5087, + systemToolsTokens: 8857, + mcpToolsTokens: 234, + skillsTokens: 0, + systemPromptTokens: 5505, + userRulesTokens: 0, + totalTokens: 141027, + }, + }, + ], + }; + + const h = backendHarness({ + cache: { c311b: staleCacheEntry }, + trajectories: { c311b: raw311b }, + summaries: { + c311b: { + stepCount: 2505, + lastModifiedTime: finishedAt, + status: 'IDLE', + annotations: { title: '用量图表与调用记录优化建议' }, + }, + }, + }); + + const payload = await h.buildTelemetryPayloadInternal('c311b'); + const ctx = payload.activeConversation.context; + const step0 = payload.activeConversation.recentSteps[0]; + + // Context window total matches step table contextTokens (155,212 prompt + 3,116 output = 158,328) + assert.equal(step0.contextTokens, 158328); + assert.equal(ctx.totalTokens, 158328); + assert.equal(ctx.usedPct, 61.8); + assert.equal(payload.conversations[0].contextUsedPct, 61.8); + + // Previously dropped Skills & User Rules are restored and scaled cleanly + assert.ok(ctx.skillsTokens >= 2290 && ctx.skillsTokens <= 2300, `skills=${ctx.skillsTokens}`); + assert.ok(ctx.userRulesTokens >= 2375 && ctx.userRulesTokens <= 2385, `rules=${ctx.userRulesTokens}`); + assert.ok(ctx.systemPromptTokens >= 9220 && ctx.systemPromptTokens <= 9230, `sys=${ctx.systemPromptTokens}`); + + // All 10 breakdown channels sum exact-to-the-token to ctx.totalTokens (158,328) + const channelSum = + ctx.userInputTokens + + ctx.assistantTokens + + ctx.toolResultsTokens + + ctx.subagentTokens + + ctx.checkpointTokens + + ctx.systemToolsTokens + + ctx.mcpToolsTokens + + ctx.skillsTokens + + ctx.systemPromptTokens + + ctx.userRulesTokens; + assert.equal(channelSum, 158328); + assert.equal( + ctx.messagesTokens, + ctx.userInputTokens + + ctx.assistantTokens + + ctx.toolResultsTokens + + ctx.subagentTokens + + ctx.checkpointTokens + ); + + // Subsequent poll does not re-fetch now that contextGroupsTelemetry is persisted + const fetchCountAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; + assert.equal(fetchCountAfterFirst, 1); + await h.buildTelemetryPayloadInternal('c311b'); + const fetchCountAfterSecond = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; + assert.equal(fetchCountAfterSecond, 1); +}); diff --git a/sidecars/panel/test/speed-metrics.test.mjs b/sidecars/panel/test/speed-metrics.test.mjs index d8f969e..cf06a05 100644 --- a/sidecars/panel/test/speed-metrics.test.mjs +++ b/sidecars/panel/test/speed-metrics.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs'; +import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs'; function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000, thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) { @@ -351,3 +351,52 @@ test('extractModelSteps tracks sequential user turns, merges consecutive prompts assert.equal(steps[3].isTurnStart, true); assert.equal(steps[3].turnPrompt, '第三轮真实提问'); }); + +test('extractContextBreakdown parses split top-level SKILLS, RULES, SUBAGENTS, and PLUGINS groups without dropping tokens', () => { + const breakdown = extractContextBreakdown({ + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 148852, + maxContextTokens: 256000, + tokenBreakdown: { + totalTokens: 148852, + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', name: 'System Prompt', numTokens: 5505 }, + { type: 'TOKEN_TYPE_MCP_TOOLS', name: 'Mcp Tools', numTokens: 234 }, + { type: 'TOKEN_TYPE_SUBAGENTS', name: 'Subagents', numTokens: 1741 }, + { type: 'TOKEN_TYPE_SKILLS', name: 'Skills', numTokens: 2201 }, + { type: 'TOKEN_TYPE_PLUGINS', name: 'Plugins', numTokens: 1601 }, + { type: 'TOKEN_TYPE_RULES', name: 'Rules', numTokens: 2282 }, + { type: 'TOKEN_TYPE_TOOLS', name: 'Tools', numTokens: 8857 }, + { + type: 'TOKEN_TYPE_CHAT_MESSAGES', + name: 'Chat Messages', + numTokens: 126431, + children: [ + { name: '2449: CHECKPOINT', numTokens: 5087 }, + { name: '2450: USER_INPUT', numTokens: 281 }, + { name: '2455: SYSTEM_MESSAGE', numTokens: 179 }, + { name: '2502: PLANNER_RESPONSE', numTokens: 15017 }, + { name: '2503: GENERIC', numTokens: 105867 }, + ], + }, + ], + }, + }, + }, + }); + + assert.ok(breakdown); + assert.equal(breakdown.skillsTokens, 2201); + assert.equal(breakdown.userRulesTokens, 2282); + assert.equal(breakdown.systemPromptTokens, 5505 + 1741 + 1601); + assert.equal(breakdown.mcpToolsTokens, 234); + assert.equal(breakdown.systemToolsTokens, 8857); + assert.equal(breakdown.checkpointTokens, 5087); + assert.equal(breakdown.userInputTokens, 281); + assert.equal(breakdown.subagentTokens, 179); + assert.equal(breakdown.assistantTokens, 15017); + assert.equal(breakdown.toolResultsTokens, 105867); + assert.equal(breakdown.messagesTokens, 126431); + assert.equal(breakdown.totalTokens, 148852); +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index 55a9d3b..54bed41 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -564,6 +564,11 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro get firstChild() { return this.children[0] || null; } get firstElementChild() { return this.children[0] || null; } get lastElementChild() { return this.children[this.children.length - 1] || null; } + get nextSibling() { + if (!this.parentNode) return null; + const idx = this.parentNode.children.indexOf(this); + return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; + } get isConnected() { let cur = this; while (cur) { @@ -1991,9 +1996,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(stepHeaders[4].textContent, '上下文 / 思考 / 正文'); const stepRows = stepsPane.querySelectorAll('.data-table')[0].children[1].children; assert.equal(stepRows.length, 2); - assert.equal(stepRows[0].children[4].textContent, '37.8k / 420 / 265'); + assert.equal(stepRows[0].children[4].children[0].textContent, '37.8k / 420 / 265'); assert.equal(stepRows[0].children[4].getAttribute('title'), '上下文 37800 · 思考 420 · 正文 265'); - assert.equal(stepRows[1].children[4].textContent, '117.7k / 14.5k / 57'); + assert.equal(stepRows[1].children[4].children[0].textContent, '117.7k / 14.5k / 57'); // Verify minimalist Turn Rail (.has-turn-rail, cap & origin dots) and hover prompt preview tooltip const stepsDataTable = stepsPane.querySelectorAll('.data-table')[0]; @@ -2341,10 +2346,40 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Turn rail remains visible independently of [主]/[子] badge switch' ); - // Restore showStepAgentBadge=true before subsequent route tests + // Restore showStepAgentBadge=true and verify [主]/[子] badge + Turn Rail still render in col 0 even when 'step' (步序) column is replaced! pillTabs[3].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 15)); sec3SegControls[1].querySelectorAll('.seg-btn')[0].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 25)); + + // Remove first column 'step' (步序) via .slot-remove-btn[0] so 'model' (模型) becomes column 0 + sec3 + .querySelector('.editable-slot-wrap') + .querySelectorAll('.slot-remove-btn')[0] + .dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 30)); + + pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 15)); + const headerCellsNoStep = stepsPane.querySelectorAll('.data-table')[0].children[0].children[0].children; + assert.equal(headerCellsNoStep[0].textContent, '模型', 'First column is now 模型 after removing 步序'); + assert.equal( + multiStepRows[0].children[0].querySelector('.agent-badge').hasAttribute('hidden'), + false, + '[子1] badge stays visible in leading 模型 column even when 步序 (step) column is absent!' + ); + assert.equal(multiStepRows[0].children[0].querySelector('.agent-badge').textContent, '子1'); + assert.equal(multiStepRows[1].children[0].querySelector('.agent-badge').textContent, '主'); + assert.equal( + multiStepRows[0].children[0].querySelector('.turn-rail').hasAttribute('hidden'), + false, + 'Turn rail also stays visible in leading 模型 column' + ); + + // Reset section 4 back to default columns before subsequent route tests + pillTabs[3].dispatchEvent({ type: 'click', stopPropagation() {} }); + await new Promise((r) => setTimeout(r, 15)); + sec3.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 260)); pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 15));