mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +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:
@@ -52,6 +52,7 @@ The dashboard is organized into four tabs, with a top header to switch conversat
|
||||
- **Mount Mode**: Dual-mount (Top Bar + Sidebar) or Sidebar only.
|
||||
- **Top-Bar Customization**: Independently toggle the live running-sessions indicator, and customize the content and left-to-right order of the three metric slots in the capsule.
|
||||
- **Model Name Format**: Compact short alias (e.g. `argon-4-high`) or raw upstream model ID (e.g. `gemini-3.8-flash-n`), plus an independent Orchestrator series ID selector (`orchestrator-argon` / `worker-agy-hydrogen` compact mode by default, or full annotated IDs).
|
||||
- **Per-model context windows**: In **Other → Model Context Settings**, choose a shared limit for all thinking levels of a model or select **Follow host settings**. The model list shows the saved limit and the most recent value reported by the host. At startup, the App / IDE window bridge reads the latest model catalog and reapplies saved limits to future messages. The CLI uses `AGY_CLI_AUTO_COMPACT_OVERRIDE`.
|
||||
- **Version Updates & Pricing Sync**: Dynamically sync [`pricing-catalog.json`](pricing-catalog.json) from GitHub, with three update modes: *Notify only, manual update* (default), *Auto update*, and *Off*.
|
||||
|
||||
## Model Identification & Cost Accounting
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
||||
- 顶部栏定制:独立开关实时运行会话入口,并自由定义右侧三个指标槽位的显示内容与排列顺序。
|
||||
- 选择模型名称格式:精简代号或原始模型 ID,并可独立设置 Orchestrator 系列显示精简代号(如 `orchestrator-argon`、`worker-agy-hydrogen`)或原始完整 ID。
|
||||
- 按模型设置上下文:在「其他 → 模型上下文设置」为同一模型的各推理档统一设置上限,或切回「跟随宿主设置」。列表右侧显示已设置的上限和宿主最近报告的数值。App / IDE 窗口桥接在插件启动时重新读取宿主模型目录并应用已保存的设置,适用于之后发送的消息。CLI 使用 `AGY_CLI_AUTO_COMPACT_OVERRIDE`。
|
||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并提供「仅提示新版本,手动更新」(默认)、「自动更新」与「关闭更新」三档更新方式。
|
||||
|
||||
## 模型识别与费用口径
|
||||
|
||||
+6577
-2483
File diff suppressed because it is too large
Load Diff
@@ -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(() => {});
|
||||
}
|
||||
|
||||
@@ -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=1794653465857">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794673025095">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794653465857"></script>
|
||||
<script src="/app.js?v=1794673025095"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -15,7 +15,10 @@ import { Response, SidecarApp } from 'sidecar_sdk';
|
||||
import {
|
||||
bootWindowBridgeRuntime,
|
||||
executeCloudSyncAction,
|
||||
executeModelContextWindowAction,
|
||||
executePluginUpdateAction,
|
||||
executeRebuildCacheAction,
|
||||
executeResetSettingsAction,
|
||||
executeSettingsAction,
|
||||
executeTelemetryAction,
|
||||
isLocalHostRequest,
|
||||
@@ -98,6 +101,54 @@ app.api('/api/settings', (data, req) => {
|
||||
return out.updated;
|
||||
});
|
||||
|
||||
app.api('/api/context-window', async (data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeModelContextWindowAction(data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
});
|
||||
|
||||
app.api('/api/settings/reset', (_data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = executeResetSettingsAction();
|
||||
if (!out.ok) {
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
return out.updated;
|
||||
});
|
||||
|
||||
app.api('/api/cache/rebuild', (_data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = executeRebuildCacheAction();
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
});
|
||||
|
||||
app.api('/api/cloud-sync', async (_data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
|
||||
@@ -437,6 +437,7 @@ export function buildBundle() {
|
||||
'src/styles/views-overview.css',
|
||||
'src/styles/views-consumption.css',
|
||||
'src/styles/views-tables.css',
|
||||
'src/styles/views-settings.css',
|
||||
'src/styles/overlay.css',
|
||||
];
|
||||
|
||||
@@ -451,6 +452,10 @@ export function buildBundle() {
|
||||
'src/icons/svgRegistry.js',
|
||||
'src/icons/SvgIcon.js',
|
||||
'src/core/reactive.js',
|
||||
'src/i18n/zh-CN.js',
|
||||
'src/i18n/en-US.js',
|
||||
'src/i18n/index.js',
|
||||
'src/core/appearance.js',
|
||||
'src/core/domPatch.js',
|
||||
'src/core/component.js',
|
||||
'src/core/formatters.js',
|
||||
@@ -467,6 +472,19 @@ export function buildBundle() {
|
||||
'src/components/ui/FourSegmentBar.js',
|
||||
'src/components/charts/TrendAreaChart.js',
|
||||
'src/components/charts/SessionStepCharts.js',
|
||||
'src/registries/metricRegistry.js',
|
||||
'src/components/widgets/MetricMatrixWidget.js',
|
||||
'src/components/widgets/ContextWindowWidget.js',
|
||||
'src/components/widgets/QuotaPoolsWidget.js',
|
||||
'src/components/widgets/LiveActivityWidget.js',
|
||||
'src/registries/widgetRegistry.js',
|
||||
'src/registries/stepColumnRegistry.js',
|
||||
'src/components/settings/CollapsibleSection.js',
|
||||
'src/components/settings/EditableSlotList.js',
|
||||
'src/components/settings/ThemeColorPicker.js',
|
||||
'src/views/settings/SettingsGeneralTab.js',
|
||||
'src/views/settings/SettingsStructureTab.js',
|
||||
'src/views/settings/SettingsOtherTab.js',
|
||||
'src/components/layout/TopSessionHeader.js',
|
||||
'src/views/LiveOverviewView.js',
|
||||
'src/views/ConsumptionView.js',
|
||||
|
||||
@@ -556,7 +556,7 @@ export function extractContextBreakdown(chat) {
|
||||
* - 优先级 4:`metadata.generatorModel`(步骤 `metadata` 顶层记录的生成模型)
|
||||
* - 优先级 5:`chat.responseModel`(上游返回的具体响应模型名)
|
||||
* 2. **5 种测速过滤与排除原因(`timingReason` / `speedReason`)**:
|
||||
* - `'incomplete_or_invalid_timing'`:步骤状态未完成(非 `CORTEX_STEP_STATUS_DONE`)或总耗时 `totalDurationSec` 缺失/非正数;
|
||||
* - `'incomplete_or_invalid_timing'`:没有完成生成的证据,或总耗时 `totalDurationSec` 缺失/非正数;
|
||||
* - `'invalid_output_tokens'`:`outputTokens` 不是合法的非负安全整数;
|
||||
* - `'short_timing'`:请求总耗时低于 `MIN_SPEED_DURATION_SECONDS`(0.5s),易受计时器粒度噪声干扰;
|
||||
* - `'inconsistent_timing'`:原生首字延迟 `nativeTtftSec` 大于请求总耗时 `totalDurationSec + 0.01s`(时钟或元数据自相矛盾);
|
||||
@@ -658,12 +658,14 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
: Math.max(0, outputTokens - thinkingTokens);
|
||||
|
||||
const start = parseIsoMs(m.createdAt);
|
||||
// 轨迹清理可把已生成的步骤改为 CLEARED;仍需原始生成结束时间,避免将清理时间计入测速。
|
||||
const isCleared = s.status === 'CORTEX_STEP_STATUS_CLEARED';
|
||||
const measuredDuration = requestDuration(
|
||||
m.createdAt,
|
||||
m.finishedGeneratingAt || m.completedAt
|
||||
m.finishedGeneratingAt || (isCleared ? null : m.completedAt)
|
||||
);
|
||||
const explicitlyIncomplete = Boolean(
|
||||
s.status && s.status !== 'CORTEX_STEP_STATUS_DONE'
|
||||
s.status && s.status !== 'CORTEX_STEP_STATUS_DONE' && !isCleared
|
||||
);
|
||||
const complete = !explicitlyIncomplete && measuredDuration !== null;
|
||||
const totalDurationSec = complete ? measuredDuration : null;
|
||||
@@ -763,6 +765,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
||||
context?.estimatedTokensUsed || contextBreakdown?.totalTokens || 0
|
||||
),
|
||||
maxContextBudgetTokens: Number(context?.maxContextTokens || 256000),
|
||||
...(context?.maxContextTokens > 0 ? { reportedContextLimitTokens: Number(context.maxContextTokens) } : {}),
|
||||
contextBreakdown,
|
||||
measurementVersion: MEASUREMENT_VERSION,
|
||||
isComplete: complete,
|
||||
@@ -1161,10 +1164,12 @@ export function summarizeTtft(steps) {
|
||||
/** 标志着原始轨迹步骤已进入终态的状态枚举集合(兼容 Connect RPC 与 transcript.jsonl) */
|
||||
const LIVE_TERMINAL_STATUSES = new Set([
|
||||
'CORTEX_STEP_STATUS_DONE',
|
||||
'CORTEX_STEP_STATUS_CLEARED',
|
||||
'CORTEX_STEP_STATUS_ERROR',
|
||||
'CORTEX_STEP_STATUS_CANCELED',
|
||||
'CORTEX_STEP_STATUS_CANCELLED',
|
||||
'DONE',
|
||||
'CLEARED',
|
||||
'ERROR',
|
||||
'CANCELED',
|
||||
'CANCELLED',
|
||||
|
||||
@@ -6,8 +6,9 @@
|
||||
|
||||
import { defineComponent } from './core/component.js';
|
||||
import { h, patchAttr } from './core/domPatch.js';
|
||||
import { i18nStore } from './i18n/index.js';
|
||||
import { resolveScopedConversation, telemetryStore } from './store/telemetryStore.js';
|
||||
import { uiStore, VIEW_TABS } from './store/uiStore.js';
|
||||
import { getViewTabs, uiStore } from './store/uiStore.js';
|
||||
import { TopSessionHeader } from './components/layout/TopSessionHeader.js';
|
||||
import { TopLongPillNav } from './components/ui/TopLongPillNav.js';
|
||||
import { LiveOverviewView } from './views/LiveOverviewView.js';
|
||||
@@ -21,7 +22,7 @@ export const App = defineComponent({
|
||||
const sessionHeader = TopSessionHeader();
|
||||
const topPillNav = TopLongPillNav({
|
||||
modelValue: uiStore.getState().activeView,
|
||||
items: VIEW_TABS,
|
||||
items: getViewTabs(),
|
||||
onUpdateModelValue: (nextView) => {
|
||||
uiStore.setState({ activeView: nextView });
|
||||
},
|
||||
@@ -61,8 +62,10 @@ export const App = defineComponent({
|
||||
);
|
||||
const stepCount = scopedConv?.stepCount ?? 0;
|
||||
topPillNav.setProps({
|
||||
items: VIEW_TABS.map((t) =>
|
||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||
items: getViewTabs().map((tabItem) =>
|
||||
tabItem.value === 'steps'
|
||||
? { ...tabItem, badge: stepCount > 0 ? stepCount : '' }
|
||||
: tabItem
|
||||
),
|
||||
});
|
||||
}
|
||||
@@ -102,10 +105,16 @@ export const App = defineComponent({
|
||||
() => syncStepsBadge()
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => syncStepsBadge()
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubUi();
|
||||
unsubStepCount();
|
||||
unsubScopeBadge();
|
||||
unsubI18n();
|
||||
sessionHeader.destroy();
|
||||
topPillNav.destroy();
|
||||
overviewView.destroy();
|
||||
|
||||
@@ -260,24 +260,63 @@ export function computePublicationFit(
|
||||
|
||||
// n >= 6:Cleveland 高斯局部加权一阶线性回归(LOESS)+ 精确帽子矩阵杠杆度 95% CI 置信带
|
||||
const q = Math.max(5, Math.min(n, Math.ceil(span * n)));
|
||||
const distBuf = new Float64Array(n);
|
||||
const wBuf = new Float64Array(n);
|
||||
const sortedXs = q <= n && xs.slice(0, n).every(
|
||||
(x, i) => Number.isFinite(x) && (i === 0 || xs[i - 1] <= x)
|
||||
);
|
||||
|
||||
function loessBandwidth(x0) {
|
||||
// 有序 x 上的 q 个最近样本可取连续区间;二分比较两端,避免每个拟合点都排序。
|
||||
let left = 0;
|
||||
let right = n - q;
|
||||
while (left < right) {
|
||||
const mid = (left + right) >>> 1;
|
||||
if (x0 - xs[mid] > xs[mid + q] - x0) {
|
||||
left = mid + 1;
|
||||
} else {
|
||||
right = mid;
|
||||
}
|
||||
}
|
||||
return Math.max(Math.abs(xs[left] - x0), Math.abs(xs[left + q - 1] - x0));
|
||||
}
|
||||
|
||||
function evalLoessPoint(x0, diagIdx = -1) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
distBuf[j] = Math.abs(xs[j] - x0);
|
||||
}
|
||||
const sortedDists = Array.from(distBuf).sort((a, b) => a - b);
|
||||
let h = sortedDists[q - 1];
|
||||
if (h <= 1e-9) {
|
||||
h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6);
|
||||
let h;
|
||||
if (sortedXs) {
|
||||
h = loessBandwidth(x0);
|
||||
if (h <= 1e-9) {
|
||||
h = Math.max(Math.abs(xs[0] - x0), Math.abs(xs[n - 1] - x0), xSpan * 0.05, 1e-6);
|
||||
}
|
||||
} else {
|
||||
const sortedDists = Array.from({ length: n }, (_, j) => Math.abs(xs[j] - x0)).sort((a, b) => a - b);
|
||||
h = sortedDists[q - 1];
|
||||
if (h <= 1e-9) {
|
||||
h = Math.max(sortedDists[n - 1], xSpan * 0.05, 1e-6);
|
||||
}
|
||||
}
|
||||
const maxDist = h * 1.0001;
|
||||
let start = 0;
|
||||
let end = n;
|
||||
if (sortedXs) {
|
||||
// 三次权重的支持区间之外权重为零,保留区间内样本原来的累加顺序。
|
||||
let right = n;
|
||||
while (start < right) {
|
||||
const mid = (start + right) >>> 1;
|
||||
if (x0 - xs[mid] >= maxDist) start = mid + 1;
|
||||
else right = mid;
|
||||
}
|
||||
let left = start;
|
||||
while (left < end) {
|
||||
const mid = (left + end) >>> 1;
|
||||
if (xs[mid] - x0 < maxDist) left = mid + 1;
|
||||
else end = mid;
|
||||
}
|
||||
}
|
||||
|
||||
let sw = 0;
|
||||
let swx = 0;
|
||||
for (let j = 0; j < n; j++) {
|
||||
const u = distBuf[j] / maxDist;
|
||||
for (let j = start; j < end; j++) {
|
||||
const u = Math.abs(xs[j] - x0) / maxDist;
|
||||
const w = u >= 1 ? 0 : (1 - u * u * u) ** 3;
|
||||
wBuf[j] = w;
|
||||
sw += w;
|
||||
@@ -291,7 +330,7 @@ export function computePublicationFit(
|
||||
|
||||
const mx = swx / sw;
|
||||
let sxxW = 0;
|
||||
for (let j = 0; j < n; j++) {
|
||||
for (let j = start; j < end; j++) {
|
||||
const w = wBuf[j];
|
||||
if (w <= 0) continue;
|
||||
const dx = xs[j] - mx;
|
||||
@@ -304,7 +343,7 @@ export function computePublicationFit(
|
||||
let leverageNormSq = 0;
|
||||
let diagHat = 0;
|
||||
|
||||
for (let j = 0; j < n; j++) {
|
||||
for (let j = start; j < end; j++) {
|
||||
const w = wBuf[j];
|
||||
if (w <= 0) continue;
|
||||
const lj = w / sw + (useSlope ? (w * (xs[j] - mx) * dx0) / sxxW : 0);
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { i18nStore, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
@@ -20,9 +21,13 @@ function formatConvOptionMeta(c) {
|
||||
if (!c) return '';
|
||||
const subs = Number(c.subagentCount || 0);
|
||||
if (subs > 0) {
|
||||
return `主${c.stepCount || 0} · ${subs}子 (共${c.totalStepCount || c.stepCount || 0}步)`;
|
||||
return t('header.convMetaWithSubs', {
|
||||
main: c.stepCount || 0,
|
||||
subs,
|
||||
total: c.totalStepCount || c.stepCount || 0,
|
||||
});
|
||||
}
|
||||
return `${c.stepCount || 0}步`;
|
||||
return t('header.convMetaSteps', { count: c.stepCount || 0 });
|
||||
}
|
||||
|
||||
export const TopSessionHeader = defineComponent({
|
||||
@@ -30,8 +35,8 @@ export const TopSessionHeader = defineComponent({
|
||||
setup({ onCleanup }) {
|
||||
const convSelect = CustomSelect({
|
||||
modelValue: telemetryStore.getState().selectedConversationId,
|
||||
placeholder: '跟随最新会话',
|
||||
options: [{ value: '', label: '跟随最新会话' }],
|
||||
placeholder: t('header.followLatest'),
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
@@ -40,7 +45,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
|
||||
const updateBtnIcon = createSvgIcon('arrow-down', { size: 11 });
|
||||
const updateBtnText = h('span', { text: '有新版本' });
|
||||
const updateBtnText = h('span', { text: t('header.hasUpdate') });
|
||||
let isHeaderUpdating = false;
|
||||
const updateBtn = h(
|
||||
'button',
|
||||
@@ -48,11 +53,11 @@ export const TopSessionHeader = defineComponent({
|
||||
type: 'button',
|
||||
className: 'update-badge-btn',
|
||||
hidden: true,
|
||||
'aria-label': '发现新版本,点击升级',
|
||||
'aria-label': t('header.ariaUpdate'),
|
||||
onClick: async () => {
|
||||
if (isHeaderUpdating) return;
|
||||
isHeaderUpdating = true;
|
||||
patchText(updateBtnText, '升级中…');
|
||||
patchText(updateBtnText, t('header.upgrading'));
|
||||
patchAttr(updateBtn, 'disabled', true);
|
||||
try {
|
||||
const res = await triggerPluginUpdate();
|
||||
@@ -67,7 +72,9 @@ export const TopSessionHeader = defineComponent({
|
||||
const cs = telemetryStore.getState().telemetry?.cloudStatus;
|
||||
patchText(
|
||||
updateBtnText,
|
||||
cs?.latestPluginVersion ? `升级 v${cs.latestPluginVersion}` : '有新版本'
|
||||
cs?.latestPluginVersion
|
||||
? t('header.upgradeToVer', { ver: cs.latestPluginVersion })
|
||||
: t('header.hasUpdate')
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -76,7 +83,7 @@ export const TopSessionHeader = defineComponent({
|
||||
);
|
||||
|
||||
const statusIcon = createSvgIcon('pulse', { size: 12 });
|
||||
const statusText = h('span', { text: '实时 2s' });
|
||||
const statusText = h('span', { text: t('header.statusLive') });
|
||||
const statusTag = h('span', { className: 'status-tag' }, [statusIcon, statusText]);
|
||||
|
||||
const refreshBtn = h(
|
||||
@@ -84,7 +91,7 @@ export const TopSessionHeader = defineComponent({
|
||||
{
|
||||
type: 'button',
|
||||
className: 'icon-btn',
|
||||
'aria-label': '刷新数据',
|
||||
'aria-label': t('header.ariaRefresh'),
|
||||
onClick: () => fetchTelemetry({ force: true }),
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 13 })]
|
||||
@@ -114,6 +121,9 @@ export const TopSessionHeader = defineComponent({
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
|
||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||
patchAttr(refreshBtn, 'aria-label', t('header.ariaRefresh'));
|
||||
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||
@@ -122,12 +132,12 @@ export const TopSessionHeader = defineComponent({
|
||||
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||
: null;
|
||||
const defaultOptLabel = hostRouteId
|
||||
? hostMatchedConv?.title
|
||||
? `当前窗口 (${hostMatchedConv.title})`
|
||||
: `当前窗口 (${hostRouteId.slice(0, 8)})`
|
||||
? t('header.currentWindowNamed', {
|
||||
title: hostMatchedConv?.title || hostRouteId.slice(0, 8),
|
||||
})
|
||||
: convs[0]?.title
|
||||
? `最新 (${convs[0].title})`
|
||||
: '跟随最新会话';
|
||||
? t('header.latestNamed', { title: convs[0].title })
|
||||
: t('header.followLatest');
|
||||
const defaultOptMeta = hostRouteId
|
||||
? hostMatchedConv
|
||||
? formatConvOptionMeta({
|
||||
@@ -153,14 +163,14 @@ export const TopSessionHeader = defineComponent({
|
||||
const lockedTitle =
|
||||
isLoadedLocked && actConv?.title
|
||||
? actConv.title
|
||||
: `已锁定会话 (${String(lockedId).slice(0, 8)})`;
|
||||
: t('header.lockedSession', { id: String(lockedId).slice(0, 8) });
|
||||
const lockedMeta = isLoadedLocked
|
||||
? formatConvOptionMeta({
|
||||
stepCount: actConv.stepCount,
|
||||
subagentCount: actConv.subagentCount,
|
||||
totalStepCount: actConv.totalStepsAllAgents,
|
||||
})
|
||||
: '已锁定';
|
||||
: t('header.lockedMeta');
|
||||
options.splice(1, 0, {
|
||||
value: lockedId,
|
||||
label: lockedTitle,
|
||||
@@ -169,6 +179,7 @@ export const TopSessionHeader = defineComponent({
|
||||
}
|
||||
convSelect.setProps({
|
||||
modelValue: telSt.selectedConversationId,
|
||||
placeholder: t('header.followLatest'),
|
||||
options,
|
||||
});
|
||||
|
||||
@@ -186,8 +197,8 @@ export const TopSessionHeader = defineComponent({
|
||||
patchText(
|
||||
updateBtnText,
|
||||
cloudStatus?.latestPluginVersion
|
||||
? `升级 v${cloudStatus.latestPluginVersion}`
|
||||
: '有新版本'
|
||||
? t('header.upgradeToVer', { ver: cloudStatus.latestPluginVersion })
|
||||
: t('header.hasUpdate')
|
||||
);
|
||||
}
|
||||
|
||||
@@ -203,7 +214,7 @@ export const TopSessionHeader = defineComponent({
|
||||
|
||||
if (isSyncing) {
|
||||
patchSvgIcon(statusIcon, 'refresh');
|
||||
patchText(statusText, '同步中');
|
||||
patchText(statusText, t('header.statusSyncing'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
@@ -211,7 +222,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else if (isSynced) {
|
||||
patchSvgIcon(statusIcon, 'check');
|
||||
patchText(statusText, '已刷新');
|
||||
patchText(statusText, t('header.statusSynced'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
@@ -219,7 +230,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else if (isError) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, '重试中');
|
||||
patchText(statusText, t('header.statusRetrying'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
@@ -230,7 +241,7 @@ export const TopSessionHeader = defineComponent({
|
||||
const runSuffix =
|
||||
hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : '';
|
||||
patchSvgIcon(statusIcon, 'bolt');
|
||||
patchText(statusText, `生成中${runSuffix}`);
|
||||
patchText(statusText, t('header.statusGenerating', { suffix: runSuffix }));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': true,
|
||||
'state-synced': false,
|
||||
@@ -238,7 +249,10 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else if (quotaStale) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线');
|
||||
patchText(
|
||||
statusText,
|
||||
quotaMeta?.hasOfficialData ? t('header.statusQuotaCached') : t('header.statusQuotaOffline')
|
||||
);
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
@@ -246,7 +260,7 @@ export const TopSessionHeader = defineComponent({
|
||||
});
|
||||
} else {
|
||||
patchSvgIcon(statusIcon, 'pulse');
|
||||
patchText(statusText, '实时 2s');
|
||||
patchText(statusText, t('header.statusLive'));
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
@@ -265,8 +279,14 @@ export const TopSessionHeader = defineComponent({
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubTelemetry();
|
||||
unsubI18n();
|
||||
convSelect.destroy();
|
||||
});
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,162 @@
|
||||
/**
|
||||
* @fileoverview Reusable Accordion / Collapsible Section (`CollapsibleSection.js`)
|
||||
* for `SettingsStructureTab`.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
export const CollapsibleSection = defineComponent({
|
||||
name: 'CollapsibleSection',
|
||||
setup({ props, onCleanup }) {
|
||||
let expanded = Boolean(props.defaultExpanded);
|
||||
let statusTimer = null;
|
||||
|
||||
const chevronIcon = createSvgIcon('chevron-right', {
|
||||
size: 12,
|
||||
className: 'collapsible-chevron',
|
||||
});
|
||||
const sectionIcon = props.icon ? createSvgIcon(props.icon, { size: 13 }) : null;
|
||||
const titleTextEl = h('span', {
|
||||
className: 'collapsible-title-text',
|
||||
text: props.title || '',
|
||||
});
|
||||
|
||||
const triggerChildren = [chevronIcon];
|
||||
if (sectionIcon) triggerChildren.push(sectionIcon);
|
||||
triggerChildren.push(titleTextEl);
|
||||
|
||||
const triggerBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'collapsible-trigger',
|
||||
'aria-expanded': expanded ? 'true' : 'false',
|
||||
onClick: () => {
|
||||
setExpanded(!expanded);
|
||||
if (typeof props.onToggle === 'function') {
|
||||
props.onToggle(expanded);
|
||||
}
|
||||
},
|
||||
},
|
||||
triggerChildren
|
||||
);
|
||||
|
||||
const statusTextEl = h('span', { className: 'collapsible-status', text: '' });
|
||||
const badgeEl = h('span', {
|
||||
className: 'collapsible-badge text-mono',
|
||||
hidden: !props.badgeText,
|
||||
text: props.badgeText || '',
|
||||
});
|
||||
|
||||
const resetBtnText = h('span', { text: props.resetLabel || t('settings.resetBtn') });
|
||||
const resetBtn =
|
||||
typeof props.onReset === 'function'
|
||||
? h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm',
|
||||
disabled: props.resetDisabled !== false,
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
props.onReset();
|
||||
},
|
||||
},
|
||||
[resetBtnText]
|
||||
)
|
||||
: null;
|
||||
|
||||
const rightChildren = [statusTextEl, badgeEl];
|
||||
if (resetBtn) rightChildren.push(resetBtn);
|
||||
|
||||
const headerRow = h('div', { className: 'collapsible-header-row' }, [
|
||||
triggerBtn,
|
||||
h('span', { className: 'collapsible-right' }, rightChildren),
|
||||
]);
|
||||
|
||||
const bodyEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'collapsible-body',
|
||||
hidden: !expanded,
|
||||
},
|
||||
Array.isArray(props.children) ? props.children : []
|
||||
);
|
||||
|
||||
const sectionEl = h(
|
||||
'section',
|
||||
{
|
||||
className: `panel collapsible-section${expanded ? ' is-expanded' : ''}`,
|
||||
},
|
||||
[headerRow, bodyEl]
|
||||
);
|
||||
|
||||
function setExpanded(next) {
|
||||
expanded = Boolean(next);
|
||||
patchClasses(sectionEl, { 'is-expanded': expanded });
|
||||
patchAttr(triggerBtn, 'aria-expanded', expanded ? 'true' : 'false');
|
||||
patchAttr(bodyEl, 'hidden', !expanded);
|
||||
}
|
||||
|
||||
function setTitle(text) {
|
||||
patchText(titleTextEl, text || '');
|
||||
}
|
||||
|
||||
function setBadge(text) {
|
||||
patchAttr(badgeEl, 'hidden', !text);
|
||||
patchText(badgeEl, text || '');
|
||||
}
|
||||
|
||||
function setResetLabel(text) {
|
||||
if (resetBtn) {
|
||||
patchText(resetBtnText, text || t('settings.resetBtn'));
|
||||
}
|
||||
}
|
||||
|
||||
function setResetDisabled(disabled) {
|
||||
if (resetBtn) {
|
||||
patchAttr(resetBtn, 'disabled', Boolean(disabled));
|
||||
}
|
||||
}
|
||||
|
||||
function showStatus(text, autoClearMs = 1500) {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
patchText(statusTextEl, text || '');
|
||||
if (text && autoClearMs > 0) {
|
||||
statusTimer = setTimeout(() => {
|
||||
statusTimer = null;
|
||||
patchText(statusTextEl, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
el: sectionEl,
|
||||
refs: {
|
||||
triggerBtn,
|
||||
bodyEl,
|
||||
resetBtn,
|
||||
setExpanded,
|
||||
isExpanded: () => expanded,
|
||||
setTitle,
|
||||
setBadge,
|
||||
setResetLabel,
|
||||
setResetDisabled,
|
||||
showStatus,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* @fileoverview Reusable `+` / `-` / `↑` / `↓` Dynamic Slot List (`EditableSlotList.js`).
|
||||
* Powers Topbar Capsule Slots (1..5), Hover Popup Modules (0..4),
|
||||
* Live Overview Modules (1..4), First-Row Metrics (1..4), and Step Table Columns (2..12).
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
|
||||
export const EditableSlotList = defineComponent({
|
||||
name: 'EditableSlotList',
|
||||
setup({ props, onCleanup }) {
|
||||
const minItems = Math.max(0, Number(props.minItems ?? 1));
|
||||
const maxItems = Math.max(minItems, Number(props.maxItems ?? 5));
|
||||
let currentItems = Array.isArray(props.items) ? [...props.items] : [];
|
||||
let currentOptions = Array.isArray(props.options) ? [...props.options] : [];
|
||||
let emptyHintText = String(props.emptyHintText || '');
|
||||
let addBtnTextFn = typeof props.addBtnTextFn === 'function' ? props.addBtnTextFn : null;
|
||||
|
||||
const listEl = h('div', { className: 'editable-slot-list' });
|
||||
const emptyEl = h('div', {
|
||||
className: 'editable-slot-empty',
|
||||
hidden: true,
|
||||
text: emptyHintText,
|
||||
});
|
||||
|
||||
const addBtnLabel = h('span', { text: '' });
|
||||
const addBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-add-btn',
|
||||
onClick: () => {
|
||||
if (currentItems.length >= maxItems) return;
|
||||
const usedSet = new Set(currentItems);
|
||||
const nextOpt = currentOptions.find((opt) => !usedSet.has(opt.value));
|
||||
if (!nextOpt) return;
|
||||
emitChange([...currentItems, nextOpt.value]);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('plus', { size: 11 }), addBtnLabel]
|
||||
);
|
||||
|
||||
const footerEl = h('div', { className: 'editable-slot-footer' }, [addBtn]);
|
||||
const rootEl = h('div', { className: 'editable-slot-wrap' }, [emptyEl, listEl, footerEl]);
|
||||
|
||||
const rowPool = [];
|
||||
|
||||
function emitChange(nextItems) {
|
||||
currentItems = [...nextItems];
|
||||
syncRows();
|
||||
if (typeof props.onChange === 'function') {
|
||||
props.onChange([...currentItems]);
|
||||
}
|
||||
}
|
||||
|
||||
function createSlotRow() {
|
||||
let rowIndex = 0;
|
||||
const indexBadge = h('span', { className: 'slot-index-badge text-mono', text: '1' });
|
||||
const selectComp = CustomSelect({
|
||||
modelValue: '',
|
||||
options: [],
|
||||
onUpdateModelValue: (nextVal) => {
|
||||
if (!nextVal || currentItems[rowIndex] === nextVal) return;
|
||||
if (currentItems.some((v, idx) => idx !== rowIndex && v === nextVal)) return;
|
||||
const next = [...currentItems];
|
||||
next[rowIndex] = nextVal;
|
||||
emitChange(next);
|
||||
},
|
||||
});
|
||||
|
||||
const upBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (rowIndex <= 0) return;
|
||||
const next = [...currentItems];
|
||||
const tmp = next[rowIndex - 1];
|
||||
next[rowIndex - 1] = next[rowIndex];
|
||||
next[rowIndex] = tmp;
|
||||
emitChange(next);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-up', { size: 12 })]
|
||||
);
|
||||
|
||||
const downBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (rowIndex >= currentItems.length - 1) return;
|
||||
const next = [...currentItems];
|
||||
const tmp = next[rowIndex + 1];
|
||||
next[rowIndex + 1] = next[rowIndex];
|
||||
next[rowIndex] = tmp;
|
||||
emitChange(next);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-down', { size: 12 })]
|
||||
);
|
||||
|
||||
const removeBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn slot-remove-btn',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (currentItems.length <= minItems) return;
|
||||
const next = currentItems.filter((_, idx) => idx !== rowIndex);
|
||||
emitChange(next);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('minus', { size: 12 })]
|
||||
);
|
||||
|
||||
const rowEl = h('div', { className: 'editable-slot-row' }, [
|
||||
indexBadge,
|
||||
selectComp.el,
|
||||
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn, removeBtn]),
|
||||
]);
|
||||
|
||||
return {
|
||||
rowEl,
|
||||
indexBadge,
|
||||
selectComp,
|
||||
upBtn,
|
||||
downBtn,
|
||||
removeBtn,
|
||||
setIndex(idx) {
|
||||
rowIndex = idx;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncRows() {
|
||||
const count = currentItems.length;
|
||||
patchAttr(emptyEl, 'hidden', count > 0 || !emptyHintText);
|
||||
if (emptyHintText) {
|
||||
patchText(emptyEl, emptyHintText);
|
||||
}
|
||||
patchAttr(listEl, 'hidden', count === 0);
|
||||
|
||||
while (rowPool.length < count) {
|
||||
rowPool.push(createSlotRow());
|
||||
}
|
||||
|
||||
while (listEl.children && listEl.children.length > count) {
|
||||
const tailIdx = listEl.children.length - 1;
|
||||
const tailChild = listEl.children[tailIdx];
|
||||
tailChild?.remove?.();
|
||||
}
|
||||
|
||||
const canRemove = count > minItems;
|
||||
const removeTitle = canRemove
|
||||
? t('settings.slot.remove')
|
||||
: t('settings.slot.minReached', { min: minItems });
|
||||
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const entry = rowPool[i];
|
||||
const itemVal = currentItems[i];
|
||||
entry.setIndex(i);
|
||||
patchAttr(entry.rowEl, 'data-slot-row', String(i));
|
||||
patchText(entry.indexBadge, String(i + 1));
|
||||
|
||||
const otherUsed = new Set(currentItems.filter((_, idx) => idx !== i));
|
||||
const rowOpts = currentOptions.map((opt) => {
|
||||
const isTaken = otherUsed.has(opt.value);
|
||||
return isTaken
|
||||
? {
|
||||
...opt,
|
||||
disabled: true,
|
||||
meta: t('settings.slot.alreadyAdded'),
|
||||
}
|
||||
: opt;
|
||||
});
|
||||
|
||||
entry.selectComp.setProps({
|
||||
modelValue: itemVal,
|
||||
options: rowOpts,
|
||||
});
|
||||
|
||||
patchAttr(entry.upBtn, 'disabled', i === 0);
|
||||
patchAttr(entry.upBtn, 'title', t('settings.slot.moveUp'));
|
||||
patchAttr(entry.upBtn, 'aria-label', t('settings.slot.moveUp'));
|
||||
|
||||
patchAttr(entry.downBtn, 'disabled', i === count - 1);
|
||||
patchAttr(entry.downBtn, 'title', t('settings.slot.moveDown'));
|
||||
patchAttr(entry.downBtn, 'aria-label', t('settings.slot.moveDown'));
|
||||
|
||||
patchAttr(entry.removeBtn, 'disabled', !canRemove);
|
||||
patchAttr(entry.removeBtn, 'title', removeTitle);
|
||||
patchAttr(entry.removeBtn, 'aria-label', removeTitle);
|
||||
|
||||
if (!listEl.children || listEl.children[i] !== entry.rowEl) {
|
||||
listEl.appendChild(entry.rowEl);
|
||||
}
|
||||
}
|
||||
|
||||
// Close any hidden pooled selects
|
||||
for (let j = count; j < rowPool.length; j += 1) {
|
||||
rowPool[j].selectComp.close();
|
||||
}
|
||||
|
||||
const usedAll = new Set(currentItems);
|
||||
const hasAvailableOption = currentOptions.some((opt) => !usedAll.has(opt.value));
|
||||
const disableAdd = count >= maxItems || !hasAvailableOption;
|
||||
patchAttr(addBtn, 'disabled', disableAdd);
|
||||
const addLabel = addBtnTextFn
|
||||
? addBtnTextFn(count, maxItems)
|
||||
: `+ (${count}/${maxItems})`;
|
||||
patchText(addBtnLabel, addLabel);
|
||||
}
|
||||
|
||||
function setProps(next = {}) {
|
||||
if (Array.isArray(next.items)) {
|
||||
currentItems = [...next.items];
|
||||
}
|
||||
if (Array.isArray(next.options)) {
|
||||
currentOptions = [...next.options];
|
||||
}
|
||||
if (next.emptyHintText !== undefined) {
|
||||
emptyHintText = String(next.emptyHintText || '');
|
||||
}
|
||||
if (typeof next.addBtnTextFn === 'function') {
|
||||
addBtnTextFn = next.addBtnTextFn;
|
||||
}
|
||||
syncRows();
|
||||
}
|
||||
|
||||
syncRows();
|
||||
|
||||
onCleanup(() => {
|
||||
for (const entry of rowPool) {
|
||||
entry.selectComp.destroy();
|
||||
}
|
||||
rowPool.length = 0;
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
listEl,
|
||||
addBtn,
|
||||
emptyEl,
|
||||
setProps,
|
||||
getItems: () => [...currentItems],
|
||||
getSelects: () => rowPool.slice(0, currentItems.length).map((r) => r.selectComp),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* @fileoverview Host-aware Theme Accent Swatch Picker (`ThemeColorPicker.js`).
|
||||
* Provides the default "跟随宿主" (`host`) pill plus 6 curated color swatches.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
THEME_ACCENT_PRESETS,
|
||||
normalizeClientThemeAccent,
|
||||
} from '../../core/appearance.js';
|
||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
export const ThemeColorPicker = defineComponent({
|
||||
name: 'ThemeColorPicker',
|
||||
setup({ props }) {
|
||||
let currentKey = normalizeClientThemeAccent(props.modelValue);
|
||||
|
||||
const hostLabelEl = h('span', { text: t('settings.gen.accentHost') });
|
||||
const hostBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'theme-host-chip',
|
||||
'data-accent-key': 'host',
|
||||
onClick: () => selectAccent('host'),
|
||||
},
|
||||
[hostLabelEl]
|
||||
);
|
||||
|
||||
const swatchPresets = THEME_ACCENT_PRESETS.filter((p) => p.key !== 'host');
|
||||
const swatchEntries = swatchPresets.map((preset) => {
|
||||
const checkIcon = createSvgIcon('check', { size: 11 });
|
||||
const btn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'theme-swatch-btn',
|
||||
'data-accent-key': preset.key,
|
||||
title: t(preset.labelKey),
|
||||
'aria-label': t(preset.labelKey),
|
||||
onClick: () => selectAccent(preset.key),
|
||||
},
|
||||
[checkIcon]
|
||||
);
|
||||
patchStyleVar(btn, '--swatch-color', preset.cssColor);
|
||||
return { preset, btn, checkIcon };
|
||||
});
|
||||
|
||||
const swatchGroup = h(
|
||||
'span',
|
||||
{ className: 'theme-swatch-group' },
|
||||
swatchEntries.map((s) => s.btn)
|
||||
);
|
||||
|
||||
const rootEl = h('div', { className: 'theme-color-picker' }, [hostBtn, swatchGroup]);
|
||||
|
||||
function syncVisuals() {
|
||||
const isHost = currentKey === 'host';
|
||||
patchClasses(hostBtn, { 'is-active': isHost });
|
||||
patchAttr(hostBtn, 'aria-pressed', isHost ? 'true' : 'false');
|
||||
for (const entry of swatchEntries) {
|
||||
const active = entry.preset.key === currentKey;
|
||||
patchClasses(entry.btn, { 'is-active': active });
|
||||
patchAttr(entry.btn, 'aria-pressed', active ? 'true' : 'false');
|
||||
patchAttr(entry.checkIcon, 'hidden', !active);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
patchText(hostLabelEl, t('settings.gen.accentHost'));
|
||||
for (const entry of swatchEntries) {
|
||||
const label = t(entry.preset.labelKey);
|
||||
patchAttr(entry.btn, 'title', label);
|
||||
patchAttr(entry.btn, 'aria-label', label);
|
||||
}
|
||||
}
|
||||
|
||||
function selectAccent(nextRaw) {
|
||||
const normalized = normalizeClientThemeAccent(nextRaw);
|
||||
if (normalized === currentKey) return;
|
||||
currentKey = normalized;
|
||||
syncVisuals();
|
||||
if (typeof props.onUpdateModelValue === 'function') {
|
||||
props.onUpdateModelValue(currentKey);
|
||||
}
|
||||
}
|
||||
|
||||
function setValue(nextRaw) {
|
||||
currentKey = normalizeClientThemeAccent(nextRaw);
|
||||
syncVisuals();
|
||||
}
|
||||
|
||||
syncVisuals();
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
hostBtn,
|
||||
swatchEntries,
|
||||
setValue,
|
||||
refreshLabels,
|
||||
getValue: () => currentKey,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
|
||||
function normalizeMultiSelection(rawValue, options = [], allValue = '') {
|
||||
@@ -120,6 +121,7 @@ export const CustomSelect = defineComponent({
|
||||
|
||||
function chooseOption(option) {
|
||||
if (!option) return;
|
||||
if (option.disabled && !getSelectedSet().has(option.value)) return;
|
||||
const { multiple, options = [], allValue = '', collapseAll = false } = getProps();
|
||||
if (!multiple) {
|
||||
const prevVal = getProps().modelValue;
|
||||
@@ -203,7 +205,7 @@ export const CustomSelect = defineComponent({
|
||||
patchKeyedList(menuEl, options, {
|
||||
keyFn: (opt) => opt.value,
|
||||
sigFn: (opt, idx) =>
|
||||
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
|
||||
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
|
||||
createRow: (opt) => {
|
||||
const checkboxIcon = createSvgIcon('check', { size: 10 });
|
||||
const checkboxBox = h('span', { className: 'select-checkbox', hidden: true }, [
|
||||
@@ -233,6 +235,7 @@ export const CustomSelect = defineComponent({
|
||||
const isMulti = Boolean(getProps().multiple);
|
||||
const selected = selSet.has(opt.value);
|
||||
const focused = idx === focusedIndex;
|
||||
const isDisabled = Boolean(opt.disabled && !selected);
|
||||
patchAttr(refs.checkboxBox, 'hidden', !isMulti);
|
||||
patchClasses(refs.checkboxBox, { 'is-checked': selected });
|
||||
patchAttr(refs.checkboxIcon, 'hidden', !selected);
|
||||
@@ -243,7 +246,10 @@ export const CustomSelect = defineComponent({
|
||||
patchClasses(el, {
|
||||
'is-selected': selected,
|
||||
'is-focused': focused,
|
||||
'is-disabled': isDisabled,
|
||||
});
|
||||
patchAttr(el, 'disabled', isDisabled);
|
||||
patchAttr(el, 'aria-disabled', isDisabled ? 'true' : null);
|
||||
patchAttr(el, 'aria-selected', selected ? 'true' : 'false');
|
||||
patchAttr(el, 'data-value', opt.value);
|
||||
},
|
||||
@@ -254,11 +260,11 @@ export const CustomSelect = defineComponent({
|
||||
const {
|
||||
options = [],
|
||||
modelValue,
|
||||
placeholder = '请选择',
|
||||
placeholder = t('fmt.selectPlaceholder'),
|
||||
icon,
|
||||
multiple = false,
|
||||
allValue = '',
|
||||
multiUnit = '项',
|
||||
multiUnit = isEnglishLocale() ? 'items' : '项',
|
||||
} = getProps();
|
||||
patchClasses(rootEl, { 'is-multi': Boolean(multiple) });
|
||||
patchAttr(leadIcon, 'hidden', !icon);
|
||||
@@ -281,8 +287,11 @@ export const CustomSelect = defineComponent({
|
||||
titleText = labelText;
|
||||
} else {
|
||||
const names = vals.map((v) => options.find((o) => String(o.value) === v)?.label || v);
|
||||
labelText = `已选 ${vals.length} ${multiUnit}`;
|
||||
titleText = `已选 (${vals.length}):${names.join('、')}`;
|
||||
labelText = t('fmt.selectedCount', { count: vals.length, unit: multiUnit });
|
||||
titleText = t('fmt.selectedListTitle', {
|
||||
count: vals.length,
|
||||
names: names.join(isEnglishLocale() ? ', ' : '、'),
|
||||
});
|
||||
}
|
||||
} else {
|
||||
const matchedOpt = options.find((o) => o.value === modelValue);
|
||||
|
||||
@@ -0,0 +1,497 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Context Window Widget (`ContextWindowWidget.js`).
|
||||
* Supports both interactive multi-agent inspector mode (`LiveOverviewView`)
|
||||
* and pointer-events-none in-place pre-allocated mode (`WindowOverlayShell` hover popup).
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokens, resolveModelDisplayInfo } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
resolveScopedConversation,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
import { ContextSegmentMeter } from '../ui/ContextSegmentMeter.js';
|
||||
|
||||
const CTX_PILL_BASE_PAD_PX = 14;
|
||||
const CTX_CJK_CHAR_PX = 11;
|
||||
const CTX_ASCII_CHAR_PX = 6.1;
|
||||
const CTX_PILL_GAP_PX = 4;
|
||||
const CTX_DEFAULT_BAR_WIDTH_PX = 310;
|
||||
|
||||
function estimateCtxPillWidth(text) {
|
||||
let w = CTX_PILL_BASE_PAD_PX;
|
||||
for (const ch of String(text || '')) {
|
||||
w += ch.charCodeAt(0) > 255 ? CTX_CJK_CHAR_PX : CTX_ASCII_CHAR_PX;
|
||||
}
|
||||
return Math.ceil(w);
|
||||
}
|
||||
|
||||
/**
|
||||
* 10 通道上下文窗口构成定义(通过动态 getter 自动跟随当前激活语言)。
|
||||
*/
|
||||
export const CTX_CHANNEL_DEFS = [
|
||||
{
|
||||
key: 'assistant',
|
||||
labelKey: 'ctx.ch.assistant',
|
||||
titleKey: 'ctx.ch.assistantTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-assistant',
|
||||
getValue: (c) => Number(c.assistantTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'toolResults',
|
||||
labelKey: 'ctx.ch.toolResults',
|
||||
titleKey: 'ctx.ch.toolResultsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-tool-results',
|
||||
getValue: (c) => Number(c.toolResultsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userInput',
|
||||
labelKey: 'ctx.ch.userInput',
|
||||
titleKey: 'ctx.ch.userInputTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-user-input',
|
||||
getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{
|
||||
key: 'subagent',
|
||||
labelKey: 'ctx.ch.subagent',
|
||||
titleKey: 'ctx.ch.subagentTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-subagent-msg',
|
||||
getValue: (c) => Number(c.subagentTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'checkpoint',
|
||||
labelKey: 'ctx.ch.checkpoint',
|
||||
titleKey: 'ctx.ch.checkpointTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-checkpoint',
|
||||
getValue: (c) => Number(c.checkpointTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemPrompt',
|
||||
labelKey: 'ctx.ch.systemPrompt',
|
||||
titleKey: 'ctx.ch.systemPromptTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-system-prompt',
|
||||
getValue: (c) => Number(c.systemPromptTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemTools',
|
||||
labelKey: 'ctx.ch.systemTools',
|
||||
titleKey: 'ctx.ch.systemToolsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-system-tools',
|
||||
getValue: (c) => Number(c.systemToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'mcpTools',
|
||||
labelKey: 'ctx.ch.mcpTools',
|
||||
titleKey: 'ctx.ch.mcpToolsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-mcp-tools',
|
||||
getValue: (c) => Number(c.mcpToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'skills',
|
||||
labelKey: 'ctx.ch.skills',
|
||||
titleKey: 'ctx.ch.skillsTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-skills',
|
||||
getValue: (c) => Number(c.skillsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userRules',
|
||||
labelKey: 'ctx.ch.userRules',
|
||||
titleKey: 'ctx.ch.userRulesTitle',
|
||||
get label() {
|
||||
return t(this.labelKey);
|
||||
},
|
||||
get title() {
|
||||
return t(this.titleKey);
|
||||
},
|
||||
segClass: 'seg-user-rules',
|
||||
getValue: (c) => Number(c.userRulesTokens || 0),
|
||||
},
|
||||
];
|
||||
|
||||
export const ContextWindowWidget = defineComponent({
|
||||
name: 'ContextWindowWidget',
|
||||
setup({ props, onCleanup }) {
|
||||
const interactiveInspector = props.interactiveInspector !== false;
|
||||
const isVisibleFn =
|
||||
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
|
||||
|
||||
const titleTextEl = h('span', { text: t('module.context') });
|
||||
const ctxAgentBadge = h('span', {
|
||||
className: 'agent-badge badge-main',
|
||||
hidden: true,
|
||||
text: t('fmt.mainAgent'),
|
||||
});
|
||||
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
|
||||
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
|
||||
|
||||
const ctxPillGroup = h('div', { className: 'ctx-pill-group' });
|
||||
const ctxInspectorBar = h(
|
||||
'div',
|
||||
{ className: 'ctx-inspector-bar', hidden: true },
|
||||
[ctxPillGroup]
|
||||
);
|
||||
|
||||
const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => {
|
||||
const swatchEl = h('span', { className: `swatch ${ch.segClass}` });
|
||||
const labelEl = h('span', { text: ch.label });
|
||||
const valEl = h('strong', { className: 'text-mono', text: '0' });
|
||||
const itemEl = h(
|
||||
'div',
|
||||
{ className: 'legend-item', ...(interactiveInspector ? { title: ch.title } : {}) },
|
||||
[h('span', { className: 'legend-left' }, [swatchEl, labelEl]), valEl]
|
||||
);
|
||||
return { ch, defaultOrder: idx, swatchEl, labelEl, valEl, itemEl };
|
||||
});
|
||||
|
||||
const ctxLegendGrid = h(
|
||||
'div',
|
||||
{ className: 'ctx-legend-grid' },
|
||||
ctxChannels.map((entry) => entry.itemEl)
|
||||
);
|
||||
let lastLegendOrderSig = ctxChannels.map((entry) => entry.ch.key).join(',');
|
||||
let lastLocale = getEffectiveLocale();
|
||||
|
||||
const children = [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('layers', { size: 13 }),
|
||||
titleTextEl,
|
||||
ctxAgentBadge,
|
||||
]),
|
||||
h('span', { className: 'panel-meta' }, [ctxSummaryText]),
|
||||
]),
|
||||
];
|
||||
if (interactiveInspector) {
|
||||
children.push(ctxInspectorBar);
|
||||
}
|
||||
children.push(ctxSegmentBar.el, ctxLegendGrid);
|
||||
|
||||
const ctxPanel = h('section', { className: 'panel' }, children);
|
||||
|
||||
let latestData = null;
|
||||
let ctxPillsExpanded = false;
|
||||
let lastCascadeId = '';
|
||||
let cachedBarWidth = 0;
|
||||
|
||||
function update({ data } = {}) {
|
||||
latestData = data || null;
|
||||
const curLocale = getEffectiveLocale();
|
||||
patchText(titleTextEl, t('module.context'));
|
||||
|
||||
if (!data) {
|
||||
if (curLocale !== lastLocale) {
|
||||
lastLocale = curLocale;
|
||||
for (const entry of ctxChannels) {
|
||||
patchText(entry.labelEl, entry.ch.label);
|
||||
if (interactiveInspector) {
|
||||
patchAttr(entry.itemEl, 'title', entry.ch.title);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let availRowWidth = CTX_DEFAULT_BAR_WIDTH_PX;
|
||||
if (interactiveInspector) {
|
||||
const measuredWidth =
|
||||
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
|
||||
if (measuredWidth > 160) {
|
||||
cachedBarWidth = measuredWidth;
|
||||
}
|
||||
availRowWidth = cachedBarWidth > 160 ? cachedBarWidth : CTX_DEFAULT_BAR_WIDTH_PX;
|
||||
|
||||
const currentCascadeId = data.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && currentCascadeId !== lastCascadeId) {
|
||||
if (lastCascadeId) {
|
||||
ctxPillsExpanded = false;
|
||||
}
|
||||
lastCascadeId = currentCascadeId;
|
||||
}
|
||||
}
|
||||
|
||||
const uiSt = uiStore.getState();
|
||||
const {
|
||||
hasSubagents,
|
||||
effectiveCtxScope,
|
||||
agents,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
ctxAgent,
|
||||
} = resolveScopedConversation(data, 'all', uiSt.ctxInspectorAgentId);
|
||||
|
||||
const active = scopedConv || data.activeConversation || {};
|
||||
const ctx = ctxAgent?.context || active.context || {};
|
||||
|
||||
patchAttr(ctxAgentBadge, 'hidden', !(hasSubagents && ctxAgent));
|
||||
if (hasSubagents && ctxAgent) {
|
||||
const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain));
|
||||
patchAttr(ctxAgentBadge, 'class', `agent-badge ${badgeCls}`);
|
||||
const badgeFullText = formatAgentLabel(ctxAgent);
|
||||
patchText(ctxAgentBadge, badgeFullText);
|
||||
if (interactiveInspector) {
|
||||
patchAttr(ctxAgentBadge, 'title', badgeFullText);
|
||||
}
|
||||
}
|
||||
|
||||
if (interactiveInspector) {
|
||||
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
|
||||
if (hasSubagents && ctxAgent) {
|
||||
const rawActiveBadge = aggregated?.activeAgentBadge || '主';
|
||||
const activeBadgeText = isEnglishLocale()
|
||||
? rawActiveBadge === '主'
|
||||
? t('fmt.mainBadge')
|
||||
: rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n }))
|
||||
: rawActiveBadge;
|
||||
|
||||
const pillItems = [
|
||||
{
|
||||
key: 'auto',
|
||||
label: t('ctx.followActive', { badge: activeBadgeText }),
|
||||
title: t('ctx.followActiveTitle'),
|
||||
isActive: effectiveCtxScope === 'auto',
|
||||
mode: 'ctx-only',
|
||||
},
|
||||
];
|
||||
|
||||
const allAgentPills = agents.map((ag) => {
|
||||
const agPct = ag.context?.usedPct ?? 0;
|
||||
const agModelDisplay = resolveModelDisplayInfo(ag, data.settings, {
|
||||
fallback: t('fmt.unknownModel'),
|
||||
}).text;
|
||||
const badgeLabel = formatAgentBadgeText(ag);
|
||||
return {
|
||||
key: ag.agentId,
|
||||
label: `${badgeLabel} ${agPct}%`,
|
||||
title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${t('header.convMetaSteps', { count: ag.stepCount || 0 })})`,
|
||||
isActive: effectiveCtxScope === ag.agentId,
|
||||
mode: 'ctx-only',
|
||||
};
|
||||
});
|
||||
|
||||
const firstPillWidth =
|
||||
pillItems.length > 0 ? estimateCtxPillWidth(pillItems[0].label) : 0;
|
||||
const totalAllWidth = allAgentPills.reduce(
|
||||
(sum, p) => sum + CTX_PILL_GAP_PX + estimateCtxPillWidth(p.label),
|
||||
firstPillWidth
|
||||
);
|
||||
const needsCollapse = totalAllWidth > availRowWidth && allAgentPills.length > 2;
|
||||
|
||||
if (needsCollapse && !ctxPillsExpanded) {
|
||||
const toggleSample = t('ctx.expandMore', { count: allAgentPills.length });
|
||||
const toggleReservePx = CTX_PILL_GAP_PX + estimateCtxPillWidth(toggleSample);
|
||||
let usedW = firstPillWidth;
|
||||
let fitCount = 0;
|
||||
for (let i = 0; i < allAgentPills.length; i += 1) {
|
||||
const pw = CTX_PILL_GAP_PX + estimateCtxPillWidth(allAgentPills[i].label);
|
||||
if (fitCount >= 1 && usedW + pw + toggleReservePx > availRowWidth) {
|
||||
break;
|
||||
}
|
||||
usedW += pw;
|
||||
fitCount += 1;
|
||||
}
|
||||
const maxKeep = Math.max(1, allAgentPills.length - 2);
|
||||
const maxCollapsedCount = Math.max(1, Math.min(maxKeep, fitCount));
|
||||
const visibleAgentPills = allAgentPills.slice(0, maxCollapsedCount);
|
||||
const activeHiddenPill = allAgentPills
|
||||
.slice(maxCollapsedCount)
|
||||
.find((p) => p.isActive);
|
||||
if (activeHiddenPill) {
|
||||
if (visibleAgentPills.length >= 2) {
|
||||
visibleAgentPills[visibleAgentPills.length - 1] = activeHiddenPill;
|
||||
} else {
|
||||
visibleAgentPills.push(activeHiddenPill);
|
||||
}
|
||||
}
|
||||
const hiddenCount = allAgentPills.length - visibleAgentPills.length;
|
||||
pillItems.push(...visibleAgentPills, {
|
||||
key: '__toggle_more__',
|
||||
label: t('ctx.expandMore', { count: hiddenCount }),
|
||||
title: t('ctx.expandMoreTitle', { count: allAgentPills.length - 1 }),
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
} else {
|
||||
pillItems.push(...allAgentPills);
|
||||
if (needsCollapse) {
|
||||
pillItems.push({
|
||||
key: '__toggle_more__',
|
||||
label: t('ctx.collapse'),
|
||||
title: t('ctx.collapseTitle'),
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
patchKeyedList(ctxPillGroup, pillItems, {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: (item) =>
|
||||
`${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`,
|
||||
createRow: () => {
|
||||
const btn = h('button', { type: 'button', className: 'ctx-agent-pill' });
|
||||
return { el: btn, refs: { btn } };
|
||||
},
|
||||
updateRow: (refs, item) => {
|
||||
patchText(refs.btn, item.label);
|
||||
patchAttr(refs.btn, 'title', item.title);
|
||||
patchClasses(refs.btn, {
|
||||
'is-active': item.isActive,
|
||||
'is-more-toggle': Boolean(item.isMoreToggle),
|
||||
});
|
||||
refs.btn.onclick = () => {
|
||||
if (item.mode === 'toggle-expand') {
|
||||
ctxPillsExpanded = !ctxPillsExpanded;
|
||||
if (latestData) update({ data: latestData });
|
||||
} else {
|
||||
uiStore.setState({ ctxInspectorAgentId: item.key });
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||
patchText(
|
||||
ctxSummaryText,
|
||||
`${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)`
|
||||
);
|
||||
ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } });
|
||||
|
||||
if (interactiveInspector) {
|
||||
const localeChanged = curLocale !== lastLocale;
|
||||
lastLocale = curLocale;
|
||||
const scored = ctxChannels.map((entry) => {
|
||||
const val = entry.ch.getValue(ctx);
|
||||
if (localeChanged) {
|
||||
patchText(entry.labelEl, entry.ch.label);
|
||||
patchAttr(entry.itemEl, 'title', entry.ch.title);
|
||||
}
|
||||
patchText(entry.valEl, formatTokens(val));
|
||||
return { entry, val };
|
||||
});
|
||||
scored.sort((a, b) => b.val - a.val || a.entry.defaultOrder - b.entry.defaultOrder);
|
||||
const nextLegendOrderSig = scored.map((x) => x.entry.ch.key).join(',');
|
||||
if (nextLegendOrderSig !== lastLegendOrderSig) {
|
||||
lastLegendOrderSig = nextLegendOrderSig;
|
||||
for (const { entry } of scored) {
|
||||
ctxLegendGrid.appendChild(entry.itemEl);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
lastLocale = curLocale;
|
||||
const scoredChannels = CTX_CHANNEL_DEFS.map((ch, defaultOrder) => ({
|
||||
ch,
|
||||
defaultOrder,
|
||||
val: ch.getValue(ctx),
|
||||
}));
|
||||
scoredChannels.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder);
|
||||
for (let i = 0; i < ctxChannels.length; i += 1) {
|
||||
const slot = ctxChannels[i];
|
||||
const item = scoredChannels[i];
|
||||
if (!slot || !item) continue;
|
||||
patchAttr(slot.swatchEl, 'class', `swatch ${item.ch.segClass}`);
|
||||
patchText(slot.labelEl, item.ch.label);
|
||||
patchText(slot.valEl, formatTokens(item.val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let ro = null;
|
||||
if (interactiveInspector && typeof ResizeObserver !== 'undefined') {
|
||||
ro = new ResizeObserver(() => {
|
||||
if (!isVisibleFn()) return;
|
||||
const nextW =
|
||||
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
|
||||
if (nextW > 160 && Math.abs(nextW - cachedBarWidth) >= 6) {
|
||||
cachedBarWidth = nextW;
|
||||
if (latestData?.activeConversation?.hasSubagents) {
|
||||
update({ data: latestData });
|
||||
}
|
||||
}
|
||||
});
|
||||
ro.observe(ctxPanel);
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (ro) ro.disconnect();
|
||||
ctxSegmentBar.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: ctxPanel,
|
||||
refs: { update, ctxSegmentBar },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,478 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`).
|
||||
* Displays active multi-session running conversations & collapsible subagent activity
|
||||
* with an isolated 1s elapsed timer lifecycle.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatElapsedSec } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
formatAgentBadgeText,
|
||||
getAgentBadgeClass,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
|
||||
export const LiveActivityWidget = defineComponent({
|
||||
name: 'LiveActivityWidget',
|
||||
setup({ props, onCleanup }) {
|
||||
const interactive = props.interactive !== false;
|
||||
const isVisibleFn =
|
||||
typeof props.isVisibleFn === 'function' ? props.isVisibleFn : () => true;
|
||||
|
||||
const liveActivityBar = h('div', {
|
||||
className: 'live-activity-list',
|
||||
hidden: true,
|
||||
'aria-live': 'polite',
|
||||
});
|
||||
|
||||
const expandedTaskConvIds = new Set();
|
||||
const activityTimersMap = new Map();
|
||||
let liveTickTimer = null;
|
||||
let latestData = null;
|
||||
|
||||
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
||||
const now = Date.now();
|
||||
const prev = activityTimersMap.get(timerKey);
|
||||
let startMs = prev?.startMs || 0;
|
||||
if (!prev || prev.sig !== sig) {
|
||||
const validRaw = Number(rawStartMs || 0);
|
||||
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
|
||||
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
|
||||
startMs = Number(rawStartMs);
|
||||
}
|
||||
activityTimersMap.set(timerKey, { sig, startMs, el: targetEl });
|
||||
const elapsedSec = Math.max(0, (now - startMs) / 1000);
|
||||
patchText(targetEl, formatElapsedSec(elapsedSec));
|
||||
}
|
||||
|
||||
function updateLiveElapsedDisplay() {
|
||||
const now = Date.now();
|
||||
for (const entry of activityTimersMap.values()) {
|
||||
if (!entry?.el) continue;
|
||||
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
|
||||
patchText(entry.el, formatElapsedSec(elapsedSec));
|
||||
}
|
||||
}
|
||||
|
||||
function pauseTicker() {
|
||||
if (liveTickTimer) {
|
||||
clearInterval(liveTickTimer);
|
||||
liveTickTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopLiveTicker() {
|
||||
pauseTicker();
|
||||
activityTimersMap.clear();
|
||||
}
|
||||
|
||||
function ensureLiveTicker() {
|
||||
if (!isVisibleFn() || activityTimersMap.size === 0) {
|
||||
pauseTicker();
|
||||
return;
|
||||
}
|
||||
if (!liveTickTimer) {
|
||||
liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function resumeTicker() {
|
||||
if (activityTimersMap.size > 0) {
|
||||
updateLiveElapsedDisplay();
|
||||
ensureLiveTicker();
|
||||
}
|
||||
}
|
||||
|
||||
function createLiveTaskCard() {
|
||||
const dotIcon = createSvgIcon('dot', { size: 11 });
|
||||
patchClasses(dotIcon, { 'is-pulsing': true });
|
||||
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
|
||||
const titleEl = h('strong', {
|
||||
className: 'live-task-title',
|
||||
text: t('live.currentSession'),
|
||||
});
|
||||
const subToggleBtn = h('button', {
|
||||
type: 'button',
|
||||
className: 'live-sub-toggle',
|
||||
hidden: true,
|
||||
text: t('live.subToggleIdle', { total: 0, arrow: '▸' }),
|
||||
});
|
||||
const elapsedEl = h('span', {
|
||||
className: 'live-activity-elapsed text-mono',
|
||||
text: '0s',
|
||||
});
|
||||
|
||||
const headerEl = h('div', { className: 'live-task-header' }, [
|
||||
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]),
|
||||
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
|
||||
]);
|
||||
|
||||
const mainBadge = h('span', {
|
||||
className: 'agent-badge badge-main',
|
||||
hidden: true,
|
||||
text: t('fmt.mainBadge'),
|
||||
});
|
||||
const mainPhase = h('strong', {
|
||||
className: 'live-activity-phase',
|
||||
text: t('live.thinking'),
|
||||
});
|
||||
const mainProgress = h('span', {
|
||||
className: 'live-activity-progress text-mono',
|
||||
hidden: true,
|
||||
text: '',
|
||||
});
|
||||
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
|
||||
const mainDetail = h('span', {
|
||||
className: 'live-activity-detail',
|
||||
hidden: true,
|
||||
text: '',
|
||||
});
|
||||
|
||||
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
|
||||
mainBadge,
|
||||
mainPhase,
|
||||
mainProgress,
|
||||
mainSep,
|
||||
mainDetail,
|
||||
]);
|
||||
|
||||
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
|
||||
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
|
||||
|
||||
return {
|
||||
el: cardEl,
|
||||
refs: {
|
||||
cardEl,
|
||||
dotIcon,
|
||||
titleEl,
|
||||
subToggleBtn,
|
||||
elapsedEl,
|
||||
mainBadge,
|
||||
mainPhase,
|
||||
mainProgress,
|
||||
mainSep,
|
||||
mainDetail,
|
||||
subListEl,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createLiveSubRow() {
|
||||
const subBadge = h('span', {
|
||||
className: 'agent-badge badge-sub-1',
|
||||
text: t('fmt.subBadge', { index: 1 }),
|
||||
});
|
||||
const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') });
|
||||
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
|
||||
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
|
||||
|
||||
const rowEl = h('div', { className: 'live-sub-row' }, [
|
||||
h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]),
|
||||
subElapsed,
|
||||
]);
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: {
|
||||
rowEl,
|
||||
subBadge,
|
||||
subRole,
|
||||
subSummary,
|
||||
subElapsed,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function update({ data } = {}) {
|
||||
latestData = data || null;
|
||||
if (!data) {
|
||||
patchAttr(liveActivityBar, 'hidden', true);
|
||||
stopLiveTicker();
|
||||
return;
|
||||
}
|
||||
|
||||
const uiSt = uiStore.getState();
|
||||
const { agents, aggregated } = resolveScopedConversation(
|
||||
data,
|
||||
'all',
|
||||
uiSt.ctxInspectorAgentId
|
||||
);
|
||||
|
||||
const rawRunningList =
|
||||
Array.isArray(data.runningConversations) && data.runningConversations.length > 0
|
||||
? data.runningConversations
|
||||
: data.activeConversation?.isRunning || aggregated?.isRunning
|
||||
? [
|
||||
{
|
||||
cascadeId: data.activeConversation?.cascadeId || 'current',
|
||||
title: data.activeConversation?.title || t('live.currentSession'),
|
||||
isCurrentSelected: true,
|
||||
isMainRunning: Boolean(data.activeConversation?.isRunning),
|
||||
isRunning: true,
|
||||
mainActivity:
|
||||
data.activeConversation?.liveActivity || aggregated?.liveActivity || null,
|
||||
subagentCount: Math.max(0, agents.length - 1),
|
||||
runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length,
|
||||
subagents: agents
|
||||
.filter((a) => !a.isMain)
|
||||
.map((s, idx) => ({
|
||||
cascadeId: s.cascadeId || s.agentId,
|
||||
index: s.index || idx + 1,
|
||||
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||
isRunning: Boolean(s.isRunning),
|
||||
stepCount: Number(s.stepCount || 0),
|
||||
lastModifiedMs: s.lastModifiedMs || 0,
|
||||
liveActivity: s.liveActivity || {
|
||||
phase: s.isRunning ? 'thinking' : 'done',
|
||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: s.lastModifiedMs || 0,
|
||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
||||
},
|
||||
})),
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
const hasRunningTasks = rawRunningList.length > 0;
|
||||
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
|
||||
if (!hasRunningTasks) {
|
||||
stopLiveTicker();
|
||||
expandedTaskConvIds.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeTimerKeys = new Set();
|
||||
for (const item of rawRunningList) {
|
||||
activeTimerKeys.add(`main:${item.cascadeId}`);
|
||||
for (const sub of item.subagents || []) {
|
||||
if (sub?.isRunning) {
|
||||
activeTimerKeys.add(`sub:${sub.cascadeId}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
|
||||
for (const id of [...expandedTaskConvIds]) {
|
||||
if (!runningIdsSet.has(id)) {
|
||||
expandedTaskConvIds.delete(id);
|
||||
}
|
||||
}
|
||||
|
||||
const locale = getEffectiveLocale();
|
||||
patchKeyedList(liveActivityBar, rawRunningList, {
|
||||
keyFn: (item) => item.cascadeId,
|
||||
sigFn: (item) => {
|
||||
const isExp = interactive
|
||||
? expandedTaskConvIds.has(item.cascadeId)
|
||||
: Number(item.runningSubagentCount || 0) > 0;
|
||||
const subSig = (item.subagents || [])
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
)
|
||||
.join('|');
|
||||
return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
},
|
||||
createRow: createLiveTaskCard,
|
||||
updateRow: (refs, item) => {
|
||||
const act = item.mainActivity || {
|
||||
phase: 'thinking',
|
||||
label: t('live.thinking'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: item.lastModifiedMs || 0,
|
||||
signature: `fallback:${item.lastModifiedMs || 0}`,
|
||||
};
|
||||
|
||||
const isWaiting = act.phase === 'waiting';
|
||||
const isCompacting = act.phase === 'compacting';
|
||||
patchClasses(refs.cardEl, {
|
||||
'is-waiting': isWaiting,
|
||||
'is-compacting': isCompacting,
|
||||
});
|
||||
patchClasses(refs.dotIcon, { 'is-pulsing': true });
|
||||
|
||||
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
|
||||
patchText(refs.titleEl, convTitle);
|
||||
if (interactive) {
|
||||
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle }));
|
||||
refs.titleEl.onclick = () => {
|
||||
if (item.cascadeId && item.cascadeId !== 'current') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
||||
fetchTelemetry({ force: false });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||
const isExpanded = interactive
|
||||
? expandedTaskConvIds.has(item.cascadeId)
|
||||
: runSubCount > 0;
|
||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
||||
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
||||
if (subCount > 0) {
|
||||
const arrow = isExpanded ? '▾' : '▸';
|
||||
const toggleText =
|
||||
runSubCount > 0
|
||||
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
|
||||
: t('live.subToggleIdle', { total: subCount, arrow });
|
||||
patchText(refs.subToggleBtn, toggleText);
|
||||
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
|
||||
if (interactive) {
|
||||
patchAttr(
|
||||
refs.subToggleBtn,
|
||||
'title',
|
||||
isExpanded ? t('live.subCollapseTitle') : t('live.subExpandTitle')
|
||||
);
|
||||
refs.subToggleBtn.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (expandedTaskConvIds.has(item.cascadeId)) {
|
||||
expandedTaskConvIds.delete(item.cascadeId);
|
||||
} else {
|
||||
expandedTaskConvIds.add(item.cascadeId);
|
||||
}
|
||||
if (latestData) update({ data: latestData });
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const mainTimerKey = `main:${item.cascadeId}`;
|
||||
activeTimerKeys.add(mainTimerKey);
|
||||
bindLiveElapsedTimer(
|
||||
mainTimerKey,
|
||||
`${item.cascadeId}:${act.signature || act.label}`,
|
||||
act.startedAtMs,
|
||||
refs.elapsedEl
|
||||
);
|
||||
|
||||
patchText(refs.mainPhase, act.label || t('live.thinking'));
|
||||
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
|
||||
patchAttr(refs.mainProgress, 'hidden', !progText);
|
||||
if (progText) {
|
||||
patchText(refs.mainProgress, progText);
|
||||
}
|
||||
|
||||
const detailStr = act.detail || '';
|
||||
patchAttr(refs.mainSep, 'hidden', !detailStr);
|
||||
patchAttr(refs.mainDetail, 'hidden', !detailStr);
|
||||
patchText(refs.mainDetail, detailStr);
|
||||
|
||||
if (interactive) {
|
||||
const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`;
|
||||
patchAttr(refs.cardEl, 'title', fullTooltip);
|
||||
}
|
||||
|
||||
const showSubs = subCount > 0 && isExpanded;
|
||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
||||
if (showSubs) {
|
||||
const subItems = item.subagents || [];
|
||||
patchKeyedList(refs.subListEl, subItems, {
|
||||
keyFn: (sub) => sub.cascadeId,
|
||||
sigFn: (sub) =>
|
||||
`${locale}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
||||
createRow: createLiveSubRow,
|
||||
updateRow: (subRefs, sub) => {
|
||||
const subAct = sub.liveActivity || {
|
||||
phase: sub.isRunning ? 'thinking' : 'done',
|
||||
label: sub.isRunning ? t('live.thinking') : t('live.done'),
|
||||
detail: '',
|
||||
stepProgress: '',
|
||||
startedAtMs: sub.lastModifiedMs || 0,
|
||||
};
|
||||
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
|
||||
|
||||
const badgeCls = getAgentBadgeClass(sub.index || 1, false);
|
||||
const subBadgeText = formatAgentBadgeText({
|
||||
...sub,
|
||||
isMain: false,
|
||||
index: sub.index || 1,
|
||||
});
|
||||
patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`);
|
||||
patchText(subRefs.subBadge, subBadgeText);
|
||||
|
||||
const roleText = sub.role || sub.shortLabel || t('fmt.subAgent');
|
||||
patchText(subRefs.subRole, roleText);
|
||||
|
||||
const rawSubLabel = sub.isRunning
|
||||
? subAct.label || ''
|
||||
: subAct.label || t('live.done');
|
||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
||||
const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || '']
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
||||
patchText(subRefs.subSummary, summaryStr);
|
||||
|
||||
if (interactive) {
|
||||
patchAttr(
|
||||
subRefs.rowEl,
|
||||
'title',
|
||||
`[${subBadgeText}] ${roleText}${summaryStr ? ` ${summaryStr}` : ''}`
|
||||
);
|
||||
}
|
||||
|
||||
if (sub.isRunning) {
|
||||
const subTimerKey = `sub:${sub.cascadeId}`;
|
||||
activeTimerKeys.add(subTimerKey);
|
||||
bindLiveElapsedTimer(
|
||||
subTimerKey,
|
||||
`${sub.cascadeId}:${subAct.signature || subAct.label}`,
|
||||
subAct.startedAtMs,
|
||||
subRefs.subElapsed
|
||||
);
|
||||
} else {
|
||||
activityTimersMap.delete(`sub:${sub.cascadeId}`);
|
||||
patchText(
|
||||
subRefs.subElapsed,
|
||||
t('header.convMetaSteps', { count: sub.stepCount || 0 })
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
for (const key of [...activityTimersMap.keys()]) {
|
||||
if (!activeTimerKeys.has(key)) {
|
||||
activityTimersMap.delete(key);
|
||||
}
|
||||
}
|
||||
updateLiveElapsedDisplay();
|
||||
ensureLiveTicker();
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
stopLiveTicker();
|
||||
});
|
||||
|
||||
return {
|
||||
el: liveActivityBar,
|
||||
refs: {
|
||||
update,
|
||||
pauseTicker,
|
||||
resumeTicker,
|
||||
stopLiveTicker,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Metric Matrix Widget (`MetricMatrixWidget.js`).
|
||||
* Renders 1..4 user-selected telemetry cells dynamically via `metricRegistry.js`.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { resolveOverviewMetricCell } from '../../registries/metricRegistry.js';
|
||||
import {
|
||||
normalizeClientOverviewMetrics,
|
||||
resolveScopedConversation,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
|
||||
export const MetricMatrixWidget = defineComponent({
|
||||
name: 'MetricMatrixWidget',
|
||||
setup() {
|
||||
const matrixEl = h('section', {
|
||||
className: 'telemetry-matrix',
|
||||
'aria-label': t('module.metrics'),
|
||||
'data-cols': '4',
|
||||
});
|
||||
patchStyleVar(matrixEl, '--matrix-cols', '4');
|
||||
|
||||
function createMetricCellNode() {
|
||||
const labelSpan = h('span', { text: '—' });
|
||||
const iconSvg = createSvgIcon('pulse', { size: 11 });
|
||||
const valueEl = h('strong', { className: 'cell-value', text: '—' });
|
||||
const subEl = h('span', { className: 'cell-sub', text: '—' });
|
||||
const el = h('div', { className: 'matrix-cell' }, [
|
||||
h('div', { className: 'cell-label' }, [labelSpan, iconSvg]),
|
||||
valueEl,
|
||||
subEl,
|
||||
]);
|
||||
return {
|
||||
el,
|
||||
refs: { labelSpan, iconSvg, valueEl, subEl },
|
||||
};
|
||||
}
|
||||
|
||||
function update({ data } = {}) {
|
||||
patchAttr(matrixEl, 'aria-label', t('module.metrics'));
|
||||
const metricKeys = normalizeClientOverviewMetrics(data?.settings?.overviewMetrics);
|
||||
const colCount = Math.max(1, Math.min(4, metricKeys.length));
|
||||
patchAttr(matrixEl, 'data-cols', String(colCount));
|
||||
patchStyleVar(matrixEl, '--matrix-cols', String(colCount));
|
||||
|
||||
const uiSt = uiStore.getState();
|
||||
const { hasSubagents, scopedConv, ctxAgent } = resolveScopedConversation(
|
||||
data,
|
||||
'all',
|
||||
uiSt.ctxInspectorAgentId
|
||||
);
|
||||
const active = scopedConv || data?.activeConversation || {};
|
||||
const ctx = ctxAgent?.context || active.context || {};
|
||||
const quotas = data?.quotas || {};
|
||||
const settings = data?.settings || {};
|
||||
const locale = getEffectiveLocale();
|
||||
|
||||
const cells = metricKeys.map((key) =>
|
||||
resolveOverviewMetricCell(key, {
|
||||
active,
|
||||
ctx,
|
||||
quotas,
|
||||
settings,
|
||||
hasSubagents,
|
||||
})
|
||||
);
|
||||
|
||||
patchKeyedList(matrixEl, cells, {
|
||||
keyFn: (cell) => cell.key,
|
||||
sigFn: (cell) =>
|
||||
`${locale}:${cell.key}:${cell.label}:${cell.icon}:${cell.isPulsing}:${cell.valueClass}:${cell.valueText}:${cell.subClass}:${cell.subText}`,
|
||||
createRow: createMetricCellNode,
|
||||
updateRow: (refs, cell) => {
|
||||
patchText(refs.labelSpan, cell.label);
|
||||
patchSvgIcon(refs.iconSvg, cell.icon);
|
||||
refs.iconSvg.setAttribute('width', String(cell.iconSize));
|
||||
refs.iconSvg.setAttribute('height', String(cell.iconSize));
|
||||
patchClasses(refs.iconSvg, { 'is-pulsing': Boolean(cell.isPulsing) });
|
||||
patchAttr(refs.valueEl, 'class', cell.valueClass);
|
||||
patchText(refs.valueEl, cell.valueText);
|
||||
patchAttr(refs.subEl, 'class', cell.subClass);
|
||||
patchText(refs.subEl, cell.subText);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Initialize default 4-cell skeleton so hover/overview has zero initial height jump
|
||||
update({ data: null });
|
||||
|
||||
return {
|
||||
el: matrixEl,
|
||||
refs: { update },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,359 @@
|
||||
/**
|
||||
* @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`).
|
||||
* Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT)
|
||||
* and weekly summary footer for both `LiveOverviewView` and `WindowOverlayShell`.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatCountdown, formatTokens, formatUsd } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
* 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。
|
||||
*
|
||||
* @param {object|null|undefined} quotas
|
||||
* @param {number} minuteTick
|
||||
* @param {{ isPending?: boolean }} [options]
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) {
|
||||
const safeQuotas = quotas || {};
|
||||
const activePool = safeQuotas.activePool || {};
|
||||
const rawPools =
|
||||
Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0
|
||||
? safeQuotas.pools
|
||||
: [
|
||||
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
|
||||
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
|
||||
];
|
||||
const weekly = safeQuotas.weekly || {};
|
||||
const poolItems = rawPools.map((p) => {
|
||||
const key = p.poolKey || p.family || p.poolLabel || 'Other';
|
||||
const poolLabel = p.poolLabel || p.family || key;
|
||||
const isActivePool =
|
||||
Boolean(activePool.family) &&
|
||||
(activePool.poolKey === key ||
|
||||
activePool.family === p.family ||
|
||||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
|
||||
return {
|
||||
key,
|
||||
poolLabel,
|
||||
poolData: p,
|
||||
fallbackWeekly: weekly,
|
||||
isActivePool,
|
||||
minuteTick,
|
||||
isPending,
|
||||
};
|
||||
});
|
||||
if (
|
||||
weekly?.isOfficial === false &&
|
||||
poolItems.length > 0 &&
|
||||
!poolItems.some((item) => item.isActivePool)
|
||||
) {
|
||||
poolItems[0].isActivePool = true;
|
||||
}
|
||||
return poolItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
||||
*/
|
||||
export function createPoolQuotaRow() {
|
||||
const title5h = h('span', { className: 'quota-win-title', text: '5h' });
|
||||
const usage5h = h('span', { className: 'quota-win-usage', hidden: true, text: '' });
|
||||
const left5h = h('span', { className: 'quota-win-left' }, [title5h, usage5h]);
|
||||
const meta5h = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' });
|
||||
const fill5h = h('div', { className: 'progress-fill' });
|
||||
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header quota-win-head' }, [left5h, meta5h]),
|
||||
h('div', { className: 'progress-track' }, [fill5h]),
|
||||
]);
|
||||
|
||||
const titleWk = h('span', { className: 'quota-win-title', text: t('quota.weeklyShort') });
|
||||
const usageWk = h('span', { className: 'quota-win-usage', hidden: true, text: '' });
|
||||
const leftWk = h('span', { className: 'quota-win-left' }, [titleWk, usageWk]);
|
||||
const metaWk = h('span', { className: 'panel-meta quota-win-meta text-mono', text: '--' });
|
||||
const fillWk = h('div', { className: 'progress-fill' });
|
||||
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header quota-win-head' }, [leftWk, metaWk]),
|
||||
h('div', { className: 'progress-track' }, [fillWk]),
|
||||
]);
|
||||
|
||||
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
|
||||
row5h,
|
||||
rowWk,
|
||||
]);
|
||||
|
||||
return {
|
||||
el,
|
||||
refs: {
|
||||
row5h,
|
||||
left5h,
|
||||
title5h,
|
||||
usage5h,
|
||||
meta5h,
|
||||
fill5h,
|
||||
rowWk,
|
||||
leftWk,
|
||||
titleWk,
|
||||
usageWk,
|
||||
metaWk,
|
||||
fillWk,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化可用额度面板底部的汇总行文案(官方配额模式下展示各池周期合计,自定义预算模式下展示自然周累计)。
|
||||
*/
|
||||
export function formatQuotaSummaryFooter(quotas, account) {
|
||||
const weekly = quotas?.weekly || {};
|
||||
const isCustomLocal = weekly.isOfficial === false;
|
||||
const tokStr = formatTokens(weekly.tokens || 0);
|
||||
const costStr = formatUsd(weekly.costUsd || 0);
|
||||
const leftText = isCustomLocal
|
||||
? t('quota.footTokensCustom', { tok: tokStr, cost: costStr })
|
||||
: t('quota.footTokensCycle', { tok: tokStr, cost: costStr });
|
||||
const rightText =
|
||||
Number(account?.aiCredits) > 0
|
||||
? t('quota.footCredits', { credits: account.aiCredits })
|
||||
: isCustomLocal
|
||||
? t('quota.footCallsCustom', { calls: weekly.calls || 0 })
|
||||
: t('quota.footCallsCycle', { calls: weekly.calls || 0 });
|
||||
const tooltip = isCustomLocal ? t('quota.footTipCustom') : t('quota.footTipCycle');
|
||||
return { leftText, rightText, tooltip };
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步单个配额池行的 5h 与每周窗口状态。
|
||||
*/
|
||||
export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
||||
const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item;
|
||||
patchAttr(
|
||||
rowEl,
|
||||
'style',
|
||||
idx === 0
|
||||
? 'display: flex; flex-direction: column; gap: 8px;'
|
||||
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
|
||||
);
|
||||
|
||||
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
|
||||
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
|
||||
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
|
||||
|
||||
const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false);
|
||||
const wkUsedRaw = useCustomWeekly
|
||||
? fallbackWeekly?.usedPct
|
||||
: poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
|
||||
const wkRemRaw = useCustomWeekly
|
||||
? fallbackWeekly?.remainingPct
|
||||
: poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
|
||||
const wkResetRaw = useCustomWeekly
|
||||
? fallbackWeekly?.resetTime || poolData?.weeklyResetTime
|
||||
: poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
|
||||
const hasWk = wkUsedRaw != null && wkRemRaw != null;
|
||||
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
||||
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
||||
|
||||
const hide5h = !has5h && hasWk;
|
||||
const hideWk = !hasWk && has5h;
|
||||
refs.row5h.hidden = hide5h;
|
||||
refs.row5h.style.display = hide5h ? 'none' : 'flex';
|
||||
refs.rowWk.hidden = hideWk;
|
||||
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
|
||||
|
||||
const fallbackMetaText = isPending ? t('quota.loading') : t('quota.failed');
|
||||
|
||||
patchText(refs.title5h, `5h (${poolLabel})`);
|
||||
const c5h = poolData?.cycle5h;
|
||||
if (!isPending && has5h && c5h && (c5h.tokens != null || c5h.costUsd != null)) {
|
||||
const tok5h = formatTokens(c5h.tokens || 0);
|
||||
const cost5h = formatUsd(c5h.costUsd || 0);
|
||||
const calls5h = Number(c5h.calls || 0);
|
||||
refs.usage5h.hidden = false;
|
||||
patchText(refs.usage5h, `· ${tok5h} (${cost5h})`);
|
||||
patchAttr(
|
||||
refs.left5h,
|
||||
'title',
|
||||
t('quota.cycle5hTitle', {
|
||||
pool: poolLabel,
|
||||
tok: tok5h,
|
||||
cost: cost5h,
|
||||
calls: calls5h,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
refs.usage5h.hidden = true;
|
||||
patchText(refs.usage5h, '');
|
||||
patchAttr(refs.left5h, 'title', null);
|
||||
}
|
||||
patchText(
|
||||
refs.meta5h,
|
||||
has5h
|
||||
? t('quota.usedAndLeft', {
|
||||
reset: formatCountdown(poolData.resetTime),
|
||||
used: used5hVal.toFixed(1),
|
||||
rem: rem5hVal.toFixed(1),
|
||||
})
|
||||
: fallbackMetaText
|
||||
);
|
||||
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
|
||||
patchClasses(refs.fill5h, {
|
||||
'tone-warn': used5hVal >= 60 && used5hVal < 85,
|
||||
'tone-danger': used5hVal >= 85,
|
||||
});
|
||||
|
||||
const customTitle =
|
||||
useCustomWeekly && fallbackWeekly?.title
|
||||
? fallbackWeekly.title
|
||||
: t('quota.weeklyPool', { pool: poolLabel });
|
||||
patchText(refs.titleWk, customTitle);
|
||||
const cWk = useCustomWeekly
|
||||
? fallbackWeekly
|
||||
: poolData?.cycleWeekly || (isActivePool ? fallbackWeekly : null);
|
||||
if (!isPending && hasWk && cWk && (cWk.tokens != null || cWk.costUsd != null)) {
|
||||
const tokWk = formatTokens(cWk.tokens || 0);
|
||||
const costWk = formatUsd(cWk.costUsd || 0);
|
||||
const callsWk = Number(cWk.calls || 0);
|
||||
refs.usageWk.hidden = false;
|
||||
patchText(refs.usageWk, `· ${tokWk} (${costWk})`);
|
||||
patchAttr(
|
||||
refs.leftWk,
|
||||
'title',
|
||||
useCustomWeekly
|
||||
? t('quota.cycleWkCustomTitle', { tok: tokWk, cost: costWk, calls: callsWk })
|
||||
: t('quota.cycleWkPoolTitle', {
|
||||
pool: poolLabel,
|
||||
tok: tokWk,
|
||||
cost: costWk,
|
||||
calls: callsWk,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
refs.usageWk.hidden = true;
|
||||
patchText(refs.usageWk, '');
|
||||
patchAttr(refs.leftWk, 'title', null);
|
||||
}
|
||||
patchText(
|
||||
refs.metaWk,
|
||||
hasWk
|
||||
? t('quota.usedAndLeft', {
|
||||
reset: formatCountdown(wkResetRaw),
|
||||
used: usedWkVal.toFixed(1),
|
||||
rem: remWkVal.toFixed(1),
|
||||
})
|
||||
: fallbackMetaText
|
||||
);
|
||||
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
|
||||
patchClasses(refs.fillWk, {
|
||||
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
|
||||
'tone-danger': usedWkVal >= 85,
|
||||
});
|
||||
}
|
||||
|
||||
export function quotaPoolRowSig(item, idx) {
|
||||
const c5h = item.poolData?.cycle5h;
|
||||
const cWk = item.poolData?.cycleWeekly;
|
||||
const fw = item.fallbackWeekly;
|
||||
return `${getEffectiveLocale()}:${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${c5h?.tokens}:${c5h?.costUsd}:${c5h?.calls}:${cWk?.tokens}:${cWk?.costUsd}:${cWk?.calls}:${fw?.isOfficial}:${fw?.usedPct}:${fw?.remainingPct}:${fw?.resetTime}:${fw?.title}:${fw?.tokens}:${fw?.costUsd}:${fw?.calls}`;
|
||||
}
|
||||
|
||||
export const QuotaPoolsWidget = defineComponent({
|
||||
name: 'QuotaPoolsWidget',
|
||||
setup({ props }) {
|
||||
const compactHover = Boolean(props.compactHover);
|
||||
const titleTextEl = h('span', { text: t('module.quotas') });
|
||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||
const poolsListEl = h(
|
||||
'div',
|
||||
compactHover
|
||||
? { className: 'wm-hover-quota-pools' }
|
||||
: { style: 'display: flex; flex-direction: column; gap: 0;' }
|
||||
);
|
||||
|
||||
if (compactHover) {
|
||||
patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
}
|
||||
|
||||
const initFoot = formatQuotaSummaryFooter(null, null);
|
||||
const wkFootLeft = h('span', { className: 'text-muted', text: initFoot.leftText });
|
||||
const wkFootRight = h('span', {
|
||||
className: 'text-muted',
|
||||
text: compactHover ? initFoot.rightText : '',
|
||||
});
|
||||
|
||||
const quotaPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('pulse', { size: 13 }),
|
||||
titleTextEl,
|
||||
]),
|
||||
tierBadge,
|
||||
]),
|
||||
poolsListEl,
|
||||
h(
|
||||
'div',
|
||||
compactHover
|
||||
? { className: 'panel-header wm-hover-quota-foot' }
|
||||
: { className: 'panel-header', style: 'font-size: var(--fs-md); padding-top: 2px;' },
|
||||
[wkFootLeft, wkFootRight]
|
||||
),
|
||||
]);
|
||||
|
||||
function update({ data, minuteTick } = {}) {
|
||||
patchText(titleTextEl, t('module.quotas'));
|
||||
if (!data) {
|
||||
if (compactHover) {
|
||||
patchKeyedList(poolsListEl, buildQuotaPoolItems(null, 0, { isPending: true }), {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
const pendingFoot = formatQuotaSummaryFooter(null, null);
|
||||
patchText(wkFootLeft, pendingFoot.leftText);
|
||||
patchText(wkFootRight, pendingFoot.rightText);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const quotas = data.quotas || {};
|
||||
const effTick = Number.isFinite(minuteTick) ? minuteTick : Math.floor(Date.now() / 30000);
|
||||
patchText(
|
||||
tierBadge,
|
||||
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
|
||||
);
|
||||
patchKeyedList(poolsListEl, buildQuotaPoolItems(quotas, effTick), {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
|
||||
const footSummary = formatQuotaSummaryFooter(quotas, data.account);
|
||||
patchText(wkFootLeft, footSummary.leftText);
|
||||
patchText(wkFootRight, footSummary.rightText);
|
||||
patchAttr(wkFootLeft, 'title', footSummary.tooltip);
|
||||
patchAttr(wkFootRight, 'title', footSummary.tooltip);
|
||||
}
|
||||
|
||||
return {
|
||||
el: quotaPanel,
|
||||
refs: { update, poolsListEl },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* @fileoverview Theme accent palette & panel font-scale appearance engine.
|
||||
* Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts,
|
||||
* while strictly isolating `#ag-usage-monitor-capsule` from font scaling.
|
||||
*/
|
||||
|
||||
export const THEME_ACCENT_PRESETS = Object.freeze([
|
||||
{ key: 'host', labelKey: 'settings.gen.accentHost', cssColor: '' },
|
||||
{ key: 'blue', labelKey: 'settings.gen.accentBlue', cssColor: 'hsl(217 84% 53%)' },
|
||||
{ key: 'emerald', labelKey: 'settings.gen.accentEmerald', cssColor: 'hsl(152 66% 39%)' },
|
||||
{ key: 'amber', labelKey: 'settings.gen.accentAmber', cssColor: 'hsl(34 88% 46%)' },
|
||||
{ key: 'violet', labelKey: 'settings.gen.accentViolet', cssColor: 'hsl(262 76% 58%)' },
|
||||
{ key: 'cyan', labelKey: 'settings.gen.accentCyan', cssColor: 'hsl(191 82% 41%)' },
|
||||
{ key: 'rose', labelKey: 'settings.gen.accentRose', cssColor: 'hsl(346 78% 54%)' },
|
||||
]);
|
||||
|
||||
export const FONT_SCALE_FACTORS = Object.freeze({
|
||||
sm: 0.92,
|
||||
md: 1,
|
||||
lg: 1.08,
|
||||
xl: 1.15,
|
||||
});
|
||||
|
||||
export function normalizeClientThemeAccent(raw) {
|
||||
const val = String(raw ?? '').trim().toLowerCase();
|
||||
return THEME_ACCENT_PRESETS.some((p) => p.key === val) ? val : 'host';
|
||||
}
|
||||
|
||||
export function normalizeClientFontScale(raw) {
|
||||
const val = String(raw ?? '').trim().toLowerCase();
|
||||
return Object.prototype.hasOwnProperty.call(FONT_SCALE_FACTORS, val) ? val : 'md';
|
||||
}
|
||||
|
||||
function setOrClearStyleVar(el, propName, value) {
|
||||
if (!el || !el.style) return;
|
||||
if (value) {
|
||||
if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, value);
|
||||
} else {
|
||||
el.style[propName] = value;
|
||||
}
|
||||
} else if (typeof el.style.removeProperty === 'function') {
|
||||
el.style.removeProperty(propName);
|
||||
} else if (typeof el.style.setProperty === 'function') {
|
||||
el.style.setProperty(propName, '');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronize theme accent and (optionally) font scale tokens onto a root/host element.
|
||||
*
|
||||
* @param {HTMLElement | null | undefined} targetEl
|
||||
* @param {object | null | undefined} settings
|
||||
* @param {{ includeFontScale?: boolean }} [options]
|
||||
*/
|
||||
export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = {}) {
|
||||
if (!targetEl || !targetEl.style) return;
|
||||
const accentKey = normalizeClientThemeAccent(settings?.themeAccent);
|
||||
const preset = THEME_ACCENT_PRESETS.find((p) => p.key === accentKey) || THEME_ACCENT_PRESETS[0];
|
||||
|
||||
if (preset.key !== 'host' && preset.cssColor) {
|
||||
setOrClearStyleVar(targetEl, '--user-accent-primary', preset.cssColor);
|
||||
setOrClearStyleVar(targetEl, '--user-accent-contrast', '#ffffff');
|
||||
} else {
|
||||
setOrClearStyleVar(targetEl, '--user-accent-primary', '');
|
||||
setOrClearStyleVar(targetEl, '--user-accent-contrast', '');
|
||||
}
|
||||
targetEl.setAttribute?.('data-accent', preset.key);
|
||||
|
||||
if (includeFontScale) {
|
||||
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
||||
const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1;
|
||||
setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor));
|
||||
targetEl.setAttribute?.('data-font-scale', scaleKey);
|
||||
} else {
|
||||
setOrClearStyleVar(targetEl, '--ui-font-scale', '');
|
||||
if (typeof targetEl.removeAttribute === 'function') {
|
||||
targetEl.removeAttribute('data-font-scale');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
export function defineComponent({ name, setup }) {
|
||||
return function createInstance(initialProps = {}) {
|
||||
let props = { ...initialProps };
|
||||
const props = { ...initialProps };
|
||||
const cleanups = [];
|
||||
|
||||
function emit(event, payload) {
|
||||
@@ -30,7 +30,7 @@ export function defineComponent({ name, setup }) {
|
||||
let setupResult = null;
|
||||
|
||||
function setProps(nextProps = {}) {
|
||||
props = { ...props, ...nextProps };
|
||||
Object.assign(props, nextProps);
|
||||
if (setupResult && typeof setupResult.onPropsChange === 'function') {
|
||||
setupResult.onPropsChange(props);
|
||||
}
|
||||
@@ -41,6 +41,7 @@ export function defineComponent({ name, setup }) {
|
||||
}
|
||||
|
||||
setupResult = setup({
|
||||
props,
|
||||
getProps: () => props,
|
||||
setProps,
|
||||
emit,
|
||||
|
||||
@@ -179,6 +179,15 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
|
||||
}
|
||||
}
|
||||
|
||||
if (!container.firstChild && orderedNodes.length > 1 && typeof document.createDocumentFragment === 'function') {
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (const node of orderedNodes) {
|
||||
fragment.appendChild(node);
|
||||
}
|
||||
container.appendChild(fragment);
|
||||
return;
|
||||
}
|
||||
|
||||
// Reorder or insert nodes with minimal DOM moves
|
||||
for (let i = 0; i < orderedNodes.length; i++) {
|
||||
const targetNode = orderedNodes[i];
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
* USD estimates, countdown timers, and custom datetime displays.
|
||||
*/
|
||||
|
||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||
|
||||
const EN_MONTH_SHORT = Object.freeze([
|
||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
|
||||
]);
|
||||
|
||||
export function formatMetric(value, unit = '') {
|
||||
return Number.isFinite(value) ? `${value.toFixed(1)}${unit}` : '—';
|
||||
}
|
||||
@@ -34,6 +41,14 @@ export function formatCnyApprox(usdAmount, rate = 7.2) {
|
||||
export function formatDateSpanBadge(startMs, endMs) {
|
||||
const s = startMs && Number.isFinite(startMs) ? new Date(startMs) : new Date();
|
||||
const e = endMs && Number.isFinite(endMs) ? new Date(endMs) : new Date();
|
||||
if (isEnglishLocale()) {
|
||||
const sMon = EN_MONTH_SHORT[s.getMonth()] || '';
|
||||
const eMon = EN_MONTH_SHORT[e.getMonth()] || '';
|
||||
if (s.getFullYear() !== e.getFullYear()) {
|
||||
return `${sMon} ${s.getDate()}, ${s.getFullYear()} ~ ${eMon} ${e.getDate()}, ${e.getFullYear()}`;
|
||||
}
|
||||
return `${sMon} ${s.getDate()} ~ ${eMon} ${e.getDate()}`;
|
||||
}
|
||||
if (s.getFullYear() !== e.getFullYear()) {
|
||||
return `${s.getFullYear()}年${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getFullYear()}年${e.getMonth() + 1}月${e.getDate()}日`;
|
||||
}
|
||||
@@ -41,7 +56,7 @@ export function formatDateSpanBadge(startMs, endMs) {
|
||||
}
|
||||
|
||||
export function formatUsd(amount, { precise = false } = {}) {
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return '待定';
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return t('fmt.pending');
|
||||
const val = Number(amount || 0);
|
||||
if (precise) {
|
||||
if (val > 0 && val < 0.001) return '<$0.001';
|
||||
@@ -50,42 +65,46 @@ export function formatUsd(amount, { precise = false } = {}) {
|
||||
return `$${val.toFixed(2)}`;
|
||||
}
|
||||
|
||||
const SPEED_REASON_LABELS = {
|
||||
__proto__: null,
|
||||
incomplete_or_invalid_timing: 'fmt.speedIncomplete',
|
||||
invalid_output_tokens: 'fmt.speedInvalidOutput',
|
||||
inconsistent_timing: 'fmt.speedInconsistent',
|
||||
short_timing: 'fmt.speedShort',
|
||||
legacy_cache: 'fmt.speedLegacy',
|
||||
};
|
||||
|
||||
export function speedReasonText(reason) {
|
||||
return ({
|
||||
incomplete_or_invalid_timing: '生成未完成',
|
||||
invalid_output_tokens: '无有效输出',
|
||||
inconsistent_timing: '耗时数据异常',
|
||||
short_timing: '耗时过短 (<0.5s)',
|
||||
legacy_cache: '旧版缓存记录',
|
||||
})[reason] || '';
|
||||
const label = SPEED_REASON_LABELS[reason];
|
||||
return label ? t(label) : '';
|
||||
}
|
||||
|
||||
export function sampleSummary(summary) {
|
||||
const valid = summary?.sampleCount || 0;
|
||||
const excluded = summary?.excludedCount || 0;
|
||||
return `${valid}/${valid + excluded} 步`;
|
||||
return t('fmt.sampleSteps', { valid, total: valid + excluded });
|
||||
}
|
||||
|
||||
export function formatCountdown(isoTime, nowMs = Date.now()) {
|
||||
if (!isoTime) return '未知重置时间';
|
||||
if (!isoTime) return t('fmt.resetUnknown');
|
||||
const targetMs = Date.parse(isoTime);
|
||||
if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间';
|
||||
if (!Number.isFinite(targetMs) || targetMs <= 0) return t('fmt.resetUnknown');
|
||||
const diffMs = targetMs - nowMs;
|
||||
if (diffMs <= 0) return '即将重置';
|
||||
if (diffMs < 60_000) return '<1分钟后重置';
|
||||
if (diffMs <= 0) return t('fmt.resetSoon');
|
||||
if (diffMs < 60_000) return t('fmt.resetUnder1m');
|
||||
|
||||
const totalMinutes = Math.floor(diffMs / 60000);
|
||||
const days = Math.floor(totalMinutes / (60 * 24));
|
||||
const hours = Math.floor((totalMinutes % (60 * 24)) / 60);
|
||||
const minutes = totalMinutes % 60;
|
||||
|
||||
if (days > 0) return `${days}天 ${hours}小时后重置`;
|
||||
if (hours > 0) return `${hours}小时 ${minutes}分后重置`;
|
||||
return `${minutes}分钟后重置`;
|
||||
if (days > 0) return t('fmt.resetDaysHours', { d: days, h: hours });
|
||||
if (hours > 0) return t('fmt.resetHoursMins', { h: hours, m: minutes });
|
||||
return t('fmt.resetMins', { m: minutes });
|
||||
}
|
||||
|
||||
export function formatCompactDateTime(ms) {
|
||||
if (!ms || !Number.isFinite(ms)) return '选择时间';
|
||||
if (!ms || !Number.isFinite(ms)) return t('fmt.selectTime');
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
@@ -135,7 +154,7 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
typeof settings === 'object' && settings ? settings.orchestratorIdMode : 'compact'
|
||||
);
|
||||
const preferLabelInShort = Boolean(options?.preferLabelInShort);
|
||||
const fallback = options?.fallback ?? '模型未知';
|
||||
const fallback = options?.fallback ?? t('fmt.unknownModel');
|
||||
|
||||
if (!target || typeof target !== 'object') {
|
||||
return { text: fallback, title: fallback, isOrchestratorSeries: false };
|
||||
|
||||
@@ -0,0 +1,425 @@
|
||||
/**
|
||||
* @fileoverview English (en-US) dictionary for Antigravity Usage & Speed Monitor.
|
||||
* Zero emoji characters.
|
||||
*/
|
||||
|
||||
export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
// Top Navigation
|
||||
'nav.overview': 'Live',
|
||||
'nav.consumption': 'Usage',
|
||||
'nav.steps': 'Steps',
|
||||
'nav.settings': 'Settings',
|
||||
|
||||
// Top Session Header
|
||||
'header.followLatest': 'Follow Latest Session',
|
||||
'header.currentWindowNamed': 'Current ({title})',
|
||||
'header.latestNamed': 'Latest ({title})',
|
||||
'header.lockedSession': 'Pinned Session ({id})',
|
||||
'header.lockedMeta': 'Pinned',
|
||||
'header.convMetaWithSubs': 'Main {main} · {subs} sub ({total} steps)',
|
||||
'header.convMetaSteps': '{count} steps',
|
||||
'header.hasUpdate': 'Update',
|
||||
'header.upgradeToVer': 'Update v{ver}',
|
||||
'header.upgrading': 'Updating…',
|
||||
'header.ariaUpdate': 'New version available, click to update',
|
||||
'header.ariaRefresh': 'Refresh telemetry',
|
||||
'header.statusSyncing': 'Syncing',
|
||||
'header.statusSynced': 'Synced',
|
||||
'header.statusRetrying': 'Retrying',
|
||||
'header.statusGenerating': 'Running{suffix}',
|
||||
'header.statusQuotaCached': 'Quota Cached',
|
||||
'header.statusQuotaOffline': 'Quota Offline',
|
||||
'header.statusLive': 'Live 2s',
|
||||
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': 'N/A',
|
||||
'fmt.speedIncomplete': 'Incomplete timing',
|
||||
'fmt.speedInvalidOutput': 'No valid output',
|
||||
'fmt.speedInconsistent': 'Invalid timing',
|
||||
'fmt.speedShort': 'Too brief (<0.5s)',
|
||||
'fmt.speedLegacy': 'Legacy cached',
|
||||
'fmt.sampleSteps': '{valid}/{total} steps',
|
||||
'fmt.resetUnknown': 'Unknown reset',
|
||||
'fmt.resetSoon': 'Resetting soon',
|
||||
'fmt.resetUnder1m': 'Resets in <1m',
|
||||
'fmt.resetDaysHours': 'Resets in {d}d {h}h',
|
||||
'fmt.resetHoursMins': 'Resets in {h}h {m}m',
|
||||
'fmt.resetMins': 'Resets in {m}m',
|
||||
'fmt.selectTime': 'Select time',
|
||||
'fmt.unknownModel': 'Unknown model',
|
||||
'fmt.mainAgent': 'Main Agent',
|
||||
'fmt.mainBadge': 'Main',
|
||||
'fmt.subAgent': 'Subagent',
|
||||
'fmt.subBadge': 'S{index}',
|
||||
'fmt.subBadgeShort': 'Sub',
|
||||
'fmt.selectedCount': '{count} {unit} selected',
|
||||
'fmt.selectedListTitle': 'Selected ({count}): {names}',
|
||||
'fmt.selectPlaceholder': 'Select',
|
||||
|
||||
// Capsule & Multi-Session Overlay
|
||||
'capsule.ariaMonitor': 'Usage & Speed Monitor',
|
||||
'capsule.ariaMulti': 'Active Sessions Overview',
|
||||
'capsule.multiZero': '0 active',
|
||||
'capsule.multiRunning': '{count} active',
|
||||
'capsule.multiRunningWithSubs': '{count} active · {subs} sub',
|
||||
'capsule.tpsRunning': 'Running',
|
||||
'capsule.tpsIdle': 'Idle',
|
||||
'capsule.quotaLeft': '{pct}% left',
|
||||
'capsule.quotaUnknown': '--% left',
|
||||
'capsule.newVersion': 'Update',
|
||||
'capsule.updating': 'Updating…',
|
||||
'capsule.ariaUpdateTitle': 'New version available, click to update',
|
||||
'capsule.hoverNewVer': 'Update v{ver} available',
|
||||
'capsule.hoverNewVerGeneric': 'New version available',
|
||||
'capsule.hoverUpdateHintTopbar': 'Click v{ver} in titlebar to update',
|
||||
'capsule.hoverUpdateHintComposer': 'Click v{ver} badge to update',
|
||||
'capsule.hoverUpdateHintTopbarGeneric': 'Click update badge in titlebar',
|
||||
'capsule.hoverUpdateHintComposerGeneric': 'Click update badge to install',
|
||||
'multi.title': 'Active Sessions',
|
||||
'multi.ariaDialog': 'Active Sessions Panel',
|
||||
'multi.pinned': 'Pinned',
|
||||
'multi.loading': 'Loading...',
|
||||
'multi.empty': 'No active running sessions',
|
||||
'multi.allIdle': 'All idle',
|
||||
'multi.metaWithSubs': '{main} main · {subs} subagents active',
|
||||
'multi.metaMainOnly': '{main} sessions active',
|
||||
'multi.hereTag': 'Here',
|
||||
'multi.inspectSessionTitle': 'Inspect session in monitor: {title}',
|
||||
|
||||
// Live Overview & Widgets
|
||||
'module.metrics': 'Live Metrics',
|
||||
'module.context': 'Context Window',
|
||||
'module.quotas': 'Available Quotas',
|
||||
'module.live_tasks': 'Live Running Tasks',
|
||||
|
||||
// Capsule Slot Metric Options
|
||||
'capMetric.context': 'Context Usage (%)',
|
||||
'capMetric.tps': 'Output Speed (TPS)',
|
||||
'capMetric.ttft': 'First Token Latency (TTFT)',
|
||||
'capMetric.avg_tps': 'Avg Speed (Avg TPS)',
|
||||
'capMetric.cost': 'Step Cost ($)',
|
||||
'capMetric.session_cost': 'Session Cost ($)',
|
||||
'capMetric.cache_hit': 'Cache Hit Rate (%)',
|
||||
'capMetric.session_tokens': 'Session Tokens',
|
||||
'capMetric.quota_auto': 'Auto Tightest Quota',
|
||||
'capMetric.gemini_5h': 'Gemini 5h Quota',
|
||||
'capMetric.gemini_weekly': 'Gemini Weekly Quota',
|
||||
'capMetric.claude_5h': 'Claude 5h Quota',
|
||||
'capMetric.claude_weekly': 'Claude Weekly Quota',
|
||||
|
||||
// Overview Matrix Metric Options & Cells
|
||||
'ovMetric.tps': 'Output Speed',
|
||||
'ovMetric.ttft': 'First Token',
|
||||
'ovMetric.avg_tps': 'Avg Speed',
|
||||
'ovMetric.step_cost': 'Step Cost',
|
||||
'ovMetric.session_cost': 'Session Cost',
|
||||
'ovMetric.cache_hit': 'Cache Hit',
|
||||
'ovMetric.session_tokens': 'Session Tokens',
|
||||
'ovMetric.context_usage': 'Context Usage',
|
||||
'ovMetric.quota_tightest': 'Tightest Quota',
|
||||
'ovMetric.subAvgTtft': 'Avg {val}',
|
||||
'ovMetric.subValidSamples': 'Valid {samples}',
|
||||
'ovMetric.subCacheAndTotal': 'Cache {cache}% · Total {cost}',
|
||||
'ovMetric.subStepsAndCache': '{steps} steps · Cache {cache}%',
|
||||
'ovMetric.subStepCost': 'Latest {cost}',
|
||||
'ovMetric.subPromptHit': 'Latest {latest}% · Avg {avg}%',
|
||||
'ovMetric.subInOutTokens': 'In {inTok} · Out {outTok}',
|
||||
'ovMetric.subCtxRatio': '{used} / {limit}',
|
||||
'ovMetric.subQuotaPool': '{label}',
|
||||
'ovMetric.subQuotaPending': 'Waiting for quota sync',
|
||||
|
||||
// Context Window Widget
|
||||
'ctx.followActive': 'Follow Active ({badge})',
|
||||
'ctx.followActiveTitle': 'Automatically inspect the active or running agent context window',
|
||||
'ctx.expandMore': '+{count} More ▾',
|
||||
'ctx.expandMoreTitle': 'Expand all {count} subagent context pills',
|
||||
'ctx.collapse': 'Less ▴',
|
||||
'ctx.collapseTitle': 'Collapse extra subagent pills',
|
||||
'ctx.ch.assistant': 'Assistant',
|
||||
'ctx.ch.assistantTitle': 'Model reasoning, responses, and tool call arguments',
|
||||
'ctx.ch.toolResults': 'Tool Results',
|
||||
'ctx.ch.toolResultsTitle': 'File reads, terminal outputs, and tool execution results',
|
||||
'ctx.ch.userInput': 'User Input',
|
||||
'ctx.ch.userInputTitle': 'User messages and uploaded attachments',
|
||||
'ctx.ch.subagent': 'Subagent',
|
||||
'ctx.ch.subagentTitle': 'Subagent reports and background task notifications',
|
||||
'ctx.ch.checkpoint': 'Checkpoint',
|
||||
'ctx.ch.checkpointTitle': 'Compacted conversation checkpoint summaries',
|
||||
'ctx.ch.systemPrompt': 'System Prompt',
|
||||
'ctx.ch.systemPromptTitle': 'Core identity, sandbox, artifact, and environment prompts',
|
||||
'ctx.ch.systemTools': 'System Tools',
|
||||
'ctx.ch.systemToolsTitle': 'Built-in tool schema declarations',
|
||||
'ctx.ch.mcpTools': 'MCP Tools',
|
||||
'ctx.ch.mcpToolsTitle': 'MCP external server tool and resource schemas',
|
||||
'ctx.ch.skills': 'Skills',
|
||||
'ctx.ch.skillsTitle': 'Installed Skills index and instructions',
|
||||
'ctx.ch.userRules': 'User Rules',
|
||||
'ctx.ch.userRulesTitle': 'Global and workspace custom user_rules',
|
||||
|
||||
// Quota Pools Widget
|
||||
'quota.weeklyShort': 'Weekly',
|
||||
'quota.weeklyPool': 'Weekly ({pool})',
|
||||
'quota.loading': 'Loading...',
|
||||
'quota.failed': 'Unavailable (--%)',
|
||||
'quota.usedAndLeft': '{reset} · Used {used}% ({rem}% left)',
|
||||
'quota.cycle5hTitle': 'Current 5h cycle ({pool}): {tok} Tokens · {cost} · {calls} calls',
|
||||
'quota.cycleWkCustomTitle': 'Current calendar week: {tok} Tokens · {cost} · {calls} calls',
|
||||
'quota.cycleWkPoolTitle': 'Current weekly cycle ({pool}): {tok} Tokens · {cost} · {calls} calls',
|
||||
'quota.footTokensCustom': 'Week Total: {tok} ({cost})',
|
||||
'quota.footTokensCycle': 'Cycle Total: {tok} ({cost})',
|
||||
'quota.footCredits': 'AI Credits: {credits}',
|
||||
'quota.footCallsCustom': 'Week Calls: {calls}',
|
||||
'quota.footCallsCycle': 'Cycle Calls: {calls}',
|
||||
'quota.footTipCustom': 'Counted since Monday 00:00 local time',
|
||||
'quota.footTipCycle': 'Summed across each quota pool weekly reset window',
|
||||
|
||||
// Live Activity Widget
|
||||
'live.currentSession': 'Current Session',
|
||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||
'live.thinking': 'Thinking',
|
||||
'live.running': 'Running',
|
||||
'live.done': 'Done',
|
||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||
'live.subToggleRunning': 'Subagents {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': 'Subagents ({total}) {arrow}',
|
||||
'live.subCollapseTitle': 'Collapse subagent list',
|
||||
'live.subExpandTitle': 'Expand subagent activity list',
|
||||
|
||||
// Consumption View
|
||||
'cons.rangeToday': 'Today',
|
||||
'cons.range24h': '24h',
|
||||
'cons.range7d': '7d',
|
||||
'cons.range14d': '14d',
|
||||
'cons.range30d': '30d',
|
||||
'cons.rangeAll': 'All',
|
||||
'cons.rangeCustom': 'Custom',
|
||||
'cons.rangeAria': 'Usage statistics time range',
|
||||
'cons.applyFilter': 'Apply',
|
||||
'cons.rangeTo': 'to',
|
||||
'cons.overviewTitle': 'Usage Overview',
|
||||
'cons.totalTokens': 'Total Tokens',
|
||||
'cons.estCost': 'Est. Cost',
|
||||
'cons.cacheHitRate': 'Cache Hit Rate',
|
||||
'cons.callsCount': '{calls} calls',
|
||||
'cons.cacheHitTokens': 'Hit {tokens}',
|
||||
'cons.newInput': 'New Input',
|
||||
'cons.uncachedInput': 'Uncached input',
|
||||
'cons.cacheRead': 'Cache Read',
|
||||
'cons.savedCost': 'Saved {cost}',
|
||||
'cons.outputUsage': 'Output',
|
||||
'cons.replyAndThink': 'Reply {resp} · Think {think}',
|
||||
'cons.trendTitle': 'Usage Trend',
|
||||
'cons.allTime': 'All Time',
|
||||
'cons.trendHeatmapHint': 'Daily ({days}d) · Hover for details',
|
||||
'cons.trendPointsHintHourly': 'Hourly ({points} pts) · Hover for details',
|
||||
'cons.trendPointsHintDaily': 'Daily ({points} pts) · Hover for details',
|
||||
'cons.topModels': 'Top Models',
|
||||
'cons.clientSources': 'Client Sources',
|
||||
'cons.monthlyTitle': 'Monthly Breakdown',
|
||||
'cons.monthLabel': 'M{m}',
|
||||
'cons.legInput': 'Input',
|
||||
'cons.legCache': 'Cache',
|
||||
'cons.legOutput': 'Output',
|
||||
'cons.legThinking': 'Think',
|
||||
'cons.footInput': 'In ',
|
||||
'cons.footCache': 'Cache ',
|
||||
'cons.footOutput': 'Out ',
|
||||
'cons.footThinking': 'Think ',
|
||||
'cons.footCalls': 'Calls ',
|
||||
|
||||
// Steps Detail View & Step Column Registry
|
||||
'steps.title': 'Step Records',
|
||||
'steps.tabSteps': 'Steps ({count})',
|
||||
'steps.tabStepsFiltered': 'Steps ({filtered}/{total})',
|
||||
'steps.tabModels': 'Analytics',
|
||||
'steps.allAgents': 'All Agents',
|
||||
'steps.allModels': 'All Models',
|
||||
'steps.selectModel': 'Select Model',
|
||||
'steps.unitAgent': 'agents',
|
||||
'steps.unitModel': 'models',
|
||||
'steps.lineTitle': 'Session Timeline',
|
||||
'steps.fitTitle': 'Trend Fit',
|
||||
'steps.modelsTitle': 'Model Summary',
|
||||
'steps.modelsEmpty': 'No model calls in current scope',
|
||||
'steps.metricTotalTokens': 'Tokens',
|
||||
'steps.metricContext': 'Context',
|
||||
'steps.metricTps': 'TPS',
|
||||
'steps.metricTtft': 'TTFT',
|
||||
'steps.metricCache': 'Cache',
|
||||
'steps.metricCost': 'Cost',
|
||||
'steps.badgeBackAll': 'Click to return to All Agents',
|
||||
'steps.badgeFilterAgent': 'Click to filter {agent} (Ctrl/Shift-click to multi-select)',
|
||||
'steps.ctxTitle': 'Context {ctx} · Thinking {think} · Reply {resp}',
|
||||
'steps.modelCallsShare': '{calls} calls · {pct}%',
|
||||
'steps.modelCallsOnly': '{calls} calls',
|
||||
'steps.modelsSummaryPrefix': '{count} models · ',
|
||||
'steps.modelPerfFoot': 'Avg {tps} · TTFT {ttft} · Cache {cache}%',
|
||||
'steps.modelSplitFoot': 'In {inTok} · Cache {cacheTok} · Think {thinkTok} · Out {respTok}',
|
||||
'steps.fitActiveCardTitle': '{title} (Active in Trend Fit; Ctrl/Shift-click to compare)',
|
||||
'steps.fitInactiveCardTitle': 'Click to inspect {text} in Trend Fit (Ctrl/Shift-click to compare)',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': 'Step',
|
||||
'stepCol.step.opt': 'Step & Agent',
|
||||
'stepCol.time.th': 'Time',
|
||||
'stepCol.time.opt': 'Timestamp (HH:mm:ss)',
|
||||
'stepCol.model.th': 'Model',
|
||||
'stepCol.model.opt': 'Model',
|
||||
'stepCol.tps.th': 'Speed',
|
||||
'stepCol.tps.opt': 'Output Speed (TPS)',
|
||||
'stepCol.ttft.th': 'TTFT',
|
||||
'stepCol.ttft.opt': 'First Token (TTFT)',
|
||||
'stepCol.duration.th': 'Time(s)',
|
||||
'stepCol.duration.opt': 'Total Duration (s)',
|
||||
'stepCol.tokens_combo.th': 'Ctx / Think / Reply',
|
||||
'stepCol.tokens_combo.opt': 'Ctx / Think / Reply (Combo)',
|
||||
'stepCol.input_tokens.th': 'Input',
|
||||
'stepCol.input_tokens.opt': 'New Input Tokens',
|
||||
'stepCol.cache_tokens.th': 'CacheTok',
|
||||
'stepCol.cache_tokens.opt': 'Cache Read Tokens',
|
||||
'stepCol.output_tokens.th': 'Output',
|
||||
'stepCol.output_tokens.opt': 'Total Output Tokens',
|
||||
'stepCol.cache.th': 'Cache',
|
||||
'stepCol.cache.opt': 'Cache Hit Rate (%)',
|
||||
'stepCol.cost.th': 'Cost',
|
||||
'stepCol.cost.opt': 'Step Cost ($)',
|
||||
|
||||
// Preferences (3-Tab Modular Settings)
|
||||
'settings.subTab.general': 'General',
|
||||
'settings.subTab.structure': 'Structure',
|
||||
'settings.subTab.other': 'Other',
|
||||
'settings.subTab.aria': 'Preferences category tabs',
|
||||
'settings.saving': 'Saving…',
|
||||
'settings.saved': 'Saved',
|
||||
'settings.saveFailed': 'Save failed',
|
||||
'settings.resetDone': 'Reset to default',
|
||||
'settings.resetBtn': 'Reset',
|
||||
|
||||
// Preferences -> General Tab
|
||||
'settings.gen.appearanceTitle': 'Interface & Appearance',
|
||||
'settings.gen.language': 'Language',
|
||||
'settings.gen.langZh': '简体中文',
|
||||
'settings.gen.langEn': 'English',
|
||||
'settings.gen.langAuto': 'Follow System',
|
||||
'settings.gen.themeAccent': 'Accent Color',
|
||||
'settings.gen.accentHost': 'Host',
|
||||
'settings.gen.accentBlue': 'Blue',
|
||||
'settings.gen.accentEmerald': 'Emerald',
|
||||
'settings.gen.accentAmber': 'Amber',
|
||||
'settings.gen.accentViolet': 'Violet',
|
||||
'settings.gen.accentCyan': 'Cyan',
|
||||
'settings.gen.accentRose': 'Rose',
|
||||
'settings.gen.fontScale': 'Font Size',
|
||||
'settings.gen.fontSm': 'Small',
|
||||
'settings.gen.fontMd': 'Default',
|
||||
'settings.gen.fontLg': 'Large',
|
||||
'settings.gen.fontXl': 'XL',
|
||||
'settings.gen.fontHint': 'Scales sidebar and popover typography while keeping the inline capsule compact',
|
||||
'settings.gen.updateTitle': 'Updates & Pricing',
|
||||
'settings.gen.updateMode': 'Update Policy',
|
||||
'settings.gen.updateManual': 'Notify only, update manually',
|
||||
'settings.gen.updateAuto': 'Auto update',
|
||||
'settings.gen.updateOff': 'Disable updates',
|
||||
'settings.gen.pricingLabel': 'Pricing Catalog',
|
||||
'settings.gen.versionLabel': 'Current Version',
|
||||
'settings.gen.modelCount': '{count} models',
|
||||
'settings.gen.srcRemote': 'Cloud synced',
|
||||
'settings.gen.srcLocal': 'Local file',
|
||||
'settings.gen.srcDefault': 'Built-in',
|
||||
'settings.gen.syncAt': 'Synced {time}',
|
||||
'settings.gen.pubAt': 'Published {date}',
|
||||
'settings.gen.defaultPricing': 'Default catalog',
|
||||
'settings.gen.syncBtn': 'Sync Pricing',
|
||||
'settings.gen.syncingBtn': 'Syncing…',
|
||||
'settings.gen.syncingMsg': 'Syncing pricing catalog…',
|
||||
'settings.gen.syncedMsg': 'Pricing updated ({count} models)',
|
||||
'settings.gen.syncFallbackMsg': 'Timed out, using local catalog',
|
||||
'settings.gen.checkUpdateBtn': 'Check Updates',
|
||||
'settings.gen.checkingBtn': 'Checking…',
|
||||
'settings.gen.checkingMsg': 'Checking for updates…',
|
||||
'settings.gen.checkFailedMsg': 'Check failed: {err}',
|
||||
'settings.gen.upToDateMsg': 'Already up to date (v{ver})',
|
||||
'settings.gen.downloadingMsg': 'Downloading update…',
|
||||
'settings.gen.updatedRestartMsg': 'Update complete, restarting panel…',
|
||||
'settings.gen.updateSkippedMsg': 'Update not applied',
|
||||
'settings.gen.updateFailedMsg': 'Update failed',
|
||||
'settings.gen.canUpgradeSub': 'v{ver} available ({mode})',
|
||||
'settings.gen.upgradeToBtn': 'Upgrade to v{ver}',
|
||||
'settings.gen.manualUpgradeBtn': 'Upgrade v{ver}',
|
||||
'settings.gen.updateOffSub': 'Notifications off ({mode})',
|
||||
'settings.gen.latestSub': 'Up to date ({mode})',
|
||||
|
||||
// Preferences -> Structure Tab
|
||||
'settings.str.mountSection': 'Mount & Capsule Bar',
|
||||
'settings.str.mountBadge': '{count}/5 slots',
|
||||
'settings.str.mountMode': 'Panel Mount Mode',
|
||||
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
|
||||
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
||||
'settings.str.mountSidebar': 'Sidebar Only',
|
||||
'settings.str.multiToggle': 'Active Sessions Pill',
|
||||
'settings.str.show': 'Show',
|
||||
'settings.str.hide': 'Hide',
|
||||
'settings.str.capsuleSlotsLabel': 'Capsule Metrics & Order (Left → Right, 1–5)',
|
||||
'settings.str.addCapsuleSlot': 'Add Slot ({count}/{max})',
|
||||
'settings.str.hoverSection': 'Hover Quick-View',
|
||||
'settings.str.hoverBadgeOff': 'Off',
|
||||
'settings.str.hoverBadgeCount': '{count} modules',
|
||||
'settings.str.hoverModulesLabel': 'Hover Popup Modules (Top → Bottom, 0–4)',
|
||||
'settings.str.hoverEmptyHint': 'Hover quick-view disabled (click capsule to open full panel)',
|
||||
'settings.str.addHoverModule': 'Add Module ({count}/{max})',
|
||||
'settings.str.overviewSection': 'Live Overview Layout',
|
||||
'settings.str.overviewBadge': '{modCount} mod · {metCount} cells',
|
||||
'settings.str.overviewModulesLabel': 'Overview Modules & Order (Top → Bottom, min 1)',
|
||||
'settings.str.addOverviewModule': 'Add Module ({count}/{max})',
|
||||
'settings.str.overviewMetricsLabel': 'First-Row Metrics (Left → Right, 1–4)',
|
||||
'settings.str.overviewMetricsInactiveHint': '"Live Metrics" is hidden here; these cells still apply to Hover Quick-View or when re-added',
|
||||
'settings.str.addOverviewMetric': 'Add Metric ({count}/{max})',
|
||||
'settings.str.stepsSection': 'Step Table Columns',
|
||||
'settings.str.stepsBadge': '{count} cols',
|
||||
'settings.str.stepsColsLabel': '"Steps" Visible Columns (Left → Right, min 2)',
|
||||
'settings.str.addStepCol': 'Add Column ({count}/{max})',
|
||||
'settings.slot.moveUp': 'Move earlier',
|
||||
'settings.slot.moveDown': 'Move later',
|
||||
'settings.slot.remove': 'Remove item',
|
||||
'settings.slot.minReached': 'Keep at least {min}',
|
||||
'settings.slot.alreadyAdded': 'Added',
|
||||
|
||||
// Preferences -> Other Tab
|
||||
'settings.oth.modelTitle': 'Model Identity Display',
|
||||
'settings.oth.modelFormat': 'Model Name Format',
|
||||
'settings.oth.modelShort': 'Short Alias (e.g. argon-4-high)',
|
||||
'settings.oth.modelUpstream': 'Raw Upstream ID (e.g. gemini-3.8-flash-n)',
|
||||
'settings.oth.orchFormat': 'Orchestrator Series ID',
|
||||
'settings.oth.orchCompact': 'Compact Alias (e.g. orchestrator-argon)',
|
||||
'settings.oth.orchFull': 'Full Upstream ID (e.g. gemini-pro-orchestrator)',
|
||||
'settings.oth.baselineTitle': 'Model Context Settings',
|
||||
'settings.oth.ctxModel': 'Model',
|
||||
'settings.oth.ctxBaselineLabel': 'Context Window Limit',
|
||||
'settings.oth.ctxChooseModel': 'Choose a model',
|
||||
'settings.oth.ctxDefault': 'Follow host settings',
|
||||
'settings.oth.ctxExpensive': '{name} (uses more quota)',
|
||||
'settings.oth.ctxTokens': '{count} tokens',
|
||||
'settings.oth.ctxUnavailable': '{name} (currently unavailable)',
|
||||
'settings.oth.ctxConfigured': '{name} · Set',
|
||||
'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}',
|
||||
'settings.oth.ctxDefaultReported': 'Default · Last seen {name}',
|
||||
'settings.oth.ctxReported': 'The host reported {name} on the latest request.',
|
||||
'settings.oth.ctxMixed': 'Different limits by thinking level',
|
||||
'settings.oth.ctxMixedHint': 'Thinking levels for this model have different saved limits. Choose a limit to apply it to all levels.',
|
||||
'settings.oth.ctxBaselineHint': 'Thinking levels for the same model share a limit. Saved limits are reapplied at plugin startup and used for future messages.',
|
||||
'settings.oth.ctxNoModels': 'The host has not returned any available models.',
|
||||
'settings.oth.ctxNoOptions': 'The host has not provided context options or a capacity for this model. Follow host settings is the only available option.',
|
||||
'settings.oth.maintTitle': 'Cache & Reset',
|
||||
'settings.oth.cacheLabel': 'Local Trajectory Cache',
|
||||
'settings.oth.cacheDesc': 'Clear cached step records and rescan all conversation transcripts immediately',
|
||||
'settings.oth.rebuildBtn': 'Rebuild Trajectory Cache',
|
||||
'settings.oth.rebuildingBtn': 'Rebuilding…',
|
||||
'settings.oth.rebuildDone': 'Trajectory cache rebuilt',
|
||||
'settings.oth.rebuildFailed': 'Failed to rebuild cache',
|
||||
'settings.oth.resetLabel': 'Factory Defaults',
|
||||
'settings.oth.resetDesc': 'Restore all preferences across General, Structure, and Other tabs to default values',
|
||||
'settings.oth.resetAllBtn': 'Reset All Defaults',
|
||||
'settings.oth.resetConfirmBtn': 'Click Again to Confirm',
|
||||
'settings.oth.resettingBtn': 'Resetting…',
|
||||
'settings.oth.resetAllDone': 'All preferences restored to defaults',
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* @fileoverview Reactive lightweight i18n engine (`zh-CN` / `en-US` / `auto`).
|
||||
* Default language is `'zh-CN'` so out-of-the-box UI matches existing behavior 100%.
|
||||
*/
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { I18N_MESSAGES_ZH_CN } from './zh-CN.js';
|
||||
import { I18N_MESSAGES_EN_US } from './en-US.js';
|
||||
|
||||
export const I18N_DICTIONARIES = Object.freeze({
|
||||
'zh-CN': I18N_MESSAGES_ZH_CN,
|
||||
'en-US': I18N_MESSAGES_EN_US,
|
||||
});
|
||||
|
||||
export function normalizeI18nLanguage(raw) {
|
||||
const val = String(raw ?? '').trim();
|
||||
if (val === 'auto') return 'auto';
|
||||
if (/^en(?:-|$)/i.test(val)) return 'en-US';
|
||||
if (/^zh(?:-|$)/i.test(val)) return 'zh-CN';
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
export function detectHostSystemLocale() {
|
||||
try {
|
||||
if (typeof navigator !== 'undefined' && navigator.language) {
|
||||
return String(navigator.language).toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US';
|
||||
}
|
||||
} catch {
|
||||
// Ignore environment navigator read errors
|
||||
}
|
||||
return 'zh-CN';
|
||||
}
|
||||
|
||||
export const i18nStore = createReactiveStore({
|
||||
language: 'zh-CN',
|
||||
locale: 'zh-CN',
|
||||
});
|
||||
|
||||
export function setI18nLanguage(rawLang) {
|
||||
const language = normalizeI18nLanguage(rawLang);
|
||||
const locale = language === 'auto' ? detectHostSystemLocale() : language;
|
||||
const cur = i18nStore.getState();
|
||||
if (cur.language !== language || cur.locale !== locale) {
|
||||
i18nStore.setState({ language, locale });
|
||||
}
|
||||
return locale;
|
||||
}
|
||||
|
||||
export function getEffectiveLocale() {
|
||||
return i18nStore.getState().locale || 'zh-CN';
|
||||
}
|
||||
|
||||
export function isEnglishLocale() {
|
||||
return getEffectiveLocale() === 'en-US';
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a message key with optional `{name}` variable interpolation.
|
||||
*
|
||||
* @param {string} key
|
||||
* @param {Record<string, string | number>} [vars]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function t(key, vars = undefined) {
|
||||
const locale = getEffectiveLocale();
|
||||
const dict = I18N_DICTIONARIES[locale] || I18N_MESSAGES_ZH_CN;
|
||||
const template = dict[key] ?? I18N_MESSAGES_ZH_CN[key] ?? key;
|
||||
if (!vars || typeof template !== 'string') return template;
|
||||
return template.replace(/\{(\w+)\}/g, (_, k) =>
|
||||
vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : ''
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
/**
|
||||
* @fileoverview Simplified Chinese (zh-CN) dictionary for Antigravity Usage & Speed Monitor.
|
||||
* Matches 100% of the existing out-of-the-box UI copy. Zero emoji characters.
|
||||
*/
|
||||
|
||||
export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
// Top Navigation
|
||||
'nav.overview': '实时监控',
|
||||
'nav.consumption': '用量统计',
|
||||
'nav.steps': '调用明细',
|
||||
'nav.settings': '偏好设置',
|
||||
|
||||
// Top Session Header
|
||||
'header.followLatest': '跟随最新会话',
|
||||
'header.currentWindowNamed': '当前窗口 ({title})',
|
||||
'header.latestNamed': '最新 ({title})',
|
||||
'header.lockedSession': '已锁定会话 ({id})',
|
||||
'header.lockedMeta': '已锁定',
|
||||
'header.convMetaWithSubs': '主{main} · {subs}子 (共{total}步)',
|
||||
'header.convMetaSteps': '{count}步',
|
||||
'header.hasUpdate': '有新版本',
|
||||
'header.upgradeToVer': '升级 v{ver}',
|
||||
'header.upgrading': '升级中…',
|
||||
'header.ariaUpdate': '发现新版本,点击升级',
|
||||
'header.ariaRefresh': '刷新数据',
|
||||
'header.statusSyncing': '同步中',
|
||||
'header.statusSynced': '已刷新',
|
||||
'header.statusRetrying': '重试中',
|
||||
'header.statusGenerating': '生成中{suffix}',
|
||||
'header.statusQuotaCached': '额度缓存',
|
||||
'header.statusQuotaOffline': '额度离线',
|
||||
'header.statusLive': '实时 2s',
|
||||
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': '待定',
|
||||
'fmt.speedIncomplete': '计时不完整',
|
||||
'fmt.speedInvalidOutput': '无有效输出',
|
||||
'fmt.speedInconsistent': '耗时数据异常',
|
||||
'fmt.speedShort': '耗时过短 (<0.5s)',
|
||||
'fmt.speedLegacy': '旧版缓存记录',
|
||||
'fmt.sampleSteps': '{valid}/{total} 步',
|
||||
'fmt.resetUnknown': '未知重置时间',
|
||||
'fmt.resetSoon': '即将重置',
|
||||
'fmt.resetUnder1m': '<1分钟后重置',
|
||||
'fmt.resetDaysHours': '{d}天 {h}小时后重置',
|
||||
'fmt.resetHoursMins': '{h}小时 {m}分后重置',
|
||||
'fmt.resetMins': '{m}分钟后重置',
|
||||
'fmt.selectTime': '选择时间',
|
||||
'fmt.unknownModel': '模型未知',
|
||||
'fmt.mainAgent': '主代理',
|
||||
'fmt.mainBadge': '主',
|
||||
'fmt.subAgent': '子代理',
|
||||
'fmt.subBadge': '子{index}',
|
||||
'fmt.subBadgeShort': '子',
|
||||
'fmt.selectedCount': '已选 {count} {unit}',
|
||||
'fmt.selectedListTitle': '已选 ({count}):{names}',
|
||||
'fmt.selectPlaceholder': '请选择',
|
||||
|
||||
// Capsule & Multi-Session Overlay
|
||||
'capsule.ariaMonitor': '用量与速度监控',
|
||||
'capsule.ariaMulti': '多会话实时信息',
|
||||
'capsule.multiZero': '0 运行中',
|
||||
'capsule.multiRunning': '{count} 运行中',
|
||||
'capsule.multiRunningWithSubs': '{count} 运行 · {subs} 子',
|
||||
'capsule.tpsRunning': '生成中',
|
||||
'capsule.tpsIdle': '待命',
|
||||
'capsule.quotaLeft': '余 {pct}%',
|
||||
'capsule.quotaUnknown': '余 --%',
|
||||
'capsule.newVersion': '新版本',
|
||||
'capsule.updating': '更新中…',
|
||||
'capsule.ariaUpdateTitle': '发现新版本,点击立即更新',
|
||||
'capsule.hoverNewVer': '发现新版本 v{ver}',
|
||||
'capsule.hoverNewVerGeneric': '发现新版本可用',
|
||||
'capsule.hoverUpdateHintTopbar': '点击顶栏 v{ver} 即可更新',
|
||||
'capsule.hoverUpdateHintComposer': '点击版本胶囊 v{ver} 即可更新',
|
||||
'capsule.hoverUpdateHintTopbarGeneric': '点击顶栏版本胶囊即可更新',
|
||||
'capsule.hoverUpdateHintComposerGeneric': '点击版本胶囊即可更新',
|
||||
'multi.title': '实时运行会话',
|
||||
'multi.ariaDialog': '多会话实时信息面板',
|
||||
'multi.pinned': '已固定',
|
||||
'multi.loading': '读取中...',
|
||||
'multi.empty': '当前暂无在线运行的会话',
|
||||
'multi.allIdle': '全部待命',
|
||||
'multi.metaWithSubs': '{main} 主会话 · {subs} 子代理运行中',
|
||||
'multi.metaMainOnly': '{main} 个会话运行中',
|
||||
'multi.hereTag': '本窗',
|
||||
'multi.inspectSessionTitle': '点击在监控面板中检视会话:{title}',
|
||||
|
||||
// Live Overview & Widgets
|
||||
'module.metrics': '实时指标',
|
||||
'module.context': '上下文窗口',
|
||||
'module.quotas': '可用额度',
|
||||
'module.live_tasks': '实时运行任务',
|
||||
|
||||
// Capsule Slot Metric Options
|
||||
'capMetric.context': '上下文占用 (%)',
|
||||
'capMetric.tps': '输出速度 (TPS)',
|
||||
'capMetric.ttft': '首字延迟 (TTFT)',
|
||||
'capMetric.avg_tps': '会话均速 (Avg TPS)',
|
||||
'capMetric.cost': '本次费用 ($)',
|
||||
'capMetric.session_cost': '会话累计费用 ($)',
|
||||
'capMetric.cache_hit': '缓存命中率 (%)',
|
||||
'capMetric.session_tokens': '会话总 Token',
|
||||
'capMetric.quota_auto': '自动紧俏额度',
|
||||
'capMetric.gemini_5h': 'Gemini 5h 额度',
|
||||
'capMetric.gemini_weekly': 'Gemini 周额度',
|
||||
'capMetric.claude_5h': 'Claude 5h 额度',
|
||||
'capMetric.claude_weekly': 'Claude 周额度',
|
||||
|
||||
// Overview Matrix Metric Options & Cells
|
||||
'ovMetric.tps': '输出速度',
|
||||
'ovMetric.ttft': '首字延迟',
|
||||
'ovMetric.avg_tps': '平均速度',
|
||||
'ovMetric.step_cost': '本次费用',
|
||||
'ovMetric.session_cost': '累计费用',
|
||||
'ovMetric.cache_hit': '缓存命中率',
|
||||
'ovMetric.session_tokens': '会话 Token',
|
||||
'ovMetric.context_usage': '上下文占用',
|
||||
'ovMetric.quota_tightest': '紧俏额度',
|
||||
'ovMetric.subAvgTtft': '均值 {val}',
|
||||
'ovMetric.subValidSamples': '有效 {samples}',
|
||||
'ovMetric.subCacheAndTotal': '缓存 {cache}% · 累计 {cost}',
|
||||
'ovMetric.subStepsAndCache': '{steps} 步 · 缓存 {cache}%',
|
||||
'ovMetric.subStepCost': '单步 {cost}',
|
||||
'ovMetric.subPromptHit': '当步 {latest}% · 均值 {avg}%',
|
||||
'ovMetric.subInOutTokens': '入 {inTok} · 出 {outTok}',
|
||||
'ovMetric.subCtxRatio': '{used} / {limit}',
|
||||
'ovMetric.subQuotaPool': '{label}',
|
||||
'ovMetric.subQuotaPending': '等待配额同步',
|
||||
|
||||
// Context Window Widget
|
||||
'ctx.followActive': '跟随活跃 ({badge})',
|
||||
'ctx.followActiveTitle': '自动展示当前正在运行或最新活跃的代理上下文窗口',
|
||||
'ctx.expandMore': '+{count} 展开 ▾',
|
||||
'ctx.expandMoreTitle': '展开全部 {count} 个子代理的上下文窗口胶囊',
|
||||
'ctx.collapse': '收起 ▴',
|
||||
'ctx.collapseTitle': '折叠多余子代理胶囊',
|
||||
'ctx.ch.assistant': '模型回复',
|
||||
'ctx.ch.assistantTitle': '模型推理思考、回复正文与工具调用入参',
|
||||
'ctx.ch.toolResults': '工具结果',
|
||||
'ctx.ch.toolResultsTitle': '文件读取、终端输出与工具执行返回内容',
|
||||
'ctx.ch.userInput': '用户消息',
|
||||
'ctx.ch.userInputTitle': '用户提问文本与上传附件',
|
||||
'ctx.ch.subagent': '子代理通知',
|
||||
'ctx.ch.subagentTitle': '子代理完成汇报与后台任务系统通知',
|
||||
'ctx.ch.checkpoint': '压缩摘要',
|
||||
'ctx.ch.checkpointTitle': '自动上下文压缩生成的历史摘要检查点',
|
||||
'ctx.ch.systemPrompt': '系统提示词',
|
||||
'ctx.ch.systemPromptTitle': '核心身份、终端沙箱、制品与环境提示词',
|
||||
'ctx.ch.systemTools': '系统工具',
|
||||
'ctx.ch.systemToolsTitle': '内置系统工具 Schema 定义',
|
||||
'ctx.ch.mcpTools': 'MCP 工具',
|
||||
'ctx.ch.mcpToolsTitle': 'MCP 外部服务工具与资源定义',
|
||||
'ctx.ch.skills': 'Skill',
|
||||
'ctx.ch.skillsTitle': '已挂载的 Skills 技能索引与说明',
|
||||
'ctx.ch.userRules': '用户规则',
|
||||
'ctx.ch.userRulesTitle': '全局与工作区自定义规则 (user_rules)',
|
||||
|
||||
// Quota Pools Widget
|
||||
'quota.weeklyShort': '周限',
|
||||
'quota.weeklyPool': '周限 ({pool})',
|
||||
'quota.loading': '读取中...',
|
||||
'quota.failed': '获取失败 (--%)',
|
||||
'quota.usedAndLeft': '{reset} · 已用 {used}% (余 {rem}%)',
|
||||
'quota.cycle5hTitle': '当前 5h 周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用',
|
||||
'quota.cycleWkCustomTitle': '本周自然周累计:{tok} Tokens · {cost} · {calls} 次调用',
|
||||
'quota.cycleWkPoolTitle': '当前周限周期累计 ({pool}):{tok} Tokens · {cost} · {calls} 次调用',
|
||||
'quota.footTokensCustom': '本周累计: {tok} ({cost})',
|
||||
'quota.footTokensCycle': '周期累计: {tok} ({cost})',
|
||||
'quota.footCredits': 'AI 积分: {credits}',
|
||||
'quota.footCallsCustom': '本周调用: {calls} 次',
|
||||
'quota.footCallsCycle': '周期调用: {calls} 次',
|
||||
'quota.footTipCustom': '按本机自然周(周一 00:00 起)统计',
|
||||
'quota.footTipCycle': '按各配额池独立周限重置周期分别统计并汇总',
|
||||
|
||||
// Live Activity Widget
|
||||
'live.currentSession': '当前会话',
|
||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||
'live.thinking': '推理中',
|
||||
'live.running': '运行中',
|
||||
'live.done': '已完成',
|
||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||
'live.subToggleRunning': '子代理 {run}/{total} {arrow}',
|
||||
'live.subToggleIdle': '子代理 ({total}) {arrow}',
|
||||
'live.subCollapseTitle': '点击收起子代理列表',
|
||||
'live.subExpandTitle': '点击展开查看子代理缩略状态',
|
||||
|
||||
// Consumption View
|
||||
'cons.rangeToday': '今天',
|
||||
'cons.range24h': '1天',
|
||||
'cons.range7d': '7天',
|
||||
'cons.range14d': '14天',
|
||||
'cons.range30d': '30天',
|
||||
'cons.rangeAll': '全部',
|
||||
'cons.rangeCustom': '自定义',
|
||||
'cons.rangeAria': '消耗统计时间范围',
|
||||
'cons.applyFilter': '筛选',
|
||||
'cons.rangeTo': '至',
|
||||
'cons.overviewTitle': '用量总览',
|
||||
'cons.totalTokens': '总 Token',
|
||||
'cons.estCost': '预估费用',
|
||||
'cons.cacheHitRate': '缓存命中率',
|
||||
'cons.callsCount': '{calls} 次',
|
||||
'cons.cacheHitTokens': '命中 {tokens}',
|
||||
'cons.newInput': '新输入',
|
||||
'cons.uncachedInput': '未命中缓存输入',
|
||||
'cons.cacheRead': '缓存读取',
|
||||
'cons.savedCost': '节省 {cost}',
|
||||
'cons.outputUsage': '输出用量',
|
||||
'cons.replyAndThink': '回复 {resp} · 思考 {think}',
|
||||
'cons.trendTitle': '用量趋势',
|
||||
'cons.allTime': '全部时间',
|
||||
'cons.trendHeatmapHint': '按日 ({days}天) · 悬停查看',
|
||||
'cons.trendPointsHintHourly': '按小时 ({points}点) · 悬停查看',
|
||||
'cons.trendPointsHintDaily': '按日 ({points}点) · 悬停查看',
|
||||
'cons.topModels': '模型排行',
|
||||
'cons.clientSources': '客户端来源',
|
||||
'cons.monthlyTitle': '月度统计',
|
||||
'cons.monthLabel': '{m}月',
|
||||
'cons.legInput': '输入',
|
||||
'cons.legCache': '缓存',
|
||||
'cons.legOutput': '输出',
|
||||
'cons.legThinking': '思考',
|
||||
'cons.footInput': '输入 ',
|
||||
'cons.footCache': '缓存 ',
|
||||
'cons.footOutput': '输出 ',
|
||||
'cons.footThinking': '思考 ',
|
||||
'cons.footCalls': '调用 ',
|
||||
|
||||
// Steps Detail View & Step Column Registry
|
||||
'steps.title': '调用记录',
|
||||
'steps.tabSteps': '按步查看 ({count})',
|
||||
'steps.tabStepsFiltered': '按步查看 ({filtered}/{total})',
|
||||
'steps.tabModels': '总汇总',
|
||||
'steps.allAgents': '全部汇总',
|
||||
'steps.allModels': '全部模型',
|
||||
'steps.selectModel': '选择模型',
|
||||
'steps.unitAgent': '代理',
|
||||
'steps.unitModel': '模型',
|
||||
'steps.lineTitle': '会话走势',
|
||||
'steps.fitTitle': '趋势拟合',
|
||||
'steps.modelsTitle': '模型总览',
|
||||
'steps.modelsEmpty': '当前范围暂无模型调用记录',
|
||||
'steps.metricTotalTokens': '总Token',
|
||||
'steps.metricContext': '上下文',
|
||||
'steps.metricTps': 'TPS',
|
||||
'steps.metricTtft': '首字',
|
||||
'steps.metricCache': '缓存',
|
||||
'steps.metricCost': '费用',
|
||||
'steps.badgeBackAll': '点击切回全部汇总',
|
||||
'steps.badgeFilterAgent': '点击仅过滤查看 {agent}(按住 Ctrl/Shift 可加减多选)',
|
||||
'steps.ctxTitle': '上下文 {ctx} · 思考 {think} · 正文 {resp}',
|
||||
'steps.modelCallsShare': '{calls}次 · {pct}%',
|
||||
'steps.modelCallsOnly': '{calls}次',
|
||||
'steps.modelsSummaryPrefix': '{count} 模型 · ',
|
||||
'steps.modelPerfFoot': '均速 {tps} · 首字 {ttft} · 缓存 {cache}%',
|
||||
'steps.modelSplitFoot': '入 {inTok} · 缓 {cacheTok} · 思 {thinkTok} · 正 {respTok}',
|
||||
'steps.fitActiveCardTitle': '{title}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)',
|
||||
'steps.fitInactiveCardTitle': '点击在上方拟合图查看 {text}(按住 Ctrl/Shift 点击可多选同图对比)',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': '步序',
|
||||
'stepCol.step.opt': '步序与代理',
|
||||
'stepCol.time.th': '时间',
|
||||
'stepCol.time.opt': '调用时间 (HH:mm:ss)',
|
||||
'stepCol.model.th': '模型',
|
||||
'stepCol.model.opt': '调用模型',
|
||||
'stepCol.tps.th': '速度',
|
||||
'stepCol.tps.opt': '输出速度 (TPS)',
|
||||
'stepCol.ttft.th': '首字',
|
||||
'stepCol.ttft.opt': '首字延迟 (TTFT)',
|
||||
'stepCol.duration.th': '耗时',
|
||||
'stepCol.duration.opt': '端到端耗时 (s)',
|
||||
'stepCol.tokens_combo.th': '上下文 / 思考 / 正文',
|
||||
'stepCol.tokens_combo.opt': '上下文 / 思考 / 正文 (组合)',
|
||||
'stepCol.input_tokens.th': '新输入',
|
||||
'stepCol.input_tokens.opt': '新输入 Token',
|
||||
'stepCol.cache_tokens.th': '缓存读',
|
||||
'stepCol.cache_tokens.opt': '缓存读取 Token',
|
||||
'stepCol.output_tokens.th': '总输出',
|
||||
'stepCol.output_tokens.opt': '总输出 Token',
|
||||
'stepCol.cache.th': '缓存',
|
||||
'stepCol.cache.opt': '缓存命中率 (%)',
|
||||
'stepCol.cost.th': '费用',
|
||||
'stepCol.cost.opt': '单步费用 ($)',
|
||||
|
||||
// Preferences (3-Tab Modular Settings)
|
||||
'settings.subTab.general': '常规',
|
||||
'settings.subTab.structure': '结构',
|
||||
'settings.subTab.other': '其他',
|
||||
'settings.subTab.aria': '偏好设置分类切换',
|
||||
'settings.saving': '保存中…',
|
||||
'settings.saved': '已保存',
|
||||
'settings.saveFailed': '保存失败',
|
||||
'settings.resetDone': '已恢复默认',
|
||||
'settings.resetBtn': '恢复默认',
|
||||
|
||||
// Preferences -> General Tab
|
||||
'settings.gen.appearanceTitle': '界面与外观',
|
||||
'settings.gen.language': '界面语言',
|
||||
'settings.gen.langZh': '简体中文',
|
||||
'settings.gen.langEn': 'English',
|
||||
'settings.gen.langAuto': '跟随系统',
|
||||
'settings.gen.themeAccent': '主题色',
|
||||
'settings.gen.accentHost': '跟随宿主',
|
||||
'settings.gen.accentBlue': '经典蓝',
|
||||
'settings.gen.accentEmerald': '翡翠绿',
|
||||
'settings.gen.accentAmber': '琥珀橙',
|
||||
'settings.gen.accentViolet': '鸢尾紫',
|
||||
'settings.gen.accentCyan': '青碧色',
|
||||
'settings.gen.accentRose': '玫瑰红',
|
||||
'settings.gen.fontScale': '字体大小',
|
||||
'settings.gen.fontSm': '小',
|
||||
'settings.gen.fontMd': '标准',
|
||||
'settings.gen.fontLg': '大',
|
||||
'settings.gen.fontXl': '特大',
|
||||
'settings.gen.fontHint': '等比缩放侧边栏与展开面板字号,顶栏及输入框内嵌胶囊保持紧凑定高',
|
||||
'settings.gen.updateTitle': '版本更新',
|
||||
'settings.gen.updateMode': '更新方式',
|
||||
'settings.gen.updateManual': '仅提示新版本,手动更新',
|
||||
'settings.gen.updateAuto': '自动更新',
|
||||
'settings.gen.updateOff': '关闭更新',
|
||||
'settings.gen.pricingLabel': '价格表',
|
||||
'settings.gen.versionLabel': '当前版本',
|
||||
'settings.gen.modelCount': '{count} 个模型',
|
||||
'settings.gen.srcRemote': '云端同步',
|
||||
'settings.gen.srcLocal': '本地文件',
|
||||
'settings.gen.srcDefault': '内置默认',
|
||||
'settings.gen.syncAt': '更新于 {time}',
|
||||
'settings.gen.pubAt': '发布于 {date}',
|
||||
'settings.gen.defaultPricing': '默认价格',
|
||||
'settings.gen.syncBtn': '更新价格表',
|
||||
'settings.gen.syncingBtn': '更新中…',
|
||||
'settings.gen.syncingMsg': '正在同步价格表…',
|
||||
'settings.gen.syncedMsg': '价格表已更新 ({count} 个模型)',
|
||||
'settings.gen.syncFallbackMsg': '连接超时,使用本地价格表',
|
||||
'settings.gen.checkUpdateBtn': '检查更新',
|
||||
'settings.gen.checkingBtn': '检查中…',
|
||||
'settings.gen.checkingMsg': '正在检查新版本…',
|
||||
'settings.gen.checkFailedMsg': '检查失败:{err}',
|
||||
'settings.gen.upToDateMsg': '当前已是最新版本 (v{ver})',
|
||||
'settings.gen.downloadingMsg': '正在下载更新…',
|
||||
'settings.gen.updatedRestartMsg': '更新完成,正在重启面板…',
|
||||
'settings.gen.updateSkippedMsg': '未执行更新',
|
||||
'settings.gen.updateFailedMsg': '更新失败',
|
||||
'settings.gen.canUpgradeSub': '可升级至 v{ver} ({mode})',
|
||||
'settings.gen.upgradeToBtn': '升级至 v{ver}',
|
||||
'settings.gen.manualUpgradeBtn': '手动升级 v{ver}',
|
||||
'settings.gen.updateOffSub': '已关闭更新提醒 ({mode})',
|
||||
'settings.gen.latestSub': '已是最新 ({mode})',
|
||||
|
||||
// Preferences -> Structure Tab
|
||||
'settings.str.mountSection': '挂载与胶囊栏',
|
||||
'settings.str.mountBadge': '{count}/5 项',
|
||||
'settings.str.mountMode': '面板挂载方式',
|
||||
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
||||
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
||||
'settings.str.mountSidebar': '仅侧边栏',
|
||||
'settings.str.multiToggle': '实时运行会话入口',
|
||||
'settings.str.show': '显示',
|
||||
'settings.str.hide': '隐藏',
|
||||
'settings.str.capsuleSlotsLabel': '胶囊数值与顺序 (左 → 右,1~5 项)',
|
||||
'settings.str.addCapsuleSlot': '添加槽位 ({count}/{max})',
|
||||
'settings.str.hoverSection': '鼠标悬浮窗',
|
||||
'settings.str.hoverBadgeOff': '已关闭',
|
||||
'settings.str.hoverBadgeCount': '{count} 模块',
|
||||
'settings.str.hoverModulesLabel': '悬浮窗展示模块 (上 → 下,0~4 项)',
|
||||
'settings.str.hoverEmptyHint': '已关闭悬浮速览窗(点击胶囊仍可展开完整面板)',
|
||||
'settings.str.addHoverModule': '添加模块 ({count}/{max})',
|
||||
'settings.str.overviewSection': '实时监控布局',
|
||||
'settings.str.overviewBadge': '{modCount} 模块 · {metCount} 指标',
|
||||
'settings.str.overviewModulesLabel': '监控模块与顺序 (上 → 下,至少 1 项)',
|
||||
'settings.str.addOverviewModule': '添加模块 ({count}/{max})',
|
||||
'settings.str.overviewMetricsLabel': '第一行实时指标 (左 → 右,1~4 项)',
|
||||
'settings.str.overviewMetricsInactiveHint': '当前已移出「实时指标」模块,此配置将在悬浮窗启用或重新添加模块时生效',
|
||||
'settings.str.addOverviewMetric': '添加指标 ({count}/{max})',
|
||||
'settings.str.stepsSection': '调用明细字段',
|
||||
'settings.str.stepsBadge': '{count} 列',
|
||||
'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列)',
|
||||
'settings.str.addStepCol': '添加字段 ({count}/{max})',
|
||||
'settings.slot.moveUp': '前移',
|
||||
'settings.slot.moveDown': '后移',
|
||||
'settings.slot.remove': '移除此项',
|
||||
'settings.slot.minReached': '至少保留 {min} 项',
|
||||
'settings.slot.alreadyAdded': '已添加',
|
||||
|
||||
// Preferences -> Other Tab
|
||||
'settings.oth.modelTitle': '模型标识显示',
|
||||
'settings.oth.modelFormat': '模型名称格式',
|
||||
'settings.oth.modelShort': '精简代号 (如 argon-4-high)',
|
||||
'settings.oth.modelUpstream': '原始模型 ID (如 gemini-3.8-flash-n)',
|
||||
'settings.oth.orchFormat': 'Orchestrator 系列 ID',
|
||||
'settings.oth.orchCompact': '精简代号 (如 orchestrator-argon)',
|
||||
'settings.oth.orchFull': '原始完整 ID (如 gemini-pro-orchestrator)',
|
||||
'settings.oth.baselineTitle': '模型上下文设置',
|
||||
'settings.oth.ctxModel': '模型',
|
||||
'settings.oth.ctxBaselineLabel': '上下文窗口上限',
|
||||
'settings.oth.ctxChooseModel': '选择模型',
|
||||
'settings.oth.ctxDefault': '跟随宿主设置',
|
||||
'settings.oth.ctxExpensive': '{name}(消耗更多配额)',
|
||||
'settings.oth.ctxTokens': '{count} token',
|
||||
'settings.oth.ctxUnavailable': '{name}(当前不可用)',
|
||||
'settings.oth.ctxConfigured': '{name} · 已设置',
|
||||
'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}',
|
||||
'settings.oth.ctxDefaultReported': '默认 · 最近 {name}',
|
||||
'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。',
|
||||
'settings.oth.ctxMixed': '各推理档设置不同',
|
||||
'settings.oth.ctxMixedHint': '该模型的推理档保留了不同的旧设置。选择一个上限即可统一。',
|
||||
'settings.oth.ctxBaselineHint': '同一模型的推理档共享上限。插件会在启动后重新应用已保存的设置,用于之后发送的消息。',
|
||||
'settings.oth.ctxNoModels': '宿主暂未返回可用模型。',
|
||||
'settings.oth.ctxNoOptions': '宿主未提供此模型的上下文档位或容量,当前只能跟随宿主设置。',
|
||||
'settings.oth.maintTitle': '缓存与重置',
|
||||
'settings.oth.cacheLabel': '本地轨迹缓存',
|
||||
'settings.oth.cacheDesc': '清空内存与磁盘步骤解析缓存并立即重扫全部会话',
|
||||
'settings.oth.rebuildBtn': '重建本地轨迹缓存',
|
||||
'settings.oth.rebuildingBtn': '重建中…',
|
||||
'settings.oth.rebuildDone': '本地轨迹缓存已重建',
|
||||
'settings.oth.rebuildFailed': '缓存重建失败',
|
||||
'settings.oth.resetLabel': '恢复出厂偏好',
|
||||
'settings.oth.resetDesc': '将常规、结构与其他分页中的所有偏好设置还原为初始默认状态',
|
||||
'settings.oth.resetAllBtn': '恢复全部默认设置',
|
||||
'settings.oth.resetConfirmBtn': '再次点击确认重置',
|
||||
'settings.oth.resettingBtn': '重置中…',
|
||||
'settings.oth.resetAllDone': '已恢复全部默认设置',
|
||||
});
|
||||
@@ -6,17 +6,33 @@
|
||||
|
||||
import { App } from './App.js';
|
||||
import { mountWindowOverlay } from './components/layout/WindowOverlayShell.js';
|
||||
import { applyAppearanceToRoot } from './core/appearance.js';
|
||||
import { isWindowOverlayMode } from './core/httpClient.js';
|
||||
import { startAsyncTelemetryLoop } from './store/telemetryStore.js';
|
||||
import { setI18nLanguage } from './i18n/index.js';
|
||||
import { startAsyncTelemetryLoop, telemetryStore } from './store/telemetryStore.js';
|
||||
|
||||
async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
||||
if (!mountTarget) return null;
|
||||
const appInstance = App();
|
||||
mountTarget.appendChild(appInstance.el);
|
||||
|
||||
const unsubAppearance = telemetryStore.subscribe(
|
||||
(st) => st.telemetry?.settings,
|
||||
(settings) => {
|
||||
setI18nLanguage(settings?.language);
|
||||
if (typeof document !== 'undefined' && document.documentElement) {
|
||||
applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true });
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const stopPolling = startAsyncTelemetryLoop(2000);
|
||||
return {
|
||||
appInstance,
|
||||
stopPolling,
|
||||
stopPolling: () => {
|
||||
unsubAppearance();
|
||||
stopPolling();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,617 @@
|
||||
/**
|
||||
* @fileoverview Decoupled Metric Registry (`metricRegistry.js`).
|
||||
* Centralizes presentation & option metadata for:
|
||||
* 1. Topbar / Composer Capsule Slots (1..5 items out of 13 metrics)
|
||||
* 2. Live Overview / Hover First-Row Metric Matrix (1..4 items out of 9 metrics)
|
||||
*/
|
||||
|
||||
import {
|
||||
formatMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
resolveModelDisplayInfo,
|
||||
sampleSummary,
|
||||
speedReasonText,
|
||||
} 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',
|
||||
]);
|
||||
|
||||
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'step_cost',
|
||||
'session_cost',
|
||||
'cache_hit',
|
||||
'session_tokens',
|
||||
'context_usage',
|
||||
'quota_tightest',
|
||||
]);
|
||||
|
||||
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
||||
|
||||
export function getCapsuleMetricOptions() {
|
||||
return CAPSULE_METRIC_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: t(`capMetric.${key}`),
|
||||
}));
|
||||
}
|
||||
|
||||
export function getOverviewMetricOptions() {
|
||||
return OVERVIEW_METRIC_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: t(`ovMetric.${key}`),
|
||||
}));
|
||||
}
|
||||
|
||||
export function resolveQuotaCapsuleSummary(quotas) {
|
||||
if (!quotas) return null;
|
||||
const activePool = quotas.activePool;
|
||||
const weekly = quotas.weekly;
|
||||
const candidates = [];
|
||||
const defaultPoolName = isEnglishLocale() ? 'Active Pool' : '当前池';
|
||||
const wkTag = isEnglishLocale() ? 'Wk' : '周';
|
||||
|
||||
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
|
||||
candidates.push({
|
||||
pct: Number(activePool.remainingPct),
|
||||
label: activePool.poolLabel || activePool.family || defaultPoolName,
|
||||
windowTag: '5h',
|
||||
});
|
||||
}
|
||||
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
|
||||
candidates.push({
|
||||
pct: Number(activePool.weeklyRemainingPct),
|
||||
label: activePool.poolLabel || activePool.family || defaultPoolName,
|
||||
windowTag: wkTag,
|
||||
});
|
||||
}
|
||||
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
|
||||
candidates.push({
|
||||
pct: Number(weekly.remainingPct),
|
||||
label: weekly.poolFamily || (isEnglishLocale() ? 'Weekly' : '周限额'),
|
||||
windowTag: wkTag,
|
||||
});
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
candidates.sort((a, b) => a.pct - b.pct);
|
||||
const tightest = candidates[0];
|
||||
const rounded = Math.max(0, Math.min(100, Math.round(tightest.pct)));
|
||||
return {
|
||||
roundedPct: rounded,
|
||||
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
||||
detailText: candidates
|
||||
.map((c) => {
|
||||
const cPct = Math.max(0, Math.min(100, Math.round(c.pct)));
|
||||
return `${c.label} ${c.windowTag} ${t('capsule.quotaLeft', { pct: cPct })}`;
|
||||
})
|
||||
.join(' · '),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析指定模型池(Gemini 或 Claude & GPT)与指定时间窗口(5h 或周额度)的剩余百分比摘要。
|
||||
*
|
||||
* @param {object|null|undefined} quotas
|
||||
* @param {'gemini_5h'|'gemini_weekly'|'claude_5h'|'claude_weekly'} slotKey
|
||||
* @returns {{ roundedPct: number, shortText: string } | null}
|
||||
*/
|
||||
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
|
||||
if (!quotas) return null;
|
||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
||||
const activePool = quotas.activePool || null;
|
||||
const isClaude = slotKey.startsWith('claude_');
|
||||
const isWeekly = slotKey.endsWith('_weekly');
|
||||
let rawPct = null;
|
||||
|
||||
if (isClaude) {
|
||||
const claudePool =
|
||||
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
||||
pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || '')));
|
||||
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
||||
if (cand != null && Number.isFinite(Number(cand))) {
|
||||
rawPct = Number(cand);
|
||||
} else if (
|
||||
activePool &&
|
||||
THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) {
|
||||
rawPct = Number(fb);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const stdGemini =
|
||||
pools.find((p) => p?.poolKey === 'Gemini') ||
|
||||
pools.find(
|
||||
(p) =>
|
||||
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
||||
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
||||
);
|
||||
const geminiFamilyPools = pools.filter((p) =>
|
||||
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||
);
|
||||
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
||||
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
||||
rawPct = Number(primaryCand);
|
||||
} else {
|
||||
const familyVals = geminiFamilyPools
|
||||
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
||||
.filter((v) => v != null && Number.isFinite(Number(v)))
|
||||
.map(Number);
|
||||
if (familyVals.length > 0) {
|
||||
rawPct = Math.min(...familyVals);
|
||||
} else if (
|
||||
activePool &&
|
||||
!THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
||||
) {
|
||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||
if (fb != null && Number.isFinite(Number(fb))) {
|
||||
rawPct = Number(fb);
|
||||
}
|
||||
}
|
||||
if (
|
||||
rawPct == null &&
|
||||
isWeekly &&
|
||||
quotas.weekly &&
|
||||
!THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) &&
|
||||
quotas.weekly.remainingPct != null &&
|
||||
Number.isFinite(Number(quotas.weekly.remainingPct))
|
||||
) {
|
||||
rawPct = Number(quotas.weekly.remainingPct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
||||
const rounded = Math.max(0, Math.min(100, Math.round(rawPct)));
|
||||
return {
|
||||
roundedPct: rounded,
|
||||
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
||||
};
|
||||
}
|
||||
|
||||
export function formatCompactCapsuleCost(costUsd) {
|
||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
||||
const val = Math.max(0, Number(costUsd));
|
||||
if (val === 0) return '$0.00';
|
||||
if (val < 0.001) return '<$0.001';
|
||||
if (val < 1) return `$${val.toFixed(3)}`;
|
||||
if (val < 100) return `$${val.toFixed(2)}`;
|
||||
return `$${Math.round(val)}`;
|
||||
}
|
||||
|
||||
export function formatCompactCapsuleTtft(ttftSec) {
|
||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
||||
const val = Number(ttftSec);
|
||||
if (val < 1) return `${val.toFixed(2)}s`;
|
||||
if (val < 100) return `${val.toFixed(1)}s`;
|
||||
return `${Math.round(val)}s`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析顶栏/输入框精简胶囊单槽位展示结构。
|
||||
*
|
||||
* @param {string} metricKey
|
||||
* @param {object} slotCtx
|
||||
* @param {number} ringCircumference
|
||||
*/
|
||||
export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) {
|
||||
if (!metricKey || metricKey === 'none') {
|
||||
return {
|
||||
hidden: true,
|
||||
metric: 'none',
|
||||
segClass: 'wm-cap-slot',
|
||||
textClass: 'wm-slot-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: '',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'context') {
|
||||
if (!slotCtx.hasTelemetry) {
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'context',
|
||||
segClass: 'wm-cap-slot wm-ctx-seg',
|
||||
textClass: 'wm-slot-text wm-ctx-pct',
|
||||
showRing: true,
|
||||
dashOffset: ringCircumference,
|
||||
text: '--%',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
const isDanger = slotCtx.usedPct >= 88;
|
||||
const isWarn = !isDanger && slotCtx.usedPct >= 70;
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'context',
|
||||
segClass: 'wm-cap-slot wm-ctx-seg',
|
||||
textClass: 'wm-slot-text wm-ctx-pct',
|
||||
showRing: true,
|
||||
dashOffset: slotCtx.dashOffset,
|
||||
text: `${Math.round(slotCtx.usedPct)}%`,
|
||||
running: false,
|
||||
warn: isWarn,
|
||||
danger: isDanger,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'tps') {
|
||||
if (!slotCtx.hasTelemetry) {
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'tps',
|
||||
segClass: 'wm-cap-slot wm-seg-speed',
|
||||
textClass: 'wm-slot-text wm-speed-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: '-- t/s',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
const hasValidTps = Number.isFinite(slotCtx.tps) && slotCtx.tps > 0;
|
||||
const tpsText = hasValidTps
|
||||
? `${slotCtx.tps >= 100 ? Math.round(slotCtx.tps) : slotCtx.tps.toFixed(1)} t/s`
|
||||
: slotCtx.isRunning
|
||||
? t('capsule.tpsRunning')
|
||||
: t('capsule.tpsIdle');
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'tps',
|
||||
segClass: 'wm-cap-slot wm-seg-speed',
|
||||
textClass: 'wm-slot-text wm-speed-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: tpsText,
|
||||
running: Boolean(slotCtx.isRunning),
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'avg_tps') {
|
||||
const avgVal = slotCtx.hasTelemetry ? slotCtx.avgTps : null;
|
||||
const valid = Number.isFinite(avgVal) && avgVal > 0;
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'avg_tps',
|
||||
segClass: 'wm-cap-slot wm-seg-speed',
|
||||
textClass: 'wm-slot-text wm-speed-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? `${avgVal >= 100 ? Math.round(avgVal) : avgVal.toFixed(1)} t/s` : '-- t/s',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'ttft') {
|
||||
const val = slotCtx.hasTelemetry ? slotCtx.ttft : null;
|
||||
const valid = val != null && Number.isFinite(Number(val)) && Number(val) >= 0;
|
||||
const numVal = valid ? Number(val) : 0;
|
||||
const isDanger = valid && numVal >= 30;
|
||||
const isWarn = valid && !isDanger && numVal >= 15;
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'ttft',
|
||||
segClass: 'wm-cap-slot wm-seg-ttft',
|
||||
textClass: 'wm-slot-text wm-ttft-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? formatCompactCapsuleTtft(numVal) : '--s',
|
||||
running: false,
|
||||
warn: isWarn,
|
||||
danger: isDanger,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'cost' || metricKey === 'session_cost') {
|
||||
const costVal = !slotCtx.hasTelemetry
|
||||
? null
|
||||
: metricKey === 'session_cost'
|
||||
? slotCtx.sessionCost
|
||||
: slotCtx.stepCost;
|
||||
return {
|
||||
hidden: false,
|
||||
metric: metricKey,
|
||||
segClass: 'wm-cap-slot wm-seg-cost',
|
||||
textClass: 'wm-slot-text wm-cost-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: slotCtx.hasTelemetry ? formatCompactCapsuleCost(costVal) : '--',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'cache_hit') {
|
||||
const cachePct = slotCtx.hasTelemetry ? slotCtx.cacheHitPct : null;
|
||||
const valid = cachePct != null && Number.isFinite(Number(cachePct));
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'cache_hit',
|
||||
segClass: 'wm-cap-slot wm-seg-cache',
|
||||
textClass: 'wm-slot-text wm-cache-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? `${Math.round(Number(cachePct))}%` : '--%',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'session_tokens') {
|
||||
const tokVal = slotCtx.hasTelemetry ? slotCtx.sessionTokens : null;
|
||||
const valid = tokVal != null && Number.isFinite(Number(tokVal)) && Number(tokVal) >= 0;
|
||||
return {
|
||||
hidden: false,
|
||||
metric: 'session_tokens',
|
||||
segClass: 'wm-cap-slot wm-seg-tokens',
|
||||
textClass: 'wm-slot-text wm-tokens-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: valid ? formatTokens(Number(tokVal)) : '--',
|
||||
running: false,
|
||||
warn: false,
|
||||
danger: false,
|
||||
};
|
||||
}
|
||||
|
||||
const quotaSum = !slotCtx.hasTelemetry
|
||||
? null
|
||||
: metricKey === 'quota_auto'
|
||||
? resolveQuotaCapsuleSummary(slotCtx.quotas)
|
||||
: resolveSpecificQuotaSlotSummary(slotCtx.quotas, metricKey);
|
||||
const isDanger = Boolean(quotaSum && quotaSum.roundedPct <= 15);
|
||||
const isWarn = Boolean(quotaSum && !isDanger && quotaSum.roundedPct <= 30);
|
||||
return {
|
||||
hidden: false,
|
||||
metric: metricKey,
|
||||
segClass: 'wm-cap-slot wm-seg-quota',
|
||||
textClass: 'wm-slot-text wm-quota-text',
|
||||
showRing: false,
|
||||
dashOffset: ringCircumference,
|
||||
text: quotaSum ? quotaSum.shortText : t('capsule.quotaUnknown'),
|
||||
running: false,
|
||||
warn: isWarn,
|
||||
danger: isDanger,
|
||||
};
|
||||
}
|
||||
|
||||
function translateRawAgentBadge(rawBadge) {
|
||||
if (!rawBadge) return '';
|
||||
if (!isEnglishLocale()) return String(rawBadge);
|
||||
const str = String(rawBadge).trim();
|
||||
if (str === '主') return t('fmt.mainBadge');
|
||||
const m = str.match(/^子(\d+)$/);
|
||||
if (m) return t('fmt.subBadge', { index: m[1] });
|
||||
if (str === '子') return t('fmt.subBadgeShort');
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析实时监控第一行矩阵单个单元格的展示数据。
|
||||
*
|
||||
* @param {string} metricKey
|
||||
* @param {{ active?: object, ctx?: object, quotas?: object, settings?: object, hasSubagents?: boolean }} cellCtx
|
||||
*/
|
||||
export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
|
||||
const active = cellCtx.active || {};
|
||||
const ctx = cellCtx.ctx || active.context || {};
|
||||
const quotas = cellCtx.quotas || {};
|
||||
const settings = cellCtx.settings || {};
|
||||
const hasSubagents = Boolean(cellCtx.hasSubagents);
|
||||
const hasAnySteps = Number(active.stepCount || 0) > 0;
|
||||
|
||||
if (metricKey === 'tps') {
|
||||
const activeModelDisplay = resolveModelDisplayInfo(active, settings, {
|
||||
fallback: t('fmt.unknownModel'),
|
||||
}).text;
|
||||
const reason = speedReasonText(active.latestSpeedReason);
|
||||
const badgeStr = translateRawAgentBadge(active.activeAgentBadge);
|
||||
const modelAndAgent =
|
||||
hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay;
|
||||
return {
|
||||
key: 'tps',
|
||||
label: t('ovMetric.tps'),
|
||||
icon: 'dot',
|
||||
iconSize: 10,
|
||||
isPulsing: Boolean(active.isRunning),
|
||||
valueText: formatMetric(active.latestTokPerSec, ' tok/s'),
|
||||
valueClass: 'cell-value accent-speed',
|
||||
subText: reason ? `${modelAndAgent} · ${reason}` : modelAndAgent,
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'ttft') {
|
||||
return {
|
||||
key: 'ttft',
|
||||
label: t('ovMetric.ttft'),
|
||||
icon: 'clock',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: formatMetric(active.latestTtftSec, 's'),
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subAvgTtft', {
|
||||
val: formatMetric(active.ttftSummary?.avgSec, 's'),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'avg_tps') {
|
||||
return {
|
||||
key: 'avg_tps',
|
||||
label: t('ovMetric.avg_tps'),
|
||||
icon: 'pulse',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: formatMetric(active.avgTokPerSec, ' tok/s'),
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subValidSamples', {
|
||||
samples: sampleSummary(active.speedSummary),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'step_cost') {
|
||||
const stepCost = active.latestStepCostUsd;
|
||||
return {
|
||||
key: 'step_cost',
|
||||
label: t('ovMetric.step_cost'),
|
||||
icon: 'bolt',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: !hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true }),
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subCacheAndTotal', {
|
||||
cache: active.latestCacheHitPct ?? 0,
|
||||
cost: formatUsd(active.sessionCostUsd || 0),
|
||||
}),
|
||||
subClass: 'cell-sub accent-ok',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'session_cost') {
|
||||
const sessCost = Number(active.sessionCostUsd || 0);
|
||||
const stepCnt = Number(active.stepCount || 0);
|
||||
const isAllUnpriced =
|
||||
stepCnt > 0 && Number(active.sessionUnpricedCalls || 0) >= stepCnt && !(sessCost > 0);
|
||||
return {
|
||||
key: 'session_cost',
|
||||
label: t('ovMetric.session_cost'),
|
||||
icon: 'bolt',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText:
|
||||
!hasAnySteps && active.sessionCostUsd == null
|
||||
? '—'
|
||||
: formatUsd(isAllUnpriced ? null : sessCost, {
|
||||
precise: sessCost > 0 && sessCost < 0.1,
|
||||
}),
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subStepsAndCache', {
|
||||
steps: stepCnt,
|
||||
cache: Math.round(Number(active.sessionCacheHitPct ?? active.latestCacheHitPct ?? 0)),
|
||||
}),
|
||||
subClass: 'cell-sub accent-ok',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'cache_hit') {
|
||||
const avgCache = Number(active.sessionCacheHitPct ?? active.latestCacheHitPct ?? 0);
|
||||
const latestCache = Number(active.latestCacheHitPct ?? 0);
|
||||
return {
|
||||
key: 'cache_hit',
|
||||
label: t('ovMetric.cache_hit'),
|
||||
icon: 'layers',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: !hasAnySteps ? '—' : `${Math.round(avgCache)}%`,
|
||||
valueClass: 'cell-value accent-ok',
|
||||
subText: t('ovMetric.subPromptHit', {
|
||||
latest: Math.round(latestCache),
|
||||
avg: Math.round(avgCache),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'session_tokens') {
|
||||
const inTok = Math.max(0, Number(active.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(active.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(active.outputTokens || 0));
|
||||
const totalTok = Math.max(0, Number(active.totalTokens ?? inTok + cacheTok + outTok));
|
||||
return {
|
||||
key: 'session_tokens',
|
||||
label: t('ovMetric.session_tokens'),
|
||||
icon: 'chart-bar',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: !hasAnySteps && !totalTok ? '—' : formatTokens(totalTok),
|
||||
valueClass: 'cell-value',
|
||||
subText: t('ovMetric.subInOutTokens', {
|
||||
inTok: formatTokens(inTok + cacheTok),
|
||||
outTok: formatTokens(outTok),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
if (metricKey === 'context_usage') {
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||
const toneCls =
|
||||
usedPct >= 88
|
||||
? 'cell-value tone-danger'
|
||||
: usedPct >= 70
|
||||
? 'cell-value tone-warn'
|
||||
: 'cell-value';
|
||||
return {
|
||||
key: 'context_usage',
|
||||
label: t('ovMetric.context_usage'),
|
||||
icon: 'layers',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: `${usedPct}%`,
|
||||
valueClass: toneCls,
|
||||
subText: t('ovMetric.subCtxRatio', {
|
||||
used: formatTokens(totalTokens),
|
||||
limit: formatTokens(limitTokens),
|
||||
}),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
|
||||
const quotaSum = resolveQuotaCapsuleSummary(quotas);
|
||||
const quotaToneCls =
|
||||
quotaSum && quotaSum.roundedPct <= 15
|
||||
? 'cell-value tone-danger'
|
||||
: quotaSum && quotaSum.roundedPct <= 30
|
||||
? 'cell-value tone-warn'
|
||||
: 'cell-value';
|
||||
return {
|
||||
key: 'quota_tightest',
|
||||
label: t('ovMetric.quota_tightest'),
|
||||
icon: 'pulse',
|
||||
iconSize: 11,
|
||||
isPulsing: false,
|
||||
valueText: quotaSum ? quotaSum.shortText : '—',
|
||||
valueClass: quotaToneCls,
|
||||
subText: quotaSum
|
||||
? t('ovMetric.subQuotaPool', { label: quotaSum.detailText })
|
||||
: t('ovMetric.subQuotaPending'),
|
||||
subClass: 'cell-sub',
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* @fileoverview Decoupled Step Table Column Registry (`stepColumnRegistry.js`).
|
||||
* Defines all 12 customizable columns for `StepsDetailView` ("按步查看"),
|
||||
* preserving 100% of the 7 out-of-the-box default columns, clickable agent filter badges,
|
||||
* speed reason sub-lines, token combo tooltips, and high-cost highlights.
|
||||
*/
|
||||
|
||||
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
||||
import {
|
||||
formatMetric,
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
resolveModelDisplayInfo,
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||
import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
} from '../store/telemetryStore.js';
|
||||
|
||||
export const STEP_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'time',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'tokens_combo',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
function formatStepClockTime(createdAtMs) {
|
||||
const ms = Number(createdAtMs || 0);
|
||||
if (!(ms > 0) || !Number.isFinite(ms)) {
|
||||
return { text: '—', title: '' };
|
||||
}
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
const hhmmss = `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
const full = `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${hhmmss}`;
|
||||
return { text: hhmmss, title: full };
|
||||
}
|
||||
|
||||
export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
step: {
|
||||
key: 'step',
|
||||
thLabel: () => t('stepCol.step.th'),
|
||||
optLabel: () => t('stepCol.step.opt'),
|
||||
sigPart: (st, ctx) =>
|
||||
`${ctx.hasSubagents}:${ctx.scopeSigKey}:${st.agentId || 'main'}:${st.stepIndex}:${st.agentBadge || ''}:${st.agentLabel || ''}`,
|
||||
createCell: () => {
|
||||
const agentBadgeEl = h('span', {
|
||||
className: 'agent-badge is-clickable',
|
||||
hidden: true,
|
||||
style: 'margin-right: 4px;',
|
||||
});
|
||||
const stepNumText = h('span');
|
||||
const td = h('td', {}, [agentBadgeEl, stepNumText]);
|
||||
return { td, refs: { agentBadgeEl, stepNumText } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
const { hasSubagents, effectiveScopes, onSelectAgentScopes } = ctx;
|
||||
patchAttr(refs.agentBadgeEl, 'hidden', !hasSubagents);
|
||||
if (hasSubagents) {
|
||||
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
|
||||
patchAttr(refs.agentBadgeEl, 'class', `agent-badge is-clickable ${badgeCls}`);
|
||||
const badgeText = isEnglishLocale()
|
||||
? formatAgentBadgeText({
|
||||
isMain: !st.isSubagent,
|
||||
index: st.agentIndex || 0,
|
||||
badgeText: st.agentBadge,
|
||||
})
|
||||
: st.agentBadge || (st.isSubagent ? '子' : '主');
|
||||
patchText(refs.agentBadgeEl, badgeText);
|
||||
|
||||
const targetScope = st.agentId || 'main';
|
||||
const isSoleTarget =
|
||||
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
|
||||
const agentName = isEnglishLocale()
|
||||
? formatAgentLabel({
|
||||
isMain: !st.isSubagent,
|
||||
index: st.agentIndex || 0,
|
||||
role: st.agentRole || '',
|
||||
})
|
||||
: st.agentLabel || t('steps.unitAgent');
|
||||
patchAttr(
|
||||
refs.agentBadgeEl,
|
||||
'title',
|
||||
isSoleTarget
|
||||
? t('steps.badgeBackAll')
|
||||
: t('steps.badgeFilterAgent', { agent: agentName })
|
||||
);
|
||||
refs.agentBadgeEl.onclick = (e) => {
|
||||
if (typeof onSelectAgentScopes !== 'function') return;
|
||||
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
|
||||
const next = effectiveScopes.includes(targetScope)
|
||||
? effectiveScopes.filter((id) => id !== targetScope)
|
||||
: [...effectiveScopes, targetScope];
|
||||
onSelectAgentScopes(next.length > 0 ? next : ['all']);
|
||||
} else {
|
||||
onSelectAgentScopes(isSoleTarget ? ['all'] : [targetScope]);
|
||||
}
|
||||
};
|
||||
}
|
||||
patchText(refs.stepNumText, `#${Number(st.stepIndex)}`);
|
||||
},
|
||||
},
|
||||
|
||||
time: {
|
||||
key: 'time',
|
||||
thLabel: () => t('stepCol.time.th'),
|
||||
optLabel: () => t('stepCol.time.opt'),
|
||||
sigPart: (st) => `${st.createdAtMs || 0}`,
|
||||
createCell: () => {
|
||||
const td = h('td', { className: 'text-muted' });
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const { text, title } = formatStepClockTime(st.createdAtMs);
|
||||
patchText(refs.td, text);
|
||||
patchAttr(refs.td, 'title', title || null);
|
||||
},
|
||||
},
|
||||
|
||||
model: {
|
||||
key: 'model',
|
||||
thLabel: () => t('stepCol.model.th'),
|
||||
optLabel: () => t('stepCol.model.opt'),
|
||||
sigPart: (st, ctx) => {
|
||||
const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
return `${disp.text}:${disp.title}`;
|
||||
},
|
||||
createCell: () => {
|
||||
const td = h('td', {
|
||||
style: 'max-width: 120px; overflow: hidden; text-overflow: ellipsis;',
|
||||
});
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
patchText(refs.td, modelDisplay.text);
|
||||
patchAttr(refs.td, 'title', modelDisplay.title);
|
||||
},
|
||||
},
|
||||
|
||||
tps: {
|
||||
key: 'tps',
|
||||
thLabel: () => t('stepCol.tps.th'),
|
||||
optLabel: () => t('stepCol.tps.opt'),
|
||||
sigPart: (st) => `${st.tokPerSec}:${st.selectedSpeedReason || ''}`,
|
||||
createCell: () => {
|
||||
const speedMain = h('strong', {
|
||||
className: 'cell-value accent-speed',
|
||||
style: 'font-size: var(--fs-base-sm);',
|
||||
});
|
||||
const speedReason = h('div', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-2xs);',
|
||||
});
|
||||
const td = h('td', {}, [speedMain, speedReason]);
|
||||
return { td, refs: { speedMain, speedReason } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
const reason = speedReasonText(st.selectedSpeedReason);
|
||||
patchText(refs.speedReason, reason);
|
||||
patchAttr(refs.speedReason, 'hidden', !reason);
|
||||
},
|
||||
},
|
||||
|
||||
ttft: {
|
||||
key: 'ttft',
|
||||
thLabel: () => t('stepCol.ttft.th'),
|
||||
optLabel: () => t('stepCol.ttft.opt'),
|
||||
sigPart: (st) => `${st.ttftSec}`,
|
||||
createCell: () => {
|
||||
const td = h('td');
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.td, formatMetric(st.ttftSec, 's'));
|
||||
},
|
||||
},
|
||||
|
||||
duration: {
|
||||
key: 'duration',
|
||||
thLabel: () => t('stepCol.duration.th'),
|
||||
optLabel: () => t('stepCol.duration.opt'),
|
||||
sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`,
|
||||
createCell: () => {
|
||||
const td = h('td');
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const dur = st.totalDurationSec ?? st.streamDurationSec ?? null;
|
||||
patchText(refs.td, formatMetric(dur, 's'));
|
||||
},
|
||||
},
|
||||
|
||||
tokens_combo: {
|
||||
key: 'tokens_combo',
|
||||
thLabel: () => t('stepCol.tokens_combo.th'),
|
||||
optLabel: () => t('stepCol.tokens_combo.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`,
|
||||
createCell: () => {
|
||||
const td = h('td');
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const outTok = Math.max(0, Number(st.outputTokens || 0));
|
||||
const thinkTok = Math.max(0, Number(st.thinkingTokens || 0));
|
||||
const respTok =
|
||||
st.responseTokens != null
|
||||
? Math.max(0, Number(st.responseTokens))
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
patchText(
|
||||
refs.td,
|
||||
`${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}`
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
t('steps.ctxTitle', {
|
||||
ctx: Math.round(Number(st.contextTokens || 0)),
|
||||
think: Math.round(thinkTok),
|
||||
resp: Math.round(respTok),
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
input_tokens: {
|
||||
key: 'input_tokens',
|
||||
thLabel: () => t('stepCol.input_tokens.th'),
|
||||
optLabel: () => t('stepCol.input_tokens.opt'),
|
||||
sigPart: (st) => `${st.inputTokens || 0}`,
|
||||
createCell: () => {
|
||||
const td = h('td');
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.td, formatTokens(st.inputTokens || 0));
|
||||
},
|
||||
},
|
||||
|
||||
cache_tokens: {
|
||||
key: 'cache_tokens',
|
||||
thLabel: () => t('stepCol.cache_tokens.th'),
|
||||
optLabel: () => t('stepCol.cache_tokens.opt'),
|
||||
sigPart: (st) => `${st.cacheReadTokens || 0}`,
|
||||
createCell: () => {
|
||||
const td = h('td');
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.td, formatTokens(st.cacheReadTokens || 0));
|
||||
},
|
||||
},
|
||||
|
||||
output_tokens: {
|
||||
key: 'output_tokens',
|
||||
thLabel: () => t('stepCol.output_tokens.th'),
|
||||
optLabel: () => t('stepCol.output_tokens.opt'),
|
||||
sigPart: (st) => `${st.outputTokens || 0}`,
|
||||
createCell: () => {
|
||||
const td = h('td');
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.td, formatTokens(st.outputTokens || 0));
|
||||
},
|
||||
},
|
||||
|
||||
cache: {
|
||||
key: 'cache',
|
||||
thLabel: () => t('stepCol.cache.th'),
|
||||
optLabel: () => t('stepCol.cache.opt'),
|
||||
sigPart: (st) => `${st.cacheHitPct ?? 0}`,
|
||||
createCell: () => {
|
||||
const td = h('td', {
|
||||
className: 'cell-value accent-ok',
|
||||
style: 'font-size: var(--fs-base-sm);',
|
||||
});
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
patchText(refs.td, `${Number(st.cacheHitPct ?? 0)}%`);
|
||||
},
|
||||
},
|
||||
|
||||
cost: {
|
||||
key: 'cost',
|
||||
thLabel: () => t('stepCol.cost.th'),
|
||||
optLabel: () => t('stepCol.cost.opt'),
|
||||
sigPart: (st) => `${st.costUsd}`,
|
||||
createCell: () => {
|
||||
const td = h('td', { style: 'font-weight: 600;' });
|
||||
return { td, refs: { td } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const costVal = st.costUsd;
|
||||
patchText(refs.td, formatUsd(costVal, { precise: true }));
|
||||
patchClasses(refs.td, { 'accent-speed': costVal >= 0.15 });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export function getStepColumnOptions() {
|
||||
return STEP_COLUMN_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: STEP_COLUMN_REGISTRY[key].optLabel(),
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* @fileoverview Decoupled Overview & Hover Widget Registry (`widgetRegistry.js`).
|
||||
* Maps module keys (`metrics`, `context`, `quotas`, `live_tasks`) to standalone
|
||||
* widget components and provides `createDynamicWidgetHost` for zero-hardcode mounting,
|
||||
* live reordering, and clean instance disposal.
|
||||
*/
|
||||
|
||||
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
|
||||
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
|
||||
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
|
||||
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
export const OVERVIEW_WIDGET_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
|
||||
metrics: {
|
||||
key: 'metrics',
|
||||
labelKey: 'module.metrics',
|
||||
create: ({ mode, isVisibleFn }) => MetricMatrixWidget({ mode, isVisibleFn }),
|
||||
},
|
||||
context: {
|
||||
key: 'context',
|
||||
labelKey: 'module.context',
|
||||
create: ({ mode, isVisibleFn }) =>
|
||||
ContextWindowWidget({
|
||||
interactiveInspector: mode !== 'hover',
|
||||
isVisibleFn,
|
||||
}),
|
||||
},
|
||||
quotas: {
|
||||
key: 'quotas',
|
||||
labelKey: 'module.quotas',
|
||||
create: ({ mode }) =>
|
||||
QuotaPoolsWidget({
|
||||
compactHover: mode === 'hover',
|
||||
}),
|
||||
},
|
||||
live_tasks: {
|
||||
key: 'live_tasks',
|
||||
labelKey: 'module.live_tasks',
|
||||
create: ({ mode, isVisibleFn }) =>
|
||||
LiveActivityWidget({
|
||||
interactive: mode !== 'hover',
|
||||
isVisibleFn,
|
||||
}),
|
||||
},
|
||||
});
|
||||
|
||||
export function getOverviewModuleOptions() {
|
||||
return OVERVIEW_WIDGET_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: t(`module.${key}`),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a dynamic container host that mounts, reorders, updates, and disposes
|
||||
* standalone telemetry widgets based on user-configured module keys.
|
||||
*
|
||||
* @param {{
|
||||
* containerEl: HTMLElement,
|
||||
* mode?: 'overview' | 'hover',
|
||||
* isVisibleFn?: () => boolean,
|
||||
* initialModuleKeys?: string[]
|
||||
* }} options
|
||||
*/
|
||||
export function createDynamicWidgetHost({
|
||||
containerEl,
|
||||
mode = 'overview',
|
||||
isVisibleFn = () => true,
|
||||
initialModuleKeys = [],
|
||||
}) {
|
||||
const instances = new Map();
|
||||
let currentKeys = [];
|
||||
|
||||
function syncModules(nextKeys) {
|
||||
const validKeys = [];
|
||||
const seen = new Set();
|
||||
for (const rawKey of Array.isArray(nextKeys) ? nextKeys : []) {
|
||||
const k = String(rawKey || '').trim();
|
||||
if (!k || seen.has(k) || !OVERVIEW_WIDGET_REGISTRY[k]) continue;
|
||||
seen.add(k);
|
||||
validKeys.push(k);
|
||||
}
|
||||
|
||||
// Remove and destroy widgets no longer present
|
||||
for (const [existingKey, inst] of [...instances.entries()]) {
|
||||
if (!seen.has(existingKey)) {
|
||||
try {
|
||||
inst.el?.remove?.();
|
||||
} catch {}
|
||||
try {
|
||||
inst.destroy?.();
|
||||
} catch {}
|
||||
instances.delete(existingKey);
|
||||
}
|
||||
}
|
||||
|
||||
// Instantiate newly added widgets
|
||||
for (const key of validKeys) {
|
||||
if (!instances.has(key)) {
|
||||
const inst = OVERVIEW_WIDGET_REGISTRY[key].create({ mode, isVisibleFn });
|
||||
instances.set(key, inst);
|
||||
}
|
||||
}
|
||||
|
||||
// Reorder DOM nodes in containerEl only where needed
|
||||
const orderChanged =
|
||||
validKeys.length !== currentKeys.length ||
|
||||
validKeys.some((k, idx) => currentKeys[idx] !== k) ||
|
||||
(containerEl.children && containerEl.children.length !== validKeys.length);
|
||||
|
||||
if (orderChanged) {
|
||||
for (let i = 0; i < validKeys.length; i += 1) {
|
||||
const targetEl = instances.get(validKeys[i]).el;
|
||||
const curChild = containerEl.children ? containerEl.children[i] : null;
|
||||
if (curChild !== targetEl) {
|
||||
if (curChild && typeof containerEl.insertBefore === 'function') {
|
||||
containerEl.insertBefore(targetEl, curChild);
|
||||
} else {
|
||||
containerEl.appendChild(targetEl);
|
||||
}
|
||||
}
|
||||
}
|
||||
currentKeys = [...validKeys];
|
||||
}
|
||||
|
||||
return validKeys;
|
||||
}
|
||||
|
||||
function update({ moduleKeys = [], data = null, minuteTick = undefined } = {}) {
|
||||
const validKeys = syncModules(moduleKeys);
|
||||
for (const key of validKeys) {
|
||||
const inst = instances.get(key);
|
||||
inst?.refs?.update?.({ data, minuteTick });
|
||||
}
|
||||
}
|
||||
|
||||
function pauseTickers() {
|
||||
for (const inst of instances.values()) {
|
||||
inst?.refs?.pauseTicker?.();
|
||||
}
|
||||
}
|
||||
|
||||
function resumeTickers() {
|
||||
for (const inst of instances.values()) {
|
||||
inst?.refs?.resumeTicker?.();
|
||||
}
|
||||
}
|
||||
|
||||
function getInstance(key) {
|
||||
return instances.get(key) || null;
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
for (const inst of instances.values()) {
|
||||
try {
|
||||
inst.el?.remove?.();
|
||||
} catch {}
|
||||
try {
|
||||
inst.destroy?.();
|
||||
} catch {}
|
||||
}
|
||||
instances.clear();
|
||||
currentKeys = [];
|
||||
}
|
||||
|
||||
if (Array.isArray(initialModuleKeys) && initialModuleKeys.length > 0) {
|
||||
syncModules(initialModuleKeys);
|
||||
}
|
||||
|
||||
return {
|
||||
update,
|
||||
pauseTickers,
|
||||
resumeTickers,
|
||||
getInstance,
|
||||
getActiveKeys: () => [...currentKeys],
|
||||
destroy,
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js';
|
||||
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js';
|
||||
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
|
||||
|
||||
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;
|
||||
|
||||
@@ -106,33 +108,179 @@ 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',
|
||||
'none',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
|
||||
export const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([
|
||||
'metrics',
|
||||
'context',
|
||||
'quotas',
|
||||
'live_tasks',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
||||
|
||||
export const CLIENT_OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'step_cost',
|
||||
'session_cost',
|
||||
'cache_hit',
|
||||
'session_tokens',
|
||||
'context_usage',
|
||||
'quota_tightest',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_OVERVIEW_METRICS = Object.freeze([
|
||||
'tps',
|
||||
'ttft',
|
||||
'avg_tps',
|
||||
'step_cost',
|
||||
]);
|
||||
|
||||
export const CLIENT_STEP_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
'time',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_STEP_COLUMNS = Object.freeze([
|
||||
'step',
|
||||
'model',
|
||||
'tps',
|
||||
'ttft',
|
||||
'tokens_combo',
|
||||
'cache',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
function normalizeClientOrderedList(raw, { allowedKeys, defaultItems, minLen, maxLen }) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...defaultItems];
|
||||
}
|
||||
const allowedSet = new Set(allowedKeys);
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of raw) {
|
||||
const key = String(item ?? '').trim();
|
||||
if (!key || key === 'none' || !allowedSet.has(key) || seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push(key);
|
||||
if (out.length >= maxLen) break;
|
||||
}
|
||||
if (out.length < minLen) {
|
||||
for (const fallbackKey of [...defaultItems, ...allowedKeys]) {
|
||||
if (!seen.has(fallbackKey) && allowedSet.has(fallbackKey)) {
|
||||
seen.add(fallbackKey);
|
||||
out.push(fallbackKey);
|
||||
if (out.length >= minLen) break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化前端顶栏胶囊三槽位配置数组,非法项回退默认值,且禁止三项同时为 `none`。
|
||||
* 归一化前端顶栏胶囊动态槽位配置数组(支持 1..5 项不重复指标,兼容迁移旧版 `'none'` 占位)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {[string, string, string]}
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeClientTopbarSlots(raw) {
|
||||
const arr = Array.isArray(raw) ? raw : [];
|
||||
const slots = [0, 1, 2].map((idx) => {
|
||||
const val = String(arr[idx] ?? '').trim();
|
||||
return CLIENT_TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_CLIENT_TOPBAR_SLOTS[idx];
|
||||
return normalizeClientOrderedList(raw, {
|
||||
allowedKeys: CLIENT_TOPBAR_SLOT_KEYS,
|
||||
defaultItems: DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||
minLen: 1,
|
||||
maxLen: 5,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化鼠标悬浮速览窗展示模块列表(支持 0..4 项,`0` 项代表关闭悬浮窗)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeClientHoverModules(raw) {
|
||||
return normalizeClientOrderedList(raw, {
|
||||
allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS,
|
||||
defaultItems: DEFAULT_CLIENT_HOVER_MODULES,
|
||||
minLen: 0,
|
||||
maxLen: 4,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实时监控视图展示模块列表(支持 1..4 项)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeClientOverviewModules(raw) {
|
||||
return normalizeClientOrderedList(raw, {
|
||||
allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS,
|
||||
defaultItems: DEFAULT_CLIENT_OVERVIEW_MODULES,
|
||||
minLen: 1,
|
||||
maxLen: 4,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化实时监控第一行指标矩阵配置(支持 1..4 项)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeClientOverviewMetrics(raw) {
|
||||
return normalizeClientOrderedList(raw, {
|
||||
allowedKeys: CLIENT_OVERVIEW_METRIC_KEYS,
|
||||
defaultItems: DEFAULT_CLIENT_OVERVIEW_METRICS,
|
||||
minLen: 1,
|
||||
maxLen: 4,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化调用明细「按步查看」显示列配置(支持 2..12 列)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function normalizeClientStepColumns(raw) {
|
||||
return normalizeClientOrderedList(raw, {
|
||||
allowedKeys: CLIENT_STEP_COLUMN_KEYS,
|
||||
defaultItems: DEFAULT_CLIENT_STEP_COLUMNS,
|
||||
minLen: 2,
|
||||
maxLen: 12,
|
||||
});
|
||||
if (slots.every((s) => s === 'none')) {
|
||||
slots[0] = 'context';
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -173,58 +321,73 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (!prev || !next) return false;
|
||||
if (prev === next) return true;
|
||||
|
||||
// 1. 比对系统设置项(模型显示策略、Orchestrator ID 显示风格、周预算模式与额度、插件更新策略、双栖与顶栏槽位配置)
|
||||
const sameArr = (a, b) => {
|
||||
if (a === b) return true;
|
||||
if (!Array.isArray(a) || !Array.isArray(b)) return false;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
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;
|
||||
if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false;
|
||||
const prevOrchIdMode = String(prev.settings?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||
const nextOrchIdMode = String(next.settings?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||
if (prevOrchIdMode !== nextOrchIdMode) {
|
||||
return false;
|
||||
}
|
||||
if (prev.settings?.weeklyLimitMode !== next.settings?.weeklyLimitMode) return false;
|
||||
if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false;
|
||||
if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false;
|
||||
if ((prev.settings?.pluginUpdateMode ?? '') !== (next.settings?.pluginUpdateMode ?? '')) return false;
|
||||
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
||||
const rawPrevMount = String(prev.settings?.windowMountMode ?? '').trim().toLowerCase();
|
||||
const prevMountMode =
|
||||
rawPrevMount === 'composer' || rawPrevMount === 'input'
|
||||
? 'composer'
|
||||
: rawPrevMount === 'sidebar' || rawPrevMount === 'off'
|
||||
? 'sidebar'
|
||||
: rawPrevMount === 'dual' || rawPrevMount === 'topbar'
|
||||
? 'dual'
|
||||
: prev.settings?.enableWindowOverlay === false
|
||||
? 'sidebar'
|
||||
: 'dual';
|
||||
const rawNextMount = String(next.settings?.windowMountMode ?? '').trim().toLowerCase();
|
||||
const nextMountMode =
|
||||
rawNextMount === 'composer' || rawNextMount === 'input'
|
||||
? 'composer'
|
||||
: rawNextMount === 'sidebar' || rawNextMount === 'off'
|
||||
? 'sidebar'
|
||||
: rawNextMount === 'dual' || rawNextMount === 'topbar'
|
||||
? 'dual'
|
||||
: next.settings?.enableWindowOverlay === false
|
||||
? 'sidebar'
|
||||
: 'dual';
|
||||
if (prevMountMode !== nextMountMode) return false;
|
||||
if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false;
|
||||
if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) {
|
||||
return false;
|
||||
}
|
||||
const pTopSlots = prev.settings?.topbarCapsuleSlots;
|
||||
const nTopSlots = next.settings?.topbarCapsuleSlots;
|
||||
const pSet = prev.settings;
|
||||
const nSet = next.settings;
|
||||
|
||||
if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false;
|
||||
if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false;
|
||||
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
||||
if (
|
||||
(pTopSlots?.[0] ?? 'context') !== (nTopSlots?.[0] ?? 'context') ||
|
||||
(pTopSlots?.[1] ?? 'tps') !== (nTopSlots?.[1] ?? 'tps') ||
|
||||
(pTopSlots?.[2] ?? 'quota_auto') !== (nTopSlots?.[2] ?? 'quota_auto')
|
||||
JSON.stringify(pSet?.modelContextWindows) !== JSON.stringify(nSet?.modelContextWindows) ||
|
||||
JSON.stringify(prev.contextWindowModels) !== JSON.stringify(next.contextWindowModels)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false;
|
||||
const prevOrchIdMode =
|
||||
String(pSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
||||
? 'full'
|
||||
: 'compact';
|
||||
const nextOrchIdMode =
|
||||
String(nSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
||||
? 'full'
|
||||
: 'compact';
|
||||
if (prevOrchIdMode !== nextOrchIdMode) {
|
||||
return false;
|
||||
}
|
||||
if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false;
|
||||
if (pSet?.weeklyTokenBudget !== nSet?.weeklyTokenBudget) return false;
|
||||
if (pSet?.weeklyCostBudget !== nSet?.weeklyCostBudget) return false;
|
||||
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)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (pSet?.enableWindowOverlay !== nSet?.enableWindowOverlay) return false;
|
||||
if ((pSet?.showTopbarMultiSession !== false) !== (nSet?.showTopbarMultiSession !== false)) {
|
||||
return false;
|
||||
}
|
||||
if (!sameArr(pSet?.topbarCapsuleSlots, nSet?.topbarCapsuleSlots)) return false;
|
||||
if (!sameArr(pSet?.hoverModules, nSet?.hoverModules)) return false;
|
||||
if (!sameArr(pSet?.overviewModules, nSet?.overviewModules)) return false;
|
||||
if (!sameArr(pSet?.overviewMetrics, nSet?.overviewMetrics)) return false;
|
||||
if (!sameArr(pSet?.stepTableColumns, nSet?.stepTableColumns)) return false;
|
||||
|
||||
// 2. 比对云端状态(插件当前/最新版本、安装模式、价格表版本与模型数量、同步/更新执行状态及错误信息)
|
||||
// 2. 比对云端状态
|
||||
const pCloud = prev.cloudStatus;
|
||||
const nCloud = next.cloudStatus;
|
||||
if (
|
||||
@@ -245,12 +408,20 @@ function isEquivalentTelemetry(prev, next) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与费用)
|
||||
// 3. 比对活跃会话的实时测速指标
|
||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
||||
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||
if (
|
||||
pAct?.inputTokens !== nAct?.inputTokens ||
|
||||
pAct?.cacheReadTokens !== nAct?.cacheReadTokens ||
|
||||
pAct?.outputTokens !== nAct?.outputTokens ||
|
||||
pAct?.totalTokens !== nAct?.totalTokens
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature ||
|
||||
pAct?.liveActivity?.startedAtMs !== nAct?.liveActivity?.startedAtMs
|
||||
@@ -258,6 +429,14 @@ function isEquivalentTelemetry(prev, next) {
|
||||
return false;
|
||||
}
|
||||
if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false;
|
||||
if (
|
||||
pAct?.aggregated?.inputTokens !== nAct?.aggregated?.inputTokens ||
|
||||
pAct?.aggregated?.cacheReadTokens !== nAct?.aggregated?.cacheReadTokens ||
|
||||
pAct?.aggregated?.outputTokens !== nAct?.aggregated?.outputTokens ||
|
||||
pAct?.aggregated?.totalTokens !== nAct?.aggregated?.totalTokens
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature ||
|
||||
pAct?.aggregated?.liveActivity?.startedAtMs !== nAct?.aggregated?.liveActivity?.startedAtMs
|
||||
@@ -349,6 +528,9 @@ function isEquivalentTelemetry(prev, next) {
|
||||
const as = naSteps[j];
|
||||
if (
|
||||
bs?.stepIndex !== as?.stepIndex ||
|
||||
bs?.createdAtMs !== as?.createdAtMs ||
|
||||
bs?.totalDurationSec !== as?.totalDurationSec ||
|
||||
bs?.streamDurationSec !== as?.streamDurationSec ||
|
||||
bs?.modelKey !== as?.modelKey ||
|
||||
bs?.modelShort !== as?.modelShort ||
|
||||
bs?.modelLabel !== as?.modelLabel ||
|
||||
@@ -393,6 +575,9 @@ function isEquivalentTelemetry(prev, next) {
|
||||
for (let i = 0; i < (pAct?.recentSteps?.length || 0); i++) {
|
||||
const before = pAct.recentSteps[i], after = nAct.recentSteps[i];
|
||||
if (
|
||||
before.createdAtMs !== after.createdAtMs ||
|
||||
before.totalDurationSec !== after.totalDurationSec ||
|
||||
before.streamDurationSec !== after.streamDurationSec ||
|
||||
before.modelKey !== after.modelKey ||
|
||||
before.modelShort !== after.modelShort ||
|
||||
before.modelLabel !== after.modelLabel ||
|
||||
@@ -502,7 +687,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 比对账号订阅档位与动态多配额池(活跃池、周汇总及各配额池的 5h/周限额进度与重置时间)
|
||||
// 8. 比对账号订阅档位与动态多配额池
|
||||
if (
|
||||
prev.account?.tierName !== next.account?.tierName ||
|
||||
prev.account?.planName !== next.account?.planName ||
|
||||
@@ -725,6 +910,15 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
|
||||
export async function saveSettingsPatch(patch) {
|
||||
const safePatch = patch && typeof patch === 'object' ? { ...patch } : {};
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'language')) {
|
||||
safePatch.language = normalizeI18nLanguage(safePatch.language);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'themeAccent')) {
|
||||
safePatch.themeAccent = normalizeClientThemeAccent(safePatch.themeAccent);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'fontScale')) {
|
||||
safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||
const mode = safePatch.weeklyLimitMode;
|
||||
safePatch.weeklyLimitMode =
|
||||
@@ -736,6 +930,18 @@ export async function saveSettingsPatch(patch) {
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
||||
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'hoverModules')) {
|
||||
safePatch.hoverModules = normalizeClientHoverModules(safePatch.hoverModules);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'overviewModules')) {
|
||||
safePatch.overviewModules = normalizeClientOverviewModules(safePatch.overviewModules);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'overviewMetrics')) {
|
||||
safePatch.overviewMetrics = normalizeClientOverviewMetrics(safePatch.overviewMetrics);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'stepTableColumns')) {
|
||||
safePatch.stepTableColumns = normalizeClientStepColumns(safePatch.stepTableColumns);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) {
|
||||
safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode);
|
||||
}
|
||||
@@ -770,6 +976,44 @@ export async function saveSettingsPatch(patch) {
|
||||
await fetchTelemetry({ force: true });
|
||||
}
|
||||
|
||||
export async function saveModelContextWindow(modelId, option) {
|
||||
const result = await callSidecarApi('/api/context-window', {
|
||||
method: 'POST',
|
||||
body: { modelId, option },
|
||||
});
|
||||
const telemetry = telemetryStore.getState().telemetry;
|
||||
if (telemetry?.settings) {
|
||||
telemetryStore.setState({
|
||||
telemetry: {
|
||||
...telemetry,
|
||||
settings: { ...telemetry.settings, modelContextWindows: result.modelContextWindows },
|
||||
},
|
||||
});
|
||||
}
|
||||
return result.modelContextWindows;
|
||||
}
|
||||
|
||||
export async function resetAllSettings() {
|
||||
const res = await callSidecarApi('/api/settings/reset', { method: 'POST', body: {} });
|
||||
const prevTelemetry = telemetryStore.getState().telemetry;
|
||||
if (res?.settings && prevTelemetry) {
|
||||
telemetryStore.setState({
|
||||
telemetry: {
|
||||
...prevTelemetry,
|
||||
settings: { ...res.settings },
|
||||
},
|
||||
});
|
||||
}
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function rebuildTrajectoryCache() {
|
||||
const res = await callSidecarApi('/api/cache/rebuild', { method: 'POST', body: {} });
|
||||
await fetchTelemetry({ force: true });
|
||||
return res;
|
||||
}
|
||||
|
||||
export async function triggerCloudSync() {
|
||||
const res = await callSidecarApi('/api/cloud-sync', { method: 'POST', body: {} });
|
||||
await fetchTelemetry({ force: true });
|
||||
@@ -848,6 +1092,21 @@ export function getAgentBadgeClass(index = 0, isMain = false) {
|
||||
return `badge-sub-${slot}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。
|
||||
*
|
||||
* @param {object|null|undefined} agent
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatAgentBadgeText(agent) {
|
||||
if (!isEnglishLocale()) {
|
||||
if (!agent || agent.isMain) return agent?.badgeText || '主';
|
||||
return agent.badgeText || `子${agent.index || ''}`;
|
||||
}
|
||||
if (!agent || agent.isMain) return t('fmt.mainBadge');
|
||||
return agent.index ? t('fmt.subBadge', { index: agent.index }) : t('fmt.subBadgeShort');
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。
|
||||
*
|
||||
@@ -855,10 +1114,18 @@ export function getAgentBadgeClass(index = 0, isMain = false) {
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatAgentLabel(agent) {
|
||||
if (!agent) return '主代理';
|
||||
if (agent.isMain) return agent.shortLabel || '主代理';
|
||||
const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : '';
|
||||
return `${agent.shortLabel || '子代理'}${rolePart}`;
|
||||
if (!isEnglishLocale()) {
|
||||
if (!agent) return '主代理';
|
||||
if (agent.isMain) return agent.shortLabel || '主代理';
|
||||
const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : '';
|
||||
return `${agent.shortLabel || '子代理'}${rolePart}`;
|
||||
}
|
||||
if (!agent || agent.isMain) return t('fmt.mainAgent');
|
||||
const idx = Number(agent.index || 0);
|
||||
const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent');
|
||||
const rolePart =
|
||||
agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : '';
|
||||
return `${baseLabel}${rolePart}`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
export const VIEW_TABS = Object.freeze([
|
||||
{ value: 'overview', label: '实时监控', icon: 'pulse' },
|
||||
@@ -11,9 +12,19 @@ export const VIEW_TABS = Object.freeze([
|
||||
{ value: 'settings', label: '偏好设置', icon: 'sliders' },
|
||||
]);
|
||||
|
||||
export function getViewTabs() {
|
||||
return [
|
||||
{ value: 'overview', label: t('nav.overview'), icon: 'pulse' },
|
||||
{ value: 'consumption', label: t('nav.consumption'), icon: 'chart-bar' },
|
||||
{ value: 'steps', label: t('nav.steps'), icon: 'table' },
|
||||
{ value: 'settings', label: t('nav.settings'), icon: 'sliders' },
|
||||
];
|
||||
}
|
||||
|
||||
export const uiStore = createReactiveStore({
|
||||
activeView: 'overview',
|
||||
stepsSubTab: 'steps', // 'steps' | 'models'
|
||||
settingsSubTab: 'general', // 'general' | 'structure' | 'other'
|
||||
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
|
||||
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
|
||||
});
|
||||
|
||||
@@ -30,7 +30,7 @@ body {
|
||||
background: var(--surface-bg);
|
||||
color: var(--text-primary);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
||||
font-size: 12.5px;
|
||||
font-size: var(--fs-body);
|
||||
line-height: 1.4;
|
||||
font-variant-numeric: tabular-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 2px 6px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid color-mix(in srgb, var(--metric-ok) 32%, var(--border-hairline));
|
||||
@@ -154,7 +154,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 500;
|
||||
line-height: 1;
|
||||
border-radius: var(--radius-pill);
|
||||
@@ -181,7 +181,7 @@
|
||||
|
||||
.pill-tab-badge {
|
||||
margin-left: -2px;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
@@ -229,7 +229,7 @@
|
||||
color: var(--text-primary);
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast);
|
||||
@@ -276,7 +276,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
text-align: left;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
@@ -293,6 +293,15 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.select-option.is-disabled {
|
||||
opacity: 0.42;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.select-option.is-disabled:hover {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.select-option-text {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -302,7 +311,7 @@
|
||||
}
|
||||
|
||||
.select-option-meta {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
flex-shrink: 0;
|
||||
font-family: var(--font-mono);
|
||||
}
|
||||
@@ -406,7 +415,7 @@
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
@@ -436,7 +445,7 @@
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
}
|
||||
|
||||
.dt-weekdays,
|
||||
@@ -448,7 +457,7 @@
|
||||
}
|
||||
|
||||
.dt-weekday {
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
padding: 2px 0;
|
||||
}
|
||||
@@ -458,7 +467,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -484,7 +493,7 @@
|
||||
gap: var(--space-2);
|
||||
padding-top: var(--space-2);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
}
|
||||
|
||||
.dt-time-controls {
|
||||
@@ -535,7 +544,7 @@
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
@@ -629,7 +638,7 @@
|
||||
}
|
||||
|
||||
.form-label {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
@@ -646,7 +655,7 @@
|
||||
border: 1px solid var(--accent-primary);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
cursor: pointer;
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
@@ -671,7 +680,7 @@
|
||||
border: 1px solid var(--border-strong);
|
||||
border-radius: var(--radius-xs);
|
||||
font-weight: 500;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
cursor: pointer;
|
||||
transition: background-color var(--dur-instant) var(--ease-fast), border-color var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
@@ -705,7 +714,7 @@
|
||||
gap: 4px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 600;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
@@ -745,7 +754,7 @@
|
||||
justify-content: center;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
@@ -804,7 +813,7 @@
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-secondary);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */
|
||||
:host(.wm-capsule-host) {
|
||||
--ui-font-scale: 1;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
@@ -326,6 +327,26 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 缓存命中率槽位(固定预占宽度 44px 居中对齐) */
|
||||
.wm-seg-cache {
|
||||
width: 44px;
|
||||
}
|
||||
|
||||
.wm-cache-text {
|
||||
width: 44px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 会话总 Token 槽位(固定预占宽度 52px 居中对齐) */
|
||||
.wm-seg-tokens {
|
||||
width: 52px;
|
||||
}
|
||||
|
||||
.wm-tokens-text {
|
||||
width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-warn,
|
||||
.wm-cap-slot.tone-warn .wm-slot-text {
|
||||
color: var(--metric-warn);
|
||||
@@ -423,16 +444,24 @@
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 与分隔线次序 data-sep-for-rank 动态折叠) */
|
||||
/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 1..5 与分隔线次序 data-sep-for-rank 动态折叠) */
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"] {
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="5"] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-label {
|
||||
display: none !important;
|
||||
}
|
||||
@@ -444,8 +473,12 @@
|
||||
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="4"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="5"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct,
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label {
|
||||
display: none !important;
|
||||
@@ -469,7 +502,7 @@
|
||||
pointer-events: none;
|
||||
z-index: 2147483000;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
||||
font-size: 12.5px;
|
||||
font-size: var(--fs-body);
|
||||
line-height: 1.4;
|
||||
font-variant-numeric: tabular-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
@@ -609,6 +642,13 @@
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.wm-hover-widgets {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wm-hover-update-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -618,7 +658,7 @@
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--accent-primary-soft);
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
@@ -633,7 +673,7 @@
|
||||
|
||||
.wm-hover-update-hint {
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -646,7 +686,7 @@
|
||||
}
|
||||
|
||||
.wm-hover-quota-foot {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
@@ -655,7 +695,7 @@
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 5px;
|
||||
font-size: 10px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
@@ -668,7 +708,7 @@
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
font-size: 10px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||
@@ -683,7 +723,7 @@
|
||||
}
|
||||
|
||||
.wm-task-metrics {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
@@ -720,7 +760,7 @@
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-title {
|
||||
font-size: 12.5px;
|
||||
font-size: var(--fs-body);
|
||||
}
|
||||
|
||||
.wm-multi-empty {
|
||||
@@ -730,7 +770,7 @@
|
||||
gap: var(--space-3);
|
||||
min-height: 36px;
|
||||
padding: 12px 2px 4px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
|
||||
@@ -42,16 +42,30 @@
|
||||
);
|
||||
--border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%);
|
||||
|
||||
/* Typography Hierarchy */
|
||||
/* Typography Hierarchy & Scalable Font Tokens */
|
||||
--ui-font-scale: 1;
|
||||
--fs-2xs: calc(9.5px * var(--ui-font-scale, 1));
|
||||
--fs-xs: calc(10px * var(--ui-font-scale, 1));
|
||||
--fs-sm: calc(10.5px * var(--ui-font-scale, 1));
|
||||
--fs-md: calc(11px * var(--ui-font-scale, 1));
|
||||
--fs-base-sm: calc(11.5px * var(--ui-font-scale, 1));
|
||||
--fs-base: calc(12px * var(--ui-font-scale, 1));
|
||||
--fs-body: calc(12.5px * var(--ui-font-scale, 1));
|
||||
--fs-lg: calc(14.5px * var(--ui-font-scale, 1));
|
||||
--fs-hero: calc(17px * var(--ui-font-scale, 1));
|
||||
|
||||
--text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%))));
|
||||
--text-secondary: var(--muted-foreground, var(--vscode-descriptionForeground, hsl(215 12% 44%)));
|
||||
--text-muted: color-mix(in srgb, var(--text-secondary) 74%, var(--surface-panel) 26%);
|
||||
--text-inverse: var(--surface-panel);
|
||||
--text-inverse: var(--user-accent-contrast, var(--surface-panel));
|
||||
|
||||
/* Semantic Telemetry Accents */
|
||||
--accent-primary: var(
|
||||
--primary,
|
||||
var(--vscode-textLink-foreground, var(--vscode-button-background, hsl(217 82% 51%)))
|
||||
--user-accent-primary,
|
||||
var(
|
||||
--primary,
|
||||
var(--vscode-textLink-foreground, var(--vscode-button-background, hsl(217 82% 51%)))
|
||||
)
|
||||
);
|
||||
--accent-primary-soft: color-mix(in srgb, var(--accent-primary) 13%, transparent);
|
||||
--accent-primary-border: color-mix(in srgb, var(--accent-primary) 38%, var(--border-hairline));
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
}
|
||||
|
||||
.cons-badge {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
@@ -98,21 +98,21 @@
|
||||
}
|
||||
|
||||
.cons-hero-num {
|
||||
font-size: 17px;
|
||||
font-size: var(--fs-hero);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-hero-cost {
|
||||
font-size: 17px;
|
||||
font-size: var(--fs-hero);
|
||||
font-weight: 700;
|
||||
color: var(--accent-primary);
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-hero-cache {
|
||||
font-size: 17px;
|
||||
font-size: var(--fs-hero);
|
||||
font-weight: 700;
|
||||
color: var(--ctx-cached);
|
||||
letter-spacing: -0.02em;
|
||||
@@ -132,7 +132,7 @@
|
||||
}
|
||||
|
||||
.cons-sub-label {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -140,7 +140,7 @@
|
||||
}
|
||||
|
||||
.cons-mid-num {
|
||||
font-size: 14.5px;
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
color: var(--text-primary);
|
||||
@@ -168,7 +168,7 @@
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 20px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
@@ -187,7 +187,7 @@
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
padding: 0 6px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--metric-ok);
|
||||
background: color-mix(in srgb, var(--metric-ok) 11%, transparent);
|
||||
@@ -201,7 +201,7 @@
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
@@ -211,7 +211,7 @@
|
||||
align-items: center;
|
||||
height: 20px;
|
||||
line-height: 1;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
@@ -611,7 +611,7 @@
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 10px;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
@@ -712,6 +712,6 @@
|
||||
justify-content: center;
|
||||
gap: var(--space-4);
|
||||
padding-top: var(--space-2);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
flex: 1;
|
||||
@@ -47,7 +47,7 @@
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
@@ -69,7 +69,7 @@
|
||||
}
|
||||
|
||||
.quota-win-title {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -79,7 +79,7 @@
|
||||
.quota-win-usage {
|
||||
font-family: var(--font-mono);
|
||||
font-variant-numeric: tabular-nums;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 400;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
@@ -89,7 +89,7 @@
|
||||
}
|
||||
|
||||
.quota-win-meta {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -130,7 +130,7 @@
|
||||
}
|
||||
|
||||
.live-task-title {
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
color: var(--text-primary);
|
||||
@@ -158,7 +158,7 @@
|
||||
gap: 3px;
|
||||
height: 18px;
|
||||
padding: 0 6px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-panel);
|
||||
@@ -208,7 +208,7 @@
|
||||
}
|
||||
|
||||
.live-activity-phase {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -216,7 +216,7 @@
|
||||
}
|
||||
|
||||
.live-activity-progress {
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
@@ -227,13 +227,13 @@
|
||||
}
|
||||
|
||||
.live-activity-sep {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-activity-detail {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -243,7 +243,7 @@
|
||||
}
|
||||
|
||||
.live-activity-elapsed {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
@@ -270,7 +270,7 @@
|
||||
gap: 10px;
|
||||
min-height: 22px;
|
||||
min-width: 0;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
@@ -306,7 +306,7 @@
|
||||
}
|
||||
|
||||
.live-sub-elapsed {
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
min-width: 28px;
|
||||
@@ -316,7 +316,7 @@
|
||||
|
||||
.telemetry-matrix {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(var(--matrix-cols, 4), minmax(0, 1fr));
|
||||
flex-shrink: 0;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
@@ -338,12 +338,12 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.cell-value {
|
||||
font-size: 14.5px;
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -360,7 +360,7 @@
|
||||
}
|
||||
|
||||
.cell-sub {
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -457,7 +457,7 @@
|
||||
padding: 2px 0 0 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
}
|
||||
|
||||
.legend-item {
|
||||
@@ -527,7 +527,7 @@
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
@@ -573,7 +573,7 @@
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 1px 5px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
border-radius: var(--radius-xs);
|
||||
@@ -616,8 +616,8 @@
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.telemetry-matrix {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
.telemetry-matrix:not([data-cols="1"]):not([data-cols="2"]) {
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
}
|
||||
.dual-grid {
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
/*
|
||||
* 模块化偏好设置三栏样式表 (views-settings.css).
|
||||
* 包含:
|
||||
* 1. 顶部常规 / 结构 / 其他三栏切换导航条 (.settings-view-root, .settings-subnav-bar)
|
||||
* 2. 主题强调色色卡选择器 (.theme-color-picker, .theme-host-chip, .theme-swatch-btn)
|
||||
* 3. 结构页手风琴折叠面板 (.collapsible-section, .collapsible-trigger, .collapsible-body)
|
||||
* 4. 通用 + / - / ↑ / ↓ 自添加排序列表 (.editable-slot-list, .editable-slot-row, .slot-add-btn)
|
||||
* 5. 其他页维护操作行与二次确认危险态按钮 (.settings-action-row, .btn-danger-confirm)
|
||||
*/
|
||||
|
||||
.settings-view-root {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.settings-subnav-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 3px 4px;
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.settings-subnav-bar .segmented {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.settings-subnav-bar .seg-btn {
|
||||
height: 24px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.settings-tab-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding-bottom: 2px;
|
||||
}
|
||||
|
||||
.settings-hint-text {
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.4;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
/* --- 主题色色卡选择器 (ThemeColorPicker) --- */
|
||||
.theme-color-picker {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.theme-host-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
height: 24px;
|
||||
padding: 0 9px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-pill);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.theme-host-chip:hover {
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.theme-host-chip.is-active {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.theme-swatch-group {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.theme-swatch-btn {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
padding: 0;
|
||||
border-radius: var(--radius-pill);
|
||||
border: 1.5px solid color-mix(in srgb, var(--text-primary) 18%, transparent);
|
||||
background: var(--swatch-color, var(--accent-primary));
|
||||
color: #ffffff;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
transform var(--dur-instant) var(--ease-fast),
|
||||
box-shadow var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.theme-swatch-btn:hover {
|
||||
transform: scale(1.08);
|
||||
}
|
||||
|
||||
.theme-swatch-btn.is-active {
|
||||
border-color: var(--text-primary);
|
||||
box-shadow: 0 0 0 2px color-mix(in srgb, var(--swatch-color, var(--accent-primary)) 32%, transparent);
|
||||
}
|
||||
|
||||
.theme-swatch-btn .svg-icon {
|
||||
stroke-width: 2.5;
|
||||
}
|
||||
|
||||
/* --- 手风琴折叠面板 (CollapsibleSection) --- */
|
||||
.collapsible-section {
|
||||
gap: 0;
|
||||
padding: 0;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
.collapsible-header-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
min-height: 36px;
|
||||
}
|
||||
|
||||
.collapsible-trigger {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.collapsible-trigger:hover {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.collapsible-chevron {
|
||||
color: var(--text-secondary);
|
||||
transition: transform var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.collapsible-section.is-expanded .collapsible-chevron {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.collapsible-title-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.collapsible-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.collapsible-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 18px;
|
||||
padding: 0 6px;
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.collapsible-status {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.collapsible-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-4) var(--space-4);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-divider {
|
||||
height: 1px;
|
||||
width: 100%;
|
||||
background: var(--border-hairline);
|
||||
margin: 2px 0;
|
||||
}
|
||||
|
||||
/* --- 通用可增删排序槽位列表 (EditableSlotList) --- */
|
||||
.editable-slot-wrap {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.editable-slot-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.editable-slot-empty {
|
||||
padding: 8px 10px;
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
background: var(--surface-subtle);
|
||||
border: 1px dashed var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.editable-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: var(--surface-panel);
|
||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.editable-slot-row:focus-within,
|
||||
.editable-slot-row:has(.is-open) {
|
||||
z-index: 35;
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.editable-slot-row .select-menu {
|
||||
max-height: 216px;
|
||||
}
|
||||
|
||||
.slot-remove-btn {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.slot-remove-btn:hover:not(:disabled) {
|
||||
color: var(--metric-danger);
|
||||
background: color-mix(in srgb, var(--metric-danger) 10%, transparent);
|
||||
}
|
||||
|
||||
.editable-slot-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
padding-top: 1px;
|
||||
}
|
||||
|
||||
.slot-add-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
height: 24px;
|
||||
padding: 0 9px;
|
||||
font-size: var(--fs-md);
|
||||
font-weight: 500;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border: 1px dashed var(--accent-primary-border);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
opacity var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.slot-add-btn:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--accent-primary) 18%, transparent);
|
||||
}
|
||||
|
||||
.slot-add-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* --- 其他页:维护操作行 --- */
|
||||
.settings-action-block {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.settings-action-block + .settings-action-block {
|
||||
padding-top: var(--space-3);
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.settings-action-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.settings-action-title {
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.settings-action-desc {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.settings-context-model .select-option-meta {
|
||||
max-width: 62%;
|
||||
text-align: right;
|
||||
white-space: normal;
|
||||
}
|
||||
|
||||
.btn-danger-confirm {
|
||||
color: var(--metric-danger) !important;
|
||||
border-color: color-mix(in srgb, var(--metric-danger) 55%, var(--border-hairline)) !important;
|
||||
background: color-mix(in srgb, var(--metric-danger) 11%, var(--surface-panel)) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
@@ -27,11 +27,15 @@
|
||||
background: var(--surface-panel);
|
||||
}
|
||||
|
||||
.table-viewport.is-step-table {
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
/* --- 2. 粘性表头数据表 (Sticky-Header Data Table) --- */
|
||||
.data-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.data-table th,
|
||||
@@ -42,6 +46,11 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.data-table th.is-right,
|
||||
.data-table td.is-right {
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.data-table th:first-child,
|
||||
.data-table td:first-child {
|
||||
padding-left: 2px;
|
||||
@@ -102,7 +111,7 @@
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
@@ -143,7 +152,7 @@
|
||||
}
|
||||
|
||||
.sstep-card-title {
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
@@ -151,7 +160,7 @@
|
||||
|
||||
.sstep-card .seg-btn {
|
||||
padding: 2px 6px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
}
|
||||
|
||||
.sstep-fit-controls {
|
||||
@@ -174,7 +183,7 @@
|
||||
gap: 4px;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
@@ -465,7 +474,7 @@
|
||||
.smodel-empty {
|
||||
padding: var(--space-5) var(--space-3);
|
||||
text-align: center;
|
||||
font-size: 11px;
|
||||
font-size: var(--fs-md);
|
||||
border: 1px dashed var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
}
|
||||
@@ -516,7 +525,7 @@
|
||||
}
|
||||
|
||||
.smodel-name {
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
overflow: hidden;
|
||||
@@ -526,7 +535,7 @@
|
||||
|
||||
.smodel-calls-pill {
|
||||
flex-shrink: 0;
|
||||
font-size: 10px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 500;
|
||||
padding: 1px 5px;
|
||||
color: var(--text-secondary);
|
||||
@@ -542,13 +551,13 @@
|
||||
}
|
||||
|
||||
.smodel-tok {
|
||||
font-size: 11.5px;
|
||||
font-size: var(--fs-base-sm);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.smodel-cost {
|
||||
font-size: 12px;
|
||||
font-size: var(--fs-base);
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
@@ -563,7 +572,7 @@
|
||||
justify-content: space-between;
|
||||
flex-wrap: wrap;
|
||||
gap: 2px 10px;
|
||||
font-size: 10.5px;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
mergeModelsByDisplayName,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
} from '../core/formatters.js';
|
||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
@@ -39,15 +40,17 @@ import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
|
||||
/** 消耗统计顶栏支持的时间范围预设项 */
|
||||
const TIME_RANGE_OPTIONS = [
|
||||
{ value: 'today', label: '今天' },
|
||||
{ value: '24h', label: '1天' },
|
||||
{ value: '7d', label: '7天' },
|
||||
{ value: '14d', label: '14天' },
|
||||
{ value: '30d', label: '30天' },
|
||||
{ value: 'all', label: '全部' },
|
||||
{ value: 'custom', label: '自定义' },
|
||||
];
|
||||
function getConsumptionTimeRangeOptions() {
|
||||
return [
|
||||
{ value: 'today', label: t('cons.rangeToday') },
|
||||
{ value: '24h', label: t('cons.range24h') },
|
||||
{ value: '7d', label: t('cons.range7d') },
|
||||
{ value: '14d', label: t('cons.range14d') },
|
||||
{ value: '30d', label: t('cons.range30d') },
|
||||
{ value: 'all', label: t('cons.rangeAll') },
|
||||
{ value: 'custom', label: t('cons.rangeCustom') },
|
||||
];
|
||||
}
|
||||
|
||||
export const ConsumptionView = defineComponent({
|
||||
name: 'ConsumptionView',
|
||||
@@ -58,9 +61,9 @@ export const ConsumptionView = defineComponent({
|
||||
let hasUncommittedCustomDraft = false;
|
||||
|
||||
const timeFilterSwitch = SegmentedControl({
|
||||
ariaLabel: '消耗统计时间范围',
|
||||
ariaLabel: t('cons.rangeAria'),
|
||||
modelValue: telemetryStore.getState().selectedTimeRange,
|
||||
options: TIME_RANGE_OPTIONS,
|
||||
options: getConsumptionTimeRangeOptions(),
|
||||
onUpdateModelValue: (nextRange) => {
|
||||
if (nextRange === 'custom') {
|
||||
const st = telemetryStore.getState();
|
||||
@@ -95,6 +98,7 @@ export const ConsumptionView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const applyCustomBtnLabel = h('span', { text: t('cons.applyFilter') });
|
||||
const applyCustomBtn = h(
|
||||
'button',
|
||||
{
|
||||
@@ -119,9 +123,10 @@ export const ConsumptionView = defineComponent({
|
||||
fetchTelemetry({ force: true });
|
||||
},
|
||||
},
|
||||
[createSvgIcon('check', { size: 12 }), h('span', { text: '筛选' })]
|
||||
[createSvgIcon('check', { size: 12 }), applyCustomBtnLabel]
|
||||
);
|
||||
|
||||
const rangeToSpan = h('span', { className: 'text-muted', text: t('cons.rangeTo') });
|
||||
const customRangeBar = h(
|
||||
'div',
|
||||
{
|
||||
@@ -131,7 +136,7 @@ export const ConsumptionView = defineComponent({
|
||||
},
|
||||
[
|
||||
startPicker.el,
|
||||
h('span', { className: 'text-muted', text: '至' }),
|
||||
rangeToSpan,
|
||||
endPicker.el,
|
||||
applyCustomBtn,
|
||||
]
|
||||
@@ -140,31 +145,38 @@ export const ConsumptionView = defineComponent({
|
||||
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
|
||||
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
|
||||
const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.callsCount', { calls: 0 }) });
|
||||
const heroCostUsd = h('strong', { className: 'cons-hero-cost text-mono', text: '$0.00' });
|
||||
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '≈ ¥0' });
|
||||
const heroCostCny = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: '≈ ¥0' });
|
||||
|
||||
const cacheHitPctEl = h('strong', { className: 'cons-hero-cache text-mono', text: '0%' });
|
||||
const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '命中 0' });
|
||||
const cacheTokensEl = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.cacheHitTokens', { tokens: 0 }) });
|
||||
|
||||
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
|
||||
const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '未命中缓存输入' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.uncachedInput') });
|
||||
|
||||
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
|
||||
const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' });
|
||||
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.savedCost', { cost: '$0.00' }) });
|
||||
|
||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: var(--fs-base-sm);', text: '0%' });
|
||||
const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '回复 0 · 思考 0' });
|
||||
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.replyAndThink', { resp: 0, think: 0 }) });
|
||||
|
||||
const overviewSegBar = createFourSegmentBar();
|
||||
const overviewTitleSpan = h('span', { text: t('cons.overviewTitle') });
|
||||
const totalTokensLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.totalTokens') });
|
||||
const estCostLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.estCost') });
|
||||
const cacheHitRateLabel = h('span', { text: t('cons.cacheHitRate') });
|
||||
const newInputLabel = h('span', { text: t('cons.newInput') });
|
||||
const cacheReadLabel = h('span', { text: t('cons.cacheRead') });
|
||||
const outputUsageLabel = h('span', { text: t('cons.outputUsage') });
|
||||
|
||||
const overviewPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header cons-overview-head' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
h('span', { text: '用量总览' }),
|
||||
overviewTitleSpan,
|
||||
dateSpanBadge,
|
||||
]),
|
||||
timeFilterSwitch.el,
|
||||
@@ -173,17 +185,17 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-box cons-unified-matrix' }, [
|
||||
h('div', { className: 'cons-split-3' }, [
|
||||
h('div', { className: 'cons-col' }, [
|
||||
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '总 Token' }),
|
||||
totalTokensLabel,
|
||||
h('div', { className: 'cons-baseline' }, [heroTotalTokens, heroTotalCalls]),
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '预估费用' }),
|
||||
estCostLabel,
|
||||
h('div', { className: 'cons-baseline' }, [heroCostUsd, heroCostCny]),
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
h('span', { className: 'legend-left', style: 'font-size: 11px;' }, [
|
||||
h('span', { className: 'legend-left', style: 'font-size: var(--fs-md);' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存命中率' }),
|
||||
cacheHitRateLabel,
|
||||
]),
|
||||
h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]),
|
||||
]),
|
||||
@@ -193,7 +205,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { text: '新输入' }),
|
||||
newInputLabel,
|
||||
]),
|
||||
inputSharePct,
|
||||
]),
|
||||
@@ -204,7 +216,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存读取' }),
|
||||
cacheReadLabel,
|
||||
]),
|
||||
cacheSharePct,
|
||||
]),
|
||||
@@ -215,7 +227,7 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { text: '输出用量' }),
|
||||
outputUsageLabel,
|
||||
]),
|
||||
outputSharePct,
|
||||
]),
|
||||
@@ -228,18 +240,19 @@ export const ConsumptionView = defineComponent({
|
||||
]);
|
||||
|
||||
// --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 多刻度时间轴) ---
|
||||
const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' });
|
||||
const trendTitleSpan = h('span', { text: t('cons.trendTitle') });
|
||||
const trendRangeBadge = h('span', { className: 'cons-badge', text: t('cons.allTime') });
|
||||
const trendGranularityHint = h('span', {
|
||||
className: 'text-muted text-mono',
|
||||
style: 'font-size: 10.5px;',
|
||||
text: '按小时 · 悬停查看明细',
|
||||
style: 'font-size: var(--fs-sm);',
|
||||
text: t('cons.trendPointsHintHourly', { points: 0 }),
|
||||
});
|
||||
const trendChart = createTrendAreaChart();
|
||||
|
||||
const trendPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
h('span', { text: '用量趋势' }),
|
||||
trendTitleSpan,
|
||||
trendRangeBadge,
|
||||
]),
|
||||
trendGranularityHint,
|
||||
@@ -248,24 +261,27 @@ export const ConsumptionView = defineComponent({
|
||||
]);
|
||||
|
||||
// --- Section 3: 模型排行列表 ---
|
||||
const modelsTitleSpan = h('span', { className: 'panel-title', text: t('cons.topModels') });
|
||||
const modelsListEl = h('div', { className: 'cons-item-list' });
|
||||
const modelsPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '模型排行' }),
|
||||
modelsTitleSpan,
|
||||
]),
|
||||
modelsListEl,
|
||||
]);
|
||||
|
||||
// --- Section 4: 客户端来源列表 ---
|
||||
const sourcesTitleSpan = h('span', { className: 'panel-title', text: t('cons.clientSources') });
|
||||
const sourcesListEl = h('div', { className: 'cons-item-list' });
|
||||
const sourcesPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '客户端来源' }),
|
||||
sourcesTitleSpan,
|
||||
]),
|
||||
sourcesListEl,
|
||||
]);
|
||||
|
||||
// --- Section 5: 按月细分 (12 个月垂直 4 段堆叠柱状图) ---
|
||||
const monthlyTitleSpan = h('span', { className: 'panel-title', text: t('cons.monthlyTitle') });
|
||||
const monthlyYearBadge = h('span', { className: 'cons-badge text-mono', text: '2026' });
|
||||
const monthlyCols = Array.from({ length: 12 }, (_, idx) => {
|
||||
const costText = h('span', { className: 'month-cost text-mono', text: '' });
|
||||
@@ -280,7 +296,7 @@ export const ConsumptionView = defineComponent({
|
||||
barIn,
|
||||
]);
|
||||
const zeroDot = h('span', { className: 'month-zero-dot' });
|
||||
const monthLabel = h('span', { className: 'month-label', text: `${idx + 1}月` });
|
||||
const monthLabel = h('span', { className: 'month-label', text: t('cons.monthLabel', { m: idx + 1 }) });
|
||||
const tokText = h('span', { className: 'month-tok text-mono', text: '' });
|
||||
|
||||
const colEl = h('div', { className: 'month-col' }, [
|
||||
@@ -303,9 +319,14 @@ export const ConsumptionView = defineComponent({
|
||||
};
|
||||
});
|
||||
|
||||
const legInputSpan = h('span', { text: t('cons.legInput') });
|
||||
const legCacheSpan = h('span', { text: t('cons.legCache') });
|
||||
const legOutputSpan = h('span', { text: t('cons.legOutput') });
|
||||
const legThinkingSpan = h('span', { text: t('cons.legThinking') });
|
||||
|
||||
const monthlyPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title', text: '月度统计' }),
|
||||
monthlyTitleSpan,
|
||||
monthlyYearBadge,
|
||||
]),
|
||||
h(
|
||||
@@ -316,19 +337,19 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'monthly-legend' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { text: '输入' }),
|
||||
legInputSpan,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存' }),
|
||||
legCacheSpan,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { text: '输出' }),
|
||||
legOutputSpan,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
h('span', { text: '思考' }),
|
||||
legThinkingSpan,
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
@@ -362,6 +383,12 @@ export const ConsumptionView = defineComponent({
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const segBar = createFourSegmentBar();
|
||||
|
||||
const inLbl = h('span', { text: t('cons.footInput') });
|
||||
const cacheLbl = h('span', { text: t('cons.footCache') });
|
||||
const outLbl = h('span', { text: t('cons.footOutput') });
|
||||
const thinkLbl = h('span', { text: t('cons.footThinking') });
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
|
||||
const inVal = h('strong', { className: 'text-mono' });
|
||||
const cacheVal = h('strong', { className: 'text-mono' });
|
||||
const outVal = h('strong', { className: 'text-mono' });
|
||||
@@ -381,26 +408,26 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-item-foot' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { text: '输入 ' }),
|
||||
inLbl,
|
||||
inVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存 ' }),
|
||||
cacheLbl,
|
||||
cacheVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { text: '输出 ' }),
|
||||
outLbl,
|
||||
outVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
h('span', { text: '思考 ' }),
|
||||
thinkLbl,
|
||||
thinkVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { text: '调用 ' }),
|
||||
callsLbl,
|
||||
callsVal,
|
||||
]),
|
||||
]),
|
||||
@@ -408,7 +435,23 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { nameEl, pctBadge, totalTokEl, costEl, segBar, inVal, cacheVal, outVal, thinkVal, callsVal },
|
||||
refs: {
|
||||
nameEl,
|
||||
pctBadge,
|
||||
totalTokEl,
|
||||
costEl,
|
||||
segBar,
|
||||
inLbl,
|
||||
cacheLbl,
|
||||
outLbl,
|
||||
thinkLbl,
|
||||
callsLbl,
|
||||
inVal,
|
||||
cacheVal,
|
||||
outVal,
|
||||
thinkVal,
|
||||
callsVal,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -416,6 +459,11 @@ export const ConsumptionView = defineComponent({
|
||||
* 增量更新热门模型或数据来源单行的指标文本与 4 段比例条宽度。
|
||||
*/
|
||||
function updateBreakdownItemRow(refs, item, grandTotalTokens, showTokensInHeader = true) {
|
||||
patchText(refs.inLbl, t('cons.footInput'));
|
||||
patchText(refs.cacheLbl, t('cons.footCache'));
|
||||
patchText(refs.outLbl, t('cons.footOutput'));
|
||||
patchText(refs.thinkLbl, t('cons.footThinking'));
|
||||
patchText(refs.callsLbl, t('cons.footCalls'));
|
||||
const displayLabel = item.label || item.name || item.shortName || '—';
|
||||
patchText(refs.nameEl, displayLabel);
|
||||
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
|
||||
@@ -492,12 +540,12 @@ export const ConsumptionView = defineComponent({
|
||||
const savedCostUsd = Number(acct.savedCostUsd || 0);
|
||||
|
||||
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
|
||||
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
|
||||
patchText(heroTotalCalls, t('cons.callsCount', { calls: acct.calls || 0 }));
|
||||
patchText(heroCostUsd, formatUsd(costUsd));
|
||||
patchText(heroCostCny, formatCnyApprox(costUsd));
|
||||
|
||||
patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`);
|
||||
patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`);
|
||||
patchText(cacheTokensEl, t('cons.cacheHitTokens', { tokens: formatTokensPrecise(cacheTokens) }));
|
||||
|
||||
let inPct = 0;
|
||||
let cachePct = 0;
|
||||
@@ -523,20 +571,25 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
patchText(inputSharePct, `${inPct}%`);
|
||||
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
|
||||
patchText(inputSubText, '未命中缓存输入');
|
||||
patchText(inputSubText, t('cons.uncachedInput'));
|
||||
|
||||
patchText(cacheSharePct, `${cachePct}%`);
|
||||
patchText(cacheMainTokens, formatTokensPrecise(cacheTokens));
|
||||
patchText(
|
||||
cacheSubText,
|
||||
`节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}`
|
||||
t('cons.savedCost', {
|
||||
cost: formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 }),
|
||||
})
|
||||
);
|
||||
|
||||
patchText(outputSharePct, `${outPct}%`);
|
||||
patchText(outputMainTokens, formatTokensPrecise(outputTokens));
|
||||
patchText(
|
||||
outputSubText,
|
||||
`回复 ${formatTokensPrecise(responseTokens)} · 思考 ${formatTokensPrecise(thinkingTokens)}`
|
||||
t('cons.replyAndThink', {
|
||||
resp: formatTokensPrecise(responseTokens),
|
||||
think: formatTokensPrecise(thinkingTokens),
|
||||
})
|
||||
);
|
||||
|
||||
overviewSegBar.update({
|
||||
@@ -547,7 +600,11 @@ export const ConsumptionView = defineComponent({
|
||||
});
|
||||
|
||||
// 2. 同步历史趋势交互式 SVG 面积图 / 类 GitHub 每日热力图(>90天)与粒度提示
|
||||
patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间');
|
||||
const rangeBadgeText = isEnglishLocale()
|
||||
? getConsumptionTimeRangeOptions().find((o) => o.value === slice.range)?.label ||
|
||||
t('cons.allTime')
|
||||
: preset?.label || rangeInfo.label || t('cons.allTime');
|
||||
patchText(trendRangeBadge, rangeBadgeText);
|
||||
const trendSeries = cons.trendSeries || [];
|
||||
const isHourlyTrend =
|
||||
trendSeries[0]?.granularity === 'hour' ||
|
||||
@@ -556,12 +613,15 @@ export const ConsumptionView = defineComponent({
|
||||
patchText(
|
||||
trendGranularityHint,
|
||||
isHeatmapTrend
|
||||
? `按日 (${trendSeries.length}天) · 悬停查看`
|
||||
: `${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看`
|
||||
? t('cons.trendHeatmapHint', { days: trendSeries.length })
|
||||
: isHourlyTrend
|
||||
? t('cons.trendPointsHintHourly', { points: trendSeries.length || 0 })
|
||||
: t('cons.trendPointsHintDaily', { points: trendSeries.length || 0 })
|
||||
);
|
||||
trendChart.update(trendSeries);
|
||||
|
||||
// 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账)
|
||||
const localeSig = i18nStore.getState().locale;
|
||||
const displaySettings = {
|
||||
showUpstreamModel: Boolean(slice.showUpstreamModel),
|
||||
orchestratorIdMode: slice.orchestratorIdMode,
|
||||
@@ -574,7 +634,7 @@ export const ConsumptionView = defineComponent({
|
||||
patchKeyedList(modelsListEl, models, {
|
||||
keyFn: (m) => m.displayText || m.label || m.shortName,
|
||||
sigFn: (m) =>
|
||||
`${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||
`${localeSig}:${m.displayText}:${m.displayTitle}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||
createRow: createBreakdownItemRow,
|
||||
updateRow: (refs, m) =>
|
||||
updateBreakdownItemRow(
|
||||
@@ -590,7 +650,7 @@ export const ConsumptionView = defineComponent({
|
||||
const sourcesTotalTok = sources.reduce((s, x) => s + Number(x.totalTokens || 0), 0);
|
||||
patchKeyedList(sourcesListEl, sources, {
|
||||
keyFn: (s) => s.name,
|
||||
sigFn: (s) => `${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`,
|
||||
sigFn: (s) => `${localeSig}:${s.name}:${s.totalTokens}:${s.costUsd}:${s.unpricedCalls}:${s.calls}:${sourcesTotalTok}`,
|
||||
createRow: createBreakdownItemRow,
|
||||
updateRow: (refs, s) => updateBreakdownItemRow(refs, s, sourcesTotalTok, true),
|
||||
});
|
||||
@@ -679,9 +739,50 @@ export const ConsumptionView = defineComponent({
|
||||
}
|
||||
);
|
||||
|
||||
function syncStaticLocaleLabels() {
|
||||
timeFilterSwitch.setProps({
|
||||
ariaLabel: t('cons.rangeAria'),
|
||||
options: getConsumptionTimeRangeOptions(),
|
||||
});
|
||||
patchText(applyCustomBtnLabel, t('cons.applyFilter'));
|
||||
patchText(rangeToSpan, t('cons.rangeTo'));
|
||||
patchText(overviewTitleSpan, t('cons.overviewTitle'));
|
||||
patchText(totalTokensLabel, t('cons.totalTokens'));
|
||||
patchText(estCostLabel, t('cons.estCost'));
|
||||
patchText(cacheHitRateLabel, t('cons.cacheHitRate'));
|
||||
patchText(newInputLabel, t('cons.newInput'));
|
||||
patchText(cacheReadLabel, t('cons.cacheRead'));
|
||||
patchText(outputUsageLabel, t('cons.outputUsage'));
|
||||
patchText(trendTitleSpan, t('cons.trendTitle'));
|
||||
patchText(modelsTitleSpan, t('cons.topModels'));
|
||||
patchText(sourcesTitleSpan, t('cons.clientSources'));
|
||||
patchText(monthlyTitleSpan, t('cons.monthlyTitle'));
|
||||
for (let i = 0; i < 12; i++) {
|
||||
patchText(monthlyCols[i].monthLabel, t('cons.monthLabel', { m: i + 1 }));
|
||||
}
|
||||
patchText(legInputSpan, t('cons.legInput'));
|
||||
patchText(legCacheSpan, t('cons.legCache'));
|
||||
patchText(legOutputSpan, t('cons.legOutput'));
|
||||
patchText(legThinkingSpan, t('cons.legThinking'));
|
||||
}
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
syncStaticLocaleLabels();
|
||||
if (uiStore.getState().activeView === 'consumption' && latestSlice) {
|
||||
isDirty = false;
|
||||
renderConsumptionData(latestSlice);
|
||||
} else {
|
||||
isDirty = true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsub();
|
||||
unsubView();
|
||||
unsubI18n();
|
||||
trendChart.destroy?.();
|
||||
timeFilterSwitch.destroy();
|
||||
startPicker.destroy();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,695 +1,169 @@
|
||||
/**
|
||||
* @fileoverview View 4: SettingsView (系统设置视图).
|
||||
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
|
||||
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)、模型名称格式(精简代号 / 原始模型 ID)与 Orchestrator 系列 ID 格式;
|
||||
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
|
||||
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||
* @fileoverview View 4: Modular 3-Tab `SettingsView.js` ("常规" / "结构" / "其他").
|
||||
* Orchestrates `SettingsGeneralTab`, `SettingsStructureTab`, and `SettingsOtherTab`
|
||||
* with top sub-navigation and a shared `CustomScrollbar` viewport.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import {
|
||||
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||
normalizeClientOrchestratorIdMode,
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientUpdateMode,
|
||||
normalizeClientWindowMountMode,
|
||||
saveSettingsPatch,
|
||||
telemetryStore,
|
||||
triggerCloudSync,
|
||||
triggerPluginUpdate,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { h, patchAttr } from '../core/domPatch.js';
|
||||
import { i18nStore, t } from '../i18n/index.js';
|
||||
import { telemetryStore } from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
||||
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
||||
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
||||
|
||||
/** 步骤明细表中的模型名称显示方式可选项 */
|
||||
const STEP_MODEL_DISPLAY_OPTIONS = [
|
||||
{ value: 'short', label: '精简代号 (如 argon-4-high)' },
|
||||
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
||||
];
|
||||
|
||||
/** Orchestrator 系列模型 ID 显示方式可选项(独立于普通模型名称格式) */
|
||||
const ORCHESTRATOR_ID_DISPLAY_OPTIONS = [
|
||||
{ value: 'compact', label: '精简代号 (如 orchestrator-argon)' },
|
||||
{ value: 'full', label: '原始完整 ID (如 gemini-pro-orchestrator)' },
|
||||
];
|
||||
|
||||
/** 面板挂载模式可选项(顶部栏 + 侧边栏 / 输入框 + 侧边栏 / 仅侧边栏) */
|
||||
const WINDOW_MOUNT_OPTIONS = [
|
||||
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
|
||||
{ value: 'composer', label: '输入框挂载 (输入框 + 侧边栏)' },
|
||||
{ value: 'sidebar', label: '仅侧边栏' },
|
||||
];
|
||||
|
||||
/** 顶栏左侧实时运行会话入口显隐选项 */
|
||||
const TOPBAR_MULTI_TOGGLE_OPTIONS = [
|
||||
{ value: 'show', label: '显示' },
|
||||
{ value: 'hide', label: '隐藏' },
|
||||
];
|
||||
|
||||
/** 顶栏右侧精简胶囊三槽位可选指标项 */
|
||||
const TOPBAR_SLOT_OPTIONS = [
|
||||
{ value: 'context', label: '上下文占用 (%)' },
|
||||
{ value: 'tps', label: '输出速度 (TPS)' },
|
||||
{ value: 'ttft', label: '首字延迟 (TTFT)' },
|
||||
{ value: 'cost', label: '本次费用 ($)' },
|
||||
{ value: 'quota_auto', label: '自动紧俏额度' },
|
||||
{ value: 'gemini_5h', label: 'Gemini 5h 额度' },
|
||||
{ value: 'gemini_weekly', label: 'Gemini 周额度' },
|
||||
{ value: 'claude_5h', label: 'Claude 5h 额度' },
|
||||
{ value: 'claude_weekly', label: 'Claude 周额度' },
|
||||
{ value: 'none', label: '不显示' },
|
||||
];
|
||||
|
||||
/** 插件版本更新策略可选项(默认仅提示新版本、手动更新) */
|
||||
const AUTO_UPDATE_OPTIONS = [
|
||||
{ value: 'manual', label: '仅提示新版本,手动更新' },
|
||||
{ value: 'auto', label: '自动更新' },
|
||||
{ value: 'off', label: '关闭更新' },
|
||||
];
|
||||
|
||||
/**
|
||||
* 格式化云端价格目录的最近同步时间或版本日期文本。
|
||||
*/
|
||||
function formatSyncTimeText(tsMs, updatedAt) {
|
||||
if (Number(tsMs) > 0) {
|
||||
const d = new Date(Number(tsMs));
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
return `更新于 ${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
if (updatedAt) {
|
||||
return `发布于 ${String(updatedAt).slice(0, 10)}`;
|
||||
}
|
||||
return '默认价格';
|
||||
function getSettingsSubTabOptions() {
|
||||
return [
|
||||
{ value: 'general', label: t('settings.subTab.general') },
|
||||
{ value: 'structure', label: t('settings.subTab.structure') },
|
||||
{ value: 'other', label: t('settings.subTab.other') },
|
||||
];
|
||||
}
|
||||
|
||||
export const SettingsView = defineComponent({
|
||||
name: 'SettingsView',
|
||||
setup({ onCleanup }) {
|
||||
let draftShowUpstreamModel = false;
|
||||
let draftOrchestratorIdMode = 'compact';
|
||||
let draftPluginUpdateMode = 'manual';
|
||||
let draftWindowMountMode = 'dual';
|
||||
let draftEnableWindowOverlay = true;
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
let statusTimer = null;
|
||||
let topbarTimer = null;
|
||||
let cloudTimer = null;
|
||||
const initialSubTab = uiStore.getState().settingsSubTab || 'general';
|
||||
|
||||
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
|
||||
/** 在常规设置面板右上角展示短暂的保存状态提示 */
|
||||
function showSaveFeedback(text) {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
statusTimer = null;
|
||||
}
|
||||
patchText(saveStatusText, text);
|
||||
if (text === '已保存' || text === '保存失败') {
|
||||
statusTimer = setTimeout(() => {
|
||||
statusTimer = null;
|
||||
patchText(saveStatusText, '');
|
||||
}, text === '保存失败' ? 2500 : 1500);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在顶部栏定制面板右上角展示短暂的状态提示 */
|
||||
function showTopbarFeedback(text, autoClearMs = 1500) {
|
||||
if (topbarTimer) {
|
||||
clearTimeout(topbarTimer);
|
||||
topbarTimer = null;
|
||||
}
|
||||
patchText(topbarStatusText, text);
|
||||
if (autoClearMs > 0) {
|
||||
topbarTimer = setTimeout(() => {
|
||||
topbarTimer = null;
|
||||
patchText(topbarStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在云端同步面板右上角展示同步或更新进度提示 */
|
||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||
if (cloudTimer) {
|
||||
clearTimeout(cloudTimer);
|
||||
cloudTimer = null;
|
||||
}
|
||||
patchText(cloudStatusMsg, text);
|
||||
if (autoClearMs > 0) {
|
||||
cloudTimer = setTimeout(() => {
|
||||
cloudTimer = null;
|
||||
patchText(cloudStatusMsg, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
// --- 面板 1:常规设置 ---
|
||||
const windowMountSelect = CustomSelect({
|
||||
modelValue: 'dual',
|
||||
icon: 'dock',
|
||||
options: WINDOW_MOUNT_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientWindowMountMode(val);
|
||||
const nextEnable = nextMode !== 'sidebar';
|
||||
draftWindowMountMode = nextMode;
|
||||
draftEnableWindowOverlay = nextEnable;
|
||||
windowMountSelect.setValue(nextMode);
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
windowMountMode: nextMode,
|
||||
enableWindowOverlay: nextEnable,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
const subNavSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.subTab.aria'),
|
||||
modelValue: initialSubTab,
|
||||
options: getSettingsSubTabOptions(),
|
||||
onUpdateModelValue: (nextSubTab) => {
|
||||
uiStore.setState({ settingsSubTab: nextSubTab });
|
||||
},
|
||||
});
|
||||
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
options: STEP_MODEL_DISPLAY_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextUpstream = val === 'upstream';
|
||||
draftShowUpstreamModel = nextUpstream;
|
||||
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showUpstreamModel: nextUpstream,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
},
|
||||
});
|
||||
const subNavBar = h('div', { className: 'settings-subnav-bar' }, [subNavSwitch.el]);
|
||||
|
||||
const orchestratorIdSelect = CustomSelect({
|
||||
modelValue: 'compact',
|
||||
icon: 'layers',
|
||||
options: ORCHESTRATOR_ID_DISPLAY_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientOrchestratorIdMode(val);
|
||||
draftOrchestratorIdMode = nextMode;
|
||||
orchestratorIdSelect.setValue(nextMode);
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
orchestratorIdMode: nextMode,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const generalPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
h('span', { text: '常规设置' }),
|
||||
]),
|
||||
saveStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '面板挂载方式' }),
|
||||
windowMountSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '模型名称格式' }),
|
||||
stepModelSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: 'Orchestrator 系列 ID' }),
|
||||
orchestratorIdSelect.el,
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
|
||||
const multiSessionToggle = SegmentedControl({
|
||||
ariaLabel: '实时运行会话开关',
|
||||
modelValue: 'show',
|
||||
options: TOPBAR_MULTI_TOGGLE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextShow = val !== 'hide';
|
||||
draftShowTopbarMulti = nextShow;
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showTopbarMultiSession: nextShow,
|
||||
});
|
||||
showTopbarFeedback('已保存', 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function persistTopbarSlots(nextRawSlots, noticeText = '') {
|
||||
const normalized = normalizeClientTopbarSlots(nextRawSlots);
|
||||
draftTopbarSlots = normalized;
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback(noticeText || '保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
topbarCapsuleSlots: normalized,
|
||||
});
|
||||
showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
let viewScrollbar = null;
|
||||
const refreshScroll = () => {
|
||||
if (viewScrollbar) {
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
};
|
||||
|
||||
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
|
||||
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
|
||||
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
|
||||
|
||||
function applyActiveSubTab(subTab) {
|
||||
const target =
|
||||
subTab === 'structure' || subTab === 'other' ? subTab : 'general';
|
||||
subNavSwitch.setValue(target);
|
||||
patchAttr(generalTab.el, 'hidden', target !== 'general');
|
||||
patchAttr(structureTab.el, 'hidden', target !== 'structure');
|
||||
patchAttr(otherTab.el, 'hidden', target !== 'other');
|
||||
refreshScroll();
|
||||
}
|
||||
|
||||
function handleSlotMetricChange(slotIndex, nextVal) {
|
||||
const candidate = [...draftTopbarSlots];
|
||||
candidate[slotIndex] = nextVal;
|
||||
const wouldAllBeHidden = candidate.every((item) => item === 'none');
|
||||
void persistTopbarSlots(
|
||||
candidate,
|
||||
wouldAllBeHidden ? '至少保留 1 项显示' : ''
|
||||
);
|
||||
}
|
||||
|
||||
function swapTopbarSlots(idxA, idxB) {
|
||||
if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return;
|
||||
const candidate = [...draftTopbarSlots];
|
||||
const temp = candidate[idxA];
|
||||
candidate[idxA] = candidate[idxB];
|
||||
candidate[idxB] = temp;
|
||||
void persistTopbarSlots(candidate);
|
||||
}
|
||||
|
||||
const slotSelects = [0, 1, 2].map((idx) =>
|
||||
CustomSelect({
|
||||
modelValue: draftTopbarSlots[idx],
|
||||
options: TOPBAR_SLOT_OPTIONS,
|
||||
onUpdateModelValue: (val) => handleSlotMetricChange(idx, val),
|
||||
})
|
||||
);
|
||||
|
||||
const slotRows = [0, 1, 2].map((idx) => {
|
||||
const upBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
disabled: idx === 0,
|
||||
'aria-label': `槽位 ${idx + 1} 左移`,
|
||||
title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
swapTopbarSlots(idx, idx - 1);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-up', { size: 12 })]
|
||||
);
|
||||
|
||||
const downBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
disabled: idx === 2,
|
||||
'aria-label': `槽位 ${idx + 1} 右移`,
|
||||
title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
swapTopbarSlots(idx, idx + 1);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-down', { size: 12 })]
|
||||
);
|
||||
|
||||
return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [
|
||||
h('span', { className: 'slot-index-badge', text: String(idx + 1) }),
|
||||
slotSelects[idx].el,
|
||||
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]),
|
||||
]);
|
||||
});
|
||||
|
||||
const resetTopbarBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm',
|
||||
disabled: true,
|
||||
onClick: async () => {
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
});
|
||||
showTopbarFeedback('已恢复默认', 1600);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
},
|
||||
[h('span', { text: '恢复默认' })]
|
||||
);
|
||||
|
||||
function syncTopbarControls() {
|
||||
multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide');
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
slotSelects[i].setValue(draftTopbarSlots[i]);
|
||||
}
|
||||
const isDefault =
|
||||
draftShowTopbarMulti === true &&
|
||||
draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] &&
|
||||
draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] &&
|
||||
draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2];
|
||||
patchAttr(resetTopbarBtn, 'disabled', isDefault);
|
||||
}
|
||||
|
||||
const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('dock', { size: 13 }),
|
||||
h('span', { text: '顶部栏定制' }),
|
||||
]),
|
||||
h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]),
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
h('span', { className: 'form-label', text: '实时运行会话' }),
|
||||
multiSessionToggle.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }),
|
||||
h('div', { className: 'topbar-slot-list' }, slotRows),
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- 面板 3:版本更新面板 ---
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: AUTO_UPDATE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientUpdateMode(val);
|
||||
draftPluginUpdateMode = nextMode;
|
||||
autoUpdateSelect.setValue(nextMode);
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
showCloudFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
pluginUpdateMode: nextMode,
|
||||
autoUpdatePlugin: nextMode === 'auto',
|
||||
});
|
||||
showCloudFeedback('已保存', 1800);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
showCloudFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
||||
const syncPricingBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(syncPricingBtn, 'disabled', true);
|
||||
patchText(syncPricingBtnText, '更新中…');
|
||||
showCloudFeedback('正在同步价格表…', 0);
|
||||
try {
|
||||
const res = await triggerCloudSync();
|
||||
const cs = res?.cloudStatus;
|
||||
if (res?.ok && cs) {
|
||||
showCloudFeedback(`价格表已更新 (${cs.modelCount} 个模型)`, 3500);
|
||||
} else {
|
||||
showCloudFeedback(cs?.lastSyncError || '连接超时,使用本地价格表', 4500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || '同步失败,使用本地价格表', 4500);
|
||||
} finally {
|
||||
patchAttr(syncPricingBtn, 'disabled', false);
|
||||
patchText(syncPricingBtnText, '更新价格表');
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
|
||||
);
|
||||
|
||||
const updatePluginBtnText = h('span', { text: '检查更新' });
|
||||
const updatePluginBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(updatePluginBtn, 'disabled', true);
|
||||
try {
|
||||
if (!latestCloudStatus?.updateAvailable) {
|
||||
patchText(updatePluginBtnText, '检查中…');
|
||||
showCloudFeedback('正在检查新版本…', 0);
|
||||
const syncRes = await triggerCloudSync();
|
||||
const cs = syncRes?.cloudStatus || latestCloudStatus;
|
||||
if (cs) {
|
||||
latestCloudStatus = cs;
|
||||
renderCloudStatus(cs);
|
||||
}
|
||||
if (!syncRes?.ok && cs?.lastSyncError) {
|
||||
showCloudFeedback(`检查失败:${cs.lastSyncError}`, 5000);
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.4';
|
||||
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
||||
return;
|
||||
}
|
||||
}
|
||||
patchText(updatePluginBtnText, '更新中…');
|
||||
showCloudFeedback('正在下载更新…', 0);
|
||||
const res = await triggerPluginUpdate();
|
||||
if (res?.cloudStatus) {
|
||||
latestCloudStatus = res.cloudStatus;
|
||||
}
|
||||
if (res?.ok) {
|
||||
showCloudFeedback(res.message || '更新完成,正在重启面板…', 5000);
|
||||
} else {
|
||||
showCloudFeedback(res?.message || '未执行更新', 5500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || '更新失败', 5000);
|
||||
} finally {
|
||||
patchAttr(updatePluginBtn, 'disabled', false);
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
|
||||
);
|
||||
|
||||
const cloudPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('bolt', { size: 13 }),
|
||||
h('span', { text: '版本更新' }),
|
||||
]),
|
||||
cloudStatusMsg,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '更新方式' }),
|
||||
autoUpdateSelect.el,
|
||||
]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('span', { className: 'cell-label', text: '价格表' }),
|
||||
pricingCountVal,
|
||||
pricingSyncSub,
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
h('span', { className: 'cell-label', text: '当前版本' }),
|
||||
versionVal,
|
||||
versionSub,
|
||||
]),
|
||||
]),
|
||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||
]);
|
||||
|
||||
const settingsInner = h(
|
||||
'div',
|
||||
{
|
||||
style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;',
|
||||
},
|
||||
[generalPanel, topbarPanel, cloudPanel]
|
||||
);
|
||||
const viewScrollbar = CustomScrollbar({
|
||||
contentEl: settingsInner,
|
||||
const contentContainer = h('div', {}, [generalTab.el, structureTab.el, otherTab.el]);
|
||||
viewScrollbar = CustomScrollbar({
|
||||
contentEl: contentContainer,
|
||||
className: 'view-pane',
|
||||
});
|
||||
|
||||
applyActiveSubTab(initialSubTab);
|
||||
|
||||
const rootEl = h('div', { className: 'settings-view-root' }, [
|
||||
subNavBar,
|
||||
viewScrollbar.el,
|
||||
]);
|
||||
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let latestContextWindowModels = [];
|
||||
|
||||
/** 将后端返回的最新设置同步至表单控件 */
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
|
||||
draftPluginUpdateMode = normalizeClientUpdateMode(
|
||||
settings.pluginUpdateMode,
|
||||
settings.autoUpdatePlugin
|
||||
);
|
||||
draftWindowMountMode = normalizeClientWindowMountMode(
|
||||
settings.windowMountMode,
|
||||
settings.enableWindowOverlay
|
||||
);
|
||||
draftEnableWindowOverlay = draftWindowMountMode !== 'sidebar';
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
|
||||
windowMountSelect.setValue(draftWindowMountMode);
|
||||
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
||||
orchestratorIdSelect.setValue(draftOrchestratorIdMode);
|
||||
autoUpdateSelect.setValue(draftPluginUpdateMode);
|
||||
syncTopbarControls();
|
||||
viewScrollbar.refresh();
|
||||
function syncAllTabs(settings, cloudStatus) {
|
||||
if (settings) {
|
||||
generalTab.refs.renderSettings(settings);
|
||||
structureTab.refs.renderSettings(settings);
|
||||
otherTab.refs.renderSettings(settings, latestContextWindowModels);
|
||||
}
|
||||
if (cloudStatus) {
|
||||
generalTab.refs.renderCloudStatus(cloudStatus);
|
||||
}
|
||||
refreshScroll();
|
||||
}
|
||||
|
||||
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
|
||||
function renderCloudStatus(cs) {
|
||||
if (!cs) return;
|
||||
const srcLabel =
|
||||
cs.source === 'remote'
|
||||
? '云端同步'
|
||||
: cs.source === 'local'
|
||||
? '本地文件'
|
||||
: '内置默认';
|
||||
patchText(pricingCountVal, `${cs.modelCount || 0} 个模型`);
|
||||
patchText(
|
||||
pricingSyncSub,
|
||||
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.4';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
if (cs.updateAvailable && draftPluginUpdateMode !== 'off') {
|
||||
patchText(versionSub, `可升级至 v${latVer} (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': true });
|
||||
patchText(updatePluginBtnText, `升级至 v${latVer}`);
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
|
||||
} else if (draftPluginUpdateMode === 'off') {
|
||||
patchText(versionSub, `已关闭更新提醒 (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, cs.updateAvailable ? `手动升级 v${latVer}` : '检查更新');
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
} else {
|
||||
patchText(versionSub, `已是最新 (${modeTag})`);
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, '检查更新');
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
}
|
||||
|
||||
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
|
||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||
}
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
|
||||
const unsub = telemetryStore.subscribe(
|
||||
const unsubTelemetry = telemetryStore.subscribe(
|
||||
(st) => ({
|
||||
settings: st.telemetry?.settings,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
contextWindowModels: st.telemetry?.contextWindowModels,
|
||||
}),
|
||||
(slice) => {
|
||||
latestSettings = slice.settings;
|
||||
latestCloudStatus = slice.cloudStatus;
|
||||
renderSettings(slice.settings);
|
||||
if (uiStore.getState().activeView === 'settings') {
|
||||
renderCloudStatus(slice.cloudStatus);
|
||||
latestContextWindowModels = slice.contextWindowModels || [];
|
||||
if (slice.settings) {
|
||||
generalTab.refs.renderSettings(slice.settings);
|
||||
structureTab.refs.renderSettings(slice.settings);
|
||||
otherTab.refs.renderSettings(slice.settings, latestContextWindowModels);
|
||||
}
|
||||
if (uiStore.getState().activeView === 'settings' && slice.cloudStatus) {
|
||||
generalTab.refs.renderCloudStatus(slice.cloudStatus);
|
||||
}
|
||||
refreshScroll();
|
||||
}
|
||||
);
|
||||
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
settingsSubTab: st.settingsSubTab,
|
||||
}),
|
||||
(slice) => {
|
||||
applyActiveSubTab(slice.settingsSubTab);
|
||||
if (slice.activeView === 'settings') {
|
||||
syncAllTabs(latestSettings, latestCloudStatus);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
(activeView) => {
|
||||
if (activeView === 'settings') {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
subNavSwitch.setProps({
|
||||
modelValue: uiStore.getState().settingsSubTab || 'general',
|
||||
options: getSettingsSubTabOptions(),
|
||||
});
|
||||
generalTab.refs.refreshLabels();
|
||||
structureTab.refs.refreshLabels();
|
||||
otherTab.refs.refreshLabels();
|
||||
refreshScroll();
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
if (statusTimer) clearTimeout(statusTimer);
|
||||
if (topbarTimer) clearTimeout(topbarTimer);
|
||||
if (cloudTimer) clearTimeout(cloudTimer);
|
||||
unsub();
|
||||
unsubView();
|
||||
windowMountSelect.destroy();
|
||||
stepModelSelect.destroy();
|
||||
orchestratorIdSelect.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
for (const sel of slotSelects) {
|
||||
sel.destroy();
|
||||
}
|
||||
autoUpdateSelect.destroy();
|
||||
unsubTelemetry();
|
||||
unsubUi();
|
||||
unsubI18n();
|
||||
subNavSwitch.destroy();
|
||||
generalTab.destroy();
|
||||
structureTab.destroy();
|
||||
otherTab.destroy();
|
||||
viewScrollbar.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: viewScrollbar.el,
|
||||
el: rootEl,
|
||||
refs: {
|
||||
windowMountSelect,
|
||||
stepModelSelect,
|
||||
orchestratorIdSelect,
|
||||
multiSessionToggle,
|
||||
slotSelects,
|
||||
resetTopbarBtn,
|
||||
autoUpdateSelect,
|
||||
subNavSwitch,
|
||||
generalTab,
|
||||
structureTab,
|
||||
otherTab,
|
||||
viewScrollbar,
|
||||
// Convenience aliases for external callers / tests
|
||||
windowMountSelect: structureTab.refs.windowMountSelect,
|
||||
multiSessionToggle: structureTab.refs.multiSessionToggle,
|
||||
topbarSlotsList: structureTab.refs.topbarSlotsList,
|
||||
stepModelSelect: otherTab.refs.stepModelSelect,
|
||||
orchestratorIdSelect: otherTab.refs.orchestratorIdSelect,
|
||||
autoUpdateSelect: generalTab.refs.autoUpdateSelect,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
/**
|
||||
* @fileoverview View 3: StepsDetailView (步骤明细与总汇总分析视图).
|
||||
* 提供“按步查看”与“总汇总”双子视图切换:
|
||||
* - 单步测速表采用 `patchKeyedList` 实现行级 DOM 增量对账与就地复用,支持多代理与多模型复选过滤;
|
||||
* - 总汇总视图在顶部提供当前会话线性走势图(总Token / 上下文 / TPS / 首字 / 费用)与趋势拟合曲线图(TPS / 首字 / 缓存 / 费用),
|
||||
* 单模型时自动隐藏模型下拉框,多模型时支持独立多选(趋势拟合勾选多模型时同图绘制多条独立颜色回归曲线对比);
|
||||
* - 底部以极简高密度模型卡片表达各模型总数据,全链路支持主代理 / 子代理多选汇总筛选。
|
||||
* - 单步测速表通过 `stepColumnRegistry.js` 动态渲染用户自选的 2..12 个字段列,并支持行级增量对账;
|
||||
* - 总汇总视图提供会话线性走势图、多模型同图趋势拟合曲线与极简高密度模型总览卡片。
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
@@ -22,12 +20,16 @@ import {
|
||||
mergeModelsByDisplayName,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
resolveModelDisplayInfo,
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
|
||||
import {
|
||||
DEFAULT_STEP_COLUMN_KEYS,
|
||||
STEP_COLUMN_REGISTRY,
|
||||
} from '../registries/stepColumnRegistry.js';
|
||||
import {
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
normalizeClientStepColumns,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../store/telemetryStore.js';
|
||||
@@ -44,9 +46,6 @@ import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
|
||||
/**
|
||||
* 当多选勾选了部分代理子集(>=2 个且非全选)时,动态合并所选代理的步骤列表与模型汇总。
|
||||
*/
|
||||
function mergeSelectedAgentUnits(units) {
|
||||
const combinedSteps = [];
|
||||
const modelMap = new Map();
|
||||
@@ -67,7 +66,9 @@ function mergeSelectedAgentUnits(units) {
|
||||
shortName: m.shortName || gk,
|
||||
rawModel: m.rawModel || '',
|
||||
upstreamName: m.upstreamName || m.upstreamModel || '',
|
||||
upstreamSet: new Set(Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : []),
|
||||
upstreamSet: new Set(
|
||||
Array.isArray(m.upstreamModels) ? m.upstreamModels.filter(Boolean) : []
|
||||
),
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
@@ -122,7 +123,11 @@ function mergeSelectedAgentUnits(units) {
|
||||
acc._speedWeightedSum += Number(m.avgTokPerSec) * w;
|
||||
acc._speedWeight += w;
|
||||
}
|
||||
if (m.avgTtftSec != null && Number.isFinite(Number(m.avgTtftSec)) && Number(m.avgTtftSec) >= 0) {
|
||||
if (
|
||||
m.avgTtftSec != null &&
|
||||
Number.isFinite(Number(m.avgTtftSec)) &&
|
||||
Number(m.avgTtftSec) >= 0
|
||||
) {
|
||||
const w = Math.max(1, calls || 1);
|
||||
acc._ttftWeightedSum += Number(m.avgTtftSec) * w;
|
||||
acc._ttftWeight += w;
|
||||
@@ -167,6 +172,25 @@ function mergeSelectedAgentUnits(units) {
|
||||
return { steps: combinedSteps, models: mergedModels };
|
||||
}
|
||||
|
||||
function getLineMetricSwitchOptions() {
|
||||
return [
|
||||
{ value: 'totalTokens', label: t('steps.metricTotalTokens') },
|
||||
{ value: 'context', label: t('steps.metricContext') },
|
||||
{ value: 'tps', label: t('steps.metricTps') },
|
||||
{ value: 'ttft', label: t('steps.metricTtft') },
|
||||
{ value: 'cost', label: t('steps.metricCost') },
|
||||
];
|
||||
}
|
||||
|
||||
function getFitMetricSwitchOptions() {
|
||||
return [
|
||||
{ value: 'tps', label: t('steps.metricTps') },
|
||||
{ value: 'ttft', label: t('steps.metricTtft') },
|
||||
{ value: 'cache', label: t('steps.metricCache') },
|
||||
{ value: 'cost', label: t('steps.metricCost') },
|
||||
];
|
||||
}
|
||||
|
||||
export const StepsDetailView = defineComponent({
|
||||
name: 'StepsDetailView',
|
||||
setup({ onCleanup }) {
|
||||
@@ -191,17 +215,16 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
// 明细面板标题栏内嵌代理多选筛选下拉框(单选时与顶栏代理切换条双向同步,支持多代理组合筛选)
|
||||
const inlineScopeSelect = CustomSelect({
|
||||
multiple: true,
|
||||
allValue: 'all',
|
||||
collapseAll: true,
|
||||
multiUnit: '代理',
|
||||
multiUnit: t('steps.unitAgent'),
|
||||
modelValue: selectedAgentScopes,
|
||||
icon: 'layers',
|
||||
placeholder: '全部汇总',
|
||||
placeholder: t('steps.allAgents'),
|
||||
className: 'steps-inline-scope-select',
|
||||
options: [{ value: 'all', label: '全部汇总' }],
|
||||
options: [{ value: 'all', label: t('steps.allAgents') }],
|
||||
onUpdateModelValue: (nextScopes) => {
|
||||
if (!Array.isArray(nextScopes) || nextScopes.length === 0) return;
|
||||
applyAgentScopesSelection(nextScopes);
|
||||
@@ -209,16 +232,15 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
inlineScopeSelect.el.setAttribute('hidden', '');
|
||||
|
||||
// “按步查看”标题栏内嵌模型多选筛选下拉框(仅在多模型且处于“按步查看”时展示)
|
||||
const stepsModelSelect = CustomSelect({
|
||||
multiple: true,
|
||||
allValue: '__all__',
|
||||
collapseAll: false,
|
||||
multiUnit: '模型',
|
||||
multiUnit: t('steps.unitModel'),
|
||||
modelValue: selectedTableModels,
|
||||
placeholder: '全部模型',
|
||||
placeholder: t('steps.allModels'),
|
||||
className: 'steps-inline-model-select',
|
||||
options: [{ value: '__all__', label: '全部模型' }],
|
||||
options: [{ value: '__all__', label: t('steps.allModels') }],
|
||||
onUpdateModelValue: (nextModels) => {
|
||||
if (!Array.isArray(nextModels) || nextModels.length === 0) return;
|
||||
selectedTableModels = nextModels;
|
||||
@@ -227,34 +249,42 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
stepsModelSelect.el.setAttribute('hidden', '');
|
||||
|
||||
// 顶部子表分段切换器:在“按步查看”与“总汇总”之间切换
|
||||
const subTabSwitch = SegmentedControl({
|
||||
ariaLabel: '明细表视图切换',
|
||||
ariaLabel: t('steps.title'),
|
||||
modelValue: uiStore.getState().stepsSubTab,
|
||||
options: [
|
||||
{ value: 'steps', label: '按步查看 (0)' },
|
||||
{ value: 'models', label: '总汇总' },
|
||||
{ value: 'steps', label: t('steps.tabSteps', { count: 0 }) },
|
||||
{ value: 'models', label: t('steps.tabModels') },
|
||||
],
|
||||
onUpdateModelValue: (nextTab) => {
|
||||
uiStore.setState({ stepsSubTab: nextTab });
|
||||
},
|
||||
});
|
||||
|
||||
// --- 子视图 1:单步明细表(步序、模型、吞吐速度、首字延迟、上下文/思考/正文、缓存命中率、单步费用) ---
|
||||
// --- 子视图 1:单步明细表(动态表头与行内列插槽由 `stepColumnRegistry.js` 驱动) ---
|
||||
const stepsTheadRow = h('tr');
|
||||
const stepsTbody = h('tbody');
|
||||
const stepsTablePane = h('div', { className: 'table-viewport' }, [
|
||||
|
||||
function syncTableHeaderColumns(colKeys) {
|
||||
const locale = getEffectiveLocale();
|
||||
patchKeyedList(stepsTheadRow, colKeys, {
|
||||
keyFn: (colKey) => colKey,
|
||||
sigFn: (colKey) => `${locale}:${colKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel()}`,
|
||||
createRow: (colKey) => {
|
||||
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel() });
|
||||
return { el: th, refs: { th } };
|
||||
},
|
||||
updateRow: (refs, colKey) => {
|
||||
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel());
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
syncTableHeaderColumns(DEFAULT_STEP_COLUMN_KEYS);
|
||||
|
||||
const stepsTablePane = h('div', { className: 'table-viewport is-step-table' }, [
|
||||
h('table', { className: 'data-table' }, [
|
||||
h('thead', {}, [
|
||||
h('tr', {}, [
|
||||
h('th', { text: '步序' }),
|
||||
h('th', { text: '模型' }),
|
||||
h('th', { text: '速度' }),
|
||||
h('th', { text: '首字' }),
|
||||
h('th', { text: '上下文 / 思考 / 正文' }),
|
||||
h('th', { text: '缓存' }),
|
||||
h('th', { text: '费用' }),
|
||||
]),
|
||||
]),
|
||||
h('thead', {}, [stepsTheadRow]),
|
||||
stepsTbody,
|
||||
]),
|
||||
]);
|
||||
@@ -263,26 +293,29 @@ export const StepsDetailView = defineComponent({
|
||||
className: 'table-scroll-host',
|
||||
});
|
||||
|
||||
// --- 子视图 2:总汇总分析面板(顶部会话线性图 + 顶部趋势拟合图 + 底部极简模型总览) ---
|
||||
// --- 子视图 2:总汇总分析面板 ---
|
||||
let selectedLineMetric = 'totalTokens';
|
||||
let selectedFitMetric = 'tps';
|
||||
|
||||
// 拟合模型锁定状态机:进入“总汇总”时默认锚定当前调用模型,停留在视图内期间绝不随轮询跳变
|
||||
let fitLockedCascadeId = null;
|
||||
let fitLockedModelKeys = [];
|
||||
let fitPinnedWhileVisible = false;
|
||||
let fitUserPicked = false;
|
||||
|
||||
const lineSummaryBadge = h('span', { className: 'cons-badge text-mono', text: '0 步' });
|
||||
const lineTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.lineTitle') });
|
||||
const lineSummaryBadge = h('span', {
|
||||
className: 'cons-badge text-mono',
|
||||
text: t('header.convMetaSteps', { count: 0 }),
|
||||
});
|
||||
const lineModelSelect = CustomSelect({
|
||||
multiple: true,
|
||||
allValue: '__all__',
|
||||
collapseAll: false,
|
||||
multiUnit: '模型',
|
||||
multiUnit: t('steps.unitModel'),
|
||||
modelValue: selectedLineModels,
|
||||
placeholder: '全部模型',
|
||||
placeholder: t('steps.allModels'),
|
||||
className: 'sstep-fit-model-select sstep-line-model-select',
|
||||
options: [{ value: '__all__', label: '全部模型' }],
|
||||
options: [{ value: '__all__', label: t('steps.allModels') }],
|
||||
onUpdateModelValue: (nextModels) => {
|
||||
if (!Array.isArray(nextModels) || nextModels.length === 0) return;
|
||||
selectedLineModels = nextModels;
|
||||
@@ -292,15 +325,9 @@ export const StepsDetailView = defineComponent({
|
||||
lineModelSelect.el.setAttribute('hidden', '');
|
||||
|
||||
const lineMetricSwitch = SegmentedControl({
|
||||
ariaLabel: '会话线性图指标切换',
|
||||
ariaLabel: t('steps.lineTitle'),
|
||||
modelValue: selectedLineMetric,
|
||||
options: [
|
||||
{ value: 'totalTokens', label: '总Token' },
|
||||
{ value: 'context', label: '上下文' },
|
||||
{ value: 'tps', label: 'TPS' },
|
||||
{ value: 'ttft', label: '首字' },
|
||||
{ value: 'cost', label: '费用' },
|
||||
],
|
||||
options: getLineMetricSwitchOptions(),
|
||||
onUpdateModelValue: (nextMetric) => {
|
||||
selectedLineMetric = nextMetric;
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
@@ -309,10 +336,7 @@ export const StepsDetailView = defineComponent({
|
||||
const sessionLineChart = createSessionLineChart();
|
||||
const sessionLineCard = h('div', { className: 'sstep-card sstep-line-card' }, [
|
||||
h('div', { className: 'sstep-card-head' }, [
|
||||
h('div', { className: 'sstep-card-title-group' }, [
|
||||
h('span', { className: 'sstep-card-title', text: '会话走势' }),
|
||||
lineSummaryBadge,
|
||||
]),
|
||||
h('div', { className: 'sstep-card-title-group' }, [lineTitleEl, lineSummaryBadge]),
|
||||
h('div', { className: 'sstep-fit-controls' }, [
|
||||
lineModelSelect.el,
|
||||
lineMetricSwitch.el,
|
||||
@@ -321,16 +345,20 @@ export const StepsDetailView = defineComponent({
|
||||
sessionLineChart.el,
|
||||
]);
|
||||
|
||||
const fitSummaryBadge = h('span', { className: 'cons-badge text-mono', text: '0 样本' });
|
||||
const fitTitleEl = h('span', { className: 'sstep-card-title', text: t('steps.fitTitle') });
|
||||
const fitSummaryBadge = h('span', {
|
||||
className: 'cons-badge text-mono',
|
||||
text: t('header.convMetaSteps', { count: 0 }),
|
||||
});
|
||||
const fitModelSelect = CustomSelect({
|
||||
multiple: true,
|
||||
allValue: '__all__',
|
||||
collapseAll: false,
|
||||
multiUnit: '模型',
|
||||
multiUnit: t('steps.unitModel'),
|
||||
modelValue: ['__all__'],
|
||||
placeholder: '选择模型',
|
||||
placeholder: t('steps.selectModel'),
|
||||
className: 'sstep-fit-model-select',
|
||||
options: [{ value: '__all__', label: '全部模型' }],
|
||||
options: [{ value: '__all__', label: t('steps.allModels') }],
|
||||
onUpdateModelValue: (nextModelKeys) => {
|
||||
if (!Array.isArray(nextModelKeys) || nextModelKeys.length === 0) return;
|
||||
fitLockedModelKeys = nextModelKeys;
|
||||
@@ -342,14 +370,9 @@ export const StepsDetailView = defineComponent({
|
||||
fitModelSelect.el.setAttribute('hidden', '');
|
||||
|
||||
const fitMetricSwitch = SegmentedControl({
|
||||
ariaLabel: '趋势拟合指标切换',
|
||||
ariaLabel: t('steps.fitTitle'),
|
||||
modelValue: selectedFitMetric,
|
||||
options: [
|
||||
{ value: 'tps', label: 'TPS' },
|
||||
{ value: 'ttft', label: '首字' },
|
||||
{ value: 'cache', label: '缓存' },
|
||||
{ value: 'cost', label: '费用' },
|
||||
],
|
||||
options: getFitMetricSwitchOptions(),
|
||||
onUpdateModelValue: (nextMetric) => {
|
||||
selectedFitMetric = nextMetric;
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
@@ -358,29 +381,27 @@ export const StepsDetailView = defineComponent({
|
||||
const modelFitChart = createModelFitChart();
|
||||
const modelFitCard = h('div', { className: 'sstep-card sstep-fit-card' }, [
|
||||
h('div', { className: 'sstep-card-head' }, [
|
||||
h('div', { className: 'sstep-card-title-group' }, [
|
||||
h('span', { className: 'sstep-card-title', text: '趋势拟合' }),
|
||||
fitSummaryBadge,
|
||||
]),
|
||||
h('div', { className: 'sstep-fit-controls' }, [
|
||||
fitModelSelect.el,
|
||||
fitMetricSwitch.el,
|
||||
]),
|
||||
h('div', { className: 'sstep-card-title-group' }, [fitTitleEl, fitSummaryBadge]),
|
||||
h('div', { className: 'sstep-fit-controls' }, [fitModelSelect.el, fitMetricSwitch.el]),
|
||||
]),
|
||||
modelFitChart.el,
|
||||
]);
|
||||
|
||||
const modelsSummaryMeta = h('span', { className: 'cons-badge text-mono', text: '0 次' });
|
||||
const modelsSectionTitleEl = h('span', {
|
||||
className: 'sstep-card-title',
|
||||
text: t('steps.modelsTitle'),
|
||||
});
|
||||
const modelsSummaryMeta = h('span', {
|
||||
className: 'cons-badge text-mono',
|
||||
text: t('cons.callsCount', { calls: 0 }),
|
||||
});
|
||||
const modelsEmptyEl = h('div', {
|
||||
className: 'smodel-empty text-muted',
|
||||
text: '当前范围暂无模型调用记录',
|
||||
text: t('steps.modelsEmpty'),
|
||||
});
|
||||
const modelsListEl = h('div', { className: 'smodel-list' });
|
||||
const modelsSummarySection = h('div', { className: 'smodel-section' }, [
|
||||
h('div', { className: 'smodel-section-head' }, [
|
||||
h('span', { className: 'sstep-card-title', text: '模型总览' }),
|
||||
modelsSummaryMeta,
|
||||
]),
|
||||
h('div', { className: 'smodel-section-head' }, [modelsSectionTitleEl, modelsSummaryMeta]),
|
||||
modelsEmptyEl,
|
||||
modelsListEl,
|
||||
]);
|
||||
@@ -396,6 +417,7 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
modelsScroll.el.setAttribute('hidden', '');
|
||||
|
||||
const panelTitleTextEl = h('span', { text: t('steps.title') });
|
||||
const panelEl = h(
|
||||
'section',
|
||||
{
|
||||
@@ -406,7 +428,7 @@ export const StepsDetailView = defineComponent({
|
||||
h('div', { className: 'panel-header steps-panel-header' }, [
|
||||
h('span', { className: 'panel-title steps-panel-title' }, [
|
||||
createSvgIcon('table', { size: 13 }),
|
||||
h('span', { text: '调用记录' }),
|
||||
panelTitleTextEl,
|
||||
]),
|
||||
h('div', { className: 'steps-header-controls' }, [
|
||||
inlineScopeSelect.el,
|
||||
@@ -424,15 +446,17 @@ export const StepsDetailView = defineComponent({
|
||||
let latestSlice = null;
|
||||
let isDirty = false;
|
||||
|
||||
/**
|
||||
* 解析当前会话/代理作用域下的默认活跃调用模型分组键。
|
||||
*/
|
||||
function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) {
|
||||
const activeCand = getStepModelGroupKey({
|
||||
modelLabel: scopedConv?.activeModelLabel,
|
||||
modelShort: scopedConv?.activeModelShort,
|
||||
});
|
||||
if (activeCand && activeCand !== '模型未知' && availableModelKeys.has(activeCand)) {
|
||||
if (
|
||||
activeCand &&
|
||||
activeCand !== '模型未知' &&
|
||||
activeCand !== t('fmt.unknownModel') &&
|
||||
availableModelKeys.has(activeCand)
|
||||
) {
|
||||
return activeCand;
|
||||
}
|
||||
for (let i = chronoSteps.length - 1; i >= 0; i--) {
|
||||
@@ -452,9 +476,6 @@ export const StepsDetailView = defineComponent({
|
||||
return '__all__';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化模型多选列表(支持同时勾选 2..N 个具体模型以独立分色对比,仅在明确点击“全部模型”或无有效项时回到 `['__all__']`)。
|
||||
*/
|
||||
function normalizeMultiModelSelection(rawSelection, availableModelKeys) {
|
||||
if (availableModelKeys.size <= 1) return ['__all__'];
|
||||
const arr = Array.isArray(rawSelection) ? rawSelection : [];
|
||||
@@ -464,12 +485,102 @@ export const StepsDetailView = defineComponent({
|
||||
return valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对单步测速表、顶部会话走势图、顶部趋势拟合图及底部极简模型列表执行增量更新。
|
||||
*/
|
||||
function refreshStaticLocaleLabels() {
|
||||
patchText(panelTitleTextEl, t('steps.title'));
|
||||
patchText(lineTitleEl, t('steps.lineTitle'));
|
||||
patchText(fitTitleEl, t('steps.fitTitle'));
|
||||
patchText(modelsSectionTitleEl, t('steps.modelsTitle'));
|
||||
patchText(modelsEmptyEl, t('steps.modelsEmpty'));
|
||||
lineMetricSwitch.setProps({
|
||||
modelValue: selectedLineMetric,
|
||||
options: getLineMetricSwitchOptions(),
|
||||
});
|
||||
fitMetricSwitch.setProps({
|
||||
modelValue: selectedFitMetric,
|
||||
options: getFitMetricSwitchOptions(),
|
||||
});
|
||||
const colKeys = normalizeClientStepColumns(latestSlice?.stepTableColumns);
|
||||
syncTableHeaderColumns(colKeys);
|
||||
if (!latestSlice) {
|
||||
subTabSwitch.setProps({
|
||||
modelValue: uiStore.getState().stepsSubTab,
|
||||
options: [
|
||||
{ value: 'steps', label: t('steps.tabSteps', { count: 0 }) },
|
||||
{ value: 'models', label: t('steps.tabModels') },
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function renderStepTable(tableSteps, cascadeId, colKeys, locale, {
|
||||
effectiveScopes,
|
||||
hasSubagents,
|
||||
displaySettings,
|
||||
}) {
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const wantedSet = new Set(colKeys);
|
||||
syncTableHeaderColumns(colKeys);
|
||||
|
||||
const cellCtx = {
|
||||
hasSubagents,
|
||||
effectiveScopes,
|
||||
scopeSigKey: effectiveScopes.join(','),
|
||||
displaySettings,
|
||||
onSelectAgentScopes: applyAgentScopesSelection,
|
||||
};
|
||||
|
||||
patchKeyedList(stepsTbody, tableSteps, {
|
||||
keyFn: (st) => `${st.agentCascadeId || cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
sigFn: (st) => {
|
||||
const parts = colKeys
|
||||
.map((colKey) => STEP_COLUMN_REGISTRY[colKey].sigPart(st, cellCtx))
|
||||
.join('|');
|
||||
return `${locale}:${colOrderSig}:${parts}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const tr = h('tr');
|
||||
return {
|
||||
el: tr,
|
||||
refs: {
|
||||
cellMap: new Map(),
|
||||
colOrderSig: '',
|
||||
},
|
||||
};
|
||||
},
|
||||
updateRow: (refs, st, _idx, tr) => {
|
||||
if (refs.colOrderSig !== colOrderSig) {
|
||||
for (const [oldColKey, entry] of refs.cellMap) {
|
||||
if (!wantedSet.has(oldColKey)) {
|
||||
tr.removeChild(entry.td);
|
||||
refs.cellMap.delete(oldColKey);
|
||||
}
|
||||
}
|
||||
|
||||
for (const [i, colKey] of colKeys.entries()) {
|
||||
if (!refs.cellMap.has(colKey)) {
|
||||
refs.cellMap.set(colKey, STEP_COLUMN_REGISTRY[colKey].createCell());
|
||||
}
|
||||
const targetTd = refs.cellMap.get(colKey).td;
|
||||
const currentTd = tr.children[i] || null;
|
||||
if (currentTd !== targetTd) {
|
||||
tr.insertBefore(targetTd, currentTd);
|
||||
}
|
||||
}
|
||||
refs.colOrderSig = colOrderSig;
|
||||
}
|
||||
|
||||
for (const colKey of colKeys) {
|
||||
const cellEntry = refs.cellMap.get(colKey);
|
||||
STEP_COLUMN_REGISTRY[colKey].updateCell(cellEntry.refs, st, cellCtx);
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function renderStepsData(slice) {
|
||||
if (!slice) return;
|
||||
const uiSt = uiStore.getState();
|
||||
const locale = getEffectiveLocale();
|
||||
|
||||
const currentCid = String(slice.cascadeId || slice.activeConversation?.cascadeId || '');
|
||||
if (currentCid !== fitLockedCascadeId) {
|
||||
@@ -516,23 +627,25 @@ export const StepsDetailView = defineComponent({
|
||||
const scopeOpts = [
|
||||
{
|
||||
value: 'all',
|
||||
label: '全部汇总',
|
||||
meta: `${aggregated?.stepCount ?? 0}步`,
|
||||
label: t('steps.allAgents'),
|
||||
meta: t('header.convMetaSteps', { count: aggregated?.stepCount ?? 0 }),
|
||||
},
|
||||
{
|
||||
value: 'main',
|
||||
label: '主代理',
|
||||
meta: `${mainAgent?.stepCount ?? 0}步`,
|
||||
label: t('fmt.mainAgent'),
|
||||
meta: t('header.convMetaSteps', { count: mainAgent?.stepCount ?? 0 }),
|
||||
},
|
||||
...subagents.map((s) => ({
|
||||
value: s.agentId,
|
||||
label: formatAgentLabel(s),
|
||||
meta: `${s.stepCount || 0}步`,
|
||||
meta: t('header.convMetaSteps', { count: s.stepCount || 0 }),
|
||||
})),
|
||||
];
|
||||
inlineScopeSelect.setProps({
|
||||
modelValue: effectiveScopes,
|
||||
options: scopeOpts,
|
||||
placeholder: t('steps.allAgents'),
|
||||
multiUnit: t('steps.unitAgent'),
|
||||
});
|
||||
|
||||
if (effectiveScopes[0] === 'all') {
|
||||
@@ -573,8 +686,8 @@ export const StepsDetailView = defineComponent({
|
||||
orchestratorIdMode: slice.orchestratorIdMode,
|
||||
};
|
||||
|
||||
// 提取当前代理作用域下的时间升序步骤与全量可选模型列表
|
||||
const showAgentPrefix = isMergedMultiAgents;
|
||||
const showModels = uiSt.stepsSubTab === 'models';
|
||||
const chronoSteps = toChronologicalSteps(steps, isMergedMultiAgents);
|
||||
|
||||
const stepTtftFallbackMap = new Map();
|
||||
@@ -584,13 +697,13 @@ export const StepsDetailView = defineComponent({
|
||||
if (!stepModelOptionMap.has(gk)) {
|
||||
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
||||
stepModelOptionMap.set(gk, {
|
||||
label: disp.text.replace(/·压缩\s*$/u, '').trim() || gk,
|
||||
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk,
|
||||
calls: 0,
|
||||
});
|
||||
}
|
||||
stepModelOptionMap.get(gk).calls += 1;
|
||||
|
||||
if (!st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) {
|
||||
if (showModels && !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0) {
|
||||
const prev = stepTtftFallbackMap.get(gk) || { sum: 0, count: 0 };
|
||||
prev.sum += Number(st.ttftSec);
|
||||
prev.count += 1;
|
||||
@@ -615,8 +728,8 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
perModelOptions.push({
|
||||
value: gk,
|
||||
label: disp.text.replace(/·压缩\s*$/u, '').trim() || gk,
|
||||
meta: `${Number(m.calls || 0)}步`,
|
||||
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk,
|
||||
meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }),
|
||||
});
|
||||
}
|
||||
for (const [gk, info] of stepModelOptionMap.entries()) {
|
||||
@@ -629,7 +742,7 @@ export const StepsDetailView = defineComponent({
|
||||
perModelOptions.push({
|
||||
value: gk,
|
||||
label: info.label,
|
||||
meta: `${info.calls}步`,
|
||||
meta: t('header.convMetaSteps', { count: info.calls }),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -638,13 +751,13 @@ export const StepsDetailView = defineComponent({
|
||||
const modelSelectOptions = [
|
||||
{
|
||||
value: '__all__',
|
||||
label: '全部模型',
|
||||
meta: `${chronoSteps.length}步`,
|
||||
label: t('steps.allModels'),
|
||||
meta: t('header.convMetaSteps', { count: steps.length }),
|
||||
},
|
||||
...perModelOptions,
|
||||
];
|
||||
|
||||
// 1. “按步查看”模型多选过滤与表格增量对账
|
||||
// 1. “按步查看”动态列头同步与表格行级增量对账
|
||||
selectedTableModels = normalizeMultiModelSelection(
|
||||
selectedTableModels,
|
||||
availableModelKeys
|
||||
@@ -655,6 +768,8 @@ export const StepsDetailView = defineComponent({
|
||||
stepsModelSelect.setProps({
|
||||
modelValue: selectedTableModels,
|
||||
options: modelSelectOptions,
|
||||
placeholder: t('steps.allModels'),
|
||||
multiUnit: t('steps.unitModel'),
|
||||
});
|
||||
if (!showStepsModelFilter) stepsModelSelect.close();
|
||||
} else {
|
||||
@@ -670,143 +785,64 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
const stepsTabLabel =
|
||||
tableSteps.length !== steps.length
|
||||
? `按步查看 (${tableSteps.length}/${steps.length})`
|
||||
: `按步查看 (${steps.length})`;
|
||||
? t('steps.tabStepsFiltered', {
|
||||
filtered: tableSteps.length,
|
||||
total: steps.length,
|
||||
})
|
||||
: t('steps.tabSteps', { count: steps.length });
|
||||
|
||||
subTabSwitch.setProps({
|
||||
options: [
|
||||
{ value: 'steps', label: stepsTabLabel },
|
||||
{ value: 'models', label: '总汇总' },
|
||||
{ value: 'models', label: t('steps.tabModels') },
|
||||
],
|
||||
});
|
||||
|
||||
const scopeSigKey = effectiveScopes.join(',');
|
||||
patchKeyedList(stepsTbody, tableSteps, {
|
||||
keyFn: (st) => `${st.agentCascadeId || slice.cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
sigFn: (st) => {
|
||||
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: '—' });
|
||||
const outTok = Math.max(0, Number(st.outputTokens || 0));
|
||||
const thinkTok = Math.max(0, Number(st.thinkingTokens || 0));
|
||||
const respTok =
|
||||
st.responseTokens != null
|
||||
? Math.max(0, Number(st.responseTokens))
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
return `${hasSubagents}:${scopeSigKey}:${st.agentId || 'main'}:${st.stepIndex}:${disp.text}:${disp.title}:${st.tokPerSec}:${st.ttftSec}:${st.contextTokens}:${outTok}:${thinkTok}:${respTok}:${st.cacheHitPct}:${st.costUsd}:${st.selectedSpeedReason}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const agentBadgeEl = h('span', {
|
||||
className: 'agent-badge is-clickable',
|
||||
hidden: true,
|
||||
style: 'margin-right: 4px;',
|
||||
});
|
||||
const stepNumText = h('span');
|
||||
const tdStep = h('td', {}, [agentBadgeEl, stepNumText]);
|
||||
if (!showModels) {
|
||||
const colKeys = normalizeClientStepColumns(slice.stepTableColumns);
|
||||
renderStepTable(tableSteps, slice.cascadeId, colKeys, locale, {
|
||||
effectiveScopes,
|
||||
hasSubagents,
|
||||
displaySettings,
|
||||
});
|
||||
stepsScroll.refresh();
|
||||
}
|
||||
|
||||
const tdModel = h('td', {
|
||||
style: 'max-width: 120px; overflow: hidden; text-overflow: ellipsis;',
|
||||
});
|
||||
const speedMain = h('strong', {
|
||||
className: 'cell-value accent-speed',
|
||||
style: 'font-size: 11px;',
|
||||
});
|
||||
const speedReason = h('div', { className: 'text-muted', style: 'font-size: 9.5px;' });
|
||||
const tdSpeed = h('td', {}, [speedMain, speedReason]);
|
||||
|
||||
const tdTtft = h('td');
|
||||
const tdCtx = h('td');
|
||||
const tdCache = h('td', {
|
||||
className: 'cell-value accent-ok',
|
||||
style: 'font-size: 11px;',
|
||||
});
|
||||
const tdCost = h('td', { style: 'font-weight: 600;' });
|
||||
|
||||
const tr = h('tr', {}, [tdStep, tdModel, tdSpeed, tdTtft, tdCtx, tdCache, tdCost]);
|
||||
return {
|
||||
el: tr,
|
||||
refs: {
|
||||
agentBadgeEl,
|
||||
stepNumText,
|
||||
tdModel,
|
||||
speedMain,
|
||||
speedReason,
|
||||
tdTtft,
|
||||
tdCtx,
|
||||
tdCache,
|
||||
tdCost,
|
||||
},
|
||||
};
|
||||
},
|
||||
updateRow: (refs, st) => {
|
||||
patchAttr(refs.agentBadgeEl, 'hidden', !hasSubagents);
|
||||
if (hasSubagents) {
|
||||
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
|
||||
patchAttr(refs.agentBadgeEl, 'class', `agent-badge is-clickable ${badgeCls}`);
|
||||
patchText(refs.agentBadgeEl, st.agentBadge || (st.isSubagent ? '子' : '主'));
|
||||
const targetScope = st.agentId || 'main';
|
||||
const isSoleTarget =
|
||||
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
|
||||
patchAttr(
|
||||
refs.agentBadgeEl,
|
||||
'title',
|
||||
isSoleTarget
|
||||
? '点击切回全部汇总'
|
||||
: `点击仅过滤查看 ${st.agentLabel || '该代理'}(按住 Ctrl/Shift 可加减多选)`
|
||||
);
|
||||
refs.agentBadgeEl.onclick = (e) => {
|
||||
if (e && (e.ctrlKey || e.metaKey || e.shiftKey) && effectiveScopes[0] !== 'all') {
|
||||
const next = effectiveScopes.includes(targetScope)
|
||||
? effectiveScopes.filter((id) => id !== targetScope)
|
||||
: [...effectiveScopes, targetScope];
|
||||
applyAgentScopesSelection(next.length > 0 ? next : ['all']);
|
||||
} else {
|
||||
applyAgentScopesSelection(isSoleTarget ? ['all'] : [targetScope]);
|
||||
}
|
||||
};
|
||||
}
|
||||
patchText(refs.stepNumText, `#${Number(st.stepIndex)}`);
|
||||
const modelDisplay = resolveModelDisplayInfo(st, displaySettings, { fallback: '—' });
|
||||
patchText(refs.tdModel, modelDisplay.text);
|
||||
patchAttr(refs.tdModel, 'title', modelDisplay.title);
|
||||
|
||||
patchText(refs.speedMain, formatMetric(st.tokPerSec, ' tok/s'));
|
||||
const reason = speedReasonText(st.selectedSpeedReason);
|
||||
patchText(refs.speedReason, reason);
|
||||
patchAttr(refs.speedReason, 'hidden', !reason);
|
||||
|
||||
patchText(refs.tdTtft, formatMetric(st.ttftSec, 's'));
|
||||
const outTok = Math.max(0, Number(st.outputTokens || 0));
|
||||
const thinkTok = Math.max(0, Number(st.thinkingTokens || 0));
|
||||
const respTok =
|
||||
st.responseTokens != null
|
||||
? Math.max(0, Number(st.responseTokens))
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
patchText(
|
||||
refs.tdCtx,
|
||||
`${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}`
|
||||
);
|
||||
patchAttr(
|
||||
refs.tdCtx,
|
||||
'title',
|
||||
`上下文 ${Math.round(Number(st.contextTokens || 0))} · 思考 ${Math.round(thinkTok)} · 正文 ${Math.round(respTok)}`
|
||||
);
|
||||
patchText(refs.tdCache, `${Number(st.cacheHitPct ?? 0)}%`);
|
||||
|
||||
const costVal = st.costUsd;
|
||||
patchText(refs.tdCost, formatUsd(costVal, { precise: true }));
|
||||
patchClasses(refs.tdCost, { 'accent-speed': costVal >= 0.15 });
|
||||
},
|
||||
});
|
||||
|
||||
// 2. 顶部“会话走势”多选模型对比与图表更新(单模型时隐藏下拉框)
|
||||
// 2. 顶部“会话走势”更新
|
||||
selectedLineModels = normalizeMultiModelSelection(
|
||||
selectedLineModels,
|
||||
availableModelKeys
|
||||
);
|
||||
|
||||
// 3. 顶部“趋势拟合”模型锁定随当前会话与代理范围更新。
|
||||
const defaultActiveModelKey = resolveDefaultActiveModelKey(
|
||||
activeModelSource,
|
||||
chronoSteps,
|
||||
models,
|
||||
availableModelKeys
|
||||
);
|
||||
const sanitizedLocked = fitLockedModelKeys.includes('__all__')
|
||||
? ['__all__']
|
||||
: Array.from(new Set(fitLockedModelKeys.filter((k) => availableModelKeys.has(k))));
|
||||
|
||||
if (!showModels) {
|
||||
fitPinnedWhileVisible = false;
|
||||
}
|
||||
if ((!fitPinnedWhileVisible && !fitUserPicked) || sanitizedLocked.length === 0) {
|
||||
fitLockedModelKeys = [defaultActiveModelKey];
|
||||
} else {
|
||||
fitLockedModelKeys = sanitizedLocked;
|
||||
}
|
||||
if (!showModels) return;
|
||||
if (availableModelKeys.size > 0) fitPinnedWhileVisible = true;
|
||||
|
||||
patchAttr(lineModelSelect.el, 'hidden', !hasMultipleModels);
|
||||
if (hasMultipleModels) {
|
||||
lineModelSelect.setProps({
|
||||
modelValue: selectedLineModels,
|
||||
options: modelSelectOptions,
|
||||
placeholder: t('steps.allModels'),
|
||||
multiUnit: t('steps.unitModel'),
|
||||
});
|
||||
} else {
|
||||
lineModelSelect.close();
|
||||
@@ -823,46 +859,6 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
patchText(lineSummaryBadge, lineRes.summaryBadge);
|
||||
|
||||
// 3. 顶部“趋势拟合”多选模型对比与锁定状态机更新(单模型时隐藏下拉框)
|
||||
const defaultActiveModelKey = resolveDefaultActiveModelKey(
|
||||
activeModelSource,
|
||||
chronoSteps,
|
||||
models,
|
||||
availableModelKeys
|
||||
);
|
||||
|
||||
const sanitizeFitSelection = (keys) => {
|
||||
if (!Array.isArray(keys) || keys.length === 0) return [];
|
||||
if (keys.includes('__all__')) return ['__all__'];
|
||||
return Array.from(new Set(keys.filter((k) => availableModelKeys.has(k))));
|
||||
};
|
||||
|
||||
const isModelsViewVisible =
|
||||
uiSt.activeView === 'steps' && uiSt.stepsSubTab === 'models';
|
||||
const sanitizedLocked = sanitizeFitSelection(fitLockedModelKeys);
|
||||
|
||||
if (!isModelsViewVisible) {
|
||||
fitPinnedWhileVisible = false;
|
||||
if (!fitUserPicked || sanitizedLocked.length === 0) {
|
||||
fitLockedModelKeys = [defaultActiveModelKey];
|
||||
} else {
|
||||
fitLockedModelKeys = sanitizedLocked;
|
||||
}
|
||||
} else if (!fitPinnedWhileVisible) {
|
||||
if (!fitUserPicked || sanitizedLocked.length === 0) {
|
||||
fitLockedModelKeys = [defaultActiveModelKey];
|
||||
} else {
|
||||
fitLockedModelKeys = sanitizedLocked;
|
||||
}
|
||||
if (availableModelKeys.size > 0) {
|
||||
fitPinnedWhileVisible = true;
|
||||
}
|
||||
} else if (sanitizedLocked.length === 0) {
|
||||
fitLockedModelKeys = [defaultActiveModelKey];
|
||||
} else {
|
||||
fitLockedModelKeys = sanitizedLocked;
|
||||
}
|
||||
|
||||
const effectiveFitModelKeys =
|
||||
availableModelKeys.size === 0
|
||||
? ['__all__']
|
||||
@@ -877,6 +873,8 @@ export const StepsDetailView = defineComponent({
|
||||
fitModelSelect.setProps({
|
||||
modelValue: effectiveFitModelKeys,
|
||||
options: modelSelectOptions,
|
||||
placeholder: t('steps.selectModel'),
|
||||
multiUnit: t('steps.unitModel'),
|
||||
});
|
||||
} else {
|
||||
fitModelSelect.close();
|
||||
@@ -893,7 +891,7 @@ export const StepsDetailView = defineComponent({
|
||||
});
|
||||
patchText(fitSummaryBadge, fitRes.summaryBadge);
|
||||
|
||||
// 4. 极简模型总览列表增量对账(按最终展示名去重归并,一卡表达调用、Token 4 段占比、均速/首字/缓存与费用)
|
||||
// 4. 极简模型总览列表增量对账
|
||||
const displayModels = mergeModelsByDisplayName(models, displaySettings, { fallback: '—' });
|
||||
let sumCalls = 0;
|
||||
let sumTokens = 0;
|
||||
@@ -909,13 +907,16 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
|
||||
if (displayModels.length === 0) {
|
||||
patchText(modelsSummaryMeta, '0 次');
|
||||
patchText(modelsSummaryMeta, t('cons.callsCount', { calls: 0 }));
|
||||
} else {
|
||||
const modelCountPart = displayModels.length > 1 ? `${displayModels.length} 模型 · ` : '';
|
||||
const modelCountPart =
|
||||
displayModels.length > 1
|
||||
? t('steps.modelsSummaryPrefix', { count: displayModels.length })
|
||||
: '';
|
||||
const isAllUnpricedSum = sumCalls > 0 && sumUnpriced >= sumCalls && !(sumCost > 0);
|
||||
patchText(
|
||||
modelsSummaryMeta,
|
||||
`${modelCountPart}${sumCalls} 次 · ${formatTokens(sumTokens)} · ${formatUsd(
|
||||
`${modelCountPart}${t('cons.callsCount', { calls: sumCalls })} · ${formatTokens(sumTokens)} · ${formatUsd(
|
||||
isAllUnpricedSum ? null : sumCost,
|
||||
{
|
||||
precise: sumCost > 0 && sumCost < 0.1,
|
||||
@@ -946,7 +947,7 @@ export const StepsDetailView = defineComponent({
|
||||
: [gk];
|
||||
const isActiveFit =
|
||||
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
|
||||
return `${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`;
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const nameEl = h('strong', { className: 'smodel-name' });
|
||||
@@ -977,7 +978,9 @@ export const StepsDetailView = defineComponent({
|
||||
const gk = getStepModelGroupKey(m);
|
||||
const cardGroupKeys =
|
||||
Array.isArray(m.sourceLabels) && m.sourceLabels.length > 0
|
||||
? Array.from(new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl }))))
|
||||
? Array.from(
|
||||
new Set(m.sourceLabels.map((lbl) => getStepModelGroupKey({ label: lbl })))
|
||||
)
|
||||
: [gk];
|
||||
const dispText = m.displayText || '—';
|
||||
const dispTitle = m.displayTitle || dispText;
|
||||
@@ -988,7 +991,9 @@ export const StepsDetailView = defineComponent({
|
||||
const callSharePct = sumCalls > 0 ? Math.round((calls / sumCalls) * 100) : 0;
|
||||
patchText(
|
||||
refs.callsPillEl,
|
||||
displayModels.length > 1 ? `${calls}次 · ${callSharePct}%` : `${calls}次`
|
||||
displayModels.length > 1
|
||||
? t('steps.modelCallsShare', { calls, pct: callSharePct })
|
||||
: t('steps.modelCallsOnly', { calls })
|
||||
);
|
||||
|
||||
const inTok = Math.max(0, Number(m.inputTokens || 0));
|
||||
@@ -1033,11 +1038,20 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
patchText(
|
||||
refs.perfEl,
|
||||
`均速 ${formatMetric(m.avgTokPerSec, ' tok/s')} · 首字 ${formatMetric(resolvedAvgTtft, 's')} · 缓存 ${resolvedCachePct}%`
|
||||
t('steps.modelPerfFoot', {
|
||||
tps: formatMetric(m.avgTokPerSec, ' tok/s'),
|
||||
ttft: formatMetric(resolvedAvgTtft, 's'),
|
||||
cache: resolvedCachePct,
|
||||
})
|
||||
);
|
||||
patchText(
|
||||
refs.splitEl,
|
||||
`入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 思 ${formatTokens(thinkTok)} · 正 ${formatTokens(respTok)}`
|
||||
t('steps.modelSplitFoot', {
|
||||
inTok: formatTokens(inTok),
|
||||
cacheTok: formatTokens(cacheTok),
|
||||
thinkTok: formatTokens(thinkTok),
|
||||
respTok: formatTokens(respTok),
|
||||
})
|
||||
);
|
||||
|
||||
const isActiveFit =
|
||||
@@ -1049,8 +1063,8 @@ export const StepsDetailView = defineComponent({
|
||||
!hasMultipleModels
|
||||
? dispTitle
|
||||
: isActiveFit
|
||||
? `${dispTitle}(已纳入上方趋势拟合,按住 Ctrl/Shift 点击可多选对比)`
|
||||
: `点击在上方拟合图查看 ${dispText}(按住 Ctrl/Shift 点击可多选同图对比)`
|
||||
? t('steps.fitActiveCardTitle', { title: dispTitle })
|
||||
: t('steps.fitInactiveCardTitle', { text: dispText })
|
||||
);
|
||||
cardEl.onclick = (e) => {
|
||||
if (!hasMultipleModels) return;
|
||||
@@ -1079,11 +1093,7 @@ export const StepsDetailView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
if (uiSt.stepsSubTab === 'models') {
|
||||
modelsScroll.refresh();
|
||||
} else {
|
||||
stepsScroll.refresh();
|
||||
}
|
||||
modelsScroll.refresh();
|
||||
}
|
||||
|
||||
const unsubUi = uiStore.subscribe(
|
||||
@@ -1108,11 +1118,11 @@ export const StepsDetailView = defineComponent({
|
||||
cascadeId: st.telemetry?.activeConversation?.cascadeId,
|
||||
recentSteps: st.telemetry?.activeConversation?.recentSteps,
|
||||
sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown,
|
||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||
st.telemetry?.settings?.orchestratorIdMode
|
||||
),
|
||||
stepTableColumns: st.telemetry?.settings?.stepTableColumns,
|
||||
}),
|
||||
(slice) => {
|
||||
latestSlice = slice;
|
||||
@@ -1157,10 +1167,23 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
(st) => st.locale,
|
||||
() => {
|
||||
refreshStaticLocaleLabels();
|
||||
if (uiStore.getState().activeView === 'steps' && latestSlice) {
|
||||
renderStepsData(latestSlice);
|
||||
} else {
|
||||
isDirty = true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubUi();
|
||||
unsubTelemetry();
|
||||
unsubView();
|
||||
unsubI18n();
|
||||
sessionLineChart.destroy?.();
|
||||
modelFitChart.destroy?.();
|
||||
inlineScopeSelect.destroy();
|
||||
@@ -1177,6 +1200,7 @@ export const StepsDetailView = defineComponent({
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
stepsTheadRow,
|
||||
stepsTbody,
|
||||
modelsListEl,
|
||||
inlineScopeSelect,
|
||||
|
||||
@@ -0,0 +1,479 @@
|
||||
/**
|
||||
* @fileoverview Preferences Tab 1: `SettingsGeneralTab.js` ("常规").
|
||||
* Manages UI Language (`zh-CN` / `en-US` / `auto`), Theme Accent (`host` + 6 swatches),
|
||||
* Panel Font Scale (`sm` / `md` / `lg` / `xl`), Pricing Sync, and Plugin Updates.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import {
|
||||
normalizeClientFontScale,
|
||||
normalizeClientThemeAccent,
|
||||
} from '../../core/appearance.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { normalizeI18nLanguage, setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
normalizeClientUpdateMode,
|
||||
saveSettingsPatch,
|
||||
triggerCloudSync,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { ThemeColorPicker } from '../../components/settings/ThemeColorPicker.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||
|
||||
function getLanguageOptions() {
|
||||
return [
|
||||
{ value: 'zh-CN', label: t('settings.gen.langZh') },
|
||||
{ value: 'en-US', label: t('settings.gen.langEn') },
|
||||
{ value: 'auto', label: t('settings.gen.langAuto') },
|
||||
];
|
||||
}
|
||||
|
||||
function getFontScaleOptions() {
|
||||
return [
|
||||
{ value: 'sm', label: t('settings.gen.fontSm') },
|
||||
{ value: 'md', label: t('settings.gen.fontMd') },
|
||||
{ value: 'lg', label: t('settings.gen.fontLg') },
|
||||
{ value: 'xl', label: t('settings.gen.fontXl') },
|
||||
];
|
||||
}
|
||||
|
||||
function getUpdateModeOptions() {
|
||||
return [
|
||||
{ value: 'manual', label: t('settings.gen.updateManual') },
|
||||
{ value: 'auto', label: t('settings.gen.updateAuto') },
|
||||
{ value: 'off', label: t('settings.gen.updateOff') },
|
||||
];
|
||||
}
|
||||
|
||||
function formatCloudSyncTimeText(tsMs, updatedAt) {
|
||||
if (Number(tsMs) > 0) {
|
||||
const d = new Date(Number(tsMs));
|
||||
const pad = (n) => String(n).padStart(2, '0');
|
||||
const timeStr = `${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
return t('settings.gen.syncAt', { time: timeStr });
|
||||
}
|
||||
if (updatedAt) {
|
||||
return t('settings.gen.pubAt', { date: String(updatedAt).slice(0, 10) });
|
||||
}
|
||||
return t('settings.gen.defaultPricing');
|
||||
}
|
||||
|
||||
export const SettingsGeneralTab = defineComponent({
|
||||
name: 'SettingsGeneralTab',
|
||||
setup({ props, onCleanup }) {
|
||||
let draftLanguage = 'zh-CN';
|
||||
let draftThemeAccent = 'host';
|
||||
let draftFontScale = 'md';
|
||||
let draftPluginUpdateMode = 'manual';
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let appearanceTimer = null;
|
||||
let cloudTimer = null;
|
||||
|
||||
const appearanceStatusText = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
const cloudStatusMsg = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
|
||||
function showAppearanceFeedback(text, autoClearMs = 1500) {
|
||||
if (appearanceTimer) {
|
||||
clearTimeout(appearanceTimer);
|
||||
appearanceTimer = null;
|
||||
}
|
||||
patchText(appearanceStatusText, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
appearanceTimer = setTimeout(() => {
|
||||
appearanceTimer = null;
|
||||
patchText(appearanceStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||
if (cloudTimer) {
|
||||
clearTimeout(cloudTimer);
|
||||
cloudTimer = null;
|
||||
}
|
||||
patchText(cloudStatusMsg, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
cloudTimer = setTimeout(() => {
|
||||
cloudTimer = null;
|
||||
patchText(cloudStatusMsg, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Card 1: 界面与外观 ---
|
||||
const appearanceTitleEl = h('span', { text: t('settings.gen.appearanceTitle') });
|
||||
const langLabelEl = h('span', { className: 'form-label', text: t('settings.gen.language') });
|
||||
const accentLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.gen.themeAccent'),
|
||||
});
|
||||
const fontLabelEl = h('span', { className: 'form-label', text: t('settings.gen.fontScale') });
|
||||
const fontHintEl = h('span', {
|
||||
className: 'settings-hint-text',
|
||||
text: t('settings.gen.fontHint'),
|
||||
});
|
||||
|
||||
const languageSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.language'),
|
||||
modelValue: draftLanguage,
|
||||
options: getLanguageOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextLang = normalizeI18nLanguage(val);
|
||||
draftLanguage = nextLang;
|
||||
setI18nLanguage(nextLang);
|
||||
languageSwitch.setValue(nextLang);
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ language: nextLang });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const themeColorPicker = ThemeColorPicker({
|
||||
modelValue: draftThemeAccent,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextAccent = normalizeClientThemeAccent(val);
|
||||
draftThemeAccent = nextAccent;
|
||||
themeColorPicker.refs.setValue(nextAccent);
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ themeAccent: nextAccent });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const fontScaleSwitch = SegmentedControl({
|
||||
ariaLabel: t('settings.gen.fontScale'),
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextScale = normalizeClientFontScale(val);
|
||||
draftFontScale = nextScale;
|
||||
fontScaleSwitch.setValue(nextScale);
|
||||
showAppearanceFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ fontScale: nextScale });
|
||||
showAppearanceFeedback(t('settings.saved'), 1500);
|
||||
props.onLayoutChange?.();
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showAppearanceFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const appearancePanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
appearanceTitleEl,
|
||||
]),
|
||||
appearanceStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [langLabelEl, languageSwitch.el]),
|
||||
h('div', { className: 'form-row' }, [accentLabelEl, themeColorPicker.el]),
|
||||
h('div', { className: 'form-row' }, [fontLabelEl, fontScaleSwitch.el, fontHintEl]),
|
||||
]);
|
||||
|
||||
// --- Card 2: 版本更新 ---
|
||||
const updateTitleEl = h('span', { text: t('settings.gen.updateTitle') });
|
||||
const updateModeLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.gen.updateMode'),
|
||||
});
|
||||
const pricingCellLabelEl = h('span', {
|
||||
className: 'cell-label',
|
||||
text: t('settings.gen.pricingLabel'),
|
||||
});
|
||||
const versionCellLabelEl = h('span', {
|
||||
className: 'cell-label',
|
||||
text: t('settings.gen.versionLabel'),
|
||||
});
|
||||
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: getUpdateModeOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientUpdateMode(val);
|
||||
draftPluginUpdateMode = nextMode;
|
||||
autoUpdateSelect.setValue(nextMode);
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
showCloudFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
pluginUpdateMode: nextMode,
|
||||
autoUpdatePlugin: nextMode === 'auto',
|
||||
});
|
||||
showCloudFeedback(t('settings.saved'), 1800);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||
showCloudFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: t('quota.loading') });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.4' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: t('settings.gen.checkingBtn') });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: t('settings.gen.syncBtn') });
|
||||
const syncPricingBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(syncPricingBtn, 'disabled', true);
|
||||
patchText(syncPricingBtnText, t('settings.gen.syncingBtn'));
|
||||
showCloudFeedback(t('settings.gen.syncingMsg'), 0);
|
||||
try {
|
||||
const res = await triggerCloudSync();
|
||||
const cs = res?.cloudStatus;
|
||||
if (res?.ok && cs) {
|
||||
showCloudFeedback(t('settings.gen.syncedMsg', { count: cs.modelCount }), 3500);
|
||||
} else {
|
||||
showCloudFeedback(cs?.lastSyncError || t('settings.gen.syncFallbackMsg'), 4500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || t('settings.gen.syncFallbackMsg'), 4500);
|
||||
} finally {
|
||||
patchAttr(syncPricingBtn, 'disabled', false);
|
||||
patchText(syncPricingBtnText, t('settings.gen.syncBtn'));
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), syncPricingBtnText]
|
||||
);
|
||||
|
||||
const updatePluginBtnText = h('span', { text: t('settings.gen.checkUpdateBtn') });
|
||||
const updatePluginBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
patchAttr(updatePluginBtn, 'disabled', true);
|
||||
try {
|
||||
if (!latestCloudStatus?.updateAvailable) {
|
||||
patchText(updatePluginBtnText, t('settings.gen.checkingBtn'));
|
||||
showCloudFeedback(t('settings.gen.checkingMsg'), 0);
|
||||
const syncRes = await triggerCloudSync();
|
||||
const cs = syncRes?.cloudStatus || latestCloudStatus;
|
||||
if (cs) {
|
||||
latestCloudStatus = cs;
|
||||
renderCloudStatus(cs);
|
||||
}
|
||||
if (!syncRes?.ok && cs?.lastSyncError) {
|
||||
showCloudFeedback(
|
||||
t('settings.gen.checkFailedMsg', { err: cs.lastSyncError }),
|
||||
5000
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.4';
|
||||
showCloudFeedback(t('settings.gen.upToDateMsg', { ver: curVer }), 4500);
|
||||
return;
|
||||
}
|
||||
}
|
||||
patchText(updatePluginBtnText, t('capsule.updating'));
|
||||
showCloudFeedback(t('settings.gen.downloadingMsg'), 0);
|
||||
const res = await triggerPluginUpdate();
|
||||
if (res?.cloudStatus) {
|
||||
latestCloudStatus = res.cloudStatus;
|
||||
}
|
||||
if (res?.ok) {
|
||||
showCloudFeedback(res.message || t('settings.gen.updatedRestartMsg'), 5000);
|
||||
} else {
|
||||
showCloudFeedback(res?.message || t('settings.gen.updateSkippedMsg'), 5500);
|
||||
}
|
||||
} catch (err) {
|
||||
showCloudFeedback(err?.message || t('settings.gen.updateFailedMsg'), 5000);
|
||||
} finally {
|
||||
patchAttr(updatePluginBtn, 'disabled', false);
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('arrow-down', { size: 12 }), updatePluginBtnText]
|
||||
);
|
||||
|
||||
const cloudPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('bolt', { size: 13 }),
|
||||
updateTitleEl,
|
||||
]),
|
||||
cloudStatusMsg,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [updateModeLabelEl, autoUpdateSelect.el]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'matrix-cell' }, [
|
||||
pricingCellLabelEl,
|
||||
pricingCountVal,
|
||||
pricingSyncSub,
|
||||
]),
|
||||
h('div', { className: 'matrix-cell' }, [versionCellLabelEl, versionVal, versionSub]),
|
||||
]),
|
||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'settings-tab-stack' }, [appearancePanel, cloudPanel]);
|
||||
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
draftLanguage = normalizeI18nLanguage(settings.language);
|
||||
draftThemeAccent = normalizeClientThemeAccent(settings.themeAccent);
|
||||
draftFontScale = normalizeClientFontScale(settings.fontScale);
|
||||
draftPluginUpdateMode = normalizeClientUpdateMode(
|
||||
settings.pluginUpdateMode,
|
||||
settings.autoUpdatePlugin
|
||||
);
|
||||
|
||||
languageSwitch.setProps({
|
||||
modelValue: draftLanguage,
|
||||
options: getLanguageOptions(),
|
||||
});
|
||||
themeColorPicker.refs.setValue(draftThemeAccent);
|
||||
fontScaleSwitch.setProps({
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
options: getUpdateModeOptions(),
|
||||
});
|
||||
}
|
||||
|
||||
function renderCloudStatus(cs) {
|
||||
if (!cs) return;
|
||||
latestCloudStatus = cs;
|
||||
const srcLabel =
|
||||
cs.source === 'remote'
|
||||
? t('settings.gen.srcRemote')
|
||||
: cs.source === 'local'
|
||||
? t('settings.gen.srcLocal')
|
||||
: t('settings.gen.srcDefault');
|
||||
patchText(pricingCountVal, t('settings.gen.modelCount', { count: cs.modelCount || 0 }));
|
||||
patchText(
|
||||
pricingSyncSub,
|
||||
`${srcLabel} · ${formatCloudSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.4';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
if (cs.updateAvailable && draftPluginUpdateMode !== 'off') {
|
||||
patchText(versionSub, t('settings.gen.canUpgradeSub', { ver: latVer, mode: modeTag }));
|
||||
patchClasses(versionSub, { 'accent-ok': true });
|
||||
patchText(updatePluginBtnText, t('settings.gen.upgradeToBtn', { ver: latVer }));
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': true, 'btn-secondary': false });
|
||||
} else if (draftPluginUpdateMode === 'off') {
|
||||
patchText(versionSub, t('settings.gen.updateOffSub', { mode: modeTag }));
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(
|
||||
updatePluginBtnText,
|
||||
cs.updateAvailable
|
||||
? t('settings.gen.manualUpgradeBtn', { ver: latVer })
|
||||
: t('settings.gen.checkUpdateBtn')
|
||||
);
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
} else {
|
||||
patchText(versionSub, t('settings.gen.latestSub', { mode: modeTag }));
|
||||
patchClasses(versionSub, { 'accent-ok': false });
|
||||
patchText(updatePluginBtnText, t('settings.gen.checkUpdateBtn'));
|
||||
patchClasses(updatePluginBtn, { 'btn-primary': false, 'btn-secondary': true });
|
||||
}
|
||||
|
||||
if (
|
||||
!cloudTimer &&
|
||||
(cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))
|
||||
) {
|
||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||
}
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
patchText(appearanceTitleEl, t('settings.gen.appearanceTitle'));
|
||||
patchText(langLabelEl, t('settings.gen.language'));
|
||||
patchText(accentLabelEl, t('settings.gen.themeAccent'));
|
||||
patchText(fontLabelEl, t('settings.gen.fontScale'));
|
||||
patchText(fontHintEl, t('settings.gen.fontHint'));
|
||||
patchText(updateTitleEl, t('settings.gen.updateTitle'));
|
||||
patchText(updateModeLabelEl, t('settings.gen.updateMode'));
|
||||
patchText(pricingCellLabelEl, t('settings.gen.pricingLabel'));
|
||||
patchText(versionCellLabelEl, t('settings.gen.versionLabel'));
|
||||
if (!syncPricingBtn.hasAttribute('disabled')) {
|
||||
patchText(syncPricingBtnText, t('settings.gen.syncBtn'));
|
||||
}
|
||||
languageSwitch.setProps({
|
||||
modelValue: draftLanguage,
|
||||
options: getLanguageOptions(),
|
||||
});
|
||||
themeColorPicker.refs.refreshLabels();
|
||||
fontScaleSwitch.setProps({
|
||||
modelValue: draftFontScale,
|
||||
options: getFontScaleOptions(),
|
||||
});
|
||||
autoUpdateSelect.setProps({
|
||||
modelValue: draftPluginUpdateMode,
|
||||
options: getUpdateModeOptions(),
|
||||
});
|
||||
if (latestCloudStatus) {
|
||||
renderCloudStatus(latestCloudStatus);
|
||||
} else {
|
||||
patchText(pricingSyncSub, t('quota.loading'));
|
||||
}
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (appearanceTimer) clearTimeout(appearanceTimer);
|
||||
if (cloudTimer) clearTimeout(cloudTimer);
|
||||
languageSwitch.destroy();
|
||||
themeColorPicker.destroy();
|
||||
fontScaleSwitch.destroy();
|
||||
autoUpdateSelect.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
languageSwitch,
|
||||
themeColorPicker,
|
||||
fontScaleSwitch,
|
||||
autoUpdateSelect,
|
||||
syncPricingBtn,
|
||||
updatePluginBtn,
|
||||
renderSettings,
|
||||
renderCloudStatus,
|
||||
refreshLabels,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,480 @@
|
||||
/**
|
||||
* @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他").
|
||||
* Houses Model Identifier Formatting, Per-Model Context Windows,
|
||||
* Local Trajectory Cache Rebuild, and Two-Step Factory Preference Reset.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
normalizeClientOrchestratorIdMode,
|
||||
rebuildTrajectoryCache,
|
||||
resetAllSettings,
|
||||
saveModelContextWindow,
|
||||
saveSettingsPatch,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
|
||||
function getStepModelDisplayOptions() {
|
||||
return [
|
||||
{ value: 'short', label: t('settings.oth.modelShort') },
|
||||
{ value: 'upstream', label: t('settings.oth.modelUpstream') },
|
||||
];
|
||||
}
|
||||
|
||||
function getOrchestratorIdDisplayOptions() {
|
||||
return [
|
||||
{ value: 'compact', label: t('settings.oth.orchCompact') },
|
||||
{ value: 'full', label: t('settings.oth.orchFull') },
|
||||
];
|
||||
}
|
||||
|
||||
export const SettingsOtherTab = defineComponent({
|
||||
name: 'SettingsOtherTab',
|
||||
setup({ onCleanup, getProps }) {
|
||||
let draftShowUpstreamModel = false;
|
||||
let draftOrchestratorIdMode = 'compact';
|
||||
let latestSettings = null;
|
||||
let contextWindowModels = [];
|
||||
let contextModelId = '';
|
||||
let savingContextWindow = false;
|
||||
let contextFeedback = '';
|
||||
let modelTimer = null;
|
||||
let maintTimer = null;
|
||||
let resetConfirmTimer = null;
|
||||
let resetConfirmArmed = false;
|
||||
let isRebuilding = false;
|
||||
let isResetting = false;
|
||||
|
||||
const modelStatusText = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
const maintStatusText = h('span', {
|
||||
className: 'text-muted',
|
||||
style: 'font-size: var(--fs-md);',
|
||||
text: '',
|
||||
});
|
||||
|
||||
function showModelFeedback(text, autoClearMs = 1500) {
|
||||
if (modelTimer) {
|
||||
clearTimeout(modelTimer);
|
||||
modelTimer = null;
|
||||
}
|
||||
patchText(modelStatusText, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
modelTimer = setTimeout(() => {
|
||||
modelTimer = null;
|
||||
patchText(modelStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
function showMaintFeedback(text, autoClearMs = 2500) {
|
||||
if (maintTimer) {
|
||||
clearTimeout(maintTimer);
|
||||
maintTimer = null;
|
||||
}
|
||||
patchText(maintStatusText, text);
|
||||
if (text && autoClearMs > 0) {
|
||||
maintTimer = setTimeout(() => {
|
||||
maintTimer = null;
|
||||
patchText(maintStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Card 1: 模型标识显示 ---
|
||||
const modelCardTitleEl = h('span', { text: t('settings.oth.modelTitle') });
|
||||
const modelFormatLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.modelFormat'),
|
||||
});
|
||||
const orchFormatLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.oth.orchFormat'),
|
||||
});
|
||||
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
options: getStepModelDisplayOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextUpstream = val === 'upstream';
|
||||
draftShowUpstreamModel = nextUpstream;
|
||||
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
|
||||
showModelFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ showUpstreamModel: nextUpstream });
|
||||
showModelFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showModelFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const orchestratorIdSelect = CustomSelect({
|
||||
modelValue: 'compact',
|
||||
icon: 'layers',
|
||||
options: getOrchestratorIdDisplayOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextMode = normalizeClientOrchestratorIdMode(val);
|
||||
draftOrchestratorIdMode = nextMode;
|
||||
orchestratorIdSelect.setValue(nextMode);
|
||||
showModelFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ orchestratorIdMode: nextMode });
|
||||
showModelFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
showModelFeedback(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const modelPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
modelCardTitleEl,
|
||||
]),
|
||||
modelStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [modelFormatLabelEl, stepModelSelect.el]),
|
||||
h('div', { className: 'form-row' }, [orchFormatLabelEl, orchestratorIdSelect.el]),
|
||||
]);
|
||||
|
||||
// --- Card 2: 按模型设置上下文窗口 ---
|
||||
const baselineTitleEl = h('span', { text: t('settings.oth.baselineTitle') });
|
||||
const ctxModelLabel = h('span', { className: 'form-label' });
|
||||
const ctxWindowLabel = h('span', { className: 'form-label' });
|
||||
const ctxHint = h('span', { className: 'settings-hint-text' });
|
||||
const ctxStatus = h('span', { className: 'text-muted', role: 'status' });
|
||||
const ctxModelSelect = CustomSelect({
|
||||
className: 'settings-context-model',
|
||||
options: [],
|
||||
onUpdateModelValue: (id) => {
|
||||
if (savingContextWindow) return;
|
||||
contextModelId = id;
|
||||
contextFeedback = '';
|
||||
renderContextWindows();
|
||||
},
|
||||
});
|
||||
const ctxWindowSelect = CustomSelect({
|
||||
options: [],
|
||||
onUpdateModelValue: async (value) => {
|
||||
if (savingContextWindow || !contextModelId) return;
|
||||
savingContextWindow = true;
|
||||
contextFeedback = 'settings.saving';
|
||||
renderContextWindows();
|
||||
try {
|
||||
const modelContextWindows = await saveModelContextWindow(contextModelId, value || null);
|
||||
latestSettings = { ...latestSettings, modelContextWindows };
|
||||
contextFeedback = 'settings.saved';
|
||||
} catch {
|
||||
contextFeedback = 'settings.saveFailed';
|
||||
} finally {
|
||||
savingContextWindow = false;
|
||||
renderContextWindows();
|
||||
}
|
||||
},
|
||||
});
|
||||
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
|
||||
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
|
||||
|
||||
function renderContextWindows() {
|
||||
const saved = latestSettings?.modelContextWindows || {};
|
||||
const models = new Map(contextWindowModels.map((model) => [model.id, model]));
|
||||
const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members]));
|
||||
for (const id of Object.keys(saved)) {
|
||||
if (!knownIds.has(id)) models.set(id, { id, label: id.replace(/^model:/, ''), options: [] });
|
||||
}
|
||||
if (!models.has(contextModelId)) contextModelId = '';
|
||||
const mixed = '\u0000mixed';
|
||||
const getSelection = ({ id, members = [] }) => {
|
||||
const legacy = new Set(members.map((member) => saved[member]).filter(Boolean));
|
||||
return saved[id] || (legacy.size > 1 ? mixed : legacy.values().next().value) || '';
|
||||
};
|
||||
const formatLimit = (value) => /^\d+$/.test(value) ? t('settings.oth.ctxTokens', { count: Number(value).toLocaleString() }) : value;
|
||||
const isAvailable = (model, value) => model.options.some(({ name }) => name === value) ||
|
||||
(/^[1-9]\d*$/.test(value) && Number(value) <= model.capacity);
|
||||
const current = models.get(contextModelId);
|
||||
const options = current?.options || [];
|
||||
const selected = current ? getSelection(current) : '';
|
||||
const choices = [
|
||||
{ value: '', label: t('settings.oth.ctxDefault') },
|
||||
...options.map(({ name, expensive, tokens }) => ({
|
||||
value: name,
|
||||
label: tokens ? formatLimit(name) :
|
||||
(expensive ? t('settings.oth.ctxExpensive', { name }) : name),
|
||||
})),
|
||||
];
|
||||
if (selected && !choices.some((item) => item.value === selected)) {
|
||||
let label = t('settings.oth.ctxMixed');
|
||||
if (selected !== mixed) {
|
||||
const name = formatLimit(selected);
|
||||
label = isAvailable(current, selected) ? name : t('settings.oth.ctxUnavailable', { name });
|
||||
}
|
||||
choices.push({ value: selected, label, disabled: true });
|
||||
}
|
||||
ctxModelSelect.setProps({
|
||||
modelValue: contextModelId,
|
||||
options: [
|
||||
{ value: '', label: t('settings.oth.ctxChooseModel') },
|
||||
...[...models.values()].map((model) => {
|
||||
const value = getSelection(model);
|
||||
let meta = t('settings.oth.ctxDefault');
|
||||
if (value === mixed) meta = t('settings.oth.ctxMixed');
|
||||
else if (value) {
|
||||
const name = formatLimit(value);
|
||||
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
|
||||
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
|
||||
meta = t('settings.oth.ctxConfiguredReported', {
|
||||
name,
|
||||
reported: formatLimit(String(model.reportedLimitTokens)),
|
||||
});
|
||||
} else meta = t('settings.oth.ctxConfigured', { name });
|
||||
}
|
||||
else if (model.reportedLimitTokens) meta = t('settings.oth.ctxDefaultReported', { name: formatLimit(String(model.reportedLimitTokens)) });
|
||||
return { value: model.id, label: model.label, meta };
|
||||
}),
|
||||
],
|
||||
});
|
||||
ctxWindowSelect.setProps({ modelValue: selected, options: choices });
|
||||
patchAttr(ctxModelSelect.refs.triggerBtn, 'disabled', savingContextWindow);
|
||||
patchAttr(ctxWindowSelect.refs.triggerBtn, 'disabled', savingContextWindow || (!options.length && !selected));
|
||||
patchAttr(ctxModelSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxModel'));
|
||||
patchAttr(ctxWindowSelect.refs.triggerBtn, 'aria-label', t('settings.oth.ctxBaselineLabel'));
|
||||
patchAttr(ctxModelRow, 'hidden', !models.size);
|
||||
patchAttr(ctxWindowRow, 'hidden', !contextModelId);
|
||||
patchText(ctxModelLabel, t('settings.oth.ctxModel'));
|
||||
patchText(ctxWindowLabel, t('settings.oth.ctxBaselineLabel'));
|
||||
const hint = !models.size ? 'ctxNoModels' : selected === mixed ? 'ctxMixedHint' :
|
||||
contextModelId && !options.length ? 'ctxNoOptions' : 'ctxBaselineHint';
|
||||
const reported = current?.reportedLimitTokens;
|
||||
patchText(ctxHint, [t(`settings.oth.${hint}`), reported &&
|
||||
t('settings.oth.ctxReported', { name: formatLimit(String(reported)) })].filter(Boolean).join(' '));
|
||||
patchText(ctxStatus, contextFeedback ? t(contextFeedback) : '');
|
||||
getProps().onLayoutChange?.();
|
||||
}
|
||||
|
||||
const baselinePanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('layers', { size: 13 }),
|
||||
baselineTitleEl,
|
||||
]),
|
||||
ctxStatus,
|
||||
]),
|
||||
ctxModelRow,
|
||||
ctxWindowRow,
|
||||
h('div', { className: 'form-row' }, [ctxHint]),
|
||||
]);
|
||||
renderContextWindows();
|
||||
|
||||
// --- Card 3: 缓存与重置 ---
|
||||
const maintTitleEl = h('span', { text: t('settings.oth.maintTitle') });
|
||||
const cacheLabelEl = h('span', {
|
||||
className: 'settings-action-title',
|
||||
text: t('settings.oth.cacheLabel'),
|
||||
});
|
||||
const cacheDescEl = h('span', {
|
||||
className: 'settings-action-desc',
|
||||
text: t('settings.oth.cacheDesc'),
|
||||
});
|
||||
|
||||
const rebuildBtnText = h('span', { text: t('settings.oth.rebuildBtn') });
|
||||
const rebuildCacheBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
if (isRebuilding) return;
|
||||
isRebuilding = true;
|
||||
patchAttr(rebuildCacheBtn, 'disabled', true);
|
||||
patchText(rebuildBtnText, t('settings.oth.rebuildingBtn'));
|
||||
showMaintFeedback(t('settings.oth.rebuildingBtn'), 0);
|
||||
try {
|
||||
const res = await rebuildTrajectoryCache();
|
||||
if (res?.ok !== false) {
|
||||
showMaintFeedback(t('settings.oth.rebuildDone'), 2800);
|
||||
} else {
|
||||
showMaintFeedback(t('settings.oth.rebuildFailed'), 3000);
|
||||
}
|
||||
} catch {
|
||||
showMaintFeedback(t('settings.oth.rebuildFailed'), 3000);
|
||||
} finally {
|
||||
isRebuilding = false;
|
||||
patchAttr(rebuildCacheBtn, 'disabled', false);
|
||||
patchText(rebuildBtnText, t('settings.oth.rebuildBtn'));
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('refresh', { size: 12 }), rebuildBtnText]
|
||||
);
|
||||
|
||||
const resetLabelEl = h('span', {
|
||||
className: 'settings-action-title',
|
||||
text: t('settings.oth.resetLabel'),
|
||||
});
|
||||
const resetDescEl = h('span', {
|
||||
className: 'settings-action-desc',
|
||||
text: t('settings.oth.resetDesc'),
|
||||
});
|
||||
|
||||
const resetBtnText = h('span', { text: t('settings.oth.resetAllBtn') });
|
||||
|
||||
function disarmResetConfirm() {
|
||||
resetConfirmArmed = false;
|
||||
if (resetConfirmTimer) {
|
||||
clearTimeout(resetConfirmTimer);
|
||||
resetConfirmTimer = null;
|
||||
}
|
||||
patchClasses(resetAllBtn, { 'btn-danger-confirm': false });
|
||||
if (!isResetting) {
|
||||
patchText(resetBtnText, t('settings.oth.resetAllBtn'));
|
||||
}
|
||||
}
|
||||
|
||||
const resetAllBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: async () => {
|
||||
if (isResetting) return;
|
||||
if (!resetConfirmArmed) {
|
||||
resetConfirmArmed = true;
|
||||
patchClasses(resetAllBtn, { 'btn-danger-confirm': true });
|
||||
patchText(resetBtnText, t('settings.oth.resetConfirmBtn'));
|
||||
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
|
||||
resetConfirmTimer = setTimeout(() => {
|
||||
disarmResetConfirm();
|
||||
}, 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
disarmResetConfirm();
|
||||
isResetting = true;
|
||||
patchAttr(resetAllBtn, 'disabled', true);
|
||||
patchText(resetBtnText, t('settings.oth.resettingBtn'));
|
||||
showMaintFeedback(t('settings.oth.resettingBtn'), 0);
|
||||
try {
|
||||
const res = await resetAllSettings();
|
||||
setI18nLanguage(res?.settings?.language || 'zh-CN');
|
||||
showMaintFeedback(t('settings.oth.resetAllDone'), 2800);
|
||||
} catch {
|
||||
showMaintFeedback(t('settings.saveFailed'), 2800);
|
||||
} finally {
|
||||
isResetting = false;
|
||||
patchAttr(resetAllBtn, 'disabled', false);
|
||||
patchText(resetBtnText, t('settings.oth.resetAllBtn'));
|
||||
}
|
||||
},
|
||||
},
|
||||
[resetBtnText]
|
||||
);
|
||||
|
||||
const maintPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('refresh', { size: 13 }),
|
||||
maintTitleEl,
|
||||
]),
|
||||
maintStatusText,
|
||||
]),
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [cacheLabelEl, cacheDescEl]),
|
||||
rebuildCacheBtn,
|
||||
]),
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [resetLabelEl, resetDescEl]),
|
||||
resetAllBtn,
|
||||
]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'settings-tab-stack' }, [
|
||||
modelPanel,
|
||||
baselinePanel,
|
||||
maintPanel,
|
||||
]);
|
||||
|
||||
function renderSettings(settings, models = contextWindowModels) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
contextWindowModels = models;
|
||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftShowUpstreamModel ? 'upstream' : 'short',
|
||||
options: getStepModelDisplayOptions(),
|
||||
});
|
||||
orchestratorIdSelect.setProps({
|
||||
modelValue: draftOrchestratorIdMode,
|
||||
options: getOrchestratorIdDisplayOptions(),
|
||||
});
|
||||
renderContextWindows();
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
patchText(modelCardTitleEl, t('settings.oth.modelTitle'));
|
||||
patchText(modelFormatLabelEl, t('settings.oth.modelFormat'));
|
||||
patchText(orchFormatLabelEl, t('settings.oth.orchFormat'));
|
||||
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
|
||||
renderContextWindows();
|
||||
patchText(maintTitleEl, t('settings.oth.maintTitle'));
|
||||
patchText(cacheLabelEl, t('settings.oth.cacheLabel'));
|
||||
patchText(cacheDescEl, t('settings.oth.cacheDesc'));
|
||||
patchText(resetLabelEl, t('settings.oth.resetLabel'));
|
||||
patchText(resetDescEl, t('settings.oth.resetDesc'));
|
||||
|
||||
if (!isRebuilding) {
|
||||
patchText(rebuildBtnText, t('settings.oth.rebuildBtn'));
|
||||
}
|
||||
if (!isResetting) {
|
||||
patchText(
|
||||
resetBtnText,
|
||||
resetConfirmArmed ? t('settings.oth.resetConfirmBtn') : t('settings.oth.resetAllBtn')
|
||||
);
|
||||
}
|
||||
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftShowUpstreamModel ? 'upstream' : 'short',
|
||||
options: getStepModelDisplayOptions(),
|
||||
});
|
||||
orchestratorIdSelect.setProps({
|
||||
modelValue: draftOrchestratorIdMode,
|
||||
options: getOrchestratorIdDisplayOptions(),
|
||||
});
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
if (modelTimer) clearTimeout(modelTimer);
|
||||
if (maintTimer) clearTimeout(maintTimer);
|
||||
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
|
||||
stepModelSelect.destroy();
|
||||
orchestratorIdSelect.destroy();
|
||||
ctxModelSelect.destroy();
|
||||
ctxWindowSelect.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
stepModelSelect,
|
||||
orchestratorIdSelect,
|
||||
ctxModelSelect,
|
||||
ctxWindowSelect,
|
||||
rebuildCacheBtn,
|
||||
resetAllBtn,
|
||||
renderSettings,
|
||||
refreshLabels,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,507 @@
|
||||
/**
|
||||
* @fileoverview Preferences Tab 2: `SettingsStructureTab.js` ("结构").
|
||||
* Provides 4 collapsible customization sections with `+` / `-` / `↑` / `↓`:
|
||||
* 1. 挂载与胶囊栏 (`windowMountMode`, `showTopbarMultiSession`, `topbarCapsuleSlots` 1..5)
|
||||
* 2. 鼠标悬浮窗 (`hoverModules` 0..4)
|
||||
* 3. 实时监控布局 (`overviewModules` 1..4 + `overviewMetrics` 1..4)
|
||||
* 4. 调用明细字段 (`stepTableColumns` 2..12)
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchText } from '../../core/domPatch.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import {
|
||||
getCapsuleMetricOptions,
|
||||
getOverviewMetricOptions,
|
||||
} from '../../registries/metricRegistry.js';
|
||||
import { getStepColumnOptions } from '../../registries/stepColumnRegistry.js';
|
||||
import { getOverviewModuleOptions } from '../../registries/widgetRegistry.js';
|
||||
import {
|
||||
DEFAULT_CLIENT_HOVER_MODULES,
|
||||
DEFAULT_CLIENT_OVERVIEW_METRICS,
|
||||
DEFAULT_CLIENT_OVERVIEW_MODULES,
|
||||
DEFAULT_CLIENT_STEP_COLUMNS,
|
||||
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||
normalizeClientHoverModules,
|
||||
normalizeClientOverviewMetrics,
|
||||
normalizeClientOverviewModules,
|
||||
normalizeClientStepColumns,
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientWindowMountMode,
|
||||
saveSettingsPatch,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
|
||||
import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
|
||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../../components/ui/SegmentedControl.js';
|
||||
|
||||
function getMountModeOptions() {
|
||||
return [
|
||||
{ value: 'dual', label: t('settings.str.mountDual') },
|
||||
{ value: 'composer', label: t('settings.str.mountComposer') },
|
||||
{ value: 'sidebar', label: t('settings.str.mountSidebar') },
|
||||
];
|
||||
}
|
||||
|
||||
function getMultiToggleOptions() {
|
||||
return [
|
||||
{ value: 'show', label: t('settings.str.show') },
|
||||
{ value: 'hide', label: t('settings.str.hide') },
|
||||
];
|
||||
}
|
||||
|
||||
function isSameList(a, b) {
|
||||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export const SettingsStructureTab = defineComponent({
|
||||
name: 'SettingsStructureTab',
|
||||
setup({ props, onCleanup }) {
|
||||
let draftWindowMountMode = 'dual';
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
let draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
|
||||
let draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
|
||||
let draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
|
||||
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
let latestSettings = null;
|
||||
|
||||
async function persistStructurePatch(sectionComp, patchObj, successKey = 'settings.saved') {
|
||||
sectionComp.refs.showStatus(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch(patchObj);
|
||||
sectionComp.refs.showStatus(t(successKey), 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
sectionComp.refs.showStatus(t('settings.saveFailed'), 2500);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Section 1: 挂载与胶囊栏 (defaultExpanded: true) ---
|
||||
const mountModeLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.mountMode'),
|
||||
});
|
||||
const multiToggleLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.multiToggle'),
|
||||
});
|
||||
const capsuleSlotsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.capsuleSlotsLabel'),
|
||||
});
|
||||
|
||||
const windowMountSelect = CustomSelect({
|
||||
modelValue: draftWindowMountMode,
|
||||
icon: 'dock',
|
||||
options: getMountModeOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
const nextMode = normalizeClientWindowMountMode(val);
|
||||
draftWindowMountMode = nextMode;
|
||||
syncMountSectionMeta();
|
||||
void persistStructurePatch(mountSection, {
|
||||
windowMountMode: nextMode,
|
||||
enableWindowOverlay: nextMode !== 'sidebar',
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const multiSessionToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.multiToggle'),
|
||||
modelValue: 'show',
|
||||
options: getMultiToggleOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftShowTopbarMulti = val !== 'hide';
|
||||
syncMountSectionMeta();
|
||||
void persistStructurePatch(mountSection, {
|
||||
showTopbarMultiSession: draftShowTopbarMulti,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const topbarSlotsList = EditableSlotList({
|
||||
items: draftTopbarSlots,
|
||||
options: getCapsuleMetricOptions(),
|
||||
minItems: 1,
|
||||
maxItems: 5,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }),
|
||||
onChange: (nextItems) => {
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(nextItems);
|
||||
syncMountSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(mountSection, {
|
||||
topbarCapsuleSlots: draftTopbarSlots,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const mountSection = CollapsibleSection({
|
||||
icon: 'dock',
|
||||
title: t('settings.str.mountSection'),
|
||||
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
|
||||
defaultExpanded: true,
|
||||
onToggle: () => props.onLayoutChange?.(),
|
||||
onReset: () => {
|
||||
draftWindowMountMode = 'dual';
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
syncMountSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(
|
||||
mountSection,
|
||||
{
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
},
|
||||
'settings.resetDone'
|
||||
);
|
||||
},
|
||||
children: [
|
||||
h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
multiToggleLabelEl,
|
||||
multiSessionToggle.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [capsuleSlotsLabelEl, topbarSlotsList.el]),
|
||||
],
|
||||
});
|
||||
|
||||
function syncMountSectionMeta() {
|
||||
windowMountSelect.setProps({
|
||||
modelValue: draftWindowMountMode,
|
||||
options: getMountModeOptions(),
|
||||
});
|
||||
multiSessionToggle.setProps({
|
||||
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
});
|
||||
topbarSlotsList.refs.setProps({
|
||||
items: draftTopbarSlots,
|
||||
options: getCapsuleMetricOptions(),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addCapsuleSlot', { count, max }),
|
||||
});
|
||||
mountSection.refs.setBadge(
|
||||
t('settings.str.mountBadge', { count: draftTopbarSlots.length })
|
||||
);
|
||||
const isDefault =
|
||||
draftWindowMountMode === 'dual' &&
|
||||
draftShowTopbarMulti === true &&
|
||||
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
|
||||
mountSection.refs.setResetDisabled(isDefault);
|
||||
}
|
||||
|
||||
// --- Section 2: 鼠标悬浮窗 (0..4 items) ---
|
||||
const hoverModulesLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.hoverModulesLabel'),
|
||||
});
|
||||
|
||||
const hoverModulesList = EditableSlotList({
|
||||
items: draftHoverModules,
|
||||
options: getOverviewModuleOptions(),
|
||||
minItems: 0,
|
||||
maxItems: 4,
|
||||
emptyHintText: t('settings.str.hoverEmptyHint'),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }),
|
||||
onChange: (nextItems) => {
|
||||
draftHoverModules = normalizeClientHoverModules(nextItems);
|
||||
syncHoverSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(hoverSection, {
|
||||
hoverModules: draftHoverModules,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const hoverSection = CollapsibleSection({
|
||||
icon: 'layers',
|
||||
title: t('settings.str.hoverSection'),
|
||||
badgeText: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length }),
|
||||
defaultExpanded: false,
|
||||
onToggle: () => props.onLayoutChange?.(),
|
||||
onReset: () => {
|
||||
draftHoverModules = [...DEFAULT_CLIENT_HOVER_MODULES];
|
||||
syncHoverSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(
|
||||
hoverSection,
|
||||
{ hoverModules: [...DEFAULT_CLIENT_HOVER_MODULES] },
|
||||
'settings.resetDone'
|
||||
);
|
||||
},
|
||||
children: [h('div', { className: 'form-row' }, [hoverModulesLabelEl, hoverModulesList.el])],
|
||||
});
|
||||
|
||||
function syncHoverSectionMeta() {
|
||||
hoverModulesList.refs.setProps({
|
||||
items: draftHoverModules,
|
||||
options: getOverviewModuleOptions(),
|
||||
emptyHintText: t('settings.str.hoverEmptyHint'),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addHoverModule', { count, max }),
|
||||
});
|
||||
hoverSection.refs.setBadge(
|
||||
draftHoverModules.length === 0
|
||||
? t('settings.str.hoverBadgeOff')
|
||||
: t('settings.str.hoverBadgeCount', { count: draftHoverModules.length })
|
||||
);
|
||||
hoverSection.refs.setResetDisabled(isSameList(draftHoverModules, DEFAULT_CLIENT_HOVER_MODULES));
|
||||
}
|
||||
|
||||
// --- Section 3: 实时监控布局 (Modules 1..4 + First-Row Metrics 1..4) ---
|
||||
const overviewModulesLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.overviewModulesLabel'),
|
||||
});
|
||||
const overviewMetricsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.overviewMetricsLabel'),
|
||||
});
|
||||
const overviewMetricsHintEl = h('span', {
|
||||
className: 'settings-hint-text',
|
||||
hidden: true,
|
||||
text: t('settings.str.overviewMetricsInactiveHint'),
|
||||
});
|
||||
|
||||
const overviewModulesList = EditableSlotList({
|
||||
items: draftOverviewModules,
|
||||
options: getOverviewModuleOptions(),
|
||||
minItems: 1,
|
||||
maxItems: 4,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }),
|
||||
onChange: (nextItems) => {
|
||||
draftOverviewModules = normalizeClientOverviewModules(nextItems);
|
||||
syncOverviewSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(overviewSection, {
|
||||
overviewModules: draftOverviewModules,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const overviewMetricsList = EditableSlotList({
|
||||
items: draftOverviewMetrics,
|
||||
options: getOverviewMetricOptions(),
|
||||
minItems: 1,
|
||||
maxItems: 4,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }),
|
||||
onChange: (nextItems) => {
|
||||
draftOverviewMetrics = normalizeClientOverviewMetrics(nextItems);
|
||||
syncOverviewSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(overviewSection, {
|
||||
overviewMetrics: draftOverviewMetrics,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const overviewSection = CollapsibleSection({
|
||||
icon: 'pulse',
|
||||
title: t('settings.str.overviewSection'),
|
||||
badgeText: t('settings.str.overviewBadge', {
|
||||
modCount: draftOverviewModules.length,
|
||||
metCount: draftOverviewMetrics.length,
|
||||
}),
|
||||
defaultExpanded: false,
|
||||
onToggle: () => props.onLayoutChange?.(),
|
||||
onReset: () => {
|
||||
draftOverviewModules = [...DEFAULT_CLIENT_OVERVIEW_MODULES];
|
||||
draftOverviewMetrics = [...DEFAULT_CLIENT_OVERVIEW_METRICS];
|
||||
syncOverviewSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(
|
||||
overviewSection,
|
||||
{
|
||||
overviewModules: [...DEFAULT_CLIENT_OVERVIEW_MODULES],
|
||||
overviewMetrics: [...DEFAULT_CLIENT_OVERVIEW_METRICS],
|
||||
},
|
||||
'settings.resetDone'
|
||||
);
|
||||
},
|
||||
children: [
|
||||
h('div', { className: 'form-row' }, [overviewModulesLabelEl, overviewModulesList.el]),
|
||||
h('div', { className: 'settings-divider' }),
|
||||
h('div', { className: 'form-row' }, [
|
||||
overviewMetricsLabelEl,
|
||||
overviewMetricsHintEl,
|
||||
overviewMetricsList.el,
|
||||
]),
|
||||
],
|
||||
});
|
||||
|
||||
function syncOverviewSectionMeta() {
|
||||
overviewModulesList.refs.setProps({
|
||||
items: draftOverviewModules,
|
||||
options: getOverviewModuleOptions(),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addOverviewModule', { count, max }),
|
||||
});
|
||||
overviewMetricsList.refs.setProps({
|
||||
items: draftOverviewMetrics,
|
||||
options: getOverviewMetricOptions(),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addOverviewMetric', { count, max }),
|
||||
});
|
||||
const metricsModuleActive = draftOverviewModules.includes('metrics');
|
||||
patchAttr(overviewMetricsHintEl, 'hidden', metricsModuleActive);
|
||||
overviewSection.refs.setBadge(
|
||||
t('settings.str.overviewBadge', {
|
||||
modCount: draftOverviewModules.length,
|
||||
metCount: draftOverviewMetrics.length,
|
||||
})
|
||||
);
|
||||
const isDefault =
|
||||
isSameList(draftOverviewModules, DEFAULT_CLIENT_OVERVIEW_MODULES) &&
|
||||
isSameList(draftOverviewMetrics, DEFAULT_CLIENT_OVERVIEW_METRICS);
|
||||
overviewSection.refs.setResetDisabled(isDefault);
|
||||
}
|
||||
|
||||
// --- Section 4: 调用明细字段 (Step Table Columns 2..12) ---
|
||||
const stepColsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepsColsLabel'),
|
||||
});
|
||||
|
||||
const stepColumnsList = EditableSlotList({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
minItems: 2,
|
||||
maxItems: 12,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
onChange: (nextItems) => {
|
||||
draftStepColumns = normalizeClientStepColumns(nextItems);
|
||||
syncStepsSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(stepsSection, {
|
||||
stepTableColumns: draftStepColumns,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const stepsSection = CollapsibleSection({
|
||||
icon: 'table',
|
||||
title: t('settings.str.stepsSection'),
|
||||
badgeText: t('settings.str.stepsBadge', { count: draftStepColumns.length }),
|
||||
defaultExpanded: false,
|
||||
onToggle: () => props.onLayoutChange?.(),
|
||||
onReset: () => {
|
||||
draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
syncStepsSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(
|
||||
stepsSection,
|
||||
{ stepTableColumns: [...DEFAULT_CLIENT_STEP_COLUMNS] },
|
||||
'settings.resetDone'
|
||||
);
|
||||
},
|
||||
children: [h('div', { className: 'form-row' }, [stepColsLabelEl, stepColumnsList.el])],
|
||||
});
|
||||
|
||||
function syncStepsSectionMeta() {
|
||||
stepColumnsList.refs.setProps({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
});
|
||||
stepsSection.refs.setBadge(t('settings.str.stepsBadge', { count: draftStepColumns.length }));
|
||||
stepsSection.refs.setResetDisabled(isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS));
|
||||
}
|
||||
|
||||
const rootEl = h('div', { className: 'settings-tab-stack' }, [
|
||||
mountSection.el,
|
||||
hoverSection.el,
|
||||
overviewSection.el,
|
||||
stepsSection.el,
|
||||
]);
|
||||
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
draftWindowMountMode = normalizeClientWindowMountMode(
|
||||
settings.windowMountMode,
|
||||
settings.enableWindowOverlay
|
||||
);
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
draftHoverModules = normalizeClientHoverModules(settings.hoverModules);
|
||||
draftOverviewModules = normalizeClientOverviewModules(settings.overviewModules);
|
||||
draftOverviewMetrics = normalizeClientOverviewMetrics(settings.overviewMetrics);
|
||||
draftStepColumns = normalizeClientStepColumns(settings.stepTableColumns);
|
||||
|
||||
syncMountSectionMeta();
|
||||
syncHoverSectionMeta();
|
||||
syncOverviewSectionMeta();
|
||||
syncStepsSectionMeta();
|
||||
}
|
||||
|
||||
function refreshLabels() {
|
||||
mountSection.refs.setTitle(t('settings.str.mountSection'));
|
||||
mountSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(mountModeLabelEl, t('settings.str.mountMode'));
|
||||
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
|
||||
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
|
||||
|
||||
hoverSection.refs.setTitle(t('settings.str.hoverSection'));
|
||||
hoverSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(hoverModulesLabelEl, t('settings.str.hoverModulesLabel'));
|
||||
|
||||
overviewSection.refs.setTitle(t('settings.str.overviewSection'));
|
||||
overviewSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(overviewModulesLabelEl, t('settings.str.overviewModulesLabel'));
|
||||
patchText(overviewMetricsLabelEl, t('settings.str.overviewMetricsLabel'));
|
||||
patchText(overviewMetricsHintEl, t('settings.str.overviewMetricsInactiveHint'));
|
||||
|
||||
stepsSection.refs.setTitle(t('settings.str.stepsSection'));
|
||||
stepsSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(stepColsLabelEl, t('settings.str.stepsColsLabel'));
|
||||
|
||||
syncMountSectionMeta();
|
||||
syncHoverSectionMeta();
|
||||
syncOverviewSectionMeta();
|
||||
syncStepsSectionMeta();
|
||||
}
|
||||
|
||||
syncMountSectionMeta();
|
||||
syncHoverSectionMeta();
|
||||
syncOverviewSectionMeta();
|
||||
syncStepsSectionMeta();
|
||||
|
||||
onCleanup(() => {
|
||||
windowMountSelect.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
topbarSlotsList.destroy();
|
||||
hoverModulesList.destroy();
|
||||
overviewModulesList.destroy();
|
||||
overviewMetricsList.destroy();
|
||||
stepColumnsList.destroy();
|
||||
mountSection.destroy();
|
||||
hoverSection.destroy();
|
||||
overviewSection.destroy();
|
||||
stepsSection.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: {
|
||||
windowMountSelect,
|
||||
multiSessionToggle,
|
||||
topbarSlotsList,
|
||||
hoverModulesList,
|
||||
overviewModulesList,
|
||||
overviewMetricsList,
|
||||
stepColumnsList,
|
||||
mountSection,
|
||||
hoverSection,
|
||||
overviewSection,
|
||||
stepsSection,
|
||||
renderSettings,
|
||||
refreshLabels,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
+517
-80
File diff suppressed because it is too large
Load Diff
@@ -14,6 +14,8 @@ const DEFAULT_BUNDLED_CATALOG = {
|
||||
};
|
||||
|
||||
const BACKEND_MODULE_FILES = [
|
||||
'../backend/context-windows.mjs',
|
||||
'../backend/settings-schema.mjs',
|
||||
'../backend/config.mjs',
|
||||
'../backend/ls-discovery.mjs',
|
||||
'../backend/pricing-catalog.mjs',
|
||||
@@ -47,6 +49,7 @@ export function backendHarness({
|
||||
trajectories={},
|
||||
summaries={},
|
||||
userStatus={},
|
||||
availableModels={},
|
||||
quotaSummary={groups:[]},
|
||||
localCatalog=DEFAULT_BUNDLED_CATALOG,
|
||||
remoteCatalog=null,
|
||||
@@ -61,7 +64,7 @@ export function backendHarness({
|
||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||
const state={calls:[],errors:[],saves:[],trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||
const state={calls:[],errors:[],saves:[],settings,trajectories,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
||||
const ctx={
|
||||
...metricsImplementation, URL, AbortSignal, Buffer,
|
||||
process:{platform:'win32',env:{ANTIGRAVITY_EXECUTABLE_DATA_DIR:'/test-data',ANTIGRAVITY_LS_ADDRESS:'test.invalid',ANTIGRAVITY_CSRF_TOKEN:'test'}},
|
||||
@@ -109,7 +112,7 @@ export function backendHarness({
|
||||
const lines = m && state.transcripts?.[m[1]];
|
||||
return Array.isArray(lines) ? lines.map(x => JSON.stringify(x)).join('\n') : String(lines || '');
|
||||
}
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(settings);
|
||||
if (norm.endsWith('settings.json')) return JSON.stringify(state.settings);
|
||||
if (norm.endsWith('/antigravity/brain/.deep_stats_cache.json')) return JSON.stringify(state.deepStats);
|
||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||
@@ -120,6 +123,9 @@ export function backendHarness({
|
||||
const norm = String(p).replace(/\\/g, '/');
|
||||
const parsed = typeof s === 'string' ? JSON.parse(s) : s;
|
||||
state.saves.push({path:p,data:parsed});
|
||||
if (norm.endsWith('settings.json')) {
|
||||
state.settings = parsed;
|
||||
}
|
||||
if (norm.endsWith('remote_pricing_cache.json')) {
|
||||
state.remoteCatalog = parsed;
|
||||
}
|
||||
@@ -142,10 +148,10 @@ export function backendHarness({
|
||||
if(qs instanceof Error) throw qs;
|
||||
return {ok:true,json:async()=>({response:qs})};
|
||||
}
|
||||
const data={GetUserStatus:{userStatus:state.userStatus},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method];
|
||||
const data={GetUserStatus:{userStatus:state.userStatus},GetAvailableModels:{response:{models:availableModels}},GetAllCascadeTrajectories:{trajectorySummaries:summaries}}[method];
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,loadSettings,executeSettingsAction};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -616,6 +616,38 @@ test('trendSeries preserves 1-day-per-slot granularity for >90 day spans and rec
|
||||
assert.equal(steps[1].responseTokens, 280);
|
||||
});
|
||||
|
||||
test('cached incomplete timing is refreshed once without invalidating completed historical steps', async () => {
|
||||
const time = '2026-01-01T00:00:12Z';
|
||||
const summary = { stepCount: 1, lastModifiedTime: time, status: 'IDLE' };
|
||||
const incompleteStep = {
|
||||
...structuredClone(raw.trajectory.steps[0]),
|
||||
status: 'CORTEX_STEP_STATUS_CLEARED',
|
||||
};
|
||||
const { extractModelSteps } = await import('../speed-metrics.mjs');
|
||||
const [completed] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
||||
const [incomplete] = extractModelSteps([{ ...incompleteStep, status: 'CORTEX_STEP_STATUS_GENERATING' }]);
|
||||
const cacheEntry = (step) => ({
|
||||
signature: `v10-model-identity:1:${time}`,
|
||||
steps: [step],
|
||||
contextLimitTelemetry: true,
|
||||
subagentRefs: [],
|
||||
});
|
||||
const h = backendHarness({
|
||||
cache: { repaired: cacheEntry(incomplete), stable: cacheEntry(completed) },
|
||||
summaries: { repaired: summary, stable: summary },
|
||||
trajectories: { repaired: { trajectory: { ...raw.trajectory, steps: [incompleteStep] } } },
|
||||
});
|
||||
|
||||
for (let i = 0; i < 2; i++) {
|
||||
const result = await h.buildTelemetryPayloadInternal('repaired');
|
||||
assert.equal(result.activeConversation.latestTokPerSec, Math.round(completed.totalTokPerSec * 10) / 10);
|
||||
}
|
||||
assert.deepEqual(
|
||||
h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').map((c) => c.body.cascadeId),
|
||||
['repaired']
|
||||
);
|
||||
});
|
||||
|
||||
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
|
||||
const {
|
||||
computeLinearFit,
|
||||
@@ -768,3 +800,90 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd
|
||||
const aggMb = payload.activeConversation.aggregated.modelBreakdown;
|
||||
assert.equal(aggMb.length, 2);
|
||||
});
|
||||
|
||||
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({});
|
||||
const def = hDefault.loadSettings();
|
||||
assert.equal(def.language, 'zh-CN');
|
||||
assert.equal(def.themeAccent, 'host');
|
||||
assert.equal(def.fontScale, 'md');
|
||||
assert.equal(def.pluginUpdateMode, 'manual');
|
||||
assert.equal(def.windowMountMode, 'dual');
|
||||
assert.equal(def.enableWindowOverlay, true);
|
||||
assert.equal(def.showTopbarMultiSession, true);
|
||||
assert.deepEqual([...def.topbarCapsuleSlots], ['context', 'tps', 'quota_auto']);
|
||||
assert.deepEqual([...def.hoverModules], ['metrics', 'context', 'quotas']);
|
||||
assert.deepEqual([...def.overviewModules], ['metrics', 'context', 'quotas', 'live_tasks']);
|
||||
assert.deepEqual([...def.overviewMetrics], ['tps', 'ttft', 'avg_tps', 'step_cost']);
|
||||
assert.deepEqual([...def.stepTableColumns], ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost']);
|
||||
assert.deepEqual({ ...def.modelContextWindows }, {});
|
||||
|
||||
// 2. Legacy 3-slot ['context', 'none', 'quota_auto'] migrates cleanly to 2-item ['context', 'quota_auto']
|
||||
assert.deepEqual(
|
||||
[...hDefault.normalizeTopbarCapsuleSlots(['context', 'none', 'quota_auto'])],
|
||||
['context', 'quota_auto']
|
||||
);
|
||||
// Up to 5 unique items supported, duplicates stripped, empty falls back to ['context']
|
||||
assert.deepEqual(
|
||||
[...hDefault.normalizeTopbarCapsuleSlots(['tps', 'ttft', 'cost', 'cache_hit', 'session_tokens', 'gemini_5h'])],
|
||||
['tps', 'ttft', 'cost', 'cache_hit', 'session_tokens']
|
||||
);
|
||||
assert.deepEqual([...hDefault.normalizeTopbarCapsuleSlots(['none', 'none', 'none'])], ['context']);
|
||||
|
||||
// 3. Hover modules allow 0 items (explicit []), overviewModules & overviewMetrics require >= 1, stepTableColumns require >= 2
|
||||
assert.deepEqual([...hDefault.normalizeHoverModules([])], []);
|
||||
assert.deepEqual([...hDefault.normalizeOverviewModules([])], ['metrics']);
|
||||
assert.deepEqual([...hDefault.normalizeOverviewMetrics([])], ['tps']);
|
||||
assert.deepEqual([...hDefault.normalizeStepTableColumns(['cost'])], ['cost', 'step']);
|
||||
|
||||
// 4. Updating preferences must not apply legacy global limits or bulk model updates
|
||||
const saveRes = hDefault.executeSettingsAction({
|
||||
language: 'en-US',
|
||||
themeAccent: 'emerald',
|
||||
fontScale: 'lg',
|
||||
topbarCapsuleSlots: ['context', 'tps', 'ttft', 'cost'],
|
||||
hoverModules: ['metrics', 'context'],
|
||||
overviewModules: ['quotas', 'metrics'],
|
||||
overviewMetrics: ['avg_tps', 'cache_hit'],
|
||||
stepTableColumns: ['step', 'time', 'model', 'duration', 'input_tokens', 'output_tokens', 'cost'],
|
||||
contextLimitOverrideTokens: 128000,
|
||||
modelContextWindows: { MODEL_PLACEHOLDER_M418: '900K' },
|
||||
});
|
||||
assert.equal(saveRes.ok, true);
|
||||
assert.equal(saveRes.updated.language, 'en-US');
|
||||
assert.equal(saveRes.updated.themeAccent, 'emerald');
|
||||
assert.equal(saveRes.updated.fontScale, 'lg');
|
||||
assert.equal(saveRes.updated.topbarCapsuleSlots.length, 4);
|
||||
assert.deepEqual([...saveRes.updated.hoverModules], ['metrics', 'context']);
|
||||
assert.deepEqual([...saveRes.updated.overviewModules], ['quotas', 'metrics']);
|
||||
assert.deepEqual([...saveRes.updated.overviewMetrics], ['avg_tps', 'cache_hit']);
|
||||
assert.equal(saveRes.updated.contextLimitOverrideTokens, undefined);
|
||||
assert.deepEqual({ ...saveRes.updated.modelContextWindows }, {});
|
||||
|
||||
const hWithSteps = backendHarness({
|
||||
settings: {
|
||||
contextLimitOverrideTokens: 128000,
|
||||
modelContextWindows: { MODEL_PLACEHOLDER_M418: '900K' },
|
||||
},
|
||||
cache: { c1: old },
|
||||
trajectories: { c1: raw },
|
||||
summaries: { c1: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:10Z', status: 'IDLE' } },
|
||||
});
|
||||
const telemetry = await hWithSteps.buildTelemetryPayloadInternal('c1');
|
||||
assert.equal(telemetry.activeConversation.context.compactionLimitTokens, 256000);
|
||||
assert.equal(telemetry.activeConversation.context.limitTokens, 256000);
|
||||
|
||||
// 5. executeRebuildCacheAction clears trajectoryCache & writes empty cache object
|
||||
const rebuildRes = hWithSteps.executeRebuildCacheAction();
|
||||
assert.equal(rebuildRes.ok, true);
|
||||
const lastCacheSave = hWithSteps.state.saves[hWithSteps.state.saves.length - 1];
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(lastCacheSave.data)), {});
|
||||
|
||||
// 6. executeResetSettingsAction restores full defaults cleanly
|
||||
const resetRes = hDefault.executeResetSettingsAction();
|
||||
assert.equal(resetRes.ok, true);
|
||||
assert.equal(resetRes.updated.language, 'zh-CN');
|
||||
assert.equal(resetRes.updated.themeAccent, 'host');
|
||||
assert.deepEqual([...resetRes.updated.topbarCapsuleSlots], ['context', 'tps', 'quota_auto']);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import vm from 'node:vm';
|
||||
import { createContextWindowSyncExpression } from '../backend/context-windows.mjs';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
|
||||
const argon = 'MODEL_PLACEHOLDER_M430';
|
||||
const flash = 'MODEL_PLACEHOLDER_M431';
|
||||
const other = 'MODEL_PLACEHOLDER_M432';
|
||||
const carbon = 'MODEL_PLACEHOLDER_M427';
|
||||
const carbonLow = 'MODEL_PLACEHOLDER_M438';
|
||||
const newCarbonLow = 'MODEL_PLACEHOLDER_M439';
|
||||
const carbonGroup = 'model:gemini-4-carbon';
|
||||
const availableModels = {
|
||||
'gemini-4-carbon-high': { model: carbon, maxTokens: 1048576, maxOutputTokens: 262144 },
|
||||
'gemini-4-carbon-low': { model: carbonLow, maxTokens: 700000, maxOutputTokens: 64000 },
|
||||
'gemini-other': { model: other, maxTokens: 250000, maxOutputTokens: 64000 },
|
||||
};
|
||||
const carbonModels = [
|
||||
{ label: 'Gemini 4 Carbon (High)', modelId: 'gemini-4-carbon-high', modelOrAlias: { model: carbon } },
|
||||
{ label: 'Gemini 4 Carbon (Low)', modelId: 'gemini-4-carbon-low', modelOrAlias: { model: carbonLow } },
|
||||
];
|
||||
|
||||
test('saves and restores one model at a time using host presets or verified model capacity', async () => {
|
||||
const h = backendHarness({
|
||||
settings: { contextLimitOverrideTokens: 900000 },
|
||||
availableModels,
|
||||
userStatus: {
|
||||
cascadeModelConfigData: {
|
||||
clientModelConfigs: [
|
||||
{ label: 'Argon', modelOrAlias: { model: argon },
|
||||
contextWindowOptions: [{ name: '512K' }, { name: '900K', expensive: true }] },
|
||||
{ label: 'Flash', modelOrAlias: { model: flash }, contextWindowOptions: [{ name: '256K' }] },
|
||||
{ label: 'Other', modelOrAlias: { model: other } },
|
||||
...carbonModels,
|
||||
],
|
||||
},
|
||||
},
|
||||
});
|
||||
const update = h.executeModelContextWindowAction;
|
||||
const { contextWindowModels } = await h.buildTelemetryPayloadInternal('');
|
||||
const [argonModel, flashModel, otherModel, carbonModel] = JSON.parse(JSON.stringify(contextWindowModels));
|
||||
assert.deepEqual(argonModel.options, [{ name: '512K', expensive: false }, { name: '900K', expensive: true }]);
|
||||
assert.deepEqual(flashModel.options, [{ name: '256K', expensive: false }]);
|
||||
assert.deepEqual(otherModel.options.map(({ tokens }) => tokens), [128000, 186000]);
|
||||
assert.equal(carbonModel.id, carbonGroup);
|
||||
assert.equal(carbonModel.label, 'Gemini 4 Carbon');
|
||||
assert.deepEqual(carbonModel.members, [carbon, carbonLow]);
|
||||
assert.equal(carbonModel.options.at(-1).tokens, 636000);
|
||||
assert.equal((await update({ modelId: carbonGroup, option: '768000' })).status, 400);
|
||||
h.state.settings.modelContextWindows = { [carbon]: '768000', [carbonLow]: '256000' };
|
||||
assert.equal((await update({ modelId: carbonGroup, option: '512000' })).status, 200);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '512000' });
|
||||
assert.equal((await update({ modelId: carbonGroup, option: null })).status, 200);
|
||||
assert.equal((await update({ modelId: flash, option: '900K' })).status, 400);
|
||||
assert.equal((await update({ modelId: other, option: '900K' })).status, 400);
|
||||
assert.equal((await update({ modelId: '__proto__', option: null })).status, 400);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, {});
|
||||
|
||||
const [a, b] = await Promise.all([
|
||||
update({ modelId: argon, option: '900K' }),
|
||||
update({ modelId: flash, option: '256K' }),
|
||||
]);
|
||||
assert.equal(a.status, 200);
|
||||
assert.equal(b.status, 200);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [argon]: '900K', [flash]: '256K' });
|
||||
assert.equal((await update({ modelId: argon, option: null })).status, 200);
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [flash]: '256K' });
|
||||
h.executeResetSettingsAction();
|
||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, {});
|
||||
});
|
||||
|
||||
test('reports the latest observed threshold separately from the saved group preference', async () => {
|
||||
const h = backendHarness({
|
||||
availableModels,
|
||||
settings: { modelContextWindows: { [carbonGroup]: '512000' } },
|
||||
userStatus: { cascadeModelConfigData: { clientModelConfigs: carbonModels } },
|
||||
summaries: { active: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:01Z', status: 'IDLE' } },
|
||||
trajectories: {
|
||||
active: { trajectory: {
|
||||
steps: [{ metadata: {
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
finishedGeneratingAt: '2026-01-01T00:00:01Z',
|
||||
modelUsage: { model: carbonLow, inputTokens: 20, outputTokens: 20 },
|
||||
}, plannerResponse: { response: 'ok' } }],
|
||||
generatorMetadata: [{ stepIndices: [0], chatModel: {
|
||||
chatStartMetadata: { contextWindowMetadata: { maxContextTokens: 256000 } },
|
||||
} }],
|
||||
} },
|
||||
},
|
||||
});
|
||||
const result = await h.buildTelemetryPayloadInternal('active');
|
||||
assert.equal(result.contextWindowModels.find(({ id }) => id === carbonGroup).reportedLimitTokens, 256000);
|
||||
assert.equal(result.settings.modelContextWindows[carbonGroup], '512000');
|
||||
const previouslyCached = h.state.saves.find(({ data }) => data.active?.contextLimitTelemetry).data.active;
|
||||
const cached = structuredClone(previouslyCached);
|
||||
delete cached.contextLimitTelemetry;
|
||||
delete cached.steps[0].reportedContextLimitTokens;
|
||||
const upgraded = backendHarness({
|
||||
availableModels,
|
||||
userStatus: h.state.userStatus,
|
||||
cache: { active: cached },
|
||||
summaries: { active: { stepCount: 1, lastModifiedTime: '2026-01-01T00:00:01Z', status: 'IDLE' } },
|
||||
trajectories: h.state.trajectories,
|
||||
});
|
||||
const reloaded = await upgraded.buildTelemetryPayloadInternal('active');
|
||||
assert.equal(reloaded.contextWindowModels[0].reportedLimitTokens, 256000);
|
||||
});
|
||||
|
||||
test('host requests apply a rule only to the exact model across App and IDE transports', async () => {
|
||||
const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage';
|
||||
const statusPath = sendPath.replace('SendUserCascadeMessage', 'GetUserStatus');
|
||||
const host = 'https://127.0.0.1:25190';
|
||||
let catalog = availableModels;
|
||||
let variants = carbonModels;
|
||||
const nativeFetch = async (url, init) => {
|
||||
if (url === host + statusPath.replace('GetUserStatus', 'GetAvailableModels')) {
|
||||
return { ok: true, json: async () => ({ response: { models: catalog } }) };
|
||||
}
|
||||
if (url !== host + statusPath || init.body !== '{}') return init;
|
||||
assert.equal(init.headers['x-codeium-csrf-token'], 'local-test');
|
||||
return { ok: true, json: async () => ({ userStatus: { cascadeModelConfigData: { clientModelConfigs: [
|
||||
{ modelOrAlias: { model: argon }, contextWindowOptions: [{ name: '900K' }] },
|
||||
{ modelOrAlias: { model: flash }, contextWindowOptions: [{ name: '256K' }] },
|
||||
...variants,
|
||||
{ modelOrAlias: { model: other } },
|
||||
] } } }) };
|
||||
};
|
||||
class WebSocket {
|
||||
constructor(url) { this.url = url; }
|
||||
send(data) { return data; }
|
||||
}
|
||||
const nativeSend = WebSocket.prototype.send;
|
||||
const window = { location: new URL(host), fetch: nativeFetch, WebSocket, __APP_CONFIG__: { csrfToken: 'local-test' } };
|
||||
const context = vm.createContext({ window, URL, TextEncoder, TextDecoder, Headers, Uint8Array, AbortSignal, setTimeout, clearTimeout });
|
||||
const install = (rules, boot = 'first') => vm.runInContext(createContextWindowSyncExpression(rules, boot), context);
|
||||
const request = (model) => ({
|
||||
cascadeId: 'conversation-1',
|
||||
items: [{ text: 'Keep the request intact' }],
|
||||
cascadeConfig: {
|
||||
plannerConfig: { planModel: model },
|
||||
checkpointConfig: { maxTokenLimit: 128000, checkpointIntervalTokens: 20000 },
|
||||
},
|
||||
});
|
||||
const options = (body, type = 'application/json') => ({
|
||||
method: 'POST', headers: { 'Content-Type': type }, body,
|
||||
});
|
||||
const preferences = { [argon]: '900K', [flash]: '900K', [carbonGroup]: '512000', [other]: '512000' };
|
||||
await install(preferences);
|
||||
try {
|
||||
const payload = request(argon);
|
||||
const input = options(JSON.stringify(payload));
|
||||
const edited = JSON.parse((await window.fetch(host + sendPath, input)).body);
|
||||
assert.deepEqual(edited, {
|
||||
...payload,
|
||||
cascadeConfig: {
|
||||
...payload.cascadeConfig,
|
||||
checkpointConfig: { contextWindow: '900K', checkpointIntervalTokens: 20000 },
|
||||
},
|
||||
});
|
||||
const untouched = options(JSON.stringify(request(flash)));
|
||||
assert.equal(await window.fetch(host + sendPath, untouched), untouched);
|
||||
const lowCapacity = options(JSON.stringify(request(other)));
|
||||
assert.equal(await window.fetch(host + sendPath, lowCapacity), lowCapacity);
|
||||
const carbonPayload = request(carbon);
|
||||
carbonPayload.cascadeConfig.checkpointConfig.contextWindow = 'default';
|
||||
const carbonBody = (await window.fetch(host + sendPath, options(JSON.stringify(carbonPayload)))).body;
|
||||
assert.deepEqual(JSON.parse(carbonBody).cascadeConfig.checkpointConfig,
|
||||
{ maxTokenLimit: 512000, checkpointIntervalTokens: 20000 });
|
||||
const lowPayload = options(JSON.stringify(request(carbonLow)));
|
||||
assert.equal(JSON.parse((await window.fetch(host + sendPath, lowPayload)).body).cascadeConfig.checkpointConfig.maxTokenLimit, 512000);
|
||||
assert.equal(await window.fetch('https://127.0.0.1:25191' + sendPath, input), input);
|
||||
assert.equal(await window.fetch(host + statusPath, input), input);
|
||||
|
||||
const frame = Buffer.alloc(5 + Buffer.byteLength(input.body));
|
||||
frame.writeUInt32BE(frame.length - 5, 1);
|
||||
frame.write(input.body, 5);
|
||||
const framed = await window.fetch(host + sendPath, options(frame, 'application/grpc-web+json'));
|
||||
assert.equal(Buffer.from(framed.body).readUInt32BE(1), framed.body.length - 5);
|
||||
assert.deepEqual(JSON.parse(Buffer.from(framed.body.subarray(5)).toString()), edited);
|
||||
|
||||
const socket = new WebSocket('wss://127.0.0.1:25190/connect-websocket');
|
||||
const msg = { type: 'start', stream: false, procedure: sendPath, streamId: 'request-1', payload };
|
||||
assert.deepEqual(JSON.parse(socket.send(JSON.stringify(msg))), { ...msg, payload: edited });
|
||||
const unrelated = JSON.stringify({ ...msg, payload: request(flash) });
|
||||
assert.equal(socket.send(unrelated), unrelated);
|
||||
const external = new WebSocket('wss://127.0.0.1:25191/connect-websocket');
|
||||
assert.equal(external.send(JSON.stringify(msg)), JSON.stringify(msg));
|
||||
|
||||
const firstHook = window.fetch;
|
||||
variants = [carbonModels[0], { ...carbonModels[1], modelOrAlias: { model: newCarbonLow } }];
|
||||
catalog = { ...availableModels, 'gemini-4-carbon-low': { ...availableModels['gemini-4-carbon-low'], model: newCarbonLow } };
|
||||
await install(preferences, 'second');
|
||||
assert.notEqual(window.fetch, firstHook);
|
||||
assert.equal(await window.fetch(host + sendPath, lowPayload), lowPayload);
|
||||
window.fetch = nativeFetch;
|
||||
await install(preferences, 'second');
|
||||
const newLowPayload = options(JSON.stringify(request(newCarbonLow)));
|
||||
assert.equal(JSON.parse((await window.fetch(host + sendPath, newLowPayload)).body).cascadeConfig.checkpointConfig.maxTokenLimit, 512000);
|
||||
|
||||
catalog['gemini-4-carbon-low'] = { model: newCarbonLow, maxTokens: 300000, maxOutputTokens: 64000 };
|
||||
await install(preferences, 'third');
|
||||
assert.equal(await window.fetch(host + sendPath, newLowPayload), newLowPayload);
|
||||
assert.equal(await window.fetch(host + sendPath, options(JSON.stringify(carbonPayload))).then(({ body }) => body), JSON.stringify(carbonPayload));
|
||||
} finally {
|
||||
await install({});
|
||||
}
|
||||
assert.equal(window.fetch, nativeFetch);
|
||||
assert.equal(WebSocket.prototype.send, nativeSend);
|
||||
});
|
||||
@@ -72,6 +72,20 @@ test('unfinished, missing-completion and reversed-time requests cannot fabricate
|
||||
assert.equal(parse({total:0}).totalTokPerSec,null);
|
||||
assert.equal(parse({status:'CORTEX_STEP_STATUS_GENERATING'}).totalTokPerSec,null);
|
||||
});
|
||||
test('cleared steps with a recorded generation end retain their original request speed',()=>{
|
||||
const {s,gm}=sample({status:'CORTEX_STEP_STATUS_CLEARED'});
|
||||
s.metadata.completedAt='2026-01-01T00:04:00Z';
|
||||
const [cleared]=extractModelSteps([s],[gm]);
|
||||
assert.equal(cleared.totalDurationSec,12);
|
||||
assert.equal(cleared.totalTokPerSec,1100/12);
|
||||
assert.equal(cleared.isComplete,true);
|
||||
|
||||
for(const status of ['CORTEX_STEP_STATUS_CANCELED','CORTEX_STEP_STATUS_ERROR','CORTEX_STEP_STATUS_GENERATING']){
|
||||
assert.equal(extractModelSteps([{...s,status}],[gm])[0].totalTokPerSec,null);
|
||||
}
|
||||
delete s.metadata.finishedGeneratingAt;
|
||||
assert.equal(extractModelSteps([s],[gm])[0].totalTokPerSec,null);
|
||||
});
|
||||
test('zero output is a real zero; malformed or missing output counts cannot produce rates',()=>{
|
||||
const zero=parse({output:0,response:0,thinking:0});
|
||||
assert.equal(zero.totalTokPerSec,0);assert.equal(zero.responseTokens,0);
|
||||
|
||||
@@ -491,11 +491,24 @@ test('Capsule 4-stage responsive hysteresis and backend settings default/overrid
|
||||
settings: { topbarCapsuleSlots: ['none', 'none', 'none'] },
|
||||
});
|
||||
const allNonePayload = await allNoneEnv.buildTelemetryPayloadInternal('', false, {});
|
||||
assert.deepEqual(Array.from(allNonePayload.settings.topbarCapsuleSlots), [
|
||||
assert.deepEqual(Array.from(allNonePayload.settings.topbarCapsuleSlots), ['context']);
|
||||
|
||||
// Dynamic 5-slot configuration & hysteresis width threshold scaling (+58px per slot beyond 3)
|
||||
const fiveSlotEnv = backendHarness({
|
||||
settings: {
|
||||
topbarCapsuleSlots: ['context', 'tps', 'ttft', 'session_cost', 'claude_weekly'],
|
||||
},
|
||||
});
|
||||
const fiveSlotPayload = await fiveSlotEnv.buildTelemetryPayloadInternal('', false, {});
|
||||
assert.deepEqual(Array.from(fiveSlotPayload.settings.topbarCapsuleSlots), [
|
||||
'context',
|
||||
'none',
|
||||
'none',
|
||||
'tps',
|
||||
'ttft',
|
||||
'session_cost',
|
||||
'claude_weekly',
|
||||
]);
|
||||
assert.equal(computeCapsuleLayoutMode(340, 'wide', { slotCount: 5 }), 'compact');
|
||||
assert.equal(computeCapsuleLayoutMode(400, 'compact', { slotCount: 5 }), 'wide');
|
||||
});
|
||||
|
||||
test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, protects host reload, and supports composedPath()', async () => {
|
||||
@@ -515,6 +528,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
_vars: new Map(),
|
||||
setProperty(k, v) { this._vars.set(k, String(v)); },
|
||||
getPropertyValue(k) { return this._vars.get(k) || ''; },
|
||||
removeProperty(k) { this._vars.delete(k); },
|
||||
};
|
||||
this.dataset = {};
|
||||
this.attributes = new Map();
|
||||
@@ -732,17 +746,29 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
},
|
||||
};
|
||||
|
||||
const mockSettings = {
|
||||
weeklyLimitMode: 'official',
|
||||
weeklyTokenBudget: 150000000,
|
||||
weeklyCostBudget: 100,
|
||||
showUpstreamModel: false,
|
||||
orchestratorIdMode: 'compact',
|
||||
const defaultMockSettings = {
|
||||
language: 'zh-CN',
|
||||
themeAccent: 'host',
|
||||
fontScale: 'md',
|
||||
pluginUpdateMode: 'manual',
|
||||
autoUpdatePlugin: false,
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: ['context', 'tps', 'quota_auto'],
|
||||
hoverModules: ['metrics', 'context', 'quotas'],
|
||||
overviewModules: ['metrics', 'context', 'quotas', 'live_tasks'],
|
||||
overviewMetrics: ['tps', 'ttft', 'avg_tps', 'step_cost'],
|
||||
stepTableColumns: ['step', 'model', 'tps', 'ttft', 'tokens_combo', 'cache', 'cost'],
|
||||
showUpstreamModel: false,
|
||||
orchestratorIdMode: 'compact',
|
||||
weeklyLimitMode: 'official',
|
||||
weeklyTokenBudget: 150000000,
|
||||
weeklyCostBudget: 100,
|
||||
modelContextWindows: {},
|
||||
};
|
||||
const mockSettings = { ...defaultMockSettings };
|
||||
let cacheRebuildCalls = 0;
|
||||
|
||||
const mockWindow = {
|
||||
innerWidth: 1440,
|
||||
@@ -770,9 +796,47 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const urlStr = String(url);
|
||||
fetchedUrls.push(urlStr);
|
||||
fetchedHeaders.push(opts.headers || {});
|
||||
if (urlStr.includes('/api/settings/reset') && String(opts.method || '').toUpperCase() === 'POST') {
|
||||
for (const k of Object.keys(mockSettings)) delete mockSettings[k];
|
||||
Object.assign(mockSettings, {
|
||||
...defaultMockSettings,
|
||||
topbarCapsuleSlots: [...defaultMockSettings.topbarCapsuleSlots],
|
||||
hoverModules: [...defaultMockSettings.hoverModules],
|
||||
overviewModules: [...defaultMockSettings.overviewModules],
|
||||
overviewMetrics: [...defaultMockSettings.overviewMetrics],
|
||||
stepTableColumns: [...defaultMockSettings.stepTableColumns],
|
||||
});
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ ok: true, settings: { ...mockSettings } }),
|
||||
};
|
||||
}
|
||||
if (urlStr.includes('/api/cache/rebuild') && String(opts.method || '').toUpperCase() === 'POST') {
|
||||
cacheRebuildCalls += 1;
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ ok: true, clearedEntries: 12 }),
|
||||
};
|
||||
}
|
||||
if (urlStr.includes('/api/context-window') && opts.method === 'POST') {
|
||||
const { modelId, option } = JSON.parse(opts.body);
|
||||
const modelContextWindows = { ...mockSettings.modelContextWindows };
|
||||
if (option === null) delete modelContextWindows[modelId];
|
||||
else modelContextWindows[modelId] = option;
|
||||
mockSettings.modelContextWindows = modelContextWindows;
|
||||
return { ok: true, status: 200, json: async () => ({ modelContextWindows }) };
|
||||
}
|
||||
if (urlStr.includes('/api/settings') && String(opts.method || '').toUpperCase() === 'POST') {
|
||||
const patch = opts.body ? JSON.parse(opts.body) : {};
|
||||
Object.assign(mockSettings, patch);
|
||||
if (patch.windowMountMode !== undefined && patch.enableWindowOverlay === undefined) {
|
||||
mockSettings.enableWindowOverlay = patch.windowMountMode !== 'sidebar';
|
||||
}
|
||||
if (patch.pluginUpdateMode !== undefined && patch.autoUpdatePlugin === undefined) {
|
||||
mockSettings.autoUpdatePlugin = patch.pluginUpdateMode === 'auto';
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
@@ -785,6 +849,12 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
json: async () => ({
|
||||
uiBundleVersion: currentBundleVer,
|
||||
settings: { ...mockSettings },
|
||||
contextWindowModels: [
|
||||
{ id: 'model:gemini-4-argon', label: 'Argon', members: ['MODEL_PLACEHOLDER_M430', 'MODEL_PLACEHOLDER_M417'],
|
||||
reportedLimitTokens: 256000, options: [{ name: '512000', tokens: 512000 }] },
|
||||
{ id: 'model:gemini-3.8-flash', label: 'Flash', options: [{ name: '256K' }] },
|
||||
{ id: 'MODEL_PLACEHOLDER_M432', label: 'Other', options: [] },
|
||||
],
|
||||
cloudStatus: { updateAvailable: true, currentPluginVersion: '1.4.2', latestPluginVersion: '1.5.0' },
|
||||
account: { tierName: 'Google AI Ultra', planName: 'Pro', totalConversations: 5 },
|
||||
runningConversations: [
|
||||
@@ -1257,16 +1327,22 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(liveDotSvg.attributes.get('width'), '11', 'Enlarged live activity SVG dot size is 11');
|
||||
assert.equal(liveDotSvg.children[0].attributes.get('r'), '5', 'Enlarged dot circle radius is 5');
|
||||
assert.match(stylesCss, /\.wm-multi-dot\s*\{\s*width:\s*8px;\s*height:\s*8px;/, 'Topbar multi-session dot enlarged to 8px');
|
||||
assert.match(stylesCss, /\.wm-hover-tip\s*\{[^}]*width:\s*min\(542px,\s*calc\(100vw - 24px\)\);/, 'Hover floating card widened by 50px to 542px');
|
||||
assert.match(stylesCss, /\.wm-hover-tip\s*\{[^}]*width:\s*min\(522px,\s*calc\(100vw - 24px\)\);/, 'Hover floating card width is 522px');
|
||||
assert.equal(multiPanelEl.querySelector('.wm-recent-list'), null, 'Recent sessions list removed so panel shows online sessions only');
|
||||
assert.equal(multiPanelEl.querySelector('.panel'), null, 'Single-layer multi-session panel without nested .panel box');
|
||||
|
||||
// Verify hovering right capsule closes unpinned multi-session panel and opens rich 3-card hover overview HUD (.wm-hover-tip)
|
||||
// Verify hovering right capsule closes unpinned multi-session panel and opens decoupled 3-widget hover HUD (.wm-hover-tip)
|
||||
assert.ok(hoverTipEl, 'Hover overview HUD mounted in portal shadow root');
|
||||
assert.equal(
|
||||
hoverTipEl.children.length,
|
||||
4,
|
||||
'Hover HUD has optional update banner + 3 signature cards (matrix + context + quotas)'
|
||||
2,
|
||||
'Hover HUD has optional update banner + decoupled .wm-hover-widgets host'
|
||||
);
|
||||
const hoverWidgetsHost = hoverTipEl.querySelector('.wm-hover-widgets');
|
||||
assert.equal(
|
||||
hoverWidgetsHost.children.length,
|
||||
3,
|
||||
'Default hoverModules mounts 3 standalone widgets (metrics + context + quotas)'
|
||||
);
|
||||
assert.equal(
|
||||
multiPanelEl.querySelector('.wm-multi-empty-hint'),
|
||||
@@ -1343,152 +1419,78 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(selectRoot.classList.contains('is-open'), true, 'CustomSelect stays open via composedPath');
|
||||
selectTrigger.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
|
||||
// Verify SettingsView: weekly budget UI removed; topbar multi-session switch & 3-slot customization work live
|
||||
// Verify modular 3-tab SettingsView (常规 / 结构 / 其他) & decoupled registries
|
||||
const pillTabs = popoverEl.querySelectorAll('.pill-tab');
|
||||
pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
|
||||
const allPanes = popoverEl.querySelectorAll('.view-pane');
|
||||
const settingsPane = allPanes[allPanes.length - 1];
|
||||
assert.equal(settingsPane.querySelectorAll('.number-input').length, 0, 'Obsolete weekly budget number inputs removed');
|
||||
const settingsSelects = settingsPane.querySelectorAll('.custom-select');
|
||||
assert.equal(
|
||||
settingsSelects.length,
|
||||
7,
|
||||
'SettingsView renders 7 CustomSelect controls (mount, modelFormat, orchestratorIdFormat, 3 topbar slots, autoUpdate)'
|
||||
);
|
||||
const mountSelectEl = settingsSelects[0];
|
||||
const modelFormatSelectEl = settingsSelects[1];
|
||||
const orchestratorIdSelectEl = settingsSelects[2];
|
||||
const slot0SelectEl = settingsSelects[3];
|
||||
const slot1SelectEl = settingsSelects[4];
|
||||
const slot2SelectEl = settingsSelects[5];
|
||||
const settingsRoot = popoverEl.querySelector('.settings-view-root');
|
||||
const subNavBtns = settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn');
|
||||
assert.equal(subNavBtns.length, 3, 'SettingsView renders 3 sub-tabs: 常规 / 结构 / 其他');
|
||||
assert.equal(subNavBtns[0].textContent, '常规');
|
||||
assert.equal(subNavBtns[1].textContent, '结构');
|
||||
assert.equal(subNavBtns[2].textContent, '其他');
|
||||
const [generalPane, structurePane, otherPane] = settingsRoot.querySelectorAll('.settings-tab-stack');
|
||||
assert.equal(generalPane.hasAttribute('hidden'), false, 'General tab active by default');
|
||||
assert.equal(structurePane.hasAttribute('hidden'), true);
|
||||
assert.equal(otherPane.hasAttribute('hidden'), true);
|
||||
|
||||
// Toggle windowMountSelect: dual -> composer -> sidebar -> dual
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏'));
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
// --- Tab 0: 常规 (languageSwitch, themeAccent, fontScaleSwitch, pluginUpdateMode) ---
|
||||
const generalSegControls = generalPane.querySelectorAll('.segmented');
|
||||
assert.equal(generalSegControls.length, 2, 'General tab has Language and FontScale segmented controls');
|
||||
const langBtns = generalSegControls[0].querySelectorAll('.seg-btn');
|
||||
const fontScaleBtns = generalSegControls[1].querySelectorAll('.seg-btn');
|
||||
assert.equal(langBtns.length, 3, 'Language switch has 简体中文 / English / 跟随宿主');
|
||||
assert.equal(langBtns[0].textContent, '简体中文');
|
||||
assert.equal(langBtns[0].classList.contains('is-active'), true, 'Default language is zh-CN');
|
||||
const generalSelects = generalPane.querySelectorAll('.custom-select');
|
||||
assert.equal(generalSelects.length, 1, 'General tab has Update Mode select');
|
||||
const updateModeSelectEl = generalSelects[0];
|
||||
|
||||
// Theme accent picker: switch to emerald, verify CSS vars injected on both hosts, then restore host
|
||||
const swatchBtns = generalPane.querySelectorAll('.theme-swatch-btn');
|
||||
assert.equal(swatchBtns.length, 6, '6 curated theme swatches rendered');
|
||||
const emeraldBtn = swatchBtns.find((b) => b.getAttribute('data-accent-key') === 'emerald');
|
||||
emeraldBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.windowMountMode, 'composer', 'windowMountMode persisted as composer');
|
||||
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay stays true in composer mode');
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('输入框挂载'), 'UI reflects composer mode');
|
||||
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(mockSettings.themeAccent, 'emerald');
|
||||
assert.equal(portalHost.style.getPropertyValue('--user-accent-primary'), 'hsl(152 66% 39%)', 'Portal host gets emerald accent');
|
||||
assert.equal(capsuleHost.style.getPropertyValue('--user-accent-primary'), 'hsl(152 66% 39%)', 'Capsule host gets emerald accent');
|
||||
const hostChipBtn = generalPane.querySelector('.theme-host-chip');
|
||||
hostChipBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.windowMountMode, 'sidebar', 'windowMountMode persisted as sidebar');
|
||||
assert.equal(mockSettings.enableWindowOverlay, false, 'enableWindowOverlay persisted as false');
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('仅侧边栏'), 'UI reflects sidebar mode');
|
||||
assert.equal(mockSettings.themeAccent, 'host');
|
||||
assert.equal(portalHost.style.getPropertyValue('--user-accent-primary'), '', 'Host accent clears override');
|
||||
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
// Font scale: switch to xl (1.15), verify portalHost scales while capsuleHost NEVER scales
|
||||
assert.equal(fontScaleBtns.length, 4, 'Font scale segmented control has sm / md / lg / xl');
|
||||
fontScaleBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.windowMountMode, 'dual', 'windowMountMode persisted back to dual');
|
||||
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true');
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏'), 'UI reflects dual mode');
|
||||
|
||||
// Toggle stepModelSelect: short -> upstream -> short
|
||||
assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('精简代号'));
|
||||
modelFormatSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
modelFormatSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(mockSettings.fontScale, 'xl');
|
||||
assert.equal(portalHost.style.getPropertyValue('--ui-font-scale'), '1.15', 'Portal host scales to 1.15');
|
||||
assert.equal(capsuleHost.style.getPropertyValue('--ui-font-scale'), '', 'Capsule host strictly excludes font scale');
|
||||
assert.equal(capsuleHost.hasAttribute('data-font-scale'), false);
|
||||
fontScaleBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showUpstreamModel, true);
|
||||
assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('原始模型 ID'));
|
||||
assert.equal(mockSettings.fontScale, 'md');
|
||||
assert.equal(portalHost.style.getPropertyValue('--ui-font-scale'), '');
|
||||
assert.equal(portalHost.getAttribute('data-font-scale'), 'md');
|
||||
|
||||
modelFormatSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
modelFormatSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
// Live i18n switch: zh-CN -> en-US -> zh-CN without page reload
|
||||
langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showUpstreamModel, false);
|
||||
assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('精简代号'));
|
||||
|
||||
// Toggle orchestratorIdSelect: compact -> full -> compact
|
||||
assert.ok(orchestratorIdSelectEl.querySelector('.select-label').textContent.includes('精简代号'));
|
||||
orchestratorIdSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
orchestratorIdSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(mockSettings.language, 'en-US');
|
||||
assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, 'Live');
|
||||
assert.equal(pillTabs[3].querySelector('.pill-tab-label').textContent, 'Settings');
|
||||
assert.equal(subNavBtns[0].textContent, 'General');
|
||||
assert.equal(subNavBtns[1].textContent, 'Structure');
|
||||
assert.equal(subNavBtns[2].textContent, 'Other');
|
||||
langBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.orchestratorIdMode, 'full');
|
||||
assert.ok(orchestratorIdSelectEl.querySelector('.select-label').textContent.includes('原始完整 ID'));
|
||||
|
||||
orchestratorIdSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
orchestratorIdSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.orchestratorIdMode, 'compact');
|
||||
assert.ok(orchestratorIdSelectEl.querySelector('.select-label').textContent.includes('精简代号'));
|
||||
|
||||
// Toggle topbar multi-session switch: show -> hide -> show
|
||||
const topbarSegBtns = settingsPane.querySelectorAll('.seg-btn');
|
||||
assert.equal(topbarSegBtns.length, 2, 'Topbar multi-session toggle has 显示 / 隐藏 buttons');
|
||||
topbarSegBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showTopbarMultiSession, false);
|
||||
assert.equal(multiBtn.hasAttribute('hidden'), true, 'Topbar multi-session button hidden immediately');
|
||||
assert.equal(capsuleHost.getAttribute('data-multi'), 'off');
|
||||
|
||||
topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showTopbarMultiSession, true);
|
||||
assert.equal(multiBtn.hasAttribute('hidden'), false, 'Topbar multi-session button restored immediately');
|
||||
|
||||
// Customize 3 topbar capsule slots: [gemini_5h, ttft, cost], then swap order, test claude_weekly + none, then reset default
|
||||
const capSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot');
|
||||
const capSeps = capsuleHost.shadowRoot.querySelectorAll('.wm-sep');
|
||||
assert.equal(capSlots.length, 3);
|
||||
assert.equal(capSeps.length, 2);
|
||||
|
||||
// Slot 0 -> Gemini 5h (option index 5)
|
||||
slot0SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
slot0SelectEl.querySelectorAll('.select-option')[5].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h');
|
||||
assert.equal(capSlots[0].children.length, 1, 'Ring SVG detached cleanly when slot leaves context');
|
||||
assert.equal(capSlots[0].children[0].textContent, '余 44%');
|
||||
|
||||
// Slot 1 -> TTFT (option index 2)
|
||||
slot1SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
slot1SelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft');
|
||||
assert.equal(capSlots[1].children[0].textContent, '0.85s');
|
||||
|
||||
// Slot 2 -> Cost (option index 3)
|
||||
slot2SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
slot2SelectEl.querySelectorAll('.select-option')[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[2].getAttribute('data-metric'), 'cost');
|
||||
assert.equal(capSlots[2].children[0].textContent, '$0.040');
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']);
|
||||
|
||||
// Swap Slot 1 up (left) so order becomes ['ttft', 'gemini_5h', 'cost']
|
||||
const slotMoveBtns = settingsPane.querySelectorAll('.slot-move-btn');
|
||||
// Row 1 up button is index 2 ([row0Up, row0Down, row1Up, row1Down, row2Up, row2Down])
|
||||
slotMoveBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']);
|
||||
assert.equal(capSlots[0].children[0].textContent, '0.85s');
|
||||
assert.equal(capSlots[1].children[0].textContent, '余 44%');
|
||||
|
||||
// Test hiding middle slot ('none', option index 9) and setting Slot 2 to Claude Weekly (option index 8)
|
||||
slot1SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
slot1SelectEl.querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
slot2SelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
slot2SelectEl.querySelectorAll('.select-option')[8].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[1].hasAttribute('hidden'), true, 'Middle slot hidden when set to none');
|
||||
assert.equal(capSeps[0].hasAttribute('hidden'), true, 'Separator before hidden middle slot collapses');
|
||||
assert.equal(capSeps[1].hasAttribute('hidden'), false, 'Single separator remains between Slot 0 and Slot 2');
|
||||
assert.equal(capSeps[1].getAttribute('data-sep-for-rank'), '2');
|
||||
assert.equal(capSlots[2].getAttribute('data-vis-rank'), '2');
|
||||
assert.equal(capSlots[2].children[0].textContent, '余 91%');
|
||||
|
||||
// Reset default restores ['context', 'tps', 'quota_auto'] with ring SVG re-attached on Slot 0
|
||||
const resetTopbarBtn = settingsPane.querySelector('.btn-ghost-sm');
|
||||
resetTopbarBtn.dispatchEvent({ type: 'click' });
|
||||
await new Promise((r) => setTimeout(r, 260));
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['context', 'tps', 'quota_auto']);
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'context');
|
||||
assert.equal(capSlots[0].children.length, 2, 'Ring SVG re-attached on Slot 0');
|
||||
assert.equal(capSlots[0].querySelector('.wm-ctx-pct').textContent, '50%');
|
||||
assert.equal(mockSettings.language, 'zh-CN');
|
||||
assert.equal(pillTabs[0].querySelector('.pill-tab-label').textContent, '实时监控');
|
||||
assert.equal(subNavBtns[0].textContent, '常规');
|
||||
|
||||
// Verify 3-tier update mode select (manual default -> off hides topbar/hover prompts -> auto -> manual)
|
||||
const topbarUpdateBtn = capsuleHost.shadowRoot.querySelector('.wm-update-btn');
|
||||
@@ -1520,7 +1522,6 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
);
|
||||
assert.equal(headerUpdateBtn.hasAttribute('hidden'), false);
|
||||
|
||||
const updateModeSelectEl = settingsSelects[6];
|
||||
assert.equal(updateModeSelectEl.querySelector('.select-label').textContent, '仅提示新版本,手动更新');
|
||||
updateModeSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
const updateOpts = updateModeSelectEl.querySelectorAll('.select-option');
|
||||
@@ -1551,6 +1552,271 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(mockSettings.autoUpdatePlugin, false);
|
||||
assert.equal(topbarUpdateBtn.hasAttribute('hidden'), false, 'Topbar update pill visible when mode=manual');
|
||||
|
||||
// --- Tab 1: 结构 (4 accordion sections: capsule 1..5, hover 0..4, overview 1..4 + 1..4, step columns 2..12) ---
|
||||
subNavBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
assert.equal(structurePane.hasAttribute('hidden'), false);
|
||||
const accordionSections = structurePane.querySelectorAll('.collapsible-section');
|
||||
assert.equal(accordionSections.length, 4, 'Structure tab has 4 collapsible sections');
|
||||
assert.equal(accordionSections[0].classList.contains('is-expanded'), true, 'Section 1 expanded by default');
|
||||
assert.equal(accordionSections[1].classList.contains('is-expanded'), false, 'Section 2 collapsed by default');
|
||||
|
||||
const sec0 = accordionSections[0];
|
||||
const mountSelectEl = sec0.querySelectorAll('.custom-select')[0];
|
||||
|
||||
// Toggle windowMountSelect: dual -> composer -> sidebar -> dual
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('顶部栏 + 侧边栏'));
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.windowMountMode, 'composer', 'windowMountMode persisted as composer');
|
||||
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay stays true in composer mode');
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('输入框挂载'), 'UI reflects composer mode');
|
||||
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.windowMountMode, 'sidebar', 'windowMountMode persisted as sidebar');
|
||||
assert.equal(mockSettings.enableWindowOverlay, false, 'enableWindowOverlay persisted as false');
|
||||
assert.ok(mountSelectEl.querySelector('.select-label').textContent.includes('仅侧边栏'), 'UI reflects sidebar mode');
|
||||
|
||||
// Re-open popover after sidebar closed it and switch back to dual
|
||||
ov.open();
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.windowMountMode, 'dual', 'windowMountMode persisted back to dual');
|
||||
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true');
|
||||
|
||||
// Toggle topbar multi-session switch: show -> hide -> show
|
||||
const topbarSegBtns = sec0.querySelectorAll('.seg-btn');
|
||||
assert.equal(topbarSegBtns.length, 2, 'Topbar multi-session toggle has 显示 / 隐藏 buttons');
|
||||
topbarSegBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showTopbarMultiSession, false);
|
||||
assert.equal(multiBtn.hasAttribute('hidden'), true, 'Topbar multi-session button hidden immediately');
|
||||
assert.equal(capsuleHost.getAttribute('data-multi'), 'off');
|
||||
topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showTopbarMultiSession, true);
|
||||
assert.equal(multiBtn.hasAttribute('hidden'), false, 'Topbar multi-session button restored immediately');
|
||||
|
||||
// Dynamic 1..5 capsule slots via EditableSlotList (+ / - / ↑ / ↓)
|
||||
const capSlots = capsuleHost.shadowRoot.querySelectorAll('.wm-cap-slot');
|
||||
const capSeps = capsuleHost.shadowRoot.querySelectorAll('.wm-sep');
|
||||
assert.equal(capSlots.length, 5, '5 capsule slot nodes pre-reserved');
|
||||
assert.equal(capSeps.length, 4, '4 capsule separators pre-reserved');
|
||||
assert.equal(capSlots[3].hasAttribute('hidden'), true, 'Slot 4 hidden by default (3 slots)');
|
||||
assert.equal(capSlots[4].hasAttribute('hidden'), true, 'Slot 5 hidden by default (3 slots)');
|
||||
|
||||
const capSlotWrap = sec0.querySelector('.editable-slot-wrap');
|
||||
let capRowSelects = capSlotWrap.querySelectorAll('.custom-select');
|
||||
assert.equal(capRowSelects.length, 3, 'Default 3 capsule slot rows in EditableSlotList');
|
||||
|
||||
// Slot 0 -> Gemini 5h (index 9), Slot 1 -> TTFT (index 2), Slot 2 -> Cost (index 4)
|
||||
capRowSelects[0].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
capRowSelects[0].querySelectorAll('.select-option')[9].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'gemini_5h');
|
||||
assert.equal(capSlots[0].children.length, 1, 'Ring SVG detached cleanly when slot leaves context');
|
||||
assert.equal(capSlots[0].children[0].textContent, '余 44%');
|
||||
|
||||
capRowSelects[1].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
capRowSelects[1].querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[1].getAttribute('data-metric'), 'ttft');
|
||||
assert.equal(capSlots[1].children[0].textContent, '0.85s');
|
||||
|
||||
capRowSelects[2].querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
capRowSelects[2].querySelectorAll('.select-option')[4].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(capSlots[2].getAttribute('data-metric'), 'cost');
|
||||
assert.equal(capSlots[2].children[0].textContent, '$0.040');
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['gemini_5h', 'ttft', 'cost']);
|
||||
|
||||
// Move Row 1 up (left): each row has [up, down, remove], so Row 1 up is index 3
|
||||
capSlotWrap.querySelectorAll('.slot-move-btn')[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['ttft', 'gemini_5h', 'cost']);
|
||||
assert.equal(capSlots[0].children[0].textContent, '0.85s');
|
||||
assert.equal(capSlots[1].children[0].textContent, '余 44%');
|
||||
|
||||
// Click `+ 添加指标` twice to expand from 3 -> 5 slots
|
||||
const capAddBtn = capSlotWrap.querySelector('.slot-add-btn');
|
||||
capAddBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
capAddBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.topbarCapsuleSlots.length, 5, 'Expanded to maximum 5 capsule slots');
|
||||
assert.equal(capAddBtn.hasAttribute('disabled'), true, '+ button disabled at max 5 slots');
|
||||
assert.equal(capSlots[3].hasAttribute('hidden'), false, 'Slot 4 now visible');
|
||||
assert.equal(capSlots[4].hasAttribute('hidden'), false, 'Slot 5 now visible');
|
||||
assert.equal(capSeps[3].hasAttribute('hidden'), false, 'Separator 4 now visible');
|
||||
|
||||
// Remove down to 1 slot using `-` button, verifying min=1 protection
|
||||
for (let r = 0; r < 4; r += 1) {
|
||||
const remBtns = capSlotWrap.querySelectorAll('.slot-remove-btn');
|
||||
remBtns[remBtns.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
}
|
||||
assert.equal(mockSettings.topbarCapsuleSlots.length, 1, 'Shrunk to minimum 1 capsule slot');
|
||||
assert.equal(capSlotWrap.querySelector('.slot-remove-btn').hasAttribute('disabled'), true, '- button disabled at min 1 slot');
|
||||
assert.equal(capSeps[0].hasAttribute('hidden'), true, 'All separators hidden when 1 slot');
|
||||
|
||||
// Reset Section 0 restores default 3 slots ['context', 'tps', 'quota_auto']
|
||||
sec0.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.deepEqual(mockSettings.topbarCapsuleSlots, ['context', 'tps', 'quota_auto']);
|
||||
assert.equal(capSlots[0].getAttribute('data-metric'), 'context');
|
||||
assert.equal(capSlots[0].children.length, 2, 'Ring SVG re-attached on Slot 0');
|
||||
assert.equal(capSlots[0].querySelector('.wm-ctx-pct').textContent, '50%');
|
||||
|
||||
// Section 1: Hover Popup Modules (0..4) — removing all 3 suppresses hover popup while click popover still works
|
||||
const sec1 = accordionSections[1];
|
||||
sec1.querySelector('.collapsible-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
const hoverSlotWrap = sec1.querySelector('.editable-slot-wrap');
|
||||
for (let r = 0; r < 3; r += 1) {
|
||||
const remBtns = hoverSlotWrap.querySelectorAll('.slot-remove-btn');
|
||||
remBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
}
|
||||
assert.deepEqual(mockSettings.hoverModules, [], 'Hover modules emptied to 0 items');
|
||||
assert.equal(hoverSlotWrap.querySelector('.editable-slot-empty').hasAttribute('hidden'), false, '0-module empty hint visible');
|
||||
// Temporarily set pluginUpdateMode=off via Settings UI so update banner is also absent, then close popover and hover capsuleBtn
|
||||
updateModeSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
updateModeSelectEl.querySelectorAll('.select-option')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
ov.close();
|
||||
capsuleBtn.dispatchEvent({ type: 'mouseenter', clientX: 960, clientY: 18 });
|
||||
assert.equal(ov.isHoverOpen(), false, 'Hover popup stays suppressed when hoverModules=[] and no update banner');
|
||||
// Click popover still opens cleanly!
|
||||
capsuleBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(ov.isOpen(), true, 'Click full monitor popover still opens when hoverModules=[]');
|
||||
updateModeSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
updateModeSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
sec1.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.deepEqual(mockSettings.hoverModules, ['metrics', 'context', 'quotas']);
|
||||
|
||||
// Section 2: Live Overview Layout (overviewModules 1..4 + overviewMetrics 1..4)
|
||||
const sec2 = accordionSections[2];
|
||||
sec2.querySelector('.collapsible-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
const [ovModWrap, ovMetricWrap] = sec2.querySelectorAll('.editable-slot-wrap');
|
||||
// Move row 2 ('quotas') up above 'context' -> ['metrics', 'quotas', 'context', 'live_tasks']
|
||||
ovModWrap.querySelectorAll('.slot-move-btn')[6].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(mockSettings.overviewModules, ['metrics', 'quotas', 'context', 'live_tasks']);
|
||||
// Remove 2 metrics from first-row matrix -> 2 columns ['tps', 'ttft']
|
||||
ovMetricWrap.querySelectorAll('.slot-remove-btn')[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
ovMetricWrap.querySelectorAll('.slot-remove-btn')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.deepEqual(mockSettings.overviewMetrics, ['tps', 'ttft']);
|
||||
pillTabs[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
const overviewHostEl = allPanes[0].querySelector('.overview-modules-host');
|
||||
assert.equal(overviewHostEl.children[0].getAttribute('data-cols'), '2', 'MetricMatrixWidget adapts to 2 columns');
|
||||
assert.ok(
|
||||
overviewHostEl.children[1].querySelector('.panel-title').children[1].textContent.includes('可用额度'),
|
||||
'QuotaPoolsWidget moved above ContextWindowWidget in LiveOverviewView'
|
||||
);
|
||||
pillTabs[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
sec2.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.deepEqual(mockSettings.overviewModules, ['metrics', 'context', 'quotas', 'live_tasks']);
|
||||
assert.deepEqual(mockSettings.overviewMetrics, ['tps', 'ttft', 'avg_tps', 'step_cost']);
|
||||
|
||||
// Section 3: Step Table Columns (2..12) — add optional 'time' and 'duration' columns
|
||||
const sec3 = accordionSections[3];
|
||||
sec3.querySelector('.collapsible-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
const stepColWrap = sec3.querySelector('.editable-slot-wrap');
|
||||
stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
stepColWrap.querySelector('.slot-add-btn').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
assert.equal(mockSettings.stepTableColumns.length, 9, 'Added time and duration columns (7 -> 9)');
|
||||
pillTabs[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
const stepHeaderThs = allPanes[2].querySelector('.data-table').children[0].children[0].children;
|
||||
assert.equal(stepHeaderThs.length, 9, 'StepsDetailView thead dynamically renders 9 columns');
|
||||
pillTabs[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
sec3.querySelector('.btn-ghost-sm').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
assert.equal(mockSettings.stepTableColumns.length, 7);
|
||||
|
||||
// --- Tab 2: 其他 (modelFormat, orchestratorId, contextBaseline reserved pill, cache rebuild, reset all) ---
|
||||
subNavBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
assert.equal(otherPane.hasAttribute('hidden'), false);
|
||||
const otherSelects = otherPane.querySelectorAll('.custom-select');
|
||||
assert.equal(otherSelects.length, 4);
|
||||
const modelFormatSelectEl = otherSelects[0];
|
||||
const orchestratorIdSelectEl = otherSelects[1];
|
||||
|
||||
// Toggle stepModelSelect: short -> upstream -> short
|
||||
assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('精简代号'));
|
||||
modelFormatSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
modelFormatSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showUpstreamModel, true);
|
||||
assert.ok(modelFormatSelectEl.querySelector('.select-label').textContent.includes('原始模型 ID'));
|
||||
modelFormatSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
modelFormatSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.showUpstreamModel, false);
|
||||
|
||||
// Toggle orchestratorIdSelect: compact -> full
|
||||
assert.ok(orchestratorIdSelectEl.querySelector('.select-label').textContent.includes('精简代号'));
|
||||
orchestratorIdSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
orchestratorIdSelectEl.querySelectorAll('.select-option')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.orchestratorIdMode, 'full');
|
||||
assert.ok(orchestratorIdSelectEl.querySelector('.select-label').textContent.includes('原始完整 ID'));
|
||||
|
||||
const [contextModel, contextWindow] = otherSelects.slice(2);
|
||||
const selectOption = (select, index) => {
|
||||
select.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
select.querySelectorAll('.select-option')[index].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
};
|
||||
assert.equal(contextWindow.parentNode.hasAttribute('hidden'), true);
|
||||
contextModel.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.match(contextModel.querySelectorAll('.select-option')[1].querySelector('.select-option-meta').textContent, /默认.*256,000/);
|
||||
contextModel.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
selectOption(contextModel, 1);
|
||||
selectOption(contextWindow, 1);
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(mockSettings.modelContextWindows, { 'model:gemini-4-argon': '512000' });
|
||||
contextModel.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.match(contextModel.querySelectorAll('.select-option')[1].querySelector('.select-option-meta').textContent, /512,000.*已设置/);
|
||||
contextModel.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
selectOption(contextModel, 2);
|
||||
assert.equal(contextWindow.querySelector('.select-label').textContent, '跟随宿主设置');
|
||||
selectOption(contextWindow, 1);
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
selectOption(contextModel, 1);
|
||||
selectOption(contextWindow, 0);
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.deepEqual(mockSettings.modelContextWindows, { 'model:gemini-3.8-flash': '256K' });
|
||||
selectOption(contextModel, 3);
|
||||
assert.equal(contextWindow.querySelector('.select-trigger').hasAttribute('disabled'), true);
|
||||
|
||||
const maintBtns = otherPane.querySelectorAll('.btn-secondary');
|
||||
const rebuildBtn = maintBtns[0];
|
||||
const resetAllBtn = maintBtns[1];
|
||||
rebuildBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(cacheRebuildCalls, 1, 'POST /api/cache/rebuild invoked cleanly');
|
||||
|
||||
// Two-step confirm for Reset All Settings: 1st click arms confirm, 2nd click resets all settings
|
||||
resetAllBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
assert.equal(resetAllBtn.classList.contains('btn-danger-confirm'), true, '1st click arms confirmation state');
|
||||
assert.equal(mockSettings.orchestratorIdMode, 'full', 'Not yet reset on 1st click');
|
||||
resetAllBtn.dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 260));
|
||||
assert.equal(mockSettings.orchestratorIdMode, 'compact', '2nd click resets orchestratorIdMode to default');
|
||||
|
||||
// Verify ConsumptionView omits "+ 待定" / "3993 步费用待定" and StepsDetailView protects header title
|
||||
pillTabs[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
@@ -2125,9 +2391,20 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
jetskiObj.globalThis = jetskiObj;
|
||||
const jetskiVm = vm.createContext(jetskiObj);
|
||||
|
||||
const modelId = 'MODEL_PLACEHOLDER_M430';
|
||||
const chat = {
|
||||
location: new URL('http://127.0.0.1:50234/?extensionView=true'),
|
||||
__APP_CONFIG__: { csrfToken: 'chat-test' },
|
||||
fetch: async () => ({ ok: true, json: async () => ({ userStatus: { cascadeModelConfigData: {
|
||||
clientModelConfigs: [{ modelOrAlias: { model: modelId }, contextWindowOptions: [{ name: '900K' }] }],
|
||||
} } }) }),
|
||||
};
|
||||
chat.window = chat;
|
||||
const chatVm = vm.createContext({ ...chat, window: chat, TextEncoder, TextDecoder, AbortSignal, setTimeout, clearTimeout });
|
||||
const vmMap = new Map([
|
||||
['ide-main', ideVm],
|
||||
['ide-jetski', jetskiVm],
|
||||
['ide-chat', chatVm],
|
||||
]);
|
||||
|
||||
class MockIdeWebSocket {
|
||||
@@ -2145,9 +2422,9 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
if (msg.method === 'Runtime.evaluate') {
|
||||
const ctx = vmMap.get(this.targetId);
|
||||
const value = vm.runInContext(msg.params.expression, ctx);
|
||||
queueMicrotask(() =>
|
||||
Promise.resolve(value).then((result) =>
|
||||
this._emit('message', {
|
||||
data: JSON.stringify({ id: msg.id, result: { result: { value } } }),
|
||||
data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }),
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -2165,6 +2442,7 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
res.end(
|
||||
JSON.stringify([
|
||||
{
|
||||
id: 'ide-main',
|
||||
type: 'page',
|
||||
url: 'vscode-file://vscode-app/c:/Program%20Files/Antigravity%20IDE/resources/app/out/vs/code/electron-browser/workbench/workbench.html',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/ide-main`,
|
||||
@@ -2179,6 +2457,12 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
url: 'vscode-file://vscode-app/c:/Program%20Files/Antigravity%20IDE/resources/app/out/vs/code/electron-browser/sharedProcess/sharedProcess.html',
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/shared`,
|
||||
},
|
||||
{
|
||||
type: 'iframe',
|
||||
parentId: 'ide-main',
|
||||
url: chat.location.href,
|
||||
webSocketDebuggerUrl: `ws://127.0.0.1:${p}/devtools/page/ide-chat`,
|
||||
},
|
||||
])
|
||||
);
|
||||
return;
|
||||
@@ -2195,6 +2479,7 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
);
|
||||
|
||||
const prefetchedConvIds = [];
|
||||
const settings = { enableWindowOverlay: true, modelContextWindows: { [modelId]: '900K' } };
|
||||
const mockAppJs = `
|
||||
(() => {
|
||||
const br = window.__AGUsageMonitorBridge;
|
||||
@@ -2215,7 +2500,7 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
return { status: 200, contentType: 'application/json', body: JSON.stringify({ ok: true }) };
|
||||
},
|
||||
readAssetFn: async (rel) => (rel === 'styles.css' ? ':host{}' : mockAppJs),
|
||||
getSettingsFn: () => ({ enableWindowOverlay: true }),
|
||||
getSettingsFn: () => settings,
|
||||
getBundleVersionFn: () => 'ide-v1',
|
||||
env: { APPDATA: roamingDir, LOCALAPPDATA: localDir },
|
||||
platform: 'win32',
|
||||
@@ -2228,6 +2513,8 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
assert.equal(syncRes.ok, true, 'Stale 2.0 port did not block live Antigravity IDE port');
|
||||
assert.equal(syncRes.targets, 2, 'Matched workbench.html and workbench-jetski-agent.html while excluding sharedProcess.html');
|
||||
assert.equal(syncRes.injected, 2);
|
||||
assert.equal(chat.__AGUsageMonitorContextWindows?.rules[modelId], '900K');
|
||||
assert.equal(ideContextObj.__AGUsageMonitorContextWindows, undefined);
|
||||
assert.ok(
|
||||
prefetchedConvIds.includes('99999999-aaaa-bbbb-cccc-888888888888'),
|
||||
'Initial telemetry prefetch extracted active IDE conversation UUID from DOM'
|
||||
@@ -2242,6 +2529,10 @@ test('Multi-port CDP discovery tolerates stale 2.0 DevToolsActivePort while inje
|
||||
},
|
||||
});
|
||||
assert.equal(ideOriginRes.status, 200);
|
||||
|
||||
settings.modelContextWindows = {};
|
||||
await controller.syncAllWindows();
|
||||
assert.equal(chat.__AGUsageMonitorContextWindows, undefined);
|
||||
} finally {
|
||||
await controller.stop({ disposeWindows: true });
|
||||
await new Promise((resolve) => ideCdpServer.close(resolve));
|
||||
@@ -3353,13 +3644,14 @@ test('Composer mount mode (输入框挂载) docks capsule immediately left of Au
|
||||
const popTop = parseInt(popoverEl.style.top, 10);
|
||||
assert.ok(Number.isFinite(popTop) && popTop < 810 - 200, `Popover opens above composer (top=${popTop})`);
|
||||
|
||||
// 4. Live hot-switch inside SettingsView from composer -> dual moves capsule back to topbar immediately
|
||||
// 4. Live hot-switch inside SettingsView (结构 sub-tab) from composer -> dual moves capsule back to topbar immediately
|
||||
const pillTabs = popoverEl.querySelectorAll('.pill-tab');
|
||||
pillTabs[pillTabs.length - 1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 15));
|
||||
const allPanes = popoverEl.querySelectorAll('.view-pane');
|
||||
const settingsPane = allPanes[allPanes.length - 1];
|
||||
const mountSelectEl = settingsPane.querySelectorAll('.custom-select')[0];
|
||||
const settingsRoot = popoverEl.querySelector('.settings-view-root');
|
||||
settingsRoot.querySelector('.settings-subnav-bar').querySelectorAll('.seg-btn')[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
const structurePane = settingsRoot.querySelectorAll('.settings-tab-stack')[1];
|
||||
const mountSelectEl = structurePane.querySelectorAll('.custom-select')[0];
|
||||
mountSelectEl.querySelector('.select-trigger').dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
mountSelectEl.querySelectorAll('.select-option')[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
|
||||
Reference in New Issue
Block a user