mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): add worker hot-reload, sticky bridge lease, custom token combos, trimmed model IDs, and adaptive popover width
- Isolate SidecarApp /api/* backend runtime inside a hot-swappable Worker thread (sidecar-worker.mjs) with 3s disk-drift detection and queued request handoff so live plugin updates never drop the host-assigned SidecarApp port - Persist and reuse sticky loopback bridge port/token leases across bridge-daemon and worker reloads, pre-bind the bridge server on boot, allow /api/cache/rebuild on the bridge, and self-heal poisoned CDP fallback states back to HTTP - Add billing-aligned In / Out / Cache (tokens_io_cache) preset with per-segment USD hover breakdown and custom format DSL (tokens_custom + stepTokenComboFormat, e.g. context:new:cache, in:out:cache) - Add 3-way model name format (short / upstream / upstream_compact) stripping gemini-, claude-, and gpt- prefixes while protecting compaction suffixes from ellipsis truncation - Add adaptive content-fit popover width (auto up to viewport bounds on wide step tables) alongside custom fixed width (440-1080 px)
This commit is contained in:
@@ -49,10 +49,10 @@ The dashboard is organized into four tabs, with a top header to switch conversat
|
||||
- **By Step**: Lists every step in the selected conversation with its model, TPS, TTFT, context/output tokens, cache hit rate, and step cost.
|
||||
- **By Model**: Aggregates call counts, mean speed, total tokens, and cost per model within the current session and selected agent scope.
|
||||
- **Preferences**
|
||||
- **Mount Mode**: Dual-mount (Top Bar + Sidebar) or Sidebar only.
|
||||
- **Mount Mode & Popover Width**: Choose Dual-mount (Top Bar + Sidebar), Composer mount, or Sidebar only; the floating popover defaults to **Auto Fit** (expanding automatically on wide step tables within viewport bounds to avoid horizontal scrolling) or accepts a custom fixed width (`440–1080 px`).
|
||||
- **Top-Bar & CLI Capsule Customization**: Independently toggle the live running-sessions indicator and the Antigravity CLI bottom status capsule (auto-provisioned via `~/.gemini/antigravity-cli/settings.json` `statusLine`), and customize 1 to 5 metric slots and their left-to-right order (defaulting to Output Speed, TTFT, and Context Usage).
|
||||
- **Call Details Display**: Under **Layout -> Step Table**, independently toggle main/subagent badges, the turn rail (off by default), and **Speed Multi-Color** grading (off by default so step speeds render in clean monochrome when generation speed fluctuates).
|
||||
- **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).
|
||||
- **Call Details & Custom Token Combos**: Under **Structure -> Step Table**, independently toggle main/subagent badges, the turn rail (off by default), and **Speed Multi-Color** grading (off by default); keep the default `Ctx / Think / Reply` combo column, switch to the billing-aligned `In / Out / Cache` preset (with per-segment cost breakdown on hover), or enter a custom format string such as `context:new:cache` or `in:out:cache`.
|
||||
- **Model Name Format**: Choose among Compact short alias (e.g. `argon-4-high`), full raw upstream ID, or Trimmed raw ID (hiding `gemini-`, `claude-`, and `gpt-` prefixes to save single-line space, e.g. `3.8-flash-n`, `sonnet-4-6`, `5.4-mini`), with compaction suffixes (`·compact`) protected from ellipsis truncation; Orchestrator series IDs remain independently configurable.
|
||||
- **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*.
|
||||
|
||||
|
||||
+3
-3
@@ -49,10 +49,10 @@
|
||||
- 按步查看:列出当前会话全部步骤的模型、输出速度、首字延迟、上下文/输出 Token、缓存命中率与单步费用。
|
||||
- 按模型汇总:按当前所选会话(及所选主/子代理范围)统计各模型的调用次数、均速、总 Token 与费用。
|
||||
- **偏好设置**
|
||||
- 选择面板挂载方式:双栖挂载(顶部栏 + 侧边栏)或仅侧边栏。
|
||||
- 选择面板挂载方式与悬浮窗宽度:支持双栖挂载(顶部栏 + 侧边栏)、输入框挂载与仅侧边栏;悬浮面板默认按表格内容自动适配增宽(免水平滚动且自动受窗口边界约束),也可手动指定 `440~1080 px` 固定宽度。
|
||||
- 顶部栏与 CLI 胶囊定制:独立开关实时运行会话入口与 Antigravity CLI 底部状态胶囊(自动写入 `~/.gemini/antigravity-cli/settings.json` 的 `statusLine`),并自由定义 1 至 5 个指标槽位的显示内容与排列顺序(默认为输出速度、首字延迟、上下文占用)。
|
||||
- 调用明细显示:在「界面编排 -> 调用明细字段」可独立开关主/子代理标识、对话轮次导轨(默认关闭)与输出速度多色分级(默认关闭,以清爽单色显示输出速度,避免速度波动时色彩繁杂)。
|
||||
- 选择模型名称格式:精简代号或原始模型 ID,并可独立设置 Orchestrator 系列显示精简代号(如 `orchestrator-argon`、`worker-agy-hydrogen`)或原始完整 ID。
|
||||
- 调用明细显示与自定义 Token 组合:在「界面编排 -> 调用明细字段」可独立开关主/子代理标识、对话轮次导轨(默认关闭)与输出速度多色分级(默认关闭);默认保留 `上下文 / 思考 / 正文` 组合列,同时提供对齐计费维度的 `输入 / 输出 / 缓存` 可选组合列(悬停显示对应三项费用拆解),并支持输入 `context:new:cache`、`in:out:cache` 等自定义格式字符串自由拼装单列指标。
|
||||
- 选择模型名称格式:提供精简代号(如 `argon-4-high`)、原始模型 ID 与去前缀原始 ID(自动隐藏 `gemini-` / `claude-` / `gpt-` 前缀以节省单行空间,如 `3.8-flash-n`、`sonnet-4-6`、`5.4-mini`)三档,且自动压缩尾标(`·压缩`)独立保护永不截断;Orchestrator 系列仍可独立设置精简或完整 ID。
|
||||
- 按模型设置上下文:在「其他 → 模型上下文设置」为同一模型的各推理档统一设置上限,或切回「跟随宿主设置」。列表右侧显示已设置的上限和宿主最近报告的数值。App / IDE 窗口桥接在插件启动时重新读取宿主模型目录并应用已保存的设置,适用于之后发送的消息。CLI 使用 `AGY_CLI_AUTO_COMPACT_OVERRIDE`。
|
||||
- 版本更新与价格表同步:支持从云端 [`pricing-catalog.json`](pricing-catalog.json) 动态同步最新模型价格表,并提供「仅提示新版本,手动更新」(默认)、「自动更新」与「关闭更新」三档更新方式。
|
||||
|
||||
|
||||
+865
-91
File diff suppressed because it is too large
Load Diff
@@ -22,6 +22,7 @@ import {
|
||||
loadSettings,
|
||||
lsRuntimeEndpoint,
|
||||
normalizeFullSettings,
|
||||
normalizeModelDisplayMode,
|
||||
normalizePluginUpdateMode,
|
||||
normalizeWindowMountMode,
|
||||
saveJson,
|
||||
@@ -38,6 +39,7 @@ import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
|
||||
import {
|
||||
performPluginUpdate,
|
||||
scheduleSidecarRestart,
|
||||
setSidecarRestartHandler,
|
||||
syncCloudCatalog,
|
||||
} from './plugin-updater.mjs';
|
||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
@@ -124,19 +126,19 @@ function projectDisplayStep(st) {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
|
||||
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
} = st;
|
||||
return {
|
||||
stepIndex, createdAtMs, isCompactionStep, modelKey, modelShort, modelLabel,
|
||||
modelUpstream, responseModel, modelSource, tokPerSec, ttftSec, totalDurationSec,
|
||||
streamDurationSec, selectedSpeedReason, contextTokens, inputTokens, cacheReadTokens,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, agentId,
|
||||
agentCascadeId, agentLabel, agentBadge, agentRole, agentIndex, isSubagent,
|
||||
turnIndex, isTurnStart, isLatestTurn, turnPrompt, rootTurnIndex, isRootTurnStart,
|
||||
isRootLatestTurn, rootTurnPrompt,
|
||||
outputTokens, thinkingTokens, responseTokens, cacheHitPct, costUsd, inCostUsd,
|
||||
cacheCostUsd, outCostUsd, agentId, agentCascadeId, agentLabel, agentBadge,
|
||||
agentRole, agentIndex, isSubagent, turnIndex, isTurnStart, isLatestTurn,
|
||||
turnPrompt, rootTurnIndex, isRootTurnStart, isRootLatestTurn, rootTurnPrompt,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -288,6 +290,14 @@ export function executeSettingsAction(data) {
|
||||
: 'dual'
|
||||
: 'sidebar'
|
||||
: normalizeWindowMountMode(current.windowMountMode, current.enableWindowOverlay);
|
||||
const nextModelDisplayMode =
|
||||
payload.modelDisplayMode !== undefined
|
||||
? normalizeModelDisplayMode(payload.modelDisplayMode)
|
||||
: typeof payload.showUpstreamModel === 'boolean'
|
||||
? payload.showUpstreamModel
|
||||
? 'upstream'
|
||||
: 'short'
|
||||
: normalizeModelDisplayMode(current.modelDisplayMode, current.showUpstreamModel);
|
||||
const updated = normalizeFullSettings({
|
||||
...current,
|
||||
...payload,
|
||||
@@ -300,6 +310,7 @@ export function executeSettingsAction(data) {
|
||||
payload.weeklyCostBudget,
|
||||
current.weeklyCostBudget
|
||||
),
|
||||
modelDisplayMode: nextModelDisplayMode,
|
||||
pluginUpdateMode: nextPluginUpdateMode,
|
||||
windowMountMode: nextWindowMountMode,
|
||||
});
|
||||
@@ -528,6 +539,9 @@ export function bootWindowBridgeRuntime({ allowDynamicLs = false, onRestart = nu
|
||||
|
||||
const triggerRestart =
|
||||
typeof onRestart === 'function' ? onRestart : () => scheduleSidecarRestart(150);
|
||||
if (typeof onRestart === 'function') {
|
||||
setSidecarRestartHandler(onRestart);
|
||||
}
|
||||
|
||||
if (lsRuntimeEndpoint.baseUrl) {
|
||||
syncCloudCatalog({ force: false }).catch(() => {});
|
||||
|
||||
@@ -18,16 +18,22 @@ import {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_POPOVER_WIDTH,
|
||||
DEFAULT_SETTINGS_SCHEMA,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_POPOVER_WIDTH,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_POPOVER_WIDTH,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
MODEL_DISPLAY_MODES,
|
||||
ORCHESTRATOR_ID_MODES,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
PLUGIN_UPDATE_MODES,
|
||||
POPOVER_WIDTH_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
@@ -38,32 +44,43 @@ import {
|
||||
normalizeFullSettings,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
parseStepTokenComboSegments,
|
||||
} from './settings-schema.mjs';
|
||||
|
||||
export {
|
||||
DEFAULT_HOVER_MODULES,
|
||||
DEFAULT_OVERVIEW_METRICS,
|
||||
DEFAULT_OVERVIEW_MODULES,
|
||||
DEFAULT_POPOVER_WIDTH,
|
||||
DEFAULT_SETTINGS_SCHEMA,
|
||||
DEFAULT_STEP_TABLE_COLUMNS,
|
||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_TOPBAR_SLOTS,
|
||||
FONT_SCALE_KEYS,
|
||||
MAX_POPOVER_WIDTH,
|
||||
MAX_TOPBAR_SLOTS,
|
||||
MIN_POPOVER_WIDTH,
|
||||
MIN_TOPBAR_SLOTS,
|
||||
MODEL_DISPLAY_MODES,
|
||||
ORCHESTRATOR_ID_MODES,
|
||||
OVERVIEW_METRIC_KEYS,
|
||||
OVERVIEW_MODULE_KEYS,
|
||||
PLUGIN_UPDATE_MODES,
|
||||
POPOVER_WIDTH_MODES,
|
||||
STEP_TABLE_COLUMN_KEYS,
|
||||
SUPPORTED_LANGUAGES,
|
||||
THEME_ACCENT_KEYS,
|
||||
@@ -74,16 +91,21 @@ export {
|
||||
normalizeFullSettings,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
parseStepTokenComboSegments,
|
||||
} from './settings-schema.mjs';
|
||||
|
||||
/**
|
||||
@@ -292,7 +314,7 @@ export function loadJson(filePath, fallback) {
|
||||
*/
|
||||
export function saveJson(filePath, data) {
|
||||
try {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
mkdirSync(dirname(filePath), { recursive: true });
|
||||
if (filePath === CACHE_FILE) {
|
||||
writeTrajectoryCacheFile(filePath, data);
|
||||
} else {
|
||||
|
||||
@@ -72,15 +72,39 @@ function runExecFile(cmd, args, opts = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
let customSidecarRestartHandler = null;
|
||||
|
||||
/**
|
||||
* 更新完成后调度 Sidecar 进程平滑退出,让宿主进程监督器自动重启新代码。
|
||||
* 注册自定义运行时热重载回调(例如 `main.mjs` 的 `Worker` 热替换或 `bridge-daemon.mjs` 的平滑退出),
|
||||
* 避免直接调用 `process.exit(0)` 导致宿主 `SidecarApp` 固定端口失联。
|
||||
*
|
||||
* @param {(() => void)|null} handler
|
||||
*/
|
||||
export function setSidecarRestartHandler(handler) {
|
||||
customSidecarRestartHandler = typeof handler === 'function' ? handler : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新完成后调度 Sidecar 运行时热重载(若未注册自定义处理器,则回退平滑退出供父监督器拉起)。
|
||||
* 在单元测试环境(`!LS_ADDR || LS_ADDR === 'test.invalid'`)下自动跳过。
|
||||
*
|
||||
* @param {number} [delayMs=350] 延迟毫秒数,确保当前 HTTP 响应先发回前端
|
||||
*/
|
||||
export function scheduleSidecarRestart(delayMs = 350) {
|
||||
const activeAddr = lsRuntimeEndpoint.addr || LS_ADDR;
|
||||
if (!activeAddr || activeAddr === 'test.invalid' || typeof process?.exit !== 'function') return;
|
||||
if (!activeAddr || activeAddr === 'test.invalid') return;
|
||||
if (typeof customSidecarRestartHandler === 'function') {
|
||||
const fn = customSidecarRestartHandler;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
fn();
|
||||
} catch {
|
||||
// 忽略自定义热重载回调异常
|
||||
}
|
||||
}, delayMs);
|
||||
return;
|
||||
}
|
||||
if (typeof process?.exit !== 'function') return;
|
||||
setTimeout(() => {
|
||||
try {
|
||||
process.exit(0);
|
||||
|
||||
@@ -84,6 +84,8 @@ export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
@@ -101,12 +103,57 @@ export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
||||
|
||||
export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
|
||||
context: 'context',
|
||||
ctx: 'context',
|
||||
'上下文': 'context',
|
||||
in: 'in',
|
||||
new: 'in',
|
||||
input: 'in',
|
||||
'输入': 'in',
|
||||
'新输入': 'in',
|
||||
out: 'out',
|
||||
output: 'out',
|
||||
'输出': 'out',
|
||||
'总输出': 'out',
|
||||
cache: 'cache',
|
||||
cached: 'cache',
|
||||
cache_read: 'cache',
|
||||
cacheread: 'cache',
|
||||
'缓存': 'cache',
|
||||
'缓存读': 'cache',
|
||||
think: 'think',
|
||||
thinking: 'think',
|
||||
'思考': 'think',
|
||||
reply: 'reply',
|
||||
body: 'reply',
|
||||
resp: 'reply',
|
||||
response: 'reply',
|
||||
text: 'reply',
|
||||
'正文': 'reply',
|
||||
'回复': 'reply',
|
||||
total: 'total',
|
||||
all: 'total',
|
||||
sum: 'total',
|
||||
'总计': 'total',
|
||||
'总token': 'total',
|
||||
});
|
||||
|
||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
||||
|
||||
export const MODEL_DISPLAY_MODES = Object.freeze(['short', 'upstream', 'upstream_compact']);
|
||||
|
||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
||||
|
||||
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
||||
|
||||
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
|
||||
export const MIN_POPOVER_WIDTH = 440;
|
||||
export const MAX_POPOVER_WIDTH = 1080;
|
||||
export const DEFAULT_POPOVER_WIDTH = 580;
|
||||
|
||||
function isSchemaPlainObject(v) {
|
||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||
}
|
||||
@@ -171,6 +218,25 @@ export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
|
||||
return 'dual';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化模型名称展示模式(`'short'` 精简代号 | `'upstream_compact'` 去前缀原始 ID | `'upstream'` 完整原始 ID),
|
||||
* 兼容历史 `showUpstreamModel` 布尔开关,默认 `'short'`。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyShowUpstream]
|
||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
||||
*/
|
||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
if (legacyShowUpstream === true) return 'upstream';
|
||||
return 'short';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
||||
*
|
||||
@@ -182,6 +248,65 @@ export function normalizeOrchestratorIdMode(mode) {
|
||||
return m === 'full' ? 'full' : 'compact';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化悬浮主面板宽度模式(`'auto'` 自适应内容宽度 | `'custom'` 指定像素宽度,默认 `'auto'`)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @returns {'auto'|'custom'}
|
||||
*/
|
||||
export function normalizePopoverWidthMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。
|
||||
*
|
||||
* @param {unknown} width
|
||||
* @returns {number}
|
||||
*/
|
||||
export function normalizePopoverWidth(width) {
|
||||
const num = Number(width);
|
||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH;
|
||||
return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>}
|
||||
*/
|
||||
export function parseStepTokenComboSegments(raw) {
|
||||
const str = String(raw ?? '').trim();
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
if (str) {
|
||||
for (const part of str.split(/[:/,|]+/)) {
|
||||
const key = part.trim().toLowerCase();
|
||||
if (!key) continue;
|
||||
const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key)
|
||||
? STEP_TOKEN_SEGMENT_ALIASES[key]
|
||||
: null;
|
||||
if (!mapped || seen.has(mapped)) continue;
|
||||
seen.add(mapped);
|
||||
out.push(/** @type {any} */ (mapped));
|
||||
if (out.length >= 4) break;
|
||||
}
|
||||
}
|
||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {string}
|
||||
*/
|
||||
export function normalizeStepTokenComboFormat(raw) {
|
||||
return parseStepTokenComboSegments(raw).join(':');
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||
*
|
||||
@@ -362,12 +487,15 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
weeklyTokenBudget: 150000000,
|
||||
weeklyCostBudget: 100,
|
||||
weeklyLimitMode: 'official',
|
||||
modelDisplayMode: 'short',
|
||||
showUpstreamModel: false,
|
||||
orchestratorIdMode: 'compact',
|
||||
pluginUpdateMode: 'manual',
|
||||
autoUpdatePlugin: false,
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
popoverWidthMode: 'auto',
|
||||
popoverWidth: DEFAULT_POPOVER_WIDTH,
|
||||
enableCliStatusLine: true,
|
||||
standalonePort: 0,
|
||||
showTopbarMultiSession: true,
|
||||
@@ -378,6 +506,7 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
stepTokenComboFormat: DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||
stepTableColumns: DEFAULT_STEP_TABLE_COLUMNS,
|
||||
modelContextWindows: Object.freeze({}),
|
||||
});
|
||||
@@ -393,12 +522,15 @@ export function createDefaultSettingsObject() {
|
||||
weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget,
|
||||
weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget,
|
||||
weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode,
|
||||
modelDisplayMode: DEFAULT_SETTINGS_SCHEMA.modelDisplayMode,
|
||||
showUpstreamModel: DEFAULT_SETTINGS_SCHEMA.showUpstreamModel,
|
||||
orchestratorIdMode: DEFAULT_SETTINGS_SCHEMA.orchestratorIdMode,
|
||||
pluginUpdateMode: DEFAULT_SETTINGS_SCHEMA.pluginUpdateMode,
|
||||
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
|
||||
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
|
||||
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
|
||||
popoverWidthMode: DEFAULT_SETTINGS_SCHEMA.popoverWidthMode,
|
||||
popoverWidth: DEFAULT_SETTINGS_SCHEMA.popoverWidth,
|
||||
enableCliStatusLine: DEFAULT_SETTINGS_SCHEMA.enableCliStatusLine,
|
||||
standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort,
|
||||
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
|
||||
@@ -409,6 +541,7 @@ export function createDefaultSettingsObject() {
|
||||
showStepTurnRail: DEFAULT_SETTINGS_SCHEMA.showStepTurnRail,
|
||||
showStepAgentBadge: DEFAULT_SETTINGS_SCHEMA.showStepAgentBadge,
|
||||
showStepSpeedColor: DEFAULT_SETTINGS_SCHEMA.showStepSpeedColor,
|
||||
stepTokenComboFormat: DEFAULT_SETTINGS_SCHEMA.stepTokenComboFormat,
|
||||
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||
modelContextWindows: {},
|
||||
};
|
||||
@@ -429,6 +562,10 @@ export function normalizeFullSettings(rawInput) {
|
||||
safeRaw.windowMountMode,
|
||||
safeRaw.enableWindowOverlay
|
||||
);
|
||||
const modelDisplayMode = normalizeModelDisplayMode(
|
||||
safeRaw.modelDisplayMode,
|
||||
safeRaw.showUpstreamModel
|
||||
);
|
||||
return {
|
||||
language: normalizeLanguageSetting(safeRaw.language),
|
||||
themeAccent: normalizeThemeAccent(safeRaw.themeAccent),
|
||||
@@ -442,12 +579,15 @@ export function normalizeFullSettings(rawInput) {
|
||||
DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget
|
||||
),
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(safeRaw.weeklyLimitMode),
|
||||
showUpstreamModel: safeRaw.showUpstreamModel === true,
|
||||
modelDisplayMode,
|
||||
showUpstreamModel: modelDisplayMode !== 'short',
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(safeRaw.orchestratorIdMode),
|
||||
pluginUpdateMode,
|
||||
autoUpdatePlugin: pluginUpdateMode === 'auto',
|
||||
windowMountMode,
|
||||
enableWindowOverlay: windowMountMode !== 'sidebar',
|
||||
popoverWidthMode: normalizePopoverWidthMode(safeRaw.popoverWidthMode),
|
||||
popoverWidth: normalizePopoverWidth(safeRaw.popoverWidth),
|
||||
enableCliStatusLine: safeRaw.enableCliStatusLine !== false,
|
||||
standalonePort: normalizeStandalonePort(safeRaw.standalonePort),
|
||||
showTopbarMultiSession: safeRaw.showTopbarMultiSession !== false,
|
||||
@@ -458,6 +598,7 @@ export function normalizeFullSettings(rawInput) {
|
||||
showStepTurnRail: safeRaw.showStepTurnRail === true,
|
||||
showStepAgentBadge: safeRaw.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: safeRaw.showStepSpeedColor === true,
|
||||
stepTokenComboFormat: normalizeStepTokenComboFormat(safeRaw.stepTokenComboFormat),
|
||||
stepTableColumns: normalizeStepTableColumns(safeRaw.stepTableColumns),
|
||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* @fileoverview Hot-reloadable backend Worker runtime (`sidecar-worker.mjs`) for `main.mjs`.
|
||||
*
|
||||
* Isolates all ESM backend modules (`api-actions.mjs`, `telemetry-builder.mjs`, `window-bridge.mjs`,
|
||||
* `pricing-catalog.mjs`, etc.) inside a dedicated V8 Worker isolate so plugin updates (in-app Git/ZIP
|
||||
* or external file overwrite while Antigravity is open) can tear down and respawn a fresh Worker
|
||||
* without ever exiting the parent `SidecarApp` process or losing its host-assigned HTTP port.
|
||||
*/
|
||||
|
||||
import { parentPort } from 'node:worker_threads';
|
||||
import {
|
||||
bootBundleVersion,
|
||||
bootWindowBridgeRuntime,
|
||||
dispatchBridgeApiRequest,
|
||||
} from './api-actions.mjs';
|
||||
import { computeRuntimeCodeVersion } from './config.mjs';
|
||||
|
||||
let shuttingDown = false;
|
||||
let reloadRequested = false;
|
||||
|
||||
function requestWorkerReload() {
|
||||
if (shuttingDown || reloadRequested) return;
|
||||
reloadRequested = true;
|
||||
try {
|
||||
parentPort?.postMessage({ type: 'reload_request' });
|
||||
} catch {
|
||||
// Ignore postMessage errors if parent is already closing
|
||||
}
|
||||
}
|
||||
|
||||
const bridgeController = bootWindowBridgeRuntime({
|
||||
allowDynamicLs: true,
|
||||
onRestart: requestWorkerReload,
|
||||
});
|
||||
|
||||
const driftWatchTimer = setInterval(() => {
|
||||
if (shuttingDown || reloadRequested) return;
|
||||
try {
|
||||
const diskVersion = String(computeRuntimeCodeVersion() || '');
|
||||
if (bootBundleVersion && diskVersion && diskVersion !== String(bootBundleVersion)) {
|
||||
requestWorkerReload();
|
||||
}
|
||||
} catch {
|
||||
// Ignore transient file stat errors while files are being overwritten
|
||||
}
|
||||
}, 3000);
|
||||
driftWatchTimer.unref?.();
|
||||
|
||||
async function gracefulStop() {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
clearInterval(driftWatchTimer);
|
||||
try {
|
||||
await bridgeController?.stop?.({ disposeWindows: false });
|
||||
} catch {
|
||||
// Ignore shutdown errors
|
||||
}
|
||||
}
|
||||
|
||||
parentPort?.on('message', async (msg) => {
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
if (msg.type === 'shutdown') {
|
||||
await gracefulStop();
|
||||
try {
|
||||
parentPort?.postMessage({ type: 'shutdown_ack', id: msg.id });
|
||||
} catch {
|
||||
// Ignore closed channel
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'api') {
|
||||
const reqId = msg.id;
|
||||
try {
|
||||
const out = await dispatchBridgeApiRequest(
|
||||
String(msg.pathname || ''),
|
||||
String(msg.method || 'GET'),
|
||||
msg.data,
|
||||
{ onRestart: requestWorkerReload }
|
||||
);
|
||||
parentPort?.postMessage({
|
||||
type: 'api_result',
|
||||
id: reqId,
|
||||
ok: true,
|
||||
response: {
|
||||
status: out?.status || 200,
|
||||
contentType: out?.contentType || 'application/json',
|
||||
headers: out?.headers || { 'Cache-Control': 'no-store' },
|
||||
body: typeof out?.body === 'string' ? out.body : JSON.stringify(out?.body ?? {}),
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
parentPort?.postMessage({
|
||||
type: 'api_result',
|
||||
id: reqId,
|
||||
ok: false,
|
||||
error: err?.message || 'Worker API execution failed',
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
parentPort?.postMessage({ type: 'ready', bundleVersion: bootBundleVersion });
|
||||
@@ -29,6 +29,7 @@ const ALLOWED_BRIDGE_PATHS = new Set([
|
||||
'/api/telemetry',
|
||||
'/api/settings',
|
||||
'/api/settings/reset',
|
||||
'/api/cache/rebuild',
|
||||
'/api/accounts',
|
||||
'/api/accounts/update',
|
||||
'/api/context-window',
|
||||
@@ -789,8 +790,13 @@ export function createWindowBridgeController(options) {
|
||||
}
|
||||
serverStartPromise = (async () => {
|
||||
const { http, crypto } = await loadNodeDeps();
|
||||
const persistedLease = leaseFilePath ? loadJson(leaseFilePath, null) : null;
|
||||
const persistedToken = String(persistedLease?.bridgeToken || '').trim();
|
||||
const persistedPort = Number(persistedLease?.bridgePort || 0);
|
||||
if (!bridgeToken) {
|
||||
bridgeToken = crypto.randomBytes(32).toString('hex');
|
||||
bridgeToken = /^[0-9a-f]{64}$/i.test(persistedToken)
|
||||
? persistedToken
|
||||
: crypto.randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
const srv = http.createServer((req, res) => {
|
||||
@@ -915,17 +921,47 @@ export function createWindowBridgeController(options) {
|
||||
});
|
||||
});
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
srv.once('error', reject);
|
||||
srv.listen(0, '127.0.0.1', () => {
|
||||
srv.removeListener('error', reject);
|
||||
const listenOnLoopback = (targetPort) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const onErr = (err) => {
|
||||
srv.removeListener('listening', onListening);
|
||||
reject(err);
|
||||
};
|
||||
const onListening = () => {
|
||||
srv.removeListener('error', onErr);
|
||||
resolve();
|
||||
};
|
||||
srv.once('error', onErr);
|
||||
srv.once('listening', onListening);
|
||||
srv.listen(targetPort, '127.0.0.1');
|
||||
});
|
||||
});
|
||||
|
||||
const preferredPort =
|
||||
Number.isInteger(persistedPort) && persistedPort >= 1024 && persistedPort <= 65535
|
||||
? persistedPort
|
||||
: 0;
|
||||
if (preferredPort > 0) {
|
||||
try {
|
||||
await listenOnLoopback(preferredPort);
|
||||
} catch {
|
||||
await listenOnLoopback(0);
|
||||
}
|
||||
} else {
|
||||
await listenOnLoopback(0);
|
||||
}
|
||||
srv.unref?.();
|
||||
const addr = srv.address();
|
||||
bridgePort = typeof addr === 'object' && addr ? Number(addr.port || 0) : 0;
|
||||
server = srv;
|
||||
if (leaseFilePath && bridgePort > 0) {
|
||||
saveJson(leaseFilePath, {
|
||||
pid: process.pid,
|
||||
bundleVersion: String(getBundleVersionFn() || ''),
|
||||
bridgePort,
|
||||
bridgeToken,
|
||||
updatedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
return { port: bridgePort, token: bridgeToken };
|
||||
})().finally(() => {
|
||||
serverStartPromise = null;
|
||||
@@ -1133,6 +1169,8 @@ export function createWindowBridgeController(options) {
|
||||
saveJson(leaseFilePath, {
|
||||
pid: process.pid,
|
||||
bundleVersion,
|
||||
bridgePort: bridgePort > 0 ? bridgePort : Number(lease?.bridgePort || 0) || undefined,
|
||||
bridgeToken: bridgeToken || String(lease?.bridgeToken || '') || undefined,
|
||||
updatedAtMs: Date.now(),
|
||||
});
|
||||
}
|
||||
@@ -1462,6 +1500,17 @@ export function createWindowBridgeController(options) {
|
||||
if (initialTimer) clearTimeout(initialTimer);
|
||||
if (pollTimer) clearTimeout(pollTimer);
|
||||
|
||||
if (leaseFilePath) {
|
||||
const curSettings = getSettingsFn() || {};
|
||||
const mountMode = normalizeWindowMountMode(
|
||||
curSettings.windowMountMode,
|
||||
curSettings.enableWindowOverlay
|
||||
);
|
||||
if (curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar') {
|
||||
ensureBridgeServer().catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
initialTimer = setTimeout(() => {
|
||||
initialTimer = null;
|
||||
syncAllWindows()
|
||||
@@ -1469,7 +1518,7 @@ export function createWindowBridgeController(options) {
|
||||
.finally(() => {
|
||||
scheduleNextPoll();
|
||||
});
|
||||
}, 350);
|
||||
}, 120);
|
||||
initialTimer.unref?.();
|
||||
}
|
||||
|
||||
|
||||
@@ -12,10 +12,15 @@
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
bootBundleVersion,
|
||||
bootWindowBridgeRuntime,
|
||||
setStandalonePortListener,
|
||||
} from './backend/api-actions.mjs';
|
||||
import { loadSettings, normalizeStandalonePort } from './backend/config.mjs';
|
||||
import {
|
||||
computeRuntimeCodeVersion,
|
||||
loadSettings,
|
||||
normalizeStandalonePort,
|
||||
} from './backend/config.mjs';
|
||||
import {
|
||||
createStandaloneWebServer,
|
||||
parseStandaloneCliArgs,
|
||||
@@ -42,6 +47,19 @@ export function startBridgeDaemon() {
|
||||
onRestart: triggerRestart,
|
||||
});
|
||||
|
||||
const driftWatchTimer = setInterval(() => {
|
||||
if (shuttingDown) return;
|
||||
try {
|
||||
const diskVersion = String(computeRuntimeCodeVersion() || '');
|
||||
if (bootBundleVersion && diskVersion && diskVersion !== String(bootBundleVersion)) {
|
||||
triggerRestart();
|
||||
}
|
||||
} catch {
|
||||
// 忽略文件覆盖期间瞬态 stat 异常
|
||||
}
|
||||
}, 3000);
|
||||
driftWatchTimer.unref?.();
|
||||
|
||||
function resolveDesiredStandalonePort(settingsOverride = null) {
|
||||
if (envPinnedPort !== null) {
|
||||
return envPinnedPort;
|
||||
@@ -102,6 +120,7 @@ export function startBridgeDaemon() {
|
||||
async function shutdown({ disposeWindows = false, exitCode = 0 } = {}) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
clearInterval(driftWatchTimer);
|
||||
setStandalonePortListener(null);
|
||||
const forceTimer = setTimeout(() => {
|
||||
process.exit(exitCode);
|
||||
|
||||
@@ -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=1794804132149">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794815058602">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794804132149"></script>
|
||||
<script src="/app.js?v=1794815058602"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+175
-148
@@ -2,26 +2,18 @@
|
||||
* @fileoverview Antigravity Usage Monitor 面板 Sidecar HTTP 服务入口。
|
||||
*
|
||||
* 职责边界:
|
||||
* - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`);
|
||||
* - 提供严格同端口 Loopback 受保护的 JSON API 路由:
|
||||
* - `GET /api/telemetry`:获取实时配额、当前会话指标与历史聚合遥测数据;
|
||||
* - `POST /api/settings`:保存用户偏好设置(写入失败时返回 HTTP 500);
|
||||
* - `POST /api/cloud-sync`:立即从 GitHub 同步最新云端价格目录与版本信息;
|
||||
* - `POST /api/plugin-update`:一键执行插件自更新(Git / Release ZIP 双通道);
|
||||
* - 所有核心业务逻辑与双栖桥接引导均委托至 `./backend/api-actions.mjs`。
|
||||
* - 提供前端静态资产路由(`/`、`/app.js`、`/styles.css`,每次请求从磁盘读取最新产物);
|
||||
* - 提供严格同端口 Loopback 受保护的 JSON API 路由;
|
||||
* - 在真实宿主环境中通过 `node:worker_threads` 托管 `./backend/sidecar-worker.mjs`:
|
||||
* 当插件在客户端未关闭时执行自更新或外部覆盖文件,主进程保持常驻不退出(守护 `SidecarApp` 宿主端口不断连),
|
||||
* 仅在后台毫秒级平滑替换为全新 V8 Isolate 的 Worker 实例并复用桥接端口,彻底消除热更新后的「重试中」失联问题。
|
||||
*/
|
||||
|
||||
import { Worker } from 'node:worker_threads';
|
||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||
import {
|
||||
bootWindowBridgeRuntime,
|
||||
executeAccountCredentialAction,
|
||||
executeCloudSyncAction,
|
||||
executeModelContextWindowAction,
|
||||
executePluginUpdateAction,
|
||||
executeRebuildCacheAction,
|
||||
executeResetSettingsAction,
|
||||
executeSettingsAction,
|
||||
executeTelemetryAction,
|
||||
dispatchBridgeApiRequest,
|
||||
isLocalHostRequest,
|
||||
readLocalAsync,
|
||||
} from './backend/api-actions.mjs';
|
||||
@@ -30,6 +22,160 @@ const app = new SidecarApp();
|
||||
|
||||
const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' };
|
||||
|
||||
const isTestHarnessEnv =
|
||||
String(process?.env?.ANTIGRAVITY_LS_ADDRESS || '').trim() === 'test.invalid' ||
|
||||
typeof Worker !== 'function';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 热可替换后端 Worker 监督器(仅在真实宿主运行时启用,测试沙箱直接走内存分发)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
let activeWorker = null;
|
||||
let workerSwapPromise = null;
|
||||
let rpcSeq = 0;
|
||||
const pendingWorkerRpcs = new Map();
|
||||
|
||||
function createBackendWorkerInstance() {
|
||||
const workerUrl = new URL('./backend/sidecar-worker.mjs', import.meta.url);
|
||||
const worker = new Worker(workerUrl);
|
||||
|
||||
worker.on('message', (msg) => {
|
||||
if (!msg || typeof msg !== 'object') return;
|
||||
if (msg.type === 'reload_request') {
|
||||
if (worker === activeWorker) {
|
||||
void reloadBackendWorker();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (msg.type === 'api_result' || msg.type === 'shutdown_ack') {
|
||||
const pending = pendingWorkerRpcs.get(msg.id);
|
||||
if (!pending) return;
|
||||
pendingWorkerRpcs.delete(msg.id);
|
||||
clearTimeout(pending.timer);
|
||||
if (msg.type === 'shutdown_ack' || msg.ok) {
|
||||
pending.resolve(msg.response ?? true);
|
||||
} else {
|
||||
pending.reject(new Error(msg.error || 'Backend worker error'));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('exit', () => {
|
||||
for (const [id, entry] of pendingWorkerRpcs.entries()) {
|
||||
if (entry.worker === worker) {
|
||||
pendingWorkerRpcs.delete(id);
|
||||
clearTimeout(entry.timer);
|
||||
entry.reject(new Error('Backend worker exited during request'));
|
||||
}
|
||||
}
|
||||
if (activeWorker === worker) {
|
||||
activeWorker = null;
|
||||
if (!workerSwapPromise) {
|
||||
setTimeout(() => {
|
||||
if (!activeWorker && !workerSwapPromise) {
|
||||
activeWorker = createBackendWorkerInstance();
|
||||
}
|
||||
}, 120).unref?.();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
worker.on('error', () => {
|
||||
// 交由 exit 回调统一回收并拉起新实例
|
||||
});
|
||||
|
||||
return worker;
|
||||
}
|
||||
|
||||
function sendWorkerMessage(worker, payload, timeoutMs = 30000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const id = ++rpcSeq;
|
||||
const timer = setTimeout(() => {
|
||||
pendingWorkerRpcs.delete(id);
|
||||
reject(new Error('Backend worker request timeout'));
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
pendingWorkerRpcs.set(id, { worker, timer, resolve, reject });
|
||||
try {
|
||||
worker.postMessage({ ...payload, id });
|
||||
} catch (err) {
|
||||
pendingWorkerRpcs.delete(id);
|
||||
clearTimeout(timer);
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopWorkerGracefully(worker) {
|
||||
if (!worker) return;
|
||||
try {
|
||||
await sendWorkerMessage(worker, { type: 'shutdown' }, 1200);
|
||||
} catch {
|
||||
// 超时或通道已关闭时直接强制终止旧 Isolate
|
||||
}
|
||||
try {
|
||||
await worker.terminate();
|
||||
} catch {
|
||||
// 忽略重复终止异常
|
||||
}
|
||||
}
|
||||
|
||||
function reloadBackendWorker() {
|
||||
if (workerSwapPromise) return workerSwapPromise;
|
||||
workerSwapPromise = (async () => {
|
||||
const prev = activeWorker;
|
||||
activeWorker = null;
|
||||
await stopWorkerGracefully(prev);
|
||||
activeWorker = createBackendWorkerInstance();
|
||||
return activeWorker;
|
||||
})().finally(() => {
|
||||
workerSwapPromise = null;
|
||||
});
|
||||
return workerSwapPromise;
|
||||
}
|
||||
|
||||
async function ensureActiveWorker() {
|
||||
if (workerSwapPromise) {
|
||||
return workerSwapPromise;
|
||||
}
|
||||
if (!activeWorker) {
|
||||
activeWorker = createBackendWorkerInstance();
|
||||
}
|
||||
return activeWorker;
|
||||
}
|
||||
|
||||
async function forwardApiCall(pathname, method, data) {
|
||||
if (isTestHarnessEnv) {
|
||||
return dispatchBridgeApiRequest(pathname, method, data);
|
||||
}
|
||||
const upperMethod = String(method || 'GET').toUpperCase();
|
||||
try {
|
||||
const worker = await ensureActiveWorker();
|
||||
return await sendWorkerMessage(worker, { type: 'api', pathname, method: upperMethod, data });
|
||||
} catch (err) {
|
||||
if (upperMethod === 'GET') {
|
||||
const retryWorker = await ensureActiveWorker();
|
||||
return sendWorkerMessage(retryWorker, { type: 'api', pathname, method: upperMethod, data });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleProtectedApi(pathname, method, data, req) {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await forwardApiCall(pathname, method, data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 静态页面与前端资产路由
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -65,138 +211,19 @@ app.page(
|
||||
// 业务数据与控制 API 路由
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
app.api(
|
||||
'/api/telemetry',
|
||||
async (data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeTelemetryAction(data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
},
|
||||
'GET'
|
||||
);
|
||||
|
||||
app.api('/api/settings', (data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = executeSettingsAction(data);
|
||||
if (!out.ok) {
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
return out.updated;
|
||||
});
|
||||
|
||||
async function serveAccountCredentials(data, req) {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeAccountCredentialAction(data);
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
}
|
||||
|
||||
app.api('/api/accounts', (_data, req) => serveAccountCredentials(undefined, req), 'GET');
|
||||
app.api('/api/accounts/update', serveAccountCredentials, 'POST');
|
||||
|
||||
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' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executeCloudSyncAction();
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
});
|
||||
|
||||
app.api('/api/plugin-update', async (_data, req) => {
|
||||
if (!isLocalHostRequest(req)) {
|
||||
return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), {
|
||||
status: 403,
|
||||
contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
const out = await executePluginUpdateAction();
|
||||
return new Response(out.body, {
|
||||
status: out.status,
|
||||
contentType: out.contentType,
|
||||
headers: out.headers,
|
||||
});
|
||||
});
|
||||
app.api('/api/telemetry', (data, req) => handleProtectedApi('/api/telemetry', 'GET', data, req), 'GET');
|
||||
app.api('/api/settings', (data, req) => handleProtectedApi('/api/settings', 'POST', data, req));
|
||||
app.api('/api/accounts', (_data, req) => handleProtectedApi('/api/accounts', 'GET', undefined, req), 'GET');
|
||||
app.api('/api/accounts/update', (data, req) => handleProtectedApi('/api/accounts/update', 'POST', data, req), 'POST');
|
||||
app.api('/api/context-window', (data, req) => handleProtectedApi('/api/context-window', 'POST', data, req));
|
||||
app.api('/api/settings/reset', (_data, req) => handleProtectedApi('/api/settings/reset', 'POST', undefined, req));
|
||||
app.api('/api/cache/rebuild', (_data, req) => handleProtectedApi('/api/cache/rebuild', 'POST', undefined, req));
|
||||
app.api('/api/cloud-sync', (_data, req) => handleProtectedApi('/api/cloud-sync', 'POST', undefined, req));
|
||||
app.api('/api/plugin-update', (_data, req) => handleProtectedApi('/api/plugin-update', 'POST', undefined, req));
|
||||
|
||||
app.run();
|
||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||
if (isTestHarnessEnv) {
|
||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||
} else {
|
||||
void ensureActiveWorker();
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ function startMcpHostSupervisor() {
|
||||
if (shuttingDown) return;
|
||||
|
||||
const ranDurationMs = Date.now() - lastSpawnMs;
|
||||
let delayMs = 350;
|
||||
let delayMs = code === 0 ? 120 : 350;
|
||||
if (code !== 0 && ranDurationMs < 10_000) {
|
||||
rapidCrashCount += 1;
|
||||
delayMs = Math.min(30_000, 1000 * 2 ** Math.min(rapidCrashCount - 1, 5));
|
||||
|
||||
@@ -35,6 +35,8 @@ import {
|
||||
formatAgentBadgeText,
|
||||
getAgentBadgeClass,
|
||||
normalizeClientHoverModules,
|
||||
normalizeClientPopoverWidth,
|
||||
normalizeClientPopoverWidthMode,
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientUpdateMode,
|
||||
normalizeClientWindowMountMode,
|
||||
@@ -49,6 +51,8 @@ import { uiStore } from '../../store/uiStore.js';
|
||||
const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule';
|
||||
const PORTAL_HOST_ID = 'ag-usage-monitor-portal';
|
||||
const FLOATING_CARD_WIDTH = 522;
|
||||
const POPOVER_BASE_WIDTH = 540;
|
||||
const POPOVER_MAX_AUTO_WIDTH = 960;
|
||||
const MULTI_PANEL_WIDTH = 464;
|
||||
|
||||
/**
|
||||
@@ -1969,11 +1973,72 @@ export function mountWindowOverlay() {
|
||||
: bRect.right;
|
||||
|
||||
if (popoverOpen) {
|
||||
const maxPopCardW = Math.max(280, vw - minLeft - 12);
|
||||
const curSettings = telemetryStore.getState().telemetry?.settings;
|
||||
const popWidthMode = normalizeClientPopoverWidthMode(curSettings?.popoverWidthMode);
|
||||
let desiredPopW = Math.min(POPOVER_BASE_WIDTH, maxPopCardW);
|
||||
if (popWidthMode === 'custom') {
|
||||
desiredPopW = Math.min(
|
||||
normalizeClientPopoverWidth(curSettings?.popoverWidth),
|
||||
maxPopCardW
|
||||
);
|
||||
} else if (typeof popoverEl.querySelectorAll === 'function') {
|
||||
const panes = popoverEl.querySelectorAll('.table-viewport.is-step-table');
|
||||
for (const pane of panes) {
|
||||
let anc = pane;
|
||||
let inHiddenTree = false;
|
||||
while (anc && anc !== popoverEl) {
|
||||
if (anc.hasAttribute?.('hidden')) {
|
||||
inHiddenTree = true;
|
||||
break;
|
||||
}
|
||||
anc = anc.parentElement || anc.parentNode;
|
||||
}
|
||||
if (inHiddenTree) continue;
|
||||
const tableEl = pane.querySelector?.('.steps-data-table') || pane.firstElementChild;
|
||||
if (!tableEl) continue;
|
||||
const paneClientW = Number(pane.clientWidth || 0);
|
||||
const curPopW = Number(
|
||||
popoverEl.offsetWidth ||
|
||||
popoverEl.getBoundingClientRect?.().width ||
|
||||
POPOVER_BASE_WIDTH
|
||||
);
|
||||
let naturalTableW = 0;
|
||||
if (tableEl.style) {
|
||||
const prevW = tableEl.style.width || '';
|
||||
tableEl.style.width = 'max-content';
|
||||
naturalTableW = Math.ceil(
|
||||
Number(
|
||||
tableEl.getBoundingClientRect?.().width ||
|
||||
tableEl.scrollWidth ||
|
||||
tableEl.offsetWidth ||
|
||||
0
|
||||
)
|
||||
);
|
||||
tableEl.style.width = prevW;
|
||||
} else {
|
||||
naturalTableW = Math.ceil(Number(tableEl.scrollWidth || tableEl.offsetWidth || 0));
|
||||
}
|
||||
if (naturalTableW > 0) {
|
||||
const chromeW =
|
||||
paneClientW > 0 && curPopW >= paneClientW
|
||||
? Math.max(24, curPopW - paneClientW)
|
||||
: 34;
|
||||
desiredPopW = Math.max(
|
||||
desiredPopW,
|
||||
Math.min(POPOVER_MAX_AUTO_WIDTH, maxPopCardW, naturalTableW + chromeW + 4)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
popoverEl.style.setProperty?.('--wm-popover-w', `${desiredPopW}px`);
|
||||
popoverEl.style.width = `${desiredPopW}px`;
|
||||
|
||||
const rawW =
|
||||
Number(popoverEl.offsetWidth) ||
|
||||
Number(popoverEl.getBoundingClientRect?.().width) ||
|
||||
defaultCardW;
|
||||
const panelW = Math.min(rawW, Math.max(280, vw - minLeft - 12));
|
||||
desiredPopW;
|
||||
const panelW = Math.min(rawW, maxPopCardW);
|
||||
const spaceBelowPop = vh - bRect.bottom - 12;
|
||||
const spaceAbovePop = bRect.top - 16;
|
||||
const openPopAbove =
|
||||
@@ -2804,6 +2869,9 @@ export function mountWindowOverlay() {
|
||||
}
|
||||
lastAppliedMountMode = nextMountMode;
|
||||
renderCapsuleTelemetry();
|
||||
if (popoverOpen) {
|
||||
positionFloatingElements();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
@@ -2811,8 +2879,25 @@ export function mountWindowOverlay() {
|
||||
(st) => ({
|
||||
selectedAgentScope: st.selectedAgentScope,
|
||||
ctxInspectorAgentId: st.ctxInspectorAgentId,
|
||||
activeView: st.activeView,
|
||||
stepsSubTab: st.stepsSubTab,
|
||||
settingsSubTab: st.settingsSubTab,
|
||||
settingsStructureTab: st.settingsStructureTab,
|
||||
}),
|
||||
() => renderCapsuleTelemetry()
|
||||
() => {
|
||||
renderCapsuleTelemetry();
|
||||
if (popoverOpen) {
|
||||
positionFloatingElements();
|
||||
if (typeof requestAnimationFrame === 'function') {
|
||||
requestAnimationFrame(() => {
|
||||
if (!disposed && popoverOpen) {
|
||||
positionFloatingElements();
|
||||
refreshActiveViewScrollbars();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const unsubI18n = i18nStore.subscribe(
|
||||
@@ -3000,10 +3085,10 @@ export function mountWindowOverlay() {
|
||||
const token = String(nextBridge.token || '');
|
||||
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
||||
const cur = window.__AGUsageMonitorBridge || {};
|
||||
const portChanged = Number(cur.port || 0) !== port;
|
||||
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
|
||||
cur.port = port;
|
||||
cur.token = token;
|
||||
if (portChanged && cur.transportMode !== 'cdp') {
|
||||
if (portChanged) {
|
||||
cur.transportMode = 'http';
|
||||
}
|
||||
window.__AGUsageMonitorBridge = cur;
|
||||
|
||||
@@ -67,8 +67,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
||||
agentBadge: '主',
|
||||
agentLabel: t('fmt.mainAgent'),
|
||||
modelLabel: 'Gemini 4 Carbon (High)',
|
||||
modelShort: 'gemini-4-carbon',
|
||||
modelShort: 'carbon-4-high',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M37',
|
||||
modelUpstream: 'gemini-4-carbon-high',
|
||||
upstreamModel: 'gemini-4-carbon-high',
|
||||
tokPerSec: 68.4,
|
||||
ttftSec: 1.15,
|
||||
@@ -82,6 +83,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
||||
responseTokens: 560,
|
||||
cacheHitPct: 94.5,
|
||||
costUsd: 0.042,
|
||||
inCostUsd: 0.0156,
|
||||
cacheCostUsd: 0.0134,
|
||||
outCostUsd: 0.0142,
|
||||
createdAtMs: anchorMinMs - 14_000,
|
||||
turnIndex: 2,
|
||||
rootTurnIndex: 2,
|
||||
@@ -102,8 +106,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
||||
agentRole: subRole,
|
||||
agentLabel: subRole,
|
||||
modelLabel: 'Gemini 3.8 Flash',
|
||||
modelShort: 'gemini-3.8-flash',
|
||||
modelShort: 'flash-3.8',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M42',
|
||||
modelUpstream: 'gemini-3.8-flash-n',
|
||||
upstreamModel: 'gemini-3.8-flash-n',
|
||||
tokPerSec: 96.2,
|
||||
ttftSec: 0.68,
|
||||
@@ -117,6 +122,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
||||
responseTokens: 464,
|
||||
cacheHitPct: 88.1,
|
||||
costUsd: 0.009,
|
||||
inCostUsd: 0.0065,
|
||||
cacheCostUsd: 0.0005,
|
||||
outCostUsd: 0.0026,
|
||||
createdAtMs: anchorMinMs - 42_000,
|
||||
turnIndex: 1,
|
||||
rootTurnIndex: 2,
|
||||
@@ -135,9 +143,11 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
||||
isSubagent: false,
|
||||
agentBadge: '主',
|
||||
agentLabel: t('fmt.mainAgent'),
|
||||
modelLabel: 'Gemini 4 Carbon (High)',
|
||||
modelShort: 'gemini-4-carbon',
|
||||
isCompactionStep: true,
|
||||
modelLabel: 'Gemini 4 Carbon (High) [自动压缩]',
|
||||
modelShort: 'carbon-4-high·压缩',
|
||||
rawModel: 'MODEL_PLACEHOLDER_M37',
|
||||
modelUpstream: 'gemini-4-carbon-high·压缩',
|
||||
upstreamModel: 'gemini-4-carbon-high',
|
||||
tokPerSec: 46.5,
|
||||
ttftSec: 3.4,
|
||||
@@ -151,6 +161,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
||||
responseTokens: 380,
|
||||
cacheHitPct: 61.4,
|
||||
costUsd: 0.068,
|
||||
inCostUsd: 0.0492,
|
||||
cacheCostUsd: 0.0078,
|
||||
outCostUsd: 0.011,
|
||||
createdAtMs: anchorMinMs - 88_000,
|
||||
turnIndex: 2,
|
||||
rootTurnIndex: 2,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
formatAgentBadgeText,
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
normalizeClientStepTokenComboFormat,
|
||||
} from '../../store/telemetryStore.js';
|
||||
|
||||
export function formatTurnPromptText(rawPrompt) {
|
||||
@@ -45,17 +46,19 @@ export const StepTableWidget = defineComponent({
|
||||
const stepsTheadRow = h('tr');
|
||||
const stepsTbody = h('tbody');
|
||||
|
||||
function syncTableHeaderColumns(colKeys) {
|
||||
function syncTableHeaderColumns(colKeys, headerCtx = {}) {
|
||||
const locale = getEffectiveLocale();
|
||||
const fmtKey = normalizeClientStepTokenComboFormat(headerCtx?.stepTokenComboFormat);
|
||||
const ctx = { stepTokenComboFormat: fmtKey };
|
||||
patchKeyedList(stepsTheadRow, colKeys, {
|
||||
keyFn: (colKey) => colKey,
|
||||
sigFn: (colKey) => `${locale}:${colKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel()}`,
|
||||
sigFn: (colKey) => `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}`,
|
||||
createRow: (colKey) => {
|
||||
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel() });
|
||||
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx) });
|
||||
return { el: th, refs: { th } };
|
||||
},
|
||||
updateRow: (refs, colKey) => {
|
||||
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel());
|
||||
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel(ctx));
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -169,13 +172,16 @@ export const StepTableWidget = defineComponent({
|
||||
showStepTurnRail = false,
|
||||
showStepAgentBadge = true,
|
||||
showStepSpeedColor = false,
|
||||
stepTokenComboFormat = undefined,
|
||||
displaySettings = {},
|
||||
} = {}
|
||||
) {
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat);
|
||||
const renderOptions = JSON.stringify([
|
||||
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, displaySettings.showUpstreamModel,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt,
|
||||
displaySettings.modelDisplayMode, displaySettings.showUpstreamModel,
|
||||
displaySettings.orchestratorIdMode,
|
||||
]);
|
||||
if (lastRenderOptions === renderOptions && lastRenderedRows &&
|
||||
@@ -184,13 +190,14 @@ export const StepTableWidget = defineComponent({
|
||||
return;
|
||||
}
|
||||
const wantedSet = new Set(colKeys);
|
||||
syncTableHeaderColumns(colKeys);
|
||||
syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt });
|
||||
|
||||
const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge);
|
||||
const cellCtx = {
|
||||
hasSubagents,
|
||||
showAgentBadge,
|
||||
showStepSpeedColor,
|
||||
stepTokenComboFormat: normTokenFmt,
|
||||
effectiveScopes,
|
||||
scopeSigKey: effectiveScopes.join(','),
|
||||
displaySettings,
|
||||
|
||||
@@ -172,6 +172,42 @@ export function formatElapsedSec(seconds) {
|
||||
return `${h}h ${remM}m`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化普通模型显示模式(`'short'` 精简代号 | `'upstream_compact'` 去厂商前缀原始 ID | `'upstream'` 完整原始 ID)。
|
||||
*
|
||||
* @param {unknown} mode
|
||||
* @param {unknown} [legacyShowUpstream]
|
||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
||||
*/
|
||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
if (legacyShowUpstream === true) return 'upstream';
|
||||
return 'short';
|
||||
}
|
||||
|
||||
/**
|
||||
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
|
||||
*
|
||||
* @param {string} rawText
|
||||
* @returns {string}
|
||||
*/
|
||||
export function stripVendorModelPrefix(rawText) {
|
||||
return String(rawText || '')
|
||||
.trim()
|
||||
.replace(/^(?:gemini|claude|gpt)-(?=.+)/i, '');
|
||||
}
|
||||
|
||||
function stripCompactionMarker(rawText) {
|
||||
return String(rawText || '')
|
||||
.replace(/(?:·(?:压缩|compact)|\[自动压缩\]|\[auto[- ]?compact\])\s*$/iu, '')
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。
|
||||
*
|
||||
@@ -188,17 +224,23 @@ export function normalizeOrchestratorIdDisplayMode(mode) {
|
||||
* 规则:
|
||||
* - Orchestrator 系列(`Orchestrator (Carbon)`、`Orchestrator (Argon)`、`gemini-flash-worker-agy` / `M669`)
|
||||
* 独立遵循 `orchestratorIdMode`(`'compact'` 显示 `orchestrator-carbon` / `orchestrator-argon` / `worker-agy-hydrogen`;
|
||||
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型“精简代号 / 原始模型 ID”切换影响;
|
||||
* - 其余普通模型继续按 `showUpstreamModel` 与视图选项切换。
|
||||
* `'full'` 显示带括号标注的完整上游 ID),不受普通模型显示模式影响;
|
||||
* - 其余普通模型遵循 `modelDisplayMode`(`'short'` | `'upstream_compact'` | `'upstream'`,兼容旧版布尔 `showUpstreamModel`);
|
||||
* - 独立拆分 `baseText` 与 `compactionSuffix`(`·压缩`),供步骤表单独保护压缩尾标永不截断。
|
||||
*
|
||||
* @param {object|null|undefined} target
|
||||
* @param {{ showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
|
||||
* @param {{ modelDisplayMode?: string, showUpstreamModel?: boolean, orchestratorIdMode?: string }|boolean} [settings]
|
||||
* @param {{ preferLabelInShort?: boolean, fallback?: string }} [options]
|
||||
* @returns {{ text: string, title: string, isOrchestratorSeries: boolean }}
|
||||
* @returns {{ text: string, baseText: string, compactionSuffix: string, isCompaction: boolean, title: string, isOrchestratorSeries: boolean }}
|
||||
*/
|
||||
export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
const showUpstream =
|
||||
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
|
||||
const modelDisplayMode =
|
||||
typeof settings === 'boolean'
|
||||
? settings
|
||||
? 'upstream'
|
||||
: 'short'
|
||||
: normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel);
|
||||
const showUpstream = modelDisplayMode !== 'short';
|
||||
const orchestratorMode = normalizeOrchestratorIdDisplayMode(
|
||||
typeof settings === 'object' && settings ? settings.orchestratorIdMode : 'compact'
|
||||
);
|
||||
@@ -206,7 +248,14 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
const fallback = options?.fallback ?? t('fmt.unknownModel');
|
||||
|
||||
if (!target || typeof target !== 'object') {
|
||||
return { text: fallback, title: fallback, isOrchestratorSeries: false };
|
||||
return {
|
||||
text: fallback,
|
||||
baseText: fallback,
|
||||
compactionSuffix: '',
|
||||
isCompaction: false,
|
||||
title: fallback,
|
||||
isOrchestratorSeries: false,
|
||||
};
|
||||
}
|
||||
|
||||
const shortText = String(
|
||||
@@ -223,9 +272,12 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
|
||||
const isCompaction =
|
||||
Boolean(target.isCompactionStep) ||
|
||||
/·压缩\s*$/.test(shortText) ||
|
||||
/·压缩\s*$/.test(upstreamText) ||
|
||||
/·压缩\s*$/.test(labelText);
|
||||
/·(?:压缩|compact)\s*$/iu.test(shortText) ||
|
||||
/·(?:压缩|compact)\s*$/iu.test(upstreamText) ||
|
||||
/·(?:压缩|compact)\s*$/iu.test(labelText) ||
|
||||
/\[自动压缩\]\s*$/u.test(labelText);
|
||||
|
||||
const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : '';
|
||||
|
||||
const combined = `${modelKeyText} ${shortText} ${labelText} ${upstreamText} ${responseText}`;
|
||||
const isOrchWorker =
|
||||
@@ -248,27 +300,50 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
compactId = 'orchestrator-argon';
|
||||
fullId = 'gemini-pro-orchestrator-argon (argon-4)';
|
||||
}
|
||||
const suffix = isCompaction ? '·压缩' : '';
|
||||
const text = `${orchestratorMode === 'full' ? fullId : compactId}${suffix}`;
|
||||
const baseText = orchestratorMode === 'full' ? fullId : compactId;
|
||||
const text = `${baseText}${compactionSuffix}`;
|
||||
const multiUpstream =
|
||||
Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
|
||||
? target.upstreamModels.join(' / ')
|
||||
: '';
|
||||
const title = multiUpstream || `${fullId}${suffix}`;
|
||||
return { text, title, isOrchestratorSeries: true };
|
||||
const title = multiUpstream || `${fullId}${compactionSuffix}`;
|
||||
return {
|
||||
text,
|
||||
baseText,
|
||||
compactionSuffix,
|
||||
isCompaction,
|
||||
title,
|
||||
isOrchestratorSeries: true,
|
||||
};
|
||||
}
|
||||
|
||||
const standardText =
|
||||
const rawSelected =
|
||||
(showUpstream
|
||||
? upstreamText || responseText || shortText || labelText
|
||||
: preferLabelInShort
|
||||
? labelText || shortText
|
||||
: shortText || labelText) || fallback;
|
||||
const cleanRawBase = stripCompactionMarker(rawSelected) || fallback;
|
||||
const baseText =
|
||||
modelDisplayMode === 'upstream_compact'
|
||||
? stripVendorModelPrefix(cleanRawBase) || cleanRawBase
|
||||
: cleanRawBase;
|
||||
const text = `${baseText}${compactionSuffix}`;
|
||||
const fullUpstreamWithSuffix = `${cleanRawBase}${compactionSuffix}`;
|
||||
const standardTitle =
|
||||
showUpstream && Array.isArray(target.upstreamModels) && target.upstreamModels.length > 1
|
||||
? target.upstreamModels.join(' / ')
|
||||
: standardText;
|
||||
return { text: standardText, title: standardTitle, isOrchestratorSeries: false };
|
||||
: showUpstream
|
||||
? fullUpstreamWithSuffix
|
||||
: text;
|
||||
return {
|
||||
text,
|
||||
baseText,
|
||||
compactionSuffix,
|
||||
isCompaction,
|
||||
title: standardTitle,
|
||||
isOrchestratorSeries: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -284,7 +359,9 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
||||
export function mergeModelsByDisplayName(models = [], settings = {}, options = {}) {
|
||||
if (!Array.isArray(models) || models.length === 0) return [];
|
||||
const showUpstream =
|
||||
typeof settings === 'boolean' ? settings : Boolean(settings?.showUpstreamModel);
|
||||
typeof settings === 'boolean'
|
||||
? settings
|
||||
: normalizeModelDisplayMode(settings?.modelDisplayMode, settings?.showUpstreamModel) !== 'short';
|
||||
const byDisplay = new Map();
|
||||
|
||||
for (const m of models) {
|
||||
|
||||
@@ -118,7 +118,7 @@ function callViaCdpBridge(bridge, path, { method, body, signal, cdpTimeoutMs })
|
||||
});
|
||||
}
|
||||
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 8000 } = {}) {
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTimeoutMs = 3500 } = {}) {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||
|
||||
@@ -138,43 +138,27 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
signal = requestController.signal;
|
||||
}
|
||||
|
||||
const runRequest = async () => {
|
||||
const execHttpOnce = async (activeBridge) => {
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
|
||||
const fetchFn = sidecar?.fetch
|
||||
? sidecar.fetch.bind(sidecar)
|
||||
: typeof window !== 'undefined' && typeof window.fetch === 'function'
|
||||
? window.fetch.bind(window)
|
||||
: globalThis.fetch.bind(globalThis);
|
||||
|
||||
const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path;
|
||||
const requestUrl = activeBridge ? `http://127.0.0.1:${activeBridge.port}${path}` : path;
|
||||
const headers = {};
|
||||
if (body !== undefined || !bridge) {
|
||||
if (body !== undefined || !activeBridge) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
if (bridge) {
|
||||
headers['X-Usage-Monitor-Token'] = bridge.token;
|
||||
if (bridge.transportMode === 'cdp') {
|
||||
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
|
||||
if (activeBridge) {
|
||||
headers['X-Usage-Monitor-Token'] = activeBridge.token;
|
||||
}
|
||||
}
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetchFn(requestUrl, {
|
||||
const res = await fetchFn(requestUrl, {
|
||||
method: upperMethod,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
} catch (fetchErr) {
|
||||
if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') {
|
||||
throw fetchErr;
|
||||
}
|
||||
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
|
||||
bridge.transportMode = 'cdp';
|
||||
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal, cdpTimeoutMs });
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
@@ -189,9 +173,60 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
if (!res.ok) {
|
||||
throw new Error(data.error || `HTTP ${res.status}`);
|
||||
}
|
||||
if (activeBridge) {
|
||||
activeBridge.transportMode = 'http';
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
const fallbackViaCdpWithRecovery = async (initialBridge) => {
|
||||
initialBridge.transportMode = 'cdp';
|
||||
try {
|
||||
return await callViaCdpBridge(initialBridge, path, {
|
||||
method: upperMethod,
|
||||
body,
|
||||
signal,
|
||||
cdpTimeoutMs,
|
||||
});
|
||||
} catch (cdpErr) {
|
||||
if (signal?.aborted || cdpErr?.name === 'AbortError') {
|
||||
throw cdpErr;
|
||||
}
|
||||
// 热更新或守护重启期间若 CDP 尚未轮询投递,自动重置回 HTTP 并用最新桥接端口重试一次
|
||||
const latestBridge = getWindowBridgeConfig() || initialBridge;
|
||||
latestBridge.transportMode = 'http';
|
||||
return execHttpOnce(latestBridge);
|
||||
}
|
||||
};
|
||||
|
||||
const runRequest = async () => {
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
|
||||
if (bridge && bridge.transportMode === 'cdp') {
|
||||
return fallbackViaCdpWithRecovery(bridge);
|
||||
}
|
||||
|
||||
try {
|
||||
return await execHttpOnce(bridge);
|
||||
} catch (fetchErr) {
|
||||
if (signal?.aborted || fetchErr?.name === 'AbortError') {
|
||||
throw fetchErr;
|
||||
}
|
||||
if (!bridge) {
|
||||
// 辅助栏 Webview 在 Worker 热替换瞬间若有极短暂波动,延迟 180ms 自动无感重试一次
|
||||
if (upperMethod === 'GET') {
|
||||
await new Promise((r) => setTimeout(r, 180));
|
||||
if (!signal?.aborted) {
|
||||
return execHttpOnce(null);
|
||||
}
|
||||
}
|
||||
throw fetchErr;
|
||||
}
|
||||
// 当宿主环境的 CSP connect-src、混合内容策略或瞬态端口切换阻断直连时,切至带 HTTP 自愈恢复的 CDP 通道
|
||||
return fallbackViaCdpWithRecovery(bridge);
|
||||
}
|
||||
};
|
||||
|
||||
const promise = runRequest().finally(() => {
|
||||
if (dedupKey) {
|
||||
inFlightGets.delete(dedupKey);
|
||||
|
||||
@@ -49,6 +49,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'fmt.resetMins': 'Resets in {m}m',
|
||||
'fmt.selectTime': 'Select time',
|
||||
'fmt.unknownModel': 'Unknown model',
|
||||
'fmt.compactionSuffix': '·compact',
|
||||
'fmt.mainAgent': 'Main Agent',
|
||||
'fmt.mainBadge': 'Main',
|
||||
'fmt.subAgent': 'Subagent',
|
||||
@@ -251,6 +252,21 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'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.ioCacheTitle': 'New In {inPart} · Out {outPart} · Cache Read {cachePart}',
|
||||
'steps.tokSeg.context.th': 'Ctx',
|
||||
'steps.tokSeg.context.tip': 'Context',
|
||||
'steps.tokSeg.in.th': 'In',
|
||||
'steps.tokSeg.in.tip': 'New In',
|
||||
'steps.tokSeg.out.th': 'Out',
|
||||
'steps.tokSeg.out.tip': 'Output',
|
||||
'steps.tokSeg.cache.th': 'Cache',
|
||||
'steps.tokSeg.cache.tip': 'Cache Read',
|
||||
'steps.tokSeg.think.th': 'Think',
|
||||
'steps.tokSeg.think.tip': 'Thinking',
|
||||
'steps.tokSeg.reply.th': 'Reply',
|
||||
'steps.tokSeg.reply.tip': 'Reply',
|
||||
'steps.tokSeg.total.th': 'Total',
|
||||
'steps.tokSeg.total.tip': 'Total',
|
||||
'steps.modelCallsShare': '{calls} calls · {pct}%',
|
||||
'steps.modelCallsOnly': '{calls} calls',
|
||||
'steps.modelsSummaryPrefix': '{count} models · ',
|
||||
@@ -276,6 +292,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'stepCol.duration.opt': 'Total Duration (s)',
|
||||
'stepCol.tokens_combo.th': 'Ctx / Think / Reply',
|
||||
'stepCol.tokens_combo.opt': 'Ctx / Think / Reply (Combo)',
|
||||
'stepCol.tokens_io_cache.th': 'In / Out / Cache',
|
||||
'stepCol.tokens_io_cache.opt': 'In / Out / Cache (Combo)',
|
||||
'stepCol.tokens_custom.opt': 'Custom Combo ({fmt})',
|
||||
'stepCol.input_tokens.th': 'Input',
|
||||
'stepCol.input_tokens.opt': 'New Input Tokens',
|
||||
'stepCol.cache_tokens.th': 'CacheTok',
|
||||
@@ -412,6 +431,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
|
||||
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
||||
'settings.str.mountSidebar': 'Sidebar Only',
|
||||
'settings.str.popoverWidthLabel': 'Popover Width',
|
||||
'settings.str.popoverWidthAuto': 'Auto Fit',
|
||||
'settings.str.popoverWidthCustom': 'Custom',
|
||||
'settings.str.popoverWidthHint': 'Auto Fit widens wide tables like Step Records to avoid horizontal scroll; Custom accepts 440–1080 px',
|
||||
'settings.str.multiToggle': 'Active Sessions Pill',
|
||||
'settings.str.cliCapsuleToggle': 'CLI Bottom Capsule',
|
||||
'settings.str.show': 'Show',
|
||||
@@ -438,6 +461,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.str.stepTurnRailToggle': 'Turn Rail & Preview',
|
||||
'settings.str.stepAgentBadgeToggle': 'Main/Sub Agent Badge',
|
||||
'settings.str.stepSpeedColorToggle': 'Speed Multi-Color',
|
||||
'settings.str.stepTokenComboLabel': 'Custom Token Combo Format',
|
||||
'settings.str.stepTokenComboPlaceholder': 'e.g. context:new:cache or in:out:cache',
|
||||
'settings.str.stepTokenComboHint': 'Tokens: context, in/new, out, cache, think, reply, total — separated by : or / (1–4 items)',
|
||||
'settings.str.stepsColsLabel': '"Steps" Visible Columns (Left → Right, min 2, draggable)',
|
||||
'settings.str.addStepCol': 'Add Column ({count}/{max})',
|
||||
'settings.slot.dragHint': 'Drag up or down to reorder',
|
||||
@@ -456,6 +482,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'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.modelUpstreamCompact': 'Trimmed Raw ID (hide gemini- / claude- / gpt-)',
|
||||
'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)',
|
||||
|
||||
@@ -49,6 +49,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'fmt.resetMins': '{m}分钟后重置',
|
||||
'fmt.selectTime': '选择时间',
|
||||
'fmt.unknownModel': '模型未知',
|
||||
'fmt.compactionSuffix': '·压缩',
|
||||
'fmt.mainAgent': '主代理',
|
||||
'fmt.mainBadge': '主',
|
||||
'fmt.subAgent': '子代理',
|
||||
@@ -251,6 +252,21 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'steps.badgeBackAll': '点击切回全部汇总',
|
||||
'steps.badgeFilterAgent': '点击仅过滤查看 {agent}(按住 Ctrl/Shift 可加减多选)',
|
||||
'steps.ctxTitle': '上下文 {ctx} · 思考 {think} · 正文 {resp}',
|
||||
'steps.ioCacheTitle': '新输入 {inPart} · 输出 {outPart} · 缓存读 {cachePart}',
|
||||
'steps.tokSeg.context.th': '上下文',
|
||||
'steps.tokSeg.context.tip': '上下文',
|
||||
'steps.tokSeg.in.th': '输入',
|
||||
'steps.tokSeg.in.tip': '新输入',
|
||||
'steps.tokSeg.out.th': '输出',
|
||||
'steps.tokSeg.out.tip': '输出',
|
||||
'steps.tokSeg.cache.th': '缓存',
|
||||
'steps.tokSeg.cache.tip': '缓存读',
|
||||
'steps.tokSeg.think.th': '思考',
|
||||
'steps.tokSeg.think.tip': '思考',
|
||||
'steps.tokSeg.reply.th': '正文',
|
||||
'steps.tokSeg.reply.tip': '正文',
|
||||
'steps.tokSeg.total.th': '总计',
|
||||
'steps.tokSeg.total.tip': '总计',
|
||||
'steps.modelCallsShare': '{calls}次 · {pct}%',
|
||||
'steps.modelCallsOnly': '{calls}次',
|
||||
'steps.modelsSummaryPrefix': '{count} 模型 · ',
|
||||
@@ -276,6 +292,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'stepCol.duration.opt': '端到端耗时 (s)',
|
||||
'stepCol.tokens_combo.th': '上下文 / 思考 / 正文',
|
||||
'stepCol.tokens_combo.opt': '上下文 / 思考 / 正文 (组合)',
|
||||
'stepCol.tokens_io_cache.th': '输入 / 输出 / 缓存',
|
||||
'stepCol.tokens_io_cache.opt': '输入 / 输出 / 缓存 (组合)',
|
||||
'stepCol.tokens_custom.opt': '自定义组合 ({fmt})',
|
||||
'stepCol.input_tokens.th': '新输入',
|
||||
'stepCol.input_tokens.opt': '新输入 Token',
|
||||
'stepCol.cache_tokens.th': '缓存读',
|
||||
@@ -412,6 +431,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
||||
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
||||
'settings.str.mountSidebar': '仅侧边栏',
|
||||
'settings.str.popoverWidthLabel': '悬浮面板宽度',
|
||||
'settings.str.popoverWidthAuto': '自适应',
|
||||
'settings.str.popoverWidthCustom': '指定宽度',
|
||||
'settings.str.popoverWidthHint': '自适应模式下在调用明细等宽表格视图自动撑宽免水平滚动;指定宽度范围 440~1080 px',
|
||||
'settings.str.multiToggle': '实时运行会话入口',
|
||||
'settings.str.cliCapsuleToggle': 'CLI 底部状态胶囊',
|
||||
'settings.str.show': '显示',
|
||||
@@ -438,6 +461,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.str.stepTurnRailToggle': '对话轮次导轨',
|
||||
'settings.str.stepAgentBadgeToggle': '主/子代理标识',
|
||||
'settings.str.stepSpeedColorToggle': '输出速度多色分级',
|
||||
'settings.str.stepTokenComboLabel': '自定义 Token 组合格式',
|
||||
'settings.str.stepTokenComboPlaceholder': '例如 context:new:cache 或 in:out:cache',
|
||||
'settings.str.stepTokenComboHint': '可用字段:context(上下文)、in/new(新输入)、out(输出)、cache(缓存)、think(思考)、reply(正文)、total(总计),以 : 或 / 分隔(1~4 项)',
|
||||
'settings.str.stepsColsLabel': '「按步查看」显示列 (左 → 右,至少 2 列,可拖拽)',
|
||||
'settings.str.addStepCol': '添加字段 ({count}/{max})',
|
||||
'settings.slot.dragHint': '按住上下拖动调整顺序',
|
||||
@@ -456,6 +482,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.oth.modelFormat': '模型名称格式',
|
||||
'settings.oth.modelShort': '精简代号 (如 argon-4-high)',
|
||||
'settings.oth.modelUpstream': '原始模型 ID (如 gemini-3.8-flash-n)',
|
||||
'settings.oth.modelUpstreamCompact': '去前缀原始 ID (如 3.8-flash-n / sonnet-4-6 / 5.4-mini)',
|
||||
'settings.oth.orchFormat': 'Orchestrator 系列 ID',
|
||||
'settings.oth.orchCompact': '精简代号 (如 orchestrator-argon)',
|
||||
'settings.oth.orchFull': '原始完整 ID (如 gemini-pro-orchestrator)',
|
||||
|
||||
@@ -19,6 +19,11 @@ import {
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
import {
|
||||
DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT,
|
||||
normalizeClientStepTokenComboFormat,
|
||||
parseClientStepTokenComboSegments,
|
||||
} from '../store/telemetryStore.js';
|
||||
|
||||
export const STEP_COLUMN_KEYS = Object.freeze([
|
||||
'step',
|
||||
@@ -28,6 +33,8 @@ export const STEP_COLUMN_KEYS = Object.freeze([
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
@@ -45,6 +52,74 @@ export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([
|
||||
'cost',
|
||||
]);
|
||||
|
||||
function resolveStepTokenParts(st) {
|
||||
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0));
|
||||
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);
|
||||
const totalTok = inTok + cacheTok + outTok;
|
||||
const ctxTok = Math.max(0, Number(st?.contextTokens ?? totalTok));
|
||||
return { inTok, cacheTok, outTok, thinkTok, respTok, totalTok, ctxTok };
|
||||
}
|
||||
|
||||
function formatPartWithOptionalCost(tokCount, costVal) {
|
||||
const countStr = Math.round(Number(tokCount || 0)).toLocaleString();
|
||||
if (costVal != null && Number.isFinite(Number(costVal))) {
|
||||
return `${countStr} (${formatUsd(Number(costVal), { precise: true })})`;
|
||||
}
|
||||
return countStr;
|
||||
}
|
||||
|
||||
export function formatCustomTokenComboHeader(rawFormat) {
|
||||
const segs = parseClientStepTokenComboSegments(rawFormat);
|
||||
return segs.map((seg) => t(`steps.tokSeg.${seg}.th`)).join(' / ');
|
||||
}
|
||||
|
||||
function resolveSegmentDisplay(seg, parts, st) {
|
||||
switch (seg) {
|
||||
case 'context':
|
||||
return {
|
||||
short: formatTokens(parts.ctxTok),
|
||||
tip: `${t('steps.tokSeg.context.tip')} ${Math.round(parts.ctxTok).toLocaleString()}`,
|
||||
};
|
||||
case 'in':
|
||||
return {
|
||||
short: formatTokens(parts.inTok),
|
||||
tip: `${t('steps.tokSeg.in.tip')} ${formatPartWithOptionalCost(parts.inTok, st?.inCostUsd)}`,
|
||||
};
|
||||
case 'out':
|
||||
return {
|
||||
short: formatTokens(parts.outTok),
|
||||
tip: `${t('steps.tokSeg.out.tip')} ${formatPartWithOptionalCost(parts.outTok, st?.outCostUsd)}`,
|
||||
};
|
||||
case 'cache':
|
||||
return {
|
||||
short: formatTokens(parts.cacheTok),
|
||||
tip: `${t('steps.tokSeg.cache.tip')} ${formatPartWithOptionalCost(parts.cacheTok, st?.cacheCostUsd)}`,
|
||||
};
|
||||
case 'think':
|
||||
return {
|
||||
short: formatTokens(parts.thinkTok),
|
||||
tip: `${t('steps.tokSeg.think.tip')} ${Math.round(parts.thinkTok).toLocaleString()}`,
|
||||
};
|
||||
case 'reply':
|
||||
return {
|
||||
short: formatTokens(parts.respTok),
|
||||
tip: `${t('steps.tokSeg.reply.tip')} ${Math.round(parts.respTok).toLocaleString()}`,
|
||||
};
|
||||
case 'total':
|
||||
default:
|
||||
return {
|
||||
short: formatTokens(parts.totalTok),
|
||||
tip: `${t('steps.tokSeg.total.tip')} ${formatPartWithOptionalCost(parts.totalTok, st?.costUsd)}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function formatStepClockTime(createdAtMs) {
|
||||
const ms = Number(createdAtMs || 0);
|
||||
if (!(ms > 0) || !Number.isFinite(ms)) {
|
||||
@@ -96,19 +171,21 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
optLabel: () => t('stepCol.model.opt'),
|
||||
sigPart: (st, ctx) => {
|
||||
const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
return `${disp.text}:${disp.title}`;
|
||||
return `${disp.baseText}:${disp.compactionSuffix}:${disp.title}`;
|
||||
},
|
||||
createCell: () => {
|
||||
const valEl = h('span', {
|
||||
style:
|
||||
'display: inline-block; max-width: 120px; overflow: hidden; text-overflow: ellipsis; vertical-align: bottom;',
|
||||
});
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
const nameEl = h('span', { className: 'step-model-name' });
|
||||
const compactEl = h('span', { className: 'step-model-compact', hidden: true });
|
||||
const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl, compactEl]);
|
||||
const td = h('td', {}, [wrapEl]);
|
||||
return { td, refs: { td, wrapEl, nameEl, compactEl } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
const modelDisplay = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
patchText(refs.valEl, modelDisplay.text);
|
||||
patchText(refs.nameEl, modelDisplay.baseText);
|
||||
const suffix = modelDisplay.compactionSuffix || '';
|
||||
patchText(refs.compactEl, suffix);
|
||||
patchAttr(refs.compactEl, 'hidden', !suffix);
|
||||
patchAttr(refs.td, 'title', modelDisplay.title);
|
||||
},
|
||||
},
|
||||
@@ -203,28 +280,82 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
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);
|
||||
const parts = resolveStepTokenParts(st);
|
||||
patchText(
|
||||
refs.valEl,
|
||||
`${formatTokens(st.contextTokens)} / ${formatTokens(thinkTok)} / ${formatTokens(respTok)}`
|
||||
`${formatTokens(parts.ctxTok)} / ${formatTokens(parts.thinkTok)} / ${formatTokens(parts.respTok)}`
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
t('steps.ctxTitle', {
|
||||
ctx: Math.round(Number(st.contextTokens || 0)),
|
||||
think: Math.round(thinkTok),
|
||||
resp: Math.round(respTok),
|
||||
ctx: Math.round(parts.ctxTok),
|
||||
think: Math.round(parts.thinkTok),
|
||||
resp: Math.round(parts.respTok),
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
tokens_io_cache: {
|
||||
key: 'tokens_io_cache',
|
||||
thLabel: () => t('stepCol.tokens_io_cache.th'),
|
||||
optLabel: () => t('stepCol.tokens_io_cache.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.inputTokens || 0}:${st.outputTokens || 0}:${st.cacheReadTokens || 0}:${st.inCostUsd ?? ''}:${st.outCostUsd ?? ''}:${st.cacheCostUsd ?? ''}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st) => {
|
||||
const parts = resolveStepTokenParts(st);
|
||||
patchText(
|
||||
refs.valEl,
|
||||
`${formatTokens(parts.inTok)} / ${formatTokens(parts.outTok)} / ${formatTokens(parts.cacheTok)}`
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
t('steps.ioCacheTitle', {
|
||||
inPart: formatPartWithOptionalCost(parts.inTok, st?.inCostUsd),
|
||||
outPart: formatPartWithOptionalCost(parts.outTok, st?.outCostUsd),
|
||||
cachePart: formatPartWithOptionalCost(parts.cacheTok, st?.cacheCostUsd),
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
tokens_custom: {
|
||||
key: 'tokens_custom',
|
||||
thLabel: (ctx) => formatCustomTokenComboHeader(ctx?.stepTokenComboFormat),
|
||||
optLabel: (ctx) =>
|
||||
t('stepCol.tokens_custom.opt', {
|
||||
fmt: formatCustomTokenComboHeader(ctx?.stepTokenComboFormat),
|
||||
}),
|
||||
sigPart: (st, ctx) =>
|
||||
`${normalizeClientStepTokenComboFormat(ctx?.stepTokenComboFormat)}:${st.contextTokens || 0}:${st.inputTokens || 0}:${st.cacheReadTokens || 0}:${st.outputTokens || 0}:${st.thinkingTokens || 0}:${st.responseTokens ?? ''}:${st.costUsd ?? ''}`,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
return { td, refs: { td, valEl } };
|
||||
},
|
||||
updateCell: (refs, st, ctx) => {
|
||||
const segs = parseClientStepTokenComboSegments(ctx?.stepTokenComboFormat);
|
||||
const parts = resolveStepTokenParts(st);
|
||||
const rendered = segs.map((seg) => resolveSegmentDisplay(seg, parts, st));
|
||||
patchText(
|
||||
refs.valEl,
|
||||
rendered.map((r) => r.short).join(' / ')
|
||||
);
|
||||
patchAttr(
|
||||
refs.td,
|
||||
'title',
|
||||
rendered.map((r) => r.tip).join(' · ')
|
||||
);
|
||||
},
|
||||
},
|
||||
|
||||
input_tokens: {
|
||||
key: 'input_tokens',
|
||||
thLabel: () => t('stepCol.input_tokens.th'),
|
||||
@@ -314,9 +445,12 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
},
|
||||
});
|
||||
|
||||
export function getStepColumnOptions() {
|
||||
export function getStepColumnOptions(
|
||||
stepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT
|
||||
) {
|
||||
const ctx = { stepTokenComboFormat };
|
||||
return STEP_COLUMN_KEYS.map((key) => ({
|
||||
value: key,
|
||||
label: STEP_COLUMN_REGISTRY[key].optLabel(),
|
||||
label: STEP_COLUMN_REGISTRY[key].optLabel(ctx),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -100,6 +100,7 @@ let feedbackTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let consecutivePollFailures = 0;
|
||||
let inFlightTelemetryPoll = null;
|
||||
let lastReceivedSteps = null;
|
||||
let loopActive = false;
|
||||
@@ -167,6 +168,8 @@ export const CLIENT_STEP_COLUMN_KEYS = Object.freeze([
|
||||
'ttft',
|
||||
'duration',
|
||||
'tokens_combo',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'input_tokens',
|
||||
'cache_tokens',
|
||||
'output_tokens',
|
||||
@@ -184,6 +187,94 @@ export const DEFAULT_CLIENT_STEP_COLUMNS = Object.freeze([
|
||||
'cost',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
||||
|
||||
const CLIENT_STEP_TOKEN_ALIASES = Object.freeze({
|
||||
context: 'context',
|
||||
ctx: 'context',
|
||||
'上下文': 'context',
|
||||
in: 'in',
|
||||
new: 'in',
|
||||
input: 'in',
|
||||
'输入': 'in',
|
||||
'新输入': 'in',
|
||||
out: 'out',
|
||||
output: 'out',
|
||||
'输出': 'out',
|
||||
'总输出': 'out',
|
||||
cache: 'cache',
|
||||
cached: 'cache',
|
||||
cache_read: 'cache',
|
||||
cacheread: 'cache',
|
||||
'缓存': 'cache',
|
||||
'缓存读': 'cache',
|
||||
think: 'think',
|
||||
thinking: 'think',
|
||||
'思考': 'think',
|
||||
reply: 'reply',
|
||||
body: 'reply',
|
||||
resp: 'reply',
|
||||
response: 'reply',
|
||||
text: 'reply',
|
||||
'正文': 'reply',
|
||||
'回复': 'reply',
|
||||
total: 'total',
|
||||
all: 'total',
|
||||
sum: 'total',
|
||||
'总计': 'total',
|
||||
'总token': 'total',
|
||||
});
|
||||
|
||||
export function parseClientStepTokenComboSegments(raw) {
|
||||
const str = String(raw ?? '').trim();
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
if (str) {
|
||||
for (const part of str.split(/[:/,|]+/)) {
|
||||
const key = part.trim().toLowerCase();
|
||||
if (!key) continue;
|
||||
const mapped = Object.prototype.hasOwnProperty.call(CLIENT_STEP_TOKEN_ALIASES, key)
|
||||
? CLIENT_STEP_TOKEN_ALIASES[key]
|
||||
: null;
|
||||
if (!mapped || seen.has(mapped)) continue;
|
||||
seen.add(mapped);
|
||||
out.push(mapped);
|
||||
if (out.length >= 4) break;
|
||||
}
|
||||
}
|
||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
||||
}
|
||||
|
||||
export function normalizeClientStepTokenComboFormat(raw) {
|
||||
return parseClientStepTokenComboSegments(raw).join(':');
|
||||
}
|
||||
|
||||
export const MIN_CLIENT_POPOVER_WIDTH = 440;
|
||||
export const MAX_CLIENT_POPOVER_WIDTH = 1080;
|
||||
export const DEFAULT_CLIENT_POPOVER_WIDTH = 580;
|
||||
|
||||
export function normalizeClientPopoverWidthMode(mode) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
||||
}
|
||||
|
||||
export function normalizeClientPopoverWidth(width) {
|
||||
const num = Number(width);
|
||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_CLIENT_POPOVER_WIDTH;
|
||||
return Math.max(MIN_CLIENT_POPOVER_WIDTH, Math.min(MAX_CLIENT_POPOVER_WIDTH, Math.round(num)));
|
||||
}
|
||||
|
||||
export function normalizeClientModelDisplayMode(mode, legacyShowUpstream) {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
if (legacyShowUpstream === true) return 'upstream';
|
||||
return 'short';
|
||||
}
|
||||
|
||||
function normalizeClientOrderedList(raw, { allowedKeys, defaultItems, minLen, maxLen }) {
|
||||
if (!Array.isArray(raw)) {
|
||||
return [...defaultItems];
|
||||
@@ -281,7 +372,7 @@ export function normalizeClientStepColumns(raw) {
|
||||
allowedKeys: CLIENT_STEP_COLUMN_KEYS,
|
||||
defaultItems: DEFAULT_CLIENT_STEP_COLUMNS,
|
||||
minLen: 2,
|
||||
maxLen: 12,
|
||||
maxLen: CLIENT_STEP_COLUMN_KEYS.length,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -356,7 +447,42 @@ function isEquivalentTelemetry(prev, next) {
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const normModelMode = (mode, legacyShowUpstream) => {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||
return 'upstream_compact';
|
||||
}
|
||||
if (m === 'short') return 'short';
|
||||
return legacyShowUpstream === true ? 'upstream' : 'short';
|
||||
};
|
||||
const normPopMode = (mode) => {
|
||||
const m = String(mode ?? '').trim().toLowerCase();
|
||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
||||
};
|
||||
const normPopW = (w) => {
|
||||
const n = Number(w);
|
||||
return Number.isFinite(n) && n > 0 ? Math.max(440, Math.min(1080, Math.round(n))) : 580;
|
||||
};
|
||||
if (
|
||||
normModelMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !==
|
||||
normModelMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false;
|
||||
if (normPopMode(pSet?.popoverWidthMode) !== normPopMode(nSet?.popoverWidthMode)) {
|
||||
return false;
|
||||
}
|
||||
if (normPopW(pSet?.popoverWidth) !== normPopW(nSet?.popoverWidth)) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
String(pSet?.stepTokenComboFormat ?? 'context:in:cache').trim() !==
|
||||
String(nSet?.stepTokenComboFormat ?? 'context:in:cache').trim()
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const prevOrchIdMode =
|
||||
String(pSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
||||
? 'full'
|
||||
@@ -940,6 +1066,7 @@ async function requestTelemetry(params, force) {
|
||||
}
|
||||
activeBundleVersion = payload.uiBundleVersion;
|
||||
}
|
||||
consecutivePollFailures = 0;
|
||||
|
||||
const latestSt = telemetryStore.getState();
|
||||
const previousAccount = latestSt.telemetry?.account;
|
||||
@@ -980,7 +1107,10 @@ async function requestTelemetry(params, force) {
|
||||
return payload;
|
||||
} catch (err) {
|
||||
if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null;
|
||||
consecutivePollFailures += 1;
|
||||
if (force || consecutivePollFailures >= 2 || !telemetryStore.getState().telemetry) {
|
||||
telemetryStore.setState({ syncState: 'error' });
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
if (force) {
|
||||
@@ -1038,6 +1168,28 @@ export async function saveSettingsPatch(patch) {
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'stepTableColumns')) {
|
||||
safePatch.stepTableColumns = normalizeClientStepColumns(safePatch.stepTableColumns);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'stepTokenComboFormat')) {
|
||||
safePatch.stepTokenComboFormat = normalizeClientStepTokenComboFormat(
|
||||
safePatch.stepTokenComboFormat
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'modelDisplayMode')) {
|
||||
const normDisp = normalizeClientModelDisplayMode(
|
||||
safePatch.modelDisplayMode,
|
||||
safePatch.showUpstreamModel
|
||||
);
|
||||
safePatch.modelDisplayMode = normDisp;
|
||||
safePatch.showUpstreamModel = normDisp !== 'short';
|
||||
} else if (Object.prototype.hasOwnProperty.call(safePatch, 'showUpstreamModel')) {
|
||||
safePatch.showUpstreamModel = Boolean(safePatch.showUpstreamModel);
|
||||
safePatch.modelDisplayMode = safePatch.showUpstreamModel ? 'upstream' : 'short';
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'popoverWidthMode')) {
|
||||
safePatch.popoverWidthMode = normalizeClientPopoverWidthMode(safePatch.popoverWidthMode);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'popoverWidth')) {
|
||||
safePatch.popoverWidth = normalizeClientPopoverWidth(safePatch.popoverWidth);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'orchestratorIdMode')) {
|
||||
safePatch.orchestratorIdMode = normalizeClientOrchestratorIdMode(safePatch.orchestratorIdMode);
|
||||
}
|
||||
|
||||
@@ -549,10 +549,11 @@
|
||||
}
|
||||
|
||||
.wm-popover-panel {
|
||||
--step-model-max-w: 240px;
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(522px, calc(100vw - 24px));
|
||||
width: min(var(--wm-popover-w, 540px), calc(100vw - 24px));
|
||||
height: min(588px, calc(100vh - 54px));
|
||||
max-height: calc(100vh - 54px);
|
||||
display: flex;
|
||||
|
||||
@@ -700,3 +700,52 @@
|
||||
background: color-mix(in srgb, var(--metric-danger) 11%, var(--surface-panel)) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.settings-inline-controls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.settings-text-input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-primary);
|
||||
outline: none;
|
||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.settings-text-input:focus {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.settings-number-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.settings-number-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.settings-number-wrap .settings-text-input {
|
||||
width: 68px;
|
||||
height: 24px;
|
||||
padding: 0 6px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-number-unit {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
@@ -75,6 +75,33 @@
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.step-model-cell {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
max-width: var(--step-model-max-w, 176px);
|
||||
min-width: 0;
|
||||
vertical-align: bottom;
|
||||
}
|
||||
|
||||
.step-model-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.step-model-compact {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--metric-info, var(--accent-primary));
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.step-model-compact[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-panel-header {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
|
||||
@@ -24,6 +24,7 @@ import {
|
||||
formatTokensPrecise,
|
||||
formatUsd,
|
||||
mergeModelsByDisplayName,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
} from '../core/formatters.js';
|
||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||
@@ -527,8 +528,9 @@ export const ConsumptionView = defineComponent({
|
||||
const locale = i18nStore.getState().locale;
|
||||
// 额度与会话状态也会发布遥测更新,只对用量页实际展示的数据重绘。
|
||||
const signature = JSON.stringify([
|
||||
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.showUpstreamModel,
|
||||
slice.orchestratorIdMode, dateSpan, preset?.label || rangeInfo.label, acct,
|
||||
locale, slice.range, slice.customStartMs, slice.customEndMs, slice.modelDisplayMode,
|
||||
slice.showUpstreamModel, slice.orchestratorIdMode, dateSpan,
|
||||
preset?.label || rangeInfo.label, acct,
|
||||
cons.trendSeries, slice.modelBreakdown, cons.sourcesBreakdown,
|
||||
monthlyYear, currentMonthIdx, cons.monthlySeries,
|
||||
]);
|
||||
@@ -642,6 +644,10 @@ export const ConsumptionView = defineComponent({
|
||||
// 3. 同步热门模型列表(按最终展示名称去重归并后按总 Token 数降序排列并执行键值增量对账)
|
||||
const localeSig = i18nStore.getState().locale;
|
||||
const displaySettings = {
|
||||
modelDisplayMode: normalizeModelDisplayMode(
|
||||
slice.modelDisplayMode,
|
||||
slice.showUpstreamModel
|
||||
),
|
||||
showUpstreamModel: Boolean(slice.showUpstreamModel),
|
||||
orchestratorIdMode: slice.orchestratorIdMode,
|
||||
};
|
||||
@@ -728,6 +734,10 @@ export const ConsumptionView = defineComponent({
|
||||
customEndMs: st.customEndMs,
|
||||
consumption: st.telemetry?.consumption,
|
||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||
modelDisplayMode: normalizeModelDisplayMode(
|
||||
st.telemetry?.settings?.modelDisplayMode,
|
||||
st.telemetry?.settings?.showUpstreamModel
|
||||
),
|
||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||
st.telemetry?.settings?.orchestratorIdMode
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
formatTokens,
|
||||
formatUsd,
|
||||
mergeModelsByDisplayName,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeOrchestratorIdDisplayMode,
|
||||
resolveModelDisplayInfo,
|
||||
} from '../core/formatters.js';
|
||||
@@ -26,6 +27,7 @@ import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
|
||||
import {
|
||||
formatAgentLabel,
|
||||
normalizeClientStepColumns,
|
||||
normalizeClientStepTokenComboFormat,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../store/telemetryStore.js';
|
||||
@@ -604,6 +606,10 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
|
||||
const displaySettings = {
|
||||
modelDisplayMode: normalizeModelDisplayMode(
|
||||
slice.modelDisplayMode,
|
||||
slice.showUpstreamModel
|
||||
),
|
||||
showUpstreamModel: Boolean(slice.showUpstreamModel),
|
||||
orchestratorIdMode: slice.orchestratorIdMode,
|
||||
};
|
||||
@@ -729,6 +735,7 @@ export const StepsDetailView = defineComponent({
|
||||
showStepTurnRail: slice.showStepTurnRail === true,
|
||||
showStepAgentBadge: slice.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: slice.showStepSpeedColor === true,
|
||||
stepTokenComboFormat: slice.stepTokenComboFormat,
|
||||
displaySettings,
|
||||
});
|
||||
stepsScroll.refresh();
|
||||
@@ -1045,6 +1052,10 @@ export const StepsDetailView = defineComponent({
|
||||
cascadeId: st.telemetry?.activeConversation?.cascadeId,
|
||||
recentSteps: st.telemetry?.activeConversation?.recentSteps,
|
||||
sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown,
|
||||
modelDisplayMode: normalizeModelDisplayMode(
|
||||
st.telemetry?.settings?.modelDisplayMode,
|
||||
st.telemetry?.settings?.showUpstreamModel
|
||||
),
|
||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||
orchestratorIdMode: normalizeOrchestratorIdDisplayMode(
|
||||
st.telemetry?.settings?.orchestratorIdMode
|
||||
@@ -1052,6 +1063,9 @@ export const StepsDetailView = defineComponent({
|
||||
showStepTurnRail: st.telemetry?.settings?.showStepTurnRail === true,
|
||||
showStepAgentBadge: st.telemetry?.settings?.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: st.telemetry?.settings?.showStepSpeedColor === true,
|
||||
stepTokenComboFormat: normalizeClientStepTokenComboFormat(
|
||||
st.telemetry?.settings?.stepTokenComboFormat
|
||||
),
|
||||
stepTableColumns: st.telemetry?.settings?.stepTableColumns,
|
||||
}),
|
||||
(slice) => {
|
||||
|
||||
@@ -9,6 +9,7 @@ import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
normalizeClientModelDisplayMode,
|
||||
normalizeClientOrchestratorIdMode,
|
||||
rebuildTrajectoryCache,
|
||||
resetAllSettings,
|
||||
@@ -21,6 +22,7 @@ function getStepModelDisplayOptions() {
|
||||
return [
|
||||
{ value: 'short', label: t('settings.oth.modelShort') },
|
||||
{ value: 'upstream', label: t('settings.oth.modelUpstream') },
|
||||
{ value: 'upstream_compact', label: t('settings.oth.modelUpstreamCompact') },
|
||||
];
|
||||
}
|
||||
|
||||
@@ -34,7 +36,7 @@ function getOrchestratorIdDisplayOptions() {
|
||||
export const SettingsOtherTab = defineComponent({
|
||||
name: 'SettingsOtherTab',
|
||||
setup({ onCleanup, getProps }) {
|
||||
let draftShowUpstreamModel = false;
|
||||
let draftModelDisplayMode = 'short';
|
||||
let draftOrchestratorIdMode = 'compact';
|
||||
let latestSettings = null;
|
||||
let contextWindowModels = [];
|
||||
@@ -103,12 +105,15 @@ export const SettingsOtherTab = defineComponent({
|
||||
icon: 'table',
|
||||
options: getStepModelDisplayOptions(),
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextUpstream = val === 'upstream';
|
||||
draftShowUpstreamModel = nextUpstream;
|
||||
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
|
||||
const nextMode = normalizeClientModelDisplayMode(val);
|
||||
draftModelDisplayMode = nextMode;
|
||||
stepModelSelect.setValue(nextMode);
|
||||
showModelFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch({ showUpstreamModel: nextUpstream });
|
||||
await saveSettingsPatch({
|
||||
modelDisplayMode: nextMode,
|
||||
showUpstreamModel: nextMode !== 'short',
|
||||
});
|
||||
showModelFeedback(t('settings.saved'), 1500);
|
||||
} catch {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
@@ -408,10 +413,13 @@ export const SettingsOtherTab = defineComponent({
|
||||
if (!settings) return;
|
||||
latestSettings = settings;
|
||||
contextWindowModels = models;
|
||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||
draftModelDisplayMode = normalizeClientModelDisplayMode(
|
||||
settings.modelDisplayMode,
|
||||
settings.showUpstreamModel
|
||||
);
|
||||
draftOrchestratorIdMode = normalizeClientOrchestratorIdMode(settings.orchestratorIdMode);
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftShowUpstreamModel ? 'upstream' : 'short',
|
||||
modelValue: draftModelDisplayMode,
|
||||
options: getStepModelDisplayOptions(),
|
||||
});
|
||||
orchestratorIdSelect.setProps({
|
||||
@@ -444,7 +452,7 @@ export const SettingsOtherTab = defineComponent({
|
||||
}
|
||||
|
||||
stepModelSelect.setProps({
|
||||
modelValue: draftShowUpstreamModel ? 'upstream' : 'short',
|
||||
modelValue: draftModelDisplayMode,
|
||||
options: getStepModelDisplayOptions(),
|
||||
});
|
||||
orchestratorIdSelect.setProps({
|
||||
|
||||
@@ -23,12 +23,19 @@ import {
|
||||
DEFAULT_CLIENT_HOVER_MODULES,
|
||||
DEFAULT_CLIENT_OVERVIEW_METRICS,
|
||||
DEFAULT_CLIENT_OVERVIEW_MODULES,
|
||||
DEFAULT_CLIENT_POPOVER_WIDTH,
|
||||
DEFAULT_CLIENT_STEP_COLUMNS,
|
||||
DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT,
|
||||
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||
MAX_CLIENT_POPOVER_WIDTH,
|
||||
MIN_CLIENT_POPOVER_WIDTH,
|
||||
normalizeClientHoverModules,
|
||||
normalizeClientOverviewMetrics,
|
||||
normalizeClientOverviewModules,
|
||||
normalizeClientPopoverWidth,
|
||||
normalizeClientPopoverWidthMode,
|
||||
normalizeClientStepColumns,
|
||||
normalizeClientStepTokenComboFormat,
|
||||
normalizeClientTopbarSlots,
|
||||
normalizeClientWindowMountMode,
|
||||
saveSettingsPatch,
|
||||
@@ -76,6 +83,13 @@ function getEnableToggleOptions() {
|
||||
];
|
||||
}
|
||||
|
||||
function getPopoverWidthModeOptions() {
|
||||
return [
|
||||
{ value: 'auto', label: t('settings.str.popoverWidthAuto') },
|
||||
{ value: 'custom', label: t('settings.str.popoverWidthCustom') },
|
||||
];
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -89,6 +103,8 @@ export const SettingsStructureTab = defineComponent({
|
||||
setup({ props, onCleanup }) {
|
||||
let activeThirdTab = normalizeStructureTabKey(uiStore.getState().settingsStructureTab);
|
||||
let draftWindowMountMode = 'dual';
|
||||
let draftPopoverWidthMode = 'auto';
|
||||
let draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH;
|
||||
let draftEnableCliStatusLine = true;
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
@@ -98,6 +114,8 @@ export const SettingsStructureTab = defineComponent({
|
||||
let draftShowStepTurnRail = false;
|
||||
let draftShowStepAgentBadge = true;
|
||||
let draftShowStepSpeedColor = false;
|
||||
let draftStepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
||||
let rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
||||
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
let latestSettings = null;
|
||||
|
||||
@@ -110,6 +128,8 @@ export const SettingsStructureTab = defineComponent({
|
||||
return buildStructurePreviewTelemetry(latestSettings, {
|
||||
windowMountMode: draftWindowMountMode,
|
||||
enableWindowOverlay: draftWindowMountMode !== 'sidebar',
|
||||
popoverWidthMode: draftPopoverWidthMode,
|
||||
popoverWidth: draftPopoverWidth,
|
||||
enableCliStatusLine: draftEnableCliStatusLine,
|
||||
showTopbarMultiSession: draftShowTopbarMulti,
|
||||
topbarCapsuleSlots: draftTopbarSlots,
|
||||
@@ -119,6 +139,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
showStepTurnRail: draftShowStepTurnRail,
|
||||
showStepAgentBadge: draftShowStepAgentBadge,
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
stepTokenComboFormat: draftStepTokenComboFormat,
|
||||
stepTableColumns: draftStepColumns,
|
||||
});
|
||||
}
|
||||
@@ -185,6 +206,14 @@ export const SettingsStructureTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.str.mountMode'),
|
||||
});
|
||||
const popoverWidthLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.popoverWidthLabel'),
|
||||
});
|
||||
const popoverWidthHintEl = h('span', {
|
||||
className: 'settings-hint-text',
|
||||
text: t('settings.str.popoverWidthHint'),
|
||||
});
|
||||
const multiToggleLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.multiToggle'),
|
||||
@@ -214,6 +243,54 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
const popoverWidthInput = h('input', {
|
||||
type: 'number',
|
||||
className: 'settings-text-input',
|
||||
min: String(MIN_CLIENT_POPOVER_WIDTH),
|
||||
max: String(MAX_CLIENT_POPOVER_WIDTH),
|
||||
step: '10',
|
||||
value: String(draftPopoverWidth),
|
||||
'aria-label': t('settings.str.popoverWidthLabel'),
|
||||
onChange: () => {
|
||||
const nextWidth = normalizeClientPopoverWidth(popoverWidthInput.value);
|
||||
draftPopoverWidth = nextWidth;
|
||||
popoverWidthInput.value = String(nextWidth);
|
||||
syncMountSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(mountSection, {
|
||||
popoverWidthMode: draftPopoverWidthMode,
|
||||
popoverWidth: draftPopoverWidth,
|
||||
});
|
||||
},
|
||||
onKeydown: (e) => {
|
||||
if (e?.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
popoverWidthInput.blur();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const popoverWidthNumWrap = h(
|
||||
'span',
|
||||
{ className: 'settings-number-wrap', hidden: draftPopoverWidthMode !== 'custom' },
|
||||
[popoverWidthInput, h('span', { className: 'settings-number-unit', text: 'px' })]
|
||||
);
|
||||
|
||||
const popoverWidthModeToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.popoverWidthLabel'),
|
||||
modelValue: draftPopoverWidthMode,
|
||||
options: getPopoverWidthModeOptions(),
|
||||
onUpdateModelValue: (val) => {
|
||||
draftPopoverWidthMode = normalizeClientPopoverWidthMode(val);
|
||||
syncMountSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(mountSection, {
|
||||
popoverWidthMode: draftPopoverWidthMode,
|
||||
popoverWidth: draftPopoverWidth,
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const multiSessionToggle = SegmentedControl({
|
||||
ariaLabel: t('settings.str.multiToggle'),
|
||||
modelValue: 'show',
|
||||
@@ -267,6 +344,9 @@ export const SettingsStructureTab = defineComponent({
|
||||
badgeText: t('settings.str.mountBadge', { count: draftTopbarSlots.length }),
|
||||
onReset: () => {
|
||||
draftWindowMountMode = 'dual';
|
||||
draftPopoverWidthMode = 'auto';
|
||||
draftPopoverWidth = DEFAULT_CLIENT_POPOVER_WIDTH;
|
||||
popoverWidthInput.value = String(DEFAULT_CLIENT_POPOVER_WIDTH);
|
||||
draftEnableCliStatusLine = true;
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
@@ -277,6 +357,8 @@ export const SettingsStructureTab = defineComponent({
|
||||
{
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
popoverWidthMode: 'auto',
|
||||
popoverWidth: DEFAULT_CLIENT_POPOVER_WIDTH,
|
||||
enableCliStatusLine: true,
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
@@ -288,6 +370,16 @@ export const SettingsStructureTab = defineComponent({
|
||||
mountPreviewCanvas,
|
||||
h('div', { className: 'settings-divider' }),
|
||||
h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
popoverWidthLabelEl,
|
||||
h('div', { className: 'settings-inline-controls' }, [
|
||||
popoverWidthModeToggle.el,
|
||||
popoverWidthNumWrap,
|
||||
]),
|
||||
]),
|
||||
popoverWidthHintEl,
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
multiToggleLabelEl,
|
||||
multiSessionToggle.el,
|
||||
@@ -310,6 +402,14 @@ export const SettingsStructureTab = defineComponent({
|
||||
modelValue: draftWindowMountMode,
|
||||
options: getMountModeOptions(),
|
||||
});
|
||||
popoverWidthModeToggle.setProps({
|
||||
modelValue: draftPopoverWidthMode,
|
||||
options: getPopoverWidthModeOptions(),
|
||||
});
|
||||
patchAttr(popoverWidthNumWrap, 'hidden', draftPopoverWidthMode !== 'custom');
|
||||
if (document?.activeElement !== popoverWidthInput) {
|
||||
popoverWidthInput.value = String(draftPopoverWidth);
|
||||
}
|
||||
multiSessionToggle.setProps({
|
||||
modelValue: draftShowTopbarMulti ? 'show' : 'hide',
|
||||
options: getMultiToggleOptions(),
|
||||
@@ -328,6 +428,8 @@ export const SettingsStructureTab = defineComponent({
|
||||
);
|
||||
const isDefault =
|
||||
draftWindowMountMode === 'dual' &&
|
||||
draftPopoverWidthMode === 'auto' &&
|
||||
draftPopoverWidth === DEFAULT_CLIENT_POPOVER_WIDTH &&
|
||||
draftEnableCliStatusLine === true &&
|
||||
draftShowTopbarMulti === true &&
|
||||
isSameList(draftTopbarSlots, DEFAULT_CLIENT_TOPBAR_SLOTS);
|
||||
@@ -593,6 +695,14 @@ export const SettingsStructureTab = defineComponent({
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepSpeedColorToggle'),
|
||||
});
|
||||
const stepTokenComboLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepTokenComboLabel'),
|
||||
});
|
||||
const stepTokenComboHintEl = h('span', {
|
||||
className: 'settings-hint-text',
|
||||
text: t('settings.str.stepTokenComboHint'),
|
||||
});
|
||||
const stepColsLabelEl = h('span', {
|
||||
className: 'form-label',
|
||||
text: t('settings.str.stepsColsLabel'),
|
||||
@@ -637,11 +747,65 @@ export const SettingsStructureTab = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
function commitStepTokenComboInput() {
|
||||
const rawTrimmed = String(stepTokenComboInput.value || '').trim();
|
||||
const normFmt = normalizeClientStepTokenComboFormat(rawTrimmed);
|
||||
rawStepTokenComboText = normFmt;
|
||||
draftStepTokenComboFormat = normFmt;
|
||||
stepTokenComboInput.value = normFmt;
|
||||
if (rawTrimmed && !draftStepColumns.includes('tokens_custom')) {
|
||||
const comboIdx = draftStepColumns.findIndex(
|
||||
(k) => k === 'tokens_combo' || k === 'tokens_io_cache'
|
||||
);
|
||||
if (comboIdx >= 0) {
|
||||
const nextCols = [...draftStepColumns];
|
||||
nextCols[comboIdx] = 'tokens_custom';
|
||||
draftStepColumns = normalizeClientStepColumns(nextCols);
|
||||
} else {
|
||||
draftStepColumns = normalizeClientStepColumns([...draftStepColumns, 'tokens_custom']);
|
||||
}
|
||||
}
|
||||
syncStepsSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
void persistStructurePatch(stepsSection, {
|
||||
stepTokenComboFormat: draftStepTokenComboFormat,
|
||||
stepTableColumns: draftStepColumns,
|
||||
});
|
||||
}
|
||||
|
||||
const stepTokenComboInput = h('input', {
|
||||
type: 'text',
|
||||
className: 'settings-text-input',
|
||||
spellcheck: 'false',
|
||||
value: rawStepTokenComboText,
|
||||
placeholder: t('settings.str.stepTokenComboPlaceholder'),
|
||||
'aria-label': t('settings.str.stepTokenComboLabel'),
|
||||
onInput: () => {
|
||||
rawStepTokenComboText = stepTokenComboInput.value;
|
||||
draftStepTokenComboFormat = normalizeClientStepTokenComboFormat(rawStepTokenComboText);
|
||||
stepColumnsList.refs.setProps({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
});
|
||||
refreshStepsPreview();
|
||||
},
|
||||
onChange: () => {
|
||||
commitStepTokenComboInput();
|
||||
},
|
||||
onKeydown: (e) => {
|
||||
if (e?.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
stepTokenComboInput.blur();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const stepColumnsList = EditableSlotList({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||
minItems: 2,
|
||||
maxItems: 12,
|
||||
maxItems: 15,
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
onPreview: (previewItems) => {
|
||||
draftStepColumns = normalizeClientStepColumns(previewItems);
|
||||
@@ -666,6 +830,9 @@ export const SettingsStructureTab = defineComponent({
|
||||
draftShowStepTurnRail = false;
|
||||
draftShowStepAgentBadge = true;
|
||||
draftShowStepSpeedColor = false;
|
||||
draftStepTokenComboFormat = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
||||
rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
||||
stepTokenComboInput.value = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
||||
draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||
syncStepsSectionMeta();
|
||||
props.onLayoutChange?.();
|
||||
@@ -675,6 +842,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
showStepTurnRail: false,
|
||||
showStepAgentBadge: true,
|
||||
showStepSpeedColor: false,
|
||||
stepTokenComboFormat: DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT,
|
||||
stepTableColumns: [...DEFAULT_CLIENT_STEP_COLUMNS],
|
||||
},
|
||||
'settings.resetDone'
|
||||
@@ -696,6 +864,11 @@ export const SettingsStructureTab = defineComponent({
|
||||
stepSpeedColorToggle.el,
|
||||
]),
|
||||
h('div', { className: 'settings-divider' }),
|
||||
h('div', { className: 'form-row' }, [
|
||||
stepTokenComboLabelEl,
|
||||
stepTokenComboInput,
|
||||
stepTokenComboHintEl,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [stepColsLabelEl, stepColumnsList.el]),
|
||||
],
|
||||
});
|
||||
@@ -704,10 +877,22 @@ export const SettingsStructureTab = defineComponent({
|
||||
if (!isStructureVisible() || activeThirdTab !== 'steps') return;
|
||||
const mockData = buildDraftTelemetry();
|
||||
const mockSteps = mockData.activeConversation?.recentSteps || [];
|
||||
const previewCols =
|
||||
document?.activeElement === stepTokenComboInput &&
|
||||
String(rawStepTokenComboText || '').trim() &&
|
||||
!draftStepColumns.includes('tokens_custom')
|
||||
? normalizeClientStepColumns(
|
||||
draftStepColumns.some((k) => k === 'tokens_combo' || k === 'tokens_io_cache')
|
||||
? draftStepColumns.map((k) =>
|
||||
k === 'tokens_combo' || k === 'tokens_io_cache' ? 'tokens_custom' : k
|
||||
)
|
||||
: [...draftStepColumns, 'tokens_custom']
|
||||
)
|
||||
: draftStepColumns;
|
||||
stepTablePreview.refs.renderStepTable(
|
||||
mockSteps,
|
||||
'mock-preview-conv',
|
||||
draftStepColumns,
|
||||
previewCols,
|
||||
getEffectiveLocale(),
|
||||
{
|
||||
effectiveScopes: ['all'],
|
||||
@@ -716,6 +901,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
showStepTurnRail: draftShowStepTurnRail,
|
||||
showStepAgentBadge: draftShowStepAgentBadge,
|
||||
showStepSpeedColor: draftShowStepSpeedColor,
|
||||
stepTokenComboFormat: draftStepTokenComboFormat,
|
||||
displaySettings: mockData.settings,
|
||||
}
|
||||
);
|
||||
@@ -734,9 +920,12 @@ export const SettingsStructureTab = defineComponent({
|
||||
modelValue: draftShowStepSpeedColor ? 'on' : 'off',
|
||||
options: getEnableToggleOptions(),
|
||||
});
|
||||
if (document?.activeElement !== stepTokenComboInput) {
|
||||
stepTokenComboInput.value = rawStepTokenComboText;
|
||||
}
|
||||
stepColumnsList.refs.setProps({
|
||||
items: draftStepColumns,
|
||||
options: getStepColumnOptions(),
|
||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||
});
|
||||
stepsSection.refs.setBadge(t('settings.str.stepsBadge', { count: draftStepColumns.length }));
|
||||
@@ -744,6 +933,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
draftShowStepTurnRail === false &&
|
||||
draftShowStepAgentBadge === true &&
|
||||
draftShowStepSpeedColor === false &&
|
||||
draftStepTokenComboFormat === DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT &&
|
||||
isSameList(draftStepColumns, DEFAULT_CLIENT_STEP_COLUMNS);
|
||||
stepsSection.refs.setResetDisabled(isDefault);
|
||||
refreshStepsPreview();
|
||||
@@ -805,6 +995,8 @@ export const SettingsStructureTab = defineComponent({
|
||||
settings.windowMountMode,
|
||||
settings.enableWindowOverlay
|
||||
);
|
||||
draftPopoverWidthMode = normalizeClientPopoverWidthMode(settings.popoverWidthMode);
|
||||
draftPopoverWidth = normalizeClientPopoverWidth(settings.popoverWidth);
|
||||
draftEnableCliStatusLine = settings.enableCliStatusLine !== false;
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
@@ -814,6 +1006,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
draftShowStepTurnRail = settings.showStepTurnRail === true;
|
||||
draftShowStepAgentBadge = settings.showStepAgentBadge !== false;
|
||||
draftShowStepSpeedColor = settings.showStepSpeedColor === true;
|
||||
draftStepTokenComboFormat = normalizeClientStepTokenComboFormat(
|
||||
settings.stepTokenComboFormat
|
||||
);
|
||||
rawStepTokenComboText = draftStepTokenComboFormat;
|
||||
draftStepColumns = normalizeClientStepColumns(settings.stepTableColumns);
|
||||
|
||||
syncMountSectionMeta();
|
||||
@@ -831,6 +1027,9 @@ export const SettingsStructureTab = defineComponent({
|
||||
mountSection.refs.setTitle(t('settings.str.mountSection'));
|
||||
mountSection.refs.setResetLabel(t('settings.resetBtn'));
|
||||
patchText(mountModeLabelEl, t('settings.str.mountMode'));
|
||||
patchText(popoverWidthLabelEl, t('settings.str.popoverWidthLabel'));
|
||||
patchText(popoverWidthHintEl, t('settings.str.popoverWidthHint'));
|
||||
patchAttr(popoverWidthInput, 'aria-label', t('settings.str.popoverWidthLabel'));
|
||||
patchText(multiToggleLabelEl, t('settings.str.multiToggle'));
|
||||
patchText(cliCapsuleLabelEl, t('settings.str.cliCapsuleToggle'));
|
||||
patchText(capsuleSlotsLabelEl, t('settings.str.capsuleSlotsLabel'));
|
||||
@@ -850,6 +1049,10 @@ export const SettingsStructureTab = defineComponent({
|
||||
patchText(stepTurnRailLabelEl, t('settings.str.stepTurnRailToggle'));
|
||||
patchText(stepAgentBadgeLabelEl, t('settings.str.stepAgentBadgeToggle'));
|
||||
patchText(stepSpeedColorLabelEl, t('settings.str.stepSpeedColorToggle'));
|
||||
patchText(stepTokenComboLabelEl, t('settings.str.stepTokenComboLabel'));
|
||||
patchText(stepTokenComboHintEl, t('settings.str.stepTokenComboHint'));
|
||||
patchAttr(stepTokenComboInput, 'placeholder', t('settings.str.stepTokenComboPlaceholder'));
|
||||
patchAttr(stepTokenComboInput, 'aria-label', t('settings.str.stepTokenComboLabel'));
|
||||
patchText(stepColsLabelEl, t('settings.str.stepsColsLabel'));
|
||||
|
||||
syncMountSectionMeta();
|
||||
@@ -894,6 +1097,7 @@ export const SettingsStructureTab = defineComponent({
|
||||
overviewPreviewHost.destroy();
|
||||
stepTablePreview.destroy();
|
||||
windowMountSelect.destroy();
|
||||
popoverWidthModeToggle.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
cliCapsuleToggle.destroy();
|
||||
topbarSlotsList.destroy();
|
||||
|
||||
@@ -2622,6 +2622,33 @@ html[data-standalone="true"] .app-shell {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.step-model-cell {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
max-width: var(--step-model-max-w, 176px);
|
||||
min-width: 0;
|
||||
vertical-align: bottom;
|
||||
}
|
||||
|
||||
.step-model-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
flex: 0 1 auto;
|
||||
}
|
||||
|
||||
.step-model-compact {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--metric-info, var(--accent-primary));
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.step-model-compact[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.steps-panel-header {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
@@ -3952,6 +3979,55 @@ html[data-standalone="true"] .app-shell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.settings-inline-controls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.settings-text-input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-primary);
|
||||
outline: none;
|
||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.settings-text-input:focus {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.settings-number-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.settings-number-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.settings-number-wrap .settings-text-input {
|
||||
width: 68px;
|
||||
height: 24px;
|
||||
padding: 0 6px;
|
||||
text-align: right;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.settings-number-unit {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
/* --- src/styles/overlay.css --- */
|
||||
/*
|
||||
* 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css).
|
||||
@@ -4504,10 +4580,11 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
.wm-popover-panel {
|
||||
--step-model-max-w: 240px;
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(522px, calc(100vw - 24px));
|
||||
width: min(var(--wm-popover-w, 540px), calc(100vw - 24px));
|
||||
height: min(588px, calc(100vh - 54px));
|
||||
max-height: calc(100vh - 54px);
|
||||
display: flex;
|
||||
|
||||
@@ -176,6 +176,6 @@ export function backendHarness({
|
||||
return {ok:true,json:async()=>data};
|
||||
},
|
||||
};
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||
return {...ctx.api,state};
|
||||
}
|
||||
|
||||
@@ -2185,3 +2185,141 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from
|
||||
rmSync(tempRoot, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('v1.5 feedback settings schema: custom token combo DSL, 3-way model display mode, popover width bounds, and Worker hot-reload IPC', async () => {
|
||||
const { Worker } = await import('node:worker_threads');
|
||||
const h = backendHarness({
|
||||
trajectories: {
|
||||
'conv-cost': {
|
||||
trajectory: {
|
||||
steps: [
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
metadata: {
|
||||
createdAt: '2026-11-16T05:00:00Z',
|
||||
completedAt: '2026-11-16T05:00:04Z',
|
||||
firstChunkAt: '2026-11-16T05:00:01Z',
|
||||
generatorModel: 'MODEL_PLACEHOLDER_M526',
|
||||
modelUsage: {
|
||||
model: 'gemini-4-hydrogen-medium',
|
||||
inputTokens: '10000',
|
||||
cacheReadTokens: '40000',
|
||||
outputTokens: '2000',
|
||||
thinkingTokens: '500',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
'conv-cost': { summary: 'Cost Breakdown Session', status: 'CASCADE_RUN_STATUS_IDLE' },
|
||||
},
|
||||
});
|
||||
|
||||
// 1. Custom token combo DSL normalization & aliases
|
||||
assert.deepEqual([...h.parseStepTokenComboSegments('context:new:cache')], [
|
||||
'context',
|
||||
'in',
|
||||
'cache',
|
||||
]);
|
||||
assert.equal(h.normalizeStepTokenComboFormat('in / out / cache'), 'in:out:cache');
|
||||
assert.equal(h.normalizeStepTokenComboFormat('上下文:输入:正文:思考:总计'), 'context:in:reply:think');
|
||||
assert.equal(h.normalizeStepTokenComboFormat('invalid:foo'), 'context:in:cache');
|
||||
|
||||
// 2. 3-way model display mode & legacy showUpstreamModel round-trip
|
||||
assert.equal(h.normalizeModelDisplayMode('upstream_compact', false), 'upstream_compact');
|
||||
assert.equal(h.normalizeModelDisplayMode(undefined, true), 'upstream');
|
||||
assert.equal(h.normalizeModelDisplayMode(undefined, false), 'short');
|
||||
|
||||
const compactRes = h.executeSettingsAction({
|
||||
modelDisplayMode: 'upstream_compact',
|
||||
popoverWidthMode: 'custom',
|
||||
popoverWidth: 1500,
|
||||
stepTokenComboFormat: 'in:out:cache',
|
||||
stepTableColumns: ['step', 'model', 'tokens_io_cache', 'tokens_custom', 'cost'],
|
||||
});
|
||||
assert.equal(compactRes.ok, true);
|
||||
assert.equal(compactRes.updated.modelDisplayMode, 'upstream_compact');
|
||||
assert.equal(compactRes.updated.showUpstreamModel, true);
|
||||
assert.equal(compactRes.updated.popoverWidthMode, 'custom');
|
||||
assert.equal(compactRes.updated.popoverWidth, 1080, 'Clamped to MAX_POPOVER_WIDTH 1080');
|
||||
assert.equal(compactRes.updated.stepTokenComboFormat, 'in:out:cache');
|
||||
assert.deepEqual([...compactRes.updated.stepTableColumns], [
|
||||
'step',
|
||||
'model',
|
||||
'tokens_io_cache',
|
||||
'tokens_custom',
|
||||
'cost',
|
||||
]);
|
||||
|
||||
// Legacy caller passing { showUpstreamModel: false } cleanly resets modelDisplayMode -> 'short'
|
||||
const legacyReset = h.executeSettingsAction({ showUpstreamModel: false, popoverWidth: 320 });
|
||||
assert.equal(legacyReset.updated.modelDisplayMode, 'short');
|
||||
assert.equal(legacyReset.updated.showUpstreamModel, false);
|
||||
assert.equal(legacyReset.updated.popoverWidth, 440, 'Clamped to MIN_POPOVER_WIDTH 440');
|
||||
|
||||
// 3. Display projection retains inCostUsd / outCostUsd / cacheCostUsd for Sub2-style tooltips
|
||||
const dispOut = await h.executeTelemetryAction({
|
||||
conversationId: 'conv-cost',
|
||||
stepDetails: 'display',
|
||||
});
|
||||
const dispPayload = JSON.parse(dispOut.body);
|
||||
const step0 = dispPayload.activeConversation.recentSteps[0];
|
||||
assert.ok(Number.isFinite(step0.inCostUsd) && step0.inCostUsd > 0, 'inCostUsd projected');
|
||||
assert.ok(Number.isFinite(step0.cacheCostUsd) && step0.cacheCostUsd > 0, 'cacheCostUsd projected');
|
||||
assert.ok(Number.isFinite(step0.outCostUsd) && step0.outCostUsd > 0, 'outCostUsd projected');
|
||||
|
||||
// 4. Real Worker isolate (`sidecar-worker.mjs`) handles API IPC & graceful shutdown without parent exit
|
||||
const workerTemp = mkdtempSync(fileURLToPath(new URL('./.worker-test-', import.meta.url)));
|
||||
const workerUrl = new URL('../backend/sidecar-worker.mjs', import.meta.url);
|
||||
const worker = new Worker(workerUrl, {
|
||||
env: {
|
||||
...process.env,
|
||||
USAGE_MONITOR_DATA_DIR: workerTemp,
|
||||
ANTIGRAVITY_GEMINI_DIR: workerTemp,
|
||||
ANTIGRAVITY_LS_ADDRESS: 'test.invalid',
|
||||
},
|
||||
});
|
||||
try {
|
||||
const callWorker = (payload) =>
|
||||
new Promise((resolve, reject) => {
|
||||
const id = Math.random().toString(36).slice(2);
|
||||
const onMsg = (msg) => {
|
||||
if (msg?.id !== id) return;
|
||||
worker.off('message', onMsg);
|
||||
resolve(msg);
|
||||
};
|
||||
worker.on('message', onMsg);
|
||||
worker.once('error', reject);
|
||||
worker.postMessage({ ...payload, id });
|
||||
});
|
||||
|
||||
const saveMsg = await callWorker({
|
||||
type: 'api',
|
||||
pathname: '/api/settings',
|
||||
method: 'POST',
|
||||
data: { modelDisplayMode: 'upstream_compact', stepTokenComboFormat: 'context:new:cache' },
|
||||
});
|
||||
assert.equal(saveMsg.ok, true);
|
||||
assert.equal(saveMsg.response.status, 200);
|
||||
const savedBody = JSON.parse(saveMsg.response.body);
|
||||
assert.equal(savedBody.modelDisplayMode, 'upstream_compact');
|
||||
assert.equal(savedBody.stepTokenComboFormat, 'context:in:cache');
|
||||
|
||||
const rebuildMsg = await callWorker({
|
||||
type: 'api',
|
||||
pathname: '/api/cache/rebuild',
|
||||
method: 'POST',
|
||||
});
|
||||
assert.equal(rebuildMsg.ok, true);
|
||||
assert.equal(rebuildMsg.response.status, 200);
|
||||
|
||||
const ackMsg = await callWorker({ type: 'shutdown' });
|
||||
assert.equal(ackMsg.type, 'shutdown_ack');
|
||||
} finally {
|
||||
await worker.terminate().catch(() => {});
|
||||
rmSync(workerTemp, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1708,25 +1708,39 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
assert.equal(mockSettings.enableWindowOverlay, true, 'enableWindowOverlay persisted back to true');
|
||||
assert.equal(previewCapsuleBar.getAttribute('data-mount-mode'), 'dual');
|
||||
|
||||
// Toggle topbar multi-session switch (show -> hide -> show) and CLI bottom capsule switch (on -> off -> on)
|
||||
// Toggle popover width mode (auto -> custom 640px -> auto), topbar multi-session switch (show -> hide -> show), and CLI bottom capsule switch (on -> off -> on)
|
||||
const topbarSegBtns = sec0.querySelectorAll('.seg-btn');
|
||||
assert.equal(topbarSegBtns.length, 4, 'Topbar multi-session + CLI bottom capsule toggles render 4 buttons');
|
||||
assert.equal(topbarSegBtns.length, 6, 'Popover width + Topbar multi-session + CLI bottom capsule toggles render 6 buttons');
|
||||
const popWidthInput = sec0.querySelector('.settings-text-input');
|
||||
assert.ok(popWidthInput, 'Numeric popover width input exists');
|
||||
topbarSegBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.popoverWidthMode, 'custom', 'Popover width mode switches to custom');
|
||||
popWidthInput.value = '640';
|
||||
popWidthInput.dispatchEvent({ type: 'change', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.popoverWidth, 640, 'Custom popover width persisted');
|
||||
assert.equal(popoverEl.style.width, '640px', 'Popover width immediately reflects custom 640px');
|
||||
topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.popoverWidthMode, 'auto', 'Popover width mode restored to auto');
|
||||
|
||||
topbarSegBtns[3].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(previewMultiBtn.hasAttribute('hidden'), true, 'Preview multi-session button hidden immediately');
|
||||
assert.equal(capsuleHost.getAttribute('data-multi'), 'off');
|
||||
topbarSegBtns[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
topbarSegBtns[2].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');
|
||||
assert.equal(previewMultiBtn.hasAttribute('hidden'), false, 'Preview multi-session button restored immediately');
|
||||
|
||||
topbarSegBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
topbarSegBtns[5].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.enableCliStatusLine, false, 'CLI bottom capsule toggle turns off enableCliStatusLine');
|
||||
topbarSegBtns[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
topbarSegBtns[4].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.enableCliStatusLine, true, 'CLI bottom capsule toggle restores enableCliStatusLine');
|
||||
|
||||
@@ -2029,16 +2043,24 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const modelFormatSelectEl = otherSelects[0];
|
||||
const orchestratorIdSelectEl = otherSelects[1];
|
||||
|
||||
// Toggle stepModelSelect: short -> upstream -> short
|
||||
// Toggle stepModelSelect: short -> upstream -> upstream_compact -> 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.modelDisplayMode, 'upstream');
|
||||
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')[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 30));
|
||||
assert.equal(mockSettings.modelDisplayMode, 'upstream_compact');
|
||||
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.modelDisplayMode, 'short');
|
||||
assert.equal(mockSettings.showUpstreamModel, false);
|
||||
|
||||
// Toggle orchestratorIdSelect: compact -> full
|
||||
@@ -5145,3 +5167,466 @@ test('Standalone Web server enforces loopback/non-loopback security boundaries,
|
||||
await tokenSrv.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP self-healing, trimmed raw model IDs, non-truncating compaction suffix, custom token combo DSL, and adaptive popover width', async () => {
|
||||
const stickyDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-wm-sticky-'));
|
||||
const leaseFile = path.join(stickyDir, 'window-bridge-lease.json');
|
||||
|
||||
// 1. Verify sticky port + token across window-bridge restarts & /api/cache/rebuild support
|
||||
const makeCtrl = () =>
|
||||
createWindowBridgeController({
|
||||
leaseFilePath: leaseFile,
|
||||
getSettingsFn: () => ({ enableWindowOverlay: true, windowMountMode: 'dual' }),
|
||||
getBundleVersionFn: () => 'v-sticky-1',
|
||||
readAssetFn: async () => '',
|
||||
handleApiRequest: async (pathname, method) => ({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ ok: true, pathname, method }),
|
||||
}),
|
||||
});
|
||||
|
||||
const ctrl1 = makeCtrl();
|
||||
let ctrl2 = null;
|
||||
try {
|
||||
const info1 = await ctrl1.ensureBridgeServer();
|
||||
assert.ok(info1.port >= 1024 && info1.token.length === 64);
|
||||
|
||||
// /api/cache/rebuild is allowed over loopback bridge
|
||||
const rebuildRes = await fetch(`http://127.0.0.1:${info1.port}/api/cache/rebuild`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Origin: 'https://127.0.0.1:55111',
|
||||
'Content-Type': 'application/json',
|
||||
'X-Usage-Monitor-Token': info1.token,
|
||||
},
|
||||
body: '{}',
|
||||
});
|
||||
assert.equal(rebuildRes.status, 200);
|
||||
assert.equal((await rebuildRes.json()).pathname, '/api/cache/rebuild');
|
||||
|
||||
// Stop ctrl1 (simulating hot-reload) and start ctrl2 -> rebinds exact same port & token!
|
||||
await ctrl1.stop();
|
||||
ctrl2 = makeCtrl();
|
||||
const info2 = await ctrl2.ensureBridgeServer();
|
||||
assert.equal(info2.port, info1.port, 'Hot-reloaded bridge reuses exact previous port');
|
||||
assert.equal(info2.token, info1.token, 'Hot-reloaded bridge reuses exact previous token');
|
||||
} finally {
|
||||
await ctrl1.stop().catch(() => {});
|
||||
if (ctrl2) await ctrl2.stop().catch(() => {});
|
||||
fs.rmSync(stickyDir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// 2. Verify frontend formatters, non-truncating compaction cell, custom token combo, trimmed model ID, adaptive width & CDP recovery
|
||||
const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
|
||||
const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
|
||||
assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*flex-shrink:\s*0;/, 'Compaction suffix never shrinks/truncates');
|
||||
assert.match(stylesCss, /\.wm-popover-panel\s*\{[^}]*--wm-popover-w,\s*540px/, 'Popover supports dynamic CSS width variable');
|
||||
|
||||
const savedSettings = {
|
||||
language: 'zh-CN',
|
||||
windowMountMode: 'dual',
|
||||
enableWindowOverlay: true,
|
||||
popoverWidthMode: 'auto',
|
||||
popoverWidth: 580,
|
||||
modelDisplayMode: 'upstream_compact',
|
||||
showUpstreamModel: true,
|
||||
orchestratorIdMode: 'compact',
|
||||
stepTokenComboFormat: 'context:in:cache',
|
||||
stepTableColumns: ['step', 'model', 'tps', 'tokens_io_cache', 'tokens_custom', 'cost'],
|
||||
};
|
||||
|
||||
const buildMockPayload = () => ({
|
||||
uiBundleVersion: 'ver-v15',
|
||||
settings: { ...savedSettings },
|
||||
cloudStatus: { currentPluginVersion: '1.5.0', latestPluginVersion: '1.5.0', updateAvailable: false },
|
||||
account: { planName: 'Google AI Ultra' },
|
||||
quotas: { activePool: { remainingPct: 62 }, pools: [], weekly: {} },
|
||||
runningConversations: [],
|
||||
conversations: [{ cascadeId: '11111111-2222-3333-4444-555555555555', title: 'v1.5 Test', stepCount: 3 }],
|
||||
activeConversation: {
|
||||
cascadeId: '11111111-2222-3333-4444-555555555555',
|
||||
title: 'v1.5 Test',
|
||||
isRunning: false,
|
||||
stepCount: 3,
|
||||
latestTokPerSec: 140.6,
|
||||
latestTtftSec: 1.2,
|
||||
context: { totalTokens: 50000, compactionLimitTokens: 256000, limitTokens: 256000 },
|
||||
recentSteps: [
|
||||
{
|
||||
stepIndex: 51,
|
||||
isCompactionStep: true,
|
||||
modelShort: 'hydrogen-4·压缩',
|
||||
modelLabel: 'Gemini 4 Hydrogen [自动压缩]',
|
||||
modelUpstream: 'gemini-4-hydrogen·压缩',
|
||||
tokPerSec: 191.3,
|
||||
ttftSec: null,
|
||||
contextTokens: 133100,
|
||||
inputTokens: 2500,
|
||||
cacheReadTokens: 128000,
|
||||
outputTokens: 2600,
|
||||
thinkingTokens: 698,
|
||||
responseTokens: 1902,
|
||||
cacheHitPct: 98.1,
|
||||
costUsd: 0.042,
|
||||
inCostUsd: 0.0038,
|
||||
cacheCostUsd: 0.0192,
|
||||
outCostUsd: 0.0195,
|
||||
createdAtMs: 1794800051000,
|
||||
},
|
||||
{
|
||||
stepIndex: 50,
|
||||
isCompactionStep: false,
|
||||
modelShort: 'sonnet',
|
||||
modelLabel: 'Claude Sonnet 4.6',
|
||||
modelUpstream: 'claude-sonnet-4-6',
|
||||
tokPerSec: 84.0,
|
||||
ttftSec: 1.4,
|
||||
contextTokens: 60000,
|
||||
inputTokens: 10000,
|
||||
cacheReadTokens: 49000,
|
||||
outputTokens: 1000,
|
||||
thinkingTokens: 200,
|
||||
responseTokens: 800,
|
||||
cacheHitPct: 83.1,
|
||||
costUsd: 0.059,
|
||||
inCostUsd: 0.03,
|
||||
cacheCostUsd: 0.0147,
|
||||
outCostUsd: 0.015,
|
||||
createdAtMs: 1794800020000,
|
||||
},
|
||||
{
|
||||
stepIndex: 49,
|
||||
isCompactionStep: false,
|
||||
modelShort: 'gpt-5.4-mini',
|
||||
modelLabel: 'GPT 5.4 Mini',
|
||||
modelUpstream: 'gpt-5.4-mini',
|
||||
tokPerSec: 112.0,
|
||||
ttftSec: 0.9,
|
||||
contextTokens: 40000,
|
||||
inputTokens: 5000,
|
||||
cacheReadTokens: 34000,
|
||||
outputTokens: 1000,
|
||||
thinkingTokens: 100,
|
||||
responseTokens: 900,
|
||||
cacheHitPct: 87.2,
|
||||
costUsd: 0.011,
|
||||
inCostUsd: 0.0038,
|
||||
cacheCostUsd: 0.0026,
|
||||
outCostUsd: 0.0045,
|
||||
createdAtMs: 1794800000000,
|
||||
},
|
||||
],
|
||||
agents: [],
|
||||
},
|
||||
consumption: {
|
||||
selectedRange: { key: 'today', label: '今天', startMs: 1, endMs: 2 },
|
||||
session: {},
|
||||
account: {},
|
||||
trendSeries: [],
|
||||
monthlySeries: [],
|
||||
},
|
||||
modelBreakdown: [],
|
||||
});
|
||||
|
||||
function makeLiteElem(tag) {
|
||||
const attrs = new Map();
|
||||
const classes = new Set();
|
||||
const styleProps = new Map();
|
||||
const listeners = new Map();
|
||||
let ownText = '';
|
||||
const el = {
|
||||
tagName: String(tag || 'div').toUpperCase(),
|
||||
nodeType: 1,
|
||||
id: '',
|
||||
value: '',
|
||||
dataset: {},
|
||||
children: [],
|
||||
parentNode: null,
|
||||
parentElement: null,
|
||||
shadowRoot: null,
|
||||
clientWidth: 0,
|
||||
offsetWidth: 0,
|
||||
scrollWidth: 0,
|
||||
get firstChild() { return el.children[0] || null; },
|
||||
get lastChild() { return el.children[el.children.length - 1] || null; },
|
||||
get textContent() {
|
||||
if (el.children.length === 0) return ownText;
|
||||
return el.children.map((c) => c.textContent ?? '').join('');
|
||||
},
|
||||
set textContent(v) {
|
||||
el.children = [];
|
||||
ownText = String(v ?? '');
|
||||
},
|
||||
style: {
|
||||
width: '',
|
||||
height: '',
|
||||
maxHeight: '',
|
||||
top: '',
|
||||
left: '',
|
||||
right: '',
|
||||
display: '',
|
||||
setProperty(k, v) { styleProps.set(k, String(v)); },
|
||||
getPropertyValue(k) { return styleProps.get(k) || ''; },
|
||||
removeProperty(k) { styleProps.delete(k); },
|
||||
},
|
||||
classList: {
|
||||
add(...names) { for (const n of names) if (n) classes.add(n); },
|
||||
remove(...names) { for (const n of names) classes.delete(n); },
|
||||
toggle(n, force) {
|
||||
const add = force === undefined ? !classes.has(n) : Boolean(force);
|
||||
if (add) classes.add(n); else classes.delete(n);
|
||||
return add;
|
||||
},
|
||||
contains(n) { return classes.has(n); },
|
||||
},
|
||||
get className() { return [...classes].join(' '); },
|
||||
set className(v) {
|
||||
classes.clear();
|
||||
for (const p of String(v || '').split(/\s+/)) if (p) classes.add(p);
|
||||
},
|
||||
setAttribute(k, v) {
|
||||
attrs.set(k, String(v));
|
||||
if (k === 'id') el.id = String(v);
|
||||
if (k === 'class') el.className = String(v);
|
||||
},
|
||||
getAttribute(k) { return attrs.has(k) ? attrs.get(k) : null; },
|
||||
removeAttribute(k) { attrs.delete(k); },
|
||||
hasAttribute(k) { return attrs.has(k); },
|
||||
appendChild(child) {
|
||||
if (!child) return child;
|
||||
if (child.parentNode?.removeChild) child.parentNode.removeChild(child);
|
||||
child.parentNode = el;
|
||||
child.parentElement = el;
|
||||
el.children.push(child);
|
||||
return child;
|
||||
},
|
||||
insertBefore(child, ref) {
|
||||
if (!ref) return el.appendChild(child);
|
||||
if (child.parentNode?.removeChild) child.parentNode.removeChild(child);
|
||||
const idx = el.children.indexOf(ref);
|
||||
child.parentNode = el;
|
||||
child.parentElement = el;
|
||||
if (idx >= 0) el.children.splice(idx, 0, child);
|
||||
else el.children.push(child);
|
||||
return child;
|
||||
},
|
||||
removeChild(child) {
|
||||
const idx = el.children.indexOf(child);
|
||||
if (idx >= 0) {
|
||||
el.children.splice(idx, 1);
|
||||
child.parentNode = null;
|
||||
child.parentElement = null;
|
||||
}
|
||||
return child;
|
||||
},
|
||||
remove() {
|
||||
if (el.parentNode?.removeChild) el.parentNode.removeChild(el);
|
||||
},
|
||||
contains(target) {
|
||||
let cur = target;
|
||||
while (cur) {
|
||||
if (cur === el) return true;
|
||||
cur = cur.parentNode;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
attachShadow() {
|
||||
const sr = makeLiteElem('shadow-root');
|
||||
el.shadowRoot = sr;
|
||||
return sr;
|
||||
},
|
||||
addEventListener(type, fn) {
|
||||
if (!listeners.has(type)) listeners.set(type, []);
|
||||
listeners.get(type).push(fn);
|
||||
},
|
||||
removeEventListener() {},
|
||||
dispatchEvent(ev) {
|
||||
for (const fn of listeners.get(ev.type) || []) fn(ev);
|
||||
},
|
||||
getBoundingClientRect() {
|
||||
const w = Number.parseFloat(el.style.width) || el.offsetWidth || 120;
|
||||
return { left: 900, right: 900 + w, top: 8, bottom: 36, width: w, height: 28 };
|
||||
},
|
||||
querySelectorAll(sel) {
|
||||
const out = [];
|
||||
const parts = String(sel).trim().split(/\s+/);
|
||||
const matchesSimple = (node, s) => {
|
||||
if (s.startsWith('#')) return node.id === s.slice(1);
|
||||
if (s.startsWith('.')) {
|
||||
return s.slice(1).split('.').filter(Boolean).every((c) => node.classList.contains(c));
|
||||
}
|
||||
return node.tagName.toLowerCase() === s.toLowerCase();
|
||||
};
|
||||
const matchesChain = (node, idx) => {
|
||||
if (!matchesSimple(node, parts[idx])) return false;
|
||||
if (idx === 0) return true;
|
||||
let p = node.parentElement;
|
||||
while (p) {
|
||||
if (matchesChain(p, idx - 1)) return true;
|
||||
p = p.parentElement;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
const walk = (root) => {
|
||||
for (const ch of root.children || []) {
|
||||
if (matchesChain(ch, parts.length - 1)) out.push(ch);
|
||||
walk(ch);
|
||||
}
|
||||
};
|
||||
walk(el);
|
||||
return out;
|
||||
},
|
||||
querySelector(sel) {
|
||||
return el.querySelectorAll(sel)[0] || null;
|
||||
},
|
||||
};
|
||||
return el;
|
||||
}
|
||||
|
||||
const body = makeLiteElem('body');
|
||||
const head = makeLiteElem('head');
|
||||
let failHttpOnce = false;
|
||||
const mockWin = {
|
||||
innerWidth: 1280,
|
||||
innerHeight: 820,
|
||||
location: { pathname: '/c/11111111-2222-3333-4444-555555555555', search: '' },
|
||||
__AGUsageMonitorBridge: {
|
||||
port: 43111,
|
||||
token: 'a'.repeat(64),
|
||||
bundleVersion: 'ver-v15',
|
||||
stylesCss,
|
||||
initialTelemetry: buildMockPayload(),
|
||||
},
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
getComputedStyle: () => ({ getPropertyValue: () => '', display: 'flex', flexDirection: 'row' }),
|
||||
fetch: async (_url, opts) => {
|
||||
if (failHttpOnce) {
|
||||
throw new TypeError('Connection refused during transient restart');
|
||||
}
|
||||
if (opts?.method === 'POST' && opts?.body) {
|
||||
Object.assign(savedSettings, JSON.parse(opts.body));
|
||||
return { ok: true, status: 200, json: async () => ({ ...savedSettings }) };
|
||||
}
|
||||
return { ok: true, status: 200, json: async () => buildMockPayload() };
|
||||
},
|
||||
};
|
||||
const mockDoc = {
|
||||
hidden: false,
|
||||
body,
|
||||
head,
|
||||
documentElement: makeLiteElem('html'),
|
||||
activeElement: null,
|
||||
createElement: (t) => makeLiteElem(t),
|
||||
createElementNS: (_ns, t) => makeLiteElem(t),
|
||||
createTextNode: (txt) => ({ nodeType: 3, textContent: String(txt ?? ''), parentNode: null }),
|
||||
getElementById: (id) => body.children.find((c) => c.id === id) || null,
|
||||
querySelector: (s) => body.querySelector(s),
|
||||
querySelectorAll: (s) => body.querySelectorAll(s),
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
|
||||
const sandbox = {
|
||||
window: mockWin,
|
||||
document: mockDoc,
|
||||
navigator: { language: 'zh-CN' },
|
||||
URLSearchParams,
|
||||
AbortController,
|
||||
queueMicrotask,
|
||||
requestAnimationFrame: (fn) => setTimeout(fn, 0),
|
||||
cancelAnimationFrame: clearTimeout,
|
||||
setTimeout,
|
||||
clearTimeout,
|
||||
setInterval,
|
||||
clearInterval,
|
||||
Promise,
|
||||
Math,
|
||||
Date,
|
||||
JSON,
|
||||
Number,
|
||||
String,
|
||||
Boolean,
|
||||
Array,
|
||||
Object,
|
||||
Map,
|
||||
Set,
|
||||
WeakMap,
|
||||
RegExp,
|
||||
Error,
|
||||
TypeError,
|
||||
parseFloat,
|
||||
parseInt,
|
||||
isNaN,
|
||||
};
|
||||
sandbox.globalThis = sandbox;
|
||||
vm.runInNewContext(appJs, sandbox);
|
||||
|
||||
const ov = mockWin.__AGUsageMonitorOverlay;
|
||||
assert.ok(ov, 'Overlay mounted');
|
||||
try {
|
||||
ov.open();
|
||||
const portalHost = mockDoc.getElementById('ag-usage-monitor-portal');
|
||||
const popEl = portalHost.shadowRoot.querySelector('.wm-popover-panel');
|
||||
assert.equal(popEl.style.width, '540px', 'Base overview width starts at 540px');
|
||||
|
||||
// Switch to Steps tab (index 2 of top pill nav)
|
||||
const navPills = popEl.querySelectorAll('.pill-tab');
|
||||
const tableViewport = popEl.querySelector('.table-viewport.is-step-table');
|
||||
const stepTable = tableViewport.querySelector('.steps-data-table');
|
||||
tableViewport.clientWidth = 506;
|
||||
popEl.offsetWidth = 540;
|
||||
stepTable.scrollWidth = 660;
|
||||
stepTable.offsetWidth = 660;
|
||||
|
||||
navPills[2].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 25));
|
||||
|
||||
// Adaptive width expands popover to fit wide 660px table (+ 34px chrome + 4px buffer = 698px)
|
||||
assert.equal(popEl.style.width, '698px', 'Popover adaptively widens on wide step table to eliminate horizontal scroll');
|
||||
|
||||
// Verify trimmed raw IDs (hiding gemini-, claude-, gpt-) AND non-truncating compaction suffix
|
||||
const bodyRows = stepTable.querySelector('tbody').querySelectorAll('tr');
|
||||
assert.equal(bodyRows.length, 3);
|
||||
|
||||
const row0ModelName = bodyRows[0].querySelector('.step-model-name').textContent;
|
||||
const row0Compact = bodyRows[0].querySelector('.step-model-compact');
|
||||
assert.equal(row0ModelName, '4-hydrogen', 'Strips gemini- prefix from gemini-4-hydrogen');
|
||||
assert.equal(row0Compact.hasAttribute('hidden'), false, 'Compaction badge visible as dedicated flex-shrink:0 span');
|
||||
assert.equal(row0Compact.textContent, '·压缩', 'Compaction suffix never merged into ellipsized span');
|
||||
assert.equal(bodyRows[0].children[1].getAttribute('title'), 'gemini-4-hydrogen·压缩', 'Hover title keeps full upstream ID');
|
||||
|
||||
assert.equal(bodyRows[1].querySelector('.step-model-name').textContent, 'sonnet-4-6', 'Strips claude- prefix');
|
||||
assert.equal(bodyRows[1].querySelector('.step-model-compact').hasAttribute('hidden'), true);
|
||||
assert.equal(bodyRows[2].querySelector('.step-model-name').textContent, '5.4-mini', 'Strips gpt- prefix');
|
||||
|
||||
// Verify In / Out / Cache column & Custom Combo column ('context:in:cache')
|
||||
const ths = stepTable.querySelector('thead').querySelectorAll('th');
|
||||
assert.equal(ths[3].textContent, '输入 / 输出 / 缓存');
|
||||
assert.equal(ths[4].textContent, '上下文 / 输入 / 缓存');
|
||||
assert.equal(bodyRows[0].children[3].children[0].textContent, '2.5k / 2.6k / 128.0k');
|
||||
assert.equal(
|
||||
bodyRows[0].children[3].getAttribute('title'),
|
||||
'新输入 2,500 ($0.004) · 输出 2,600 ($0.019) · 缓存读 128,000 ($0.019)'
|
||||
);
|
||||
assert.equal(bodyRows[0].children[4].children[0].textContent, '133.1k / 2.5k / 128.0k');
|
||||
|
||||
// Switch back to Live Overview -> popover smoothly shrinks back to 540px
|
||||
navPills[0].dispatchEvent({ type: 'click', stopPropagation() {} });
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
assert.equal(popEl.style.width, '540px', 'Popover returns to 540px base width when leaving wide step table');
|
||||
|
||||
// Verify p0-1 updateBridge resets poisoned 'cdp' transportMode back to 'http' immediately
|
||||
failHttpOnce = true;
|
||||
mockWin.location.pathname = '/c/99999999-2222-3333-4444-555555555555';
|
||||
ov.syncHostRoute();
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
assert.equal(mockWin.__AGUsageMonitorBridge.transportMode, 'cdp');
|
||||
failHttpOnce = false;
|
||||
ov.updateBridge({ port: 43222, token: 'b'.repeat(64) });
|
||||
assert.equal(mockWin.__AGUsageMonitorBridge.transportMode, 'http', 'updateBridge immediately heals transportMode back to http');
|
||||
} finally {
|
||||
ov.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user