feat(panel): Antigravity IDE & composer mount, modular preferences, session charts, and per-model context windows (v1.5.0)

This commit is contained in:
fish
2026-11-15 15:25:45 +09:00
parent 18c608ae63
commit ff2470481f
35 changed files with 2602 additions and 128 deletions
+377 -13
View File
@@ -551,8 +551,55 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({
// Preferences (3-Tab Modular Settings)
'settings.subTab.general': '常规',
'settings.subTab.structure': '结构',
'settings.subTab.account': '账号',
'settings.subTab.other': '其他',
'settings.subTab.aria': '偏好设置分类切换',
'settings.account.current': '当前账号',
'settings.account.signedOut': '未登录',
'settings.account.unknown': '暂未获取账号状态',
'settings.account.email': '账号邮箱',
'settings.account.credential': 'OAuth 凭证',
'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。',
'settings.account.save': '导入凭证',
'settings.account.capture': '保存当前凭证',
'settings.account.reload': '刷新列表',
'settings.account.switch': '切换',
'settings.account.remove': '移除',
'settings.account.active': '当前使用',
'settings.account.written': '凭证已写入',
'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。',
'settings.account.savedCredentials': '已保存的凭证',
'settings.account.empty': '暂无已保存的凭证。',
'settings.account.loading': '正在读取已保存的凭证…',
'settings.account.saved': '凭证已保存。',
'settings.account.removed': '已移除保存的凭证。',
'settings.account.switched': '已切换账号,正在刷新当前额度。',
'settings.account.switching': '正在替换凭证并确认宿主账号…',
'settings.account.verifying': '正在验证凭证所属账号…',
'settings.account.loadQuota': '查额度',
'settings.account.loadingQuota': '正在查询此凭证的额度…',
'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。',
'settings.account.quota': '额度池剩余',
'settings.account.quota5h': '5 小时 {percent}%',
'settings.account.quotaWeekly': '每周 {percent}%',
'settings.account.noQuota': '暂未获取当前账号的额度池。',
'settings.account.quotaStale': '额度刷新失败,显示的是当前账号上次获取的数据。',
'settings.account.unsupported': '凭证切换目前支持 Windows 上的 Antigravity 共享登录。',
'settings.account.invalidEmail': '请先选择一个已保存的账号。',
'settings.account.invalidCredential': '请输入有效的 Antigravity 个人账号 OAuth 凭证。',
'settings.account.credentialTooLarge': '凭证超过 Windows 凭据管理器的 2560 字节上限。',
'settings.account.notFound': '该凭证已移除,请刷新列表。',
'settings.account.noCurrentCredential': '暂时无法读取当前账号的共享凭证。',
'settings.account.busy': '另一个窗口正在操作凭证,请稍后重试。',
'settings.account.storeFailed': '凭证操作失败,请重试。',
'settings.account.rollbackFailed': '凭证写入和回滚均失败。请在 Antigravity 中确认当前账号后再继续。',
'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。',
'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。',
'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。',
'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。',
'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。',
'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。',
'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。',
'settings.saving': '保存中…',
'settings.saved': '已保存',
'settings.saveFailed': '保存失败',
@@ -978,7 +1025,54 @@ const I18N_MESSAGES_EN_US = Object.freeze({
// Preferences (3-Tab Modular Settings)
'settings.subTab.general': 'General',
'settings.subTab.structure': 'Structure',
'settings.subTab.account': 'Account',
'settings.subTab.other': 'Other',
'settings.account.current': 'Current account',
'settings.account.signedOut': 'Signed out',
'settings.account.unknown': 'Account status unavailable',
'settings.account.email': 'Account email',
'settings.account.credential': 'OAuth credential',
'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.',
'settings.account.save': 'Import credential',
'settings.account.capture': 'Save current credential',
'settings.account.reload': 'Refresh list',
'settings.account.switch': 'Switch',
'settings.account.remove': 'Remove',
'settings.account.active': 'In use',
'settings.account.written': 'Credential written',
'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.',
'settings.account.savedCredentials': 'Saved credentials',
'settings.account.empty': 'No saved credentials.',
'settings.account.loading': 'Loading saved credentials…',
'settings.account.saved': 'Credential saved.',
'settings.account.removed': 'Saved credential removed.',
'settings.account.switched': 'Account switched. Refreshing the current quota.',
'settings.account.switching': 'Replacing the credential and confirming the active account…',
'settings.account.verifying': 'Verifying the credential owner…',
'settings.account.loadQuota': 'Check quota',
'settings.account.loadingQuota': 'Checking quota for this credential…',
'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.',
'settings.account.quota': 'Quota remaining by pool',
'settings.account.quota5h': '5 hours {percent}%',
'settings.account.quotaWeekly': 'Weekly {percent}%',
'settings.account.noQuota': 'Quota pools are unavailable for the current account.',
'settings.account.quotaStale': 'Quota refresh failed. Showing the last data for the current account.',
'settings.account.unsupported': 'Credential switching currently supports Antigravity shared sign-in on Windows.',
'settings.account.invalidEmail': 'Select a saved account first.',
'settings.account.invalidCredential': 'Enter a valid Antigravity OAuth credential for a personal account.',
'settings.account.credentialTooLarge': 'The credential exceeds the Windows Credential Manager limit of 2560 bytes.',
'settings.account.notFound': 'This credential was removed. Refresh the list.',
'settings.account.noCurrentCredential': 'The shared credential for the current account is unavailable.',
'settings.account.busy': 'Another window is updating credentials. Try again shortly.',
'settings.account.storeFailed': 'The credential operation failed. Try again.',
'settings.account.rollbackFailed': 'Writing and restoring the credential both failed. Check the active account in Antigravity before continuing.',
'settings.account.credentialAccessDenied': 'Windows denied access to Credential Manager. Open Antigravity in your Windows user session and try again.',
'settings.account.credentialChanged': 'This credential was updated in another window. Refresh the list and try again.',
'settings.account.credentialRejected': 'Google rejected this credential. Check that the Antigravity refresh token is still valid.',
'settings.account.identityMismatch': 'The credential belongs to a different account. Import the credential again.',
'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.',
'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.',
'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.',
'settings.subTab.aria': 'Preferences category tabs',
'settings.saving': 'Saving…',
'settings.saved': 'Saved',
@@ -1995,7 +2089,7 @@ function deliverCdpBridgeResponses(responses) {
return delivered;
}
function callViaCdpBridge(bridge, path, { method, body, signal }) {
function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
@@ -2017,7 +2111,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
bridge.rpcPending.delete(reqId);
cleanupQueueItem();
reject(new Error('CDP bridge timeout'));
}, 8000);
}, cdpTimeoutMs);
const onAbort = () => {
clearTimeout(timeoutId);
@@ -2056,7 +2150,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
});
}
async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 8000 } = {}) {
const upperMethod = method.toUpperCase();
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
@@ -2093,7 +2187,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}
if (bridge) {
headers['X-Usage-Monitor-Token'] = bridge.token;
if (bridge.transportMode === 'cdp') {
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
}
@@ -2111,7 +2205,7 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}
}
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
bridge.transportMode = 'cdp';
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
@@ -2170,7 +2264,7 @@ function getViewTabs() {
const uiStore = createReactiveStore({
activeView: 'overview',
stepsSubTab: 'steps', // 'steps' | 'models'
settingsSubTab: 'general', // 'general' | 'structure' | 'other'
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
});
@@ -2863,6 +2957,9 @@ function isEquivalentTelemetry(prev, next) {
// 8. 比对账号订阅档位与动态多配额池
if (
prev.account?.email !== next.account?.email ||
prev.account?.name !== next.account?.name ||
prev.account?.status !== next.account?.status ||
prev.account?.tierName !== next.account?.tierName ||
prev.account?.planName !== next.account?.planName ||
prev.account?.aiCredits !== next.account?.aiCredits
@@ -3040,6 +3137,12 @@ async function fetchTelemetry({ force = false } = {}) {
}
const latestSt = telemetryStore.getState();
const previousAccount = latestSt.telemetry?.account;
const nextAccount = payload?.account;
const accountChanged = previousAccount?.status === 'signedIn' &&
(nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' &&
(previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name)));
const accountPatch = accountChanged ? { selectedConversationId: '' } : {};
if (force) {
const elapsed = Date.now() - startMs;
if (elapsed < 220) {
@@ -3050,6 +3153,7 @@ async function fetchTelemetry({ force = false } = {}) {
}
if (feedbackTimer) clearTimeout(feedbackTimer);
telemetryStore.setState({
...accountPatch,
telemetry: payload,
minuteTick: Math.floor(Date.now() / 30000),
syncState: 'synced',
@@ -3062,6 +3166,7 @@ async function fetchTelemetry({ force = false } = {}) {
const isSame = isEquivalentTelemetry(latestSt.telemetry, payload);
const nextTelemetry = isSame ? latestSt.telemetry : payload;
telemetryStore.setState({
...accountPatch,
telemetry: nextTelemetry,
minuteTick: Math.floor(Date.now() / 30000),
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
@@ -11612,6 +11717,238 @@ const SettingsStructureTab = defineComponent({
},
});
// --- src/views/settings/SettingsAccountTab.js ---
/** @fileoverview Saved account credentials and the host's active account quota. */
const key = (name) => `settings.account.${name}`;
const errors = new Set([
'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
'oauthUnavailable', 'quotaUnavailable',
]);
function renderQuotaRows(container, quotaPools) {
const locale = getEffectiveLocale();
const pools = quotaPools.filter((pool) => Number.isFinite(pool.remainingPct) || Number.isFinite(pool.weeklyRemainingPct));
patchKeyedList(container, pools, {
keyFn: (pool) => pool.poolKey || pool.poolLabel,
sigFn: (pool) => JSON.stringify([locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct]),
createRow: () => {
const label = h('span');
const remaining = h('span', { className: 'settings-account-quota' });
return { el: h('div', { className: 'settings-action-block' }, [label, remaining]), refs: { label, remaining } };
},
updateRow: ({ label, remaining }, pool) => {
patchText(label, pool.poolLabel || pool.poolKey);
const values = [];
if (Number.isFinite(pool.remainingPct)) values.push(t(key('quota5h'), { percent: pool.remainingPct }));
if (Number.isFinite(pool.weeklyRemainingPct)) values.push(t(key('quotaWeekly'), { percent: pool.weeklyRemainingPct }));
patchText(remaining, values.join(' · '));
},
});
return pools.length;
}
const SettingsAccountTab = defineComponent({
name: 'SettingsAccountTab',
setup({ props, onCleanup }) {
let account = null;
let quotas = null;
let accounts = [];
let selectedEmail = '';
let supported = null;
let operation = '';
let status = '';
let disposed = false;
const savedQuotas = new Map();
const title = h('span', { className: 'panel-title' });
const identityLabel = h('div', { className: 'settings-action-title' });
const identity = h('div', { className: 'settings-action-desc settings-account-identity' });
const plan = h('div', { className: 'settings-action-desc' });
const quotaTitle = h('div', { className: 'settings-action-title' });
const quotaRows = h('div', { className: 'settings-account-list' });
const quotaMessage = h('div', { className: 'settings-action-desc' });
const savedTitle = h('span', { className: 'panel-title' });
const savedRows = h('div', { className: 'settings-account-list' });
const savedMessage = h('div', { className: 'settings-action-desc' });
const pending = h('div', { className: 'settings-action-desc', role: 'status' });
const feedback = h('div', { className: 'settings-action-desc', role: 'status' });
const capture = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('capture') });
const reload = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('list') });
const credentialLabel = h('span');
const importHint = h('div', { className: 'settings-action-desc' });
const credential = h('input', { type: 'password', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384 });
const save = h('button', { type: 'submit', className: 'btn-secondary' });
const form = h('form', { className: 'settings-account-form', autocomplete: 'off', onSubmit: importCredential }, [
h('label', {}, [credentialLabel, credential]),
importHint,
save,
]);
function render() {
const signedIn = account?.status === 'signedIn';
const activeEmail = signedIn ? account.email?.trim().toLowerCase() : '';
const canWrite = supported === true && !operation;
const locale = getEffectiveLocale();
patchText(title, t(key('current')));
patchText(identityLabel, t(key('email')));
patchText(identity, signedIn ? account.email || account.name :
t(key(account?.status === 'signedOut' ? 'signedOut' : 'unknown')));
patchText(plan, signedIn ? account.tierName || account.planName || '' : '');
patchAttr(plan, 'hidden', !plan.textContent);
patchText(quotaTitle, t(key('quota')));
const poolCount = renderQuotaRows(quotaRows, signedIn ? quotas?.pools || [] : []);
patchText(quotaMessage, t(key(poolCount ? 'quotaStale' : 'noQuota')));
patchAttr(quotaMessage, 'hidden', poolCount > 0 && !quotas?.meta?.isStale);
patchText(savedTitle, t(key('savedCredentials')));
patchText(capture, t(key('capture')));
patchText(reload, t(key('reload')));
patchText(save, t(key('save')));
patchText(credentialLabel, t(key('credential')));
patchText(importHint, t(key('importHint')));
patchAttr(capture, 'disabled', !canWrite || !activeEmail);
patchAttr(reload, 'disabled', Boolean(operation));
patchAttr(form, 'hidden', supported === false);
patchAttr(save, 'disabled', !canWrite);
patchAttr(credential, 'disabled', !canWrite);
patchText(savedMessage, t(key(supported === null ? 'loading' : 'empty')));
patchAttr(savedMessage, 'hidden', accounts.length > 0 || supported === false || Boolean(status));
const message = status || (operation === 'switch' ? 'switching' : operation === 'quota' ? 'loadingQuota' :
operation === 'save' || operation === 'capture' ? 'verifying' : '');
patchText(feedback, message ? t(key(message)) : '');
patchAttr(feedback, 'hidden', !message);
const waiting = selectedEmail && activeEmail !== selectedEmail;
patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : '');
patchAttr(pending, 'hidden', !waiting);
patchKeyedList(savedRows, accounts, {
keyFn: (addr) => addr,
sigFn: (addr) => JSON.stringify([locale, activeEmail, selectedEmail, canWrite, savedQuotas.get(addr)]),
createRow: (addr) => {
const state = h('div', { className: 'settings-action-desc' });
const select = h('button', {
type: 'button', className: 'btn-secondary settings-account-switch', onClick: () => request('switch', { email: addr }),
});
const remove = h('button', {
type: 'button', className: 'btn-secondary', onClick: () => request('remove', { email: addr }),
});
const loadQuota = h('button', {
type: 'button', className: 'btn-secondary settings-account-load-quota', onClick: () => request('quota', { email: addr }),
});
const rows = h('div', { className: 'settings-account-list' });
const empty = h('div', { className: 'settings-action-desc' });
return {
el: h('div', { className: 'settings-account-entry' }, [
h('div', { className: 'settings-action-block' }, [
h('div', { className: 'settings-action-info' }, [h('div', { className: 'settings-account-identity', text: addr }), state]),
h('div', { className: 'settings-account-buttons' }, [loadQuota, select, remove]),
]), rows, empty,
]),
refs: { state, select, remove, loadQuota, rows, empty },
};
},
updateRow: (row, addr) => {
const active = addr === activeEmail;
const written = addr === selectedEmail && !active;
patchText(row.state, active ? t(key('active')) : written ? t(key('written')) : '');
patchAttr(row.state, 'hidden', !active && !written);
patchText(row.select, t(key('switch')));
patchText(row.remove, t(key('remove')));
patchText(row.loadQuota, t(key('loadQuota')));
patchAttr(row.select, 'disabled', !canWrite);
patchAttr(row.remove, 'disabled', !canWrite);
patchAttr(row.loadQuota, 'disabled', !canWrite);
const cached = savedQuotas.get(addr);
const count = renderQuotaRows(row.rows, cached || []);
patchText(row.empty, t(key('emptyCredentialQuota')));
patchAttr(row.empty, 'hidden', !cached || count > 0);
},
});
props.onLayoutChange?.();
}
async function request(action, fields) {
if (operation) return;
operation = action;
status = '';
render();
try {
const result = action === 'list'
? await callSidecarApi('/api/accounts')
: await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields }, cdpTimeoutMs: 40000 });
if (disposed) return;
if (result?.error) {
if (result.error === 'unsupported') supported = false;
status = errors.has(result.error) ? result.error : 'storeFailed';
return;
}
if (action === 'quota') {
savedQuotas.set(result.email, result.pools);
return;
}
supported = result?.supported === true;
accounts = result?.accounts || [];
selectedEmail = result?.selectedEmail || '';
if (action === 'save' || action === 'capture') status = 'saved';
if (action === 'remove') {
savedQuotas.delete(fields.email);
status = 'removed';
}
if (action === 'switch') {
status = result.confirmed ? 'switched' : '';
void fetchTelemetry({ force: true }).catch(() => {});
}
} catch {
status = 'storeFailed';
} finally {
operation = '';
if (!disposed) render();
}
}
function importCredential(event) {
event.preventDefault();
if (operation) return;
const input = credential.value;
credential.value = '';
void request('save', { credential: input });
}
function renderAccount(value, quotaData) {
if (account === value && quotas === quotaData) return;
account = value;
quotas = quotaData;
render();
}
const root = h('div', { className: 'settings-tab-stack' }, [
h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [title]),
h('div', { className: 'settings-action-block' }, [
h('div', { className: 'settings-action-info' }, [identityLabel, identity, plan]),
]),
quotaTitle, quotaRows, quotaMessage, pending,
]),
h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [savedTitle]),
h('div', { className: 'settings-account-buttons' }, [capture, reload]),
savedRows, savedMessage, form, feedback,
]),
]);
render();
onCleanup(() => {
disposed = true;
credential.value = '';
});
return { el: root, refs: { renderAccount, refreshLabels: render, load: () => request('list') } };
},
});
// --- src/views/settings/SettingsOtherTab.js ---
/**
* @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他").
@@ -14481,16 +14818,19 @@ const StepsDetailView = defineComponent({
// --- src/views/SettingsView.js ---
/**
* @fileoverview View 4: Modular 3-Tab `SettingsView.js` ("常规" / "结构" / "其他").
* Orchestrates `SettingsGeneralTab`, `SettingsStructureTab`, and `SettingsOtherTab`
* @fileoverview View 4: Modular preferences ("常规" / "结构" / "账号" / "其他").
* Orchestrates the four preference tabs
* with top sub-navigation and a shared `CustomScrollbar` viewport.
*/
const SHOW_ACCOUNT_TAB = false;
function getSettingsSubTabOptions() {
return [
{ value: 'general', label: t('settings.subTab.general') },
{ value: 'structure', label: t('settings.subTab.structure') },
...(SHOW_ACCOUNT_TAB ? [{ value: 'account', label: t('settings.subTab.account') }] : []),
{ value: 'other', label: t('settings.subTab.other') },
];
}
@@ -14520,25 +14860,41 @@ const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
function applyActiveSubTab(subTab) {
let showingAccount = false;
function applyActiveSubTab(subTab, activeView) {
const target =
subTab === 'structure' || subTab === 'other' ? subTab : 'general';
subTab === 'structure' ||
subTab === 'other' ||
(SHOW_ACCOUNT_TAB && subTab === 'account')
? subTab
: 'general';
subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure');
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
patchAttr(otherTab.el, 'hidden', target !== 'other');
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
refreshScroll();
}
const contentContainer = h('div', {}, [generalTab.el, structureTab.el, otherTab.el]);
const contentContainer = h(
'div',
{},
SHOW_ACCOUNT_TAB
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
: [generalTab.el, structureTab.el, otherTab.el]
);
viewScrollbar = CustomScrollbar({
contentEl: contentContainer,
className: 'view-pane',
});
applyActiveSubTab(initialSubTab);
applyActiveSubTab(initialSubTab, uiStore.getState().activeView);
const rootEl = h('div', { className: 'settings-view-root' }, [
subNavBar,
@@ -14548,6 +14904,8 @@ const SettingsView = defineComponent({
let latestSettings = null;
let latestCloudStatus = null;
let latestContextWindowModels = [];
const initialTelemetry = telemetryStore.getState().telemetry;
accountTab.refs.renderAccount(initialTelemetry?.account, initialTelemetry?.quotas);
function syncAllTabs(settings, cloudStatus) {
if (settings) {
@@ -14566,11 +14924,14 @@ const SettingsView = defineComponent({
settings: st.telemetry?.settings,
cloudStatus: st.telemetry?.cloudStatus,
contextWindowModels: st.telemetry?.contextWindowModels,
account: st.telemetry?.account,
quotas: st.telemetry?.quotas,
}),
(slice) => {
latestSettings = slice.settings;
latestCloudStatus = slice.cloudStatus;
latestContextWindowModels = slice.contextWindowModels || [];
accountTab.refs.renderAccount(slice.account, slice.quotas);
if (slice.settings) {
generalTab.refs.renderSettings(slice.settings);
structureTab.refs.renderSettings(slice.settings);
@@ -14589,7 +14950,7 @@ const SettingsView = defineComponent({
settingsSubTab: st.settingsSubTab,
}),
(slice) => {
applyActiveSubTab(slice.settingsSubTab);
applyActiveSubTab(slice.settingsSubTab, slice.activeView);
if (slice.activeView === 'settings') {
syncAllTabs(latestSettings, latestCloudStatus);
}
@@ -14605,6 +14966,7 @@ const SettingsView = defineComponent({
});
generalTab.refs.refreshLabels();
structureTab.refs.refreshLabels();
accountTab.refs.refreshLabels();
otherTab.refs.refreshLabels();
refreshScroll();
}
@@ -14617,6 +14979,7 @@ const SettingsView = defineComponent({
subNavSwitch.destroy();
generalTab.destroy();
structureTab.destroy();
accountTab.destroy();
otherTab.destroy();
viewScrollbar.destroy();
});
@@ -14627,6 +14990,7 @@ const SettingsView = defineComponent({
subNavSwitch,
generalTab,
structureTab,
accountTab,
otherTab,
viewScrollbar,
// Convenience aliases for external callers / tests
@@ -0,0 +1,204 @@
$ErrorActionPreference = 'Stop'
[Console]::InputEncoding = [Text.UTF8Encoding]::new($false)
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false)
$utf8 = [Console]::OutputEncoding
function Test-AccountFile($path) {
if (-not (Test-Path -LiteralPath $path)) { return $false }
$item = Get-Item -LiteralPath $path -Force
if ($item.PSIsContainer -or ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
throw 'Invalid account file'
}
return $true
}
function Write-AccountFile($path, [byte[]]$bytes) {
$temp = Join-Path ([IO.Path]::GetDirectoryName($path)) ([guid]::NewGuid().ToString() + '.tmp')
try {
[IO.File]::WriteAllBytes($temp, $bytes)
if (Test-AccountFile $path) {
[IO.File]::Replace($temp, $path, [NullString]::Value)
} else {
[IO.File]::Move($temp, $path)
}
} finally {
[IO.File]::Delete($temp)
}
}
function Save-Vault($path, $vault) {
$bytes = $utf8.GetBytes((ConvertTo-Json -InputObject $vault -Depth 4 -Compress))
$encrypted = [Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($path))
Write-AccountFile $path $encrypted
}
function Add-NativeCredentialType {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
public static class NativeAccountCredential {
private const uint Generic = 1;
private const uint PersistLocalMachine = 2;
private const int NotFound = 1168;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct Credential {
public uint Flags, Type;
public string TargetName, Comment;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWritten;
public uint BlobSize;
public IntPtr Blob;
public uint Persist, AttributeCount;
public IntPtr Attributes;
public string TargetAlias, UserName;
}
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
private static extern bool CredReadW(string target, uint type, uint flags, out IntPtr credential);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
private static extern bool CredWriteW(ref Credential credential, uint flags);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)]
private static extern bool CredDeleteW(string target, uint type, uint flags);
[DllImport("advapi32.dll")]
private static extern void CredFree(IntPtr buffer);
public static byte[] Read(string target) {
IntPtr pointer;
if (!CredReadW(target, Generic, 0, out pointer)) {
int error = Marshal.GetLastWin32Error();
if (error == NotFound) return null;
throw new Win32Exception(error);
}
try {
var credential = (Credential)Marshal.PtrToStructure(pointer, typeof(Credential));
var bytes = new byte[credential.BlobSize];
if (bytes.Length > 0) Marshal.Copy(credential.Blob, bytes, 0, bytes.Length);
return bytes;
} finally {
CredFree(pointer);
}
}
public static void Write(string target, byte[] bytes) {
var buffer = GCHandle.Alloc(bytes, GCHandleType.Pinned);
try {
var credential = new Credential {
Type = Generic, Persist = PersistLocalMachine, TargetName = target,
UserName = "antigravity", Blob = buffer.AddrOfPinnedObject(), BlobSize = (uint)bytes.Length
};
if (!CredWriteW(ref credential, 0)) throw new Win32Exception(Marshal.GetLastWin32Error());
} finally {
buffer.Free();
}
}
public static void Restore(string target, byte[] bytes) {
if (bytes != null) Write(target, bytes);
else if (!CredDeleteW(target, Generic, 0)) {
int error = Marshal.GetLastWin32Error();
if (error != NotFound) throw new Win32Exception(error);
}
}
}
'@
}
function Invoke-AccountAction($request) {
Add-Type -AssemblyName System.Security
$vault = @{ entries = @(); selectedEmail = '' }
if (Test-AccountFile $request.vault) {
$plain = [Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($request.vault), $null, 'CurrentUser')
$vault = ConvertFrom-Json -InputObject ($utf8.GetString($plain))
}
$entry = $vault.entries | Where-Object { $_.email -eq $request.email } | Select-Object -First 1
if ($null -ne $request.expectedCredential -and $entry.credential -cne $request.expectedCredential) {
return @{ error = 'credentialChanged' }
}
switch ($request.action) {
'readCurrent' {
Add-NativeCredentialType
$bytes = [NativeAccountCredential]::Read($request.target)
if (-not $bytes) {
foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) {
$bytes = [IO.File]::ReadAllBytes($path)
if ($bytes) { break }
}
}
}
if (-not $bytes) { return @{ error = 'noCurrentCredential' } }
return @{ credential = $utf8.GetString($bytes).TrimStart([char]0xfeff).Trim() }
}
'read' {
if (-not $entry) { return @{ error = 'notFound' } }
return @{ credential = $entry.credential }
}
'save' {
if ($entry) { $entry.credential = $request.credential }
else { $vault.entries = @($vault.entries) + @(@{ email = $request.email; credential = $request.credential }) }
Save-Vault $request.vault $vault
}
'switch' {
if (-not $entry) { return @{ error = 'notFound' } }
$replacement = $utf8.GetBytes($request.credential)
if ($replacement.Length -gt 2560) { return @{ error = 'credentialTooLarge' } }
Add-NativeCredentialType
$previous = [NativeAccountCredential]::Read($request.target)
$fallbacks = @(foreach ($path in $request.fallbacks) {
if (Test-AccountFile $path) { @{ path = $path; original = [IO.File]::ReadAllBytes($path) } }
})
$written = @()
[NativeAccountCredential]::Write($request.target, $replacement)
try {
foreach ($fallback in $fallbacks) {
Write-AccountFile $fallback.path $replacement
$written += $fallback
}
$entry.credential = $request.credential
$vault.selectedEmail = $request.email
Save-Vault $request.vault $vault
} catch {
$restored = $true
try { [NativeAccountCredential]::Restore($request.target, $previous) } catch { $restored = $false }
foreach ($fallback in $written) {
try { Write-AccountFile $fallback.path $fallback.original } catch { $restored = $false }
}
if (-not $restored) { return @{ error = 'rollbackFailed' } }
throw
}
}
'remove' {
if (-not $entry) { return @{ error = 'notFound' } }
$vault.entries = @($vault.entries | Where-Object { $_.email -ne $request.email })
if ($vault.selectedEmail -eq $request.email) { $vault.selectedEmail = '' }
Save-Vault $request.vault $vault
}
}
return @{ accounts = @($vault.entries | ForEach-Object { $_.email }); selectedEmail = $vault.selectedEmail }
}
$mutex = $null
$locked = $false
try {
$request = ConvertFrom-Json -InputObject ([Console]::In.ReadToEnd())
$mutex = [Threading.Mutex]::new($false, 'Local\AntigravityUsageMonitor.AccountCredentials')
try { $locked = $mutex.WaitOne(4000) } catch [Threading.AbandonedMutexException] { $locked = $true }
$result = if ($locked) { Invoke-AccountAction $request } else { @{ error = 'busy' } }
} catch {
$result = @{ error = 'storeFailed' }
$nativeError = $_.Exception.InnerException
if ($nativeError -is [ComponentModel.Win32Exception] -and $nativeError.NativeErrorCode -in 5, 1312) {
$result.error = 'credentialAccessDenied'
}
} finally {
if ($locked) { $mutex.ReleaseMutex() }
if ($mutex) { $mutex.Dispose() }
}
[Console]::Write((ConvertTo-Json -InputObject $result -Compress))
+178
View File
@@ -0,0 +1,178 @@
/** @fileoverview Google OAuth identity and quota queries for saved Antigravity credentials. */
import { readFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { buildOfficialQuotaPools } from './quota-pools.mjs';
const OAUTH_TOKEN_URL = 'https://oauth2.googleapis.com/token';
const OAUTH_USER_URL = 'https://www.googleapis.com/oauth2/v2/userinfo';
const CLOUD_CODE_HOSTS = ['cloudcode-pa.googleapis.com', 'daily-cloudcode-pa.googleapis.com'];
let nativeOAuthClients;
export function extractNativeOAuthClients(binary) {
const pe = binary.length >= 64 && binary.readUInt16LE(0) === 0x5a4d ? binary.readUInt32LE(60) : 0;
if (!pe || pe + 24 > binary.length || binary.readUInt32LE(pe) !== 0x4550 || binary.readUInt16LE(pe + 4) !== 0x8664) return [];
const count = binary.readUInt16LE(pe + 6);
const table = pe + 24 + binary.readUInt16LE(pe + 20);
if (table + count * 40 > binary.length) return [];
const sections = Array.from({ length: count }, (_, i) => {
const offset = table + i * 40;
return {
name: binary.toString('ascii', offset, offset + 8).replace(/\0+$/, ''),
rva: binary.readUInt32LE(offset + 12),
size: binary.readUInt32LE(offset + 16),
start: binary.readUInt32LE(offset + 20),
};
});
const text = sections.find(({ name }) => name === '.text');
const rodata = sections.find(({ name }) => name === '.rdata');
if (!text || !rodata || text.start + text.size > binary.length || rodata.start + rodata.size > binary.length) return [];
const machineCode = binary.subarray(text.start, text.start + text.size);
function readLiteral(displacementOffset, length) {
const rva = text.rva + displacementOffset + 4 + machineCode.readInt32LE(displacementOffset);
const offset = rva - rodata.rva;
if (length > 100 || offset < 0 || offset + length > rodata.size) return '';
return binary.toString('ascii', rodata.start + offset, rodata.start + offset + length);
}
// Go's x64 OAuth config initializer sets ClientID and ClientSecret as two consecutive pointer/length pairs.
const idLength = Buffer.from([0x48, 0xc7, 0x40, 0x08]);
const loadAndStoreId = Buffer.from([0x48, 0x8d, 0x0d]);
const betweenLiterals = Buffer.from([0x48, 0x89, 0x08, 0x48, 0xc7, 0x40, 0x18]);
const clients = new Map();
for (let i = machineCode.indexOf(idLength); i >= 0 && i + 33 <= machineCode.length; i = machineCode.indexOf(idLength, i + 1)) {
if (!machineCode.subarray(i + 8, i + 11).equals(loadAndStoreId) ||
!machineCode.subarray(i + 15, i + 22).equals(betweenLiterals) ||
!machineCode.subarray(i + 26, i + 29).equals(loadAndStoreId)) continue;
const id = readLiteral(i + 11, machineCode.readUInt32LE(i + 4));
const secret = readLiteral(i + 29, machineCode.readUInt32LE(i + 22));
if (/^\d+-[\w-]+\.apps\.googleusercontent\.com$/.test(id) && /^GOCSPX-[\w-]+$/.test(secret)) {
clients.set(id, { id, secret });
}
}
return Array.from(clients.values()).reverse();
}
async function loadNativeOAuthClients() {
if (!nativeOAuthClients) {
nativeOAuthClients = (async () => {
const local = process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local');
const binaries = [
join(local, 'Programs', 'Antigravity', 'resources', 'bin', 'language_server.exe'),
join(homedir(), '.gemini', 'bin', 'agy.exe'),
];
for (const filename of binaries) {
const binary = await readFile(filename).catch(() => null);
const clients = binary ? extractNativeOAuthClients(binary) : [];
if (clients.length) return clients;
}
return [];
})();
}
const clients = await nativeOAuthClients;
if (!clients.length) nativeOAuthClients = null;
return clients;
}
export async function resolveGoogleCredential(credential, { refresh = false, fetchFn = fetch, getClients = loadNativeOAuthClients } = {}) {
let { access_token: accessToken, refresh_token: refreshToken, expiry } = credential.token;
let idToken = credential.id_token;
if (refresh || !accessToken || Date.parse(expiry) <= Date.now() + 60_000) {
const clients = await getClients();
if (!clients.length) throw new Error('oauthClientUnavailable');
let refreshed = false;
for (const { id, secret } of clients) {
const response = await fetchFn(OAUTH_TOKEN_URL, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(6000),
body: new URLSearchParams({ client_id: id, client_secret: secret, grant_type: 'refresh_token', refresh_token: refreshToken }),
});
const result = await response.json();
if (!response.ok) {
if (['invalid_grant', 'invalid_client', 'unauthorized_client'].includes(result?.error)) continue;
throw new Error('oauthUnavailable');
}
if (!result.access_token || !Number.isFinite(result.expires_in) || result.expires_in <= 0) throw new Error('oauthUnavailable');
accessToken = result.access_token;
refreshToken = result.refresh_token || refreshToken;
idToken = result.id_token;
expiry = new Date(Date.now() + result.expires_in * 1000).toISOString();
refreshed = true;
break;
}
if (!refreshed) throw new Error('credentialRejected');
}
const userResponse = await fetchFn(OAUTH_USER_URL, {
redirect: 'error', signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${accessToken}` },
});
if (!userResponse.ok) throw new Error(userResponse.status === 401 ? 'credentialRejected' : 'oauthUnavailable');
const user = await userResponse.json();
if (!user.email || user.verified_email === false) throw new Error('credentialRejected');
return {
email: user.email,
credential: {
token: { access_token: accessToken, refresh_token: refreshToken, token_type: 'Bearer', expiry },
auth_method: 'consumer',
id_token_email: user.email,
...(idToken ? { id_token: idToken } : {}),
},
};
}
export async function retrieveCredentialQuota(accessToken, fetchFn = fetch) {
async function post(method, data) {
for (const host of CLOUD_CODE_HOSTS) {
const response = await fetchFn(`https://${host}/v1internal:${method}`, {
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4500),
headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}).catch(() => null);
if (response?.ok) {
const payload = await response.json().catch(() => null);
if (payload) return payload.response ?? payload;
}
if (response?.status === 401 || response?.status === 403) break;
}
return null;
}
const setup = await post('loadCodeAssist', { metadata: { ideType: 'ANTIGRAVITY' } });
const project = setup?.cloudaicompanionProject?.id || setup?.cloudaicompanionProject;
if (!setup) throw new Error('quotaUnavailable');
const request = {
project: typeof project === 'string' && project ? project : 'cloudaicompanion-enterprise',
};
const clientConfigs = setup.cascadeModelConfigData?.clientModelConfigs;
const [summary, available] = await Promise.all([
post('retrieveUserQuotaSummary', request),
Array.isArray(clientConfigs) && clientConfigs.length ? null : post('fetchAvailableModels', request),
]);
const configs = Array.isArray(clientConfigs) && clientConfigs.length ? clientConfigs :
Object.entries(available?.models || {}).filter(([, model]) => model?.quotaInfo && !model.disabled)
.map(([modelId, model]) => ({ modelId, modelOrAlias: { model: modelId }, label: model.displayName, quotaInfo: model.quotaInfo }));
const raw = summary?.quotaSummary ?? summary;
if (!Array.isArray(raw?.groups) && !Array.isArray(raw?.buckets) && !configs.length) throw new Error('quotaUnavailable');
const adaptBuckets = (buckets) => (Array.isArray(buckets) ? buckets : []).map((bucket) => ({
...bucket,
bucketId: bucket?.bucketId ?? bucket?.bucket_id,
remainingFraction: bucket?.remainingFraction ?? bucket?.remaining_fraction,
resetTime: bucket?.resetTime ?? bucket?.reset_time,
}));
const quota = {
groups: (Array.isArray(raw?.groups) ? raw.groups : []).map((group) => ({
...group, displayName: group?.displayName || group?.name, buckets: adaptBuckets(group?.buckets),
})),
buckets: adaptBuckets(raw?.buckets),
};
const { quotaPoolsMap } = buildOfficialQuotaPools(quota, configs);
return Array.from(quotaPoolsMap.values()).filter(({ isAvailable }) => isAvailable).map((pool) => ({
poolKey: pool.poolKey,
poolLabel: pool.poolLabel,
remainingPct: pool.remainingPct,
weeklyRemainingPct: pool.weeklyRemainingPct,
resetTime: pool.resetTime,
weeklyResetTime: pool.weeklyResetTime,
}));
}
+173
View File
@@ -0,0 +1,173 @@
/** @fileoverview Antigravity shared credentials and the plugin's Windows credential vault. */
import { spawn } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import { resolveGoogleCredential, retrieveCredentialQuota } from './account-oauth.mjs';
import { HERE } from './config.mjs';
import { callLsRpc } from './ls-rpc.mjs';
const ACCOUNT_ERRORS = new Set([
'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
'oauthUnavailable', 'quotaUnavailable',
]);
export function normalizeAccountEmail(value) {
const email = typeof value === 'string' ? value.trim().toLowerCase() : '';
return email.length <= 254 && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email) ? email : '';
}
export function normalizeAccountCredential(input) {
if (typeof input !== 'string' || Buffer.byteLength(input, 'utf8') > 16384) return null;
const text = input.trim();
let source;
try { source = JSON.parse(text); } catch {
if (!/^1\/{1,2}[\w.-]{20,}$/.test(text)) return null;
source = { refresh_token: text };
}
const token = source?.token || source;
if (!token || (source.auth_method && source.auth_method !== 'consumer') ||
typeof token.refresh_token !== 'string' || !token.refresh_token.trim() ||
/\s/.test(token.refresh_token) || (token.token_type && !/^bearer$/i.test(token.token_type))) return null;
const timestamp = token.expiry_date ?? (Number(token.expiry_timestamp) * 1000);
const expiry = token.expiry || (Number.isSafeInteger(timestamp) && timestamp > 0 && timestamp <= 253402300799999
? new Date(timestamp).toISOString() : '1970-01-01T00:00:00Z');
if (typeof expiry !== 'string' || !Number.isFinite(Date.parse(expiry))) return null;
const payload = {
token: {
access_token: typeof token.access_token === 'string' ? token.access_token : '',
refresh_token: token.refresh_token,
token_type: 'Bearer',
expiry: new Date(expiry).toISOString(),
},
auth_method: 'consumer',
};
const idToken = source.id_token || token.id_token;
if (typeof idToken === 'string' && idToken) payload.id_token = idToken;
return JSON.stringify(payload);
}
export function runWindowsCredentialStore(request) {
const script = readFileSync(join(HERE, 'backend', 'account-credentials.ps1'), 'utf8');
const encoded = Buffer.from(script, 'utf16le').toString('base64');
const shell = join(process.env.SystemRoot || 'C:/Windows', 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
return new Promise((resolve, reject) => {
// The helper exchanges private data over its pipes, keeping it out of process arguments.
const child = spawn(shell, ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded], { windowsHide: true, stdio: ['pipe', 'pipe', 'ignore'] });
let output = '';
child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => { output += chunk; });
child.on('error', reject);
child.stdin.on('error', reject);
child.on('close', (code) => {
if (code !== 0) return reject(new Error('storeFailed'));
try { resolve(JSON.parse(output.replace(/^\uFEFF/, ''))); } catch { reject(new Error('storeFailed')); }
});
child.stdin.end(JSON.stringify(request), 'utf8');
});
}
function serializeHostCredential(credential) {
let payload = JSON.stringify(credential);
if (Buffer.byteLength(payload, 'utf8') > 2560 && credential.id_token) {
const { id_token, ...compact } = credential;
payload = JSON.stringify(compact);
}
if (Buffer.byteLength(payload, 'utf8') > 2560) throw new Error('credentialTooLarge');
return payload;
}
async function confirmHostCredential(email, rpc) {
for (let attempt = 0; attempt < 3; attempt += 1) {
await rpc('GetAuthStatus', {}, 1200).catch(() => null);
const status = await rpc('GetUserStatus', {}, 1200).catch(() => null);
if (normalizeAccountEmail(status?.userStatus?.email) === email) return true;
if (attempt < 2) await delay(300);
}
return false;
}
export async function handleAccountCredentialAction(data, {
platform = process.platform,
store = runWindowsCredentialStore,
rpc = callLsRpc,
resolveCredential = resolveGoogleCredential,
getQuota = retrieveCredentialQuota,
} = {}) {
if (platform !== 'win32') return { supported: false, accounts: [], error: 'unsupported' };
const action = data?.action || 'list';
if (!['list', 'save', 'capture', 'switch', 'remove', 'quota'].includes(action)) return { error: 'invalidCredential' };
const email = normalizeAccountEmail(data?.email);
if (['switch', 'remove', 'quota'].includes(action) && !email) return { error: 'invalidEmail' };
const gemini = join(homedir(), '.gemini');
const config = {
target: 'gemini:antigravity',
vault: join(process.env.LOCALAPPDATA || join(homedir(), 'AppData', 'Local'), 'AntigravityUsageMonitor', 'accounts.dpapi'),
fallbacks: [join(gemini, 'jetski-standalone-oauth-token'), join(gemini, 'antigravity-cli', 'antigravity-oauth-token')],
};
async function runStore(fields) {
const result = await store({ ...config, ...fields });
if (!result || result.error) throw new Error(result?.error || 'storeFailed');
return result;
}
function publicList(result) {
return {
supported: true,
accounts: (Array.isArray(result.accounts) ? result.accounts : []).map(normalizeAccountEmail).filter(Boolean),
selectedEmail: normalizeAccountEmail(result.selectedEmail),
};
}
async function verifyCredential(raw, refresh = false) {
const normalized = normalizeAccountCredential(raw);
if (!normalized) throw new Error('invalidCredential');
let result;
try {
result = await resolveCredential(JSON.parse(normalized), { refresh });
} catch (error) {
throw new Error(ACCOUNT_ERRORS.has(error?.message) ? error.message : 'oauthUnavailable');
}
result.email = normalizeAccountEmail(result.email);
if (!result.email) throw new Error('credentialRejected');
return result;
}
try {
if (action === 'list' || action === 'remove') return publicList(await runStore({ action, email }));
if (action === 'save') {
const verified = await verifyCredential(data.credential, true);
return publicList(await runStore({ action, email: verified.email, credential: serializeHostCredential(verified.credential) }));
}
if (action === 'capture') {
const status = await rpc('GetUserStatus', {}, 2000).catch(() => null);
const activeEmail = normalizeAccountEmail(status?.userStatus?.email);
if (!activeEmail) throw new Error('noCurrentCredential');
const { credential } = await runStore({ action: 'readCurrent' });
const verified = await verifyCredential(credential);
if (verified.email !== activeEmail) throw new Error('identityMismatch');
return publicList(await runStore({ action: 'save', email: activeEmail, credential: serializeHostCredential(verified.credential) }));
}
const saved = await runStore({ action: 'read', email });
const verified = await verifyCredential(saved.credential);
if (verified.email !== email) throw new Error('identityMismatch');
const credential = serializeHostCredential(verified.credential);
if (action === 'quota') {
if (credential !== saved.credential) {
await runStore({ action: 'save', email, credential, expectedCredential: saved.credential });
}
const pools = await getQuota(verified.credential.token.access_token);
return { email, pools };
}
const updated = await runStore({ action: 'switch', email, credential, expectedCredential: saved.credential });
const confirmed = await confirmHostCredential(email, rpc);
return { ...publicList(updated), confirmed };
} catch (error) {
return { error: ACCOUNT_ERRORS.has(error?.message) ? error.message : 'storeFailed' };
}
}
+17
View File
@@ -8,6 +8,7 @@
import { readFileSync, promises as fsPromises } from 'node:fs';
import { join } from 'node:path';
import { handleAccountCredentialAction } from './account-switch.mjs';
import {
HERE,
SETTINGS_FILE,
@@ -337,6 +338,16 @@ export async function executePluginUpdateAction() {
};
}
export async function executeAccountCredentialAction(data) {
const result = await handleAccountCredentialAction(data);
return {
status: 200,
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
if (pathname === '/api/telemetry' && method === 'GET') {
return executeTelemetryAction(data, opts);
@@ -344,6 +355,12 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
if (pathname === '/api/settings' && method === 'POST') {
return executeSettingsAction(data);
}
if (pathname === '/api/accounts' && method === 'GET') {
return executeAccountCredentialAction();
}
if (pathname === '/api/accounts/update' && method === 'POST') {
return executeAccountCredentialAction(data);
}
if (pathname === '/api/context-window' && method === 'POST') {
return executeModelContextWindowAction(data);
}
+10 -4
View File
@@ -170,15 +170,19 @@ export function setLsRuntimeEndpoint(nextAddr, nextCsrfToken) {
/**
* GitHub 官方云端价格目录与插件发布包地址配置。
*/
export const OFFICIAL_GITHUB_REPO = 'yuhuan-dev/antigravity-usage-monitor';
export const LEGACY_GITHUB_REPOS = Object.freeze([
'yuhuan2498281558/antigravity-usage-monitor',
]);
export const CLOUD_CATALOG_URLS = [
'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
`https://raw.githubusercontent.com/${OFFICIAL_GITHUB_REPO}/main/pricing-catalog.json`,
];
export const DEFAULT_RELEASE_URL =
'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest';
`https://github.com/${OFFICIAL_GITHUB_REPO}/releases/latest`;
export const DEFAULT_DOWNLOAD_URL =
'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip';
`https://github.com/${OFFICIAL_GITHUB_REPO}/releases/latest/download/usage-monitor.zip`;
export const DEFAULT_ARCHIVE_FALLBACK_URL =
'https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main';
`https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`;
/** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
@@ -363,6 +367,7 @@ export const quotaSummaryCache = {
ts: 0,
lastAttemptTs: 0,
accountName: '',
accountGeneration: 0,
data: null,
error: null,
};
@@ -409,6 +414,7 @@ export function clearRuntimeCaches() {
quotaSummaryCache.ts = 0;
quotaSummaryCache.lastAttemptTs = 0;
quotaSummaryCache.accountName = '';
quotaSummaryCache.accountGeneration += 1;
quotaSummaryCache.data = null;
quotaSummaryCache.error = null;
return saveJson(CACHE_FILE, {});
+9 -11
View File
@@ -537,7 +537,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
*
* @param {{
* summariesObj?: Record<string, object>,
* currentAccountName?: string,
* currentAccountName?: string|null,
* requestedConvId?: string,
* forceRefresh?: boolean
* }} params
@@ -610,13 +610,11 @@ export async function enumerateAndSyncConversations({
}
// 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表
for (const [cacheKey, entry] of Object.entries(trajectoryCache)) {
const cacheKeyLower = String(cacheKey || '').toLowerCase();
for (const entry of Object.values(trajectoryCache)) {
if (
entry?.accountName &&
currentAccountName &&
entry.accountName !== currentAccountName &&
!summariesByLower.has(cacheKeyLower)
currentAccountName !== '' &&
entry.accountName !== currentAccountName
) {
continue;
}
@@ -635,9 +633,8 @@ export async function enumerateAndSyncConversations({
const cached = trajectoryCache[cascadeId];
if (
cached?.accountName &&
currentAccountName &&
cached.accountName !== currentAccountName &&
!item
currentAccountName !== '' &&
cached.accountName !== currentAccountName
) {
continue;
}
@@ -1262,8 +1259,9 @@ export async function enumerateAndSyncConversations({
))) ||
conversations[0] ||
null;
const safeReqId =
requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null;
const requestedOwner = trajectoryCache[canonicalIdByLower.get(reqLower)]?.accountName;
const safeReqId = requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) &&
(!requestedOwner || currentAccountName === '' || requestedOwner === currentAccountName) ? requestedConvId : null;
const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null;
return {
+17 -1
View File
@@ -122,9 +122,21 @@ export async function callLsRpc(method, body = {}, timeoutMs = 5000) {
* 向 LS 传递 `{ forceRefresh: true }`,绕过 `language_server.exe` 自身的 3 分钟缓存。
*
* @param {boolean} [forceRefresh=false] 是否强制穿透本地缓存与失败冷却
* @param {string} [accountName=''] 发起查询时宿主报告的账号,用于隔离配额缓存
* @returns {Promise<{data: object|null, fetchedAtMs: number, isStale: boolean, refreshFailed: boolean, error: string|null, fromCache: boolean}>}
*/
export async function getOfficialQuotaSummary(forceRefresh = false) {
export async function getOfficialQuotaSummary(forceRefresh = false, accountName = '') {
if (quotaSummaryCache.accountName !== accountName) {
Object.assign(quotaSummaryCache, {
accountName,
accountGeneration: quotaSummaryCache.accountGeneration + 1,
ts: 0,
lastAttemptTs: 0,
data: null,
error: null,
});
}
const generation = quotaSummaryCache.accountGeneration;
const now = Date.now();
if (!forceRefresh && quotaSummaryCache.data && now - quotaSummaryCache.ts < QUOTA_CACHE_TTL_MS) {
return {
@@ -155,6 +167,9 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
quotaSummaryCache.lastAttemptTs = now;
try {
const res = await callLsRpc('RetrieveUserQuotaSummary', { forceRefresh: true }, 6000);
const { userStatus } = await callLsRpc('GetUserStatus', {}, 2000);
if ((userStatus?.email || userStatus?.name || '') !== accountName) return {};
if (generation !== quotaSummaryCache.accountGeneration) return {};
const payload = res?.response !== undefined ? res.response : res;
if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
const normalized =
@@ -175,6 +190,7 @@ export async function getOfficialQuotaSummary(forceRefresh = false) {
}
quotaSummaryCache.error = 'Quota summary empty';
} catch (err) {
if (generation !== quotaSummaryCache.accountGeneration) return {};
console.error(`RetrieveUserQuotaSummary failed: ${err.message}`);
quotaSummaryCache.error = err.message;
}
+60 -12
View File
@@ -26,6 +26,9 @@ import {
DATA_DIR,
DEFAULT_ARCHIVE_FALLBACK_URL,
DEFAULT_DOWNLOAD_URL,
LEGACY_GITHUB_REPOS,
LS_ADDR,
OFFICIAL_GITHUB_REPO,
PLUGIN_ROOT,
REMOTE_CATALOG_CACHE_FILE,
cloudSyncState,
@@ -76,13 +79,8 @@ function runExecFile(cmd, args, opts = {}) {
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
*/
export function scheduleSidecarRestart(delayMs = 350) {
if (
!lsRuntimeEndpoint.addr ||
lsRuntimeEndpoint.addr === 'test.invalid' ||
typeof process?.exit !== 'function'
) {
return;
}
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
if (!activeAddr || activeAddr === 'test.invalid' || typeof process?.exit !== 'function') return;
setTimeout(() => {
try {
process.exit(0);
@@ -164,13 +162,39 @@ function pruneExtraneousFiles(targetDir, referenceDir) {
}
}
/**
* 若本地 Git 仓库的 `origin` 仍指向已迁移的旧官方仓库地址,返回同协议的新官方仓库地址;
* 对于非旧官方仓库(如已是新地址或用户自建 Fork)返回空字符串,不做改动。
*
* @param {string} rawUrl
* @returns {string}
*/
export function resolveMigratedGitRemoteUrl(rawUrl) {
const trimmed = String(rawUrl || '').trim();
if (!trimmed) return '';
for (const legacyRepo of LEGACY_GITHUB_REPOS) {
const escaped = legacyRepo.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
if (new RegExp(`^https://github\\.com/${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
return `https://github.com/${OFFICIAL_GITHUB_REPO}.git`;
}
if (new RegExp(`^git@github\\.com:${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
return `git@github.com:${OFFICIAL_GITHUB_REPO}.git`;
}
if (new RegExp(`^ssh://git@github\\.com/${escaped}(?:\\.git)?/?$`, 'i').test(trimmed)) {
return `ssh://git@github.com/${OFFICIAL_GITHUB_REPO}.git`;
}
}
return '';
}
/**
* 在真实运行环境下对目标目录的核心 JS 文件执行 `node --check` 语法预检。
*
* @param {string} rootDir 插件根目录或解压目录
*/
async function verifyPluginJsSyntax(rootDir) {
if (!lsRuntimeEndpoint.addr || lsRuntimeEndpoint.addr === 'test.invalid') return;
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
if (!activeAddr || activeAddr === 'test.invalid') return;
const nodeBin = process?.execPath || 'node';
const filesToCheck = [
join(rootDir, 'sidecars', 'panel', 'main.mjs'),
@@ -285,7 +309,31 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
const targetBranch = currentBranch || 'main';
const remoteRef = `origin/${targetBranch}`;
// 3. 只读拉取远端分支引用,并严格从 origin/<branch>:plugin.json 读取远端版本号(严禁回退使用缓存版本)
// 3. 存量旧仓库远程地址平滑迁移:若 origin 仍指向已更换的旧官方仓库,自动切换至新仓库地址
try {
const remoteUrlRes = await runExecFile('git', [
'-C',
PLUGIN_ROOT,
'remote',
'get-url',
'origin',
]);
const migratedRemoteUrl = resolveMigratedGitRemoteUrl(remoteUrlRes.stdout);
if (migratedRemoteUrl) {
await runExecFile('git', [
'-C',
PLUGIN_ROOT,
'remote',
'set-url',
'origin',
migratedRemoteUrl,
]);
}
} catch {
// 忽略非标准 remote 配置异常,不阻断常规拉取
}
// 4. 只读拉取远端分支引用,并严格从 origin/<branch>:plugin.json 读取远端版本号(严禁回退使用缓存版本)
await runExecFile('git', ['-C', PLUGIN_ROOT, 'fetch', 'origin', targetBranch, '--tags']);
let remoteVersion = '';
@@ -306,7 +354,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
remoteVersion = '';
}
// 4. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
// 5. 强制版本门禁:远端版本无法确认或不高于当前版本时,严禁执行 git pull 降级/覆盖
if (!remoteVersion || compareSemver(remoteVersion, previousVersion) <= 0) {
const msg = `当前已是最新版本 (v${previousVersion})`;
const result = {
@@ -325,7 +373,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
return result;
}
// 5. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
// 6. 提交拓扑预检:确保当前 HEAD 是远端分支的祖先提交(无本地超前或分叉提交)
try {
await runExecFile('git', [
'-C',
@@ -351,7 +399,7 @@ export async function performPluginUpdate({ isAuto = false } = {}) {
return pluginUpdateState.lastResult;
}
// 6. 确认全部门禁通过后,执行快进合并并校验 JS 语法
// 7. 确认全部门禁通过后,执行快进合并并校验 JS 语法
await runExecFile('git', ['-C', PLUGIN_ROOT, 'pull', '--ff-only', 'origin', targetBranch]);
await verifyPluginJsSyntax(PLUGIN_ROOT);
rebuildActiveCatalog();
+35 -3
View File
@@ -16,7 +16,9 @@ import {
DEFAULT_ARCHIVE_FALLBACK_URL,
DEFAULT_DOWNLOAD_URL,
DEFAULT_RELEASE_URL,
LEGACY_GITHUB_REPOS,
LOCAL_CATALOG_FILE,
OFFICIAL_GITHUB_REPO,
PLUGIN_MANIFEST_FILE,
PLUGIN_ROOT,
REMOTE_CATALOG_CACHE_FILE,
@@ -44,7 +46,35 @@ export function isValidSemver(v) {
);
}
const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor';
const OFFICIAL_REPO_PATH_PREFIX = `/${OFFICIAL_GITHUB_REPO.toLowerCase()}`;
const LEGACY_REPO_PATH_PREFIXES = LEGACY_GITHUB_REPOS.map((repo) => `/${repo.toLowerCase()}`);
/**
* 判断来源 URL 是否属于已迁移的旧官方 GitHub 仓库地址。
*
* @param {*} rawUrl
* @returns {boolean}
*/
function isLegacyGithubRepoUrl(rawUrl) {
if (typeof rawUrl !== 'string' || !rawUrl.trim()) return false;
try {
const parsed = new URL(rawUrl.trim());
const host = parsed.hostname.toLowerCase();
const pathname = parsed.pathname.toLowerCase();
if (
host !== 'github.com' &&
host !== 'raw.githubusercontent.com' &&
host !== 'codeload.github.com'
) {
return false;
}
return LEGACY_REPO_PATH_PREFIXES.some(
(prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`)
);
} catch {
return false;
}
}
/**
* 校验更新/下载链接是否属于可信的 GitHub 官方仓库与 HTTPS 域名白名单。
@@ -245,6 +275,8 @@ export function sanitizeCatalogPayload(raw) {
const explicitReleaseUrl = sanitizeTrustedGithubUrl(raw.releaseUrl, '');
const explicitDownloadUrl = sanitizeTrustedGithubUrl(raw.downloadUrl, '');
const explicitArchiveUrl = sanitizeTrustedGithubUrl(raw.archiveFallbackUrl, '');
const rawSourceUrl = typeof raw.sourceUrl === 'string' ? raw.sourceUrl.trim() : '';
const isLegacySource = isLegacyGithubRepoUrl(rawSourceUrl);
return {
schemaVersion: Number(raw.schemaVersion || 1),
@@ -261,8 +293,8 @@ export function sanitizeCatalogPayload(raw) {
hasReleaseUrl: Boolean(explicitReleaseUrl),
hasDownloadUrl: Boolean(explicitDownloadUrl),
hasArchiveFallbackUrl: Boolean(explicitArchiveUrl),
fetchedAtMs: Number(raw.fetchedAtMs || 0),
sourceUrl: typeof raw.sourceUrl === 'string' ? raw.sourceUrl : '',
fetchedAtMs: isLegacySource ? 0 : Number(raw.fetchedAtMs || 0),
sourceUrl: isLegacySource ? '' : rawSourceUrl,
pricing,
placeholders,
};
+11 -32
View File
@@ -20,7 +20,6 @@ import {
computeRuntimeCodeVersion,
inFlightRequests,
loadSettings,
quotaSummaryCache,
roundMetric,
trajectoryCache,
} from './config.mjs';
@@ -393,39 +392,17 @@ export async function buildTelemetryPayloadInternal(
filterOpts = {}
) {
const settings = loadSettings();
const [userStatusRes, allTrajRes, initialOfficialQuotaInfo, contextModelCatalog] = await Promise.all([
callLsRpc('GetUserStatus', {}).catch(() => ({})),
const userStatus = await callLsRpc('GetUserStatus', {}).then((data) => data?.userStatus).catch(() => null);
const currentAccountName = userStatus?.email || userStatus?.name || '';
const accountStatus = currentAccountName ? 'signedIn' :
userStatus && !userStatus.userTier && !userStatus.planStatus ? 'signedOut' : 'unknown';
const accountScope = accountStatus === 'signedOut' ? null : currentAccountName;
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
getOfficialQuotaSummary(forceQuotaRefresh),
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
getContextModelCatalog(),
]);
const userStatus = userStatusRes?.userStatus || {};
const currentAccountName = userStatus?.email || userStatus?.name || '';
let officialQuotaInfo = initialOfficialQuotaInfo;
// 若检测到账号发生切换:仅当并发的 initialOfficialQuotaInfo 命中了旧账号本地缓存 (fromCache === true) 时才需清空并重刷;
// 若本轮已经实时穿透请求了上游 RPC (fromCache === false),直接更新归属账号即可,避免二次重复 RPC
const accountChanged = Boolean(
currentAccountName &&
quotaSummaryCache.accountName &&
quotaSummaryCache.accountName !== currentAccountName
);
if (accountChanged) {
if (initialOfficialQuotaInfo?.fromCache) {
quotaSummaryCache.data = null;
quotaSummaryCache.ts = 0;
quotaSummaryCache.lastAttemptTs = 0;
quotaSummaryCache.error = null;
quotaSummaryCache.accountName = currentAccountName;
officialQuotaInfo = await getOfficialQuotaSummary(true);
} else {
quotaSummaryCache.accountName = currentAccountName;
}
} else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) {
quotaSummaryCache.accountName = currentAccountName;
}
const officialQuota = officialQuotaInfo?.data || null;
const clientConfigs = userStatus?.cascadeModelConfigData?.clientModelConfigs || [];
@@ -439,7 +416,7 @@ export async function buildTelemetryPayloadInternal(
const { conversations, activeConvSummary, activeCascadeId } =
await enumerateAndSyncConversations({
summariesObj: allTrajRes?.trajectorySummaries || {},
currentAccountName,
currentAccountName: accountScope,
requestedConvId,
forceRefresh: forceQuotaRefresh,
});
@@ -734,7 +711,7 @@ export async function buildTelemetryPayloadInternal(
} = aggregateMultiWindowUsage({
filterOpts,
cycleAnchors,
currentAccountName,
currentAccountName: accountScope,
activeCascadeId,
activeFamilyCascadeIds,
resolveStepModel,
@@ -1081,6 +1058,8 @@ export async function buildTelemetryPayloadInternal(
}),
cloudStatus: getCloudStatus(),
account: {
status: accountStatus,
email: userStatus?.email || '',
name: userStatus?.name || '',
tierName: rawTierName || 'Google AI',
planName: resolvedPlanName,
+6 -8
View File
@@ -187,7 +187,7 @@ function createUsageBucket() {
*
* @param {ReturnType<typeof createUsageBucket>} bucket
* @param {object} st 步骤对象
* @param {ReturnType<ReturnType<typeof createStepModelResolver>>} mInfo 模型信息
* @param {ReturnType<StepModelResolver>} mInfo 模型信息
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
* @param {string} cascadeId 会话标识
*/
@@ -389,7 +389,7 @@ export function buildScopedModelBreakdown(steps, resolveStepModel) {
* @param {{
* filterOpts?: { range?: string, startMs?: number, endMs?: number },
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
* currentAccountName?: string,
* currentAccountName?: string|null,
* activeCascadeId?: string|null,
* activeFamilyCascadeIds?: Set<string>|null,
* resolveStepModel: StepModelResolver
@@ -502,9 +502,8 @@ export function aggregateMultiWindowUsage({
const ownerAccount = ext.accountName || knownLive?.accountName || '';
if (
ownerAccount &&
currentAccountName &&
ownerAccount !== currentAccountName &&
!familySet.has(extCidLower)
currentAccountName !== '' &&
ownerAccount !== currentAccountName
) {
continue;
}
@@ -519,9 +518,8 @@ export function aggregateMultiWindowUsage({
for (const [cidLower, entry] of allLiveByLower.entries()) {
if (
entry?.accountName &&
currentAccountName &&
entry.accountName !== currentAccountName &&
!familySet.has(cidLower)
currentAccountName !== '' &&
entry.accountName !== currentAccountName
) {
continue;
}
+2
View File
@@ -29,6 +29,8 @@ const ALLOWED_BRIDGE_PATHS = new Set([
'/api/telemetry',
'/api/settings',
'/api/settings/reset',
'/api/accounts',
'/api/accounts/update',
'/api/context-window',
'/api/cloud-sync',
'/api/plugin-update',
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1794673025095">
<link rel="stylesheet" href="/styles.css?v=1794722545161">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1794673025095"></script>
<script src="/app.js?v=1794722545161"></script>
</body>
</html>
+19
View File
@@ -14,6 +14,7 @@
import { Response, SidecarApp } from 'sidecar_sdk';
import {
bootWindowBridgeRuntime,
executeAccountCredentialAction,
executeCloudSyncAction,
executeModelContextWindowAction,
executePluginUpdateAction,
@@ -101,6 +102,24 @@ app.api('/api/settings', (data, req) => {
return out.updated;
});
async function serveAccountCredentials(data, req) {
if (!isLocalHostRequest(req)) {
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
status: 403,
contentType: 'application/json',
});
}
const out = await executeAccountCredentialAction(data);
return new Response(out.body, {
status: out.status,
contentType: out.contentType,
headers: out.headers,
});
}
app.api('/api/accounts', (_data, req) => serveAccountCredentials(undefined, req), 'GET');
app.api('/api/accounts/update', serveAccountCredentials, 'POST');
app.api('/api/context-window', async (data, req) => {
if (!isLocalHostRequest(req)) {
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "usage-monitor-panel",
"version": "1.4.4",
"version": "1.5.0",
"private": true,
"type": "module",
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
+1
View File
@@ -484,6 +484,7 @@ export function buildBundle() {
'src/components/settings/ThemeColorPicker.js',
'src/views/settings/SettingsGeneralTab.js',
'src/views/settings/SettingsStructureTab.js',
'src/views/settings/SettingsAccountTab.js',
'src/views/settings/SettingsOtherTab.js',
'src/components/layout/TopSessionHeader.js',
'src/views/LiveOverviewView.js',
+5 -5
View File
@@ -57,7 +57,7 @@ export function deliverCdpBridgeResponses(responses) {
return delivered;
}
function callViaCdpBridge(bridge, path, { method, body, signal }) {
function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs }) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
@@ -79,7 +79,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
bridge.rpcPending.delete(reqId);
cleanupQueueItem();
reject(new Error('CDP bridge timeout'));
}, 8000);
}, cdpTimeoutMs);
const onAbort = () => {
clearTimeout(timeoutId);
@@ -118,7 +118,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal }) {
});
}
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 8000 } = {}) {
const upperMethod = method.toUpperCase();
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
@@ -155,7 +155,7 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
if (bridge) {
headers['X-Usage-Monitor-Token'] = bridge.token;
if (bridge.transportMode === 'cdp') {
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
}
@@ -173,7 +173,7 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
}
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
bridge.transportMode = 'cdp';
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
}
if (signal?.aborted) {
const abortErr = new Error('Request aborted');
+47
View File
@@ -287,7 +287,54 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
// Preferences (3-Tab Modular Settings)
'settings.subTab.general': 'General',
'settings.subTab.structure': 'Structure',
'settings.subTab.account': 'Account',
'settings.subTab.other': 'Other',
'settings.account.current': 'Current account',
'settings.account.signedOut': 'Signed out',
'settings.account.unknown': 'Account status unavailable',
'settings.account.email': 'Account email',
'settings.account.credential': 'OAuth credential',
'settings.account.importHint': 'Paste an Antigravity refresh token or OAuth JSON containing a refresh_token. The account email is verified and the credential is encrypted on this device.',
'settings.account.save': 'Import credential',
'settings.account.capture': 'Save current credential',
'settings.account.reload': 'Refresh list',
'settings.account.switch': 'Switch',
'settings.account.remove': 'Remove',
'settings.account.active': 'In use',
'settings.account.written': 'Credential written',
'settings.account.pending': 'The credential for {email} was written. If Antigravity stays on the previous account, reopen it.',
'settings.account.savedCredentials': 'Saved credentials',
'settings.account.empty': 'No saved credentials.',
'settings.account.loading': 'Loading saved credentials…',
'settings.account.saved': 'Credential saved.',
'settings.account.removed': 'Saved credential removed.',
'settings.account.switched': 'Account switched. Refreshing the current quota.',
'settings.account.switching': 'Replacing the credential and confirming the active account…',
'settings.account.verifying': 'Verifying the credential owner…',
'settings.account.loadQuota': 'Check quota',
'settings.account.loadingQuota': 'Checking quota for this credential…',
'settings.account.emptyCredentialQuota': 'There are no quota pools to display for this account.',
'settings.account.quota': 'Quota remaining by pool',
'settings.account.quota5h': '5 hours {percent}%',
'settings.account.quotaWeekly': 'Weekly {percent}%',
'settings.account.noQuota': 'Quota pools are unavailable for the current account.',
'settings.account.quotaStale': 'Quota refresh failed. Showing the last data for the current account.',
'settings.account.unsupported': 'Credential switching currently supports Antigravity shared sign-in on Windows.',
'settings.account.invalidEmail': 'Select a saved account first.',
'settings.account.invalidCredential': 'Enter a valid Antigravity OAuth credential for a personal account.',
'settings.account.credentialTooLarge': 'The credential exceeds the Windows Credential Manager limit of 2560 bytes.',
'settings.account.notFound': 'This credential was removed. Refresh the list.',
'settings.account.noCurrentCredential': 'The shared credential for the current account is unavailable.',
'settings.account.busy': 'Another window is updating credentials. Try again shortly.',
'settings.account.storeFailed': 'The credential operation failed. Try again.',
'settings.account.rollbackFailed': 'Writing and restoring the credential both failed. Check the active account in Antigravity before continuing.',
'settings.account.credentialAccessDenied': 'Windows denied access to Credential Manager. Open Antigravity in your Windows user session and try again.',
'settings.account.credentialChanged': 'This credential was updated in another window. Refresh the list and try again.',
'settings.account.credentialRejected': 'Google rejected this credential. Check that the Antigravity refresh token is still valid.',
'settings.account.identityMismatch': 'The credential belongs to a different account. Import the credential again.',
'settings.account.oauthClientUnavailable': 'The local Antigravity OAuth client configuration could not be read.',
'settings.account.oauthUnavailable': 'Google OAuth verification is unavailable. Check your network and try again.',
'settings.account.quotaUnavailable': 'Quota for this account is unavailable. Try again shortly.',
'settings.subTab.aria': 'Preferences category tabs',
'settings.saving': 'Saving…',
'settings.saved': 'Saved',
+47
View File
@@ -287,8 +287,55 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
// Preferences (3-Tab Modular Settings)
'settings.subTab.general': '常规',
'settings.subTab.structure': '结构',
'settings.subTab.account': '账号',
'settings.subTab.other': '其他',
'settings.subTab.aria': '偏好设置分类切换',
'settings.account.current': '当前账号',
'settings.account.signedOut': '未登录',
'settings.account.unknown': '暂未获取账号状态',
'settings.account.email': '账号邮箱',
'settings.account.credential': 'OAuth 凭证',
'settings.account.importHint': '粘贴 Antigravity 的刷新令牌或含 refresh_token 的 OAuth JSON。插件会验证账号邮箱,并在本机加密保存。',
'settings.account.save': '导入凭证',
'settings.account.capture': '保存当前凭证',
'settings.account.reload': '刷新列表',
'settings.account.switch': '切换',
'settings.account.remove': '移除',
'settings.account.active': '当前使用',
'settings.account.written': '凭证已写入',
'settings.account.pending': '已写入 {email} 的凭证,等待宿主更新。如果一直未更新,请重开当前 Antigravity。',
'settings.account.savedCredentials': '已保存的凭证',
'settings.account.empty': '暂无已保存的凭证。',
'settings.account.loading': '正在读取已保存的凭证…',
'settings.account.saved': '凭证已保存。',
'settings.account.removed': '已移除保存的凭证。',
'settings.account.switched': '已切换账号,正在刷新当前额度。',
'settings.account.switching': '正在替换凭证并确认宿主账号…',
'settings.account.verifying': '正在验证凭证所属账号…',
'settings.account.loadQuota': '查额度',
'settings.account.loadingQuota': '正在查询此凭证的额度…',
'settings.account.emptyCredentialQuota': '这个账号暂无可显示的额度池。',
'settings.account.quota': '额度池剩余',
'settings.account.quota5h': '5 小时 {percent}%',
'settings.account.quotaWeekly': '每周 {percent}%',
'settings.account.noQuota': '暂未获取当前账号的额度池。',
'settings.account.quotaStale': '额度刷新失败,显示的是当前账号上次获取的数据。',
'settings.account.unsupported': '凭证切换目前支持 Windows 上的 Antigravity 共享登录。',
'settings.account.invalidEmail': '请先选择一个已保存的账号。',
'settings.account.invalidCredential': '请输入有效的 Antigravity 个人账号 OAuth 凭证。',
'settings.account.credentialTooLarge': '凭证超过 Windows 凭据管理器的 2560 字节上限。',
'settings.account.notFound': '该凭证已移除,请刷新列表。',
'settings.account.noCurrentCredential': '暂时无法读取当前账号的共享凭证。',
'settings.account.busy': '另一个窗口正在操作凭证,请稍后重试。',
'settings.account.storeFailed': '凭证操作失败,请重试。',
'settings.account.rollbackFailed': '凭证写入和回滚均失败。请在 Antigravity 中确认当前账号后再继续。',
'settings.account.credentialAccessDenied': 'Windows 拒绝访问凭据管理器。请在当前 Windows 用户会话中打开 Antigravity 后重试。',
'settings.account.credentialChanged': '这份凭证已在其他窗口更新,请刷新列表后重试。',
'settings.account.credentialRejected': 'Google 未接受此凭证。请检查令牌是否属于 Antigravity 且仍然有效。',
'settings.account.identityMismatch': '凭证所属账号与宿主或保存的账号不一致。请重新导入该凭证。',
'settings.account.oauthClientUnavailable': '未能从本机 Antigravity 读取 OAuth 客户端配置。',
'settings.account.oauthUnavailable': '暂时无法完成 Google OAuth 验证,请检查网络后重试。',
'settings.account.quotaUnavailable': '暂时无法取得此账号的额度,请稍候重试。',
'settings.saving': '保存中…',
'settings.saved': '已保存',
'settings.saveFailed': '保存失败',
@@ -689,6 +689,9 @@ function isEquivalentTelemetry(prev, next) {
// 8. 比对账号订阅档位与动态多配额池
if (
prev.account?.email !== next.account?.email ||
prev.account?.name !== next.account?.name ||
prev.account?.status !== next.account?.status ||
prev.account?.tierName !== next.account?.tierName ||
prev.account?.planName !== next.account?.planName ||
prev.account?.aiCredits !== next.account?.aiCredits
@@ -866,6 +869,12 @@ export async function fetchTelemetry({ force = false } = {}) {
}
const latestSt = telemetryStore.getState();
const previousAccount = latestSt.telemetry?.account;
const nextAccount = payload?.account;
const accountChanged = previousAccount?.status === 'signedIn' &&
(nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' &&
(previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name)));
const accountPatch = accountChanged ? { selectedConversationId: '' } : {};
if (force) {
const elapsed = Date.now() - startMs;
if (elapsed < 220) {
@@ -876,6 +885,7 @@ export async function fetchTelemetry({ force = false } = {}) {
}
if (feedbackTimer) clearTimeout(feedbackTimer);
telemetryStore.setState({
...accountPatch,
telemetry: payload,
minuteTick: Math.floor(Date.now() / 30000),
syncState: 'synced',
@@ -888,6 +898,7 @@ export async function fetchTelemetry({ force = false } = {}) {
const isSame = isEquivalentTelemetry(latestSt.telemetry, payload);
const nextTelemetry = isSame ? latestSt.telemetry : payload;
telemetryStore.setState({
...accountPatch,
telemetry: nextTelemetry,
minuteTick: Math.floor(Date.now() / 30000),
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
+1 -1
View File
@@ -24,7 +24,7 @@ export function getViewTabs() {
export const uiStore = createReactiveStore({
activeView: 'overview',
stepsSubTab: 'steps', // 'steps' | 'models'
settingsSubTab: 'general', // 'general' | 'structure' | 'other'
settingsSubTab: 'general', // 'general' | 'structure' | 'account' | 'other'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
});
+58 -3
View File
@@ -1,7 +1,7 @@
/*
* 模块化偏好设置三栏样式表 (views-settings.css).
* 模块化偏好设置样式表 (views-settings.css).
* 包含:
* 1. 顶部常规 / 结构 / 其他三栏切换导航条 (.settings-view-root, .settings-subnav-bar)
* 1. 顶部偏好设置切换导航条 (.settings-view-root, .settings-subnav-bar)
* 2. 主题强调色色卡选择器 (.theme-color-picker, .theme-host-chip, .theme-swatch-btn)
* 3. 结构页手风琴折叠面板 (.collapsible-section, .collapsible-trigger, .collapsible-body)
* 4. 通用 + / - / ↑ / ↓ 自添加排序列表 (.editable-slot-list, .editable-slot-row, .slot-add-btn)
@@ -31,7 +31,8 @@
.settings-subnav-bar .segmented {
width: 100%;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: column;
grid-auto-columns: minmax(0, 1fr);
gap: 3px;
}
@@ -349,6 +350,60 @@
line-height: 1.35;
}
.settings-account-identity {
overflow-wrap: anywhere;
user-select: text;
}
.settings-account-list,
.settings-account-form,
.settings-account-form label {
display: grid;
gap: var(--space-2);
}
.settings-account-list:empty {
display: none;
}
.settings-account-entry {
display: grid;
gap: var(--space-2);
padding: var(--space-2) 0;
border-top: 1px solid var(--border-hairline);
}
.settings-account-form label {
font-size: var(--fs-sm);
color: var(--text-secondary);
}
.settings-account-form input {
min-width: 0;
padding: var(--space-2);
background: var(--surface-subtle);
border: 1px solid var(--border-hairline);
border-radius: var(--radius-sm);
font: inherit;
color: var(--text-primary);
}
.settings-account-form button {
justify-self: start;
}
.settings-account-buttons {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.settings-account-quota {
text-align: right;
color: var(--text-secondary);
font-variant-numeric: tabular-nums;
}
.settings-context-model .select-option-meta {
max-width: 62%;
text-align: right;
+35 -7
View File
@@ -1,6 +1,6 @@
/**
* @fileoverview View 4: Modular 3-Tab `SettingsView.js` ("常规" / "结构" / "其他").
* Orchestrates `SettingsGeneralTab`, `SettingsStructureTab`, and `SettingsOtherTab`
* @fileoverview View 4: Modular preferences ("常规" / "结构" / "账号" / "其他").
* Orchestrates the four preference tabs
* with top sub-navigation and a shared `CustomScrollbar` viewport.
*/
@@ -11,14 +11,18 @@ import { telemetryStore } from '../store/telemetryStore.js';
import { uiStore } from '../store/uiStore.js';
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
export const SHOW_ACCOUNT_TAB = false;
function getSettingsSubTabOptions() {
return [
{ value: 'general', label: t('settings.subTab.general') },
{ value: 'structure', label: t('settings.subTab.structure') },
...(SHOW_ACCOUNT_TAB ? [{ value: 'account', label: t('settings.subTab.account') }] : []),
{ value: 'other', label: t('settings.subTab.other') },
];
}
@@ -48,25 +52,41 @@ export const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
function applyActiveSubTab(subTab) {
let showingAccount = false;
function applyActiveSubTab(subTab, activeView) {
const target =
subTab === 'structure' || subTab === 'other' ? subTab : 'general';
subTab === 'structure' ||
subTab === 'other' ||
(SHOW_ACCOUNT_TAB && subTab === 'account')
? subTab
: 'general';
subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure');
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
patchAttr(otherTab.el, 'hidden', target !== 'other');
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
refreshScroll();
}
const contentContainer = h('div', {}, [generalTab.el, structureTab.el, otherTab.el]);
const contentContainer = h(
'div',
{},
SHOW_ACCOUNT_TAB
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
: [generalTab.el, structureTab.el, otherTab.el]
);
viewScrollbar = CustomScrollbar({
contentEl: contentContainer,
className: 'view-pane',
});
applyActiveSubTab(initialSubTab);
applyActiveSubTab(initialSubTab, uiStore.getState().activeView);
const rootEl = h('div', { className: 'settings-view-root' }, [
subNavBar,
@@ -76,6 +96,8 @@ export const SettingsView = defineComponent({
let latestSettings = null;
let latestCloudStatus = null;
let latestContextWindowModels = [];
const initialTelemetry = telemetryStore.getState().telemetry;
accountTab.refs.renderAccount(initialTelemetry?.account, initialTelemetry?.quotas);
function syncAllTabs(settings, cloudStatus) {
if (settings) {
@@ -94,11 +116,14 @@ export const SettingsView = defineComponent({
settings: st.telemetry?.settings,
cloudStatus: st.telemetry?.cloudStatus,
contextWindowModels: st.telemetry?.contextWindowModels,
account: st.telemetry?.account,
quotas: st.telemetry?.quotas,
}),
(slice) => {
latestSettings = slice.settings;
latestCloudStatus = slice.cloudStatus;
latestContextWindowModels = slice.contextWindowModels || [];
accountTab.refs.renderAccount(slice.account, slice.quotas);
if (slice.settings) {
generalTab.refs.renderSettings(slice.settings);
structureTab.refs.renderSettings(slice.settings);
@@ -117,7 +142,7 @@ export const SettingsView = defineComponent({
settingsSubTab: st.settingsSubTab,
}),
(slice) => {
applyActiveSubTab(slice.settingsSubTab);
applyActiveSubTab(slice.settingsSubTab, slice.activeView);
if (slice.activeView === 'settings') {
syncAllTabs(latestSettings, latestCloudStatus);
}
@@ -133,6 +158,7 @@ export const SettingsView = defineComponent({
});
generalTab.refs.refreshLabels();
structureTab.refs.refreshLabels();
accountTab.refs.refreshLabels();
otherTab.refs.refreshLabels();
refreshScroll();
}
@@ -145,6 +171,7 @@ export const SettingsView = defineComponent({
subNavSwitch.destroy();
generalTab.destroy();
structureTab.destroy();
accountTab.destroy();
otherTab.destroy();
viewScrollbar.destroy();
});
@@ -155,6 +182,7 @@ export const SettingsView = defineComponent({
subNavSwitch,
generalTab,
structureTab,
accountTab,
otherTab,
viewScrollbar,
// Convenience aliases for external callers / tests
@@ -0,0 +1,235 @@
/** @fileoverview Saved account credentials and the host's active account quota. */
import { defineComponent } from '../../core/component.js';
import { h, patchAttr, patchKeyedList, patchText } from '../../core/domPatch.js';
import { callSidecarApi } from '../../core/httpClient.js';
import { getEffectiveLocale, t } from '../../i18n/index.js';
import { fetchTelemetry } from '../../store/telemetryStore.js';
const key = (name) => `settings.account.${name}`;
const errors = new Set([
'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound',
'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied',
'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable',
'oauthUnavailable', 'quotaUnavailable',
]);
function renderQuotaRows(container, quotaPools) {
const locale = getEffectiveLocale();
const pools = quotaPools.filter((pool) => Number.isFinite(pool.remainingPct) || Number.isFinite(pool.weeklyRemainingPct));
patchKeyedList(container, pools, {
keyFn: (pool) => pool.poolKey || pool.poolLabel,
sigFn: (pool) => JSON.stringify([locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct]),
createRow: () => {
const label = h('span');
const remaining = h('span', { className: 'settings-account-quota' });
return { el: h('div', { className: 'settings-action-block' }, [label, remaining]), refs: { label, remaining } };
},
updateRow: ({ label, remaining }, pool) => {
patchText(label, pool.poolLabel || pool.poolKey);
const values = [];
if (Number.isFinite(pool.remainingPct)) values.push(t(key('quota5h'), { percent: pool.remainingPct }));
if (Number.isFinite(pool.weeklyRemainingPct)) values.push(t(key('quotaWeekly'), { percent: pool.weeklyRemainingPct }));
patchText(remaining, values.join(' · '));
},
});
return pools.length;
}
export const SettingsAccountTab = defineComponent({
name: 'SettingsAccountTab',
setup({ props, onCleanup }) {
let account = null;
let quotas = null;
let accounts = [];
let selectedEmail = '';
let supported = null;
let operation = '';
let status = '';
let disposed = false;
const savedQuotas = new Map();
const title = h('span', { className: 'panel-title' });
const identityLabel = h('div', { className: 'settings-action-title' });
const identity = h('div', { className: 'settings-action-desc settings-account-identity' });
const plan = h('div', { className: 'settings-action-desc' });
const quotaTitle = h('div', { className: 'settings-action-title' });
const quotaRows = h('div', { className: 'settings-account-list' });
const quotaMessage = h('div', { className: 'settings-action-desc' });
const savedTitle = h('span', { className: 'panel-title' });
const savedRows = h('div', { className: 'settings-account-list' });
const savedMessage = h('div', { className: 'settings-action-desc' });
const pending = h('div', { className: 'settings-action-desc', role: 'status' });
const feedback = h('div', { className: 'settings-action-desc', role: 'status' });
const capture = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('capture') });
const reload = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('list') });
const credentialLabel = h('span');
const importHint = h('div', { className: 'settings-action-desc' });
const credential = h('input', { type: 'password', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384 });
const save = h('button', { type: 'submit', className: 'btn-secondary' });
const form = h('form', { className: 'settings-account-form', autocomplete: 'off', onSubmit: importCredential }, [
h('label', {}, [credentialLabel, credential]),
importHint,
save,
]);
function render() {
const signedIn = account?.status === 'signedIn';
const activeEmail = signedIn ? account.email?.trim().toLowerCase() : '';
const canWrite = supported === true && !operation;
const locale = getEffectiveLocale();
patchText(title, t(key('current')));
patchText(identityLabel, t(key('email')));
patchText(identity, signedIn ? account.email || account.name :
t(key(account?.status === 'signedOut' ? 'signedOut' : 'unknown')));
patchText(plan, signedIn ? account.tierName || account.planName || '' : '');
patchAttr(plan, 'hidden', !plan.textContent);
patchText(quotaTitle, t(key('quota')));
const poolCount = renderQuotaRows(quotaRows, signedIn ? quotas?.pools || [] : []);
patchText(quotaMessage, t(key(poolCount ? 'quotaStale' : 'noQuota')));
patchAttr(quotaMessage, 'hidden', poolCount > 0 && !quotas?.meta?.isStale);
patchText(savedTitle, t(key('savedCredentials')));
patchText(capture, t(key('capture')));
patchText(reload, t(key('reload')));
patchText(save, t(key('save')));
patchText(credentialLabel, t(key('credential')));
patchText(importHint, t(key('importHint')));
patchAttr(capture, 'disabled', !canWrite || !activeEmail);
patchAttr(reload, 'disabled', Boolean(operation));
patchAttr(form, 'hidden', supported === false);
patchAttr(save, 'disabled', !canWrite);
patchAttr(credential, 'disabled', !canWrite);
patchText(savedMessage, t(key(supported === null ? 'loading' : 'empty')));
patchAttr(savedMessage, 'hidden', accounts.length > 0 || supported === false || Boolean(status));
const message = status || (operation === 'switch' ? 'switching' : operation === 'quota' ? 'loadingQuota' :
operation === 'save' || operation === 'capture' ? 'verifying' : '');
patchText(feedback, message ? t(key(message)) : '');
patchAttr(feedback, 'hidden', !message);
const waiting = selectedEmail && activeEmail !== selectedEmail;
patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : '');
patchAttr(pending, 'hidden', !waiting);
patchKeyedList(savedRows, accounts, {
keyFn: (addr) => addr,
sigFn: (addr) => JSON.stringify([locale, activeEmail, selectedEmail, canWrite, savedQuotas.get(addr)]),
createRow: (addr) => {
const state = h('div', { className: 'settings-action-desc' });
const select = h('button', {
type: 'button', className: 'btn-secondary settings-account-switch', onClick: () => request('switch', { email: addr }),
});
const remove = h('button', {
type: 'button', className: 'btn-secondary', onClick: () => request('remove', { email: addr }),
});
const loadQuota = h('button', {
type: 'button', className: 'btn-secondary settings-account-load-quota', onClick: () => request('quota', { email: addr }),
});
const rows = h('div', { className: 'settings-account-list' });
const empty = h('div', { className: 'settings-action-desc' });
return {
el: h('div', { className: 'settings-account-entry' }, [
h('div', { className: 'settings-action-block' }, [
h('div', { className: 'settings-action-info' }, [h('div', { className: 'settings-account-identity', text: addr }), state]),
h('div', { className: 'settings-account-buttons' }, [loadQuota, select, remove]),
]), rows, empty,
]),
refs: { state, select, remove, loadQuota, rows, empty },
};
},
updateRow: (row, addr) => {
const active = addr === activeEmail;
const written = addr === selectedEmail && !active;
patchText(row.state, active ? t(key('active')) : written ? t(key('written')) : '');
patchAttr(row.state, 'hidden', !active && !written);
patchText(row.select, t(key('switch')));
patchText(row.remove, t(key('remove')));
patchText(row.loadQuota, t(key('loadQuota')));
patchAttr(row.select, 'disabled', !canWrite);
patchAttr(row.remove, 'disabled', !canWrite);
patchAttr(row.loadQuota, 'disabled', !canWrite);
const cached = savedQuotas.get(addr);
const count = renderQuotaRows(row.rows, cached || []);
patchText(row.empty, t(key('emptyCredentialQuota')));
patchAttr(row.empty, 'hidden', !cached || count > 0);
},
});
props.onLayoutChange?.();
}
async function request(action, fields) {
if (operation) return;
operation = action;
status = '';
render();
try {
const result = action === 'list'
? await callSidecarApi('/api/accounts')
: await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields }, cdpTimeoutMs: 40000 });
if (disposed) return;
if (result?.error) {
if (result.error === 'unsupported') supported = false;
status = errors.has(result.error) ? result.error : 'storeFailed';
return;
}
if (action === 'quota') {
savedQuotas.set(result.email, result.pools);
return;
}
supported = result?.supported === true;
accounts = result?.accounts || [];
selectedEmail = result?.selectedEmail || '';
if (action === 'save' || action === 'capture') status = 'saved';
if (action === 'remove') {
savedQuotas.delete(fields.email);
status = 'removed';
}
if (action === 'switch') {
status = result.confirmed ? 'switched' : '';
void fetchTelemetry({ force: true }).catch(() => {});
}
} catch {
status = 'storeFailed';
} finally {
operation = '';
if (!disposed) render();
}
}
function importCredential(event) {
event.preventDefault();
if (operation) return;
const input = credential.value;
credential.value = '';
void request('save', { credential: input });
}
function renderAccount(value, quotaData) {
if (account === value && quotas === quotaData) return;
account = value;
quotas = quotaData;
render();
}
const root = h('div', { className: 'settings-tab-stack' }, [
h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [title]),
h('div', { className: 'settings-action-block' }, [
h('div', { className: 'settings-action-info' }, [identityLabel, identity, plan]),
]),
quotaTitle, quotaRows, quotaMessage, pending,
]),
h('section', { className: 'panel' }, [
h('div', { className: 'panel-header' }, [savedTitle]),
h('div', { className: 'settings-account-buttons' }, [capture, reload]),
savedRows, savedMessage, form, feedback,
]),
]);
render();
onCleanup(() => {
disposed = true;
credential.value = '';
});
return { el: root, refs: { renderAccount, refreshLabels: render, load: () => request('list') } };
},
});
+58 -3
View File
@@ -3081,9 +3081,9 @@ input {
/* --- src/styles/views-settings.css --- */
/*
* 模块化偏好设置三栏样式表 (views-settings.css).
* 模块化偏好设置样式表 (views-settings.css).
* 包含:
* 1. 顶部常规 / 结构 / 其他三栏切换导航条 (.settings-view-root, .settings-subnav-bar)
* 1. 顶部偏好设置切换导航条 (.settings-view-root, .settings-subnav-bar)
* 2. 主题强调色色卡选择器 (.theme-color-picker, .theme-host-chip, .theme-swatch-btn)
* 3. 结构页手风琴折叠面板 (.collapsible-section, .collapsible-trigger, .collapsible-body)
* 4. 通用 + / - / ↑ / ↓ 自添加排序列表 (.editable-slot-list, .editable-slot-row, .slot-add-btn)
@@ -3113,7 +3113,8 @@ input {
.settings-subnav-bar .segmented {
width: 100%;
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-auto-flow: column;
grid-auto-columns: minmax(0, 1fr);
gap: 3px;
}
@@ -3431,6 +3432,60 @@ input {
line-height: 1.35;
}
.settings-account-identity {
overflow-wrap: anywhere;
user-select: text;
}
.settings-account-list,
.settings-account-form,
.settings-account-form label {
display: grid;
gap: var(--space-2);
}
.settings-account-list:empty {
display: none;
}
.settings-account-entry {
display: grid;
gap: var(--space-2);
padding: var(--space-2) 0;
border-top: 1px solid var(--border-hairline);
}
.settings-account-form label {
font-size: var(--fs-sm);
color: var(--text-secondary);
}
.settings-account-form input {
min-width: 0;
padding: var(--space-2);
background: var(--surface-subtle);
border: 1px solid var(--border-hairline);
border-radius: var(--radius-sm);
font: inherit;
color: var(--text-primary);
}
.settings-account-form button {
justify-self: start;
}
.settings-account-buttons {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.settings-account-quota {
text-align: right;
color: var(--text-secondary);
font-variant-numeric: tabular-nums;
}
.settings-context-model .select-option-meta {
max-width: 62%;
text-align: right;
+128
View File
@@ -0,0 +1,128 @@
import assert from 'node:assert/strict';
import { mkdtemp, readFile, rmdir, unlink } from 'node:fs/promises';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { resolveGoogleCredential, retrieveCredentialQuota } from '../backend/account-oauth.mjs';
import { handleAccountCredentialAction, normalizeAccountCredential, runWindowsCredentialStore } from '../backend/account-switch.mjs';
test('accepts a shared OAuth credential or refresh token, and rejects other credential types', () => {
const refreshToken = '1//synthetic-refresh-token-for-test';
assert.deepEqual(JSON.parse(normalizeAccountCredential(refreshToken)), {
auth_method: 'consumer',
token: { access_token: '', token_type: 'Bearer', refresh_token: refreshToken, expiry: '1970-01-01T00:00:00.000Z' },
});
const saved = JSON.parse(normalizeAccountCredential(JSON.stringify({
token: { refresh_token: refreshToken, access_token: 'example-access', expiry_timestamp: 1800000000 },
})));
assert.equal(saved.token.access_token, 'example-access');
assert.equal(saved.token.expiry, '2027-01-15T08:00:00.000Z');
assert.equal(normalizeAccountCredential(JSON.stringify({ auth_method: 'enterprise', refresh_token: refreshToken })), null);
assert.equal(normalizeAccountCredential('example-api-key'), null);
});
test('import uses the verified email and switches only after checking the credential identity', async () => {
const calls = [];
const input = '1//synthetic-refresh-token-for-test';
const credential = JSON.parse(normalizeAccountCredential(input));
const saved = JSON.stringify(credential);
let verifiedEmail = 'Next@example.com';
const options = {
platform: 'win32',
resolveCredential: async (_credential, opts) => {
calls.push(opts.refresh ? 'refresh-identity' : 'verify-identity');
return { email: verifiedEmail, credential };
},
rpc: async (method) => {
calls.push(method);
return { userStatus: { email: 'Next@example.com' } };
},
store: async (request) => {
calls.push(request.action);
if (request.action === 'read') return { credential: saved };
assert.equal(request.target, 'gemini:antigravity');
assert.equal(request.email, 'next@example.com');
if (request.action === 'switch') assert.equal(request.expectedCredential, saved);
return { accounts: ['next@example.com'], selectedEmail: request.email, credential: saved };
},
};
assert.deepEqual(await handleAccountCredentialAction({ action: 'save', email: 'ignored@example.com', credential: input }, options), {
supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com',
});
assert.deepEqual(calls.splice(0), ['refresh-identity', 'save']);
const result = await handleAccountCredentialAction({ action: 'switch', email: 'NEXT@example.com' }, options);
assert.deepEqual(result, { supported: true, accounts: ['next@example.com'], selectedEmail: 'next@example.com', confirmed: true });
assert.deepEqual(calls.splice(0), ['read', 'verify-identity', 'switch', 'GetAuthStatus', 'GetUserStatus']);
verifiedEmail = 'different@example.com';
assert.deepEqual(await handleAccountCredentialAction({ action: 'switch', email: 'next@example.com' }, options), { error: 'identityMismatch' });
assert.deepEqual(calls, ['read', 'verify-identity']);
});
test('a saved credential can query its quota without replacing the active login', async () => {
const credential = normalizeAccountCredential(JSON.stringify({ refresh_token: 'test', access_token: 'saved-access' }));
const pools = [{ poolKey: 'Gemini', remainingPct: 0, weeklyRemainingPct: 29 }];
const result = await handleAccountCredentialAction({ action: 'quota', email: 'next@example.com' }, {
platform: 'win32',
store: async (request) => {
assert.equal(request.action, 'read');
return { credential };
},
resolveCredential: async (stored) => ({ email: 'next@example.com', credential: stored }),
getQuota: async (token) => {
assert.equal(token, 'saved-access');
return pools;
},
});
assert.deepEqual(result, { email: 'next@example.com', pools });
});
test('Google OAuth confirms the email and the same account token retrieves quota pools', async () => {
const endpoints = [];
const refreshToken = 'first-refresh';
const token = { access_token: 'new-access', refresh_token: 'latest-refresh', expires_in: 3600 };
const fetchFn = async (url, request) => {
endpoints.push(url);
assert.equal(request.redirect, 'error');
if (url.endsWith('/token')) {
assert.equal(request.body.get('refresh_token'), refreshToken);
return { ok: true, json: async () => token };
}
assert.equal(request.headers.Authorization, 'Bearer new-access');
if (url.endsWith('/userinfo')) return { ok: true, json: async () => ({ email: 'owner@example.com', verified_email: true }) };
if (url.endsWith(':loadCodeAssist')) return { ok: true, json: async () => ({ cloudaicompanionProject: { id: 'test-project' } }) };
assert.equal(JSON.parse(request.body).project, 'test-project');
if (url.endsWith(':fetchAvailableModels')) return { ok: true, json: async () => ({ models: {} }) };
assert.match(url, /:retrieveUserQuotaSummary$/);
return { ok: true, json: async () => ({ response: { quotaSummary: { groups: [
{ name: 'Gemini Models', buckets: [{ window: '5h', remaining_fraction: 0 }, { window: 'weekly', remainingFraction: 0.29 }] },
] } } }) };
};
const resolved = await resolveGoogleCredential({ token: { refresh_token: refreshToken } }, {
fetchFn, getClients: async () => [{ id: 'desktop-client', secret: 'test-config' }],
});
assert.equal(resolved.email, 'owner@example.com');
assert.equal(resolved.credential.token.refresh_token, token.refresh_token);
const pools = await retrieveCredentialQuota(resolved.credential.token.access_token, fetchFn);
assert.deepEqual(pools.map(({ poolKey, remainingPct, weeklyRemainingPct }) => [poolKey, remainingPct, weeklyRemainingPct]), [['Gemini', 0, 29]]);
assert.equal(endpoints.length, 5);
});
test('Windows vault atomically saves, reloads and removes encrypted entries', { skip: process.platform !== 'win32' }, async () => {
const directory = await mkdtemp(fileURLToPath(new URL('../.account-test-', import.meta.url)));
const vault = join(directory, 'test.dpapi');
const run = (action, email, credential) => runWindowsCredentialStore({ action, email, credential, vault });
try {
const credential = normalizeAccountCredential('1//synthetic-refresh-token-for-test');
assert.deepEqual(await run('list'), { accounts: [], selectedEmail: '' });
assert.deepEqual(await run('save', 'active@example.com', credential), { accounts: ['active@example.com'], selectedEmail: '' });
assert.deepEqual(await run('save', 'next@example.com', credential), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
assert.deepEqual(await run('read', 'next@example.com'), { credential });
assert.deepEqual(await runWindowsCredentialStore({ action: 'save', email: 'next@example.com', credential, expectedCredential: 'stale', vault }), { error: 'credentialChanged' });
assert.equal((await readFile(vault)).includes('synthetic-refresh-token-for-test'), false);
assert.deepEqual(await run('list'), { accounts: ['active@example.com', 'next@example.com'], selectedEmail: '' });
assert.deepEqual(await run('remove', 'next@example.com'), { accounts: ['active@example.com'], selectedEmail: '' });
} finally {
await unlink(vault).catch((err) => { if (err.code !== 'ENOENT') throw err; });
await rmdir(directory);
}
});
+4 -2
View File
@@ -15,6 +15,8 @@ const DEFAULT_BUNDLED_CATALOG = {
const BACKEND_MODULE_FILES = [
'../backend/context-windows.mjs',
'../backend/account-oauth.mjs',
'../backend/account-switch.mjs',
'../backend/settings-schema.mjs',
'../backend/config.mjs',
'../backend/ls-discovery.mjs',
@@ -144,7 +146,7 @@ export function backendHarness({
return {ok:true,json:async()=>data||{}};
}
if(method==='RetrieveUserQuotaSummary') {
const qs=state.quotaSummary;
const qs=await state.quotaSummary;
if(qs instanceof Error) throw qs;
return {ok:true,json:async()=>({response:qs})};
}
@@ -152,6 +154,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,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
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);
return {...ctx.api,state};
}
@@ -52,7 +52,7 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs
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.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan-dev/'));
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
});
@@ -94,7 +94,7 @@ test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newl
// 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.ok(fetchedUrl.startsWith('https://raw.githubusercontent.com/yuhuan-dev/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');
@@ -273,7 +273,103 @@ test('performPluginUpdate pulls fast-forward when git worktree is clean, on main
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
assert.equal(gitCalls.length, 7); // status, rev-parse, remote get-url, fetch, show, merge-base, pull
});
test('repository migration: scrubs legacy yuhuan2498281558 cache URLs/TTL and migrates git origin remote to yuhuan-dev', async () => {
let fetchedNewRepoUrl = '';
const cacheH = backendHarness({
pluginManifest: { name: 'usage-monitor', version: '1.4.4' },
remoteCatalog: {
schemaVersion: 1,
catalogVersion: '2026.11.11.4',
updatedAt: '2026-11-11T23:20:00+09:00',
latestPluginVersion: '1.4.4',
releaseUrl: 'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest',
downloadUrl: 'https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip',
archiveFallbackUrl: 'https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main',
sourceUrl: 'https://raw.githubusercontent.com/yuhuan2498281558/antigravity-usage-monitor/main/pricing-catalog.json',
fetchedAtMs: Date.now() - 60_000,
pricing: {
'gemini-4-carbon-high': { input: 2.0, cache: 0.1, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
},
},
remoteFetch: async (url) => {
fetchedNewRepoUrl = String(url);
return {
ok: true,
json: async () => ({
schemaVersion: 1,
catalogVersion: '2026.11.12.1',
updatedAt: '2026-11-12T10:00:00+09:00',
latestPluginVersion: '1.4.5',
pricing: {
'gemini-4-carbon-high': { input: 2.0, cache: 0.1, output: 10.0, short: 'carbon-4-high', family: 'Gemini' },
},
}),
};
},
});
const initialStatus = cacheH.getCloudStatus();
assert.equal(initialStatus.releaseUrl, 'https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest');
assert.equal(initialStatus.downloadUrl, 'https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip');
assert.equal(initialStatus.lastSyncedAtMs, 0, 'legacy repo cache TTL must be invalidated so new repo syncs immediately');
const synced = await cacheH.syncCloudCatalog({ force: false });
assert.equal(
fetchedNewRepoUrl,
'https://raw.githubusercontent.com/yuhuan-dev/antigravity-usage-monitor/main/pricing-catalog.json'
);
assert.equal(synced.catalogVersion, '2026.11.12.1');
assert.equal(synced.latestPluginVersion, '1.4.5');
assert.equal(
cacheH.resolveMigratedGitRemoteUrl('https://github.com/yuhuan2498281558/antigravity-usage-monitor.git'),
'https://github.com/yuhuan-dev/antigravity-usage-monitor.git'
);
assert.equal(
cacheH.resolveMigratedGitRemoteUrl('git@github.com:yuhuan2498281558/antigravity-usage-monitor.git'),
'git@github.com:yuhuan-dev/antigravity-usage-monitor.git'
);
assert.equal(
cacheH.resolveMigratedGitRemoteUrl('https://github.com/custom-fork/antigravity-usage-monitor.git'),
''
);
const gitCalls = [];
const migrateH = backendHarness({
hasGitDir: true,
pluginRootPath: '/Users/test/.gemini/config/plugins/usage-monitor',
pluginManifest: { name: 'usage-monitor', version: '1.4.3' },
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('remote') && args.includes('get-url')) {
fn(null, 'https://github.com/yuhuan2498281558/antigravity-usage-monitor.git\n', '');
return;
}
if (args.includes('show')) {
fn(null, JSON.stringify({ name: 'usage-monitor', version: '1.4.4' }), '');
return;
}
if (args.includes('pull')) {
migrateH.state.pluginManifest = { name: 'usage-monitor', version: '1.4.4' };
}
fn(null, '', '');
},
});
const updRes = await migrateH.performPluginUpdate({ isAuto: false });
assert.equal(updRes.ok, true);
assert.equal(updRes.currentVersion, '1.4.4');
const setUrlCall = gitCalls.find((args) => args.includes('remote') && args.includes('set-url'));
assert.ok(setUrlCall, 'must run git remote set-url origin before fetching');
assert.equal(setUrlCall[setUrlCall.length - 1], 'https://github.com/yuhuan-dev/antigravity-usage-monitor.git');
});
test('pluginUpdateMode supports manual (default), auto, and off with legacy autoUpdatePlugin compatibility', async () => {
+30
View File
@@ -402,6 +402,36 @@ test('switching accounts within 10s immediately invalidates quotaSummaryCache',
assert.equal(second.quotas.pools[0].weeklyRemainingPct, 8.7);
});
test('late quota results from another account cannot replace the current account cache', async () => {
const quota = (remainingFraction) => ({ groups: [{
displayName: 'Gemini Models',
buckets: [{ bucketId: 'gemini-weekly', window: 'weekly', remainingFraction }],
}] });
const pro = { name: 'Same name', userTier: { id: 'g1-pro-tier', name: 'Google AI Pro' } };
let resolvePrevious;
const h = backendHarness({
userStatus: { ...pro, email: 'a@example.com' },
quotaSummary: new Promise((resolve) => { resolvePrevious = resolve; }),
});
const previous = h.buildTelemetryPayloadInternal('none');
while (!h.state.calls.some(({ method }) => method === 'RetrieveUserQuotaSummary')) {
await new Promise((resolve) => setImmediate(resolve));
}
h.state.userStatus = { ...pro, email: 'b@example.com' };
h.state.quotaSummary = quota(0.24);
const switched = await h.buildTelemetryPayloadInternal('none');
assert.equal(switched.account.email, 'b@example.com');
assert.equal(switched.quotas.pools.find(({ poolKey }) => poolKey === 'Gemini').weeklyRemainingPct, 24);
resolvePrevious(quota(0.75));
const stale = await previous;
assert.equal(stale.quotas.meta.hasOfficialData, false);
const refreshed = await h.buildTelemetryPayloadInternal('none');
assert.equal(refreshed.account.email, 'b@example.com');
assert.equal(refreshed.quotas.pools.find(({ poolKey }) => poolKey === 'Gemini').weeklyRemainingPct, 24);
});
test('Orchestrator quota pool binding follows active phase: Carbon/Argon while planning, Gemini when offloaded to Hydrogen', async () => {
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
const ORCH_ARGON = 'MODEL_PLACEHOLDER_M681';
+30 -10
View File
@@ -317,9 +317,9 @@ test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on vers
}
const ctx = windowContexts.get(this.targetId);
const value = vm.runInContext(expr, ctx);
queueMicrotask(() =>
Promise.resolve(value).then((result) =>
this._emit('message', {
data: JSON.stringify({ id: msg.id, result: { result: { value } } }),
data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }),
})
);
}
@@ -337,11 +337,13 @@ test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on vers
res.end(
JSON.stringify([
{
id: 'win1',
type: 'page',
url: 'https://127.0.0.1:61001/c/11111111-1111-1111-1111-111111111111',
webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win1`,
},
{
id: 'win2',
type: 'page',
url: 'https://127.0.0.1:61002/c/22222222-2222-2222-2222-222222222222',
webSocketDebuggerUrl: `ws://127.0.0.1:${cdpPort}/devtools/page/win2`,
@@ -705,6 +707,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
let reloadCalled = false;
let currentBundleVer = 'ver-100';
let currentAccountEmail = 'test@example.com';
let liveSubagentPollActive = false;
const fetchedUrls = [];
const fetchedHeaders = [];
@@ -769,6 +772,8 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
};
const mockSettings = { ...defaultMockSettings };
let cacheRebuildCalls = 0;
let selectedEmail = '';
const accountRequests = [];
const mockWindow = {
innerWidth: 1440,
@@ -796,6 +801,17 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const urlStr = String(url);
fetchedUrls.push(urlStr);
fetchedHeaders.push(opts.headers || {});
if (urlStr.endsWith('/api/accounts') || urlStr.endsWith('/api/accounts/update')) {
if (opts.method === 'POST') {
const update = JSON.parse(opts.body);
accountRequests.push(update);
if (update.action === 'quota') {
return { ok: true, status: 200, json: async () => ({ email: update.email, pools: [{ poolKey: 'Gemini', remainingPct: 70 }] }) };
}
if (update.action === 'switch') selectedEmail = update.email;
}
return { ok: true, status: 200, json: async () => ({ supported: true, accounts: ['next@example.com'], selectedEmail }) };
}
if (urlStr.includes('/api/settings/reset') && String(opts.method || '').toUpperCase() === 'POST') {
for (const k of Object.keys(mockSettings)) delete mockSettings[k];
Object.assign(mockSettings, {
@@ -856,7 +872,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
{ id: 'MODEL_PLACEHOLDER_M432', label: 'Other', options: [] },
],
cloudStatus: { updateAvailable: true, currentPluginVersion: '1.4.2', latestPluginVersion: '1.5.0' },
account: { tierName: 'Google AI Ultra', planName: 'Pro', totalConversations: 5 },
account: { status: 'signedIn', email: currentAccountEmail, tierName: 'Google AI Ultra', planName: 'Pro', totalConversations: 5 },
runningConversations: [
{
cascadeId: 'bbbbbbbb-2222-3333-4444-cccccccccccc',
@@ -1195,7 +1211,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
poolKey: 'Gemini',
poolLabel: 'Gemini',
usedPct: 56,
remainingPct: 44,
remainingPct: currentAccountEmail === 'test@example.com' ? 44 : 0,
resetTime: new Date(Date.now() + 2 * 3600_000).toISOString(),
weeklyUsedPct: 74,
weeklyRemainingPct: 26,
@@ -1419,7 +1435,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath');
selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} });
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) & decoupled registries
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) with Account tab hidden
const pillTabs = popoverEl.querySelectorAll('.pill-tab');
pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
@@ -1427,10 +1443,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
const allPanes = popoverEl.querySelectorAll('.view-pane');
const settingsRoot = popoverEl.querySelector('.settings-view-root');
const subNavBtns = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn');
assert.equal(subNavBtns.length, 3, 'SettingsView renders 3 sub-tabs: 常规 / 结构 / 其他');
assert.equal(subNavBtns[0].textContent, '常规');
assert.equal(subNavBtns[1].textContent, '结构');
assert.equal(subNavBtns[2].textContent, '其他');
assert.deepEqual(subNavBtns.map((button) => button.textContent), ['常规', '结构', '其他']);
assert.match(
stylesCss,
/\.settings-subnav-bar\s+\.segmented\s*\{[^}]*grid-auto-flow:\s*column;[^}]*grid-auto-columns:\s*minmax\(0,\s*1fr\);/,
'Settings subnav uses auto-sized equal columns regardless of visible tab count'
);
const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
assert.equal(generalPane.hasAttribute('hidden'), false, 'General tab active by default');
assert.equal(structurePane.hasAttribute('hidden'), true);
@@ -1746,7 +1764,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
await new Promise((r) => setTimeout(r, 40));
assert.equal(mockSettings.stepTableColumns.length, 7);
// --- Tab 2: 其他 (modelFormat, orchestratorId, contextBaseline reserved pill, cache rebuild, reset all) ---
// --- 其他 (model format, context limits, cache rebuild, reset) ---
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
await new Promise((r) => setTimeout(r, 15));
assert.equal(otherPane.hasAttribute('hidden'), false);
@@ -2179,6 +2197,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
// Verify bundle version bump NEVER calls window.location.reload() in overlay mode
currentBundleVer = 'ver-200';
currentAccountEmail = 'next@example.com';
mockLocation.pathname = '/c/cccccccc-4444-5555-6666-dddddddddddd';
for (const fn of winListeners.get('popstate') || []) fn({});
await new Promise((r) => setTimeout(r, 40));
@@ -2369,6 +2388,7 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
// Live Antigravity IDE CDP server exposing workbench.html + workbench-jetski-agent.html + ignored sharedProcess.html
const ideContextObj = {
location: { pathname: '/out/vs/code/electron-browser/workbench/workbench.html' },
setTimeout,
document: {
querySelector(sel) {
if (sel.includes('conversation-view')) {