mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
1141 lines
49 KiB
JavaScript
1141 lines
49 KiB
JavaScript
import test from 'node:test';
|
|
import assert from 'node:assert/strict';
|
|
import {backendHarness} from './backend-harness.mjs';
|
|
|
|
const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
|
createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
|
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
|
|
},plannerResponse:{response:'answer',thinkingDuration:'5s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}]}};
|
|
const old={signature:'v5:old',title:'test',steps:[{stepIndex:0,modelKey:'MODEL_PLACEHOLDER_M418',inputTokens:100,cacheReadTokens:200,outputTokens:600,thinkingTokens:100,responseTokens:500,createdAtMs:1767225600000,ttftSec:0.4,streamTokPerSec:200,streamTokens:500,streamDurationSec:2.5,totalDurationSec:10,totalTokPerSec:60}]};
|
|
|
|
test('failed migration retains all accounting, makes legacy speed and TTFT unavailable',async()=>{
|
|
const h=backendHarness({cache:{test:old},trajectories:{test:new Error('offline')}});
|
|
const p=await h.buildTelemetryPayloadInternal('test');
|
|
assert.equal(p.activeConversation.latestTokPerSec,null);
|
|
assert.equal(p.activeConversation.latestTtftSec,null);
|
|
assert.equal(p.activeConversation.avgTokPerSec,null);
|
|
assert.equal(p.activeConversation.recentSteps[0].outputTokens,600);
|
|
assert.equal(p.consumption.session.totalTokens,900);
|
|
assert.equal(p.modelBreakdown[0].avgTokPerSec,null);
|
|
assert.equal(h.state.saves.length,1);
|
|
assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600);
|
|
assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown');
|
|
});
|
|
test('successful migration rebuilds measurements and uses the same mean in both tables',async()=>{
|
|
const h=backendHarness({cache:{test:old},trajectories:{test:raw}});
|
|
const p=await h.buildTelemetryPayloadInternal('test');
|
|
assert.equal(p.activeConversation.latestTokPerSec,60);
|
|
assert.equal(p.activeConversation.latestTtftSec,3);
|
|
assert.equal(p.activeConversation.avgTokPerSec,60);
|
|
assert.equal(p.modelBreakdown[0].avgTokPerSec,60);
|
|
assert.equal(p.modelBreakdown[0].speedSummary.sampleCount,1);
|
|
assert.equal(p.consumption.session.totalTokens,900);
|
|
assert.match(h.state.saves[0].data.test.signature,/^v10-model-identity:/);
|
|
});
|
|
test('a legacy stream setting cannot re-enable mixed speed formulas',async()=>{
|
|
const h=backendHarness({cache:{test:old},trajectories:{test:raw},settings:{speedMode:'stream'}});
|
|
const p=await h.buildTelemetryPayloadInternal('test');
|
|
assert.equal(p.activeConversation.latestTokPerSec,60);
|
|
assert.equal(p.activeConversation.avgTokPerSec,60);
|
|
assert.equal(p.modelBreakdown[0].avgTokPerSec,60);
|
|
assert.equal(p.settings.speedMode,undefined);
|
|
});
|
|
test('a malformed successful RPC cannot erase previously recorded usage',async()=>{
|
|
const h=backendHarness({cache:{test:old},trajectories:{test:{}}});
|
|
const p=await h.buildTelemetryPayloadInternal('test');
|
|
assert.equal(p.consumption.session.totalTokens,900);
|
|
assert.equal(p.activeConversation.latestTtftSec,null);
|
|
assert.equal(h.state.saves.length,1);
|
|
assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600);
|
|
assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown');
|
|
});
|
|
test('a partial trajectory cannot replace a complete historical cache',async()=>{
|
|
const h=backendHarness({cache:{test:old},trajectories:{test:{trajectory:{steps:[]},numTotalSteps:3}}});
|
|
const p=await h.buildTelemetryPayloadInternal('test');
|
|
assert.equal(p.consumption.session.totalTokens,900);
|
|
assert.equal(h.state.saves.length,1);
|
|
assert.equal(h.state.saves[0].data.test.steps[0].outputTokens,600);
|
|
assert.equal(h.state.saves[0].data.test.steps[0].modelKey,'unknown');
|
|
assert.match(h.state.errors[0],/Incomplete trajectory/);
|
|
});
|
|
|
|
test('a TTFT-only correction is persisted even when usage, duration and signature match',async()=>{
|
|
const h=backendHarness({cache:{test:old},trajectories:{test:raw},summaries:{test:{
|
|
stepCount:1,lastModifiedTime:'2026-01-01T00:00:10Z',status:'CASCADE_RUN_STATUS_RUNNING',
|
|
}}});
|
|
await h.buildTelemetryPayloadInternal('test');
|
|
h.state.trajectories.test=structuredClone(raw);
|
|
h.state.trajectories.test.trajectory.generatorMetadata[0].chatModel.timeToFirstToken='9s';
|
|
const next=await h.buildTelemetryPayloadInternal('test');
|
|
assert.equal(next.activeConversation.latestTtftSec,9);
|
|
assert.equal(h.state.saves.length,2);
|
|
assert.equal(h.state.saves[1].data.test.steps[0].ttftSec,9);
|
|
});
|
|
|
|
test('groups subagents under root conversation and computes both per-agent and aggregated telemetry',async()=>{
|
|
const subRaw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
|
createdAt:'2026-01-01T00:00:20Z',finishedGeneratingAt:'2026-01-01T00:00:25Z',
|
|
modelUsage:{inputTokens:'300',cacheReadTokens:'400',outputTokens:'250',thinkingOutputTokens:'50',responseOutputTokens:'200'},
|
|
},plannerResponse:{response:'sub answer',thinkingDuration:'1s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'1s',streamingDuration:'4s',chatStartMetadata:{contextWindowMetadata:{tokenBreakdown:{groups:[{type:'TOKEN_TYPE_CHAT_MESSAGES',numTokens:12000},{type:'TOKEN_TYPE_TOOLS',numTokens:3000}]}}}}}]}};
|
|
const h=backendHarness({
|
|
trajectories:{root1:raw,sub1:subRaw},
|
|
summaries:{
|
|
root1:{stepCount:1,lastModifiedTime:'2026-01-01T00:00:10Z',status:'IDLE',annotations:{title:'Root Task'}},
|
|
sub1:{stepCount:1,createdTime:'2026-01-01T00:00:20Z',lastModifiedTime:'2026-01-01T00:00:25Z',status:'CASCADE_RUN_STATUS_RUNNING',trajectoryMetadata:{rootConversationId:'root1',parentConversationId:'root1',subagentSpec:{typeName:'research',role:'Codebase Researcher'}}},
|
|
},
|
|
});
|
|
const p=await h.buildTelemetryPayloadInternal('');
|
|
// Top-level conversations list only contains root1, not raw sub1
|
|
assert.equal(p.conversations.length,1);
|
|
assert.equal(p.conversations[0].cascadeId,'root1');
|
|
assert.equal(p.conversations[0].subagentCount,1);
|
|
assert.equal(p.conversations[0].totalStepCount,2);
|
|
// Active conversation has both individual agents and aggregated view
|
|
assert.equal(p.activeConversation.hasSubagents,true);
|
|
assert.equal(p.activeConversation.subagentCount,1);
|
|
assert.equal(p.activeConversation.agents.length,2);
|
|
assert.equal(p.activeConversation.agents[0].agentId,'main');
|
|
assert.equal(p.activeConversation.agents[0].stepCount,1);
|
|
assert.equal(p.activeConversation.agents[1].agentId,'sub1');
|
|
assert.equal(p.activeConversation.agents[1].role,'Codebase Researcher');
|
|
assert.equal(p.activeConversation.agents[1].context.messagesTokens,12000);
|
|
assert.equal(p.activeConversation.aggregated.stepCount,2);
|
|
assert.equal(p.activeConversation.aggregated.isRunning,true);
|
|
assert.equal(p.activeConversation.aggregated.activeAgentId,'sub1');
|
|
// Session consumption includes both root1 (900) and sub1 (950)
|
|
assert.equal(p.consumption.session.totalTokens,1850);
|
|
});
|
|
|
|
test('discovers and links subagents from parent invokeSubagent steps after Antigravity restart when omitted from trajectorySummaries',async()=>{
|
|
const rootWithInvoke={
|
|
trajectory:{
|
|
metadata:{rootConversationId:'root-audit'},
|
|
steps:[
|
|
{
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{
|
|
createdAt:'2026-01-01T00:00:00Z',
|
|
finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
|
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
|
|
},
|
|
plannerResponse:{response:'spawning subagents',thinkingDuration:'5s'},
|
|
},
|
|
{
|
|
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{
|
|
createdAt:'2026-01-01T00:00:12Z',
|
|
toolCall:{name:'invoke_subagent',argumentsJson:JSON.stringify({Role:'Build & Baseline Verifier',TypeName:'issue_verifier'})},
|
|
},
|
|
invokeSubagent:{
|
|
subagents:[{typeName:'issue_verifier',role:'Build & Baseline Verifier',initialPrompt:'long prompt...'}],
|
|
results:[{conversationId:'sub-cached-1'}],
|
|
},
|
|
},
|
|
{
|
|
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{
|
|
createdAt:'2026-01-01T00:00:15Z',
|
|
toolCall:{name:'invoke_subagent',argumentsJson:JSON.stringify({Role:'P0 Disk Quiz Patch Verifier',TypeName:'issue_verifier'})},
|
|
},
|
|
invokeSubagent:{
|
|
subagents:[{typeName:'issue_verifier',role:'P0 Disk Quiz Patch Verifier',initialPrompt:'long prompt 2...'}],
|
|
results:[{conversationId:'sub-uncached-2'}],
|
|
},
|
|
},
|
|
],
|
|
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}],
|
|
},
|
|
};
|
|
const sub2Raw={
|
|
trajectory:{
|
|
metadata:{
|
|
parentConversationId:'root-audit',
|
|
rootConversationId:'root-audit',
|
|
subagentSpec:{typeName:'issue_verifier',role:'P0 Disk Quiz Patch Verifier',initialPrompt:'huge prompt'},
|
|
},
|
|
steps:[{
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{
|
|
createdAt:'2026-01-01T00:00:20Z',
|
|
finishedGeneratingAt:'2026-01-01T00:00:25Z',
|
|
modelUsage:{inputTokens:'400',cacheReadTokens:'600',outputTokens:'300',thinkingOutputTokens:'50',responseOutputTokens:'250'},
|
|
},
|
|
plannerResponse:{response:'sub2 report',thinkingDuration:'1s'},
|
|
}],
|
|
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'1s',streamingDuration:'4s'}}],
|
|
},
|
|
};
|
|
// Simulate pre-existing v10 cache entries saved before subagentRefs existed
|
|
const preCachedSub1Step={
|
|
stepIndex:1,
|
|
createdAt:'2026-01-01T00:00:14Z',
|
|
createdAtMs:Date.parse('2026-01-01T00:00:14Z'),
|
|
modelKey:'MODEL_PLACEHOLDER_M417',
|
|
responseModel:'gemini-3.1-pro-high',
|
|
modelIdentityVersion:2,
|
|
modelSource:'explicit',
|
|
inputTokens:200,
|
|
cacheReadTokens:300,
|
|
outputTokens:500,
|
|
thinkingTokens:100,
|
|
responseTokens:400,
|
|
contextBreakdown:{messagesTokens:18000,userInputTokens:2000,assistantTokens:6000,toolResultsTokens:10000,subagentTokens:0,checkpointTokens:0,systemToolsTokens:4000,mcpToolsTokens:0,skillsTokens:1000,systemPromptTokens:5000,userRulesTokens:2000},
|
|
};
|
|
const h=backendHarness({
|
|
cache:{
|
|
'root-audit':{
|
|
signature:'v10-model-identity:3:2026-01-01T00:00:15Z',
|
|
title:'Frontend Issue Audit Verification',
|
|
lastModifiedMs:Date.parse('2026-01-01T00:00:15Z'),
|
|
steps:[{...preCachedSub1Step,inputTokens:100,cacheReadTokens:200,outputTokens:600}],
|
|
},
|
|
'sub-cached-1':{
|
|
signature:'v10-model-identity:disk:1767225614000',
|
|
title:'sub-cach',
|
|
lastModifiedMs:Date.parse('2026-01-01T00:00:14Z'),
|
|
steps:[preCachedSub1Step],
|
|
},
|
|
},
|
|
trajectories:{
|
|
'root-audit':rootWithInvoke,
|
|
'sub-uncached-2':sub2Raw,
|
|
},
|
|
// After restart, GetAllCascadeTrajectories only returns root-audit!
|
|
summaries:{
|
|
'root-audit':{
|
|
stepCount:3,
|
|
lastModifiedTime:'2026-01-01T00:00:15Z',
|
|
status:'IDLE',
|
|
annotations:{title:'Frontend Issue Audit Verification'},
|
|
},
|
|
},
|
|
});
|
|
|
|
const p=await h.buildTelemetryPayloadInternal('root-audit');
|
|
assert.equal(p.conversations.length,1);
|
|
assert.equal(p.conversations[0].cascadeId,'root-audit');
|
|
assert.equal(p.conversations[0].subagentCount,2);
|
|
assert.equal(p.activeConversation.hasSubagents,true);
|
|
assert.equal(p.activeConversation.subagentCount,2);
|
|
assert.equal(p.activeConversation.agents.length,3);
|
|
assert.equal(p.activeConversation.agents[1].agentId,'sub-cached-1');
|
|
assert.equal(p.activeConversation.agents[1].role,'Build & Baseline Verifier');
|
|
assert.equal(p.activeConversation.agents[1].context.messagesTokens,18000);
|
|
assert.equal(p.activeConversation.agents[2].agentId,'sub-uncached-2');
|
|
assert.equal(p.activeConversation.agents[2].role,'P0 Disk Quiz Patch Verifier');
|
|
assert.equal(p.activeConversation.aggregated.stepCount,3);
|
|
// Verify initialPrompt was stripped from persisted cache
|
|
const savedSub2=h.state.saves[h.state.saves.length-1].data['sub-uncached-2'];
|
|
assert.equal(savedSub2.subagentSpec.initialPrompt,undefined);
|
|
assert.equal(savedSub2.subagentSpec.role,'P0 Disk Quiz Patch Verifier');
|
|
// Conversation dropdown stepCount matches model step count (1, not 3 raw steps)
|
|
assert.equal(p.conversations[0].stepCount,1);
|
|
assert.equal(p.conversations[0].totalStepCount,3);
|
|
});
|
|
|
|
test('converges multi-level nested subagents to ultimate root and preserves metrics when a newly spawned subagent has 0 steps',async()=>{
|
|
const rootTraj={
|
|
trajectory:{
|
|
steps:[
|
|
{
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{
|
|
createdAt:'2026-01-01T00:00:00Z',
|
|
finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
|
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
|
|
},
|
|
plannerResponse:{response:'root step',thinkingDuration:'5s'},
|
|
},
|
|
{
|
|
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{createdAt:'2026-01-01T00:00:11Z'},
|
|
invokeSubagent:{
|
|
subagents:[{typeName:'self',role:'Level 1 Orchestrator'}],
|
|
results:[{conversationId:'sub-l1'}],
|
|
},
|
|
},
|
|
],
|
|
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'2s',streamingDuration:'8s'}}],
|
|
},
|
|
};
|
|
const subL1Traj={
|
|
trajectory:{
|
|
metadata:{
|
|
parentConversationId:'root-multi',
|
|
subagentSpec:{typeName:'self'},
|
|
},
|
|
steps:[
|
|
{
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{
|
|
createdAt:'2026-01-01T00:00:15Z',
|
|
finishedGeneratingAt:'2026-01-01T00:00:20Z',
|
|
modelUsage:{inputTokens:'200',cacheReadTokens:'300',outputTokens:'400',thinkingOutputTokens:'50',responseOutputTokens:'350'},
|
|
},
|
|
plannerResponse:{response:'l1 step',thinkingDuration:'1s'},
|
|
},
|
|
{
|
|
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
|
status:'CORTEX_STEP_STATUS_DONE',
|
|
metadata:{createdAt:'2026-01-01T00:00:21Z'},
|
|
invokeSubagent:{
|
|
subagents:[{typeName:'research',role:'Level 2 Deep Worker'}],
|
|
results:[{conversationId:'sub-l2'}],
|
|
},
|
|
},
|
|
],
|
|
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'1s',streamingDuration:'4s',chatStartMetadata:{contextWindowMetadata:{tokenBreakdown:{groups:[{type:'TOKEN_TYPE_CHAT_MESSAGES',numTokens:24000}]}}}}}],
|
|
},
|
|
};
|
|
// Level 2 subagent is currently running with 0 completed model steps so far
|
|
const subL2Traj={
|
|
trajectory:{
|
|
metadata:{
|
|
parentConversationId:'sub-l1',
|
|
rootConversationId:'sub-l1',
|
|
},
|
|
steps:[],
|
|
generatorMetadata:[],
|
|
},
|
|
};
|
|
|
|
const h=backendHarness({
|
|
trajectories:{
|
|
'root-multi':rootTraj,
|
|
'sub-l1':subL1Traj,
|
|
'sub-l2':subL2Traj,
|
|
},
|
|
summaries:{
|
|
'root-multi':{stepCount:2,lastModifiedTime:'2026-01-01T00:00:11Z',status:'IDLE',annotations:{title:'Multi-Level Task'}},
|
|
'sub-l1':{stepCount:2,lastModifiedTime:'2026-01-01T00:00:21Z',status:'IDLE',trajectoryMetadata:{parentConversationId:'root-multi'}},
|
|
'sub-l2':{stepCount:0,lastModifiedTime:'2026-01-01T00:00:25Z',status:'CASCADE_RUN_STATUS_RUNNING',trajectoryMetadata:{parentConversationId:'sub-l1',rootConversationId:'sub-l1'}},
|
|
},
|
|
});
|
|
|
|
const p=await h.buildTelemetryPayloadInternal('root-multi');
|
|
assert.equal(p.conversations.length,1);
|
|
assert.equal(p.conversations[0].subagentCount,2);
|
|
assert.equal(p.activeConversation.subagentCount,2);
|
|
assert.equal(p.activeConversation.agents.length,3);
|
|
// Partial subagentSpec ({typeName:'self'}) merged with invokeSubagent role ('Level 1 Orchestrator')
|
|
assert.equal(p.activeConversation.agents[1].role,'Level 1 Orchestrator');
|
|
assert.equal(p.activeConversation.agents[2].agentId,'sub-l2');
|
|
assert.equal(p.activeConversation.agents[2].role,'Level 2 Deep Worker');
|
|
// Even though sub-l2 is running with 0 steps, aggregated telemetry retains valid speed & context from sub-l1
|
|
assert.equal(p.activeConversation.aggregated.activeAgentId,'sub-l2');
|
|
assert.equal(p.activeConversation.aggregated.latestTokPerSec,80);
|
|
assert.equal(p.activeConversation.aggregated.context.messagesTokens,24000);
|
|
// Main agent steps are not duplicated in agents[0].recentSteps or aggregated.recentSteps
|
|
assert.equal(p.activeConversation.agents[0].recentSteps,undefined);
|
|
assert.equal(p.activeConversation.aggregated.recentSteps,undefined);
|
|
// Running sub-l2 with 0 steps still exposes liveActivity on both subagent and aggregated view
|
|
assert.equal(p.activeConversation.agents[0].liveActivity,null);
|
|
assert.equal(p.activeConversation.agents[2].liveActivity.phase,'thinking');
|
|
assert.equal(p.activeConversation.aggregated.liveActivity.agentId,'sub-l2');
|
|
assert.equal(p.activeConversation.aggregated.liveActivity.agentBadge,'子2');
|
|
// runningConversations includes root-multi with main summary and collapsible subagents summary
|
|
assert.equal(p.runningConversations.length,1);
|
|
assert.equal(p.runningConversations[0].cascadeId,'root-multi');
|
|
assert.equal(p.runningConversations[0].title,'Multi-Level Task');
|
|
assert.equal(p.runningConversations[0].subagentCount,2);
|
|
assert.equal(p.runningConversations[0].runningSubagentCount,1);
|
|
assert.equal(p.runningConversations[0].mainActivity.label,'等待子代理');
|
|
assert.equal(p.runningConversations[0].subagents[0].role,'Level 1 Orchestrator');
|
|
assert.equal(p.runningConversations[0].subagents[0].isRunning,false);
|
|
assert.equal(p.runningConversations[0].subagents[0].liveActivity.label,'已完成');
|
|
assert.equal(p.runningConversations[0].subagents[1].role,'Level 2 Deep Worker');
|
|
assert.equal(p.runningConversations[0].subagents[1].isRunning,true);
|
|
});
|
|
|
|
test('trendSeries buckets hourly for <=72h windows (today/24h) and daily for >72h windows (7d)', async () => {
|
|
const nowMs = Date.now();
|
|
const nowIso = new Date(nowMs - 5000).toISOString();
|
|
const finIso = new Date(nowMs).toISOString();
|
|
const h = backendHarness({
|
|
trajectories: {
|
|
c1: {
|
|
trajectory: {
|
|
steps: [
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: nowIso,
|
|
finishedGeneratingAt: finIso,
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M37',
|
|
inputTokens: '100',
|
|
cacheReadTokens: '200',
|
|
outputTokens: '600',
|
|
thinkingOutputTokens: '100',
|
|
responseOutputTokens: '500',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'answer', thinkingDuration: '2s' },
|
|
},
|
|
],
|
|
generatorMetadata: [{ stepIndices: [0], chatModel: { timeToFirstToken: '1s', streamingDuration: '4s' } }],
|
|
},
|
|
},
|
|
},
|
|
summaries: {
|
|
c1: { stepCount: 1, lastModifiedTime: finIso, status: 'IDLE' },
|
|
},
|
|
});
|
|
|
|
const p24h = await h.buildTelemetryPayloadInternal('c1', false, { range: '24h' });
|
|
const trend24h = p24h.consumption.trendSeries;
|
|
assert.ok(trend24h.length >= 24 && trend24h.length <= 26);
|
|
assert.equal(trend24h[0].granularity, 'hour');
|
|
assert.match(trend24h[0].fullLabel, /\d+月\d+日 \d{2}:00 - \d{2}:00/);
|
|
assert.equal(trend24h.reduce((sum, b) => sum + b.tokens, 0), 900);
|
|
assert.equal(trend24h.reduce((sum, b) => sum + b.calls, 0), 1);
|
|
|
|
const p7d = await h.buildTelemetryPayloadInternal('c1', false, { range: '7d' });
|
|
const trend7d = p7d.consumption.trendSeries;
|
|
assert.ok(trend7d.length >= 7 && trend7d.length <= 8);
|
|
assert.equal(trend7d[0].granularity, 'day');
|
|
assert.match(trend7d[0].fullLabel, /\d+月\d+日 \(周[日一二三四五六]\)/);
|
|
assert.equal(trend7d.reduce((sum, b) => sum + b.tokens, 0), 900);
|
|
});
|
|
|
|
test('supports Gemini 4 Carbon pricing/pool and resolves all newly added language_server placeholder enums', async () => {
|
|
const nowIso = new Date().toISOString();
|
|
const h = backendHarness({
|
|
userStatus: {
|
|
name: 'Carbon Tester',
|
|
cascadeModelConfigData: {
|
|
clientModelConfigs: [
|
|
{
|
|
label: 'Gemini 3.8 Flash (High)',
|
|
modelId: 'gemini-3.8-flash-high',
|
|
modelOrAlias: { model: 'MODEL_PLACEHOLDER_M318' },
|
|
quotaInfo: { remainingFraction: 0.9, resetTime: '2026-11-12T00:00:00Z' },
|
|
},
|
|
{
|
|
label: 'Gemini 4 Carbon (High)',
|
|
modelId: 'gemini-4-carbon-high',
|
|
modelOrAlias: { model: 'MODEL_PLACEHOLDER_M429' },
|
|
quotaInfo: { remainingFraction: 0.65, resetTime: '2026-11-17T00:00:00Z' },
|
|
},
|
|
],
|
|
},
|
|
},
|
|
trajectories: {
|
|
cCarbon: {
|
|
trajectory: {
|
|
steps: [
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-11-10T00:00:00Z',
|
|
finishedGeneratingAt: '2026-11-10T00:00:05Z',
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M298',
|
|
inputTokens: '1000000',
|
|
cacheReadTokens: '0',
|
|
outputTokens: '0',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'flash 3.7 high' },
|
|
},
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-11-10T00:00:06Z',
|
|
finishedGeneratingAt: '2026-11-10T00:00:10Z',
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M402',
|
|
inputTokens: '1000000',
|
|
cacheReadTokens: '0',
|
|
outputTokens: '0',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'claude opus 5.5 high' },
|
|
},
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-11-10T00:00:11Z',
|
|
finishedGeneratingAt: '2026-11-10T00:00:15Z',
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M429',
|
|
inputTokens: '1000000',
|
|
cacheReadTokens: '1000000',
|
|
outputTokens: '100000',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'carbon high' },
|
|
},
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-11-10T00:00:16Z',
|
|
finishedGeneratingAt: '2026-11-10T00:00:20Z',
|
|
modelUsage: {
|
|
model: 'claude-fable-5-2-high',
|
|
inputTokens: '1000000',
|
|
cacheReadTokens: '1000000',
|
|
outputTokens: '100000',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'fable 5.2 high' },
|
|
},
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-11-10T00:00:21Z',
|
|
finishedGeneratingAt: '2026-11-10T00:00:25Z',
|
|
modelUsage: {
|
|
model: 'gpt-6.1-terra',
|
|
inputTokens: '1000000',
|
|
cacheReadTokens: '1000000',
|
|
outputTokens: '100000',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'gpt 6.1 terra' },
|
|
},
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-11-10T00:00:26Z',
|
|
finishedGeneratingAt: '2026-11-10T00:00:30Z',
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M429',
|
|
inputTokens: '0',
|
|
cacheReadTokens: '0',
|
|
outputTokens: '100',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'carbon tail' },
|
|
},
|
|
],
|
|
generatorMetadata: [
|
|
{ stepIndices: [0], chatModel: { timeToFirstToken: '1s', streamingDuration: '4s' } },
|
|
{ stepIndices: [1], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } },
|
|
{ stepIndices: [2], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } },
|
|
{ stepIndices: [3], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } },
|
|
{ stepIndices: [4], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } },
|
|
{ stepIndices: [5], chatModel: { timeToFirstToken: '1s', streamingDuration: '1s' } },
|
|
],
|
|
},
|
|
},
|
|
},
|
|
summaries: {
|
|
cCarbon: { stepCount: 6, lastModifiedTime: nowIso, status: 'IDLE' },
|
|
},
|
|
});
|
|
|
|
const p = await h.buildTelemetryPayloadInternal('cCarbon');
|
|
assert.equal(p.activeConversation.sessionUnpricedCalls, 0);
|
|
// Step 0: M298 -> Gemini 3.7 Flash ($0.75)
|
|
// Step 1: M402 -> Claude Opus 5.5 ($4.00)
|
|
// Step 2: Carbon High -> 1M*$2.00 + 1M*$0.10 + 0.1M*$10.0 = $3.10
|
|
// Step 3: Fable 5.2 High -> 1M*$8.00 + 1M*$0.20 + 0.1M*$40.0 = $12.20
|
|
// Step 4: GPT-6.1 Terra -> 1M*$1.00 + 1M*$0.05 + 0.1M*$5.0 = $1.55
|
|
// Step 5: Carbon High -> 100 tok * $10/1M = $0.001
|
|
// Total = 0.75 + 4.00 + 3.10 + 12.20 + 1.55 + 0.001 = $21.601 -> $21.60
|
|
assert.equal(p.activeConversation.sessionCostUsd, 21.6);
|
|
assert.equal(p.activeConversation.activeModelShort, 'carbon-4-high');
|
|
assert.equal(p.quotas.activePool.poolKey, 'Carbon');
|
|
assert.equal(p.quotas.activePool.weeklyRemainingIntPct, 65);
|
|
});
|
|
|
|
test('trendSeries preserves 1-day-per-slot granularity for >90 day spans and recentSteps separates thinking vs response tokens', async () => {
|
|
const nowMs = Date.now();
|
|
const oldStartMs = nowMs - 120 * 24 * 3600 * 1000;
|
|
const oldStartIso = new Date(oldStartMs).toISOString();
|
|
const oldEndIso = new Date(oldStartMs + 6000).toISOString();
|
|
const recentStartIso = new Date(nowMs - 8000).toISOString();
|
|
const recentEndIso = new Date(nowMs - 1000).toISOString();
|
|
|
|
const h = backendHarness({
|
|
trajectories: {
|
|
cLong: {
|
|
trajectory: {
|
|
steps: [
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
|
createdAt: oldStartIso,
|
|
finishedGeneratingAt: oldEndIso,
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M429',
|
|
inputTokens: '10000',
|
|
cacheReadTokens: '20000',
|
|
outputTokens: '700',
|
|
thinkingOutputTokens: '420',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'early step' },
|
|
},
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
sourceTrajectoryStepInfo: { stepIndex: 2 },
|
|
createdAt: recentStartIso,
|
|
finishedGeneratingAt: recentEndIso,
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M429',
|
|
inputTokens: '5000',
|
|
cacheReadTokens: '32115',
|
|
outputTokens: '685',
|
|
thinkingOutputTokens: '420',
|
|
responseOutputTokens: '265',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'recent step' },
|
|
},
|
|
],
|
|
},
|
|
},
|
|
},
|
|
summaries: {
|
|
cLong: { stepCount: 2, lastModifiedTime: recentEndIso, status: 'IDLE' },
|
|
},
|
|
});
|
|
|
|
const pAll = await h.buildTelemetryPayloadInternal('cLong', false, { range: 'all' });
|
|
const trendAll = pAll.consumption.trendSeries;
|
|
assert.ok(trendAll.length >= 120 && trendAll.length <= 122, `Expected ~121 daily slots, got ${trendAll.length}`);
|
|
assert.equal(trendAll[0].granularity, 'day');
|
|
assert.match(trendAll[0].fullLabel, /^\d{4}年\d+月\d+日 \(周[日一二三四五六]\)$/);
|
|
assert.equal(trendAll.reduce((sum, b) => sum + b.tokens, 0), 30700 + 37800);
|
|
assert.equal(trendAll.reduce((sum, b) => sum + b.calls, 0), 2);
|
|
|
|
const steps = pAll.activeConversation.recentSteps;
|
|
assert.equal(steps.length, 2);
|
|
// recentSteps is reversed (newest first)
|
|
assert.equal(steps[0].contextTokens, 37800);
|
|
assert.equal(steps[0].thinkingTokens, 420);
|
|
assert.equal(steps[0].responseTokens, 265);
|
|
assert.equal(steps[1].thinkingTokens, 420);
|
|
assert.equal(steps[1].responseTokens, 280);
|
|
});
|
|
|
|
test('cached incomplete timing is refreshed once without invalidating completed historical steps', async () => {
|
|
const time = '2026-01-01T00:00:12Z';
|
|
const summary = { stepCount: 1, lastModifiedTime: time, status: 'IDLE' };
|
|
const incompleteStep = {
|
|
...structuredClone(raw.trajectory.steps[0]),
|
|
status: 'CORTEX_STEP_STATUS_CLEARED',
|
|
};
|
|
const { extractModelSteps } = await import('../speed-metrics.mjs');
|
|
const [completed] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
|
const [incomplete] = extractModelSteps([{ ...incompleteStep, status: 'CORTEX_STEP_STATUS_GENERATING' }]);
|
|
const cacheEntry = (step) => ({
|
|
signature: `v10-model-identity:1:${time}`,
|
|
steps: [step],
|
|
contextLimitTelemetry: true,
|
|
subagentRefs: [],
|
|
});
|
|
const h = backendHarness({
|
|
cache: { repaired: cacheEntry(incomplete), stable: cacheEntry(completed) },
|
|
summaries: { repaired: summary, stable: summary },
|
|
trajectories: { repaired: { trajectory: { ...raw.trajectory, steps: [incompleteStep] } } },
|
|
});
|
|
|
|
for (let i = 0; i < 2; i++) {
|
|
const result = await h.buildTelemetryPayloadInternal('repaired');
|
|
assert.equal(result.activeConversation.latestTokPerSec, Math.round(completed.totalTokPerSec * 10) / 10);
|
|
}
|
|
assert.deepEqual(
|
|
h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').map((c) => c.body.cascadeId),
|
|
['repaired']
|
|
);
|
|
});
|
|
|
|
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
|
|
const {
|
|
computeLinearFit,
|
|
computeLoessFit,
|
|
computePublicationFit,
|
|
getStepModelGroupKey,
|
|
toChronologicalSteps,
|
|
} = await import('../src/components/charts/SessionStepCharts.js');
|
|
|
|
// 1. Verify OLS + publication LOESS + 95% CI confidence band & [0, 100] cache bounds
|
|
const olsExact = computeLinearFit([10, 20, 30, 40]);
|
|
assert.ok(Math.abs(olsExact.slope - 10) < 1e-9);
|
|
assert.ok(Math.abs(olsExact.r - 1) < 1e-9);
|
|
assert.ok(Math.abs(olsExact.r2 - 1) < 1e-9);
|
|
assert.deepEqual(
|
|
olsExact.values.map((v) => +v.toFixed(4)),
|
|
[10, 20, 30, 40]
|
|
);
|
|
|
|
// Verify bimodal / high-peak TPS series is NOT crushed flat by Bisquare and builds valid 95% CI band
|
|
const waveXs = Array.from({ length: 20 }, (_, idx) => idx * 5 + 1);
|
|
const waveYs = [
|
|
22, 26, 48, 78, 92, 85, 64, 34, 24, 28,
|
|
55, 84, 76, 42, 25, 22, 26, 32, 38, 44,
|
|
];
|
|
const pubWave = computePublicationFit(waveXs, waveYs, { minVal: 0 });
|
|
assert.equal(pubWave.method, 'LOESS');
|
|
assert.equal(pubWave.grid.length, 64);
|
|
assert.ok(
|
|
pubWave.grid.every((g) => g.ciLow <= g.fit + 1e-9 && g.fit <= g.ciHigh + 1e-9),
|
|
'Every grid point satisfies ciLow <= fit <= ciHigh'
|
|
);
|
|
// Around peak x ~ 21 (index 4), fitted conditional expectation must rise well above overall mean (~47)
|
|
assert.ok(pubWave.sampleFits[4] > 55, `Expected peak conditional mean > 55, got ${pubWave.sampleFits[4]}`);
|
|
|
|
// Warmup cache curve stays clamped within [0, 100]
|
|
const cacheSeries = [0, 90, 92, 93, 94, 95, 95];
|
|
const loessCache = computeLoessFit(cacheSeries, { minVal: 0, maxVal: 100 });
|
|
assert.equal(loessCache.length, cacheSeries.length);
|
|
assert.ok(
|
|
loessCache.every((v) => v >= 0 && v <= 100),
|
|
'Fitted cache values must stay clamped within [0, 100]'
|
|
);
|
|
assert.ok(loessCache[6] > 90, 'Tail fit tracks steady warm cache region');
|
|
|
|
// Group key strips [自动压缩] and thinking tier suffixes
|
|
assert.equal(getStepModelGroupKey({ modelLabel: 'Gemini 3.1 Pro (High) [自动压缩]' }), 'Gemini 3.1 Pro');
|
|
assert.equal(getStepModelGroupKey({ modelLabel: 'Orchestrator (Carbon)' }), 'Orchestrator (Carbon)');
|
|
|
|
const chrono = toChronologicalSteps(
|
|
[
|
|
{ stepIndex: 3, createdAtMs: 3000 },
|
|
{ stepIndex: 1, createdAtMs: 1000 },
|
|
{ stepIndex: 2, createdAtMs: 2000 },
|
|
],
|
|
true
|
|
);
|
|
assert.deepEqual(
|
|
chrono.map((s) => s.stepIndex),
|
|
[1, 2, 3]
|
|
);
|
|
|
|
// 2. Verify backend modelBreakdown enriches avgTtftSec and cacheHitPct for main & subagents
|
|
const h = backendHarness({
|
|
trajectories: {
|
|
'root-fit': {
|
|
trajectory: {
|
|
steps: [
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-06-01T00:00:00Z',
|
|
finishedGeneratingAt: '2026-06-01T00:00:10Z',
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M37',
|
|
inputTokens: '1000',
|
|
cacheReadTokens: '9000',
|
|
outputTokens: '500',
|
|
thinkingOutputTokens: '100',
|
|
responseOutputTokens: '400',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'main step 1' },
|
|
},
|
|
{
|
|
type: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: { createdAt: '2026-06-01T00:00:12Z' },
|
|
invokeSubagent: {
|
|
subagents: [{ typeName: 'research', role: 'Fast Researcher' }],
|
|
results: [{ conversationId: 'sub-fit' }],
|
|
},
|
|
},
|
|
],
|
|
generatorMetadata: [
|
|
{ stepIndices: [0], chatModel: { timeToFirstToken: '2.4s', streamingDuration: '7.6s' } },
|
|
],
|
|
},
|
|
},
|
|
'sub-fit': {
|
|
trajectory: {
|
|
metadata: { parentConversationId: 'root-fit', subagentSpec: { typeName: 'research' } },
|
|
steps: [
|
|
{
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
metadata: {
|
|
createdAt: '2026-06-01T00:00:15Z',
|
|
finishedGeneratingAt: '2026-06-01T00:00:20Z',
|
|
modelUsage: {
|
|
model: 'MODEL_PLACEHOLDER_M18',
|
|
inputTokens: '2000',
|
|
cacheReadTokens: '6000',
|
|
outputTokens: '400',
|
|
thinkingOutputTokens: '50',
|
|
responseOutputTokens: '350',
|
|
},
|
|
},
|
|
plannerResponse: { response: 'sub step 1' },
|
|
},
|
|
],
|
|
generatorMetadata: [
|
|
{ stepIndices: [0], chatModel: { timeToFirstToken: '0.8s', streamingDuration: '4.2s' } },
|
|
],
|
|
},
|
|
},
|
|
},
|
|
summaries: {
|
|
'root-fit': { stepCount: 2, lastModifiedTime: '2026-06-01T00:00:12Z', status: 'IDLE' },
|
|
'sub-fit': {
|
|
stepCount: 1,
|
|
lastModifiedTime: '2026-06-01T00:00:20Z',
|
|
status: 'IDLE',
|
|
trajectoryMetadata: { parentConversationId: 'root-fit' },
|
|
},
|
|
},
|
|
});
|
|
|
|
const payload = await h.buildTelemetryPayloadInternal('root-fit');
|
|
const mainMb = payload.activeConversation.modelBreakdown;
|
|
assert.equal(mainMb.length, 1);
|
|
assert.equal(mainMb[0].avgTtftSec, 2.4);
|
|
assert.equal(mainMb[0].ttftSampleCount, 1);
|
|
assert.equal(mainMb[0].cacheHitPct, 90);
|
|
|
|
const subMb = payload.activeConversation.agents[1].modelBreakdown;
|
|
assert.equal(subMb.length, 1);
|
|
assert.equal(subMb[0].avgTtftSec, 0.8);
|
|
assert.equal(subMb[0].cacheHitPct, 75);
|
|
|
|
const aggMb = payload.activeConversation.aggregated.modelBreakdown;
|
|
assert.equal(aggMb.length, 2);
|
|
});
|
|
|
|
test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => {
|
|
// 1. Default schema matches pre-refactor out-of-box UI 100%
|
|
const hDefault = backendHarness({});
|
|
const def = hDefault.loadSettings();
|
|
assert.equal(def.language, 'zh-CN');
|
|
assert.equal(def.themeAccent, 'host');
|
|
assert.equal(def.fontScale, 'md');
|
|
assert.equal(def.pluginUpdateMode, 'manual');
|
|
assert.equal(def.windowMountMode, 'dual');
|
|
assert.equal(def.enableWindowOverlay, true);
|
|
assert.equal(def.showTopbarMultiSession, true);
|
|
assert.deepEqual([...def.topbarCapsuleSlots], ['context', 'tps', 'quota_auto']);
|
|
assert.deepEqual([...def.hoverModules], ['metrics', 'context', 'quotas']);
|
|
assert.deepEqual([...def.overviewModules], ['metrics', 'context', 'quotas', 'live_tasks']);
|
|
assert.deepEqual([...def.overviewMetrics], ['tps', 'ttft', 'avg_tps', 'step_cost']);
|
|
assert.equal(def.showStepTurnRail, true);
|
|
assert.equal(def.showStepAgentBadge, true);
|
|
assert.deepEqual([...def.stepTableColumns], ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost']);
|
|
assert.deepEqual({ ...def.modelContextWindows }, {});
|
|
|
|
// 2. Legacy 3-slot ['context', 'none', 'quota_auto'] migrates cleanly to 2-item ['context', 'quota_auto']
|
|
assert.deepEqual(
|
|
[...hDefault.normalizeTopbarCapsuleSlots(['context', 'none', 'quota_auto'])],
|
|
['context', 'quota_auto']
|
|
);
|
|
// Up to 5 unique items supported, duplicates stripped, empty falls back to ['context']
|
|
assert.deepEqual(
|
|
[...hDefault.normalizeTopbarCapsuleSlots(['tps', 'ttft', 'cost', 'cache_hit', 'session_tokens', 'gemini_5h'])],
|
|
['tps', 'ttft', 'cost', 'cache_hit', 'session_tokens']
|
|
);
|
|
assert.deepEqual([...hDefault.normalizeTopbarCapsuleSlots(['none', 'none', 'none'])], ['context']);
|
|
|
|
// 3. Hover modules allow 0 items (explicit []), overviewModules & overviewMetrics require >= 1, stepTableColumns require >= 2
|
|
assert.deepEqual([...hDefault.normalizeHoverModules([])], []);
|
|
assert.deepEqual([...hDefault.normalizeOverviewModules([])], ['metrics']);
|
|
assert.deepEqual([...hDefault.normalizeOverviewMetrics([])], ['tps']);
|
|
assert.deepEqual([...hDefault.normalizeStepTableColumns(['cost'])], ['cost', 'step']);
|
|
|
|
// 4. Updating preferences must not apply legacy global limits or bulk model updates
|
|
const saveRes = hDefault.executeSettingsAction({
|
|
language: 'en-US',
|
|
themeAccent: 'emerald',
|
|
fontScale: 'lg',
|
|
topbarCapsuleSlots: ['context', 'tps', 'ttft', 'cost'],
|
|
hoverModules: ['metrics', 'context'],
|
|
overviewModules: ['quotas', 'metrics'],
|
|
overviewMetrics: ['avg_tps', 'cache_hit'],
|
|
showStepTurnRail: false,
|
|
showStepAgentBadge: false,
|
|
stepTableColumns: ['step', 'time', 'model', 'duration', 'input_tokens', 'output_tokens', 'cost'],
|
|
contextLimitOverrideTokens: 128000,
|
|
modelContextWindows: { MODEL_PLACEHOLDER_M418: '900K' },
|
|
});
|
|
assert.equal(saveRes.ok, true);
|
|
assert.equal(saveRes.updated.language, 'en-US');
|
|
assert.equal(saveRes.updated.themeAccent, 'emerald');
|
|
assert.equal(saveRes.updated.fontScale, 'lg');
|
|
assert.equal(saveRes.updated.topbarCapsuleSlots.length, 4);
|
|
assert.deepEqual([...saveRes.updated.hoverModules], ['metrics', 'context']);
|
|
assert.deepEqual([...saveRes.updated.overviewModules], ['quotas', 'metrics']);
|
|
assert.deepEqual([...saveRes.updated.overviewMetrics], ['avg_tps', 'cache_hit']);
|
|
assert.equal(saveRes.updated.showStepTurnRail, false);
|
|
assert.equal(saveRes.updated.showStepAgentBadge, false);
|
|
assert.equal(saveRes.updated.contextLimitOverrideTokens, undefined);
|
|
assert.deepEqual({ ...saveRes.updated.modelContextWindows }, {});
|
|
|
|
const hWithSteps = backendHarness({
|
|
settings: {
|
|
contextLimitOverrideTokens: 128000,
|
|
modelContextWindows: { MODEL_PLACEHOLDER_M418: '900K' },
|
|
},
|
|
cache: { c1: old },
|
|
trajectories: { c1: raw },
|
|
summaries: { c1: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:10Z', status: 'IDLE' } },
|
|
});
|
|
const telemetry = await hWithSteps.buildTelemetryPayloadInternal('c1');
|
|
assert.equal(telemetry.activeConversation.context.compactionLimitTokens, 256000);
|
|
assert.equal(telemetry.activeConversation.context.limitTokens, 256000);
|
|
|
|
// 5. executeRebuildCacheAction clears trajectoryCache & writes empty cache object
|
|
const rebuildRes = hWithSteps.executeRebuildCacheAction();
|
|
assert.equal(rebuildRes.ok, true);
|
|
const lastCacheSave = hWithSteps.state.saves[hWithSteps.state.saves.length - 1];
|
|
assert.deepEqual(JSON.parse(JSON.stringify(lastCacheSave.data)), {});
|
|
|
|
// 6. executeResetSettingsAction restores full defaults cleanly
|
|
const resetRes = hDefault.executeResetSettingsAction();
|
|
assert.equal(resetRes.ok, true);
|
|
assert.equal(resetRes.updated.language, 'zh-CN');
|
|
assert.equal(resetRes.updated.themeAccent, 'host');
|
|
assert.equal(resetRes.updated.showStepTurnRail, true);
|
|
assert.equal(resetRes.updated.showStepAgentBadge, true);
|
|
assert.deepEqual([...resetRes.updated.topbarCapsuleSlots], ['context', 'tps', 'quota_auto']);
|
|
});
|
|
|
|
test('assigns unified rootTurnIndex across interleaved main and subagent steps so multi-agent turn rail never fragments', async () => {
|
|
const mkPlanner = (stepIndex, createdAt, finishedGeneratingAt) => ({
|
|
status: 'CORTEX_STEP_STATUS_DONE',
|
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
|
metadata: {
|
|
sourceTrajectoryStepInfo: { stepIndex },
|
|
createdAt,
|
|
finishedGeneratingAt,
|
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M429', inputTokens: '100', cacheReadTokens: '0', outputTokens: '80' },
|
|
},
|
|
plannerResponse: { response: 'ok' },
|
|
});
|
|
|
|
const h = backendHarness({
|
|
trajectories: {
|
|
'root-turn': {
|
|
trajectory: {
|
|
steps: [
|
|
{ type: 'CORTEX_STEP_TYPE_USER_INPUT', userInput: { userResponse: '第一轮设计' } },
|
|
mkPlanner(1, '2026-11-13T20:00:01Z', '2026-11-13T20:00:03Z'),
|
|
{ type: 'CORTEX_STEP_TYPE_USER_INPUT', userInput: { userResponse: '确认。设计是满意的。执行' } },
|
|
mkPlanner(3, '2026-11-13T20:33:10Z', '2026-11-13T20:33:12Z'),
|
|
mkPlanner(5, '2026-11-13T20:33:30Z', '2026-11-13T20:33:35Z'),
|
|
],
|
|
},
|
|
},
|
|
'sub-turn': {
|
|
trajectory: {
|
|
metadata: { parentConversationId: 'root-turn', rootConversationId: 'root-turn' },
|
|
steps: [
|
|
{ type: 'CORTEX_STEP_TYPE_USER_INPUT', userInput: { userResponse: 'Subagent internal brief' } },
|
|
mkPlanner(1, '2026-11-13T20:33:20Z', '2026-11-13T20:33:25Z'),
|
|
mkPlanner(2, '2026-11-13T20:33:40Z', '2026-11-13T20:33:45Z'),
|
|
],
|
|
},
|
|
},
|
|
},
|
|
summaries: {
|
|
'root-turn': { stepCount: 5, lastModifiedTime: '2026-11-13T20:33:35Z', status: 'IDLE' },
|
|
'sub-turn': {
|
|
stepCount: 3,
|
|
lastModifiedTime: '2026-11-13T20:33:45Z',
|
|
status: 'IDLE',
|
|
trajectoryMetadata: { parentConversationId: 'root-turn', rootConversationId: 'root-turn' },
|
|
},
|
|
},
|
|
});
|
|
|
|
const p = await h.buildTelemetryPayloadInternal('root-turn');
|
|
const mainSteps = p.activeConversation.recentSteps; // desc: #5 (20:33:30), #3 (20:33:10), #1 (20:00:01)
|
|
const subSteps = p.activeConversation.agents[1].recentSteps; // desc: #2 (20:33:40), #1 (20:33:20)
|
|
|
|
for (const s of [mainSteps[0], mainSteps[1], subSteps[0], subSteps[1]]) {
|
|
assert.equal(s.rootTurnIndex, 2);
|
|
assert.equal(s.isRootLatestTurn, true);
|
|
assert.equal(s.rootTurnPrompt, '确认。设计是满意的。执行');
|
|
}
|
|
assert.equal(mainSteps[1].isRootTurnStart, true);
|
|
assert.equal(mainSteps[0].isRootTurnStart, false);
|
|
assert.equal(subSteps[1].isRootTurnStart, false);
|
|
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);
|
|
assert.equal(payload.activeConversation.inputTokens, 4989);
|
|
assert.equal(payload.activeConversation.cacheReadTokens, 150223);
|
|
assert.equal(payload.activeConversation.outputTokens, 3116);
|
|
assert.equal(payload.activeConversation.totalTokens, 158328);
|
|
assert.equal(payload.activeConversation.latestPromptTokens, 155212);
|
|
|
|
// 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);
|
|
});
|