mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
refactor(panel): complete shared single-source rules, isolate per-module bundle scopes, and purify scoped selector
This commit is contained in:
+902
-750
File diff suppressed because it is too large
Load Diff
@@ -8,6 +8,7 @@
|
|||||||
|
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { BRIDGE_API_ROUTE_DEFS } from '../shared/window-bridge-protocol.mjs';
|
||||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||||
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||||
import { clearScannerRuntimeMemos } from './local-scanner.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) {
|
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
||||||
if (pathname === '/api/telemetry' && method === 'GET') {
|
const action = BRIDGE_ROUTE_LOOKUP.get(`${String(method || '').toUpperCase()}:${pathname}`);
|
||||||
return executeTelemetryAction(data, opts);
|
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 { delimiter, dirname, join } from 'node:path';
|
||||||
import { pathToFileURL } from 'node:url';
|
import { pathToFileURL } from 'node:url';
|
||||||
import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs';
|
import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs';
|
||||||
|
import {
|
||||||
const CLI_STATUS_THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
classifyCacheTier,
|
||||||
|
classifySpeedTier,
|
||||||
|
classifyStepCostTier,
|
||||||
|
classifyTtftTier,
|
||||||
|
formatCompactCapsuleCost,
|
||||||
|
formatCompactCapsuleTtft,
|
||||||
|
formatCompactTokens,
|
||||||
|
resolveCapsuleQuotaSlotPct,
|
||||||
|
} from '../shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
// 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符)
|
// 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符)
|
||||||
const SGR_RESET = '\x1b[0m';
|
const SGR_RESET = '\x1b[0m';
|
||||||
@@ -388,165 +396,42 @@ export function ensureCliStatusLineConfigured({
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
function cliStatusSpeedSgr(tokPerSec) {
|
function cliStatusSpeedSgr(tokPerSec) {
|
||||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
const tier = classifySpeedTier(tokPerSec);
|
||||||
return SGR_FG_MUTED;
|
if (tier === 'good') return SGR_FG_GOOD;
|
||||||
}
|
if (tier === 'info') return SGR_FG_INFO;
|
||||||
const v = Number(tokPerSec);
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 60) return SGR_FG_GOOD;
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
if (v >= 35) return SGR_FG_INFO;
|
return SGR_FG_MUTED;
|
||||||
if (v >= 20) return SGR_FG_WARN;
|
|
||||||
return SGR_FG_DANGER;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliStatusCacheSgr(cacheHitPct, promptTokens = null) {
|
function cliStatusCacheSgr(cacheHitPct, promptTokens = null) {
|
||||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) return SGR_FG_MUTED;
|
const tier = classifyCacheTier(cacheHitPct, promptTokens);
|
||||||
const v = Number(cacheHitPct);
|
if (tier === 'good') return SGR_FG_GOOD;
|
||||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) return SGR_FG_MUTED;
|
if (tier === 'info') return SGR_FG_INFO;
|
||||||
if (v >= 85) return SGR_FG_GOOD;
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 65) return SGR_FG_INFO;
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
if (v >= 30) return SGR_FG_WARN;
|
return SGR_FG_MUTED;
|
||||||
return SGR_FG_DANGER;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliStatusCostSgr(costUsd) {
|
function cliStatusCostSgr(costUsd) {
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return SGR_FG_NORMAL;
|
const tier = classifyStepCostTier(costUsd);
|
||||||
const v = Number(costUsd);
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
if (v >= 0.3) return SGR_FG_DANGER;
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 0.15) return SGR_FG_WARN;
|
|
||||||
return SGR_FG_NORMAL;
|
return SGR_FG_NORMAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliStatusTtftSgr(ttftSec) {
|
function cliStatusTtftSgr(ttftSec) {
|
||||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) {
|
const tier = classifyTtftTier(ttftSec);
|
||||||
return SGR_FG_MUTED;
|
if (tier === 'muted') return SGR_FG_MUTED;
|
||||||
}
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
const v = Number(ttftSec);
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 30) return SGR_FG_DANGER;
|
|
||||||
if (v >= 18) return SGR_FG_WARN;
|
|
||||||
return SGR_FG_NORMAL;
|
return SGR_FG_NORMAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliFormatCompactCost(costUsd) {
|
const cliFormatCompactCost = formatCompactCapsuleCost;
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
const cliFormatCompactTtft = formatCompactCapsuleTtft;
|
||||||
const val = Math.max(0, Number(costUsd));
|
const cliFormatTokens = formatCompactTokens;
|
||||||
if (val === 0) return '$0.00';
|
const cliResolveQuotaPct = resolveCapsuleQuotaSlotPct;
|
||||||
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)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。
|
* 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。
|
||||||
|
|||||||
@@ -359,21 +359,21 @@ export function computeRuntimeCodeVersion() {
|
|||||||
join(HERE, 'mcp-entry.mjs'),
|
join(HERE, 'mcp-entry.mjs'),
|
||||||
join(HERE, 'cli-statusline.mjs'),
|
join(HERE, 'cli-statusline.mjs'),
|
||||||
join(HERE, 'trajectory-metrics.mjs'),
|
join(HERE, 'trajectory-metrics.mjs'),
|
||||||
join(HERE, 'shared', 'settings-normalization.mjs'),
|
|
||||||
join(HERE, 'shared', 'window-bridge-protocol.mjs'),
|
|
||||||
LOCAL_CATALOG_FILE,
|
LOCAL_CATALOG_FILE,
|
||||||
];
|
];
|
||||||
const backendDir = join(HERE, 'backend');
|
for (const subDir of ['shared', 'backend']) {
|
||||||
try {
|
const absDir = join(HERE, subDir);
|
||||||
if (existsSync(backendDir)) {
|
try {
|
||||||
for (const name of readdirSync(backendDir)) {
|
if (existsSync(absDir)) {
|
||||||
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
for (const name of readdirSync(absDir)) {
|
||||||
candidates.push(join(backendDir, name));
|
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
||||||
|
candidates.push(join(absDir, name));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略目录列举异常
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
// 忽略目录列举异常
|
|
||||||
}
|
}
|
||||||
for (const file of candidates) {
|
for (const file of candidates) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
||||||
|
|
||||||
|
import { CONTEXT_WINDOWS_GLOBAL_KEY } from '../shared/window-bridge-protocol.mjs';
|
||||||
|
|
||||||
export function isContextWindowModelId(value) {
|
export function isContextWindowModelId(value) {
|
||||||
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
||||||
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
||||||
@@ -115,8 +117,11 @@ export function resolveContextWindowRules(models, preferences) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
||||||
export async function syncHostContextWindows(rules, bootId) {
|
export async function syncHostContextWindows(
|
||||||
const key = '__AGUsageMonitorContextWindows';
|
rules,
|
||||||
|
bootId,
|
||||||
|
key = '__AGUsageMonitorContextWindows'
|
||||||
|
) {
|
||||||
let state = window[key];
|
let state = window[key];
|
||||||
const appConfig = window.__APP_CONFIG__;
|
const appConfig = window.__APP_CONFIG__;
|
||||||
const csrfToken = appConfig?.csrfToken;
|
const csrfToken = appConfig?.csrfToken;
|
||||||
@@ -280,6 +285,6 @@ export function createContextWindowSyncExpression(preferences, bootId) {
|
|||||||
${getContextWindowGroups.toString()}
|
${getContextWindowGroups.toString()}
|
||||||
${resolveContextWindowOption.toString()}
|
${resolveContextWindowOption.toString()}
|
||||||
${resolveContextWindowRules.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 { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||||
|
import { THIRD_PARTY_POOL_RE } from '../shared/telemetry-display-rules.mjs';
|
||||||
import {
|
import {
|
||||||
isArgonModelIdentifier,
|
isArgonModelIdentifier,
|
||||||
isCarbonModelIdentifier,
|
isCarbonModelIdentifier,
|
||||||
@@ -90,9 +91,6 @@ function classifyOfficialBucketWindow(bucket, _groupBucketCount = 1, nowMs = Dat
|
|||||||
return 'weekly';
|
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`)。
|
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。
|
||||||
* 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。
|
* 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。
|
||||||
|
|||||||
@@ -1,132 +1,91 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 用户偏好设置 Schema、枚举常量、默认值与无状态纯函数归一化器。
|
* @fileoverview 用户偏好设置完整 Schema、默认对象工厂与带上下文窗口校验的整表归一化器。
|
||||||
*
|
*
|
||||||
* 独立于文件系统与运行时状态,统一约束「常规 / 结构 / 其他」三栏偏好结构,
|
* 所有跨端通用枚举与单项纯函数归一化规则统一源自 `../shared/settings-normalization.mjs`。
|
||||||
* 并无缝兼容旧版 `settings.json`(如 3 槽固定数组中的 `'none'`、`enableWindowOverlay`、`autoUpdatePlugin` 等)。
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
||||||
import {
|
import {
|
||||||
|
DEFAULT_HOVER_MODULES,
|
||||||
DEFAULT_OVERVIEW_METRICS,
|
DEFAULT_OVERVIEW_METRICS,
|
||||||
|
DEFAULT_OVERVIEW_MODULES,
|
||||||
|
DEFAULT_POPOVER_WIDTH,
|
||||||
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
DEFAULT_TOPBAR_SLOTS,
|
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,
|
normalizeOverviewMetrics,
|
||||||
|
normalizeOverviewModules,
|
||||||
|
normalizePluginUpdateMode,
|
||||||
|
normalizePopoverWidth,
|
||||||
|
normalizePopoverWidthMode,
|
||||||
|
normalizeStandalonePort,
|
||||||
|
normalizeStepTableColumns,
|
||||||
|
normalizeStepTokenComboFormat,
|
||||||
|
normalizeThemeAccent,
|
||||||
normalizeTopbarCapsuleSlots,
|
normalizeTopbarCapsuleSlots,
|
||||||
normalizeWeeklyLimitMode,
|
normalizeWeeklyLimitMode,
|
||||||
normalizeWindowMountMode,
|
normalizeWindowMountMode,
|
||||||
|
parseStepTokenComboSegments,
|
||||||
} from '../shared/settings-normalization.mjs';
|
} from '../shared/settings-normalization.mjs';
|
||||||
|
|
||||||
export {
|
export {
|
||||||
|
DEFAULT_HOVER_MODULES,
|
||||||
DEFAULT_OVERVIEW_METRICS,
|
DEFAULT_OVERVIEW_METRICS,
|
||||||
|
DEFAULT_OVERVIEW_MODULES,
|
||||||
|
DEFAULT_POPOVER_WIDTH,
|
||||||
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
DEFAULT_TOPBAR_SLOTS,
|
DEFAULT_TOPBAR_SLOTS,
|
||||||
|
FONT_SCALE_KEYS,
|
||||||
|
MAX_POPOVER_WIDTH,
|
||||||
MAX_TOPBAR_SLOTS,
|
MAX_TOPBAR_SLOTS,
|
||||||
|
MIN_POPOVER_WIDTH,
|
||||||
MIN_TOPBAR_SLOTS,
|
MIN_TOPBAR_SLOTS,
|
||||||
OVERVIEW_METRIC_KEYS,
|
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,
|
TOPBAR_SLOT_KEYS,
|
||||||
|
normalizeFontScale,
|
||||||
|
normalizeHoverModules,
|
||||||
|
normalizeLanguageSetting,
|
||||||
|
normalizeModelDisplayMode,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
normalizeOverviewMetrics,
|
normalizeOverviewMetrics,
|
||||||
|
normalizeOverviewModules,
|
||||||
|
normalizePluginUpdateMode,
|
||||||
|
normalizePopoverWidth,
|
||||||
|
normalizePopoverWidthMode,
|
||||||
|
normalizeStandalonePort,
|
||||||
|
normalizeStepTableColumns,
|
||||||
|
normalizeStepTokenComboFormat,
|
||||||
|
normalizeThemeAccent,
|
||||||
normalizeTopbarCapsuleSlots,
|
normalizeTopbarCapsuleSlots,
|
||||||
normalizeWeeklyLimitMode,
|
normalizeWeeklyLimitMode,
|
||||||
normalizeWindowMountMode,
|
normalizeWindowMountMode,
|
||||||
} from '../shared/settings-normalization.mjs';
|
parseStepTokenComboSegments,
|
||||||
|
};
|
||||||
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;
|
|
||||||
|
|
||||||
function isSchemaPlainObject(v) {
|
function isSchemaPlainObject(v) {
|
||||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(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;
|
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) {
|
export function normalizeModelContextWindows(value) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(isSchemaPlainObject(value) ? value : {}).filter(
|
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({
|
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||||
language: 'zh-CN',
|
language: 'zh-CN',
|
||||||
themeAccent: 'host',
|
themeAccent: 'host',
|
||||||
@@ -411,34 +141,12 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
|||||||
*/
|
*/
|
||||||
export function createDefaultSettingsObject() {
|
export function createDefaultSettingsObject() {
|
||||||
return {
|
return {
|
||||||
language: DEFAULT_SETTINGS_SCHEMA.language,
|
...DEFAULT_SETTINGS_SCHEMA,
|
||||||
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,
|
|
||||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
||||||
hoverModules: [...DEFAULT_HOVER_MODULES],
|
hoverModules: [...DEFAULT_HOVER_MODULES],
|
||||||
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
||||||
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
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],
|
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||||
contextWindowRiskAccepted: DEFAULT_SETTINGS_SCHEMA.contextWindowRiskAccepted,
|
|
||||||
modelContextWindows: {},
|
modelContextWindows: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -500,4 +208,3 @@ export function normalizeFullSettings(rawInput) {
|
|||||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -10,6 +10,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
|
||||||
import {
|
import {
|
||||||
extractLiveActivity,
|
extractLiveActivity,
|
||||||
parseIsoMs,
|
parseIsoMs,
|
||||||
@@ -268,51 +269,6 @@ function resolveStepOutputTokens(st) {
|
|||||||
return Number(st?.thinkingTokens || 0) + Number(st?.responseTokens || 0);
|
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) {
|
function extractRawBreakdownChannels(breakdown) {
|
||||||
const rawMessages = Number(breakdown?.messagesTokens || 0);
|
const rawMessages = Number(breakdown?.messagesTokens || 0);
|
||||||
const hasGranularMsgBreakdown =
|
const hasGranularMsgBreakdown =
|
||||||
|
|||||||
@@ -14,6 +14,8 @@ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from
|
|||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import {
|
import {
|
||||||
|
BRIDGE_API_PATHS,
|
||||||
|
CONTEXT_WINDOWS_GLOBAL_KEY,
|
||||||
WINDOW_BRIDGE_KEY,
|
WINDOW_BRIDGE_KEY,
|
||||||
WINDOW_BRIDGE_ROUTE_KEY,
|
WINDOW_BRIDGE_ROUTE_KEY,
|
||||||
WINDOW_OVERLAY_KEY,
|
WINDOW_OVERLAY_KEY,
|
||||||
@@ -32,23 +34,14 @@ import { createContextWindowSyncExpression } from './context-windows.mjs';
|
|||||||
|
|
||||||
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
||||||
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_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 windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
|
||||||
const overlayMethods = Object.fromEntries(
|
const overlayMethods = Object.fromEntries(
|
||||||
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
|
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
|
||||||
);
|
);
|
||||||
|
|
||||||
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
||||||
const ALLOWED_BRIDGE_PATHS = new Set([
|
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
|
||||||
'/api/telemetry',
|
|
||||||
'/api/settings',
|
|
||||||
'/api/settings/reset',
|
|
||||||
'/api/cache/rebuild',
|
|
||||||
'/api/accounts',
|
|
||||||
'/api/accounts/update',
|
|
||||||
'/api/context-window',
|
|
||||||
'/api/cloud-sync',
|
|
||||||
'/api/plugin-update',
|
|
||||||
]);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
||||||
@@ -1581,7 +1574,7 @@ export function createWindowBridgeController(options) {
|
|||||||
}));
|
}));
|
||||||
const disposeExpr = `(() => {
|
const disposeExpr = `(() => {
|
||||||
try {
|
try {
|
||||||
window.__AGUsageMonitorContextWindows?.dispose?.();
|
${windowContextWindowsRef}?.dispose?.();
|
||||||
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
|
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
|
||||||
delete ${windowOverlayRef};
|
delete ${windowOverlayRef};
|
||||||
delete ${windowBridgeRef};
|
delete ${windowBridgeRef};
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
loadSettings,
|
loadSettings,
|
||||||
} from './backend/config.mjs';
|
} from './backend/config.mjs';
|
||||||
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
||||||
|
import { isThirdPartyPoolText } from './shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
const CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
const CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
||||||
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
||||||
@@ -386,7 +387,7 @@ function buildStdinFallbackQuotas(stdinData) {
|
|||||||
const frac = Number(bucket.remaining_fraction);
|
const frac = Number(bucket.remaining_fraction);
|
||||||
if (!Number.isFinite(frac)) continue;
|
if (!Number.isFinite(frac)) continue;
|
||||||
const remainingPct = Math.max(0, Math.min(100, Math.round(frac * 100)));
|
const remainingPct = Math.max(0, Math.min(100, Math.round(frac * 100)));
|
||||||
const isThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(key);
|
const isThirdParty = isThirdPartyPoolText(key);
|
||||||
pools.push({
|
pools.push({
|
||||||
poolKey: isThirdParty ? 'Claude & GPT' : 'Gemini',
|
poolKey: isThirdParty ? 'Claude & GPT' : 'Gemini',
|
||||||
poolLabel: key,
|
poolLabel: key,
|
||||||
@@ -396,7 +397,7 @@ function buildStdinFallbackQuotas(stdinData) {
|
|||||||
}
|
}
|
||||||
if (pools.length === 0) return null;
|
if (pools.length === 0) return null;
|
||||||
const modelStr = String(stdinData?.model?.id || stdinData?.model?.display_name || '');
|
const modelStr = String(stdinData?.model?.id || stdinData?.model?.display_name || '');
|
||||||
const activeIsThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(modelStr);
|
const activeIsThirdParty = isThirdPartyPoolText(modelStr);
|
||||||
const matchingPools = pools.filter((p) =>
|
const matchingPools = pools.filter((p) =>
|
||||||
activeIsThirdParty ? p.poolKey === 'Claude & GPT' : p.poolKey === 'Gemini'
|
activeIsThirdParty ? p.poolKey === 'Claude & GPT' : p.poolKey === 'Gemini'
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1794981269167">
|
<link rel="stylesheet" href="/styles.css?v=1794988117189">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1794981269167"></script>
|
<script src="/app.js?v=1794988117189"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+15
-10
@@ -11,6 +11,7 @@
|
|||||||
|
|
||||||
import { Worker } from 'node:worker_threads';
|
import { Worker } from 'node:worker_threads';
|
||||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||||
|
import { BRIDGE_API_ROUTE_DEFS } from './shared/window-bridge-protocol.mjs';
|
||||||
import { isLocalHostRequest, readLocalAsync } from './backend/http-helpers.mjs';
|
import { isLocalHostRequest, readLocalAsync } from './backend/http-helpers.mjs';
|
||||||
|
|
||||||
const app = new SidecarApp();
|
const app = new SidecarApp();
|
||||||
@@ -214,18 +215,22 @@ app.page(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 业务数据与控制 API 路由
|
// 业务数据与控制 API 路由(统一源自 shared/window-bridge-protocol.mjs)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
app.api('/api/telemetry', (data, req) => handleProtectedApi('/api/telemetry', 'GET', data, req), 'GET');
|
for (const route of BRIDGE_API_ROUTE_DEFS) {
|
||||||
app.api('/api/settings', (data, req) => handleProtectedApi('/api/settings', 'POST', data, req));
|
app.api(
|
||||||
app.api('/api/accounts', (_data, req) => handleProtectedApi('/api/accounts', 'GET', undefined, req), 'GET');
|
route.path,
|
||||||
app.api('/api/accounts/update', (data, req) => handleProtectedApi('/api/accounts/update', 'POST', data, req), 'POST');
|
(data, req) =>
|
||||||
app.api('/api/context-window', (data, req) => handleProtectedApi('/api/context-window', 'POST', data, req));
|
handleProtectedApi(
|
||||||
app.api('/api/settings/reset', (_data, req) => handleProtectedApi('/api/settings/reset', 'POST', undefined, req));
|
route.path,
|
||||||
app.api('/api/cache/rebuild', (_data, req) => handleProtectedApi('/api/cache/rebuild', 'POST', undefined, req));
|
route.method,
|
||||||
app.api('/api/cloud-sync', (_data, req) => handleProtectedApi('/api/cloud-sync', 'POST', undefined, req));
|
route.method === 'GET' && route.action !== 'telemetry' ? undefined : data,
|
||||||
app.api('/api/plugin-update', (_data, req) => handleProtectedApi('/api/plugin-update', 'POST', undefined, req));
|
req
|
||||||
|
),
|
||||||
|
route.method
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
app.run();
|
app.run();
|
||||||
if (isTestHarnessEnv) {
|
if (isTestHarnessEnv) {
|
||||||
|
|||||||
@@ -129,9 +129,11 @@ function scanImportDeclarationEnd(source, afterImportIdx, onImport) {
|
|||||||
return source.length;
|
return source.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
function scanExportClauseEnd(source, afterExportIdx) {
|
function scanExportClauseEnd(source, afterExportIdx, onImport, onExport) {
|
||||||
let idx = afterExportIdx;
|
let idx = afterExportIdx;
|
||||||
|
let braceBody = '';
|
||||||
if (source[idx] === '{') {
|
if (source[idx] === '{') {
|
||||||
|
const bodyStart = idx + 1;
|
||||||
let depth = 1;
|
let depth = 1;
|
||||||
idx += 1;
|
idx += 1;
|
||||||
while (idx < source.length && depth > 0) {
|
while (idx < source.length && depth > 0) {
|
||||||
@@ -155,6 +157,7 @@ function scanExportClauseEnd(source, afterExportIdx) {
|
|||||||
else if (ch === '}') depth -= 1;
|
else if (ch === '}') depth -= 1;
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
|
braceBody = source.slice(bodyStart, Math.max(bodyStart, idx - 1));
|
||||||
} else if (source[idx] === '*') {
|
} else if (source[idx] === '*') {
|
||||||
idx += 1;
|
idx += 1;
|
||||||
idx = skipSpacesAndComments(source, idx);
|
idx = skipSpacesAndComments(source, idx);
|
||||||
@@ -168,21 +171,57 @@ function scanExportClauseEnd(source, afterExportIdx) {
|
|||||||
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
||||||
const specIdx = skipSpacesAndComments(source, peekFrom + 4);
|
const specIdx = skipSpacesAndComments(source, peekFrom + 4);
|
||||||
if (source[specIdx] === "'" || source[specIdx] === '"') {
|
if (source[specIdx] === "'" || source[specIdx] === '"') {
|
||||||
idx = skipSimpleString(source, specIdx);
|
const specEnd = skipSimpleString(source, specIdx);
|
||||||
|
const specifier = source.slice(specIdx + 1, specEnd - 1);
|
||||||
|
onImport?.(specifier, braceBody ? `{ ${braceBody} } from` : '');
|
||||||
|
idx = specEnd;
|
||||||
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (braceBody && onExport) {
|
||||||
|
const cleaned = braceBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ');
|
||||||
|
for (const part of cleaned.split(',')) {
|
||||||
|
const tok = part.trim();
|
||||||
|
if (!tok) continue;
|
||||||
|
const asMatch = /^([$_\w]+)\s+as\s+([$_\w]+)$/.exec(tok);
|
||||||
|
onExport(asMatch ? asMatch[2] : tok, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return consumeTrailingStatementEnd(source, idx);
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function recordExportedDeclarationIdent(source, declKeywordIdx, onExport) {
|
||||||
|
if (!onExport) return;
|
||||||
|
let pos = declKeywordIdx;
|
||||||
|
if (source.startsWith('async', pos) && !isIdentPart(source[pos + 5])) {
|
||||||
|
pos = skipSpacesAndComments(source, pos + 5);
|
||||||
|
}
|
||||||
|
for (const kw of ['const', 'let', 'var', 'function', 'class']) {
|
||||||
|
if (source.startsWith(kw, pos) && !isIdentPart(source[pos + kw.length])) {
|
||||||
|
pos = skipSpacesAndComments(source, pos + kw.length);
|
||||||
|
if (source[pos] === '*') pos = skipSpacesAndComments(source, pos + 1);
|
||||||
|
if (isIdentStart(source[pos])) {
|
||||||
|
let end = pos + 1;
|
||||||
|
while (end < source.length && isIdentPart(source[end])) end += 1;
|
||||||
|
onExport(source.slice(pos, end), false);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lexical ES module syntax stripper that skips comments, single/double-quoted
|
* Lexical ES module syntax stripper that skips comments, single/double-quoted
|
||||||
* strings, template literals (including nested `${...}` expressions), and regex
|
* strings, template literals (including nested `${...}` expressions), and regex
|
||||||
* literals, removing only true top-level `import` / `export` syntax.
|
* literals, removing only true top-level `import` / `export` syntax.
|
||||||
*
|
*
|
||||||
* @param {string} source
|
* @param {string} source
|
||||||
|
* @param {(specifier: string, clause: string) => void} [onImport]
|
||||||
|
* @param {(name: string, isClauseExport: boolean) => void} [onExport]
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
export function stripModuleSyntax(source, onImport) {
|
export function stripModuleSyntax(source, onImport, onExport) {
|
||||||
const len = source.length;
|
const len = source.length;
|
||||||
let out = '';
|
let out = '';
|
||||||
let i = 0;
|
let i = 0;
|
||||||
@@ -366,7 +405,7 @@ export function stripModuleSyntax(source, onImport) {
|
|||||||
const afterExport = skipSpacesAndComments(source, end);
|
const afterExport = skipSpacesAndComments(source, end);
|
||||||
const nextCh = source[afterExport];
|
const nextCh = source[afterExport];
|
||||||
if (nextCh === '{' || nextCh === '*') {
|
if (nextCh === '{' || nextCh === '*') {
|
||||||
i = scanExportClauseEnd(source, afterExport);
|
i = scanExportClauseEnd(source, afterExport, onImport, onExport);
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ';';
|
prevNonWsChar = ';';
|
||||||
continue;
|
continue;
|
||||||
@@ -379,6 +418,7 @@ export function stripModuleSyntax(source, onImport) {
|
|||||||
(source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) ||
|
(source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) ||
|
||||||
(source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5]));
|
(source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5]));
|
||||||
if (isDecl) {
|
if (isDecl) {
|
||||||
|
recordExportedDeclarationIdent(source, afterDefault, onExport);
|
||||||
i = afterDefault;
|
i = afterDefault;
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
continue;
|
continue;
|
||||||
@@ -398,6 +438,7 @@ export function stripModuleSyntax(source, onImport) {
|
|||||||
(source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) ||
|
(source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) ||
|
||||||
(source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5]))
|
(source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5]))
|
||||||
) {
|
) {
|
||||||
|
recordExportedDeclarationIdent(source, afterExport, onExport);
|
||||||
i = afterExport;
|
i = afterExport;
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
continue;
|
continue;
|
||||||
@@ -427,14 +468,22 @@ export function stripModuleSyntax(source, onImport) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
function validateBundleImport(sourcePath, specifier, clause, bundledPaths) {
|
function validateBundleImport(sourcePath, specifier, clause, bundledPaths, moduleImportedNames) {
|
||||||
const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim();
|
const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim();
|
||||||
if (binding) {
|
if (binding) {
|
||||||
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
|
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
|
||||||
const identifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
|
const identifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
|
||||||
if (!named || named[1].split(',').map((item) => item.trim()).some((name) => name && !identifier.test(name))) {
|
if (!named) {
|
||||||
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
||||||
}
|
}
|
||||||
|
for (const rawItem of named[1].split(',')) {
|
||||||
|
const name = rawItem.trim();
|
||||||
|
if (!name) continue;
|
||||||
|
if (!identifier.test(name)) {
|
||||||
|
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
||||||
|
}
|
||||||
|
moduleImportedNames?.add(name);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
!(specifier.startsWith('./') || specifier.startsWith('../')) ||
|
!(specifier.startsWith('./') || specifier.startsWith('../')) ||
|
||||||
@@ -467,6 +516,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
|||||||
|
|
||||||
const jsOrder = [
|
const jsOrder = [
|
||||||
'shared/settings-normalization.mjs',
|
'shared/settings-normalization.mjs',
|
||||||
|
'shared/telemetry-display-rules.mjs',
|
||||||
'shared/window-bridge-protocol.mjs',
|
'shared/window-bridge-protocol.mjs',
|
||||||
'src/icons/svgRegistry.js',
|
'src/icons/svgRegistry.js',
|
||||||
'src/icons/SvgIcon.js',
|
'src/icons/SvgIcon.js',
|
||||||
@@ -506,7 +556,6 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
|||||||
'src/components/settings/ThemeColorPicker.js',
|
'src/components/settings/ThemeColorPicker.js',
|
||||||
'src/views/settings/SettingsGeneralTab.js',
|
'src/views/settings/SettingsGeneralTab.js',
|
||||||
'src/views/settings/SettingsStructureTab.js',
|
'src/views/settings/SettingsStructureTab.js',
|
||||||
'src/views/settings/SettingsAccountTab.js',
|
|
||||||
'src/views/settings/SettingsOtherTab.js',
|
'src/views/settings/SettingsOtherTab.js',
|
||||||
'src/components/layout/TopSessionHeader.js',
|
'src/components/layout/TopSessionHeader.js',
|
||||||
'src/views/LiveOverviewView.js',
|
'src/views/LiveOverviewView.js',
|
||||||
@@ -519,16 +568,36 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
|||||||
];
|
];
|
||||||
|
|
||||||
const bundledPaths = new Set();
|
const bundledPaths = new Set();
|
||||||
|
const outerExportedSymbols = new Set();
|
||||||
const innerModules = jsOrder
|
const innerModules = jsOrder
|
||||||
.map((rel) => {
|
.map((rel) => {
|
||||||
const path = resolve(panelDir, rel);
|
const path = resolve(panelDir, rel);
|
||||||
if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`);
|
if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`);
|
||||||
const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
|
const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
|
||||||
const stripped = stripModuleSyntax(raw, (specifier, clause) =>
|
const moduleImportedNames = new Set();
|
||||||
validateBundleImport(path, specifier, clause, bundledPaths)
|
const moduleLocalExports = new Set();
|
||||||
|
const stripped = stripModuleSyntax(
|
||||||
|
raw,
|
||||||
|
(specifier, clause) =>
|
||||||
|
validateBundleImport(path, specifier, clause, bundledPaths, moduleImportedNames),
|
||||||
|
(name, isClauseExport) => {
|
||||||
|
if (isClauseExport && moduleImportedNames.has(name) && outerExportedSymbols.has(name)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
moduleLocalExports.add(name);
|
||||||
|
}
|
||||||
);
|
);
|
||||||
bundledPaths.add(path);
|
bundledPaths.add(path);
|
||||||
return `// --- ${rel} ---\n${stripped.trim()}`;
|
const exportList = [...moduleLocalExports];
|
||||||
|
for (const sym of exportList) {
|
||||||
|
outerExportedSymbols.add(sym);
|
||||||
|
}
|
||||||
|
const body = stripped.trim();
|
||||||
|
const wrapped =
|
||||||
|
exportList.length > 0
|
||||||
|
? `const { ${exportList.join(', ')} } = (() => {\n${body}\nreturn { ${exportList.join(', ')} };\n})();`
|
||||||
|
: `(() => {\n${body}\n})();`;
|
||||||
|
return `// --- ${rel} ---\n${wrapped}`;
|
||||||
})
|
})
|
||||||
.join('\n\n');
|
.join('\n\n');
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,21 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 前后端共用的偏好设置归一化规则。
|
* @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
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 TOPBAR_SLOT_KEYS = Object.freeze([
|
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||||
'context',
|
'context',
|
||||||
'tps',
|
'tps',
|
||||||
@@ -22,6 +36,22 @@ export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
|||||||
export const MIN_TOPBAR_SLOTS = 1;
|
export const MIN_TOPBAR_SLOTS = 1;
|
||||||
export const MAX_TOPBAR_SLOTS = 5;
|
export const MAX_TOPBAR_SLOTS = 5;
|
||||||
|
|
||||||
|
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 OVERVIEW_METRIC_KEYS = Object.freeze([
|
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||||
'tps',
|
'tps',
|
||||||
'ttft',
|
'ttft',
|
||||||
@@ -41,9 +71,217 @@ export const DEFAULT_OVERVIEW_METRICS = Object.freeze([
|
|||||||
'step_cost',
|
'step_cost',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏),
|
* 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。
|
||||||
* 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。
|
*
|
||||||
|
* @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'` | `'upstream'`),兼容历史 `showUpstreamModel`。
|
||||||
|
*
|
||||||
|
* @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'`,默认 `'compact'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'compact'|'full'}
|
||||||
|
*/
|
||||||
|
export function normalizeOrchestratorIdMode(mode) {
|
||||||
|
return String(mode ?? '').trim().toLowerCase() === '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';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化面板挂载方式枚举(`'dual'` | `'composer'` | `'sidebar'`),兼容历史 `enableWindowOverlay`。
|
||||||
*
|
*
|
||||||
* @param {unknown} mode
|
* @param {unknown} mode
|
||||||
* @param {unknown} [legacyEnableOverlay]
|
* @param {unknown} [legacyEnableOverlay]
|
||||||
@@ -59,7 +297,7 @@ export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
|
* 归一化每周额度统计模式枚举(`'official'` | `'custom_tokens'` | `'custom_cost'`)。
|
||||||
*
|
*
|
||||||
* @param {unknown} mode
|
* @param {unknown} mode
|
||||||
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
||||||
@@ -120,3 +358,91 @@ export function normalizeOverviewMetrics(raw) {
|
|||||||
}
|
}
|
||||||
return out.length > 0 ? out : ['tps'];
|
return out.length > 0 ? out : ['tps'];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化实时监控视图展示的模块及上下顺序(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~14 列,默认保留现有 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;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化独立 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;
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,243 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const THIRD_PARTY_POOL_RE =
|
||||||
|
/3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断模型或配额桶文本是否归属第三方模型池(Claude & GPT / OSS / 3P)。
|
||||||
|
*
|
||||||
|
* @param {unknown} text
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isThirdPartyPoolText(text) {
|
||||||
|
return THIRD_PARTY_POOL_RE.test(String(text || ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输出速度四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifySpeedTier(tokPerSec) {
|
||||||
|
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
const v = Number(tokPerSec);
|
||||||
|
if (v >= 60) return 'good';
|
||||||
|
if (v >= 35) return 'info';
|
||||||
|
if (v >= 20) return 'warn';
|
||||||
|
return 'danger';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缓存命中率四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifyCacheTier(cacheHitPct, promptTokens = null) {
|
||||||
|
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
const v = Number(cacheHitPct);
|
||||||
|
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
if (v >= 85) return 'good';
|
||||||
|
if (v >= 65) return 'info';
|
||||||
|
if (v >= 30) return 'warn';
|
||||||
|
return 'danger';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单步费用告警色阶分类(`''|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifyStepCostTier(costUsd) {
|
||||||
|
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '';
|
||||||
|
const v = Number(costUsd);
|
||||||
|
if (v >= 0.3) return 'danger';
|
||||||
|
if (v >= 0.15) return 'warn';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 首字延迟告警色阶分类(`'muted'|''|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifyTtftTier(ttftSec) {
|
||||||
|
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
const v = Number(ttftSec);
|
||||||
|
if (v >= 30) return 'danger';
|
||||||
|
if (v >= 18) return 'warn';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompactTokens(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));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompactCapsuleCost(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)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompactCapsuleTtft(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`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} quotas
|
||||||
|
* @param {string} slotKey
|
||||||
|
* @returns {number|null}
|
||||||
|
*/
|
||||||
|
export function resolveCapsuleQuotaSlotPct(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) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || ''));
|
||||||
|
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
||||||
|
if (cand != null && Number.isFinite(Number(cand))) {
|
||||||
|
rawPct = Number(cand);
|
||||||
|
} else if (activePool && isThirdPartyPoolText(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 &&
|
||||||
|
!isThirdPartyPoolText(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 &&
|
||||||
|
!isThirdPartyPoolText(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)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用最大余数法(Hamilton 方法)将各非零分桶等比缩放至目标整数总和,
|
||||||
|
* 保证 0 值通道绝不被凭空分配余数,且缩放后各分桶之和精确等于 `targetTotal`。
|
||||||
|
*
|
||||||
|
* @param {Record<string, number>} buckets
|
||||||
|
* @param {readonly string[]} keys
|
||||||
|
* @param {number} targetTotal
|
||||||
|
* @returns {Record<string, number>}
|
||||||
|
*/
|
||||||
|
export 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 });
|
||||||
|
}
|
||||||
|
const 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;
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
|
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
|
||||||
export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
|
export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
|
||||||
export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
|
export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
|
||||||
|
export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows';
|
||||||
|
|
||||||
export const WINDOW_OVERLAY_METHODS = Object.freeze({
|
export const WINDOW_OVERLAY_METHODS = Object.freeze({
|
||||||
ensureAlive: 'ensureAlive',
|
ensureAlive: 'ensureAlive',
|
||||||
@@ -13,6 +14,20 @@ export const WINDOW_OVERLAY_METHODS = Object.freeze({
|
|||||||
dispose: 'dispose',
|
dispose: 'dispose',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
export const BRIDGE_API_ROUTE_DEFS = Object.freeze([
|
||||||
|
Object.freeze({ path: '/api/telemetry', method: 'GET', action: 'telemetry' }),
|
||||||
|
Object.freeze({ path: '/api/settings', method: 'POST', action: 'settings' }),
|
||||||
|
Object.freeze({ path: '/api/accounts', method: 'GET', action: 'accounts_get' }),
|
||||||
|
Object.freeze({ path: '/api/accounts/update', method: 'POST', action: 'accounts_update' }),
|
||||||
|
Object.freeze({ path: '/api/context-window', method: 'POST', action: 'context_window' }),
|
||||||
|
Object.freeze({ path: '/api/settings/reset', method: 'POST', action: 'settings_reset' }),
|
||||||
|
Object.freeze({ path: '/api/cache/rebuild', method: 'POST', action: 'cache_rebuild' }),
|
||||||
|
Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }),
|
||||||
|
Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path));
|
||||||
|
|
||||||
export function readInjectedWindowBridge() {
|
export function readInjectedWindowBridge() {
|
||||||
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
|
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
totalTokens: 142800,
|
totalTokens: 142800,
|
||||||
limitTokens: 256000,
|
limitTokens: 256000,
|
||||||
compactionLimitTokens: 256000,
|
compactionLimitTokens: 256000,
|
||||||
|
compactionUsedTokens: 142800,
|
||||||
usedPct: 55.8,
|
usedPct: 55.8,
|
||||||
|
messagesTokens: 119660,
|
||||||
toolResultsTokens: 86400,
|
toolResultsTokens: 86400,
|
||||||
assistantTokens: 24200,
|
assistantTokens: 24200,
|
||||||
systemToolsTokens: 11800,
|
systemToolsTokens: 11800,
|
||||||
@@ -44,7 +46,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
totalTokens: 72704,
|
totalTokens: 72704,
|
||||||
limitTokens: 256000,
|
limitTokens: 256000,
|
||||||
compactionLimitTokens: 256000,
|
compactionLimitTokens: 256000,
|
||||||
|
compactionUsedTokens: 72704,
|
||||||
usedPct: 28.4,
|
usedPct: 28.4,
|
||||||
|
messagesTokens: 63704,
|
||||||
toolResultsTokens: 51200,
|
toolResultsTokens: 51200,
|
||||||
assistantTokens: 11400,
|
assistantTokens: 11400,
|
||||||
systemToolsTokens: 5600,
|
systemToolsTokens: 5600,
|
||||||
@@ -198,6 +202,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
responseTokens: 260,
|
responseTokens: 260,
|
||||||
cacheHitPct: 0,
|
cacheHitPct: 0,
|
||||||
costUsd: 0.198,
|
costUsd: 0.198,
|
||||||
|
inCostUsd: 0.19,
|
||||||
|
cacheCostUsd: 0,
|
||||||
|
outCostUsd: 0.008,
|
||||||
createdAtMs: anchorMinMs - 215_000,
|
createdAtMs: anchorMinMs - 215_000,
|
||||||
turnIndex: 1,
|
turnIndex: 1,
|
||||||
rootTurnIndex: 1,
|
rootTurnIndex: 1,
|
||||||
@@ -241,6 +248,24 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
latestUpstreamModel: 'gemini-4-carbon-high',
|
latestUpstreamModel: 'gemini-4-carbon-high',
|
||||||
activeModelLabel: 'Gemini 4 Carbon (High)',
|
activeModelLabel: 'Gemini 4 Carbon (High)',
|
||||||
activeModelShort: 'gemini-4-carbon',
|
activeModelShort: 'gemini-4-carbon',
|
||||||
|
activeModelUpstream: 'gemini-4-carbon-high',
|
||||||
|
sessionUnpricedCalls: 0,
|
||||||
|
modelBreakdown: [
|
||||||
|
{
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
modelShort: 'gemini-4-carbon',
|
||||||
|
modelLabel: 'Gemini 4 Carbon (High)',
|
||||||
|
upstreamModel: 'gemini-4-carbon-high',
|
||||||
|
calls: 16,
|
||||||
|
inputTokens: 152400,
|
||||||
|
cacheReadTokens: 1260000,
|
||||||
|
outputTokens: 22100,
|
||||||
|
thinkingTokens: 14200,
|
||||||
|
totalTokens: 1434500,
|
||||||
|
costUsd: 1.16,
|
||||||
|
sharePct: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
context: mainContext,
|
context: mainContext,
|
||||||
recentSteps: mockSteps.filter((s) => !s.isSubagent),
|
recentSteps: mockSteps.filter((s) => !s.isSubagent),
|
||||||
};
|
};
|
||||||
@@ -277,12 +302,34 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
latestUpstreamModel: 'gemini-3.8-flash-n',
|
latestUpstreamModel: 'gemini-3.8-flash-n',
|
||||||
activeModelLabel: 'Gemini 3.8 Flash',
|
activeModelLabel: 'Gemini 3.8 Flash',
|
||||||
activeModelShort: 'gemini-3.8-flash',
|
activeModelShort: 'gemini-3.8-flash',
|
||||||
|
activeModelUpstream: 'gemini-3.8-flash-n',
|
||||||
|
sessionUnpricedCalls: 0,
|
||||||
|
modelBreakdown: [
|
||||||
|
{
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M42',
|
||||||
|
modelShort: 'gemini-3.8-flash',
|
||||||
|
modelLabel: 'Gemini 3.8 Flash',
|
||||||
|
upstreamModel: 'gemini-3.8-flash-n',
|
||||||
|
calls: 8,
|
||||||
|
inputTokens: 34000,
|
||||||
|
cacheReadTokens: 280000,
|
||||||
|
outputTokens: 6300,
|
||||||
|
thinkingTokens: 2100,
|
||||||
|
totalTokens: 320300,
|
||||||
|
costUsd: 0.12,
|
||||||
|
sharePct: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
context: subContext,
|
context: subContext,
|
||||||
recentSteps: mockSteps.filter((s) => s.isSubagent),
|
recentSteps: mockSteps.filter((s) => s.isSubagent),
|
||||||
};
|
};
|
||||||
|
|
||||||
const aggregated = {
|
const aggregated = {
|
||||||
...mainAgent,
|
...mainAgent,
|
||||||
|
agentId: 'all',
|
||||||
|
isMain: false,
|
||||||
|
badgeText: '全部',
|
||||||
|
activeAgentId: 'main',
|
||||||
stepCount: 24,
|
stepCount: 24,
|
||||||
speedSampleCount: 23,
|
speedSampleCount: 23,
|
||||||
speedSummary: { sampleCount: 23, excludedCount: 1 },
|
speedSummary: { sampleCount: 23, excludedCount: 1 },
|
||||||
@@ -290,12 +337,14 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
avgTtftSec: 1.38,
|
avgTtftSec: 1.38,
|
||||||
ttftSummary: { avgSec: 1.38, sampleCount: 23 },
|
ttftSummary: { avgSec: 1.38, sampleCount: 23 },
|
||||||
sessionCostUsd: 1.28,
|
sessionCostUsd: 1.28,
|
||||||
|
sessionUnpricedCalls: 0,
|
||||||
sessionCacheHitPct: 88.9,
|
sessionCacheHitPct: 88.9,
|
||||||
inputTokens: 186400,
|
inputTokens: 186400,
|
||||||
cacheReadTokens: 1540000,
|
cacheReadTokens: 1540000,
|
||||||
outputTokens: 28400,
|
outputTokens: 28400,
|
||||||
totalTokens: 1754800,
|
totalTokens: 1754800,
|
||||||
activeAgentBadge: '主',
|
activeAgentBadge: '主',
|
||||||
|
modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown],
|
||||||
recentSteps: mockSteps,
|
recentSteps: mockSteps,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -307,6 +356,11 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
aiCredits: 0,
|
aiCredits: 0,
|
||||||
},
|
},
|
||||||
quotas: {
|
quotas: {
|
||||||
|
meta: {
|
||||||
|
hasOfficialData: true,
|
||||||
|
isStale: false,
|
||||||
|
refreshFailed: false,
|
||||||
|
},
|
||||||
activePool: {
|
activePool: {
|
||||||
family: 'Gemini',
|
family: 'Gemini',
|
||||||
poolKey: 'Gemini',
|
poolKey: 'Gemini',
|
||||||
|
|||||||
@@ -4,6 +4,17 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||||
|
import {
|
||||||
|
normalizeModelDisplayMode,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
|
} from '../../shared/settings-normalization.mjs';
|
||||||
|
import {
|
||||||
|
classifyCacheTier,
|
||||||
|
classifySpeedTier,
|
||||||
|
classifyStepCostTier,
|
||||||
|
classifyTtftTier,
|
||||||
|
formatCompactTokens,
|
||||||
|
} from '../../shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
const EN_MONTH_SHORT = Object.freeze([
|
const EN_MONTH_SHORT = Object.freeze([
|
||||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||||
@@ -21,53 +32,24 @@ export function formatCachePct(value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getSpeedToneClass(tokPerSec) {
|
export function getSpeedToneClass(tokPerSec) {
|
||||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
return `tone-${classifySpeedTier(tokPerSec)}`;
|
||||||
return 'tone-muted';
|
|
||||||
}
|
|
||||||
const v = Number(tokPerSec);
|
|
||||||
if (v >= 60) return 'tone-good';
|
|
||||||
if (v >= 35) return 'tone-info';
|
|
||||||
if (v >= 20) return 'tone-warn';
|
|
||||||
return 'tone-danger';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCacheToneClass(cacheHitPct, promptTokens = null) {
|
export function getCacheToneClass(cacheHitPct, promptTokens = null) {
|
||||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) {
|
return `tone-${classifyCacheTier(cacheHitPct, promptTokens)}`;
|
||||||
return 'tone-muted';
|
|
||||||
}
|
|
||||||
const v = Number(cacheHitPct);
|
|
||||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) {
|
|
||||||
return 'tone-muted';
|
|
||||||
}
|
|
||||||
if (v >= 85) return 'tone-good';
|
|
||||||
if (v >= 65) return 'tone-info';
|
|
||||||
if (v >= 30) return 'tone-warn';
|
|
||||||
return 'tone-danger';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getStepCostToneClass(costUsd) {
|
export function getStepCostToneClass(costUsd) {
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '';
|
const tier = classifyStepCostTier(costUsd);
|
||||||
const v = Number(costUsd);
|
return tier ? `tone-${tier}` : '';
|
||||||
if (v >= 0.3) return 'tone-danger';
|
|
||||||
if (v >= 0.15) return 'tone-warn';
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getTtftToneClass(ttftSec) {
|
export function getTtftToneClass(ttftSec) {
|
||||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '';
|
const tier = classifyTtftTier(ttftSec);
|
||||||
const v = Number(ttftSec);
|
return tier === 'warn' || tier === 'danger' ? `tone-${tier}` : '';
|
||||||
if (v >= 30) return 'tone-danger';
|
|
||||||
if (v >= 18) return 'tone-warn';
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatTokens(num) {
|
export const formatTokens = formatCompactTokens;
|
||||||
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));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatTokensPrecise(num) {
|
export function formatTokensPrecise(num) {
|
||||||
const n = Number(num || 0);
|
const n = Number(num || 0);
|
||||||
@@ -172,23 +154,7 @@ export function formatElapsedSec(seconds) {
|
|||||||
return `${h}h ${remM}m`;
|
return `${h}h ${remM}m`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export { normalizeModelDisplayMode };
|
||||||
* 归一化普通模型显示模式(`'short'` 精简代号 | `'upstream_compact'` 去厂商前缀原始 ID | `'upstream'` 完整原始 ID)。
|
|
||||||
*
|
|
||||||
* @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';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
|
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
|
||||||
@@ -208,15 +174,7 @@ function stripCompactionMarker(rawText) {
|
|||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode;
|
||||||
* 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @returns {'compact'|'full'}
|
|
||||||
*/
|
|
||||||
export function normalizeOrchestratorIdDisplayMode(mode) {
|
|
||||||
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。
|
* 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
|
import { normalizeLanguageSetting } from '../../shared/settings-normalization.mjs';
|
||||||
import { I18N_MESSAGES_ZH_CN } from './zh-CN.js';
|
import { I18N_MESSAGES_ZH_CN } from './zh-CN.js';
|
||||||
import { I18N_MESSAGES_EN_US } from './en-US.js';
|
import { I18N_MESSAGES_EN_US } from './en-US.js';
|
||||||
|
|
||||||
@@ -13,11 +14,7 @@ export const I18N_DICTIONARIES = Object.freeze({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export function normalizeI18nLanguage(raw) {
|
export function normalizeI18nLanguage(raw) {
|
||||||
const val = String(raw ?? '').trim();
|
return normalizeLanguageSetting(raw);
|
||||||
if (val === 'auto') return 'auto';
|
|
||||||
if (/^en(?:-|$)/i.test(val)) return 'en-US';
|
|
||||||
if (/^zh(?:-|$)/i.test(val)) return 'zh-CN';
|
|
||||||
return 'zh-CN';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function detectHostSystemLocale() {
|
export function detectHostSystemLocale() {
|
||||||
|
|||||||
@@ -19,14 +19,16 @@ import {
|
|||||||
speedReasonText,
|
speedReasonText,
|
||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||||
|
|
||||||
import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-normalization.mjs';
|
import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-normalization.mjs';
|
||||||
|
import {
|
||||||
|
formatCompactCapsuleCost,
|
||||||
|
formatCompactCapsuleTtft,
|
||||||
|
resolveCapsuleQuotaSlotPct,
|
||||||
|
} from '../../shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
export { OVERVIEW_METRIC_KEYS };
|
export { OVERVIEW_METRIC_KEYS, formatCompactCapsuleCost, formatCompactCapsuleTtft };
|
||||||
export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS;
|
export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS;
|
||||||
|
|
||||||
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
|
||||||
|
|
||||||
export function getCapsuleMetricOptions() {
|
export function getCapsuleMetricOptions() {
|
||||||
return CAPSULE_METRIC_KEYS.map((key) => ({
|
return CAPSULE_METRIC_KEYS.map((key) => ({
|
||||||
value: key,
|
value: key,
|
||||||
@@ -114,98 +116,14 @@ export function resolveQuotaCapsuleSummary(quotas) {
|
|||||||
* @returns {{ roundedPct: number, shortText: string } | null}
|
* @returns {{ roundedPct: number, shortText: string } | null}
|
||||||
*/
|
*/
|
||||||
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
|
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
|
||||||
if (!quotas) return null;
|
const rounded = resolveCapsuleQuotaSlotPct(quotas, slotKey);
|
||||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
if (rounded == null) return null;
|
||||||
const activePool = quotas.activePool || null;
|
|
||||||
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) => 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 &&
|
|
||||||
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 &&
|
|
||||||
!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 &&
|
|
||||||
quotas.weekly &&
|
|
||||||
!THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) &&
|
|
||||||
quotas.weekly.remainingPct != null &&
|
|
||||||
Number.isFinite(Number(quotas.weekly.remainingPct))
|
|
||||||
) {
|
|
||||||
rawPct = Number(quotas.weekly.remainingPct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
|
||||||
const rounded = Math.max(0, Math.min(100, Math.round(rawPct)));
|
|
||||||
return {
|
return {
|
||||||
roundedPct: rounded,
|
roundedPct: rounded,
|
||||||
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatCompactCapsuleCost(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)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatCompactCapsuleTtft(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`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析顶栏/输入框精简胶囊单槽位展示结构。
|
* 解析顶栏/输入框精简胶囊单槽位展示结构。
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -20,37 +20,18 @@ import {
|
|||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
import { t } from '../i18n/index.js';
|
import { t } from '../i18n/index.js';
|
||||||
import {
|
import {
|
||||||
DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT,
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
normalizeClientStepTokenComboFormat,
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
parseClientStepTokenComboSegments,
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
} from '../store/telemetryStore.js';
|
normalizeStepTokenComboFormat,
|
||||||
|
parseStepTokenComboSegments,
|
||||||
|
} from '../../shared/settings-normalization.mjs';
|
||||||
|
|
||||||
export const STEP_COLUMN_KEYS = Object.freeze([
|
export const STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS;
|
||||||
'step',
|
export const DEFAULT_STEP_COLUMN_KEYS = DEFAULT_STEP_TABLE_COLUMNS;
|
||||||
'time',
|
const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT;
|
||||||
'model',
|
const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat;
|
||||||
'tps',
|
const parseClientStepTokenComboSegments = parseStepTokenComboSegments;
|
||||||
'ttft',
|
|
||||||
'duration',
|
|
||||||
'tokens_combo',
|
|
||||||
'tokens_io_cache',
|
|
||||||
'tokens_custom',
|
|
||||||
'input_tokens',
|
|
||||||
'cache_tokens',
|
|
||||||
'output_tokens',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([
|
|
||||||
'step',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'tokens_combo',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
function resolveStepTokenParts(st) {
|
function resolveStepTokenParts(st) {
|
||||||
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
||||||
|
|||||||
@@ -5,18 +5,14 @@
|
|||||||
* live reordering, and clean instance disposal.
|
* live reordering, and clean instance disposal.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { OVERVIEW_MODULE_KEYS } from '../../shared/settings-normalization.mjs';
|
||||||
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
|
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
|
||||||
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
|
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
|
||||||
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
|
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
|
||||||
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
|
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
|
||||||
import { t } from '../i18n/index.js';
|
import { t } from '../i18n/index.js';
|
||||||
|
|
||||||
export const OVERVIEW_WIDGET_KEYS = Object.freeze([
|
export const OVERVIEW_WIDGET_KEYS = OVERVIEW_MODULE_KEYS;
|
||||||
'metrics',
|
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
|
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
|
||||||
metrics: {
|
metrics: {
|
||||||
|
|||||||
@@ -8,14 +8,33 @@ import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../c
|
|||||||
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js';
|
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js';
|
||||||
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
|
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
|
||||||
import {
|
import {
|
||||||
|
DEFAULT_HOVER_MODULES,
|
||||||
DEFAULT_OVERVIEW_METRICS,
|
DEFAULT_OVERVIEW_METRICS,
|
||||||
|
DEFAULT_OVERVIEW_MODULES,
|
||||||
|
DEFAULT_POPOVER_WIDTH,
|
||||||
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
DEFAULT_TOPBAR_SLOTS,
|
DEFAULT_TOPBAR_SLOTS,
|
||||||
|
MAX_POPOVER_WIDTH,
|
||||||
|
MIN_POPOVER_WIDTH,
|
||||||
OVERVIEW_METRIC_KEYS,
|
OVERVIEW_METRIC_KEYS,
|
||||||
|
OVERVIEW_MODULE_KEYS,
|
||||||
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
TOPBAR_SLOT_KEYS,
|
TOPBAR_SLOT_KEYS,
|
||||||
|
normalizeHoverModules,
|
||||||
|
normalizeModelDisplayMode,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
normalizeOverviewMetrics,
|
normalizeOverviewMetrics,
|
||||||
|
normalizeOverviewModules,
|
||||||
|
normalizePluginUpdateMode,
|
||||||
|
normalizePopoverWidth,
|
||||||
|
normalizePopoverWidthMode,
|
||||||
|
normalizeStepTableColumns,
|
||||||
|
normalizeStepTokenComboFormat,
|
||||||
normalizeTopbarCapsuleSlots,
|
normalizeTopbarCapsuleSlots,
|
||||||
normalizeWeeklyLimitMode,
|
normalizeWeeklyLimitMode,
|
||||||
normalizeWindowMountMode,
|
normalizeWindowMountMode,
|
||||||
|
parseStepTokenComboSegments,
|
||||||
} from '../../shared/settings-normalization.mjs';
|
} from '../../shared/settings-normalization.mjs';
|
||||||
import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
|
import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
|
||||||
|
|
||||||
@@ -119,265 +138,34 @@ let loopIntervalMs = 2000;
|
|||||||
let loopTickFn = null;
|
let loopTickFn = null;
|
||||||
|
|
||||||
export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
|
export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
|
export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
|
||||||
|
export const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS;
|
||||||
export const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
|
export const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES;
|
||||||
'metrics',
|
export const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES;
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([
|
|
||||||
'metrics',
|
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
|
||||||
|
|
||||||
export const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS;
|
export const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS;
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS;
|
export const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS;
|
||||||
|
export const CLIENT_STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS;
|
||||||
|
export const DEFAULT_CLIENT_STEP_COLUMNS = DEFAULT_STEP_TABLE_COLUMNS;
|
||||||
|
export const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT;
|
||||||
|
export const MIN_CLIENT_POPOVER_WIDTH = MIN_POPOVER_WIDTH;
|
||||||
|
export const MAX_CLIENT_POPOVER_WIDTH = MAX_POPOVER_WIDTH;
|
||||||
|
export const DEFAULT_CLIENT_POPOVER_WIDTH = DEFAULT_POPOVER_WIDTH;
|
||||||
|
|
||||||
export const CLIENT_STEP_COLUMN_KEYS = Object.freeze([
|
export const parseClientStepTokenComboSegments = parseStepTokenComboSegments;
|
||||||
'step',
|
export const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat;
|
||||||
'time',
|
export const normalizeClientPopoverWidthMode = normalizePopoverWidthMode;
|
||||||
'model',
|
export const normalizeClientPopoverWidth = normalizePopoverWidth;
|
||||||
'tps',
|
export const normalizeClientModelDisplayMode = normalizeModelDisplayMode;
|
||||||
'ttft',
|
export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots;
|
||||||
'duration',
|
export const normalizeClientHoverModules = normalizeHoverModules;
|
||||||
'tokens_combo',
|
export const normalizeClientOverviewModules = normalizeOverviewModules;
|
||||||
'tokens_io_cache',
|
export const normalizeClientOverviewMetrics = normalizeOverviewMetrics;
|
||||||
'tokens_custom',
|
export const normalizeClientStepColumns = normalizeStepTableColumns;
|
||||||
'input_tokens',
|
export const normalizeClientUpdateMode = normalizePluginUpdateMode;
|
||||||
'cache_tokens',
|
export const normalizeClientOrchestratorIdMode = normalizeOrchestratorIdMode;
|
||||||
'output_tokens',
|
export const normalizeClientWindowMountMode = normalizeWindowMountMode;
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_STEP_COLUMNS = Object.freeze([
|
export function isEquivalentTelemetry(prev, next) {
|
||||||
'step',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'tokens_combo',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
|
||||||
|
|
||||||
const CLIENT_STEP_TOKEN_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 function parseClientStepTokenComboSegments(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(CLIENT_STEP_TOKEN_ALIASES, key)
|
|
||||||
? CLIENT_STEP_TOKEN_ALIASES[key]
|
|
||||||
: null;
|
|
||||||
if (!mapped || seen.has(mapped)) continue;
|
|
||||||
seen.add(mapped);
|
|
||||||
out.push(mapped);
|
|
||||||
if (out.length >= 4) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientStepTokenComboFormat(raw) {
|
|
||||||
return parseClientStepTokenComboSegments(raw).join(':');
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MIN_CLIENT_POPOVER_WIDTH = 440;
|
|
||||||
export const MAX_CLIENT_POPOVER_WIDTH = 1080;
|
|
||||||
export const DEFAULT_CLIENT_POPOVER_WIDTH = 580;
|
|
||||||
|
|
||||||
export function normalizeClientPopoverWidthMode(mode) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientPopoverWidth(width) {
|
|
||||||
const num = Number(width);
|
|
||||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_CLIENT_POPOVER_WIDTH;
|
|
||||||
return Math.max(MIN_CLIENT_POPOVER_WIDTH, Math.min(MAX_CLIENT_POPOVER_WIDTH, Math.round(num)));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientModelDisplayMode(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';
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeClientOrderedList(raw, { allowedKeys, defaultItems, minLen, maxLen }) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...defaultItems];
|
|
||||||
}
|
|
||||||
const allowedSet = new Set(allowedKeys);
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const key = String(item ?? '').trim();
|
|
||||||
if (!key || key === 'none' || !allowedSet.has(key) || seen.has(key)) continue;
|
|
||||||
seen.add(key);
|
|
||||||
out.push(key);
|
|
||||||
if (out.length >= maxLen) break;
|
|
||||||
}
|
|
||||||
if (out.length < minLen) {
|
|
||||||
for (const fallbackKey of [...defaultItems, ...allowedKeys]) {
|
|
||||||
if (!seen.has(fallbackKey) && allowedSet.has(fallbackKey)) {
|
|
||||||
seen.add(fallbackKey);
|
|
||||||
out.push(fallbackKey);
|
|
||||||
if (out.length >= minLen) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化前端顶栏胶囊动态槽位配置数组(支持 1..5 项不重复指标,兼容迁移旧版 `'none'` 占位)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientTopbarSlots(raw) {
|
|
||||||
return normalizeTopbarCapsuleSlots(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化鼠标悬浮速览窗展示模块列表(支持 0..4 项,`0` 项代表关闭悬浮窗)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientHoverModules(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_HOVER_MODULES,
|
|
||||||
minLen: 0,
|
|
||||||
maxLen: 4,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化实时监控视图展示模块列表(支持 1..4 项)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientOverviewModules(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_OVERVIEW_MODULES,
|
|
||||||
minLen: 1,
|
|
||||||
maxLen: 4,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化实时监控第一行指标矩阵配置(支持 1..4 项)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientOverviewMetrics(raw) {
|
|
||||||
return normalizeOverviewMetrics(raw);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化调用明细「按步查看」显示列配置(支持 2..12 列)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientStepColumns(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_STEP_COLUMN_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_STEP_COLUMNS,
|
|
||||||
minLen: 2,
|
|
||||||
maxLen: CLIENT_STEP_COLUMN_KEYS.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化前端插件更新策略(`'off'` | `'manual'` | `'auto'`),兼容旧版布尔字段。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyAutoUpdate]
|
|
||||||
* @returns {'off'|'manual'|'auto'}
|
|
||||||
*/
|
|
||||||
export function normalizeClientUpdateMode(mode, legacyAutoUpdate) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
|
||||||
if (legacyAutoUpdate === true) return 'auto';
|
|
||||||
return 'manual';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientOrchestratorIdMode(mode) {
|
|
||||||
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化前端面板挂载方式(`'dual'` | `'composer'` | `'sidebar'`),兼容旧版 `enableWindowOverlay` 布尔字段。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyEnableOverlay]
|
|
||||||
* @returns {'dual'|'composer'|'sidebar'}
|
|
||||||
*/
|
|
||||||
export function normalizeClientWindowMountMode(mode, legacyEnableOverlay) {
|
|
||||||
return normalizeWindowMountMode(mode, legacyEnableOverlay);
|
|
||||||
}
|
|
||||||
|
|
||||||
function isEquivalentTelemetry(prev, next) {
|
|
||||||
if (!prev || !next) return false;
|
if (!prev || !next) return false;
|
||||||
if (prev === next) return true;
|
if (prev === next) return true;
|
||||||
|
|
||||||
@@ -409,51 +197,29 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const normModelMode = (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';
|
|
||||||
return legacyShowUpstream === true ? 'upstream' : 'short';
|
|
||||||
};
|
|
||||||
const normPopMode = (mode) => {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
|
||||||
};
|
|
||||||
const normPopW = (w) => {
|
|
||||||
const n = Number(w);
|
|
||||||
return Number.isFinite(n) && n > 0 ? Math.max(440, Math.min(1080, Math.round(n))) : 580;
|
|
||||||
};
|
|
||||||
if (
|
if (
|
||||||
normModelMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !==
|
normalizeModelDisplayMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !==
|
||||||
normModelMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel)
|
normalizeModelDisplayMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel)
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false;
|
if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false;
|
||||||
if (normPopMode(pSet?.popoverWidthMode) !== normPopMode(nSet?.popoverWidthMode)) {
|
if (normalizePopoverWidthMode(pSet?.popoverWidthMode) !== normalizePopoverWidthMode(nSet?.popoverWidthMode)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (normPopW(pSet?.popoverWidth) !== normPopW(nSet?.popoverWidth)) {
|
if (normalizePopoverWidth(pSet?.popoverWidth) !== normalizePopoverWidth(nSet?.popoverWidth)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
String(pSet?.stepTokenComboFormat ?? 'context:in:cache').trim() !==
|
String(pSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() !==
|
||||||
String(nSet?.stepTokenComboFormat ?? 'context:in:cache').trim()
|
String(nSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim()
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const prevOrchIdMode =
|
if (
|
||||||
String(pSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
normalizeOrchestratorIdMode(pSet?.orchestratorIdMode) !==
|
||||||
? 'full'
|
normalizeOrchestratorIdMode(nSet?.orchestratorIdMode)
|
||||||
: 'compact';
|
) {
|
||||||
const nextOrchIdMode =
|
|
||||||
String(nSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
|
||||||
? 'full'
|
|
||||||
: 'compact';
|
|
||||||
if (prevOrchIdMode !== nextOrchIdMode) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false;
|
if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false;
|
||||||
@@ -1392,46 +1158,73 @@ export function formatAgentLabel(agent) {
|
|||||||
* @param {string} [ctxInspectorAgentId='auto']
|
* @param {string} [ctxInspectorAgentId='auto']
|
||||||
* @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表
|
* @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表
|
||||||
*/
|
*/
|
||||||
|
const scopedStepProjectionMemo = new WeakMap();
|
||||||
|
|
||||||
export function resolveScopedConversation(
|
export function resolveScopedConversation(
|
||||||
telemetry,
|
telemetry,
|
||||||
selectedAgentScope = 'all',
|
selectedAgentScope = 'all',
|
||||||
ctxInspectorAgentId = 'auto',
|
ctxInspectorAgentId = 'auto',
|
||||||
includeSteps = false
|
includeSteps = false
|
||||||
) {
|
) {
|
||||||
const active = telemetry?.activeConversation || {};
|
const rawActive = telemetry?.activeConversation;
|
||||||
|
const active = rawActive || {};
|
||||||
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
|
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
|
||||||
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
|
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
|
||||||
const subagents = agents.filter((a) => !a.isMain);
|
const subagents = agents.filter((a) => !a.isMain);
|
||||||
const mainAgent = agents.find((a) => a.isMain) || active;
|
let mainAgent = agents.find((a) => a.isMain) || active;
|
||||||
if (includeSteps && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) {
|
let aggregated = active.aggregated || active;
|
||||||
mainAgent.recentSteps = active.recentSteps;
|
let resolvedAgents = agents;
|
||||||
}
|
|
||||||
const aggregated = active.aggregated || active;
|
if (includeSteps) {
|
||||||
if (includeSteps && hasSubagents && !Array.isArray(aggregated.recentSteps)) {
|
let cached = rawActive && typeof rawActive === 'object' ? scopedStepProjectionMemo.get(rawActive) : null;
|
||||||
const combined = [];
|
if (!cached) {
|
||||||
for (const ag of agents) {
|
let nextMain = mainAgent;
|
||||||
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
|
let nextAgents = agents;
|
||||||
for (const step of steps) combined.push(step);
|
if (!Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) {
|
||||||
|
nextMain = { ...mainAgent, recentSteps: active.recentSteps };
|
||||||
|
if (agents.includes(mainAgent)) {
|
||||||
|
nextAgents = agents.map((ag) => (ag === mainAgent ? nextMain : ag));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let nextAgg = aggregated;
|
||||||
|
if (hasSubagents && !Array.isArray(aggregated.recentSteps)) {
|
||||||
|
const combined = [];
|
||||||
|
for (const ag of nextAgents) {
|
||||||
|
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
|
||||||
|
for (const step of steps) combined.push(step);
|
||||||
|
}
|
||||||
|
combined.sort(
|
||||||
|
(a, b) =>
|
||||||
|
(b.createdAtMs || 0) - (a.createdAtMs || 0) ||
|
||||||
|
(b.agentIndex || 0) - (a.agentIndex || 0) ||
|
||||||
|
(b.stepIndex || 0) - (a.stepIndex || 0)
|
||||||
|
);
|
||||||
|
nextAgg = { ...aggregated, recentSteps: combined };
|
||||||
|
}
|
||||||
|
cached = { mainAgent: nextMain, aggregated: nextAgg, agents: nextAgents };
|
||||||
|
if (rawActive && typeof rawActive === 'object') {
|
||||||
|
scopedStepProjectionMemo.set(rawActive, cached);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
combined.sort(
|
mainAgent = cached.mainAgent;
|
||||||
(a, b) =>
|
aggregated = cached.aggregated;
|
||||||
(b.createdAtMs || 0) - (a.createdAtMs || 0) ||
|
resolvedAgents = cached.agents;
|
||||||
(b.agentIndex || 0) - (a.agentIndex || 0) ||
|
|
||||||
(b.stepIndex || 0) - (a.stepIndex || 0)
|
|
||||||
);
|
|
||||||
aggregated.recentSteps = combined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasSubagents) {
|
if (!hasSubagents) {
|
||||||
|
const singleScoped =
|
||||||
|
includeSteps && !Array.isArray(active.recentSteps) && Array.isArray(mainAgent.recentSteps)
|
||||||
|
? { ...active, recentSteps: mainAgent.recentSteps }
|
||||||
|
: active;
|
||||||
return {
|
return {
|
||||||
hasSubagents: false,
|
hasSubagents: false,
|
||||||
effectiveScope: 'main',
|
effectiveScope: 'main',
|
||||||
effectiveCtxScope: 'main',
|
effectiveCtxScope: 'main',
|
||||||
agents,
|
agents: resolvedAgents,
|
||||||
subagents: [],
|
subagents: [],
|
||||||
mainAgent,
|
mainAgent,
|
||||||
aggregated,
|
aggregated,
|
||||||
scopedConv: active,
|
scopedConv: singleScoped,
|
||||||
ctxAgent: mainAgent,
|
ctxAgent: mainAgent,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1447,13 +1240,13 @@ export function resolveScopedConversation(
|
|||||||
const scopedConv =
|
const scopedConv =
|
||||||
effectiveScope === 'all'
|
effectiveScope === 'all'
|
||||||
? aggregated
|
? aggregated
|
||||||
: agents.find((a) => a.agentId === effectiveScope) || mainAgent;
|
: resolvedAgents.find((a) => a.agentId === effectiveScope) || mainAgent;
|
||||||
|
|
||||||
let ctxAgent = scopedConv;
|
let ctxAgent = scopedConv;
|
||||||
let effectiveCtxScope = effectiveScope;
|
let effectiveCtxScope = effectiveScope;
|
||||||
if (effectiveScope === 'all') {
|
if (effectiveScope === 'all') {
|
||||||
if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') {
|
if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') {
|
||||||
const matched = agents.find((a) => a.agentId === ctxInspectorAgentId);
|
const matched = resolvedAgents.find((a) => a.agentId === ctxInspectorAgentId);
|
||||||
if (matched) {
|
if (matched) {
|
||||||
ctxAgent = matched;
|
ctxAgent = matched;
|
||||||
effectiveCtxScope = matched.agentId;
|
effectiveCtxScope = matched.agentId;
|
||||||
@@ -1465,8 +1258,8 @@ export function resolveScopedConversation(
|
|||||||
}
|
}
|
||||||
if (effectiveCtxScope === 'auto') {
|
if (effectiveCtxScope === 'auto') {
|
||||||
ctxAgent =
|
ctxAgent =
|
||||||
agents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) ||
|
resolvedAgents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) ||
|
||||||
agents.find((a) => !a.isSideQuestion && a.isRunning) ||
|
resolvedAgents.find((a) => !a.isSideQuestion && a.isRunning) ||
|
||||||
mainAgent;
|
mainAgent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1475,7 +1268,7 @@ export function resolveScopedConversation(
|
|||||||
hasSubagents: true,
|
hasSubagents: true,
|
||||||
effectiveScope,
|
effectiveScope,
|
||||||
effectiveCtxScope,
|
effectiveCtxScope,
|
||||||
agents,
|
agents: resolvedAgents,
|
||||||
subagents,
|
subagents,
|
||||||
mainAgent,
|
mainAgent,
|
||||||
aggregated,
|
aggregated,
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
normalizeModelDisplayMode,
|
normalizeModelDisplayMode,
|
||||||
normalizeOrchestratorIdDisplayMode,
|
normalizeOrchestratorIdDisplayMode,
|
||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
|
import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs';
|
||||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||||
@@ -572,22 +573,14 @@ export const ConsumptionView = defineComponent({
|
|||||||
let cachePct = 0;
|
let cachePct = 0;
|
||||||
let outPct = 0;
|
let outPct = 0;
|
||||||
if (totalTokens > 0) {
|
if (totalTokens > 0) {
|
||||||
const rawTenths = [
|
const scaled = scaleBucketsExact(
|
||||||
(inputTokens / totalTokens) * 1000,
|
{ in: inputTokens, cache: cacheTokens, out: outputTokens },
|
||||||
(cacheTokens / totalTokens) * 1000,
|
['in', 'cache', 'out'],
|
||||||
(outputTokens / totalTokens) * 1000,
|
1000
|
||||||
];
|
|
||||||
const floored = rawTenths.map((v) => Math.max(0, Math.floor(v)));
|
|
||||||
const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2]));
|
|
||||||
const order = [0, 1, 2].sort(
|
|
||||||
(a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a])
|
|
||||||
);
|
);
|
||||||
for (let k = 0; k < rem && k < 3; k++) {
|
inPct = +(scaled.in / 10).toFixed(1);
|
||||||
floored[order[k]] += 1;
|
cachePct = +(scaled.cache / 10).toFixed(1);
|
||||||
}
|
outPct = +(scaled.out / 10).toFixed(1);
|
||||||
inPct = +(floored[0] / 10).toFixed(1);
|
|
||||||
cachePct = +(floored[1] / 10).toFixed(1);
|
|
||||||
outPct = +(floored[2] / 10).toFixed(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
patchText(inputSharePct, `${inPct}%`);
|
patchText(inputSharePct, `${inPct}%`);
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import { telemetryStore } from '../store/telemetryStore.js';
|
|||||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||||
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
|
|
||||||
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
||||||
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
||||||
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
||||||
@@ -52,7 +51,7 @@ export const SettingsView = defineComponent({
|
|||||||
|
|
||||||
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
|
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
|
||||||
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
|
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
|
||||||
const accountTab = SHOW_ACCOUNT_TAB ? SettingsAccountTab({ onLayoutChange: refreshScroll }) : null;
|
const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in
|
||||||
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
|
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
|
||||||
|
|
||||||
let showingAccount = false;
|
let showingAccount = false;
|
||||||
|
|||||||
@@ -17,11 +17,12 @@ const DEFAULT_BUNDLED_CATALOG = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const BACKEND_MODULE_FILES = [
|
const BACKEND_MODULE_FILES = [
|
||||||
|
'../shared/settings-normalization.mjs',
|
||||||
|
'../shared/telemetry-display-rules.mjs',
|
||||||
|
'../shared/window-bridge-protocol.mjs',
|
||||||
'../backend/context-windows.mjs',
|
'../backend/context-windows.mjs',
|
||||||
'../backend/account-oauth.mjs',
|
'../backend/account-oauth.mjs',
|
||||||
'../backend/account-switch.mjs',
|
'../backend/account-switch.mjs',
|
||||||
'../shared/settings-normalization.mjs',
|
|
||||||
'../shared/window-bridge-protocol.mjs',
|
|
||||||
'../backend/http-helpers.mjs',
|
'../backend/http-helpers.mjs',
|
||||||
'../backend/settings-schema.mjs',
|
'../backend/settings-schema.mjs',
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
|
|||||||
@@ -588,7 +588,7 @@ test('bundle validation rejects incompatible imports and duplicate bindings befo
|
|||||||
["import { SVG_NS /* comment */ as ns } from './SvgIcon.js';", /svgRegistry\.js.*without aliases/],
|
["import { SVG_NS /* comment */ as ns } from './SvgIcon.js';", /svgRegistry\.js.*without aliases/],
|
||||||
["import { SVG_NS } from './SvgIcon.js';", /svgRegistry\.js.*SvgIcon\.js.*earlier in jsOrder/],
|
["import { SVG_NS } from './SvgIcon.js';", /svgRegistry\.js.*SvgIcon\.js.*earlier in jsOrder/],
|
||||||
["import './missing.js';", /svgRegistry\.js.*missing\.js.*earlier in jsOrder/],
|
["import './missing.js';", /svgRegistry\.js.*missing\.js.*earlier in jsOrder/],
|
||||||
['const SVG_NS = "duplicate";', /Identifier 'SVG_NS' has already been declared/],
|
['export const SVG_NS = "duplicate";', /Identifier 'SVG_NS' has already been declared/],
|
||||||
]) {
|
]) {
|
||||||
fs.writeFileSync(iconSource, `${prefix}\n${original}`);
|
fs.writeFileSync(iconSource, `${prefix}\n${original}`);
|
||||||
assert.throws(() => buildBundle(tempDir), error);
|
assert.throws(() => buildBundle(tempDir), error);
|
||||||
@@ -596,6 +596,10 @@ test('bundle validation rejects incompatible imports and duplicate bindings befo
|
|||||||
assert.equal(fs.readFileSync(join(tempDir, file), 'utf8'), file);
|
assert.equal(fs.readFileSync(join(tempDir, file), 'utf8'), file);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Per-module closure isolation: unexported private identifiers never collide across modules
|
||||||
|
fs.writeFileSync(iconSource, `const SVG_NS = "private_local";\n${original}`);
|
||||||
|
assert.doesNotThrow(() => buildBundle(tempDir));
|
||||||
});
|
});
|
||||||
|
|
||||||
test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => {
|
test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => {
|
||||||
@@ -1108,3 +1112,74 @@ test('P0 audit fixes: main/bridge-daemon import isolation, standalone lsAddr, du
|
|||||||
);
|
);
|
||||||
assert.doesNotMatch(renderBody, /\buiStore\.setState\b/);
|
assert.doesNotMatch(renderBody, /\buiStore\.setState\b/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and dead SettingsAccountTab exclusion', async () => {
|
||||||
|
const { normalizeI18nLanguage } = await import('../src/i18n/index.js');
|
||||||
|
const { resolveSpecificQuotaSlotSummary } = await import('../src/registries/metricRegistry.js');
|
||||||
|
const { resolveScopedConversation, isEquivalentTelemetry } = await import(
|
||||||
|
'../src/store/telemetryStore.js'
|
||||||
|
);
|
||||||
|
const { buildStructurePreviewTelemetry } = await import(
|
||||||
|
'../src/components/settings/structurePreviewMock.js'
|
||||||
|
);
|
||||||
|
const { BRIDGE_API_ROUTE_DEFS } = await import('../shared/window-bridge-protocol.mjs');
|
||||||
|
|
||||||
|
assert.equal(normalizeI18nLanguage('system'), 'auto');
|
||||||
|
assert.equal(typeof isEquivalentTelemetry, 'function');
|
||||||
|
assert.equal(BRIDGE_API_ROUTE_DEFS.length, 9);
|
||||||
|
|
||||||
|
// 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry
|
||||||
|
const h = backendHarness();
|
||||||
|
const poolSample = 'Fable / OSS Third-Party Pool';
|
||||||
|
assert.equal(h.classifyQuotaPoolIdentity({ groupName: poolSample }).poolKey, 'Claude & GPT');
|
||||||
|
const quotasFixture = {
|
||||||
|
pools: [
|
||||||
|
{
|
||||||
|
poolKey: poolSample,
|
||||||
|
poolLabel: poolSample,
|
||||||
|
family: poolSample,
|
||||||
|
remainingPct: 37,
|
||||||
|
weeklyRemainingPct: 68,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
assert.equal(resolveSpecificQuotaSlotSummary(quotasFixture, 'claude_5h')?.roundedPct, 37);
|
||||||
|
assert.match(
|
||||||
|
h.formatCliStatusLineCapsule({ quotas: quotasFixture }, { slots: ['claude_5h'], terminalWidth: 120 }),
|
||||||
|
/37%/
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. Pure resolveScopedConversation never mutates deeply frozen telemetry
|
||||||
|
const deepFreeze = (obj) => {
|
||||||
|
if (!obj || typeof obj !== 'object') return obj;
|
||||||
|
Object.freeze(obj);
|
||||||
|
for (const v of Object.values(obj)) deepFreeze(v);
|
||||||
|
return obj;
|
||||||
|
};
|
||||||
|
const frozenTelemetry = deepFreeze({
|
||||||
|
activeConversation: {
|
||||||
|
cascadeId: 'frozen-conv',
|
||||||
|
hasSubagents: true,
|
||||||
|
recentSteps: [{ stepIndex: 1, createdAtMs: 100 }],
|
||||||
|
agents: [
|
||||||
|
{ agentId: 'main', isMain: true, index: 0 },
|
||||||
|
{ agentId: 'sub-1', isMain: false, index: 1, recentSteps: [{ stepIndex: 2, createdAtMs: 200 }] },
|
||||||
|
],
|
||||||
|
aggregated: { activeAgentId: 'main' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const scoped = resolveScopedConversation(frozenTelemetry, 'all', 'auto', true);
|
||||||
|
assert.equal(scoped.aggregated.recentSteps.length, 2);
|
||||||
|
assert.equal(scoped.mainAgent.recentSteps.length, 1);
|
||||||
|
|
||||||
|
// 3. structurePreviewMock schema completeness & dead SettingsAccountTab exclusion from app.js
|
||||||
|
const mock = buildStructurePreviewTelemetry();
|
||||||
|
assert.equal(typeof mock.activeConversation.context.compactionUsedTokens, 'number');
|
||||||
|
assert.equal(mock.activeConversation.aggregated.agentId, 'all');
|
||||||
|
assert.equal(Array.isArray(mock.activeConversation.agents[0].modelBreakdown), true);
|
||||||
|
assert.equal(mock.quotas.meta.hasOfficialData, true);
|
||||||
|
|
||||||
|
const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
|
||||||
|
assert.equal(appJs.includes('SettingsAccountTab.js'), false);
|
||||||
|
assert.equal(appJs.includes('function renderQuotaRows('), false);
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import fs from 'node:fs';
|
import { isEquivalentTelemetry } from '../src/store/telemetryStore.js';
|
||||||
import vm from 'node:vm';
|
|
||||||
import { normalizeClientWindowMountMode } from '../src/store/telemetryStore.js';
|
|
||||||
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs';
|
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
formatUsd,
|
formatUsd,
|
||||||
@@ -194,12 +192,9 @@ test('custom cost budget cannot claim a complete remaining percentage when price
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('frontend considers a model-only correction a real telemetry update', () => {
|
test('frontend considers a model-only correction a real telemetry update', () => {
|
||||||
const source = fs.readFileSync(new URL('../src/store/telemetryStore.js',import.meta.url),'utf8');
|
|
||||||
const fn = source.slice(source.indexOf('function isEquivalentTelemetry'),source.indexOf('export async function fetchTelemetry'));
|
|
||||||
const ctx = { normalizeClientWindowMountMode }; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx);
|
|
||||||
const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}};
|
const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}};
|
||||||
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
|
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
|
||||||
assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true);
|
assert.equal(isEquivalentTelemetry(a,b),false); assert.equal(isEquivalentTelemetry(a,structuredClone(a)),true);
|
||||||
});
|
});
|
||||||
|
|
||||||
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
||||||
|
|||||||
@@ -1,8 +1,6 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import fs from 'node:fs';
|
import { isEquivalentTelemetry } from '../src/store/telemetryStore.js';
|
||||||
import vm from 'node:vm';
|
|
||||||
import { normalizeClientWindowMountMode } from '../src/store/telemetryStore.js';
|
|
||||||
import { backendHarness } from './backend-harness.mjs';
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
|
|
||||||
const FLASH = 'MODEL_PLACEHOLDER_M318';
|
const FLASH = 'MODEL_PLACEHOLDER_M318';
|
||||||
@@ -286,14 +284,9 @@ test('exhausted 0% bucket omitting remainingFraction in proto3 is reported as 10
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('telemetryStore isEquivalentTelemetry detects quota changes in non-active pools', () => {
|
test('telemetryStore isEquivalentTelemetry detects quota changes in non-active pools', () => {
|
||||||
const source = fs.readFileSync(new URL('../src/store/telemetryStore.js', import.meta.url), 'utf8');
|
const compare = isEquivalentTelemetry;
|
||||||
const fn = source.slice(
|
|
||||||
source.indexOf('function isEquivalentTelemetry'),
|
|
||||||
source.indexOf('export async function fetchTelemetry')
|
|
||||||
);
|
|
||||||
const ctx = { normalizeClientWindowMountMode };
|
|
||||||
vm.runInNewContext(fn + '\nglobalThis.compare=isEquivalentTelemetry;', ctx);
|
|
||||||
|
|
||||||
|
const ctx = { compare };
|
||||||
const a = {
|
const a = {
|
||||||
account: { tierName: 'Google AI Pro', planName: 'Pro' },
|
account: { tierName: 'Google AI Pro', planName: 'Pro' },
|
||||||
quotas: {
|
quotas: {
|
||||||
|
|||||||
Reference in New Issue
Block a user