mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
perf(panel): add incremental step transport, memoized aggregation, atomic cache writes, and hidden-view gating
- Project display-only step fields in /api/telemetry, skip unchanged step payloads via stepRevision, coalesce identical client refreshes, and share in-flight backend trajectory scans across same-account requests - Reuse normalized step values and memoize up to two range aggregations in usage-aggregator gated by step timestamps, pricing revision, model overrides, timezone, and source identity; cache per-trajectory model facts and single-agent step preparation via WeakMap/WeakRef - Persist trajectory checkpoints atomically in trajectory-cache-file.mjs via chunked writevSync + renameSync while reusing serialized step byte slices for unchanged conversations - Render step turn-rail lines/dots via CSS pseudo-elements, allocate speed-reason nodes on demand, short-circuit unchanged table reconciliations, and cache per-series LOESS publication fits in SessionStepCharts - Gate DOM updates and timers across closed overlay panels, hover popups, inactive settings tabs, and unchanged ConsumptionView payloads - Distinguish canceled steps (CORTEX_STEP_STATUS_CANCELED) and untimed compaction steps from generic incomplete timing in speed-metrics and bilingual i18n labels
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||
|
||||
@@ -61,6 +63,7 @@ export function backendHarness({
|
||||
remoteFetch=null,
|
||||
execFileImpl=null,
|
||||
sourceText=null,
|
||||
clock=null,
|
||||
metricsImplementation=metrics,
|
||||
}={}) {
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
@@ -68,7 +71,11 @@ export function backendHarness({
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal, Buffer,
|
||||
...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID,
|
||||
...(clock ? { Date: class extends Date {
|
||||
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
||||
static now() { return clock(); }
|
||||
} } : {}),
|
||||
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
console:{error:m=>state.errors.push(m)},
|
||||
cpSync:()=>{},
|
||||
@@ -132,6 +139,9 @@ export function backendHarness({
|
||||
state.remoteCatalog = parsed;
|
||||
}
|
||||
},
|
||||
writeTrajectoryCacheFile:(p,data)=>{
|
||||
state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))});
|
||||
},
|
||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,fileURLToPath:()=>mainPath,
|
||||
Response:class {constructor(body,options){this.body=body;this.options=options;}},
|
||||
SidecarApp:class {page(){} api(){} run(){}},
|
||||
@@ -154,6 +164,6 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {backendHarness} from './backend-harness.mjs';
|
||||
import { writeTrajectoryCacheFile } from '../backend/trajectory-cache-file.mjs';
|
||||
|
||||
const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
||||
createdAt:'2026-01-01T00:00:00Z',finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
||||
@@ -8,6 +12,37 @@ const raw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
||||
},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('trajectory checkpoints preserve updated metadata and ignore bytes replaced by another writer', () => {
|
||||
const directory = mkdtempSync(fileURLToPath(new URL('./.checkpoint-', import.meta.url)));
|
||||
const file = join(directory, 'trajectory_usage_cache.json');
|
||||
const state = {
|
||||
'会话📝': { title: 'first', steps: [{ stepIndex: 1, model: '模型', inputTokens: 10 }] },
|
||||
second: { title: 'second', steps: [{ stepIndex: 2, outputTokens: 4 }] },
|
||||
};
|
||||
const read = () => JSON.parse(readFileSync(file, 'utf8'));
|
||||
try {
|
||||
writeTrajectoryCacheFile(file, state);
|
||||
assert.deepEqual(read(), state);
|
||||
state['会话📝'].title = 'new metadata';
|
||||
state.second.steps = [{ stepIndex: 2, outputTokens: 8 }];
|
||||
writeTrajectoryCacheFile(file, state);
|
||||
assert.deepEqual(read(), state);
|
||||
|
||||
const external = read();
|
||||
external['会话📝'].steps[0].inputTokens = 90;
|
||||
writeFileSync(file, JSON.stringify(external));
|
||||
writeTrajectoryCacheFile(file, state);
|
||||
assert.deepEqual(read(), state);
|
||||
|
||||
writeTrajectoryCacheFile(file, {});
|
||||
assert.deepEqual(read(), {});
|
||||
assert.deepEqual(readdirSync(directory), ['trajectory_usage_cache.json']);
|
||||
} finally {
|
||||
if (existsSync(file)) unlinkSync(file);
|
||||
rmdirSync(directory);
|
||||
}
|
||||
});
|
||||
|
||||
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');
|
||||
@@ -648,6 +683,118 @@ test('cached incomplete timing is refreshed once without invalidating completed
|
||||
);
|
||||
});
|
||||
|
||||
test('unchanged running steps skip cache writes, but corrected timing with the same summary is persisted', async () => {
|
||||
const time = '2026-01-01T00:00:10Z';
|
||||
const live = structuredClone(raw);
|
||||
live.trajectory.steps[0].status = 'CORTEX_STEP_STATUS_GENERATING';
|
||||
const h = backendHarness({
|
||||
trajectories: { live },
|
||||
summaries: { live: { stepCount: 1, lastModifiedTime: time, status: 'CASCADE_RUN_STATUS_RUNNING' } },
|
||||
});
|
||||
|
||||
const pending = await h.buildTelemetryPayloadInternal('live');
|
||||
assert.equal(pending.activeConversation.latestTokPerSec, null);
|
||||
const writes = h.state.saves.length;
|
||||
assert.ok(writes > 0);
|
||||
|
||||
await h.buildTelemetryPayloadInternal('live');
|
||||
assert.equal(h.state.saves.length, writes);
|
||||
|
||||
h.state.trajectories.live = raw;
|
||||
const completed = await h.buildTelemetryPayloadInternal('live');
|
||||
assert.equal(completed.activeConversation.latestTokPerSec, 60);
|
||||
assert.equal(h.state.saves.length, writes + 1);
|
||||
assert.equal(h.state.saves.at(-1).data.live.steps[0].totalTokPerSec, 60);
|
||||
});
|
||||
|
||||
test('display step revisions omit only matching rows and invalidate on timing changes', async () => {
|
||||
const time = '2026-01-01T00:00:10Z';
|
||||
const live = structuredClone(raw);
|
||||
live.trajectory.steps[0].status = 'CORTEX_STEP_STATUS_GENERATING';
|
||||
const h = backendHarness({
|
||||
trajectories: { live },
|
||||
summaries: { live: { stepCount: 1, lastModifiedTime: time, status: 'CASCADE_RUN_STATUS_RUNNING' } },
|
||||
});
|
||||
const request = { conversationId: 'live', stepDetails: 'display' };
|
||||
const get = async (stepRevision) => JSON.parse((await h.executeTelemetryAction({
|
||||
...request, stepRevision
|
||||
})).body);
|
||||
const initial = await get('');
|
||||
assert.equal(initial.stepsUnchanged, false);
|
||||
assert.equal(initial.activeConversation.recentSteps[0].tokPerSec, null);
|
||||
const same = await get(initial.stepRevision);
|
||||
assert.equal(same.stepsUnchanged, true);
|
||||
assert.equal(same.stepRevision, initial.stepRevision);
|
||||
assert.equal(same.activeConversation.recentSteps, undefined);
|
||||
|
||||
h.state.trajectories.live = raw;
|
||||
const changed = await get(initial.stepRevision);
|
||||
assert.equal(changed.stepsUnchanged, false);
|
||||
assert.notEqual(changed.stepRevision, initial.stepRevision);
|
||||
assert.equal(changed.activeConversation.recentSteps[0].tokPerSec, 60);
|
||||
assert.equal((await get()).activeConversation.recentSteps[0].tokPerSec, 60);
|
||||
});
|
||||
|
||||
test('simultaneous ranges share the trajectory scan while keeping their own totals', async () => {
|
||||
const h = backendHarness({
|
||||
trajectories: { live: raw },
|
||||
summaries: { live: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:10Z' } },
|
||||
});
|
||||
const [all, custom] = await Promise.all([
|
||||
h.buildTelemetryPayloadInternal('live', false, { range: 'all' }),
|
||||
h.buildTelemetryPayloadInternal('live', false, { range: 'custom', startMs: 1, endMs: 2 }),
|
||||
]);
|
||||
assert.equal(all.consumption.account.totalTokens, 900);
|
||||
assert.equal(custom.consumption.account.totalTokens, 0);
|
||||
assert.equal(h.state.calls.filter((call) => call.method === 'GetAllCascadeTrajectories').length, 1);
|
||||
assert.equal(h.state.calls.filter((call) => call.method === 'GetCascadeTrajectory').length, 1);
|
||||
});
|
||||
|
||||
test('cached usage follows rolling boundaries and reprices unchanged steps', async () => {
|
||||
const { extractModelSteps } = await import('../speed-metrics.mjs');
|
||||
const [step] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
||||
const modelKey = 'test-metered-model';
|
||||
let now = Date.parse('2026-03-08T07:00:00Z');
|
||||
const priceCatalog = (price) => ({
|
||||
schemaVersion: 1,
|
||||
pricing: {
|
||||
[modelKey]: { input: price, cache: price, output: price, family: 'Gemini', short: modelKey },
|
||||
},
|
||||
});
|
||||
const h = backendHarness({
|
||||
clock: () => now,
|
||||
localCatalog: priceCatalog(100),
|
||||
cache: {
|
||||
live: {
|
||||
signature: 'v10-model-identity:disk:0',
|
||||
contextLimitTelemetry: true, turnRailTelemetry: true, contextGroupsTelemetry: true,
|
||||
speedClearedTelemetry: true, subagentRefs: [],
|
||||
steps: [
|
||||
{ ...step, modelKey, createdAtMs: now - 86400000, turnIndex: null },
|
||||
{ ...step, modelKey, stepIndex: 2, createdAtMs: now + 1, inputTokens: 120, turnIndex: null },
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const build = () => h.buildTelemetryPayloadInternal('live', false, { range: '24h' });
|
||||
const first = await build();
|
||||
assert.equal(first.consumption.account.totalTokens, 900);
|
||||
assert.equal(first.consumption.account.costUsd, 0.09);
|
||||
|
||||
now += 1;
|
||||
const crossing = await build();
|
||||
assert.equal(crossing.consumption.account.totalTokens, 920);
|
||||
assert.equal(crossing.consumption.account.calls, 1);
|
||||
|
||||
now += 1;
|
||||
h.state.localCatalog = priceCatalog(1000);
|
||||
h.rebuildActiveCatalog();
|
||||
const repriced = await build();
|
||||
assert.equal(repriced.consumption.account.totalTokens, 920);
|
||||
assert.equal(repriced.consumption.account.costUsd, 0.92);
|
||||
assert.equal(repriced.activeConversation.recentSteps[0].costUsd, 0.92);
|
||||
});
|
||||
|
||||
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
|
||||
const {
|
||||
computeLinearFit,
|
||||
@@ -958,6 +1105,37 @@ test('assigns unified rootTurnIndex across interleaved main and subagent steps s
|
||||
assert.equal(subSteps[1].isRootTurnStart, false);
|
||||
assert.equal(subSteps[1].isTurnStart, true);
|
||||
assert.equal(subSteps[1].turnPrompt, 'Subagent internal brief');
|
||||
|
||||
const panel = JSON.parse((await h.executeTelemetryAction({
|
||||
conversationId: 'root-turn', stepDetails: 'display'
|
||||
})).body).activeConversation;
|
||||
const full = JSON.parse((await h.executeTelemetryAction({
|
||||
conversationId: 'root-turn'
|
||||
})).body).activeConversation;
|
||||
assert.equal(panel.recentSteps.length, full.recentSteps.length);
|
||||
assert.equal(panel.agents.length, full.agents.length);
|
||||
for (const [displaySteps, fullSteps] of [
|
||||
[panel.recentSteps, full.recentSteps],
|
||||
[panel.agents[1].recentSteps, full.agents[1].recentSteps],
|
||||
]) {
|
||||
assert.equal(displaySteps.length, fullSteps.length);
|
||||
for (let i = 0; i < fullSteps.length; i++) {
|
||||
assert.equal(displaySteps[i].rootTurnPrompt, fullSteps[i].rootTurnPrompt);
|
||||
assert.equal(displaySteps[i].tokPerSec, fullSteps[i].tokPerSec);
|
||||
assert.equal(displaySteps[i].contextTokens, fullSteps[i].contextTokens);
|
||||
assert.ok(!Object.hasOwn(displaySteps[i], 'contextBreakdown'));
|
||||
assert.ok(Object.hasOwn(fullSteps[i], 'contextBreakdown'));
|
||||
}
|
||||
}
|
||||
const requested = { conversationId: 'root-turn', stepDetails: 'display' };
|
||||
const initial = JSON.parse((await h.executeTelemetryAction({ ...requested, stepRevision: '' })).body);
|
||||
const delta = JSON.parse((await h.executeTelemetryAction({
|
||||
...requested, stepRevision: initial.stepRevision,
|
||||
})).body);
|
||||
assert.equal(delta.stepsUnchanged, true);
|
||||
assert.equal(delta.activeConversation.recentSteps, undefined);
|
||||
assert.equal(delta.activeConversation.agents[1].recentSteps, undefined);
|
||||
assert.equal(delta.activeConversation.agents[1].stepCount, 2);
|
||||
});
|
||||
|
||||
test('reconciles 8-group context breakdown with real API prompt+output tokens and auto-refreshes cached dropped groups', async () => {
|
||||
|
||||
@@ -83,8 +83,14 @@ test('cleared steps with a recorded generation end retain their original request
|
||||
for(const status of ['CORTEX_STEP_STATUS_CANCELED','CORTEX_STEP_STATUS_ERROR','CORTEX_STEP_STATUS_GENERATING']){
|
||||
assert.equal(extractModelSteps([{...s,status}],[gm])[0].totalTokPerSec,null);
|
||||
}
|
||||
const [canceled]=extractModelSteps([{...s,status:'CORTEX_STEP_STATUS_CANCELED'}],[gm]);
|
||||
assert.equal(speedMetric(canceled).reason,'canceled');
|
||||
delete s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
const [checkpoint]=extractModelSteps([{...s,type:'CORTEX_STEP_TYPE_CHECKPOINT'}],[gm]);
|
||||
assert.equal(speedMetric(checkpoint).value,null);
|
||||
assert.equal(speedMetric(checkpoint).reason,'compaction_timing_unavailable');
|
||||
assert.equal(summarizeSpeed([checkpoint,canceled]).sampleCount,0);
|
||||
});
|
||||
test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{
|
||||
const zero=parse({output:0,response:0,thinking:0});
|
||||
|
||||
@@ -1958,9 +1958,10 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
'has-turn-rail class removed when showStepTurnRail is false'
|
||||
);
|
||||
assert.equal(
|
||||
stepTableWhileRailOff.querySelector('.turn-rail').hasAttribute('hidden'),
|
||||
Array.from(stepTableWhileRailOff.querySelectorAll('.turn-rail'))
|
||||
.every((rail) => rail.hasAttribute('hidden')),
|
||||
true,
|
||||
'Turn rail DOM hidden when showStepTurnRail is false'
|
||||
'No visible turn rail when showStepTurnRail is false'
|
||||
);
|
||||
const stepHeaderThs = stepTableWhileRailOff.children[0].children[0].children;
|
||||
assert.equal(stepHeaderThs.length, 9, 'StepsDetailView thead dynamically renders 9 columns');
|
||||
@@ -2144,8 +2145,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const row1Rail = stepRows[1].children[0].querySelector('.turn-rail');
|
||||
assert.equal(row0Rail.hasAttribute('hidden'), false);
|
||||
assert.equal(row0Rail.classList.contains('is-latest'), true);
|
||||
assert.equal(row0Rail.querySelector('.turn-rail-dot').classList.contains('is-cap'), true, 'Newest step in turn renders cap dot');
|
||||
assert.equal(row1Rail.querySelector('.turn-rail-dot').classList.contains('is-origin'), true, 'First step of user turn renders hollow origin dot');
|
||||
assert.equal(row0Rail.classList.contains('is-cap'), true, 'Newest step in turn renders cap dot');
|
||||
assert.equal(row1Rail.classList.contains('is-origin'), true, 'First step of user turn renders hollow origin dot');
|
||||
|
||||
const turnPromptTipEl = stepsPane.querySelector('.turn-prompt-tip');
|
||||
assert.equal(turnPromptTipEl.hasAttribute('hidden'), true, 'Prompt preview tooltip hidden initially');
|
||||
@@ -2438,17 +2439,18 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
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-dot').classList.contains('is-cap'),
|
||||
multiStepRows[0].children[0].querySelector('.turn-rail').classList.contains('is-cap'),
|
||||
true,
|
||||
'Interleaved subagent step at top joins unified rootTurnIndex rail as cap'
|
||||
);
|
||||
assert.equal(
|
||||
multiStepRows[1].children[0].querySelector('.turn-rail-dot').hasAttribute('hidden'),
|
||||
true,
|
||||
multiStepRows[1].children[0].querySelector('.turn-rail').classList.contains('is-cap') ||
|
||||
multiStepRows[1].children[0].querySelector('.turn-rail').classList.contains('is-origin'),
|
||||
false,
|
||||
'Middle main step connects continuously along unified rootTurnIndex rail'
|
||||
);
|
||||
assert.equal(
|
||||
multiStepRows[2].children[0].querySelector('.turn-rail-dot').classList.contains('is-origin'),
|
||||
multiStepRows[2].children[0].querySelector('.turn-rail').classList.contains('is-origin'),
|
||||
true,
|
||||
'Earliest main step anchors unified rootTurnIndex rail origin'
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user