mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
refactor(panel): complete shared single-source rules, isolate per-module bundle scopes, and purify scoped selector
This commit is contained in:
@@ -8,6 +8,7 @@
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { BRIDGE_API_ROUTE_DEFS } from '../shared/window-bridge-protocol.mjs';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
||||
@@ -451,39 +452,38 @@ export async function executeAccountCredentialAction(data) {
|
||||
};
|
||||
}
|
||||
|
||||
const BRIDGE_ROUTE_LOOKUP = new Map(
|
||||
BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action])
|
||||
);
|
||||
|
||||
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
||||
if (pathname === '/api/telemetry' && method === 'GET') {
|
||||
return executeTelemetryAction(data, opts);
|
||||
const action = BRIDGE_ROUTE_LOOKUP.get(`${String(method || '').toUpperCase()}:${pathname}`);
|
||||
switch (action) {
|
||||
case 'telemetry':
|
||||
return executeTelemetryAction(data, opts);
|
||||
case 'settings':
|
||||
return executeSettingsAction(data);
|
||||
case 'accounts_get':
|
||||
return executeAccountCredentialAction();
|
||||
case 'accounts_update':
|
||||
return executeAccountCredentialAction(data);
|
||||
case 'context_window':
|
||||
return executeModelContextWindowAction(data);
|
||||
case 'settings_reset':
|
||||
return executeResetSettingsAction();
|
||||
case 'cache_rebuild':
|
||||
return executeRebuildCacheAction();
|
||||
case 'cloud_sync':
|
||||
return executeCloudSyncAction();
|
||||
case 'plugin_update':
|
||||
return executePluginUpdateAction();
|
||||
default:
|
||||
return {
|
||||
status: 404,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: 'Not found' }),
|
||||
};
|
||||
}
|
||||
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);
|
||||
}
|
||||
if (pathname === '/api/settings/reset' && method === 'POST') {
|
||||
return executeResetSettingsAction();
|
||||
}
|
||||
if (pathname === '/api/cache/rebuild' && method === 'POST') {
|
||||
return executeRebuildCacheAction();
|
||||
}
|
||||
if (pathname === '/api/cloud-sync' && method === 'POST') {
|
||||
return executeCloudSyncAction();
|
||||
}
|
||||
if (pathname === '/api/plugin-update' && method === 'POST') {
|
||||
return executePluginUpdateAction();
|
||||
}
|
||||
return {
|
||||
status: 404,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: 'Not found' }),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,8 +16,16 @@ import { homedir } from 'node:os';
|
||||
import { delimiter, dirname, join } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs';
|
||||
|
||||
const CLI_STATUS_THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
||||
import {
|
||||
classifyCacheTier,
|
||||
classifySpeedTier,
|
||||
classifyStepCostTier,
|
||||
classifyTtftTier,
|
||||
formatCompactCapsuleCost,
|
||||
formatCompactCapsuleTtft,
|
||||
formatCompactTokens,
|
||||
resolveCapsuleQuotaSlotPct,
|
||||
} from '../shared/telemetry-display-rules.mjs';
|
||||
|
||||
// 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符)
|
||||
const SGR_RESET = '\x1b[0m';
|
||||
@@ -388,165 +396,42 @@ export function ensureCliStatusLineConfigured({
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function cliStatusSpeedSgr(tokPerSec) {
|
||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
||||
return SGR_FG_MUTED;
|
||||
}
|
||||
const v = Number(tokPerSec);
|
||||
if (v >= 60) return SGR_FG_GOOD;
|
||||
if (v >= 35) return SGR_FG_INFO;
|
||||
if (v >= 20) return SGR_FG_WARN;
|
||||
return SGR_FG_DANGER;
|
||||
const tier = classifySpeedTier(tokPerSec);
|
||||
if (tier === 'good') return SGR_FG_GOOD;
|
||||
if (tier === 'info') return SGR_FG_INFO;
|
||||
if (tier === 'warn') return SGR_FG_WARN;
|
||||
if (tier === 'danger') return SGR_FG_DANGER;
|
||||
return SGR_FG_MUTED;
|
||||
}
|
||||
|
||||
function cliStatusCacheSgr(cacheHitPct, promptTokens = null) {
|
||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) return SGR_FG_MUTED;
|
||||
const v = Number(cacheHitPct);
|
||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) return SGR_FG_MUTED;
|
||||
if (v >= 85) return SGR_FG_GOOD;
|
||||
if (v >= 65) return SGR_FG_INFO;
|
||||
if (v >= 30) return SGR_FG_WARN;
|
||||
return SGR_FG_DANGER;
|
||||
const tier = classifyCacheTier(cacheHitPct, promptTokens);
|
||||
if (tier === 'good') return SGR_FG_GOOD;
|
||||
if (tier === 'info') return SGR_FG_INFO;
|
||||
if (tier === 'warn') return SGR_FG_WARN;
|
||||
if (tier === 'danger') return SGR_FG_DANGER;
|
||||
return SGR_FG_MUTED;
|
||||
}
|
||||
|
||||
function cliStatusCostSgr(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return SGR_FG_NORMAL;
|
||||
const v = Number(costUsd);
|
||||
if (v >= 0.3) return SGR_FG_DANGER;
|
||||
if (v >= 0.15) return SGR_FG_WARN;
|
||||
const tier = classifyStepCostTier(costUsd);
|
||||
if (tier === 'danger') return SGR_FG_DANGER;
|
||||
if (tier === 'warn') return SGR_FG_WARN;
|
||||
return SGR_FG_NORMAL;
|
||||
}
|
||||
|
||||
function cliStatusTtftSgr(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) {
|
||||
return SGR_FG_MUTED;
|
||||
}
|
||||
const v = Number(ttftSec);
|
||||
if (v >= 30) return SGR_FG_DANGER;
|
||||
if (v >= 18) return SGR_FG_WARN;
|
||||
const tier = classifyTtftTier(ttftSec);
|
||||
if (tier === 'muted') return SGR_FG_MUTED;
|
||||
if (tier === 'danger') return SGR_FG_DANGER;
|
||||
if (tier === 'warn') return SGR_FG_WARN;
|
||||
return SGR_FG_NORMAL;
|
||||
}
|
||||
|
||||
function cliFormatCompactCost(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
||||
const val = Math.max(0, Number(costUsd));
|
||||
if (val === 0) return '$0.00';
|
||||
if (val < 0.001) return '<$0.001';
|
||||
if (val < 1) return `$${val.toFixed(3)}`;
|
||||
if (val < 100) return `$${val.toFixed(2)}`;
|
||||
return `$${Math.round(val)}`;
|
||||
}
|
||||
|
||||
function cliFormatCompactTtft(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
||||
const val = Number(ttftSec);
|
||||
if (val < 1) return `${val.toFixed(2)}s`;
|
||||
if (val < 100) return `${val.toFixed(1)}s`;
|
||||
return `${Math.round(val)}s`;
|
||||
}
|
||||
|
||||
function cliFormatTokens(num) {
|
||||
const n = Number(num || 0);
|
||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
||||
return String(Math.round(n));
|
||||
}
|
||||
|
||||
function cliResolveQuotaPct(quotas, slotKey) {
|
||||
if (!quotas || typeof quotas !== 'object') return null;
|
||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
||||
const activePool = quotas.activePool || null;
|
||||
const weekly = quotas.weekly || null;
|
||||
|
||||
if (slotKey === 'quota_auto') {
|
||||
const candidates = [];
|
||||
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
|
||||
candidates.push(Number(activePool.remainingPct));
|
||||
}
|
||||
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
|
||||
candidates.push(Number(activePool.weeklyRemainingPct));
|
||||
}
|
||||
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
|
||||
candidates.push(Number(weekly.remainingPct));
|
||||
}
|
||||
if (!candidates.length && pools.length > 0) {
|
||||
for (const p of pools) {
|
||||
if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct));
|
||||
if (p && Number.isFinite(Number(p.weeklyRemainingPct))) {
|
||||
candidates.push(Number(p.weeklyRemainingPct));
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
return Math.max(0, Math.min(100, Math.round(Math.min(...candidates))));
|
||||
}
|
||||
|
||||
const isClaude = slotKey.startsWith('claude_');
|
||||
const isWeekly = slotKey.endsWith('_weekly');
|
||||
let rawPct = null;
|
||||
|
||||
if (isClaude) {
|
||||
const claudePool =
|
||||
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
||||
pools.find((p) =>
|
||||
CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||
);
|
||||
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
||||
if (cand != null && Number.isFinite(Number(cand))) {
|
||||
rawPct = Number(cand);
|
||||
} else if (
|
||||
activePool &&
|
||||
CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
||||
}
|
||||
} else {
|
||||
const stdGemini =
|
||||
pools.find((p) => p?.poolKey === 'Gemini') ||
|
||||
pools.find(
|
||||
(p) =>
|
||||
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
||||
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
||||
);
|
||||
const geminiFamilyPools = pools.filter((p) =>
|
||||
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||
);
|
||||
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
||||
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
||||
rawPct = Number(primaryCand);
|
||||
} else {
|
||||
const familyVals = geminiFamilyPools
|
||||
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
||||
.filter((v) => v != null && Number.isFinite(Number(v)))
|
||||
.map(Number);
|
||||
if (familyVals.length > 0) {
|
||||
rawPct = Math.min(...familyVals);
|
||||
} else if (
|
||||
activePool &&
|
||||
!CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(
|
||||
String(activePool.family || activePool.poolLabel || '')
|
||||
)
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
||||
}
|
||||
if (
|
||||
rawPct == null &&
|
||||
isWeekly &&
|
||||
weekly &&
|
||||
!CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(weekly.poolFamily || '')) &&
|
||||
weekly.remainingPct != null &&
|
||||
Number.isFinite(Number(weekly.remainingPct))
|
||||
) {
|
||||
rawPct = Number(weekly.remainingPct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
||||
return Math.max(0, Math.min(100, Math.round(rawPct)));
|
||||
}
|
||||
const cliFormatCompactCost = formatCompactCapsuleCost;
|
||||
const cliFormatCompactTtft = formatCompactCapsuleTtft;
|
||||
const cliFormatTokens = formatCompactTokens;
|
||||
const cliResolveQuotaPct = resolveCapsuleQuotaSlotPct;
|
||||
|
||||
/**
|
||||
* 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。
|
||||
|
||||
@@ -359,21 +359,21 @@ export function computeRuntimeCodeVersion() {
|
||||
join(HERE, 'mcp-entry.mjs'),
|
||||
join(HERE, 'cli-statusline.mjs'),
|
||||
join(HERE, 'trajectory-metrics.mjs'),
|
||||
join(HERE, 'shared', 'settings-normalization.mjs'),
|
||||
join(HERE, 'shared', 'window-bridge-protocol.mjs'),
|
||||
LOCAL_CATALOG_FILE,
|
||||
];
|
||||
const backendDir = join(HERE, 'backend');
|
||||
try {
|
||||
if (existsSync(backendDir)) {
|
||||
for (const name of readdirSync(backendDir)) {
|
||||
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
||||
candidates.push(join(backendDir, name));
|
||||
for (const subDir of ['shared', 'backend']) {
|
||||
const absDir = join(HERE, subDir);
|
||||
try {
|
||||
if (existsSync(absDir)) {
|
||||
for (const name of readdirSync(absDir)) {
|
||||
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
||||
candidates.push(join(absDir, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略目录列举异常
|
||||
}
|
||||
} catch {
|
||||
// 忽略目录列举异常
|
||||
}
|
||||
for (const file of candidates) {
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
||||
|
||||
import { CONTEXT_WINDOWS_GLOBAL_KEY } from '../shared/window-bridge-protocol.mjs';
|
||||
|
||||
export function isContextWindowModelId(value) {
|
||||
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
||||
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
||||
@@ -115,8 +117,11 @@ export function resolveContextWindowRules(models, preferences) {
|
||||
}
|
||||
|
||||
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
||||
export async function syncHostContextWindows(rules, bootId) {
|
||||
const key = '__AGUsageMonitorContextWindows';
|
||||
export async function syncHostContextWindows(
|
||||
rules,
|
||||
bootId,
|
||||
key = '__AGUsageMonitorContextWindows'
|
||||
) {
|
||||
let state = window[key];
|
||||
const appConfig = window.__APP_CONFIG__;
|
||||
const csrfToken = appConfig?.csrfToken;
|
||||
@@ -280,6 +285,6 @@ export function createContextWindowSyncExpression(preferences, bootId) {
|
||||
${getContextWindowGroups.toString()}
|
||||
${resolveContextWindowOption.toString()}
|
||||
${resolveContextWindowRules.toString()}
|
||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)});
|
||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)});
|
||||
})()`;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||
import { THIRD_PARTY_POOL_RE } from '../shared/telemetry-display-rules.mjs';
|
||||
import {
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
@@ -90,9 +91,6 @@ function classifyOfficialBucketWindow(bucket, _groupBucketCount = 1, nowMs = Dat
|
||||
return 'weekly';
|
||||
}
|
||||
|
||||
const THIRD_PARTY_POOL_RE =
|
||||
/3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i;
|
||||
|
||||
/**
|
||||
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。
|
||||
* 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。
|
||||
|
||||
@@ -1,132 +1,91 @@
|
||||
/**
|
||||
* @fileoverview 用户偏好设置 Schema、枚举常量、默认值与无状态纯函数归一化器。
|
||||
* @fileoverview 用户偏好设置完整 Schema、默认对象工厂与带上下文窗口校验的整表归一化器。
|
||||
*
|
||||
* 独立于文件系统与运行时状态,统一约束「常规 / 结构 / 其他」三栏偏好结构,
|
||||
* 并无缝兼容旧版 `settings.json`(如 3 槽固定数组中的 `'none'`、`enableWindowOverlay`、`autoUpdatePlugin` 等)。
|
||||
* 所有跨端通用枚举与单项纯函数归一化规则统一源自 `../shared/settings-normalization.mjs`。
|
||||
*/
|
||||
|
||||
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
||||
import {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_POPOVER_WIDTH,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_POPOVER_WIDTH,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_POPOVER_WIDTH,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
POPOVER_WIDTH_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
STEP_TOKEN_SEGMENT_ALIASES,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
normalizeFontScale,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
parseStepTokenComboSegments,
|
||||
} from '../shared/settings-normalization.mjs';
|
||||
|
||||
export {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_POPOVER_WIDTH,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_POPOVER_WIDTH,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_POPOVER_WIDTH,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
POPOVER_WIDTH_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
STEP_TOKEN_SEGMENT_ALIASES,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
normalizeFontScale,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
} from '../shared/settings-normalization.mjs';
|
||||
|
||||
export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']);
|
||||
|
||||
export const THEME_ACCENT_KEYS = Object.freeze([
|
||||
'host',
|
||||
'blue',
|
||||
'emerald',
|
||||
'amber',
|
||||
'violet',
|
||||
'cyan',
|
||||
'rose',
|
||||
]);
|
||||
|
||||
export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']);
|
||||
|
||||
export const OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_OVERVIEW_MODULES = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
||||
|
||||
export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'time',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
|
||||
'step',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'tokens_combo',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
||||
|
||||
export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
|
||||
context: 'context',
|
||||
ctx: 'context',
|
||||
'上下文': 'context',
|
||||
in: 'in',
|
||||
new: 'in',
|
||||
input: 'in',
|
||||
'输入': 'in',
|
||||
'新输入': 'in',
|
||||
out: 'out',
|
||||
output: 'out',
|
||||
'输出': 'out',
|
||||
'总输出': 'out',
|
||||
cache: 'cache',
|
||||
cached: 'cache',
|
||||
cache_read: 'cache',
|
||||
cacheread: 'cache',
|
||||
'缓存': 'cache',
|
||||
'缓存读': 'cache',
|
||||
think: 'think',
|
||||
thinking: 'think',
|
||||
'思考': 'think',
|
||||
reply: 'reply',
|
||||
body: 'reply',
|
||||
resp: 'reply',
|
||||
response: 'reply',
|
||||
text: 'reply',
|
||||
'正文': 'reply',
|
||||
'回复': 'reply',
|
||||
total: 'total',
|
||||
all: 'total',
|
||||
sum: 'total',
|
||||
'总计': 'total',
|
||||
'总token': 'total',
|
||||
});
|
||||
|
||||
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
|
||||
export const MIN_POPOVER_WIDTH = 440;
|
||||
export const MAX_POPOVER_WIDTH = 1080;
|
||||
export const DEFAULT_POPOVER_WIDTH = 580;
|
||||
parseStepTokenComboSegments,
|
||||
};
|
||||
|
||||
function isSchemaPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
@@ -137,222 +96,6 @@ function schemaSanitizePositiveNum(val, fallback) {
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化界面语言枚举(默认 `'zh-CN'`,保持与现有界面一致;同时支持 `'auto'` 与 `'en-US'`)。
|
||||
*
|
||||
* @param {unknown} lang
|
||||
* @returns {'auto'|'zh-CN'|'en-US'}
|
||||
*/
|
||||
export function normalizeLanguageSetting(lang) {
|
||||
const raw = String(lang ?? '').trim();
|
||||
if (!raw) return 'zh-CN';
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'auto' || lower === 'system') return 'auto';
|
||||
if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US';
|
||||
if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN';
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。
|
||||
*
|
||||
* @param {unknown} accent
|
||||
* @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'}
|
||||
*/
|
||||
export function normalizeThemeAccent(accent) {
|
||||
const clean = String(accent ?? '').trim().toLowerCase();
|
||||
return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化面板字号档位(默认 `'md'` 标准 100%)。
|
||||
*
|
||||
* @param {unknown} scale
|
||||
* @returns {'sm'|'md'|'lg'|'xl'}
|
||||
*/
|
||||
export function normalizeFontScale(scale) {
|
||||
const clean = String(scale ?? '').trim().toLowerCase();
|
||||
return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化模型名称展示模式(`'short'` 精简代号 | `'upstream_compact'` 去前缀原始 ID | `'upstream'` 完整原始 ID),
|
||||
* 兼容历史 `showUpstreamModel` 布尔开关,默认 `'short'`。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyShowUpstream]
|
||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
||||
*/
|
||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
if (legacyShowUpstream === true) return 'upstream';
|
||||
return 'short';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'compact'|'full'}
|
||||
*/
|
||||
export function normalizeOrchestratorIdMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'full' ? 'full' : 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化悬浮主面板宽度模式(`'auto'` 自适应内容宽度 | `'custom'` 指定像素宽度,默认 `'auto'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'auto'|'custom'}
|
||||
*/
|
||||
export function normalizePopoverWidthMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。
|
||||
*
|
||||
* @param {unknown} width
|
||||
* @returns {number}
|
||||
*/
|
||||
export function normalizePopoverWidth(width) {
|
||||
const num = Number(width);
|
||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH;
|
||||
return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>}
|
||||
*/
|
||||
export function parseStepTokenComboSegments(raw) {
|
||||
const str = String(raw ?? '').trim();
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
if (str) {
|
||||
for (const part of str.split(/[:/,|]+/)) {
|
||||
const key = part.trim().toLowerCase();
|
||||
if (!key) continue;
|
||||
const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key)
|
||||
? STEP_TOKEN_SEGMENT_ALIASES[key]
|
||||
: null;
|
||||
if (!mapped || seen.has(mapped)) continue;
|
||||
seen.add(mapped);
|
||||
out.push(/** @type {any} */ (mapped));
|
||||
if (out.length >= 4) break;
|
||||
}
|
||||
}
|
||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeStepTokenComboFormat(raw) {
|
||||
return parseStepTokenComboSegments(raw).join(':');
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyAutoUpdate]
|
||||
* @returns {'off'|'manual'|'auto'}
|
||||
*/
|
||||
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
||||
if (legacyAutoUpdate === true) return 'auto';
|
||||
return 'manual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeOverviewModules(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_OVERVIEW_MODULES];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||
}
|
||||
return out.length > 0 ? out : ['metrics'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeHoverModules(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_HOVER_MODULES];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化调用明细「按步查看」表格列配置与左右顺序(2~12 列,默认保留现有 7 列)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeStepTableColumns(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_STEP_TABLE_COLUMNS];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break;
|
||||
}
|
||||
if (out.length < 2) {
|
||||
for (const fallbackCol of ['step', 'model', 'tps']) {
|
||||
if (!seen.has(fallbackCol)) {
|
||||
seen.add(fallbackCol);
|
||||
out.push(fallbackCol);
|
||||
}
|
||||
if (out.length >= 2) break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeModelContextWindows(value) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(isSchemaPlainObject(value) ? value : {}).filter(
|
||||
@@ -361,19 +104,6 @@ export function normalizeModelContextWindows(value) {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。
|
||||
*
|
||||
* @param {unknown} port
|
||||
* @returns {number}
|
||||
*/
|
||||
export function normalizeStandalonePort(port) {
|
||||
const num = Number(port);
|
||||
if (!Number.isInteger(num) || num <= 0) return 0;
|
||||
if (num >= 1024 && num <= 65535) return num;
|
||||
return 0;
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
language: 'zh-CN',
|
||||
themeAccent: 'host',
|
||||
@@ -411,34 +141,12 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
*/
|
||||
export function createDefaultSettingsObject() {
|
||||
return {
|
||||
language: DEFAULT_SETTINGS_SCHEMA.language,
|
||||
themeAccent: DEFAULT_SETTINGS_SCHEMA.themeAccent,
|
||||
fontScale: DEFAULT_SETTINGS_SCHEMA.fontScale,
|
||||
weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget,
|
||||
weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget,
|
||||
weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode,
|
||||
modelDisplayMode: DEFAULT_SETTINGS_SCHEMA.modelDisplayMode,
|
||||
showUpstreamModel: DEFAULT_SETTINGS_SCHEMA.showUpstreamModel,
|
||||
orchestratorIdMode: DEFAULT_SETTINGS_SCHEMA.orchestratorIdMode,
|
||||
pluginUpdateMode: DEFAULT_SETTINGS_SCHEMA.pluginUpdateMode,
|
||||
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
|
||||
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
|
||||
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
|
||||
popoverWidthMode: DEFAULT_SETTINGS_SCHEMA.popoverWidthMode,
|
||||
popoverWidth: DEFAULT_SETTINGS_SCHEMA.popoverWidth,
|
||||
enableCliStatusLine: DEFAULT_SETTINGS_SCHEMA.enableCliStatusLine,
|
||||
standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort,
|
||||
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
|
||||
...DEFAULT_SETTINGS_SCHEMA,
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
||||
hoverModules: [...DEFAULT_HOVER_MODULES],
|
||||
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
||||
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
||||
showStepTurnRail: DEFAULT_SETTINGS_SCHEMA.showStepTurnRail,
|
||||
showStepAgentBadge: DEFAULT_SETTINGS_SCHEMA.showStepAgentBadge,
|
||||
showStepSpeedColor: DEFAULT_SETTINGS_SCHEMA.showStepSpeedColor,
|
||||
stepTokenComboFormat: DEFAULT_SETTINGS_SCHEMA.stepTokenComboFormat,
|
||||
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||
contextWindowRiskAccepted: DEFAULT_SETTINGS_SCHEMA.contextWindowRiskAccepted,
|
||||
modelContextWindows: {},
|
||||
};
|
||||
}
|
||||
@@ -500,4 +208,3 @@ export function normalizeFullSettings(rawInput) {
|
||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
*/
|
||||
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
|
||||
import {
|
||||
extractLiveActivity,
|
||||
parseIsoMs,
|
||||
@@ -268,51 +269,6 @@ function resolveStepOutputTokens(st) {
|
||||
return Number(st?.thinkingTokens || 0) + Number(st?.responseTokens || 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用最大余数法(Hamilton 方法)将各非零上下文分桶等比缩放至目标整数总和,
|
||||
* 保证 0 值通道绝不被凭空分配 Token,且缩放后各分桶之和精确等于 `targetTotal`。
|
||||
*/
|
||||
function scaleBucketsExact(buckets, keys, targetTotal) {
|
||||
const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0)));
|
||||
const out = {};
|
||||
let currentSum = 0;
|
||||
for (const k of keys) {
|
||||
const val = Math.max(0, Number(buckets[k] || 0));
|
||||
out[k] = val;
|
||||
currentSum += val;
|
||||
}
|
||||
if (safeTarget === 0 || currentSum <= 0) {
|
||||
for (const k of keys) out[k] = 0;
|
||||
return out;
|
||||
}
|
||||
if (currentSum === safeTarget) {
|
||||
for (const k of keys) out[k] = Math.round(out[k]);
|
||||
return out;
|
||||
}
|
||||
const remainders = [];
|
||||
let assigned = 0;
|
||||
for (const k of keys) {
|
||||
const rawVal = out[k];
|
||||
if (rawVal <= 0) {
|
||||
out[k] = 0;
|
||||
continue;
|
||||
}
|
||||
const exact = (rawVal * safeTarget) / currentSum;
|
||||
const floored = Math.floor(exact);
|
||||
out[k] = floored;
|
||||
assigned += floored;
|
||||
remainders.push({ key: k, rem: exact - floored, orig: rawVal });
|
||||
}
|
||||
let diff = safeTarget - assigned;
|
||||
if (diff > 0 && remainders.length > 0) {
|
||||
remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig);
|
||||
for (let i = 0; i < diff; i++) {
|
||||
out[remainders[i % remainders.length].key] += 1;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractRawBreakdownChannels(breakdown) {
|
||||
const rawMessages = Number(breakdown?.messagesTokens || 0);
|
||||
const hasGranularMsgBreakdown =
|
||||
|
||||
@@ -14,6 +14,8 @@ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from
|
||||
import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import {
|
||||
BRIDGE_API_PATHS,
|
||||
CONTEXT_WINDOWS_GLOBAL_KEY,
|
||||
WINDOW_BRIDGE_KEY,
|
||||
WINDOW_BRIDGE_ROUTE_KEY,
|
||||
WINDOW_OVERLAY_KEY,
|
||||
@@ -32,23 +34,14 @@ import { createContextWindowSyncExpression } from './context-windows.mjs';
|
||||
|
||||
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
||||
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
|
||||
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
|
||||
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
|
||||
const overlayMethods = Object.fromEntries(
|
||||
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
|
||||
);
|
||||
|
||||
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
||||
const ALLOWED_BRIDGE_PATHS = new Set([
|
||||
'/api/telemetry',
|
||||
'/api/settings',
|
||||
'/api/settings/reset',
|
||||
'/api/cache/rebuild',
|
||||
'/api/accounts',
|
||||
'/api/accounts/update',
|
||||
'/api/context-window',
|
||||
'/api/cloud-sync',
|
||||
'/api/plugin-update',
|
||||
]);
|
||||
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
|
||||
|
||||
/**
|
||||
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
||||
@@ -1581,7 +1574,7 @@ export function createWindowBridgeController(options) {
|
||||
}));
|
||||
const disposeExpr = `(() => {
|
||||
try {
|
||||
window.__AGUsageMonitorContextWindows?.dispose?.();
|
||||
${windowContextWindowsRef}?.dispose?.();
|
||||
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
|
||||
delete ${windowOverlayRef};
|
||||
delete ${windowBridgeRef};
|
||||
|
||||
Reference in New Issue
Block a user