mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): upgrade modular dashboard UI, 6-segment context meter, and consumption analytics
This commit is contained in:
@@ -1,35 +0,0 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
|
||||
export function backendHarness({cache={},settings={},trajectories={},summaries={},sourceText=null,metricsImplementation=metrics}={}) {
|
||||
const source=(sourceText ?? fs.readFileSync(new URL('../main.mjs',import.meta.url),'utf8'))
|
||||
.replace(/^import .*;\r?\n/gm,'').replaceAll('import.meta.url',JSON.stringify('file:///test/main.mjs'));
|
||||
const state={calls:[],errors:[],saves:[],trajectories};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal,
|
||||
process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
existsSync:p=>p.endsWith('settings.json') || p.endsWith('trajectory_usage_cache.json'),
|
||||
mkdirSync:()=>{},readdirSync:()=>[],statSync:()=>({mtimeMs:0}),
|
||||
readFileSync:p=>JSON.stringify(p.endsWith('settings.json')?settings:cache),
|
||||
writeFileSync:(p,s)=>state.saves.push({path:p,data:JSON.parse(s)}),
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,fileURLToPath:()=>'/test/main.mjs',
|
||||
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||
SidecarApp:class {page(){} api(){} run(){}},
|
||||
StreamDiagnostics:class {status(){return {enabled:false};} start(){}},
|
||||
fetch:async(url,options)=>{
|
||||
const method=url.split('/').pop(); const body=JSON.parse(options.body);state.calls.push({method,body});
|
||||
if(method==='GetCascadeTrajectory') {
|
||||
const data=state.trajectories[body.cascadeId];
|
||||
if(data instanceof Error) throw data;
|
||||
return {ok:true,json:async()=>data||{}};
|
||||
}
|
||||
const data={GetUserStatus:{userStatus:{}},GetAllCascadeTrajectories:{trajectorySummaries:summaries},RetrieveUserQuotaSummary:{response:{groups:[]}}}[method];
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
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,0);
|
||||
});
|
||||
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,/^v9-unified-throughput:/);
|
||||
});
|
||||
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,0);
|
||||
});
|
||||
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,0);
|
||||
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);
|
||||
});
|
||||
@@ -1,52 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {readFileSync} from 'node:fs';
|
||||
import vm from 'node:vm';
|
||||
|
||||
function page() {
|
||||
function element(){return {children:[],_html:'',textContent:'',title:'',scrollTop:0,
|
||||
get innerHTML(){return this._html;},set innerHTML(s){this._html=s;this.children=[];},
|
||||
appendChild(child){if(child.fragment)this.children.push(...child.children);else this.children.push(child);},
|
||||
closest(){return null;}};}
|
||||
const elements=Object.fromEntries(['tab-steps-btn','steps-tbody','models-tbody'].map(id=>[id,element()]));
|
||||
const document={getElementById:id=>elements[id],createElement:element,createDocumentFragment:()=>({...element(),fragment:true})};
|
||||
const source=readFileSync(new URL('../app.js',import.meta.url),'utf8');
|
||||
assert.match(source,/\ninit\(\);\s*$/);
|
||||
const ctx=vm.createContext({window:{},document});
|
||||
vm.runInContext(source.replace(/\ninit\(\);\s*$/,'\n'),ctx);
|
||||
return {ctx,elements};
|
||||
}
|
||||
const step={stepIndex:1,modelShort:'test',outputTokens:300,responseTokens:200,thinkingTokens:100,
|
||||
totalDurationSec:10,tokPerSec:30,ttftSec:2,costUsd:.01};
|
||||
test('tools and text render one TPS column without per-row speed categories',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[{...step,hasToolCalls:true}]},[]);
|
||||
const row=elements['steps-tbody'].children[0];
|
||||
assert.match(row.innerHTML,/30\.0 tok\/s/);
|
||||
assert.doesNotMatch(row.innerHTML,/正文估算|整体吞吐|≈/);
|
||||
assert.match(row.title,/含等待与思考/);
|
||||
});
|
||||
test('unknown and zero are distinct, and insufficient timing explains the missing rate',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[{...step,tokPerSec:null,ttftSec:null,selectedSpeedReason:'short_timing'}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/计时过短/);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>—<\/td>/);
|
||||
ctx.renderTables({recentSteps:[{...step,tokPerSec:0,ttftSec:0}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/0\.0 tok\/s/);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>0\.0s<\/td>/);
|
||||
});
|
||||
test('a TTFT-only correction refreshes the table even when TPS and step count do not change',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[step]},[]);
|
||||
ctx.renderTables({recentSteps:[{...step,ttftSec:12.974}]},[]);
|
||||
assert.match(elements['steps-tbody'].children[0].innerHTML,/<td>13\.0s<\/td>/);
|
||||
});
|
||||
|
||||
test('contradictory timing is explained and zero cache remains a per-request usage fact',()=>{
|
||||
const {ctx,elements}=page();
|
||||
ctx.renderTables({recentSteps:[{...step,tokPerSec:null,cacheHitPct:0,selectedSpeedReason:'inconsistent_timing'}]},[]);
|
||||
const row=elements['steps-tbody'].children[0];
|
||||
assert.match(row.innerHTML,/原生首响应与总计时不一致/);
|
||||
assert.match(row.innerHTML,/不是缓存容量/);assert.match(row.innerHTML,/>0%<\/td>/);
|
||||
assert.doesNotMatch(row.innerHTML,/≈/);
|
||||
});
|
||||
@@ -1,157 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {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'}={}) {
|
||||
const s={status,type:'CORTEX_STEP_TYPE_PLANNER_RESPONSE',metadata:{
|
||||
createdAt:'2026-01-01T00:00:00Z',viewableAt:'2026-01-01T00:00:02Z',
|
||||
finishedGeneratingAt:new Date(Date.parse('2026-01-01T00:00:00Z')+total*1000).toISOString(),
|
||||
modelUsage:{inputTokens:'500',cacheReadTokens:'2000',outputTokens:String(output),thinkingOutputTokens:String(thinking),responseOutputTokens:String(response)},
|
||||
},plannerResponse:{response:text?'answer':'',thinkingDuration,toolCalls:tools?[{}]:[]}};
|
||||
const gm={stepIndices:[0],chatModel:{timeToFirstToken:ttft,streamingDuration:stream}};
|
||||
return {s,gm};
|
||||
}
|
||||
function parse(options) {const {s,gm}=sample(options);return extractModelSteps([s],[gm])[0];}
|
||||
|
||||
test('text, tools and mixed output all use total output / full request duration',()=>{
|
||||
for(const tools of [false,true])for(const text of [false,true]){
|
||||
const step=parse({tools,text});
|
||||
assert.equal(speedMetric(step).value,1100/12);
|
||||
assert.equal(step.speedBasis,'request_total');
|
||||
assert.equal(step.speedSampleEligible,true);
|
||||
}
|
||||
});
|
||||
test('buffered JSON cannot create a burst peak by shortening native or thinking phase timers',()=>{
|
||||
for(const stream of ['0.001s','0.01s','1s','10s',undefined]){
|
||||
for(const thinkingDuration of ['0.01s','9.999s',undefined]){
|
||||
const step=parse({total:10,ttft:'9.999s',stream,thinkingDuration,output:300,tools:true,text:false});
|
||||
assert.equal(step.totalTokPerSec,30);
|
||||
assert.equal(step.ttftSec,9.999);
|
||||
}
|
||||
}
|
||||
});
|
||||
test('TTFT is the exact native value, never a token-ratio guess or viewable-event substitute',()=>{
|
||||
assert.equal(parse({total:20,ttft:'19.9s',thinkingDuration:'19.95s',tools:true,text:false}).ttftSec,19.9);
|
||||
const {s,gm}=sample();delete gm.chatModel.timeToFirstToken;
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.ttftSec,null);assert.equal(step.viewableDelaySec,2);
|
||||
assert.deepEqual(summarizeTtft([step]),{sampleCount:0,avgSec:null});
|
||||
});
|
||||
test('zero TTFT is preserved and malformed or negative durations remain unknown',()=>{
|
||||
const zero=parse({ttft:'0s'});
|
||||
assert.equal(zero.ttftSec,0);
|
||||
assert.equal(summarizeTtft([zero]).avgSec,0);
|
||||
for(const ttft of ['-1s','12garbage','NaNs','Infinitys',''])assert.equal(parse({ttft}).ttftSec,null);
|
||||
});
|
||||
test('short output keeps the same formula but does not bias the mean',()=>{
|
||||
const short=parse({output:13,response:13,thinking:0,total:5.015,stream:'0.118s'});
|
||||
assert.equal(short.totalTokPerSec,13/5.015);
|
||||
assert.equal(short.speedReason,'short_sample');
|
||||
assert.equal(summarizeSpeed([short,parse()]).avgTokPerSec,1100/12);
|
||||
assert.equal(summarizeSpeed([short]).avgTokPerSec,null);
|
||||
assert.equal(parse({output:50}).speedSampleEligible,true);
|
||||
});
|
||||
test('sub-half-second whole requests are withheld, never divided by a tiny interval',()=>{
|
||||
const tiny=parse({total:.05,output:1000});
|
||||
assert.equal(tiny.totalTokPerSec,null);assert.equal(tiny.speedReason,'short_timing');
|
||||
assert.equal(speedMetric(tiny).value,null);
|
||||
assert.equal(summarizeSpeed([tiny]).sampleCount,0);
|
||||
assert.equal(parse({total:.5,output:100,ttft:'0.1s'}).totalTokPerSec,200);
|
||||
});
|
||||
test('weighted mean matches token/time totals and does not average step rates',()=>{
|
||||
const a=parse({output:1000,total:10}),b=parse({output:1000,total:20,tools:true});
|
||||
const mean=summarizeSpeed([a,b]);
|
||||
assert.equal(mean.tokens,2000);assert.equal(mean.seconds,30);
|
||||
assert.equal(mean.avgTokPerSec,2000/30);assert.equal(mean.sampleCount,2);
|
||||
});
|
||||
test('unfinished, missing-completion and reversed-time requests cannot fabricate speed',()=>{
|
||||
const {s,gm}=sample();delete s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
assert.equal(parse({total:-1}).totalTokPerSec,null);
|
||||
assert.equal(parse({total:0}).totalTokPerSec,null);
|
||||
assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null);
|
||||
});
|
||||
test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{
|
||||
const zero=parse({output:0,response:0,thinking:0});
|
||||
assert.equal(zero.totalTokPerSec,0);assert.equal(zero.responseTokens,0);
|
||||
for(const output of [-1,1.5,NaN,Infinity])assert.equal(parse({output}).totalTokPerSec,null);
|
||||
const {s,gm}=sample();delete s.metadata.modelUsage.outputTokens;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
});
|
||||
test('missing phase/token breakdown cannot change a valid full-request rate',()=>{
|
||||
const {s,gm}=sample();delete s.plannerResponse.thinkingDuration;
|
||||
delete s.metadata.modelUsage.thinkingOutputTokens;delete s.metadata.modelUsage.responseOutputTokens;
|
||||
delete gm.chatModel.streamingDuration;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,1100/12);
|
||||
});
|
||||
test('no rate-dependent cap or formula switch at the former 260 TPS boundary',()=>{
|
||||
const a=parse({total:10,output:2590,tools:true}),b=parse({total:10,output:2610,tools:true});
|
||||
assert.equal(a.totalTokPerSec,259);assert.equal(b.totalTokPerSec,261);
|
||||
assert.equal(a.speedBasis,b.speedBasis);
|
||||
});
|
||||
test('legacy cache retains billing but cannot masquerade as current measurements',()=>{
|
||||
for(const measurementVersion of [undefined,1,2,3]){
|
||||
const old={measurementVersion,inputTokens:500,cacheReadTokens:2000,outputTokens:1100,ttftSec:0.4,totalTokPerSec:55};
|
||||
const migrated=normalizeCachedStep(old);
|
||||
assert.equal(migrated.outputTokens,1100);assert.equal(migrated.inputTokens,500);
|
||||
assert.equal(migrated.ttftSec,null);assert.equal(speedMetric(migrated).value,null);
|
||||
assert.equal(speedMetric(migrated).reason,'legacy_cache');
|
||||
}
|
||||
});
|
||||
|
||||
test('half-second cutoff uses the original nanoseconds, not rounded epoch milliseconds',()=>{
|
||||
const {s,gm}=sample({output:100,ttft:'0.1s'});
|
||||
s.metadata.createdAt='2026-01-01T00:00:00.000000001Z';
|
||||
s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000000Z';
|
||||
const below=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(below.totalDurationSec,.499999999);assert.equal(below.totalTokPerSec,null);
|
||||
s.metadata.finishedGeneratingAt='2026-01-01T00:00:00.500000001Z';
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200);
|
||||
s.metadata.createdAt='2026-01-01T08:00:00.000000001+08:00';
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,200);
|
||||
});
|
||||
test('non-chat generator metadata cannot overwrite matching model timing',()=>{
|
||||
const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};gm.stepIndices=[42];
|
||||
const other={stepIndices:[42],tool:{}};
|
||||
assert.equal(extractModelSteps([s],[gm,other])[0].nativeTtftSec,2);
|
||||
s.metadata.generatorMetadata=[other,{chatModel:{timeToFirstToken:'3s'}}];
|
||||
assert.equal(extractModelSteps([s],[gm])[0].nativeTtftSec,3);
|
||||
});
|
||||
test('a paginated source step never borrows timing from an unrelated array position',()=>{
|
||||
const {s,gm}=sample();s.metadata.sourceTrajectoryStepInfo={stepIndex:42};
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.nativeTtftSec,null);assert.equal(step.totalTokPerSec,1100/12);
|
||||
});
|
||||
test('contradictory native TTFT is preserved but cannot validate TPS or bias the TTFT mean',()=>{
|
||||
const bad=parse({total:5,ttft:'9s'});
|
||||
assert.equal(bad.nativeTtftSec,9);assert.equal(bad.totalTokPerSec,null);
|
||||
assert.equal(bad.speedReason,'inconsistent_timing');
|
||||
assert.deepEqual(summarizeTtft([bad,parse()]),{sampleCount:1,avgSec:2});
|
||||
});
|
||||
test('unfinished steps do not enter the TTFT mean even when partial metadata includes TTFT',()=>{
|
||||
const partial=parse({status:'CORTEX_STEP_STATUS_GENERATING',ttft:'8s'});
|
||||
assert.deepEqual(summarizeTtft([partial,parse()]),{sampleCount:1,avgSec:2});
|
||||
});
|
||||
test('coercible non-token values cannot silently become zero or one output token',()=>{
|
||||
for(const value of [true,false,' ',[],{}]){
|
||||
const {s,gm}=sample();s.metadata.modelUsage.outputTokens=value;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].speedReason,'invalid_output_tokens');
|
||||
}
|
||||
});
|
||||
test('visible buffered text and tools use full time without a rate-dependent switch',()=>{
|
||||
const {s,gm}=sample({output:64,thinking:33,response:31,ttft:'7.0108593s',stream:'0.0045919s'});
|
||||
s.metadata.finishedGeneratingAt='2026-01-01T00:00:07.015451200Z';
|
||||
delete s.plannerResponse.thinkingDuration;
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.totalDurationSec,7.0154512);
|
||||
assert.equal(speedMetric(step).value,64/7.0154512);
|
||||
assert.equal(step.speedBasis,'request_total');
|
||||
});
|
||||
test('compaction displays a valid rate and retains billing but is excluded from speed/TTFT means',()=>{
|
||||
const {s,gm}=sample();s.type='CORTEX_STEP_TYPE_CHECKPOINT';
|
||||
const step=extractModelSteps([s],[gm])[0];
|
||||
assert.equal(step.outputTokens,1100);assert.equal(speedMetric(step).value,1100/12);
|
||||
assert.equal(summarizeSpeed([step]).sampleCount,0);
|
||||
assert.equal(summarizeTtft([step]).sampleCount,0);
|
||||
});
|
||||
@@ -1,194 +0,0 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, readFileSync, readdirSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { ConnectJsonDecoder, StreamObservation, StreamDiagnostics, encodeConnectJson } from '../stream-diagnostics.mjs';
|
||||
|
||||
const ID = '12345678-1234-1234-1234-123456789abc';
|
||||
const CREATED = '2026-10-15T01:00:00.000Z';
|
||||
const FINISHED = '2026-10-15T01:00:08.000Z';
|
||||
const event = (ms, batch = ms) => ({ elapsedMs: ms, receiveBatch: batch, receivedAt: CREATED });
|
||||
const model = (p = {}, done = false, extra = {}) => ({
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: done ? 'CORTEX_STEP_STATUS_DONE' : 'CORTEX_STEP_STATUS_STREAMING',
|
||||
metadata: { createdAt: CREATED, ...(done ? { finishedGeneratingAt: FINISHED, modelUsage: { outputTokens: '400' } } : {}) },
|
||||
plannerResponse: p, ...extra,
|
||||
});
|
||||
const update = (indices, steps, totalLength, more = {}) => ({ update: { conversationId: ID,
|
||||
mainTrajectoryUpdate: { stepsUpdate: { indices, steps, totalLength }, ...more } } });
|
||||
function observer() {
|
||||
const records = [];
|
||||
const observation = new StreamObservation({ conversationId: ID, connectedWallMs: Date.parse(CREATED) - 1000, emit: r => records.push(r) });
|
||||
return { records, observation };
|
||||
}
|
||||
|
||||
test('Connect decoder reconstructs fragmented headers/UTF-8 and keeps coalesced messages separate', () => {
|
||||
const a = { update: { text: '中文🙂' } };
|
||||
const b = { update: { text: 'second' } };
|
||||
const bytes = Buffer.concat([encodeConnectJson(a), encodeConnectJson(b)]);
|
||||
const decoder = new ConnectJsonDecoder();
|
||||
const messages = [];
|
||||
for (let i = 0; i < bytes.length; i += 3) messages.push(...decoder.push(bytes.subarray(i, i + 3)));
|
||||
decoder.finish();
|
||||
assert.deepEqual(messages.map(m => m.value), [a, b]);
|
||||
const end = encodeConnectJson({}); end[0] = 2;
|
||||
assert.equal(decoder.push(end)[0].end, true);
|
||||
assert.throws(() => decoder.push(encodeConnectJson(a)), /data_after_end/);
|
||||
});
|
||||
|
||||
test('Connect decoder rejects oversized, compressed, malformed and truncated frames', () => {
|
||||
const huge = Buffer.from([0, 0, 0, 1, 0]);
|
||||
assert.throws(() => new ConnectJsonDecoder(100).push(huge), /frame_too_large/);
|
||||
const compressed = encodeConnectJson({}); compressed[0] = 1;
|
||||
assert.throws(() => new ConnectJsonDecoder().push(compressed), /unsupported_frame_flags/);
|
||||
assert.throws(() => new ConnectJsonDecoder().push(Buffer.from([0, 0, 0, 0, 1, 120])), /invalid_frame_json/);
|
||||
const decoder = new ConnectJsonDecoder(); decoder.push(Buffer.from([0, 0]));
|
||||
assert.throws(() => decoder.finish(), /truncated_frame/);
|
||||
});
|
||||
|
||||
test('history, delayed rehydration and status-only notifications never become live output', () => {
|
||||
const { observation: o, records } = observer();
|
||||
o.accept({ update: { conversationId: ID, status: 'IDLE' } }, event(0));
|
||||
assert.equal(o.initialized, false);
|
||||
o.accept(update([9], [model({ response: 'old response' }, true)], 10), event(1));
|
||||
o.accept(update([4], [model({ response: 'late history' }, true)], 10), event(2));
|
||||
assert.equal(o.contentEvents, 0);
|
||||
assert.equal(o.recent.length, 0);
|
||||
assert.deepEqual(records.map(r => r.kind), ['baseline']);
|
||||
});
|
||||
|
||||
test('tool arguments, thinking and text are counted independently; receive batches are not tokens', () => {
|
||||
const { observation: o, records } = observer();
|
||||
o.accept(update([], [], 10), event(0));
|
||||
o.accept(update([10], [model()], 11), event(10));
|
||||
o.accept(update([10], [model({ thinking: 'hidden-secret', response: '中', toolCalls: [{ argumentsJson: '{', name: 'secret-tool' }] })], 11), event(20, 2));
|
||||
o.accept(update([10], [model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"' }] })], 11), event(20, 2));
|
||||
const full = model({ thinking: 'hidden-secret!', response: '中文', toolCalls: [{ argumentsJson: '{"secret":"argument-secret"}' }] }, true);
|
||||
o.accept(update([10], [full], 11), event(120, 3));
|
||||
o.accept(update([10], [full], 11), event(300, 4));
|
||||
o.accept(update([], [], 11, { generatorMetadatasUpdate: { generatorMetadatas: [{ stepIndices: [10], chatModel: {
|
||||
usage: { outputTokens: '400', thinkingOutputTokens: '50', responseHeader: { authorization: 'credential-secret' } },
|
||||
timeToFirstToken: '7.999s', streamingDuration: '0.001s', systemPrompt: 'prompt-secret',
|
||||
} }] } }), event(400, 5));
|
||||
const r = o.recent[0];
|
||||
assert.equal(r.contentEvents, 3);
|
||||
assert.equal(r.contentReceiveBatches, 2);
|
||||
assert.equal(r.toolArgumentEvents, 3);
|
||||
assert.equal(r.observedSpanMs, 100);
|
||||
assert.equal(r.channels.text.bytes, 6);
|
||||
assert.equal(r.channels.text.utf16Units, 2);
|
||||
assert.equal(r.usage.outputTokens, 400);
|
||||
assert.equal(r.nativeStreamSec, 0.001);
|
||||
assert.equal(r.partialCapture, false);
|
||||
const serialized = JSON.stringify([records, r]);
|
||||
for (const secret of ['hidden-secret', 'argument-secret', 'secret-tool', 'credential-secret', 'prompt-secret', '中文']) assert.ok(!serialized.includes(secret));
|
||||
assert.ok(!/tokPerSec|tps|firstTokenMs/i.test(serialized));
|
||||
});
|
||||
|
||||
test('same-batch delivery is not reported as a timed stream, even with several updates', () => {
|
||||
const { observation: o } = observer();
|
||||
o.accept(update([], [], 0), event(0));
|
||||
o.accept(update([0], [model({ response: 'a' })], 1), event(5, 1));
|
||||
o.accept(update([0], [model({ response: 'ab' }, true)], 1), event(5, 1));
|
||||
assert.equal(o.recent[0].observation, 'single_receive_batch');
|
||||
assert.equal(o.recent[0].observedSpanMs, 0);
|
||||
});
|
||||
|
||||
test('rewrites, shrinking output and tool-only updates are retained as revisions', () => {
|
||||
const { observation: o, records } = observer();
|
||||
o.accept(update([], [], 0), event(0));
|
||||
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'abcd' }] })], 1), event(10));
|
||||
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wxyz' }] })], 1), event(20));
|
||||
o.accept(update([0], [model({ toolCalls: [{ argumentsJson: 'wx' }] }, true)], 1), event(30));
|
||||
assert.equal(o.recent[0].revisions, 2);
|
||||
assert.equal(o.recent[0].toolArgumentEvents, 3);
|
||||
assert.equal(records.at(-1).changes.toolArguments.deltaBytes, -2);
|
||||
assert.equal(records.at(-1).changes.toolArguments.appendOnly, false);
|
||||
});
|
||||
|
||||
test('joining during generation marks partial capture and excludes initial content from updates', () => {
|
||||
const { observation: o } = observer();
|
||||
o.accept(update([2], [model({ response: 'already there' })], 3), event(10));
|
||||
o.accept(update([2], [model({ response: 'already there plus more' }, true)], 3), event(20));
|
||||
assert.equal(o.recent[0].partialCapture, true);
|
||||
assert.equal(o.recent[0].contentEvents, 1);
|
||||
assert.equal(o.recent[0].observation, 'partial_capture');
|
||||
});
|
||||
|
||||
test('missing or earlier creation time never claims a complete observation', () => {
|
||||
const { observation: o } = observer();
|
||||
o.accept(update([], [], 0), event(0));
|
||||
o.accept(update([0], [model({ response: 'arrived' }, true, { metadata: { finishedGeneratingAt: FINISHED } })], 1), event(20));
|
||||
assert.equal(o.recent[0].partialCapture, true);
|
||||
assert.throws(() => o.accept(update([], [model()], 2), event(25)), /invalid_step_indices/);
|
||||
});
|
||||
|
||||
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function until(check) {
|
||||
for (let i = 0; i < 100; i++) { if (check()) return; await sleep(10); }
|
||||
assert.fail('timed out');
|
||||
}
|
||||
function temp(t) {
|
||||
const dir = mkdtempSync(join(tmpdir(), 'usage-monitor-diag-test-'));
|
||||
t.after(() => {
|
||||
const absolute = resolve(dir);
|
||||
assert.equal(dirname(absolute), resolve(tmpdir()));
|
||||
assert.ok(absolute.startsWith(join(resolve(tmpdir()), 'usage-monitor-diag-test-')));
|
||||
rmSync(absolute, { recursive: true, force: true });
|
||||
});
|
||||
return dir;
|
||||
}
|
||||
|
||||
test('collector only subscribes to read APIs, persists counters and stops without touching billing', async t => {
|
||||
const dir = temp(t);
|
||||
const calls = [];
|
||||
let streamController;
|
||||
const fetchImpl = async (url, options) => {
|
||||
calls.push({ url, options });
|
||||
if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: { stepCount: 0, lastModifiedTime: CREATED } } }));
|
||||
assert.ok(url.endsWith('StreamAgentStateUpdates'));
|
||||
const request = new ConnectJsonDecoder().push(options.body)[0].value;
|
||||
assert.equal(request.trajectoryVerbosity, 'CLIENT_TRAJECTORY_VERBOSITY_FULL');
|
||||
const stream = new ReadableStream({ start(c) {
|
||||
streamController = c;
|
||||
c.enqueue(encodeConnectJson(update([], [], 0)));
|
||||
options.signal.addEventListener('abort', () => c.error(new Error('aborted')), { once: true });
|
||||
} });
|
||||
return new Response(stream, { headers: { 'Content-Type': 'application/connect+json' } });
|
||||
};
|
||||
const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'secret-csrf', fetchImpl, pollMs: 60000 });
|
||||
t.after(() => d.stop());
|
||||
assert.equal(d.status().enabled, false);
|
||||
d.configure({ enabled: true });
|
||||
await until(() => d.status().phase === 'collecting');
|
||||
streamController.enqueue(encodeConnectJson(update([0], [model({ toolCalls: [{ argumentsJson: 'private-arguments' }] }, true)], 1)));
|
||||
await until(() => d.status().contentEvents === 1);
|
||||
assert.equal(d.status().affectsTps, false);
|
||||
d.configure({ enabled: false });
|
||||
await sleep(10);
|
||||
assert.equal(d.status().phase, 'disabled');
|
||||
assert.equal(d.current, null);
|
||||
const log = readFileSync(join(dir, 'stream-diagnostics', 'events.jsonl'), 'utf8');
|
||||
assert.ok(!log.includes('secret-csrf'));
|
||||
assert.ok(!log.includes('private-arguments'));
|
||||
assert.ok(log.includes('step_update'));
|
||||
assert.deepEqual(readdirSync(dir).sort(), ['stream-diagnostics', 'stream-diagnostics-config.json']);
|
||||
assert.equal(calls.length, 2);
|
||||
});
|
||||
|
||||
test('failed subscriptions back off and never expose the server error body', async t => {
|
||||
const dir = temp(t);
|
||||
let calls = 0;
|
||||
const d = new StreamDiagnostics({ dataDir: dir, lsAddress: '127.0.0.1:1', csrfToken: 'csrf', pollMs: 10, retryMs: 5000,
|
||||
fetchImpl: async url => {
|
||||
calls++;
|
||||
if (url.endsWith('GetAllCascadeTrajectories')) return new Response(JSON.stringify({ trajectorySummaries: { [ID]: {} } }));
|
||||
return new Response('private server error with credentials', { status: 403 });
|
||||
} });
|
||||
t.after(() => d.stop());
|
||||
d.configure({ enabled: true });
|
||||
await until(() => d.status().error === 'stream_http_403');
|
||||
await sleep(40);
|
||||
assert.equal(calls, 2);
|
||||
assert.ok(!JSON.stringify(d.status()).includes('private'));
|
||||
});
|
||||
Reference in New Issue
Block a user