fix(panel): reconcile context window breakdown with API tokens and decouple agent badge from step column

This commit is contained in:
fish
2026-11-15 18:19:36 +09:00
parent 228031e335
commit 2db06050be
10 changed files with 784 additions and 243 deletions
+174
View File
@@ -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);
});
+50 -1
View File
@@ -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);
});
+38 -3
View File
@@ -564,6 +564,11 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> 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/<uuid> 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/<uuid> 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));