refactor(panel): unify settings and bridge contracts, prune dead code, and rename trajectory metrics

- Share settings normalization and window-bridge protocol contracts across frontend and backend
- Encapsulate trajectory cache accessors inside config.mjs and validate bundle imports/syntax before writing
- Remove dead selectors, unused symbols, duplicate re-export imports, and unmounted account tab instantiation
- Rename speed-metrics.mjs to trajectory-metrics.mjs and audit-fixes.test.mjs to cross-module-regressions.test.mjs
This commit is contained in:
fish
2026-11-17 20:00:50 +09:00
parent dba3473494
commit 1ff1c128a8
34 changed files with 802 additions and 676 deletions
+1 -1
View File
@@ -12,7 +12,7 @@
import { existsSync, readFileSync, statSync } from 'node:fs';
import { basename, join } from 'node:path';
import { parseIsoMs } from '../speed-metrics.mjs';
import { parseIsoMs } from '../trajectory-metrics.mjs';
import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs';
const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+33 -67
View File
@@ -12,54 +12,9 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSy
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
import {
DEFAULT_HOVER_MODULES,
DEFAULT_OVERVIEW_METRICS,
DEFAULT_OVERVIEW_MODULES,
DEFAULT_POPOVER_WIDTH,
DEFAULT_SETTINGS_SCHEMA,
DEFAULT_STEP_TABLE_COLUMNS,
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
DEFAULT_TOPBAR_SLOTS,
FONT_SCALE_KEYS,
MAX_POPOVER_WIDTH,
MAX_TOPBAR_SLOTS,
MIN_POPOVER_WIDTH,
MIN_TOPBAR_SLOTS,
MODEL_DISPLAY_MODES,
ORCHESTRATOR_ID_MODES,
OVERVIEW_METRIC_KEYS,
OVERVIEW_MODULE_KEYS,
PLUGIN_UPDATE_MODES,
POPOVER_WIDTH_MODES,
STEP_TABLE_COLUMN_KEYS,
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
WINDOW_MOUNT_MODES,
createDefaultSettingsObject,
normalizeFontScale,
normalizeFullSettings,
normalizeHoverModules,
normalizeLanguageSetting,
normalizeModelDisplayMode,
normalizeOrchestratorIdMode,
normalizeOverviewMetrics,
normalizeOverviewModules,
normalizePluginUpdateMode,
normalizePopoverWidth,
normalizePopoverWidthMode,
normalizeStandalonePort,
normalizeStepTableColumns,
normalizeStepTokenComboFormat,
normalizeThemeAccent,
normalizeTopbarCapsuleSlots,
normalizeWeeklyLimitMode,
normalizeWindowMountMode,
parseStepTokenComboSegments,
} from './settings-schema.mjs';
import { normalizeFullSettings } from './settings-schema.mjs';
export {
DEFAULT_HOVER_MODULES,
@@ -75,17 +30,12 @@ export {
MAX_TOPBAR_SLOTS,
MIN_POPOVER_WIDTH,
MIN_TOPBAR_SLOTS,
MODEL_DISPLAY_MODES,
ORCHESTRATOR_ID_MODES,
OVERVIEW_METRIC_KEYS,
OVERVIEW_MODULE_KEYS,
PLUGIN_UPDATE_MODES,
POPOVER_WIDTH_MODES,
STEP_TABLE_COLUMN_KEYS,
SUPPORTED_LANGUAGES,
THEME_ACCENT_KEYS,
TOPBAR_SLOT_KEYS,
WINDOW_MOUNT_MODES,
createDefaultSettingsObject,
normalizeFontScale,
normalizeFullSettings,
@@ -408,7 +358,9 @@ export function computeRuntimeCodeVersion() {
join(HERE, 'bridge-daemon.mjs'),
join(HERE, 'mcp-entry.mjs'),
join(HERE, 'cli-statusline.mjs'),
join(HERE, 'speed-metrics.mjs'),
join(HERE, 'trajectory-metrics.mjs'),
join(HERE, 'shared', 'settings-normalization.mjs'),
join(HERE, 'shared', 'window-bridge-protocol.mjs'),
LOCAL_CATALOG_FILE,
];
const backendDir = join(HERE, 'backend');
@@ -446,7 +398,10 @@ let initialCacheMigrated =
loadedTrajectoryCache !== undefined &&
!isPlainObject(loadedTrajectoryCache);
const safeCacheEntries = [];
/**
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
*/
const trajectoryCache = Object.create(null);
if (isPlainObject(loadedTrajectoryCache)) {
for (const [id, entry] of Object.entries(loadedTrajectoryCache)) {
if (!id || !isPlainObject(entry)) {
@@ -473,20 +428,25 @@ if (isPlainObject(loadedTrajectoryCache)) {
break;
}
}
safeCacheEntries.push([
id,
{
...entry,
steps: finalSteps,
},
]);
trajectoryCache[id] = { ...entry, steps: finalSteps };
}
}
/**
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
*/
export const trajectoryCache = Object.fromEntries(safeCacheEntries);
export function getCachedTrajectory(cascadeId) {
return trajectoryCache[cascadeId];
}
export function listCachedTrajectoryEntries() {
return Object.entries(trajectoryCache);
}
export function setCachedTrajectory(cascadeId, entry) {
trajectoryCache[cascadeId] = entry;
}
export function removeCachedTrajectory(cascadeId) {
delete trajectoryCache[cascadeId];
}
/**
* 缓存状态与外部深层统计缓存 Memo。
@@ -494,12 +454,16 @@ export const trajectoryCache = Object.fromEntries(safeCacheEntries);
*/
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
export const cacheState = {
const cacheState = {
needsSave: initialCacheMigrated,
lastSavedAtMs: 0,
flushTimer: null,
};
export function hasPendingTrajectoryCacheSave() {
return cacheState.needsSave;
}
function cancelPendingCacheFlushTimer() {
if (cacheState.flushTimer) {
try {
@@ -632,10 +596,12 @@ export const pluginUpdateState = {
/**
* 清空内存态轨迹缓存、外部深层统计 Memo 与配额摘要短期缓存,并将磁盘缓存重置为空对象。
* 空缓存落盘成功后再清理内存,写入失败时可继续使用内存数据并重试。
*
* @returns {boolean} 是否成功写回空白缓存文件
*/
export function clearRuntimeCaches() {
if (!saveJson(CACHE_FILE, {})) return false;
cancelPendingCacheFlushTimer();
for (const key of Object.keys(trajectoryCache)) {
delete trajectoryCache[key];
@@ -655,5 +621,5 @@ export function clearRuntimeCaches() {
quotaSummaryCache.accountGeneration += 1;
quotaSummaryCache.data = null;
quotaSummaryCache.error = null;
return saveJson(CACHE_FILE, {});
return true;
}
+41 -42
View File
@@ -16,7 +16,7 @@ import {
extractModelSteps,
getMaxMeaningfulStepIndex,
parseIsoMs,
} from '../speed-metrics.mjs';
} from '../trajectory-metrics.mjs';
import {
ANNOTATION_DIRS,
BRAIN_DIR,
@@ -25,11 +25,14 @@ import {
CONVERSATIONS_DIR,
CONVERSATION_DIRS,
DEEP_STATS_CACHE_CANDIDATES,
cacheState,
getCachedTrajectory,
hasPendingTrajectoryCacheSave,
listCachedTrajectoryEntries,
externalDeepStatsMemo,
loadJson,
persistTrajectoryCacheIfNeeded,
trajectoryCache,
removeCachedTrajectory,
setCachedTrajectory,
} from './config.mjs';
import {
computeSqliteWalSig,
@@ -1144,7 +1147,7 @@ export async function enumerateAndSyncConversations({
}
}
let cacheDirty = cacheState.needsSave;
let cacheDirty = hasPendingTrajectoryCacheSave();
const diskConvMap = discoverLocalConversationFiles();
// 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC)
@@ -1194,7 +1197,7 @@ export async function enumerateAndSyncConversations({
}
}
for (const rawCacheKey of Object.keys(trajectoryCache)) {
for (const [rawCacheKey] of listCachedTrajectoryEntries()) {
const lower = String(rawCacheKey || '').trim().toLowerCase();
if (!lower) continue;
const existingCanon = canonicalIdByLower.get(lower);
@@ -1202,18 +1205,18 @@ export async function enumerateAndSyncConversations({
// 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目
const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey;
if (normalizedKey !== rawCacheKey) {
trajectoryCache[normalizedKey] = trajectoryCache[rawCacheKey];
delete trajectoryCache[rawCacheKey];
setCachedTrajectory(normalizedKey, getCachedTrajectory(rawCacheKey));
removeCachedTrajectory(rawCacheKey);
cacheDirty = true;
}
canonicalIdByLower.set(lower, normalizedKey);
} else if (existingCanon !== rawCacheKey) {
const targetEntry = trajectoryCache[existingCanon];
const dupEntry = trajectoryCache[rawCacheKey];
const targetEntry = getCachedTrajectory(existingCanon);
const dupEntry = getCachedTrajectory(rawCacheKey);
if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) {
trajectoryCache[existingCanon] = dupEntry;
setCachedTrajectory(existingCanon, dupEntry);
}
delete trajectoryCache[rawCacheKey];
removeCachedTrajectory(rawCacheKey);
cacheDirty = true;
}
}
@@ -1225,7 +1228,7 @@ export async function enumerateAndSyncConversations({
}
// 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表
for (const entry of Object.values(trajectoryCache)) {
for (const [, entry] of listCachedTrajectoryEntries()) {
if (
entry?.accountName &&
currentAccountName !== '' &&
@@ -1249,7 +1252,7 @@ export async function enumerateAndSyncConversations({
for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) {
const item = summariesByLower.get(cidLower);
const localSum = item ? null : localSummaryByLower.get(cidLower) || null;
const cached = trajectoryCache[cascadeId];
const cached = getCachedTrajectory(cascadeId);
if (
cached?.accountName &&
currentAccountName !== '' &&
@@ -1525,7 +1528,7 @@ export async function enumerateAndSyncConversations({
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower);
const prev = trajectoryCache[conv.cascadeId];
const prev = getCachedTrajectory(conv.cascadeId);
let partialTailSteps = [];
let hasTailStepInfo = false;
try {
@@ -1723,7 +1726,7 @@ export async function enumerateAndSyncConversations({
!isDeepStrictEqual(prev.steps, steps);
if (!stepsChanged) cacheEntry.steps = prev.steps;
trajectoryCache[conv.cascadeId] = cacheEntry;
setCachedTrajectory(conv.cascadeId, cacheEntry);
if (stepsChanged) {
cacheDirty = true;
}
@@ -1806,7 +1809,7 @@ export async function enumerateAndSyncConversations({
Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) ||
!isDeepStrictEqual(prev.steps, offlineEntry.steps);
if (!changed) offlineEntry.steps = prev.steps;
trajectoryCache[conv.cascadeId] = offlineEntry;
setCachedTrajectory(conv.cascadeId, offlineEntry);
if (changed) {
cacheDirty = true;
}
@@ -1845,10 +1848,11 @@ export async function enumerateAndSyncConversations({
if (
!offlineRecovered &&
prev &&
getCachedTrajectory(conv.cascadeId) === prev &&
String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
!Array.isArray(prev.subagentRefs)
) {
prev.subagentRefs = [];
setCachedTrajectory(conv.cascadeId, { ...prev, subagentRefs: [] });
cacheDirty = true;
}
}
@@ -1896,7 +1900,7 @@ export async function enumerateAndSyncConversations({
const sig = buildConvSig(conv);
if (isFetchInCooldown(conv, sig)) return false;
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
const cached = trajectoryCache[conv.cascadeId];
const cached = getCachedTrajectory(conv.cascadeId);
if (!cached || conv.needsInitialLoad) return true;
const lowerCid = conv.cascadeId.toLowerCase();
const isSelectedFamily =
@@ -1983,7 +1987,7 @@ export async function enumerateAndSyncConversations({
const missingSubagentsToFetch = [];
for (const parentConv of [...rawConversations]) {
const parentCached = trajectoryCache[parentConv.cascadeId];
const parentCached = getCachedTrajectory(parentConv.cascadeId);
const refs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
if (!Array.isArray(refs) || refs.length === 0) continue;
@@ -2001,7 +2005,7 @@ export async function enumerateAndSyncConversations({
const canonSubId = canonicalIdByLower.get(subCid) || subCid;
canonicalIdByLower.set(subCid, canonSubId);
let subConv = byLowerId.get(subCid);
const subCached = trajectoryCache[subConv?.cascadeId || canonSubId];
const subCached = getCachedTrajectory(subConv?.cascadeId || canonSubId);
if (!subConv) {
const subDiskFiles = diskConvMap.get(subCid) || [];
const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null;
@@ -2059,7 +2063,7 @@ export async function enumerateAndSyncConversations({
}
const targetCacheKey = subConv.cascadeId;
const existingSubCache = trajectoryCache[targetCacheKey];
const existingSubCache = getCachedTrajectory(targetCacheKey);
const isSelectedSubFamily = rootId === selectedRootId;
const hasValidSubCache =
existingSubCache &&
@@ -2076,42 +2080,37 @@ export async function enumerateAndSyncConversations({
!hasDroppedContextGroups(existingSubCache)));
if (hasValidSubCache) {
let subMetaUpdated = false;
const updatedMetadata = {};
if (existingSubCache.parentConversationId !== subConv.parentConversationId) {
existingSubCache.parentConversationId = subConv.parentConversationId;
subMetaUpdated = true;
updatedMetadata.parentConversationId = subConv.parentConversationId;
}
if (existingSubCache.rootConversationId !== subConv.rootConversationId) {
existingSubCache.rootConversationId = subConv.rootConversationId;
subMetaUpdated = true;
updatedMetadata.rootConversationId = subConv.rootConversationId;
}
const nextSpec = sanitizeSubagentSpec(subConv.subagentSpec);
if (
nextSpec &&
JSON.stringify(existingSubCache.subagentSpec || null) !== JSON.stringify(nextSpec)
) {
existingSubCache.subagentSpec = nextSpec;
subMetaUpdated = true;
updatedMetadata.subagentSpec = nextSpec;
}
if (
subConv.createdTimeMs &&
existingSubCache.createdTimeMs !== subConv.createdTimeMs
) {
existingSubCache.createdTimeMs = subConv.createdTimeMs;
subMetaUpdated = true;
updatedMetadata.createdTimeMs = subConv.createdTimeMs;
}
if (
Number.isFinite(subConv.spawnOrder) &&
existingSubCache.spawnOrder !== subConv.spawnOrder
) {
existingSubCache.spawnOrder = subConv.spawnOrder;
subMetaUpdated = true;
updatedMetadata.spawnOrder = subConv.spawnOrder;
}
if (!Array.isArray(existingSubCache.subagentRefs)) {
existingSubCache.subagentRefs = [];
subMetaUpdated = true;
updatedMetadata.subagentRefs = [];
}
if (subMetaUpdated) {
if (Object.keys(updatedMetadata).length > 0) {
setCachedTrajectory(targetCacheKey, { ...existingSubCache, ...updatedMetadata });
cacheDirty = true;
}
} else {
@@ -2137,7 +2136,7 @@ export async function enumerateAndSyncConversations({
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
return false;
}
const cached = trajectoryCache[c.cascadeId];
const cached = getCachedTrajectory(c.cascadeId);
return cached && !Array.isArray(cached.subagentRefs);
})
.slice(0, LEGACY_MIGRATION_BATCH_SIZE);
@@ -2171,9 +2170,9 @@ export async function enumerateAndSyncConversations({
}
if (candidate && candidate !== conv.rootConversationId) {
conv.rootConversationId = candidate;
const cached = trajectoryCache[conv.cascadeId];
const cached = getCachedTrajectory(conv.cascadeId);
if (cached && cached.rootConversationId !== candidate) {
cached.rootConversationId = candidate;
setCachedTrajectory(conv.cascadeId, { ...cached, rootConversationId: candidate });
cacheDirty = true;
}
}
@@ -2182,7 +2181,7 @@ export async function enumerateAndSyncConversations({
const hasRunningSessions = rawConversations.some(
(c) => c.status === 'CASCADE_RUN_STATUS_RUNNING'
);
if (cacheDirty || (cacheState.needsSave && !hasRunningSessions)) {
if (cacheDirty || (hasPendingTrajectoryCacheSave() && !hasRunningSessions)) {
persistTrajectoryCacheIfNeeded({ hasRunningSessions });
}
@@ -2259,12 +2258,12 @@ export async function enumerateAndSyncConversations({
}
const aStart =
a.createdTimeMs ||
trajectoryCache[a.cascadeId]?.steps?.[0]?.createdAtMs ||
getCachedTrajectory(a.cascadeId)?.steps?.[0]?.createdAtMs ||
a.lastModifiedMs ||
0;
const bStart =
b.createdTimeMs ||
trajectoryCache[b.cascadeId]?.steps?.[0]?.createdAtMs ||
getCachedTrajectory(b.cascadeId)?.steps?.[0]?.createdAtMs ||
b.lastModifiedMs ||
0;
return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId));
@@ -2293,7 +2292,7 @@ export async function enumerateAndSyncConversations({
))) ||
conversations[0] ||
null;
const requestedOwner = trajectoryCache[canonicalIdByLower.get(reqLower)]?.accountName;
const requestedOwner = getCachedTrajectory(canonicalIdByLower.get(reqLower))?.accountName;
const safeReqId = requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) &&
(!requestedOwner || currentAccountName === '' || requestedOwner === currentAccountName) ? requestedConvId : null;
const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null;
+1 -1
View File
@@ -8,7 +8,7 @@
* 绝不借用其他模型单价伪造费用。
*/
import { parseIsoMs } from '../speed-metrics.mjs';
import { parseIsoMs } from '../trajectory-metrics.mjs';
import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs';
/**
+1 -1
View File
@@ -11,7 +11,7 @@
import { existsSync } from 'node:fs';
import { join } from 'node:path';
import { parseIsoMs } from '../speed-metrics.mjs';
import { parseIsoMs } from '../trajectory-metrics.mjs';
import {
DEFAULT_ARCHIVE_FALLBACK_URL,
DEFAULT_DOWNLOAD_URL,
+1 -1
View File
@@ -9,7 +9,7 @@
* - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略且存在尚未过期的有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。
*/
import { parseIsoMs } from '../speed-metrics.mjs';
import { parseIsoMs } from '../trajectory-metrics.mjs';
import {
isArgonModelIdentifier,
isCarbonModelIdentifier,
+21 -127
View File
@@ -6,6 +6,27 @@
*/
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
import {
DEFAULT_OVERVIEW_METRICS,
DEFAULT_TOPBAR_SLOTS,
normalizeOverviewMetrics,
normalizeTopbarCapsuleSlots,
normalizeWeeklyLimitMode,
normalizeWindowMountMode,
} from '../shared/settings-normalization.mjs';
export {
DEFAULT_OVERVIEW_METRICS,
DEFAULT_TOPBAR_SLOTS,
MAX_TOPBAR_SLOTS,
MIN_TOPBAR_SLOTS,
OVERVIEW_METRIC_KEYS,
TOPBAR_SLOT_KEYS,
normalizeOverviewMetrics,
normalizeTopbarCapsuleSlots,
normalizeWeeklyLimitMode,
normalizeWindowMountMode,
} from '../shared/settings-normalization.mjs';
export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']);
@@ -21,26 +42,6 @@ export const THEME_ACCENT_KEYS = Object.freeze([
export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']);
export const TOPBAR_SLOT_KEYS = Object.freeze([
'context',
'tps',
'ttft',
'avg_tps',
'cost',
'session_cost',
'cache_hit',
'session_tokens',
'quota_auto',
'gemini_5h',
'gemini_weekly',
'claude_5h',
'claude_weekly',
]);
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
export const MIN_TOPBAR_SLOTS = 1;
export const MAX_TOPBAR_SLOTS = 5;
export const OVERVIEW_MODULE_KEYS = Object.freeze([
'metrics',
'context',
@@ -57,25 +58,6 @@ export const DEFAULT_OVERVIEW_MODULES = Object.freeze([
export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
export const OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
export const DEFAULT_OVERVIEW_METRICS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
]);
export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
'step',
'time',
@@ -141,14 +123,6 @@ export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
'总token': 'total',
});
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
export const MODEL_DISPLAY_MODES = Object.freeze(['short', 'upstream', 'upstream_compact']);
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
export const MIN_POPOVER_WIDTH = 440;
export const MAX_POPOVER_WIDTH = 1080;
@@ -201,23 +175,6 @@ export function normalizeFontScale(scale) {
return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md';
}
/**
* 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏),
* 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。
*
* @param {unknown} mode
* @param {unknown} [legacyEnableOverlay]
* @returns {'dual'|'composer'|'sidebar'}
*/
export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
const m = String(mode ?? '').trim().toLowerCase();
if (m === 'composer' || m === 'input') return 'composer';
if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar';
if (m === 'dual' || m === 'topbar') return 'dual';
if (legacyEnableOverlay === false) return 'sidebar';
return 'dual';
}
/**
* 归一化模型名称展示模式(`'short'` 精简代号 | `'upstream_compact'` 去前缀原始 ID | `'upstream'` 完整原始 ID),
* 兼容历史 `showUpstreamModel` 布尔开关,默认 `'short'`。
@@ -321,46 +278,6 @@ export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
return 'manual';
}
/**
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
*
* @param {unknown} mode
* @returns {'official'|'custom_tokens'|'custom_cost'}
*/
export function normalizeWeeklyLimitMode(mode) {
const m = String(mode || '').trim().toLowerCase();
if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens';
if (m === 'custom_cost' || m === 'cost') return 'custom_cost';
return 'official';
}
/**
* 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。
*
* @param {unknown} raw
* @returns {string[]}
*/
export function normalizeTopbarCapsuleSlots(raw) {
if (!Array.isArray(raw)) {
return [...DEFAULT_TOPBAR_SLOTS];
}
const seen = new Set();
const out = [];
for (const item of raw) {
const val = String(item ?? '').trim();
if (!val || val === 'none') continue;
const mapped = val === 'step_cost' ? 'cost' : val;
if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue;
seen.add(mapped);
out.push(mapped);
if (out.length >= MAX_TOPBAR_SLOTS) break;
}
if (out.length < MIN_TOPBAR_SLOTS) {
return ['context'];
}
return out;
}
/**
* 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。
*
@@ -405,29 +322,6 @@ export function normalizeHoverModules(raw) {
return out;
}
/**
* 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。
*
* @param {unknown} raw
* @returns {string[]}
*/
export function normalizeOverviewMetrics(raw) {
if (!Array.isArray(raw)) {
return [...DEFAULT_OVERVIEW_METRICS];
}
const seen = new Set();
const out = [];
for (const item of raw) {
const rawVal = String(item ?? '').trim();
const val = rawVal === 'cost' ? 'step_cost' : rawVal;
if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue;
seen.add(val);
out.push(val);
if (out.length >= 4) break;
}
return out.length > 0 ? out : ['tps'];
}
/**
* 归一化调用明细「按步查看」表格列配置与左右顺序(2~12 列,默认保留现有 7 列)。
*
+7 -5
View File
@@ -16,16 +16,17 @@ import {
speedMetric,
summarizeSpeed,
summarizeTtft,
} from '../speed-metrics.mjs';
} from '../trajectory-metrics.mjs';
import {
CLI_STATUS_SNAPSHOT_FILE,
computeRuntimeCodeVersion,
getCachedTrajectory,
inFlightRequests,
listCachedTrajectoryEntries,
loadSettings,
lsRuntimeEndpoint,
roundMetric,
saveJson,
trajectoryCache,
} from './config.mjs';
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs';
@@ -60,9 +61,10 @@ function roundSessionCost(val) {
function findTrajectoryCacheEntry(cascadeId) {
if (!cascadeId) return null;
if (trajectoryCache[cascadeId]) return trajectoryCache[cascadeId];
const entry = getCachedTrajectory(cascadeId);
if (entry) return entry;
const targetLower = String(cascadeId).toLowerCase();
for (const [k, v] of Object.entries(trajectoryCache)) {
for (const [k, v] of listCachedTrajectoryEntries()) {
if (k.toLowerCase() === targetLower) return v;
}
return null;
@@ -98,7 +100,7 @@ function readTrajectoryModelFacts(steps) {
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
const knownUpstreamByModelKey = new Map();
for (const entry of Object.values(trajectoryCache)) {
for (const [, entry] of listCachedTrajectoryEntries()) {
if (!entry?.steps?.length) continue;
const facts = readTrajectoryModelFacts(entry.steps);
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
+3 -3
View File
@@ -13,8 +13,8 @@ import {
createSpeedAccumulator,
finishSpeed,
parseIsoMs,
} from '../speed-metrics.mjs';
import { roundMetric, trajectoryCache } from './config.mjs';
} from '../trajectory-metrics.mjs';
import { listCachedTrajectoryEntries, roundMetric } from './config.mjs';
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
import {
computeStepCost,
@@ -550,7 +550,7 @@ export function aggregateMultiWindowUsage({
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
const allLiveByLower = new Map();
for (const [rawId, entry] of Object.entries(trajectoryCache)) {
for (const [rawId, entry] of listCachedTrajectoryEntries()) {
const cidLower = String(rawId || '').toLowerCase();
if (!cidLower || !entry || typeof entry !== 'object') continue;
const prev = allLiveByLower.get(cidLower);
+61 -17
View File
@@ -13,6 +13,12 @@
import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
import {
WINDOW_BRIDGE_KEY,
WINDOW_BRIDGE_ROUTE_KEY,
WINDOW_OVERLAY_KEY,
WINDOW_OVERLAY_METHODS,
} from '../shared/window-bridge-protocol.mjs';
import {
DATA_DIR,
computeRuntimeCodeVersion,
@@ -24,6 +30,13 @@ import {
} from './config.mjs';
import { createContextWindowSyncExpression } from './context-windows.mjs';
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
const overlayMethods = Object.fromEntries(
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
);
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
const ALLOWED_BRIDGE_PATHS = new Set([
'/api/telemetry',
@@ -1200,10 +1213,10 @@ export function createWindowBridgeController(options) {
const disposeExpr = `(() => {
try {
const existed = Boolean(window.__AGUsageMonitorOverlay || window.__AGUsageMonitorBridge);
window.__AGUsageMonitorOverlay?.dispose?.();
delete window.__AGUsageMonitorOverlay;
delete window.__AGUsageMonitorBridge;
const existed = Boolean(${windowOverlayRef} || ${windowBridgeRef});
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
delete ${windowOverlayRef};
delete ${windowBridgeRef};
return existed;
} catch {
return false;
@@ -1240,11 +1253,11 @@ export function createWindowBridgeController(options) {
const { port, token } = await ensureBridgeServer();
const probeExpr = `(() => {
try {
const ov = window.__AGUsageMonitorOverlay;
const br = window.__AGUsageMonitorBridge;
const alive = Boolean(ov && typeof ov.ensureAlive === 'function' && ov.ensureAlive());
const dockKind = String(ov?.getDockKind?.() || '');
const clientMountMode = String(ov?.getMountMode?.() || '');
const ov = ${windowOverlayRef};
const br = ${windowBridgeRef};
const alive = Boolean(ov && typeof ov[${overlayMethods.ensureAlive}] === 'function' && ov[${overlayMethods.ensureAlive}]());
const dockKind = String(ov?.[${overlayMethods.getDockKind}]?.() || '');
const clientMountMode = String(ov?.[${overlayMethods.getMountMode}]?.() || '');
const visible = Boolean(
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
@@ -1276,7 +1289,7 @@ export function createWindowBridgeController(options) {
bridgePort: Number(br?.port || 0),
hasToken: Boolean(br?.token),
transportMode: String(br?.transportMode || 'http'),
hostRouteCascadeId: String(br?.hostRouteCascadeId || ''),
hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''),
routeCascadeId,
rpcBatch,
};
@@ -1314,12 +1327,16 @@ export function createWindowBridgeController(options) {
}
if (snap.bundleVersion === bundleVersion) {
if (snap.bridgePort !== port || snap.hasToken !== true) {
const rebindExpr = `window.__AGUsageMonitorOverlay?.updateBridge?.(${JSON.stringify({ port, token })})`;
const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ port, token })})`;
await evaluateOnTarget(wsUrl, rebindExpr);
}
let effectiveDockKind = String(snap.dockKind || '');
if (snap.clientMountMode && snap.clientMountMode !== mountMode) {
const modeSyncExpr = `(() => { window.__AGUsageMonitorOverlay?.applyMountMode?.(${JSON.stringify(mountMode)}); return String(window.__AGUsageMonitorOverlay?.getDockKind?.() || ''); })()`;
const modeSyncExpr = `(() => {
const overlay = ${windowOverlayRef};
overlay?.[${overlayMethods.applyMountMode}]?.(${JSON.stringify(mountMode)});
return String(overlay?.[${overlayMethods.getDockKind}]?.() || '');
})()`;
const modeRes = await evaluateOnTarget(wsUrl, modeSyncExpr);
if (typeof modeRes?.result?.result?.value === 'string') {
effectiveDockKind = modeRes.result.result.value;
@@ -1330,7 +1347,11 @@ export function createWindowBridgeController(options) {
ideRouteId &&
String(snap.hostRouteCascadeId || '') !== ideRouteId
) {
const routeSyncExpr = `(() => { if (window.__AGUsageMonitorBridge) { window.__AGUsageMonitorBridge.hostRouteCascadeId = ${JSON.stringify(ideRouteId)}; } window.__AGUsageMonitorOverlay?.syncHostRoute?.(); })()`;
const routeSyncExpr = `(() => {
const bridge = ${windowBridgeRef};
if (bridge) bridge[${windowBridgeRouteKey}] = ${JSON.stringify(ideRouteId)};
${windowOverlayRef}?.[${overlayMethods.syncHostRoute}]?.();
})()`;
await evaluateOnTarget(wsUrl, routeSyncExpr);
}
aliveCount += 1;
@@ -1346,7 +1367,7 @@ export function createWindowBridgeController(options) {
sawCdpTransport = true;
const rpcResults = await executeRpcBatch(snap.rpcBatch);
relayedRpcCount += rpcResults.length;
const deliverExpr = `window.__AGUsageMonitorOverlay?.deliverRpc?.(${JSON.stringify(rpcResults)})`;
const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`;
await evaluateOnTarget(wsUrl, deliverExpr);
}
return {
@@ -1388,12 +1409,25 @@ export function createWindowBridgeController(options) {
token,
bundleVersion,
mountMode,
hostRouteCascadeId: ideRouteId || '',
[WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '',
isIdeChatFrame: Boolean(isIdeChatFrame),
stylesCss: cachedAssets.stylesCss,
initialTelemetry,
});
const injectionScript = `(() => {\nwindow.__AGUsageMonitorBridge = ${bridgeConfigJson};\n})();\n${cachedAssets.appJs}\n(() => { const ov = window.__AGUsageMonitorOverlay; const alive = Boolean(ov && ov.ensureAlive && ov.ensureAlive()); return { alive, dockKind: String(ov?.getDockKind?.() || ''), visible: Boolean((window.innerWidth === undefined || Number(window.innerWidth) > 80) && (window.innerHeight === undefined || Number(window.innerHeight) > 80) && !(typeof document !== 'undefined' && document?.hidden === true)) }; })();`;
const injectionScript = `(() => {
${windowBridgeRef} = ${bridgeConfigJson};
})();
${cachedAssets.appJs}
(() => {
const ov = ${windowOverlayRef};
const alive = Boolean(ov?.[${overlayMethods.ensureAlive}]?.());
const visible = Boolean(
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
!(typeof document !== 'undefined' && document?.hidden === true)
);
return { alive, dockKind: String(ov?.[${overlayMethods.getDockKind}]?.() || ''), visible };
})();`;
const evalRes = await evaluateOnTarget(wsUrl, injectionScript);
const evalVal = evalRes?.result?.result?.value;
@@ -1540,7 +1574,17 @@ export function createWindowBridgeController(options) {
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({
targets: [],
}));
const disposeExpr = `(() => { try { window.__AGUsageMonitorContextWindows?.dispose?.(); window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`;
const disposeExpr = `(() => {
try {
window.__AGUsageMonitorContextWindows?.dispose?.();
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
delete ${windowOverlayRef};
delete ${windowBridgeRef};
return true;
} catch {
return false;
}
})()`;
const allUrls = [
...targets.map((t) => String(t.webSocketDebuggerUrl || '')).filter(Boolean),
...collectAllChatDebuggerUrls(targets),