From 8ac5da8d118a21475f014179896170470b133deb Mon Sep 17 00:00:00 2001 From: fish <1770968958@qq.com> Date: Wed, 11 Nov 2026 01:06:31 +0900 Subject: [PATCH] feat(panel): live task cards, interactive usage trend chart, and Gemini 4 Carbon support (v1.4.2) --- plugin.json | 2 +- pricing-catalog.json | 83 +- sidecars/panel/app.js | 1239 ++++++++++++----- sidecars/panel/backend/config.mjs | 64 +- sidecars/panel/backend/local-scanner.mjs | 231 ++- sidecars/panel/backend/model-pricing.mjs | 18 +- sidecars/panel/backend/pricing-catalog.mjs | 142 +- sidecars/panel/backend/quota-pools.mjs | 87 +- sidecars/panel/backend/telemetry-builder.mjs | 218 ++- sidecars/panel/backend/usage-aggregator.mjs | 228 ++- sidecars/panel/index.html | 4 +- sidecars/panel/main.mjs | 81 +- sidecars/panel/package.json | 2 +- sidecars/panel/scripts/build-bundle.mjs | 2 +- sidecars/panel/speed-metrics.mjs | 929 +++++++++++- .../src/components/charts/TrendAreaChart.js | 335 ++++- .../src/components/layout/TopSessionHeader.js | 108 +- .../src/components/ui/ContextSegmentMeter.js | 49 +- .../src/components/ui/CustomDateTimePicker.js | 4 +- .../src/components/ui/CustomScrollbar.js | 21 +- .../panel/src/components/ui/CustomSelect.js | 8 +- .../panel/src/components/ui/TopLongPillNav.js | 17 +- sidecars/panel/src/core/component.js | 16 +- sidecars/panel/src/core/formatters.js | 17 +- sidecars/panel/src/core/httpClient.js | 10 +- sidecars/panel/src/icons/svgRegistry.js | 18 - sidecars/panel/src/store/telemetryStore.js | 114 +- sidecars/panel/src/store/uiStore.js | 2 - sidecars/panel/src/styles/controls.css | 92 +- sidecars/panel/src/styles/tokens.css | 4 +- .../panel/src/styles/views-consumption.css | 147 +- sidecars/panel/src/styles/views-overview.css | 276 +++- sidecars/panel/src/views/ConsumptionView.js | 60 +- sidecars/panel/src/views/LiveOverviewView.js | 416 +++++- sidecars/panel/src/views/SettingsView.js | 48 +- sidecars/panel/src/views/StepsDetailView.js | 7 +- sidecars/panel/styles.css | 519 +++++-- sidecars/panel/test/backend.test.mjs | 210 +++ sidecars/panel/test/speed-metrics.test.mjs | 128 +- 39 files changed, 4857 insertions(+), 1099 deletions(-) diff --git a/plugin.json b/plugin.json index 81a990b..03c6072 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "name": "usage-monitor", "displayName": "Usage & Speed Monitor", - "version": "1.4.1", + "version": "1.4.2", "description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。", "logo": "assets/logo.svg", "suggestedPrompts": [ diff --git a/pricing-catalog.json b/pricing-catalog.json index 30862c7..6c63d0b 100644 --- a/pricing-catalog.json +++ b/pricing-catalog.json @@ -1,12 +1,16 @@ { "schemaVersion": 1, - "catalogVersion": "2026.11.03.1", - "updatedAt": "2026-11-03T13:00:00+09:00", - "latestPluginVersion": "1.4.1", + "catalogVersion": "2026.11.11.1", + "updatedAt": "2026-11-11T00:30:00+09:00", + "latestPluginVersion": "1.4.2", "releaseUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest", "downloadUrl": "https://github.com/yuhuan2498281558/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip", "archiveFallbackUrl": "https://codeload.github.com/yuhuan2498281558/antigravity-usage-monitor/zip/refs/heads/main", "pricing": { + "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" }, @@ -14,34 +18,72 @@ "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-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": { "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.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": { "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.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.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" }, + "gemini-3.5-flash-extra-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.5-xlow", "family": "Gemini" }, "gemini-3.5-flash": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5", "family": "Gemini" }, "gemini-3.5-flash-lite": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.5-lite", "family": "Gemini" }, + "gemini-3.1-pro-high": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1-high", "family": "Gemini" }, + "gemini-3.1-pro-low": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1-low", "family": "Gemini" }, + "gemini-3.1-pro-low-thinking": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1-low", "family": "Gemini" }, + "gemini-3.1-pro-preview": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" }, + "gemini-3.1-pro-preview-customtools": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" }, "gemini-3.1-pro": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3.1", "family": "Gemini" }, + "gemini-3.1-flash-lite-preview": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" }, "gemini-3.1-flash-lite": { "input": 0.25, "cache": 0.025, "output": 1.50, "short": "flash-3.1-lite", "family": "Gemini" }, + "gemini-for-google-3.1-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1", "family": "Gemini" }, + "gemini-3.1-flash-image": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3.1-img", "family": "Gemini" }, + "gemini-3-flash-preview": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, "gemini-3-flash": { "input": 0.50, "cache": 0.05, "output": 3.00, "short": "flash-3", "family": "Gemini" }, + "gemini-3-pro-image": { "input": 2.00, "cache": 0.20, "output": 12.0, "short": "pro-3-img", "family": "Gemini" }, "gemini-2.5-pro": { "input": 1.25, "cache": 0.125, "output": 10.0, "short": "pro-2.5", "family": "Gemini" }, "gemini-2.5-flash": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-2.5", "family": "Gemini" }, "gemini-2.5-flash-lite": { "input": 0.10, "cache": 0.01, "output": 0.40, "short": "flash-2.5-lite", "family": "Gemini" }, + "claude-fable-5-2-max": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2-max", "family": "Claude" }, + "claude-fable-5-2-high": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2-high", "family": "Claude" }, + "claude-fable-5-2-medium": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2", "family": "Claude" }, + "claude-fable-5-2-low": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2-low", "family": "Claude" }, + "claude-fable-5-2": { "input": 8.00, "cache": 0.20, "output": 40.0, "short": "fable-5.2", "family": "Claude" }, "claude-fable-5-1": { "input": 10.0, "cache": 0.25, "output": 50.0, "short": "fable-5.1", "family": "Claude" }, "claude-fable-5": { "input": 10.0, "cache": 1.00, "output": 50.0, "short": "fable-5", "family": "Claude" }, + "claude-opus-5-5-max": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "opus-5.5-max", "family": "Claude" }, + "claude-opus-5-5-high": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "opus-5.5-high", "family": "Claude" }, + "claude-opus-5-5-medium": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "opus-5.5", "family": "Claude" }, + "claude-opus-5-5-low": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "opus-5.5-low", "family": "Claude" }, "claude-opus-5-5": { "input": 4.00, "cache": 0.20, "output": 20.0, "short": "opus-5.5", "family": "Claude" }, "claude-opus-5": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-5", "family": "Claude" }, "claude-opus-4-8": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.8", "family": "Claude" }, "claude-opus-4-7": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.7", "family": "Claude" }, "claude-opus-4-6-thinking": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus", "family": "Claude" }, "claude-opus-4-6": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.6", "family": "Claude" }, + "claude-opus-4-5-thinking": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.5", "family": "Claude" }, "claude-opus-4-5": { "input": 5.00, "cache": 0.50, "output": 25.0, "short": "opus-4.5", "family": "Claude" }, + "claude-sonnet-5-5-max": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "sonnet-5.5-max", "family": "Claude" }, + "claude-sonnet-5-5-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "sonnet-5.5-high", "family": "Claude" }, + "claude-sonnet-5-5-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "sonnet-5.5", "family": "Claude" }, + "claude-sonnet-5-5-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "sonnet-5.5-low", "family": "Claude" }, "claude-sonnet-5-5": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "sonnet-5.5", "family": "Claude" }, "claude-sonnet-5": { "input": 2.00, "cache": 0.20, "output": 10.0, "short": "sonnet-5", "family": "Claude" }, "claude-sonnet-4-6": { "input": 3.00, "cache": 0.30, "output": 15.0, "short": "sonnet", "family": "Claude" }, + "claude-sonnet-4-5-thinking": { "input": 3.00, "cache": 0.30, "output": 15.0, "short": "sonnet-4.5", "family": "Claude" }, "claude-sonnet-4-5": { "input": 3.00, "cache": 0.30, "output": 15.0, "short": "sonnet-4.5", "family": "Claude" }, "claude-haiku-5-5": { "input": 0.10, "cache": 0.01, "output": 0.50, "short": "haiku-5.5", "family": "Claude" }, "claude-haiku-4-5": { "input": 1.00, "cache": 0.10, "output": 5.00, "short": "haiku-4.5", "family": "Claude" }, "gpt-6-astra": { "input": 10.0, "cache": 1.00, "output": 50.0, "short": "gpt-6-astra", "family": "GPT" }, "gpt-6.1-sol": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "gpt-6.1-sol", "family": "GPT" }, + "gpt-6.1-terra": { "input": 1.00, "cache": 0.05, "output": 5.00, "short": "gpt-6.1-terra", "family": "GPT" }, "gpt-6-sol": { "input": 2.00, "cache": 0.20, "output": 10.0, "short": "gpt-6-sol", "family": "GPT" }, "gpt-6-luna": { "input": 0.10, "cache": 0.01, "output": 0.50, "short": "gpt-6-luna", "family": "GPT" }, "gpt-5.6": { "input": 4.00, "cache": 0.40, "output": 20.0, "short": "gpt-5.6", "family": "GPT" }, @@ -75,14 +117,45 @@ "MODEL_PLACEHOLDER_M319": { "modelId": "gemini-3.8-flash-medium", "label": "Gemini 3.8 Flash (Medium)" }, "MODEL_PLACEHOLDER_M320": { "modelId": "gemini-3.8-flash-low", "label": "Gemini 3.8 Flash (Low)" }, "MODEL_PLACEHOLDER_M322": { "modelId": "gemini-3.8-flash", "label": "Gemini 3.8 Flash (Tiered)" }, + "MODEL_PLACEHOLDER_M298": { "modelId": "gemini-3.7-flash-high", "label": "Gemini 3.7 Flash (High)" }, + "MODEL_PLACEHOLDER_M299": { "modelId": "gemini-3.7-flash-medium", "label": "Gemini 3.7 Flash (Medium)" }, + "MODEL_PLACEHOLDER_M300": { "modelId": "gemini-3.7-flash-low", "label": "Gemini 3.7 Flash (Low)" }, + "MODEL_PLACEHOLDER_M301": { "modelId": "gemini-3.7-flash-tiered", "label": "Gemini 3.7 Flash (Tiered)" }, + "MODEL_PLACEHOLDER_M71": { "modelId": "gemini-3.6-flash-high", "label": "Gemini 3.6 Flash (High)" }, + "MODEL_PLACEHOLDER_M72": { "modelId": "gemini-3.6-flash-medium", "label": "Gemini 3.6 Flash (Medium)" }, + "MODEL_PLACEHOLDER_M73": { "modelId": "gemini-3.6-flash-low", "label": "Gemini 3.6 Flash (Low)" }, + "MODEL_PLACEHOLDER_M196": { "modelId": "gemini-3.6-flash", "label": "Gemini 3.6 Flash" }, + "MODEL_PLACEHOLDER_M149": { "modelId": "gemini-3.5-flash", "label": "Gemini 3.5 Flash (High)" }, + "MODEL_PLACEHOLDER_M20": { "modelId": "gemini-3.5-flash-low", "label": "Gemini 3.5 Flash" }, + "MODEL_PLACEHOLDER_M187": { "modelId": "gemini-3.5-flash-extra-low", "label": "Gemini 3.5 Flash (Extra Low)" }, "MODEL_PLACEHOLDER_M198": { "modelId": "gemini-3.5-flash-lite", "label": "Gemini 3.5 Flash Lite" }, + "MODEL_PLACEHOLDER_M37": { "modelId": "gemini-3.1-pro-high", "label": "Gemini 3.1 Pro (High)" }, + "MODEL_PLACEHOLDER_M36": { "modelId": "gemini-3.1-pro-low", "label": "Gemini 3.1 Pro (Low)" }, "MODEL_PLACEHOLDER_M50": { "modelId": "gemini-3.1-flash-lite", "label": "Gemini 3.1 Flash Lite" }, + "MODEL_PLACEHOLDER_M59": { "modelId": "gemini-for-google-3.1-flash", "label": "Gemini for Google 3.1 Flash" }, + "MODEL_PLACEHOLDER_M21": { "modelId": "gemini-3.1-flash-image", "label": "Gemini 3.1 Flash Image" }, "MODEL_PLACEHOLDER_M18": { "modelId": "gemini-3-flash", "label": "Gemini 3 Flash" }, - "MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" }, - "MODEL_GOOGLE_GEMINI_2_5_FLASH": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash" }, + "MODEL_PLACEHOLDER_M9": { "modelId": "gemini-3-pro-image", "label": "Gemini 3 Pro Image" }, "MODEL_GOOGLE_GEMINI_2_5_PRO": { "modelId": "gemini-2.5-pro", "label": "Gemini 2.5 Pro" }, + "MODEL_GOOGLE_GEMINI_2_5_FLASH": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash" }, + "MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING": { "modelId": "gemini-2.5-flash", "label": "Gemini 2.5 Flash (Thinking)" }, + "MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE": { "modelId": "gemini-2.5-flash-lite", "label": "Gemini 2.5 Flash Lite" }, + "MODEL_PLACEHOLDER_M406": { "modelId": "claude-opus-5-5-max", "label": "Claude Opus 5.5 (Max)" }, + "MODEL_PLACEHOLDER_M402": { "modelId": "claude-opus-5-5-high", "label": "Claude Opus 5.5 (High)" }, + "MODEL_PLACEHOLDER_M401": { "modelId": "claude-opus-5-5-medium", "label": "Claude Opus 5.5 (Medium)" }, + "MODEL_PLACEHOLDER_M400": { "modelId": "claude-opus-5-5-low", "label": "Claude Opus 5.5 (Low)" }, + "MODEL_PLACEHOLDER_M368": { "modelId": "claude-opus-5-5", "label": "Claude Opus 5.5" }, + "MODEL_PLACEHOLDER_M407": { "modelId": "claude-sonnet-5-5-max", "label": "Claude Sonnet 5.5 (Max)" }, + "MODEL_PLACEHOLDER_M405": { "modelId": "claude-sonnet-5-5-high", "label": "Claude Sonnet 5.5 (High)" }, + "MODEL_PLACEHOLDER_M404": { "modelId": "claude-sonnet-5-5-medium", "label": "Claude Sonnet 5.5 (Medium)" }, + "MODEL_PLACEHOLDER_M403": { "modelId": "claude-sonnet-5-5-low", "label": "Claude Sonnet 5.5 (Low)" }, + "MODEL_PLACEHOLDER_M254": { "modelId": "claude-opus-4-8", "label": "Claude Opus 4.8" }, "MODEL_PLACEHOLDER_M26": { "modelId": "claude-opus-4-6-thinking", "label": "Claude Opus 4.6 (Thinking)" }, "MODEL_PLACEHOLDER_M35": { "modelId": "claude-sonnet-4-6", "label": "Claude Sonnet 4.6 (Thinking)" }, + "MODEL_PLACEHOLDER_M12": { "modelId": "claude-opus-4-5-thinking", "label": "Claude Opus 4.5 (Thinking)" }, + "MODEL_PLACEHOLDER_M11": { "modelId": "claude-opus-4-5", "label": "Claude Opus 4.5" }, + "MODEL_CLAUDE_4_5_SONNET_THINKING": { "modelId": "claude-sonnet-4-5-thinking", "label": "Claude Sonnet 4.5 (Thinking)" }, + "MODEL_CLAUDE_4_5_SONNET": { "modelId": "claude-sonnet-4-5", "label": "Claude Sonnet 4.5" }, "MODEL_OPENAI_GPT_OSS_120B_MEDIUM": { "modelId": "gpt-oss-120b-medium", "label": "GPT-OSS 120B (Medium)" } } } diff --git a/sidecars/panel/app.js b/sidecars/panel/app.js index 7c8789f..7cee930 100644 --- a/sidecars/panel/app.js +++ b/sidecars/panel/app.js @@ -59,18 +59,6 @@ const SVG_ICON_DEFS = Object.freeze({ { tag: 'circle', attrs: { cx: '10.5', cy: '8', r: '1.5' } }, { tag: 'circle', attrs: { cx: '6.8', cy: '12.5', r: '1.5' } }, ], - flask: [ - { tag: 'path', attrs: { d: 'M6 2.2h4' } }, - { tag: 'path', attrs: { d: 'M6.8 2.2v3.6L3.2 12.2a1.2 1.2 0 0 0 1.1 1.8h7.4a1.2 1.2 0 0 0 1.1-1.8L9.2 5.8V2.2' } }, - { tag: 'path', attrs: { d: 'M4.6 10.2h6.8' } }, - ], - session: [ - { tag: 'path', attrs: { d: 'M2.5 3.2h11v7.6H6l-3.5 2.5V3.2z' } }, - ], - cpu: [ - { tag: 'rect', attrs: { x: '4', y: '4', width: '8', height: '8', rx: '1' } }, - { tag: 'path', attrs: { d: 'M6.5 1.8v2.2M9.5 1.8v2.2M6.5 12v2.2M9.5 12v2.2M1.8 6.5H4M1.8 9.5H4M12 6.5h2.2M12 9.5h2.2' } }, - ], calendar: [ { tag: 'rect', attrs: { x: '2.2', y: '3.2', width: '11.6', height: '10.6', rx: '1' } }, { tag: 'path', attrs: { d: 'M5.2 1.8v2.4M10.8 1.8v2.4M2.2 6.5h11.6' } }, @@ -85,12 +73,6 @@ const SVG_ICON_DEFS = Object.freeze({ minus: [ { tag: 'path', attrs: { d: 'M3.5 8h9' } }, ], - swap: [ - { tag: 'path', attrs: { d: 'M3 5.5h10l-2.6-2.6M13 10.5H3l2.6 2.6' } }, - ], - close: [ - { tag: 'path', attrs: { d: 'M4 4l8 8M12 4l-8 8' } }, - ], dot: [ { tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } }, ], @@ -427,13 +409,6 @@ function patchKeyedList(container, items, { keyFn, sigFn, createRow, updateRow } * reactive subscriptions, and lifecycle cleanup. */ -const globalEmitListeners = new Set(); - -function onComponentEmit(listener) { - globalEmitListeners.add(listener); - return () => globalEmitListeners.delete(listener); -} - function defineComponent({ name, setup }) { return function createInstance(initialProps = {}) { let props = { ...initialProps }; @@ -464,14 +439,6 @@ function defineComponent({ name, setup }) { fn(payload); } } - for (const observer of globalEmitListeners) { - observer({ - component: name || 'AnonymousComponent', - event, - payload, - timestamp: Date.now(), - }); - } } function onCleanup(fn) { @@ -511,6 +478,7 @@ function defineComponent({ name, setup }) { console.error(`[${name}] cleanup error:`, err); } } + eventHandlers.clear(); if (setupResult.el?.parentNode) { setupResult.el.parentNode.removeChild(setupResult.el); } @@ -621,12 +589,17 @@ function formatCompactDateTime(ms) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; } -function escapeHtml(str) { - return String(str || '') - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); +function formatElapsedSec(seconds) { + const s = Math.max(0, Math.floor(Number(seconds) || 0)); + if (s < 60) return `${s}s`; + const m = Math.floor(s / 60); + const remS = s % 60; + if (m < 60) { + return `${m}m ${String(remS).padStart(2, '0')}s`; + } + const h = Math.floor(m / 60); + const remM = m % 60; + return `${h}h ${remM}m`; } // --- src/core/httpClient.js --- @@ -647,14 +620,15 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {} } let signal; + let requestController = null; if (abortKey && typeof AbortController !== 'undefined') { const prev = activeControllers.get(abortKey); if (prev) { prev.abort(); } - const controller = new AbortController(); - activeControllers.set(abortKey, controller); - signal = controller.signal; + requestController = new AbortController(); + activeControllers.set(abortKey, requestController); + signal = requestController.signal; } const runRequest = async () => { @@ -690,6 +664,9 @@ async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {} if (dedupKey) { inFlightGets.delete(dedupKey); } + if (abortKey && requestController && activeControllers.get(abortKey) === requestController) { + activeControllers.delete(abortKey); + } }); if (dedupKey) { @@ -716,8 +693,6 @@ const uiStore = createReactiveStore({ stepsSubTab: 'steps', // 'steps' | 'models' selectedAgentScope: 'all', // 'all' | 'main' | ctxInspectorAgentId: 'auto', // 'auto' | 'main' | - showAllPools: true, - ctxBreakdownOpen: true, }); // --- src/store/telemetryStore.js --- @@ -783,7 +758,10 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.subagentCount !== nAct?.subagentCount) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; + if (pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature) return false; if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false; + if (pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature) return false; + if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false; if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false; if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false; @@ -792,8 +770,14 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false; + if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false; + if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; + if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false; + if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false; + if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false; if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false; if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false; @@ -810,9 +794,12 @@ function isEquivalentTelemetry(prev, next) { pa?.role !== na?.role || pa?.stepCount !== na?.stepCount || pa?.isRunning !== na?.isRunning || + pa?.liveActivity?.signature !== na?.liveActivity?.signature || pa?.latestTokPerSec !== na?.latestTokPerSec || pa?.latestTtftSec !== na?.latestTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || + pa?.latestCacheHitPct !== na?.latestCacheHitPct || + pa?.latestSpeedReason !== na?.latestSpeedReason || pa?.latestStepCostUsd !== na?.latestStepCostUsd || pa?.sessionCostUsd !== na?.sessionCostUsd || pa?.activeModelShort !== na?.activeModelShort || @@ -820,6 +807,14 @@ function isEquivalentTelemetry(prev, next) { pa?.context?.messagesTokens !== na?.context?.messagesTokens || pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens || pa?.context?.assistantTokens !== na?.context?.assistantTokens || + pa?.context?.userInputTokens !== na?.context?.userInputTokens || + pa?.context?.subagentTokens !== na?.context?.subagentTokens || + pa?.context?.checkpointTokens !== na?.context?.checkpointTokens || + pa?.context?.systemToolsTokens !== na?.context?.systemToolsTokens || + pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens || + pa?.context?.skillsTokens !== na?.context?.skillsTokens || + pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens || + pa?.context?.userRulesTokens !== na?.context?.userRulesTokens || pLastStep?.tokPerSec !== nLastStep?.tokPerSec || pLastStep?.ttftSec !== nLastStep?.ttftSec || pLastStep?.outputTokens !== nLastStep?.outputTokens || @@ -830,7 +825,7 @@ function isEquivalentTelemetry(prev, next) { } } - // 4. 比对 6 通道上下文窗口构成(总 Token 与消息/系统工具/MCP/Skill/系统提示词/用户规则)及近期步骤明细 + // 4. 比对 10 通道上下文窗口构成及近期步骤明细 const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; @@ -848,9 +843,21 @@ function isEquivalentTelemetry(prev, next) { if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; for (let i = 0; i < (pAct?.recentSteps?.length || 0); i++) { const before = pAct.recentSteps[i], after = nAct.recentSteps[i]; - if (before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || - before.modelUpstream !== after.modelUpstream || before.responseModel !== after.responseModel || - before.modelSource !== after.modelSource || before.costUsd !== after.costUsd) return false; + if ( + before.modelKey !== after.modelKey || + before.modelShort !== after.modelShort || + before.modelUpstream !== after.modelUpstream || + before.responseModel !== after.responseModel || + before.modelSource !== after.modelSource || + before.costUsd !== after.costUsd || + before.tokPerSec !== after.tokPerSec || + before.ttftSec !== after.ttftSec || + before.outputTokens !== after.outputTokens || + before.inputTokens !== after.inputTokens || + before.cacheReadTokens !== after.cacheReadTokens + ) { + return false; + } } // 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 @@ -874,12 +881,30 @@ function isEquivalentTelemetry(prev, next) { if (pAcct?.costUsd !== nAcct?.costUsd) return false; if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; - // 6. 比对历史趋势时间分桶序列 + // 6. 比对历史趋势时间分桶序列与年度分月序列 const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; if (pTrend.length !== nTrend.length) return false; for (let i = 0; i < pTrend.length; i++) { - if (pTrend[i]?.tokens !== nTrend[i]?.tokens || pTrend[i]?.label !== nTrend[i]?.label) { + if ( + pTrend[i]?.tokens !== nTrend[i]?.tokens || + pTrend[i]?.calls !== nTrend[i]?.calls || + pTrend[i]?.label !== nTrend[i]?.label || + pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel + ) { + return false; + } + } + if (prev.consumption?.monthlyYear !== next.consumption?.monthlyYear) return false; + const pMonthly = prev.consumption?.monthlySeries || []; + const nMonthly = next.consumption?.monthlySeries || []; + if (pMonthly.length !== nMonthly.length) return false; + for (let i = 0; i < pMonthly.length; i++) { + if ( + pMonthly[i]?.totalTokens !== nMonthly[i]?.totalTokens || + pMonthly[i]?.costUsd !== nMonthly[i]?.costUsd || + pMonthly[i]?.calls !== nMonthly[i]?.calls + ) { return false; } } @@ -918,7 +943,18 @@ function isEquivalentTelemetry(prev, next) { } // 8. 比对账号订阅档位与动态多配额池(活跃池、周汇总及各配额池的 5h/周限额进度与重置时间) - if (prev.account?.tierName !== next.account?.tierName || prev.account?.planName !== next.account?.planName) { + if ( + prev.account?.tierName !== next.account?.tierName || + prev.account?.planName !== next.account?.planName || + prev.account?.aiCredits !== next.account?.aiCredits + ) { + return false; + } + + if ( + prev.quotas?.meta?.refreshFailed !== next.quotas?.meta?.refreshFailed || + prev.quotas?.meta?.isStale !== next.quotas?.meta?.isStale + ) { return false; } @@ -930,6 +966,11 @@ function isEquivalentTelemetry(prev, next) { if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false; if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false; if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false; + if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false; + if (prev.quotas?.weekly?.costUsd !== next.quotas?.weekly?.costUsd) return false; + if (prev.quotas?.weekly?.calls !== next.quotas?.weekly?.calls) return false; + if (prev.quotas?.weekly?.unpricedCalls !== next.quotas?.weekly?.unpricedCalls) return false; + if (prev.quotas?.weekly?.resetTime !== next.quotas?.weekly?.resetTime) return false; const pPools = prev.quotas?.pools || []; const nPools = next.quotas?.pools || []; @@ -956,6 +997,7 @@ function isEquivalentTelemetry(prev, next) { if ( pConvs[i]?.cascadeId !== nConvs[i]?.cascadeId || pConvs[i]?.title !== nConvs[i]?.title || + pConvs[i]?.status !== nConvs[i]?.status || pConvs[i]?.stepCount !== nConvs[i]?.stepCount || pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount || pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount @@ -964,6 +1006,39 @@ function isEquivalentTelemetry(prev, next) { } } + const pRunning = prev.runningConversations || []; + const nRunning = next.runningConversations || []; + if (pRunning.length !== nRunning.length) return false; + for (let i = 0; i < pRunning.length; i++) { + const pr = pRunning[i]; + const nr = nRunning[i]; + if ( + pr?.cascadeId !== nr?.cascadeId || + pr?.title !== nr?.title || + pr?.isCurrentSelected !== nr?.isCurrentSelected || + pr?.isMainRunning !== nr?.isMainRunning || + pr?.subagentCount !== nr?.subagentCount || + pr?.runningSubagentCount !== nr?.runningSubagentCount || + pr?.mainActivity?.signature !== nr?.mainActivity?.signature + ) { + return false; + } + const pSubs = pr?.subagents || []; + const nSubs = nr?.subagents || []; + if (pSubs.length !== nSubs.length) return false; + for (let j = 0; j < pSubs.length; j++) { + if ( + pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId || + pSubs[j]?.role !== nSubs[j]?.role || + pSubs[j]?.isRunning !== nSubs[j]?.isRunning || + pSubs[j]?.stepCount !== nSubs[j]?.stepCount || + pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature + ) { + return false; + } + } + } + return true; } @@ -1280,6 +1355,16 @@ const TopLongPillNav = defineComponent({ const { items = [], modelValue } = getProps(); patchStyleVar(navEl, '--pill-count', Math.max(1, items.length)); + const validValues = new Set(items.map((it) => it.value)); + for (const [val, entry] of tabButtons.entries()) { + if (!validValues.has(val)) { + if (entry.btn?.parentNode === navEl) { + navEl.removeChild(entry.btn); + } + tabButtons.delete(val); + } + } + let activeIdx = 0; items.forEach((item, index) => { if (item.value === modelValue) { @@ -1302,8 +1387,13 @@ const TopLongPillNav = defineComponent({ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { e.preventDefault(); const curItems = getProps().items || []; + if (!curItems.length) return; + const curIndex = Math.max( + 0, + curItems.findIndex((it) => it.value === item.value) + ); const delta = e.key === 'ArrowRight' ? 1 : -1; - const nextIndex = (index + delta + curItems.length) % curItems.length; + const nextIndex = (curIndex + delta + curItems.length) % curItems.length; const target = curItems[nextIndex]; if (target) { selectValue(target.value); @@ -1499,9 +1589,7 @@ const CustomSelect = defineComponent({ } const selectedOpt = options.find((o) => o.value === modelValue) || - (modelValue !== '' && modelValue !== null && modelValue !== undefined - ? options[0] - : undefined); + (!modelValue ? options[0] : undefined); patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder); if (isOpen) { renderMenuOptions(); @@ -1515,8 +1603,8 @@ const CustomSelect = defineComponent({ }; if (typeof document !== 'undefined' && document.addEventListener) { - document.addEventListener('click', handleDocClick); - onCleanup(() => document.removeEventListener('click', handleDocClick)); + document.addEventListener('click', handleDocClick, true); + onCleanup(() => document.removeEventListener('click', handleDocClick, true)); } syncTriggerAndMenu(); @@ -1910,8 +1998,8 @@ const CustomDateTimePicker = defineComponent({ }; if (typeof document !== 'undefined' && document.addEventListener) { - document.addEventListener('click', handleDocClick); - onCleanup(() => document.removeEventListener('click', handleDocClick)); + document.addEventListener('click', handleDocClick, true); + onCleanup(() => document.removeEventListener('click', handleDocClick, true)); } syncDisplay(); @@ -2076,16 +2164,27 @@ const CustomScrollbar = defineComponent({ } }); + let pendingSync = false; + function scheduleSyncThumb() { + if (typeof queueMicrotask === 'function') { + if (pendingSync) return; + pendingSync = true; + queueMicrotask(() => { + pendingSync = false; + syncThumb(); + }); + } else { + syncThumb(); + } + } + return { el: hostEl, refs: { contentEl, railEl, thumbEl }, - onPropsChange: syncThumb, + onPropsChange: scheduleSyncThumb, methods: { refresh() { - syncThumb(); - if (typeof queueMicrotask === 'function') { - queueMicrotask(syncThumb); - } + scheduleSyncThumb(); }, scrollToRatio(ratio) { const r = Math.max(0, Math.min(1, Number(ratio || 0))); @@ -2181,11 +2280,10 @@ const SEGMENT_DEFS = [ const ContextSegmentMeter = defineComponent({ name: 'ContextSegmentMeter', setup({ getProps }) { - const segments = SEGMENT_DEFS.map((def, idx) => ({ - ...def, - defaultOrder: idx, - el: h('div', { className: `progress-seg ${def.cls}` }), - })); + // 固定 10 个位置槽位节点,不通过 appendChild 移动 DOM,防止浏览器中断 CSS transition 动画 + const slotEls = SEGMENT_DEFS.map((def) => + h('div', { className: `progress-seg ${def.cls}` }) + ); const trackEl = h( 'div', @@ -2195,28 +2293,38 @@ const ContextSegmentMeter = defineComponent({ 'aria-valuemin': '0', 'aria-valuemax': '100', }, - segments.map((s) => s.el) + slotEls ); - let lastOrderSig = segments.map((s) => s.key).join(','); + let lastOrderSig = ''; function syncMeter() { const ctx = getProps().context || {}; const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000)); - const scored = segments.map((seg) => { - const val = seg.getVal(ctx); + const scored = SEGMENT_DEFS.map((def, defaultOrder) => { + const val = def.getVal(ctx); const pct = Math.min(100, (val / limit) * 100); - patchStyleVar(seg.el, '--seg-w', `${pct.toFixed(2)}%`); - return { seg, val }; + return { def, defaultOrder, val, pct }; }); - scored.sort((a, b) => b.val - a.val || a.seg.defaultOrder - b.seg.defaultOrder); - const nextOrderSig = scored.map((x) => x.seg.key).join(','); - if (nextOrderSig !== lastOrderSig) { - lastOrderSig = nextOrderSig; - for (const { seg } of scored) { - trackEl.appendChild(seg.el); - } + scored.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder); + // 仅关注非零通道的相对顺序变化,决定是否启用 0.05s 先变色再伸缩的衔接延迟 + const activeOrderSig = scored + .filter((x) => x.val > 0) + .map((x) => x.def.key) + .join(','); + const orderChanged = Boolean(lastOrderSig && activeOrderSig && activeOrderSig !== lastOrderSig); + if (activeOrderSig) { + lastOrderSig = activeOrderSig; + } + + patchClasses(trackEl, { 'is-reordering': orderChanged }); + + for (let i = 0; i < slotEls.length; i++) { + const slotEl = slotEls[i]; + const item = scored[i]; + patchAttr(slotEl, 'class', `progress-seg ${item.def.cls}`); + patchStyleVar(slotEl, '--seg-w', `${item.pct.toFixed(2)}%`); } patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); @@ -2226,7 +2334,7 @@ const ContextSegmentMeter = defineComponent({ return { el: trackEl, - refs: { segments }, + refs: { segments: slotEls }, onPropsChange: syncMeter, }; }, @@ -2282,15 +2390,17 @@ function createFourSegmentBar() { // --- src/components/charts/TrendAreaChart.js --- /** - * @fileoverview 纯 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart). - * 负责将按时间分桶的 Token 消耗序列渲染为带垂直渐变填充、虚线参考网格、 - * 峰值描点与自适应防溢出的顶部峰值胶囊标签的面积图。 + * @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart). + * 支持: + * 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染; + * 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数); + * 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。 */ /** * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 - * 控制点沿 X 轴取相邻点间距的 `0.45` 张力系数,Y 轴与各自端点齐平, + * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 * * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组 @@ -2303,33 +2413,59 @@ function buildSmoothSplinePath(points) { for (let i = 0; i < points.length - 1; i++) { const p0 = points[i]; const p1 = points[i + 1]; - const cpx1 = p0.x + (p1.x - p0.x) * 0.45; - const cpx2 = p1.x - (p1.x - p0.x) * 0.45; + const cpx1 = p0.x + (p1.x - p0.x) * 0.42; + const cpx2 = p1.x - (p1.x - p0.x) * 0.42; d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; } return d; } /** - * 创建 SVG 历史趋势平滑面积图组件。 + * 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 * - * SVG 视口坐标系 (`viewBox="0 0 460 116"`) 布局约定: - * - 水平绘图区:`leftX = 12` 至 `rightX = 448`(总跨度 `spanX = 436`),左右预留边距容纳端点圆点描边; - * - 垂直绘图区:顶部峰值线 `topY = 26` 至底部零基线 `bottomY = 98`(总跨度 `spanY = 72`), - * 顶部预留 26px 空间给 HTML 峰值胶囊 (`.trend-peak-pill`)。 + * @param {Array<{ label?: string }>} slots + * @returns {number[]} + */ +function computeTickIndices(slots) { + const n = slots.length; + if (n <= 1) return [0]; + if (n <= 8) { + return Array.from({ length: n }, (_, i) => i); + } + const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); + const maxTicks = sampleLabel.length > 6 ? 5 : 6; + const set = new Set(); + for (let k = 0; k < maxTicks; k++) { + const idx = Math.round((k / (maxTicks - 1)) * (n - 1)); + set.add(idx); + } + return Array.from(set).sort((a, b) => a - b); +} + +/** + * 创建交互式 SVG 历史趋势平滑面积图组件。 * * @returns {{ * el: HTMLElement, - * update: (series?: Array<{ label: string, tokens: number }>) => void - * }} 图表容器节点与序列更新方法 + * update: (series?: Array) => void + * }} */ function createTrendAreaChart() { + const VIEW_W = 460; + const VIEW_H = 120; + const LEFT_X = 14; + const RIGHT_X = 446; + const TOP_Y = 24; + const BOTTOM_Y = 102; + const SPAN_X = RIGHT_X - LEFT_X; + const SPAN_Y = BOTTOM_Y - TOP_Y; + const svg = document.createElementNS(SVG_NS, 'svg'); - svg.setAttribute('viewBox', '0 0 460 116'); + svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`); svg.setAttribute('class', 'trend-svg'); svg.setAttribute('aria-hidden', 'true'); - // 垂直线性渐变:由顶部 36% 不透明度的主题色平滑衰减至底部全透明 + // 垂直线性渐变 const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); grad.setAttribute('id', 'trend-area-grad'); @@ -2341,7 +2477,7 @@ function createTrendAreaChart() { const stop1 = document.createElementNS(SVG_NS, 'stop'); stop1.setAttribute('offset', '0%'); stop1.setAttribute('stop-color', 'var(--ctx-cached)'); - stop1.setAttribute('stop-opacity', '0.36'); + stop1.setAttribute('stop-opacity', '0.34'); const stop2 = document.createElementNS(SVG_NS, 'stop'); stop2.setAttribute('offset', '100%'); @@ -2353,26 +2489,22 @@ function createTrendAreaChart() { defs.appendChild(grad); svg.appendChild(defs); - // 背景辅助参考网格线:3 条水平分位线 + 3 条垂直时间锚点分割线 - const gridGroup = document.createElementNS(SVG_NS, 'g'); - gridGroup.setAttribute('class', 'trend-grid'); - for (const y of [26, 62, 98]) { + // 背景水平与垂直参考网格线 + const hGridGroup = document.createElementNS(SVG_NS, 'g'); + hGridGroup.setAttribute('class', 'trend-grid'); + for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) { const line = document.createElementNS(SVG_NS, 'line'); - line.setAttribute('x1', '10'); + line.setAttribute('x1', String(LEFT_X)); line.setAttribute('y1', String(y)); - line.setAttribute('x2', '450'); + line.setAttribute('x2', String(RIGHT_X)); line.setAttribute('y2', String(y)); - gridGroup.appendChild(line); + hGridGroup.appendChild(line); } - for (const x of [118, 230, 342]) { - const line = document.createElementNS(SVG_NS, 'line'); - line.setAttribute('x1', String(x)); - line.setAttribute('y1', '16'); - line.setAttribute('x2', String(x)); - line.setAttribute('y2', '98'); - gridGroup.appendChild(line); - } - svg.appendChild(gridGroup); + svg.appendChild(hGridGroup); + + const vGridGroup = document.createElementNS(SVG_NS, 'g'); + vGridGroup.setAttribute('class', 'trend-grid trend-v-grid'); + svg.appendChild(vGridGroup); const areaPath = document.createElementNS(SVG_NS, 'path'); areaPath.setAttribute('fill', 'url(#trend-area-grad)'); @@ -2383,25 +2515,157 @@ function createTrendAreaChart() { linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); + const dotsGroup = document.createElementNS(SVG_NS, 'g'); + dotsGroup.setAttribute('class', 'trend-dots-group'); + svg.appendChild(dotsGroup); + const peakDot = document.createElementNS(SVG_NS, 'circle'); peakDot.setAttribute('r', '3'); peakDot.setAttribute('class', 'trend-peak-dot'); svg.appendChild(peakDot); - const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); - const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]); + // 悬停十字准星与焦点圆点 + const hoverLine = document.createElementNS(SVG_NS, 'line'); + hoverLine.setAttribute('class', 'trend-hover-line'); + hoverLine.setAttribute('y1', '12'); + hoverLine.setAttribute('y2', String(BOTTOM_Y)); + hoverLine.setAttribute('hidden', 'true'); + svg.appendChild(hoverLine); - let lastLineD = ''; + const hoverDot = document.createElementNS(SVG_NS, 'circle'); + hoverDot.setAttribute('r', '3.2'); + hoverDot.setAttribute('class', 'trend-hover-dot'); + hoverDot.setAttribute('hidden', 'true'); + svg.appendChild(hoverDot); + + const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); + + // 悬停详情浮层卡片 + const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); + const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); + const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); + const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); + const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + + const tooltipEl = h( + 'div', + { className: 'trend-tooltip', hidden: true }, + [ + h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]), + h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]), + tipSubEl, + ] + ); + + // 底部对齐刻度轴 + const xAxisEl = h('div', { className: 'trend-x-axis' }); + + const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]); + const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]); + + let currentSlots = []; + let currentPts = []; + let tickElsByIdx = new Map(); + let hoveredIdx = -1; + let lastRenderSig = ''; + + function showHoverAtIndex(idx) { + if (idx < 0 || idx >= currentSlots.length || !currentPts[idx]) { + clearHover(); + return; + } + hoveredIdx = idx; + const slot = currentSlots[idx]; + const pt = currentPts[idx]; + + patchAttr(hoverLine, 'hidden', false); + patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); + patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); + + patchAttr(hoverDot, 'hidden', false); + patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); + patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + + patchAttr(peakPill, 'hidden', true); + patchAttr(tooltipEl, 'hidden', false); + + patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); + patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`); + patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`); + patchText( + tipCostEl, + formatUsd(Number(slot.costUsd || 0), { + unpricedCalls: slot.unpricedCalls, + precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1, + }) + ); + + const hasSubBreakdown = + Number(slot.tokens || 0) > 0 && + (slot.inputTokens !== undefined || + slot.cacheReadTokens !== undefined || + slot.outputTokens !== undefined); + patchAttr(tipSubEl, 'hidden', !hasSubBreakdown); + if (hasSubBreakdown) { + patchText( + tipSubEl, + `入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}` + ); + } + + const rawPct = (pt.x / VIEW_W) * 100; + const clampedPct = Math.max(2, Math.min(98, rawPct)); + const shiftX = rawPct < 28 ? '0%' : rawPct > 72 ? '-100%' : '-50%'; + patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-shift', shiftX); + + for (const [tIdx, el] of tickElsByIdx.entries()) { + patchClasses(el, { 'is-hovered': tIdx === idx }); + } + } + + function clearHover() { + hoveredIdx = -1; + patchAttr(hoverLine, 'hidden', true); + patchAttr(hoverDot, 'hidden', true); + patchAttr(tooltipEl, 'hidden', true); + patchAttr(peakPill, 'hidden', false); + for (const el of tickElsByIdx.values()) { + patchClasses(el, { 'is-hovered': false }); + } + } + + function handlePointerMove(e) { + if (!currentSlots.length) return; + const rect = svg.getBoundingClientRect(); + if (!rect || rect.width <= 0) return; + const relX = ((e.clientX - rect.left) / rect.width) * VIEW_W; + const ratio = (relX - LEFT_X) / Math.max(1, SPAN_X); + const idx = Math.max( + 0, + Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1))) + ); + showHoverAtIndex(idx); + } + + plotStage.addEventListener('mousemove', handlePointerMove); + plotStage.addEventListener('mouseleave', clearHover); /** - * 根据最新时间分桶序列重绘平滑曲线、闭合渐变区域以及最高峰标记位置。 + * 根据最新时间分桶序列重绘平滑曲线、渐变区域、峰值气泡与底部对齐刻度。 */ function update(series = []) { - const slots = series.length >= 2 ? series : [ - { label: '00:00', tokens: 0 }, - { label: '06:00', tokens: 0 }, - { label: '12:00', tokens: 0 }, - ]; + const slots = + Array.isArray(series) && series.length >= 2 + ? series + : [ + { label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 }, + { label: '06:00', fullLabel: '06:00 - 07:00', tokens: 0, calls: 0, costUsd: 0 }, + { label: '12:00', fullLabel: '12:00 - 13:00', tokens: 0, calls: 0, costUsd: 0 }, + { label: '18:00', fullLabel: '18:00 - 19:00', tokens: 0, calls: 0, costUsd: 0 }, + ]; + currentSlots = slots; + let maxTokens = 0; let peakIdx = 0; for (let i = 0; i < slots.length; i++) { @@ -2412,39 +2676,92 @@ function createTrendAreaChart() { } } - // SVG 绘图区边界与跨度参数(Y 轴向下递增,因此数值越大对应的 y 坐标越小) - const leftX = 12; - const rightX = 448; - const topY = 26; - const bottomY = 98; - const spanX = rightX - leftX; - const spanY = bottomY - topY; const denom = Math.max(1, maxTokens); - const pts = slots.map((s, idx) => { - const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX; + const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X; const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0; - const y = bottomY - ratio * spanY; - return { x, y }; + const y = BOTTOM_Y - ratio * SPAN_Y; + return { x, y, tokens: Number(s.tokens || 0) }; }); + currentPts = pts; - // 仅在曲线路径发生变化时更新 DOM 属性,避免无意义的 SVG 重绘 - const lineD = buildSmoothSplinePath(pts); - if (lineD !== lastLineD) { - lastLineD = lineD; - const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`; + const sig = slots + .map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`) + .join('|'); + + if (sig !== lastRenderSig) { + lastRenderSig = sig; + const lineD = buildSmoothSplinePath(pts); + const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', areaD); + + // 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签 + const tickIndices = computeTickIndices(slots); + while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild); + while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); + tickElsByIdx = new Map(); + + for (let i = 0; i < tickIndices.length; i++) { + const tIdx = tickIndices[i]; + const pt = pts[tIdx]; + const slot = slots[tIdx]; + if (!pt || !slot) continue; + + if (i > 0 && i < tickIndices.length - 1) { + const vLine = document.createElementNS(SVG_NS, 'line'); + vLine.setAttribute('x1', pt.x.toFixed(1)); + vLine.setAttribute('y1', '16'); + vLine.setAttribute('x2', pt.x.toFixed(1)); + vLine.setAttribute('y2', String(BOTTOM_Y)); + vGridGroup.appendChild(vLine); + } + + const isFirst = i === 0; + const isLast = i === tickIndices.length - 1; + const pct = (pt.x / VIEW_W) * 100; + const tickEl = h('span', { + className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, + text: slot.label || '', + title: slot.fullLabel || slot.label || '', + }); + patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); + tickEl.onclick = () => showHoverAtIndex(tIdx); + xAxisEl.appendChild(tickEl); + tickElsByIdx.set(tIdx, tickEl); + } + + // 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期) + while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); + if (pts.length <= 36) { + for (let i = 0; i < pts.length; i++) { + if (pts[i].tokens <= 0) continue; + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', pts[i].x.toFixed(1)); + dot.setAttribute('cy', pts[i].y.toFixed(1)); + dot.setAttribute('r', '2'); + dot.setAttribute('class', 'trend-node-dot'); + dotsGroup.appendChild(dot); + } + } } - // 定位峰值圆点,并将顶部峰值气泡水平位置钳制在 [8%, 92%] 区间内以防贴边裁切 - const peakPt = pts[peakIdx] || { x: 230, y: bottomY }; + const peakPt = pts[peakIdx] || { x: 230, y: BOTTOM_Y }; patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); - patchText(peakPill, formatTokensPrecise(maxTokens)); - const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100)); + const peakSlot = slots[peakIdx]; + const peakText = + maxTokens > 0 && peakSlot?.label + ? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` + : formatTokensPrecise(maxTokens); + patchText(peakPill, peakText); + const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + + if (hoveredIdx >= 0 && hoveredIdx < slots.length) { + showHoverAtIndex(hoveredIdx); + } } return { el: chartWrap, update }; @@ -2537,59 +2854,7 @@ const TopSessionHeader = defineComponent({ h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]), ]); - // --- 方案 A:顶栏二级主/子代理切换条 (.agent-scope-bar,无子代理时自动隐藏) --- - const scopeAllBtnText = h('span', { text: '全部汇总' }); - const scopeAllBtn = h( - 'button', - { - type: 'button', - className: 'scope-pill-btn is-active', - onClick: () => - uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }), - }, - [scopeAllBtnText] - ); - - const scopeMainBtnText = h('span', { text: '主代理' }); - const scopeMainBtn = h( - 'button', - { - type: 'button', - className: 'scope-pill-btn', - onClick: () => uiStore.setState({ selectedAgentScope: 'main' }), - }, - [scopeMainBtnText] - ); - - const subagentSelect = CustomSelect({ - modelValue: '', - icon: 'cpu', - placeholder: '子代理 (0)', - className: 'scope-subagent-select', - options: [], - onUpdateModelValue: (nextSubId) => { - if (nextSubId) { - uiStore.setState({ selectedAgentScope: nextSubId }); - } - }, - }); - - const scopeRightText = h('span', { className: 'agent-scope-right text-mono', text: '' }); - - const scopeBarEl = h( - 'div', - { className: 'agent-scope-bar', hidden: true }, - [ - h('div', { className: 'agent-scope-left' }, [ - scopeAllBtn, - scopeMainBtn, - subagentSelect.el, - ]), - scopeRightText, - ] - ); - - const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl, scopeBarEl]); + const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); let lastActiveCascadeId = ''; @@ -2623,45 +2888,9 @@ const TopSessionHeader = defineComponent({ options, }); - const { - hasSubagents, - effectiveScope, - subagents, - mainAgent, - aggregated, - scopedConv, - } = resolveScopedConversation(telemetry, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId); - - patchAttr(scopeBarEl, 'hidden', !hasSubagents); - if (hasSubagents) { - patchText(scopeAllBtnText, `全部 (${aggregated?.stepCount ?? 0})`); - patchClasses(scopeAllBtn, { 'is-active': effectiveScope === 'all' }); - - patchText(scopeMainBtnText, `主代理 (${mainAgent?.stepCount ?? 0})`); - patchClasses(scopeMainBtn, { 'is-active': effectiveScope === 'main' }); - - const isSubSelected = effectiveScope !== 'all' && effectiveScope !== 'main'; - patchClasses(subagentSelect.el, { 'is-active-sub': isSubSelected }); - const subOptions = subagents.map((s) => ({ - value: s.agentId, - label: formatAgentLabel(s), - meta: `${s.stepCount || 0}步 · 窗${s.context?.usedPct ?? 0}%`, - })); - subagentSelect.setProps({ - modelValue: isSubSelected ? effectiveScope : '', - placeholder: `子代理 (${subagents.length})`, - options: subOptions, - }); - - patchText( - scopeRightText, - formatUsd(scopedConv?.sessionCostUsd || 0, { - unpricedCalls: scopedConv?.sessionUnpricedCalls, - }) - ); - } else { - subagentSelect.close(); - } + const actConv = telemetry?.activeConversation; + const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0); + const aggregated = actConv?.aggregated; const cloudStatus = telemetry?.cloudStatus; const hasUpdate = Boolean(cloudStatus?.updateAvailable); @@ -2748,21 +2977,14 @@ const TopSessionHeader = defineComponent({ () => renderHeaderState() ); - const unsubUi = uiStore.subscribe( - (st) => st.selectedAgentScope, - () => renderHeaderState() - ); - onCleanup(() => { unsubTelemetry(); - unsubUi(); convSelect.destroy(); - subagentSelect.destroy(); }); return { el: headerEl, - refs: { convSelect, subagentSelect, statusTag, refreshBtn, scopeBarEl }, + refs: { convSelect, statusTag, refreshBtn }, }; }, }); @@ -2796,6 +3018,145 @@ function estPillWidth(text) { const LiveOverviewView = defineComponent({ name: 'LiveOverviewView', setup({ onCleanup }) { + // --- 0. 可用额度下方的多任务实时运行卡片列表 (展示所有正在运行的主进程 + 默认主代理缩略 + 可折叠子代理列表) --- + const liveActivityBar = h('div', { + className: 'live-activity-list', + hidden: true, + 'aria-live': 'polite', + }); + + const expandedTaskConvIds = new Set(); + const activityTimersMap = new Map(); + let liveTickTimer = null; + + function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { + const now = Date.now(); + const prev = activityTimersMap.get(timerKey); + let startMs = prev?.startMs || 0; + if (!prev || prev.sig !== sig) { + const validRaw = Number(rawStartMs || 0); + startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; + } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { + startMs = Number(rawStartMs); + } + activityTimersMap.set(timerKey, { sig, startMs, el: targetEl }); + const elapsedSec = Math.max(0, (now - startMs) / 1000); + patchText(targetEl, formatElapsedSec(elapsedSec)); + } + + function updateLiveElapsedDisplay() { + const now = Date.now(); + for (const entry of activityTimersMap.values()) { + if (!entry?.el) continue; + const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; + patchText(entry.el, formatElapsedSec(elapsedSec)); + } + } + + function stopLiveTicker() { + if (liveTickTimer) { + clearInterval(liveTickTimer); + liveTickTimer = null; + } + activityTimersMap.clear(); + } + + function ensureLiveTicker() { + if (!liveTickTimer) { + liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000); + } + } + + function createLiveTaskCard() { + const dotIcon = createSvgIcon('dot', { size: 9 }); + patchClasses(dotIcon, { 'is-pulsing': true }); + const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); + const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' }); + const subToggleBtn = h('button', { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + text: '子代理 (0) ▸', + }); + const elapsedEl = h('span', { + className: 'live-activity-elapsed text-mono', + text: '0s', + }); + + const headerEl = h('div', { className: 'live-task-header' }, [ + h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), + h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), + ]); + + const mainBadge = h('span', { className: 'agent-badge badge-main', text: '主' }); + const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' }); + const mainProgress = h('span', { + className: 'live-activity-progress text-mono', + hidden: true, + text: '', + }); + const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); + const mainDetail = h('span', { + className: 'live-activity-detail', + hidden: true, + text: '', + }); + + const mainRowEl = h('div', { className: 'live-task-main-row' }, [ + mainBadge, + mainPhase, + mainProgress, + mainSep, + mainDetail, + ]); + + const subListEl = h('div', { className: 'live-sub-list', hidden: true }); + const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + + return { + el: cardEl, + refs: { + cardEl, + dotIcon, + titleEl, + subToggleBtn, + elapsedEl, + mainPhase, + mainProgress, + mainSep, + mainDetail, + subListEl, + }, + }; + } + + function createLiveSubRow() { + const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: '子1' }); + const subRole = h('span', { className: 'live-sub-role', text: '子代理' }); + 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, + }, + }; + } + // --- 1. 4 格实时测速矩阵 (实时吞吐 / 首Token / 会话均速 / 本步消费) --- const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); const tpsSub = h('span', { className: 'cell-sub', text: '模型未知' }); @@ -3020,7 +3381,7 @@ const LiveOverviewView = defineComponent({ { style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', }, - [matrixEl, ctxPanel, quotaPanel] + [matrixEl, ctxPanel, quotaPanel, liveActivityBar] ); const viewScrollbar = CustomScrollbar({ contentEl: overviewInner, @@ -3126,24 +3487,246 @@ const LiveOverviewView = defineComponent({ const uiSt = uiStore.getState(); const { hasSubagents, - effectiveScope, effectiveCtxScope, agents, aggregated, scopedConv, ctxAgent, - } = resolveScopedConversation(data, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId); + } = resolveScopedConversation(data, 'all', uiSt.ctxInspectorAgentId); const active = scopedConv || data.activeConversation || {}; const ctx = ctxAgent?.context || active.context || {}; const quotas = data.quotas || {}; - // 1. 更新 4 格实时测速矩阵(根据当前代理作用域动态展示全部汇总或单代理指标) + // 0. 更新多任务实时运行列表(展示所有正在运行的主进程 + 默认主代理缩略 + 默认收起的子代理列表) + 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 || '当前会话', + 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: s.badgeText || `子${idx + 1}`, + shortLabel: s.shortLabel || `子代理 #${idx + 1}`, + role: s.role || `子代理 #${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 ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ] + : []; + + const hasRunningTasks = rawRunningList.length > 0; + patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); + if (!hasRunningTasks) { + stopLiveTicker(); + } else { + // 先基于完整运行列表收集所有有效计时器 Key(防止 patchKeyedList 在 sig 未变化跳过 updateRow 时误删计时器) + const activeTimerKeys = new Set(); + for (const item of rawRunningList) { + activeTimerKeys.add(`main:${item.cascadeId}`); + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } + } + } + // 清理已结束会话的展开状态 + const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); + for (const id of [...expandedTaskConvIds]) { + if (!runningIdsSet.has(id)) { + expandedTaskConvIds.delete(id); + } + } + + patchKeyedList(liveActivityBar, rawRunningList, { + keyFn: (item) => item.cascadeId, + sigFn: (item) => { + const isExp = expandedTaskConvIds.has(item.cascadeId); + const subSig = (item.subagents || []) + .map( + (s) => + `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}` + ) + .join('|'); + return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${subSig}`; + }, + createRow: createLiveTaskCard, + updateRow: (refs, item) => { + const act = item.mainActivity || { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: item.lastModifiedMs || 0, + signature: `fallback:${item.lastModifiedMs || 0}`, + }; + + const isWaiting = act.phase === 'waiting'; + patchClasses(refs.cardEl, { 'is-waiting': isWaiting }); + patchClasses(refs.dotIcon, { 'is-pulsing': true }); + + const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话'; + patchText(refs.titleEl, convTitle); + patchAttr(refs.titleEl, 'title', `点击切换查看会话:${convTitle}`); + refs.titleEl.onclick = () => { + if (item.cascadeId && item.cascadeId !== 'current') { + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + telemetryStore.setState({ selectedConversationId: item.cascadeId }); + fetchTelemetry({ force: false }); + } + }; + + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const runSubCount = Number(item.runningSubagentCount || 0); + const isExpanded = expandedTaskConvIds.has(item.cascadeId); + patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); + if (subCount > 0) { + const arrow = isExpanded ? '▾' : '▸'; + const toggleText = + runSubCount > 0 + ? `子代理 ${runSubCount}/${subCount} ${arrow}` + : `子代理 (${subCount}) ${arrow}`; + patchText(refs.subToggleBtn, toggleText); + patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); + patchAttr( + refs.subToggleBtn, + 'title', + isExpanded ? '点击收起子代理列表' : '点击展开查看子代理缩略状态' + ); + refs.subToggleBtn.onclick = (e) => { + e.stopPropagation(); + if (expandedTaskConvIds.has(item.cascadeId)) { + expandedTaskConvIds.delete(item.cascadeId); + } else { + expandedTaskConvIds.add(item.cascadeId); + } + renderData(latestData); + }; + } + + const mainTimerKey = `main:${item.cascadeId}`; + activeTimerKeys.add(mainTimerKey); + bindLiveElapsedTimer( + mainTimerKey, + `${item.cascadeId}:${act.signature || act.label}`, + act.startedAtMs, + refs.elapsedEl + ); + + patchText(refs.mainPhase, act.label || '推理中'); + 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 fullTooltip = `[${convTitle}] 主代理 · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; + patchAttr(refs.cardEl, 'title', fullTooltip); + + const showSubs = subCount > 0 && isExpanded; + patchAttr(refs.subListEl, 'hidden', !showSubs); + if (showSubs) { + const subItems = item.subagents || []; + patchKeyedList(refs.subListEl, subItems, { + keyFn: (sub) => sub.cascadeId, + sigFn: (sub) => + `${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, + createRow: createLiveSubRow, + updateRow: (subRefs, sub) => { + const subAct = sub.liveActivity || { + phase: sub.isRunning ? 'thinking' : 'done', + label: sub.isRunning ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: sub.lastModifiedMs || 0, + }; + patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); + + const badgeCls = getAgentBadgeClass(sub.index || 1, false); + patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); + patchText(subRefs.subBadge, sub.badgeText || `子${sub.index || 1}`); + + const roleText = sub.role || sub.shortLabel || '子代理'; + patchText(subRefs.subRole, roleText); + + const rawSubLabel = sub.isRunning ? subAct.label || '' : subAct.label || '已完成'; + const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; + const summaryStr = [ + `${rawSubLabel}${subProg}`.trim(), + subAct.detail || '', + ] + .filter(Boolean) + .join(' '); + patchAttr(subRefs.subSummary, 'hidden', !summaryStr); + patchText(subRefs.subSummary, summaryStr); + + patchAttr( + subRefs.rowEl, + 'title', + `[${sub.badgeText || '子'}] ${roleText}${summaryStr ? ` ${summaryStr}` : ''}` + ); + + if (sub.isRunning) { + const subTimerKey = `sub:${sub.cascadeId}`; + activeTimerKeys.add(subTimerKey); + bindLiveElapsedTimer( + subTimerKey, + `${sub.cascadeId}:${subAct.signature || subAct.label}`, + subAct.startedAtMs, + subRefs.subElapsed + ); + } else { + patchText(subRefs.subElapsed, `${sub.stepCount || 0}步`); + } + }, + }); + } + }, + }); + + for (const key of [...activityTimersMap.keys()]) { + if (!activeTimerKeys.has(key)) { + activityTimersMap.delete(key); + } + } + updateLiveElapsedDisplay(); + ensureLiveTicker(); + } + + // 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标) patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) }); patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s')); const reason = speedReasonText(active.latestSpeedReason); const modelAndAgent = - hasSubagents && effectiveScope === 'all' && active.activeAgentBadge + hasSubagents && active.activeAgentBadge ? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}` : active.activeModelShort || '模型未知'; patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent); @@ -3161,7 +3744,7 @@ const LiveOverviewView = defineComponent({ `缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}` ); - // 2. 更新 6 段上下文窗口构成与方案 B 内嵌上下文窗口检视胶囊条 + // 2. 更新 10 段上下文窗口构成与内嵌上下文窗口检视胶囊条 patchAttr(ctxAgentBadge, 'hidden', !hasSubagents); patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (hasSubagents && ctxAgent) { @@ -3171,37 +3754,24 @@ const LiveOverviewView = defineComponent({ patchText(ctxAgentBadge, badgeFullText); patchAttr(ctxAgentBadge, 'title', badgeFullText); - const pillItems = []; - if (effectiveScope === 'all') { - pillItems.push({ + const pillItems = [ + { key: 'auto', label: `跟随活跃 (${aggregated?.activeAgentBadge || '主'})`, title: '自动展示当前正在运行或最新活跃的代理上下文窗口', isActive: effectiveCtxScope === 'auto', mode: 'ctx-only', - }); - } else { - pillItems.push({ - key: 'all', - label: `全部汇总 (${aggregated?.stepCount ?? 0}步)`, - title: '切回全部代理汇总视图', - isActive: false, - mode: 'scope', - }); - } + }, + ]; const allAgentPills = agents.map((ag) => { const agPct = ag.context?.usedPct ?? 0; - const isAct = - effectiveScope === 'all' - ? effectiveCtxScope === ag.agentId - : effectiveScope === ag.agentId; return { key: ag.agentId, label: `${ag.badgeText || ag.shortLabel} ${agPct}%`, title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`, - isActive: isAct, - mode: effectiveScope === 'all' ? 'ctx-only' : 'scope', + isActive: effectiveCtxScope === ag.agentId, + mode: 'ctx-only', }; }); @@ -3375,6 +3945,15 @@ const LiveOverviewView = defineComponent({ (data) => { latestData = data; if (uiStore.getState().activeView !== 'overview') { + const stillRunning = + (Array.isArray(data?.runningConversations) && data.runningConversations.length > 0) || + Boolean( + data?.activeConversation?.isRunning || + data?.activeConversation?.aggregated?.isRunning + ); + if (!stillRunning) { + stopLiveTicker(); + } isDirty = true; return; } @@ -3383,19 +3962,15 @@ const LiveOverviewView = defineComponent({ } ); - let prevScope = uiStore.getState().selectedAgentScope; let prevCtxTarget = uiStore.getState().ctxInspectorAgentId; const unsubView = uiStore.subscribe( (st) => ({ activeView: st.activeView, - selectedAgentScope: st.selectedAgentScope, ctxInspectorAgentId: st.ctxInspectorAgentId, }), (slice) => { - const scopeChanged = - slice.selectedAgentScope !== prevScope || slice.ctxInspectorAgentId !== prevCtxTarget; - prevScope = slice.selectedAgentScope; + const scopeChanged = slice.ctxInspectorAgentId !== prevCtxTarget; prevCtxTarget = slice.ctxInspectorAgentId; if (slice.activeView !== 'overview') { @@ -3426,6 +4001,7 @@ const LiveOverviewView = defineComponent({ } onCleanup(() => { + stopLiveTicker(); unsub(); unsubView(); if (ro) ro.disconnect(); @@ -3499,7 +4075,20 @@ const ConsumptionView = defineComponent({ className: 'btn-primary', style: 'height: 26px; padding: 0 10px;', onClick: () => { - telemetryStore.setState({ selectedTimeRange: 'custom' }); + const st = telemetryStore.getState(); + const sMs = Number(st.customStartMs || 0); + const eMs = Number(st.customEndMs || 0); + if (sMs > 0 && eMs > 0 && sMs > eMs) { + startPicker.setValue(eMs); + endPicker.setValue(sMs); + telemetryStore.setState({ + selectedTimeRange: 'custom', + customStartMs: eMs, + customEndMs: sMs, + }); + } else { + telemetryStore.setState({ selectedTimeRange: 'custom' }); + } fetchTelemetry({ force: true }); }, }, @@ -3596,27 +4185,24 @@ const ConsumptionView = defineComponent({ overviewSegBar.el, ]); - // --- Section 2: 历史趋势 (SVG 三次贝塞尔平滑曲线图 + 首/中/末三时间锚点) --- + // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 多刻度时间轴) --- const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' }); + const trendGranularityHint = h('span', { + className: 'text-muted text-mono', + style: 'font-size: 10.5px;', + text: '按小时 · 悬停查看明细', + }); const trendChart = createTrendAreaChart(); - const anchorStartTime = h('span', { className: 'text-muted text-mono', text: '00:00' }); - const anchorStartVal = h('strong', { className: 'text-mono', text: '0' }); - const anchorMidTime = h('span', { className: 'text-muted text-mono', text: '06:00' }); - const anchorMidVal = h('strong', { className: 'text-mono', text: '0' }); - const anchorEndTime = h('span', { className: 'text-muted text-mono', text: '12:00' }); - const anchorEndVal = h('strong', { className: 'text-mono', text: '0' }); const trendPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ - h('span', { className: 'panel-title', text: '用量趋势' }), - trendRangeBadge, + h('span', { className: 'panel-title' }, [ + h('span', { text: '用量趋势' }), + trendRangeBadge, + ]), + trendGranularityHint, ]), trendChart.el, - h('div', { className: 'trend-anchors' }, [ - h('div', { className: 'trend-anchor-col' }, [anchorStartTime, anchorStartVal]), - h('div', { className: 'trend-anchor-col is-center' }, [anchorMidTime, anchorMidVal]), - h('div', { className: 'trend-anchor-col is-end' }, [anchorEndTime, anchorEndVal]), - ]), ]); // --- Section 3: 模型排行列表 --- @@ -3878,21 +4464,17 @@ const ConsumptionView = defineComponent({ thinkingTokens, }); - // 2. 同步历史趋势 SVG 面积图与首/中/末三时间锚点 + // 2. 同步历史趋势交互式 SVG 面积图与粒度提示 patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间'); const trendSeries = cons.trendSeries || []; + const isHourlyTrend = + trendSeries[0]?.granularity === 'hour' || + (trendSeries[0]?.label || '').includes(':'); + patchText( + trendGranularityHint, + `${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看` + ); trendChart.update(trendSeries); - if (trendSeries.length > 0) { - const first = trendSeries[0]; - const mid = trendSeries[Math.floor(trendSeries.length / 2)]; - const last = trendSeries[trendSeries.length - 1]; - patchText(anchorStartTime, first.label); - patchText(anchorStartVal, formatTokensPrecise(first.tokens)); - patchText(anchorMidTime, mid.label); - patchText(anchorMidVal, formatTokensPrecise(mid.tokens)); - patchText(anchorEndTime, last.label); - patchText(anchorEndVal, formatTokensPrecise(last.tokens)); - } // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账) const models = (slice.modelBreakdown || []) @@ -4190,15 +4772,15 @@ const StepsDetailView = defineComponent({ slice.recentSteps || []; const models = - hasSubagents && Array.isArray(scopedConv?.modelBreakdown) + (Array.isArray(scopedConv?.modelBreakdown) && scopedConv.modelBreakdown.length > 0 ? scopedConv.modelBreakdown - : slice.modelBreakdown || []; + : slice.sessionModelBreakdown || slice.modelBreakdown) || []; const showUpstream = Boolean(slice.showUpstreamModel); const modelsTabBadge = hasSubagents ? effectiveScope === 'all' ? '本会话汇总' : scopedConv?.shortLabel || '当前代理' - : slice.rangeLabel; + : '本会话'; subTabSwitch.setProps({ options: [ @@ -4354,6 +4936,7 @@ const StepsDetailView = defineComponent({ activeConversation: st.telemetry?.activeConversation, cascadeId: st.telemetry?.activeConversation?.cascadeId, recentSteps: st.telemetry?.activeConversation?.recentSteps, + sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown, modelBreakdown: st.telemetry?.modelBreakdown, rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间', showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), @@ -4480,11 +5063,11 @@ const SettingsView = defineComponent({ statusTimer = null; } patchText(saveStatusText, text); - if (text === '已保存') { + if (text === '已保存' || text === '保存失败') { statusTimer = setTimeout(() => { statusTimer = null; patchText(saveStatusText, ''); - }, 1500); + }, text === '保存失败' ? 2500 : 1500); } } @@ -4526,10 +5109,14 @@ const SettingsView = defineComponent({ }); } showSaveFeedback('保存中…'); - await saveSettingsPatch({ - showUpstreamModel: draftShowUpstreamModel, - }); - showSaveFeedback('已保存'); + try { + await saveSettingsPatch({ + showUpstreamModel: draftShowUpstreamModel, + }); + showSaveFeedback('已保存'); + } catch { + showSaveFeedback('保存失败'); + } }, }); @@ -4547,10 +5134,14 @@ const SettingsView = defineComponent({ }); } showCloudFeedback('保存中…', 0); - await saveSettingsPatch({ - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - showCloudFeedback('已保存', 1800); + try { + await saveSettingsPatch({ + autoUpdatePlugin: draftAutoUpdatePlugin, + }); + showCloudFeedback('已保存', 1800); + } catch { + showCloudFeedback('保存失败', 2500); + } }, }); @@ -4581,14 +5172,18 @@ const SettingsView = defineComponent({ className: 'btn-primary', onClick: async () => { showSaveFeedback('保存中…'); - await saveSettingsPatch({ - weeklyLimitMode: draftMode, - weeklyTokenBudget: draftTokens, - weeklyCostBudget: draftCost, - showUpstreamModel: draftShowUpstreamModel, - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - showSaveFeedback('已保存'); + try { + await saveSettingsPatch({ + weeklyLimitMode: draftMode, + weeklyTokenBudget: draftTokens, + weeklyCostBudget: draftCost, + showUpstreamModel: draftShowUpstreamModel, + autoUpdatePlugin: draftAutoUpdatePlugin, + }); + showSaveFeedback('已保存'); + } catch { + showSaveFeedback('保存失败'); + } }, }, [createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })] diff --git a/sidecars/panel/backend/config.mjs b/sidecars/panel/backend/config.mjs index 48f7eb5..eb5fb24 100644 --- a/sidecars/panel/backend/config.mjs +++ b/sidecars/panel/backend/config.mjs @@ -38,6 +38,7 @@ export const REMOTE_CATALOG_CACHE_FILE = join(DATA_DIR, 'remote_pricing_cache.js * 本地对话记录目录与跨端深层统计缓存路径候选列表。 */ export const CONVERSATIONS_DIR = join(homedir(), '.gemini', 'antigravity', 'conversations'); +export const BRAIN_DIR = join(homedir(), '.gemini', 'antigravity', 'brain'); export const DEEP_STATS_CACHE_CANDIDATES = [ join(homedir(), '.gemini', 'antigravity-ide', 'brain', '.deep_stats_cache.json'), join(homedir(), '.gemini', 'antigravity', 'brain', '.deep_stats_cache.json'), @@ -108,7 +109,9 @@ export function loadJson(filePath, fallback) { export function saveJson(filePath, data) { try { mkdirSync(DATA_DIR, { recursive: true }); - writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf8'); + const serialized = + filePath === CACHE_FILE ? JSON.stringify(data) : JSON.stringify(data, null, 2); + writeFileSync(filePath, serialized, 'utf8'); return true; } catch (err) { console.error(`Failed writing ${filePath}: ${err.message}`); @@ -116,16 +119,39 @@ export function saveJson(filePath, data) { } } +const VALID_WEEKLY_MODES = new Set(['official', 'tokens', 'cost']); + +function sanitizeSettingNumber(val, fallback) { + const num = Number(val); + return Number.isFinite(num) && num > 0 ? num : fallback; +} + /** - * 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode`。 + * 读取用户设置并与默认设置合并,同时剔除已废弃的历史字段 `speedMode` 并兜底非法数值。 * * @returns {typeof DEFAULT_SETTINGS} */ export function loadSettings() { - const { speedMode: _legacySpeedMode, ...settings } = loadJson(SETTINGS_FILE, {}); + const raw = loadJson(SETTINGS_FILE, {}); + const { speedMode: _legacySpeedMode, ...settings } = + raw && typeof raw === 'object' ? raw : {}; const merged = { ...DEFAULT_SETTINGS, ...settings }; + const mode = String(merged.weeklyLimitMode || '').trim(); return { ...merged, + contextWindowLimit: sanitizeSettingNumber( + merged.contextWindowLimit, + DEFAULT_SETTINGS.contextWindowLimit + ), + weeklyTokenBudget: sanitizeSettingNumber( + merged.weeklyTokenBudget, + DEFAULT_SETTINGS.weeklyTokenBudget + ), + weeklyCostBudget: sanitizeSettingNumber( + merged.weeklyCostBudget, + DEFAULT_SETTINGS.weeklyCostBudget + ), + weeklyLimitMode: VALID_WEEKLY_MODES.has(mode) ? mode : DEFAULT_SETTINGS.weeklyLimitMode, showUpstreamModel: merged.showUpstreamModel === true, autoUpdatePlugin: merged.autoUpdatePlugin === true, }; @@ -146,25 +172,41 @@ export function roundMetric(value) { // --------------------------------------------------------------------------- const loadedTrajectoryCache = loadJson(CACHE_FILE, {}); +let initialCacheMigrated = false; /** * 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }` */ export const trajectoryCache = Object.fromEntries( - Object.entries(loadedTrajectoryCache).map(([id, entry]) => [ - id, - { - ...entry, - steps: inferCompactionStepModels((entry.steps || []).map(normalizeCachedStep)), - }, - ]) + Object.entries(loadedTrajectoryCache).map(([id, entry]) => { + const rawSteps = Array.isArray(entry?.steps) ? entry.steps : []; + const normalizedSteps = rawSteps.map((s) => { + const norm = normalizeCachedStep(s); + if (norm !== s) initialCacheMigrated = true; + return norm; + }); + const finalSteps = inferCompactionStepModels(normalizedSteps); + for (let i = 0; i < finalSteps.length; i++) { + if (finalSteps[i] !== normalizedSteps[i]) { + initialCacheMigrated = true; + break; + } + } + return [ + id, + { + ...entry, + steps: finalSteps, + }, + ]; + }) ); /** * 缓存状态与外部深层统计缓存 Memo。 */ export const cacheState = { - needsSave: JSON.stringify(trajectoryCache) !== JSON.stringify(loadedTrajectoryCache), + needsSave: initialCacheMigrated, }; export const externalDeepStatsMemo = { diff --git a/sidecars/panel/backend/local-scanner.mjs b/sidecars/panel/backend/local-scanner.mjs index 8df2fd9..21fdc74 100644 --- a/sidecars/panel/backend/local-scanner.mjs +++ b/sidecars/panel/backend/local-scanner.mjs @@ -8,10 +8,11 @@ * 拉取新增或 Schema 过期的会话轨迹步骤,持久化至 `trajectory_usage_cache.json`。 */ -import { existsSync, readdirSync, statSync } from 'node:fs'; +import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from 'node:fs'; import { join } from 'node:path'; -import { extractModelSteps, parseIsoMs } from '../speed-metrics.mjs'; +import { extractLiveActivity, extractModelSteps, parseIsoMs } from '../speed-metrics.mjs'; import { + BRAIN_DIR, CACHE_FILE, CACHE_SCHEMA_VERSION, CONVERSATIONS_DIR, @@ -171,7 +172,176 @@ const MAX_CONCURRENT_RPC = 4; const LEGACY_MIGRATION_BATCH_SIZE = 8; const MAX_SUBAGENT_RECONCILE_DEPTH = 4; const FAILED_RPC_COOLDOWN_MS = 60_000; +const TRANSCRIPT_TAIL_MAX_BYTES = 96 * 1024; +const MAX_TRANSCRIPT_MEMO_ENTRIES = 64; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; const failedFetchCooldownMap = new Map(); +const liveActivityMemo = new Map(); +const transcriptTailMemo = new Map(); + +/** + * 读取指定会话在本地 `brain//.system_generated/logs/transcript.jsonl` 的尾部步骤。 + * 采用 `mtimeMs + size` 签名缓存与尾部 96KB 定长切片读取,避免长会话大文件全量读取阻塞事件循环。 + * + * @param {string} cascadeId + * @param {number} [maxLines=24] + * @returns {object[]} + */ +function readTranscriptTailSteps(cascadeId, maxLines = 24) { + if (!cascadeId) return []; + const normId = String(cascadeId).trim().toLowerCase(); + if (!UUID_RE.test(normId)) return []; + const transcriptPath = join( + BRAIN_DIR, + normId, + '.system_generated', + 'logs', + 'transcript.jsonl' + ); + if (!existsSync(transcriptPath)) return []; + try { + const st = statSync(transcriptPath); + const mtimeMs = Number(st?.mtimeMs || 0); + const size = Number(st?.size || 0); + const cached = transcriptTailMemo.get(normId); + if (cached && cached.mtimeMs === mtimeMs && cached.size === size && size > 0) { + return cached.steps; + } + + let raw = ''; + if ( + size > TRANSCRIPT_TAIL_MAX_BYTES && + typeof openSync === 'function' && + typeof readSync === 'function' && + typeof closeSync === 'function' + ) { + const fd = openSync(transcriptPath, 'r'); + try { + const buf = Buffer.allocUnsafe(TRANSCRIPT_TAIL_MAX_BYTES); + const bytesRead = readSync( + fd, + buf, + 0, + TRANSCRIPT_TAIL_MAX_BYTES, + size - TRANSCRIPT_TAIL_MAX_BYTES + ); + raw = buf.toString('utf8', 0, bytesRead); + const trimmedRaw = raw.replace(/[\r\n]+$/, ''); + const firstNewline = trimmedRaw.indexOf('\n'); + if (firstNewline >= 0 && !trimmedRaw.trimStart().startsWith('{')) { + raw = trimmedRaw.slice(firstNewline + 1); + } else { + raw = trimmedRaw; + } + } finally { + try { + closeSync(fd); + } catch { + // 忽略关闭异常 + } + } + } else { + raw = readFileSync(transcriptPath, 'utf8'); + } + + if (typeof raw !== 'string' || !raw.trim()) { + transcriptTailMemo.set(normId, { mtimeMs, size, steps: [] }); + return []; + } + const lines = raw.trim().split(/\r?\n/); + const tail = lines.slice(-maxLines); + const steps = []; + for (const line of tail) { + const trimmed = line.trim(); + if (!trimmed) continue; + try { + const parsed = JSON.parse(trimmed); + if (parsed && typeof parsed === 'object') { + steps.push(parsed); + } + } catch { + // 忽略头部被截断或末尾正在写入的半行 JSON + } + } + if (transcriptTailMemo.size >= MAX_TRANSCRIPT_MEMO_ENTRIES && !transcriptTailMemo.has(normId)) { + const oldestKey = transcriptTailMemo.keys().next().value; + if (oldestKey !== undefined) transcriptTailMemo.delete(oldestKey); + } + transcriptTailMemo.set(normId, { mtimeMs, size, steps }); + return steps; + } catch { + return []; + } +} + +function scoreLiveActivitySpecificity(act) { + if (!act || typeof act !== 'object') return 0; + const sig = String(act.signature || ''); + if ( + sig.startsWith('planner-tool:') || + sig.startsWith('step-run:') || + sig.startsWith('pending-tool:') + ) { + return 4; + } + if ( + sig.startsWith('compacting:') || + sig.startsWith('responding:') || + sig.startsWith('thinking:') || + sig.startsWith('responding-done:') || + sig.startsWith('thinking-done:') + ) { + return 3; + } + if ( + sig.startsWith('post-tool-think:') || + sig.startsWith('post-step-tool:') + ) { + return 2; + } + return 1; +} + +function extractActivityStepOrd(act) { + const m = String(act?.signature || '').match(/^[a-z0-9-]+:(\d+)(?::|$)/i); + return m ? Number(m[1]) : -1; +} + +function resolveBestLiveActivity(cascadeId, rpcRawSteps, isRunning, fallbackMs) { + if (!isRunning) return null; + const rpcAct = + Array.isArray(rpcRawSteps) && rpcRawSteps.length > 0 + ? extractLiveActivity(rpcRawSteps, true, fallbackMs) + : null; + const transcriptSteps = readTranscriptTailSteps(cascadeId); + const transcriptAct = + transcriptSteps.length > 0 ? extractLiveActivity(transcriptSteps, true, fallbackMs) : null; + + if (rpcAct && transcriptAct) { + const rpcMs = Number(rpcAct.startedAtMs || 0); + const transMs = Number(transcriptAct.startedAtMs || 0); + if (rpcMs > 0 && transMs > 0 && rpcMs !== transMs) { + return rpcMs > transMs ? rpcAct : transcriptAct; + } + const rpcOrd = extractActivityStepOrd(rpcAct); + const transOrd = extractActivityStepOrd(transcriptAct); + if (rpcOrd >= 0 && transOrd >= 0 && rpcOrd !== transOrd) { + return rpcOrd > transOrd ? rpcAct : transcriptAct; + } + const rpcScore = scoreLiveActivitySpecificity(rpcAct); + const transScore = scoreLiveActivitySpecificity(transcriptAct); + if (transScore > rpcScore) return transcriptAct; + if (rpcScore > transScore) return rpcAct; + // 同步骤、同优先级下优先采用包含完整 tool_calls 参数的 transcript.jsonl 解析结果 + return transcriptAct; + } + return ( + transcriptAct || + rpcAct || + liveActivityMemo.get(String(cascadeId || '').toLowerCase()) || + extractLiveActivity([], true, fallbackMs) + ); +} /** * 清洗并裁剪 `subagentSpec`,仅保留 UI 与分组所需的 `typeName` 和 `role`, @@ -327,6 +497,12 @@ export async function enumerateAndSyncConversations({ currentAccountName = '', requestedConvId = '', }) { + const nowSweepMs = Date.now(); + for (const [k, ts] of failedFetchCooldownMap.entries()) { + if (nowSweepMs - ts >= FAILED_RPC_COOLDOWN_MS) { + failedFetchCooldownMap.delete(k); + } + } const diskConvMap = discoverLocalConversationFiles(); const allCascadeIds = new Set([ ...Object.keys(summariesObj), @@ -551,9 +727,23 @@ export async function enumerateAndSyncConversations({ conv.lastModifiedMs = resolvedLastModMs; conv.stepCount = steps.length; + const liveAct = resolveBestLiveActivity( + conv.cascadeId, + rawSteps, + isRunning, + resolvedLastModMs || conv.createdTimeMs || 0 + ); + if (liveAct) { + conv.liveActivity = liveAct; + liveActivityMemo.set(conv.cascadeId.toLowerCase(), liveAct); + } else { + conv.liveActivity = null; + liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + } + const cacheEntry = { signature: sig, - accountName: currentAccountName || prev?.accountName || '', + accountName: prev?.accountName || currentAccountName || '', title: conv.title, lastModifiedMs: resolvedLastModMs, diskMtimeMs: conv.diskMtimeMs || 0, @@ -589,6 +779,18 @@ export async function enumerateAndSyncConversations({ console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`); if (!isRunning) { failedFetchCooldownMap.set(cooldownKey, nowPollMs); + liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + } else { + const fallbackLive = resolveBestLiveActivity( + conv.cascadeId, + [], + true, + conv.lastModifiedMs || conv.createdTimeMs || 0 + ); + conv.liveActivity = fallbackLive; + if (fallbackLive) { + liveActivityMemo.set(conv.cascadeId.toLowerCase(), fallbackLive); + } } if ( prev && @@ -818,6 +1020,23 @@ export async function enumerateAndSyncConversations({ cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache); } + // 确保所有处于 RUNNING 状态的会话(含本轮未触发 RPC 拉取的会话)都同步了最新的实时动作摘要 + for (const conv of rawConversations) { + if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') { + if (!conv.liveActivity) { + const fallbackMs = conv.lastModifiedMs || conv.createdTimeMs || 0; + const resolved = resolveBestLiveActivity(conv.cascadeId, [], true, fallbackMs); + conv.liveActivity = resolved; + if (resolved) { + liveActivityMemo.set(conv.cascadeId.toLowerCase(), resolved); + } + } + } else { + conv.liveActivity = null; + liveActivityMemo.delete(conv.cascadeId.toLowerCase()); + } + } + // 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下 const subagentsByRoot = new Map(); const conversations = []; @@ -831,7 +1050,7 @@ export async function enumerateAndSyncConversations({ subagentsByRoot.set(rootId, []); } subagentsByRoot.get(rootId).push(conv); - } else if (!conv.isSubagent || !rootTarget) { + } else { conversations.push(conv); } } @@ -884,7 +1103,9 @@ export async function enumerateAndSyncConversations({ ))) || conversations[0] || null; - const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null; + const safeReqId = + requestedConvId && !/[\\/]|\.\./.test(String(requestedConvId)) ? requestedConvId : null; + const activeCascadeId = activeConvSummary?.cascadeId || safeReqId || null; return { conversations, diff --git a/sidecars/panel/backend/model-pricing.mjs b/sidecars/panel/backend/model-pricing.mjs index 0f0dcdc..dbaf582 100644 --- a/sidecars/panel/backend/model-pricing.mjs +++ b/sidecars/panel/backend/model-pricing.mjs @@ -27,6 +27,7 @@ export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', api const combined = `${rawModelKey} ${modelId}`.toUpperCase(); if ( combined.includes('GEMINI') || + combined.includes('CARBON') || combined.includes('ARGON') || combined.includes('FLASH') || combined.includes('GOOGLE') @@ -35,6 +36,7 @@ export function inferFamilyFromProviderOrKey(rawModelKey = '', modelId = '', api } if ( combined.includes('CLAUDE') || + combined.includes('FABLE') || combined.includes('SONNET') || combined.includes('OPUS') || combined.includes('HAIKU') @@ -57,6 +59,16 @@ export function isArgonModelIdentifier(...parts) { return /argon|MODEL_PLACEHOLDER_M41[789]\b/i.test(parts.filter(Boolean).join(' ')); } +/** + * 判断一组模型标识字段是否指向 Gemini 4 Carbon 系列模型。 + * + * @param {...string} parts 待检测的标识片段 + * @returns {boolean} + */ +export function isCarbonModelIdentifier(...parts) { + return /\bcarbon\b|gemini-4-carbon/i.test(parts.filter(Boolean).join(' ')); +} + /** * 剥离模型展示名称末尾的思考档位后缀(如 `(High)`、`(Medium)`、`(Thinking)`),提取基础模型族名。 * @@ -66,13 +78,13 @@ export function isArgonModelIdentifier(...parts) { export function getBaseModelLabel(label = '') { return ( String(label || '') - .replace(/\s*\((?:High|Medium|Low|Thinking|Extra Low)\)\s*$/i, '') + .replace(/\s*\((?:Max|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '') .trim() || String(label || 'Unknown Model') ); } /** - * 将形如 `gemini-3.1-pro` 或 `gemini-3.5-flash-lite` 的通用模型 Slug 转为人类可读标签。 + * 将形如 `gemini-3.1-pro`、`gemini-3.5-flash-lite` 或 `gemini-4-carbon` 的通用模型 Slug 转为人类可读标签。 * * @param {string} [slug=''] * @returns {string} @@ -82,7 +94,7 @@ export function formatGenericModelSlug(slug = '') { .trim() .replace(/^session-display:/i, ''); if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return ''; - const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon)(?:-(lite))?/i); + const m = s.match(/^gemini-(\d+(?:\.\d+)?)-(pro|flash|argon|carbon)(?:-(lite))?/i); if (m) { const ver = m[1]; const tier = m[2].charAt(0).toUpperCase() + m[2].slice(1).toLowerCase(); diff --git a/sidecars/panel/backend/pricing-catalog.mjs b/sidecars/panel/backend/pricing-catalog.mjs index 1d750bc..8bde4b5 100644 --- a/sidecars/panel/backend/pricing-catalog.mjs +++ b/sidecars/panel/backend/pricing-catalog.mjs @@ -28,7 +28,11 @@ import { * 代码内置兜底模型价格字典(当本地与云端目录均不可用时的离线基准)。 */ export const BUILTIN_MODEL_PRICING = { - // Gemini 4 & 3.x & 2.5 官方目录价格 (USD / 1M tokens) + // Gemini 4 (Carbon & Argon) & 3.x & 2.5 官方目录价格 (USD / 1M tokens) + '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' }, @@ -36,31 +40,68 @@ export const BUILTIN_MODEL_PRICING = { '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-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': { 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.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': { 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.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.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' }, + 'gemini-3.5-flash-extra-low': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-xlow', family: 'Gemini' }, 'gemini-3.5-flash': { input: 1.50, cache: 0.15, output: 9.00, short: 'flash-3.5', family: 'Gemini' }, 'gemini-3.5-flash-lite': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-3.5-lite', family: 'Gemini' }, + 'gemini-3.1-pro-high': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-high', family: 'Gemini' }, + 'gemini-3.1-pro-low': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' }, + 'gemini-3.1-pro-low-thinking': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1-low', family: 'Gemini' }, + 'gemini-3.1-pro-preview': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, + 'gemini-3.1-pro-preview-customtools': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, 'gemini-3.1-pro': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3.1', family: 'Gemini' }, + 'gemini-3.1-flash-lite-preview': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' }, 'gemini-3.1-flash-lite': { input: 0.25, cache: 0.025, output: 1.50, short: 'flash-3.1-lite', family: 'Gemini' }, + 'gemini-for-google-3.1-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1', family: 'Gemini' }, + 'gemini-3.1-flash-image': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3.1-img', family: 'Gemini' }, + 'gemini-3-flash-preview': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' }, 'gemini-3-flash': { input: 0.50, cache: 0.05, output: 3.00, short: 'flash-3', family: 'Gemini' }, + 'gemini-3-pro-image': { input: 2.00, cache: 0.20, output: 12.0, short: 'pro-3-img', family: 'Gemini' }, 'gemini-2.5-pro': { input: 1.25, cache: 0.125, output: 10.0, short: 'pro-2.5', family: 'Gemini' }, 'gemini-2.5-flash': { input: 0.30, cache: 0.03, output: 2.50, short: 'flash-2.5', family: 'Gemini' }, 'gemini-2.5-flash-lite': { input: 0.10, cache: 0.01, output: 0.40, short: 'flash-2.5-lite', family: 'Gemini' }, // Claude 4.5 / 4.6 / 4.7 / 4.8 / 5.x 官方目录价格 + 'claude-fable-5-2-max': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-max', family: 'Claude' }, + 'claude-fable-5-2-high': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-high', family: 'Claude' }, + 'claude-fable-5-2-medium': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' }, + 'claude-fable-5-2-low': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2-low', family: 'Claude' }, + 'claude-fable-5-2': { input: 8.00, cache: 0.20, output: 40.0, short: 'fable-5.2', family: 'Claude' }, 'claude-fable-5-1': { input: 10.0, cache: 0.25, output: 50.0, short: 'fable-5.1', family: 'Claude' }, 'claude-fable-5': { input: 10.0, cache: 1.00, output: 50.0, short: 'fable-5', family: 'Claude' }, + 'claude-opus-5-5-max': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-max', family: 'Claude' }, + 'claude-opus-5-5-high': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-high', family: 'Claude' }, + 'claude-opus-5-5-medium': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' }, + 'claude-opus-5-5-low': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5-low', family: 'Claude' }, 'claude-opus-5-5': { input: 4.00, cache: 0.20, output: 20.0, short: 'opus-5.5', family: 'Claude' }, 'claude-opus-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-5', family: 'Claude' }, 'claude-opus-4-8': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.8', family: 'Claude' }, 'claude-opus-4-7': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.7', family: 'Claude' }, 'claude-opus-4-6-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus', family: 'Claude' }, 'claude-opus-4-6': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.6', family: 'Claude' }, + 'claude-opus-4-5-thinking': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' }, 'claude-opus-4-5': { input: 5.00, cache: 0.50, output: 25.0, short: 'opus-4.5', family: 'Claude' }, + 'claude-sonnet-5-5-max': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-max', family: 'Claude' }, + 'claude-sonnet-5-5-high': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-high', family: 'Claude' }, + 'claude-sonnet-5-5-medium': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' }, + 'claude-sonnet-5-5-low': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5-low', family: 'Claude' }, 'claude-sonnet-5-5': { input: 2.00, cache: 0.10, output: 10.0, short: 'sonnet-5.5', family: 'Claude' }, 'claude-sonnet-5': { input: 2.00, cache: 0.20, output: 10.0, short: 'sonnet-5', family: 'Claude' }, 'claude-sonnet-4-6': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet', family: 'Claude' }, + 'claude-sonnet-4-5-thinking': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' }, 'claude-sonnet-4-5': { input: 3.00, cache: 0.30, output: 15.0, short: 'sonnet-4.5', family: 'Claude' }, 'claude-haiku-5-5': { input: 0.10, cache: 0.01, output: 0.50, short: 'haiku-5.5', family: 'Claude' }, 'claude-haiku-4-5': { input: 1.00, cache: 0.10, output: 5.00, short: 'haiku-4.5', family: 'Claude' }, @@ -68,6 +109,7 @@ export const BUILTIN_MODEL_PRICING = { // OpenAI / GPT 官方目录价格 'gpt-6-astra': { input: 10.0, cache: 1.00, output: 50.0, short: 'gpt-6-astra', family: 'GPT' }, 'gpt-6.1-sol': { input: 2.00, cache: 0.10, output: 10.0, short: 'gpt-6.1-sol', family: 'GPT' }, + 'gpt-6.1-terra': { input: 1.00, cache: 0.05, output: 5.00, short: 'gpt-6.1-terra', family: 'GPT' }, 'gpt-6-sol': { input: 2.00, cache: 0.20, output: 10.0, short: 'gpt-6-sol', family: 'GPT' }, 'gpt-6-luna': { input: 0.10, cache: 0.01, output: 0.50, short: 'gpt-6-luna', family: 'GPT' }, 'gpt-5.6': { input: 4.00, cache: 0.40, output: 20.0, short: 'gpt-5.6', family: 'GPT' }, @@ -98,21 +140,61 @@ export const BUILTIN_MODEL_PRICING = { * 代码内置兜底枚举占位符映射表(`MODEL_PLACEHOLDER_Mxxx` -> `modelId` & `label`)。 */ export const BUILTIN_PLACEHOLDER_MAP = { + // Gemini 4 Argon MODEL_PLACEHOLDER_M417: { modelId: 'gemini-4-argon-high', label: 'Gemini 4 Argon (High)' }, MODEL_PLACEHOLDER_M418: { modelId: 'gemini-4-argon-medium', label: 'Gemini 4 Argon (Medium)' }, MODEL_PLACEHOLDER_M419: { modelId: 'gemini-4-argon-low', label: 'Gemini 4 Argon (Low)' }, + // Gemini 3.8 Flash MODEL_PLACEHOLDER_M318: { modelId: 'gemini-3.8-flash-high', label: 'Gemini 3.8 Flash (High)' }, MODEL_PLACEHOLDER_M319: { modelId: 'gemini-3.8-flash-medium', label: 'Gemini 3.8 Flash (Medium)' }, MODEL_PLACEHOLDER_M320: { modelId: 'gemini-3.8-flash-low', label: 'Gemini 3.8 Flash (Low)' }, MODEL_PLACEHOLDER_M322: { modelId: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash (Tiered)' }, + // Gemini 3.7 Flash + MODEL_PLACEHOLDER_M298: { modelId: 'gemini-3.7-flash-high', label: 'Gemini 3.7 Flash (High)' }, + MODEL_PLACEHOLDER_M299: { modelId: 'gemini-3.7-flash-medium', label: 'Gemini 3.7 Flash (Medium)' }, + MODEL_PLACEHOLDER_M300: { modelId: 'gemini-3.7-flash-low', label: 'Gemini 3.7 Flash (Low)' }, + MODEL_PLACEHOLDER_M301: { modelId: 'gemini-3.7-flash-tiered', label: 'Gemini 3.7 Flash (Tiered)' }, + // Gemini 3.6 Flash + MODEL_PLACEHOLDER_M71: { modelId: 'gemini-3.6-flash-high', label: 'Gemini 3.6 Flash (High)' }, + MODEL_PLACEHOLDER_M72: { modelId: 'gemini-3.6-flash-medium', label: 'Gemini 3.6 Flash (Medium)' }, + MODEL_PLACEHOLDER_M73: { modelId: 'gemini-3.6-flash-low', label: 'Gemini 3.6 Flash (Low)' }, + MODEL_PLACEHOLDER_M196: { modelId: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' }, + // Gemini 3.5 Flash & Lite + MODEL_PLACEHOLDER_M149: { modelId: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash (High)' }, + MODEL_PLACEHOLDER_M20: { modelId: 'gemini-3.5-flash-low', label: 'Gemini 3.5 Flash' }, + MODEL_PLACEHOLDER_M187: { modelId: 'gemini-3.5-flash-extra-low', label: 'Gemini 3.5 Flash (Extra Low)' }, MODEL_PLACEHOLDER_M198: { modelId: 'gemini-3.5-flash-lite', label: 'Gemini 3.5 Flash Lite' }, + // Gemini 3.1 & 3.0 + MODEL_PLACEHOLDER_M37: { modelId: 'gemini-3.1-pro-high', label: 'Gemini 3.1 Pro (High)' }, + MODEL_PLACEHOLDER_M36: { modelId: 'gemini-3.1-pro-low', label: 'Gemini 3.1 Pro (Low)' }, MODEL_PLACEHOLDER_M50: { modelId: 'gemini-3.1-flash-lite', label: 'Gemini 3.1 Flash Lite' }, + MODEL_PLACEHOLDER_M59: { modelId: 'gemini-for-google-3.1-flash', label: 'Gemini for Google 3.1 Flash' }, + MODEL_PLACEHOLDER_M21: { modelId: 'gemini-3.1-flash-image', label: 'Gemini 3.1 Flash Image' }, MODEL_PLACEHOLDER_M18: { modelId: 'gemini-3-flash', label: 'Gemini 3 Flash' }, - MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' }, - MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' }, + MODEL_PLACEHOLDER_M9: { modelId: 'gemini-3-pro-image', label: 'Gemini 3 Pro Image' }, + // Gemini 2.5 MODEL_GOOGLE_GEMINI_2_5_PRO: { modelId: 'gemini-2.5-pro', label: 'Gemini 2.5 Pro' }, + MODEL_GOOGLE_GEMINI_2_5_FLASH: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash' }, + MODEL_GOOGLE_GEMINI_2_5_FLASH_THINKING: { modelId: 'gemini-2.5-flash', label: 'Gemini 2.5 Flash (Thinking)' }, + MODEL_GOOGLE_GEMINI_2_5_FLASH_LITE: { modelId: 'gemini-2.5-flash-lite', label: 'Gemini 2.5 Flash Lite' }, + // Claude 5.5 / 4.8 / 4.6 / 4.5 + MODEL_PLACEHOLDER_M406: { modelId: 'claude-opus-5-5-max', label: 'Claude Opus 5.5 (Max)' }, + MODEL_PLACEHOLDER_M402: { modelId: 'claude-opus-5-5-high', label: 'Claude Opus 5.5 (High)' }, + MODEL_PLACEHOLDER_M401: { modelId: 'claude-opus-5-5-medium', label: 'Claude Opus 5.5 (Medium)' }, + MODEL_PLACEHOLDER_M400: { modelId: 'claude-opus-5-5-low', label: 'Claude Opus 5.5 (Low)' }, + MODEL_PLACEHOLDER_M368: { modelId: 'claude-opus-5-5', label: 'Claude Opus 5.5' }, + MODEL_PLACEHOLDER_M407: { modelId: 'claude-sonnet-5-5-max', label: 'Claude Sonnet 5.5 (Max)' }, + MODEL_PLACEHOLDER_M405: { modelId: 'claude-sonnet-5-5-high', label: 'Claude Sonnet 5.5 (High)' }, + MODEL_PLACEHOLDER_M404: { modelId: 'claude-sonnet-5-5-medium', label: 'Claude Sonnet 5.5 (Medium)' }, + MODEL_PLACEHOLDER_M403: { modelId: 'claude-sonnet-5-5-low', label: 'Claude Sonnet 5.5 (Low)' }, + MODEL_PLACEHOLDER_M254: { modelId: 'claude-opus-4-8', label: 'Claude Opus 4.8' }, MODEL_PLACEHOLDER_M26: { modelId: 'claude-opus-4-6-thinking', label: 'Claude Opus 4.6 (Thinking)' }, MODEL_PLACEHOLDER_M35: { modelId: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6 (Thinking)' }, + MODEL_PLACEHOLDER_M12: { modelId: 'claude-opus-4-5-thinking', label: 'Claude Opus 4.5 (Thinking)' }, + MODEL_PLACEHOLDER_M11: { modelId: 'claude-opus-4-5', label: 'Claude Opus 4.5' }, + MODEL_CLAUDE_4_5_SONNET_THINKING: { modelId: 'claude-sonnet-4-5-thinking', label: 'Claude Sonnet 4.5 (Thinking)' }, + MODEL_CLAUDE_4_5_SONNET: { modelId: 'claude-sonnet-4-5', label: 'Claude Sonnet 4.5' }, + // OpenAI MODEL_OPENAI_GPT_OSS_120B_MEDIUM: { modelId: 'gpt-oss-120b-medium', label: 'GPT-OSS 120B (Medium)' }, }; @@ -132,8 +214,10 @@ export function isValidSemver(v) { return typeof v === 'string' && /^v?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(v.trim()); } +const OFFICIAL_REPO_PATH_PREFIX = '/yuhuan2498281558/antigravity-usage-monitor'; + /** - * 校验更新/下载链接是否属于可信的 GitHub 官方 HTTPS 域名白名单。 + * 校验更新/下载链接是否属于可信的 GitHub 官方仓库与 HTTPS 域名白名单。 * * @param {*} rawUrl * @param {string} fallbackUrl @@ -145,19 +229,25 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) { const parsed = new URL(rawUrl.trim()); if (parsed.protocol !== 'https:') return fallbackUrl; const host = parsed.hostname.toLowerCase(); - const isTrustedHost = + const pathname = parsed.pathname.toLowerCase(); + if ( host === 'github.com' || host === 'raw.githubusercontent.com' || - host === 'codeload.github.com' || - host === 'objects.githubusercontent.com'; - return isTrustedHost ? parsed.toString() : fallbackUrl; + host === 'codeload.github.com' + ) { + const hasRepoPrefix = + pathname === OFFICIAL_REPO_PATH_PREFIX || + pathname.startsWith(`${OFFICIAL_REPO_PATH_PREFIX}/`); + return hasRepoPrefix ? parsed.toString() : fallbackUrl; + } + return fallbackUrl; } catch { return fallbackUrl; } } /** - * 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`)。 + * 比较两个语义化版本号(如 `'1.5.0'` vs `'1.4.0'`,支持 `-beta.1` 预发布后缀比较)。 * * @param {string} a * @param {string} b @@ -165,26 +255,30 @@ export function sanitizeTrustedGithubUrl(rawUrl, fallbackUrl) { */ export function compareSemver(a, b) { if (!isValidSemver(a) || !isValidSemver(b)) return 0; - const parse = (v) => - String(v || '') - .trim() - .replace(/^v/i, '') - .split('-')[0] - .split('.') - .map((n) => { - const parsed = parseInt(n, 10); - return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0; - }); + const parse = (v) => { + const cleaned = String(v || '').trim().replace(/^v/i, ''); + const dashIdx = cleaned.indexOf('-'); + const coreStr = dashIdx >= 0 ? cleaned.slice(0, dashIdx) : cleaned; + const preStr = dashIdx >= 0 ? cleaned.slice(dashIdx + 1) : ''; + const core = coreStr.split('.').map((n) => { + const parsed = parseInt(n, 10); + return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0; + }); + return { core, pre: preStr }; + }; const pa = parse(a); const pb = parse(b); - const len = Math.max(pa.length, pb.length, 3); + const len = Math.max(pa.core.length, pb.core.length, 3); for (let i = 0; i < len; i++) { - const va = pa[i] || 0; - const vb = pb[i] || 0; + const va = pa.core[i] || 0; + const vb = pb.core[i] || 0; if (va > vb) return 1; if (va < vb) return -1; } - return 0; + if (!pa.pre && !pb.pre) return 0; + if (!pa.pre && pb.pre) return 1; + if (pa.pre && !pb.pre) return -1; + return pa.pre.localeCompare(pb.pre, undefined, { numeric: true }); } /** @@ -195,7 +289,7 @@ export function compareSemver(a, b) { export function readInstalledPluginVersion() { const manifest = loadJson(PLUGIN_MANIFEST_FILE, null); const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : ''; - return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.1'; + return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.2'; } /** diff --git a/sidecars/panel/backend/quota-pools.mjs b/sidecars/panel/backend/quota-pools.mjs index d4a317b..38160e8 100644 --- a/sidecars/panel/backend/quota-pools.mjs +++ b/sidecars/panel/backend/quota-pools.mjs @@ -10,7 +10,11 @@ */ import { parseIsoMs } from '../speed-metrics.mjs'; -import { isArgonModelIdentifier, resolveModelInfo } from './model-pricing.mjs'; +import { + isArgonModelIdentifier, + isCarbonModelIdentifier, + resolveModelInfo, +} from './model-pricing.mjs'; /** * 将原始配额对象(来自 `RetrieveUserQuotaSummary` 桶或 `clientModelConfigs.quotaInfo`)归一化为百分比结构。 @@ -98,6 +102,20 @@ export function classifyQuotaPoolIdentity({ const bName = String(bucketName || ''); const gName = String(groupName || ''); const gDesc = String(groupDesc || ''); + if ( + /carbon/i.test(bId) || + /carbon/i.test(bName) || + /carbon/i.test(gName) || + (/\bcarbon\b/i.test(gDesc) && + !/\bflash\b/i.test(gDesc) && + !/^gemini models$/i.test(gName.trim())) + ) { + return { + poolKey: 'Carbon', + poolLabel: 'Gemini 4 Carbon', + poolName: 'Gemini 4 Carbon 模型池', + }; + } if ( /argon/i.test(bId) || /argon/i.test(bName) || @@ -119,7 +137,7 @@ export function classifyQuotaPoolIdentity({ poolName: 'Gemini 模型池', }; } - if (/3p|claude|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) { + if (/3p|claude|fable|gpt|sonnet|opus|haiku|third[-_\s]?party/i.test(`${bId} ${gName} ${gDesc}`)) { return { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', @@ -166,7 +184,6 @@ export function quotaFractionsMatch(a, b) { export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { const dynamicModelMap = new Map(); const nowForQuotaMs = Date.now(); - const officialBuckets = new Map(); const poolBuilders = new Map(); function ensurePoolBuilder({ poolKey, poolLabel, poolName }) { @@ -211,21 +228,19 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { groupName: grp?.displayName || ident.poolLabel, window: win, }; - if (b?.bucketId) { - officialBuckets.set(b.bucketId, entry); - } const builder = ensurePoolBuilder(ident); if (win === '5h' && !builder.bucket5h) { builder.bucket5h = entry; } else if (win === 'weekly' && !builder.bucketWeekly) { builder.bucketWeekly = entry; - } else if (!builder.bucketWeekly) { + } else if (win !== '5h' && !builder.bucketWeekly) { builder.bucketWeekly = entry; } } } - // 注册动态模型字典,并采样 Argon 与标准 Gemini 的单模型 quotaInfo + // 注册动态模型字典,并采样 Carbon / Argon 与标准 Gemini 的单模型 quotaInfo + let sampleCarbonCfgQuota = null; let sampleArgonCfgQuota = null; let sampleStdGeminiCfgQuota = null; @@ -241,15 +256,17 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { const info = resolveModelInfo(rawKey, dynamicModelMap); const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo); if (!cfgQuota || info.family !== 'Gemini') continue; - if (isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) { + if (isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) { + if (!sampleCarbonCfgQuota) sampleCarbonCfgQuota = cfgQuota; + } else if (isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId)) { if (!sampleArgonCfgQuota) sampleArgonCfgQuota = cfgQuota; } else if (!sampleStdGeminiCfgQuota) { sampleStdGeminiCfgQuota = cfgQuota; } } - // Pro 账号回退检测:若 RetrieveUserQuotaSummary 未单独列出 Argon 分组, - // 但 GetUserStatus 中 Argon 模型的 quotaInfo 与标准 Gemini 明显分离,则合成独立 Argon 周限池 + // Pro 账号回退检测:若 RetrieveUserQuotaSummary 未单独列出 Argon / Carbon 分组, + // 但 GetUserStatus 中 Argon / Carbon 模型的 quotaInfo 与标准 Gemini 明显分离,则合成独立周限池 if (!poolBuilders.has('Argon') && sampleArgonCfgQuota) { const geminiBuilder = poolBuilders.get('Gemini'); const hasGeminiBaseline = Boolean( @@ -275,20 +292,56 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { } } + if (!poolBuilders.has('Carbon') && sampleCarbonCfgQuota) { + const geminiBuilder = poolBuilders.get('Gemini'); + const argonBuilder = poolBuilders.get('Argon'); + const hasBaseline = Boolean( + sampleStdGeminiCfgQuota || + sampleArgonCfgQuota || + geminiBuilder?.bucket5h || + geminiBuilder?.bucketWeekly || + argonBuilder?.bucketWeekly + ); + const matchesSharedPool = + quotaFractionsMatch(sampleCarbonCfgQuota, sampleStdGeminiCfgQuota) || + quotaFractionsMatch(sampleCarbonCfgQuota, sampleArgonCfgQuota) || + quotaFractionsMatch(sampleCarbonCfgQuota, geminiBuilder?.bucket5h) || + quotaFractionsMatch(sampleCarbonCfgQuota, geminiBuilder?.bucketWeekly) || + quotaFractionsMatch(sampleCarbonCfgQuota, argonBuilder?.bucketWeekly); + + if (hasBaseline && !matchesSharedPool) { + const carbonBuilder = ensurePoolBuilder({ + poolKey: 'Carbon', + poolLabel: 'Gemini 4 Carbon', + poolName: 'Gemini 4 Carbon 模型池', + }); + carbonBuilder.bucketWeekly = { + ...sampleCarbonCfgQuota, + bucketId: 'carbon-weekly-inferred', + groupName: 'Gemini 4 Carbon', + window: 'weekly', + }; + } + } + const hasDedicatedArgonPool = poolBuilders.has('Argon'); + const hasDedicatedCarbonPool = poolBuilders.has('Carbon'); const modelQuotas = []; for (const cfg of clientConfigs) { const rawKey = cfg?.modelOrAlias?.model; const info = resolveModelInfo(rawKey, dynamicModelMap); + const isCarbon = isCarbonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId); const isArgon = isArgonModelIdentifier(rawKey, cfg?.modelId, cfg?.label, info.modelId); const isGemini = info.family === 'Gemini'; const targetIdent = - isArgon && hasDedicatedArgonPool - ? { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', poolName: 'Gemini 4 Argon 模型池' } - : isGemini - ? { poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' } - : { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池' }; + isCarbon && hasDedicatedCarbonPool + ? { poolKey: 'Carbon', poolLabel: 'Gemini 4 Carbon', poolName: 'Gemini 4 Carbon 模型池' } + : isArgon && hasDedicatedArgonPool + ? { poolKey: 'Argon', poolLabel: 'Gemini 4 Argon', poolName: 'Gemini 4 Argon 模型池' } + : isGemini + ? { poolKey: 'Gemini', poolLabel: 'Gemini', poolName: 'Gemini 模型池' } + : { poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', poolName: 'Claude & GPT 模型池' }; const builder = ensurePoolBuilder(targetIdent); if (cfg?.label && !builder.models.includes(cfg.label)) { @@ -297,7 +350,7 @@ export function buildOfficialQuotaPools(officialQuota, clientConfigs = []) { const cfgQuota = normalizeQuotaFraction(cfg?.quotaInfo); if (!builder.bucket5h && !builder.bucketWeekly && !builder.fallback5h && cfgQuota) { - if (targetIdent.poolKey === 'Argon') { + if (targetIdent.poolKey === 'Argon' || targetIdent.poolKey === 'Carbon') { builder.bucketWeekly = cfgQuota; } else { builder.fallback5h = cfgQuota; diff --git a/sidecars/panel/backend/telemetry-builder.mjs b/sidecars/panel/backend/telemetry-builder.mjs index ab3c8bc..ad1eb83 100644 --- a/sidecars/panel/backend/telemetry-builder.mjs +++ b/sidecars/panel/backend/telemetry-builder.mjs @@ -12,6 +12,7 @@ import { statSync } from 'node:fs'; import { join } from 'node:path'; import { + extractLiveActivity, parseIsoMs, speedMetric, summarizeSpeed, @@ -30,6 +31,7 @@ import { callLsRpc, diagnostics, getOfficialQuotaSummary } from './ls-rpc.mjs'; import { computeStepCost, isArgonModelIdentifier, + isCarbonModelIdentifier, resolveModelInfo, } from './model-pricing.mjs'; import { getCloudStatus } from './pricing-catalog.mjs'; @@ -268,6 +270,7 @@ function buildAgentUnitTelemetry({ agentLabel, status, rawSteps, + liveActivity = null, fallbackLastModMs, dynamicModelMap, knownUpstreamByModelKey, @@ -297,6 +300,11 @@ function buildAgentUnitTelemetry({ const modelBreakdown = buildScopedModelBreakdown(taggedSteps, dynamicModelMap); const lastModifiedMs = enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0; + const isRunning = status === 'CASCADE_RUN_STATUS_RUNNING'; + const resolvedLiveActivity = isRunning + ? liveActivity || + extractLiveActivity([], true, lastModifiedMs || fallbackLastModMs || 0) + : null; return { enrichedRes, @@ -311,8 +319,9 @@ function buildAgentUnitTelemetry({ badgeText, role, typeName, - isRunning: status === 'CASCADE_RUN_STATUS_RUNNING', + isRunning, status: status || 'IDLE', + liveActivity: resolvedLiveActivity, stepCount: taggedSteps.length, latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null, latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null, @@ -359,15 +368,18 @@ export async function buildTelemetryPayloadInternal( const currentAccountName = userStatus?.email || userStatus?.name || ''; let officialQuotaInfo = initialOfficialQuotaInfo; - // 若检测到登录账号在 10 秒缓存期内发生切换,立即强制刷新配额摘要 - if ( + // 若检测到登录账号在 10 秒缓存期内发生切换,先清空旧账号配额缓存再立即强制刷新,防止刷新失败时串号 + const accountChanged = Boolean( currentAccountName && - quotaSummaryCache.accountName && - quotaSummaryCache.accountName !== currentAccountName - ) { + quotaSummaryCache.accountName && + quotaSummaryCache.accountName !== currentAccountName + ); + if (accountChanged) { + quotaSummaryCache.data = null; + quotaSummaryCache.ts = 0; + quotaSummaryCache.accountName = currentAccountName; officialQuotaInfo = await getOfficialQuotaSummary(true); - } - if (currentAccountName && officialQuotaInfo?.data) { + } else if (currentAccountName && officialQuotaInfo?.data && !officialQuotaInfo.refreshFailed) { quotaSummaryCache.accountName = currentAccountName; } @@ -404,6 +416,7 @@ export async function buildTelemetryPayloadInternal( agentLabel: '主代理', status: activeConvSummary?.status || 'IDLE', rawSteps: activeSteps, + liveActivity: activeConvSummary?.liveActivity || null, fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0, dynamicModelMap, knownUpstreamByModelKey, @@ -464,6 +477,7 @@ export async function buildTelemetryPayloadInternal( agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel, status: subSum.status || 'IDLE', rawSteps: subRawSteps, + liveActivity: subSum.liveActivity || null, fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0, dynamicModelMap, knownUpstreamByModelKey, @@ -528,6 +542,25 @@ export async function buildTelemetryPayloadInternal( ? Math.round((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100) : 0; + const runningSubs = subAgentTelemetries.filter((a) => a.isRunning); + const primaryRunningSub = runningSubs + .slice() + .sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0]; + const activeActivityAgent = + primaryRunningSub || (mainAgentTelemetry.isRunning ? mainAgentTelemetry : null); + const aggregatedLiveActivity = activeActivityAgent?.liveActivity + ? { + ...activeActivityAgent.liveActivity, + agentId: activeActivityAgent.agentId, + agentBadge: activeActivityAgent.badgeText, + agentShortLabel: activeActivityAgent.shortLabel, + agentRole: activeActivityAgent.role, + agentIndex: activeActivityAgent.index, + isMain: Boolean(activeActivityAgent.isMain), + parallelCount: runningSubs.length > 1 ? runningSubs.length : 1, + } + : null; + aggregatedTelemetry = { agentId: 'all', cascadeId: activeCascadeId, @@ -543,6 +576,7 @@ export async function buildTelemetryPayloadInternal( activeAgentRole: latestActiveAgent.role, isRunning: allAgents.some((a) => a.isRunning), status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE', + liveActivity: aggregatedLiveActivity, stepCount: allCombinedEnrichedSteps.length, latestTokPerSec: latestMetricAgent.latestTokPerSec, latestTtftSec: latestMetricAgent.latestTtftSec, @@ -568,6 +602,14 @@ export async function buildTelemetryPayloadInternal( allCombinedEnrichedSteps.length > 0 ? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1] : latestEnriched; + const latestIsCarbon = latestFamilyStep + ? isCarbonModelIdentifier( + latestFamilyStep.modelKey, + latestFamilyStep.responseModel, + latestFamilyStep.modelUpstream, + latestFamilyStep.modelLabel + ) + : false; const latestIsArgon = latestFamilyStep ? isArgonModelIdentifier( latestFamilyStep.modelKey, @@ -578,13 +620,15 @@ export async function buildTelemetryPayloadInternal( : false; const rawActiveFamily = latestFamilyStep?.family || 'Other'; const activePoolKey = - latestIsArgon && quotaPoolsMap.has('Argon') - ? 'Argon' - : rawActiveFamily === 'Gemini' - ? 'Gemini' - : ['Claude', 'GPT'].includes(rawActiveFamily) - ? 'Claude & GPT' - : 'Unknown'; + latestIsCarbon && quotaPoolsMap.has('Carbon') + ? 'Carbon' + : latestIsArgon && quotaPoolsMap.has('Argon') + ? 'Argon' + : rawActiveFamily === 'Gemini' + ? 'Gemini' + : ['Claude', 'GPT'].includes(rawActiveFamily) + ? 'Claude & GPT' + : 'Unknown'; const matchedActivePool = quotaPoolsMap.get(activePoolKey) || null; const activeLive5h = matchedActivePool?.has5h ? { @@ -638,13 +682,15 @@ export async function buildTelemetryPayloadInternal( poolKey: activePoolKey, poolLabel: activePoolKey === 'Unknown' ? '未知' : activePoolKey, poolName: - activePoolKey === 'Argon' - ? 'Gemini 4 Argon 模型池' - : activePoolKey === 'Gemini' - ? 'Gemini 模型池' - : activePoolKey === 'Claude & GPT' - ? 'Claude & GPT 模型池' - : '模型池未知', + activePoolKey === 'Carbon' + ? 'Gemini 4 Carbon 模型池' + : activePoolKey === 'Argon' + ? 'Gemini 4 Argon 模型池' + : activePoolKey === 'Gemini' + ? 'Gemini 模型池' + : activePoolKey === 'Claude & GPT' + ? 'Claude & GPT 模型池' + : '模型池未知', family: activePoolKey, isAvailable: Boolean(activeLive5h || activeLiveWeekly), has5h: Boolean(activeLive5h), @@ -706,6 +752,130 @@ export async function buildTelemetryPayloadInternal( // 忽略 stat 异常 } + // 7. 构建所有正在运行的主进程(根会话)及其子代理缩略状态列表 + const runningConversations = []; + for (const rootConv of conversations) { + const isMainRunning = rootConv.status === 'CASCADE_RUN_STATUS_RUNNING'; + const rawSubs = Array.isArray(rootConv.subagents) ? rootConv.subagents : []; + const hasRunningSub = rawSubs.some((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING'); + if (!isMainRunning && !hasRunningSub) { + continue; + } + + const rootEntry = trajectoryCache[rootConv.cascadeId] || null; + const rootFallbackMs = + rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0; + + const subItems = rawSubs.map((subSum, idx) => { + const subCid = subSum.cascadeId; + const subEntry = trajectoryCache[subCid] || null; + const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null; + const rawRole = + subSpec?.role || + subSum.agentScriptName || + subEntry?.agentScriptName || + subSpec?.typeName || + ''; + const subIndex = idx + 1; + const badgeText = `子${subIndex}`; + const shortLabel = `子代理 #${subIndex}`; + const 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; + const liveActivity = isSubRunning + ? subSum.liveActivity || extractLiveActivity([], true, subModMs) + : { + phase: 'done', + label: '已完成', + detail: '', + stepProgress: '', + startedAtMs: subModMs, + signature: `done:${stepCount}`, + }; + return { + cascadeId: subCid, + index: subIndex, + badgeText, + shortLabel, + role, + typeName: subSpec?.typeName || '', + isRunning: isSubRunning, + status: subSum.status || 'IDLE', + stepCount, + lastModifiedMs: subModMs, + liveActivity, + }; + }); + + const mainLiveAct = isMainRunning + ? rootConv.liveActivity || extractLiveActivity([], true, rootFallbackMs) + : null; + + // 若主代理正在调用 invoke_subagent 但新子代理轨迹尚未出现在 rawSubs 中,生成临时子代理占位项 + const runningSubCount = subItems.filter((s) => s.isRunning).length; + if ( + isMainRunning && + (mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') && + runningSubCount === 0 + ) { + const pendingIndex = subItems.length + 1; + const pendingRole = mainLiveAct.detail || '子代理'; + subItems.push({ + cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`, + index: pendingIndex, + badgeText: `子${pendingIndex}`, + shortLabel: `子代理 #${pendingIndex}`, + role: pendingRole, + typeName: '', + isRunning: true, + status: 'CASCADE_RUN_STATUS_RUNNING', + stepCount: 0, + lastModifiedMs: rootFallbackMs, + liveActivity: { + phase: 'thinking', + label: '启动中', + detail: '', + stepProgress: '', + startedAtMs: mainLiveAct.startedAtMs || 0, + signature: `spawning-sub:${pendingIndex}:${pendingRole}`, + }, + }); + } + + const runningSubList = subItems.filter((s) => s.isRunning); + const resolvedMainActivity = + mainLiveAct || + (runningSubList.length > 0 + ? { + phase: 'waiting', + label: '等待子代理', + detail: runningSubList.map((s) => s.role).join(', '), + stepProgress: '', + startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs, + signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`, + } + : extractLiveActivity([], true, rootFallbackMs)); + + runningConversations.push({ + cascadeId: rootConv.cascadeId, + title: rootConv.title || rootConv.cascadeId.slice(0, 8), + isCurrentSelected: + Boolean(activeCascadeId) && + rootConv.cascadeId.toLowerCase() === String(activeCascadeId).toLowerCase(), + isMainRunning, + isRunning: true, + status: isMainRunning ? rootConv.status : 'CASCADE_RUN_STATUS_RUNNING', + stepCount: Number(rootConv.stepCount || 0), + totalStepCount: Number(rootConv.totalStepCount || rootConv.stepCount || 0), + lastModifiedMs: rootConv.groupLastModifiedMs || rootConv.lastModifiedMs || 0, + mainActivity: resolvedMainActivity, + subagentCount: subItems.length, + runningSubagentCount: runningSubList.length, + subagents: subItems, + }); + } + return { timestamp: new Date().toISOString(), uiBundleVersion, @@ -719,6 +889,7 @@ export async function buildTelemetryPayloadInternal( aiCredits: realAiCredits > 0 ? realAiCredits : null, totalConversations: conversations.length, }, + runningConversations, conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => ({ cascadeId: c.cascadeId, title: c.title, @@ -734,6 +905,7 @@ export async function buildTelemetryPayloadInternal( title: activeConvSummary?.title || '当前会话', isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING', status: activeConvSummary?.status || 'IDLE', + liveActivity: mainAgentTelemetry.liveActivity || null, stepCount: enrichedActiveSteps.length, hasSubagents: subAgentTelemetries.length > 0, subagentCount: subAgentTelemetries.length, @@ -785,7 +957,7 @@ export async function buildTelemetryPayloadInternal( }, activePool: activePoolQuota, pools: Array.from(quotaPoolsMap.values()).sort((a, b) => { - const order = { Gemini: 0, Argon: 1, 'Claude & GPT': 2 }; + const order = { Gemini: 0, Argon: 1, Carbon: 2, 'Claude & GPT': 3 }; return (order[a.family] ?? 99) - (order[b.family] ?? 99); }), models: modelQuotas.sort((a, b) => String(a.label).localeCompare(String(b.label))), diff --git a/sidecars/panel/backend/usage-aggregator.mjs b/sidecars/panel/backend/usage-aggregator.mjs index 42625b3..e91bdc0 100644 --- a/sidecars/panel/backend/usage-aggregator.mjs +++ b/sidecars/panel/backend/usage-aggregator.mjs @@ -413,6 +413,10 @@ export function aggregateMultiWindowUsage({ ) { continue; } + const extMatch = externalConvos.get(cascadeId) || externalConvos.get(cidLower); + if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) { + continue; + } const groupCascadeId = String( entry?.rootConversationId || entry?.parentConversationId || cascadeId ).toLowerCase(); @@ -427,18 +431,14 @@ export function aggregateMultiWindowUsage({ for (const ext of externalConvos.values()) { const extCidLower = String(ext.cascadeId || '').toLowerCase(); const liveEntry = trajectoryCache[ext.cascadeId] || trajectoryCache[extCidLower]; - if ( - ext.appSource === 'standalone' && - liveEntry && - (liveEntry.steps?.length || 0) >= ext.steps.length - ) { + if (liveEntry && (liveEntry.steps?.length || 0) >= (ext.steps?.length || 0)) { continue; } allEntriesToAggregate.push({ cascadeId: `${ext.appSource}:${extCidLower}`, appSource: ext.appSource || 'ide', steps: ext.steps || [], - isCurrentConv: familySet.has(extCidLower) && !liveEntry, + isCurrentConv: familySet.has(extCidLower), }); } @@ -501,6 +501,10 @@ export function aggregateMultiWindowUsage({ selectedWindowSteps.push({ tMs, tokens: stepTotalTokens, + inputTokens: st.inputTokens || 0, + cacheReadTokens: st.cacheReadTokens || 0, + outputTokens: + (st.responseTokens || 0) + (st.thinkingTokens || 0) || st.outputTokens || 0, costUsd: stepCost ?? 0, unpricedCalls: unpriced, }); @@ -533,46 +537,190 @@ export function aggregateMultiWindowUsage({ } } - // 构建当前选定时间窗口的 12 段等宽趋势序列 (trendSeries) - const trendSlotsCount = 12; - const trendEndMs = Number.isFinite(selectedWindow.endMs) ? selectedWindow.endMs : nowMs; + // 构建当前选定时间窗口的自适应自然整点/整日趋势序列 (trendSeries) + const MAX_SAFE_MS = 8_640_000_000_000_000; + const safeMs = (val, fallback) => + Number.isFinite(val) && val > 0 && val <= MAX_SAFE_MS ? val : fallback; + let latestSelectedStepMs = 0; + for (const item of selectedWindowSteps) { + if (item.tMs > latestSelectedStepMs && item.tMs <= MAX_SAFE_MS) { + latestSelectedStepMs = item.tMs; + } + } + const baseEndMs = safeMs(selectedWindow.endMs, Math.max(nowMs, latestSelectedStepMs || nowMs)); + const trendEndMs = Math.max(baseEndMs, latestSelectedStepMs || 0); const rawTrendStartMs = selectedWindow.key === 'all' - ? Number.isFinite(earliestSelectedStepMs) - ? earliestSelectedStepMs - : nowMs - 24 * 3600 * 1000 - : selectedWindow.startMs; - const trendStartMs = Math.min(rawTrendStartMs, trendEndMs - 60 * 1000); - const trendSpanMs = Math.max(60 * 1000, trendEndMs - trendStartMs); - const slotWidthMs = trendSpanMs / trendSlotsCount; - const isShortSpan = trendSpanMs <= 36 * 3600 * 1000; + ? safeMs(earliestSelectedStepMs, trendEndMs - 24 * 3600 * 1000) + : safeMs(selectedWindow.startMs, trendEndMs - 24 * 3600 * 1000); + const effectiveStartMs = + selectedWindow.key === 'all' + ? Math.min( + rawTrendStartMs, + earliestSelectedStepMs < Infinity + ? safeMs(earliestSelectedStepMs, rawTrendStartMs) + : rawTrendStartMs, + trendEndMs - 3600 * 1000 + ) + : Math.min(rawTrendStartMs, trendEndMs); + const trendStartMs = effectiveStartMs; + const rawSpanMs = Math.max(3600 * 1000, trendEndMs - effectiveStartMs); const pad2 = (n) => String(n).padStart(2, '0'); - const formatTrendLabel = (ms) => { - const d = new Date(ms); - if (isShortSpan) { - return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`; + const WEEKDAY_NAMES = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; + + // 72 小时(3 天)以内按自然整点小时分桶;超过 72 小时按本地自然日分桶 + const useHourly = + selectedWindow.key === 'today' || + selectedWindow.key === '24h' || + selectedWindow.key === '5h' || + rawSpanMs <= 72 * 3600 * 1000; + + const trendSeries = []; + if (useHourly) { + const startHourD = new Date(effectiveStartMs); + startHourD.setMinutes(0, 0, 0); + const endHourD = new Date(trendEndMs); + endHourD.setMinutes(0, 0, 0); + + let firstHourMs = startHourD.getTime(); + let lastHourMs = endHourD.getTime(); + if (selectedWindow.key === 'today') { + const minTodayEndMs = firstHourMs + 5 * 3600 * 1000; + if (lastHourMs < minTodayEndMs) { + lastHourMs = minTodayEndMs; + } + } else if (lastHourMs - firstHourMs < 5 * 3600 * 1000) { + firstHourMs = lastHourMs - 5 * 3600 * 1000; } - return `${d.getMonth() + 1}/${d.getDate()}`; - }; - const trendSeries = Array.from({ length: trendSlotsCount }, (_, idx) => { - const sMs = trendStartMs + idx * slotWidthMs; - return { - index: idx, - label: formatTrendLabel(sMs), - tokens: 0, - costUsd: 0, - calls: 0, - }; - }); + const totalHours = Math.max(2, Math.round((lastHourMs - firstHourMs) / (3600 * 1000)) + 1); + const stepHours = totalHours > 72 ? Math.ceil(totalHours / 48) : 1; + const slotMs = stepHours * 3600 * 1000; + const slotCount = Math.max(2, Math.ceil((lastHourMs - firstHourMs + 3600 * 1000) / slotMs)); - for (const item of selectedWindowSteps) { - const rawIdx = Math.floor((item.tMs - trendStartMs) / slotWidthMs); - const idx = Math.max(0, Math.min(trendSlotsCount - 1, rawIdx)); - trendSeries[idx].tokens += item.tokens; - trendSeries[idx].costUsd = +(trendSeries[idx].costUsd + item.costUsd).toFixed(4); - trendSeries[idx].unpricedCalls = (trendSeries[idx].unpricedCalls || 0) + item.unpricedCalls; - trendSeries[idx].calls += 1; + const firstD = new Date(firstHourMs); + const lastD = new Date(firstHourMs + (slotCount - 1) * slotMs); + const isSameDay = + firstD.getFullYear() === lastD.getFullYear() && + firstD.getMonth() === lastD.getMonth() && + firstD.getDate() === lastD.getDate(); + + for (let idx = 0; idx < slotCount; idx++) { + const sMs = firstHourMs + idx * slotMs; + const eMs = sMs + slotMs; + const sd = new Date(sMs); + const ed = new Date(eMs); + if (Number.isNaN(sd.getTime())) continue; + const hh = `${pad2(sd.getHours())}:00`; + const endHh = `${pad2(ed.getHours())}:00`; + const dateStr = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; + const axisLabel = isSameDay ? hh : `${dateStr} ${hh}`; + const fullLabel = `${sd.getMonth() + 1}月${sd.getDate()}日 ${hh} - ${endHh}`; + trendSeries.push({ + index: idx, + startMs: sMs, + endMs: eMs, + granularity: 'hour', + label: axisLabel, + fullLabel, + tokens: 0, + inputTokens: 0, + cacheReadTokens: 0, + outputTokens: 0, + costUsd: 0, + unpricedCalls: 0, + calls: 0, + }); + } + } else { + const firstDayMs = getStartOfLocalDayMs(effectiveStartMs); + const lastDayMs = getStartOfLocalDayMs(trendEndMs); + const dayStarts = []; + const cursor = new Date(firstDayMs); + cursor.setHours(0, 0, 0, 0); + let safety = 0; + while (cursor.getTime() <= lastDayMs && safety < 3660) { + dayStarts.push(cursor.getTime()); + cursor.setDate(cursor.getDate() + 1); + cursor.setHours(0, 0, 0, 0); + safety++; + } + while (dayStarts.length < 2) { + const prev = new Date(dayStarts[0] || firstDayMs); + prev.setDate(prev.getDate() - 1); + prev.setHours(0, 0, 0, 0); + dayStarts.unshift(prev.getTime()); + } + + const stepDays = dayStarts.length > 60 ? Math.ceil(dayStarts.length / 45) : 1; + let bucketIdx = 0; + for (let i = 0; i < dayStarts.length; i += stepDays) { + const sMs = dayStarts[i]; + const endDayStartMs = dayStarts[Math.min(dayStarts.length - 1, i + stepDays - 1)]; + const endCursor = new Date(endDayStartMs); + endCursor.setDate(endCursor.getDate() + 1); + endCursor.setHours(0, 0, 0, 0); + const eMs = endCursor.getTime(); + + const sd = new Date(sMs); + const ed = new Date(endDayStartMs); + const axisLabel = `${sd.getMonth() + 1}/${pad2(sd.getDate())}`; + const fullLabel = + stepDays === 1 + ? `${sd.getMonth() + 1}月${sd.getDate()}日 (${WEEKDAY_NAMES[sd.getDay()]})` + : `${sd.getMonth() + 1}月${sd.getDate()}日 - ${ed.getMonth() + 1}月${ed.getDate()}日`; + + trendSeries.push({ + index: bucketIdx++, + startMs: sMs, + endMs: eMs, + granularity: 'day', + label: axisLabel, + fullLabel, + tokens: 0, + inputTokens: 0, + cacheReadTokens: 0, + outputTokens: 0, + costUsd: 0, + unpricedCalls: 0, + calls: 0, + }); + } + } + + if (trendSeries.length > 0) { + const firstBucketStart = trendSeries[0].startMs; + const lastIdx = trendSeries.length - 1; + for (const item of selectedWindowSteps) { + let targetIdx = lastIdx; + if (item.tMs <= firstBucketStart) { + targetIdx = 0; + } else { + // 二分查找匹配的时间桶 [startMs, endMs) + let lo = 0; + let hi = lastIdx; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + const b = trendSeries[mid]; + if (item.tMs < b.startMs) { + hi = mid - 1; + } else if (item.tMs >= b.endMs && mid < lastIdx) { + lo = mid + 1; + } else { + targetIdx = mid; + break; + } + } + } + const bucket = trendSeries[targetIdx]; + bucket.tokens += item.tokens; + bucket.inputTokens += item.inputTokens || 0; + bucket.cacheReadTokens += item.cacheReadTokens || 0; + bucket.outputTokens += item.outputTokens || 0; + bucket.costUsd = +(bucket.costUsd + item.costUsd).toFixed(4); + bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls; + bucket.calls += 1; + } } const finalizedPresets = {}; diff --git a/sidecars/panel/index.html b/sidecars/panel/index.html index b984ee4..d03d5a2 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 604b69c..37b2a9e 100644 --- a/sidecars/panel/main.mjs +++ b/sidecars/panel/main.mjs @@ -12,7 +12,7 @@ * - 所有核心业务逻辑均已模块化拆分至 `./backend/*.mjs`。 */ -import { readFileSync, promises as fsPromises } from 'node:fs'; +import { readFileSync, statSync, promises as fsPromises } from 'node:fs'; import { join } from 'node:path'; import { Response, SidecarApp } from 'sidecar_sdk'; import { @@ -24,12 +24,24 @@ import { saveJson, } from './backend/config.mjs'; import { diagnostics } from './backend/ls-rpc.mjs'; -import { performPluginUpdate, syncCloudCatalog } from './backend/plugin-updater.mjs'; +import { + performPluginUpdate, + scheduleSidecarRestart, + syncCloudCatalog, +} from './backend/plugin-updater.mjs'; import { getCloudStatus } from './backend/pricing-catalog.mjs'; import { buildTelemetryPayload } from './backend/telemetry-builder.mjs'; const app = new SidecarApp(); +const bootBundleVersion = (() => { + try { + return statSync(join(HERE, 'app.js')).mtimeMs || 0; + } catch { + return 0; + } +})(); + /** * 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。 * @@ -53,6 +65,10 @@ const readLocalAsync = async (relPath) => { */ function isLocalHostRequest(req) { if (!req?.headers) return true; + const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase(); + if (secFetchSite === 'cross-site') { + return false; + } const host = String(req.headers.host || '').toLowerCase(); if (host && !/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host)) { return false; @@ -60,13 +76,22 @@ function isLocalHostRequest(req) { const origin = String(req.headers.origin || '').toLowerCase(); if ( origin && - !/^(https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?|vscode-webview:\/\/)/.test(origin) + !/^(?:https?:\/\/(?:127\.0\.0\.1|localhost|\[::1\])(?::\d+)?|vscode-webview:\/\/[a-z0-9._-]+)$/.test( + origin + ) ) { return false; } return true; } +const MAX_SAFE_DATE_MS = 8_640_000_000_000_000; + +function sanitizePositiveFiniteMs(val) { + const num = Number(val); + return Number.isFinite(num) && num > 0 && num <= MAX_SAFE_DATE_MS ? Math.floor(num) : 0; +} + const NO_STORE_HEADERS = { 'Cache-Control': 'no-store, no-cache, must-revalidate' }; // --------------------------------------------------------------------------- @@ -114,7 +139,10 @@ app.api( contentType: 'application/json', }); } - const convId = data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || ''; + const rawConvId = String( + data?.conversationId || process.env.ANTIGRAVITY_CONVERSATION_ID || '' + ).trim(); + const convId = rawConvId && !/[\\/]|\.\./.test(rawConvId) ? rawConvId : ''; const force = data?.force === '1' || data?.force === true; if (LS_ADDR !== 'test.invalid') { if (force && Date.now() - cloudSyncState.lastAttemptMs > 15_000) { @@ -128,10 +156,17 @@ app.api( } const filterOpts = { range: data?.range || 'all', - startMs: data?.startMs ? Number(data.startMs) : 0, - endMs: data?.endMs ? Number(data.endMs) : 0, + startMs: sanitizePositiveFiniteMs(data?.startMs), + endMs: sanitizePositiveFiniteMs(data?.endMs), }; const payload = await buildTelemetryPayload(convId, force, filterOpts); + if ( + bootBundleVersion > 0 && + payload.uiBundleVersion > 0 && + payload.uiBundleVersion !== bootBundleVersion + ) { + scheduleSidecarRestart(150); + } return new Response(JSON.stringify(payload), { status: 200, contentType: 'application/json', @@ -141,6 +176,13 @@ app.api( 'GET' ); +const VALID_WEEKLY_LIMIT_MODES = new Set(['official', 'tokens', 'cost']); + +function sanitizePositiveSettingNumber(val, fallback) { + const num = Number(val); + return Number.isFinite(num) && num > 0 ? num : fallback; +} + app.api('/api/settings', (data, req) => { if (!isLocalHostRequest(req)) { return new Response(JSON.stringify({ error: 'Forbidden host or origin' }), { @@ -149,19 +191,30 @@ app.api('/api/settings', (data, req) => { }); } const current = loadSettings(); + const payload = data && typeof data === 'object' ? data : {}; + const rawMode = String(payload.weeklyLimitMode || '').trim(); const updated = { ...current, - contextWindowLimit: Number(data.contextWindowLimit || current.contextWindowLimit), - weeklyTokenBudget: Number(data.weeklyTokenBudget || current.weeklyTokenBudget), - weeklyCostBudget: Number(data.weeklyCostBudget || current.weeklyCostBudget), - weeklyLimitMode: data.weeklyLimitMode || current.weeklyLimitMode, + contextWindowLimit: sanitizePositiveSettingNumber( + payload.contextWindowLimit, + current.contextWindowLimit + ), + weeklyTokenBudget: sanitizePositiveSettingNumber( + payload.weeklyTokenBudget, + current.weeklyTokenBudget + ), + weeklyCostBudget: sanitizePositiveSettingNumber( + payload.weeklyCostBudget, + current.weeklyCostBudget + ), + weeklyLimitMode: VALID_WEEKLY_LIMIT_MODES.has(rawMode) ? rawMode : current.weeklyLimitMode, showUpstreamModel: - typeof data.showUpstreamModel === 'boolean' - ? data.showUpstreamModel + typeof payload.showUpstreamModel === 'boolean' + ? payload.showUpstreamModel : Boolean(current.showUpstreamModel), autoUpdatePlugin: - typeof data.autoUpdatePlugin === 'boolean' - ? data.autoUpdatePlugin + typeof payload.autoUpdatePlugin === 'boolean' + ? payload.autoUpdatePlugin : Boolean(current.autoUpdatePlugin), }; saveJson(SETTINGS_FILE, updated); diff --git a/sidecars/panel/package.json b/sidecars/panel/package.json index 7966d4c..725884f 100644 --- a/sidecars/panel/package.json +++ b/sidecars/panel/package.json @@ -1,6 +1,6 @@ { "name": "usage-monitor-panel", - "version": "1.4.1", + "version": "1.4.2", "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 0fec7da..80b87cb 100644 --- a/sidecars/panel/scripts/build-bundle.mjs +++ b/sidecars/panel/scripts/build-bundle.mjs @@ -4,7 +4,7 @@ * Sidecar Webview sandbox. */ -import { existsSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; diff --git a/sidecars/panel/speed-metrics.mjs b/sidecars/panel/speed-metrics.mjs index 1359b2c..95391dd 100644 --- a/sidecars/panel/speed-metrics.mjs +++ b/sidecars/panel/speed-metrics.mjs @@ -33,7 +33,7 @@ export function parseIsoMs(value) { if (!Number.isFinite(ms)) { return 0; } - const fraction = value.match(/\.(\d+)Z$/); + const fraction = value.match(/\.(\d+)(?:Z|[+-]\d{2}:?\d{2})$/i); if (!fraction) { return ms; } @@ -184,39 +184,6 @@ function isMcpToolItem(name, source = '', type = '') { ); } -/** - * 从 `chatModel` 元数据中提取并拆解 6 大上下文 Token 构成分类: - * - `messagesTokens`:对话历史消息 - * - `systemToolsTokens`:内置系统工具定义 - * - `mcpToolsTokens`:MCP 外部服务器工具与资源定义 - * - `skillsTokens`:已注入的 Skills 指令说明 - * - `systemPromptTokens`:核心系统提示词 - * - `userRulesTokens`:用户自定义全局/工作区规则 - * - * 提取算法分为两个阶段: - * 1. **第一阶段(优先采用原生 `contextWindowMetadata.tokenBreakdown.groups`)**: - * 遍历服务端提供的精确 Token 分组树: - * - 针对 `TOKEN_TYPE_SYSTEM_PROMPT` 分组:遍历其 `children`,通过 `classifyPromptSection` 精细拆分为 - * `skills`、`userRules`、`mcpTools` 与 `systemPrompt`;若父组 `gTokens` 大于子项之和,差额归入 `systemPromptTokens`。 - * - 针对 `TOKEN_TYPE_TOOLS` 或含 `MCP` 标识的分组:遍历其 `children`,通过 `isMcpToolItem` 区分内置系统工具(`systemToolsTokens`) - * 与 MCP 工具(`mcpToolsTokens`);未拆分子项的余量同样按 `isMcpToolItem` 归属。 - * - 针对 `TOKEN_TYPE_CHAT_MESSAGES` 分组:优先累加分组总 `gTokens`,若为 0 则累加其 `children` 的 Token 数至 `messagesTokens`。 - * 2. **第二阶段(缺失分组时的结构化字段回退估算)**: - * 当第一阶段未覆盖某类分组(`!hasPromptGroup` / `!hasToolsGroup` / `!hasMessagesGroup`)时, - * 分别回退遍历 `chat.promptSections`、`chat.tools`、`chat.messagePrompts`: - * 优先读取条目自带的 `numTokens`,若缺失则按 UTF-8 字节长度除以 3(`byteLength / 3` 向上取整)进行估算。 - * - * @param {object} chat `generatorMetadata.chatModel` 对象 - * @returns {{ - * messagesTokens: number, - * systemToolsTokens: number, - * mcpToolsTokens: number, - * skillsTokens: number, - * systemPromptTokens: number, - * userRulesTokens: number, - * totalTokens: number - * } | null} 上下文 Token 构成明细,无任何可用元数据时返回 null - */ /** * 识别 `TOKEN_TYPE_CHAT_MESSAGES` 子项(如 `"391: CHECKPOINT"`、`"404: GENERIC"`)所属的对话细分类型。 * @@ -246,6 +213,22 @@ function classifyChatMessageChild(child) { return 'toolResults'; } +/** + * 从 `chatModel` 元数据中提取并拆解 10 大上下文 Token 构成分类: + * - `systemPromptTokens`:核心系统提示词 + * - `userRulesTokens`:用户自定义全局/工作区规则 + * - `skillsTokens`:已注入的 Skills 指令说明 + * - `systemToolsTokens`:内置系统工具定义 + * - `mcpToolsTokens`:MCP 外部服务器工具与资源定义 + * - `checkpointTokens`:上下文压缩摘要(Checkpoint) + * - `userInputTokens`:用户输入消息 + * - `assistantTokens`:主代理回复与思考 + * - `subagentTokens`:子代理汇报消息 + * - `toolResultsTokens`:工具执行返回结果 + * + * @param {object} chat `generatorMetadata.chatModel` 对象 + * @returns {object | null} 上下文 Token 构成明细,无任何可用元数据时返回 null + */ export function extractContextBreakdown(chat) { if (!chat || typeof chat !== 'object') { return null; @@ -811,6 +794,23 @@ export function normalizeCachedStep(step) { }; } + const DEAD_V3_KEYS = [ + 'phaseDurationSec', + 'phaseTokPerSec', + 'phaseReason', + 'answerStartDelaySec', + 'streamDurationSec', + 'streamTokens', + 'streamTokPerSec', + ]; + const hasDeadV3Key = DEAD_V3_KEYS.some((k) => Object.prototype.hasOwnProperty.call(step, k)); + if (hasDeadV3Key) { + step = { ...step }; + for (const k of DEAD_V3_KEYS) { + delete step[k]; + } + } + if (step.measurementVersion === MEASUREMENT_VERSION) { return step; } @@ -827,13 +827,6 @@ export function normalizeCachedStep(step) { thinkingDurationSec: null, totalDurationSec: null, totalTokPerSec: null, - phaseDurationSec: null, - phaseTokPerSec: null, - phaseReason: 'legacy_cache', - answerStartDelaySec: null, - streamDurationSec: null, - streamTokens: null, - streamTokPerSec: null, speedBasis: 'unavailable', speedSampleEligible: false, speedReason: 'legacy_cache', @@ -969,3 +962,857 @@ export function summarizeTtft(steps) { avgSec, }; } + +/** 标志着原始轨迹步骤已进入终态的状态枚举集合(兼容 Connect RPC 与 transcript.jsonl) */ +const LIVE_TERMINAL_STATUSES = new Set([ + 'CORTEX_STEP_STATUS_DONE', + 'CORTEX_STEP_STATUS_ERROR', + 'CORTEX_STEP_STATUS_CANCELED', + 'CORTEX_STEP_STATUS_CANCELLED', + 'DONE', + 'ERROR', + 'CANCELED', + 'CANCELLED', +]); + +/** + * 判断原始步骤状态是否属于等待人工确认或审批状态。 + * + * @param {unknown} status + * @returns {boolean} + */ +function isWaitingStepStatus(status) { + const s = String(status || '').toUpperCase(); + return ( + s.includes('WAIT') || + s.includes('CONFIRM') || + s.includes('APPROV') || + s.includes('BLOCKED') + ); +} + +/** + * 判断单个原始轨迹步骤是否已执行完毕。 + * + * @param {object} step + * @returns {boolean} + */ +function isRawStepComplete(step) { + if (!step || typeof step !== 'object') return true; + if (typeof step.status === 'string' && step.status.trim()) { + return LIVE_TERMINAL_STATUSES.has(step.status.trim().toUpperCase()); + } + return Boolean( + step.metadata?.completedAt || + step.metadata?.finishedGeneratingAt || + step.completed_at || + step.completedAt + ); +} + +function getRawStepStartMs(step) { + const m = step?.metadata || {}; + return Math.floor( + parseIsoMs(m.createdAt || m.viewableAt || step?.created_at || step?.createdAt) || 0 + ); +} + +function getRawStepFinishMs(step) { + const m = step?.metadata || {}; + const explicitEnd = parseIsoMs( + m.completedAt || m.finishedGeneratingAt || step?.completed_at || step?.completedAt + ); + if (explicitEnd > 0) return Math.floor(explicitEnd); + if (typeof step?.content === 'string') { + const mCompleted = step.content.match(/^Completed At:\s*(\S+)/m); + if (mCompleted && mCompleted[1]) { + const parsed = parseIsoMs(mCompleted[1]); + if (parsed > 0) return Math.floor(parsed); + } + } + return 0; +} + +function getRawStepEndMs(step) { + const finishMs = getRawStepFinishMs(step); + if (finishMs > 0) return finishMs; + const m = step?.metadata || {}; + return Math.floor( + parseIsoMs(m.viewableAt || m.createdAt || step?.created_at || step?.createdAt) || 0 + ); +} + +function getStepStableId(step, fallbackIdx) { + const idx = + step?.step_index ?? + step?.stepIndex ?? + step?.metadata?.sourceTrajectoryStepInfo?.stepIndex; + return idx !== undefined && idx !== null ? idx : fallbackIdx; +} + +/** + * 反转义 `transcript.jsonl` 或工具参数中可能被二次 JSON 序列化的字段值。 + * + * @param {unknown} val + * @returns {unknown} + */ +function unwrapArgValue(val) { + if (typeof val !== 'string') return val; + const trimmed = val.trim(); + if ( + (trimmed.startsWith('"') && trimmed.endsWith('"')) || + (trimmed.startsWith('[') && trimmed.endsWith(']')) || + (trimmed.startsWith('{') && trimmed.endsWith('}')) + ) { + try { + return JSON.parse(trimmed); + } catch { + // 半流式或非标准 JSON 回退至正则反转义 + } + } + return trimmed + .replace(/^"+|"+$/g, '') + .replace(/\\"/g, '"') + .replace(/\\\\/g, '\\') + .replace(/\\n/g, ' ') + .replace(/\\r/g, ''); +} + +function unwrapArgString(val) { + const unwrapped = unwrapArgValue(val); + if (typeof unwrapped === 'string') return unwrapped.trim(); + if (typeof unwrapped === 'number' && Number.isFinite(unwrapped)) return String(unwrapped); + return ''; +} + +/** + * 截取路径末尾的文件或目录基名(兼容 Windows 反斜杠、`file://` URI 及二次转义字符串)。 + * + * @param {unknown} rawPath + * @returns {string} + */ +function shortBasename(rawPath) { + if (typeof rawPath !== 'string' || !rawPath.trim()) return ''; + let cleaned = unwrapArgString(rawPath).replace(/^file:\/\/\/?/i, ''); + try { + if (cleaned.includes('%')) { + cleaned = decodeURIComponent(cleaned); + } + } catch { + // 忽略 URI 解码异常 + } + cleaned = cleaned.replace(/[\\/]+$/, ''); + const parts = cleaned.split(/[\\/]/); + return parts[parts.length - 1] || cleaned; +} + +/** + * 将多行或含 Markdown 标记的文本清洗为紧凑的单行预览摘要。 + * + * @param {unknown} rawText + * @param {number} [maxLen=52] + * @param {boolean} [takeLastLine=false] + * @returns {string} + */ +function cleanSingleLineSnippet(rawText, maxLen = 52, takeLastLine = false) { + if (typeof rawText !== 'string' || !rawText.trim()) return ''; + const lines = rawText + .split(/\r?\n/) + .map((l) => + l + .replace(/^[#>*\-\d.\s]+/, '') + .replace(/[`*_~]/g, '') + .replace(/\s+/g, ' ') + .trim() + ) + .filter(Boolean); + if (lines.length === 0) return ''; + const target = takeLastLine ? lines[lines.length - 1] : lines[0]; + return target.length > maxLen ? `${target.slice(0, maxLen - 1)}…` : target; +} + +/** + * 从可能尚未流式接收完毕的半截 JSON 字符串中按字段名提取字符串值。 + * + * @param {string} rawJson + * @param {string[]} keys + * @returns {string} + */ +function extractPartialJsonStringField(rawJson, keys) { + if (typeof rawJson !== 'string' || !rawJson) return ''; + for (const key of keys) { + const re = new RegExp(`"${key}"\\s*:\\s*"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)`, 'i'); + const m = rawJson.match(re); + if (m && m[1]) { + return m[1] + .replace(/\\"/g, '"') + .replace(/\\\\/g, '\\') + .replace(/\\n/g, ' ') + .replace(/\\r/g, '') + .trim(); + } + } + return ''; +} + +function getStepPlannerToolCalls(step) { + if (Array.isArray(step?.plannerResponse?.toolCalls)) { + return step.plannerResponse.toolCalls; + } + if (Array.isArray(step?.tool_calls)) { + return step.tool_calls; + } + if (Array.isArray(step?.toolCalls)) { + return step.toolCalls; + } + return []; +} + +function getStepResponseText(step) { + const p = step?.plannerResponse || {}; + return String(p.modifiedResponse || p.response || step?.content || '').trim(); +} + +function getStepThinkingText(step) { + const p = step?.plannerResponse || {}; + return String(p.rawThinking || p.thinking || step?.thinking || '').trim(); +} + +function isPlannerStep(step) { + const t = String(step?.type || '').toUpperCase(); + return ( + t === 'CORTEX_STEP_TYPE_PLANNER_RESPONSE' || + t === 'PLANNER_RESPONSE' || + Boolean(step?.plannerResponse) || + Array.isArray(step?.tool_calls) + ); +} + +function isCheckpointStep(step) { + const t = String(step?.type || '').toUpperCase(); + return t === 'CORTEX_STEP_TYPE_CHECKPOINT' || t === 'CHECKPOINT'; +} + +/** + * 解析工具调用对象或半流式 JSON 参数,返回适合界面单行展示的中文动作标签与详情描述。 + * + * @param {object|null|undefined} rawToolCall + * @param {object|null|undefined} [fallbackStep=null] + * @returns {{ toolName: string, isAskUser: boolean, label: string, detail: string }} + */ +export function summarizeToolCall(rawToolCall, fallbackStep = null) { + const stepToolCall = fallbackStep?.metadata?.toolCall || {}; + const stepType = String(fallbackStep?.type || '').toUpperCase(); + let rawName = String( + rawToolCall?.name || + rawToolCall?.toolName || + rawToolCall?.function?.name || + stepToolCall?.name || + '' + ).trim(); + + if (!rawName) { + if ( + stepType.includes('RUN_COMMAND') || + stepType.includes('COMMAND_STATUS') || + fallbackStep?.runCommand + ) { + rawName = 'run_command'; + } else if (stepType.includes('INVOKE_SUBAGENT') || fallbackStep?.invokeSubagent) { + rawName = 'invoke_subagent'; + } else if ( + stepType.includes('VIEW_FILE') || + stepType.includes('READ_FILE') || + fallbackStep?.viewFile || + fallbackStep?.readFile + ) { + rawName = 'read_file'; + } else if ( + stepType.includes('CODE_ACTION') || + stepType.includes('EDIT_FILE') || + fallbackStep?.codeAction || + fallbackStep?.editFile + ) { + rawName = 'edit_file'; + } else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) { + rawName = 'grep_search'; + } else if (stepType.includes('FIND_BY_NAME') || fallbackStep?.findByName) { + rawName = 'find_by_name'; + } else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) { + rawName = 'search_web'; + } + } + + const nameLower = rawName.toLowerCase().replace(/^default_api:/, ''); + let args = {}; + let rawArgsStr = ''; + + const candidateArgs = + rawToolCall?.args ?? + rawToolCall?.arguments ?? + rawToolCall?.argumentsJson ?? + rawToolCall?.function?.arguments ?? + stepToolCall?.argumentsJson; + + if (candidateArgs && typeof candidateArgs === 'object') { + args = candidateArgs; + } else if (typeof candidateArgs === 'string' && candidateArgs.trim()) { + rawArgsStr = candidateArgs.trim(); + try { + const parsed = JSON.parse(rawArgsStr); + if (parsed && typeof parsed === 'object') args = parsed; + } catch { + // 半流式 JSON 尚未闭合,后续通过正则提取关键字段 + } + } + + const stepPayload = + fallbackStep?.runCommand || + fallbackStep?.commandStatus || + fallbackStep?.viewFile || + fallbackStep?.readFile || + fallbackStep?.viewFileOutline || + fallbackStep?.viewCodeItem || + fallbackStep?.codeAction || + fallbackStep?.editFile || + fallbackStep?.replaceFileContent || + fallbackStep?.writeToFile || + fallbackStep?.grepSearch || + fallbackStep?.findByName || + fallbackStep?.listDir || + fallbackStep?.searchWeb || + fallbackStep?.readUrlContent || + null; + + const pickField = (keys) => { + for (const k of keys) { + const fromArgs = unwrapArgString(args?.[k]); + if (fromArgs) return fromArgs; + const camelKey = k.charAt(0).toLowerCase() + k.slice(1); + const fromArgsCamel = unwrapArgString(args?.[camelKey]); + if (fromArgsCamel) return fromArgsCamel; + if (stepPayload && typeof stepPayload === 'object') { + const fromStep = unwrapArgString(stepPayload[k] ?? stepPayload[camelKey]); + if (fromStep) return fromStep; + } + } + return extractPartialJsonStringField(rawArgsStr, keys); + }; + + if ( + nameLower === 'run_command' || + nameLower === 'command_status' || + nameLower === 'send_command_input' + ) { + const summary = pickField(['toolSummary', 'Description', 'Summary']); + const cmd = pickField(['CommandLine', 'Command', 'command']); + const cmdSnippet = cleanSingleLineSnippet(cmd, 48); + const detail = + summary && cmdSnippet && summary !== cmdSnippet + ? `${summary} (${cmdSnippet})` + : summary || cmdSnippet || ''; + return { + toolName: nameLower, + isAskUser: false, + label: '执行命令', + detail, + }; + } + + if ( + nameLower === 'read_file' || + nameLower === 'view_file' || + nameLower === 'view_file_outline' || + nameLower === 'view_code_item' || + nameLower === 'read_notebook' + ) { + const file = shortBasename( + pickField(['Path', 'AbsolutePath', 'AbsolutePathUri', 'FilePath', 'File', 'Uri']) + ); + const startLine = pickField(['StartLine', 'startLine']); + const endLine = pickField(['EndLine', 'endLine']); + const rangeSuffix = + startLine && endLine + ? `:${startLine}-${endLine}` + : startLine + ? `:${startLine}+` + : ''; + return { + toolName: nameLower, + isAskUser: false, + label: '读取文件', + detail: file ? `${file}${rangeSuffix}` : '', + }; + } + + if ( + nameLower === 'edit_file' || + nameLower === 'replace_file_content' || + nameLower === 'multi_replace_file_content' || + nameLower === 'edit_notebook' + ) { + const file = shortBasename( + pickField(['Path', 'TargetFile', 'AbsolutePath', 'AbsolutePathUri', 'FilePath', 'Uri']) + ); + return { + toolName: nameLower, + isAskUser: false, + label: '修改文件', + detail: file || '', + }; + } + + if (nameLower === 'write_file' || nameLower === 'write_to_file') { + const file = shortBasename( + pickField(['Path', 'TargetFile', 'AbsolutePath', 'AbsolutePathUri', 'FilePath', 'Uri']) + ); + return { + toolName: nameLower, + isAskUser: false, + label: '写入文件', + detail: file || '', + }; + } + + if (nameLower === 'grep_search' || nameLower === 'ripgrep') { + const query = pickField(['Query', 'Pattern', 'query']); + const searchPath = shortBasename(pickField(['SearchPath', 'DirectoryPath', 'Path'])); + const detail = + query && searchPath + ? `${cleanSingleLineSnippet(query, 32)} (${searchPath})` + : cleanSingleLineSnippet(query, 48) || searchPath || ''; + return { + toolName: nameLower, + isAskUser: false, + label: '搜索代码', + detail, + }; + } + + if (nameLower === 'find_by_name' || nameLower === 'list_dir') { + const pattern = pickField(['Pattern', 'Query']); + const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path'])); + return { + toolName: nameLower, + isAskUser: false, + label: '查找文件', + detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '', + }; + } + + if (nameLower === 'search_web' || nameLower === 'read_url_content' || nameLower === 'fetch_url') { + const isUrl = nameLower.includes('url'); + const target = pickField(['query', 'Query', 'Url', 'url']); + return { + toolName: nameLower, + isAskUser: false, + label: isUrl ? '读取网页' : '网页搜索', + detail: cleanSingleLineSnippet(target, 52) || '', + }; + } + + if (nameLower === 'invoke_subagent') { + const subSpec = fallbackStep?.invokeSubagent?.subagents?.[0] || {}; + const role = + pickField(['Role', 'role']) || + String(subSpec.role || '').trim() || + pickField(['TypeName', 'typeName']) || + String(subSpec.typeName || '').trim(); + return { + toolName: nameLower, + isAskUser: false, + label: '调用子代理', + detail: role || '', + }; + } + + if (nameLower === 'send_message') { + const recipient = pickField(['Recipient', 'recipient']); + return { + toolName: nameLower, + isAskUser: false, + label: '通信子代理', + detail: recipient ? recipient.slice(0, 8) : '', + }; + } + + if (nameLower === 'manage_subagents' || nameLower === 'define_subagent') { + const subName = pickField(['Name', 'Action', 'action']); + return { + toolName: nameLower, + isAskUser: false, + label: '管理子代理', + detail: subName || '', + }; + } + + if (nameLower === 'manage_task') { + const action = pickField(['Action', 'action']); + const taskId = pickField(['TaskId', 'taskId']); + return { + toolName: nameLower, + isAskUser: false, + label: '后台任务', + detail: taskId ? `${action || 'status'} (${taskId})` : action || '', + }; + } + + if (nameLower === 'schedule') { + const dur = pickField(['DurationSeconds']); + const cron = pickField(['CronExpression']); + return { + toolName: nameLower, + isAskUser: false, + label: '定时任务', + detail: dur ? `${dur}s` : cron || '', + }; + } + + if (nameLower === 'ask_question') { + const rawQuestions = unwrapArgValue(args?.questions); + const qText = + (Array.isArray(rawQuestions) ? rawQuestions[0]?.question : '') || + extractPartialJsonStringField( + typeof args?.questions === 'string' ? args.questions : rawArgsStr, + ['question'] + ); + return { + toolName: nameLower, + isAskUser: true, + label: '等待用户选择', + detail: cleanSingleLineSnippet(qText, 50) || '', + }; + } + + if (nameLower === 'search_marketplace' || nameLower === 'list_plugin_accounts') { + const rawQueries = unwrapArgValue(args?.queries); + const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : ''; + return { + toolName: nameLower, + isAskUser: false, + label: '查询插件', + detail: cleanSingleLineSnippet(q, 48) || '', + }; + } + + if (isMcpToolItem(nameLower)) { + const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · '); + return { + toolName: nameLower, + isAskUser: false, + label: '调用 MCP', + detail: mcpClean || '', + }; + } + + return { + toolName: nameLower || 'tool', + isAskUser: false, + label: '调用工具', + detail: nameLower || '', + }; +} + +/** + * 从当前正在运行的会话原始步骤数组 (`rawSteps`,兼容 `GetCascadeTrajectory` 与 `transcript.jsonl`) 中提取模型实时动作摘要。 + * + * 状态判定覆盖完整 Agent 循环: + * 1. 轨迹为空或刚创建:显示“准备推理”; + * 2. 末尾步骤未完成 (`!isRawStepComplete(lastStep)`): + * - 若为 `CHECKPOINT`:显示“上下文压缩”; + * - 若为 `PLANNER_RESPONSE`:按 `toolCalls -> response -> thinking -> 首字等待` 优先级提取当前流式动作; + * - 若为工具执行步骤:结合 `status` 判定是否处于“等待确认”,并回溯最近一次 `PLANNER_RESPONSE` 匹配对应的工具名与 `[m/n]` 批次进度; + * 3. 末尾步骤已完成 (`DONE`) 但会话仍处于 `RUNNING`: + * - 若最近一次 `PLANNER_RESPONSE` 声明了 `N` 个工具调用,而其后仅有 `M < N` 个完成步骤,则判定第 `M + 1` 个工具正在执行中; + * - 若 `M >= N`(全部工具已返回结果)或末尾为 `USER_INPUT`,则判定模型正在汇总工具结果并准备下一轮推理。 + * + * @param {Array} [rawSteps=[]] + * @param {boolean} [isRunning=false] + * @param {number} [fallbackStartMs=0] + * @returns {{ + * phase: 'thinking' | 'responding' | 'tool' | 'waiting' | 'compacting', + * label: string, + * detail: string, + * stepProgress: string, + * startedAtMs: number, + * signature: string + * } | null} + */ +export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackStartMs = 0) { + if (!isRunning) return null; + if (!Array.isArray(rawSteps) || rawSteps.length === 0) { + const startMs = Math.floor(fallbackStartMs || 0); + return { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: startMs, + signature: `init:0`, + }; + } + + const hasBracketPrefix = (text) => /^\[\d+\s*\/\s*\d+\]/.test(String(text || '').trim()); + + let lastPlannerIdx = -1; + let lastUserIdx = -1; + for (let i = rawSteps.length - 1; i >= 0; i--) { + const st = rawSteps[i]; + const t = String(st?.type || '').toUpperCase(); + if (lastPlannerIdx === -1 && isPlannerStep(st)) { + lastPlannerIdx = i; + } + if (lastUserIdx === -1 && t.includes('USER_INPUT')) { + lastUserIdx = i; + } + if (lastPlannerIdx !== -1 && lastUserIdx !== -1) break; + } + + const lastIdx = rawSteps.length - 1; + const lastStep = rawSteps[lastIdx]; + const lastStepId = getStepStableId(lastStep, lastIdx); + const lastComplete = isRawStepComplete(lastStep); + + // 情况 A:最后一个步骤本身尚未完成(正在流式生成或正在执行该步骤) + if (!lastComplete) { + const startMs = getRawStepStartMs(lastStep) || Math.floor(fallbackStartMs || 0); + + if (isCheckpointStep(lastStep)) { + return { + phase: 'compacting', + label: '上下文压缩', + detail: '', + stepProgress: '', + startedAtMs: startMs, + signature: `compacting:${lastStepId}`, + }; + } + + if (isPlannerStep(lastStep)) { + const tools = getStepPlannerToolCalls(lastStep); + const respText = getStepResponseText(lastStep); + const thinkText = getStepThinkingText(lastStep); + + if (tools.length > 0) { + const activeTool = tools[tools.length - 1]; + const info = summarizeToolCall(activeTool, lastStep); + const stepProgress = + tools.length > 1 && !hasBracketPrefix(info.detail) ? `${tools.length}/${tools.length}` : ''; + const phase = info.isAskUser ? 'waiting' : 'tool'; + return { + phase, + label: info.label, + detail: info.detail, + stepProgress, + startedAtMs: startMs, + signature: `planner-tool:${lastStepId}:${tools.length}:${info.label}:${info.detail}`, + }; + } + + if (respText.length > 0) { + const snippet = cleanSingleLineSnippet(respText, 52, true); + return { + phase: 'responding', + label: '正在输出回复', + detail: snippet, + stepProgress: '', + startedAtMs: startMs, + signature: `responding:${lastStepId}:${snippet}`, + }; + } + + if (thinkText.length > 0) { + const snippet = cleanSingleLineSnippet(thinkText, 52, true); + return { + phase: 'thinking', + label: '推理中', + detail: snippet, + stepProgress: '', + startedAtMs: startMs, + signature: `thinking:${lastStepId}:${snippet}`, + }; + } + + return { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: startMs, + signature: `waiting-ttft:${lastStepId}`, + }; + } + + // 末尾是未完成的工具执行步骤 + let matchedPlannerTool = null; + let stepProgress = ''; + if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx) { + const pTools = getStepPlannerToolCalls(rawSteps[lastPlannerIdx]); + const toolStepsAfterPlanner = []; + for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) { + const kt = String(rawSteps[k]?.type || '').toUpperCase(); + if (!kt.includes('CHECKPOINT') && !kt.includes('MEMENTO') && !kt.includes('EPHEMERAL')) { + toolStepsAfterPlanner.push(rawSteps[k]); + } + } + const toolIdx = toolStepsAfterPlanner.length - 1; + if (toolIdx >= 0 && toolIdx < pTools.length) { + matchedPlannerTool = pTools[toolIdx]; + if (pTools.length > 1) { + stepProgress = `${toolIdx + 1}/${pTools.length}`; + } + } + } + + const info = summarizeToolCall(matchedPlannerTool, lastStep); + if (hasBracketPrefix(info.detail)) { + stepProgress = ''; + } + const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser; + const prevEndMs = lastIdx > 0 ? getRawStepFinishMs(rawSteps[lastIdx - 1]) : 0; + const resolvedStartMs = startMs || prevEndMs || 0; + const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label; + + return { + phase: waiting ? 'waiting' : 'tool', + label, + detail: info.detail, + stepProgress, + startedAtMs: resolvedStartMs, + signature: `step-run:${lastStepId}:${waiting}:${label}:${stepProgress}:${info.detail}`, + }; + } + + // 情况 B:末尾步骤已是完成态 (DONE),但整个会话仍处于 RUNNING 状态 + if (lastPlannerIdx >= 0 && lastPlannerIdx > lastUserIdx) { + const plannerStep = rawSteps[lastPlannerIdx]; + const plannerStepId = getStepStableId(plannerStep, lastPlannerIdx); + const pTools = getStepPlannerToolCalls(plannerStep); + const toolStepsAfterPlanner = []; + for (let k = lastPlannerIdx + 1; k <= lastIdx; k++) { + const kt = String(rawSteps[k]?.type || '').toUpperCase(); + if (!kt.includes('CHECKPOINT') && !kt.includes('MEMENTO') && !kt.includes('EPHEMERAL')) { + toolStepsAfterPlanner.push(rawSteps[k]); + } + } + const completedAfterPlanner = toolStepsAfterPlanner.length; + + // B1:上一轮 PLANNER_RESPONSE 发出的 N 个工具调用尚有未落盘完成的项 (completedAfterPlanner < N) + if (pTools.length > 0 && completedAfterPlanner < pTools.length) { + const currentTool = pTools[completedAfterPlanner]; + const info = summarizeToolCall(currentTool, null); + const stepProgress = + pTools.length > 1 && !hasBracketPrefix(info.detail) + ? `${completedAfterPlanner + 1}/${pTools.length}` + : ''; + // 优先采用上一已完成步骤的真实完成时刻,若为 transcript.jsonl 无完成时间戳则回退至步骤创建时刻 + const startMs = + getRawStepFinishMs(lastStep) || + getRawStepFinishMs(plannerStep) || + getRawStepEndMs(lastStep) || + getRawStepEndMs(plannerStep) || + 0; + const phase = info.isAskUser ? 'waiting' : 'tool'; + + return { + phase, + label: info.label, + detail: info.detail, + stepProgress, + startedAtMs: startMs, + signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.label}:${stepProgress}:${info.detail}`, + }; + } + + // B2:上一轮发出的工具已全部执行完毕,按各自对应的工具完成步骤提取目标文件/命令 + if (pTools.length > 0 && completedAfterPlanner >= pTools.length) { + const infos = pTools.map((t, idx) => + summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep) + ); + const lastToolInfo = infos[infos.length - 1]; + const allSameLabel = infos.every((x) => x.label === lastToolInfo.label); + const detailsList = infos.map((x) => x.detail).filter(Boolean); + const combinedDetail = + infos.length > 1 && allSameLabel + ? cleanSingleLineSnippet(detailsList.join(', '), 64) + : lastToolInfo.detail || cleanSingleLineSnippet(detailsList.join(', '), 64); + const stepProgress = + pTools.length > 1 && !hasBracketPrefix(combinedDetail) + ? `${pTools.length}/${pTools.length}` + : ''; + const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; + return { + phase: 'thinking', + label: lastToolInfo.label, + detail: combinedDetail, + stepProgress, + startedAtMs: startMs, + signature: `post-tool-think:${lastStepId}:${lastToolInfo.label}:${combinedDetail}`, + }; + } + + // B2.5:Connect RPC 轨迹中工具作为独立步骤存在(plannerResponse.toolCalls 为空)时,直接提取最后一个工具步骤的目标文件/命令 + if (lastIdx > lastPlannerIdx) { + const stepTypeUpper = String(lastStep?.type || '').toUpperCase(); + if (!stepTypeUpper.includes('USER_INPUT') && !stepTypeUpper.includes('GENERIC')) { + const lastInfo = summarizeToolCall(null, lastStep); + if (lastInfo.toolName !== 'tool' || lastInfo.detail) { + const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0; + return { + phase: 'thinking', + label: lastInfo.label, + detail: lastInfo.detail, + stepProgress: '', + startedAtMs: startMs, + signature: `post-step-tool:${lastStepId}:${lastInfo.label}:${lastInfo.detail}`, + }; + } + } + } + + // B3:末尾即为无工具调用的 PLANNER_RESPONSE(但会话仍处于 RUNNING),展示最新回复或思考摘要 + if (lastPlannerIdx === lastIdx) { + const respText = getStepResponseText(plannerStep); + const thinkText = getStepThinkingText(plannerStep); + const startMs = getRawStepFinishMs(plannerStep) || getRawStepStartMs(plannerStep) || 0; + if (respText.length > 0) { + const snippet = cleanSingleLineSnippet(respText, 52, true); + if (snippet) { + return { + phase: 'responding', + label: '正在输出回复', + detail: snippet, + stepProgress: '', + startedAtMs: startMs, + signature: `responding-done:${lastStepId}:${snippet}`, + }; + } + } + if (thinkText.length > 0) { + const snippet = cleanSingleLineSnippet(thinkText, 52, true); + if (snippet) { + return { + phase: 'thinking', + label: '推理中', + detail: snippet, + stepProgress: '', + startedAtMs: startMs, + signature: `thinking-done:${lastStepId}:${snippet}`, + }; + } + } + } + } + + // B4:末尾是 USER_INPUT 或普通完成步骤 + const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0; + return { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: startMs, + signature: `post-step-think:${lastStepId}`, + }; +} + diff --git a/sidecars/panel/src/components/charts/TrendAreaChart.js b/sidecars/panel/src/components/charts/TrendAreaChart.js index 2414f71..948da0f 100644 --- a/sidecars/panel/src/components/charts/TrendAreaChart.js +++ b/sidecars/panel/src/components/charts/TrendAreaChart.js @@ -1,16 +1,18 @@ /** - * @fileoverview 纯 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart). - * 负责将按时间分桶的 Token 消耗序列渲染为带垂直渐变填充、虚线参考网格、 - * 峰值描点与自适应防溢出的顶部峰值胶囊标签的面积图。 + * @fileoverview 交互式 SVG 三次贝塞尔平滑曲线趋势图组件 (TrendAreaChart). + * 支持: + * 1. 自适应整点小时(<=72h)与自然日(>72h)高精度分桶序列渲染; + * 2. 鼠标悬停/滑动十字准星探针、高亮圆点与自适应防溢出的悬浮详情卡片(精确日期/小时区间、Token 拆分、费用与调用次数); + * 3. 与 SVG 垂直网格线像素级对齐的多刻度底部时间轴(彻底告别首/中/末简单对半切分)。 */ -import { h, patchAttr, patchStyleVar, patchText } from '../../core/domPatch.js'; -import { formatTokensPrecise } from '../../core/formatters.js'; +import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js'; +import { formatTokensPrecise, formatUsd } from '../../core/formatters.js'; import { SVG_NS } from '../../icons/SvgIcon.js'; /** * 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。 - * 控制点沿 X 轴取相邻点间距的 `0.45` 张力系数,Y 轴与各自端点齐平, + * 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平, * 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。 * * @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组 @@ -23,33 +25,59 @@ function buildSmoothSplinePath(points) { for (let i = 0; i < points.length - 1; i++) { const p0 = points[i]; const p1 = points[i + 1]; - const cpx1 = p0.x + (p1.x - p0.x) * 0.45; - const cpx2 = p1.x - (p1.x - p0.x) * 0.45; + const cpx1 = p0.x + (p1.x - p0.x) * 0.42; + const cpx2 = p1.x - (p1.x - p0.x) * 0.42; d += ` C ${cpx1.toFixed(1)} ${p0.y.toFixed(1)}, ${cpx2.toFixed(1)} ${p1.y.toFixed(1)}, ${p1.x.toFixed(1)} ${p1.y.toFixed(1)}`; } return d; } /** - * 创建 SVG 历史趋势平滑面积图组件。 + * 根据分桶总数与标签平均长度,计算底部 X 轴应当展示的均匀刻度下标列表。 * - * SVG 视口坐标系 (`viewBox="0 0 460 116"`) 布局约定: - * - 水平绘图区:`leftX = 12` 至 `rightX = 448`(总跨度 `spanX = 436`),左右预留边距容纳端点圆点描边; - * - 垂直绘图区:顶部峰值线 `topY = 26` 至底部零基线 `bottomY = 98`(总跨度 `spanY = 72`), - * 顶部预留 26px 空间给 HTML 峰值胶囊 (`.trend-peak-pill`)。 + * @param {Array<{ label?: string }>} slots + * @returns {number[]} + */ +function computeTickIndices(slots) { + const n = slots.length; + if (n <= 1) return [0]; + if (n <= 8) { + return Array.from({ length: n }, (_, i) => i); + } + const sampleLabel = String(slots[Math.floor(n / 2)]?.label || slots[0]?.label || ''); + const maxTicks = sampleLabel.length > 6 ? 5 : 6; + const set = new Set(); + for (let k = 0; k < maxTicks; k++) { + const idx = Math.round((k / (maxTicks - 1)) * (n - 1)); + set.add(idx); + } + return Array.from(set).sort((a, b) => a - b); +} + +/** + * 创建交互式 SVG 历史趋势平滑面积图组件。 * * @returns {{ * el: HTMLElement, - * update: (series?: Array<{ label: string, tokens: number }>) => void - * }} 图表容器节点与序列更新方法 + * update: (series?: Array) => void + * }} */ export function createTrendAreaChart() { + const VIEW_W = 460; + const VIEW_H = 120; + const LEFT_X = 14; + const RIGHT_X = 446; + const TOP_Y = 24; + const BOTTOM_Y = 102; + const SPAN_X = RIGHT_X - LEFT_X; + const SPAN_Y = BOTTOM_Y - TOP_Y; + const svg = document.createElementNS(SVG_NS, 'svg'); - svg.setAttribute('viewBox', '0 0 460 116'); + svg.setAttribute('viewBox', `0 0 ${VIEW_W} ${VIEW_H}`); svg.setAttribute('class', 'trend-svg'); svg.setAttribute('aria-hidden', 'true'); - // 垂直线性渐变:由顶部 36% 不透明度的主题色平滑衰减至底部全透明 + // 垂直线性渐变 const defs = document.createElementNS(SVG_NS, 'defs'); const grad = document.createElementNS(SVG_NS, 'linearGradient'); grad.setAttribute('id', 'trend-area-grad'); @@ -61,7 +89,7 @@ export function createTrendAreaChart() { const stop1 = document.createElementNS(SVG_NS, 'stop'); stop1.setAttribute('offset', '0%'); stop1.setAttribute('stop-color', 'var(--ctx-cached)'); - stop1.setAttribute('stop-opacity', '0.36'); + stop1.setAttribute('stop-opacity', '0.34'); const stop2 = document.createElementNS(SVG_NS, 'stop'); stop2.setAttribute('offset', '100%'); @@ -73,26 +101,22 @@ export function createTrendAreaChart() { defs.appendChild(grad); svg.appendChild(defs); - // 背景辅助参考网格线:3 条水平分位线 + 3 条垂直时间锚点分割线 - const gridGroup = document.createElementNS(SVG_NS, 'g'); - gridGroup.setAttribute('class', 'trend-grid'); - for (const y of [26, 62, 98]) { + // 背景水平与垂直参考网格线 + const hGridGroup = document.createElementNS(SVG_NS, 'g'); + hGridGroup.setAttribute('class', 'trend-grid'); + for (const y of [TOP_Y, Math.round((TOP_Y + BOTTOM_Y) / 2), BOTTOM_Y]) { const line = document.createElementNS(SVG_NS, 'line'); - line.setAttribute('x1', '10'); + line.setAttribute('x1', String(LEFT_X)); line.setAttribute('y1', String(y)); - line.setAttribute('x2', '450'); + line.setAttribute('x2', String(RIGHT_X)); line.setAttribute('y2', String(y)); - gridGroup.appendChild(line); + hGridGroup.appendChild(line); } - for (const x of [118, 230, 342]) { - const line = document.createElementNS(SVG_NS, 'line'); - line.setAttribute('x1', String(x)); - line.setAttribute('y1', '16'); - line.setAttribute('x2', String(x)); - line.setAttribute('y2', '98'); - gridGroup.appendChild(line); - } - svg.appendChild(gridGroup); + svg.appendChild(hGridGroup); + + const vGridGroup = document.createElementNS(SVG_NS, 'g'); + vGridGroup.setAttribute('class', 'trend-grid trend-v-grid'); + svg.appendChild(vGridGroup); const areaPath = document.createElementNS(SVG_NS, 'path'); areaPath.setAttribute('fill', 'url(#trend-area-grad)'); @@ -103,25 +127,157 @@ export function createTrendAreaChart() { linePath.setAttribute('fill', 'none'); svg.appendChild(linePath); + const dotsGroup = document.createElementNS(SVG_NS, 'g'); + dotsGroup.setAttribute('class', 'trend-dots-group'); + svg.appendChild(dotsGroup); + const peakDot = document.createElementNS(SVG_NS, 'circle'); peakDot.setAttribute('r', '3'); peakDot.setAttribute('class', 'trend-peak-dot'); svg.appendChild(peakDot); - const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); - const chartWrap = h('div', { className: 'trend-chart-wrap' }, [peakPill, svg]); + // 悬停十字准星与焦点圆点 + const hoverLine = document.createElementNS(SVG_NS, 'line'); + hoverLine.setAttribute('class', 'trend-hover-line'); + hoverLine.setAttribute('y1', '12'); + hoverLine.setAttribute('y2', String(BOTTOM_Y)); + hoverLine.setAttribute('hidden', 'true'); + svg.appendChild(hoverLine); - let lastLineD = ''; + const hoverDot = document.createElementNS(SVG_NS, 'circle'); + hoverDot.setAttribute('r', '3.2'); + hoverDot.setAttribute('class', 'trend-hover-dot'); + hoverDot.setAttribute('hidden', 'true'); + svg.appendChild(hoverDot); + + const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' }); + + // 悬停详情浮层卡片 + const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' }); + const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' }); + const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' }); + const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' }); + const tipSubEl = h('div', { className: 'trend-tip-sub text-mono', hidden: true }); + + const tooltipEl = h( + 'div', + { className: 'trend-tooltip', hidden: true }, + [ + h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]), + h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]), + tipSubEl, + ] + ); + + // 底部对齐刻度轴 + const xAxisEl = h('div', { className: 'trend-x-axis' }); + + const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, tooltipEl, svg]); + const chartWrap = h('div', { className: 'trend-chart-wrap' }, [plotStage, xAxisEl]); + + let currentSlots = []; + let currentPts = []; + let tickElsByIdx = new Map(); + let hoveredIdx = -1; + let lastRenderSig = ''; + + function showHoverAtIndex(idx) { + if (idx < 0 || idx >= currentSlots.length || !currentPts[idx]) { + clearHover(); + return; + } + hoveredIdx = idx; + const slot = currentSlots[idx]; + const pt = currentPts[idx]; + + patchAttr(hoverLine, 'hidden', false); + patchAttr(hoverLine, 'x1', pt.x.toFixed(1)); + patchAttr(hoverLine, 'x2', pt.x.toFixed(1)); + + patchAttr(hoverDot, 'hidden', false); + patchAttr(hoverDot, 'cx', pt.x.toFixed(1)); + patchAttr(hoverDot, 'cy', pt.y.toFixed(1)); + + patchAttr(peakPill, 'hidden', true); + patchAttr(tooltipEl, 'hidden', false); + + patchText(tipTimeEl, slot.fullLabel || slot.label || '--'); + patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`); + patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`); + patchText( + tipCostEl, + formatUsd(Number(slot.costUsd || 0), { + unpricedCalls: slot.unpricedCalls, + precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1, + }) + ); + + const hasSubBreakdown = + Number(slot.tokens || 0) > 0 && + (slot.inputTokens !== undefined || + slot.cacheReadTokens !== undefined || + slot.outputTokens !== undefined); + patchAttr(tipSubEl, 'hidden', !hasSubBreakdown); + if (hasSubBreakdown) { + patchText( + tipSubEl, + `入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}` + ); + } + + const rawPct = (pt.x / VIEW_W) * 100; + const clampedPct = Math.max(2, Math.min(98, rawPct)); + const shiftX = rawPct < 28 ? '0%' : rawPct > 72 ? '-100%' : '-50%'; + patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`); + patchStyleVar(tooltipEl, '--tip-shift', shiftX); + + for (const [tIdx, el] of tickElsByIdx.entries()) { + patchClasses(el, { 'is-hovered': tIdx === idx }); + } + } + + function clearHover() { + hoveredIdx = -1; + patchAttr(hoverLine, 'hidden', true); + patchAttr(hoverDot, 'hidden', true); + patchAttr(tooltipEl, 'hidden', true); + patchAttr(peakPill, 'hidden', false); + for (const el of tickElsByIdx.values()) { + patchClasses(el, { 'is-hovered': false }); + } + } + + function handlePointerMove(e) { + if (!currentSlots.length) return; + const rect = svg.getBoundingClientRect(); + if (!rect || rect.width <= 0) return; + const relX = ((e.clientX - rect.left) / rect.width) * VIEW_W; + const ratio = (relX - LEFT_X) / Math.max(1, SPAN_X); + const idx = Math.max( + 0, + Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1))) + ); + showHoverAtIndex(idx); + } + + plotStage.addEventListener('mousemove', handlePointerMove); + plotStage.addEventListener('mouseleave', clearHover); /** - * 根据最新时间分桶序列重绘平滑曲线、闭合渐变区域以及最高峰标记位置。 + * 根据最新时间分桶序列重绘平滑曲线、渐变区域、峰值气泡与底部对齐刻度。 */ function update(series = []) { - const slots = series.length >= 2 ? series : [ - { label: '00:00', tokens: 0 }, - { label: '06:00', tokens: 0 }, - { label: '12:00', tokens: 0 }, - ]; + const slots = + Array.isArray(series) && series.length >= 2 + ? series + : [ + { label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 }, + { label: '06:00', fullLabel: '06:00 - 07:00', tokens: 0, calls: 0, costUsd: 0 }, + { label: '12:00', fullLabel: '12:00 - 13:00', tokens: 0, calls: 0, costUsd: 0 }, + { label: '18:00', fullLabel: '18:00 - 19:00', tokens: 0, calls: 0, costUsd: 0 }, + ]; + currentSlots = slots; + let maxTokens = 0; let peakIdx = 0; for (let i = 0; i < slots.length; i++) { @@ -132,39 +288,92 @@ export function createTrendAreaChart() { } } - // SVG 绘图区边界与跨度参数(Y 轴向下递增,因此数值越大对应的 y 坐标越小) - const leftX = 12; - const rightX = 448; - const topY = 26; - const bottomY = 98; - const spanX = rightX - leftX; - const spanY = bottomY - topY; const denom = Math.max(1, maxTokens); - const pts = slots.map((s, idx) => { - const x = leftX + (idx / Math.max(1, slots.length - 1)) * spanX; + const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X; const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0; - const y = bottomY - ratio * spanY; - return { x, y }; + const y = BOTTOM_Y - ratio * SPAN_Y; + return { x, y, tokens: Number(s.tokens || 0) }; }); + currentPts = pts; - // 仅在曲线路径发生变化时更新 DOM 属性,避免无意义的 SVG 重绘 - const lineD = buildSmoothSplinePath(pts); - if (lineD !== lastLineD) { - lastLineD = lineD; - const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${bottomY} L ${pts[0].x.toFixed(1)} ${bottomY} Z`; + const sig = slots + .map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`) + .join('|'); + + if (sig !== lastRenderSig) { + lastRenderSig = sig; + const lineD = buildSmoothSplinePath(pts); + const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`; patchAttr(linePath, 'd', lineD); patchAttr(areaPath, 'd', areaD); + + // 渲染与底部刻度对齐的垂直参考网格线及底部 X 轴标签 + const tickIndices = computeTickIndices(slots); + while (vGridGroup.firstChild) vGridGroup.removeChild(vGridGroup.firstChild); + while (xAxisEl.firstChild) xAxisEl.removeChild(xAxisEl.firstChild); + tickElsByIdx = new Map(); + + for (let i = 0; i < tickIndices.length; i++) { + const tIdx = tickIndices[i]; + const pt = pts[tIdx]; + const slot = slots[tIdx]; + if (!pt || !slot) continue; + + if (i > 0 && i < tickIndices.length - 1) { + const vLine = document.createElementNS(SVG_NS, 'line'); + vLine.setAttribute('x1', pt.x.toFixed(1)); + vLine.setAttribute('y1', '16'); + vLine.setAttribute('x2', pt.x.toFixed(1)); + vLine.setAttribute('y2', String(BOTTOM_Y)); + vGridGroup.appendChild(vLine); + } + + const isFirst = i === 0; + const isLast = i === tickIndices.length - 1; + const pct = (pt.x / VIEW_W) * 100; + const tickEl = h('span', { + className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`, + text: slot.label || '', + title: slot.fullLabel || slot.label || '', + }); + patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`); + tickEl.onclick = () => showHoverAtIndex(tIdx); + xAxisEl.appendChild(tickEl); + tickElsByIdx.set(tIdx, tickEl); + } + + // 渲染采样点小圆点(当点数 <= 36 时展示,突出有消耗的整点/日期) + while (dotsGroup.firstChild) dotsGroup.removeChild(dotsGroup.firstChild); + if (pts.length <= 36) { + for (let i = 0; i < pts.length; i++) { + if (pts[i].tokens <= 0) continue; + const dot = document.createElementNS(SVG_NS, 'circle'); + dot.setAttribute('cx', pts[i].x.toFixed(1)); + dot.setAttribute('cy', pts[i].y.toFixed(1)); + dot.setAttribute('r', '2'); + dot.setAttribute('class', 'trend-node-dot'); + dotsGroup.appendChild(dot); + } + } } - // 定位峰值圆点,并将顶部峰值气泡水平位置钳制在 [8%, 92%] 区间内以防贴边裁切 - const peakPt = pts[peakIdx] || { x: 230, y: bottomY }; + const peakPt = pts[peakIdx] || { x: 230, y: BOTTOM_Y }; patchAttr(peakDot, 'cx', peakPt.x.toFixed(1)); patchAttr(peakDot, 'cy', peakPt.y.toFixed(1)); - patchText(peakPill, formatTokensPrecise(maxTokens)); - const pctLeft = Math.max(8, Math.min(92, (peakPt.x / 460) * 100)); + const peakSlot = slots[peakIdx]; + const peakText = + maxTokens > 0 && peakSlot?.label + ? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}` + : formatTokensPrecise(maxTokens); + patchText(peakPill, peakText); + const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100)); patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`); + + if (hoveredIdx >= 0 && hoveredIdx < slots.length) { + showHoverAtIndex(hoveredIdx); + } } return { el: chartWrap, update }; diff --git a/sidecars/panel/src/components/layout/TopSessionHeader.js b/sidecars/panel/src/components/layout/TopSessionHeader.js index 8f03688..898e7df 100644 --- a/sidecars/panel/src/components/layout/TopSessionHeader.js +++ b/sidecars/panel/src/components/layout/TopSessionHeader.js @@ -6,12 +6,9 @@ import { defineComponent } from '../../core/component.js'; import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js'; -import { formatUsd } from '../../core/formatters.js'; import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js'; import { fetchTelemetry, - formatAgentLabel, - resolveScopedConversation, telemetryStore, triggerPluginUpdate, } from '../../store/telemetryStore.js'; @@ -97,59 +94,7 @@ export const TopSessionHeader = defineComponent({ h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]), ]); - // --- 方案 A:顶栏二级主/子代理切换条 (.agent-scope-bar,无子代理时自动隐藏) --- - const scopeAllBtnText = h('span', { text: '全部汇总' }); - const scopeAllBtn = h( - 'button', - { - type: 'button', - className: 'scope-pill-btn is-active', - onClick: () => - uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }), - }, - [scopeAllBtnText] - ); - - const scopeMainBtnText = h('span', { text: '主代理' }); - const scopeMainBtn = h( - 'button', - { - type: 'button', - className: 'scope-pill-btn', - onClick: () => uiStore.setState({ selectedAgentScope: 'main' }), - }, - [scopeMainBtnText] - ); - - const subagentSelect = CustomSelect({ - modelValue: '', - icon: 'cpu', - placeholder: '子代理 (0)', - className: 'scope-subagent-select', - options: [], - onUpdateModelValue: (nextSubId) => { - if (nextSubId) { - uiStore.setState({ selectedAgentScope: nextSubId }); - } - }, - }); - - const scopeRightText = h('span', { className: 'agent-scope-right text-mono', text: '' }); - - const scopeBarEl = h( - 'div', - { className: 'agent-scope-bar', hidden: true }, - [ - h('div', { className: 'agent-scope-left' }, [ - scopeAllBtn, - scopeMainBtn, - subagentSelect.el, - ]), - scopeRightText, - ] - ); - - const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl, scopeBarEl]); + const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl]); let lastActiveCascadeId = ''; @@ -183,45 +128,9 @@ export const TopSessionHeader = defineComponent({ options, }); - const { - hasSubagents, - effectiveScope, - subagents, - mainAgent, - aggregated, - scopedConv, - } = resolveScopedConversation(telemetry, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId); - - patchAttr(scopeBarEl, 'hidden', !hasSubagents); - if (hasSubagents) { - patchText(scopeAllBtnText, `全部 (${aggregated?.stepCount ?? 0})`); - patchClasses(scopeAllBtn, { 'is-active': effectiveScope === 'all' }); - - patchText(scopeMainBtnText, `主代理 (${mainAgent?.stepCount ?? 0})`); - patchClasses(scopeMainBtn, { 'is-active': effectiveScope === 'main' }); - - const isSubSelected = effectiveScope !== 'all' && effectiveScope !== 'main'; - patchClasses(subagentSelect.el, { 'is-active-sub': isSubSelected }); - const subOptions = subagents.map((s) => ({ - value: s.agentId, - label: formatAgentLabel(s), - meta: `${s.stepCount || 0}步 · 窗${s.context?.usedPct ?? 0}%`, - })); - subagentSelect.setProps({ - modelValue: isSubSelected ? effectiveScope : '', - placeholder: `子代理 (${subagents.length})`, - options: subOptions, - }); - - patchText( - scopeRightText, - formatUsd(scopedConv?.sessionCostUsd || 0, { - unpricedCalls: scopedConv?.sessionUnpricedCalls, - }) - ); - } else { - subagentSelect.close(); - } + const actConv = telemetry?.activeConversation; + const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0); + const aggregated = actConv?.aggregated; const cloudStatus = telemetry?.cloudStatus; const hasUpdate = Boolean(cloudStatus?.updateAvailable); @@ -308,21 +217,14 @@ export const TopSessionHeader = defineComponent({ () => renderHeaderState() ); - const unsubUi = uiStore.subscribe( - (st) => st.selectedAgentScope, - () => renderHeaderState() - ); - onCleanup(() => { unsubTelemetry(); - unsubUi(); convSelect.destroy(); - subagentSelect.destroy(); }); return { el: headerEl, - refs: { convSelect, subagentSelect, statusTag, refreshBtn, scopeBarEl }, + refs: { convSelect, statusTag, refreshBtn }, }; }, }); diff --git a/sidecars/panel/src/components/ui/ContextSegmentMeter.js b/sidecars/panel/src/components/ui/ContextSegmentMeter.js index 84f0c06..6ef3e52 100644 --- a/sidecars/panel/src/components/ui/ContextSegmentMeter.js +++ b/sidecars/panel/src/components/ui/ContextSegmentMeter.js @@ -5,7 +5,7 @@ */ import { defineComponent } from '../../core/component.js'; -import { h, patchAttr, patchStyleVar } from '../../core/domPatch.js'; +import { h, patchAttr, patchClasses, patchStyleVar } from '../../core/domPatch.js'; const SEGMENT_DEFS = [ { key: 'assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) }, @@ -27,11 +27,10 @@ const SEGMENT_DEFS = [ export const ContextSegmentMeter = defineComponent({ name: 'ContextSegmentMeter', setup({ getProps }) { - const segments = SEGMENT_DEFS.map((def, idx) => ({ - ...def, - defaultOrder: idx, - el: h('div', { className: `progress-seg ${def.cls}` }), - })); + // 固定 10 个位置槽位节点,不通过 appendChild 移动 DOM,防止浏览器中断 CSS transition 动画 + const slotEls = SEGMENT_DEFS.map((def) => + h('div', { className: `progress-seg ${def.cls}` }) + ); const trackEl = h( 'div', @@ -41,28 +40,38 @@ export const ContextSegmentMeter = defineComponent({ 'aria-valuemin': '0', 'aria-valuemax': '100', }, - segments.map((s) => s.el) + slotEls ); - let lastOrderSig = segments.map((s) => s.key).join(','); + let lastOrderSig = ''; function syncMeter() { const ctx = getProps().context || {}; const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000)); - const scored = segments.map((seg) => { - const val = seg.getVal(ctx); + const scored = SEGMENT_DEFS.map((def, defaultOrder) => { + const val = def.getVal(ctx); const pct = Math.min(100, (val / limit) * 100); - patchStyleVar(seg.el, '--seg-w', `${pct.toFixed(2)}%`); - return { seg, val }; + return { def, defaultOrder, val, pct }; }); - scored.sort((a, b) => b.val - a.val || a.seg.defaultOrder - b.seg.defaultOrder); - const nextOrderSig = scored.map((x) => x.seg.key).join(','); - if (nextOrderSig !== lastOrderSig) { - lastOrderSig = nextOrderSig; - for (const { seg } of scored) { - trackEl.appendChild(seg.el); - } + scored.sort((a, b) => b.val - a.val || a.defaultOrder - b.defaultOrder); + // 仅关注非零通道的相对顺序变化,决定是否启用 0.05s 先变色再伸缩的衔接延迟 + const activeOrderSig = scored + .filter((x) => x.val > 0) + .map((x) => x.def.key) + .join(','); + const orderChanged = Boolean(lastOrderSig && activeOrderSig && activeOrderSig !== lastOrderSig); + if (activeOrderSig) { + lastOrderSig = activeOrderSig; + } + + patchClasses(trackEl, { 'is-reordering': orderChanged }); + + for (let i = 0; i < slotEls.length; i++) { + const slotEl = slotEls[i]; + const item = scored[i]; + patchAttr(slotEl, 'class', `progress-seg ${item.def.cls}`); + patchStyleVar(slotEl, '--seg-w', `${item.pct.toFixed(2)}%`); } patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0)); @@ -72,7 +81,7 @@ export const ContextSegmentMeter = defineComponent({ return { el: trackEl, - refs: { segments }, + refs: { segments: slotEls }, onPropsChange: syncMeter, }; }, diff --git a/sidecars/panel/src/components/ui/CustomDateTimePicker.js b/sidecars/panel/src/components/ui/CustomDateTimePicker.js index b1792de..5cc1d68 100644 --- a/sidecars/panel/src/components/ui/CustomDateTimePicker.js +++ b/sidecars/panel/src/components/ui/CustomDateTimePicker.js @@ -257,8 +257,8 @@ export const CustomDateTimePicker = defineComponent({ }; if (typeof document !== 'undefined' && document.addEventListener) { - document.addEventListener('click', handleDocClick); - onCleanup(() => document.removeEventListener('click', handleDocClick)); + document.addEventListener('click', handleDocClick, true); + onCleanup(() => document.removeEventListener('click', handleDocClick, true)); } syncDisplay(); diff --git a/sidecars/panel/src/components/ui/CustomScrollbar.js b/sidecars/panel/src/components/ui/CustomScrollbar.js index b6fd305..37e1ef3 100644 --- a/sidecars/panel/src/components/ui/CustomScrollbar.js +++ b/sidecars/panel/src/components/ui/CustomScrollbar.js @@ -141,16 +141,27 @@ export const CustomScrollbar = defineComponent({ } }); + let pendingSync = false; + function scheduleSyncThumb() { + if (typeof queueMicrotask === 'function') { + if (pendingSync) return; + pendingSync = true; + queueMicrotask(() => { + pendingSync = false; + syncThumb(); + }); + } else { + syncThumb(); + } + } + return { el: hostEl, refs: { contentEl, railEl, thumbEl }, - onPropsChange: syncThumb, + onPropsChange: scheduleSyncThumb, methods: { refresh() { - syncThumb(); - if (typeof queueMicrotask === 'function') { - queueMicrotask(syncThumb); - } + scheduleSyncThumb(); }, scrollToRatio(ratio) { const r = Math.max(0, Math.min(1, Number(ratio || 0))); diff --git a/sidecars/panel/src/components/ui/CustomSelect.js b/sidecars/panel/src/components/ui/CustomSelect.js index 8398bcb..87135f5 100644 --- a/sidecars/panel/src/components/ui/CustomSelect.js +++ b/sidecars/panel/src/components/ui/CustomSelect.js @@ -152,9 +152,7 @@ export const CustomSelect = defineComponent({ } const selectedOpt = options.find((o) => o.value === modelValue) || - (modelValue !== '' && modelValue !== null && modelValue !== undefined - ? options[0] - : undefined); + (!modelValue ? options[0] : undefined); patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder); if (isOpen) { renderMenuOptions(); @@ -168,8 +166,8 @@ export const CustomSelect = defineComponent({ }; if (typeof document !== 'undefined' && document.addEventListener) { - document.addEventListener('click', handleDocClick); - onCleanup(() => document.removeEventListener('click', handleDocClick)); + document.addEventListener('click', handleDocClick, true); + onCleanup(() => document.removeEventListener('click', handleDocClick, true)); } syncTriggerAndMenu(); diff --git a/sidecars/panel/src/components/ui/TopLongPillNav.js b/sidecars/panel/src/components/ui/TopLongPillNav.js index d0ad82f..5eb93d7 100644 --- a/sidecars/panel/src/components/ui/TopLongPillNav.js +++ b/sidecars/panel/src/components/ui/TopLongPillNav.js @@ -35,6 +35,16 @@ export const TopLongPillNav = defineComponent({ const { items = [], modelValue } = getProps(); patchStyleVar(navEl, '--pill-count', Math.max(1, items.length)); + const validValues = new Set(items.map((it) => it.value)); + for (const [val, entry] of tabButtons.entries()) { + if (!validValues.has(val)) { + if (entry.btn?.parentNode === navEl) { + navEl.removeChild(entry.btn); + } + tabButtons.delete(val); + } + } + let activeIdx = 0; items.forEach((item, index) => { if (item.value === modelValue) { @@ -57,8 +67,13 @@ export const TopLongPillNav = defineComponent({ if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') { e.preventDefault(); const curItems = getProps().items || []; + if (!curItems.length) return; + const curIndex = Math.max( + 0, + curItems.findIndex((it) => it.value === item.value) + ); const delta = e.key === 'ArrowRight' ? 1 : -1; - const nextIndex = (index + delta + curItems.length) % curItems.length; + const nextIndex = (curIndex + delta + curItems.length) % curItems.length; const target = curItems[nextIndex]; if (target) { selectValue(target.value); diff --git a/sidecars/panel/src/core/component.js b/sidecars/panel/src/core/component.js index b5fa968..77f98a5 100644 --- a/sidecars/panel/src/core/component.js +++ b/sidecars/panel/src/core/component.js @@ -4,13 +4,6 @@ * reactive subscriptions, and lifecycle cleanup. */ -const globalEmitListeners = new Set(); - -export function onComponentEmit(listener) { - globalEmitListeners.add(listener); - return () => globalEmitListeners.delete(listener); -} - export function defineComponent({ name, setup }) { return function createInstance(initialProps = {}) { let props = { ...initialProps }; @@ -41,14 +34,6 @@ export function defineComponent({ name, setup }) { fn(payload); } } - for (const observer of globalEmitListeners) { - observer({ - component: name || 'AnonymousComponent', - event, - payload, - timestamp: Date.now(), - }); - } } function onCleanup(fn) { @@ -88,6 +73,7 @@ export function defineComponent({ name, setup }) { console.error(`[${name}] cleanup error:`, err); } } + eventHandlers.clear(); if (setupResult.el?.parentNode) { setupResult.el.parentNode.removeChild(setupResult.el); } diff --git a/sidecars/panel/src/core/formatters.js b/sidecars/panel/src/core/formatters.js index 51c5f5a..d3f17f8 100644 --- a/sidecars/panel/src/core/formatters.js +++ b/sidecars/panel/src/core/formatters.js @@ -87,10 +87,15 @@ export function formatCompactDateTime(ms) { return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`; } -export function escapeHtml(str) { - return String(str || '') - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"'); +export function formatElapsedSec(seconds) { + const s = Math.max(0, Math.floor(Number(seconds) || 0)); + if (s < 60) return `${s}s`; + const m = Math.floor(s / 60); + const remS = s % 60; + if (m < 60) { + return `${m}m ${String(remS).padStart(2, '0')}s`; + } + const h = Math.floor(m / 60); + const remM = m % 60; + return `${h}h ${remM}m`; } diff --git a/sidecars/panel/src/core/httpClient.js b/sidecars/panel/src/core/httpClient.js index 9b51b55..28d1f3a 100644 --- a/sidecars/panel/src/core/httpClient.js +++ b/sidecars/panel/src/core/httpClient.js @@ -15,14 +15,15 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } let signal; + let requestController = null; if (abortKey && typeof AbortController !== 'undefined') { const prev = activeControllers.get(abortKey); if (prev) { prev.abort(); } - const controller = new AbortController(); - activeControllers.set(abortKey, controller); - signal = controller.signal; + requestController = new AbortController(); + activeControllers.set(abortKey, requestController); + signal = requestController.signal; } const runRequest = async () => { @@ -58,6 +59,9 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' if (dedupKey) { inFlightGets.delete(dedupKey); } + if (abortKey && requestController && activeControllers.get(abortKey) === requestController) { + activeControllers.delete(abortKey); + } }); if (dedupKey) { diff --git a/sidecars/panel/src/icons/svgRegistry.js b/sidecars/panel/src/icons/svgRegistry.js index e657e49..e6bb452 100644 --- a/sidecars/panel/src/icons/svgRegistry.js +++ b/sidecars/panel/src/icons/svgRegistry.js @@ -58,18 +58,6 @@ export const SVG_ICON_DEFS = Object.freeze({ { tag: 'circle', attrs: { cx: '10.5', cy: '8', r: '1.5' } }, { tag: 'circle', attrs: { cx: '6.8', cy: '12.5', r: '1.5' } }, ], - flask: [ - { tag: 'path', attrs: { d: 'M6 2.2h4' } }, - { tag: 'path', attrs: { d: 'M6.8 2.2v3.6L3.2 12.2a1.2 1.2 0 0 0 1.1 1.8h7.4a1.2 1.2 0 0 0 1.1-1.8L9.2 5.8V2.2' } }, - { tag: 'path', attrs: { d: 'M4.6 10.2h6.8' } }, - ], - session: [ - { tag: 'path', attrs: { d: 'M2.5 3.2h11v7.6H6l-3.5 2.5V3.2z' } }, - ], - cpu: [ - { tag: 'rect', attrs: { x: '4', y: '4', width: '8', height: '8', rx: '1' } }, - { tag: 'path', attrs: { d: 'M6.5 1.8v2.2M9.5 1.8v2.2M6.5 12v2.2M9.5 12v2.2M1.8 6.5H4M1.8 9.5H4M12 6.5h2.2M12 9.5h2.2' } }, - ], calendar: [ { tag: 'rect', attrs: { x: '2.2', y: '3.2', width: '11.6', height: '10.6', rx: '1' } }, { tag: 'path', attrs: { d: 'M5.2 1.8v2.4M10.8 1.8v2.4M2.2 6.5h11.6' } }, @@ -84,12 +72,6 @@ export const SVG_ICON_DEFS = Object.freeze({ minus: [ { tag: 'path', attrs: { d: 'M3.5 8h9' } }, ], - swap: [ - { tag: 'path', attrs: { d: 'M3 5.5h10l-2.6-2.6M13 10.5H3l2.6 2.6' } }, - ], - close: [ - { tag: 'path', attrs: { d: 'M4 4l8 8M12 4l-8 8' } }, - ], dot: [ { tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } }, ], diff --git a/sidecars/panel/src/store/telemetryStore.js b/sidecars/panel/src/store/telemetryStore.js index 0323feb..ac1482e 100644 --- a/sidecars/panel/src/store/telemetryStore.js +++ b/sidecars/panel/src/store/telemetryStore.js @@ -62,7 +62,10 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.subagentCount !== nAct?.subagentCount) return false; if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false; if (pAct?.isRunning !== nAct?.isRunning) return false; + if (pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature) return false; if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false; + if (pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature) return false; + if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false; if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false; if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false; if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false; @@ -71,8 +74,14 @@ function isEquivalentTelemetry(prev, next) { if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false; if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false; if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false; + if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false; + if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false; if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false; if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false; + if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false; + if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false; + if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false; + if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false; if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false; if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false; @@ -89,9 +98,12 @@ function isEquivalentTelemetry(prev, next) { pa?.role !== na?.role || pa?.stepCount !== na?.stepCount || pa?.isRunning !== na?.isRunning || + pa?.liveActivity?.signature !== na?.liveActivity?.signature || pa?.latestTokPerSec !== na?.latestTokPerSec || pa?.latestTtftSec !== na?.latestTtftSec || pa?.avgTokPerSec !== na?.avgTokPerSec || + pa?.latestCacheHitPct !== na?.latestCacheHitPct || + pa?.latestSpeedReason !== na?.latestSpeedReason || pa?.latestStepCostUsd !== na?.latestStepCostUsd || pa?.sessionCostUsd !== na?.sessionCostUsd || pa?.activeModelShort !== na?.activeModelShort || @@ -99,6 +111,14 @@ function isEquivalentTelemetry(prev, next) { pa?.context?.messagesTokens !== na?.context?.messagesTokens || pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens || pa?.context?.assistantTokens !== na?.context?.assistantTokens || + pa?.context?.userInputTokens !== na?.context?.userInputTokens || + pa?.context?.subagentTokens !== na?.context?.subagentTokens || + pa?.context?.checkpointTokens !== na?.context?.checkpointTokens || + pa?.context?.systemToolsTokens !== na?.context?.systemToolsTokens || + pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens || + pa?.context?.skillsTokens !== na?.context?.skillsTokens || + pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens || + pa?.context?.userRulesTokens !== na?.context?.userRulesTokens || pLastStep?.tokPerSec !== nLastStep?.tokPerSec || pLastStep?.ttftSec !== nLastStep?.ttftSec || pLastStep?.outputTokens !== nLastStep?.outputTokens || @@ -109,7 +129,7 @@ function isEquivalentTelemetry(prev, next) { } } - // 4. 比对 6 通道上下文窗口构成(总 Token 与消息/系统工具/MCP/Skill/系统提示词/用户规则)及近期步骤明细 + // 4. 比对 10 通道上下文窗口构成及近期步骤明细 const pCtx = pAct?.context; const nCtx = nAct?.context; if (pCtx?.totalTokens !== nCtx?.totalTokens) return false; @@ -127,9 +147,21 @@ function isEquivalentTelemetry(prev, next) { if ((pAct?.recentSteps?.length || 0) !== (nAct?.recentSteps?.length || 0)) return false; for (let i = 0; i < (pAct?.recentSteps?.length || 0); i++) { const before = pAct.recentSteps[i], after = nAct.recentSteps[i]; - if (before.modelKey !== after.modelKey || before.modelShort !== after.modelShort || - before.modelUpstream !== after.modelUpstream || before.responseModel !== after.responseModel || - before.modelSource !== after.modelSource || before.costUsd !== after.costUsd) return false; + if ( + before.modelKey !== after.modelKey || + before.modelShort !== after.modelShort || + before.modelUpstream !== after.modelUpstream || + before.responseModel !== after.responseModel || + before.modelSource !== after.modelSource || + before.costUsd !== after.costUsd || + before.tokPerSec !== after.tokPerSec || + before.ttftSec !== after.ttftSec || + before.outputTokens !== after.outputTokens || + before.inputTokens !== after.inputTokens || + before.cacheReadTokens !== after.cacheReadTokens + ) { + return false; + } } // 5. 比对消费统计所选时间区间、当前会话累计消费与账号全局累计消费 @@ -153,12 +185,30 @@ function isEquivalentTelemetry(prev, next) { if (pAcct?.costUsd !== nAcct?.costUsd) return false; if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false; - // 6. 比对历史趋势时间分桶序列 + // 6. 比对历史趋势时间分桶序列与年度分月序列 const pTrend = prev.consumption?.trendSeries || []; const nTrend = next.consumption?.trendSeries || []; if (pTrend.length !== nTrend.length) return false; for (let i = 0; i < pTrend.length; i++) { - if (pTrend[i]?.tokens !== nTrend[i]?.tokens || pTrend[i]?.label !== nTrend[i]?.label) { + if ( + pTrend[i]?.tokens !== nTrend[i]?.tokens || + pTrend[i]?.calls !== nTrend[i]?.calls || + pTrend[i]?.label !== nTrend[i]?.label || + pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel + ) { + return false; + } + } + if (prev.consumption?.monthlyYear !== next.consumption?.monthlyYear) return false; + const pMonthly = prev.consumption?.monthlySeries || []; + const nMonthly = next.consumption?.monthlySeries || []; + if (pMonthly.length !== nMonthly.length) return false; + for (let i = 0; i < pMonthly.length; i++) { + if ( + pMonthly[i]?.totalTokens !== nMonthly[i]?.totalTokens || + pMonthly[i]?.costUsd !== nMonthly[i]?.costUsd || + pMonthly[i]?.calls !== nMonthly[i]?.calls + ) { return false; } } @@ -197,7 +247,18 @@ function isEquivalentTelemetry(prev, next) { } // 8. 比对账号订阅档位与动态多配额池(活跃池、周汇总及各配额池的 5h/周限额进度与重置时间) - if (prev.account?.tierName !== next.account?.tierName || prev.account?.planName !== next.account?.planName) { + if ( + prev.account?.tierName !== next.account?.tierName || + prev.account?.planName !== next.account?.planName || + prev.account?.aiCredits !== next.account?.aiCredits + ) { + return false; + } + + if ( + prev.quotas?.meta?.refreshFailed !== next.quotas?.meta?.refreshFailed || + prev.quotas?.meta?.isStale !== next.quotas?.meta?.isStale + ) { return false; } @@ -209,6 +270,11 @@ function isEquivalentTelemetry(prev, next) { if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false; if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false; if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false; + if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false; + if (prev.quotas?.weekly?.costUsd !== next.quotas?.weekly?.costUsd) return false; + if (prev.quotas?.weekly?.calls !== next.quotas?.weekly?.calls) return false; + if (prev.quotas?.weekly?.unpricedCalls !== next.quotas?.weekly?.unpricedCalls) return false; + if (prev.quotas?.weekly?.resetTime !== next.quotas?.weekly?.resetTime) return false; const pPools = prev.quotas?.pools || []; const nPools = next.quotas?.pools || []; @@ -235,6 +301,7 @@ function isEquivalentTelemetry(prev, next) { if ( pConvs[i]?.cascadeId !== nConvs[i]?.cascadeId || pConvs[i]?.title !== nConvs[i]?.title || + pConvs[i]?.status !== nConvs[i]?.status || pConvs[i]?.stepCount !== nConvs[i]?.stepCount || pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount || pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount @@ -243,6 +310,39 @@ function isEquivalentTelemetry(prev, next) { } } + const pRunning = prev.runningConversations || []; + const nRunning = next.runningConversations || []; + if (pRunning.length !== nRunning.length) return false; + for (let i = 0; i < pRunning.length; i++) { + const pr = pRunning[i]; + const nr = nRunning[i]; + if ( + pr?.cascadeId !== nr?.cascadeId || + pr?.title !== nr?.title || + pr?.isCurrentSelected !== nr?.isCurrentSelected || + pr?.isMainRunning !== nr?.isMainRunning || + pr?.subagentCount !== nr?.subagentCount || + pr?.runningSubagentCount !== nr?.runningSubagentCount || + pr?.mainActivity?.signature !== nr?.mainActivity?.signature + ) { + return false; + } + const pSubs = pr?.subagents || []; + const nSubs = nr?.subagents || []; + if (pSubs.length !== nSubs.length) return false; + for (let j = 0; j < pSubs.length; j++) { + if ( + pSubs[j]?.cascadeId !== nSubs[j]?.cascadeId || + pSubs[j]?.role !== nSubs[j]?.role || + pSubs[j]?.isRunning !== nSubs[j]?.isRunning || + pSubs[j]?.stepCount !== nSubs[j]?.stepCount || + pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature + ) { + return false; + } + } + } + return true; } diff --git a/sidecars/panel/src/store/uiStore.js b/sidecars/panel/src/store/uiStore.js index 7bc8b06..e520508 100644 --- a/sidecars/panel/src/store/uiStore.js +++ b/sidecars/panel/src/store/uiStore.js @@ -16,6 +16,4 @@ export const uiStore = createReactiveStore({ stepsSubTab: 'steps', // 'steps' | 'models' selectedAgentScope: 'all', // 'all' | 'main' | ctxInspectorAgentId: 'auto', // 'auto' | 'main' | - showAllPools: true, - ctxBreakdownOpen: true, }); diff --git a/sidecars/panel/src/styles/controls.css b/sidecars/panel/src/styles/controls.css index 2c80f3e..4507135 100644 --- a/sidecars/panel/src/styles/controls.css +++ b/sidecars/panel/src/styles/controls.css @@ -29,93 +29,11 @@ border-radius: var(--radius-sm); } -.agent-scope-bar { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-2); - padding: 4px var(--space-3); - background: var(--surface-panel); - border: 1px solid var(--border-hairline); - border-radius: var(--radius-sm); -} - -.agent-scope-left { - display: flex; - align-items: center; - gap: 4px; - flex: 1; - min-width: 0; -} - -.scope-pill-btn { - display: inline-flex; - align-items: center; - gap: 3px; - height: 22px; - padding: 0 7px; - border: 1px solid transparent; - background: transparent; - color: var(--text-secondary); - font-size: 11.5px; - border-radius: var(--radius-xs); - cursor: pointer; - white-space: nowrap; - flex-shrink: 0; - transition: - background-color var(--dur-instant) var(--ease-fast), - color var(--dur-instant) var(--ease-fast), - border-color var(--dur-instant) var(--ease-fast); -} - -.scope-pill-btn:hover { - background: var(--surface-hover); - color: var(--text-primary); -} - -.scope-pill-btn.is-active { - background: var(--accent-primary-soft); - color: var(--accent-primary); - border-color: var(--accent-primary-border); - font-weight: 600; -} - -.scope-subagent-select { - flex: 1 1 115px; - min-width: 105px; -} - -.scope-subagent-select .select-trigger { - height: 22px; - padding: 0 6px; - font-size: 11.5px; - border: 1px solid var(--border-hairline); - background: var(--surface-subtle); -} - -.scope-subagent-select.is-active-sub .select-trigger { - background: var(--accent-primary-soft); - color: var(--accent-primary); - border-color: var(--accent-primary-border); - font-weight: 600; -} - -.scope-subagent-select .select-menu, .steps-inline-scope-select .select-menu { left: auto; right: 0; } -.agent-scope-right { - display: inline-flex; - align-items: center; - gap: 5px; - font-size: 11px; - color: var(--text-secondary); - white-space: nowrap; - flex-shrink: 0; -} - .session-left { display: flex; align-items: center; @@ -193,12 +111,6 @@ transform: scale(0.95); } -.icon-btn.is-active { - background: var(--accent-primary-soft); - color: var(--accent-primary); - border-color: var(--accent-primary-border); -} - /* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */ .long-pill-nav { position: relative; @@ -344,7 +256,7 @@ box-shadow: var(--shadow-popover); padding: 4px; z-index: 60; - animation: popover-in var(--dur-fast) var(--ease-fast); + animation: anim-popover-in var(--dur-fast) var(--ease-fast); } .select-option { @@ -474,7 +386,7 @@ display: flex; flex-direction: column; gap: var(--space-2); - animation: popover-in var(--dur-fast) var(--ease-fast); + animation: anim-popover-in var(--dur-fast) var(--ease-fast); } .dt-nav { diff --git a/sidecars/panel/src/styles/tokens.css b/sidecars/panel/src/styles/tokens.css index 2e48aaf..099fe8e 100644 --- a/sidecars/panel/src/styles/tokens.css +++ b/sidecars/panel/src/styles/tokens.css @@ -68,8 +68,8 @@ --ctx-output: hsl(190 80% 38%); /* Elevation & Shadows */ - --shadow-popover: 0 6px 20px color-mix(in srgb, var(--text-primary) 14%, transparent); - --shadow-glider: 0 1px 2px color-mix(in srgb, var(--text-primary) 10%, transparent); + --shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22); + --shadow-glider: 0 1px 2px rgb(0 0 0 / 0.14); /* Fast Hardware-Accelerated Motion Tokens */ --ease-fast: cubic-bezier(0.22, 1, 0.36, 1); diff --git a/sidecars/panel/src/styles/views-consumption.css b/sidecars/panel/src/styles/views-consumption.css index 5c91954..f5187a1 100644 --- a/sidecars/panel/src/styles/views-consumption.css +++ b/sidecars/panel/src/styles/views-consumption.css @@ -73,8 +73,7 @@ padding-right: 0; } -.cons-col.is-bordered-col, -.cons-col.is-right-col { +.cons-col.is-bordered-col { border-left: 1px solid var(--border-hairline); } @@ -184,16 +183,25 @@ height: 5px; } -/* --- 4. 历史趋势 SVG 平滑曲线图 (Historical Trend SVG Chart) --- */ +/* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */ .trend-chart-wrap { position: relative; width: 100%; - padding-top: 8px; + display: flex; + flex-direction: column; + gap: 2px; +} + +.trend-plot-stage { + position: relative; + width: 100%; + padding-top: 6px; + cursor: crosshair; } .trend-svg { width: 100%; - height: 112px; + height: 118px; display: block; overflow: visible; } @@ -210,12 +218,33 @@ stroke-linecap: round; } +.trend-node-dot { + fill: var(--surface-panel); + stroke: var(--ctx-cached); + stroke-width: 1.4; +} + .trend-peak-dot { fill: var(--ctx-cached); stroke: var(--surface-panel); stroke-width: 1.5; } +.trend-hover-line { + stroke: var(--accent-primary); + stroke-width: 1; + stroke-dasharray: 2 2; + opacity: 0.75; + pointer-events: none; +} + +.trend-hover-dot { + fill: var(--accent-primary); + stroke: var(--surface-panel); + stroke-width: 1.8; + pointer-events: none; +} + .trend-peak-pill { position: absolute; top: 2px; @@ -226,31 +255,113 @@ padding: 1px 6px; color: var(--text-primary); background: color-mix(in srgb, var(--ctx-cached) 16%, var(--surface-panel)); - border: none; + border: 1px solid color-mix(in srgb, var(--ctx-cached) 30%, var(--border-hairline)); border-radius: var(--radius-xs); pointer-events: none; white-space: nowrap; + z-index: 2; } -.trend-anchors { - display: grid; - grid-template-columns: repeat(3, 1fr); - padding-top: 2px; - font-size: 11px; -} - -.trend-anchor-col { +.trend-tooltip { + position: absolute; + top: 0; + left: var(--tip-x, 50%); + transform: translateX(var(--tip-shift, -50%)); + min-width: 148px; + max-width: 240px; + padding: 5px 8px; + background: var(--surface-panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + box-shadow: none; + pointer-events: none; + z-index: 15; display: flex; flex-direction: column; - gap: 1px; + gap: 2px; } -.trend-anchor-col.is-center { +.trend-tip-head { + display: flex; align-items: center; + justify-content: space-between; + gap: 8px; + font-size: 10.5px; + color: var(--text-secondary); } -.trend-anchor-col.is-end { - align-items: flex-end; +.trend-tip-time { + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; +} + +.trend-tip-calls { + font-size: 10px; + color: var(--text-muted); + white-space: nowrap; +} + +.trend-tip-main { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.trend-tip-tokens { + font-size: 12px; + font-weight: 700; + color: var(--accent-primary); +} + +.trend-tip-cost { + font-size: 11px; + font-weight: 600; + color: var(--text-primary); +} + +.trend-tip-sub { + font-size: 10px; + color: var(--text-secondary); + white-space: nowrap; + border-top: 1px solid var(--border-hairline); + padding-top: 2px; + margin-top: 1px; +} + +.trend-x-axis { + position: relative; + width: 100%; + height: 18px; + user-select: none; +} + +.trend-x-tick { + position: absolute; + top: 0; + left: var(--tick-x, 0%); + transform: translateX(-50%); + font-size: 10px; + color: var(--text-muted); + white-space: nowrap; + line-height: 16px; + cursor: pointer; + transition: color var(--dur-instant) var(--ease-fast); +} + +.trend-x-tick.is-start { + transform: translateX(0); +} + +.trend-x-tick.is-end { + transform: translateX(-100%); +} + +.trend-x-tick:hover, +.trend-x-tick.is-hovered { + color: var(--accent-primary); + font-weight: 600; } /* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */ diff --git a/sidecars/panel/src/styles/views-overview.css b/sidecars/panel/src/styles/views-overview.css index 7970ae7..36933a4 100644 --- a/sidecars/panel/src/styles/views-overview.css +++ b/sidecars/panel/src/styles/views-overview.css @@ -53,7 +53,239 @@ white-space: nowrap; } -/* --- 2. 4 格实时测速指标矩阵 (4-Cell Telemetry Matrix) --- */ +/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */ +.live-activity-list { + display: flex; + flex-direction: column; + gap: 6px; + flex-shrink: 0; + min-width: 0; +} + +.live-activity-list[hidden] { + display: none !important; +} + +.live-task-card { + display: flex; + flex-direction: column; + gap: 5px; + padding: 7px 10px; + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--accent-primary) 5%, var(--surface-panel)); + min-width: 0; +} + +.live-task-card.is-waiting { + border-color: color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel)); +} + +.live-task-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + min-width: 0; +} + +.live-task-title-wrap { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + flex: 1; +} + +.live-task-title { + font-size: 11.5px; + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + cursor: pointer; +} + +.live-task-title:hover { + color: var(--accent-primary); +} + +.live-task-header-right { + display: inline-flex; + align-items: center; + gap: 6px; + flex-shrink: 0; +} + +.live-sub-toggle { + display: inline-flex; + align-items: center; + gap: 3px; + height: 18px; + padding: 0 6px; + font-size: 10.5px; + font-weight: 600; + color: var(--text-secondary); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + cursor: pointer; + white-space: nowrap; + transition: + border-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast), + background-color var(--dur-instant) var(--ease-fast); +} + +.live-sub-toggle:hover { + border-color: var(--border-strong); + color: var(--text-primary); +} + +.live-sub-toggle.is-expanded { + color: var(--accent-primary); + border-color: var(--accent-primary-border); + background: var(--accent-primary-soft); +} + +.live-sub-toggle[hidden] { + display: none !important; +} + +.live-task-main-row { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + padding-left: 1px; +} + +.live-activity-dot { + color: var(--accent-primary); + display: inline-flex; + align-items: center; + flex-shrink: 0; +} + +.live-task-card.is-waiting .live-activity-dot { + color: var(--metric-warn); +} + +.live-activity-phase { + font-size: 11px; + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + flex-shrink: 0; +} + +.live-task-card.is-waiting .live-activity-phase { + color: var(--metric-warn); +} + +.live-activity-progress { + font-size: 10px; + font-weight: 600; + color: var(--accent-primary); + background: var(--accent-primary-soft); + padding: 0 4px; + border-radius: var(--radius-xs); + white-space: nowrap; + flex-shrink: 0; +} + +.live-activity-sep { + font-size: 11px; + color: var(--text-muted); + flex-shrink: 0; +} + +.live-activity-detail { + font-size: 11px; + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + flex: 1; +} + +.live-activity-elapsed { + font-size: 11px; + font-weight: 600; + color: var(--accent-primary); + white-space: nowrap; + flex-shrink: 0; +} + +.live-task-card.is-waiting .live-activity-elapsed { + color: var(--metric-warn); +} + +.live-sub-list { + display: flex; + flex-direction: column; + gap: 4px; + padding-top: 5px; + margin-top: 1px; + border-top: 1px dashed var(--border-hairline); + min-width: 0; +} + +.live-sub-list[hidden] { + display: none !important; +} + +.live-sub-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + min-width: 0; + font-size: 10.5px; +} + +.live-sub-row.is-done { + opacity: 0.72; +} + +.live-sub-left { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + flex: 1; +} + +.live-sub-role { + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 110px; + flex-shrink: 0; +} + +.live-sub-summary { + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + flex: 1; +} + +.live-sub-elapsed { + font-size: 10.5px; + color: var(--text-secondary); + white-space: nowrap; + flex-shrink: 0; +} + .telemetry-matrix { display: grid; grid-template-columns: repeat(4, 1fr); @@ -120,53 +352,58 @@ .progress-seg { height: 100%; width: var(--seg-w, 0%); - transition: width var(--dur-normal) var(--ease-fast); + transition: + background-color 0.05s ease, + width var(--dur-normal) var(--ease-fast); } -.progress-seg.seg-messages { - background: var(--ctx-messages); +.progress-track.is-reordering .progress-seg { + transition: + background-color 0.05s ease, + width var(--dur-normal) var(--ease-fast) 0.05s; } + .progress-seg.seg-assistant { - background: var(--ctx-assistant); + background-color: var(--ctx-assistant); } .progress-seg.seg-tool-results { - background: var(--ctx-tool-results); + background-color: var(--ctx-tool-results); } .progress-seg.seg-user-input { - background: var(--ctx-user-input); + background-color: var(--ctx-user-input); } .progress-seg.seg-subagent-msg { - background: var(--ctx-subagent-msg); + background-color: var(--ctx-subagent-msg); } .progress-seg.seg-checkpoint { - background: var(--ctx-checkpoint); + background-color: var(--ctx-checkpoint); } .progress-seg.seg-system-tools { - background: var(--ctx-system-tools); + background-color: var(--ctx-system-tools); } .progress-seg.seg-mcp-tools { - background: var(--ctx-mcp-tools); + background-color: var(--ctx-mcp-tools); } .progress-seg.seg-skills { - background: var(--ctx-skills); + background-color: var(--ctx-skills); } .progress-seg.seg-system-prompt { - background: var(--ctx-system-prompt); + background-color: var(--ctx-system-prompt); } .progress-seg.seg-user-rules { - background: var(--ctx-user-rules); + background-color: var(--ctx-user-rules); } .progress-seg.seg-cached { - background: var(--ctx-cached); + background-color: var(--ctx-cached); } .progress-seg.seg-input { - background: var(--ctx-input); + background-color: var(--ctx-input); } .progress-seg.seg-thinking { - background: var(--ctx-thinking); + background-color: var(--ctx-thinking); } .progress-seg.seg-output { - background: var(--ctx-output); + background-color: var(--ctx-output); } .progress-fill { @@ -184,7 +421,7 @@ background: var(--metric-danger); } -/* --- 4. 上下文双列图例网格 (Context 6-Channel Legend Grid) --- */ +/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; grid-template-columns: repeat(2, 1fr); @@ -216,7 +453,6 @@ display: inline-block; } -.swatch.seg-messages { background: var(--ctx-messages); } .swatch.seg-assistant { background: var(--ctx-assistant); } .swatch.seg-tool-results { background: var(--ctx-tool-results); } .swatch.seg-user-input { background: var(--ctx-user-input); } diff --git a/sidecars/panel/src/views/ConsumptionView.js b/sidecars/panel/src/views/ConsumptionView.js index c607836..7447121 100644 --- a/sidecars/panel/src/views/ConsumptionView.js +++ b/sidecars/panel/src/views/ConsumptionView.js @@ -79,7 +79,20 @@ export const ConsumptionView = defineComponent({ className: 'btn-primary', style: 'height: 26px; padding: 0 10px;', onClick: () => { - telemetryStore.setState({ selectedTimeRange: 'custom' }); + const st = telemetryStore.getState(); + const sMs = Number(st.customStartMs || 0); + const eMs = Number(st.customEndMs || 0); + if (sMs > 0 && eMs > 0 && sMs > eMs) { + startPicker.setValue(eMs); + endPicker.setValue(sMs); + telemetryStore.setState({ + selectedTimeRange: 'custom', + customStartMs: eMs, + customEndMs: sMs, + }); + } else { + telemetryStore.setState({ selectedTimeRange: 'custom' }); + } fetchTelemetry({ force: true }); }, }, @@ -176,27 +189,24 @@ export const ConsumptionView = defineComponent({ overviewSegBar.el, ]); - // --- Section 2: 历史趋势 (SVG 三次贝塞尔平滑曲线图 + 首/中/末三时间锚点) --- + // --- Section 2: 历史趋势 (交互式 SVG 平滑曲线图 + 悬停精确日期/小时浮层 + 多刻度时间轴) --- const trendRangeBadge = h('span', { className: 'cons-badge', text: '全部时间' }); + const trendGranularityHint = h('span', { + className: 'text-muted text-mono', + style: 'font-size: 10.5px;', + text: '按小时 · 悬停查看明细', + }); const trendChart = createTrendAreaChart(); - const anchorStartTime = h('span', { className: 'text-muted text-mono', text: '00:00' }); - const anchorStartVal = h('strong', { className: 'text-mono', text: '0' }); - const anchorMidTime = h('span', { className: 'text-muted text-mono', text: '06:00' }); - const anchorMidVal = h('strong', { className: 'text-mono', text: '0' }); - const anchorEndTime = h('span', { className: 'text-muted text-mono', text: '12:00' }); - const anchorEndVal = h('strong', { className: 'text-mono', text: '0' }); const trendPanel = h('section', { className: 'panel' }, [ h('div', { className: 'panel-header' }, [ - h('span', { className: 'panel-title', text: '用量趋势' }), - trendRangeBadge, + h('span', { className: 'panel-title' }, [ + h('span', { text: '用量趋势' }), + trendRangeBadge, + ]), + trendGranularityHint, ]), trendChart.el, - h('div', { className: 'trend-anchors' }, [ - h('div', { className: 'trend-anchor-col' }, [anchorStartTime, anchorStartVal]), - h('div', { className: 'trend-anchor-col is-center' }, [anchorMidTime, anchorMidVal]), - h('div', { className: 'trend-anchor-col is-end' }, [anchorEndTime, anchorEndVal]), - ]), ]); // --- Section 3: 模型排行列表 --- @@ -458,21 +468,17 @@ export const ConsumptionView = defineComponent({ thinkingTokens, }); - // 2. 同步历史趋势 SVG 面积图与首/中/末三时间锚点 + // 2. 同步历史趋势交互式 SVG 面积图与粒度提示 patchText(trendRangeBadge, preset?.label || rangeInfo.label || '全部时间'); const trendSeries = cons.trendSeries || []; + const isHourlyTrend = + trendSeries[0]?.granularity === 'hour' || + (trendSeries[0]?.label || '').includes(':'); + patchText( + trendGranularityHint, + `${isHourlyTrend ? '按小时' : '按日'} (${trendSeries.length || 0}点) · 悬停查看` + ); trendChart.update(trendSeries); - if (trendSeries.length > 0) { - const first = trendSeries[0]; - const mid = trendSeries[Math.floor(trendSeries.length / 2)]; - const last = trendSeries[trendSeries.length - 1]; - patchText(anchorStartTime, first.label); - patchText(anchorStartVal, formatTokensPrecise(first.tokens)); - patchText(anchorMidTime, mid.label); - patchText(anchorMidVal, formatTokensPrecise(mid.tokens)); - patchText(anchorEndTime, last.label); - patchText(anchorEndVal, formatTokensPrecise(last.tokens)); - } // 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账) const models = (slice.modelBreakdown || []) diff --git a/sidecars/panel/src/views/LiveOverviewView.js b/sidecars/panel/src/views/LiveOverviewView.js index 59a7364..c534aa8 100644 --- a/sidecars/panel/src/views/LiveOverviewView.js +++ b/sidecars/panel/src/views/LiveOverviewView.js @@ -19,6 +19,7 @@ import { } from '../core/domPatch.js'; import { formatCountdown, + formatElapsedSec, formatMetric, formatTokens, formatUsd, @@ -27,6 +28,7 @@ import { } from '../core/formatters.js'; import { createSvgIcon } from '../icons/SvgIcon.js'; import { + fetchTelemetry, formatAgentLabel, getAgentBadgeClass, resolveScopedConversation, @@ -53,6 +55,145 @@ function estPillWidth(text) { export const LiveOverviewView = defineComponent({ name: 'LiveOverviewView', setup({ onCleanup }) { + // --- 0. 可用额度下方的多任务实时运行卡片列表 (展示所有正在运行的主进程 + 默认主代理缩略 + 可折叠子代理列表) --- + const liveActivityBar = h('div', { + className: 'live-activity-list', + hidden: true, + 'aria-live': 'polite', + }); + + const expandedTaskConvIds = new Set(); + const activityTimersMap = new Map(); + let liveTickTimer = null; + + function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) { + const now = Date.now(); + const prev = activityTimersMap.get(timerKey); + let startMs = prev?.startMs || 0; + if (!prev || prev.sig !== sig) { + const validRaw = Number(rawStartMs || 0); + startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now; + } else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) { + startMs = Number(rawStartMs); + } + activityTimersMap.set(timerKey, { sig, startMs, el: targetEl }); + const elapsedSec = Math.max(0, (now - startMs) / 1000); + patchText(targetEl, formatElapsedSec(elapsedSec)); + } + + function updateLiveElapsedDisplay() { + const now = Date.now(); + for (const entry of activityTimersMap.values()) { + if (!entry?.el) continue; + const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0; + patchText(entry.el, formatElapsedSec(elapsedSec)); + } + } + + function stopLiveTicker() { + if (liveTickTimer) { + clearInterval(liveTickTimer); + liveTickTimer = null; + } + activityTimersMap.clear(); + } + + function ensureLiveTicker() { + if (!liveTickTimer) { + liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000); + } + } + + function createLiveTaskCard() { + const dotIcon = createSvgIcon('dot', { size: 9 }); + patchClasses(dotIcon, { 'is-pulsing': true }); + const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]); + const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' }); + const subToggleBtn = h('button', { + type: 'button', + className: 'live-sub-toggle', + hidden: true, + text: '子代理 (0) ▸', + }); + const elapsedEl = h('span', { + className: 'live-activity-elapsed text-mono', + text: '0s', + }); + + const headerEl = h('div', { className: 'live-task-header' }, [ + h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]), + h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]), + ]); + + const mainBadge = h('span', { className: 'agent-badge badge-main', text: '主' }); + const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' }); + const mainProgress = h('span', { + className: 'live-activity-progress text-mono', + hidden: true, + text: '', + }); + const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' }); + const mainDetail = h('span', { + className: 'live-activity-detail', + hidden: true, + text: '', + }); + + const mainRowEl = h('div', { className: 'live-task-main-row' }, [ + mainBadge, + mainPhase, + mainProgress, + mainSep, + mainDetail, + ]); + + const subListEl = h('div', { className: 'live-sub-list', hidden: true }); + const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]); + + return { + el: cardEl, + refs: { + cardEl, + dotIcon, + titleEl, + subToggleBtn, + elapsedEl, + mainPhase, + mainProgress, + mainSep, + mainDetail, + subListEl, + }, + }; + } + + function createLiveSubRow() { + const subBadge = h('span', { className: 'agent-badge badge-sub-1', text: '子1' }); + const subRole = h('span', { className: 'live-sub-role', text: '子代理' }); + 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, + }, + }; + } + // --- 1. 4 格实时测速矩阵 (实时吞吐 / 首Token / 会话均速 / 本步消费) --- const tpsVal = h('strong', { className: 'cell-value accent-speed', text: '—' }); const tpsSub = h('span', { className: 'cell-sub', text: '模型未知' }); @@ -277,7 +418,7 @@ export const LiveOverviewView = defineComponent({ { style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;', }, - [matrixEl, ctxPanel, quotaPanel] + [matrixEl, ctxPanel, quotaPanel, liveActivityBar] ); const viewScrollbar = CustomScrollbar({ contentEl: overviewInner, @@ -383,24 +524,246 @@ export const LiveOverviewView = defineComponent({ const uiSt = uiStore.getState(); const { hasSubagents, - effectiveScope, effectiveCtxScope, agents, aggregated, scopedConv, ctxAgent, - } = resolveScopedConversation(data, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId); + } = resolveScopedConversation(data, 'all', uiSt.ctxInspectorAgentId); const active = scopedConv || data.activeConversation || {}; const ctx = ctxAgent?.context || active.context || {}; const quotas = data.quotas || {}; - // 1. 更新 4 格实时测速矩阵(根据当前代理作用域动态展示全部汇总或单代理指标) + // 0. 更新多任务实时运行列表(展示所有正在运行的主进程 + 默认主代理缩略 + 默认收起的子代理列表) + 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 || '当前会话', + 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: s.badgeText || `子${idx + 1}`, + shortLabel: s.shortLabel || `子代理 #${idx + 1}`, + role: s.role || `子代理 #${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 ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: s.lastModifiedMs || 0, + signature: `${s.agentId}:${s.stepCount || 0}`, + }, + })), + }, + ] + : []; + + const hasRunningTasks = rawRunningList.length > 0; + patchAttr(liveActivityBar, 'hidden', !hasRunningTasks); + if (!hasRunningTasks) { + stopLiveTicker(); + } else { + // 先基于完整运行列表收集所有有效计时器 Key(防止 patchKeyedList 在 sig 未变化跳过 updateRow 时误删计时器) + const activeTimerKeys = new Set(); + for (const item of rawRunningList) { + activeTimerKeys.add(`main:${item.cascadeId}`); + for (const sub of item.subagents || []) { + if (sub?.isRunning) { + activeTimerKeys.add(`sub:${sub.cascadeId}`); + } + } + } + // 清理已结束会话的展开状态 + const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId)); + for (const id of [...expandedTaskConvIds]) { + if (!runningIdsSet.has(id)) { + expandedTaskConvIds.delete(id); + } + } + + patchKeyedList(liveActivityBar, rawRunningList, { + keyFn: (item) => item.cascadeId, + sigFn: (item) => { + const isExp = expandedTaskConvIds.has(item.cascadeId); + const subSig = (item.subagents || []) + .map( + (s) => + `${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}` + ) + .join('|'); + return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${subSig}`; + }, + createRow: createLiveTaskCard, + updateRow: (refs, item) => { + const act = item.mainActivity || { + phase: 'thinking', + label: '推理中', + detail: '', + stepProgress: '', + startedAtMs: item.lastModifiedMs || 0, + signature: `fallback:${item.lastModifiedMs || 0}`, + }; + + const isWaiting = act.phase === 'waiting'; + patchClasses(refs.cardEl, { 'is-waiting': isWaiting }); + patchClasses(refs.dotIcon, { 'is-pulsing': true }); + + const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话'; + patchText(refs.titleEl, convTitle); + patchAttr(refs.titleEl, 'title', `点击切换查看会话:${convTitle}`); + refs.titleEl.onclick = () => { + if (item.cascadeId && item.cascadeId !== 'current') { + uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }); + telemetryStore.setState({ selectedConversationId: item.cascadeId }); + fetchTelemetry({ force: false }); + } + }; + + const subCount = Number(item.subagentCount || item.subagents?.length || 0); + const runSubCount = Number(item.runningSubagentCount || 0); + const isExpanded = expandedTaskConvIds.has(item.cascadeId); + patchAttr(refs.subToggleBtn, 'hidden', subCount === 0); + if (subCount > 0) { + const arrow = isExpanded ? '▾' : '▸'; + const toggleText = + runSubCount > 0 + ? `子代理 ${runSubCount}/${subCount} ${arrow}` + : `子代理 (${subCount}) ${arrow}`; + patchText(refs.subToggleBtn, toggleText); + patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded }); + patchAttr( + refs.subToggleBtn, + 'title', + isExpanded ? '点击收起子代理列表' : '点击展开查看子代理缩略状态' + ); + refs.subToggleBtn.onclick = (e) => { + e.stopPropagation(); + if (expandedTaskConvIds.has(item.cascadeId)) { + expandedTaskConvIds.delete(item.cascadeId); + } else { + expandedTaskConvIds.add(item.cascadeId); + } + renderData(latestData); + }; + } + + const mainTimerKey = `main:${item.cascadeId}`; + activeTimerKeys.add(mainTimerKey); + bindLiveElapsedTimer( + mainTimerKey, + `${item.cascadeId}:${act.signature || act.label}`, + act.startedAtMs, + refs.elapsedEl + ); + + patchText(refs.mainPhase, act.label || '推理中'); + 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 fullTooltip = `[${convTitle}] 主代理 · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`; + patchAttr(refs.cardEl, 'title', fullTooltip); + + const showSubs = subCount > 0 && isExpanded; + patchAttr(refs.subListEl, 'hidden', !showSubs); + if (showSubs) { + const subItems = item.subagents || []; + patchKeyedList(refs.subListEl, subItems, { + keyFn: (sub) => sub.cascadeId, + sigFn: (sub) => + `${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? activityTimersMap.has(`sub:${sub.cascadeId}`) : true}`, + createRow: createLiveSubRow, + updateRow: (subRefs, sub) => { + const subAct = sub.liveActivity || { + phase: sub.isRunning ? 'thinking' : 'done', + label: sub.isRunning ? '推理中' : '已完成', + detail: '', + stepProgress: '', + startedAtMs: sub.lastModifiedMs || 0, + }; + patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning }); + + const badgeCls = getAgentBadgeClass(sub.index || 1, false); + patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`); + patchText(subRefs.subBadge, sub.badgeText || `子${sub.index || 1}`); + + const roleText = sub.role || sub.shortLabel || '子代理'; + patchText(subRefs.subRole, roleText); + + const rawSubLabel = sub.isRunning ? subAct.label || '' : subAct.label || '已完成'; + const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : ''; + const summaryStr = [ + `${rawSubLabel}${subProg}`.trim(), + subAct.detail || '', + ] + .filter(Boolean) + .join(' '); + patchAttr(subRefs.subSummary, 'hidden', !summaryStr); + patchText(subRefs.subSummary, summaryStr); + + patchAttr( + subRefs.rowEl, + 'title', + `[${sub.badgeText || '子'}] ${roleText}${summaryStr ? ` ${summaryStr}` : ''}` + ); + + if (sub.isRunning) { + const subTimerKey = `sub:${sub.cascadeId}`; + activeTimerKeys.add(subTimerKey); + bindLiveElapsedTimer( + subTimerKey, + `${sub.cascadeId}:${subAct.signature || subAct.label}`, + subAct.startedAtMs, + subRefs.subElapsed + ); + } else { + patchText(subRefs.subElapsed, `${sub.stepCount || 0}步`); + } + }, + }); + } + }, + }); + + for (const key of [...activityTimersMap.keys()]) { + if (!activeTimerKeys.has(key)) { + activityTimersMap.delete(key); + } + } + updateLiveElapsedDisplay(); + ensureLiveTicker(); + } + + // 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标) patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) }); patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s')); const reason = speedReasonText(active.latestSpeedReason); const modelAndAgent = - hasSubagents && effectiveScope === 'all' && active.activeAgentBadge + hasSubagents && active.activeAgentBadge ? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}` : active.activeModelShort || '模型未知'; patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent); @@ -418,7 +781,7 @@ export const LiveOverviewView = defineComponent({ `缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}` ); - // 2. 更新 6 段上下文窗口构成与方案 B 内嵌上下文窗口检视胶囊条 + // 2. 更新 10 段上下文窗口构成与内嵌上下文窗口检视胶囊条 patchAttr(ctxAgentBadge, 'hidden', !hasSubagents); patchAttr(ctxInspectorBar, 'hidden', !hasSubagents); if (hasSubagents && ctxAgent) { @@ -428,37 +791,24 @@ export const LiveOverviewView = defineComponent({ patchText(ctxAgentBadge, badgeFullText); patchAttr(ctxAgentBadge, 'title', badgeFullText); - const pillItems = []; - if (effectiveScope === 'all') { - pillItems.push({ + const pillItems = [ + { key: 'auto', label: `跟随活跃 (${aggregated?.activeAgentBadge || '主'})`, title: '自动展示当前正在运行或最新活跃的代理上下文窗口', isActive: effectiveCtxScope === 'auto', mode: 'ctx-only', - }); - } else { - pillItems.push({ - key: 'all', - label: `全部汇总 (${aggregated?.stepCount ?? 0}步)`, - title: '切回全部代理汇总视图', - isActive: false, - mode: 'scope', - }); - } + }, + ]; const allAgentPills = agents.map((ag) => { const agPct = ag.context?.usedPct ?? 0; - const isAct = - effectiveScope === 'all' - ? effectiveCtxScope === ag.agentId - : effectiveScope === ag.agentId; return { key: ag.agentId, label: `${ag.badgeText || ag.shortLabel} ${agPct}%`, title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`, - isActive: isAct, - mode: effectiveScope === 'all' ? 'ctx-only' : 'scope', + isActive: effectiveCtxScope === ag.agentId, + mode: 'ctx-only', }; }); @@ -632,6 +982,15 @@ export const LiveOverviewView = defineComponent({ (data) => { latestData = data; if (uiStore.getState().activeView !== 'overview') { + const stillRunning = + (Array.isArray(data?.runningConversations) && data.runningConversations.length > 0) || + Boolean( + data?.activeConversation?.isRunning || + data?.activeConversation?.aggregated?.isRunning + ); + if (!stillRunning) { + stopLiveTicker(); + } isDirty = true; return; } @@ -640,19 +999,15 @@ export const LiveOverviewView = defineComponent({ } ); - let prevScope = uiStore.getState().selectedAgentScope; let prevCtxTarget = uiStore.getState().ctxInspectorAgentId; const unsubView = uiStore.subscribe( (st) => ({ activeView: st.activeView, - selectedAgentScope: st.selectedAgentScope, ctxInspectorAgentId: st.ctxInspectorAgentId, }), (slice) => { - const scopeChanged = - slice.selectedAgentScope !== prevScope || slice.ctxInspectorAgentId !== prevCtxTarget; - prevScope = slice.selectedAgentScope; + const scopeChanged = slice.ctxInspectorAgentId !== prevCtxTarget; prevCtxTarget = slice.ctxInspectorAgentId; if (slice.activeView !== 'overview') { @@ -683,6 +1038,7 @@ export const LiveOverviewView = defineComponent({ } onCleanup(() => { + stopLiveTicker(); unsub(); unsubView(); if (ro) ro.disconnect(); diff --git a/sidecars/panel/src/views/SettingsView.js b/sidecars/panel/src/views/SettingsView.js index 8c47f5c..0eb1a96 100644 --- a/sidecars/panel/src/views/SettingsView.js +++ b/sidecars/panel/src/views/SettingsView.js @@ -75,11 +75,11 @@ export const SettingsView = defineComponent({ statusTimer = null; } patchText(saveStatusText, text); - if (text === '已保存') { + if (text === '已保存' || text === '保存失败') { statusTimer = setTimeout(() => { statusTimer = null; patchText(saveStatusText, ''); - }, 1500); + }, text === '保存失败' ? 2500 : 1500); } } @@ -121,10 +121,14 @@ export const SettingsView = defineComponent({ }); } showSaveFeedback('保存中…'); - await saveSettingsPatch({ - showUpstreamModel: draftShowUpstreamModel, - }); - showSaveFeedback('已保存'); + try { + await saveSettingsPatch({ + showUpstreamModel: draftShowUpstreamModel, + }); + showSaveFeedback('已保存'); + } catch { + showSaveFeedback('保存失败'); + } }, }); @@ -142,10 +146,14 @@ export const SettingsView = defineComponent({ }); } showCloudFeedback('保存中…', 0); - await saveSettingsPatch({ - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - showCloudFeedback('已保存', 1800); + try { + await saveSettingsPatch({ + autoUpdatePlugin: draftAutoUpdatePlugin, + }); + showCloudFeedback('已保存', 1800); + } catch { + showCloudFeedback('保存失败', 2500); + } }, }); @@ -176,14 +184,18 @@ export const SettingsView = defineComponent({ className: 'btn-primary', onClick: async () => { showSaveFeedback('保存中…'); - await saveSettingsPatch({ - weeklyLimitMode: draftMode, - weeklyTokenBudget: draftTokens, - weeklyCostBudget: draftCost, - showUpstreamModel: draftShowUpstreamModel, - autoUpdatePlugin: draftAutoUpdatePlugin, - }); - showSaveFeedback('已保存'); + try { + await saveSettingsPatch({ + weeklyLimitMode: draftMode, + weeklyTokenBudget: draftTokens, + weeklyCostBudget: draftCost, + showUpstreamModel: draftShowUpstreamModel, + autoUpdatePlugin: draftAutoUpdatePlugin, + }); + showSaveFeedback('已保存'); + } catch { + showSaveFeedback('保存失败'); + } }, }, [createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })] diff --git a/sidecars/panel/src/views/StepsDetailView.js b/sidecars/panel/src/views/StepsDetailView.js index 04d4db0..90bb576 100644 --- a/sidecars/panel/src/views/StepsDetailView.js +++ b/sidecars/panel/src/views/StepsDetailView.js @@ -201,15 +201,15 @@ export const StepsDetailView = defineComponent({ slice.recentSteps || []; const models = - hasSubagents && Array.isArray(scopedConv?.modelBreakdown) + (Array.isArray(scopedConv?.modelBreakdown) && scopedConv.modelBreakdown.length > 0 ? scopedConv.modelBreakdown - : slice.modelBreakdown || []; + : slice.sessionModelBreakdown || slice.modelBreakdown) || []; const showUpstream = Boolean(slice.showUpstreamModel); const modelsTabBadge = hasSubagents ? effectiveScope === 'all' ? '本会话汇总' : scopedConv?.shortLabel || '当前代理' - : slice.rangeLabel; + : '本会话'; subTabSwitch.setProps({ options: [ @@ -365,6 +365,7 @@ export const StepsDetailView = defineComponent({ activeConversation: st.telemetry?.activeConversation, cascadeId: st.telemetry?.activeConversation?.cascadeId, recentSteps: st.telemetry?.activeConversation?.recentSteps, + sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown, modelBreakdown: st.telemetry?.modelBreakdown, rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间', showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel), diff --git a/sidecars/panel/styles.css b/sidecars/panel/styles.css index e3f4d32..6b6632c 100644 --- a/sidecars/panel/styles.css +++ b/sidecars/panel/styles.css @@ -69,8 +69,8 @@ --ctx-output: hsl(190 80% 38%); /* Elevation & Shadows */ - --shadow-popover: 0 6px 20px color-mix(in srgb, var(--text-primary) 14%, transparent); - --shadow-glider: 0 1px 2px color-mix(in srgb, var(--text-primary) 10%, transparent); + --shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22); + --shadow-glider: 0 1px 2px rgb(0 0 0 / 0.14); /* Fast Hardware-Accelerated Motion Tokens */ --ease-fast: cubic-bezier(0.22, 1, 0.36, 1); @@ -280,93 +280,11 @@ input { border-radius: var(--radius-sm); } -.agent-scope-bar { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--space-2); - padding: 4px var(--space-3); - background: var(--surface-panel); - border: 1px solid var(--border-hairline); - border-radius: var(--radius-sm); -} - -.agent-scope-left { - display: flex; - align-items: center; - gap: 4px; - flex: 1; - min-width: 0; -} - -.scope-pill-btn { - display: inline-flex; - align-items: center; - gap: 3px; - height: 22px; - padding: 0 7px; - border: 1px solid transparent; - background: transparent; - color: var(--text-secondary); - font-size: 11.5px; - border-radius: var(--radius-xs); - cursor: pointer; - white-space: nowrap; - flex-shrink: 0; - transition: - background-color var(--dur-instant) var(--ease-fast), - color var(--dur-instant) var(--ease-fast), - border-color var(--dur-instant) var(--ease-fast); -} - -.scope-pill-btn:hover { - background: var(--surface-hover); - color: var(--text-primary); -} - -.scope-pill-btn.is-active { - background: var(--accent-primary-soft); - color: var(--accent-primary); - border-color: var(--accent-primary-border); - font-weight: 600; -} - -.scope-subagent-select { - flex: 1 1 115px; - min-width: 105px; -} - -.scope-subagent-select .select-trigger { - height: 22px; - padding: 0 6px; - font-size: 11.5px; - border: 1px solid var(--border-hairline); - background: var(--surface-subtle); -} - -.scope-subagent-select.is-active-sub .select-trigger { - background: var(--accent-primary-soft); - color: var(--accent-primary); - border-color: var(--accent-primary-border); - font-weight: 600; -} - -.scope-subagent-select .select-menu, .steps-inline-scope-select .select-menu { left: auto; right: 0; } -.agent-scope-right { - display: inline-flex; - align-items: center; - gap: 5px; - font-size: 11px; - color: var(--text-secondary); - white-space: nowrap; - flex-shrink: 0; -} - .session-left { display: flex; align-items: center; @@ -444,12 +362,6 @@ input { transform: scale(0.95); } -.icon-btn.is-active { - background: var(--accent-primary-soft); - color: var(--accent-primary); - border-color: var(--accent-primary-border); -} - /* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */ .long-pill-nav { position: relative; @@ -595,7 +507,7 @@ input { box-shadow: var(--shadow-popover); padding: 4px; z-index: 60; - animation: popover-in var(--dur-fast) var(--ease-fast); + animation: anim-popover-in var(--dur-fast) var(--ease-fast); } .select-option { @@ -725,7 +637,7 @@ input { display: flex; flex-direction: column; gap: var(--space-2); - animation: popover-in var(--dur-fast) var(--ease-fast); + animation: anim-popover-in var(--dur-fast) var(--ease-fast); } .dt-nav { @@ -1085,7 +997,239 @@ input { white-space: nowrap; } -/* --- 2. 4 格实时测速指标矩阵 (4-Cell Telemetry Matrix) --- */ +/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */ +.live-activity-list { + display: flex; + flex-direction: column; + gap: 6px; + flex-shrink: 0; + min-width: 0; +} + +.live-activity-list[hidden] { + display: none !important; +} + +.live-task-card { + display: flex; + flex-direction: column; + gap: 5px; + padding: 7px 10px; + border: 1px solid var(--accent-primary-border); + border-radius: var(--radius-xs); + background: color-mix(in srgb, var(--accent-primary) 5%, var(--surface-panel)); + min-width: 0; +} + +.live-task-card.is-waiting { + border-color: color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline)); + background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel)); +} + +.live-task-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + min-width: 0; +} + +.live-task-title-wrap { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + flex: 1; +} + +.live-task-title { + font-size: 11.5px; + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + cursor: pointer; +} + +.live-task-title:hover { + color: var(--accent-primary); +} + +.live-task-header-right { + display: inline-flex; + align-items: center; + gap: 6px; + flex-shrink: 0; +} + +.live-sub-toggle { + display: inline-flex; + align-items: center; + gap: 3px; + height: 18px; + padding: 0 6px; + font-size: 10.5px; + font-weight: 600; + color: var(--text-secondary); + background: var(--surface-panel); + border: 1px solid var(--border-hairline); + border-radius: var(--radius-xs); + cursor: pointer; + white-space: nowrap; + transition: + border-color var(--dur-instant) var(--ease-fast), + color var(--dur-instant) var(--ease-fast), + background-color var(--dur-instant) var(--ease-fast); +} + +.live-sub-toggle:hover { + border-color: var(--border-strong); + color: var(--text-primary); +} + +.live-sub-toggle.is-expanded { + color: var(--accent-primary); + border-color: var(--accent-primary-border); + background: var(--accent-primary-soft); +} + +.live-sub-toggle[hidden] { + display: none !important; +} + +.live-task-main-row { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + padding-left: 1px; +} + +.live-activity-dot { + color: var(--accent-primary); + display: inline-flex; + align-items: center; + flex-shrink: 0; +} + +.live-task-card.is-waiting .live-activity-dot { + color: var(--metric-warn); +} + +.live-activity-phase { + font-size: 11px; + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + flex-shrink: 0; +} + +.live-task-card.is-waiting .live-activity-phase { + color: var(--metric-warn); +} + +.live-activity-progress { + font-size: 10px; + font-weight: 600; + color: var(--accent-primary); + background: var(--accent-primary-soft); + padding: 0 4px; + border-radius: var(--radius-xs); + white-space: nowrap; + flex-shrink: 0; +} + +.live-activity-sep { + font-size: 11px; + color: var(--text-muted); + flex-shrink: 0; +} + +.live-activity-detail { + font-size: 11px; + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + flex: 1; +} + +.live-activity-elapsed { + font-size: 11px; + font-weight: 600; + color: var(--accent-primary); + white-space: nowrap; + flex-shrink: 0; +} + +.live-task-card.is-waiting .live-activity-elapsed { + color: var(--metric-warn); +} + +.live-sub-list { + display: flex; + flex-direction: column; + gap: 4px; + padding-top: 5px; + margin-top: 1px; + border-top: 1px dashed var(--border-hairline); + min-width: 0; +} + +.live-sub-list[hidden] { + display: none !important; +} + +.live-sub-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + min-width: 0; + font-size: 10.5px; +} + +.live-sub-row.is-done { + opacity: 0.72; +} + +.live-sub-left { + display: flex; + align-items: center; + gap: 5px; + min-width: 0; + flex: 1; +} + +.live-sub-role { + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 110px; + flex-shrink: 0; +} + +.live-sub-summary { + color: var(--text-secondary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + min-width: 0; + flex: 1; +} + +.live-sub-elapsed { + font-size: 10.5px; + color: var(--text-secondary); + white-space: nowrap; + flex-shrink: 0; +} + .telemetry-matrix { display: grid; grid-template-columns: repeat(4, 1fr); @@ -1152,53 +1296,58 @@ input { .progress-seg { height: 100%; width: var(--seg-w, 0%); - transition: width var(--dur-normal) var(--ease-fast); + transition: + background-color 0.05s ease, + width var(--dur-normal) var(--ease-fast); } -.progress-seg.seg-messages { - background: var(--ctx-messages); +.progress-track.is-reordering .progress-seg { + transition: + background-color 0.05s ease, + width var(--dur-normal) var(--ease-fast) 0.05s; } + .progress-seg.seg-assistant { - background: var(--ctx-assistant); + background-color: var(--ctx-assistant); } .progress-seg.seg-tool-results { - background: var(--ctx-tool-results); + background-color: var(--ctx-tool-results); } .progress-seg.seg-user-input { - background: var(--ctx-user-input); + background-color: var(--ctx-user-input); } .progress-seg.seg-subagent-msg { - background: var(--ctx-subagent-msg); + background-color: var(--ctx-subagent-msg); } .progress-seg.seg-checkpoint { - background: var(--ctx-checkpoint); + background-color: var(--ctx-checkpoint); } .progress-seg.seg-system-tools { - background: var(--ctx-system-tools); + background-color: var(--ctx-system-tools); } .progress-seg.seg-mcp-tools { - background: var(--ctx-mcp-tools); + background-color: var(--ctx-mcp-tools); } .progress-seg.seg-skills { - background: var(--ctx-skills); + background-color: var(--ctx-skills); } .progress-seg.seg-system-prompt { - background: var(--ctx-system-prompt); + background-color: var(--ctx-system-prompt); } .progress-seg.seg-user-rules { - background: var(--ctx-user-rules); + background-color: var(--ctx-user-rules); } .progress-seg.seg-cached { - background: var(--ctx-cached); + background-color: var(--ctx-cached); } .progress-seg.seg-input { - background: var(--ctx-input); + background-color: var(--ctx-input); } .progress-seg.seg-thinking { - background: var(--ctx-thinking); + background-color: var(--ctx-thinking); } .progress-seg.seg-output { - background: var(--ctx-output); + background-color: var(--ctx-output); } .progress-fill { @@ -1216,7 +1365,7 @@ input { background: var(--metric-danger); } -/* --- 4. 上下文双列图例网格 (Context 6-Channel Legend Grid) --- */ +/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */ .ctx-legend-grid { display: grid; grid-template-columns: repeat(2, 1fr); @@ -1248,7 +1397,6 @@ input { display: inline-block; } -.swatch.seg-messages { background: var(--ctx-messages); } .swatch.seg-assistant { background: var(--ctx-assistant); } .swatch.seg-tool-results { background: var(--ctx-tool-results); } .swatch.seg-user-input { background: var(--ctx-user-input); } @@ -1471,8 +1619,7 @@ input { padding-right: 0; } -.cons-col.is-bordered-col, -.cons-col.is-right-col { +.cons-col.is-bordered-col { border-left: 1px solid var(--border-hairline); } @@ -1582,16 +1729,25 @@ input { height: 5px; } -/* --- 4. 历史趋势 SVG 平滑曲线图 (Historical Trend SVG Chart) --- */ +/* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */ .trend-chart-wrap { position: relative; width: 100%; - padding-top: 8px; + display: flex; + flex-direction: column; + gap: 2px; +} + +.trend-plot-stage { + position: relative; + width: 100%; + padding-top: 6px; + cursor: crosshair; } .trend-svg { width: 100%; - height: 112px; + height: 118px; display: block; overflow: visible; } @@ -1608,12 +1764,33 @@ input { stroke-linecap: round; } +.trend-node-dot { + fill: var(--surface-panel); + stroke: var(--ctx-cached); + stroke-width: 1.4; +} + .trend-peak-dot { fill: var(--ctx-cached); stroke: var(--surface-panel); stroke-width: 1.5; } +.trend-hover-line { + stroke: var(--accent-primary); + stroke-width: 1; + stroke-dasharray: 2 2; + opacity: 0.75; + pointer-events: none; +} + +.trend-hover-dot { + fill: var(--accent-primary); + stroke: var(--surface-panel); + stroke-width: 1.8; + pointer-events: none; +} + .trend-peak-pill { position: absolute; top: 2px; @@ -1624,31 +1801,113 @@ input { padding: 1px 6px; color: var(--text-primary); background: color-mix(in srgb, var(--ctx-cached) 16%, var(--surface-panel)); - border: none; + border: 1px solid color-mix(in srgb, var(--ctx-cached) 30%, var(--border-hairline)); border-radius: var(--radius-xs); pointer-events: none; white-space: nowrap; + z-index: 2; } -.trend-anchors { - display: grid; - grid-template-columns: repeat(3, 1fr); - padding-top: 2px; - font-size: 11px; -} - -.trend-anchor-col { +.trend-tooltip { + position: absolute; + top: 0; + left: var(--tip-x, 50%); + transform: translateX(var(--tip-shift, -50%)); + min-width: 148px; + max-width: 240px; + padding: 5px 8px; + background: var(--surface-panel); + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm); + box-shadow: none; + pointer-events: none; + z-index: 15; display: flex; flex-direction: column; - gap: 1px; + gap: 2px; } -.trend-anchor-col.is-center { +.trend-tip-head { + display: flex; align-items: center; + justify-content: space-between; + gap: 8px; + font-size: 10.5px; + color: var(--text-secondary); } -.trend-anchor-col.is-end { - align-items: flex-end; +.trend-tip-time { + font-weight: 600; + color: var(--text-primary); + white-space: nowrap; +} + +.trend-tip-calls { + font-size: 10px; + color: var(--text-muted); + white-space: nowrap; +} + +.trend-tip-main { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 8px; +} + +.trend-tip-tokens { + font-size: 12px; + font-weight: 700; + color: var(--accent-primary); +} + +.trend-tip-cost { + font-size: 11px; + font-weight: 600; + color: var(--text-primary); +} + +.trend-tip-sub { + font-size: 10px; + color: var(--text-secondary); + white-space: nowrap; + border-top: 1px solid var(--border-hairline); + padding-top: 2px; + margin-top: 1px; +} + +.trend-x-axis { + position: relative; + width: 100%; + height: 18px; + user-select: none; +} + +.trend-x-tick { + position: absolute; + top: 0; + left: var(--tick-x, 0%); + transform: translateX(-50%); + font-size: 10px; + color: var(--text-muted); + white-space: nowrap; + line-height: 16px; + cursor: pointer; + transition: color var(--dur-instant) var(--ease-fast); +} + +.trend-x-tick.is-start { + transform: translateX(0); +} + +.trend-x-tick.is-end { + transform: translateX(-100%); +} + +.trend-x-tick:hover, +.trend-x-tick.is-hovered { + color: var(--accent-primary); + font-weight: 600; } /* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */ diff --git a/sidecars/panel/test/backend.test.mjs b/sidecars/panel/test/backend.test.mjs index 404cf05..18d197d 100644 --- a/sidecars/panel/test/backend.test.mjs +++ b/sidecars/panel/test/backend.test.mjs @@ -331,4 +331,214 @@ test('converges multi-level nested subagents to ultimate root and preserves metr // Main agent steps are not duplicated in agents[0].recentSteps or aggregated.recentSteps assert.equal(p.activeConversation.agents[0].recentSteps,undefined); assert.equal(p.activeConversation.aggregated.recentSteps,undefined); + // Running sub-l2 with 0 steps still exposes liveActivity on both subagent and aggregated view + assert.equal(p.activeConversation.agents[0].liveActivity,null); + assert.equal(p.activeConversation.agents[2].liveActivity.phase,'thinking'); + assert.equal(p.activeConversation.aggregated.liveActivity.agentId,'sub-l2'); + assert.equal(p.activeConversation.aggregated.liveActivity.agentBadge,'子2'); + // runningConversations includes root-multi with main summary and collapsible subagents summary + assert.equal(p.runningConversations.length,1); + assert.equal(p.runningConversations[0].cascadeId,'root-multi'); + assert.equal(p.runningConversations[0].title,'Multi-Level Task'); + assert.equal(p.runningConversations[0].subagentCount,2); + assert.equal(p.runningConversations[0].runningSubagentCount,1); + assert.equal(p.runningConversations[0].mainActivity.label,'等待子代理'); + assert.equal(p.runningConversations[0].subagents[0].role,'Level 1 Orchestrator'); + assert.equal(p.runningConversations[0].subagents[0].isRunning,false); + assert.equal(p.runningConversations[0].subagents[0].liveActivity.label,'已完成'); + assert.equal(p.runningConversations[0].subagents[1].role,'Level 2 Deep Worker'); + assert.equal(p.runningConversations[0].subagents[1].isRunning,true); +}); + +test('trendSeries buckets hourly for <=72h windows (today/24h) and daily for >72h windows (7d)', async () => { + const nowMs = Date.now(); + const nowIso = new Date(nowMs - 5000).toISOString(); + const finIso = new Date(nowMs).toISOString(); + const h = backendHarness({ + trajectories: { + c1: { + trajectory: { + steps: [ + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: nowIso, + finishedGeneratingAt: finIso, + modelUsage: { + model: 'MODEL_PLACEHOLDER_M37', + inputTokens: '100', + cacheReadTokens: '200', + outputTokens: '600', + thinkingOutputTokens: '100', + responseOutputTokens: '500', + }, + }, + plannerResponse: { response: 'answer', thinkingDuration: '2s' }, + }, + ], + generatorMetadata: [{ stepIndices: [0], chatModel: { timeToFirstToken: '1s', streamingDuration: '4s' } }], + }, + }, + }, + summaries: { + c1: { stepCount: 1, lastModifiedTime: finIso, status: 'IDLE' }, + }, + }); + + const p24h = await h.buildTelemetryPayloadInternal('c1', false, { range: '24h' }); + const trend24h = p24h.consumption.trendSeries; + assert.ok(trend24h.length >= 24 && trend24h.length <= 26); + assert.equal(trend24h[0].granularity, 'hour'); + assert.match(trend24h[0].fullLabel, /\d+月\d+日 \d{2}:00 - \d{2}:00/); + assert.equal(trend24h.reduce((sum, b) => sum + b.tokens, 0), 900); + assert.equal(trend24h.reduce((sum, b) => sum + b.calls, 0), 1); + + const p7d = await h.buildTelemetryPayloadInternal('c1', false, { range: '7d' }); + const trend7d = p7d.consumption.trendSeries; + assert.ok(trend7d.length >= 7 && trend7d.length <= 8); + assert.equal(trend7d[0].granularity, 'day'); + assert.match(trend7d[0].fullLabel, /\d+月\d+日 \(周[日一二三四五六]\)/); + assert.equal(trend7d.reduce((sum, b) => sum + b.tokens, 0), 900); +}); + +test('supports Gemini 4 Carbon pricing/pool and resolves all newly added language_server placeholder enums', async () => { + const nowIso = new Date().toISOString(); + const h = backendHarness({ + userStatus: { + name: 'Carbon Tester', + cascadeModelConfigData: { + clientModelConfigs: [ + { + label: 'Gemini 3.8 Flash (High)', + modelId: 'gemini-3.8-flash-high', + modelOrAlias: { model: 'MODEL_PLACEHOLDER_M318' }, + quotaInfo: { remainingFraction: 0.9, resetTime: '2026-11-12T00:00:00Z' }, + }, + { + label: 'Gemini 4 Carbon (High)', + modelId: 'gemini-4-carbon-high', + modelOrAlias: { model: 'MODEL_PLACEHOLDER_M429' }, + quotaInfo: { remainingFraction: 0.65, resetTime: '2026-11-17T00:00:00Z' }, + }, + ], + }, + }, + trajectories: { + cCarbon: { + trajectory: { + steps: [ + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-10T00:00:00Z', + finishedGeneratingAt: '2026-11-10T00:00:05Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M298', + inputTokens: '1000000', + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + plannerResponse: { response: 'flash 3.7 high' }, + }, + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-10T00:00:06Z', + finishedGeneratingAt: '2026-11-10T00:00:10Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M402', + inputTokens: '1000000', + cacheReadTokens: '0', + outputTokens: '0', + }, + }, + plannerResponse: { response: 'claude opus 5.5 high' }, + }, + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-10T00:00:11Z', + finishedGeneratingAt: '2026-11-10T00:00:15Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '1000000', + cacheReadTokens: '1000000', + outputTokens: '100000', + }, + }, + plannerResponse: { response: 'carbon high' }, + }, + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-10T00:00:16Z', + finishedGeneratingAt: '2026-11-10T00:00:20Z', + modelUsage: { + model: 'claude-fable-5-2-high', + inputTokens: '1000000', + cacheReadTokens: '1000000', + outputTokens: '100000', + }, + }, + plannerResponse: { response: 'fable 5.2 high' }, + }, + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-10T00:00:21Z', + finishedGeneratingAt: '2026-11-10T00:00:25Z', + modelUsage: { + model: 'gpt-6.1-terra', + inputTokens: '1000000', + cacheReadTokens: '1000000', + outputTokens: '100000', + }, + }, + plannerResponse: { response: 'gpt 6.1 terra' }, + }, + { + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { + createdAt: '2026-11-10T00:00:26Z', + finishedGeneratingAt: '2026-11-10T00:00:30Z', + modelUsage: { + model: 'MODEL_PLACEHOLDER_M429', + inputTokens: '0', + cacheReadTokens: '0', + outputTokens: '100', + }, + }, + plannerResponse: { response: 'carbon tail' }, + }, + ], + generatorMetadata: [ + { stepIndices: [0], chatModel: { timeToFirstToken: '1s', streamingDuration: '4s' } }, + { stepIndices: [1], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } }, + { stepIndices: [2], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } }, + { stepIndices: [3], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } }, + { stepIndices: [4], chatModel: { timeToFirstToken: '1s', streamingDuration: '3s' } }, + { stepIndices: [5], chatModel: { timeToFirstToken: '1s', streamingDuration: '1s' } }, + ], + }, + }, + }, + summaries: { + cCarbon: { stepCount: 6, lastModifiedTime: nowIso, status: 'IDLE' }, + }, + }); + + const p = await h.buildTelemetryPayloadInternal('cCarbon'); + assert.equal(p.activeConversation.sessionUnpricedCalls, 0); + // Step 0: M298 -> Gemini 3.7 Flash ($0.75) + // Step 1: M402 -> Claude Opus 5.5 ($4.00) + // Step 2: Carbon High -> 1M*$2.00 + 1M*$0.10 + 0.1M*$10.0 = $3.10 + // Step 3: Fable 5.2 High -> 1M*$8.00 + 1M*$0.20 + 0.1M*$40.0 = $12.20 + // Step 4: GPT-6.1 Terra -> 1M*$1.00 + 1M*$0.05 + 0.1M*$5.0 = $1.55 + // Step 5: Carbon High -> 100 tok * $10/1M = $0.001 + // Total = 0.75 + 4.00 + 3.10 + 12.20 + 1.55 + 0.001 = $21.601 -> $21.60 + assert.equal(p.activeConversation.sessionCostUsd, 21.6); + assert.equal(p.activeConversation.activeModelShort, 'carbon-4-high'); + assert.equal(p.quotas.activePool.poolKey, 'Carbon'); + assert.equal(p.quotas.activePool.weeklyRemainingIntPct, 65); }); diff --git a/sidecars/panel/test/speed-metrics.test.mjs b/sidecars/panel/test/speed-metrics.test.mjs index 18810cd..6dfbdbf 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 {extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs'; +import {extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-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'}={}) { @@ -155,3 +155,129 @@ test('compaction displays a valid rate and retains billing but is excluded from assert.equal(summarizeSpeed([step]).sampleCount,0); assert.equal(summarizeTtft([step]).sampleCount,0); }); + +test('extractLiveActivity covers thinking, partial streaming tool args, multi-tool batch progress, waiting, and post-tool reasoning',()=>{ + // 1. Idle conversation returns null + assert.equal(extractLiveActivity([], false), null); + + // 2. Streaming thinking + const thinkingStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_GENERATING', + metadata: { createdAt: '2026-01-01T00:00:10Z' }, + plannerResponse: { thinking: 'Analyzing the telemetry pipeline\nChecking LiveOverviewView layout' }, + }; + const actThink = extractLiveActivity([thinkingStep], true); + assert.equal(actThink.phase, 'thinking'); + assert.equal(actThink.label, '推理中'); + assert.match(actThink.detail, /Checking LiveOverviewView layout/); + + // 3. Partial JSON tool call while streaming edit_file + const streamingToolStep = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_STREAMING', + metadata: { createdAt: '2026-01-01T00:00:12Z' }, + plannerResponse: { + thinking: 'done thinking', + toolCalls: [{ name: 'edit_file', argumentsJson: '{"Path":"f:\\\\ppt\\\\sidecars\\\\panel\\\\src\\\\views\\\\LiveOverviewView.js","Replacement":"const a = 1;' }], + }, + }; + const actPartialTool = extractLiveActivity([streamingToolStep], true); + assert.equal(actPartialTool.phase, 'tool'); + assert.equal(actPartialTool.label, '修改文件'); + assert.equal(actPartialTool.detail, 'LiveOverviewView.js'); + + // 4. Multi-tool batch execution progress ([1/3] -> [2/3] -> post-tool thinking) + const completedPlannerWith3Tools = { + type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-01-01T00:00:10Z', finishedGeneratingAt: '2026-01-01T00:00:12Z' }, + plannerResponse: { + toolCalls: [ + { name: 'read_file', argumentsJson: JSON.stringify({ Path: '/repo/plugin.json' }) }, + { name: 'run_command', argumentsJson: JSON.stringify({ CommandLine: 'npm test', toolSummary: '运行单元测试' }) }, + { name: 'edit_file', argumentsJson: JSON.stringify({ Path: '/repo/main.mjs' }) }, + ], + }, + }; + const toolResult1Done = { + type: 'CORTEX_STEP_TYPE_GENERIC', + status: 'CORTEX_STEP_STATUS_DONE', + metadata: { createdAt: '2026-01-01T00:00:12Z', completedAt: '2026-01-01T00:00:13Z' }, + }; + // After 1st tool finishes, 2nd tool (run_command) is active -> [2/3] 执行命令 · 运行单元测试 (npm test) + const actBatch2 = extractLiveActivity([completedPlannerWith3Tools, toolResult1Done], true); + assert.equal(actBatch2.phase, 'tool'); + assert.equal(actBatch2.label, '执行命令'); + assert.equal(actBatch2.stepProgress, '2/3'); + assert.equal(actBatch2.detail, '运行单元测试 (npm test)'); + + // When all 3 tools are done and conversation is still running -> shows last completed tool & actual file/command + const toolResult2Done = { ...toolResult1Done, metadata: { completedAt: '2026-01-01T00:00:15Z' } }; + const toolResult3Done = { ...toolResult1Done, metadata: { completedAt: '2026-01-01T00:00:16Z' } }; + const actPostTools = extractLiveActivity( + [completedPlannerWith3Tools, toolResult1Done, toolResult2Done, toolResult3Done], + true + ); + assert.equal(actPostTools.phase, 'thinking'); + assert.equal(actPostTools.label, '修改文件'); + assert.equal(actPostTools.detail, 'main.mjs'); + + // 5. Waiting for user confirmation on command step + const waitingStep = { + type: 'CORTEX_STEP_TYPE_RUN_COMMAND', + status: 'CORTEX_STEP_STATUS_WAITING', + metadata: { + createdAt: '2026-01-01T00:00:20Z', + toolCall: { name: 'run_command', argumentsJson: JSON.stringify({ toolSummary: '安装依赖包' }) }, + }, + }; + const actWait = extractLiveActivity([waitingStep], true); + assert.equal(actWait.phase, 'waiting'); + assert.equal(actWait.label, '等待确认 · 执行命令'); + assert.equal(actWait.detail, '安装依赖包'); + + // 6. transcript.jsonl format (snake_case tool_calls + JSON-encoded string args + DONE status) + const transcriptPlannerStep = { + step_index: 7, + source: 'MODEL', + type: 'PLANNER_RESPONSE', + status: 'DONE', + created_at: '2026-11-10T10:29:49Z', + thinking: 'Inspecting project files', + tool_calls: [ + { + name: 'read_file', + args: { + Path: '"f:\\\\ppt\\\\1111\\\\antigravity-usage-monitor\\\\plugin.json"', + }, + }, + { + name: 'run_command', + args: { + CommandLine: '"Get-ChildItem -Path \\"f:\\\\ppt\\""', + toolSummary: '"列出插件项目全部源文件"', + }, + }, + ], + }; + const transcriptGenericDone = { + step_index: 8, + source: 'MODEL', + type: 'GENERIC', + status: 'DONE', + created_at: '2026-11-10T10:29:57Z', + content: 'Showing lines 1-12 of 12', + }; + const actTranscript1 = extractLiveActivity([transcriptPlannerStep], true); + assert.equal(actTranscript1.phase, 'tool'); + assert.equal(actTranscript1.label, '读取文件'); + assert.equal(actTranscript1.stepProgress, '1/2'); + assert.equal(actTranscript1.detail, 'plugin.json'); + + const actTranscript2 = extractLiveActivity([transcriptPlannerStep, transcriptGenericDone], true); + assert.equal(actTranscript2.phase, 'tool'); + assert.equal(actTranscript2.label, '执行命令'); + assert.equal(actTranscript2.stepProgress, '2/2'); + assert.equal(actTranscript2.detail, '列出插件项目全部源文件 (Get-ChildItem -Path "f:\\ppt")'); +});