mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(release): v1.4.0 cloud pricing sync, one-click plugin update, and UI copy refresh
This commit is contained in:
@@ -3,24 +3,98 @@ import path from 'node:path';
|
||||
import vm from 'node:vm';
|
||||
import * as metrics from '../speed-metrics.mjs';
|
||||
|
||||
export function backendHarness({cache={},settings={},trajectories={},summaries={},userStatus={},quotaSummary={groups:[]},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,userStatus,quotaSummary};
|
||||
const BACKEND_MODULE_FILES = [
|
||||
'../backend/config.mjs',
|
||||
'../backend/pricing-catalog.mjs',
|
||||
'../backend/plugin-updater.mjs',
|
||||
'../backend/ls-rpc.mjs',
|
||||
'../backend/model-pricing.mjs',
|
||||
'../backend/quota-pools.mjs',
|
||||
'../backend/local-scanner.mjs',
|
||||
'../backend/usage-aggregator.mjs',
|
||||
'../backend/telemetry-builder.mjs',
|
||||
'../main.mjs',
|
||||
];
|
||||
|
||||
function loadCombinedBackendSource() {
|
||||
return BACKEND_MODULE_FILES.map((relPath) =>
|
||||
fs.readFileSync(new URL(relPath, import.meta.url), 'utf8')
|
||||
).join('\n');
|
||||
}
|
||||
|
||||
function stripEsmSyntax(rawSource, mainUrl) {
|
||||
return rawSource
|
||||
.replace(/^\s*import\s+[\s\S]*?from\s+['"][^'"]+['"];?\r?\n/gm, '')
|
||||
.replace(/^\s*export\s+(?=(?:async\s+)?function\b|const\b|let\b|class\b)/gm, '')
|
||||
.replaceAll('import.meta.url', JSON.stringify(mainUrl));
|
||||
}
|
||||
|
||||
export function backendHarness({
|
||||
cache={},
|
||||
settings={},
|
||||
trajectories={},
|
||||
summaries={},
|
||||
userStatus={},
|
||||
quotaSummary={groups:[]},
|
||||
localCatalog=null,
|
||||
remoteCatalog=null,
|
||||
pluginManifest=null,
|
||||
hasGitDir=false,
|
||||
pluginRootPath=null,
|
||||
remoteFetch=null,
|
||||
execFileImpl=null,
|
||||
sourceText=null,
|
||||
metricsImplementation=metrics,
|
||||
}={}) {
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],trajectories,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal,
|
||||
process:{env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
...metricsImplementation, URL, AbortSignal, Buffer,
|
||||
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)},
|
||||
existsSync:p=>p.endsWith('settings.json') || p.endsWith('trajectory_usage_cache.json'),
|
||||
cpSync:()=>{},
|
||||
rmSync:()=>{},
|
||||
execFile:execFileImpl || ((cmd,args,opts,cb)=>{
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
fn(new Error('execFile not mocked'));
|
||||
}),
|
||||
existsSync:p=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (norm.endsWith('settings.json') || norm.endsWith('trajectory_usage_cache.json')) return true;
|
||||
if (norm.endsWith('pricing-catalog.json')) return Boolean(state.localCatalog);
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return Boolean(state.remoteCatalog);
|
||||
if (norm.endsWith('plugin.json')) return Boolean(state.pluginManifest);
|
||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir);
|
||||
return false;
|
||||
},
|
||||
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',
|
||||
readFileSync:p=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(settings);
|
||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
||||
return JSON.stringify(cache);
|
||||
},
|
||||
writeFileSync:(p,s)=>{
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
||||
state.saves.push({path:p,data:parsed});
|
||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
||||
state.remoteCatalog = parsed;
|
||||
}
|
||||
},
|
||||
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(){}},
|
||||
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});
|
||||
fetch:async(url,options={})=>{
|
||||
if (/^https?:\/\/(?!test\.invalid)/i.test(String(url)) && remoteFetch) {
|
||||
return remoteFetch(url, options);
|
||||
}
|
||||
const method=url.split('/').pop(); const body=options.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;
|
||||
@@ -34,6 +108,6 @@ export function backendHarness({cache={},settings={},trajectories={},summaries={
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,compareSemver,performPluginUpdate};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
|
||||
const createdAtMs = Date.now() - 20_000;
|
||||
function makeStep(index, modelKey, responseModel = '') {
|
||||
return {
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
sourceTrajectoryStepInfo: { stepIndex: index },
|
||||
createdAt: new Date(createdAtMs).toISOString(),
|
||||
completedAt: new Date(createdAtMs + 5_000).toISOString(),
|
||||
modelUsage: {
|
||||
model: modelKey,
|
||||
...(responseModel ? { responseModel } : {}),
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '100000',
|
||||
cacheReadTokens: '400000',
|
||||
outputTokens: '50000',
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs, and preserves valid pricing', () => {
|
||||
const { sanitizeCatalogPayload } = backendHarness();
|
||||
assert.equal(sanitizeCatalogPayload(null), null);
|
||||
assert.equal(sanitizeCatalogPayload({ pricing: {} }), null);
|
||||
|
||||
const sanitized = sanitizeCatalogPayload({
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.03.9',
|
||||
updatedAt: '2026-11-03T15:00:00Z',
|
||||
latestPluginVersion: '1.5.0',
|
||||
downloadUrl: 'https://evil.example.com/malware.zip',
|
||||
pricing: {
|
||||
'gemini-4.5-ultra': { input: 3.5, cache: 0.35, output: 15.0, short: 'ultra-4.5', family: 'Gemini' },
|
||||
'broken-negative': { input: -1, cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-nan': { input: 'NaN', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-null': { input: null, cache: null, output: null, short: 'bad', family: 'Gemini' },
|
||||
'broken-zero': { input: 0, cache: 0, output: 0, short: 'bad', family: 'Gemini' },
|
||||
'broken-string-num': { input: '1.5', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||
'broken-missing-short': { input: 1, cache: 0.1, output: 5, short: '', family: 'Gemini' },
|
||||
},
|
||||
placeholders: {
|
||||
MODEL_PLACEHOLDER_M999: { modelId: 'gemini-4.5-ultra', label: 'Gemini 4.5 Ultra' },
|
||||
MODEL_BROKEN: { modelId: '', label: 'Broken' },
|
||||
},
|
||||
});
|
||||
|
||||
assert.ok(sanitized);
|
||||
assert.equal(sanitized.catalogVersion, '2026.11.03.9');
|
||||
assert.equal(sanitized.latestPluginVersion, '1.5.0');
|
||||
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan2498281558/'));
|
||||
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
|
||||
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
|
||||
});
|
||||
|
||||
test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newly pushed models', async () => {
|
||||
const step = makeStep(1, 'MODEL_PLACEHOLDER_M888');
|
||||
let fetchedUrl = '';
|
||||
|
||||
const h = backendHarness({
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
summaries: { conv1: { stepCount: 1 } },
|
||||
trajectories: { conv1: { trajectory: { steps: [step] } } },
|
||||
remoteFetch: async (url) => {
|
||||
fetchedUrl = String(url);
|
||||
return {
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.03.2',
|
||||
updatedAt: '2026-11-03T16:00:00Z',
|
||||
latestPluginVersion: '1.5.0',
|
||||
pricing: {
|
||||
'gemini-5-nova': { input: 4.0, cache: 0.4, output: 20.0, short: 'nova-5', family: 'Gemini' },
|
||||
},
|
||||
placeholders: {
|
||||
MODEL_PLACEHOLDER_M888: { modelId: 'gemini-5-nova', label: 'Gemini 5 Nova' },
|
||||
},
|
||||
}),
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
// Before cloud sync: M888 is unknown and unpriced
|
||||
const before = await h.buildTelemetryPayloadInternal('conv1');
|
||||
assert.equal(before.activeConversation.activeModelShort, 'MODEL_PLACEHOLDER_M888');
|
||||
assert.equal(before.activeConversation.latestStepCostUsd, null);
|
||||
assert.equal(before.consumption.account.unpricedCalls, 1);
|
||||
assert.equal(before.cloudStatus.updateAvailable, false);
|
||||
|
||||
// Sync cloud catalog from GitHub
|
||||
const syncStatus = await h.syncCloudCatalog({ force: true });
|
||||
assert.ok(fetchedUrl.startsWith('https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json'));
|
||||
assert.equal(syncStatus.source, 'remote');
|
||||
assert.equal(syncStatus.catalogVersion, '2026.11.03.2');
|
||||
assert.equal(syncStatus.latestPluginVersion, '1.5.0');
|
||||
assert.equal(syncStatus.updateAvailable, true);
|
||||
|
||||
// Immediately re-evaluate payload: M888 is now resolved and priced without clearing trajectoryCache
|
||||
const after = await h.buildTelemetryPayloadInternal('conv1');
|
||||
assert.equal(after.activeConversation.activeModelShort, 'nova-5');
|
||||
assert.equal(after.activeConversation.activeModelLabel, 'Gemini 5 Nova');
|
||||
// Cost = 0.1M * $4.0 + 0.4M * $0.4 + 0.05M * $20.0 = 0.4 + 0.16 + 1.0 = $1.56
|
||||
assert.equal(after.activeConversation.latestStepCostUsd, 1.56);
|
||||
assert.equal(after.consumption.account.unpricedCalls, 0);
|
||||
assert.equal(after.consumption.account.costUsd, 1.56);
|
||||
});
|
||||
|
||||
test('resolveModelInfo falls back to responseModel when placeholder enum is unmapped', async () => {
|
||||
const step = makeStep(1, 'MODEL_PLACEHOLDER_M777', 'gemini-4-argon-high');
|
||||
const h = backendHarness({
|
||||
summaries: { conv1: { stepCount: 1 } },
|
||||
trajectories: { conv1: { trajectory: { steps: [step] } } },
|
||||
});
|
||||
const p = await h.buildTelemetryPayloadInternal('conv1');
|
||||
assert.equal(p.activeConversation.activeModelShort, 'argon-4-high');
|
||||
assert.equal(p.consumption.account.unpricedCalls, 0);
|
||||
assert.ok(p.activeConversation.latestStepCostUsd > 0);
|
||||
});
|
||||
|
||||
test('performPluginUpdate blocks overwriting dirty worktrees (including untracked ?? files) without stashing', async () => {
|
||||
for (const [rootPath, porcelainOutput] of [
|
||||
['/workspace/antigravity-usage-monitor', ' M sidecars/panel/main.mjs\n'],
|
||||
['/Users/test/.gemini/config/plugins/usage-monitor', '?? sidecars/panel/backend/config.mjs\n'],
|
||||
]) {
|
||||
const gitCalls = [];
|
||||
const h = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: rootPath,
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('status')) {
|
||||
assert(!args.includes('--untracked-files=no'), 'must inspect untracked files too');
|
||||
fn(null, porcelainOutput, '');
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await h.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.skipped, true);
|
||||
assert.equal(res.reason, 'dirty_worktree');
|
||||
assert.equal(gitCalls.length, 1);
|
||||
assert(!gitCalls.some((args) => args.includes('stash')));
|
||||
}
|
||||
});
|
||||
|
||||
test('performPluginUpdate blocks non-main branches and diverged git history', async () => {
|
||||
const branchH = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'fix/humanize-copy-strings\n', '');
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
const branchRes = await branchH.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(branchRes.ok, false);
|
||||
assert.equal(branchRes.reason, 'not_on_main_branch');
|
||||
|
||||
const divergedH = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.3.0' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
fn(null, JSON.stringify({ name: 'usage-monitor', version: '1.4.0' }), '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('merge-base')) {
|
||||
fn(new Error('not ancestor'));
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
const divRes = await divergedH.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(divRes.ok, false);
|
||||
assert.equal(divRes.reason, 'diverged_worktree');
|
||||
});
|
||||
|
||||
test('performPluginUpdate refuses to downgrade or pull when remote version is older, equal, or unreadable', async () => {
|
||||
for (const showOutput of [
|
||||
JSON.stringify({ name: 'usage-monitor', version: '1.2.0' }),
|
||||
JSON.stringify({ name: 'usage-monitor', version: '1.4.0' }),
|
||||
'', // git show failed or empty — must NOT fall back to cloudSyncState.latestPluginVersion
|
||||
]) {
|
||||
const gitCalls = [];
|
||||
const h = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.4.0' },
|
||||
remoteCatalog: {
|
||||
schemaVersion: 1,
|
||||
catalogVersion: '2026.11.03.9',
|
||||
updatedAt: '2026-11-03T18:00:00Z',
|
||||
latestPluginVersion: '1.9.0',
|
||||
pricing: { 'gemini-4-argon': { input: 2, cache: 0.1, output: 10, short: 'argon-4', family: 'Gemini' } },
|
||||
},
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
if (!showOutput) {
|
||||
fn(new Error('fatal: Path plugin.json does not exist'));
|
||||
return;
|
||||
}
|
||||
fn(null, showOutput, '');
|
||||
return;
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await h.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(res.ok, false);
|
||||
assert.equal(res.skipped, true);
|
||||
assert.equal(res.upToDate, true);
|
||||
assert.equal(res.reason, 'already_up_to_date');
|
||||
assert.equal(res.currentVersion, '1.4.0');
|
||||
assert(!gitCalls.some((args) => args.includes('pull')));
|
||||
}
|
||||
});
|
||||
|
||||
test('performPluginUpdate pulls fast-forward when git worktree is clean, on main, ancestor, and remote version is newer', async () => {
|
||||
const gitCalls = [];
|
||||
const h = backendHarness({
|
||||
hasGitDir: true,
|
||||
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
|
||||
pluginManifest: { name: 'usage-monitor', version: '1.3.1' },
|
||||
execFileImpl: (_cmd, args, opts, cb) => {
|
||||
const fn = typeof opts === 'function' ? opts : cb;
|
||||
gitCalls.push(args);
|
||||
if (args.includes('rev-parse')) {
|
||||
fn(null, 'main\n', '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('show')) {
|
||||
fn(null, JSON.stringify({ name: 'usage-monitor', version: '1.4.0' }), '');
|
||||
return;
|
||||
}
|
||||
if (args.includes('pull')) {
|
||||
h.state.pluginManifest = { name: 'usage-monitor', version: '1.4.0' };
|
||||
}
|
||||
fn(null, '', '');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await h.performPluginUpdate({ isAuto: false });
|
||||
assert.equal(res.ok, true);
|
||||
assert.equal(res.mode, 'git');
|
||||
assert.equal(res.previousVersion, '1.3.1');
|
||||
assert.equal(res.currentVersion, '1.4.0');
|
||||
assert.equal(gitCalls.length, 6); // status, rev-parse, fetch, show, merge-base, pull
|
||||
});
|
||||
Reference in New Issue
Block a user