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
+189 -146
View File
@@ -1,6 +1,150 @@
(() => {
'use strict';
// --- shared/settings-normalization.mjs ---
/**
* @fileoverview 前后端共用的偏好设置归一化规则。
*/
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',
]);
const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
const MIN_TOPBAR_SLOTS = 1;
const MAX_TOPBAR_SLOTS = 5;
const OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
const DEFAULT_OVERVIEW_METRICS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
]);
/**
* 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏),
* 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。
*
* @param {unknown} mode
* @param {unknown} [legacyEnableOverlay]
* @returns {'dual'|'composer'|'sidebar'}
*/
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';
}
/**
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
*
* @param {unknown} mode
* @returns {'official'|'custom_tokens'|'custom_cost'}
*/
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[]}
*/
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 项)。
*
* @param {unknown} raw
* @returns {string[]}
*/
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'];
}
// --- shared/window-bridge-protocol.mjs ---
const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
const WINDOW_OVERLAY_METHODS = Object.freeze({
ensureAlive: 'ensureAlive',
getDockKind: 'getDockKind',
getMountMode: 'getMountMode',
updateBridge: 'updateBridge',
applyMountMode: 'applyMountMode',
syncHostRoute: 'syncHostRoute',
deliverRpc: 'deliverRpc',
dispose: 'dispose',
});
function readInjectedWindowBridge() {
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
}
// --- src/icons/svgRegistry.js ---
/**
* @fileoverview Pure vector SVG icon registry (16x16 grid).
@@ -2276,6 +2420,7 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
*/
const inFlightGets = new Map();
const activeControllers = new Map();
@@ -2285,8 +2430,7 @@ const activeControllers = new Map();
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
*/
function getWindowBridgeConfig() {
if (typeof window === 'undefined') return null;
const br = window.__AGUsageMonitorBridge;
const br = readInjectedWindowBridge();
const port = Number(br?.port || 0);
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
return br;
@@ -2520,13 +2664,6 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi
*/
const VIEW_TABS = Object.freeze([
{ value: 'overview', label: '实时监控', icon: 'pulse' },
{ value: 'consumption', label: '用量统计', icon: 'chart-bar' },
{ value: 'steps', label: '调用明细', icon: 'table' },
{ value: 'settings', label: '偏好设置', icon: 'sliders' },
]);
function getViewTabs() {
return [
{ value: 'overview', label: t('nav.overview'), icon: 'pulse' },
@@ -2574,7 +2711,7 @@ function extractHostRouteCascadeId() {
if (m && CASCADE_UUID_RE.test(m[1])) {
return m[1];
}
const extBridgeRouteId = String(window.__AGUsageMonitorBridge?.hostRouteCascadeId || '').trim();
const extBridgeRouteId = String(readInjectedWindowBridge()?.[WINDOW_BRIDGE_ROUTE_KEY] || '').trim();
if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) {
return extBridgeRouteId;
}
@@ -2656,23 +2793,9 @@ let loopActive = false;
let loopIntervalMs = 2000;
let loopTickFn = null;
const CLIENT_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',
]);
const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
'metrics',
@@ -2690,24 +2813,9 @@ const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([
const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
const CLIENT_OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS;
const DEFAULT_CLIENT_OVERVIEW_METRICS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
]);
const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS;
const CLIENT_STEP_COLUMN_KEYS = Object.freeze([
'step',
@@ -2857,12 +2965,7 @@ function normalizeClientOrderedList(raw, { allowedKeys, defaultItems, minLen, ma
* @returns {string[]}
*/
function normalizeClientTopbarSlots(raw) {
return normalizeClientOrderedList(raw, {
allowedKeys: CLIENT_TOPBAR_SLOT_KEYS,
defaultItems: DEFAULT_CLIENT_TOPBAR_SLOTS,
minLen: 1,
maxLen: 5,
});
return normalizeTopbarCapsuleSlots(raw);
}
/**
@@ -2902,12 +3005,7 @@ function normalizeClientOverviewModules(raw) {
* @returns {string[]}
*/
function normalizeClientOverviewMetrics(raw) {
return normalizeClientOrderedList(raw, {
allowedKeys: CLIENT_OVERVIEW_METRIC_KEYS,
defaultItems: DEFAULT_CLIENT_OVERVIEW_METRICS,
minLen: 1,
maxLen: 4,
});
return normalizeOverviewMetrics(raw);
}
/**
@@ -2951,12 +3049,7 @@ function normalizeClientOrchestratorIdMode(mode) {
* @returns {'dual'|'composer'|'sidebar'}
*/
function normalizeClientWindowMountMode(mode, legacyEnableOverlay) {
const m = String(mode ?? '').trim().toLowerCase();
if (m === 'composer' || m === 'input') return 'composer';
if (m === 'sidebar' || m === 'off') return 'sidebar';
if (m === 'dual' || m === 'topbar') return 'dual';
if (legacyEnableOverlay === false) return 'sidebar';
return 'dual';
return normalizeWindowMountMode(mode, legacyEnableOverlay);
}
function isEquivalentTelemetry(prev, next) {
@@ -2972,15 +3065,6 @@ function isEquivalentTelemetry(prev, next) {
}
return true;
};
const normMount = (mode, legacyEnableOverlay) => {
const m = String(mode ?? '').trim().toLowerCase();
if (m === 'composer' || m === 'input') return 'composer';
if (m === 'sidebar' || m === 'off') return 'sidebar';
if (m === 'dual' || m === 'topbar') return 'dual';
if (legacyEnableOverlay === false) return 'sidebar';
return 'dual';
};
// 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置)
const pAct = prev.activeConversation;
const nAct = next.activeConversation;
@@ -3052,8 +3136,8 @@ function isEquivalentTelemetry(prev, next) {
if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false;
if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false;
if (
normMount(pSet?.windowMountMode, pSet?.enableWindowOverlay) !==
normMount(nSet?.windowMountMode, nSet?.enableWindowOverlay)
normalizeClientWindowMountMode(pSet?.windowMountMode, pSet?.enableWindowOverlay) !==
normalizeClientWindowMountMode(nSet?.windowMountMode, nSet?.enableWindowOverlay)
) {
return false;
}
@@ -3686,9 +3770,7 @@ async function saveSettingsPatch(patch) {
safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
const mode = safePatch.weeklyLimitMode;
safePatch.weeklyLimitMode =
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) {
safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine);
@@ -6531,21 +6613,6 @@ function computePublicationFit(
};
}
/**
* 计算样本点上的平滑回归拟合值序列(供单元测试与轻量调用直接读取)。
*
* @param {number[]} ys
* @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [bounds]
* @returns {number[]}
*/
function computeLoessFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) {
const n = Array.isArray(ys) ? ys.length : 0;
if (n === 0) return [];
const xArr =
Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx);
return computePublicationFit(xArr, ys, { minVal, maxVal }).sampleFits;
}
/**
* Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。
*/
@@ -8370,33 +8437,8 @@ function createModelFitChart() {
*/
const CAPSULE_METRIC_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',
]);
const OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS;
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
@@ -17741,7 +17783,7 @@ const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const accountTab = SHOW_ACCOUNT_TAB ? SettingsAccountTab({ onLayoutChange: refreshScroll }) : null;
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
let showingAccount = false;
@@ -17749,25 +17791,27 @@ const SettingsView = defineComponent({
const target =
subTab === 'structure' ||
subTab === 'other' ||
(SHOW_ACCOUNT_TAB && subTab === 'account')
(accountTab && subTab === 'account')
? subTab
: 'general';
subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure');
patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure');
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
patchAttr(otherTab.el, 'hidden', target !== 'other');
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
if (accountTab) {
patchAttr(accountTab.el, 'hidden', target !== 'account');
const nextShowingAccount = target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
}
refreshScroll();
}
const contentContainer = h(
'div',
{},
SHOW_ACCOUNT_TAB
accountTab
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
: [generalTab.el, structureTab.el, otherTab.el]
);
@@ -17794,7 +17838,7 @@ const SettingsView = defineComponent({
if (settings) structureTab.refs.renderSettings(settings);
} else if (settingsSubTab === 'other') {
if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []);
} else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') {
} else if (accountTab && settingsSubTab === 'account') {
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
} else {
if (settings) generalTab.refs.renderSettings(settings);
@@ -17834,7 +17878,7 @@ const SettingsView = defineComponent({
});
generalTab.refs.refreshLabels();
structureTab.refs.refreshLabels();
accountTab.refs.refreshLabels();
accountTab?.refs.refreshLabels();
otherTab.refs.refreshLabels();
refreshScroll();
}
@@ -17847,7 +17891,7 @@ const SettingsView = defineComponent({
subNavSwitch.destroy();
generalTab.destroy();
structureTab.destroy();
accountTab.destroy();
accountTab?.destroy();
otherTab.destroy();
viewScrollbar.destroy();
});
@@ -18779,7 +18823,7 @@ function isImmediatelyBeforeNode(node, refNode) {
function isIdeExtensionChatFrame() {
try {
if (typeof window === 'undefined') return false;
if (window.__AGUsageMonitorBridge?.isIdeChatFrame === true) return true;
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
} catch {
return false;
@@ -18790,7 +18834,7 @@ function resolveActiveDockTarget(options = undefined) {
const settings = telemetryStore.getState().telemetry?.settings;
const rawMode =
settings?.windowMountMode ??
(typeof window !== 'undefined' ? window.__AGUsageMonitorBridge?.mountMode : undefined);
readInjectedWindowBridge()?.mountMode;
const mountMode =
options?.mountMode ||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
@@ -18891,14 +18935,14 @@ function mountWindowOverlay() {
let carryOverMultiPinnedOpen = false;
let carryOverPointer = null;
try {
const prevOv = window.__AGUsageMonitorOverlay;
const prevOv = window[WINDOW_OVERLAY_KEY];
carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null;
carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.());
carryOverPopoverOpen = Boolean(prevOv?.isOpen?.());
carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.());
carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.());
carryOverPointer = prevOv?.getLastPointer?.() || null;
prevOv?.dispose?.();
prevOv?.[WINDOW_OVERLAY_METHODS.dispose]?.();
} catch {
// 忽略旧实例卸载异常
}
@@ -21036,28 +21080,28 @@ function mountWindowOverlay() {
const handle = {
bundleVersion,
ensureAlive() {
[WINDOW_OVERLAY_METHODS.ensureAlive]() {
if (disposed) return false;
return ensureCapsuleDocked();
},
syncHostRoute() {
[WINDOW_OVERLAY_METHODS.syncHostRoute]() {
if (disposed) return false;
syncHostRouteIfChanged();
return true;
},
updateBridge(nextBridge) {
[WINDOW_OVERLAY_METHODS.updateBridge](nextBridge) {
if (disposed || !nextBridge || typeof nextBridge !== 'object') return false;
const port = Number(nextBridge.port || 0);
const token = String(nextBridge.token || '');
if (!Number.isInteger(port) || port <= 0 || !token) return false;
const cur = window.__AGUsageMonitorBridge || {};
const cur = readInjectedWindowBridge() || {};
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
cur.port = port;
cur.token = token;
if (portChanged) {
cur.transportMode = 'http';
}
window.__AGUsageMonitorBridge = cur;
window[WINDOW_BRIDGE_KEY] = cur;
void fetchTelemetry({ force: false });
return true;
},
@@ -21067,7 +21111,7 @@ function mountWindowOverlay() {
getLastPointer() {
return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null;
},
deliverRpc(responses) {
[WINDOW_OVERLAY_METHODS.deliverRpc](responses) {
if (disposed) return 0;
return deliverCdpBridgeResponses(responses);
},
@@ -21092,14 +21136,13 @@ function mountWindowOverlay() {
isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned),
isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned),
getLayoutMode: () => layoutMode,
getDockKind: () => String(capsuleHost.getAttribute('data-dock') || ''),
getMountMode: () => lastAppliedMountMode,
applyMountMode(nextMode) {
[WINDOW_OVERLAY_METHODS.getDockKind]: () => String(capsuleHost.getAttribute('data-dock') || ''),
[WINDOW_OVERLAY_METHODS.getMountMode]: () => lastAppliedMountMode,
[WINDOW_OVERLAY_METHODS.applyMountMode](nextMode) {
if (disposed) return false;
const normalized = normalizeClientWindowMountMode(nextMode, nextMode !== 'sidebar');
if (typeof window !== 'undefined' && window.__AGUsageMonitorBridge) {
window.__AGUsageMonitorBridge.mountMode = normalized;
}
const bridgeConfig = readInjectedWindowBridge();
if (bridgeConfig) bridgeConfig.mountMode = normalized;
const curTel = telemetryStore.getState().telemetry;
if (curTel?.settings) {
telemetryStore.setState({
@@ -21116,7 +21159,7 @@ function mountWindowOverlay() {
lastAppliedMountMode = normalized;
return ensureCapsuleDocked();
},
dispose() {
[WINDOW_OVERLAY_METHODS.dispose]() {
if (disposed) return;
disposed = true;
clearInterval(watchdogTimer);
@@ -21169,13 +21212,13 @@ function mountWindowOverlay() {
try {
portalHost.remove();
} catch {}
if (window.__AGUsageMonitorOverlay === handle) {
delete window.__AGUsageMonitorOverlay;
if (window[WINDOW_OVERLAY_KEY] === handle) {
delete window[WINDOW_OVERLAY_KEY];
}
},
};
window.__AGUsageMonitorOverlay = handle;
window[WINDOW_OVERLAY_KEY] = handle;
return handle;
}
+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),
+1 -1
View File
@@ -23,7 +23,7 @@ import {
speedMetric,
summarizeSpeed,
summarizeTtft,
} from './speed-metrics.mjs';
} from './trajectory-metrics.mjs';
import {
getNodeSqliteDatabaseSync,
readLocalSqliteTrajectory,
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1794904298571">
<link rel="stylesheet" href="/styles.css?v=1794908461497">
<script src="/preload.js"></script>
</head>
<body>
<div id="app-root"></div>
<script src="/app.js?v=1794904298571"></script>
<script src="/app.js?v=1794908461497"></script>
</body>
</html>
+47 -21
View File
@@ -7,6 +7,7 @@
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { Script } from 'node:vm';
const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -93,18 +94,18 @@ function consumeTrailingStatementEnd(source, startIdx) {
return idx;
}
function scanImportDeclarationEnd(source, afterImportIdx) {
function scanImportDeclarationEnd(source, afterImportIdx, onImport) {
let idx = afterImportIdx;
let braceDepth = 0;
let sawModuleSpecifierString = false;
while (idx < source.length) {
const ch = source[idx];
if (ch === "'" || ch === '"') {
idx = skipSimpleString(source, idx);
const end = skipSimpleString(source, idx);
if (braceDepth === 0) {
sawModuleSpecifierString = true;
return consumeTrailingStatementEnd(source, idx);
onImport?.(source.slice(idx + 1, end - 1), source.slice(afterImportIdx, idx));
return consumeTrailingStatementEnd(source, end);
}
idx = end;
continue;
}
if (ch === '/' && source[idx + 1] === '/') {
@@ -122,8 +123,6 @@ function scanImportDeclarationEnd(source, afterImportIdx) {
else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
else if (ch === ';' && braceDepth === 0) {
return consumeTrailingStatementEnd(source, idx);
} else if (ch === '\n' && braceDepth === 0 && sawModuleSpecifierString) {
return idx + 1;
}
idx += 1;
}
@@ -183,7 +182,7 @@ function scanExportClauseEnd(source, afterExportIdx) {
* @param {string} source
* @returns {string}
*/
export function stripModuleSyntax(source) {
export function stripModuleSyntax(source, onImport) {
const len = source.length;
let out = '';
let i = 0;
@@ -356,7 +355,7 @@ export function stripModuleSyntax(source) {
const nextCh = source[afterImport];
// Exclude `import.meta` and dynamic `import(...)`
if (nextCh && nextCh !== '.' && nextCh !== '(') {
i = scanImportDeclarationEnd(source, afterImport);
i = scanImportDeclarationEnd(source, afterImport, onImport);
canStartRegex = true;
prevNonWsChar = ';';
continue;
@@ -428,7 +427,24 @@ export function stripModuleSyntax(source) {
return out;
}
export function buildBundle() {
function validateBundleImport(sourcePath, specifier, clause, bundledPaths) {
const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim();
if (binding) {
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
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))) {
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
}
}
if (
!(specifier.startsWith('./') || specifier.startsWith('../')) ||
!bundledPaths.has(resolve(dirname(sourcePath), specifier))
) {
throw new Error(`${sourcePath}: ${specifier} must appear earlier in jsOrder`);
}
}
export function buildBundle(panelDir = PANEL_DIR) {
const cssOrder = [
'src/styles/tokens.css',
'src/styles/base.css',
@@ -443,12 +459,12 @@ export function buildBundle() {
const cssBundle =
cssOrder
.map((rel) => `/* --- ${rel} --- */\n${readFileSync(join(PANEL_DIR, rel), 'utf8').trim()}`)
.map((rel) => `/* --- ${rel} --- */\n${readFileSync(join(panelDir, rel), 'utf8').trim()}`)
.join('\n\n') + '\n';
writeFileSync(join(PANEL_DIR, 'styles.css'), cssBundle, 'utf8');
const jsOrder = [
'shared/settings-normalization.mjs',
'shared/window-bridge-protocol.mjs',
'src/icons/svgRegistry.js',
'src/icons/SvgIcon.js',
'src/core/reactive.js',
@@ -499,24 +515,34 @@ export function buildBundle() {
'src/main.js',
];
const bundledPaths = new Set();
const innerModules = jsOrder
.map((rel) => {
const raw = readFileSync(join(PANEL_DIR, rel), 'utf8');
const stripped = stripModuleSyntax(raw);
const path = resolve(panelDir, rel);
if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`);
const raw = readFileSync(path, 'utf8');
const stripped = stripModuleSyntax(raw, (specifier, clause) =>
validateBundleImport(path, specifier, clause, bundledPaths)
);
bundledPaths.add(path);
return `// --- ${rel} ---\n${stripped.trim()}`;
})
.join('\n\n');
const jsBundle = `(() => {\n'use strict';\n\n${innerModules}\n})();\n`;
writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8');
new Script(jsBundle, { filename: 'app.js' });
const ver = Date.now();
const indexHtmlPath = join(PANEL_DIR, 'index.html');
if (existsSync(indexHtmlPath)) {
const html = readFileSync(indexHtmlPath, 'utf8')
const indexHtmlPath = join(panelDir, 'index.html');
const html = existsSync(indexHtmlPath)
? readFileSync(indexHtmlPath, 'utf8')
.replace(/href="\/styles\.css(?:\?v=[^"]*)?"/, `href="/styles.css?v=${ver}"`)
.replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`);
.replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`)
: null;
writeFileSync(join(panelDir, 'styles.css'), cssBundle, 'utf8');
writeFileSync(join(panelDir, 'app.js'), jsBundle, 'utf8');
if (html !== null) {
writeFileSync(indexHtmlPath, html, 'utf8');
}
@@ -0,0 +1,122 @@
/**
* @fileoverview 前后端共用的偏好设置归一化规则。
*/
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_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',
]);
/**
* 归一化面板挂载方式枚举(`'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';
}
/**
* 归一化每周额度统计模式枚举(兼容历史简写 `'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 项)。
*
* @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'];
}
@@ -0,0 +1,18 @@
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
export const WINDOW_OVERLAY_METHODS = Object.freeze({
ensureAlive: 'ensureAlive',
getDockKind: 'getDockKind',
getMountMode: 'getMountMode',
updateBridge: 'updateBridge',
applyMountMode: 'applyMountMode',
syncHostRoute: 'syncHostRoute',
deliverRpc: 'deliverRpc',
dispose: 'dispose',
});
export function readInjectedWindowBridge() {
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
}
@@ -10,7 +10,6 @@
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
import {
formatMetric,
formatTokens,
formatTokensPrecise,
formatUsd,
@@ -422,21 +421,6 @@ export function computePublicationFit(
};
}
/**
* 计算样本点上的平滑回归拟合值序列(供单元测试与轻量调用直接读取)。
*
* @param {number[]} ys
* @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [bounds]
* @returns {number[]}
*/
export function computeLoessFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) {
const n = Array.isArray(ys) ? ys.length : 0;
if (n === 0) return [];
const xArr =
Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx);
return computePublicationFit(xArr, ys, { minVal, maxVal }).sampleFits;
}
/**
* Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。
*/
@@ -8,6 +8,12 @@
* 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。
*/
import {
WINDOW_BRIDGE_KEY,
WINDOW_OVERLAY_KEY,
WINDOW_OVERLAY_METHODS,
readInjectedWindowBridge,
} from '../../../shared/window-bridge-protocol.mjs';
import { App } from '../../App.js';
import { applyAppearanceToRoot } from '../../core/appearance.js';
import {
@@ -813,7 +819,7 @@ function isImmediatelyBeforeNode(node, refNode) {
function isIdeExtensionChatFrame() {
try {
if (typeof window === 'undefined') return false;
if (window.__AGUsageMonitorBridge?.isIdeChatFrame === true) return true;
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
} catch {
return false;
@@ -824,7 +830,7 @@ function resolveActiveDockTarget(options = undefined) {
const settings = telemetryStore.getState().telemetry?.settings;
const rawMode =
settings?.windowMountMode ??
(typeof window !== 'undefined' ? window.__AGUsageMonitorBridge?.mountMode : undefined);
readInjectedWindowBridge()?.mountMode;
const mountMode =
options?.mountMode ||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
@@ -925,14 +931,14 @@ export function mountWindowOverlay() {
let carryOverMultiPinnedOpen = false;
let carryOverPointer = null;
try {
const prevOv = window.__AGUsageMonitorOverlay;
const prevOv = window[WINDOW_OVERLAY_KEY];
carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null;
carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.());
carryOverPopoverOpen = Boolean(prevOv?.isOpen?.());
carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.());
carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.());
carryOverPointer = prevOv?.getLastPointer?.() || null;
prevOv?.dispose?.();
prevOv?.[WINDOW_OVERLAY_METHODS.dispose]?.();
} catch {
// 忽略旧实例卸载异常
}
@@ -3070,28 +3076,28 @@ export function mountWindowOverlay() {
const handle = {
bundleVersion,
ensureAlive() {
[WINDOW_OVERLAY_METHODS.ensureAlive]() {
if (disposed) return false;
return ensureCapsuleDocked();
},
syncHostRoute() {
[WINDOW_OVERLAY_METHODS.syncHostRoute]() {
if (disposed) return false;
syncHostRouteIfChanged();
return true;
},
updateBridge(nextBridge) {
[WINDOW_OVERLAY_METHODS.updateBridge](nextBridge) {
if (disposed || !nextBridge || typeof nextBridge !== 'object') return false;
const port = Number(nextBridge.port || 0);
const token = String(nextBridge.token || '');
if (!Number.isInteger(port) || port <= 0 || !token) return false;
const cur = window.__AGUsageMonitorBridge || {};
const cur = readInjectedWindowBridge() || {};
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
cur.port = port;
cur.token = token;
if (portChanged) {
cur.transportMode = 'http';
}
window.__AGUsageMonitorBridge = cur;
window[WINDOW_BRIDGE_KEY] = cur;
void fetchTelemetry({ force: false });
return true;
},
@@ -3101,7 +3107,7 @@ export function mountWindowOverlay() {
getLastPointer() {
return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null;
},
deliverRpc(responses) {
[WINDOW_OVERLAY_METHODS.deliverRpc](responses) {
if (disposed) return 0;
return deliverCdpBridgeResponses(responses);
},
@@ -3126,14 +3132,13 @@ export function mountWindowOverlay() {
isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned),
isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned),
getLayoutMode: () => layoutMode,
getDockKind: () => String(capsuleHost.getAttribute('data-dock') || ''),
getMountMode: () => lastAppliedMountMode,
applyMountMode(nextMode) {
[WINDOW_OVERLAY_METHODS.getDockKind]: () => String(capsuleHost.getAttribute('data-dock') || ''),
[WINDOW_OVERLAY_METHODS.getMountMode]: () => lastAppliedMountMode,
[WINDOW_OVERLAY_METHODS.applyMountMode](nextMode) {
if (disposed) return false;
const normalized = normalizeClientWindowMountMode(nextMode, nextMode !== 'sidebar');
if (typeof window !== 'undefined' && window.__AGUsageMonitorBridge) {
window.__AGUsageMonitorBridge.mountMode = normalized;
}
const bridgeConfig = readInjectedWindowBridge();
if (bridgeConfig) bridgeConfig.mountMode = normalized;
const curTel = telemetryStore.getState().telemetry;
if (curTel?.settings) {
telemetryStore.setState({
@@ -3150,7 +3155,7 @@ export function mountWindowOverlay() {
lastAppliedMountMode = normalized;
return ensureCapsuleDocked();
},
dispose() {
[WINDOW_OVERLAY_METHODS.dispose]() {
if (disposed) return;
disposed = true;
clearInterval(watchdogTimer);
@@ -3203,12 +3208,12 @@ export function mountWindowOverlay() {
try {
portalHost.remove();
} catch {}
if (window.__AGUsageMonitorOverlay === handle) {
delete window.__AGUsageMonitorOverlay;
if (window[WINDOW_OVERLAY_KEY] === handle) {
delete window[WINDOW_OVERLAY_KEY];
}
},
};
window.__AGUsageMonitorOverlay = handle;
window[WINDOW_OVERLAY_KEY] = handle;
return handle;
}
+3 -2
View File
@@ -4,6 +4,8 @@
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
*/
import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
const inFlightGets = new Map();
const activeControllers = new Map();
@@ -13,8 +15,7 @@ const activeControllers = new Map();
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
*/
export function getWindowBridgeConfig() {
if (typeof window === 'undefined') return null;
const br = window.__AGUsageMonitorBridge;
const br = readInjectedWindowBridge();
const port = Number(br?.port || 0);
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
return br;
@@ -20,33 +20,10 @@ import {
} from '../core/formatters.js';
import { isEnglishLocale, t } from '../i18n/index.js';
export const CAPSULE_METRIC_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',
]);
import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-normalization.mjs';
export const OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
export { OVERVIEW_METRIC_KEYS };
export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS;
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
+22 -66
View File
@@ -7,6 +7,17 @@ import { createReactiveStore } from '../core/reactive.js';
import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js';
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
import {
DEFAULT_OVERVIEW_METRICS,
DEFAULT_TOPBAR_SLOTS,
OVERVIEW_METRIC_KEYS,
TOPBAR_SLOT_KEYS,
normalizeOverviewMetrics,
normalizeTopbarCapsuleSlots,
normalizeWeeklyLimitMode,
normalizeWindowMountMode,
} from '../../shared/settings-normalization.mjs';
import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -25,7 +36,7 @@ export function extractHostRouteCascadeId() {
if (m && CASCADE_UUID_RE.test(m[1])) {
return m[1];
}
const extBridgeRouteId = String(window.__AGUsageMonitorBridge?.hostRouteCascadeId || '').trim();
const extBridgeRouteId = String(readInjectedWindowBridge()?.[WINDOW_BRIDGE_ROUTE_KEY] || '').trim();
if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) {
return extBridgeRouteId;
}
@@ -107,23 +118,9 @@ let loopActive = false;
let loopIntervalMs = 2000;
let loopTickFn = null;
export const CLIENT_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 CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
export const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
'metrics',
@@ -141,24 +138,9 @@ export const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([
export const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
export const CLIENT_OVERVIEW_METRIC_KEYS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
'session_cost',
'cache_hit',
'session_tokens',
'context_usage',
'quota_tightest',
]);
export const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS;
export const DEFAULT_CLIENT_OVERVIEW_METRICS = Object.freeze([
'tps',
'ttft',
'avg_tps',
'step_cost',
]);
export const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS;
export const CLIENT_STEP_COLUMN_KEYS = Object.freeze([
'step',
@@ -308,12 +290,7 @@ function normalizeClientOrderedList(raw, { allowedKeys, defaultItems, minLen, ma
* @returns {string[]}
*/
export function normalizeClientTopbarSlots(raw) {
return normalizeClientOrderedList(raw, {
allowedKeys: CLIENT_TOPBAR_SLOT_KEYS,
defaultItems: DEFAULT_CLIENT_TOPBAR_SLOTS,
minLen: 1,
maxLen: 5,
});
return normalizeTopbarCapsuleSlots(raw);
}
/**
@@ -353,12 +330,7 @@ export function normalizeClientOverviewModules(raw) {
* @returns {string[]}
*/
export function normalizeClientOverviewMetrics(raw) {
return normalizeClientOrderedList(raw, {
allowedKeys: CLIENT_OVERVIEW_METRIC_KEYS,
defaultItems: DEFAULT_CLIENT_OVERVIEW_METRICS,
minLen: 1,
maxLen: 4,
});
return normalizeOverviewMetrics(raw);
}
/**
@@ -402,12 +374,7 @@ export function normalizeClientOrchestratorIdMode(mode) {
* @returns {'dual'|'composer'|'sidebar'}
*/
export function normalizeClientWindowMountMode(mode, legacyEnableOverlay) {
const m = String(mode ?? '').trim().toLowerCase();
if (m === 'composer' || m === 'input') return 'composer';
if (m === 'sidebar' || m === 'off') return 'sidebar';
if (m === 'dual' || m === 'topbar') return 'dual';
if (legacyEnableOverlay === false) return 'sidebar';
return 'dual';
return normalizeWindowMountMode(mode, legacyEnableOverlay);
}
function isEquivalentTelemetry(prev, next) {
@@ -423,15 +390,6 @@ function isEquivalentTelemetry(prev, next) {
}
return true;
};
const normMount = (mode, legacyEnableOverlay) => {
const m = String(mode ?? '').trim().toLowerCase();
if (m === 'composer' || m === 'input') return 'composer';
if (m === 'sidebar' || m === 'off') return 'sidebar';
if (m === 'dual' || m === 'topbar') return 'dual';
if (legacyEnableOverlay === false) return 'sidebar';
return 'dual';
};
// 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置)
const pAct = prev.activeConversation;
const nAct = next.activeConversation;
@@ -503,8 +461,8 @@ function isEquivalentTelemetry(prev, next) {
if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false;
if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false;
if (
normMount(pSet?.windowMountMode, pSet?.enableWindowOverlay) !==
normMount(nSet?.windowMountMode, nSet?.enableWindowOverlay)
normalizeClientWindowMountMode(pSet?.windowMountMode, pSet?.enableWindowOverlay) !==
normalizeClientWindowMountMode(nSet?.windowMountMode, nSet?.enableWindowOverlay)
) {
return false;
}
@@ -1137,9 +1095,7 @@ export async function saveSettingsPatch(patch) {
safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
const mode = safePatch.weeklyLimitMode;
safePatch.weeklyLimitMode =
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode);
}
if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) {
safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine);
-7
View File
@@ -5,13 +5,6 @@
import { createReactiveStore } from '../core/reactive.js';
import { t } from '../i18n/index.js';
export const VIEW_TABS = Object.freeze([
{ value: 'overview', label: '实时监控', icon: 'pulse' },
{ value: 'consumption', label: '用量统计', icon: 'chart-bar' },
{ value: 'steps', label: '调用明细', icon: 'table' },
{ value: 'settings', label: '偏好设置', icon: 'sliders' },
]);
export function getViewTabs() {
return [
{ value: 'overview', label: t('nav.overview'), icon: 'pulse' },
-34
View File
@@ -744,12 +744,6 @@
min-height: 26px;
}
.topbar-header-right {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}
.btn-ghost-sm {
display: inline-flex;
align-items: center;
@@ -781,34 +775,6 @@
cursor: default;
}
.topbar-slot-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.topbar-slot-row {
position: relative;
display: flex;
align-items: center;
gap: 6px;
padding: 2px 4px 2px 6px;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: transparent;
transition: border-color var(--dur-instant) var(--ease-fast);
}
.topbar-slot-row:focus-within,
.topbar-slot-row:has(.is-open) {
z-index: 30;
border-color: var(--border-strong);
}
.topbar-slot-row .select-menu {
max-height: 216px;
}
.slot-index-badge {
display: inline-flex;
align-items: center;
+12 -10
View File
@@ -52,7 +52,7 @@ export const SettingsView = defineComponent({
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
const accountTab = SHOW_ACCOUNT_TAB ? SettingsAccountTab({ onLayoutChange: refreshScroll }) : null;
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
let showingAccount = false;
@@ -60,25 +60,27 @@ export const SettingsView = defineComponent({
const target =
subTab === 'structure' ||
subTab === 'other' ||
(SHOW_ACCOUNT_TAB && subTab === 'account')
(accountTab && subTab === 'account')
? subTab
: 'general';
subNavSwitch.setValue(target);
patchAttr(generalTab.el, 'hidden', target !== 'general');
patchAttr(structureTab.el, 'hidden', target !== 'structure');
patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure');
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
patchAttr(otherTab.el, 'hidden', target !== 'other');
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
if (accountTab) {
patchAttr(accountTab.el, 'hidden', target !== 'account');
const nextShowingAccount = target === 'account' && activeView === 'settings';
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
showingAccount = nextShowingAccount;
}
refreshScroll();
}
const contentContainer = h(
'div',
{},
SHOW_ACCOUNT_TAB
accountTab
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
: [generalTab.el, structureTab.el, otherTab.el]
);
@@ -105,7 +107,7 @@ export const SettingsView = defineComponent({
if (settings) structureTab.refs.renderSettings(settings);
} else if (settingsSubTab === 'other') {
if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []);
} else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') {
} else if (accountTab && settingsSubTab === 'account') {
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
} else {
if (settings) generalTab.refs.renderSettings(settings);
@@ -145,7 +147,7 @@ export const SettingsView = defineComponent({
});
generalTab.refs.refreshLabels();
structureTab.refs.refreshLabels();
accountTab.refs.refreshLabels();
accountTab?.refs.refreshLabels();
otherTab.refs.refreshLabels();
refreshScroll();
}
@@ -158,7 +160,7 @@ export const SettingsView = defineComponent({
subNavSwitch.destroy();
generalTab.destroy();
structureTab.destroy();
accountTab.destroy();
accountTab?.destroy();
otherTab.destroy();
viewScrollbar.destroy();
});
-34
View File
@@ -1066,12 +1066,6 @@ html[data-standalone="true"] .app-shell {
min-height: 26px;
}
.topbar-header-right {
display: inline-flex;
align-items: center;
gap: var(--space-2);
}
.btn-ghost-sm {
display: inline-flex;
align-items: center;
@@ -1103,34 +1097,6 @@ html[data-standalone="true"] .app-shell {
cursor: default;
}
.topbar-slot-list {
display: flex;
flex-direction: column;
gap: 6px;
}
.topbar-slot-row {
position: relative;
display: flex;
align-items: center;
gap: 6px;
padding: 2px 4px 2px 6px;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: transparent;
transition: border-color var(--dur-instant) var(--ease-fast);
}
.topbar-slot-row:focus-within,
.topbar-slot-row:has(.is-open) {
z-index: 30;
border-color: var(--border-strong);
}
.topbar-slot-row .select-menu {
max-height: 216px;
}
.slot-index-badge {
display: inline-flex;
align-items: center;
+7 -3
View File
@@ -4,7 +4,7 @@ import { pathToFileURL } from 'node:url';
import vm from 'node:vm';
import { randomUUID } from 'node:crypto';
import { isDeepStrictEqual } from 'node:util';
import * as metrics from '../speed-metrics.mjs';
import * as metrics from '../trajectory-metrics.mjs';
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
const REAL_CATALOG_RAW = JSON.parse(
@@ -20,6 +20,8 @@ const BACKEND_MODULE_FILES = [
'../backend/context-windows.mjs',
'../backend/account-oauth.mjs',
'../backend/account-switch.mjs',
'../shared/settings-normalization.mjs',
'../shared/window-bridge-protocol.mjs',
'../backend/settings-schema.mjs',
'../backend/config.mjs',
'../backend/cli-sqlite-reader.mjs',
@@ -69,6 +71,7 @@ export function backendHarness({
execFileImpl=null,
sourceText=null,
clock=null,
timerApi={ setTimeout, clearTimeout },
metricsImplementation=metrics,
}={}) {
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
@@ -76,7 +79,7 @@ export function backendHarness({
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1};
const ctx={
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, setTimeout, clearTimeout, isDeepStrictEqual, randomUUID,
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID,
...(clock ? { Date: class extends Date {
constructor(...args) { super(...(args.length ? args : [clock()])); }
static now() { return clock(); }
@@ -155,6 +158,7 @@ export function backendHarness({
}
},
writeTrajectoryCacheFile:(p,data)=>{
if (state.cacheWriteError) throw state.cacheWriteError;
state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))});
},
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,delimiter:path.delimiter,pathToFileURL,fileURLToPath:()=>mainPath,
@@ -179,6 +183,6 @@ export function backendHarness({
return {ok:true,json:async()=>data};
},
};
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,cacheState,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
return {...ctx.api,state};
}
+101 -4
View File
@@ -666,7 +666,7 @@ test('cached incomplete timing is refreshed once without invalidating completed
...structuredClone(raw.trajectory.steps[0]),
status: 'CORTEX_STEP_STATUS_CLEARED',
};
const { extractModelSteps } = await import('../speed-metrics.mjs');
const { extractModelSteps } = await import('../trajectory-metrics.mjs');
const [completed] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
const [incomplete] = extractModelSteps([{ ...incompleteStep, status: 'CORTEX_STEP_STATUS_GENERATING' }]);
const cacheEntry = (step) => ({
@@ -743,6 +743,39 @@ test('display step revisions omit only matching rows and invalidate on timing ch
assert.equal((await get()).activeConversation.recentSteps[0].tokPerSec, 60);
});
test('telemetry reuses display rows only for a matching revision', async (t) => {
const { fetchTelemetry, telemetryStore } = await import('../src/store/telemetryStore.js');
const previousTelemetry = telemetryStore.getState().telemetry;
t.after(() => telemetryStore.setState({ telemetry: previousTelemetry }));
const recentSteps = [{ stepIndex: 1, tokPerSec: 20 }];
const agentSteps = [{ stepIndex: 2, tokPerSec: 40 }];
let response = {
stepRevision: 'test-revision',
activeConversation: { recentSteps, agents: [{ recentSteps: agentSteps }] },
};
const revisions = [];
t.mock.method(globalThis, 'fetch', async (url) => {
revisions.push(new URL(url, 'http://localhost').searchParams.get('stepRevision'));
return { ok: true, json: async () => structuredClone(response) };
});
assert.equal((await fetchTelemetry()).stepRevision, 'test-revision');
response = {
stepsUnchanged: true,
stepRevision: 'test-revision',
activeConversation: { agents: [{}] },
};
const refreshed = await fetchTelemetry();
assert.equal(revisions[1], 'test-revision');
assert.deepEqual(refreshed.activeConversation.recentSteps, recentSteps);
assert.deepEqual(refreshed.activeConversation.agents[0].recentSteps, agentSteps);
const telemetryBeforeMismatch = telemetryStore.getState().telemetry;
response.stepRevision = 'unknown-revision';
assert.equal(await fetchTelemetry(), null);
assert.equal(telemetryStore.getState().telemetry, telemetryBeforeMismatch);
});
test('simultaneous ranges share the trajectory scan while keeping their own totals', async () => {
const h = backendHarness({
trajectories: { live: raw },
@@ -759,7 +792,7 @@ test('simultaneous ranges share the trajectory scan while keeping their own tota
});
test('cached usage follows rolling boundaries and reprices unchanged steps', async () => {
const { extractModelSteps } = await import('../speed-metrics.mjs');
const { extractModelSteps } = await import('../trajectory-metrics.mjs');
const [step] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
const modelKey = 'test-metered-model';
let now = Date.parse('2026-03-08T07:00:00Z');
@@ -806,7 +839,6 @@ test('cached usage follows rolling boundaries and reprices unchanged steps', asy
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
const {
computeLinearFit,
computeLoessFit,
computePublicationFit,
getStepModelGroupKey,
toChronologicalSteps,
@@ -840,7 +872,11 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd
// Warmup cache curve stays clamped within [0, 100]
const cacheSeries = [0, 90, 92, 93, 94, 95, 95];
const loessCache = computeLoessFit(cacheSeries, { minVal: 0, maxVal: 100 });
const loessCache = computePublicationFit(
cacheSeries.map((_, index) => index),
cacheSeries,
{ minVal: 0, maxVal: 100 }
).sampleFits;
assert.equal(loessCache.length, cacheSeries.length);
assert.ok(
loessCache.every((v) => v >= 0 && v <= 100),
@@ -956,6 +992,67 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd
assert.equal(aggMb.length, 2);
});
test('saving preferences sends the same legacy values normalized by the backend', async (t) => {
const { saveSettingsPatch, stopAsyncTelemetryLoop, telemetryStore } =
await import('../src/store/telemetryStore.js');
const h = backendHarness({ settings: { themeAccent: 'blue' } });
let savedSettings = JSON.parse(JSON.stringify(h.loadSettings()));
const previousTelemetry = telemetryStore.getState().telemetry;
t.after(() => {
stopAsyncTelemetryLoop();
telemetryStore.setState({ telemetry: previousTelemetry });
});
telemetryStore.setState({ telemetry: { settings: savedSettings } });
const patches = [];
let failSave = false;
t.mock.method(globalThis, 'fetch', async (path, options) => {
if (options.method === 'POST') {
assert.equal(path, '/api/settings');
const patch = JSON.parse(options.body);
patches.push(patch);
for (const [key, value] of Object.entries(patch)) {
assert.deepEqual(telemetryStore.getState().telemetry.settings[key], value);
}
if (failSave) {
return { ok: false, json: async () => ({ error: 'Failed to persist settings' }) };
}
const result = h.executeSettingsAction(patch);
savedSettings = JSON.parse(result.body);
return { ok: result.ok, json: async () => savedSettings };
}
assert.match(path, /^\/api\/telemetry\?/);
return { ok: true, json: async () => ({ settings: savedSettings }) };
});
await saveSettingsPatch({
windowMountMode: 'sidebar_only',
topbarCapsuleSlots: ['step_cost', 'cost', 'none'],
overviewMetrics: ['cost', 'tps'],
weeklyLimitMode: 'tokens',
});
assert.deepEqual(patches[0], {
windowMountMode: 'sidebar',
enableWindowOverlay: false,
topbarCapsuleSlots: ['cost'],
overviewMetrics: ['step_cost', 'tps'],
weeklyLimitMode: 'custom_tokens',
});
assert.deepEqual(telemetryStore.getState().telemetry.settings, savedSettings);
assert.equal(savedSettings.themeAccent, 'blue');
await saveSettingsPatch({ topbarCapsuleSlots: [], weeklyLimitMode: 'cost' });
assert.deepEqual(patches[1], {
topbarCapsuleSlots: ['context'],
weeklyLimitMode: 'custom_cost',
});
const telemetryBeforeFailure = telemetryStore.getState().telemetry;
failSave = true;
await assert.rejects(saveSettingsPatch({ windowMountMode: 'composer' }), /Failed to persist/);
assert.equal(telemetryStore.getState().telemetry, telemetryBeforeFailure);
});
test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => {
// 1. Default schema matches pre-refactor out-of-box UI 100%
const hDefault = backendHarness({});
@@ -1,20 +1,22 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import vm from 'node:vm';
import { backendHarness } from './backend-harness.mjs';
import {
extractContextBreakdown,
extractModelSteps,
normalizeCachedStep,
} from '../speed-metrics.mjs';
} from '../trajectory-metrics.mjs';
import {
formatCountdown,
formatUsd,
speedReasonText,
} from '../src/core/formatters.js';
import { createReactiveStore } from '../src/core/reactive.js';
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
import { buildBundle, stripModuleSyntax } from '../scripts/build-bundle.mjs';
const nowMs = Date.now();
const nowIso = new Date(nowMs - 5_000).toISOString();
@@ -425,6 +427,31 @@ test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax
assert.ok(appBundle.trimEnd().endsWith('})();'));
});
test('bundle validation rejects incompatible imports and duplicate bindings before touching output', (t) => {
const tempDir = fs.mkdtempSync(fileURLToPath(new URL('./.bundle-test-', import.meta.url)));
t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
for (const dir of ['src', 'shared']) {
fs.cpSync(new URL(`../${dir}/`, import.meta.url), join(tempDir, dir), { recursive: true });
}
const outputs = ['app.js', 'styles.css', 'index.html'];
for (const file of outputs) fs.writeFileSync(join(tempDir, file), file);
const iconSource = join(tempDir, 'src', 'icons', 'svgRegistry.js');
const original = fs.readFileSync(iconSource, 'utf8');
for (const [prefix, error] of [
["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 './missing.js';", /svgRegistry\.js.*missing\.js.*earlier in jsOrder/],
['const SVG_NS = "duplicate";', /Identifier 'SVG_NS' has already been declared/],
]) {
fs.writeFileSync(iconSource, `${prefix}\n${original}`);
assert.throws(() => buildBundle(tempDir), error);
for (const file of outputs) {
assert.equal(fs.readFileSync(join(tempDir, file), 'utf8'), file);
}
}
});
test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => {
const convId = '4432b724-3e1e-4421-a375-c6855a7b7b37';
+3 -2
View File
@@ -2,7 +2,8 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs';
import { normalizeClientWindowMountMode } from '../src/store/telemetryStore.js';
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs';
import {
formatUsd,
mergeModelsByDisplayName,
@@ -195,7 +196,7 @@ test('custom cost budget cannot claim a complete remaining percentage when price
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 = {}; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx);
const ctx = { normalizeClientWindowMountMode }; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx);
const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}};
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);
+2 -1
View File
@@ -2,6 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import vm from 'node:vm';
import { normalizeClientWindowMountMode } from '../src/store/telemetryStore.js';
import { backendHarness } from './backend-harness.mjs';
const FLASH = 'MODEL_PLACEHOLDER_M318';
@@ -290,7 +291,7 @@ test('telemetryStore isEquivalentTelemetry detects quota changes in non-active p
source.indexOf('function isEquivalentTelemetry'),
source.indexOf('export async function fetchTelemetry')
);
const ctx = {};
const ctx = { normalizeClientWindowMountMode };
vm.runInNewContext(fn + '\nglobalThis.compare=isEquivalentTelemetry;', ctx);
const a = {
+1 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs';
import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../trajectory-metrics.mjs';
function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000,
thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) {
@@ -653,12 +653,26 @@ test('Hybrid SQLite+WAL mode skips trajectory RPCs for local DBs, falls back to
test('persistTrajectoryCacheIfNeeded throttles RUNNING disk writes to 30s and flushes immediately on IDLE or cache rebuild', () => {
let now = 1_000_000;
const h = backendHarness({ clock: () => now });
const scheduled = new Map();
const h = backendHarness({
cache: { live: { title: 'Cached session', steps: [] } },
clock: () => now,
timerApi: {
setTimeout(_callback, delay) {
const id = Symbol();
scheduled.set(id, delay);
return id;
},
clearTimeout(id) {
scheduled.delete(id);
},
},
});
// 1st save (lastSavedAtMs === 0) flushes immediately even while running
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
assert.equal(h.state.saves.length, 1);
assert.equal(h.cacheState.needsSave, false);
assert.equal(h.hasPendingTrajectoryCacheSave(), false);
// Subsequent saves within 30s window while RUNNING are throttled in memory
now += 2_000;
@@ -666,22 +680,31 @@ test('persistTrajectoryCacheIfNeeded throttles RUNNING disk writes to 30s and fl
now += 2_000;
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
assert.equal(h.state.saves.length, 1, '2s polling during RUNNING must not rewrite disk every tick');
assert.equal(h.cacheState.needsSave, true);
assert.ok(h.cacheState.flushTimer !== null);
assert.equal(h.hasPendingTrajectoryCacheSave(), true);
assert.deepEqual([...scheduled.values()], [28_000]);
// Transitioning to IDLE flushes immediately and clears pending timer
now += 2_000;
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: false, allowThrottleInTest: true });
assert.equal(h.state.saves.length, 2, 'transition to IDLE flushes immediately');
assert.equal(h.cacheState.needsSave, false);
assert.equal(h.cacheState.flushTimer, null);
assert.equal(h.hasPendingTrajectoryCacheSave(), false);
assert.equal(scheduled.size, 0);
// Re-arming throttle then calling executeRebuildCacheAction cancels timer cleanly
now += 2_000;
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
assert.ok(h.cacheState.flushTimer !== null);
assert.equal(scheduled.size, 1);
h.state.cacheWriteError = new Error('Disk unavailable');
assert.equal(h.executeRebuildCacheAction().status, 500);
assert.equal(h.getCachedTrajectory('live').title, 'Cached session');
assert.equal(h.hasPendingTrajectoryCacheSave(), true);
assert.equal(scheduled.size, 1);
h.state.cacheWriteError = null;
const rebuildRes = h.executeRebuildCacheAction();
assert.equal(rebuildRes.ok, true);
assert.equal(h.cacheState.flushTimer, null);
assert.equal(h.cacheState.needsSave, false);
assert.equal(scheduled.size, 0);
assert.equal(h.hasPendingTrajectoryCacheSave(), false);
assert.equal(h.listCachedTrajectoryEntries().length, 0);
assert.deepEqual(h.state.saves.at(-1).data, {});
});
+13 -4
View File
@@ -330,11 +330,12 @@ test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on vers
const msg = JSON.parse(raw);
if (msg.method === 'Runtime.evaluate') {
const expr = msg.params.expression;
if (expr.includes('__AGUsageMonitorBridge =')) {
const ctx = windowContexts.get(this.targetId);
const previousBridge = ctx.__AGUsageMonitorBridge;
const value = vm.runInContext(expr, ctx);
if (ctx.__AGUsageMonitorBridge && ctx.__AGUsageMonitorBridge !== previousBridge) {
injectEvalCount += 1;
}
const ctx = windowContexts.get(this.targetId);
const value = vm.runInContext(expr, ctx);
Promise.resolve(value).then((result) =>
this._emit('message', {
data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }),
@@ -734,6 +735,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
let liveSubagentPollActive = false;
const fetchedUrls = [];
const fetchedHeaders = [];
const createdForms = [];
const docListeners = new Map();
const winListeners = new Map();
@@ -743,7 +745,11 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
hidden: false,
documentElement: docRoot,
body,
createElement: (tag) => new MockNode(tag),
createElement: (tag) => {
const node = new MockNode(tag);
if (tag === 'form') createdForms.push(node);
return node;
},
createElementNS: (_ns, tag) => new MockNode(tag),
createTextNode: (txt) => {
const t = new MockNode('#text');
@@ -2702,6 +2708,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
'Hover legend updates strictly in-place without DOM node replacement or appendChild'
);
assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), false);
assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), false);
// Verify in-place bridge port rotation preserves exact DOM host nodes without remount
fetchShouldFail = false;
assert.equal(ov.updateBridge({ port: 51234, token: 'rotated-token-456' }), true);