diff --git a/plugin.json b/plugin.json index 9296f1d..1342256 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "usage-monitor", "displayName": "Usage & Speed Monitor", - "version": "1.5.0", + "version": "1.5.1", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "logo": "assets/logo.svg", "suggestedPrompts": [ diff --git a/pricing-catalog.json b/pricing-catalog.json index f1d8808..7f2b7ab 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,26 +1,28 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.17.1", - "updatedAt": "2026-11-17T00:15:00+09:00", - "latestPluginVersion": "1.5.0", + "catalogVersion": "2026.11.17.4", + "updatedAt": "2026-11-17T20:00:00+09:00", + "latestPluginVersion": "1.5.1", "releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main", "pricing": { - "gemini-pro-orchestrator": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" }, - "orchestrator-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" }, - "gemini-pro-orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini" }, - "orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini" }, - "gemini-4-carbon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-high", "family": "Gemini" }, - "gemini-4-carbon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini" }, - "gemini-4-carbon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-low", "family": "Gemini" }, - "gemini-4-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini" }, - "gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini" }, - "gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" }, - "gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini" }, - "gemini-4-argon-f": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" }, - "gemini-4-argon-disabled": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" }, - "gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" }, + "gemini-pro-orchestrator": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "orchestrator-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-pro-orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-carbon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-high", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-carbon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-carbon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-low", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-b": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-f": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-trial": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon-disabled": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, + "gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] }, "gemini-4-hydrogen-xhigh": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-xhigh", "family": "Gemini" }, "gemini-4-hydrogen-high": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-high", "family": "Gemini" }, "gemini-4-hydrogen-medium": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" }, @@ -42,22 +44,22 @@ "gemini-helix-medium": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix", "family": "Gemini" }, "gemini-helix-low": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix-low", "family": "Gemini" }, "gemini-helix": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix", "family": "Gemini" }, - "gemini-3.8-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8-high", "family": "Gemini" }, - "gemini-3.8-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" }, + "gemini-3.8-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8-high", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.8-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, "gemini-3.8-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.8-low", "family": "Gemini" }, - "gemini-3.8-flash-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" }, - "gemini-3.8-flash-n": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" }, - "gemini-3.8-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" }, - "gemini-3.7-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7-high", "family": "Gemini" }, - "gemini-3.7-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" }, + "gemini-3.8-flash-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.8-flash-n": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.8-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.7-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7-high", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.7-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, "gemini-3.7-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.7-low", "family": "Gemini" }, - "gemini-3.7-flash-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" }, - "gemini-3.7-flash-safety-le": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" }, - "gemini-3.7-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" }, - "gemini-3.6-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6-high", "family": "Gemini" }, - "gemini-3.6-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini" }, + "gemini-3.7-flash-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.7-flash-safety-le": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.7-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.6-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6-high", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, + "gemini-3.6-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, "gemini-3.6-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.6-low", "family": "Gemini" }, - "gemini-3.6-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini" }, + "gemini-3.6-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] }, "gemini-3.5-flash-high": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5-high", "family": "Gemini" }, "gemini-3.5-flash-medium": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" }, "gemini-3.5-flash-low": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5-low", "family": "Gemini" }, diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 7e45c4a..4d62a6d 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -1,7 +1,748 @@ (() => { 'use strict'; +// --- shared/settings-normalization.mjs --- +const { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort } = (() => { +/** + * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 + */ + +const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']); + +const THEME_ACCENT_KEYS = Object.freeze([ + 'host', + 'blue', + 'emerald', + 'amber', + 'violet', + 'cyan', + 'rose', +]); + +const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']); + +const TOPBAR_SLOT_KEYS = Object.freeze([ + 'context', + 'tps', + 'ttft', + 'avg_tps', + 'cost', + 'session_cost', + 'cache_hit', + 'session_tokens', + 'quota_auto', + 'gemini_5h', + 'gemini_weekly', + 'claude_5h', + 'claude_weekly', +]); + +const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); +const MIN_TOPBAR_SLOTS = 1; +const MAX_TOPBAR_SLOTS = 5; + +const OVERVIEW_MODULE_KEYS = Object.freeze([ + 'metrics', + 'context', + 'quotas', + 'live_tasks', +]); + +const DEFAULT_OVERVIEW_MODULES = Object.freeze([ + 'metrics', + 'context', + 'quotas', + 'live_tasks', +]); + +const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']); + +const OVERVIEW_METRIC_KEYS = Object.freeze([ + 'tps', + 'ttft', + 'avg_tps', + 'step_cost', + 'session_cost', + 'cache_hit', + 'session_tokens', + 'context_usage', + 'quota_tightest', +]); + +const DEFAULT_OVERVIEW_METRICS = Object.freeze([ + 'tps', + 'ttft', + 'avg_tps', + 'step_cost', +]); + +const STEP_TABLE_COLUMN_KEYS = Object.freeze([ + 'step', + 'time', + 'model', + 'tps', + 'ttft', + 'duration', + 'tokens_combo', + 'tokens_io_cache', + 'tokens_custom', + 'input_tokens', + 'cache_tokens', + 'output_tokens', + 'cache', + 'cost', +]); + +const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([ + 'step', + 'model', + 'tps', + 'ttft', + 'tokens_combo', + 'cache', + 'cost', +]); + +const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache'; + +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', +}); + +const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']); +const MIN_POPOVER_WIDTH = 440; +const MAX_POPOVER_WIDTH = 1080; +const DEFAULT_POPOVER_WIDTH = 580; + +/** + * 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。 + * + * @param {unknown} lang + * @returns {'auto'|'zh-CN'|'en-US'} + */ +function normalizeLanguageSetting(lang) { + const raw = String(lang ?? '').trim(); + if (!raw) return 'zh-CN'; + const lower = raw.toLowerCase(); + if (lower === 'auto' || lower === 'system') return 'auto'; + if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; + if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; + return 'zh-CN'; +} + +/** + * 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。 + * + * @param {unknown} accent + * @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'} + */ +function normalizeThemeAccent(accent) { + const clean = String(accent ?? '').trim().toLowerCase(); + return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host'; +} + +/** + * 归一化面板字号档位(默认 `'md'` 标准 100%)。 + * + * @param {unknown} scale + * @returns {'sm'|'md'|'lg'|'xl'} + */ +function normalizeFontScale(scale) { + const clean = String(scale ?? '').trim().toLowerCase(); + return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md'; +} + +/** + * 归一化模型名称展示模式(`'short'` | `'upstream_compact'` | `'upstream'`),兼容历史 `showUpstreamModel`。 + * + * @param {unknown} mode + * @param {unknown} [legacyShowUpstream] + * @returns {'short'|'upstream_compact'|'upstream'} + */ +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'`,默认 `'compact'`)。 + * + * @param {unknown} mode + * @returns {'compact'|'full'} + */ +function normalizeOrchestratorIdMode(mode) { + return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact'; +} + +/** + * 归一化悬浮主面板宽度模式(`'auto'` | `'custom'`,默认 `'auto'`)。 + * + * @param {unknown} mode + * @returns {'auto'|'custom'} + */ +function normalizePopoverWidthMode(mode) { + const m = String(mode ?? '').trim().toLowerCase(); + return m === 'custom' || m === 'fixed' ? 'custom' : 'auto'; +} + +/** + * 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。 + * + * @param {unknown} width + * @returns {number} + */ +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'>} + */ +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} + */ +function normalizeStepTokenComboFormat(raw) { + return parseStepTokenComboSegments(raw).join(':'); +} + +/** + * 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。 + * + * @param {unknown} mode + * @param {unknown} [legacyAutoUpdate] + * @returns {'off'|'manual'|'auto'} + */ +function normalizePluginUpdateMode(mode, legacyAutoUpdate) { + const m = String(mode ?? '').trim().toLowerCase(); + if (m === 'off' || m === 'manual' || m === 'auto') return m; + if (legacyAutoUpdate === true) return 'auto'; + return 'manual'; +} + +/** + * 归一化面板挂载方式枚举(`'dual'` | `'composer'` | `'sidebar'`),兼容历史 `enableWindowOverlay`。 + * + * @param {unknown} mode + * @param {unknown} [legacyEnableOverlay] + * @returns {'dual'|'composer'|'sidebar'} + */ +function normalizeWindowMountMode(mode, legacyEnableOverlay) { + const m = String(mode ?? '').trim().toLowerCase(); + if (m === 'composer' || m === 'input') return 'composer'; + if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar'; + if (m === 'dual' || m === 'topbar') return 'dual'; + if (legacyEnableOverlay === false) return 'sidebar'; + return 'dual'; +} + +/** + * 归一化每周额度统计模式枚举(`'official'` | `'custom_tokens'` | `'custom_cost'`)。 + * + * @param {unknown} mode + * @returns {'official'|'custom_tokens'|'custom_cost'} + */ +function normalizeWeeklyLimitMode(mode) { + const m = String(mode || '').trim().toLowerCase(); + if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens'; + if (m === 'custom_cost' || m === 'cost') return 'custom_cost'; + return 'official'; +} + +/** + * 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +function normalizeTopbarCapsuleSlots(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_TOPBAR_SLOTS]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!val || val === 'none') continue; + const mapped = val === 'step_cost' ? 'cost' : val; + if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; + seen.add(mapped); + out.push(mapped); + if (out.length >= MAX_TOPBAR_SLOTS) break; + } + if (out.length < MIN_TOPBAR_SLOTS) { + return ['context']; + } + return out; +} + +/** + * 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +function normalizeOverviewMetrics(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_OVERVIEW_METRICS]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const rawVal = String(item ?? '').trim(); + const val = rawVal === 'cost' ? 'step_cost' : rawVal; + if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= 4) break; + } + return out.length > 0 ? out : ['tps']; +} + +/** + * 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +function normalizeOverviewModules(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_OVERVIEW_MODULES]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= OVERVIEW_MODULE_KEYS.length) break; + } + return out.length > 0 ? out : ['metrics']; +} + +/** + * 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +function normalizeHoverModules(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_HOVER_MODULES]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= OVERVIEW_MODULE_KEYS.length) break; + } + return out; +} + +/** + * 归一化调用明细「按步查看」表格列配置与左右顺序(2~14 列,默认保留现有 7 列)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +function normalizeStepTableColumns(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_STEP_TABLE_COLUMNS]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break; + } + if (out.length < 2) { + for (const fallbackCol of ['step', 'model', 'tps']) { + if (!seen.has(fallbackCol)) { + seen.add(fallbackCol); + out.push(fallbackCol); + } + if (out.length >= 2) break; + } + } + return out; +} + +/** + * 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。 + * + * @param {unknown} port + * @returns {number} + */ +function normalizeStandalonePort(port) { + const num = Number(port); + if (!Number.isInteger(num) || num <= 0) return 0; + if (num >= 1024 && num <= 65535) return num; + return 0; +} +return { SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, FONT_SCALE_KEYS, TOPBAR_SLOT_KEYS, DEFAULT_TOPBAR_SLOTS, MIN_TOPBAR_SLOTS, MAX_TOPBAR_SLOTS, OVERVIEW_MODULE_KEYS, DEFAULT_OVERVIEW_MODULES, DEFAULT_HOVER_MODULES, OVERVIEW_METRIC_KEYS, DEFAULT_OVERVIEW_METRICS, STEP_TABLE_COLUMN_KEYS, DEFAULT_STEP_TABLE_COLUMNS, DEFAULT_STEP_TOKEN_COMBO_FORMAT, STEP_TOKEN_SEGMENT_ALIASES, POPOVER_WIDTH_MODES, MIN_POPOVER_WIDTH, MAX_POPOVER_WIDTH, DEFAULT_POPOVER_WIDTH, normalizeLanguageSetting, normalizeThemeAccent, normalizeFontScale, normalizeModelDisplayMode, normalizeOrchestratorIdMode, normalizePopoverWidthMode, normalizePopoverWidth, parseStepTokenComboSegments, normalizeStepTokenComboFormat, normalizePluginUpdateMode, normalizeWindowMountMode, normalizeWeeklyLimitMode, normalizeTopbarCapsuleSlots, normalizeOverviewMetrics, normalizeOverviewModules, normalizeHoverModules, normalizeStepTableColumns, normalizeStandalonePort }; +})(); + +// --- shared/telemetry-display-rules.mjs --- +const { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact } = (() => { +/** + * @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。 + */ + +const THIRD_PARTY_POOL_RE = + /3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i; + +/** + * 判断模型或配额桶文本是否归属第三方模型池(Claude & GPT / OSS / 3P)。 + * + * @param {unknown} text + * @returns {boolean} + */ +function isThirdPartyPoolText(text) { + return THIRD_PARTY_POOL_RE.test(String(text || '')); +} + +/** + * 输出速度四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。 + */ +function classifySpeedTier(tokPerSec) { + if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) { + return 'muted'; + } + const v = Number(tokPerSec); + if (v >= 60) return 'good'; + if (v >= 35) return 'info'; + if (v >= 20) return 'warn'; + return 'danger'; +} + +/** + * 缓存命中率四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。 + */ +function classifyCacheTier(cacheHitPct, promptTokens = null) { + if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) { + return 'muted'; + } + const v = Number(cacheHitPct); + if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) { + return 'muted'; + } + if (v >= 85) return 'good'; + if (v >= 65) return 'info'; + if (v >= 30) return 'warn'; + return 'danger'; +} + +/** + * 单步费用告警色阶分类(`''|'warn'|'danger'`)。 + */ +function classifyStepCostTier(costUsd) { + if (costUsd == null || !Number.isFinite(Number(costUsd))) return ''; + const v = Number(costUsd); + if (v >= 0.3) return 'danger'; + if (v >= 0.15) return 'warn'; + return ''; +} + +/** + * 首字延迟告警色阶分类(`'muted'|''|'warn'|'danger'`)。 + */ +function classifyTtftTier(ttftSec) { + if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) { + return 'muted'; + } + const v = Number(ttftSec); + if (v >= 30) return 'danger'; + if (v >= 18) return 'warn'; + return ''; +} + +function formatCompactTokens(num) { + const n = Number(num || 0); + if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; + if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; + if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; + return String(Math.round(n)); +} + +function formatCompactCapsuleCost(costUsd) { + if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--'; + const val = Math.max(0, Number(costUsd)); + if (val === 0) return '$0.00'; + if (val < 0.001) return '<$0.001'; + if (val < 1) return `$${val.toFixed(3)}`; + if (val < 100) return `$${val.toFixed(2)}`; + return `$${Math.round(val)}`; +} + +function formatCompactCapsuleTtft(ttftSec) { + if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; + const val = Number(ttftSec); + if (val < 1) return `${val.toFixed(2)}s`; + if (val < 100) return `${val.toFixed(1)}s`; + return `${Math.round(val)}s`; +} + +/** + * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * + * @param {object|null|undefined} quotas + * @param {string} slotKey + * @returns {number|null} + */ +function resolveCapsuleQuotaSlotPct(quotas, slotKey) { + if (!quotas || typeof quotas !== 'object') return null; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const activePool = quotas.activePool || null; + const weekly = quotas.weekly || null; + + if (slotKey === 'quota_auto') { + const candidates = []; + if (activePool && Number.isFinite(Number(activePool.remainingPct))) { + candidates.push(Number(activePool.remainingPct)); + } + if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { + candidates.push(Number(activePool.weeklyRemainingPct)); + } + if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { + candidates.push(Number(weekly.remainingPct)); + } + if (!candidates.length && pools.length > 0) { + for (const p of pools) { + if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); + if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { + candidates.push(Number(p.weeklyRemainingPct)); + } + } + } + if (!candidates.length) return null; + return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); + } + + const isClaude = slotKey.startsWith('claude_'); + const isWeekly = slotKey.endsWith('_weekly'); + let rawPct = null; + + if (isClaude) { + const claudePool = + pools.find((p) => p?.poolKey === 'Claude & GPT') || + pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); + const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + if (cand != null && Number.isFinite(Number(cand))) { + rawPct = Number(cand); + } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); + } + } else { + const stdGemini = + pools.find((p) => p?.poolKey === 'Gemini') || + pools.find( + (p) => + /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && + !/carbon|argon/i.test(String(p?.poolKey || '')) + ); + const geminiFamilyPools = pools.filter((p) => + /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) + ); + const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + if (primaryCand != null && Number.isFinite(Number(primaryCand))) { + rawPct = Number(primaryCand); + } else { + const familyVals = geminiFamilyPools + .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .filter((v) => v != null && Number.isFinite(Number(v))) + .map(Number); + if (familyVals.length > 0) { + rawPct = Math.min(...familyVals); + } else if ( + activePool && + !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') + ) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); + } + if ( + rawPct == null && + isWeekly && + weekly && + !isThirdPartyPoolText(weekly.poolFamily || '') && + weekly.remainingPct != null && + Number.isFinite(Number(weekly.remainingPct)) + ) { + rawPct = Number(weekly.remainingPct); + } + } + } + + if (rawPct == null || !Number.isFinite(rawPct)) return null; + return Math.max(0, Math.min(100, Math.round(rawPct))); +} + +/** + * 使用最大余数法(Hamilton 方法)将各非零分桶等比缩放至目标整数总和, + * 保证 0 值通道绝不被凭空分配余数,且缩放后各分桶之和精确等于 `targetTotal`。 + * + * @param {Record} buckets + * @param {readonly string[]} keys + * @param {number} targetTotal + * @returns {Record} + */ +function scaleBucketsExact(buckets, keys, targetTotal) { + const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0))); + const out = {}; + let currentSum = 0; + for (const k of keys) { + const val = Math.max(0, Number(buckets[k] || 0)); + out[k] = val; + currentSum += val; + } + if (safeTarget === 0 || currentSum <= 0) { + for (const k of keys) out[k] = 0; + return out; + } + if (currentSum === safeTarget) { + for (const k of keys) out[k] = Math.round(out[k]); + return out; + } + const remainders = []; + let assigned = 0; + for (const k of keys) { + const rawVal = out[k]; + if (rawVal <= 0) { + out[k] = 0; + continue; + } + const exact = (rawVal * safeTarget) / currentSum; + const floored = Math.floor(exact); + out[k] = floored; + assigned += floored; + remainders.push({ key: k, rem: exact - floored, orig: rawVal }); + } + const diff = safeTarget - assigned; + if (diff > 0 && remainders.length > 0) { + remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig); + for (let i = 0; i < diff; i++) { + out[remainders[i % remainders.length].key] += 1; + } + } + return out; +} +return { THIRD_PARTY_POOL_RE, isThirdPartyPoolText, classifySpeedTier, classifyCacheTier, classifyStepCostTier, classifyTtftTier, formatCompactTokens, formatCompactCapsuleCost, formatCompactCapsuleTtft, resolveCapsuleQuotaSlotPct, scaleBucketsExact }; +})(); + +// --- shared/window-bridge-protocol.mjs --- +const { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge } = (() => { +const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge'; +const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId'; +const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay'; +const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows'; + +const WINDOW_OVERLAY_METHODS = Object.freeze({ + ensureAlive: 'ensureAlive', + getDockKind: 'getDockKind', + getMountMode: 'getMountMode', + updateBridge: 'updateBridge', + applyMountMode: 'applyMountMode', + syncHostRoute: 'syncHostRoute', + deliverRpc: 'deliverRpc', + dispose: 'dispose', +}); + +const BRIDGE_API_ROUTE_DEFS = Object.freeze([ + Object.freeze({ path: '/api/telemetry', method: 'GET', action: 'telemetry' }), + Object.freeze({ path: '/api/settings', method: 'POST', action: 'settings' }), + Object.freeze({ path: '/api/accounts', method: 'GET', action: 'accounts_get' }), + Object.freeze({ path: '/api/accounts/update', method: 'POST', action: 'accounts_update' }), + Object.freeze({ path: '/api/context-window', method: 'POST', action: 'context_window' }), + Object.freeze({ path: '/api/settings/reset', method: 'POST', action: 'settings_reset' }), + Object.freeze({ path: '/api/cache/rebuild', method: 'POST', action: 'cache_rebuild' }), + Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }), + Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }), + Object.freeze({ path: '/api/bridge/relaunch', method: 'POST', action: 'bridge_relaunch' }), +]); + +const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); + +function readInjectedWindowBridge() { + return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY]; +} +return { WINDOW_BRIDGE_KEY, WINDOW_BRIDGE_ROUTE_KEY, WINDOW_OVERLAY_KEY, CONTEXT_WINDOWS_GLOBAL_KEY, WINDOW_OVERLAY_METHODS, BRIDGE_API_ROUTE_DEFS, BRIDGE_API_PATHS, readInjectedWindowBridge }; +})(); + // --- src/icons/svgRegistry.js --- +const { SVG_ICON_DEFS } = (() => { /** * @fileoverview Pure vector SVG icon registry (16x16 grid). * Strictly zero emoji characters anywhere in the codebase. @@ -93,6 +834,10 @@ const SVG_ICON_DEFS = Object.freeze({ close: [ { tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } }, ], + copy: [ + { tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } }, + { tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } }, + ], grip: [ { tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, @@ -102,8 +847,11 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'circle', attrs: { cx: '10', cy: '12', r: '1.05', fill: 'currentColor', stroke: 'none' } }, ], }); +return { SVG_ICON_DEFS }; +})(); // --- src/icons/SvgIcon.js --- +const { SVG_NS, createSvgIcon, patchSvgIcon } = (() => { /** * @fileoverview Dynamic SVG icon component and incremental icon patcher. */ @@ -149,8 +897,11 @@ function patchSvgIcon(svgEl, name) { } return true; } +return { SVG_NS, createSvgIcon, patchSvgIcon }; +})(); // --- src/core/reactive.js --- +const { createReactiveStore } = (() => { /** * @fileoverview Fine-grained reactive store with async microtask batching * and structural slice comparison to prevent full-page re-renders. @@ -268,8 +1019,11 @@ function createReactiveStore(initialState) { subscribe, }; } +return { createReactiveStore }; +})(); // --- src/i18n/zh-CN.js --- +const { I18N_MESSAGES_ZH_CN } = (() => { /** * @fileoverview Simplified Chinese (zh-CN) dictionary for Antigravity Usage & Speed Monitor. * Matches 100% of the existing out-of-the-box UI copy. Zero emoji characters. @@ -327,6 +1081,9 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', + 'fmt.sideQuestion': '旁路提问', + 'fmt.sideBadge': '旁{index}', + 'fmt.sideBadgeShort': '旁', 'fmt.selectedCount': '已选 {count} {unit}', 'fmt.selectedListTitle': '已选 ({count}):{names}', 'fmt.selectPlaceholder': '请选择', @@ -451,6 +1208,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.currentSession': '当前会话', 'live.switchSessionTitle': '点击切换查看会话:{title}', 'live.thinking': '推理中', + 'live.generating': '生成中', 'live.running': '运行中', 'live.done': '已完成', 'live.doneWithSteps': '已完成 ({steps} 步)', @@ -703,6 +1461,21 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)', 'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)', 'settings.str.mountSidebar': '仅侧边栏', + 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', + 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', + 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。', + 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', + 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', + 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', + 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', + 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。', + 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', + 'settings.bridge.relaunchBtn': '立即重启并启用挂载', + 'settings.bridge.relaunchingBtn': '正在重启客户端...', + 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', + 'settings.bridge.dismissAria': '暂时关闭提示', + 'settings.bridge.copyFlagBtn': '复制 {cmd}', + 'settings.bridge.copiedBtn': '已复制启动参数', 'settings.str.popoverWidthLabel': '悬浮面板宽度', 'settings.str.popoverWidthAuto': '自适应', 'settings.str.popoverWidthCustom': '指定宽度', @@ -771,6 +1544,7 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.ctxUnavailable': '{name}(当前不可用)', 'settings.oth.ctxConfigured': '{name} · 已设置', 'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}', + 'settings.oth.ctxPendingBridge': '{name} · 待重启生效', 'settings.oth.ctxDefaultReported': '默认 · 最近 {name}', 'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。', 'settings.oth.ctxMixed': '各推理档设置不同', @@ -791,9 +1565,95 @@ const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', + + // Structured Live Activity Actions + 'live.act.run_command': '执行命令', + 'live.act.read_file': '读取文件', + 'live.act.edit_file': '修改文件', + 'live.act.write_file': '写入文件', + 'live.act.grep_search': '搜索代码', + 'live.act.find_file': '查找文件', + 'live.act.read_url': '读取网页', + 'live.act.search_web': '网页搜索', + 'live.act.invoke_subagent': '调用子代理', + 'live.act.send_message': '通信子代理', + 'live.act.manage_subagents': '管理子代理', + 'live.act.manage_task': '后台任务', + 'live.act.schedule': '定时任务', + 'live.act.ask_question': '等待用户选择', + 'live.act.search_marketplace': '查询插件', + 'live.act.mcp_tool': '调用 MCP', + 'live.act.tool_call': '调用工具', + 'live.act.thinking': '推理中', + 'live.act.compacting': '上下文压缩', + 'live.act.responding': '正在输出回复', + 'live.act.waiting_subagent': '等待子代理', + 'live.act.starting': '启动中', + 'live.act.done': '已完成', + 'live.act.awaitingApproval': '等待确认 · {label}', + 'live.act.compactionResuming': '已完成压缩,正在恢复推理', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': '当前范围暂无可绘制的调用步骤', + 'chart.step.excluded': '未纳入', + 'chart.step.zeroSteps': '0 步', + 'chart.step.stepAdd': '本步 +{tokens}', + 'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}', + 'chart.step.cacheShort': '缓存 {pct}%', + 'chart.step.compactionCheckpoint': '上下文自动压缩检查点', + 'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}', + 'chart.step.ttftShort': '首字 {sec}s', + 'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}', + 'chart.step.compactionStep': '上下文压缩步', + 'chart.step.noSpeedSample': '无测速样本', + 'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%', + 'chart.step.noTtftSample': '无首字计时样本', + 'chart.step.cumCost': '累计 {cost}', + 'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}', + 'chart.step.noSamples': '无样本', + 'chart.step.peakShort': '峰 {val}', + 'chart.step.peakPill': '峰值 {tag} · {val}', + 'chart.step.stepsCount': '{count}步', + 'chart.step.multiPrefix': '{count} 模型 · ', + 'chart.step.sumTokens': '{prefix}累计 {tokens}', + 'chart.step.peakTokens': '{prefix}峰值 {tokens}', + 'chart.step.currentCtx': '当前 {tokens}', + 'chart.step.meanTps': '{prefix}均值 {val} tok/s', + 'chart.step.meanSec': '{prefix}均值 {val}s', + 'chart.step.noValidSamples': '暂无有效样本', + 'chart.step.sumCost': '{prefix}累计 {cost}', + 'chart.fit.empty': '该模型暂无有效拟合样本', + 'chart.fit.loess': 'LOESS 拟合', + 'chart.fit.olsLinear': 'OLS 线性', + 'chart.fit.olsReg': 'OLS 回归', + 'chart.fit.observed': '观测值', + 'chart.fit.tipFit': '拟合 {val}', + 'chart.fit.tipObs': '观测 {val}', + 'chart.fit.zeroSamples': '0 样本', + 'chart.fit.peerMean': '{label} 均 {val}', + 'chart.fit.peerCompare': '同图对比:{peers}', + 'chart.fit.curvesCount': '{count} 条拟合线', + 'chart.fit.multiBadge': '{steps}步 · {models} 模型对比', + 'chart.fit.singleBadge': '{steps}步 · 均 {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}', + 'chart.trend.hmMonthYear': '{yy}年{month}月', + 'chart.trend.hmMonthOnly': '{month}月', + 'chart.trend.wdayMon': '一', + 'chart.trend.wdayWed': '三', + 'chart.trend.wdayFri': '五', + 'chart.trend.wdaySun': '日', + 'chart.trend.hmAria': '每日用量热力格子图', + 'chart.trend.hmLess': '少', + 'chart.trend.hmMore': '多', + 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', + 'chart.trend.hmActiveZero': '活跃 0/{total} 天', + 'chart.trend.peakPill': '峰值 {label} · {tokens}', }); +return { I18N_MESSAGES_ZH_CN }; +})(); // --- src/i18n/en-US.js --- +const { I18N_MESSAGES_EN_US } = (() => { /** * @fileoverview English (en-US) dictionary for Antigravity Usage & Speed Monitor. * Zero emoji characters. @@ -851,6 +1711,9 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', + 'fmt.sideQuestion': 'Side Question', + 'fmt.sideBadge': 'Q{index}', + 'fmt.sideBadgeShort': 'Q', 'fmt.selectedCount': '{count} {unit} selected', 'fmt.selectedListTitle': 'Selected ({count}): {names}', 'fmt.selectPlaceholder': 'Select', @@ -975,6 +1838,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'live.currentSession': 'Current Session', 'live.switchSessionTitle': 'Switch monitor to session: {title}', 'live.thinking': 'Thinking', + 'live.generating': 'Generating', 'live.running': 'Running', 'live.done': 'Done', 'live.doneWithSteps': 'Done ({steps} steps)', @@ -1227,6 +2091,21 @@ 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.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', + 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', + 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.', + 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', + 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', + 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', + 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', + 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.', + 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', + 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', + 'settings.bridge.relaunchingBtn': 'Relaunching Host...', + 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', + 'settings.bridge.dismissAria': 'Dismiss notice for now', + 'settings.bridge.copyFlagBtn': 'Copy {cmd}', + 'settings.bridge.copiedBtn': 'Copied to Clipboard', 'settings.str.popoverWidthLabel': 'Popover Width', 'settings.str.popoverWidthAuto': 'Auto Fit', 'settings.str.popoverWidthCustom': 'Custom', @@ -1295,6 +2174,7 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.ctxUnavailable': '{name} (currently unavailable)', 'settings.oth.ctxConfigured': '{name} · Set', 'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}', + 'settings.oth.ctxPendingBridge': '{name} · Pending Restart', 'settings.oth.ctxDefaultReported': 'Default · Last seen {name}', 'settings.oth.ctxReported': 'The host reported {name} on the latest request.', 'settings.oth.ctxMixed': 'Different limits by thinking level', @@ -1315,9 +2195,95 @@ const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', + + // Structured Live Activity Actions + 'live.act.run_command': 'Run Command', + 'live.act.read_file': 'Read File', + 'live.act.edit_file': 'Edit File', + 'live.act.write_file': 'Write File', + 'live.act.grep_search': 'Search Code', + 'live.act.find_file': 'Find Files', + 'live.act.read_url': 'Read Web Page', + 'live.act.search_web': 'Search Web', + 'live.act.invoke_subagent': 'Invoke Subagent', + 'live.act.send_message': 'Message Subagent', + 'live.act.manage_subagents': 'Manage Subagents', + 'live.act.manage_task': 'Manage Task', + 'live.act.schedule': 'Schedule Task', + 'live.act.ask_question': 'Waiting for User Choice', + 'live.act.search_marketplace': 'Search Plugins', + 'live.act.mcp_tool': 'Call MCP Tool', + 'live.act.tool_call': 'Call Tool', + 'live.act.thinking': 'Thinking', + 'live.act.compacting': 'Compacting Context', + 'live.act.responding': 'Responding', + 'live.act.waiting_subagent': 'Waiting for Subagent', + 'live.act.starting': 'Starting', + 'live.act.done': 'Completed', + 'live.act.awaitingApproval': 'Awaiting Approval · {label}', + 'live.act.compactionResuming': 'Compaction finished, resuming reasoning', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': 'No plottable steps in current scope', + 'chart.step.excluded': 'Excluded', + 'chart.step.zeroSteps': '0 steps', + 'chart.step.stepAdd': 'Step +{tokens}', + 'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}', + 'chart.step.cacheShort': 'Cache {pct}%', + 'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint', + 'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}', + 'chart.step.ttftShort': 'TTFT {sec}s', + 'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}', + 'chart.step.compactionStep': 'Compaction step', + 'chart.step.noSpeedSample': 'No speed sample', + 'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%', + 'chart.step.noTtftSample': 'No TTFT sample', + 'chart.step.cumCost': 'Total {cost}', + 'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}', + 'chart.step.noSamples': 'No samples', + 'chart.step.peakShort': 'Peak {val}', + 'chart.step.peakPill': 'Peak {tag} · {val}', + 'chart.step.stepsCount': '{count} steps', + 'chart.step.multiPrefix': '{count} models · ', + 'chart.step.sumTokens': '{prefix}Total {tokens}', + 'chart.step.peakTokens': '{prefix}Peak {tokens}', + 'chart.step.currentCtx': 'Current {tokens}', + 'chart.step.meanTps': '{prefix}Avg {val} tok/s', + 'chart.step.meanSec': '{prefix}Avg {val}s', + 'chart.step.noValidSamples': 'No valid samples', + 'chart.step.sumCost': '{prefix}Total {cost}', + 'chart.fit.empty': 'No valid regression samples for this model', + 'chart.fit.loess': 'LOESS Fit', + 'chart.fit.olsLinear': 'OLS Linear', + 'chart.fit.olsReg': 'OLS Reg', + 'chart.fit.observed': 'Observed', + 'chart.fit.tipFit': 'Fit {val}', + 'chart.fit.tipObs': 'Obs {val}', + 'chart.fit.zeroSamples': '0 samples', + 'chart.fit.peerMean': '{label} Avg {val}', + 'chart.fit.peerCompare': 'Compare: {peers}', + 'chart.fit.curvesCount': '{count} fit curves', + 'chart.fit.multiBadge': '{steps} steps · {models} models', + 'chart.fit.singleBadge': '{steps} steps · Avg {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}', + 'chart.trend.hmMonthYear': "{month}/{yy}", + 'chart.trend.hmMonthOnly': 'M{month}', + 'chart.trend.wdayMon': 'M', + 'chart.trend.wdayWed': 'W', + 'chart.trend.wdayFri': 'F', + 'chart.trend.wdaySun': 'S', + 'chart.trend.hmAria': 'Daily usage heatmap', + 'chart.trend.hmLess': 'Less', + 'chart.trend.hmMore': 'More', + 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', + 'chart.trend.hmActiveZero': 'Active 0/{total}d', + 'chart.trend.peakPill': 'Peak {label} · {tokens}', }); +return { I18N_MESSAGES_EN_US }; +})(); // --- src/i18n/index.js --- +const { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nStore, setI18nLanguage, getEffectiveLocale, isEnglishLocale, t } = (() => { /** * @fileoverview Reactive lightweight i18n engine (`zh-CN` / `en-US` / `auto`). * Default language is `'zh-CN'` so out-of-the-box UI matches existing behavior 100%. @@ -1330,11 +2296,7 @@ const I18N_DICTIONARIES = Object.freeze({ }); function normalizeI18nLanguage(raw) { - const val = String(raw ?? '').trim(); - if (val === 'auto') return 'auto'; - if (/^en(?:-|$)/i.test(val)) return 'en-US'; - if (/^zh(?:-|$)/i.test(val)) return 'zh-CN'; - return 'zh-CN'; + return normalizeLanguageSetting(raw); } function detectHostSystemLocale() { @@ -1387,8 +2349,11 @@ function t(key, vars = undefined) { vars[k] !== undefined && vars[k] !== null ? String(vars[k]) : '' ); } +return { I18N_DICTIONARIES, normalizeI18nLanguage, detectHostSystemLocale, i18nStore, setI18nLanguage, getEffectiveLocale, isEnglishLocale, t }; +})(); // --- src/core/appearance.js --- +const { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot } = (() => { /** * @fileoverview Theme accent palette & panel font-scale appearance engine. * Applies CSS custom properties cleanly to Sidebar `:root` and Shadow DOM hosts, @@ -1408,8 +2373,15 @@ const THEME_ACCENT_PRESETS = Object.freeze([ const FONT_SCALE_FACTORS = Object.freeze({ sm: 0.92, md: 1, - lg: 1.08, - xl: 1.15, + lg: 1.14, + xl: 1.28, +}); + +const PANEL_SCALE_FACTORS = Object.freeze({ + sm: 1, + md: 1, + lg: 1.09, + xl: 1.18, }); function normalizeClientThemeAccent(raw) { @@ -1461,17 +2433,23 @@ function applyAppearanceToRoot(targetEl, settings, { includeFontScale = true } = if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1; + const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1; setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor)); + setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor)); targetEl.setAttribute?.('data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); + setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); if (typeof targetEl.removeAttribute === 'function') { targetEl.removeAttribute('data-font-scale'); } } } +return { THEME_ACCENT_PRESETS, FONT_SCALE_FACTORS, PANEL_SCALE_FACTORS, normalizeClientThemeAccent, normalizeClientFontScale, applyAppearanceToRoot }; +})(); // --- src/core/domPatch.js --- +const { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList } = (() => { /** * @fileoverview Incremental DOM patching utilities and keyed list reconciler. * Prevents full innerHTML replacements and preserves active DOM element state. @@ -1671,8 +2649,11 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow } } } } +return { h, patchText, patchAttr, patchClasses, patchStyleVar, isEventInside, patchKeyedList }; +})(); // --- src/core/component.js --- +const { defineComponent } = (() => { /** * @fileoverview Vue-inspired lightweight component kernel supporting * props, custom v-model value transmission (emit('update:modelValue', val)), @@ -1747,8 +2728,11 @@ function defineComponent({ name, setup }) { }; }; } +return { defineComponent }; +})(); // --- src/core/formatters.js --- +const { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail } = (() => { /** * @fileoverview Pure formatting utilities for speed metrics, token counts, * USD estimates, countdown timers, and custom datetime displays. @@ -1771,53 +2755,24 @@ function formatCachePct(value) { } function getSpeedToneClass(tokPerSec) { - if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) { - return 'tone-muted'; - } - const v = Number(tokPerSec); - if (v >= 60) return 'tone-good'; - if (v >= 35) return 'tone-info'; - if (v >= 20) return 'tone-warn'; - return 'tone-danger'; + return `tone-${classifySpeedTier(tokPerSec)}`; } function getCacheToneClass(cacheHitPct, promptTokens = null) { - if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) { - return 'tone-muted'; - } - const v = Number(cacheHitPct); - if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) { - return 'tone-muted'; - } - if (v >= 85) return 'tone-good'; - if (v >= 65) return 'tone-info'; - if (v >= 30) return 'tone-warn'; - return 'tone-danger'; + return `tone-${classifyCacheTier(cacheHitPct, promptTokens)}`; } function getStepCostToneClass(costUsd) { - if (costUsd == null || !Number.isFinite(Number(costUsd))) return ''; - const v = Number(costUsd); - if (v >= 0.3) return 'tone-danger'; - if (v >= 0.15) return 'tone-warn'; - return ''; + const tier = classifyStepCostTier(costUsd); + return tier ? `tone-${tier}` : ''; } function getTtftToneClass(ttftSec) { - if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return ''; - const v = Number(ttftSec); - if (v >= 30) return 'tone-danger'; - if (v >= 18) return 'tone-warn'; - return ''; + const tier = classifyTtftTier(ttftSec); + return tier === 'warn' || tier === 'danger' ? `tone-${tier}` : ''; } -function formatTokens(num) { - const n = Number(num || 0); - if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; - if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; - if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; - return String(Math.round(n)); -} +const formatTokens = formatCompactTokens; function formatTokensPrecise(num) { const n = Number(num || 0); @@ -1922,23 +2877,6 @@ 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'} - */ -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-` 厂商前缀以节省单行表格空间(确保剥离后非空)。 @@ -1958,15 +2896,7 @@ function stripCompactionMarker(rawText) { .trim(); } -/** - * 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。 - * - * @param {unknown} mode - * @returns {'compact'|'full'} - */ -function normalizeOrchestratorIdDisplayMode(mode) { - return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact'; -} +const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode; /** * 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。 @@ -2009,23 +2939,35 @@ function resolveModelDisplayInfo(target, settings = {}, options = {}) { } const shortText = String( - target.activeModelShort ?? target.modelShort ?? target.shortName ?? '' + target.activeBaseModelShort ?? + target.baseModelShort ?? + target.activeModelShort ?? + target.modelShort ?? + target.shortName ?? + '' ).trim(); const labelText = String( - target.activeModelLabel ?? target.modelLabel ?? target.label ?? '' + target.activeBaseModelLabel ?? + target.baseModelLabel ?? + target.activeModelLabel ?? + target.modelLabel ?? + target.label ?? + '' ).trim(); const upstreamText = String( - target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? '' + target.baseModelUpstream ?? + target.activeModelUpstream ?? + target.modelUpstream ?? + target.upstreamName ?? + '' ).trim(); + const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`; const responseText = String(target.responseModel ?? '').trim(); const modelKeyText = String(target.modelKey ?? '').trim(); const isCompaction = Boolean(target.isCompactionStep) || - /·(?:压缩|compact)\s*$/iu.test(shortText) || - /·(?:压缩|compact)\s*$/iu.test(upstreamText) || - /·(?:压缩|compact)\s*$/iu.test(labelText) || - /\[自动压缩\]\s*$/u.test(labelText); + /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText); const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : ''; @@ -2263,13 +3205,145 @@ function mergeModelsByDisplayName(models = [], settings = {}, options = {}) { }); } +/** + * 根据代理索引返回对应的微边框语义徽章样式类名。 + * + * @param {number} [index=0] + * @param {boolean} [isMain=false] + * @returns {string} + */ +function getAgentBadgeClass(index = 0, isMain = false) { + if (isMain || index <= 0) return 'badge-main'; + const slot = ((index - 1) % 3) + 1; + return `badge-sub-${slot}`; +} + +/** + * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。 + * + * @param {object|null|undefined} agent + * @returns {string} + */ +function formatAgentBadgeText(agent) { + if (!agent) return t('fmt.mainBadge'); + const kind = + agent.agentKind || + (agent.isMain + ? 'main' + : agent.isSideQuestion || agent.typeName === 'side_question' + ? 'side_question' + : 'subagent'); + if (kind === 'all') return t('header.scopeAllShort'); + if (kind === 'main') return t('fmt.mainBadge'); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + if (ord > 0) return t('fmt.sideBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.sideBadgeShort'); + } + const ord = Number(agent.agentOrdinal || agent.index || 0); + if (ord > 0) return t('fmt.subBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.subBadgeShort'); +} + +/** + * 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。 + * + * @param {object|null|undefined} agent + * @returns {string} + */ +function formatAgentLabel(agent) { + if (!agent) return t('fmt.mainAgent'); + const kind = + agent.agentKind || + (agent.isMain + ? 'main' + : agent.isSideQuestion || agent.typeName === 'side_question' + ? 'side_question' + : 'subagent'); + if (kind === 'all') return t('header.scopeAll'); + if (kind === 'main') return t('fmt.mainAgent'); + + const rawCustom = + agent.customRole !== undefined + ? String(agent.customRole || '').trim() + : String(agent.role || '').trim(); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.sideQuestion') || + rawCustom === 'Side Question' || + rawCustom === 'side_question'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; + } + + const ord = Number(agent.agentOrdinal || agent.index || 0); + const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.subAgent') || + rawCustom === 'Subagent'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; +} + +/** + * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 + * + * @param {object|null|undefined} act + * @param {string} [fallbackKey='live.thinking'] + * @returns {string} + */ +function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') { + if (!act || typeof act !== 'object') return t(fallbackKey); + let baseLabel = ''; + if (act.actionKey) { + const i18nKey = `live.act.${act.actionKey}`; + const translated = t(i18nKey); + if (translated && translated !== i18nKey) { + baseLabel = translated; + } + } + if (!baseLabel) { + baseLabel = String(act.label || '').trim() || t(fallbackKey); + } + if (act.waitingApproval) { + return t('live.act.awaitingApproval', { label: baseLabel }); + } + return baseLabel; +} + +/** + * 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。 + * + * @param {object|null|undefined} act + * @returns {string} + */ +function formatLiveActivityDetail(act) { + if (!act || typeof act !== 'object') return ''; + if (act.detailKey === 'compaction_resuming') { + return t('live.act.compactionResuming'); + } + return String(act.detail || ''); +} +return { formatMetric, formatCachePct, getSpeedToneClass, getCacheToneClass, getStepCostToneClass, getTtftToneClass, formatTokens, formatTokensPrecise, formatCnyApprox, formatDateSpanBadge, formatUsd, speedReasonText, sampleSummary, formatCountdown, formatCompactDateTime, formatElapsedSec, stripVendorModelPrefix, normalizeOrchestratorIdDisplayMode, resolveModelDisplayInfo, mergeModelsByDisplayName, getAgentBadgeClass, formatAgentBadgeText, formatAgentLabel, formatLiveActivityLabel, formatLiveActivityDetail }; +})(); + // --- src/core/httpClient.js --- +const { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi } = (() => { /** * @fileoverview Async HTTP client with AbortController cancellation for stale * polling requests, concurrent GET deduplication, and dual-mode transport * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). */ + const inFlightGets = new Map(); const activeControllers = new Map(); @@ -2279,8 +3353,7 @@ const activeControllers = new Map(); * @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null} */ function getWindowBridgeConfig() { - if (typeof window === 'undefined') return null; - const br = window.__AGUsageMonitorBridge; + const br = readInjectedWindowBridge(); const port = Number(br?.port || 0); if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) { return br; @@ -2507,20 +3580,16 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '', cdpTi } return promise; } +return { getWindowBridgeConfig, isWindowOverlayMode, deliverCdpBridgeResponses, callSidecarApi }; +})(); // --- src/store/uiStore.js --- +const { getViewTabs, uiStore, getVisibleMonitorView } = (() => { /** * @fileoverview UI navigation and view state store. */ -const VIEW_TABS = Object.freeze([ - { value: 'overview', label: '实时监控', icon: 'pulse' }, - { value: 'consumption', label: '用量统计', icon: 'chart-bar' }, - { value: 'steps', label: '调用明细', icon: 'table' }, - { value: 'settings', label: '偏好设置', icon: 'sliders' }, -]); - function getViewTabs() { return [ { value: 'overview', label: t('nav.overview'), icon: 'pulse' }, @@ -2543,8 +3612,11 @@ const uiStore = createReactiveStore({ function getVisibleMonitorView(state = uiStore.getState()) { return state.monitorVisible ? state.activeView : null; } +return { getViewTabs, uiStore, getVisibleMonitorView }; +})(); // --- src/store/telemetryStore.js --- +const { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform } = (() => { /** * @fileoverview Reactive telemetry store with async non-overlapping poll scheduler * and granular slice updates. @@ -2568,7 +3640,7 @@ function extractHostRouteCascadeId() { if (m && CASCADE_UUID_RE.test(m[1])) { return m[1]; } - const extBridgeRouteId = String(window.__AGUsageMonitorBridge?.hostRouteCascadeId || '').trim(); + const extBridgeRouteId = String(readInjectedWindowBridge()?.[WINDOW_BRIDGE_ROUTE_KEY] || '').trim(); if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) { return extBridgeRouteId; } @@ -2650,308 +3722,33 @@ let loopActive = false; let loopIntervalMs = 2000; let loopTickFn = null; -const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([ - 'context', - 'tps', - 'ttft', - 'avg_tps', - 'cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'quota_auto', - 'gemini_5h', - 'gemini_weekly', - 'claude_5h', - 'claude_weekly', -]); +const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; +const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; +const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS; +const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES; +const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES; +const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS; +const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS; +const CLIENT_STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS; +const DEFAULT_CLIENT_STEP_COLUMNS = DEFAULT_STEP_TABLE_COLUMNS; +const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT; +const MIN_CLIENT_POPOVER_WIDTH = MIN_POPOVER_WIDTH; +const MAX_CLIENT_POPOVER_WIDTH = MAX_POPOVER_WIDTH; +const DEFAULT_CLIENT_POPOVER_WIDTH = DEFAULT_POPOVER_WIDTH; -const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); - -const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); - -const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); - -const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']); - -const CLIENT_OVERVIEW_METRIC_KEYS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'context_usage', - 'quota_tightest', -]); - -const DEFAULT_CLIENT_OVERVIEW_METRICS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', -]); - -const CLIENT_STEP_COLUMN_KEYS = Object.freeze([ - 'step', - 'time', - 'model', - 'tps', - 'ttft', - 'duration', - 'tokens_combo', - 'tokens_io_cache', - 'tokens_custom', - 'input_tokens', - 'cache_tokens', - 'output_tokens', - 'cache', - 'cost', -]); - -const DEFAULT_CLIENT_STEP_COLUMNS = Object.freeze([ - 'step', - 'model', - 'tps', - 'ttft', - 'tokens_combo', - 'cache', - 'cost', -]); - -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', -}); - -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']; -} - -function normalizeClientStepTokenComboFormat(raw) { - return parseClientStepTokenComboSegments(raw).join(':'); -} - -const MIN_CLIENT_POPOVER_WIDTH = 440; -const MAX_CLIENT_POPOVER_WIDTH = 1080; -const DEFAULT_CLIENT_POPOVER_WIDTH = 580; - -function normalizeClientPopoverWidthMode(mode) { - const m = String(mode ?? '').trim().toLowerCase(); - return m === 'custom' || m === 'fixed' ? 'custom' : 'auto'; -} - -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))); -} - -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]; - } - const allowedSet = new Set(allowedKeys); - const seen = new Set(); - const out = []; - for (const item of raw) { - const key = String(item ?? '').trim(); - if (!key || key === 'none' || !allowedSet.has(key) || seen.has(key)) continue; - seen.add(key); - out.push(key); - if (out.length >= maxLen) break; - } - if (out.length < minLen) { - for (const fallbackKey of [...defaultItems, ...allowedKeys]) { - if (!seen.has(fallbackKey) && allowedSet.has(fallbackKey)) { - seen.add(fallbackKey); - out.push(fallbackKey); - if (out.length >= minLen) break; - } - } - } - return out; -} - -/** - * 归一化前端顶栏胶囊动态槽位配置数组(支持 1..5 项不重复指标,兼容迁移旧版 `'none'` 占位)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -function normalizeClientTopbarSlots(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_TOPBAR_SLOT_KEYS, - defaultItems: DEFAULT_CLIENT_TOPBAR_SLOTS, - minLen: 1, - maxLen: 5, - }); -} - -/** - * 归一化鼠标悬浮速览窗展示模块列表(支持 0..4 项,`0` 项代表关闭悬浮窗)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -function normalizeClientHoverModules(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS, - defaultItems: DEFAULT_CLIENT_HOVER_MODULES, - minLen: 0, - maxLen: 4, - }); -} - -/** - * 归一化实时监控视图展示模块列表(支持 1..4 项)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -function normalizeClientOverviewModules(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS, - defaultItems: DEFAULT_CLIENT_OVERVIEW_MODULES, - minLen: 1, - maxLen: 4, - }); -} - -/** - * 归一化实时监控第一行指标矩阵配置(支持 1..4 项)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -function normalizeClientOverviewMetrics(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_OVERVIEW_METRIC_KEYS, - defaultItems: DEFAULT_CLIENT_OVERVIEW_METRICS, - minLen: 1, - maxLen: 4, - }); -} - -/** - * 归一化调用明细「按步查看」显示列配置(支持 2..12 列)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -function normalizeClientStepColumns(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_STEP_COLUMN_KEYS, - defaultItems: DEFAULT_CLIENT_STEP_COLUMNS, - minLen: 2, - maxLen: CLIENT_STEP_COLUMN_KEYS.length, - }); -} - -/** - * 归一化前端插件更新策略(`'off'` | `'manual'` | `'auto'`),兼容旧版布尔字段。 - * - * @param {unknown} mode - * @param {unknown} [legacyAutoUpdate] - * @returns {'off'|'manual'|'auto'} - */ -function normalizeClientUpdateMode(mode, legacyAutoUpdate) { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'off' || m === 'manual' || m === 'auto') return m; - if (legacyAutoUpdate === true) return 'auto'; - return 'manual'; -} - -function normalizeClientOrchestratorIdMode(mode) { - return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact'; -} - -/** - * 归一化前端面板挂载方式(`'dual'` | `'composer'` | `'sidebar'`),兼容旧版 `enableWindowOverlay` 布尔字段。 - * - * @param {unknown} mode - * @param {unknown} [legacyEnableOverlay] - * @returns {'dual'|'composer'|'sidebar'} - */ -function normalizeClientWindowMountMode(mode, legacyEnableOverlay) { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'composer' || m === 'input') return 'composer'; - if (m === 'sidebar' || m === 'off') return 'sidebar'; - if (m === 'dual' || m === 'topbar') return 'dual'; - if (legacyEnableOverlay === false) return 'sidebar'; - return 'dual'; -} +const parseClientStepTokenComboSegments = parseStepTokenComboSegments; +const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat; +const normalizeClientPopoverWidthMode = normalizePopoverWidthMode; +const normalizeClientPopoverWidth = normalizePopoverWidth; +const normalizeClientModelDisplayMode = normalizeModelDisplayMode; +const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; +const normalizeClientHoverModules = normalizeHoverModules; +const normalizeClientOverviewModules = normalizeOverviewModules; +const normalizeClientOverviewMetrics = normalizeOverviewMetrics; +const normalizeClientStepColumns = normalizeStepTableColumns; +const normalizeClientUpdateMode = normalizePluginUpdateMode; +const normalizeClientOrchestratorIdMode = normalizeOrchestratorIdMode; +const normalizeClientWindowMountMode = normalizeWindowMountMode; function isEquivalentTelemetry(prev, next) { if (!prev || !next) return false; @@ -2966,15 +3763,6 @@ function isEquivalentTelemetry(prev, next) { } return true; }; - const normMount = (mode, legacyEnableOverlay) => { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'composer' || m === 'input') return 'composer'; - if (m === 'sidebar' || m === 'off') return 'sidebar'; - if (m === 'dual' || m === 'topbar') return 'dual'; - if (legacyEnableOverlay === false) return 'sidebar'; - return 'dual'; - }; - // 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置) const pAct = prev.activeConversation; const nAct = next.activeConversation; @@ -2984,6 +3772,7 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; + if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } @@ -2993,51 +3782,29 @@ 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) + normalizeModelDisplayMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !== + normalizeModelDisplayMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel) ) { return false; } if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false; - if (normPopMode(pSet?.popoverWidthMode) !== normPopMode(nSet?.popoverWidthMode)) { + if (normalizePopoverWidthMode(pSet?.popoverWidthMode) !== normalizePopoverWidthMode(nSet?.popoverWidthMode)) { return false; } - if (normPopW(pSet?.popoverWidth) !== normPopW(nSet?.popoverWidth)) { + if (normalizePopoverWidth(pSet?.popoverWidth) !== normalizePopoverWidth(nSet?.popoverWidth)) { return false; } if ( - String(pSet?.stepTokenComboFormat ?? 'context:in:cache').trim() !== - String(nSet?.stepTokenComboFormat ?? 'context:in:cache').trim() + String(pSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() !== + String(nSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() ) { return false; } - const prevOrchIdMode = - String(pSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' - ? 'full' - : 'compact'; - const nextOrchIdMode = - String(nSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' - ? 'full' - : 'compact'; - if (prevOrchIdMode !== nextOrchIdMode) { + if ( + normalizeOrchestratorIdMode(pSet?.orchestratorIdMode) !== + normalizeOrchestratorIdMode(nSet?.orchestratorIdMode) + ) { return false; } if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false; @@ -3046,8 +3813,8 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false; if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false; if ( - normMount(pSet?.windowMountMode, pSet?.enableWindowOverlay) !== - normMount(nSet?.windowMountMode, nSet?.enableWindowOverlay) + normalizeClientWindowMountMode(pSet?.windowMountMode, pSet?.enableWindowOverlay) !== + normalizeClientWindowMountMode(nSet?.windowMountMode, nSet?.enableWindowOverlay) ) { return false; } @@ -3073,7 +3840,19 @@ function isEquivalentTelemetry(prev, next) { if (!sameArr(pSet?.overviewMetrics, nSet?.overviewMetrics)) return false; if (!sameArr(pSet?.stepTableColumns, nSet?.stepTableColumns)) return false; - // 2. 比对云端状态 + // 2. 比对云端状态与桥接健康度 + const pWb = prev.windowBridge; + const nWb = next.windowBridge; + if ( + (pWb?.state || '') !== (nWb?.state || '') || + Boolean(pWb?.argvUpdatedThisBoot) !== Boolean(nWb?.argvUpdatedThisBoot) || + Boolean(pWb?.argvConfigured) !== Boolean(nWb?.argvConfigured) || + Boolean(pWb?.launcherConfigured) !== Boolean(nWb?.launcherConfigured) || + Boolean(pWb?.canRelaunch) !== Boolean(nWb?.canRelaunch) || + Number(pWb?.aliveCount || 0) !== Number(nWb?.aliveCount || 0) + ) { + return false; + } const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( @@ -3615,12 +4394,6 @@ async function requestTelemetry(params, force) { consecutivePollFailures = 0; const latestSt = telemetryStore.getState(); - const previousAccount = latestSt.telemetry?.account; - const nextAccount = payload?.account; - const accountChanged = previousAccount?.status === 'signedIn' && - (nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' && - (previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name))); - const accountPatch = accountChanged ? { selectedConversationId: '' } : {}; if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { @@ -3631,7 +4404,6 @@ async function requestTelemetry(params, force) { } if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ - ...accountPatch, telemetry: payload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', @@ -3644,7 +4416,6 @@ async function requestTelemetry(params, force) { const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); const nextTelemetry = isSame ? latestSt.telemetry : payload; telemetryStore.setState({ - ...accountPatch, telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', @@ -3680,9 +4451,7 @@ async function saveSettingsPatch(patch) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { - const mode = safePatch.weeklyLimitMode; - safePatch.weeklyLimitMode = - mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official'; + safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) { safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine); @@ -3822,6 +4591,18 @@ async function triggerCloudSync() { return res; } +async function triggerBridgeHostRelaunch() { + try { + return await callSidecarApi('/api/bridge/relaunch', { method: 'POST', body: {} }); + } catch { + // 兼容热更新后常驻父进程 main.mjs 尚未重注册新路由的场景,平滑回退至既有 POST /api/settings 通道转发至最新 Worker + return callSidecarApi('/api/settings', { + method: 'POST', + body: { __bridgeAction: 'relaunch' }, + }); + } +} + async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { @@ -3881,54 +4662,6 @@ function stopAsyncTelemetryLoop() { } } -/** - * 根据代理索引返回对应的微边框语义徽章样式类名。 - * - * @param {number} [index=0] - * @param {boolean} [isMain=false] - * @returns {string} - */ -function getAgentBadgeClass(index = 0, isMain = false) { - if (isMain || index <= 0) return 'badge-main'; - const slot = ((index - 1) % 3) + 1; - return `badge-sub-${slot}`; -} - -/** - * 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -function formatAgentBadgeText(agent) { - if (!isEnglishLocale()) { - if (!agent || agent.isMain) return agent?.badgeText || '主'; - return agent.badgeText || `子${agent.index || ''}`; - } - if (!agent || agent.isMain) return t('fmt.mainBadge'); - return agent.index ? t('fmt.subBadge', { index: agent.index }) : t('fmt.subBadgeShort'); -} - -/** - * 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -function formatAgentLabel(agent) { - if (!isEnglishLocale()) { - if (!agent) return '主代理'; - if (agent.isMain) return agent.shortLabel || '主代理'; - const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : ''; - return `${agent.shortLabel || '子代理'}${rolePart}`; - } - if (!agent || agent.isMain) return t('fmt.mainAgent'); - const idx = Number(agent.index || 0); - const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent'); - const rolePart = - agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : ''; - return `${baseLabel}${rolePart}`; -} /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 @@ -3939,46 +4672,73 @@ function formatAgentLabel(agent) { * @param {string} [ctxInspectorAgentId='auto'] * @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表 */ +const scopedStepProjectionMemo = new WeakMap(); + function resolveScopedConversation( telemetry, selectedAgentScope = 'all', ctxInspectorAgentId = 'auto', includeSteps = false ) { - const active = telemetry?.activeConversation || {}; + const rawActive = telemetry?.activeConversation; + const active = rawActive || {}; const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : []; const hasSubagents = Boolean(active.hasSubagents && agents.length > 1); const subagents = agents.filter((a) => !a.isMain); - const mainAgent = agents.find((a) => a.isMain) || active; - if (includeSteps && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) { - mainAgent.recentSteps = active.recentSteps; - } - const aggregated = active.aggregated || active; - if (includeSteps && hasSubagents && !Array.isArray(aggregated.recentSteps)) { - const combined = []; - for (const ag of agents) { - const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || []; - for (const step of steps) combined.push(step); + let mainAgent = agents.find((a) => a.isMain) || active; + let aggregated = active.aggregated || active; + let resolvedAgents = agents; + + if (includeSteps) { + let cached = rawActive && typeof rawActive === 'object' ? scopedStepProjectionMemo.get(rawActive) : null; + if (!cached) { + let nextMain = mainAgent; + let nextAgents = agents; + if (!Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) { + nextMain = { ...mainAgent, recentSteps: active.recentSteps }; + if (agents.includes(mainAgent)) { + nextAgents = agents.map((ag) => (ag === mainAgent ? nextMain : ag)); + } + } + let nextAgg = aggregated; + if (hasSubagents && !Array.isArray(aggregated.recentSteps)) { + const combined = []; + for (const ag of nextAgents) { + const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || []; + for (const step of steps) combined.push(step); + } + combined.sort( + (a, b) => + (b.createdAtMs || 0) - (a.createdAtMs || 0) || + (b.agentIndex || 0) - (a.agentIndex || 0) || + (b.stepIndex || 0) - (a.stepIndex || 0) + ); + nextAgg = { ...aggregated, recentSteps: combined }; + } + cached = { mainAgent: nextMain, aggregated: nextAgg, agents: nextAgents }; + if (rawActive && typeof rawActive === 'object') { + scopedStepProjectionMemo.set(rawActive, cached); + } } - combined.sort( - (a, b) => - (b.createdAtMs || 0) - (a.createdAtMs || 0) || - (b.agentIndex || 0) - (a.agentIndex || 0) || - (b.stepIndex || 0) - (a.stepIndex || 0) - ); - aggregated.recentSteps = combined; + mainAgent = cached.mainAgent; + aggregated = cached.aggregated; + resolvedAgents = cached.agents; } if (!hasSubagents) { + const singleScoped = + includeSteps && !Array.isArray(active.recentSteps) && Array.isArray(mainAgent.recentSteps) + ? { ...active, recentSteps: mainAgent.recentSteps } + : active; return { hasSubagents: false, effectiveScope: 'main', effectiveCtxScope: 'main', - agents, + agents: resolvedAgents, subagents: [], mainAgent, aggregated, - scopedConv: active, + scopedConv: singleScoped, ctxAgent: mainAgent, }; } @@ -3994,13 +4754,13 @@ function resolveScopedConversation( const scopedConv = effectiveScope === 'all' ? aggregated - : agents.find((a) => a.agentId === effectiveScope) || mainAgent; + : resolvedAgents.find((a) => a.agentId === effectiveScope) || mainAgent; let ctxAgent = scopedConv; let effectiveCtxScope = effectiveScope; if (effectiveScope === 'all') { if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') { - const matched = agents.find((a) => a.agentId === ctxInspectorAgentId); + const matched = resolvedAgents.find((a) => a.agentId === ctxInspectorAgentId); if (matched) { ctxAgent = matched; effectiveCtxScope = matched.agentId; @@ -4012,8 +4772,8 @@ function resolveScopedConversation( } if (effectiveCtxScope === 'auto') { ctxAgent = - agents.find((a) => a.agentId === aggregated.activeAgentId) || - agents.find((a) => a.isRunning) || + resolvedAgents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) || + resolvedAgents.find((a) => !a.isSideQuestion && a.isRunning) || mainAgent; } } @@ -4022,7 +4782,7 @@ function resolveScopedConversation( hasSubagents: true, effectiveScope, effectiveCtxScope, - agents, + agents: resolvedAgents, subagents, mainAgent, aggregated, @@ -4031,7 +4791,28 @@ function resolveScopedConversation( }; } +/** + * 判断宿主系统是否为 macOS (`darwin`):优先读取后端遥测或双栖桥接注入的 `platform`,首帧缺省时回退 UA/平台标识。 + * + * @param {Record|null|undefined} telemetry + * @returns {boolean} + */ +function isMacHostPlatform(telemetry) { + const p = String(telemetry?.hostPlatform || readInjectedWindowBridge()?.platform || '') + .trim() + .toLowerCase(); + if (p) return p === 'darwin'; + if (typeof navigator !== 'undefined') { + const ua = String(navigator.platform || navigator.userAgent || ''); + return /\b(?:mac|darwin)\b|macintosh|mac\s*os/i.test(ua); + } + return false; +} +return { extractHostRouteCascadeId, telemetryStore, CLIENT_TOPBAR_SLOT_KEYS, DEFAULT_CLIENT_TOPBAR_SLOTS, CLIENT_OVERVIEW_MODULE_KEYS, DEFAULT_CLIENT_OVERVIEW_MODULES, DEFAULT_CLIENT_HOVER_MODULES, CLIENT_OVERVIEW_METRIC_KEYS, DEFAULT_CLIENT_OVERVIEW_METRICS, CLIENT_STEP_COLUMN_KEYS, DEFAULT_CLIENT_STEP_COLUMNS, DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, MIN_CLIENT_POPOVER_WIDTH, MAX_CLIENT_POPOVER_WIDTH, DEFAULT_CLIENT_POPOVER_WIDTH, parseClientStepTokenComboSegments, normalizeClientStepTokenComboFormat, normalizeClientPopoverWidthMode, normalizeClientPopoverWidth, normalizeClientModelDisplayMode, normalizeClientTopbarSlots, normalizeClientHoverModules, normalizeClientOverviewModules, normalizeClientOverviewMetrics, normalizeClientStepColumns, normalizeClientUpdateMode, normalizeClientOrchestratorIdMode, normalizeClientWindowMountMode, isEquivalentTelemetry, fetchTelemetry, saveSettingsPatch, saveModelContextWindow, resetAllSettings, rebuildTrajectoryCache, triggerCloudSync, triggerBridgeHostRelaunch, triggerPluginUpdate, startAsyncTelemetryLoop, stopAsyncTelemetryLoop, resolveScopedConversation, isMacHostPlatform }; +})(); + // --- src/components/ui/TopLongPillNav.js --- +const { TopLongPillNav } = (() => { /** * @fileoverview Top Long-Pill Navigation Bar (顶部唯一长药丸功能分割栏). * Splits the application into focused single-viewport views and animates @@ -4121,12 +4902,14 @@ const TopLongPillNav = defineComponent({ } patchText(entry.labelEl, item.label); - if (item.badge !== undefined && item.badge !== null && item.badge !== '') { + const hasBadge = item.badge !== undefined && item.badge !== null && item.badge !== ''; + if (hasBadge) { patchAttr(entry.badgeEl, 'hidden', false); patchText(entry.badgeEl, `(${item.badge})`); } else { patchAttr(entry.badgeEl, 'hidden', true); } + patchAttr(entry.btn, 'title', hasBadge ? `${item.label} (${item.badge})` : item.label); const isActive = item.value === modelValue; patchClasses(entry.btn, { 'is-active': isActive }); @@ -4147,8 +4930,11 @@ const TopLongPillNav = defineComponent({ }; }, }); +return { TopLongPillNav }; +})(); // --- src/components/ui/CustomSelect.js --- +const { CustomSelect } = (() => { /** * @fileoverview Bespoke CustomSelect dropdown component replacing native with custom SVG step controls, @@ -4601,8 +5390,11 @@ const CustomNumberInput = defineComponent({ }; }, }); +return { CustomNumberInput }; +})(); // --- src/components/ui/CustomDateTimePicker.js --- +const { CustomDateTimePicker } = (() => { /** * @fileoverview Bespoke CustomDateTimePicker calendar matrix and hour/minute stepper. * Replaces native and emits Unix epoch ms. @@ -4871,8 +5663,11 @@ const CustomDateTimePicker = defineComponent({ }; }, }); +return { CustomDateTimePicker }; +})(); // --- src/components/ui/CustomScrollbar.js --- +const { CustomScrollbar } = (() => { /** * @fileoverview Bespoke custom scrollbar component (零原生滚动条). * Hides native OS scrollbars completely and renders a precision 4px floating @@ -5035,8 +5830,11 @@ const CustomScrollbar = defineComponent({ }; }, }); +return { CustomScrollbar }; +})(); // --- src/components/ui/SegmentedControl.js --- +const { SegmentedControl } = (() => { /** * @fileoverview Micro-bezel (2px radius) SegmentedControl switcher * for time-range filtering, context limit selection, and sub-table switching. @@ -5091,8 +5889,11 @@ const SegmentedControl = defineComponent({ }; }, }); +return { SegmentedControl }; +})(); // --- src/components/ui/ContextSegmentMeter.js --- +const { ContextSegmentMeter } = (() => { /** * @fileoverview 10-channel segmented context window progress bar updated via * CSS custom variables against the current model's automatic compaction baseline, @@ -5179,8 +5980,11 @@ const ContextSegmentMeter = defineComponent({ }; }, }); +return { ContextSegmentMeter }; +})(); // --- src/components/ui/FourSegmentBar.js --- +const { createFourSegmentBar } = (() => { /** * @fileoverview 通用 4 段式 Token 构成比例条组件 (FourSegmentBar). * 用于在消费概览、热门模型明细及数据来源明细中直观展示: @@ -5227,8 +6031,11 @@ function createFourSegmentBar() { return { el, update }; } +return { createFourSegmentBar }; +})(); // --- src/components/charts/TrendAreaChart.js --- +const { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart } = (() => { /** * @fileoverview 交互式历史用量趋势图组件 (TrendAreaChart). * 支持双模式自适应切换: @@ -5404,7 +6211,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue; if (ticks.length > 0 && c.col < nextAllowedCol) continue; const showYear = crossYear && (c.month === 1 || ticks.length === 0); - const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`; + const text = showYear + ? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month }) + : t('chart.trend.hmMonthOnly', { month: c.month }); ticks.push({ col: c.col, text }); nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap); } @@ -5539,26 +6348,41 @@ function createTrendAreaChart() { const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]); // 类 GitHub 每日小格子热力图容器(> 90 天模式) - const weekdayLabels = ['一', '', '三', '', '五', '', '日']; + const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') }); + const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') }); + const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') }); + const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') }); const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [ h('span', { className: 'trend-hm-month-spacer' }), - ...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })), + wdayMonEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayWedEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayFriEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdaySunEl, ]); const hmMonthsEl = h('div', { className: 'trend-hm-months' }); - const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' }); + const hmGridEl = h('div', { + className: 'trend-hm-grid', + role: 'grid', + 'aria-label': t('chart.trend.hmAria'), + }); const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]); const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]); const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]); const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' }); + const hmLessEl = h('span', { text: t('chart.trend.hmLess') }); + const hmMoreEl = h('span', { text: t('chart.trend.hmMore') }); const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [ - h('span', { text: '少' }), + hmLessEl, h('span', { className: 'trend-hm-swatch lv-0' }), h('span', { className: 'trend-hm-swatch lv-1' }), h('span', { className: 'trend-hm-swatch lv-2' }), h('span', { className: 'trend-hm-swatch lv-3' }), h('span', { className: 'trend-hm-swatch lv-4' }), - h('span', { text: '多' }), + hmMoreEl, ]); const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]); const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [ @@ -5577,6 +6401,8 @@ function createTrendAreaChart() { let currentPts = []; let currentIsHeatmap = false; let currentHeatmapWeeks = 0; + let currentHeatmapFirstDow = 0; + let currentHeatmapGapPx = 2; let currentCellEls = []; let tickElsByIdx = new Map(); let hoveredIdx = -1; @@ -5585,7 +6411,10 @@ function createTrendAreaChart() { function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); - patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); + patchText( + tipCallsEl, + t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) }) + ); const slotTok = safeSlotTokens(slot.tokens); patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; @@ -5605,7 +6434,11 @@ function createTrendAreaChart() { if (hasSubBreakdown) { patchText( tipSubEl, - `入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` + t('chart.step.ioSplit', { + inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), + cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), + outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), + }) ); } } @@ -5741,21 +6574,117 @@ function createTrendAreaChart() { showLineHoverAtIndex(idx); } - function findHeatmapCellFromEvent(e) { + function findDirectHeatmapCell(e) { let cur = e?.target || null; while (cur && cur !== hmGridEl) { const idxAttr = cur.getAttribute?.('data-slot-idx'); if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') { - return { idx: Number(idxAttr), cellEl: cur }; + const idx = Number(idxAttr); + if (Number.isFinite(idx) && idx >= 0 && idx < currentSlots.length) { + return { idx, cellEl: cur }; + } } cur = cur.parentNode || null; } return null; } + function resolveHeatmapCellFromPointer(e) { + const directHit = findDirectHeatmapCell(e); + if (directHit) return directHit; + + const clientX = Number(e?.clientX); + const clientY = Number(e?.clientY); + if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) { + if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { + return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + } + return null; + } + + const rect = hmGridEl.getBoundingClientRect?.(); + if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) { + if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { + return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + } + return null; + } + + const W = currentHeatmapWeeks; + const G = currentHeatmapGapPx; + const relX = clientX - rect.left; + const relY = clientY - rect.top; + if ( + relX < -(G + 1) || + relX > rect.width + G + 1 || + relY < -(G + 1) || + relY > rect.height + G + 1 + ) { + return null; + } + + const pitchX = (rect.width + G) / W; + const pitchY = (rect.height + G) / 7; + const cellW = Math.max(1, pitchX - G); + const cellH = Math.max(1, pitchY - G); + + function distanceToCell(c, r) { + const x0 = c * pitchX; + const y0 = r * pitchY; + const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0; + const dy = relY < y0 ? y0 - relY : relY > y0 + cellH ? relY - (y0 + cellH) : 0; + return { chebyshev: Math.max(dx, dy), distSq: dx * dx + dy * dy }; + } + + // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁与边缘微抖 + if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { + const curGridPos = currentHeatmapFirstDow + hoveredIdx; + const curCol = Math.floor(curGridPos / 7); + const curRow = curGridPos % 7; + if (distanceToCell(curCol, curRow).chebyshev <= G + 0.75) { + return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + } + } + + // 快速扫过或初始落入格子间隙时,按网格步距吸附到最近的有效日期格 + const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX))); + const approxRow = Math.max(0, Math.min(6, Math.floor((relY + G * 0.5) / pitchY))); + const directSlotIdx = approxCol * 7 + approxRow - currentHeatmapFirstDow; + if ( + directSlotIdx >= 0 && + directSlotIdx < currentSlots.length && + currentCellEls[directSlotIdx] + ) { + return { idx: directSlotIdx, cellEl: currentCellEls[directSlotIdx] }; + } + + // 首周补位或末周未来空白边缘:仅当仍在相邻有效格的间隙光晕内才吸附,深入纯空白角则清空 + let bestIdx = -1; + let bestDistSq = Infinity; + for (let dc = -1; dc <= 1; dc++) { + const c = approxCol + dc; + if (c < 0 || c >= W) continue; + for (let dr = -1; dr <= 1; dr++) { + const r = approxRow + dr; + if (r < 0 || r > 6) continue; + const sIdx = c * 7 + r - currentHeatmapFirstDow; + if (sIdx < 0 || sIdx >= currentSlots.length || !currentCellEls[sIdx]) continue; + const d = distanceToCell(c, r); + if (d.chebyshev <= G + 1.5 && d.distSq < bestDistSq) { + bestDistSq = d.distSq; + bestIdx = sIdx; + } + } + } + if (bestIdx >= 0) { + return { idx: bestIdx, cellEl: currentCellEls[bestIdx] }; + } + return null; + } + function handleHeatmapPointer(e) { if (!currentIsHeatmap || !currentSlots.length) return; - const hit = findHeatmapCellFromEvent(e); + const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) { clearHover(); return; @@ -5858,19 +6787,28 @@ function createTrendAreaChart() { const nonZeroVals = []; for (let i = 0; i < slots.length; i++) { - const t = safeSlotTokens(slots[i]?.tokens); - if (t > 0) { + const tokVal = safeSlotTokens(slots[i]?.tokens); + if (tokVal > 0) { activeDays++; - nonZeroVals.push(t); + nonZeroVals.push(tokVal); } - if (t >= maxTokens) { - maxTokens = t; + if (tokVal >= maxTokens) { + maxTokens = tokVal; peakIdx = i; } } + const locale = getEffectiveLocale(); + patchText(wdayMonEl, t('chart.trend.wdayMon')); + patchText(wdayWedEl, t('chart.trend.wdayWed')); + patchText(wdayFriEl, t('chart.trend.wdayFri')); + patchText(wdaySunEl, t('chart.trend.wdaySun')); + patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria')); + patchText(hmLessEl, t('chart.trend.hmLess')); + patchText(hmMoreEl, t('chart.trend.hmMore')); + const sig = - `${useHeatmap ? 'hm' : `line:${viewW}`}|` + + `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + slots .map( (s) => @@ -5892,10 +6830,13 @@ function createTrendAreaChart() { : 0; const totalCells = firstDow + slots.length; const totalWeeks = Math.max(1, Math.ceil(totalCells / 7)); + const gapPx = totalWeeks > 42 ? 1.5 : 2; currentHeatmapWeeks = totalWeeks; + currentHeatmapFirstDow = firstDow; + currentHeatmapGapPx = gapPx; patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks)); - patchStyleVar(hmBodyEl, '--hm-gap', totalWeeks > 42 ? '1.5px' : '2px'); + patchStyleVar(hmBodyEl, '--hm-gap', `${gapPx}px`); // 重建顶部对齐月份标签 while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild); @@ -5947,8 +6888,13 @@ function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const summaryText = maxTokens > 0 && peakSlot?.label - ? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` - : `活跃 0/${slots.length} 天`; + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); patchText(hmSummaryEl, summaryText); if (hoveredIdx >= slots.length) { @@ -6047,7 +6993,10 @@ function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const peakText = maxTokens > 0 && peakSlot?.label - ? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` + ? t('chart.trend.peakPill', { + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) : formatTokensPrecise(maxTokens); patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); @@ -6062,8 +7011,11 @@ function createTrendAreaChart() { return { el: chartWrap, update, destroy }; } +return { HEATMAP_DAYS_THRESHOLD, createTrendAreaChart }; +})(); // --- src/components/charts/SessionStepCharts.js --- +const { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, computeLinearFit, computePublicationFit, createSessionLineChart, createModelFitChart } = (() => { /** * @fileoverview 当前会话步骤级线性走势图与模型趋势拟合图组件 (SessionStepCharts). * @@ -6095,16 +7047,16 @@ const MODEL_COLOR_VARS = Object.freeze([ * @returns {string} */ function getStepModelGroupKey(step) { - if (!step || typeof step !== 'object') return '模型未知'; - const rawLabel = String(step.modelLabel || step.label || '') + if (!step || typeof step !== 'object') return t('fmt.unknownModel'); + const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') .replace(/\s*\[自动压缩\]\s*$/u, '') .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .trim(); if (rawLabel) return rawLabel; - const rawShort = String(step.modelShort || step.shortName || '') - .replace(/·压缩\s*$/u, '') + const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') + .replace(/·(?:压缩|Compact)\s*$/iu, '') .trim(); - return rawShort || '模型未知'; + return rawShort || t('fmt.unknownModel'); } /** @@ -6478,21 +7430,6 @@ function computePublicationFit( }; } -/** - * 计算样本点上的平滑回归拟合值序列(供单元测试与轻量调用直接读取)。 - * - * @param {number[]} ys - * @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [bounds] - * @returns {number[]} - */ -function computeLoessFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) { - const n = Array.isArray(ys) ? ys.length : 0; - if (n === 0) return []; - const xArr = - Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx); - return computePublicationFit(xArr, ys, { minVal, maxVal }).sampleFits; -} - /** * Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。 */ @@ -6646,7 +7583,17 @@ function computeStepTickIndices(count) { function formatStepAxisTag(st, showAgentPrefix) { const num = `#${Number(st?.stepIndex ?? 0)}`; if (!showAgentPrefix) return num; - const badge = st?.agentBadge || (st?.isSubagent ? '子' : '主'); + const badge = formatAgentBadgeText({ + agentKind: + st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), + isMain: !st?.isSubagent, + isSideQuestion: Boolean(st?.isSideQuestion), + sideIndex: st?.sideIndex || 0, + index: st?.agentIndex || 0, + badgeText: st?.agentBadge, + }); return `${badge}${num}`; } @@ -6781,7 +7728,7 @@ function createSessionLineChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '当前范围暂无可绘制的调用步骤', + text: t('chart.step.empty'), hidden: true, }); @@ -6859,7 +7806,10 @@ function createSessionLineChart() { patchText(tipHeadLeft, pt.stepTag); patchText(tipHeadRight, pt.modelText); - patchText(tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : '未纳入'); + patchText( + tipMainLeft, + pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') + ); patchText(tipMainRight, pt.secondaryRight || ''); patchAttr(tipSub, 'hidden', !pt.subDetail); if (pt.subDetail) { @@ -6986,6 +7936,7 @@ function createSessionLineChart() { ? steps : steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st))); + patchText(emptyHintEl, t('chart.step.empty')); if (!matchedSteps.length) { currentPoints = []; lastSig = 'empty'; @@ -6999,7 +7950,7 @@ function createSessionLineChart() { patchAttr(peakPill, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); clearHover(); - return { summaryBadge: '0 步' }; + return { summaryBadge: t('chart.step.zeroSteps') }; } const modelColorMap = new Map(); @@ -7013,7 +7964,7 @@ function createSessionLineChart() { const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, { fallback: gk, }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } for (const st of matchedSteps) { @@ -7026,7 +7977,7 @@ function createSessionLineChart() { } if (!modelLabelByGroup.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } @@ -7086,41 +8037,62 @@ function createSessionLineChart() { if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; - secondaryRight = `本步 +${formatTokens(stepTotalTok)}`; - subDetail = `入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 出 ${formatTokens(outTok)}`; + secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); + subDetail = t('chart.step.ioSplit', { + inTok: formatTokens(inTok), + cacheTok: formatTokens(cacheTok), + outTok: formatTokens(outTok), + }); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { const sign = ctxDelta >= 0 ? '+' : '-'; secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`; } else { - secondaryRight = `缓存 ${Number(st.cacheHitPct ?? 0)}%`; + secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) }); } subDetail = st.isCompactionStep - ? '上下文自动压缩检查点' - : `缓存命中 ${Number(st.cacheHitPct ?? 0)}% · 输出 +${formatTokens(outTok)}`; + ? t('chart.step.compactionCheckpoint') + : t('chart.step.cacheHitOut', { + pct: Number(st.cacheHitPct ?? 0), + outTok: formatTokens(outTok), + }); } else if (metric === 'tps') { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; - secondaryRight = Number.isFinite(st.ttftSec) ? `首字 ${st.ttftSec.toFixed(1)}s` : ''; + secondaryRight = Number.isFinite(st.ttftSec) + ? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) }) + : ''; subDetail = valid - ? `输出 ${formatTokens(outTok)} · 上下文 ${formatTokens(ctxTok)}` - : speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? '上下文压缩步' : '无测速样本'); + ? t('chart.step.outAndCtx', { + outTok: formatTokens(outTok), + ctxTok: formatTokens(ctxTok), + }) + : speedReasonText(st.selectedSpeedReason) || + (st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample')); } else if (metric === 'ttft') { valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; value = valid ? Number(st.ttftSec) : 0; secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : ''; subDetail = valid - ? `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(st.cacheHitPct ?? 0)}%` + ? t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(st.cacheHitPct ?? 0), + }) : st.isCompactionStep - ? '上下文压缩步' - : '无首字计时样本'; + ? t('chart.step.compactionStep') + : t('chart.step.noTtftSample'); } else if (metric === 'cost') { valid = stepCost !== null; value = valid ? stepCost : 0; const shownCumCost = isMultiCompare ? modelCumCost : runningCost; - secondaryRight = `累计 ${formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 })}`; - subDetail = `缓存 ${Number(st.cacheHitPct ?? 0)}% · 本步 ${formatTokens(stepTotalTok)}`; + secondaryRight = t('chart.step.cumCost', { + cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }), + }); + subDetail = t('chart.step.cacheAndStepTok', { + pct: Number(st.cacheHitPct ?? 0), + tokens: formatTokens(stepTotalTok), + }); } if (valid) { @@ -7180,11 +8152,12 @@ function createSessionLineChart() { const validPoints = points.filter((p) => p.valid); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); + const locale = getEffectiveLocale(); const colorSig = Array.from(modelColorMap.entries()) .map(([k, v]) => `${k}=${v}`) .join(','); const sig = - `${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + + `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points .map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`) .join('|'); @@ -7319,12 +8292,12 @@ function createSessionLineChart() { patchStyleVar(swatch, '--swatch-bg', colorVar); const stStat = perModelStats.get(gk); const baseLabel = modelLabelByGroup.get(gk) || gk; - let summarySuffix = '无样本'; + let summarySuffix = t('chart.step.noSamples'); if (stStat && stStat.count > 0) { if (metric === 'totalTokens') { summarySuffix = formatTokens(stStat.cumTok); } else if (metric === 'context') { - summarySuffix = `峰 ${formatTokens(stStat.max)}`; + summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) }); } else if (metric === 'tps' || metric === 'ttft') { summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count); } else if (metric === 'cost') { @@ -7362,7 +8335,10 @@ function createSessionLineChart() { const peakPt = points[peakIdx]; patchText( peakPill, - `峰值 ${peakPt.stepTag} · ${formatChartMetricCompact(metric, peakPt.value)}` + t('chart.step.peakPill', { + tag: peakPt.stepTag, + val: formatChartMetricCompact(metric, peakPt.value), + }) ); patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); @@ -7378,28 +8354,42 @@ function createSessionLineChart() { showHoverAt(hoveredIdx); } - let summaryBadge = `${matchedSteps.length}步`; + let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); const activeCompareCount = isMultiCompare ? targetKeys.length : 1; - const multiPrefix = isMultiCompare ? `${activeCompareCount} 模型 · ` : ''; + const multiPrefix = isMultiCompare + ? t('chart.step.multiPrefix', { count: activeCompareCount }) + : ''; if (metric === 'totalTokens') { - summaryBadge = `${multiPrefix}累计 ${formatTokens(runningTokens)}`; + summaryBadge = t('chart.step.sumTokens', { + prefix: multiPrefix, + tokens: formatTokens(runningTokens), + }); } else if (metric === 'context') { const lastCtx = points[points.length - 1]?.value || 0; summaryBadge = isMultiCompare - ? `${multiPrefix}峰值 ${formatTokens(maxVal)}` - : `当前 ${formatTokens(lastCtx)}`; + ? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) }) + : t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) }); } else if (metric === 'tps') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)} tok/s` - : '暂无有效样本'; + ? t('chart.step.meanTps', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'ttft') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)}s` - : '暂无有效样本'; + ? t('chart.step.meanSec', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'cost') { - summaryBadge = `${multiPrefix}累计 ${formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 })}`; + summaryBadge = t('chart.step.sumCost', { + prefix: multiPrefix, + cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }), + }); } return { summaryBadge }; @@ -7490,7 +8480,7 @@ function createModelFitChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '该模型暂无有效拟合样本', + text: t('chart.fit.empty'), hidden: true, }); @@ -7505,14 +8495,16 @@ function createModelFitChart() { tipSub, ]); - const fitMethodLabelEl = h('span', { text: 'LOESS 拟合' }); + const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); + const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') }); const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [ h('span', { className: 'sstep-fit-swatch is-ols' }), - h('span', { text: 'OLS 线性' }), + olsLegendTextEl, ]); + const obsLegendTextEl = h('span', { text: t('chart.fit.observed') }); const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [ h('span', { className: 'sstep-fit-swatch is-scatter' }), - h('span', { text: '观测值' }), + obsLegendTextEl, h('span', { className: 'sstep-fit-swatch is-curve' }), fitMethodLabelEl, h('span', { className: 'sstep-fit-swatch is-ci' }), @@ -7595,8 +8587,14 @@ function createModelFitChart() { patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); - patchText(tipMainLeft, `拟合 ${formatChartMetricValue(currentMetric, sp.fitVal)}`); - patchText(tipMainRight, `观测 ${formatChartMetricValue(currentMetric, sp.rawVal)}`); + patchText( + tipMainLeft, + t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) + ); + patchText( + tipMainRight, + t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) + ); patchAttr(tipSub, 'hidden', false); if (sp.compareHint) { @@ -7610,7 +8608,10 @@ function createModelFitChart() { const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); patchText( tipSub, - `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(sp.st?.cacheHitPct ?? 0)}%` + t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(sp.st?.cacheHitPct ?? 0), + }) ); } @@ -7876,11 +8877,16 @@ function createModelFitChart() { xVal: globalX, rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), - modelText: disp.text.replace(/·压缩\s*$/u, '').trim() || disp.text, + modelText: disp.baseText || disp.text, }); } } + const locale = getEffectiveLocale(); + patchText(emptyHintEl, t('chart.fit.empty')); + patchText(obsLegendTextEl, t('chart.fit.observed')); + patchText(olsLegendTextEl, t('chart.fit.olsLinear')); + if (fitCacheMetric !== metric) { fitCache.clear(); fitCacheMetric = metric; @@ -7904,9 +8910,10 @@ function createModelFitChart() { patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); + patchText(fitMethodLabelEl, t('chart.fit.loess')); patchText(fitStatsEl, 'n = 0'); clearHover(); - return { sampleCount: 0, summaryBadge: '0 样本' }; + return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') }; } patchAttr(emptyHintEl, 'hidden', true); @@ -7988,7 +8995,12 @@ function createModelFitChart() { if (interp !== null) { peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`); } else { - peerParts.push(`${other.label} 均 ${formatChartMetricCompact(metric, other.pubFit.mean)}`); + peerParts.push( + t('chart.fit.peerMean', { + label: other.label, + val: formatChartMetricCompact(metric, other.pubFit.mean), + }) + ); } } return { @@ -8001,7 +9013,10 @@ function createModelFitChart() { ciHigh: s.pubFit.sampleCiHigh[i], ciHalf: s.pubFit.sampleCiHalf[i], seriesColor: s.colorVar, - compareHint: peerParts.length > 0 ? `同图对比:${peerParts.join(' · ')}` : '', + compareHint: + peerParts.length > 0 + ? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') }) + : '', }; }); s.samples = sSamples; @@ -8011,7 +9026,7 @@ function createModelFitChart() { currentSamples = combinedSamples; const sig = - `multi|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + seriesList .map( (s) => @@ -8125,7 +9140,7 @@ function createModelFitChart() { fitStatsEl, seriesList.length <= 2 ? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ') - : `${seriesList.length} 条拟合线` + : t('chart.fit.curvesCount', { count: seriesList.length }) ); patchAttr(fitStatsEl, 'title', r2SummaryTitle); @@ -8137,7 +9152,10 @@ function createModelFitChart() { return { sampleCount: combinedSamples.length, - summaryBadge: `${combinedSamples.length}步 · ${seriesList.length} 模型对比`, + summaryBadge: t('chart.fit.multiBadge', { + steps: combinedSamples.length, + models: seriesList.length, + }), }; } @@ -8152,7 +9170,10 @@ function createModelFitChart() { const rawYs = filtered.map((d) => d.rawVal); const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false); - patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归'); + patchText( + fitMethodLabelEl, + pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg') + ); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); let dataMin = Infinity; @@ -8205,7 +9226,7 @@ function createModelFitChart() { currentSamples = samples; const sig = - `single|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|'); if (sig !== lastSig) { @@ -8281,7 +9302,10 @@ function createModelFitChart() { } } - const summaryBadge = `${samples.length}步 · 均 ${formatChartMetricCompact(metric, pubFit.mean)}`; + const summaryBadge = t('chart.fit.singleBadge', { + steps: samples.length, + mean: formatChartMetricCompact(metric, pubFit.mean), + }); if (samples.length >= 2) { const rSign = pubFit.r >= 0 ? '+' : ''; const slopeSign = pubFit.slope >= 0 ? '+' : ''; @@ -8289,7 +9313,11 @@ function createModelFitChart() { patchAttr( fitStatsEl, 'title', - `OLS: y = ${slopeSign}${pubFit.slope.toFixed(3)}x + ${pubFit.intercept.toFixed(2)} · 样本标准差 SD = ±${pubFit.sd.toFixed(2)}` + t('chart.fit.olsTitle', { + slope: `${slopeSign}${pubFit.slope.toFixed(3)}`, + intercept: pubFit.intercept.toFixed(2), + sd: pubFit.sd.toFixed(2), + }) ); } else { patchText(fitStatsEl, `n = ${samples.length}`); @@ -8307,8 +9335,11 @@ function createModelFitChart() { return { el: rootEl, update, destroy }; } +return { MODEL_COLOR_VARS, getStepModelGroupKey, toChronologicalSteps, computeLinearFit, computePublicationFit, createSessionLineChart, createModelFitChart }; +})(); // --- src/registries/metricRegistry.js --- +const { CAPSULE_METRIC_KEYS, getCapsuleMetricOptions, getOverviewMetricOptions, resolveQuotaCapsuleSummary, resolveSpecificQuotaSlotSummary, resolveCapsuleMetricPresentation, resolveOverviewMetricCell } = (() => { /** * @fileoverview Decoupled Metric Registry (`metricRegistry.js`). * Centralizes presentation & option metadata for: @@ -8317,35 +9348,7 @@ function createModelFitChart() { */ -const CAPSULE_METRIC_KEYS = Object.freeze([ - 'context', - 'tps', - 'ttft', - 'avg_tps', - 'cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'quota_auto', - 'gemini_5h', - 'gemini_weekly', - 'claude_5h', - 'claude_weekly', -]); - -const OVERVIEW_METRIC_KEYS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'context_usage', - 'quota_tightest', -]); - -const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i; +const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; function getCapsuleMetricOptions() { return CAPSULE_METRIC_KEYS.map((key) => ({ @@ -8434,98 +9437,14 @@ function resolveQuotaCapsuleSummary(quotas) { * @returns {{ roundedPct: number, shortText: string } | null} */ function resolveSpecificQuotaSlotSummary(quotas, slotKey) { - if (!quotas) return null; - const pools = Array.isArray(quotas.pools) ? quotas.pools : []; - const activePool = quotas.activePool || null; - const isClaude = slotKey.startsWith('claude_'); - const isWeekly = slotKey.endsWith('_weekly'); - let rawPct = null; - - if (isClaude) { - const claudePool = - pools.find((p) => p?.poolKey === 'Claude & GPT') || - pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; - if (cand != null && Number.isFinite(Number(cand))) { - rawPct = Number(cand); - } else if ( - activePool && - THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) - ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; - if (fb != null && Number.isFinite(Number(fb))) { - rawPct = Number(fb); - } - } - } else { - const stdGemini = - pools.find((p) => p?.poolKey === 'Gemini') || - pools.find( - (p) => - /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && - !/carbon|argon/i.test(String(p?.poolKey || '')) - ); - const geminiFamilyPools = pools.filter((p) => - /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) - ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; - if (primaryCand != null && Number.isFinite(Number(primaryCand))) { - rawPct = Number(primaryCand); - } else { - const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) - .filter((v) => v != null && Number.isFinite(Number(v))) - .map(Number); - if (familyVals.length > 0) { - rawPct = Math.min(...familyVals); - } else if ( - activePool && - !THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) - ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; - if (fb != null && Number.isFinite(Number(fb))) { - rawPct = Number(fb); - } - } - if ( - rawPct == null && - isWeekly && - quotas.weekly && - !THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) && - quotas.weekly.remainingPct != null && - Number.isFinite(Number(quotas.weekly.remainingPct)) - ) { - rawPct = Number(quotas.weekly.remainingPct); - } - } - } - - if (rawPct == null || !Number.isFinite(rawPct)) return null; - const rounded = Math.max(0, Math.min(100, Math.round(rawPct))); + const rounded = resolveCapsuleQuotaSlotPct(quotas, slotKey); + if (rounded == null) return null; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), }; } -function formatCompactCapsuleCost(costUsd) { - if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--'; - const val = Math.max(0, Number(costUsd)); - if (val === 0) return '$0.00'; - if (val < 0.001) return '<$0.001'; - if (val < 1) return `$${val.toFixed(3)}`; - if (val < 100) return `$${val.toFixed(2)}`; - return `$${Math.round(val)}`; -} - -function formatCompactCapsuleTtft(ttftSec) { - if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; - const val = Number(ttftSec); - if (val < 1) return `${val.toFixed(2)}s`; - if (val < 100) return `${val.toFixed(1)}s`; - return `${Math.round(val)}s`; -} - /** * 解析顶栏/输入框精简胶囊单槽位展示结构。 * @@ -8747,15 +9666,16 @@ function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumference) }; } -function translateRawAgentBadge(rawBadge) { - if (!rawBadge) return ''; - if (!isEnglishLocale()) return String(rawBadge); - const str = String(rawBadge).trim(); - if (str === '主') return t('fmt.mainBadge'); - const m = str.match(/^子(\d+)$/); - if (m) return t('fmt.subBadge', { index: m[1] }); - if (str === '子') return t('fmt.subBadgeShort'); - return str; +function resolveActiveBadgeText(active) { + if (!active?.activeAgentBadge && !active?.activeAgentKind) return ''; + return formatAgentBadgeText({ + agentKind: + active.activeAgentKind || + (!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'), + agentOrdinal: Number(active.activeAgentOrdinal || 0), + isMain: !active.activeAgentId || active.activeAgentId === 'main', + badgeText: active.activeAgentBadge, + }); } /** @@ -8777,7 +9697,7 @@ function resolveOverviewMetricCell(metricKey, cellCtx = {}) { fallback: t('fmt.unknownModel'), }).text; const reason = speedReasonText(active.latestSpeedReason); - const badgeStr = translateRawAgentBadge(active.activeAgentBadge); + const badgeStr = resolveActiveBadgeText(active); const modelAndAgent = hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay; const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0; @@ -8967,8 +9887,11 @@ function resolveOverviewMetricCell(metricKey, cellCtx = {}) { subClass: 'cell-sub', }; } +return { CAPSULE_METRIC_KEYS, getCapsuleMetricOptions, getOverviewMetricOptions, resolveQuotaCapsuleSummary, resolveSpecificQuotaSlotSummary, resolveCapsuleMetricPresentation, resolveOverviewMetricCell }; +})(); // --- src/components/widgets/MetricMatrixWidget.js --- +const { MetricMatrixWidget } = (() => { /** * @fileoverview Standalone decoupled Metric Matrix Widget (`MetricMatrixWidget.js`). * Renders 1..4 user-selected telemetry cells dynamically via `metricRegistry.js`. @@ -9061,8 +9984,11 @@ const MetricMatrixWidget = defineComponent({ }; }, }); +return { MetricMatrixWidget }; +})(); // --- src/components/widgets/ContextWindowWidget.js --- +const { CTX_CHANNEL_DEFS, ContextWindowWidget } = (() => { /** * @fileoverview Standalone decoupled Context Window Widget (`ContextWindowWidget.js`). * Supports both interactive multi-agent inspector mode (`LiveOverviewView`) @@ -9355,12 +10281,16 @@ const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (hasSubagents && ctxAgent) { - const rawActiveBadge = aggregated?.activeAgentBadge || '主'; - const activeBadgeText = isEnglishLocale() - ? rawActiveBadge === '主' - ? t('fmt.mainBadge') - : rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) - : rawActiveBadge; + const activeBadgeText = formatAgentBadgeText({ + agentKind: + aggregated?.activeAgentKind || + (!aggregated?.activeAgentId || aggregated.activeAgentId === 'main' + ? 'main' + : 'subagent'), + agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0), + isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main', + badgeText: aggregated?.activeAgentBadge, + }); const pillItems = [ { @@ -9551,8 +10481,11 @@ const ContextWindowWidget = defineComponent({ }; }, }); +return { CTX_CHANNEL_DEFS, ContextWindowWidget }; +})(); // --- src/components/widgets/QuotaPoolsWidget.js --- +const { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, QuotaPoolsWidget } = (() => { /** * @fileoverview Standalone decoupled Quota Pools Widget (`QuotaPoolsWidget.js`). * Renders dynamic multi-pool quota bars (Gemini, Argon/Carbon, Claude & GPT) @@ -9900,20 +10833,81 @@ const QuotaPoolsWidget = defineComponent({ }; }, }); +return { buildQuotaPoolItems, createPoolQuotaRow, formatQuotaSummaryFooter, syncPoolQuotaRow, quotaPoolRowSig, QuotaPoolsWidget }; +})(); // --- src/components/widgets/LiveActivityWidget.js --- +const { buildFallbackRunningConversations, LiveActivityWidget } = (() => { /** * @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`). * Displays active multi-session running conversations & collapsible subagent activity - * with an isolated 1s elapsed timer lifecycle. + * with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode + * and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`). */ +function buildFallbackRunningConversations( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + if (!data) return []; + if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) { + return data.runningConversations; + } + const activeConv = data.activeConversation || {}; + if (!activeConv.isRunning && !aggregated?.isRunning) return []; + return [ + { + cascadeId: activeConv.cascadeId || 'current', + title: activeConv.title || t('live.currentSession'), + isCurrentSelected: true, + isMainRunning: Boolean(activeConv.isRunning), + isRunning: true, + mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, + subagentCount: Math.max(0, (agents?.length || 1) - 1), + runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, + ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), + ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), + subagents: (agents || []) + .filter((a) => !a.isMain) + .map((s, idx) => ({ + cascadeId: s.cascadeId || s.agentId, + index: s.index || idx + 1, + agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), + customRole: s.customRole, + ...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}), + badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), + shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, + role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, + isRunning: Boolean(s.isRunning), + stepCount: Number(s.stepCount || 0), + lastModifiedMs: s.lastModifiedMs || 0, + liveActivity: s.liveActivity || { + phase: s.isRunning ? 'thinking' : 'done', + actionKey: s.isRunning ? 'thinking' : 'done', + label: s.isRunning ? t('live.thinking') : t('live.done'), + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ]; +} + const LiveActivityWidget = defineComponent({ name: 'LiveActivityWidget', setup({ props, onCleanup }) { const interactive = props.interactive !== false; const preview = Boolean(props.preview); + const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs); + const showSessionExtras = Boolean(props.showSessionExtras); + const onSelectSession = + typeof props.onSelectSession === 'function' ? props.onSelectSession : null; + const onLayoutChange = + typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null; const getCtxAgentId = typeof props.getCtxAgentId === 'function' ? props.getCtxAgentId @@ -9927,10 +10921,19 @@ const LiveActivityWidget = defineComponent({ 'aria-live': 'polite', }); - const expandedTaskConvIds = new Set(); + const manualSubExpandMap = new Map(); const activityTimersMap = new Map(); let liveTickTimer = null; - let latestData = null; + let latestUpdateArgs = null; + + function resolveIsExpanded(item) { + const runSubCount = Number(item?.runningSubagentCount || 0); + if (!interactive) return runSubCount > 0; + if (manualSubExpandMap.has(item.cascadeId)) { + return Boolean(manualSubExpandMap.get(item.cascadeId)); + } + return defaultExpandRunningSubs ? runSubCount > 0 : false; + } function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); @@ -9993,6 +10996,20 @@ const LiveActivityWidget = defineComponent({ className: 'live-task-title', text: t('live.currentSession'), }); + const hereTagEl = showSessionExtras + ? h('span', { + className: 'wm-session-tag is-here', + hidden: true, + text: t('multi.hereTag'), + }) + : null; + const metricsEl = showSessionExtras + ? h('span', { + className: 'wm-task-metrics text-mono', + hidden: true, + text: '', + }) + : null; const subToggleBtn = h('button', { type: 'button', className: 'live-sub-toggle', @@ -10005,8 +11022,16 @@ const LiveActivityWidget = defineComponent({ }); const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), - h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), + h('div', { className: 'live-task-title-wrap' }, [ + dotWrap, + titleEl, + ...(hereTagEl ? [hereTagEl] : []), + ]), + h('div', { className: 'live-task-header-right' }, [ + ...(metricsEl ? [metricsEl] : []), + subToggleBtn, + elapsedEl, + ]), ]); const mainBadge = h('span', { @@ -10047,6 +11072,8 @@ const LiveActivityWidget = defineComponent({ cardEl, dotIcon, titleEl, + hereTagEl, + metricsEl, subToggleBtn, elapsedEl, mainBadge, @@ -10085,103 +11112,86 @@ const LiveActivityWidget = defineComponent({ }; } - function update({ data } = {}) { - latestData = data || null; - if (!data) { + function update({ data = null, items = null, hostRouteConversationId = '' } = {}) { + latestUpdateArgs = { data, items, hostRouteConversationId }; + if (!data && !Array.isArray(items)) { patchAttr(liveActivityBar, 'hidden', true); stopLiveTicker(); return; } - const { agents, aggregated } = resolveScopedConversation( - data, - 'all', - getCtxAgentId() - ); + let rawRunningList = Array.isArray(items) ? items : null; + if (!rawRunningList) { + const { agents, aggregated } = resolveScopedConversation( + data, + 'all', + getCtxAgentId() + ); + rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated }); + } - const rawRunningList = - Array.isArray(data.runningConversations) && data.runningConversations.length > 0 - ? data.runningConversations - : data.activeConversation?.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: data.activeConversation?.cascadeId || 'current', - title: data.activeConversation?.title || t('live.currentSession'), - isCurrentSelected: true, - isMainRunning: Boolean(data.activeConversation?.isRunning), - isRunning: true, - mainActivity: - data.activeConversation?.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, agents.length - 1), - runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length, - subagents: agents - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; + if (manualSubExpandMap.size > 0) { + const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); + for (const id of [...manualSubExpandMap.keys()]) { + if (!runningIdsSet.has(id)) { + manualSubExpandMap.delete(id); + } + } + } const hasRunningTasks = rawRunningList.length > 0; patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - expandedTaskConvIds.clear(); + patchKeyedList(liveActivityBar, [], {}); return; } + if (!isVisibleFn()) { + pauseTicker(); + return; + } + + const locale = getEffectiveLocale(); + const hostRouteLower = showSessionExtras + ? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase() + : ''; + const activeTimerKeys = new Set(); for (const item of rawRunningList) { activeTimerKeys.add(`main:${item.cascadeId}`); - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const isExp = resolveIsExpanded(item); + if (subCount > 0 && isExp) { + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } } } } - const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of [...expandedTaskConvIds]) { - if (!runningIdsSet.has(id)) { - expandedTaskConvIds.delete(id); - } - } - - const locale = getEffectiveLocale(); patchKeyedList(liveActivityBar, rawRunningList, { keyFn: (item) => item.cascadeId, sigFn: (item) => { - const isExp = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : Number(item.runningSubagentCount || 0) > 0; + const isExp = resolveIsExpanded(item); + const isHere = + showSessionExtras && + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; const subSig = (item.subagents || []) .map( (s) => `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { const act = item.mainActivity || { phase: 'thinking', + actionKey: 'thinking', label: t('live.thinking'), detail: '', stepProgress: '', @@ -10200,9 +11210,18 @@ const LiveActivityWidget = defineComponent({ const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); patchText(refs.titleEl, convTitle); if (interactive && !preview) { - patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle })); - refs.titleEl.onclick = () => { - if (item.cascadeId && item.cascadeId !== 'current') { + patchAttr( + refs.titleEl, + 'title', + onSelectSession + ? t('multi.inspectSessionTitle', { title: convTitle }) + : t('live.switchSessionTitle', { title: convTitle }) + ); + refs.titleEl.onclick = (e) => { + e?.stopPropagation?.(); + if (onSelectSession) { + onSelectSession(item.cascadeId); + } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); telemetryStore.setState({ selectedConversationId: item.cascadeId }); fetchTelemetry({ force: false }); @@ -10210,11 +11229,32 @@ const LiveActivityWidget = defineComponent({ }; } + if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + patchText(refs.hereTagEl, t('multi.hereTag')); + patchAttr(refs.hereTagEl, 'hidden', !isHere); + + const metricParts = []; + if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { + metricParts.push( + `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` + ); + } + if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { + metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); + } + const metricsStr = metricParts.join(' · '); + patchAttr(refs.metricsEl, 'hidden', !metricsStr); + if (metricsStr) { + patchText(refs.metricsEl, metricsStr); + } + } + const subCount = Number(item.subagentCount || item.subagents?.length || 0); const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : runSubCount > 0; + const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); @@ -10234,39 +11274,37 @@ const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - if (expandedTaskConvIds.has(item.cascadeId)) { - expandedTaskConvIds.delete(item.cascadeId); - } else { - expandedTaskConvIds.add(item.cascadeId); - } - if (latestData) update({ data: latestData }); + manualSubExpandMap.set(item.cascadeId, !isExpanded); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); }; } } + const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); + const detailStr = formatLiveActivityDetail(act); const mainTimerKey = `main:${item.cascadeId}`; activeTimerKeys.add(mainTimerKey); bindLiveElapsedTimer( mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, + `${item.cascadeId}:${act.signature || mainLabel}`, act.startedAtMs, refs.elapsedEl ); - patchText(refs.mainPhase, act.label || t('live.thinking')); + patchText(refs.mainPhase, mainLabel); const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; patchAttr(refs.mainProgress, 'hidden', !progText); if (progText) { patchText(refs.mainProgress, progText); } - const detailStr = act.detail || ''; patchAttr(refs.mainSep, 'hidden', !detailStr); patchAttr(refs.mainDetail, 'hidden', !detailStr); patchText(refs.mainDetail, detailStr); - if (interactive) { - const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; + if (interactive && !showSessionExtras) { + const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; patchAttr(refs.cardEl, 'title', fullTooltip); } @@ -10282,6 +11320,7 @@ const LiveActivityWidget = defineComponent({ updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { phase: sub.isRunning ? 'thinking' : 'done', + actionKey: sub.isRunning ? 'thinking' : 'done', label: sub.isRunning ? t('live.thinking') : t('live.done'), detail: '', stepProgress: '', @@ -10298,20 +11337,30 @@ const LiveActivityWidget = defineComponent({ patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); patchText(subRefs.subBadge, subBadgeText); - const roleText = sub.role || sub.shortLabel || t('fmt.subAgent'); + const fallbackRole = + sub.agentKind === 'side_question' || sub.isSideQuestion + ? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}` + : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; + const roleText = + sub.customRole !== undefined + ? sub.customRole || fallbackRole + : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); - const rawSubLabel = sub.isRunning - ? subAct.label || '' - : subAct.label || t('live.done'); + const subLabel = sub.isRunning + ? formatLiveActivityLabel(subAct, 'live.running') + : formatLiveActivityLabel(subAct, 'live.done'); + const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || ''] - .filter(Boolean) - .join(' '); + const summaryStr = showSessionExtras + ? sub.isRunning + ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` + : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) + : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); - if (interactive) { + if (interactive && !showSessionExtras) { patchAttr( subRefs.rowEl, 'title', @@ -10324,8 +11373,8 @@ const LiveActivityWidget = defineComponent({ activeTimerKeys.add(subTimerKey); bindLiveElapsedTimer( subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs, + `${sub.cascadeId}:${subAct.signature || subLabel}`, + subAct.startedAtMs || sub.lastModifiedMs, subRefs.subElapsed ); } else { @@ -10365,8 +11414,11 @@ const LiveActivityWidget = defineComponent({ }; }, }); +return { buildFallbackRunningConversations, LiveActivityWidget }; +})(); // --- src/registries/widgetRegistry.js --- +const { OVERVIEW_WIDGET_KEYS, OVERVIEW_WIDGET_REGISTRY, getOverviewModuleOptions, createDynamicWidgetHost } = (() => { /** * @fileoverview Decoupled Overview & Hover Widget Registry (`widgetRegistry.js`). * Maps module keys (`metrics`, `context`, `quotas`, `live_tasks`) to standalone @@ -10375,12 +11427,7 @@ const LiveActivityWidget = defineComponent({ */ -const OVERVIEW_WIDGET_KEYS = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); +const OVERVIEW_WIDGET_KEYS = OVERVIEW_MODULE_KEYS; const OVERVIEW_WIDGET_REGISTRY = Object.freeze({ metrics: { @@ -10576,8 +11623,11 @@ function createDynamicWidgetHost({ destroy, }; } +return { OVERVIEW_WIDGET_KEYS, OVERVIEW_WIDGET_REGISTRY, getOverviewModuleOptions, createDynamicWidgetHost }; +})(); // --- src/registries/stepColumnRegistry.js --- +const { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeader, STEP_COLUMN_REGISTRY, getStepColumnOptions } = (() => { /** * @fileoverview Decoupled Step Table Column Registry (`stepColumnRegistry.js`). * Defines all 12 customizable columns for `StepsDetailView` ("按步查看"), @@ -10586,32 +11636,11 @@ function createDynamicWidgetHost({ */ -const STEP_COLUMN_KEYS = Object.freeze([ - 'step', - 'time', - 'model', - 'tps', - 'ttft', - 'duration', - 'tokens_combo', - 'tokens_io_cache', - 'tokens_custom', - 'input_tokens', - 'cache_tokens', - 'output_tokens', - 'cache', - 'cost', -]); - -const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([ - 'step', - 'model', - 'tps', - 'ttft', - 'tokens_combo', - 'cache', - 'cost', -]); +const STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS; +const DEFAULT_STEP_COLUMN_KEYS = DEFAULT_STEP_TABLE_COLUMNS; +const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT; +const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat; +const parseClientStepTokenComboSegments = parseStepTokenComboSegments; function resolveStepTokenParts(st) { const inTok = Math.max(0, Number(st?.inputTokens || 0)); @@ -10785,7 +11814,7 @@ const STEP_COLUMN_REGISTRY = Object.freeze({ if (reason && !refs.speedReason) { refs.speedReason = h('div', { className: 'text-muted', - style: 'font-size: var(--fs-2xs);', + style: 'font-size: var(--fs-xs);', }); refs.wrapEl.appendChild(refs.speedReason); } @@ -11015,8 +12044,11 @@ function getStepColumnOptions( label: STEP_COLUMN_REGISTRY[key].optLabel(ctx), })); } +return { STEP_COLUMN_KEYS, DEFAULT_STEP_COLUMN_KEYS, formatCustomTokenComboHeader, STEP_COLUMN_REGISTRY, getStepColumnOptions }; +})(); // --- src/components/widgets/CapsuleBarWidget.js --- +const { RING_RADIUS, RING_CIRCUMFERENCE, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget } = (() => { /** * @fileoverview Shared Decoupled Capsule Bar Primitives & Widget (`CapsuleBarWidget.js`). * Powers both the live host window capsule (`WindowOverlayShell.js`) and the @@ -11027,6 +12059,91 @@ function getStepColumnOptions( const RING_RADIUS = 5.2; const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); +/** + * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. + */ +function buildCapsuleSlotContext( + data, + { scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {} +) { + if (!data) return { hasTelemetry: false }; + const activeConv = data.activeConversation || {}; + const overviewActive = overviewConv || scopedConv || aggregated || activeConv; + const capActive = scopedConv || aggregated || activeConv || {}; + const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; + const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); + const totalTokens = Number(ctx.totalTokens || 0); + const usedPct = + limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; + const dashOffset = +( + RING_CIRCUMFERENCE * + (1 - Math.max(0, Math.min(100, usedPct)) / 100) + ).toFixed(2); + + const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); + const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); + const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); + const sessionTokens = + Number(capActive.stepCount || 0) > 0 || + capActive.totalTokens != null || + capInTok + capCacheTok + capOutTok > 0 + ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) + : null; + + return { + hasTelemetry: true, + usedPct, + dashOffset, + isRunning, + tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, + avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, + ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null, + stepCost: + scopedConv?.latestStepCostUsd ?? + aggregated?.latestStepCostUsd ?? + activeConv.latestStepCostUsd ?? + null, + sessionCost: + scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null, + cacheHitPct: + Number(capActive.stepCount || 0) > 0 + ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null + : null, + latestPromptTokens: capActive.latestPromptTokens ?? null, + sessionTokens, + quotas: data.quotas, + }; +} + +/** + * Compute multi-session button state & normalized running conversation list. + */ +function resolveMultiSessionCapsuleState( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + const rawRunningList = buildFallbackRunningConversations(data, { + agents, + aggregated, + latestTokPerSec, + contextUsedPct, + }); + const runningCount = rawRunningList.length; + const runningSubCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSubagentCount || 0), + 0 + ); + const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const multiBtnText = + runningCount > 0 + ? runningSubCount > 0 + ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) + : t('capsule.multiRunning', { count: runningCount }) + : t('capsule.multiZero'); + return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText }; +} + /** * Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring. */ @@ -11231,11 +12348,6 @@ const CapsuleBarWidget = defineComponent({ ] ); - const titlebarRightMock = h('div', { className: 'preview-win-controls', 'aria-hidden': 'true' }, [ - h('span', { className: 'preview-win-dot' }), - h('span', { className: 'preview-win-dot' }), - h('span', { className: 'preview-win-dot' }), - ]); const composerSendMock = h( 'span', { className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true }, @@ -11245,7 +12357,7 @@ const CapsuleBarWidget = defineComponent({ const hostBarEl = h( 'div', { className: 'preview-capsule-bar', 'data-mount-mode': 'dual' }, - [titlebarLeftMock, composerLeftMock, capsuleCluster, titlebarRightMock, composerSendMock] + [titlebarLeftMock, composerLeftMock, capsuleCluster, composerSendMock] ); const sidebarHintEl = h('div', { @@ -11274,7 +12386,6 @@ const CapsuleBarWidget = defineComponent({ }); patchAttr(titlebarLeftMock, 'hidden', isComposer); - patchAttr(titlebarRightMock, 'hidden', isComposer); patchAttr(composerLeftMock, 'hidden', !isComposer); patchAttr(composerSendMock, 'hidden', !isComposer); patchAttr(sidebarHintEl, 'hidden', !isSidebar); @@ -11289,75 +12400,26 @@ const CapsuleBarWidget = defineComponent({ return; } - const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( + const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation( data, 'all', 'auto' ); - const activeConv = data.activeConversation || {}; - const capActive = scopedConv || aggregated || activeConv; - const ctx = ctxAgent?.context || capActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - - const rawRunningList = Array.isArray(data.runningConversations) - ? data.runningConversations - : []; - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated }); + const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, { + agents, + aggregated, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps: capActive.latestTokPerSec ?? null, - avgTps: capActive.avgTokPerSec ?? null, - ttft: capActive.latestTtftSec ?? null, - stepCost: capActive.latestStepCostUsd ?? null, - sessionCost: capActive.sessionCostUsd ?? null, - cacheHitPct: - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null, - latestPromptTokens: capActive.latestPromptTokens ?? null, - sessionTokens, - quotas: data.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } return { @@ -11373,8 +12435,11 @@ const CapsuleBarWidget = defineComponent({ }; }, }); +return { RING_RADIUS, RING_CIRCUMFERENCE, buildCapsuleSlotContext, resolveMultiSessionCapsuleState, createCapsuleSlotNode, syncCapsuleSlotNodes, CapsuleBarWidget }; +})(); // --- src/components/widgets/StepTableWidget.js --- +const { formatTurnPromptText, StepTableWidget } = (() => { /** * @fileoverview Reusable Decoupled Step Table Widget (`StepTableWidget.js`). * Powers both `StepsDetailView` ("按步查看") and `SettingsStructureTab` live preview, @@ -11383,14 +12448,11 @@ const CapsuleBarWidget = defineComponent({ */ -function formatTurnPromptText(rawPrompt) { +function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) { const text = String(rawPrompt || '').trim(); - if (!text || !isEnglishLocale()) return text; - if (text === '[图片/附件提问]') return t('steps.turnMediaOnly'); - if (text.endsWith(' [附图]')) { - return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`; - } - return text; + if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly'); + if (!text) return ''; + return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } const StepTableWidget = defineComponent({ @@ -11570,7 +12632,13 @@ const StepTableWidget = defineComponent({ const getStepIsLatest = (st) => Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); const getStepPrompt = (st) => - (useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || ''; + (useRootTurn + ? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt) + : (st?.turnPromptClean ?? st?.turnPrompt)) || ''; + const getStepHasMedia = (st) => + Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia); + const getStepMediaOnly = (st) => + Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly); const turnKeys = showStepTurnRail ? tableSteps.map((st) => { const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; @@ -11579,8 +12647,13 @@ const StepTableWidget = defineComponent({ const formattedPrompts = new Map(); function formattedTurnPrompt(st) { const raw = getStepPrompt(st); - if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw)); - return formattedPrompts.get(raw); + const hasMedia = getStepHasMedia(st); + const mediaOnly = getStepMediaOnly(st); + const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`; + if (!formattedPrompts.has(cacheKey)) { + formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly })); + } + return formattedPrompts.get(cacheKey); } const decoratedSteps = tableSteps.map((st, idx) => { @@ -11702,26 +12775,38 @@ const StepTableWidget = defineComponent({ const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : ''; patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`); - const badgeText = isEnglishLocale() - ? formatAgentBadgeText({ - isMain: !st.isSubagent, - index: st.agentIndex || 0, - badgeText: st.agentBadge, - }) - : st.agentBadge || (st.isSubagent ? '子' : '主'); + const badgeText = formatAgentBadgeText({ + agentKind: + st.agentKind || + (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), + isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, + index: st.agentIndex || 0, + badgeText: st.agentBadge, + }); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { const targetScope = st.agentId || 'main'; const isSoleTarget = effectiveScopes.length === 1 && effectiveScopes[0] === targetScope; - const agentName = isEnglishLocale() - ? formatAgentLabel({ - isMain: !st.isSubagent, - index: st.agentIndex || 0, - role: st.agentRole || '', - }) - : st.agentLabel || t('steps.unitAgent'); + const agentName = formatAgentLabel({ + agentKind: + st.agentKind || + (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), + customRole: st.agentCustomRole, + isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, + index: st.agentIndex || 0, + role: st.agentRole || '', + shortLabel: st.agentLabel || '', + }); patchAttr( refs.agentBadgeEl, 'title', @@ -11789,8 +12874,11 @@ const StepTableWidget = defineComponent({ }; }, }); +return { formatTurnPromptText, StepTableWidget }; +})(); // --- src/components/settings/structurePreviewMock.js --- +const { buildStructurePreviewTelemetry } = (() => { /** * @fileoverview Realistic Simulated Telemetry Builder (`structurePreviewMock.js`) * for `SettingsStructureTab` real-UI live previews. @@ -11819,7 +12907,9 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) totalTokens: 142800, limitTokens: 256000, compactionLimitTokens: 256000, + compactionUsedTokens: 142800, usedPct: 55.8, + messagesTokens: 119660, toolResultsTokens: 86400, assistantTokens: 24200, systemToolsTokens: 11800, @@ -11836,7 +12926,9 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) totalTokens: 72704, limitTokens: 256000, compactionLimitTokens: 256000, + compactionUsedTokens: 72704, usedPct: 28.4, + messagesTokens: 63704, toolResultsTokens: 51200, assistantTokens: 11400, systemToolsTokens: 5600, @@ -11990,6 +13082,9 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) responseTokens: 260, cacheHitPct: 0, costUsd: 0.198, + inCostUsd: 0.19, + cacheCostUsd: 0, + outCostUsd: 0.008, createdAtMs: anchorMinMs - 215_000, turnIndex: 1, rootTurnIndex: 1, @@ -12012,10 +13107,12 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) isRunning: true, stepCount: 16, speedSampleCount: 15, + speedSummary: { sampleCount: 15, excludedCount: 1 }, latestTokPerSec: 68.4, avgTokPerSec: 54.8, latestTtftSec: 1.15, avgTtftSec: 1.62, + ttftSummary: { avgSec: 1.62, sampleCount: 15 }, latestStepCostUsd: 0.042, sessionCostUsd: 1.16, latestCacheHitPct: 94.5, @@ -12031,6 +13128,24 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) latestUpstreamModel: 'gemini-4-carbon-high', activeModelLabel: 'Gemini 4 Carbon (High)', activeModelShort: 'gemini-4-carbon', + activeModelUpstream: 'gemini-4-carbon-high', + sessionUnpricedCalls: 0, + modelBreakdown: [ + { + modelKey: 'MODEL_PLACEHOLDER_M37', + modelShort: 'gemini-4-carbon', + modelLabel: 'Gemini 4 Carbon (High)', + upstreamModel: 'gemini-4-carbon-high', + calls: 16, + inputTokens: 152400, + cacheReadTokens: 1260000, + outputTokens: 22100, + thinkingTokens: 14200, + totalTokens: 1434500, + costUsd: 1.16, + sharePct: 100, + }, + ], context: mainContext, recentSteps: mockSteps.filter((s) => !s.isSubagent), }; @@ -12046,10 +13161,12 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) isRunning: false, stepCount: 8, speedSampleCount: 8, + speedSummary: { sampleCount: 8, excludedCount: 0 }, latestTokPerSec: 96.2, avgTokPerSec: 88.5, latestTtftSec: 0.68, avgTtftSec: 0.82, + ttftSummary: { avgSec: 0.82, sampleCount: 8 }, latestStepCostUsd: 0.009, sessionCostUsd: 0.12, latestCacheHitPct: 88.1, @@ -12065,33 +13182,69 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) latestUpstreamModel: 'gemini-3.8-flash-n', activeModelLabel: 'Gemini 3.8 Flash', activeModelShort: 'gemini-3.8-flash', + activeModelUpstream: 'gemini-3.8-flash-n', + sessionUnpricedCalls: 0, + modelBreakdown: [ + { + modelKey: 'MODEL_PLACEHOLDER_M42', + modelShort: 'gemini-3.8-flash', + modelLabel: 'Gemini 3.8 Flash', + upstreamModel: 'gemini-3.8-flash-n', + calls: 8, + inputTokens: 34000, + cacheReadTokens: 280000, + outputTokens: 6300, + thinkingTokens: 2100, + totalTokens: 320300, + costUsd: 0.12, + sharePct: 100, + }, + ], context: subContext, recentSteps: mockSteps.filter((s) => s.isSubagent), }; const aggregated = { ...mainAgent, + agentId: 'all', + isMain: false, + agentKind: 'all', + agentOrdinal: 0, + badgeText: t('header.scopeAllShort'), + activeAgentId: 'main', + activeAgentKind: 'main', + activeAgentOrdinal: 0, stepCount: 24, speedSampleCount: 23, + speedSummary: { sampleCount: 23, excludedCount: 1 }, avgTokPerSec: 59.6, avgTtftSec: 1.38, + ttftSummary: { avgSec: 1.38, sampleCount: 23 }, sessionCostUsd: 1.28, + sessionUnpricedCalls: 0, sessionCacheHitPct: 88.9, inputTokens: 186400, cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, - activeAgentBadge: '主', + activeAgentBadge: t('fmt.mainBadge'), + modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; return { settings: mergedSettings, account: { - planName: 'Google AI Pro', - aiCredits: 1200, + tierName: 'Google AI Ultra', + planName: 'Pro', + aiCredits: 0, }, quotas: { + meta: { + hasOfficialData: true, + isStale: false, + refreshFailed: false, + }, activePool: { family: 'Gemini', poolKey: 'Gemini', @@ -12193,8 +13346,11 @@ function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides = {}) }, }; } +return { buildStructurePreviewTelemetry }; +})(); // --- src/components/settings/CollapsibleSection.js --- +const { CollapsibleSection } = (() => { /** * @fileoverview Reusable Section Card (`CollapsibleSection.js`) * for `SettingsStructureTab` — supports both accordion mode (`collapsible: true`) @@ -12363,8 +13519,11 @@ const CollapsibleSection = defineComponent({ }; }, }); +return { CollapsibleSection }; +})(); // --- src/components/settings/EditableSlotList.js --- +const { EditableSlotList } = (() => { /** * @fileoverview Reusable Drag-Sortable & `+` / `-` / `↑` / `↓` Dynamic Slot List (`EditableSlotList.js`). * Powers Topbar Capsule Slots (1..5), Hover Popup Modules (0..4), @@ -12806,8 +13965,11 @@ const EditableSlotList = defineComponent({ }; }, }); +return { EditableSlotList }; +})(); // --- src/components/settings/ThemeColorPicker.js --- +const { ThemeColorPicker } = (() => { /** * @fileoverview Host-aware Theme Accent Swatch Picker (`ThemeColorPicker.js`). * Provides the default "跟随宿主" (`host`) pill plus 6 curated color swatches. @@ -12908,8 +14070,313 @@ const ThemeColorPicker = defineComponent({ }; }, }); +return { ThemeColorPicker }; +})(); + +// --- src/components/settings/BridgeStatusNotice.js --- +const { BridgeStatusNotice } = (() => { +/** + * @fileoverview Shared CDP / Window Bridge diagnostic & one-click relaunch card (`BridgeStatusNotice.js`). + * Surfaces automatic shortcut provisioning status and a one-click host relaunch button when + * Antigravity 2.33.0+ runs without an active `DevToolsActivePort` (`no_devtools_port` / `cdp_unreachable`). + */ + + +const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0'; + +async function copyTextToClipboard(text) { + try { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + } catch { + // Fallback to temporary textarea inside restricted webview contexts + } + try { + if (typeof document === 'undefined' || !document.body) return false; + const area = document.createElement('textarea'); + area.value = text; + area.setAttribute('readonly', 'true'); + area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; + document.body.appendChild(area); + area.select?.(); + const ok = Boolean(document.execCommand?.('copy')); + document.body.removeChild(area); + return ok; + } catch { + return false; + } +} + +const BridgeStatusNotice = defineComponent({ + name: 'BridgeStatusNotice', + setup({ props, onCleanup }) { + let contextMode = Boolean(props?.contextMode); + const dismissible = Boolean(props?.dismissible); + let lastPayload = { + visible: false, + windowBridge: null, + hostPlatform: 'win32', + }; + let dismissed = false; + let copied = false; + let copiedTimer = null; + let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed' + let relaunchResetTimer = null; + let destroyed = false; + + const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' }); + const titleEl = h('strong', { className: 'settings-bridge-title', text: '' }); + const bodyEl = h('p', { className: 'settings-bridge-desc', text: '' }); + + const dismissBtnEl = dismissible + ? h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm settings-bridge-dismiss-btn', + 'aria-label': t('settings.bridge.dismissAria'), + title: t('settings.bridge.dismissAria'), + onClick: () => { + dismissed = true; + render(); + props?.onDismiss?.(); + }, + }, + [createSvgIcon('close', { size: 11 })] + ) + : null; + + const relaunchBtnIconEl = createSvgIcon('refresh', { size: 11 }); + const relaunchBtnTextEl = h('span', { + className: 'settings-bridge-relaunch-text', + text: t('settings.bridge.relaunchBtn'), + }); + const relaunchBtnEl = h( + 'button', + { + type: 'button', + className: 'settings-bridge-relaunch-btn', + onClick: async () => { + if (relaunchState === 'relaunching' || destroyed) return; + relaunchState = 'relaunching'; + if (relaunchResetTimer) { + clearTimeout(relaunchResetTimer); + relaunchResetTimer = null; + } + syncActionButtons(); + try { + const res = await triggerBridgeHostRelaunch(); + if (destroyed) return; + if (!res || res.ok === false) { + relaunchState = 'failed'; + syncActionButtons(); + relaunchResetTimer = setTimeout(() => { + relaunchResetTimer = null; + if (destroyed) return; + relaunchState = 'idle'; + syncActionButtons(); + }, 3500); + relaunchResetTimer?.unref?.(); + return; + } + // Reset button if host is still open after 9s (e.g. cancelled close prompt) + relaunchResetTimer = setTimeout(() => { + relaunchResetTimer = null; + if (destroyed) return; + relaunchState = 'idle'; + syncActionButtons(); + }, 9000); + relaunchResetTimer?.unref?.(); + } catch { + if (destroyed) return; + relaunchState = 'failed'; + syncActionButtons(); + relaunchResetTimer = setTimeout(() => { + relaunchResetTimer = null; + if (destroyed) return; + relaunchState = 'idle'; + syncActionButtons(); + }, 3500); + relaunchResetTimer?.unref?.(); + } + }, + }, + [relaunchBtnIconEl, relaunchBtnTextEl] + ); + + const copyBtnIconEl = createSvgIcon('copy', { size: 11 }); + const copyBtnTextEl = h('span', { + className: 'settings-bridge-copy-text', + text: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }), + }); + const copyBtnEl = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm settings-bridge-copy-btn', + onClick: async () => { + await copyTextToClipboard(LAUNCH_FLAG_TEXT); + if (destroyed) return; + copied = true; + if (copiedTimer) clearTimeout(copiedTimer); + syncActionButtons(); + copiedTimer = setTimeout(() => { + copiedTimer = null; + if (destroyed) return; + copied = false; + syncActionButtons(); + }, 1800); + copiedTimer?.unref?.(); + }, + }, + [copyBtnIconEl, copyBtnTextEl] + ); + + const headLeftEl = h('div', { className: 'settings-bridge-head-main' }, [headIconEl, titleEl]); + const headRowEl = h( + 'div', + { className: 'settings-bridge-head' }, + dismissBtnEl ? [headLeftEl, dismissBtnEl] : [headLeftEl] + ); + const actionsRowEl = h('div', { className: 'settings-bridge-actions' }, [ + relaunchBtnEl, + copyBtnEl, + ]); + + const rootEl = h( + 'div', + { + className: 'settings-bridge-notice', + role: 'status', + hidden: true, + }, + [headRowEl, bodyEl, actionsRowEl] + ); + + function syncActionButtons() { + const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; + patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); + patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); + patchText( + relaunchBtnTextEl, + relaunchState === 'relaunching' + ? t('settings.bridge.relaunchingBtn') + : relaunchState === 'failed' + ? t('settings.bridge.relaunchFailed') + : t('settings.bridge.relaunchBtn') + ); + + patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); + patchText( + copyBtnTextEl, + copied + ? t('settings.bridge.copiedBtn') + : t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }) + ); + + if (dismissBtnEl) { + const aria = t('settings.bridge.dismissAria'); + patchAttr(dismissBtnEl, 'aria-label', aria); + patchAttr(dismissBtnEl, 'title', aria); + } + } + + function render() { + const wb = lastPayload.windowBridge; + const state = String(wb?.state || '').trim(); + if (state === 'active') { + dismissed = false; + } + const shouldShow = + !dismissed && + Boolean(lastPayload.visible) && + !isWindowOverlayMode() && + (state === 'no_devtools_port' || state === 'cdp_unreachable'); + + patchAttr(rootEl, 'hidden', !shouldShow); + if (!shouldShow) return; + + const isAutoConfigured = Boolean( + wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured + ); + patchClasses(rootEl, { + 'is-restart': isAutoConfigured, + 'is-warn': !isAutoConfigured, + }); + patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning'); + + let titleText = ''; + if (isAutoConfigured) { + titleText = contextMode + ? t('settings.bridge.ctxRestartTitle') + : t('settings.bridge.restartTitle'); + } else if (contextMode) { + titleText = t('settings.bridge.ctxTitle'); + } else if (state === 'cdp_unreachable') { + titleText = t('settings.bridge.unreachableTitle'); + } else { + titleText = t('settings.bridge.noPortTitle'); + } + + const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); + let bodyText = ''; + if (isAutoConfigured) { + bodyText = t('settings.bridge.restartBody'); + } else if (plat === 'darwin') { + bodyText = t('settings.bridge.guideMac'); + } else if (plat === 'linux') { + bodyText = t('settings.bridge.guideLinux'); + } else { + bodyText = t('settings.bridge.guideWin'); + } + + patchText(titleEl, titleText); + patchText(bodyEl, bodyText); + syncActionButtons(); + } + + function update(next = {}) { + if (typeof next.contextMode === 'boolean') { + contextMode = next.contextMode; + } + lastPayload = { + ...lastPayload, + ...next, + }; + render(); + } + + onCleanup(() => { + destroyed = true; + if (copiedTimer) { + clearTimeout(copiedTimer); + copiedTimer = null; + } + if (relaunchResetTimer) { + clearTimeout(relaunchResetTimer); + relaunchResetTimer = null; + } + }); + + return { + el: rootEl, + refs: { + update, + refreshLabels: render, + relaunchBtnEl, + copyBtnEl, + dismissBtnEl, + }, + }; + }, +}); +return { BridgeStatusNotice }; +})(); // --- src/views/settings/SettingsGeneralTab.js --- +const { SettingsGeneralTab } = (() => { /** * @fileoverview Preferences Tab 1: `SettingsGeneralTab.js` ("常规"). * Manages UI Language (`zh-CN` / `en-US` / `auto`), Theme Accent (`host` + 6 swatches), @@ -13372,8 +14839,11 @@ const SettingsGeneralTab = defineComponent({ }; }, }); +return { SettingsGeneralTab }; +})(); // --- src/views/settings/SettingsStructureTab.js --- +const { SettingsStructureTab } = (() => { /** * @fileoverview Preferences Tab 2: `SettingsStructureTab.js` ("结构"). * Organizes the 4 structure settings panes under a dedicated 3rd-level menu bar, @@ -13452,6 +14922,8 @@ const SettingsStructureTab = defineComponent({ let rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; let latestSettings = null; + let latestWindowBridge = null; + let latestHostPlatform = 'win32'; function isStructureVisible() { const st = uiStore.getState(); @@ -13662,6 +15134,8 @@ const SettingsStructureTab = defineComponent({ }, }); + const mountBridgeNotice = BridgeStatusNotice({}); + const mountSection = CollapsibleSection({ collapsible: false, icon: 'dock', @@ -13695,6 +15169,7 @@ const SettingsStructureTab = defineComponent({ mountPreviewCanvas, h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]), + mountBridgeNotice.el, h('div', { className: 'form-row' }, [ h('div', { className: 'settings-inline-row' }, [ popoverWidthLabelEl, @@ -13727,6 +15202,11 @@ const SettingsStructureTab = defineComponent({ modelValue: draftWindowMountMode, options: getMountModeOptions(), }); + mountBridgeNotice.refs.update({ + visible: draftWindowMountMode !== 'sidebar', + windowBridge: latestWindowBridge, + hostPlatform: latestHostPlatform, + }); popoverWidthModeToggle.setProps({ modelValue: draftPopoverWidthMode, options: getPopoverWidthModeOptions(), @@ -13782,7 +15262,7 @@ const SettingsStructureTab = defineComponent({ isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover', initialModuleKeys: [], }); - const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [ + const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ hoverPreviewTipEl, hoverPreviewEmptyEl, ]); @@ -13874,7 +15354,7 @@ const SettingsStructureTab = defineComponent({ isVisibleFn: () => isStructureVisible() && activeThirdTab === 'overview', initialModuleKeys: [], }); - const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [ + const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ overviewPreviewContainerEl, ]); @@ -14133,7 +15613,7 @@ const SettingsStructureTab = defineComponent({ items: draftStepColumns, options: getStepColumnOptions(draftStepTokenComboFormat), minItems: 2, - maxItems: 15, + maxItems: 14, addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }), onPreview: (previewItems) => { draftStepColumns = normalizeClientStepColumns(previewItems); @@ -14316,9 +15796,15 @@ const SettingsStructureTab = defineComponent({ stepsSection.el, ]); - function renderSettings(settings) { + function renderSettings( + settings, + windowBridge = latestWindowBridge, + hostPlatform = latestHostPlatform + ) { if (!settings) return; latestSettings = settings; + if (windowBridge !== undefined) latestWindowBridge = windowBridge; + if (hostPlatform) latestHostPlatform = hostPlatform; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay @@ -14420,6 +15906,7 @@ const SettingsStructureTab = defineComponent({ onCleanup(() => { unsubUi(); + mountBridgeNotice.destroy(); capsulePreviewWidget.destroy(); hoverPreviewHost.destroy(); overviewPreviewHost.destroy(); @@ -14448,6 +15935,7 @@ const SettingsStructureTab = defineComponent({ refs: { thirdNavBar, capsulePreviewWidget, + mountBridgeNotice, hoverPreviewHost, overviewPreviewHost, stepTablePreview, @@ -14472,240 +15960,11 @@ const SettingsStructureTab = defineComponent({ }; }, }); - -// --- src/views/settings/SettingsAccountTab.js --- -/** @fileoverview Saved account credentials and the host's active account quota. */ - - -const key = (name) => `settings.account.${name}`; -const errors = new Set([ - 'unsupported', 'invalidEmail', 'invalidCredential', 'credentialTooLarge', 'notFound', - 'noCurrentCredential', 'busy', 'storeFailed', 'rollbackFailed', 'credentialAccessDenied', - 'credentialChanged', 'credentialRejected', 'identityMismatch', 'oauthClientUnavailable', - 'oauthUnavailable', 'quotaUnavailable', -]); - -function renderQuotaRows(container, quotaPools) { - const locale = getEffectiveLocale(); - const pools = quotaPools.filter((pool) => Number.isFinite(pool.remainingPct) || Number.isFinite(pool.weeklyRemainingPct)); - patchKeyedList(container, pools, { - keyFn: (pool) => pool.poolKey || pool.poolLabel, - sigFn: (pool) => JSON.stringify([locale, pool.poolLabel, pool.remainingPct, pool.weeklyRemainingPct]), - createRow: () => { - const label = h('span'); - const remaining = h('span', { className: 'settings-account-quota' }); - return { el: h('div', { className: 'settings-action-block' }, [label, remaining]), refs: { label, remaining } }; - }, - updateRow: ({ label, remaining }, pool) => { - patchText(label, pool.poolLabel || pool.poolKey); - const values = []; - if (Number.isFinite(pool.remainingPct)) values.push(t(key('quota5h'), { percent: pool.remainingPct })); - if (Number.isFinite(pool.weeklyRemainingPct)) values.push(t(key('quotaWeekly'), { percent: pool.weeklyRemainingPct })); - patchText(remaining, values.join(' · ')); - }, - }); - return pools.length; -} - -const SettingsAccountTab = defineComponent({ - name: 'SettingsAccountTab', - setup({ props, onCleanup }) { - let account = null; - let quotas = null; - let accounts = []; - let selectedEmail = ''; - let supported = null; - let operation = ''; - let status = ''; - let disposed = false; - const savedQuotas = new Map(); - - const title = h('span', { className: 'panel-title' }); - const identityLabel = h('div', { className: 'settings-action-title' }); - const identity = h('div', { className: 'settings-action-desc settings-account-identity' }); - const plan = h('div', { className: 'settings-action-desc' }); - const quotaTitle = h('div', { className: 'settings-action-title' }); - const quotaRows = h('div', { className: 'settings-account-list' }); - const quotaMessage = h('div', { className: 'settings-action-desc' }); - const savedTitle = h('span', { className: 'panel-title' }); - const savedRows = h('div', { className: 'settings-account-list' }); - const savedMessage = h('div', { className: 'settings-action-desc' }); - const pending = h('div', { className: 'settings-action-desc', role: 'status' }); - const feedback = h('div', { className: 'settings-action-desc', role: 'status' }); - const capture = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('capture') }); - const reload = h('button', { type: 'button', className: 'btn-secondary', onClick: () => request('list') }); - const credentialLabel = h('span'); - const importHint = h('div', { className: 'settings-action-desc' }); - const credential = h('input', { type: 'password', required: true, autocomplete: 'off', spellcheck: 'false', maxlength: 16384 }); - const save = h('button', { type: 'submit', className: 'btn-secondary' }); - const form = h('form', { className: 'settings-account-form', autocomplete: 'off', onSubmit: importCredential }, [ - h('label', {}, [credentialLabel, credential]), - importHint, - save, - ]); - - function render() { - const signedIn = account?.status === 'signedIn'; - const activeEmail = signedIn ? account.email?.trim().toLowerCase() : ''; - const canWrite = supported === true && !operation; - const locale = getEffectiveLocale(); - patchText(title, t(key('current'))); - patchText(identityLabel, t(key('email'))); - patchText(identity, signedIn ? account.email || account.name : - t(key(account?.status === 'signedOut' ? 'signedOut' : 'unknown'))); - patchText(plan, signedIn ? account.tierName || account.planName || '' : ''); - patchAttr(plan, 'hidden', !plan.textContent); - - patchText(quotaTitle, t(key('quota'))); - const poolCount = renderQuotaRows(quotaRows, signedIn ? quotas?.pools || [] : []); - patchText(quotaMessage, t(key(poolCount ? 'quotaStale' : 'noQuota'))); - patchAttr(quotaMessage, 'hidden', poolCount > 0 && !quotas?.meta?.isStale); - - patchText(savedTitle, t(key('savedCredentials'))); - patchText(capture, t(key('capture'))); - patchText(reload, t(key('reload'))); - patchText(save, t(key('save'))); - patchText(credentialLabel, t(key('credential'))); - patchText(importHint, t(key('importHint'))); - patchAttr(capture, 'disabled', !canWrite || !activeEmail); - patchAttr(reload, 'disabled', Boolean(operation)); - patchAttr(form, 'hidden', supported === false); - patchAttr(save, 'disabled', !canWrite); - patchAttr(credential, 'disabled', !canWrite); - patchText(savedMessage, t(key(supported === null ? 'loading' : 'empty'))); - patchAttr(savedMessage, 'hidden', accounts.length > 0 || supported === false || Boolean(status)); - const message = status || (operation === 'switch' ? 'switching' : operation === 'quota' ? 'loadingQuota' : - operation === 'save' || operation === 'capture' ? 'verifying' : ''); - patchText(feedback, message ? t(key(message)) : ''); - patchAttr(feedback, 'hidden', !message); - const waiting = selectedEmail && activeEmail !== selectedEmail; - patchText(pending, waiting ? t(key('pending'), { email: selectedEmail }) : ''); - patchAttr(pending, 'hidden', !waiting); - - patchKeyedList(savedRows, accounts, { - keyFn: (addr) => addr, - sigFn: (addr) => JSON.stringify([locale, activeEmail, selectedEmail, canWrite, savedQuotas.get(addr)]), - createRow: (addr) => { - const state = h('div', { className: 'settings-action-desc' }); - const select = h('button', { - type: 'button', className: 'btn-secondary settings-account-switch', onClick: () => request('switch', { email: addr }), - }); - const remove = h('button', { - type: 'button', className: 'btn-secondary', onClick: () => request('remove', { email: addr }), - }); - const loadQuota = h('button', { - type: 'button', className: 'btn-secondary settings-account-load-quota', onClick: () => request('quota', { email: addr }), - }); - const rows = h('div', { className: 'settings-account-list' }); - const empty = h('div', { className: 'settings-action-desc' }); - return { - el: h('div', { className: 'settings-account-entry' }, [ - h('div', { className: 'settings-action-block' }, [ - h('div', { className: 'settings-action-info' }, [h('div', { className: 'settings-account-identity', text: addr }), state]), - h('div', { className: 'settings-account-buttons' }, [loadQuota, select, remove]), - ]), rows, empty, - ]), - refs: { state, select, remove, loadQuota, rows, empty }, - }; - }, - updateRow: (row, addr) => { - const active = addr === activeEmail; - const written = addr === selectedEmail && !active; - patchText(row.state, active ? t(key('active')) : written ? t(key('written')) : ''); - patchAttr(row.state, 'hidden', !active && !written); - patchText(row.select, t(key('switch'))); - patchText(row.remove, t(key('remove'))); - patchText(row.loadQuota, t(key('loadQuota'))); - patchAttr(row.select, 'disabled', !canWrite); - patchAttr(row.remove, 'disabled', !canWrite); - patchAttr(row.loadQuota, 'disabled', !canWrite); - const cached = savedQuotas.get(addr); - const count = renderQuotaRows(row.rows, cached || []); - patchText(row.empty, t(key('emptyCredentialQuota'))); - patchAttr(row.empty, 'hidden', !cached || count > 0); - }, - }); - props.onLayoutChange?.(); - } - - async function request(action, fields) { - if (operation) return; - operation = action; - status = ''; - render(); - try { - const result = action === 'list' - ? await callSidecarApi('/api/accounts') - : await callSidecarApi('/api/accounts/update', { method: 'POST', body: { action, ...fields }, cdpTimeoutMs: 40000 }); - if (disposed) return; - if (result?.error) { - if (result.error === 'unsupported') supported = false; - status = errors.has(result.error) ? result.error : 'storeFailed'; - return; - } - if (action === 'quota') { - savedQuotas.set(result.email, result.pools); - return; - } - supported = result?.supported === true; - accounts = result?.accounts || []; - selectedEmail = result?.selectedEmail || ''; - if (action === 'save' || action === 'capture') status = 'saved'; - if (action === 'remove') { - savedQuotas.delete(fields.email); - status = 'removed'; - } - if (action === 'switch') { - status = result.confirmed ? 'switched' : ''; - void fetchTelemetry({ force: true }).catch(() => {}); - } - } catch { - status = 'storeFailed'; - } finally { - operation = ''; - if (!disposed) render(); - } - } - - function importCredential(event) { - event.preventDefault(); - if (operation) return; - const input = credential.value; - credential.value = ''; - void request('save', { credential: input }); - } - - function renderAccount(value, quotaData) { - if (account === value && quotas === quotaData) return; - account = value; - quotas = quotaData; - render(); - } - - const root = h('div', { className: 'settings-tab-stack' }, [ - h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [title]), - h('div', { className: 'settings-action-block' }, [ - h('div', { className: 'settings-action-info' }, [identityLabel, identity, plan]), - ]), - quotaTitle, quotaRows, quotaMessage, pending, - ]), - h('section', { className: 'panel' }, [ - h('div', { className: 'panel-header' }, [savedTitle]), - h('div', { className: 'settings-account-buttons' }, [capture, reload]), - savedRows, savedMessage, form, feedback, - ]), - ]); - render(); - onCleanup(() => { - disposed = true; - credential.value = ''; - }); - return { el: root, refs: { renderAccount, refreshLabels: render, load: () => request('list') } }; - }, -}); +return { SettingsStructureTab }; +})(); // --- src/views/settings/SettingsOtherTab.js --- +const { SettingsOtherTab } = (() => { /** * @fileoverview Preferences Tab 3: `SettingsOtherTab.js` ("其他"). * Houses Model Identifier Formatting, Per-Model Context Windows, @@ -14736,6 +15995,8 @@ const SettingsOtherTab = defineComponent({ let draftContextRiskAccepted = false; let acceptingContextRisk = false; let latestSettings = null; + let latestWindowBridge = null; + let latestHostPlatform = 'win32'; let contextWindowModels = []; let contextModelId = ''; let savingContextWindow = false; @@ -14885,9 +16146,11 @@ const SettingsOtherTab = defineComponent({ } }, }); + const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true }); const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]); const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]); const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ + ctxBridgeNotice.el, ctxModelRow, ctxWindowRow, h('div', { className: 'form-row' }, [ctxHint]), @@ -14964,6 +16227,13 @@ const SettingsOtherTab = defineComponent({ patchAttr(ctxRiskAcceptBtn, 'disabled', acceptingContextRisk); const saved = latestSettings?.modelContextWindows || {}; + const wbState = String(latestWindowBridge?.state || '').trim(); + const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable'; + ctxBridgeNotice.refs.update({ + visible: unlocked, + windowBridge: latestWindowBridge, + hostPlatform: latestHostPlatform, + }); const models = new Map(contextWindowModels.map((model) => [model.id, model])); const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members])); for (const id of Object.keys(saved)) { @@ -15008,6 +16278,7 @@ const SettingsOtherTab = defineComponent({ else if (value) { const name = formatLimit(value); if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name }); + else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name }); else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) { meta = t('settings.oth.ctxConfiguredReported', { name, @@ -15178,10 +16449,17 @@ const SettingsOtherTab = defineComponent({ maintPanel, ]); - function renderSettings(settings, models = contextWindowModels) { + function renderSettings( + settings, + models = contextWindowModels, + windowBridge = latestWindowBridge, + hostPlatform = latestHostPlatform + ) { if (!settings) return; latestSettings = settings; contextWindowModels = models; + if (windowBridge !== undefined) latestWindowBridge = windowBridge; + if (hostPlatform) latestHostPlatform = hostPlatform; draftModelDisplayMode = normalizeClientModelDisplayMode( settings.modelDisplayMode, settings.showUpstreamModel @@ -15239,6 +16517,7 @@ const SettingsOtherTab = defineComponent({ if (resetConfirmTimer) clearTimeout(resetConfirmTimer); stepModelSelect.destroy(); orchestratorIdSelect.destroy(); + ctxBridgeNotice.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); }); @@ -15248,6 +16527,7 @@ const SettingsOtherTab = defineComponent({ refs: { stepModelSelect, orchestratorIdSelect, + ctxBridgeNotice, ctxModelSelect, ctxWindowSelect, rebuildCacheBtn, @@ -15258,8 +16538,11 @@ const SettingsOtherTab = defineComponent({ }; }, }); +return { SettingsOtherTab }; +})(); // --- src/components/layout/TopSessionHeader.js --- +const { TopSessionHeader } = (() => { /** * @fileoverview Row 1 of the compact top bar: * Bespoke CustomSelect for session switching, SVG live status indicator, @@ -15356,20 +16639,24 @@ const TopSessionHeader = defineComponent({ let lastActiveCascadeId = ''; + function syncSessionScopeOnCascadeChange(telemetry) { + const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; + if (!currentCascadeId) return; + if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { + lastActiveCascadeId = currentCascadeId; + const uiSt = uiStore.getState(); + if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') { + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + } + } else { + lastActiveCascadeId = currentCascadeId; + } + } + function renderHeaderState() { const telSt = telemetryStore.getState(); const uiSt = uiStore.getState(); const telemetry = telSt.telemetry; - const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; - if (currentCascadeId && lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { - lastActiveCascadeId = currentCascadeId; - if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') { - uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - return; - } - } else if (currentCascadeId) { - lastActiveCascadeId = currentCascadeId; - } if (!uiSt.monitorVisible) return; patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); @@ -15490,7 +16777,7 @@ const TopSessionHeader = defineComponent({ } else if (isRunning) { const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning); const runSuffix = - hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : ''; + hasSubagents && runningAgent ? ` · ${formatAgentBadgeText(runningAgent)}` : ''; patchSvgIcon(statusIcon, 'bolt'); patchText(statusText, t('header.statusGenerating', { suffix: runSuffix })); patchClasses(statusTag, { @@ -15527,7 +16814,10 @@ const TopSessionHeader = defineComponent({ syncState: st.syncState, telemetry: st.telemetry, }), - () => renderHeaderState() + (slice) => { + syncSessionScopeOnCascadeChange(slice.telemetry); + renderHeaderState(); + } ); const unsubI18n = i18nStore.subscribe( @@ -15555,8 +16845,11 @@ const TopSessionHeader = defineComponent({ }; }, }); +return { TopSessionHeader }; +})(); // --- src/views/LiveOverviewView.js --- +const { LiveOverviewView } = (() => { /** * @fileoverview View 1: Decoupled `LiveOverviewView.js` (实时监控视图). * Acts as a lightweight host container delegating all telemetry cards @@ -15571,7 +16864,6 @@ const LiveOverviewView = defineComponent({ setup({ onCleanup }) { const overviewInner = h('div', { className: 'overview-modules-host', - style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', }); const widgetHost = createDynamicWidgetHost({ @@ -15713,8 +17005,11 @@ const LiveOverviewView = defineComponent({ }; }, }); +return { LiveOverviewView }; +})(); // --- src/views/ConsumptionView.js --- +const { ConsumptionView } = (() => { /** * @fileoverview View 2: ConsumptionView (全景消耗统计视图). * 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗: @@ -16259,22 +17554,14 @@ const ConsumptionView = defineComponent({ let cachePct = 0; let outPct = 0; if (totalTokens > 0) { - const rawTenths = [ - (inputTokens / totalTokens) * 1000, - (cacheTokens / totalTokens) * 1000, - (outputTokens / totalTokens) * 1000, - ]; - const floored = rawTenths.map((v) => Math.max(0, Math.floor(v))); - const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2])); - const order = [0, 1, 2].sort( - (a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a]) + const scaled = scaleBucketsExact( + { in: inputTokens, cache: cacheTokens, out: outputTokens }, + ['in', 'cache', 'out'], + 1000 ); - for (let k = 0; k < rem && k < 3; k++) { - floored[order[k]] += 1; - } - inPct = +(floored[0] / 10).toFixed(1); - cachePct = +(floored[1] / 10).toFixed(1); - outPct = +(floored[2] / 10).toFixed(1); + inPct = +(scaled.in / 10).toFixed(1); + cachePct = +(scaled.cache / 10).toFixed(1); + outPct = +(scaled.out / 10).toFixed(1); } patchText(inputSharePct, `${inPct}%`); @@ -16510,8 +17797,11 @@ const ConsumptionView = defineComponent({ }; }, }); +return { ConsumptionView }; +})(); // --- src/views/StepsDetailView.js --- +const { StepsDetailView } = (() => { /** * @fileoverview View 3: StepsDetailView (步骤明细与总汇总分析视图). * 提供“按步查看”与“总汇总”双子视图切换: @@ -16910,17 +18200,20 @@ const StepsDetailView = defineComponent({ let isDirty = false; function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { - const activeCand = getStepModelGroupKey({ - modelLabel: scopedConv?.activeModelLabel, - modelShort: scopedConv?.activeModelShort, - }); - if ( - activeCand && - activeCand !== '模型未知' && - activeCand !== t('fmt.unknownModel') && - availableModelKeys.has(activeCand) - ) { - return activeCand; + if (scopedConv?.hasKnownModel !== false) { + const activeCand = getStepModelGroupKey({ + baseModelLabel: scopedConv?.activeBaseModelLabel, + baseModelShort: scopedConv?.activeBaseModelShort, + modelLabel: scopedConv?.activeModelLabel, + modelShort: scopedConv?.activeModelShort, + }); + if ( + activeCand && + activeCand !== t('fmt.unknownModel') && + availableModelKeys.has(activeCand) + ) { + return activeCand; + } } for (let i = chronoSteps.length - 1; i >= 0; i--) { const st = chronoSteps[i]; @@ -17100,7 +18393,7 @@ const StepsDetailView = defineComponent({ if (!stepModelOptionMap.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); stepModelOptionMap.set(gk, { - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, calls: 0, }); } @@ -17131,7 +18424,7 @@ const StepsDetailView = defineComponent({ }); perModelOptions.push({ value: gk, - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } @@ -17639,8 +18932,11 @@ const StepsDetailView = defineComponent({ }; }, }); +return { StepsDetailView }; +})(); // --- src/views/SettingsView.js --- +const { SHOW_ACCOUNT_TAB, SettingsView } = (() => { /** * @fileoverview View 4: Modular preferences ("常规" / "结构" / "账号" / "其他"). * Orchestrates the four preference tabs @@ -17684,7 +18980,7 @@ const SettingsView = defineComponent({ const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll }); const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll }); - const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll }); + const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll }); let showingAccount = false; @@ -17692,25 +18988,27 @@ const SettingsView = defineComponent({ const target = subTab === 'structure' || subTab === 'other' || - (SHOW_ACCOUNT_TAB && subTab === 'account') + (accountTab && subTab === 'account') ? subTab : 'general'; subNavSwitch.setValue(target); patchAttr(generalTab.el, 'hidden', target !== 'general'); patchAttr(structureTab.el, 'hidden', target !== 'structure'); patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure'); - patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account'); patchAttr(otherTab.el, 'hidden', target !== 'other'); - const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings'; - if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); - showingAccount = nextShowingAccount; + if (accountTab) { + patchAttr(accountTab.el, 'hidden', target !== 'account'); + const nextShowingAccount = target === 'account' && activeView === 'settings'; + if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); + showingAccount = nextShowingAccount; + } refreshScroll(); } const contentContainer = h( 'div', {}, - SHOW_ACCOUNT_TAB + accountTab ? [generalTab.el, structureTab.el, accountTab.el, otherTab.el] : [generalTab.el, structureTab.el, otherTab.el] ); @@ -17734,10 +19032,23 @@ const SettingsView = defineComponent({ const telemetry = telemetryStore.getState().telemetry; const settings = telemetry?.settings; if (settingsSubTab === 'structure') { - if (settings) structureTab.refs.renderSettings(settings); + if (settings) { + structureTab.refs.renderSettings( + settings, + telemetry?.windowBridge, + telemetry?.hostPlatform + ); + } } else if (settingsSubTab === 'other') { - if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []); - } else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') { + if (settings) { + otherTab.refs.renderSettings( + settings, + telemetry.contextWindowModels || [], + telemetry?.windowBridge, + telemetry?.hostPlatform + ); + } + } else if (accountTab && settingsSubTab === 'account') { accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas); } else { if (settings) generalTab.refs.renderSettings(settings); @@ -17749,6 +19060,8 @@ const SettingsView = defineComponent({ const unsubTelemetry = telemetryStore.subscribe( (st) => ({ settings: st.telemetry?.settings, + windowBridge: st.telemetry?.windowBridge, + hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, contextWindowModels: st.telemetry?.contextWindowModels, account: st.telemetry?.account, @@ -17777,7 +19090,7 @@ const SettingsView = defineComponent({ }); generalTab.refs.refreshLabels(); structureTab.refs.refreshLabels(); - accountTab.refs.refreshLabels(); + accountTab?.refs.refreshLabels(); otherTab.refs.refreshLabels(); refreshScroll(); } @@ -17790,7 +19103,7 @@ const SettingsView = defineComponent({ subNavSwitch.destroy(); generalTab.destroy(); structureTab.destroy(); - accountTab.destroy(); + accountTab?.destroy(); otherTab.destroy(); viewScrollbar.destroy(); }); @@ -17815,8 +19128,11 @@ const SettingsView = defineComponent({ }; }, }); +return { SHOW_ACCOUNT_TAB, SettingsView }; +})(); // --- src/App.js --- +const { App } = (() => { /** * @fileoverview Root Application Shell (App.js). * Combines the compact dual-layer header (TopSessionHeader + TopLongPillNav) @@ -17841,6 +19157,36 @@ const App = defineComponent({ const stepsView = StepsDetailView(); const settingsView = SettingsView(); + const globalBridgeNotice = BridgeStatusNotice({ + dismissible: true, + }); + const bannerSlotEl = h('div', { className: 'app-bridge-banner-slot', hidden: true }, [ + globalBridgeNotice.el, + ]); + + function syncGlobalBridgeBanner() { + const activeView = uiStore.getState().activeView; + const telemetry = telemetryStore.getState().telemetry; + const settings = telemetry?.settings; + const mountMode = settings + ? normalizeClientWindowMountMode(settings.windowMountMode, settings.enableWindowOverlay) + : 'sidebar'; + const hasCtxOverrides = Boolean( + settings?.modelContextWindows && Object.keys(settings.modelContextWindows).length > 0 + ); + const shouldOfferGlobal = + !isWindowOverlayMode() && + activeView !== 'settings' && + (mountMode !== 'sidebar' || hasCtxOverrides); + globalBridgeNotice.refs.update({ + visible: shouldOfferGlobal, + contextMode: mountMode === 'sidebar' && hasCtxOverrides, + windowBridge: telemetry?.windowBridge || null, + hostPlatform: telemetry?.hostPlatform || 'win32', + }); + patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); + } + const viewMap = { overview: overviewView.el, consumption: consumptionView.el, @@ -17857,6 +19203,7 @@ const App = defineComponent({ const shellEl = h('main', { className: 'app-shell' }, [ h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]), + bannerSlotEl, stageEl, ]); @@ -17896,6 +19243,7 @@ const App = defineComponent({ settingsView.refs?.viewScrollbar?.refresh(); } syncStepsBadge(); + syncGlobalBridgeBanner(); } ); @@ -17904,8 +19252,16 @@ const App = defineComponent({ stepCount: st.telemetry?.activeConversation?.stepCount ?? 0, totalStepsAllAgents: st.telemetry?.activeConversation?.totalStepsAllAgents ?? 0, subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0, + windowMountMode: st.telemetry?.settings?.windowMountMode, + enableWindowOverlay: st.telemetry?.settings?.enableWindowOverlay, + modelContextWindows: st.telemetry?.settings?.modelContextWindows, + windowBridge: st.telemetry?.windowBridge, + hostPlatform: st.telemetry?.hostPlatform, }), - () => syncStepsBadge() + () => { + syncStepsBadge(); + syncGlobalBridgeBanner(); + } ); const unsubScopeBadge = uiStore.subscribe( @@ -17915,7 +19271,11 @@ const App = defineComponent({ const unsubI18n = i18nStore.subscribe( (st) => st.locale, - () => syncStepsBadge() + () => { + syncStepsBadge(); + globalBridgeNotice.refs.refreshLabels(); + patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); + } ); onCleanup(() => { @@ -17923,6 +19283,7 @@ const App = defineComponent({ unsubStepCount(); unsubScopeBadge(); unsubI18n(); + globalBridgeNotice.destroy(); sessionHeader.destroy(); topPillNav.destroy(); overviewView.destroy(); @@ -17936,6 +19297,7 @@ const App = defineComponent({ refs: { sessionHeader, topPillNav, + globalBridgeNotice, overviewView, consumptionView, stepsView, @@ -17944,8 +19306,11 @@ const App = defineComponent({ }; }, }); +return { App }; +})(); // --- src/components/layout/WindowOverlayShell.js --- +const { computeCapsuleLayoutMode, mountWindowOverlay } = (() => { /** * @fileoverview 主窗口双栖挂载外壳 (WindowOverlayShell.js). * @@ -18722,7 +20087,7 @@ function isImmediatelyBeforeNode(node, refNode) { function isIdeExtensionChatFrame() { try { if (typeof window === 'undefined') return false; - if (window.__AGUsageMonitorBridge?.isIdeChatFrame === true) return true; + if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true; return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || '')); } catch { return false; @@ -18733,7 +20098,7 @@ function resolveActiveDockTarget(options = undefined) { const settings = telemetryStore.getState().telemetry?.settings; const rawMode = settings?.windowMountMode ?? - (typeof window !== 'undefined' ? window.__AGUsageMonitorBridge?.mountMode : undefined); + readInjectedWindowBridge()?.mountMode; const mountMode = options?.mountMode || normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay); @@ -18834,14 +20199,14 @@ function mountWindowOverlay() { let carryOverMultiPinnedOpen = false; let carryOverPointer = null; try { - const prevOv = window.__AGUsageMonitorOverlay; + const prevOv = window[WINDOW_OVERLAY_KEY]; carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null; carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.()); carryOverPopoverOpen = Boolean(prevOv?.isOpen?.()); carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.()); carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.()); carryOverPointer = prevOv?.getLastPointer?.() || null; - prevOv?.dispose?.(); + prevOv?.[WINDOW_OVERLAY_METHODS.dispose]?.(); } catch { // 忽略旧实例卸载异常 } @@ -18880,9 +20245,6 @@ function mountWindowOverlay() { let multiPinned = false; let hoverLeaveTimer = null; let multiLeaveTimer = null; - const manualSubExpandMap = new Map(); - const multiTimersMap = new Map(); - let multiLiveTickTimer = null; let hasPointerCoords = Boolean( carryOverPointer && Number.isFinite(carryOverPointer.x) && @@ -18980,52 +20342,6 @@ function mountWindowOverlay() { }, 90); } - function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) { - const now = Date.now(); - const prev = multiTimersMap.get(timerKey); - let startMs = prev?.startMs || 0; - if (!prev || prev.sig !== sig) { - const validRaw = Number(rawStartMs || 0); - startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; - } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { - startMs = Number(rawStartMs); - } - multiTimersMap.set(timerKey, { sig, startMs, el: targetEl }); - const elapsedSec = Math.max(0, (now - startMs) / 1000); - patchText(targetEl, formatElapsedSec(elapsedSec)); - } - - function tickMultiElapsedDisplay() { - const now = Date.now(); - for (const entry of multiTimersMap.values()) { - if (!entry?.el) continue; - const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; - patchText(entry.el, formatElapsedSec(elapsedSec)); - } - } - - function pauseMultiLiveTicker() { - if (multiLiveTickTimer) { - clearInterval(multiLiveTickTimer); - multiLiveTickTimer = null; - } - } - - function stopMultiLiveTicker() { - pauseMultiLiveTicker(); - multiTimersMap.clear(); - } - - function ensureMultiLiveTicker() { - if (multiTimersMap.size === 0) { - stopMultiLiveTicker(); - return; - } - if (!multiLiveTickTimer) { - multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000); - } - } - function inspectSessionInMonitor(cascadeId) { if (!cascadeId || cascadeId === 'current') return; uiStore.setState({ @@ -19283,8 +20599,6 @@ function mountWindowOverlay() { portalShadow.appendChild(portalStyleEl); const initialSettings = telemetryStore.getState().telemetry?.settings; - applyAppearanceToRoot(capsuleHost, initialSettings, { includeFontScale: false }); - applyAppearanceToRoot(portalHost, initialSettings, { includeFontScale: true }); // 悬停全景概览浮层(完全解耦至 widgetRegistry,由 hoverModules 动态驱动 0..4 个独立组件,零硬编码) const hoverUpdateVerText = h('span', { text: t('capsule.hoverNewVerGeneric') }); @@ -19324,105 +20638,7 @@ function mountWindowOverlay() { [hoverUpdateBar, hoverWidgetsContainer] ); - // 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) - function createMultiLiveSubRow() { - const subBadge = h('span', { - className: 'agent-badge badge-sub-1', - text: t('fmt.subBadge', { index: 1 }), - }); - const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') }); - const subSummary = h('span', { className: 'live-sub-summary', text: '' }); - const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); - const rowEl = h('div', { className: 'live-sub-row' }, [ - h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), - subElapsed, - ]); - return { - el: rowEl, - refs: { rowEl, subBadge, subRole, subSummary, subElapsed }, - }; - } - - function createMultiLiveTaskCard() { - const dotIcon = createSvgIcon('dot', { size: 11 }); - patchClasses(dotIcon, { 'is-pulsing': true }); - const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); - const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession') }); - const hereTagEl = h('span', { - className: 'wm-session-tag is-here', - hidden: true, - text: t('multi.hereTag'), - }); - const metricsEl = h('span', { - className: 'wm-task-metrics text-mono', - hidden: true, - text: '', - }); - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), - }); - const elapsedEl = h('span', { - className: 'live-activity-elapsed text-mono', - text: '0s', - }); - - const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]), - h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]), - ]); - - const mainBadge = h('span', { - className: 'agent-badge badge-main', - hidden: true, - text: t('fmt.mainBadge'), - }); - const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking') }); - const mainProgress = h('span', { - className: 'live-activity-progress text-mono', - hidden: true, - text: '', - }); - const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); - const mainDetail = h('span', { - className: 'live-activity-detail', - hidden: true, - text: '', - }); - - const mainRowEl = h('div', { className: 'live-task-main-row' }, [ - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - ]); - - const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); - - return { - el: cardEl, - refs: { - cardEl, - dotIcon, - titleEl, - hereTagEl, - metricsEl, - subToggleBtn, - elapsedEl, - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - subListEl, - }, - }; - } - + // 左侧多会话实时看板浮层(受控复用 LiveActivityWidget,保持零硬编码与同一套计时器状态机) const multiPinBadge = h('span', { className: 'wm-pin-badge', hidden: true, @@ -19439,10 +20655,16 @@ function mountWindowOverlay() { multiEmptyTextEl, ]), ]); - const multiRunningListEl = h('div', { - className: 'live-activity-list', - hidden: true, - 'aria-live': 'polite', + const multiRunningWidget = LiveActivityWidget({ + defaultExpandRunningSubs: true, + showSessionExtras: true, + isVisibleFn: () => Boolean(multiOpen && !document.hidden && !disposed), + onSelectSession: inspectSessionInMonitor, + onLayoutChange: () => { + if (multiOpen) { + positionFloatingElements(); + } + }, }); const multiTitleTextEl = h('span', { text: t('multi.title') }); @@ -19476,7 +20698,7 @@ function mountWindowOverlay() { } }, }, - [multiHeaderEl, multiEmptyEl, multiRunningListEl] + [multiHeaderEl, multiEmptyEl, multiRunningWidget.el] ); // 完整四标签悬浮容器 @@ -19493,9 +20715,19 @@ function mountWindowOverlay() { [appInstance.el] ); + function syncPortalAppearance(settings) { + applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); + applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); + const scaleKey = normalizeClientFontScale(settings?.fontScale); + popoverEl.setAttribute?.('data-font-scale', scaleKey); + hoverTipEl.setAttribute?.('data-font-scale', scaleKey); + multiPanelEl.setAttribute?.('data-font-scale', scaleKey); + } + portalShadow.appendChild(multiPanelEl); portalShadow.appendChild(hoverTipEl); portalShadow.appendChild(popoverEl); + syncPortalAppearance(initialSettings); (document.body || document.documentElement).appendChild(portalHost); // --- 3. 几何测量、IDE 主题桥接、顶栏停靠与防溢出定位 --- @@ -19668,6 +20900,8 @@ function mountWindowOverlay() { return true; } + const isMac = () => isMacHostPlatform(telemetryStore.getState().telemetry); + function updateFixedFallbackPosition() { const dockMode = capsuleHost.getAttribute('data-dock'); if (dockMode === 'flow' || dockMode === 'ide-titlebar' || dockMode === 'composer') { @@ -19677,12 +20911,13 @@ function mountWindowOverlay() { } try { const vw = Number(window.innerWidth || 1280); - let rightOffset = 144; + const minRight = isMac() ? 12 : 144; + let rightOffset = minRight; const anchor = findNativeTopRightAnchor(); if (anchor?.getBoundingClientRect) { const r = anchor.getBoundingClientRect(); if (r.width > 0 && r.left > 0 && r.left < vw) { - rightOffset = Math.max(144, Math.ceil(vw - r.left + 6)); + rightOffset = Math.max(minRight, Math.ceil(vw - r.left + 6)); } } capsuleHost.style.top = '7px'; @@ -19692,6 +20927,16 @@ function mountWindowOverlay() { } } + function syncCapsuleOsAttr() { + const nextOs = isMac() ? 'mac' : 'default'; + if (capsuleHost.getAttribute('data-os') !== nextOs) { + patchAttr(capsuleHost, 'data-os', nextOs); + if (capsuleHost.getAttribute('data-dock') === 'fixed') { + updateFixedFallbackPosition(); + } + } + } + function measureAvailableTitlebarWidth(dockTarget) { try { const titlebar = dockTarget?.titlebar || null; @@ -19761,10 +21006,19 @@ function mountWindowOverlay() { } } } - if (!hasVisibleWindowControls && navigator?.windowControlsOverlay?.visible) { + if (navigator?.windowControlsOverlay?.visible) { const wcoRect = navigator.windowControlsOverlay.getTitlebarAreaRect?.(); - if (wcoRect && wcoRect.width > 0 && tbRect.right > wcoRect.right + 4) { - rightSiblingsWidth += tbRect.right - wcoRect.right; + if (wcoRect && wcoRect.width > 0) { + if (!hasVisibleWindowControls && tbRect.right > wcoRect.right + 4) { + rightSiblingsWidth += tbRect.right - wcoRect.right; + } + const leftOverlayInset = wcoRect.left - tbRect.left; + if (leftOverlayInset > leftContentWidth) { + leftContentWidth = Math.min( + Math.round(tbRect.width * 0.45), + Math.ceil(leftOverlayInset) + ); + } } } @@ -19777,10 +21031,11 @@ function mountWindowOverlay() { if (tbRect.width > 0) { const titleEl = titlebar.firstElementChild; const titleInner = titleEl?.firstElementChild; + const macTrafficReserve = isMac() ? 80 : 168; const contentStart = titleInner?.getBoundingClientRect ? Math.max(8, titleInner.getBoundingClientRect().left - tbRect.left) - : tbRect.left < 168 - ? 168 - tbRect.left + : tbRect.left < macTrafficReserve + ? macTrafficReserve - tbRect.left : 12; const minTitleWidth = 180; let siblingButtonsWidth = 64; @@ -19834,8 +21089,17 @@ function mountWindowOverlay() { const vh = Number(window.innerHeight || 800); const navRight = getLeftSidebarRightEdge(vw); const minLeft = navRight > 0 ? Math.max(12, navRight + 12) : 12; - const defaultCardW = Math.min(FLOATING_CARD_WIDTH, Math.max(280, vw - 24)); - const defaultMultiW = Math.min(MULTI_PANEL_WIDTH, Math.max(280, vw - 24)); + const curSettings = telemetryStore.getState().telemetry?.settings; + const panelScale = + PANEL_SCALE_FACTORS[normalizeClientFontScale(curSettings?.fontScale)] ?? 1; + const defaultCardW = Math.min( + Math.round(FLOATING_CARD_WIDTH * panelScale), + Math.max(280, vw - 24) + ); + const defaultMultiW = Math.min( + Math.round(MULTI_PANEL_WIDTH * panelScale), + Math.max(280, vw - 24) + ); const isDockComposer = capsuleHost.getAttribute('data-dock') === 'composer'; if (multiOpen) { @@ -19883,9 +21147,8 @@ function mountWindowOverlay() { 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); + let desiredPopW = Math.min(Math.round(POPOVER_BASE_WIDTH * panelScale), maxPopCardW); if (popWidthMode === 'custom') { desiredPopW = Math.min( normalizeClientPopoverWidth(curSettings?.popoverWidth), @@ -20050,6 +21313,7 @@ function mountWindowOverlay() { if (bodyOrDoc && !portalHost.isConnected) { bodyOrDoc.appendChild(portalHost); } + syncCapsuleOsAttr(); ensureWorkbenchThemeObserved(); const dockTarget = resolveRuntimeDockTarget(); @@ -20218,12 +21482,13 @@ function mountWindowOverlay() { patchAttr(multiPanelEl, 'hidden', !multiOpen); if (multiOpen) { renderCapsuleTelemetry(); + multiRunningWidget.refs.resumeTicker(); positionFloatingElements(); if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => positionFloatingElements()); } } else { - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); } } @@ -20298,18 +21563,10 @@ function mountWindowOverlay() { } function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { - if (manualSubExpandMap.size > 0) { - const runningIds = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of manualSubExpandMap.keys()) { - if (!runningIds.has(id)) manualSubExpandMap.delete(id); - } + if (!multiOpen || document.hidden) { + multiRunningWidget.refs.pauseTicker(); + return; } - if (!multiOpen || document.hidden) return; - const localeKey = getEffectiveLocale(); - const hostRouteLower = String( - hostRouteConversationId || extractHostRouteCascadeId() || '' - ).toLowerCase(); - patchText( multiRunningMetaEl, runningCount > 0 @@ -20319,201 +21576,10 @@ function mountWindowOverlay() { : t('multi.allIdle') ); patchAttr(multiEmptyEl, 'hidden', runningCount > 0); - patchAttr(multiRunningListEl, 'hidden', runningCount === 0); - - if (runningCount === 0) { - stopMultiLiveTicker(); - patchKeyedList(multiRunningListEl, [], {}); - } else { - const activeTimerKeys = new Set(); - for (const item of rawRunningList) { - activeTimerKeys.add(`main:${item.cascadeId}`); - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - if (subCount > 0 && isExp) { - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); - } - } - } - } - - patchKeyedList(multiRunningListEl, rawRunningList, { - keyFn: (item) => item.cascadeId, - sigFn: (item) => { - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - const subSig = (item.subagents || []) - .map( - (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` - ) - .join('|'); - return `${localeKey}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; - }, - createRow: createMultiLiveTaskCard, - updateRow: (refs, item) => { - const act = item.mainActivity || { - phase: 'thinking', - label: t('live.thinking'), - detail: '', - stepProgress: '', - startedAtMs: item.lastModifiedMs || 0, - signature: `fallback:${item.lastModifiedMs || 0}`, - }; - const isWaiting = act.phase === 'waiting'; - const isCompacting = act.phase === 'compacting'; - patchClasses(refs.cardEl, { - 'is-waiting': isWaiting, - 'is-compacting': isCompacting, - }); - patchClasses(refs.dotIcon, { 'is-pulsing': true }); - - const convTitle = - item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); - patchText(refs.titleEl, convTitle); - patchAttr(refs.titleEl, 'title', t('multi.inspectSessionTitle', { title: convTitle })); - refs.titleEl.onclick = (e) => { - e.stopPropagation(); - inspectSessionInMonitor(item.cascadeId); - }; - - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - patchText(refs.hereTagEl, t('multi.hereTag')); - patchAttr(refs.hereTagEl, 'hidden', !isHere); - - const metricParts = []; - if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { - metricParts.push( - `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` - ); - } - if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { - metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); - } - const metricsStr = metricParts.join(' · '); - patchAttr(refs.metricsEl, 'hidden', !metricsStr); - if (metricsStr) { - patchText(refs.metricsEl, metricsStr); - } - - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubCount > 0; - patchText(refs.mainBadge, t('fmt.mainBadge')); - patchAttr(refs.mainBadge, 'hidden', subCount === 0); - patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); - if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; - const toggleText = - runSubCount > 0 - ? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow }) - : t('live.subToggleIdle', { total: subCount, arrow }); - patchText(refs.subToggleBtn, toggleText); - patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); - refs.subToggleBtn.onclick = (e) => { - e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - renderCapsuleTelemetry(); - if (multiOpen) { - positionFloatingElements(); - } - }; - } - - const mainTimerKey = `main:${item.cascadeId}`; - activeTimerKeys.add(mainTimerKey); - bindMultiElapsedTimer( - mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, - act.startedAtMs, - refs.elapsedEl - ); - - patchText(refs.mainPhase, act.label || t('live.thinking')); - const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; - patchAttr(refs.mainProgress, 'hidden', !progText); - if (progText) { - patchText(refs.mainProgress, progText); - } - - const detailStr = act.detail || ''; - patchAttr(refs.mainSep, 'hidden', !detailStr); - patchAttr(refs.mainDetail, 'hidden', !detailStr); - patchText(refs.mainDetail, detailStr); - - const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); - if (showSubs) { - const subItems = item.subagents || []; - patchKeyedList(refs.subListEl, subItems, { - keyFn: (sub) => sub.cascadeId, - sigFn: (sub) => - `${localeKey}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`, - createRow: createMultiLiveSubRow, - updateRow: (subRefs, sub) => { - const subAct = sub.liveActivity || { - phase: sub.isRunning ? 'thinking' : 'done', - label: sub.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: sub.lastModifiedMs || 0, - }; - patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); - const subBadgeCls = getAgentBadgeClass(sub.index || 1, false); - patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`); - patchText(subRefs.subBadge, formatAgentBadgeText(sub)); - patchText(subRefs.subRole, sub.role || sub.shortLabel || t('fmt.subAgent')); - - const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryText = sub.isRunning - ? `${subAct.label || t('live.running')}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}` - : t('live.doneWithSteps', { steps: sub.stepCount || 0 }); - patchText(subRefs.subSummary, summaryText); - - const subTimerKey = `sub:${sub.cascadeId}`; - if (sub.isRunning) { - activeTimerKeys.add(subTimerKey); - bindMultiElapsedTimer( - subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs || sub.lastModifiedMs, - subRefs.subElapsed - ); - } else { - multiTimersMap.delete(subTimerKey); - patchText( - subRefs.subElapsed, - t('header.convMetaSteps', { count: sub.stepCount || 0 }) - ); - } - }, - }); - } - }, - }); - - for (const k of [...multiTimersMap.keys()]) { - if (!activeTimerKeys.has(k)) { - multiTimersMap.delete(k); - } - } - ensureMultiLiveTicker(); - tickMultiElapsedDisplay(); - } + multiRunningWidget.refs.update({ + items: rawRunningList, + hostRouteConversationId, + }); } function renderHoverWidgets() { @@ -20533,8 +21599,8 @@ function mountWindowOverlay() { const telemetry = telSt.telemetry; setI18nLanguage(telemetry?.settings?.language); - applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false }); - applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true }); + syncPortalAppearance(telemetry?.settings); + syncCapsuleOsAttr(); const showMulti = telemetry?.settings?.showTopbarMultiSession !== false; patchAttr(multiBtn, 'hidden', !showMulti); @@ -20556,7 +21622,7 @@ function mountWindowOverlay() { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); patchText(multiLabel, t('capsule.multiZero')); patchText(multiRunningMetaEl, t('multi.loading')); - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); applyCapsuleSlots(slotKeys, { hasTelemetry: false }); return; @@ -20569,138 +21635,36 @@ function mountWindowOverlay() { uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId ); - const activeConv = telemetry.activeConversation || {}; - const overviewActive = overviewScopedConv || activeConv; - const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - // --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- - const rawRunningList = - Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 - ? telemetry.runningConversations - : activeConv.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: activeConv.cascadeId || 'current', - title: activeConv.title || t('live.currentSession'), - isCurrentSelected: true, - isMainRunning: Boolean(activeConv.isRunning), - isRunning: true, - mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, (agents?.length || 1) - 1), - runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, - latestTokPerSec: overviewActive.latestTokPerSec ?? null, - contextUsedPct: usedPct, - subagents: (agents || []) - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; - - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const overviewActive = overviewScopedConv || telemetry.activeConversation || {}; + const slotCtx = buildCapsuleSlotContext(telemetry, { + scopedConv: capsuleScopedConv, + overviewConv: overviewActive, + ctxAgent, + aggregated, + }); + const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } = + resolveMultiSessionCapsuleState(telemetry, { + agents, + aggregated, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId); + renderMultiRunningPanel( + rawRunningList, + runningCount, + runningSubCount, + telSt.hostRouteConversationId + ); - // --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 --- - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capActive = capsuleScopedConv || aggregated || activeConv || {}; - const tps = - capsuleScopedConv?.latestTokPerSec ?? - aggregated?.latestTokPerSec ?? - activeConv.latestTokPerSec ?? - null; - const avgTps = - capsuleScopedConv?.avgTokPerSec ?? - aggregated?.avgTokPerSec ?? - activeConv.avgTokPerSec ?? - null; - const ttft = - capsuleScopedConv?.latestTtftSec ?? - aggregated?.latestTtftSec ?? - activeConv.latestTtftSec ?? - null; - const capsuleStepCost = - capsuleScopedConv?.latestStepCostUsd ?? - aggregated?.latestStepCostUsd ?? - activeConv.latestStepCostUsd ?? - null; - const sessionCost = - capsuleScopedConv?.sessionCostUsd ?? - aggregated?.sessionCostUsd ?? - activeConv.sessionCostUsd ?? - null; - const cacheHitPct = - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null; - const latestPromptTokens = capActive.latestPromptTokens ?? null; - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - applyCapsuleSlots(slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps, - avgTps, - ttft, - stepCost: capsuleStepCost, - sessionCost, - cacheHitPct, - latestPromptTokens, - sessionTokens, - quotas: telemetry.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + applyCapsuleSlots(slotKeys, slotCtx); const updateMode = normalizeClientUpdateMode( telemetry.settings?.pluginUpdateMode, @@ -20877,7 +21841,7 @@ function mountWindowOverlay() { const onVisibilityChange = () => { if (document.hidden) { uiStore.setState({ monitorVisible: false }); - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); hasPointerCoords = false; if (tooltipOpen) { setTooltipOpen(false); @@ -20979,28 +21943,28 @@ function mountWindowOverlay() { const handle = { bundleVersion, - ensureAlive() { + [WINDOW_OVERLAY_METHODS.ensureAlive]() { if (disposed) return false; return ensureCapsuleDocked(); }, - syncHostRoute() { + [WINDOW_OVERLAY_METHODS.syncHostRoute]() { if (disposed) return false; syncHostRouteIfChanged(); return true; }, - updateBridge(nextBridge) { + [WINDOW_OVERLAY_METHODS.updateBridge](nextBridge) { if (disposed || !nextBridge || typeof nextBridge !== 'object') return false; const port = Number(nextBridge.port || 0); const token = String(nextBridge.token || ''); if (!Number.isInteger(port) || port <= 0 || !token) return false; - const cur = window.__AGUsageMonitorBridge || {}; + const cur = readInjectedWindowBridge() || {}; const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token; cur.port = port; cur.token = token; if (portChanged) { cur.transportMode = 'http'; } - window.__AGUsageMonitorBridge = cur; + window[WINDOW_BRIDGE_KEY] = cur; void fetchTelemetry({ force: false }); return true; }, @@ -21010,7 +21974,7 @@ function mountWindowOverlay() { getLastPointer() { return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null; }, - deliverRpc(responses) { + [WINDOW_OVERLAY_METHODS.deliverRpc](responses) { if (disposed) return 0; return deliverCdpBridgeResponses(responses); }, @@ -21035,14 +21999,13 @@ function mountWindowOverlay() { isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned), isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned), getLayoutMode: () => layoutMode, - getDockKind: () => String(capsuleHost.getAttribute('data-dock') || ''), - getMountMode: () => lastAppliedMountMode, - applyMountMode(nextMode) { + [WINDOW_OVERLAY_METHODS.getDockKind]: () => String(capsuleHost.getAttribute('data-dock') || ''), + [WINDOW_OVERLAY_METHODS.getMountMode]: () => lastAppliedMountMode, + [WINDOW_OVERLAY_METHODS.applyMountMode](nextMode) { if (disposed) return false; const normalized = normalizeClientWindowMountMode(nextMode, nextMode !== 'sidebar'); - if (typeof window !== 'undefined' && window.__AGUsageMonitorBridge) { - window.__AGUsageMonitorBridge.mountMode = normalized; - } + const bridgeConfig = readInjectedWindowBridge(); + if (bridgeConfig) bridgeConfig.mountMode = normalized; const curTel = telemetryStore.getState().telemetry; if (curTel?.settings) { telemetryStore.setState({ @@ -21059,7 +22022,7 @@ function mountWindowOverlay() { lastAppliedMountMode = normalized; return ensureCapsuleDocked(); }, - dispose() { + [WINDOW_OVERLAY_METHODS.dispose]() { if (disposed) return; disposed = true; clearInterval(watchdogTimer); @@ -21071,7 +22034,7 @@ function mountWindowOverlay() { clearTimeout(multiLeaveTimer); multiLeaveTimer = null; } - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); if (dockRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(dockRafId); dockRafId = 0; @@ -21112,17 +22075,20 @@ function mountWindowOverlay() { try { portalHost.remove(); } catch {} - if (window.__AGUsageMonitorOverlay === handle) { - delete window.__AGUsageMonitorOverlay; + if (window[WINDOW_OVERLAY_KEY] === handle) { + delete window[WINDOW_OVERLAY_KEY]; } }, }; - window.__AGUsageMonitorOverlay = handle; + window[WINDOW_OVERLAY_KEY] = handle; return handle; } +return { computeCapsuleLayoutMode, mountWindowOverlay }; +})(); // --- src/main.js --- +(() => { /** * @fileoverview Async entry point for Antigravity Usage & Speed Monitor. * Automatically branches between Auxiliary Sidebar Webview mode (`#app-root`) @@ -21135,14 +22101,17 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { const appInstance = App(); mountTarget.appendChild(appInstance.el); + const syncDocAppearance = (settings) => { + setI18nLanguage(settings?.language); + if (typeof document !== 'undefined' && document.documentElement) { + applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true }); + } + }; + syncDocAppearance(telemetryStore.getState().telemetry?.settings); + const unsubAppearance = telemetryStore.subscribe( (st) => st.telemetry?.settings, - (settings) => { - setI18nLanguage(settings?.language); - if (typeof document !== 'undefined' && document.documentElement) { - applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true }); - } - } + syncDocAppearance ); const stopPolling = startAsyncTelemetryLoop(2000); @@ -21184,3 +22153,4 @@ function init() { init(); })(); +})(); diff --git a/sidecars/panel/backend/api-actions.mjs b/sidecars/panel/backend/api-actions.mjs index 7866ec9..21150e6 100644 --- a/sidecars/panel/backend/api-actions.mjs +++ b/sidecars/panel/backend/api-actions.mjs @@ -6,13 +6,13 @@ * 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。 */ -import { readFileSync, promises as fsPromises } from 'node:fs'; -import { join } from 'node:path'; import { randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; +import { BRIDGE_API_ROUTE_DEFS } from '../shared/window-bridge-protocol.mjs'; import { handleAccountCredentialAction } from './account-switch.mjs'; +import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs'; +import { clearScannerRuntimeMemos } from './local-scanner.mjs'; import { - HERE, SETTINGS_FILE, clearRuntimeCaches, cloudSyncState, @@ -45,8 +45,14 @@ import { import { getCloudStatus } from './pricing-catalog.mjs'; import { buildTelemetryPayload } from './telemetry-builder.mjs'; import { + ensureDesktopLaunchEntriesConfigured, + triggerDesktopHostRelaunch, +} from './desktop-launcher-config.mjs'; +import { + ensureIdeRemoteDebuggingArgv, notifyModelContextWindowsChanged, notifyWindowOverlaySetting, + resolveDevToolsPortCandidates, startDefaultWindowBridge, } from './window-bridge.mjs'; import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs'; @@ -59,60 +65,7 @@ export function setStandalonePortListener(listener) { standalonePortListener = typeof listener === 'function' ? listener : null; } -/** - * 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。 - * - * @param {string} relPath 相对路径 - * @returns {Promise} - */ -export const readLocalAsync = async (relPath) => { - const fullPath = join(HERE, relPath); - if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) { - return fsPromises.readFile(fullPath, 'utf8'); - } - return readFileSync(fullPath, 'utf8'); -}; - -/** - * 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin, - * 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。 - * - * @param {object} req - * @returns {boolean} - */ -export function isLocalHostRequest(req) { - if (!req?.headers) return true; - const host = String(req.headers.host || '').trim().toLowerCase(); - const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/); - if (host && !hostMatch) { - return false; - } - const origin = String(req.headers.origin || '').trim().toLowerCase(); - if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) { - return true; - } - const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase(); - if (secFetchSite === 'cross-site') { - return false; - } - if (origin) { - const originMatch = origin.match( - /^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/ - ); - if (!originMatch) { - return false; - } - if (hostMatch) { - const defaultPort = originMatch[1] === 'https' ? '443' : '80'; - const originPort = originMatch[3] || defaultPort; - const hostPort = hostMatch[2] || defaultPort; - if (originPort !== hostPort) { - return false; - } - } - } - return true; -} +export { isLocalHostRequest, readLocalAsync }; const MAX_SAFE_DATE_MS = 8_640_000_000_000_000; @@ -142,7 +95,8 @@ function projectDisplayStep(st) { }; } -let lastDisplaySteps = null; +const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8; +const displayStepsCache = new Map(); const displayStepFields = Object.keys(projectDisplayStep({})); function haveSameDisplaySteps(previous, current) { @@ -165,23 +119,34 @@ function projectDisplayTelemetry(payload, requestedRevision) { let projected; let revision; if (typeof requestedRevision === 'string') { + const cacheKey = active.cascadeId || '__empty__'; const scope = [ payload.account?.status, payload.account?.email || payload.account?.name || '', active.cascadeId, ...agents.map((agent) => agent.agentId), ]; - const previous = lastDisplaySteps; + const previous = displayStepsCache.get(cacheKey); if (previous && isDeepStrictEqual(scope, previous.scope) && sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) || haveSameDisplaySteps(previous.steps[index], steps))) { ({ revision, steps: projected } = previous); previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined); + displayStepsCache.delete(cacheKey); + displayStepsCache.set(cacheKey, previous); } else { revision = randomUUID(); projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep)); - lastDisplaySteps = { scope, steps: projected, revision, - sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) }; + if (!displayStepsCache.has(cacheKey) && displayStepsCache.size >= MAX_DISPLAY_STEP_CACHE_ENTRIES) { + displayStepsCache.delete(displayStepsCache.keys().next().value); + } + displayStepsCache.delete(cacheKey); + displayStepsCache.set(cacheKey, { + scope, + steps: projected, + revision, + sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined), + }); } } projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep)); @@ -452,6 +417,8 @@ export function executeRebuildCacheAction() { body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }), }; } + displayStepsCache.clear(); + clearScannerRuntimeMemos(); return { ok: true, status: 200, @@ -491,41 +458,59 @@ export async function executeAccountCredentialAction(data) { }; } -export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) { - if (pathname === '/api/telemetry' && method === 'GET') { - return executeTelemetryAction(data, opts); - } - if (pathname === '/api/settings' && method === 'POST') { - return executeSettingsAction(data); - } - if (pathname === '/api/accounts' && method === 'GET') { - return executeAccountCredentialAction(); - } - if (pathname === '/api/accounts/update' && method === 'POST') { - return executeAccountCredentialAction(data); - } - if (pathname === '/api/context-window' && method === 'POST') { - return executeModelContextWindowAction(data); - } - if (pathname === '/api/settings/reset' && method === 'POST') { - return executeResetSettingsAction(); - } - if (pathname === '/api/cache/rebuild' && method === 'POST') { - return executeRebuildCacheAction(); - } - if (pathname === '/api/cloud-sync' && method === 'POST') { - return executeCloudSyncAction(); - } - if (pathname === '/api/plugin-update' && method === 'POST') { - return executePluginUpdateAction(); - } +export async function executeBridgeRelaunchAction() { + ensureIdeRemoteDebuggingArgv({ enabled: true }); + await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch(() => {}); + const result = await triggerDesktopHostRelaunch({ + stalePortFiles: resolveDevToolsPortCandidates(), + }); return { - status: 404, + status: result.ok ? 200 : Number(result.status || 500), contentType: 'application/json', - body: JSON.stringify({ error: 'Not found' }), + headers: { 'Cache-Control': 'no-store' }, + body: JSON.stringify(result), }; } +const BRIDGE_ROUTE_LOOKUP = new Map( + BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action]) +); + +export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) { + const action = BRIDGE_ROUTE_LOOKUP.get(`${String(method || '').toUpperCase()}:${pathname}`); + switch (action) { + case 'telemetry': + return executeTelemetryAction(data, opts); + case 'settings': + if (isPlainObject(data) && data.__bridgeAction === 'relaunch') { + return executeBridgeRelaunchAction(); + } + return executeSettingsAction(data); + case 'accounts_get': + return executeAccountCredentialAction(); + case 'accounts_update': + return executeAccountCredentialAction(data); + case 'context_window': + return executeModelContextWindowAction(data); + case 'settings_reset': + return executeResetSettingsAction(); + case 'cache_rebuild': + return executeRebuildCacheAction(); + case 'cloud_sync': + return executeCloudSyncAction(); + case 'plugin_update': + return executePluginUpdateAction(); + case 'bridge_relaunch': + return executeBridgeRelaunchAction(); + default: + return { + status: 404, + contentType: 'application/json', + body: JSON.stringify({ error: 'Not found' }), + }; + } +} + /** * 启动进程级双栖窗口桥接器(兼容 Sidecar 环境与独立后台守护进程环境)。 * diff --git a/sidecars/panel/backend/cli-sqlite-reader.mjs b/sidecars/panel/backend/cli-sqlite-reader.mjs index d4f6706..4fe2a74 100644 --- a/sidecars/panel/backend/cli-sqlite-reader.mjs +++ b/sidecars/panel/backend/cli-sqlite-reader.mjs @@ -1,117 +1,47 @@ /** - * @fileoverview 本地 Antigravity CLI / Desktop SQLite 会话轨迹与 Protobuf 文本标题解析器。 + * @fileoverview 本地 Antigravity (Desktop / IDE / CLI) SQLite + WAL 会话摘要、轨迹直读与标题解析器。 * - * 解决 `agy` CLI(进程内嵌随机端口 Language Server、无 `daemon/hub_*.json`、桌面 LS 无法跨目录读取 - * `~/.gemini/antigravity-cli`)下的完整遥测还原: + * 核心能力: * 1. 解析 `/annotations/.pbtxt` 中的真实会话标题(兼容 UTF-8 直出与八进制/十六进制字节转义); - * 2. 通过 Node 22.5+ 内置 `node:sqlite` 只读扫描 `/conversation_summaries.db`,获取标题、实时运行状态与父会话归属; - * 3. 只读解码 `/conversations/.db` 的 `steps.metadata` 与 `gen_metadata.data` 轻量 Protobuf 字段 - * (跳过大体积提示词与工具载荷),完整还原纳秒级耗时、TTFT、思考/正文 Token 拆分、模型展示名与 10 通道上下文构成。 + * 2. 通过 Node 22.5+ 内置 `node:sqlite`(只读 + `SQLITE_BUSY` 退避重试 + WAL `mtime+size` 复合签名缓存)扫描 + * `/conversation_summaries.db`(含 `raw_summary` 与 `conversation_parents` 表),还原会话摘要与旁路提问父子映射; + * 3. 只读解码 `/conversations/.db`,自动过滤分叉/旁路提问克隆自父会话的步骤与 `gen_metadata` + * (`originCid !== cascadeId`),并对 `step_payload` 做按需列投影(仅读取 `USER_INPUT` 轮次提问、`INVOKE_SUBAGENT` + * 及运行态末尾步骤,O(1) 跳过大体积工具输出页),完整保留耗时、TTFT、轮次导轨与 10 通道上下文构成。 */ -import { existsSync, readFileSync, statSync } from 'node:fs'; +import { existsSync, readFileSync } from 'node:fs'; import { basename, join } from 'node:path'; -import { parseIsoMs } from '../speed-metrics.mjs'; +import { parseIsoMs } from '../trajectory-metrics.mjs'; import { ANNOTATION_DIRS, PRODUCT_DATA_ROOTS, localSummaryMemo } from './config.mjs'; +import { + SQLITE_IN_CHUNK_SIZE, + computeSqliteWalSig, + getNodeSqliteDatabaseSync, + hasBuiltinNodeSqlite, + normalizeSqliteIsoTime, + withReadOnlySqliteDb, +} from './sqlite-client.mjs'; +import { + decodeProtoDurationSlice, + decodeProtoMapStringEntry, + decodeProtoTimestampSlice, + readProtoString, + readProtoVarint, + readSubEnd, + skipProtoField, + toUint8Array, + unescapePbtxtString, +} from './proto-wire.mjs'; -let sqliteResolved = false; -let sqliteDatabaseSyncCtor = null; +export { + computeSqliteWalSig, + getNodeSqliteDatabaseSync, + hasBuiltinNodeSqlite, + withReadOnlySqliteDb, +}; -/** - * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器。 - * 首次加载时静默过滤 Node 22 的实验特性提示,避免污染 CLI 终端或 MCP 日志;不支持时返回 `null`。 - * - * @returns {Function | null} - */ -export function getNodeSqliteDatabaseSync() { - if (sqliteResolved) return sqliteDatabaseSyncCtor; - sqliteResolved = true; - if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') { - return null; - } - const origEmitWarning = process.emitWarning; - try { - if (typeof origEmitWarning === 'function') { - process.emitWarning = function filteredSqliteWarning(warning, ...rest) { - const msg = typeof warning === 'string' ? warning : String(warning?.message || ''); - if (/SQLite is an experimental feature/i.test(msg)) return; - return origEmitWarning.call(this, warning, ...rest); - }; - } - const mod = process.getBuiltinModule('node:sqlite'); - sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null; - } catch { - sqliteDatabaseSyncCtor = null; - } finally { - if (typeof origEmitWarning === 'function') { - process.emitWarning = origEmitWarning; - } - } - return sqliteDatabaseSyncCtor; -} - -/** - * 当前运行时是否具备内置 `node:sqlite` 读取能力。 - * - * @returns {boolean} - */ -export function hasBuiltinNodeSqlite() { - return Boolean(getNodeSqliteDatabaseSync()); -} - -/** - * 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。 - * - * @param {string} raw - * @returns {string} - */ -function unescapePbtxtString(raw) { - if (typeof raw !== 'string' || !raw) return ''; - if (!raw.includes('\\')) return raw; - const bytes = []; - for (let i = 0; i < raw.length; i++) { - const ch = raw[i]; - if (ch !== '\\' || i + 1 >= raw.length) { - const encoded = Buffer.from(ch, 'utf8'); - for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); - continue; - } - const next = raw[++i]; - if (next >= '0' && next <= '7') { - let oct = next; - if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; - if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; - bytes.push(parseInt(oct, 8) & 0xff); - } else if ((next === 'x' || next === 'X') && i + 2 < raw.length) { - const hex = raw.slice(i + 1, i + 3); - if (/^[0-9a-fA-F]{2}$/.test(hex)) { - bytes.push(parseInt(hex, 16)); - i += 2; - } else { - bytes.push(next.charCodeAt(0)); - } - } else if (next === 'u' && i + 4 < raw.length) { - const uHex = raw.slice(i + 1, i + 5); - if (/^[0-9a-fA-F]{4}$/.test(uHex)) { - const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8'); - for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); - i += 4; - } else { - bytes.push(next.charCodeAt(0)); - } - } else if (next === 'n') { - bytes.push(0x0a); - } else if (next === 'r') { - bytes.push(0x0d); - } else if (next === 't') { - bytes.push(0x09); - } else { - const encoded = Buffer.from(next, 'utf8'); - for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); - } - } - return Buffer.from(bytes).toString('utf8'); -} +const UUID_FILE_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; /** * 从 `annotations/.pbtxt` 文本内容中提取顶层 `title` 字段。 @@ -157,32 +87,327 @@ export function readAnnotationTitleForCascade(cascadeId, annotationDirs = ANNOTA return ''; } -function normalizeSqliteIsoTime(value) { - const raw = String(value || '').trim(); - if (!raw) return ''; - return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T'); +// --------------------------------------------------------------------------- +// 零依赖轻量 Protobuf Wire 解码器(按需提取指标字段,O(1) 跳过大体积载荷) +// --------------------------------------------------------------------------- + +const PROTO_STATIC_MODELS = Object.freeze({ + 235: 'MODEL_CHAT_20706', + 246: 'MODEL_GOOGLE_GEMINI_2_5_PRO', + 269: 'MODEL_CHAT_23310', + 281: 'MODEL_CLAUDE_4_SONNET', + 282: 'MODEL_CLAUDE_4_SONNET_THINKING', + 290: 'MODEL_CLAUDE_4_OPUS', + 291: 'MODEL_CLAUDE_4_OPUS_THINKING', + 312: 'MODEL_GOOGLE_GEMINI_2_5_FLASH', + 313: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING', + 327: 'MODEL_GOOGLE_GEMINI_FOR_GOOGLE_2_5_PRO', + 329: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING_TOOLS', + 330: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE', + 332: 'MODEL_GOOGLE_GEMINI_2_5_FLASH_IMAGE_PREVIEW', + 333: 'MODEL_CLAUDE_4_5_SONNET', + 334: 'MODEL_CLAUDE_4_5_SONNET_THINKING', + 340: 'MODEL_CLAUDE_4_5_HAIKU', + 341: 'MODEL_CLAUDE_4_5_HAIKU_THINKING', + 342: 'MODEL_OPENAI_GPT_OSS_120B_MEDIUM', +}); + +const PROTO_API_PROVIDERS = Object.freeze({ + 1: 'API_PROVIDER_INTERNAL', + 3: 'API_PROVIDER_GOOGLE_VERTEX', + 24: 'API_PROVIDER_GOOGLE_GEMINI', + 26: 'API_PROVIDER_ANTHROPIC_VERTEX', + 30: 'API_PROVIDER_GOOGLE_EVERGREEN', + 31: 'API_PROVIDER_OPENAI_VERTEX', + 32: 'API_PROVIDER_OPENAI_RESPONSES_VERTEX', +}); + +const PROTO_STEP_TYPES = Object.freeze({ + 5: 'CORTEX_STEP_TYPE_CODE_ACTION', + 7: 'CORTEX_STEP_TYPE_GREP_SEARCH', + 8: 'CORTEX_STEP_TYPE_VIEW_FILE', + 9: 'CORTEX_STEP_TYPE_LIST_DIRECTORY', + 14: 'CORTEX_STEP_TYPE_USER_INPUT', + 15: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + 17: 'CORTEX_STEP_TYPE_ERROR_MESSAGE', + 21: 'CORTEX_STEP_TYPE_RUN_COMMAND', + 23: 'CORTEX_STEP_TYPE_CHECKPOINT', + 25: 'CORTEX_STEP_TYPE_FIND', + 28: 'CORTEX_STEP_TYPE_COMMAND_STATUS', + 31: 'CORTEX_STEP_TYPE_READ_URL_CONTENT', + 33: 'CORTEX_STEP_TYPE_SEARCH_WEB', + 38: 'CORTEX_STEP_TYPE_MCP_TOOL', + 51: 'CORTEX_STEP_TYPE_LIST_RESOURCES', + 52: 'CORTEX_STEP_TYPE_READ_RESOURCE', + 81: 'CORTEX_STEP_TYPE_TASK_BOUNDARY', + 82: 'CORTEX_STEP_TYPE_NOTIFY_USER', + 85: 'CORTEX_STEP_TYPE_BROWSER_SUBAGENT', + 90: 'CORTEX_STEP_TYPE_EPHEMERAL_MESSAGE', + 91: 'CORTEX_STEP_TYPE_GENERATE_IMAGE', + 100: 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT', + 101: 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE', + 127: 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT', + 132: 'CORTEX_STEP_TYPE_GENERIC', + 138: 'CORTEX_STEP_TYPE_ASK_QUESTION', +}); + +const PROTO_STEP_STATUSES = Object.freeze({ + 1: 'CORTEX_STEP_STATUS_PENDING', + 2: 'CORTEX_STEP_STATUS_RUNNING', + 3: 'CORTEX_STEP_STATUS_DONE', + 4: 'CORTEX_STEP_STATUS_INVALID', + 5: 'CORTEX_STEP_STATUS_CLEARED', + 6: 'CORTEX_STEP_STATUS_CANCELED', + 7: 'CORTEX_STEP_STATUS_ERROR', + 8: 'CORTEX_STEP_STATUS_GENERATING', + 9: 'CORTEX_STEP_STATUS_WAITING', + 11: 'CORTEX_STEP_STATUS_QUEUED', + 12: 'CORTEX_STEP_STATUS_INTERRUPTED', +}); + +const PROTO_RUN_STATUSES = Object.freeze({ + 1: 'CASCADE_RUN_STATUS_IDLE', + 2: 'CASCADE_RUN_STATUS_RUNNING', + 3: 'CASCADE_RUN_STATUS_CANCELING', + 4: 'CASCADE_RUN_STATUS_BUSY', +}); + +const PROTO_TRAJECTORY_SOURCES = Object.freeze({ + 1: 'CORTEX_TRAJECTORY_SOURCE_CASCADE_CLIENT', + 12: 'CORTEX_TRAJECTORY_SOURCE_INTERACTIVE_CASCADE', + 15: 'CORTEX_TRAJECTORY_SOURCE_SDK', + 16: 'CORTEX_TRAJECTORY_SOURCE_SUBAGENT', + 17: 'CORTEX_TRAJECTORY_SOURCE_CLI', + 18: 'CORTEX_TRAJECTORY_SOURCE_JETBOX', + 22: 'CORTEX_TRAJECTORY_SOURCE_VSCODE', + 23: 'CORTEX_TRAJECTORY_SOURCE_VISUAL_STUDIO', +}); + +const PROTO_TOKEN_TYPES = Object.freeze({ + 1: 'TOKEN_TYPE_SYSTEM_PROMPT', + 2: 'TOKEN_TYPE_TOOLS', + 3: 'TOKEN_TYPE_RULES', + 4: 'TOKEN_TYPE_MCP_TOOLS', + 5: 'TOKEN_TYPE_SKILLS', + 6: 'TOKEN_TYPE_SUBAGENTS', + 7: 'TOKEN_TYPE_CHAT_MESSAGES', + 8: 'TOKEN_TYPE_WORKFLOWS', + 9: 'TOKEN_TYPE_PLUGINS', + 10: 'TOKEN_TYPE_FLOWS', +}); + +const PROTO_TOKEN_SOURCES = Object.freeze({ + 1: 'TOKEN_SOURCE_SYSTEM', + 2: 'TOKEN_SOURCE_USER', +}); + +const PROTO_CHAT_MSG_SOURCES = Object.freeze({ + 1: 'CHAT_MESSAGE_SOURCE_USER', + 2: 'CHAT_MESSAGE_SOURCE_SYSTEM', + 3: 'CHAT_MESSAGE_SOURCE_UNKNOWN', + 4: 'CHAT_MESSAGE_SOURCE_TOOL', + 5: 'CHAT_MESSAGE_SOURCE_SYSTEM_PROMPT', + 6: 'CHAT_MESSAGE_SOURCE_CONTEXT', +}); + +function decodeProtoModelEnumInt(val) { + const n = Math.trunc(Number(val)); + if (!Number.isFinite(n) || n <= 0) return ''; + if (n >= 1000 && n < 100000) { + return `MODEL_PLACEHOLDER_M${n - 1000}`; + } + return PROTO_STATIC_MODELS[n] || ''; +} + +function decodeProtoStepTypeEnum(val) { + const n = Math.trunc(Number(val)); + return PROTO_STEP_TYPES[n] || 'CORTEX_STEP_TYPE_GENERIC'; +} + +function decodeProtoStepStatusEnum(val) { + const n = Math.trunc(Number(val)); + return PROTO_STEP_STATUSES[n] || 'CORTEX_STEP_STATUS_DONE'; +} + +function decodeProtoSubagentSpecSlice(buf, state, end) { + let typeName = ''; + let role = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + typeName = readProtoString(buf, state, end).trim(); + } else if (fn === 2 && wt === 2) { + role = readProtoString(buf, state, end).trim(); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return typeName || role ? { typeName, role } : null; +} + +function decodeProtoTrajectoryMetadataSlice(buf, state, end) { + let createdAt = ''; + let parentConversationId = ''; + let rootConversationId = ''; + let nestingDepth = 0; + let subagentSpec = null; + let agentScript = null; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 2 && wt === 2) { + createdAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 4 && wt === 2) { + const asEnd = readSubEnd(buf, state, end); + let name = ''; + while (state.off < asEnd) { + const asTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, asEnd))); + if ((asTag >>> 3) === 1 && (asTag & 7) === 2) { + name = readProtoString(buf, state, asEnd).trim(); + } else { + skipProtoField(buf, state, asTag & 7, asEnd); + } + } + state.off = asEnd; + if (name) agentScript = { name }; + } else if (fn === 5 && wt === 2) { + parentConversationId = readProtoString(buf, state, end).trim().toLowerCase(); + } else if (fn === 6 && wt === 2) { + rootConversationId = readProtoString(buf, state, end).trim().toLowerCase(); + } else if (fn === 8 && wt === 2) { + subagentSpec = decodeProtoSubagentSpecSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 17 && wt === 0) { + nestingDepth = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { + createdAt, + parentConversationId, + rootConversationId, + nestingDepth, + subagentSpec, + agentScript, + }; +} + +function decodeProtoCascadeTrajectorySummary(rawBlob) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) return null; + const state = { off: 0 }; + const end = buf.length; + + let summary = ''; + let stepCount; + let lastModifiedTime = ''; + let status = ''; + let createdTime = ''; + let source = ''; + let notFullyIdle; + let trajectoryType = 0; + let killed; + let forkParentConversationId = ''; + let title = ''; + let archived = false; + const sideQuestionCascadeIds = []; + const sideQuestionTitles = {}; + let trajectoryMetadata = null; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + summary = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 0) { + stepCount = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + } else if (fn === 3 && wt === 2) { + lastModifiedTime = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 5 && wt === 0) { + const sNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + status = PROTO_RUN_STATUSES[sNum] || ''; + } else if (fn === 7 && wt === 2) { + createdTime = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 15 && wt === 2) { + const annEnd = readSubEnd(buf, state, end); + while (state.off < annEnd) { + const aTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, annEnd))); + const aFn = aTag >>> 3; + const aWt = aTag & 7; + if (aFn === 1 && aWt === 2) { + title = readProtoString(buf, state, annEnd); + } else if (aFn === 4 && aWt === 0) { + archived = readProtoVarint(buf, state, annEnd) !== 0n; + } else if (aFn === 17 && aWt === 2) { + const sqId = readProtoString(buf, state, annEnd).trim().toLowerCase(); + if (sqId) sideQuestionCascadeIds.push(sqId); + } else if (aFn === 18 && aWt === 2) { + const [k, v] = decodeProtoMapStringEntry(buf, state, readSubEnd(buf, state, annEnd)); + const lk = k.trim().toLowerCase(); + if (lk) sideQuestionTitles[lk] = v; + } else { + skipProtoField(buf, state, aWt, annEnd); + } + } + state.off = annEnd; + } else if (fn === 17 && wt === 2) { + trajectoryMetadata = decodeProtoTrajectoryMetadataSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 20 && wt === 0) { + const srcNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + source = PROTO_TRAJECTORY_SOURCES[srcNum] || ''; + } else if (fn === 21 && wt === 0) { + notFullyIdle = readProtoVarint(buf, state, end) !== 0n; + } else if (fn === 22 && wt === 0) { + trajectoryType = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + } else if (fn === 23 && wt === 0) { + killed = readProtoVarint(buf, state, end) !== 0n; + } else if (fn === 24 && wt === 2) { + forkParentConversationId = readProtoString(buf, state, end).trim().toLowerCase(); + } else { + skipProtoField(buf, state, wt, end); + } + } + + return { + summary, + stepCount, + lastModifiedTime, + createdTime, + status, + source, + notFullyIdle, + trajectoryType, + killed, + forkParentConversationId, + annotations: { + title, + archived, + sideQuestionCascadeIds, + sideQuestionTitles, + }, + trajectoryMetadata, + }; } /** - * 读取并缓存各产品数据根目录下的 `conversation_summaries.db` 摘要索引。 - * 使用 `.db` 与 `.db-wal` 的 `mtimeMs + size` 组合签名做内存 Memoize,未发生写入时零 I/O 返回。 + * 读取并缓存各产品数据根目录(Desktop / IDE / CLI)下的 `conversation_summaries.db` 完整快照。 + * 使用 `.db` 与 `.db-wal` 复合签名做内存 Memoize,未发生写入时零 I/O 返回。 * * @param {string[]} [productRoots=PRODUCT_DATA_ROOTS] - * @returns {Map} + * @param {{ forceRefresh?: boolean }} [options={}] */ -export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { +export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { forceRefresh = false } = {}) { const DatabaseSync = getNodeSqliteDatabaseSync(); - if (!DatabaseSync) return new Map(); + if (!DatabaseSync) { + return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} }; + } const roots = Array.isArray(productRoots) ? productRoots : []; const sigParts = []; const targets = []; @@ -190,335 +415,402 @@ export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { for (const root of roots) { if (!root) continue; const dbPath = join(root, 'conversation_summaries.db'); - if (!existsSync(dbPath)) continue; - try { - const st = statSync(dbPath); - let walPart = '0:0'; - const walPath = `${dbPath}-wal`; - if (existsSync(walPath)) { - try { - const wst = statSync(walPath); - walPart = `${wst.mtimeMs || 0}:${wst.size || 0}`; - } catch { - // 忽略并发清理的 wal 文件 - } - } - sigParts.push(`${dbPath}:${st.mtimeMs || 0}:${st.size || 0}:${walPart}`); - targets.push({ rootName: basename(root).toLowerCase(), dbPath }); - } catch { - // 忽略不可访问的摘要库 - } + const walInfo = computeSqliteWalSig(dbPath); + if (!walInfo.exists) continue; + sigParts.push(`${dbPath}:${walInfo.sig}`); + targets.push({ rootName: basename(root).toLowerCase(), dbPath }); } + const rootsKey = roots + .map((r) => String(r || '').trim()) + .filter(Boolean) + .join('\n'); + if (targets.length === 0) { - localSummaryMemo.sig = ''; - localSummaryMemo.byId.clear(); - return localSummaryMemo.byId; + if (productRoots === PRODUCT_DATA_ROOTS) { + localSummaryMemo.sig = ''; + localSummaryMemo.byId.clear(); + localSummaryMemo.available = false; + localSummaryMemo.summariesObj = {}; + localSummaryMemo.sideQuestionParents = {}; + } + if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) { + localSummaryMemo.byRootsKey.delete(rootsKey); + } + return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} }; } - const sig = sigParts.join('|'); - if (localSummaryMemo.sig === sig && localSummaryMemo.byId.size > 0) { - return localSummaryMemo.byId; + const sig = sigParts.join('||'); + if (!forceRefresh) { + if ( + productRoots === PRODUCT_DATA_ROOTS && + localSummaryMemo.sig === sig && + localSummaryMemo.available + ) { + return { + available: true, + sig, + byId: localSummaryMemo.byId, + summariesObj: localSummaryMemo.summariesObj || {}, + sideQuestionParents: localSummaryMemo.sideQuestionParents || {}, + }; + } + if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) { + const cached = localSummaryMemo.byRootsKey.get(rootsKey); + if (cached && cached.sig === sig && cached.available) { + localSummaryMemo.byRootsKey.delete(rootsKey); + localSummaryMemo.byRootsKey.set(rootsKey, cached); + return { + available: true, + sig, + byId: cached.byId, + summariesObj: cached.summariesObj, + sideQuestionParents: cached.sideQuestionParents, + }; + } + } } const nextMap = new Map(); + const nextSummariesObj = {}; + const nextSideQuestionParents = {}; + let anyDbSucceeded = false; + for (const { rootName, dbPath } of targets) { - let db = null; try { - db = new DatabaseSync(dbPath, { readOnly: true }); - const rows = db - .prepare( - `SELECT - conversation_id, - title, - status, - parent_conversation_id, - agent_name, - not_fully_idle, - killed, - step_count, - last_modified_time, - app_data_dir - FROM conversation_summaries` - ) - .all(); - for (const row of rows || []) { - const cidLower = String(row?.conversation_id || '').trim().toLowerCase(); - if (!cidLower) continue; - const appDataDir = String(row?.app_data_dir || '').trim().toLowerCase(); - const isNativeRootRow = Boolean(appDataDir && appDataDir === rootName); - const lastModifiedTime = normalizeSqliteIsoTime(row?.last_modified_time); - const lastModifiedMs = parseIsoMs(lastModifiedTime); - const rawStatus = String(row?.status || '').trim(); - const isRunning = - !Number(row?.killed) && - (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || - (Number(row?.not_fully_idle) > 0 && rawStatus !== 'CASCADE_RUN_STATUS_IDLE')); - const entry = { - cascadeId: cidLower, - title: String(row?.title || '').trim(), - status: isRunning ? 'CASCADE_RUN_STATUS_RUNNING' : rawStatus || 'CASCADE_RUN_STATUS_IDLE', - parentConversationId: String(row?.parent_conversation_id || '').trim().toLowerCase(), - agentName: String(row?.agent_name || '').trim(), - stepCount: Math.max(0, Math.floor(Number(row?.step_count) || 0)), - lastModifiedTime, - lastModifiedMs, - appDataDir, - isNativeRootRow, - }; - const prev = nextMap.get(cidLower); - if ( - !prev || - (entry.isNativeRootRow && !prev.isNativeRootRow) || - (entry.isNativeRootRow === prev.isNativeRootRow && - entry.lastModifiedMs >= prev.lastModifiedMs) - ) { - nextMap.set(cidLower, entry); - } - } - } catch { - // 忽略正在初始化或损坏的 SQLite 文件 - } finally { - if (db) { + withReadOnlySqliteDb(dbPath, (db) => { + let rows = []; try { - db.close(); + rows = db + .prepare( + `SELECT + conversation_id, + title, + preview, + status, + source, + parent_conversation_id, + nesting_depth, + agent_name, + not_fully_idle, + killed, + step_count, + last_modified_time, + app_data_dir, + raw_summary + FROM conversation_summaries` + ) + .all(); } catch { - // 忽略关闭异常 + rows = db + .prepare( + `SELECT + conversation_id, + title, + status, + parent_conversation_id, + agent_name, + not_fully_idle, + killed, + step_count, + last_modified_time, + app_data_dir + FROM conversation_summaries` + ) + .all(); } - } + anyDbSucceeded = true; + + let parentRows = []; + try { + parentRows = db + .prepare('SELECT conversation_id, parent_id FROM conversation_parents') + .all(); + } catch { + parentRows = []; + } + + for (const row of rows || []) { + const cidLower = String(row?.conversation_id || '').trim().toLowerCase(); + if (!cidLower) continue; + + let decoded = null; + if (row?.raw_summary) { + try { + decoded = decodeProtoCascadeTrajectorySummary(row.raw_summary); + } catch { + decoded = null; + } + } + + const appDataDir = String(row?.app_data_dir || '').trim().toLowerCase(); + const isNativeRootRow = Boolean(appDataDir && appDataDir === rootName); + const sqlLastMod = normalizeSqliteIsoTime(row?.last_modified_time); + const createdTime = String( + decoded?.createdTime || decoded?.trajectoryMetadata?.createdAt || '' + ); + const lastModifiedTime = String(decoded?.lastModifiedTime || sqlLastMod || createdTime || ''); + const lastModifiedMs = parseIsoMs(lastModifiedTime); + const rawStatus = String(decoded?.status || row?.status || '').trim(); + const killed = Boolean(decoded?.killed ?? Number(row?.killed)); + const notFullyIdle = Boolean(decoded?.notFullyIdle ?? Number(row?.not_fully_idle) > 0); + const isRunning = + !killed && + (rawStatus === 'CASCADE_RUN_STATUS_RUNNING' || + (notFullyIdle && rawStatus !== 'CASCADE_RUN_STATUS_IDLE')); + const effectiveStatus = isRunning + ? 'CASCADE_RUN_STATUS_RUNNING' + : rawStatus || 'CASCADE_RUN_STATUS_IDLE'; + + const rawMeta = decoded?.trajectoryMetadata || null; + const parentConversationId = String( + rawMeta?.parentConversationId || row?.parent_conversation_id || '' + ) + .trim() + .toLowerCase(); + const rootConversationId = String(rawMeta?.rootConversationId || '').trim().toLowerCase(); + const agentName = String( + rawMeta?.agentScript?.name || row?.agent_name || '' + ).trim(); + const title = String(decoded?.annotations?.title || row?.title || '').trim(); + const stepCount = Math.max( + 0, + Math.floor(Number(decoded?.stepCount ?? row?.step_count ?? 0) || 0) + ); + const trajectoryType = Number(decoded?.trajectoryType || 0); + const isSideQuestion = trajectoryType === 22; + const forkParentConversationId = String(decoded?.forkParentConversationId || '') + .trim() + .toLowerCase(); + + const sideQuestionIds = Array.isArray(decoded?.annotations?.sideQuestionCascadeIds) + ? decoded.annotations.sideQuestionCascadeIds + : []; + const sideQuestionTitles = decoded?.annotations?.sideQuestionTitles || {}; + + const entry = { + cascadeId: cidLower, + title, + status: effectiveStatus, + parentConversationId, + rootConversationId, + agentName, + subagentSpec: rawMeta?.subagentSpec || null, + stepCount, + lastModifiedTime, + lastModifiedMs, + createdTime, + appDataDir, + isNativeRootRow, + trajectoryType, + isSideQuestion, + forkParentConversationId, + }; + + const summaryRpcShape = { + summary: String(decoded?.summary || row?.preview || ''), + stepCount, + lastModifiedTime, + createdTime, + status: effectiveStatus, + source: String(decoded?.source || row?.source || ''), + appDataDir, + notFullyIdle, + killed, + trajectoryType, + isSideQuestion, + forkParentConversationId, + annotations: { + title, + archived: Boolean(decoded?.annotations?.archived), + sideQuestionCascadeIds: sideQuestionIds, + sideQuestionTitles, + }, + trajectoryMetadata: { + createdAt: String(rawMeta?.createdAt || createdTime || ''), + parentConversationId, + rootConversationId, + nestingDepth: Number(rawMeta?.nestingDepth ?? row?.nesting_depth ?? 0), + subagentSpec: rawMeta?.subagentSpec || null, + agentScript: agentName ? { name: agentName } : null, + }, + }; + + const prev = nextMap.get(cidLower); + if ( + !prev || + (entry.isNativeRootRow && !prev.isNativeRootRow) || + (entry.isNativeRootRow === prev.isNativeRootRow && + entry.lastModifiedMs >= prev.lastModifiedMs) + ) { + nextMap.set(cidLower, entry); + nextSummariesObj[cidLower] = summaryRpcShape; + } + + if (isSideQuestion && forkParentConversationId) { + const existingSq = nextSideQuestionParents[cidLower]; + nextSideQuestionParents[cidLower] = { + parentConversationId: existingSq?.parentConversationId || forkParentConversationId, + title: existingSq?.title || title || '', + }; + } + + for (const sqId of sideQuestionIds) { + const sqLower = String(sqId || '').trim().toLowerCase(); + if (!sqLower) continue; + nextSideQuestionParents[sqLower] = { + parentConversationId: cidLower, + title: String(sideQuestionTitles[sqLower] || nextSideQuestionParents[sqLower]?.title || ''), + }; + } + for (const [sqKey, sqTitle] of Object.entries(sideQuestionTitles)) { + const sqLower = String(sqKey || '').trim().toLowerCase(); + if (!sqLower) continue; + const existingSq = nextSideQuestionParents[sqLower]; + nextSideQuestionParents[sqLower] = { + parentConversationId: existingSq?.parentConversationId || cidLower, + title: String(sqTitle || existingSq?.title || ''), + }; + } + } + + for (const pRow of parentRows || []) { + const sqLower = String(pRow?.conversation_id || '').trim().toLowerCase(); + const parentLower = String(pRow?.parent_id || '').trim().toLowerCase(); + if (!sqLower || !parentLower) continue; + const parentSummary = nextSummariesObj[parentLower]; + const titleFromParent = String( + parentSummary?.annotations?.sideQuestionTitles?.[sqLower] || + nextSideQuestionParents[sqLower]?.title || + '' + ); + nextSideQuestionParents[sqLower] = { + parentConversationId: parentLower, + title: titleFromParent, + }; + } + }); + } catch { + // 忽略正在初始化或不可读的单个 SQLite 摘要库 } } - localSummaryMemo.sig = sig; - localSummaryMemo.byId = nextMap; - return nextMap; -} - -// --------------------------------------------------------------------------- -// 零依赖轻量 Protobuf Wire 解码器(仅提取指标字段,O(1) 跳过大体积 Prompt 载荷) -// --------------------------------------------------------------------------- - -function readProtoVarint(buf, state) { - let result = 0n; - let shift = 0n; - while (state.off < buf.length) { - const byte = BigInt(buf[state.off++]); - result |= (byte & 0x7fn) << shift; - if ((byte & 0x80n) === 0n) return result; - shift += 7n; - if (shift > 70n) throw new Error('Invalid protobuf varint'); + if (!anyDbSucceeded) { + return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} }; } - throw new Error('Unexpected EOF in protobuf varint'); -} -function skipProtoField(buf, state, wireType) { - if (wireType === 0) { - readProtoVarint(buf, state); - } else if (wireType === 1) { - state.off += 8; - } else if (wireType === 2) { - const len = Number(readProtoVarint(buf, state)); - state.off += len; - } else if (wireType === 5) { - state.off += 4; - } else { - throw new Error(`Unsupported protobuf wireType: ${wireType}`); - } - if (state.off > buf.length) { - throw new Error('Protobuf field length out of bounds'); - } -} - -function decodeProtoTimestampIso(buf) { - const st = { off: 0 }; - let seconds = 0n; - let nanos = 0n; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 0) { - seconds = BigInt.asIntN(64, readProtoVarint(buf, st)); - } else if (fn === 2 && wt === 0) { - nanos = BigInt.asIntN(32, readProtoVarint(buf, st)); - } else { - skipProtoField(buf, st, wt); - } - } - if (seconds <= 0n) return ''; - const baseIso = new Date(Number(seconds) * 1000).toISOString(); - const prefix = baseIso.slice(0, 19); - if (nanos > 0n && nanos < 1_000_000_000n) { - const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); - return frac ? `${prefix}.${frac}Z` : `${prefix}Z`; - } - return `${prefix}Z`; -} - -function decodeProtoDurationStr(buf) { - const st = { off: 0 }; - let seconds = 0n; - let nanos = 0n; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 0) { - seconds = BigInt.asIntN(64, readProtoVarint(buf, st)); - } else if (fn === 2 && wt === 0) { - nanos = BigInt.asIntN(32, readProtoVarint(buf, st)); - } else { - skipProtoField(buf, st, wt); - } - } - if (seconds < 0n || nanos < 0n) return ''; - if (nanos === 0n) return `${seconds}s`; - const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); - return frac ? `${seconds}.${frac}s` : `${seconds}s`; -} - -function decodeProtoModelEnumInt(val) { - const n = Number(val); - if (Number.isInteger(n) && n >= 1000 && n < 10000) { - return `MODEL_PLACEHOLDER_M${n - 1000}`; - } - return ''; -} - -function decodeProtoTokenTypeEnum(val) { - switch (Number(val)) { - case 1: - return 'TOKEN_TYPE_SYSTEM_PROMPT'; - case 2: - return 'TOKEN_TYPE_TOOLS'; - case 3: - return 'TOKEN_TYPE_RULES'; - case 4: - return 'TOKEN_TYPE_MCP_TOOLS'; - case 5: - return 'TOKEN_TYPE_SKILLS'; - case 6: - return 'TOKEN_TYPE_SUBAGENTS'; - case 7: - return 'TOKEN_TYPE_CHAT_MESSAGES'; - default: - return ''; - } -} - -function decodeProtoStepTypeEnum(val) { - switch (Number(val)) { - case 14: - return 'CORTEX_STEP_TYPE_USER_INPUT'; - case 15: - return 'CORTEX_STEP_TYPE_PLANNER_RESPONSE'; - case 17: - return 'CORTEX_STEP_TYPE_ERROR_MESSAGE'; - case 23: - return 'CORTEX_STEP_TYPE_CHECKPOINT'; - case 101: - return 'CORTEX_STEP_TYPE_SYSTEM_MESSAGE'; - default: - return 'CORTEX_STEP_TYPE_GENERIC'; - } -} - -function decodeProtoStepStatusEnum(val) { - switch (Number(val)) { - case 2: - return 'CORTEX_STEP_STATUS_RUNNING'; - case 3: - return 'CORTEX_STEP_STATUS_DONE'; - case 5: - return 'CORTEX_STEP_STATUS_CLEARED'; - case 6: - return 'CORTEX_STEP_STATUS_CANCELED'; - case 7: - return 'CORTEX_STEP_STATUS_ERROR'; - case 8: - return 'CORTEX_STEP_STATUS_GENERATING'; - default: - return 'CORTEX_STEP_STATUS_DONE'; - } -} - -function decodeProtoModelUsage(buf) { - const st = { off: 0 }; - let model = ''; - let inputTokens = 0; - let outputTokens = 0; - let cacheReadTokens = 0; - let apiProviderNum = 0; - let thinkingOutputTokens; - let responseOutputTokens; - - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 0) { - model = decodeProtoModelEnumInt(readProtoVarint(buf, st)); - } else if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - model = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; - } else if (fn === 2 && wt === 0) { - inputTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 3 && wt === 0) { - outputTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 5 && wt === 0) { - cacheReadTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 6 && wt === 0) { - apiProviderNum = Number(readProtoVarint(buf, st)); - } else if (fn === 9 && wt === 0) { - thinkingOutputTokens = Number(readProtoVarint(buf, st)); - } else if (fn === 10 && wt === 0) { - responseOutputTokens = Number(readProtoVarint(buf, st)); - } else { - skipProtoField(buf, st, wt); + if (productRoots === PRODUCT_DATA_ROOTS) { + localSummaryMemo.sig = sig; + localSummaryMemo.byId = nextMap; + localSummaryMemo.available = true; + localSummaryMemo.summariesObj = nextSummariesObj; + localSummaryMemo.sideQuestionParents = nextSideQuestionParents; + } else if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) { + if (!localSummaryMemo.byRootsKey.has(rootsKey) && localSummaryMemo.byRootsKey.size >= 8) { + localSummaryMemo.byRootsKey.delete(localSummaryMemo.byRootsKey.keys().next().value); } + localSummaryMemo.byRootsKey.delete(rootsKey); + localSummaryMemo.byRootsKey.set(rootsKey, { + available: true, + sig, + byId: nextMap, + summariesObj: nextSummariesObj, + sideQuestionParents: nextSideQuestionParents, + }); } return { - ...(model ? { model } : {}), - ...(apiProviderNum === 24 ? { apiProvider: 'API_PROVIDER_GOOGLE_GEMINI' } : {}), - inputTokens, - cacheReadTokens, - outputTokens, - ...(thinkingOutputTokens !== undefined ? { thinkingOutputTokens } : {}), - ...(responseOutputTokens !== undefined ? { responseOutputTokens } : {}), + available: true, + sig, + byId: nextMap, + summariesObj: nextSummariesObj, + sideQuestionParents: nextSideQuestionParents, }; } -function decodeProtoTokenBreakdownGroup(buf, depth = 0) { - const st = { off: 0 }; +/** + * 读取并缓存各产品数据根目录下的 `conversation_summaries.db` 摘要索引(返回 `Map`,保持向后兼容)。 + * + * @param {string[]} [productRoots=PRODUCT_DATA_ROOTS] + * @returns {Map} + */ +export function readLocalSummaryIndex(productRoots = PRODUCT_DATA_ROOTS) { + return readLocalSummarySnapshot(productRoots).byId; +} + +function decodeProtoModelUsageSlice(buf, state, end) { + const usage = {}; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + const m = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); + if (m) usage.model = m; + } else if (fn === 1 && wt === 2) { + const m = readProtoString(buf, state, end).trim(); + if (m) usage.model = m; + } else if (fn === 2 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.inputTokens = v; + } else if (fn === 3 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.outputTokens = v; + } else if (fn === 5 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.cacheReadTokens = v; + } else if (fn === 6 && wt === 0) { + const provNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const prov = PROTO_API_PROVIDERS[provNum] || ''; + if (prov) usage.apiProvider = prov; + } else if (fn === 9 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.thinkingOutputTokens = v; + } else if (fn === 10 && wt === 0) { + const v = Number(BigInt.asUintN(64, readProtoVarint(buf, state, end))); + if (v > 0) usage.responseOutputTokens = v; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (usage.inputTokens === undefined) usage.inputTokens = 0; + if (usage.cacheReadTokens === undefined) usage.cacheReadTokens = 0; + if (usage.outputTokens === undefined) usage.outputTokens = 0; + return usage; +} + +function decodeProtoChildTokenGroupSlice(buf, state, end, depth = 0) { let name = ''; let type = ''; let numTokens = 0; const children = []; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - name = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; + name = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2 && depth < 2) { + // 子级 TokenGroup 的 children 位于 field 2 + children.push(decodeProtoChildTokenGroupSlice(buf, state, readSubEnd(buf, state, end), depth + 1)); } else if (fn === 2 && wt === 0) { - type = decodeProtoTokenTypeEnum(readProtoVarint(buf, st)); + const tNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + type = PROTO_TOKEN_TYPES[tNum] || ''; + } else if (fn === 3 && wt === 0) { + // 子级 TokenGroup 的 numTokens 位于 field 3 + numTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 4 && wt === 0) { - numTokens = Number(readProtoVarint(buf, st)); + // 兼容直接按顶层结构编码的子组(numTokens 位于 field 4) + numTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 5 && wt === 2 && depth < 2) { - const len = Number(readProtoVarint(buf, st)); - const sub = buf.subarray(st.off, st.off + len); - st.off += len; - children.push(decodeProtoTokenBreakdownGroup(sub, depth + 1)); + children.push(decodeProtoChildTokenGroupSlice(buf, state, readSubEnd(buf, state, end), depth + 1)); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } - + state.off = end; return { name, ...(type ? { type } : {}), @@ -527,75 +819,92 @@ function decodeProtoTokenBreakdownGroup(buf, depth = 0) { }; } -function decodeProtoContextWindowMeta(buf) { - const st = { off: 0 }; +function decodeProtoTopTokenGroupSlice(buf, state, end) { + let name = ''; + let type = ''; + let source = ''; + let numTokens = 0; + const children = []; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + name = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 0) { + const tNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + type = PROTO_TOKEN_TYPES[tNum] || ''; + } else if (fn === 3 && wt === 0) { + const sNum = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + source = PROTO_TOKEN_SOURCES[sNum] || ''; + } else if (fn === 4 && wt === 0) { + numTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); + } else if (fn === 5 && wt === 2) { + children.push(decodeProtoChildTokenGroupSlice(buf, state, readSubEnd(buf, state, end), 0)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { + name, + ...(type ? { type } : {}), + ...(source ? { source } : {}), + numTokens, + ...(children.length > 0 ? { children } : {}), + }; +} + +function decodeProtoContextWindowMetaSlice(buf, state, end, includeBreakdown) { let estimatedTokensUsed = 0; let maxContextTokens = 0; const groups = []; + let totalTokens = 0; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 1 && wt === 0) { - estimatedTokensUsed = Number(readProtoVarint(buf, st)); + estimatedTokensUsed = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 4 && wt === 0) { - maxContextTokens = Number(readProtoVarint(buf, st)); + maxContextTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, end))); } else if (fn === 3 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const tbBuf = buf.subarray(st.off, st.off + len); - st.off += len; - const tbSt = { off: 0 }; - while (tbSt.off < tbBuf.length) { - const tbTag = Number(readProtoVarint(tbBuf, tbSt)); - const tbFn = tbTag >>> 3; - const tbWt = tbTag & 7; - if (tbFn === 1 && tbWt === 2) { - const gLen = Number(readProtoVarint(tbBuf, tbSt)); - const gBuf = tbBuf.subarray(tbSt.off, tbSt.off + gLen); - tbSt.off += gLen; - groups.push(decodeProtoTokenBreakdownGroup(gBuf, 0)); - } else { - skipProtoField(tbBuf, tbSt, tbWt); + if (includeBreakdown) { + const tbEnd = readSubEnd(buf, state, end); + while (state.off < tbEnd) { + const tbTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, tbEnd))); + const tbFn = tbTag >>> 3; + const tbWt = tbTag & 7; + if (tbFn === 1 && tbWt === 2) { + groups.push(decodeProtoTopTokenGroupSlice(buf, state, readSubEnd(buf, state, tbEnd))); + } else if (tbFn === 2 && tbWt === 0) { + totalTokens = Number(BigInt.asIntN(32, readProtoVarint(buf, state, tbEnd))); + } else { + skipProtoField(buf, state, tbWt, tbEnd); + } } + state.off = tbEnd; + } else { + skipProtoField(buf, state, wt, end); } } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } + state.off = end; return { ...(estimatedTokensUsed > 0 ? { estimatedTokensUsed } : {}), ...(maxContextTokens > 0 ? { maxContextTokens } : {}), - ...(groups.length > 0 ? { tokenBreakdown: { groups } } : {}), + ...(includeBreakdown && groups.length > 0 + ? { tokenBreakdown: { groups, ...(totalTokens > 0 ? { totalTokens } : {}) } } + : {}), }; } -function decodeProtoMapStringEntry(buf) { - const st = { off: 0 }; - let key = ''; - let val = ''; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); - const fn = tag >>> 3; - const wt = tag & 7; - if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - key = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; - } else if (fn === 2 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - val = buf.subarray(st.off, st.off + len).toString('utf8'); - st.off += len; - } else { - skipProtoField(buf, st, wt); - } - } - return [key, val]; -} - -function decodeProtoChatModelMeta(buf) { - const st = { off: 0 }; +function decodeProtoChatModelMetaSlice(buf, state, end, includeBreakdown) { let model = ''; let usage = null; let contextWindowMetadata = null; @@ -604,67 +913,133 @@ function decodeProtoChatModelMeta(buf) { let responseModel = ''; let modelDisplayName = ''; const extraMeta = {}; + let messagePrompts = null; + let tools = null; + let promptSections = null; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; - if (fn === 3 && wt === 0) { - const enumStr = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + if (fn === 2 && wt === 2) { + if (includeBreakdown) { + const mpEnd = readSubEnd(buf, state, end); + const msg = {}; + while (state.off < mpEnd) { + const mTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, mpEnd))); + const mFn = mTag >>> 3; + const mWt = mTag & 7; + if (mFn === 2 && mWt === 0) { + const src = PROTO_CHAT_MSG_SOURCES[Number(BigInt.asUintN(32, readProtoVarint(buf, state, mpEnd)))]; + if (src) msg.source = src; + } else if (mFn === 3 && mWt === 2) { + msg.prompt = readProtoString(buf, state, mpEnd); + } else if (mFn === 4 && mWt === 0) { + const nt = Number(BigInt.asUintN(32, readProtoVarint(buf, state, mpEnd))); + if (nt > 0) msg.numTokens = nt; + } else { + skipProtoField(buf, state, mWt, mpEnd); + } + } + state.off = mpEnd; + if (!messagePrompts) messagePrompts = []; + messagePrompts.push(msg); + } else { + skipProtoField(buf, state, wt, end); + } + } else if (fn === 3 && wt === 0) { + const enumStr = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); if (enumStr && !model) model = enumStr; } else if (fn === 4 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - usage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len)); - st.off += len; + usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 8 && wt === 2) { + if (includeBreakdown) { + const tdEnd = readSubEnd(buf, state, end); + const tool = {}; + while (state.off < tdEnd) { + const tTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, tdEnd))); + const tFn = tTag >>> 3; + const tWt = tTag & 7; + if (tFn === 1 && tWt === 2) tool.name = readProtoString(buf, state, tdEnd); + else if (tFn === 2 && tWt === 2) tool.description = readProtoString(buf, state, tdEnd); + else if (tFn === 3 && tWt === 2) tool.jsonSchemaString = readProtoString(buf, state, tdEnd); + else if (tFn === 6 && tWt === 2) tool.serverName = readProtoString(buf, state, tdEnd); + else skipProtoField(buf, state, tWt, tdEnd); + } + state.off = tdEnd; + if (!tools) tools = []; + tools.push(tool); + } else { + skipProtoField(buf, state, wt, end); + } } else if (fn === 9 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const csBuf = buf.subarray(st.off, st.off + len); - st.off += len; - const csSt = { off: 0 }; - while (csSt.off < csBuf.length) { - const csTag = Number(readProtoVarint(csBuf, csSt)); + const csEnd = readSubEnd(buf, state, end); + while (state.off < csEnd) { + const csTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, csEnd))); const csFn = csTag >>> 3; const csWt = csTag & 7; if (csFn === 10 && csWt === 2) { - const cwLen = Number(readProtoVarint(csBuf, csSt)); - contextWindowMetadata = decodeProtoContextWindowMeta( - csBuf.subarray(csSt.off, csSt.off + cwLen) + contextWindowMetadata = decodeProtoContextWindowMetaSlice( + buf, + state, + readSubEnd(buf, state, csEnd), + includeBreakdown ); - csSt.off += cwLen; } else { - skipProtoField(csBuf, csSt, csWt); + skipProtoField(buf, state, csWt, csEnd); } } + state.off = csEnd; } else if (fn === 11 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - timeToFirstToken = decodeProtoDurationStr(buf.subarray(st.off, st.off + len)); - st.off += len; + timeToFirstToken = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 12 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - streamingDuration = decodeProtoDurationStr(buf.subarray(st.off, st.off + len)); - st.off += len; + streamingDuration = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 16 && wt === 2) { + if (includeBreakdown) { + const psEnd = readSubEnd(buf, state, end); + const sec = {}; + while (state.off < psEnd) { + const pTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, psEnd))); + const pFn = pTag >>> 3; + const pWt = pTag & 7; + if (pFn === 1 && pWt === 2) sec.title = readProtoString(buf, state, psEnd); + else if (pFn === 2 && pWt === 2) sec.content = readProtoString(buf, state, psEnd); + else if (pFn === 6 && pWt === 0) { + const tt = PROTO_TOKEN_TYPES[Number(BigInt.asUintN(32, readProtoVarint(buf, state, psEnd)))]; + if (tt) sec.tokenType = tt; + } else if (pFn === 7 && pWt === 0) { + const ts = PROTO_TOKEN_SOURCES[Number(BigInt.asUintN(32, readProtoVarint(buf, state, psEnd)))]; + if (ts) sec.tokenSource = ts; + } else { + skipProtoField(buf, state, pWt, psEnd); + } + } + state.off = psEnd; + if (!promptSections) promptSections = []; + promptSections.push(sec); + } else { + skipProtoField(buf, state, wt, end); + } } else if (fn === 19 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - responseModel = buf.subarray(st.off, st.off + len).toString('utf8').trim(); - st.off += len; + responseModel = readProtoString(buf, state, end).trim(); } else if (fn === 20 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const [k, v] = decodeProtoMapStringEntry(buf.subarray(st.off, st.off + len)); - st.off += len; + const [k, v] = decodeProtoMapStringEntry(buf, state, readSubEnd(buf, state, end)); if (k && v) extraMeta[k] = v; } else if (fn === 21 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - modelDisplayName = buf.subarray(st.off, st.off + len).toString('utf8').trim(); - st.off += len; + modelDisplayName = readProtoString(buf, state, end).trim(); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } + state.off = end; if (extraMeta.model_enum) { - model = extraMeta.model_enum.trim(); - if (usage && !usage.model) { - usage.model = model; + const cleanEnum = extraMeta.model_enum.trim(); + if (cleanEnum && !/^MODEL_(?:UNSPECIFIED|UNKNOWN)$/i.test(cleanEnum) && cleanEnum !== '0') { + model = cleanEnum; + if (usage && !usage.model) { + usage.model = model; + } } } if (extraMeta.used_claude === 'true' && usage && !usage.apiProvider) { @@ -675,103 +1050,200 @@ function decodeProtoChatModelMeta(buf) { chatModel: { ...(model ? { model } : {}), ...(usage ? { usage } : {}), - ...(contextWindowMetadata ? { chatStartMetadata: { contextWindowMetadata } } : {}), + ...(contextWindowMetadata && Object.keys(contextWindowMetadata).length > 0 + ? { chatStartMetadata: { contextWindowMetadata } } + : {}), ...(timeToFirstToken ? { timeToFirstToken } : {}), ...(streamingDuration ? { streamingDuration } : {}), ...(responseModel ? { responseModel } : {}), ...(modelDisplayName ? { modelDisplayName } : {}), + ...(messagePrompts ? { messagePrompts } : {}), + ...(tools ? { tools } : {}), + ...(promptSections ? { promptSections } : {}), }, extraMeta, }; } -function decodeProtoGeneratorMeta(buf) { - const st = { off: 0 }; +function decodeProtoPlannerConfigSlice(buf, state, end) { + const pc = {}; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + const pm = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); + if (pm) pc.planModel = pm; + } else if (fn === 28 && wt === 2) { + const mn = readProtoString(buf, state, end).trim(); + if (mn) pc.modelName = mn; + } else if (fn === 60 && wt === 2) { + const pecEnd = readSubEnd(buf, state, end); + let execModel = ''; + while (state.off < pecEnd) { + const pTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, pecEnd))); + if ((pTag >>> 3) === 1 && (pTag & 7) === 0) { + execModel = decodeProtoModelEnumInt(readProtoVarint(buf, state, pecEnd)); + } else { + skipProtoField(buf, state, pTag & 7, pecEnd); + } + } + state.off = pecEnd; + if (execModel) pc.planExecuteConfig = { executionModel: execModel }; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return Object.keys(pc).length > 0 ? pc : null; +} + +function decodeProtoGeneratorMeta(rawBlob, includeBreakdown = true) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) return null; + const state = { off: 0 }; + const end = buf.length; const stepIndices = []; let chatDecoded = null; + let plannerConfig = null; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 2 && wt === 0) { - stepIndices.push(Number(readProtoVarint(buf, st))); + stepIndices.push(Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)))); } else if (fn === 2 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const end = st.off + len; - while (st.off < end) { - stepIndices.push(Number(readProtoVarint(buf, st))); + const pEnd = readSubEnd(buf, state, end); + while (state.off < pEnd) { + stepIndices.push(Number(BigInt.asUintN(32, readProtoVarint(buf, state, pEnd)))); } + state.off = pEnd; } else if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - chatDecoded = decodeProtoChatModelMeta(buf.subarray(st.off, st.off + len)); - st.off += len; + chatDecoded = decodeProtoChatModelMetaSlice( + buf, + state, + readSubEnd(buf, state, end), + includeBreakdown + ); + } else if (fn === 3 && wt === 2) { + plannerConfig = decodeProtoPlannerConfigSlice(buf, state, readSubEnd(buf, state, end)); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } - if (!chatDecoded) return null; + if (!chatDecoded && !plannerConfig) return null; return { stepIndices, - chatModel: chatDecoded.chatModel, - extraMeta: chatDecoded.extraMeta, + ...(chatDecoded ? { chatModel: chatDecoded.chatModel } : {}), + ...(plannerConfig ? { plannerConfig } : {}), + extraMeta: chatDecoded?.extraMeta || {}, }; } -function decodeProtoStepMeta(buf, fallbackIdx) { - const st = { off: 0 }; +function decodeProtoToolCallSlice(buf, state, end, includeArgs = true) { + const tc = {}; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + tc.id = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + tc.name = readProtoString(buf, state, end); + } else if (fn === 3 && wt === 2) { + if (includeArgs) { + tc.argumentsJson = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return tc; +} + +function decodeProtoStepMeta(rawBlob, fallbackIdx) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) { + return { sourceTrajectoryStepInfo: { stepIndex: fallbackIdx, cascadeId: '' } }; + } + const state = { off: 0 }; + const end = buf.length; + let createdAt = ''; let viewableAt = ''; let finishedGeneratingAt = ''; let completedAt = ''; + let startedAt = ''; let modelUsage = null; let generatorModel = ''; + let toolCall = null; + let retryInfos = null; + let toolSummary = ''; let stepIndex = fallbackIdx; + let sawStepIndex = false; + let originCascadeId = ''; - while (st.off < buf.length) { - const tag = Number(readProtoVarint(buf, st)); + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); const fn = tag >>> 3; const wt = tag & 7; if (fn === 1 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - createdAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; + createdAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 4 && wt === 2) { + toolCall = decodeProtoToolCallSlice(buf, state, readSubEnd(buf, state, end), true); } else if (fn === 6 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - viewableAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; + viewableAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 7 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - finishedGeneratingAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; - } else if (fn === 32 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - completedAt = decodeProtoTimestampIso(buf.subarray(st.off, st.off + len)); - st.off += len; + finishedGeneratingAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); + } else if (fn === 8 && wt === 2) { + completedAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 9 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - modelUsage = decodeProtoModelUsage(buf.subarray(st.off, st.off + len)); - st.off += len; + modelUsage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, end)); } else if (fn === 11 && wt === 0) { - generatorModel = decodeProtoModelEnumInt(readProtoVarint(buf, st)); + generatorModel = decodeProtoModelEnumInt(readProtoVarint(buf, state, end)); } else if (fn === 20 && wt === 2) { - const len = Number(readProtoVarint(buf, st)); - const siBuf = buf.subarray(st.off, st.off + len); - st.off += len; - const siSt = { off: 0 }; - while (siSt.off < siBuf.length) { - const siTag = Number(readProtoVarint(siBuf, siSt)); + const siEnd = readSubEnd(buf, state, end); + while (state.off < siEnd) { + const siTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, siEnd))); const siFn = siTag >>> 3; const siWt = siTag & 7; if (siFn === 2 && siWt === 0) { - stepIndex = Number(readProtoVarint(siBuf, siSt)); + stepIndex = Number(BigInt.asUintN(32, readProtoVarint(buf, state, siEnd))); + sawStepIndex = true; + } else if (siFn === 4 && siWt === 2) { + originCascadeId = readProtoString(buf, state, siEnd).trim().toLowerCase(); } else { - skipProtoField(siBuf, siSt, siWt); + skipProtoField(buf, state, siWt, siEnd); } } + state.off = siEnd; + } else if (fn === 28 && wt === 2) { + const riEnd = readSubEnd(buf, state, end); + const ri = {}; + while (state.off < riEnd) { + const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, riEnd))); + const rFn = rTag >>> 3; + const rWt = rTag & 7; + if (rFn === 2 && rWt === 2) { + ri.usage = decodeProtoModelUsageSlice(buf, state, readSubEnd(buf, state, riEnd)); + } else { + skipProtoField(buf, state, rWt, riEnd); + } + } + state.off = riEnd; + if (!retryInfos) retryInfos = []; + retryInfos.push(ri); + } else if (fn === 30 && wt === 2) { + toolSummary = readProtoString(buf, state, end); + } else if (fn === 32 && wt === 2) { + startedAt = decodeProtoTimestampSlice(buf, state, readSubEnd(buf, state, end)); } else { - skipProtoField(buf, st, wt); + skipProtoField(buf, state, wt, end); } } @@ -779,105 +1251,614 @@ function decodeProtoStepMeta(buf, fallbackIdx) { ...(createdAt ? { createdAt } : {}), ...(viewableAt ? { viewableAt } : {}), ...(finishedGeneratingAt ? { finishedGeneratingAt } : {}), - ...(completedAt ? { completedAt } : {}), + ...(completedAt ? { completedAt } : startedAt && !finishedGeneratingAt ? { completedAt: startedAt } : {}), + ...(startedAt ? { startedAt } : {}), ...(generatorModel ? { generatorModel } : {}), - sourceTrajectoryStepInfo: { stepIndex }, + ...(toolCall ? { toolCall } : {}), + ...(retryInfos ? { retryInfos } : {}), + ...(toolSummary ? { toolSummary } : {}), + sourceTrajectoryStepInfo: { + stepIndex: sawStepIndex ? stepIndex : fallbackIdx, + ...(originCascadeId ? { cascadeId: originCascadeId } : {}), + }, ...(modelUsage ? { modelUsage } : {}), }; } +function hasNonWhitespaceUtf8(buf, start, end) { + for (let i = start; i < end; i++) { + const b = buf[i]; + if (b !== 0x20 && b !== 0x09 && b !== 0x0a && b !== 0x0d) return true; + } + return false; +} + +function decodeProtoPlannerResponseSlice(buf, state, end, keepFullText) { + const pr = {}; + let hasText = false; + let toolCalls = null; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if ((fn === 1 || fn === 8) && wt === 2) { + if (keepFullText) { + const str = readProtoString(buf, state, end); + if (str) { + if (fn === 1) pr.response = str; + else pr.modifiedResponse = str; + } + } else { + const sEnd = readSubEnd(buf, state, end); + if (!hasText && hasNonWhitespaceUtf8(buf, state.off, sEnd)) { + hasText = true; + } + state.off = sEnd; + } + } else if ((fn === 3 || fn === 16) && wt === 2) { + if (keepFullText) { + const str = readProtoString(buf, state, end); + if (str) { + if (fn === 3) pr.thinking = str; + else pr.rawThinking = str; + } + } else { + skipProtoField(buf, state, wt, end); + } + } else if (fn === 7 && wt === 2) { + if (!toolCalls) toolCalls = []; + toolCalls.push(decodeProtoToolCallSlice(buf, state, readSubEnd(buf, state, end), keepFullText)); + } else if (fn === 11 && wt === 2) { + const dur = decodeProtoDurationSlice(buf, state, readSubEnd(buf, state, end)); + if (dur) pr.thinkingDuration = dur; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (!keepFullText && hasText) { + pr.response = '1'; + } + if (toolCalls) { + pr.toolCalls = toolCalls; + } + return pr; +} + +function decodeProtoUserInputSlice(buf, state, end) { + let query = ''; + let userResponse = ''; + const items = []; + let hasMedia = false; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + query = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + userResponse = readProtoString(buf, state, end); + } else if (fn === 3 && wt === 2) { + const itEnd = readSubEnd(buf, state, end); + let itemText = ''; + while (state.off < itEnd) { + const iTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, itEnd))); + if ((iTag >>> 3) === 1 && (iTag & 7) === 2) { + itemText = readProtoString(buf, state, itEnd); + } else { + skipProtoField(buf, state, iTag & 7, itEnd); + } + } + state.off = itEnd; + if (itemText) items.push({ text: itemText }); + } else if ((fn === 4 || fn === 5 || fn === 6) && wt === 2) { + const mEnd = readSubEnd(buf, state, end); + if (mEnd > state.off) hasMedia = true; + state.off = mEnd; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + + const primaryText = userResponse || query || items.map((x) => x.text).join('\n') || ''; + if (!primaryText && !hasMedia) return null; + return { + ...(primaryText ? { userResponse: primaryText } : {}), + ...(items.length > 0 ? { items } : {}), + ...(hasMedia ? { media: [{}] } : {}), + }; +} + +function decodeProtoInvokeSubagentSlice(buf, state, end) { + const subagents = []; + const results = []; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + const spec = decodeProtoSubagentSpecSlice(buf, state, readSubEnd(buf, state, end)); + subagents.push(spec || { typeName: '', role: '' }); + } else if (fn === 2 && wt === 2) { + const resEnd = readSubEnd(buf, state, end); + let conversationId = ''; + while (state.off < resEnd) { + const rTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd))); + if ((rTag >>> 3) === 1 && (rTag & 7) === 2) { + conversationId = readProtoString(buf, state, resEnd).trim().toLowerCase(); + } else { + skipProtoField(buf, state, rTag & 7, resEnd); + } + } + state.off = resEnd; + results.push({ conversationId }); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return { subagents, results }; +} + +function decodeProtoGenericStepInvokeSubagentSlice(buf, state, end) { + let invokeSubagent = null; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 2 && wt === 2) { + const resEnd = readSubEnd(buf, state, end); + while (state.off < resEnd) { + const resTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, resEnd))); + if ((resTag >>> 3) === 6 && (resTag & 7) === 2) { + const anyEnd = readSubEnd(buf, state, resEnd); + let typeUrl = ''; + let valStart = 0; + let valEnd = 0; + while (state.off < anyEnd) { + const aTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, anyEnd))); + if ((aTag >>> 3) === 1 && (aTag & 7) === 2) { + typeUrl = readProtoString(buf, state, anyEnd); + } else if ((aTag >>> 3) === 2 && (aTag & 7) === 2) { + valEnd = readSubEnd(buf, state, anyEnd); + valStart = state.off; + state.off = valEnd; + } else { + skipProtoField(buf, state, aTag & 7, anyEnd); + } + } + state.off = anyEnd; + if ( + valEnd > valStart && + (typeUrl.endsWith('/exa.cortex.core.tools.InvokeSubagent') || + typeUrl === 'exa.cortex.core.tools.InvokeSubagent') + ) { + invokeSubagent = decodeProtoInvokeSubagentSlice(buf, { off: valStart }, valEnd); + } + } else { + skipProtoField(buf, state, resTag & 7, resEnd); + } + } + state.off = resEnd; + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return invokeSubagent; +} + +function decodeProtoSelectiveStepPayload(rawBlob, { stepTypeNum, isInvokeSubagent, keepFullText }) { + const buf = toUint8Array(rawBlob); + if (!buf || buf.length === 0) return {}; + const state = { off: 0 }; + const end = buf.length; + const out = {}; + + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 19 && wt === 2 && stepTypeNum === 14) { + const ui = decodeProtoUserInputSlice(buf, state, readSubEnd(buf, state, end)); + if (ui) out.userInput = ui; + } else if (fn === 20 && wt === 2 && stepTypeNum === 15) { + out.plannerResponse = decodeProtoPlannerResponseSlice( + buf, + state, + readSubEnd(buf, state, end), + keepFullText + ); + } else if (fn === 140 && wt === 2 && isInvokeSubagent) { + const inv = decodeProtoGenericStepInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); + if (inv) out.invokeSubagent = inv; + } else if (fn === 143 && wt === 2 && isInvokeSubagent) { + out.invokeSubagent = decodeProtoInvokeSubagentSlice(buf, state, readSubEnd(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + return out; +} + +function isInvokeSubagentToolName(rawName) { + return /^(?:default_api:)?invoke_subagent$/i.test(String(rawName || '').trim()); +} + +function mapRunningGenericToolStepType(rawToolName) { + const name = String(rawToolName || '') + .trim() + .toLowerCase() + .replace(/^default_api:/, ''); + if (!name) return 'CORTEX_STEP_TYPE_GENERIC'; + if (name === 'invoke_subagent') return 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + if (name === 'run_command') return 'CORTEX_STEP_TYPE_RUN_COMMAND'; + if (name === 'command_status') return 'CORTEX_STEP_TYPE_COMMAND_STATUS'; + if (name === 'send_command_input') return 'CORTEX_STEP_TYPE_SEND_COMMAND_INPUT'; + if ( + name === 'read_file' || + name === 'view_file' || + name === 'view_file_outline' || + name === 'view_code_item' + ) { + return 'CORTEX_STEP_TYPE_VIEW_FILE'; + } + if ( + name === 'edit_file' || + name === 'write_file' || + name === 'write_to_file' || + name === 'replace_file_content' || + name === 'multi_replace_file_content' + ) { + return 'CORTEX_STEP_TYPE_CODE_ACTION'; + } + if (name === 'grep_search' || name === 'ripgrep') return 'CORTEX_STEP_TYPE_GREP_SEARCH'; + if (name === 'find_by_name') return 'CORTEX_STEP_TYPE_FIND'; + if (name === 'list_dir') return 'CORTEX_STEP_TYPE_LIST_DIRECTORY'; + if (name === 'search_web') return 'CORTEX_STEP_TYPE_SEARCH_WEB'; + if (name === 'read_url_content' || name === 'fetch_url') return 'CORTEX_STEP_TYPE_READ_URL_CONTENT'; + if (name === 'ask_question') return 'CORTEX_STEP_TYPE_ASK_QUESTION'; + if (name === 'call_mcp_tool' || name.startsWith('mcp_') || name.startsWith('mcp-')) { + return 'CORTEX_STEP_TYPE_MCP_TOOL'; + } + if (name === 'list_resources') return 'CORTEX_STEP_TYPE_LIST_RESOURCES'; + if (name === 'read_resource') return 'CORTEX_STEP_TYPE_READ_RESOURCE'; + return 'CORTEX_STEP_TYPE_GENERIC'; +} + +function cleanShortPromptTitle(rawText, maxChars = 80) { + const withoutTags = String(rawText || '') + .replace(/[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '') + .replace(/[\s\S]*$/i, '') + .replace(/[\s\S]*$/i, ''); + const reqMatches = [...withoutTags.matchAll(/([\s\S]*?)<\/USER_REQUEST>/gi)]; + const target = reqMatches.length > 0 ? reqMatches[reqMatches.length - 1][1] : withoutTags; + const singleLine = target.replace(/\s+/g, ' ').trim(); + if (!singleLine) return ''; + return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`; +} + +function hasContextBreakdownPayload(chat) { + if (!chat || typeof chat !== 'object') return false; + return Boolean( + chat.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown?.groups?.length || + chat.promptSections?.length || + chat.tools?.length || + chat.messagePrompts?.length + ); +} + /** - * 从单个会话的本地 SQLite 数据库(`/conversations/.db`)提取步骤元数据与生成器元数据。 - * 严格只查询 `steps.metadata` 与 `gen_metadata.data`,不加载 `step_payload` 大字段。 + * 从单个会话的本地 SQLite 数据库(`/conversations/.db`)提取步骤元数据、按需载荷与生成器元数据。 + * 自动过滤分叉/旁路提问克隆自父会话的步骤(`originCid !== cascadeId`),并按需解码末尾上下文拆解。 * * @param {string} dbFilePath - * @returns {{ - * steps: Array<{ idx: number, type: string, status: string, metadata: object }>, - * generatorMetadata: Array<{ stepIndices: number[], chatModel: object }>, - * rootConversationId: string, - * parentConversationId: string - * } | null} + * @param {{ cascadeId?: string, isRunning?: boolean }} [options={}] */ -export function readLocalSqliteTrajectory(dbFilePath) { +export function readLocalSqliteTrajectory(dbFilePath, options = {}) { if (!dbFilePath || !existsSync(dbFilePath)) return null; const DatabaseSync = getNodeSqliteDatabaseSync(); if (!DatabaseSync) return null; - let db = null; - try { - db = new DatabaseSync(dbFilePath, { readOnly: true }); - const genRows = db.prepare('SELECT idx, data FROM gen_metadata ORDER BY idx ASC').all(); - const generatorMetadata = []; - const genByStep = new Map(); - let rootConversationId = ''; - let parentConversationId = ''; - - for (const row of genRows || []) { - if (!row?.data) continue; - try { - const decoded = decodeProtoGeneratorMeta(Buffer.from(row.data)); - if (!decoded) continue; - const gmItem = { - stepIndices: decoded.stepIndices, - chatModel: decoded.chatModel, - }; - generatorMetadata.push(gmItem); - for (const sIdx of decoded.stepIndices) { - genByStep.set(Number(sIdx), gmItem); - } - if (!rootConversationId && decoded.extraMeta?.root_cascade_id) { - rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase(); - } - if (!parentConversationId && decoded.extraMeta?.parent_cascade_id) { - parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase(); - } - } catch { - // 忽略单条损坏的 generatorMetadata - } - } - - const stepRows = db - .prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx ASC') - .all(); - const steps = []; - for (const row of stepRows || []) { - const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : steps.length; - const type = decodeProtoStepTypeEnum(row?.step_type); - const status = decodeProtoStepStatusEnum(row?.status); - let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } }; - if (row?.metadata && row.metadata.byteLength > 0) { - try { - metadata = decodeProtoStepMeta(Buffer.from(row.metadata), idx); - } catch { - // 忽略单步元数据解码异常 - } - } - const stepIdx = metadata.sourceTrajectoryStepInfo?.stepIndex ?? idx; - const gm = genByStep.get(Number(stepIdx)); - if (metadata.modelUsage && gm?.chatModel?.model && !metadata.modelUsage.model) { - metadata.modelUsage.model = gm.chatModel.model; - } - steps.push({ idx, type, status, metadata }); - } - - if (steps.length === 0 && generatorMetadata.length === 0) { - return null; - } - return { - steps, - generatorMetadata, - rootConversationId, - parentConversationId, - }; - } catch { - return null; - } finally { - if (db) { - try { - db.close(); - } catch { - // 忽略关闭异常 - } + let normCid = String(options?.cascadeId || '') + .trim() + .toLowerCase(); + if (!normCid) { + const stem = basename(dbFilePath).replace(/\.db$/i, '').trim().toLowerCase(); + if (UUID_FILE_RE.test(stem)) { + normCid = stem; } } + const isRunning = Boolean(options?.isRunning); + + try { + return withReadOnlySqliteDb(dbFilePath, (db) => { + let trajectoryType = 0; + try { + const metaRow = db + .prepare( + 'SELECT trajectory_id, cascade_id, trajectory_type, source FROM trajectory_meta LIMIT 1' + ) + .get(); + if (!normCid && metaRow?.cascade_id) { + normCid = String(metaRow.cascade_id).trim().toLowerCase(); + } + trajectoryType = Number(metaRow?.trajectory_type || 0); + } catch { + // 兼容未包含 trajectory_meta 表的精简库 + } + const isSideQuestion = trajectoryType === 22; + + let trajectoryMetadata = { + createdAt: '', + parentConversationId: '', + rootConversationId: '', + nestingDepth: 0, + subagentSpec: null, + agentScript: null, + }; + try { + const blobRow = db + .prepare("SELECT data FROM trajectory_metadata_blob WHERE id = 'main' LIMIT 1") + .get(); + const blobBuf = toUint8Array(blobRow?.data); + if (blobBuf && blobBuf.length > 0) { + trajectoryMetadata = decodeProtoTrajectoryMetadataSlice( + blobBuf, + { off: 0 }, + blobBuf.length + ); + } + } catch { + // 兼容未包含 trajectory_metadata_blob 表的库 + } + + let forkParentConversationId = ''; + try { + const refRows = db.prepare('SELECT idx, data FROM parent_references ORDER BY idx ASC').all(); + for (const refRow of refRows || []) { + const refBuf = toUint8Array(refRow?.data); + if (!refBuf || refBuf.length === 0) continue; + const st = { off: 0 }; + let refCid = ''; + while (st.off < refBuf.length) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(refBuf, st, refBuf.length))); + if ((tag >>> 3) === 6 && (tag & 7) === 2) { + refCid = readProtoString(refBuf, st, refBuf.length).trim().toLowerCase(); + } else { + skipProtoField(refBuf, st, tag & 7, refBuf.length); + } + } + if (refCid && (!normCid || refCid !== normCid)) { + forkParentConversationId = refCid; + } + } + } catch { + // 兼容未包含 parent_references 表的库 + } + + const genRows = db.prepare('SELECT idx, data FROM gen_metadata ORDER BY idx ASC').all(); + const ownGenRecords = []; + let rootConversationId = trajectoryMetadata.rootConversationId || ''; + let parentConversationId = trajectoryMetadata.parentConversationId || ''; + + for (const row of genRows || []) { + if (!row?.data) continue; + try { + const decoded = decodeProtoGeneratorMeta(row.data, false); + if (!decoded) continue; + const gmCid = String(decoded.extraMeta?.cascade_id || '') + .trim() + .toLowerCase(); + if (gmCid && normCid && gmCid !== normCid) { + // 过滤旁路提问或会话分叉从父会话克隆来的历史生成器记录 + continue; + } + if (!rootConversationId && decoded.extraMeta?.root_cascade_id) { + rootConversationId = String(decoded.extraMeta.root_cascade_id).trim().toLowerCase(); + } + if (!parentConversationId && decoded.extraMeta?.parent_cascade_id) { + parentConversationId = String(decoded.extraMeta.parent_cascade_id).trim().toLowerCase(); + } + ownGenRecords.push({ rawData: row.data, gm: decoded }); + } catch { + // 忽略单条损坏的 generatorMetadata + } + } + + if (ownGenRecords.length > 0) { + // 从末尾向前定位最近一条包含完整上下文拆解(tokenBreakdown / promptSections / tools / messagePrompts)的记录, + // 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成。 + for (let i = ownGenRecords.length - 1; i >= 0; i--) { + const rec = ownGenRecords[i]; + try { + const fullDecoded = decodeProtoGeneratorMeta(rec.rawData, true); + if (fullDecoded) { + rec.gm = fullDecoded; + if (hasContextBreakdownPayload(fullDecoded.chatModel)) { + break; + } + } + } catch { + // 保留轻量版本 + } + } + } + + const generatorMetadata = []; + const genByStep = new Map(); + for (const { gm } of ownGenRecords) { + const gmItem = { + stepIndices: gm.stepIndices, + ...(gm.chatModel ? { chatModel: gm.chatModel } : {}), + ...(gm.plannerConfig ? { plannerConfig: gm.plannerConfig } : {}), + }; + generatorMetadata.push(gmItem); + for (const sIdx of gm.stepIndices) { + genByStep.set(Number(sIdx), gmItem); + } + } + + const stepRows = db + .prepare('SELECT idx, step_type, status, metadata FROM steps ORDER BY idx ASC') + .all(); + const ownStepRecords = []; + for (const row of stepRows || []) { + const idx = Number.isFinite(Number(row?.idx)) ? Number(row.idx) : ownStepRecords.length; + const stepTypeNum = Number(row?.step_type || 0); + const statusNum = Number(row?.status || 0); + let metadata = { sourceTrajectoryStepInfo: { stepIndex: idx } }; + if (row?.metadata && row.metadata.byteLength > 0) { + try { + metadata = decodeProtoStepMeta(row.metadata, idx); + } catch { + // 忽略单步元数据解码异常 + } + } + const originCid = String(metadata.sourceTrajectoryStepInfo?.cascadeId || '') + .trim() + .toLowerCase(); + if (originCid && normCid && originCid !== normCid) { + // 过滤克隆自父会话的步骤,防止双倍重复计费 + continue; + } + ownStepRecords.push({ idx, stepTypeNum, statusNum, metadata }); + } + + const runningTailStart = isRunning + ? Math.max(0, ownStepRecords.length - 16) + : ownStepRecords.length; + + const payloadIndices = []; + try { + for (let i = 0; i < ownStepRecords.length; i++) { + const rec = ownStepRecords[i]; + const inRunningTail = isRunning && i >= runningTailStart; + const isInvSub = + rec.stepTypeNum === 127 || + (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + if ( + rec.stepTypeNum === 14 || + rec.stepTypeNum === 15 || + isInvSub || + (inRunningTail && (rec.stepTypeNum !== 132 || !rec.metadata?.toolCall?.argumentsJson)) + ) { + payloadIndices.push(rec.idx); + } + } + } catch { + // 忽略索引构建异常 + } + + const payloadByIdx = new Map(); + if (payloadIndices.length > 0) { + try { + for (let off = 0; off < payloadIndices.length; off += SQLITE_IN_CHUNK_SIZE) { + const batch = payloadIndices.slice(off, off + SQLITE_IN_CHUNK_SIZE); + const placeholders = batch.map(() => '?').join(','); + const pRows = db + .prepare(`SELECT idx, step_payload FROM steps WHERE idx IN (${placeholders})`) + .all(...batch); + for (const pRow of pRows || []) { + if (pRow?.step_payload && pRow.step_payload.byteLength > 0) { + payloadByIdx.set(Number(pRow.idx), pRow.step_payload); + } + } + } + } catch { + // 兼容不含 step_payload 列的旧表 + } + } + + let firstOwnUserPrompt = ''; + const steps = []; + for (let i = 0; i < ownStepRecords.length; i++) { + const rec = ownStepRecords[i]; + const inRunningTail = isRunning && i >= runningTailStart; + const isInvSub = + rec.stepTypeNum === 127 || + (rec.stepTypeNum === 132 && isInvokeSubagentToolName(rec.metadata?.toolCall?.name)); + + let type = ''; + if (isInvSub) { + type = 'CORTEX_STEP_TYPE_INVOKE_SUBAGENT'; + } else if (rec.stepTypeNum === 132 && inRunningTail) { + type = mapRunningGenericToolStepType(rec.metadata?.toolCall?.name); + } else { + type = decodeProtoStepTypeEnum(rec.stepTypeNum); + } + const status = decodeProtoStepStatusEnum(rec.statusNum); + const metadata = rec.metadata; + const stepIdx = metadata.sourceTrajectoryStepInfo?.stepIndex ?? rec.idx; + const gm = genByStep.get(Number(stepIdx)); + if (metadata.modelUsage && gm?.chatModel?.model && !metadata.modelUsage.model) { + metadata.modelUsage.model = gm.chatModel.model; + } + + const stepObj = { idx: rec.idx, type, status, metadata }; + const rawPayload = payloadByIdx.get(rec.idx); + if (rawPayload) { + try { + const decodedPayload = decodeProtoSelectiveStepPayload(rawPayload, { + stepTypeNum: rec.stepTypeNum, + isInvokeSubagent: isInvSub, + keepFullText: inRunningTail, + }); + if (decodedPayload.userInput) { + stepObj.userInput = decodedPayload.userInput; + if (!firstOwnUserPrompt && decodedPayload.userInput.userResponse) { + firstOwnUserPrompt = cleanShortPromptTitle( + decodedPayload.userInput.userResponse, + 80 + ); + } + } + if (decodedPayload.plannerResponse) { + stepObj.plannerResponse = decodedPayload.plannerResponse; + } + if (decodedPayload.invokeSubagent) { + stepObj.invokeSubagent = decodedPayload.invokeSubagent; + } + } catch { + // 忽略单步载荷解析异常 + } + } + steps.push(stepObj); + } + + if (steps.length === 0 && generatorMetadata.length === 0 && !isSideQuestion) { + return null; + } + + const mergedMetadata = { + ...trajectoryMetadata, + parentConversationId: trajectoryMetadata.parentConversationId || parentConversationId, + rootConversationId: trajectoryMetadata.rootConversationId || rootConversationId, + }; + + return { + cascadeId: normCid, + numTotalSteps: steps.length, + rawTableStepCount: stepRows.length, + trajectoryType, + isSideQuestion, + forkParentConversationId, + firstOwnUserPrompt, + steps, + generatorMetadata, + rootConversationId: mergedMetadata.rootConversationId, + parentConversationId: mergedMetadata.parentConversationId, + trajectory: { + metadata: mergedMetadata, + steps, + generatorMetadata, + }, + }; + }); + } catch { + return null; + } } diff --git a/sidecars/panel/backend/cli-statusline-config.mjs b/sidecars/panel/backend/cli-statusline-config.mjs index 9aea9d7..3571cfd 100644 --- a/sidecars/panel/backend/cli-statusline-config.mjs +++ b/sidecars/panel/backend/cli-statusline-config.mjs @@ -16,8 +16,16 @@ import { homedir } from 'node:os'; import { delimiter, dirname, join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs'; - -const CLI_STATUS_THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i; +import { + classifyCacheTier, + classifySpeedTier, + classifyStepCostTier, + classifyTtftTier, + formatCompactCapsuleCost, + formatCompactCapsuleTtft, + formatCompactTokens, + resolveCapsuleQuotaSlotPct, +} from '../shared/telemetry-display-rules.mjs'; // 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符) const SGR_RESET = '\x1b[0m'; @@ -388,165 +396,42 @@ export function ensureCliStatusLineConfigured({ // --------------------------------------------------------------------------- function cliStatusSpeedSgr(tokPerSec) { - if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) { - return SGR_FG_MUTED; - } - const v = Number(tokPerSec); - if (v >= 60) return SGR_FG_GOOD; - if (v >= 35) return SGR_FG_INFO; - if (v >= 20) return SGR_FG_WARN; - return SGR_FG_DANGER; + const tier = classifySpeedTier(tokPerSec); + if (tier === 'good') return SGR_FG_GOOD; + if (tier === 'info') return SGR_FG_INFO; + if (tier === 'warn') return SGR_FG_WARN; + if (tier === 'danger') return SGR_FG_DANGER; + return SGR_FG_MUTED; } function cliStatusCacheSgr(cacheHitPct, promptTokens = null) { - if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) return SGR_FG_MUTED; - const v = Number(cacheHitPct); - if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) return SGR_FG_MUTED; - if (v >= 85) return SGR_FG_GOOD; - if (v >= 65) return SGR_FG_INFO; - if (v >= 30) return SGR_FG_WARN; - return SGR_FG_DANGER; + const tier = classifyCacheTier(cacheHitPct, promptTokens); + if (tier === 'good') return SGR_FG_GOOD; + if (tier === 'info') return SGR_FG_INFO; + if (tier === 'warn') return SGR_FG_WARN; + if (tier === 'danger') return SGR_FG_DANGER; + return SGR_FG_MUTED; } function cliStatusCostSgr(costUsd) { - if (costUsd == null || !Number.isFinite(Number(costUsd))) return SGR_FG_NORMAL; - const v = Number(costUsd); - if (v >= 0.3) return SGR_FG_DANGER; - if (v >= 0.15) return SGR_FG_WARN; + const tier = classifyStepCostTier(costUsd); + if (tier === 'danger') return SGR_FG_DANGER; + if (tier === 'warn') return SGR_FG_WARN; return SGR_FG_NORMAL; } function cliStatusTtftSgr(ttftSec) { - if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) { - return SGR_FG_MUTED; - } - const v = Number(ttftSec); - if (v >= 30) return SGR_FG_DANGER; - if (v >= 18) return SGR_FG_WARN; + const tier = classifyTtftTier(ttftSec); + if (tier === 'muted') return SGR_FG_MUTED; + if (tier === 'danger') return SGR_FG_DANGER; + if (tier === 'warn') return SGR_FG_WARN; return SGR_FG_NORMAL; } -function cliFormatCompactCost(costUsd) { - if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--'; - const val = Math.max(0, Number(costUsd)); - if (val === 0) return '$0.00'; - if (val < 0.001) return '<$0.001'; - if (val < 1) return `$${val.toFixed(3)}`; - if (val < 100) return `$${val.toFixed(2)}`; - return `$${Math.round(val)}`; -} - -function cliFormatCompactTtft(ttftSec) { - if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; - const val = Number(ttftSec); - if (val < 1) return `${val.toFixed(2)}s`; - if (val < 100) return `${val.toFixed(1)}s`; - return `${Math.round(val)}s`; -} - -function cliFormatTokens(num) { - const n = Number(num || 0); - if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; - if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; - if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; - return String(Math.round(n)); -} - -function cliResolveQuotaPct(quotas, slotKey) { - if (!quotas || typeof quotas !== 'object') return null; - const pools = Array.isArray(quotas.pools) ? quotas.pools : []; - const activePool = quotas.activePool || null; - const weekly = quotas.weekly || null; - - if (slotKey === 'quota_auto') { - const candidates = []; - if (activePool && Number.isFinite(Number(activePool.remainingPct))) { - candidates.push(Number(activePool.remainingPct)); - } - if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { - candidates.push(Number(activePool.weeklyRemainingPct)); - } - if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { - candidates.push(Number(weekly.remainingPct)); - } - if (!candidates.length && pools.length > 0) { - for (const p of pools) { - if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); - if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { - candidates.push(Number(p.weeklyRemainingPct)); - } - } - } - if (!candidates.length) return null; - return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); - } - - const isClaude = slotKey.startsWith('claude_'); - const isWeekly = slotKey.endsWith('_weekly'); - let rawPct = null; - - if (isClaude) { - const claudePool = - pools.find((p) => p?.poolKey === 'Claude & GPT') || - pools.find((p) => - CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || '')) - ); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; - if (cand != null && Number.isFinite(Number(cand))) { - rawPct = Number(cand); - } else if ( - activePool && - CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) - ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; - if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); - } - } else { - const stdGemini = - pools.find((p) => p?.poolKey === 'Gemini') || - pools.find( - (p) => - /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && - !/carbon|argon/i.test(String(p?.poolKey || '')) - ); - const geminiFamilyPools = pools.filter((p) => - /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) - ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; - if (primaryCand != null && Number.isFinite(Number(primaryCand))) { - rawPct = Number(primaryCand); - } else { - const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) - .filter((v) => v != null && Number.isFinite(Number(v))) - .map(Number); - if (familyVals.length > 0) { - rawPct = Math.min(...familyVals); - } else if ( - activePool && - !CLI_STATUS_THIRD_PARTY_FAMILY_RE.test( - String(activePool.family || activePool.poolLabel || '') - ) - ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; - if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); - } - if ( - rawPct == null && - isWeekly && - weekly && - !CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(weekly.poolFamily || '')) && - weekly.remainingPct != null && - Number.isFinite(Number(weekly.remainingPct)) - ) { - rawPct = Number(weekly.remainingPct); - } - } - } - - if (rawPct == null || !Number.isFinite(rawPct)) return null; - return Math.max(0, Math.min(100, Math.round(rawPct))); -} +const cliFormatCompactCost = formatCompactCapsuleCost; +const cliFormatCompactTtft = formatCompactCapsuleTtft; +const cliFormatTokens = formatCompactTokens; +const cliResolveQuotaPct = resolveCapsuleQuotaSlotPct; /** * 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。 diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 83dcc04..8e8a430 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -12,54 +12,9 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSy import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs'; +import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs'; import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs'; -import { - DEFAULT_HOVER_MODULES, - DEFAULT_OVERVIEW_METRICS, - DEFAULT_OVERVIEW_MODULES, - DEFAULT_POPOVER_WIDTH, - DEFAULT_SETTINGS_SCHEMA, - DEFAULT_STEP_TABLE_COLUMNS, - DEFAULT_STEP_TOKEN_COMBO_FORMAT, - DEFAULT_TOPBAR_SLOTS, - FONT_SCALE_KEYS, - MAX_POPOVER_WIDTH, - MAX_TOPBAR_SLOTS, - MIN_POPOVER_WIDTH, - MIN_TOPBAR_SLOTS, - MODEL_DISPLAY_MODES, - ORCHESTRATOR_ID_MODES, - OVERVIEW_METRIC_KEYS, - OVERVIEW_MODULE_KEYS, - PLUGIN_UPDATE_MODES, - POPOVER_WIDTH_MODES, - STEP_TABLE_COLUMN_KEYS, - SUPPORTED_LANGUAGES, - THEME_ACCENT_KEYS, - TOPBAR_SLOT_KEYS, - WINDOW_MOUNT_MODES, - createDefaultSettingsObject, - normalizeFontScale, - normalizeFullSettings, - normalizeHoverModules, - normalizeLanguageSetting, - normalizeModelDisplayMode, - normalizeOrchestratorIdMode, - normalizeOverviewMetrics, - normalizeOverviewModules, - normalizePluginUpdateMode, - normalizePopoverWidth, - normalizePopoverWidthMode, - normalizeStandalonePort, - normalizeStepTableColumns, - normalizeStepTokenComboFormat, - normalizeThemeAccent, - normalizeTopbarCapsuleSlots, - normalizeWeeklyLimitMode, - normalizeWindowMountMode, - parseStepTokenComboSegments, -} from './settings-schema.mjs'; +import { normalizeFullSettings } from './settings-schema.mjs'; export { DEFAULT_HOVER_MODULES, @@ -75,17 +30,12 @@ export { MAX_TOPBAR_SLOTS, MIN_POPOVER_WIDTH, MIN_TOPBAR_SLOTS, - MODEL_DISPLAY_MODES, - ORCHESTRATOR_ID_MODES, OVERVIEW_METRIC_KEYS, OVERVIEW_MODULE_KEYS, - PLUGIN_UPDATE_MODES, - POPOVER_WIDTH_MODES, STEP_TABLE_COLUMN_KEYS, SUPPORTED_LANGUAGES, THEME_ACCENT_KEYS, TOPBAR_SLOT_KEYS, - WINDOW_MOUNT_MODES, createDefaultSettingsObject, normalizeFontScale, normalizeFullSettings, @@ -272,6 +222,55 @@ export const DEFAULT_DOWNLOAD_URL = export const DEFAULT_ARCHIVE_FALLBACK_URL = `https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`; +/** + * 检测当前插件目录是否关联了非官方自定义 GitHub Fork 远端(如二次开发分支)。 + * 命中自定义 Fork 时保留上游价格目录热同步,但将插件版本号与更新包地址锚定至用户自己的 Fork,避免误报更新。 + * + * @returns {string} 自定义 Fork 的 `owner/repo`,未命中或为官方仓库时返回 `''` + */ +export function detectCustomGitForkRepo() { + try { + const dotGitPath = join(PLUGIN_ROOT, '.git'); + if (!existsSync(dotGitPath)) return ''; + let gitConfigPath = join(dotGitPath, 'config'); + if (!existsSync(gitConfigPath)) { + const ptrText = readFileSync(dotGitPath, 'utf8'); + const m = typeof ptrText === 'string' && ptrText.match(/^gitdir:\s*(.+)$/im); + if (m) { + const gitDir = m[1].trim(); + const commonDirFile = join(gitDir, 'commondir'); + if (existsSync(commonDirFile)) { + const relCommon = String(readFileSync(commonDirFile, 'utf8') || '').trim(); + gitConfigPath = join(gitDir, relCommon, 'config'); + } else { + gitConfigPath = join(gitDir, 'config'); + } + } + } + if (!existsSync(gitConfigPath)) return ''; + const cfg = readFileSync(gitConfigPath, 'utf8'); + if (typeof cfg !== 'string' || !cfg) return ''; + const originBlock = cfg.match(/\[remote\s+"origin"\]([\s\S]*?)(?:\r?\n\[|$)/i); + if (!originBlock) return ''; + const urlMatch = originBlock[1].match(/^\s*url\s*=\s*(.+)$/im); + if (!urlMatch) return ''; + const rawUrl = urlMatch[1].trim(); + const ghMatch = rawUrl.match(/github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i); + if (!ghMatch) return ''; + const repo = ghMatch[1]; + const lower = repo.toLowerCase(); + if ( + lower === OFFICIAL_GITHUB_REPO.toLowerCase() || + LEGACY_GITHUB_REPOS.some((r) => r.toLowerCase() === lower) + ) { + return ''; + } + return repo; + } catch { + return ''; + } +} + /** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */ export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000; export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000; @@ -359,20 +358,22 @@ export function computeRuntimeCodeVersion() { join(HERE, 'bridge-daemon.mjs'), join(HERE, 'mcp-entry.mjs'), join(HERE, 'cli-statusline.mjs'), - join(HERE, 'speed-metrics.mjs'), + join(HERE, 'trajectory-metrics.mjs'), LOCAL_CATALOG_FILE, ]; - const backendDir = join(HERE, 'backend'); - try { - if (existsSync(backendDir)) { - for (const name of readdirSync(backendDir)) { - if (name.endsWith('.mjs') || name.endsWith('.js')) { - candidates.push(join(backendDir, name)); + for (const subDir of ['shared', 'backend']) { + const absDir = join(HERE, subDir); + try { + if (existsSync(absDir)) { + for (const name of readdirSync(absDir)) { + if (name.endsWith('.mjs') || name.endsWith('.js')) { + candidates.push(join(absDir, name)); + } } } + } catch { + // 忽略目录列举异常 } - } catch { - // 忽略目录列举异常 } for (const file of candidates) { try { @@ -397,7 +398,10 @@ let initialCacheMigrated = loadedTrajectoryCache !== undefined && !isPlainObject(loadedTrajectoryCache); -const safeCacheEntries = []; +/** + * 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }` + */ +const trajectoryCache = Object.create(null); if (isPlainObject(loadedTrajectoryCache)) { for (const [id, entry] of Object.entries(loadedTrajectoryCache)) { if (!id || !isPlainObject(entry)) { @@ -424,27 +428,118 @@ if (isPlainObject(loadedTrajectoryCache)) { break; } } - safeCacheEntries.push([ - id, - { - ...entry, - steps: finalSteps, - }, - ]); + trajectoryCache[id] = { ...entry, steps: finalSteps }; + } +} + +export function getCachedTrajectory(cascadeId) { + return trajectoryCache[cascadeId]; +} + +export function listCachedTrajectoryEntries() { + return Object.entries(trajectoryCache); +} + +export function setCachedTrajectory(cascadeId, entry) { + trajectoryCache[cascadeId] = entry; +} + +export function removeCachedTrajectory(cascadeId) { + delete trajectoryCache[cascadeId]; +} + +/** + * 缓存状态与外部深层统计缓存 Memo。 + * 运行中会话采用 30 秒节流落盘(转入 IDLE、重建缓存或进程退出时立即刷盘),消除高频文件替换开销。 + */ +export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000; + +const cacheState = { + needsSave: initialCacheMigrated, + lastSavedAtMs: 0, + flushTimer: null, +}; + +export function hasPendingTrajectoryCacheSave() { + return cacheState.needsSave; +} + +function cancelPendingCacheFlushTimer() { + if (cacheState.flushTimer) { + try { + clearTimeout(cacheState.flushTimer); + } catch { + // 忽略沙箱无 clearTimeout 异常 + } + cacheState.flushTimer = null; } } /** - * 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }` + * 立即将当前内存态 `trajectoryCache` 原子刷入磁盘并清理挂起定时器。 + * + * @returns {boolean} */ -export const trajectoryCache = Object.fromEntries(safeCacheEntries); +export function flushTrajectoryCacheNow() { + cancelPendingCacheFlushTimer(); + const ok = saveJson(CACHE_FILE, trajectoryCache); + cacheState.needsSave = !ok; + if (ok) { + cacheState.lastSavedAtMs = Date.now(); + } + return ok; +} /** - * 缓存状态与外部深层统计缓存 Memo。 + * 按当前是否存在运行中会话决定立即写盘还是 30 秒节流延迟写盘。 + * 默认单元测试沙箱(`lsRuntimeEndpoint.addr === 'test.invalid'`)同步落盘以保持断言确定性。 + * + * @param {{ hasRunningSessions?: boolean, allowThrottleInTest?: boolean }} [options={}] */ -export const cacheState = { - needsSave: initialCacheMigrated, -}; +export function persistTrajectoryCacheIfNeeded({ + hasRunningSessions = false, + allowThrottleInTest = false, +} = {}) { + if ( + (lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest) || + typeof setTimeout !== 'function' + ) { + flushTrajectoryCacheNow(); + return; + } + const nowMs = Date.now(); + const elapsedMs = nowMs - (cacheState.lastSavedAtMs || 0); + if ( + !hasRunningSessions || + cacheState.lastSavedAtMs === 0 || + elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS + ) { + flushTrajectoryCacheNow(); + return; + } + cacheState.needsSave = true; + if (!cacheState.flushTimer) { + const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs); + const timer = setTimeout(() => { + cacheState.flushTimer = null; + if (cacheState.needsSave) { + flushTrajectoryCacheNow(); + } + }, delayMs); + if (timer && typeof timer.unref === 'function') { + timer.unref(); + } + cacheState.flushTimer = timer; + } +} + +if (typeof process !== 'undefined' && typeof process?.once === 'function') { + process.once('exit', () => { + if (cacheState.needsSave) { + flushTrajectoryCacheNow(); + } + }); +} export const externalDeepStatsMemo = { sig: '', @@ -454,6 +549,10 @@ export const externalDeepStatsMemo = { export const localSummaryMemo = { sig: '', byId: new Map(), + available: false, + summariesObj: {}, + sideQuestionParents: {}, + byRootsKey: new Map(), }; /** 并发请求去重表(防止同一参数并发重复拉取)。 */ @@ -498,23 +597,31 @@ export const pluginUpdateState = { /** * 清空内存态轨迹缓存、外部深层统计 Memo 与配额摘要短期缓存,并将磁盘缓存重置为空对象。 + * 空缓存落盘成功后再清理内存,写入失败时可继续使用内存数据并重试。 * * @returns {boolean} 是否成功写回空白缓存文件 */ export function clearRuntimeCaches() { + if (!saveJson(CACHE_FILE, {})) return false; + cancelPendingCacheFlushTimer(); for (const key of Object.keys(trajectoryCache)) { delete trajectoryCache[key]; } cacheState.needsSave = false; + cacheState.lastSavedAtMs = 0; externalDeepStatsMemo.sig = ''; externalDeepStatsMemo.convos.clear(); localSummaryMemo.sig = ''; localSummaryMemo.byId.clear(); + localSummaryMemo.available = false; + localSummaryMemo.summariesObj = {}; + localSummaryMemo.sideQuestionParents = {}; + localSummaryMemo.byRootsKey.clear(); quotaSummaryCache.ts = 0; quotaSummaryCache.lastAttemptTs = 0; quotaSummaryCache.accountName = ''; quotaSummaryCache.accountGeneration += 1; quotaSummaryCache.data = null; quotaSummaryCache.error = null; - return saveJson(CACHE_FILE, {}); + return true; } diff --git a/sidecars/panel/backend/context-windows.mjs b/sidecars/panel/backend/context-windows.mjs index 9372224..7341de1 100644 --- a/sidecars/panel/backend/context-windows.mjs +++ b/sidecars/panel/backend/context-windows.mjs @@ -1,5 +1,7 @@ /** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */ +import { CONTEXT_WINDOWS_GLOBAL_KEY } from '../shared/window-bridge-protocol.mjs'; + export function isContextWindowModelId(value) { return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) && value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN'; @@ -77,7 +79,7 @@ export function getContextWindowGroups(models) { })); const capacity = Math.min(...members.map((member) => member.capacity)); if (!options.length && capacity) { - for (const tokens of new Set([128000, 256000, 512000, 768000, 900000, capacity])) { + for (const tokens of new Set([128000, 256000, 384000, 512000, 768000, 900000, capacity])) { if (tokens <= capacity && !options.some(({ name }) => name === String(tokens))) { options.push({ name: String(tokens), tokens }); } @@ -115,14 +117,24 @@ export function resolveContextWindowRules(models, preferences) { } // 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。 -export async function syncHostContextWindows(rules, bootId) { - const key = '__AGUsageMonitorContextWindows'; +export async function syncHostContextWindows( + rules, + bootId, + key = '__AGUsageMonitorContextWindows', + fallbackRules = {} +) { let state = window[key]; const appConfig = window.__APP_CONFIG__; const csrfToken = appConfig?.csrfToken; - if (!Object.keys(rules).length || !csrfToken || appConfig.isRemoteControl) { + const hasPrefs = Boolean(rules && Object.keys(rules).length > 0); + const safeFallback = + fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules) + ? fallbackRules + : {}; + const hasFallback = Object.keys(safeFallback).length > 0; + if (!hasPrefs || appConfig?.isRemoteControl || (!csrfToken && !hasFallback)) { state?.dispose(); - return; + return { attached: false, ruleCount: 0 }; } if (state && (state.bootId !== bootId || !state.isAttached?.())) { state.dispose(); @@ -131,6 +143,8 @@ export async function syncHostContextWindows(rules, bootId) { if (!state) { const servicePath = '/exa.language_server_pb.LanguageServerService/'; const sendPath = servicePath + 'SendUserCascadeMessage'; + const startPath = servicePath + 'StartCascade'; + const isTargetProcedure = (p) => p === sendPath || p === startPath; const nativeFetch = window.fetch; const wsProto = window.WebSocket?.prototype; const nativeSend = wsProto?.send; @@ -155,11 +169,20 @@ export async function syncHostContextWindows(rules, bootId) { } function rewriteBody(body, contentType) { - if (contentType === 'application/json' && typeof body === 'string') { - const json = JSON.parse(body); - if (updatePayload(json)) return JSON.stringify(json); - } else if (contentType === 'application/grpc-web+json' && body instanceof Uint8Array && - body.length >= 5 && body[0] === 0) { + if (contentType === 'application/json') { + if (typeof body === 'string') { + const json = JSON.parse(body); + if (updatePayload(json)) return JSON.stringify(json); + } else if (body instanceof Uint8Array) { + const json = JSON.parse(decoder.decode(body)); + if (updatePayload(json)) return encoder.encode(JSON.stringify(json)); + } + } else if ( + (contentType === 'application/grpc-web+json' || contentType === 'application/connect+json') && + body instanceof Uint8Array && + body.length >= 5 && + body[0] === 0 + ) { const header = new DataView(body.buffer, body.byteOffset, body.byteLength); if (header.getUint32(1) !== body.length - 5) return body; const json = JSON.parse(decoder.decode(body.subarray(5))); @@ -176,9 +199,15 @@ export async function syncHostContextWindows(rules, bootId) { function fetchWithContextWindow(input, init) { let nextInit = init; try { - if (typeof input === 'string' && init?.method === 'POST') { - const url = new URL(input, window.location.href); - if (url.origin === window.location.origin && url.pathname === sendPath) { + const rawUrl = + typeof input === 'string' + ? input + : input instanceof URL + ? input.href + : ''; + if (rawUrl && init?.method === 'POST') { + const url = new URL(rawUrl, window.location.href); + if (url.origin === window.location.origin && isTargetProcedure(url.pathname)) { const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim(); const body = rewriteBody(init.body, type); if (body !== init.body) nextInit = { ...init, body }; @@ -195,13 +224,13 @@ export async function syncHostContextWindows(rules, bootId) { function sendWithContextWindow(data) { let nextData = data; try { - if (typeof data === 'string' && data.includes(sendPath)) { + if (typeof data === 'string' && (data.includes(sendPath) || data.includes(startPath))) { const url = new URL(this.url); const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; if (url.protocol === protocol && url.host === window.location.host && url.pathname === '/connect-websocket') { const frame = JSON.parse(data); - if (frame.type === 'start' && frame.stream === false && frame.procedure === sendPath && + if (frame.type === 'start' && frame.stream === false && isTargetProcedure(frame.procedure) && updatePayload(frame.payload)) { nextData = JSON.stringify(frame); } @@ -215,7 +244,7 @@ export async function syncHostContextWindows(rules, bootId) { state = window[key] = { bootId, - rules: {}, + rules: { ...safeFallback }, serviceUrl: window.location.origin + servicePath, isAttached() { return (typeof nativeFetch !== 'function' || window.fetch === fetchWithContextWindow) && @@ -233,12 +262,18 @@ export async function syncHostContextWindows(rules, bootId) { if (typeof nativeSend === 'function') wsProto.send = sendWithContextWindow; } state.preferences = rules; + state.fallbackRules = safeFallback; clearTimeout(state.timer); state.timer = setTimeout(() => state.dispose(), 15000); - // App 和 IDE 同时打开时,各窗口只使用自身宿主上报的档位。 + if (!csrfToken) { + state.rules = { ...safeFallback }; + return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length }; + } + + // App 和 IDE 同时打开时,各窗口优先使用自身宿主上报的档位;若窗口内查询异常则回退后端预解析规则。 if (state.csrfToken !== csrfToken || Date.now() >= state.refreshAt) { - if (state.csrfToken !== csrfToken) state.rules = {}; + if (state.csrfToken !== csrfToken) state.rules = { ...safeFallback }; state.csrfToken = csrfToken; state.refreshAt = Date.now() + 10000; state.status = (async () => { @@ -259,19 +294,25 @@ export async function syncHostContextWindows(rules, bootId) { ]); const userStatus = status?.userStatus; const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs; + if (!Array.isArray(configs)) return null; return getContextWindowModels(configs, catalog?.response?.models); } catch { - return []; + return null; } })(); } const status = state.status; const models = await status; - if (window[key] !== state || state.status !== status) return; - state.rules = resolveContextWindowRules(models, state.preferences); + if (window[key] !== state || state.status !== status) { + return { attached: Boolean(state?.isAttached?.()), ruleCount: Object.keys(state?.rules || {}).length }; + } + state.rules = Array.isArray(models) + ? resolveContextWindowRules(models, state.preferences) + : { ...state.fallbackRules }; + return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length }; } -export function createContextWindowSyncExpression(preferences, bootId) { +export function createContextWindowSyncExpression(preferences, bootId, fallbackRules = {}) { return `(() => { ${isContextWindowModelId.toString()} ${isContextWindowSettingId.toString()} @@ -280,6 +321,6 @@ export function createContextWindowSyncExpression(preferences, bootId) { ${getContextWindowGroups.toString()} ${resolveContextWindowOption.toString()} ${resolveContextWindowRules.toString()} - return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}); + return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})}); })()`; } diff --git a/sidecars/panel/backend/desktop-launcher-config.mjs b/sidecars/panel/backend/desktop-launcher-config.mjs new file mode 100644 index 0000000..57b10a1 --- /dev/null +++ b/sidecars/panel/backend/desktop-launcher-config.mjs @@ -0,0 +1,995 @@ +/** + * @fileoverview Antigravity Desktop 2.33.0+ 跨平台启动入口自动补齐与一键带参重拉控制器。 + * + * 背景: + * Antigravity Desktop (`Antigravity.exe` / `Antigravity.app` / `antigravity`) 自 `2.33.0` 起 + * 默认不再于启动时开启 `--remote-debugging-port=0`,且独立 Electron 桌面端不读取 VS Code 系的 `argv.json`。 + * + * 本模块在不触碰任何宿主二进制与 `app.asar` 的前提下,提供两层无感恢复能力: + * 1. 日常全自动层 (`ensureDesktopLaunchEntriesConfigured`): + * - Windows:自动为当前用户的桌面(含 OneDrive 重定向桌面)、开始菜单、任务栏固定图标、启动文件夹中的 + * `Antigravity.lnk` 快捷方式及已存在的 `HKCU\...\Run` 自启项补齐 `--remote-debugging-port=0`; + * - Linux:自动在 `~/.local/share/applications/antigravity.desktop`(必要时自系统目录复制)与 + * `~/.config/autostart/antigravity.desktop` 的 `Exec=` 中补齐 `--remote-debugging-port=0`; + * - 当用户切回「仅侧边栏」且无上下文窗口覆写时,可干净移除本插件托管的 `--remote-debugging-port=0`,绝不触碰用户自定义端口; + * 2. 当下裸启动会话一键重拉层 (`triggerDesktopHostRelaunch`): + * - Windows 通过 `Shell.Application` (`explorer.exe` 进程外 COM) 脱离宿主 Job Object 托管生命周期, + * macOS / Linux 通过独立会话 `nohup` 脱离进程组,自动退出系统托盘常驻实例、清理陈旧 `DevToolsActivePort` + * 并以纯净桌面环境变量追加 `--remote-debugging-port=0` 重新拉起宿主客户端。 + */ + +import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { basename, dirname, join } from 'node:path'; +import { DATA_DIR, lsRuntimeEndpoint } from './config.mjs'; + +export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0'; + +const REMOTE_DEBUG_ANY_RE = /(?:^|\s)--remote-debugging-port(?:=|\s|$)/i; +const REMOTE_DEBUG_MANAGED_ZERO_RE = /(?:^|\s+)--remote-debugging-port=(?:"0"|'0'|0)(?=\s|$)/gi; + +/** + * 在命令行参数字符串中幂等补齐或移除托管的 `--remote-debugging-port=0`,保留用户自定义的其它参数或自定义端口。 + * + * @param {unknown} rawArgs + * @param {{ enabled?: boolean }} [options] + * @returns {{ changed: boolean, configured: boolean, alreadyConfigured?: boolean, removed?: boolean, args: string }} + */ +export function ensureRemoteDebugFlagInArgs(rawArgs, { enabled = true } = {}) { + const current = String(rawArgs ?? '').trim(); + if (enabled) { + if (REMOTE_DEBUG_ANY_RE.test(current)) { + return { + changed: false, + configured: true, + alreadyConfigured: true, + args: current, + }; + } + const nextArgs = current + ? `${current} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : REMOTE_DEBUG_LAUNCH_FLAG; + return { + changed: true, + configured: true, + args: nextArgs, + }; + } + + if (!REMOTE_DEBUG_MANAGED_ZERO_RE.test(current)) { + REMOTE_DEBUG_MANAGED_ZERO_RE.lastIndex = 0; + return { + changed: false, + configured: REMOTE_DEBUG_ANY_RE.test(current), + args: current, + }; + } + REMOTE_DEBUG_MANAGED_ZERO_RE.lastIndex = 0; + const stripped = current.replace(REMOTE_DEBUG_MANAGED_ZERO_RE, ' ').replace(/\s{2,}/g, ' ').trim(); + return { + changed: stripped !== current, + configured: REMOTE_DEBUG_ANY_RE.test(stripped), + removed: stripped !== current, + args: stripped, + }; +} + +/** + * 解析并无损修补 Windows `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` 自启命令行字符串。 + * 严格仅匹配目标可执行文件名为 `Antigravity.exe` 的项(排除 `Antigravity IDE.exe` 及无关程序)。 + * + * @param {unknown} rawValue + * @param {{ enabled?: boolean }} [options] + * @returns {{ matched: boolean, changed: boolean, configured: boolean, value: string }} + */ +export function patchWindowsRunRegistryCommand(rawValue, { enabled = true } = {}) { + const raw = String(rawValue ?? '').trim(); + if (!raw) { + return { matched: false, changed: false, configured: false, value: raw }; + } + const m = raw.match(/^\s*(?:"([^"]+)"|([^\s"]+))([\s\S]*)$/); + if (!m) { + return { matched: false, changed: false, configured: false, value: raw }; + } + const exePath = String(m[1] || m[2] || '').trim(); + const exeLeaf = exePath.split(/[\\/]/).pop() || ''; + if (exeLeaf.toLowerCase() !== 'antigravity.exe') { + return { matched: false, changed: false, configured: false, value: raw }; + } + const quotedExe = m[1] ? `"${exePath}"` : /\s/.test(exePath) ? `"${exePath}"` : exePath; + const patchedArgs = ensureRemoteDebugFlagInArgs(m[3] || '', { enabled }); + const nextValue = patchedArgs.args ? `${quotedExe} ${patchedArgs.args}` : quotedExe; + return { + matched: true, + changed: nextValue !== raw, + configured: patchedArgs.configured, + value: nextValue, + }; +} + +/** + * 修补 Linux XDG `.desktop` 文件文本中的 `Exec=` 启动行(仅作用于 `antigravity` 桌面端,不修改 `antigravity-ide`)。 + * + * @param {string} rawText + * @param {{ enabled?: boolean }} [options] + * @returns {{ matched: boolean, changed: boolean, configured: boolean, text: string }} + */ +export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) { + if (typeof rawText !== 'string' || !rawText.trim()) { + return { matched: false, changed: false, configured: false, text: String(rawText || '') }; + } + const eol = rawText.includes('\r\n') ? '\r\n' : '\n'; + const lines = rawText.split(/\r?\n/); + let matched = false; + let changed = false; + let configured = false; + + const nextLines = lines.map((line) => { + const execMatch = line.match(/^(\s*Exec\s*=\s*)(.+)$/); + if (!execMatch) return line; + const prefix = execMatch[1]; + const cmdBody = execMatch[2].trim(); + const binMatch = cmdBody.match(/^(?:"([^"]+)"|'([^']+)'|([^\s"']+))([\s\S]*)$/); + if (!binMatch) return line; + const rawBin = String(binMatch[1] || binMatch[2] || binMatch[3] || ''); + const leaf = (rawBin.split('/').pop() || '').toLowerCase(); + if (leaf !== 'antigravity') { + return line; + } + matched = true; + const binToken = binMatch[1] + ? `"${binMatch[1]}"` + : binMatch[2] + ? `'${binMatch[2]}'` + : binMatch[3]; + const rest = String(binMatch[4] || '').trim(); + + if (enabled) { + if (REMOTE_DEBUG_ANY_RE.test(rest)) { + configured = true; + return line; + } + configured = true; + changed = true; + const fieldCodeMatch = rest.match(/^(.*?)\s*(%[fFuUdDnNickvm](?:\s+%[fFuUdDnNickvm])*)\s*$/); + if (fieldCodeMatch) { + const beforeCodes = fieldCodeMatch[1].trim(); + const codes = fieldCodeMatch[2].trim(); + const mid = beforeCodes + ? `${beforeCodes} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : REMOTE_DEBUG_LAUNCH_FLAG; + return `${prefix}${binToken} ${mid} ${codes}`; + } + return rest + ? `${prefix}${binToken} ${rest} ${REMOTE_DEBUG_LAUNCH_FLAG}` + : `${prefix}${binToken} ${REMOTE_DEBUG_LAUNCH_FLAG}`; + } + + const stripped = ensureRemoteDebugFlagInArgs(rest, { enabled: false }); + configured = configured || stripped.configured; + if (!stripped.changed) return line; + changed = true; + return stripped.args ? `${prefix}${binToken} ${stripped.args}` : `${prefix}${binToken}`; + }); + + return { + matched, + changed, + configured, + text: changed ? nextLines.join(eol) : rawText, + }; +} + +/** + * 清理 Sidecar / MCP 子进程继承的宿主会话私有环境变量,确保重拉后的客户端运行于纯净桌面上下文。 + * + * @param {Record} [baseEnv=process.env] + * @returns {Record} + */ +export function buildSanitizedDesktopRelaunchEnv(baseEnv = process.env) { + const clean = {}; + for (const [key, val] of Object.entries(baseEnv || {})) { + if (val === undefined || val === null) continue; + if ( + /^(?:ANTIGRAVITY_|CHROME_DEVTOOLS_MCP_|USAGE_MONITOR_|ELECTRON_RUN_AS_NODE$|NODE_OPTIONS$)/i.test( + key + ) + ) { + continue; + } + clean[key] = String(val); + } + return clean; +} + +/** + * 自动定位本机 Antigravity Desktop(或 IDE)主程序路径(优先从 `ANTIGRAVITY_AGENTAPI_EXE` 向上反推,回退标准安装目录)。 + * + * @param {{ + * env?: Record, + * platform?: string, + * homeDir?: string, + * existsFn?: (p: string) => boolean, + * }} [options] + * @returns {{ found: boolean, kind: 'desktop'|'ide'|'', executablePath: string, appBundlePath: string }} + */ +export function resolveDesktopHostExecutable({ + env = process.env, + platform = process.platform, + homeDir = homedir(), + existsFn = existsSync, +} = {}) { + const safeExists = (p) => { + try { + return Boolean(p && existsFn(p)); + } catch { + return false; + } + }; + + const hintPaths = [ + String(env?.USAGE_MONITOR_HOST_EXE || '').trim(), + String(env?.ANTIGRAVITY_AGENTAPI_EXE || '').trim(), + String(env?.CHROME_DEVTOOLS_MCP_JS || '').trim(), + ].filter(Boolean); + + for (const rawHint of hintPaths) { + if (platform === 'darwin') { + const appIdx = rawHint.toLowerCase().indexOf('.app/'); + const bundleCand = + appIdx >= 0 + ? rawHint.slice(0, appIdx + 4) + : rawHint.toLowerCase().endsWith('.app') + ? rawHint + : ''; + if (bundleCand && safeExists(bundleCand)) { + const isIde = /antigravity\s*ide\.app$/i.test(bundleCand); + const macBin = join( + bundleCand, + 'Contents', + 'MacOS', + isIde ? 'Antigravity IDE' : 'Antigravity' + ); + return { + found: true, + kind: isIde ? 'ide' : 'desktop', + executablePath: safeExists(macBin) ? macBin : bundleCand, + appBundlePath: bundleCand, + }; + } + } + + if (platform === 'win32' && /\.exe$/i.test(rawHint) && !/language_server/i.test(rawHint)) { + if (safeExists(rawHint)) { + const isIde = /antigravity\s*ide\.exe$/i.test(rawHint); + return { + found: true, + kind: isIde ? 'ide' : 'desktop', + executablePath: rawHint, + appBundlePath: '', + }; + } + } + + let cur = rawHint; + for (let depth = 0; depth < 8 && cur && dirname(cur) !== cur; depth += 1) { + const base = basename(cur).toLowerCase(); + if (base === 'resources') { + const installRoot = dirname(cur); + if (platform === 'win32') { + const desktopExe = join(installRoot, 'Antigravity.exe'); + if (safeExists(desktopExe)) { + return { found: true, kind: 'desktop', executablePath: desktopExe, appBundlePath: '' }; + } + const ideExe = join(installRoot, 'Antigravity IDE.exe'); + if (safeExists(ideExe)) { + return { found: true, kind: 'ide', executablePath: ideExe, appBundlePath: '' }; + } + } else if (platform === 'linux') { + for (const binName of ['antigravity', 'Antigravity']) { + const linuxExe = join(installRoot, binName); + if (safeExists(linuxExe)) { + return { found: true, kind: 'desktop', executablePath: linuxExe, appBundlePath: '' }; + } + } + } + } + cur = dirname(cur); + } + } + + if (platform === 'win32') { + const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local'); + const programFiles = env?.ProgramFiles || 'C:\\Program Files'; + const winCandidates = [ + join(localAppData, 'Programs', 'Antigravity', 'Antigravity.exe'), + join(programFiles, 'Antigravity', 'Antigravity.exe'), + join(localAppData, 'Antigravity', 'Antigravity.exe'), + ]; + for (const cand of winCandidates) { + if (safeExists(cand)) { + return { found: true, kind: 'desktop', executablePath: cand, appBundlePath: '' }; + } + } + } else if (platform === 'darwin') { + const macBundles = [ + join(homeDir, 'Applications', 'Antigravity.app'), + '/Applications/Antigravity.app', + ]; + for (const bundlePath of macBundles) { + if (safeExists(bundlePath)) { + const macBin = join(bundlePath, 'Contents', 'MacOS', 'Antigravity'); + return { + found: true, + kind: 'desktop', + executablePath: safeExists(macBin) ? macBin : bundlePath, + appBundlePath: bundlePath, + }; + } + } + } else { + const linuxCandidates = [ + '/opt/Antigravity/antigravity', + '/opt/antigravity/antigravity', + '/usr/share/antigravity/antigravity', + '/usr/bin/antigravity', + join(homeDir, '.local', 'bin', 'antigravity'), + ]; + for (const cand of linuxCandidates) { + if (safeExists(cand)) { + return { found: true, kind: 'desktop', executablePath: cand, appBundlePath: '' }; + } + } + } + + return { found: false, kind: '', executablePath: '', appBundlePath: '' }; +} + +async function runLauncherExecFile(file, args, options = {}) { + const cpMod = await import('node:child_process'); + const execFileFn = cpMod.execFile || cpMod.default?.execFile; + if (typeof execFileFn !== 'function') { + throw new Error('child_process.execFile unavailable'); + } + return new Promise((resolve, reject) => { + execFileFn( + file, + args, + { + windowsHide: true, + timeout: options.timeoutMs || 8000, + maxBuffer: 1024 * 1024, + env: options.env || process.env, + }, + (err, stdout) => { + if (err) { + reject(err); + return; + } + resolve(String(stdout || '')); + } + ); + }); +} + +async function spawnDetachedProcess(file, args, options = {}) { + const cpMod = await import('node:child_process'); + const spawnFn = cpMod.spawn || cpMod.default?.spawn; + if (typeof spawnFn !== 'function') { + throw new Error('child_process.spawn unavailable'); + } + const child = spawnFn(file, args, { + detached: true, + stdio: 'ignore', + windowsHide: true, + cwd: options.cwd || undefined, + env: options.env || process.env, + }); + child.unref?.(); + return { pid: Number(child?.pid || 0) }; +} + +function writeTextFileAtomically(filePath, content, fsOps) { + const { mkdirFn, writeFn, renameFn, unlinkFn } = fsOps; + mkdirFn(dirname(filePath), { recursive: true }); + const tmpPath = `${filePath}.tmp-${process.pid}`; + try { + writeFn(tmpPath, content, 'utf8'); + renameFn(tmpPath, filePath); + } catch { + try { + unlinkFn(tmpPath); + } catch { + // 忽略临时文件清理异常 + } + writeFn(filePath, content, 'utf8'); + } +} + +const WIN_SHORTCUT_PROVISION_PS = ` +$ErrorActionPreference = 'Stop' +$enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1' +$updated = New-Object System.Collections.Generic.List[string] +$configured = New-Object System.Collections.Generic.List[string] +$ws = New-Object -ComObject WScript.Shell +$userProgramsDir = [Environment]::GetFolderPath('Programs') + +$scanSpecs = @( + @{ Dir = [Environment]::GetFolderPath('Desktop'); Recurse = $false; IsCommon = $false }, + @{ Dir = $userProgramsDir; Recurse = $true; IsCommon = $false }, + @{ Dir = [Environment]::GetFolderPath('StartMenu'); Recurse = $false; IsCommon = $false }, + @{ Dir = [Environment]::GetFolderPath('Startup'); Recurse = $false; IsCommon = $false }, + @{ Dir = (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar'); Recurse = $false; IsCommon = $false }, + @{ Dir = [Environment]::GetFolderPath('CommonDesktopDirectory'); Recurse = $false; IsCommon = $true }, + @{ Dir = [Environment]::GetFolderPath('CommonPrograms'); Recurse = $true; IsCommon = $true } +) + +$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase) +foreach ($spec in $scanSpecs) { + $dir = [string]$spec.Dir + if (-not $dir -or -not (Test-Path -LiteralPath $dir)) { continue } + $items = @() + try { + if ($spec.Recurse) { + $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -Recurse -Depth 2 -ErrorAction SilentlyContinue) + } else { + $items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue) + } + } catch { continue } + + foreach ($item in $items) { + $lnkPath = [string]$item.FullName + if (-not $seen.Add($lnkPath)) { continue } + try { + $sc = $ws.CreateShortcut($lnkPath) + $target = [string]$sc.TargetPath + if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue } + $curArgs = [string]$sc.Arguments + if ($enableFlag) { + if ($curArgs -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($lnkPath) + continue + } + $nextArgs = ($curArgs.Trim() + ' --remote-debugging-port=0').Trim() + try { + $sc.Arguments = $nextArgs + $sc.Save() + $updated.Add($lnkPath) + $configured.Add($lnkPath) + } catch { + if ($spec.IsCommon -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir)) { + $fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath)) + if (-not (Test-Path -LiteralPath $fallbackLnk)) { + try { + $uSc = $ws.CreateShortcut($fallbackLnk) + $uSc.TargetPath = $target + $uSc.Arguments = $nextArgs + if ($sc.WorkingDirectory) { $uSc.WorkingDirectory = $sc.WorkingDirectory } + if ($sc.IconLocation) { $uSc.IconLocation = $sc.IconLocation } + if ($sc.Description) { $uSc.Description = $sc.Description } + $uSc.Save() + $updated.Add($fallbackLnk) + $configured.Add($fallbackLnk) + } catch {} + } + } + } + } else { + $stripped = ([regex]::Replace($curArgs, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + if ($stripped -ne $curArgs.Trim()) { + try { + $sc.Arguments = $stripped + $sc.Save() + $updated.Add($lnkPath) + } catch {} + } + if ($stripped -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add($lnkPath) + } + } + } catch {} + } +} + +$runKey = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' +if (Test-Path -LiteralPath $runKey) { + try { + $regItem = Get-Item -LiteralPath $runKey -ErrorAction SilentlyContinue + if ($regItem) { + foreach ($valName in $regItem.GetValueNames()) { + $rawCmd = [string]$regItem.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + if (-not $rawCmd) { continue } + if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue } + $exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] } + $restPart = [string]$Matches[3] + if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue } + $quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate } + if ($enableFlag) { + if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add("HKCU:Run:$valName") + continue + } + $nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim() + $nextVal = "$quotedExe $nextRest" + Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue + $updated.Add("HKCU:Run:$valName") + $configured.Add("HKCU:Run:$valName") + } else { + $strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim() + $nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe } + if ($nextVal -ne $rawCmd.Trim()) { + Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue + $updated.Add("HKCU:Run:$valName") + } + if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') { + $configured.Add("HKCU:Run:$valName") + } + } + } + } + } catch {} +} + +[pscustomobject]@{ + ok = $true + updatedPaths = @($updated) + configuredPaths = @($configured) +} | ConvertTo-Json -Compress +`.trim(); + +/** + * 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run`、Linux `.desktop`)中的 `--remote-debugging-port=0`。 + * + * @param {{ + * enabled?: boolean, + * env?: Record, + * platform?: string, + * homeDir?: string, + * execFileFn?: ((file: string, args: string[], opts?: object) => Promise)|null, + * fsOps?: { + * existsFn?: typeof existsSync, + * readFn?: typeof readFileSync, + * writeFn?: typeof writeFileSync, + * mkdirFn?: typeof mkdirSync, + * renameFn?: typeof renameSync, + * unlinkFn?: typeof unlinkSync, + * }|null, + * allowInTest?: boolean, + * }} [options] + */ +export async function ensureDesktopLaunchEntriesConfigured({ + enabled = true, + env = process.env, + platform = process.platform, + homeDir = homedir(), + execFileFn = null, + fsOps = null, + allowInTest = false, +} = {}) { + if (lsRuntimeEndpoint.addr === 'test.invalid' && !allowInTest) { + return { + checked: false, + updated: false, + alreadyConfigured: false, + updatedPaths: [], + configuredPaths: [], + reason: 'test_sandbox_skipped', + }; + } + + const ops = { + existsFn: fsOps?.existsFn || existsSync, + readFn: fsOps?.readFn || readFileSync, + writeFn: fsOps?.writeFn || writeFileSync, + mkdirFn: fsOps?.mkdirFn || mkdirSync, + renameFn: fsOps?.renameFn || renameSync, + unlinkFn: fsOps?.unlinkFn || unlinkSync, + }; + + if (platform === 'win32') { + try { + const runner = execFileFn || runLauncherExecFile; + const out = await runner( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_SHORTCUT_PROVISION_PS], + { + timeoutMs: 9000, + env: { + ...env, + AGY_LAUNCH_ENABLED: enabled ? '1' : '0', + }, + } + ); + const trimmed = String(out || '').trim(); + const jsonLine = trimmed.split(/\r?\n/).reverse().find((l) => l.trim().startsWith('{')) || ''; + const parsed = jsonLine ? JSON.parse(jsonLine) : null; + const updatedPaths = Array.isArray(parsed?.updatedPaths) + ? parsed.updatedPaths.map(String).filter(Boolean) + : []; + const configuredPaths = Array.isArray(parsed?.configuredPaths) + ? parsed.configuredPaths.map(String).filter(Boolean) + : []; + return { + checked: true, + updated: updatedPaths.length > 0, + alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0, + configured: configuredPaths.length > 0, + updatedPaths, + configuredPaths, + }; + } catch (err) { + return { + checked: true, + updated: false, + alreadyConfigured: false, + configured: false, + updatedPaths: [], + configuredPaths: [], + reason: 'win_shortcut_error', + error: err?.message || String(err), + }; + } + } + + if (platform === 'linux') { + const dataHome = env?.XDG_DATA_HOME || join(homeDir, '.local', 'share'); + const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); + const userDesktopFile = join(dataHome, 'applications', 'antigravity.desktop'); + const systemDesktopFiles = [ + '/usr/share/applications/antigravity.desktop', + '/usr/local/share/applications/antigravity.desktop', + ]; + const autostartDesktopFile = join(configHome, 'autostart', 'antigravity.desktop'); + + const updatedPaths = []; + const configuredPaths = []; + + try { + let baseUserText = ''; + if (ops.existsFn(userDesktopFile)) { + baseUserText = String(ops.readFn(userDesktopFile, 'utf8') || ''); + } else if (enabled) { + const sysSource = systemDesktopFiles.find((p) => ops.existsFn(p)); + if (sysSource) { + baseUserText = String(ops.readFn(sysSource, 'utf8') || ''); + } + } + if (baseUserText) { + const patched = patchLinuxDesktopEntryText(baseUserText, { enabled }); + if (patched.changed) { + writeTextFileAtomically(userDesktopFile, patched.text, ops); + updatedPaths.push(userDesktopFile); + } + if (patched.configured) { + configuredPaths.push(userDesktopFile); + } + } + + if (ops.existsFn(autostartDesktopFile)) { + const autoRaw = String(ops.readFn(autostartDesktopFile, 'utf8') || ''); + const patchedAuto = patchLinuxDesktopEntryText(autoRaw, { enabled }); + if (patchedAuto.changed) { + writeTextFileAtomically(autostartDesktopFile, patchedAuto.text, ops); + updatedPaths.push(autostartDesktopFile); + } + if (patchedAuto.configured) { + configuredPaths.push(autostartDesktopFile); + } + } + + return { + checked: true, + updated: updatedPaths.length > 0, + alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0, + configured: configuredPaths.length > 0, + updatedPaths, + configuredPaths, + }; + } catch (err) { + return { + checked: true, + updated: false, + alreadyConfigured: false, + configured: false, + updatedPaths, + configuredPaths, + reason: 'linux_desktop_error', + error: err?.message || String(err), + }; + } + } + + // macOS `.app` 包具有 Apple 代码签名,不修改签名目录,交由一键重拉 (`open -a ... --args`) 处理 + return { + checked: true, + updated: false, + alreadyConfigured: false, + configured: false, + updatedPaths: [], + configuredPaths: [], + reason: 'macos_app_bundle_signed', + }; +} + +/** + * 当静态环境变量与默认安装目录均未命中(如用户自定义安装至 D:/E: 盘且 Sidecar 未继承 `ANTIGRAVITY_AGENTAPI_EXE`)时, + * 直接从当前正在运行的宿主进程动态反查主程序绝对路径。 + */ +async function discoverRunningHostExecutable({ platform = process.platform, execFileFn = null } = {}) { + const runner = execFileFn || runLauncherExecFile; + if (platform === 'win32') { + try { + const ps = + "@(Get-Process -Name 'Antigravity','Antigravity IDE' -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -First 1) | ForEach-Object { [pscustomobject]@{ path = [string]$_.Path; name = [string]$_.ProcessName } } | ConvertTo-Json -Compress"; + const out = await runner( + 'powershell.exe', + ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ps], + { timeoutMs: 4000 } + ); + const trimmed = String(out || '').trim(); + if (trimmed && trimmed.startsWith('{')) { + const parsed = JSON.parse(trimmed); + const exePath = String(parsed?.path || '').trim(); + if (exePath) { + const isIde = /ide/i.test(String(parsed?.name || '')) || /antigravity\s*ide\.exe$/i.test(exePath); + return { + found: true, + kind: isIde ? 'ide' : 'desktop', + executablePath: exePath, + appBundlePath: '', + }; + } + } + } catch { + // 忽略动态进程探测异常 + } + } else if (platform === 'darwin') { + try { + const out = await runner( + 'osascript', + ['-e', 'POSIX path of (path to application "Antigravity")'], + { timeoutMs: 3000 } + ); + const bundlePath = String(out || '').trim().replace(/\/+$/, ''); + if (bundlePath && /\.app$/i.test(bundlePath)) { + return { + found: true, + kind: 'desktop', + executablePath: bundlePath, + appBundlePath: bundlePath, + }; + } + } catch { + // 忽略 AppleScript 探测异常 + } + } + return { found: false, kind: '', executablePath: '', appBundlePath: '' }; +} + +function psSingleQuote(val) { + return `'${String(val ?? '').replace(/'/g, "''")}'`; +} + +/** + * 构建 Windows 脱离宿主 Job Object 的隐藏重拉内层脚本(写入临时 UTF-8 BOM `.ps1` 文件后交由 `explorer.exe` 拉起,规避 `ShellExecute` 参数长度上限)。 + * + * @param {string} executablePath + * @param {string[]} stalePortFiles + * @param {'desktop'|'ide'|''} kind + * @returns {string} + */ +export function buildWindowsRelaunchInnerScript(executablePath, stalePortFiles = [], kind = 'desktop') { + const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'; + const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : []) + .map((p) => String(p || '').trim()) + .filter(Boolean) + .map(psSingleQuote) + .join(', '); + + return ` +Start-Sleep -Milliseconds 480 +$exe = ${psSingleQuote(executablePath)} +$procName = ${psSingleQuote(procName)} +$staleList = @(${portLiterals}) +$mySid = (Get-Process -Id $PID).SessionId + +if (-not $exe -or -not (Test-Path -LiteralPath $exe)) { + $livePath = Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $mySid -and $_.Path } | Select-Object -First 1 -ExpandProperty Path + if ($livePath) { $exe = [string]$livePath } +} + +$findTargets = { + @(Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { + $_.SessionId -eq $mySid -and (-not $_.Path -or -not $exe -or [string]::Equals($_.Path, $exe, [System.StringComparison]::OrdinalIgnoreCase)) + }) +} + +$initial = & $findTargets +foreach ($p in $initial) { + try { + if ($p.MainWindowHandle -ne 0) { [void]$p.CloseMainWindow() } + } catch {} +} +Start-Sleep -Milliseconds 850 + +$remaining = & $findTargets +foreach ($p in $remaining) { + try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {} +} + +for ($i = 0; $i -lt 30; $i++) { + if ((& $findTargets).Count -eq 0) { break } + Start-Sleep -Milliseconds 200 +} + +foreach ($fp in $staleList) { + if ($fp -and (Test-Path -LiteralPath $fp)) { + try { Remove-Item -LiteralPath $fp -Force -ErrorAction SilentlyContinue } catch {} + } +} + +if ($exe -and (Test-Path -LiteralPath $exe)) { + $workDir = Split-Path -Parent $exe + Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir +} + +if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) { + Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue +} +`.trim(); +} + +const WIN_OUT_OF_JOB_DISPATCH_PS = ` +$ErrorActionPreference = 'Stop' +$innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '"' +try { + $shellApp = New-Object -ComObject Shell.Application + $shellApp.ShellExecute('powershell.exe', $innerArgs, '', 'open', 0) + Write-Output '{"ok":true,"method":"shell_application"}' +} catch { + Start-Process -FilePath 'powershell.exe' -ArgumentList $innerArgs -WindowStyle Hidden + Write-Output '{"ok":true,"method":"start_process"}' +} +`.trim(); + +/** + * 触发跨平台一键退出系统托盘后台并追加 `--remote-debugging-port=0` 重新拉起宿主客户端。 + * + * @param {{ + * env?: Record, + * platform?: string, + * homeDir?: string, + * stalePortFiles?: string[], + * execFileFn?: ((file: string, args: string[], opts?: object) => Promise)|null, + * spawnFn?: ((file: string, args: string[], opts?: object) => Promise<{ pid: number }>)|null, + * existsFn?: typeof existsSync, + * writeFileFn?: typeof writeFileSync, + * mkdirFn?: typeof mkdirSync, + * allowInTest?: boolean, + * }} [options] + */ +export async function triggerDesktopHostRelaunch({ + env = process.env, + platform = process.platform, + homeDir = homedir(), + stalePortFiles = [], + execFileFn = null, + spawnFn = null, + existsFn = existsSync, + writeFileFn = writeFileSync, + mkdirFn = mkdirSync, + allowInTest = false, +} = {}) { + if (lsRuntimeEndpoint.addr === 'test.invalid' && !allowInTest) { + return { ok: false, status: 403, error: 'Disabled in test sandbox' }; + } + + let hostInfo = resolveDesktopHostExecutable({ env, platform, homeDir, existsFn }); + if (!hostInfo.found) { + hostInfo = await discoverRunningHostExecutable({ platform, execFileFn }); + } + if (!hostInfo.found) { + return { + ok: false, + status: 404, + error: 'Unable to locate Antigravity executable on this machine', + }; + } + + const cleanEnv = buildSanitizedDesktopRelaunchEnv(env); + const cleanStaleFiles = (Array.isArray(stalePortFiles) ? stalePortFiles : []) + .map((p) => String(p || '').trim()) + .filter(Boolean); + + if (platform === 'win32') { + const innerScript = buildWindowsRelaunchInnerScript( + hostInfo.executablePath, + cleanStaleFiles, + hostInfo.kind + ); + const tempDir = String(env?.TEMP || env?.TMP || DATA_DIR || homeDir).trim(); + mkdirFn(tempDir, { recursive: true }); + const relaunchPs1Path = join(tempDir, `agy-monitor-relaunch-${process.pid}.ps1`); + // UTF-8 with BOM ensures Windows PowerShell 5.1 parses non-ASCII paths accurately across all system locales + writeFileFn(relaunchPs1Path, `\uFEFF${innerScript}\r\n`, 'utf8'); + + const runner = execFileFn || runLauncherExecFile; + await runner( + 'powershell.exe', + [ + '-Sta', + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-Command', + WIN_OUT_OF_JOB_DISPATCH_PS, + ], + { + timeoutMs: 6000, + env: { + ...cleanEnv, + AGY_RELAUNCH_PS1: relaunchPs1Path, + }, + } + ); + return { + ok: true, + relaunching: true, + platform, + executablePath: hostInfo.executablePath, + }; + } + + const spawner = spawnFn || spawnDetachedProcess; + + if (platform === 'darwin') { + const appTarget = hostInfo.appBundlePath || hostInfo.executablePath; + const appName = hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity'; + const shScript = [ + 'sleep 0.45', + `osascript -e 'tell application "${appName}" to quit' >/dev/null 2>&1 || true`, + `i=0; while [ $i -lt 25 ] && pgrep -x "${appName}" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done`, + `if pgrep -x "${appName}" >/dev/null 2>&1; then killall "${appName}" >/dev/null 2>&1 || true; sleep 0.4; fi`, + 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', + 'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1', + ].join('; '); + await spawner('/bin/sh', ['-c', shScript], { + env: { + ...cleanEnv, + AGY_RELAUNCH_APP: appTarget, + AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'), + }, + }); + return { + ok: true, + relaunching: true, + platform, + executablePath: appTarget, + }; + } + + const procLeaf = basename(hostInfo.executablePath) || 'antigravity'; + const linuxScript = [ + 'sleep 0.45', + 'uid="$(id -u)"', + 'pkill -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || true', + 'i=0; while [ $i -lt 25 ] && pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done', + 'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done', + 'nohup "$AGY_RELAUNCH_EXE" --remote-debugging-port=0 >/dev/null 2>&1 &', + ].join('; '); + await spawner('/bin/sh', ['-c', linuxScript], { + env: { + ...cleanEnv, + AGY_RELAUNCH_EXE: hostInfo.executablePath, + AGY_PROC_NAME: procLeaf, + AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'), + }, + }); + return { + ok: true, + relaunching: true, + platform, + executablePath: hostInfo.executablePath, + }; +} diff --git a/sidecars/panel/backend/http-helpers.mjs b/sidecars/panel/backend/http-helpers.mjs new file mode 100644 index 0000000..ba361d5 --- /dev/null +++ b/sidecars/panel/backend/http-helpers.mjs @@ -0,0 +1,69 @@ +/** + * @fileoverview 零业务状态依赖的静态资源读取与本机回环请求来源校验工具。 + * + * 独立于 `./config.mjs` 与 `./api-actions.mjs`,使宿主入口 `main.mjs` 在生产环境下无需加载完整后端图谱与轨迹缓存。 + */ + +import { readFileSync, promises as fsPromises } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +function resolveHttpHelperPanelDir() { + const modDir = dirname(fileURLToPath(import.meta.url)); + return /[\\/]backend$/i.test(modDir) ? dirname(modDir) : modDir; +} + +/** + * 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。 + * + * @param {string} relPath 相对路径 + * @returns {Promise} + */ +export const readLocalAsync = async (relPath) => { + const fullPath = join(resolveHttpHelperPanelDir(), relPath); + if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) { + return fsPromises.readFile(fullPath, 'utf8'); + } + return readFileSync(fullPath, 'utf8'); +}; + +/** + * 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin, + * 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。 + * + * @param {object} req + * @returns {boolean} + */ +export function isLocalHostRequest(req) { + if (!req?.headers) return true; + const host = String(req.headers.host || '').trim().toLowerCase(); + const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/); + if (host && !hostMatch) { + return false; + } + const origin = String(req.headers.origin || '').trim().toLowerCase(); + if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) { + return true; + } + const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase(); + if (secFetchSite === 'cross-site') { + return false; + } + if (origin) { + const originMatch = origin.match( + /^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/ + ); + if (!originMatch) { + return false; + } + if (hostMatch) { + const defaultPort = originMatch[1] === 'https' ? '443' : '80'; + const originPort = originMatch[3] || defaultPort; + const hostPort = hostMatch[2] || defaultPort; + if (originPort !== hostPort) { + return false; + } + } + } + return true; +} diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 9e179c0..77dab0e 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -16,23 +16,26 @@ import { extractModelSteps, getMaxMeaningfulStepIndex, parseIsoMs, -} from '../speed-metrics.mjs'; +} from '../trajectory-metrics.mjs'; import { ANNOTATION_DIRS, BRAIN_DIR, BRAIN_DIRS, - CACHE_FILE, CACHE_SCHEMA_VERSION, CONVERSATIONS_DIR, CONVERSATION_DIRS, DEEP_STATS_CACHE_CANDIDATES, - cacheState, + getCachedTrajectory, + hasPendingTrajectoryCacheSave, + listCachedTrajectoryEntries, externalDeepStatsMemo, loadJson, - saveJson, - trajectoryCache, + persistTrajectoryCacheIfNeeded, + removeCachedTrajectory, + setCachedTrajectory, } from './config.mjs'; import { + computeSqliteWalSig, hasBuiltinNodeSqlite, readAnnotationTitleForCascade, readLocalSqliteTrajectory, @@ -279,6 +282,68 @@ export function loadExternalDeepStatsCache() { const MAX_CONCURRENT_RPC = 4; const LEGACY_MIGRATION_BATCH_SIZE = 8; const stepFieldChecks = new WeakMap(); + +function normalizeOwnerAccount(value) { + return typeof value === 'string' ? value.trim().toLowerCase() : ''; +} + +/** + * 为会话步骤维护细粒度账号归属: + * - 已存在于旧缓存中的历史步骤保留原归属账号(兼容跨账号续聊同一会话); + * - 切换账号后在该会话中新产生的步骤写入当前活跃账号 `step.accountName`,仅供「可用额度」按账号隔离统计。 + */ +function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountName) { + if (!Array.isArray(steps) || steps.length === 0) return steps; + const activeOwner = normalizeOwnerAccount(currentAccountName); + const entryOwner = normalizeOwnerAccount(entryAccountName); + const prevOwner = normalizeOwnerAccount(prev?.accountName); + const prevSteps = Array.isArray(prev?.steps) ? prev.steps : []; + + if (prevSteps.length === 0) { + const initialOwner = prevOwner || activeOwner || entryOwner; + if (!initialOwner || initialOwner === entryOwner) return steps; + return steps.map((s) => ({ ...s, accountName: initialOwner })); + } + + const prevByIndex = new Map(); + let maxPrevStepIndex = -1; + let maxPrevCreatedAtMs = 0; + for (const ps of prevSteps) { + if (!ps || typeof ps !== 'object') continue; + const idx = Number(ps.stepIndex); + if (Number.isFinite(idx)) { + prevByIndex.set(idx, ps); + if (idx > maxPrevStepIndex) maxPrevStepIndex = idx; + } + const cMs = Number(ps.createdAtMs || 0); + if (cMs > maxPrevCreatedAtMs) maxPrevCreatedAtMs = cMs; + } + + let mutated = false; + const out = steps.map((s) => { + const idx = Number(s?.stepIndex); + const matchedPrev = Number.isFinite(idx) ? prevByIndex.get(idx) : null; + let stepOwner = ''; + if (matchedPrev) { + stepOwner = normalizeOwnerAccount(matchedPrev.accountName) || prevOwner; + } else { + const cMs = Number(s?.createdAtMs || 0); + const isHistoricalBackfill = + (Number.isFinite(idx) && maxPrevStepIndex >= 0 && idx <= maxPrevStepIndex) || + (cMs > 0 && maxPrevCreatedAtMs > 0 && cMs <= maxPrevCreatedAtMs); + stepOwner = isHistoricalBackfill ? prevOwner || activeOwner : activeOwner || prevOwner; + } + const storedAccount = stepOwner && stepOwner !== entryOwner ? stepOwner : undefined; + if (s?.accountName === storedAccount) return s; + mutated = true; + if (storedAccount) { + return { ...s, accountName: storedAccount }; + } + const { accountName: _removed, ...rest } = s; + return rest; + }); + return mutated ? out : steps; +} const MAX_SUBAGENT_RECONCILE_DEPTH = 4; const FAILED_RPC_COOLDOWN_MS = 60_000; const ACTIVE_FAILED_RPC_COOLDOWN_MS = 15_000; @@ -289,6 +354,12 @@ const failedFetchCooldownMap = new Map(); const liveActivityMemo = new Map(); const transcriptTailMemo = new Map(); +export function clearScannerRuntimeMemos() { + failedFetchCooldownMap.clear(); + liveActivityMemo.clear(); + transcriptTailMemo.clear(); +} + function findTranscriptPath(cascadeId) { if (!cascadeId) return ''; const normId = String(cascadeId).trim().toLowerCase(); @@ -348,26 +419,135 @@ function hasLocalSqliteDb(diskFiles = []) { return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || ''))); } -function findBestSqliteDbPath(diskFiles = []) { - if (!Array.isArray(diskFiles) || diskFiles.length === 0) return ''; - let bestPath = ''; - let bestMtime = -1; +function resolveBestSqliteDbInfo(diskFiles = []) { + if (!Array.isArray(diskFiles) || diskFiles.length === 0) return null; + let best = null; for (const rawPath of diskFiles) { const p = String(rawPath || '').trim(); if (!/\.db$/i.test(p)) continue; const fullPath = /[\\/]|^[a-zA-Z]:/.test(p) ? p : join(CONVERSATIONS_DIR, p); - if (!existsSync(fullPath)) continue; - try { - const mtime = Number(statSync(fullPath)?.mtimeMs || 0); - if (mtime > bestMtime) { - bestMtime = mtime; - bestPath = fullPath; - } - } catch { - if (!bestPath) bestPath = fullPath; + const walInfo = computeSqliteWalSig(fullPath); + if (!walInfo.exists) continue; + if (!best || walInfo.mtimeMs > best.mtimeMs) { + best = { + dbPath: fullPath, + mtimeMs: walInfo.mtimeMs, + sig: walInfo.sig, + }; } } - return bestPath; + return best; +} + +function findBestSqliteDbPath(diskFiles = []) { + return resolveBestSqliteDbInfo(diskFiles)?.dbPath || ''; +} + +function inferAppSourceFromSummary(sourceEnum = '', diskFiles = [], fallback = '') { + const fromDisk = inferConversationAppSource(diskFiles, null); + if (fromDisk) return fromDisk; + const src = String(sourceEnum || '').toUpperCase(); + if (src.includes('CLI')) return 'cli'; + if (src.includes('VSCODE') || src.includes('JETBOX') || src.includes('VISUAL_STUDIO')) { + return 'ide'; + } + return fallback || 'standalone'; +} + +function enrichSqliteStepsFromTranscriptIfNeeded(cidLower, sqliteSteps) { + if (!cidLower || !Array.isArray(sqliteSteps) || sqliteSteps.length === 0) { + return { firstUserTitle: '' }; + } + const needsTranscriptBackfill = sqliteSteps.some( + (s) => + (s?.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !s.userInput) || + (s?.metadata?.modelUsage && !s.metadata.modelUsage.model) + ); + if (!needsTranscriptBackfill) { + return { firstUserTitle: '' }; + } + const transcriptPath = findTranscriptPath(cidLower); + if (!transcriptPath || !existsSync(transcriptPath)) { + return { firstUserTitle: '' }; + } + let raw = ''; + try { + raw = readFileSync(transcriptPath, 'utf8'); + } catch { + return { firstUserTitle: '' }; + } + if (typeof raw !== 'string' || !raw.trim()) { + return { firstUserTitle: '' }; + } + + let firstUserTitle = ''; + const byStepIdx = new Map(); + let lineOrdinal = 0; + for (const rawLine of raw.split(/\r?\n/)) { + const trimmed = rawLine.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + if (!parsed || typeof parsed !== 'object') continue; + const idx = Number.isFinite(Number(parsed.step_index)) + ? Number(parsed.step_index) + : lineOrdinal; + lineOrdinal += 1; + byStepIdx.set(idx, parsed); + const upperType = String(parsed.type || '').trim().toUpperCase(); + if ( + !firstUserTitle && + (upperType === 'USER_INPUT' || + upperType === 'CORTEX_STEP_TYPE_USER_INPUT' || + (parsed.userInput && typeof parsed.userInput === 'object')) + ) { + firstUserTitle = extractOfflineUserTitle( + typeof parsed.content === 'string' + ? parsed.content + : parsed.userInput?.userResponse || '' + ); + } + } catch { + // 忽略损坏 JSON 行 + } + } + + let maxSqliteIdx = -1; + for (const sq of sqliteSteps) { + const sIdx = Number(sq?.metadata?.sourceTrajectoryStepInfo?.stepIndex ?? sq?.idx); + if (Number.isFinite(sIdx) && sIdx > maxSqliteIdx) maxSqliteIdx = sIdx; + const tLine = byStepIdx.get(sIdx); + if (!tLine) continue; + if (sq.type === 'CORTEX_STEP_TYPE_USER_INPUT' && !sq.userInput) { + if (typeof tLine.content === 'string') sq.content = tLine.content; + if (tLine.userInput) sq.userInput = tLine.userInput; + if (Array.isArray(tLine.media)) sq.media = tLine.media; + } else if (sq.metadata?.modelUsage && !sq.metadata.modelUsage.model) { + const fallbackModel = String(tLine.model || tLine.generator_model || '').trim(); + if (fallbackModel) sq.metadata.modelUsage.model = fallbackModel; + } + } + + return { firstUserTitle }; +} + +function filterClonedTrajectorySteps(rawSteps, generatorMeta, targetCidLower) { + if (!targetCidLower) { + return { steps: rawSteps || [], generatorMeta: generatorMeta || [] }; + } + const filteredSteps = (rawSteps || []).filter((s) => { + const originCid = String(s?.metadata?.sourceTrajectoryStepInfo?.cascadeId || '') + .trim() + .toLowerCase(); + return !originCid || originCid === targetCidLower; + }); + const filteredGen = (generatorMeta || []).filter((gm) => { + const gmCid = String(gm?.chatModel?.customMetadata?.cascade_id || '') + .trim() + .toLowerCase(); + return !gmCid || gmCid === targetCidLower; + }); + return { steps: filteredSteps, generatorMeta: filteredGen }; } /** @@ -1017,6 +1197,7 @@ function extractTrajectorySubagentMeta(trajRes, fallback = {}) { */ export async function enumerateAndSyncConversations({ summariesObj = {}, + sideQuestionParents = {}, currentAccountName = '', requestedConvId = '', forceRefresh = false, @@ -1034,10 +1215,11 @@ export async function enumerateAndSyncConversations({ } } - let cacheDirty = cacheState.needsSave; + let cacheDirty = hasPendingTrajectoryCacheSave(); const diskConvMap = discoverLocalConversationFiles(); // 构建大小写不敏感索引,将同一会话的不同大小写键合并至唯一规范键(优先保留 summariesObj 中的原始键以兼容 RPC) + const mergedSideQuestionParents = { ...(sideQuestionParents || {}) }; const canonicalIdByLower = new Map(); const summariesByLower = new Map(); for (const [rawId, summary] of Object.entries(summariesObj || {})) { @@ -1045,9 +1227,45 @@ export async function enumerateAndSyncConversations({ if (!lower) continue; canonicalIdByLower.set(lower, rawId); summariesByLower.set(lower, summary); + + const sqIds = summary?.annotations?.sideQuestionCascadeIds; + const sqTitles = summary?.annotations?.sideQuestionTitles || {}; + if (Array.isArray(sqIds)) { + for (const sqId of sqIds) { + const sqLower = String(sqId || '').trim().toLowerCase(); + if (!sqLower) continue; + mergedSideQuestionParents[sqLower] = { + parentConversationId: lower, + title: String(sqTitles[sqLower] || mergedSideQuestionParents[sqLower]?.title || ''), + }; + } + } + if (sqTitles && typeof sqTitles === 'object') { + for (const [sqKey, sqTitle] of Object.entries(sqTitles)) { + const sqLower = String(sqKey || '').trim().toLowerCase(); + if (!sqLower) continue; + const prevSq = mergedSideQuestionParents[sqLower]; + mergedSideQuestionParents[sqLower] = { + parentConversationId: prevSq?.parentConversationId || lower, + title: String(sqTitle || prevSq?.title || ''), + }; + } + } + const isSummarySideQ = + Boolean(summary?.isSideQuestion) || + Number(summary?.trajectoryType) === 22 || + summary?.trajectoryType === 'CORTEX_TRAJECTORY_TYPE_SIDE_QUESTION'; + const forkParent = String(summary?.forkParentConversationId || '').trim().toLowerCase(); + if (isSummarySideQ && forkParent) { + const prevSq = mergedSideQuestionParents[lower]; + mergedSideQuestionParents[lower] = { + parentConversationId: prevSq?.parentConversationId || forkParent, + title: String(prevSq?.title || summary?.annotations?.title || ''), + }; + } } - for (const rawCacheKey of Object.keys(trajectoryCache)) { + for (const [rawCacheKey] of listCachedTrajectoryEntries()) { const lower = String(rawCacheKey || '').trim().toLowerCase(); if (!lower) continue; const existingCanon = canonicalIdByLower.get(lower); @@ -1055,18 +1273,18 @@ export async function enumerateAndSyncConversations({ // 标准 UUID 统一收敛为小写键,避免大小写分裂产生双份条目 const normalizedKey = UUID_RE.test(rawCacheKey) ? lower : rawCacheKey; if (normalizedKey !== rawCacheKey) { - trajectoryCache[normalizedKey] = trajectoryCache[rawCacheKey]; - delete trajectoryCache[rawCacheKey]; + setCachedTrajectory(normalizedKey, getCachedTrajectory(rawCacheKey)); + removeCachedTrajectory(rawCacheKey); cacheDirty = true; } canonicalIdByLower.set(lower, normalizedKey); } else if (existingCanon !== rawCacheKey) { - const targetEntry = trajectoryCache[existingCanon]; - const dupEntry = trajectoryCache[rawCacheKey]; + const targetEntry = getCachedTrajectory(existingCanon); + const dupEntry = getCachedTrajectory(rawCacheKey); if (!targetEntry || (dupEntry?.steps?.length || 0) > (targetEntry?.steps?.length || 0)) { - trajectoryCache[existingCanon] = dupEntry; + setCachedTrajectory(existingCanon, dupEntry); } - delete trajectoryCache[rawCacheKey]; + removeCachedTrajectory(rawCacheKey); cacheDirty = true; } } @@ -1077,15 +1295,8 @@ export async function enumerateAndSyncConversations({ } } - // 仅从归属于当前账号的缓存会话收集 subagentRefs,防止跨账号切换时将其他账号的子代理复活进当前会话列表 - for (const entry of Object.values(trajectoryCache)) { - if ( - entry?.accountName && - currentAccountName !== '' && - entry.accountName !== currentAccountName - ) { - continue; - } + // 从所有本地缓存会话收集 subagentRefs,确保跨账号切换时历史会话与派生子代理均不丢失 + for (const [, entry] of listCachedTrajectoryEntries()) { for (const ref of entry?.subagentRefs || []) { const refCid = String(ref?.cascadeId || '').trim().toLowerCase(); if (refCid && !canonicalIdByLower.has(refCid)) { @@ -1095,45 +1306,88 @@ export async function enumerateAndSyncConversations({ } const localSummaryByLower = readLocalSummaryIndex(); + const sqliteAvailable = hasBuiltinNodeSqlite(); const STALE_LOCAL_RUNNING_MAX_AGE_MS = 10 * 60_000; const reqLower = String(requestedConvId || '').trim().toLowerCase(); const rawConversations = []; for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) { const item = summariesByLower.get(cidLower); const localSum = item ? null : localSummaryByLower.get(cidLower) || null; - const cached = trajectoryCache[cascadeId]; - if ( - cached?.accountName && - currentAccountName !== '' && - cached.accountName !== currentAccountName - ) { - continue; - } + const cached = getCachedTrajectory(cascadeId); + const diskFiles = diskConvMap.get(cidLower) || []; + const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null; + const dbPath = sqliteDbInfo?.dbPath || ''; + const diskFileSig = sqliteDbInfo?.sig || ''; const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || ''; const summaryMtimeMs = parseIsoMs(lastModifiedTime); - const diskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskConvMap.get(cidLower)); + const rawDiskMtimeMs = summaryMtimeMs ? null : readConversationMtime(diskFiles); + const diskMtimeMs = sqliteDbInfo + ? Math.max(rawDiskMtimeMs || 0, sqliteDbInfo.mtimeMs || 0) + : rawDiskMtimeMs; + const appSource = inferAppSourceFromSummary( + item?.source || '', + diskFiles, + cached?.appSource || 'standalone' + ); + + const sqParentInfo = mergedSideQuestionParents[cidLower] || null; + const isSideQuestion = Boolean( + sqParentInfo || + item?.isSideQuestion || + Number(item?.trajectoryType) === 22 || + item?.trajectoryType === 'CORTEX_TRAJECTORY_TYPE_SIDE_QUESTION' || + localSum?.isSideQuestion || + Number(localSum?.trajectoryType) === 22 || + cached?.isSideQuestion || + cached?.subagentSpec?.typeName === 'side_question' + ); + const rawMeta = item?.trajectoryMetadata || item?.metadata || {}; const parentConversationId = String( rawMeta.parentConversationId || + sqParentInfo?.parentConversationId || + item?.forkParentConversationId || localSum?.parentConversationId || + localSum?.forkParentConversationId || cached?.parentConversationId || + cached?.parentCascadeId || '' ).toLowerCase(); - const rootConversationId = String( - rawMeta.rootConversationId || cached?.rootConversationId || parentConversationId || '' - ).toLowerCase(); + const rawRootCid = String( + rawMeta.rootConversationId || localSum?.rootConversationId || '' + ) + .trim() + .toLowerCase(); + const cachedRootCid = String(cached?.rootConversationId || '').trim().toLowerCase(); + const rootConversationId = + (rawRootCid && rawRootCid !== cidLower ? rawRootCid : '') || + (cachedRootCid && cachedRootCid !== cidLower ? cachedRootCid : '') || + parentConversationId || + ''; const localAgentSpec = - parentConversationId && localSum?.agentName ? { role: localSum.agentName } : null; + parentConversationId && (localSum?.subagentSpec || localSum?.agentName) + ? localSum.subagentSpec || { role: localSum.agentName } + : null; + const primarySpec = isSideQuestion + ? { + typeName: 'side_question', + role: String(sqParentInfo?.title || item?.annotations?.title || localSum?.title || '').trim(), + } + : rawMeta.subagentSpec; const subagentSpec = mergeSubagentSpecs( - rawMeta.subagentSpec, + primarySpec, mergeSubagentSpecs(localAgentSpec, cached?.subagentSpec) ); const agentScriptName = rawMeta.agentScript?.name || cached?.agentScriptName || ''; const createdTimeMs = - parseIsoMs(item?.createdTime || rawMeta?.createdAt) || cached?.createdTimeMs || 0; + parseIsoMs(item?.createdTime || rawMeta?.createdAt || localSum?.createdTime) || + cached?.createdTimeMs || + 0; const spawnOrder = Number.isFinite(cached?.spawnOrder) ? cached.spawnOrder : null; const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null; const isSubagent = + isSideQuestion || + Boolean(cached?.isSubagent) || Boolean(parentConversationId) || Boolean(rootConversationId && rootConversationId !== cidLower); const latestLocalTouchMs = Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0); @@ -1150,19 +1404,29 @@ export async function enumerateAndSyncConversations({ const rawSummaryStepCount = Number(item?.stepCount || 0); const modelStepCount = Array.isArray(cached?.steps) ? cached.steps.length - : rawSummaryStepCount; + : isSideQuestion + ? 0 + : rawSummaryStepCount; rawConversations.push({ cascadeId, title: - item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8), + sqParentInfo?.title || + item?.annotations?.title || + item?.summary || + cached?.title || + (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: modelStepCount, rawStepCount: rawSummaryStepCount, status: item?.status || '', lastModifiedTime, lastModifiedMs, diskMtimeMs, + dbPath, + diskFileSig, + appSource, inSummaries: true, isSubagent, + isSideQuestion, parentConversationId, rootConversationId, subagentSpec, @@ -1176,9 +1440,13 @@ export async function enumerateAndSyncConversations({ const cachedStepCount = Number(cached.steps?.length || 0); rawConversations.push({ cascadeId, - title: localSum?.title || cached.title || cascadeId.slice(0, 8), + title: + sqParentInfo?.title || + localSum?.title || + cached.title || + (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: cachedStepCount, - rawStepCount: localSum?.stepCount || cachedStepCount, + rawStepCount: localSum?.stepCount || cached.rawStepCount || cachedStepCount, status: localStatus, lastModifiedTime: localSum?.lastModifiedTime || '', lastModifiedMs: Math.max( @@ -1188,8 +1456,12 @@ export async function enumerateAndSyncConversations({ localSum?.lastModifiedMs || 0 ), diskMtimeMs, + dbPath, + diskFileSig, + appSource, inSummaries: false, isSubagent, + isSideQuestion, parentConversationId, rootConversationId, subagentSpec, @@ -1201,16 +1473,23 @@ export async function enumerateAndSyncConversations({ } else { rawConversations.push({ cascadeId, - title: localSum?.title || cascadeId.slice(0, 8), + title: + sqParentInfo?.title || + localSum?.title || + (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)), stepCount: 0, rawStepCount: localSum?.stepCount || 0, status: localStatus, lastModifiedTime: localSum?.lastModifiedTime || '', lastModifiedMs: Math.max(diskMtimeMs || 0, localSum?.lastModifiedMs || 0), diskMtimeMs, + dbPath, + diskFileSig, + appSource, inSummaries: false, needsInitialLoad: true, isSubagent, + isSideQuestion, parentConversationId, rootConversationId, subagentSpec, @@ -1228,6 +1507,9 @@ export async function enumerateAndSyncConversations({ const nowPollMs = Date.now(); function buildConvSig(conv) { + if (conv.dbPath && conv.diskFileSig && sqliteAvailable) { + return `${CACHE_SCHEMA_VERSION}:sqlite:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime || ''}:${conv.diskFileSig}`; + } return conv.inSummaries ? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}` : `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`; @@ -1302,42 +1584,130 @@ export async function enumerateAndSyncConversations({ const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; const isReq = Boolean(reqLower && conv.cascadeId.toLowerCase() === reqLower); - const prev = trajectoryCache[conv.cascadeId]; + const prev = getCachedTrajectory(conv.cascadeId); let partialTailSteps = []; let hasTailStepInfo = false; try { - const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); + const cidLower = conv.cascadeId.toLowerCase(); + let trajRes = null; + let loadedViaSqlite = false; + let transcriptFirstTitle = ''; + if (conv.dbPath && sqliteAvailable) { + const sqlRes = readLocalSqliteTrajectory(conv.dbPath, { + cascadeId: conv.cascadeId, + isRunning, + }); + if (sqlRes && Array.isArray(sqlRes.trajectory?.steps)) { + trajRes = sqlRes; + loadedViaSqlite = true; + const enriched = enrichSqliteStepsFromTranscriptIfNeeded( + cidLower, + trajRes.trajectory.steps + ); + transcriptFirstTitle = enriched.firstUserTitle || ''; + } + } + if (!trajRes) { + trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId }); + } if (!Array.isArray(trajRes?.trajectory?.steps)) { throw new Error('Trajectory steps unavailable'); } - const rawSteps = trajRes.trajectory.steps; - if (Number(trajRes.numTotalSteps) > rawSteps.length) { - if (rawSteps.length > 0) { - partialTailSteps = rawSteps; + const rawStepsUnfiltered = trajRes.trajectory.steps; + if (!loadedViaSqlite && Number(trajRes.numTotalSteps) > rawStepsUnfiltered.length) { + if (rawStepsUnfiltered.length > 0) { + partialTailSteps = rawStepsUnfiltered; const tailIdx = - rawSteps[rawSteps.length - 1]?.metadata?.sourceTrajectoryStepInfo?.stepIndex; + rawStepsUnfiltered[rawStepsUnfiltered.length - 1]?.metadata?.sourceTrajectoryStepInfo + ?.stepIndex; hasTailStepInfo = Number.isFinite(Number(tailIdx)); } throw new Error('Incomplete trajectory; retaining cached usage'); } failedFetchCooldownMap.delete(cooldownKey); - const generatorMeta = trajRes?.trajectory?.generatorMetadata || []; + const rawGenMeta = trajRes?.trajectory?.generatorMetadata || []; + const { steps: rawSteps, generatorMeta } = loadedViaSqlite + ? { steps: rawStepsUnfiltered, generatorMeta: rawGenMeta } + : filterClonedTrajectorySteps(rawStepsUnfiltered, rawGenMeta, cidLower); const steps = extractModelSteps(rawSteps, generatorMeta); const nextLast = steps[steps.length - 1]; - // 提取轨迹内携带的子代理归属元数据与派生的子代理引用列表 + // 提取轨迹内携带的子代理归属元数据、旁路提问父归属与派生的子代理引用列表 + const sqParentInfo = mergedSideQuestionParents[cidLower] || null; const extractedMeta = extractTrajectorySubagentMeta(trajRes, conv); - conv.parentConversationId = extractedMeta.parentConversationId; - conv.rootConversationId = extractedMeta.rootConversationId; - conv.subagentSpec = extractedMeta.subagentSpec; - conv.agentScriptName = extractedMeta.agentScriptName; - conv.createdTimeMs = extractedMeta.createdTimeMs; - conv.isSubagent = - Boolean(conv.parentConversationId) || - Boolean( - conv.rootConversationId && - conv.rootConversationId !== conv.cascadeId.toLowerCase() - ); + const detectedSideQuestion = Boolean( + trajRes?.isSideQuestion || + Number(trajRes?.trajectoryType) === 22 || + trajRes?.trajectoryType === 'CORTEX_TRAJECTORY_TYPE_SIDE_QUESTION' || + conv.isSideQuestion || + sqParentInfo + ); + const defaultShortId = cidLower.slice(0, 8); + const nonShortTitle = (t) => { + const clean = String(t || '').trim(); + return clean && clean.toLowerCase() !== defaultShortId ? clean : ''; + }; + + if (detectedSideQuestion) { + const parentCid = String( + sqParentInfo?.parentConversationId || + trajRes?.forkParentConversationId || + extractedMeta.parentConversationId || + conv.parentConversationId || + '' + ) + .trim() + .toLowerCase(); + const sqTitle = String( + sqParentInfo?.title || + trajRes?.firstOwnUserPrompt || + transcriptFirstTitle || + (prev?.isSideQuestion ? nonShortTitle(prev?.title) : '') || + nonShortTitle(conv.title) || + '' + ).trim(); + const cleanSqRole = sqTitle && sqTitle !== '旁路提问' ? sqTitle : ''; + conv.isSideQuestion = true; + conv.parentConversationId = parentCid; + const extRoot = String(extractedMeta.rootConversationId || '').trim().toLowerCase(); + const prevConvRoot = String(conv.rootConversationId || '').trim().toLowerCase(); + conv.rootConversationId = + (extRoot && extRoot !== cidLower ? extRoot : '') || + (prevConvRoot && prevConvRoot !== cidLower ? prevConvRoot : '') || + parentCid || + ''; + conv.title = cleanSqRole || '旁路提问'; + conv.subagentSpec = { + typeName: 'side_question', + role: cleanSqRole || '旁路提问', + }; + conv.agentScriptName = ''; + conv.createdTimeMs = + extractedMeta.createdTimeMs || steps[0]?.createdAtMs || conv.createdTimeMs || 0; + conv.isSubagent = Boolean(conv.parentConversationId || conv.rootConversationId); + } else { + conv.parentConversationId = extractedMeta.parentConversationId; + conv.rootConversationId = extractedMeta.rootConversationId; + conv.subagentSpec = extractedMeta.subagentSpec; + conv.agentScriptName = extractedMeta.agentScriptName; + conv.createdTimeMs = extractedMeta.createdTimeMs; + conv.isSubagent = + Boolean(conv.parentConversationId) || + Boolean( + conv.rootConversationId && conv.rootConversationId !== cidLower + ); + if (!nonShortTitle(conv.title)) { + const annTitle = nonShortTitle(readAnnotationTitleForCascade(cidLower)); + const resolvedFallbackTitle = + annTitle || trajRes?.firstOwnUserPrompt || transcriptFirstTitle; + if (resolvedFallbackTitle) { + conv.title = resolvedFallbackTitle; + } + } + } + if (loadedViaSqlite && Number.isFinite(trajRes?.rawTableStepCount) && !conv.inSummaries) { + conv.rawStepCount = trajRes.rawTableStepCount; + } const subagentRefs = extractSubagentRefsFromSteps(rawSteps); conv.subagentRefs = subagentRefs; @@ -1346,6 +1716,7 @@ export async function enumerateAndSyncConversations({ const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs); conv.lastModifiedMs = resolvedLastModMs; conv.stepCount = steps.length; + const finalSig = buildConvSig(conv); const liveAct = resolveBestLiveActivity( conv.cascadeId, @@ -1355,27 +1726,42 @@ export async function enumerateAndSyncConversations({ ); if (liveAct) { conv.liveActivity = liveAct; - liveActivityMemo.set(conv.cascadeId.toLowerCase(), liveAct); + liveActivityMemo.set(cidLower, liveAct); } else { conv.liveActivity = null; - liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + liveActivityMemo.delete(cidLower); } + const entryAccountName = prev ? prev.accountName || '' : currentAccountName || ''; + const stepsWithOwners = attachStepAccountOwners( + steps, + prev, + currentAccountName, + entryAccountName + ); const cacheEntry = { - signature: sig, - accountName: prev?.accountName || currentAccountName || '', + signature: finalSig, + accountName: entryAccountName, title: conv.title, lastModifiedMs: resolvedLastModMs, diskMtimeMs: - conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(conv.cascadeId.toLowerCase())), + conv.diskMtimeMs ?? readConversationMtime(diskConvMap.get(cidLower)), + rawStepCount: conv.rawStepCount ?? stepsWithOwners.length, wasRunning: isRunning, contextLimitTelemetry: true, speedClearedTelemetry: true, turnRailTelemetry: true, - contextGroupsTelemetry: true, - steps, + contextGroupsTelemetry: 2, + steps: stepsWithOwners, subagentRefs, }; + if (conv.diskFileSig) cacheEntry.diskFileSig = conv.diskFileSig; + if (conv.appSource && conv.appSource !== 'standalone') { + cacheEntry.appSource = conv.appSource; + } + if (conv.isSideQuestion) { + cacheEntry.isSideQuestion = true; + } if (conv.isSubagent) { cacheEntry.parentConversationId = conv.parentConversationId; cacheEntry.rootConversationId = conv.rootConversationId; @@ -1388,21 +1774,22 @@ export async function enumerateAndSyncConversations({ const metaChanged = !Array.isArray(prev?.subagentRefs) || JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) || - (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || ''); + (prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') || + Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion); const stepsChanged = !prev || Boolean(prev.offlineTranscriptFallback) || - prev.signature !== sig || + prev.signature !== finalSig || Boolean(prev.wasRunning) !== isRunning || !prev.contextLimitTelemetry || !prev.speedClearedTelemetry || !prev.turnRailTelemetry || !prev.contextGroupsTelemetry || metaChanged || - !isDeepStrictEqual(prev.steps, steps); + !isDeepStrictEqual(prev.steps, stepsWithOwners); if (!stepsChanged) cacheEntry.steps = prev.steps; - trajectoryCache[conv.cascadeId] = cacheEntry; + setCachedTrajectory(conv.cascadeId, cacheEntry); if (stepsChanged) { cacheDirty = true; } @@ -1414,13 +1801,6 @@ export async function enumerateAndSyncConversations({ for (const ext of loadExternalDeepStatsCache().values()) { const extCid = String(ext?.cascadeId || '').toLowerCase(); if (!extCid) continue; - if ( - ext.accountName && - currentAccountName !== '' && - ext.accountName !== currentAccountName - ) { - continue; - } const existingExt = lazyExternalByLower.get(extCid); if (!existingExt || (ext.steps?.length || 0) > (existingExt.steps?.length || 0)) { lazyExternalByLower.set(extCid, ext); @@ -1451,10 +1831,18 @@ export async function enumerateAndSyncConversations({ Boolean(conv.parentConversationId) || Boolean(conv.rootConversationId && conv.rootConversationId !== cidLower); const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles); + const offlineAccountName = prev + ? prev.accountName || offlineFallback.accountName || '' + : offlineFallback.accountName || currentAccountName || ''; + const offlineStepsWithOwners = attachStepAccountOwners( + offlineFallback.steps, + prev, + offlineFallback.accountName || currentAccountName, + offlineAccountName + ); const offlineEntry = { signature: sig, - accountName: - prev?.accountName || offlineFallback.accountName || currentAccountName || '', + accountName: offlineAccountName, title: offlineFallback.title, ...(offlineFallback.appSource ? { appSource: offlineFallback.appSource } : {}), lastModifiedMs: offlineFallback.lastModifiedMs, @@ -1465,8 +1853,8 @@ export async function enumerateAndSyncConversations({ contextLimitTelemetry: true, speedClearedTelemetry: true, turnRailTelemetry: true, - contextGroupsTelemetry: true, - steps: offlineFallback.steps, + contextGroupsTelemetry: 2, + steps: offlineStepsWithOwners, subagentRefs: offlineFallback.subagentRefs, }; if (conv.isSubagent) { @@ -1485,7 +1873,7 @@ export async function enumerateAndSyncConversations({ Boolean(prev.offlineSqliteTelemetry) !== Boolean(offlineEntry.offlineSqliteTelemetry) || !isDeepStrictEqual(prev.steps, offlineEntry.steps); if (!changed) offlineEntry.steps = prev.steps; - trajectoryCache[conv.cascadeId] = offlineEntry; + setCachedTrajectory(conv.cascadeId, offlineEntry); if (changed) { cacheDirty = true; } @@ -1524,10 +1912,11 @@ export async function enumerateAndSyncConversations({ if ( !offlineRecovered && prev && + getCachedTrajectory(conv.cascadeId) === prev && String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && !Array.isArray(prev.subagentRefs) ) { - prev.subagentRefs = []; + setCachedTrajectory(conv.cascadeId, { ...prev, subagentRefs: [] }); cacheDirty = true; } } @@ -1549,8 +1938,12 @@ export async function enumerateAndSyncConversations({ return !Object.prototype.hasOwnProperty.call(lastCachedStep, 'turnIndex'); } function hasDroppedContextGroups(cached) { - if (cached?.contextGroupsTelemetry) return false; + if (cached?.contextGroupsTelemetry === 2) return false; const steps = cached?.steps || []; + if (steps.some((st) => st?.isCompactionStep)) { + return true; + } + if (cached?.contextGroupsTelemetry) return false; for (let i = steps.length - 1; i >= 0; i--) { const st = steps[i]; if (!st || st.isCompactionStep) break; @@ -1575,7 +1968,7 @@ export async function enumerateAndSyncConversations({ const sig = buildConvSig(conv); if (isFetchInCooldown(conv, sig)) return false; const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING'; - const cached = trajectoryCache[conv.cascadeId]; + const cached = getCachedTrajectory(conv.cascadeId); if (!cached || conv.needsInitialLoad) return true; const lowerCid = conv.cascadeId.toLowerCase(); const isSelectedFamily = @@ -1595,10 +1988,20 @@ export async function enumerateAndSyncConversations({ `${CACHE_SCHEMA_VERSION}:` ); if (!hasCurrentSchema) return true; + if ( + conv.dbPath && + sqliteAvailable && + !String(cached.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:sqlite:`) + ) { + return true; + } if (hasMissingStepFields(cached)) return true; const missingSubagentRefs = !Array.isArray(cached.subagentRefs); if (!conv.inSummaries) { if (isRunning || cached.wasRunning) return true; + if (conv.dbPath && sqliteAvailable) { + return cached.signature !== sig; + } if ( cached.offlineTranscriptFallback && !cached.offlineSqliteTelemetry && @@ -1652,7 +2055,7 @@ export async function enumerateAndSyncConversations({ const missingSubagentsToFetch = []; for (const parentConv of [...rawConversations]) { - const parentCached = trajectoryCache[parentConv.cascadeId]; + const parentCached = getCachedTrajectory(parentConv.cascadeId); const refs = parentConv.subagentRefs || parentCached?.subagentRefs || []; if (!Array.isArray(refs) || refs.length === 0) continue; @@ -1670,9 +2073,14 @@ export async function enumerateAndSyncConversations({ const canonSubId = canonicalIdByLower.get(subCid) || subCid; canonicalIdByLower.set(subCid, canonSubId); let subConv = byLowerId.get(subCid); - const subCached = trajectoryCache[subConv?.cascadeId || canonSubId]; + const subCached = getCachedTrajectory(subConv?.cascadeId || canonSubId); if (!subConv) { - const diskMtimeMs = readConversationMtime(diskConvMap.get(subCid)); + const subDiskFiles = diskConvMap.get(subCid) || []; + const subDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(subDiskFiles) : null; + const diskMtimeMs = Math.max( + readConversationMtime(subDiskFiles), + subDbInfo?.mtimeMs || 0 + ); const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0; const stepCount = Number(subCached?.steps?.length || 0); subConv = { @@ -1689,9 +2097,13 @@ export async function enumerateAndSyncConversations({ ref.createdTimeMs || 0 ), diskMtimeMs, + dbPath: subDbInfo?.dbPath || '', + diskFileSig: subDbInfo?.sig || '', + appSource: inferAppSourceFromSummary('', subDiskFiles, subCached?.appSource || 'standalone'), inSummaries: false, needsInitialLoad: !subCached, isSubagent: true, + isSideQuestion: false, parentConversationId: parentId, rootConversationId: rootId, subagentSpec: mergeSubagentSpecs(ref, subCached?.subagentSpec), @@ -1719,12 +2131,16 @@ export async function enumerateAndSyncConversations({ } const targetCacheKey = subConv.cascadeId; - const existingSubCache = trajectoryCache[targetCacheKey]; + const existingSubCache = getCachedTrajectory(targetCacheKey); const isSelectedSubFamily = rootId === selectedRootId; const hasValidSubCache = existingSubCache && !(existingSubCache.offlineTranscriptFallback && subConv.inSummaries) && - String(existingSubCache.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) && + String(existingSubCache.signature || '').startsWith( + subConv.dbPath && sqliteAvailable + ? `${CACHE_SCHEMA_VERSION}:sqlite:` + : `${CACHE_SCHEMA_VERSION}:` + ) && !hasMissingStepFields(existingSubCache) && (!isSelectedSubFamily || (Boolean(existingSubCache.turnRailTelemetry) && @@ -1732,42 +2148,37 @@ export async function enumerateAndSyncConversations({ !hasDroppedContextGroups(existingSubCache))); if (hasValidSubCache) { - let subMetaUpdated = false; + const updatedMetadata = {}; if (existingSubCache.parentConversationId !== subConv.parentConversationId) { - existingSubCache.parentConversationId = subConv.parentConversationId; - subMetaUpdated = true; + updatedMetadata.parentConversationId = subConv.parentConversationId; } if (existingSubCache.rootConversationId !== subConv.rootConversationId) { - existingSubCache.rootConversationId = subConv.rootConversationId; - subMetaUpdated = true; + updatedMetadata.rootConversationId = subConv.rootConversationId; } const nextSpec = sanitizeSubagentSpec(subConv.subagentSpec); if ( nextSpec && JSON.stringify(existingSubCache.subagentSpec || null) !== JSON.stringify(nextSpec) ) { - existingSubCache.subagentSpec = nextSpec; - subMetaUpdated = true; + updatedMetadata.subagentSpec = nextSpec; } if ( subConv.createdTimeMs && existingSubCache.createdTimeMs !== subConv.createdTimeMs ) { - existingSubCache.createdTimeMs = subConv.createdTimeMs; - subMetaUpdated = true; + updatedMetadata.createdTimeMs = subConv.createdTimeMs; } if ( Number.isFinite(subConv.spawnOrder) && existingSubCache.spawnOrder !== subConv.spawnOrder ) { - existingSubCache.spawnOrder = subConv.spawnOrder; - subMetaUpdated = true; + updatedMetadata.spawnOrder = subConv.spawnOrder; } if (!Array.isArray(existingSubCache.subagentRefs)) { - existingSubCache.subagentRefs = []; - subMetaUpdated = true; + updatedMetadata.subagentRefs = []; } - if (subMetaUpdated) { + if (Object.keys(updatedMetadata).length > 0) { + setCachedTrajectory(targetCacheKey, { ...existingSubCache, ...updatedMetadata }); cacheDirty = true; } } else { @@ -1793,7 +2204,7 @@ export async function enumerateAndSyncConversations({ if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) { return false; } - const cached = trajectoryCache[c.cascadeId]; + const cached = getCachedTrajectory(c.cascadeId); return cached && !Array.isArray(cached.subagentRefs); }) .slice(0, LEGACY_MIGRATION_BATCH_SIZE); @@ -1809,6 +2220,9 @@ export async function enumerateAndSyncConversations({ if (!conv.isSubagent) continue; const cid = conv.cascadeId.toLowerCase(); let candidate = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase(); + if (candidate === cid) { + candidate = (conv.parentConversationId || '').toLowerCase(); + } const visited = new Set([cid]); while (candidate && !visited.has(candidate)) { visited.add(candidate); @@ -1824,16 +2238,19 @@ export async function enumerateAndSyncConversations({ } if (candidate && candidate !== conv.rootConversationId) { conv.rootConversationId = candidate; - const cached = trajectoryCache[conv.cascadeId]; + const cached = getCachedTrajectory(conv.cascadeId); if (cached && cached.rootConversationId !== candidate) { - cached.rootConversationId = candidate; + setCachedTrajectory(conv.cascadeId, { ...cached, rootConversationId: candidate }); cacheDirty = true; } } } - if (cacheDirty) { - cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache); + const hasRunningSessions = rawConversations.some( + (c) => c.status === 'CASCADE_RUN_STATUS_RUNNING' + ); + if (cacheDirty || (hasPendingTrajectoryCacheSave() && !hasRunningSessions)) { + persistTrajectoryCacheIfNeeded({ hasRunningSessions }); } // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要 @@ -1861,12 +2278,28 @@ export async function enumerateAndSyncConversations({ const cid = conv.cascadeId.toLowerCase(); const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase(); const rootTarget = byId.get(rootId); - if (conv.isSubagent) { - if (rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) { + if (conv.isSubagent || conv.isSideQuestion) { + if ( + conv.isSideQuestion && + Number(conv.stepCount || 0) === 0 && + conv.status !== 'CASCADE_RUN_STATUS_RUNNING' && + cid !== reqLower + ) { + continue; + } + if ( + rootId && + rootId !== cid && + rootTarget && + !rootTarget.isSubagent && + !rootTarget.isSideQuestion + ) { if (!subagentsByRoot.has(rootId)) { subagentsByRoot.set(rootId, []); } subagentsByRoot.get(rootId).push(conv); + } else if (conv.isSideQuestion && cid === reqLower) { + conversations.push(conv); } } else { conversations.push(conv); @@ -1877,7 +2310,13 @@ export async function enumerateAndSyncConversations({ const cid = rootConv.cascadeId.toLowerCase(); const subs = subagentsByRoot.get(cid) || []; subs.sort((a, b) => { + const aSide = Boolean(a.isSideQuestion); + const bSide = Boolean(b.isSideQuestion); + if (aSide !== bSide) { + return aSide ? 1 : -1; + } if ( + !aSide && a.parentConversationId === b.parentConversationId && Number.isFinite(a.spawnOrder) && Number.isFinite(b.spawnOrder) && @@ -1887,12 +2326,12 @@ export async function enumerateAndSyncConversations({ } const aStart = a.createdTimeMs || - trajectoryCache[a.cascadeId]?.steps?.[0]?.createdAtMs || + getCachedTrajectory(a.cascadeId)?.steps?.[0]?.createdAtMs || a.lastModifiedMs || 0; const bStart = b.createdTimeMs || - trajectoryCache[b.cascadeId]?.steps?.[0]?.createdAtMs || + getCachedTrajectory(b.cascadeId)?.steps?.[0]?.createdAtMs || b.lastModifiedMs || 0; return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId)); @@ -1921,9 +2360,8 @@ export async function enumerateAndSyncConversations({ ))) || conversations[0] || null; - const requestedOwner = trajectoryCache[canonicalIdByLower.get(reqLower)]?.accountName; - const safeReqId = requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) && - (!requestedOwner || currentAccountName === '' || requestedOwner === currentAccountName) ? requestedConvId : null; + const safeReqId = + requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null; const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null; return { diff --git a/sidecars/panel/backend/ls-discovery.mjs b/sidecars/panel/backend/ls-discovery.mjs index b73617e..f9db480 100644 --- a/sidecars/panel/backend/ls-discovery.mjs +++ b/sidecars/panel/backend/ls-discovery.mjs @@ -513,7 +513,7 @@ export async function ensureLsEndpointDiscovered({ if (lsRuntimeEndpoint.addr === 'test.invalid') { return false; } - if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) { + if (!force && lsRuntimeEndpoint.baseUrl && (lsRuntimeEndpoint.csrfToken || !lsRuntimeEndpoint.isDynamic)) { return true; } if (lsDiscoveryState.inFlight) { diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index c850899..d8c3493 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -8,6 +8,7 @@ * 绝不借用其他模型单价伪造费用。 */ +import { parseIsoMs } from '../trajectory-metrics.mjs'; import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs'; /** @@ -130,7 +131,7 @@ export function formatGenericModelSlug(slug = '') { .trim() .replace(/^session-display:/i, ''); if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return ''; - if (/^gemini-4-argon-(?:f|disabled)$/i.test(s)) return 'Gemini 4 Argon'; + if (/^gemini-4-argon-(?:b|f|trial|disabled)$/i.test(s)) return 'Gemini 4 Argon'; if (/^gemini-3\.8-flash-n$/i.test(s)) return 'Gemini 3.8 Flash'; if (/^gemini-3\.7-flash-safety-le$/i.test(s)) return 'Gemini 3.7 Flash'; if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash'; @@ -159,16 +160,78 @@ export function formatGenericModelSlug(slug = '') { return ''; } +function extractStepTimestampMs(step) { + if (!step || typeof step !== 'object') return 0; + const direct = Number(step.createdAtMs); + if (Number.isFinite(direct) && direct > 0) return direct; + if (typeof step.createdAt === 'string' && step.createdAt.trim()) { + return parseIsoMs(step.createdAt.trim()) || 0; + } + return 0; +} + /** - * 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。 + * 根据目标时间戳匹配模型价格条目的时间阶段(`phases`,左闭右开 `[fromMs, untilMs)`)。 + * 未传入有效时间戳时按当前时刻匹配;未命中任何阶段或未配置阶段时回退至顶层基础单价。 * - * @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`) - * @param {Map} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表 - * @param {string} [apiProvider=''] API 提供商枚举 - * @param {string} [modelDisplayName=''] 已知的模型展示名称 - * @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`) + * @param {object|null} pricingEntry + * @param {number|string|null} [atMs] + * @returns {object|null} */ -export function resolveModelInfo( +export function resolvePricingAt(pricingEntry, atMs) { + if (!pricingEntry || typeof pricingEntry !== 'object') return null; + const baseEntry = pricingEntry._basePricing || pricingEntry; + const phases = baseEntry.phases; + if (!Array.isArray(phases) || phases.length === 0) return baseEntry; + + let tMs = 0; + if (typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0) { + tMs = atMs; + } else if (typeof atMs === 'string' && atMs.trim()) { + tMs = parseIsoMs(atMs.trim()) || 0; + } + if (tMs <= 0) { + tMs = Date.now(); + } + + for (let i = 0; i < phases.length; i++) { + const ph = phases[i]; + if (!ph || typeof ph !== 'object') continue; + const fromMs = Number.isFinite(ph.fromMs) + ? ph.fromMs + : typeof ph.from === 'string' && ph.from.trim() + ? parseIsoMs(ph.from.trim()) || -Infinity + : -Infinity; + const untilMs = Number.isFinite(ph.untilMs) + ? ph.untilMs + : typeof ph.until === 'string' && ph.until.trim() + ? parseIsoMs(ph.until.trim()) || Infinity + : Infinity; + if (tMs >= fromMs && tMs < untilMs) { + if ( + ph.input === baseEntry.input && + ph.cache === baseEntry.cache && + ph.output === baseEntry.output + ) { + return baseEntry; + } + const resolved = { + ...baseEntry, + input: ph.input, + cache: ph.cache, + output: ph.output, + }; + Object.defineProperty(resolved, '_basePricing', { + value: baseEntry, + enumerable: false, + }); + return resolved; + } + } + return baseEntry; +} + +function resolveModelCatalogEntry( rawModelKey, dynamicModelMap = new Map(), apiProvider = '', @@ -251,42 +314,86 @@ export function resolveModelInfo( if (explicitPricing) { return { - rawModel: rawModelKey, - modelId, - label: derivedDisplay, - baseLabel, - shortName: explicitPricing.short, - family: explicitPricing.family, - pricing: explicitPricing, - isEstimatedPrice: false, + catalogPricing: explicitPricing, + info: { + rawModel: rawModelKey, + modelId, + label: derivedDisplay, + baseLabel, + shortName: explicitPricing.short, + family: explicitPricing.family, + pricing: explicitPricing, + isEstimatedPrice: false, + }, }; } const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider); return { - rawModel: rawModelKey, - modelId, - label: derivedDisplay, - baseLabel, - shortName: derivedDisplay, - family: inferredFamily, - pricing: null, - isEstimatedPrice: true, + catalogPricing: null, + info: { + rawModel: rawModelKey, + modelId, + label: derivedDisplay, + baseLabel, + shortName: derivedDisplay, + family: inferredFamily, + pricing: null, + isEstimatedPrice: true, + }, }; } -/** 在单次遥测请求内复用同一模型身份与价格的解析结果。 */ +/** + * 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与指定时刻的单价配置。 + * + * @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`) + * @param {Map} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表 + * @param {string} [apiProvider=''] API 提供商枚举 + * @param {string} [modelDisplayName=''] 已知的模型展示名称 + * @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`) + * @param {number|string|null} [atMs=0] 步骤发生时间戳(缺省按当前时刻匹配阶段价格) + */ +export function resolveModelInfo( + rawModelKey, + dynamicModelMap = new Map(), + apiProvider = '', + modelDisplayName = '', + responseModel = '', + atMs = 0 +) { + const { catalogPricing, info } = resolveModelCatalogEntry( + rawModelKey, + dynamicModelMap, + apiProvider, + modelDisplayName, + responseModel + ); + if (!catalogPricing) return info; + const effectivePricing = resolvePricingAt(catalogPricing, atMs); + return effectivePricing === catalogPricing ? info : { ...info, pricing: effectivePricing }; +} + +/** 在单次遥测请求内按模型身份与价格阶段复用解析结果。 */ export function createStepModelResolver(dynamicModelMap) { const models = new Map(); return (step) => { - const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step; + const stepMs = extractStepTimestampMs(step); + const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step || {}; if ( typeof modelKey !== 'string' || typeof apiProvider !== 'string' || typeof modelDisplayName !== 'string' || typeof responseModel !== 'string' ) { - return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel); + return resolveModelInfo( + modelKey, + dynamicModelMap, + apiProvider, + modelDisplayName, + responseModel, + stepMs + ); } let providers = models.get(modelKey); if (!providers) models.set(modelKey, (providers = new Map())); @@ -294,12 +401,50 @@ export function createStepModelResolver(dynamicModelMap) { if (!names) providers.set(apiProvider, (names = new Map())); let responses = names.get(modelDisplayName); if (!responses) names.set(modelDisplayName, (responses = new Map())); - let info = responses.get(responseModel); - if (!info) { - info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel); - responses.set(responseModel, info); + let cached = responses.get(responseModel); + if (!cached) { + const { catalogPricing, info } = resolveModelCatalogEntry( + modelKey, + dynamicModelMap, + apiProvider, + modelDisplayName, + responseModel + ); + cached = { + catalogPricing, + baseInfo: info, + byPhaseIdx: catalogPricing?.phases?.length ? new Map() : null, + }; + responses.set(responseModel, cached); } - return info; + if (!cached.byPhaseIdx) { + return cached.baseInfo; + } + const tMs = stepMs > 0 ? stepMs : Date.now(); + const phases = cached.catalogPricing.phases; + let phaseIdx = -1; + for (let i = 0; i < phases.length; i++) { + const ph = phases[i]; + const fromMs = Number.isFinite(ph.fromMs) ? ph.fromMs : -Infinity; + const untilMs = Number.isFinite(ph.untilMs) ? ph.untilMs : Infinity; + if (tMs >= fromMs && tMs < untilMs) { + phaseIdx = i; + break; + } + } + let phasedInfo = cached.byPhaseIdx.get(phaseIdx); + if (!phasedInfo) { + const effectivePricing = + phaseIdx >= 0 + ? resolvePricingAt(cached.catalogPricing, tMs) + : cached.catalogPricing; + phasedInfo = + effectivePricing === cached.catalogPricing + ? cached.baseInfo + : { ...cached.baseInfo, pricing: effectivePricing }; + cached.byPhaseIdx.set(phaseIdx, phasedInfo); + } + return phasedInfo; }; } @@ -343,12 +488,17 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) { */ export function computeStepCost(step, pricing) { if (!pricing) return null; + const stepMs = extractStepTimestampMs(step); + const effectivePricing = + stepMs > 0 && Array.isArray(pricing.phases) && pricing.phases.length > 0 + ? resolvePricingAt(pricing, stepMs) + : pricing; const safeTok = (v) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? n : 0; }; - const inCost = (safeTok(step?.inputTokens) / 1_000_000) * pricing.input; - const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * pricing.cache; - const outCost = (safeTok(step?.outputTokens) / 1_000_000) * pricing.output; + const inCost = (safeTok(step?.inputTokens) / 1_000_000) * effectivePricing.input; + const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * effectivePricing.cache; + const outCost = (safeTok(step?.outputTokens) / 1_000_000) * effectivePricing.output; return inCost + cacheCost + outCost; } diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs index 296e3a5..84b82dd 100644 --- a/sidecars/panel/backend/pricing-catalog.mjs +++ b/sidecars/panel/backend/pricing-catalog.mjs @@ -11,7 +11,7 @@ import { existsSync } from 'node:fs'; import { join } from 'node:path'; -import { parseIsoMs } from '../speed-metrics.mjs'; +import { parseIsoMs } from '../trajectory-metrics.mjs'; import { DEFAULT_ARCHIVE_FALLBACK_URL, DEFAULT_DOWNLOAD_URL, @@ -23,6 +23,7 @@ import { PLUGIN_ROOT, REMOTE_CATALOG_CACHE_FILE, cloudSyncState, + detectCustomGitForkRepo, loadJson, pluginUpdateState, } from './config.mjs'; @@ -33,6 +34,24 @@ import { export const MODEL_PRICING = {}; export const PLACEHOLDER_MAP = {}; export let pricingCatalogRevision = 0; +let pricingPhaseBoundariesMs = []; + +/** + * 返回给定时刻已跨过的全局价格阶段边界计数,供遥测与聚合快照在跨越优惠截止时间点时自动失效重算。 + * + * @param {number} [atMs=Date.now()] + * @returns {number} + */ +export function getPricingPhaseEpoch(atMs = Date.now()) { + const t = Number(atMs); + if (!Number.isFinite(t) || t <= 0 || pricingPhaseBoundariesMs.length === 0) return 0; + let epoch = 0; + for (let i = 0; i < pricingPhaseBoundariesMs.length; i++) { + if (t >= pricingPhaseBoundariesMs[i]) epoch = i + 1; + else break; + } + return epoch; +} /** * 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。 @@ -189,13 +208,7 @@ function normalizeModelFamily(rawFamily) { return f; } -/** - * 校验单条模型价格配置是否合法: - * - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞); - * - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00); - * - `short`/`family` 必须为非空字符串。 - */ -function isValidPricingEntry(entry) { +function isValidPricingRateTriplet(entry) { if (!entry || typeof entry !== 'object') return false; if ( typeof entry.input !== 'number' || @@ -209,6 +222,52 @@ function isValidPricingEntry(entry) { if (!Number.isFinite(cache) || cache < 0 || cache > 10000) return false; if (!Number.isFinite(output) || output < 0 || output > 10000) return false; if (input === 0 && output === 0) return false; + return true; +} + +/** + * 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。 + * 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。 + */ +function sanitizePricingPhase(rawPhase) { + if (!isValidPricingRateTriplet(rawPhase)) return null; + let from = null; + let fromMs = -Infinity; + if (rawPhase.from !== undefined && rawPhase.from !== null) { + if (typeof rawPhase.from !== 'string' || !rawPhase.from.trim()) return null; + const parsedFrom = parseIsoMs(rawPhase.from.trim()); + if (!parsedFrom || parsedFrom <= 0) return null; + from = rawPhase.from.trim(); + fromMs = parsedFrom; + } + let until = null; + let untilMs = Infinity; + if (rawPhase.until !== undefined && rawPhase.until !== null) { + if (typeof rawPhase.until !== 'string' || !rawPhase.until.trim()) return null; + const parsedUntil = parseIsoMs(rawPhase.until.trim()); + if (!parsedUntil || parsedUntil <= 0) return null; + until = rawPhase.until.trim(); + untilMs = parsedUntil; + } + if (from === null && until === null) return null; + if (fromMs >= untilMs) return null; + return { + ...(from !== null ? { from, fromMs } : {}), + ...(until !== null ? { until, untilMs } : {}), + input: rawPhase.input, + cache: rawPhase.cache, + output: rawPhase.output, + }; +} + +/** + * 校验单条模型价格配置是否合法: + * - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞); + * - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00); + * - `short`/`family` 必须为非空字符串。 + */ +function isValidPricingEntry(entry) { + if (!isValidPricingRateTriplet(entry)) return false; if (typeof entry.short !== 'string' || !entry.short.trim()) return false; if (typeof entry.family !== 'string' || !entry.family.trim()) return false; return true; @@ -239,12 +298,20 @@ export function sanitizeCatalogPayload(raw) { for (const [k, v] of Object.entries(raw.pricing)) { const key = String(k || '').trim(); if (!key || !isValidPricingEntry(v)) continue; + let phases = null; + if (Array.isArray(v.phases)) { + const cleanedPhases = v.phases.map(sanitizePricingPhase).filter(Boolean); + if (cleanedPhases.length > 0) { + phases = cleanedPhases; + } + } pricing[key] = { input: v.input, cache: v.cache, output: v.output, short: String(v.short).trim(), family: normalizeModelFamily(v.family), + ...(phases ? { phases } : {}), }; validPricingCount++; } @@ -332,10 +399,18 @@ export function rebuildActiveCatalog() { let catalogVersion = 'builtin'; let updatedAt = null; const installedVersion = readInstalledPluginVersion(); + const customForkRepo = detectCustomGitForkRepo(); + const customForkPrefix = customForkRepo ? `/${customForkRepo.toLowerCase()}` : ''; let latestPluginVersion = installedVersion; - let releaseUrl = DEFAULT_RELEASE_URL; - let downloadUrl = DEFAULT_DOWNLOAD_URL; - let archiveFallbackUrl = DEFAULT_ARCHIVE_FALLBACK_URL; + let releaseUrl = customForkRepo + ? `https://github.com/${customForkRepo}/releases/latest` + : DEFAULT_RELEASE_URL; + let downloadUrl = customForkRepo + ? `https://github.com/${customForkRepo}/releases/latest/download/usage-monitor.zip` + : DEFAULT_DOWNLOAD_URL; + let archiveFallbackUrl = customForkRepo + ? `https://codeload.github.com/${customForkRepo}/zip/refs/heads/main` + : DEFAULT_ARCHIVE_FALLBACK_URL; for (const { kind, cat } of layers) { Object.assign(nextPricing, cat.pricing); @@ -345,21 +420,39 @@ export function rebuildActiveCatalog() { } if (cat.catalogVersion) catalogVersion = cat.catalogVersion; if (cat.updatedAt) updatedAt = cat.updatedAt; - if (cat.latestPluginVersion) { - // 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本 + const isFromCustomFork = Boolean( + customForkPrefix && + typeof cat.sourceUrl === 'string' && + cat.sourceUrl.toLowerCase().includes(customForkPrefix) + ); + const shouldAcceptCatalogReleaseMeta = !customForkRepo || isFromCustomFork; + if (shouldAcceptCatalogReleaseMeta && cat.latestPluginVersion) { + // 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本;自定义 Fork 忽略上游版本号 latestPluginVersion = compareSemver(cat.latestPluginVersion, installedVersion) > 0 ? cat.latestPluginVersion : installedVersion; } - if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl; - if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl; - if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl; + if (shouldAcceptCatalogReleaseMeta) { + if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl; + if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl; + if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl; + } } for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k]; Object.assign(MODEL_PRICING, nextPricing); + const boundarySet = new Set(); + for (const entry of Object.values(nextPricing)) { + if (!Array.isArray(entry?.phases)) continue; + for (const ph of entry.phases) { + if (Number.isFinite(ph.fromMs) && ph.fromMs > 0) boundarySet.add(ph.fromMs); + if (Number.isFinite(ph.untilMs) && ph.untilMs > 0) boundarySet.add(ph.untilMs); + } + } + pricingPhaseBoundariesMs = Array.from(boundarySet).sort((a, b) => a - b); + for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k]; Object.assign(PLACEHOLDER_MAP, nextPlaceholders); pricingCatalogRevision += 1; diff --git a/sidecars/panel/backend/proto-wire.mjs b/sidecars/panel/backend/proto-wire.mjs new file mode 100644 index 0000000..ca6c225 --- /dev/null +++ b/sidecars/panel/backend/proto-wire.mjs @@ -0,0 +1,210 @@ +/** + * @fileoverview 零外部依赖的二进制 Protobuf Wire 跳读游标与 `prototext` 字符串反转义原语 (`proto-wire.mjs`)。 + * + * 核心能力: + * 1. 无需引入 `protobufjs`,以 `O(1)` 游标位移跳过大体积定长/变长/Group 载荷; + * 2. 基于 `BigInt` 无损解码 64-bit Varint、`google.protobuf.Timestamp` 纳秒级时间戳与 `Duration`; + * 3. 按原始 UTF-8 字节流无损反转义 `prototext` 的 `\ddd` 八进制、`\xHH` 十六进制与 `\uXXXX` 多字节字符。 + */ + +const protoUtf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null; + +/** + * 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。 + * + * @param {string} raw + * @returns {string} + */ +export function unescapePbtxtString(raw) { + if (typeof raw !== 'string' || !raw) return ''; + if (!raw.includes('\\')) return raw; + const bytes = []; + for (let i = 0; i < raw.length; i++) { + const ch = raw[i]; + if (ch !== '\\' || i + 1 >= raw.length) { + const encoded = Buffer.from(ch, 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + continue; + } + const next = raw[++i]; + if (next >= '0' && next <= '7') { + let oct = next; + if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; + if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i]; + bytes.push(parseInt(oct, 8) & 0xff); + } else if ((next === 'x' || next === 'X') && i + 2 < raw.length) { + const hex = raw.slice(i + 1, i + 3); + if (/^[0-9a-fA-F]{2}$/.test(hex)) { + bytes.push(parseInt(hex, 16)); + i += 2; + } else { + bytes.push(next.charCodeAt(0)); + } + } else if (next === 'u' && i + 4 < raw.length) { + const uHex = raw.slice(i + 1, i + 5); + if (/^[0-9a-fA-F]{4}$/.test(uHex)) { + const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + i += 4; + } else { + bytes.push(next.charCodeAt(0)); + } + } else if (next === 'n') { + bytes.push(0x0a); + } else if (next === 'r') { + bytes.push(0x0d); + } else if (next === 't') { + bytes.push(0x09); + } else { + const encoded = Buffer.from(next, 'utf8'); + for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]); + } + } + return Buffer.from(bytes).toString('utf8'); +} + +export function toUint8Array(raw) { + if (!raw) return null; + if (raw instanceof Uint8Array) return raw; + if (ArrayBuffer.isView(raw)) { + return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength); + } + if (raw instanceof ArrayBuffer) { + return new Uint8Array(raw); + } + return null; +} + +export function decodeUtf8Slice(buf, start, end) { + if (start >= end) return ''; + if (protoUtf8Decoder) { + return protoUtf8Decoder.decode(buf.subarray(start, end)); + } + return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8'); +} + +export function readProtoVarint(buf, state, limit = buf.length) { + if (state.off >= limit) return 0n; + const b0 = buf[state.off]; + if (b0 < 0x80) { + state.off += 1; + return BigInt(b0); + } + let result = 0n; + let shift = 0n; + for (let i = 0; i < 10 && state.off < limit; i++) { + const byte = buf[state.off++]; + result |= BigInt(byte & 0x7f) << shift; + if ((byte & 0x80) === 0) { + return BigInt.asUintN(64, result); + } + shift += 7n; + } + while (state.off < limit && (buf[state.off++] & 0x80) !== 0) { + // 安全排空超长 varint 延续字节 + } + return BigInt.asUintN(64, result); +} + +export function readSubEnd(buf, state, limit = buf.length) { + const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + return Math.min(limit, state.off + len); +} + +export function readProtoString(buf, state, limit = buf.length) { + const end = readSubEnd(buf, state, limit); + const str = decodeUtf8Slice(buf, state.off, end); + state.off = end; + return str; +} + +export function skipProtoField(buf, state, wireType, limit = buf.length) { + if (wireType === 0) { + readProtoVarint(buf, state, limit); + } else if (wireType === 1) { + state.off = Math.min(limit, state.off + 8); + } else if (wireType === 2) { + state.off = readSubEnd(buf, state, limit); + } else if (wireType === 5) { + state.off = Math.min(limit, state.off + 4); + } else if (wireType === 3) { + while (state.off < limit) { + const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit))); + const innerWt = innerTag & 7; + if (innerWt === 4) break; + skipProtoField(buf, state, innerWt, limit); + } + } else if (wireType !== 4) { + state.off = limit; + } +} + +export function decodeProtoTimestampSlice(buf, state, end) { + let seconds = 0n; + let nanos = 0n; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + if (seconds <= 0n || seconds > 253402300799n) return ''; + const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19); + if (nanos > 0n && nanos < 1_000_000_000n) { + const frac = String(nanos).padStart(9, '0').replace(/0+$/, ''); + return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`; + } + return `${baseIso}Z`; +} + +export function decodeProtoDurationSlice(buf, state, end) { + let seconds = 0n; + let nanos = 0n; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 0) { + seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end)); + } else if (fn === 2 && wt === 0) { + nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end)); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + const totalNs = seconds * 1_000_000_000n + nanos; + if (totalNs < 0n) return ''; + if (totalNs === 0n) return '0s'; + const wholeSec = totalNs / 1_000_000_000n; + const remNs = Number(totalNs % 1_000_000_000n); + if (remNs === 0) return `${wholeSec}s`; + const frac = String(remNs).padStart(9, '0').replace(/0+$/, ''); + return `${wholeSec}.${frac}s`; +} + +export function decodeProtoMapStringEntry(buf, state, end) { + let key = ''; + let val = ''; + while (state.off < end) { + const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end))); + const fn = tag >>> 3; + const wt = tag & 7; + if (fn === 1 && wt === 2) { + key = readProtoString(buf, state, end); + } else if (fn === 2 && wt === 2) { + val = readProtoString(buf, state, end); + } else { + skipProtoField(buf, state, wt, end); + } + } + state.off = end; + return [key, val]; +} diff --git a/sidecars/panel/backend/quota-pools.mjs b/sidecars/panel/backend/quota-pools.mjs index f4233fc..47d6729 100644 --- a/sidecars/panel/backend/quota-pools.mjs +++ b/sidecars/panel/backend/quota-pools.mjs @@ -9,7 +9,8 @@ * - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略且存在尚未过期的有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。 */ -import { parseIsoMs } from '../speed-metrics.mjs'; +import { parseIsoMs } from '../trajectory-metrics.mjs'; +import { THIRD_PARTY_POOL_RE } from '../shared/telemetry-display-rules.mjs'; import { isArgonModelIdentifier, isCarbonModelIdentifier, @@ -90,9 +91,6 @@ function classifyOfficialBucketWindow(bucket, _groupBucketCount = 1, nowMs = Dat return 'weekly'; } -const THIRD_PARTY_POOL_RE = - /3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i; - /** * 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。 * 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。 diff --git a/sidecars/panel/backend/settings-schema.mjs b/sidecars/panel/backend/settings-schema.mjs index 9ec2db0..3c6fa79 100644 --- a/sidecars/panel/backend/settings-schema.mjs +++ b/sidecars/panel/backend/settings-schema.mjs @@ -1,158 +1,91 @@ /** - * @fileoverview 用户偏好设置 Schema、枚举常量、默认值与无状态纯函数归一化器。 + * @fileoverview 用户偏好设置完整 Schema、默认对象工厂与带上下文窗口校验的整表归一化器。 * - * 独立于文件系统与运行时状态,统一约束「常规 / 结构 / 其他」三栏偏好结构, - * 并无缝兼容旧版 `settings.json`(如 3 槽固定数组中的 `'none'`、`enableWindowOverlay`、`autoUpdatePlugin` 等)。 + * 所有跨端通用枚举与单项纯函数归一化规则统一源自 `../shared/settings-normalization.mjs`。 */ import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs'; +import { + DEFAULT_HOVER_MODULES, + DEFAULT_OVERVIEW_METRICS, + DEFAULT_OVERVIEW_MODULES, + DEFAULT_POPOVER_WIDTH, + 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, + OVERVIEW_METRIC_KEYS, + OVERVIEW_MODULE_KEYS, + POPOVER_WIDTH_MODES, + STEP_TABLE_COLUMN_KEYS, + STEP_TOKEN_SEGMENT_ALIASES, + SUPPORTED_LANGUAGES, + THEME_ACCENT_KEYS, + TOPBAR_SLOT_KEYS, + normalizeFontScale, + normalizeHoverModules, + normalizeLanguageSetting, + normalizeModelDisplayMode, + normalizeOrchestratorIdMode, + normalizeOverviewMetrics, + normalizeOverviewModules, + normalizePluginUpdateMode, + normalizePopoverWidth, + normalizePopoverWidthMode, + normalizeStandalonePort, + normalizeStepTableColumns, + normalizeStepTokenComboFormat, + normalizeThemeAccent, + normalizeTopbarCapsuleSlots, + normalizeWeeklyLimitMode, + normalizeWindowMountMode, + parseStepTokenComboSegments, +} from '../shared/settings-normalization.mjs'; -export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']); - -export const THEME_ACCENT_KEYS = Object.freeze([ - 'host', - 'blue', - 'emerald', - 'amber', - 'violet', - 'cyan', - 'rose', -]); - -export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']); - -export const TOPBAR_SLOT_KEYS = Object.freeze([ - 'context', - 'tps', - 'ttft', - 'avg_tps', - 'cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'quota_auto', - 'gemini_5h', - 'gemini_weekly', - 'claude_5h', - 'claude_weekly', -]); - -export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); -export const MIN_TOPBAR_SLOTS = 1; -export const MAX_TOPBAR_SLOTS = 5; - -export const OVERVIEW_MODULE_KEYS = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); - -export const DEFAULT_OVERVIEW_MODULES = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); - -export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']); - -export const OVERVIEW_METRIC_KEYS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'context_usage', - 'quota_tightest', -]); - -export const DEFAULT_OVERVIEW_METRICS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', -]); - -export const STEP_TABLE_COLUMN_KEYS = Object.freeze([ - 'step', - 'time', - 'model', - 'tps', - 'ttft', - 'duration', - 'tokens_combo', - 'tokens_io_cache', - 'tokens_custom', - 'input_tokens', - 'cache_tokens', - 'output_tokens', - 'cache', - 'cost', -]); - -export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([ - 'step', - 'model', - 'tps', - 'ttft', - 'tokens_combo', - 'cache', - 'cost', -]); - -export const 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; +export { + DEFAULT_HOVER_MODULES, + DEFAULT_OVERVIEW_METRICS, + DEFAULT_OVERVIEW_MODULES, + DEFAULT_POPOVER_WIDTH, + 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, + OVERVIEW_METRIC_KEYS, + OVERVIEW_MODULE_KEYS, + POPOVER_WIDTH_MODES, + STEP_TABLE_COLUMN_KEYS, + STEP_TOKEN_SEGMENT_ALIASES, + SUPPORTED_LANGUAGES, + THEME_ACCENT_KEYS, + TOPBAR_SLOT_KEYS, + normalizeFontScale, + normalizeHoverModules, + normalizeLanguageSetting, + normalizeModelDisplayMode, + normalizeOrchestratorIdMode, + normalizeOverviewMetrics, + normalizeOverviewModules, + normalizePluginUpdateMode, + normalizePopoverWidth, + normalizePopoverWidthMode, + normalizeStandalonePort, + normalizeStepTableColumns, + normalizeStepTokenComboFormat, + normalizeThemeAccent, + normalizeTopbarCapsuleSlots, + normalizeWeeklyLimitMode, + normalizeWindowMountMode, + parseStepTokenComboSegments, +}; function isSchemaPlainObject(v) { return Boolean(v) && typeof v === 'object' && !Array.isArray(v); @@ -163,302 +96,6 @@ function schemaSanitizePositiveNum(val, fallback) { return Number.isFinite(num) && num > 0 ? num : fallback; } -/** - * 归一化界面语言枚举(默认 `'zh-CN'`,保持与现有界面一致;同时支持 `'auto'` 与 `'en-US'`)。 - * - * @param {unknown} lang - * @returns {'auto'|'zh-CN'|'en-US'} - */ -export function normalizeLanguageSetting(lang) { - const raw = String(lang ?? '').trim(); - if (!raw) return 'zh-CN'; - const lower = raw.toLowerCase(); - if (lower === 'auto' || lower === 'system') return 'auto'; - if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; - if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; - return 'zh-CN'; -} - -/** - * 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。 - * - * @param {unknown} accent - * @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'} - */ -export function normalizeThemeAccent(accent) { - const clean = String(accent ?? '').trim().toLowerCase(); - return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host'; -} - -/** - * 归一化面板字号档位(默认 `'md'` 标准 100%)。 - * - * @param {unknown} scale - * @returns {'sm'|'md'|'lg'|'xl'} - */ -export function normalizeFontScale(scale) { - const clean = String(scale ?? '').trim().toLowerCase(); - return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md'; -} - -/** - * 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏), - * 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。 - * - * @param {unknown} mode - * @param {unknown} [legacyEnableOverlay] - * @returns {'dual'|'composer'|'sidebar'} - */ -export function normalizeWindowMountMode(mode, legacyEnableOverlay) { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'composer' || m === 'input') return 'composer'; - if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar'; - if (m === 'dual' || m === 'topbar') return 'dual'; - if (legacyEnableOverlay === false) return 'sidebar'; - return 'dual'; -} - -/** - * 归一化模型名称展示模式(`'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'`)。 - * - * @param {unknown} mode - * @returns {'compact'|'full'} - */ -export function normalizeOrchestratorIdMode(mode) { - const m = String(mode ?? '').trim().toLowerCase(); - 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'`)。 - * - * @param {unknown} mode - * @param {unknown} [legacyAutoUpdate] - * @returns {'off'|'manual'|'auto'} - */ -export function normalizePluginUpdateMode(mode, legacyAutoUpdate) { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'off' || m === 'manual' || m === 'auto') return m; - if (legacyAutoUpdate === true) return 'auto'; - return 'manual'; -} - -/** - * 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。 - * - * @param {unknown} mode - * @returns {'official'|'custom_tokens'|'custom_cost'} - */ -export function normalizeWeeklyLimitMode(mode) { - const m = String(mode || '').trim().toLowerCase(); - if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens'; - if (m === 'custom_cost' || m === 'cost') return 'custom_cost'; - return 'official'; -} - -/** - * 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeTopbarCapsuleSlots(raw) { - if (!Array.isArray(raw)) { - return [...DEFAULT_TOPBAR_SLOTS]; - } - const seen = new Set(); - const out = []; - for (const item of raw) { - const val = String(item ?? '').trim(); - if (!val || val === 'none') continue; - const mapped = val === 'step_cost' ? 'cost' : val; - if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; - seen.add(mapped); - out.push(mapped); - if (out.length >= MAX_TOPBAR_SLOTS) break; - } - if (out.length < MIN_TOPBAR_SLOTS) { - return ['context']; - } - return out; -} - -/** - * 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeOverviewModules(raw) { - if (!Array.isArray(raw)) { - return [...DEFAULT_OVERVIEW_MODULES]; - } - const seen = new Set(); - const out = []; - for (const item of raw) { - const val = String(item ?? '').trim(); - if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; - seen.add(val); - out.push(val); - if (out.length >= OVERVIEW_MODULE_KEYS.length) break; - } - return out.length > 0 ? out : ['metrics']; -} - -/** - * 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeHoverModules(raw) { - if (!Array.isArray(raw)) { - return [...DEFAULT_HOVER_MODULES]; - } - const seen = new Set(); - const out = []; - for (const item of raw) { - const val = String(item ?? '').trim(); - if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; - seen.add(val); - out.push(val); - if (out.length >= OVERVIEW_MODULE_KEYS.length) break; - } - return out; -} - -/** - * 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeOverviewMetrics(raw) { - if (!Array.isArray(raw)) { - return [...DEFAULT_OVERVIEW_METRICS]; - } - const seen = new Set(); - const out = []; - for (const item of raw) { - const rawVal = String(item ?? '').trim(); - const val = rawVal === 'cost' ? 'step_cost' : rawVal; - if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue; - seen.add(val); - out.push(val); - if (out.length >= 4) break; - } - return out.length > 0 ? out : ['tps']; -} - -/** - * 归一化调用明细「按步查看」表格列配置与左右顺序(2~12 列,默认保留现有 7 列)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeStepTableColumns(raw) { - if (!Array.isArray(raw)) { - return [...DEFAULT_STEP_TABLE_COLUMNS]; - } - const seen = new Set(); - const out = []; - for (const item of raw) { - const val = String(item ?? '').trim(); - if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue; - seen.add(val); - out.push(val); - if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break; - } - if (out.length < 2) { - for (const fallbackCol of ['step', 'model', 'tps']) { - if (!seen.has(fallbackCol)) { - seen.add(fallbackCol); - out.push(fallbackCol); - } - if (out.length >= 2) break; - } - } - return out; -} - export function normalizeModelContextWindows(value) { return Object.fromEntries( Object.entries(isSchemaPlainObject(value) ? value : {}).filter( @@ -467,19 +104,6 @@ export function normalizeModelContextWindows(value) { ); } -/** - * 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。 - * - * @param {unknown} port - * @returns {number} - */ -export function normalizeStandalonePort(port) { - const num = Number(port); - if (!Number.isInteger(num) || num <= 0) return 0; - if (num >= 1024 && num <= 65535) return num; - return 0; -} - export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ language: 'zh-CN', themeAccent: 'host', @@ -517,34 +141,12 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({ */ export function createDefaultSettingsObject() { return { - language: DEFAULT_SETTINGS_SCHEMA.language, - themeAccent: DEFAULT_SETTINGS_SCHEMA.themeAccent, - fontScale: DEFAULT_SETTINGS_SCHEMA.fontScale, - weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget, - weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget, - weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode, - 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, + ...DEFAULT_SETTINGS_SCHEMA, topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS], hoverModules: [...DEFAULT_HOVER_MODULES], overviewModules: [...DEFAULT_OVERVIEW_MODULES], overviewMetrics: [...DEFAULT_OVERVIEW_METRICS], - 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], - contextWindowRiskAccepted: DEFAULT_SETTINGS_SCHEMA.contextWindowRiskAccepted, modelContextWindows: {}, }; } @@ -606,4 +208,3 @@ export function normalizeFullSettings(rawInput) { modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows), }; } - diff --git a/sidecars/panel/backend/sqlite-client.mjs b/sidecars/panel/backend/sqlite-client.mjs new file mode 100644 index 0000000..03da145 --- /dev/null +++ b/sidecars/panel/backend/sqlite-client.mjs @@ -0,0 +1,155 @@ +/** + * @fileoverview 零业务依赖的本地 SQLite + WAL 非阻塞只读短连接原语 (`sqlite-client.mjs`)。 + * + * 核心能力: + * 1. 惰性加载 Node 22.5+ 内置 `node:sqlite`,自动静默实验特性告警,避免污染 CLI / MCP `stdio`; + * 2. 组合主库 `.db` 与 `.db-wal` 的 `mtime + size` 生成复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入; + * 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。 + */ + +import { existsSync, statSync } from 'node:fs'; + +export const SQLITE_IN_CHUNK_SIZE = 400; + +let sqliteResolved = false; +let sqliteDatabaseSyncCtor = null; + +/** + * 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。 + * 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。 + * + * @returns {Function | null} + */ +export function getNodeSqliteDatabaseSync() { + if (typeof globalThis.DatabaseSync === 'function') { + return globalThis.DatabaseSync; + } + if (sqliteResolved) return sqliteDatabaseSyncCtor; + sqliteResolved = true; + if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') { + return null; + } + const origEmitWarning = process.emitWarning; + try { + if (typeof origEmitWarning === 'function') { + process.emitWarning = function filteredSqliteWarning(warning, ...rest) { + const msg = typeof warning === 'string' ? warning : String(warning?.message || ''); + if (/SQLite is an experimental feature/i.test(msg)) return; + return origEmitWarning.call(this, warning, ...rest); + }; + } + const mod = process.getBuiltinModule('node:sqlite'); + sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null; + } catch { + sqliteDatabaseSyncCtor = null; + } finally { + if (typeof origEmitWarning === 'function') { + process.emitWarning = origEmitWarning; + } + } + return sqliteDatabaseSyncCtor; +} + +/** + * 当前运行时是否具备内置 `node:sqlite` 读取能力。 + * + * @returns {boolean} + */ +export function hasBuiltinNodeSqlite() { + return Boolean(getNodeSqliteDatabaseSync()); +} + +/** + * 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。 + * + * @param {string} dbPath + * @returns {{ exists: boolean, mtimeMs: number, sig: string }} + */ +export function computeSqliteWalSig(dbPath) { + if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) { + return { exists: false, mtimeMs: 0, sig: '' }; + } + let dbStat = null; + try { + dbStat = statSync(dbPath); + } catch { + return { exists: false, mtimeMs: 0, sig: '' }; + } + if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' }; + + let walStat = null; + const walPath = `${dbPath}-wal`; + if (existsSync(walPath)) { + try { + walStat = statSync(walPath); + } catch { + walStat = null; + } + } + const dbMtimeMs = Number(dbStat.mtimeMs || 0); + const dbSize = Number(dbStat.size || 0); + const walMtimeMs = Number(walStat?.mtimeMs || 0); + const walSize = Number(walStat?.size || 0); + return { + exists: true, + mtimeMs: Math.max(dbMtimeMs, walMtimeMs), + sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`, + }; +} + +export function isSqliteBusyError(err) { + const msg = String(err?.message || err?.code || ''); + return /SQLITE_BUSY|database is locked/i.test(msg); +} + +/** + * 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。 + * 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。 + * + * @template T + * @param {string} dbPath + * @param {(db: any) => T} queryFn + * @returns {T | null} + */ +export function withReadOnlySqliteDb(dbPath, queryFn) { + const DatabaseSync = getNodeSqliteDatabaseSync(); + if (!DatabaseSync) return null; + for (let attempt = 0; attempt < 2; attempt++) { + let db = null; + try { + db = new DatabaseSync(dbPath, { readOnly: true }); + try { + db.exec('PRAGMA busy_timeout = 1000;'); + } catch { + // 兼容最小测试桩 + } + return queryFn(db); + } catch (err) { + if (attempt === 0 && isSqliteBusyError(err)) { + continue; + } + throw err; + } finally { + if (db) { + try { + db.close(); + } catch { + // 忽略关闭异常 + } + } + } + } + return null; +} + +/** + * 归一化 SQLite `TEXT` 时间列(如 `'2026-11-18 08:12:00+00:00'` -> ISO-8601),剔除零值哨兵时间。 + * + * @param {unknown} value + * @returns {string} + */ +export function normalizeSqliteIsoTime(value) { + const raw = String(value || '').trim(); + if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return ''; + return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z'); +} diff --git a/sidecars/panel/backend/standalone-server.mjs b/sidecars/panel/backend/standalone-server.mjs index 65c3096..250d093 100644 --- a/sidecars/panel/backend/standalone-server.mjs +++ b/sidecars/panel/backend/standalone-server.mjs @@ -356,8 +356,8 @@ export function createStandaloneWebServer(options = {}) { ); } - if (options.lsAddr && options.csrfToken) { - setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false }); + if (options.lsAddr) { + setLsRuntimeEndpoint(options.lsAddr, options.csrfToken || '', { isDynamic: false }); } const expectedCookieVal = token ? deriveCookieValue(token) : ''; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index 5bf3786..0f0716a 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -10,24 +10,27 @@ */ import { isDeepStrictEqual } from 'node:util'; +import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs'; import { extractLiveActivity, parseIsoMs, speedMetric, summarizeSpeed, summarizeTtft, -} from '../speed-metrics.mjs'; +} from '../trajectory-metrics.mjs'; import { CLI_STATUS_SNAPSHOT_FILE, computeRuntimeCodeVersion, + getCachedTrajectory, inFlightRequests, + listCachedTrajectoryEntries, loadSettings, lsRuntimeEndpoint, roundMetric, saveJson, - trajectoryCache, } from './config.mjs'; import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs'; +import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs'; import { enumerateAndSyncConversations } from './local-scanner.mjs'; import { ensureLsEndpointDiscovered } from './ls-discovery.mjs'; import { callLsRpc, getContextModelCatalog, getOfficialQuotaSummary } from './ls-rpc.mjs'; @@ -38,8 +41,9 @@ import { isArgonModelIdentifier, isCarbonModelIdentifier, } from './model-pricing.mjs'; -import { getCloudStatus, pricingCatalogRevision } from './pricing-catalog.mjs'; +import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs'; import { buildOfficialQuotaPools } from './quota-pools.mjs'; +import { getDefaultWindowBridgeStatus } from './window-bridge.mjs'; import { aggregateMultiWindowUsage, buildScopedModelBreakdown, @@ -59,9 +63,10 @@ function roundSessionCost(val) { function findTrajectoryCacheEntry(cascadeId) { if (!cascadeId) return null; - if (trajectoryCache[cascadeId]) return trajectoryCache[cascadeId]; + const entry = getCachedTrajectory(cascadeId); + if (entry) return entry; const targetLower = String(cascadeId).toLowerCase(); - for (const [k, v] of Object.entries(trajectoryCache)) { + for (const [k, v] of listCachedTrajectoryEntries()) { if (k.toLowerCase() === targetLower) return v; } return null; @@ -95,13 +100,13 @@ function readTrajectoryModelFacts(steps) { } /** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */ -function buildKnownUpstreamModelMap(contextLimits, currentAccountName) { +function buildKnownUpstreamModelMap(contextLimits) { const knownUpstreamByModelKey = new Map(); - for (const entry of Object.values(trajectoryCache)) { + for (const [, entry] of listCachedTrajectoryEntries()) { if (!entry?.steps?.length) continue; const facts = readTrajectoryModelFacts(entry.steps); for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model); - if (entry.subagentSpec || (entry.accountName && entry.accountName !== currentAccountName)) continue; + if (entry.subagentSpec) continue; if (facts.limits) { for (const [key, limit] of facts.limits) { const previous = contextLimits.get(key); @@ -186,6 +191,10 @@ function enrichActiveConversationSteps( return { ...serializedStep, responseModel: st.responseModel || '', + hasKnownModel: Boolean(mInfo.modelId && mInfo.modelId !== 'unknown'), + baseModelUpstream: annotatedUpstreamModel, + baseModelLabel: mInfo.label, + baseModelShort: mInfo.shortName, modelUpstream, modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label, modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName, @@ -206,6 +215,7 @@ function enrichActiveConversationSteps( // 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示 let maxTurnIndex = 0; const promptByTurn = new Map(); + const mediaByTurn = new Map(); for (const st of enrichedActiveSteps) { const tIdx = st.turnIndex; if (!Number.isInteger(tIdx) || tIdx <= 0) continue; @@ -213,6 +223,13 @@ function enrichActiveConversationSteps( if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) { promptByTurn.set(tIdx, st.turnPrompt); } + if (st.isTurnStart || !mediaByTurn.has(tIdx)) { + mediaByTurn.set(tIdx, { + cleanPrompt: st.turnPromptClean ?? '', + hasMedia: Boolean(st.turnHasMedia), + mediaOnly: Boolean(st.turnMediaOnly), + }); + } } for (const st of enrichedActiveSteps) { const tIdx = st.turnIndex; @@ -221,11 +238,18 @@ function enrichActiveConversationSteps( st.isTurnStart = false; st.isLatestTurn = false; st.turnPrompt = ''; + st.turnPromptClean = ''; + st.turnHasMedia = false; + st.turnMediaOnly = false; continue; } + const turnMedia = mediaByTurn.get(tIdx); st.isTurnStart = Boolean(st.isTurnStart); st.isLatestTurn = tIdx === maxTurnIndex; st.turnPrompt = promptByTurn.get(tIdx) || ''; + st.turnPromptClean = turnMedia?.cleanPrompt || ''; + st.turnHasMedia = Boolean(turnMedia?.hasMedia); + st.turnMediaOnly = Boolean(turnMedia?.mediaOnly); } const latestEnriched = @@ -265,49 +289,41 @@ function resolveStepOutputTokens(st) { return Number(st?.thinkingTokens || 0) + Number(st?.responseTokens || 0); } -/** - * 使用最大余数法(Hamilton 方法)将各非零上下文分桶等比缩放至目标整数总和, - * 保证 0 值通道绝不被凭空分配 Token,且缩放后各分桶之和精确等于 `targetTotal`。 - */ -function scaleBucketsExact(buckets, keys, targetTotal) { - const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0))); - const out = {}; - let currentSum = 0; - for (const k of keys) { - const val = Math.max(0, Number(buckets[k] || 0)); - out[k] = val; - currentSum += val; +function extractRawBreakdownChannels(breakdown) { + const rawMessages = Number(breakdown?.messagesTokens || 0); + const hasGranularMsgBreakdown = + Boolean(breakdown) && + Object.prototype.hasOwnProperty.call(breakdown, 'toolResultsTokens'); + const channels = { + userInput: hasGranularMsgBreakdown + ? Number(breakdown?.userInputTokens || 0) + : rawMessages, + assistant: Number(breakdown?.assistantTokens || 0), + toolResults: Number(breakdown?.toolResultsTokens || 0), + subagent: Number(breakdown?.subagentTokens || 0), + checkpoint: Number(breakdown?.checkpointTokens || 0), + systemTools: Number(breakdown?.systemToolsTokens || 0), + mcpTools: Number(breakdown?.mcpToolsTokens || 0), + skills: Number(breakdown?.skillsTokens || 0), + systemPrompt: Number(breakdown?.systemPromptTokens || 0), + userRules: Number(breakdown?.userRulesTokens || 0), + }; + const msgSubtotal = + channels.userInput + + channels.assistant + + channels.toolResults + + channels.subagent + + channels.checkpoint; + if (rawMessages > msgSubtotal) { + channels.userInput += rawMessages - msgSubtotal; } - if (safeTarget === 0 || currentSum <= 0) { - for (const k of keys) out[k] = 0; - return out; - } - if (currentSum === safeTarget) { - for (const k of keys) out[k] = Math.round(out[k]); - return out; - } - const remainders = []; - let assigned = 0; - for (const k of keys) { - const rawVal = out[k]; - if (rawVal <= 0) { - out[k] = 0; - continue; - } - const exact = (rawVal * safeTarget) / currentSum; - const floored = Math.floor(exact); - out[k] = floored; - assigned += floored; - remainders.push({ key: k, rem: exact - floored, orig: rawVal }); - } - let diff = safeTarget - assigned; - if (diff > 0 && remainders.length > 0) { - remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig); - for (let i = 0; i < diff; i++) { - out[remainders[i % remainders.length].key] += 1; - } - } - return out; + return channels; +} + +function resolveCompactionSummaryTokens(compactionStep) { + const respTok = Number(compactionStep?.responseTokens || 0); + if (respTok > 0) return respTok; + return resolveStepOutputTokens(compactionStep); } /** @@ -316,7 +332,10 @@ function scaleBucketsExact(buckets, keys, targetTotal) { * `chatStartMetadata.contextWindowMetadata` 记录在步骤请求发送前且基于宿主离线估算器: * 1. 先按该步模型 API 真实计费输入(`inputTokens + cacheReadTokens`)对请求前 10 通道做等比整数对齐,消除离线估算偏差; * 2. 再将该步自身新生成的输出(`outputTokens`)补入 `assistantTokens`,并滚动推进后续无独立拆解的步骤, - * 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致。 + * 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致; + * 3. 当末尾或最近边界为上下文压缩步骤(`isCompactionStep`)且压缩后尚未产生新的 `contextBreakdown` 时, + * 继承压缩前最近一次拆解中的 5 个会话静态通道(`systemPrompt` / `systemTools` / `mcpTools` / `skills` / `userRules`), + * 清空已被折叠的历史对话通道,并将压缩步生成的摘要正文计入 `checkpointTokens`,避免误把压缩前全量输入当作压缩后水位。 * * @param {object[]} enrichedActiveSteps * @param {object|null} latestEnriched @@ -329,85 +348,113 @@ function extractActiveContextTelemetry( sessionInputTokens, sessionCacheReadTokens ) { - let latestBreakdown = latestEnriched?.contextBreakdown || null; - let breakdownIdx = latestBreakdown ? enrichedActiveSteps.length - 1 : -1; - if (!latestBreakdown && !latestEnriched?.isCompactionStep) { - for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { - if (enrichedActiveSteps[i]?.isCompactionStep) { - break; + let lastCompactionIdx = -1; + for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) { + if (enrichedActiveSteps[i]?.isCompactionStep) { + lastCompactionIdx = i; + break; + } + } + + let latestBreakdown = null; + let breakdownIdx = -1; + for (let i = enrichedActiveSteps.length - 1; i > lastCompactionIdx; i--) { + if (enrichedActiveSteps[i]?.contextBreakdown) { + latestBreakdown = enrichedActiveSteps[i].contextBreakdown; + breakdownIdx = i; + break; + } + } + + let channels = extractRawBreakdownChannels(latestBreakdown); + let fallbackPreCompactionLimit = 0; + + if (latestBreakdown && breakdownIdx > lastCompactionIdx) { + const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0); + if (rawBreakdownTotal > 0) { + const bdStep = enrichedActiveSteps[breakdownIdx]; + const bdPromptTokens = + Number(bdStep?.inputTokens || 0) + Number(bdStep?.cacheReadTokens || 0); + const bdOutTokens = resolveStepOutputTokens(bdStep); + // 仅当模型 API 返回了完整的请求级输入(排除省略 cacheReadTokens 的残缺网关或极小合成桩数据)时对齐至真实分词口径 + if (bdPromptTokens >= rawBreakdownTotal * 0.5) { + channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, bdPromptTokens); + channels.assistant += bdOutTokens; + let runningTotal = bdPromptTokens + bdOutTokens; + + for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) { + const stepM = enrichedActiveSteps[m]; + if (!stepM || stepM.isCompactionStep) break; + const mPrompt = + Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); + const mOut = resolveStepOutputTokens(stepM); + if (mPrompt >= runningTotal * 0.5) { + if (mPrompt > runningTotal) { + const delta = mPrompt - runningTotal; + if (enrichedActiveSteps[m - 1]?.hasToolCalls) { + channels.toolResults += delta; + } else { + channels.userInput += delta; + } + } else if (mPrompt < runningTotal) { + channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt); + } + channels.assistant += mOut; + runningTotal = mPrompt + mOut; + } + } } + } + } else if (lastCompactionIdx >= 0) { + const compactionStep = enrichedActiveSteps[lastCompactionIdx]; + let preStep = null; + for (let i = lastCompactionIdx - 1; i >= 0; i--) { if (enrichedActiveSteps[i]?.contextBreakdown) { - latestBreakdown = enrichedActiveSteps[i].contextBreakdown; - breakdownIdx = i; + preStep = enrichedActiveSteps[i]; break; } } - } - const rawMessages = Number(latestBreakdown?.messagesTokens || 0); - const hasGranularMsgBreakdown = - Boolean(latestBreakdown) && - Object.prototype.hasOwnProperty.call(latestBreakdown, 'toolResultsTokens'); - let channels = { - userInput: hasGranularMsgBreakdown - ? Number(latestBreakdown?.userInputTokens || 0) - : rawMessages, - assistant: Number(latestBreakdown?.assistantTokens || 0), - toolResults: Number(latestBreakdown?.toolResultsTokens || 0), - subagent: Number(latestBreakdown?.subagentTokens || 0), - checkpoint: Number(latestBreakdown?.checkpointTokens || 0), - systemTools: Number(latestBreakdown?.systemToolsTokens || 0), - mcpTools: Number(latestBreakdown?.mcpToolsTokens || 0), - skills: Number(latestBreakdown?.skillsTokens || 0), - systemPrompt: Number(latestBreakdown?.systemPromptTokens || 0), - userRules: Number(latestBreakdown?.userRulesTokens || 0), - }; - const msgSubtotal = - channels.userInput + - channels.assistant + - channels.toolResults + - channels.subagent + - channels.checkpoint; - if (rawMessages > msgSubtotal) { - channels.userInput += rawMessages - msgSubtotal; - } - const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0); + if (preStep) { + fallbackPreCompactionLimit = Number(preStep.maxContextBudgetTokens || 0); + let preChannels = extractRawBreakdownChannels(preStep.contextBreakdown); + const preRawTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + preChannels[k], 0); + const prePromptTokens = + Number(preStep.inputTokens || 0) + Number(preStep.cacheReadTokens || 0); + if (preRawTotal > 0 && prePromptTokens >= preRawTotal * 0.5) { + preChannels = scaleBucketsExact(preChannels, CONTEXT_CHANNEL_KEYS, prePromptTokens); + } + channels.systemTools = preChannels.systemTools; + channels.mcpTools = preChannels.mcpTools; + channels.skills = preChannels.skills; + channels.systemPrompt = preChannels.systemPrompt; + channels.userRules = preChannels.userRules; + } + channels.userInput = 0; + channels.assistant = 0; + channels.toolResults = 0; + channels.subagent = 0; + channels.checkpoint = resolveCompactionSummaryTokens(compactionStep); - if ( - latestBreakdown && - breakdownIdx >= 0 && - !latestEnriched?.isCompactionStep && - rawBreakdownTotal > 0 - ) { - const bdStep = enrichedActiveSteps[breakdownIdx]; - const bdPromptTokens = - Number(bdStep?.inputTokens || 0) + Number(bdStep?.cacheReadTokens || 0); - const bdOutTokens = resolveStepOutputTokens(bdStep); - // 仅当模型 API 返回了完整的请求级输入(排除省略 cacheReadTokens 的残缺网关或极小合成桩数据)时对齐至真实分词口径 - if (bdPromptTokens >= rawBreakdownTotal * 0.5) { - channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, bdPromptTokens); - channels.assistant += bdOutTokens; - let runningTotal = bdPromptTokens + bdOutTokens; - - for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) { - const stepM = enrichedActiveSteps[m]; - if (!stepM || stepM.isCompactionStep) break; - const mPrompt = - Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); - const mOut = resolveStepOutputTokens(stepM); - if (mPrompt >= runningTotal * 0.5) { - if (mPrompt > runningTotal) { - const delta = mPrompt - runningTotal; - if (enrichedActiveSteps[m - 1]?.hasToolCalls) { - channels.toolResults += delta; - } else { - channels.userInput += delta; - } - } else if (mPrompt < runningTotal) { - channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt); + let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0); + for (let m = lastCompactionIdx + 1; m < enrichedActiveSteps.length; m++) { + const stepM = enrichedActiveSteps[m]; + if (!stepM || stepM.isCompactionStep) continue; + const mPrompt = + Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0); + const mOut = resolveStepOutputTokens(stepM); + if (mPrompt > 0 && (runningTotal === 0 || mPrompt >= runningTotal * 0.35)) { + if (mPrompt > runningTotal) { + const delta = mPrompt - runningTotal; + if (m > lastCompactionIdx + 1 && enrichedActiveSteps[m - 1]?.hasToolCalls) { + channels.toolResults += delta; + } else { + channels.userInput += delta; } - channels.assistant += mOut; - runningTotal = mPrompt + mOut; + } else if (mPrompt < runningTotal) { + channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt); } + channels.assistant += mOut; + runningTotal = mPrompt + mOut; } } } @@ -427,17 +474,25 @@ function extractActiveContextTelemetry( const ctxBreakdownTotal = ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules; + const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep); const ctxCached = latestEnriched?.cacheReadTokens || 0; const ctxFreshInput = latestEnriched?.inputTokens || 0; const ctxThinking = latestEnriched?.thinkingTokens || 0; const ctxResponse = latestEnriched?.responseTokens || 0; const ctxOut = resolveStepOutputTokens(latestEnriched); - const ctxTotal = - ctxBreakdownTotal > 0 ? ctxBreakdownTotal : ctxCached + ctxFreshInput + ctxOut; - const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000); - const compactionUsedTokens = Number( - ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput + const ctxTotal = isLatestCompaction + ? ctxBreakdownTotal + : ctxBreakdownTotal > 0 + ? ctxBreakdownTotal + : ctxCached + ctxFreshInput + ctxOut; + const compactionLimitTokens = Number( + (isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0 + ? fallbackPreCompactionLimit + : latestEnriched?.maxContextBudgetTokens) || 256000 ); + const compactionUsedTokens = isLatestCompaction + ? Number(ctxTotal) + : Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput); const compactionUsedPct = compactionLimitTokens > 0 ? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1)) @@ -509,10 +564,15 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re /** * 构建单个代理(主代理或子代理)的标准遥测单元对象。 */ -function buildAgentUnitTelemetry({ +export function buildAgentUnitTelemetry({ agentId, cascadeId, isMain, + isSideQuestion = false, + sideIndex = 0, + agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent', + agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0, + customRole = '', index, shortLabel, badgeText, @@ -535,11 +595,15 @@ function buildAgentUnitTelemetry({ { agentId, agentCascadeId: cascadeId, + agentKind, + agentOrdinal, + agentCustomRole: customRole, agentLabel, agentBadge: badgeText, agentRole: role, agentIndex: index, isSubagent: !isMain, + ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), }, reuseInputs ); @@ -561,6 +625,10 @@ function buildAgentUnitTelemetry({ agentId, cascadeId, isMain, + agentKind, + agentOrdinal, + customRole, + ...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}), index, shortLabel, badgeText, @@ -592,6 +660,9 @@ function buildAgentUnitTelemetry({ : 0, latestCacheHitPct: ctxRes.latestCacheHitPct, sessionCacheHitPct: ctxRes.sessionCacheHitPct, + hasKnownModel: Boolean(enrichedRes.latestEnriched?.hasKnownModel), + activeBaseModelShort: enrichedRes.latestEnriched?.baseModelShort || '', + activeBaseModelLabel: enrichedRes.latestEnriched?.baseModelLabel || '', activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知', activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知', activeModelUpstream: @@ -607,14 +678,20 @@ function buildAgentUnitTelemetry({ } async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) { + const localSummaries = readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh }); const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([ - callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), + localSummaries.available + ? Promise.resolve(null) + : callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})), userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null, getContextModelCatalog(), ]); const sessions = await enumerateAndSyncConversations({ - summariesObj: allTrajRes?.trajectorySummaries || {}, + summariesObj: localSummaries.available + ? localSummaries.summariesObj + : allTrajRes?.trajectorySummaries || {}, + sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {}, currentAccountName: accountScope, requestedConvId, forceRefresh: forceQuotaRefresh, @@ -696,12 +773,16 @@ export async function buildTelemetryPayloadInternal( // 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总 const reportedContextLimits = new Map(); - const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName); + const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits); const activeEntry = findTrajectoryCacheEntry(activeCascadeId); const activeSteps = activeEntry?.steps || []; const subagentSummaries = activeConvSummary?.subagents || []; if (subagentSummaries.length) lastMainPreparation = null; - const modelInputs = { catalogRevision: pricingCatalogRevision, dynamicModelMap }; + const modelInputs = { + catalogRevision: pricingCatalogRevision, + phaseEpoch: getPricingPhaseEpoch(), + dynamicModelMap, + }; const mainUnit = buildAgentUnitTelemetry({ agentId: 'main', cascadeId: activeCascadeId, @@ -747,6 +828,8 @@ export async function buildTelemetryPayloadInternal( let totalFamilyCacheReadTokens = sessionCacheReadTokens; let totalFamilyOutputTokens = sessionOutputTokens; + let normalSubCount = 0; + let sideQuestionCount = 0; for (let idx = 0; idx < subagentSummaries.length; idx++) { const subSum = subagentSummaries[idx]; const subCid = subSum.cascadeId; @@ -756,24 +839,65 @@ export async function buildTelemetryPayloadInternal( for (const step of subRawSteps) allCombinedRawSteps.push(step); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; + const isSideQ = Boolean( + subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question' + ); const rawRole = subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || ''; const subIndex = idx + 1; - const shortLabel = `子代理 #${subIndex}`; - const badgeText = `子${subIndex}`; - const roleLabel = rawRole || '子代理'; - const typeName = subSpec?.typeName || ''; + let sideIndex = 0; + let agentKind = 'subagent'; + let agentOrdinal = 0; + let customRole = ''; + let shortLabel = ''; + let badgeText = ''; + let roleLabel = ''; + let typeName = ''; + let agentLabel = ''; + if (isSideQ) { + sideIndex = ++sideQuestionCount; + agentKind = 'side_question'; + agentOrdinal = sideIndex; + shortLabel = `旁路提问 #${sideIndex}`; + badgeText = `旁${sideIndex}`; + const cleanSideRole = + rawRole && + rawRole !== '旁路提问' && + rawRole !== 'Side Question' && + rawRole !== 'side_question' + ? rawRole + : ''; + customRole = cleanSideRole; + roleLabel = cleanSideRole || '旁路提问'; + typeName = 'side_question'; + agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel; + } else { + const subOrd = ++normalSubCount; + agentKind = 'subagent'; + agentOrdinal = subOrd; + customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : ''; + shortLabel = `子代理 #${subOrd}`; + badgeText = `子${subOrd}`; + roleLabel = rawRole || '子代理'; + typeName = subSpec?.typeName || ''; + agentLabel = rawRole ? `${shortLabel} · ${rawRole}` : shortLabel; + } const subUnit = buildAgentUnitTelemetry({ agentId: subCid, cascadeId: subCid, isMain: false, + isSideQuestion: isSideQ, + sideIndex, + agentKind, + agentOrdinal, + customRole, index: subIndex, shortLabel, badgeText, role: roleLabel, typeName, - agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel, + agentLabel, status: subSum.status || 'IDLE', rawSteps: subRawSteps, liveActivity: subSum.liveActivity || null, @@ -817,6 +941,9 @@ export async function buildTelemetryPayloadInternal( turnIndex: tIdx, startMs: mSt.createdAtMs || 0, prompt: mSt.turnPrompt || '', + cleanPrompt: mSt.turnPromptClean ?? '', + hasMedia: Boolean(mSt.turnHasMedia), + mediaOnly: Boolean(mSt.turnMediaOnly), }); } } @@ -843,6 +970,9 @@ export async function buildTelemetryPayloadInternal( st.rootTurnIndex = matched.turnIndex; st.isRootLatestTurn = matched.turnIndex === maxRootTurn; st.rootTurnPrompt = matched.prompt || ''; + st.rootTurnPromptClean = matched.cleanPrompt ?? ''; + st.rootTurnHasMedia = Boolean(matched.hasMedia); + st.rootTurnMediaOnly = Boolean(matched.mediaOnly); if (!seenRootStarts.has(matched.turnIndex)) { seenRootStarts.add(matched.turnIndex); st.isRootTurnStart = true; @@ -878,6 +1008,31 @@ export async function buildTelemetryPayloadInternal( .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || latestActiveAgent; + // 汇总视图与自动跟随上下文始终锁定主线(主代理与常规子代理),防止旁路提问抽屉篡改主会话 10 通道上下文水位 + const mainlineAgents = allAgents.filter((a) => !a.isSideQuestion); + const activeMainlineAgent = !latestActiveAgent.isSideQuestion + ? latestActiveAgent + : mainlineAgents.find((a) => a.isRunning) || + mainlineAgents + .slice() + .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || + mainAgentTelemetry; + const mainlineWithSteps = mainlineAgents.filter((a) => a.stepCount > 0); + const contextMetricAgent = !latestMetricAgent.isSideQuestion + ? latestMetricAgent + : mainlineWithSteps.find((a) => a.isRunning) || + mainlineWithSteps + .slice() + .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] || + mainAgentTelemetry; + + const aggregatedRoleLabel = + normalSubCount > 0 && sideQuestionCount > 0 + ? `主代理 + ${normalSubCount} 子代理 + ${sideQuestionCount} 旁问` + : sideQuestionCount > 0 + ? `主代理 + ${sideQuestionCount} 旁路提问` + : `主代理 + ${subAgentTelemetries.length} 子代理`; + const totalCostUsd = roundSessionCost(totalRawSessionCostUsd); const totalUnpricedCalls = allAgents.reduce( (sum, a) => sum + (a.sessionUnpricedCalls || 0), @@ -899,11 +1054,16 @@ export async function buildTelemetryPayloadInternal( ? { ...activeActivityAgent.liveActivity, agentId: activeActivityAgent.agentId, + agentKind: activeActivityAgent.agentKind || (activeActivityAgent.isMain ? 'main' : activeActivityAgent.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: activeActivityAgent.agentOrdinal || 0, agentBadge: activeActivityAgent.badgeText, agentShortLabel: activeActivityAgent.shortLabel, agentRole: activeActivityAgent.role, agentIndex: activeActivityAgent.index, isMain: Boolean(activeActivityAgent.isMain), + ...(activeActivityAgent.isSideQuestion + ? { isSideQuestion: true, sideIndex: activeActivityAgent.sideIndex || 0 } + : {}), parallelCount: runningSubs.length > 1 ? runningSubs.length : 1, } : null; @@ -912,15 +1072,19 @@ export async function buildTelemetryPayloadInternal( agentId: 'all', cascadeId: activeCascadeId, isMain: false, + agentKind: 'all', + agentOrdinal: 0, index: -1, shortLabel: '全部汇总', badgeText: '全部', - role: `主代理 + ${subAgentTelemetries.length} 子代理`, + role: aggregatedRoleLabel, typeName: 'all', - activeAgentId: latestActiveAgent.agentId, - activeAgentShortLabel: latestActiveAgent.shortLabel, - activeAgentBadge: latestActiveAgent.badgeText, - activeAgentRole: latestActiveAgent.role, + activeAgentId: activeMainlineAgent.agentId, + activeAgentKind: activeMainlineAgent.agentKind || (activeMainlineAgent.isMain ? 'main' : activeMainlineAgent.isSideQuestion ? 'side_question' : 'subagent'), + activeAgentOrdinal: activeMainlineAgent.agentOrdinal || 0, + activeAgentShortLabel: activeMainlineAgent.shortLabel, + activeAgentBadge: activeMainlineAgent.badgeText, + activeAgentRole: activeMainlineAgent.role, isRunning: allAgents.some((a) => a.isRunning), status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE', liveActivity: aggregatedLiveActivity, @@ -941,10 +1105,13 @@ export async function buildTelemetryPayloadInternal( latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0, latestCacheHitPct: latestMetricAgent.latestCacheHitPct, sessionCacheHitPct: combinedSessionCacheHitPct, + hasKnownModel: Boolean(latestMetricAgent.hasKnownModel), + activeBaseModelShort: latestMetricAgent.activeBaseModelShort || '', + activeBaseModelLabel: latestMetricAgent.activeBaseModelLabel || '', activeModelShort: latestMetricAgent.activeModelShort, activeModelLabel: latestMetricAgent.activeModelLabel, activeModelUpstream: latestMetricAgent.activeModelUpstream, - context: latestMetricAgent.context, + context: contextMetricAgent.context, modelBreakdown: combinedModelBreakdown, lastModifiedMs: latestActiveAgent.lastModifiedMs, }; @@ -1036,6 +1203,7 @@ export async function buildTelemetryPayloadInternal( currentYear, monthlySeries, weekBucket, + quotaWeekBucket, modelBreakdown, poolCycleStats, poolsWeeklySummary, @@ -1192,34 +1360,8 @@ export async function buildTelemetryPayloadInternal( let contextUsedPct = null; if (lastRootStep) { - const limitTokens = Number(lastRootStep.maxContextBudgetTokens || 256000); - const cb = lastRootStep.contextBreakdown; - const cbTotal = cb - ? Number(cb.messagesTokens || 0) + - Number(cb.systemToolsTokens || 0) + - Number(cb.mcpToolsTokens || 0) + - Number(cb.skillsTokens || 0) + - Number(cb.systemPromptTokens || 0) + - Number(cb.userRulesTokens || 0) - : 0; - const apiPrompt = - Number(lastRootStep.inputTokens || 0) + Number(lastRootStep.cacheReadTokens || 0); - const apiOut = resolveStepOutputTokens(lastRootStep); - const fallbackTotal = apiPrompt + apiOut; - const estTotal = Math.max(cbTotal, Number(lastRootStep.estimatedContextTokens || 0)); - const hasAlignedApiPrompt = - !lastRootStep.isCompactionStep && - apiPrompt > 0 && - (estTotal === 0 || apiPrompt >= estTotal * 0.5); - const usedTokens = Number( - hasAlignedApiPrompt - ? fallbackTotal - : cbTotal > 0 - ? cbTotal - : lastRootStep.estimatedContextTokens || fallbackTotal - ); - contextUsedPct = - limitTokens > 0 ? Math.min(100, +((usedTokens / limitTokens) * 100).toFixed(1)) : 0; + contextUsedPct = extractActiveContextTelemetry(rootSteps, lastRootStep, 0, 0).context + .compactionUsedPct; } let modelShort = ''; @@ -1269,10 +1411,15 @@ export async function buildTelemetryPayloadInternal( const rootFallbackMs = rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; + let runNormalSubIdx = 0; + let runSideIdx = 0; const subItems = rawSubs.map((subSum, idx) => { const subCid = subSum.cascadeId; const subEntry = findTrajectoryCacheEntry(subCid); const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; + const isSideQ = Boolean( + subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question' + ); const rawRole = subSpec?.role || subSum.agentScriptName || @@ -1280,9 +1427,37 @@ export async function buildTelemetryPayloadInternal( subSpec?.typeName || ''; const subIndex = idx + 1; - const badgeText = `子${subIndex}`; - const shortLabel = `子代理 #${subIndex}`; - const role = rawRole || shortLabel; + let sideIndex = 0; + let agentKind = 'subagent'; + let agentOrdinal = 0; + let customRole = ''; + let badgeText = ''; + let shortLabel = ''; + let role = ''; + if (isSideQ) { + sideIndex = ++runSideIdx; + agentKind = 'side_question'; + agentOrdinal = sideIndex; + badgeText = `旁${sideIndex}`; + shortLabel = `旁路提问 #${sideIndex}`; + const cleanSide = + rawRole && + rawRole !== '旁路提问' && + rawRole !== 'Side Question' && + rawRole !== 'side_question' + ? rawRole + : ''; + customRole = cleanSide; + role = cleanSide || shortLabel; + } else { + const nOrd = ++runNormalSubIdx; + agentKind = 'subagent'; + agentOrdinal = nOrd; + customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : ''; + badgeText = `子${nOrd}`; + shortLabel = `子代理 #${nOrd}`; + role = rawRole || shortLabel; + } const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING'; const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0); const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0; @@ -1290,6 +1465,9 @@ export async function buildTelemetryPayloadInternal( ? subSum.liveActivity || extractLiveActivity([], true, subModMs) : { phase: 'done', + actionKey: 'done', + waitingApproval: false, + detailKey: '', label: '已完成', detail: '', stepProgress: '', @@ -1299,10 +1477,14 @@ export async function buildTelemetryPayloadInternal( return { cascadeId: subCid, index: subIndex, + agentKind, + agentOrdinal, + customRole, + ...(isSideQ ? { isSideQuestion: true, sideIndex } : {}), badgeText, shortLabel, role, - typeName: subSpec?.typeName || '', + typeName: isSideQ ? 'side_question' : subSpec?.typeName || '', isRunning: isSubRunning, status: subSum.status || 'IDLE', stepCount, @@ -1318,14 +1500,18 @@ export async function buildTelemetryPayloadInternal( const runningSubCount = subItems.filter((s) => s.isRunning).length; if ( isMainRunning && - (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') && + (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') && runningSubCount === 0 ) { const pendingIndex = subItems.length + 1; - const pendingRole = mainLiveAct.detail || '子代理'; + const pendingCustomRole = mainLiveAct.detail || ''; + const pendingRole = pendingCustomRole || '子代理'; subItems.push({ cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`, index: pendingIndex, + agentKind: 'subagent', + agentOrdinal: pendingIndex, + customRole: pendingCustomRole, badgeText: `子${pendingIndex}`, shortLabel: `子代理 #${pendingIndex}`, role: pendingRole, @@ -1336,6 +1522,9 @@ export async function buildTelemetryPayloadInternal( lastModifiedMs: rootFallbackMs, liveActivity: { phase: 'thinking', + actionKey: 'starting', + waitingApproval: false, + detailKey: '', label: '启动中', detail: '', stepProgress: '', @@ -1351,8 +1540,11 @@ export async function buildTelemetryPayloadInternal( (runningSubList.length > 0 ? { phase: 'waiting', + actionKey: 'waiting_subagent', + waitingApproval: false, + detailKey: '', label: '等待子代理', - detail: runningSubList.map((s) => s.role).join(', '), + detail: runningSubList.map((s) => s.customRole || s.role).join(', '), stepProgress: '', startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs, signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`, @@ -1385,9 +1577,12 @@ export async function buildTelemetryPayloadInternal( }); } + const officialFallbackWeekBucket = quotaWeekBucket || weekBucket; const finalPayload = { timestamp: new Date().toISOString(), + hostPlatform: process.platform || 'unknown', uiBundleVersion, + windowBridge: getDefaultWindowBridgeStatus(), settings, contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => { const latest = group.members.reduce((previous, id) => { @@ -1460,6 +1655,9 @@ export async function buildTelemetryPayloadInternal( : 0, latestCacheHitPct, sessionCacheHitPct, + hasKnownModel: Boolean(latestEnriched?.hasKnownModel), + activeBaseModelShort: latestEnriched?.baseModelShort || '', + activeBaseModelLabel: latestEnriched?.baseModelLabel || '', activeModelShort: latestEnriched?.modelShort || '模型未知', activeModelLabel: latestEnriched?.modelLabel || '模型未知', activeModelUpstream: @@ -1505,19 +1703,26 @@ export async function buildTelemetryPayloadInternal( title: isCustomWeeklyMode ? '每周限额 (自定义本机)' : `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`, - calls: !isCustomWeeklyMode && poolsWeeklySummary ? poolsWeeklySummary.calls : weekBucket.calls, - tokens: - !isCustomWeeklyMode && poolsWeeklySummary + calls: isCustomWeeklyMode + ? weekBucket.calls + : poolsWeeklySummary + ? poolsWeeklySummary.calls + : officialFallbackWeekBucket.calls, + tokens: isCustomWeeklyMode + ? weekBucket.totalTokens + : poolsWeeklySummary ? poolsWeeklySummary.tokens - : weekBucket.totalTokens, - costUsd: - !isCustomWeeklyMode && poolsWeeklySummary + : officialFallbackWeekBucket.totalTokens, + costUsd: isCustomWeeklyMode + ? weekBucket.costUsd + : poolsWeeklySummary ? poolsWeeklySummary.costUsd - : weekBucket.costUsd, - unpricedCalls: - !isCustomWeeklyMode && poolsWeeklySummary + : officialFallbackWeekBucket.costUsd, + unpricedCalls: isCustomWeeklyMode + ? weekBucket.unpricedCalls + : poolsWeeklySummary ? poolsWeeklySummary.unpricedCalls - : weekBucket.unpricedCalls, + : officialFallbackWeekBucket.unpricedCalls, usedPct: weeklyUsedPct, remainingPct: weeklyRemainingPct, remainingIntPct: weeklyRemainingIntPct, diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 4611116..2cf9c5b 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -13,8 +13,8 @@ import { createSpeedAccumulator, finishSpeed, parseIsoMs, -} from '../speed-metrics.mjs'; -import { roundMetric, trajectoryCache } from './config.mjs'; +} from '../trajectory-metrics.mjs'; +import { listCachedTrajectoryEntries, roundMetric } from './config.mjs'; import { loadExternalDeepStatsCache } from './local-scanner.mjs'; import { computeStepCost, @@ -30,6 +30,10 @@ function safeTok(val) { return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0; } +function normalizeOwnerAccount(val) { + return typeof val === 'string' ? val.trim().toLowerCase() : ''; +} + /** * 获取本地当日 00:00:00.000 的毫秒时间戳。 * @@ -399,7 +403,8 @@ function sameUsageEntries(previous, current) { return previous.length === current.length && current.every((entry, index) => { const before = previous[index]; return entry.steps === before.steps && entry.cascadeId === before.cascadeId && - entry.appSource === before.appSource && entry.isCurrentConv === before.isCurrentConv; + entry.appSource === before.appSource && entry.accountName === before.accountName && + entry.isCurrentConv === before.isCurrentConv; }); } @@ -515,6 +520,9 @@ export function aggregateMultiWindowUsage({ const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon'); const hasDedicatedArgonPool = poolCycleBuckets.has('Argon'); const poolByModel = new Map(); + const quotaWeekBucket = createUsageBucket(); + const normalizedQuotaAccount = + currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName); const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket(); const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket(); const perModelStats = new Map(); @@ -523,6 +531,11 @@ export function aggregateMultiWindowUsage({ let latestSelectedStepMs = 0; const currentYear = new Date(nowMs).getFullYear(); + const monthBoundsMs = Array.from({ length: 13 }, (_, idx) => + new Date(currentYear, idx, 1).getTime() + ); + const yearStartMs = monthBoundsMs[0]; + const nextYearStartMs = monthBoundsMs[12]; const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({ month: idx + 1, label: `${idx + 1}月`, @@ -545,7 +558,7 @@ export function aggregateMultiWindowUsage({ // 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费 const allLiveByLower = new Map(); - for (const [rawId, entry] of Object.entries(trajectoryCache)) { + for (const [rawId, entry] of listCachedTrajectoryEntries()) { const cidLower = String(rawId || '').toLowerCase(); if (!cidLower || !entry || typeof entry !== 'object') continue; const prev = allLiveByLower.get(cidLower); @@ -558,15 +571,6 @@ export function aggregateMultiWindowUsage({ for (const ext of externalConvos.values()) { const extCidLower = String(ext?.cascadeId || '').toLowerCase(); if (!extCidLower) continue; - const knownLive = allLiveByLower.get(extCidLower); - const ownerAccount = ext.accountName || knownLive?.accountName || ''; - if ( - ownerAccount && - currentAccountName !== '' && - ownerAccount !== currentAccountName - ) { - continue; - } const prevExt = externalByCid.get(extCidLower); if (!prevExt || (ext.steps?.length || 0) > (prevExt.steps?.length || 0)) { externalByCid.set(extCidLower, ext); @@ -576,13 +580,6 @@ export function aggregateMultiWindowUsage({ const allEntriesToAggregate = []; for (const [cidLower, entry] of allLiveByLower.entries()) { - if ( - entry?.accountName && - currentAccountName !== '' && - entry.accountName !== currentAccountName - ) { - continue; - } const extMatch = externalByCid.get(cidLower); if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) { continue; @@ -593,6 +590,7 @@ export function aggregateMultiWindowUsage({ allEntriesToAggregate.push({ cascadeId: groupCascadeId, appSource: entry?.appSource || 'standalone', + accountName: entry?.accountName || extMatch?.accountName || '', steps: entry?.steps || [], isCurrentConv: familySet.has(cidLower), }); @@ -606,6 +604,7 @@ export function aggregateMultiWindowUsage({ allEntriesToAggregate.push({ cascadeId: extCidLower, appSource: ext.appSource || 'ide', + accountName: ext.accountName || liveEntry?.accountName || '', steps: ext.steps || [], isCurrentConv: familySet.has(extCidLower), }); @@ -619,7 +618,9 @@ export function aggregateMultiWindowUsage({ const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows]; const snapshot = lastUsageSnapshot; const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone && - currentYear === snapshot.currentYear && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && + currentYear === snapshot.currentYear && + normalizedQuotaAccount === snapshot.normalizedQuotaAccount && + modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision && isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) && sameUsageEntries(snapshot.entries, allEntriesToAggregate); const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null; @@ -640,11 +641,19 @@ export function aggregateMultiWindowUsage({ for (const entry of allEntriesToAggregate) { const { cascadeId, isCurrentConv } = entry; + const entryOwner = normalizeOwnerAccount(entry.accountName); const srcKey = entry.appSource || 'standalone'; const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`; for (const st of entry.steps || []) { if (!st || typeof st !== 'object') continue; + const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner; + const includeInQuotaPools = + normalizedQuotaAccount === null + ? false + : normalizedQuotaAccount === '' + ? true + : stepOwner === normalizedQuotaAccount; const mInfo = resolveStepModel(st); const inTok = safeTok(st.inputTokens); const cacheTok = safeTok(st.cacheReadTokens); @@ -665,21 +674,25 @@ export function aggregateMultiWindowUsage({ const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens, resolvedCost, savedCost, unpriced }; - if (tMs > 0) { - const stepDate = new Date(tMs); - if (stepDate.getFullYear() === currentYear) { - const mBucket = monthlySeries[stepDate.getMonth()]; - if (mBucket) { - mBucket.calls += 1; - mBucket.inputTokens += inTok; - mBucket.cacheReadTokens += cacheTok; - mBucket.responseTokens += respTok; - mBucket.thinkingTokens += thinkTok; - mBucket.totalTokens += stepTotalTokens; - mBucket.costUsd += resolvedCost; - mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; + if (tMs >= yearStartMs && tMs < nextYearStartMs) { + let monthIdx = 11; + for (let m = 0; m < 12; m++) { + if (tMs < monthBoundsMs[m + 1]) { + monthIdx = m; + break; } } + const mBucket = monthlySeries[monthIdx]; + if (mBucket) { + mBucket.calls += 1; + mBucket.inputTokens += inTok; + mBucket.cacheReadTokens += cacheTok; + mBucket.responseTokens += respTok; + mBucket.thinkingTokens += thinkTok; + mBucket.totalTokens += stepTotalTokens; + mBucket.costUsd += resolvedCost; + mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced; + } } for (const k of presetKeys) { @@ -689,10 +702,13 @@ export function aggregateMultiWindowUsage({ if (isCurrentConv) { accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId); } + if (k === 'week' && includeInQuotaPools) { + accumulateStepIntoBucket(quotaWeekBucket, stepUsage, cascadeId); + } } } - if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) { + if (includeInQuotaPools && poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) { let cachedPool = poolByModel.get(mInfo); if (!cachedPool || cachedPool.key !== st.modelKey || cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) { @@ -952,6 +968,7 @@ export function aggregateMultiWindowUsage({ const todayBucket = finalizedPresets.today.account; const weekBucket = finalizedPresets.week.account; + const finalizedQuotaWeekBucket = finalizeUsageBucket(quotaWeekBucket); const modelBreakdown = finalizeModelBreakdownMap(perModelStats); const formatCycleSummary = (b) => { @@ -1005,6 +1022,7 @@ export function aggregateMultiWindowUsage({ monthlySeries, todayBucket, weekBucket, + quotaWeekBucket: finalizedQuotaWeekBucket, modelBreakdown, poolCycleStats, poolsWeeklySummary, @@ -1012,7 +1030,13 @@ export function aggregateMultiWindowUsage({ if (modelInputs) { if (!sameSnapshot) { lastUsageSnapshot = { - timeZone, modelInputs, currentYear, entries: allEntriesToAggregate, dates: null, ranges: new Map(), + timeZone, + modelInputs, + currentYear, + normalizedQuotaAccount, + entries: allEntriesToAggregate, + dates: null, + ranges: new Map(), }; } const { ranges } = lastUsageSnapshot; diff --git a/sidecars/panel/backend/window-bridge.mjs b/sidecars/panel/backend/window-bridge.mjs index fcfc254..098141a 100644 --- a/sidecars/panel/backend/window-bridge.mjs +++ b/sidecars/panel/backend/window-bridge.mjs @@ -10,9 +10,17 @@ * 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。 */ -import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs'; import { homedir } from 'node:os'; import { dirname, join } from 'node:path'; +import { + BRIDGE_API_PATHS, + CONTEXT_WINDOWS_GLOBAL_KEY, + WINDOW_BRIDGE_KEY, + WINDOW_BRIDGE_ROUTE_KEY, + WINDOW_OVERLAY_KEY, + WINDOW_OVERLAY_METHODS, +} from '../shared/window-bridge-protocol.mjs'; import { DATA_DIR, computeRuntimeCodeVersion, @@ -22,20 +30,27 @@ import { normalizeWindowMountMode, saveJson, } from './config.mjs'; -import { createContextWindowSyncExpression } from './context-windows.mjs'; +import { + createContextWindowSyncExpression, + getContextWindowModels, + resolveContextWindowRules, +} from './context-windows.mjs'; +import { + ensureDesktopLaunchEntriesConfigured, + resolveDesktopHostExecutable, +} from './desktop-launcher-config.mjs'; +import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs'; + +const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`; +const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`; +const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`; +const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY); +const overlayMethods = Object.fromEntries( + Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)]) +); const BRIDGE_MAX_BODY_BYTES = 64 * 1024; -const ALLOWED_BRIDGE_PATHS = new Set([ - '/api/telemetry', - '/api/settings', - '/api/settings/reset', - '/api/cache/rebuild', - '/api/accounts', - '/api/accounts/update', - '/api/context-window', - '/api/cloud-sync', - '/api/plugin-update', -]); +const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS); /** * 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。 @@ -68,6 +83,10 @@ export function resolveDevToolsPortCandidates( return [ join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'), join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort'), + join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort'), + join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort'), + join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort'), + join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort'), ]; } const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config'); @@ -256,8 +275,8 @@ function scanJsoncObject(rawText) { */ export function ensureRemoteDebuggingInArgvText(rawText) { if (typeof rawText !== 'string' || !rawText.trim()) { - const fresh = - '{\n\t// Automatically configured by Antigravity Usage & Speed Monitor for topbar overlay support.\n\t"remote-debugging-port": "0"\n}\n'; + // 新建文件使用纯 JSON(无注释),同时兼容 VS Code/IDE JSONC 解析器与 Electron 严格 JSON.parse() + const fresh = '{\n\t"remote-debugging-port": "0"\n}\n'; return { changed: true, valid: true, portValue: '0', text: fresh }; } @@ -329,25 +348,14 @@ export function ensureRemoteDebuggingInArgvText(rawText) { }; } -/** - * 当本机存在 `~/.antigravity-ide` 配置目录且开启双栖模式时,自动补齐 `argv.json` 中的 - * `"remote-debugging-port": "0"`,使 Antigravity IDE 下次启动时自动生成 `DevToolsActivePort`。 - * - * @param {{ env?: Record, homeDir?: string, enabled?: boolean }} [options] - */ -export function ensureIdeRemoteDebuggingArgv({ - env = process.env, - homeDir = homedir(), - enabled = true, -} = {}) { - if (!enabled) { - return { checked: false, updated: false, reason: 'disabled' }; - } - const argvPath = resolveIdeArgvPath(env, homeDir); +function patchSingleHostArgvFile(argvPath, { createDir = false, missingReason = 'dir_missing' } = {}) { try { const dirPath = dirname(argvPath); if (!existsSync(dirPath)) { - return { checked: true, updated: false, reason: 'ide_dir_missing', argvPath }; + if (!createDir) { + return { checked: true, updated: false, reason: missingReason, argvPath }; + } + mkdirSync(dirPath, { recursive: true }); } const rawText = existsSync(argvPath) ? readFileSync(argvPath, 'utf8') : ''; const patched = ensureRemoteDebuggingInArgvText(rawText); @@ -391,6 +399,27 @@ export function ensureIdeRemoteDebuggingArgv({ } } +/** + * 当本机存在 `~/.antigravity-ide` 配置目录且开启双栖模式时,自动补齐 `argv.json` 中的 + * `"remote-debugging-port": "0"`,使 Antigravity IDE 下次启动时自动生成 `DevToolsActivePort`。 + * + * @param {{ env?: Record, homeDir?: string, enabled?: boolean }} [options] + */ +export function ensureIdeRemoteDebuggingArgv({ + env = process.env, + homeDir = homedir(), + enabled = true, +} = {}) { + if (!enabled) { + return { checked: false, updated: false, reason: 'disabled' }; + } + const argvPath = resolveIdeArgvPath(env, homeDir); + return patchSingleHostArgvFile(argvPath, { + createDir: false, + missingReason: 'ide_dir_missing', + }); +} + /** * 从 `DevToolsActivePort` 文件文本首行提取合法的本地调试端口号。 * @@ -685,6 +714,10 @@ export function createWindowBridgeController(options) { onVersionDrift = null, leaseFilePath = '', autoConfigureIdeArgv = options?.env === undefined && options?.homeDir === undefined, + launcherExecFileFn = null, + launcherFsOps = null, + allowDesktopLauncherInTest = false, + existsHostFn = existsSync, WebSocketImpl = globalThis.WebSocket, } = options || {}; @@ -711,8 +744,36 @@ export function createWindowBridgeController(options) { let hadInjectedChatFrames = false; let cdpFallbackActive = false; let ideArgvProvisioned = false; + let hostLauncherPromise = null; + let argvUpdatedThisBoot = false; + let argvConfigured = false; + let launcherConfigured = false; + const hostExecInfo = resolveDesktopHostExecutable({ + env, + platform, + homeDir, + existsFn: existsHostFn, + }); + // Windows / macOS 支持从运行中宿主进程动态反查任意盘符路径,因此桌面端环境下即使自定义安装路径不在默认盘符也可一键重拉 + const canRelaunch = Boolean( + hostExecInfo.found || + ((platform === 'win32' || platform === 'darwin') && options?.existsHostFn === undefined) + ); + let lastPersistedLeaseSig = ''; + let lastBridgeStatus = { + state: 'pending', + enabled: true, + aliveCount: 0, + targets: 0, + argvUpdatedThisBoot: false, + argvConfigured: false, + launcherConfigured: false, + canRelaunch, + updatedAtMs: 0, + }; let hadContextWindows = false; let contextWindowBootId = `${process.pid}:${Date.now()}`; + let cachedBackendCtxModels = { expiresAt: 0, models: [] }; let nodeDepsPromise = null; const allowedDynamicOrigins = new Set(); @@ -986,6 +1047,17 @@ export function createWindowBridgeController(options) { // 忽略不可读候选文件 } } + const rawExplicitPorts = String(env?.ANTIGRAVITY_DEVTOOLS_PORT || '').trim(); + if (rawExplicitPorts) { + for (const token of rawExplicitPorts.split(/[\s,]+/)) { + if (!/^\d+$/.test(token)) continue; + const p = Number(token); + if (Number.isInteger(p) && p > 0 && p <= 65535 && !seen.has(p)) { + seen.add(p); + ports.push(p); + } + } + } return ports; } @@ -1128,6 +1200,70 @@ export function createWindowBridgeController(options) { } } + function updateBridgeStatus(nextState, { enabled = true, aliveCount = 0, targets = 0, leasedBySelf = false, bundleVersion = '', prevLease = null } = {}) { + lastBridgeStatus = { + state: nextState, + enabled: Boolean(enabled), + aliveCount: Number(aliveCount || 0), + targets: Number(targets || 0), + argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot), + argvConfigured: Boolean(argvConfigured || launcherConfigured), + launcherConfigured: Boolean(launcherConfigured || argvConfigured), + canRelaunch: Boolean(canRelaunch), + updatedAtMs: Date.now(), + }; + if (leasedBySelf && leaseFilePath) { + const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`; + if (sig !== lastPersistedLeaseSig) { + lastPersistedLeaseSig = sig; + saveJson(leaseFilePath, { + pid: process.pid, + bundleVersion, + bridgePort: bridgePort > 0 ? bridgePort : Number(prevLease?.bridgePort || 0) || undefined, + bridgeToken: bridgeToken || String(prevLease?.bridgeToken || '') || undefined, + syncState: lastBridgeStatus.state, + aliveCount: lastBridgeStatus.aliveCount, + targets: lastBridgeStatus.targets, + argvUpdatedThisBoot: lastBridgeStatus.argvUpdatedThisBoot, + argvConfigured: lastBridgeStatus.argvConfigured, + launcherConfigured: lastBridgeStatus.launcherConfigured, + canRelaunch: lastBridgeStatus.canRelaunch, + updatedAtMs: Date.now(), + }); + } + } + } + + function provisionHostLaunchersOnce() { + if (ideArgvProvisioned) return Promise.resolve(); + if (hostLauncherPromise) return hostLauncherPromise; + hostLauncherPromise = (async () => { + const ideRes = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true }); + const desktopRes = await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + env, + platform, + homeDir, + execFileFn: launcherExecFileFn, + fsOps: launcherFsOps, + allowInTest: allowDesktopLauncherInTest, + }); + if (ideRes.updated || desktopRes.updated) { + argvUpdatedThisBoot = true; + } + if (ideRes.updated || ideRes.alreadyConfigured) { + argvConfigured = true; + } + if (desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured) { + launcherConfigured = true; + } + ideArgvProvisioned = true; + })().finally(() => { + hostLauncherPromise = null; + }); + return hostLauncherPromise; + } + async function runSyncInternal({ forceReinject = false } = {}) { if (stopped) return { ok: false, reason: 'stopped' }; const bundleVersion = String(getBundleVersionFn() || ''); @@ -1144,15 +1280,16 @@ export function createWindowBridgeController(options) { const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar'); const contextWindows = curSettings.modelContextWindows || {}; const hasContextWindows = Object.keys(contextWindows).length > 0; - if ((enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned) { - const prov = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true }); - if (prov.updated || prov.alreadyConfigured || prov.reason === 'ide_dir_missing') { - ideArgvProvisioned = true; - } - } + const provPending = + (enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned + ? provisionHostLaunchersOnce() + : hostLauncherPromise; + let leasedBySelf = false; + let currentLease = null; if ((enabled || hasContextWindows) && leaseFilePath && !forceReinject) { const lease = loadJson(leaseFilePath, null); + currentLease = lease; const leasePid = Number(lease?.pid || 0); const leaseAgeMs = Date.now() - Number(lease?.updatedAtMs || 0); if (leasePid > 0 && leasePid !== process.pid && leaseAgeMs >= 0 && leaseAgeMs < 9000 && isPidAlive(leasePid)) { @@ -1163,47 +1300,125 @@ export function createWindowBridgeController(options) { return { ok: false, enabled: true, reason: 'older_than_leader', injected: 0 }; } if (leaseVerNum === myVerNum || String(lease?.bundleVersion || '') === bundleVersion) { + const mergedConfigured = Boolean( + lease?.launcherConfigured || lease?.argvConfigured || launcherConfigured || argvConfigured + ); + lastBridgeStatus = { + state: String(lease?.syncState || 'active'), + enabled: Boolean(enabled), + aliveCount: Number(lease?.aliveCount || 0), + targets: Number(lease?.targets || 0), + argvUpdatedThisBoot: Boolean(lease?.argvUpdatedThisBoot || argvUpdatedThisBoot), + argvConfigured: mergedConfigured, + launcherConfigured: mergedConfigured, + canRelaunch: Boolean(lease?.canRelaunch ?? canRelaunch), + updatedAtMs: Date.now(), + }; return { ok: true, enabled: true, reason: 'follower_yield', leaderPid: leasePid, injected: 0 }; } } + leasedBySelf = true; + lastPersistedLeaseSig = ''; saveJson(leaseFilePath, { pid: process.pid, bundleVersion, bridgePort: bridgePort > 0 ? bridgePort : Number(lease?.bridgePort || 0) || undefined, bridgeToken: bridgeToken || String(lease?.bridgeToken || '') || undefined, + syncState: lastBridgeStatus.state, + aliveCount: lastBridgeStatus.aliveCount, + targets: lastBridgeStatus.targets, + argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot), + argvConfigured: Boolean(argvConfigured || launcherConfigured), + launcherConfigured: Boolean(launcherConfigured || argvConfigured), + canRelaunch: Boolean(canRelaunch), updatedAtMs: Date.now(), }); } const cdpPorts = findActiveDevToolsPorts(); if (!cdpPorts.length) { + if (provPending) { + await provPending.catch(() => {}); + } + updateBridgeStatus(enabled || hasContextWindows ? 'no_devtools_port' : 'disabled', { + enabled, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 }; } const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts); if (reachableCount === 0) { + if (provPending) { + await provPending.catch(() => {}); + } + updateBridgeStatus(enabled || hasContextWindows ? 'cdp_unreachable' : 'disabled', { + enabled, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 }; } if (!targets.length) { + updateBridgeStatus(enabled ? 'no_targets' : 'disabled', { + enabled, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); return { ok: true, enabled, reason: 'no_targets', injected: 0 }; } if (hasContextWindows || hadContextWindows) { + let fallbackRules = {}; + if ( + hasContextWindows && + lsRuntimeEndpoint.baseUrl && + lsRuntimeEndpoint.addr !== 'test.invalid' + ) { + if (Date.now() >= cachedBackendCtxModels.expiresAt) { + try { + const [stRes, cat] = await Promise.all([ + callLsRpc('GetUserStatus', {}, 1500), + getContextModelCatalog(), + ]); + const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs; + if (Array.isArray(cfgs)) { + cachedBackendCtxModels = { + expiresAt: Date.now() + 10_000, + models: getContextWindowModels(cfgs, cat), + }; + } + } catch { + // 忽略瞬态 LS 查询失败,保留上次缓存或交由窗口端解析 + } + } + if (cachedBackendCtxModels.models.length > 0) { + fallbackRules = resolveContextWindowRules(cachedBackendCtxModels.models, contextWindows); + } + } const chatUrls = [ ...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl), ...collectAllChatDebuggerUrls(targets), ]; - const expression = createContextWindowSyncExpression(contextWindows, contextWindowBootId); + const expression = createContextWindowSyncExpression( + contextWindows, + contextWindowBootId, + fallbackRules + ); await Promise.allSettled([...new Set(chatUrls)].map((url) => evaluateOnTarget(url, expression))); hadContextWindows = hasContextWindows; } const disposeExpr = `(() => { try { - const existed = Boolean(window.__AGUsageMonitorOverlay || window.__AGUsageMonitorBridge); - window.__AGUsageMonitorOverlay?.dispose?.(); - delete window.__AGUsageMonitorOverlay; - delete window.__AGUsageMonitorBridge; + const existed = Boolean(${windowOverlayRef} || ${windowBridgeRef}); + ${windowOverlayRef}?.[${overlayMethods.dispose}]?.(); + delete ${windowOverlayRef}; + delete ${windowBridgeRef}; return existed; } catch { return false; @@ -1222,6 +1437,13 @@ export function createWindowBridgeController(options) { if (!enabled) { if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) { + updateBridgeStatus('disabled', { + enabled: false, + targets: targets.length, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); return { ok: true, enabled: false, removed: 0 }; } let removed = 0; @@ -1234,17 +1456,24 @@ export function createWindowBridgeController(options) { } hadInjectedTargets = false; hadInjectedChatFrames = false; + updateBridgeStatus('disabled', { + enabled: false, + targets: targets.length, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); return { ok: true, enabled: false, removed }; } const { port, token } = await ensureBridgeServer(); const probeExpr = `(() => { try { - const ov = window.__AGUsageMonitorOverlay; - const br = window.__AGUsageMonitorBridge; - const alive = Boolean(ov && typeof ov.ensureAlive === 'function' && ov.ensureAlive()); - const dockKind = String(ov?.getDockKind?.() || ''); - const clientMountMode = String(ov?.getMountMode?.() || ''); + const ov = ${windowOverlayRef}; + const br = ${windowBridgeRef}; + const alive = Boolean(ov && typeof ov[${overlayMethods.ensureAlive}] === 'function' && ov[${overlayMethods.ensureAlive}]()); + const dockKind = String(ov?.[${overlayMethods.getDockKind}]?.() || ''); + const clientMountMode = String(ov?.[${overlayMethods.getMountMode}]?.() || ''); const visible = Boolean( (window.innerWidth === undefined || Number(window.innerWidth) > 80) && (window.innerHeight === undefined || Number(window.innerHeight) > 80) && @@ -1276,7 +1505,7 @@ export function createWindowBridgeController(options) { bridgePort: Number(br?.port || 0), hasToken: Boolean(br?.token), transportMode: String(br?.transportMode || 'http'), - hostRouteCascadeId: String(br?.hostRouteCascadeId || ''), + hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''), routeCascadeId, rpcBatch, }; @@ -1314,12 +1543,16 @@ export function createWindowBridgeController(options) { } if (snap.bundleVersion === bundleVersion) { if (snap.bridgePort !== port || snap.hasToken !== true) { - const rebindExpr = `window.__AGUsageMonitorOverlay?.updateBridge?.(${JSON.stringify({ port, token })})`; + const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ port, token })})`; await evaluateOnTarget(wsUrl, rebindExpr); } let effectiveDockKind = String(snap.dockKind || ''); if (snap.clientMountMode && snap.clientMountMode !== mountMode) { - const modeSyncExpr = `(() => { window.__AGUsageMonitorOverlay?.applyMountMode?.(${JSON.stringify(mountMode)}); return String(window.__AGUsageMonitorOverlay?.getDockKind?.() || ''); })()`; + const modeSyncExpr = `(() => { + const overlay = ${windowOverlayRef}; + overlay?.[${overlayMethods.applyMountMode}]?.(${JSON.stringify(mountMode)}); + return String(overlay?.[${overlayMethods.getDockKind}]?.() || ''); + })()`; const modeRes = await evaluateOnTarget(wsUrl, modeSyncExpr); if (typeof modeRes?.result?.result?.value === 'string') { effectiveDockKind = modeRes.result.result.value; @@ -1330,7 +1563,11 @@ export function createWindowBridgeController(options) { ideRouteId && String(snap.hostRouteCascadeId || '') !== ideRouteId ) { - const routeSyncExpr = `(() => { if (window.__AGUsageMonitorBridge) { window.__AGUsageMonitorBridge.hostRouteCascadeId = ${JSON.stringify(ideRouteId)}; } window.__AGUsageMonitorOverlay?.syncHostRoute?.(); })()`; + const routeSyncExpr = `(() => { + const bridge = ${windowBridgeRef}; + if (bridge) bridge[${windowBridgeRouteKey}] = ${JSON.stringify(ideRouteId)}; + ${windowOverlayRef}?.[${overlayMethods.syncHostRoute}]?.(); + })()`; await evaluateOnTarget(wsUrl, routeSyncExpr); } aliveCount += 1; @@ -1346,7 +1583,7 @@ export function createWindowBridgeController(options) { sawCdpTransport = true; const rpcResults = await executeRpcBatch(snap.rpcBatch); relayedRpcCount += rpcResults.length; - const deliverExpr = `window.__AGUsageMonitorOverlay?.deliverRpc?.(${JSON.stringify(rpcResults)})`; + const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`; await evaluateOnTarget(wsUrl, deliverExpr); } return { @@ -1387,13 +1624,27 @@ export function createWindowBridgeController(options) { port, token, bundleVersion, + platform: String(platform || ''), mountMode, - hostRouteCascadeId: ideRouteId || '', + [WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '', isIdeChatFrame: Boolean(isIdeChatFrame), stylesCss: cachedAssets.stylesCss, initialTelemetry, }); - const injectionScript = `(() => {\nwindow.__AGUsageMonitorBridge = ${bridgeConfigJson};\n})();\n${cachedAssets.appJs}\n(() => { const ov = window.__AGUsageMonitorOverlay; const alive = Boolean(ov && ov.ensureAlive && ov.ensureAlive()); return { alive, dockKind: String(ov?.getDockKind?.() || ''), visible: Boolean((window.innerWidth === undefined || Number(window.innerWidth) > 80) && (window.innerHeight === undefined || Number(window.innerHeight) > 80) && !(typeof document !== 'undefined' && document?.hidden === true)) }; })();`; + const injectionScript = `(() => { + ${windowBridgeRef} = ${bridgeConfigJson}; + })(); + ${cachedAssets.appJs} + (() => { + const ov = ${windowOverlayRef}; + const alive = Boolean(ov?.[${overlayMethods.ensureAlive}]?.()); + const visible = Boolean( + (window.innerWidth === undefined || Number(window.innerWidth) > 80) && + (window.innerHeight === undefined || Number(window.innerHeight) > 80) && + !(typeof document !== 'undefined' && document?.hidden === true) + ); + return { alive, dockKind: String(ov?.[${overlayMethods.getDockKind}]?.() || ''), visible }; + })();`; const evalRes = await evaluateOnTarget(wsUrl, injectionScript); const evalVal = evalRes?.result?.result?.value; @@ -1458,6 +1709,14 @@ export function createWindowBridgeController(options) { } cdpFallbackActive = sawCdpTransport; + updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', { + enabled: true, + aliveCount, + targets: targets.length, + leasedBySelf, + bundleVersion, + prevLease: currentLease, + }); return { ok: true, enabled: true, @@ -1540,7 +1799,17 @@ export function createWindowBridgeController(options) { const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({ targets: [], })); - const disposeExpr = `(() => { try { window.__AGUsageMonitorContextWindows?.dispose?.(); window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`; + const disposeExpr = `(() => { + try { + ${windowContextWindowsRef}?.dispose?.(); + ${windowOverlayRef}?.[${overlayMethods.dispose}]?.(); + delete ${windowOverlayRef}; + delete ${windowBridgeRef}; + return true; + } catch { + return false; + } + })()`; const allUrls = [ ...targets.map((t) => String(t.webSocketDebuggerUrl || '')).filter(Boolean), ...collectAllChatDebuggerUrls(targets), @@ -1569,6 +1838,20 @@ export function createWindowBridgeController(options) { if (!enabled) { hadInjectedTargets = true; hadInjectedChatFrames = true; + const cur = getSettingsFn() || {}; + const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; + if (!hasCtx && autoConfigureIdeArgv) { + launcherConfigured = false; + void ensureDesktopLaunchEntriesConfigured({ + enabled: false, + env, + platform, + homeDir, + execFileFn: launcherExecFileFn, + fsOps: launcherFsOps, + allowInTest: allowDesktopLauncherInTest, + }).catch(() => {}); + } } else { ideArgvProvisioned = false; hadInjectedChatFrames = true; @@ -1576,18 +1859,62 @@ export function createWindowBridgeController(options) { return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false })); } + function notifyContextWindowsChanged() { + const cur = getSettingsFn() || {}; + const mountMode = normalizeWindowMountMode(cur.windowMountMode, cur.enableWindowOverlay); + const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar'); + const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0; + if (hasCtx) { + ideArgvProvisioned = false; + } else if (!overlayOn && autoConfigureIdeArgv) { + launcherConfigured = false; + void ensureDesktopLaunchEntriesConfigured({ + enabled: false, + env, + platform, + homeDir, + execFileFn: launcherExecFileFn, + fsOps: launcherFsOps, + allowInTest: allowDesktopLauncherInTest, + }).catch(() => {}); + } + return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false })); + } + return { ensureBridgeServer, syncAllWindows, notifySettingChanged, + notifyContextWindowsChanged, start, stop, getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }), + getBridgeStatus: () => ({ ...lastBridgeStatus }), }; } let defaultBridgeController = null; +/** + * 读取进程级默认双栖桥接器的最新同步健康度快照(供 `/api/telemetry` 与偏好设置面板诊断使用)。 + */ +export function getDefaultWindowBridgeStatus() { + if (!defaultBridgeController) { + return { + state: 'pending', + enabled: true, + aliveCount: 0, + targets: 0, + argvUpdatedThisBoot: false, + argvConfigured: false, + launcherConfigured: false, + canRelaunch: false, + updatedAtMs: 0, + }; + } + return defaultBridgeController.getBridgeStatus(); +} + /** * 启动进程级默认的双栖窗口桥接控制器(幂等)。 * @@ -1615,5 +1942,6 @@ export function notifyWindowOverlaySetting(enabled) { } export function notifyModelContextWindowsChanged() { - return defaultBridgeController?.syncAllWindows().catch(() => {}); + if (!defaultBridgeController) return Promise.resolve({ ok: false }); + return defaultBridgeController.notifyContextWindowsChanged(); } diff --git a/sidecars/panel/bridge-daemon.mjs b/sidecars/panel/bridge-daemon.mjs index ee71055..102ec80 100644 --- a/sidecars/panel/bridge-daemon.mjs +++ b/sidecars/panel/bridge-daemon.mjs @@ -11,23 +11,18 @@ import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { - bootBundleVersion, - bootWindowBridgeRuntime, - setStandalonePortListener, -} from './backend/api-actions.mjs'; -import { - computeRuntimeCodeVersion, - loadSettings, - normalizeStandalonePort, -} from './backend/config.mjs'; -import { - createStandaloneWebServer, - parseStandaloneCliArgs, -} from './backend/standalone-server.mjs'; -import { runStandaloneCli } from './standalone.mjs'; -export function startBridgeDaemon() { +export async function startBridgeDaemon() { + const [ + { bootBundleVersion, bootWindowBridgeRuntime, setStandalonePortListener }, + { computeRuntimeCodeVersion, loadSettings, normalizeStandalonePort }, + { createStandaloneWebServer, parseStandaloneCliArgs }, + ] = await Promise.all([ + import('./backend/api-actions.mjs'), + import('./backend/config.mjs'), + import('./backend/standalone-server.mjs'), + ]); + let shuttingDown = false; let sawShutdownDispose = false; let stdinBuf = ''; @@ -171,8 +166,8 @@ const invokedPath = process.argv[1] ? resolve(process.argv[1]) : ''; if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) { const cliArgs = process.argv.slice(2); if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) { - void runStandaloneCli(cliArgs); + void import('./standalone.mjs').then(({ runStandaloneCli }) => runStandaloneCli(cliArgs)); } else { - startBridgeDaemon(); + void startBridgeDaemon(); } } diff --git a/sidecars/panel/cli-statusline.mjs b/sidecars/panel/cli-statusline.mjs index b8e7da9..d2a8908 100644 --- a/sidecars/panel/cli-statusline.mjs +++ b/sidecars/panel/cli-statusline.mjs @@ -23,12 +23,12 @@ import { speedMetric, summarizeSpeed, summarizeTtft, -} from './speed-metrics.mjs'; +} from './trajectory-metrics.mjs'; import { - getNodeSqliteDatabaseSync, readLocalSqliteTrajectory, readLocalSummaryIndex, } from './backend/cli-sqlite-reader.mjs'; +import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs'; import { ensureCliStatusLineConfigured, formatCliStatusLineCapsule, @@ -39,6 +39,7 @@ import { loadSettings, } from './backend/config.mjs'; import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs'; +import { isThirdPartyPoolText } from './shared/telemetry-display-rules.mjs'; const CLI_RUNNING_STALE_MS = 10 * 60 * 1000; const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000; @@ -145,43 +146,35 @@ function findConversationIdByWorkspaceFts(cliRoot, cwd) { if (!cwd) return ''; const summariesDbPath = join(cliRoot, 'conversation_summaries.db'); if (!existsSync(summariesDbPath)) return ''; - const DatabaseSync = getNodeSqliteDatabaseSync(); - if (!DatabaseSync) return ''; const normCwd = normalizePathForMatch(cwd); if (!normCwd) return ''; - let db = null; try { - db = new DatabaseSync(summariesDbPath, { readOnly: true }); - const rows = db - .prepare( - `SELECT conversation_id, workspace, last_modified_time - FROM conversations_fts - WHERE chunk_index = -1 - ORDER BY last_modified_time DESC - LIMIT 40` - ) - .all(); - for (const row of rows || []) { - const ws = normalizePathForMatch(row?.workspace); - const cid = String(row?.conversation_id || '').trim().toLowerCase(); - if (cid && ws && ws === normCwd) { - return cid; + const matched = withReadOnlySqliteDb(summariesDbPath, (db) => { + const rows = db + .prepare( + `SELECT conversation_id, workspace, last_modified_time + FROM conversations_fts + WHERE chunk_index = -1 + ORDER BY last_modified_time DESC + LIMIT 40` + ) + .all(); + for (const row of rows || []) { + const ws = normalizePathForMatch(row?.workspace); + const cid = String(row?.conversation_id || '').trim().toLowerCase(); + if (cid && ws && ws === normCwd) { + return cid; + } } - } + return ''; + }); + return matched || ''; } catch { // 忽略不存在 conversations_fts 表或读取失败 - } finally { - if (db) { - try { - db.close(); - } catch { - // 忽略关闭异常 - } - } + return ''; } - return ''; } /** @@ -394,7 +387,7 @@ function buildStdinFallbackQuotas(stdinData) { const frac = Number(bucket.remaining_fraction); if (!Number.isFinite(frac)) continue; const remainingPct = Math.max(0, Math.min(100, Math.round(frac * 100))); - const isThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(key); + const isThirdParty = isThirdPartyPoolText(key); pools.push({ poolKey: isThirdParty ? 'Claude & GPT' : 'Gemini', poolLabel: key, @@ -404,7 +397,7 @@ function buildStdinFallbackQuotas(stdinData) { } if (pools.length === 0) return null; const modelStr = String(stdinData?.model?.id || stdinData?.model?.display_name || ''); - const activeIsThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(modelStr); + const activeIsThirdParty = isThirdPartyPoolText(modelStr); const matchingPools = pools.filter((p) => activeIsThirdParty ? p.poolKey === 'Claude & GPT' : p.poolKey === 'Gemini' ); diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index 6ef5ab6..71755bf 100644 --- a/sidecars/panel/index.html +++ b/sidecars/panel/index.html @@ -4,11 +4,11 @@ 用量监控 - +
- + diff --git a/sidecars/panel/main.mjs b/sidecars/panel/main.mjs index 1626d67..107d2f8 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -11,12 +11,8 @@ import { Worker } from 'node:worker_threads'; import { Response, SidecarApp } from 'sidecar_sdk'; -import { - bootWindowBridgeRuntime, - dispatchBridgeApiRequest, - isLocalHostRequest, - readLocalAsync, -} from './backend/api-actions.mjs'; +import { BRIDGE_API_ROUTE_DEFS } from './shared/window-bridge-protocol.mjs'; +import { isLocalHostRequest, readLocalAsync } from './backend/http-helpers.mjs'; const app = new SidecarApp(); @@ -144,9 +140,20 @@ async function ensureActiveWorker() { return activeWorker; } +let testHarnessApiModulePromise = null; + +function getTestHarnessApiModule() { + testHarnessApiModulePromise ||= import('./backend/api-actions.mjs'); + return testHarnessApiModulePromise; +} + async function forwardApiCall(pathname, method, data) { if (isTestHarnessEnv) { - return dispatchBridgeApiRequest(pathname, method, data); + if (typeof dispatchBridgeApiRequest === 'function') { + return dispatchBridgeApiRequest(pathname, method, data); + } + const mod = await getTestHarnessApiModule(); + return mod.dispatchBridgeApiRequest(pathname, method, data); } const upperMethod = String(method || 'GET').toUpperCase(); try { @@ -208,22 +215,32 @@ app.page( ); // --------------------------------------------------------------------------- -// 业务数据与控制 API 路由 +// 业务数据与控制 API 路由(统一源自 shared/window-bridge-protocol.mjs) // --------------------------------------------------------------------------- -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)); +for (const route of BRIDGE_API_ROUTE_DEFS) { + app.api( + route.path, + (data, req) => + handleProtectedApi( + route.path, + route.method, + route.method === 'GET' && route.action !== 'telemetry' ? undefined : data, + req + ), + route.method + ); +} app.run(); if (isTestHarnessEnv) { - bootWindowBridgeRuntime({ allowDynamicLs: false }); + if (typeof bootWindowBridgeRuntime === 'function') { + bootWindowBridgeRuntime({ allowDynamicLs: false }); + } else { + void getTestHarnessApiModule().then((mod) => + mod.bootWindowBridgeRuntime({ allowDynamicLs: false }) + ); + } } else { void ensureActiveWorker(); } diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 29fb062..d4c248a 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -1,6 +1,6 @@ { "name": "usage-monitor-panel", - "version": "1.5.0", + "version": "1.5.1", "private": true, "type": "module", "description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.", diff --git a/sidecars/panel/scripts/build-bundle.mjs b/sidecars/panel/scripts/build-bundle.mjs index f343230..09347dd 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -7,6 +7,7 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { Script } from 'node:vm'; const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url))); @@ -93,18 +94,18 @@ function consumeTrailingStatementEnd(source, startIdx) { return idx; } -function scanImportDeclarationEnd(source, afterImportIdx) { +function scanImportDeclarationEnd(source, afterImportIdx, onImport) { let idx = afterImportIdx; let braceDepth = 0; - let sawModuleSpecifierString = false; while (idx < source.length) { const ch = source[idx]; if (ch === "'" || ch === '"') { - idx = skipSimpleString(source, idx); + const end = skipSimpleString(source, idx); if (braceDepth === 0) { - sawModuleSpecifierString = true; - return consumeTrailingStatementEnd(source, idx); + onImport?.(source.slice(idx + 1, end - 1), source.slice(afterImportIdx, idx)); + return consumeTrailingStatementEnd(source, end); } + idx = end; continue; } if (ch === '/' && source[idx + 1] === '/') { @@ -122,17 +123,17 @@ function scanImportDeclarationEnd(source, afterImportIdx) { else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1); else if (ch === ';' && braceDepth === 0) { return consumeTrailingStatementEnd(source, idx); - } else if (ch === '\n' && braceDepth === 0 && sawModuleSpecifierString) { - return idx + 1; } idx += 1; } return source.length; } -function scanExportClauseEnd(source, afterExportIdx) { +function scanExportClauseEnd(source, afterExportIdx, onImport, onExport) { let idx = afterExportIdx; + let braceBody = ''; if (source[idx] === '{') { + const bodyStart = idx + 1; let depth = 1; idx += 1; while (idx < source.length && depth > 0) { @@ -156,6 +157,7 @@ function scanExportClauseEnd(source, afterExportIdx) { else if (ch === '}') depth -= 1; idx += 1; } + braceBody = source.slice(bodyStart, Math.max(bodyStart, idx - 1)); } else if (source[idx] === '*') { idx += 1; idx = skipSpacesAndComments(source, idx); @@ -169,21 +171,57 @@ function scanExportClauseEnd(source, afterExportIdx) { if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) { const specIdx = skipSpacesAndComments(source, peekFrom + 4); if (source[specIdx] === "'" || source[specIdx] === '"') { - idx = skipSimpleString(source, specIdx); + const specEnd = skipSimpleString(source, specIdx); + const specifier = source.slice(specIdx + 1, specEnd - 1); + onImport?.(specifier, braceBody ? `{ ${braceBody} } from` : ''); + idx = specEnd; + return consumeTrailingStatementEnd(source, idx); + } + } + + if (braceBody && onExport) { + const cleaned = braceBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' '); + for (const part of cleaned.split(',')) { + const tok = part.trim(); + if (!tok) continue; + const asMatch = /^([$_\w]+)\s+as\s+([$_\w]+)$/.exec(tok); + onExport(asMatch ? asMatch[2] : tok, true); } } return consumeTrailingStatementEnd(source, idx); } +function recordExportedDeclarationIdent(source, declKeywordIdx, onExport) { + if (!onExport) return; + let pos = declKeywordIdx; + if (source.startsWith('async', pos) && !isIdentPart(source[pos + 5])) { + pos = skipSpacesAndComments(source, pos + 5); + } + for (const kw of ['const', 'let', 'var', 'function', 'class']) { + if (source.startsWith(kw, pos) && !isIdentPart(source[pos + kw.length])) { + pos = skipSpacesAndComments(source, pos + kw.length); + if (source[pos] === '*') pos = skipSpacesAndComments(source, pos + 1); + if (isIdentStart(source[pos])) { + let end = pos + 1; + while (end < source.length && isIdentPart(source[end])) end += 1; + onExport(source.slice(pos, end), false); + } + return; + } + } +} + /** * Lexical ES module syntax stripper that skips comments, single/double-quoted * strings, template literals (including nested `${...}` expressions), and regex * literals, removing only true top-level `import` / `export` syntax. * * @param {string} source + * @param {(specifier: string, clause: string) => void} [onImport] + * @param {(name: string, isClauseExport: boolean) => void} [onExport] * @returns {string} */ -export function stripModuleSyntax(source) { +export function stripModuleSyntax(source, onImport, onExport) { const len = source.length; let out = ''; let i = 0; @@ -356,7 +394,7 @@ export function stripModuleSyntax(source) { const nextCh = source[afterImport]; // Exclude `import.meta` and dynamic `import(...)` if (nextCh && nextCh !== '.' && nextCh !== '(') { - i = scanImportDeclarationEnd(source, afterImport); + i = scanImportDeclarationEnd(source, afterImport, onImport); canStartRegex = true; prevNonWsChar = ';'; continue; @@ -367,7 +405,7 @@ export function stripModuleSyntax(source) { const afterExport = skipSpacesAndComments(source, end); const nextCh = source[afterExport]; if (nextCh === '{' || nextCh === '*') { - i = scanExportClauseEnd(source, afterExport); + i = scanExportClauseEnd(source, afterExport, onImport, onExport); canStartRegex = true; prevNonWsChar = ';'; continue; @@ -380,6 +418,7 @@ export function stripModuleSyntax(source) { (source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) || (source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5])); if (isDecl) { + recordExportedDeclarationIdent(source, afterDefault, onExport); i = afterDefault; canStartRegex = false; continue; @@ -399,6 +438,7 @@ export function stripModuleSyntax(source) { (source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) || (source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5])) ) { + recordExportedDeclarationIdent(source, afterExport, onExport); i = afterExport; canStartRegex = false; continue; @@ -428,7 +468,32 @@ export function stripModuleSyntax(source) { return out; } -export function buildBundle() { +function validateBundleImport(sourcePath, specifier, clause, bundledPaths, moduleImportedNames) { + const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim(); + if (binding) { + const named = /^\{([^}]*)\}\s*from$/.exec(binding); + const identifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u; + if (!named) { + throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`); + } + for (const rawItem of named[1].split(',')) { + const name = rawItem.trim(); + if (!name) continue; + if (!identifier.test(name)) { + throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`); + } + moduleImportedNames?.add(name); + } + } + if ( + !(specifier.startsWith('./') || specifier.startsWith('../')) || + !bundledPaths.has(resolve(dirname(sourcePath), specifier)) + ) { + throw new Error(`${sourcePath}: ${specifier} must appear earlier in jsOrder`); + } +} + +export function buildBundle(panelDir = PANEL_DIR) { const cssOrder = [ 'src/styles/tokens.css', 'src/styles/base.css', @@ -443,12 +508,16 @@ export function buildBundle() { const cssBundle = cssOrder - .map((rel) => `/* --- ${rel} --- */\n${readFileSync(join(PANEL_DIR, rel), 'utf8').trim()}`) + .map( + (rel) => + `/* --- ${rel} --- */\n${readFileSync(join(panelDir, rel), 'utf8').replace(/\r\n/g, '\n').trim()}` + ) .join('\n\n') + '\n'; - writeFileSync(join(PANEL_DIR, 'styles.css'), cssBundle, 'utf8'); - const jsOrder = [ + 'shared/settings-normalization.mjs', + 'shared/telemetry-display-rules.mjs', + 'shared/window-bridge-protocol.mjs', 'src/icons/svgRegistry.js', 'src/icons/SvgIcon.js', 'src/core/reactive.js', @@ -485,9 +554,9 @@ export function buildBundle() { 'src/components/settings/CollapsibleSection.js', 'src/components/settings/EditableSlotList.js', 'src/components/settings/ThemeColorPicker.js', + 'src/components/settings/BridgeStatusNotice.js', 'src/views/settings/SettingsGeneralTab.js', 'src/views/settings/SettingsStructureTab.js', - 'src/views/settings/SettingsAccountTab.js', 'src/views/settings/SettingsOtherTab.js', 'src/components/layout/TopSessionHeader.js', 'src/views/LiveOverviewView.js', @@ -499,24 +568,55 @@ export function buildBundle() { 'src/main.js', ]; + const bundledPaths = new Set(); + const outerExportedSymbols = new Set(); const innerModules = jsOrder .map((rel) => { - const raw = readFileSync(join(PANEL_DIR, rel), 'utf8'); - const stripped = stripModuleSyntax(raw); - return `// --- ${rel} ---\n${stripped.trim()}`; + const path = resolve(panelDir, rel); + if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`); + const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n'); + const moduleImportedNames = new Set(); + const moduleLocalExports = new Set(); + const stripped = stripModuleSyntax( + raw, + (specifier, clause) => + validateBundleImport(path, specifier, clause, bundledPaths, moduleImportedNames), + (name, isClauseExport) => { + if (isClauseExport && moduleImportedNames.has(name) && outerExportedSymbols.has(name)) { + return; + } + moduleLocalExports.add(name); + } + ); + bundledPaths.add(path); + const exportList = [...moduleLocalExports]; + for (const sym of exportList) { + outerExportedSymbols.add(sym); + } + const body = stripped.trim(); + const wrapped = + exportList.length > 0 + ? `const { ${exportList.join(', ')} } = (() => {\n${body}\nreturn { ${exportList.join(', ')} };\n})();` + : `(() => {\n${body}\n})();`; + return `// --- ${rel} ---\n${wrapped}`; }) .join('\n\n'); const jsBundle = `(() => {\n'use strict';\n\n${innerModules}\n})();\n`; - - writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8'); + new Script(jsBundle, { filename: 'app.js' }); const ver = Date.now(); - const indexHtmlPath = join(PANEL_DIR, 'index.html'); - if (existsSync(indexHtmlPath)) { - const html = readFileSync(indexHtmlPath, 'utf8') + const indexHtmlPath = join(panelDir, 'index.html'); + const html = existsSync(indexHtmlPath) + ? readFileSync(indexHtmlPath, 'utf8') + .replace(/\r\n/g, '\n') .replace(/href="\/styles\.css(?:\?v=[^"]*)?"/, `href="/styles.css?v=${ver}"`) - .replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`); + .replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`) + : null; + + writeFileSync(join(panelDir, 'styles.css'), cssBundle, 'utf8'); + writeFileSync(join(panelDir, 'app.js'), jsBundle, 'utf8'); + if (html !== null) { writeFileSync(indexHtmlPath, html, 'utf8'); } diff --git a/sidecars/panel/shared/settings-normalization.mjs b/sidecars/panel/shared/settings-normalization.mjs new file mode 100644 index 0000000..f991242 --- /dev/null +++ b/sidecars/panel/shared/settings-normalization.mjs @@ -0,0 +1,448 @@ +/** + * @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。 + */ + +export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']); + +export const THEME_ACCENT_KEYS = Object.freeze([ + 'host', + 'blue', + 'emerald', + 'amber', + 'violet', + 'cyan', + 'rose', +]); + +export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']); + +export const TOPBAR_SLOT_KEYS = Object.freeze([ + 'context', + 'tps', + 'ttft', + 'avg_tps', + 'cost', + 'session_cost', + 'cache_hit', + 'session_tokens', + 'quota_auto', + 'gemini_5h', + 'gemini_weekly', + 'claude_5h', + 'claude_weekly', +]); + +export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); +export const MIN_TOPBAR_SLOTS = 1; +export const MAX_TOPBAR_SLOTS = 5; + +export const OVERVIEW_MODULE_KEYS = Object.freeze([ + 'metrics', + 'context', + 'quotas', + 'live_tasks', +]); + +export const DEFAULT_OVERVIEW_MODULES = Object.freeze([ + 'metrics', + 'context', + 'quotas', + 'live_tasks', +]); + +export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']); + +export const OVERVIEW_METRIC_KEYS = Object.freeze([ + 'tps', + 'ttft', + 'avg_tps', + 'step_cost', + 'session_cost', + 'cache_hit', + 'session_tokens', + 'context_usage', + 'quota_tightest', +]); + +export const DEFAULT_OVERVIEW_METRICS = Object.freeze([ + 'tps', + 'ttft', + 'avg_tps', + 'step_cost', +]); + +export const STEP_TABLE_COLUMN_KEYS = Object.freeze([ + 'step', + 'time', + 'model', + 'tps', + 'ttft', + 'duration', + 'tokens_combo', + 'tokens_io_cache', + 'tokens_custom', + 'input_tokens', + 'cache_tokens', + 'output_tokens', + 'cache', + 'cost', +]); + +export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([ + 'step', + 'model', + 'tps', + 'ttft', + 'tokens_combo', + 'cache', + 'cost', +]); + +export const 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 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; + +/** + * 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。 + * + * @param {unknown} lang + * @returns {'auto'|'zh-CN'|'en-US'} + */ +export function normalizeLanguageSetting(lang) { + const raw = String(lang ?? '').trim(); + if (!raw) return 'zh-CN'; + const lower = raw.toLowerCase(); + if (lower === 'auto' || lower === 'system') return 'auto'; + if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US'; + if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN'; + return 'zh-CN'; +} + +/** + * 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。 + * + * @param {unknown} accent + * @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'} + */ +export function normalizeThemeAccent(accent) { + const clean = String(accent ?? '').trim().toLowerCase(); + return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host'; +} + +/** + * 归一化面板字号档位(默认 `'md'` 标准 100%)。 + * + * @param {unknown} scale + * @returns {'sm'|'md'|'lg'|'xl'} + */ +export function normalizeFontScale(scale) { + const clean = String(scale ?? '').trim().toLowerCase(); + return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md'; +} + +/** + * 归一化模型名称展示模式(`'short'` | `'upstream_compact'` | `'upstream'`),兼容历史 `showUpstreamModel`。 + * + * @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'`,默认 `'compact'`)。 + * + * @param {unknown} mode + * @returns {'compact'|'full'} + */ +export function normalizeOrchestratorIdMode(mode) { + return String(mode ?? '').trim().toLowerCase() === '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'`)。 + * + * @param {unknown} mode + * @param {unknown} [legacyAutoUpdate] + * @returns {'off'|'manual'|'auto'} + */ +export function normalizePluginUpdateMode(mode, legacyAutoUpdate) { + const m = String(mode ?? '').trim().toLowerCase(); + if (m === 'off' || m === 'manual' || m === 'auto') return m; + if (legacyAutoUpdate === true) return 'auto'; + return 'manual'; +} + +/** + * 归一化面板挂载方式枚举(`'dual'` | `'composer'` | `'sidebar'`),兼容历史 `enableWindowOverlay`。 + * + * @param {unknown} mode + * @param {unknown} [legacyEnableOverlay] + * @returns {'dual'|'composer'|'sidebar'} + */ +export function normalizeWindowMountMode(mode, legacyEnableOverlay) { + const m = String(mode ?? '').trim().toLowerCase(); + if (m === 'composer' || m === 'input') return 'composer'; + if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar'; + if (m === 'dual' || m === 'topbar') return 'dual'; + if (legacyEnableOverlay === false) return 'sidebar'; + return 'dual'; +} + +/** + * 归一化每周额度统计模式枚举(`'official'` | `'custom_tokens'` | `'custom_cost'`)。 + * + * @param {unknown} mode + * @returns {'official'|'custom_tokens'|'custom_cost'} + */ +export function normalizeWeeklyLimitMode(mode) { + const m = String(mode || '').trim().toLowerCase(); + if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens'; + if (m === 'custom_cost' || m === 'cost') return 'custom_cost'; + return 'official'; +} + +/** + * 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +export function normalizeTopbarCapsuleSlots(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_TOPBAR_SLOTS]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!val || val === 'none') continue; + const mapped = val === 'step_cost' ? 'cost' : val; + if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue; + seen.add(mapped); + out.push(mapped); + if (out.length >= MAX_TOPBAR_SLOTS) break; + } + if (out.length < MIN_TOPBAR_SLOTS) { + return ['context']; + } + return out; +} + +/** + * 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +export function normalizeOverviewMetrics(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_OVERVIEW_METRICS]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const rawVal = String(item ?? '').trim(); + const val = rawVal === 'cost' ? 'step_cost' : rawVal; + if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= 4) break; + } + return out.length > 0 ? out : ['tps']; +} + +/** + * 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +export function normalizeOverviewModules(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_OVERVIEW_MODULES]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= OVERVIEW_MODULE_KEYS.length) break; + } + return out.length > 0 ? out : ['metrics']; +} + +/** + * 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +export function normalizeHoverModules(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_HOVER_MODULES]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= OVERVIEW_MODULE_KEYS.length) break; + } + return out; +} + +/** + * 归一化调用明细「按步查看」表格列配置与左右顺序(2~14 列,默认保留现有 7 列)。 + * + * @param {unknown} raw + * @returns {string[]} + */ +export function normalizeStepTableColumns(raw) { + if (!Array.isArray(raw)) { + return [...DEFAULT_STEP_TABLE_COLUMNS]; + } + const seen = new Set(); + const out = []; + for (const item of raw) { + const val = String(item ?? '').trim(); + if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue; + seen.add(val); + out.push(val); + if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break; + } + if (out.length < 2) { + for (const fallbackCol of ['step', 'model', 'tps']) { + if (!seen.has(fallbackCol)) { + seen.add(fallbackCol); + out.push(fallbackCol); + } + if (out.length >= 2) break; + } + } + return out; +} + +/** + * 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。 + * + * @param {unknown} port + * @returns {number} + */ +export function normalizeStandalonePort(port) { + const num = Number(port); + if (!Number.isInteger(num) || num <= 0) return 0; + if (num >= 1024 && num <= 65535) return num; + return 0; +} diff --git a/sidecars/panel/shared/telemetry-display-rules.mjs b/sidecars/panel/shared/telemetry-display-rules.mjs new file mode 100644 index 0000000..cf6aa7d --- /dev/null +++ b/sidecars/panel/shared/telemetry-display-rules.mjs @@ -0,0 +1,243 @@ +/** + * @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。 + */ + +export const THIRD_PARTY_POOL_RE = + /3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i; + +/** + * 判断模型或配额桶文本是否归属第三方模型池(Claude & GPT / OSS / 3P)。 + * + * @param {unknown} text + * @returns {boolean} + */ +export function isThirdPartyPoolText(text) { + return THIRD_PARTY_POOL_RE.test(String(text || '')); +} + +/** + * 输出速度四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。 + */ +export function classifySpeedTier(tokPerSec) { + if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) { + return 'muted'; + } + const v = Number(tokPerSec); + if (v >= 60) return 'good'; + if (v >= 35) return 'info'; + if (v >= 20) return 'warn'; + return 'danger'; +} + +/** + * 缓存命中率四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。 + */ +export function classifyCacheTier(cacheHitPct, promptTokens = null) { + if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) { + return 'muted'; + } + const v = Number(cacheHitPct); + if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) { + return 'muted'; + } + if (v >= 85) return 'good'; + if (v >= 65) return 'info'; + if (v >= 30) return 'warn'; + return 'danger'; +} + +/** + * 单步费用告警色阶分类(`''|'warn'|'danger'`)。 + */ +export function classifyStepCostTier(costUsd) { + if (costUsd == null || !Number.isFinite(Number(costUsd))) return ''; + const v = Number(costUsd); + if (v >= 0.3) return 'danger'; + if (v >= 0.15) return 'warn'; + return ''; +} + +/** + * 首字延迟告警色阶分类(`'muted'|''|'warn'|'danger'`)。 + */ +export function classifyTtftTier(ttftSec) { + if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) { + return 'muted'; + } + const v = Number(ttftSec); + if (v >= 30) return 'danger'; + if (v >= 18) return 'warn'; + return ''; +} + +export function formatCompactTokens(num) { + const n = Number(num || 0); + if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; + if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; + if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; + return String(Math.round(n)); +} + +export function formatCompactCapsuleCost(costUsd) { + if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--'; + const val = Math.max(0, Number(costUsd)); + if (val === 0) return '$0.00'; + if (val < 0.001) return '<$0.001'; + if (val < 1) return `$${val.toFixed(3)}`; + if (val < 100) return `$${val.toFixed(2)}`; + return `$${Math.round(val)}`; +} + +export function formatCompactCapsuleTtft(ttftSec) { + if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; + const val = Number(ttftSec); + if (val < 1) return `${val.toFixed(2)}s`; + if (val < 100) return `${val.toFixed(1)}s`; + return `${Math.round(val)}s`; +} + +/** + * 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。 + * + * @param {object|null|undefined} quotas + * @param {string} slotKey + * @returns {number|null} + */ +export function resolveCapsuleQuotaSlotPct(quotas, slotKey) { + if (!quotas || typeof quotas !== 'object') return null; + const pools = Array.isArray(quotas.pools) ? quotas.pools : []; + const activePool = quotas.activePool || null; + const weekly = quotas.weekly || null; + + if (slotKey === 'quota_auto') { + const candidates = []; + if (activePool && Number.isFinite(Number(activePool.remainingPct))) { + candidates.push(Number(activePool.remainingPct)); + } + if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) { + candidates.push(Number(activePool.weeklyRemainingPct)); + } + if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) { + candidates.push(Number(weekly.remainingPct)); + } + if (!candidates.length && pools.length > 0) { + for (const p of pools) { + if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct)); + if (p && Number.isFinite(Number(p.weeklyRemainingPct))) { + candidates.push(Number(p.weeklyRemainingPct)); + } + } + } + if (!candidates.length) return null; + return Math.max(0, Math.min(100, Math.round(Math.min(...candidates)))); + } + + const isClaude = slotKey.startsWith('claude_'); + const isWeekly = slotKey.endsWith('_weekly'); + let rawPct = null; + + if (isClaude) { + const claudePool = + pools.find((p) => p?.poolKey === 'Claude & GPT') || + pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || '')); + const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; + if (cand != null && Number.isFinite(Number(cand))) { + rawPct = Number(cand); + } else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); + } + } else { + const stdGemini = + pools.find((p) => p?.poolKey === 'Gemini') || + pools.find( + (p) => + /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && + !/carbon|argon/i.test(String(p?.poolKey || '')) + ); + const geminiFamilyPools = pools.filter((p) => + /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) + ); + const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; + if (primaryCand != null && Number.isFinite(Number(primaryCand))) { + rawPct = Number(primaryCand); + } else { + const familyVals = geminiFamilyPools + .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) + .filter((v) => v != null && Number.isFinite(Number(v))) + .map(Number); + if (familyVals.length > 0) { + rawPct = Math.min(...familyVals); + } else if ( + activePool && + !isThirdPartyPoolText(activePool.family || activePool.poolLabel || '') + ) { + const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; + if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb); + } + if ( + rawPct == null && + isWeekly && + weekly && + !isThirdPartyPoolText(weekly.poolFamily || '') && + weekly.remainingPct != null && + Number.isFinite(Number(weekly.remainingPct)) + ) { + rawPct = Number(weekly.remainingPct); + } + } + } + + if (rawPct == null || !Number.isFinite(rawPct)) return null; + return Math.max(0, Math.min(100, Math.round(rawPct))); +} + +/** + * 使用最大余数法(Hamilton 方法)将各非零分桶等比缩放至目标整数总和, + * 保证 0 值通道绝不被凭空分配余数,且缩放后各分桶之和精确等于 `targetTotal`。 + * + * @param {Record} buckets + * @param {readonly string[]} keys + * @param {number} targetTotal + * @returns {Record} + */ +export function scaleBucketsExact(buckets, keys, targetTotal) { + const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0))); + const out = {}; + let currentSum = 0; + for (const k of keys) { + const val = Math.max(0, Number(buckets[k] || 0)); + out[k] = val; + currentSum += val; + } + if (safeTarget === 0 || currentSum <= 0) { + for (const k of keys) out[k] = 0; + return out; + } + if (currentSum === safeTarget) { + for (const k of keys) out[k] = Math.round(out[k]); + return out; + } + const remainders = []; + let assigned = 0; + for (const k of keys) { + const rawVal = out[k]; + if (rawVal <= 0) { + out[k] = 0; + continue; + } + const exact = (rawVal * safeTarget) / currentSum; + const floored = Math.floor(exact); + out[k] = floored; + assigned += floored; + remainders.push({ key: k, rem: exact - floored, orig: rawVal }); + } + const diff = safeTarget - assigned; + if (diff > 0 && remainders.length > 0) { + remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig); + for (let i = 0; i < diff; i++) { + out[remainders[i % remainders.length].key] += 1; + } + } + return out; +} diff --git a/sidecars/panel/shared/window-bridge-protocol.mjs b/sidecars/panel/shared/window-bridge-protocol.mjs new file mode 100644 index 0000000..fa9f774 --- /dev/null +++ b/sidecars/panel/shared/window-bridge-protocol.mjs @@ -0,0 +1,34 @@ +export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge'; +export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId'; +export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay'; +export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows'; + +export const WINDOW_OVERLAY_METHODS = Object.freeze({ + ensureAlive: 'ensureAlive', + getDockKind: 'getDockKind', + getMountMode: 'getMountMode', + updateBridge: 'updateBridge', + applyMountMode: 'applyMountMode', + syncHostRoute: 'syncHostRoute', + deliverRpc: 'deliverRpc', + dispose: 'dispose', +}); + +export const BRIDGE_API_ROUTE_DEFS = Object.freeze([ + Object.freeze({ path: '/api/telemetry', method: 'GET', action: 'telemetry' }), + Object.freeze({ path: '/api/settings', method: 'POST', action: 'settings' }), + Object.freeze({ path: '/api/accounts', method: 'GET', action: 'accounts_get' }), + Object.freeze({ path: '/api/accounts/update', method: 'POST', action: 'accounts_update' }), + Object.freeze({ path: '/api/context-window', method: 'POST', action: 'context_window' }), + Object.freeze({ path: '/api/settings/reset', method: 'POST', action: 'settings_reset' }), + Object.freeze({ path: '/api/cache/rebuild', method: 'POST', action: 'cache_rebuild' }), + Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }), + Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }), + Object.freeze({ path: '/api/bridge/relaunch', method: 'POST', action: 'bridge_relaunch' }), +]); + +export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); + +export function readInjectedWindowBridge() { + return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY]; +} diff --git a/sidecars/panel/src/App.js b/sidecars/panel/src/App.js index 9f0158a..1aaddef 100644 --- a/sidecars/panel/src/App.js +++ b/sidecars/panel/src/App.js @@ -6,9 +6,15 @@ import { defineComponent } from './core/component.js'; import { h, patchAttr } from './core/domPatch.js'; +import { isWindowOverlayMode } from './core/httpClient.js'; import { i18nStore } from './i18n/index.js'; -import { resolveScopedConversation, telemetryStore } from './store/telemetryStore.js'; +import { + normalizeClientWindowMountMode, + resolveScopedConversation, + telemetryStore, +} from './store/telemetryStore.js'; import { getViewTabs, uiStore } from './store/uiStore.js'; +import { BridgeStatusNotice } from './components/settings/BridgeStatusNotice.js'; import { TopSessionHeader } from './components/layout/TopSessionHeader.js'; import { TopLongPillNav } from './components/ui/TopLongPillNav.js'; import { LiveOverviewView } from './views/LiveOverviewView.js'; @@ -33,6 +39,36 @@ export const App = defineComponent({ const stepsView = StepsDetailView(); const settingsView = SettingsView(); + const globalBridgeNotice = BridgeStatusNotice({ + dismissible: true, + }); + const bannerSlotEl = h('div', { className: 'app-bridge-banner-slot', hidden: true }, [ + globalBridgeNotice.el, + ]); + + function syncGlobalBridgeBanner() { + const activeView = uiStore.getState().activeView; + const telemetry = telemetryStore.getState().telemetry; + const settings = telemetry?.settings; + const mountMode = settings + ? normalizeClientWindowMountMode(settings.windowMountMode, settings.enableWindowOverlay) + : 'sidebar'; + const hasCtxOverrides = Boolean( + settings?.modelContextWindows && Object.keys(settings.modelContextWindows).length > 0 + ); + const shouldOfferGlobal = + !isWindowOverlayMode() && + activeView !== 'settings' && + (mountMode !== 'sidebar' || hasCtxOverrides); + globalBridgeNotice.refs.update({ + visible: shouldOfferGlobal, + contextMode: mountMode === 'sidebar' && hasCtxOverrides, + windowBridge: telemetry?.windowBridge || null, + hostPlatform: telemetry?.hostPlatform || 'win32', + }); + patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); + } + const viewMap = { overview: overviewView.el, consumption: consumptionView.el, @@ -49,6 +85,7 @@ export const App = defineComponent({ const shellEl = h('main', { className: 'app-shell' }, [ h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]), + bannerSlotEl, stageEl, ]); @@ -88,6 +125,7 @@ export const App = defineComponent({ settingsView.refs?.viewScrollbar?.refresh(); } syncStepsBadge(); + syncGlobalBridgeBanner(); } ); @@ -96,8 +134,16 @@ export const App = defineComponent({ stepCount: st.telemetry?.activeConversation?.stepCount ?? 0, totalStepsAllAgents: st.telemetry?.activeConversation?.totalStepsAllAgents ?? 0, subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0, + windowMountMode: st.telemetry?.settings?.windowMountMode, + enableWindowOverlay: st.telemetry?.settings?.enableWindowOverlay, + modelContextWindows: st.telemetry?.settings?.modelContextWindows, + windowBridge: st.telemetry?.windowBridge, + hostPlatform: st.telemetry?.hostPlatform, }), - () => syncStepsBadge() + () => { + syncStepsBadge(); + syncGlobalBridgeBanner(); + } ); const unsubScopeBadge = uiStore.subscribe( @@ -107,7 +153,11 @@ export const App = defineComponent({ const unsubI18n = i18nStore.subscribe( (st) => st.locale, - () => syncStepsBadge() + () => { + syncStepsBadge(); + globalBridgeNotice.refs.refreshLabels(); + patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); + } ); onCleanup(() => { @@ -115,6 +165,7 @@ export const App = defineComponent({ unsubStepCount(); unsubScopeBadge(); unsubI18n(); + globalBridgeNotice.destroy(); sessionHeader.destroy(); topPillNav.destroy(); overviewView.destroy(); @@ -128,6 +179,7 @@ export const App = defineComponent({ refs: { sessionHeader, topPillNav, + globalBridgeNotice, overviewView, consumptionView, stepsView, diff --git a/sidecars/panel/src/components/charts/SessionStepCharts.js b/sidecars/panel/src/components/charts/SessionStepCharts.js index 1021a04..359a92e 100644 --- a/sidecars/panel/src/components/charts/SessionStepCharts.js +++ b/sidecars/panel/src/components/charts/SessionStepCharts.js @@ -10,7 +10,7 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { - formatMetric, + formatAgentBadgeText, formatTokens, formatTokensPrecise, formatUsd, @@ -18,6 +18,7 @@ import { speedReasonText, } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; +import { getEffectiveLocale, t } from '../../i18n/index.js'; let sessionChartUid = 0; @@ -39,16 +40,16 @@ export const MODEL_COLOR_VARS = Object.freeze([ * @returns {string} */ export function getStepModelGroupKey(step) { - if (!step || typeof step !== 'object') return '模型未知'; - const rawLabel = String(step.modelLabel || step.label || '') + if (!step || typeof step !== 'object') return t('fmt.unknownModel'); + const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '') .replace(/\s*\[自动压缩\]\s*$/u, '') .replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .trim(); if (rawLabel) return rawLabel; - const rawShort = String(step.modelShort || step.shortName || '') - .replace(/·压缩\s*$/u, '') + const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '') + .replace(/·(?:压缩|Compact)\s*$/iu, '') .trim(); - return rawShort || '模型未知'; + return rawShort || t('fmt.unknownModel'); } /** @@ -422,21 +423,6 @@ export function computePublicationFit( }; } -/** - * 计算样本点上的平滑回归拟合值序列(供单元测试与轻量调用直接读取)。 - * - * @param {number[]} ys - * @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [bounds] - * @returns {number[]} - */ -export function computeLoessFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) { - const n = Array.isArray(ys) ? ys.length : 0; - if (n === 0) return []; - const xArr = - Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx); - return computePublicationFit(xArr, ys, { minVal, maxVal }).sampleFits; -} - /** * Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。 */ @@ -590,7 +576,17 @@ function computeStepTickIndices(count) { function formatStepAxisTag(st, showAgentPrefix) { const num = `#${Number(st?.stepIndex ?? 0)}`; if (!showAgentPrefix) return num; - const badge = st?.agentBadge || (st?.isSubagent ? '子' : '主'); + const badge = formatAgentBadgeText({ + agentKind: + st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0), + isMain: !st?.isSubagent, + isSideQuestion: Boolean(st?.isSideQuestion), + sideIndex: st?.sideIndex || 0, + index: st?.agentIndex || 0, + badgeText: st?.agentBadge, + }); return `${badge}${num}`; } @@ -725,7 +721,7 @@ export function createSessionLineChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '当前范围暂无可绘制的调用步骤', + text: t('chart.step.empty'), hidden: true, }); @@ -803,7 +799,10 @@ export function createSessionLineChart() { patchText(tipHeadLeft, pt.stepTag); patchText(tipHeadRight, pt.modelText); - patchText(tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : '未纳入'); + patchText( + tipMainLeft, + pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded') + ); patchText(tipMainRight, pt.secondaryRight || ''); patchAttr(tipSub, 'hidden', !pt.subDetail); if (pt.subDetail) { @@ -930,6 +929,7 @@ export function createSessionLineChart() { ? steps : steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st))); + patchText(emptyHintEl, t('chart.step.empty')); if (!matchedSteps.length) { currentPoints = []; lastSig = 'empty'; @@ -943,7 +943,7 @@ export function createSessionLineChart() { patchAttr(peakPill, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); clearHover(); - return { summaryBadge: '0 步' }; + return { summaryBadge: t('chart.step.zeroSteps') }; } const modelColorMap = new Map(); @@ -957,7 +957,7 @@ export function createSessionLineChart() { const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, { fallback: gk, }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } for (const st of matchedSteps) { @@ -970,7 +970,7 @@ export function createSessionLineChart() { } if (!modelLabelByGroup.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); - modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk); + modelLabelByGroup.set(gk, disp.baseText || disp.text || gk); } } @@ -1030,41 +1030,62 @@ export function createSessionLineChart() { if (metric === 'totalTokens') { value = isMultiCompare ? modelCumTok : runningTokens; - secondaryRight = `本步 +${formatTokens(stepTotalTok)}`; - subDetail = `入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 出 ${formatTokens(outTok)}`; + secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) }); + subDetail = t('chart.step.ioSplit', { + inTok: formatTokens(inTok), + cacheTok: formatTokens(cacheTok), + outTok: formatTokens(outTok), + }); } else if (metric === 'context') { value = ctxTok; if (hasPrevCtx) { const sign = ctxDelta >= 0 ? '+' : '-'; secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`; } else { - secondaryRight = `缓存 ${Number(st.cacheHitPct ?? 0)}%`; + secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) }); } subDetail = st.isCompactionStep - ? '上下文自动压缩检查点' - : `缓存命中 ${Number(st.cacheHitPct ?? 0)}% · 输出 +${formatTokens(outTok)}`; + ? t('chart.step.compactionCheckpoint') + : t('chart.step.cacheHitOut', { + pct: Number(st.cacheHitPct ?? 0), + outTok: formatTokens(outTok), + }); } else if (metric === 'tps') { valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0; value = valid ? Number(st.tokPerSec) : 0; - secondaryRight = Number.isFinite(st.ttftSec) ? `首字 ${st.ttftSec.toFixed(1)}s` : ''; + secondaryRight = Number.isFinite(st.ttftSec) + ? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) }) + : ''; subDetail = valid - ? `输出 ${formatTokens(outTok)} · 上下文 ${formatTokens(ctxTok)}` - : speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? '上下文压缩步' : '无测速样本'); + ? t('chart.step.outAndCtx', { + outTok: formatTokens(outTok), + ctxTok: formatTokens(ctxTok), + }) + : speedReasonText(st.selectedSpeedReason) || + (st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample')); } else if (metric === 'ttft') { valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0; value = valid ? Number(st.ttftSec) : 0; secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : ''; subDetail = valid - ? `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(st.cacheHitPct ?? 0)}%` + ? t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(st.cacheHitPct ?? 0), + }) : st.isCompactionStep - ? '上下文压缩步' - : '无首字计时样本'; + ? t('chart.step.compactionStep') + : t('chart.step.noTtftSample'); } else if (metric === 'cost') { valid = stepCost !== null; value = valid ? stepCost : 0; const shownCumCost = isMultiCompare ? modelCumCost : runningCost; - secondaryRight = `累计 ${formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 })}`; - subDetail = `缓存 ${Number(st.cacheHitPct ?? 0)}% · 本步 ${formatTokens(stepTotalTok)}`; + secondaryRight = t('chart.step.cumCost', { + cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }), + }); + subDetail = t('chart.step.cacheAndStepTok', { + pct: Number(st.cacheHitPct ?? 0), + tokens: formatTokens(stepTotalTok), + }); } if (valid) { @@ -1124,11 +1145,12 @@ export function createSessionLineChart() { const validPoints = points.filter((p) => p.valid); patchAttr(emptyHintEl, 'hidden', validPoints.length > 0); + const locale = getEffectiveLocale(); const colorSig = Array.from(modelColorMap.entries()) .map(([k, v]) => `${k}=${v}`) .join(','); const sig = - `${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + + `${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` + points .map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`) .join('|'); @@ -1263,12 +1285,12 @@ export function createSessionLineChart() { patchStyleVar(swatch, '--swatch-bg', colorVar); const stStat = perModelStats.get(gk); const baseLabel = modelLabelByGroup.get(gk) || gk; - let summarySuffix = '无样本'; + let summarySuffix = t('chart.step.noSamples'); if (stStat && stStat.count > 0) { if (metric === 'totalTokens') { summarySuffix = formatTokens(stStat.cumTok); } else if (metric === 'context') { - summarySuffix = `峰 ${formatTokens(stStat.max)}`; + summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) }); } else if (metric === 'tps' || metric === 'ttft') { summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count); } else if (metric === 'cost') { @@ -1306,7 +1328,10 @@ export function createSessionLineChart() { const peakPt = points[peakIdx]; patchText( peakPill, - `峰值 ${peakPt.stepTag} · ${formatChartMetricCompact(metric, peakPt.value)}` + t('chart.step.peakPill', { + tag: peakPt.stepTag, + val: formatChartMetricCompact(metric, peakPt.value), + }) ); patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor); const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100)); @@ -1322,28 +1347,42 @@ export function createSessionLineChart() { showHoverAt(hoveredIdx); } - let summaryBadge = `${matchedSteps.length}步`; + let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length }); const activeCompareCount = isMultiCompare ? targetKeys.length : 1; - const multiPrefix = isMultiCompare ? `${activeCompareCount} 模型 · ` : ''; + const multiPrefix = isMultiCompare + ? t('chart.step.multiPrefix', { count: activeCompareCount }) + : ''; if (metric === 'totalTokens') { - summaryBadge = `${multiPrefix}累计 ${formatTokens(runningTokens)}`; + summaryBadge = t('chart.step.sumTokens', { + prefix: multiPrefix, + tokens: formatTokens(runningTokens), + }); } else if (metric === 'context') { const lastCtx = points[points.length - 1]?.value || 0; summaryBadge = isMultiCompare - ? `${multiPrefix}峰值 ${formatTokens(maxVal)}` - : `当前 ${formatTokens(lastCtx)}`; + ? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) }) + : t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) }); } else if (metric === 'tps') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)} tok/s` - : '暂无有效样本'; + ? t('chart.step.meanTps', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'ttft') { summaryBadge = validCount > 0 - ? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)}s` - : '暂无有效样本'; + ? t('chart.step.meanSec', { + prefix: multiPrefix, + val: (validSum / validCount).toFixed(1), + }) + : t('chart.step.noValidSamples'); } else if (metric === 'cost') { - summaryBadge = `${multiPrefix}累计 ${formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 })}`; + summaryBadge = t('chart.step.sumCost', { + prefix: multiPrefix, + cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }), + }); } return { summaryBadge }; @@ -1434,7 +1473,7 @@ export function createModelFitChart() { const emptyHintEl = h('div', { className: 'sstep-empty-hint text-muted', - text: '该模型暂无有效拟合样本', + text: t('chart.fit.empty'), hidden: true, }); @@ -1449,14 +1488,16 @@ export function createModelFitChart() { tipSub, ]); - const fitMethodLabelEl = h('span', { text: 'LOESS 拟合' }); + const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') }); + const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') }); const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [ h('span', { className: 'sstep-fit-swatch is-ols' }), - h('span', { text: 'OLS 线性' }), + olsLegendTextEl, ]); + const obsLegendTextEl = h('span', { text: t('chart.fit.observed') }); const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [ h('span', { className: 'sstep-fit-swatch is-scatter' }), - h('span', { text: '观测值' }), + obsLegendTextEl, h('span', { className: 'sstep-fit-swatch is-curve' }), fitMethodLabelEl, h('span', { className: 'sstep-fit-swatch is-ci' }), @@ -1539,8 +1580,14 @@ export function createModelFitChart() { patchAttr(tooltipEl, 'hidden', false); patchText(tipHeadLeft, sp.stepTag); patchText(tipHeadRight, sp.modelText); - patchText(tipMainLeft, `拟合 ${formatChartMetricValue(currentMetric, sp.fitVal)}`); - patchText(tipMainRight, `观测 ${formatChartMetricValue(currentMetric, sp.rawVal)}`); + patchText( + tipMainLeft, + t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) }) + ); + patchText( + tipMainRight, + t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) }) + ); patchAttr(tipSub, 'hidden', false); if (sp.compareHint) { @@ -1554,7 +1601,10 @@ export function createModelFitChart() { const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0)); patchText( tipSub, - `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(sp.st?.cacheHitPct ?? 0)}%` + t('chart.step.ctxAndCache', { + ctxTok: formatTokens(ctxTok), + pct: Number(sp.st?.cacheHitPct ?? 0), + }) ); } @@ -1820,11 +1870,16 @@ export function createModelFitChart() { xVal: globalX, rawVal, stepTag: formatStepAxisTag(st, showAgentPrefix), - modelText: disp.text.replace(/·压缩\s*$/u, '').trim() || disp.text, + modelText: disp.baseText || disp.text, }); } } + const locale = getEffectiveLocale(); + patchText(emptyHintEl, t('chart.fit.empty')); + patchText(obsLegendTextEl, t('chart.fit.observed')); + patchText(olsLegendTextEl, t('chart.fit.olsLinear')); + if (fitCacheMetric !== metric) { fitCache.clear(); fitCacheMetric = metric; @@ -1848,9 +1903,10 @@ export function createModelFitChart() { patchAttr(singleLegendEl, 'hidden', false); patchAttr(multiLegendEl, 'hidden', true); patchAttr(emptyHintEl, 'hidden', false); + patchText(fitMethodLabelEl, t('chart.fit.loess')); patchText(fitStatsEl, 'n = 0'); clearHover(); - return { sampleCount: 0, summaryBadge: '0 样本' }; + return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') }; } patchAttr(emptyHintEl, 'hidden', true); @@ -1932,7 +1988,12 @@ export function createModelFitChart() { if (interp !== null) { peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`); } else { - peerParts.push(`${other.label} 均 ${formatChartMetricCompact(metric, other.pubFit.mean)}`); + peerParts.push( + t('chart.fit.peerMean', { + label: other.label, + val: formatChartMetricCompact(metric, other.pubFit.mean), + }) + ); } } return { @@ -1945,7 +2006,10 @@ export function createModelFitChart() { ciHigh: s.pubFit.sampleCiHigh[i], ciHalf: s.pubFit.sampleCiHalf[i], seriesColor: s.colorVar, - compareHint: peerParts.length > 0 ? `同图对比:${peerParts.join(' · ')}` : '', + compareHint: + peerParts.length > 0 + ? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') }) + : '', }; }); s.samples = sSamples; @@ -1955,7 +2019,7 @@ export function createModelFitChart() { currentSamples = combinedSamples; const sig = - `multi|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + seriesList .map( (s) => @@ -2069,7 +2133,7 @@ export function createModelFitChart() { fitStatsEl, seriesList.length <= 2 ? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ') - : `${seriesList.length} 条拟合线` + : t('chart.fit.curvesCount', { count: seriesList.length }) ); patchAttr(fitStatsEl, 'title', r2SummaryTitle); @@ -2081,7 +2145,10 @@ export function createModelFitChart() { return { sampleCount: combinedSamples.length, - summaryBadge: `${combinedSamples.length}步 · ${seriesList.length} 模型对比`, + summaryBadge: t('chart.fit.multiBadge', { + steps: combinedSamples.length, + models: seriesList.length, + }), }; } @@ -2096,7 +2163,10 @@ export function createModelFitChart() { const rawYs = filtered.map((d) => d.rawVal); const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false); - patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归'); + patchText( + fitMethodLabelEl, + pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg') + ); patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6); let dataMin = Infinity; @@ -2149,7 +2219,7 @@ export function createModelFitChart() { currentSamples = samples; const sig = - `single|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + + `single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` + samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|'); if (sig !== lastSig) { @@ -2225,7 +2295,10 @@ export function createModelFitChart() { } } - const summaryBadge = `${samples.length}步 · 均 ${formatChartMetricCompact(metric, pubFit.mean)}`; + const summaryBadge = t('chart.fit.singleBadge', { + steps: samples.length, + mean: formatChartMetricCompact(metric, pubFit.mean), + }); if (samples.length >= 2) { const rSign = pubFit.r >= 0 ? '+' : ''; const slopeSign = pubFit.slope >= 0 ? '+' : ''; @@ -2233,7 +2306,11 @@ export function createModelFitChart() { patchAttr( fitStatsEl, 'title', - `OLS: y = ${slopeSign}${pubFit.slope.toFixed(3)}x + ${pubFit.intercept.toFixed(2)} · 样本标准差 SD = ±${pubFit.sd.toFixed(2)}` + t('chart.fit.olsTitle', { + slope: `${slopeSign}${pubFit.slope.toFixed(3)}`, + intercept: pubFit.intercept.toFixed(2), + sd: pubFit.sd.toFixed(2), + }) ); } else { patchText(fitStatsEl, `n = ${samples.length}`); diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 0c57faf..0acbfa2 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -9,6 +9,7 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; +import { getEffectiveLocale, t } from '../../i18n/index.js'; /** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */ export const HEATMAP_DAYS_THRESHOLD = 90; @@ -176,7 +177,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) { if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue; if (ticks.length > 0 && c.col < nextAllowedCol) continue; const showYear = crossYear && (c.month === 1 || ticks.length === 0); - const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`; + const text = showYear + ? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month }) + : t('chart.trend.hmMonthOnly', { month: c.month }); ticks.push({ col: c.col, text }); nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap); } @@ -311,26 +314,41 @@ export function createTrendAreaChart() { const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]); // 类 GitHub 每日小格子热力图容器(> 90 天模式) - const weekdayLabels = ['一', '', '三', '', '五', '', '日']; + const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') }); + const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') }); + const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') }); + const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') }); const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [ h('span', { className: 'trend-hm-month-spacer' }), - ...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })), + wdayMonEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayWedEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdayFriEl, + h('span', { className: 'trend-hm-wday', text: '' }), + wdaySunEl, ]); const hmMonthsEl = h('div', { className: 'trend-hm-months' }); - const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' }); + const hmGridEl = h('div', { + className: 'trend-hm-grid', + role: 'grid', + 'aria-label': t('chart.trend.hmAria'), + }); const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]); const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]); const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]); const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' }); + const hmLessEl = h('span', { text: t('chart.trend.hmLess') }); + const hmMoreEl = h('span', { text: t('chart.trend.hmMore') }); const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [ - h('span', { text: '少' }), + hmLessEl, h('span', { className: 'trend-hm-swatch lv-0' }), h('span', { className: 'trend-hm-swatch lv-1' }), h('span', { className: 'trend-hm-swatch lv-2' }), h('span', { className: 'trend-hm-swatch lv-3' }), h('span', { className: 'trend-hm-swatch lv-4' }), - h('span', { text: '多' }), + hmMoreEl, ]); const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]); const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [ @@ -349,6 +367,8 @@ export function createTrendAreaChart() { let currentPts = []; let currentIsHeatmap = false; let currentHeatmapWeeks = 0; + let currentHeatmapFirstDow = 0; + let currentHeatmapGapPx = 2; let currentCellEls = []; let tickElsByIdx = new Map(); let hoveredIdx = -1; @@ -357,7 +377,10 @@ export function createTrendAreaChart() { function populateTooltipContent(slot) { patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); - patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`); + patchText( + tipCallsEl, + t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) }) + ); const slotTok = safeSlotTokens(slot.tokens); patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`); const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0; @@ -377,7 +400,11 @@ export function createTrendAreaChart() { if (hasSubBreakdown) { patchText( tipSubEl, - `入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}` + t('chart.step.ioSplit', { + inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)), + cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)), + outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)), + }) ); } } @@ -513,21 +540,117 @@ export function createTrendAreaChart() { showLineHoverAtIndex(idx); } - function findHeatmapCellFromEvent(e) { + function findDirectHeatmapCell(e) { let cur = e?.target || null; while (cur && cur !== hmGridEl) { const idxAttr = cur.getAttribute?.('data-slot-idx'); if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') { - return { idx: Number(idxAttr), cellEl: cur }; + const idx = Number(idxAttr); + if (Number.isFinite(idx) && idx >= 0 && idx < currentSlots.length) { + return { idx, cellEl: cur }; + } } cur = cur.parentNode || null; } return null; } + function resolveHeatmapCellFromPointer(e) { + const directHit = findDirectHeatmapCell(e); + if (directHit) return directHit; + + const clientX = Number(e?.clientX); + const clientY = Number(e?.clientY); + if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) { + if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { + return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + } + return null; + } + + const rect = hmGridEl.getBoundingClientRect?.(); + if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) { + if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { + return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + } + return null; + } + + const W = currentHeatmapWeeks; + const G = currentHeatmapGapPx; + const relX = clientX - rect.left; + const relY = clientY - rect.top; + if ( + relX < -(G + 1) || + relX > rect.width + G + 1 || + relY < -(G + 1) || + relY > rect.height + G + 1 + ) { + return null; + } + + const pitchX = (rect.width + G) / W; + const pitchY = (rect.height + G) / 7; + const cellW = Math.max(1, pitchX - G); + const cellH = Math.max(1, pitchY - G); + + function distanceToCell(c, r) { + const x0 = c * pitchX; + const y0 = r * pitchY; + const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0; + const dy = relY < y0 ? y0 - relY : relY > y0 + cellH ? relY - (y0 + cellH) : 0; + return { chebyshev: Math.max(dx, dy), distSq: dx * dx + dy * dy }; + } + + // 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁与边缘微抖 + if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) { + const curGridPos = currentHeatmapFirstDow + hoveredIdx; + const curCol = Math.floor(curGridPos / 7); + const curRow = curGridPos % 7; + if (distanceToCell(curCol, curRow).chebyshev <= G + 0.75) { + return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] }; + } + } + + // 快速扫过或初始落入格子间隙时,按网格步距吸附到最近的有效日期格 + const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX))); + const approxRow = Math.max(0, Math.min(6, Math.floor((relY + G * 0.5) / pitchY))); + const directSlotIdx = approxCol * 7 + approxRow - currentHeatmapFirstDow; + if ( + directSlotIdx >= 0 && + directSlotIdx < currentSlots.length && + currentCellEls[directSlotIdx] + ) { + return { idx: directSlotIdx, cellEl: currentCellEls[directSlotIdx] }; + } + + // 首周补位或末周未来空白边缘:仅当仍在相邻有效格的间隙光晕内才吸附,深入纯空白角则清空 + let bestIdx = -1; + let bestDistSq = Infinity; + for (let dc = -1; dc <= 1; dc++) { + const c = approxCol + dc; + if (c < 0 || c >= W) continue; + for (let dr = -1; dr <= 1; dr++) { + const r = approxRow + dr; + if (r < 0 || r > 6) continue; + const sIdx = c * 7 + r - currentHeatmapFirstDow; + if (sIdx < 0 || sIdx >= currentSlots.length || !currentCellEls[sIdx]) continue; + const d = distanceToCell(c, r); + if (d.chebyshev <= G + 1.5 && d.distSq < bestDistSq) { + bestDistSq = d.distSq; + bestIdx = sIdx; + } + } + } + if (bestIdx >= 0) { + return { idx: bestIdx, cellEl: currentCellEls[bestIdx] }; + } + return null; + } + function handleHeatmapPointer(e) { if (!currentIsHeatmap || !currentSlots.length) return; - const hit = findHeatmapCellFromEvent(e); + const hit = resolveHeatmapCellFromPointer(e); if (!hit || !Number.isFinite(hit.idx)) { clearHover(); return; @@ -630,19 +753,28 @@ export function createTrendAreaChart() { const nonZeroVals = []; for (let i = 0; i < slots.length; i++) { - const t = safeSlotTokens(slots[i]?.tokens); - if (t > 0) { + const tokVal = safeSlotTokens(slots[i]?.tokens); + if (tokVal > 0) { activeDays++; - nonZeroVals.push(t); + nonZeroVals.push(tokVal); } - if (t >= maxTokens) { - maxTokens = t; + if (tokVal >= maxTokens) { + maxTokens = tokVal; peakIdx = i; } } + const locale = getEffectiveLocale(); + patchText(wdayMonEl, t('chart.trend.wdayMon')); + patchText(wdayWedEl, t('chart.trend.wdayWed')); + patchText(wdayFriEl, t('chart.trend.wdayFri')); + patchText(wdaySunEl, t('chart.trend.wdaySun')); + patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria')); + patchText(hmLessEl, t('chart.trend.hmLess')); + patchText(hmMoreEl, t('chart.trend.hmMore')); + const sig = - `${useHeatmap ? 'hm' : `line:${viewW}`}|` + + `${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` + slots .map( (s) => @@ -664,10 +796,13 @@ export function createTrendAreaChart() { : 0; const totalCells = firstDow + slots.length; const totalWeeks = Math.max(1, Math.ceil(totalCells / 7)); + const gapPx = totalWeeks > 42 ? 1.5 : 2; currentHeatmapWeeks = totalWeeks; + currentHeatmapFirstDow = firstDow; + currentHeatmapGapPx = gapPx; patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks)); - patchStyleVar(hmBodyEl, '--hm-gap', totalWeeks > 42 ? '1.5px' : '2px'); + patchStyleVar(hmBodyEl, '--hm-gap', `${gapPx}px`); // 重建顶部对齐月份标签 while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild); @@ -719,8 +854,13 @@ export function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const summaryText = maxTokens > 0 && peakSlot?.label - ? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` - : `活跃 0/${slots.length} 天`; + ? t('chart.trend.hmActivePeak', { + active: activeDays, + total: slots.length, + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) + : t('chart.trend.hmActiveZero', { total: slots.length }); patchText(hmSummaryEl, summaryText); if (hoveredIdx >= slots.length) { @@ -819,7 +959,10 @@ export function createTrendAreaChart() { const peakSlot = slots[peakIdx]; const peakText = maxTokens > 0 && peakSlot?.label - ? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` + ? t('chart.trend.peakPill', { + label: peakSlot.label, + tokens: formatTokensPrecise(maxTokens), + }) : formatTokensPrecise(maxTokens); patchText(peakPill, peakText); const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100)); diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index d5a163c..0de020b 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -10,6 +10,7 @@ import { i18nStore, t } from '../../i18n/index.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { fetchTelemetry, + formatAgentBadgeText, normalizeClientUpdateMode, telemetryStore, triggerPluginUpdate, @@ -106,20 +107,24 @@ export const TopSessionHeader = defineComponent({ let lastActiveCascadeId = ''; + function syncSessionScopeOnCascadeChange(telemetry) { + const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; + if (!currentCascadeId) return; + if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { + lastActiveCascadeId = currentCascadeId; + const uiSt = uiStore.getState(); + if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') { + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + } + } else { + lastActiveCascadeId = currentCascadeId; + } + } + function renderHeaderState() { const telSt = telemetryStore.getState(); const uiSt = uiStore.getState(); const telemetry = telSt.telemetry; - const currentCascadeId = telemetry?.activeConversation?.cascadeId || ''; - if (currentCascadeId && lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) { - lastActiveCascadeId = currentCascadeId; - if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') { - uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); - return; - } - } else if (currentCascadeId) { - lastActiveCascadeId = currentCascadeId; - } if (!uiSt.monitorVisible) return; patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate')); @@ -240,7 +245,7 @@ export const TopSessionHeader = defineComponent({ } else if (isRunning) { const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning); const runSuffix = - hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : ''; + hasSubagents && runningAgent ? ` · ${formatAgentBadgeText(runningAgent)}` : ''; patchSvgIcon(statusIcon, 'bolt'); patchText(statusText, t('header.statusGenerating', { suffix: runSuffix })); patchClasses(statusTag, { @@ -277,7 +282,10 @@ export const TopSessionHeader = defineComponent({ syncState: st.syncState, telemetry: st.telemetry, }), - () => renderHeaderState() + (slice) => { + syncSessionScopeOnCascadeChange(slice.telemetry); + renderHeaderState(); + } ); const unsubI18n = i18nStore.subscribe( diff --git a/sidecars/panel/src/components/layout/WindowOverlayShell.js b/sidecars/panel/src/components/layout/WindowOverlayShell.js index 9c6c97f..08a460a 100644 --- a/sidecars/panel/src/components/layout/WindowOverlayShell.js +++ b/sidecars/panel/src/components/layout/WindowOverlayShell.js @@ -8,32 +8,41 @@ * 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。 */ +import { + WINDOW_BRIDGE_KEY, + WINDOW_OVERLAY_KEY, + WINDOW_OVERLAY_METHODS, + readInjectedWindowBridge, +} from '../../../shared/window-bridge-protocol.mjs'; import { App } from '../../App.js'; -import { applyAppearanceToRoot } from '../../core/appearance.js'; +import { + PANEL_SCALE_FACTORS, + applyAppearanceToRoot, + normalizeClientFontScale, +} from '../../core/appearance.js'; import { h, isEventInside, patchAttr, patchClasses, - patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { formatElapsedSec } from '../../core/formatters.js'; import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js'; -import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js'; +import { i18nStore, setI18nLanguage, t } from '../../i18n/index.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { - RING_CIRCUMFERENCE, + buildCapsuleSlotContext, createCapsuleSlotNode, + resolveMultiSessionCapsuleState, syncCapsuleSlotNodes, } from '../widgets/CapsuleBarWidget.js'; +import { LiveActivityWidget } from '../widgets/LiveActivityWidget.js'; import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js'; import { DEFAULT_CLIENT_HOVER_MODULES, extractHostRouteCascadeId, fetchTelemetry, - formatAgentBadgeText, - getAgentBadgeClass, + isMacHostPlatform, normalizeClientHoverModules, normalizeClientPopoverWidth, normalizeClientPopoverWidthMode, @@ -813,7 +822,7 @@ function isImmediatelyBeforeNode(node, refNode) { function isIdeExtensionChatFrame() { try { if (typeof window === 'undefined') return false; - if (window.__AGUsageMonitorBridge?.isIdeChatFrame === true) return true; + if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true; return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || '')); } catch { return false; @@ -824,7 +833,7 @@ function resolveActiveDockTarget(options = undefined) { const settings = telemetryStore.getState().telemetry?.settings; const rawMode = settings?.windowMountMode ?? - (typeof window !== 'undefined' ? window.__AGUsageMonitorBridge?.mountMode : undefined); + readInjectedWindowBridge()?.mountMode; const mountMode = options?.mountMode || normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay); @@ -925,14 +934,14 @@ export function mountWindowOverlay() { let carryOverMultiPinnedOpen = false; let carryOverPointer = null; try { - const prevOv = window.__AGUsageMonitorOverlay; + const prevOv = window[WINDOW_OVERLAY_KEY]; carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null; carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.()); carryOverPopoverOpen = Boolean(prevOv?.isOpen?.()); carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.()); carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.()); carryOverPointer = prevOv?.getLastPointer?.() || null; - prevOv?.dispose?.(); + prevOv?.[WINDOW_OVERLAY_METHODS.dispose]?.(); } catch { // 忽略旧实例卸载异常 } @@ -971,9 +980,6 @@ export function mountWindowOverlay() { let multiPinned = false; let hoverLeaveTimer = null; let multiLeaveTimer = null; - const manualSubExpandMap = new Map(); - const multiTimersMap = new Map(); - let multiLiveTickTimer = null; let hasPointerCoords = Boolean( carryOverPointer && Number.isFinite(carryOverPointer.x) && @@ -1071,52 +1077,6 @@ export function mountWindowOverlay() { }, 90); } - function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) { - const now = Date.now(); - const prev = multiTimersMap.get(timerKey); - let startMs = prev?.startMs || 0; - if (!prev || prev.sig !== sig) { - const validRaw = Number(rawStartMs || 0); - startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; - } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { - startMs = Number(rawStartMs); - } - multiTimersMap.set(timerKey, { sig, startMs, el: targetEl }); - const elapsedSec = Math.max(0, (now - startMs) / 1000); - patchText(targetEl, formatElapsedSec(elapsedSec)); - } - - function tickMultiElapsedDisplay() { - const now = Date.now(); - for (const entry of multiTimersMap.values()) { - if (!entry?.el) continue; - const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; - patchText(entry.el, formatElapsedSec(elapsedSec)); - } - } - - function pauseMultiLiveTicker() { - if (multiLiveTickTimer) { - clearInterval(multiLiveTickTimer); - multiLiveTickTimer = null; - } - } - - function stopMultiLiveTicker() { - pauseMultiLiveTicker(); - multiTimersMap.clear(); - } - - function ensureMultiLiveTicker() { - if (multiTimersMap.size === 0) { - stopMultiLiveTicker(); - return; - } - if (!multiLiveTickTimer) { - multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000); - } - } - function inspectSessionInMonitor(cascadeId) { if (!cascadeId || cascadeId === 'current') return; uiStore.setState({ @@ -1374,8 +1334,6 @@ export function mountWindowOverlay() { portalShadow.appendChild(portalStyleEl); const initialSettings = telemetryStore.getState().telemetry?.settings; - applyAppearanceToRoot(capsuleHost, initialSettings, { includeFontScale: false }); - applyAppearanceToRoot(portalHost, initialSettings, { includeFontScale: true }); // 悬停全景概览浮层(完全解耦至 widgetRegistry,由 hoverModules 动态驱动 0..4 个独立组件,零硬编码) const hoverUpdateVerText = h('span', { text: t('capsule.hoverNewVerGeneric') }); @@ -1415,105 +1373,7 @@ export function mountWindowOverlay() { [hoverUpdateBar, hoverWidgetsContainer] ); - // 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新) - function createMultiLiveSubRow() { - const subBadge = h('span', { - className: 'agent-badge badge-sub-1', - text: t('fmt.subBadge', { index: 1 }), - }); - const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') }); - const subSummary = h('span', { className: 'live-sub-summary', text: '' }); - const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' }); - const rowEl = h('div', { className: 'live-sub-row' }, [ - h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]), - subElapsed, - ]); - return { - el: rowEl, - refs: { rowEl, subBadge, subRole, subSummary, subElapsed }, - }; - } - - function createMultiLiveTaskCard() { - const dotIcon = createSvgIcon('dot', { size: 11 }); - patchClasses(dotIcon, { 'is-pulsing': true }); - const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); - const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession') }); - const hereTagEl = h('span', { - className: 'wm-session-tag is-here', - hidden: true, - text: t('multi.hereTag'), - }); - const metricsEl = h('span', { - className: 'wm-task-metrics text-mono', - hidden: true, - text: '', - }); - const subToggleBtn = h('button', { - type: 'button', - className: 'live-sub-toggle', - hidden: true, - text: t('live.subToggleIdle', { total: 0, arrow: '▸' }), - }); - const elapsedEl = h('span', { - className: 'live-activity-elapsed text-mono', - text: '0s', - }); - - const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]), - h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]), - ]); - - const mainBadge = h('span', { - className: 'agent-badge badge-main', - hidden: true, - text: t('fmt.mainBadge'), - }); - const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking') }); - const mainProgress = h('span', { - className: 'live-activity-progress text-mono', - hidden: true, - text: '', - }); - const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); - const mainDetail = h('span', { - className: 'live-activity-detail', - hidden: true, - text: '', - }); - - const mainRowEl = h('div', { className: 'live-task-main-row' }, [ - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - ]); - - const subListEl = h('div', { className: 'live-sub-list', hidden: true }); - const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); - - return { - el: cardEl, - refs: { - cardEl, - dotIcon, - titleEl, - hereTagEl, - metricsEl, - subToggleBtn, - elapsedEl, - mainBadge, - mainPhase, - mainProgress, - mainSep, - mainDetail, - subListEl, - }, - }; - } - + // 左侧多会话实时看板浮层(受控复用 LiveActivityWidget,保持零硬编码与同一套计时器状态机) const multiPinBadge = h('span', { className: 'wm-pin-badge', hidden: true, @@ -1530,10 +1390,16 @@ export function mountWindowOverlay() { multiEmptyTextEl, ]), ]); - const multiRunningListEl = h('div', { - className: 'live-activity-list', - hidden: true, - 'aria-live': 'polite', + const multiRunningWidget = LiveActivityWidget({ + defaultExpandRunningSubs: true, + showSessionExtras: true, + isVisibleFn: () => Boolean(multiOpen && !document.hidden && !disposed), + onSelectSession: inspectSessionInMonitor, + onLayoutChange: () => { + if (multiOpen) { + positionFloatingElements(); + } + }, }); const multiTitleTextEl = h('span', { text: t('multi.title') }); @@ -1567,7 +1433,7 @@ export function mountWindowOverlay() { } }, }, - [multiHeaderEl, multiEmptyEl, multiRunningListEl] + [multiHeaderEl, multiEmptyEl, multiRunningWidget.el] ); // 完整四标签悬浮容器 @@ -1584,9 +1450,19 @@ export function mountWindowOverlay() { [appInstance.el] ); + function syncPortalAppearance(settings) { + applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false }); + applyAppearanceToRoot(portalHost, settings, { includeFontScale: true }); + const scaleKey = normalizeClientFontScale(settings?.fontScale); + popoverEl.setAttribute?.('data-font-scale', scaleKey); + hoverTipEl.setAttribute?.('data-font-scale', scaleKey); + multiPanelEl.setAttribute?.('data-font-scale', scaleKey); + } + portalShadow.appendChild(multiPanelEl); portalShadow.appendChild(hoverTipEl); portalShadow.appendChild(popoverEl); + syncPortalAppearance(initialSettings); (document.body || document.documentElement).appendChild(portalHost); // --- 3. 几何测量、IDE 主题桥接、顶栏停靠与防溢出定位 --- @@ -1759,6 +1635,8 @@ export function mountWindowOverlay() { return true; } + const isMac = () => isMacHostPlatform(telemetryStore.getState().telemetry); + function updateFixedFallbackPosition() { const dockMode = capsuleHost.getAttribute('data-dock'); if (dockMode === 'flow' || dockMode === 'ide-titlebar' || dockMode === 'composer') { @@ -1768,12 +1646,13 @@ export function mountWindowOverlay() { } try { const vw = Number(window.innerWidth || 1280); - let rightOffset = 144; + const minRight = isMac() ? 12 : 144; + let rightOffset = minRight; const anchor = findNativeTopRightAnchor(); if (anchor?.getBoundingClientRect) { const r = anchor.getBoundingClientRect(); if (r.width > 0 && r.left > 0 && r.left < vw) { - rightOffset = Math.max(144, Math.ceil(vw - r.left + 6)); + rightOffset = Math.max(minRight, Math.ceil(vw - r.left + 6)); } } capsuleHost.style.top = '7px'; @@ -1783,6 +1662,16 @@ export function mountWindowOverlay() { } } + function syncCapsuleOsAttr() { + const nextOs = isMac() ? 'mac' : 'default'; + if (capsuleHost.getAttribute('data-os') !== nextOs) { + patchAttr(capsuleHost, 'data-os', nextOs); + if (capsuleHost.getAttribute('data-dock') === 'fixed') { + updateFixedFallbackPosition(); + } + } + } + function measureAvailableTitlebarWidth(dockTarget) { try { const titlebar = dockTarget?.titlebar || null; @@ -1852,10 +1741,19 @@ export function mountWindowOverlay() { } } } - if (!hasVisibleWindowControls && navigator?.windowControlsOverlay?.visible) { + if (navigator?.windowControlsOverlay?.visible) { const wcoRect = navigator.windowControlsOverlay.getTitlebarAreaRect?.(); - if (wcoRect && wcoRect.width > 0 && tbRect.right > wcoRect.right + 4) { - rightSiblingsWidth += tbRect.right - wcoRect.right; + if (wcoRect && wcoRect.width > 0) { + if (!hasVisibleWindowControls && tbRect.right > wcoRect.right + 4) { + rightSiblingsWidth += tbRect.right - wcoRect.right; + } + const leftOverlayInset = wcoRect.left - tbRect.left; + if (leftOverlayInset > leftContentWidth) { + leftContentWidth = Math.min( + Math.round(tbRect.width * 0.45), + Math.ceil(leftOverlayInset) + ); + } } } @@ -1868,10 +1766,11 @@ export function mountWindowOverlay() { if (tbRect.width > 0) { const titleEl = titlebar.firstElementChild; const titleInner = titleEl?.firstElementChild; + const macTrafficReserve = isMac() ? 80 : 168; const contentStart = titleInner?.getBoundingClientRect ? Math.max(8, titleInner.getBoundingClientRect().left - tbRect.left) - : tbRect.left < 168 - ? 168 - tbRect.left + : tbRect.left < macTrafficReserve + ? macTrafficReserve - tbRect.left : 12; const minTitleWidth = 180; let siblingButtonsWidth = 64; @@ -1925,8 +1824,17 @@ export function mountWindowOverlay() { const vh = Number(window.innerHeight || 800); const navRight = getLeftSidebarRightEdge(vw); const minLeft = navRight > 0 ? Math.max(12, navRight + 12) : 12; - const defaultCardW = Math.min(FLOATING_CARD_WIDTH, Math.max(280, vw - 24)); - const defaultMultiW = Math.min(MULTI_PANEL_WIDTH, Math.max(280, vw - 24)); + const curSettings = telemetryStore.getState().telemetry?.settings; + const panelScale = + PANEL_SCALE_FACTORS[normalizeClientFontScale(curSettings?.fontScale)] ?? 1; + const defaultCardW = Math.min( + Math.round(FLOATING_CARD_WIDTH * panelScale), + Math.max(280, vw - 24) + ); + const defaultMultiW = Math.min( + Math.round(MULTI_PANEL_WIDTH * panelScale), + Math.max(280, vw - 24) + ); const isDockComposer = capsuleHost.getAttribute('data-dock') === 'composer'; if (multiOpen) { @@ -1974,9 +1882,8 @@ export function mountWindowOverlay() { 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); + let desiredPopW = Math.min(Math.round(POPOVER_BASE_WIDTH * panelScale), maxPopCardW); if (popWidthMode === 'custom') { desiredPopW = Math.min( normalizeClientPopoverWidth(curSettings?.popoverWidth), @@ -2141,6 +2048,7 @@ export function mountWindowOverlay() { if (bodyOrDoc && !portalHost.isConnected) { bodyOrDoc.appendChild(portalHost); } + syncCapsuleOsAttr(); ensureWorkbenchThemeObserved(); const dockTarget = resolveRuntimeDockTarget(); @@ -2309,12 +2217,13 @@ export function mountWindowOverlay() { patchAttr(multiPanelEl, 'hidden', !multiOpen); if (multiOpen) { renderCapsuleTelemetry(); + multiRunningWidget.refs.resumeTicker(); positionFloatingElements(); if (typeof requestAnimationFrame === 'function') { requestAnimationFrame(() => positionFloatingElements()); } } else { - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); } } @@ -2389,18 +2298,10 @@ export function mountWindowOverlay() { } function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) { - if (manualSubExpandMap.size > 0) { - const runningIds = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of manualSubExpandMap.keys()) { - if (!runningIds.has(id)) manualSubExpandMap.delete(id); - } + if (!multiOpen || document.hidden) { + multiRunningWidget.refs.pauseTicker(); + return; } - if (!multiOpen || document.hidden) return; - const localeKey = getEffectiveLocale(); - const hostRouteLower = String( - hostRouteConversationId || extractHostRouteCascadeId() || '' - ).toLowerCase(); - patchText( multiRunningMetaEl, runningCount > 0 @@ -2410,201 +2311,10 @@ export function mountWindowOverlay() { : t('multi.allIdle') ); patchAttr(multiEmptyEl, 'hidden', runningCount > 0); - patchAttr(multiRunningListEl, 'hidden', runningCount === 0); - - if (runningCount === 0) { - stopMultiLiveTicker(); - patchKeyedList(multiRunningListEl, [], {}); - } else { - const activeTimerKeys = new Set(); - for (const item of rawRunningList) { - activeTimerKeys.add(`main:${item.cascadeId}`); - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - if (subCount > 0 && isExp) { - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); - } - } - } - } - - patchKeyedList(multiRunningListEl, rawRunningList, { - keyFn: (item) => item.cascadeId, - sigFn: (item) => { - const runSubs = Number(item.runningSubagentCount || 0); - const isExp = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubs > 0; - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - const subSig = (item.subagents || []) - .map( - (s) => - `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` - ) - .join('|'); - return `${localeKey}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; - }, - createRow: createMultiLiveTaskCard, - updateRow: (refs, item) => { - const act = item.mainActivity || { - phase: 'thinking', - label: t('live.thinking'), - detail: '', - stepProgress: '', - startedAtMs: item.lastModifiedMs || 0, - signature: `fallback:${item.lastModifiedMs || 0}`, - }; - const isWaiting = act.phase === 'waiting'; - const isCompacting = act.phase === 'compacting'; - patchClasses(refs.cardEl, { - 'is-waiting': isWaiting, - 'is-compacting': isCompacting, - }); - patchClasses(refs.dotIcon, { 'is-pulsing': true }); - - const convTitle = - item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); - patchText(refs.titleEl, convTitle); - patchAttr(refs.titleEl, 'title', t('multi.inspectSessionTitle', { title: convTitle })); - refs.titleEl.onclick = (e) => { - e.stopPropagation(); - inspectSessionInMonitor(item.cascadeId); - }; - - const isHere = - Boolean(hostRouteLower) && - String(item.cascadeId || '').toLowerCase() === hostRouteLower; - patchText(refs.hereTagEl, t('multi.hereTag')); - patchAttr(refs.hereTagEl, 'hidden', !isHere); - - const metricParts = []; - if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { - metricParts.push( - `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` - ); - } - if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { - metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); - } - const metricsStr = metricParts.join(' · '); - patchAttr(refs.metricsEl, 'hidden', !metricsStr); - if (metricsStr) { - patchText(refs.metricsEl, metricsStr); - } - - const subCount = Number(item.subagentCount || item.subagents?.length || 0); - const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = manualSubExpandMap.has(item.cascadeId) - ? manualSubExpandMap.get(item.cascadeId) - : runSubCount > 0; - patchText(refs.mainBadge, t('fmt.mainBadge')); - patchAttr(refs.mainBadge, 'hidden', subCount === 0); - patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); - if (subCount > 0) { - const arrow = isExpanded ? '▾' : '▸'; - const toggleText = - runSubCount > 0 - ? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow }) - : t('live.subToggleIdle', { total: subCount, arrow }); - patchText(refs.subToggleBtn, toggleText); - patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); - refs.subToggleBtn.onclick = (e) => { - e.stopPropagation(); - manualSubExpandMap.set(item.cascadeId, !isExpanded); - renderCapsuleTelemetry(); - if (multiOpen) { - positionFloatingElements(); - } - }; - } - - const mainTimerKey = `main:${item.cascadeId}`; - activeTimerKeys.add(mainTimerKey); - bindMultiElapsedTimer( - mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, - act.startedAtMs, - refs.elapsedEl - ); - - patchText(refs.mainPhase, act.label || t('live.thinking')); - const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; - patchAttr(refs.mainProgress, 'hidden', !progText); - if (progText) { - patchText(refs.mainProgress, progText); - } - - const detailStr = act.detail || ''; - patchAttr(refs.mainSep, 'hidden', !detailStr); - patchAttr(refs.mainDetail, 'hidden', !detailStr); - patchText(refs.mainDetail, detailStr); - - const showSubs = subCount > 0 && isExpanded; - patchAttr(refs.subListEl, 'hidden', !showSubs); - if (showSubs) { - const subItems = item.subagents || []; - patchKeyedList(refs.subListEl, subItems, { - keyFn: (sub) => sub.cascadeId, - sigFn: (sub) => - `${localeKey}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`, - createRow: createMultiLiveSubRow, - updateRow: (subRefs, sub) => { - const subAct = sub.liveActivity || { - phase: sub.isRunning ? 'thinking' : 'done', - label: sub.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: sub.lastModifiedMs || 0, - }; - patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); - const subBadgeCls = getAgentBadgeClass(sub.index || 1, false); - patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`); - patchText(subRefs.subBadge, formatAgentBadgeText(sub)); - patchText(subRefs.subRole, sub.role || sub.shortLabel || t('fmt.subAgent')); - - const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryText = sub.isRunning - ? `${subAct.label || t('live.running')}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}` - : t('live.doneWithSteps', { steps: sub.stepCount || 0 }); - patchText(subRefs.subSummary, summaryText); - - const subTimerKey = `sub:${sub.cascadeId}`; - if (sub.isRunning) { - activeTimerKeys.add(subTimerKey); - bindMultiElapsedTimer( - subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs || sub.lastModifiedMs, - subRefs.subElapsed - ); - } else { - multiTimersMap.delete(subTimerKey); - patchText( - subRefs.subElapsed, - t('header.convMetaSteps', { count: sub.stepCount || 0 }) - ); - } - }, - }); - } - }, - }); - - for (const k of [...multiTimersMap.keys()]) { - if (!activeTimerKeys.has(k)) { - multiTimersMap.delete(k); - } - } - ensureMultiLiveTicker(); - tickMultiElapsedDisplay(); - } + multiRunningWidget.refs.update({ + items: rawRunningList, + hostRouteConversationId, + }); } function renderHoverWidgets() { @@ -2624,8 +2334,8 @@ export function mountWindowOverlay() { const telemetry = telSt.telemetry; setI18nLanguage(telemetry?.settings?.language); - applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false }); - applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true }); + syncPortalAppearance(telemetry?.settings); + syncCapsuleOsAttr(); const showMulti = telemetry?.settings?.showTopbarMultiSession !== false; patchAttr(multiBtn, 'hidden', !showMulti); @@ -2647,7 +2357,7 @@ export function mountWindowOverlay() { patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false }); patchText(multiLabel, t('capsule.multiZero')); patchText(multiRunningMetaEl, t('multi.loading')); - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); applyCapsuleSlots(slotKeys, { hasTelemetry: false }); return; @@ -2660,138 +2370,36 @@ export function mountWindowOverlay() { uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId ); - const activeConv = telemetry.activeConversation || {}; - const overviewActive = overviewScopedConv || activeConv; - const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - // --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 --- - const rawRunningList = - Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0 - ? telemetry.runningConversations - : activeConv.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: activeConv.cascadeId || 'current', - title: activeConv.title || t('live.currentSession'), - isCurrentSelected: true, - isMainRunning: Boolean(activeConv.isRunning), - isRunning: true, - mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, (agents?.length || 1) - 1), - runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, - latestTokPerSec: overviewActive.latestTokPerSec ?? null, - contextUsedPct: usedPct, - subagents: (agents || []) - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; - - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const overviewActive = overviewScopedConv || telemetry.activeConversation || {}; + const slotCtx = buildCapsuleSlotContext(telemetry, { + scopedConv: capsuleScopedConv, + overviewConv: overviewActive, + ctxAgent, + aggregated, + }); + const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } = + resolveMultiSessionCapsuleState(telemetry, { + agents, + aggregated, + latestTokPerSec: overviewActive.latestTokPerSec ?? null, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId); + renderMultiRunningPanel( + rawRunningList, + runningCount, + runningSubCount, + telSt.hostRouteConversationId + ); - // --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 --- - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capActive = capsuleScopedConv || aggregated || activeConv || {}; - const tps = - capsuleScopedConv?.latestTokPerSec ?? - aggregated?.latestTokPerSec ?? - activeConv.latestTokPerSec ?? - null; - const avgTps = - capsuleScopedConv?.avgTokPerSec ?? - aggregated?.avgTokPerSec ?? - activeConv.avgTokPerSec ?? - null; - const ttft = - capsuleScopedConv?.latestTtftSec ?? - aggregated?.latestTtftSec ?? - activeConv.latestTtftSec ?? - null; - const capsuleStepCost = - capsuleScopedConv?.latestStepCostUsd ?? - aggregated?.latestStepCostUsd ?? - activeConv.latestStepCostUsd ?? - null; - const sessionCost = - capsuleScopedConv?.sessionCostUsd ?? - aggregated?.sessionCostUsd ?? - activeConv.sessionCostUsd ?? - null; - const cacheHitPct = - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null; - const latestPromptTokens = capActive.latestPromptTokens ?? null; - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - applyCapsuleSlots(slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps, - avgTps, - ttft, - stepCost: capsuleStepCost, - sessionCost, - cacheHitPct, - latestPromptTokens, - sessionTokens, - quotas: telemetry.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + applyCapsuleSlots(slotKeys, slotCtx); const updateMode = normalizeClientUpdateMode( telemetry.settings?.pluginUpdateMode, @@ -2968,7 +2576,7 @@ export function mountWindowOverlay() { const onVisibilityChange = () => { if (document.hidden) { uiStore.setState({ monitorVisible: false }); - pauseMultiLiveTicker(); + multiRunningWidget.refs.pauseTicker(); hasPointerCoords = false; if (tooltipOpen) { setTooltipOpen(false); @@ -3070,28 +2678,28 @@ export function mountWindowOverlay() { const handle = { bundleVersion, - ensureAlive() { + [WINDOW_OVERLAY_METHODS.ensureAlive]() { if (disposed) return false; return ensureCapsuleDocked(); }, - syncHostRoute() { + [WINDOW_OVERLAY_METHODS.syncHostRoute]() { if (disposed) return false; syncHostRouteIfChanged(); return true; }, - updateBridge(nextBridge) { + [WINDOW_OVERLAY_METHODS.updateBridge](nextBridge) { if (disposed || !nextBridge || typeof nextBridge !== 'object') return false; const port = Number(nextBridge.port || 0); const token = String(nextBridge.token || ''); if (!Number.isInteger(port) || port <= 0 || !token) return false; - const cur = window.__AGUsageMonitorBridge || {}; + const cur = readInjectedWindowBridge() || {}; const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token; cur.port = port; cur.token = token; if (portChanged) { cur.transportMode = 'http'; } - window.__AGUsageMonitorBridge = cur; + window[WINDOW_BRIDGE_KEY] = cur; void fetchTelemetry({ force: false }); return true; }, @@ -3101,7 +2709,7 @@ export function mountWindowOverlay() { getLastPointer() { return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null; }, - deliverRpc(responses) { + [WINDOW_OVERLAY_METHODS.deliverRpc](responses) { if (disposed) return 0; return deliverCdpBridgeResponses(responses); }, @@ -3126,14 +2734,13 @@ export function mountWindowOverlay() { isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned), isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned), getLayoutMode: () => layoutMode, - getDockKind: () => String(capsuleHost.getAttribute('data-dock') || ''), - getMountMode: () => lastAppliedMountMode, - applyMountMode(nextMode) { + [WINDOW_OVERLAY_METHODS.getDockKind]: () => String(capsuleHost.getAttribute('data-dock') || ''), + [WINDOW_OVERLAY_METHODS.getMountMode]: () => lastAppliedMountMode, + [WINDOW_OVERLAY_METHODS.applyMountMode](nextMode) { if (disposed) return false; const normalized = normalizeClientWindowMountMode(nextMode, nextMode !== 'sidebar'); - if (typeof window !== 'undefined' && window.__AGUsageMonitorBridge) { - window.__AGUsageMonitorBridge.mountMode = normalized; - } + const bridgeConfig = readInjectedWindowBridge(); + if (bridgeConfig) bridgeConfig.mountMode = normalized; const curTel = telemetryStore.getState().telemetry; if (curTel?.settings) { telemetryStore.setState({ @@ -3150,7 +2757,7 @@ export function mountWindowOverlay() { lastAppliedMountMode = normalized; return ensureCapsuleDocked(); }, - dispose() { + [WINDOW_OVERLAY_METHODS.dispose]() { if (disposed) return; disposed = true; clearInterval(watchdogTimer); @@ -3162,7 +2769,7 @@ export function mountWindowOverlay() { clearTimeout(multiLeaveTimer); multiLeaveTimer = null; } - stopMultiLiveTicker(); + multiRunningWidget.refs.stopLiveTicker(); if (dockRafId && typeof cancelAnimationFrame === 'function') { cancelAnimationFrame(dockRafId); dockRafId = 0; @@ -3203,12 +2810,12 @@ export function mountWindowOverlay() { try { portalHost.remove(); } catch {} - if (window.__AGUsageMonitorOverlay === handle) { - delete window.__AGUsageMonitorOverlay; + if (window[WINDOW_OVERLAY_KEY] === handle) { + delete window[WINDOW_OVERLAY_KEY]; } }, }; - window.__AGUsageMonitorOverlay = handle; + window[WINDOW_OVERLAY_KEY] = handle; return handle; } diff --git a/sidecars/panel/src/components/settings/BridgeStatusNotice.js b/sidecars/panel/src/components/settings/BridgeStatusNotice.js new file mode 100644 index 0000000..ee3e47b --- /dev/null +++ b/sidecars/panel/src/components/settings/BridgeStatusNotice.js @@ -0,0 +1,303 @@ +/** + * @fileoverview Shared CDP / Window Bridge diagnostic & one-click relaunch card (`BridgeStatusNotice.js`). + * Surfaces automatic shortcut provisioning status and a one-click host relaunch button when + * Antigravity 2.33.0+ runs without an active `DevToolsActivePort` (`no_devtools_port` / `cdp_unreachable`). + */ + +import { defineComponent } from '../../core/component.js'; +import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; +import { isWindowOverlayMode } from '../../core/httpClient.js'; +import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; +import { t } from '../../i18n/index.js'; +import { triggerBridgeHostRelaunch } from '../../store/telemetryStore.js'; + +const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0'; + +async function copyTextToClipboard(text) { + try { + if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + return true; + } + } catch { + // Fallback to temporary textarea inside restricted webview contexts + } + try { + if (typeof document === 'undefined' || !document.body) return false; + const area = document.createElement('textarea'); + area.value = text; + area.setAttribute('readonly', 'true'); + area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;'; + document.body.appendChild(area); + area.select?.(); + const ok = Boolean(document.execCommand?.('copy')); + document.body.removeChild(area); + return ok; + } catch { + return false; + } +} + +export const BridgeStatusNotice = defineComponent({ + name: 'BridgeStatusNotice', + setup({ props, onCleanup }) { + let contextMode = Boolean(props?.contextMode); + const dismissible = Boolean(props?.dismissible); + let lastPayload = { + visible: false, + windowBridge: null, + hostPlatform: 'win32', + }; + let dismissed = false; + let copied = false; + let copiedTimer = null; + let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed' + let relaunchResetTimer = null; + let destroyed = false; + + const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' }); + const titleEl = h('strong', { className: 'settings-bridge-title', text: '' }); + const bodyEl = h('p', { className: 'settings-bridge-desc', text: '' }); + + const dismissBtnEl = dismissible + ? h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm settings-bridge-dismiss-btn', + 'aria-label': t('settings.bridge.dismissAria'), + title: t('settings.bridge.dismissAria'), + onClick: () => { + dismissed = true; + render(); + props?.onDismiss?.(); + }, + }, + [createSvgIcon('close', { size: 11 })] + ) + : null; + + const relaunchBtnIconEl = createSvgIcon('refresh', { size: 11 }); + const relaunchBtnTextEl = h('span', { + className: 'settings-bridge-relaunch-text', + text: t('settings.bridge.relaunchBtn'), + }); + const relaunchBtnEl = h( + 'button', + { + type: 'button', + className: 'settings-bridge-relaunch-btn', + onClick: async () => { + if (relaunchState === 'relaunching' || destroyed) return; + relaunchState = 'relaunching'; + if (relaunchResetTimer) { + clearTimeout(relaunchResetTimer); + relaunchResetTimer = null; + } + syncActionButtons(); + try { + const res = await triggerBridgeHostRelaunch(); + if (destroyed) return; + if (!res || res.ok === false) { + relaunchState = 'failed'; + syncActionButtons(); + relaunchResetTimer = setTimeout(() => { + relaunchResetTimer = null; + if (destroyed) return; + relaunchState = 'idle'; + syncActionButtons(); + }, 3500); + relaunchResetTimer?.unref?.(); + return; + } + // Reset button if host is still open after 9s (e.g. cancelled close prompt) + relaunchResetTimer = setTimeout(() => { + relaunchResetTimer = null; + if (destroyed) return; + relaunchState = 'idle'; + syncActionButtons(); + }, 9000); + relaunchResetTimer?.unref?.(); + } catch { + if (destroyed) return; + relaunchState = 'failed'; + syncActionButtons(); + relaunchResetTimer = setTimeout(() => { + relaunchResetTimer = null; + if (destroyed) return; + relaunchState = 'idle'; + syncActionButtons(); + }, 3500); + relaunchResetTimer?.unref?.(); + } + }, + }, + [relaunchBtnIconEl, relaunchBtnTextEl] + ); + + const copyBtnIconEl = createSvgIcon('copy', { size: 11 }); + const copyBtnTextEl = h('span', { + className: 'settings-bridge-copy-text', + text: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }), + }); + const copyBtnEl = h( + 'button', + { + type: 'button', + className: 'btn-ghost-sm settings-bridge-copy-btn', + onClick: async () => { + await copyTextToClipboard(LAUNCH_FLAG_TEXT); + if (destroyed) return; + copied = true; + if (copiedTimer) clearTimeout(copiedTimer); + syncActionButtons(); + copiedTimer = setTimeout(() => { + copiedTimer = null; + if (destroyed) return; + copied = false; + syncActionButtons(); + }, 1800); + copiedTimer?.unref?.(); + }, + }, + [copyBtnIconEl, copyBtnTextEl] + ); + + const headLeftEl = h('div', { className: 'settings-bridge-head-main' }, [headIconEl, titleEl]); + const headRowEl = h( + 'div', + { className: 'settings-bridge-head' }, + dismissBtnEl ? [headLeftEl, dismissBtnEl] : [headLeftEl] + ); + const actionsRowEl = h('div', { className: 'settings-bridge-actions' }, [ + relaunchBtnEl, + copyBtnEl, + ]); + + const rootEl = h( + 'div', + { + className: 'settings-bridge-notice', + role: 'status', + hidden: true, + }, + [headRowEl, bodyEl, actionsRowEl] + ); + + function syncActionButtons() { + const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false; + patchAttr(relaunchBtnEl, 'hidden', !canRelaunch); + patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching'); + patchText( + relaunchBtnTextEl, + relaunchState === 'relaunching' + ? t('settings.bridge.relaunchingBtn') + : relaunchState === 'failed' + ? t('settings.bridge.relaunchFailed') + : t('settings.bridge.relaunchBtn') + ); + + patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy'); + patchText( + copyBtnTextEl, + copied + ? t('settings.bridge.copiedBtn') + : t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }) + ); + + if (dismissBtnEl) { + const aria = t('settings.bridge.dismissAria'); + patchAttr(dismissBtnEl, 'aria-label', aria); + patchAttr(dismissBtnEl, 'title', aria); + } + } + + function render() { + const wb = lastPayload.windowBridge; + const state = String(wb?.state || '').trim(); + if (state === 'active') { + dismissed = false; + } + const shouldShow = + !dismissed && + Boolean(lastPayload.visible) && + !isWindowOverlayMode() && + (state === 'no_devtools_port' || state === 'cdp_unreachable'); + + patchAttr(rootEl, 'hidden', !shouldShow); + if (!shouldShow) return; + + const isAutoConfigured = Boolean( + wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured + ); + patchClasses(rootEl, { + 'is-restart': isAutoConfigured, + 'is-warn': !isAutoConfigured, + }); + patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning'); + + let titleText = ''; + if (isAutoConfigured) { + titleText = contextMode + ? t('settings.bridge.ctxRestartTitle') + : t('settings.bridge.restartTitle'); + } else if (contextMode) { + titleText = t('settings.bridge.ctxTitle'); + } else if (state === 'cdp_unreachable') { + titleText = t('settings.bridge.unreachableTitle'); + } else { + titleText = t('settings.bridge.noPortTitle'); + } + + const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase(); + let bodyText = ''; + if (isAutoConfigured) { + bodyText = t('settings.bridge.restartBody'); + } else if (plat === 'darwin') { + bodyText = t('settings.bridge.guideMac'); + } else if (plat === 'linux') { + bodyText = t('settings.bridge.guideLinux'); + } else { + bodyText = t('settings.bridge.guideWin'); + } + + patchText(titleEl, titleText); + patchText(bodyEl, bodyText); + syncActionButtons(); + } + + function update(next = {}) { + if (typeof next.contextMode === 'boolean') { + contextMode = next.contextMode; + } + lastPayload = { + ...lastPayload, + ...next, + }; + render(); + } + + onCleanup(() => { + destroyed = true; + if (copiedTimer) { + clearTimeout(copiedTimer); + copiedTimer = null; + } + if (relaunchResetTimer) { + clearTimeout(relaunchResetTimer); + relaunchResetTimer = null; + } + }); + + return { + el: rootEl, + refs: { + update, + refreshLabels: render, + relaunchBtnEl, + copyBtnEl, + dismissBtnEl, + }, + }; + }, +}); diff --git a/sidecars/panel/src/components/settings/structurePreviewMock.js b/sidecars/panel/src/components/settings/structurePreviewMock.js index 0e7b14e..9cc2e4a 100644 --- a/sidecars/panel/src/components/settings/structurePreviewMock.js +++ b/sidecars/panel/src/components/settings/structurePreviewMock.js @@ -27,7 +27,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides totalTokens: 142800, limitTokens: 256000, compactionLimitTokens: 256000, + compactionUsedTokens: 142800, usedPct: 55.8, + messagesTokens: 119660, toolResultsTokens: 86400, assistantTokens: 24200, systemToolsTokens: 11800, @@ -44,7 +46,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides totalTokens: 72704, limitTokens: 256000, compactionLimitTokens: 256000, + compactionUsedTokens: 72704, usedPct: 28.4, + messagesTokens: 63704, toolResultsTokens: 51200, assistantTokens: 11400, systemToolsTokens: 5600, @@ -198,6 +202,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides responseTokens: 260, cacheHitPct: 0, costUsd: 0.198, + inCostUsd: 0.19, + cacheCostUsd: 0, + outCostUsd: 0.008, createdAtMs: anchorMinMs - 215_000, turnIndex: 1, rootTurnIndex: 1, @@ -220,10 +227,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides isRunning: true, stepCount: 16, speedSampleCount: 15, + speedSummary: { sampleCount: 15, excludedCount: 1 }, latestTokPerSec: 68.4, avgTokPerSec: 54.8, latestTtftSec: 1.15, avgTtftSec: 1.62, + ttftSummary: { avgSec: 1.62, sampleCount: 15 }, latestStepCostUsd: 0.042, sessionCostUsd: 1.16, latestCacheHitPct: 94.5, @@ -239,6 +248,24 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides latestUpstreamModel: 'gemini-4-carbon-high', activeModelLabel: 'Gemini 4 Carbon (High)', activeModelShort: 'gemini-4-carbon', + activeModelUpstream: 'gemini-4-carbon-high', + sessionUnpricedCalls: 0, + modelBreakdown: [ + { + modelKey: 'MODEL_PLACEHOLDER_M37', + modelShort: 'gemini-4-carbon', + modelLabel: 'Gemini 4 Carbon (High)', + upstreamModel: 'gemini-4-carbon-high', + calls: 16, + inputTokens: 152400, + cacheReadTokens: 1260000, + outputTokens: 22100, + thinkingTokens: 14200, + totalTokens: 1434500, + costUsd: 1.16, + sharePct: 100, + }, + ], context: mainContext, recentSteps: mockSteps.filter((s) => !s.isSubagent), }; @@ -254,10 +281,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides isRunning: false, stepCount: 8, speedSampleCount: 8, + speedSummary: { sampleCount: 8, excludedCount: 0 }, latestTokPerSec: 96.2, avgTokPerSec: 88.5, latestTtftSec: 0.68, avgTtftSec: 0.82, + ttftSummary: { avgSec: 0.82, sampleCount: 8 }, latestStepCostUsd: 0.009, sessionCostUsd: 0.12, latestCacheHitPct: 88.1, @@ -273,33 +302,69 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides latestUpstreamModel: 'gemini-3.8-flash-n', activeModelLabel: 'Gemini 3.8 Flash', activeModelShort: 'gemini-3.8-flash', + activeModelUpstream: 'gemini-3.8-flash-n', + sessionUnpricedCalls: 0, + modelBreakdown: [ + { + modelKey: 'MODEL_PLACEHOLDER_M42', + modelShort: 'gemini-3.8-flash', + modelLabel: 'Gemini 3.8 Flash', + upstreamModel: 'gemini-3.8-flash-n', + calls: 8, + inputTokens: 34000, + cacheReadTokens: 280000, + outputTokens: 6300, + thinkingTokens: 2100, + totalTokens: 320300, + costUsd: 0.12, + sharePct: 100, + }, + ], context: subContext, recentSteps: mockSteps.filter((s) => s.isSubagent), }; const aggregated = { ...mainAgent, + agentId: 'all', + isMain: false, + agentKind: 'all', + agentOrdinal: 0, + badgeText: t('header.scopeAllShort'), + activeAgentId: 'main', + activeAgentKind: 'main', + activeAgentOrdinal: 0, stepCount: 24, speedSampleCount: 23, + speedSummary: { sampleCount: 23, excludedCount: 1 }, avgTokPerSec: 59.6, avgTtftSec: 1.38, + ttftSummary: { avgSec: 1.38, sampleCount: 23 }, sessionCostUsd: 1.28, + sessionUnpricedCalls: 0, sessionCacheHitPct: 88.9, inputTokens: 186400, cacheReadTokens: 1540000, outputTokens: 28400, totalTokens: 1754800, - activeAgentBadge: '主', + activeAgentBadge: t('fmt.mainBadge'), + modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown], recentSteps: mockSteps, }; return { settings: mergedSettings, account: { - planName: 'Google AI Pro', - aiCredits: 1200, + tierName: 'Google AI Ultra', + planName: 'Pro', + aiCredits: 0, }, quotas: { + meta: { + hasOfficialData: true, + isStale: false, + refreshFailed: false, + }, activePool: { family: 'Gemini', poolKey: 'Gemini', diff --git a/sidecars/panel/src/components/ui/TopLongPillNav.js b/sidecars/panel/src/components/ui/TopLongPillNav.js index 5eb93d7..4360afd 100644 --- a/sidecars/panel/src/components/ui/TopLongPillNav.js +++ b/sidecars/panel/src/components/ui/TopLongPillNav.js @@ -90,12 +90,14 @@ export const TopLongPillNav = defineComponent({ } patchText(entry.labelEl, item.label); - if (item.badge !== undefined && item.badge !== null && item.badge !== '') { + const hasBadge = item.badge !== undefined && item.badge !== null && item.badge !== ''; + if (hasBadge) { patchAttr(entry.badgeEl, 'hidden', false); patchText(entry.badgeEl, `(${item.badge})`); } else { patchAttr(entry.badgeEl, 'hidden', true); } + patchAttr(entry.btn, 'title', hasBadge ? `${item.label} (${item.badge})` : item.label); const isActive = item.value === modelValue; patchClasses(entry.btn, { 'is-active': isActive }); diff --git a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js index 995cdca..e74c8c6 100644 --- a/sidecars/panel/src/components/widgets/CapsuleBarWidget.js +++ b/sidecars/panel/src/components/widgets/CapsuleBarWidget.js @@ -14,10 +14,96 @@ import { normalizeClientWindowMountMode, resolveScopedConversation, } from '../../store/telemetryStore.js'; +import { buildFallbackRunningConversations } from './LiveActivityWidget.js'; export const RING_RADIUS = 5.2; export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2); +/** + * Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation. + */ +export function buildCapsuleSlotContext( + data, + { scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {} +) { + if (!data) return { hasTelemetry: false }; + const activeConv = data.activeConversation || {}; + const overviewActive = overviewConv || scopedConv || aggregated || activeConv; + const capActive = scopedConv || aggregated || activeConv || {}; + const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {}; + const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); + const totalTokens = Number(ctx.totalTokens || 0); + const usedPct = + limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; + const dashOffset = +( + RING_CIRCUMFERENCE * + (1 - Math.max(0, Math.min(100, usedPct)) / 100) + ).toFixed(2); + + const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); + const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); + const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); + const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); + const sessionTokens = + Number(capActive.stepCount || 0) > 0 || + capActive.totalTokens != null || + capInTok + capCacheTok + capOutTok > 0 + ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) + : null; + + return { + hasTelemetry: true, + usedPct, + dashOffset, + isRunning, + tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null, + avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null, + ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null, + stepCost: + scopedConv?.latestStepCostUsd ?? + aggregated?.latestStepCostUsd ?? + activeConv.latestStepCostUsd ?? + null, + sessionCost: + scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null, + cacheHitPct: + Number(capActive.stepCount || 0) > 0 + ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null + : null, + latestPromptTokens: capActive.latestPromptTokens ?? null, + sessionTokens, + quotas: data.quotas, + }; +} + +/** + * Compute multi-session button state & normalized running conversation list. + */ +export function resolveMultiSessionCapsuleState( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + const rawRunningList = buildFallbackRunningConversations(data, { + agents, + aggregated, + latestTokPerSec, + contextUsedPct, + }); + const runningCount = rawRunningList.length; + const runningSubCount = rawRunningList.reduce( + (acc, item) => acc + Number(item.runningSubagentCount || 0), + 0 + ); + const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const multiBtnText = + runningCount > 0 + ? runningSubCount > 0 + ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) + : t('capsule.multiRunning', { count: runningCount }) + : t('capsule.multiZero'); + return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText }; +} + /** * Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring. */ @@ -222,11 +308,6 @@ export const CapsuleBarWidget = defineComponent({ ] ); - const titlebarRightMock = h('div', { className: 'preview-win-controls', 'aria-hidden': 'true' }, [ - h('span', { className: 'preview-win-dot' }), - h('span', { className: 'preview-win-dot' }), - h('span', { className: 'preview-win-dot' }), - ]); const composerSendMock = h( 'span', { className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true }, @@ -236,7 +317,7 @@ export const CapsuleBarWidget = defineComponent({ const hostBarEl = h( 'div', { className: 'preview-capsule-bar', 'data-mount-mode': 'dual' }, - [titlebarLeftMock, composerLeftMock, capsuleCluster, titlebarRightMock, composerSendMock] + [titlebarLeftMock, composerLeftMock, capsuleCluster, composerSendMock] ); const sidebarHintEl = h('div', { @@ -265,7 +346,6 @@ export const CapsuleBarWidget = defineComponent({ }); patchAttr(titlebarLeftMock, 'hidden', isComposer); - patchAttr(titlebarRightMock, 'hidden', isComposer); patchAttr(composerLeftMock, 'hidden', !isComposer); patchAttr(composerSendMock, 'hidden', !isComposer); patchAttr(sidebarHintEl, 'hidden', !isSidebar); @@ -280,75 +360,26 @@ export const CapsuleBarWidget = defineComponent({ return; } - const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation( + const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation( data, 'all', 'auto' ); - const activeConv = data.activeConversation || {}; - const capActive = scopedConv || aggregated || activeConv; - const ctx = ctxAgent?.context || capActive.context || activeConv.context || {}; - const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000); - const totalTokens = Number(ctx.totalTokens || 0); - const usedPct = - limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0; - const dashOffset = +( - RING_CIRCUMFERENCE * - (1 - Math.max(0, Math.min(100, usedPct)) / 100) - ).toFixed(2); - - const rawRunningList = Array.isArray(data.runningConversations) - ? data.runningConversations - : []; - const runningCount = rawRunningList.length; - const runningSubCount = rawRunningList.reduce( - (acc, item) => acc + Number(item.runningSubagentCount || 0), - 0 - ); - const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting'); + const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated }); + const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, { + agents, + aggregated, + contextUsedPct: slotCtx.usedPct, + }); patchClasses(multiBtn, { 'is-running': runningCount > 0 && !hasWaiting, 'is-waiting': runningCount > 0 && hasWaiting, }); - const multiBtnText = - runningCount > 0 - ? runningSubCount > 0 - ? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount }) - : t('capsule.multiRunning', { count: runningCount }) - : t('capsule.multiZero'); patchText(multiLabel, multiBtnText); - const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning); - const capInTok = Math.max(0, Number(capActive.inputTokens || 0)); - const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0)); - const capOutTok = Math.max(0, Number(capActive.outputTokens || 0)); - const sessionTokens = - Number(capActive.stepCount || 0) > 0 || - capActive.totalTokens != null || - capInTok + capCacheTok + capOutTok > 0 - ? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok)) - : null; - - patchClasses(capsuleBtn, { 'is-running': isRunning }); - syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, { - hasTelemetry: true, - usedPct, - dashOffset, - isRunning, - tps: capActive.latestTokPerSec ?? null, - avgTps: capActive.avgTokPerSec ?? null, - ttft: capActive.latestTtftSec ?? null, - stepCost: capActive.latestStepCostUsd ?? null, - sessionCost: capActive.sessionCostUsd ?? null, - cacheHitPct: - Number(capActive.stepCount || 0) > 0 - ? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null - : null, - latestPromptTokens: capActive.latestPromptTokens ?? null, - sessionTokens, - quotas: data.quotas, - }); + patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning }); + syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx); } return { diff --git a/sidecars/panel/src/components/widgets/ContextWindowWidget.js b/sidecars/panel/src/components/widgets/ContextWindowWidget.js index 185b33c..8540c5c 100644 --- a/sidecars/panel/src/components/widgets/ContextWindowWidget.js +++ b/sidecars/panel/src/components/widgets/ContextWindowWidget.js @@ -309,12 +309,16 @@ export const ContextWindowWidget = defineComponent({ if (interactiveInspector) { patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (hasSubagents && ctxAgent) { - const rawActiveBadge = aggregated?.activeAgentBadge || '主'; - const activeBadgeText = isEnglishLocale() - ? rawActiveBadge === '主' - ? t('fmt.mainBadge') - : rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n })) - : rawActiveBadge; + const activeBadgeText = formatAgentBadgeText({ + agentKind: + aggregated?.activeAgentKind || + (!aggregated?.activeAgentId || aggregated.activeAgentId === 'main' + ? 'main' + : 'subagent'), + agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0), + isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main', + badgeText: aggregated?.activeAgentBadge, + }); const pillItems = [ { diff --git a/sidecars/panel/src/components/widgets/LiveActivityWidget.js b/sidecars/panel/src/components/widgets/LiveActivityWidget.js index 0b42767..23f4b2a 100644 --- a/sidecars/panel/src/components/widgets/LiveActivityWidget.js +++ b/sidecars/panel/src/components/widgets/LiveActivityWidget.js @@ -1,7 +1,8 @@ /** * @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`). * Displays active multi-session running conversations & collapsible subagent activity - * with an isolated 1s elapsed timer lifecycle. + * with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode + * and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`). */ import { defineComponent } from '../../core/component.js'; @@ -12,23 +13,85 @@ import { patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { formatElapsedSec } from '../../core/formatters.js'; +import { + formatAgentBadgeText, + formatElapsedSec, + formatLiveActivityDetail, + formatLiveActivityLabel, + getAgentBadgeClass, +} from '../../core/formatters.js'; import { createSvgIcon } from '../../icons/SvgIcon.js'; import { getEffectiveLocale, t } from '../../i18n/index.js'; import { + extractHostRouteCascadeId, fetchTelemetry, - formatAgentBadgeText, - getAgentBadgeClass, resolveScopedConversation, telemetryStore, } from '../../store/telemetryStore.js'; import { uiStore } from '../../store/uiStore.js'; +export function buildFallbackRunningConversations( + data, + { agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {} +) { + if (!data) return []; + if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) { + return data.runningConversations; + } + const activeConv = data.activeConversation || {}; + if (!activeConv.isRunning && !aggregated?.isRunning) return []; + return [ + { + cascadeId: activeConv.cascadeId || 'current', + title: activeConv.title || t('live.currentSession'), + isCurrentSelected: true, + isMainRunning: Boolean(activeConv.isRunning), + isRunning: true, + mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null, + subagentCount: Math.max(0, (agents?.length || 1) - 1), + runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length, + ...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}), + ...(contextUsedPct !== undefined ? { contextUsedPct } : {}), + subagents: (agents || []) + .filter((a) => !a.isMain) + .map((s, idx) => ({ + cascadeId: s.cascadeId || s.agentId, + index: s.index || idx + 1, + agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1), + customRole: s.customRole, + ...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}), + badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), + shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, + role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, + isRunning: Boolean(s.isRunning), + stepCount: Number(s.stepCount || 0), + lastModifiedMs: s.lastModifiedMs || 0, + liveActivity: s.liveActivity || { + phase: s.isRunning ? 'thinking' : 'done', + actionKey: s.isRunning ? 'thinking' : 'done', + label: s.isRunning ? t('live.thinking') : t('live.done'), + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ]; +} + export const LiveActivityWidget = defineComponent({ name: 'LiveActivityWidget', setup({ props, onCleanup }) { const interactive = props.interactive !== false; const preview = Boolean(props.preview); + const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs); + const showSessionExtras = Boolean(props.showSessionExtras); + const onSelectSession = + typeof props.onSelectSession === 'function' ? props.onSelectSession : null; + const onLayoutChange = + typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null; const getCtxAgentId = typeof props.getCtxAgentId === 'function' ? props.getCtxAgentId @@ -42,10 +105,19 @@ export const LiveActivityWidget = defineComponent({ 'aria-live': 'polite', }); - const expandedTaskConvIds = new Set(); + const manualSubExpandMap = new Map(); const activityTimersMap = new Map(); let liveTickTimer = null; - let latestData = null; + let latestUpdateArgs = null; + + function resolveIsExpanded(item) { + const runSubCount = Number(item?.runningSubagentCount || 0); + if (!interactive) return runSubCount > 0; + if (manualSubExpandMap.has(item.cascadeId)) { + return Boolean(manualSubExpandMap.get(item.cascadeId)); + } + return defaultExpandRunningSubs ? runSubCount > 0 : false; + } function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { const now = Date.now(); @@ -108,6 +180,20 @@ export const LiveActivityWidget = defineComponent({ className: 'live-task-title', text: t('live.currentSession'), }); + const hereTagEl = showSessionExtras + ? h('span', { + className: 'wm-session-tag is-here', + hidden: true, + text: t('multi.hereTag'), + }) + : null; + const metricsEl = showSessionExtras + ? h('span', { + className: 'wm-task-metrics text-mono', + hidden: true, + text: '', + }) + : null; const subToggleBtn = h('button', { type: 'button', className: 'live-sub-toggle', @@ -120,8 +206,16 @@ export const LiveActivityWidget = defineComponent({ }); const headerEl = h('div', { className: 'live-task-header' }, [ - h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), - h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), + h('div', { className: 'live-task-title-wrap' }, [ + dotWrap, + titleEl, + ...(hereTagEl ? [hereTagEl] : []), + ]), + h('div', { className: 'live-task-header-right' }, [ + ...(metricsEl ? [metricsEl] : []), + subToggleBtn, + elapsedEl, + ]), ]); const mainBadge = h('span', { @@ -162,6 +256,8 @@ export const LiveActivityWidget = defineComponent({ cardEl, dotIcon, titleEl, + hereTagEl, + metricsEl, subToggleBtn, elapsedEl, mainBadge, @@ -200,103 +296,86 @@ export const LiveActivityWidget = defineComponent({ }; } - function update({ data } = {}) { - latestData = data || null; - if (!data) { + function update({ data = null, items = null, hostRouteConversationId = '' } = {}) { + latestUpdateArgs = { data, items, hostRouteConversationId }; + if (!data && !Array.isArray(items)) { patchAttr(liveActivityBar, 'hidden', true); stopLiveTicker(); return; } - const { agents, aggregated } = resolveScopedConversation( - data, - 'all', - getCtxAgentId() - ); + let rawRunningList = Array.isArray(items) ? items : null; + if (!rawRunningList) { + const { agents, aggregated } = resolveScopedConversation( + data, + 'all', + getCtxAgentId() + ); + rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated }); + } - const rawRunningList = - Array.isArray(data.runningConversations) && data.runningConversations.length > 0 - ? data.runningConversations - : data.activeConversation?.isRunning || aggregated?.isRunning - ? [ - { - cascadeId: data.activeConversation?.cascadeId || 'current', - title: data.activeConversation?.title || t('live.currentSession'), - isCurrentSelected: true, - isMainRunning: Boolean(data.activeConversation?.isRunning), - isRunning: true, - mainActivity: - data.activeConversation?.liveActivity || aggregated?.liveActivity || null, - subagentCount: Math.max(0, agents.length - 1), - runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length, - subagents: agents - .filter((a) => !a.isMain) - .map((s, idx) => ({ - cascadeId: s.cascadeId || s.agentId, - index: s.index || idx + 1, - badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }), - shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`, - role: s.role || `${t('fmt.subAgent')} #${idx + 1}`, - isRunning: Boolean(s.isRunning), - stepCount: Number(s.stepCount || 0), - lastModifiedMs: s.lastModifiedMs || 0, - liveActivity: s.liveActivity || { - phase: s.isRunning ? 'thinking' : 'done', - label: s.isRunning ? t('live.thinking') : t('live.done'), - detail: '', - stepProgress: '', - startedAtMs: s.lastModifiedMs || 0, - signature: `${s.agentId}:${s.stepCount || 0}`, - }, - })), - }, - ] - : []; + if (manualSubExpandMap.size > 0) { + const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); + for (const id of [...manualSubExpandMap.keys()]) { + if (!runningIdsSet.has(id)) { + manualSubExpandMap.delete(id); + } + } + } const hasRunningTasks = rawRunningList.length > 0; patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); if (!hasRunningTasks) { stopLiveTicker(); - expandedTaskConvIds.clear(); + patchKeyedList(liveActivityBar, [], {}); return; } + if (!isVisibleFn()) { + pauseTicker(); + return; + } + + const locale = getEffectiveLocale(); + const hostRouteLower = showSessionExtras + ? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase() + : ''; + const activeTimerKeys = new Set(); for (const item of rawRunningList) { activeTimerKeys.add(`main:${item.cascadeId}`); - for (const sub of item.subagents || []) { - if (sub?.isRunning) { - activeTimerKeys.add(`sub:${sub.cascadeId}`); + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const isExp = resolveIsExpanded(item); + if (subCount > 0 && isExp) { + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } } } } - const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); - for (const id of [...expandedTaskConvIds]) { - if (!runningIdsSet.has(id)) { - expandedTaskConvIds.delete(id); - } - } - - const locale = getEffectiveLocale(); patchKeyedList(liveActivityBar, rawRunningList, { keyFn: (item) => item.cascadeId, sigFn: (item) => { - const isExp = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : Number(item.runningSubagentCount || 0) > 0; + const isExp = resolveIsExpanded(item); + const isHere = + showSessionExtras && + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; const subSig = (item.subagents || []) .map( (s) => `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}` ) .join('|'); - return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; + return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`; }, createRow: createLiveTaskCard, updateRow: (refs, item) => { const act = item.mainActivity || { phase: 'thinking', + actionKey: 'thinking', label: t('live.thinking'), detail: '', stepProgress: '', @@ -315,9 +394,18 @@ export const LiveActivityWidget = defineComponent({ const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession'); patchText(refs.titleEl, convTitle); if (interactive && !preview) { - patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle })); - refs.titleEl.onclick = () => { - if (item.cascadeId && item.cascadeId !== 'current') { + patchAttr( + refs.titleEl, + 'title', + onSelectSession + ? t('multi.inspectSessionTitle', { title: convTitle }) + : t('live.switchSessionTitle', { title: convTitle }) + ); + refs.titleEl.onclick = (e) => { + e?.stopPropagation?.(); + if (onSelectSession) { + onSelectSession(item.cascadeId); + } else if (item.cascadeId && item.cascadeId !== 'current') { uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); telemetryStore.setState({ selectedConversationId: item.cascadeId }); fetchTelemetry({ force: false }); @@ -325,11 +413,32 @@ export const LiveActivityWidget = defineComponent({ }; } + if (showSessionExtras && refs.hereTagEl && refs.metricsEl) { + const isHere = + Boolean(hostRouteLower) && + String(item.cascadeId || '').toLowerCase() === hostRouteLower; + patchText(refs.hereTagEl, t('multi.hereTag')); + patchAttr(refs.hereTagEl, 'hidden', !isHere); + + const metricParts = []; + if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) { + metricParts.push( + `${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s` + ); + } + if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) { + metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`); + } + const metricsStr = metricParts.join(' · '); + patchAttr(refs.metricsEl, 'hidden', !metricsStr); + if (metricsStr) { + patchText(refs.metricsEl, metricsStr); + } + } + const subCount = Number(item.subagentCount || item.subagents?.length || 0); const runSubCount = Number(item.runningSubagentCount || 0); - const isExpanded = interactive - ? expandedTaskConvIds.has(item.cascadeId) - : runSubCount > 0; + const isExpanded = resolveIsExpanded(item); patchText(refs.mainBadge, t('fmt.mainBadge')); patchAttr(refs.mainBadge, 'hidden', subCount === 0); patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); @@ -349,39 +458,37 @@ export const LiveActivityWidget = defineComponent({ ); refs.subToggleBtn.onclick = (e) => { e.stopPropagation(); - if (expandedTaskConvIds.has(item.cascadeId)) { - expandedTaskConvIds.delete(item.cascadeId); - } else { - expandedTaskConvIds.add(item.cascadeId); - } - if (latestData) update({ data: latestData }); + manualSubExpandMap.set(item.cascadeId, !isExpanded); + if (latestUpdateArgs) update(latestUpdateArgs); + onLayoutChange?.(); }; } } + const mainLabel = formatLiveActivityLabel(act, 'live.thinking'); + const detailStr = formatLiveActivityDetail(act); const mainTimerKey = `main:${item.cascadeId}`; activeTimerKeys.add(mainTimerKey); bindLiveElapsedTimer( mainTimerKey, - `${item.cascadeId}:${act.signature || act.label}`, + `${item.cascadeId}:${act.signature || mainLabel}`, act.startedAtMs, refs.elapsedEl ); - patchText(refs.mainPhase, act.label || t('live.thinking')); + patchText(refs.mainPhase, mainLabel); const progText = act.stepProgress ? `[${act.stepProgress}]` : ''; patchAttr(refs.mainProgress, 'hidden', !progText); if (progText) { patchText(refs.mainProgress, progText); } - const detailStr = act.detail || ''; patchAttr(refs.mainSep, 'hidden', !detailStr); patchAttr(refs.mainDetail, 'hidden', !detailStr); patchText(refs.mainDetail, detailStr); - if (interactive) { - const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; + if (interactive && !showSessionExtras) { + const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; patchAttr(refs.cardEl, 'title', fullTooltip); } @@ -397,6 +504,7 @@ export const LiveActivityWidget = defineComponent({ updateRow: (subRefs, sub) => { const subAct = sub.liveActivity || { phase: sub.isRunning ? 'thinking' : 'done', + actionKey: sub.isRunning ? 'thinking' : 'done', label: sub.isRunning ? t('live.thinking') : t('live.done'), detail: '', stepProgress: '', @@ -413,20 +521,30 @@ export const LiveActivityWidget = defineComponent({ patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); patchText(subRefs.subBadge, subBadgeText); - const roleText = sub.role || sub.shortLabel || t('fmt.subAgent'); + const fallbackRole = + sub.agentKind === 'side_question' || sub.isSideQuestion + ? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}` + : `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`; + const roleText = + sub.customRole !== undefined + ? sub.customRole || fallbackRole + : sub.role || sub.shortLabel || fallbackRole; patchText(subRefs.subRole, roleText); - const rawSubLabel = sub.isRunning - ? subAct.label || '' - : subAct.label || t('live.done'); + const subLabel = sub.isRunning + ? formatLiveActivityLabel(subAct, 'live.running') + : formatLiveActivityLabel(subAct, 'live.done'); + const subDetail = formatLiveActivityDetail(subAct); const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; - const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || ''] - .filter(Boolean) - .join(' '); + const summaryStr = showSessionExtras + ? sub.isRunning + ? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}` + : t('live.doneWithSteps', { steps: sub.stepCount || 0 }) + : [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' '); patchAttr(subRefs.subSummary, 'hidden', !summaryStr); patchText(subRefs.subSummary, summaryStr); - if (interactive) { + if (interactive && !showSessionExtras) { patchAttr( subRefs.rowEl, 'title', @@ -439,8 +557,8 @@ export const LiveActivityWidget = defineComponent({ activeTimerKeys.add(subTimerKey); bindLiveElapsedTimer( subTimerKey, - `${sub.cascadeId}:${subAct.signature || subAct.label}`, - subAct.startedAtMs, + `${sub.cascadeId}:${subAct.signature || subLabel}`, + subAct.startedAtMs || sub.lastModifiedMs, subRefs.subElapsed ); } else { diff --git a/sidecars/panel/src/components/widgets/StepTableWidget.js b/sidecars/panel/src/components/widgets/StepTableWidget.js index f6c6874..c38ce47 100644 --- a/sidecars/panel/src/components/widgets/StepTableWidget.js +++ b/sidecars/panel/src/components/widgets/StepTableWidget.js @@ -13,7 +13,7 @@ import { patchKeyedList, patchText, } from '../../core/domPatch.js'; -import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js'; +import { getEffectiveLocale, t } from '../../i18n/index.js'; import { DEFAULT_STEP_COLUMN_KEYS, STEP_COLUMN_REGISTRY, @@ -25,14 +25,11 @@ import { normalizeClientStepTokenComboFormat, } from '../../store/telemetryStore.js'; -export function formatTurnPromptText(rawPrompt) { +export function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) { const text = String(rawPrompt || '').trim(); - if (!text || !isEnglishLocale()) return text; - if (text === '[图片/附件提问]') return t('steps.turnMediaOnly'); - if (text.endsWith(' [附图]')) { - return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`; - } - return text; + if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly'); + if (!text) return ''; + return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text; } export const StepTableWidget = defineComponent({ @@ -212,7 +209,13 @@ export const StepTableWidget = defineComponent({ const getStepIsLatest = (st) => Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn); const getStepPrompt = (st) => - (useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || ''; + (useRootTurn + ? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt) + : (st?.turnPromptClean ?? st?.turnPrompt)) || ''; + const getStepHasMedia = (st) => + Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia); + const getStepMediaOnly = (st) => + Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly); const turnKeys = showStepTurnRail ? tableSteps.map((st) => { const tIdx = getStepTurnIdx(st); if (!Number.isInteger(tIdx) || tIdx <= 0) return ''; @@ -221,8 +224,13 @@ export const StepTableWidget = defineComponent({ const formattedPrompts = new Map(); function formattedTurnPrompt(st) { const raw = getStepPrompt(st); - if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw)); - return formattedPrompts.get(raw); + const hasMedia = getStepHasMedia(st); + const mediaOnly = getStepMediaOnly(st); + const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`; + if (!formattedPrompts.has(cacheKey)) { + formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly })); + } + return formattedPrompts.get(cacheKey); } const decoratedSteps = tableSteps.map((st, idx) => { @@ -344,26 +352,38 @@ export const StepTableWidget = defineComponent({ const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent); const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : ''; patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`); - const badgeText = isEnglishLocale() - ? formatAgentBadgeText({ - isMain: !st.isSubagent, - index: st.agentIndex || 0, - badgeText: st.agentBadge, - }) - : st.agentBadge || (st.isSubagent ? '子' : '主'); + const badgeText = formatAgentBadgeText({ + agentKind: + st.agentKind || + (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), + isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, + index: st.agentIndex || 0, + badgeText: st.agentBadge, + }); patchText(refs.agentBadgeEl, badgeText); if (interactiveBadges && onSelectAgentScopes) { const targetScope = st.agentId || 'main'; const isSoleTarget = effectiveScopes.length === 1 && effectiveScopes[0] === targetScope; - const agentName = isEnglishLocale() - ? formatAgentLabel({ - isMain: !st.isSubagent, - index: st.agentIndex || 0, - role: st.agentRole || '', - }) - : st.agentLabel || t('steps.unitAgent'); + const agentName = formatAgentLabel({ + agentKind: + st.agentKind || + (!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'), + agentOrdinal: + st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0), + customRole: st.agentCustomRole, + isMain: !st.isSubagent, + isSideQuestion: Boolean(st.isSideQuestion), + sideIndex: st.sideIndex || 0, + index: st.agentIndex || 0, + role: st.agentRole || '', + shortLabel: st.agentLabel || '', + }); patchAttr( refs.agentBadgeEl, 'title', diff --git a/sidecars/panel/src/core/appearance.js b/sidecars/panel/src/core/appearance.js index 06c4c76..2ff0a5e 100644 --- a/sidecars/panel/src/core/appearance.js +++ b/sidecars/panel/src/core/appearance.js @@ -17,8 +17,15 @@ export const THEME_ACCENT_PRESETS = Object.freeze([ export const FONT_SCALE_FACTORS = Object.freeze({ sm: 0.92, md: 1, - lg: 1.08, - xl: 1.15, + lg: 1.14, + xl: 1.28, +}); + +export const PANEL_SCALE_FACTORS = Object.freeze({ + sm: 1, + md: 1, + lg: 1.09, + xl: 1.18, }); export function normalizeClientThemeAccent(raw) { @@ -70,10 +77,13 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t if (includeFontScale) { const scaleKey = normalizeClientFontScale(settings?.fontScale); const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1; + const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1; setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor)); + setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor)); targetEl.setAttribute?.('data-font-scale', scaleKey); } else { setOrClearStyleVar(targetEl, '--ui-font-scale', ''); + setOrClearStyleVar(targetEl, '--ui-panel-scale', ''); if (typeof targetEl.removeAttribute === 'function') { targetEl.removeAttribute('data-font-scale'); } diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index b9e8e96..5eac14e 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -4,6 +4,17 @@ */ import { isEnglishLocale, t } from '../i18n/index.js'; +import { + normalizeModelDisplayMode, + normalizeOrchestratorIdMode, +} from '../../shared/settings-normalization.mjs'; +import { + classifyCacheTier, + classifySpeedTier, + classifyStepCostTier, + classifyTtftTier, + formatCompactTokens, +} from '../../shared/telemetry-display-rules.mjs'; const EN_MONTH_SHORT = Object.freeze([ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', @@ -21,53 +32,24 @@ export function formatCachePct(value) { } export function getSpeedToneClass(tokPerSec) { - if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) { - return 'tone-muted'; - } - const v = Number(tokPerSec); - if (v >= 60) return 'tone-good'; - if (v >= 35) return 'tone-info'; - if (v >= 20) return 'tone-warn'; - return 'tone-danger'; + return `tone-${classifySpeedTier(tokPerSec)}`; } export function getCacheToneClass(cacheHitPct, promptTokens = null) { - if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) { - return 'tone-muted'; - } - const v = Number(cacheHitPct); - if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) { - return 'tone-muted'; - } - if (v >= 85) return 'tone-good'; - if (v >= 65) return 'tone-info'; - if (v >= 30) return 'tone-warn'; - return 'tone-danger'; + return `tone-${classifyCacheTier(cacheHitPct, promptTokens)}`; } export function getStepCostToneClass(costUsd) { - if (costUsd == null || !Number.isFinite(Number(costUsd))) return ''; - const v = Number(costUsd); - if (v >= 0.3) return 'tone-danger'; - if (v >= 0.15) return 'tone-warn'; - return ''; + const tier = classifyStepCostTier(costUsd); + return tier ? `tone-${tier}` : ''; } export function getTtftToneClass(ttftSec) { - if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return ''; - const v = Number(ttftSec); - if (v >= 30) return 'tone-danger'; - if (v >= 18) return 'tone-warn'; - return ''; + const tier = classifyTtftTier(ttftSec); + return tier === 'warn' || tier === 'danger' ? `tone-${tier}` : ''; } -export function formatTokens(num) { - const n = Number(num || 0); - if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`; - if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; - if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`; - return String(Math.round(n)); -} +export const formatTokens = formatCompactTokens; export function formatTokensPrecise(num) { const n = Number(num || 0); @@ -172,23 +154,7 @@ 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'; -} +export { normalizeModelDisplayMode }; /** * 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。 @@ -208,15 +174,7 @@ function stripCompactionMarker(rawText) { .trim(); } -/** - * 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。 - * - * @param {unknown} mode - * @returns {'compact'|'full'} - */ -export function normalizeOrchestratorIdDisplayMode(mode) { - return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact'; -} +export const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode; /** * 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。 @@ -259,23 +217,35 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) { } const shortText = String( - target.activeModelShort ?? target.modelShort ?? target.shortName ?? '' + target.activeBaseModelShort ?? + target.baseModelShort ?? + target.activeModelShort ?? + target.modelShort ?? + target.shortName ?? + '' ).trim(); const labelText = String( - target.activeModelLabel ?? target.modelLabel ?? target.label ?? '' + target.activeBaseModelLabel ?? + target.baseModelLabel ?? + target.activeModelLabel ?? + target.modelLabel ?? + target.label ?? + '' ).trim(); const upstreamText = String( - target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? '' + target.baseModelUpstream ?? + target.activeModelUpstream ?? + target.modelUpstream ?? + target.upstreamName ?? + '' ).trim(); + const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`; const responseText = String(target.responseModel ?? '').trim(); const modelKeyText = String(target.modelKey ?? '').trim(); const isCompaction = Boolean(target.isCompactionStep) || - /·(?:压缩|compact)\s*$/iu.test(shortText) || - /·(?:压缩|compact)\s*$/iu.test(upstreamText) || - /·(?:压缩|compact)\s*$/iu.test(labelText) || - /\[自动压缩\]\s*$/u.test(labelText); + /·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText); const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : ''; @@ -512,3 +482,131 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = { }; }); } + +/** + * 根据代理索引返回对应的微边框语义徽章样式类名。 + * + * @param {number} [index=0] + * @param {boolean} [isMain=false] + * @returns {string} + */ +export function getAgentBadgeClass(index = 0, isMain = false) { + if (isMain || index <= 0) return 'badge-main'; + const slot = ((index - 1) % 3) + 1; + return `badge-sub-${slot}`; +} + +/** + * 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。 + * + * @param {object|null|undefined} agent + * @returns {string} + */ +export function formatAgentBadgeText(agent) { + if (!agent) return t('fmt.mainBadge'); + const kind = + agent.agentKind || + (agent.isMain + ? 'main' + : agent.isSideQuestion || agent.typeName === 'side_question' + ? 'side_question' + : 'subagent'); + if (kind === 'all') return t('header.scopeAllShort'); + if (kind === 'main') return t('fmt.mainBadge'); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + if (ord > 0) return t('fmt.sideBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.sideBadgeShort'); + } + const ord = Number(agent.agentOrdinal || agent.index || 0); + if (ord > 0) return t('fmt.subBadge', { index: ord }); + if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText); + return t('fmt.subBadgeShort'); +} + +/** + * 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。 + * + * @param {object|null|undefined} agent + * @returns {string} + */ +export function formatAgentLabel(agent) { + if (!agent) return t('fmt.mainAgent'); + const kind = + agent.agentKind || + (agent.isMain + ? 'main' + : agent.isSideQuestion || agent.typeName === 'side_question' + ? 'side_question' + : 'subagent'); + if (kind === 'all') return t('header.scopeAll'); + if (kind === 'main') return t('fmt.mainAgent'); + + const rawCustom = + agent.customRole !== undefined + ? String(agent.customRole || '').trim() + : String(agent.role || '').trim(); + if (kind === 'side_question') { + const ord = Number(agent.agentOrdinal || agent.sideIndex || 0); + const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.sideQuestion') || + rawCustom === 'Side Question' || + rawCustom === 'side_question'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; + } + + const ord = Number(agent.agentOrdinal || agent.index || 0); + const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent'); + const isGeneric = + !rawCustom || + rawCustom === baseLabel || + rawCustom === agent.shortLabel || + rawCustom === t('fmt.subAgent') || + rawCustom === 'Subagent'; + return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`; +} + +/** + * 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。 + * + * @param {object|null|undefined} act + * @param {string} [fallbackKey='live.thinking'] + * @returns {string} + */ +export function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') { + if (!act || typeof act !== 'object') return t(fallbackKey); + let baseLabel = ''; + if (act.actionKey) { + const i18nKey = `live.act.${act.actionKey}`; + const translated = t(i18nKey); + if (translated && translated !== i18nKey) { + baseLabel = translated; + } + } + if (!baseLabel) { + baseLabel = String(act.label || '').trim() || t(fallbackKey); + } + if (act.waitingApproval) { + return t('live.act.awaitingApproval', { label: baseLabel }); + } + return baseLabel; +} + +/** + * 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。 + * + * @param {object|null|undefined} act + * @returns {string} + */ +export function formatLiveActivityDetail(act) { + if (!act || typeof act !== 'object') return ''; + if (act.detailKey === 'compaction_resuming') { + return t('live.act.compactionResuming'); + } + return String(act.detail || ''); +} diff --git a/sidecars/panel/src/core/httpClient.js b/sidecars/panel/src/core/httpClient.js index e5931b9..f18c9d3 100644 --- a/sidecars/panel/src/core/httpClient.js +++ b/sidecars/panel/src/core/httpClient.js @@ -4,6 +4,8 @@ * (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge). */ +import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs'; + const inFlightGets = new Map(); const activeControllers = new Map(); @@ -13,8 +15,7 @@ const activeControllers = new Map(); * @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null} */ export function getWindowBridgeConfig() { - if (typeof window === 'undefined') return null; - const br = window.__AGUsageMonitorBridge; + const br = readInjectedWindowBridge(); const port = Number(br?.port || 0); if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) { return br; diff --git a/sidecars/panel/src/i18n/en-US.js b/sidecars/panel/src/i18n/en-US.js index 1170e3e..f712f8b 100644 --- a/sidecars/panel/src/i18n/en-US.js +++ b/sidecars/panel/src/i18n/en-US.js @@ -55,6 +55,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'fmt.subAgent': 'Subagent', 'fmt.subBadge': 'S{index}', 'fmt.subBadgeShort': 'Sub', + 'fmt.sideQuestion': 'Side Question', + 'fmt.sideBadge': 'Q{index}', + 'fmt.sideBadgeShort': 'Q', 'fmt.selectedCount': '{count} {unit} selected', 'fmt.selectedListTitle': 'Selected ({count}): {names}', 'fmt.selectPlaceholder': 'Select', @@ -179,6 +182,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'live.currentSession': 'Current Session', 'live.switchSessionTitle': 'Switch monitor to session: {title}', 'live.thinking': 'Thinking', + 'live.generating': 'Generating', 'live.running': 'Running', 'live.done': 'Done', 'live.doneWithSteps': 'Done ({steps} steps)', @@ -431,6 +435,21 @@ 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.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate', + 'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override', + 'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.', + 'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive', + 'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive', + 'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending', + 'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.', + 'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.', + 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.', + 'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount', + 'settings.bridge.relaunchingBtn': 'Relaunching Host...', + 'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry', + 'settings.bridge.dismissAria': 'Dismiss notice for now', + 'settings.bridge.copyFlagBtn': 'Copy {cmd}', + 'settings.bridge.copiedBtn': 'Copied to Clipboard', 'settings.str.popoverWidthLabel': 'Popover Width', 'settings.str.popoverWidthAuto': 'Auto Fit', 'settings.str.popoverWidthCustom': 'Custom', @@ -499,6 +518,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.ctxUnavailable': '{name} (currently unavailable)', 'settings.oth.ctxConfigured': '{name} · Set', 'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}', + 'settings.oth.ctxPendingBridge': '{name} · Pending Restart', 'settings.oth.ctxDefaultReported': 'Default · Last seen {name}', 'settings.oth.ctxReported': 'The host reported {name} on the latest request.', 'settings.oth.ctxMixed': 'Different limits by thinking level', @@ -519,4 +539,87 @@ export const I18N_MESSAGES_EN_US = Object.freeze({ 'settings.oth.resetConfirmBtn': 'Click Again to Confirm', 'settings.oth.resettingBtn': 'Resetting…', 'settings.oth.resetAllDone': 'All preferences restored to defaults', + + // Structured Live Activity Actions + 'live.act.run_command': 'Run Command', + 'live.act.read_file': 'Read File', + 'live.act.edit_file': 'Edit File', + 'live.act.write_file': 'Write File', + 'live.act.grep_search': 'Search Code', + 'live.act.find_file': 'Find Files', + 'live.act.read_url': 'Read Web Page', + 'live.act.search_web': 'Search Web', + 'live.act.invoke_subagent': 'Invoke Subagent', + 'live.act.send_message': 'Message Subagent', + 'live.act.manage_subagents': 'Manage Subagents', + 'live.act.manage_task': 'Manage Task', + 'live.act.schedule': 'Schedule Task', + 'live.act.ask_question': 'Waiting for User Choice', + 'live.act.search_marketplace': 'Search Plugins', + 'live.act.mcp_tool': 'Call MCP Tool', + 'live.act.tool_call': 'Call Tool', + 'live.act.thinking': 'Thinking', + 'live.act.compacting': 'Compacting Context', + 'live.act.responding': 'Responding', + 'live.act.waiting_subagent': 'Waiting for Subagent', + 'live.act.starting': 'Starting', + 'live.act.done': 'Completed', + 'live.act.awaitingApproval': 'Awaiting Approval · {label}', + 'live.act.compactionResuming': 'Compaction finished, resuming reasoning', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': 'No plottable steps in current scope', + 'chart.step.excluded': 'Excluded', + 'chart.step.zeroSteps': '0 steps', + 'chart.step.stepAdd': 'Step +{tokens}', + 'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}', + 'chart.step.cacheShort': 'Cache {pct}%', + 'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint', + 'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}', + 'chart.step.ttftShort': 'TTFT {sec}s', + 'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}', + 'chart.step.compactionStep': 'Compaction step', + 'chart.step.noSpeedSample': 'No speed sample', + 'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%', + 'chart.step.noTtftSample': 'No TTFT sample', + 'chart.step.cumCost': 'Total {cost}', + 'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}', + 'chart.step.noSamples': 'No samples', + 'chart.step.peakShort': 'Peak {val}', + 'chart.step.peakPill': 'Peak {tag} · {val}', + 'chart.step.stepsCount': '{count} steps', + 'chart.step.multiPrefix': '{count} models · ', + 'chart.step.sumTokens': '{prefix}Total {tokens}', + 'chart.step.peakTokens': '{prefix}Peak {tokens}', + 'chart.step.currentCtx': 'Current {tokens}', + 'chart.step.meanTps': '{prefix}Avg {val} tok/s', + 'chart.step.meanSec': '{prefix}Avg {val}s', + 'chart.step.noValidSamples': 'No valid samples', + 'chart.step.sumCost': '{prefix}Total {cost}', + 'chart.fit.empty': 'No valid regression samples for this model', + 'chart.fit.loess': 'LOESS Fit', + 'chart.fit.olsLinear': 'OLS Linear', + 'chart.fit.olsReg': 'OLS Reg', + 'chart.fit.observed': 'Observed', + 'chart.fit.tipFit': 'Fit {val}', + 'chart.fit.tipObs': 'Obs {val}', + 'chart.fit.zeroSamples': '0 samples', + 'chart.fit.peerMean': '{label} Avg {val}', + 'chart.fit.peerCompare': 'Compare: {peers}', + 'chart.fit.curvesCount': '{count} fit curves', + 'chart.fit.multiBadge': '{steps} steps · {models} models', + 'chart.fit.singleBadge': '{steps} steps · Avg {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}', + 'chart.trend.hmMonthYear': "{month}/{yy}", + 'chart.trend.hmMonthOnly': 'M{month}', + 'chart.trend.wdayMon': 'M', + 'chart.trend.wdayWed': 'W', + 'chart.trend.wdayFri': 'F', + 'chart.trend.wdaySun': 'S', + 'chart.trend.hmAria': 'Daily usage heatmap', + 'chart.trend.hmLess': 'Less', + 'chart.trend.hmMore': 'More', + 'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}', + 'chart.trend.hmActiveZero': 'Active 0/{total}d', + 'chart.trend.peakPill': 'Peak {label} · {tokens}', }); diff --git a/sidecars/panel/src/i18n/index.js b/sidecars/panel/src/i18n/index.js index 2c5c419..b8088a7 100644 --- a/sidecars/panel/src/i18n/index.js +++ b/sidecars/panel/src/i18n/index.js @@ -4,6 +4,7 @@ */ import { createReactiveStore } from '../core/reactive.js'; +import { normalizeLanguageSetting } from '../../shared/settings-normalization.mjs'; import { I18N_MESSAGES_ZH_CN } from './zh-CN.js'; import { I18N_MESSAGES_EN_US } from './en-US.js'; @@ -13,11 +14,7 @@ export const I18N_DICTIONARIES = Object.freeze({ }); export function normalizeI18nLanguage(raw) { - const val = String(raw ?? '').trim(); - if (val === 'auto') return 'auto'; - if (/^en(?:-|$)/i.test(val)) return 'en-US'; - if (/^zh(?:-|$)/i.test(val)) return 'zh-CN'; - return 'zh-CN'; + return normalizeLanguageSetting(raw); } export function detectHostSystemLocale() { diff --git a/sidecars/panel/src/i18n/zh-CN.js b/sidecars/panel/src/i18n/zh-CN.js index d11d118..206be74 100644 --- a/sidecars/panel/src/i18n/zh-CN.js +++ b/sidecars/panel/src/i18n/zh-CN.js @@ -55,6 +55,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'fmt.subAgent': '子代理', 'fmt.subBadge': '子{index}', 'fmt.subBadgeShort': '子', + 'fmt.sideQuestion': '旁路提问', + 'fmt.sideBadge': '旁{index}', + 'fmt.sideBadgeShort': '旁', 'fmt.selectedCount': '已选 {count} {unit}', 'fmt.selectedListTitle': '已选 ({count}):{names}', 'fmt.selectPlaceholder': '请选择', @@ -179,6 +182,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'live.currentSession': '当前会话', 'live.switchSessionTitle': '点击切换查看会话:{title}', 'live.thinking': '推理中', + 'live.generating': '生成中', 'live.running': '运行中', 'live.done': '已完成', 'live.doneWithSteps': '已完成 ({steps} 步)', @@ -431,6 +435,21 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)', 'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)', 'settings.str.mountSidebar': '仅侧边栏', + 'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊', + 'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写', + 'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。', + 'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效', + 'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效', + 'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入', + 'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。', + 'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。', + 'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。', + 'settings.bridge.relaunchBtn': '立即重启并启用挂载', + 'settings.bridge.relaunchingBtn': '正在重启客户端...', + 'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试', + 'settings.bridge.dismissAria': '暂时关闭提示', + 'settings.bridge.copyFlagBtn': '复制 {cmd}', + 'settings.bridge.copiedBtn': '已复制启动参数', 'settings.str.popoverWidthLabel': '悬浮面板宽度', 'settings.str.popoverWidthAuto': '自适应', 'settings.str.popoverWidthCustom': '指定宽度', @@ -499,6 +518,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.ctxUnavailable': '{name}(当前不可用)', 'settings.oth.ctxConfigured': '{name} · 已设置', 'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}', + 'settings.oth.ctxPendingBridge': '{name} · 待重启生效', 'settings.oth.ctxDefaultReported': '默认 · 最近 {name}', 'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。', 'settings.oth.ctxMixed': '各推理档设置不同', @@ -519,4 +539,87 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({ 'settings.oth.resetConfirmBtn': '再次点击确认重置', 'settings.oth.resettingBtn': '重置中…', 'settings.oth.resetAllDone': '已恢复全部默认设置', + + // Structured Live Activity Actions + 'live.act.run_command': '执行命令', + 'live.act.read_file': '读取文件', + 'live.act.edit_file': '修改文件', + 'live.act.write_file': '写入文件', + 'live.act.grep_search': '搜索代码', + 'live.act.find_file': '查找文件', + 'live.act.read_url': '读取网页', + 'live.act.search_web': '网页搜索', + 'live.act.invoke_subagent': '调用子代理', + 'live.act.send_message': '通信子代理', + 'live.act.manage_subagents': '管理子代理', + 'live.act.manage_task': '后台任务', + 'live.act.schedule': '定时任务', + 'live.act.ask_question': '等待用户选择', + 'live.act.search_marketplace': '查询插件', + 'live.act.mcp_tool': '调用 MCP', + 'live.act.tool_call': '调用工具', + 'live.act.thinking': '推理中', + 'live.act.compacting': '上下文压缩', + 'live.act.responding': '正在输出回复', + 'live.act.waiting_subagent': '等待子代理', + 'live.act.starting': '启动中', + 'live.act.done': '已完成', + 'live.act.awaitingApproval': '等待确认 · {label}', + 'live.act.compactionResuming': '已完成压缩,正在恢复推理', + + // SVG Charts (SessionStepCharts & TrendAreaChart) + 'chart.step.empty': '当前范围暂无可绘制的调用步骤', + 'chart.step.excluded': '未纳入', + 'chart.step.zeroSteps': '0 步', + 'chart.step.stepAdd': '本步 +{tokens}', + 'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}', + 'chart.step.cacheShort': '缓存 {pct}%', + 'chart.step.compactionCheckpoint': '上下文自动压缩检查点', + 'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}', + 'chart.step.ttftShort': '首字 {sec}s', + 'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}', + 'chart.step.compactionStep': '上下文压缩步', + 'chart.step.noSpeedSample': '无测速样本', + 'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%', + 'chart.step.noTtftSample': '无首字计时样本', + 'chart.step.cumCost': '累计 {cost}', + 'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}', + 'chart.step.noSamples': '无样本', + 'chart.step.peakShort': '峰 {val}', + 'chart.step.peakPill': '峰值 {tag} · {val}', + 'chart.step.stepsCount': '{count}步', + 'chart.step.multiPrefix': '{count} 模型 · ', + 'chart.step.sumTokens': '{prefix}累计 {tokens}', + 'chart.step.peakTokens': '{prefix}峰值 {tokens}', + 'chart.step.currentCtx': '当前 {tokens}', + 'chart.step.meanTps': '{prefix}均值 {val} tok/s', + 'chart.step.meanSec': '{prefix}均值 {val}s', + 'chart.step.noValidSamples': '暂无有效样本', + 'chart.step.sumCost': '{prefix}累计 {cost}', + 'chart.fit.empty': '该模型暂无有效拟合样本', + 'chart.fit.loess': 'LOESS 拟合', + 'chart.fit.olsLinear': 'OLS 线性', + 'chart.fit.olsReg': 'OLS 回归', + 'chart.fit.observed': '观测值', + 'chart.fit.tipFit': '拟合 {val}', + 'chart.fit.tipObs': '观测 {val}', + 'chart.fit.zeroSamples': '0 样本', + 'chart.fit.peerMean': '{label} 均 {val}', + 'chart.fit.peerCompare': '同图对比:{peers}', + 'chart.fit.curvesCount': '{count} 条拟合线', + 'chart.fit.multiBadge': '{steps}步 · {models} 模型对比', + 'chart.fit.singleBadge': '{steps}步 · 均 {mean}', + 'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}', + 'chart.trend.hmMonthYear': '{yy}年{month}月', + 'chart.trend.hmMonthOnly': '{month}月', + 'chart.trend.wdayMon': '一', + 'chart.trend.wdayWed': '三', + 'chart.trend.wdayFri': '五', + 'chart.trend.wdaySun': '日', + 'chart.trend.hmAria': '每日用量热力格子图', + 'chart.trend.hmLess': '少', + 'chart.trend.hmMore': '多', + 'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}', + 'chart.trend.hmActiveZero': '活跃 0/{total} 天', + 'chart.trend.peakPill': '峰值 {label} · {tokens}', }); diff --git a/sidecars/panel/src/icons/svgRegistry.js b/sidecars/panel/src/icons/svgRegistry.js index 593dccf..bdfd806 100644 --- a/sidecars/panel/src/icons/svgRegistry.js +++ b/sidecars/panel/src/icons/svgRegistry.js @@ -89,6 +89,10 @@ export const SVG_ICON_DEFS = Object.freeze({ close: [ { tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } }, ], + copy: [ + { tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } }, + { tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } }, + ], grip: [ { tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, diff --git a/sidecars/panel/src/main.js b/sidecars/panel/src/main.js index 63c924f..a4dede6 100644 --- a/sidecars/panel/src/main.js +++ b/sidecars/panel/src/main.js @@ -16,14 +16,17 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) { const appInstance = App(); mountTarget.appendChild(appInstance.el); + const syncDocAppearance = (settings) => { + setI18nLanguage(settings?.language); + if (typeof document !== 'undefined' && document.documentElement) { + applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true }); + } + }; + syncDocAppearance(telemetryStore.getState().telemetry?.settings); + const unsubAppearance = telemetryStore.subscribe( (st) => st.telemetry?.settings, - (settings) => { - setI18nLanguage(settings?.language); - if (typeof document !== 'undefined' && document.documentElement) { - applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true }); - } - } + syncDocAppearance ); const stopPolling = startAsyncTelemetryLoop(2000); diff --git a/sidecars/panel/src/registries/metricRegistry.js b/sidecars/panel/src/registries/metricRegistry.js index dae9c82..9e70df0 100644 --- a/sidecars/panel/src/registries/metricRegistry.js +++ b/sidecars/panel/src/registries/metricRegistry.js @@ -6,6 +6,7 @@ */ import { + formatAgentBadgeText, formatCachePct, formatMetric, formatTokens, @@ -19,36 +20,15 @@ import { speedReasonText, } from '../core/formatters.js'; import { isEnglishLocale, t } from '../i18n/index.js'; +import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-normalization.mjs'; +import { + formatCompactCapsuleCost, + formatCompactCapsuleTtft, + resolveCapsuleQuotaSlotPct, +} from '../../shared/telemetry-display-rules.mjs'; -export const CAPSULE_METRIC_KEYS = Object.freeze([ - 'context', - 'tps', - 'ttft', - 'avg_tps', - 'cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'quota_auto', - 'gemini_5h', - 'gemini_weekly', - 'claude_5h', - 'claude_weekly', -]); - -export const OVERVIEW_METRIC_KEYS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'context_usage', - 'quota_tightest', -]); - -const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i; +export { OVERVIEW_METRIC_KEYS, formatCompactCapsuleCost, formatCompactCapsuleTtft }; +export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS; export function getCapsuleMetricOptions() { return CAPSULE_METRIC_KEYS.map((key) => ({ @@ -137,98 +117,14 @@ export function resolveQuotaCapsuleSummary(quotas) { * @returns {{ roundedPct: number, shortText: string } | null} */ export function resolveSpecificQuotaSlotSummary(quotas, slotKey) { - if (!quotas) return null; - const pools = Array.isArray(quotas.pools) ? quotas.pools : []; - const activePool = quotas.activePool || null; - const isClaude = slotKey.startsWith('claude_'); - const isWeekly = slotKey.endsWith('_weekly'); - let rawPct = null; - - if (isClaude) { - const claudePool = - pools.find((p) => p?.poolKey === 'Claude & GPT') || - pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))); - const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct; - if (cand != null && Number.isFinite(Number(cand))) { - rawPct = Number(cand); - } else if ( - activePool && - THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) - ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; - if (fb != null && Number.isFinite(Number(fb))) { - rawPct = Number(fb); - } - } - } else { - const stdGemini = - pools.find((p) => p?.poolKey === 'Gemini') || - pools.find( - (p) => - /gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) && - !/carbon|argon/i.test(String(p?.poolKey || '')) - ); - const geminiFamilyPools = pools.filter((p) => - /gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || '')) - ); - const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct; - if (primaryCand != null && Number.isFinite(Number(primaryCand))) { - rawPct = Number(primaryCand); - } else { - const familyVals = geminiFamilyPools - .map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct)) - .filter((v) => v != null && Number.isFinite(Number(v))) - .map(Number); - if (familyVals.length > 0) { - rawPct = Math.min(...familyVals); - } else if ( - activePool && - !THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || '')) - ) { - const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct; - if (fb != null && Number.isFinite(Number(fb))) { - rawPct = Number(fb); - } - } - if ( - rawPct == null && - isWeekly && - quotas.weekly && - !THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) && - quotas.weekly.remainingPct != null && - Number.isFinite(Number(quotas.weekly.remainingPct)) - ) { - rawPct = Number(quotas.weekly.remainingPct); - } - } - } - - if (rawPct == null || !Number.isFinite(rawPct)) return null; - const rounded = Math.max(0, Math.min(100, Math.round(rawPct))); + const rounded = resolveCapsuleQuotaSlotPct(quotas, slotKey); + if (rounded == null) return null; return { roundedPct: rounded, shortText: t('capsule.quotaLeft', { pct: rounded }), }; } -export function formatCompactCapsuleCost(costUsd) { - if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--'; - const val = Math.max(0, Number(costUsd)); - if (val === 0) return '$0.00'; - if (val < 0.001) return '<$0.001'; - if (val < 1) return `$${val.toFixed(3)}`; - if (val < 100) return `$${val.toFixed(2)}`; - return `$${Math.round(val)}`; -} - -export function formatCompactCapsuleTtft(ttftSec) { - if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s'; - const val = Number(ttftSec); - if (val < 1) return `${val.toFixed(2)}s`; - if (val < 100) return `${val.toFixed(1)}s`; - return `${Math.round(val)}s`; -} - /** * 解析顶栏/输入框精简胶囊单槽位展示结构。 * @@ -450,15 +346,16 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf }; } -function translateRawAgentBadge(rawBadge) { - if (!rawBadge) return ''; - if (!isEnglishLocale()) return String(rawBadge); - const str = String(rawBadge).trim(); - if (str === '主') return t('fmt.mainBadge'); - const m = str.match(/^子(\d+)$/); - if (m) return t('fmt.subBadge', { index: m[1] }); - if (str === '子') return t('fmt.subBadgeShort'); - return str; +function resolveActiveBadgeText(active) { + if (!active?.activeAgentBadge && !active?.activeAgentKind) return ''; + return formatAgentBadgeText({ + agentKind: + active.activeAgentKind || + (!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'), + agentOrdinal: Number(active.activeAgentOrdinal || 0), + isMain: !active.activeAgentId || active.activeAgentId === 'main', + badgeText: active.activeAgentBadge, + }); } /** @@ -480,7 +377,7 @@ export function resolveOverviewMetricCell(metricKey, cellCtx = {}) { fallback: t('fmt.unknownModel'), }).text; const reason = speedReasonText(active.latestSpeedReason); - const badgeStr = translateRawAgentBadge(active.activeAgentBadge); + const badgeStr = resolveActiveBadgeText(active); const modelAndAgent = hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay; const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0; diff --git a/sidecars/panel/src/registries/stepColumnRegistry.js b/sidecars/panel/src/registries/stepColumnRegistry.js index b667e3e..ddee8f9 100644 --- a/sidecars/panel/src/registries/stepColumnRegistry.js +++ b/sidecars/panel/src/registries/stepColumnRegistry.js @@ -20,37 +20,18 @@ import { } from '../core/formatters.js'; import { t } from '../i18n/index.js'; import { - DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT, - normalizeClientStepTokenComboFormat, - parseClientStepTokenComboSegments, -} from '../store/telemetryStore.js'; + DEFAULT_STEP_TABLE_COLUMNS, + DEFAULT_STEP_TOKEN_COMBO_FORMAT, + STEP_TABLE_COLUMN_KEYS, + normalizeStepTokenComboFormat, + parseStepTokenComboSegments, +} from '../../shared/settings-normalization.mjs'; -export const STEP_COLUMN_KEYS = Object.freeze([ - 'step', - 'time', - 'model', - 'tps', - 'ttft', - 'duration', - 'tokens_combo', - 'tokens_io_cache', - 'tokens_custom', - 'input_tokens', - 'cache_tokens', - 'output_tokens', - 'cache', - 'cost', -]); - -export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([ - 'step', - 'model', - 'tps', - 'ttft', - 'tokens_combo', - 'cache', - 'cost', -]); +export const STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS; +export const DEFAULT_STEP_COLUMN_KEYS = DEFAULT_STEP_TABLE_COLUMNS; +const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT; +const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat; +const parseClientStepTokenComboSegments = parseStepTokenComboSegments; function resolveStepTokenParts(st) { const inTok = Math.max(0, Number(st?.inputTokens || 0)); @@ -224,7 +205,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({ if (reason && !refs.speedReason) { refs.speedReason = h('div', { className: 'text-muted', - style: 'font-size: var(--fs-2xs);', + style: 'font-size: var(--fs-xs);', }); refs.wrapEl.appendChild(refs.speedReason); } diff --git a/sidecars/panel/src/registries/widgetRegistry.js b/sidecars/panel/src/registries/widgetRegistry.js index d062524..da1f684 100644 --- a/sidecars/panel/src/registries/widgetRegistry.js +++ b/sidecars/panel/src/registries/widgetRegistry.js @@ -5,18 +5,14 @@ * live reordering, and clean instance disposal. */ +import { OVERVIEW_MODULE_KEYS } from '../../shared/settings-normalization.mjs'; import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js'; import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js'; import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js'; import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js'; import { t } from '../i18n/index.js'; -export const OVERVIEW_WIDGET_KEYS = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); +export const OVERVIEW_WIDGET_KEYS = OVERVIEW_MODULE_KEYS; export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({ metrics: { diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index f398509..c0dafbd 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -5,8 +5,45 @@ import { createReactiveStore } from '../core/reactive.js'; import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js'; -import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js'; +import { + formatAgentBadgeText, + formatAgentLabel, + formatLiveActivityDetail, + formatLiveActivityLabel, + getAgentBadgeClass, +} from '../core/formatters.js'; +import { normalizeI18nLanguage, t } from '../i18n/index.js'; import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js'; +import { + DEFAULT_HOVER_MODULES, + DEFAULT_OVERVIEW_METRICS, + DEFAULT_OVERVIEW_MODULES, + DEFAULT_POPOVER_WIDTH, + DEFAULT_STEP_TABLE_COLUMNS, + DEFAULT_STEP_TOKEN_COMBO_FORMAT, + DEFAULT_TOPBAR_SLOTS, + MAX_POPOVER_WIDTH, + MIN_POPOVER_WIDTH, + OVERVIEW_METRIC_KEYS, + OVERVIEW_MODULE_KEYS, + STEP_TABLE_COLUMN_KEYS, + TOPBAR_SLOT_KEYS, + normalizeHoverModules, + normalizeModelDisplayMode, + normalizeOrchestratorIdMode, + normalizeOverviewMetrics, + normalizeOverviewModules, + normalizePluginUpdateMode, + normalizePopoverWidth, + normalizePopoverWidthMode, + normalizeStepTableColumns, + normalizeStepTokenComboFormat, + normalizeTopbarCapsuleSlots, + normalizeWeeklyLimitMode, + normalizeWindowMountMode, + parseStepTokenComboSegments, +} from '../../shared/settings-normalization.mjs'; +import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs'; const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; @@ -25,7 +62,7 @@ export function extractHostRouteCascadeId() { if (m && CASCADE_UUID_RE.test(m[1])) { return m[1]; } - const extBridgeRouteId = String(window.__AGUsageMonitorBridge?.hostRouteCascadeId || '').trim(); + const extBridgeRouteId = String(readInjectedWindowBridge()?.[WINDOW_BRIDGE_ROUTE_KEY] || '').trim(); if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) { return extBridgeRouteId; } @@ -107,310 +144,35 @@ let loopActive = false; let loopIntervalMs = 2000; let loopTickFn = null; -export const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([ - 'context', - 'tps', - 'ttft', - 'avg_tps', - 'cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'quota_auto', - 'gemini_5h', - 'gemini_weekly', - 'claude_5h', - 'claude_weekly', -]); +export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS; +export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS; +export const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS; +export const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES; +export const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES; +export const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS; +export const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS; +export const CLIENT_STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS; +export const DEFAULT_CLIENT_STEP_COLUMNS = DEFAULT_STEP_TABLE_COLUMNS; +export const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT; +export const MIN_CLIENT_POPOVER_WIDTH = MIN_POPOVER_WIDTH; +export const MAX_CLIENT_POPOVER_WIDTH = MAX_POPOVER_WIDTH; +export const DEFAULT_CLIENT_POPOVER_WIDTH = DEFAULT_POPOVER_WIDTH; -export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']); +export const parseClientStepTokenComboSegments = parseStepTokenComboSegments; +export const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat; +export const normalizeClientPopoverWidthMode = normalizePopoverWidthMode; +export const normalizeClientPopoverWidth = normalizePopoverWidth; +export const normalizeClientModelDisplayMode = normalizeModelDisplayMode; +export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots; +export const normalizeClientHoverModules = normalizeHoverModules; +export const normalizeClientOverviewModules = normalizeOverviewModules; +export const normalizeClientOverviewMetrics = normalizeOverviewMetrics; +export const normalizeClientStepColumns = normalizeStepTableColumns; +export const normalizeClientUpdateMode = normalizePluginUpdateMode; +export const normalizeClientOrchestratorIdMode = normalizeOrchestratorIdMode; +export const normalizeClientWindowMountMode = normalizeWindowMountMode; -export const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); - -export const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([ - 'metrics', - 'context', - 'quotas', - 'live_tasks', -]); - -export const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']); - -export const CLIENT_OVERVIEW_METRIC_KEYS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', - 'session_cost', - 'cache_hit', - 'session_tokens', - 'context_usage', - 'quota_tightest', -]); - -export const DEFAULT_CLIENT_OVERVIEW_METRICS = Object.freeze([ - 'tps', - 'ttft', - 'avg_tps', - 'step_cost', -]); - -export const CLIENT_STEP_COLUMN_KEYS = Object.freeze([ - 'step', - 'time', - 'model', - 'tps', - 'ttft', - 'duration', - 'tokens_combo', - 'tokens_io_cache', - 'tokens_custom', - 'input_tokens', - 'cache_tokens', - 'output_tokens', - 'cache', - 'cost', -]); - -export const DEFAULT_CLIENT_STEP_COLUMNS = Object.freeze([ - 'step', - 'model', - 'tps', - 'ttft', - 'tokens_combo', - 'cache', - '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]; - } - const allowedSet = new Set(allowedKeys); - const seen = new Set(); - const out = []; - for (const item of raw) { - const key = String(item ?? '').trim(); - if (!key || key === 'none' || !allowedSet.has(key) || seen.has(key)) continue; - seen.add(key); - out.push(key); - if (out.length >= maxLen) break; - } - if (out.length < minLen) { - for (const fallbackKey of [...defaultItems, ...allowedKeys]) { - if (!seen.has(fallbackKey) && allowedSet.has(fallbackKey)) { - seen.add(fallbackKey); - out.push(fallbackKey); - if (out.length >= minLen) break; - } - } - } - return out; -} - -/** - * 归一化前端顶栏胶囊动态槽位配置数组(支持 1..5 项不重复指标,兼容迁移旧版 `'none'` 占位)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeClientTopbarSlots(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_TOPBAR_SLOT_KEYS, - defaultItems: DEFAULT_CLIENT_TOPBAR_SLOTS, - minLen: 1, - maxLen: 5, - }); -} - -/** - * 归一化鼠标悬浮速览窗展示模块列表(支持 0..4 项,`0` 项代表关闭悬浮窗)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeClientHoverModules(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS, - defaultItems: DEFAULT_CLIENT_HOVER_MODULES, - minLen: 0, - maxLen: 4, - }); -} - -/** - * 归一化实时监控视图展示模块列表(支持 1..4 项)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeClientOverviewModules(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS, - defaultItems: DEFAULT_CLIENT_OVERVIEW_MODULES, - minLen: 1, - maxLen: 4, - }); -} - -/** - * 归一化实时监控第一行指标矩阵配置(支持 1..4 项)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeClientOverviewMetrics(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_OVERVIEW_METRIC_KEYS, - defaultItems: DEFAULT_CLIENT_OVERVIEW_METRICS, - minLen: 1, - maxLen: 4, - }); -} - -/** - * 归一化调用明细「按步查看」显示列配置(支持 2..12 列)。 - * - * @param {unknown} raw - * @returns {string[]} - */ -export function normalizeClientStepColumns(raw) { - return normalizeClientOrderedList(raw, { - allowedKeys: CLIENT_STEP_COLUMN_KEYS, - defaultItems: DEFAULT_CLIENT_STEP_COLUMNS, - minLen: 2, - maxLen: CLIENT_STEP_COLUMN_KEYS.length, - }); -} - -/** - * 归一化前端插件更新策略(`'off'` | `'manual'` | `'auto'`),兼容旧版布尔字段。 - * - * @param {unknown} mode - * @param {unknown} [legacyAutoUpdate] - * @returns {'off'|'manual'|'auto'} - */ -export function normalizeClientUpdateMode(mode, legacyAutoUpdate) { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'off' || m === 'manual' || m === 'auto') return m; - if (legacyAutoUpdate === true) return 'auto'; - return 'manual'; -} - -export function normalizeClientOrchestratorIdMode(mode) { - return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact'; -} - -/** - * 归一化前端面板挂载方式(`'dual'` | `'composer'` | `'sidebar'`),兼容旧版 `enableWindowOverlay` 布尔字段。 - * - * @param {unknown} mode - * @param {unknown} [legacyEnableOverlay] - * @returns {'dual'|'composer'|'sidebar'} - */ -export function normalizeClientWindowMountMode(mode, legacyEnableOverlay) { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'composer' || m === 'input') return 'composer'; - if (m === 'sidebar' || m === 'off') return 'sidebar'; - if (m === 'dual' || m === 'topbar') return 'dual'; - if (legacyEnableOverlay === false) return 'sidebar'; - return 'dual'; -} - -function isEquivalentTelemetry(prev, next) { +export function isEquivalentTelemetry(prev, next) { if (!prev || !next) return false; if (prev === next) return true; @@ -423,15 +185,6 @@ function isEquivalentTelemetry(prev, next) { } return true; }; - const normMount = (mode, legacyEnableOverlay) => { - const m = String(mode ?? '').trim().toLowerCase(); - if (m === 'composer' || m === 'input') return 'composer'; - if (m === 'sidebar' || m === 'off') return 'sidebar'; - if (m === 'dual' || m === 'topbar') return 'dual'; - if (legacyEnableOverlay === false) return 'sidebar'; - return 'dual'; - }; - // 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置) const pAct = prev.activeConversation; const nAct = next.activeConversation; @@ -441,6 +194,7 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false; if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false; if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false; + if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false; if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) { return false; } @@ -450,51 +204,29 @@ 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) + normalizeModelDisplayMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !== + normalizeModelDisplayMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel) ) { return false; } if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false; - if (normPopMode(pSet?.popoverWidthMode) !== normPopMode(nSet?.popoverWidthMode)) { + if (normalizePopoverWidthMode(pSet?.popoverWidthMode) !== normalizePopoverWidthMode(nSet?.popoverWidthMode)) { return false; } - if (normPopW(pSet?.popoverWidth) !== normPopW(nSet?.popoverWidth)) { + if (normalizePopoverWidth(pSet?.popoverWidth) !== normalizePopoverWidth(nSet?.popoverWidth)) { return false; } if ( - String(pSet?.stepTokenComboFormat ?? 'context:in:cache').trim() !== - String(nSet?.stepTokenComboFormat ?? 'context:in:cache').trim() + String(pSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() !== + String(nSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() ) { return false; } - const prevOrchIdMode = - String(pSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' - ? 'full' - : 'compact'; - const nextOrchIdMode = - String(nSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full' - ? 'full' - : 'compact'; - if (prevOrchIdMode !== nextOrchIdMode) { + if ( + normalizeOrchestratorIdMode(pSet?.orchestratorIdMode) !== + normalizeOrchestratorIdMode(nSet?.orchestratorIdMode) + ) { return false; } if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false; @@ -503,8 +235,8 @@ function isEquivalentTelemetry(prev, next) { if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false; if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false; if ( - normMount(pSet?.windowMountMode, pSet?.enableWindowOverlay) !== - normMount(nSet?.windowMountMode, nSet?.enableWindowOverlay) + normalizeClientWindowMountMode(pSet?.windowMountMode, pSet?.enableWindowOverlay) !== + normalizeClientWindowMountMode(nSet?.windowMountMode, nSet?.enableWindowOverlay) ) { return false; } @@ -530,7 +262,19 @@ function isEquivalentTelemetry(prev, next) { if (!sameArr(pSet?.overviewMetrics, nSet?.overviewMetrics)) return false; if (!sameArr(pSet?.stepTableColumns, nSet?.stepTableColumns)) return false; - // 2. 比对云端状态 + // 2. 比对云端状态与桥接健康度 + const pWb = prev.windowBridge; + const nWb = next.windowBridge; + if ( + (pWb?.state || '') !== (nWb?.state || '') || + Boolean(pWb?.argvUpdatedThisBoot) !== Boolean(nWb?.argvUpdatedThisBoot) || + Boolean(pWb?.argvConfigured) !== Boolean(nWb?.argvConfigured) || + Boolean(pWb?.launcherConfigured) !== Boolean(nWb?.launcherConfigured) || + Boolean(pWb?.canRelaunch) !== Boolean(nWb?.canRelaunch) || + Number(pWb?.aliveCount || 0) !== Number(nWb?.aliveCount || 0) + ) { + return false; + } const pCloud = prev.cloudStatus; const nCloud = next.cloudStatus; if ( @@ -1072,12 +816,6 @@ async function requestTelemetry(params, force) { consecutivePollFailures = 0; const latestSt = telemetryStore.getState(); - const previousAccount = latestSt.telemetry?.account; - const nextAccount = payload?.account; - const accountChanged = previousAccount?.status === 'signedIn' && - (nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' && - (previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name))); - const accountPatch = accountChanged ? { selectedConversationId: '' } : {}; if (force) { const elapsed = Date.now() - startMs; if (elapsed < 220) { @@ -1088,7 +826,6 @@ async function requestTelemetry(params, force) { } if (feedbackTimer) clearTimeout(feedbackTimer); telemetryStore.setState({ - ...accountPatch, telemetry: payload, minuteTick: Math.floor(Date.now() / 30000), syncState: 'synced', @@ -1101,7 +838,6 @@ async function requestTelemetry(params, force) { const isSame = isEquivalentTelemetry(latestSt.telemetry, payload); const nextTelemetry = isSame ? latestSt.telemetry : payload; telemetryStore.setState({ - ...accountPatch, telemetry: nextTelemetry, minuteTick: Math.floor(Date.now() / 30000), syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle', @@ -1137,9 +873,7 @@ export async function saveSettingsPatch(patch) { safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale); } if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) { - const mode = safePatch.weeklyLimitMode; - safePatch.weeklyLimitMode = - mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official'; + safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode); } if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) { safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine); @@ -1279,6 +1013,18 @@ export async function triggerCloudSync() { return res; } +export async function triggerBridgeHostRelaunch() { + try { + return await callSidecarApi('/api/bridge/relaunch', { method: 'POST', body: {} }); + } catch { + // 兼容热更新后常驻父进程 main.mjs 尚未重注册新路由的场景,平滑回退至既有 POST /api/settings 通道转发至最新 Worker + return callSidecarApi('/api/settings', { + method: 'POST', + body: { __bridgeAction: 'relaunch' }, + }); + } +} + export async function triggerPluginUpdate() { const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} }); if (res?.ok && res?.restarting) { @@ -1338,54 +1084,13 @@ export function stopAsyncTelemetryLoop() { } } -/** - * 根据代理索引返回对应的微边框语义徽章样式类名。 - * - * @param {number} [index=0] - * @param {boolean} [isMain=false] - * @returns {string} - */ -export function getAgentBadgeClass(index = 0, isMain = false) { - if (isMain || index <= 0) return 'badge-main'; - const slot = ((index - 1) % 3) + 1; - return `badge-sub-${slot}`; -} - -/** - * 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -export function formatAgentBadgeText(agent) { - if (!isEnglishLocale()) { - if (!agent || agent.isMain) return agent?.badgeText || '主'; - return agent.badgeText || `子${agent.index || ''}`; - } - if (!agent || agent.isMain) return t('fmt.mainBadge'); - return agent.index ? t('fmt.subBadge', { index: agent.index }) : t('fmt.subBadgeShort'); -} - -/** - * 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。 - * - * @param {object|null|undefined} agent - * @returns {string} - */ -export function formatAgentLabel(agent) { - if (!isEnglishLocale()) { - if (!agent) return '主代理'; - if (agent.isMain) return agent.shortLabel || '主代理'; - const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : ''; - return `${agent.shortLabel || '子代理'}${rolePart}`; - } - if (!agent || agent.isMain) return t('fmt.mainAgent'); - const idx = Number(agent.index || 0); - const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent'); - const rolePart = - agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : ''; - return `${baseLabel}${rolePart}`; -} +export { + formatAgentBadgeText, + formatAgentLabel, + formatLiveActivityDetail, + formatLiveActivityLabel, + getAgentBadgeClass, +}; /** * 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。 @@ -1396,46 +1101,73 @@ export function formatAgentLabel(agent) { * @param {string} [ctxInspectorAgentId='auto'] * @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表 */ +const scopedStepProjectionMemo = new WeakMap(); + export function resolveScopedConversation( telemetry, selectedAgentScope = 'all', ctxInspectorAgentId = 'auto', includeSteps = false ) { - const active = telemetry?.activeConversation || {}; + const rawActive = telemetry?.activeConversation; + const active = rawActive || {}; const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : []; const hasSubagents = Boolean(active.hasSubagents && agents.length > 1); const subagents = agents.filter((a) => !a.isMain); - const mainAgent = agents.find((a) => a.isMain) || active; - if (includeSteps && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) { - mainAgent.recentSteps = active.recentSteps; - } - const aggregated = active.aggregated || active; - if (includeSteps && hasSubagents && !Array.isArray(aggregated.recentSteps)) { - const combined = []; - for (const ag of agents) { - const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || []; - for (const step of steps) combined.push(step); + let mainAgent = agents.find((a) => a.isMain) || active; + let aggregated = active.aggregated || active; + let resolvedAgents = agents; + + if (includeSteps) { + let cached = rawActive && typeof rawActive === 'object' ? scopedStepProjectionMemo.get(rawActive) : null; + if (!cached) { + let nextMain = mainAgent; + let nextAgents = agents; + if (!Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) { + nextMain = { ...mainAgent, recentSteps: active.recentSteps }; + if (agents.includes(mainAgent)) { + nextAgents = agents.map((ag) => (ag === mainAgent ? nextMain : ag)); + } + } + let nextAgg = aggregated; + if (hasSubagents && !Array.isArray(aggregated.recentSteps)) { + const combined = []; + for (const ag of nextAgents) { + const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || []; + for (const step of steps) combined.push(step); + } + combined.sort( + (a, b) => + (b.createdAtMs || 0) - (a.createdAtMs || 0) || + (b.agentIndex || 0) - (a.agentIndex || 0) || + (b.stepIndex || 0) - (a.stepIndex || 0) + ); + nextAgg = { ...aggregated, recentSteps: combined }; + } + cached = { mainAgent: nextMain, aggregated: nextAgg, agents: nextAgents }; + if (rawActive && typeof rawActive === 'object') { + scopedStepProjectionMemo.set(rawActive, cached); + } } - combined.sort( - (a, b) => - (b.createdAtMs || 0) - (a.createdAtMs || 0) || - (b.agentIndex || 0) - (a.agentIndex || 0) || - (b.stepIndex || 0) - (a.stepIndex || 0) - ); - aggregated.recentSteps = combined; + mainAgent = cached.mainAgent; + aggregated = cached.aggregated; + resolvedAgents = cached.agents; } if (!hasSubagents) { + const singleScoped = + includeSteps && !Array.isArray(active.recentSteps) && Array.isArray(mainAgent.recentSteps) + ? { ...active, recentSteps: mainAgent.recentSteps } + : active; return { hasSubagents: false, effectiveScope: 'main', effectiveCtxScope: 'main', - agents, + agents: resolvedAgents, subagents: [], mainAgent, aggregated, - scopedConv: active, + scopedConv: singleScoped, ctxAgent: mainAgent, }; } @@ -1451,13 +1183,13 @@ export function resolveScopedConversation( const scopedConv = effectiveScope === 'all' ? aggregated - : agents.find((a) => a.agentId === effectiveScope) || mainAgent; + : resolvedAgents.find((a) => a.agentId === effectiveScope) || mainAgent; let ctxAgent = scopedConv; let effectiveCtxScope = effectiveScope; if (effectiveScope === 'all') { if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') { - const matched = agents.find((a) => a.agentId === ctxInspectorAgentId); + const matched = resolvedAgents.find((a) => a.agentId === ctxInspectorAgentId); if (matched) { ctxAgent = matched; effectiveCtxScope = matched.agentId; @@ -1469,8 +1201,8 @@ export function resolveScopedConversation( } if (effectiveCtxScope === 'auto') { ctxAgent = - agents.find((a) => a.agentId === aggregated.activeAgentId) || - agents.find((a) => a.isRunning) || + resolvedAgents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) || + resolvedAgents.find((a) => !a.isSideQuestion && a.isRunning) || mainAgent; } } @@ -1479,7 +1211,7 @@ export function resolveScopedConversation( hasSubagents: true, effectiveScope, effectiveCtxScope, - agents, + agents: resolvedAgents, subagents, mainAgent, aggregated, @@ -1487,3 +1219,21 @@ export function resolveScopedConversation( ctxAgent, }; } + +/** + * 判断宿主系统是否为 macOS (`darwin`):优先读取后端遥测或双栖桥接注入的 `platform`,首帧缺省时回退 UA/平台标识。 + * + * @param {Record|null|undefined} telemetry + * @returns {boolean} + */ +export function isMacHostPlatform(telemetry) { + const p = String(telemetry?.hostPlatform || readInjectedWindowBridge()?.platform || '') + .trim() + .toLowerCase(); + if (p) return p === 'darwin'; + if (typeof navigator !== 'undefined') { + const ua = String(navigator.platform || navigator.userAgent || ''); + return /\b(?:mac|darwin)\b|macintosh|mac\s*os/i.test(ua); + } + return false; +} diff --git a/sidecars/panel/src/store/uiStore.js b/sidecars/panel/src/store/uiStore.js index 16f76f1..525b3b3 100644 --- a/sidecars/panel/src/store/uiStore.js +++ b/sidecars/panel/src/store/uiStore.js @@ -5,13 +5,6 @@ import { createReactiveStore } from '../core/reactive.js'; import { t } from '../i18n/index.js'; -export const VIEW_TABS = Object.freeze([ - { value: 'overview', label: '实时监控', icon: 'pulse' }, - { value: 'consumption', label: '用量统计', icon: 'chart-bar' }, - { value: 'steps', label: '调用明细', icon: 'table' }, - { value: 'settings', label: '偏好设置', icon: 'sliders' }, -]); - export function getViewTabs() { return [ { value: 'overview', label: t('nav.overview'), icon: 'pulse' }, diff --git a/sidecars/panel/src/styles/base.css b/sidecars/panel/src/styles/base.css index c6057d1..8d4c8e7 100644 --- a/sidecars/panel/src/styles/base.css +++ b/sidecars/panel/src/styles/base.css @@ -29,15 +29,21 @@ body { overflow: hidden; background: var(--surface-bg); color: var(--text-primary); - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-family: var(--font-sans); font-size: var(--fs-body); line-height: 1.4; font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } button, -input { +input, +select, +textarea, +table, +th, +td { font-family: inherit; font-size: inherit; font-stretch: inherit; diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index c86ee49..96c2b09 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -117,13 +117,15 @@ /* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */ .long-pill-nav { position: relative; + container-type: inline-size; display: grid; - grid-template-columns: repeat(var(--pill-count, 4), 1fr); + grid-template-columns: repeat(var(--pill-count, 4), minmax(0, 1fr)); align-items: center; padding: 3px; background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-pill); + overflow: hidden; user-select: none; } @@ -149,15 +151,17 @@ align-items: center; justify-content: center; gap: 5px; - height: 26px; - padding: 0 var(--space-2); + min-width: 0; + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px var(--space-2); border: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-base); font-weight: 500; - line-height: 1; + line-height: 1.15; border-radius: var(--radius-pill); + overflow: hidden; cursor: pointer; white-space: nowrap; transition: color var(--dur-instant) var(--ease-fast); @@ -171,20 +175,60 @@ flex-shrink: 0; } -.pill-tab-label, -.pill-tab-badge { - display: inline-flex; - align-items: center; - height: 14px; - line-height: 1; +.pill-tab-label { + display: block; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + line-height: 1.2; } .pill-tab-badge { + display: inline-flex; + align-items: center; + flex-shrink: 0; + min-height: 14px; + line-height: 1.15; margin-left: -2px; font-size: var(--fs-base-sm); opacity: 0.85; } +@container (max-width: 30em) { + .pill-tab { + gap: 3.5px; + padding: 2px 4px; + font-size: var(--fs-md); + } + .pill-tab .svg-icon { + width: 13px; + height: 13px; + } + .pill-tab-badge { + display: none !important; + } +} + +@container (max-width: 23em) { + .pill-tab { + gap: 0; + padding: 2px 3px; + } + .pill-tab .svg-icon { + display: none; + } +} + +@container (max-width: 17.5em) { + .pill-tab .svg-icon { + display: block; + } + .pill-tab-label { + display: none; + } +} + .pill-tab:hover { color: var(--text-primary); } @@ -223,8 +267,8 @@ justify-content: space-between; gap: var(--space-2); width: 100%; - height: 24px; - padding: 0 6px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 6px; background: transparent; color: var(--text-primary); border: none; @@ -350,7 +394,7 @@ .number-input { display: inline-flex; align-items: stretch; - height: 28px; + min-height: calc(28px * var(--ui-font-scale, 1)); background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); @@ -410,8 +454,8 @@ justify-content: space-between; gap: var(--space-2); width: 100%; - height: 26px; - padding: 0 var(--space-2); + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px var(--space-2); background: var(--surface-panel); color: var(--text-primary); border: 1px solid var(--border-hairline); @@ -464,7 +508,7 @@ } .dt-day { - height: 22px; + min-height: calc(22px * var(--ui-font-scale, 1)); border: none; background: transparent; color: var(--text-primary); @@ -540,8 +584,8 @@ align-items: center; justify-content: center; gap: 4px; - height: 22px; - padding: 0 7px; + min-height: calc(22px * var(--ui-font-scale, 1)); + padding: 2px 7px; border: none; background: transparent; color: var(--text-secondary); @@ -650,8 +694,8 @@ align-items: center; justify-content: center; gap: 6px; - height: 28px; - padding: 0 var(--space-5); + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 3px var(--space-5); background: var(--accent-primary); color: var(--text-inverse); border: 1px solid var(--accent-primary); @@ -675,8 +719,8 @@ align-items: center; justify-content: center; gap: 6px; - height: 28px; - padding: 0 var(--space-4); + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 3px var(--space-4); background: var(--surface-panel); color: var(--text-primary); border: 1px solid var(--border-strong); @@ -714,8 +758,8 @@ display: inline-flex; align-items: center; gap: 4px; - height: 22px; - padding: 0 7px; + min-height: calc(22px * var(--ui-font-scale, 1)); + padding: 2px 7px; font-size: var(--fs-md); font-weight: 600; border-radius: var(--radius-xs); @@ -744,18 +788,12 @@ min-height: 26px; } -.topbar-header-right { - display: inline-flex; - align-items: center; - gap: var(--space-2); -} - .btn-ghost-sm { display: inline-flex; align-items: center; justify-content: center; - height: 20px; - padding: 0 6px; + min-height: calc(20px * var(--ui-font-scale, 1)); + padding: 1px 6px; font-size: var(--fs-md); font-weight: 500; color: var(--text-secondary); @@ -781,40 +819,13 @@ cursor: default; } -.topbar-slot-list { - display: flex; - flex-direction: column; - gap: 6px; -} - -.topbar-slot-row { - position: relative; - display: flex; - align-items: center; - gap: 6px; - padding: 2px 4px 2px 6px; - border: 1px solid var(--border-hairline); - border-radius: var(--radius-xs); - background: transparent; - transition: border-color var(--dur-instant) var(--ease-fast); -} - -.topbar-slot-row:focus-within, -.topbar-slot-row:has(.is-open) { - z-index: 30; - border-color: var(--border-strong); -} - -.topbar-slot-row .select-menu { - max-height: 216px; -} - .slot-index-badge { display: inline-flex; align-items: center; justify-content: center; - width: 16px; - height: 16px; + min-width: calc(16px * var(--ui-font-scale, 1)); + min-height: calc(16px * var(--ui-font-scale, 1)); + padding: 0 3px; font-size: var(--fs-sm); font-weight: 600; font-variant-numeric: tabular-nums; diff --git a/sidecars/panel/src/styles/overlay.css b/sidecars/panel/src/styles/overlay.css index 5b52ca9..b77c47c 100644 --- a/sidecars/panel/src/styles/overlay.css +++ b/sidecars/panel/src/styles/overlay.css @@ -5,7 +5,7 @@ /* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */ :host(.wm-capsule-host) { - --ui-font-scale: 1; + --ui-font-scale: 1 !important; display: inline-flex; align-items: center; gap: 6px; @@ -15,7 +15,7 @@ -webkit-app-region: no-drag; pointer-events: auto; user-select: none; - font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; + font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; font-size: 12px; font-weight: 450; font-stretch: 100%; @@ -24,6 +24,7 @@ letter-spacing: 0.015em; font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; color: var(--text-primary); z-index: 2147482900; } @@ -77,6 +78,10 @@ right: 144px; } +:host(.wm-capsule-host[data-dock="fixed"][data-os="mac"]) { + right: 12px; +} + @keyframes wm-dot-pulse { 0%, 100% { opacity: 1; @@ -227,11 +232,11 @@ flex-shrink: 0; } -/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */ +/* 环形上下文指示器(固定预占宽度 58px:14px 环 + 5px 间距 + 完整容纳四字符 100%) */ .wm-ctx-seg { justify-content: center; gap: 5px; - width: 50px; + width: 58px; } .wm-ring-svg { @@ -266,8 +271,10 @@ } .wm-ctx-pct { - min-width: 27px; - max-width: 31px; + min-width: 28px; + max-width: none; + overflow: visible; + text-overflow: clip; text-align: left; font-weight: 500; color: var(--text-primary); @@ -518,11 +525,12 @@ overflow: visible; pointer-events: none; z-index: 2147483000; - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-family: var(--font-sans); font-size: var(--fs-body); line-height: 1.4; font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; color: var(--text-primary); } @@ -581,7 +589,7 @@ position: fixed; top: 42px; left: 12px; - width: min(522px, calc(100vw - 24px)); + width: min(calc(522px * var(--ui-panel-scale, 1)), calc(100vw - 24px)); max-height: calc(100vh - 54px); padding: var(--space-3) var(--space-4); display: flex; @@ -605,7 +613,7 @@ position: fixed; top: 42px; left: 12px; - width: min(464px, calc(100vw - 24px)); + width: min(calc(464px * var(--ui-panel-scale, 1)), calc(100vw - 24px)); max-height: calc(100vh - 54px); padding: 14px 16px; display: flex; @@ -711,8 +719,8 @@ .wm-pin-badge { display: inline-flex; align-items: center; - height: 16px; - padding: 0 5px; + min-height: calc(16px * var(--ui-font-scale, 1)); + padding: 1px 5px; font-size: var(--fs-xs); font-weight: 600; color: var(--accent-primary); @@ -724,8 +732,8 @@ .wm-session-tag { display: inline-flex; align-items: center; - height: 16px; - padding: 0 4px; + min-height: calc(16px * var(--ui-font-scale, 1)); + padding: 1px 4px; font-size: var(--fs-xs); font-weight: 600; color: var(--text-secondary); diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css index c8ab516..eee1401 100644 --- a/sidecars/panel/src/styles/tokens.css +++ b/sidecars/panel/src/styles/tokens.css @@ -6,6 +6,10 @@ :root, :host { + /* Cross-Platform Typography Stacks (macOS SF Pro / SF Mono + Windows / Linux Fallbacks) */ + --font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Roboto, sans-serif; + --font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, "Cascadia Mono", Consolas, monospace; + /* Architectural Geometry: Only Top Nav uses --radius-pill */ --radius-pill: 999px; --radius-sm: 4px; @@ -43,16 +47,15 @@ --border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%); /* Typography Hierarchy & Scalable Font Tokens */ - --ui-font-scale: 1; - --fs-2xs: calc(9.5px * var(--ui-font-scale, 1)); - --fs-xs: calc(10px * var(--ui-font-scale, 1)); - --fs-sm: calc(10.5px * var(--ui-font-scale, 1)); - --fs-md: calc(11px * var(--ui-font-scale, 1)); - --fs-base-sm: calc(11.5px * var(--ui-font-scale, 1)); - --fs-base: calc(12px * var(--ui-font-scale, 1)); - --fs-body: calc(12.5px * var(--ui-font-scale, 1)); - --fs-lg: calc(14.5px * var(--ui-font-scale, 1)); - --fs-hero: calc(17px * var(--ui-font-scale, 1)); + --fs-2xs: calc(10.5px * var(--ui-font-scale, 1)); + --fs-xs: calc(11px * var(--ui-font-scale, 1)); + --fs-sm: calc(11.5px * var(--ui-font-scale, 1)); + --fs-md: calc(12px * var(--ui-font-scale, 1)); + --fs-base-sm: calc(12.5px * var(--ui-font-scale, 1)); + --fs-base: calc(13px * var(--ui-font-scale, 1)); + --fs-body: calc(13px * var(--ui-font-scale, 1)); + --fs-lg: calc(15px * var(--ui-font-scale, 1)); + --fs-hero: calc(18px * var(--ui-font-scale, 1)); --text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%)))); --text-secondary: var(--muted-foreground, var(--vscode-descriptionForeground, hsl(215 12% 44%))); @@ -120,6 +123,46 @@ --space-5: 12px; } +:root[data-font-scale="sm"], +:host([data-font-scale="sm"]), +[data-font-scale="sm"] { + --ui-font-scale: 0.92; + --ui-panel-scale: 1; +} + +:root[data-font-scale="md"], +:host([data-font-scale="md"]), +[data-font-scale="md"] { + --ui-font-scale: 1; + --ui-panel-scale: 1; +} + +:root[data-font-scale="lg"], +:host([data-font-scale="lg"]), +[data-font-scale="lg"] { + --ui-font-scale: 1.14; + --ui-panel-scale: 1.09; +} + +:root[data-font-scale="xl"], +:host([data-font-scale="xl"]), +[data-font-scale="xl"] { + --ui-font-scale: 1.28; + --ui-panel-scale: 1.18; +} + +[data-font-scale] { + --fs-2xs: calc(10.5px * var(--ui-font-scale, 1)); + --fs-xs: calc(11px * var(--ui-font-scale, 1)); + --fs-sm: calc(11.5px * var(--ui-font-scale, 1)); + --fs-md: calc(12px * var(--ui-font-scale, 1)); + --fs-base-sm: calc(12.5px * var(--ui-font-scale, 1)); + --fs-base: calc(13px * var(--ui-font-scale, 1)); + --fs-body: calc(13px * var(--ui-font-scale, 1)); + --fs-lg: calc(15px * var(--ui-font-scale, 1)); + --fs-hero: calc(18px * var(--ui-font-scale, 1)); +} + @media (prefers-color-scheme: dark) { html[data-standalone="true"] { color-scheme: dark; diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index cb5b3b2..cb49807 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -45,7 +45,7 @@ .cons-split-3 { display: grid; - grid-template-columns: repeat(3, 1fr); + grid-template-columns: repeat(3, minmax(0, 1fr)); } .cons-matrix-bottom { @@ -166,8 +166,8 @@ .cons-row-title { display: inline-flex; align-items: center; - height: 20px; - line-height: 20px; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.3; font-size: var(--fs-base); font-weight: 600; color: var(--text-primary); @@ -177,16 +177,16 @@ display: inline-flex; align-items: center; gap: 8px; - height: 20px; + min-height: calc(20px * var(--ui-font-scale, 1)); } .cons-share-pill { display: inline-flex; align-items: center; justify-content: center; - height: 20px; - line-height: 1; - padding: 0 6px; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.2; + padding: 1px 6px; font-size: var(--fs-base); font-weight: 600; color: var(--metric-ok); @@ -199,8 +199,8 @@ .cons-row-tok { display: inline-flex; align-items: center; - height: 20px; - line-height: 1; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.25; font-size: var(--fs-base); font-weight: 500; color: var(--text-secondary); @@ -209,8 +209,8 @@ .cons-row-cost { display: inline-flex; align-items: center; - height: 20px; - line-height: 1; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.25; font-size: var(--fs-base); font-weight: 700; color: var(--text-primary); @@ -287,7 +287,7 @@ top: 2px; left: var(--peak-x, 50%); transform: translateX(-50%); - font-size: 10px; + font-size: var(--fs-xs); font-weight: 600; padding: 1px 6px; color: var(--text-primary); @@ -306,7 +306,7 @@ transform: translateX(var(--tip-shift, -50%)); width: max-content; min-width: 152px; - max-width: min(300px, calc(100% - 8px)); + max-width: min(320px, calc(100% - 8px)); padding: 5px 9px; background: var(--surface-panel); border: 1px solid var(--border-strong); @@ -324,7 +324,7 @@ align-items: center; justify-content: space-between; gap: 10px; - font-size: 10.5px; + font-size: var(--fs-sm); color: var(--text-secondary); } @@ -336,7 +336,7 @@ } .trend-tip-calls { - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); white-space: nowrap; max-width: 190px; @@ -352,7 +352,7 @@ } .trend-tip-tokens { - font-size: 12px; + font-size: var(--fs-base); font-weight: 700; color: var(--accent-primary); white-space: nowrap; @@ -360,7 +360,7 @@ } .trend-tip-cost { - font-size: 11px; + font-size: var(--fs-md); font-weight: 600; color: var(--text-primary); white-space: nowrap; @@ -368,7 +368,7 @@ } .trend-tip-sub { - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-secondary); white-space: nowrap; overflow: hidden; @@ -391,7 +391,7 @@ .trend-x-axis { position: relative; width: 100%; - height: 18px; + min-height: calc(18px * var(--ui-font-scale, 1)); user-select: none; } @@ -400,10 +400,10 @@ top: 0; left: var(--tick-x, 0%); transform: translateX(-50%); - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); white-space: nowrap; - line-height: 16px; + line-height: 1.35; cursor: pointer; transition: color var(--dur-instant) var(--ease-fast); } @@ -455,21 +455,21 @@ .trend-hm-weekdays { display: grid; - grid-template-rows: 15px repeat(7, var(--hm-cell)); + grid-template-rows: calc(15px * var(--ui-font-scale, 1)) repeat(7, var(--hm-cell)); row-gap: var(--hm-gap); - width: 14px; + width: calc(15px * var(--ui-font-scale, 1)); flex-shrink: 0; } .trend-hm-month-spacer { - height: 15px; + height: calc(15px * var(--ui-font-scale, 1)); } .trend-hm-wday { display: flex; align-items: center; justify-content: flex-start; - font-size: 9px; + font-size: var(--fs-2xs); line-height: 1; color: var(--text-muted); } @@ -490,7 +490,7 @@ .trend-hm-months { position: relative; - height: 15px; + height: calc(15px * var(--ui-font-scale, 1)); width: 100%; } @@ -498,8 +498,8 @@ position: absolute; top: 0; left: calc(var(--hm-col, 0) * (var(--hm-cell) + var(--hm-gap))); - font-size: 9.5px; - line-height: 14px; + font-size: var(--fs-2xs); + line-height: 1.25; color: var(--text-muted); white-space: nowrap; pointer-events: none; @@ -511,6 +511,7 @@ grid-auto-flow: column; grid-auto-columns: var(--hm-cell); gap: var(--hm-gap); + cursor: pointer; } .trend-hm-cell { @@ -564,7 +565,7 @@ align-items: center; justify-content: space-between; gap: 8px; - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); min-height: 16px; } @@ -581,7 +582,7 @@ align-items: center; gap: 3px; flex-shrink: 0; - font-size: 9.5px; + font-size: var(--fs-2xs); color: var(--text-muted); } @@ -642,7 +643,7 @@ } .month-cost { - font-size: 9.5px; + font-size: var(--fs-2xs); color: var(--text-secondary); min-height: 14px; white-space: nowrap; @@ -686,7 +687,7 @@ } .month-label { - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-secondary); padding: 1px 3px; border-radius: var(--radius-xs); @@ -700,7 +701,7 @@ } .month-tok { - font-size: 9px; + font-size: var(--fs-2xs); color: var(--text-muted); min-height: 12px; white-space: nowrap; diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index ac4d82e..eb40399 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -94,6 +94,14 @@ } /* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */ +.overview-modules-host { + display: flex; + flex-direction: column; + gap: var(--space-3); + min-width: 0; + padding-bottom: 2px; +} + .live-activity-list { display: flex; flex-direction: column; @@ -156,8 +164,8 @@ display: inline-flex; align-items: center; gap: 3px; - height: 18px; - padding: 0 6px; + min-height: calc(18px * var(--ui-font-scale, 1)); + padding: 1px 6px; font-size: var(--fs-sm); font-weight: 600; color: var(--text-secondary); @@ -477,7 +485,7 @@ /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; - grid-template-columns: repeat(2, 1fr); + grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 5px var(--space-4); padding: 2px 0 0 0; background: transparent; @@ -490,6 +498,7 @@ align-items: center; justify-content: space-between; gap: var(--space-2); + min-width: 0; } .legend-left { @@ -547,8 +556,8 @@ display: inline-flex; align-items: center; gap: 4px; - height: 20px; - padding: 0 6px; + min-height: calc(20px * var(--ui-font-scale, 1)); + padding: 1px 6px; border: 1px solid var(--border-hairline); background: var(--surface-panel); color: var(--text-secondary); diff --git a/sidecars/panel/src/styles/views-settings.css b/sidecars/panel/src/styles/views-settings.css index 636b229..1c3d50a 100644 --- a/sidecars/panel/src/styles/views-settings.css +++ b/sidecars/panel/src/styles/views-settings.css @@ -37,7 +37,7 @@ } .settings-subnav-bar .seg-btn { - height: 24px; + min-height: calc(24px * var(--ui-font-scale, 1)); font-size: var(--fs-base-sm); font-weight: 500; } @@ -55,9 +55,9 @@ align-items: center; justify-content: center; gap: 4px; - height: 25px; + min-height: calc(25px * var(--ui-font-scale, 1)); min-width: 0; - padding: 0 6px; + padding: 2px 6px; border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); background: var(--surface-subtle); @@ -116,8 +116,8 @@ display: inline-flex; align-items: center; gap: 5px; - height: 24px; - padding: 0 9px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 9px; font-size: var(--fs-md); font-weight: 500; color: var(--text-secondary); @@ -230,19 +230,15 @@ font-weight: 600; } -/* --- 结构页真实 UI 实时预览画布(无套娃外框,直接呈现真实组件) --- */ +/* --- 结构页真实 UI 实时预览画布(1:1 零缩放、零套娃外框,直接呈现真实组件) --- */ .structure-preview-canvas { position: relative; display: flex; flex-direction: column; - gap: var(--space-2); + gap: var(--space-3); min-width: 0; } -.structure-preview-canvas.is-scaled { - zoom: 0.86; -} - .wm-hover-tip.is-preview { position: relative; top: auto; @@ -260,10 +256,7 @@ } .overview-modules-host.is-preview { - display: flex; - flex-direction: column; - gap: var(--space-2); - min-width: 0; + padding-bottom: 0; } .structure-preview-empty, @@ -286,6 +279,7 @@ } .preview-capsule-bar { + --ui-font-scale: 1; display: flex; align-items: center; justify-content: space-between; @@ -295,6 +289,10 @@ background: var(--surface-bg); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; + font-variant-numeric: tabular-nums; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; overflow-x: auto; user-select: none; } @@ -367,21 +365,6 @@ white-space: nowrap; } -.preview-win-controls { - display: inline-flex; - align-items: center; - gap: 5px; - padding-left: 4px; - flex-shrink: 0; -} - -.preview-win-dot { - width: 7px; - height: 7px; - border-radius: var(--radius-pill); - background: color-mix(in srgb, var(--text-secondary) 26%, transparent); -} - .preview-composer-send { display: inline-flex; align-items: center; @@ -431,8 +414,8 @@ .collapsible-badge { display: inline-flex; align-items: center; - height: 18px; - padding: 0 6px; + min-height: calc(18px * var(--ui-font-scale, 1)); + padding: 1px 6px; font-size: var(--fs-sm); font-weight: 500; color: var(--text-secondary); @@ -577,8 +560,8 @@ align-items: center; justify-content: center; gap: 5px; - height: 24px; - padding: 0 9px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 9px; font-size: var(--fs-md); font-weight: 500; color: var(--accent-primary); @@ -711,8 +694,8 @@ .settings-text-input { width: 100%; min-width: 0; - height: 28px; - padding: 0 8px; + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 2px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); @@ -738,7 +721,7 @@ } .settings-number-wrap .number-input { - height: 24px; + min-height: calc(24px * var(--ui-font-scale, 1)); background: var(--surface-subtle); } @@ -831,7 +814,148 @@ .ctx-risk-accept-btn { margin-top: 2px; - height: 26px; - padding: 0 var(--space-3); + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px var(--space-3); font-size: var(--fs-md); } + +/* --- CDP / 双栖桥接端口诊断与一键重拉卡片 (.settings-bridge-notice) --- */ +.app-bridge-banner-slot { + padding: 0 var(--space-4) var(--space-2); + flex-shrink: 0; +} + +.app-bridge-banner-slot[hidden] { + display: none !important; +} + +.settings-bridge-notice { + display: flex; + flex-direction: column; + align-items: stretch; + gap: 5px; + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-xs); + border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 89%, var(--metric-warn) 7%); +} + +.settings-bridge-notice.is-restart { + border-color: color-mix(in srgb, var(--metric-info) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 89%, var(--metric-info) 7%); +} + +.settings-bridge-notice[hidden] { + display: none !important; +} + +.settings-bridge-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 6px; + min-width: 0; + color: var(--metric-warn); +} + +.settings-bridge-head-main { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; + flex: 1; +} + +.settings-bridge-notice.is-restart .settings-bridge-head, +.settings-bridge-notice.is-restart .settings-bridge-icon, +.settings-bridge-notice.is-restart .settings-bridge-title { + color: var(--metric-info); +} + +.settings-bridge-icon { + color: var(--metric-warn); + flex-shrink: 0; +} + +.settings-bridge-title { + font-size: var(--fs-md); + font-weight: 600; + line-height: 1.35; + color: var(--metric-warn); +} + +.settings-bridge-dismiss-btn { + padding: 2px 4px; + min-height: 20px; + line-height: 1; + flex-shrink: 0; +} + +.settings-bridge-desc { + margin: 0; + font-size: var(--fs-sm); + line-height: 1.48; + color: var(--text-primary); + word-break: break-word; +} + +.settings-bridge-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-top: 2px; +} + +.settings-bridge-relaunch-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 5px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px var(--space-3); + border-radius: var(--radius-xs); + border: 1px solid var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-size: var(--fs-xs); + font-weight: 600; + cursor: pointer; + max-width: 100%; + transition: + background-color var(--dur-instant) var(--ease-fast), + opacity var(--dur-instant) var(--ease-fast); +} + +.settings-bridge-relaunch-btn:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent-primary) 20%, transparent); +} + +.settings-bridge-relaunch-btn:disabled { + opacity: 0.65; + cursor: wait; +} + +.settings-bridge-relaunch-btn[hidden] { + display: none !important; +} + +.settings-bridge-relaunch-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.settings-bridge-copy-btn { + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px var(--space-3); + font-size: var(--fs-xs); + font-family: var(--font-mono); + max-width: 100%; +} + +.settings-bridge-copy-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} diff --git a/sidecars/panel/src/styles/views-tables.css b/sidecars/panel/src/styles/views-tables.css index 39050ca..f1c9336 100644 --- a/sidecars/panel/src/styles/views-tables.css +++ b/sidecars/panel/src/styles/views-tables.css @@ -35,13 +35,14 @@ .data-table { width: 100%; border-collapse: collapse; - font-size: var(--fs-md); + font-size: var(--fs-base-sm); } .data-table th, .data-table td { - padding: 5px 4px; + padding: calc(5px * var(--ui-font-scale, 1)) calc(4px * var(--ui-font-scale, 1)); text-align: left; + font-size: var(--fs-base-sm); border-bottom: 1px solid var(--border-hairline); white-space: nowrap; } @@ -78,7 +79,7 @@ .step-model-cell { display: inline-flex; align-items: baseline; - max-width: var(--step-model-max-w, 176px); + max-width: calc(var(--step-model-max-w, 176px) * var(--ui-font-scale, 1)); min-width: 0; vertical-align: bottom; } @@ -94,7 +95,7 @@ .step-model-compact { flex-shrink: 0; white-space: nowrap; - color: var(--metric-info, var(--accent-primary)); + color: var(--accent-primary); font-weight: 500; } @@ -133,8 +134,9 @@ .steps-inline-scope-select .select-trigger, .steps-inline-model-select .select-trigger { - height: 22px; - padding: 0 6px; + min-height: calc(22px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 6px; gap: 4px; min-width: 0; overflow: hidden; @@ -320,8 +322,9 @@ } .sstep-fit-model-select .select-trigger { - height: 22px; - padding: 0 6px; + min-height: calc(22px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 6px; gap: 4px; min-width: 0; overflow: hidden; @@ -377,7 +380,7 @@ .sstep-axis-label { fill: var(--text-muted); font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); - font-size: 9.5px; + font-size: var(--fs-2xs); user-select: none; pointer-events: none; } @@ -485,7 +488,7 @@ display: flex; align-items: center; justify-content: center; - font-size: 11px; + font-size: var(--fs-md); pointer-events: none; z-index: 2; } @@ -496,7 +499,7 @@ flex-wrap: wrap; gap: 4px 10px; padding-top: 2px; - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-secondary); } @@ -535,7 +538,7 @@ flex-wrap: wrap; gap: 4px 8px; padding-top: 2px; - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); } @@ -595,7 +598,7 @@ } .sstep-fit-delta { - font-size: 10px; + font-size: var(--fs-xs); } /* --- 4. 极简高密度模型总览列表 (Minimalist Session Model Summary Cards) --- */ diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index a4ee6c5..759b19a 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -27,6 +27,7 @@ import { normalizeModelDisplayMode, normalizeOrchestratorIdDisplayMode, } from '../core/formatters.js'; +import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs'; import { i18nStore, isEnglishLocale, t } from '../i18n/index.js'; import { createSvgIcon } from '../icons/SvgIcon.js'; import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js'; @@ -572,22 +573,14 @@ export const ConsumptionView = defineComponent({ let cachePct = 0; let outPct = 0; if (totalTokens > 0) { - const rawTenths = [ - (inputTokens / totalTokens) * 1000, - (cacheTokens / totalTokens) * 1000, - (outputTokens / totalTokens) * 1000, - ]; - const floored = rawTenths.map((v) => Math.max(0, Math.floor(v))); - const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2])); - const order = [0, 1, 2].sort( - (a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a]) + const scaled = scaleBucketsExact( + { in: inputTokens, cache: cacheTokens, out: outputTokens }, + ['in', 'cache', 'out'], + 1000 ); - for (let k = 0; k < rem && k < 3; k++) { - floored[order[k]] += 1; - } - inPct = +(floored[0] / 10).toFixed(1); - cachePct = +(floored[1] / 10).toFixed(1); - outPct = +(floored[2] / 10).toFixed(1); + inPct = +(scaled.in / 10).toFixed(1); + cachePct = +(scaled.cache / 10).toFixed(1); + outPct = +(scaled.out / 10).toFixed(1); } patchText(inputSharePct, `${inPct}%`); diff --git a/sidecars/panel/src/views/LiveOverviewView.js b/sidecars/panel/src/views/LiveOverviewView.js index 12344e8..390947e 100644 --- a/sidecars/panel/src/views/LiveOverviewView.js +++ b/sidecars/panel/src/views/LiveOverviewView.js @@ -31,7 +31,6 @@ export const LiveOverviewView = defineComponent({ setup({ onCleanup }) { const overviewInner = h('div', { className: 'overview-modules-host', - style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', }); const widgetHost = createDynamicWidgetHost({ diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index a0cf277..76dace3 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -11,7 +11,6 @@ import { telemetryStore } from '../store/telemetryStore.js'; import { getVisibleMonitorView, uiStore } from '../store/uiStore.js'; import { CustomScrollbar } from '../components/ui/CustomScrollbar.js'; import { SegmentedControl } from '../components/ui/SegmentedControl.js'; -import { SettingsAccountTab } from './settings/SettingsAccountTab.js'; import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js'; import { SettingsOtherTab } from './settings/SettingsOtherTab.js'; import { SettingsStructureTab } from './settings/SettingsStructureTab.js'; @@ -52,7 +51,7 @@ export const SettingsView = defineComponent({ const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll }); const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll }); - const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll }); + const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll }); let showingAccount = false; @@ -60,25 +59,27 @@ export const SettingsView = defineComponent({ const target = subTab === 'structure' || subTab === 'other' || - (SHOW_ACCOUNT_TAB && subTab === 'account') + (accountTab && subTab === 'account') ? subTab : 'general'; subNavSwitch.setValue(target); patchAttr(generalTab.el, 'hidden', target !== 'general'); patchAttr(structureTab.el, 'hidden', target !== 'structure'); patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure'); - patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account'); patchAttr(otherTab.el, 'hidden', target !== 'other'); - const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings'; - if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); - showingAccount = nextShowingAccount; + if (accountTab) { + patchAttr(accountTab.el, 'hidden', target !== 'account'); + const nextShowingAccount = target === 'account' && activeView === 'settings'; + if (nextShowingAccount && !showingAccount) void accountTab.refs.load(); + showingAccount = nextShowingAccount; + } refreshScroll(); } const contentContainer = h( 'div', {}, - SHOW_ACCOUNT_TAB + accountTab ? [generalTab.el, structureTab.el, accountTab.el, otherTab.el] : [generalTab.el, structureTab.el, otherTab.el] ); @@ -102,10 +103,23 @@ export const SettingsView = defineComponent({ const telemetry = telemetryStore.getState().telemetry; const settings = telemetry?.settings; if (settingsSubTab === 'structure') { - if (settings) structureTab.refs.renderSettings(settings); + if (settings) { + structureTab.refs.renderSettings( + settings, + telemetry?.windowBridge, + telemetry?.hostPlatform + ); + } } else if (settingsSubTab === 'other') { - if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []); - } else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') { + if (settings) { + otherTab.refs.renderSettings( + settings, + telemetry.contextWindowModels || [], + telemetry?.windowBridge, + telemetry?.hostPlatform + ); + } + } else if (accountTab && settingsSubTab === 'account') { accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas); } else { if (settings) generalTab.refs.renderSettings(settings); @@ -117,6 +131,8 @@ export const SettingsView = defineComponent({ const unsubTelemetry = telemetryStore.subscribe( (st) => ({ settings: st.telemetry?.settings, + windowBridge: st.telemetry?.windowBridge, + hostPlatform: st.telemetry?.hostPlatform, cloudStatus: st.telemetry?.cloudStatus, contextWindowModels: st.telemetry?.contextWindowModels, account: st.telemetry?.account, @@ -145,7 +161,7 @@ export const SettingsView = defineComponent({ }); generalTab.refs.refreshLabels(); structureTab.refs.refreshLabels(); - accountTab.refs.refreshLabels(); + accountTab?.refs.refreshLabels(); otherTab.refs.refreshLabels(); refreshScroll(); } @@ -158,7 +174,7 @@ export const SettingsView = defineComponent({ subNavSwitch.destroy(); generalTab.destroy(); structureTab.destroy(); - accountTab.destroy(); + accountTab?.destroy(); otherTab.destroy(); viewScrollbar.destroy(); }); diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index f62c822..a3479fe 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -435,17 +435,20 @@ export const StepsDetailView = defineComponent({ let isDirty = false; function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) { - const activeCand = getStepModelGroupKey({ - modelLabel: scopedConv?.activeModelLabel, - modelShort: scopedConv?.activeModelShort, - }); - if ( - activeCand && - activeCand !== '模型未知' && - activeCand !== t('fmt.unknownModel') && - availableModelKeys.has(activeCand) - ) { - return activeCand; + if (scopedConv?.hasKnownModel !== false) { + const activeCand = getStepModelGroupKey({ + baseModelLabel: scopedConv?.activeBaseModelLabel, + baseModelShort: scopedConv?.activeBaseModelShort, + modelLabel: scopedConv?.activeModelLabel, + modelShort: scopedConv?.activeModelShort, + }); + if ( + activeCand && + activeCand !== t('fmt.unknownModel') && + availableModelKeys.has(activeCand) + ) { + return activeCand; + } } for (let i = chronoSteps.length - 1; i >= 0; i--) { const st = chronoSteps[i]; @@ -625,7 +628,7 @@ export const StepsDetailView = defineComponent({ if (!stepModelOptionMap.has(gk)) { const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk }); stepModelOptionMap.set(gk, { - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, calls: 0, }); } @@ -656,7 +659,7 @@ export const StepsDetailView = defineComponent({ }); perModelOptions.push({ value: gk, - label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk, + label: disp.baseText || disp.text || gk, meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }), }); } diff --git a/sidecars/panel/src/views/settings/SettingsOtherTab.js b/sidecars/panel/src/views/settings/SettingsOtherTab.js index a173212..ca8c187 100644 --- a/sidecars/panel/src/views/settings/SettingsOtherTab.js +++ b/sidecars/panel/src/views/settings/SettingsOtherTab.js @@ -17,6 +17,7 @@ import { saveSettingsPatch, } from '../../store/telemetryStore.js'; import { CustomSelect } from '../../components/ui/CustomSelect.js'; +import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js'; function getStepModelDisplayOptions() { return [ @@ -41,6 +42,8 @@ export const SettingsOtherTab = defineComponent({ let draftContextRiskAccepted = false; let acceptingContextRisk = false; let latestSettings = null; + let latestWindowBridge = null; + let latestHostPlatform = 'win32'; let contextWindowModels = []; let contextModelId = ''; let savingContextWindow = false; @@ -190,9 +193,11 @@ export const SettingsOtherTab = defineComponent({ } }, }); + const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true }); const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]); const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]); const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [ + ctxBridgeNotice.el, ctxModelRow, ctxWindowRow, h('div', { className: 'form-row' }, [ctxHint]), @@ -269,6 +274,13 @@ export const SettingsOtherTab = defineComponent({ patchAttr(ctxRiskAcceptBtn, 'disabled', acceptingContextRisk); const saved = latestSettings?.modelContextWindows || {}; + const wbState = String(latestWindowBridge?.state || '').trim(); + const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable'; + ctxBridgeNotice.refs.update({ + visible: unlocked, + windowBridge: latestWindowBridge, + hostPlatform: latestHostPlatform, + }); const models = new Map(contextWindowModels.map((model) => [model.id, model])); const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members])); for (const id of Object.keys(saved)) { @@ -313,6 +325,7 @@ export const SettingsOtherTab = defineComponent({ else if (value) { const name = formatLimit(value); if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name }); + else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name }); else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) { meta = t('settings.oth.ctxConfiguredReported', { name, @@ -483,10 +496,17 @@ export const SettingsOtherTab = defineComponent({ maintPanel, ]); - function renderSettings(settings, models = contextWindowModels) { + function renderSettings( + settings, + models = contextWindowModels, + windowBridge = latestWindowBridge, + hostPlatform = latestHostPlatform + ) { if (!settings) return; latestSettings = settings; contextWindowModels = models; + if (windowBridge !== undefined) latestWindowBridge = windowBridge; + if (hostPlatform) latestHostPlatform = hostPlatform; draftModelDisplayMode = normalizeClientModelDisplayMode( settings.modelDisplayMode, settings.showUpstreamModel @@ -544,6 +564,7 @@ export const SettingsOtherTab = defineComponent({ if (resetConfirmTimer) clearTimeout(resetConfirmTimer); stepModelSelect.destroy(); orchestratorIdSelect.destroy(); + ctxBridgeNotice.destroy(); ctxModelSelect.destroy(); ctxWindowSelect.destroy(); }); @@ -553,6 +574,7 @@ export const SettingsOtherTab = defineComponent({ refs: { stepModelSelect, orchestratorIdSelect, + ctxBridgeNotice, ctxModelSelect, ctxWindowSelect, rebuildCacheBtn, diff --git a/sidecars/panel/src/views/settings/SettingsStructureTab.js b/sidecars/panel/src/views/settings/SettingsStructureTab.js index 4b98f15..2674351 100644 --- a/sidecars/panel/src/views/settings/SettingsStructureTab.js +++ b/sidecars/panel/src/views/settings/SettingsStructureTab.js @@ -41,6 +41,7 @@ import { saveSettingsPatch, } from '../../store/telemetryStore.js'; import { getVisibleMonitorView, uiStore } from '../../store/uiStore.js'; +import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js'; import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js'; import { EditableSlotList } from '../../components/settings/EditableSlotList.js'; import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js'; @@ -119,6 +120,8 @@ export const SettingsStructureTab = defineComponent({ let rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT; let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS]; let latestSettings = null; + let latestWindowBridge = null; + let latestHostPlatform = 'win32'; function isStructureVisible() { const st = uiStore.getState(); @@ -329,6 +332,8 @@ export const SettingsStructureTab = defineComponent({ }, }); + const mountBridgeNotice = BridgeStatusNotice({}); + const mountSection = CollapsibleSection({ collapsible: false, icon: 'dock', @@ -362,6 +367,7 @@ export const SettingsStructureTab = defineComponent({ mountPreviewCanvas, h('div', { className: 'settings-divider' }), h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]), + mountBridgeNotice.el, h('div', { className: 'form-row' }, [ h('div', { className: 'settings-inline-row' }, [ popoverWidthLabelEl, @@ -394,6 +400,11 @@ export const SettingsStructureTab = defineComponent({ modelValue: draftWindowMountMode, options: getMountModeOptions(), }); + mountBridgeNotice.refs.update({ + visible: draftWindowMountMode !== 'sidebar', + windowBridge: latestWindowBridge, + hostPlatform: latestHostPlatform, + }); popoverWidthModeToggle.setProps({ modelValue: draftPopoverWidthMode, options: getPopoverWidthModeOptions(), @@ -449,7 +460,7 @@ export const SettingsStructureTab = defineComponent({ isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover', initialModuleKeys: [], }); - const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [ + const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ hoverPreviewTipEl, hoverPreviewEmptyEl, ]); @@ -541,7 +552,7 @@ export const SettingsStructureTab = defineComponent({ isVisibleFn: () => isStructureVisible() && activeThirdTab === 'overview', initialModuleKeys: [], }); - const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [ + const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [ overviewPreviewContainerEl, ]); @@ -800,7 +811,7 @@ export const SettingsStructureTab = defineComponent({ items: draftStepColumns, options: getStepColumnOptions(draftStepTokenComboFormat), minItems: 2, - maxItems: 15, + maxItems: 14, addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }), onPreview: (previewItems) => { draftStepColumns = normalizeClientStepColumns(previewItems); @@ -983,9 +994,15 @@ export const SettingsStructureTab = defineComponent({ stepsSection.el, ]); - function renderSettings(settings) { + function renderSettings( + settings, + windowBridge = latestWindowBridge, + hostPlatform = latestHostPlatform + ) { if (!settings) return; latestSettings = settings; + if (windowBridge !== undefined) latestWindowBridge = windowBridge; + if (hostPlatform) latestHostPlatform = hostPlatform; draftWindowMountMode = normalizeClientWindowMountMode( settings.windowMountMode, settings.enableWindowOverlay @@ -1087,6 +1104,7 @@ export const SettingsStructureTab = defineComponent({ onCleanup(() => { unsubUi(); + mountBridgeNotice.destroy(); capsulePreviewWidget.destroy(); hoverPreviewHost.destroy(); overviewPreviewHost.destroy(); @@ -1115,6 +1133,7 @@ export const SettingsStructureTab = defineComponent({ refs: { thirdNavBar, capsulePreviewWidget, + mountBridgeNotice, hoverPreviewHost, overviewPreviewHost, stepTablePreview, diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index dce4b03..3658b78 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -7,6 +7,10 @@ :root, :host { + /* Cross-Platform Typography Stacks (macOS SF Pro / SF Mono + Windows / Linux Fallbacks) */ + --font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Roboto, sans-serif; + --font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, "Cascadia Mono", Consolas, monospace; + /* Architectural Geometry: Only Top Nav uses --radius-pill */ --radius-pill: 999px; --radius-sm: 4px; @@ -44,16 +48,15 @@ --border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%); /* Typography Hierarchy & Scalable Font Tokens */ - --ui-font-scale: 1; - --fs-2xs: calc(9.5px * var(--ui-font-scale, 1)); - --fs-xs: calc(10px * var(--ui-font-scale, 1)); - --fs-sm: calc(10.5px * var(--ui-font-scale, 1)); - --fs-md: calc(11px * var(--ui-font-scale, 1)); - --fs-base-sm: calc(11.5px * var(--ui-font-scale, 1)); - --fs-base: calc(12px * var(--ui-font-scale, 1)); - --fs-body: calc(12.5px * var(--ui-font-scale, 1)); - --fs-lg: calc(14.5px * var(--ui-font-scale, 1)); - --fs-hero: calc(17px * var(--ui-font-scale, 1)); + --fs-2xs: calc(10.5px * var(--ui-font-scale, 1)); + --fs-xs: calc(11px * var(--ui-font-scale, 1)); + --fs-sm: calc(11.5px * var(--ui-font-scale, 1)); + --fs-md: calc(12px * var(--ui-font-scale, 1)); + --fs-base-sm: calc(12.5px * var(--ui-font-scale, 1)); + --fs-base: calc(13px * var(--ui-font-scale, 1)); + --fs-body: calc(13px * var(--ui-font-scale, 1)); + --fs-lg: calc(15px * var(--ui-font-scale, 1)); + --fs-hero: calc(18px * var(--ui-font-scale, 1)); --text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%)))); --text-secondary: var(--muted-foreground, var(--vscode-descriptionForeground, hsl(215 12% 44%))); @@ -121,6 +124,46 @@ --space-5: 12px; } +:root[data-font-scale="sm"], +:host([data-font-scale="sm"]), +[data-font-scale="sm"] { + --ui-font-scale: 0.92; + --ui-panel-scale: 1; +} + +:root[data-font-scale="md"], +:host([data-font-scale="md"]), +[data-font-scale="md"] { + --ui-font-scale: 1; + --ui-panel-scale: 1; +} + +:root[data-font-scale="lg"], +:host([data-font-scale="lg"]), +[data-font-scale="lg"] { + --ui-font-scale: 1.14; + --ui-panel-scale: 1.09; +} + +:root[data-font-scale="xl"], +:host([data-font-scale="xl"]), +[data-font-scale="xl"] { + --ui-font-scale: 1.28; + --ui-panel-scale: 1.18; +} + +[data-font-scale] { + --fs-2xs: calc(10.5px * var(--ui-font-scale, 1)); + --fs-xs: calc(11px * var(--ui-font-scale, 1)); + --fs-sm: calc(11.5px * var(--ui-font-scale, 1)); + --fs-md: calc(12px * var(--ui-font-scale, 1)); + --fs-base-sm: calc(12.5px * var(--ui-font-scale, 1)); + --fs-base: calc(13px * var(--ui-font-scale, 1)); + --fs-body: calc(13px * var(--ui-font-scale, 1)); + --fs-lg: calc(15px * var(--ui-font-scale, 1)); + --fs-hero: calc(18px * var(--ui-font-scale, 1)); +} + @media (prefers-color-scheme: dark) { html[data-standalone="true"] { color-scheme: dark; @@ -165,15 +208,21 @@ body { overflow: hidden; background: var(--surface-bg); color: var(--text-primary); - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-family: var(--font-sans); font-size: var(--fs-body); line-height: 1.4; font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; } button, -input { +input, +select, +textarea, +table, +th, +td { font-family: inherit; font-size: inherit; font-stretch: inherit; @@ -439,13 +488,15 @@ html[data-standalone="true"] .app-shell { /* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */ .long-pill-nav { position: relative; + container-type: inline-size; display: grid; - grid-template-columns: repeat(var(--pill-count, 4), 1fr); + grid-template-columns: repeat(var(--pill-count, 4), minmax(0, 1fr)); align-items: center; padding: 3px; background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-pill); + overflow: hidden; user-select: none; } @@ -471,15 +522,17 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: center; gap: 5px; - height: 26px; - padding: 0 var(--space-2); + min-width: 0; + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px var(--space-2); border: none; background: transparent; color: var(--text-secondary); font-size: var(--fs-base); font-weight: 500; - line-height: 1; + line-height: 1.15; border-radius: var(--radius-pill); + overflow: hidden; cursor: pointer; white-space: nowrap; transition: color var(--dur-instant) var(--ease-fast); @@ -493,20 +546,60 @@ html[data-standalone="true"] .app-shell { flex-shrink: 0; } -.pill-tab-label, -.pill-tab-badge { - display: inline-flex; - align-items: center; - height: 14px; - line-height: 1; +.pill-tab-label { + display: block; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + line-height: 1.2; } .pill-tab-badge { + display: inline-flex; + align-items: center; + flex-shrink: 0; + min-height: 14px; + line-height: 1.15; margin-left: -2px; font-size: var(--fs-base-sm); opacity: 0.85; } +@container (max-width: 30em) { + .pill-tab { + gap: 3.5px; + padding: 2px 4px; + font-size: var(--fs-md); + } + .pill-tab .svg-icon { + width: 13px; + height: 13px; + } + .pill-tab-badge { + display: none !important; + } +} + +@container (max-width: 23em) { + .pill-tab { + gap: 0; + padding: 2px 3px; + } + .pill-tab .svg-icon { + display: none; + } +} + +@container (max-width: 17.5em) { + .pill-tab .svg-icon { + display: block; + } + .pill-tab-label { + display: none; + } +} + .pill-tab:hover { color: var(--text-primary); } @@ -545,8 +638,8 @@ html[data-standalone="true"] .app-shell { justify-content: space-between; gap: var(--space-2); width: 100%; - height: 24px; - padding: 0 6px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 6px; background: transparent; color: var(--text-primary); border: none; @@ -672,7 +765,7 @@ html[data-standalone="true"] .app-shell { .number-input { display: inline-flex; align-items: stretch; - height: 28px; + min-height: calc(28px * var(--ui-font-scale, 1)); background: var(--surface-panel); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); @@ -732,8 +825,8 @@ html[data-standalone="true"] .app-shell { justify-content: space-between; gap: var(--space-2); width: 100%; - height: 26px; - padding: 0 var(--space-2); + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px var(--space-2); background: var(--surface-panel); color: var(--text-primary); border: 1px solid var(--border-hairline); @@ -786,7 +879,7 @@ html[data-standalone="true"] .app-shell { } .dt-day { - height: 22px; + min-height: calc(22px * var(--ui-font-scale, 1)); border: none; background: transparent; color: var(--text-primary); @@ -862,8 +955,8 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: center; gap: 4px; - height: 22px; - padding: 0 7px; + min-height: calc(22px * var(--ui-font-scale, 1)); + padding: 2px 7px; border: none; background: transparent; color: var(--text-secondary); @@ -972,8 +1065,8 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: center; gap: 6px; - height: 28px; - padding: 0 var(--space-5); + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 3px var(--space-5); background: var(--accent-primary); color: var(--text-inverse); border: 1px solid var(--accent-primary); @@ -997,8 +1090,8 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: center; gap: 6px; - height: 28px; - padding: 0 var(--space-4); + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 3px var(--space-4); background: var(--surface-panel); color: var(--text-primary); border: 1px solid var(--border-strong); @@ -1036,8 +1129,8 @@ html[data-standalone="true"] .app-shell { display: inline-flex; align-items: center; gap: 4px; - height: 22px; - padding: 0 7px; + min-height: calc(22px * var(--ui-font-scale, 1)); + padding: 2px 7px; font-size: var(--fs-md); font-weight: 600; border-radius: var(--radius-xs); @@ -1066,18 +1159,12 @@ html[data-standalone="true"] .app-shell { min-height: 26px; } -.topbar-header-right { - display: inline-flex; - align-items: center; - gap: var(--space-2); -} - .btn-ghost-sm { display: inline-flex; align-items: center; justify-content: center; - height: 20px; - padding: 0 6px; + min-height: calc(20px * var(--ui-font-scale, 1)); + padding: 1px 6px; font-size: var(--fs-md); font-weight: 500; color: var(--text-secondary); @@ -1103,40 +1190,13 @@ html[data-standalone="true"] .app-shell { cursor: default; } -.topbar-slot-list { - display: flex; - flex-direction: column; - gap: 6px; -} - -.topbar-slot-row { - position: relative; - display: flex; - align-items: center; - gap: 6px; - padding: 2px 4px 2px 6px; - border: 1px solid var(--border-hairline); - border-radius: var(--radius-xs); - background: transparent; - transition: border-color var(--dur-instant) var(--ease-fast); -} - -.topbar-slot-row:focus-within, -.topbar-slot-row:has(.is-open) { - z-index: 30; - border-color: var(--border-strong); -} - -.topbar-slot-row .select-menu { - max-height: 216px; -} - .slot-index-badge { display: inline-flex; align-items: center; justify-content: center; - width: 16px; - height: 16px; + min-width: calc(16px * var(--ui-font-scale, 1)); + min-height: calc(16px * var(--ui-font-scale, 1)); + padding: 0 3px; font-size: var(--fs-sm); font-weight: 600; font-variant-numeric: tabular-nums; @@ -1281,6 +1341,14 @@ html[data-standalone="true"] .app-shell { } /* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */ +.overview-modules-host { + display: flex; + flex-direction: column; + gap: var(--space-3); + min-width: 0; + padding-bottom: 2px; +} + .live-activity-list { display: flex; flex-direction: column; @@ -1343,8 +1411,8 @@ html[data-standalone="true"] .app-shell { display: inline-flex; align-items: center; gap: 3px; - height: 18px; - padding: 0 6px; + min-height: calc(18px * var(--ui-font-scale, 1)); + padding: 1px 6px; font-size: var(--fs-sm); font-weight: 600; color: var(--text-secondary); @@ -1664,7 +1732,7 @@ html[data-standalone="true"] .app-shell { /* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; - grid-template-columns: repeat(2, 1fr); + grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 5px var(--space-4); padding: 2px 0 0 0; background: transparent; @@ -1677,6 +1745,7 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: space-between; gap: var(--space-2); + min-width: 0; } .legend-left { @@ -1734,8 +1803,8 @@ html[data-standalone="true"] .app-shell { display: inline-flex; align-items: center; gap: 4px; - height: 20px; - padding: 0 6px; + min-height: calc(20px * var(--ui-font-scale, 1)); + padding: 1px 6px; border: 1px solid var(--border-hairline); background: var(--surface-panel); color: var(--text-secondary); @@ -1884,7 +1953,7 @@ html[data-standalone="true"] .app-shell { .cons-split-3 { display: grid; - grid-template-columns: repeat(3, 1fr); + grid-template-columns: repeat(3, minmax(0, 1fr)); } .cons-matrix-bottom { @@ -2005,8 +2074,8 @@ html[data-standalone="true"] .app-shell { .cons-row-title { display: inline-flex; align-items: center; - height: 20px; - line-height: 20px; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.3; font-size: var(--fs-base); font-weight: 600; color: var(--text-primary); @@ -2016,16 +2085,16 @@ html[data-standalone="true"] .app-shell { display: inline-flex; align-items: center; gap: 8px; - height: 20px; + min-height: calc(20px * var(--ui-font-scale, 1)); } .cons-share-pill { display: inline-flex; align-items: center; justify-content: center; - height: 20px; - line-height: 1; - padding: 0 6px; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.2; + padding: 1px 6px; font-size: var(--fs-base); font-weight: 600; color: var(--metric-ok); @@ -2038,8 +2107,8 @@ html[data-standalone="true"] .app-shell { .cons-row-tok { display: inline-flex; align-items: center; - height: 20px; - line-height: 1; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.25; font-size: var(--fs-base); font-weight: 500; color: var(--text-secondary); @@ -2048,8 +2117,8 @@ html[data-standalone="true"] .app-shell { .cons-row-cost { display: inline-flex; align-items: center; - height: 20px; - line-height: 1; + min-height: calc(20px * var(--ui-font-scale, 1)); + line-height: 1.25; font-size: var(--fs-base); font-weight: 700; color: var(--text-primary); @@ -2126,7 +2195,7 @@ html[data-standalone="true"] .app-shell { top: 2px; left: var(--peak-x, 50%); transform: translateX(-50%); - font-size: 10px; + font-size: var(--fs-xs); font-weight: 600; padding: 1px 6px; color: var(--text-primary); @@ -2145,7 +2214,7 @@ html[data-standalone="true"] .app-shell { transform: translateX(var(--tip-shift, -50%)); width: max-content; min-width: 152px; - max-width: min(300px, calc(100% - 8px)); + max-width: min(320px, calc(100% - 8px)); padding: 5px 9px; background: var(--surface-panel); border: 1px solid var(--border-strong); @@ -2163,7 +2232,7 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: space-between; gap: 10px; - font-size: 10.5px; + font-size: var(--fs-sm); color: var(--text-secondary); } @@ -2175,7 +2244,7 @@ html[data-standalone="true"] .app-shell { } .trend-tip-calls { - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); white-space: nowrap; max-width: 190px; @@ -2191,7 +2260,7 @@ html[data-standalone="true"] .app-shell { } .trend-tip-tokens { - font-size: 12px; + font-size: var(--fs-base); font-weight: 700; color: var(--accent-primary); white-space: nowrap; @@ -2199,7 +2268,7 @@ html[data-standalone="true"] .app-shell { } .trend-tip-cost { - font-size: 11px; + font-size: var(--fs-md); font-weight: 600; color: var(--text-primary); white-space: nowrap; @@ -2207,7 +2276,7 @@ html[data-standalone="true"] .app-shell { } .trend-tip-sub { - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-secondary); white-space: nowrap; overflow: hidden; @@ -2230,7 +2299,7 @@ html[data-standalone="true"] .app-shell { .trend-x-axis { position: relative; width: 100%; - height: 18px; + min-height: calc(18px * var(--ui-font-scale, 1)); user-select: none; } @@ -2239,10 +2308,10 @@ html[data-standalone="true"] .app-shell { top: 0; left: var(--tick-x, 0%); transform: translateX(-50%); - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); white-space: nowrap; - line-height: 16px; + line-height: 1.35; cursor: pointer; transition: color var(--dur-instant) var(--ease-fast); } @@ -2294,21 +2363,21 @@ html[data-standalone="true"] .app-shell { .trend-hm-weekdays { display: grid; - grid-template-rows: 15px repeat(7, var(--hm-cell)); + grid-template-rows: calc(15px * var(--ui-font-scale, 1)) repeat(7, var(--hm-cell)); row-gap: var(--hm-gap); - width: 14px; + width: calc(15px * var(--ui-font-scale, 1)); flex-shrink: 0; } .trend-hm-month-spacer { - height: 15px; + height: calc(15px * var(--ui-font-scale, 1)); } .trend-hm-wday { display: flex; align-items: center; justify-content: flex-start; - font-size: 9px; + font-size: var(--fs-2xs); line-height: 1; color: var(--text-muted); } @@ -2329,7 +2398,7 @@ html[data-standalone="true"] .app-shell { .trend-hm-months { position: relative; - height: 15px; + height: calc(15px * var(--ui-font-scale, 1)); width: 100%; } @@ -2337,8 +2406,8 @@ html[data-standalone="true"] .app-shell { position: absolute; top: 0; left: calc(var(--hm-col, 0) * (var(--hm-cell) + var(--hm-gap))); - font-size: 9.5px; - line-height: 14px; + font-size: var(--fs-2xs); + line-height: 1.25; color: var(--text-muted); white-space: nowrap; pointer-events: none; @@ -2350,6 +2419,7 @@ html[data-standalone="true"] .app-shell { grid-auto-flow: column; grid-auto-columns: var(--hm-cell); gap: var(--hm-gap); + cursor: pointer; } .trend-hm-cell { @@ -2403,7 +2473,7 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: space-between; gap: 8px; - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); min-height: 16px; } @@ -2420,7 +2490,7 @@ html[data-standalone="true"] .app-shell { align-items: center; gap: 3px; flex-shrink: 0; - font-size: 9.5px; + font-size: var(--fs-2xs); color: var(--text-muted); } @@ -2481,7 +2551,7 @@ html[data-standalone="true"] .app-shell { } .month-cost { - font-size: 9.5px; + font-size: var(--fs-2xs); color: var(--text-secondary); min-height: 14px; white-space: nowrap; @@ -2525,7 +2595,7 @@ html[data-standalone="true"] .app-shell { } .month-label { - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-secondary); padding: 1px 3px; border-radius: var(--radius-xs); @@ -2539,7 +2609,7 @@ html[data-standalone="true"] .app-shell { } .month-tok { - font-size: 9px; + font-size: var(--fs-2xs); color: var(--text-muted); min-height: 12px; white-space: nowrap; @@ -2593,13 +2663,14 @@ html[data-standalone="true"] .app-shell { .data-table { width: 100%; border-collapse: collapse; - font-size: var(--fs-md); + font-size: var(--fs-base-sm); } .data-table th, .data-table td { - padding: 5px 4px; + padding: calc(5px * var(--ui-font-scale, 1)) calc(4px * var(--ui-font-scale, 1)); text-align: left; + font-size: var(--fs-base-sm); border-bottom: 1px solid var(--border-hairline); white-space: nowrap; } @@ -2636,7 +2707,7 @@ html[data-standalone="true"] .app-shell { .step-model-cell { display: inline-flex; align-items: baseline; - max-width: var(--step-model-max-w, 176px); + max-width: calc(var(--step-model-max-w, 176px) * var(--ui-font-scale, 1)); min-width: 0; vertical-align: bottom; } @@ -2652,7 +2723,7 @@ html[data-standalone="true"] .app-shell { .step-model-compact { flex-shrink: 0; white-space: nowrap; - color: var(--metric-info, var(--accent-primary)); + color: var(--accent-primary); font-weight: 500; } @@ -2691,8 +2762,9 @@ html[data-standalone="true"] .app-shell { .steps-inline-scope-select .select-trigger, .steps-inline-model-select .select-trigger { - height: 22px; - padding: 0 6px; + min-height: calc(22px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 6px; gap: 4px; min-width: 0; overflow: hidden; @@ -2878,8 +2950,9 @@ html[data-standalone="true"] .app-shell { } .sstep-fit-model-select .select-trigger { - height: 22px; - padding: 0 6px; + min-height: calc(22px * var(--ui-font-scale, 1)); + height: auto; + padding: 2px 6px; gap: 4px; min-width: 0; overflow: hidden; @@ -2935,7 +3008,7 @@ html[data-standalone="true"] .app-shell { .sstep-axis-label { fill: var(--text-muted); font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace); - font-size: 9.5px; + font-size: var(--fs-2xs); user-select: none; pointer-events: none; } @@ -3043,7 +3116,7 @@ html[data-standalone="true"] .app-shell { display: flex; align-items: center; justify-content: center; - font-size: 11px; + font-size: var(--fs-md); pointer-events: none; z-index: 2; } @@ -3054,7 +3127,7 @@ html[data-standalone="true"] .app-shell { flex-wrap: wrap; gap: 4px 10px; padding-top: 2px; - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-secondary); } @@ -3093,7 +3166,7 @@ html[data-standalone="true"] .app-shell { flex-wrap: wrap; gap: 4px 8px; padding-top: 2px; - font-size: 10px; + font-size: var(--fs-xs); color: var(--text-muted); } @@ -3153,7 +3226,7 @@ html[data-standalone="true"] .app-shell { } .sstep-fit-delta { - font-size: 10px; + font-size: var(--fs-xs); } /* --- 4. 极简高密度模型总览列表 (Minimalist Session Model Summary Cards) --- */ @@ -3326,7 +3399,7 @@ html[data-standalone="true"] .app-shell { } .settings-subnav-bar .seg-btn { - height: 24px; + min-height: calc(24px * var(--ui-font-scale, 1)); font-size: var(--fs-base-sm); font-weight: 500; } @@ -3344,9 +3417,9 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: center; gap: 4px; - height: 25px; + min-height: calc(25px * var(--ui-font-scale, 1)); min-width: 0; - padding: 0 6px; + padding: 2px 6px; border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); background: var(--surface-subtle); @@ -3405,8 +3478,8 @@ html[data-standalone="true"] .app-shell { display: inline-flex; align-items: center; gap: 5px; - height: 24px; - padding: 0 9px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 9px; font-size: var(--fs-md); font-weight: 500; color: var(--text-secondary); @@ -3519,19 +3592,15 @@ html[data-standalone="true"] .app-shell { font-weight: 600; } -/* --- 结构页真实 UI 实时预览画布(无套娃外框,直接呈现真实组件) --- */ +/* --- 结构页真实 UI 实时预览画布(1:1 零缩放、零套娃外框,直接呈现真实组件) --- */ .structure-preview-canvas { position: relative; display: flex; flex-direction: column; - gap: var(--space-2); + gap: var(--space-3); min-width: 0; } -.structure-preview-canvas.is-scaled { - zoom: 0.86; -} - .wm-hover-tip.is-preview { position: relative; top: auto; @@ -3549,10 +3618,7 @@ html[data-standalone="true"] .app-shell { } .overview-modules-host.is-preview { - display: flex; - flex-direction: column; - gap: var(--space-2); - min-width: 0; + padding-bottom: 0; } .structure-preview-empty, @@ -3575,6 +3641,7 @@ html[data-standalone="true"] .app-shell { } .preview-capsule-bar { + --ui-font-scale: 1; display: flex; align-items: center; justify-content: space-between; @@ -3584,6 +3651,10 @@ html[data-standalone="true"] .app-shell { background: var(--surface-bg); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); + font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; + font-variant-numeric: tabular-nums; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; overflow-x: auto; user-select: none; } @@ -3656,21 +3727,6 @@ html[data-standalone="true"] .app-shell { white-space: nowrap; } -.preview-win-controls { - display: inline-flex; - align-items: center; - gap: 5px; - padding-left: 4px; - flex-shrink: 0; -} - -.preview-win-dot { - width: 7px; - height: 7px; - border-radius: var(--radius-pill); - background: color-mix(in srgb, var(--text-secondary) 26%, transparent); -} - .preview-composer-send { display: inline-flex; align-items: center; @@ -3720,8 +3776,8 @@ html[data-standalone="true"] .app-shell { .collapsible-badge { display: inline-flex; align-items: center; - height: 18px; - padding: 0 6px; + min-height: calc(18px * var(--ui-font-scale, 1)); + padding: 1px 6px; font-size: var(--fs-sm); font-weight: 500; color: var(--text-secondary); @@ -3866,8 +3922,8 @@ html[data-standalone="true"] .app-shell { align-items: center; justify-content: center; gap: 5px; - height: 24px; - padding: 0 9px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px 9px; font-size: var(--fs-md); font-weight: 500; color: var(--accent-primary); @@ -4000,8 +4056,8 @@ html[data-standalone="true"] .app-shell { .settings-text-input { width: 100%; min-width: 0; - height: 28px; - padding: 0 8px; + min-height: calc(28px * var(--ui-font-scale, 1)); + padding: 2px 8px; background: var(--surface-subtle); border: 1px solid var(--border-hairline); border-radius: var(--radius-xs); @@ -4027,7 +4083,7 @@ html[data-standalone="true"] .app-shell { } .settings-number-wrap .number-input { - height: 24px; + min-height: calc(24px * var(--ui-font-scale, 1)); background: var(--surface-subtle); } @@ -4120,11 +4176,152 @@ html[data-standalone="true"] .app-shell { .ctx-risk-accept-btn { margin-top: 2px; - height: 26px; - padding: 0 var(--space-3); + min-height: calc(26px * var(--ui-font-scale, 1)); + padding: 2px var(--space-3); font-size: var(--fs-md); } +/* --- CDP / 双栖桥接端口诊断与一键重拉卡片 (.settings-bridge-notice) --- */ +.app-bridge-banner-slot { + padding: 0 var(--space-4) var(--space-2); + flex-shrink: 0; +} + +.app-bridge-banner-slot[hidden] { + display: none !important; +} + +.settings-bridge-notice { + display: flex; + flex-direction: column; + align-items: stretch; + gap: 5px; + padding: var(--space-3) var(--space-4); + border-radius: var(--radius-xs); + border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 89%, var(--metric-warn) 7%); +} + +.settings-bridge-notice.is-restart { + border-color: color-mix(in srgb, var(--metric-info) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--surface-panel) 89%, var(--metric-info) 7%); +} + +.settings-bridge-notice[hidden] { + display: none !important; +} + +.settings-bridge-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 6px; + min-width: 0; + color: var(--metric-warn); +} + +.settings-bridge-head-main { + display: inline-flex; + align-items: center; + gap: 6px; + min-width: 0; + flex: 1; +} + +.settings-bridge-notice.is-restart .settings-bridge-head, +.settings-bridge-notice.is-restart .settings-bridge-icon, +.settings-bridge-notice.is-restart .settings-bridge-title { + color: var(--metric-info); +} + +.settings-bridge-icon { + color: var(--metric-warn); + flex-shrink: 0; +} + +.settings-bridge-title { + font-size: var(--fs-md); + font-weight: 600; + line-height: 1.35; + color: var(--metric-warn); +} + +.settings-bridge-dismiss-btn { + padding: 2px 4px; + min-height: 20px; + line-height: 1; + flex-shrink: 0; +} + +.settings-bridge-desc { + margin: 0; + font-size: var(--fs-sm); + line-height: 1.48; + color: var(--text-primary); + word-break: break-word; +} + +.settings-bridge-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-top: 2px; +} + +.settings-bridge-relaunch-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 5px; + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px var(--space-3); + border-radius: var(--radius-xs); + border: 1px solid var(--accent-primary-border); + background: var(--accent-primary-soft); + color: var(--accent-primary); + font-size: var(--fs-xs); + font-weight: 600; + cursor: pointer; + max-width: 100%; + transition: + background-color var(--dur-instant) var(--ease-fast), + opacity var(--dur-instant) var(--ease-fast); +} + +.settings-bridge-relaunch-btn:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent-primary) 20%, transparent); +} + +.settings-bridge-relaunch-btn:disabled { + opacity: 0.65; + cursor: wait; +} + +.settings-bridge-relaunch-btn[hidden] { + display: none !important; +} + +.settings-bridge-relaunch-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.settings-bridge-copy-btn { + min-height: calc(24px * var(--ui-font-scale, 1)); + padding: 2px var(--space-3); + font-size: var(--fs-xs); + font-family: var(--font-mono); + max-width: 100%; +} + +.settings-bridge-copy-text { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + /* --- src/styles/overlay.css --- */ /* * 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css). @@ -4133,7 +4330,7 @@ html[data-standalone="true"] .app-shell { /* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */ :host(.wm-capsule-host) { - --ui-font-scale: 1; + --ui-font-scale: 1 !important; display: inline-flex; align-items: center; gap: 6px; @@ -4143,7 +4340,7 @@ html[data-standalone="true"] .app-shell { -webkit-app-region: no-drag; pointer-events: auto; user-select: none; - font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; + font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif; font-size: 12px; font-weight: 450; font-stretch: 100%; @@ -4152,6 +4349,7 @@ html[data-standalone="true"] .app-shell { letter-spacing: 0.015em; font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; color: var(--text-primary); z-index: 2147482900; } @@ -4205,6 +4403,10 @@ html[data-standalone="true"] .app-shell { right: 144px; } +:host(.wm-capsule-host[data-dock="fixed"][data-os="mac"]) { + right: 12px; +} + @keyframes wm-dot-pulse { 0%, 100% { opacity: 1; @@ -4355,11 +4557,11 @@ html[data-standalone="true"] .app-shell { flex-shrink: 0; } -/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */ +/* 环形上下文指示器(固定预占宽度 58px:14px 环 + 5px 间距 + 完整容纳四字符 100%) */ .wm-ctx-seg { justify-content: center; gap: 5px; - width: 50px; + width: 58px; } .wm-ring-svg { @@ -4394,8 +4596,10 @@ html[data-standalone="true"] .app-shell { } .wm-ctx-pct { - min-width: 27px; - max-width: 31px; + min-width: 28px; + max-width: none; + overflow: visible; + text-overflow: clip; text-align: left; font-weight: 500; color: var(--text-primary); @@ -4646,11 +4850,12 @@ html[data-standalone="true"] .app-shell { overflow: visible; pointer-events: none; z-index: 2147483000; - font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif; + font-family: var(--font-sans); font-size: var(--fs-body); line-height: 1.4; font-variant-numeric: tabular-nums; -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; color: var(--text-primary); } @@ -4709,7 +4914,7 @@ html[data-standalone="true"] .app-shell { position: fixed; top: 42px; left: 12px; - width: min(522px, calc(100vw - 24px)); + width: min(calc(522px * var(--ui-panel-scale, 1)), calc(100vw - 24px)); max-height: calc(100vh - 54px); padding: var(--space-3) var(--space-4); display: flex; @@ -4733,7 +4938,7 @@ html[data-standalone="true"] .app-shell { position: fixed; top: 42px; left: 12px; - width: min(464px, calc(100vw - 24px)); + width: min(calc(464px * var(--ui-panel-scale, 1)), calc(100vw - 24px)); max-height: calc(100vh - 54px); padding: 14px 16px; display: flex; @@ -4839,8 +5044,8 @@ html[data-standalone="true"] .app-shell { .wm-pin-badge { display: inline-flex; align-items: center; - height: 16px; - padding: 0 5px; + min-height: calc(16px * var(--ui-font-scale, 1)); + padding: 1px 5px; font-size: var(--fs-xs); font-weight: 600; color: var(--accent-primary); @@ -4852,8 +5057,8 @@ html[data-standalone="true"] .app-shell { .wm-session-tag { display: inline-flex; align-items: center; - height: 16px; - padding: 0 4px; + min-height: calc(16px * var(--ui-font-scale, 1)); + padding: 1px 4px; font-size: var(--fs-xs); font-weight: 600; color: var(--text-secondary); diff --git a/sidecars/panel/test/audit-fixes.test.mjs b/sidecars/panel/test/audit-fixes.test.mjs deleted file mode 100644 index 2d6e179..0000000 --- a/sidecars/panel/test/audit-fixes.test.mjs +++ /dev/null @@ -1,586 +0,0 @@ -import test from 'node:test'; -import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import vm from 'node:vm'; -import { backendHarness } from './backend-harness.mjs'; -import { - extractContextBreakdown, - extractModelSteps, - normalizeCachedStep, -} from '../speed-metrics.mjs'; -import { - formatCountdown, - formatUsd, - speedReasonText, -} from '../src/core/formatters.js'; -import { createReactiveStore } from '../src/core/reactive.js'; -import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; - -const nowMs = Date.now(); -const nowIso = new Date(nowMs - 5_000).toISOString(); -const doneIso = new Date(nowMs - 3_000).toISOString(); - -test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as Gemini, and M429/M322/M149/M20 resolve accurately', () => { - const h = backendHarness({ - userStatus: { - cascadeModelConfigData: { - clientModelConfigs: [ - { - modelOrAlias: { model: 'MODEL_CLAUDE_PROXY' }, - label: 'Claude Opus 4.6 (Google Vertex)', - quotaInfo: { remainingFraction: 0.75, resetTime: new Date(nowMs + 3600_000).toISOString() }, - }, - ], - }, - }, - }); - - const infoClaude = h.resolveModelInfo('claude-opus-4-6', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); - assert.equal(infoClaude.family, 'Claude'); - const infoO3 = h.resolveModelInfo('o3-mini', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); - assert.equal(infoO3.family, 'GPT'); - - // Calling resolveModelInfo with omitted dynamicModelMap must not throw (BUG-03) - const infoDefaultMap = h.resolveModelInfo('MODEL_PLACEHOLDER_M320'); - assert.equal(infoDefaultMap.modelId, 'gemini-3.8-flash-low'); - assert.equal(infoDefaultMap.pricing?.input, 0.3); - - const m429 = h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); - assert.equal(m429.modelId, 'gemini-4-carbon-high'); - assert.equal(m429.shortName, 'carbon-4-high'); - - const m322 = h.resolveModelInfo('MODEL_PLACEHOLDER_M322', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); - assert.equal(m322.modelId, 'gemini-3.8-flash-tiered'); - assert.equal( - h.computeStepCost( - { - modelKey: 'MODEL_PLACEHOLDER_M322', - inputTokens: 1_000_000, - cacheReadTokens: 0, - outputTokens: 0, - }, - m322.pricing - ), - 0.75 - ); - - const m149 = h.resolveModelInfo('MODEL_PLACEHOLDER_M149', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); - assert.equal(m149.modelId, 'gemini-3.5-flash-high'); - - const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); - assert.equal(m20.modelId, 'gemini-3.5-flash'); - - // Gemini Hydrogen ($1.50/$0.075/$7.50) & Helix ($0.30/$0.015/$2.50), shared Gemini pool - const dynHydrogenMap = new Map([ - ['MODEL_PLACEHOLDER_M480', { modelId: '', label: 'Gemini 4 Hydrogen (High)' }], - ['MODEL_PLACEHOLDER_M481', { modelId: '', label: 'Gemini 4 Hydrogen (Low)' }], - ['MODEL_PLACEHOLDER_M482', { modelId: '', label: 'Gemini 4 Helix' }], - ]); - const hydroHigh = h.resolveModelInfo('MODEL_PLACEHOLDER_M480', dynHydrogenMap); - assert.equal(hydroHigh.family, 'Gemini'); - assert.equal(hydroHigh.shortName, 'hydrogen-4-high'); - assert.deepEqual( - { i: hydroHigh.pricing?.input, c: hydroHigh.pricing?.cache, o: hydroHigh.pricing?.output }, - { i: 1.5, c: 0.075, o: 7.5 } - ); - const hydroLow = h.resolveModelInfo('MODEL_PLACEHOLDER_M481', dynHydrogenMap); - assert.equal(hydroLow.shortName, 'hydrogen-4-low'); - assert.deepEqual( - { i: hydroLow.pricing?.input, c: hydroLow.pricing?.cache, o: hydroLow.pricing?.output }, - { i: 1.5, c: 0.075, o: 7.5 } - ); - const hydroCodename = h.resolveModelInfo('gemini-hydrogen'); - assert.equal(hydroCodename.family, 'Gemini'); - assert.equal(hydroCodename.label, 'Gemini Hydrogen'); - assert.equal(hydroCodename.pricing?.input, 1.5); - assert.equal(hydroCodename.pricing?.output, 7.5); - - const helixInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M482', dynHydrogenMap); - assert.equal(helixInfo.family, 'Gemini'); - assert.equal(helixInfo.shortName, 'helix-4'); - assert.deepEqual( - { i: helixInfo.pricing?.input, c: helixInfo.pricing?.cache, o: helixInfo.pricing?.output }, - { i: 0.3, c: 0.015, o: 2.5 } - ); - const helixCodename = h.resolveModelInfo('gemini-helix'); - assert.equal(helixCodename.family, 'Gemini'); - assert.equal(helixCodename.label, 'Gemini Helix'); - assert.equal(helixCodename.pricing?.output, 2.5); - - const { quotaPoolsMap } = h.buildOfficialQuotaPools(null, [ - { - modelOrAlias: { model: 'MODEL_PLACEHOLDER_M480' }, - label: 'Gemini 4 Hydrogen (High)', - quotaInfo: { remainingFraction: 0.8, resetTime: new Date(nowMs + 3600_000).toISOString() }, - }, - { - modelOrAlias: { model: 'MODEL_PLACEHOLDER_M482' }, - label: 'Gemini 4 Helix', - quotaInfo: { remainingFraction: 0.8, resetTime: new Date(nowMs + 3600_000).toISOString() }, - }, - ]); - assert.equal(quotaPoolsMap.has('Hydrogen'), false, 'Hydrogen has no dedicated quota pool'); - assert.equal(quotaPoolsMap.has('Helix'), false, 'Helix has no dedicated quota pool'); - assert.equal(quotaPoolsMap.get('Gemini')?.isAvailable, true); -}); - -test('BUG-02 & BUG-11: ide: external sessions do not double-count live conversations, cross-account entries are isolated, and orphan subagents never leak to top-level list', async () => { - const stepObj = { - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - sourceTrajectoryStepInfo: { stepIndex: 1 }, - createdAt: nowIso, - completedAt: doneIso, - modelUsage: { - model: 'MODEL_PLACEHOLDER_M318', - inputTokens: '10000', - cacheReadTokens: '20000', - outputTokens: '5000', - }, - }, - }; - const h = backendHarness({ - userStatus: { email: 'alice@example.com' }, - deepStats: { - accountName: 'alice@example.com', - perConvo: { - // Same conversation ID as live 'abcd-1234' (case-insensitive, prefixed with 'ide:') -> must deduplicate! - 'ide:AbCd-1234': { - accountName: 'alice@example.com', - appSource: 'ide', - entries: [ - { ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, - { ts: doneIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, - ], - }, - // Different account -> must be excluded when logged in as alice@example.com! - 'ide:bob-conv': { - accountName: 'bob@example.com', - appSource: 'ide', - entries: [ - { ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 99000, cache: 0, out: 1000, reasoning: 0 }, - ], - }, - }, - }, - cache: { - 'orphan-sub': { - accountName: 'bob@example.com', - isSubagent: true, - parentCascadeId: 'deleted-parent', - signature: 'v10-model-identity:sub', - steps: extractModelSteps([stepObj]), - }, - }, - summaries: { - 'abcd-1234': { stepCount: 1, lastModifiedTime: doneIso, status: 'IDLE' }, - }, - trajectories: { - 'abcd-1234': { trajectory: { steps: [stepObj] } }, - }, - }); - - const p = await h.buildTelemetryPayloadInternal('abcd-1234', false, { range: 'all' }); - // ide:AbCd-1234 has 2 entries vs live abcd-1234's 1 step -> deduplicated (no 1 + 2 = 3 double counting!), bob excluded! - assert.equal(p.consumption.account.conversationsCount, 1); - assert.equal(p.consumption.account.calls, 2); - assert.equal(p.consumption.account.totalTokens, 70_000); - assert.equal( - p.conversations.some((c) => c.cascadeId === 'orphan-sub'), - false, - 'orphan subagent must not appear in top-level conversation dropdown' - ); -}); - -test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd rounding, and dynamicModelMap default', async () => { - const badStep = { - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - sourceTrajectoryStepInfo: { stepIndex: 1 }, - createdAt: nowIso, - completedAt: doneIso, - modelUsage: { - model: 'MODEL_PLACEHOLDER_M318', - inputTokens: '-5000', - cacheReadTokens: 'NaN', - outputTokens: '1000', - thinkingOutputTokens: '2500', - }, - }, - }; - const extracted = extractModelSteps([badStep]); - assert.equal(extracted[0].inputTokens, 0); - assert.equal(extracted[0].cacheReadTokens, 0); - assert.equal(extracted[0].outputTokens, 1000); - assert.equal(extracted[0].thinkingTokens, 1000); - assert.equal(extracted[0].responseTokens, 0); - assert.equal(normalizeCachedStep({ ...extracted[0], inputTokens: -99 }).inputTokens, 0); - assert.equal(normalizeCachedStep(null), null); - - // Micro-steps: 100 steps * (1067 output * $3.75 / 1M = $0.00400125) = $0.40 (previously rounded per-step to $0.00 -> $0.00!) - const microSteps = Array.from({ length: 100 }, (_, idx) => ({ - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - sourceTrajectoryStepInfo: { stepIndex: idx + 1 }, - createdAt: nowIso, - completedAt: doneIso, - modelUsage: { - model: 'MODEL_PLACEHOLDER_M318', // gemini-3.8-flash-high: $0.75/1M input, $3.75/1M output - inputTokens: '0', - cacheReadTokens: '0', - outputTokens: '1067', - }, - }, - })); - const h = backendHarness({ - summaries: { micro: { stepCount: 100, lastModifiedTime: doneIso, status: 'IDLE' } }, - trajectories: { micro: { trajectory: { steps: microSteps } } }, - }); - const p = await h.buildTelemetryPayloadInternal('micro', false, { range: 'today' }); - assert.equal(p.consumption.account.costUsd, 0.4); -}); - -test('BUG-04 & BUG-10: failed RUNNING trajectory fetch enters cooldown instead of hammering RPC every poll, cleared by forceRefresh', async () => { - const h = backendHarness({ - summaries: { run1: { stepCount: 2, lastModifiedTime: doneIso, status: 'CASCADE_RUN_STATUS_RUNNING' } }, - trajectories: { run1: new Error('LS timeout') }, - quotaSummary: new Error('Quota RPC down'), - }); - - await h.buildTelemetryPayloadInternal('run1', false); - const callsAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; - const quotaCallsAfterFirst = h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length; - assert.equal(callsAfterFirst, 1); - assert.equal(quotaCallsAfterFirst, 1); - - // Immediate second background poll must respect cooldown for both trajectory and quota RPC - await h.buildTelemetryPayloadInternal('run1', false); - assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 1); - assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 1); - - // Manual forceRefresh=true bypasses cooldown immediately - await h.buildTelemetryPayloadInternal('run1', true); - assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 2); - assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 2); -}); - -test('BUG-09, BUG-14 & BUG-15: SemVer 2.0 prerelease/build ordering, future-only exhausted quota inference, and <6h dual-bucket classification', async () => { - const h = backendHarness({ - quotaSummary: { - groups: [ - { - displayName: 'Gemini', - buckets: [ - { - // Omitted remainingFraction with epoch-0 resetTime must NOT falsely report 0% remaining! - resetTime: '1970-01-01T00:00:00Z', - }, - ], - }, - { - displayName: 'Claude & GPT', - buckets: [ - { - remainingFraction: 0.4, - resetTime: new Date(nowMs + 2 * 3600_000).toISOString(), - }, - { - remainingFraction: 0.8, - // Weekly bucket that happens to be 4h away from resetting! - resetTime: new Date(nowMs + 4 * 3600_000).toISOString(), - }, - ], - }, - ], - }, - }); - - assert.equal(h.compareSemver('1.4.2+20261110', '1.4.2'), 0); - assert.equal(h.compareSemver('1.5.0-beta.2', '1.5.0-alpha.10'), 1); - assert.equal(h.compareSemver('1.5.0-alpha.1', '1.5.0-alpha.beta'), -1); - - const p = await h.buildTelemetryPayloadInternal(''); - const geminiPool = p.quotas.pools.find((x) => x.poolKey === 'Gemini'); - assert.ok(geminiPool); - assert.equal(geminiPool.isAvailable, false, 'epoch-0 omitted remainingFraction must not create fake 0% exhausted pool'); - assert.equal(geminiPool.remainingPct, null); - assert.equal(geminiPool.usedPct, null); - - const claudePool = p.quotas.pools.find((x) => x.poolKey === 'Claude & GPT'); - assert.ok(claudePool); - assert.equal(claudePool.remainingPct, 40); - assert.equal(claudePool.weeklyRemainingPct, 80); - - assert.equal(formatCountdown(new Date(nowMs + 30_000).toISOString(), nowMs), '<1分钟后重置'); - assert.equal(formatCountdown('1969-12-31T23:59:59Z', nowMs), '未知重置时间'); - assert.equal(formatUsd(0.0004, { precise: true }), '<$0.001'); - assert.equal(formatUsd(12.34, { unpricedCalls: 1, compactPending: true }), '$12.34'); - assert.equal(speedReasonText('short_timing'), '耗时过短 (<0.5s)'); -}); - -test('BUG-17 & CANCEL-06: extractContextBreakdown classifies messagePrompts when children are empty and blocks post-compaction carryover', () => { - const ctx = extractContextBreakdown({ - chatStartMetadata: { - contextWindowMetadata: { - estimatedTokensUsed: 10000, - tokenBreakdown: { - groups: [ - { type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 2000 }, - { type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 8000, children: [] }, - ], - }, - }, - }, - messagePrompts: [ - { source: 'CHAT_MESSAGE_SOURCE_USER', prompt: 'hello world' }, - { source: 'CHAT_MESSAGE_SOURCE_MODEL', prompt: 'Assistant reply content here!' }, - ], - }); - assert.ok(ctx); - assert.equal(ctx.systemPromptTokens, 2000); - assert.ok(ctx.userInputTokens > 0); - assert.ok(ctx.assistantTokens > 0); - assert.equal(ctx.userInputTokens + ctx.assistantTokens, 8000); - - const stepsWithTrailingCheckpoint = extractModelSteps( - [ - { - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - sourceTrajectoryStepInfo: { stepIndex: 1 }, - createdAt: nowIso, - completedAt: doneIso, - modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '500' }, - }, - }, - { - type: 'CORTEX_STEP_TYPE_CHECKPOINT', - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - sourceTrajectoryStepInfo: { stepIndex: 2 }, - createdAt: nowIso, - completedAt: doneIso, - modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '1200' }, - }, - }, - ], - [ - { - stepIndices: [1], - chatModel: { - chatStartMetadata: { - contextWindowMetadata: { - estimatedTokensUsed: 180_000, - tokenBreakdown: { - groups: [{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 180_000 }], - }, - }, - }, - }, - }, - ] - ); - assert.equal(stepsWithTrailingCheckpoint.length, 2); - assert.equal(stepsWithTrailingCheckpoint[1].isCompactionStep, true); - assert.equal( - stepsWithTrailingCheckpoint[1].contextBreakdown, - null, - 'compaction checkpoint must not inherit pre-compaction 180k contextBreakdown' - ); -}); - -test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax safety, and IIFE bundle isolation', async () => { - const store = createReactiveStore({ a: 1, b: 2 }); - let calls = 0; - store.subscribe((s) => s.a + s.b, () => { - calls += 1; - }, { immediate: false }); - - store.setState({ a: 10 }); - store.setState({ b: 20 }); - await new Promise((r) => queueMicrotask(r)); - assert.equal(calls, 1, 'multiple setState calls in same microtask must batch into 1 subscriber flush'); - - const trickyModule = [ - "import './side-effect.js';", - "import { foo,\n bar } from './multi.js';", - 'const tpl = `\nimport { keepMe } from "tpl";\nexport const KEEP_ME = 42;\n`;', - 'export async function runTask() { return tpl; }', - 'export { runTask };', - ].join('\n'); - - const stripped = stripModuleSyntax(trickyModule); - assert.ok(stripped.includes('import { keepMe } from "tpl"')); - assert.ok(stripped.includes('export const KEEP_ME = 42')); - assert.equal(/^\s*import\s/m.test(stripped.replace(/`[\s\S]*?`/g, '')), false); - assert.doesNotThrow(() => new vm.Script(stripped)); - - const appBundle = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); - assert.ok(appBundle.startsWith('(() => {\n\'use strict\';')); - assert.ok(appBundle.trimEnd().endsWith('})();')); -}); - -test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => { - const convId = '4432b724-3e1e-4421-a375-c6855a7b7b37'; - - // Pre-compaction steps (matching real-world step 0..2: planner edit_file x2 + 2 completed tool results) - const rpcPreCompactionSteps = [ - { - type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - createdAt: '2026-11-11T02:18:21Z', - finishedGeneratingAt: '2026-11-11T02:18:35Z', - modelUsage: { - model: 'MODEL_PLACEHOLDER_M318', - inputTokens: '2918', - cacheReadTokens: '252465', - outputTokens: '814', - }, - }, - plannerResponse: { - toolCalls: [ - { name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/backend-harness.mjs' }) }, - { name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/04-post-fix-verify.mjs' }) }, - ], - }, - }, - { - type: 'CORTEX_STEP_TYPE_CODE_ACTION', - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:38Z' }, - }, - { - type: 'CORTEX_STEP_TYPE_CODE_ACTION', - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:40Z' }, - }, - ]; - - // transcript.jsonl still ends at step_index 2 (since CHECKPOINT only flushes to transcript.jsonl when DONE) - const transcriptPreFlush = [ - { - step_index: 0, - source: 'MODEL', - type: 'PLANNER_RESPONSE', - status: 'DONE', - created_at: '2026-11-11T02:18:21Z', - tool_calls: [ - { name: 'edit_file', args: { Path: '"f:\\\\repo\\\\backend-harness.mjs"' } }, - { name: 'edit_file', args: { Path: '"f:\\\\repo\\\\04-post-fix-verify.mjs"' } }, - ], - }, - { - step_index: 1, - source: 'MODEL', - type: 'GENERIC', - status: 'DONE', - created_at: '2026-11-11T02:18:35Z', - content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:38+09:00\nMade 1 replacement', - }, - { - step_index: 2, - source: 'MODEL', - type: 'GENERIC', - status: 'DONE', - created_at: '2026-11-11T02:18:35Z', - content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:40+09:00\nMade 1 replacement', - }, - ]; - - // Phase 1: In-progress CORTEX_STEP_TYPE_CHECKPOINT in RPC WITHOUT metadata.createdAt yet + trailing MEMENTO - const h = backendHarness({ - summaries: { - [convId]: { - stepCount: 4, - lastModifiedTime: '2026-11-11T02:18:35Z', - status: 'CASCADE_RUN_STATUS_RUNNING', - annotations: { title: 'Audit & Fix Session' }, - }, - }, - trajectories: { - [convId]: { - trajectory: { - steps: [ - ...rpcPreCompactionSteps, - { - type: 'CORTEX_STEP_TYPE_CHECKPOINT', - status: 'CORTEX_STEP_STATUS_RUNNING', - metadata: {}, - }, - { - type: 'CORTEX_STEP_TYPE_MEMENTO', - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { createdAt: '2026-11-11T02:18:40Z' }, - }, - ], - }, - }, - }, - transcripts: { - [convId]: transcriptPreFlush, - }, - }); - - const pCompacting = await h.buildTelemetryPayloadInternal(convId); - assert.equal(pCompacting.activeConversation.liveActivity.phase, 'compacting'); - assert.equal(pCompacting.activeConversation.liveActivity.label, '上下文压缩'); - assert.equal( - pCompacting.activeConversation.liveActivity.startedAtMs, - Date.parse('2026-11-11T02:18:40Z'), - 'uses previous tool completion timestamp when in-progress CHECKPOINT lacks createdAt' - ); - assert.equal(pCompacting.runningConversations[0].mainActivity.phase, 'compacting'); - assert.equal(pCompacting.runningConversations[0].mainActivity.label, '上下文压缩'); - - // Phase 2: CHECKPOINT finishes (status=DONE in both RPC & transcript.jsonl) while resuming before next PLANNER_RESPONSE - h.state.trajectories[convId] = { - trajectory: { - steps: [ - ...rpcPreCompactionSteps, - { - type: 'CORTEX_STEP_TYPE_CHECKPOINT', - status: 'CORTEX_STEP_STATUS_DONE', - metadata: { - createdAt: '2026-11-11T02:18:40Z', - finishedGeneratingAt: '2026-11-11T02:19:33Z', - modelUsage: { - model: 'MODEL_PLACEHOLDER_M318', - inputTokens: '3082', - cacheReadTokens: '254224', - outputTokens: '4627', - }, - }, - }, - ], - }, - }; - h.state.transcripts[convId] = [ - ...transcriptPreFlush, - { - step_index: 3, - source: 'SYSTEM', - type: 'CHECKPOINT', - status: 'DONE', - created_at: '2026-11-11T02:18:40Z', - content: '# Resuming from a compaction\n...', - }, - ]; - h.state.transcriptMtimeMs = 2; - - const pResuming = await h.buildTelemetryPayloadInternal(convId); - assert.equal(pResuming.activeConversation.liveActivity.phase, 'compacting'); - assert.equal(pResuming.activeConversation.liveActivity.label, '上下文压缩'); - assert.equal(pResuming.activeConversation.liveActivity.detail, '已完成压缩,正在恢复推理'); - assert.equal( - pResuming.activeConversation.liveActivity.startedAtMs, - Date.parse('2026-11-11T02:19:33Z') - ); - - // Phase 3: Even when RPC fails/cools down and ONLY transcript.jsonl (with status="DONE" CHECKPOINT) is available, - // it STILL detects compaction instead of regressing to pre-compaction "修改文件" - h.state.trajectories[convId] = new Error('temporary RPC timeout'); - const pTranscriptOnly = await h.buildTelemetryPayloadInternal(convId, true); - assert.equal(pTranscriptOnly.activeConversation.liveActivity.phase, 'compacting'); - assert.equal(pTranscriptOnly.activeConversation.liveActivity.label, '上下文压缩'); -}); diff --git a/sidecars/panel/test/backend-harness.mjs b/sidecars/panel/test/backend-harness.mjs index d0e883d..de33c29 100644 --- a/sidecars/panel/test/backend-harness.mjs +++ b/sidecars/panel/test/backend-harness.mjs @@ -4,7 +4,7 @@ import { pathToFileURL } from 'node:url'; import vm from 'node:vm'; import { randomUUID } from 'node:crypto'; import { isDeepStrictEqual } from 'node:util'; -import * as metrics from '../speed-metrics.mjs'; +import * as metrics from '../trajectory-metrics.mjs'; import { stripModuleSyntax } from '../scripts/build-bundle.mjs'; const REAL_CATALOG_RAW = JSON.parse( @@ -17,11 +17,17 @@ const DEFAULT_BUNDLED_CATALOG = { }; const BACKEND_MODULE_FILES = [ + '../shared/settings-normalization.mjs', + '../shared/telemetry-display-rules.mjs', + '../shared/window-bridge-protocol.mjs', '../backend/context-windows.mjs', '../backend/account-oauth.mjs', '../backend/account-switch.mjs', + '../backend/http-helpers.mjs', '../backend/settings-schema.mjs', '../backend/config.mjs', + '../backend/sqlite-client.mjs', + '../backend/proto-wire.mjs', '../backend/cli-sqlite-reader.mjs', '../backend/cli-statusline-config.mjs', '../backend/ls-discovery.mjs', @@ -33,6 +39,7 @@ const BACKEND_MODULE_FILES = [ '../backend/local-scanner.mjs', '../backend/usage-aggregator.mjs', '../backend/telemetry-builder.mjs', + '../backend/desktop-launcher-config.mjs', '../backend/window-bridge.mjs', '../backend/api-actions.mjs', '../main.mjs', @@ -63,19 +70,21 @@ export function backendHarness({ remoteCatalog=null, pluginManifest=null, hasGitDir=false, + gitConfigText=null, pluginRootPath=null, remoteFetch=null, execFileImpl=null, sourceText=null, clock=null, + timerApi={ setTimeout, clearTimeout }, metricsImplementation=metrics, }={}) { const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs'; const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs'; const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl); - const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1}; + const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1}; const ctx={ - ...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID, + ...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID, ...(clock ? { Date: class extends Date { constructor(...args) { super(...(args.length ? args : [clock()])); } static now() { return clock(); } @@ -101,7 +110,8 @@ export function backendHarness({ const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i); return Boolean(m && state.transcripts?.[m[1]]); } - if (norm.endsWith('/.git')) return Boolean(state.hasGitDir); + if (norm.endsWith('/.git')) return Boolean(state.hasGitDir || state.gitConfigText); + if (norm.endsWith('/.git/config')) return Boolean(state.gitConfigText); if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true; return false; }, @@ -138,6 +148,7 @@ export function backendHarness({ if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog); if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog); if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest); + if (norm.endsWith('/.git/config')) return String(state.gitConfigText || ''); return JSON.stringify(cache); }, writeFileSync:(p,s)=>{ @@ -152,6 +163,7 @@ export function backendHarness({ } }, writeTrajectoryCacheFile:(p,data)=>{ + if (state.cacheWriteError) throw state.cacheWriteError; state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))}); }, homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,delimiter:path.delimiter,pathToFileURL,fileURLToPath:()=>mainPath, @@ -176,6 +188,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,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx); + vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx); return {...ctx.api,state}; } diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index df10837..150bedb 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -666,7 +666,7 @@ test('cached incomplete timing is refreshed once without invalidating completed ...structuredClone(raw.trajectory.steps[0]), status: 'CORTEX_STEP_STATUS_CLEARED', }; - const { extractModelSteps } = await import('../speed-metrics.mjs'); + const { extractModelSteps } = await import('../trajectory-metrics.mjs'); const [completed] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata); const [incomplete] = extractModelSteps([{ ...incompleteStep, status: 'CORTEX_STEP_STATUS_GENERATING' }]); const cacheEntry = (step) => ({ @@ -743,6 +743,39 @@ test('display step revisions omit only matching rows and invalidate on timing ch assert.equal((await get()).activeConversation.recentSteps[0].tokPerSec, 60); }); +test('telemetry reuses display rows only for a matching revision', async (t) => { + const { fetchTelemetry, telemetryStore } = await import('../src/store/telemetryStore.js'); + const previousTelemetry = telemetryStore.getState().telemetry; + t.after(() => telemetryStore.setState({ telemetry: previousTelemetry })); + const recentSteps = [{ stepIndex: 1, tokPerSec: 20 }]; + const agentSteps = [{ stepIndex: 2, tokPerSec: 40 }]; + let response = { + stepRevision: 'test-revision', + activeConversation: { recentSteps, agents: [{ recentSteps: agentSteps }] }, + }; + const revisions = []; + t.mock.method(globalThis, 'fetch', async (url) => { + revisions.push(new URL(url, 'http://localhost').searchParams.get('stepRevision')); + return { ok: true, json: async () => structuredClone(response) }; + }); + + assert.equal((await fetchTelemetry()).stepRevision, 'test-revision'); + response = { + stepsUnchanged: true, + stepRevision: 'test-revision', + activeConversation: { agents: [{}] }, + }; + const refreshed = await fetchTelemetry(); + assert.equal(revisions[1], 'test-revision'); + assert.deepEqual(refreshed.activeConversation.recentSteps, recentSteps); + assert.deepEqual(refreshed.activeConversation.agents[0].recentSteps, agentSteps); + + const telemetryBeforeMismatch = telemetryStore.getState().telemetry; + response.stepRevision = 'unknown-revision'; + assert.equal(await fetchTelemetry(), null); + assert.equal(telemetryStore.getState().telemetry, telemetryBeforeMismatch); +}); + test('simultaneous ranges share the trajectory scan while keeping their own totals', async () => { const h = backendHarness({ trajectories: { live: raw }, @@ -759,7 +792,7 @@ test('simultaneous ranges share the trajectory scan while keeping their own tota }); test('cached usage follows rolling boundaries and reprices unchanged steps', async () => { - const { extractModelSteps } = await import('../speed-metrics.mjs'); + const { extractModelSteps } = await import('../trajectory-metrics.mjs'); const [step] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata); const modelKey = 'test-metered-model'; let now = Date.parse('2026-03-08T07:00:00Z'); @@ -806,7 +839,6 @@ test('cached usage follows rolling boundaries and reprices unchanged steps', asy test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => { const { computeLinearFit, - computeLoessFit, computePublicationFit, getStepModelGroupKey, toChronologicalSteps, @@ -840,7 +872,11 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd // Warmup cache curve stays clamped within [0, 100] const cacheSeries = [0, 90, 92, 93, 94, 95, 95]; - const loessCache = computeLoessFit(cacheSeries, { minVal: 0, maxVal: 100 }); + const loessCache = computePublicationFit( + cacheSeries.map((_, index) => index), + cacheSeries, + { minVal: 0, maxVal: 100 } + ).sampleFits; assert.equal(loessCache.length, cacheSeries.length); assert.ok( loessCache.every((v) => v >= 0 && v <= 100), @@ -956,6 +992,67 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd assert.equal(aggMb.length, 2); }); +test('saving preferences sends the same legacy values normalized by the backend', async (t) => { + const { saveSettingsPatch, stopAsyncTelemetryLoop, telemetryStore } = + await import('../src/store/telemetryStore.js'); + const h = backendHarness({ settings: { themeAccent: 'blue' } }); + let savedSettings = JSON.parse(JSON.stringify(h.loadSettings())); + const previousTelemetry = telemetryStore.getState().telemetry; + t.after(() => { + stopAsyncTelemetryLoop(); + telemetryStore.setState({ telemetry: previousTelemetry }); + }); + telemetryStore.setState({ telemetry: { settings: savedSettings } }); + + const patches = []; + let failSave = false; + t.mock.method(globalThis, 'fetch', async (path, options) => { + if (options.method === 'POST') { + assert.equal(path, '/api/settings'); + const patch = JSON.parse(options.body); + patches.push(patch); + for (const [key, value] of Object.entries(patch)) { + assert.deepEqual(telemetryStore.getState().telemetry.settings[key], value); + } + if (failSave) { + return { ok: false, json: async () => ({ error: 'Failed to persist settings' }) }; + } + const result = h.executeSettingsAction(patch); + savedSettings = JSON.parse(result.body); + return { ok: result.ok, json: async () => savedSettings }; + } + assert.match(path, /^\/api\/telemetry\?/); + return { ok: true, json: async () => ({ settings: savedSettings }) }; + }); + + await saveSettingsPatch({ + windowMountMode: 'sidebar_only', + topbarCapsuleSlots: ['step_cost', 'cost', 'none'], + overviewMetrics: ['cost', 'tps'], + weeklyLimitMode: 'tokens', + }); + assert.deepEqual(patches[0], { + windowMountMode: 'sidebar', + enableWindowOverlay: false, + topbarCapsuleSlots: ['cost'], + overviewMetrics: ['step_cost', 'tps'], + weeklyLimitMode: 'custom_tokens', + }); + assert.deepEqual(telemetryStore.getState().telemetry.settings, savedSettings); + assert.equal(savedSettings.themeAccent, 'blue'); + + await saveSettingsPatch({ topbarCapsuleSlots: [], weeklyLimitMode: 'cost' }); + assert.deepEqual(patches[1], { + topbarCapsuleSlots: ['context'], + weeklyLimitMode: 'custom_cost', + }); + + const telemetryBeforeFailure = telemetryStore.getState().telemetry; + failSave = true; + await assert.rejects(saveSettingsPatch({ windowMountMode: 'composer' }), /Failed to persist/); + assert.equal(telemetryStore.getState().telemetry, telemetryBeforeFailure); +}); + test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => { // 1. Default schema matches pre-refactor out-of-box UI 100% const hDefault = backendHarness({}); diff --git a/sidecars/panel/test/cloud-sync-and-update.test.mjs b/sidecars/panel/test/cloud-sync-and-update.test.mjs index 1e44fdc..113270e 100644 --- a/sidecars/panel/test/cloud-sync-and-update.test.mjs +++ b/sidecars/panel/test/cloud-sync-and-update.test.mjs @@ -35,7 +35,23 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs latestPluginVersion: '1.5.0', downloadUrl: 'https://evil.example.com/malware.zip', pricing: { - 'gemini-4.5-ultra': { input: 3.5, cache: 0.35, output: 15.0, short: 'ultra-4.5', family: 'Gemini' }, + 'gemini-4.5-ultra': { + input: 3.5, + cache: 0.35, + output: 15.0, + short: 'ultra-4.5', + family: 'Gemini', + phases: [ + { until: '2026-12-01T00:00:00Z', input: 1.75, cache: 0.175, output: 7.5 }, + { from: '2026-12-01T00:00:00Z', input: 3.5, cache: 0.35, output: 15.0 }, + { until: 'not-a-date', input: 1.0, cache: 0.1, output: 5.0 }, + { from: '2026-12-10T00:00:00Z', until: '2026-12-01T00:00:00Z', input: 1.0, cache: 0.1, output: 5.0 }, + { input: 1.0, cache: 0.1, output: 5.0 }, + { until: '2026-12-01T00:00:00Z', input: -1, cache: 0.1, output: 5.0 }, + { until: '2026-12-01T00:00:00Z', input: 0, cache: 0, output: 0 }, + { until: '2026-12-01T00:00:00Z', input: '1.0', cache: 0.1, output: 5.0 }, + ], + }, 'broken-negative': { input: -1, cache: 0.1, output: 5, short: 'bad', family: 'Gemini' }, 'broken-nan': { input: 'NaN', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' }, 'broken-null': { input: null, cache: null, output: null, short: 'bad', family: 'Gemini' }, @@ -54,9 +70,165 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs assert.equal(sanitized.latestPluginVersion, '1.5.0'); assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan-dev/')); assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']); + assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases.length, 2); + assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases[0].input, 1.75); + assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases[1].input, 3.5); assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']); }); +test('time-phased promotional pricing resolves exact rates across Carbon/Argon (Dec 1) and 3.6-3.8 Flash (Jan 1) boundaries while preserving historical costs and flat models', async () => { + let now = Date.parse('2026-11-30T23:59:59.000Z'); + const makeTimedStep = (idx, model, isoStart, inTok = 1_000_000, cacheTok = 1_000_000, outTok = 1_000_000) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: isoStart, + completedAt: new Date(Date.parse(isoStart) + 1_000).toISOString(), + modelUsage: { + model, + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: String(inTok), + cacheReadTokens: String(cacheTok), + outputTokens: String(outTok), + }, + }, + }); + + const steps = [ + // Step 1: Carbon High right before Nov 30 cutoff -> $2.0 + $0.1 + $10.0 = $12.10 (saved: $1.90) + makeTimedStep(1, 'MODEL_PLACEHOLDER_M429', '2026-11-30T23:59:59.999Z'), + // Step 2: Carbon High at exact Dec 1 cutoff -> $4.0 + $0.2 + $20.0 = $24.20 (saved: $3.80) + makeTimedStep(2, 'MODEL_PLACEHOLDER_M429', '2026-12-01T00:00:00.000Z'), + // Step 3: Orchestrator (Argon) in Nov promo -> $2.0 + $0.1 + $10.0 = $12.10 + makeTimedStep(3, 'MODEL_PLACEHOLDER_M681', '2026-11-20T10:00:00.000Z'), + // Step 4: Orchestrator (Argon) in Dec standard -> $4.0 + $0.2 + $20.0 = $24.20 + makeTimedStep(4, 'MODEL_PLACEHOLDER_M681', '2026-12-05T10:00:00.000Z'), + // Step 5: Gemini 3.8 Flash (High) in Dec (still promo!) -> $0.75 + $0.075 + $3.75 = $4.575 + makeTimedStep(5, 'MODEL_PLACEHOLDER_M318', '2026-12-31T23:59:59.999Z'), + // Step 6: Gemini 3.8 Flash (High) on Jan 1, 2027 (standard!) -> $1.50 + $0.15 + $7.50 = $9.15 + makeTimedStep(6, 'MODEL_PLACEHOLDER_M318', '2027-01-01T00:00:00.000Z'), + // Step 7: Gemini 3.8 Flash (Low) in Jan 2027 (flat, no doubling!) -> $0.30 + $0.03 + $2.50 = $2.83 + makeTimedStep(7, 'MODEL_PLACEHOLDER_M320', '2027-01-15T00:00:00.000Z'), + // Step 8: Gemini 3.5 Flash in Nov 2026 (no half-price promo!) -> $1.50 + $0.15 + $9.00 = $10.65 + makeTimedStep(8, 'MODEL_PLACEHOLDER_M149', '2026-11-17T00:00:00.000Z'), + // Step 9: Gemini 3.6 Flash in Jan 2027 -> $1.50 + $0.15 + $7.50 = $9.15 + makeTimedStep(9, 'MODEL_PLACEHOLDER_M71', '2027-01-02T00:00:00.000Z'), + // Step 10: Gemini 3.7 Flash in Nov 2026 -> $0.75 + $0.075 + $3.75 = $4.575 + makeTimedStep(10, 'MODEL_PLACEHOLDER_M298', '2026-11-17T00:00:00.000Z'), + ]; + + // Advance clock to 2027-01-20: historical Nov & Dec steps must NOT be overwritten with 2027 rates! + now = Date.parse('2027-01-20T12:00:00Z'); + const h = backendHarness({ + clock: () => now, + summaries: { convPhase: { stepCount: steps.length, lastModifiedTime: '2027-01-15T00:00:01Z' } }, + trajectories: { convPhase: { trajectory: { steps } } }, + }); + + // Direct resolveModelInfo without timestamp uses current clock (2027-01-20 -> post-promo for all phased models) + assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M429').pricing.input, 4.0); + assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M417').pricing.output, 20.0); + assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M318').pricing.input, 1.5); + assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M318').pricing.output, 7.5); + // Explicit historical timestamp still resolves promo pricing + assert.equal( + h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), '', '', '', '2026-11-17T00:00:00Z').pricing.input, + 2.0 + ); + assert.equal( + h.resolveModelInfo('MODEL_PLACEHOLDER_M318', new Map(), '', '', '', '2026-12-15T00:00:00Z').pricing.input, + 0.75 + ); + + // computeStepCost honors step timestamp even when passed post-promo pricing object + const postPromoCarbonPricing = h.resolveModelInfo('MODEL_PLACEHOLDER_M429').pricing; + assert.equal( + h.computeStepCost( + { createdAtMs: Date.parse('2026-11-15T00:00:00Z'), inputTokens: 1_000_000, cacheReadTokens: 0, outputTokens: 0 }, + postPromoCarbonPricing + ), + 2.0 + ); + assert.equal( + h.computeStepCost( + { createdAtMs: Date.parse('2026-12-15T00:00:00Z'), inputTokens: 1_000_000, cacheReadTokens: 0, outputTokens: 0 }, + postPromoCarbonPricing + ), + 4.0 + ); + + const p = await h.buildTelemetryPayloadInternal('convPhase'); + const byIdx = new Map(p.activeConversation.recentSteps.map((s) => [s.stepIndex, s])); + + assert.equal(byIdx.get(1).costUsd, 12.1); + assert.equal(byIdx.get(1).inCostUsd, 2.0); + assert.equal(byIdx.get(1).cacheCostUsd, 0.1); + assert.equal(byIdx.get(1).outCostUsd, 10.0); + + assert.equal(byIdx.get(2).costUsd, 24.2); + assert.equal(byIdx.get(2).inCostUsd, 4.0); + assert.equal(byIdx.get(2).cacheCostUsd, 0.2); + assert.equal(byIdx.get(2).outCostUsd, 20.0); + + assert.equal(byIdx.get(3).costUsd, 12.1); + assert.equal(byIdx.get(4).costUsd, 24.2); + assert.equal(byIdx.get(5).costUsd, 4.575); + assert.equal(byIdx.get(6).costUsd, 9.15); + assert.equal(byIdx.get(7).costUsd, 2.83); + assert.equal(byIdx.get(8).costUsd, 10.65); + assert.equal(byIdx.get(9).costUsd, 9.15); + assert.equal(byIdx.get(10).costUsd, 4.575); + + // Total across all 10 steps = 12.1 + 24.2 + 12.1 + 24.2 + 4.575 + 9.15 + 2.83 + 10.65 + 9.15 + 4.575 = 113.53 + assert.equal(p.activeConversation.sessionCostUsd, 113.53); + assert.equal(p.consumption.account.costUsd, 113.53); + + // Verify getPricingPhaseEpoch advances across boundaries (0 -> 1 -> 2) and invalidates cached snapshots for timestamp-less steps + assert.equal(h.getPricingPhaseEpoch(Date.parse('2026-11-30T23:59:59Z')), 0); + assert.equal(h.getPricingPhaseEpoch(Date.parse('2026-12-15T00:00:00Z')), 1); + assert.equal(h.getPricingPhaseEpoch(Date.parse('2027-01-01T00:00:00Z')), 2); + + let dynamicClock = Date.parse('2026-11-30T23:59:59Z'); + const hBoundary = backendHarness({ + clock: () => dynamicClock, + summaries: { cZeroTs: { stepCount: 1 } }, + cache: { + cZeroTs: { + signature: 'v10-model-identity:disk:0', + contextLimitTelemetry: true, + turnRailTelemetry: true, + contextGroupsTelemetry: true, + speedClearedTelemetry: true, + subagentRefs: [], + steps: [ + { + stepIndex: 1, + createdAtMs: 0, + modelKey: 'MODEL_PLACEHOLDER_M429', + modelIdentityVersion: 1, + modelSource: 'usage.model', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: 1_000_000, + cacheReadTokens: 0, + outputTokens: 0, + thinkingTokens: 0, + responseTokens: 0, + }, + ], + }, + }, + }); + const beforeCutoff = await hBoundary.buildTelemetryPayloadInternal('cZeroTs'); + assert.equal(beforeCutoff.activeConversation.latestStepCostUsd, 2.0); + assert.equal(beforeCutoff.consumption.account.costUsd, 2.0); + + dynamicClock = Date.parse('2026-12-01T00:00:01Z'); + const afterCutoff = await hBoundary.buildTelemetryPayloadInternal('cZeroTs'); + assert.equal(afterCutoff.activeConversation.latestStepCostUsd, 4.0); + assert.equal(afterCutoff.consumption.account.costUsd, 4.0); +}); + test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newly pushed models', async () => { const step = makeStep(1, 'MODEL_PLACEHOLDER_M888'); let fetchedUrl = ''; @@ -425,3 +597,58 @@ test('pluginUpdateMode supports manual (default), auto, and off with legacy auto await new Promise((r) => setTimeout(r, 20)); assert.equal(gitTriggered, true, 'pluginUpdateMode=auto triggers background update check'); }); + +test('argon-b / argon-trial deployment shards resolve phased pricing without wildcarding unknown single-letter suffixes, and custom Git forks suppress upstream update badges', async () => { + const hPromo = backendHarness({ clock: () => Date.parse('2026-11-20T00:00:00Z') }); + for (const shardSlug of ['gemini-4-argon-b', 'gemini-4-argon-trial']) { + const promoInfo = hPromo.resolveModelInfo(shardSlug); + assert.equal(promoInfo.label, 'Gemini 4 Argon'); + assert.equal(promoInfo.shortName, 'argon-4'); + assert.equal(promoInfo.pricing.input, 2.0); + assert.equal(promoInfo.pricing.output, 10.0); + + const postInfo = hPromo.resolveModelInfo(shardSlug, new Map(), '', '', '', '2026-12-05T00:00:00Z'); + assert.equal(postInfo.pricing.input, 4.0); + assert.equal(postInfo.pricing.output, 20.0); + } + + // Unverified single-letter shard must NOT recklessly fall back to base model pricing + const unknownShard = hPromo.resolveModelInfo('gemini-4-argon-z'); + assert.equal(unknownShard.pricing, null); + + // Custom Git fork: upstream cloud catalog sync updates model pricing, while suppressing upstream version badge + const forkH = backendHarness({ + hasGitDir: true, + gitConfigText: '[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n\turl = https://github.com/custom-contributor/antigravity-usage-monitor.git\n', + pluginManifest: { name: 'usage-monitor', version: '1.5.0' }, + remoteFetch: async () => ({ + ok: true, + json: async () => ({ + schemaVersion: 1, + catalogVersion: '2026.12.10.1', + updatedAt: '2026-12-10T10:00:00Z', + latestPluginVersion: '1.9.0', + pricing: { + 'gemini-5-experimental': { + input: 6.0, + cache: 0.3, + output: 30.0, + short: 'gem-5-exp', + family: 'Gemini', + }, + }, + }), + }), + }); + + assert.equal(forkH.detectCustomGitForkRepo(), 'custom-contributor/antigravity-usage-monitor'); + const statusAfterSync = await forkH.syncCloudCatalog({ force: true }); + assert.equal(statusAfterSync.catalogVersion, '2026.12.10.1'); + assert.equal(statusAfterSync.updateAvailable, false, 'custom fork must not show false update badge from upstream repo'); + assert.equal(statusAfterSync.latestPluginVersion, '1.5.0'); + assert.equal( + statusAfterSync.releaseUrl, + 'https://github.com/custom-contributor/antigravity-usage-monitor/releases/latest' + ); + assert.equal(forkH.resolveModelInfo('gemini-5-experimental').pricing.input, 6.0); +}); diff --git a/sidecars/panel/test/context-windows.test.mjs b/sidecars/panel/test/context-windows.test.mjs index e99a060..01320cc 100644 --- a/sidecars/panel/test/context-windows.test.mjs +++ b/sidecars/panel/test/context-windows.test.mjs @@ -46,9 +46,11 @@ test('saves and restores one model at a time using host presets or verified mode assert.equal(carbonModel.id, carbonGroup); assert.equal(carbonModel.label, 'Gemini 4 Carbon'); assert.deepEqual(carbonModel.members, [carbon, carbonLow]); - assert.equal(carbonModel.options.at(-1).tokens, 636000); + assert.deepEqual(carbonModel.options.map(({ tokens }) => tokens), [128000, 256000, 384000, 512000, 636000]); assert.equal((await update({ modelId: carbonGroup, option: '768000' })).status, 400); h.state.settings.modelContextWindows = { [carbon]: '768000', [carbonLow]: '256000' }; + assert.equal((await update({ modelId: carbonGroup, option: '384000' })).status, 200); + assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '384000' }); assert.equal((await update({ modelId: carbonGroup, option: '512000' })).status, 200); assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '512000' }); assert.equal((await update({ modelId: carbonGroup, option: null })).status, 200); @@ -208,3 +210,97 @@ test('host requests apply a rule only to the exact model across App and IDE tran assert.equal(window.fetch, nativeFetch); assert.equal(WebSocket.prototype.send, nativeSend); }); + +test('Issue #27: syncHostContextWindows falls back to backend pre-resolved rules without __APP_CONFIG__.csrfToken and intercepts StartCascade + Uint8Array / connect+json frames', async () => { + const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage'; + const startPath = '/exa.language_server_pb.LanguageServerService/StartCascade'; + const host = 'https://127.0.0.1:26190'; + const nativeFetch = async (_url, init) => init; + class WebSocket { + constructor(url) { + this.url = url; + } + send(data) { + return data; + } + } + const window = { + location: new URL(host), + fetch: nativeFetch, + WebSocket, + __APP_CONFIG__: {}, // Simulate 2.33.0+ environment without exposed csrfToken on window + }; + const context = vm.createContext({ + window, + URL, + TextEncoder, + TextDecoder, + Headers, + Uint8Array, + AbortSignal, + setTimeout, + clearTimeout, + }); + + const prefs = { [carbonGroup]: '256000' }; + const fallbackRules = { [carbon]: 256000, [carbonLow]: 256000 }; + const syncResult = await vm.runInContext( + createContextWindowSyncExpression(prefs, 'boot-233', fallbackRules), + context + ); + assert.deepEqual({ ...syncResult }, { attached: true, ruleCount: 2 }); + + try { + // 1. StartCascade on new conversation creation with Uint8Array JSON body + const startPayload = { + cascadeConfig: { + plannerConfig: { planModel: carbon }, + checkpointConfig: { maxTokenLimit: 512000 }, + }, + }; + const uint8Body = new TextEncoder().encode(JSON.stringify(startPayload)); + const startOut = await window.fetch(new URL(host + startPath), { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: uint8Body, + }); + assert.equal(startOut.body instanceof Uint8Array, true); + assert.equal( + JSON.parse(new TextDecoder().decode(startOut.body)).cascadeConfig.checkpointConfig + .maxTokenLimit, + 256000 + ); + + // 2. application/connect+json 5-byte envelope on SendUserCascadeMessage + const msgBytes = Buffer.from(JSON.stringify(startPayload), 'utf8'); + const connectFrame = new Uint8Array(5 + msgBytes.length); + new DataView(connectFrame.buffer).setUint32(1, msgBytes.length); + connectFrame.set(msgBytes, 5); + const framedOut = await window.fetch(host + sendPath, { + method: 'POST', + headers: { 'Content-Type': 'application/connect+json' }, + body: connectFrame, + }); + const decodedJson = JSON.parse( + new TextDecoder().decode(framedOut.body.subarray(5)) + ); + assert.equal(decodedJson.cascadeConfig.checkpointConfig.maxTokenLimit, 256000); + + // 3. WebSocket StartCascade frame + const ws = new WebSocket('wss://127.0.0.1:26190/connect-websocket'); + const wsFrame = JSON.parse( + ws.send( + JSON.stringify({ + type: 'start', + stream: false, + procedure: startPath, + payload: startPayload, + }) + ) + ); + assert.equal(wsFrame.payload.cascadeConfig.checkpointConfig.maxTokenLimit, 256000); + } finally { + await vm.runInContext(createContextWindowSyncExpression({}, 'boot-233', {}), context); + } + assert.equal(window.fetch, nativeFetch); +}); diff --git a/sidecars/panel/test/cross-module-regressions.test.mjs b/sidecars/panel/test/cross-module-regressions.test.mjs new file mode 100644 index 0000000..c51ff92 --- /dev/null +++ b/sidecars/panel/test/cross-module-regressions.test.mjs @@ -0,0 +1,1378 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import vm from 'node:vm'; +import { backendHarness } from './backend-harness.mjs'; +import { + extractContextBreakdown, + extractLiveActivity, + extractModelSteps, + normalizeCachedStep, +} from '../trajectory-metrics.mjs'; +import { + formatCountdown, + formatUsd, + speedReasonText, +} from '../src/core/formatters.js'; +import { createReactiveStore } from '../src/core/reactive.js'; +import { buildBundle, stripModuleSyntax } from '../scripts/build-bundle.mjs'; + +const nowMs = Date.now(); +const nowIso = new Date(nowMs - 5_000).toISOString(); +const doneIso = new Date(nowMs - 3_000).toISOString(); +const promoMs = Date.parse('2026-11-17T12:00:00Z'); +const promoNowIso = new Date(promoMs - 5_000).toISOString(); +const promoDoneIso = new Date(promoMs - 3_000).toISOString(); + +test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as Gemini, and M429/M322/M149/M20 resolve accurately', () => { + const h = backendHarness({ + clock: () => promoMs, + userStatus: { + cascadeModelConfigData: { + clientModelConfigs: [ + { + modelOrAlias: { model: 'MODEL_CLAUDE_PROXY' }, + label: 'Claude Opus 4.6 (Google Vertex)', + quotaInfo: { remainingFraction: 0.75, resetTime: new Date(nowMs + 3600_000).toISOString() }, + }, + ], + }, + }, + }); + + const infoClaude = h.resolveModelInfo('claude-opus-4-6', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(infoClaude.family, 'Claude'); + const infoO3 = h.resolveModelInfo('o3-mini', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(infoO3.family, 'GPT'); + + // Calling resolveModelInfo with omitted dynamicModelMap must not throw (BUG-03) + const infoDefaultMap = h.resolveModelInfo('MODEL_PLACEHOLDER_M320'); + assert.equal(infoDefaultMap.modelId, 'gemini-3.8-flash-low'); + assert.equal(infoDefaultMap.pricing?.input, 0.3); + + const m429 = h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m429.modelId, 'gemini-4-carbon-high'); + assert.equal(m429.shortName, 'carbon-4-high'); + + const m322 = h.resolveModelInfo('MODEL_PLACEHOLDER_M322', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m322.modelId, 'gemini-3.8-flash-tiered'); + assert.equal( + h.computeStepCost( + { + modelKey: 'MODEL_PLACEHOLDER_M322', + inputTokens: 1_000_000, + cacheReadTokens: 0, + outputTokens: 0, + }, + m322.pricing + ), + 0.75 + ); + + const m149 = h.resolveModelInfo('MODEL_PLACEHOLDER_M149', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m149.modelId, 'gemini-3.5-flash-high'); + + const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI'); + assert.equal(m20.modelId, 'gemini-3.5-flash'); + + // Gemini Hydrogen ($1.50/$0.075/$7.50) & Helix ($0.30/$0.015/$2.50), shared Gemini pool + const dynHydrogenMap = new Map([ + ['MODEL_PLACEHOLDER_M480', { modelId: '', label: 'Gemini 4 Hydrogen (High)' }], + ['MODEL_PLACEHOLDER_M481', { modelId: '', label: 'Gemini 4 Hydrogen (Low)' }], + ['MODEL_PLACEHOLDER_M482', { modelId: '', label: 'Gemini 4 Helix' }], + ]); + const hydroHigh = h.resolveModelInfo('MODEL_PLACEHOLDER_M480', dynHydrogenMap); + assert.equal(hydroHigh.family, 'Gemini'); + assert.equal(hydroHigh.shortName, 'hydrogen-4-high'); + assert.deepEqual( + { i: hydroHigh.pricing?.input, c: hydroHigh.pricing?.cache, o: hydroHigh.pricing?.output }, + { i: 1.5, c: 0.075, o: 7.5 } + ); + const hydroLow = h.resolveModelInfo('MODEL_PLACEHOLDER_M481', dynHydrogenMap); + assert.equal(hydroLow.shortName, 'hydrogen-4-low'); + assert.deepEqual( + { i: hydroLow.pricing?.input, c: hydroLow.pricing?.cache, o: hydroLow.pricing?.output }, + { i: 1.5, c: 0.075, o: 7.5 } + ); + const hydroCodename = h.resolveModelInfo('gemini-hydrogen'); + assert.equal(hydroCodename.family, 'Gemini'); + assert.equal(hydroCodename.label, 'Gemini Hydrogen'); + assert.equal(hydroCodename.pricing?.input, 1.5); + assert.equal(hydroCodename.pricing?.output, 7.5); + + const helixInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M482', dynHydrogenMap); + assert.equal(helixInfo.family, 'Gemini'); + assert.equal(helixInfo.shortName, 'helix-4'); + assert.deepEqual( + { i: helixInfo.pricing?.input, c: helixInfo.pricing?.cache, o: helixInfo.pricing?.output }, + { i: 0.3, c: 0.015, o: 2.5 } + ); + const helixCodename = h.resolveModelInfo('gemini-helix'); + assert.equal(helixCodename.family, 'Gemini'); + assert.equal(helixCodename.label, 'Gemini Helix'); + assert.equal(helixCodename.pricing?.output, 2.5); + + const { quotaPoolsMap } = h.buildOfficialQuotaPools(null, [ + { + modelOrAlias: { model: 'MODEL_PLACEHOLDER_M480' }, + label: 'Gemini 4 Hydrogen (High)', + quotaInfo: { remainingFraction: 0.8, resetTime: new Date(nowMs + 3600_000).toISOString() }, + }, + { + modelOrAlias: { model: 'MODEL_PLACEHOLDER_M482' }, + label: 'Gemini 4 Helix', + quotaInfo: { remainingFraction: 0.8, resetTime: new Date(nowMs + 3600_000).toISOString() }, + }, + ]); + assert.equal(quotaPoolsMap.has('Hydrogen'), false, 'Hydrogen has no dedicated quota pool'); + assert.equal(quotaPoolsMap.has('Helix'), false, 'Helix has no dedicated quota pool'); + assert.equal(quotaPoolsMap.get('Gemini')?.isAvailable, true); +}); + +test('BUG-02 & BUG-11: ide: external sessions do not double-count live conversations, only quota pools isolate cross-account entries, and orphan subagents never leak to top-level list', async () => { + const reset5hIso = new Date(Date.now() + 4 * 3600_000).toISOString(); + const resetWkIso = new Date(Date.now() + 6 * 24 * 3600_000).toISOString(); + const stepObj = { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '10000', + cacheReadTokens: '20000', + outputTokens: '5000', + }, + }, + }; + const h = backendHarness({ + userStatus: { email: 'alice@example.com' }, + quotaSummary: { + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: 0.9, resetTime: reset5hIso }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: 0.95, resetTime: resetWkIso }, + ], + }, + ], + }, + deepStats: { + accountName: 'alice@example.com', + perConvo: { + // Same conversation ID as live 'abcd-1234' (case-insensitive, prefixed with 'ide:') -> must deduplicate! + 'ide:AbCd-1234': { + accountName: 'alice@example.com', + appSource: 'ide', + entries: [ + { ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, + { ts: doneIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 }, + ], + }, + // Different account -> retained in global consumption, isolated out of Alice's quota pools! + 'ide:bob-conv': { + accountName: 'bob@example.com', + appSource: 'ide', + entries: [ + { ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 99000, cache: 0, out: 1000, reasoning: 0 }, + ], + }, + }, + }, + cache: { + 'orphan-sub': { + accountName: 'bob@example.com', + isSubagent: true, + parentCascadeId: 'deleted-parent', + signature: 'v10-model-identity:sub', + steps: extractModelSteps([stepObj]), + }, + }, + summaries: { + 'abcd-1234': { stepCount: 1, lastModifiedTime: doneIso, status: 'IDLE' }, + }, + trajectories: { + 'abcd-1234': { trajectory: { steps: [stepObj] } }, + }, + }); + + const p = await h.buildTelemetryPayloadInternal('abcd-1234', false, { range: 'all' }); + // ide:AbCd-1234 (70k) deduplicates live abcd-1234 (35k); global consumption retains ide:bob-conv (100k) + orphan-sub (35k) + assert.equal(p.consumption.account.conversationsCount, 3); + assert.equal(p.consumption.account.calls, 4); + assert.equal(p.consumption.account.totalTokens, 205_000); + // Quota pools & weekly cycle strictly isolate to alice@example.com (2 calls = 70,000 tokens) + const geminiPool = p.quotas.pools.find((pool) => pool.poolKey === 'Gemini'); + assert.equal(geminiPool.cycle5h.calls, 2); + assert.equal(geminiPool.cycle5h.tokens, 70_000); + assert.equal(geminiPool.cycleWeekly.calls, 2); + assert.equal(geminiPool.cycleWeekly.tokens, 70_000); + assert.equal(p.quotas.weekly.calls, 2); + assert.equal(p.quotas.weekly.tokens, 70_000); + assert.equal( + p.conversations.some((c) => c.cascadeId === 'orphan-sub'), + false, + 'orphan subagent must not appear in top-level conversation dropdown' + ); +}); + +test('account switch preserves conversation list, locked session steps, and consumption history while isolating quota pools per step across mid-conversation switches', async () => { + const baseMs = Date.now() - 60_000; + const reset5hIso = new Date(baseMs + 4 * 3600_000).toISOString(); + const resetWkIso = new Date(baseMs + 6 * 24 * 3600_000).toISOString(); + const makeStepAt = (idx, inTok, outTok, offsetMs) => ({ + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx }, + createdAt: new Date(baseMs + offsetMs).toISOString(), + completedAt: new Date(baseMs + offsetMs + 1000).toISOString(), + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: String(inTok), + cacheReadTokens: '0', + outputTokens: String(outTok), + }, + }, + }); + const makeQuota = (rem5h, remWk) => ({ + groups: [ + { + displayName: 'Gemini Models', + buckets: [ + { bucketId: 'gemini-5h', window: '5h', remainingFraction: rem5h, resetTime: reset5hIso }, + { bucketId: 'gemini-weekly', window: 'weekly', remainingFraction: remWk, resetTime: resetWkIso }, + ], + }, + ], + }); + + const sharedStep1 = makeStepAt(1, 25_000, 5_000, 1_000); // 30,000 + const sharedStep2 = makeStepAt(2, 25_000, 5_000, 3_000); // 30,000 + const aliceOldStep = makeStepAt(1, 35_000, 5_000, 5_000); // 40,000 + + const h = backendHarness({ + userStatus: { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } }, + quotaSummary: makeQuota(0.8, 0.9), + summaries: { + 'conv-shared': { + stepCount: 2, + lastModifiedTime: new Date(baseMs + 4_000).toISOString(), + status: 'IDLE', + annotations: { title: 'Greeting and Hello' }, + }, + 'conv-alice-old': { + stepCount: 1, + lastModifiedTime: new Date(baseMs + 6_000).toISOString(), + status: 'IDLE', + annotations: { title: 'Earlier Alice Session' }, + }, + }, + trajectories: { + 'conv-shared': { trajectory: { steps: [sharedStep1, sharedStep2] } }, + 'conv-alice-old': { trajectory: { steps: [aliceOldStep] } }, + }, + }); + + // 1. Initial state under Alice: 3 calls = 100,000 tokens in both consumption and Alice's quota pools + const pAlice = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pAlice.conversations.length, 2); + assert.equal(pAlice.activeConversation.cascadeId, 'conv-shared'); + assert.equal(pAlice.activeConversation.stepCount, 2); + assert.equal(pAlice.consumption.account.calls, 3); + assert.equal(pAlice.consumption.account.totalTokens, 100_000); + assert.equal(pAlice.quotas.weekly.calls, 3); + assert.equal(pAlice.quotas.weekly.tokens, 100_000); + + // 2. Switch to Bob and create 1 new step (15,900 tokens) in conv-bob while keeping conv-shared locked + const bobStep1 = makeStepAt(1, 15_552, 348, 10_000); // 15,900 + h.state.userStatus = { email: 'bob@example.com', userTier: { name: 'Google AI Ultra' } }; + h.state.quotaSummary = makeQuota(0.977, 0.994); + h.state.summaries['conv-bob'] = { + stepCount: 1, + lastModifiedTime: new Date(baseMs + 11_000).toISOString(), + status: 'IDLE', + annotations: { title: 'New Bob Session' }, + }; + h.state.trajectories['conv-bob'] = { trajectory: { steps: [bobStep1] } }; + + const pBob = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pBob.conversations.length, 3, 'All historical conversations remain visible after account switch'); + assert.equal(pBob.activeConversation.cascadeId, 'conv-shared', 'Locked conversation stays selected'); + assert.equal(pBob.activeConversation.stepCount, 2, 'Step details of locked conversation are preserved'); + assert.equal(pBob.consumption.account.calls, 4, 'Global consumption retains all 4 calls across accounts'); + assert.equal(pBob.consumption.account.totalTokens, 115_900); + const bobGemini = pBob.quotas.pools.find((pool) => pool.poolKey === 'Gemini'); + assert.equal(bobGemini.cycle5h.calls, 1, 'Quota 5h isolates strictly to Bob'); + assert.equal(bobGemini.cycle5h.tokens, 15_900); + assert.equal(bobGemini.cycleWeekly.tokens, 15_900); + assert.equal(pBob.quotas.weekly.calls, 1); + assert.equal(pBob.quotas.weekly.tokens, 15_900); + + // 3. Continue chatting inside conv-shared while logged in as Bob (step #3 = 25,000 tokens) + const sharedStep3ByBob = makeStepAt(3, 24_000, 1_000, 20_000); // 25,000 + h.state.summaries['conv-shared'] = { + ...h.state.summaries['conv-shared'], + stepCount: 3, + lastModifiedTime: new Date(baseMs + 21_000).toISOString(), + }; + h.state.trajectories['conv-shared'] = { + trajectory: { steps: [sharedStep1, sharedStep2, sharedStep3ByBob] }, + }; + + const pBobContinued = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pBobContinued.activeConversation.stepCount, 3); + assert.equal(pBobContinued.consumption.account.calls, 5); + assert.equal(pBobContinued.consumption.account.totalTokens, 140_900); + const bobGeminiAfter = pBobContinued.quotas.pools.find((pool) => pool.poolKey === 'Gemini'); + assert.equal(bobGeminiAfter.cycle5h.calls, 2, 'Bob quota includes conv-bob + his new step #3 in conv-shared'); + assert.equal(bobGeminiAfter.cycle5h.tokens, 40_900); + assert.equal(pBobContinued.quotas.weekly.calls, 2); + assert.equal(pBobContinued.quotas.weekly.tokens, 40_900); + + // 4. Switch back to Alice -> Alice quota remains strictly her 3 calls (100,000 tokens) + h.state.userStatus = { email: 'alice@example.com', userTier: { name: 'Google AI Ultra' } }; + h.state.quotaSummary = makeQuota(0.8, 0.9); + const pAliceBack = await h.buildTelemetryPayloadInternal('conv-shared', false, { range: 'all' }); + assert.equal(pAliceBack.consumption.account.calls, 5); + assert.equal(pAliceBack.consumption.account.totalTokens, 140_900); + assert.equal(pAliceBack.quotas.weekly.calls, 3); + assert.equal(pAliceBack.quotas.weekly.tokens, 100_000); +}); + +test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd rounding, and dynamicModelMap default', async () => { + const badStep = { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '-5000', + cacheReadTokens: 'NaN', + outputTokens: '1000', + thinkingOutputTokens: '2500', + }, + }, + }; + const extracted = extractModelSteps([badStep]); + assert.equal(extracted[0].inputTokens, 0); + assert.equal(extracted[0].cacheReadTokens, 0); + assert.equal(extracted[0].outputTokens, 1000); + assert.equal(extracted[0].thinkingTokens, 1000); + assert.equal(extracted[0].responseTokens, 0); + assert.equal(normalizeCachedStep({ ...extracted[0], inputTokens: -99 }).inputTokens, 0); + assert.equal(normalizeCachedStep(null), null); + + // Micro-steps: 100 steps * (1067 output * $3.75 / 1M = $0.00400125) = $0.40 (previously rounded per-step to $0.00 -> $0.00!) + const microSteps = Array.from({ length: 100 }, (_, idx) => ({ + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: idx + 1 }, + createdAt: promoNowIso, + completedAt: promoDoneIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', // gemini-3.8-flash-high: $0.75/1M input, $3.75/1M output + inputTokens: '0', + cacheReadTokens: '0', + outputTokens: '1067', + }, + }, + })); + const h = backendHarness({ + clock: () => promoMs, + summaries: { micro: { stepCount: 100, lastModifiedTime: promoDoneIso, status: 'IDLE' } }, + trajectories: { micro: { trajectory: { steps: microSteps } } }, + }); + const p = await h.buildTelemetryPayloadInternal('micro', false, { range: 'today' }); + assert.equal(p.consumption.account.costUsd, 0.4); +}); + +test('BUG-04 & BUG-10: failed RUNNING trajectory fetch enters cooldown instead of hammering RPC every poll, cleared by forceRefresh', async () => { + const h = backendHarness({ + summaries: { run1: { stepCount: 2, lastModifiedTime: doneIso, status: 'CASCADE_RUN_STATUS_RUNNING' } }, + trajectories: { run1: new Error('LS timeout') }, + quotaSummary: new Error('Quota RPC down'), + }); + + await h.buildTelemetryPayloadInternal('run1', false); + const callsAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length; + const quotaCallsAfterFirst = h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length; + assert.equal(callsAfterFirst, 1); + assert.equal(quotaCallsAfterFirst, 1); + + // Immediate second background poll must respect cooldown for both trajectory and quota RPC + await h.buildTelemetryPayloadInternal('run1', false); + assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 1); + assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 1); + + // Manual forceRefresh=true bypasses cooldown immediately + await h.buildTelemetryPayloadInternal('run1', true); + assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 2); + assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 2); +}); + +test('BUG-09, BUG-14 & BUG-15: SemVer 2.0 prerelease/build ordering, future-only exhausted quota inference, and <6h dual-bucket classification', async () => { + const h = backendHarness({ + quotaSummary: { + groups: [ + { + displayName: 'Gemini', + buckets: [ + { + // Omitted remainingFraction with epoch-0 resetTime must NOT falsely report 0% remaining! + resetTime: '1970-01-01T00:00:00Z', + }, + ], + }, + { + displayName: 'Claude & GPT', + buckets: [ + { + remainingFraction: 0.4, + resetTime: new Date(nowMs + 2 * 3600_000).toISOString(), + }, + { + remainingFraction: 0.8, + // Weekly bucket that happens to be 4h away from resetting! + resetTime: new Date(nowMs + 4 * 3600_000).toISOString(), + }, + ], + }, + ], + }, + }); + + assert.equal(h.compareSemver('1.4.2+20261110', '1.4.2'), 0); + assert.equal(h.compareSemver('1.5.0-beta.2', '1.5.0-alpha.10'), 1); + assert.equal(h.compareSemver('1.5.0-alpha.1', '1.5.0-alpha.beta'), -1); + + const p = await h.buildTelemetryPayloadInternal(''); + const geminiPool = p.quotas.pools.find((x) => x.poolKey === 'Gemini'); + assert.ok(geminiPool); + assert.equal(geminiPool.isAvailable, false, 'epoch-0 omitted remainingFraction must not create fake 0% exhausted pool'); + assert.equal(geminiPool.remainingPct, null); + assert.equal(geminiPool.usedPct, null); + + const claudePool = p.quotas.pools.find((x) => x.poolKey === 'Claude & GPT'); + assert.ok(claudePool); + assert.equal(claudePool.remainingPct, 40); + assert.equal(claudePool.weeklyRemainingPct, 80); + + assert.equal(formatCountdown(new Date(nowMs + 30_000).toISOString(), nowMs), '<1分钟后重置'); + assert.equal(formatCountdown('1969-12-31T23:59:59Z', nowMs), '未知重置时间'); + assert.equal(formatUsd(0.0004, { precise: true }), '<$0.001'); + assert.equal(formatUsd(12.34, { unpricedCalls: 1, compactPending: true }), '$12.34'); + assert.equal(speedReasonText('short_timing'), '耗时过短 (<0.5s)'); +}); + +test('BUG-17 & CANCEL-06: extractContextBreakdown classifies messagePrompts when children are empty and blocks post-compaction carryover', () => { + const ctx = extractContextBreakdown({ + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 10000, + tokenBreakdown: { + groups: [ + { type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 2000 }, + { type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 8000, children: [] }, + ], + }, + }, + }, + messagePrompts: [ + { source: 'CHAT_MESSAGE_SOURCE_USER', prompt: 'hello world' }, + { source: 'CHAT_MESSAGE_SOURCE_MODEL', prompt: 'Assistant reply content here!' }, + ], + }); + assert.ok(ctx); + assert.equal(ctx.systemPromptTokens, 2000); + assert.ok(ctx.userInputTokens > 0); + assert.ok(ctx.assistantTokens > 0); + assert.equal(ctx.userInputTokens + ctx.assistantTokens, 8000); + + const stepsWithTrailingCheckpoint = extractModelSteps( + [ + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 1 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '500' }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + sourceTrajectoryStepInfo: { stepIndex: 2 }, + createdAt: nowIso, + completedAt: doneIso, + modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '1200' }, + }, + }, + ], + [ + { + stepIndices: [1], + chatModel: { + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 180_000, + tokenBreakdown: { + groups: [{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 180_000 }], + }, + }, + }, + }, + }, + ] + ); + assert.equal(stepsWithTrailingCheckpoint.length, 2); + assert.equal(stepsWithTrailingCheckpoint[1].isCompactionStep, true); + assert.equal( + stepsWithTrailingCheckpoint[1].contextBreakdown, + null, + 'compaction checkpoint must not inherit pre-compaction 180k contextBreakdown' + ); +}); + +test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax safety, and IIFE bundle isolation', async () => { + const store = createReactiveStore({ a: 1, b: 2 }); + let calls = 0; + store.subscribe((s) => s.a + s.b, () => { + calls += 1; + }, { immediate: false }); + + store.setState({ a: 10 }); + store.setState({ b: 20 }); + await new Promise((r) => queueMicrotask(r)); + assert.equal(calls, 1, 'multiple setState calls in same microtask must batch into 1 subscriber flush'); + + const trickyModule = [ + "import './side-effect.js';", + "import { foo,\n bar } from './multi.js';", + 'const tpl = `\nimport { keepMe } from "tpl";\nexport const KEEP_ME = 42;\n`;', + 'export async function runTask() { return tpl; }', + 'export { runTask };', + ].join('\n'); + + const stripped = stripModuleSyntax(trickyModule); + assert.ok(stripped.includes('import { keepMe } from "tpl"')); + assert.ok(stripped.includes('export const KEEP_ME = 42')); + assert.equal(/^\s*import\s/m.test(stripped.replace(/`[\s\S]*?`/g, '')), false); + assert.doesNotThrow(() => new vm.Script(stripped)); + + const appBundle = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); + assert.ok(appBundle.startsWith('(() => {\n\'use strict\';')); + assert.ok(appBundle.trimEnd().endsWith('})();')); +}); + +test('bundle validation rejects incompatible imports and duplicate bindings before touching output', (t) => { + const tempDir = fs.mkdtempSync(fileURLToPath(new URL('./.bundle-test-', import.meta.url))); + t.after(() => fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })); + for (const dir of ['src', 'shared']) { + fs.cpSync(new URL(`../${dir}/`, import.meta.url), join(tempDir, dir), { recursive: true }); + } + const outputs = ['app.js', 'styles.css', 'index.html']; + for (const file of outputs) fs.writeFileSync(join(tempDir, file), file); + + const iconSource = join(tempDir, 'src', 'icons', 'svgRegistry.js'); + const original = fs.readFileSync(iconSource, 'utf8'); + for (const [prefix, error] of [ + ["import { SVG_NS /* comment */ as ns } from './SvgIcon.js';", /svgRegistry\.js.*without aliases/], + ["import { SVG_NS } from './SvgIcon.js';", /svgRegistry\.js.*SvgIcon\.js.*earlier in jsOrder/], + ["import './missing.js';", /svgRegistry\.js.*missing\.js.*earlier in jsOrder/], + ['export const SVG_NS = "duplicate";', /Identifier 'SVG_NS' has already been declared/], + ]) { + fs.writeFileSync(iconSource, `${prefix}\n${original}`); + assert.throws(() => buildBundle(tempDir), error); + for (const file of outputs) { + assert.equal(fs.readFileSync(join(tempDir, file), 'utf8'), file); + } + } + + // Per-module closure isolation: unexported private identifiers never collide across modules + fs.writeFileSync(iconSource, `const SVG_NS = "private_local";\n${original}`); + assert.doesNotThrow(() => buildBundle(tempDir)); +}); + +test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => { + const convId = '4432b724-3e1e-4421-a375-c6855a7b7b37'; + + // Pre-compaction steps (matching real-world step 0..2: planner edit_file x2 + 2 completed tool results) + const rpcPreCompactionSteps = [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-11T02:18:21Z', + finishedGeneratingAt: '2026-11-11T02:18:35Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '2918', + cacheReadTokens: '252465', + outputTokens: '814', + }, + }, + plannerResponse: { + toolCalls: [ + { name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/backend-harness.mjs' }) }, + { name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/04-post-fix-verify.mjs' }) }, + ], + }, + }, + { + type: 'CORTEX_STEP_TYPE_CODE_ACTION', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:38Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_CODE_ACTION', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:40Z' }, + }, + ]; + + // transcript.jsonl still ends at step_index 2 (since CHECKPOINT only flushes to transcript.jsonl when DONE) + const transcriptPreFlush = [ + { + step_index: 0, + source: 'MODEL', + type: 'PLANNER_RESPONSE', + status: 'DONE', + created_at: '2026-11-11T02:18:21Z', + tool_calls: [ + { name: 'edit_file', args: { Path: '"f:\\\\repo\\\\backend-harness.mjs"' } }, + { name: 'edit_file', args: { Path: '"f:\\\\repo\\\\04-post-fix-verify.mjs"' } }, + ], + }, + { + step_index: 1, + source: 'MODEL', + type: 'GENERIC', + status: 'DONE', + created_at: '2026-11-11T02:18:35Z', + content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:38+09:00\nMade 1 replacement', + }, + { + step_index: 2, + source: 'MODEL', + type: 'GENERIC', + status: 'DONE', + created_at: '2026-11-11T02:18:35Z', + content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:40+09:00\nMade 1 replacement', + }, + ]; + + // Phase 1: In-progress CORTEX_STEP_TYPE_CHECKPOINT in RPC WITHOUT metadata.createdAt yet + trailing MEMENTO + const h = backendHarness({ + summaries: { + [convId]: { + stepCount: 4, + lastModifiedTime: '2026-11-11T02:18:35Z', + status: 'CASCADE_RUN_STATUS_RUNNING', + annotations: { title: 'Audit & Fix Session' }, + }, + }, + trajectories: { + [convId]: { + trajectory: { + steps: [ + ...rpcPreCompactionSteps, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_RUNNING', + metadata: {}, + }, + { + type: 'CORTEX_STEP_TYPE_MEMENTO', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-11-11T02:18:40Z' }, + }, + ], + }, + }, + }, + transcripts: { + [convId]: transcriptPreFlush, + }, + }); + + const pCompacting = await h.buildTelemetryPayloadInternal(convId); + assert.equal(pCompacting.activeConversation.liveActivity.phase, 'compacting'); + assert.equal(pCompacting.activeConversation.liveActivity.label, '上下文压缩'); + assert.equal( + pCompacting.activeConversation.liveActivity.startedAtMs, + Date.parse('2026-11-11T02:18:40Z'), + 'uses previous tool completion timestamp when in-progress CHECKPOINT lacks createdAt' + ); + assert.equal(pCompacting.runningConversations[0].mainActivity.phase, 'compacting'); + assert.equal(pCompacting.runningConversations[0].mainActivity.label, '上下文压缩'); + + // Phase 2: CHECKPOINT finishes (status=DONE in both RPC & transcript.jsonl) while resuming before next PLANNER_RESPONSE + h.state.trajectories[convId] = { + trajectory: { + steps: [ + ...rpcPreCompactionSteps, + { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-11T02:18:40Z', + finishedGeneratingAt: '2026-11-11T02:19:33Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M318', + inputTokens: '3082', + cacheReadTokens: '254224', + outputTokens: '4627', + }, + }, + }, + ], + }, + }; + h.state.transcripts[convId] = [ + ...transcriptPreFlush, + { + step_index: 3, + source: 'SYSTEM', + type: 'CHECKPOINT', + status: 'DONE', + created_at: '2026-11-11T02:18:40Z', + content: '# Resuming from a compaction\n...', + }, + ]; + h.state.transcriptMtimeMs = 2; + + const pResuming = await h.buildTelemetryPayloadInternal(convId); + assert.equal(pResuming.activeConversation.liveActivity.phase, 'compacting'); + assert.equal(pResuming.activeConversation.liveActivity.label, '上下文压缩'); + assert.equal(pResuming.activeConversation.liveActivity.detail, '已完成压缩,正在恢复推理'); + assert.equal( + pResuming.activeConversation.liveActivity.startedAtMs, + Date.parse('2026-11-11T02:19:33Z') + ); + + // Phase 3: Even when RPC fails/cools down and ONLY transcript.jsonl (with status="DONE" CHECKPOINT) is available, + // it STILL detects compaction instead of regressing to pre-compaction "修改文件" + h.state.trajectories[convId] = new Error('temporary RPC timeout'); + const pTranscriptOnly = await h.buildTelemetryPayloadInternal(convId, true); + assert.equal(pTranscriptOnly.activeConversation.liveActivity.phase, 'compacting'); + assert.equal(pTranscriptOnly.activeConversation.liveActivity.label, '上下文压缩'); +}); + +test('panel typography scales all view/table/chart CSS rules via --fs-* tokens without hardcoded px sizes', () => { + const stylesDir = fileURLToPath(new URL('../src/styles', import.meta.url)); + const viewCssFiles = [ + 'controls.css', + 'views-overview.css', + 'views-tables.css', + 'views-consumption.css', + 'views-settings.css', + ]; + for (const file of viewCssFiles) { + const css = fs.readFileSync(join(stylesDir, file), 'utf8'); + const rawFontLines = css + .split(/\r?\n/) + .filter((line) => /font-size\s*:/.test(line) && !/var\(--fs-/.test(line)); + assert.deepEqual( + rawFontLines, + [], + `${file} must route every font-size declaration through scalable --fs-* tokens` + ); + } + const tokensCss = fs.readFileSync(join(stylesDir, 'tokens.css'), 'utf8'); + assert.match(tokensCss, /--font-sans\s*:[^;]+"SF Pro Text"/); + assert.match(tokensCss, /--font-mono\s*:\s*ui-monospace,\s*SFMono-Regular,\s*"SF Mono"/); + assert.match(tokensCss, /:host\(\[data-font-scale="xl"\]\)/); + assert.match(tokensCss, /\[data-font-scale\]\s*\{[\s\S]*?--fs-base-sm:/); + assert.doesNotMatch(tokensCss, /:root,\s*:host\s*\{[^}]*--ui-font-scale\s*:\s*1\s*;/); + + const panelRoot = fileURLToPath(new URL('..', import.meta.url)); + for (const artifact of ['styles.css', 'app.js', 'index.html']) { + const rawArtifact = fs.readFileSync(join(panelRoot, artifact), 'utf8'); + assert.equal(rawArtifact.includes('\r\n'), false, `${artifact} must normalize line endings to LF`); + } +}); + +test('post-compaction context preserves static channels + checkpoint summary, capsule fits 100% without ellipsis, and .step-model-compact follows --accent-primary', async () => { + const convId = '99999999-8888-4777-8666-555555555555'; + const preStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T03:00:00Z', + finishedGeneratingAt: '2026-11-18T03:00:05Z', + sourceTrajectoryStepInfo: { stepIndex: 10 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '5400', + cacheReadTokens: '270000', + outputTokens: '1200', + }, + }, + }; + const checkpointStep = { + type: 'CORTEX_STEP_TYPE_CHECKPOINT', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T03:01:00Z', + finishedGeneratingAt: '2026-11-18T03:01:06Z', + sourceTrajectoryStepInfo: { stepIndex: 12 }, + modelUsage: { + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '5400', + cacheReadTokens: '270000', + outputTokens: '3800', + thinkingOutputTokens: '800', + responseOutputTokens: '3000', + }, + }, + }; + const preGeneratorMetadata = [ + { + stepIndices: [10], + chatModel: { + responseModel: 'gemini-4-carbon-high', + modelDisplayName: 'Gemini 4 Carbon (High)', + chatStartMetadata: { + contextWindowMetadata: { + estimatedTokensUsed: 275_400, + maxContextTokens: 384_000, + tokenBreakdown: { + groups: [ + { + type: 'TOKEN_TYPE_SYSTEM_PROMPT', + numTokens: 16_000, + children: [ + { name: 'identity', numTokens: 10_000 }, + { name: 'skills', numTokens: 4_000 }, + { name: 'user_rules', numTokens: 2_000 }, + ], + }, + { + type: 'TOKEN_TYPE_TOOLS', + numTokens: 10_000, + children: [ + { name: 'run_command', numTokens: 8_000 }, + { name: 'mcp_gradio_predict', numTokens: 2_000 }, + ], + }, + { + type: 'TOKEN_TYPE_CHAT_MESSAGES', + numTokens: 249_400, + children: [ + { name: '1: USER_INPUT', numTokens: 49_400 }, + { name: '2: PLANNER_RESPONSE', numTokens: 80_000 }, + { name: '3: GENERIC', numTokens: 120_000 }, + ], + }, + ], + }, + }, + }, + }, + }, + ]; + + const h = backendHarness({ + clock: () => Date.parse('2026-11-18T03:02:00Z'), + summaries: { + [convId]: { + summary: 'Compaction test', + stepCount: 2, + status: 'CASCADE_RUN_STATUS_IDLE', + lastModifiedTime: '2026-11-18T03:01:06Z', + }, + }, + trajectories: { + [convId]: { + numTotalSteps: 2, + trajectory: { + steps: [preStep, checkpointStep], + generatorMetadata: preGeneratorMetadata, + }, + }, + }, + }); + + const payload = await h.buildTelemetryPayloadInternal(convId); + const ctx = payload.activeConversation.context; + + // Static channels must survive compaction while old chat history resets and checkpoint summary is recorded + assert.equal(ctx.systemPromptTokens, 10_000); + assert.equal(ctx.skillsTokens, 4_000); + assert.equal(ctx.userRulesTokens, 2_000); + assert.equal(ctx.systemToolsTokens, 8_000); + assert.equal(ctx.mcpToolsTokens, 2_000); + assert.equal(ctx.checkpointTokens, 3_000, 'checkpoint summary uses responseTokens excluding thinkingTokens'); + assert.equal(ctx.userInputTokens, 0); + assert.equal(ctx.assistantTokens, 0); + assert.equal(ctx.toolResultsTokens, 0); + assert.equal(ctx.subagentTokens, 0); + assert.equal(ctx.totalTokens, 29_000, 'must not leak 275.4k pre-compaction input into post-compaction total'); + assert.equal(ctx.compactionLimitTokens, 384_000, 'inherits 384k custom context budget across compaction step'); + assert.equal(ctx.usedPct, 7.6); + assert.equal(payload.conversations[0].contextUsedPct, 7.6, 'Multi-Session quick stats must also reflect post-compaction %'); + + // Subsequent lightweight step without its own tokenBreakdown rolls forward cleanly on top of compacted baseline + h.state.summaries[convId].stepCount = 3; + h.state.summaries[convId].lastModifiedTime = '2026-11-18T03:02:10Z'; + h.state.trajectories[convId] = { + numTotalSteps: 3, + trajectory: { + steps: [ + preStep, + checkpointStep, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-18T03:02:05Z', + finishedGeneratingAt: '2026-11-18T03:02:10Z', + sourceTrajectoryStepInfo: { stepIndex: 14 }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '1500', + cacheReadTokens: '29000', + outputTokens: '600', + }, + }, + }, + ], + generatorMetadata: preGeneratorMetadata, + }, + }; + const payloadFollowup = await h.buildTelemetryPayloadInternal(convId, true); + const ctx2 = payloadFollowup.activeConversation.context; + assert.equal(ctx2.systemPromptTokens, 10_000); + assert.equal(ctx2.checkpointTokens, 3_000); + assert.equal(ctx2.userInputTokens, 1_500); + assert.equal(ctx2.assistantTokens, 600); + assert.equal(ctx2.totalTokens, 31_100); + + // Verify capsule 100% slot CSS, non-hardcoded compaction suffix color, and narrow-width top pill nav containment + const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); + assert.match(stylesCss, /\.wm-ctx-seg\s*\{[^}]*width:\s*58px;/); + assert.match(stylesCss, /\.wm-ctx-pct\s*\{[^}]*max-width:\s*none;[^}]*overflow:\s*visible;[^}]*text-overflow:\s*clip;/s); + assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*color:\s*var\(--accent-primary\);/); + assert.doesNotMatch(stylesCss, /\.step-model-compact\s*\{[^}]*--metric-info/); + assert.match(stylesCss, /\.long-pill-nav\s*\{[^}]*container-type:\s*inline-size;[^}]*minmax\(0,\s*1fr\)[^}]*overflow:\s*hidden;/s); + assert.match(stylesCss, /\.pill-tab\s*\{[^}]*min-width:\s*0;/s); + assert.match(stylesCss, /@container\s*\(max-width:\s*30em\)\s*\{[\s\S]*?\.pill-tab-badge\s*\{\s*display:\s*none\s*!important;/); + assert.doesNotMatch(stylesCss, /\.structure-preview-canvas[^{]*\{[^}]*zoom:/, 'Structure preview must stay 1:1 without zoom distortion'); + assert.match(stylesCss, /\.preview-capsule-bar\s*\{[^}]*"Google Sans Flex"/s); +}); + +test('P0 audit fixes: main/bridge-daemon import isolation, standalone lsAddr, dual-window stepRevision LRU, CORTEX_STEP_TYPE_FIND, preview i18n, and header render purity', async () => { + // 1. Static import isolation on main.mjs and bridge-daemon.mjs + const mainSrc = fs.readFileSync(new URL('../main.mjs', import.meta.url), 'utf8'); + assert.doesNotMatch( + mainSrc, + /^import\s+[\s\S]*?from\s+['"]\.\/backend\/(?:api-actions|config)\.mjs['"]/m, + 'main.mjs must not statically import api-actions.mjs or config.mjs in the host parent process' + ); + const daemonSrc = fs.readFileSync(new URL('../bridge-daemon.mjs', import.meta.url), 'utf8'); + assert.doesNotMatch( + daemonSrc, + /^import\s+[\s\S]*?from\s+['"]\.\/backend\/config\.mjs['"]/m, + 'bridge-daemon.mjs must not statically import config.mjs before --standalone env overrides' + ); + + // 2. Dual-window alternating stepDetails='display' stepRevision cache hit + rebuild invalidation + const makeConv = (prompt) => ({ + trajectory: { + steps: [ + { + type: 'CORTEX_STEP_TYPE_USER_INPUT', + userInput: { userResponse: prompt }, + metadata: { createdAt: '2026-11-18T05:00:00Z' }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { response: 'done' }, + metadata: { + createdAt: '2026-11-18T05:00:01Z', + completedAt: '2026-11-18T05:00:02Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M65', + inputTokens: '1200', + outputTokens: '60', + }, + }, + }, + ], + }, + }); + const cidA = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa'; + const cidB = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb'; + const h = backendHarness({ + summaries: { + [cidA]: { summary: 'A', stepCount: 2, lastModifiedTime: '2026-11-18T05:00:02Z' }, + [cidB]: { summary: 'B', stepCount: 2, lastModifiedTime: '2026-11-18T05:00:03Z' }, + }, + trajectories: { + [cidA]: makeConv('Prompt A'), + [cidB]: makeConv('Prompt B'), + }, + }); + + const firstA = JSON.parse( + (await h.executeTelemetryAction({ conversationId: cidA, stepDetails: 'display', stepRevision: '' })).body + ); + const firstB = JSON.parse( + (await h.executeTelemetryAction({ conversationId: cidB, stepDetails: 'display', stepRevision: '' })).body + ); + const secondA = JSON.parse( + (await h.executeTelemetryAction({ + conversationId: cidA, + stepDetails: 'display', + stepRevision: firstA.stepRevision, + })).body + ); + const secondB = JSON.parse( + (await h.executeTelemetryAction({ + conversationId: cidB, + stepDetails: 'display', + stepRevision: firstB.stepRevision, + })).body + ); + assert.equal(secondA.stepsUnchanged, true); + assert.equal(secondB.stepsUnchanged, true); + assert.equal(secondA.activeConversation.recentSteps, undefined); + assert.equal(secondB.activeConversation.recentSteps, undefined); + + h.executeRebuildCacheAction(); + const afterRebuildA = JSON.parse( + (await h.executeTelemetryAction({ + conversationId: cidA, + stepDetails: 'display', + stepRevision: firstA.stepRevision, + })).body + ); + assert.equal(afterRebuildA.stepsUnchanged, false); + assert.equal(Array.isArray(afterRebuildA.activeConversation.recentSteps), true); + + // 3. CORTEX_STEP_TYPE_FIND live activity resolution + const findAct = extractLiveActivity( + [ + { + type: 'CORTEX_STEP_TYPE_FIND', + status: 'CORTEX_STEP_STATUS_RUNNING', + metadata: { createdAt: '2026-11-18T05:00:00Z' }, + }, + ], + true + ); + assert.equal(findAct?.label, '查找文件'); + + // 4. Preview i18n ('live.generating'), stepColumns maxItems: 14, SQLite busy helper reuse, and pure header render + const { setI18nLanguage } = await import('../src/i18n/index.js'); + const { buildStructurePreviewTelemetry } = await import( + '../src/components/settings/structurePreviewMock.js' + ); + setI18nLanguage('zh-CN'); + assert.equal( + buildStructurePreviewTelemetry().runningConversations[0].mainActivity.label, + '生成中' + ); + setI18nLanguage('en-US'); + assert.equal( + buildStructurePreviewTelemetry().runningConversations[0].mainActivity.label, + 'Generating' + ); + setI18nLanguage('zh-CN'); + + const structureTabSrc = fs.readFileSync( + new URL('../src/views/settings/SettingsStructureTab.js', import.meta.url), + 'utf8' + ); + assert.match(structureTabSrc, /options:\s*getStepColumnOptions[\s\S]{0,120}?maxItems:\s*14\b/); + + const cliStatusSrc = fs.readFileSync(new URL('../cli-statusline.mjs', import.meta.url), 'utf8'); + assert.match(cliStatusSrc, /\bwithReadOnlySqliteDb\b/); + assert.doesNotMatch(cliStatusSrc, /\bnew\s+DatabaseSync\s*\(/); + + const headerSrc = fs.readFileSync( + new URL('../src/components/layout/TopSessionHeader.js', import.meta.url), + 'utf8' + ); + const renderBody = headerSrc.slice( + headerSrc.indexOf('function renderHeaderState()'), + headerSrc.indexOf('const unsubTelemetry =') + ); + assert.doesNotMatch(renderBody, /\buiStore\.setState\b/); +}); + +test('P1 audit fixes: shared third-party pool & route single-source, pure frozen resolveScopedConversation, mock schema alignment, and dead SettingsAccountTab exclusion', async () => { + const { normalizeI18nLanguage } = await import('../src/i18n/index.js'); + const { resolveSpecificQuotaSlotSummary } = await import('../src/registries/metricRegistry.js'); + const { resolveScopedConversation, isEquivalentTelemetry } = await import( + '../src/store/telemetryStore.js' + ); + const { buildStructurePreviewTelemetry } = await import( + '../src/components/settings/structurePreviewMock.js' + ); + const { BRIDGE_API_ROUTE_DEFS } = await import('../shared/window-bridge-protocol.mjs'); + + assert.equal(normalizeI18nLanguage('system'), 'auto'); + assert.equal(typeof isEquivalentTelemetry, 'function'); + assert.equal(BRIDGE_API_ROUTE_DEFS.length, 10); + assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/bridge/relaunch')); + + // 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry + const h = backendHarness(); + const poolSample = 'Fable / OSS Third-Party Pool'; + assert.equal(h.classifyQuotaPoolIdentity({ groupName: poolSample }).poolKey, 'Claude & GPT'); + const quotasFixture = { + pools: [ + { + poolKey: poolSample, + poolLabel: poolSample, + family: poolSample, + remainingPct: 37, + weeklyRemainingPct: 68, + }, + ], + }; + assert.equal(resolveSpecificQuotaSlotSummary(quotasFixture, 'claude_5h')?.roundedPct, 37); + assert.match( + h.formatCliStatusLineCapsule({ quotas: quotasFixture }, { slots: ['claude_5h'], terminalWidth: 120 }), + /37%/ + ); + + // 2. Pure resolveScopedConversation never mutates deeply frozen telemetry + const deepFreeze = (obj) => { + if (!obj || typeof obj !== 'object') return obj; + Object.freeze(obj); + for (const v of Object.values(obj)) deepFreeze(v); + return obj; + }; + const frozenTelemetry = deepFreeze({ + activeConversation: { + cascadeId: 'frozen-conv', + hasSubagents: true, + recentSteps: [{ stepIndex: 1, createdAtMs: 100 }], + agents: [ + { agentId: 'main', isMain: true, index: 0 }, + { agentId: 'sub-1', isMain: false, index: 1, recentSteps: [{ stepIndex: 2, createdAtMs: 200 }] }, + ], + aggregated: { activeAgentId: 'main' }, + }, + }); + const scoped = resolveScopedConversation(frozenTelemetry, 'all', 'auto', true); + assert.equal(scoped.aggregated.recentSteps.length, 2); + assert.equal(scoped.mainAgent.recentSteps.length, 1); + + // 3. structurePreviewMock schema completeness & dead SettingsAccountTab exclusion from app.js + const mock = buildStructurePreviewTelemetry(); + assert.equal(typeof mock.activeConversation.context.compactionUsedTokens, 'number'); + assert.equal(mock.activeConversation.aggregated.agentId, 'all'); + assert.equal(Array.isArray(mock.activeConversation.agents[0].modelBreakdown), true); + assert.equal(mock.quotas.meta.hasOfficialData, true); + + const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); + assert.equal(appJs.includes('SettingsAccountTab.js'), false); + assert.equal(appJs.includes('function renderQuotaRows('), false); +}); + +test('P2 audit fixes: standalone sqlite/proto-wire primitives, structured liveActivity/agent/media i18n, full en-US SVG charts, controlled LiveActivityWidget reuse, and shared Mock DOM', async () => { + // 1. Standalone sqlite-client & proto-wire primitives (zero config/metrics imports) + const sqliteClientSrc = fs.readFileSync( + new URL('../backend/sqlite-client.mjs', import.meta.url), + 'utf8' + ); + const protoWireSrc = fs.readFileSync( + new URL('../backend/proto-wire.mjs', import.meta.url), + 'utf8' + ); + assert.doesNotMatch(sqliteClientSrc, /config\.mjs|trajectory-metrics\.mjs/); + assert.doesNotMatch(protoWireSrc, /config\.mjs|trajectory-metrics\.mjs/); + + const protoWire = await import('../backend/proto-wire.mjs'); + assert.equal(protoWire.unescapePbtxtString('\\344\\275\\240\\345\\245\\275'), '你好'); + const varState = { off: 0 }; + assert.equal(protoWire.readProtoVarint(new Uint8Array([0xac, 0x02]), varState), 300n); + + // 2. Bilingual dictionary 100% key parity + const { I18N_MESSAGES_ZH_CN } = await import('../src/i18n/zh-CN.js'); + const { I18N_MESSAGES_EN_US } = await import('../src/i18n/en-US.js'); + const zhKeys = Object.keys(I18N_MESSAGES_ZH_CN).sort(); + const enKeys = Object.keys(I18N_MESSAGES_EN_US).sort(); + assert.deepEqual(enKeys, zhKeys); + + // 3. Structured liveActivity, agent badges/labels, turn media, and en-US SVG charts (zero Chinese leakage) + const { createMockDom } = await import('./mock-dom.mjs'); + const prevDoc = globalThis.document; + const prevWin = globalThis.window; + const { document: mockDoc } = createMockDom(); + globalThis.document = mockDoc; + globalThis.window = { + innerWidth: 1280, + innerHeight: 800, + devicePixelRatio: 1, + document: mockDoc, + addEventListener() {}, + removeEventListener() {}, + getComputedStyle: () => ({ getPropertyValue: () => '' }), + }; + + try { + const { setI18nLanguage } = await import('../src/i18n/index.js'); + const { + formatAgentBadgeText, + formatAgentLabel, + formatLiveActivityDetail, + formatLiveActivityLabel, + } = await import('../src/core/formatters.js'); + const { formatTurnPromptText } = await import('../src/components/widgets/StepTableWidget.js'); + const { LiveActivityWidget } = await import('../src/components/widgets/LiveActivityWidget.js'); + const { buildCapsuleSlotContext } = await import('../src/components/widgets/CapsuleBarWidget.js'); + const { createModelFitChart, createSessionLineChart } = await import( + '../src/components/charts/SessionStepCharts.js' + ); + const { createTrendAreaChart } = await import('../src/components/charts/TrendAreaChart.js'); + + const waitCmdAct = extractLiveActivity( + [ + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + plannerResponse: { + toolCalls: [{ name: 'run_command', argumentsJson: '{"CommandLine":"npm test"}' }], + }, + }, + { type: 'CORTEX_STEP_TYPE_RUN_COMMAND', status: 'CORTEX_STEP_STATUS_WAITING' }, + ], + true + ); + assert.equal(waitCmdAct?.actionKey, 'run_command'); + assert.equal(waitCmdAct?.waitingApproval, true); + + setI18nLanguage('en-US'); + assert.equal(formatLiveActivityLabel(waitCmdAct), 'Awaiting Approval · Run Command'); + assert.equal( + formatLiveActivityDetail({ detailKey: 'compaction_resuming' }), + 'Compaction finished, resuming reasoning' + ); + assert.equal( + formatAgentBadgeText({ agentKind: 'side_question', agentOrdinal: 2 }), + 'Q2' + ); + assert.equal( + formatAgentLabel({ agentKind: 'subagent', agentOrdinal: 1, customRole: 'Auditor' }), + 'Subagent #1 · Auditor' + ); + assert.equal( + formatTurnPromptText('Check image', { hasMedia: true, mediaOnly: false }), + 'Check image [Media]' + ); + assert.equal(formatTurnPromptText('', { hasMedia: true, mediaOnly: true }), '[Media Attachment]'); + + // Controlled LiveActivityWidget auto-expands running subagents and renders session extras + let selectedCid = ''; + const controlledLive = LiveActivityWidget({ + defaultExpandRunningSubs: true, + showSessionExtras: true, + onSelectSession: (cid) => { + selectedCid = cid; + }, + }); + controlledLive.refs.update({ + hostRouteConversationId: 'conv-en-ctrl', + items: [ + { + cascadeId: 'conv-en-ctrl', + title: 'Controlled Multi Panel', + isMainRunning: true, + isRunning: true, + latestTokPerSec: 82.4, + contextUsedPct: 44, + mainActivity: waitCmdAct, + subagentCount: 1, + runningSubagentCount: 1, + subagents: [ + { + cascadeId: 'sub-ctrl-1', + index: 1, + agentKind: 'subagent', + agentOrdinal: 1, + customRole: 'Verifier', + isRunning: true, + stepCount: 2, + liveActivity: { + phase: 'compacting', + actionKey: 'compacting', + detailKey: 'compaction_resuming', + signature: 'cp:1', + }, + }, + ], + }, + ], + }); + assert.equal(controlledLive.el.querySelector('.live-sub-list').hasAttribute('hidden'), false); + assert.equal(controlledLive.el.querySelector('.wm-session-tag.is-here').hasAttribute('hidden'), false); + assert.equal(controlledLive.el.querySelector('.wm-task-metrics').textContent, '82.4 t/s · 44%'); + assert.equal(/[\u4e00-\u9fff]/.test(controlledLive.el.textContent), false); + controlledLive.el.querySelector('.live-task-title').onclick({}); + assert.equal(selectedCid, 'conv-en-ctrl'); + controlledLive.refs.stopLiveTicker(); + + // SVG charts in en-US emit zero Chinese characters + const sampleSteps = Array.from({ length: 6 }, (_, i) => ({ + stepIndex: i + 1, + baseModelLabel: 'Gemini 4 Carbon', + baseModelShort: 'carbon-4', + tokPerSec: 70 + i * 4, + ttftSec: 1.1, + cacheHitPct: 88, + inputTokens: 1000, + cacheReadTokens: 8000, + outputTokens: 300, + contextTokens: 12000, + costUsd: 0.01, + })); + const lineChart = createSessionLineChart(); + const lineRes = lineChart.update({ steps: sampleSteps, metric: 'tps' }); + assert.equal(/[\u4e00-\u9fff]/.test(lineRes.summaryBadge), false); + assert.equal(/[\u4e00-\u9fff]/.test(lineChart.el.textContent), false); + lineChart.destroy(); + + const fitChart = createModelFitChart(); + const fitRes = fitChart.update({ steps: sampleSteps, metric: 'tps' }); + assert.equal(/[\u4e00-\u9fff]/.test(fitRes.summaryBadge), false); + assert.equal(/[\u4e00-\u9fff]/.test(fitChart.el.textContent), false); + fitChart.destroy(); + + const trendChart = createTrendAreaChart(); + const hmSlots = Array.from({ length: 95 }, (_, i) => { + const iso = new Date(Date.UTC(2026, 6, 1 + i)).toISOString().slice(0, 10); + return { dateKey: iso, label: iso.slice(5), fullLabel: iso, tokens: (i + 1) * 500, calls: 2, costUsd: 0.02 }; + }); + trendChart.update(hmSlots); + assert.equal(/[\u4e00-\u9fff]/.test(trendChart.el.textContent), false); + trendChart.destroy(); + + const slotCtx = buildCapsuleSlotContext( + { activeConversation: { isRunning: true, stepCount: 2, latestTokPerSec: 64.5, context: { totalTokens: 64000, limitTokens: 256000 } } }, + {} + ); + assert.equal(slotCtx.usedPct, 25); + assert.equal(slotCtx.tps, 64.5); + + setI18nLanguage('zh-CN'); + } finally { + globalThis.document = prevDoc; + globalThis.window = prevWin; + } +}); diff --git a/sidecars/panel/test/mock-dom.mjs b/sidecars/panel/test/mock-dom.mjs new file mode 100644 index 0000000..77b7233 --- /dev/null +++ b/sidecars/panel/test/mock-dom.mjs @@ -0,0 +1,548 @@ +/** + * @fileoverview Shared lightweight W3C-compatible Mock DOM for Node `vm` UI & overlay tests. + * Replaces 6 separate copy-pasted inline mock DOM classes across `window-bridge.test.mjs`. + */ + +const ATTR_TOKEN_RE = /\[\s*([a-zA-Z0-9_:-]+)\s*(?:([*^$~|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\]]*)))?\s*\]/g; + +function matchCompoundSelector(node, rawCompound) { + if (!node || !node.tagName || String(node.tagName).startsWith('#')) return false; + let rem = String(rawCompound || '').trim(); + if (!rem) return false; + if (rem === '*') return true; + + // Match attribute clauses `[attr]`, `[attr="v"]`, `[attr^="v"]`, `[attr*="v"]`, `[attr$="v"]` + const attrs = []; + rem = rem.replace(ATTR_TOKEN_RE, (_m, name, op, dq, sq, bare) => { + attrs.push({ name, op: op || '', val: dq ?? sq ?? (bare ? bare.trim() : '') }); + return ''; + }); + + for (const a of attrs) { + if (!a.op) { + if (!node.hasAttribute(a.name)) return false; + continue; + } + const actual = node.getAttribute(a.name); + if (actual === null || actual === undefined) return false; + const str = String(actual); + if (a.op === '=' && str !== a.val) return false; + if (a.op === '^=' && !str.startsWith(a.val)) return false; + if (a.op === '*=' && !str.includes(a.val)) return false; + if (a.op === '$=' && !str.endsWith(a.val)) return false; + if (a.op === '~=' && !str.split(/\s+/).includes(a.val)) return false; + } + + // Extract `#id` and `.class` tokens + let idReq = ''; + const classReqs = []; + rem = rem.replace(/#([a-zA-Z0-9_-]+)/g, (_m, id) => { + idReq = id; + return ''; + }); + rem = rem.replace(/\.([a-zA-Z0-9_@/-]+)/g, (_m, cls) => { + classReqs.push(cls); + return ''; + }); + + if (idReq && node.id !== idReq) return false; + for (const cls of classReqs) { + if (!node.classList.contains(cls)) return false; + } + + const tag = rem.trim(); + if (tag && node.tagName.toLowerCase() !== tag.toLowerCase()) return false; + return true; +} + +function splitTopLevelCommas(selector) { + const out = []; + let depth = 0; + let quote = ''; + let start = 0; + const s = String(selector || ''); + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (quote) { + if (ch === quote && s[i - 1] !== '\\') quote = ''; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + } else if (ch === '[') { + depth++; + } else if (ch === ']') { + depth = Math.max(0, depth - 1); + } else if (ch === ',' && depth === 0) { + const part = s.slice(start, i).trim(); + if (part) out.push(part); + start = i + 1; + } + } + const tail = s.slice(start).trim(); + if (tail) out.push(tail); + return out; +} + +function tokenizeCombinators(singleSelector) { + const tokens = []; + let depth = 0; + let quote = ''; + let buf = ''; + let pendingDirect = false; + const s = String(singleSelector || '').trim(); + for (let i = 0; i < s.length; i++) { + const ch = s[i]; + if (quote) { + buf += ch; + if (ch === quote && s[i - 1] !== '\\') quote = ''; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + buf += ch; + continue; + } + if (ch === '[') { + depth++; + buf += ch; + continue; + } + if (ch === ']') { + depth = Math.max(0, depth - 1); + buf += ch; + continue; + } + if (depth === 0 && (ch === '>' || /\s/.test(ch))) { + if (buf) { + tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' }); + buf = ''; + pendingDirect = false; + } + if (ch === '>') pendingDirect = true; + continue; + } + buf += ch; + } + if (buf) { + tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' }); + } + return tokens; +} + +function matchChainFromScope(node, scopeRoot, tokens, idx) { + const step = tokens[idx]; + if (step.compound === ':scope') { + return node === scopeRoot; + } + if (!matchCompoundSelector(node, step.compound)) return false; + if (idx === 0) return true; + + if (step.combinator === '>') { + const p = node.parentNode; + if (!p) return false; + return matchChainFromScope(p, scopeRoot, tokens, idx - 1); + } + + let p = node.parentNode; + while (p) { + if (matchChainFromScope(p, scopeRoot, tokens, idx - 1)) return true; + if (p === scopeRoot) break; + p = p.parentNode; + } + return false; +} + +export class MockMutationObserver { + constructor(cb, registry = null) { + this.cb = cb; + this.targets = []; + if (Array.isArray(registry)) registry.push(this); + } + observe(target, options) { + this.targets.push({ target, options }); + } + disconnect() { + this.targets = []; + } +} + +export class MockDomNode { + constructor(tag = 'div', rect = null, domOptions = null) { + this._domOptions = domOptions || null; + this.tagName = String(tag || 'div').toUpperCase(); + this.nodeName = this.tagName; + this.nodeType = this.tagName === '#TEXT' ? 3 : 1; + this.id = ''; + this.value = ''; + this._text = ''; + this._rect = null; + this._ownRect = rect || null; + this.offsetWidth = 0; + this.offsetHeight = 0; + this.clientWidth = 0; + this.scrollWidth = 0; + this.dataset = {}; + this.attributes = new Map(); + this._classes = new Set(); + this.children = []; + this.parentNode = null; + this.shadowRoot = null; + this._listeners = new Map(); + + const styleVars = new Map(); + this.style = { + width: '', + height: '', + maxHeight: '', + marginLeft: '', + top: '', + left: '', + right: '', + display: '', + visibility: '', + opacity: '', + _vars: styleVars, + setProperty(k, v) { + const s = String(v ?? ''); + styleVars.set(k, s); + this[k] = s; + }, + getPropertyValue(k) { + return styleVars.get(k) || this[k] || ''; + }, + removeProperty(k) { + styleVars.delete(k); + delete this[k]; + }, + }; + + const self = this; + this.classList = { + add(...tokens) { + for (const t of tokens) if (t) self._classes.add(t); + self._syncClassAttr(); + }, + remove(...tokens) { + for (const t of tokens) self._classes.delete(t); + self._syncClassAttr(); + }, + contains(tok) { + return self._classes.has(tok); + }, + toggle(tok, force) { + const should = force === undefined ? !self._classes.has(tok) : Boolean(force); + if (should) self._classes.add(tok); + else self._classes.delete(tok); + self._syncClassAttr(); + return should; + }, + }; + } + + _syncClassAttr() { + const joined = [...this._classes].join(' '); + if (joined) this.attributes.set('class', joined); + else this.attributes.delete('class'); + } + + get className() { + return [...this._classes].join(' '); + } + + set className(v) { + this._classes.clear(); + for (const part of String(v || '').split(/\s+/)) { + if (part) this._classes.add(part); + } + this._syncClassAttr(); + } + + get textContent() { + if (this.children.length === 0) return this._text; + return this._text + this.children.map((c) => c.textContent ?? '').join(''); + } + + set textContent(v) { + for (const c of this.children) { + if (c) c.parentNode = null; + } + this.children = []; + this._text = String(v ?? ''); + } + + get parentElement() { + return this.parentNode; + } + + set parentElement(v) { + this.parentNode = v; + } + + get firstChild() { + return this.children[0] || null; + } + + get lastChild() { + return this.children[this.children.length - 1] || null; + } + + get firstElementChild() { + return this.children[0] || null; + } + + get lastElementChild() { + return this.children[this.children.length - 1] || null; + } + + get nextSibling() { + if (!this.parentNode) return null; + const idx = this.parentNode.children.indexOf(this); + return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; + } + + get nextElementSibling() { + return this.nextSibling; + } + + get isConnected() { + let cur = this; + while (cur) { + if (cur.isDocumentRoot) return true; + cur = cur.parentNode || cur.host || null; + } + return false; + } + + setAttribute(k, v) { + const s = String(v); + if (k === 'class') { + this.className = s; + return; + } + this.attributes.set(k, s); + if (k === 'id') this.id = s; + } + + getAttribute(k) { + if (k === 'class') return this.attributes.has('class') ? this.className : null; + return this.attributes.has(k) ? this.attributes.get(k) : null; + } + + hasAttribute(k) { + return this.attributes.has(k); + } + + removeAttribute(k) { + if (k === 'class') { + this._classes.clear(); + } + this.attributes.delete(k); + } + + appendChild(child) { + if (!child) return child; + if (child.parentNode?.removeChild) child.parentNode.removeChild(child); + child.parentNode = this; + this.children.push(child); + return child; + } + + insertBefore(node, refNode) { + if (!refNode) return this.appendChild(node); + if (node.parentNode?.removeChild) node.parentNode.removeChild(node); + const idx = this.children.indexOf(refNode); + node.parentNode = this; + if (idx < 0) this.children.push(node); + else this.children.splice(idx, 0, node); + return node; + } + + removeChild(child) { + const idx = this.children.indexOf(child); + if (idx >= 0) { + this.children.splice(idx, 1); + child.parentNode = null; + } + return child; + } + + remove() { + if (this.parentNode?.removeChild) this.parentNode.removeChild(this); + } + + attachShadow() { + const sr = new MockDomNode('#shadow-root', null, this._domOptions); + sr.host = this; + this.shadowRoot = sr; + return sr; + } + + contains(other) { + let cur = other; + while (cur) { + if (cur === this) return true; + cur = cur.parentNode; + } + return false; + } + + closest(sel) { + let cur = this; + while (cur && cur.nodeType === 1) { + if (cur.matches(sel)) return cur; + cur = cur.parentNode; + } + return null; + } + + addEventListener(type, fn) { + if (!this._listeners.has(type)) this._listeners.set(type, []); + this._listeners.get(type).push(fn); + } + + removeEventListener(type, fn) { + const arr = this._listeners.get(type); + if (!arr) return; + const idx = arr.indexOf(fn); + if (idx >= 0) arr.splice(idx, 1); + } + + dispatchEvent(ev) { + for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); + } + + setRect(rect) { + this._ownRect = rect; + } + + getBoundingClientRect() { + if (typeof this._domOptions?.resolveRect === 'function') { + const custom = this._domOptions.resolveRect(this); + if (custom) return custom; + } + if (this._ownRect) return this._ownRect; + if (this._rect) return this._rect; + if (this._domOptions?.inheritAncestorRect) { + let cur = this.parentNode || this.host || null; + while (cur) { + if (cur._ownRect) return cur._ownRect; + if (cur._rect) return cur._rect; + cur = cur.parentNode || cur.host || null; + } + } + return ( + this._domOptions?.defaultRect || { + left: 900, + right: 1080, + top: 6, + bottom: 32, + width: 180, + height: 26, + } + ); + } + + matches(selector) { + const groups = splitTopLevelCommas(selector); + if (groups.length === 0) return false; + return groups.some((g) => { + const tokens = tokenizeCombinators(g); + if (tokens.length === 0) return false; + return matchChainFromScope(this, null, tokens, tokens.length - 1); + }); + } + + querySelectorAll(selector) { + const groups = splitTopLevelCommas(selector); + if (groups.length === 0) return []; + const parsedGroups = groups.map(tokenizeCombinators).filter((t) => t.length > 0); + if (parsedGroups.length === 0) return []; + + const out = []; + const walk = (root) => { + for (const child of root.children || []) { + if ( + parsedGroups.some((tokens) => + matchChainFromScope(child, this, tokens, tokens.length - 1) + ) + ) { + out.push(child); + } + walk(child); + } + }; + walk(this); + return out; + } + + querySelector(selector) { + return this.querySelectorAll(selector)[0] || null; + } + + _find(pred) { + for (const c of this.children) { + if (pred(c)) return c; + const hit = c._find?.(pred); + if (hit) return hit; + } + return null; + } +} + +export function createMockDom({ + rootRect = null, + defaultRect = null, + inheritAncestorRect = false, + resolveRect = null, + onCreateElement = null, +} = {}) { + const domOptions = { defaultRect, inheritAncestorRect, resolveRect }; + const makeElement = (tag, rect = null) => { + const node = new MockDomNode(tag, rect, domOptions); + if (typeof onCreateElement === 'function') onCreateElement(node, tag); + return node; + }; + + const docRoot = makeElement('html', rootRect); + docRoot.isDocumentRoot = true; + const head = makeElement('head'); + const body = makeElement('body', rootRect); + docRoot.appendChild(head); + docRoot.appendChild(body); + + const docListeners = new Map(); + const document = { + readyState: 'complete', + hidden: false, + activeElement: null, + documentElement: docRoot, + head, + body, + createElement: (tag) => makeElement(tag), + createElementNS: (_ns, tag) => makeElement(tag), + createTextNode: (txt) => { + const t = new MockDomNode('#text', null, domOptions); + t.textContent = String(txt ?? ''); + return t; + }, + getElementById: (id) => docRoot._find((n) => n.id === id), + querySelector: (sel) => docRoot.querySelector(sel), + querySelectorAll: (sel) => docRoot.querySelectorAll(sel), + addEventListener(type, fn) { + if (!docListeners.has(type)) docListeners.set(type, []); + docListeners.get(type).push(fn); + }, + removeEventListener(type, fn) { + const arr = docListeners.get(type); + if (!arr) return; + const idx = arr.indexOf(fn); + if (idx >= 0) arr.splice(idx, 1); + }, + dispatchEvent(ev) { + for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev); + }, + }; + + return { docRoot, head, body, document, docListeners, makeElement }; +} diff --git a/sidecars/panel/test/model-identity.test.mjs b/sidecars/panel/test/model-identity.test.mjs index 4a60317..150753a 100644 --- a/sidecars/panel/test/model-identity.test.mjs +++ b/sidecars/panel/test/model-identity.test.mjs @@ -1,8 +1,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import vm from 'node:vm'; -import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs'; +import { isEquivalentTelemetry } from '../src/store/telemetryStore.js'; +import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs'; import { formatUsd, mergeModelsByDisplayName, @@ -11,7 +10,8 @@ import { import { backendHarness } from './backend-harness.mjs'; const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418'; -const createdAtMs = Date.now() - 20_000; +const PROMO_CLOCK_MS = Date.parse('2026-11-17T12:00:20Z'); +const createdAtMs = PROMO_CLOCK_MS - 20_000; function step(index, model, checkpoint = false) { return { type: checkpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', status: 'CORTEX_STEP_STATUS_DONE', metadata: { @@ -22,7 +22,7 @@ function step(index, model, checkpoint = false) { } }; } async function payload(steps, options = {}) { - return backendHarness({ summaries: { test: { stepCount: steps.length } }, + return backendHarness({ clock: () => PROMO_CLOCK_MS, summaries: { test: { stepCount: steps.length } }, trajectories: { test: { trajectory: { steps } } }, ...options }).buildTelemetryPayloadInternal('test'); } @@ -135,7 +135,7 @@ test('upstream responseModel is preserved alongside placeholder modelKey for Ste }); test('server model catalog overrides static placeholder mapping', () => { - const {resolveModelInfo} = backendHarness(); + const {resolveModelInfo} = backendHarness({ clock: () => PROMO_CLOCK_MS }); const result = resolveModelInfo(ARGON, new Map([[ARGON, {modelId:'gemini-3.8-flash-high', label:'Gemini 3.8 Flash (High)'}]])); assert.equal(result.shortName,'flash-3.8-high'); assert.equal(result.pricing.input,0.75); }); @@ -192,12 +192,9 @@ test('custom cost budget cannot claim a complete remaining percentage when price }); test('frontend considers a model-only correction a real telemetry update', () => { - const source = fs.readFileSync(new URL('../src/store/telemetryStore.js',import.meta.url),'utf8'); - const fn = source.slice(source.indexOf('function isEquivalentTelemetry'),source.indexOf('export async function fetchTelemetry')); - const ctx = {}; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx); const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}}; const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model'; - assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true); + assert.equal(isEquivalentTelemetry(a,b),false); assert.equal(isEquivalentTelemetry(a,structuredClone(a)),true); }); const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667'; @@ -256,6 +253,7 @@ test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolv test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is not misclassified as Carbon', async () => { const h = backendHarness({ + clock: () => PROMO_CLOCK_MS, summaries: { test: { stepCount: 1 } }, trajectories: { test: { @@ -488,7 +486,7 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and }); test('historical placeholders (M15/M16/M47/M84/M132/M133/M264/M330) and verified internal routing slugs resolve and price accurately without wildcarding unknown slugs', () => { - const { resolveModelInfo } = backendHarness(); + const { resolveModelInfo } = backendHarness({ clock: () => PROMO_CLOCK_MS }); const expectedPlaceholders = [ ['MODEL_PLACEHOLDER_M84', 'flash-3.5-high', 1.5, 9.0], diff --git a/sidecars/panel/test/quota-pools.test.mjs b/sidecars/panel/test/quota-pools.test.mjs index 7b054f2..397536c 100644 --- a/sidecars/panel/test/quota-pools.test.mjs +++ b/sidecars/panel/test/quota-pools.test.mjs @@ -1,7 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import fs from 'node:fs'; -import vm from 'node:vm'; +import { isEquivalentTelemetry } from '../src/store/telemetryStore.js'; import { backendHarness } from './backend-harness.mjs'; const FLASH = 'MODEL_PLACEHOLDER_M318'; @@ -285,14 +284,9 @@ test('exhausted 0% bucket omitting remainingFraction in proto3 is reported as 10 }); test('telemetryStore isEquivalentTelemetry detects quota changes in non-active pools', () => { - const source = fs.readFileSync(new URL('../src/store/telemetryStore.js', import.meta.url), 'utf8'); - const fn = source.slice( - source.indexOf('function isEquivalentTelemetry'), - source.indexOf('export async function fetchTelemetry') - ); - const ctx = {}; - vm.runInNewContext(fn + '\nglobalThis.compare=isEquivalentTelemetry;', ctx); + const compare = isEquivalentTelemetry; + const ctx = { compare }; const a = { account: { tierName: 'Google AI Pro', planName: 'Pro' }, quotas: { diff --git a/sidecars/panel/test/speed-metrics.test.mjs b/sidecars/panel/test/speed-metrics.test.mjs index 7399199..d3ee118 100644 --- a/sidecars/panel/test/speed-metrics.test.mjs +++ b/sidecars/panel/test/speed-metrics.test.mjs @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs'; +import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../trajectory-metrics.mjs'; function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000, thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) { diff --git a/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs new file mode 100644 index 0000000..3ffe156 --- /dev/null +++ b/sidecars/panel/test/sqlite-hybrid-and-side-question.test.mjs @@ -0,0 +1,788 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtempSync, mkdirSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs'; +import { backendHarness } from './backend-harness.mjs'; +import { i18nStore } from '../src/i18n/index.js'; +import { + formatAgentBadgeText, + formatAgentLabel, + resolveScopedConversation, +} from '../src/store/telemetryStore.js'; + +function encodeVarint(val) { + let v = BigInt(val); + if (v < 0n) v = BigInt.asUintN(64, v); + const out = []; + while (v >= 0x80n) { + out.push(Number((v & 0x7fn) | 0x80n)); + v >>= 7n; + } + out.push(Number(v)); + return Buffer.from(out); +} + +function encodeFieldVarint(fieldNo, val) { + return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]); +} + +function encodeFieldBytes(fieldNo, bufOrStr) { + const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8'); + return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]); +} + +function encodeTimestamp(sec, nanos = 0) { + return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]); +} + +function encodeStepMeta({ + createdSec, + finishedSec, + stepIndex, + originCascadeId = '', + modelEnumInt = 0, + inputTokens = 0, + cacheReadTokens = 0, + outputTokens = 0, + thinkingTokens = 0, + responseTokens = 0, +}) { + const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))]; + if (finishedSec) { + parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec))); + } + if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) { + const muParts = []; + if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt)); + if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens)); + if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens)); + if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens)); + muParts.push(encodeFieldVarint(6, 24)); // API_PROVIDER_GOOGLE_GEMINI + if (thinkingTokens) muParts.push(encodeFieldVarint(9, thinkingTokens)); + if (responseTokens) muParts.push(encodeFieldVarint(10, responseTokens)); + parts.push(encodeFieldBytes(9, Buffer.concat(muParts))); + } + const siParts = [encodeFieldVarint(2, stepIndex)]; + if (originCascadeId) { + siParts.push(encodeFieldBytes(4, originCascadeId)); + } + parts.push(encodeFieldBytes(20, Buffer.concat(siParts))); + return Buffer.concat(parts); +} + +function encodeUserInputPayload(text) { + return encodeFieldBytes(19, encodeFieldBytes(2, text)); +} + +function encodePlannerResponsePayload(text) { + return encodeFieldBytes(20, encodeFieldBytes(1, text)); +} + +function encodeGenMeta({ + stepIndex, + cascadeId, + responseModel, + modelDisplayName, + estimatedTokensUsed = 0, + maxContextTokens = 256000, + userMsgTokens = 0, +}) { + const groups = []; + if (userMsgTokens > 0) { + const child = Buffer.concat([ + encodeFieldBytes(1, '0: USER_INPUT'), + encodeFieldVarint(3, userMsgTokens), + ]); + const topGroup = Buffer.concat([ + encodeFieldBytes(1, 'Chat Messages'), + encodeFieldVarint(2, 7), // TOKEN_TYPE_CHAT_MESSAGES + encodeFieldVarint(4, userMsgTokens), + encodeFieldBytes(5, child), + ]); + groups.push(encodeFieldBytes(1, topGroup)); + } + const cwParts = []; + if (estimatedTokensUsed > 0) cwParts.push(encodeFieldVarint(1, estimatedTokensUsed)); + if (groups.length > 0) cwParts.push(encodeFieldBytes(3, Buffer.concat(groups))); + if (maxContextTokens > 0) cwParts.push(encodeFieldVarint(4, maxContextTokens)); + + const mapCascade = Buffer.concat([ + encodeFieldBytes(1, 'cascade_id'), + encodeFieldBytes(2, cascadeId), + ]); + const chatParts = [ + encodeFieldBytes(9, encodeFieldBytes(10, Buffer.concat(cwParts))), + encodeFieldBytes(11, encodeTimestamp(1, 0)), // 1s TTFT + encodeFieldBytes(19, responseModel), + encodeFieldBytes(20, mapCascade), + encodeFieldBytes(21, modelDisplayName), + ]; + return Buffer.concat([ + encodeFieldVarint(2, stepIndex), + encodeFieldBytes(1, Buffer.concat(chatParts)), + ]); +} + +function encodeSummaryBlob({ + title = '', + stepCount = 0, + lastModSec = 0, + statusInt = 1, + trajectoryType = 0, + forkParentId = '', + sideQuestionIds = [], + sideQuestionTitles = {}, + parentConversationId = '', + subagentSpec = null, +}) { + const parts = []; + if (stepCount > 0) parts.push(encodeFieldVarint(2, stepCount)); + if (lastModSec > 0) parts.push(encodeFieldBytes(3, encodeTimestamp(lastModSec))); + if (statusInt > 0) parts.push(encodeFieldVarint(5, statusInt)); + + const annParts = []; + if (title) annParts.push(encodeFieldBytes(1, title)); + for (const sqId of sideQuestionIds) { + annParts.push(encodeFieldBytes(17, sqId)); + } + for (const [k, v] of Object.entries(sideQuestionTitles)) { + annParts.push( + encodeFieldBytes(18, Buffer.concat([encodeFieldBytes(1, k), encodeFieldBytes(2, v)])) + ); + } + if (annParts.length > 0) parts.push(encodeFieldBytes(15, Buffer.concat(annParts))); + + if (parentConversationId || subagentSpec) { + const tmParts = []; + if (parentConversationId) tmParts.push(encodeFieldBytes(5, parentConversationId)); + if (subagentSpec) { + const specParts = []; + if (subagentSpec.typeName) specParts.push(encodeFieldBytes(1, subagentSpec.typeName)); + if (subagentSpec.role) specParts.push(encodeFieldBytes(2, subagentSpec.role)); + tmParts.push(encodeFieldBytes(8, Buffer.concat(specParts))); + } + parts.push(encodeFieldBytes(17, Buffer.concat(tmParts))); + } + + if (trajectoryType > 0) parts.push(encodeFieldVarint(22, trajectoryType)); + if (forkParentId) parts.push(encodeFieldBytes(24, forkParentId)); + return Buffer.concat(parts); +} + +test('Hybrid SQLite+WAL mode skips trajectory RPCs for local DBs, falls back to RPC when DB is absent, deduplicates cloned Side Question steps, protects mainline context, and renders zh/en badges', async (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempRoot = mkdtempSync(join(tmpdir(), 'agy-hybrid-sqlite-')); + + const mainCid = '11111111-1111-4111-8111-111111111111'; + const subCid = '22222222-2222-4222-8222-222222222222'; + const sideCid = '33333333-3333-4333-8333-333333333333'; + const emptySideCid = '44444444-4444-4444-8444-444444444444'; + const rpcOnlyCid = '55555555-5555-4555-8555-555555555555'; + + // Use promo-period timestamp: 2026-11-18T00:00:00Z = 1794960000 + const baseSec = Math.floor(Date.parse('2026-11-18T00:00:00Z') / 1000); + const rpcCalls = []; + + const mockLsServer = http.createServer((req, res) => { + let rawBody = ''; + req.on('data', (chunk) => { + rawBody += chunk; + }); + req.on('end', () => { + const method = req.url.split('/').pop(); + const body = rawBody ? JSON.parse(rawBody) : {}; + rpcCalls.push({ method, cascadeId: body.cascadeId || '' }); + + res.setHeader('Content-Type', 'application/json'); + if (method === 'GetUserStatus') { + res.end(JSON.stringify({ userStatus: { email: 'dev@example.com' } })); + return; + } + if (method === 'RetrieveUserQuotaSummary') { + res.end(JSON.stringify({ response: { groups: [] } })); + return; + } + if (method === 'GetAvailableModels') { + res.end(JSON.stringify({ response: { models: {} } })); + return; + } + if (method === 'GetCascadeTrajectory' && body.cascadeId === rpcOnlyCid) { + res.end( + JSON.stringify({ + numTotalSteps: 2, + trajectory: { + steps: [ + { + // Cloned step from mainCid over RPC — must ALSO be stripped by filterClonedTrajectorySteps! + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date((baseSec + 50) * 1000).toISOString(), + finishedGeneratingAt: new Date((baseSec + 54) * 1000).toISOString(), + sourceTrajectoryStepInfo: { stepIndex: 0, cascadeId: mainCid }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '5000000', + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + }, + { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: new Date((baseSec + 100) * 1000).toISOString(), + finishedGeneratingAt: new Date((baseSec + 102) * 1000).toISOString(), + sourceTrajectoryStepInfo: { stepIndex: 1, cascadeId: rpcOnlyCid }, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M320', // gemini-3.8-flash-low: $0.30/M input + apiProvider: 'API_PROVIDER_GOOGLE_GEMINI', + inputTokens: '1000000', + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + }, + ], + }, + }) + ); + return; + } + res.statusCode = 500; + res.end(JSON.stringify({ error: `unexpected RPC ${method}` })); + }); + }); + + await new Promise((resolve) => mockLsServer.listen(0, '127.0.0.1', resolve)); + const lsPort = mockLsServer.address().port; + + try { + const agyDir = join(tempRoot, 'antigravity'); + const convDir = join(agyDir, 'conversations'); + mkdirSync(convDir, { recursive: true }); + + // 1. Build conversation_summaries.db in WAL mode + const sumDbPath = join(agyDir, 'conversation_summaries.db'); + const sumDb = new DatabaseSync(sumDbPath); + sumDb.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE conversation_summaries ( + conversation_id TEXT PRIMARY KEY, + title TEXT, + preview TEXT, + status TEXT, + source TEXT, + parent_conversation_id TEXT, + nesting_depth INTEGER, + agent_name TEXT, + not_fully_idle INTEGER, + killed INTEGER, + step_count INTEGER, + last_modified_time TEXT, + app_data_dir TEXT, + raw_summary BLOB + ); + CREATE TABLE conversation_parents ( + conversation_id TEXT, + parent_id TEXT + ); + `); + + const insSum = sumDb.prepare(` + INSERT INTO conversation_summaries ( + conversation_id, title, status, parent_conversation_id, step_count, last_modified_time, app_data_dir, raw_summary + ) VALUES (?, ?, ?, ?, ?, ?, 'antigravity', ?) + `); + + insSum.run( + mainCid, + 'Main Architecture Task', + 'CASCADE_RUN_STATUS_IDLE', + '', + 2, + '2026-11-18T00:01:35Z', + encodeSummaryBlob({ + title: 'Main Architecture Task', + stepCount: 2, + lastModSec: baseSec + 95, + sideQuestionIds: [sideCid, emptySideCid], + sideQuestionTitles: { [sideCid]: '为什么用 WAL 模式?' }, + }) + ); + insSum.run( + subCid, + 'SQLite Researcher', + 'CASCADE_RUN_STATUS_IDLE', + mainCid, + 2, + '2026-11-18T00:01:10Z', + encodeSummaryBlob({ + title: 'SQLite Researcher', + stepCount: 2, + lastModSec: baseSec + 70, + parentConversationId: mainCid, + subagentSpec: { typeName: 'research', role: 'SQLite Researcher' }, + }) + ); + insSum.run( + sideCid, + '', + 'CASCADE_RUN_STATUS_IDLE', + '', + 4, + '2026-11-18T00:02:00Z', + encodeSummaryBlob({ + stepCount: 4, + lastModSec: baseSec + 120, + trajectoryType: 22, + forkParentId: mainCid, + }) + ); + insSum.run( + emptySideCid, + '', + 'CASCADE_RUN_STATUS_IDLE', + '', + 2, + '2026-11-18T00:01:30Z', + encodeSummaryBlob({ + stepCount: 2, + lastModSec: baseSec + 90, + trajectoryType: 22, + forkParentId: mainCid, + }) + ); + // rpcOnlyCid is present in summaries, but has NO local .db file -> must fall back to GetCascadeTrajectory RPC! + insSum.run( + rpcOnlyCid, + 'Remote WSL Session', + 'CASCADE_RUN_STATUS_IDLE', + '', + 1, + '2026-11-18T00:00:30Z', + encodeSummaryBlob({ + title: 'Remote WSL Session', + stepCount: 1, + lastModSec: baseSec + 30, + }) + ); + sumDb.prepare('INSERT INTO conversation_parents (conversation_id, parent_id) VALUES (?, ?)').run(sideCid, mainCid); + sumDb.close(); + + const initConvDb = (cid, trajectoryType = 1) => { + const db = new DatabaseSync(join(convDir, `${cid}.db`)); + db.exec(` + PRAGMA journal_mode = WAL; + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, ?, 1)').run(cid, cid, trajectoryType); + return db; + }; + + // 2. Main conversation DB: 1 USER_INPUT ("设计混合 SQLite 读取") + 1 Carbon High response ($12.10, context 120k/256k) + const mainDb = initConvDb(mainCid, 1); + mainDb + .prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: mainCid }), + encodeUserInputPayload('设计混合 SQLite 读取') + ); + mainDb + .prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 50, + finishedSec: baseSec + 54, + stepIndex: 1, + originCascadeId: mainCid, + modelEnumInt: 1429, // MODEL_PLACEHOLDER_M429 -> Carbon High ($2 + $0.1 + $10 = $12.10) + inputTokens: 1_000_000, + cacheReadTokens: 1_000_000, + outputTokens: 1_000_000, + thinkingTokens: 400_000, + responseTokens: 600_000, + }), + encodePlannerResponsePayload('这是混合架构方案。') + ); + mainDb + .prepare('INSERT INTO gen_metadata VALUES (0, ?)') + .run( + encodeGenMeta({ + stepIndex: 1, + cascadeId: mainCid, + responseModel: 'gemini-4-carbon-high', + modelDisplayName: 'Gemini 4 Carbon (High)', + estimatedTokensUsed: 120_000, + maxContextTokens: 256_000, + userMsgTokens: 120_000, + }) + ); + mainDb.close(); + + // 3. Regular subagent DB: 1 Flash 3.8 Low step ($0.30) + const subDb = initConvDb(subCid, 1); + subDb + .prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 10, stepIndex: 0, originCascadeId: subCid }), + encodeUserInputPayload('调研 SQLite WAL') + ); + subDb + .prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 11, + finishedSec: baseSec + 13, + stepIndex: 1, + originCascadeId: subCid, + modelEnumInt: 1320, // MODEL_PLACEHOLDER_M320 -> $0.30/1M input + inputTokens: 1_000_000, + }), + encodePlannerResponsePayload('WAL 调研完毕') + ); + subDb.close(); + + // 4. Side Question DB (trajectory_type = 22): + // Contains 2 CLONED parent steps from mainCid ($12.10) + 1 own USER_INPUT + 1 own Flash 3.8 High step ($0.75) + // Context watermark in Side Question is tiny (15k) and later than mainCid — must NOT overwrite mainCid's context! + const sideDb = initConvDb(sideCid, 22); + sideDb + .prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: mainCid }), + encodeUserInputPayload('设计混合 SQLite 读取') + ); + sideDb + .prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 50, + finishedSec: baseSec + 54, + stepIndex: 1, + originCascadeId: mainCid, // CLONED FROM PARENT! Must be filtered out! + modelEnumInt: 1429, + inputTokens: 1_000_000, + cacheReadTokens: 1_000_000, + outputTokens: 1_000_000, + }), + encodePlannerResponsePayload('克隆的父回复') + ); + sideDb + .prepare('INSERT INTO steps VALUES (2, 14, 3, ?, ?)') + .run( + encodeStepMeta({ createdSec: baseSec + 80, stepIndex: 2, originCascadeId: sideCid }), + encodeUserInputPayload('顺便问下为什么用 WAL?') + ); + sideDb + .prepare('INSERT INTO steps VALUES (3, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 81, + finishedSec: baseSec + 83, + stepIndex: 3, + originCascadeId: sideCid, + modelEnumInt: 1318, // MODEL_PLACEHOLDER_M318 -> $0.75/1M input + inputTokens: 1_000_000, + }), + encodePlannerResponsePayload('因为只读不阻塞 checkpoint。') + ); + sideDb + .prepare('INSERT INTO gen_metadata VALUES (0, ?)') + .run( + encodeGenMeta({ + stepIndex: 1, + cascadeId: mainCid, // Cloned gen_metadata from parent! + responseModel: 'gemini-4-carbon-high', + modelDisplayName: 'Gemini 4 Carbon (High)', + estimatedTokensUsed: 120_000, + maxContextTokens: 256_000, + userMsgTokens: 120_000, + }) + ); + sideDb + .prepare('INSERT INTO gen_metadata VALUES (1, ?)') + .run( + encodeGenMeta({ + stepIndex: 3, + cascadeId: sideCid, + responseModel: 'gemini-3.8-flash-high', + modelDisplayName: 'Gemini 3.8 Flash (High)', + estimatedTokensUsed: 15_000, + maxContextTokens: 256_000, + userMsgTokens: 15_000, + }) + ); + sideDb.close(); + + // 5. Empty Side Question DB: only cloned parent steps, 0 own steps -> must be hidden! + const emptySideDb = initConvDb(emptySideCid, 22); + emptySideDb + .prepare('INSERT INTO steps VALUES (0, 15, 3, ?, ?)') + .run( + encodeStepMeta({ + createdSec: baseSec + 2, + finishedSec: baseSec + 6, + stepIndex: 1, + originCascadeId: mainCid, + modelEnumInt: 1429, + inputTokens: 1_000_000, + }), + null + ); + emptySideDb.close(); + + const execFileAsync = promisify(execFile); + const builderUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href; + const { stdout: rawJson } = await execFileAsync( + process.execPath, + [ + '--input-type=module', + '-e', + `const { buildTelemetryPayload } = await import(${JSON.stringify(builderUrl)}); + const p = await buildTelemetryPayload(${JSON.stringify(mainCid)}, false, { range: 'all' }); + process.stdout.write(JSON.stringify(p));`, + ], + { + env: { + ...process.env, + ANTIGRAVITY_GEMINI_DIR: tempRoot, + ANTIGRAVITY_APP_DATA_DIR: '', + USAGE_MONITOR_APP_DATA_DIR: '', + ANTIGRAVITY_EXECUTABLE_DATA_DIR: '', + USAGE_MONITOR_DATA_DIR: join(tempRoot, 'sidecar-data'), + ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${lsPort}`, + ANTIGRAVITY_CSRF_TOKEN: 'test-csrf', + }, + encoding: 'utf8', + maxBuffer: 16 * 1024 * 1024, + } + ); + + const payload = JSON.parse(rawJson); + + // A. Verify RPC calls: ZERO GetAllCascadeTrajectories, ZERO GetCascadeTrajectory for local SQLite DBs, + // and exactly ONE GetCascadeTrajectory fallback for rpcOnlyCid! + assert.equal( + rpcCalls.some((c) => c.method === 'GetAllCascadeTrajectories'), + false, + 'local conversation_summaries.db must eliminate GetAllCascadeTrajectories RPC' + ); + const trajRpcTargets = rpcCalls + .filter((c) => c.method === 'GetCascadeTrajectory') + .map((c) => c.cascadeId); + assert.deepEqual( + trajRpcTargets, + [rpcOnlyCid], + 'only conversation missing local .db falls back to GetCascadeTrajectory RPC' + ); + + // B. Top-level conversations list contains ONLY mainCid and rpcOnlyCid (no orphan/empty side questions or subagents) + assert.deepEqual( + payload.conversations.map((c) => c.cascadeId).sort(), + [mainCid, rpcOnlyCid].sort() + ); + + // C. Verify Turn Rail prompt decoded directly from SQLite USER_INPUT step_payload + const mainUnit = payload.activeConversation.agents.find((a) => a.isMain); + assert.ok(mainUnit); + assert.equal(payload.activeConversation.recentSteps[0].turnPrompt, '设计混合 SQLite 读取'); + + // D. Verify agents under mainCid: [main, subagent #1, side question #1] (emptySideCid hidden!) + const agents = payload.activeConversation.agents; + assert.equal(agents.length, 3); + assert.equal(agents[1].badgeText, '子1'); + assert.equal(Boolean(agents[1].isSideQuestion), false); + assert.equal(agents[2].badgeText, '旁1'); + assert.equal(agents[2].isSideQuestion, true); + assert.equal(agents[2].sideIndex, 1); + assert.equal(agents[2].role, '为什么用 WAL 模式?'); + assert.equal(agents[2].stepCount, 1, 'cloned parent steps must be stripped from Side Question'); + assert.equal(agents[2].sessionCostUsd, 0.75, 'Side Question bills ONLY its own step ($0.75), never parent ($12.10)'); + + // E. Verify total session & account costs have ZERO double-counting: + // Session (main $12.10 + sub $0.30 + sideQ $0.75) = $13.15 + // Account (session $13.15 + rpcOnlyCid $0.30) = $13.45 + assert.equal(payload.activeConversation.aggregated.sessionCostUsd, 13.15); + assert.equal(payload.consumption.account.costUsd, 13.45); + assert.equal(payload.activeConversation.aggregated.role, '主代理 + 1 子代理 + 1 旁问'); + + // F. Verify mainline context watermark protection (backend aggregated + frontend auto-follow) + // Main agent has 3_000_000 tokens (1M in + 1M cache + 1M out), Side Question has 15_000/1_000_000 + assert.equal(payload.activeConversation.aggregated.activeAgentId, 'main'); + assert.equal(payload.activeConversation.aggregated.context.totalTokens, mainUnit.context.totalTokens); + + const scopedAuto = resolveScopedConversation(payload, 'all', 'auto', true); + assert.equal(scopedAuto.ctxAgent.agentId, 'main', 'auto context inspector locks onto mainline agent'); + const scopedExplicitSide = resolveScopedConversation(payload, 'all', sideCid, false); + assert.equal(scopedExplicitSide.ctxAgent.agentId, sideCid, 'explicitly selecting Side Question pill still inspects it'); + + // G. Verify zh-CN & en-US badge and label formatting + const prevLocale = i18nStore.getState().locale; + try { + i18nStore.setState({ locale: 'zh-CN', hostLocale: 'zh-CN' }); + assert.equal(formatAgentBadgeText(agents[2]), '旁1'); + assert.equal(formatAgentLabel(agents[2]), '旁路提问 #1 · 为什么用 WAL 模式?'); + + i18nStore.setState({ locale: 'en-US', hostLocale: 'en-US' }); + assert.equal(formatAgentBadgeText(agents[1]), 'S1'); + assert.equal(formatAgentBadgeText(agents[2]), 'Q1'); + assert.equal(formatAgentLabel(agents[2]), 'Side Question #1 · 为什么用 WAL 模式?'); + } finally { + i18nStore.setState({ locale: prevLocale }); + } + } finally { + await new Promise((resolve) => mockLsServer.close(resolve)); + rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('persistTrajectoryCacheIfNeeded throttles RUNNING disk writes to 30s and flushes immediately on IDLE or cache rebuild', () => { + let now = 1_000_000; + const scheduled = new Map(); + const h = backendHarness({ + cache: { live: { title: 'Cached session', steps: [] } }, + clock: () => now, + timerApi: { + setTimeout(_callback, delay) { + const id = Symbol(); + scheduled.set(id, delay); + return id; + }, + clearTimeout(id) { + scheduled.delete(id); + }, + }, + }); + + // 1st save (lastSavedAtMs === 0) flushes immediately even while running + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + assert.equal(h.state.saves.length, 1); + assert.equal(h.hasPendingTrajectoryCacheSave(), false); + + // Subsequent saves within 30s window while RUNNING are throttled in memory + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + assert.equal(h.state.saves.length, 1, '2s polling during RUNNING must not rewrite disk every tick'); + assert.equal(h.hasPendingTrajectoryCacheSave(), true); + assert.deepEqual([...scheduled.values()], [28_000]); + + // Transitioning to IDLE flushes immediately and clears pending timer + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: false, allowThrottleInTest: true }); + assert.equal(h.state.saves.length, 2, 'transition to IDLE flushes immediately'); + assert.equal(h.hasPendingTrajectoryCacheSave(), false); + assert.equal(scheduled.size, 0); + + // Re-arming throttle then calling executeRebuildCacheAction cancels timer cleanly + now += 2_000; + h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true }); + assert.equal(scheduled.size, 1); + h.state.cacheWriteError = new Error('Disk unavailable'); + assert.equal(h.executeRebuildCacheAction().status, 500); + assert.equal(h.getCachedTrajectory('live').title, 'Cached session'); + assert.equal(h.hasPendingTrajectoryCacheSave(), true); + assert.equal(scheduled.size, 1); + + h.state.cacheWriteError = null; + const rebuildRes = h.executeRebuildCacheAction(); + assert.equal(rebuildRes.ok, true); + assert.equal(scheduled.size, 0); + assert.equal(h.hasPendingTrajectoryCacheSave(), false); + assert.equal(h.listCachedTrajectoryEntries().length, 0); + assert.deepEqual(h.state.saves.at(-1).data, {}); +}); + +test('SQLite trajectory reader scans backwards past trailing plannerConfig-only gen_metadata rows to preserve pre-compaction tokenBreakdown', (t) => { + const sqliteMod = + typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null; + if (!sqliteMod?.DatabaseSync) { + t.skip('node:sqlite DatabaseSync unavailable'); + return; + } + const { DatabaseSync } = sqliteMod; + const tempRoot = mkdtempSync(join(tmpdir(), 'agy-sqlite-compact-')); + t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 })); + + const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee'; + const dbPath = join(tempRoot, `${cid}.db`); + const db = new DatabaseSync(dbPath); + db.exec(` + CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER); + CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB); + CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB); + `); + db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid); + db.prepare('INSERT INTO steps VALUES (0, 15, 3, ?, NULL)').run( + encodeStepMeta({ + createdSec: 1794960010, + finishedSec: 1794960014, + stepIndex: 0, + originCascadeId: cid, + modelEnumInt: 1429, + inputTokens: 10000, + cacheReadTokens: 110000, + outputTokens: 500, + }) + ); + // Step 1: CHECKPOINT compaction step (step_type = 23) + db.prepare('INSERT INTO steps VALUES (1, 23, 3, ?, NULL)').run( + encodeStepMeta({ + createdSec: 1794960020, + finishedSec: 1794960024, + stepIndex: 1, + originCascadeId: cid, + modelEnumInt: 1429, + inputTokens: 10000, + cacheReadTokens: 110000, + outputTokens: 2400, + thinkingTokens: 400, + responseTokens: 2000, + }) + ); + + // gen_metadata[0] has the full tokenBreakdown, followed by 3 plannerConfig-only records [1..3] + db.prepare('INSERT INTO gen_metadata VALUES (0, ?)').run( + encodeGenMeta({ + stepIndex: 0, + cascadeId: cid, + responseModel: 'gemini-4-carbon-high', + modelDisplayName: 'Gemini 4 Carbon (High)', + estimatedTokensUsed: 120_000, + maxContextTokens: 384_000, + userMsgTokens: 120_000, + }) + ); + const plannerOnlyBlob = encodeFieldBytes(3, encodeFieldBytes(28, 'gemini-4-carbon-high')); + db.prepare('INSERT INTO gen_metadata VALUES (1, ?)').run(plannerOnlyBlob); + db.prepare('INSERT INTO gen_metadata VALUES (2, ?)').run(plannerOnlyBlob); + db.prepare('INSERT INTO gen_metadata VALUES (3, ?)').run(plannerOnlyBlob); + db.close(); + + const res = readLocalSqliteTrajectory(dbPath, { cascadeId: cid }); + assert.ok(res); + assert.equal(res.steps.length, 2); + assert.equal(res.steps[1].type, 'CORTEX_STEP_TYPE_CHECKPOINT'); + const gm0 = res.generatorMetadata.find((g) => g.stepIndices.includes(0)); + assert.ok( + gm0?.chatModel?.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown?.groups?.length > 0, + 'must decode tokenBreakdown on gen_metadata[0] even with 3 trailing plannerConfig-only records' + ); +}); diff --git a/sidecars/panel/test/window-bridge.test.mjs b/sidecars/panel/test/window-bridge.test.mjs index b03a92e..a479c1f 100644 --- a/sidecars/panel/test/window-bridge.test.mjs +++ b/sidecars/panel/test/window-bridge.test.mjs @@ -6,6 +6,7 @@ import http from 'node:http'; import os from 'node:os'; import path from 'node:path'; import vm from 'node:vm'; +import { MockMutationObserver, createMockDom } from './mock-dom.mjs'; import { associateIdeIframeRoutes, createWindowBridgeController, @@ -19,6 +20,16 @@ import { resolveDevToolsPortCandidates, resolveIdeArgvPath, } from '../backend/window-bridge.mjs'; +import { + buildSanitizedDesktopRelaunchEnv, + buildWindowsRelaunchInnerScript, + ensureDesktopLaunchEntriesConfigured, + ensureRemoteDebugFlagInArgs, + patchLinuxDesktopEntryText, + patchWindowsRunRegistryCommand, + resolveDesktopHostExecutable, + triggerDesktopHostRelaunch, +} from '../backend/desktop-launcher-config.mjs'; import { discoverAntigravityLsEndpoint, parseLinuxProcNetTcpPorts, @@ -71,7 +82,7 @@ test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and stri assert.equal(winPaths[3], path.join('C:\\Local', 'Antigravity IDE', 'DevToolsActivePort')); const macPaths = resolveDevToolsPortCandidates({}, 'darwin', '/Users/dev'); - assert.equal(macPaths.length, 2); + assert.equal(macPaths.length, 6); assert.equal( macPaths[0], path.join('/Users/dev', 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort') @@ -80,6 +91,22 @@ test('DevToolsActivePort parsing, cross-platform discovery (2.0 + IDE), and stri macPaths[1], path.join('/Users/dev', 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort') ); + assert.equal( + macPaths[2], + path.join('/Users/dev', 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort') + ); + assert.equal( + macPaths[3], + path.join('/Users/dev', 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort') + ); + assert.equal( + macPaths[4], + path.join('/Users/dev', '.config', 'Antigravity', 'DevToolsActivePort') + ); + assert.equal( + macPaths[5], + path.join('/Users/dev', '.config', 'Antigravity IDE', 'DevToolsActivePort') + ); const linuxPaths = resolveDevToolsPortCandidates({ XDG_CONFIG_HOME: '/home/dev/.config' }, 'linux', '/home/dev'); assert.equal(linuxPaths.length, 2); @@ -330,11 +357,12 @@ test('CDP multi-window sync injects, skips healthy windows, hot-upgrades on vers const msg = JSON.parse(raw); if (msg.method === 'Runtime.evaluate') { const expr = msg.params.expression; - if (expr.includes('__AGUsageMonitorBridge =')) { + const ctx = windowContexts.get(this.targetId); + const previousBridge = ctx.__AGUsageMonitorBridge; + const value = vm.runInContext(expr, ctx); + if (ctx.__AGUsageMonitorBridge && ctx.__AGUsageMonitorBridge !== previousBridge) { injectEvalCount += 1; } - const ctx = windowContexts.get(this.targetId); - const value = vm.runInContext(expr, ctx); Promise.resolve(value).then((result) => this._emit('message', { data: JSON.stringify({ id: msg.id, result: { result: { value: result } } }), @@ -537,236 +565,40 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const appJs = fs.readFileSync(appJsPath, 'utf8'); const stylesCss = fs.readFileSync(stylesCssPath, 'utf8'); - // Minimal DOM mock supporting ShadowRoot, querySelector, attributes, classes, and composedPath - class MockNode { - constructor(tag = 'div') { - this.tagName = String(tag).toUpperCase(); - this.id = ''; - this.className = ''; - this.textContent = ''; - this.style = { - _vars: new Map(), - setProperty(k, v) { this._vars.set(k, String(v)); }, - getPropertyValue(k) { return this._vars.get(k) || ''; }, - removeProperty(k) { this._vars.delete(k); }, - }; - this.dataset = {}; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get parentElement() { return this.parentNode; } - get firstChild() { return this.children[0] || null; } - get firstElementChild() { return this.children[0] || null; } - get lastElementChild() { return this.children[this.children.length - 1] || null; } - get nextSibling() { - if (!this.parentNode) return null; - const idx = this.parentNode.children.indexOf(this); - return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { return this.attributes.has(k) ? this.attributes.get(k) : null; } - hasAttribute(k) { return this.attributes.has(k); } - removeAttribute(k) { this.attributes.delete(k); } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new MockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const idx = arr.indexOf(fn); - if (idx >= 0) arr.splice(idx, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - return { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 }; - } - querySelector(sel) { - if (sel === ':scope > div.shrink-0') { - return this.children.find((c) => c.classList.contains('shrink-0')) || null; - } - return this._find((n) => { - if (sel === '[class*="@container/titlebar"]') { - return String(n.className || '').includes('@container/titlebar'); - } - if (sel.startsWith('.')) { - return n.classList.contains(sel.slice(1)); - } - return false; - }); - } - querySelectorAll(sel) { - const s = String(sel || '').trim(); - if (!s || s.includes(',')) return []; - if (s.includes(' ')) { - const [first, ...rest] = s.split(/\s+/); - const roots = this.querySelectorAll(first); - const out = []; - for (const r of roots) { - for (const item of r.querySelectorAll(rest.join(' '))) { - if (!out.includes(item)) out.push(item); - } - } - return out; - } - if (!s.startsWith('.')) return []; - const cls = s.slice(1); - const out = []; - const walk = (node) => { - for (const c of node.children) { - if (c.classList.contains(cls)) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - _find(pred) { - for (const c of this.children) { - if (pred(c)) return c; - const hit = c._find(pred); - if (hit) return hit; - } - return null; - } - } - - const docRoot = new MockNode('html'); - docRoot.isDocumentRoot = true; - const body = new MockNode('body'); - docRoot.appendChild(body); - - // Build simulated Antigravity titlebar - const titlebar = new MockNode('div'); - titlebar.className = 'flex items-center @container/titlebar'; - const titleLeft = new MockNode('div'); - titleLeft.textContent = 'Chat Title'; - const titleRight = new MockNode('div'); - titleRight.className = 'shrink-0 flex items-center'; - const nativeBtn = new MockNode('button'); - titleRight.appendChild(nativeBtn); - titlebar.appendChild(titleLeft); - titlebar.appendChild(titleRight); - body.appendChild(titlebar); - let reloadCalled = false; let currentBundleVer = 'ver-100'; let currentAccountEmail = 'test@example.com'; let liveSubagentPollActive = false; const fetchedUrls = []; const fetchedHeaders = []; - - const docListeners = new Map(); + const createdForms = []; const winListeners = new Map(); - const mockDocument = { - readyState: 'complete', - hidden: false, - documentElement: docRoot, + const { + docRoot, body, - createElement: (tag) => new MockNode(tag), - createElementNS: (_ns, tag) => new MockNode(tag), - createTextNode: (txt) => { - const t = new MockNode('#text'); - t.textContent = String(txt); - return t; + document: mockDocument, + docListeners, + makeElement, + } = createMockDom({ + defaultRect: { left: 900, right: 1080, top: 6, bottom: 32, width: 180, height: 26 }, + onCreateElement: (node, tag) => { + if (tag === 'form') createdForms.push(node); }, - getElementById: (id) => docRoot._find((n) => n.id === id), - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: () => [], - addEventListener(type, fn) { - if (!docListeners.has(type)) docListeners.set(type, []); - docListeners.get(type).push(fn); - }, - removeEventListener(type, fn) { - const arr = docListeners.get(type); - if (!arr) return; - const i = arr.indexOf(fn); - if (i >= 0) arr.splice(i, 1); - }, - dispatchEvent(ev) { - for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev); - }, - }; + }); + + // Build simulated Antigravity titlebar + const titlebar = makeElement('div'); + titlebar.className = 'flex items-center @container/titlebar'; + const titleLeft = makeElement('div'); + titleLeft.textContent = 'Chat Title'; + const titleRight = makeElement('div'); + titleRight.className = 'shrink-0 flex items-center'; + const nativeBtn = makeElement('button'); + titleRight.appendChild(nativeBtn); + titlebar.appendChild(titleLeft); + titlebar.appendChild(titleRight); + body.appendChild(titlebar); const mockLocation = { pathname: '/c/aaaaaaaa-1111-2222-3333-bbbbbbbbbbbb', @@ -1416,7 +1248,11 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(liveDotSvg.attributes.get('width'), '11', 'Enlarged live activity SVG dot size is 11'); assert.equal(liveDotSvg.children[0].attributes.get('r'), '5', 'Enlarged dot circle radius is 5'); assert.match(stylesCss, /\.wm-multi-dot\s*\{\s*width:\s*8px;\s*height:\s*8px;/, 'Topbar multi-session dot enlarged to 8px'); - assert.match(stylesCss, /\.wm-hover-tip\s*\{[^}]*width:\s*min\(522px,\s*calc\(100vw - 24px\)\);/, 'Hover floating card width is 522px'); + assert.match( + stylesCss, + /\.wm-hover-tip\s*\{[^}]*width:\s*min\(calc\(522px \* var\(--ui-panel-scale, 1\)\),\s*calc\(100vw - 24px\)\);/, + 'Hover floating card base width is 522px and scales with --ui-panel-scale' + ); assert.equal(multiPanelEl.querySelector('.wm-recent-list'), null, 'Recent sessions list removed so panel shows online sessions only'); assert.equal(multiPanelEl.querySelector('.panel'), null, 'Single-layer multi-session panel without nested .panel box'); @@ -1557,19 +1393,25 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(mockSettings.themeAccent, 'host'); assert.equal(portalHost.style.getPropertyValue('--user-accent-primary'), '', 'Host accent clears override'); - // Font scale: switch to xl (1.15), verify portalHost scales while capsuleHost NEVER scales + // Font scale: switch to xl (1.28), verify portalHost and inner panels scale while capsuleHost NEVER scales assert.equal(fontScaleBtns.length, 4, 'Font scale segmented control has sm / md / lg / xl'); fontScaleBtns[3].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.fontScale, 'xl'); - assert.equal(portalHost.style.getPropertyValue('--ui-font-scale'), '1.15', 'Portal host scales to 1.15'); + assert.equal(portalHost.style.getPropertyValue('--ui-font-scale'), '1.28', 'Portal host scales to 1.28'); + assert.equal(portalHost.style.getPropertyValue('--ui-panel-scale'), '1.18', 'Portal host panel width scales to 1.18'); + assert.equal(popoverEl.getAttribute('data-font-scale'), 'xl', 'Popover panel receives data-font-scale'); + assert.equal(hoverTipEl.getAttribute('data-font-scale'), 'xl', 'Hover card receives data-font-scale'); + assert.equal(multiPanelEl.getAttribute('data-font-scale'), 'xl', 'Multi-session panel receives data-font-scale'); assert.equal(capsuleHost.style.getPropertyValue('--ui-font-scale'), '', 'Capsule host strictly excludes font scale'); assert.equal(capsuleHost.hasAttribute('data-font-scale'), false); fontScaleBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); await new Promise((r) => setTimeout(r, 30)); assert.equal(mockSettings.fontScale, 'md'); assert.equal(portalHost.style.getPropertyValue('--ui-font-scale'), ''); + assert.equal(portalHost.style.getPropertyValue('--ui-panel-scale'), ''); assert.equal(portalHost.getAttribute('data-font-scale'), 'md'); + assert.equal(popoverEl.getAttribute('data-font-scale'), 'md'); // Live i18n switch: zh-CN -> en-US -> zh-CN without page reload langBtns[1].dispatchEvent({ type: 'click', stopPropagation() {} }); @@ -1673,6 +1515,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro const previewCapsuleSlots = sec0.querySelectorAll('.wm-cap-slot'); const previewMultiBtn = sec0.querySelector('.wm-multi-btn'); assert.ok(previewCapsuleBar, 'Pane 0 mounts real CapsuleBarWidget preview'); + assert.equal(previewCapsuleBar.querySelector('.preview-win-controls'), null, 'No redundant 3 window dots after capsule'); assert.equal(previewCapsuleSlots.length, 5, 'Preview CapsuleBarWidget mounts real 5 capsule slots'); assert.equal(previewCapsuleSlots[0].children[0].textContent, '68.4 t/s', 'Preview slot 0 renders simulated speed'); assert.equal(previewCapsuleSlots[0].classList.contains('tone-good'), true, 'Preview capsule 68.4 t/s shares tone-good green with cards'); @@ -1910,6 +1753,21 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(sec2.hasAttribute('hidden'), false); const overviewPreviewHostEl = sec2.querySelector('.overview-modules-host'); assert.equal(overviewPreviewHostEl.children.length, 4, 'Overview preview mounts all 4 real overview widgets'); + assert.equal( + sec2.querySelector('.structure-preview-canvas').classList.contains('is-scaled'), + false, + 'Overview preview canvas renders 1:1 without zoom scaling' + ); + const previewCellSubs = Array.from(overviewPreviewHostEl.children[0].querySelectorAll('.cell-sub')).map( + (el) => el.textContent + ); + assert.ok(previewCellSubs.includes('均值 1.4s'), 'Preview TTFT card shows populated mean TTFT'); + assert.ok(previewCellSubs.includes('有效 23/24 步'), 'Preview Avg TPS card shows populated valid sample ratio'); + assert.equal( + overviewPreviewHostEl.children[2].querySelector('.panel-meta').textContent, + 'Google AI Ultra · Pro', + 'Preview quota badge matches real tier · plan format' + ); const [ovModWrap, ovMetricWrap] = sec2.querySelectorAll('.editable-slot-wrap'); // Move row 2 ('quotas') up above 'context' -> ['metrics', 'quotas', 'context', 'live_tasks'] @@ -2219,6 +2077,47 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro assert.equal(trendTooltipEl.hasAttribute('hidden'), false, 'Tooltip opens on heatmap cell hover'); assert.equal(activeCell.classList.contains('is-hovered'), true); assert.match(trendTooltipEl.querySelector('.trend-tip-tokens').textContent, /100\.0k tok/); + + // Crossing 2px inter-cell gaps keeps highlight/tooltip steady without flickering, and fast jumps snap to nearest cell + const hmBodyEl = heatmapStageEl.querySelector('.trend-heatmap-body'); + const hmTotalWeeks = Number(hmBodyEl.style.getPropertyValue('--hm-weeks')); + const origGridRectFn = hmGridEl.getBoundingClientRect; + hmGridEl.getBoundingClientRect = () => ({ + left: 100, + top: 200, + width: hmTotalWeeks * 10 - 2, + height: 7 * 10 - 2, + right: 100 + hmTotalWeeks * 10 - 2, + bottom: 200 + 7 * 10 - 2, + }); + const activeCol = Number(activeCell.getAttribute('data-hm-col')); + const activeRow = Number(activeCell.getAttribute('data-hm-row')); + hmGridEl.dispatchEvent({ type: 'mouseover', target: hmGridEl }); + assert.equal(trendTooltipEl.hasAttribute('hidden'), false, 'Container mouseover in gap does not blink tooltip'); + hmGridEl.dispatchEvent({ + type: 'mousemove', + target: hmGridEl, + clientX: 100 + activeCol * 10 + 9, + clientY: 200 + activeRow * 10 + 4, + }); + assert.equal(trendTooltipEl.hasAttribute('hidden'), false, 'Tooltip stays visible in 2px gap beside active cell'); + assert.equal(activeCell.classList.contains('is-hovered'), true, 'Active cell stays highlighted across bordering gap'); + + const snappedCol5Cell = realDayCells.find( + (c) => c.getAttribute('data-hm-col') === '5' && c.getAttribute('data-hm-row') === '2' + ); + assert.ok(snappedCol5Cell, 'Target cell at col=5,row=2 exists'); + hmGridEl.dispatchEvent({ + type: 'mousemove', + target: hmGridEl, + clientX: 100 + 5 * 10 + 8.4, + clientY: 200 + 2 * 10 + 4, + }); + assert.equal(trendTooltipEl.hasAttribute('hidden'), false, 'Tooltip stays visible when snapping across distant gap'); + assert.equal(activeCell.classList.contains('is-hovered'), false); + assert.equal(snappedCol5Cell.classList.contains('is-hovered'), true, 'Fast pointer jump into distant gap snaps to nearest cell'); + hmGridEl.getBoundingClientRect = origGridRectFn; + hmGridEl.dispatchEvent({ type: 'mouseleave' }); assert.equal(trendTooltipEl.hasAttribute('hidden'), true, 'Tooltip hides on mouseleave'); @@ -2702,6 +2601,9 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/ routes, pro 'Hover legend updates strictly in-place without DOM node replacement or appendChild' ); + assert.equal(createdForms.some((form) => form.className.includes('settings-account-form')), false); + assert.equal(fetchedUrls.some((url) => url.includes('/api/accounts')), false); + // Verify in-place bridge port rotation preserves exact DOM host nodes without remount fetchShouldFail = false; assert.equal(ov.updateBridge({ port: 51234, token: 'rotated-token-456' }), true); @@ -3009,245 +2911,37 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - class IdeMockNode { - constructor(tag = 'div') { - this.tagName = String(tag).toUpperCase(); - this.id = ''; - this.className = ''; - this.textContent = ''; - this._rect = { left: 0, right: 1440, top: 0, bottom: 35, width: 1440, height: 35 }; - this.dataset = {}; - const vars = new Map(); - this.style = { - marginLeft: '', - top: '', - right: '', - left: '', - maxHeight: '', - _vars: vars, - setProperty(k, v) { - vars.set(k, String(v)); - }, - removeProperty(k) { - vars.delete(k); - }, - getPropertyValue(k) { - return vars.get(k) || ''; - }, - }; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get parentElement() { - return this.parentNode; - } - get firstChild() { - return this.children[0] || null; - } - get firstElementChild() { - return this.children[0] || null; - } - get lastElementChild() { - return this.children[this.children.length - 1] || null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { - return this.attributes.has(k) ? this.attributes.get(k) : null; - } - hasAttribute(k) { - return this.attributes.has(k); - } - removeAttribute(k) { - this.attributes.delete(k); - } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new IdeMockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const idx = arr.indexOf(fn); - if (idx >= 0) arr.splice(idx, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - if (this._rect) return this._rect; - if (this._ownRect) return this._ownRect; - let cur = this.parentNode || this.host || null; - while (cur) { - if (cur._rect) return cur._rect; - if (cur._ownRect) return cur._ownRect; - cur = cur.parentNode || cur.host || null; - } - return { left: 820, right: 946, top: 810, bottom: 836, width: 126, height: 26 }; - } - matchesNode(sel) { - if (sel === '[class*="@container/titlebar"]') { - return String(this.className || '').includes('@container/titlebar'); - } - if (sel === '[data-testid="conversation-view"][data-cascade-id]') { - return ( - this.getAttribute('data-testid') === 'conversation-view' && - this.hasAttribute('data-cascade-id') - ); - } - if (sel === '[data-testid^="conversation-row-"][data-selected="true"][data-cascade-id]') { - return ( - String(this.getAttribute('data-testid') || '').startsWith('conversation-row-') && - this.getAttribute('data-selected') === 'true' && - this.hasAttribute('data-cascade-id') - ); - } - if (sel.startsWith('.')) { - const classes = sel.slice(1).split('.').filter(Boolean); - return classes.every((c) => this.classList.contains(c)); - } - return false; - } - querySelector(sel) { - if (sel.startsWith(':scope > ')) { - const rest = sel.slice(':scope > '.length).trim(); - if (rest === 'div.shrink-0') { - return this.children.find((c) => c.classList.contains('shrink-0')) || null; - } - return this.children.find((c) => c.matchesNode(rest)) || null; - } - return this._find((n) => n.matchesNode(sel)); - } - querySelectorAll(sel) { - const out = []; - const walk = (node) => { - for (const c of node.children) { - if (c.matchesNode(sel)) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - _find(pred) { - for (const c of this.children) { - if (pred(c)) return c; - const hit = c._find(pred); - if (hit) return hit; - } - return null; - } - } - - const docRoot = new IdeMockNode('html'); - docRoot.isDocumentRoot = true; - const head = new IdeMockNode('head'); - const body = new IdeMockNode('body'); - docRoot.appendChild(head); - docRoot.appendChild(body); + const { + docRoot, + body, + document: mockDocument, + makeElement: makeIdeNode, + } = createMockDom({ + defaultRect: { left: 0, right: 1440, top: 0, bottom: 35, width: 1440, height: 35 }, + inheritAncestorRect: true, + }); // Build Antigravity IDE .monaco-workbench with BOTH top window .part.titlebar AND inner chat @container/titlebar - const workbench = new IdeMockNode('div'); + const workbench = makeIdeNode('div'); workbench.className = 'monaco-workbench vs-dark'; - const partTitlebar = new IdeMockNode('div'); + const partTitlebar = makeIdeNode('div'); partTitlebar.className = 'part titlebar'; - const tbContainer = new IdeMockNode('div'); + const tbContainer = makeIdeNode('div'); tbContainer.className = 'titlebar-container has-center'; - const tbLeft = new IdeMockNode('div'); + const tbLeft = makeIdeNode('div', { left: 0, right: 60, top: 0, bottom: 35, width: 60, height: 35 }); tbLeft.className = 'titlebar-left'; - tbLeft._rect = { left: 0, right: 60, top: 0, bottom: 35, width: 60, height: 35 }; - const tbCenter = new IdeMockNode('div'); + const tbCenter = makeIdeNode('div', { left: 540, right: 900, top: 0, bottom: 35, width: 360, height: 35 }); tbCenter.className = 'titlebar-center'; - tbCenter._rect = { left: 540, right: 900, top: 0, bottom: 35, width: 360, height: 35 }; - const tbRight = new IdeMockNode('div'); + const tbRight = makeIdeNode('div', { left: 900, right: 1440, top: 0, bottom: 35, width: 540, height: 35 }); tbRight.className = 'titlebar-right'; - tbRight._rect = { left: 900, right: 1440, top: 0, bottom: 35, width: 540, height: 35 }; - const actionToolbar = new IdeMockNode('div'); + const actionToolbar = makeIdeNode('div', { left: 1170, right: 1300, top: 0, bottom: 35, width: 130, height: 35 }); actionToolbar.className = 'action-toolbar-container'; actionToolbar.style.marginLeft = 'auto'; - actionToolbar._rect = { left: 1170, right: 1300, top: 0, bottom: 35, width: 130, height: 35 }; - const winControls = new IdeMockNode('div'); + const winControls = makeIdeNode('div', { left: 1300, right: 1440, top: 0, bottom: 35, width: 140, height: 35 }); winControls.className = 'window-controls-container'; - winControls._rect = { left: 1300, right: 1440, top: 0, bottom: 35, width: 140, height: 35 }; tbRight.appendChild(actionToolbar); tbRight.appendChild(winControls); @@ -3258,15 +2952,15 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba workbench.appendChild(partTitlebar); // Inner chat pane header + conversation view - const innerChatHeader = new IdeMockNode('div'); + const innerChatHeader = makeIdeNode('div'); innerChatHeader.className = 'flex items-center @container/titlebar'; - const innerChatRight = new IdeMockNode('div'); + const innerChatRight = makeIdeNode('div'); innerChatRight.className = 'shrink-0 flex items-center'; - innerChatHeader.appendChild(new IdeMockNode('div')); + innerChatHeader.appendChild(makeIdeNode('div')); innerChatHeader.appendChild(innerChatRight); workbench.appendChild(innerChatHeader); - const convView = new IdeMockNode('div'); + const convView = makeIdeNode('div'); convView.setAttribute('data-testid', 'conversation-view'); convView.setAttribute('data-cascade-id', '12345678-aaaa-bbbb-cccc-1234567890ab'); workbench.appendChild(convView); @@ -3284,41 +2978,12 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba ]); const mutationObservers = []; - class MockMutationObserver { + class IdeMutationObserver extends MockMutationObserver { constructor(cb) { - this.cb = cb; - this.targets = []; - mutationObservers.push(this); - } - observe(target, options) { - this.targets.push({ target, options }); - } - disconnect() { - this.targets = []; + super(cb, mutationObservers); } } - const fetchedUrls = []; - const mockDocument = { - readyState: 'complete', - hidden: false, - activeElement: null, - documentElement: docRoot, - head, - body, - createElement: (tag) => new IdeMockNode(tag), - createElementNS: (_ns, tag) => new IdeMockNode(tag), - createTextNode: (txt) => { - const t = new IdeMockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => docRoot._find((n) => n.id === id), - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: (sel) => docRoot.querySelectorAll(sel), - addEventListener() {}, - removeEventListener() {}, - }; const mockWindow = { innerWidth: 1440, @@ -3387,7 +3052,7 @@ test('Compiled app.js in Antigravity IDE workbench.html docks into .part.titleba document: mockDocument, location: mockWindow.location, navigator: {}, - MutationObserver: MockMutationObserver, + MutationObserver: IdeMutationObserver, URLSearchParams, AbortController, setTimeout, @@ -3684,261 +3349,65 @@ test('Composer mount mode (输入框挂载) docks capsule immediately left of Au const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - class ComposerMockNode { - constructor(tag, rect = null) { - this.tagName = String(tag || 'div').toUpperCase(); - this.nodeName = this.tagName; - this.id = ''; - this.className = ''; - this._text = ''; - this._ownRect = rect || null; - this.style = { - marginLeft: '', - top: '', - left: '', - right: '', - height: '', - maxHeight: '', - _vars: new Map(), - setProperty(k, v) { - this._vars.set(k, String(v)); - }, - getPropertyValue(k) { - return this._vars.get(k) || ''; - }, - }; - this.dataset = {}; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get textContent() { - if (this.children.length === 0) return this._text; - return this._text + this.children.map((c) => c.textContent).join(''); - } - set textContent(v) { - this._text = String(v ?? ''); - this.children = []; - } - get parentElement() { - return this.parentNode; - } - get firstChild() { - return this.children[0] || null; - } - get firstElementChild() { - return this.children[0] || null; - } - get lastElementChild() { - return this.children[this.children.length - 1] || null; - } - get nextElementSibling() { - if (!this.parentNode) return null; - const idx = this.parentNode.children.indexOf(this); - return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { - return this.attributes.has(k) ? this.attributes.get(k) : null; - } - hasAttribute(k) { - return this.attributes.has(k); - } - removeAttribute(k) { - this.attributes.delete(k); - } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new ComposerMockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const i = arr.indexOf(fn); - if (i >= 0) arr.splice(i, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - if (this._rect) return this._rect; - if (this._ownRect) return this._ownRect; - let cur = this.parentNode || this.host || null; - while (cur) { - if (cur._rect) return cur._rect; - if (cur._ownRect) return cur._ownRect; - cur = cur.parentNode || cur.host || null; - } - return { left: 820, right: 946, top: 810, bottom: 836, width: 126, height: 26 }; - } - _matchesSingle(sel) { - const s = String(sel || '').trim(); - if (!s) return false; - if (s === '[class*="@container/titlebar"]') { - return String(this.className || '').includes('@container/titlebar'); - } - if (s.startsWith('.')) return this.classList.contains(s.slice(1)); - if (s.startsWith('[') && s.endsWith(']')) { - const inner = s.slice(1, -1); - const eqIdx = inner.indexOf('='); - if (eqIdx < 0) return this.hasAttribute(inner); - const attr = inner.slice(0, eqIdx).trim(); - const val = inner.slice(eqIdx + 1).trim().replace(/^['"]|['"]$/g, ''); - return this.getAttribute(attr) === val; - } - return this.tagName.toLowerCase() === s.toLowerCase(); - } - querySelector(sel) { - if (sel === ':scope > div.shrink-0') { - return this.children.find((c) => c.classList.contains('shrink-0')) || null; - } - return this.querySelectorAll(sel)[0] || null; - } - querySelectorAll(sel) { - const s = String(sel || '').trim(); - if (!s) return []; - const out = []; - const walk = (node) => { - for (const c of node.children) { - if (c._matchesSingle(s)) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - } - - const docRoot = new ComposerMockNode('html', { left: 0, right: 1440, top: 0, bottom: 900, width: 1440, height: 900 }); - docRoot.isDocumentRoot = true; - const body = new ComposerMockNode('body', { left: 0, right: 1440, top: 0, bottom: 900, width: 1440, height: 900 }); - docRoot.appendChild(body); + const { + body, + document: mockDocument, + makeElement: makeCompNode, + } = createMockDom({ + rootRect: { left: 0, right: 1440, top: 0, bottom: 900, width: 1440, height: 900 }, + defaultRect: { left: 820, right: 946, top: 810, bottom: 836, width: 126, height: 26 }, + inheritAncestorRect: true, + }); // 1. Topbar - const titlebar = new ComposerMockNode('div', { left: 0, right: 1440, top: 0, bottom: 38, width: 1440, height: 38 }); + const titlebar = makeCompNode('div', { left: 0, right: 1440, top: 0, bottom: 38, width: 1440, height: 38 }); titlebar.className = 'flex items-center @container/titlebar'; - const titleLeft = new ComposerMockNode('div', { left: 16, right: 220, top: 6, bottom: 32, width: 204, height: 26 }); + const titleLeft = makeCompNode('div', { left: 16, right: 220, top: 6, bottom: 32, width: 204, height: 26 }); titleLeft.textContent = 'Chat Title'; - const titleRight = new ComposerMockNode('div', { left: 1200, right: 1420, top: 6, bottom: 32, width: 220, height: 26 }); + const titleRight = makeCompNode('div', { left: 1200, right: 1420, top: 6, bottom: 32, width: 220, height: 26 }); titleRight.className = 'shrink-0 flex items-center'; - titleRight.appendChild(new ComposerMockNode('button', { left: 1380, right: 1412, top: 6, bottom: 32, width: 32, height: 26 })); + titleRight.appendChild(makeCompNode('button', { left: 1380, right: 1412, top: 6, bottom: 32, width: 32, height: 26 })); titlebar.appendChild(titleLeft); titlebar.appendChild(titleRight); body.appendChild(titlebar); // 2. Chat composer card at bottom: [+] [Gemini 4 Carbon High ^] ... [🛡️ Auto ^] [🎤] [→] - const composerCard = new ComposerMockNode('div', { left: 220, right: 1120, top: 700, bottom: 848, width: 900, height: 148 }); + const composerCard = makeCompNode('div', { left: 220, right: 1120, top: 700, bottom: 848, width: 900, height: 148 }); composerCard.className = 'rounded-2xl border p-3'; - const editorEl = new ComposerMockNode('textarea', { left: 236, right: 1104, top: 712, bottom: 796, width: 868, height: 84 }); + const editorEl = makeCompNode('textarea', { left: 236, right: 1104, top: 712, bottom: 796, width: 868, height: 84 }); editorEl.setAttribute('role', 'textbox'); - const toolbarRow = new ComposerMockNode('div', { left: 236, right: 1104, top: 808, bottom: 838, width: 868, height: 30 }); + const toolbarRow = makeCompNode('div', { left: 236, right: 1104, top: 808, bottom: 838, width: 868, height: 30 }); toolbarRow.className = 'flex items-center justify-between'; - const leftCluster = new ComposerMockNode('div', { left: 236, right: 446, top: 808, bottom: 838, width: 210, height: 30 }); + const leftCluster = makeCompNode('div', { left: 236, right: 446, top: 808, bottom: 838, width: 210, height: 30 }); leftCluster.className = 'flex items-center gap-1'; - const plusBtn = new ComposerMockNode('button', { left: 236, right: 264, top: 810, bottom: 836, width: 28, height: 26 }); + const plusBtn = makeCompNode('button', { left: 236, right: 264, top: 810, bottom: 836, width: 28, height: 26 }); plusBtn.textContent = '+'; - const modelBtn = new ComposerMockNode('button', { left: 270, right: 446, top: 810, bottom: 836, width: 176, height: 26 }); + const modelBtn = makeCompNode('button', { left: 270, right: 446, top: 810, bottom: 836, width: 176, height: 26 }); modelBtn.textContent = 'Gemini 4 Carbon High ^'; leftCluster.appendChild(plusBtn); leftCluster.appendChild(modelBtn); - const rightCluster = new ComposerMockNode('div', { left: 950, right: 1104, top: 808, bottom: 838, width: 154, height: 30 }); + const rightCluster = makeCompNode('div', { left: 950, right: 1104, top: 808, bottom: 838, width: 154, height: 30 }); rightCluster.className = 'flex items-center gap-1.5'; - const autoWrap = new ComposerMockNode('div', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); + const autoWrap = makeCompNode('div', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); autoWrap.className = 'relative'; - const autoBtn = new ComposerMockNode('button', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); - const shieldSvg = new ComposerMockNode('svg'); - const shieldTitle = new ComposerMockNode('title'); + const autoBtn = makeCompNode('button', { left: 950, right: 1028, top: 810, bottom: 836, width: 78, height: 26 }); + const shieldSvg = makeCompNode('svg'); + const shieldTitle = makeCompNode('title'); shieldTitle.textContent = 'Shield Icon'; shieldSvg.appendChild(shieldTitle); - const autoLabel = new ComposerMockNode('span'); + const autoLabel = makeCompNode('span'); autoLabel.textContent = 'Auto'; - const chevronSvg = new ComposerMockNode('svg'); + const chevronSvg = makeCompNode('svg'); autoBtn.appendChild(shieldSvg); autoBtn.appendChild(autoLabel); autoBtn.appendChild(chevronSvg); autoWrap.appendChild(autoBtn); - const micBtn = new ComposerMockNode('button', { left: 1034, right: 1062, top: 810, bottom: 836, width: 28, height: 26 }); + const micBtn = makeCompNode('button', { left: 1034, right: 1062, top: 810, bottom: 836, width: 28, height: 26 }); micBtn.setAttribute('aria-label', 'Voice input'); - const sendBtn = new ComposerMockNode('button', { left: 1068, right: 1100, top: 808, bottom: 838, width: 32, height: 30 }); + const sendBtn = makeCompNode('button', { left: 1068, right: 1100, top: 808, bottom: 838, width: 32, height: 30 }); sendBtn.setAttribute('aria-label', 'Send message'); rightCluster.appendChild(autoWrap); @@ -3964,35 +3433,6 @@ test('Composer mount mode (输入框挂载) docks capsule immediately left of Au topbarCapsuleSlots: ['context', 'tps', 'quota_auto'], }; - const mockDocument = { - readyState: 'complete', - hidden: false, - documentElement: docRoot, - body, - createElement: (tag) => new ComposerMockNode(tag), - createElementNS: (_ns, tag) => new ComposerMockNode(tag), - createTextNode: (txt) => { - const t = new ComposerMockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => { - const walk = (n) => { - if (n.id === id) return n; - for (const c of n.children) { - const hit = walk(c); - if (hit) return hit; - } - return null; - }; - return walk(docRoot); - }, - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: (sel) => docRoot.querySelectorAll(sel), - addEventListener() {}, - removeEventListener() {}, - }; - const mockWindow = { innerWidth: 1440, innerHeight: 900, @@ -4182,233 +3622,45 @@ test('Antigravity IDE composer mount mode (输入框挂载) docks inside extensi const appJs = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8'); const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8'); - class IdeChatMockNode { - constructor(tag = 'div', rect = null) { - this.tagName = String(tag).toUpperCase(); - this.id = ''; - this.className = ''; - this._text = ''; - this._rect = rect || { left: 0, right: 0, top: 0, bottom: 0, width: 0, height: 0 }; - this.dataset = {}; - const vars = new Map(); - this.style = { - display: '', - visibility: '', - opacity: '', - marginLeft: '', - top: '', - right: '', - left: '', - height: '', - maxHeight: '', - setProperty(k, v) { - vars.set(k, String(v)); - }, - removeProperty(k) { - vars.delete(k); - }, - getPropertyValue(k) { - return vars.get(k) || ''; - }, - }; - this.attributes = new Map(); - this.children = []; - this.parentNode = null; - this.shadowRoot = null; - this._listeners = new Map(); - const self = this; - this.classList = { - _set() { - return new Set(String(self.className || '').split(/\s+/).filter(Boolean)); - }, - add(...tokens) { - const s = this._set(); - for (const t of tokens) if (t) s.add(t); - self.className = Array.from(s).join(' '); - }, - contains(tok) { - return this._set().has(tok); - }, - toggle(tok, force) { - const s = this._set(); - const should = force === undefined ? !s.has(tok) : Boolean(force); - if (should) s.add(tok); - else s.delete(tok); - self.className = Array.from(s).join(' '); - }, - }; - } - get textContent() { - if (this.children.length === 0) return this._text; - return this._text + this.children.map((c) => c.textContent).join(''); - } - set textContent(v) { - this._text = String(v ?? ''); - this.children = []; - } - get parentElement() { - return this.parentNode; - } - get firstChild() { - return this.children[0] || null; - } - get firstElementChild() { - return this.children[0] || null; - } - get lastChild() { - return this.children[this.children.length - 1] || null; - } - get lastElementChild() { - return this.children[this.children.length - 1] || null; - } - get nextElementSibling() { - if (!this.parentNode) return null; - const idx = this.parentNode.children.indexOf(this); - return idx >= 0 ? this.parentNode.children[idx + 1] || null : null; - } - get isConnected() { - let cur = this; - while (cur) { - if (cur.isDocumentRoot) return true; - cur = cur.parentNode || cur.host || null; - } - return false; - } - setAttribute(k, v) { - const s = String(v); - this.attributes.set(k, s); - if (k === 'id') this.id = s; - if (k === 'class') this.className = s; - } - getAttribute(k) { - return this.attributes.has(k) ? this.attributes.get(k) : null; - } - hasAttribute(k) { - return this.attributes.has(k); - } - removeAttribute(k) { - this.attributes.delete(k); - } - appendChild(child) { - if (child.parentNode) child.parentNode.removeChild(child); - child.parentNode = this; - this.children.push(child); - return child; - } - insertBefore(node, refNode) { - if (!refNode) return this.appendChild(node); - if (node.parentNode) node.parentNode.removeChild(node); - const idx = this.children.indexOf(refNode); - node.parentNode = this; - if (idx < 0) this.children.push(node); - else this.children.splice(idx, 0, node); - return node; - } - removeChild(child) { - const idx = this.children.indexOf(child); - if (idx >= 0) { - this.children.splice(idx, 1); - child.parentNode = null; - } - return child; - } - remove() { - if (this.parentNode) this.parentNode.removeChild(this); - } - attachShadow() { - const sr = new IdeChatMockNode('#shadow-root'); - sr.host = this; - this.shadowRoot = sr; - return sr; - } - contains(other) { - let cur = other; - while (cur) { - if (cur === this) return true; - cur = cur.parentNode; - } - return false; - } - addEventListener(type, fn) { - if (!this._listeners.has(type)) this._listeners.set(type, []); - this._listeners.get(type).push(fn); - } - removeEventListener(type, fn) { - const arr = this._listeners.get(type); - if (!arr) return; - const i = arr.indexOf(fn); - if (i >= 0) arr.splice(i, 1); - } - dispatchEvent(ev) { - for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev); - } - getBoundingClientRect() { - if (this.id === 'ag-usage-monitor-capsule' || this.classList.contains('wm-capsule-btn')) { - return { left: 680, right: 830, top: 824, bottom: 850, width: 150, height: 26 }; - } - return this._rect; - } - matches(sel) { - if (sel === 'button') return this.tagName === 'BUTTON'; - if (sel === 'textarea') return this.tagName === 'TEXTAREA'; - if (sel === '[contenteditable]') return this.hasAttribute('contenteditable'); - if (sel === '[role="button"]') return this.getAttribute('role') === 'button'; - if (sel === '[role="textbox"]') return this.getAttribute('role') === 'textbox'; - if (sel === '[aria-haspopup]') return this.hasAttribute('aria-haspopup'); - if (sel === '[data-lexical-editor]') return this.hasAttribute('data-lexical-editor'); - if (sel.startsWith('.')) return this.classList.contains(sel.slice(1)); - return false; - } - querySelectorAll(sel) { - const parts = sel.split(',').map((s) => s.trim()).filter(Boolean); - const out = []; - const walk = (n) => { - for (const c of n.children) { - if (parts.some((p) => c.matches(p))) out.push(c); - walk(c); - } - }; - walk(this); - return out; - } - querySelector(sel) { - return this.querySelectorAll(sel)[0] || null; - } - } - - const docRoot = new IdeChatMockNode('html', { left: 0, right: 980, top: 0, bottom: 900, width: 980, height: 900 }); - docRoot.isDocumentRoot = true; - const head = new IdeChatMockNode('head'); - const body = new IdeChatMockNode('body', { left: 0, right: 980, top: 0, bottom: 900, width: 980, height: 900 }); - docRoot.appendChild(head); - docRoot.appendChild(body); + const { + body, + document: mockDoc, + makeElement: makeChatNode, + } = createMockDom({ + rootRect: { left: 0, right: 980, top: 0, bottom: 900, width: 980, height: 900 }, + defaultRect: { left: 0, right: 0, top: 0, bottom: 0, width: 0, height: 0 }, + resolveRect: (node) => + node.id === 'ag-usage-monitor-capsule' || node.classList.contains('wm-capsule-btn') + ? { left: 680, right: 830, top: 824, bottom: 850, width: 150, height: 26 } + : null, + }); // Header inside IDE chat pane (must NEVER be docked into inside extensionView iframe!) - const paneHeader = new IdeChatMockNode('header', { left: 0, right: 980, top: 0, bottom: 36, width: 980, height: 36 }); + const paneHeader = makeChatNode('header', { left: 0, right: 980, top: 0, bottom: 36, width: 980, height: 36 }); paneHeader.className = '@container/titlebar flex h-9 w-full items-center justify-between'; body.appendChild(paneHeader); // Antigravity IDE Composer Card: outer role="button" focus wrapper + Lexical/Monaco editor + [+] [Gemini 4 Carbon High ^] ... [->] - const outerFocusCard = new IdeChatMockNode('div', { left: 130, right: 882, top: 770, bottom: 862, width: 752, height: 92 }); + const outerFocusCard = makeChatNode('div', { left: 130, right: 882, top: 770, bottom: 862, width: 752, height: 92 }); outerFocusCard.setAttribute('role', 'button'); - const editorEl = new IdeChatMockNode('div', { left: 146, right: 866, top: 782, bottom: 816, width: 720, height: 34 }); + const editorEl = makeChatNode('div', { left: 146, right: 866, top: 782, bottom: 816, width: 720, height: 34 }); editorEl.setAttribute('contenteditable', 'true'); editorEl.setAttribute('data-lexical-editor', 'true'); - const toolbarRow = new IdeChatMockNode('div', { left: 146, right: 866, top: 822, bottom: 852, width: 720, height: 30 }); + const toolbarRow = makeChatNode('div', { left: 146, right: 866, top: 822, bottom: 852, width: 720, height: 30 }); toolbarRow.className = 'flex items-center justify-between'; - const leftCluster = new IdeChatMockNode('div', { left: 146, right: 340, top: 822, bottom: 852, width: 194, height: 30 }); - const plusBtn = new IdeChatMockNode('button', { left: 146, right: 172, top: 824, bottom: 850, width: 26, height: 26 }); + const leftCluster = makeChatNode('div', { left: 146, right: 340, top: 822, bottom: 852, width: 194, height: 30 }); + const plusBtn = makeChatNode('button', { left: 146, right: 172, top: 824, bottom: 850, width: 26, height: 26 }); plusBtn.textContent = '+'; - const modelBtn = new IdeChatMockNode('div', { left: 178, right: 336, top: 824, bottom: 850, width: 158, height: 26 }); + const modelBtn = makeChatNode('div', { left: 178, right: 336, top: 824, bottom: 850, width: 158, height: 26 }); modelBtn.setAttribute('aria-haspopup', 'menu'); modelBtn.textContent = 'Gemini 4 Carbon High'; leftCluster.appendChild(plusBtn); leftCluster.appendChild(modelBtn); - const rightCluster = new IdeChatMockNode('div', { left: 836, right: 866, top: 822, bottom: 852, width: 30, height: 30 }); - const sendBtn = new IdeChatMockNode('button', { left: 838, right: 866, top: 823, bottom: 851, width: 28, height: 28 }); - const arrowIcon = new IdeChatMockNode('span'); + const rightCluster = makeChatNode('div', { left: 836, right: 866, top: 822, bottom: 852, width: 30, height: 30 }); + const sendBtn = makeChatNode('button', { left: 838, right: 866, top: 823, bottom: 851, width: 28, height: 28 }); + const arrowIcon = makeChatNode('span'); arrowIcon.className = 'codicon codicon-arrow-right'; arrowIcon.textContent = 'arrow_forward'; sendBtn.appendChild(arrowIcon); @@ -4427,36 +3679,6 @@ test('Antigravity IDE composer mount mode (输入框挂载) docks inside extensi topbarCapsuleSlots: ['context', 'tps', 'quota_auto'], }; - const mockDoc = { - readyState: 'complete', - hidden: false, - documentElement: docRoot, - head, - body, - createElement: (tag) => new IdeChatMockNode(tag), - createElementNS: (_ns, tag) => new IdeChatMockNode(tag), - createTextNode: (txt) => { - const t = new IdeChatMockNode('#text'); - t.textContent = String(txt); - return t; - }, - getElementById: (id) => { - const walk = (n) => { - if (n.id === id) return n; - for (const c of n.children) { - const hit = walk(c); - if (hit) return hit; - } - return null; - }; - return walk(docRoot); - }, - querySelector: (sel) => docRoot.querySelector(sel), - querySelectorAll: (sel) => docRoot.querySelectorAll(sel), - addEventListener() {}, - removeEventListener() {}, - }; - const chatConvId = 'a4206937-54dd-4d4e-a161-813719bf7107'; const buildIdeChatTelemetry = () => ({ uiBundleVersion: 'ver-ide-comp-1', @@ -5357,163 +4579,15 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP 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'); + const { + body, + document: mockDoc, + } = createMockDom({ + resolveRect: (el) => { + const w = Number.parseFloat(el.style.width) || el.offsetWidth || 120; + return { left: 900, right: 900 + w, top: 8, bottom: 36, width: w, height: 28 }; + }, + }); let failHttpOnce = false; const mockWin = { innerWidth: 1280, @@ -5540,21 +4614,6 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP 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, @@ -5658,3 +4717,661 @@ test('v1.5 feedback E2E: sticky bridge port/token across hot-reloads, CDP->HTTP ov.dispose(); } }); + +test('WindowOverlayShell macOS (darwin) adaptation: sets data-os="mac", uses 12px fixed right fallback, and reserves 80px for traffic lights', async () => { + const panelDir = path.resolve(import.meta.dirname, '..'); + const appJs = fs.readFileSync(path.join(panelDir, 'app.js'), 'utf8'); + const stylesCss = fs.readFileSync(path.join(panelDir, 'styles.css'), 'utf8'); + assert.match(stylesCss, /:host\(\.wm-capsule-host\[data-dock="fixed"\]\[data-os="mac"\]\)\s*\{\s*right:\s*12px;/); + + function runOverlayForPlatform(platformKey, { withTitlebar = false, auxLeft = 0, winWidth = 1280 } = {}) { + const { + body, + document: mockDoc, + makeElement: makeNode, + } = createMockDom({ + defaultRect: { left: 0, right: 64, top: 6, bottom: 34, width: 64, height: 28 }, + }); + + if (withTitlebar) { + const tb = makeNode('div'); + tb.className = 'flex @container/titlebar'; + tb.setRect({ left: 0, right: winWidth, top: 0, bottom: 36, width: winWidth, height: 36 }); + const titleGroup = makeNode('div'); + const rightGroup = makeNode('div'); + rightGroup.className = 'shrink-0'; + const siblingBtn = makeNode('button'); + siblingBtn.setRect({ left: winWidth - 56, right: winWidth, top: 4, bottom: 32, width: 56, height: 28 }); + rightGroup.appendChild(siblingBtn); + tb.appendChild(titleGroup); + tb.appendChild(rightGroup); + body.appendChild(tb); + } else if (auxLeft > 0) { + const auxBtn = makeNode('button'); + auxBtn.setAttribute('data-testid', 'toggle-aux-sidebar'); + auxBtn.setRect({ left: auxLeft, right: auxLeft + 28, top: 8, bottom: 34, width: 28, height: 26 }); + body.appendChild(auxBtn); + } + + const payload = { + timestamp: '2026-11-17T00:00:00Z', + hostPlatform: platformKey, + settings: { windowMountMode: 'dual', enableWindowOverlay: true, showTopbarMultiSession: true, topbarCapsuleSlots: ['tps', 'ttft', 'context'] }, + cloudStatus: { updateAvailable: false }, + account: { planName: 'Pro' }, + runningConversations: [], + conversations: [], + activeConversation: { cascadeId: '11111111-2222-3333-4444-555555555555', stepCount: 1, context: { totalTokens: 10000, limitTokens: 256000 } }, + quotas: { pools: [] }, + }; + + const mockWin = { + innerWidth: winWidth, + innerHeight: 800, + location: { pathname: '/c/11111111-2222-3333-4444-555555555555', search: '' }, + __AGUsageMonitorBridge: { + port: 43111, + token: 'c'.repeat(64), + bundleVersion: 'ver-mac', + platform: platformKey, + stylesCss, + initialTelemetry: payload, + }, + addEventListener() {}, + removeEventListener() {}, + getComputedStyle: () => ({ paddingRight: '8px', getPropertyValue: () => '' }), + fetch: async () => ({ ok: true, status: 200, json: async () => payload }), + }; + const sb = { + window: mockWin, + document: mockDoc, + navigator: { language: 'zh-CN', platform: platformKey === 'darwin' ? 'MacIntel' : 'Win32' }, + 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, + RegExp, + Error, + TypeError, + parseFloat, + parseInt, + isNaN, + Infinity, + }; + sb.globalThis = sb; + vm.runInNewContext(appJs, sb); + const cap = body._foundCap || (function findCap(n) { + if (n.id === 'ag-usage-monitor-capsule') return n; + for (const c of n.children || []) { const r = findCap(c); if (r) return r; } + return null; + })(body); + return { ov: mockWin.__AGUsageMonitorOverlay, cap }; + } + + // 1. Fixed fallback without native anchor: macOS uses 12px right inset vs Windows 144px window-controls reserve + const macFixed = runOverlayForPlatform('darwin'); + const winFixed = runOverlayForPlatform('win32'); + try { + assert.equal(macFixed.cap.getAttribute('data-os'), 'mac'); + assert.equal(macFixed.cap.style.right, '12px'); + assert.equal(winFixed.cap.getAttribute('data-os'), 'default'); + assert.equal(winFixed.cap.style.right, '144px'); + } finally { + macFixed.ov.dispose(); + winFixed.ov.dispose(); + } + + // 2. Fixed fallback with native top-right button at x=1230 on 1280px viewport: macOS hugs button at 56px instead of jumping to 144px + const macAnchored = runOverlayForPlatform('darwin', { auxLeft: 1230, winWidth: 1280 }); + try { + assert.equal(macAnchored.cap.style.right, '56px'); + } finally { + macAnchored.ov.dispose(); + } + + // 3. Flow titlebar narrow window (610px): macOS 80px traffic-light reserve retains 'wide' capsule while Windows 168px reserve collapses + const macNarrowFlow = runOverlayForPlatform('darwin', { withTitlebar: true, winWidth: 610 }); + const winNarrowFlow = runOverlayForPlatform('win32', { withTitlebar: true, winWidth: 610 }); + try { + assert.equal(macNarrowFlow.cap.getAttribute('data-layout'), 'wide'); + assert.notEqual(winNarrowFlow.cap.getAttribute('data-layout'), 'wide'); + } finally { + macNarrowFlow.ov.dispose(); + winNarrowFlow.ov.dispose(); + } +}); + +test('Issue #26: Antigravity Desktop 2.33.0+ automatic shortcut/launcher provisioning, out-of-job host relaunch, and global/settings BridgeStatusNotice UI', async () => { + // 1. Fresh IDE argv.json remains strict-JSON parseable + const fresh = ensureRemoteDebuggingInArgvText(''); + assert.deepEqual(JSON.parse(fresh.text), { 'remote-debugging-port': '0' }); + + // 2. Pure argument / HKCU Run / Linux .desktop patchers & non-destructive rollback + const addedEmpty = ensureRemoteDebugFlagInArgs('', { enabled: true }); + assert.equal(addedEmpty.changed, true); + assert.equal(addedEmpty.args, '--remote-debugging-port=0'); + + const preservedCustom = ensureRemoteDebugFlagInArgs('--foo --remote-debugging-port=9229', { + enabled: true, + }); + assert.equal(preservedCustom.changed, false); + assert.equal(preservedCustom.alreadyConfigured, true); + + const preservedCustomOnDisable = ensureRemoteDebugFlagInArgs( + '--foo --remote-debugging-port=9229', + { enabled: false } + ); + assert.equal(preservedCustomOnDisable.changed, false); + assert.equal(preservedCustomOnDisable.configured, true); + + const strippedManaged = ensureRemoteDebugFlagInArgs('--hidden --remote-debugging-port=0 --bar', { + enabled: false, + }); + assert.equal(strippedManaged.changed, true); + assert.equal(strippedManaged.removed, true); + assert.equal(strippedManaged.args, '--hidden --bar'); + + const winRunDesktop = patchWindowsRunRegistryCommand( + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" --hidden', + { enabled: true } + ); + assert.equal(winRunDesktop.matched, true); + assert.equal(winRunDesktop.changed, true); + assert.equal( + winRunDesktop.value, + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" --hidden --remote-debugging-port=0' + ); + const winRunRollback = patchWindowsRunRegistryCommand(winRunDesktop.value, { enabled: false }); + assert.equal(winRunRollback.changed, true); + assert.equal( + winRunRollback.value, + '"C:\\Users\\Dev\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe" --hidden' + ); + const winRunIdeIgnored = patchWindowsRunRegistryCommand( + '"C:\\Program Files\\Antigravity IDE\\Antigravity IDE.exe"', + { enabled: true } + ); + assert.equal(winRunIdeIgnored.matched, false); + + const linuxDesktopRaw = [ + '[Desktop Entry]', + 'Name=Antigravity', + 'Exec=/opt/Antigravity/antigravity %U', + 'Type=Application', + '', + ].join('\n'); + const linuxPatched = patchLinuxDesktopEntryText(linuxDesktopRaw, { enabled: true }); + assert.equal(linuxPatched.matched, true); + assert.equal(linuxPatched.changed, true); + assert.match(linuxPatched.text, /Exec=\/opt\/Antigravity\/antigravity --remote-debugging-port=0 %U/); + const linuxReverted = patchLinuxDesktopEntryText(linuxPatched.text, { enabled: false }); + assert.equal(linuxReverted.changed, true); + assert.equal(linuxReverted.text, linuxDesktopRaw); + + // 3. Host executable resolution from ANTIGRAVITY_AGENTAPI_EXE & clean relaunch env sanitization + const resolvedWinHost = resolveDesktopHostExecutable({ + env: { + ANTIGRAVITY_AGENTAPI_EXE: + 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Antigravity\\resources\\bin\\language_server_windows_x64.exe', + }, + platform: 'win32', + homeDir: 'C:\\Users\\Administrator', + existsFn: (p) => + p.replace(/\//g, '\\') === + 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe', + }); + assert.equal(resolvedWinHost.found, true); + assert.equal(resolvedWinHost.kind, 'desktop'); + assert.equal( + resolvedWinHost.executablePath.replace(/\//g, '\\'), + 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Antigravity\\Antigravity.exe' + ); + + const resolvedMacHost = resolveDesktopHostExecutable({ + env: { + ANTIGRAVITY_AGENTAPI_EXE: + '/Applications/Antigravity.app/Contents/Resources/bin/language_server_darwin_arm64', + }, + platform: 'darwin', + homeDir: '/Users/dev', + existsFn: (p) => + p === '/Applications/Antigravity.app' || + p === '/Applications/Antigravity.app/Contents/MacOS/Antigravity', + }); + assert.equal(resolvedMacHost.found, true); + assert.equal(resolvedMacHost.appBundlePath, '/Applications/Antigravity.app'); + + const sanitizedEnv = buildSanitizedDesktopRelaunchEnv({ + PATH: 'C:\\Windows\\System32', + USERPROFILE: 'C:\\Users\\Administrator', + ANTIGRAVITY_LS_ADDRESS: 'localhost:13088', + ANTIGRAVITY_CSRF_TOKEN: 'secret', + CHROME_DEVTOOLS_MCP_JS: 'C:\\foo.js', + USAGE_MONITOR_HOST_PPID: '123', + ELECTRON_RUN_AS_NODE: '1', + NODE_OPTIONS: '--inspect', + }); + assert.deepEqual(sanitizedEnv, { + PATH: 'C:\\Windows\\System32', + USERPROFILE: 'C:\\Users\\Administrator', + }); + + // 4. Linux .desktop provisioning on real temp dir + Windows shortcut provisioning + stale DevToolsActivePort (cdp_unreachable) + relaunch dispatch + const simTmp = fs.mkdtempSync(path.join(os.tmpdir(), 'ag-233-auto-')); + const homeDir = path.join(simTmp, 'home'); + const roamingDir = path.join(homeDir, 'AppData', 'Roaming'); + const localDir = path.join(homeDir, 'AppData', 'Local'); + const desktopRoamingDir = path.join(roamingDir, 'Antigravity'); + const fakeExe = path.join(localDir, 'Programs', 'Antigravity', 'Antigravity.exe'); + const leaseFile = path.join(simTmp, 'window-bridge-lease.json'); + fs.mkdirSync(desktopRoamingDir, { recursive: true }); + fs.mkdirSync(path.dirname(fakeExe), { recursive: true }); + fs.writeFileSync(fakeExe, '', 'utf8'); + + // Simulate stale DevToolsActivePort left behind by 2.32.x pointing to a closed port + const stalePortServer = http.createServer(); + await new Promise((r) => stalePortServer.listen(0, '127.0.0.1', r)); + const deadPort = stalePortServer.address().port; + await new Promise((r) => stalePortServer.close(r)); + const stalePortFile = path.join(desktopRoamingDir, 'DevToolsActivePort'); + fs.writeFileSync(stalePortFile, `${deadPort}\n/devtools/browser/stale-232\n`, 'utf8'); + + const simEnv = { + PATH: 'C:\\Windows\\System32', + APPDATA: roamingDir, + LOCALAPPDATA: localDir, + ANTIGRAVITY_AGENTAPI_EXE: path.join( + localDir, + 'Programs', + 'Antigravity', + 'resources', + 'bin', + 'language_server_windows_x64.exe' + ), + ANTIGRAVITY_LS_ADDRESS: 'localhost:13088', + }; + + try { + // Verify Linux XDG .desktop copy + autostart provisioning in isolated temp home + const linuxDataHome = path.join(simTmp, 'xdg-data'); + const linuxCfgHome = path.join(simTmp, 'xdg-config'); + const linuxAutostart = path.join(linuxCfgHome, 'autostart', 'antigravity.desktop'); + fs.mkdirSync(path.dirname(linuxAutostart), { recursive: true }); + fs.writeFileSync(linuxAutostart, linuxDesktopRaw, 'utf8'); + const sysDesktopPath = '/usr/share/applications/antigravity.desktop'; + const linuxProv = await ensureDesktopLaunchEntriesConfigured({ + enabled: true, + env: { XDG_DATA_HOME: linuxDataHome, XDG_CONFIG_HOME: linuxCfgHome }, + platform: 'linux', + homeDir, + allowInTest: true, + fsOps: { + existsFn: (p) => (p === sysDesktopPath ? true : fs.existsSync(p)), + readFn: (p, enc) => (p === sysDesktopPath ? linuxDesktopRaw : fs.readFileSync(p, enc)), + writeFn: fs.writeFileSync, + mkdirFn: fs.mkdirSync, + renameFn: fs.renameSync, + unlinkFn: fs.unlinkSync, + }, + }); + assert.equal(linuxProv.updated, true); + assert.equal(linuxProv.configured, true); + assert.equal(linuxProv.updatedPaths.length, 2); + assert.match( + fs.readFileSync(path.join(linuxDataHome, 'applications', 'antigravity.desktop'), 'utf8'), + /--remote-debugging-port=0 %U/ + ); + + // Verify Windows shortcut auto-provisioning + stale port (`cdp_unreachable`) status reporting + clean rollback on disable + const winPsCalls = []; + const mockWinExec = async (file, args, opts) => { + winPsCalls.push({ file, args, env: opts?.env }); + const enabledFlag = opts?.env?.AGY_LAUNCH_ENABLED === '1'; + return JSON.stringify({ + ok: true, + updatedPaths: enabledFlag + ? ['C:\\Users\\Admin\\Desktop\\Antigravity.lnk', 'C:\\TaskBar\\Antigravity.lnk'] + : ['C:\\Users\\Admin\\Desktop\\Antigravity.lnk'], + configuredPaths: enabledFlag + ? ['C:\\Users\\Admin\\Desktop\\Antigravity.lnk', 'C:\\TaskBar\\Antigravity.lnk'] + : [], + }); + }; + + let currentMountSettings = { + windowMountMode: 'dual', + enableWindowOverlay: true, + modelContextWindows: {}, + }; + const ctrlWin = createWindowBridgeController({ + handleApiRequest: async () => ({ status: 200, body: '{}' }), + readAssetFn: async () => '', + getSettingsFn: () => currentMountSettings, + getBundleVersionFn: () => '201', + env: simEnv, + platform: 'win32', + homeDir, + leaseFilePath: leaseFile, + autoConfigureIdeArgv: true, + launcherExecFileFn: mockWinExec, + allowDesktopLauncherInTest: true, + }); + + const syncRes = await ctrlWin.syncAllWindows(); + assert.equal(syncRes.reason, 'cdp_unreachable', 'Stale 2.32.x port surfaces cdp_unreachable'); + const stWin = ctrlWin.getBridgeStatus(); + assert.equal(stWin.state, 'cdp_unreachable'); + assert.equal(stWin.argvUpdatedThisBoot, true); + assert.equal(stWin.launcherConfigured, true); + assert.equal(stWin.canRelaunch, true); + assert.equal(winPsCalls.length, 1); + assert.equal(winPsCalls[0].env.AGY_LAUNCH_ENABLED, '1'); + + // Disabling overlay (Sidebar Only) cleanly triggers shortcut flag rollback + currentMountSettings = { + windowMountMode: 'sidebar', + enableWindowOverlay: false, + modelContextWindows: {}, + }; + await ctrlWin.notifySettingChanged(false); + await new Promise((r) => setTimeout(r, 10)); + assert.equal(winPsCalls.length, 2); + assert.equal(winPsCalls[1].env.AGY_LAUNCH_ENABLED, '0'); + await ctrlWin.stop(); + + // Verify Windows out-of-job Shell.Application relaunch payload (.ps1 file with UTF-8 BOM) & macOS open -a relaunch + let capturedRelaunchEnv = null; + let capturedRelaunchArgs = null; + const relaunchWinRes = await triggerDesktopHostRelaunch({ + env: { ...simEnv, TEMP: simTmp }, + platform: 'win32', + homeDir, + stalePortFiles: [stalePortFile], + allowInTest: true, + execFileFn: async (_file, args, opts) => { + capturedRelaunchArgs = args; + capturedRelaunchEnv = opts?.env; + return '{"ok":true,"method":"shell_application"}'; + }, + }); + assert.equal(relaunchWinRes.ok, true); + assert.equal(relaunchWinRes.relaunching, true); + assert.equal(capturedRelaunchArgs.includes('-Sta'), true, 'Forces STA for Shell.Application COM'); + assert.equal(capturedRelaunchEnv.ANTIGRAVITY_LS_ADDRESS, undefined, 'Strips host LS env'); + assert.equal(fs.existsSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1), true); + const writtenPs1 = fs.readFileSync(capturedRelaunchEnv.AGY_RELAUNCH_PS1, 'utf8'); + assert.equal(writtenPs1.startsWith('\uFEFF'), true, 'Writes UTF-8 BOM for Windows PowerShell 5.1'); + assert.match(writtenPs1, /--remote-debugging-port=0/); + assert.ok(writtenPs1.includes(stalePortFile)); + + // Verify dynamic running-process path discovery when installed on custom non-default drive (e.g. D:\Apps\Antigravity) + const customDriveRes = await triggerDesktopHostRelaunch({ + env: { TEMP: simTmp }, + platform: 'win32', + homeDir: path.join(simTmp, 'empty-home'), + allowInTest: true, + existsFn: () => false, + execFileFn: async (_file, args) => { + const cmdStr = args.join(' '); + if (cmdStr.includes('Get-Process')) { + return JSON.stringify({ path: 'D:\\Apps\\Antigravity\\Antigravity.exe', name: 'Antigravity' }); + } + return '{"ok":true,"method":"shell_application"}'; + }, + }); + assert.equal(customDriveRes.ok, true); + assert.equal(customDriveRes.executablePath, 'D:\\Apps\\Antigravity\\Antigravity.exe'); + + let macSpawnArgs = null; + const relaunchMacRes = await triggerDesktopHostRelaunch({ + env: { + PATH: '/usr/bin:/bin', + ANTIGRAVITY_AGENTAPI_EXE: + '/Applications/Antigravity.app/Contents/Resources/bin/language_server_darwin_arm64', + }, + platform: 'darwin', + homeDir: '/Users/dev', + stalePortFiles: ['/Users/dev/Library/Application Support/Antigravity/DevToolsActivePort'], + allowInTest: true, + existsFn: (p) => p === '/Applications/Antigravity.app', + spawnFn: async (file, args, opts) => { + macSpawnArgs = { file, args, env: opts?.env }; + return { pid: 4321 }; + }, + }); + assert.equal(relaunchMacRes.ok, true); + assert.equal(macSpawnArgs.env.AGY_RELAUNCH_APP, '/Applications/Antigravity.app'); + assert.match(macSpawnArgs.args[1], /open -a "\$AGY_RELAUNCH_APP" --args --remote-debugging-port=0/); + + // Explicit ANTIGRAVITY_DEVTOOLS_PORT fallback still works seamlessly + const innerScriptCheck = buildWindowsRelaunchInnerScript(fakeExe, [stalePortFile], 'desktop'); + assert.match(innerScriptCheck, /CloseMainWindow/); + assert.match(innerScriptCheck, /Stop-Process/); + } finally { + fs.rmSync(simTmp, { recursive: true, force: true }); + } + + // 5. Verify zh-CN / en-US i18n parity & BridgeStatusNotice one-click relaunch + dismiss + copy behavior + const [ + { I18N_MESSAGES_ZH_CN }, + { I18N_MESSAGES_EN_US }, + { setI18nLanguage }, + { SettingsStructureTab }, + { SettingsOtherTab }, + { BridgeStatusNotice }, + ] = await Promise.all([ + import('../src/i18n/zh-CN.js'), + import('../src/i18n/en-US.js'), + import('../src/i18n/index.js'), + import('../src/views/settings/SettingsStructureTab.js'), + import('../src/views/settings/SettingsOtherTab.js'), + import('../src/components/settings/BridgeStatusNotice.js'), + ]); + + assert.deepEqual( + Object.keys(I18N_MESSAGES_ZH_CN).sort(), + Object.keys(I18N_MESSAGES_EN_US).sort() + ); + + const { document: mockDoc } = createMockDom(); + const prevDoc = globalThis.document; + const prevNav = globalThis.navigator; + const prevFetch = globalThis.fetch; + let copiedClipboardText = ''; + const fetchedUrls = []; + globalThis.document = mockDoc; + globalThis.fetch = async (url, opts) => { + fetchedUrls.push({ url: String(url), method: opts?.method || 'GET' }); + return { + ok: true, + status: 200, + json: async () => ({ ok: true, relaunching: true }), + text: async () => JSON.stringify({ ok: true, relaunching: true }), + }; + }; + Object.defineProperty(globalThis, 'navigator', { + value: { + clipboard: { + writeText: async (txt) => { + copiedClipboardText = txt; + }, + }, + }, + configurable: true, + }); + + try { + setI18nLanguage('zh-CN'); + const strTab = SettingsStructureTab({}); + const noticeEl = strTab.refs.mountBridgeNotice.el; + assert.equal(noticeEl.hasAttribute('hidden'), true, 'Hidden before bridge status arrives'); + + // Stale DevToolsActivePort (`cdp_unreachable`) with auto-patched shortcuts -> shows blue `.is-restart` + 1-click relaunch button! + strTab.refs.renderSettings( + { windowMountMode: 'dual', enableWindowOverlay: true }, + { + state: 'cdp_unreachable', + argvUpdatedThisBoot: false, + argvConfigured: true, + launcherConfigured: true, + canRelaunch: true, + }, + 'win32' + ); + assert.equal(noticeEl.hasAttribute('hidden'), false); + assert.equal(noticeEl.classList.contains('is-restart'), true); + assert.match(noticeEl.textContent, /已自动补齐启动参数/); + assert.equal( + strTab.refs.mountBridgeNotice.refs.relaunchBtnEl.hasAttribute('hidden'), + false + ); + + // Click 1-click relaunch button -> POST /api/bridge/relaunch & shows "正在重启客户端..." + strTab.refs.mountBridgeNotice.refs.relaunchBtnEl.dispatchEvent({ type: 'click' }); + await new Promise((r) => setTimeout(r, 0)); + assert.equal( + fetchedUrls.some((u) => u.url.endsWith('/api/bridge/relaunch') && u.method === 'POST'), + true + ); + assert.match(strTab.refs.mountBridgeNotice.refs.relaunchBtnEl.textContent, /正在重启客户端/); + + // macOS unconfigured state -> `.is-warn` with 1-click relaunch + copy button + strTab.refs.renderSettings( + { windowMountMode: 'dual', enableWindowOverlay: true }, + { + state: 'no_devtools_port', + argvUpdatedThisBoot: false, + argvConfigured: false, + launcherConfigured: false, + canRelaunch: true, + }, + 'darwin' + ); + assert.equal(noticeEl.classList.contains('is-warn'), true); + assert.match(noticeEl.textContent, /open -a "Antigravity" --args --remote-debugging-port=0/); + + strTab.refs.mountBridgeNotice.refs.copyBtnEl.dispatchEvent({ type: 'click' }); + await new Promise((r) => setTimeout(r, 0)); + assert.equal(copiedClipboardText, '--remote-debugging-port=0'); + assert.match(strTab.refs.mountBridgeNotice.refs.copyBtnEl.textContent, /已复制/); + + // Dismissible global banner hides on dismiss click and resets once state becomes 'active' + const globalBanner = BridgeStatusNotice({ dismissible: true }); + globalBanner.refs.update({ + visible: true, + windowBridge: { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + hostPlatform: 'win32', + }); + assert.equal(globalBanner.el.hasAttribute('hidden'), false); + globalBanner.refs.dismissBtnEl.dispatchEvent({ type: 'click' }); + assert.equal(globalBanner.el.hasAttribute('hidden'), true); + globalBanner.refs.update({ + visible: true, + windowBridge: { state: 'active', launcherConfigured: true, canRelaunch: true }, + hostPlatform: 'win32', + }); + globalBanner.refs.update({ + visible: true, + windowBridge: { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + hostPlatform: 'win32', + }); + assert.equal(globalBanner.el.hasAttribute('hidden'), false, 'Re-armed after active cycle'); + + // English localization check + setI18nLanguage('en-US'); + strTab.refs.refreshLabels(); + assert.match(noticeEl.textContent, /Local Debug Port Missing/); + + // Switching to Sidebar Only hides notice immediately + strTab.refs.renderSettings( + { windowMountMode: 'sidebar', enableWindowOverlay: false }, + { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + 'win32' + ); + assert.equal(noticeEl.hasAttribute('hidden'), true); + + // SettingsOtherTab context window override notice & pending-restart meta state (Issue #27) + setI18nLanguage('zh-CN'); + const othTab = SettingsOtherTab({ onLayoutChange: () => {} }); + const ctxNoticeEl = othTab.refs.ctxBridgeNotice.el; + const mockCtxModels = [ + { + id: 'model:gemini-4-carbon', + label: 'Gemini 4 Carbon', + capacity: 786432, + members: ['MODEL_PLACEHOLDER_M427'], + options: [{ name: '256000', tokens: 256000 }, { name: '512000', tokens: 512000 }], + }, + ]; + + // Locked risk mask -> notice stays hidden + othTab.refs.renderSettings( + { contextWindowRiskAccepted: false, modelContextWindows: {} }, + mockCtxModels, + { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + 'win32' + ); + assert.equal(ctxNoticeEl.hasAttribute('hidden'), true); + + // Unlocked + no_devtools_port -> notice immediately visible AND saved option meta shows "待重启生效" instead of "已设置" + othTab.refs.renderSettings( + { + contextWindowRiskAccepted: true, + modelContextWindows: { 'model:gemini-4-carbon': '256000' }, + }, + mockCtxModels, + { state: 'no_devtools_port', launcherConfigured: true, canRelaunch: true }, + 'win32' + ); + assert.equal(ctxNoticeEl.hasAttribute('hidden'), false); + assert.match(ctxNoticeEl.textContent, /激活上下文覆写/); + othTab.refs.ctxModelSelect.refs.triggerBtn.dispatchEvent({ + type: 'click', + stopPropagation() {}, + }); + assert.match( + othTab.refs.ctxModelSelect.refs.menuEl.textContent, + /256,000 token · 待重启生效/ + ); + + othTab.refs.renderSettings( + { + contextWindowRiskAccepted: true, + modelContextWindows: { 'model:gemini-4-carbon': '256000' }, + }, + mockCtxModels, + { state: 'active', aliveCount: 1, launcherConfigured: true, canRelaunch: true }, + 'win32' + ); + assert.equal(ctxNoticeEl.hasAttribute('hidden'), true); + assert.match(othTab.refs.ctxModelSelect.refs.menuEl.textContent, /256,000 token · 已设置/); + + globalBanner.destroy(); + strTab.destroy(); + othTab.destroy(); + } finally { + setI18nLanguage('zh-CN'); + globalThis.document = prevDoc; + globalThis.fetch = prevFetch; + Object.defineProperty(globalThis, 'navigator', { + value: prevNav, + configurable: true, + }); + } +}); diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/trajectory-metrics.mjs similarity index 94% rename from sidecars/panel/speed-metrics.mjs rename to sidecars/panel/trajectory-metrics.mjs index 5634c98..58f9c73 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/trajectory-metrics.mjs @@ -667,6 +667,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { let turnCounter = 0; let activeTurnIndex = null; let pendingTurnPrompts = []; + let pendingTurnHasMedia = false; let hasUnconsumedTurn = false; const isUserTurnBoundary = (step) => { @@ -678,7 +679,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { return Boolean(step.userInput && typeof step.userInput === 'object'); }; - const extractUserTurnPrompt = (step) => { + const extractUserTurnInfo = (step) => { const ui = step?.userInput; let raw = ''; if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) { @@ -709,24 +710,35 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { ? step.media : []; const hasMedia = mediaArr.length > 0; - if (!cleaned) { - return hasMedia ? '[图片/附件提问]' : ''; - } - const withMedia = hasMedia ? `${cleaned} [附图]` : cleaned; - return withMedia.length > 180 ? `${withMedia.slice(0, 179)}…` : withMedia; + const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned; + const legacyRaw = !cleaned ? (hasMedia ? '[图片/附件提问]' : '') : hasMedia ? `${cleaned} [附图]` : cleaned; + const legacyPrompt = legacyRaw.length > 180 ? `${legacyRaw.slice(0, 179)}…` : legacyRaw; + return { cleanText, legacyPrompt, hasMedia }; }; + let pendingTurnCleanPrompts = []; rawSteps.forEach((s, index) => { if (isUserTurnBoundary(s)) { - const promptText = extractUserTurnPrompt(s); + const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s); if (!hasUnconsumedTurn) { hasUnconsumedTurn = true; - pendingTurnPrompts = promptText ? [promptText] : []; - } else if ( - promptText && - pendingTurnPrompts[pendingTurnPrompts.length - 1] !== promptText - ) { - pendingTurnPrompts.push(promptText); + pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : []; + pendingTurnCleanPrompts = cleanText ? [cleanText] : []; + pendingTurnHasMedia = hasMedia; + } else { + if ( + legacyPrompt && + pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt + ) { + pendingTurnPrompts.push(legacyPrompt); + } + if ( + cleanText && + pendingTurnCleanPrompts[pendingTurnCleanPrompts.length - 1] !== cleanText + ) { + pendingTurnCleanPrompts.push(cleanText); + } + if (hasMedia) pendingTurnHasMedia = true; } } @@ -738,15 +750,25 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { let stepIsTurnStart = false; let stepTurnPrompt = ''; + let stepTurnPromptClean = ''; + let stepTurnHasMedia = false; + let stepTurnMediaOnly = false; if (hasUnconsumedTurn) { turnCounter += 1; activeTurnIndex = turnCounter; stepIsTurnStart = true; const joinedPrompt = pendingTurnPrompts.join('\n').trim(); + const joinedClean = pendingTurnCleanPrompts.join('\n').trim(); stepTurnPrompt = joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt; + stepTurnPromptClean = + joinedClean.length > 180 ? `${joinedClean.slice(0, 179)}…` : joinedClean; + stepTurnHasMedia = pendingTurnHasMedia; + stepTurnMediaOnly = Boolean(pendingTurnHasMedia && !stepTurnPromptClean); hasUnconsumedTurn = false; pendingTurnPrompts = []; + pendingTurnCleanPrompts = []; + pendingTurnHasMedia = false; } const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index; @@ -917,6 +939,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) { turnIndex: activeTurnIndex, isTurnStart: stepIsTurnStart, ...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}), + ...(stepIsTurnStart && stepTurnPromptClean ? { turnPromptClean: stepTurnPromptClean } : {}), + ...(stepIsTurnStart ? { turnHasMedia: stepTurnHasMedia, turnMediaOnly: stepTurnMediaOnly } : {}), }); }); @@ -1046,12 +1070,17 @@ export function inferCompactionStepModels(steps) { step.responseModel || (donorSameModel ? donor.responseModel || '' : ''); const nextDisplayName = step.modelDisplayName || (donorSameModel ? donor.modelDisplayName || '' : ''); + const nextMaxBudget = + !step.reportedContextLimitTokens && donor.maxContextBudgetTokens > 0 + ? donor.maxContextBudgetTokens + : step.maxContextBudgetTokens; if ( nextModelKey === step.modelKey && nextModelSource === step.modelSource && nextResponseModel === (step.responseModel || '') && - nextDisplayName === (step.modelDisplayName || '') + nextDisplayName === (step.modelDisplayName || '') && + nextMaxBudget === step.maxContextBudgetTokens ) { return step; } @@ -1062,6 +1091,7 @@ export function inferCompactionStepModels(steps) { modelSource: nextModelSource, responseModel: nextResponseModel, modelDisplayName: nextDisplayName, + maxContextBudgetTokens: nextMaxBudget, }; }); } @@ -1591,7 +1621,11 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { rawName = 'edit_file'; } else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) { rawName = 'grep_search'; - } else if (stepType.includes('FIND_BY_NAME') || fallbackStep?.findByName) { + } else if ( + stepType.includes('FIND_BY_NAME') || + stepType === 'CORTEX_STEP_TYPE_FIND' || + fallbackStep?.findByName + ) { rawName = 'find_by_name'; } else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) { rawName = 'search_web'; @@ -1668,6 +1702,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { : summary || cmdSnippet || ''; return { toolName: nameLower, + actionKey: 'run_command', isAskUser: false, label: '执行命令', detail, @@ -1694,6 +1729,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { : ''; return { toolName: nameLower, + actionKey: 'read_file', isAskUser: false, label: '读取文件', detail: file ? `${file}${rangeSuffix}` : '', @@ -1711,6 +1747,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { ); return { toolName: nameLower, + actionKey: 'edit_file', isAskUser: false, label: '修改文件', detail: file || '', @@ -1723,6 +1760,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { ); return { toolName: nameLower, + actionKey: 'write_file', isAskUser: false, label: '写入文件', detail: file || '', @@ -1738,6 +1776,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { : cleanSingleLineSnippet(query, 48) || searchPath || ''; return { toolName: nameLower, + actionKey: 'grep_search', isAskUser: false, label: '搜索代码', detail, @@ -1749,6 +1788,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path'])); return { toolName: nameLower, + actionKey: 'find_file', isAskUser: false, label: '查找文件', detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '', @@ -1760,6 +1800,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const target = pickField(['query', 'Query', 'Url', 'url']); return { toolName: nameLower, + actionKey: isUrl ? 'read_url' : 'search_web', isAskUser: false, label: isUrl ? '读取网页' : '网页搜索', detail: cleanSingleLineSnippet(target, 52) || '', @@ -1775,6 +1816,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { String(subSpec.typeName || '').trim(); return { toolName: nameLower, + actionKey: 'invoke_subagent', isAskUser: false, label: '调用子代理', detail: role || '', @@ -1785,6 +1827,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const recipient = pickField(['Recipient', 'recipient']); return { toolName: nameLower, + actionKey: 'send_message', isAskUser: false, label: '通信子代理', detail: recipient ? recipient.slice(0, 8) : '', @@ -1795,6 +1838,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const subName = pickField(['Name', 'Action', 'action']); return { toolName: nameLower, + actionKey: 'manage_subagents', isAskUser: false, label: '管理子代理', detail: subName || '', @@ -1806,6 +1850,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const taskId = pickField(['TaskId', 'taskId']); return { toolName: nameLower, + actionKey: 'manage_task', isAskUser: false, label: '后台任务', detail: taskId ? `${action || 'status'} (${taskId})` : action || '', @@ -1817,6 +1862,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const cron = pickField(['CronExpression']); return { toolName: nameLower, + actionKey: 'schedule', isAskUser: false, label: '定时任务', detail: dur ? `${dur}s` : cron || '', @@ -1833,6 +1879,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { ); return { toolName: nameLower, + actionKey: 'ask_question', isAskUser: true, label: '等待用户选择', detail: cleanSingleLineSnippet(qText, 50) || '', @@ -1844,6 +1891,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : ''; return { toolName: nameLower, + actionKey: 'search_marketplace', isAskUser: false, label: '查询插件', detail: cleanSingleLineSnippet(q, 48) || '', @@ -1854,6 +1902,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · '); return { toolName: nameLower, + actionKey: 'mcp_tool', isAskUser: false, label: '调用 MCP', detail: mcpClean || '', @@ -1862,6 +1911,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) { return { toolName: nameLower || 'tool', + actionKey: 'tool_call', isAskUser: false, label: '调用工具', detail: nameLower || '', @@ -1909,6 +1959,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = Math.floor(fallbackStartMs || 0); return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: '', stepProgress: '', @@ -1958,6 +2011,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (isCheckpointStep(lastStep)) { return { phase: 'compacting', + actionKey: 'compacting', + waitingApproval: false, + detailKey: '', label: '上下文压缩', detail: '', stepProgress: '', @@ -1979,11 +2035,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const phase = info.isAskUser ? 'waiting' : 'tool'; return { phase, + toolName: info.toolName, + actionKey: info.actionKey, + waitingApproval: false, + detailKey: '', label: info.label, detail: info.detail, stepProgress, startedAtMs: startMs, - signature: `planner-tool:${lastStepId}:${tools.length}:${info.label}:${info.detail}`, + signature: `planner-tool:${lastStepId}:${tools.length}:${info.actionKey}:${info.detail}`, }; } @@ -1991,6 +2051,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const snippet = cleanSingleLineSnippet(respText, 52, true); return { phase: 'responding', + actionKey: 'responding', + waitingApproval: false, + detailKey: '', label: '正在输出回复', detail: snippet, stepProgress: '', @@ -2003,6 +2066,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const snippet = cleanSingleLineSnippet(thinkText, 52, true); return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: snippet, stepProgress: '', @@ -2013,6 +2079,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: '', stepProgress: '', @@ -2047,16 +2116,21 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt stepProgress = ''; } const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser; + const waitingApproval = Boolean(waiting && !info.isAskUser); const resolvedStartMs = startMs || prevStepEndMs || 0; - const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label; + const label = waitingApproval ? `等待确认 · ${info.label}` : info.label; return { phase: waiting ? 'waiting' : 'tool', + toolName: info.toolName, + actionKey: info.actionKey, + waitingApproval, + detailKey: '', label, detail: info.detail, stepProgress, startedAtMs: resolvedStartMs, - signature: `step-run:${lastStepId}:${waiting}:${label}:${stepProgress}:${info.detail}`, + signature: `step-run:${lastStepId}:${waiting}:${info.actionKey}:${stepProgress}:${info.detail}`, }; } @@ -2092,6 +2166,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt Math.floor(fallbackStartMs || 0); return { phase: 'compacting', + actionKey: 'compacting', + waitingApproval: false, + detailKey: cpFinishMs > 0 ? 'compaction_resuming' : '', label: '上下文压缩', detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '', stepProgress: '', @@ -2134,11 +2211,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt return { phase, + toolName: info.toolName, + actionKey: info.actionKey, + waitingApproval: false, + detailKey: '', label: info.label, detail: info.detail, stepProgress, startedAtMs: startMs, - signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.label}:${stepProgress}:${info.detail}`, + signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.actionKey}:${stepProgress}:${info.detail}`, }; } @@ -2148,7 +2229,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep) ); const lastToolInfo = infos[infos.length - 1]; - const allSameLabel = infos.every((x) => x.label === lastToolInfo.label); + const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey); const detailsList = infos.map((x) => x.detail).filter(Boolean); const combinedDetail = infos.length > 1 && allSameLabel @@ -2161,11 +2242,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; return { phase: 'thinking', + toolName: lastToolInfo.toolName, + actionKey: lastToolInfo.actionKey, + waitingApproval: false, + detailKey: '', label: lastToolInfo.label, detail: combinedDetail, stepProgress, startedAtMs: startMs, - signature: `post-tool-think:${lastStepId}:${lastToolInfo.label}:${combinedDetail}`, + signature: `post-tool-think:${lastStepId}:${lastToolInfo.actionKey}:${combinedDetail}`, }; } @@ -2178,11 +2263,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; return { phase: 'thinking', + toolName: lastInfo.toolName, + actionKey: lastInfo.actionKey, + waitingApproval: false, + detailKey: '', label: lastInfo.label, detail: lastInfo.detail, stepProgress: '', startedAtMs: startMs, - signature: `post-step-tool:${lastStepId}:${lastInfo.label}:${lastInfo.detail}`, + signature: `post-step-tool:${lastStepId}:${lastInfo.actionKey}:${lastInfo.detail}`, }; } } @@ -2198,6 +2287,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (snippet) { return { phase: 'responding', + actionKey: 'responding', + waitingApproval: false, + detailKey: '', label: '正在输出回复', detail: snippet, stepProgress: '', @@ -2211,6 +2303,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt if (snippet) { return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: snippet, stepProgress: '', @@ -2226,6 +2321,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0; return { phase: 'thinking', + actionKey: 'thinking', + waitingApproval: false, + detailKey: '', label: '推理中', detail: '', stepProgress: '',