mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): modularize 3-tab preferences, add model context windows, and optimize telemetry
- Refactor Preferences into decoupled General, Structure, and Other tabs with unified settings schema, factory reset, and trajectory cache rebuild endpoints - Extract standalone widget, metric, and step-table column registries to customize topbar/composer slots, hover popup modules, live overview layout, and step detail columns - Add bilingual zh-CN/en-US i18n dictionaries, theme accent presets, and font scale controls across Shadow DOM overlay and sidebar views - Support per-model host-advertised context window rules across App and IDE transports - Preserve CLEARED step generation timings, memoize per-poll model resolution, optimize LOESS sorted-x fitting, and update bilingual READMEs and test suites
This commit is contained in:
@@ -11,19 +11,27 @@ import { join } from 'node:path';
|
||||
import {
|
||||
HERE,
|
||||
SETTINGS_FILE,
|
||||
clearRuntimeCaches,
|
||||
cloudSyncState,
|
||||
computeRuntimeCodeVersion,
|
||||
createDefaultSettingsObject,
|
||||
isPlainObject,
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeFullSettings,
|
||||
normalizePluginUpdateMode,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
import {
|
||||
getContextWindowModels,
|
||||
getContextWindowGroups,
|
||||
isContextWindowSettingId,
|
||||
isContextWindowOption,
|
||||
resolveContextWindowOption,
|
||||
} from './context-windows.mjs';
|
||||
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||
import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
|
||||
import {
|
||||
performPluginUpdate,
|
||||
scheduleSidecarRestart,
|
||||
@@ -32,6 +40,7 @@ import {
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||
import {
|
||||
notifyModelContextWindowsChanged,
|
||||
notifyWindowOverlaySetting,
|
||||
startDefaultWindowBridge,
|
||||
} from './window-bridge.mjs';
|
||||
@@ -172,7 +181,10 @@ export function executeSettingsAction(data) {
|
||||
: 'dual'
|
||||
: 'sidebar'
|
||||
: normalizeWindowMountMode(current.windowMountMode, current.enableWindowOverlay);
|
||||
const updated = {
|
||||
const updated = normalizeFullSettings({
|
||||
...current,
|
||||
...payload,
|
||||
modelContextWindows: current.modelContextWindows,
|
||||
weeklyTokenBudget: sanitizePositiveSettingNumber(
|
||||
payload.weeklyTokenBudget ?? payload.weeklyTokenLimit,
|
||||
current.weeklyTokenBudget
|
||||
@@ -181,31 +193,9 @@ export function executeSettingsAction(data) {
|
||||
payload.weeklyCostBudget,
|
||||
current.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode:
|
||||
payload.weeklyLimitMode !== undefined
|
||||
? normalizeWeeklyLimitMode(payload.weeklyLimitMode)
|
||||
: current.weeklyLimitMode,
|
||||
showUpstreamModel:
|
||||
typeof payload.showUpstreamModel === 'boolean'
|
||||
? payload.showUpstreamModel
|
||||
: Boolean(current.showUpstreamModel),
|
||||
orchestratorIdMode:
|
||||
payload.orchestratorIdMode !== undefined
|
||||
? normalizeOrchestratorIdMode(payload.orchestratorIdMode)
|
||||
: normalizeOrchestratorIdMode(current.orchestratorIdMode),
|
||||
pluginUpdateMode: nextPluginUpdateMode,
|
||||
autoUpdatePlugin: nextPluginUpdateMode === 'auto',
|
||||
windowMountMode: nextWindowMountMode,
|
||||
enableWindowOverlay: nextWindowMountMode !== 'sidebar',
|
||||
showTopbarMultiSession:
|
||||
typeof payload.showTopbarMultiSession === 'boolean'
|
||||
? payload.showTopbarMultiSession
|
||||
: current.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots:
|
||||
payload.topbarCapsuleSlots !== undefined
|
||||
? normalizeTopbarCapsuleSlots(payload.topbarCapsuleSlots)
|
||||
: normalizeTopbarCapsuleSlots(current.topbarCapsuleSlots),
|
||||
};
|
||||
});
|
||||
if (!saveJson(SETTINGS_FILE, updated)) {
|
||||
return {
|
||||
ok: false,
|
||||
@@ -235,6 +225,98 @@ export function executeSettingsAction(data) {
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeModelContextWindowAction(data) {
|
||||
const { modelId, option } = data || {};
|
||||
const respond = (status, payload) => ({
|
||||
status,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!isContextWindowSettingId(modelId) || (option !== null && !isContextWindowOption(option))) {
|
||||
return respond(400, { error: 'Invalid model context window' });
|
||||
}
|
||||
let group;
|
||||
try {
|
||||
const [{ userStatus }, catalog] = await Promise.all([callLsRpc('GetUserStatus'), getContextModelCatalog()]);
|
||||
const models = getContextWindowModels(userStatus?.cascadeModelConfigData?.clientModelConfigs, catalog);
|
||||
group = getContextWindowGroups(models).find(({ id }) => id === modelId);
|
||||
} catch {
|
||||
if (option !== null || modelId.startsWith('model:')) {
|
||||
return respond(503, { error: 'Unable to verify the host model configuration' });
|
||||
}
|
||||
}
|
||||
if (option !== null && (!group || resolveContextWindowOption(group, option) === null)) {
|
||||
return respond(400, { error: 'This context window is not available for the selected model' });
|
||||
}
|
||||
const current = loadSettings();
|
||||
for (const id of group?.members || []) delete current.modelContextWindows[id];
|
||||
if (option === null) {
|
||||
delete current.modelContextWindows[modelId];
|
||||
} else {
|
||||
current.modelContextWindows[modelId] = option;
|
||||
}
|
||||
if (!saveJson(SETTINGS_FILE, current)) {
|
||||
return respond(500, { error: 'Failed to persist model context window' });
|
||||
}
|
||||
void notifyModelContextWindowsChanged();
|
||||
return respond(200, { modelContextWindows: current.modelContextWindows });
|
||||
}
|
||||
|
||||
export function executeResetSettingsAction() {
|
||||
const current = loadSettings();
|
||||
const updated = createDefaultSettingsObject();
|
||||
if (!saveJson(SETTINGS_FILE, updated)) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to reset settings' }),
|
||||
};
|
||||
}
|
||||
const prevMountMode = normalizeWindowMountMode(
|
||||
current.windowMountMode,
|
||||
current.enableWindowOverlay
|
||||
);
|
||||
if (
|
||||
updated.enableWindowOverlay !== (current.enableWindowOverlay !== false) ||
|
||||
updated.windowMountMode !== prevMountMode
|
||||
) {
|
||||
void notifyWindowOverlaySetting(updated.enableWindowOverlay);
|
||||
} else if (Object.keys(current.modelContextWindows).length) {
|
||||
void notifyModelContextWindowsChanged();
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
updated,
|
||||
body: JSON.stringify(updated),
|
||||
};
|
||||
}
|
||||
|
||||
export function executeRebuildCacheAction() {
|
||||
const ok = clearRuntimeCaches();
|
||||
if (!ok) {
|
||||
return {
|
||||
ok: false,
|
||||
status: 500,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
headers: { 'Cache-Control': 'no-store' },
|
||||
body: JSON.stringify({ ok: true, clearedAt: Date.now() }),
|
||||
};
|
||||
}
|
||||
|
||||
export async function executeCloudSyncAction() {
|
||||
const cloudStatus = await syncCloudCatalog({ force: true });
|
||||
return {
|
||||
@@ -262,6 +344,15 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
|
||||
if (pathname === '/api/settings' && method === 'POST') {
|
||||
return executeSettingsAction(data);
|
||||
}
|
||||
if (pathname === '/api/context-window' && method === 'POST') {
|
||||
return executeModelContextWindowAction(data);
|
||||
}
|
||||
if (pathname === '/api/settings/reset' && method === 'POST') {
|
||||
return executeResetSettingsAction();
|
||||
}
|
||||
if (pathname === '/api/cache/rebuild' && method === 'POST') {
|
||||
return executeRebuildCacheAction();
|
||||
}
|
||||
if (pathname === '/api/cloud-sync' && method === 'POST') {
|
||||
return executeCloudSyncAction();
|
||||
}
|
||||
|
||||
@@ -13,6 +13,75 @@ import { homedir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
|
||||
import {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_SETTINGS_SCHEMA,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
ORCHESTRATOR_ID_MODES,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
PLUGIN_UPDATE_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
WINDOW_MOUNT_MODES,
|
||||
createDefaultSettingsObject,
|
||||
normalizeFontScale,
|
||||
normalizeFullSettings,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizeStepTableColumns,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
} from './settings-schema.mjs';
|
||||
|
||||
export {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_SETTINGS_SCHEMA,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
ORCHESTRATOR_ID_MODES,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
PLUGIN_UPDATE_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
TOPBAR_SLOT_KEYS,
|
||||
WINDOW_MOUNT_MODES,
|
||||
createDefaultSettingsObject,
|
||||
normalizeFontScale,
|
||||
normalizeFullSettings,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizeStepTableColumns,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
} from './settings-schema.mjs';
|
||||
|
||||
/**
|
||||
* 自适应解析 `sidecars/panel` 目录路径:
|
||||
@@ -115,107 +184,6 @@ export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
||||
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
||||
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||
|
||||
/**
|
||||
* 顶栏右侧精简胶囊三槽位允许配置的指标枚举与默认顺序。
|
||||
*/
|
||||
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'context',
|
||||
'tps',
|
||||
'ttft',
|
||||
'cost',
|
||||
'quota_auto',
|
||||
'gemini_5h',
|
||||
'gemini_weekly',
|
||||
'claude_5h',
|
||||
'claude_weekly',
|
||||
'none',
|
||||
]);
|
||||
|
||||
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
|
||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||
|
||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||
|
||||
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
||||
|
||||
/**
|
||||
* 归一化面板挂载方式枚举(`'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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'compact'|'full'}
|
||||
*/
|
||||
export function normalizeOrchestratorIdMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'full' ? 'full' : 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyAutoUpdate]
|
||||
* @returns {'off'|'manual'|'auto'}
|
||||
*/
|
||||
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
||||
if (legacyAutoUpdate === true) return 'auto';
|
||||
return 'manual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化顶栏三槽位配置数组,兜底非法枚举值并保证至少保留一个可见槽位。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {[string, string, string]}
|
||||
*/
|
||||
export function normalizeTopbarCapsuleSlots(raw) {
|
||||
const arr = Array.isArray(raw) ? raw : [];
|
||||
const slots = [0, 1, 2].map((idx) => {
|
||||
const val = String(arr[idx] ?? '').trim();
|
||||
return TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_TOPBAR_SLOTS[idx];
|
||||
});
|
||||
if (slots.every((s) => s === 'none')) {
|
||||
slots[0] = 'context';
|
||||
}
|
||||
return /** @type {[string, string, string]} */ (slots);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户可配置项的默认值。
|
||||
*/
|
||||
const DEFAULT_SETTINGS = {
|
||||
weeklyTokenBudget: 150000000, // 自定义每周 Token 预算默认值 (150M,保留底层兼容)
|
||||
weeklyCostBudget: 100, // 自定义每周美元费用预算默认值 ($100,保留底层兼容)
|
||||
weeklyLimitMode: 'official', // 'official' | 'custom_tokens' | 'custom_cost'
|
||||
showUpstreamModel: false, // 是否显示上游真实 responseModel 名称
|
||||
orchestratorIdMode: 'compact', // 'compact' | 'full'(Orchestrator 系列显示精简 ID 或完整 ID)
|
||||
pluginUpdateMode: 'manual', // 'off' | 'manual' | 'auto'(默认仅提示新版本,手动更新)
|
||||
autoUpdatePlugin: false, // 派生自 pluginUpdateMode === 'auto',保留底层兼容
|
||||
windowMountMode: 'dual', // 'dual' | 'composer' | 'sidebar'(顶部栏 / 输入框 Auto 左侧 / 仅侧边栏)
|
||||
enableWindowOverlay: true, // 派生自 windowMountMode !== 'sidebar',控制主窗口 CDP 注入启停
|
||||
showTopbarMultiSession: true, // 是否在顶栏左侧显示实时运行会话入口
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], // 顶栏右侧胶囊三槽位指标与顺序
|
||||
};
|
||||
|
||||
/** 历史轨迹缓存 Schema 版本号,升级时触发旧缓存字段迁移校验。 */
|
||||
export const CACHE_SCHEMA_VERSION = 'v10-model-identity';
|
||||
|
||||
@@ -266,59 +234,10 @@ export function saveJson(filePath, data) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化每周额度统计模式枚举(兼容历史简写 `'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';
|
||||
}
|
||||
|
||||
function sanitizeSettingNumber(val, fallback) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段并兜底非法数值。
|
||||
*
|
||||
* @returns {typeof DEFAULT_SETTINGS}
|
||||
* 读取用户设置并通过统一 Schema 归一化合并默认值,自动迁移旧版字段。
|
||||
*/
|
||||
export function loadSettings() {
|
||||
const raw = loadJson(SETTINGS_FILE, {});
|
||||
const safeRaw = isPlainObject(raw) ? raw : {};
|
||||
const merged = { ...DEFAULT_SETTINGS, ...safeRaw };
|
||||
const pluginUpdateMode = normalizePluginUpdateMode(
|
||||
safeRaw.pluginUpdateMode,
|
||||
safeRaw.autoUpdatePlugin
|
||||
);
|
||||
const windowMountMode = normalizeWindowMountMode(
|
||||
safeRaw.windowMountMode,
|
||||
safeRaw.enableWindowOverlay
|
||||
);
|
||||
return {
|
||||
weeklyTokenBudget: sanitizeSettingNumber(
|
||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit ?? merged.weeklyTokenBudget,
|
||||
DEFAULT_SETTINGS.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: sanitizeSettingNumber(
|
||||
merged.weeklyCostBudget,
|
||||
DEFAULT_SETTINGS.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(merged.weeklyLimitMode),
|
||||
showUpstreamModel: merged.showUpstreamModel === true,
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(merged.orchestratorIdMode),
|
||||
pluginUpdateMode,
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
windowMountMode,
|
||||
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||
showTopbarMultiSession: merged.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||
};
|
||||
return normalizeFullSettings(loadJson(SETTINGS_FILE, {}));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -474,3 +393,23 @@ export const pluginUpdateState = {
|
||||
lastError: null,
|
||||
inFlight: null,
|
||||
};
|
||||
|
||||
/**
|
||||
* 清空内存态轨迹缓存、外部深层统计 Memo 与配额摘要短期缓存,并将磁盘缓存重置为空对象。
|
||||
*
|
||||
* @returns {boolean} 是否成功写回空白缓存文件
|
||||
*/
|
||||
export function clearRuntimeCaches() {
|
||||
for (const key of Object.keys(trajectoryCache)) {
|
||||
delete trajectoryCache[key];
|
||||
}
|
||||
cacheState.needsSave = false;
|
||||
externalDeepStatsMemo.sig = '';
|
||||
externalDeepStatsMemo.convos.clear();
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.lastAttemptTs = 0;
|
||||
quotaSummaryCache.accountName = '';
|
||||
quotaSummaryCache.data = null;
|
||||
quotaSummaryCache.error = null;
|
||||
return saveJson(CACHE_FILE, {});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
||||
|
||||
export function isContextWindowModelId(value) {
|
||||
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
||||
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
||||
}
|
||||
|
||||
export function isContextWindowSettingId(value) {
|
||||
return isContextWindowModelId(value) || (typeof value === 'string' && /^model:[a-z0-9][a-z0-9._-]{0,119}$/.test(value));
|
||||
}
|
||||
|
||||
export function isContextWindowOption(value) {
|
||||
return typeof value === 'string' && value.length > 0 && value.length <= 80 &&
|
||||
value.trim() === value && value.toLowerCase() !== 'default' && !/[\x00-\x1f\x7f]/.test(value);
|
||||
}
|
||||
|
||||
export function getContextWindowModels(clientConfigs, catalog) {
|
||||
const capacities = new Map();
|
||||
const upstreamIds = new Map();
|
||||
const thinkingLevels = new Set();
|
||||
for (const [key, info] of Object.entries(catalog || {})) {
|
||||
const { model, maxTokens, maxOutputTokens } = info || {};
|
||||
if (isContextWindowModelId(model)) upstreamIds.set(model, upstreamIds.has(model) ? '' : key);
|
||||
if (Number.isInteger(info?.thinkingLevel) && info.thinkingLevel > 0) thinkingLevels.add(model);
|
||||
if (!Number.isSafeInteger(maxTokens) || !Number.isSafeInteger(maxOutputTokens) ||
|
||||
maxOutputTokens <= 0 || maxTokens <= maxOutputTokens) continue;
|
||||
// 宿主校验压缩阈值时会从模型总窗口中扣除输出预算。
|
||||
const capacity = maxTokens - maxOutputTokens;
|
||||
capacities.set(model, Math.min(capacity, capacities.get(model) ?? capacity));
|
||||
}
|
||||
const models = new Map();
|
||||
for (const config of Array.isArray(clientConfigs) ? clientConfigs : []) {
|
||||
const id = config?.modelOrAlias?.model;
|
||||
if (!isContextWindowModelId(id) || config.disabled || models.has(id)) continue;
|
||||
const options = Array.isArray(config.contextWindowOptions) ? config.contextWindowOptions : [];
|
||||
const byName = new Map();
|
||||
for (const option of options) {
|
||||
if (!isContextWindowOption(option?.name) || byName.has(option.name)) continue;
|
||||
byName.set(option.name, {
|
||||
name: option.name,
|
||||
expensive: option.expensive === true,
|
||||
});
|
||||
}
|
||||
const reportedId = typeof config.modelId === 'string' ? config.modelId.trim() : '';
|
||||
const upstreamId = (reportedId && reportedId !== id ? reportedId : upstreamIds.get(id) || '').toLowerCase();
|
||||
const label = config.label || id;
|
||||
const effort = upstreamId.match(/-(low|medium|high|xhigh|extra-high|extra|max)$/);
|
||||
const labelEffort = typeof label === 'string' && label.match(/\s+\((low|medium|high|xhigh|extra[ -]high|extra|max)\)$/i);
|
||||
const isEffortVariant = effort && (thinkingLevels.has(id) ||
|
||||
labelEffort && effort[1].replace('-', '') === labelEffort[1].toLowerCase().replace(/[ -]/g, ''));
|
||||
const baseId = isEffortVariant ? upstreamId.slice(0, effort.index) : upstreamId;
|
||||
const groupId = `model:${baseId}`;
|
||||
models.set(id, {
|
||||
id,
|
||||
groupId: isContextWindowSettingId(groupId) ? groupId : id,
|
||||
label: isEffortVariant ? (labelEffort ? label.slice(0, labelEffort.index) : baseId) : label,
|
||||
capacity: capacities.get(id) || 0,
|
||||
options: [...byName.values()],
|
||||
});
|
||||
}
|
||||
return [...models.values()];
|
||||
}
|
||||
|
||||
export function getContextWindowGroups(models) {
|
||||
const byId = new Map();
|
||||
for (const model of models) {
|
||||
const group = byId.get(model.groupId);
|
||||
if (group) group.members.push(model);
|
||||
else byId.set(model.groupId, { id: model.groupId, label: model.label, members: [model] });
|
||||
}
|
||||
return [...byId.values()].map(({ id, label, members }) => {
|
||||
const options = members[0].options.filter(({ name }) =>
|
||||
members.every((member) => member.options.some((option) => option.name === name))
|
||||
).map(({ name }) => ({
|
||||
name,
|
||||
expensive: members.some(({ options }) => options.some((option) => option.name === name && option.expensive)),
|
||||
}));
|
||||
const capacity = Math.min(...members.map((member) => member.capacity));
|
||||
if (!options.length && capacity) {
|
||||
for (const tokens of new Set([128000, 256000, 512000, 768000, 900000, capacity])) {
|
||||
if (tokens <= capacity && !options.some(({ name }) => name === String(tokens))) {
|
||||
options.push({ name: String(tokens), tokens });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { id, label, members: members.map((member) => member.id), capacity, options };
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveContextWindowOption(model, value) {
|
||||
if (!value) return null;
|
||||
if (model.options.some(({ name, tokens }) => name === value && !tokens)) return value;
|
||||
const tokens = Number(value);
|
||||
return Number.isSafeInteger(tokens) && String(tokens) === value && tokens > 0 && tokens <= model.capacity ? tokens : null;
|
||||
}
|
||||
|
||||
export function resolveContextWindowRules(models, preferences) {
|
||||
const byId = new Map(models.map((model) => [model.id, model]));
|
||||
const rules = {};
|
||||
for (const group of getContextWindowGroups(models)) {
|
||||
const saved = preferences[group.id];
|
||||
// 不同推理档的旧设置有冲突时,保留各自的值,直到用户选定统一上限。
|
||||
const previous = new Set(group.members.map((id) => preferences[id]).filter(Boolean));
|
||||
const shared = saved || (previous.size === 1 ? previous.values().next().value : null);
|
||||
if (resolveContextWindowOption(group, shared) !== null) {
|
||||
for (const id of group.members) rules[id] = resolveContextWindowOption(byId.get(id), shared);
|
||||
} else if (!saved) {
|
||||
for (const id of group.members) {
|
||||
const option = resolveContextWindowOption(byId.get(id), preferences[id]);
|
||||
if (option !== null) rules[id] = option;
|
||||
}
|
||||
}
|
||||
}
|
||||
return rules;
|
||||
}
|
||||
|
||||
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
||||
export async function syncHostContextWindows(rules, bootId) {
|
||||
const key = '__AGUsageMonitorContextWindows';
|
||||
let state = window[key];
|
||||
const appConfig = window.__APP_CONFIG__;
|
||||
const csrfToken = appConfig?.csrfToken;
|
||||
if (!Object.keys(rules).length || !csrfToken || appConfig.isRemoteControl) {
|
||||
state?.dispose();
|
||||
return;
|
||||
}
|
||||
if (state && (state.bootId !== bootId || !state.isAttached?.())) {
|
||||
state.dispose();
|
||||
state = null;
|
||||
}
|
||||
if (!state) {
|
||||
const servicePath = '/exa.language_server_pb.LanguageServerService/';
|
||||
const sendPath = servicePath + 'SendUserCascadeMessage';
|
||||
const nativeFetch = window.fetch;
|
||||
const wsProto = window.WebSocket?.prototype;
|
||||
const nativeSend = wsProto?.send;
|
||||
const encoder = new TextEncoder();
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
function updatePayload(payload) {
|
||||
const config = payload?.cascadeConfig;
|
||||
const model = config?.plannerConfig?.planModel;
|
||||
if (typeof model !== 'string' || !Object.hasOwn(state.rules, model)) return false;
|
||||
const checkpoint = config.checkpointConfig ??= {};
|
||||
if (typeof checkpoint !== 'object' || Array.isArray(checkpoint)) return false;
|
||||
const option = state.rules[model];
|
||||
if (typeof option === 'number') {
|
||||
delete checkpoint.contextWindow;
|
||||
checkpoint.maxTokenLimit = option;
|
||||
} else {
|
||||
delete checkpoint.maxTokenLimit;
|
||||
checkpoint.contextWindow = option;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function rewriteBody(body, contentType) {
|
||||
if (contentType === 'application/json' && typeof body === 'string') {
|
||||
const json = JSON.parse(body);
|
||||
if (updatePayload(json)) return JSON.stringify(json);
|
||||
} else if (contentType === 'application/grpc-web+json' && body instanceof Uint8Array &&
|
||||
body.length >= 5 && body[0] === 0) {
|
||||
const header = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
||||
if (header.getUint32(1) !== body.length - 5) return body;
|
||||
const json = JSON.parse(decoder.decode(body.subarray(5)));
|
||||
if (!updatePayload(json)) return body;
|
||||
const message = encoder.encode(JSON.stringify(json));
|
||||
const frame = new Uint8Array(5 + message.length);
|
||||
new DataView(frame.buffer).setUint32(1, message.length);
|
||||
frame.set(message, 5);
|
||||
return frame;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function fetchWithContextWindow(input, init) {
|
||||
let nextInit = init;
|
||||
try {
|
||||
if (typeof input === 'string' && init?.method === 'POST') {
|
||||
const url = new URL(input, window.location.href);
|
||||
if (url.origin === window.location.origin && url.pathname === sendPath) {
|
||||
const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim();
|
||||
const body = rewriteBody(init.body, type);
|
||||
if (body !== init.body) nextInit = { ...init, body };
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 未识别的请求格式交回宿主原样发送。
|
||||
}
|
||||
return nextInit === init
|
||||
? nativeFetch.apply(this, arguments)
|
||||
: nativeFetch.call(this, input, nextInit);
|
||||
}
|
||||
|
||||
function sendWithContextWindow(data) {
|
||||
let nextData = data;
|
||||
try {
|
||||
if (typeof data === 'string' && data.includes(sendPath)) {
|
||||
const url = new URL(this.url);
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
if (url.protocol === protocol && url.host === window.location.host &&
|
||||
url.pathname === '/connect-websocket') {
|
||||
const frame = JSON.parse(data);
|
||||
if (frame.type === 'start' && frame.stream === false && frame.procedure === sendPath &&
|
||||
updatePayload(frame.payload)) {
|
||||
nextData = JSON.stringify(frame);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 未识别的帧交回宿主原样发送。
|
||||
}
|
||||
return nativeSend.call(this, nextData);
|
||||
}
|
||||
|
||||
state = window[key] = {
|
||||
bootId,
|
||||
rules: {},
|
||||
serviceUrl: window.location.origin + servicePath,
|
||||
isAttached() {
|
||||
return (typeof nativeFetch !== 'function' || window.fetch === fetchWithContextWindow) &&
|
||||
(typeof nativeSend !== 'function' || wsProto.send === sendWithContextWindow);
|
||||
},
|
||||
dispose() {
|
||||
clearTimeout(state.timer);
|
||||
state.rules = {};
|
||||
if (window.fetch === fetchWithContextWindow) window.fetch = nativeFetch;
|
||||
if (wsProto?.send === sendWithContextWindow) wsProto.send = nativeSend;
|
||||
delete window[key];
|
||||
},
|
||||
};
|
||||
if (typeof nativeFetch === 'function') window.fetch = fetchWithContextWindow;
|
||||
if (typeof nativeSend === 'function') wsProto.send = sendWithContextWindow;
|
||||
}
|
||||
state.preferences = rules;
|
||||
clearTimeout(state.timer);
|
||||
state.timer = setTimeout(() => state.dispose(), 15000);
|
||||
|
||||
// App 和 IDE 同时打开时,各窗口只使用自身宿主上报的档位。
|
||||
if (state.csrfToken !== csrfToken || Date.now() >= state.refreshAt) {
|
||||
if (state.csrfToken !== csrfToken) state.rules = {};
|
||||
state.csrfToken = csrfToken;
|
||||
state.refreshAt = Date.now() + 10000;
|
||||
state.status = (async () => {
|
||||
try {
|
||||
const init = {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'x-codeium-csrf-token': csrfToken },
|
||||
body: '{}',
|
||||
signal: AbortSignal.timeout(1500),
|
||||
};
|
||||
const call = async (method) => {
|
||||
const response = await window.fetch(state.serviceUrl + method, init);
|
||||
return response.ok ? response.json() : null;
|
||||
};
|
||||
const [status, catalog] = await Promise.all([
|
||||
call('GetUserStatus'),
|
||||
call('GetAvailableModels').catch(() => null),
|
||||
]);
|
||||
const userStatus = status?.userStatus;
|
||||
const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||
return getContextWindowModels(configs, catalog?.response?.models);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
}
|
||||
const status = state.status;
|
||||
const models = await status;
|
||||
if (window[key] !== state || state.status !== status) return;
|
||||
state.rules = resolveContextWindowRules(models, state.preferences);
|
||||
}
|
||||
|
||||
export function createContextWindowSyncExpression(preferences, bootId) {
|
||||
return `(() => {
|
||||
${isContextWindowModelId.toString()}
|
||||
${isContextWindowSettingId.toString()}
|
||||
${isContextWindowOption.toString()}
|
||||
${getContextWindowModels.toString()}
|
||||
${getContextWindowGroups.toString()}
|
||||
${resolveContextWindowOption.toString()}
|
||||
${resolveContextWindowRules.toString()}
|
||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)});
|
||||
})()`;
|
||||
}
|
||||
@@ -33,9 +33,9 @@ import { formatGenericModelSlug, getBaseModelLabel } from './model-pricing.mjs';
|
||||
import { PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||
|
||||
/**
|
||||
* 扫描本地 `conversations` 目录,返回 `cascadeId -> 最新磁盘修改时间 (mtimeMs)` 映射表。
|
||||
* 扫描本地 `conversations` 目录,按会话归并轨迹文件。
|
||||
*
|
||||
* @returns {Map<string, number>}
|
||||
* @returns {Map<string, string[]>}
|
||||
*/
|
||||
function discoverLocalConversationFiles() {
|
||||
const map = new Map();
|
||||
@@ -47,15 +47,8 @@ function discoverLocalConversationFiles() {
|
||||
);
|
||||
if (!m) continue;
|
||||
const cascadeId = m[1].toLowerCase();
|
||||
try {
|
||||
const st = statSync(join(CONVERSATIONS_DIR, name));
|
||||
const prevMtime = map.get(cascadeId) || 0;
|
||||
if (st.mtimeMs > prevMtime) {
|
||||
map.set(cascadeId, st.mtimeMs);
|
||||
}
|
||||
} catch {
|
||||
if (!map.has(cascadeId)) map.set(cascadeId, 0);
|
||||
}
|
||||
if (!map.has(cascadeId)) map.set(cascadeId, []);
|
||||
map.get(cascadeId).push(name);
|
||||
}
|
||||
} catch {
|
||||
// 忽略目录读取异常
|
||||
@@ -63,6 +56,18 @@ function discoverLocalConversationFiles() {
|
||||
return map;
|
||||
}
|
||||
|
||||
function readConversationMtime(files = []) {
|
||||
let mtimeMs = 0;
|
||||
for (const name of files) {
|
||||
try {
|
||||
mtimeMs = Math.max(mtimeMs, statSync(join(CONVERSATIONS_DIR, name)).mtimeMs);
|
||||
} catch {
|
||||
// 轨迹文件可能在目录枚举后被宿主删除。
|
||||
}
|
||||
}
|
||||
return mtimeMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载并解析跨端(IDE / Standalone / JetBrains)写入的 `.deep_stats_cache.json` 缓存。
|
||||
* 使用文件签名 (`mtimeMs + size`) 进行 Memoize,文件未变化时直接返回内存 Map。
|
||||
@@ -219,6 +224,7 @@ export function loadExternalDeepStatsCache() {
|
||||
|
||||
const MAX_CONCURRENT_RPC = 4;
|
||||
const LEGACY_MIGRATION_BATCH_SIZE = 8;
|
||||
const stepFieldChecks = new WeakMap();
|
||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||
const FAILED_RPC_COOLDOWN_MS = 60_000;
|
||||
const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000;
|
||||
@@ -635,7 +641,9 @@ export async function enumerateAndSyncConversations({
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const diskMtimeMs = diskConvMap.get(cidLower) || 0;
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
const summaryMtimeMs = parseIsoMs(lastModifiedTime);
|
||||
const diskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskConvMap.get(cidLower));
|
||||
const rawMeta = item?.trajectoryMetadata || item?.metadata || {};
|
||||
const parentConversationId = String(
|
||||
rawMeta.parentConversationId || cached?.parentConversationId || ''
|
||||
@@ -654,9 +662,8 @@ export async function enumerateAndSyncConversations({
|
||||
Boolean(rootConversationId && rootConversationId !== cidLower);
|
||||
|
||||
if (item) {
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
const lastModifiedMs =
|
||||
parseIsoMs(lastModifiedTime) || diskMtimeMs || cached?.lastModifiedMs || 0;
|
||||
summaryMtimeMs || diskMtimeMs || cached?.lastModifiedMs || 0;
|
||||
const rawSummaryStepCount = Number(item?.stepCount || 0);
|
||||
const modelStepCount = Array.isArray(cached?.steps)
|
||||
? cached.steps.length
|
||||
@@ -762,18 +769,30 @@ export async function enumerateAndSyncConversations({
|
||||
if (!Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown')) {
|
||||
return true;
|
||||
}
|
||||
if (steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel'))) {
|
||||
return true;
|
||||
}
|
||||
const { missingResponseModel, missingToolResultsTokens } = readStepFieldChecks(steps);
|
||||
return missingResponseModel || missingToolResultsTokens;
|
||||
}
|
||||
|
||||
function readStepFieldChecks(steps) {
|
||||
const known = stepFieldChecks.get(steps);
|
||||
if (known) return known;
|
||||
let missingToolResultsTokens = false;
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
if (steps[i]?.contextBreakdown) {
|
||||
return !Object.prototype.hasOwnProperty.call(
|
||||
missingToolResultsTokens = !Object.prototype.hasOwnProperty.call(
|
||||
steps[i].contextBreakdown,
|
||||
'toolResultsTokens'
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
const checks = {
|
||||
missingResponseModel: steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel')),
|
||||
missingToolResultsTokens,
|
||||
hasIncompleteTiming: steps.some((s) => s.speedReason === 'incomplete_or_invalid_timing'),
|
||||
};
|
||||
stepFieldChecks.set(steps, checks);
|
||||
return checks;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -857,8 +876,11 @@ export async function enumerateAndSyncConversations({
|
||||
accountName: prev?.accountName || currentAccountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
diskMtimeMs:
|
||||
conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(conv.cascadeId.toLowerCase())),
|
||||
wasRunning: isRunning,
|
||||
contextLimitTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
steps,
|
||||
subagentRefs,
|
||||
};
|
||||
@@ -879,6 +901,8 @@ export async function enumerateAndSyncConversations({
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
!prev.contextLimitTelemetry ||
|
||||
!prev.speedClearedTelemetry ||
|
||||
metaChanged ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
|
||||
@@ -922,11 +946,18 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
|
||||
// 阶段 1:拉取常规新增/变更会话,以及摘要列表中尚未提取 subagentRefs 的会话
|
||||
// 旧缓存只补读当前会话的宿主上限,避免重拉全部历史轨迹。
|
||||
const contextTelemetryCascadeId = reqLower || rawConversations[0]?.cascadeId.toLowerCase();
|
||||
const selectedRootId = rawConversations.find(
|
||||
(c) => c.cascadeId.toLowerCase() === contextTelemetryCascadeId
|
||||
)?.rootConversationId || contextTelemetryCascadeId;
|
||||
let remainingTimingRefreshes = LEGACY_MIGRATION_BATCH_SIZE;
|
||||
const toFetch = rawConversations.filter((conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
if (isFetchInCooldown(conv, sig)) return false;
|
||||
const cached = trajectoryCache[conv.cascadeId];
|
||||
if (!cached || conv.needsInitialLoad) return true;
|
||||
if (!cached.contextLimitTelemetry && conv.cascadeId.toLowerCase() === contextTelemetryCascadeId) return true;
|
||||
const hasCurrentSchema = String(cached.signature || '').startsWith(
|
||||
`${CACHE_SCHEMA_VERSION}:`
|
||||
);
|
||||
@@ -937,14 +968,23 @@ export async function enumerateAndSyncConversations({
|
||||
if (missingSubagentRefs && conv.cascadeId.toLowerCase() === reqLower) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
if (
|
||||
conv.diskMtimeMs > 0 &&
|
||||
conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0)
|
||||
);
|
||||
) return true;
|
||||
} else {
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
if (missingSubagentRefs || cached.signature !== sig || isRunning || cached.wasRunning) return true;
|
||||
}
|
||||
if (missingSubagentRefs) return true;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
return cached.signature !== sig || isRunning || Boolean(cached.wasRunning);
|
||||
// 保留已有效的历史测速,按批补读需要确认原始状态与生成结束时间的旧步骤。
|
||||
if (!cached.speedClearedTelemetry && readStepFieldChecks(cached.steps).hasIncompleteTiming) {
|
||||
if (conv.cascadeId.toLowerCase() === selectedRootId || conv.rootConversationId === selectedRootId) return true;
|
||||
if (remainingTimingRefreshes > 0) {
|
||||
remainingTimingRefreshes -= 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
});
|
||||
|
||||
await fetchTrajectoryBatch(toFetch);
|
||||
@@ -979,7 +1019,7 @@ export async function enumerateAndSyncConversations({
|
||||
let subConv = byLowerId.get(subCid);
|
||||
const subCached = trajectoryCache[subConv?.cascadeId || canonSubId];
|
||||
if (!subConv) {
|
||||
const diskMtimeMs = diskConvMap.get(subCid) || 0;
|
||||
const diskMtimeMs = readConversationMtime(diskConvMap.get(subCid));
|
||||
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||
const stepCount = Number(subCached?.steps?.length || 0);
|
||||
subConv = {
|
||||
|
||||
@@ -12,6 +12,21 @@ import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||
|
||||
const QUOTA_CACHE_TTL_MS = 10_000;
|
||||
const QUOTA_RETRY_COOLDOWN_MS = 5_000;
|
||||
let contextModelCatalog = null;
|
||||
|
||||
export function getContextModelCatalog() {
|
||||
const { baseUrl, csrfToken } = lsRuntimeEndpoint;
|
||||
if (!contextModelCatalog || contextModelCatalog.baseUrl !== baseUrl || contextModelCatalog.csrfToken !== csrfToken ||
|
||||
Date.now() >= contextModelCatalog.expiresAt) {
|
||||
contextModelCatalog = {
|
||||
baseUrl,
|
||||
csrfToken,
|
||||
expiresAt: Date.now() + 30000,
|
||||
promise: callLsRpc('GetAvailableModels', {}, 1500).then((data) => data?.response?.models).catch(() => null),
|
||||
};
|
||||
}
|
||||
return contextModelCatalog.promise;
|
||||
}
|
||||
|
||||
async function postLsRpcOnce(baseUrl, csrfToken, method, body, timeoutMs) {
|
||||
return fetch(`${baseUrl}/exa.language_server_pb.LanguageServerService/${method}`, {
|
||||
|
||||
@@ -275,6 +275,29 @@ export function resolveModelInfo(
|
||||
};
|
||||
}
|
||||
|
||||
/** 在单次遥测请求内复用同一模型身份与价格的解析结果。 */
|
||||
export function createStepModelResolver(dynamicModelMap) {
|
||||
const models = new Map();
|
||||
return (step) => {
|
||||
const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step;
|
||||
if (
|
||||
typeof modelKey !== 'string' ||
|
||||
typeof apiProvider !== 'string' ||
|
||||
typeof modelDisplayName !== 'string' ||
|
||||
typeof responseModel !== 'string'
|
||||
) {
|
||||
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
}
|
||||
const key = JSON.stringify([modelKey, apiProvider, modelDisplayName, responseModel]);
|
||||
let info = models.get(key);
|
||||
if (!info) {
|
||||
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
||||
models.set(key, info);
|
||||
}
|
||||
return info;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 为不透明的 Orchestrator 路由模型 ID 补充底层实际模型代号标注(如 `gemini-pro-orchestrator (carbon-4)`),
|
||||
* 普通透明上游模型 ID(如 `gemini-3.8-flash-n`、`gemini-4-hydrogen`)原样返回。
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
/**
|
||||
* @fileoverview 用户偏好设置 Schema、枚举常量、默认值与无状态纯函数归一化器。
|
||||
*
|
||||
* 独立于文件系统与运行时状态,统一约束「常规 / 结构 / 其他」三栏偏好结构,
|
||||
* 并无缝兼容旧版 `settings.json`(如 3 槽固定数组中的 `'none'`、`enableWindowOverlay`、`autoUpdatePlugin` 等)。
|
||||
*/
|
||||
|
||||
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
||||
|
||||
export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']);
|
||||
|
||||
export const THEME_ACCENT_KEYS = Object.freeze([
|
||||
'host',
|
||||
'blue',
|
||||
'emerald',
|
||||
'amber',
|
||||
'violet',
|
||||
'cyan',
|
||||
'rose',
|
||||
]);
|
||||
|
||||
export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']);
|
||||
|
||||
export const 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(['context', 'tps', 'quota_auto']);
|
||||
export const MIN_TOPBAR_SLOTS = 1;
|
||||
export const MAX_TOPBAR_SLOTS = 5;
|
||||
|
||||
export const OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_OVERVIEW_MODULES = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
||||
|
||||
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||
'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',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
|
||||
'step',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'tokens_combo',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||
|
||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||
|
||||
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
||||
|
||||
function isSchemaPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
}
|
||||
|
||||
function schemaSanitizePositiveNum(val, fallback) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化界面语言枚举(默认 `'zh-CN'`,保持与现有界面一致;同时支持 `'auto'` 与 `'en-US'`)。
|
||||
*
|
||||
* @param {unknown} lang
|
||||
* @returns {'auto'|'zh-CN'|'en-US'}
|
||||
*/
|
||||
export function normalizeLanguageSetting(lang) {
|
||||
const raw = String(lang ?? '').trim();
|
||||
if (!raw) return 'zh-CN';
|
||||
const lower = raw.toLowerCase();
|
||||
if (lower === 'auto' || lower === 'system') return 'auto';
|
||||
if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US';
|
||||
if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN';
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。
|
||||
*
|
||||
* @param {unknown} accent
|
||||
* @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'}
|
||||
*/
|
||||
export function normalizeThemeAccent(accent) {
|
||||
const clean = String(accent ?? '').trim().toLowerCase();
|
||||
return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化面板字号档位(默认 `'md'` 标准 100%)。
|
||||
*
|
||||
* @param {unknown} scale
|
||||
* @returns {'sm'|'md'|'lg'|'xl'}
|
||||
*/
|
||||
export function normalizeFontScale(scale) {
|
||||
const clean = String(scale ?? '').trim().toLowerCase();
|
||||
return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化面板挂载方式枚举(`'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';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'compact'|'full'}
|
||||
*/
|
||||
export function normalizeOrchestratorIdMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'full' ? 'full' : 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyAutoUpdate]
|
||||
* @returns {'off'|'manual'|'auto'}
|
||||
*/
|
||||
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
||||
if (legacyAutoUpdate === true) return 'auto';
|
||||
return 'manual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化每周额度统计模式枚举(兼容历史简写 `'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 normalizeOverviewModules(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_OVERVIEW_MODULES];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||
}
|
||||
return out.length > 0 ? out : ['metrics'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeHoverModules(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_HOVER_MODULES];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实时监控第一行指标矩阵的槽位与顺序(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 列)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeStepTableColumns(raw) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...DEFAULT_STEP_TABLE_COLUMNS];
|
||||
}
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const val = String(item ?? '').trim();
|
||||
if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue;
|
||||
seen.add(val);
|
||||
out.push(val);
|
||||
if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break;
|
||||
}
|
||||
if (out.length < 2) {
|
||||
for (const fallbackCol of ['step', 'model', 'tps']) {
|
||||
if (!seen.has(fallbackCol)) {
|
||||
seen.add(fallbackCol);
|
||||
out.push(fallbackCol);
|
||||
}
|
||||
if (out.length >= 2) break;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function normalizeModelContextWindows(value) {
|
||||
return Object.fromEntries(
|
||||
Object.entries(isSchemaPlainObject(value) ? value : {}).filter(
|
||||
([id, option]) => isContextWindowSettingId(id) && isContextWindowOption(option)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
language: 'zh-CN',
|
||||
themeAccent: 'host',
|
||||
fontScale: 'md',
|
||||
weeklyTokenBudget: 150000000,
|
||||
weeklyCostBudget: 100,
|
||||
weeklyLimitMode: 'official',
|
||||
showUpstreamModel: false,
|
||||
orchestratorIdMode: 'compact',
|
||||
pluginUpdateMode: 'manual',
|
||||
autoUpdatePlugin: false,
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: DEFAULT_TOPBAR_SLOTS,
|
||||
hoverModules: DEFAULT_HOVER_MODULES,
|
||||
overviewModules: DEFAULT_OVERVIEW_MODULES,
|
||||
overviewMetrics: DEFAULT_OVERVIEW_METRICS,
|
||||
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
|
||||
modelContextWindows: Object.freeze({}),
|
||||
});
|
||||
|
||||
/**
|
||||
* 创建一份深拷贝的全新默认偏好设置对象。
|
||||
*/
|
||||
export function createDefaultSettingsObject() {
|
||||
return {
|
||||
language: DEFAULT_SETTINGS_SCHEMA.language,
|
||||
themeAccent: DEFAULT_SETTINGS_SCHEMA.themeAccent,
|
||||
fontScale: DEFAULT_SETTINGS_SCHEMA.fontScale,
|
||||
weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget,
|
||||
weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget,
|
||||
weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode,
|
||||
showUpstreamModel: DEFAULT_SETTINGS_SCHEMA.showUpstreamModel,
|
||||
orchestratorIdMode: DEFAULT_SETTINGS_SCHEMA.orchestratorIdMode,
|
||||
pluginUpdateMode: DEFAULT_SETTINGS_SCHEMA.pluginUpdateMode,
|
||||
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
|
||||
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
|
||||
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
|
||||
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
|
||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
||||
hoverModules: [...DEFAULT_HOVER_MODULES],
|
||||
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
||||
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
||||
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||
modelContextWindows: {},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将原始持久化对象或增量合并结果完整归一化为合法偏好对象。
|
||||
*
|
||||
* @param {unknown} rawInput
|
||||
*/
|
||||
export function normalizeFullSettings(rawInput) {
|
||||
const safeRaw = isSchemaPlainObject(rawInput) ? rawInput : {};
|
||||
const pluginUpdateMode = normalizePluginUpdateMode(
|
||||
safeRaw.pluginUpdateMode,
|
||||
safeRaw.autoUpdatePlugin
|
||||
);
|
||||
const windowMountMode = normalizeWindowMountMode(
|
||||
safeRaw.windowMountMode,
|
||||
safeRaw.enableWindowOverlay
|
||||
);
|
||||
return {
|
||||
language: normalizeLanguageSetting(safeRaw.language),
|
||||
themeAccent: normalizeThemeAccent(safeRaw.themeAccent),
|
||||
fontScale: normalizeFontScale(safeRaw.fontScale),
|
||||
weeklyTokenBudget: schemaSanitizePositiveNum(
|
||||
safeRaw.weeklyTokenBudget ?? safeRaw.weeklyTokenLimit,
|
||||
DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget
|
||||
),
|
||||
weeklyCostBudget: schemaSanitizePositiveNum(
|
||||
safeRaw.weeklyCostBudget,
|
||||
DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(safeRaw.weeklyLimitMode),
|
||||
showUpstreamModel: safeRaw.showUpstreamModel === true,
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(safeRaw.orchestratorIdMode),
|
||||
pluginUpdateMode,
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
windowMountMode,
|
||||
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||
showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(safeRaw.topbarCapsuleSlots),
|
||||
hoverModules: normalizeHoverModules(safeRaw.hoverModules),
|
||||
overviewModules: normalizeOverviewModules(safeRaw.overviewModules),
|
||||
overviewMetrics: normalizeOverviewMetrics(safeRaw.overviewMetrics),
|
||||
stepTableColumns: normalizeStepTableColumns(safeRaw.stepTableColumns),
|
||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,14 +24,15 @@ import {
|
||||
roundMetric,
|
||||
trajectoryCache,
|
||||
} from './config.mjs';
|
||||
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
|
||||
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
||||
import { callLsRpc, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||
import { callLsRpc, getContextModelCatalog, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||
import {
|
||||
computeStepCost,
|
||||
createStepModelResolver,
|
||||
formatUpstreamModelId,
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
} from './model-pricing.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
@@ -64,13 +65,21 @@ function findTrajectoryCacheEntry(cascadeId) {
|
||||
*
|
||||
* @returns {Map<string, string>}
|
||||
*/
|
||||
function buildKnownUpstreamModelMap() {
|
||||
function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
|
||||
const knownUpstreamByModelKey = new Map();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
const trackContext = contextLimits && !entry.subagentSpec &&
|
||||
(!entry.accountName || entry.accountName === currentAccountName);
|
||||
for (const s of entry?.steps || []) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
}
|
||||
if (trackContext && !s.isCompactionStep && s.reportedContextLimitTokens > 0) {
|
||||
const prev = contextLimits.get(s.modelKey);
|
||||
if (!prev || s.createdAtMs > prev.at) {
|
||||
contextLimits.set(s.modelKey, { tokens: s.reportedContextLimitTokens, at: s.createdAtMs });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return knownUpstreamByModelKey;
|
||||
@@ -81,12 +90,12 @@ function buildKnownUpstreamModelMap() {
|
||||
* 并剔除前端未使用的冗余诊断字段以减小 JSON 体积。
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {Map<string, object>} [dynamicModelMap=new Map()] 动态模型字典
|
||||
* @param {ReturnType<typeof createStepModelResolver>} resolveStepModel 模型身份与价格解析器
|
||||
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
||||
*/
|
||||
function enrichActiveConversationSteps(
|
||||
activeSteps,
|
||||
dynamicModelMap = new Map(),
|
||||
resolveStepModel,
|
||||
sharedUpstreamMap = null
|
||||
) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
@@ -104,13 +113,7 @@ function enrichActiveConversationSteps(
|
||||
}
|
||||
|
||||
const enrichedActiveSteps = activeSteps.map((st) => {
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(st);
|
||||
const costUsd = computeStepCost(st, mInfo.pricing);
|
||||
const metric = speedMetric(st);
|
||||
|
||||
@@ -300,13 +303,13 @@ function buildAgentUnitTelemetry({
|
||||
rawSteps,
|
||||
liveActivity = null,
|
||||
fallbackLastModMs,
|
||||
dynamicModelMap,
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps = true,
|
||||
}) {
|
||||
const enrichedRes = enrichActiveConversationSteps(
|
||||
rawSteps,
|
||||
dynamicModelMap,
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey
|
||||
);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps.map((st) => ({
|
||||
@@ -325,7 +328,7 @@ function buildAgentUnitTelemetry({
|
||||
enrichedRes.sessionInputTokens,
|
||||
enrichedRes.sessionCacheReadTokens
|
||||
);
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, dynamicModelMap);
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, resolveStepModel);
|
||||
const lastModifiedMs =
|
||||
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
|
||||
const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
@@ -390,10 +393,11 @@ export async function buildTelemetryPayloadInternal(
|
||||
filterOpts = {}
|
||||
) {
|
||||
const settings = loadSettings();
|
||||
const [userStatusRes, allTrajRes, initialOfficialQuotaInfo] = await Promise.all([
|
||||
const [userStatusRes, allTrajRes, initialOfficialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||
callLsRpc('GetUserStatus', {}).catch(() => ({})),
|
||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||
getOfficialQuotaSummary(forceQuotaRefresh),
|
||||
getContextModelCatalog(),
|
||||
]);
|
||||
|
||||
const userStatus = userStatusRes?.userStatus || {};
|
||||
@@ -439,9 +443,11 @@ export async function buildTelemetryPayloadInternal(
|
||||
requestedConvId,
|
||||
forceRefresh: forceQuotaRefresh,
|
||||
});
|
||||
const resolveStepModel = createStepModelResolver(dynamicModelMap);
|
||||
|
||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap();
|
||||
const reportedContextLimits = new Map();
|
||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName);
|
||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const mainUnit = buildAgentUnitTelemetry({
|
||||
@@ -458,7 +464,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
rawSteps: activeSteps,
|
||||
liveActivity: activeConvSummary?.liveActivity || null,
|
||||
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps: false,
|
||||
});
|
||||
@@ -518,7 +524,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
rawSteps: subRawSteps,
|
||||
liveActivity: subSum.liveActivity || null,
|
||||
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
resolveStepModel,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps: true,
|
||||
});
|
||||
@@ -548,7 +554,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
const combinedAvgTokPerSec = roundMetric(combinedSpeed.avgTokPerSec);
|
||||
const combinedModelBreakdown = buildScopedModelBreakdown(
|
||||
allCombinedEnrichedSteps,
|
||||
dynamicModelMap
|
||||
resolveStepModel
|
||||
);
|
||||
|
||||
const runningAgent = allAgents.find((a) => a.isRunning);
|
||||
@@ -731,7 +737,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
currentAccountName,
|
||||
activeCascadeId,
|
||||
activeFamilyCascadeIds,
|
||||
dynamicModelMap,
|
||||
resolveStepModel,
|
||||
quotaPoolsMap,
|
||||
});
|
||||
|
||||
@@ -845,13 +851,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
let unpricedCalls = 0;
|
||||
const accumulateStepsCost = (steps) => {
|
||||
for (const st of steps) {
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(st);
|
||||
const c = computeStepCost(st, mInfo.pricing);
|
||||
if (c === null) unpricedCalls += 1;
|
||||
else totalCost += c;
|
||||
@@ -909,13 +909,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
let modelUpstream = '';
|
||||
let latestTokPerSec = null;
|
||||
if (bestMetricStep) {
|
||||
const mInfo = resolveModelInfo(
|
||||
bestMetricStep.modelKey,
|
||||
dynamicModelMap,
|
||||
bestMetricStep.apiProvider,
|
||||
bestMetricStep.modelDisplayName,
|
||||
bestMetricStep.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(bestMetricStep);
|
||||
const resolvedResp =
|
||||
bestMetricStep.responseModel ||
|
||||
(bestMetricStep.modelKey && bestMetricStep.modelKey !== 'unknown'
|
||||
@@ -1078,6 +1072,13 @@ export async function buildTelemetryPayloadInternal(
|
||||
timestamp: new Date().toISOString(),
|
||||
uiBundleVersion,
|
||||
settings,
|
||||
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
||||
const latest = group.members.reduce((previous, id) => {
|
||||
const reported = reportedContextLimits.get(id);
|
||||
return reported && (!previous || reported.at > previous.at) ? reported : previous;
|
||||
}, null);
|
||||
return { ...group, reportedLimitTokens: latest?.tokens ?? null };
|
||||
}),
|
||||
cloudStatus: getCloudStatus(),
|
||||
account: {
|
||||
name: userStatus?.name || '',
|
||||
|
||||
@@ -20,9 +20,10 @@ import {
|
||||
formatUpstreamModelId,
|
||||
isArgonModelIdentifier,
|
||||
isCarbonModelIdentifier,
|
||||
resolveModelInfo,
|
||||
} from './model-pricing.mjs';
|
||||
|
||||
/** @typedef {ReturnType<import('./model-pricing.mjs').createStepModelResolver>} StepModelResolver */
|
||||
|
||||
function safeTok(val) {
|
||||
const n = Number(val);
|
||||
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||
@@ -186,7 +187,7 @@ function createUsageBucket() {
|
||||
*
|
||||
* @param {ReturnType<typeof createUsageBucket>} bucket
|
||||
* @param {object} st 步骤对象
|
||||
* @param {ReturnType<typeof resolveModelInfo>} mInfo 模型信息
|
||||
* @param {ReturnType<ReturnType<typeof createStepModelResolver>>} mInfo 模型信息
|
||||
* @param {number|null} stepCost 单步美元成本(未知时为 `null`)
|
||||
* @param {string} cascadeId 会话标识
|
||||
*/
|
||||
@@ -368,20 +369,14 @@ function finalizeModelBreakdownMap(perModelStats) {
|
||||
* 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。
|
||||
*
|
||||
* @param {object[]} [steps=[]]
|
||||
* @param {Map<string, object>} [dynamicModelMap=new Map()]
|
||||
* @param {StepModelResolver} resolveStepModel
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function buildScopedModelBreakdown(steps = [], dynamicModelMap = new Map()) {
|
||||
export function buildScopedModelBreakdown(steps, resolveStepModel) {
|
||||
const perModelStats = new Map();
|
||||
for (const st of steps) {
|
||||
if (!st || typeof st !== 'object') continue;
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(st);
|
||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
@@ -397,7 +392,7 @@ export function buildScopedModelBreakdown(steps = [], dynamicModelMap = new Map(
|
||||
* currentAccountName?: string,
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* dynamicModelMap?: Map<string, object>
|
||||
* resolveStepModel: StepModelResolver
|
||||
* }} params
|
||||
*/
|
||||
export function aggregateMultiWindowUsage({
|
||||
@@ -406,9 +401,9 @@ export function aggregateMultiWindowUsage({
|
||||
currentAccountName = '',
|
||||
activeCascadeId = null,
|
||||
activeFamilyCascadeIds = null,
|
||||
dynamicModelMap = new Map(),
|
||||
resolveStepModel,
|
||||
quotaPoolsMap = null,
|
||||
} = {}) {
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
? Array.from(activeFamilyCascadeIds)
|
||||
@@ -565,13 +560,7 @@ export function aggregateMultiWindowUsage({
|
||||
|
||||
for (const st of entry.steps || []) {
|
||||
if (!st || typeof st !== 'object') continue;
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const mInfo = resolveStepModel(st);
|
||||
const inTok = safeTok(st.inputTokens);
|
||||
const cacheTok = safeTok(st.cacheReadTokens);
|
||||
const outTok = safeTok(st.outputTokens);
|
||||
|
||||
@@ -22,11 +22,14 @@ import {
|
||||
normalizeWindowMountMode,
|
||||
saveJson,
|
||||
} from './config.mjs';
|
||||
import { createContextWindowSyncExpression } from './context-windows.mjs';
|
||||
|
||||
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
||||
const ALLOWED_BRIDGE_PATHS = new Set([
|
||||
'/api/telemetry',
|
||||
'/api/settings',
|
||||
'/api/settings/reset',
|
||||
'/api/context-window',
|
||||
'/api/cloud-sync',
|
||||
'/api/plugin-update',
|
||||
]);
|
||||
@@ -705,6 +708,8 @@ export function createWindowBridgeController(options) {
|
||||
let hadInjectedChatFrames = false;
|
||||
let cdpFallbackActive = false;
|
||||
let ideArgvProvisioned = false;
|
||||
let hadContextWindows = false;
|
||||
let contextWindowBootId = `${process.pid}:${Date.now()}`;
|
||||
let nodeDepsPromise = null;
|
||||
const allowedDynamicOrigins = new Set();
|
||||
|
||||
@@ -1099,14 +1104,16 @@ export function createWindowBridgeController(options) {
|
||||
curSettings.enableWindowOverlay
|
||||
);
|
||||
const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||
if (enabled && autoConfigureIdeArgv && !ideArgvProvisioned) {
|
||||
const contextWindows = curSettings.modelContextWindows || {};
|
||||
const hasContextWindows = Object.keys(contextWindows).length > 0;
|
||||
if ((enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned) {
|
||||
const prov = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true });
|
||||
if (prov.updated || prov.alreadyConfigured || prov.reason === 'ide_dir_missing') {
|
||||
ideArgvProvisioned = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (enabled && leaseFilePath && !forceReinject) {
|
||||
if ((enabled || hasContextWindows) && leaseFilePath && !forceReinject) {
|
||||
const lease = loadJson(leaseFilePath, null);
|
||||
const leasePid = Number(lease?.pid || 0);
|
||||
const leaseAgeMs = Date.now() - Number(lease?.updatedAtMs || 0);
|
||||
@@ -1141,6 +1148,16 @@ export function createWindowBridgeController(options) {
|
||||
return { ok: true, enabled, reason: 'no_targets', injected: 0 };
|
||||
}
|
||||
|
||||
if (hasContextWindows || hadContextWindows) {
|
||||
const chatUrls = [
|
||||
...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl),
|
||||
...collectAllChatDebuggerUrls(targets),
|
||||
];
|
||||
const expression = createContextWindowSyncExpression(contextWindows, contextWindowBootId);
|
||||
await Promise.allSettled([...new Set(chatUrls)].map((url) => evaluateOnTarget(url, expression)));
|
||||
hadContextWindows = hasContextWindows;
|
||||
}
|
||||
|
||||
const disposeExpr = `(() => {
|
||||
try {
|
||||
const existed = Boolean(window.__AGUsageMonitorOverlay || window.__AGUsageMonitorBridge);
|
||||
@@ -1437,6 +1454,7 @@ export function createWindowBridgeController(options) {
|
||||
|
||||
function start() {
|
||||
stopped = false;
|
||||
contextWindowBootId = `${process.pid}:${Date.now()}`;
|
||||
if (initialTimer) clearTimeout(initialTimer);
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
|
||||
@@ -1460,7 +1478,7 @@ export function createWindowBridgeController(options) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
if (disposeWindows && (hadInjectedTargets || hadInjectedChatFrames)) {
|
||||
if (disposeWindows && (hadInjectedTargets || hadInjectedChatFrames || hadContextWindows)) {
|
||||
const prevStopped = stopped;
|
||||
stopped = false;
|
||||
try {
|
||||
@@ -1469,7 +1487,7 @@ export function createWindowBridgeController(options) {
|
||||
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({
|
||||
targets: [],
|
||||
}));
|
||||
const disposeExpr = `(() => { try { window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`;
|
||||
const disposeExpr = `(() => { try { window.__AGUsageMonitorContextWindows?.dispose?.(); window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`;
|
||||
const allUrls = [
|
||||
...targets.map((t) => String(t.webSocketDebuggerUrl || '')).filter(Boolean),
|
||||
...collectAllChatDebuggerUrls(targets),
|
||||
@@ -1485,6 +1503,7 @@ export function createWindowBridgeController(options) {
|
||||
stopped = true;
|
||||
hadInjectedTargets = false;
|
||||
hadInjectedChatFrames = false;
|
||||
hadContextWindows = false;
|
||||
if (server) {
|
||||
const srv = server;
|
||||
server = null;
|
||||
@@ -1541,3 +1560,7 @@ export function notifyWindowOverlaySetting(enabled) {
|
||||
if (!defaultBridgeController) return Promise.resolve({ ok: false });
|
||||
return defaultBridgeController.notifySettingChanged(enabled);
|
||||
}
|
||||
|
||||
export function notifyModelContextWindowsChanged() {
|
||||
return defaultBridgeController?.syncAllWindows().catch(() => {});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user