mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
Merge pull request #25 from yuhuan-dev/release/v1.5.1
feat(panel): hybrid SQLite+WAL trajectory reader, side-question views, time-phased promo pricing, and architecture cleanup (v1.5.1)
This commit is contained in:
+1
-1
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "usage-monitor",
|
"name": "usage-monitor",
|
||||||
"displayName": "Usage & Speed Monitor",
|
"displayName": "Usage & Speed Monitor",
|
||||||
"version": "1.5.0",
|
"version": "1.5.1",
|
||||||
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
"description": "实时查看生成速度、首字延迟、上下文占用、可用额度及历史用量。",
|
||||||
"logo": "assets/logo.svg",
|
"logo": "assets/logo.svg",
|
||||||
"suggestedPrompts": [
|
"suggestedPrompts": [
|
||||||
|
|||||||
+32
-30
@@ -1,26 +1,28 @@
|
|||||||
{
|
{
|
||||||
"schemaVersion": 1,
|
"schemaVersion": 1,
|
||||||
"catalogVersion": "2026.11.17.1",
|
"catalogVersion": "2026.11.17.4",
|
||||||
"updatedAt": "2026-11-17T00:15:00+09:00",
|
"updatedAt": "2026-11-17T20:00:00+09:00",
|
||||||
"latestPluginVersion": "1.5.0",
|
"latestPluginVersion": "1.5.1",
|
||||||
"releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest",
|
"releaseUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest",
|
||||||
"downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
|
"downloadUrl": "https://github.com/yuhuan-dev/antigravity-usage-monitor/releases/latest/download/usage-monitor.zip",
|
||||||
"archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main",
|
"archiveFallbackUrl": "https://codeload.github.com/yuhuan-dev/antigravity-usage-monitor/zip/refs/heads/main",
|
||||||
"pricing": {
|
"pricing": {
|
||||||
"gemini-pro-orchestrator": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" },
|
"gemini-pro-orchestrator": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"orchestrator-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini" },
|
"orchestrator-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-carbon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-pro-orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini" },
|
"gemini-pro-orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini" },
|
"orchestrator-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "orch-argon", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-carbon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-high", "family": "Gemini" },
|
"gemini-4-carbon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-high", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-carbon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini" },
|
"gemini-4-carbon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-carbon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-low", "family": "Gemini" },
|
"gemini-4-carbon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4-low", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini" },
|
"gemini-4-carbon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "carbon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini" },
|
"gemini-4-argon-high": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-high", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
"gemini-4-argon-medium": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini" },
|
"gemini-4-argon-low": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4-low", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-argon-f": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
"gemini-4-argon-b": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-argon-disabled": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
"gemini-4-argon-f": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini" },
|
"gemini-4-argon-trial": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
|
"gemini-4-argon-disabled": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
|
"gemini-4-argon": { "input": 2.00, "cache": 0.10, "output": 10.0, "short": "argon-4", "family": "Gemini", "phases": [{ "until": "2026-12-01T00:00:00Z", "input": 2.00, "cache": 0.10, "output": 10.0 }, { "from": "2026-12-01T00:00:00Z", "input": 4.00, "cache": 0.20, "output": 20.0 }] },
|
||||||
"gemini-4-hydrogen-xhigh": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-xhigh", "family": "Gemini" },
|
"gemini-4-hydrogen-xhigh": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-xhigh", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen-high": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-high", "family": "Gemini" },
|
"gemini-4-hydrogen-high": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4-high", "family": "Gemini" },
|
||||||
"gemini-4-hydrogen-medium": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" },
|
"gemini-4-hydrogen-medium": { "input": 1.50, "cache": 0.075, "output": 7.50, "short": "hydrogen-4", "family": "Gemini" },
|
||||||
@@ -42,22 +44,22 @@
|
|||||||
"gemini-helix-medium": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix", "family": "Gemini" },
|
"gemini-helix-medium": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix", "family": "Gemini" },
|
||||||
"gemini-helix-low": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix-low", "family": "Gemini" },
|
"gemini-helix-low": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix-low", "family": "Gemini" },
|
||||||
"gemini-helix": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix", "family": "Gemini" },
|
"gemini-helix": { "input": 0.30, "cache": 0.015, "output": 2.50, "short": "helix", "family": "Gemini" },
|
||||||
"gemini-3.8-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8-high", "family": "Gemini" },
|
"gemini-3.8-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8-high", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.8-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" },
|
"gemini-3.8-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.8-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.8-low", "family": "Gemini" },
|
"gemini-3.8-flash-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-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.8-flash-n": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" },
|
"gemini-3.8-flash-n": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.8-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini" },
|
"gemini-3.8-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.8", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.7-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7-high", "family": "Gemini" },
|
"gemini-3.7-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7-high", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.7-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
"gemini-3.7-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.7-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.7-low", "family": "Gemini" },
|
"gemini-3.7-flash-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-tiered": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.7-flash-safety-le": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
"gemini-3.7-flash-safety-le": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.7-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini" },
|
"gemini-3.7-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.7", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.6-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6-high", "family": "Gemini" },
|
"gemini-3.6-flash-high": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6-high", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.6-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini" },
|
"gemini-3.6-flash-medium": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.6-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.6-low", "family": "Gemini" },
|
"gemini-3.6-flash-low": { "input": 0.30, "cache": 0.03, "output": 2.50, "short": "flash-3.6-low", "family": "Gemini" },
|
||||||
"gemini-3.6-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini" },
|
"gemini-3.6-flash": { "input": 0.75, "cache": 0.075, "output": 3.75, "short": "flash-3.6", "family": "Gemini", "phases": [{ "until": "2027-01-01T00:00:00Z", "input": 0.75, "cache": 0.075, "output": 3.75 }, { "from": "2027-01-01T00:00:00Z", "input": 1.50, "cache": 0.15, "output": 7.50 }] },
|
||||||
"gemini-3.5-flash-high": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5-high", "family": "Gemini" },
|
"gemini-3.5-flash-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-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-low": { "input": 1.50, "cache": 0.15, "output": 9.00, "short": "flash-3.5-low", "family": "Gemini" },
|
||||||
|
|||||||
+2748
-1778
File diff suppressed because it is too large
Load Diff
@@ -6,13 +6,13 @@
|
|||||||
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
|
||||||
import { join } from 'node:path';
|
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { BRIDGE_API_ROUTE_DEFS } from '../shared/window-bridge-protocol.mjs';
|
||||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||||
|
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||||
|
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
||||||
import {
|
import {
|
||||||
HERE,
|
|
||||||
SETTINGS_FILE,
|
SETTINGS_FILE,
|
||||||
clearRuntimeCaches,
|
clearRuntimeCaches,
|
||||||
cloudSyncState,
|
cloudSyncState,
|
||||||
@@ -45,8 +45,14 @@ import {
|
|||||||
import { getCloudStatus } from './pricing-catalog.mjs';
|
import { getCloudStatus } from './pricing-catalog.mjs';
|
||||||
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
import { buildTelemetryPayload } from './telemetry-builder.mjs';
|
||||||
import {
|
import {
|
||||||
|
ensureDesktopLaunchEntriesConfigured,
|
||||||
|
triggerDesktopHostRelaunch,
|
||||||
|
} from './desktop-launcher-config.mjs';
|
||||||
|
import {
|
||||||
|
ensureIdeRemoteDebuggingArgv,
|
||||||
notifyModelContextWindowsChanged,
|
notifyModelContextWindowsChanged,
|
||||||
notifyWindowOverlaySetting,
|
notifyWindowOverlaySetting,
|
||||||
|
resolveDevToolsPortCandidates,
|
||||||
startDefaultWindowBridge,
|
startDefaultWindowBridge,
|
||||||
} from './window-bridge.mjs';
|
} from './window-bridge.mjs';
|
||||||
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
|
import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
|
||||||
@@ -59,60 +65,7 @@ export function setStandalonePortListener(listener) {
|
|||||||
standalonePortListener = typeof listener === 'function' ? listener : null;
|
standalonePortListener = typeof listener === 'function' ? listener : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export { isLocalHostRequest, readLocalAsync };
|
||||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
|
||||||
*
|
|
||||||
* @param {string} relPath 相对路径
|
|
||||||
* @returns {Promise<string>}
|
|
||||||
*/
|
|
||||||
export const readLocalAsync = async (relPath) => {
|
|
||||||
const fullPath = join(HERE, relPath);
|
|
||||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
|
||||||
return fsPromises.readFile(fullPath, 'utf8');
|
|
||||||
}
|
|
||||||
return readFileSync(fullPath, 'utf8');
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
|
||||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
|
||||||
*
|
|
||||||
* @param {object} req
|
|
||||||
* @returns {boolean}
|
|
||||||
*/
|
|
||||||
export function isLocalHostRequest(req) {
|
|
||||||
if (!req?.headers) return true;
|
|
||||||
const host = String(req.headers.host || '').trim().toLowerCase();
|
|
||||||
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
|
||||||
if (host && !hostMatch) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
|
||||||
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
|
||||||
if (secFetchSite === 'cross-site') {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (origin) {
|
|
||||||
const originMatch = origin.match(
|
|
||||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
|
||||||
);
|
|
||||||
if (!originMatch) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
if (hostMatch) {
|
|
||||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
|
||||||
const originPort = originMatch[3] || defaultPort;
|
|
||||||
const hostPort = hostMatch[2] || defaultPort;
|
|
||||||
if (originPort !== hostPort) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
||||||
|
|
||||||
@@ -142,7 +95,8 @@ function projectDisplayStep(st) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let lastDisplaySteps = null;
|
const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8;
|
||||||
|
const displayStepsCache = new Map();
|
||||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||||
|
|
||||||
function haveSameDisplaySteps(previous, current) {
|
function haveSameDisplaySteps(previous, current) {
|
||||||
@@ -165,23 +119,34 @@ function projectDisplayTelemetry(payload, requestedRevision) {
|
|||||||
let projected;
|
let projected;
|
||||||
let revision;
|
let revision;
|
||||||
if (typeof requestedRevision === 'string') {
|
if (typeof requestedRevision === 'string') {
|
||||||
|
const cacheKey = active.cascadeId || '__empty__';
|
||||||
const scope = [
|
const scope = [
|
||||||
payload.account?.status,
|
payload.account?.status,
|
||||||
payload.account?.email || payload.account?.name || '',
|
payload.account?.email || payload.account?.name || '',
|
||||||
active.cascadeId,
|
active.cascadeId,
|
||||||
...agents.map((agent) => agent.agentId),
|
...agents.map((agent) => agent.agentId),
|
||||||
];
|
];
|
||||||
const previous = lastDisplaySteps;
|
const previous = displayStepsCache.get(cacheKey);
|
||||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||||
({ revision, steps: projected } = previous);
|
({ revision, steps: projected } = previous);
|
||||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||||
|
displayStepsCache.delete(cacheKey);
|
||||||
|
displayStepsCache.set(cacheKey, previous);
|
||||||
} else {
|
} else {
|
||||||
revision = randomUUID();
|
revision = randomUUID();
|
||||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||||
lastDisplaySteps = { scope, steps: projected, revision,
|
if (!displayStepsCache.has(cacheKey) && displayStepsCache.size >= MAX_DISPLAY_STEP_CACHE_ENTRIES) {
|
||||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
displayStepsCache.delete(displayStepsCache.keys().next().value);
|
||||||
|
}
|
||||||
|
displayStepsCache.delete(cacheKey);
|
||||||
|
displayStepsCache.set(cacheKey, {
|
||||||
|
scope,
|
||||||
|
steps: projected,
|
||||||
|
revision,
|
||||||
|
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||||
@@ -452,6 +417,8 @@ export function executeRebuildCacheAction() {
|
|||||||
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
displayStepsCache.clear();
|
||||||
|
clearScannerRuntimeMemos();
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -491,41 +458,59 @@ export async function executeAccountCredentialAction(data) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
export async function executeBridgeRelaunchAction() {
|
||||||
if (pathname === '/api/telemetry' && method === 'GET') {
|
ensureIdeRemoteDebuggingArgv({ enabled: true });
|
||||||
return executeTelemetryAction(data, opts);
|
await ensureDesktopLaunchEntriesConfigured({ enabled: true }).catch(() => {});
|
||||||
}
|
const result = await triggerDesktopHostRelaunch({
|
||||||
if (pathname === '/api/settings' && method === 'POST') {
|
stalePortFiles: resolveDevToolsPortCandidates(),
|
||||||
return executeSettingsAction(data);
|
});
|
||||||
}
|
|
||||||
if (pathname === '/api/accounts' && method === 'GET') {
|
|
||||||
return executeAccountCredentialAction();
|
|
||||||
}
|
|
||||||
if (pathname === '/api/accounts/update' && method === 'POST') {
|
|
||||||
return executeAccountCredentialAction(data);
|
|
||||||
}
|
|
||||||
if (pathname === '/api/context-window' && method === 'POST') {
|
|
||||||
return executeModelContextWindowAction(data);
|
|
||||||
}
|
|
||||||
if (pathname === '/api/settings/reset' && method === 'POST') {
|
|
||||||
return executeResetSettingsAction();
|
|
||||||
}
|
|
||||||
if (pathname === '/api/cache/rebuild' && method === 'POST') {
|
|
||||||
return executeRebuildCacheAction();
|
|
||||||
}
|
|
||||||
if (pathname === '/api/cloud-sync' && method === 'POST') {
|
|
||||||
return executeCloudSyncAction();
|
|
||||||
}
|
|
||||||
if (pathname === '/api/plugin-update' && method === 'POST') {
|
|
||||||
return executePluginUpdateAction();
|
|
||||||
}
|
|
||||||
return {
|
return {
|
||||||
status: 404,
|
status: result.ok ? 200 : Number(result.status || 500),
|
||||||
contentType: 'application/json',
|
contentType: 'application/json',
|
||||||
body: JSON.stringify({ error: 'Not found' }),
|
headers: { 'Cache-Control': 'no-store' },
|
||||||
|
body: JSON.stringify(result),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const BRIDGE_ROUTE_LOOKUP = new Map(
|
||||||
|
BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action])
|
||||||
|
);
|
||||||
|
|
||||||
|
export async function dispatchBridgeApiRequest(pathname, method, data, opts = undefined) {
|
||||||
|
const action = BRIDGE_ROUTE_LOOKUP.get(`${String(method || '').toUpperCase()}:${pathname}`);
|
||||||
|
switch (action) {
|
||||||
|
case 'telemetry':
|
||||||
|
return executeTelemetryAction(data, opts);
|
||||||
|
case 'settings':
|
||||||
|
if (isPlainObject(data) && data.__bridgeAction === 'relaunch') {
|
||||||
|
return executeBridgeRelaunchAction();
|
||||||
|
}
|
||||||
|
return executeSettingsAction(data);
|
||||||
|
case 'accounts_get':
|
||||||
|
return executeAccountCredentialAction();
|
||||||
|
case 'accounts_update':
|
||||||
|
return executeAccountCredentialAction(data);
|
||||||
|
case 'context_window':
|
||||||
|
return executeModelContextWindowAction(data);
|
||||||
|
case 'settings_reset':
|
||||||
|
return executeResetSettingsAction();
|
||||||
|
case 'cache_rebuild':
|
||||||
|
return executeRebuildCacheAction();
|
||||||
|
case 'cloud_sync':
|
||||||
|
return executeCloudSyncAction();
|
||||||
|
case 'plugin_update':
|
||||||
|
return executePluginUpdateAction();
|
||||||
|
case 'bridge_relaunch':
|
||||||
|
return executeBridgeRelaunchAction();
|
||||||
|
default:
|
||||||
|
return {
|
||||||
|
status: 404,
|
||||||
|
contentType: 'application/json',
|
||||||
|
body: JSON.stringify({ error: 'Not found' }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 启动进程级双栖窗口桥接器(兼容 Sidecar 环境与独立后台守护进程环境)。
|
* 启动进程级双栖窗口桥接器(兼容 Sidecar 环境与独立后台守护进程环境)。
|
||||||
*
|
*
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -16,8 +16,16 @@ import { homedir } from 'node:os';
|
|||||||
import { delimiter, dirname, join } from 'node:path';
|
import { delimiter, dirname, join } from 'node:path';
|
||||||
import { pathToFileURL } from 'node:url';
|
import { pathToFileURL } from 'node:url';
|
||||||
import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs';
|
import { HERE, lsRuntimeEndpoint, normalizeLanguageSetting, normalizeTopbarCapsuleSlots } from './config.mjs';
|
||||||
|
import {
|
||||||
const CLI_STATUS_THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
classifyCacheTier,
|
||||||
|
classifySpeedTier,
|
||||||
|
classifyStepCostTier,
|
||||||
|
classifyTtftTier,
|
||||||
|
formatCompactCapsuleCost,
|
||||||
|
formatCompactCapsuleTtft,
|
||||||
|
formatCompactTokens,
|
||||||
|
resolveCapsuleQuotaSlotPct,
|
||||||
|
} from '../shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
// 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符)
|
// 24-bit ANSI 前景 SGR 调色板(透明底色,与桌面端四档语义色阶及 CLI 原生底栏色调对齐,无任何背景填充或非 SGR 控制符)
|
||||||
const SGR_RESET = '\x1b[0m';
|
const SGR_RESET = '\x1b[0m';
|
||||||
@@ -388,165 +396,42 @@ export function ensureCliStatusLineConfigured({
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
function cliStatusSpeedSgr(tokPerSec) {
|
function cliStatusSpeedSgr(tokPerSec) {
|
||||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
const tier = classifySpeedTier(tokPerSec);
|
||||||
return SGR_FG_MUTED;
|
if (tier === 'good') return SGR_FG_GOOD;
|
||||||
}
|
if (tier === 'info') return SGR_FG_INFO;
|
||||||
const v = Number(tokPerSec);
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 60) return SGR_FG_GOOD;
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
if (v >= 35) return SGR_FG_INFO;
|
return SGR_FG_MUTED;
|
||||||
if (v >= 20) return SGR_FG_WARN;
|
|
||||||
return SGR_FG_DANGER;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliStatusCacheSgr(cacheHitPct, promptTokens = null) {
|
function cliStatusCacheSgr(cacheHitPct, promptTokens = null) {
|
||||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) return SGR_FG_MUTED;
|
const tier = classifyCacheTier(cacheHitPct, promptTokens);
|
||||||
const v = Number(cacheHitPct);
|
if (tier === 'good') return SGR_FG_GOOD;
|
||||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) return SGR_FG_MUTED;
|
if (tier === 'info') return SGR_FG_INFO;
|
||||||
if (v >= 85) return SGR_FG_GOOD;
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 65) return SGR_FG_INFO;
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
if (v >= 30) return SGR_FG_WARN;
|
return SGR_FG_MUTED;
|
||||||
return SGR_FG_DANGER;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliStatusCostSgr(costUsd) {
|
function cliStatusCostSgr(costUsd) {
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return SGR_FG_NORMAL;
|
const tier = classifyStepCostTier(costUsd);
|
||||||
const v = Number(costUsd);
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
if (v >= 0.3) return SGR_FG_DANGER;
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 0.15) return SGR_FG_WARN;
|
|
||||||
return SGR_FG_NORMAL;
|
return SGR_FG_NORMAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliStatusTtftSgr(ttftSec) {
|
function cliStatusTtftSgr(ttftSec) {
|
||||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) {
|
const tier = classifyTtftTier(ttftSec);
|
||||||
return SGR_FG_MUTED;
|
if (tier === 'muted') return SGR_FG_MUTED;
|
||||||
}
|
if (tier === 'danger') return SGR_FG_DANGER;
|
||||||
const v = Number(ttftSec);
|
if (tier === 'warn') return SGR_FG_WARN;
|
||||||
if (v >= 30) return SGR_FG_DANGER;
|
|
||||||
if (v >= 18) return SGR_FG_WARN;
|
|
||||||
return SGR_FG_NORMAL;
|
return SGR_FG_NORMAL;
|
||||||
}
|
}
|
||||||
|
|
||||||
function cliFormatCompactCost(costUsd) {
|
const cliFormatCompactCost = formatCompactCapsuleCost;
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
const cliFormatCompactTtft = formatCompactCapsuleTtft;
|
||||||
const val = Math.max(0, Number(costUsd));
|
const cliFormatTokens = formatCompactTokens;
|
||||||
if (val === 0) return '$0.00';
|
const cliResolveQuotaPct = resolveCapsuleQuotaSlotPct;
|
||||||
if (val < 0.001) return '<$0.001';
|
|
||||||
if (val < 1) return `$${val.toFixed(3)}`;
|
|
||||||
if (val < 100) return `$${val.toFixed(2)}`;
|
|
||||||
return `$${Math.round(val)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cliFormatCompactTtft(ttftSec) {
|
|
||||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
|
||||||
const val = Number(ttftSec);
|
|
||||||
if (val < 1) return `${val.toFixed(2)}s`;
|
|
||||||
if (val < 100) return `${val.toFixed(1)}s`;
|
|
||||||
return `${Math.round(val)}s`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cliFormatTokens(num) {
|
|
||||||
const n = Number(num || 0);
|
|
||||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
|
||||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
|
||||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
|
||||||
return String(Math.round(n));
|
|
||||||
}
|
|
||||||
|
|
||||||
function cliResolveQuotaPct(quotas, slotKey) {
|
|
||||||
if (!quotas || typeof quotas !== 'object') return null;
|
|
||||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
|
||||||
const activePool = quotas.activePool || null;
|
|
||||||
const weekly = quotas.weekly || null;
|
|
||||||
|
|
||||||
if (slotKey === 'quota_auto') {
|
|
||||||
const candidates = [];
|
|
||||||
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
|
|
||||||
candidates.push(Number(activePool.remainingPct));
|
|
||||||
}
|
|
||||||
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
|
|
||||||
candidates.push(Number(activePool.weeklyRemainingPct));
|
|
||||||
}
|
|
||||||
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
|
|
||||||
candidates.push(Number(weekly.remainingPct));
|
|
||||||
}
|
|
||||||
if (!candidates.length && pools.length > 0) {
|
|
||||||
for (const p of pools) {
|
|
||||||
if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct));
|
|
||||||
if (p && Number.isFinite(Number(p.weeklyRemainingPct))) {
|
|
||||||
candidates.push(Number(p.weeklyRemainingPct));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (!candidates.length) return null;
|
|
||||||
return Math.max(0, Math.min(100, Math.round(Math.min(...candidates))));
|
|
||||||
}
|
|
||||||
|
|
||||||
const isClaude = slotKey.startsWith('claude_');
|
|
||||||
const isWeekly = slotKey.endsWith('_weekly');
|
|
||||||
let rawPct = null;
|
|
||||||
|
|
||||||
if (isClaude) {
|
|
||||||
const claudePool =
|
|
||||||
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
|
||||||
pools.find((p) =>
|
|
||||||
CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || ''))
|
|
||||||
);
|
|
||||||
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
|
||||||
if (cand != null && Number.isFinite(Number(cand))) {
|
|
||||||
rawPct = Number(cand);
|
|
||||||
} else if (
|
|
||||||
activePool &&
|
|
||||||
CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
|
||||||
) {
|
|
||||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
|
||||||
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const stdGemini =
|
|
||||||
pools.find((p) => p?.poolKey === 'Gemini') ||
|
|
||||||
pools.find(
|
|
||||||
(p) =>
|
|
||||||
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
|
||||||
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
|
||||||
);
|
|
||||||
const geminiFamilyPools = pools.filter((p) =>
|
|
||||||
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
|
||||||
);
|
|
||||||
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
|
||||||
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
|
||||||
rawPct = Number(primaryCand);
|
|
||||||
} else {
|
|
||||||
const familyVals = geminiFamilyPools
|
|
||||||
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
|
||||||
.filter((v) => v != null && Number.isFinite(Number(v)))
|
|
||||||
.map(Number);
|
|
||||||
if (familyVals.length > 0) {
|
|
||||||
rawPct = Math.min(...familyVals);
|
|
||||||
} else if (
|
|
||||||
activePool &&
|
|
||||||
!CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(
|
|
||||||
String(activePool.family || activePool.poolLabel || '')
|
|
||||||
)
|
|
||||||
) {
|
|
||||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
|
||||||
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
rawPct == null &&
|
|
||||||
isWeekly &&
|
|
||||||
weekly &&
|
|
||||||
!CLI_STATUS_THIRD_PARTY_FAMILY_RE.test(String(weekly.poolFamily || '')) &&
|
|
||||||
weekly.remainingPct != null &&
|
|
||||||
Number.isFinite(Number(weekly.remainingPct))
|
|
||||||
) {
|
|
||||||
rawPct = Number(weekly.remainingPct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
|
||||||
return Math.max(0, Math.min(100, Math.round(rawPct)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。
|
* 计算终端可见列宽(剥离 CSI SGR 转义序列,CJK 全角字符按 2 列、`●`/`◎`/`·` 与 ASCII 按 1 列计算)。
|
||||||
|
|||||||
@@ -12,54 +12,9 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSy
|
|||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import { inferCompactionStepModels, normalizeCachedStep } from '../speed-metrics.mjs';
|
import { inferCompactionStepModels, normalizeCachedStep } from '../trajectory-metrics.mjs';
|
||||||
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
import { writeTrajectoryCacheFile } from './trajectory-cache-file.mjs';
|
||||||
import {
|
import { normalizeFullSettings } from './settings-schema.mjs';
|
||||||
DEFAULT_HOVER_MODULES,
|
|
||||||
DEFAULT_OVERVIEW_METRICS,
|
|
||||||
DEFAULT_OVERVIEW_MODULES,
|
|
||||||
DEFAULT_POPOVER_WIDTH,
|
|
||||||
DEFAULT_SETTINGS_SCHEMA,
|
|
||||||
DEFAULT_STEP_TABLE_COLUMNS,
|
|
||||||
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
|
||||||
DEFAULT_TOPBAR_SLOTS,
|
|
||||||
FONT_SCALE_KEYS,
|
|
||||||
MAX_POPOVER_WIDTH,
|
|
||||||
MAX_TOPBAR_SLOTS,
|
|
||||||
MIN_POPOVER_WIDTH,
|
|
||||||
MIN_TOPBAR_SLOTS,
|
|
||||||
MODEL_DISPLAY_MODES,
|
|
||||||
ORCHESTRATOR_ID_MODES,
|
|
||||||
OVERVIEW_METRIC_KEYS,
|
|
||||||
OVERVIEW_MODULE_KEYS,
|
|
||||||
PLUGIN_UPDATE_MODES,
|
|
||||||
POPOVER_WIDTH_MODES,
|
|
||||||
STEP_TABLE_COLUMN_KEYS,
|
|
||||||
SUPPORTED_LANGUAGES,
|
|
||||||
THEME_ACCENT_KEYS,
|
|
||||||
TOPBAR_SLOT_KEYS,
|
|
||||||
WINDOW_MOUNT_MODES,
|
|
||||||
createDefaultSettingsObject,
|
|
||||||
normalizeFontScale,
|
|
||||||
normalizeFullSettings,
|
|
||||||
normalizeHoverModules,
|
|
||||||
normalizeLanguageSetting,
|
|
||||||
normalizeModelDisplayMode,
|
|
||||||
normalizeOrchestratorIdMode,
|
|
||||||
normalizeOverviewMetrics,
|
|
||||||
normalizeOverviewModules,
|
|
||||||
normalizePluginUpdateMode,
|
|
||||||
normalizePopoverWidth,
|
|
||||||
normalizePopoverWidthMode,
|
|
||||||
normalizeStandalonePort,
|
|
||||||
normalizeStepTableColumns,
|
|
||||||
normalizeStepTokenComboFormat,
|
|
||||||
normalizeThemeAccent,
|
|
||||||
normalizeTopbarCapsuleSlots,
|
|
||||||
normalizeWeeklyLimitMode,
|
|
||||||
normalizeWindowMountMode,
|
|
||||||
parseStepTokenComboSegments,
|
|
||||||
} from './settings-schema.mjs';
|
|
||||||
|
|
||||||
export {
|
export {
|
||||||
DEFAULT_HOVER_MODULES,
|
DEFAULT_HOVER_MODULES,
|
||||||
@@ -75,17 +30,12 @@ export {
|
|||||||
MAX_TOPBAR_SLOTS,
|
MAX_TOPBAR_SLOTS,
|
||||||
MIN_POPOVER_WIDTH,
|
MIN_POPOVER_WIDTH,
|
||||||
MIN_TOPBAR_SLOTS,
|
MIN_TOPBAR_SLOTS,
|
||||||
MODEL_DISPLAY_MODES,
|
|
||||||
ORCHESTRATOR_ID_MODES,
|
|
||||||
OVERVIEW_METRIC_KEYS,
|
OVERVIEW_METRIC_KEYS,
|
||||||
OVERVIEW_MODULE_KEYS,
|
OVERVIEW_MODULE_KEYS,
|
||||||
PLUGIN_UPDATE_MODES,
|
|
||||||
POPOVER_WIDTH_MODES,
|
|
||||||
STEP_TABLE_COLUMN_KEYS,
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
SUPPORTED_LANGUAGES,
|
SUPPORTED_LANGUAGES,
|
||||||
THEME_ACCENT_KEYS,
|
THEME_ACCENT_KEYS,
|
||||||
TOPBAR_SLOT_KEYS,
|
TOPBAR_SLOT_KEYS,
|
||||||
WINDOW_MOUNT_MODES,
|
|
||||||
createDefaultSettingsObject,
|
createDefaultSettingsObject,
|
||||||
normalizeFontScale,
|
normalizeFontScale,
|
||||||
normalizeFullSettings,
|
normalizeFullSettings,
|
||||||
@@ -272,6 +222,55 @@ export const DEFAULT_DOWNLOAD_URL =
|
|||||||
export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
export const DEFAULT_ARCHIVE_FALLBACK_URL =
|
||||||
`https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`;
|
`https://codeload.github.com/${OFFICIAL_GITHUB_REPO}/zip/refs/heads/main`;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测当前插件目录是否关联了非官方自定义 GitHub Fork 远端(如二次开发分支)。
|
||||||
|
* 命中自定义 Fork 时保留上游价格目录热同步,但将插件版本号与更新包地址锚定至用户自己的 Fork,避免误报更新。
|
||||||
|
*
|
||||||
|
* @returns {string} 自定义 Fork 的 `owner/repo`,未命中或为官方仓库时返回 `''`
|
||||||
|
*/
|
||||||
|
export function detectCustomGitForkRepo() {
|
||||||
|
try {
|
||||||
|
const dotGitPath = join(PLUGIN_ROOT, '.git');
|
||||||
|
if (!existsSync(dotGitPath)) return '';
|
||||||
|
let gitConfigPath = join(dotGitPath, 'config');
|
||||||
|
if (!existsSync(gitConfigPath)) {
|
||||||
|
const ptrText = readFileSync(dotGitPath, 'utf8');
|
||||||
|
const m = typeof ptrText === 'string' && ptrText.match(/^gitdir:\s*(.+)$/im);
|
||||||
|
if (m) {
|
||||||
|
const gitDir = m[1].trim();
|
||||||
|
const commonDirFile = join(gitDir, 'commondir');
|
||||||
|
if (existsSync(commonDirFile)) {
|
||||||
|
const relCommon = String(readFileSync(commonDirFile, 'utf8') || '').trim();
|
||||||
|
gitConfigPath = join(gitDir, relCommon, 'config');
|
||||||
|
} else {
|
||||||
|
gitConfigPath = join(gitDir, 'config');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!existsSync(gitConfigPath)) return '';
|
||||||
|
const cfg = readFileSync(gitConfigPath, 'utf8');
|
||||||
|
if (typeof cfg !== 'string' || !cfg) return '';
|
||||||
|
const originBlock = cfg.match(/\[remote\s+"origin"\]([\s\S]*?)(?:\r?\n\[|$)/i);
|
||||||
|
if (!originBlock) return '';
|
||||||
|
const urlMatch = originBlock[1].match(/^\s*url\s*=\s*(.+)$/im);
|
||||||
|
if (!urlMatch) return '';
|
||||||
|
const rawUrl = urlMatch[1].trim();
|
||||||
|
const ghMatch = rawUrl.match(/github\.com[:/]([^/\s]+\/[^/\s]+?)(?:\.git)?\/?$/i);
|
||||||
|
if (!ghMatch) return '';
|
||||||
|
const repo = ghMatch[1];
|
||||||
|
const lower = repo.toLowerCase();
|
||||||
|
if (
|
||||||
|
lower === OFFICIAL_GITHUB_REPO.toLowerCase() ||
|
||||||
|
LEGACY_GITHUB_REPOS.some((r) => r.toLowerCase() === lower)
|
||||||
|
) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
return repo;
|
||||||
|
} catch {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */
|
/** 云端目录常规自动检查间隔(6 小时)与失败冷却时间(5 分钟)。 */
|
||||||
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
export const CLOUD_SYNC_TTL_MS = 6 * 3600 * 1000;
|
||||||
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
export const CLOUD_SYNC_RETRY_COOLDOWN_MS = 5 * 60 * 1000;
|
||||||
@@ -359,20 +358,22 @@ export function computeRuntimeCodeVersion() {
|
|||||||
join(HERE, 'bridge-daemon.mjs'),
|
join(HERE, 'bridge-daemon.mjs'),
|
||||||
join(HERE, 'mcp-entry.mjs'),
|
join(HERE, 'mcp-entry.mjs'),
|
||||||
join(HERE, 'cli-statusline.mjs'),
|
join(HERE, 'cli-statusline.mjs'),
|
||||||
join(HERE, 'speed-metrics.mjs'),
|
join(HERE, 'trajectory-metrics.mjs'),
|
||||||
LOCAL_CATALOG_FILE,
|
LOCAL_CATALOG_FILE,
|
||||||
];
|
];
|
||||||
const backendDir = join(HERE, 'backend');
|
for (const subDir of ['shared', 'backend']) {
|
||||||
try {
|
const absDir = join(HERE, subDir);
|
||||||
if (existsSync(backendDir)) {
|
try {
|
||||||
for (const name of readdirSync(backendDir)) {
|
if (existsSync(absDir)) {
|
||||||
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
for (const name of readdirSync(absDir)) {
|
||||||
candidates.push(join(backendDir, name));
|
if (name.endsWith('.mjs') || name.endsWith('.js')) {
|
||||||
|
candidates.push(join(absDir, name));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略目录列举异常
|
||||||
}
|
}
|
||||||
} catch {
|
|
||||||
// 忽略目录列举异常
|
|
||||||
}
|
}
|
||||||
for (const file of candidates) {
|
for (const file of candidates) {
|
||||||
try {
|
try {
|
||||||
@@ -397,7 +398,10 @@ let initialCacheMigrated =
|
|||||||
loadedTrajectoryCache !== undefined &&
|
loadedTrajectoryCache !== undefined &&
|
||||||
!isPlainObject(loadedTrajectoryCache);
|
!isPlainObject(loadedTrajectoryCache);
|
||||||
|
|
||||||
const safeCacheEntries = [];
|
/**
|
||||||
|
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
||||||
|
*/
|
||||||
|
const trajectoryCache = Object.create(null);
|
||||||
if (isPlainObject(loadedTrajectoryCache)) {
|
if (isPlainObject(loadedTrajectoryCache)) {
|
||||||
for (const [id, entry] of Object.entries(loadedTrajectoryCache)) {
|
for (const [id, entry] of Object.entries(loadedTrajectoryCache)) {
|
||||||
if (!id || !isPlainObject(entry)) {
|
if (!id || !isPlainObject(entry)) {
|
||||||
@@ -424,27 +428,118 @@ if (isPlainObject(loadedTrajectoryCache)) {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
safeCacheEntries.push([
|
trajectoryCache[id] = { ...entry, steps: finalSteps };
|
||||||
id,
|
}
|
||||||
{
|
}
|
||||||
...entry,
|
|
||||||
steps: finalSteps,
|
export function getCachedTrajectory(cascadeId) {
|
||||||
},
|
return trajectoryCache[cascadeId];
|
||||||
]);
|
}
|
||||||
|
|
||||||
|
export function listCachedTrajectoryEntries() {
|
||||||
|
return Object.entries(trajectoryCache);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCachedTrajectory(cascadeId, entry) {
|
||||||
|
trajectoryCache[cascadeId] = entry;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function removeCachedTrajectory(cascadeId) {
|
||||||
|
delete trajectoryCache[cascadeId];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缓存状态与外部深层统计缓存 Memo。
|
||||||
|
* 运行中会话采用 30 秒节流落盘(转入 IDLE、重建缓存或进程退出时立即刷盘),消除高频文件替换开销。
|
||||||
|
*/
|
||||||
|
export const CACHE_RUNNING_SAVE_INTERVAL_MS = 30_000;
|
||||||
|
|
||||||
|
const cacheState = {
|
||||||
|
needsSave: initialCacheMigrated,
|
||||||
|
lastSavedAtMs: 0,
|
||||||
|
flushTimer: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
export function hasPendingTrajectoryCacheSave() {
|
||||||
|
return cacheState.needsSave;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cancelPendingCacheFlushTimer() {
|
||||||
|
if (cacheState.flushTimer) {
|
||||||
|
try {
|
||||||
|
clearTimeout(cacheState.flushTimer);
|
||||||
|
} catch {
|
||||||
|
// 忽略沙箱无 clearTimeout 异常
|
||||||
|
}
|
||||||
|
cacheState.flushTimer = null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 内存中的会话轨迹步骤缓存:`cascadeId -> { signature, accountName, title, lastModifiedMs, diskMtimeMs, wasRunning, steps }`
|
* 立即将当前内存态 `trajectoryCache` 原子刷入磁盘并清理挂起定时器。
|
||||||
|
*
|
||||||
|
* @returns {boolean}
|
||||||
*/
|
*/
|
||||||
export const trajectoryCache = Object.fromEntries(safeCacheEntries);
|
export function flushTrajectoryCacheNow() {
|
||||||
|
cancelPendingCacheFlushTimer();
|
||||||
|
const ok = saveJson(CACHE_FILE, trajectoryCache);
|
||||||
|
cacheState.needsSave = !ok;
|
||||||
|
if (ok) {
|
||||||
|
cacheState.lastSavedAtMs = Date.now();
|
||||||
|
}
|
||||||
|
return ok;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 缓存状态与外部深层统计缓存 Memo。
|
* 按当前是否存在运行中会话决定立即写盘还是 30 秒节流延迟写盘。
|
||||||
|
* 默认单元测试沙箱(`lsRuntimeEndpoint.addr === 'test.invalid'`)同步落盘以保持断言确定性。
|
||||||
|
*
|
||||||
|
* @param {{ hasRunningSessions?: boolean, allowThrottleInTest?: boolean }} [options={}]
|
||||||
*/
|
*/
|
||||||
export const cacheState = {
|
export function persistTrajectoryCacheIfNeeded({
|
||||||
needsSave: initialCacheMigrated,
|
hasRunningSessions = false,
|
||||||
};
|
allowThrottleInTest = false,
|
||||||
|
} = {}) {
|
||||||
|
if (
|
||||||
|
(lsRuntimeEndpoint.addr === 'test.invalid' && !allowThrottleInTest) ||
|
||||||
|
typeof setTimeout !== 'function'
|
||||||
|
) {
|
||||||
|
flushTrajectoryCacheNow();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const nowMs = Date.now();
|
||||||
|
const elapsedMs = nowMs - (cacheState.lastSavedAtMs || 0);
|
||||||
|
if (
|
||||||
|
!hasRunningSessions ||
|
||||||
|
cacheState.lastSavedAtMs === 0 ||
|
||||||
|
elapsedMs >= CACHE_RUNNING_SAVE_INTERVAL_MS
|
||||||
|
) {
|
||||||
|
flushTrajectoryCacheNow();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cacheState.needsSave = true;
|
||||||
|
if (!cacheState.flushTimer) {
|
||||||
|
const delayMs = Math.max(100, CACHE_RUNNING_SAVE_INTERVAL_MS - elapsedMs);
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
cacheState.flushTimer = null;
|
||||||
|
if (cacheState.needsSave) {
|
||||||
|
flushTrajectoryCacheNow();
|
||||||
|
}
|
||||||
|
}, delayMs);
|
||||||
|
if (timer && typeof timer.unref === 'function') {
|
||||||
|
timer.unref();
|
||||||
|
}
|
||||||
|
cacheState.flushTimer = timer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof process !== 'undefined' && typeof process?.once === 'function') {
|
||||||
|
process.once('exit', () => {
|
||||||
|
if (cacheState.needsSave) {
|
||||||
|
flushTrajectoryCacheNow();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export const externalDeepStatsMemo = {
|
export const externalDeepStatsMemo = {
|
||||||
sig: '',
|
sig: '',
|
||||||
@@ -454,6 +549,10 @@ export const externalDeepStatsMemo = {
|
|||||||
export const localSummaryMemo = {
|
export const localSummaryMemo = {
|
||||||
sig: '',
|
sig: '',
|
||||||
byId: new Map(),
|
byId: new Map(),
|
||||||
|
available: false,
|
||||||
|
summariesObj: {},
|
||||||
|
sideQuestionParents: {},
|
||||||
|
byRootsKey: new Map(),
|
||||||
};
|
};
|
||||||
|
|
||||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||||
@@ -498,23 +597,31 @@ export const pluginUpdateState = {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* 清空内存态轨迹缓存、外部深层统计 Memo 与配额摘要短期缓存,并将磁盘缓存重置为空对象。
|
* 清空内存态轨迹缓存、外部深层统计 Memo 与配额摘要短期缓存,并将磁盘缓存重置为空对象。
|
||||||
|
* 空缓存落盘成功后再清理内存,写入失败时可继续使用内存数据并重试。
|
||||||
*
|
*
|
||||||
* @returns {boolean} 是否成功写回空白缓存文件
|
* @returns {boolean} 是否成功写回空白缓存文件
|
||||||
*/
|
*/
|
||||||
export function clearRuntimeCaches() {
|
export function clearRuntimeCaches() {
|
||||||
|
if (!saveJson(CACHE_FILE, {})) return false;
|
||||||
|
cancelPendingCacheFlushTimer();
|
||||||
for (const key of Object.keys(trajectoryCache)) {
|
for (const key of Object.keys(trajectoryCache)) {
|
||||||
delete trajectoryCache[key];
|
delete trajectoryCache[key];
|
||||||
}
|
}
|
||||||
cacheState.needsSave = false;
|
cacheState.needsSave = false;
|
||||||
|
cacheState.lastSavedAtMs = 0;
|
||||||
externalDeepStatsMemo.sig = '';
|
externalDeepStatsMemo.sig = '';
|
||||||
externalDeepStatsMemo.convos.clear();
|
externalDeepStatsMemo.convos.clear();
|
||||||
localSummaryMemo.sig = '';
|
localSummaryMemo.sig = '';
|
||||||
localSummaryMemo.byId.clear();
|
localSummaryMemo.byId.clear();
|
||||||
|
localSummaryMemo.available = false;
|
||||||
|
localSummaryMemo.summariesObj = {};
|
||||||
|
localSummaryMemo.sideQuestionParents = {};
|
||||||
|
localSummaryMemo.byRootsKey.clear();
|
||||||
quotaSummaryCache.ts = 0;
|
quotaSummaryCache.ts = 0;
|
||||||
quotaSummaryCache.lastAttemptTs = 0;
|
quotaSummaryCache.lastAttemptTs = 0;
|
||||||
quotaSummaryCache.accountName = '';
|
quotaSummaryCache.accountName = '';
|
||||||
quotaSummaryCache.accountGeneration += 1;
|
quotaSummaryCache.accountGeneration += 1;
|
||||||
quotaSummaryCache.data = null;
|
quotaSummaryCache.data = null;
|
||||||
quotaSummaryCache.error = null;
|
quotaSummaryCache.error = null;
|
||||||
return saveJson(CACHE_FILE, {});
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
/** @fileoverview 宿主上报的模型上下文档位与逐次请求配置。 */
|
||||||
|
|
||||||
|
import { CONTEXT_WINDOWS_GLOBAL_KEY } from '../shared/window-bridge-protocol.mjs';
|
||||||
|
|
||||||
export function isContextWindowModelId(value) {
|
export function isContextWindowModelId(value) {
|
||||||
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
return typeof value === 'string' && /^MODEL_[A-Z0-9_]{1,120}$/.test(value) &&
|
||||||
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
value !== 'MODEL_UNSPECIFIED' && value !== 'MODEL_UNKNOWN';
|
||||||
@@ -77,7 +79,7 @@ export function getContextWindowGroups(models) {
|
|||||||
}));
|
}));
|
||||||
const capacity = Math.min(...members.map((member) => member.capacity));
|
const capacity = Math.min(...members.map((member) => member.capacity));
|
||||||
if (!options.length && capacity) {
|
if (!options.length && capacity) {
|
||||||
for (const tokens of new Set([128000, 256000, 512000, 768000, 900000, capacity])) {
|
for (const tokens of new Set([128000, 256000, 384000, 512000, 768000, 900000, capacity])) {
|
||||||
if (tokens <= capacity && !options.some(({ name }) => name === String(tokens))) {
|
if (tokens <= capacity && !options.some(({ name }) => name === String(tokens))) {
|
||||||
options.push({ name: String(tokens), tokens });
|
options.push({ name: String(tokens), tokens });
|
||||||
}
|
}
|
||||||
@@ -115,14 +117,24 @@ export function resolveContextWindowRules(models, preferences) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
// 在宿主聊天窗口执行;只改发往当前 LS 的提交请求,模型 ID 必须完全匹配。
|
||||||
export async function syncHostContextWindows(rules, bootId) {
|
export async function syncHostContextWindows(
|
||||||
const key = '__AGUsageMonitorContextWindows';
|
rules,
|
||||||
|
bootId,
|
||||||
|
key = '__AGUsageMonitorContextWindows',
|
||||||
|
fallbackRules = {}
|
||||||
|
) {
|
||||||
let state = window[key];
|
let state = window[key];
|
||||||
const appConfig = window.__APP_CONFIG__;
|
const appConfig = window.__APP_CONFIG__;
|
||||||
const csrfToken = appConfig?.csrfToken;
|
const csrfToken = appConfig?.csrfToken;
|
||||||
if (!Object.keys(rules).length || !csrfToken || appConfig.isRemoteControl) {
|
const hasPrefs = Boolean(rules && Object.keys(rules).length > 0);
|
||||||
|
const safeFallback =
|
||||||
|
fallbackRules && typeof fallbackRules === 'object' && !Array.isArray(fallbackRules)
|
||||||
|
? fallbackRules
|
||||||
|
: {};
|
||||||
|
const hasFallback = Object.keys(safeFallback).length > 0;
|
||||||
|
if (!hasPrefs || appConfig?.isRemoteControl || (!csrfToken && !hasFallback)) {
|
||||||
state?.dispose();
|
state?.dispose();
|
||||||
return;
|
return { attached: false, ruleCount: 0 };
|
||||||
}
|
}
|
||||||
if (state && (state.bootId !== bootId || !state.isAttached?.())) {
|
if (state && (state.bootId !== bootId || !state.isAttached?.())) {
|
||||||
state.dispose();
|
state.dispose();
|
||||||
@@ -131,6 +143,8 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
if (!state) {
|
if (!state) {
|
||||||
const servicePath = '/exa.language_server_pb.LanguageServerService/';
|
const servicePath = '/exa.language_server_pb.LanguageServerService/';
|
||||||
const sendPath = servicePath + 'SendUserCascadeMessage';
|
const sendPath = servicePath + 'SendUserCascadeMessage';
|
||||||
|
const startPath = servicePath + 'StartCascade';
|
||||||
|
const isTargetProcedure = (p) => p === sendPath || p === startPath;
|
||||||
const nativeFetch = window.fetch;
|
const nativeFetch = window.fetch;
|
||||||
const wsProto = window.WebSocket?.prototype;
|
const wsProto = window.WebSocket?.prototype;
|
||||||
const nativeSend = wsProto?.send;
|
const nativeSend = wsProto?.send;
|
||||||
@@ -155,11 +169,20 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function rewriteBody(body, contentType) {
|
function rewriteBody(body, contentType) {
|
||||||
if (contentType === 'application/json' && typeof body === 'string') {
|
if (contentType === 'application/json') {
|
||||||
const json = JSON.parse(body);
|
if (typeof body === 'string') {
|
||||||
if (updatePayload(json)) return JSON.stringify(json);
|
const json = JSON.parse(body);
|
||||||
} else if (contentType === 'application/grpc-web+json' && body instanceof Uint8Array &&
|
if (updatePayload(json)) return JSON.stringify(json);
|
||||||
body.length >= 5 && body[0] === 0) {
|
} else if (body instanceof Uint8Array) {
|
||||||
|
const json = JSON.parse(decoder.decode(body));
|
||||||
|
if (updatePayload(json)) return encoder.encode(JSON.stringify(json));
|
||||||
|
}
|
||||||
|
} else if (
|
||||||
|
(contentType === 'application/grpc-web+json' || contentType === 'application/connect+json') &&
|
||||||
|
body instanceof Uint8Array &&
|
||||||
|
body.length >= 5 &&
|
||||||
|
body[0] === 0
|
||||||
|
) {
|
||||||
const header = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
const header = new DataView(body.buffer, body.byteOffset, body.byteLength);
|
||||||
if (header.getUint32(1) !== body.length - 5) return body;
|
if (header.getUint32(1) !== body.length - 5) return body;
|
||||||
const json = JSON.parse(decoder.decode(body.subarray(5)));
|
const json = JSON.parse(decoder.decode(body.subarray(5)));
|
||||||
@@ -176,9 +199,15 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
function fetchWithContextWindow(input, init) {
|
function fetchWithContextWindow(input, init) {
|
||||||
let nextInit = init;
|
let nextInit = init;
|
||||||
try {
|
try {
|
||||||
if (typeof input === 'string' && init?.method === 'POST') {
|
const rawUrl =
|
||||||
const url = new URL(input, window.location.href);
|
typeof input === 'string'
|
||||||
if (url.origin === window.location.origin && url.pathname === sendPath) {
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.href
|
||||||
|
: '';
|
||||||
|
if (rawUrl && init?.method === 'POST') {
|
||||||
|
const url = new URL(rawUrl, window.location.href);
|
||||||
|
if (url.origin === window.location.origin && isTargetProcedure(url.pathname)) {
|
||||||
const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim();
|
const type = new Headers(init.headers).get('content-type')?.split(';')[0].trim();
|
||||||
const body = rewriteBody(init.body, type);
|
const body = rewriteBody(init.body, type);
|
||||||
if (body !== init.body) nextInit = { ...init, body };
|
if (body !== init.body) nextInit = { ...init, body };
|
||||||
@@ -195,13 +224,13 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
function sendWithContextWindow(data) {
|
function sendWithContextWindow(data) {
|
||||||
let nextData = data;
|
let nextData = data;
|
||||||
try {
|
try {
|
||||||
if (typeof data === 'string' && data.includes(sendPath)) {
|
if (typeof data === 'string' && (data.includes(sendPath) || data.includes(startPath))) {
|
||||||
const url = new URL(this.url);
|
const url = new URL(this.url);
|
||||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||||
if (url.protocol === protocol && url.host === window.location.host &&
|
if (url.protocol === protocol && url.host === window.location.host &&
|
||||||
url.pathname === '/connect-websocket') {
|
url.pathname === '/connect-websocket') {
|
||||||
const frame = JSON.parse(data);
|
const frame = JSON.parse(data);
|
||||||
if (frame.type === 'start' && frame.stream === false && frame.procedure === sendPath &&
|
if (frame.type === 'start' && frame.stream === false && isTargetProcedure(frame.procedure) &&
|
||||||
updatePayload(frame.payload)) {
|
updatePayload(frame.payload)) {
|
||||||
nextData = JSON.stringify(frame);
|
nextData = JSON.stringify(frame);
|
||||||
}
|
}
|
||||||
@@ -215,7 +244,7 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
|
|
||||||
state = window[key] = {
|
state = window[key] = {
|
||||||
bootId,
|
bootId,
|
||||||
rules: {},
|
rules: { ...safeFallback },
|
||||||
serviceUrl: window.location.origin + servicePath,
|
serviceUrl: window.location.origin + servicePath,
|
||||||
isAttached() {
|
isAttached() {
|
||||||
return (typeof nativeFetch !== 'function' || window.fetch === fetchWithContextWindow) &&
|
return (typeof nativeFetch !== 'function' || window.fetch === fetchWithContextWindow) &&
|
||||||
@@ -233,12 +262,18 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
if (typeof nativeSend === 'function') wsProto.send = sendWithContextWindow;
|
if (typeof nativeSend === 'function') wsProto.send = sendWithContextWindow;
|
||||||
}
|
}
|
||||||
state.preferences = rules;
|
state.preferences = rules;
|
||||||
|
state.fallbackRules = safeFallback;
|
||||||
clearTimeout(state.timer);
|
clearTimeout(state.timer);
|
||||||
state.timer = setTimeout(() => state.dispose(), 15000);
|
state.timer = setTimeout(() => state.dispose(), 15000);
|
||||||
|
|
||||||
// App 和 IDE 同时打开时,各窗口只使用自身宿主上报的档位。
|
if (!csrfToken) {
|
||||||
|
state.rules = { ...safeFallback };
|
||||||
|
return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length };
|
||||||
|
}
|
||||||
|
|
||||||
|
// App 和 IDE 同时打开时,各窗口优先使用自身宿主上报的档位;若窗口内查询异常则回退后端预解析规则。
|
||||||
if (state.csrfToken !== csrfToken || Date.now() >= state.refreshAt) {
|
if (state.csrfToken !== csrfToken || Date.now() >= state.refreshAt) {
|
||||||
if (state.csrfToken !== csrfToken) state.rules = {};
|
if (state.csrfToken !== csrfToken) state.rules = { ...safeFallback };
|
||||||
state.csrfToken = csrfToken;
|
state.csrfToken = csrfToken;
|
||||||
state.refreshAt = Date.now() + 10000;
|
state.refreshAt = Date.now() + 10000;
|
||||||
state.status = (async () => {
|
state.status = (async () => {
|
||||||
@@ -259,19 +294,25 @@ export async function syncHostContextWindows(rules, bootId) {
|
|||||||
]);
|
]);
|
||||||
const userStatus = status?.userStatus;
|
const userStatus = status?.userStatus;
|
||||||
const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
const configs = userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||||
|
if (!Array.isArray(configs)) return null;
|
||||||
return getContextWindowModels(configs, catalog?.response?.models);
|
return getContextWindowModels(configs, catalog?.response?.models);
|
||||||
} catch {
|
} catch {
|
||||||
return [];
|
return null;
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
const status = state.status;
|
const status = state.status;
|
||||||
const models = await status;
|
const models = await status;
|
||||||
if (window[key] !== state || state.status !== status) return;
|
if (window[key] !== state || state.status !== status) {
|
||||||
state.rules = resolveContextWindowRules(models, state.preferences);
|
return { attached: Boolean(state?.isAttached?.()), ruleCount: Object.keys(state?.rules || {}).length };
|
||||||
|
}
|
||||||
|
state.rules = Array.isArray(models)
|
||||||
|
? resolveContextWindowRules(models, state.preferences)
|
||||||
|
: { ...state.fallbackRules };
|
||||||
|
return { attached: Boolean(state.isAttached?.()), ruleCount: Object.keys(state.rules).length };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createContextWindowSyncExpression(preferences, bootId) {
|
export function createContextWindowSyncExpression(preferences, bootId, fallbackRules = {}) {
|
||||||
return `(() => {
|
return `(() => {
|
||||||
${isContextWindowModelId.toString()}
|
${isContextWindowModelId.toString()}
|
||||||
${isContextWindowSettingId.toString()}
|
${isContextWindowSettingId.toString()}
|
||||||
@@ -280,6 +321,6 @@ export function createContextWindowSyncExpression(preferences, bootId) {
|
|||||||
${getContextWindowGroups.toString()}
|
${getContextWindowGroups.toString()}
|
||||||
${resolveContextWindowOption.toString()}
|
${resolveContextWindowOption.toString()}
|
||||||
${resolveContextWindowRules.toString()}
|
${resolveContextWindowRules.toString()}
|
||||||
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)});
|
return (${syncHostContextWindows.toString()})(${JSON.stringify(preferences)}, ${JSON.stringify(bootId)}, ${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}, ${JSON.stringify(fallbackRules || {})});
|
||||||
})()`;
|
})()`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,995 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Antigravity Desktop 2.33.0+ 跨平台启动入口自动补齐与一键带参重拉控制器。
|
||||||
|
*
|
||||||
|
* 背景:
|
||||||
|
* Antigravity Desktop (`Antigravity.exe` / `Antigravity.app` / `antigravity`) 自 `2.33.0` 起
|
||||||
|
* 默认不再于启动时开启 `--remote-debugging-port=0`,且独立 Electron 桌面端不读取 VS Code 系的 `argv.json`。
|
||||||
|
*
|
||||||
|
* 本模块在不触碰任何宿主二进制与 `app.asar` 的前提下,提供两层无感恢复能力:
|
||||||
|
* 1. 日常全自动层 (`ensureDesktopLaunchEntriesConfigured`):
|
||||||
|
* - Windows:自动为当前用户的桌面(含 OneDrive 重定向桌面)、开始菜单、任务栏固定图标、启动文件夹中的
|
||||||
|
* `Antigravity.lnk` 快捷方式及已存在的 `HKCU\...\Run` 自启项补齐 `--remote-debugging-port=0`;
|
||||||
|
* - Linux:自动在 `~/.local/share/applications/antigravity.desktop`(必要时自系统目录复制)与
|
||||||
|
* `~/.config/autostart/antigravity.desktop` 的 `Exec=` 中补齐 `--remote-debugging-port=0`;
|
||||||
|
* - 当用户切回「仅侧边栏」且无上下文窗口覆写时,可干净移除本插件托管的 `--remote-debugging-port=0`,绝不触碰用户自定义端口;
|
||||||
|
* 2. 当下裸启动会话一键重拉层 (`triggerDesktopHostRelaunch`):
|
||||||
|
* - Windows 通过 `Shell.Application` (`explorer.exe` 进程外 COM) 脱离宿主 Job Object 托管生命周期,
|
||||||
|
* macOS / Linux 通过独立会话 `nohup` 脱离进程组,自动退出系统托盘常驻实例、清理陈旧 `DevToolsActivePort`
|
||||||
|
* 并以纯净桌面环境变量追加 `--remote-debugging-port=0` 重新拉起宿主客户端。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||||
|
import { homedir } from 'node:os';
|
||||||
|
import { basename, dirname, join } from 'node:path';
|
||||||
|
import { DATA_DIR, lsRuntimeEndpoint } from './config.mjs';
|
||||||
|
|
||||||
|
export const REMOTE_DEBUG_LAUNCH_FLAG = '--remote-debugging-port=0';
|
||||||
|
|
||||||
|
const REMOTE_DEBUG_ANY_RE = /(?:^|\s)--remote-debugging-port(?:=|\s|$)/i;
|
||||||
|
const REMOTE_DEBUG_MANAGED_ZERO_RE = /(?:^|\s+)--remote-debugging-port=(?:"0"|'0'|0)(?=\s|$)/gi;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 在命令行参数字符串中幂等补齐或移除托管的 `--remote-debugging-port=0`,保留用户自定义的其它参数或自定义端口。
|
||||||
|
*
|
||||||
|
* @param {unknown} rawArgs
|
||||||
|
* @param {{ enabled?: boolean }} [options]
|
||||||
|
* @returns {{ changed: boolean, configured: boolean, alreadyConfigured?: boolean, removed?: boolean, args: string }}
|
||||||
|
*/
|
||||||
|
export function ensureRemoteDebugFlagInArgs(rawArgs, { enabled = true } = {}) {
|
||||||
|
const current = String(rawArgs ?? '').trim();
|
||||||
|
if (enabled) {
|
||||||
|
if (REMOTE_DEBUG_ANY_RE.test(current)) {
|
||||||
|
return {
|
||||||
|
changed: false,
|
||||||
|
configured: true,
|
||||||
|
alreadyConfigured: true,
|
||||||
|
args: current,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const nextArgs = current
|
||||||
|
? `${current} ${REMOTE_DEBUG_LAUNCH_FLAG}`
|
||||||
|
: REMOTE_DEBUG_LAUNCH_FLAG;
|
||||||
|
return {
|
||||||
|
changed: true,
|
||||||
|
configured: true,
|
||||||
|
args: nextArgs,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!REMOTE_DEBUG_MANAGED_ZERO_RE.test(current)) {
|
||||||
|
REMOTE_DEBUG_MANAGED_ZERO_RE.lastIndex = 0;
|
||||||
|
return {
|
||||||
|
changed: false,
|
||||||
|
configured: REMOTE_DEBUG_ANY_RE.test(current),
|
||||||
|
args: current,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
REMOTE_DEBUG_MANAGED_ZERO_RE.lastIndex = 0;
|
||||||
|
const stripped = current.replace(REMOTE_DEBUG_MANAGED_ZERO_RE, ' ').replace(/\s{2,}/g, ' ').trim();
|
||||||
|
return {
|
||||||
|
changed: stripped !== current,
|
||||||
|
configured: REMOTE_DEBUG_ANY_RE.test(stripped),
|
||||||
|
removed: stripped !== current,
|
||||||
|
args: stripped,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析并无损修补 Windows `HKCU\Software\Microsoft\Windows\CurrentVersion\Run` 自启命令行字符串。
|
||||||
|
* 严格仅匹配目标可执行文件名为 `Antigravity.exe` 的项(排除 `Antigravity IDE.exe` 及无关程序)。
|
||||||
|
*
|
||||||
|
* @param {unknown} rawValue
|
||||||
|
* @param {{ enabled?: boolean }} [options]
|
||||||
|
* @returns {{ matched: boolean, changed: boolean, configured: boolean, value: string }}
|
||||||
|
*/
|
||||||
|
export function patchWindowsRunRegistryCommand(rawValue, { enabled = true } = {}) {
|
||||||
|
const raw = String(rawValue ?? '').trim();
|
||||||
|
if (!raw) {
|
||||||
|
return { matched: false, changed: false, configured: false, value: raw };
|
||||||
|
}
|
||||||
|
const m = raw.match(/^\s*(?:"([^"]+)"|([^\s"]+))([\s\S]*)$/);
|
||||||
|
if (!m) {
|
||||||
|
return { matched: false, changed: false, configured: false, value: raw };
|
||||||
|
}
|
||||||
|
const exePath = String(m[1] || m[2] || '').trim();
|
||||||
|
const exeLeaf = exePath.split(/[\\/]/).pop() || '';
|
||||||
|
if (exeLeaf.toLowerCase() !== 'antigravity.exe') {
|
||||||
|
return { matched: false, changed: false, configured: false, value: raw };
|
||||||
|
}
|
||||||
|
const quotedExe = m[1] ? `"${exePath}"` : /\s/.test(exePath) ? `"${exePath}"` : exePath;
|
||||||
|
const patchedArgs = ensureRemoteDebugFlagInArgs(m[3] || '', { enabled });
|
||||||
|
const nextValue = patchedArgs.args ? `${quotedExe} ${patchedArgs.args}` : quotedExe;
|
||||||
|
return {
|
||||||
|
matched: true,
|
||||||
|
changed: nextValue !== raw,
|
||||||
|
configured: patchedArgs.configured,
|
||||||
|
value: nextValue,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 修补 Linux XDG `.desktop` 文件文本中的 `Exec=` 启动行(仅作用于 `antigravity` 桌面端,不修改 `antigravity-ide`)。
|
||||||
|
*
|
||||||
|
* @param {string} rawText
|
||||||
|
* @param {{ enabled?: boolean }} [options]
|
||||||
|
* @returns {{ matched: boolean, changed: boolean, configured: boolean, text: string }}
|
||||||
|
*/
|
||||||
|
export function patchLinuxDesktopEntryText(rawText, { enabled = true } = {}) {
|
||||||
|
if (typeof rawText !== 'string' || !rawText.trim()) {
|
||||||
|
return { matched: false, changed: false, configured: false, text: String(rawText || '') };
|
||||||
|
}
|
||||||
|
const eol = rawText.includes('\r\n') ? '\r\n' : '\n';
|
||||||
|
const lines = rawText.split(/\r?\n/);
|
||||||
|
let matched = false;
|
||||||
|
let changed = false;
|
||||||
|
let configured = false;
|
||||||
|
|
||||||
|
const nextLines = lines.map((line) => {
|
||||||
|
const execMatch = line.match(/^(\s*Exec\s*=\s*)(.+)$/);
|
||||||
|
if (!execMatch) return line;
|
||||||
|
const prefix = execMatch[1];
|
||||||
|
const cmdBody = execMatch[2].trim();
|
||||||
|
const binMatch = cmdBody.match(/^(?:"([^"]+)"|'([^']+)'|([^\s"']+))([\s\S]*)$/);
|
||||||
|
if (!binMatch) return line;
|
||||||
|
const rawBin = String(binMatch[1] || binMatch[2] || binMatch[3] || '');
|
||||||
|
const leaf = (rawBin.split('/').pop() || '').toLowerCase();
|
||||||
|
if (leaf !== 'antigravity') {
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
matched = true;
|
||||||
|
const binToken = binMatch[1]
|
||||||
|
? `"${binMatch[1]}"`
|
||||||
|
: binMatch[2]
|
||||||
|
? `'${binMatch[2]}'`
|
||||||
|
: binMatch[3];
|
||||||
|
const rest = String(binMatch[4] || '').trim();
|
||||||
|
|
||||||
|
if (enabled) {
|
||||||
|
if (REMOTE_DEBUG_ANY_RE.test(rest)) {
|
||||||
|
configured = true;
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
configured = true;
|
||||||
|
changed = true;
|
||||||
|
const fieldCodeMatch = rest.match(/^(.*?)\s*(%[fFuUdDnNickvm](?:\s+%[fFuUdDnNickvm])*)\s*$/);
|
||||||
|
if (fieldCodeMatch) {
|
||||||
|
const beforeCodes = fieldCodeMatch[1].trim();
|
||||||
|
const codes = fieldCodeMatch[2].trim();
|
||||||
|
const mid = beforeCodes
|
||||||
|
? `${beforeCodes} ${REMOTE_DEBUG_LAUNCH_FLAG}`
|
||||||
|
: REMOTE_DEBUG_LAUNCH_FLAG;
|
||||||
|
return `${prefix}${binToken} ${mid} ${codes}`;
|
||||||
|
}
|
||||||
|
return rest
|
||||||
|
? `${prefix}${binToken} ${rest} ${REMOTE_DEBUG_LAUNCH_FLAG}`
|
||||||
|
: `${prefix}${binToken} ${REMOTE_DEBUG_LAUNCH_FLAG}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const stripped = ensureRemoteDebugFlagInArgs(rest, { enabled: false });
|
||||||
|
configured = configured || stripped.configured;
|
||||||
|
if (!stripped.changed) return line;
|
||||||
|
changed = true;
|
||||||
|
return stripped.args ? `${prefix}${binToken} ${stripped.args}` : `${prefix}${binToken}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
matched,
|
||||||
|
changed,
|
||||||
|
configured,
|
||||||
|
text: changed ? nextLines.join(eol) : rawText,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理 Sidecar / MCP 子进程继承的宿主会话私有环境变量,确保重拉后的客户端运行于纯净桌面上下文。
|
||||||
|
*
|
||||||
|
* @param {Record<string, string|undefined>} [baseEnv=process.env]
|
||||||
|
* @returns {Record<string, string>}
|
||||||
|
*/
|
||||||
|
export function buildSanitizedDesktopRelaunchEnv(baseEnv = process.env) {
|
||||||
|
const clean = {};
|
||||||
|
for (const [key, val] of Object.entries(baseEnv || {})) {
|
||||||
|
if (val === undefined || val === null) continue;
|
||||||
|
if (
|
||||||
|
/^(?:ANTIGRAVITY_|CHROME_DEVTOOLS_MCP_|USAGE_MONITOR_|ELECTRON_RUN_AS_NODE$|NODE_OPTIONS$)/i.test(
|
||||||
|
key
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
clean[key] = String(val);
|
||||||
|
}
|
||||||
|
return clean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动定位本机 Antigravity Desktop(或 IDE)主程序路径(优先从 `ANTIGRAVITY_AGENTAPI_EXE` 向上反推,回退标准安装目录)。
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* env?: Record<string, string|undefined>,
|
||||||
|
* platform?: string,
|
||||||
|
* homeDir?: string,
|
||||||
|
* existsFn?: (p: string) => boolean,
|
||||||
|
* }} [options]
|
||||||
|
* @returns {{ found: boolean, kind: 'desktop'|'ide'|'', executablePath: string, appBundlePath: string }}
|
||||||
|
*/
|
||||||
|
export function resolveDesktopHostExecutable({
|
||||||
|
env = process.env,
|
||||||
|
platform = process.platform,
|
||||||
|
homeDir = homedir(),
|
||||||
|
existsFn = existsSync,
|
||||||
|
} = {}) {
|
||||||
|
const safeExists = (p) => {
|
||||||
|
try {
|
||||||
|
return Boolean(p && existsFn(p));
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const hintPaths = [
|
||||||
|
String(env?.USAGE_MONITOR_HOST_EXE || '').trim(),
|
||||||
|
String(env?.ANTIGRAVITY_AGENTAPI_EXE || '').trim(),
|
||||||
|
String(env?.CHROME_DEVTOOLS_MCP_JS || '').trim(),
|
||||||
|
].filter(Boolean);
|
||||||
|
|
||||||
|
for (const rawHint of hintPaths) {
|
||||||
|
if (platform === 'darwin') {
|
||||||
|
const appIdx = rawHint.toLowerCase().indexOf('.app/');
|
||||||
|
const bundleCand =
|
||||||
|
appIdx >= 0
|
||||||
|
? rawHint.slice(0, appIdx + 4)
|
||||||
|
: rawHint.toLowerCase().endsWith('.app')
|
||||||
|
? rawHint
|
||||||
|
: '';
|
||||||
|
if (bundleCand && safeExists(bundleCand)) {
|
||||||
|
const isIde = /antigravity\s*ide\.app$/i.test(bundleCand);
|
||||||
|
const macBin = join(
|
||||||
|
bundleCand,
|
||||||
|
'Contents',
|
||||||
|
'MacOS',
|
||||||
|
isIde ? 'Antigravity IDE' : 'Antigravity'
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
found: true,
|
||||||
|
kind: isIde ? 'ide' : 'desktop',
|
||||||
|
executablePath: safeExists(macBin) ? macBin : bundleCand,
|
||||||
|
appBundlePath: bundleCand,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === 'win32' && /\.exe$/i.test(rawHint) && !/language_server/i.test(rawHint)) {
|
||||||
|
if (safeExists(rawHint)) {
|
||||||
|
const isIde = /antigravity\s*ide\.exe$/i.test(rawHint);
|
||||||
|
return {
|
||||||
|
found: true,
|
||||||
|
kind: isIde ? 'ide' : 'desktop',
|
||||||
|
executablePath: rawHint,
|
||||||
|
appBundlePath: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let cur = rawHint;
|
||||||
|
for (let depth = 0; depth < 8 && cur && dirname(cur) !== cur; depth += 1) {
|
||||||
|
const base = basename(cur).toLowerCase();
|
||||||
|
if (base === 'resources') {
|
||||||
|
const installRoot = dirname(cur);
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const desktopExe = join(installRoot, 'Antigravity.exe');
|
||||||
|
if (safeExists(desktopExe)) {
|
||||||
|
return { found: true, kind: 'desktop', executablePath: desktopExe, appBundlePath: '' };
|
||||||
|
}
|
||||||
|
const ideExe = join(installRoot, 'Antigravity IDE.exe');
|
||||||
|
if (safeExists(ideExe)) {
|
||||||
|
return { found: true, kind: 'ide', executablePath: ideExe, appBundlePath: '' };
|
||||||
|
}
|
||||||
|
} else if (platform === 'linux') {
|
||||||
|
for (const binName of ['antigravity', 'Antigravity']) {
|
||||||
|
const linuxExe = join(installRoot, binName);
|
||||||
|
if (safeExists(linuxExe)) {
|
||||||
|
return { found: true, kind: 'desktop', executablePath: linuxExe, appBundlePath: '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cur = dirname(cur);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const localAppData = env?.LOCALAPPDATA || join(homeDir, 'AppData', 'Local');
|
||||||
|
const programFiles = env?.ProgramFiles || 'C:\\Program Files';
|
||||||
|
const winCandidates = [
|
||||||
|
join(localAppData, 'Programs', 'Antigravity', 'Antigravity.exe'),
|
||||||
|
join(programFiles, 'Antigravity', 'Antigravity.exe'),
|
||||||
|
join(localAppData, 'Antigravity', 'Antigravity.exe'),
|
||||||
|
];
|
||||||
|
for (const cand of winCandidates) {
|
||||||
|
if (safeExists(cand)) {
|
||||||
|
return { found: true, kind: 'desktop', executablePath: cand, appBundlePath: '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (platform === 'darwin') {
|
||||||
|
const macBundles = [
|
||||||
|
join(homeDir, 'Applications', 'Antigravity.app'),
|
||||||
|
'/Applications/Antigravity.app',
|
||||||
|
];
|
||||||
|
for (const bundlePath of macBundles) {
|
||||||
|
if (safeExists(bundlePath)) {
|
||||||
|
const macBin = join(bundlePath, 'Contents', 'MacOS', 'Antigravity');
|
||||||
|
return {
|
||||||
|
found: true,
|
||||||
|
kind: 'desktop',
|
||||||
|
executablePath: safeExists(macBin) ? macBin : bundlePath,
|
||||||
|
appBundlePath: bundlePath,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const linuxCandidates = [
|
||||||
|
'/opt/Antigravity/antigravity',
|
||||||
|
'/opt/antigravity/antigravity',
|
||||||
|
'/usr/share/antigravity/antigravity',
|
||||||
|
'/usr/bin/antigravity',
|
||||||
|
join(homeDir, '.local', 'bin', 'antigravity'),
|
||||||
|
];
|
||||||
|
for (const cand of linuxCandidates) {
|
||||||
|
if (safeExists(cand)) {
|
||||||
|
return { found: true, kind: 'desktop', executablePath: cand, appBundlePath: '' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { found: false, kind: '', executablePath: '', appBundlePath: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runLauncherExecFile(file, args, options = {}) {
|
||||||
|
const cpMod = await import('node:child_process');
|
||||||
|
const execFileFn = cpMod.execFile || cpMod.default?.execFile;
|
||||||
|
if (typeof execFileFn !== 'function') {
|
||||||
|
throw new Error('child_process.execFile unavailable');
|
||||||
|
}
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
execFileFn(
|
||||||
|
file,
|
||||||
|
args,
|
||||||
|
{
|
||||||
|
windowsHide: true,
|
||||||
|
timeout: options.timeoutMs || 8000,
|
||||||
|
maxBuffer: 1024 * 1024,
|
||||||
|
env: options.env || process.env,
|
||||||
|
},
|
||||||
|
(err, stdout) => {
|
||||||
|
if (err) {
|
||||||
|
reject(err);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
resolve(String(stdout || ''));
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function spawnDetachedProcess(file, args, options = {}) {
|
||||||
|
const cpMod = await import('node:child_process');
|
||||||
|
const spawnFn = cpMod.spawn || cpMod.default?.spawn;
|
||||||
|
if (typeof spawnFn !== 'function') {
|
||||||
|
throw new Error('child_process.spawn unavailable');
|
||||||
|
}
|
||||||
|
const child = spawnFn(file, args, {
|
||||||
|
detached: true,
|
||||||
|
stdio: 'ignore',
|
||||||
|
windowsHide: true,
|
||||||
|
cwd: options.cwd || undefined,
|
||||||
|
env: options.env || process.env,
|
||||||
|
});
|
||||||
|
child.unref?.();
|
||||||
|
return { pid: Number(child?.pid || 0) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeTextFileAtomically(filePath, content, fsOps) {
|
||||||
|
const { mkdirFn, writeFn, renameFn, unlinkFn } = fsOps;
|
||||||
|
mkdirFn(dirname(filePath), { recursive: true });
|
||||||
|
const tmpPath = `${filePath}.tmp-${process.pid}`;
|
||||||
|
try {
|
||||||
|
writeFn(tmpPath, content, 'utf8');
|
||||||
|
renameFn(tmpPath, filePath);
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
unlinkFn(tmpPath);
|
||||||
|
} catch {
|
||||||
|
// 忽略临时文件清理异常
|
||||||
|
}
|
||||||
|
writeFn(filePath, content, 'utf8');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const WIN_SHORTCUT_PROVISION_PS = `
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$enableFlag = $env:AGY_LAUNCH_ENABLED -eq '1'
|
||||||
|
$updated = New-Object System.Collections.Generic.List[string]
|
||||||
|
$configured = New-Object System.Collections.Generic.List[string]
|
||||||
|
$ws = New-Object -ComObject WScript.Shell
|
||||||
|
$userProgramsDir = [Environment]::GetFolderPath('Programs')
|
||||||
|
|
||||||
|
$scanSpecs = @(
|
||||||
|
@{ Dir = [Environment]::GetFolderPath('Desktop'); Recurse = $false; IsCommon = $false },
|
||||||
|
@{ Dir = $userProgramsDir; Recurse = $true; IsCommon = $false },
|
||||||
|
@{ Dir = [Environment]::GetFolderPath('StartMenu'); Recurse = $false; IsCommon = $false },
|
||||||
|
@{ Dir = [Environment]::GetFolderPath('Startup'); Recurse = $false; IsCommon = $false },
|
||||||
|
@{ Dir = (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar'); Recurse = $false; IsCommon = $false },
|
||||||
|
@{ Dir = [Environment]::GetFolderPath('CommonDesktopDirectory'); Recurse = $false; IsCommon = $true },
|
||||||
|
@{ Dir = [Environment]::GetFolderPath('CommonPrograms'); Recurse = $true; IsCommon = $true }
|
||||||
|
)
|
||||||
|
|
||||||
|
$seen = New-Object 'System.Collections.Generic.HashSet[string]' ([System.StringComparer]::OrdinalIgnoreCase)
|
||||||
|
foreach ($spec in $scanSpecs) {
|
||||||
|
$dir = [string]$spec.Dir
|
||||||
|
if (-not $dir -or -not (Test-Path -LiteralPath $dir)) { continue }
|
||||||
|
$items = @()
|
||||||
|
try {
|
||||||
|
if ($spec.Recurse) {
|
||||||
|
$items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -Recurse -Depth 2 -ErrorAction SilentlyContinue)
|
||||||
|
} else {
|
||||||
|
$items = @(Get-ChildItem -LiteralPath $dir -Filter '*.lnk' -File -ErrorAction SilentlyContinue)
|
||||||
|
}
|
||||||
|
} catch { continue }
|
||||||
|
|
||||||
|
foreach ($item in $items) {
|
||||||
|
$lnkPath = [string]$item.FullName
|
||||||
|
if (-not $seen.Add($lnkPath)) { continue }
|
||||||
|
try {
|
||||||
|
$sc = $ws.CreateShortcut($lnkPath)
|
||||||
|
$target = [string]$sc.TargetPath
|
||||||
|
if ([System.IO.Path]::GetFileName($target) -ine 'Antigravity.exe') { continue }
|
||||||
|
$curArgs = [string]$sc.Arguments
|
||||||
|
if ($enableFlag) {
|
||||||
|
if ($curArgs -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||||
|
$configured.Add($lnkPath)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
$nextArgs = ($curArgs.Trim() + ' --remote-debugging-port=0').Trim()
|
||||||
|
try {
|
||||||
|
$sc.Arguments = $nextArgs
|
||||||
|
$sc.Save()
|
||||||
|
$updated.Add($lnkPath)
|
||||||
|
$configured.Add($lnkPath)
|
||||||
|
} catch {
|
||||||
|
if ($spec.IsCommon -and $userProgramsDir -and (Test-Path -LiteralPath $userProgramsDir)) {
|
||||||
|
$fallbackLnk = Join-Path $userProgramsDir ([System.IO.Path]::GetFileName($lnkPath))
|
||||||
|
if (-not (Test-Path -LiteralPath $fallbackLnk)) {
|
||||||
|
try {
|
||||||
|
$uSc = $ws.CreateShortcut($fallbackLnk)
|
||||||
|
$uSc.TargetPath = $target
|
||||||
|
$uSc.Arguments = $nextArgs
|
||||||
|
if ($sc.WorkingDirectory) { $uSc.WorkingDirectory = $sc.WorkingDirectory }
|
||||||
|
if ($sc.IconLocation) { $uSc.IconLocation = $sc.IconLocation }
|
||||||
|
if ($sc.Description) { $uSc.Description = $sc.Description }
|
||||||
|
$uSc.Save()
|
||||||
|
$updated.Add($fallbackLnk)
|
||||||
|
$configured.Add($fallbackLnk)
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
$stripped = ([regex]::Replace($curArgs, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
||||||
|
if ($stripped -ne $curArgs.Trim()) {
|
||||||
|
try {
|
||||||
|
$sc.Arguments = $stripped
|
||||||
|
$sc.Save()
|
||||||
|
$updated.Add($lnkPath)
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
if ($stripped -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||||
|
$configured.Add($lnkPath)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$runKey = 'HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run'
|
||||||
|
if (Test-Path -LiteralPath $runKey) {
|
||||||
|
try {
|
||||||
|
$regItem = Get-Item -LiteralPath $runKey -ErrorAction SilentlyContinue
|
||||||
|
if ($regItem) {
|
||||||
|
foreach ($valName in $regItem.GetValueNames()) {
|
||||||
|
$rawCmd = [string]$regItem.GetValue($valName, '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
|
||||||
|
if (-not $rawCmd) { continue }
|
||||||
|
if ($rawCmd -notmatch '^\\s*(?:"([^"]+)"|([^\\s"]+))(.*)$') { continue }
|
||||||
|
$exeCandidate = if ($Matches[1]) { $Matches[1] } else { $Matches[2] }
|
||||||
|
$restPart = [string]$Matches[3]
|
||||||
|
if ([System.IO.Path]::GetFileName($exeCandidate) -ine 'Antigravity.exe') { continue }
|
||||||
|
$quotedExe = if ($Matches[1] -or $exeCandidate -match '\\s') { '"' + $exeCandidate + '"' } else { $exeCandidate }
|
||||||
|
if ($enableFlag) {
|
||||||
|
if ($restPart -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||||
|
$configured.Add("HKCU:Run:$valName")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
$nextRest = ($restPart.Trim() + ' --remote-debugging-port=0').Trim()
|
||||||
|
$nextVal = "$quotedExe $nextRest"
|
||||||
|
Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue
|
||||||
|
$updated.Add("HKCU:Run:$valName")
|
||||||
|
$configured.Add("HKCU:Run:$valName")
|
||||||
|
} else {
|
||||||
|
$strippedRest = ([regex]::Replace($restPart, '(?:^|\\s+)--remote-debugging-port=(?:"0"|''0''|0)(?=\\s|$)', ' ')).Trim()
|
||||||
|
$nextVal = if ($strippedRest) { "$quotedExe $strippedRest" } else { $quotedExe }
|
||||||
|
if ($nextVal -ne $rawCmd.Trim()) {
|
||||||
|
Set-ItemProperty -LiteralPath $runKey -Name $valName -Value $nextVal -ErrorAction SilentlyContinue
|
||||||
|
$updated.Add("HKCU:Run:$valName")
|
||||||
|
}
|
||||||
|
if ($strippedRest -match '(?:^|\\s)--remote-debugging-port(?:=|\\s|$)') {
|
||||||
|
$configured.Add("HKCU:Run:$valName")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
[pscustomobject]@{
|
||||||
|
ok = $true
|
||||||
|
updatedPaths = @($updated)
|
||||||
|
configuredPaths = @($configured)
|
||||||
|
} | ConvertTo-Json -Compress
|
||||||
|
`.trim();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自动同步当前系统下用户空间启动入口(Windows `.lnk` / `HKCU:Run`、Linux `.desktop`)中的 `--remote-debugging-port=0`。
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* enabled?: boolean,
|
||||||
|
* env?: Record<string, string|undefined>,
|
||||||
|
* platform?: string,
|
||||||
|
* homeDir?: string,
|
||||||
|
* execFileFn?: ((file: string, args: string[], opts?: object) => Promise<string>)|null,
|
||||||
|
* fsOps?: {
|
||||||
|
* existsFn?: typeof existsSync,
|
||||||
|
* readFn?: typeof readFileSync,
|
||||||
|
* writeFn?: typeof writeFileSync,
|
||||||
|
* mkdirFn?: typeof mkdirSync,
|
||||||
|
* renameFn?: typeof renameSync,
|
||||||
|
* unlinkFn?: typeof unlinkSync,
|
||||||
|
* }|null,
|
||||||
|
* allowInTest?: boolean,
|
||||||
|
* }} [options]
|
||||||
|
*/
|
||||||
|
export async function ensureDesktopLaunchEntriesConfigured({
|
||||||
|
enabled = true,
|
||||||
|
env = process.env,
|
||||||
|
platform = process.platform,
|
||||||
|
homeDir = homedir(),
|
||||||
|
execFileFn = null,
|
||||||
|
fsOps = null,
|
||||||
|
allowInTest = false,
|
||||||
|
} = {}) {
|
||||||
|
if (lsRuntimeEndpoint.addr === 'test.invalid' && !allowInTest) {
|
||||||
|
return {
|
||||||
|
checked: false,
|
||||||
|
updated: false,
|
||||||
|
alreadyConfigured: false,
|
||||||
|
updatedPaths: [],
|
||||||
|
configuredPaths: [],
|
||||||
|
reason: 'test_sandbox_skipped',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const ops = {
|
||||||
|
existsFn: fsOps?.existsFn || existsSync,
|
||||||
|
readFn: fsOps?.readFn || readFileSync,
|
||||||
|
writeFn: fsOps?.writeFn || writeFileSync,
|
||||||
|
mkdirFn: fsOps?.mkdirFn || mkdirSync,
|
||||||
|
renameFn: fsOps?.renameFn || renameSync,
|
||||||
|
unlinkFn: fsOps?.unlinkFn || unlinkSync,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (platform === 'win32') {
|
||||||
|
try {
|
||||||
|
const runner = execFileFn || runLauncherExecFile;
|
||||||
|
const out = await runner(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WIN_SHORTCUT_PROVISION_PS],
|
||||||
|
{
|
||||||
|
timeoutMs: 9000,
|
||||||
|
env: {
|
||||||
|
...env,
|
||||||
|
AGY_LAUNCH_ENABLED: enabled ? '1' : '0',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
const trimmed = String(out || '').trim();
|
||||||
|
const jsonLine = trimmed.split(/\r?\n/).reverse().find((l) => l.trim().startsWith('{')) || '';
|
||||||
|
const parsed = jsonLine ? JSON.parse(jsonLine) : null;
|
||||||
|
const updatedPaths = Array.isArray(parsed?.updatedPaths)
|
||||||
|
? parsed.updatedPaths.map(String).filter(Boolean)
|
||||||
|
: [];
|
||||||
|
const configuredPaths = Array.isArray(parsed?.configuredPaths)
|
||||||
|
? parsed.configuredPaths.map(String).filter(Boolean)
|
||||||
|
: [];
|
||||||
|
return {
|
||||||
|
checked: true,
|
||||||
|
updated: updatedPaths.length > 0,
|
||||||
|
alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0,
|
||||||
|
configured: configuredPaths.length > 0,
|
||||||
|
updatedPaths,
|
||||||
|
configuredPaths,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
checked: true,
|
||||||
|
updated: false,
|
||||||
|
alreadyConfigured: false,
|
||||||
|
configured: false,
|
||||||
|
updatedPaths: [],
|
||||||
|
configuredPaths: [],
|
||||||
|
reason: 'win_shortcut_error',
|
||||||
|
error: err?.message || String(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === 'linux') {
|
||||||
|
const dataHome = env?.XDG_DATA_HOME || join(homeDir, '.local', 'share');
|
||||||
|
const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config');
|
||||||
|
const userDesktopFile = join(dataHome, 'applications', 'antigravity.desktop');
|
||||||
|
const systemDesktopFiles = [
|
||||||
|
'/usr/share/applications/antigravity.desktop',
|
||||||
|
'/usr/local/share/applications/antigravity.desktop',
|
||||||
|
];
|
||||||
|
const autostartDesktopFile = join(configHome, 'autostart', 'antigravity.desktop');
|
||||||
|
|
||||||
|
const updatedPaths = [];
|
||||||
|
const configuredPaths = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
let baseUserText = '';
|
||||||
|
if (ops.existsFn(userDesktopFile)) {
|
||||||
|
baseUserText = String(ops.readFn(userDesktopFile, 'utf8') || '');
|
||||||
|
} else if (enabled) {
|
||||||
|
const sysSource = systemDesktopFiles.find((p) => ops.existsFn(p));
|
||||||
|
if (sysSource) {
|
||||||
|
baseUserText = String(ops.readFn(sysSource, 'utf8') || '');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (baseUserText) {
|
||||||
|
const patched = patchLinuxDesktopEntryText(baseUserText, { enabled });
|
||||||
|
if (patched.changed) {
|
||||||
|
writeTextFileAtomically(userDesktopFile, patched.text, ops);
|
||||||
|
updatedPaths.push(userDesktopFile);
|
||||||
|
}
|
||||||
|
if (patched.configured) {
|
||||||
|
configuredPaths.push(userDesktopFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ops.existsFn(autostartDesktopFile)) {
|
||||||
|
const autoRaw = String(ops.readFn(autostartDesktopFile, 'utf8') || '');
|
||||||
|
const patchedAuto = patchLinuxDesktopEntryText(autoRaw, { enabled });
|
||||||
|
if (patchedAuto.changed) {
|
||||||
|
writeTextFileAtomically(autostartDesktopFile, patchedAuto.text, ops);
|
||||||
|
updatedPaths.push(autostartDesktopFile);
|
||||||
|
}
|
||||||
|
if (patchedAuto.configured) {
|
||||||
|
configuredPaths.push(autostartDesktopFile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
checked: true,
|
||||||
|
updated: updatedPaths.length > 0,
|
||||||
|
alreadyConfigured: updatedPaths.length === 0 && configuredPaths.length > 0,
|
||||||
|
configured: configuredPaths.length > 0,
|
||||||
|
updatedPaths,
|
||||||
|
configuredPaths,
|
||||||
|
};
|
||||||
|
} catch (err) {
|
||||||
|
return {
|
||||||
|
checked: true,
|
||||||
|
updated: false,
|
||||||
|
alreadyConfigured: false,
|
||||||
|
configured: false,
|
||||||
|
updatedPaths,
|
||||||
|
configuredPaths,
|
||||||
|
reason: 'linux_desktop_error',
|
||||||
|
error: err?.message || String(err),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// macOS `.app` 包具有 Apple 代码签名,不修改签名目录,交由一键重拉 (`open -a ... --args`) 处理
|
||||||
|
return {
|
||||||
|
checked: true,
|
||||||
|
updated: false,
|
||||||
|
alreadyConfigured: false,
|
||||||
|
configured: false,
|
||||||
|
updatedPaths: [],
|
||||||
|
configuredPaths: [],
|
||||||
|
reason: 'macos_app_bundle_signed',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当静态环境变量与默认安装目录均未命中(如用户自定义安装至 D:/E: 盘且 Sidecar 未继承 `ANTIGRAVITY_AGENTAPI_EXE`)时,
|
||||||
|
* 直接从当前正在运行的宿主进程动态反查主程序绝对路径。
|
||||||
|
*/
|
||||||
|
async function discoverRunningHostExecutable({ platform = process.platform, execFileFn = null } = {}) {
|
||||||
|
const runner = execFileFn || runLauncherExecFile;
|
||||||
|
if (platform === 'win32') {
|
||||||
|
try {
|
||||||
|
const ps =
|
||||||
|
"@(Get-Process -Name 'Antigravity','Antigravity IDE' -ErrorAction SilentlyContinue | Where-Object { $_.Path } | Select-Object -First 1) | ForEach-Object { [pscustomobject]@{ path = [string]$_.Path; name = [string]$_.ProcessName } } | ConvertTo-Json -Compress";
|
||||||
|
const out = await runner(
|
||||||
|
'powershell.exe',
|
||||||
|
['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', ps],
|
||||||
|
{ timeoutMs: 4000 }
|
||||||
|
);
|
||||||
|
const trimmed = String(out || '').trim();
|
||||||
|
if (trimmed && trimmed.startsWith('{')) {
|
||||||
|
const parsed = JSON.parse(trimmed);
|
||||||
|
const exePath = String(parsed?.path || '').trim();
|
||||||
|
if (exePath) {
|
||||||
|
const isIde = /ide/i.test(String(parsed?.name || '')) || /antigravity\s*ide\.exe$/i.test(exePath);
|
||||||
|
return {
|
||||||
|
found: true,
|
||||||
|
kind: isIde ? 'ide' : 'desktop',
|
||||||
|
executablePath: exePath,
|
||||||
|
appBundlePath: '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略动态进程探测异常
|
||||||
|
}
|
||||||
|
} else if (platform === 'darwin') {
|
||||||
|
try {
|
||||||
|
const out = await runner(
|
||||||
|
'osascript',
|
||||||
|
['-e', 'POSIX path of (path to application "Antigravity")'],
|
||||||
|
{ timeoutMs: 3000 }
|
||||||
|
);
|
||||||
|
const bundlePath = String(out || '').trim().replace(/\/+$/, '');
|
||||||
|
if (bundlePath && /\.app$/i.test(bundlePath)) {
|
||||||
|
return {
|
||||||
|
found: true,
|
||||||
|
kind: 'desktop',
|
||||||
|
executablePath: bundlePath,
|
||||||
|
appBundlePath: bundlePath,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略 AppleScript 探测异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { found: false, kind: '', executablePath: '', appBundlePath: '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function psSingleQuote(val) {
|
||||||
|
return `'${String(val ?? '').replace(/'/g, "''")}'`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建 Windows 脱离宿主 Job Object 的隐藏重拉内层脚本(写入临时 UTF-8 BOM `.ps1` 文件后交由 `explorer.exe` 拉起,规避 `ShellExecute` 参数长度上限)。
|
||||||
|
*
|
||||||
|
* @param {string} executablePath
|
||||||
|
* @param {string[]} stalePortFiles
|
||||||
|
* @param {'desktop'|'ide'|''} kind
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function buildWindowsRelaunchInnerScript(executablePath, stalePortFiles = [], kind = 'desktop') {
|
||||||
|
const procName = kind === 'ide' ? 'Antigravity IDE' : 'Antigravity';
|
||||||
|
const portLiterals = (Array.isArray(stalePortFiles) ? stalePortFiles : [])
|
||||||
|
.map((p) => String(p || '').trim())
|
||||||
|
.filter(Boolean)
|
||||||
|
.map(psSingleQuote)
|
||||||
|
.join(', ');
|
||||||
|
|
||||||
|
return `
|
||||||
|
Start-Sleep -Milliseconds 480
|
||||||
|
$exe = ${psSingleQuote(executablePath)}
|
||||||
|
$procName = ${psSingleQuote(procName)}
|
||||||
|
$staleList = @(${portLiterals})
|
||||||
|
$mySid = (Get-Process -Id $PID).SessionId
|
||||||
|
|
||||||
|
if (-not $exe -or -not (Test-Path -LiteralPath $exe)) {
|
||||||
|
$livePath = Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $mySid -and $_.Path } | Select-Object -First 1 -ExpandProperty Path
|
||||||
|
if ($livePath) { $exe = [string]$livePath }
|
||||||
|
}
|
||||||
|
|
||||||
|
$findTargets = {
|
||||||
|
@(Get-Process -Name $procName -ErrorAction SilentlyContinue | Where-Object {
|
||||||
|
$_.SessionId -eq $mySid -and (-not $_.Path -or -not $exe -or [string]::Equals($_.Path, $exe, [System.StringComparison]::OrdinalIgnoreCase))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
$initial = & $findTargets
|
||||||
|
foreach ($p in $initial) {
|
||||||
|
try {
|
||||||
|
if ($p.MainWindowHandle -ne 0) { [void]$p.CloseMainWindow() }
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
Start-Sleep -Milliseconds 850
|
||||||
|
|
||||||
|
$remaining = & $findTargets
|
||||||
|
foreach ($p in $remaining) {
|
||||||
|
try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
for ($i = 0; $i -lt 30; $i++) {
|
||||||
|
if ((& $findTargets).Count -eq 0) { break }
|
||||||
|
Start-Sleep -Milliseconds 200
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($fp in $staleList) {
|
||||||
|
if ($fp -and (Test-Path -LiteralPath $fp)) {
|
||||||
|
try { Remove-Item -LiteralPath $fp -Force -ErrorAction SilentlyContinue } catch {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($exe -and (Test-Path -LiteralPath $exe)) {
|
||||||
|
$workDir = Split-Path -Parent $exe
|
||||||
|
Start-Process -FilePath $exe -ArgumentList '--remote-debugging-port=0' -WorkingDirectory $workDir
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($PSCommandPath -and (Test-Path -LiteralPath $PSCommandPath)) {
|
||||||
|
Remove-Item -LiteralPath $PSCommandPath -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
const WIN_OUT_OF_JOB_DISPATCH_PS = `
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
$innerArgs = '-NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "' + $env:AGY_RELAUNCH_PS1 + '"'
|
||||||
|
try {
|
||||||
|
$shellApp = New-Object -ComObject Shell.Application
|
||||||
|
$shellApp.ShellExecute('powershell.exe', $innerArgs, '', 'open', 0)
|
||||||
|
Write-Output '{"ok":true,"method":"shell_application"}'
|
||||||
|
} catch {
|
||||||
|
Start-Process -FilePath 'powershell.exe' -ArgumentList $innerArgs -WindowStyle Hidden
|
||||||
|
Write-Output '{"ok":true,"method":"start_process"}'
|
||||||
|
}
|
||||||
|
`.trim();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 触发跨平台一键退出系统托盘后台并追加 `--remote-debugging-port=0` 重新拉起宿主客户端。
|
||||||
|
*
|
||||||
|
* @param {{
|
||||||
|
* env?: Record<string, string|undefined>,
|
||||||
|
* platform?: string,
|
||||||
|
* homeDir?: string,
|
||||||
|
* stalePortFiles?: string[],
|
||||||
|
* execFileFn?: ((file: string, args: string[], opts?: object) => Promise<string>)|null,
|
||||||
|
* spawnFn?: ((file: string, args: string[], opts?: object) => Promise<{ pid: number }>)|null,
|
||||||
|
* existsFn?: typeof existsSync,
|
||||||
|
* writeFileFn?: typeof writeFileSync,
|
||||||
|
* mkdirFn?: typeof mkdirSync,
|
||||||
|
* allowInTest?: boolean,
|
||||||
|
* }} [options]
|
||||||
|
*/
|
||||||
|
export async function triggerDesktopHostRelaunch({
|
||||||
|
env = process.env,
|
||||||
|
platform = process.platform,
|
||||||
|
homeDir = homedir(),
|
||||||
|
stalePortFiles = [],
|
||||||
|
execFileFn = null,
|
||||||
|
spawnFn = null,
|
||||||
|
existsFn = existsSync,
|
||||||
|
writeFileFn = writeFileSync,
|
||||||
|
mkdirFn = mkdirSync,
|
||||||
|
allowInTest = false,
|
||||||
|
} = {}) {
|
||||||
|
if (lsRuntimeEndpoint.addr === 'test.invalid' && !allowInTest) {
|
||||||
|
return { ok: false, status: 403, error: 'Disabled in test sandbox' };
|
||||||
|
}
|
||||||
|
|
||||||
|
let hostInfo = resolveDesktopHostExecutable({ env, platform, homeDir, existsFn });
|
||||||
|
if (!hostInfo.found) {
|
||||||
|
hostInfo = await discoverRunningHostExecutable({ platform, execFileFn });
|
||||||
|
}
|
||||||
|
if (!hostInfo.found) {
|
||||||
|
return {
|
||||||
|
ok: false,
|
||||||
|
status: 404,
|
||||||
|
error: 'Unable to locate Antigravity executable on this machine',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanEnv = buildSanitizedDesktopRelaunchEnv(env);
|
||||||
|
const cleanStaleFiles = (Array.isArray(stalePortFiles) ? stalePortFiles : [])
|
||||||
|
.map((p) => String(p || '').trim())
|
||||||
|
.filter(Boolean);
|
||||||
|
|
||||||
|
if (platform === 'win32') {
|
||||||
|
const innerScript = buildWindowsRelaunchInnerScript(
|
||||||
|
hostInfo.executablePath,
|
||||||
|
cleanStaleFiles,
|
||||||
|
hostInfo.kind
|
||||||
|
);
|
||||||
|
const tempDir = String(env?.TEMP || env?.TMP || DATA_DIR || homeDir).trim();
|
||||||
|
mkdirFn(tempDir, { recursive: true });
|
||||||
|
const relaunchPs1Path = join(tempDir, `agy-monitor-relaunch-${process.pid}.ps1`);
|
||||||
|
// UTF-8 with BOM ensures Windows PowerShell 5.1 parses non-ASCII paths accurately across all system locales
|
||||||
|
writeFileFn(relaunchPs1Path, `\uFEFF${innerScript}\r\n`, 'utf8');
|
||||||
|
|
||||||
|
const runner = execFileFn || runLauncherExecFile;
|
||||||
|
await runner(
|
||||||
|
'powershell.exe',
|
||||||
|
[
|
||||||
|
'-Sta',
|
||||||
|
'-NoProfile',
|
||||||
|
'-NonInteractive',
|
||||||
|
'-ExecutionPolicy',
|
||||||
|
'Bypass',
|
||||||
|
'-Command',
|
||||||
|
WIN_OUT_OF_JOB_DISPATCH_PS,
|
||||||
|
],
|
||||||
|
{
|
||||||
|
timeoutMs: 6000,
|
||||||
|
env: {
|
||||||
|
...cleanEnv,
|
||||||
|
AGY_RELAUNCH_PS1: relaunchPs1Path,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
relaunching: true,
|
||||||
|
platform,
|
||||||
|
executablePath: hostInfo.executablePath,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const spawner = spawnFn || spawnDetachedProcess;
|
||||||
|
|
||||||
|
if (platform === 'darwin') {
|
||||||
|
const appTarget = hostInfo.appBundlePath || hostInfo.executablePath;
|
||||||
|
const appName = hostInfo.kind === 'ide' ? 'Antigravity IDE' : 'Antigravity';
|
||||||
|
const shScript = [
|
||||||
|
'sleep 0.45',
|
||||||
|
`osascript -e 'tell application "${appName}" to quit' >/dev/null 2>&1 || true`,
|
||||||
|
`i=0; while [ $i -lt 25 ] && pgrep -x "${appName}" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done`,
|
||||||
|
`if pgrep -x "${appName}" >/dev/null 2>&1; then killall "${appName}" >/dev/null 2>&1 || true; sleep 0.4; fi`,
|
||||||
|
'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done',
|
||||||
|
'open -a "$AGY_RELAUNCH_APP" --args --remote-debugging-port=0 >/dev/null 2>&1',
|
||||||
|
].join('; ');
|
||||||
|
await spawner('/bin/sh', ['-c', shScript], {
|
||||||
|
env: {
|
||||||
|
...cleanEnv,
|
||||||
|
AGY_RELAUNCH_APP: appTarget,
|
||||||
|
AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
relaunching: true,
|
||||||
|
platform,
|
||||||
|
executablePath: appTarget,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const procLeaf = basename(hostInfo.executablePath) || 'antigravity';
|
||||||
|
const linuxScript = [
|
||||||
|
'sleep 0.45',
|
||||||
|
'uid="$(id -u)"',
|
||||||
|
'pkill -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1 || true',
|
||||||
|
'i=0; while [ $i -lt 25 ] && pgrep -u "$uid" -x "$AGY_PROC_NAME" >/dev/null 2>&1; do sleep 0.2; i=$((i+1)); done',
|
||||||
|
'IFS=":"; for f in $AGY_STALE_PORT_FILES; do [ -n "$f" ] && rm -f "$f"; done',
|
||||||
|
'nohup "$AGY_RELAUNCH_EXE" --remote-debugging-port=0 >/dev/null 2>&1 &',
|
||||||
|
].join('; ');
|
||||||
|
await spawner('/bin/sh', ['-c', linuxScript], {
|
||||||
|
env: {
|
||||||
|
...cleanEnv,
|
||||||
|
AGY_RELAUNCH_EXE: hostInfo.executablePath,
|
||||||
|
AGY_PROC_NAME: procLeaf,
|
||||||
|
AGY_STALE_PORT_FILES: cleanStaleFiles.join(':'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
relaunching: true,
|
||||||
|
platform,
|
||||||
|
executablePath: hostInfo.executablePath,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 零业务状态依赖的静态资源读取与本机回环请求来源校验工具。
|
||||||
|
*
|
||||||
|
* 独立于 `./config.mjs` 与 `./api-actions.mjs`,使宿主入口 `main.mjs` 在生产环境下无需加载完整后端图谱与轨迹缓存。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
function resolveHttpHelperPanelDir() {
|
||||||
|
const modDir = dirname(fileURLToPath(import.meta.url));
|
||||||
|
return /[\\/]backend$/i.test(modDir) ? dirname(modDir) : modDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||||
|
*
|
||||||
|
* @param {string} relPath 相对路径
|
||||||
|
* @returns {Promise<string>}
|
||||||
|
*/
|
||||||
|
export const readLocalAsync = async (relPath) => {
|
||||||
|
const fullPath = join(resolveHttpHelperPanelDir(), relPath);
|
||||||
|
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||||
|
return fsPromises.readFile(fullPath, 'utf8');
|
||||||
|
}
|
||||||
|
return readFileSync(fullPath, 'utf8');
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||||
|
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||||
|
*
|
||||||
|
* @param {object} req
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isLocalHostRequest(req) {
|
||||||
|
if (!req?.headers) return true;
|
||||||
|
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||||
|
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||||
|
if (host && !hostMatch) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||||
|
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||||
|
if (secFetchSite === 'cross-site') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (origin) {
|
||||||
|
const originMatch = origin.match(
|
||||||
|
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||||
|
);
|
||||||
|
if (!originMatch) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (hostMatch) {
|
||||||
|
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||||
|
const originPort = originMatch[3] || defaultPort;
|
||||||
|
const hostPort = hostMatch[2] || defaultPort;
|
||||||
|
if (originPort !== hostPort) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -513,7 +513,7 @@ export async function ensureLsEndpointDiscovered({
|
|||||||
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) {
|
if (!force && lsRuntimeEndpoint.baseUrl && (lsRuntimeEndpoint.csrfToken || !lsRuntimeEndpoint.isDynamic)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
if (lsDiscoveryState.inFlight) {
|
if (lsDiscoveryState.inFlight) {
|
||||||
|
|||||||
@@ -8,6 +8,7 @@
|
|||||||
* 绝不借用其他模型单价伪造费用。
|
* 绝不借用其他模型单价伪造费用。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||||
import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
import { MODEL_PRICING, PLACEHOLDER_MAP } from './pricing-catalog.mjs';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -130,7 +131,7 @@ export function formatGenericModelSlug(slug = '') {
|
|||||||
.trim()
|
.trim()
|
||||||
.replace(/^session-display:/i, '');
|
.replace(/^session-display:/i, '');
|
||||||
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
if (!s || /^MODEL_PLACEHOLDER_/i.test(s)) return '';
|
||||||
if (/^gemini-4-argon-(?:f|disabled)$/i.test(s)) return 'Gemini 4 Argon';
|
if (/^gemini-4-argon-(?:b|f|trial|disabled)$/i.test(s)) return 'Gemini 4 Argon';
|
||||||
if (/^gemini-3\.8-flash-n$/i.test(s)) return 'Gemini 3.8 Flash';
|
if (/^gemini-3\.8-flash-n$/i.test(s)) return 'Gemini 3.8 Flash';
|
||||||
if (/^gemini-3\.7-flash-safety-le$/i.test(s)) return 'Gemini 3.7 Flash';
|
if (/^gemini-3\.7-flash-safety-le$/i.test(s)) return 'Gemini 3.7 Flash';
|
||||||
if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash';
|
if (/^gemini-3-flash-(?:[abd]|agent)$/i.test(s)) return 'Gemini 3.5 Flash';
|
||||||
@@ -159,16 +160,78 @@ export function formatGenericModelSlug(slug = '') {
|
|||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractStepTimestampMs(step) {
|
||||||
|
if (!step || typeof step !== 'object') return 0;
|
||||||
|
const direct = Number(step.createdAtMs);
|
||||||
|
if (Number.isFinite(direct) && direct > 0) return direct;
|
||||||
|
if (typeof step.createdAt === 'string' && step.createdAt.trim()) {
|
||||||
|
return parseIsoMs(step.createdAt.trim()) || 0;
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与单价配置。
|
* 根据目标时间戳匹配模型价格条目的时间阶段(`phases`,左闭右开 `[fromMs, untilMs)`)。
|
||||||
|
* 未传入有效时间戳时按当前时刻匹配;未命中任何阶段或未配置阶段时回退至顶层基础单价。
|
||||||
*
|
*
|
||||||
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`)
|
* @param {object|null} pricingEntry
|
||||||
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表
|
* @param {number|string|null} [atMs]
|
||||||
* @param {string} [apiProvider=''] API 提供商枚举
|
* @returns {object|null}
|
||||||
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
|
||||||
* @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`)
|
|
||||||
*/
|
*/
|
||||||
export function resolveModelInfo(
|
export function resolvePricingAt(pricingEntry, atMs) {
|
||||||
|
if (!pricingEntry || typeof pricingEntry !== 'object') return null;
|
||||||
|
const baseEntry = pricingEntry._basePricing || pricingEntry;
|
||||||
|
const phases = baseEntry.phases;
|
||||||
|
if (!Array.isArray(phases) || phases.length === 0) return baseEntry;
|
||||||
|
|
||||||
|
let tMs = 0;
|
||||||
|
if (typeof atMs === 'number' && Number.isFinite(atMs) && atMs > 0) {
|
||||||
|
tMs = atMs;
|
||||||
|
} else if (typeof atMs === 'string' && atMs.trim()) {
|
||||||
|
tMs = parseIsoMs(atMs.trim()) || 0;
|
||||||
|
}
|
||||||
|
if (tMs <= 0) {
|
||||||
|
tMs = Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let i = 0; i < phases.length; i++) {
|
||||||
|
const ph = phases[i];
|
||||||
|
if (!ph || typeof ph !== 'object') continue;
|
||||||
|
const fromMs = Number.isFinite(ph.fromMs)
|
||||||
|
? ph.fromMs
|
||||||
|
: typeof ph.from === 'string' && ph.from.trim()
|
||||||
|
? parseIsoMs(ph.from.trim()) || -Infinity
|
||||||
|
: -Infinity;
|
||||||
|
const untilMs = Number.isFinite(ph.untilMs)
|
||||||
|
? ph.untilMs
|
||||||
|
: typeof ph.until === 'string' && ph.until.trim()
|
||||||
|
? parseIsoMs(ph.until.trim()) || Infinity
|
||||||
|
: Infinity;
|
||||||
|
if (tMs >= fromMs && tMs < untilMs) {
|
||||||
|
if (
|
||||||
|
ph.input === baseEntry.input &&
|
||||||
|
ph.cache === baseEntry.cache &&
|
||||||
|
ph.output === baseEntry.output
|
||||||
|
) {
|
||||||
|
return baseEntry;
|
||||||
|
}
|
||||||
|
const resolved = {
|
||||||
|
...baseEntry,
|
||||||
|
input: ph.input,
|
||||||
|
cache: ph.cache,
|
||||||
|
output: ph.output,
|
||||||
|
};
|
||||||
|
Object.defineProperty(resolved, '_basePricing', {
|
||||||
|
value: baseEntry,
|
||||||
|
enumerable: false,
|
||||||
|
});
|
||||||
|
return resolved;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return baseEntry;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveModelCatalogEntry(
|
||||||
rawModelKey,
|
rawModelKey,
|
||||||
dynamicModelMap = new Map(),
|
dynamicModelMap = new Map(),
|
||||||
apiProvider = '',
|
apiProvider = '',
|
||||||
@@ -251,42 +314,86 @@ export function resolveModelInfo(
|
|||||||
|
|
||||||
if (explicitPricing) {
|
if (explicitPricing) {
|
||||||
return {
|
return {
|
||||||
rawModel: rawModelKey,
|
catalogPricing: explicitPricing,
|
||||||
modelId,
|
info: {
|
||||||
label: derivedDisplay,
|
rawModel: rawModelKey,
|
||||||
baseLabel,
|
modelId,
|
||||||
shortName: explicitPricing.short,
|
label: derivedDisplay,
|
||||||
family: explicitPricing.family,
|
baseLabel,
|
||||||
pricing: explicitPricing,
|
shortName: explicitPricing.short,
|
||||||
isEstimatedPrice: false,
|
family: explicitPricing.family,
|
||||||
|
pricing: explicitPricing,
|
||||||
|
isEstimatedPrice: false,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider);
|
const inferredFamily = inferFamilyFromProviderOrKey(rawModelKey, modelId, apiProvider);
|
||||||
return {
|
return {
|
||||||
rawModel: rawModelKey,
|
catalogPricing: null,
|
||||||
modelId,
|
info: {
|
||||||
label: derivedDisplay,
|
rawModel: rawModelKey,
|
||||||
baseLabel,
|
modelId,
|
||||||
shortName: derivedDisplay,
|
label: derivedDisplay,
|
||||||
family: inferredFamily,
|
baseLabel,
|
||||||
pricing: null,
|
shortName: derivedDisplay,
|
||||||
isEstimatedPrice: true,
|
family: inferredFamily,
|
||||||
|
pricing: null,
|
||||||
|
isEstimatedPrice: true,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 在单次遥测请求内复用同一模型身份与价格的解析结果。 */
|
/**
|
||||||
|
* 综合动态模型目录、占位符字典与价格表,解析步骤对应的模型元数据与指定时刻的单价配置。
|
||||||
|
*
|
||||||
|
* @param {string} rawModelKey 步骤记录的原始模型键(如 `MODEL_PLACEHOLDER_M320`)
|
||||||
|
* @param {Map<string, {modelId: string, label: string, quotaInfo?: object}>} [dynamicModelMap=new Map()] 从 `GetUserStatus` 提取的动态模型表
|
||||||
|
* @param {string} [apiProvider=''] API 提供商枚举
|
||||||
|
* @param {string} [modelDisplayName=''] 已知的模型展示名称
|
||||||
|
* @param {string} [responseModel=''] 实际响应的上游模型 ID(如 `gemini-3.8-flash-n`)
|
||||||
|
* @param {number|string|null} [atMs=0] 步骤发生时间戳(缺省按当前时刻匹配阶段价格)
|
||||||
|
*/
|
||||||
|
export function resolveModelInfo(
|
||||||
|
rawModelKey,
|
||||||
|
dynamicModelMap = new Map(),
|
||||||
|
apiProvider = '',
|
||||||
|
modelDisplayName = '',
|
||||||
|
responseModel = '',
|
||||||
|
atMs = 0
|
||||||
|
) {
|
||||||
|
const { catalogPricing, info } = resolveModelCatalogEntry(
|
||||||
|
rawModelKey,
|
||||||
|
dynamicModelMap,
|
||||||
|
apiProvider,
|
||||||
|
modelDisplayName,
|
||||||
|
responseModel
|
||||||
|
);
|
||||||
|
if (!catalogPricing) return info;
|
||||||
|
const effectivePricing = resolvePricingAt(catalogPricing, atMs);
|
||||||
|
return effectivePricing === catalogPricing ? info : { ...info, pricing: effectivePricing };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 在单次遥测请求内按模型身份与价格阶段复用解析结果。 */
|
||||||
export function createStepModelResolver(dynamicModelMap) {
|
export function createStepModelResolver(dynamicModelMap) {
|
||||||
const models = new Map();
|
const models = new Map();
|
||||||
return (step) => {
|
return (step) => {
|
||||||
const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step;
|
const stepMs = extractStepTimestampMs(step);
|
||||||
|
const { modelKey, apiProvider = '', modelDisplayName = '', responseModel = '' } = step || {};
|
||||||
if (
|
if (
|
||||||
typeof modelKey !== 'string' ||
|
typeof modelKey !== 'string' ||
|
||||||
typeof apiProvider !== 'string' ||
|
typeof apiProvider !== 'string' ||
|
||||||
typeof modelDisplayName !== 'string' ||
|
typeof modelDisplayName !== 'string' ||
|
||||||
typeof responseModel !== 'string'
|
typeof responseModel !== 'string'
|
||||||
) {
|
) {
|
||||||
return resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
return resolveModelInfo(
|
||||||
|
modelKey,
|
||||||
|
dynamicModelMap,
|
||||||
|
apiProvider,
|
||||||
|
modelDisplayName,
|
||||||
|
responseModel,
|
||||||
|
stepMs
|
||||||
|
);
|
||||||
}
|
}
|
||||||
let providers = models.get(modelKey);
|
let providers = models.get(modelKey);
|
||||||
if (!providers) models.set(modelKey, (providers = new Map()));
|
if (!providers) models.set(modelKey, (providers = new Map()));
|
||||||
@@ -294,12 +401,50 @@ export function createStepModelResolver(dynamicModelMap) {
|
|||||||
if (!names) providers.set(apiProvider, (names = new Map()));
|
if (!names) providers.set(apiProvider, (names = new Map()));
|
||||||
let responses = names.get(modelDisplayName);
|
let responses = names.get(modelDisplayName);
|
||||||
if (!responses) names.set(modelDisplayName, (responses = new Map()));
|
if (!responses) names.set(modelDisplayName, (responses = new Map()));
|
||||||
let info = responses.get(responseModel);
|
let cached = responses.get(responseModel);
|
||||||
if (!info) {
|
if (!cached) {
|
||||||
info = resolveModelInfo(modelKey, dynamicModelMap, apiProvider, modelDisplayName, responseModel);
|
const { catalogPricing, info } = resolveModelCatalogEntry(
|
||||||
responses.set(responseModel, info);
|
modelKey,
|
||||||
|
dynamicModelMap,
|
||||||
|
apiProvider,
|
||||||
|
modelDisplayName,
|
||||||
|
responseModel
|
||||||
|
);
|
||||||
|
cached = {
|
||||||
|
catalogPricing,
|
||||||
|
baseInfo: info,
|
||||||
|
byPhaseIdx: catalogPricing?.phases?.length ? new Map() : null,
|
||||||
|
};
|
||||||
|
responses.set(responseModel, cached);
|
||||||
}
|
}
|
||||||
return info;
|
if (!cached.byPhaseIdx) {
|
||||||
|
return cached.baseInfo;
|
||||||
|
}
|
||||||
|
const tMs = stepMs > 0 ? stepMs : Date.now();
|
||||||
|
const phases = cached.catalogPricing.phases;
|
||||||
|
let phaseIdx = -1;
|
||||||
|
for (let i = 0; i < phases.length; i++) {
|
||||||
|
const ph = phases[i];
|
||||||
|
const fromMs = Number.isFinite(ph.fromMs) ? ph.fromMs : -Infinity;
|
||||||
|
const untilMs = Number.isFinite(ph.untilMs) ? ph.untilMs : Infinity;
|
||||||
|
if (tMs >= fromMs && tMs < untilMs) {
|
||||||
|
phaseIdx = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let phasedInfo = cached.byPhaseIdx.get(phaseIdx);
|
||||||
|
if (!phasedInfo) {
|
||||||
|
const effectivePricing =
|
||||||
|
phaseIdx >= 0
|
||||||
|
? resolvePricingAt(cached.catalogPricing, tMs)
|
||||||
|
: cached.catalogPricing;
|
||||||
|
phasedInfo =
|
||||||
|
effectivePricing === cached.catalogPricing
|
||||||
|
? cached.baseInfo
|
||||||
|
: { ...cached.baseInfo, pricing: effectivePricing };
|
||||||
|
cached.byPhaseIdx.set(phaseIdx, phasedInfo);
|
||||||
|
}
|
||||||
|
return phasedInfo;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,12 +488,17 @@ export function formatUpstreamModelId(rawUpstream = '', mInfo = null) {
|
|||||||
*/
|
*/
|
||||||
export function computeStepCost(step, pricing) {
|
export function computeStepCost(step, pricing) {
|
||||||
if (!pricing) return null;
|
if (!pricing) return null;
|
||||||
|
const stepMs = extractStepTimestampMs(step);
|
||||||
|
const effectivePricing =
|
||||||
|
stepMs > 0 && Array.isArray(pricing.phases) && pricing.phases.length > 0
|
||||||
|
? resolvePricingAt(pricing, stepMs)
|
||||||
|
: pricing;
|
||||||
const safeTok = (v) => {
|
const safeTok = (v) => {
|
||||||
const n = Number(v);
|
const n = Number(v);
|
||||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||||
};
|
};
|
||||||
const inCost = (safeTok(step?.inputTokens) / 1_000_000) * pricing.input;
|
const inCost = (safeTok(step?.inputTokens) / 1_000_000) * effectivePricing.input;
|
||||||
const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * pricing.cache;
|
const cacheCost = (safeTok(step?.cacheReadTokens) / 1_000_000) * effectivePricing.cache;
|
||||||
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * pricing.output;
|
const outCost = (safeTok(step?.outputTokens) / 1_000_000) * effectivePricing.output;
|
||||||
return inCost + cacheCost + outCost;
|
return inCost + cacheCost + outCost;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,7 +11,7 @@
|
|||||||
|
|
||||||
import { existsSync } from 'node:fs';
|
import { existsSync } from 'node:fs';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
import { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
DEFAULT_ARCHIVE_FALLBACK_URL,
|
DEFAULT_ARCHIVE_FALLBACK_URL,
|
||||||
DEFAULT_DOWNLOAD_URL,
|
DEFAULT_DOWNLOAD_URL,
|
||||||
@@ -23,6 +23,7 @@ import {
|
|||||||
PLUGIN_ROOT,
|
PLUGIN_ROOT,
|
||||||
REMOTE_CATALOG_CACHE_FILE,
|
REMOTE_CATALOG_CACHE_FILE,
|
||||||
cloudSyncState,
|
cloudSyncState,
|
||||||
|
detectCustomGitForkRepo,
|
||||||
loadJson,
|
loadJson,
|
||||||
pluginUpdateState,
|
pluginUpdateState,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
@@ -33,6 +34,24 @@ import {
|
|||||||
export const MODEL_PRICING = {};
|
export const MODEL_PRICING = {};
|
||||||
export const PLACEHOLDER_MAP = {};
|
export const PLACEHOLDER_MAP = {};
|
||||||
export let pricingCatalogRevision = 0;
|
export let pricingCatalogRevision = 0;
|
||||||
|
let pricingPhaseBoundariesMs = [];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返回给定时刻已跨过的全局价格阶段边界计数,供遥测与聚合快照在跨越优惠截止时间点时自动失效重算。
|
||||||
|
*
|
||||||
|
* @param {number} [atMs=Date.now()]
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
export function getPricingPhaseEpoch(atMs = Date.now()) {
|
||||||
|
const t = Number(atMs);
|
||||||
|
if (!Number.isFinite(t) || t <= 0 || pricingPhaseBoundariesMs.length === 0) return 0;
|
||||||
|
let epoch = 0;
|
||||||
|
for (let i = 0; i < pricingPhaseBoundariesMs.length; i++) {
|
||||||
|
if (t >= pricingPhaseBoundariesMs[i]) epoch = i + 1;
|
||||||
|
else break;
|
||||||
|
}
|
||||||
|
return epoch;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
* 校验字符串是否为合法的 SemVer 2.0 语义化版本号格式(支持 `-prerelease` 与 `+build` 元数据)。
|
||||||
@@ -189,13 +208,7 @@ function normalizeModelFamily(rawFamily) {
|
|||||||
return f;
|
return f;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function isValidPricingRateTriplet(entry) {
|
||||||
* 校验单条模型价格配置是否合法:
|
|
||||||
* - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞);
|
|
||||||
* - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00);
|
|
||||||
* - `short`/`family` 必须为非空字符串。
|
|
||||||
*/
|
|
||||||
function isValidPricingEntry(entry) {
|
|
||||||
if (!entry || typeof entry !== 'object') return false;
|
if (!entry || typeof entry !== 'object') return false;
|
||||||
if (
|
if (
|
||||||
typeof entry.input !== 'number' ||
|
typeof entry.input !== 'number' ||
|
||||||
@@ -209,6 +222,52 @@ function isValidPricingEntry(entry) {
|
|||||||
if (!Number.isFinite(cache) || cache < 0 || cache > 10000) return false;
|
if (!Number.isFinite(cache) || cache < 0 || cache > 10000) return false;
|
||||||
if (!Number.isFinite(output) || output < 0 || output > 10000) return false;
|
if (!Number.isFinite(output) || output < 0 || output > 10000) return false;
|
||||||
if (input === 0 && output === 0) return false;
|
if (input === 0 && output === 0) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验并归一化单个时间阶段单价配置(左闭右开 `[fromMs, untilMs)`)。
|
||||||
|
* 至少需声明合法的 `from` 或 `until` ISO 时间戳,且若同时声明须满足 `fromMs < untilMs`。
|
||||||
|
*/
|
||||||
|
function sanitizePricingPhase(rawPhase) {
|
||||||
|
if (!isValidPricingRateTriplet(rawPhase)) return null;
|
||||||
|
let from = null;
|
||||||
|
let fromMs = -Infinity;
|
||||||
|
if (rawPhase.from !== undefined && rawPhase.from !== null) {
|
||||||
|
if (typeof rawPhase.from !== 'string' || !rawPhase.from.trim()) return null;
|
||||||
|
const parsedFrom = parseIsoMs(rawPhase.from.trim());
|
||||||
|
if (!parsedFrom || parsedFrom <= 0) return null;
|
||||||
|
from = rawPhase.from.trim();
|
||||||
|
fromMs = parsedFrom;
|
||||||
|
}
|
||||||
|
let until = null;
|
||||||
|
let untilMs = Infinity;
|
||||||
|
if (rawPhase.until !== undefined && rawPhase.until !== null) {
|
||||||
|
if (typeof rawPhase.until !== 'string' || !rawPhase.until.trim()) return null;
|
||||||
|
const parsedUntil = parseIsoMs(rawPhase.until.trim());
|
||||||
|
if (!parsedUntil || parsedUntil <= 0) return null;
|
||||||
|
until = rawPhase.until.trim();
|
||||||
|
untilMs = parsedUntil;
|
||||||
|
}
|
||||||
|
if (from === null && until === null) return null;
|
||||||
|
if (fromMs >= untilMs) return null;
|
||||||
|
return {
|
||||||
|
...(from !== null ? { from, fromMs } : {}),
|
||||||
|
...(until !== null ? { until, untilMs } : {}),
|
||||||
|
input: rawPhase.input,
|
||||||
|
cache: rawPhase.cache,
|
||||||
|
output: rawPhase.output,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验单条模型价格配置是否合法:
|
||||||
|
* - `input`/`cache`/`output` 必须为原生 `number` 类型(阻止 `Number(null) === 0` 或 `Number("") === 0` 的隐式转换漏洞);
|
||||||
|
* - 数值必须非负且 `<= 10000`,且至少 `input > 0` 或 `output > 0`(拒绝全 0 伪价格将未定价模型篡改为 $0.00);
|
||||||
|
* - `short`/`family` 必须为非空字符串。
|
||||||
|
*/
|
||||||
|
function isValidPricingEntry(entry) {
|
||||||
|
if (!isValidPricingRateTriplet(entry)) return false;
|
||||||
if (typeof entry.short !== 'string' || !entry.short.trim()) return false;
|
if (typeof entry.short !== 'string' || !entry.short.trim()) return false;
|
||||||
if (typeof entry.family !== 'string' || !entry.family.trim()) return false;
|
if (typeof entry.family !== 'string' || !entry.family.trim()) return false;
|
||||||
return true;
|
return true;
|
||||||
@@ -239,12 +298,20 @@ export function sanitizeCatalogPayload(raw) {
|
|||||||
for (const [k, v] of Object.entries(raw.pricing)) {
|
for (const [k, v] of Object.entries(raw.pricing)) {
|
||||||
const key = String(k || '').trim();
|
const key = String(k || '').trim();
|
||||||
if (!key || !isValidPricingEntry(v)) continue;
|
if (!key || !isValidPricingEntry(v)) continue;
|
||||||
|
let phases = null;
|
||||||
|
if (Array.isArray(v.phases)) {
|
||||||
|
const cleanedPhases = v.phases.map(sanitizePricingPhase).filter(Boolean);
|
||||||
|
if (cleanedPhases.length > 0) {
|
||||||
|
phases = cleanedPhases;
|
||||||
|
}
|
||||||
|
}
|
||||||
pricing[key] = {
|
pricing[key] = {
|
||||||
input: v.input,
|
input: v.input,
|
||||||
cache: v.cache,
|
cache: v.cache,
|
||||||
output: v.output,
|
output: v.output,
|
||||||
short: String(v.short).trim(),
|
short: String(v.short).trim(),
|
||||||
family: normalizeModelFamily(v.family),
|
family: normalizeModelFamily(v.family),
|
||||||
|
...(phases ? { phases } : {}),
|
||||||
};
|
};
|
||||||
validPricingCount++;
|
validPricingCount++;
|
||||||
}
|
}
|
||||||
@@ -332,10 +399,18 @@ export function rebuildActiveCatalog() {
|
|||||||
let catalogVersion = 'builtin';
|
let catalogVersion = 'builtin';
|
||||||
let updatedAt = null;
|
let updatedAt = null;
|
||||||
const installedVersion = readInstalledPluginVersion();
|
const installedVersion = readInstalledPluginVersion();
|
||||||
|
const customForkRepo = detectCustomGitForkRepo();
|
||||||
|
const customForkPrefix = customForkRepo ? `/${customForkRepo.toLowerCase()}` : '';
|
||||||
let latestPluginVersion = installedVersion;
|
let latestPluginVersion = installedVersion;
|
||||||
let releaseUrl = DEFAULT_RELEASE_URL;
|
let releaseUrl = customForkRepo
|
||||||
let downloadUrl = DEFAULT_DOWNLOAD_URL;
|
? `https://github.com/${customForkRepo}/releases/latest`
|
||||||
let archiveFallbackUrl = DEFAULT_ARCHIVE_FALLBACK_URL;
|
: DEFAULT_RELEASE_URL;
|
||||||
|
let downloadUrl = customForkRepo
|
||||||
|
? `https://github.com/${customForkRepo}/releases/latest/download/usage-monitor.zip`
|
||||||
|
: DEFAULT_DOWNLOAD_URL;
|
||||||
|
let archiveFallbackUrl = customForkRepo
|
||||||
|
? `https://codeload.github.com/${customForkRepo}/zip/refs/heads/main`
|
||||||
|
: DEFAULT_ARCHIVE_FALLBACK_URL;
|
||||||
|
|
||||||
for (const { kind, cat } of layers) {
|
for (const { kind, cat } of layers) {
|
||||||
Object.assign(nextPricing, cat.pricing);
|
Object.assign(nextPricing, cat.pricing);
|
||||||
@@ -345,21 +420,39 @@ export function rebuildActiveCatalog() {
|
|||||||
}
|
}
|
||||||
if (cat.catalogVersion) catalogVersion = cat.catalogVersion;
|
if (cat.catalogVersion) catalogVersion = cat.catalogVersion;
|
||||||
if (cat.updatedAt) updatedAt = cat.updatedAt;
|
if (cat.updatedAt) updatedAt = cat.updatedAt;
|
||||||
if (cat.latestPluginVersion) {
|
const isFromCustomFork = Boolean(
|
||||||
// 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本
|
customForkPrefix &&
|
||||||
|
typeof cat.sourceUrl === 'string' &&
|
||||||
|
cat.sourceUrl.toLowerCase().includes(customForkPrefix)
|
||||||
|
);
|
||||||
|
const shouldAcceptCatalogReleaseMeta = !customForkRepo || isFromCustomFork;
|
||||||
|
if (shouldAcceptCatalogReleaseMeta && cat.latestPluginVersion) {
|
||||||
|
// 以当前更高优先级层的 latestPluginVersion 为准,但永不低于本地已安装版本;自定义 Fork 忽略上游版本号
|
||||||
latestPluginVersion =
|
latestPluginVersion =
|
||||||
compareSemver(cat.latestPluginVersion, installedVersion) > 0
|
compareSemver(cat.latestPluginVersion, installedVersion) > 0
|
||||||
? cat.latestPluginVersion
|
? cat.latestPluginVersion
|
||||||
: installedVersion;
|
: installedVersion;
|
||||||
}
|
}
|
||||||
if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl;
|
if (shouldAcceptCatalogReleaseMeta) {
|
||||||
if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl;
|
if (cat.hasReleaseUrl) releaseUrl = cat.releaseUrl;
|
||||||
if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl;
|
if (cat.hasDownloadUrl) downloadUrl = cat.downloadUrl;
|
||||||
|
if (cat.hasArchiveFallbackUrl) archiveFallbackUrl = cat.archiveFallbackUrl;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k];
|
for (const k of Object.keys(MODEL_PRICING)) delete MODEL_PRICING[k];
|
||||||
Object.assign(MODEL_PRICING, nextPricing);
|
Object.assign(MODEL_PRICING, nextPricing);
|
||||||
|
|
||||||
|
const boundarySet = new Set();
|
||||||
|
for (const entry of Object.values(nextPricing)) {
|
||||||
|
if (!Array.isArray(entry?.phases)) continue;
|
||||||
|
for (const ph of entry.phases) {
|
||||||
|
if (Number.isFinite(ph.fromMs) && ph.fromMs > 0) boundarySet.add(ph.fromMs);
|
||||||
|
if (Number.isFinite(ph.untilMs) && ph.untilMs > 0) boundarySet.add(ph.untilMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pricingPhaseBoundariesMs = Array.from(boundarySet).sort((a, b) => a - b);
|
||||||
|
|
||||||
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
for (const k of Object.keys(PLACEHOLDER_MAP)) delete PLACEHOLDER_MAP[k];
|
||||||
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
Object.assign(PLACEHOLDER_MAP, nextPlaceholders);
|
||||||
pricingCatalogRevision += 1;
|
pricingCatalogRevision += 1;
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 零外部依赖的二进制 Protobuf Wire 跳读游标与 `prototext` 字符串反转义原语 (`proto-wire.mjs`)。
|
||||||
|
*
|
||||||
|
* 核心能力:
|
||||||
|
* 1. 无需引入 `protobufjs`,以 `O(1)` 游标位移跳过大体积定长/变长/Group 载荷;
|
||||||
|
* 2. 基于 `BigInt` 无损解码 64-bit Varint、`google.protobuf.Timestamp` 纳秒级时间戳与 `Duration`;
|
||||||
|
* 3. 按原始 UTF-8 字节流无损反转义 `prototext` 的 `\ddd` 八进制、`\xHH` 十六进制与 `\uXXXX` 多字节字符。
|
||||||
|
*/
|
||||||
|
|
||||||
|
const protoUtf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-8') : null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解码 Protobuf Text Format (`prototext`) 字符串字面量,兼容 UTF-8 原文与 `\ddd` / `\xHH` 字节转义。
|
||||||
|
*
|
||||||
|
* @param {string} raw
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function unescapePbtxtString(raw) {
|
||||||
|
if (typeof raw !== 'string' || !raw) return '';
|
||||||
|
if (!raw.includes('\\')) return raw;
|
||||||
|
const bytes = [];
|
||||||
|
for (let i = 0; i < raw.length; i++) {
|
||||||
|
const ch = raw[i];
|
||||||
|
if (ch !== '\\' || i + 1 >= raw.length) {
|
||||||
|
const encoded = Buffer.from(ch, 'utf8');
|
||||||
|
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const next = raw[++i];
|
||||||
|
if (next >= '0' && next <= '7') {
|
||||||
|
let oct = next;
|
||||||
|
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||||
|
if (i + 1 < raw.length && raw[i + 1] >= '0' && raw[i + 1] <= '7') oct += raw[++i];
|
||||||
|
bytes.push(parseInt(oct, 8) & 0xff);
|
||||||
|
} else if ((next === 'x' || next === 'X') && i + 2 < raw.length) {
|
||||||
|
const hex = raw.slice(i + 1, i + 3);
|
||||||
|
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
||||||
|
bytes.push(parseInt(hex, 16));
|
||||||
|
i += 2;
|
||||||
|
} else {
|
||||||
|
bytes.push(next.charCodeAt(0));
|
||||||
|
}
|
||||||
|
} else if (next === 'u' && i + 4 < raw.length) {
|
||||||
|
const uHex = raw.slice(i + 1, i + 5);
|
||||||
|
if (/^[0-9a-fA-F]{4}$/.test(uHex)) {
|
||||||
|
const encoded = Buffer.from(String.fromCharCode(parseInt(uHex, 16)), 'utf8');
|
||||||
|
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||||
|
i += 4;
|
||||||
|
} else {
|
||||||
|
bytes.push(next.charCodeAt(0));
|
||||||
|
}
|
||||||
|
} else if (next === 'n') {
|
||||||
|
bytes.push(0x0a);
|
||||||
|
} else if (next === 'r') {
|
||||||
|
bytes.push(0x0d);
|
||||||
|
} else if (next === 't') {
|
||||||
|
bytes.push(0x09);
|
||||||
|
} else {
|
||||||
|
const encoded = Buffer.from(next, 'utf8');
|
||||||
|
for (let b = 0; b < encoded.length; b++) bytes.push(encoded[b]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Buffer.from(bytes).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function toUint8Array(raw) {
|
||||||
|
if (!raw) return null;
|
||||||
|
if (raw instanceof Uint8Array) return raw;
|
||||||
|
if (ArrayBuffer.isView(raw)) {
|
||||||
|
return new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength);
|
||||||
|
}
|
||||||
|
if (raw instanceof ArrayBuffer) {
|
||||||
|
return new Uint8Array(raw);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeUtf8Slice(buf, start, end) {
|
||||||
|
if (start >= end) return '';
|
||||||
|
if (protoUtf8Decoder) {
|
||||||
|
return protoUtf8Decoder.decode(buf.subarray(start, end));
|
||||||
|
}
|
||||||
|
return Buffer.from(buf.buffer, buf.byteOffset + start, end - start).toString('utf8');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readProtoVarint(buf, state, limit = buf.length) {
|
||||||
|
if (state.off >= limit) return 0n;
|
||||||
|
const b0 = buf[state.off];
|
||||||
|
if (b0 < 0x80) {
|
||||||
|
state.off += 1;
|
||||||
|
return BigInt(b0);
|
||||||
|
}
|
||||||
|
let result = 0n;
|
||||||
|
let shift = 0n;
|
||||||
|
for (let i = 0; i < 10 && state.off < limit; i++) {
|
||||||
|
const byte = buf[state.off++];
|
||||||
|
result |= BigInt(byte & 0x7f) << shift;
|
||||||
|
if ((byte & 0x80) === 0) {
|
||||||
|
return BigInt.asUintN(64, result);
|
||||||
|
}
|
||||||
|
shift += 7n;
|
||||||
|
}
|
||||||
|
while (state.off < limit && (buf[state.off++] & 0x80) !== 0) {
|
||||||
|
// 安全排空超长 varint 延续字节
|
||||||
|
}
|
||||||
|
return BigInt.asUintN(64, result);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readSubEnd(buf, state, limit = buf.length) {
|
||||||
|
const len = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
|
||||||
|
return Math.min(limit, state.off + len);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readProtoString(buf, state, limit = buf.length) {
|
||||||
|
const end = readSubEnd(buf, state, limit);
|
||||||
|
const str = decodeUtf8Slice(buf, state.off, end);
|
||||||
|
state.off = end;
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function skipProtoField(buf, state, wireType, limit = buf.length) {
|
||||||
|
if (wireType === 0) {
|
||||||
|
readProtoVarint(buf, state, limit);
|
||||||
|
} else if (wireType === 1) {
|
||||||
|
state.off = Math.min(limit, state.off + 8);
|
||||||
|
} else if (wireType === 2) {
|
||||||
|
state.off = readSubEnd(buf, state, limit);
|
||||||
|
} else if (wireType === 5) {
|
||||||
|
state.off = Math.min(limit, state.off + 4);
|
||||||
|
} else if (wireType === 3) {
|
||||||
|
while (state.off < limit) {
|
||||||
|
const innerTag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, limit)));
|
||||||
|
const innerWt = innerTag & 7;
|
||||||
|
if (innerWt === 4) break;
|
||||||
|
skipProtoField(buf, state, innerWt, limit);
|
||||||
|
}
|
||||||
|
} else if (wireType !== 4) {
|
||||||
|
state.off = limit;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeProtoTimestampSlice(buf, state, end) {
|
||||||
|
let seconds = 0n;
|
||||||
|
let nanos = 0n;
|
||||||
|
while (state.off < end) {
|
||||||
|
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||||
|
const fn = tag >>> 3;
|
||||||
|
const wt = tag & 7;
|
||||||
|
if (fn === 1 && wt === 0) {
|
||||||
|
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
|
||||||
|
} else if (fn === 2 && wt === 0) {
|
||||||
|
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
|
||||||
|
} else {
|
||||||
|
skipProtoField(buf, state, wt, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.off = end;
|
||||||
|
if (seconds <= 0n || seconds > 253402300799n) return '';
|
||||||
|
const baseIso = new Date(Number(seconds) * 1000).toISOString().slice(0, 19);
|
||||||
|
if (nanos > 0n && nanos < 1_000_000_000n) {
|
||||||
|
const frac = String(nanos).padStart(9, '0').replace(/0+$/, '');
|
||||||
|
return frac ? `${baseIso}.${frac}Z` : `${baseIso}Z`;
|
||||||
|
}
|
||||||
|
return `${baseIso}Z`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeProtoDurationSlice(buf, state, end) {
|
||||||
|
let seconds = 0n;
|
||||||
|
let nanos = 0n;
|
||||||
|
while (state.off < end) {
|
||||||
|
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||||
|
const fn = tag >>> 3;
|
||||||
|
const wt = tag & 7;
|
||||||
|
if (fn === 1 && wt === 0) {
|
||||||
|
seconds = BigInt.asIntN(64, readProtoVarint(buf, state, end));
|
||||||
|
} else if (fn === 2 && wt === 0) {
|
||||||
|
nanos = BigInt.asIntN(32, readProtoVarint(buf, state, end));
|
||||||
|
} else {
|
||||||
|
skipProtoField(buf, state, wt, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.off = end;
|
||||||
|
const totalNs = seconds * 1_000_000_000n + nanos;
|
||||||
|
if (totalNs < 0n) return '';
|
||||||
|
if (totalNs === 0n) return '0s';
|
||||||
|
const wholeSec = totalNs / 1_000_000_000n;
|
||||||
|
const remNs = Number(totalNs % 1_000_000_000n);
|
||||||
|
if (remNs === 0) return `${wholeSec}s`;
|
||||||
|
const frac = String(remNs).padStart(9, '0').replace(/0+$/, '');
|
||||||
|
return `${wholeSec}.${frac}s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeProtoMapStringEntry(buf, state, end) {
|
||||||
|
let key = '';
|
||||||
|
let val = '';
|
||||||
|
while (state.off < end) {
|
||||||
|
const tag = Number(BigInt.asUintN(32, readProtoVarint(buf, state, end)));
|
||||||
|
const fn = tag >>> 3;
|
||||||
|
const wt = tag & 7;
|
||||||
|
if (fn === 1 && wt === 2) {
|
||||||
|
key = readProtoString(buf, state, end);
|
||||||
|
} else if (fn === 2 && wt === 2) {
|
||||||
|
val = readProtoString(buf, state, end);
|
||||||
|
} else {
|
||||||
|
skipProtoField(buf, state, wt, end);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.off = end;
|
||||||
|
return [key, val];
|
||||||
|
}
|
||||||
@@ -9,7 +9,8 @@
|
|||||||
* - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略且存在尚未过期的有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。
|
* - Proto3 零值省略兼容:当配额耗尽(`remainingFraction === 0`)导致字段被省略且存在尚未过期的有效 `resetTime` 时,正确识别为 0% 剩余(100% 已用)。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { parseIsoMs } from '../speed-metrics.mjs';
|
import { parseIsoMs } from '../trajectory-metrics.mjs';
|
||||||
|
import { THIRD_PARTY_POOL_RE } from '../shared/telemetry-display-rules.mjs';
|
||||||
import {
|
import {
|
||||||
isArgonModelIdentifier,
|
isArgonModelIdentifier,
|
||||||
isCarbonModelIdentifier,
|
isCarbonModelIdentifier,
|
||||||
@@ -90,9 +91,6 @@ function classifyOfficialBucketWindow(bucket, _groupBucketCount = 1, nowMs = Dat
|
|||||||
return 'weekly';
|
return 'weekly';
|
||||||
}
|
}
|
||||||
|
|
||||||
const THIRD_PARTY_POOL_RE =
|
|
||||||
/3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。
|
* 根据分组名称、分组描述及桶 ID 识别配额池归属身份(`Gemini` / `Argon` / `Carbon` / `Claude & GPT`)。
|
||||||
* 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。
|
* 优先识别显式的第三方模型池标识,防止分组描述附带 `"separate from Gemini"` 时把第三方池误吞入 Gemini。
|
||||||
|
|||||||
@@ -1,158 +1,91 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview 用户偏好设置 Schema、枚举常量、默认值与无状态纯函数归一化器。
|
* @fileoverview 用户偏好设置完整 Schema、默认对象工厂与带上下文窗口校验的整表归一化器。
|
||||||
*
|
*
|
||||||
* 独立于文件系统与运行时状态,统一约束「常规 / 结构 / 其他」三栏偏好结构,
|
* 所有跨端通用枚举与单项纯函数归一化规则统一源自 `../shared/settings-normalization.mjs`。
|
||||||
* 并无缝兼容旧版 `settings.json`(如 3 槽固定数组中的 `'none'`、`enableWindowOverlay`、`autoUpdatePlugin` 等)。
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
import { isContextWindowSettingId, isContextWindowOption } from './context-windows.mjs';
|
||||||
|
import {
|
||||||
|
DEFAULT_HOVER_MODULES,
|
||||||
|
DEFAULT_OVERVIEW_METRICS,
|
||||||
|
DEFAULT_OVERVIEW_MODULES,
|
||||||
|
DEFAULT_POPOVER_WIDTH,
|
||||||
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
|
DEFAULT_TOPBAR_SLOTS,
|
||||||
|
FONT_SCALE_KEYS,
|
||||||
|
MAX_POPOVER_WIDTH,
|
||||||
|
MAX_TOPBAR_SLOTS,
|
||||||
|
MIN_POPOVER_WIDTH,
|
||||||
|
MIN_TOPBAR_SLOTS,
|
||||||
|
OVERVIEW_METRIC_KEYS,
|
||||||
|
OVERVIEW_MODULE_KEYS,
|
||||||
|
POPOVER_WIDTH_MODES,
|
||||||
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
|
STEP_TOKEN_SEGMENT_ALIASES,
|
||||||
|
SUPPORTED_LANGUAGES,
|
||||||
|
THEME_ACCENT_KEYS,
|
||||||
|
TOPBAR_SLOT_KEYS,
|
||||||
|
normalizeFontScale,
|
||||||
|
normalizeHoverModules,
|
||||||
|
normalizeLanguageSetting,
|
||||||
|
normalizeModelDisplayMode,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
|
normalizeOverviewMetrics,
|
||||||
|
normalizeOverviewModules,
|
||||||
|
normalizePluginUpdateMode,
|
||||||
|
normalizePopoverWidth,
|
||||||
|
normalizePopoverWidthMode,
|
||||||
|
normalizeStandalonePort,
|
||||||
|
normalizeStepTableColumns,
|
||||||
|
normalizeStepTokenComboFormat,
|
||||||
|
normalizeThemeAccent,
|
||||||
|
normalizeTopbarCapsuleSlots,
|
||||||
|
normalizeWeeklyLimitMode,
|
||||||
|
normalizeWindowMountMode,
|
||||||
|
parseStepTokenComboSegments,
|
||||||
|
} from '../shared/settings-normalization.mjs';
|
||||||
|
|
||||||
export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']);
|
export {
|
||||||
|
DEFAULT_HOVER_MODULES,
|
||||||
export const THEME_ACCENT_KEYS = Object.freeze([
|
DEFAULT_OVERVIEW_METRICS,
|
||||||
'host',
|
DEFAULT_OVERVIEW_MODULES,
|
||||||
'blue',
|
DEFAULT_POPOVER_WIDTH,
|
||||||
'emerald',
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
'amber',
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
'violet',
|
DEFAULT_TOPBAR_SLOTS,
|
||||||
'cyan',
|
FONT_SCALE_KEYS,
|
||||||
'rose',
|
MAX_POPOVER_WIDTH,
|
||||||
]);
|
MAX_TOPBAR_SLOTS,
|
||||||
|
MIN_POPOVER_WIDTH,
|
||||||
export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']);
|
MIN_TOPBAR_SLOTS,
|
||||||
|
OVERVIEW_METRIC_KEYS,
|
||||||
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
OVERVIEW_MODULE_KEYS,
|
||||||
'context',
|
POPOVER_WIDTH_MODES,
|
||||||
'tps',
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
'ttft',
|
STEP_TOKEN_SEGMENT_ALIASES,
|
||||||
'avg_tps',
|
SUPPORTED_LANGUAGES,
|
||||||
'cost',
|
THEME_ACCENT_KEYS,
|
||||||
'session_cost',
|
TOPBAR_SLOT_KEYS,
|
||||||
'cache_hit',
|
normalizeFontScale,
|
||||||
'session_tokens',
|
normalizeHoverModules,
|
||||||
'quota_auto',
|
normalizeLanguageSetting,
|
||||||
'gemini_5h',
|
normalizeModelDisplayMode,
|
||||||
'gemini_weekly',
|
normalizeOrchestratorIdMode,
|
||||||
'claude_5h',
|
normalizeOverviewMetrics,
|
||||||
'claude_weekly',
|
normalizeOverviewModules,
|
||||||
]);
|
normalizePluginUpdateMode,
|
||||||
|
normalizePopoverWidth,
|
||||||
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
normalizePopoverWidthMode,
|
||||||
export const MIN_TOPBAR_SLOTS = 1;
|
normalizeStandalonePort,
|
||||||
export const MAX_TOPBAR_SLOTS = 5;
|
normalizeStepTableColumns,
|
||||||
|
normalizeStepTokenComboFormat,
|
||||||
export const OVERVIEW_MODULE_KEYS = Object.freeze([
|
normalizeThemeAccent,
|
||||||
'metrics',
|
normalizeTopbarCapsuleSlots,
|
||||||
'context',
|
normalizeWeeklyLimitMode,
|
||||||
'quotas',
|
normalizeWindowMountMode,
|
||||||
'live_tasks',
|
parseStepTokenComboSegments,
|
||||||
]);
|
};
|
||||||
|
|
||||||
export const DEFAULT_OVERVIEW_MODULES = Object.freeze([
|
|
||||||
'metrics',
|
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
|
||||||
|
|
||||||
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'avg_tps',
|
|
||||||
'step_cost',
|
|
||||||
'session_cost',
|
|
||||||
'cache_hit',
|
|
||||||
'session_tokens',
|
|
||||||
'context_usage',
|
|
||||||
'quota_tightest',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_OVERVIEW_METRICS = Object.freeze([
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'avg_tps',
|
|
||||||
'step_cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
|
|
||||||
'step',
|
|
||||||
'time',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'duration',
|
|
||||||
'tokens_combo',
|
|
||||||
'tokens_io_cache',
|
|
||||||
'tokens_custom',
|
|
||||||
'input_tokens',
|
|
||||||
'cache_tokens',
|
|
||||||
'output_tokens',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
|
|
||||||
'step',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'tokens_combo',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
|
||||||
|
|
||||||
export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
|
|
||||||
context: 'context',
|
|
||||||
ctx: 'context',
|
|
||||||
'上下文': 'context',
|
|
||||||
in: 'in',
|
|
||||||
new: 'in',
|
|
||||||
input: 'in',
|
|
||||||
'输入': 'in',
|
|
||||||
'新输入': 'in',
|
|
||||||
out: 'out',
|
|
||||||
output: 'out',
|
|
||||||
'输出': 'out',
|
|
||||||
'总输出': 'out',
|
|
||||||
cache: 'cache',
|
|
||||||
cached: 'cache',
|
|
||||||
cache_read: 'cache',
|
|
||||||
cacheread: 'cache',
|
|
||||||
'缓存': 'cache',
|
|
||||||
'缓存读': 'cache',
|
|
||||||
think: 'think',
|
|
||||||
thinking: 'think',
|
|
||||||
'思考': 'think',
|
|
||||||
reply: 'reply',
|
|
||||||
body: 'reply',
|
|
||||||
resp: 'reply',
|
|
||||||
response: 'reply',
|
|
||||||
text: 'reply',
|
|
||||||
'正文': 'reply',
|
|
||||||
'回复': 'reply',
|
|
||||||
total: 'total',
|
|
||||||
all: 'total',
|
|
||||||
sum: 'total',
|
|
||||||
'总计': 'total',
|
|
||||||
'总token': 'total',
|
|
||||||
});
|
|
||||||
|
|
||||||
export const PLUGIN_UPDATE_MODES = Object.freeze(['off', 'manual', 'auto']);
|
|
||||||
|
|
||||||
export const MODEL_DISPLAY_MODES = Object.freeze(['short', 'upstream', 'upstream_compact']);
|
|
||||||
|
|
||||||
export const ORCHESTRATOR_ID_MODES = Object.freeze(['compact', 'full']);
|
|
||||||
|
|
||||||
export const WINDOW_MOUNT_MODES = Object.freeze(['dual', 'composer', 'sidebar']);
|
|
||||||
|
|
||||||
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
|
|
||||||
export const MIN_POPOVER_WIDTH = 440;
|
|
||||||
export const MAX_POPOVER_WIDTH = 1080;
|
|
||||||
export const DEFAULT_POPOVER_WIDTH = 580;
|
|
||||||
|
|
||||||
function isSchemaPlainObject(v) {
|
function isSchemaPlainObject(v) {
|
||||||
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
return Boolean(v) && typeof v === 'object' && !Array.isArray(v);
|
||||||
@@ -163,302 +96,6 @@ function schemaSanitizePositiveNum(val, fallback) {
|
|||||||
return Number.isFinite(num) && num > 0 ? num : fallback;
|
return Number.isFinite(num) && num > 0 ? num : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化界面语言枚举(默认 `'zh-CN'`,保持与现有界面一致;同时支持 `'auto'` 与 `'en-US'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} lang
|
|
||||||
* @returns {'auto'|'zh-CN'|'en-US'}
|
|
||||||
*/
|
|
||||||
export function normalizeLanguageSetting(lang) {
|
|
||||||
const raw = String(lang ?? '').trim();
|
|
||||||
if (!raw) return 'zh-CN';
|
|
||||||
const lower = raw.toLowerCase();
|
|
||||||
if (lower === 'auto' || lower === 'system') return 'auto';
|
|
||||||
if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US';
|
|
||||||
if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN';
|
|
||||||
return 'zh-CN';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。
|
|
||||||
*
|
|
||||||
* @param {unknown} accent
|
|
||||||
* @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'}
|
|
||||||
*/
|
|
||||||
export function normalizeThemeAccent(accent) {
|
|
||||||
const clean = String(accent ?? '').trim().toLowerCase();
|
|
||||||
return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化面板字号档位(默认 `'md'` 标准 100%)。
|
|
||||||
*
|
|
||||||
* @param {unknown} scale
|
|
||||||
* @returns {'sm'|'md'|'lg'|'xl'}
|
|
||||||
*/
|
|
||||||
export function normalizeFontScale(scale) {
|
|
||||||
const clean = String(scale ?? '').trim().toLowerCase();
|
|
||||||
return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化面板挂载方式枚举(`'dual'` 顶部栏+侧边栏 | `'composer'` 输入框+侧边栏 | `'sidebar'` 仅侧边栏),
|
|
||||||
* 兼容历史 `enableWindowOverlay` 布尔开关,默认 `'dual'`。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyEnableOverlay]
|
|
||||||
* @returns {'dual'|'composer'|'sidebar'}
|
|
||||||
*/
|
|
||||||
export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'composer' || m === 'input') return 'composer';
|
|
||||||
if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar';
|
|
||||||
if (m === 'dual' || m === 'topbar') return 'dual';
|
|
||||||
if (legacyEnableOverlay === false) return 'sidebar';
|
|
||||||
return 'dual';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化模型名称展示模式(`'short'` 精简代号 | `'upstream_compact'` 去前缀原始 ID | `'upstream'` 完整原始 ID),
|
|
||||||
* 兼容历史 `showUpstreamModel` 布尔开关,默认 `'short'`。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyShowUpstream]
|
|
||||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
|
||||||
*/
|
|
||||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
|
||||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
|
||||||
return 'upstream_compact';
|
|
||||||
}
|
|
||||||
if (m === 'short') return 'short';
|
|
||||||
if (legacyShowUpstream === true) return 'upstream';
|
|
||||||
return 'short';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` 精简代号 vs `'full'` 完整模型 ID,默认 `'compact'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @returns {'compact'|'full'}
|
|
||||||
*/
|
|
||||||
export function normalizeOrchestratorIdMode(mode) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
return m === 'full' ? 'full' : 'compact';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化悬浮主面板宽度模式(`'auto'` 自适应内容宽度 | `'custom'` 指定像素宽度,默认 `'auto'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @returns {'auto'|'custom'}
|
|
||||||
*/
|
|
||||||
export function normalizePopoverWidthMode(mode) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} width
|
|
||||||
* @returns {number}
|
|
||||||
*/
|
|
||||||
export function normalizePopoverWidth(width) {
|
|
||||||
const num = Number(width);
|
|
||||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH;
|
|
||||||
return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>}
|
|
||||||
*/
|
|
||||||
export function parseStepTokenComboSegments(raw) {
|
|
||||||
const str = String(raw ?? '').trim();
|
|
||||||
const out = [];
|
|
||||||
const seen = new Set();
|
|
||||||
if (str) {
|
|
||||||
for (const part of str.split(/[:/,|]+/)) {
|
|
||||||
const key = part.trim().toLowerCase();
|
|
||||||
if (!key) continue;
|
|
||||||
const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key)
|
|
||||||
? STEP_TOKEN_SEGMENT_ALIASES[key]
|
|
||||||
: null;
|
|
||||||
if (!mapped || seen.has(mapped)) continue;
|
|
||||||
seen.add(mapped);
|
|
||||||
out.push(/** @type {any} */ (mapped));
|
|
||||||
if (out.length >= 4) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
export function normalizeStepTokenComboFormat(raw) {
|
|
||||||
return parseStepTokenComboSegments(raw).join(':');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyAutoUpdate]
|
|
||||||
* @returns {'off'|'manual'|'auto'}
|
|
||||||
*/
|
|
||||||
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
|
||||||
if (legacyAutoUpdate === true) return 'auto';
|
|
||||||
return 'manual';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化每周额度统计模式枚举(兼容历史简写 `'tokens'` / `'cost'` 与标准枚举 `'custom_tokens'` / `'custom_cost'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
|
||||||
*/
|
|
||||||
export function normalizeWeeklyLimitMode(mode) {
|
|
||||||
const m = String(mode || '').trim().toLowerCase();
|
|
||||||
if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens';
|
|
||||||
if (m === 'custom_cost' || m === 'cost') return 'custom_cost';
|
|
||||||
return 'official';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeTopbarCapsuleSlots(raw) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...DEFAULT_TOPBAR_SLOTS];
|
|
||||||
}
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const val = String(item ?? '').trim();
|
|
||||||
if (!val || val === 'none') continue;
|
|
||||||
const mapped = val === 'step_cost' ? 'cost' : val;
|
|
||||||
if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue;
|
|
||||||
seen.add(mapped);
|
|
||||||
out.push(mapped);
|
|
||||||
if (out.length >= MAX_TOPBAR_SLOTS) break;
|
|
||||||
}
|
|
||||||
if (out.length < MIN_TOPBAR_SLOTS) {
|
|
||||||
return ['context'];
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeOverviewModules(raw) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...DEFAULT_OVERVIEW_MODULES];
|
|
||||||
}
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const val = String(item ?? '').trim();
|
|
||||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
|
||||||
seen.add(val);
|
|
||||||
out.push(val);
|
|
||||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
|
||||||
}
|
|
||||||
return out.length > 0 ? out : ['metrics'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeHoverModules(raw) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...DEFAULT_HOVER_MODULES];
|
|
||||||
}
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const val = String(item ?? '').trim();
|
|
||||||
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
|
||||||
seen.add(val);
|
|
||||||
out.push(val);
|
|
||||||
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeOverviewMetrics(raw) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...DEFAULT_OVERVIEW_METRICS];
|
|
||||||
}
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const rawVal = String(item ?? '').trim();
|
|
||||||
const val = rawVal === 'cost' ? 'step_cost' : rawVal;
|
|
||||||
if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue;
|
|
||||||
seen.add(val);
|
|
||||||
out.push(val);
|
|
||||||
if (out.length >= 4) break;
|
|
||||||
}
|
|
||||||
return out.length > 0 ? out : ['tps'];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化调用明细「按步查看」表格列配置与左右顺序(2~12 列,默认保留现有 7 列)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeStepTableColumns(raw) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...DEFAULT_STEP_TABLE_COLUMNS];
|
|
||||||
}
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const val = String(item ?? '').trim();
|
|
||||||
if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue;
|
|
||||||
seen.add(val);
|
|
||||||
out.push(val);
|
|
||||||
if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break;
|
|
||||||
}
|
|
||||||
if (out.length < 2) {
|
|
||||||
for (const fallbackCol of ['step', 'model', 'tps']) {
|
|
||||||
if (!seen.has(fallbackCol)) {
|
|
||||||
seen.add(fallbackCol);
|
|
||||||
out.push(fallbackCol);
|
|
||||||
}
|
|
||||||
if (out.length >= 2) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeModelContextWindows(value) {
|
export function normalizeModelContextWindows(value) {
|
||||||
return Object.fromEntries(
|
return Object.fromEntries(
|
||||||
Object.entries(isSchemaPlainObject(value) ? value : {}).filter(
|
Object.entries(isSchemaPlainObject(value) ? value : {}).filter(
|
||||||
@@ -467,19 +104,6 @@ export function normalizeModelContextWindows(value) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} port
|
|
||||||
* @returns {number}
|
|
||||||
*/
|
|
||||||
export function normalizeStandalonePort(port) {
|
|
||||||
const num = Number(port);
|
|
||||||
if (!Number.isInteger(num) || num <= 0) return 0;
|
|
||||||
if (num >= 1024 && num <= 65535) return num;
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
||||||
language: 'zh-CN',
|
language: 'zh-CN',
|
||||||
themeAccent: 'host',
|
themeAccent: 'host',
|
||||||
@@ -517,34 +141,12 @@ export const DEFAULT_SETTINGS_SCHEMA = Object.freeze({
|
|||||||
*/
|
*/
|
||||||
export function createDefaultSettingsObject() {
|
export function createDefaultSettingsObject() {
|
||||||
return {
|
return {
|
||||||
language: DEFAULT_SETTINGS_SCHEMA.language,
|
...DEFAULT_SETTINGS_SCHEMA,
|
||||||
themeAccent: DEFAULT_SETTINGS_SCHEMA.themeAccent,
|
|
||||||
fontScale: DEFAULT_SETTINGS_SCHEMA.fontScale,
|
|
||||||
weeklyTokenBudget: DEFAULT_SETTINGS_SCHEMA.weeklyTokenBudget,
|
|
||||||
weeklyCostBudget: DEFAULT_SETTINGS_SCHEMA.weeklyCostBudget,
|
|
||||||
weeklyLimitMode: DEFAULT_SETTINGS_SCHEMA.weeklyLimitMode,
|
|
||||||
modelDisplayMode: DEFAULT_SETTINGS_SCHEMA.modelDisplayMode,
|
|
||||||
showUpstreamModel: DEFAULT_SETTINGS_SCHEMA.showUpstreamModel,
|
|
||||||
orchestratorIdMode: DEFAULT_SETTINGS_SCHEMA.orchestratorIdMode,
|
|
||||||
pluginUpdateMode: DEFAULT_SETTINGS_SCHEMA.pluginUpdateMode,
|
|
||||||
autoUpdatePlugin: DEFAULT_SETTINGS_SCHEMA.autoUpdatePlugin,
|
|
||||||
windowMountMode: DEFAULT_SETTINGS_SCHEMA.windowMountMode,
|
|
||||||
enableWindowOverlay: DEFAULT_SETTINGS_SCHEMA.enableWindowOverlay,
|
|
||||||
popoverWidthMode: DEFAULT_SETTINGS_SCHEMA.popoverWidthMode,
|
|
||||||
popoverWidth: DEFAULT_SETTINGS_SCHEMA.popoverWidth,
|
|
||||||
enableCliStatusLine: DEFAULT_SETTINGS_SCHEMA.enableCliStatusLine,
|
|
||||||
standalonePort: DEFAULT_SETTINGS_SCHEMA.standalonePort,
|
|
||||||
showTopbarMultiSession: DEFAULT_SETTINGS_SCHEMA.showTopbarMultiSession,
|
|
||||||
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
topbarCapsuleSlots: [...DEFAULT_TOPBAR_SLOTS],
|
||||||
hoverModules: [...DEFAULT_HOVER_MODULES],
|
hoverModules: [...DEFAULT_HOVER_MODULES],
|
||||||
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
overviewModules: [...DEFAULT_OVERVIEW_MODULES],
|
||||||
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
overviewMetrics: [...DEFAULT_OVERVIEW_METRICS],
|
||||||
showStepTurnRail: DEFAULT_SETTINGS_SCHEMA.showStepTurnRail,
|
|
||||||
showStepAgentBadge: DEFAULT_SETTINGS_SCHEMA.showStepAgentBadge,
|
|
||||||
showStepSpeedColor: DEFAULT_SETTINGS_SCHEMA.showStepSpeedColor,
|
|
||||||
stepTokenComboFormat: DEFAULT_SETTINGS_SCHEMA.stepTokenComboFormat,
|
|
||||||
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
stepTableColumns: [...DEFAULT_STEP_TABLE_COLUMNS],
|
||||||
contextWindowRiskAccepted: DEFAULT_SETTINGS_SCHEMA.contextWindowRiskAccepted,
|
|
||||||
modelContextWindows: {},
|
modelContextWindows: {},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -606,4 +208,3 @@ export function normalizeFullSettings(rawInput) {
|
|||||||
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
modelContextWindows: normalizeModelContextWindows(safeRaw.modelContextWindows),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 零业务依赖的本地 SQLite + WAL 非阻塞只读短连接原语 (`sqlite-client.mjs`)。
|
||||||
|
*
|
||||||
|
* 核心能力:
|
||||||
|
* 1. 惰性加载 Node 22.5+ 内置 `node:sqlite`,自动静默实验特性告警,避免污染 CLI / MCP `stdio`;
|
||||||
|
* 2. 组合主库 `.db` 与 `.db-wal` 的 `mtime + size` 生成复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入;
|
||||||
|
* 3. 采用短连接 + `PRAGMA busy_timeout = 1000` + `SQLITE_BUSY` 瞬时锁重试并在 `finally` 中立即释放句柄,绝不阻塞宿主 WAL checkpoint。
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { existsSync, statSync } from 'node:fs';
|
||||||
|
|
||||||
|
export const SQLITE_IN_CHUNK_SIZE = 400;
|
||||||
|
|
||||||
|
let sqliteResolved = false;
|
||||||
|
let sqliteDatabaseSyncCtor = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 惰性获取 Node 内置 `node:sqlite` 的 `DatabaseSync` 构造器(兼容测试沙箱注入的 `globalThis.DatabaseSync`)。
|
||||||
|
* 首次加载时静默过滤 Node 22 的实验特性告警;当前运行时不支持时返回 `null`。
|
||||||
|
*
|
||||||
|
* @returns {Function | null}
|
||||||
|
*/
|
||||||
|
export function getNodeSqliteDatabaseSync() {
|
||||||
|
if (typeof globalThis.DatabaseSync === 'function') {
|
||||||
|
return globalThis.DatabaseSync;
|
||||||
|
}
|
||||||
|
if (sqliteResolved) return sqliteDatabaseSyncCtor;
|
||||||
|
sqliteResolved = true;
|
||||||
|
if (typeof process === 'undefined' || typeof process.getBuiltinModule !== 'function') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const origEmitWarning = process.emitWarning;
|
||||||
|
try {
|
||||||
|
if (typeof origEmitWarning === 'function') {
|
||||||
|
process.emitWarning = function filteredSqliteWarning(warning, ...rest) {
|
||||||
|
const msg = typeof warning === 'string' ? warning : String(warning?.message || '');
|
||||||
|
if (/SQLite is an experimental feature/i.test(msg)) return;
|
||||||
|
return origEmitWarning.call(this, warning, ...rest);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const mod = process.getBuiltinModule('node:sqlite');
|
||||||
|
sqliteDatabaseSyncCtor = typeof mod?.DatabaseSync === 'function' ? mod.DatabaseSync : null;
|
||||||
|
} catch {
|
||||||
|
sqliteDatabaseSyncCtor = null;
|
||||||
|
} finally {
|
||||||
|
if (typeof origEmitWarning === 'function') {
|
||||||
|
process.emitWarning = origEmitWarning;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sqliteDatabaseSyncCtor;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当前运行时是否具备内置 `node:sqlite` 读取能力。
|
||||||
|
*
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function hasBuiltinNodeSqlite() {
|
||||||
|
return Boolean(getNodeSqliteDatabaseSync());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算 SQLite 主库与 `.db-wal` 预写日志的复合签名(忽略易抖动的 `-shm` 共享内存头),精准感知未 checkpoint 的实时写入。
|
||||||
|
*
|
||||||
|
* @param {string} dbPath
|
||||||
|
* @returns {{ exists: boolean, mtimeMs: number, sig: string }}
|
||||||
|
*/
|
||||||
|
export function computeSqliteWalSig(dbPath) {
|
||||||
|
if (!dbPath || typeof dbPath !== 'string' || !existsSync(dbPath)) {
|
||||||
|
return { exists: false, mtimeMs: 0, sig: '' };
|
||||||
|
}
|
||||||
|
let dbStat = null;
|
||||||
|
try {
|
||||||
|
dbStat = statSync(dbPath);
|
||||||
|
} catch {
|
||||||
|
return { exists: false, mtimeMs: 0, sig: '' };
|
||||||
|
}
|
||||||
|
if (!dbStat) return { exists: false, mtimeMs: 0, sig: '' };
|
||||||
|
|
||||||
|
let walStat = null;
|
||||||
|
const walPath = `${dbPath}-wal`;
|
||||||
|
if (existsSync(walPath)) {
|
||||||
|
try {
|
||||||
|
walStat = statSync(walPath);
|
||||||
|
} catch {
|
||||||
|
walStat = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const dbMtimeMs = Number(dbStat.mtimeMs || 0);
|
||||||
|
const dbSize = Number(dbStat.size || 0);
|
||||||
|
const walMtimeMs = Number(walStat?.mtimeMs || 0);
|
||||||
|
const walSize = Number(walStat?.size || 0);
|
||||||
|
return {
|
||||||
|
exists: true,
|
||||||
|
mtimeMs: Math.max(dbMtimeMs, walMtimeMs),
|
||||||
|
sig: `${Math.floor(dbMtimeMs)}:${dbSize}|${Math.floor(walMtimeMs)}:${walSize}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSqliteBusyError(err) {
|
||||||
|
const msg = String(err?.message || err?.code || '');
|
||||||
|
return /SQLITE_BUSY|database is locked/i.test(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||||
|
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||||
|
*
|
||||||
|
* @template T
|
||||||
|
* @param {string} dbPath
|
||||||
|
* @param {(db: any) => T} queryFn
|
||||||
|
* @returns {T | null}
|
||||||
|
*/
|
||||||
|
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||||
|
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||||
|
if (!DatabaseSync) return null;
|
||||||
|
for (let attempt = 0; attempt < 2; attempt++) {
|
||||||
|
let db = null;
|
||||||
|
try {
|
||||||
|
db = new DatabaseSync(dbPath, { readOnly: true });
|
||||||
|
try {
|
||||||
|
db.exec('PRAGMA busy_timeout = 1000;');
|
||||||
|
} catch {
|
||||||
|
// 兼容最小测试桩
|
||||||
|
}
|
||||||
|
return queryFn(db);
|
||||||
|
} catch (err) {
|
||||||
|
if (attempt === 0 && isSqliteBusyError(err)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
if (db) {
|
||||||
|
try {
|
||||||
|
db.close();
|
||||||
|
} catch {
|
||||||
|
// 忽略关闭异常
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化 SQLite `TEXT` 时间列(如 `'2026-11-18 08:12:00+00:00'` -> ISO-8601),剔除零值哨兵时间。
|
||||||
|
*
|
||||||
|
* @param {unknown} value
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function normalizeSqliteIsoTime(value) {
|
||||||
|
const raw = String(value || '').trim();
|
||||||
|
if (!raw || raw.startsWith('0001-01-01') || raw.startsWith('1970-01-01 00:00:00')) return '';
|
||||||
|
return raw.replace(/^(\d{4}-\d{2}-\d{2})\s+/, '$1T').replace(/\+00:00$/, 'Z');
|
||||||
|
}
|
||||||
@@ -356,8 +356,8 @@ export function createStandaloneWebServer(options = {}) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (options.lsAddr && options.csrfToken) {
|
if (options.lsAddr) {
|
||||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false });
|
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken || '', { isDynamic: false });
|
||||||
}
|
}
|
||||||
|
|
||||||
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
||||||
|
|||||||
@@ -10,24 +10,27 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
|
import { scaleBucketsExact } from '../shared/telemetry-display-rules.mjs';
|
||||||
import {
|
import {
|
||||||
extractLiveActivity,
|
extractLiveActivity,
|
||||||
parseIsoMs,
|
parseIsoMs,
|
||||||
speedMetric,
|
speedMetric,
|
||||||
summarizeSpeed,
|
summarizeSpeed,
|
||||||
summarizeTtft,
|
summarizeTtft,
|
||||||
} from '../speed-metrics.mjs';
|
} from '../trajectory-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
CLI_STATUS_SNAPSHOT_FILE,
|
CLI_STATUS_SNAPSHOT_FILE,
|
||||||
computeRuntimeCodeVersion,
|
computeRuntimeCodeVersion,
|
||||||
|
getCachedTrajectory,
|
||||||
inFlightRequests,
|
inFlightRequests,
|
||||||
|
listCachedTrajectoryEntries,
|
||||||
loadSettings,
|
loadSettings,
|
||||||
lsRuntimeEndpoint,
|
lsRuntimeEndpoint,
|
||||||
roundMetric,
|
roundMetric,
|
||||||
saveJson,
|
saveJson,
|
||||||
trajectoryCache,
|
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
|
import { getContextWindowGroups, getContextWindowModels } from './context-windows.mjs';
|
||||||
|
import { readLocalSummarySnapshot } from './cli-sqlite-reader.mjs';
|
||||||
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
import { enumerateAndSyncConversations } from './local-scanner.mjs';
|
||||||
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
import { ensureLsEndpointDiscovered } from './ls-discovery.mjs';
|
||||||
import { callLsRpc, getContextModelCatalog, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
import { callLsRpc, getContextModelCatalog, getOfficialQuotaSummary } from './ls-rpc.mjs';
|
||||||
@@ -38,8 +41,9 @@ import {
|
|||||||
isArgonModelIdentifier,
|
isArgonModelIdentifier,
|
||||||
isCarbonModelIdentifier,
|
isCarbonModelIdentifier,
|
||||||
} from './model-pricing.mjs';
|
} from './model-pricing.mjs';
|
||||||
import { getCloudStatus, pricingCatalogRevision } from './pricing-catalog.mjs';
|
import { getCloudStatus, getPricingPhaseEpoch, pricingCatalogRevision } from './pricing-catalog.mjs';
|
||||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||||
|
import { getDefaultWindowBridgeStatus } from './window-bridge.mjs';
|
||||||
import {
|
import {
|
||||||
aggregateMultiWindowUsage,
|
aggregateMultiWindowUsage,
|
||||||
buildScopedModelBreakdown,
|
buildScopedModelBreakdown,
|
||||||
@@ -59,9 +63,10 @@ function roundSessionCost(val) {
|
|||||||
|
|
||||||
function findTrajectoryCacheEntry(cascadeId) {
|
function findTrajectoryCacheEntry(cascadeId) {
|
||||||
if (!cascadeId) return null;
|
if (!cascadeId) return null;
|
||||||
if (trajectoryCache[cascadeId]) return trajectoryCache[cascadeId];
|
const entry = getCachedTrajectory(cascadeId);
|
||||||
|
if (entry) return entry;
|
||||||
const targetLower = String(cascadeId).toLowerCase();
|
const targetLower = String(cascadeId).toLowerCase();
|
||||||
for (const [k, v] of Object.entries(trajectoryCache)) {
|
for (const [k, v] of listCachedTrajectoryEntries()) {
|
||||||
if (k.toLowerCase() === targetLower) return v;
|
if (k.toLowerCase() === targetLower) return v;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
@@ -95,13 +100,13 @@ function readTrajectoryModelFacts(steps) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
|
/** 合并各会话的上游模型与上下文上限,步骤数组更新后重新提取对应会话的数据。 */
|
||||||
function buildKnownUpstreamModelMap(contextLimits, currentAccountName) {
|
function buildKnownUpstreamModelMap(contextLimits) {
|
||||||
const knownUpstreamByModelKey = new Map();
|
const knownUpstreamByModelKey = new Map();
|
||||||
for (const entry of Object.values(trajectoryCache)) {
|
for (const [, entry] of listCachedTrajectoryEntries()) {
|
||||||
if (!entry?.steps?.length) continue;
|
if (!entry?.steps?.length) continue;
|
||||||
const facts = readTrajectoryModelFacts(entry.steps);
|
const facts = readTrajectoryModelFacts(entry.steps);
|
||||||
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
for (const [key, model] of facts.upstream) knownUpstreamByModelKey.set(key, model);
|
||||||
if (entry.subagentSpec || (entry.accountName && entry.accountName !== currentAccountName)) continue;
|
if (entry.subagentSpec) continue;
|
||||||
if (facts.limits) {
|
if (facts.limits) {
|
||||||
for (const [key, limit] of facts.limits) {
|
for (const [key, limit] of facts.limits) {
|
||||||
const previous = contextLimits.get(key);
|
const previous = contextLimits.get(key);
|
||||||
@@ -186,6 +191,10 @@ function enrichActiveConversationSteps(
|
|||||||
return {
|
return {
|
||||||
...serializedStep,
|
...serializedStep,
|
||||||
responseModel: st.responseModel || '',
|
responseModel: st.responseModel || '',
|
||||||
|
hasKnownModel: Boolean(mInfo.modelId && mInfo.modelId !== 'unknown'),
|
||||||
|
baseModelUpstream: annotatedUpstreamModel,
|
||||||
|
baseModelLabel: mInfo.label,
|
||||||
|
baseModelShort: mInfo.shortName,
|
||||||
modelUpstream,
|
modelUpstream,
|
||||||
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
modelLabel: st.isCompactionStep ? `${mInfo.label} [自动压缩]` : mInfo.label,
|
||||||
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
|
modelShort: st.isCompactionStep ? `${mInfo.shortName}·压缩` : mInfo.shortName,
|
||||||
@@ -206,6 +215,7 @@ function enrichActiveConversationSteps(
|
|||||||
// 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示
|
// 关联每轮用户提问摘要与最新轮次标识,供步骤表极简导轨与气泡展示
|
||||||
let maxTurnIndex = 0;
|
let maxTurnIndex = 0;
|
||||||
const promptByTurn = new Map();
|
const promptByTurn = new Map();
|
||||||
|
const mediaByTurn = new Map();
|
||||||
for (const st of enrichedActiveSteps) {
|
for (const st of enrichedActiveSteps) {
|
||||||
const tIdx = st.turnIndex;
|
const tIdx = st.turnIndex;
|
||||||
if (!Number.isInteger(tIdx) || tIdx <= 0) continue;
|
if (!Number.isInteger(tIdx) || tIdx <= 0) continue;
|
||||||
@@ -213,6 +223,13 @@ function enrichActiveConversationSteps(
|
|||||||
if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) {
|
if (st.turnPrompt && (st.isTurnStart || !promptByTurn.has(tIdx))) {
|
||||||
promptByTurn.set(tIdx, st.turnPrompt);
|
promptByTurn.set(tIdx, st.turnPrompt);
|
||||||
}
|
}
|
||||||
|
if (st.isTurnStart || !mediaByTurn.has(tIdx)) {
|
||||||
|
mediaByTurn.set(tIdx, {
|
||||||
|
cleanPrompt: st.turnPromptClean ?? '',
|
||||||
|
hasMedia: Boolean(st.turnHasMedia),
|
||||||
|
mediaOnly: Boolean(st.turnMediaOnly),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (const st of enrichedActiveSteps) {
|
for (const st of enrichedActiveSteps) {
|
||||||
const tIdx = st.turnIndex;
|
const tIdx = st.turnIndex;
|
||||||
@@ -221,11 +238,18 @@ function enrichActiveConversationSteps(
|
|||||||
st.isTurnStart = false;
|
st.isTurnStart = false;
|
||||||
st.isLatestTurn = false;
|
st.isLatestTurn = false;
|
||||||
st.turnPrompt = '';
|
st.turnPrompt = '';
|
||||||
|
st.turnPromptClean = '';
|
||||||
|
st.turnHasMedia = false;
|
||||||
|
st.turnMediaOnly = false;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
const turnMedia = mediaByTurn.get(tIdx);
|
||||||
st.isTurnStart = Boolean(st.isTurnStart);
|
st.isTurnStart = Boolean(st.isTurnStart);
|
||||||
st.isLatestTurn = tIdx === maxTurnIndex;
|
st.isLatestTurn = tIdx === maxTurnIndex;
|
||||||
st.turnPrompt = promptByTurn.get(tIdx) || '';
|
st.turnPrompt = promptByTurn.get(tIdx) || '';
|
||||||
|
st.turnPromptClean = turnMedia?.cleanPrompt || '';
|
||||||
|
st.turnHasMedia = Boolean(turnMedia?.hasMedia);
|
||||||
|
st.turnMediaOnly = Boolean(turnMedia?.mediaOnly);
|
||||||
}
|
}
|
||||||
|
|
||||||
const latestEnriched =
|
const latestEnriched =
|
||||||
@@ -265,49 +289,41 @@ function resolveStepOutputTokens(st) {
|
|||||||
return Number(st?.thinkingTokens || 0) + Number(st?.responseTokens || 0);
|
return Number(st?.thinkingTokens || 0) + Number(st?.responseTokens || 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function extractRawBreakdownChannels(breakdown) {
|
||||||
* 使用最大余数法(Hamilton 方法)将各非零上下文分桶等比缩放至目标整数总和,
|
const rawMessages = Number(breakdown?.messagesTokens || 0);
|
||||||
* 保证 0 值通道绝不被凭空分配 Token,且缩放后各分桶之和精确等于 `targetTotal`。
|
const hasGranularMsgBreakdown =
|
||||||
*/
|
Boolean(breakdown) &&
|
||||||
function scaleBucketsExact(buckets, keys, targetTotal) {
|
Object.prototype.hasOwnProperty.call(breakdown, 'toolResultsTokens');
|
||||||
const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0)));
|
const channels = {
|
||||||
const out = {};
|
userInput: hasGranularMsgBreakdown
|
||||||
let currentSum = 0;
|
? Number(breakdown?.userInputTokens || 0)
|
||||||
for (const k of keys) {
|
: rawMessages,
|
||||||
const val = Math.max(0, Number(buckets[k] || 0));
|
assistant: Number(breakdown?.assistantTokens || 0),
|
||||||
out[k] = val;
|
toolResults: Number(breakdown?.toolResultsTokens || 0),
|
||||||
currentSum += val;
|
subagent: Number(breakdown?.subagentTokens || 0),
|
||||||
|
checkpoint: Number(breakdown?.checkpointTokens || 0),
|
||||||
|
systemTools: Number(breakdown?.systemToolsTokens || 0),
|
||||||
|
mcpTools: Number(breakdown?.mcpToolsTokens || 0),
|
||||||
|
skills: Number(breakdown?.skillsTokens || 0),
|
||||||
|
systemPrompt: Number(breakdown?.systemPromptTokens || 0),
|
||||||
|
userRules: Number(breakdown?.userRulesTokens || 0),
|
||||||
|
};
|
||||||
|
const msgSubtotal =
|
||||||
|
channels.userInput +
|
||||||
|
channels.assistant +
|
||||||
|
channels.toolResults +
|
||||||
|
channels.subagent +
|
||||||
|
channels.checkpoint;
|
||||||
|
if (rawMessages > msgSubtotal) {
|
||||||
|
channels.userInput += rawMessages - msgSubtotal;
|
||||||
}
|
}
|
||||||
if (safeTarget === 0 || currentSum <= 0) {
|
return channels;
|
||||||
for (const k of keys) out[k] = 0;
|
}
|
||||||
return out;
|
|
||||||
}
|
function resolveCompactionSummaryTokens(compactionStep) {
|
||||||
if (currentSum === safeTarget) {
|
const respTok = Number(compactionStep?.responseTokens || 0);
|
||||||
for (const k of keys) out[k] = Math.round(out[k]);
|
if (respTok > 0) return respTok;
|
||||||
return out;
|
return resolveStepOutputTokens(compactionStep);
|
||||||
}
|
|
||||||
const remainders = [];
|
|
||||||
let assigned = 0;
|
|
||||||
for (const k of keys) {
|
|
||||||
const rawVal = out[k];
|
|
||||||
if (rawVal <= 0) {
|
|
||||||
out[k] = 0;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const exact = (rawVal * safeTarget) / currentSum;
|
|
||||||
const floored = Math.floor(exact);
|
|
||||||
out[k] = floored;
|
|
||||||
assigned += floored;
|
|
||||||
remainders.push({ key: k, rem: exact - floored, orig: rawVal });
|
|
||||||
}
|
|
||||||
let diff = safeTarget - assigned;
|
|
||||||
if (diff > 0 && remainders.length > 0) {
|
|
||||||
remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig);
|
|
||||||
for (let i = 0; i < diff; i++) {
|
|
||||||
out[remainders[i % remainders.length].key] += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -316,7 +332,10 @@ function scaleBucketsExact(buckets, keys, targetTotal) {
|
|||||||
* `chatStartMetadata.contextWindowMetadata` 记录在步骤请求发送前且基于宿主离线估算器:
|
* `chatStartMetadata.contextWindowMetadata` 记录在步骤请求发送前且基于宿主离线估算器:
|
||||||
* 1. 先按该步模型 API 真实计费输入(`inputTokens + cacheReadTokens`)对请求前 10 通道做等比整数对齐,消除离线估算偏差;
|
* 1. 先按该步模型 API 真实计费输入(`inputTokens + cacheReadTokens`)对请求前 10 通道做等比整数对齐,消除离线估算偏差;
|
||||||
* 2. 再将该步自身新生成的输出(`outputTokens`)补入 `assistantTokens`,并滚动推进后续无独立拆解的步骤,
|
* 2. 再将该步自身新生成的输出(`outputTokens`)补入 `assistantTokens`,并滚动推进后续无独立拆解的步骤,
|
||||||
* 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致。
|
* 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致;
|
||||||
|
* 3. 当末尾或最近边界为上下文压缩步骤(`isCompactionStep`)且压缩后尚未产生新的 `contextBreakdown` 时,
|
||||||
|
* 继承压缩前最近一次拆解中的 5 个会话静态通道(`systemPrompt` / `systemTools` / `mcpTools` / `skills` / `userRules`),
|
||||||
|
* 清空已被折叠的历史对话通道,并将压缩步生成的摘要正文计入 `checkpointTokens`,避免误把压缩前全量输入当作压缩后水位。
|
||||||
*
|
*
|
||||||
* @param {object[]} enrichedActiveSteps
|
* @param {object[]} enrichedActiveSteps
|
||||||
* @param {object|null} latestEnriched
|
* @param {object|null} latestEnriched
|
||||||
@@ -329,85 +348,113 @@ function extractActiveContextTelemetry(
|
|||||||
sessionInputTokens,
|
sessionInputTokens,
|
||||||
sessionCacheReadTokens
|
sessionCacheReadTokens
|
||||||
) {
|
) {
|
||||||
let latestBreakdown = latestEnriched?.contextBreakdown || null;
|
let lastCompactionIdx = -1;
|
||||||
let breakdownIdx = latestBreakdown ? enrichedActiveSteps.length - 1 : -1;
|
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
||||||
if (!latestBreakdown && !latestEnriched?.isCompactionStep) {
|
if (enrichedActiveSteps[i]?.isCompactionStep) {
|
||||||
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
lastCompactionIdx = i;
|
||||||
if (enrichedActiveSteps[i]?.isCompactionStep) {
|
break;
|
||||||
break;
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let latestBreakdown = null;
|
||||||
|
let breakdownIdx = -1;
|
||||||
|
for (let i = enrichedActiveSteps.length - 1; i > lastCompactionIdx; i--) {
|
||||||
|
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
||||||
|
latestBreakdown = enrichedActiveSteps[i].contextBreakdown;
|
||||||
|
breakdownIdx = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let channels = extractRawBreakdownChannels(latestBreakdown);
|
||||||
|
let fallbackPreCompactionLimit = 0;
|
||||||
|
|
||||||
|
if (latestBreakdown && breakdownIdx > lastCompactionIdx) {
|
||||||
|
const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
|
||||||
|
if (rawBreakdownTotal > 0) {
|
||||||
|
const bdStep = enrichedActiveSteps[breakdownIdx];
|
||||||
|
const bdPromptTokens =
|
||||||
|
Number(bdStep?.inputTokens || 0) + Number(bdStep?.cacheReadTokens || 0);
|
||||||
|
const bdOutTokens = resolveStepOutputTokens(bdStep);
|
||||||
|
// 仅当模型 API 返回了完整的请求级输入(排除省略 cacheReadTokens 的残缺网关或极小合成桩数据)时对齐至真实分词口径
|
||||||
|
if (bdPromptTokens >= rawBreakdownTotal * 0.5) {
|
||||||
|
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, bdPromptTokens);
|
||||||
|
channels.assistant += bdOutTokens;
|
||||||
|
let runningTotal = bdPromptTokens + bdOutTokens;
|
||||||
|
|
||||||
|
for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) {
|
||||||
|
const stepM = enrichedActiveSteps[m];
|
||||||
|
if (!stepM || stepM.isCompactionStep) break;
|
||||||
|
const mPrompt =
|
||||||
|
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
|
||||||
|
const mOut = resolveStepOutputTokens(stepM);
|
||||||
|
if (mPrompt >= runningTotal * 0.5) {
|
||||||
|
if (mPrompt > runningTotal) {
|
||||||
|
const delta = mPrompt - runningTotal;
|
||||||
|
if (enrichedActiveSteps[m - 1]?.hasToolCalls) {
|
||||||
|
channels.toolResults += delta;
|
||||||
|
} else {
|
||||||
|
channels.userInput += delta;
|
||||||
|
}
|
||||||
|
} else if (mPrompt < runningTotal) {
|
||||||
|
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt);
|
||||||
|
}
|
||||||
|
channels.assistant += mOut;
|
||||||
|
runningTotal = mPrompt + mOut;
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
} else if (lastCompactionIdx >= 0) {
|
||||||
|
const compactionStep = enrichedActiveSteps[lastCompactionIdx];
|
||||||
|
let preStep = null;
|
||||||
|
for (let i = lastCompactionIdx - 1; i >= 0; i--) {
|
||||||
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
||||||
latestBreakdown = enrichedActiveSteps[i].contextBreakdown;
|
preStep = enrichedActiveSteps[i];
|
||||||
breakdownIdx = i;
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
if (preStep) {
|
||||||
const rawMessages = Number(latestBreakdown?.messagesTokens || 0);
|
fallbackPreCompactionLimit = Number(preStep.maxContextBudgetTokens || 0);
|
||||||
const hasGranularMsgBreakdown =
|
let preChannels = extractRawBreakdownChannels(preStep.contextBreakdown);
|
||||||
Boolean(latestBreakdown) &&
|
const preRawTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + preChannels[k], 0);
|
||||||
Object.prototype.hasOwnProperty.call(latestBreakdown, 'toolResultsTokens');
|
const prePromptTokens =
|
||||||
let channels = {
|
Number(preStep.inputTokens || 0) + Number(preStep.cacheReadTokens || 0);
|
||||||
userInput: hasGranularMsgBreakdown
|
if (preRawTotal > 0 && prePromptTokens >= preRawTotal * 0.5) {
|
||||||
? Number(latestBreakdown?.userInputTokens || 0)
|
preChannels = scaleBucketsExact(preChannels, CONTEXT_CHANNEL_KEYS, prePromptTokens);
|
||||||
: rawMessages,
|
}
|
||||||
assistant: Number(latestBreakdown?.assistantTokens || 0),
|
channels.systemTools = preChannels.systemTools;
|
||||||
toolResults: Number(latestBreakdown?.toolResultsTokens || 0),
|
channels.mcpTools = preChannels.mcpTools;
|
||||||
subagent: Number(latestBreakdown?.subagentTokens || 0),
|
channels.skills = preChannels.skills;
|
||||||
checkpoint: Number(latestBreakdown?.checkpointTokens || 0),
|
channels.systemPrompt = preChannels.systemPrompt;
|
||||||
systemTools: Number(latestBreakdown?.systemToolsTokens || 0),
|
channels.userRules = preChannels.userRules;
|
||||||
mcpTools: Number(latestBreakdown?.mcpToolsTokens || 0),
|
}
|
||||||
skills: Number(latestBreakdown?.skillsTokens || 0),
|
channels.userInput = 0;
|
||||||
systemPrompt: Number(latestBreakdown?.systemPromptTokens || 0),
|
channels.assistant = 0;
|
||||||
userRules: Number(latestBreakdown?.userRulesTokens || 0),
|
channels.toolResults = 0;
|
||||||
};
|
channels.subagent = 0;
|
||||||
const msgSubtotal =
|
channels.checkpoint = resolveCompactionSummaryTokens(compactionStep);
|
||||||
channels.userInput +
|
|
||||||
channels.assistant +
|
|
||||||
channels.toolResults +
|
|
||||||
channels.subagent +
|
|
||||||
channels.checkpoint;
|
|
||||||
if (rawMessages > msgSubtotal) {
|
|
||||||
channels.userInput += rawMessages - msgSubtotal;
|
|
||||||
}
|
|
||||||
const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
|
|
||||||
|
|
||||||
if (
|
let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
|
||||||
latestBreakdown &&
|
for (let m = lastCompactionIdx + 1; m < enrichedActiveSteps.length; m++) {
|
||||||
breakdownIdx >= 0 &&
|
const stepM = enrichedActiveSteps[m];
|
||||||
!latestEnriched?.isCompactionStep &&
|
if (!stepM || stepM.isCompactionStep) continue;
|
||||||
rawBreakdownTotal > 0
|
const mPrompt =
|
||||||
) {
|
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
|
||||||
const bdStep = enrichedActiveSteps[breakdownIdx];
|
const mOut = resolveStepOutputTokens(stepM);
|
||||||
const bdPromptTokens =
|
if (mPrompt > 0 && (runningTotal === 0 || mPrompt >= runningTotal * 0.35)) {
|
||||||
Number(bdStep?.inputTokens || 0) + Number(bdStep?.cacheReadTokens || 0);
|
if (mPrompt > runningTotal) {
|
||||||
const bdOutTokens = resolveStepOutputTokens(bdStep);
|
const delta = mPrompt - runningTotal;
|
||||||
// 仅当模型 API 返回了完整的请求级输入(排除省略 cacheReadTokens 的残缺网关或极小合成桩数据)时对齐至真实分词口径
|
if (m > lastCompactionIdx + 1 && enrichedActiveSteps[m - 1]?.hasToolCalls) {
|
||||||
if (bdPromptTokens >= rawBreakdownTotal * 0.5) {
|
channels.toolResults += delta;
|
||||||
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, bdPromptTokens);
|
} else {
|
||||||
channels.assistant += bdOutTokens;
|
channels.userInput += delta;
|
||||||
let runningTotal = bdPromptTokens + bdOutTokens;
|
|
||||||
|
|
||||||
for (let m = breakdownIdx + 1; m < enrichedActiveSteps.length; m++) {
|
|
||||||
const stepM = enrichedActiveSteps[m];
|
|
||||||
if (!stepM || stepM.isCompactionStep) break;
|
|
||||||
const mPrompt =
|
|
||||||
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
|
|
||||||
const mOut = resolveStepOutputTokens(stepM);
|
|
||||||
if (mPrompt >= runningTotal * 0.5) {
|
|
||||||
if (mPrompt > runningTotal) {
|
|
||||||
const delta = mPrompt - runningTotal;
|
|
||||||
if (enrichedActiveSteps[m - 1]?.hasToolCalls) {
|
|
||||||
channels.toolResults += delta;
|
|
||||||
} else {
|
|
||||||
channels.userInput += delta;
|
|
||||||
}
|
|
||||||
} else if (mPrompt < runningTotal) {
|
|
||||||
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt);
|
|
||||||
}
|
}
|
||||||
channels.assistant += mOut;
|
} else if (mPrompt < runningTotal) {
|
||||||
runningTotal = mPrompt + mOut;
|
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt);
|
||||||
}
|
}
|
||||||
|
channels.assistant += mOut;
|
||||||
|
runningTotal = mPrompt + mOut;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -427,17 +474,25 @@ function extractActiveContextTelemetry(
|
|||||||
const ctxBreakdownTotal =
|
const ctxBreakdownTotal =
|
||||||
ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules;
|
ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules;
|
||||||
|
|
||||||
|
const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep);
|
||||||
const ctxCached = latestEnriched?.cacheReadTokens || 0;
|
const ctxCached = latestEnriched?.cacheReadTokens || 0;
|
||||||
const ctxFreshInput = latestEnriched?.inputTokens || 0;
|
const ctxFreshInput = latestEnriched?.inputTokens || 0;
|
||||||
const ctxThinking = latestEnriched?.thinkingTokens || 0;
|
const ctxThinking = latestEnriched?.thinkingTokens || 0;
|
||||||
const ctxResponse = latestEnriched?.responseTokens || 0;
|
const ctxResponse = latestEnriched?.responseTokens || 0;
|
||||||
const ctxOut = resolveStepOutputTokens(latestEnriched);
|
const ctxOut = resolveStepOutputTokens(latestEnriched);
|
||||||
const ctxTotal =
|
const ctxTotal = isLatestCompaction
|
||||||
ctxBreakdownTotal > 0 ? ctxBreakdownTotal : ctxCached + ctxFreshInput + ctxOut;
|
? ctxBreakdownTotal
|
||||||
const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000);
|
: ctxBreakdownTotal > 0
|
||||||
const compactionUsedTokens = Number(
|
? ctxBreakdownTotal
|
||||||
ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput
|
: ctxCached + ctxFreshInput + ctxOut;
|
||||||
|
const compactionLimitTokens = Number(
|
||||||
|
(isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
|
||||||
|
? fallbackPreCompactionLimit
|
||||||
|
: latestEnriched?.maxContextBudgetTokens) || 256000
|
||||||
);
|
);
|
||||||
|
const compactionUsedTokens = isLatestCompaction
|
||||||
|
? Number(ctxTotal)
|
||||||
|
: Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput);
|
||||||
const compactionUsedPct =
|
const compactionUsedPct =
|
||||||
compactionLimitTokens > 0
|
compactionLimitTokens > 0
|
||||||
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
|
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
|
||||||
@@ -509,10 +564,15 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
|
|||||||
/**
|
/**
|
||||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象。
|
* 构建单个代理(主代理或子代理)的标准遥测单元对象。
|
||||||
*/
|
*/
|
||||||
function buildAgentUnitTelemetry({
|
export function buildAgentUnitTelemetry({
|
||||||
agentId,
|
agentId,
|
||||||
cascadeId,
|
cascadeId,
|
||||||
isMain,
|
isMain,
|
||||||
|
isSideQuestion = false,
|
||||||
|
sideIndex = 0,
|
||||||
|
agentKind = isMain ? 'main' : isSideQuestion ? 'side_question' : 'subagent',
|
||||||
|
agentOrdinal = isMain ? 0 : isSideQuestion ? sideIndex : 0,
|
||||||
|
customRole = '',
|
||||||
index,
|
index,
|
||||||
shortLabel,
|
shortLabel,
|
||||||
badgeText,
|
badgeText,
|
||||||
@@ -535,11 +595,15 @@ function buildAgentUnitTelemetry({
|
|||||||
{
|
{
|
||||||
agentId,
|
agentId,
|
||||||
agentCascadeId: cascadeId,
|
agentCascadeId: cascadeId,
|
||||||
|
agentKind,
|
||||||
|
agentOrdinal,
|
||||||
|
agentCustomRole: customRole,
|
||||||
agentLabel,
|
agentLabel,
|
||||||
agentBadge: badgeText,
|
agentBadge: badgeText,
|
||||||
agentRole: role,
|
agentRole: role,
|
||||||
agentIndex: index,
|
agentIndex: index,
|
||||||
isSubagent: !isMain,
|
isSubagent: !isMain,
|
||||||
|
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
|
||||||
},
|
},
|
||||||
reuseInputs
|
reuseInputs
|
||||||
);
|
);
|
||||||
@@ -561,6 +625,10 @@ function buildAgentUnitTelemetry({
|
|||||||
agentId,
|
agentId,
|
||||||
cascadeId,
|
cascadeId,
|
||||||
isMain,
|
isMain,
|
||||||
|
agentKind,
|
||||||
|
agentOrdinal,
|
||||||
|
customRole,
|
||||||
|
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
|
||||||
index,
|
index,
|
||||||
shortLabel,
|
shortLabel,
|
||||||
badgeText,
|
badgeText,
|
||||||
@@ -592,6 +660,9 @@ function buildAgentUnitTelemetry({
|
|||||||
: 0,
|
: 0,
|
||||||
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
||||||
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
||||||
|
hasKnownModel: Boolean(enrichedRes.latestEnriched?.hasKnownModel),
|
||||||
|
activeBaseModelShort: enrichedRes.latestEnriched?.baseModelShort || '',
|
||||||
|
activeBaseModelLabel: enrichedRes.latestEnriched?.baseModelLabel || '',
|
||||||
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
||||||
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
||||||
activeModelUpstream:
|
activeModelUpstream:
|
||||||
@@ -607,14 +678,20 @@ function buildAgentUnitTelemetry({
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) {
|
async function readTelemetrySources(requestedConvId, forceQuotaRefresh, currentAccountName, accountScope, userStatus) {
|
||||||
|
const localSummaries = readLocalSummarySnapshot(undefined, { forceRefresh: forceQuotaRefresh });
|
||||||
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
const [allTrajRes, officialQuotaInfo, contextModelCatalog] = await Promise.all([
|
||||||
callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
localSummaries.available
|
||||||
|
? Promise.resolve(null)
|
||||||
|
: callLsRpc('GetAllCascadeTrajectories', {}).catch(() => ({})),
|
||||||
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
userStatus ? getOfficialQuotaSummary(forceQuotaRefresh, currentAccountName) : null,
|
||||||
getContextModelCatalog(),
|
getContextModelCatalog(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const sessions = await enumerateAndSyncConversations({
|
const sessions = await enumerateAndSyncConversations({
|
||||||
summariesObj: allTrajRes?.trajectorySummaries || {},
|
summariesObj: localSummaries.available
|
||||||
|
? localSummaries.summariesObj
|
||||||
|
: allTrajRes?.trajectorySummaries || {},
|
||||||
|
sideQuestionParents: localSummaries.available ? localSummaries.sideQuestionParents : {},
|
||||||
currentAccountName: accountScope,
|
currentAccountName: accountScope,
|
||||||
requestedConvId,
|
requestedConvId,
|
||||||
forceRefresh: forceQuotaRefresh,
|
forceRefresh: forceQuotaRefresh,
|
||||||
@@ -696,12 +773,16 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
|
|
||||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
// 3. 计算当前活跃根会话及其子代理的步骤指标、10 通道上下文拆解与按模型汇总
|
||||||
const reportedContextLimits = new Map();
|
const reportedContextLimits = new Map();
|
||||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits, currentAccountName);
|
const knownUpstreamByModelKey = buildKnownUpstreamModelMap(reportedContextLimits);
|
||||||
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
const activeEntry = findTrajectoryCacheEntry(activeCascadeId);
|
||||||
const activeSteps = activeEntry?.steps || [];
|
const activeSteps = activeEntry?.steps || [];
|
||||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||||
if (subagentSummaries.length) lastMainPreparation = null;
|
if (subagentSummaries.length) lastMainPreparation = null;
|
||||||
const modelInputs = { catalogRevision: pricingCatalogRevision, dynamicModelMap };
|
const modelInputs = {
|
||||||
|
catalogRevision: pricingCatalogRevision,
|
||||||
|
phaseEpoch: getPricingPhaseEpoch(),
|
||||||
|
dynamicModelMap,
|
||||||
|
};
|
||||||
const mainUnit = buildAgentUnitTelemetry({
|
const mainUnit = buildAgentUnitTelemetry({
|
||||||
agentId: 'main',
|
agentId: 'main',
|
||||||
cascadeId: activeCascadeId,
|
cascadeId: activeCascadeId,
|
||||||
@@ -747,6 +828,8 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||||
let totalFamilyOutputTokens = sessionOutputTokens;
|
let totalFamilyOutputTokens = sessionOutputTokens;
|
||||||
|
|
||||||
|
let normalSubCount = 0;
|
||||||
|
let sideQuestionCount = 0;
|
||||||
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
||||||
const subSum = subagentSummaries[idx];
|
const subSum = subagentSummaries[idx];
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
@@ -756,24 +839,65 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
for (const step of subRawSteps) allCombinedRawSteps.push(step);
|
||||||
|
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||||
|
const isSideQ = Boolean(
|
||||||
|
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
||||||
|
);
|
||||||
const rawRole =
|
const rawRole =
|
||||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||||
const subIndex = idx + 1;
|
const subIndex = idx + 1;
|
||||||
const shortLabel = `子代理 #${subIndex}`;
|
let sideIndex = 0;
|
||||||
const badgeText = `子${subIndex}`;
|
let agentKind = 'subagent';
|
||||||
const roleLabel = rawRole || '子代理';
|
let agentOrdinal = 0;
|
||||||
const typeName = subSpec?.typeName || '';
|
let customRole = '';
|
||||||
|
let shortLabel = '';
|
||||||
|
let badgeText = '';
|
||||||
|
let roleLabel = '';
|
||||||
|
let typeName = '';
|
||||||
|
let agentLabel = '';
|
||||||
|
if (isSideQ) {
|
||||||
|
sideIndex = ++sideQuestionCount;
|
||||||
|
agentKind = 'side_question';
|
||||||
|
agentOrdinal = sideIndex;
|
||||||
|
shortLabel = `旁路提问 #${sideIndex}`;
|
||||||
|
badgeText = `旁${sideIndex}`;
|
||||||
|
const cleanSideRole =
|
||||||
|
rawRole &&
|
||||||
|
rawRole !== '旁路提问' &&
|
||||||
|
rawRole !== 'Side Question' &&
|
||||||
|
rawRole !== 'side_question'
|
||||||
|
? rawRole
|
||||||
|
: '';
|
||||||
|
customRole = cleanSideRole;
|
||||||
|
roleLabel = cleanSideRole || '旁路提问';
|
||||||
|
typeName = 'side_question';
|
||||||
|
agentLabel = cleanSideRole ? `${shortLabel} · ${cleanSideRole}` : shortLabel;
|
||||||
|
} else {
|
||||||
|
const subOrd = ++normalSubCount;
|
||||||
|
agentKind = 'subagent';
|
||||||
|
agentOrdinal = subOrd;
|
||||||
|
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||||
|
shortLabel = `子代理 #${subOrd}`;
|
||||||
|
badgeText = `子${subOrd}`;
|
||||||
|
roleLabel = rawRole || '子代理';
|
||||||
|
typeName = subSpec?.typeName || '';
|
||||||
|
agentLabel = rawRole ? `${shortLabel} · ${rawRole}` : shortLabel;
|
||||||
|
}
|
||||||
|
|
||||||
const subUnit = buildAgentUnitTelemetry({
|
const subUnit = buildAgentUnitTelemetry({
|
||||||
agentId: subCid,
|
agentId: subCid,
|
||||||
cascadeId: subCid,
|
cascadeId: subCid,
|
||||||
isMain: false,
|
isMain: false,
|
||||||
|
isSideQuestion: isSideQ,
|
||||||
|
sideIndex,
|
||||||
|
agentKind,
|
||||||
|
agentOrdinal,
|
||||||
|
customRole,
|
||||||
index: subIndex,
|
index: subIndex,
|
||||||
shortLabel,
|
shortLabel,
|
||||||
badgeText,
|
badgeText,
|
||||||
role: roleLabel,
|
role: roleLabel,
|
||||||
typeName,
|
typeName,
|
||||||
agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel,
|
agentLabel,
|
||||||
status: subSum.status || 'IDLE',
|
status: subSum.status || 'IDLE',
|
||||||
rawSteps: subRawSteps,
|
rawSteps: subRawSteps,
|
||||||
liveActivity: subSum.liveActivity || null,
|
liveActivity: subSum.liveActivity || null,
|
||||||
@@ -817,6 +941,9 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
turnIndex: tIdx,
|
turnIndex: tIdx,
|
||||||
startMs: mSt.createdAtMs || 0,
|
startMs: mSt.createdAtMs || 0,
|
||||||
prompt: mSt.turnPrompt || '',
|
prompt: mSt.turnPrompt || '',
|
||||||
|
cleanPrompt: mSt.turnPromptClean ?? '',
|
||||||
|
hasMedia: Boolean(mSt.turnHasMedia),
|
||||||
|
mediaOnly: Boolean(mSt.turnMediaOnly),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -843,6 +970,9 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
st.rootTurnIndex = matched.turnIndex;
|
st.rootTurnIndex = matched.turnIndex;
|
||||||
st.isRootLatestTurn = matched.turnIndex === maxRootTurn;
|
st.isRootLatestTurn = matched.turnIndex === maxRootTurn;
|
||||||
st.rootTurnPrompt = matched.prompt || '';
|
st.rootTurnPrompt = matched.prompt || '';
|
||||||
|
st.rootTurnPromptClean = matched.cleanPrompt ?? '';
|
||||||
|
st.rootTurnHasMedia = Boolean(matched.hasMedia);
|
||||||
|
st.rootTurnMediaOnly = Boolean(matched.mediaOnly);
|
||||||
if (!seenRootStarts.has(matched.turnIndex)) {
|
if (!seenRootStarts.has(matched.turnIndex)) {
|
||||||
seenRootStarts.add(matched.turnIndex);
|
seenRootStarts.add(matched.turnIndex);
|
||||||
st.isRootTurnStart = true;
|
st.isRootTurnStart = true;
|
||||||
@@ -878,6 +1008,31 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||||
latestActiveAgent;
|
latestActiveAgent;
|
||||||
|
|
||||||
|
// 汇总视图与自动跟随上下文始终锁定主线(主代理与常规子代理),防止旁路提问抽屉篡改主会话 10 通道上下文水位
|
||||||
|
const mainlineAgents = allAgents.filter((a) => !a.isSideQuestion);
|
||||||
|
const activeMainlineAgent = !latestActiveAgent.isSideQuestion
|
||||||
|
? latestActiveAgent
|
||||||
|
: mainlineAgents.find((a) => a.isRunning) ||
|
||||||
|
mainlineAgents
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||||
|
mainAgentTelemetry;
|
||||||
|
const mainlineWithSteps = mainlineAgents.filter((a) => a.stepCount > 0);
|
||||||
|
const contextMetricAgent = !latestMetricAgent.isSideQuestion
|
||||||
|
? latestMetricAgent
|
||||||
|
: mainlineWithSteps.find((a) => a.isRunning) ||
|
||||||
|
mainlineWithSteps
|
||||||
|
.slice()
|
||||||
|
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||||
|
mainAgentTelemetry;
|
||||||
|
|
||||||
|
const aggregatedRoleLabel =
|
||||||
|
normalSubCount > 0 && sideQuestionCount > 0
|
||||||
|
? `主代理 + ${normalSubCount} 子代理 + ${sideQuestionCount} 旁问`
|
||||||
|
: sideQuestionCount > 0
|
||||||
|
? `主代理 + ${sideQuestionCount} 旁路提问`
|
||||||
|
: `主代理 + ${subAgentTelemetries.length} 子代理`;
|
||||||
|
|
||||||
const totalCostUsd = roundSessionCost(totalRawSessionCostUsd);
|
const totalCostUsd = roundSessionCost(totalRawSessionCostUsd);
|
||||||
const totalUnpricedCalls = allAgents.reduce(
|
const totalUnpricedCalls = allAgents.reduce(
|
||||||
(sum, a) => sum + (a.sessionUnpricedCalls || 0),
|
(sum, a) => sum + (a.sessionUnpricedCalls || 0),
|
||||||
@@ -899,11 +1054,16 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
? {
|
? {
|
||||||
...activeActivityAgent.liveActivity,
|
...activeActivityAgent.liveActivity,
|
||||||
agentId: activeActivityAgent.agentId,
|
agentId: activeActivityAgent.agentId,
|
||||||
|
agentKind: activeActivityAgent.agentKind || (activeActivityAgent.isMain ? 'main' : activeActivityAgent.isSideQuestion ? 'side_question' : 'subagent'),
|
||||||
|
agentOrdinal: activeActivityAgent.agentOrdinal || 0,
|
||||||
agentBadge: activeActivityAgent.badgeText,
|
agentBadge: activeActivityAgent.badgeText,
|
||||||
agentShortLabel: activeActivityAgent.shortLabel,
|
agentShortLabel: activeActivityAgent.shortLabel,
|
||||||
agentRole: activeActivityAgent.role,
|
agentRole: activeActivityAgent.role,
|
||||||
agentIndex: activeActivityAgent.index,
|
agentIndex: activeActivityAgent.index,
|
||||||
isMain: Boolean(activeActivityAgent.isMain),
|
isMain: Boolean(activeActivityAgent.isMain),
|
||||||
|
...(activeActivityAgent.isSideQuestion
|
||||||
|
? { isSideQuestion: true, sideIndex: activeActivityAgent.sideIndex || 0 }
|
||||||
|
: {}),
|
||||||
parallelCount: runningSubs.length > 1 ? runningSubs.length : 1,
|
parallelCount: runningSubs.length > 1 ? runningSubs.length : 1,
|
||||||
}
|
}
|
||||||
: null;
|
: null;
|
||||||
@@ -912,15 +1072,19 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
agentId: 'all',
|
agentId: 'all',
|
||||||
cascadeId: activeCascadeId,
|
cascadeId: activeCascadeId,
|
||||||
isMain: false,
|
isMain: false,
|
||||||
|
agentKind: 'all',
|
||||||
|
agentOrdinal: 0,
|
||||||
index: -1,
|
index: -1,
|
||||||
shortLabel: '全部汇总',
|
shortLabel: '全部汇总',
|
||||||
badgeText: '全部',
|
badgeText: '全部',
|
||||||
role: `主代理 + ${subAgentTelemetries.length} 子代理`,
|
role: aggregatedRoleLabel,
|
||||||
typeName: 'all',
|
typeName: 'all',
|
||||||
activeAgentId: latestActiveAgent.agentId,
|
activeAgentId: activeMainlineAgent.agentId,
|
||||||
activeAgentShortLabel: latestActiveAgent.shortLabel,
|
activeAgentKind: activeMainlineAgent.agentKind || (activeMainlineAgent.isMain ? 'main' : activeMainlineAgent.isSideQuestion ? 'side_question' : 'subagent'),
|
||||||
activeAgentBadge: latestActiveAgent.badgeText,
|
activeAgentOrdinal: activeMainlineAgent.agentOrdinal || 0,
|
||||||
activeAgentRole: latestActiveAgent.role,
|
activeAgentShortLabel: activeMainlineAgent.shortLabel,
|
||||||
|
activeAgentBadge: activeMainlineAgent.badgeText,
|
||||||
|
activeAgentRole: activeMainlineAgent.role,
|
||||||
isRunning: allAgents.some((a) => a.isRunning),
|
isRunning: allAgents.some((a) => a.isRunning),
|
||||||
status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE',
|
status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE',
|
||||||
liveActivity: aggregatedLiveActivity,
|
liveActivity: aggregatedLiveActivity,
|
||||||
@@ -941,10 +1105,13 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0,
|
latestPromptTokens: latestMetricAgent.latestPromptTokens ?? 0,
|
||||||
latestCacheHitPct: latestMetricAgent.latestCacheHitPct,
|
latestCacheHitPct: latestMetricAgent.latestCacheHitPct,
|
||||||
sessionCacheHitPct: combinedSessionCacheHitPct,
|
sessionCacheHitPct: combinedSessionCacheHitPct,
|
||||||
|
hasKnownModel: Boolean(latestMetricAgent.hasKnownModel),
|
||||||
|
activeBaseModelShort: latestMetricAgent.activeBaseModelShort || '',
|
||||||
|
activeBaseModelLabel: latestMetricAgent.activeBaseModelLabel || '',
|
||||||
activeModelShort: latestMetricAgent.activeModelShort,
|
activeModelShort: latestMetricAgent.activeModelShort,
|
||||||
activeModelLabel: latestMetricAgent.activeModelLabel,
|
activeModelLabel: latestMetricAgent.activeModelLabel,
|
||||||
activeModelUpstream: latestMetricAgent.activeModelUpstream,
|
activeModelUpstream: latestMetricAgent.activeModelUpstream,
|
||||||
context: latestMetricAgent.context,
|
context: contextMetricAgent.context,
|
||||||
modelBreakdown: combinedModelBreakdown,
|
modelBreakdown: combinedModelBreakdown,
|
||||||
lastModifiedMs: latestActiveAgent.lastModifiedMs,
|
lastModifiedMs: latestActiveAgent.lastModifiedMs,
|
||||||
};
|
};
|
||||||
@@ -1036,6 +1203,7 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
currentYear,
|
currentYear,
|
||||||
monthlySeries,
|
monthlySeries,
|
||||||
weekBucket,
|
weekBucket,
|
||||||
|
quotaWeekBucket,
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
poolCycleStats,
|
poolCycleStats,
|
||||||
poolsWeeklySummary,
|
poolsWeeklySummary,
|
||||||
@@ -1192,34 +1360,8 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
|
|
||||||
let contextUsedPct = null;
|
let contextUsedPct = null;
|
||||||
if (lastRootStep) {
|
if (lastRootStep) {
|
||||||
const limitTokens = Number(lastRootStep.maxContextBudgetTokens || 256000);
|
contextUsedPct = extractActiveContextTelemetry(rootSteps, lastRootStep, 0, 0).context
|
||||||
const cb = lastRootStep.contextBreakdown;
|
.compactionUsedPct;
|
||||||
const cbTotal = cb
|
|
||||||
? Number(cb.messagesTokens || 0) +
|
|
||||||
Number(cb.systemToolsTokens || 0) +
|
|
||||||
Number(cb.mcpToolsTokens || 0) +
|
|
||||||
Number(cb.skillsTokens || 0) +
|
|
||||||
Number(cb.systemPromptTokens || 0) +
|
|
||||||
Number(cb.userRulesTokens || 0)
|
|
||||||
: 0;
|
|
||||||
const apiPrompt =
|
|
||||||
Number(lastRootStep.inputTokens || 0) + Number(lastRootStep.cacheReadTokens || 0);
|
|
||||||
const apiOut = resolveStepOutputTokens(lastRootStep);
|
|
||||||
const fallbackTotal = apiPrompt + apiOut;
|
|
||||||
const estTotal = Math.max(cbTotal, Number(lastRootStep.estimatedContextTokens || 0));
|
|
||||||
const hasAlignedApiPrompt =
|
|
||||||
!lastRootStep.isCompactionStep &&
|
|
||||||
apiPrompt > 0 &&
|
|
||||||
(estTotal === 0 || apiPrompt >= estTotal * 0.5);
|
|
||||||
const usedTokens = Number(
|
|
||||||
hasAlignedApiPrompt
|
|
||||||
? fallbackTotal
|
|
||||||
: cbTotal > 0
|
|
||||||
? cbTotal
|
|
||||||
: lastRootStep.estimatedContextTokens || fallbackTotal
|
|
||||||
);
|
|
||||||
contextUsedPct =
|
|
||||||
limitTokens > 0 ? Math.min(100, +((usedTokens / limitTokens) * 100).toFixed(1)) : 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let modelShort = '';
|
let modelShort = '';
|
||||||
@@ -1269,10 +1411,15 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const rootFallbackMs =
|
const rootFallbackMs =
|
||||||
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
rootConv.lastModifiedMs || rootEntry?.lastModifiedMs || rootConv.createdTimeMs || 0;
|
||||||
|
|
||||||
|
let runNormalSubIdx = 0;
|
||||||
|
let runSideIdx = 0;
|
||||||
const subItems = rawSubs.map((subSum, idx) => {
|
const subItems = rawSubs.map((subSum, idx) => {
|
||||||
const subCid = subSum.cascadeId;
|
const subCid = subSum.cascadeId;
|
||||||
const subEntry = findTrajectoryCacheEntry(subCid);
|
const subEntry = findTrajectoryCacheEntry(subCid);
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||||
|
const isSideQ = Boolean(
|
||||||
|
subSum.isSideQuestion || subEntry?.isSideQuestion || subSpec?.typeName === 'side_question'
|
||||||
|
);
|
||||||
const rawRole =
|
const rawRole =
|
||||||
subSpec?.role ||
|
subSpec?.role ||
|
||||||
subSum.agentScriptName ||
|
subSum.agentScriptName ||
|
||||||
@@ -1280,9 +1427,37 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
subSpec?.typeName ||
|
subSpec?.typeName ||
|
||||||
'';
|
'';
|
||||||
const subIndex = idx + 1;
|
const subIndex = idx + 1;
|
||||||
const badgeText = `子${subIndex}`;
|
let sideIndex = 0;
|
||||||
const shortLabel = `子代理 #${subIndex}`;
|
let agentKind = 'subagent';
|
||||||
const role = rawRole || shortLabel;
|
let agentOrdinal = 0;
|
||||||
|
let customRole = '';
|
||||||
|
let badgeText = '';
|
||||||
|
let shortLabel = '';
|
||||||
|
let role = '';
|
||||||
|
if (isSideQ) {
|
||||||
|
sideIndex = ++runSideIdx;
|
||||||
|
agentKind = 'side_question';
|
||||||
|
agentOrdinal = sideIndex;
|
||||||
|
badgeText = `旁${sideIndex}`;
|
||||||
|
shortLabel = `旁路提问 #${sideIndex}`;
|
||||||
|
const cleanSide =
|
||||||
|
rawRole &&
|
||||||
|
rawRole !== '旁路提问' &&
|
||||||
|
rawRole !== 'Side Question' &&
|
||||||
|
rawRole !== 'side_question'
|
||||||
|
? rawRole
|
||||||
|
: '';
|
||||||
|
customRole = cleanSide;
|
||||||
|
role = cleanSide || shortLabel;
|
||||||
|
} else {
|
||||||
|
const nOrd = ++runNormalSubIdx;
|
||||||
|
agentKind = 'subagent';
|
||||||
|
agentOrdinal = nOrd;
|
||||||
|
customRole = rawRole && rawRole !== '子代理' && rawRole !== 'Subagent' ? rawRole : '';
|
||||||
|
badgeText = `子${nOrd}`;
|
||||||
|
shortLabel = `子代理 #${nOrd}`;
|
||||||
|
role = rawRole || shortLabel;
|
||||||
|
}
|
||||||
const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING';
|
const isSubRunning = subSum.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||||
const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
const stepCount = Number(subSum.stepCount ?? subEntry?.steps?.length ?? 0);
|
||||||
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
const subModMs = subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0;
|
||||||
@@ -1290,6 +1465,9 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
? subSum.liveActivity || extractLiveActivity([], true, subModMs)
|
? subSum.liveActivity || extractLiveActivity([], true, subModMs)
|
||||||
: {
|
: {
|
||||||
phase: 'done',
|
phase: 'done',
|
||||||
|
actionKey: 'done',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '已完成',
|
label: '已完成',
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -1299,10 +1477,14 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
return {
|
return {
|
||||||
cascadeId: subCid,
|
cascadeId: subCid,
|
||||||
index: subIndex,
|
index: subIndex,
|
||||||
|
agentKind,
|
||||||
|
agentOrdinal,
|
||||||
|
customRole,
|
||||||
|
...(isSideQ ? { isSideQuestion: true, sideIndex } : {}),
|
||||||
badgeText,
|
badgeText,
|
||||||
shortLabel,
|
shortLabel,
|
||||||
role,
|
role,
|
||||||
typeName: subSpec?.typeName || '',
|
typeName: isSideQ ? 'side_question' : subSpec?.typeName || '',
|
||||||
isRunning: isSubRunning,
|
isRunning: isSubRunning,
|
||||||
status: subSum.status || 'IDLE',
|
status: subSum.status || 'IDLE',
|
||||||
stepCount,
|
stepCount,
|
||||||
@@ -1318,14 +1500,18 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
const runningSubCount = subItems.filter((s) => s.isRunning).length;
|
||||||
if (
|
if (
|
||||||
isMainRunning &&
|
isMainRunning &&
|
||||||
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.label === '调用子代理') &&
|
(mainLiveAct?.toolName === 'invoke_subagent' || mainLiveAct?.actionKey === 'invoke_subagent') &&
|
||||||
runningSubCount === 0
|
runningSubCount === 0
|
||||||
) {
|
) {
|
||||||
const pendingIndex = subItems.length + 1;
|
const pendingIndex = subItems.length + 1;
|
||||||
const pendingRole = mainLiveAct.detail || '子代理';
|
const pendingCustomRole = mainLiveAct.detail || '';
|
||||||
|
const pendingRole = pendingCustomRole || '子代理';
|
||||||
subItems.push({
|
subItems.push({
|
||||||
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
|
cascadeId: `${rootConv.cascadeId}:pending-sub-${pendingIndex}`,
|
||||||
index: pendingIndex,
|
index: pendingIndex,
|
||||||
|
agentKind: 'subagent',
|
||||||
|
agentOrdinal: pendingIndex,
|
||||||
|
customRole: pendingCustomRole,
|
||||||
badgeText: `子${pendingIndex}`,
|
badgeText: `子${pendingIndex}`,
|
||||||
shortLabel: `子代理 #${pendingIndex}`,
|
shortLabel: `子代理 #${pendingIndex}`,
|
||||||
role: pendingRole,
|
role: pendingRole,
|
||||||
@@ -1336,6 +1522,9 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
lastModifiedMs: rootFallbackMs,
|
lastModifiedMs: rootFallbackMs,
|
||||||
liveActivity: {
|
liveActivity: {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'starting',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '启动中',
|
label: '启动中',
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -1351,8 +1540,11 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
(runningSubList.length > 0
|
(runningSubList.length > 0
|
||||||
? {
|
? {
|
||||||
phase: 'waiting',
|
phase: 'waiting',
|
||||||
|
actionKey: 'waiting_subagent',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '等待子代理',
|
label: '等待子代理',
|
||||||
detail: runningSubList.map((s) => s.role).join(', '),
|
detail: runningSubList.map((s) => s.customRole || s.role).join(', '),
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs,
|
startedAtMs: runningSubList[0]?.liveActivity?.startedAtMs || rootFallbackMs,
|
||||||
signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`,
|
signature: `wait-subs:${runningSubList.length}:${runningSubList[0]?.cascadeId || ''}`,
|
||||||
@@ -1385,9 +1577,12 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const officialFallbackWeekBucket = quotaWeekBucket || weekBucket;
|
||||||
const finalPayload = {
|
const finalPayload = {
|
||||||
timestamp: new Date().toISOString(),
|
timestamp: new Date().toISOString(),
|
||||||
|
hostPlatform: process.platform || 'unknown',
|
||||||
uiBundleVersion,
|
uiBundleVersion,
|
||||||
|
windowBridge: getDefaultWindowBridgeStatus(),
|
||||||
settings,
|
settings,
|
||||||
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
contextWindowModels: getContextWindowGroups(getContextWindowModels(clientConfigs, contextModelCatalog)).map((group) => {
|
||||||
const latest = group.members.reduce((previous, id) => {
|
const latest = group.members.reduce((previous, id) => {
|
||||||
@@ -1460,6 +1655,9 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
: 0,
|
: 0,
|
||||||
latestCacheHitPct,
|
latestCacheHitPct,
|
||||||
sessionCacheHitPct,
|
sessionCacheHitPct,
|
||||||
|
hasKnownModel: Boolean(latestEnriched?.hasKnownModel),
|
||||||
|
activeBaseModelShort: latestEnriched?.baseModelShort || '',
|
||||||
|
activeBaseModelLabel: latestEnriched?.baseModelLabel || '',
|
||||||
activeModelShort: latestEnriched?.modelShort || '模型未知',
|
activeModelShort: latestEnriched?.modelShort || '模型未知',
|
||||||
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
||||||
activeModelUpstream:
|
activeModelUpstream:
|
||||||
@@ -1505,19 +1703,26 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
title: isCustomWeeklyMode
|
title: isCustomWeeklyMode
|
||||||
? '每周限额 (自定义本机)'
|
? '每周限额 (自定义本机)'
|
||||||
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
|
: `每周限额 (${activePoolLabel && activePoolLabel !== 'Unknown' ? activePoolLabel : '当前'})`,
|
||||||
calls: !isCustomWeeklyMode && poolsWeeklySummary ? poolsWeeklySummary.calls : weekBucket.calls,
|
calls: isCustomWeeklyMode
|
||||||
tokens:
|
? weekBucket.calls
|
||||||
!isCustomWeeklyMode && poolsWeeklySummary
|
: poolsWeeklySummary
|
||||||
|
? poolsWeeklySummary.calls
|
||||||
|
: officialFallbackWeekBucket.calls,
|
||||||
|
tokens: isCustomWeeklyMode
|
||||||
|
? weekBucket.totalTokens
|
||||||
|
: poolsWeeklySummary
|
||||||
? poolsWeeklySummary.tokens
|
? poolsWeeklySummary.tokens
|
||||||
: weekBucket.totalTokens,
|
: officialFallbackWeekBucket.totalTokens,
|
||||||
costUsd:
|
costUsd: isCustomWeeklyMode
|
||||||
!isCustomWeeklyMode && poolsWeeklySummary
|
? weekBucket.costUsd
|
||||||
|
: poolsWeeklySummary
|
||||||
? poolsWeeklySummary.costUsd
|
? poolsWeeklySummary.costUsd
|
||||||
: weekBucket.costUsd,
|
: officialFallbackWeekBucket.costUsd,
|
||||||
unpricedCalls:
|
unpricedCalls: isCustomWeeklyMode
|
||||||
!isCustomWeeklyMode && poolsWeeklySummary
|
? weekBucket.unpricedCalls
|
||||||
|
: poolsWeeklySummary
|
||||||
? poolsWeeklySummary.unpricedCalls
|
? poolsWeeklySummary.unpricedCalls
|
||||||
: weekBucket.unpricedCalls,
|
: officialFallbackWeekBucket.unpricedCalls,
|
||||||
usedPct: weeklyUsedPct,
|
usedPct: weeklyUsedPct,
|
||||||
remainingPct: weeklyRemainingPct,
|
remainingPct: weeklyRemainingPct,
|
||||||
remainingIntPct: weeklyRemainingIntPct,
|
remainingIntPct: weeklyRemainingIntPct,
|
||||||
|
|||||||
@@ -13,8 +13,8 @@ import {
|
|||||||
createSpeedAccumulator,
|
createSpeedAccumulator,
|
||||||
finishSpeed,
|
finishSpeed,
|
||||||
parseIsoMs,
|
parseIsoMs,
|
||||||
} from '../speed-metrics.mjs';
|
} from '../trajectory-metrics.mjs';
|
||||||
import { roundMetric, trajectoryCache } from './config.mjs';
|
import { listCachedTrajectoryEntries, roundMetric } from './config.mjs';
|
||||||
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
import { loadExternalDeepStatsCache } from './local-scanner.mjs';
|
||||||
import {
|
import {
|
||||||
computeStepCost,
|
computeStepCost,
|
||||||
@@ -30,6 +30,10 @@ function safeTok(val) {
|
|||||||
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
return Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function normalizeOwnerAccount(val) {
|
||||||
|
return typeof val === 'string' ? val.trim().toLowerCase() : '';
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取本地当日 00:00:00.000 的毫秒时间戳。
|
* 获取本地当日 00:00:00.000 的毫秒时间戳。
|
||||||
*
|
*
|
||||||
@@ -399,7 +403,8 @@ function sameUsageEntries(previous, current) {
|
|||||||
return previous.length === current.length && current.every((entry, index) => {
|
return previous.length === current.length && current.every((entry, index) => {
|
||||||
const before = previous[index];
|
const before = previous[index];
|
||||||
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
return entry.steps === before.steps && entry.cascadeId === before.cascadeId &&
|
||||||
entry.appSource === before.appSource && entry.isCurrentConv === before.isCurrentConv;
|
entry.appSource === before.appSource && entry.accountName === before.accountName &&
|
||||||
|
entry.isCurrentConv === before.isCurrentConv;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -515,6 +520,9 @@ export function aggregateMultiWindowUsage({
|
|||||||
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
const hasDedicatedCarbonPool = poolCycleBuckets.has('Carbon');
|
||||||
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
const hasDedicatedArgonPool = poolCycleBuckets.has('Argon');
|
||||||
const poolByModel = new Map();
|
const poolByModel = new Map();
|
||||||
|
const quotaWeekBucket = createUsageBucket();
|
||||||
|
const normalizedQuotaAccount =
|
||||||
|
currentAccountName === null ? null : normalizeOwnerAccount(currentAccountName);
|
||||||
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
||||||
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
||||||
const perModelStats = new Map();
|
const perModelStats = new Map();
|
||||||
@@ -523,6 +531,11 @@ export function aggregateMultiWindowUsage({
|
|||||||
let latestSelectedStepMs = 0;
|
let latestSelectedStepMs = 0;
|
||||||
|
|
||||||
const currentYear = new Date(nowMs).getFullYear();
|
const currentYear = new Date(nowMs).getFullYear();
|
||||||
|
const monthBoundsMs = Array.from({ length: 13 }, (_, idx) =>
|
||||||
|
new Date(currentYear, idx, 1).getTime()
|
||||||
|
);
|
||||||
|
const yearStartMs = monthBoundsMs[0];
|
||||||
|
const nextYearStartMs = monthBoundsMs[12];
|
||||||
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({
|
const monthlySeries = Array.from({ length: 12 }, (_, idx) => ({
|
||||||
month: idx + 1,
|
month: idx + 1,
|
||||||
label: `${idx + 1}月`,
|
label: `${idx + 1}月`,
|
||||||
@@ -545,7 +558,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
|
|
||||||
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
|
// 构建大小写归一化的内存缓存与跨端深层缓存索引,彻底杜绝 `${appSource}:${cascadeId}` 键不匹配导致的双倍重复计费
|
||||||
const allLiveByLower = new Map();
|
const allLiveByLower = new Map();
|
||||||
for (const [rawId, entry] of Object.entries(trajectoryCache)) {
|
for (const [rawId, entry] of listCachedTrajectoryEntries()) {
|
||||||
const cidLower = String(rawId || '').toLowerCase();
|
const cidLower = String(rawId || '').toLowerCase();
|
||||||
if (!cidLower || !entry || typeof entry !== 'object') continue;
|
if (!cidLower || !entry || typeof entry !== 'object') continue;
|
||||||
const prev = allLiveByLower.get(cidLower);
|
const prev = allLiveByLower.get(cidLower);
|
||||||
@@ -558,15 +571,6 @@ export function aggregateMultiWindowUsage({
|
|||||||
for (const ext of externalConvos.values()) {
|
for (const ext of externalConvos.values()) {
|
||||||
const extCidLower = String(ext?.cascadeId || '').toLowerCase();
|
const extCidLower = String(ext?.cascadeId || '').toLowerCase();
|
||||||
if (!extCidLower) continue;
|
if (!extCidLower) continue;
|
||||||
const knownLive = allLiveByLower.get(extCidLower);
|
|
||||||
const ownerAccount = ext.accountName || knownLive?.accountName || '';
|
|
||||||
if (
|
|
||||||
ownerAccount &&
|
|
||||||
currentAccountName !== '' &&
|
|
||||||
ownerAccount !== currentAccountName
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const prevExt = externalByCid.get(extCidLower);
|
const prevExt = externalByCid.get(extCidLower);
|
||||||
if (!prevExt || (ext.steps?.length || 0) > (prevExt.steps?.length || 0)) {
|
if (!prevExt || (ext.steps?.length || 0) > (prevExt.steps?.length || 0)) {
|
||||||
externalByCid.set(extCidLower, ext);
|
externalByCid.set(extCidLower, ext);
|
||||||
@@ -576,13 +580,6 @@ export function aggregateMultiWindowUsage({
|
|||||||
const allEntriesToAggregate = [];
|
const allEntriesToAggregate = [];
|
||||||
|
|
||||||
for (const [cidLower, entry] of allLiveByLower.entries()) {
|
for (const [cidLower, entry] of allLiveByLower.entries()) {
|
||||||
if (
|
|
||||||
entry?.accountName &&
|
|
||||||
currentAccountName !== '' &&
|
|
||||||
entry.accountName !== currentAccountName
|
|
||||||
) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
const extMatch = externalByCid.get(cidLower);
|
const extMatch = externalByCid.get(cidLower);
|
||||||
if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) {
|
if (extMatch && (extMatch.steps?.length || 0) > (entry?.steps?.length || 0)) {
|
||||||
continue;
|
continue;
|
||||||
@@ -593,6 +590,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
allEntriesToAggregate.push({
|
allEntriesToAggregate.push({
|
||||||
cascadeId: groupCascadeId,
|
cascadeId: groupCascadeId,
|
||||||
appSource: entry?.appSource || 'standalone',
|
appSource: entry?.appSource || 'standalone',
|
||||||
|
accountName: entry?.accountName || extMatch?.accountName || '',
|
||||||
steps: entry?.steps || [],
|
steps: entry?.steps || [],
|
||||||
isCurrentConv: familySet.has(cidLower),
|
isCurrentConv: familySet.has(cidLower),
|
||||||
});
|
});
|
||||||
@@ -606,6 +604,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
allEntriesToAggregate.push({
|
allEntriesToAggregate.push({
|
||||||
cascadeId: extCidLower,
|
cascadeId: extCidLower,
|
||||||
appSource: ext.appSource || 'ide',
|
appSource: ext.appSource || 'ide',
|
||||||
|
accountName: ext.accountName || liveEntry?.accountName || '',
|
||||||
steps: ext.steps || [],
|
steps: ext.steps || [],
|
||||||
isCurrentConv: familySet.has(extCidLower),
|
isCurrentConv: familySet.has(extCidLower),
|
||||||
});
|
});
|
||||||
@@ -619,7 +618,9 @@ export function aggregateMultiWindowUsage({
|
|||||||
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
const windows = [selectedWindow, ...Object.values(presetWindows), ...quotaWindows];
|
||||||
const snapshot = lastUsageSnapshot;
|
const snapshot = lastUsageSnapshot;
|
||||||
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
const sameSnapshot = modelInputs && snapshot && timeZone === snapshot.timeZone &&
|
||||||
currentYear === snapshot.currentYear && modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
|
currentYear === snapshot.currentYear &&
|
||||||
|
normalizedQuotaAccount === snapshot.normalizedQuotaAccount &&
|
||||||
|
modelInputs.catalogRevision === snapshot.modelInputs.catalogRevision &&
|
||||||
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
|
isDeepStrictEqual(modelInputs.dynamicModelMap, snapshot.modelInputs.dynamicModelMap) &&
|
||||||
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
|
sameUsageEntries(snapshot.entries, allEntriesToAggregate);
|
||||||
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
|
const previous = sameSnapshot ? snapshot.ranges.get(selectedWindow.key) : null;
|
||||||
@@ -640,11 +641,19 @@ export function aggregateMultiWindowUsage({
|
|||||||
|
|
||||||
for (const entry of allEntriesToAggregate) {
|
for (const entry of allEntriesToAggregate) {
|
||||||
const { cascadeId, isCurrentConv } = entry;
|
const { cascadeId, isCurrentConv } = entry;
|
||||||
|
const entryOwner = normalizeOwnerAccount(entry.accountName);
|
||||||
const srcKey = entry.appSource || 'standalone';
|
const srcKey = entry.appSource || 'standalone';
|
||||||
const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
|
const srcName = SOURCE_LABELS[srcKey] || `Antigravity (${srcKey})`;
|
||||||
|
|
||||||
for (const st of entry.steps || []) {
|
for (const st of entry.steps || []) {
|
||||||
if (!st || typeof st !== 'object') continue;
|
if (!st || typeof st !== 'object') continue;
|
||||||
|
const stepOwner = normalizeOwnerAccount(st.accountName) || entryOwner;
|
||||||
|
const includeInQuotaPools =
|
||||||
|
normalizedQuotaAccount === null
|
||||||
|
? false
|
||||||
|
: normalizedQuotaAccount === ''
|
||||||
|
? true
|
||||||
|
: stepOwner === normalizedQuotaAccount;
|
||||||
const mInfo = resolveStepModel(st);
|
const mInfo = resolveStepModel(st);
|
||||||
const inTok = safeTok(st.inputTokens);
|
const inTok = safeTok(st.inputTokens);
|
||||||
const cacheTok = safeTok(st.cacheReadTokens);
|
const cacheTok = safeTok(st.cacheReadTokens);
|
||||||
@@ -665,21 +674,25 @@ export function aggregateMultiWindowUsage({
|
|||||||
const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
const stepUsage = { inTok, cacheTok, outTok, thinkTok, respTok, stepTotalTokens,
|
||||||
resolvedCost, savedCost, unpriced };
|
resolvedCost, savedCost, unpriced };
|
||||||
|
|
||||||
if (tMs > 0) {
|
if (tMs >= yearStartMs && tMs < nextYearStartMs) {
|
||||||
const stepDate = new Date(tMs);
|
let monthIdx = 11;
|
||||||
if (stepDate.getFullYear() === currentYear) {
|
for (let m = 0; m < 12; m++) {
|
||||||
const mBucket = monthlySeries[stepDate.getMonth()];
|
if (tMs < monthBoundsMs[m + 1]) {
|
||||||
if (mBucket) {
|
monthIdx = m;
|
||||||
mBucket.calls += 1;
|
break;
|
||||||
mBucket.inputTokens += inTok;
|
|
||||||
mBucket.cacheReadTokens += cacheTok;
|
|
||||||
mBucket.responseTokens += respTok;
|
|
||||||
mBucket.thinkingTokens += thinkTok;
|
|
||||||
mBucket.totalTokens += stepTotalTokens;
|
|
||||||
mBucket.costUsd += resolvedCost;
|
|
||||||
mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const mBucket = monthlySeries[monthIdx];
|
||||||
|
if (mBucket) {
|
||||||
|
mBucket.calls += 1;
|
||||||
|
mBucket.inputTokens += inTok;
|
||||||
|
mBucket.cacheReadTokens += cacheTok;
|
||||||
|
mBucket.responseTokens += respTok;
|
||||||
|
mBucket.thinkingTokens += thinkTok;
|
||||||
|
mBucket.totalTokens += stepTotalTokens;
|
||||||
|
mBucket.costUsd += resolvedCost;
|
||||||
|
mBucket.unpricedCalls = (mBucket.unpricedCalls || 0) + unpriced;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const k of presetKeys) {
|
for (const k of presetKeys) {
|
||||||
@@ -689,10 +702,13 @@ export function aggregateMultiWindowUsage({
|
|||||||
if (isCurrentConv) {
|
if (isCurrentConv) {
|
||||||
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
|
accumulateStepIntoBucket(sessionBuckets[k], stepUsage, cascadeId);
|
||||||
}
|
}
|
||||||
|
if (k === 'week' && includeInQuotaPools) {
|
||||||
|
accumulateStepIntoBucket(quotaWeekBucket, stepUsage, cascadeId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
if (includeInQuotaPools && poolCycleBuckets.size > 0 && tMs > 0 && tMs <= nowMs) {
|
||||||
let cachedPool = poolByModel.get(mInfo);
|
let cachedPool = poolByModel.get(mInfo);
|
||||||
if (!cachedPool || cachedPool.key !== st.modelKey ||
|
if (!cachedPool || cachedPool.key !== st.modelKey ||
|
||||||
cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
|
cachedPool.response !== st.responseModel || cachedPool.displayName !== st.modelDisplayName) {
|
||||||
@@ -952,6 +968,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
|
|
||||||
const todayBucket = finalizedPresets.today.account;
|
const todayBucket = finalizedPresets.today.account;
|
||||||
const weekBucket = finalizedPresets.week.account;
|
const weekBucket = finalizedPresets.week.account;
|
||||||
|
const finalizedQuotaWeekBucket = finalizeUsageBucket(quotaWeekBucket);
|
||||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||||
|
|
||||||
const formatCycleSummary = (b) => {
|
const formatCycleSummary = (b) => {
|
||||||
@@ -1005,6 +1022,7 @@ export function aggregateMultiWindowUsage({
|
|||||||
monthlySeries,
|
monthlySeries,
|
||||||
todayBucket,
|
todayBucket,
|
||||||
weekBucket,
|
weekBucket,
|
||||||
|
quotaWeekBucket: finalizedQuotaWeekBucket,
|
||||||
modelBreakdown,
|
modelBreakdown,
|
||||||
poolCycleStats,
|
poolCycleStats,
|
||||||
poolsWeeklySummary,
|
poolsWeeklySummary,
|
||||||
@@ -1012,7 +1030,13 @@ export function aggregateMultiWindowUsage({
|
|||||||
if (modelInputs) {
|
if (modelInputs) {
|
||||||
if (!sameSnapshot) {
|
if (!sameSnapshot) {
|
||||||
lastUsageSnapshot = {
|
lastUsageSnapshot = {
|
||||||
timeZone, modelInputs, currentYear, entries: allEntriesToAggregate, dates: null, ranges: new Map(),
|
timeZone,
|
||||||
|
modelInputs,
|
||||||
|
currentYear,
|
||||||
|
normalizedQuotaAccount,
|
||||||
|
entries: allEntriesToAggregate,
|
||||||
|
dates: null,
|
||||||
|
ranges: new Map(),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
const { ranges } = lastUsageSnapshot;
|
const { ranges } = lastUsageSnapshot;
|
||||||
|
|||||||
@@ -10,9 +10,17 @@
|
|||||||
* 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。
|
* 3. 完全不触碰宿主 `app.asar` 文件,客户端升级或无调试端口时静默回退至右侧辅助栏。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
|
||||||
import { homedir } from 'node:os';
|
import { homedir } from 'node:os';
|
||||||
import { dirname, join } from 'node:path';
|
import { dirname, join } from 'node:path';
|
||||||
|
import {
|
||||||
|
BRIDGE_API_PATHS,
|
||||||
|
CONTEXT_WINDOWS_GLOBAL_KEY,
|
||||||
|
WINDOW_BRIDGE_KEY,
|
||||||
|
WINDOW_BRIDGE_ROUTE_KEY,
|
||||||
|
WINDOW_OVERLAY_KEY,
|
||||||
|
WINDOW_OVERLAY_METHODS,
|
||||||
|
} from '../shared/window-bridge-protocol.mjs';
|
||||||
import {
|
import {
|
||||||
DATA_DIR,
|
DATA_DIR,
|
||||||
computeRuntimeCodeVersion,
|
computeRuntimeCodeVersion,
|
||||||
@@ -22,20 +30,27 @@ import {
|
|||||||
normalizeWindowMountMode,
|
normalizeWindowMountMode,
|
||||||
saveJson,
|
saveJson,
|
||||||
} from './config.mjs';
|
} from './config.mjs';
|
||||||
import { createContextWindowSyncExpression } from './context-windows.mjs';
|
import {
|
||||||
|
createContextWindowSyncExpression,
|
||||||
|
getContextWindowModels,
|
||||||
|
resolveContextWindowRules,
|
||||||
|
} from './context-windows.mjs';
|
||||||
|
import {
|
||||||
|
ensureDesktopLaunchEntriesConfigured,
|
||||||
|
resolveDesktopHostExecutable,
|
||||||
|
} from './desktop-launcher-config.mjs';
|
||||||
|
import { callLsRpc, getContextModelCatalog } from './ls-rpc.mjs';
|
||||||
|
|
||||||
|
const windowBridgeRef = `window[${JSON.stringify(WINDOW_BRIDGE_KEY)}]`;
|
||||||
|
const windowOverlayRef = `window[${JSON.stringify(WINDOW_OVERLAY_KEY)}]`;
|
||||||
|
const windowContextWindowsRef = `window[${JSON.stringify(CONTEXT_WINDOWS_GLOBAL_KEY)}]`;
|
||||||
|
const windowBridgeRouteKey = JSON.stringify(WINDOW_BRIDGE_ROUTE_KEY);
|
||||||
|
const overlayMethods = Object.fromEntries(
|
||||||
|
Object.entries(WINDOW_OVERLAY_METHODS).map(([method, key]) => [method, JSON.stringify(key)])
|
||||||
|
);
|
||||||
|
|
||||||
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
|
||||||
const ALLOWED_BRIDGE_PATHS = new Set([
|
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
|
||||||
'/api/telemetry',
|
|
||||||
'/api/settings',
|
|
||||||
'/api/settings/reset',
|
|
||||||
'/api/cache/rebuild',
|
|
||||||
'/api/accounts',
|
|
||||||
'/api/accounts/update',
|
|
||||||
'/api/context-window',
|
|
||||||
'/api/cloud-sync',
|
|
||||||
'/api/plugin-update',
|
|
||||||
]);
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
* 解析各操作系统下 Antigravity 2.0 与 Antigravity IDE 写入 `DevToolsActivePort` 的候选路径列表。
|
||||||
@@ -68,6 +83,10 @@ export function resolveDevToolsPortCandidates(
|
|||||||
return [
|
return [
|
||||||
join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'),
|
join(homeDir, 'Library', 'Application Support', 'Antigravity', 'DevToolsActivePort'),
|
||||||
join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort'),
|
join(homeDir, 'Library', 'Application Support', 'Antigravity IDE', 'DevToolsActivePort'),
|
||||||
|
join(homeDir, 'Library', 'Application Support', 'antigravity', 'DevToolsActivePort'),
|
||||||
|
join(homeDir, 'Library', 'Application Support', 'antigravity-ide', 'DevToolsActivePort'),
|
||||||
|
join(homeDir, '.config', 'Antigravity', 'DevToolsActivePort'),
|
||||||
|
join(homeDir, '.config', 'Antigravity IDE', 'DevToolsActivePort'),
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config');
|
const configHome = env?.XDG_CONFIG_HOME || join(homeDir, '.config');
|
||||||
@@ -256,8 +275,8 @@ function scanJsoncObject(rawText) {
|
|||||||
*/
|
*/
|
||||||
export function ensureRemoteDebuggingInArgvText(rawText) {
|
export function ensureRemoteDebuggingInArgvText(rawText) {
|
||||||
if (typeof rawText !== 'string' || !rawText.trim()) {
|
if (typeof rawText !== 'string' || !rawText.trim()) {
|
||||||
const fresh =
|
// 新建文件使用纯 JSON(无注释),同时兼容 VS Code/IDE JSONC 解析器与 Electron 严格 JSON.parse()
|
||||||
'{\n\t// Automatically configured by Antigravity Usage & Speed Monitor for topbar overlay support.\n\t"remote-debugging-port": "0"\n}\n';
|
const fresh = '{\n\t"remote-debugging-port": "0"\n}\n';
|
||||||
return { changed: true, valid: true, portValue: '0', text: fresh };
|
return { changed: true, valid: true, portValue: '0', text: fresh };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -329,25 +348,14 @@ export function ensureRemoteDebuggingInArgvText(rawText) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
function patchSingleHostArgvFile(argvPath, { createDir = false, missingReason = 'dir_missing' } = {}) {
|
||||||
* 当本机存在 `~/.antigravity-ide` 配置目录且开启双栖模式时,自动补齐 `argv.json` 中的
|
|
||||||
* `"remote-debugging-port": "0"`,使 Antigravity IDE 下次启动时自动生成 `DevToolsActivePort`。
|
|
||||||
*
|
|
||||||
* @param {{ env?: Record<string, string|undefined>, homeDir?: string, enabled?: boolean }} [options]
|
|
||||||
*/
|
|
||||||
export function ensureIdeRemoteDebuggingArgv({
|
|
||||||
env = process.env,
|
|
||||||
homeDir = homedir(),
|
|
||||||
enabled = true,
|
|
||||||
} = {}) {
|
|
||||||
if (!enabled) {
|
|
||||||
return { checked: false, updated: false, reason: 'disabled' };
|
|
||||||
}
|
|
||||||
const argvPath = resolveIdeArgvPath(env, homeDir);
|
|
||||||
try {
|
try {
|
||||||
const dirPath = dirname(argvPath);
|
const dirPath = dirname(argvPath);
|
||||||
if (!existsSync(dirPath)) {
|
if (!existsSync(dirPath)) {
|
||||||
return { checked: true, updated: false, reason: 'ide_dir_missing', argvPath };
|
if (!createDir) {
|
||||||
|
return { checked: true, updated: false, reason: missingReason, argvPath };
|
||||||
|
}
|
||||||
|
mkdirSync(dirPath, { recursive: true });
|
||||||
}
|
}
|
||||||
const rawText = existsSync(argvPath) ? readFileSync(argvPath, 'utf8') : '';
|
const rawText = existsSync(argvPath) ? readFileSync(argvPath, 'utf8') : '';
|
||||||
const patched = ensureRemoteDebuggingInArgvText(rawText);
|
const patched = ensureRemoteDebuggingInArgvText(rawText);
|
||||||
@@ -391,6 +399,27 @@ export function ensureIdeRemoteDebuggingArgv({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 当本机存在 `~/.antigravity-ide` 配置目录且开启双栖模式时,自动补齐 `argv.json` 中的
|
||||||
|
* `"remote-debugging-port": "0"`,使 Antigravity IDE 下次启动时自动生成 `DevToolsActivePort`。
|
||||||
|
*
|
||||||
|
* @param {{ env?: Record<string, string|undefined>, homeDir?: string, enabled?: boolean }} [options]
|
||||||
|
*/
|
||||||
|
export function ensureIdeRemoteDebuggingArgv({
|
||||||
|
env = process.env,
|
||||||
|
homeDir = homedir(),
|
||||||
|
enabled = true,
|
||||||
|
} = {}) {
|
||||||
|
if (!enabled) {
|
||||||
|
return { checked: false, updated: false, reason: 'disabled' };
|
||||||
|
}
|
||||||
|
const argvPath = resolveIdeArgvPath(env, homeDir);
|
||||||
|
return patchSingleHostArgvFile(argvPath, {
|
||||||
|
createDir: false,
|
||||||
|
missingReason: 'ide_dir_missing',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 从 `DevToolsActivePort` 文件文本首行提取合法的本地调试端口号。
|
* 从 `DevToolsActivePort` 文件文本首行提取合法的本地调试端口号。
|
||||||
*
|
*
|
||||||
@@ -685,6 +714,10 @@ export function createWindowBridgeController(options) {
|
|||||||
onVersionDrift = null,
|
onVersionDrift = null,
|
||||||
leaseFilePath = '',
|
leaseFilePath = '',
|
||||||
autoConfigureIdeArgv = options?.env === undefined && options?.homeDir === undefined,
|
autoConfigureIdeArgv = options?.env === undefined && options?.homeDir === undefined,
|
||||||
|
launcherExecFileFn = null,
|
||||||
|
launcherFsOps = null,
|
||||||
|
allowDesktopLauncherInTest = false,
|
||||||
|
existsHostFn = existsSync,
|
||||||
WebSocketImpl = globalThis.WebSocket,
|
WebSocketImpl = globalThis.WebSocket,
|
||||||
} = options || {};
|
} = options || {};
|
||||||
|
|
||||||
@@ -711,8 +744,36 @@ export function createWindowBridgeController(options) {
|
|||||||
let hadInjectedChatFrames = false;
|
let hadInjectedChatFrames = false;
|
||||||
let cdpFallbackActive = false;
|
let cdpFallbackActive = false;
|
||||||
let ideArgvProvisioned = false;
|
let ideArgvProvisioned = false;
|
||||||
|
let hostLauncherPromise = null;
|
||||||
|
let argvUpdatedThisBoot = false;
|
||||||
|
let argvConfigured = false;
|
||||||
|
let launcherConfigured = false;
|
||||||
|
const hostExecInfo = resolveDesktopHostExecutable({
|
||||||
|
env,
|
||||||
|
platform,
|
||||||
|
homeDir,
|
||||||
|
existsFn: existsHostFn,
|
||||||
|
});
|
||||||
|
// Windows / macOS 支持从运行中宿主进程动态反查任意盘符路径,因此桌面端环境下即使自定义安装路径不在默认盘符也可一键重拉
|
||||||
|
const canRelaunch = Boolean(
|
||||||
|
hostExecInfo.found ||
|
||||||
|
((platform === 'win32' || platform === 'darwin') && options?.existsHostFn === undefined)
|
||||||
|
);
|
||||||
|
let lastPersistedLeaseSig = '';
|
||||||
|
let lastBridgeStatus = {
|
||||||
|
state: 'pending',
|
||||||
|
enabled: true,
|
||||||
|
aliveCount: 0,
|
||||||
|
targets: 0,
|
||||||
|
argvUpdatedThisBoot: false,
|
||||||
|
argvConfigured: false,
|
||||||
|
launcherConfigured: false,
|
||||||
|
canRelaunch,
|
||||||
|
updatedAtMs: 0,
|
||||||
|
};
|
||||||
let hadContextWindows = false;
|
let hadContextWindows = false;
|
||||||
let contextWindowBootId = `${process.pid}:${Date.now()}`;
|
let contextWindowBootId = `${process.pid}:${Date.now()}`;
|
||||||
|
let cachedBackendCtxModels = { expiresAt: 0, models: [] };
|
||||||
let nodeDepsPromise = null;
|
let nodeDepsPromise = null;
|
||||||
const allowedDynamicOrigins = new Set();
|
const allowedDynamicOrigins = new Set();
|
||||||
|
|
||||||
@@ -986,6 +1047,17 @@ export function createWindowBridgeController(options) {
|
|||||||
// 忽略不可读候选文件
|
// 忽略不可读候选文件
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const rawExplicitPorts = String(env?.ANTIGRAVITY_DEVTOOLS_PORT || '').trim();
|
||||||
|
if (rawExplicitPorts) {
|
||||||
|
for (const token of rawExplicitPorts.split(/[\s,]+/)) {
|
||||||
|
if (!/^\d+$/.test(token)) continue;
|
||||||
|
const p = Number(token);
|
||||||
|
if (Number.isInteger(p) && p > 0 && p <= 65535 && !seen.has(p)) {
|
||||||
|
seen.add(p);
|
||||||
|
ports.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
return ports;
|
return ports;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1128,6 +1200,70 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function updateBridgeStatus(nextState, { enabled = true, aliveCount = 0, targets = 0, leasedBySelf = false, bundleVersion = '', prevLease = null } = {}) {
|
||||||
|
lastBridgeStatus = {
|
||||||
|
state: nextState,
|
||||||
|
enabled: Boolean(enabled),
|
||||||
|
aliveCount: Number(aliveCount || 0),
|
||||||
|
targets: Number(targets || 0),
|
||||||
|
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
||||||
|
argvConfigured: Boolean(argvConfigured || launcherConfigured),
|
||||||
|
launcherConfigured: Boolean(launcherConfigured || argvConfigured),
|
||||||
|
canRelaunch: Boolean(canRelaunch),
|
||||||
|
updatedAtMs: Date.now(),
|
||||||
|
};
|
||||||
|
if (leasedBySelf && leaseFilePath) {
|
||||||
|
const sig = `${nextState}:${lastBridgeStatus.aliveCount}:${lastBridgeStatus.targets}:${lastBridgeStatus.argvUpdatedThisBoot ? 1 : 0}:${lastBridgeStatus.launcherConfigured ? 1 : 0}:${lastBridgeStatus.canRelaunch ? 1 : 0}`;
|
||||||
|
if (sig !== lastPersistedLeaseSig) {
|
||||||
|
lastPersistedLeaseSig = sig;
|
||||||
|
saveJson(leaseFilePath, {
|
||||||
|
pid: process.pid,
|
||||||
|
bundleVersion,
|
||||||
|
bridgePort: bridgePort > 0 ? bridgePort : Number(prevLease?.bridgePort || 0) || undefined,
|
||||||
|
bridgeToken: bridgeToken || String(prevLease?.bridgeToken || '') || undefined,
|
||||||
|
syncState: lastBridgeStatus.state,
|
||||||
|
aliveCount: lastBridgeStatus.aliveCount,
|
||||||
|
targets: lastBridgeStatus.targets,
|
||||||
|
argvUpdatedThisBoot: lastBridgeStatus.argvUpdatedThisBoot,
|
||||||
|
argvConfigured: lastBridgeStatus.argvConfigured,
|
||||||
|
launcherConfigured: lastBridgeStatus.launcherConfigured,
|
||||||
|
canRelaunch: lastBridgeStatus.canRelaunch,
|
||||||
|
updatedAtMs: Date.now(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function provisionHostLaunchersOnce() {
|
||||||
|
if (ideArgvProvisioned) return Promise.resolve();
|
||||||
|
if (hostLauncherPromise) return hostLauncherPromise;
|
||||||
|
hostLauncherPromise = (async () => {
|
||||||
|
const ideRes = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true });
|
||||||
|
const desktopRes = await ensureDesktopLaunchEntriesConfigured({
|
||||||
|
enabled: true,
|
||||||
|
env,
|
||||||
|
platform,
|
||||||
|
homeDir,
|
||||||
|
execFileFn: launcherExecFileFn,
|
||||||
|
fsOps: launcherFsOps,
|
||||||
|
allowInTest: allowDesktopLauncherInTest,
|
||||||
|
});
|
||||||
|
if (ideRes.updated || desktopRes.updated) {
|
||||||
|
argvUpdatedThisBoot = true;
|
||||||
|
}
|
||||||
|
if (ideRes.updated || ideRes.alreadyConfigured) {
|
||||||
|
argvConfigured = true;
|
||||||
|
}
|
||||||
|
if (desktopRes.updated || desktopRes.alreadyConfigured || desktopRes.configured) {
|
||||||
|
launcherConfigured = true;
|
||||||
|
}
|
||||||
|
ideArgvProvisioned = true;
|
||||||
|
})().finally(() => {
|
||||||
|
hostLauncherPromise = null;
|
||||||
|
});
|
||||||
|
return hostLauncherPromise;
|
||||||
|
}
|
||||||
|
|
||||||
async function runSyncInternal({ forceReinject = false } = {}) {
|
async function runSyncInternal({ forceReinject = false } = {}) {
|
||||||
if (stopped) return { ok: false, reason: 'stopped' };
|
if (stopped) return { ok: false, reason: 'stopped' };
|
||||||
const bundleVersion = String(getBundleVersionFn() || '');
|
const bundleVersion = String(getBundleVersionFn() || '');
|
||||||
@@ -1144,15 +1280,16 @@ export function createWindowBridgeController(options) {
|
|||||||
const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
const enabled = Boolean(curSettings.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||||
const contextWindows = curSettings.modelContextWindows || {};
|
const contextWindows = curSettings.modelContextWindows || {};
|
||||||
const hasContextWindows = Object.keys(contextWindows).length > 0;
|
const hasContextWindows = Object.keys(contextWindows).length > 0;
|
||||||
if ((enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned) {
|
const provPending =
|
||||||
const prov = ensureIdeRemoteDebuggingArgv({ env, homeDir, enabled: true });
|
(enabled || hasContextWindows) && autoConfigureIdeArgv && !ideArgvProvisioned
|
||||||
if (prov.updated || prov.alreadyConfigured || prov.reason === 'ide_dir_missing') {
|
? provisionHostLaunchersOnce()
|
||||||
ideArgvProvisioned = true;
|
: hostLauncherPromise;
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
let leasedBySelf = false;
|
||||||
|
let currentLease = null;
|
||||||
if ((enabled || hasContextWindows) && leaseFilePath && !forceReinject) {
|
if ((enabled || hasContextWindows) && leaseFilePath && !forceReinject) {
|
||||||
const lease = loadJson(leaseFilePath, null);
|
const lease = loadJson(leaseFilePath, null);
|
||||||
|
currentLease = lease;
|
||||||
const leasePid = Number(lease?.pid || 0);
|
const leasePid = Number(lease?.pid || 0);
|
||||||
const leaseAgeMs = Date.now() - Number(lease?.updatedAtMs || 0);
|
const leaseAgeMs = Date.now() - Number(lease?.updatedAtMs || 0);
|
||||||
if (leasePid > 0 && leasePid !== process.pid && leaseAgeMs >= 0 && leaseAgeMs < 9000 && isPidAlive(leasePid)) {
|
if (leasePid > 0 && leasePid !== process.pid && leaseAgeMs >= 0 && leaseAgeMs < 9000 && isPidAlive(leasePid)) {
|
||||||
@@ -1163,47 +1300,125 @@ export function createWindowBridgeController(options) {
|
|||||||
return { ok: false, enabled: true, reason: 'older_than_leader', injected: 0 };
|
return { ok: false, enabled: true, reason: 'older_than_leader', injected: 0 };
|
||||||
}
|
}
|
||||||
if (leaseVerNum === myVerNum || String(lease?.bundleVersion || '') === bundleVersion) {
|
if (leaseVerNum === myVerNum || String(lease?.bundleVersion || '') === bundleVersion) {
|
||||||
|
const mergedConfigured = Boolean(
|
||||||
|
lease?.launcherConfigured || lease?.argvConfigured || launcherConfigured || argvConfigured
|
||||||
|
);
|
||||||
|
lastBridgeStatus = {
|
||||||
|
state: String(lease?.syncState || 'active'),
|
||||||
|
enabled: Boolean(enabled),
|
||||||
|
aliveCount: Number(lease?.aliveCount || 0),
|
||||||
|
targets: Number(lease?.targets || 0),
|
||||||
|
argvUpdatedThisBoot: Boolean(lease?.argvUpdatedThisBoot || argvUpdatedThisBoot),
|
||||||
|
argvConfigured: mergedConfigured,
|
||||||
|
launcherConfigured: mergedConfigured,
|
||||||
|
canRelaunch: Boolean(lease?.canRelaunch ?? canRelaunch),
|
||||||
|
updatedAtMs: Date.now(),
|
||||||
|
};
|
||||||
return { ok: true, enabled: true, reason: 'follower_yield', leaderPid: leasePid, injected: 0 };
|
return { ok: true, enabled: true, reason: 'follower_yield', leaderPid: leasePid, injected: 0 };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
leasedBySelf = true;
|
||||||
|
lastPersistedLeaseSig = '';
|
||||||
saveJson(leaseFilePath, {
|
saveJson(leaseFilePath, {
|
||||||
pid: process.pid,
|
pid: process.pid,
|
||||||
bundleVersion,
|
bundleVersion,
|
||||||
bridgePort: bridgePort > 0 ? bridgePort : Number(lease?.bridgePort || 0) || undefined,
|
bridgePort: bridgePort > 0 ? bridgePort : Number(lease?.bridgePort || 0) || undefined,
|
||||||
bridgeToken: bridgeToken || String(lease?.bridgeToken || '') || undefined,
|
bridgeToken: bridgeToken || String(lease?.bridgeToken || '') || undefined,
|
||||||
|
syncState: lastBridgeStatus.state,
|
||||||
|
aliveCount: lastBridgeStatus.aliveCount,
|
||||||
|
targets: lastBridgeStatus.targets,
|
||||||
|
argvUpdatedThisBoot: Boolean(argvUpdatedThisBoot),
|
||||||
|
argvConfigured: Boolean(argvConfigured || launcherConfigured),
|
||||||
|
launcherConfigured: Boolean(launcherConfigured || argvConfigured),
|
||||||
|
canRelaunch: Boolean(canRelaunch),
|
||||||
updatedAtMs: Date.now(),
|
updatedAtMs: Date.now(),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const cdpPorts = findActiveDevToolsPorts();
|
const cdpPorts = findActiveDevToolsPorts();
|
||||||
if (!cdpPorts.length) {
|
if (!cdpPorts.length) {
|
||||||
|
if (provPending) {
|
||||||
|
await provPending.catch(() => {});
|
||||||
|
}
|
||||||
|
updateBridgeStatus(enabled || hasContextWindows ? 'no_devtools_port' : 'disabled', {
|
||||||
|
enabled,
|
||||||
|
leasedBySelf,
|
||||||
|
bundleVersion,
|
||||||
|
prevLease: currentLease,
|
||||||
|
});
|
||||||
return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 };
|
return { ok: false, enabled, reason: 'no_devtools_port', injected: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts);
|
const { reachableCount, targets } = await collectAllMainWindowTargets(cdpPorts);
|
||||||
if (reachableCount === 0) {
|
if (reachableCount === 0) {
|
||||||
|
if (provPending) {
|
||||||
|
await provPending.catch(() => {});
|
||||||
|
}
|
||||||
|
updateBridgeStatus(enabled || hasContextWindows ? 'cdp_unreachable' : 'disabled', {
|
||||||
|
enabled,
|
||||||
|
leasedBySelf,
|
||||||
|
bundleVersion,
|
||||||
|
prevLease: currentLease,
|
||||||
|
});
|
||||||
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
|
return { ok: false, enabled, reason: 'cdp_unreachable', injected: 0 };
|
||||||
}
|
}
|
||||||
if (!targets.length) {
|
if (!targets.length) {
|
||||||
|
updateBridgeStatus(enabled ? 'no_targets' : 'disabled', {
|
||||||
|
enabled,
|
||||||
|
leasedBySelf,
|
||||||
|
bundleVersion,
|
||||||
|
prevLease: currentLease,
|
||||||
|
});
|
||||||
return { ok: true, enabled, reason: 'no_targets', injected: 0 };
|
return { ok: true, enabled, reason: 'no_targets', injected: 0 };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasContextWindows || hadContextWindows) {
|
if (hasContextWindows || hadContextWindows) {
|
||||||
|
let fallbackRules = {};
|
||||||
|
if (
|
||||||
|
hasContextWindows &&
|
||||||
|
lsRuntimeEndpoint.baseUrl &&
|
||||||
|
lsRuntimeEndpoint.addr !== 'test.invalid'
|
||||||
|
) {
|
||||||
|
if (Date.now() >= cachedBackendCtxModels.expiresAt) {
|
||||||
|
try {
|
||||||
|
const [stRes, cat] = await Promise.all([
|
||||||
|
callLsRpc('GetUserStatus', {}, 1500),
|
||||||
|
getContextModelCatalog(),
|
||||||
|
]);
|
||||||
|
const cfgs = stRes?.userStatus?.cascadeModelConfigData?.clientModelConfigs;
|
||||||
|
if (Array.isArray(cfgs)) {
|
||||||
|
cachedBackendCtxModels = {
|
||||||
|
expiresAt: Date.now() + 10_000,
|
||||||
|
models: getContextWindowModels(cfgs, cat),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// 忽略瞬态 LS 查询失败,保留上次缓存或交由窗口端解析
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cachedBackendCtxModels.models.length > 0) {
|
||||||
|
fallbackRules = resolveContextWindowRules(cachedBackendCtxModels.models, contextWindows);
|
||||||
|
}
|
||||||
|
}
|
||||||
const chatUrls = [
|
const chatUrls = [
|
||||||
...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl),
|
...targets.filter((target) => !target.isIdeWorkbench).map((target) => target.webSocketDebuggerUrl),
|
||||||
...collectAllChatDebuggerUrls(targets),
|
...collectAllChatDebuggerUrls(targets),
|
||||||
];
|
];
|
||||||
const expression = createContextWindowSyncExpression(contextWindows, contextWindowBootId);
|
const expression = createContextWindowSyncExpression(
|
||||||
|
contextWindows,
|
||||||
|
contextWindowBootId,
|
||||||
|
fallbackRules
|
||||||
|
);
|
||||||
await Promise.allSettled([...new Set(chatUrls)].map((url) => evaluateOnTarget(url, expression)));
|
await Promise.allSettled([...new Set(chatUrls)].map((url) => evaluateOnTarget(url, expression)));
|
||||||
hadContextWindows = hasContextWindows;
|
hadContextWindows = hasContextWindows;
|
||||||
}
|
}
|
||||||
|
|
||||||
const disposeExpr = `(() => {
|
const disposeExpr = `(() => {
|
||||||
try {
|
try {
|
||||||
const existed = Boolean(window.__AGUsageMonitorOverlay || window.__AGUsageMonitorBridge);
|
const existed = Boolean(${windowOverlayRef} || ${windowBridgeRef});
|
||||||
window.__AGUsageMonitorOverlay?.dispose?.();
|
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
|
||||||
delete window.__AGUsageMonitorOverlay;
|
delete ${windowOverlayRef};
|
||||||
delete window.__AGUsageMonitorBridge;
|
delete ${windowBridgeRef};
|
||||||
return existed;
|
return existed;
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
@@ -1222,6 +1437,13 @@ export function createWindowBridgeController(options) {
|
|||||||
|
|
||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) {
|
if (!hadInjectedTargets && !hadInjectedChatFrames && !forceReinject) {
|
||||||
|
updateBridgeStatus('disabled', {
|
||||||
|
enabled: false,
|
||||||
|
targets: targets.length,
|
||||||
|
leasedBySelf,
|
||||||
|
bundleVersion,
|
||||||
|
prevLease: currentLease,
|
||||||
|
});
|
||||||
return { ok: true, enabled: false, removed: 0 };
|
return { ok: true, enabled: false, removed: 0 };
|
||||||
}
|
}
|
||||||
let removed = 0;
|
let removed = 0;
|
||||||
@@ -1234,17 +1456,24 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
hadInjectedTargets = false;
|
hadInjectedTargets = false;
|
||||||
hadInjectedChatFrames = false;
|
hadInjectedChatFrames = false;
|
||||||
|
updateBridgeStatus('disabled', {
|
||||||
|
enabled: false,
|
||||||
|
targets: targets.length,
|
||||||
|
leasedBySelf,
|
||||||
|
bundleVersion,
|
||||||
|
prevLease: currentLease,
|
||||||
|
});
|
||||||
return { ok: true, enabled: false, removed };
|
return { ok: true, enabled: false, removed };
|
||||||
}
|
}
|
||||||
|
|
||||||
const { port, token } = await ensureBridgeServer();
|
const { port, token } = await ensureBridgeServer();
|
||||||
const probeExpr = `(() => {
|
const probeExpr = `(() => {
|
||||||
try {
|
try {
|
||||||
const ov = window.__AGUsageMonitorOverlay;
|
const ov = ${windowOverlayRef};
|
||||||
const br = window.__AGUsageMonitorBridge;
|
const br = ${windowBridgeRef};
|
||||||
const alive = Boolean(ov && typeof ov.ensureAlive === 'function' && ov.ensureAlive());
|
const alive = Boolean(ov && typeof ov[${overlayMethods.ensureAlive}] === 'function' && ov[${overlayMethods.ensureAlive}]());
|
||||||
const dockKind = String(ov?.getDockKind?.() || '');
|
const dockKind = String(ov?.[${overlayMethods.getDockKind}]?.() || '');
|
||||||
const clientMountMode = String(ov?.getMountMode?.() || '');
|
const clientMountMode = String(ov?.[${overlayMethods.getMountMode}]?.() || '');
|
||||||
const visible = Boolean(
|
const visible = Boolean(
|
||||||
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
|
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
|
||||||
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
|
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
|
||||||
@@ -1276,7 +1505,7 @@ export function createWindowBridgeController(options) {
|
|||||||
bridgePort: Number(br?.port || 0),
|
bridgePort: Number(br?.port || 0),
|
||||||
hasToken: Boolean(br?.token),
|
hasToken: Boolean(br?.token),
|
||||||
transportMode: String(br?.transportMode || 'http'),
|
transportMode: String(br?.transportMode || 'http'),
|
||||||
hostRouteCascadeId: String(br?.hostRouteCascadeId || ''),
|
hostRouteCascadeId: String(br?.[${windowBridgeRouteKey}] || ''),
|
||||||
routeCascadeId,
|
routeCascadeId,
|
||||||
rpcBatch,
|
rpcBatch,
|
||||||
};
|
};
|
||||||
@@ -1314,12 +1543,16 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
if (snap.bundleVersion === bundleVersion) {
|
if (snap.bundleVersion === bundleVersion) {
|
||||||
if (snap.bridgePort !== port || snap.hasToken !== true) {
|
if (snap.bridgePort !== port || snap.hasToken !== true) {
|
||||||
const rebindExpr = `window.__AGUsageMonitorOverlay?.updateBridge?.(${JSON.stringify({ port, token })})`;
|
const rebindExpr = `${windowOverlayRef}?.[${overlayMethods.updateBridge}]?.(${JSON.stringify({ port, token })})`;
|
||||||
await evaluateOnTarget(wsUrl, rebindExpr);
|
await evaluateOnTarget(wsUrl, rebindExpr);
|
||||||
}
|
}
|
||||||
let effectiveDockKind = String(snap.dockKind || '');
|
let effectiveDockKind = String(snap.dockKind || '');
|
||||||
if (snap.clientMountMode && snap.clientMountMode !== mountMode) {
|
if (snap.clientMountMode && snap.clientMountMode !== mountMode) {
|
||||||
const modeSyncExpr = `(() => { window.__AGUsageMonitorOverlay?.applyMountMode?.(${JSON.stringify(mountMode)}); return String(window.__AGUsageMonitorOverlay?.getDockKind?.() || ''); })()`;
|
const modeSyncExpr = `(() => {
|
||||||
|
const overlay = ${windowOverlayRef};
|
||||||
|
overlay?.[${overlayMethods.applyMountMode}]?.(${JSON.stringify(mountMode)});
|
||||||
|
return String(overlay?.[${overlayMethods.getDockKind}]?.() || '');
|
||||||
|
})()`;
|
||||||
const modeRes = await evaluateOnTarget(wsUrl, modeSyncExpr);
|
const modeRes = await evaluateOnTarget(wsUrl, modeSyncExpr);
|
||||||
if (typeof modeRes?.result?.result?.value === 'string') {
|
if (typeof modeRes?.result?.result?.value === 'string') {
|
||||||
effectiveDockKind = modeRes.result.result.value;
|
effectiveDockKind = modeRes.result.result.value;
|
||||||
@@ -1330,7 +1563,11 @@ export function createWindowBridgeController(options) {
|
|||||||
ideRouteId &&
|
ideRouteId &&
|
||||||
String(snap.hostRouteCascadeId || '') !== ideRouteId
|
String(snap.hostRouteCascadeId || '') !== ideRouteId
|
||||||
) {
|
) {
|
||||||
const routeSyncExpr = `(() => { if (window.__AGUsageMonitorBridge) { window.__AGUsageMonitorBridge.hostRouteCascadeId = ${JSON.stringify(ideRouteId)}; } window.__AGUsageMonitorOverlay?.syncHostRoute?.(); })()`;
|
const routeSyncExpr = `(() => {
|
||||||
|
const bridge = ${windowBridgeRef};
|
||||||
|
if (bridge) bridge[${windowBridgeRouteKey}] = ${JSON.stringify(ideRouteId)};
|
||||||
|
${windowOverlayRef}?.[${overlayMethods.syncHostRoute}]?.();
|
||||||
|
})()`;
|
||||||
await evaluateOnTarget(wsUrl, routeSyncExpr);
|
await evaluateOnTarget(wsUrl, routeSyncExpr);
|
||||||
}
|
}
|
||||||
aliveCount += 1;
|
aliveCount += 1;
|
||||||
@@ -1346,7 +1583,7 @@ export function createWindowBridgeController(options) {
|
|||||||
sawCdpTransport = true;
|
sawCdpTransport = true;
|
||||||
const rpcResults = await executeRpcBatch(snap.rpcBatch);
|
const rpcResults = await executeRpcBatch(snap.rpcBatch);
|
||||||
relayedRpcCount += rpcResults.length;
|
relayedRpcCount += rpcResults.length;
|
||||||
const deliverExpr = `window.__AGUsageMonitorOverlay?.deliverRpc?.(${JSON.stringify(rpcResults)})`;
|
const deliverExpr = `${windowOverlayRef}?.[${overlayMethods.deliverRpc}]?.(${JSON.stringify(rpcResults)})`;
|
||||||
await evaluateOnTarget(wsUrl, deliverExpr);
|
await evaluateOnTarget(wsUrl, deliverExpr);
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@@ -1387,13 +1624,27 @@ export function createWindowBridgeController(options) {
|
|||||||
port,
|
port,
|
||||||
token,
|
token,
|
||||||
bundleVersion,
|
bundleVersion,
|
||||||
|
platform: String(platform || ''),
|
||||||
mountMode,
|
mountMode,
|
||||||
hostRouteCascadeId: ideRouteId || '',
|
[WINDOW_BRIDGE_ROUTE_KEY]: ideRouteId || '',
|
||||||
isIdeChatFrame: Boolean(isIdeChatFrame),
|
isIdeChatFrame: Boolean(isIdeChatFrame),
|
||||||
stylesCss: cachedAssets.stylesCss,
|
stylesCss: cachedAssets.stylesCss,
|
||||||
initialTelemetry,
|
initialTelemetry,
|
||||||
});
|
});
|
||||||
const injectionScript = `(() => {\nwindow.__AGUsageMonitorBridge = ${bridgeConfigJson};\n})();\n${cachedAssets.appJs}\n(() => { const ov = window.__AGUsageMonitorOverlay; const alive = Boolean(ov && ov.ensureAlive && ov.ensureAlive()); return { alive, dockKind: String(ov?.getDockKind?.() || ''), visible: Boolean((window.innerWidth === undefined || Number(window.innerWidth) > 80) && (window.innerHeight === undefined || Number(window.innerHeight) > 80) && !(typeof document !== 'undefined' && document?.hidden === true)) }; })();`;
|
const injectionScript = `(() => {
|
||||||
|
${windowBridgeRef} = ${bridgeConfigJson};
|
||||||
|
})();
|
||||||
|
${cachedAssets.appJs}
|
||||||
|
(() => {
|
||||||
|
const ov = ${windowOverlayRef};
|
||||||
|
const alive = Boolean(ov?.[${overlayMethods.ensureAlive}]?.());
|
||||||
|
const visible = Boolean(
|
||||||
|
(window.innerWidth === undefined || Number(window.innerWidth) > 80) &&
|
||||||
|
(window.innerHeight === undefined || Number(window.innerHeight) > 80) &&
|
||||||
|
!(typeof document !== 'undefined' && document?.hidden === true)
|
||||||
|
);
|
||||||
|
return { alive, dockKind: String(ov?.[${overlayMethods.getDockKind}]?.() || ''), visible };
|
||||||
|
})();`;
|
||||||
|
|
||||||
const evalRes = await evaluateOnTarget(wsUrl, injectionScript);
|
const evalRes = await evaluateOnTarget(wsUrl, injectionScript);
|
||||||
const evalVal = evalRes?.result?.result?.value;
|
const evalVal = evalRes?.result?.result?.value;
|
||||||
@@ -1458,6 +1709,14 @@ export function createWindowBridgeController(options) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
cdpFallbackActive = sawCdpTransport;
|
cdpFallbackActive = sawCdpTransport;
|
||||||
|
updateBridgeStatus(aliveCount > 0 ? 'active' : 'no_targets', {
|
||||||
|
enabled: true,
|
||||||
|
aliveCount,
|
||||||
|
targets: targets.length,
|
||||||
|
leasedBySelf,
|
||||||
|
bundleVersion,
|
||||||
|
prevLease: currentLease,
|
||||||
|
});
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true,
|
||||||
enabled: true,
|
enabled: true,
|
||||||
@@ -1540,7 +1799,17 @@ export function createWindowBridgeController(options) {
|
|||||||
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({
|
const { targets } = await collectAllMainWindowTargets(cdpPorts).catch(() => ({
|
||||||
targets: [],
|
targets: [],
|
||||||
}));
|
}));
|
||||||
const disposeExpr = `(() => { try { window.__AGUsageMonitorContextWindows?.dispose?.(); window.__AGUsageMonitorOverlay?.dispose?.(); delete window.__AGUsageMonitorOverlay; delete window.__AGUsageMonitorBridge; return true; } catch { return false; } })()`;
|
const disposeExpr = `(() => {
|
||||||
|
try {
|
||||||
|
${windowContextWindowsRef}?.dispose?.();
|
||||||
|
${windowOverlayRef}?.[${overlayMethods.dispose}]?.();
|
||||||
|
delete ${windowOverlayRef};
|
||||||
|
delete ${windowBridgeRef};
|
||||||
|
return true;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
})()`;
|
||||||
const allUrls = [
|
const allUrls = [
|
||||||
...targets.map((t) => String(t.webSocketDebuggerUrl || '')).filter(Boolean),
|
...targets.map((t) => String(t.webSocketDebuggerUrl || '')).filter(Boolean),
|
||||||
...collectAllChatDebuggerUrls(targets),
|
...collectAllChatDebuggerUrls(targets),
|
||||||
@@ -1569,6 +1838,20 @@ export function createWindowBridgeController(options) {
|
|||||||
if (!enabled) {
|
if (!enabled) {
|
||||||
hadInjectedTargets = true;
|
hadInjectedTargets = true;
|
||||||
hadInjectedChatFrames = true;
|
hadInjectedChatFrames = true;
|
||||||
|
const cur = getSettingsFn() || {};
|
||||||
|
const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0;
|
||||||
|
if (!hasCtx && autoConfigureIdeArgv) {
|
||||||
|
launcherConfigured = false;
|
||||||
|
void ensureDesktopLaunchEntriesConfigured({
|
||||||
|
enabled: false,
|
||||||
|
env,
|
||||||
|
platform,
|
||||||
|
homeDir,
|
||||||
|
execFileFn: launcherExecFileFn,
|
||||||
|
fsOps: launcherFsOps,
|
||||||
|
allowInTest: allowDesktopLauncherInTest,
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
ideArgvProvisioned = false;
|
ideArgvProvisioned = false;
|
||||||
hadInjectedChatFrames = true;
|
hadInjectedChatFrames = true;
|
||||||
@@ -1576,18 +1859,62 @@ export function createWindowBridgeController(options) {
|
|||||||
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function notifyContextWindowsChanged() {
|
||||||
|
const cur = getSettingsFn() || {};
|
||||||
|
const mountMode = normalizeWindowMountMode(cur.windowMountMode, cur.enableWindowOverlay);
|
||||||
|
const overlayOn = Boolean(cur.enableWindowOverlay !== false && mountMode !== 'sidebar');
|
||||||
|
const hasCtx = Object.keys(cur.modelContextWindows || {}).length > 0;
|
||||||
|
if (hasCtx) {
|
||||||
|
ideArgvProvisioned = false;
|
||||||
|
} else if (!overlayOn && autoConfigureIdeArgv) {
|
||||||
|
launcherConfigured = false;
|
||||||
|
void ensureDesktopLaunchEntriesConfigured({
|
||||||
|
enabled: false,
|
||||||
|
env,
|
||||||
|
platform,
|
||||||
|
homeDir,
|
||||||
|
execFileFn: launcherExecFileFn,
|
||||||
|
fsOps: launcherFsOps,
|
||||||
|
allowInTest: allowDesktopLauncherInTest,
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
return syncAllWindows({ forceReinject: false }).catch(() => ({ ok: false }));
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ensureBridgeServer,
|
ensureBridgeServer,
|
||||||
syncAllWindows,
|
syncAllWindows,
|
||||||
notifySettingChanged,
|
notifySettingChanged,
|
||||||
|
notifyContextWindowsChanged,
|
||||||
start,
|
start,
|
||||||
stop,
|
stop,
|
||||||
getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }),
|
getBridgeInfo: () => ({ port: bridgePort, token: bridgeToken, running: Boolean(server) }),
|
||||||
|
getBridgeStatus: () => ({ ...lastBridgeStatus }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
let defaultBridgeController = null;
|
let defaultBridgeController = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 读取进程级默认双栖桥接器的最新同步健康度快照(供 `/api/telemetry` 与偏好设置面板诊断使用)。
|
||||||
|
*/
|
||||||
|
export function getDefaultWindowBridgeStatus() {
|
||||||
|
if (!defaultBridgeController) {
|
||||||
|
return {
|
||||||
|
state: 'pending',
|
||||||
|
enabled: true,
|
||||||
|
aliveCount: 0,
|
||||||
|
targets: 0,
|
||||||
|
argvUpdatedThisBoot: false,
|
||||||
|
argvConfigured: false,
|
||||||
|
launcherConfigured: false,
|
||||||
|
canRelaunch: false,
|
||||||
|
updatedAtMs: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return defaultBridgeController.getBridgeStatus();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 启动进程级默认的双栖窗口桥接控制器(幂等)。
|
* 启动进程级默认的双栖窗口桥接控制器(幂等)。
|
||||||
*
|
*
|
||||||
@@ -1615,5 +1942,6 @@ export function notifyWindowOverlaySetting(enabled) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function notifyModelContextWindowsChanged() {
|
export function notifyModelContextWindowsChanged() {
|
||||||
return defaultBridgeController?.syncAllWindows().catch(() => {});
|
if (!defaultBridgeController) return Promise.resolve({ ok: false });
|
||||||
|
return defaultBridgeController.notifyContextWindowsChanged();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,23 +11,18 @@
|
|||||||
|
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
import {
|
|
||||||
bootBundleVersion,
|
|
||||||
bootWindowBridgeRuntime,
|
|
||||||
setStandalonePortListener,
|
|
||||||
} from './backend/api-actions.mjs';
|
|
||||||
import {
|
|
||||||
computeRuntimeCodeVersion,
|
|
||||||
loadSettings,
|
|
||||||
normalizeStandalonePort,
|
|
||||||
} from './backend/config.mjs';
|
|
||||||
import {
|
|
||||||
createStandaloneWebServer,
|
|
||||||
parseStandaloneCliArgs,
|
|
||||||
} from './backend/standalone-server.mjs';
|
|
||||||
import { runStandaloneCli } from './standalone.mjs';
|
|
||||||
|
|
||||||
export function startBridgeDaemon() {
|
export async function startBridgeDaemon() {
|
||||||
|
const [
|
||||||
|
{ bootBundleVersion, bootWindowBridgeRuntime, setStandalonePortListener },
|
||||||
|
{ computeRuntimeCodeVersion, loadSettings, normalizeStandalonePort },
|
||||||
|
{ createStandaloneWebServer, parseStandaloneCliArgs },
|
||||||
|
] = await Promise.all([
|
||||||
|
import('./backend/api-actions.mjs'),
|
||||||
|
import('./backend/config.mjs'),
|
||||||
|
import('./backend/standalone-server.mjs'),
|
||||||
|
]);
|
||||||
|
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
let sawShutdownDispose = false;
|
let sawShutdownDispose = false;
|
||||||
let stdinBuf = '';
|
let stdinBuf = '';
|
||||||
@@ -171,8 +166,8 @@ const invokedPath = process.argv[1] ? resolve(process.argv[1]) : '';
|
|||||||
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
if (invokedPath && invokedPath === fileURLToPath(import.meta.url)) {
|
||||||
const cliArgs = process.argv.slice(2);
|
const cliArgs = process.argv.slice(2);
|
||||||
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
if (cliArgs.includes('--standalone') || cliArgs.includes('--help') || cliArgs.includes('-h')) {
|
||||||
void runStandaloneCli(cliArgs);
|
void import('./standalone.mjs').then(({ runStandaloneCli }) => runStandaloneCli(cliArgs));
|
||||||
} else {
|
} else {
|
||||||
startBridgeDaemon();
|
void startBridgeDaemon();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,12 +23,12 @@ import {
|
|||||||
speedMetric,
|
speedMetric,
|
||||||
summarizeSpeed,
|
summarizeSpeed,
|
||||||
summarizeTtft,
|
summarizeTtft,
|
||||||
} from './speed-metrics.mjs';
|
} from './trajectory-metrics.mjs';
|
||||||
import {
|
import {
|
||||||
getNodeSqliteDatabaseSync,
|
|
||||||
readLocalSqliteTrajectory,
|
readLocalSqliteTrajectory,
|
||||||
readLocalSummaryIndex,
|
readLocalSummaryIndex,
|
||||||
} from './backend/cli-sqlite-reader.mjs';
|
} from './backend/cli-sqlite-reader.mjs';
|
||||||
|
import { withReadOnlySqliteDb } from './backend/sqlite-client.mjs';
|
||||||
import {
|
import {
|
||||||
ensureCliStatusLineConfigured,
|
ensureCliStatusLineConfigured,
|
||||||
formatCliStatusLineCapsule,
|
formatCliStatusLineCapsule,
|
||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
loadSettings,
|
loadSettings,
|
||||||
} from './backend/config.mjs';
|
} from './backend/config.mjs';
|
||||||
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
import { computeStepCost, createStepModelResolver } from './backend/model-pricing.mjs';
|
||||||
|
import { isThirdPartyPoolText } from './shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
const CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
const CLI_RUNNING_STALE_MS = 10 * 60 * 1000;
|
||||||
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
const SNAPSHOT_LIVE_RUNNING_TTL_MS = 20 * 1000;
|
||||||
@@ -145,43 +146,35 @@ function findConversationIdByWorkspaceFts(cliRoot, cwd) {
|
|||||||
if (!cwd) return '';
|
if (!cwd) return '';
|
||||||
const summariesDbPath = join(cliRoot, 'conversation_summaries.db');
|
const summariesDbPath = join(cliRoot, 'conversation_summaries.db');
|
||||||
if (!existsSync(summariesDbPath)) return '';
|
if (!existsSync(summariesDbPath)) return '';
|
||||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
|
||||||
if (!DatabaseSync) return '';
|
|
||||||
|
|
||||||
const normCwd = normalizePathForMatch(cwd);
|
const normCwd = normalizePathForMatch(cwd);
|
||||||
if (!normCwd) return '';
|
if (!normCwd) return '';
|
||||||
|
|
||||||
let db = null;
|
|
||||||
try {
|
try {
|
||||||
db = new DatabaseSync(summariesDbPath, { readOnly: true });
|
const matched = withReadOnlySqliteDb(summariesDbPath, (db) => {
|
||||||
const rows = db
|
const rows = db
|
||||||
.prepare(
|
.prepare(
|
||||||
`SELECT conversation_id, workspace, last_modified_time
|
`SELECT conversation_id, workspace, last_modified_time
|
||||||
FROM conversations_fts
|
FROM conversations_fts
|
||||||
WHERE chunk_index = -1
|
WHERE chunk_index = -1
|
||||||
ORDER BY last_modified_time DESC
|
ORDER BY last_modified_time DESC
|
||||||
LIMIT 40`
|
LIMIT 40`
|
||||||
)
|
)
|
||||||
.all();
|
.all();
|
||||||
for (const row of rows || []) {
|
for (const row of rows || []) {
|
||||||
const ws = normalizePathForMatch(row?.workspace);
|
const ws = normalizePathForMatch(row?.workspace);
|
||||||
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
const cid = String(row?.conversation_id || '').trim().toLowerCase();
|
||||||
if (cid && ws && ws === normCwd) {
|
if (cid && ws && ws === normCwd) {
|
||||||
return cid;
|
return cid;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
return '';
|
||||||
|
});
|
||||||
|
return matched || '';
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略不存在 conversations_fts 表或读取失败
|
// 忽略不存在 conversations_fts 表或读取失败
|
||||||
} finally {
|
return '';
|
||||||
if (db) {
|
|
||||||
try {
|
|
||||||
db.close();
|
|
||||||
} catch {
|
|
||||||
// 忽略关闭异常
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -394,7 +387,7 @@ function buildStdinFallbackQuotas(stdinData) {
|
|||||||
const frac = Number(bucket.remaining_fraction);
|
const frac = Number(bucket.remaining_fraction);
|
||||||
if (!Number.isFinite(frac)) continue;
|
if (!Number.isFinite(frac)) continue;
|
||||||
const remainingPct = Math.max(0, Math.min(100, Math.round(frac * 100)));
|
const remainingPct = Math.max(0, Math.min(100, Math.round(frac * 100)));
|
||||||
const isThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(key);
|
const isThirdParty = isThirdPartyPoolText(key);
|
||||||
pools.push({
|
pools.push({
|
||||||
poolKey: isThirdParty ? 'Claude & GPT' : 'Gemini',
|
poolKey: isThirdParty ? 'Claude & GPT' : 'Gemini',
|
||||||
poolLabel: key,
|
poolLabel: key,
|
||||||
@@ -404,7 +397,7 @@ function buildStdinFallbackQuotas(stdinData) {
|
|||||||
}
|
}
|
||||||
if (pools.length === 0) return null;
|
if (pools.length === 0) return null;
|
||||||
const modelStr = String(stdinData?.model?.id || stdinData?.model?.display_name || '');
|
const modelStr = String(stdinData?.model?.id || stdinData?.model?.display_name || '');
|
||||||
const activeIsThirdParty = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i.test(modelStr);
|
const activeIsThirdParty = isThirdPartyPoolText(modelStr);
|
||||||
const matchingPools = pools.filter((p) =>
|
const matchingPools = pools.filter((p) =>
|
||||||
activeIsThirdParty ? p.poolKey === 'Claude & GPT' : p.poolKey === 'Gemini'
|
activeIsThirdParty ? p.poolKey === 'Claude & GPT' : p.poolKey === 'Gemini'
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -4,11 +4,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<title>用量监控</title>
|
<title>用量监控</title>
|
||||||
<link rel="stylesheet" href="/styles.css?v=1794819376795">
|
<link rel="stylesheet" href="/styles.css?v=1795006728154">
|
||||||
<script src="/preload.js"></script>
|
<script src="/preload.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app-root"></div>
|
<div id="app-root"></div>
|
||||||
<script src="/app.js?v=1794819376795"></script>
|
<script src="/app.js?v=1795006728154"></script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
+35
-18
@@ -11,12 +11,8 @@
|
|||||||
|
|
||||||
import { Worker } from 'node:worker_threads';
|
import { Worker } from 'node:worker_threads';
|
||||||
import { Response, SidecarApp } from 'sidecar_sdk';
|
import { Response, SidecarApp } from 'sidecar_sdk';
|
||||||
import {
|
import { BRIDGE_API_ROUTE_DEFS } from './shared/window-bridge-protocol.mjs';
|
||||||
bootWindowBridgeRuntime,
|
import { isLocalHostRequest, readLocalAsync } from './backend/http-helpers.mjs';
|
||||||
dispatchBridgeApiRequest,
|
|
||||||
isLocalHostRequest,
|
|
||||||
readLocalAsync,
|
|
||||||
} from './backend/api-actions.mjs';
|
|
||||||
|
|
||||||
const app = new SidecarApp();
|
const app = new SidecarApp();
|
||||||
|
|
||||||
@@ -144,9 +140,20 @@ async function ensureActiveWorker() {
|
|||||||
return activeWorker;
|
return activeWorker;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let testHarnessApiModulePromise = null;
|
||||||
|
|
||||||
|
function getTestHarnessApiModule() {
|
||||||
|
testHarnessApiModulePromise ||= import('./backend/api-actions.mjs');
|
||||||
|
return testHarnessApiModulePromise;
|
||||||
|
}
|
||||||
|
|
||||||
async function forwardApiCall(pathname, method, data) {
|
async function forwardApiCall(pathname, method, data) {
|
||||||
if (isTestHarnessEnv) {
|
if (isTestHarnessEnv) {
|
||||||
return dispatchBridgeApiRequest(pathname, method, data);
|
if (typeof dispatchBridgeApiRequest === 'function') {
|
||||||
|
return dispatchBridgeApiRequest(pathname, method, data);
|
||||||
|
}
|
||||||
|
const mod = await getTestHarnessApiModule();
|
||||||
|
return mod.dispatchBridgeApiRequest(pathname, method, data);
|
||||||
}
|
}
|
||||||
const upperMethod = String(method || 'GET').toUpperCase();
|
const upperMethod = String(method || 'GET').toUpperCase();
|
||||||
try {
|
try {
|
||||||
@@ -208,22 +215,32 @@ app.page(
|
|||||||
);
|
);
|
||||||
|
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// 业务数据与控制 API 路由
|
// 业务数据与控制 API 路由(统一源自 shared/window-bridge-protocol.mjs)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
app.api('/api/telemetry', (data, req) => handleProtectedApi('/api/telemetry', 'GET', data, req), 'GET');
|
for (const route of BRIDGE_API_ROUTE_DEFS) {
|
||||||
app.api('/api/settings', (data, req) => handleProtectedApi('/api/settings', 'POST', data, req));
|
app.api(
|
||||||
app.api('/api/accounts', (_data, req) => handleProtectedApi('/api/accounts', 'GET', undefined, req), 'GET');
|
route.path,
|
||||||
app.api('/api/accounts/update', (data, req) => handleProtectedApi('/api/accounts/update', 'POST', data, req), 'POST');
|
(data, req) =>
|
||||||
app.api('/api/context-window', (data, req) => handleProtectedApi('/api/context-window', 'POST', data, req));
|
handleProtectedApi(
|
||||||
app.api('/api/settings/reset', (_data, req) => handleProtectedApi('/api/settings/reset', 'POST', undefined, req));
|
route.path,
|
||||||
app.api('/api/cache/rebuild', (_data, req) => handleProtectedApi('/api/cache/rebuild', 'POST', undefined, req));
|
route.method,
|
||||||
app.api('/api/cloud-sync', (_data, req) => handleProtectedApi('/api/cloud-sync', 'POST', undefined, req));
|
route.method === 'GET' && route.action !== 'telemetry' ? undefined : data,
|
||||||
app.api('/api/plugin-update', (_data, req) => handleProtectedApi('/api/plugin-update', 'POST', undefined, req));
|
req
|
||||||
|
),
|
||||||
|
route.method
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
app.run();
|
app.run();
|
||||||
if (isTestHarnessEnv) {
|
if (isTestHarnessEnv) {
|
||||||
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
if (typeof bootWindowBridgeRuntime === 'function') {
|
||||||
|
bootWindowBridgeRuntime({ allowDynamicLs: false });
|
||||||
|
} else {
|
||||||
|
void getTestHarnessApiModule().then((mod) =>
|
||||||
|
mod.bootWindowBridgeRuntime({ allowDynamicLs: false })
|
||||||
|
);
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
void ensureActiveWorker();
|
void ensureActiveWorker();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "usage-monitor-panel",
|
"name": "usage-monitor-panel",
|
||||||
"version": "1.5.0",
|
"version": "1.5.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
import { dirname, join, resolve } from 'node:path';
|
import { dirname, join, resolve } from 'node:path';
|
||||||
import { fileURLToPath } from 'node:url';
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { Script } from 'node:vm';
|
||||||
|
|
||||||
const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
const PANEL_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||||
|
|
||||||
@@ -93,18 +94,18 @@ function consumeTrailingStatementEnd(source, startIdx) {
|
|||||||
return idx;
|
return idx;
|
||||||
}
|
}
|
||||||
|
|
||||||
function scanImportDeclarationEnd(source, afterImportIdx) {
|
function scanImportDeclarationEnd(source, afterImportIdx, onImport) {
|
||||||
let idx = afterImportIdx;
|
let idx = afterImportIdx;
|
||||||
let braceDepth = 0;
|
let braceDepth = 0;
|
||||||
let sawModuleSpecifierString = false;
|
|
||||||
while (idx < source.length) {
|
while (idx < source.length) {
|
||||||
const ch = source[idx];
|
const ch = source[idx];
|
||||||
if (ch === "'" || ch === '"') {
|
if (ch === "'" || ch === '"') {
|
||||||
idx = skipSimpleString(source, idx);
|
const end = skipSimpleString(source, idx);
|
||||||
if (braceDepth === 0) {
|
if (braceDepth === 0) {
|
||||||
sawModuleSpecifierString = true;
|
onImport?.(source.slice(idx + 1, end - 1), source.slice(afterImportIdx, idx));
|
||||||
return consumeTrailingStatementEnd(source, idx);
|
return consumeTrailingStatementEnd(source, end);
|
||||||
}
|
}
|
||||||
|
idx = end;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if (ch === '/' && source[idx + 1] === '/') {
|
if (ch === '/' && source[idx + 1] === '/') {
|
||||||
@@ -122,17 +123,17 @@ function scanImportDeclarationEnd(source, afterImportIdx) {
|
|||||||
else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
|
else if (ch === '}') braceDepth = Math.max(0, braceDepth - 1);
|
||||||
else if (ch === ';' && braceDepth === 0) {
|
else if (ch === ';' && braceDepth === 0) {
|
||||||
return consumeTrailingStatementEnd(source, idx);
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
} else if (ch === '\n' && braceDepth === 0 && sawModuleSpecifierString) {
|
|
||||||
return idx + 1;
|
|
||||||
}
|
}
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
return source.length;
|
return source.length;
|
||||||
}
|
}
|
||||||
|
|
||||||
function scanExportClauseEnd(source, afterExportIdx) {
|
function scanExportClauseEnd(source, afterExportIdx, onImport, onExport) {
|
||||||
let idx = afterExportIdx;
|
let idx = afterExportIdx;
|
||||||
|
let braceBody = '';
|
||||||
if (source[idx] === '{') {
|
if (source[idx] === '{') {
|
||||||
|
const bodyStart = idx + 1;
|
||||||
let depth = 1;
|
let depth = 1;
|
||||||
idx += 1;
|
idx += 1;
|
||||||
while (idx < source.length && depth > 0) {
|
while (idx < source.length && depth > 0) {
|
||||||
@@ -156,6 +157,7 @@ function scanExportClauseEnd(source, afterExportIdx) {
|
|||||||
else if (ch === '}') depth -= 1;
|
else if (ch === '}') depth -= 1;
|
||||||
idx += 1;
|
idx += 1;
|
||||||
}
|
}
|
||||||
|
braceBody = source.slice(bodyStart, Math.max(bodyStart, idx - 1));
|
||||||
} else if (source[idx] === '*') {
|
} else if (source[idx] === '*') {
|
||||||
idx += 1;
|
idx += 1;
|
||||||
idx = skipSpacesAndComments(source, idx);
|
idx = skipSpacesAndComments(source, idx);
|
||||||
@@ -169,21 +171,57 @@ function scanExportClauseEnd(source, afterExportIdx) {
|
|||||||
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
if (source.startsWith('from', peekFrom) && !isIdentPart(source[peekFrom + 4])) {
|
||||||
const specIdx = skipSpacesAndComments(source, peekFrom + 4);
|
const specIdx = skipSpacesAndComments(source, peekFrom + 4);
|
||||||
if (source[specIdx] === "'" || source[specIdx] === '"') {
|
if (source[specIdx] === "'" || source[specIdx] === '"') {
|
||||||
idx = skipSimpleString(source, specIdx);
|
const specEnd = skipSimpleString(source, specIdx);
|
||||||
|
const specifier = source.slice(specIdx + 1, specEnd - 1);
|
||||||
|
onImport?.(specifier, braceBody ? `{ ${braceBody} } from` : '');
|
||||||
|
idx = specEnd;
|
||||||
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (braceBody && onExport) {
|
||||||
|
const cleaned = braceBody.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ');
|
||||||
|
for (const part of cleaned.split(',')) {
|
||||||
|
const tok = part.trim();
|
||||||
|
if (!tok) continue;
|
||||||
|
const asMatch = /^([$_\w]+)\s+as\s+([$_\w]+)$/.exec(tok);
|
||||||
|
onExport(asMatch ? asMatch[2] : tok, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return consumeTrailingStatementEnd(source, idx);
|
return consumeTrailingStatementEnd(source, idx);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function recordExportedDeclarationIdent(source, declKeywordIdx, onExport) {
|
||||||
|
if (!onExport) return;
|
||||||
|
let pos = declKeywordIdx;
|
||||||
|
if (source.startsWith('async', pos) && !isIdentPart(source[pos + 5])) {
|
||||||
|
pos = skipSpacesAndComments(source, pos + 5);
|
||||||
|
}
|
||||||
|
for (const kw of ['const', 'let', 'var', 'function', 'class']) {
|
||||||
|
if (source.startsWith(kw, pos) && !isIdentPart(source[pos + kw.length])) {
|
||||||
|
pos = skipSpacesAndComments(source, pos + kw.length);
|
||||||
|
if (source[pos] === '*') pos = skipSpacesAndComments(source, pos + 1);
|
||||||
|
if (isIdentStart(source[pos])) {
|
||||||
|
let end = pos + 1;
|
||||||
|
while (end < source.length && isIdentPart(source[end])) end += 1;
|
||||||
|
onExport(source.slice(pos, end), false);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lexical ES module syntax stripper that skips comments, single/double-quoted
|
* Lexical ES module syntax stripper that skips comments, single/double-quoted
|
||||||
* strings, template literals (including nested `${...}` expressions), and regex
|
* strings, template literals (including nested `${...}` expressions), and regex
|
||||||
* literals, removing only true top-level `import` / `export` syntax.
|
* literals, removing only true top-level `import` / `export` syntax.
|
||||||
*
|
*
|
||||||
* @param {string} source
|
* @param {string} source
|
||||||
|
* @param {(specifier: string, clause: string) => void} [onImport]
|
||||||
|
* @param {(name: string, isClauseExport: boolean) => void} [onExport]
|
||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
export function stripModuleSyntax(source) {
|
export function stripModuleSyntax(source, onImport, onExport) {
|
||||||
const len = source.length;
|
const len = source.length;
|
||||||
let out = '';
|
let out = '';
|
||||||
let i = 0;
|
let i = 0;
|
||||||
@@ -356,7 +394,7 @@ export function stripModuleSyntax(source) {
|
|||||||
const nextCh = source[afterImport];
|
const nextCh = source[afterImport];
|
||||||
// Exclude `import.meta` and dynamic `import(...)`
|
// Exclude `import.meta` and dynamic `import(...)`
|
||||||
if (nextCh && nextCh !== '.' && nextCh !== '(') {
|
if (nextCh && nextCh !== '.' && nextCh !== '(') {
|
||||||
i = scanImportDeclarationEnd(source, afterImport);
|
i = scanImportDeclarationEnd(source, afterImport, onImport);
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ';';
|
prevNonWsChar = ';';
|
||||||
continue;
|
continue;
|
||||||
@@ -367,7 +405,7 @@ export function stripModuleSyntax(source) {
|
|||||||
const afterExport = skipSpacesAndComments(source, end);
|
const afterExport = skipSpacesAndComments(source, end);
|
||||||
const nextCh = source[afterExport];
|
const nextCh = source[afterExport];
|
||||||
if (nextCh === '{' || nextCh === '*') {
|
if (nextCh === '{' || nextCh === '*') {
|
||||||
i = scanExportClauseEnd(source, afterExport);
|
i = scanExportClauseEnd(source, afterExport, onImport, onExport);
|
||||||
canStartRegex = true;
|
canStartRegex = true;
|
||||||
prevNonWsChar = ';';
|
prevNonWsChar = ';';
|
||||||
continue;
|
continue;
|
||||||
@@ -380,6 +418,7 @@ export function stripModuleSyntax(source) {
|
|||||||
(source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) ||
|
(source.startsWith('class', afterDefault) && !isIdentPart(source[afterDefault + 5])) ||
|
||||||
(source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5]));
|
(source.startsWith('async', afterDefault) && !isIdentPart(source[afterDefault + 5]));
|
||||||
if (isDecl) {
|
if (isDecl) {
|
||||||
|
recordExportedDeclarationIdent(source, afterDefault, onExport);
|
||||||
i = afterDefault;
|
i = afterDefault;
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
continue;
|
continue;
|
||||||
@@ -399,6 +438,7 @@ export function stripModuleSyntax(source) {
|
|||||||
(source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) ||
|
(source.startsWith('class', afterExport) && !isIdentPart(source[afterExport + 5])) ||
|
||||||
(source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5]))
|
(source.startsWith('async', afterExport) && !isIdentPart(source[afterExport + 5]))
|
||||||
) {
|
) {
|
||||||
|
recordExportedDeclarationIdent(source, afterExport, onExport);
|
||||||
i = afterExport;
|
i = afterExport;
|
||||||
canStartRegex = false;
|
canStartRegex = false;
|
||||||
continue;
|
continue;
|
||||||
@@ -428,7 +468,32 @@ export function stripModuleSyntax(source) {
|
|||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function buildBundle() {
|
function validateBundleImport(sourcePath, specifier, clause, bundledPaths, moduleImportedNames) {
|
||||||
|
const binding = clause.replace(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*/g, ' ').trim();
|
||||||
|
if (binding) {
|
||||||
|
const named = /^\{([^}]*)\}\s*from$/.exec(binding);
|
||||||
|
const identifier = /^[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
|
||||||
|
if (!named) {
|
||||||
|
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
||||||
|
}
|
||||||
|
for (const rawItem of named[1].split(',')) {
|
||||||
|
const name = rawItem.trim();
|
||||||
|
if (!name) continue;
|
||||||
|
if (!identifier.test(name)) {
|
||||||
|
throw new Error(`${sourcePath}: only named imports without aliases are supported in app.js`);
|
||||||
|
}
|
||||||
|
moduleImportedNames?.add(name);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!(specifier.startsWith('./') || specifier.startsWith('../')) ||
|
||||||
|
!bundledPaths.has(resolve(dirname(sourcePath), specifier))
|
||||||
|
) {
|
||||||
|
throw new Error(`${sourcePath}: ${specifier} must appear earlier in jsOrder`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildBundle(panelDir = PANEL_DIR) {
|
||||||
const cssOrder = [
|
const cssOrder = [
|
||||||
'src/styles/tokens.css',
|
'src/styles/tokens.css',
|
||||||
'src/styles/base.css',
|
'src/styles/base.css',
|
||||||
@@ -443,12 +508,16 @@ export function buildBundle() {
|
|||||||
|
|
||||||
const cssBundle =
|
const cssBundle =
|
||||||
cssOrder
|
cssOrder
|
||||||
.map((rel) => `/* --- ${rel} --- */\n${readFileSync(join(PANEL_DIR, rel), 'utf8').trim()}`)
|
.map(
|
||||||
|
(rel) =>
|
||||||
|
`/* --- ${rel} --- */\n${readFileSync(join(panelDir, rel), 'utf8').replace(/\r\n/g, '\n').trim()}`
|
||||||
|
)
|
||||||
.join('\n\n') + '\n';
|
.join('\n\n') + '\n';
|
||||||
|
|
||||||
writeFileSync(join(PANEL_DIR, 'styles.css'), cssBundle, 'utf8');
|
|
||||||
|
|
||||||
const jsOrder = [
|
const jsOrder = [
|
||||||
|
'shared/settings-normalization.mjs',
|
||||||
|
'shared/telemetry-display-rules.mjs',
|
||||||
|
'shared/window-bridge-protocol.mjs',
|
||||||
'src/icons/svgRegistry.js',
|
'src/icons/svgRegistry.js',
|
||||||
'src/icons/SvgIcon.js',
|
'src/icons/SvgIcon.js',
|
||||||
'src/core/reactive.js',
|
'src/core/reactive.js',
|
||||||
@@ -485,9 +554,9 @@ export function buildBundle() {
|
|||||||
'src/components/settings/CollapsibleSection.js',
|
'src/components/settings/CollapsibleSection.js',
|
||||||
'src/components/settings/EditableSlotList.js',
|
'src/components/settings/EditableSlotList.js',
|
||||||
'src/components/settings/ThemeColorPicker.js',
|
'src/components/settings/ThemeColorPicker.js',
|
||||||
|
'src/components/settings/BridgeStatusNotice.js',
|
||||||
'src/views/settings/SettingsGeneralTab.js',
|
'src/views/settings/SettingsGeneralTab.js',
|
||||||
'src/views/settings/SettingsStructureTab.js',
|
'src/views/settings/SettingsStructureTab.js',
|
||||||
'src/views/settings/SettingsAccountTab.js',
|
|
||||||
'src/views/settings/SettingsOtherTab.js',
|
'src/views/settings/SettingsOtherTab.js',
|
||||||
'src/components/layout/TopSessionHeader.js',
|
'src/components/layout/TopSessionHeader.js',
|
||||||
'src/views/LiveOverviewView.js',
|
'src/views/LiveOverviewView.js',
|
||||||
@@ -499,24 +568,55 @@ export function buildBundle() {
|
|||||||
'src/main.js',
|
'src/main.js',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const bundledPaths = new Set();
|
||||||
|
const outerExportedSymbols = new Set();
|
||||||
const innerModules = jsOrder
|
const innerModules = jsOrder
|
||||||
.map((rel) => {
|
.map((rel) => {
|
||||||
const raw = readFileSync(join(PANEL_DIR, rel), 'utf8');
|
const path = resolve(panelDir, rel);
|
||||||
const stripped = stripModuleSyntax(raw);
|
if (bundledPaths.has(path)) throw new Error(`${rel}: duplicate entry in jsOrder`);
|
||||||
return `// --- ${rel} ---\n${stripped.trim()}`;
|
const raw = readFileSync(path, 'utf8').replace(/\r\n/g, '\n');
|
||||||
|
const moduleImportedNames = new Set();
|
||||||
|
const moduleLocalExports = new Set();
|
||||||
|
const stripped = stripModuleSyntax(
|
||||||
|
raw,
|
||||||
|
(specifier, clause) =>
|
||||||
|
validateBundleImport(path, specifier, clause, bundledPaths, moduleImportedNames),
|
||||||
|
(name, isClauseExport) => {
|
||||||
|
if (isClauseExport && moduleImportedNames.has(name) && outerExportedSymbols.has(name)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
moduleLocalExports.add(name);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
bundledPaths.add(path);
|
||||||
|
const exportList = [...moduleLocalExports];
|
||||||
|
for (const sym of exportList) {
|
||||||
|
outerExportedSymbols.add(sym);
|
||||||
|
}
|
||||||
|
const body = stripped.trim();
|
||||||
|
const wrapped =
|
||||||
|
exportList.length > 0
|
||||||
|
? `const { ${exportList.join(', ')} } = (() => {\n${body}\nreturn { ${exportList.join(', ')} };\n})();`
|
||||||
|
: `(() => {\n${body}\n})();`;
|
||||||
|
return `// --- ${rel} ---\n${wrapped}`;
|
||||||
})
|
})
|
||||||
.join('\n\n');
|
.join('\n\n');
|
||||||
|
|
||||||
const jsBundle = `(() => {\n'use strict';\n\n${innerModules}\n})();\n`;
|
const jsBundle = `(() => {\n'use strict';\n\n${innerModules}\n})();\n`;
|
||||||
|
new Script(jsBundle, { filename: 'app.js' });
|
||||||
writeFileSync(join(PANEL_DIR, 'app.js'), jsBundle, 'utf8');
|
|
||||||
|
|
||||||
const ver = Date.now();
|
const ver = Date.now();
|
||||||
const indexHtmlPath = join(PANEL_DIR, 'index.html');
|
const indexHtmlPath = join(panelDir, 'index.html');
|
||||||
if (existsSync(indexHtmlPath)) {
|
const html = existsSync(indexHtmlPath)
|
||||||
const html = readFileSync(indexHtmlPath, 'utf8')
|
? readFileSync(indexHtmlPath, 'utf8')
|
||||||
|
.replace(/\r\n/g, '\n')
|
||||||
.replace(/href="\/styles\.css(?:\?v=[^"]*)?"/, `href="/styles.css?v=${ver}"`)
|
.replace(/href="\/styles\.css(?:\?v=[^"]*)?"/, `href="/styles.css?v=${ver}"`)
|
||||||
.replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`);
|
.replace(/src="\/app\.js(?:\?v=[^"]*)?"/, `src="/app.js?v=${ver}"`)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
writeFileSync(join(panelDir, 'styles.css'), cssBundle, 'utf8');
|
||||||
|
writeFileSync(join(panelDir, 'app.js'), jsBundle, 'utf8');
|
||||||
|
if (html !== null) {
|
||||||
writeFileSync(indexHtmlPath, html, 'utf8');
|
writeFileSync(indexHtmlPath, html, 'utf8');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,448 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 前后端与 CLI 共用的偏好设置枚举常量、默认值与无状态纯函数归一化规则。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const SUPPORTED_LANGUAGES = Object.freeze(['auto', 'zh-CN', 'en-US']);
|
||||||
|
|
||||||
|
export const THEME_ACCENT_KEYS = Object.freeze([
|
||||||
|
'host',
|
||||||
|
'blue',
|
||||||
|
'emerald',
|
||||||
|
'amber',
|
||||||
|
'violet',
|
||||||
|
'cyan',
|
||||||
|
'rose',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const FONT_SCALE_KEYS = Object.freeze(['sm', 'md', 'lg', 'xl']);
|
||||||
|
|
||||||
|
export const TOPBAR_SLOT_KEYS = Object.freeze([
|
||||||
|
'context',
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'avg_tps',
|
||||||
|
'cost',
|
||||||
|
'session_cost',
|
||||||
|
'cache_hit',
|
||||||
|
'session_tokens',
|
||||||
|
'quota_auto',
|
||||||
|
'gemini_5h',
|
||||||
|
'gemini_weekly',
|
||||||
|
'claude_5h',
|
||||||
|
'claude_weekly',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
||||||
|
export const MIN_TOPBAR_SLOTS = 1;
|
||||||
|
export const MAX_TOPBAR_SLOTS = 5;
|
||||||
|
|
||||||
|
export const OVERVIEW_MODULE_KEYS = Object.freeze([
|
||||||
|
'metrics',
|
||||||
|
'context',
|
||||||
|
'quotas',
|
||||||
|
'live_tasks',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_OVERVIEW_MODULES = Object.freeze([
|
||||||
|
'metrics',
|
||||||
|
'context',
|
||||||
|
'quotas',
|
||||||
|
'live_tasks',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
||||||
|
|
||||||
|
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'avg_tps',
|
||||||
|
'step_cost',
|
||||||
|
'session_cost',
|
||||||
|
'cache_hit',
|
||||||
|
'session_tokens',
|
||||||
|
'context_usage',
|
||||||
|
'quota_tightest',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_OVERVIEW_METRICS = Object.freeze([
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'avg_tps',
|
||||||
|
'step_cost',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const STEP_TABLE_COLUMN_KEYS = Object.freeze([
|
||||||
|
'step',
|
||||||
|
'time',
|
||||||
|
'model',
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'duration',
|
||||||
|
'tokens_combo',
|
||||||
|
'tokens_io_cache',
|
||||||
|
'tokens_custom',
|
||||||
|
'input_tokens',
|
||||||
|
'cache_tokens',
|
||||||
|
'output_tokens',
|
||||||
|
'cache',
|
||||||
|
'cost',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_STEP_TABLE_COLUMNS = Object.freeze([
|
||||||
|
'step',
|
||||||
|
'model',
|
||||||
|
'tps',
|
||||||
|
'ttft',
|
||||||
|
'tokens_combo',
|
||||||
|
'cache',
|
||||||
|
'cost',
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const DEFAULT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
||||||
|
|
||||||
|
export const STEP_TOKEN_SEGMENT_ALIASES = Object.freeze({
|
||||||
|
context: 'context',
|
||||||
|
ctx: 'context',
|
||||||
|
'上下文': 'context',
|
||||||
|
in: 'in',
|
||||||
|
new: 'in',
|
||||||
|
input: 'in',
|
||||||
|
'输入': 'in',
|
||||||
|
'新输入': 'in',
|
||||||
|
out: 'out',
|
||||||
|
output: 'out',
|
||||||
|
'输出': 'out',
|
||||||
|
'总输出': 'out',
|
||||||
|
cache: 'cache',
|
||||||
|
cached: 'cache',
|
||||||
|
cache_read: 'cache',
|
||||||
|
cacheread: 'cache',
|
||||||
|
'缓存': 'cache',
|
||||||
|
'缓存读': 'cache',
|
||||||
|
think: 'think',
|
||||||
|
thinking: 'think',
|
||||||
|
'思考': 'think',
|
||||||
|
reply: 'reply',
|
||||||
|
body: 'reply',
|
||||||
|
resp: 'reply',
|
||||||
|
response: 'reply',
|
||||||
|
text: 'reply',
|
||||||
|
'正文': 'reply',
|
||||||
|
'回复': 'reply',
|
||||||
|
total: 'total',
|
||||||
|
all: 'total',
|
||||||
|
sum: 'total',
|
||||||
|
'总计': 'total',
|
||||||
|
'总token': 'total',
|
||||||
|
});
|
||||||
|
|
||||||
|
export const POPOVER_WIDTH_MODES = Object.freeze(['auto', 'custom']);
|
||||||
|
export const MIN_POPOVER_WIDTH = 440;
|
||||||
|
export const MAX_POPOVER_WIDTH = 1080;
|
||||||
|
export const DEFAULT_POPOVER_WIDTH = 580;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化界面语言枚举(默认 `'zh-CN'`,支持 `'auto'`/`'system'` 与 `'en-US'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} lang
|
||||||
|
* @returns {'auto'|'zh-CN'|'en-US'}
|
||||||
|
*/
|
||||||
|
export function normalizeLanguageSetting(lang) {
|
||||||
|
const raw = String(lang ?? '').trim();
|
||||||
|
if (!raw) return 'zh-CN';
|
||||||
|
const lower = raw.toLowerCase();
|
||||||
|
if (lower === 'auto' || lower === 'system') return 'auto';
|
||||||
|
if (lower === 'en' || lower === 'en-us' || lower.startsWith('en-')) return 'en-US';
|
||||||
|
if (lower === 'zh' || lower === 'zh-cn' || lower.startsWith('zh')) return 'zh-CN';
|
||||||
|
return 'zh-CN';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化主题强调色预设键(默认 `'host'` 跟随宿主原生主题)。
|
||||||
|
*
|
||||||
|
* @param {unknown} accent
|
||||||
|
* @returns {'host'|'blue'|'emerald'|'amber'|'violet'|'cyan'|'rose'}
|
||||||
|
*/
|
||||||
|
export function normalizeThemeAccent(accent) {
|
||||||
|
const clean = String(accent ?? '').trim().toLowerCase();
|
||||||
|
return THEME_ACCENT_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'host';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化面板字号档位(默认 `'md'` 标准 100%)。
|
||||||
|
*
|
||||||
|
* @param {unknown} scale
|
||||||
|
* @returns {'sm'|'md'|'lg'|'xl'}
|
||||||
|
*/
|
||||||
|
export function normalizeFontScale(scale) {
|
||||||
|
const clean = String(scale ?? '').trim().toLowerCase();
|
||||||
|
return FONT_SCALE_KEYS.includes(clean) ? /** @type {any} */ (clean) : 'md';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化模型名称展示模式(`'short'` | `'upstream_compact'` | `'upstream'`),兼容历史 `showUpstreamModel`。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @param {unknown} [legacyShowUpstream]
|
||||||
|
* @returns {'short'|'upstream_compact'|'upstream'}
|
||||||
|
*/
|
||||||
|
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
||||||
|
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
||||||
|
return 'upstream_compact';
|
||||||
|
}
|
||||||
|
if (m === 'short') return 'short';
|
||||||
|
if (legacyShowUpstream === true) return 'upstream';
|
||||||
|
return 'short';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化 Orchestrator 系列模型 ID 显示风格(`'compact'` vs `'full'`,默认 `'compact'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'compact'|'full'}
|
||||||
|
*/
|
||||||
|
export function normalizeOrchestratorIdMode(mode) {
|
||||||
|
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化悬浮主面板宽度模式(`'auto'` | `'custom'`,默认 `'auto'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'auto'|'custom'}
|
||||||
|
*/
|
||||||
|
export function normalizePopoverWidthMode(mode) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化悬浮主面板自定义宽度像素值(范围 `440..1080`,默认 `580`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} width
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
export function normalizePopoverWidth(width) {
|
||||||
|
const num = Number(width);
|
||||||
|
if (!Number.isFinite(num) || num <= 0) return DEFAULT_POPOVER_WIDTH;
|
||||||
|
return Math.max(MIN_POPOVER_WIDTH, Math.min(MAX_POPOVER_WIDTH, Math.round(num)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析步骤表自定义 Token 组合表达式,支持 `:`、`/`、`,`、`|` 分隔与中英文别名(1~4 项不重复)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {Array<'context'|'in'|'out'|'cache'|'think'|'reply'|'total'>}
|
||||||
|
*/
|
||||||
|
export function parseStepTokenComboSegments(raw) {
|
||||||
|
const str = String(raw ?? '').trim();
|
||||||
|
const out = [];
|
||||||
|
const seen = new Set();
|
||||||
|
if (str) {
|
||||||
|
for (const part of str.split(/[:/,|]+/)) {
|
||||||
|
const key = part.trim().toLowerCase();
|
||||||
|
if (!key) continue;
|
||||||
|
const mapped = Object.prototype.hasOwnProperty.call(STEP_TOKEN_SEGMENT_ALIASES, key)
|
||||||
|
? STEP_TOKEN_SEGMENT_ALIASES[key]
|
||||||
|
: null;
|
||||||
|
if (!mapped || seen.has(mapped)) continue;
|
||||||
|
seen.add(mapped);
|
||||||
|
out.push(/** @type {any} */ (mapped));
|
||||||
|
if (out.length >= 4) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化步骤表自定义 Token 组合格式字符串(如 `'context:new:cache'` -> `'context:in:cache'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function normalizeStepTokenComboFormat(raw) {
|
||||||
|
return parseStepTokenComboSegments(raw).join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化插件更新策略枚举(兼容历史 `autoUpdatePlugin` 布尔开关,默认 `'manual'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @param {unknown} [legacyAutoUpdate]
|
||||||
|
* @returns {'off'|'manual'|'auto'}
|
||||||
|
*/
|
||||||
|
export function normalizePluginUpdateMode(mode, legacyAutoUpdate) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
||||||
|
if (legacyAutoUpdate === true) return 'auto';
|
||||||
|
return 'manual';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化面板挂载方式枚举(`'dual'` | `'composer'` | `'sidebar'`),兼容历史 `enableWindowOverlay`。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @param {unknown} [legacyEnableOverlay]
|
||||||
|
* @returns {'dual'|'composer'|'sidebar'}
|
||||||
|
*/
|
||||||
|
export function normalizeWindowMountMode(mode, legacyEnableOverlay) {
|
||||||
|
const m = String(mode ?? '').trim().toLowerCase();
|
||||||
|
if (m === 'composer' || m === 'input') return 'composer';
|
||||||
|
if (m === 'sidebar' || m === 'sidebar_only' || m === 'off') return 'sidebar';
|
||||||
|
if (m === 'dual' || m === 'topbar') return 'dual';
|
||||||
|
if (legacyEnableOverlay === false) return 'sidebar';
|
||||||
|
return 'dual';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化每周额度统计模式枚举(`'official'` | `'custom_tokens'` | `'custom_cost'`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} mode
|
||||||
|
* @returns {'official'|'custom_tokens'|'custom_cost'}
|
||||||
|
*/
|
||||||
|
export function normalizeWeeklyLimitMode(mode) {
|
||||||
|
const m = String(mode || '').trim().toLowerCase();
|
||||||
|
if (m === 'custom_tokens' || m === 'tokens') return 'custom_tokens';
|
||||||
|
if (m === 'custom_cost' || m === 'cost') return 'custom_cost';
|
||||||
|
return 'official';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化顶栏/输入框胶囊槽位数组(1~5 项动态自添加,默认 3 项,自动清洗历史 `'none'` 与重复项)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function normalizeTopbarCapsuleSlots(raw) {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return [...DEFAULT_TOPBAR_SLOTS];
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
const val = String(item ?? '').trim();
|
||||||
|
if (!val || val === 'none') continue;
|
||||||
|
const mapped = val === 'step_cost' ? 'cost' : val;
|
||||||
|
if (!TOPBAR_SLOT_KEYS.includes(mapped) || seen.has(mapped)) continue;
|
||||||
|
seen.add(mapped);
|
||||||
|
out.push(mapped);
|
||||||
|
if (out.length >= MAX_TOPBAR_SLOTS) break;
|
||||||
|
}
|
||||||
|
if (out.length < MIN_TOPBAR_SLOTS) {
|
||||||
|
return ['context'];
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化实时监控第一行指标矩阵的槽位与顺序(1~4 项,默认 4 项)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function normalizeOverviewMetrics(raw) {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return [...DEFAULT_OVERVIEW_METRICS];
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
const rawVal = String(item ?? '').trim();
|
||||||
|
const val = rawVal === 'cost' ? 'step_cost' : rawVal;
|
||||||
|
if (!OVERVIEW_METRIC_KEYS.includes(val) || seen.has(val)) continue;
|
||||||
|
seen.add(val);
|
||||||
|
out.push(val);
|
||||||
|
if (out.length >= 4) break;
|
||||||
|
}
|
||||||
|
return out.length > 0 ? out : ['tps'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化实时监控视图展示的模块及上下顺序(1~4 项,默认 4 项全开)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function normalizeOverviewModules(raw) {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return [...DEFAULT_OVERVIEW_MODULES];
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
const val = String(item ?? '').trim();
|
||||||
|
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||||
|
seen.add(val);
|
||||||
|
out.push(val);
|
||||||
|
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||||
|
}
|
||||||
|
return out.length > 0 ? out : ['metrics'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化鼠标悬停速览窗展示的模块及上下顺序(0~4 项,默认 3 项;显式空数组 `[]` 表示禁用悬停弹窗)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function normalizeHoverModules(raw) {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return [...DEFAULT_HOVER_MODULES];
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
const val = String(item ?? '').trim();
|
||||||
|
if (!OVERVIEW_MODULE_KEYS.includes(val) || seen.has(val)) continue;
|
||||||
|
seen.add(val);
|
||||||
|
out.push(val);
|
||||||
|
if (out.length >= OVERVIEW_MODULE_KEYS.length) break;
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化调用明细「按步查看」表格列配置与左右顺序(2~14 列,默认保留现有 7 列)。
|
||||||
|
*
|
||||||
|
* @param {unknown} raw
|
||||||
|
* @returns {string[]}
|
||||||
|
*/
|
||||||
|
export function normalizeStepTableColumns(raw) {
|
||||||
|
if (!Array.isArray(raw)) {
|
||||||
|
return [...DEFAULT_STEP_TABLE_COLUMNS];
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
const out = [];
|
||||||
|
for (const item of raw) {
|
||||||
|
const val = String(item ?? '').trim();
|
||||||
|
if (!STEP_TABLE_COLUMN_KEYS.includes(val) || seen.has(val)) continue;
|
||||||
|
seen.add(val);
|
||||||
|
out.push(val);
|
||||||
|
if (out.length >= STEP_TABLE_COLUMN_KEYS.length) break;
|
||||||
|
}
|
||||||
|
if (out.length < 2) {
|
||||||
|
for (const fallbackCol of ['step', 'model', 'tps']) {
|
||||||
|
if (!seen.has(fallbackCol)) {
|
||||||
|
seen.add(fallbackCol);
|
||||||
|
out.push(fallbackCol);
|
||||||
|
}
|
||||||
|
if (out.length >= 2) break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 归一化独立 Web 服务自动托管端口(`0` 表示关闭自动拉起,合法监听端口范围 `1024..65535`)。
|
||||||
|
*
|
||||||
|
* @param {unknown} port
|
||||||
|
* @returns {number}
|
||||||
|
*/
|
||||||
|
export function normalizeStandalonePort(port) {
|
||||||
|
const num = Number(port);
|
||||||
|
if (!Number.isInteger(num) || num <= 0) return 0;
|
||||||
|
if (num >= 1024 && num <= 65535) return num;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview 跨 Backend / Frontend / CLI 共用的纯展示阈值、紧凑格式化、第三方配额分池与精确整数缩放规则。
|
||||||
|
*/
|
||||||
|
|
||||||
|
export const THIRD_PARTY_POOL_RE =
|
||||||
|
/3p|claude|anthropic|fable|gpt|openai|oss|sonnet|opus|haiku|third[-_\s]?party/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断模型或配额桶文本是否归属第三方模型池(Claude & GPT / OSS / 3P)。
|
||||||
|
*
|
||||||
|
* @param {unknown} text
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isThirdPartyPoolText(text) {
|
||||||
|
return THIRD_PARTY_POOL_RE.test(String(text || ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 输出速度四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifySpeedTier(tokPerSec) {
|
||||||
|
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
const v = Number(tokPerSec);
|
||||||
|
if (v >= 60) return 'good';
|
||||||
|
if (v >= 35) return 'info';
|
||||||
|
if (v >= 20) return 'warn';
|
||||||
|
return 'danger';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缓存命中率四档语义色阶分类(`'muted'|'good'|'info'|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifyCacheTier(cacheHitPct, promptTokens = null) {
|
||||||
|
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
const v = Number(cacheHitPct);
|
||||||
|
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
if (v >= 85) return 'good';
|
||||||
|
if (v >= 65) return 'info';
|
||||||
|
if (v >= 30) return 'warn';
|
||||||
|
return 'danger';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 单步费用告警色阶分类(`''|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifyStepCostTier(costUsd) {
|
||||||
|
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '';
|
||||||
|
const v = Number(costUsd);
|
||||||
|
if (v >= 0.3) return 'danger';
|
||||||
|
if (v >= 0.15) return 'warn';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 首字延迟告警色阶分类(`'muted'|''|'warn'|'danger'`)。
|
||||||
|
*/
|
||||||
|
export function classifyTtftTier(ttftSec) {
|
||||||
|
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) {
|
||||||
|
return 'muted';
|
||||||
|
}
|
||||||
|
const v = Number(ttftSec);
|
||||||
|
if (v >= 30) return 'danger';
|
||||||
|
if (v >= 18) return 'warn';
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompactTokens(num) {
|
||||||
|
const n = Number(num || 0);
|
||||||
|
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
||||||
|
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
||||||
|
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
||||||
|
return String(Math.round(n));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompactCapsuleCost(costUsd) {
|
||||||
|
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
||||||
|
const val = Math.max(0, Number(costUsd));
|
||||||
|
if (val === 0) return '$0.00';
|
||||||
|
if (val < 0.001) return '<$0.001';
|
||||||
|
if (val < 1) return `$${val.toFixed(3)}`;
|
||||||
|
if (val < 100) return `$${val.toFixed(2)}`;
|
||||||
|
return `$${Math.round(val)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompactCapsuleTtft(ttftSec) {
|
||||||
|
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
||||||
|
const val = Number(ttftSec);
|
||||||
|
if (val < 1) return `${val.toFixed(2)}s`;
|
||||||
|
if (val < 100) return `${val.toFixed(1)}s`;
|
||||||
|
return `${Math.round(val)}s`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析胶囊指定配额槽位(`quota_auto` / `gemini_5h` / `gemini_weekly` / `claude_5h` / `claude_weekly`)的整数剩余百分比。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} quotas
|
||||||
|
* @param {string} slotKey
|
||||||
|
* @returns {number|null}
|
||||||
|
*/
|
||||||
|
export function resolveCapsuleQuotaSlotPct(quotas, slotKey) {
|
||||||
|
if (!quotas || typeof quotas !== 'object') return null;
|
||||||
|
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
||||||
|
const activePool = quotas.activePool || null;
|
||||||
|
const weekly = quotas.weekly || null;
|
||||||
|
|
||||||
|
if (slotKey === 'quota_auto') {
|
||||||
|
const candidates = [];
|
||||||
|
if (activePool && Number.isFinite(Number(activePool.remainingPct))) {
|
||||||
|
candidates.push(Number(activePool.remainingPct));
|
||||||
|
}
|
||||||
|
if (activePool && Number.isFinite(Number(activePool.weeklyRemainingPct))) {
|
||||||
|
candidates.push(Number(activePool.weeklyRemainingPct));
|
||||||
|
}
|
||||||
|
if (!candidates.length && weekly && Number.isFinite(Number(weekly.remainingPct))) {
|
||||||
|
candidates.push(Number(weekly.remainingPct));
|
||||||
|
}
|
||||||
|
if (!candidates.length && pools.length > 0) {
|
||||||
|
for (const p of pools) {
|
||||||
|
if (p && Number.isFinite(Number(p.remainingPct))) candidates.push(Number(p.remainingPct));
|
||||||
|
if (p && Number.isFinite(Number(p.weeklyRemainingPct))) {
|
||||||
|
candidates.push(Number(p.weeklyRemainingPct));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!candidates.length) return null;
|
||||||
|
return Math.max(0, Math.min(100, Math.round(Math.min(...candidates))));
|
||||||
|
}
|
||||||
|
|
||||||
|
const isClaude = slotKey.startsWith('claude_');
|
||||||
|
const isWeekly = slotKey.endsWith('_weekly');
|
||||||
|
let rawPct = null;
|
||||||
|
|
||||||
|
if (isClaude) {
|
||||||
|
const claudePool =
|
||||||
|
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
||||||
|
pools.find((p) => isThirdPartyPoolText(p?.poolKey || p?.poolLabel || ''));
|
||||||
|
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
||||||
|
if (cand != null && Number.isFinite(Number(cand))) {
|
||||||
|
rawPct = Number(cand);
|
||||||
|
} else if (activePool && isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')) {
|
||||||
|
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||||
|
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const stdGemini =
|
||||||
|
pools.find((p) => p?.poolKey === 'Gemini') ||
|
||||||
|
pools.find(
|
||||||
|
(p) =>
|
||||||
|
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
||||||
|
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
||||||
|
);
|
||||||
|
const geminiFamilyPools = pools.filter((p) =>
|
||||||
|
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
||||||
|
);
|
||||||
|
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
||||||
|
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
||||||
|
rawPct = Number(primaryCand);
|
||||||
|
} else {
|
||||||
|
const familyVals = geminiFamilyPools
|
||||||
|
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
||||||
|
.filter((v) => v != null && Number.isFinite(Number(v)))
|
||||||
|
.map(Number);
|
||||||
|
if (familyVals.length > 0) {
|
||||||
|
rawPct = Math.min(...familyVals);
|
||||||
|
} else if (
|
||||||
|
activePool &&
|
||||||
|
!isThirdPartyPoolText(activePool.family || activePool.poolLabel || '')
|
||||||
|
) {
|
||||||
|
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
||||||
|
if (fb != null && Number.isFinite(Number(fb))) rawPct = Number(fb);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
rawPct == null &&
|
||||||
|
isWeekly &&
|
||||||
|
weekly &&
|
||||||
|
!isThirdPartyPoolText(weekly.poolFamily || '') &&
|
||||||
|
weekly.remainingPct != null &&
|
||||||
|
Number.isFinite(Number(weekly.remainingPct))
|
||||||
|
) {
|
||||||
|
rawPct = Number(weekly.remainingPct);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
||||||
|
return Math.max(0, Math.min(100, Math.round(rawPct)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用最大余数法(Hamilton 方法)将各非零分桶等比缩放至目标整数总和,
|
||||||
|
* 保证 0 值通道绝不被凭空分配余数,且缩放后各分桶之和精确等于 `targetTotal`。
|
||||||
|
*
|
||||||
|
* @param {Record<string, number>} buckets
|
||||||
|
* @param {readonly string[]} keys
|
||||||
|
* @param {number} targetTotal
|
||||||
|
* @returns {Record<string, number>}
|
||||||
|
*/
|
||||||
|
export function scaleBucketsExact(buckets, keys, targetTotal) {
|
||||||
|
const safeTarget = Math.max(0, Math.round(Number(targetTotal || 0)));
|
||||||
|
const out = {};
|
||||||
|
let currentSum = 0;
|
||||||
|
for (const k of keys) {
|
||||||
|
const val = Math.max(0, Number(buckets[k] || 0));
|
||||||
|
out[k] = val;
|
||||||
|
currentSum += val;
|
||||||
|
}
|
||||||
|
if (safeTarget === 0 || currentSum <= 0) {
|
||||||
|
for (const k of keys) out[k] = 0;
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
if (currentSum === safeTarget) {
|
||||||
|
for (const k of keys) out[k] = Math.round(out[k]);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
const remainders = [];
|
||||||
|
let assigned = 0;
|
||||||
|
for (const k of keys) {
|
||||||
|
const rawVal = out[k];
|
||||||
|
if (rawVal <= 0) {
|
||||||
|
out[k] = 0;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const exact = (rawVal * safeTarget) / currentSum;
|
||||||
|
const floored = Math.floor(exact);
|
||||||
|
out[k] = floored;
|
||||||
|
assigned += floored;
|
||||||
|
remainders.push({ key: k, rem: exact - floored, orig: rawVal });
|
||||||
|
}
|
||||||
|
const diff = safeTarget - assigned;
|
||||||
|
if (diff > 0 && remainders.length > 0) {
|
||||||
|
remainders.sort((a, b) => b.rem - a.rem || b.orig - a.orig);
|
||||||
|
for (let i = 0; i < diff; i++) {
|
||||||
|
out[remainders[i % remainders.length].key] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
export const WINDOW_BRIDGE_KEY = '__AGUsageMonitorBridge';
|
||||||
|
export const WINDOW_BRIDGE_ROUTE_KEY = 'hostRouteCascadeId';
|
||||||
|
export const WINDOW_OVERLAY_KEY = '__AGUsageMonitorOverlay';
|
||||||
|
export const CONTEXT_WINDOWS_GLOBAL_KEY = '__AGUsageMonitorContextWindows';
|
||||||
|
|
||||||
|
export const WINDOW_OVERLAY_METHODS = Object.freeze({
|
||||||
|
ensureAlive: 'ensureAlive',
|
||||||
|
getDockKind: 'getDockKind',
|
||||||
|
getMountMode: 'getMountMode',
|
||||||
|
updateBridge: 'updateBridge',
|
||||||
|
applyMountMode: 'applyMountMode',
|
||||||
|
syncHostRoute: 'syncHostRoute',
|
||||||
|
deliverRpc: 'deliverRpc',
|
||||||
|
dispose: 'dispose',
|
||||||
|
});
|
||||||
|
|
||||||
|
export const BRIDGE_API_ROUTE_DEFS = Object.freeze([
|
||||||
|
Object.freeze({ path: '/api/telemetry', method: 'GET', action: 'telemetry' }),
|
||||||
|
Object.freeze({ path: '/api/settings', method: 'POST', action: 'settings' }),
|
||||||
|
Object.freeze({ path: '/api/accounts', method: 'GET', action: 'accounts_get' }),
|
||||||
|
Object.freeze({ path: '/api/accounts/update', method: 'POST', action: 'accounts_update' }),
|
||||||
|
Object.freeze({ path: '/api/context-window', method: 'POST', action: 'context_window' }),
|
||||||
|
Object.freeze({ path: '/api/settings/reset', method: 'POST', action: 'settings_reset' }),
|
||||||
|
Object.freeze({ path: '/api/cache/rebuild', method: 'POST', action: 'cache_rebuild' }),
|
||||||
|
Object.freeze({ path: '/api/cloud-sync', method: 'POST', action: 'cloud_sync' }),
|
||||||
|
Object.freeze({ path: '/api/plugin-update', method: 'POST', action: 'plugin_update' }),
|
||||||
|
Object.freeze({ path: '/api/bridge/relaunch', method: 'POST', action: 'bridge_relaunch' }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path));
|
||||||
|
|
||||||
|
export function readInjectedWindowBridge() {
|
||||||
|
return typeof window === 'undefined' ? undefined : window[WINDOW_BRIDGE_KEY];
|
||||||
|
}
|
||||||
@@ -6,9 +6,15 @@
|
|||||||
|
|
||||||
import { defineComponent } from './core/component.js';
|
import { defineComponent } from './core/component.js';
|
||||||
import { h, patchAttr } from './core/domPatch.js';
|
import { h, patchAttr } from './core/domPatch.js';
|
||||||
|
import { isWindowOverlayMode } from './core/httpClient.js';
|
||||||
import { i18nStore } from './i18n/index.js';
|
import { i18nStore } from './i18n/index.js';
|
||||||
import { resolveScopedConversation, telemetryStore } from './store/telemetryStore.js';
|
import {
|
||||||
|
normalizeClientWindowMountMode,
|
||||||
|
resolveScopedConversation,
|
||||||
|
telemetryStore,
|
||||||
|
} from './store/telemetryStore.js';
|
||||||
import { getViewTabs, uiStore } from './store/uiStore.js';
|
import { getViewTabs, uiStore } from './store/uiStore.js';
|
||||||
|
import { BridgeStatusNotice } from './components/settings/BridgeStatusNotice.js';
|
||||||
import { TopSessionHeader } from './components/layout/TopSessionHeader.js';
|
import { TopSessionHeader } from './components/layout/TopSessionHeader.js';
|
||||||
import { TopLongPillNav } from './components/ui/TopLongPillNav.js';
|
import { TopLongPillNav } from './components/ui/TopLongPillNav.js';
|
||||||
import { LiveOverviewView } from './views/LiveOverviewView.js';
|
import { LiveOverviewView } from './views/LiveOverviewView.js';
|
||||||
@@ -33,6 +39,36 @@ export const App = defineComponent({
|
|||||||
const stepsView = StepsDetailView();
|
const stepsView = StepsDetailView();
|
||||||
const settingsView = SettingsView();
|
const settingsView = SettingsView();
|
||||||
|
|
||||||
|
const globalBridgeNotice = BridgeStatusNotice({
|
||||||
|
dismissible: true,
|
||||||
|
});
|
||||||
|
const bannerSlotEl = h('div', { className: 'app-bridge-banner-slot', hidden: true }, [
|
||||||
|
globalBridgeNotice.el,
|
||||||
|
]);
|
||||||
|
|
||||||
|
function syncGlobalBridgeBanner() {
|
||||||
|
const activeView = uiStore.getState().activeView;
|
||||||
|
const telemetry = telemetryStore.getState().telemetry;
|
||||||
|
const settings = telemetry?.settings;
|
||||||
|
const mountMode = settings
|
||||||
|
? normalizeClientWindowMountMode(settings.windowMountMode, settings.enableWindowOverlay)
|
||||||
|
: 'sidebar';
|
||||||
|
const hasCtxOverrides = Boolean(
|
||||||
|
settings?.modelContextWindows && Object.keys(settings.modelContextWindows).length > 0
|
||||||
|
);
|
||||||
|
const shouldOfferGlobal =
|
||||||
|
!isWindowOverlayMode() &&
|
||||||
|
activeView !== 'settings' &&
|
||||||
|
(mountMode !== 'sidebar' || hasCtxOverrides);
|
||||||
|
globalBridgeNotice.refs.update({
|
||||||
|
visible: shouldOfferGlobal,
|
||||||
|
contextMode: mountMode === 'sidebar' && hasCtxOverrides,
|
||||||
|
windowBridge: telemetry?.windowBridge || null,
|
||||||
|
hostPlatform: telemetry?.hostPlatform || 'win32',
|
||||||
|
});
|
||||||
|
patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden'));
|
||||||
|
}
|
||||||
|
|
||||||
const viewMap = {
|
const viewMap = {
|
||||||
overview: overviewView.el,
|
overview: overviewView.el,
|
||||||
consumption: consumptionView.el,
|
consumption: consumptionView.el,
|
||||||
@@ -49,6 +85,7 @@ export const App = defineComponent({
|
|||||||
|
|
||||||
const shellEl = h('main', { className: 'app-shell' }, [
|
const shellEl = h('main', { className: 'app-shell' }, [
|
||||||
h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]),
|
h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]),
|
||||||
|
bannerSlotEl,
|
||||||
stageEl,
|
stageEl,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -88,6 +125,7 @@ export const App = defineComponent({
|
|||||||
settingsView.refs?.viewScrollbar?.refresh();
|
settingsView.refs?.viewScrollbar?.refresh();
|
||||||
}
|
}
|
||||||
syncStepsBadge();
|
syncStepsBadge();
|
||||||
|
syncGlobalBridgeBanner();
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -96,8 +134,16 @@ export const App = defineComponent({
|
|||||||
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
|
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
|
||||||
totalStepsAllAgents: st.telemetry?.activeConversation?.totalStepsAllAgents ?? 0,
|
totalStepsAllAgents: st.telemetry?.activeConversation?.totalStepsAllAgents ?? 0,
|
||||||
subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0,
|
subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0,
|
||||||
|
windowMountMode: st.telemetry?.settings?.windowMountMode,
|
||||||
|
enableWindowOverlay: st.telemetry?.settings?.enableWindowOverlay,
|
||||||
|
modelContextWindows: st.telemetry?.settings?.modelContextWindows,
|
||||||
|
windowBridge: st.telemetry?.windowBridge,
|
||||||
|
hostPlatform: st.telemetry?.hostPlatform,
|
||||||
}),
|
}),
|
||||||
() => syncStepsBadge()
|
() => {
|
||||||
|
syncStepsBadge();
|
||||||
|
syncGlobalBridgeBanner();
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const unsubScopeBadge = uiStore.subscribe(
|
const unsubScopeBadge = uiStore.subscribe(
|
||||||
@@ -107,7 +153,11 @@ export const App = defineComponent({
|
|||||||
|
|
||||||
const unsubI18n = i18nStore.subscribe(
|
const unsubI18n = i18nStore.subscribe(
|
||||||
(st) => st.locale,
|
(st) => st.locale,
|
||||||
() => syncStepsBadge()
|
() => {
|
||||||
|
syncStepsBadge();
|
||||||
|
globalBridgeNotice.refs.refreshLabels();
|
||||||
|
patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden'));
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
@@ -115,6 +165,7 @@ export const App = defineComponent({
|
|||||||
unsubStepCount();
|
unsubStepCount();
|
||||||
unsubScopeBadge();
|
unsubScopeBadge();
|
||||||
unsubI18n();
|
unsubI18n();
|
||||||
|
globalBridgeNotice.destroy();
|
||||||
sessionHeader.destroy();
|
sessionHeader.destroy();
|
||||||
topPillNav.destroy();
|
topPillNav.destroy();
|
||||||
overviewView.destroy();
|
overviewView.destroy();
|
||||||
@@ -128,6 +179,7 @@ export const App = defineComponent({
|
|||||||
refs: {
|
refs: {
|
||||||
sessionHeader,
|
sessionHeader,
|
||||||
topPillNav,
|
topPillNav,
|
||||||
|
globalBridgeNotice,
|
||||||
overviewView,
|
overviewView,
|
||||||
consumptionView,
|
consumptionView,
|
||||||
stepsView,
|
stepsView,
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
|
|
||||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||||
import {
|
import {
|
||||||
formatMetric,
|
formatAgentBadgeText,
|
||||||
formatTokens,
|
formatTokens,
|
||||||
formatTokensPrecise,
|
formatTokensPrecise,
|
||||||
formatUsd,
|
formatUsd,
|
||||||
@@ -18,6 +18,7 @@ import {
|
|||||||
speedReasonText,
|
speedReasonText,
|
||||||
} from '../../core/formatters.js';
|
} from '../../core/formatters.js';
|
||||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||||
|
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||||
|
|
||||||
let sessionChartUid = 0;
|
let sessionChartUid = 0;
|
||||||
|
|
||||||
@@ -39,16 +40,16 @@ export const MODEL_COLOR_VARS = Object.freeze([
|
|||||||
* @returns {string}
|
* @returns {string}
|
||||||
*/
|
*/
|
||||||
export function getStepModelGroupKey(step) {
|
export function getStepModelGroupKey(step) {
|
||||||
if (!step || typeof step !== 'object') return '模型未知';
|
if (!step || typeof step !== 'object') return t('fmt.unknownModel');
|
||||||
const rawLabel = String(step.modelLabel || step.label || '')
|
const rawLabel = String(step.baseModelLabel || step.modelLabel || step.label || '')
|
||||||
.replace(/\s*\[自动压缩\]\s*$/u, '')
|
.replace(/\s*\[自动压缩\]\s*$/u, '')
|
||||||
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
|
.replace(/\s*\((?:Max|XHigh|High|Medium|Low|Thinking|Extra Low|Tiered)\)\s*$/i, '')
|
||||||
.trim();
|
.trim();
|
||||||
if (rawLabel) return rawLabel;
|
if (rawLabel) return rawLabel;
|
||||||
const rawShort = String(step.modelShort || step.shortName || '')
|
const rawShort = String(step.baseModelShort || step.modelShort || step.shortName || '')
|
||||||
.replace(/·压缩\s*$/u, '')
|
.replace(/·(?:压缩|Compact)\s*$/iu, '')
|
||||||
.trim();
|
.trim();
|
||||||
return rawShort || '模型未知';
|
return rawShort || t('fmt.unknownModel');
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -422,21 +423,6 @@ export function computePublicationFit(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 计算样本点上的平滑回归拟合值序列(供单元测试与轻量调用直接读取)。
|
|
||||||
*
|
|
||||||
* @param {number[]} ys
|
|
||||||
* @param {{ minVal?: number, maxVal?: number, xs?: number[] }} [bounds]
|
|
||||||
* @returns {number[]}
|
|
||||||
*/
|
|
||||||
export function computeLoessFit(ys, { minVal = 0, maxVal = Infinity, xs = null } = {}) {
|
|
||||||
const n = Array.isArray(ys) ? ys.length : 0;
|
|
||||||
if (n === 0) return [];
|
|
||||||
const xArr =
|
|
||||||
Array.isArray(xs) && xs.length === n ? xs : Array.from({ length: n }, (_, idx) => idx);
|
|
||||||
return computePublicationFit(xArr, ys, { minVal, maxVal }).sampleFits;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。
|
* Heckbert 科学坐标轴刻度取整算法,生成科研图表风格的均匀整洁刻度。
|
||||||
*/
|
*/
|
||||||
@@ -590,7 +576,17 @@ function computeStepTickIndices(count) {
|
|||||||
function formatStepAxisTag(st, showAgentPrefix) {
|
function formatStepAxisTag(st, showAgentPrefix) {
|
||||||
const num = `#${Number(st?.stepIndex ?? 0)}`;
|
const num = `#${Number(st?.stepIndex ?? 0)}`;
|
||||||
if (!showAgentPrefix) return num;
|
if (!showAgentPrefix) return num;
|
||||||
const badge = st?.agentBadge || (st?.isSubagent ? '子' : '主');
|
const badge = formatAgentBadgeText({
|
||||||
|
agentKind:
|
||||||
|
st?.agentKind || (!st?.isSubagent ? 'main' : st?.isSideQuestion ? 'side_question' : 'subagent'),
|
||||||
|
agentOrdinal:
|
||||||
|
st?.agentOrdinal || (st?.isSideQuestion ? st?.sideIndex || 0 : st?.agentIndex || 0),
|
||||||
|
isMain: !st?.isSubagent,
|
||||||
|
isSideQuestion: Boolean(st?.isSideQuestion),
|
||||||
|
sideIndex: st?.sideIndex || 0,
|
||||||
|
index: st?.agentIndex || 0,
|
||||||
|
badgeText: st?.agentBadge,
|
||||||
|
});
|
||||||
return `${badge}${num}`;
|
return `${badge}${num}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -725,7 +721,7 @@ export function createSessionLineChart() {
|
|||||||
|
|
||||||
const emptyHintEl = h('div', {
|
const emptyHintEl = h('div', {
|
||||||
className: 'sstep-empty-hint text-muted',
|
className: 'sstep-empty-hint text-muted',
|
||||||
text: '当前范围暂无可绘制的调用步骤',
|
text: t('chart.step.empty'),
|
||||||
hidden: true,
|
hidden: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -803,7 +799,10 @@ export function createSessionLineChart() {
|
|||||||
|
|
||||||
patchText(tipHeadLeft, pt.stepTag);
|
patchText(tipHeadLeft, pt.stepTag);
|
||||||
patchText(tipHeadRight, pt.modelText);
|
patchText(tipHeadRight, pt.modelText);
|
||||||
patchText(tipMainLeft, pt.valid ? formatChartMetricValue(currentMetric, pt.value) : '未纳入');
|
patchText(
|
||||||
|
tipMainLeft,
|
||||||
|
pt.valid ? formatChartMetricValue(currentMetric, pt.value) : t('chart.step.excluded')
|
||||||
|
);
|
||||||
patchText(tipMainRight, pt.secondaryRight || '');
|
patchText(tipMainRight, pt.secondaryRight || '');
|
||||||
patchAttr(tipSub, 'hidden', !pt.subDetail);
|
patchAttr(tipSub, 'hidden', !pt.subDetail);
|
||||||
if (pt.subDetail) {
|
if (pt.subDetail) {
|
||||||
@@ -930,6 +929,7 @@ export function createSessionLineChart() {
|
|||||||
? steps
|
? steps
|
||||||
: steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st)));
|
: steps.filter((st) => st && targetKeySet.has(getStepModelGroupKey(st)));
|
||||||
|
|
||||||
|
patchText(emptyHintEl, t('chart.step.empty'));
|
||||||
if (!matchedSteps.length) {
|
if (!matchedSteps.length) {
|
||||||
currentPoints = [];
|
currentPoints = [];
|
||||||
lastSig = 'empty';
|
lastSig = 'empty';
|
||||||
@@ -943,7 +943,7 @@ export function createSessionLineChart() {
|
|||||||
patchAttr(peakPill, 'hidden', true);
|
patchAttr(peakPill, 'hidden', true);
|
||||||
patchAttr(emptyHintEl, 'hidden', false);
|
patchAttr(emptyHintEl, 'hidden', false);
|
||||||
clearHover();
|
clearHover();
|
||||||
return { summaryBadge: '0 步' };
|
return { summaryBadge: t('chart.step.zeroSteps') };
|
||||||
}
|
}
|
||||||
|
|
||||||
const modelColorMap = new Map();
|
const modelColorMap = new Map();
|
||||||
@@ -957,7 +957,7 @@ export function createSessionLineChart() {
|
|||||||
const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, {
|
const disp = resolveModelDisplayInfo({ modelLabel: gk, label: gk }, displaySettings, {
|
||||||
fallback: gk,
|
fallback: gk,
|
||||||
});
|
});
|
||||||
modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk);
|
modelLabelByGroup.set(gk, disp.baseText || disp.text || gk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const st of matchedSteps) {
|
for (const st of matchedSteps) {
|
||||||
@@ -970,7 +970,7 @@ export function createSessionLineChart() {
|
|||||||
}
|
}
|
||||||
if (!modelLabelByGroup.has(gk)) {
|
if (!modelLabelByGroup.has(gk)) {
|
||||||
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
||||||
modelLabelByGroup.set(gk, disp.text.replace(/·压缩\s*$/u, '').trim() || gk);
|
modelLabelByGroup.set(gk, disp.baseText || disp.text || gk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1030,41 +1030,62 @@ export function createSessionLineChart() {
|
|||||||
|
|
||||||
if (metric === 'totalTokens') {
|
if (metric === 'totalTokens') {
|
||||||
value = isMultiCompare ? modelCumTok : runningTokens;
|
value = isMultiCompare ? modelCumTok : runningTokens;
|
||||||
secondaryRight = `本步 +${formatTokens(stepTotalTok)}`;
|
secondaryRight = t('chart.step.stepAdd', { tokens: formatTokens(stepTotalTok) });
|
||||||
subDetail = `入 ${formatTokens(inTok)} · 缓 ${formatTokens(cacheTok)} · 出 ${formatTokens(outTok)}`;
|
subDetail = t('chart.step.ioSplit', {
|
||||||
|
inTok: formatTokens(inTok),
|
||||||
|
cacheTok: formatTokens(cacheTok),
|
||||||
|
outTok: formatTokens(outTok),
|
||||||
|
});
|
||||||
} else if (metric === 'context') {
|
} else if (metric === 'context') {
|
||||||
value = ctxTok;
|
value = ctxTok;
|
||||||
if (hasPrevCtx) {
|
if (hasPrevCtx) {
|
||||||
const sign = ctxDelta >= 0 ? '+' : '-';
|
const sign = ctxDelta >= 0 ? '+' : '-';
|
||||||
secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`;
|
secondaryRight = `${sign}${formatTokens(Math.abs(ctxDelta))}`;
|
||||||
} else {
|
} else {
|
||||||
secondaryRight = `缓存 ${Number(st.cacheHitPct ?? 0)}%`;
|
secondaryRight = t('chart.step.cacheShort', { pct: Number(st.cacheHitPct ?? 0) });
|
||||||
}
|
}
|
||||||
subDetail = st.isCompactionStep
|
subDetail = st.isCompactionStep
|
||||||
? '上下文自动压缩检查点'
|
? t('chart.step.compactionCheckpoint')
|
||||||
: `缓存命中 ${Number(st.cacheHitPct ?? 0)}% · 输出 +${formatTokens(outTok)}`;
|
: t('chart.step.cacheHitOut', {
|
||||||
|
pct: Number(st.cacheHitPct ?? 0),
|
||||||
|
outTok: formatTokens(outTok),
|
||||||
|
});
|
||||||
} else if (metric === 'tps') {
|
} else if (metric === 'tps') {
|
||||||
valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0;
|
valid = !st.isCompactionStep && Number.isFinite(st.tokPerSec) && st.tokPerSec > 0;
|
||||||
value = valid ? Number(st.tokPerSec) : 0;
|
value = valid ? Number(st.tokPerSec) : 0;
|
||||||
secondaryRight = Number.isFinite(st.ttftSec) ? `首字 ${st.ttftSec.toFixed(1)}s` : '';
|
secondaryRight = Number.isFinite(st.ttftSec)
|
||||||
|
? t('chart.step.ttftShort', { sec: st.ttftSec.toFixed(1) })
|
||||||
|
: '';
|
||||||
subDetail = valid
|
subDetail = valid
|
||||||
? `输出 ${formatTokens(outTok)} · 上下文 ${formatTokens(ctxTok)}`
|
? t('chart.step.outAndCtx', {
|
||||||
: speedReasonText(st.selectedSpeedReason) || (st.isCompactionStep ? '上下文压缩步' : '无测速样本');
|
outTok: formatTokens(outTok),
|
||||||
|
ctxTok: formatTokens(ctxTok),
|
||||||
|
})
|
||||||
|
: speedReasonText(st.selectedSpeedReason) ||
|
||||||
|
(st.isCompactionStep ? t('chart.step.compactionStep') : t('chart.step.noSpeedSample'));
|
||||||
} else if (metric === 'ttft') {
|
} else if (metric === 'ttft') {
|
||||||
valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0;
|
valid = !st.isCompactionStep && Number.isFinite(st.ttftSec) && st.ttftSec >= 0;
|
||||||
value = valid ? Number(st.ttftSec) : 0;
|
value = valid ? Number(st.ttftSec) : 0;
|
||||||
secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : '';
|
secondaryRight = Number.isFinite(st.tokPerSec) ? `${st.tokPerSec.toFixed(1)} tok/s` : '';
|
||||||
subDetail = valid
|
subDetail = valid
|
||||||
? `上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(st.cacheHitPct ?? 0)}%`
|
? t('chart.step.ctxAndCache', {
|
||||||
|
ctxTok: formatTokens(ctxTok),
|
||||||
|
pct: Number(st.cacheHitPct ?? 0),
|
||||||
|
})
|
||||||
: st.isCompactionStep
|
: st.isCompactionStep
|
||||||
? '上下文压缩步'
|
? t('chart.step.compactionStep')
|
||||||
: '无首字计时样本';
|
: t('chart.step.noTtftSample');
|
||||||
} else if (metric === 'cost') {
|
} else if (metric === 'cost') {
|
||||||
valid = stepCost !== null;
|
valid = stepCost !== null;
|
||||||
value = valid ? stepCost : 0;
|
value = valid ? stepCost : 0;
|
||||||
const shownCumCost = isMultiCompare ? modelCumCost : runningCost;
|
const shownCumCost = isMultiCompare ? modelCumCost : runningCost;
|
||||||
secondaryRight = `累计 ${formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 })}`;
|
secondaryRight = t('chart.step.cumCost', {
|
||||||
subDetail = `缓存 ${Number(st.cacheHitPct ?? 0)}% · 本步 ${formatTokens(stepTotalTok)}`;
|
cost: formatUsd(shownCumCost, { precise: shownCumCost > 0 && shownCumCost < 0.1 }),
|
||||||
|
});
|
||||||
|
subDetail = t('chart.step.cacheAndStepTok', {
|
||||||
|
pct: Number(st.cacheHitPct ?? 0),
|
||||||
|
tokens: formatTokens(stepTotalTok),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (valid) {
|
if (valid) {
|
||||||
@@ -1124,11 +1145,12 @@ export function createSessionLineChart() {
|
|||||||
const validPoints = points.filter((p) => p.valid);
|
const validPoints = points.filter((p) => p.valid);
|
||||||
patchAttr(emptyHintEl, 'hidden', validPoints.length > 0);
|
patchAttr(emptyHintEl, 'hidden', validPoints.length > 0);
|
||||||
|
|
||||||
|
const locale = getEffectiveLocale();
|
||||||
const colorSig = Array.from(modelColorMap.entries())
|
const colorSig = Array.from(modelColorMap.entries())
|
||||||
.map(([k, v]) => `${k}=${v}`)
|
.map(([k, v]) => `${k}=${v}`)
|
||||||
.join(',');
|
.join(',');
|
||||||
const sig =
|
const sig =
|
||||||
`${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` +
|
`${locale}|${viewW}|${metric}|${showAgentPrefix}|${isMultiCompare ? 'multi' : 'single'}:${targetKeys.join(',')}|${colorSig}|` +
|
||||||
points
|
points
|
||||||
.map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`)
|
.map((p) => `${p.stepTag}:${p.modelText}:${p.valid ? p.value.toFixed(4) : 'x'}`)
|
||||||
.join('|');
|
.join('|');
|
||||||
@@ -1263,12 +1285,12 @@ export function createSessionLineChart() {
|
|||||||
patchStyleVar(swatch, '--swatch-bg', colorVar);
|
patchStyleVar(swatch, '--swatch-bg', colorVar);
|
||||||
const stStat = perModelStats.get(gk);
|
const stStat = perModelStats.get(gk);
|
||||||
const baseLabel = modelLabelByGroup.get(gk) || gk;
|
const baseLabel = modelLabelByGroup.get(gk) || gk;
|
||||||
let summarySuffix = '无样本';
|
let summarySuffix = t('chart.step.noSamples');
|
||||||
if (stStat && stStat.count > 0) {
|
if (stStat && stStat.count > 0) {
|
||||||
if (metric === 'totalTokens') {
|
if (metric === 'totalTokens') {
|
||||||
summarySuffix = formatTokens(stStat.cumTok);
|
summarySuffix = formatTokens(stStat.cumTok);
|
||||||
} else if (metric === 'context') {
|
} else if (metric === 'context') {
|
||||||
summarySuffix = `峰 ${formatTokens(stStat.max)}`;
|
summarySuffix = t('chart.step.peakShort', { val: formatTokens(stStat.max) });
|
||||||
} else if (metric === 'tps' || metric === 'ttft') {
|
} else if (metric === 'tps' || metric === 'ttft') {
|
||||||
summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count);
|
summarySuffix = formatChartMetricCompact(metric, stStat.sum / stStat.count);
|
||||||
} else if (metric === 'cost') {
|
} else if (metric === 'cost') {
|
||||||
@@ -1306,7 +1328,10 @@ export function createSessionLineChart() {
|
|||||||
const peakPt = points[peakIdx];
|
const peakPt = points[peakIdx];
|
||||||
patchText(
|
patchText(
|
||||||
peakPill,
|
peakPill,
|
||||||
`峰值 ${peakPt.stepTag} · ${formatChartMetricCompact(metric, peakPt.value)}`
|
t('chart.step.peakPill', {
|
||||||
|
tag: peakPt.stepTag,
|
||||||
|
val: formatChartMetricCompact(metric, peakPt.value),
|
||||||
|
})
|
||||||
);
|
);
|
||||||
patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor);
|
patchStyleVar(peakPill, '--sstep-accent', isMultiCompare ? peakPt.dotColor : accentColor);
|
||||||
const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100));
|
const pctLeft = Math.max(14, Math.min(86, (peakPt.x / viewW) * 100));
|
||||||
@@ -1322,28 +1347,42 @@ export function createSessionLineChart() {
|
|||||||
showHoverAt(hoveredIdx);
|
showHoverAt(hoveredIdx);
|
||||||
}
|
}
|
||||||
|
|
||||||
let summaryBadge = `${matchedSteps.length}步`;
|
let summaryBadge = t('chart.step.stepsCount', { count: matchedSteps.length });
|
||||||
const activeCompareCount = isMultiCompare ? targetKeys.length : 1;
|
const activeCompareCount = isMultiCompare ? targetKeys.length : 1;
|
||||||
const multiPrefix = isMultiCompare ? `${activeCompareCount} 模型 · ` : '';
|
const multiPrefix = isMultiCompare
|
||||||
|
? t('chart.step.multiPrefix', { count: activeCompareCount })
|
||||||
|
: '';
|
||||||
if (metric === 'totalTokens') {
|
if (metric === 'totalTokens') {
|
||||||
summaryBadge = `${multiPrefix}累计 ${formatTokens(runningTokens)}`;
|
summaryBadge = t('chart.step.sumTokens', {
|
||||||
|
prefix: multiPrefix,
|
||||||
|
tokens: formatTokens(runningTokens),
|
||||||
|
});
|
||||||
} else if (metric === 'context') {
|
} else if (metric === 'context') {
|
||||||
const lastCtx = points[points.length - 1]?.value || 0;
|
const lastCtx = points[points.length - 1]?.value || 0;
|
||||||
summaryBadge = isMultiCompare
|
summaryBadge = isMultiCompare
|
||||||
? `${multiPrefix}峰值 ${formatTokens(maxVal)}`
|
? t('chart.step.peakTokens', { prefix: multiPrefix, tokens: formatTokens(maxVal) })
|
||||||
: `当前 ${formatTokens(lastCtx)}`;
|
: t('chart.step.currentCtx', { tokens: formatTokens(lastCtx) });
|
||||||
} else if (metric === 'tps') {
|
} else if (metric === 'tps') {
|
||||||
summaryBadge =
|
summaryBadge =
|
||||||
validCount > 0
|
validCount > 0
|
||||||
? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)} tok/s`
|
? t('chart.step.meanTps', {
|
||||||
: '暂无有效样本';
|
prefix: multiPrefix,
|
||||||
|
val: (validSum / validCount).toFixed(1),
|
||||||
|
})
|
||||||
|
: t('chart.step.noValidSamples');
|
||||||
} else if (metric === 'ttft') {
|
} else if (metric === 'ttft') {
|
||||||
summaryBadge =
|
summaryBadge =
|
||||||
validCount > 0
|
validCount > 0
|
||||||
? `${multiPrefix}均值 ${(validSum / validCount).toFixed(1)}s`
|
? t('chart.step.meanSec', {
|
||||||
: '暂无有效样本';
|
prefix: multiPrefix,
|
||||||
|
val: (validSum / validCount).toFixed(1),
|
||||||
|
})
|
||||||
|
: t('chart.step.noValidSamples');
|
||||||
} else if (metric === 'cost') {
|
} else if (metric === 'cost') {
|
||||||
summaryBadge = `${multiPrefix}累计 ${formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 })}`;
|
summaryBadge = t('chart.step.sumCost', {
|
||||||
|
prefix: multiPrefix,
|
||||||
|
cost: formatUsd(runningCost, { precise: runningCost > 0 && runningCost < 0.1 }),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return { summaryBadge };
|
return { summaryBadge };
|
||||||
@@ -1434,7 +1473,7 @@ export function createModelFitChart() {
|
|||||||
|
|
||||||
const emptyHintEl = h('div', {
|
const emptyHintEl = h('div', {
|
||||||
className: 'sstep-empty-hint text-muted',
|
className: 'sstep-empty-hint text-muted',
|
||||||
text: '该模型暂无有效拟合样本',
|
text: t('chart.fit.empty'),
|
||||||
hidden: true,
|
hidden: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1449,14 +1488,16 @@ export function createModelFitChart() {
|
|||||||
tipSub,
|
tipSub,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const fitMethodLabelEl = h('span', { text: 'LOESS 拟合' });
|
const fitMethodLabelEl = h('span', { text: t('chart.fit.loess') });
|
||||||
|
const olsLegendTextEl = h('span', { text: t('chart.fit.olsLinear') });
|
||||||
const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [
|
const olsLegendWrapEl = h('span', { className: 'sstep-fit-legend-ols' }, [
|
||||||
h('span', { className: 'sstep-fit-swatch is-ols' }),
|
h('span', { className: 'sstep-fit-swatch is-ols' }),
|
||||||
h('span', { text: 'OLS 线性' }),
|
olsLegendTextEl,
|
||||||
]);
|
]);
|
||||||
|
const obsLegendTextEl = h('span', { text: t('chart.fit.observed') });
|
||||||
const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [
|
const singleLegendEl = h('span', { className: 'sstep-fit-legend' }, [
|
||||||
h('span', { className: 'sstep-fit-swatch is-scatter' }),
|
h('span', { className: 'sstep-fit-swatch is-scatter' }),
|
||||||
h('span', { text: '观测值' }),
|
obsLegendTextEl,
|
||||||
h('span', { className: 'sstep-fit-swatch is-curve' }),
|
h('span', { className: 'sstep-fit-swatch is-curve' }),
|
||||||
fitMethodLabelEl,
|
fitMethodLabelEl,
|
||||||
h('span', { className: 'sstep-fit-swatch is-ci' }),
|
h('span', { className: 'sstep-fit-swatch is-ci' }),
|
||||||
@@ -1539,8 +1580,14 @@ export function createModelFitChart() {
|
|||||||
patchAttr(tooltipEl, 'hidden', false);
|
patchAttr(tooltipEl, 'hidden', false);
|
||||||
patchText(tipHeadLeft, sp.stepTag);
|
patchText(tipHeadLeft, sp.stepTag);
|
||||||
patchText(tipHeadRight, sp.modelText);
|
patchText(tipHeadRight, sp.modelText);
|
||||||
patchText(tipMainLeft, `拟合 ${formatChartMetricValue(currentMetric, sp.fitVal)}`);
|
patchText(
|
||||||
patchText(tipMainRight, `观测 ${formatChartMetricValue(currentMetric, sp.rawVal)}`);
|
tipMainLeft,
|
||||||
|
t('chart.fit.tipFit', { val: formatChartMetricValue(currentMetric, sp.fitVal) })
|
||||||
|
);
|
||||||
|
patchText(
|
||||||
|
tipMainRight,
|
||||||
|
t('chart.fit.tipObs', { val: formatChartMetricValue(currentMetric, sp.rawVal) })
|
||||||
|
);
|
||||||
|
|
||||||
patchAttr(tipSub, 'hidden', false);
|
patchAttr(tipSub, 'hidden', false);
|
||||||
if (sp.compareHint) {
|
if (sp.compareHint) {
|
||||||
@@ -1554,7 +1601,10 @@ export function createModelFitChart() {
|
|||||||
const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0));
|
const ctxTok = Math.max(0, Number(sp.st?.contextTokens || 0));
|
||||||
patchText(
|
patchText(
|
||||||
tipSub,
|
tipSub,
|
||||||
`上下文 ${formatTokens(ctxTok)} · 缓存 ${Number(sp.st?.cacheHitPct ?? 0)}%`
|
t('chart.step.ctxAndCache', {
|
||||||
|
ctxTok: formatTokens(ctxTok),
|
||||||
|
pct: Number(sp.st?.cacheHitPct ?? 0),
|
||||||
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1820,11 +1870,16 @@ export function createModelFitChart() {
|
|||||||
xVal: globalX,
|
xVal: globalX,
|
||||||
rawVal,
|
rawVal,
|
||||||
stepTag: formatStepAxisTag(st, showAgentPrefix),
|
stepTag: formatStepAxisTag(st, showAgentPrefix),
|
||||||
modelText: disp.text.replace(/·压缩\s*$/u, '').trim() || disp.text,
|
modelText: disp.baseText || disp.text,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const locale = getEffectiveLocale();
|
||||||
|
patchText(emptyHintEl, t('chart.fit.empty'));
|
||||||
|
patchText(obsLegendTextEl, t('chart.fit.observed'));
|
||||||
|
patchText(olsLegendTextEl, t('chart.fit.olsLinear'));
|
||||||
|
|
||||||
if (fitCacheMetric !== metric) {
|
if (fitCacheMetric !== metric) {
|
||||||
fitCache.clear();
|
fitCache.clear();
|
||||||
fitCacheMetric = metric;
|
fitCacheMetric = metric;
|
||||||
@@ -1848,9 +1903,10 @@ export function createModelFitChart() {
|
|||||||
patchAttr(singleLegendEl, 'hidden', false);
|
patchAttr(singleLegendEl, 'hidden', false);
|
||||||
patchAttr(multiLegendEl, 'hidden', true);
|
patchAttr(multiLegendEl, 'hidden', true);
|
||||||
patchAttr(emptyHintEl, 'hidden', false);
|
patchAttr(emptyHintEl, 'hidden', false);
|
||||||
|
patchText(fitMethodLabelEl, t('chart.fit.loess'));
|
||||||
patchText(fitStatsEl, 'n = 0');
|
patchText(fitStatsEl, 'n = 0');
|
||||||
clearHover();
|
clearHover();
|
||||||
return { sampleCount: 0, summaryBadge: '0 样本' };
|
return { sampleCount: 0, summaryBadge: t('chart.fit.zeroSamples') };
|
||||||
}
|
}
|
||||||
|
|
||||||
patchAttr(emptyHintEl, 'hidden', true);
|
patchAttr(emptyHintEl, 'hidden', true);
|
||||||
@@ -1932,7 +1988,12 @@ export function createModelFitChart() {
|
|||||||
if (interp !== null) {
|
if (interp !== null) {
|
||||||
peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`);
|
peerParts.push(`${other.label} ${formatChartMetricCompact(metric, interp)}`);
|
||||||
} else {
|
} else {
|
||||||
peerParts.push(`${other.label} 均 ${formatChartMetricCompact(metric, other.pubFit.mean)}`);
|
peerParts.push(
|
||||||
|
t('chart.fit.peerMean', {
|
||||||
|
label: other.label,
|
||||||
|
val: formatChartMetricCompact(metric, other.pubFit.mean),
|
||||||
|
})
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
@@ -1945,7 +2006,10 @@ export function createModelFitChart() {
|
|||||||
ciHigh: s.pubFit.sampleCiHigh[i],
|
ciHigh: s.pubFit.sampleCiHigh[i],
|
||||||
ciHalf: s.pubFit.sampleCiHalf[i],
|
ciHalf: s.pubFit.sampleCiHalf[i],
|
||||||
seriesColor: s.colorVar,
|
seriesColor: s.colorVar,
|
||||||
compareHint: peerParts.length > 0 ? `同图对比:${peerParts.join(' · ')}` : '',
|
compareHint:
|
||||||
|
peerParts.length > 0
|
||||||
|
? t('chart.fit.peerCompare', { peers: peerParts.join(' · ') })
|
||||||
|
: '',
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
s.samples = sSamples;
|
s.samples = sSamples;
|
||||||
@@ -1955,7 +2019,7 @@ export function createModelFitChart() {
|
|||||||
currentSamples = combinedSamples;
|
currentSamples = combinedSamples;
|
||||||
|
|
||||||
const sig =
|
const sig =
|
||||||
`multi|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
|
`multi|${locale}|${viewW}|${targetKeys.join(',')}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
|
||||||
seriesList
|
seriesList
|
||||||
.map(
|
.map(
|
||||||
(s) =>
|
(s) =>
|
||||||
@@ -2069,7 +2133,7 @@ export function createModelFitChart() {
|
|||||||
fitStatsEl,
|
fitStatsEl,
|
||||||
seriesList.length <= 2
|
seriesList.length <= 2
|
||||||
? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ')
|
? seriesList.map((s) => `R²=${s.pubFit.r2.toFixed(2)}`).join(' · ')
|
||||||
: `${seriesList.length} 条拟合线`
|
: t('chart.fit.curvesCount', { count: seriesList.length })
|
||||||
);
|
);
|
||||||
patchAttr(fitStatsEl, 'title', r2SummaryTitle);
|
patchAttr(fitStatsEl, 'title', r2SummaryTitle);
|
||||||
|
|
||||||
@@ -2081,7 +2145,10 @@ export function createModelFitChart() {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
sampleCount: combinedSamples.length,
|
sampleCount: combinedSamples.length,
|
||||||
summaryBadge: `${combinedSamples.length}步 · ${seriesList.length} 模型对比`,
|
summaryBadge: t('chart.fit.multiBadge', {
|
||||||
|
steps: combinedSamples.length,
|
||||||
|
models: seriesList.length,
|
||||||
|
}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2096,7 +2163,10 @@ export function createModelFitChart() {
|
|||||||
const rawYs = filtered.map((d) => d.rawVal);
|
const rawYs = filtered.map((d) => d.rawVal);
|
||||||
const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false);
|
const pubFit = reusePublicationFit(null, xs, rawYs, maxBound, false);
|
||||||
|
|
||||||
patchText(fitMethodLabelEl, pubFit.method === 'LOESS' ? 'LOESS 拟合' : 'OLS 回归');
|
patchText(
|
||||||
|
fitMethodLabelEl,
|
||||||
|
pubFit.method === 'LOESS' ? t('chart.fit.loess') : t('chart.fit.olsReg')
|
||||||
|
);
|
||||||
patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6);
|
patchAttr(olsLegendWrapEl, 'hidden', filtered.length < 6);
|
||||||
|
|
||||||
let dataMin = Infinity;
|
let dataMin = Infinity;
|
||||||
@@ -2149,7 +2219,7 @@ export function createModelFitChart() {
|
|||||||
currentSamples = samples;
|
currentSamples = samples;
|
||||||
|
|
||||||
const sig =
|
const sig =
|
||||||
`single|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
|
`single|${locale}|${viewW}|${targetKeys[0]}|${metric}|${showAgentPrefix}|${yScale.min.toFixed(4)}|${yScale.max.toFixed(4)}|` +
|
||||||
samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|');
|
samples.map((s) => `${s.xVal}:${s.rawVal.toFixed(4)}:${s.fitVal.toFixed(4)}`).join('|');
|
||||||
|
|
||||||
if (sig !== lastSig) {
|
if (sig !== lastSig) {
|
||||||
@@ -2225,7 +2295,10 @@ export function createModelFitChart() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const summaryBadge = `${samples.length}步 · 均 ${formatChartMetricCompact(metric, pubFit.mean)}`;
|
const summaryBadge = t('chart.fit.singleBadge', {
|
||||||
|
steps: samples.length,
|
||||||
|
mean: formatChartMetricCompact(metric, pubFit.mean),
|
||||||
|
});
|
||||||
if (samples.length >= 2) {
|
if (samples.length >= 2) {
|
||||||
const rSign = pubFit.r >= 0 ? '+' : '';
|
const rSign = pubFit.r >= 0 ? '+' : '';
|
||||||
const slopeSign = pubFit.slope >= 0 ? '+' : '';
|
const slopeSign = pubFit.slope >= 0 ? '+' : '';
|
||||||
@@ -2233,7 +2306,11 @@ export function createModelFitChart() {
|
|||||||
patchAttr(
|
patchAttr(
|
||||||
fitStatsEl,
|
fitStatsEl,
|
||||||
'title',
|
'title',
|
||||||
`OLS: y = ${slopeSign}${pubFit.slope.toFixed(3)}x + ${pubFit.intercept.toFixed(2)} · 样本标准差 SD = ±${pubFit.sd.toFixed(2)}`
|
t('chart.fit.olsTitle', {
|
||||||
|
slope: `${slopeSign}${pubFit.slope.toFixed(3)}`,
|
||||||
|
intercept: pubFit.intercept.toFixed(2),
|
||||||
|
sd: pubFit.sd.toFixed(2),
|
||||||
|
})
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
patchText(fitStatsEl, `n = ${samples.length}`);
|
patchText(fitStatsEl, `n = ${samples.length}`);
|
||||||
|
|||||||
@@ -9,6 +9,7 @@
|
|||||||
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core/domPatch.js';
|
||||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||||
|
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||||
|
|
||||||
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
||||||
export const HEATMAP_DAYS_THRESHOLD = 90;
|
export const HEATMAP_DAYS_THRESHOLD = 90;
|
||||||
@@ -176,7 +177,9 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
|
|||||||
if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue;
|
if (totalWeeks > 16 && c.col >= totalWeeks - 1) continue;
|
||||||
if (ticks.length > 0 && c.col < nextAllowedCol) continue;
|
if (ticks.length > 0 && c.col < nextAllowedCol) continue;
|
||||||
const showYear = crossYear && (c.month === 1 || ticks.length === 0);
|
const showYear = crossYear && (c.month === 1 || ticks.length === 0);
|
||||||
const text = showYear ? `${String(c.year).slice(-2)}年${c.month}月` : `${c.month}月`;
|
const text = showYear
|
||||||
|
? t('chart.trend.hmMonthYear', { yy: String(c.year).slice(-2), month: c.month })
|
||||||
|
: t('chart.trend.hmMonthOnly', { month: c.month });
|
||||||
ticks.push({ col: c.col, text });
|
ticks.push({ col: c.col, text });
|
||||||
nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap);
|
nextAllowedCol = c.col + (showYear ? baseMinGap + 1 : baseMinGap);
|
||||||
}
|
}
|
||||||
@@ -311,26 +314,41 @@ export function createTrendAreaChart() {
|
|||||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
|
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
|
||||||
|
|
||||||
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
||||||
const weekdayLabels = ['一', '', '三', '', '五', '', '日'];
|
const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') });
|
||||||
|
const wdayWedEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayWed') });
|
||||||
|
const wdayFriEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayFri') });
|
||||||
|
const wdaySunEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdaySun') });
|
||||||
const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [
|
const hmWeekdaysEl = h('div', { className: 'trend-hm-weekdays', 'aria-hidden': 'true' }, [
|
||||||
h('span', { className: 'trend-hm-month-spacer' }),
|
h('span', { className: 'trend-hm-month-spacer' }),
|
||||||
...weekdayLabels.map((txt) => h('span', { className: 'trend-hm-wday', text: txt })),
|
wdayMonEl,
|
||||||
|
h('span', { className: 'trend-hm-wday', text: '' }),
|
||||||
|
wdayWedEl,
|
||||||
|
h('span', { className: 'trend-hm-wday', text: '' }),
|
||||||
|
wdayFriEl,
|
||||||
|
h('span', { className: 'trend-hm-wday', text: '' }),
|
||||||
|
wdaySunEl,
|
||||||
]);
|
]);
|
||||||
const hmMonthsEl = h('div', { className: 'trend-hm-months' });
|
const hmMonthsEl = h('div', { className: 'trend-hm-months' });
|
||||||
const hmGridEl = h('div', { className: 'trend-hm-grid', role: 'grid', 'aria-label': '每日用量热力格子图' });
|
const hmGridEl = h('div', {
|
||||||
|
className: 'trend-hm-grid',
|
||||||
|
role: 'grid',
|
||||||
|
'aria-label': t('chart.trend.hmAria'),
|
||||||
|
});
|
||||||
const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]);
|
const hmTrackEl = h('div', { className: 'trend-hm-track' }, [hmMonthsEl, hmGridEl]);
|
||||||
const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]);
|
const hmScrollEl = h('div', { className: 'trend-hm-scroll' }, [hmTrackEl]);
|
||||||
const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]);
|
const hmBodyEl = h('div', { className: 'trend-heatmap-body' }, [hmWeekdaysEl, hmScrollEl]);
|
||||||
|
|
||||||
const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' });
|
const hmSummaryEl = h('span', { className: 'trend-hm-summary text-mono', text: '' });
|
||||||
|
const hmLessEl = h('span', { text: t('chart.trend.hmLess') });
|
||||||
|
const hmMoreEl = h('span', { text: t('chart.trend.hmMore') });
|
||||||
const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [
|
const hmLegendEl = h('span', { className: 'trend-hm-legend', 'aria-hidden': 'true' }, [
|
||||||
h('span', { text: '少' }),
|
hmLessEl,
|
||||||
h('span', { className: 'trend-hm-swatch lv-0' }),
|
h('span', { className: 'trend-hm-swatch lv-0' }),
|
||||||
h('span', { className: 'trend-hm-swatch lv-1' }),
|
h('span', { className: 'trend-hm-swatch lv-1' }),
|
||||||
h('span', { className: 'trend-hm-swatch lv-2' }),
|
h('span', { className: 'trend-hm-swatch lv-2' }),
|
||||||
h('span', { className: 'trend-hm-swatch lv-3' }),
|
h('span', { className: 'trend-hm-swatch lv-3' }),
|
||||||
h('span', { className: 'trend-hm-swatch lv-4' }),
|
h('span', { className: 'trend-hm-swatch lv-4' }),
|
||||||
h('span', { text: '多' }),
|
hmMoreEl,
|
||||||
]);
|
]);
|
||||||
const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]);
|
const hmFooterEl = h('div', { className: 'trend-hm-footer' }, [hmSummaryEl, hmLegendEl]);
|
||||||
const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [
|
const heatmapStage = h('div', { className: 'trend-heatmap-stage', hidden: true }, [
|
||||||
@@ -349,6 +367,8 @@ export function createTrendAreaChart() {
|
|||||||
let currentPts = [];
|
let currentPts = [];
|
||||||
let currentIsHeatmap = false;
|
let currentIsHeatmap = false;
|
||||||
let currentHeatmapWeeks = 0;
|
let currentHeatmapWeeks = 0;
|
||||||
|
let currentHeatmapFirstDow = 0;
|
||||||
|
let currentHeatmapGapPx = 2;
|
||||||
let currentCellEls = [];
|
let currentCellEls = [];
|
||||||
let tickElsByIdx = new Map();
|
let tickElsByIdx = new Map();
|
||||||
let hoveredIdx = -1;
|
let hoveredIdx = -1;
|
||||||
@@ -357,7 +377,10 @@ export function createTrendAreaChart() {
|
|||||||
|
|
||||||
function populateTooltipContent(slot) {
|
function populateTooltipContent(slot) {
|
||||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||||
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
patchText(
|
||||||
|
tipCallsEl,
|
||||||
|
t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) })
|
||||||
|
);
|
||||||
const slotTok = safeSlotTokens(slot.tokens);
|
const slotTok = safeSlotTokens(slot.tokens);
|
||||||
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
|
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
|
||||||
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
|
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
|
||||||
@@ -377,7 +400,11 @@ export function createTrendAreaChart() {
|
|||||||
if (hasSubBreakdown) {
|
if (hasSubBreakdown) {
|
||||||
patchText(
|
patchText(
|
||||||
tipSubEl,
|
tipSubEl,
|
||||||
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
t('chart.step.ioSplit', {
|
||||||
|
inTok: formatTokensPrecise(safeSlotTokens(slot.inputTokens)),
|
||||||
|
cacheTok: formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)),
|
||||||
|
outTok: formatTokensPrecise(safeSlotTokens(slot.outputTokens)),
|
||||||
|
})
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -513,21 +540,117 @@ export function createTrendAreaChart() {
|
|||||||
showLineHoverAtIndex(idx);
|
showLineHoverAtIndex(idx);
|
||||||
}
|
}
|
||||||
|
|
||||||
function findHeatmapCellFromEvent(e) {
|
function findDirectHeatmapCell(e) {
|
||||||
let cur = e?.target || null;
|
let cur = e?.target || null;
|
||||||
while (cur && cur !== hmGridEl) {
|
while (cur && cur !== hmGridEl) {
|
||||||
const idxAttr = cur.getAttribute?.('data-slot-idx');
|
const idxAttr = cur.getAttribute?.('data-slot-idx');
|
||||||
if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') {
|
if (idxAttr !== null && idxAttr !== undefined && idxAttr !== '') {
|
||||||
return { idx: Number(idxAttr), cellEl: cur };
|
const idx = Number(idxAttr);
|
||||||
|
if (Number.isFinite(idx) && idx >= 0 && idx < currentSlots.length) {
|
||||||
|
return { idx, cellEl: cur };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
cur = cur.parentNode || null;
|
cur = cur.parentNode || null;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveHeatmapCellFromPointer(e) {
|
||||||
|
const directHit = findDirectHeatmapCell(e);
|
||||||
|
if (directHit) return directHit;
|
||||||
|
|
||||||
|
const clientX = Number(e?.clientX);
|
||||||
|
const clientY = Number(e?.clientY);
|
||||||
|
if (!Number.isFinite(clientX) || !Number.isFinite(clientY)) {
|
||||||
|
if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) {
|
||||||
|
return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rect = hmGridEl.getBoundingClientRect?.();
|
||||||
|
if (!rect || !(rect.width > 0) || !(rect.height > 0) || currentHeatmapWeeks <= 0) {
|
||||||
|
if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) {
|
||||||
|
return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const W = currentHeatmapWeeks;
|
||||||
|
const G = currentHeatmapGapPx;
|
||||||
|
const relX = clientX - rect.left;
|
||||||
|
const relY = clientY - rect.top;
|
||||||
|
if (
|
||||||
|
relX < -(G + 1) ||
|
||||||
|
relX > rect.width + G + 1 ||
|
||||||
|
relY < -(G + 1) ||
|
||||||
|
relY > rect.height + G + 1
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const pitchX = (rect.width + G) / W;
|
||||||
|
const pitchY = (rect.height + G) / 7;
|
||||||
|
const cellW = Math.max(1, pitchX - G);
|
||||||
|
const cellH = Math.max(1, pitchY - G);
|
||||||
|
|
||||||
|
function distanceToCell(c, r) {
|
||||||
|
const x0 = c * pitchX;
|
||||||
|
const y0 = r * pitchY;
|
||||||
|
const dx = relX < x0 ? x0 - relX : relX > x0 + cellW ? relX - (x0 + cellW) : 0;
|
||||||
|
const dy = relY < y0 ? y0 - relY : relY > y0 + cellH ? relY - (y0 + cellH) : 0;
|
||||||
|
return { chebyshev: Math.max(dx, dy), distSq: dx * dx + dy * dy };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 指针滑入当前悬停格四周的空隙(gap)时保持原高亮,彻底消除跨格空隙闪烁与边缘微抖
|
||||||
|
if (hoveredIdx >= 0 && hoveredIdx < currentSlots.length && currentCellEls[hoveredIdx]) {
|
||||||
|
const curGridPos = currentHeatmapFirstDow + hoveredIdx;
|
||||||
|
const curCol = Math.floor(curGridPos / 7);
|
||||||
|
const curRow = curGridPos % 7;
|
||||||
|
if (distanceToCell(curCol, curRow).chebyshev <= G + 0.75) {
|
||||||
|
return { idx: hoveredIdx, cellEl: currentCellEls[hoveredIdx] };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 快速扫过或初始落入格子间隙时,按网格步距吸附到最近的有效日期格
|
||||||
|
const approxCol = Math.max(0, Math.min(W - 1, Math.floor((relX + G * 0.5) / pitchX)));
|
||||||
|
const approxRow = Math.max(0, Math.min(6, Math.floor((relY + G * 0.5) / pitchY)));
|
||||||
|
const directSlotIdx = approxCol * 7 + approxRow - currentHeatmapFirstDow;
|
||||||
|
if (
|
||||||
|
directSlotIdx >= 0 &&
|
||||||
|
directSlotIdx < currentSlots.length &&
|
||||||
|
currentCellEls[directSlotIdx]
|
||||||
|
) {
|
||||||
|
return { idx: directSlotIdx, cellEl: currentCellEls[directSlotIdx] };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 首周补位或末周未来空白边缘:仅当仍在相邻有效格的间隙光晕内才吸附,深入纯空白角则清空
|
||||||
|
let bestIdx = -1;
|
||||||
|
let bestDistSq = Infinity;
|
||||||
|
for (let dc = -1; dc <= 1; dc++) {
|
||||||
|
const c = approxCol + dc;
|
||||||
|
if (c < 0 || c >= W) continue;
|
||||||
|
for (let dr = -1; dr <= 1; dr++) {
|
||||||
|
const r = approxRow + dr;
|
||||||
|
if (r < 0 || r > 6) continue;
|
||||||
|
const sIdx = c * 7 + r - currentHeatmapFirstDow;
|
||||||
|
if (sIdx < 0 || sIdx >= currentSlots.length || !currentCellEls[sIdx]) continue;
|
||||||
|
const d = distanceToCell(c, r);
|
||||||
|
if (d.chebyshev <= G + 1.5 && d.distSq < bestDistSq) {
|
||||||
|
bestDistSq = d.distSq;
|
||||||
|
bestIdx = sIdx;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (bestIdx >= 0) {
|
||||||
|
return { idx: bestIdx, cellEl: currentCellEls[bestIdx] };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function handleHeatmapPointer(e) {
|
function handleHeatmapPointer(e) {
|
||||||
if (!currentIsHeatmap || !currentSlots.length) return;
|
if (!currentIsHeatmap || !currentSlots.length) return;
|
||||||
const hit = findHeatmapCellFromEvent(e);
|
const hit = resolveHeatmapCellFromPointer(e);
|
||||||
if (!hit || !Number.isFinite(hit.idx)) {
|
if (!hit || !Number.isFinite(hit.idx)) {
|
||||||
clearHover();
|
clearHover();
|
||||||
return;
|
return;
|
||||||
@@ -630,19 +753,28 @@ export function createTrendAreaChart() {
|
|||||||
const nonZeroVals = [];
|
const nonZeroVals = [];
|
||||||
|
|
||||||
for (let i = 0; i < slots.length; i++) {
|
for (let i = 0; i < slots.length; i++) {
|
||||||
const t = safeSlotTokens(slots[i]?.tokens);
|
const tokVal = safeSlotTokens(slots[i]?.tokens);
|
||||||
if (t > 0) {
|
if (tokVal > 0) {
|
||||||
activeDays++;
|
activeDays++;
|
||||||
nonZeroVals.push(t);
|
nonZeroVals.push(tokVal);
|
||||||
}
|
}
|
||||||
if (t >= maxTokens) {
|
if (tokVal >= maxTokens) {
|
||||||
maxTokens = t;
|
maxTokens = tokVal;
|
||||||
peakIdx = i;
|
peakIdx = i;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const locale = getEffectiveLocale();
|
||||||
|
patchText(wdayMonEl, t('chart.trend.wdayMon'));
|
||||||
|
patchText(wdayWedEl, t('chart.trend.wdayWed'));
|
||||||
|
patchText(wdayFriEl, t('chart.trend.wdayFri'));
|
||||||
|
patchText(wdaySunEl, t('chart.trend.wdaySun'));
|
||||||
|
patchAttr(hmGridEl, 'aria-label', t('chart.trend.hmAria'));
|
||||||
|
patchText(hmLessEl, t('chart.trend.hmLess'));
|
||||||
|
patchText(hmMoreEl, t('chart.trend.hmMore'));
|
||||||
|
|
||||||
const sig =
|
const sig =
|
||||||
`${useHeatmap ? 'hm' : `line:${viewW}`}|` +
|
`${locale}|${useHeatmap ? 'hm' : `line:${viewW}`}|` +
|
||||||
slots
|
slots
|
||||||
.map(
|
.map(
|
||||||
(s) =>
|
(s) =>
|
||||||
@@ -664,10 +796,13 @@ export function createTrendAreaChart() {
|
|||||||
: 0;
|
: 0;
|
||||||
const totalCells = firstDow + slots.length;
|
const totalCells = firstDow + slots.length;
|
||||||
const totalWeeks = Math.max(1, Math.ceil(totalCells / 7));
|
const totalWeeks = Math.max(1, Math.ceil(totalCells / 7));
|
||||||
|
const gapPx = totalWeeks > 42 ? 1.5 : 2;
|
||||||
currentHeatmapWeeks = totalWeeks;
|
currentHeatmapWeeks = totalWeeks;
|
||||||
|
currentHeatmapFirstDow = firstDow;
|
||||||
|
currentHeatmapGapPx = gapPx;
|
||||||
|
|
||||||
patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks));
|
patchStyleVar(hmBodyEl, '--hm-weeks', String(totalWeeks));
|
||||||
patchStyleVar(hmBodyEl, '--hm-gap', totalWeeks > 42 ? '1.5px' : '2px');
|
patchStyleVar(hmBodyEl, '--hm-gap', `${gapPx}px`);
|
||||||
|
|
||||||
// 重建顶部对齐月份标签
|
// 重建顶部对齐月份标签
|
||||||
while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild);
|
while (hmMonthsEl.firstChild) hmMonthsEl.removeChild(hmMonthsEl.firstChild);
|
||||||
@@ -719,8 +854,13 @@ export function createTrendAreaChart() {
|
|||||||
const peakSlot = slots[peakIdx];
|
const peakSlot = slots[peakIdx];
|
||||||
const summaryText =
|
const summaryText =
|
||||||
maxTokens > 0 && peakSlot?.label
|
maxTokens > 0 && peakSlot?.label
|
||||||
? `活跃 ${activeDays}/${slots.length} 天 · 峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
? t('chart.trend.hmActivePeak', {
|
||||||
: `活跃 0/${slots.length} 天`;
|
active: activeDays,
|
||||||
|
total: slots.length,
|
||||||
|
label: peakSlot.label,
|
||||||
|
tokens: formatTokensPrecise(maxTokens),
|
||||||
|
})
|
||||||
|
: t('chart.trend.hmActiveZero', { total: slots.length });
|
||||||
patchText(hmSummaryEl, summaryText);
|
patchText(hmSummaryEl, summaryText);
|
||||||
|
|
||||||
if (hoveredIdx >= slots.length) {
|
if (hoveredIdx >= slots.length) {
|
||||||
@@ -819,7 +959,10 @@ export function createTrendAreaChart() {
|
|||||||
const peakSlot = slots[peakIdx];
|
const peakSlot = slots[peakIdx];
|
||||||
const peakText =
|
const peakText =
|
||||||
maxTokens > 0 && peakSlot?.label
|
maxTokens > 0 && peakSlot?.label
|
||||||
? `峰值 ${peakSlot.label} · ${formatTokensPrecise(maxTokens)}`
|
? t('chart.trend.peakPill', {
|
||||||
|
label: peakSlot.label,
|
||||||
|
tokens: formatTokensPrecise(maxTokens),
|
||||||
|
})
|
||||||
: formatTokensPrecise(maxTokens);
|
: formatTokensPrecise(maxTokens);
|
||||||
patchText(peakPill, peakText);
|
patchText(peakPill, peakText);
|
||||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100));
|
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / viewW) * 100));
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import { i18nStore, t } from '../../i18n/index.js';
|
|||||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
import {
|
import {
|
||||||
fetchTelemetry,
|
fetchTelemetry,
|
||||||
|
formatAgentBadgeText,
|
||||||
normalizeClientUpdateMode,
|
normalizeClientUpdateMode,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
triggerPluginUpdate,
|
triggerPluginUpdate,
|
||||||
@@ -106,20 +107,24 @@ export const TopSessionHeader = defineComponent({
|
|||||||
|
|
||||||
let lastActiveCascadeId = '';
|
let lastActiveCascadeId = '';
|
||||||
|
|
||||||
|
function syncSessionScopeOnCascadeChange(telemetry) {
|
||||||
|
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||||
|
if (!currentCascadeId) return;
|
||||||
|
if (lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||||
|
lastActiveCascadeId = currentCascadeId;
|
||||||
|
const uiSt = uiStore.getState();
|
||||||
|
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||||
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
lastActiveCascadeId = currentCascadeId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function renderHeaderState() {
|
function renderHeaderState() {
|
||||||
const telSt = telemetryStore.getState();
|
const telSt = telemetryStore.getState();
|
||||||
const uiSt = uiStore.getState();
|
const uiSt = uiStore.getState();
|
||||||
const telemetry = telSt.telemetry;
|
const telemetry = telSt.telemetry;
|
||||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
|
||||||
if (currentCascadeId && lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
|
||||||
lastActiveCascadeId = currentCascadeId;
|
|
||||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
} else if (currentCascadeId) {
|
|
||||||
lastActiveCascadeId = currentCascadeId;
|
|
||||||
}
|
|
||||||
if (!uiSt.monitorVisible) return;
|
if (!uiSt.monitorVisible) return;
|
||||||
|
|
||||||
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
patchAttr(updateBtn, 'aria-label', t('header.ariaUpdate'));
|
||||||
@@ -240,7 +245,7 @@ export const TopSessionHeader = defineComponent({
|
|||||||
} else if (isRunning) {
|
} else if (isRunning) {
|
||||||
const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning);
|
const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning);
|
||||||
const runSuffix =
|
const runSuffix =
|
||||||
hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : '';
|
hasSubagents && runningAgent ? ` · ${formatAgentBadgeText(runningAgent)}` : '';
|
||||||
patchSvgIcon(statusIcon, 'bolt');
|
patchSvgIcon(statusIcon, 'bolt');
|
||||||
patchText(statusText, t('header.statusGenerating', { suffix: runSuffix }));
|
patchText(statusText, t('header.statusGenerating', { suffix: runSuffix }));
|
||||||
patchClasses(statusTag, {
|
patchClasses(statusTag, {
|
||||||
@@ -277,7 +282,10 @@ export const TopSessionHeader = defineComponent({
|
|||||||
syncState: st.syncState,
|
syncState: st.syncState,
|
||||||
telemetry: st.telemetry,
|
telemetry: st.telemetry,
|
||||||
}),
|
}),
|
||||||
() => renderHeaderState()
|
(slice) => {
|
||||||
|
syncSessionScopeOnCascadeChange(slice.telemetry);
|
||||||
|
renderHeaderState();
|
||||||
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const unsubI18n = i18nStore.subscribe(
|
const unsubI18n = i18nStore.subscribe(
|
||||||
|
|||||||
@@ -8,32 +8,41 @@
|
|||||||
* 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。
|
* 在宿主切换会话重建顶栏 DOM 时始终保持组件实例、滚动位置与动画状态不丢失。
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
WINDOW_BRIDGE_KEY,
|
||||||
|
WINDOW_OVERLAY_KEY,
|
||||||
|
WINDOW_OVERLAY_METHODS,
|
||||||
|
readInjectedWindowBridge,
|
||||||
|
} from '../../../shared/window-bridge-protocol.mjs';
|
||||||
import { App } from '../../App.js';
|
import { App } from '../../App.js';
|
||||||
import { applyAppearanceToRoot } from '../../core/appearance.js';
|
import {
|
||||||
|
PANEL_SCALE_FACTORS,
|
||||||
|
applyAppearanceToRoot,
|
||||||
|
normalizeClientFontScale,
|
||||||
|
} from '../../core/appearance.js';
|
||||||
import {
|
import {
|
||||||
h,
|
h,
|
||||||
isEventInside,
|
isEventInside,
|
||||||
patchAttr,
|
patchAttr,
|
||||||
patchClasses,
|
patchClasses,
|
||||||
patchKeyedList,
|
|
||||||
patchText,
|
patchText,
|
||||||
} from '../../core/domPatch.js';
|
} from '../../core/domPatch.js';
|
||||||
import { formatElapsedSec } from '../../core/formatters.js';
|
|
||||||
import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js';
|
import { deliverCdpBridgeResponses, getWindowBridgeConfig } from '../../core/httpClient.js';
|
||||||
import { getEffectiveLocale, i18nStore, setI18nLanguage, t } from '../../i18n/index.js';
|
import { i18nStore, setI18nLanguage, t } from '../../i18n/index.js';
|
||||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
import {
|
import {
|
||||||
RING_CIRCUMFERENCE,
|
buildCapsuleSlotContext,
|
||||||
createCapsuleSlotNode,
|
createCapsuleSlotNode,
|
||||||
|
resolveMultiSessionCapsuleState,
|
||||||
syncCapsuleSlotNodes,
|
syncCapsuleSlotNodes,
|
||||||
} from '../widgets/CapsuleBarWidget.js';
|
} from '../widgets/CapsuleBarWidget.js';
|
||||||
|
import { LiveActivityWidget } from '../widgets/LiveActivityWidget.js';
|
||||||
import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js';
|
import { createDynamicWidgetHost } from '../../registries/widgetRegistry.js';
|
||||||
import {
|
import {
|
||||||
DEFAULT_CLIENT_HOVER_MODULES,
|
DEFAULT_CLIENT_HOVER_MODULES,
|
||||||
extractHostRouteCascadeId,
|
extractHostRouteCascadeId,
|
||||||
fetchTelemetry,
|
fetchTelemetry,
|
||||||
formatAgentBadgeText,
|
isMacHostPlatform,
|
||||||
getAgentBadgeClass,
|
|
||||||
normalizeClientHoverModules,
|
normalizeClientHoverModules,
|
||||||
normalizeClientPopoverWidth,
|
normalizeClientPopoverWidth,
|
||||||
normalizeClientPopoverWidthMode,
|
normalizeClientPopoverWidthMode,
|
||||||
@@ -813,7 +822,7 @@ function isImmediatelyBeforeNode(node, refNode) {
|
|||||||
function isIdeExtensionChatFrame() {
|
function isIdeExtensionChatFrame() {
|
||||||
try {
|
try {
|
||||||
if (typeof window === 'undefined') return false;
|
if (typeof window === 'undefined') return false;
|
||||||
if (window.__AGUsageMonitorBridge?.isIdeChatFrame === true) return true;
|
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
|
||||||
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
|
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
|
||||||
} catch {
|
} catch {
|
||||||
return false;
|
return false;
|
||||||
@@ -824,7 +833,7 @@ function resolveActiveDockTarget(options = undefined) {
|
|||||||
const settings = telemetryStore.getState().telemetry?.settings;
|
const settings = telemetryStore.getState().telemetry?.settings;
|
||||||
const rawMode =
|
const rawMode =
|
||||||
settings?.windowMountMode ??
|
settings?.windowMountMode ??
|
||||||
(typeof window !== 'undefined' ? window.__AGUsageMonitorBridge?.mountMode : undefined);
|
readInjectedWindowBridge()?.mountMode;
|
||||||
const mountMode =
|
const mountMode =
|
||||||
options?.mountMode ||
|
options?.mountMode ||
|
||||||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
|
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
|
||||||
@@ -925,14 +934,14 @@ export function mountWindowOverlay() {
|
|||||||
let carryOverMultiPinnedOpen = false;
|
let carryOverMultiPinnedOpen = false;
|
||||||
let carryOverPointer = null;
|
let carryOverPointer = null;
|
||||||
try {
|
try {
|
||||||
const prevOv = window.__AGUsageMonitorOverlay;
|
const prevOv = window[WINDOW_OVERLAY_KEY];
|
||||||
carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null;
|
carryOverTelemetry = prevOv?.getTelemetrySnapshot?.() || null;
|
||||||
carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.());
|
carryOverTooltipOpen = Boolean(prevOv?.isHoverOpen?.());
|
||||||
carryOverPopoverOpen = Boolean(prevOv?.isOpen?.());
|
carryOverPopoverOpen = Boolean(prevOv?.isOpen?.());
|
||||||
carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.());
|
carryOverMultiHoverOpen = Boolean(prevOv?.isMultiHoverOpen?.());
|
||||||
carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.());
|
carryOverMultiPinnedOpen = Boolean(prevOv?.isMultiPinnedOpen?.());
|
||||||
carryOverPointer = prevOv?.getLastPointer?.() || null;
|
carryOverPointer = prevOv?.getLastPointer?.() || null;
|
||||||
prevOv?.dispose?.();
|
prevOv?.[WINDOW_OVERLAY_METHODS.dispose]?.();
|
||||||
} catch {
|
} catch {
|
||||||
// 忽略旧实例卸载异常
|
// 忽略旧实例卸载异常
|
||||||
}
|
}
|
||||||
@@ -971,9 +980,6 @@ export function mountWindowOverlay() {
|
|||||||
let multiPinned = false;
|
let multiPinned = false;
|
||||||
let hoverLeaveTimer = null;
|
let hoverLeaveTimer = null;
|
||||||
let multiLeaveTimer = null;
|
let multiLeaveTimer = null;
|
||||||
const manualSubExpandMap = new Map();
|
|
||||||
const multiTimersMap = new Map();
|
|
||||||
let multiLiveTickTimer = null;
|
|
||||||
let hasPointerCoords = Boolean(
|
let hasPointerCoords = Boolean(
|
||||||
carryOverPointer &&
|
carryOverPointer &&
|
||||||
Number.isFinite(carryOverPointer.x) &&
|
Number.isFinite(carryOverPointer.x) &&
|
||||||
@@ -1071,52 +1077,6 @@ export function mountWindowOverlay() {
|
|||||||
}, 90);
|
}, 90);
|
||||||
}
|
}
|
||||||
|
|
||||||
function bindMultiElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
|
||||||
const now = Date.now();
|
|
||||||
const prev = multiTimersMap.get(timerKey);
|
|
||||||
let startMs = prev?.startMs || 0;
|
|
||||||
if (!prev || prev.sig !== sig) {
|
|
||||||
const validRaw = Number(rawStartMs || 0);
|
|
||||||
startMs = validRaw > 0 && validRaw <= now + 2000 ? validRaw : now;
|
|
||||||
} else if (startMs <= 0 && Number(rawStartMs) > 0 && Number(rawStartMs) <= now + 2000) {
|
|
||||||
startMs = Number(rawStartMs);
|
|
||||||
}
|
|
||||||
multiTimersMap.set(timerKey, { sig, startMs, el: targetEl });
|
|
||||||
const elapsedSec = Math.max(0, (now - startMs) / 1000);
|
|
||||||
patchText(targetEl, formatElapsedSec(elapsedSec));
|
|
||||||
}
|
|
||||||
|
|
||||||
function tickMultiElapsedDisplay() {
|
|
||||||
const now = Date.now();
|
|
||||||
for (const entry of multiTimersMap.values()) {
|
|
||||||
if (!entry?.el) continue;
|
|
||||||
const elapsedSec = entry.startMs > 0 ? Math.max(0, (now - entry.startMs) / 1000) : 0;
|
|
||||||
patchText(entry.el, formatElapsedSec(elapsedSec));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function pauseMultiLiveTicker() {
|
|
||||||
if (multiLiveTickTimer) {
|
|
||||||
clearInterval(multiLiveTickTimer);
|
|
||||||
multiLiveTickTimer = null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function stopMultiLiveTicker() {
|
|
||||||
pauseMultiLiveTicker();
|
|
||||||
multiTimersMap.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
function ensureMultiLiveTicker() {
|
|
||||||
if (multiTimersMap.size === 0) {
|
|
||||||
stopMultiLiveTicker();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (!multiLiveTickTimer) {
|
|
||||||
multiLiveTickTimer = setInterval(tickMultiElapsedDisplay, 1000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function inspectSessionInMonitor(cascadeId) {
|
function inspectSessionInMonitor(cascadeId) {
|
||||||
if (!cascadeId || cascadeId === 'current') return;
|
if (!cascadeId || cascadeId === 'current') return;
|
||||||
uiStore.setState({
|
uiStore.setState({
|
||||||
@@ -1374,8 +1334,6 @@ export function mountWindowOverlay() {
|
|||||||
portalShadow.appendChild(portalStyleEl);
|
portalShadow.appendChild(portalStyleEl);
|
||||||
|
|
||||||
const initialSettings = telemetryStore.getState().telemetry?.settings;
|
const initialSettings = telemetryStore.getState().telemetry?.settings;
|
||||||
applyAppearanceToRoot(capsuleHost, initialSettings, { includeFontScale: false });
|
|
||||||
applyAppearanceToRoot(portalHost, initialSettings, { includeFontScale: true });
|
|
||||||
|
|
||||||
// 悬停全景概览浮层(完全解耦至 widgetRegistry,由 hoverModules 动态驱动 0..4 个独立组件,零硬编码)
|
// 悬停全景概览浮层(完全解耦至 widgetRegistry,由 hoverModules 动态驱动 0..4 个独立组件,零硬编码)
|
||||||
const hoverUpdateVerText = h('span', { text: t('capsule.hoverNewVerGeneric') });
|
const hoverUpdateVerText = h('span', { text: t('capsule.hoverNewVerGeneric') });
|
||||||
@@ -1415,105 +1373,7 @@ export function mountWindowOverlay() {
|
|||||||
[hoverUpdateBar, hoverWidgetsContainer]
|
[hoverUpdateBar, hoverWidgetsContainer]
|
||||||
);
|
);
|
||||||
|
|
||||||
// 左侧多会话实时看板浮层(活跃运行会话卡片 + 近期多窗口会话速览,全槽位预占、就地补丁更新)
|
// 左侧多会话实时看板浮层(受控复用 LiveActivityWidget,保持零硬编码与同一套计时器状态机)
|
||||||
function createMultiLiveSubRow() {
|
|
||||||
const subBadge = h('span', {
|
|
||||||
className: 'agent-badge badge-sub-1',
|
|
||||||
text: t('fmt.subBadge', { index: 1 }),
|
|
||||||
});
|
|
||||||
const subRole = h('span', { className: 'live-sub-role', text: t('fmt.subAgent') });
|
|
||||||
const subSummary = h('span', { className: 'live-sub-summary', text: '' });
|
|
||||||
const subElapsed = h('span', { className: 'live-sub-elapsed text-mono', text: '0s' });
|
|
||||||
const rowEl = h('div', { className: 'live-sub-row' }, [
|
|
||||||
h('div', { className: 'live-sub-left' }, [subBadge, subRole, subSummary]),
|
|
||||||
subElapsed,
|
|
||||||
]);
|
|
||||||
return {
|
|
||||||
el: rowEl,
|
|
||||||
refs: { rowEl, subBadge, subRole, subSummary, subElapsed },
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function createMultiLiveTaskCard() {
|
|
||||||
const dotIcon = createSvgIcon('dot', { size: 11 });
|
|
||||||
patchClasses(dotIcon, { 'is-pulsing': true });
|
|
||||||
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
|
|
||||||
const titleEl = h('strong', { className: 'live-task-title', text: t('live.currentSession') });
|
|
||||||
const hereTagEl = h('span', {
|
|
||||||
className: 'wm-session-tag is-here',
|
|
||||||
hidden: true,
|
|
||||||
text: t('multi.hereTag'),
|
|
||||||
});
|
|
||||||
const metricsEl = h('span', {
|
|
||||||
className: 'wm-task-metrics text-mono',
|
|
||||||
hidden: true,
|
|
||||||
text: '',
|
|
||||||
});
|
|
||||||
const subToggleBtn = h('button', {
|
|
||||||
type: 'button',
|
|
||||||
className: 'live-sub-toggle',
|
|
||||||
hidden: true,
|
|
||||||
text: t('live.subToggleIdle', { total: 0, arrow: '▸' }),
|
|
||||||
});
|
|
||||||
const elapsedEl = h('span', {
|
|
||||||
className: 'live-activity-elapsed text-mono',
|
|
||||||
text: '0s',
|
|
||||||
});
|
|
||||||
|
|
||||||
const headerEl = h('div', { className: 'live-task-header' }, [
|
|
||||||
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl, hereTagEl]),
|
|
||||||
h('div', { className: 'live-task-header-right' }, [metricsEl, subToggleBtn, elapsedEl]),
|
|
||||||
]);
|
|
||||||
|
|
||||||
const mainBadge = h('span', {
|
|
||||||
className: 'agent-badge badge-main',
|
|
||||||
hidden: true,
|
|
||||||
text: t('fmt.mainBadge'),
|
|
||||||
});
|
|
||||||
const mainPhase = h('strong', { className: 'live-activity-phase', text: t('live.thinking') });
|
|
||||||
const mainProgress = h('span', {
|
|
||||||
className: 'live-activity-progress text-mono',
|
|
||||||
hidden: true,
|
|
||||||
text: '',
|
|
||||||
});
|
|
||||||
const mainSep = h('span', { className: 'live-activity-sep', hidden: true, text: '·' });
|
|
||||||
const mainDetail = h('span', {
|
|
||||||
className: 'live-activity-detail',
|
|
||||||
hidden: true,
|
|
||||||
text: '',
|
|
||||||
});
|
|
||||||
|
|
||||||
const mainRowEl = h('div', { className: 'live-task-main-row' }, [
|
|
||||||
mainBadge,
|
|
||||||
mainPhase,
|
|
||||||
mainProgress,
|
|
||||||
mainSep,
|
|
||||||
mainDetail,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const subListEl = h('div', { className: 'live-sub-list', hidden: true });
|
|
||||||
const cardEl = h('div', { className: 'live-task-card' }, [headerEl, mainRowEl, subListEl]);
|
|
||||||
|
|
||||||
return {
|
|
||||||
el: cardEl,
|
|
||||||
refs: {
|
|
||||||
cardEl,
|
|
||||||
dotIcon,
|
|
||||||
titleEl,
|
|
||||||
hereTagEl,
|
|
||||||
metricsEl,
|
|
||||||
subToggleBtn,
|
|
||||||
elapsedEl,
|
|
||||||
mainBadge,
|
|
||||||
mainPhase,
|
|
||||||
mainProgress,
|
|
||||||
mainSep,
|
|
||||||
mainDetail,
|
|
||||||
subListEl,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const multiPinBadge = h('span', {
|
const multiPinBadge = h('span', {
|
||||||
className: 'wm-pin-badge',
|
className: 'wm-pin-badge',
|
||||||
hidden: true,
|
hidden: true,
|
||||||
@@ -1530,10 +1390,16 @@ export function mountWindowOverlay() {
|
|||||||
multiEmptyTextEl,
|
multiEmptyTextEl,
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
const multiRunningListEl = h('div', {
|
const multiRunningWidget = LiveActivityWidget({
|
||||||
className: 'live-activity-list',
|
defaultExpandRunningSubs: true,
|
||||||
hidden: true,
|
showSessionExtras: true,
|
||||||
'aria-live': 'polite',
|
isVisibleFn: () => Boolean(multiOpen && !document.hidden && !disposed),
|
||||||
|
onSelectSession: inspectSessionInMonitor,
|
||||||
|
onLayoutChange: () => {
|
||||||
|
if (multiOpen) {
|
||||||
|
positionFloatingElements();
|
||||||
|
}
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const multiTitleTextEl = h('span', { text: t('multi.title') });
|
const multiTitleTextEl = h('span', { text: t('multi.title') });
|
||||||
@@ -1567,7 +1433,7 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
[multiHeaderEl, multiEmptyEl, multiRunningListEl]
|
[multiHeaderEl, multiEmptyEl, multiRunningWidget.el]
|
||||||
);
|
);
|
||||||
|
|
||||||
// 完整四标签悬浮容器
|
// 完整四标签悬浮容器
|
||||||
@@ -1584,9 +1450,19 @@ export function mountWindowOverlay() {
|
|||||||
[appInstance.el]
|
[appInstance.el]
|
||||||
);
|
);
|
||||||
|
|
||||||
|
function syncPortalAppearance(settings) {
|
||||||
|
applyAppearanceToRoot(capsuleHost, settings, { includeFontScale: false });
|
||||||
|
applyAppearanceToRoot(portalHost, settings, { includeFontScale: true });
|
||||||
|
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
||||||
|
popoverEl.setAttribute?.('data-font-scale', scaleKey);
|
||||||
|
hoverTipEl.setAttribute?.('data-font-scale', scaleKey);
|
||||||
|
multiPanelEl.setAttribute?.('data-font-scale', scaleKey);
|
||||||
|
}
|
||||||
|
|
||||||
portalShadow.appendChild(multiPanelEl);
|
portalShadow.appendChild(multiPanelEl);
|
||||||
portalShadow.appendChild(hoverTipEl);
|
portalShadow.appendChild(hoverTipEl);
|
||||||
portalShadow.appendChild(popoverEl);
|
portalShadow.appendChild(popoverEl);
|
||||||
|
syncPortalAppearance(initialSettings);
|
||||||
(document.body || document.documentElement).appendChild(portalHost);
|
(document.body || document.documentElement).appendChild(portalHost);
|
||||||
|
|
||||||
// --- 3. 几何测量、IDE 主题桥接、顶栏停靠与防溢出定位 ---
|
// --- 3. 几何测量、IDE 主题桥接、顶栏停靠与防溢出定位 ---
|
||||||
@@ -1759,6 +1635,8 @@ export function mountWindowOverlay() {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const isMac = () => isMacHostPlatform(telemetryStore.getState().telemetry);
|
||||||
|
|
||||||
function updateFixedFallbackPosition() {
|
function updateFixedFallbackPosition() {
|
||||||
const dockMode = capsuleHost.getAttribute('data-dock');
|
const dockMode = capsuleHost.getAttribute('data-dock');
|
||||||
if (dockMode === 'flow' || dockMode === 'ide-titlebar' || dockMode === 'composer') {
|
if (dockMode === 'flow' || dockMode === 'ide-titlebar' || dockMode === 'composer') {
|
||||||
@@ -1768,12 +1646,13 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const vw = Number(window.innerWidth || 1280);
|
const vw = Number(window.innerWidth || 1280);
|
||||||
let rightOffset = 144;
|
const minRight = isMac() ? 12 : 144;
|
||||||
|
let rightOffset = minRight;
|
||||||
const anchor = findNativeTopRightAnchor();
|
const anchor = findNativeTopRightAnchor();
|
||||||
if (anchor?.getBoundingClientRect) {
|
if (anchor?.getBoundingClientRect) {
|
||||||
const r = anchor.getBoundingClientRect();
|
const r = anchor.getBoundingClientRect();
|
||||||
if (r.width > 0 && r.left > 0 && r.left < vw) {
|
if (r.width > 0 && r.left > 0 && r.left < vw) {
|
||||||
rightOffset = Math.max(144, Math.ceil(vw - r.left + 6));
|
rightOffset = Math.max(minRight, Math.ceil(vw - r.left + 6));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
capsuleHost.style.top = '7px';
|
capsuleHost.style.top = '7px';
|
||||||
@@ -1783,6 +1662,16 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function syncCapsuleOsAttr() {
|
||||||
|
const nextOs = isMac() ? 'mac' : 'default';
|
||||||
|
if (capsuleHost.getAttribute('data-os') !== nextOs) {
|
||||||
|
patchAttr(capsuleHost, 'data-os', nextOs);
|
||||||
|
if (capsuleHost.getAttribute('data-dock') === 'fixed') {
|
||||||
|
updateFixedFallbackPosition();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function measureAvailableTitlebarWidth(dockTarget) {
|
function measureAvailableTitlebarWidth(dockTarget) {
|
||||||
try {
|
try {
|
||||||
const titlebar = dockTarget?.titlebar || null;
|
const titlebar = dockTarget?.titlebar || null;
|
||||||
@@ -1852,10 +1741,19 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!hasVisibleWindowControls && navigator?.windowControlsOverlay?.visible) {
|
if (navigator?.windowControlsOverlay?.visible) {
|
||||||
const wcoRect = navigator.windowControlsOverlay.getTitlebarAreaRect?.();
|
const wcoRect = navigator.windowControlsOverlay.getTitlebarAreaRect?.();
|
||||||
if (wcoRect && wcoRect.width > 0 && tbRect.right > wcoRect.right + 4) {
|
if (wcoRect && wcoRect.width > 0) {
|
||||||
rightSiblingsWidth += tbRect.right - wcoRect.right;
|
if (!hasVisibleWindowControls && tbRect.right > wcoRect.right + 4) {
|
||||||
|
rightSiblingsWidth += tbRect.right - wcoRect.right;
|
||||||
|
}
|
||||||
|
const leftOverlayInset = wcoRect.left - tbRect.left;
|
||||||
|
if (leftOverlayInset > leftContentWidth) {
|
||||||
|
leftContentWidth = Math.min(
|
||||||
|
Math.round(tbRect.width * 0.45),
|
||||||
|
Math.ceil(leftOverlayInset)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1868,10 +1766,11 @@ export function mountWindowOverlay() {
|
|||||||
if (tbRect.width > 0) {
|
if (tbRect.width > 0) {
|
||||||
const titleEl = titlebar.firstElementChild;
|
const titleEl = titlebar.firstElementChild;
|
||||||
const titleInner = titleEl?.firstElementChild;
|
const titleInner = titleEl?.firstElementChild;
|
||||||
|
const macTrafficReserve = isMac() ? 80 : 168;
|
||||||
const contentStart = titleInner?.getBoundingClientRect
|
const contentStart = titleInner?.getBoundingClientRect
|
||||||
? Math.max(8, titleInner.getBoundingClientRect().left - tbRect.left)
|
? Math.max(8, titleInner.getBoundingClientRect().left - tbRect.left)
|
||||||
: tbRect.left < 168
|
: tbRect.left < macTrafficReserve
|
||||||
? 168 - tbRect.left
|
? macTrafficReserve - tbRect.left
|
||||||
: 12;
|
: 12;
|
||||||
const minTitleWidth = 180;
|
const minTitleWidth = 180;
|
||||||
let siblingButtonsWidth = 64;
|
let siblingButtonsWidth = 64;
|
||||||
@@ -1925,8 +1824,17 @@ export function mountWindowOverlay() {
|
|||||||
const vh = Number(window.innerHeight || 800);
|
const vh = Number(window.innerHeight || 800);
|
||||||
const navRight = getLeftSidebarRightEdge(vw);
|
const navRight = getLeftSidebarRightEdge(vw);
|
||||||
const minLeft = navRight > 0 ? Math.max(12, navRight + 12) : 12;
|
const minLeft = navRight > 0 ? Math.max(12, navRight + 12) : 12;
|
||||||
const defaultCardW = Math.min(FLOATING_CARD_WIDTH, Math.max(280, vw - 24));
|
const curSettings = telemetryStore.getState().telemetry?.settings;
|
||||||
const defaultMultiW = Math.min(MULTI_PANEL_WIDTH, Math.max(280, vw - 24));
|
const panelScale =
|
||||||
|
PANEL_SCALE_FACTORS[normalizeClientFontScale(curSettings?.fontScale)] ?? 1;
|
||||||
|
const defaultCardW = Math.min(
|
||||||
|
Math.round(FLOATING_CARD_WIDTH * panelScale),
|
||||||
|
Math.max(280, vw - 24)
|
||||||
|
);
|
||||||
|
const defaultMultiW = Math.min(
|
||||||
|
Math.round(MULTI_PANEL_WIDTH * panelScale),
|
||||||
|
Math.max(280, vw - 24)
|
||||||
|
);
|
||||||
const isDockComposer = capsuleHost.getAttribute('data-dock') === 'composer';
|
const isDockComposer = capsuleHost.getAttribute('data-dock') === 'composer';
|
||||||
|
|
||||||
if (multiOpen) {
|
if (multiOpen) {
|
||||||
@@ -1974,9 +1882,8 @@ export function mountWindowOverlay() {
|
|||||||
|
|
||||||
if (popoverOpen) {
|
if (popoverOpen) {
|
||||||
const maxPopCardW = Math.max(280, vw - minLeft - 12);
|
const maxPopCardW = Math.max(280, vw - minLeft - 12);
|
||||||
const curSettings = telemetryStore.getState().telemetry?.settings;
|
|
||||||
const popWidthMode = normalizeClientPopoverWidthMode(curSettings?.popoverWidthMode);
|
const popWidthMode = normalizeClientPopoverWidthMode(curSettings?.popoverWidthMode);
|
||||||
let desiredPopW = Math.min(POPOVER_BASE_WIDTH, maxPopCardW);
|
let desiredPopW = Math.min(Math.round(POPOVER_BASE_WIDTH * panelScale), maxPopCardW);
|
||||||
if (popWidthMode === 'custom') {
|
if (popWidthMode === 'custom') {
|
||||||
desiredPopW = Math.min(
|
desiredPopW = Math.min(
|
||||||
normalizeClientPopoverWidth(curSettings?.popoverWidth),
|
normalizeClientPopoverWidth(curSettings?.popoverWidth),
|
||||||
@@ -2141,6 +2048,7 @@ export function mountWindowOverlay() {
|
|||||||
if (bodyOrDoc && !portalHost.isConnected) {
|
if (bodyOrDoc && !portalHost.isConnected) {
|
||||||
bodyOrDoc.appendChild(portalHost);
|
bodyOrDoc.appendChild(portalHost);
|
||||||
}
|
}
|
||||||
|
syncCapsuleOsAttr();
|
||||||
ensureWorkbenchThemeObserved();
|
ensureWorkbenchThemeObserved();
|
||||||
|
|
||||||
const dockTarget = resolveRuntimeDockTarget();
|
const dockTarget = resolveRuntimeDockTarget();
|
||||||
@@ -2309,12 +2217,13 @@ export function mountWindowOverlay() {
|
|||||||
patchAttr(multiPanelEl, 'hidden', !multiOpen);
|
patchAttr(multiPanelEl, 'hidden', !multiOpen);
|
||||||
if (multiOpen) {
|
if (multiOpen) {
|
||||||
renderCapsuleTelemetry();
|
renderCapsuleTelemetry();
|
||||||
|
multiRunningWidget.refs.resumeTicker();
|
||||||
positionFloatingElements();
|
positionFloatingElements();
|
||||||
if (typeof requestAnimationFrame === 'function') {
|
if (typeof requestAnimationFrame === 'function') {
|
||||||
requestAnimationFrame(() => positionFloatingElements());
|
requestAnimationFrame(() => positionFloatingElements());
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
pauseMultiLiveTicker();
|
multiRunningWidget.refs.pauseTicker();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2389,18 +2298,10 @@ export function mountWindowOverlay() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
|
function renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, hostRouteConversationId) {
|
||||||
if (manualSubExpandMap.size > 0) {
|
if (!multiOpen || document.hidden) {
|
||||||
const runningIds = new Set(rawRunningList.map((item) => item.cascadeId));
|
multiRunningWidget.refs.pauseTicker();
|
||||||
for (const id of manualSubExpandMap.keys()) {
|
return;
|
||||||
if (!runningIds.has(id)) manualSubExpandMap.delete(id);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (!multiOpen || document.hidden) return;
|
|
||||||
const localeKey = getEffectiveLocale();
|
|
||||||
const hostRouteLower = String(
|
|
||||||
hostRouteConversationId || extractHostRouteCascadeId() || ''
|
|
||||||
).toLowerCase();
|
|
||||||
|
|
||||||
patchText(
|
patchText(
|
||||||
multiRunningMetaEl,
|
multiRunningMetaEl,
|
||||||
runningCount > 0
|
runningCount > 0
|
||||||
@@ -2410,201 +2311,10 @@ export function mountWindowOverlay() {
|
|||||||
: t('multi.allIdle')
|
: t('multi.allIdle')
|
||||||
);
|
);
|
||||||
patchAttr(multiEmptyEl, 'hidden', runningCount > 0);
|
patchAttr(multiEmptyEl, 'hidden', runningCount > 0);
|
||||||
patchAttr(multiRunningListEl, 'hidden', runningCount === 0);
|
multiRunningWidget.refs.update({
|
||||||
|
items: rawRunningList,
|
||||||
if (runningCount === 0) {
|
hostRouteConversationId,
|
||||||
stopMultiLiveTicker();
|
});
|
||||||
patchKeyedList(multiRunningListEl, [], {});
|
|
||||||
} else {
|
|
||||||
const activeTimerKeys = new Set();
|
|
||||||
for (const item of rawRunningList) {
|
|
||||||
activeTimerKeys.add(`main:${item.cascadeId}`);
|
|
||||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
|
||||||
const runSubs = Number(item.runningSubagentCount || 0);
|
|
||||||
const isExp = manualSubExpandMap.has(item.cascadeId)
|
|
||||||
? manualSubExpandMap.get(item.cascadeId)
|
|
||||||
: runSubs > 0;
|
|
||||||
if (subCount > 0 && isExp) {
|
|
||||||
for (const sub of item.subagents || []) {
|
|
||||||
if (sub?.isRunning) {
|
|
||||||
activeTimerKeys.add(`sub:${sub.cascadeId}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
patchKeyedList(multiRunningListEl, rawRunningList, {
|
|
||||||
keyFn: (item) => item.cascadeId,
|
|
||||||
sigFn: (item) => {
|
|
||||||
const runSubs = Number(item.runningSubagentCount || 0);
|
|
||||||
const isExp = manualSubExpandMap.has(item.cascadeId)
|
|
||||||
? manualSubExpandMap.get(item.cascadeId)
|
|
||||||
: runSubs > 0;
|
|
||||||
const isHere =
|
|
||||||
Boolean(hostRouteLower) &&
|
|
||||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
|
||||||
const subSig = (item.subagents || [])
|
|
||||||
.map(
|
|
||||||
(s) =>
|
|
||||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
|
||||||
)
|
|
||||||
.join('|');
|
|
||||||
return `${localeKey}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${runSubs}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
|
||||||
},
|
|
||||||
createRow: createMultiLiveTaskCard,
|
|
||||||
updateRow: (refs, item) => {
|
|
||||||
const act = item.mainActivity || {
|
|
||||||
phase: 'thinking',
|
|
||||||
label: t('live.thinking'),
|
|
||||||
detail: '',
|
|
||||||
stepProgress: '',
|
|
||||||
startedAtMs: item.lastModifiedMs || 0,
|
|
||||||
signature: `fallback:${item.lastModifiedMs || 0}`,
|
|
||||||
};
|
|
||||||
const isWaiting = act.phase === 'waiting';
|
|
||||||
const isCompacting = act.phase === 'compacting';
|
|
||||||
patchClasses(refs.cardEl, {
|
|
||||||
'is-waiting': isWaiting,
|
|
||||||
'is-compacting': isCompacting,
|
|
||||||
});
|
|
||||||
patchClasses(refs.dotIcon, { 'is-pulsing': true });
|
|
||||||
|
|
||||||
const convTitle =
|
|
||||||
item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
|
|
||||||
patchText(refs.titleEl, convTitle);
|
|
||||||
patchAttr(refs.titleEl, 'title', t('multi.inspectSessionTitle', { title: convTitle }));
|
|
||||||
refs.titleEl.onclick = (e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
inspectSessionInMonitor(item.cascadeId);
|
|
||||||
};
|
|
||||||
|
|
||||||
const isHere =
|
|
||||||
Boolean(hostRouteLower) &&
|
|
||||||
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
|
||||||
patchText(refs.hereTagEl, t('multi.hereTag'));
|
|
||||||
patchAttr(refs.hereTagEl, 'hidden', !isHere);
|
|
||||||
|
|
||||||
const metricParts = [];
|
|
||||||
if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) {
|
|
||||||
metricParts.push(
|
|
||||||
`${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s`
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) {
|
|
||||||
metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`);
|
|
||||||
}
|
|
||||||
const metricsStr = metricParts.join(' · ');
|
|
||||||
patchAttr(refs.metricsEl, 'hidden', !metricsStr);
|
|
||||||
if (metricsStr) {
|
|
||||||
patchText(refs.metricsEl, metricsStr);
|
|
||||||
}
|
|
||||||
|
|
||||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
|
||||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
|
||||||
const isExpanded = manualSubExpandMap.has(item.cascadeId)
|
|
||||||
? manualSubExpandMap.get(item.cascadeId)
|
|
||||||
: runSubCount > 0;
|
|
||||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
|
||||||
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
|
||||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
|
||||||
if (subCount > 0) {
|
|
||||||
const arrow = isExpanded ? '▾' : '▸';
|
|
||||||
const toggleText =
|
|
||||||
runSubCount > 0
|
|
||||||
? t('live.subToggleRunning', { run: runSubCount, total: subCount, arrow })
|
|
||||||
: t('live.subToggleIdle', { total: subCount, arrow });
|
|
||||||
patchText(refs.subToggleBtn, toggleText);
|
|
||||||
patchClasses(refs.subToggleBtn, { 'is-expanded': isExpanded });
|
|
||||||
refs.subToggleBtn.onclick = (e) => {
|
|
||||||
e.stopPropagation();
|
|
||||||
manualSubExpandMap.set(item.cascadeId, !isExpanded);
|
|
||||||
renderCapsuleTelemetry();
|
|
||||||
if (multiOpen) {
|
|
||||||
positionFloatingElements();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const mainTimerKey = `main:${item.cascadeId}`;
|
|
||||||
activeTimerKeys.add(mainTimerKey);
|
|
||||||
bindMultiElapsedTimer(
|
|
||||||
mainTimerKey,
|
|
||||||
`${item.cascadeId}:${act.signature || act.label}`,
|
|
||||||
act.startedAtMs,
|
|
||||||
refs.elapsedEl
|
|
||||||
);
|
|
||||||
|
|
||||||
patchText(refs.mainPhase, act.label || t('live.thinking'));
|
|
||||||
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
|
|
||||||
patchAttr(refs.mainProgress, 'hidden', !progText);
|
|
||||||
if (progText) {
|
|
||||||
patchText(refs.mainProgress, progText);
|
|
||||||
}
|
|
||||||
|
|
||||||
const detailStr = act.detail || '';
|
|
||||||
patchAttr(refs.mainSep, 'hidden', !detailStr);
|
|
||||||
patchAttr(refs.mainDetail, 'hidden', !detailStr);
|
|
||||||
patchText(refs.mainDetail, detailStr);
|
|
||||||
|
|
||||||
const showSubs = subCount > 0 && isExpanded;
|
|
||||||
patchAttr(refs.subListEl, 'hidden', !showSubs);
|
|
||||||
if (showSubs) {
|
|
||||||
const subItems = item.subagents || [];
|
|
||||||
patchKeyedList(refs.subListEl, subItems, {
|
|
||||||
keyFn: (sub) => sub.cascadeId,
|
|
||||||
sigFn: (sub) =>
|
|
||||||
`${localeKey}:${sub.cascadeId}:${sub.role}:${sub.isRunning}:${sub.stepCount}:${sub.liveActivity?.signature || ''}:${sub.isRunning ? multiTimersMap.has(`sub:${sub.cascadeId}`) : true}`,
|
|
||||||
createRow: createMultiLiveSubRow,
|
|
||||||
updateRow: (subRefs, sub) => {
|
|
||||||
const subAct = sub.liveActivity || {
|
|
||||||
phase: sub.isRunning ? 'thinking' : 'done',
|
|
||||||
label: sub.isRunning ? t('live.thinking') : t('live.done'),
|
|
||||||
detail: '',
|
|
||||||
stepProgress: '',
|
|
||||||
startedAtMs: sub.lastModifiedMs || 0,
|
|
||||||
};
|
|
||||||
patchClasses(subRefs.rowEl, { 'is-done': !sub.isRunning });
|
|
||||||
const subBadgeCls = getAgentBadgeClass(sub.index || 1, false);
|
|
||||||
patchAttr(subRefs.subBadge, 'class', `agent-badge ${subBadgeCls}`);
|
|
||||||
patchText(subRefs.subBadge, formatAgentBadgeText(sub));
|
|
||||||
patchText(subRefs.subRole, sub.role || sub.shortLabel || t('fmt.subAgent'));
|
|
||||||
|
|
||||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
|
||||||
const summaryText = sub.isRunning
|
|
||||||
? `${subAct.label || t('live.running')}${subProg}${subAct.detail ? ` · ${subAct.detail}` : ''}`
|
|
||||||
: t('live.doneWithSteps', { steps: sub.stepCount || 0 });
|
|
||||||
patchText(subRefs.subSummary, summaryText);
|
|
||||||
|
|
||||||
const subTimerKey = `sub:${sub.cascadeId}`;
|
|
||||||
if (sub.isRunning) {
|
|
||||||
activeTimerKeys.add(subTimerKey);
|
|
||||||
bindMultiElapsedTimer(
|
|
||||||
subTimerKey,
|
|
||||||
`${sub.cascadeId}:${subAct.signature || subAct.label}`,
|
|
||||||
subAct.startedAtMs || sub.lastModifiedMs,
|
|
||||||
subRefs.subElapsed
|
|
||||||
);
|
|
||||||
} else {
|
|
||||||
multiTimersMap.delete(subTimerKey);
|
|
||||||
patchText(
|
|
||||||
subRefs.subElapsed,
|
|
||||||
t('header.convMetaSteps', { count: sub.stepCount || 0 })
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
for (const k of [...multiTimersMap.keys()]) {
|
|
||||||
if (!activeTimerKeys.has(k)) {
|
|
||||||
multiTimersMap.delete(k);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ensureMultiLiveTicker();
|
|
||||||
tickMultiElapsedDisplay();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderHoverWidgets() {
|
function renderHoverWidgets() {
|
||||||
@@ -2624,8 +2334,8 @@ export function mountWindowOverlay() {
|
|||||||
const telemetry = telSt.telemetry;
|
const telemetry = telSt.telemetry;
|
||||||
|
|
||||||
setI18nLanguage(telemetry?.settings?.language);
|
setI18nLanguage(telemetry?.settings?.language);
|
||||||
applyAppearanceToRoot(capsuleHost, telemetry?.settings, { includeFontScale: false });
|
syncPortalAppearance(telemetry?.settings);
|
||||||
applyAppearanceToRoot(portalHost, telemetry?.settings, { includeFontScale: true });
|
syncCapsuleOsAttr();
|
||||||
|
|
||||||
const showMulti = telemetry?.settings?.showTopbarMultiSession !== false;
|
const showMulti = telemetry?.settings?.showTopbarMultiSession !== false;
|
||||||
patchAttr(multiBtn, 'hidden', !showMulti);
|
patchAttr(multiBtn, 'hidden', !showMulti);
|
||||||
@@ -2647,7 +2357,7 @@ export function mountWindowOverlay() {
|
|||||||
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
|
patchClasses(multiBtn, { 'is-running': false, 'is-waiting': false });
|
||||||
patchText(multiLabel, t('capsule.multiZero'));
|
patchText(multiLabel, t('capsule.multiZero'));
|
||||||
patchText(multiRunningMetaEl, t('multi.loading'));
|
patchText(multiRunningMetaEl, t('multi.loading'));
|
||||||
stopMultiLiveTicker();
|
multiRunningWidget.refs.stopLiveTicker();
|
||||||
|
|
||||||
applyCapsuleSlots(slotKeys, { hasTelemetry: false });
|
applyCapsuleSlots(slotKeys, { hasTelemetry: false });
|
||||||
return;
|
return;
|
||||||
@@ -2660,138 +2370,36 @@ export function mountWindowOverlay() {
|
|||||||
uiSt.selectedAgentScope,
|
uiSt.selectedAgentScope,
|
||||||
uiSt.ctxInspectorAgentId
|
uiSt.ctxInspectorAgentId
|
||||||
);
|
);
|
||||||
const activeConv = telemetry.activeConversation || {};
|
const overviewActive = overviewScopedConv || telemetry.activeConversation || {};
|
||||||
const overviewActive = overviewScopedConv || activeConv;
|
const slotCtx = buildCapsuleSlotContext(telemetry, {
|
||||||
const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {};
|
scopedConv: capsuleScopedConv,
|
||||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
overviewConv: overviewActive,
|
||||||
const totalTokens = Number(ctx.totalTokens || 0);
|
ctxAgent,
|
||||||
const usedPct =
|
aggregated,
|
||||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
});
|
||||||
const dashOffset = +(
|
const { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText } =
|
||||||
RING_CIRCUMFERENCE *
|
resolveMultiSessionCapsuleState(telemetry, {
|
||||||
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
|
agents,
|
||||||
).toFixed(2);
|
aggregated,
|
||||||
// --- 4a. 同步左侧多会话实时状态胶囊与浮层看板 ---
|
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
||||||
const rawRunningList =
|
contextUsedPct: slotCtx.usedPct,
|
||||||
Array.isArray(telemetry.runningConversations) && telemetry.runningConversations.length > 0
|
});
|
||||||
? telemetry.runningConversations
|
|
||||||
: activeConv.isRunning || aggregated?.isRunning
|
|
||||||
? [
|
|
||||||
{
|
|
||||||
cascadeId: activeConv.cascadeId || 'current',
|
|
||||||
title: activeConv.title || t('live.currentSession'),
|
|
||||||
isCurrentSelected: true,
|
|
||||||
isMainRunning: Boolean(activeConv.isRunning),
|
|
||||||
isRunning: true,
|
|
||||||
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
|
|
||||||
subagentCount: Math.max(0, (agents?.length || 1) - 1),
|
|
||||||
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
|
|
||||||
latestTokPerSec: overviewActive.latestTokPerSec ?? null,
|
|
||||||
contextUsedPct: usedPct,
|
|
||||||
subagents: (agents || [])
|
|
||||||
.filter((a) => !a.isMain)
|
|
||||||
.map((s, idx) => ({
|
|
||||||
cascadeId: s.cascadeId || s.agentId,
|
|
||||||
index: s.index || idx + 1,
|
|
||||||
badgeText: s.badgeText || t('fmt.subBadge', { index: idx + 1 }),
|
|
||||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
|
||||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
|
||||||
isRunning: Boolean(s.isRunning),
|
|
||||||
stepCount: Number(s.stepCount || 0),
|
|
||||||
lastModifiedMs: s.lastModifiedMs || 0,
|
|
||||||
liveActivity: s.liveActivity || {
|
|
||||||
phase: s.isRunning ? 'thinking' : 'done',
|
|
||||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
|
||||||
detail: '',
|
|
||||||
stepProgress: '',
|
|
||||||
startedAtMs: s.lastModifiedMs || 0,
|
|
||||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
|
||||||
},
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const runningCount = rawRunningList.length;
|
|
||||||
const runningSubCount = rawRunningList.reduce(
|
|
||||||
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
|
||||||
0
|
|
||||||
);
|
|
||||||
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
|
||||||
|
|
||||||
patchClasses(multiBtn, {
|
patchClasses(multiBtn, {
|
||||||
'is-running': runningCount > 0 && !hasWaiting,
|
'is-running': runningCount > 0 && !hasWaiting,
|
||||||
'is-waiting': runningCount > 0 && hasWaiting,
|
'is-waiting': runningCount > 0 && hasWaiting,
|
||||||
});
|
});
|
||||||
const multiBtnText =
|
|
||||||
runningCount > 0
|
|
||||||
? runningSubCount > 0
|
|
||||||
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
|
||||||
: t('capsule.multiRunning', { count: runningCount })
|
|
||||||
: t('capsule.multiZero');
|
|
||||||
patchText(multiLabel, multiBtnText);
|
patchText(multiLabel, multiBtnText);
|
||||||
|
|
||||||
renderMultiRunningPanel(rawRunningList, runningCount, runningSubCount, telSt.hostRouteConversationId);
|
renderMultiRunningPanel(
|
||||||
|
rawRunningList,
|
||||||
|
runningCount,
|
||||||
|
runningSubCount,
|
||||||
|
telSt.hostRouteConversationId
|
||||||
|
);
|
||||||
|
|
||||||
// --- 4b. 同步右侧 1..5 动态槽位胶囊与组件化悬停浮层 ---
|
patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
|
||||||
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
|
applyCapsuleSlots(slotKeys, slotCtx);
|
||||||
const capActive = capsuleScopedConv || aggregated || activeConv || {};
|
|
||||||
const tps =
|
|
||||||
capsuleScopedConv?.latestTokPerSec ??
|
|
||||||
aggregated?.latestTokPerSec ??
|
|
||||||
activeConv.latestTokPerSec ??
|
|
||||||
null;
|
|
||||||
const avgTps =
|
|
||||||
capsuleScopedConv?.avgTokPerSec ??
|
|
||||||
aggregated?.avgTokPerSec ??
|
|
||||||
activeConv.avgTokPerSec ??
|
|
||||||
null;
|
|
||||||
const ttft =
|
|
||||||
capsuleScopedConv?.latestTtftSec ??
|
|
||||||
aggregated?.latestTtftSec ??
|
|
||||||
activeConv.latestTtftSec ??
|
|
||||||
null;
|
|
||||||
const capsuleStepCost =
|
|
||||||
capsuleScopedConv?.latestStepCostUsd ??
|
|
||||||
aggregated?.latestStepCostUsd ??
|
|
||||||
activeConv.latestStepCostUsd ??
|
|
||||||
null;
|
|
||||||
const sessionCost =
|
|
||||||
capsuleScopedConv?.sessionCostUsd ??
|
|
||||||
aggregated?.sessionCostUsd ??
|
|
||||||
activeConv.sessionCostUsd ??
|
|
||||||
null;
|
|
||||||
const cacheHitPct =
|
|
||||||
Number(capActive.stepCount || 0) > 0
|
|
||||||
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
|
|
||||||
: null;
|
|
||||||
const latestPromptTokens = capActive.latestPromptTokens ?? null;
|
|
||||||
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
|
|
||||||
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
|
|
||||||
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
|
|
||||||
const sessionTokens =
|
|
||||||
Number(capActive.stepCount || 0) > 0 ||
|
|
||||||
capActive.totalTokens != null ||
|
|
||||||
capInTok + capCacheTok + capOutTok > 0
|
|
||||||
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
|
|
||||||
: null;
|
|
||||||
|
|
||||||
patchClasses(capsuleBtn, { 'is-running': isRunning });
|
|
||||||
applyCapsuleSlots(slotKeys, {
|
|
||||||
hasTelemetry: true,
|
|
||||||
usedPct,
|
|
||||||
dashOffset,
|
|
||||||
isRunning,
|
|
||||||
tps,
|
|
||||||
avgTps,
|
|
||||||
ttft,
|
|
||||||
stepCost: capsuleStepCost,
|
|
||||||
sessionCost,
|
|
||||||
cacheHitPct,
|
|
||||||
latestPromptTokens,
|
|
||||||
sessionTokens,
|
|
||||||
quotas: telemetry.quotas,
|
|
||||||
});
|
|
||||||
|
|
||||||
const updateMode = normalizeClientUpdateMode(
|
const updateMode = normalizeClientUpdateMode(
|
||||||
telemetry.settings?.pluginUpdateMode,
|
telemetry.settings?.pluginUpdateMode,
|
||||||
@@ -2968,7 +2576,7 @@ export function mountWindowOverlay() {
|
|||||||
const onVisibilityChange = () => {
|
const onVisibilityChange = () => {
|
||||||
if (document.hidden) {
|
if (document.hidden) {
|
||||||
uiStore.setState({ monitorVisible: false });
|
uiStore.setState({ monitorVisible: false });
|
||||||
pauseMultiLiveTicker();
|
multiRunningWidget.refs.pauseTicker();
|
||||||
hasPointerCoords = false;
|
hasPointerCoords = false;
|
||||||
if (tooltipOpen) {
|
if (tooltipOpen) {
|
||||||
setTooltipOpen(false);
|
setTooltipOpen(false);
|
||||||
@@ -3070,28 +2678,28 @@ export function mountWindowOverlay() {
|
|||||||
|
|
||||||
const handle = {
|
const handle = {
|
||||||
bundleVersion,
|
bundleVersion,
|
||||||
ensureAlive() {
|
[WINDOW_OVERLAY_METHODS.ensureAlive]() {
|
||||||
if (disposed) return false;
|
if (disposed) return false;
|
||||||
return ensureCapsuleDocked();
|
return ensureCapsuleDocked();
|
||||||
},
|
},
|
||||||
syncHostRoute() {
|
[WINDOW_OVERLAY_METHODS.syncHostRoute]() {
|
||||||
if (disposed) return false;
|
if (disposed) return false;
|
||||||
syncHostRouteIfChanged();
|
syncHostRouteIfChanged();
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
updateBridge(nextBridge) {
|
[WINDOW_OVERLAY_METHODS.updateBridge](nextBridge) {
|
||||||
if (disposed || !nextBridge || typeof nextBridge !== 'object') return false;
|
if (disposed || !nextBridge || typeof nextBridge !== 'object') return false;
|
||||||
const port = Number(nextBridge.port || 0);
|
const port = Number(nextBridge.port || 0);
|
||||||
const token = String(nextBridge.token || '');
|
const token = String(nextBridge.token || '');
|
||||||
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
if (!Number.isInteger(port) || port <= 0 || !token) return false;
|
||||||
const cur = window.__AGUsageMonitorBridge || {};
|
const cur = readInjectedWindowBridge() || {};
|
||||||
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
|
const portChanged = Number(cur.port || 0) !== port || String(cur.token || '') !== token;
|
||||||
cur.port = port;
|
cur.port = port;
|
||||||
cur.token = token;
|
cur.token = token;
|
||||||
if (portChanged) {
|
if (portChanged) {
|
||||||
cur.transportMode = 'http';
|
cur.transportMode = 'http';
|
||||||
}
|
}
|
||||||
window.__AGUsageMonitorBridge = cur;
|
window[WINDOW_BRIDGE_KEY] = cur;
|
||||||
void fetchTelemetry({ force: false });
|
void fetchTelemetry({ force: false });
|
||||||
return true;
|
return true;
|
||||||
},
|
},
|
||||||
@@ -3101,7 +2709,7 @@ export function mountWindowOverlay() {
|
|||||||
getLastPointer() {
|
getLastPointer() {
|
||||||
return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null;
|
return hasPointerCoords ? { x: lastPointerX, y: lastPointerY } : null;
|
||||||
},
|
},
|
||||||
deliverRpc(responses) {
|
[WINDOW_OVERLAY_METHODS.deliverRpc](responses) {
|
||||||
if (disposed) return 0;
|
if (disposed) return 0;
|
||||||
return deliverCdpBridgeResponses(responses);
|
return deliverCdpBridgeResponses(responses);
|
||||||
},
|
},
|
||||||
@@ -3126,14 +2734,13 @@ export function mountWindowOverlay() {
|
|||||||
isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned),
|
isMultiHoverOpen: () => Boolean(multiOpen && !multiPinned),
|
||||||
isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned),
|
isMultiPinnedOpen: () => Boolean(multiOpen && multiPinned),
|
||||||
getLayoutMode: () => layoutMode,
|
getLayoutMode: () => layoutMode,
|
||||||
getDockKind: () => String(capsuleHost.getAttribute('data-dock') || ''),
|
[WINDOW_OVERLAY_METHODS.getDockKind]: () => String(capsuleHost.getAttribute('data-dock') || ''),
|
||||||
getMountMode: () => lastAppliedMountMode,
|
[WINDOW_OVERLAY_METHODS.getMountMode]: () => lastAppliedMountMode,
|
||||||
applyMountMode(nextMode) {
|
[WINDOW_OVERLAY_METHODS.applyMountMode](nextMode) {
|
||||||
if (disposed) return false;
|
if (disposed) return false;
|
||||||
const normalized = normalizeClientWindowMountMode(nextMode, nextMode !== 'sidebar');
|
const normalized = normalizeClientWindowMountMode(nextMode, nextMode !== 'sidebar');
|
||||||
if (typeof window !== 'undefined' && window.__AGUsageMonitorBridge) {
|
const bridgeConfig = readInjectedWindowBridge();
|
||||||
window.__AGUsageMonitorBridge.mountMode = normalized;
|
if (bridgeConfig) bridgeConfig.mountMode = normalized;
|
||||||
}
|
|
||||||
const curTel = telemetryStore.getState().telemetry;
|
const curTel = telemetryStore.getState().telemetry;
|
||||||
if (curTel?.settings) {
|
if (curTel?.settings) {
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
@@ -3150,7 +2757,7 @@ export function mountWindowOverlay() {
|
|||||||
lastAppliedMountMode = normalized;
|
lastAppliedMountMode = normalized;
|
||||||
return ensureCapsuleDocked();
|
return ensureCapsuleDocked();
|
||||||
},
|
},
|
||||||
dispose() {
|
[WINDOW_OVERLAY_METHODS.dispose]() {
|
||||||
if (disposed) return;
|
if (disposed) return;
|
||||||
disposed = true;
|
disposed = true;
|
||||||
clearInterval(watchdogTimer);
|
clearInterval(watchdogTimer);
|
||||||
@@ -3162,7 +2769,7 @@ export function mountWindowOverlay() {
|
|||||||
clearTimeout(multiLeaveTimer);
|
clearTimeout(multiLeaveTimer);
|
||||||
multiLeaveTimer = null;
|
multiLeaveTimer = null;
|
||||||
}
|
}
|
||||||
stopMultiLiveTicker();
|
multiRunningWidget.refs.stopLiveTicker();
|
||||||
if (dockRafId && typeof cancelAnimationFrame === 'function') {
|
if (dockRafId && typeof cancelAnimationFrame === 'function') {
|
||||||
cancelAnimationFrame(dockRafId);
|
cancelAnimationFrame(dockRafId);
|
||||||
dockRafId = 0;
|
dockRafId = 0;
|
||||||
@@ -3203,12 +2810,12 @@ export function mountWindowOverlay() {
|
|||||||
try {
|
try {
|
||||||
portalHost.remove();
|
portalHost.remove();
|
||||||
} catch {}
|
} catch {}
|
||||||
if (window.__AGUsageMonitorOverlay === handle) {
|
if (window[WINDOW_OVERLAY_KEY] === handle) {
|
||||||
delete window.__AGUsageMonitorOverlay;
|
delete window[WINDOW_OVERLAY_KEY];
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
window.__AGUsageMonitorOverlay = handle;
|
window[WINDOW_OVERLAY_KEY] = handle;
|
||||||
return handle;
|
return handle;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,303 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Shared CDP / Window Bridge diagnostic & one-click relaunch card (`BridgeStatusNotice.js`).
|
||||||
|
* Surfaces automatic shortcut provisioning status and a one-click host relaunch button when
|
||||||
|
* Antigravity 2.33.0+ runs without an active `DevToolsActivePort` (`no_devtools_port` / `cdp_unreachable`).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { defineComponent } from '../../core/component.js';
|
||||||
|
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||||
|
import { isWindowOverlayMode } from '../../core/httpClient.js';
|
||||||
|
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
|
import { t } from '../../i18n/index.js';
|
||||||
|
import { triggerBridgeHostRelaunch } from '../../store/telemetryStore.js';
|
||||||
|
|
||||||
|
const LAUNCH_FLAG_TEXT = '--remote-debugging-port=0';
|
||||||
|
|
||||||
|
async function copyTextToClipboard(text) {
|
||||||
|
try {
|
||||||
|
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
|
||||||
|
await navigator.clipboard.writeText(text);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fallback to temporary textarea inside restricted webview contexts
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (typeof document === 'undefined' || !document.body) return false;
|
||||||
|
const area = document.createElement('textarea');
|
||||||
|
area.value = text;
|
||||||
|
area.setAttribute('readonly', 'true');
|
||||||
|
area.style.cssText = 'position:fixed;left:-9999px;top:-9999px;opacity:0;';
|
||||||
|
document.body.appendChild(area);
|
||||||
|
area.select?.();
|
||||||
|
const ok = Boolean(document.execCommand?.('copy'));
|
||||||
|
document.body.removeChild(area);
|
||||||
|
return ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BridgeStatusNotice = defineComponent({
|
||||||
|
name: 'BridgeStatusNotice',
|
||||||
|
setup({ props, onCleanup }) {
|
||||||
|
let contextMode = Boolean(props?.contextMode);
|
||||||
|
const dismissible = Boolean(props?.dismissible);
|
||||||
|
let lastPayload = {
|
||||||
|
visible: false,
|
||||||
|
windowBridge: null,
|
||||||
|
hostPlatform: 'win32',
|
||||||
|
};
|
||||||
|
let dismissed = false;
|
||||||
|
let copied = false;
|
||||||
|
let copiedTimer = null;
|
||||||
|
let relaunchState = 'idle'; // 'idle' | 'relaunching' | 'failed'
|
||||||
|
let relaunchResetTimer = null;
|
||||||
|
let destroyed = false;
|
||||||
|
|
||||||
|
const headIconEl = createSvgIcon('warning', { size: 13, className: 'settings-bridge-icon' });
|
||||||
|
const titleEl = h('strong', { className: 'settings-bridge-title', text: '' });
|
||||||
|
const bodyEl = h('p', { className: 'settings-bridge-desc', text: '' });
|
||||||
|
|
||||||
|
const dismissBtnEl = dismissible
|
||||||
|
? h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'btn-ghost-sm settings-bridge-dismiss-btn',
|
||||||
|
'aria-label': t('settings.bridge.dismissAria'),
|
||||||
|
title: t('settings.bridge.dismissAria'),
|
||||||
|
onClick: () => {
|
||||||
|
dismissed = true;
|
||||||
|
render();
|
||||||
|
props?.onDismiss?.();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[createSvgIcon('close', { size: 11 })]
|
||||||
|
)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const relaunchBtnIconEl = createSvgIcon('refresh', { size: 11 });
|
||||||
|
const relaunchBtnTextEl = h('span', {
|
||||||
|
className: 'settings-bridge-relaunch-text',
|
||||||
|
text: t('settings.bridge.relaunchBtn'),
|
||||||
|
});
|
||||||
|
const relaunchBtnEl = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'settings-bridge-relaunch-btn',
|
||||||
|
onClick: async () => {
|
||||||
|
if (relaunchState === 'relaunching' || destroyed) return;
|
||||||
|
relaunchState = 'relaunching';
|
||||||
|
if (relaunchResetTimer) {
|
||||||
|
clearTimeout(relaunchResetTimer);
|
||||||
|
relaunchResetTimer = null;
|
||||||
|
}
|
||||||
|
syncActionButtons();
|
||||||
|
try {
|
||||||
|
const res = await triggerBridgeHostRelaunch();
|
||||||
|
if (destroyed) return;
|
||||||
|
if (!res || res.ok === false) {
|
||||||
|
relaunchState = 'failed';
|
||||||
|
syncActionButtons();
|
||||||
|
relaunchResetTimer = setTimeout(() => {
|
||||||
|
relaunchResetTimer = null;
|
||||||
|
if (destroyed) return;
|
||||||
|
relaunchState = 'idle';
|
||||||
|
syncActionButtons();
|
||||||
|
}, 3500);
|
||||||
|
relaunchResetTimer?.unref?.();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Reset button if host is still open after 9s (e.g. cancelled close prompt)
|
||||||
|
relaunchResetTimer = setTimeout(() => {
|
||||||
|
relaunchResetTimer = null;
|
||||||
|
if (destroyed) return;
|
||||||
|
relaunchState = 'idle';
|
||||||
|
syncActionButtons();
|
||||||
|
}, 9000);
|
||||||
|
relaunchResetTimer?.unref?.();
|
||||||
|
} catch {
|
||||||
|
if (destroyed) return;
|
||||||
|
relaunchState = 'failed';
|
||||||
|
syncActionButtons();
|
||||||
|
relaunchResetTimer = setTimeout(() => {
|
||||||
|
relaunchResetTimer = null;
|
||||||
|
if (destroyed) return;
|
||||||
|
relaunchState = 'idle';
|
||||||
|
syncActionButtons();
|
||||||
|
}, 3500);
|
||||||
|
relaunchResetTimer?.unref?.();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[relaunchBtnIconEl, relaunchBtnTextEl]
|
||||||
|
);
|
||||||
|
|
||||||
|
const copyBtnIconEl = createSvgIcon('copy', { size: 11 });
|
||||||
|
const copyBtnTextEl = h('span', {
|
||||||
|
className: 'settings-bridge-copy-text',
|
||||||
|
text: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT }),
|
||||||
|
});
|
||||||
|
const copyBtnEl = h(
|
||||||
|
'button',
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
className: 'btn-ghost-sm settings-bridge-copy-btn',
|
||||||
|
onClick: async () => {
|
||||||
|
await copyTextToClipboard(LAUNCH_FLAG_TEXT);
|
||||||
|
if (destroyed) return;
|
||||||
|
copied = true;
|
||||||
|
if (copiedTimer) clearTimeout(copiedTimer);
|
||||||
|
syncActionButtons();
|
||||||
|
copiedTimer = setTimeout(() => {
|
||||||
|
copiedTimer = null;
|
||||||
|
if (destroyed) return;
|
||||||
|
copied = false;
|
||||||
|
syncActionButtons();
|
||||||
|
}, 1800);
|
||||||
|
copiedTimer?.unref?.();
|
||||||
|
},
|
||||||
|
},
|
||||||
|
[copyBtnIconEl, copyBtnTextEl]
|
||||||
|
);
|
||||||
|
|
||||||
|
const headLeftEl = h('div', { className: 'settings-bridge-head-main' }, [headIconEl, titleEl]);
|
||||||
|
const headRowEl = h(
|
||||||
|
'div',
|
||||||
|
{ className: 'settings-bridge-head' },
|
||||||
|
dismissBtnEl ? [headLeftEl, dismissBtnEl] : [headLeftEl]
|
||||||
|
);
|
||||||
|
const actionsRowEl = h('div', { className: 'settings-bridge-actions' }, [
|
||||||
|
relaunchBtnEl,
|
||||||
|
copyBtnEl,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const rootEl = h(
|
||||||
|
'div',
|
||||||
|
{
|
||||||
|
className: 'settings-bridge-notice',
|
||||||
|
role: 'status',
|
||||||
|
hidden: true,
|
||||||
|
},
|
||||||
|
[headRowEl, bodyEl, actionsRowEl]
|
||||||
|
);
|
||||||
|
|
||||||
|
function syncActionButtons() {
|
||||||
|
const canRelaunch = lastPayload.windowBridge?.canRelaunch !== false;
|
||||||
|
patchAttr(relaunchBtnEl, 'hidden', !canRelaunch);
|
||||||
|
patchAttr(relaunchBtnEl, 'disabled', relaunchState === 'relaunching');
|
||||||
|
patchText(
|
||||||
|
relaunchBtnTextEl,
|
||||||
|
relaunchState === 'relaunching'
|
||||||
|
? t('settings.bridge.relaunchingBtn')
|
||||||
|
: relaunchState === 'failed'
|
||||||
|
? t('settings.bridge.relaunchFailed')
|
||||||
|
: t('settings.bridge.relaunchBtn')
|
||||||
|
);
|
||||||
|
|
||||||
|
patchSvgIcon(copyBtnIconEl, copied ? 'check' : 'copy');
|
||||||
|
patchText(
|
||||||
|
copyBtnTextEl,
|
||||||
|
copied
|
||||||
|
? t('settings.bridge.copiedBtn')
|
||||||
|
: t('settings.bridge.copyFlagBtn', { cmd: LAUNCH_FLAG_TEXT })
|
||||||
|
);
|
||||||
|
|
||||||
|
if (dismissBtnEl) {
|
||||||
|
const aria = t('settings.bridge.dismissAria');
|
||||||
|
patchAttr(dismissBtnEl, 'aria-label', aria);
|
||||||
|
patchAttr(dismissBtnEl, 'title', aria);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
const wb = lastPayload.windowBridge;
|
||||||
|
const state = String(wb?.state || '').trim();
|
||||||
|
if (state === 'active') {
|
||||||
|
dismissed = false;
|
||||||
|
}
|
||||||
|
const shouldShow =
|
||||||
|
!dismissed &&
|
||||||
|
Boolean(lastPayload.visible) &&
|
||||||
|
!isWindowOverlayMode() &&
|
||||||
|
(state === 'no_devtools_port' || state === 'cdp_unreachable');
|
||||||
|
|
||||||
|
patchAttr(rootEl, 'hidden', !shouldShow);
|
||||||
|
if (!shouldShow) return;
|
||||||
|
|
||||||
|
const isAutoConfigured = Boolean(
|
||||||
|
wb?.launcherConfigured || wb?.argvUpdatedThisBoot || wb?.argvConfigured
|
||||||
|
);
|
||||||
|
patchClasses(rootEl, {
|
||||||
|
'is-restart': isAutoConfigured,
|
||||||
|
'is-warn': !isAutoConfigured,
|
||||||
|
});
|
||||||
|
patchSvgIcon(headIconEl, isAutoConfigured ? 'refresh' : 'warning');
|
||||||
|
|
||||||
|
let titleText = '';
|
||||||
|
if (isAutoConfigured) {
|
||||||
|
titleText = contextMode
|
||||||
|
? t('settings.bridge.ctxRestartTitle')
|
||||||
|
: t('settings.bridge.restartTitle');
|
||||||
|
} else if (contextMode) {
|
||||||
|
titleText = t('settings.bridge.ctxTitle');
|
||||||
|
} else if (state === 'cdp_unreachable') {
|
||||||
|
titleText = t('settings.bridge.unreachableTitle');
|
||||||
|
} else {
|
||||||
|
titleText = t('settings.bridge.noPortTitle');
|
||||||
|
}
|
||||||
|
|
||||||
|
const plat = String(lastPayload.hostPlatform || '').trim().toLowerCase();
|
||||||
|
let bodyText = '';
|
||||||
|
if (isAutoConfigured) {
|
||||||
|
bodyText = t('settings.bridge.restartBody');
|
||||||
|
} else if (plat === 'darwin') {
|
||||||
|
bodyText = t('settings.bridge.guideMac');
|
||||||
|
} else if (plat === 'linux') {
|
||||||
|
bodyText = t('settings.bridge.guideLinux');
|
||||||
|
} else {
|
||||||
|
bodyText = t('settings.bridge.guideWin');
|
||||||
|
}
|
||||||
|
|
||||||
|
patchText(titleEl, titleText);
|
||||||
|
patchText(bodyEl, bodyText);
|
||||||
|
syncActionButtons();
|
||||||
|
}
|
||||||
|
|
||||||
|
function update(next = {}) {
|
||||||
|
if (typeof next.contextMode === 'boolean') {
|
||||||
|
contextMode = next.contextMode;
|
||||||
|
}
|
||||||
|
lastPayload = {
|
||||||
|
...lastPayload,
|
||||||
|
...next,
|
||||||
|
};
|
||||||
|
render();
|
||||||
|
}
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
destroyed = true;
|
||||||
|
if (copiedTimer) {
|
||||||
|
clearTimeout(copiedTimer);
|
||||||
|
copiedTimer = null;
|
||||||
|
}
|
||||||
|
if (relaunchResetTimer) {
|
||||||
|
clearTimeout(relaunchResetTimer);
|
||||||
|
relaunchResetTimer = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
el: rootEl,
|
||||||
|
refs: {
|
||||||
|
update,
|
||||||
|
refreshLabels: render,
|
||||||
|
relaunchBtnEl,
|
||||||
|
copyBtnEl,
|
||||||
|
dismissBtnEl,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -27,7 +27,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
totalTokens: 142800,
|
totalTokens: 142800,
|
||||||
limitTokens: 256000,
|
limitTokens: 256000,
|
||||||
compactionLimitTokens: 256000,
|
compactionLimitTokens: 256000,
|
||||||
|
compactionUsedTokens: 142800,
|
||||||
usedPct: 55.8,
|
usedPct: 55.8,
|
||||||
|
messagesTokens: 119660,
|
||||||
toolResultsTokens: 86400,
|
toolResultsTokens: 86400,
|
||||||
assistantTokens: 24200,
|
assistantTokens: 24200,
|
||||||
systemToolsTokens: 11800,
|
systemToolsTokens: 11800,
|
||||||
@@ -44,7 +46,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
totalTokens: 72704,
|
totalTokens: 72704,
|
||||||
limitTokens: 256000,
|
limitTokens: 256000,
|
||||||
compactionLimitTokens: 256000,
|
compactionLimitTokens: 256000,
|
||||||
|
compactionUsedTokens: 72704,
|
||||||
usedPct: 28.4,
|
usedPct: 28.4,
|
||||||
|
messagesTokens: 63704,
|
||||||
toolResultsTokens: 51200,
|
toolResultsTokens: 51200,
|
||||||
assistantTokens: 11400,
|
assistantTokens: 11400,
|
||||||
systemToolsTokens: 5600,
|
systemToolsTokens: 5600,
|
||||||
@@ -198,6 +202,9 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
responseTokens: 260,
|
responseTokens: 260,
|
||||||
cacheHitPct: 0,
|
cacheHitPct: 0,
|
||||||
costUsd: 0.198,
|
costUsd: 0.198,
|
||||||
|
inCostUsd: 0.19,
|
||||||
|
cacheCostUsd: 0,
|
||||||
|
outCostUsd: 0.008,
|
||||||
createdAtMs: anchorMinMs - 215_000,
|
createdAtMs: anchorMinMs - 215_000,
|
||||||
turnIndex: 1,
|
turnIndex: 1,
|
||||||
rootTurnIndex: 1,
|
rootTurnIndex: 1,
|
||||||
@@ -220,10 +227,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
isRunning: true,
|
isRunning: true,
|
||||||
stepCount: 16,
|
stepCount: 16,
|
||||||
speedSampleCount: 15,
|
speedSampleCount: 15,
|
||||||
|
speedSummary: { sampleCount: 15, excludedCount: 1 },
|
||||||
latestTokPerSec: 68.4,
|
latestTokPerSec: 68.4,
|
||||||
avgTokPerSec: 54.8,
|
avgTokPerSec: 54.8,
|
||||||
latestTtftSec: 1.15,
|
latestTtftSec: 1.15,
|
||||||
avgTtftSec: 1.62,
|
avgTtftSec: 1.62,
|
||||||
|
ttftSummary: { avgSec: 1.62, sampleCount: 15 },
|
||||||
latestStepCostUsd: 0.042,
|
latestStepCostUsd: 0.042,
|
||||||
sessionCostUsd: 1.16,
|
sessionCostUsd: 1.16,
|
||||||
latestCacheHitPct: 94.5,
|
latestCacheHitPct: 94.5,
|
||||||
@@ -239,6 +248,24 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
latestUpstreamModel: 'gemini-4-carbon-high',
|
latestUpstreamModel: 'gemini-4-carbon-high',
|
||||||
activeModelLabel: 'Gemini 4 Carbon (High)',
|
activeModelLabel: 'Gemini 4 Carbon (High)',
|
||||||
activeModelShort: 'gemini-4-carbon',
|
activeModelShort: 'gemini-4-carbon',
|
||||||
|
activeModelUpstream: 'gemini-4-carbon-high',
|
||||||
|
sessionUnpricedCalls: 0,
|
||||||
|
modelBreakdown: [
|
||||||
|
{
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
modelShort: 'gemini-4-carbon',
|
||||||
|
modelLabel: 'Gemini 4 Carbon (High)',
|
||||||
|
upstreamModel: 'gemini-4-carbon-high',
|
||||||
|
calls: 16,
|
||||||
|
inputTokens: 152400,
|
||||||
|
cacheReadTokens: 1260000,
|
||||||
|
outputTokens: 22100,
|
||||||
|
thinkingTokens: 14200,
|
||||||
|
totalTokens: 1434500,
|
||||||
|
costUsd: 1.16,
|
||||||
|
sharePct: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
context: mainContext,
|
context: mainContext,
|
||||||
recentSteps: mockSteps.filter((s) => !s.isSubagent),
|
recentSteps: mockSteps.filter((s) => !s.isSubagent),
|
||||||
};
|
};
|
||||||
@@ -254,10 +281,12 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
isRunning: false,
|
isRunning: false,
|
||||||
stepCount: 8,
|
stepCount: 8,
|
||||||
speedSampleCount: 8,
|
speedSampleCount: 8,
|
||||||
|
speedSummary: { sampleCount: 8, excludedCount: 0 },
|
||||||
latestTokPerSec: 96.2,
|
latestTokPerSec: 96.2,
|
||||||
avgTokPerSec: 88.5,
|
avgTokPerSec: 88.5,
|
||||||
latestTtftSec: 0.68,
|
latestTtftSec: 0.68,
|
||||||
avgTtftSec: 0.82,
|
avgTtftSec: 0.82,
|
||||||
|
ttftSummary: { avgSec: 0.82, sampleCount: 8 },
|
||||||
latestStepCostUsd: 0.009,
|
latestStepCostUsd: 0.009,
|
||||||
sessionCostUsd: 0.12,
|
sessionCostUsd: 0.12,
|
||||||
latestCacheHitPct: 88.1,
|
latestCacheHitPct: 88.1,
|
||||||
@@ -273,33 +302,69 @@ export function buildStructurePreviewTelemetry(baseSettings = {}, draftOverrides
|
|||||||
latestUpstreamModel: 'gemini-3.8-flash-n',
|
latestUpstreamModel: 'gemini-3.8-flash-n',
|
||||||
activeModelLabel: 'Gemini 3.8 Flash',
|
activeModelLabel: 'Gemini 3.8 Flash',
|
||||||
activeModelShort: 'gemini-3.8-flash',
|
activeModelShort: 'gemini-3.8-flash',
|
||||||
|
activeModelUpstream: 'gemini-3.8-flash-n',
|
||||||
|
sessionUnpricedCalls: 0,
|
||||||
|
modelBreakdown: [
|
||||||
|
{
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M42',
|
||||||
|
modelShort: 'gemini-3.8-flash',
|
||||||
|
modelLabel: 'Gemini 3.8 Flash',
|
||||||
|
upstreamModel: 'gemini-3.8-flash-n',
|
||||||
|
calls: 8,
|
||||||
|
inputTokens: 34000,
|
||||||
|
cacheReadTokens: 280000,
|
||||||
|
outputTokens: 6300,
|
||||||
|
thinkingTokens: 2100,
|
||||||
|
totalTokens: 320300,
|
||||||
|
costUsd: 0.12,
|
||||||
|
sharePct: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
context: subContext,
|
context: subContext,
|
||||||
recentSteps: mockSteps.filter((s) => s.isSubagent),
|
recentSteps: mockSteps.filter((s) => s.isSubagent),
|
||||||
};
|
};
|
||||||
|
|
||||||
const aggregated = {
|
const aggregated = {
|
||||||
...mainAgent,
|
...mainAgent,
|
||||||
|
agentId: 'all',
|
||||||
|
isMain: false,
|
||||||
|
agentKind: 'all',
|
||||||
|
agentOrdinal: 0,
|
||||||
|
badgeText: t('header.scopeAllShort'),
|
||||||
|
activeAgentId: 'main',
|
||||||
|
activeAgentKind: 'main',
|
||||||
|
activeAgentOrdinal: 0,
|
||||||
stepCount: 24,
|
stepCount: 24,
|
||||||
speedSampleCount: 23,
|
speedSampleCount: 23,
|
||||||
|
speedSummary: { sampleCount: 23, excludedCount: 1 },
|
||||||
avgTokPerSec: 59.6,
|
avgTokPerSec: 59.6,
|
||||||
avgTtftSec: 1.38,
|
avgTtftSec: 1.38,
|
||||||
|
ttftSummary: { avgSec: 1.38, sampleCount: 23 },
|
||||||
sessionCostUsd: 1.28,
|
sessionCostUsd: 1.28,
|
||||||
|
sessionUnpricedCalls: 0,
|
||||||
sessionCacheHitPct: 88.9,
|
sessionCacheHitPct: 88.9,
|
||||||
inputTokens: 186400,
|
inputTokens: 186400,
|
||||||
cacheReadTokens: 1540000,
|
cacheReadTokens: 1540000,
|
||||||
outputTokens: 28400,
|
outputTokens: 28400,
|
||||||
totalTokens: 1754800,
|
totalTokens: 1754800,
|
||||||
activeAgentBadge: '主',
|
activeAgentBadge: t('fmt.mainBadge'),
|
||||||
|
modelBreakdown: [...mainAgent.modelBreakdown, ...subAgent1.modelBreakdown],
|
||||||
recentSteps: mockSteps,
|
recentSteps: mockSteps,
|
||||||
};
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
settings: mergedSettings,
|
settings: mergedSettings,
|
||||||
account: {
|
account: {
|
||||||
planName: 'Google AI Pro',
|
tierName: 'Google AI Ultra',
|
||||||
aiCredits: 1200,
|
planName: 'Pro',
|
||||||
|
aiCredits: 0,
|
||||||
},
|
},
|
||||||
quotas: {
|
quotas: {
|
||||||
|
meta: {
|
||||||
|
hasOfficialData: true,
|
||||||
|
isStale: false,
|
||||||
|
refreshFailed: false,
|
||||||
|
},
|
||||||
activePool: {
|
activePool: {
|
||||||
family: 'Gemini',
|
family: 'Gemini',
|
||||||
poolKey: 'Gemini',
|
poolKey: 'Gemini',
|
||||||
|
|||||||
@@ -90,12 +90,14 @@ export const TopLongPillNav = defineComponent({
|
|||||||
}
|
}
|
||||||
|
|
||||||
patchText(entry.labelEl, item.label);
|
patchText(entry.labelEl, item.label);
|
||||||
if (item.badge !== undefined && item.badge !== null && item.badge !== '') {
|
const hasBadge = item.badge !== undefined && item.badge !== null && item.badge !== '';
|
||||||
|
if (hasBadge) {
|
||||||
patchAttr(entry.badgeEl, 'hidden', false);
|
patchAttr(entry.badgeEl, 'hidden', false);
|
||||||
patchText(entry.badgeEl, `(${item.badge})`);
|
patchText(entry.badgeEl, `(${item.badge})`);
|
||||||
} else {
|
} else {
|
||||||
patchAttr(entry.badgeEl, 'hidden', true);
|
patchAttr(entry.badgeEl, 'hidden', true);
|
||||||
}
|
}
|
||||||
|
patchAttr(entry.btn, 'title', hasBadge ? `${item.label} (${item.badge})` : item.label);
|
||||||
|
|
||||||
const isActive = item.value === modelValue;
|
const isActive = item.value === modelValue;
|
||||||
patchClasses(entry.btn, { 'is-active': isActive });
|
patchClasses(entry.btn, { 'is-active': isActive });
|
||||||
|
|||||||
@@ -14,10 +14,96 @@ import {
|
|||||||
normalizeClientWindowMountMode,
|
normalizeClientWindowMountMode,
|
||||||
resolveScopedConversation,
|
resolveScopedConversation,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
|
import { buildFallbackRunningConversations } from './LiveActivityWidget.js';
|
||||||
|
|
||||||
export const RING_RADIUS = 5.2;
|
export const RING_RADIUS = 5.2;
|
||||||
export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
|
export const RING_CIRCUMFERENCE = +(2 * Math.PI * RING_RADIUS).toFixed(2);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute shared context ring + 1..5 capsule slot metric payload from telemetry & scoped conversation.
|
||||||
|
*/
|
||||||
|
export function buildCapsuleSlotContext(
|
||||||
|
data,
|
||||||
|
{ scopedConv = null, overviewConv = null, ctxAgent = null, aggregated = null } = {}
|
||||||
|
) {
|
||||||
|
if (!data) return { hasTelemetry: false };
|
||||||
|
const activeConv = data.activeConversation || {};
|
||||||
|
const overviewActive = overviewConv || scopedConv || aggregated || activeConv;
|
||||||
|
const capActive = scopedConv || aggregated || activeConv || {};
|
||||||
|
const ctx = ctxAgent?.context || overviewActive.context || activeConv.context || {};
|
||||||
|
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||||
|
const totalTokens = Number(ctx.totalTokens || 0);
|
||||||
|
const usedPct =
|
||||||
|
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||||
|
const dashOffset = +(
|
||||||
|
RING_CIRCUMFERENCE *
|
||||||
|
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
|
||||||
|
).toFixed(2);
|
||||||
|
|
||||||
|
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
|
||||||
|
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
|
||||||
|
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
|
||||||
|
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
|
||||||
|
const sessionTokens =
|
||||||
|
Number(capActive.stepCount || 0) > 0 ||
|
||||||
|
capActive.totalTokens != null ||
|
||||||
|
capInTok + capCacheTok + capOutTok > 0
|
||||||
|
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
|
||||||
|
: null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
hasTelemetry: true,
|
||||||
|
usedPct,
|
||||||
|
dashOffset,
|
||||||
|
isRunning,
|
||||||
|
tps: scopedConv?.latestTokPerSec ?? aggregated?.latestTokPerSec ?? activeConv.latestTokPerSec ?? null,
|
||||||
|
avgTps: scopedConv?.avgTokPerSec ?? aggregated?.avgTokPerSec ?? activeConv.avgTokPerSec ?? null,
|
||||||
|
ttft: scopedConv?.latestTtftSec ?? aggregated?.latestTtftSec ?? activeConv.latestTtftSec ?? null,
|
||||||
|
stepCost:
|
||||||
|
scopedConv?.latestStepCostUsd ??
|
||||||
|
aggregated?.latestStepCostUsd ??
|
||||||
|
activeConv.latestStepCostUsd ??
|
||||||
|
null,
|
||||||
|
sessionCost:
|
||||||
|
scopedConv?.sessionCostUsd ?? aggregated?.sessionCostUsd ?? activeConv.sessionCostUsd ?? null,
|
||||||
|
cacheHitPct:
|
||||||
|
Number(capActive.stepCount || 0) > 0
|
||||||
|
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
|
||||||
|
: null,
|
||||||
|
latestPromptTokens: capActive.latestPromptTokens ?? null,
|
||||||
|
sessionTokens,
|
||||||
|
quotas: data.quotas,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute multi-session button state & normalized running conversation list.
|
||||||
|
*/
|
||||||
|
export function resolveMultiSessionCapsuleState(
|
||||||
|
data,
|
||||||
|
{ agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {}
|
||||||
|
) {
|
||||||
|
const rawRunningList = buildFallbackRunningConversations(data, {
|
||||||
|
agents,
|
||||||
|
aggregated,
|
||||||
|
latestTokPerSec,
|
||||||
|
contextUsedPct,
|
||||||
|
});
|
||||||
|
const runningCount = rawRunningList.length;
|
||||||
|
const runningSubCount = rawRunningList.reduce(
|
||||||
|
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
||||||
|
0
|
||||||
|
);
|
||||||
|
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
||||||
|
const multiBtnText =
|
||||||
|
runningCount > 0
|
||||||
|
? runningSubCount > 0
|
||||||
|
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
||||||
|
: t('capsule.multiRunning', { count: runningCount })
|
||||||
|
: t('capsule.multiZero');
|
||||||
|
return { rawRunningList, runningCount, runningSubCount, hasWaiting, multiBtnText };
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring.
|
* Create a single reusable capsule metric slot node (`0..4`) with an optional SVG context ring.
|
||||||
*/
|
*/
|
||||||
@@ -222,11 +308,6 @@ export const CapsuleBarWidget = defineComponent({
|
|||||||
]
|
]
|
||||||
);
|
);
|
||||||
|
|
||||||
const titlebarRightMock = h('div', { className: 'preview-win-controls', 'aria-hidden': 'true' }, [
|
|
||||||
h('span', { className: 'preview-win-dot' }),
|
|
||||||
h('span', { className: 'preview-win-dot' }),
|
|
||||||
h('span', { className: 'preview-win-dot' }),
|
|
||||||
]);
|
|
||||||
const composerSendMock = h(
|
const composerSendMock = h(
|
||||||
'span',
|
'span',
|
||||||
{ className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true },
|
{ className: 'preview-composer-send', 'aria-hidden': 'true', hidden: true },
|
||||||
@@ -236,7 +317,7 @@ export const CapsuleBarWidget = defineComponent({
|
|||||||
const hostBarEl = h(
|
const hostBarEl = h(
|
||||||
'div',
|
'div',
|
||||||
{ className: 'preview-capsule-bar', 'data-mount-mode': 'dual' },
|
{ className: 'preview-capsule-bar', 'data-mount-mode': 'dual' },
|
||||||
[titlebarLeftMock, composerLeftMock, capsuleCluster, titlebarRightMock, composerSendMock]
|
[titlebarLeftMock, composerLeftMock, capsuleCluster, composerSendMock]
|
||||||
);
|
);
|
||||||
|
|
||||||
const sidebarHintEl = h('div', {
|
const sidebarHintEl = h('div', {
|
||||||
@@ -265,7 +346,6 @@ export const CapsuleBarWidget = defineComponent({
|
|||||||
});
|
});
|
||||||
|
|
||||||
patchAttr(titlebarLeftMock, 'hidden', isComposer);
|
patchAttr(titlebarLeftMock, 'hidden', isComposer);
|
||||||
patchAttr(titlebarRightMock, 'hidden', isComposer);
|
|
||||||
patchAttr(composerLeftMock, 'hidden', !isComposer);
|
patchAttr(composerLeftMock, 'hidden', !isComposer);
|
||||||
patchAttr(composerSendMock, 'hidden', !isComposer);
|
patchAttr(composerSendMock, 'hidden', !isComposer);
|
||||||
patchAttr(sidebarHintEl, 'hidden', !isSidebar);
|
patchAttr(sidebarHintEl, 'hidden', !isSidebar);
|
||||||
@@ -280,75 +360,26 @@ export const CapsuleBarWidget = defineComponent({
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
|
const { agents, scopedConv, ctxAgent, aggregated } = resolveScopedConversation(
|
||||||
data,
|
data,
|
||||||
'all',
|
'all',
|
||||||
'auto'
|
'auto'
|
||||||
);
|
);
|
||||||
const activeConv = data.activeConversation || {};
|
const slotCtx = buildCapsuleSlotContext(data, { scopedConv, ctxAgent, aggregated });
|
||||||
const capActive = scopedConv || aggregated || activeConv;
|
const { runningCount, hasWaiting, multiBtnText } = resolveMultiSessionCapsuleState(data, {
|
||||||
const ctx = ctxAgent?.context || capActive.context || activeConv.context || {};
|
agents,
|
||||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
aggregated,
|
||||||
const totalTokens = Number(ctx.totalTokens || 0);
|
contextUsedPct: slotCtx.usedPct,
|
||||||
const usedPct =
|
});
|
||||||
limitTokens > 0 ? Math.min(100, +((totalTokens / limitTokens) * 100).toFixed(1)) : 0;
|
|
||||||
const dashOffset = +(
|
|
||||||
RING_CIRCUMFERENCE *
|
|
||||||
(1 - Math.max(0, Math.min(100, usedPct)) / 100)
|
|
||||||
).toFixed(2);
|
|
||||||
|
|
||||||
const rawRunningList = Array.isArray(data.runningConversations)
|
|
||||||
? data.runningConversations
|
|
||||||
: [];
|
|
||||||
const runningCount = rawRunningList.length;
|
|
||||||
const runningSubCount = rawRunningList.reduce(
|
|
||||||
(acc, item) => acc + Number(item.runningSubagentCount || 0),
|
|
||||||
0
|
|
||||||
);
|
|
||||||
const hasWaiting = rawRunningList.some((item) => item.mainActivity?.phase === 'waiting');
|
|
||||||
|
|
||||||
patchClasses(multiBtn, {
|
patchClasses(multiBtn, {
|
||||||
'is-running': runningCount > 0 && !hasWaiting,
|
'is-running': runningCount > 0 && !hasWaiting,
|
||||||
'is-waiting': runningCount > 0 && hasWaiting,
|
'is-waiting': runningCount > 0 && hasWaiting,
|
||||||
});
|
});
|
||||||
const multiBtnText =
|
|
||||||
runningCount > 0
|
|
||||||
? runningSubCount > 0
|
|
||||||
? t('capsule.multiRunningWithSubs', { count: runningCount, subs: runningSubCount })
|
|
||||||
: t('capsule.multiRunning', { count: runningCount })
|
|
||||||
: t('capsule.multiZero');
|
|
||||||
patchText(multiLabel, multiBtnText);
|
patchText(multiLabel, multiBtnText);
|
||||||
|
|
||||||
const isRunning = Boolean(aggregated?.isRunning || activeConv.isRunning);
|
patchClasses(capsuleBtn, { 'is-running': slotCtx.isRunning });
|
||||||
const capInTok = Math.max(0, Number(capActive.inputTokens || 0));
|
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, slotCtx);
|
||||||
const capCacheTok = Math.max(0, Number(capActive.cacheReadTokens || 0));
|
|
||||||
const capOutTok = Math.max(0, Number(capActive.outputTokens || 0));
|
|
||||||
const sessionTokens =
|
|
||||||
Number(capActive.stepCount || 0) > 0 ||
|
|
||||||
capActive.totalTokens != null ||
|
|
||||||
capInTok + capCacheTok + capOutTok > 0
|
|
||||||
? Math.max(0, Number(capActive.totalTokens ?? capInTok + capCacheTok + capOutTok))
|
|
||||||
: null;
|
|
||||||
|
|
||||||
patchClasses(capsuleBtn, { 'is-running': isRunning });
|
|
||||||
syncCapsuleSlotNodes(capsuleSlots, capsuleSeps, slotKeys, {
|
|
||||||
hasTelemetry: true,
|
|
||||||
usedPct,
|
|
||||||
dashOffset,
|
|
||||||
isRunning,
|
|
||||||
tps: capActive.latestTokPerSec ?? null,
|
|
||||||
avgTps: capActive.avgTokPerSec ?? null,
|
|
||||||
ttft: capActive.latestTtftSec ?? null,
|
|
||||||
stepCost: capActive.latestStepCostUsd ?? null,
|
|
||||||
sessionCost: capActive.sessionCostUsd ?? null,
|
|
||||||
cacheHitPct:
|
|
||||||
Number(capActive.stepCount || 0) > 0
|
|
||||||
? capActive.latestCacheHitPct ?? capActive.sessionCacheHitPct ?? null
|
|
||||||
: null,
|
|
||||||
latestPromptTokens: capActive.latestPromptTokens ?? null,
|
|
||||||
sessionTokens,
|
|
||||||
quotas: data.quotas,
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -309,12 +309,16 @@ export const ContextWindowWidget = defineComponent({
|
|||||||
if (interactiveInspector) {
|
if (interactiveInspector) {
|
||||||
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
|
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
|
||||||
if (hasSubagents && ctxAgent) {
|
if (hasSubagents && ctxAgent) {
|
||||||
const rawActiveBadge = aggregated?.activeAgentBadge || '主';
|
const activeBadgeText = formatAgentBadgeText({
|
||||||
const activeBadgeText = isEnglishLocale()
|
agentKind:
|
||||||
? rawActiveBadge === '主'
|
aggregated?.activeAgentKind ||
|
||||||
? t('fmt.mainBadge')
|
(!aggregated?.activeAgentId || aggregated.activeAgentId === 'main'
|
||||||
: rawActiveBadge.replace(/^子(\d+)$/, (_, n) => t('fmt.subBadge', { index: n }))
|
? 'main'
|
||||||
: rawActiveBadge;
|
: 'subagent'),
|
||||||
|
agentOrdinal: Number(aggregated?.activeAgentOrdinal || 0),
|
||||||
|
isMain: !aggregated?.activeAgentId || aggregated.activeAgentId === 'main',
|
||||||
|
badgeText: aggregated?.activeAgentBadge,
|
||||||
|
});
|
||||||
|
|
||||||
const pillItems = [
|
const pillItems = [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`).
|
* @fileoverview Standalone decoupled Live Running Tasks Widget (`LiveActivityWidget.js`).
|
||||||
* Displays active multi-session running conversations & collapsible subagent activity
|
* Displays active multi-session running conversations & collapsible subagent activity
|
||||||
* with an isolated 1s elapsed timer lifecycle.
|
* with an isolated 1s elapsed timer lifecycle. Supports both Overview/Hover widget mode
|
||||||
|
* and controlled Multi-Session Floating Panel mode (`WindowOverlayShell.js`).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { defineComponent } from '../../core/component.js';
|
import { defineComponent } from '../../core/component.js';
|
||||||
@@ -12,23 +13,85 @@ import {
|
|||||||
patchKeyedList,
|
patchKeyedList,
|
||||||
patchText,
|
patchText,
|
||||||
} from '../../core/domPatch.js';
|
} from '../../core/domPatch.js';
|
||||||
import { formatElapsedSec } from '../../core/formatters.js';
|
import {
|
||||||
|
formatAgentBadgeText,
|
||||||
|
formatElapsedSec,
|
||||||
|
formatLiveActivityDetail,
|
||||||
|
formatLiveActivityLabel,
|
||||||
|
getAgentBadgeClass,
|
||||||
|
} from '../../core/formatters.js';
|
||||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||||
import {
|
import {
|
||||||
|
extractHostRouteCascadeId,
|
||||||
fetchTelemetry,
|
fetchTelemetry,
|
||||||
formatAgentBadgeText,
|
|
||||||
getAgentBadgeClass,
|
|
||||||
resolveScopedConversation,
|
resolveScopedConversation,
|
||||||
telemetryStore,
|
telemetryStore,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
import { uiStore } from '../../store/uiStore.js';
|
import { uiStore } from '../../store/uiStore.js';
|
||||||
|
|
||||||
|
export function buildFallbackRunningConversations(
|
||||||
|
data,
|
||||||
|
{ agents = [], aggregated = null, latestTokPerSec = undefined, contextUsedPct = undefined } = {}
|
||||||
|
) {
|
||||||
|
if (!data) return [];
|
||||||
|
if (Array.isArray(data.runningConversations) && data.runningConversations.length > 0) {
|
||||||
|
return data.runningConversations;
|
||||||
|
}
|
||||||
|
const activeConv = data.activeConversation || {};
|
||||||
|
if (!activeConv.isRunning && !aggregated?.isRunning) return [];
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
cascadeId: activeConv.cascadeId || 'current',
|
||||||
|
title: activeConv.title || t('live.currentSession'),
|
||||||
|
isCurrentSelected: true,
|
||||||
|
isMainRunning: Boolean(activeConv.isRunning),
|
||||||
|
isRunning: true,
|
||||||
|
mainActivity: activeConv.liveActivity || aggregated?.liveActivity || null,
|
||||||
|
subagentCount: Math.max(0, (agents?.length || 1) - 1),
|
||||||
|
runningSubagentCount: (agents || []).filter((a) => !a.isMain && a.isRunning).length,
|
||||||
|
...(latestTokPerSec !== undefined ? { latestTokPerSec } : {}),
|
||||||
|
...(contextUsedPct !== undefined ? { contextUsedPct } : {}),
|
||||||
|
subagents: (agents || [])
|
||||||
|
.filter((a) => !a.isMain)
|
||||||
|
.map((s, idx) => ({
|
||||||
|
cascadeId: s.cascadeId || s.agentId,
|
||||||
|
index: s.index || idx + 1,
|
||||||
|
agentKind: s.agentKind || (s.isSideQuestion ? 'side_question' : 'subagent'),
|
||||||
|
agentOrdinal: s.agentOrdinal || (s.isSideQuestion ? s.sideIndex || 0 : s.index || idx + 1),
|
||||||
|
customRole: s.customRole,
|
||||||
|
...(s.isSideQuestion ? { isSideQuestion: true, sideIndex: s.sideIndex || 0 } : {}),
|
||||||
|
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
||||||
|
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||||
|
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
||||||
|
isRunning: Boolean(s.isRunning),
|
||||||
|
stepCount: Number(s.stepCount || 0),
|
||||||
|
lastModifiedMs: s.lastModifiedMs || 0,
|
||||||
|
liveActivity: s.liveActivity || {
|
||||||
|
phase: s.isRunning ? 'thinking' : 'done',
|
||||||
|
actionKey: s.isRunning ? 'thinking' : 'done',
|
||||||
|
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
||||||
|
detail: '',
|
||||||
|
stepProgress: '',
|
||||||
|
startedAtMs: s.lastModifiedMs || 0,
|
||||||
|
signature: `${s.agentId}:${s.stepCount || 0}`,
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
export const LiveActivityWidget = defineComponent({
|
export const LiveActivityWidget = defineComponent({
|
||||||
name: 'LiveActivityWidget',
|
name: 'LiveActivityWidget',
|
||||||
setup({ props, onCleanup }) {
|
setup({ props, onCleanup }) {
|
||||||
const interactive = props.interactive !== false;
|
const interactive = props.interactive !== false;
|
||||||
const preview = Boolean(props.preview);
|
const preview = Boolean(props.preview);
|
||||||
|
const defaultExpandRunningSubs = Boolean(props.defaultExpandRunningSubs);
|
||||||
|
const showSessionExtras = Boolean(props.showSessionExtras);
|
||||||
|
const onSelectSession =
|
||||||
|
typeof props.onSelectSession === 'function' ? props.onSelectSession : null;
|
||||||
|
const onLayoutChange =
|
||||||
|
typeof props.onLayoutChange === 'function' ? props.onLayoutChange : null;
|
||||||
const getCtxAgentId =
|
const getCtxAgentId =
|
||||||
typeof props.getCtxAgentId === 'function'
|
typeof props.getCtxAgentId === 'function'
|
||||||
? props.getCtxAgentId
|
? props.getCtxAgentId
|
||||||
@@ -42,10 +105,19 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
'aria-live': 'polite',
|
'aria-live': 'polite',
|
||||||
});
|
});
|
||||||
|
|
||||||
const expandedTaskConvIds = new Set();
|
const manualSubExpandMap = new Map();
|
||||||
const activityTimersMap = new Map();
|
const activityTimersMap = new Map();
|
||||||
let liveTickTimer = null;
|
let liveTickTimer = null;
|
||||||
let latestData = null;
|
let latestUpdateArgs = null;
|
||||||
|
|
||||||
|
function resolveIsExpanded(item) {
|
||||||
|
const runSubCount = Number(item?.runningSubagentCount || 0);
|
||||||
|
if (!interactive) return runSubCount > 0;
|
||||||
|
if (manualSubExpandMap.has(item.cascadeId)) {
|
||||||
|
return Boolean(manualSubExpandMap.get(item.cascadeId));
|
||||||
|
}
|
||||||
|
return defaultExpandRunningSubs ? runSubCount > 0 : false;
|
||||||
|
}
|
||||||
|
|
||||||
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
@@ -108,6 +180,20 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
className: 'live-task-title',
|
className: 'live-task-title',
|
||||||
text: t('live.currentSession'),
|
text: t('live.currentSession'),
|
||||||
});
|
});
|
||||||
|
const hereTagEl = showSessionExtras
|
||||||
|
? h('span', {
|
||||||
|
className: 'wm-session-tag is-here',
|
||||||
|
hidden: true,
|
||||||
|
text: t('multi.hereTag'),
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
const metricsEl = showSessionExtras
|
||||||
|
? h('span', {
|
||||||
|
className: 'wm-task-metrics text-mono',
|
||||||
|
hidden: true,
|
||||||
|
text: '',
|
||||||
|
})
|
||||||
|
: null;
|
||||||
const subToggleBtn = h('button', {
|
const subToggleBtn = h('button', {
|
||||||
type: 'button',
|
type: 'button',
|
||||||
className: 'live-sub-toggle',
|
className: 'live-sub-toggle',
|
||||||
@@ -120,8 +206,16 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const headerEl = h('div', { className: 'live-task-header' }, [
|
const headerEl = h('div', { className: 'live-task-header' }, [
|
||||||
h('div', { className: 'live-task-title-wrap' }, [dotWrap, titleEl]),
|
h('div', { className: 'live-task-title-wrap' }, [
|
||||||
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
|
dotWrap,
|
||||||
|
titleEl,
|
||||||
|
...(hereTagEl ? [hereTagEl] : []),
|
||||||
|
]),
|
||||||
|
h('div', { className: 'live-task-header-right' }, [
|
||||||
|
...(metricsEl ? [metricsEl] : []),
|
||||||
|
subToggleBtn,
|
||||||
|
elapsedEl,
|
||||||
|
]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const mainBadge = h('span', {
|
const mainBadge = h('span', {
|
||||||
@@ -162,6 +256,8 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
cardEl,
|
cardEl,
|
||||||
dotIcon,
|
dotIcon,
|
||||||
titleEl,
|
titleEl,
|
||||||
|
hereTagEl,
|
||||||
|
metricsEl,
|
||||||
subToggleBtn,
|
subToggleBtn,
|
||||||
elapsedEl,
|
elapsedEl,
|
||||||
mainBadge,
|
mainBadge,
|
||||||
@@ -200,103 +296,86 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function update({ data } = {}) {
|
function update({ data = null, items = null, hostRouteConversationId = '' } = {}) {
|
||||||
latestData = data || null;
|
latestUpdateArgs = { data, items, hostRouteConversationId };
|
||||||
if (!data) {
|
if (!data && !Array.isArray(items)) {
|
||||||
patchAttr(liveActivityBar, 'hidden', true);
|
patchAttr(liveActivityBar, 'hidden', true);
|
||||||
stopLiveTicker();
|
stopLiveTicker();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { agents, aggregated } = resolveScopedConversation(
|
let rawRunningList = Array.isArray(items) ? items : null;
|
||||||
data,
|
if (!rawRunningList) {
|
||||||
'all',
|
const { agents, aggregated } = resolveScopedConversation(
|
||||||
getCtxAgentId()
|
data,
|
||||||
);
|
'all',
|
||||||
|
getCtxAgentId()
|
||||||
|
);
|
||||||
|
rawRunningList = buildFallbackRunningConversations(data, { agents, aggregated });
|
||||||
|
}
|
||||||
|
|
||||||
const rawRunningList =
|
if (manualSubExpandMap.size > 0) {
|
||||||
Array.isArray(data.runningConversations) && data.runningConversations.length > 0
|
const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
|
||||||
? data.runningConversations
|
for (const id of [...manualSubExpandMap.keys()]) {
|
||||||
: data.activeConversation?.isRunning || aggregated?.isRunning
|
if (!runningIdsSet.has(id)) {
|
||||||
? [
|
manualSubExpandMap.delete(id);
|
||||||
{
|
}
|
||||||
cascadeId: data.activeConversation?.cascadeId || 'current',
|
}
|
||||||
title: data.activeConversation?.title || t('live.currentSession'),
|
}
|
||||||
isCurrentSelected: true,
|
|
||||||
isMainRunning: Boolean(data.activeConversation?.isRunning),
|
|
||||||
isRunning: true,
|
|
||||||
mainActivity:
|
|
||||||
data.activeConversation?.liveActivity || aggregated?.liveActivity || null,
|
|
||||||
subagentCount: Math.max(0, agents.length - 1),
|
|
||||||
runningSubagentCount: agents.filter((a) => !a.isMain && a.isRunning).length,
|
|
||||||
subagents: agents
|
|
||||||
.filter((a) => !a.isMain)
|
|
||||||
.map((s, idx) => ({
|
|
||||||
cascadeId: s.cascadeId || s.agentId,
|
|
||||||
index: s.index || idx + 1,
|
|
||||||
badgeText: formatAgentBadgeText({ ...s, index: s.index || idx + 1 }),
|
|
||||||
shortLabel: s.shortLabel || `${t('fmt.subAgent')} #${idx + 1}`,
|
|
||||||
role: s.role || `${t('fmt.subAgent')} #${idx + 1}`,
|
|
||||||
isRunning: Boolean(s.isRunning),
|
|
||||||
stepCount: Number(s.stepCount || 0),
|
|
||||||
lastModifiedMs: s.lastModifiedMs || 0,
|
|
||||||
liveActivity: s.liveActivity || {
|
|
||||||
phase: s.isRunning ? 'thinking' : 'done',
|
|
||||||
label: s.isRunning ? t('live.thinking') : t('live.done'),
|
|
||||||
detail: '',
|
|
||||||
stepProgress: '',
|
|
||||||
startedAtMs: s.lastModifiedMs || 0,
|
|
||||||
signature: `${s.agentId}:${s.stepCount || 0}`,
|
|
||||||
},
|
|
||||||
})),
|
|
||||||
},
|
|
||||||
]
|
|
||||||
: [];
|
|
||||||
|
|
||||||
const hasRunningTasks = rawRunningList.length > 0;
|
const hasRunningTasks = rawRunningList.length > 0;
|
||||||
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
|
patchAttr(liveActivityBar, 'hidden', !hasRunningTasks);
|
||||||
if (!hasRunningTasks) {
|
if (!hasRunningTasks) {
|
||||||
stopLiveTicker();
|
stopLiveTicker();
|
||||||
expandedTaskConvIds.clear();
|
patchKeyedList(liveActivityBar, [], {});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isVisibleFn()) {
|
||||||
|
pauseTicker();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const locale = getEffectiveLocale();
|
||||||
|
const hostRouteLower = showSessionExtras
|
||||||
|
? String(hostRouteConversationId || extractHostRouteCascadeId() || '').toLowerCase()
|
||||||
|
: '';
|
||||||
|
|
||||||
const activeTimerKeys = new Set();
|
const activeTimerKeys = new Set();
|
||||||
for (const item of rawRunningList) {
|
for (const item of rawRunningList) {
|
||||||
activeTimerKeys.add(`main:${item.cascadeId}`);
|
activeTimerKeys.add(`main:${item.cascadeId}`);
|
||||||
for (const sub of item.subagents || []) {
|
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||||
if (sub?.isRunning) {
|
const isExp = resolveIsExpanded(item);
|
||||||
activeTimerKeys.add(`sub:${sub.cascadeId}`);
|
if (subCount > 0 && isExp) {
|
||||||
|
for (const sub of item.subagents || []) {
|
||||||
|
if (sub?.isRunning) {
|
||||||
|
activeTimerKeys.add(`sub:${sub.cascadeId}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const runningIdsSet = new Set(rawRunningList.map((item) => item.cascadeId));
|
|
||||||
for (const id of [...expandedTaskConvIds]) {
|
|
||||||
if (!runningIdsSet.has(id)) {
|
|
||||||
expandedTaskConvIds.delete(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const locale = getEffectiveLocale();
|
|
||||||
patchKeyedList(liveActivityBar, rawRunningList, {
|
patchKeyedList(liveActivityBar, rawRunningList, {
|
||||||
keyFn: (item) => item.cascadeId,
|
keyFn: (item) => item.cascadeId,
|
||||||
sigFn: (item) => {
|
sigFn: (item) => {
|
||||||
const isExp = interactive
|
const isExp = resolveIsExpanded(item);
|
||||||
? expandedTaskConvIds.has(item.cascadeId)
|
const isHere =
|
||||||
: Number(item.runningSubagentCount || 0) > 0;
|
showSessionExtras &&
|
||||||
|
Boolean(hostRouteLower) &&
|
||||||
|
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||||
const subSig = (item.subagents || [])
|
const subSig = (item.subagents || [])
|
||||||
.map(
|
.map(
|
||||||
(s) =>
|
(s) =>
|
||||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||||
)
|
)
|
||||||
.join('|');
|
.join('|');
|
||||||
return `${locale}:${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
return `${locale}:${item.cascadeId}:${item.title}:${isHere}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.latestTokPerSec ?? ''}:${item.contextUsedPct ?? ''}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||||
},
|
},
|
||||||
createRow: createLiveTaskCard,
|
createRow: createLiveTaskCard,
|
||||||
updateRow: (refs, item) => {
|
updateRow: (refs, item) => {
|
||||||
const act = item.mainActivity || {
|
const act = item.mainActivity || {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'thinking',
|
||||||
label: t('live.thinking'),
|
label: t('live.thinking'),
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -315,9 +394,18 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
|
const convTitle = item.title || item.cascadeId?.slice(0, 8) || t('live.currentSession');
|
||||||
patchText(refs.titleEl, convTitle);
|
patchText(refs.titleEl, convTitle);
|
||||||
if (interactive && !preview) {
|
if (interactive && !preview) {
|
||||||
patchAttr(refs.titleEl, 'title', t('live.switchSessionTitle', { title: convTitle }));
|
patchAttr(
|
||||||
refs.titleEl.onclick = () => {
|
refs.titleEl,
|
||||||
if (item.cascadeId && item.cascadeId !== 'current') {
|
'title',
|
||||||
|
onSelectSession
|
||||||
|
? t('multi.inspectSessionTitle', { title: convTitle })
|
||||||
|
: t('live.switchSessionTitle', { title: convTitle })
|
||||||
|
);
|
||||||
|
refs.titleEl.onclick = (e) => {
|
||||||
|
e?.stopPropagation?.();
|
||||||
|
if (onSelectSession) {
|
||||||
|
onSelectSession(item.cascadeId);
|
||||||
|
} else if (item.cascadeId && item.cascadeId !== 'current') {
|
||||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||||
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
telemetryStore.setState({ selectedConversationId: item.cascadeId });
|
||||||
fetchTelemetry({ force: false });
|
fetchTelemetry({ force: false });
|
||||||
@@ -325,11 +413,32 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (showSessionExtras && refs.hereTagEl && refs.metricsEl) {
|
||||||
|
const isHere =
|
||||||
|
Boolean(hostRouteLower) &&
|
||||||
|
String(item.cascadeId || '').toLowerCase() === hostRouteLower;
|
||||||
|
patchText(refs.hereTagEl, t('multi.hereTag'));
|
||||||
|
patchAttr(refs.hereTagEl, 'hidden', !isHere);
|
||||||
|
|
||||||
|
const metricParts = [];
|
||||||
|
if (Number.isFinite(item.latestTokPerSec) && item.latestTokPerSec > 0) {
|
||||||
|
metricParts.push(
|
||||||
|
`${item.latestTokPerSec >= 100 ? Math.round(item.latestTokPerSec) : item.latestTokPerSec.toFixed(1)} t/s`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (item.contextUsedPct != null && Number.isFinite(Number(item.contextUsedPct))) {
|
||||||
|
metricParts.push(`${Math.round(Number(item.contextUsedPct))}%`);
|
||||||
|
}
|
||||||
|
const metricsStr = metricParts.join(' · ');
|
||||||
|
patchAttr(refs.metricsEl, 'hidden', !metricsStr);
|
||||||
|
if (metricsStr) {
|
||||||
|
patchText(refs.metricsEl, metricsStr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||||
const isExpanded = interactive
|
const isExpanded = resolveIsExpanded(item);
|
||||||
? expandedTaskConvIds.has(item.cascadeId)
|
|
||||||
: runSubCount > 0;
|
|
||||||
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
patchText(refs.mainBadge, t('fmt.mainBadge'));
|
||||||
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
||||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
||||||
@@ -349,39 +458,37 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
);
|
);
|
||||||
refs.subToggleBtn.onclick = (e) => {
|
refs.subToggleBtn.onclick = (e) => {
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
if (expandedTaskConvIds.has(item.cascadeId)) {
|
manualSubExpandMap.set(item.cascadeId, !isExpanded);
|
||||||
expandedTaskConvIds.delete(item.cascadeId);
|
if (latestUpdateArgs) update(latestUpdateArgs);
|
||||||
} else {
|
onLayoutChange?.();
|
||||||
expandedTaskConvIds.add(item.cascadeId);
|
|
||||||
}
|
|
||||||
if (latestData) update({ data: latestData });
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const mainLabel = formatLiveActivityLabel(act, 'live.thinking');
|
||||||
|
const detailStr = formatLiveActivityDetail(act);
|
||||||
const mainTimerKey = `main:${item.cascadeId}`;
|
const mainTimerKey = `main:${item.cascadeId}`;
|
||||||
activeTimerKeys.add(mainTimerKey);
|
activeTimerKeys.add(mainTimerKey);
|
||||||
bindLiveElapsedTimer(
|
bindLiveElapsedTimer(
|
||||||
mainTimerKey,
|
mainTimerKey,
|
||||||
`${item.cascadeId}:${act.signature || act.label}`,
|
`${item.cascadeId}:${act.signature || mainLabel}`,
|
||||||
act.startedAtMs,
|
act.startedAtMs,
|
||||||
refs.elapsedEl
|
refs.elapsedEl
|
||||||
);
|
);
|
||||||
|
|
||||||
patchText(refs.mainPhase, act.label || t('live.thinking'));
|
patchText(refs.mainPhase, mainLabel);
|
||||||
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
|
const progText = act.stepProgress ? `[${act.stepProgress}]` : '';
|
||||||
patchAttr(refs.mainProgress, 'hidden', !progText);
|
patchAttr(refs.mainProgress, 'hidden', !progText);
|
||||||
if (progText) {
|
if (progText) {
|
||||||
patchText(refs.mainProgress, progText);
|
patchText(refs.mainProgress, progText);
|
||||||
}
|
}
|
||||||
|
|
||||||
const detailStr = act.detail || '';
|
|
||||||
patchAttr(refs.mainSep, 'hidden', !detailStr);
|
patchAttr(refs.mainSep, 'hidden', !detailStr);
|
||||||
patchAttr(refs.mainDetail, 'hidden', !detailStr);
|
patchAttr(refs.mainDetail, 'hidden', !detailStr);
|
||||||
patchText(refs.mainDetail, detailStr);
|
patchText(refs.mainDetail, detailStr);
|
||||||
|
|
||||||
if (interactive) {
|
if (interactive && !showSessionExtras) {
|
||||||
const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${act.label || ''}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`;
|
const fullTooltip = `[${convTitle}] ${t('fmt.mainAgent')} · ${mainLabel}${progText ? ` ${progText}` : ''}${detailStr ? ` · ${detailStr}` : ''}`;
|
||||||
patchAttr(refs.cardEl, 'title', fullTooltip);
|
patchAttr(refs.cardEl, 'title', fullTooltip);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -397,6 +504,7 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
updateRow: (subRefs, sub) => {
|
updateRow: (subRefs, sub) => {
|
||||||
const subAct = sub.liveActivity || {
|
const subAct = sub.liveActivity || {
|
||||||
phase: sub.isRunning ? 'thinking' : 'done',
|
phase: sub.isRunning ? 'thinking' : 'done',
|
||||||
|
actionKey: sub.isRunning ? 'thinking' : 'done',
|
||||||
label: sub.isRunning ? t('live.thinking') : t('live.done'),
|
label: sub.isRunning ? t('live.thinking') : t('live.done'),
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -413,20 +521,30 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`);
|
patchAttr(subRefs.subBadge, 'class', `agent-badge ${badgeCls}`);
|
||||||
patchText(subRefs.subBadge, subBadgeText);
|
patchText(subRefs.subBadge, subBadgeText);
|
||||||
|
|
||||||
const roleText = sub.role || sub.shortLabel || t('fmt.subAgent');
|
const fallbackRole =
|
||||||
|
sub.agentKind === 'side_question' || sub.isSideQuestion
|
||||||
|
? `${t('fmt.sideQuestion')}${sub.agentOrdinal || sub.sideIndex ? ` #${sub.agentOrdinal || sub.sideIndex}` : ''}`
|
||||||
|
: `${t('fmt.subAgent')}${sub.agentOrdinal || sub.index ? ` #${sub.agentOrdinal || sub.index}` : ''}`;
|
||||||
|
const roleText =
|
||||||
|
sub.customRole !== undefined
|
||||||
|
? sub.customRole || fallbackRole
|
||||||
|
: sub.role || sub.shortLabel || fallbackRole;
|
||||||
patchText(subRefs.subRole, roleText);
|
patchText(subRefs.subRole, roleText);
|
||||||
|
|
||||||
const rawSubLabel = sub.isRunning
|
const subLabel = sub.isRunning
|
||||||
? subAct.label || ''
|
? formatLiveActivityLabel(subAct, 'live.running')
|
||||||
: subAct.label || t('live.done');
|
: formatLiveActivityLabel(subAct, 'live.done');
|
||||||
|
const subDetail = formatLiveActivityDetail(subAct);
|
||||||
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
const subProg = subAct.stepProgress ? ` [${subAct.stepProgress}]` : '';
|
||||||
const summaryStr = [`${rawSubLabel}${subProg}`.trim(), subAct.detail || '']
|
const summaryStr = showSessionExtras
|
||||||
.filter(Boolean)
|
? sub.isRunning
|
||||||
.join(' ');
|
? `${subLabel}${subProg}${subDetail ? ` · ${subDetail}` : ''}`
|
||||||
|
: t('live.doneWithSteps', { steps: sub.stepCount || 0 })
|
||||||
|
: [`${subLabel}${subProg}`.trim(), subDetail].filter(Boolean).join(' ');
|
||||||
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
patchAttr(subRefs.subSummary, 'hidden', !summaryStr);
|
||||||
patchText(subRefs.subSummary, summaryStr);
|
patchText(subRefs.subSummary, summaryStr);
|
||||||
|
|
||||||
if (interactive) {
|
if (interactive && !showSessionExtras) {
|
||||||
patchAttr(
|
patchAttr(
|
||||||
subRefs.rowEl,
|
subRefs.rowEl,
|
||||||
'title',
|
'title',
|
||||||
@@ -439,8 +557,8 @@ export const LiveActivityWidget = defineComponent({
|
|||||||
activeTimerKeys.add(subTimerKey);
|
activeTimerKeys.add(subTimerKey);
|
||||||
bindLiveElapsedTimer(
|
bindLiveElapsedTimer(
|
||||||
subTimerKey,
|
subTimerKey,
|
||||||
`${sub.cascadeId}:${subAct.signature || subAct.label}`,
|
`${sub.cascadeId}:${subAct.signature || subLabel}`,
|
||||||
subAct.startedAtMs,
|
subAct.startedAtMs || sub.lastModifiedMs,
|
||||||
subRefs.subElapsed
|
subRefs.subElapsed
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
patchKeyedList,
|
patchKeyedList,
|
||||||
patchText,
|
patchText,
|
||||||
} from '../../core/domPatch.js';
|
} from '../../core/domPatch.js';
|
||||||
import { getEffectiveLocale, isEnglishLocale, t } from '../../i18n/index.js';
|
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||||
import {
|
import {
|
||||||
DEFAULT_STEP_COLUMN_KEYS,
|
DEFAULT_STEP_COLUMN_KEYS,
|
||||||
STEP_COLUMN_REGISTRY,
|
STEP_COLUMN_REGISTRY,
|
||||||
@@ -25,14 +25,11 @@ import {
|
|||||||
normalizeClientStepTokenComboFormat,
|
normalizeClientStepTokenComboFormat,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
|
|
||||||
export function formatTurnPromptText(rawPrompt) {
|
export function formatTurnPromptText(rawPrompt, { hasMedia = false, mediaOnly = false } = {}) {
|
||||||
const text = String(rawPrompt || '').trim();
|
const text = String(rawPrompt || '').trim();
|
||||||
if (!text || !isEnglishLocale()) return text;
|
if (mediaOnly || (!text && hasMedia)) return t('steps.turnMediaOnly');
|
||||||
if (text === '[图片/附件提问]') return t('steps.turnMediaOnly');
|
if (!text) return '';
|
||||||
if (text.endsWith(' [附图]')) {
|
return hasMedia ? `${text} ${t('steps.turnMediaSuffix')}` : text;
|
||||||
return `${text.slice(0, -5)} ${t('steps.turnMediaSuffix')}`;
|
|
||||||
}
|
|
||||||
return text;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export const StepTableWidget = defineComponent({
|
export const StepTableWidget = defineComponent({
|
||||||
@@ -212,7 +209,13 @@ export const StepTableWidget = defineComponent({
|
|||||||
const getStepIsLatest = (st) =>
|
const getStepIsLatest = (st) =>
|
||||||
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
|
Boolean(useRootTurn ? (st?.isRootLatestTurn ?? st?.isLatestTurn) : st?.isLatestTurn);
|
||||||
const getStepPrompt = (st) =>
|
const getStepPrompt = (st) =>
|
||||||
(useRootTurn ? (st?.rootTurnPrompt ?? st?.turnPrompt) : st?.turnPrompt) || '';
|
(useRootTurn
|
||||||
|
? (st?.rootTurnPromptClean ?? st?.rootTurnPrompt ?? st?.turnPromptClean ?? st?.turnPrompt)
|
||||||
|
: (st?.turnPromptClean ?? st?.turnPrompt)) || '';
|
||||||
|
const getStepHasMedia = (st) =>
|
||||||
|
Boolean(useRootTurn ? (st?.rootTurnHasMedia ?? st?.turnHasMedia) : st?.turnHasMedia);
|
||||||
|
const getStepMediaOnly = (st) =>
|
||||||
|
Boolean(useRootTurn ? (st?.rootTurnMediaOnly ?? st?.turnMediaOnly) : st?.turnMediaOnly);
|
||||||
const turnKeys = showStepTurnRail ? tableSteps.map((st) => {
|
const turnKeys = showStepTurnRail ? tableSteps.map((st) => {
|
||||||
const tIdx = getStepTurnIdx(st);
|
const tIdx = getStepTurnIdx(st);
|
||||||
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
|
if (!Number.isInteger(tIdx) || tIdx <= 0) return '';
|
||||||
@@ -221,8 +224,13 @@ export const StepTableWidget = defineComponent({
|
|||||||
const formattedPrompts = new Map();
|
const formattedPrompts = new Map();
|
||||||
function formattedTurnPrompt(st) {
|
function formattedTurnPrompt(st) {
|
||||||
const raw = getStepPrompt(st);
|
const raw = getStepPrompt(st);
|
||||||
if (!formattedPrompts.has(raw)) formattedPrompts.set(raw, formatTurnPromptText(raw));
|
const hasMedia = getStepHasMedia(st);
|
||||||
return formattedPrompts.get(raw);
|
const mediaOnly = getStepMediaOnly(st);
|
||||||
|
const cacheKey = `${mediaOnly ? 2 : hasMedia ? 1 : 0}:${raw}`;
|
||||||
|
if (!formattedPrompts.has(cacheKey)) {
|
||||||
|
formattedPrompts.set(cacheKey, formatTurnPromptText(raw, { hasMedia, mediaOnly }));
|
||||||
|
}
|
||||||
|
return formattedPrompts.get(cacheKey);
|
||||||
}
|
}
|
||||||
|
|
||||||
const decoratedSteps = tableSteps.map((st, idx) => {
|
const decoratedSteps = tableSteps.map((st, idx) => {
|
||||||
@@ -344,26 +352,38 @@ export const StepTableWidget = defineComponent({
|
|||||||
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
|
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
|
||||||
const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : '';
|
const clickableCls = interactiveBadges && onSelectAgentScopes ? ' is-clickable' : '';
|
||||||
patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`);
|
patchAttr(refs.agentBadgeEl, 'class', `agent-badge${clickableCls} ${badgeCls}`);
|
||||||
const badgeText = isEnglishLocale()
|
const badgeText = formatAgentBadgeText({
|
||||||
? formatAgentBadgeText({
|
agentKind:
|
||||||
isMain: !st.isSubagent,
|
st.agentKind ||
|
||||||
index: st.agentIndex || 0,
|
(!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'),
|
||||||
badgeText: st.agentBadge,
|
agentOrdinal:
|
||||||
})
|
st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0),
|
||||||
: st.agentBadge || (st.isSubagent ? '子' : '主');
|
isMain: !st.isSubagent,
|
||||||
|
isSideQuestion: Boolean(st.isSideQuestion),
|
||||||
|
sideIndex: st.sideIndex || 0,
|
||||||
|
index: st.agentIndex || 0,
|
||||||
|
badgeText: st.agentBadge,
|
||||||
|
});
|
||||||
patchText(refs.agentBadgeEl, badgeText);
|
patchText(refs.agentBadgeEl, badgeText);
|
||||||
|
|
||||||
if (interactiveBadges && onSelectAgentScopes) {
|
if (interactiveBadges && onSelectAgentScopes) {
|
||||||
const targetScope = st.agentId || 'main';
|
const targetScope = st.agentId || 'main';
|
||||||
const isSoleTarget =
|
const isSoleTarget =
|
||||||
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
|
effectiveScopes.length === 1 && effectiveScopes[0] === targetScope;
|
||||||
const agentName = isEnglishLocale()
|
const agentName = formatAgentLabel({
|
||||||
? formatAgentLabel({
|
agentKind:
|
||||||
isMain: !st.isSubagent,
|
st.agentKind ||
|
||||||
index: st.agentIndex || 0,
|
(!st.isSubagent ? 'main' : st.isSideQuestion ? 'side_question' : 'subagent'),
|
||||||
role: st.agentRole || '',
|
agentOrdinal:
|
||||||
})
|
st.agentOrdinal || (st.isSideQuestion ? st.sideIndex || 0 : st.agentIndex || 0),
|
||||||
: st.agentLabel || t('steps.unitAgent');
|
customRole: st.agentCustomRole,
|
||||||
|
isMain: !st.isSubagent,
|
||||||
|
isSideQuestion: Boolean(st.isSideQuestion),
|
||||||
|
sideIndex: st.sideIndex || 0,
|
||||||
|
index: st.agentIndex || 0,
|
||||||
|
role: st.agentRole || '',
|
||||||
|
shortLabel: st.agentLabel || '',
|
||||||
|
});
|
||||||
patchAttr(
|
patchAttr(
|
||||||
refs.agentBadgeEl,
|
refs.agentBadgeEl,
|
||||||
'title',
|
'title',
|
||||||
|
|||||||
@@ -17,8 +17,15 @@ export const THEME_ACCENT_PRESETS = Object.freeze([
|
|||||||
export const FONT_SCALE_FACTORS = Object.freeze({
|
export const FONT_SCALE_FACTORS = Object.freeze({
|
||||||
sm: 0.92,
|
sm: 0.92,
|
||||||
md: 1,
|
md: 1,
|
||||||
lg: 1.08,
|
lg: 1.14,
|
||||||
xl: 1.15,
|
xl: 1.28,
|
||||||
|
});
|
||||||
|
|
||||||
|
export const PANEL_SCALE_FACTORS = Object.freeze({
|
||||||
|
sm: 1,
|
||||||
|
md: 1,
|
||||||
|
lg: 1.09,
|
||||||
|
xl: 1.18,
|
||||||
});
|
});
|
||||||
|
|
||||||
export function normalizeClientThemeAccent(raw) {
|
export function normalizeClientThemeAccent(raw) {
|
||||||
@@ -70,10 +77,13 @@ export function applyAppearanceToRoot(targetEl, settings, { includeFontScale = t
|
|||||||
if (includeFontScale) {
|
if (includeFontScale) {
|
||||||
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
const scaleKey = normalizeClientFontScale(settings?.fontScale);
|
||||||
const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1;
|
const factor = FONT_SCALE_FACTORS[scaleKey] ?? 1;
|
||||||
|
const panelFactor = PANEL_SCALE_FACTORS[scaleKey] ?? 1;
|
||||||
setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor));
|
setOrClearStyleVar(targetEl, '--ui-font-scale', factor === 1 ? '' : String(factor));
|
||||||
|
setOrClearStyleVar(targetEl, '--ui-panel-scale', panelFactor === 1 ? '' : String(panelFactor));
|
||||||
targetEl.setAttribute?.('data-font-scale', scaleKey);
|
targetEl.setAttribute?.('data-font-scale', scaleKey);
|
||||||
} else {
|
} else {
|
||||||
setOrClearStyleVar(targetEl, '--ui-font-scale', '');
|
setOrClearStyleVar(targetEl, '--ui-font-scale', '');
|
||||||
|
setOrClearStyleVar(targetEl, '--ui-panel-scale', '');
|
||||||
if (typeof targetEl.removeAttribute === 'function') {
|
if (typeof targetEl.removeAttribute === 'function') {
|
||||||
targetEl.removeAttribute('data-font-scale');
|
targetEl.removeAttribute('data-font-scale');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,17 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||||
|
import {
|
||||||
|
normalizeModelDisplayMode,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
|
} from '../../shared/settings-normalization.mjs';
|
||||||
|
import {
|
||||||
|
classifyCacheTier,
|
||||||
|
classifySpeedTier,
|
||||||
|
classifyStepCostTier,
|
||||||
|
classifyTtftTier,
|
||||||
|
formatCompactTokens,
|
||||||
|
} from '../../shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
const EN_MONTH_SHORT = Object.freeze([
|
const EN_MONTH_SHORT = Object.freeze([
|
||||||
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
|
||||||
@@ -21,53 +32,24 @@ export function formatCachePct(value) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getSpeedToneClass(tokPerSec) {
|
export function getSpeedToneClass(tokPerSec) {
|
||||||
if (tokPerSec == null || !Number.isFinite(Number(tokPerSec)) || Number(tokPerSec) <= 0) {
|
return `tone-${classifySpeedTier(tokPerSec)}`;
|
||||||
return 'tone-muted';
|
|
||||||
}
|
|
||||||
const v = Number(tokPerSec);
|
|
||||||
if (v >= 60) return 'tone-good';
|
|
||||||
if (v >= 35) return 'tone-info';
|
|
||||||
if (v >= 20) return 'tone-warn';
|
|
||||||
return 'tone-danger';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getCacheToneClass(cacheHitPct, promptTokens = null) {
|
export function getCacheToneClass(cacheHitPct, promptTokens = null) {
|
||||||
if (cacheHitPct == null || !Number.isFinite(Number(cacheHitPct))) {
|
return `tone-${classifyCacheTier(cacheHitPct, promptTokens)}`;
|
||||||
return 'tone-muted';
|
|
||||||
}
|
|
||||||
const v = Number(cacheHitPct);
|
|
||||||
if (promptTokens != null && Number(promptTokens) <= 0 && v <= 0) {
|
|
||||||
return 'tone-muted';
|
|
||||||
}
|
|
||||||
if (v >= 85) return 'tone-good';
|
|
||||||
if (v >= 65) return 'tone-info';
|
|
||||||
if (v >= 30) return 'tone-warn';
|
|
||||||
return 'tone-danger';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getStepCostToneClass(costUsd) {
|
export function getStepCostToneClass(costUsd) {
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '';
|
const tier = classifyStepCostTier(costUsd);
|
||||||
const v = Number(costUsd);
|
return tier ? `tone-${tier}` : '';
|
||||||
if (v >= 0.3) return 'tone-danger';
|
|
||||||
if (v >= 0.15) return 'tone-warn';
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getTtftToneClass(ttftSec) {
|
export function getTtftToneClass(ttftSec) {
|
||||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '';
|
const tier = classifyTtftTier(ttftSec);
|
||||||
const v = Number(ttftSec);
|
return tier === 'warn' || tier === 'danger' ? `tone-${tier}` : '';
|
||||||
if (v >= 30) return 'tone-danger';
|
|
||||||
if (v >= 18) return 'tone-warn';
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatTokens(num) {
|
export const formatTokens = formatCompactTokens;
|
||||||
const n = Number(num || 0);
|
|
||||||
if (n >= 1_000_000_000) return `${(n / 1_000_000_000).toFixed(2)}B`;
|
|
||||||
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
|
|
||||||
if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
|
|
||||||
return String(Math.round(n));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatTokensPrecise(num) {
|
export function formatTokensPrecise(num) {
|
||||||
const n = Number(num || 0);
|
const n = Number(num || 0);
|
||||||
@@ -172,23 +154,7 @@ export function formatElapsedSec(seconds) {
|
|||||||
return `${h}h ${remM}m`;
|
return `${h}h ${remM}m`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export { normalizeModelDisplayMode };
|
||||||
* 归一化普通模型显示模式(`'short'` 精简代号 | `'upstream_compact'` 去厂商前缀原始 ID | `'upstream'` 完整原始 ID)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyShowUpstream]
|
|
||||||
* @returns {'short'|'upstream_compact'|'upstream'}
|
|
||||||
*/
|
|
||||||
export function normalizeModelDisplayMode(mode, legacyShowUpstream) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
|
||||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
|
||||||
return 'upstream_compact';
|
|
||||||
}
|
|
||||||
if (m === 'short') return 'short';
|
|
||||||
if (legacyShowUpstream === true) return 'upstream';
|
|
||||||
return 'short';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
|
* 隐藏原始模型 ID 开头的 `gemini-`、`claude-`、`gpt-` 厂商前缀以节省单行表格空间(确保剥离后非空)。
|
||||||
@@ -208,15 +174,7 @@ function stripCompactionMarker(rawText) {
|
|||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export const normalizeOrchestratorIdDisplayMode = normalizeOrchestratorIdMode;
|
||||||
* 归一化 Orchestrator 系列 ID 显示格式枚举(`'compact'` 精简代号 vs `'full'` 原始完整 ID,默认 `'compact'`)。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @returns {'compact'|'full'}
|
|
||||||
*/
|
|
||||||
export function normalizeOrchestratorIdDisplayMode(mode) {
|
|
||||||
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。
|
* 统一解析步骤、会话摘要或模型汇总行面向用户的模型显示文本与悬停提示。
|
||||||
@@ -259,23 +217,35 @@ export function resolveModelDisplayInfo(target, settings = {}, options = {}) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const shortText = String(
|
const shortText = String(
|
||||||
target.activeModelShort ?? target.modelShort ?? target.shortName ?? ''
|
target.activeBaseModelShort ??
|
||||||
|
target.baseModelShort ??
|
||||||
|
target.activeModelShort ??
|
||||||
|
target.modelShort ??
|
||||||
|
target.shortName ??
|
||||||
|
''
|
||||||
).trim();
|
).trim();
|
||||||
const labelText = String(
|
const labelText = String(
|
||||||
target.activeModelLabel ?? target.modelLabel ?? target.label ?? ''
|
target.activeBaseModelLabel ??
|
||||||
|
target.baseModelLabel ??
|
||||||
|
target.activeModelLabel ??
|
||||||
|
target.modelLabel ??
|
||||||
|
target.label ??
|
||||||
|
''
|
||||||
).trim();
|
).trim();
|
||||||
const upstreamText = String(
|
const upstreamText = String(
|
||||||
target.activeModelUpstream ?? target.modelUpstream ?? target.upstreamName ?? ''
|
target.baseModelUpstream ??
|
||||||
|
target.activeModelUpstream ??
|
||||||
|
target.modelUpstream ??
|
||||||
|
target.upstreamName ??
|
||||||
|
''
|
||||||
).trim();
|
).trim();
|
||||||
|
const rawCompactionText = `${target.activeModelShort ?? target.modelShort ?? ''} ${target.activeModelLabel ?? target.modelLabel ?? ''} ${target.activeModelUpstream ?? target.modelUpstream ?? ''}`;
|
||||||
const responseText = String(target.responseModel ?? '').trim();
|
const responseText = String(target.responseModel ?? '').trim();
|
||||||
const modelKeyText = String(target.modelKey ?? '').trim();
|
const modelKeyText = String(target.modelKey ?? '').trim();
|
||||||
|
|
||||||
const isCompaction =
|
const isCompaction =
|
||||||
Boolean(target.isCompactionStep) ||
|
Boolean(target.isCompactionStep) ||
|
||||||
/·(?:压缩|compact)\s*$/iu.test(shortText) ||
|
/·(?:压缩|compact)(?=\s|$)|\[自动压缩\]/iu.test(rawCompactionText);
|
||||||
/·(?:压缩|compact)\s*$/iu.test(upstreamText) ||
|
|
||||||
/·(?:压缩|compact)\s*$/iu.test(labelText) ||
|
|
||||||
/\[自动压缩\]\s*$/u.test(labelText);
|
|
||||||
|
|
||||||
const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : '';
|
const compactionSuffix = isCompaction ? t('fmt.compactionSuffix') : '';
|
||||||
|
|
||||||
@@ -512,3 +482,131 @@ export function mergeModelsByDisplayName(models = [], settings = {}, options = {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据代理索引返回对应的微边框语义徽章样式类名。
|
||||||
|
*
|
||||||
|
* @param {number} [index=0]
|
||||||
|
* @param {boolean} [isMain=false]
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function getAgentBadgeClass(index = 0, isMain = false) {
|
||||||
|
if (isMain || index <= 0) return 'badge-main';
|
||||||
|
const slot = ((index - 1) % 3) + 1;
|
||||||
|
return `badge-sub-${slot}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于结构化 `agentKind` / `agentOrdinal` 格式化主/子代理或旁路提问的紧凑徽章文本(零正则反拆中文)。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} agent
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function formatAgentBadgeText(agent) {
|
||||||
|
if (!agent) return t('fmt.mainBadge');
|
||||||
|
const kind =
|
||||||
|
agent.agentKind ||
|
||||||
|
(agent.isMain
|
||||||
|
? 'main'
|
||||||
|
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||||
|
? 'side_question'
|
||||||
|
: 'subagent');
|
||||||
|
if (kind === 'all') return t('header.scopeAllShort');
|
||||||
|
if (kind === 'main') return t('fmt.mainBadge');
|
||||||
|
if (kind === 'side_question') {
|
||||||
|
const ord = Number(agent.agentOrdinal || agent.sideIndex || 0);
|
||||||
|
if (ord > 0) return t('fmt.sideBadge', { index: ord });
|
||||||
|
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||||
|
return t('fmt.sideBadgeShort');
|
||||||
|
}
|
||||||
|
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||||
|
if (ord > 0) return t('fmt.subBadge', { index: ord });
|
||||||
|
if (!isEnglishLocale() && agent.badgeText) return String(agent.badgeText);
|
||||||
|
return t('fmt.subBadgeShort');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于结构化 `agentKind` / `agentOrdinal` / `customRole` 格式化代理完整显示名称(零正则反拆中文)。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} agent
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function formatAgentLabel(agent) {
|
||||||
|
if (!agent) return t('fmt.mainAgent');
|
||||||
|
const kind =
|
||||||
|
agent.agentKind ||
|
||||||
|
(agent.isMain
|
||||||
|
? 'main'
|
||||||
|
: agent.isSideQuestion || agent.typeName === 'side_question'
|
||||||
|
? 'side_question'
|
||||||
|
: 'subagent');
|
||||||
|
if (kind === 'all') return t('header.scopeAll');
|
||||||
|
if (kind === 'main') return t('fmt.mainAgent');
|
||||||
|
|
||||||
|
const rawCustom =
|
||||||
|
agent.customRole !== undefined
|
||||||
|
? String(agent.customRole || '').trim()
|
||||||
|
: String(agent.role || '').trim();
|
||||||
|
if (kind === 'side_question') {
|
||||||
|
const ord = Number(agent.agentOrdinal || agent.sideIndex || 0);
|
||||||
|
const baseLabel = ord > 0 ? `${t('fmt.sideQuestion')} #${ord}` : t('fmt.sideQuestion');
|
||||||
|
const isGeneric =
|
||||||
|
!rawCustom ||
|
||||||
|
rawCustom === baseLabel ||
|
||||||
|
rawCustom === agent.shortLabel ||
|
||||||
|
rawCustom === t('fmt.sideQuestion') ||
|
||||||
|
rawCustom === 'Side Question' ||
|
||||||
|
rawCustom === 'side_question';
|
||||||
|
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ord = Number(agent.agentOrdinal || agent.index || 0);
|
||||||
|
const baseLabel = ord > 0 ? `${t('fmt.subAgent')} #${ord}` : t('fmt.subAgent');
|
||||||
|
const isGeneric =
|
||||||
|
!rawCustom ||
|
||||||
|
rawCustom === baseLabel ||
|
||||||
|
rawCustom === agent.shortLabel ||
|
||||||
|
rawCustom === t('fmt.subAgent') ||
|
||||||
|
rawCustom === 'Subagent';
|
||||||
|
return isGeneric ? baseLabel : `${baseLabel} · ${rawCustom}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于后端结构化 `actionKey` + `waitingApproval` 渲染实时动作短标题(兼容自定义 `label` 回退)。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} act
|
||||||
|
* @param {string} [fallbackKey='live.thinking']
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function formatLiveActivityLabel(act, fallbackKey = 'live.thinking') {
|
||||||
|
if (!act || typeof act !== 'object') return t(fallbackKey);
|
||||||
|
let baseLabel = '';
|
||||||
|
if (act.actionKey) {
|
||||||
|
const i18nKey = `live.act.${act.actionKey}`;
|
||||||
|
const translated = t(i18nKey);
|
||||||
|
if (translated && translated !== i18nKey) {
|
||||||
|
baseLabel = translated;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!baseLabel) {
|
||||||
|
baseLabel = String(act.label || '').trim() || t(fallbackKey);
|
||||||
|
}
|
||||||
|
if (act.waitingApproval) {
|
||||||
|
return t('live.act.awaitingApproval', { label: baseLabel });
|
||||||
|
}
|
||||||
|
return baseLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 基于后端结构化 `detailKey` 渲染实时动作补充说明(兼容自由文本 `detail`)。
|
||||||
|
*
|
||||||
|
* @param {object|null|undefined} act
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export function formatLiveActivityDetail(act) {
|
||||||
|
if (!act || typeof act !== 'object') return '';
|
||||||
|
if (act.detailKey === 'compaction_resuming') {
|
||||||
|
return t('live.act.compactionResuming');
|
||||||
|
}
|
||||||
|
return String(act.detail || '');
|
||||||
|
}
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
|
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
|
||||||
|
|
||||||
const inFlightGets = new Map();
|
const inFlightGets = new Map();
|
||||||
const activeControllers = new Map();
|
const activeControllers = new Map();
|
||||||
|
|
||||||
@@ -13,8 +15,7 @@ const activeControllers = new Map();
|
|||||||
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
|
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
|
||||||
*/
|
*/
|
||||||
export function getWindowBridgeConfig() {
|
export function getWindowBridgeConfig() {
|
||||||
if (typeof window === 'undefined') return null;
|
const br = readInjectedWindowBridge();
|
||||||
const br = window.__AGUsageMonitorBridge;
|
|
||||||
const port = Number(br?.port || 0);
|
const port = Number(br?.port || 0);
|
||||||
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
|
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
|
||||||
return br;
|
return br;
|
||||||
|
|||||||
@@ -55,6 +55,9 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'fmt.subAgent': 'Subagent',
|
'fmt.subAgent': 'Subagent',
|
||||||
'fmt.subBadge': 'S{index}',
|
'fmt.subBadge': 'S{index}',
|
||||||
'fmt.subBadgeShort': 'Sub',
|
'fmt.subBadgeShort': 'Sub',
|
||||||
|
'fmt.sideQuestion': 'Side Question',
|
||||||
|
'fmt.sideBadge': 'Q{index}',
|
||||||
|
'fmt.sideBadgeShort': 'Q',
|
||||||
'fmt.selectedCount': '{count} {unit} selected',
|
'fmt.selectedCount': '{count} {unit} selected',
|
||||||
'fmt.selectedListTitle': 'Selected ({count}): {names}',
|
'fmt.selectedListTitle': 'Selected ({count}): {names}',
|
||||||
'fmt.selectPlaceholder': 'Select',
|
'fmt.selectPlaceholder': 'Select',
|
||||||
@@ -179,6 +182,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'live.currentSession': 'Current Session',
|
'live.currentSession': 'Current Session',
|
||||||
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
'live.switchSessionTitle': 'Switch monitor to session: {title}',
|
||||||
'live.thinking': 'Thinking',
|
'live.thinking': 'Thinking',
|
||||||
|
'live.generating': 'Generating',
|
||||||
'live.running': 'Running',
|
'live.running': 'Running',
|
||||||
'live.done': 'Done',
|
'live.done': 'Done',
|
||||||
'live.doneWithSteps': 'Done ({steps} steps)',
|
'live.doneWithSteps': 'Done ({steps} steps)',
|
||||||
@@ -431,6 +435,21 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
|
'settings.str.mountDual': 'Dual Mount (Titlebar + Sidebar)',
|
||||||
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
'settings.str.mountComposer': 'Composer Mount (Input Box + Sidebar)',
|
||||||
'settings.str.mountSidebar': 'Sidebar Only',
|
'settings.str.mountSidebar': 'Sidebar Only',
|
||||||
|
'settings.bridge.restartTitle': 'Launch Flag Auto-Configured — Restart Once to Activate',
|
||||||
|
'settings.bridge.ctxRestartTitle': 'Launch Flag Auto-Configured — Restart Once for Context Override',
|
||||||
|
'settings.bridge.restartBody': 'Automatically added --remote-debugging-port=0 to your shortcuts and startup entries (future launches mount 100% automatically). Click below to close tray processes and relaunch now.',
|
||||||
|
'settings.bridge.noPortTitle': 'Local Debug Port Missing — Window Mount Inactive',
|
||||||
|
'settings.bridge.unreachableTitle': 'Local Debug Port Not Ready — Window Mount Inactive',
|
||||||
|
'settings.bridge.ctxTitle': 'Local Debug Port Inactive — Context Override Pending',
|
||||||
|
'settings.bridge.guideWin': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to auto-configure shortcuts, close tray background processes, and relaunch.',
|
||||||
|
'settings.bridge.guideMac': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to relaunch with the flag in one click, or run open -a "Antigravity" --args --remote-debugging-port=0.',
|
||||||
|
'settings.bridge.guideLinux': 'Antigravity 2.33.0+ no longer opens a debug port by default. Click "Relaunch & Enable Mount" to update your .desktop launcher and relaunch.',
|
||||||
|
'settings.bridge.relaunchBtn': 'Relaunch & Enable Mount',
|
||||||
|
'settings.bridge.relaunchingBtn': 'Relaunching Host...',
|
||||||
|
'settings.bridge.relaunchFailed': 'Auto-relaunch failed — quit from tray and retry',
|
||||||
|
'settings.bridge.dismissAria': 'Dismiss notice for now',
|
||||||
|
'settings.bridge.copyFlagBtn': 'Copy {cmd}',
|
||||||
|
'settings.bridge.copiedBtn': 'Copied to Clipboard',
|
||||||
'settings.str.popoverWidthLabel': 'Popover Width',
|
'settings.str.popoverWidthLabel': 'Popover Width',
|
||||||
'settings.str.popoverWidthAuto': 'Auto Fit',
|
'settings.str.popoverWidthAuto': 'Auto Fit',
|
||||||
'settings.str.popoverWidthCustom': 'Custom',
|
'settings.str.popoverWidthCustom': 'Custom',
|
||||||
@@ -499,6 +518,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'settings.oth.ctxUnavailable': '{name} (currently unavailable)',
|
'settings.oth.ctxUnavailable': '{name} (currently unavailable)',
|
||||||
'settings.oth.ctxConfigured': '{name} · Set',
|
'settings.oth.ctxConfigured': '{name} · Set',
|
||||||
'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}',
|
'settings.oth.ctxConfiguredReported': '{name} · Set / Last seen {reported}',
|
||||||
|
'settings.oth.ctxPendingBridge': '{name} · Pending Restart',
|
||||||
'settings.oth.ctxDefaultReported': 'Default · Last seen {name}',
|
'settings.oth.ctxDefaultReported': 'Default · Last seen {name}',
|
||||||
'settings.oth.ctxReported': 'The host reported {name} on the latest request.',
|
'settings.oth.ctxReported': 'The host reported {name} on the latest request.',
|
||||||
'settings.oth.ctxMixed': 'Different limits by thinking level',
|
'settings.oth.ctxMixed': 'Different limits by thinking level',
|
||||||
@@ -519,4 +539,87 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
|||||||
'settings.oth.resetConfirmBtn': 'Click Again to Confirm',
|
'settings.oth.resetConfirmBtn': 'Click Again to Confirm',
|
||||||
'settings.oth.resettingBtn': 'Resetting…',
|
'settings.oth.resettingBtn': 'Resetting…',
|
||||||
'settings.oth.resetAllDone': 'All preferences restored to defaults',
|
'settings.oth.resetAllDone': 'All preferences restored to defaults',
|
||||||
|
|
||||||
|
// Structured Live Activity Actions
|
||||||
|
'live.act.run_command': 'Run Command',
|
||||||
|
'live.act.read_file': 'Read File',
|
||||||
|
'live.act.edit_file': 'Edit File',
|
||||||
|
'live.act.write_file': 'Write File',
|
||||||
|
'live.act.grep_search': 'Search Code',
|
||||||
|
'live.act.find_file': 'Find Files',
|
||||||
|
'live.act.read_url': 'Read Web Page',
|
||||||
|
'live.act.search_web': 'Search Web',
|
||||||
|
'live.act.invoke_subagent': 'Invoke Subagent',
|
||||||
|
'live.act.send_message': 'Message Subagent',
|
||||||
|
'live.act.manage_subagents': 'Manage Subagents',
|
||||||
|
'live.act.manage_task': 'Manage Task',
|
||||||
|
'live.act.schedule': 'Schedule Task',
|
||||||
|
'live.act.ask_question': 'Waiting for User Choice',
|
||||||
|
'live.act.search_marketplace': 'Search Plugins',
|
||||||
|
'live.act.mcp_tool': 'Call MCP Tool',
|
||||||
|
'live.act.tool_call': 'Call Tool',
|
||||||
|
'live.act.thinking': 'Thinking',
|
||||||
|
'live.act.compacting': 'Compacting Context',
|
||||||
|
'live.act.responding': 'Responding',
|
||||||
|
'live.act.waiting_subagent': 'Waiting for Subagent',
|
||||||
|
'live.act.starting': 'Starting',
|
||||||
|
'live.act.done': 'Completed',
|
||||||
|
'live.act.awaitingApproval': 'Awaiting Approval · {label}',
|
||||||
|
'live.act.compactionResuming': 'Compaction finished, resuming reasoning',
|
||||||
|
|
||||||
|
// SVG Charts (SessionStepCharts & TrendAreaChart)
|
||||||
|
'chart.step.empty': 'No plottable steps in current scope',
|
||||||
|
'chart.step.excluded': 'Excluded',
|
||||||
|
'chart.step.zeroSteps': '0 steps',
|
||||||
|
'chart.step.stepAdd': 'Step +{tokens}',
|
||||||
|
'chart.step.ioSplit': 'In {inTok} · Cache {cacheTok} · Out {outTok}',
|
||||||
|
'chart.step.cacheShort': 'Cache {pct}%',
|
||||||
|
'chart.step.compactionCheckpoint': 'Auto-compaction checkpoint',
|
||||||
|
'chart.step.cacheHitOut': 'Cache hit {pct}% · Out +{outTok}',
|
||||||
|
'chart.step.ttftShort': 'TTFT {sec}s',
|
||||||
|
'chart.step.outAndCtx': 'Out {outTok} · Context {ctxTok}',
|
||||||
|
'chart.step.compactionStep': 'Compaction step',
|
||||||
|
'chart.step.noSpeedSample': 'No speed sample',
|
||||||
|
'chart.step.ctxAndCache': 'Context {ctxTok} · Cache {pct}%',
|
||||||
|
'chart.step.noTtftSample': 'No TTFT sample',
|
||||||
|
'chart.step.cumCost': 'Total {cost}',
|
||||||
|
'chart.step.cacheAndStepTok': 'Cache {pct}% · Step {tokens}',
|
||||||
|
'chart.step.noSamples': 'No samples',
|
||||||
|
'chart.step.peakShort': 'Peak {val}',
|
||||||
|
'chart.step.peakPill': 'Peak {tag} · {val}',
|
||||||
|
'chart.step.stepsCount': '{count} steps',
|
||||||
|
'chart.step.multiPrefix': '{count} models · ',
|
||||||
|
'chart.step.sumTokens': '{prefix}Total {tokens}',
|
||||||
|
'chart.step.peakTokens': '{prefix}Peak {tokens}',
|
||||||
|
'chart.step.currentCtx': 'Current {tokens}',
|
||||||
|
'chart.step.meanTps': '{prefix}Avg {val} tok/s',
|
||||||
|
'chart.step.meanSec': '{prefix}Avg {val}s',
|
||||||
|
'chart.step.noValidSamples': 'No valid samples',
|
||||||
|
'chart.step.sumCost': '{prefix}Total {cost}',
|
||||||
|
'chart.fit.empty': 'No valid regression samples for this model',
|
||||||
|
'chart.fit.loess': 'LOESS Fit',
|
||||||
|
'chart.fit.olsLinear': 'OLS Linear',
|
||||||
|
'chart.fit.olsReg': 'OLS Reg',
|
||||||
|
'chart.fit.observed': 'Observed',
|
||||||
|
'chart.fit.tipFit': 'Fit {val}',
|
||||||
|
'chart.fit.tipObs': 'Obs {val}',
|
||||||
|
'chart.fit.zeroSamples': '0 samples',
|
||||||
|
'chart.fit.peerMean': '{label} Avg {val}',
|
||||||
|
'chart.fit.peerCompare': 'Compare: {peers}',
|
||||||
|
'chart.fit.curvesCount': '{count} fit curves',
|
||||||
|
'chart.fit.multiBadge': '{steps} steps · {models} models',
|
||||||
|
'chart.fit.singleBadge': '{steps} steps · Avg {mean}',
|
||||||
|
'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · Sample SD = ±{sd}',
|
||||||
|
'chart.trend.hmMonthYear': "{month}/{yy}",
|
||||||
|
'chart.trend.hmMonthOnly': 'M{month}',
|
||||||
|
'chart.trend.wdayMon': 'M',
|
||||||
|
'chart.trend.wdayWed': 'W',
|
||||||
|
'chart.trend.wdayFri': 'F',
|
||||||
|
'chart.trend.wdaySun': 'S',
|
||||||
|
'chart.trend.hmAria': 'Daily usage heatmap',
|
||||||
|
'chart.trend.hmLess': 'Less',
|
||||||
|
'chart.trend.hmMore': 'More',
|
||||||
|
'chart.trend.hmActivePeak': 'Active {active}/{total}d · Peak {label} · {tokens}',
|
||||||
|
'chart.trend.hmActiveZero': 'Active 0/{total}d',
|
||||||
|
'chart.trend.peakPill': 'Peak {label} · {tokens}',
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
|
import { normalizeLanguageSetting } from '../../shared/settings-normalization.mjs';
|
||||||
import { I18N_MESSAGES_ZH_CN } from './zh-CN.js';
|
import { I18N_MESSAGES_ZH_CN } from './zh-CN.js';
|
||||||
import { I18N_MESSAGES_EN_US } from './en-US.js';
|
import { I18N_MESSAGES_EN_US } from './en-US.js';
|
||||||
|
|
||||||
@@ -13,11 +14,7 @@ export const I18N_DICTIONARIES = Object.freeze({
|
|||||||
});
|
});
|
||||||
|
|
||||||
export function normalizeI18nLanguage(raw) {
|
export function normalizeI18nLanguage(raw) {
|
||||||
const val = String(raw ?? '').trim();
|
return normalizeLanguageSetting(raw);
|
||||||
if (val === 'auto') return 'auto';
|
|
||||||
if (/^en(?:-|$)/i.test(val)) return 'en-US';
|
|
||||||
if (/^zh(?:-|$)/i.test(val)) return 'zh-CN';
|
|
||||||
return 'zh-CN';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export function detectHostSystemLocale() {
|
export function detectHostSystemLocale() {
|
||||||
|
|||||||
@@ -55,6 +55,9 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'fmt.subAgent': '子代理',
|
'fmt.subAgent': '子代理',
|
||||||
'fmt.subBadge': '子{index}',
|
'fmt.subBadge': '子{index}',
|
||||||
'fmt.subBadgeShort': '子',
|
'fmt.subBadgeShort': '子',
|
||||||
|
'fmt.sideQuestion': '旁路提问',
|
||||||
|
'fmt.sideBadge': '旁{index}',
|
||||||
|
'fmt.sideBadgeShort': '旁',
|
||||||
'fmt.selectedCount': '已选 {count} {unit}',
|
'fmt.selectedCount': '已选 {count} {unit}',
|
||||||
'fmt.selectedListTitle': '已选 ({count}):{names}',
|
'fmt.selectedListTitle': '已选 ({count}):{names}',
|
||||||
'fmt.selectPlaceholder': '请选择',
|
'fmt.selectPlaceholder': '请选择',
|
||||||
@@ -179,6 +182,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'live.currentSession': '当前会话',
|
'live.currentSession': '当前会话',
|
||||||
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
'live.switchSessionTitle': '点击切换查看会话:{title}',
|
||||||
'live.thinking': '推理中',
|
'live.thinking': '推理中',
|
||||||
|
'live.generating': '生成中',
|
||||||
'live.running': '运行中',
|
'live.running': '运行中',
|
||||||
'live.done': '已完成',
|
'live.done': '已完成',
|
||||||
'live.doneWithSteps': '已完成 ({steps} 步)',
|
'live.doneWithSteps': '已完成 ({steps} 步)',
|
||||||
@@ -431,6 +435,21 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
'settings.str.mountDual': '双栖挂载 (顶部栏 + 侧边栏)',
|
||||||
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
'settings.str.mountComposer': '输入框挂载 (输入框 + 侧边栏)',
|
||||||
'settings.str.mountSidebar': '仅侧边栏',
|
'settings.str.mountSidebar': '仅侧边栏',
|
||||||
|
'settings.bridge.restartTitle': '已自动补齐启动参数,重启一次即可启用悬浮胶囊',
|
||||||
|
'settings.bridge.ctxRestartTitle': '已自动补齐启动参数,重启一次即可激活上下文覆写',
|
||||||
|
'settings.bridge.restartBody': '已自动为桌面 / 开始菜单 / 任务栏快捷方式及自启项写入 --remote-debugging-port=0(后续每次正常打开均 100% 全自动挂载)。点击下方按钮即可退出托盘后台并立即生效。',
|
||||||
|
'settings.bridge.noPortTitle': '未检测到本地调试端口,主窗口挂载暂未生效',
|
||||||
|
'settings.bridge.unreachableTitle': '本地调试端口未就绪,主窗口挂载暂未生效',
|
||||||
|
'settings.bridge.ctxTitle': '未连通本地调试通道,上下文窗口覆写暂未注入',
|
||||||
|
'settings.bridge.guideWin': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动补齐快捷方式参数、退出托盘后台并带参重启生效。',
|
||||||
|
'settings.bridge.guideMac': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可一键带参重开客户端生效,也可复制参数通过 open -a "Antigravity" --args --remote-debugging-port=0 启动。',
|
||||||
|
'settings.bridge.guideLinux': 'Antigravity 2.33.0+ 默认不再开启调试端口。点击「立即重启并启用挂载」即可自动写入 .desktop 启动器并重启生效。',
|
||||||
|
'settings.bridge.relaunchBtn': '立即重启并启用挂载',
|
||||||
|
'settings.bridge.relaunchingBtn': '正在重启客户端...',
|
||||||
|
'settings.bridge.relaunchFailed': '自动重启失败,请从托盘退出后重试',
|
||||||
|
'settings.bridge.dismissAria': '暂时关闭提示',
|
||||||
|
'settings.bridge.copyFlagBtn': '复制 {cmd}',
|
||||||
|
'settings.bridge.copiedBtn': '已复制启动参数',
|
||||||
'settings.str.popoverWidthLabel': '悬浮面板宽度',
|
'settings.str.popoverWidthLabel': '悬浮面板宽度',
|
||||||
'settings.str.popoverWidthAuto': '自适应',
|
'settings.str.popoverWidthAuto': '自适应',
|
||||||
'settings.str.popoverWidthCustom': '指定宽度',
|
'settings.str.popoverWidthCustom': '指定宽度',
|
||||||
@@ -499,6 +518,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'settings.oth.ctxUnavailable': '{name}(当前不可用)',
|
'settings.oth.ctxUnavailable': '{name}(当前不可用)',
|
||||||
'settings.oth.ctxConfigured': '{name} · 已设置',
|
'settings.oth.ctxConfigured': '{name} · 已设置',
|
||||||
'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}',
|
'settings.oth.ctxConfiguredReported': '{name} · 已设置 / 最近 {reported}',
|
||||||
|
'settings.oth.ctxPendingBridge': '{name} · 待重启生效',
|
||||||
'settings.oth.ctxDefaultReported': '默认 · 最近 {name}',
|
'settings.oth.ctxDefaultReported': '默认 · 最近 {name}',
|
||||||
'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。',
|
'settings.oth.ctxReported': '最近一次请求由宿主报告为 {name}。',
|
||||||
'settings.oth.ctxMixed': '各推理档设置不同',
|
'settings.oth.ctxMixed': '各推理档设置不同',
|
||||||
@@ -519,4 +539,87 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
|||||||
'settings.oth.resetConfirmBtn': '再次点击确认重置',
|
'settings.oth.resetConfirmBtn': '再次点击确认重置',
|
||||||
'settings.oth.resettingBtn': '重置中…',
|
'settings.oth.resettingBtn': '重置中…',
|
||||||
'settings.oth.resetAllDone': '已恢复全部默认设置',
|
'settings.oth.resetAllDone': '已恢复全部默认设置',
|
||||||
|
|
||||||
|
// Structured Live Activity Actions
|
||||||
|
'live.act.run_command': '执行命令',
|
||||||
|
'live.act.read_file': '读取文件',
|
||||||
|
'live.act.edit_file': '修改文件',
|
||||||
|
'live.act.write_file': '写入文件',
|
||||||
|
'live.act.grep_search': '搜索代码',
|
||||||
|
'live.act.find_file': '查找文件',
|
||||||
|
'live.act.read_url': '读取网页',
|
||||||
|
'live.act.search_web': '网页搜索',
|
||||||
|
'live.act.invoke_subagent': '调用子代理',
|
||||||
|
'live.act.send_message': '通信子代理',
|
||||||
|
'live.act.manage_subagents': '管理子代理',
|
||||||
|
'live.act.manage_task': '后台任务',
|
||||||
|
'live.act.schedule': '定时任务',
|
||||||
|
'live.act.ask_question': '等待用户选择',
|
||||||
|
'live.act.search_marketplace': '查询插件',
|
||||||
|
'live.act.mcp_tool': '调用 MCP',
|
||||||
|
'live.act.tool_call': '调用工具',
|
||||||
|
'live.act.thinking': '推理中',
|
||||||
|
'live.act.compacting': '上下文压缩',
|
||||||
|
'live.act.responding': '正在输出回复',
|
||||||
|
'live.act.waiting_subagent': '等待子代理',
|
||||||
|
'live.act.starting': '启动中',
|
||||||
|
'live.act.done': '已完成',
|
||||||
|
'live.act.awaitingApproval': '等待确认 · {label}',
|
||||||
|
'live.act.compactionResuming': '已完成压缩,正在恢复推理',
|
||||||
|
|
||||||
|
// SVG Charts (SessionStepCharts & TrendAreaChart)
|
||||||
|
'chart.step.empty': '当前范围暂无可绘制的调用步骤',
|
||||||
|
'chart.step.excluded': '未纳入',
|
||||||
|
'chart.step.zeroSteps': '0 步',
|
||||||
|
'chart.step.stepAdd': '本步 +{tokens}',
|
||||||
|
'chart.step.ioSplit': '入 {inTok} · 缓 {cacheTok} · 出 {outTok}',
|
||||||
|
'chart.step.cacheShort': '缓存 {pct}%',
|
||||||
|
'chart.step.compactionCheckpoint': '上下文自动压缩检查点',
|
||||||
|
'chart.step.cacheHitOut': '缓存命中 {pct}% · 输出 +{outTok}',
|
||||||
|
'chart.step.ttftShort': '首字 {sec}s',
|
||||||
|
'chart.step.outAndCtx': '输出 {outTok} · 上下文 {ctxTok}',
|
||||||
|
'chart.step.compactionStep': '上下文压缩步',
|
||||||
|
'chart.step.noSpeedSample': '无测速样本',
|
||||||
|
'chart.step.ctxAndCache': '上下文 {ctxTok} · 缓存 {pct}%',
|
||||||
|
'chart.step.noTtftSample': '无首字计时样本',
|
||||||
|
'chart.step.cumCost': '累计 {cost}',
|
||||||
|
'chart.step.cacheAndStepTok': '缓存 {pct}% · 本步 {tokens}',
|
||||||
|
'chart.step.noSamples': '无样本',
|
||||||
|
'chart.step.peakShort': '峰 {val}',
|
||||||
|
'chart.step.peakPill': '峰值 {tag} · {val}',
|
||||||
|
'chart.step.stepsCount': '{count}步',
|
||||||
|
'chart.step.multiPrefix': '{count} 模型 · ',
|
||||||
|
'chart.step.sumTokens': '{prefix}累计 {tokens}',
|
||||||
|
'chart.step.peakTokens': '{prefix}峰值 {tokens}',
|
||||||
|
'chart.step.currentCtx': '当前 {tokens}',
|
||||||
|
'chart.step.meanTps': '{prefix}均值 {val} tok/s',
|
||||||
|
'chart.step.meanSec': '{prefix}均值 {val}s',
|
||||||
|
'chart.step.noValidSamples': '暂无有效样本',
|
||||||
|
'chart.step.sumCost': '{prefix}累计 {cost}',
|
||||||
|
'chart.fit.empty': '该模型暂无有效拟合样本',
|
||||||
|
'chart.fit.loess': 'LOESS 拟合',
|
||||||
|
'chart.fit.olsLinear': 'OLS 线性',
|
||||||
|
'chart.fit.olsReg': 'OLS 回归',
|
||||||
|
'chart.fit.observed': '观测值',
|
||||||
|
'chart.fit.tipFit': '拟合 {val}',
|
||||||
|
'chart.fit.tipObs': '观测 {val}',
|
||||||
|
'chart.fit.zeroSamples': '0 样本',
|
||||||
|
'chart.fit.peerMean': '{label} 均 {val}',
|
||||||
|
'chart.fit.peerCompare': '同图对比:{peers}',
|
||||||
|
'chart.fit.curvesCount': '{count} 条拟合线',
|
||||||
|
'chart.fit.multiBadge': '{steps}步 · {models} 模型对比',
|
||||||
|
'chart.fit.singleBadge': '{steps}步 · 均 {mean}',
|
||||||
|
'chart.fit.olsTitle': 'OLS: y = {slope}x + {intercept} · 样本标准差 SD = ±{sd}',
|
||||||
|
'chart.trend.hmMonthYear': '{yy}年{month}月',
|
||||||
|
'chart.trend.hmMonthOnly': '{month}月',
|
||||||
|
'chart.trend.wdayMon': '一',
|
||||||
|
'chart.trend.wdayWed': '三',
|
||||||
|
'chart.trend.wdayFri': '五',
|
||||||
|
'chart.trend.wdaySun': '日',
|
||||||
|
'chart.trend.hmAria': '每日用量热力格子图',
|
||||||
|
'chart.trend.hmLess': '少',
|
||||||
|
'chart.trend.hmMore': '多',
|
||||||
|
'chart.trend.hmActivePeak': '活跃 {active}/{total} 天 · 峰值 {label} · {tokens}',
|
||||||
|
'chart.trend.hmActiveZero': '活跃 0/{total} 天',
|
||||||
|
'chart.trend.peakPill': '峰值 {label} · {tokens}',
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -89,6 +89,10 @@ export const SVG_ICON_DEFS = Object.freeze({
|
|||||||
close: [
|
close: [
|
||||||
{ tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } },
|
{ tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } },
|
||||||
],
|
],
|
||||||
|
copy: [
|
||||||
|
{ tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } },
|
||||||
|
{ tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } },
|
||||||
|
],
|
||||||
grip: [
|
grip: [
|
||||||
{ tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
{ tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||||
{ tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
{ tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||||
|
|||||||
@@ -16,14 +16,17 @@ async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
|||||||
const appInstance = App();
|
const appInstance = App();
|
||||||
mountTarget.appendChild(appInstance.el);
|
mountTarget.appendChild(appInstance.el);
|
||||||
|
|
||||||
|
const syncDocAppearance = (settings) => {
|
||||||
|
setI18nLanguage(settings?.language);
|
||||||
|
if (typeof document !== 'undefined' && document.documentElement) {
|
||||||
|
applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
syncDocAppearance(telemetryStore.getState().telemetry?.settings);
|
||||||
|
|
||||||
const unsubAppearance = telemetryStore.subscribe(
|
const unsubAppearance = telemetryStore.subscribe(
|
||||||
(st) => st.telemetry?.settings,
|
(st) => st.telemetry?.settings,
|
||||||
(settings) => {
|
syncDocAppearance
|
||||||
setI18nLanguage(settings?.language);
|
|
||||||
if (typeof document !== 'undefined' && document.documentElement) {
|
|
||||||
applyAppearanceToRoot(document.documentElement, settings, { includeFontScale: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const stopPolling = startAsyncTelemetryLoop(2000);
|
const stopPolling = startAsyncTelemetryLoop(2000);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
formatAgentBadgeText,
|
||||||
formatCachePct,
|
formatCachePct,
|
||||||
formatMetric,
|
formatMetric,
|
||||||
formatTokens,
|
formatTokens,
|
||||||
@@ -19,36 +20,15 @@ import {
|
|||||||
speedReasonText,
|
speedReasonText,
|
||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
import { isEnglishLocale, t } from '../i18n/index.js';
|
import { isEnglishLocale, t } from '../i18n/index.js';
|
||||||
|
import { OVERVIEW_METRIC_KEYS, TOPBAR_SLOT_KEYS } from '../../shared/settings-normalization.mjs';
|
||||||
|
import {
|
||||||
|
formatCompactCapsuleCost,
|
||||||
|
formatCompactCapsuleTtft,
|
||||||
|
resolveCapsuleQuotaSlotPct,
|
||||||
|
} from '../../shared/telemetry-display-rules.mjs';
|
||||||
|
|
||||||
export const CAPSULE_METRIC_KEYS = Object.freeze([
|
export { OVERVIEW_METRIC_KEYS, formatCompactCapsuleCost, formatCompactCapsuleTtft };
|
||||||
'context',
|
export const CAPSULE_METRIC_KEYS = TOPBAR_SLOT_KEYS;
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'avg_tps',
|
|
||||||
'cost',
|
|
||||||
'session_cost',
|
|
||||||
'cache_hit',
|
|
||||||
'session_tokens',
|
|
||||||
'quota_auto',
|
|
||||||
'gemini_5h',
|
|
||||||
'gemini_weekly',
|
|
||||||
'claude_5h',
|
|
||||||
'claude_weekly',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const OVERVIEW_METRIC_KEYS = Object.freeze([
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'avg_tps',
|
|
||||||
'step_cost',
|
|
||||||
'session_cost',
|
|
||||||
'cache_hit',
|
|
||||||
'session_tokens',
|
|
||||||
'context_usage',
|
|
||||||
'quota_tightest',
|
|
||||||
]);
|
|
||||||
|
|
||||||
const THIRD_PARTY_FAMILY_RE = /claude|gpt|anthropic|openai|3p|sonnet|opus|haiku/i;
|
|
||||||
|
|
||||||
export function getCapsuleMetricOptions() {
|
export function getCapsuleMetricOptions() {
|
||||||
return CAPSULE_METRIC_KEYS.map((key) => ({
|
return CAPSULE_METRIC_KEYS.map((key) => ({
|
||||||
@@ -137,98 +117,14 @@ export function resolveQuotaCapsuleSummary(quotas) {
|
|||||||
* @returns {{ roundedPct: number, shortText: string } | null}
|
* @returns {{ roundedPct: number, shortText: string } | null}
|
||||||
*/
|
*/
|
||||||
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
|
export function resolveSpecificQuotaSlotSummary(quotas, slotKey) {
|
||||||
if (!quotas) return null;
|
const rounded = resolveCapsuleQuotaSlotPct(quotas, slotKey);
|
||||||
const pools = Array.isArray(quotas.pools) ? quotas.pools : [];
|
if (rounded == null) return null;
|
||||||
const activePool = quotas.activePool || null;
|
|
||||||
const isClaude = slotKey.startsWith('claude_');
|
|
||||||
const isWeekly = slotKey.endsWith('_weekly');
|
|
||||||
let rawPct = null;
|
|
||||||
|
|
||||||
if (isClaude) {
|
|
||||||
const claudePool =
|
|
||||||
pools.find((p) => p?.poolKey === 'Claude & GPT') ||
|
|
||||||
pools.find((p) => THIRD_PARTY_FAMILY_RE.test(String(p?.poolKey || p?.poolLabel || '')));
|
|
||||||
const cand = isWeekly ? claudePool?.weeklyRemainingPct : claudePool?.remainingPct;
|
|
||||||
if (cand != null && Number.isFinite(Number(cand))) {
|
|
||||||
rawPct = Number(cand);
|
|
||||||
} else if (
|
|
||||||
activePool &&
|
|
||||||
THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
|
||||||
) {
|
|
||||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
|
||||||
if (fb != null && Number.isFinite(Number(fb))) {
|
|
||||||
rawPct = Number(fb);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const stdGemini =
|
|
||||||
pools.find((p) => p?.poolKey === 'Gemini') ||
|
|
||||||
pools.find(
|
|
||||||
(p) =>
|
|
||||||
/gemini/i.test(String(p?.poolKey || p?.poolLabel || '')) &&
|
|
||||||
!/carbon|argon/i.test(String(p?.poolKey || ''))
|
|
||||||
);
|
|
||||||
const geminiFamilyPools = pools.filter((p) =>
|
|
||||||
/gemini|carbon|argon/i.test(String(p?.poolKey || p?.poolLabel || ''))
|
|
||||||
);
|
|
||||||
const primaryCand = isWeekly ? stdGemini?.weeklyRemainingPct : stdGemini?.remainingPct;
|
|
||||||
if (primaryCand != null && Number.isFinite(Number(primaryCand))) {
|
|
||||||
rawPct = Number(primaryCand);
|
|
||||||
} else {
|
|
||||||
const familyVals = geminiFamilyPools
|
|
||||||
.map((p) => (isWeekly ? p?.weeklyRemainingPct : p?.remainingPct))
|
|
||||||
.filter((v) => v != null && Number.isFinite(Number(v)))
|
|
||||||
.map(Number);
|
|
||||||
if (familyVals.length > 0) {
|
|
||||||
rawPct = Math.min(...familyVals);
|
|
||||||
} else if (
|
|
||||||
activePool &&
|
|
||||||
!THIRD_PARTY_FAMILY_RE.test(String(activePool.family || activePool.poolLabel || ''))
|
|
||||||
) {
|
|
||||||
const fb = isWeekly ? activePool.weeklyRemainingPct : activePool.remainingPct;
|
|
||||||
if (fb != null && Number.isFinite(Number(fb))) {
|
|
||||||
rawPct = Number(fb);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (
|
|
||||||
rawPct == null &&
|
|
||||||
isWeekly &&
|
|
||||||
quotas.weekly &&
|
|
||||||
!THIRD_PARTY_FAMILY_RE.test(String(quotas.weekly.poolFamily || '')) &&
|
|
||||||
quotas.weekly.remainingPct != null &&
|
|
||||||
Number.isFinite(Number(quotas.weekly.remainingPct))
|
|
||||||
) {
|
|
||||||
rawPct = Number(quotas.weekly.remainingPct);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (rawPct == null || !Number.isFinite(rawPct)) return null;
|
|
||||||
const rounded = Math.max(0, Math.min(100, Math.round(rawPct)));
|
|
||||||
return {
|
return {
|
||||||
roundedPct: rounded,
|
roundedPct: rounded,
|
||||||
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
shortText: t('capsule.quotaLeft', { pct: rounded }),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function formatCompactCapsuleCost(costUsd) {
|
|
||||||
if (costUsd == null || !Number.isFinite(Number(costUsd))) return '--';
|
|
||||||
const val = Math.max(0, Number(costUsd));
|
|
||||||
if (val === 0) return '$0.00';
|
|
||||||
if (val < 0.001) return '<$0.001';
|
|
||||||
if (val < 1) return `$${val.toFixed(3)}`;
|
|
||||||
if (val < 100) return `$${val.toFixed(2)}`;
|
|
||||||
return `$${Math.round(val)}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function formatCompactCapsuleTtft(ttftSec) {
|
|
||||||
if (ttftSec == null || !Number.isFinite(Number(ttftSec)) || Number(ttftSec) < 0) return '--s';
|
|
||||||
const val = Number(ttftSec);
|
|
||||||
if (val < 1) return `${val.toFixed(2)}s`;
|
|
||||||
if (val < 100) return `${val.toFixed(1)}s`;
|
|
||||||
return `${Math.round(val)}s`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析顶栏/输入框精简胶囊单槽位展示结构。
|
* 解析顶栏/输入框精简胶囊单槽位展示结构。
|
||||||
*
|
*
|
||||||
@@ -450,15 +346,16 @@ export function resolveCapsuleMetricPresentation(metricKey, slotCtx, ringCircumf
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function translateRawAgentBadge(rawBadge) {
|
function resolveActiveBadgeText(active) {
|
||||||
if (!rawBadge) return '';
|
if (!active?.activeAgentBadge && !active?.activeAgentKind) return '';
|
||||||
if (!isEnglishLocale()) return String(rawBadge);
|
return formatAgentBadgeText({
|
||||||
const str = String(rawBadge).trim();
|
agentKind:
|
||||||
if (str === '主') return t('fmt.mainBadge');
|
active.activeAgentKind ||
|
||||||
const m = str.match(/^子(\d+)$/);
|
(!active.activeAgentId || active.activeAgentId === 'main' ? 'main' : 'subagent'),
|
||||||
if (m) return t('fmt.subBadge', { index: m[1] });
|
agentOrdinal: Number(active.activeAgentOrdinal || 0),
|
||||||
if (str === '子') return t('fmt.subBadgeShort');
|
isMain: !active.activeAgentId || active.activeAgentId === 'main',
|
||||||
return str;
|
badgeText: active.activeAgentBadge,
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -480,7 +377,7 @@ export function resolveOverviewMetricCell(metricKey, cellCtx = {}) {
|
|||||||
fallback: t('fmt.unknownModel'),
|
fallback: t('fmt.unknownModel'),
|
||||||
}).text;
|
}).text;
|
||||||
const reason = speedReasonText(active.latestSpeedReason);
|
const reason = speedReasonText(active.latestSpeedReason);
|
||||||
const badgeStr = translateRawAgentBadge(active.activeAgentBadge);
|
const badgeStr = resolveActiveBadgeText(active);
|
||||||
const modelAndAgent =
|
const modelAndAgent =
|
||||||
hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay;
|
hasSubagents && badgeStr ? `[${badgeStr}] ${activeModelDisplay}` : activeModelDisplay;
|
||||||
const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0;
|
const hasSpeed = Number.isFinite(active.latestTokPerSec) && Number(active.latestTokPerSec) > 0;
|
||||||
|
|||||||
@@ -20,37 +20,18 @@ import {
|
|||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
import { t } from '../i18n/index.js';
|
import { t } from '../i18n/index.js';
|
||||||
import {
|
import {
|
||||||
DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT,
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
normalizeClientStepTokenComboFormat,
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
parseClientStepTokenComboSegments,
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
} from '../store/telemetryStore.js';
|
normalizeStepTokenComboFormat,
|
||||||
|
parseStepTokenComboSegments,
|
||||||
|
} from '../../shared/settings-normalization.mjs';
|
||||||
|
|
||||||
export const STEP_COLUMN_KEYS = Object.freeze([
|
export const STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS;
|
||||||
'step',
|
export const DEFAULT_STEP_COLUMN_KEYS = DEFAULT_STEP_TABLE_COLUMNS;
|
||||||
'time',
|
const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT;
|
||||||
'model',
|
const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat;
|
||||||
'tps',
|
const parseClientStepTokenComboSegments = parseStepTokenComboSegments;
|
||||||
'ttft',
|
|
||||||
'duration',
|
|
||||||
'tokens_combo',
|
|
||||||
'tokens_io_cache',
|
|
||||||
'tokens_custom',
|
|
||||||
'input_tokens',
|
|
||||||
'cache_tokens',
|
|
||||||
'output_tokens',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_STEP_COLUMN_KEYS = Object.freeze([
|
|
||||||
'step',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'tokens_combo',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
function resolveStepTokenParts(st) {
|
function resolveStepTokenParts(st) {
|
||||||
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
||||||
@@ -224,7 +205,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
|||||||
if (reason && !refs.speedReason) {
|
if (reason && !refs.speedReason) {
|
||||||
refs.speedReason = h('div', {
|
refs.speedReason = h('div', {
|
||||||
className: 'text-muted',
|
className: 'text-muted',
|
||||||
style: 'font-size: var(--fs-2xs);',
|
style: 'font-size: var(--fs-xs);',
|
||||||
});
|
});
|
||||||
refs.wrapEl.appendChild(refs.speedReason);
|
refs.wrapEl.appendChild(refs.speedReason);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,18 +5,14 @@
|
|||||||
* live reordering, and clean instance disposal.
|
* live reordering, and clean instance disposal.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { OVERVIEW_MODULE_KEYS } from '../../shared/settings-normalization.mjs';
|
||||||
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
|
import { ContextWindowWidget } from '../components/widgets/ContextWindowWidget.js';
|
||||||
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
|
import { LiveActivityWidget } from '../components/widgets/LiveActivityWidget.js';
|
||||||
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
|
import { MetricMatrixWidget } from '../components/widgets/MetricMatrixWidget.js';
|
||||||
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
|
import { QuotaPoolsWidget } from '../components/widgets/QuotaPoolsWidget.js';
|
||||||
import { t } from '../i18n/index.js';
|
import { t } from '../i18n/index.js';
|
||||||
|
|
||||||
export const OVERVIEW_WIDGET_KEYS = Object.freeze([
|
export const OVERVIEW_WIDGET_KEYS = OVERVIEW_MODULE_KEYS;
|
||||||
'metrics',
|
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
|
export const OVERVIEW_WIDGET_REGISTRY = Object.freeze({
|
||||||
metrics: {
|
metrics: {
|
||||||
|
|||||||
@@ -5,8 +5,45 @@
|
|||||||
|
|
||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
|
import { callSidecarApi, getWindowBridgeConfig, isWindowOverlayMode } from '../core/httpClient.js';
|
||||||
import { isEnglishLocale, normalizeI18nLanguage, t } from '../i18n/index.js';
|
import {
|
||||||
|
formatAgentBadgeText,
|
||||||
|
formatAgentLabel,
|
||||||
|
formatLiveActivityDetail,
|
||||||
|
formatLiveActivityLabel,
|
||||||
|
getAgentBadgeClass,
|
||||||
|
} from '../core/formatters.js';
|
||||||
|
import { normalizeI18nLanguage, t } from '../i18n/index.js';
|
||||||
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
|
import { normalizeClientFontScale, normalizeClientThemeAccent } from '../core/appearance.js';
|
||||||
|
import {
|
||||||
|
DEFAULT_HOVER_MODULES,
|
||||||
|
DEFAULT_OVERVIEW_METRICS,
|
||||||
|
DEFAULT_OVERVIEW_MODULES,
|
||||||
|
DEFAULT_POPOVER_WIDTH,
|
||||||
|
DEFAULT_STEP_TABLE_COLUMNS,
|
||||||
|
DEFAULT_STEP_TOKEN_COMBO_FORMAT,
|
||||||
|
DEFAULT_TOPBAR_SLOTS,
|
||||||
|
MAX_POPOVER_WIDTH,
|
||||||
|
MIN_POPOVER_WIDTH,
|
||||||
|
OVERVIEW_METRIC_KEYS,
|
||||||
|
OVERVIEW_MODULE_KEYS,
|
||||||
|
STEP_TABLE_COLUMN_KEYS,
|
||||||
|
TOPBAR_SLOT_KEYS,
|
||||||
|
normalizeHoverModules,
|
||||||
|
normalizeModelDisplayMode,
|
||||||
|
normalizeOrchestratorIdMode,
|
||||||
|
normalizeOverviewMetrics,
|
||||||
|
normalizeOverviewModules,
|
||||||
|
normalizePluginUpdateMode,
|
||||||
|
normalizePopoverWidth,
|
||||||
|
normalizePopoverWidthMode,
|
||||||
|
normalizeStepTableColumns,
|
||||||
|
normalizeStepTokenComboFormat,
|
||||||
|
normalizeTopbarCapsuleSlots,
|
||||||
|
normalizeWeeklyLimitMode,
|
||||||
|
normalizeWindowMountMode,
|
||||||
|
parseStepTokenComboSegments,
|
||||||
|
} from '../../shared/settings-normalization.mjs';
|
||||||
|
import { WINDOW_BRIDGE_ROUTE_KEY, readInjectedWindowBridge } from '../../shared/window-bridge-protocol.mjs';
|
||||||
|
|
||||||
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
const CASCADE_UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
@@ -25,7 +62,7 @@ export function extractHostRouteCascadeId() {
|
|||||||
if (m && CASCADE_UUID_RE.test(m[1])) {
|
if (m && CASCADE_UUID_RE.test(m[1])) {
|
||||||
return m[1];
|
return m[1];
|
||||||
}
|
}
|
||||||
const extBridgeRouteId = String(window.__AGUsageMonitorBridge?.hostRouteCascadeId || '').trim();
|
const extBridgeRouteId = String(readInjectedWindowBridge()?.[WINDOW_BRIDGE_ROUTE_KEY] || '').trim();
|
||||||
if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) {
|
if (extBridgeRouteId && CASCADE_UUID_RE.test(extBridgeRouteId)) {
|
||||||
return extBridgeRouteId;
|
return extBridgeRouteId;
|
||||||
}
|
}
|
||||||
@@ -107,310 +144,35 @@ let loopActive = false;
|
|||||||
let loopIntervalMs = 2000;
|
let loopIntervalMs = 2000;
|
||||||
let loopTickFn = null;
|
let loopTickFn = null;
|
||||||
|
|
||||||
export const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([
|
export const CLIENT_TOPBAR_SLOT_KEYS = TOPBAR_SLOT_KEYS;
|
||||||
'context',
|
export const DEFAULT_CLIENT_TOPBAR_SLOTS = DEFAULT_TOPBAR_SLOTS;
|
||||||
'tps',
|
export const CLIENT_OVERVIEW_MODULE_KEYS = OVERVIEW_MODULE_KEYS;
|
||||||
'ttft',
|
export const DEFAULT_CLIENT_OVERVIEW_MODULES = DEFAULT_OVERVIEW_MODULES;
|
||||||
'avg_tps',
|
export const DEFAULT_CLIENT_HOVER_MODULES = DEFAULT_HOVER_MODULES;
|
||||||
'cost',
|
export const CLIENT_OVERVIEW_METRIC_KEYS = OVERVIEW_METRIC_KEYS;
|
||||||
'session_cost',
|
export const DEFAULT_CLIENT_OVERVIEW_METRICS = DEFAULT_OVERVIEW_METRICS;
|
||||||
'cache_hit',
|
export const CLIENT_STEP_COLUMN_KEYS = STEP_TABLE_COLUMN_KEYS;
|
||||||
'session_tokens',
|
export const DEFAULT_CLIENT_STEP_COLUMNS = DEFAULT_STEP_TABLE_COLUMNS;
|
||||||
'quota_auto',
|
export const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT;
|
||||||
'gemini_5h',
|
export const MIN_CLIENT_POPOVER_WIDTH = MIN_POPOVER_WIDTH;
|
||||||
'gemini_weekly',
|
export const MAX_CLIENT_POPOVER_WIDTH = MAX_POPOVER_WIDTH;
|
||||||
'claude_5h',
|
export const DEFAULT_CLIENT_POPOVER_WIDTH = DEFAULT_POPOVER_WIDTH;
|
||||||
'claude_weekly',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['tps', 'ttft', 'context']);
|
export const parseClientStepTokenComboSegments = parseStepTokenComboSegments;
|
||||||
|
export const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat;
|
||||||
|
export const normalizeClientPopoverWidthMode = normalizePopoverWidthMode;
|
||||||
|
export const normalizeClientPopoverWidth = normalizePopoverWidth;
|
||||||
|
export const normalizeClientModelDisplayMode = normalizeModelDisplayMode;
|
||||||
|
export const normalizeClientTopbarSlots = normalizeTopbarCapsuleSlots;
|
||||||
|
export const normalizeClientHoverModules = normalizeHoverModules;
|
||||||
|
export const normalizeClientOverviewModules = normalizeOverviewModules;
|
||||||
|
export const normalizeClientOverviewMetrics = normalizeOverviewMetrics;
|
||||||
|
export const normalizeClientStepColumns = normalizeStepTableColumns;
|
||||||
|
export const normalizeClientUpdateMode = normalizePluginUpdateMode;
|
||||||
|
export const normalizeClientOrchestratorIdMode = normalizeOrchestratorIdMode;
|
||||||
|
export const normalizeClientWindowMountMode = normalizeWindowMountMode;
|
||||||
|
|
||||||
export const CLIENT_OVERVIEW_MODULE_KEYS = Object.freeze([
|
export function isEquivalentTelemetry(prev, next) {
|
||||||
'metrics',
|
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_OVERVIEW_MODULES = Object.freeze([
|
|
||||||
'metrics',
|
|
||||||
'context',
|
|
||||||
'quotas',
|
|
||||||
'live_tasks',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_HOVER_MODULES = Object.freeze(['metrics', 'context', 'quotas']);
|
|
||||||
|
|
||||||
export const CLIENT_OVERVIEW_METRIC_KEYS = Object.freeze([
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'avg_tps',
|
|
||||||
'step_cost',
|
|
||||||
'session_cost',
|
|
||||||
'cache_hit',
|
|
||||||
'session_tokens',
|
|
||||||
'context_usage',
|
|
||||||
'quota_tightest',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_OVERVIEW_METRICS = Object.freeze([
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'avg_tps',
|
|
||||||
'step_cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const CLIENT_STEP_COLUMN_KEYS = Object.freeze([
|
|
||||||
'step',
|
|
||||||
'time',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'duration',
|
|
||||||
'tokens_combo',
|
|
||||||
'tokens_io_cache',
|
|
||||||
'tokens_custom',
|
|
||||||
'input_tokens',
|
|
||||||
'cache_tokens',
|
|
||||||
'output_tokens',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_STEP_COLUMNS = Object.freeze([
|
|
||||||
'step',
|
|
||||||
'model',
|
|
||||||
'tps',
|
|
||||||
'ttft',
|
|
||||||
'tokens_combo',
|
|
||||||
'cache',
|
|
||||||
'cost',
|
|
||||||
]);
|
|
||||||
|
|
||||||
export const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = 'context:in:cache';
|
|
||||||
|
|
||||||
const CLIENT_STEP_TOKEN_ALIASES = Object.freeze({
|
|
||||||
context: 'context',
|
|
||||||
ctx: 'context',
|
|
||||||
'上下文': 'context',
|
|
||||||
in: 'in',
|
|
||||||
new: 'in',
|
|
||||||
input: 'in',
|
|
||||||
'输入': 'in',
|
|
||||||
'新输入': 'in',
|
|
||||||
out: 'out',
|
|
||||||
output: 'out',
|
|
||||||
'输出': 'out',
|
|
||||||
'总输出': 'out',
|
|
||||||
cache: 'cache',
|
|
||||||
cached: 'cache',
|
|
||||||
cache_read: 'cache',
|
|
||||||
cacheread: 'cache',
|
|
||||||
'缓存': 'cache',
|
|
||||||
'缓存读': 'cache',
|
|
||||||
think: 'think',
|
|
||||||
thinking: 'think',
|
|
||||||
'思考': 'think',
|
|
||||||
reply: 'reply',
|
|
||||||
body: 'reply',
|
|
||||||
resp: 'reply',
|
|
||||||
response: 'reply',
|
|
||||||
text: 'reply',
|
|
||||||
'正文': 'reply',
|
|
||||||
'回复': 'reply',
|
|
||||||
total: 'total',
|
|
||||||
all: 'total',
|
|
||||||
sum: 'total',
|
|
||||||
'总计': 'total',
|
|
||||||
'总token': 'total',
|
|
||||||
});
|
|
||||||
|
|
||||||
export function parseClientStepTokenComboSegments(raw) {
|
|
||||||
const str = String(raw ?? '').trim();
|
|
||||||
const out = [];
|
|
||||||
const seen = new Set();
|
|
||||||
if (str) {
|
|
||||||
for (const part of str.split(/[:/,|]+/)) {
|
|
||||||
const key = part.trim().toLowerCase();
|
|
||||||
if (!key) continue;
|
|
||||||
const mapped = Object.prototype.hasOwnProperty.call(CLIENT_STEP_TOKEN_ALIASES, key)
|
|
||||||
? CLIENT_STEP_TOKEN_ALIASES[key]
|
|
||||||
: null;
|
|
||||||
if (!mapped || seen.has(mapped)) continue;
|
|
||||||
seen.add(mapped);
|
|
||||||
out.push(mapped);
|
|
||||||
if (out.length >= 4) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out.length > 0 ? out : ['context', 'in', 'cache'];
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientStepTokenComboFormat(raw) {
|
|
||||||
return parseClientStepTokenComboSegments(raw).join(':');
|
|
||||||
}
|
|
||||||
|
|
||||||
export const MIN_CLIENT_POPOVER_WIDTH = 440;
|
|
||||||
export const MAX_CLIENT_POPOVER_WIDTH = 1080;
|
|
||||||
export const DEFAULT_CLIENT_POPOVER_WIDTH = 580;
|
|
||||||
|
|
||||||
export function normalizeClientPopoverWidthMode(mode) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientPopoverWidth(width) {
|
|
||||||
const num = Number(width);
|
|
||||||
if (!Number.isFinite(num) || num <= 0) return DEFAULT_CLIENT_POPOVER_WIDTH;
|
|
||||||
return Math.max(MIN_CLIENT_POPOVER_WIDTH, Math.min(MAX_CLIENT_POPOVER_WIDTH, Math.round(num)));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientModelDisplayMode(mode, legacyShowUpstream) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
|
||||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
|
||||||
return 'upstream_compact';
|
|
||||||
}
|
|
||||||
if (m === 'short') return 'short';
|
|
||||||
if (legacyShowUpstream === true) return 'upstream';
|
|
||||||
return 'short';
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeClientOrderedList(raw, { allowedKeys, defaultItems, minLen, maxLen }) {
|
|
||||||
if (!Array.isArray(raw)) {
|
|
||||||
return [...defaultItems];
|
|
||||||
}
|
|
||||||
const allowedSet = new Set(allowedKeys);
|
|
||||||
const seen = new Set();
|
|
||||||
const out = [];
|
|
||||||
for (const item of raw) {
|
|
||||||
const key = String(item ?? '').trim();
|
|
||||||
if (!key || key === 'none' || !allowedSet.has(key) || seen.has(key)) continue;
|
|
||||||
seen.add(key);
|
|
||||||
out.push(key);
|
|
||||||
if (out.length >= maxLen) break;
|
|
||||||
}
|
|
||||||
if (out.length < minLen) {
|
|
||||||
for (const fallbackKey of [...defaultItems, ...allowedKeys]) {
|
|
||||||
if (!seen.has(fallbackKey) && allowedSet.has(fallbackKey)) {
|
|
||||||
seen.add(fallbackKey);
|
|
||||||
out.push(fallbackKey);
|
|
||||||
if (out.length >= minLen) break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化前端顶栏胶囊动态槽位配置数组(支持 1..5 项不重复指标,兼容迁移旧版 `'none'` 占位)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientTopbarSlots(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_TOPBAR_SLOT_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_TOPBAR_SLOTS,
|
|
||||||
minLen: 1,
|
|
||||||
maxLen: 5,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化鼠标悬浮速览窗展示模块列表(支持 0..4 项,`0` 项代表关闭悬浮窗)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientHoverModules(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_HOVER_MODULES,
|
|
||||||
minLen: 0,
|
|
||||||
maxLen: 4,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化实时监控视图展示模块列表(支持 1..4 项)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientOverviewModules(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_OVERVIEW_MODULE_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_OVERVIEW_MODULES,
|
|
||||||
minLen: 1,
|
|
||||||
maxLen: 4,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化实时监控第一行指标矩阵配置(支持 1..4 项)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientOverviewMetrics(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_OVERVIEW_METRIC_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_OVERVIEW_METRICS,
|
|
||||||
minLen: 1,
|
|
||||||
maxLen: 4,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化调用明细「按步查看」显示列配置(支持 2..12 列)。
|
|
||||||
*
|
|
||||||
* @param {unknown} raw
|
|
||||||
* @returns {string[]}
|
|
||||||
*/
|
|
||||||
export function normalizeClientStepColumns(raw) {
|
|
||||||
return normalizeClientOrderedList(raw, {
|
|
||||||
allowedKeys: CLIENT_STEP_COLUMN_KEYS,
|
|
||||||
defaultItems: DEFAULT_CLIENT_STEP_COLUMNS,
|
|
||||||
minLen: 2,
|
|
||||||
maxLen: CLIENT_STEP_COLUMN_KEYS.length,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化前端插件更新策略(`'off'` | `'manual'` | `'auto'`),兼容旧版布尔字段。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyAutoUpdate]
|
|
||||||
* @returns {'off'|'manual'|'auto'}
|
|
||||||
*/
|
|
||||||
export function normalizeClientUpdateMode(mode, legacyAutoUpdate) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'off' || m === 'manual' || m === 'auto') return m;
|
|
||||||
if (legacyAutoUpdate === true) return 'auto';
|
|
||||||
return 'manual';
|
|
||||||
}
|
|
||||||
|
|
||||||
export function normalizeClientOrchestratorIdMode(mode) {
|
|
||||||
return String(mode ?? '').trim().toLowerCase() === 'full' ? 'full' : 'compact';
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 归一化前端面板挂载方式(`'dual'` | `'composer'` | `'sidebar'`),兼容旧版 `enableWindowOverlay` 布尔字段。
|
|
||||||
*
|
|
||||||
* @param {unknown} mode
|
|
||||||
* @param {unknown} [legacyEnableOverlay]
|
|
||||||
* @returns {'dual'|'composer'|'sidebar'}
|
|
||||||
*/
|
|
||||||
export function normalizeClientWindowMountMode(mode, legacyEnableOverlay) {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'composer' || m === 'input') return 'composer';
|
|
||||||
if (m === 'sidebar' || m === 'off') return 'sidebar';
|
|
||||||
if (m === 'dual' || m === 'topbar') return 'dual';
|
|
||||||
if (legacyEnableOverlay === false) return 'sidebar';
|
|
||||||
return 'dual';
|
|
||||||
}
|
|
||||||
|
|
||||||
function isEquivalentTelemetry(prev, next) {
|
|
||||||
if (!prev || !next) return false;
|
if (!prev || !next) return false;
|
||||||
if (prev === next) return true;
|
if (prev === next) return true;
|
||||||
|
|
||||||
@@ -423,15 +185,6 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
const normMount = (mode, legacyEnableOverlay) => {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'composer' || m === 'input') return 'composer';
|
|
||||||
if (m === 'sidebar' || m === 'off') return 'sidebar';
|
|
||||||
if (m === 'dual' || m === 'topbar') return 'dual';
|
|
||||||
if (legacyEnableOverlay === false) return 'sidebar';
|
|
||||||
return 'dual';
|
|
||||||
};
|
|
||||||
|
|
||||||
// 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置)
|
// 1. 比对系统设置项(外观语言/主题/字号、模型显示策略、更新策略、挂载与结构布局配置)
|
||||||
const pAct = prev.activeConversation;
|
const pAct = prev.activeConversation;
|
||||||
const nAct = next.activeConversation;
|
const nAct = next.activeConversation;
|
||||||
@@ -441,6 +194,7 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false;
|
if ((pSet?.language ?? 'zh-CN') !== (nSet?.language ?? 'zh-CN')) return false;
|
||||||
if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false;
|
if ((pSet?.themeAccent ?? 'host') !== (nSet?.themeAccent ?? 'host')) return false;
|
||||||
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
if ((pSet?.fontScale ?? 'md') !== (nSet?.fontScale ?? 'md')) return false;
|
||||||
|
if ((prev.hostPlatform || '') !== (next.hostPlatform || '')) return false;
|
||||||
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
if (Boolean(pSet?.contextWindowRiskAccepted) !== Boolean(nSet?.contextWindowRiskAccepted)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -450,51 +204,29 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const normModelMode = (mode, legacyShowUpstream) => {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
if (m === 'upstream' || m === 'raw' || m === 'full') return 'upstream';
|
|
||||||
if (m === 'upstream_compact' || m === 'compact_upstream' || m === 'trimmed') {
|
|
||||||
return 'upstream_compact';
|
|
||||||
}
|
|
||||||
if (m === 'short') return 'short';
|
|
||||||
return legacyShowUpstream === true ? 'upstream' : 'short';
|
|
||||||
};
|
|
||||||
const normPopMode = (mode) => {
|
|
||||||
const m = String(mode ?? '').trim().toLowerCase();
|
|
||||||
return m === 'custom' || m === 'fixed' ? 'custom' : 'auto';
|
|
||||||
};
|
|
||||||
const normPopW = (w) => {
|
|
||||||
const n = Number(w);
|
|
||||||
return Number.isFinite(n) && n > 0 ? Math.max(440, Math.min(1080, Math.round(n))) : 580;
|
|
||||||
};
|
|
||||||
if (
|
if (
|
||||||
normModelMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !==
|
normalizeModelDisplayMode(pSet?.modelDisplayMode, pSet?.showUpstreamModel) !==
|
||||||
normModelMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel)
|
normalizeModelDisplayMode(nSet?.modelDisplayMode, nSet?.showUpstreamModel)
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false;
|
if (pSet?.showUpstreamModel !== nSet?.showUpstreamModel) return false;
|
||||||
if (normPopMode(pSet?.popoverWidthMode) !== normPopMode(nSet?.popoverWidthMode)) {
|
if (normalizePopoverWidthMode(pSet?.popoverWidthMode) !== normalizePopoverWidthMode(nSet?.popoverWidthMode)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (normPopW(pSet?.popoverWidth) !== normPopW(nSet?.popoverWidth)) {
|
if (normalizePopoverWidth(pSet?.popoverWidth) !== normalizePopoverWidth(nSet?.popoverWidth)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (
|
if (
|
||||||
String(pSet?.stepTokenComboFormat ?? 'context:in:cache').trim() !==
|
String(pSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim() !==
|
||||||
String(nSet?.stepTokenComboFormat ?? 'context:in:cache').trim()
|
String(nSet?.stepTokenComboFormat ?? DEFAULT_STEP_TOKEN_COMBO_FORMAT).trim()
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
const prevOrchIdMode =
|
if (
|
||||||
String(pSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
normalizeOrchestratorIdMode(pSet?.orchestratorIdMode) !==
|
||||||
? 'full'
|
normalizeOrchestratorIdMode(nSet?.orchestratorIdMode)
|
||||||
: 'compact';
|
) {
|
||||||
const nextOrchIdMode =
|
|
||||||
String(nSet?.orchestratorIdMode ?? 'compact').trim().toLowerCase() === 'full'
|
|
||||||
? 'full'
|
|
||||||
: 'compact';
|
|
||||||
if (prevOrchIdMode !== nextOrchIdMode) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false;
|
if (pSet?.weeklyLimitMode !== nSet?.weeklyLimitMode) return false;
|
||||||
@@ -503,8 +235,8 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false;
|
if ((pSet?.pluginUpdateMode ?? '') !== (nSet?.pluginUpdateMode ?? '')) return false;
|
||||||
if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false;
|
if (pSet?.autoUpdatePlugin !== nSet?.autoUpdatePlugin) return false;
|
||||||
if (
|
if (
|
||||||
normMount(pSet?.windowMountMode, pSet?.enableWindowOverlay) !==
|
normalizeClientWindowMountMode(pSet?.windowMountMode, pSet?.enableWindowOverlay) !==
|
||||||
normMount(nSet?.windowMountMode, nSet?.enableWindowOverlay)
|
normalizeClientWindowMountMode(nSet?.windowMountMode, nSet?.enableWindowOverlay)
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -530,7 +262,19 @@ function isEquivalentTelemetry(prev, next) {
|
|||||||
if (!sameArr(pSet?.overviewMetrics, nSet?.overviewMetrics)) return false;
|
if (!sameArr(pSet?.overviewMetrics, nSet?.overviewMetrics)) return false;
|
||||||
if (!sameArr(pSet?.stepTableColumns, nSet?.stepTableColumns)) return false;
|
if (!sameArr(pSet?.stepTableColumns, nSet?.stepTableColumns)) return false;
|
||||||
|
|
||||||
// 2. 比对云端状态
|
// 2. 比对云端状态与桥接健康度
|
||||||
|
const pWb = prev.windowBridge;
|
||||||
|
const nWb = next.windowBridge;
|
||||||
|
if (
|
||||||
|
(pWb?.state || '') !== (nWb?.state || '') ||
|
||||||
|
Boolean(pWb?.argvUpdatedThisBoot) !== Boolean(nWb?.argvUpdatedThisBoot) ||
|
||||||
|
Boolean(pWb?.argvConfigured) !== Boolean(nWb?.argvConfigured) ||
|
||||||
|
Boolean(pWb?.launcherConfigured) !== Boolean(nWb?.launcherConfigured) ||
|
||||||
|
Boolean(pWb?.canRelaunch) !== Boolean(nWb?.canRelaunch) ||
|
||||||
|
Number(pWb?.aliveCount || 0) !== Number(nWb?.aliveCount || 0)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
const pCloud = prev.cloudStatus;
|
const pCloud = prev.cloudStatus;
|
||||||
const nCloud = next.cloudStatus;
|
const nCloud = next.cloudStatus;
|
||||||
if (
|
if (
|
||||||
@@ -1072,12 +816,6 @@ async function requestTelemetry(params, force) {
|
|||||||
consecutivePollFailures = 0;
|
consecutivePollFailures = 0;
|
||||||
|
|
||||||
const latestSt = telemetryStore.getState();
|
const latestSt = telemetryStore.getState();
|
||||||
const previousAccount = latestSt.telemetry?.account;
|
|
||||||
const nextAccount = payload?.account;
|
|
||||||
const accountChanged = previousAccount?.status === 'signedIn' &&
|
|
||||||
(nextAccount?.status === 'signedOut' || (nextAccount?.status === 'signedIn' &&
|
|
||||||
(previousAccount.email || previousAccount.name) !== (nextAccount.email || nextAccount.name)));
|
|
||||||
const accountPatch = accountChanged ? { selectedConversationId: '' } : {};
|
|
||||||
if (force) {
|
if (force) {
|
||||||
const elapsed = Date.now() - startMs;
|
const elapsed = Date.now() - startMs;
|
||||||
if (elapsed < 220) {
|
if (elapsed < 220) {
|
||||||
@@ -1088,7 +826,6 @@ async function requestTelemetry(params, force) {
|
|||||||
}
|
}
|
||||||
if (feedbackTimer) clearTimeout(feedbackTimer);
|
if (feedbackTimer) clearTimeout(feedbackTimer);
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
...accountPatch,
|
|
||||||
telemetry: payload,
|
telemetry: payload,
|
||||||
minuteTick: Math.floor(Date.now() / 30000),
|
minuteTick: Math.floor(Date.now() / 30000),
|
||||||
syncState: 'synced',
|
syncState: 'synced',
|
||||||
@@ -1101,7 +838,6 @@ async function requestTelemetry(params, force) {
|
|||||||
const isSame = isEquivalentTelemetry(latestSt.telemetry, payload);
|
const isSame = isEquivalentTelemetry(latestSt.telemetry, payload);
|
||||||
const nextTelemetry = isSame ? latestSt.telemetry : payload;
|
const nextTelemetry = isSame ? latestSt.telemetry : payload;
|
||||||
telemetryStore.setState({
|
telemetryStore.setState({
|
||||||
...accountPatch,
|
|
||||||
telemetry: nextTelemetry,
|
telemetry: nextTelemetry,
|
||||||
minuteTick: Math.floor(Date.now() / 30000),
|
minuteTick: Math.floor(Date.now() / 30000),
|
||||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||||
@@ -1137,9 +873,7 @@ export async function saveSettingsPatch(patch) {
|
|||||||
safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale);
|
safePatch.fontScale = normalizeClientFontScale(safePatch.fontScale);
|
||||||
}
|
}
|
||||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||||
const mode = safePatch.weeklyLimitMode;
|
safePatch.weeklyLimitMode = normalizeWeeklyLimitMode(safePatch.weeklyLimitMode);
|
||||||
safePatch.weeklyLimitMode =
|
|
||||||
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
|
|
||||||
}
|
}
|
||||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) {
|
if (Object.prototype.hasOwnProperty.call(safePatch, 'enableCliStatusLine')) {
|
||||||
safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine);
|
safePatch.enableCliStatusLine = Boolean(safePatch.enableCliStatusLine);
|
||||||
@@ -1279,6 +1013,18 @@ export async function triggerCloudSync() {
|
|||||||
return res;
|
return res;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function triggerBridgeHostRelaunch() {
|
||||||
|
try {
|
||||||
|
return await callSidecarApi('/api/bridge/relaunch', { method: 'POST', body: {} });
|
||||||
|
} catch {
|
||||||
|
// 兼容热更新后常驻父进程 main.mjs 尚未重注册新路由的场景,平滑回退至既有 POST /api/settings 通道转发至最新 Worker
|
||||||
|
return callSidecarApi('/api/settings', {
|
||||||
|
method: 'POST',
|
||||||
|
body: { __bridgeAction: 'relaunch' },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export async function triggerPluginUpdate() {
|
export async function triggerPluginUpdate() {
|
||||||
const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} });
|
const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} });
|
||||||
if (res?.ok && res?.restarting) {
|
if (res?.ok && res?.restarting) {
|
||||||
@@ -1338,54 +1084,13 @@ export function stopAsyncTelemetryLoop() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
export {
|
||||||
* 根据代理索引返回对应的微边框语义徽章样式类名。
|
formatAgentBadgeText,
|
||||||
*
|
formatAgentLabel,
|
||||||
* @param {number} [index=0]
|
formatLiveActivityDetail,
|
||||||
* @param {boolean} [isMain=false]
|
formatLiveActivityLabel,
|
||||||
* @returns {string}
|
getAgentBadgeClass,
|
||||||
*/
|
};
|
||||||
export function getAgentBadgeClass(index = 0, isMain = false) {
|
|
||||||
if (isMain || index <= 0) return 'badge-main';
|
|
||||||
const slot = ((index - 1) % 3) + 1;
|
|
||||||
return `badge-sub-${slot}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 格式化主/子代理的紧凑短徽章文本(中文如 `主` / `子1`,英文如 `Main` / `S1`)。
|
|
||||||
*
|
|
||||||
* @param {object|null|undefined} agent
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
export function formatAgentBadgeText(agent) {
|
|
||||||
if (!isEnglishLocale()) {
|
|
||||||
if (!agent || agent.isMain) return agent?.badgeText || '主';
|
|
||||||
return agent.badgeText || `子${agent.index || ''}`;
|
|
||||||
}
|
|
||||||
if (!agent || agent.isMain) return t('fmt.mainBadge');
|
|
||||||
return agent.index ? t('fmt.subBadge', { index: agent.index }) : t('fmt.subBadgeShort');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。
|
|
||||||
*
|
|
||||||
* @param {object|null|undefined} agent
|
|
||||||
* @returns {string}
|
|
||||||
*/
|
|
||||||
export function formatAgentLabel(agent) {
|
|
||||||
if (!isEnglishLocale()) {
|
|
||||||
if (!agent) return '主代理';
|
|
||||||
if (agent.isMain) return agent.shortLabel || '主代理';
|
|
||||||
const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : '';
|
|
||||||
return `${agent.shortLabel || '子代理'}${rolePart}`;
|
|
||||||
}
|
|
||||||
if (!agent || agent.isMain) return t('fmt.mainAgent');
|
|
||||||
const idx = Number(agent.index || 0);
|
|
||||||
const baseLabel = idx > 0 ? `${t('fmt.subAgent')} #${idx}` : t('fmt.subAgent');
|
|
||||||
const rolePart =
|
|
||||||
agent.role && agent.role !== '子代理' && agent.role !== 'Subagent' ? ` · ${agent.role}` : '';
|
|
||||||
return `${baseLabel}${rolePart}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。
|
* 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。
|
||||||
@@ -1396,46 +1101,73 @@ export function formatAgentLabel(agent) {
|
|||||||
* @param {string} [ctxInspectorAgentId='auto']
|
* @param {string} [ctxInspectorAgentId='auto']
|
||||||
* @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表
|
* @param {boolean} [includeSteps=false] 是否组装调用明细所需的步骤列表
|
||||||
*/
|
*/
|
||||||
|
const scopedStepProjectionMemo = new WeakMap();
|
||||||
|
|
||||||
export function resolveScopedConversation(
|
export function resolveScopedConversation(
|
||||||
telemetry,
|
telemetry,
|
||||||
selectedAgentScope = 'all',
|
selectedAgentScope = 'all',
|
||||||
ctxInspectorAgentId = 'auto',
|
ctxInspectorAgentId = 'auto',
|
||||||
includeSteps = false
|
includeSteps = false
|
||||||
) {
|
) {
|
||||||
const active = telemetry?.activeConversation || {};
|
const rawActive = telemetry?.activeConversation;
|
||||||
|
const active = rawActive || {};
|
||||||
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
|
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
|
||||||
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
|
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
|
||||||
const subagents = agents.filter((a) => !a.isMain);
|
const subagents = agents.filter((a) => !a.isMain);
|
||||||
const mainAgent = agents.find((a) => a.isMain) || active;
|
let mainAgent = agents.find((a) => a.isMain) || active;
|
||||||
if (includeSteps && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) {
|
let aggregated = active.aggregated || active;
|
||||||
mainAgent.recentSteps = active.recentSteps;
|
let resolvedAgents = agents;
|
||||||
}
|
|
||||||
const aggregated = active.aggregated || active;
|
if (includeSteps) {
|
||||||
if (includeSteps && hasSubagents && !Array.isArray(aggregated.recentSteps)) {
|
let cached = rawActive && typeof rawActive === 'object' ? scopedStepProjectionMemo.get(rawActive) : null;
|
||||||
const combined = [];
|
if (!cached) {
|
||||||
for (const ag of agents) {
|
let nextMain = mainAgent;
|
||||||
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
|
let nextAgents = agents;
|
||||||
for (const step of steps) combined.push(step);
|
if (!Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) {
|
||||||
|
nextMain = { ...mainAgent, recentSteps: active.recentSteps };
|
||||||
|
if (agents.includes(mainAgent)) {
|
||||||
|
nextAgents = agents.map((ag) => (ag === mainAgent ? nextMain : ag));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let nextAgg = aggregated;
|
||||||
|
if (hasSubagents && !Array.isArray(aggregated.recentSteps)) {
|
||||||
|
const combined = [];
|
||||||
|
for (const ag of nextAgents) {
|
||||||
|
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
|
||||||
|
for (const step of steps) combined.push(step);
|
||||||
|
}
|
||||||
|
combined.sort(
|
||||||
|
(a, b) =>
|
||||||
|
(b.createdAtMs || 0) - (a.createdAtMs || 0) ||
|
||||||
|
(b.agentIndex || 0) - (a.agentIndex || 0) ||
|
||||||
|
(b.stepIndex || 0) - (a.stepIndex || 0)
|
||||||
|
);
|
||||||
|
nextAgg = { ...aggregated, recentSteps: combined };
|
||||||
|
}
|
||||||
|
cached = { mainAgent: nextMain, aggregated: nextAgg, agents: nextAgents };
|
||||||
|
if (rawActive && typeof rawActive === 'object') {
|
||||||
|
scopedStepProjectionMemo.set(rawActive, cached);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
combined.sort(
|
mainAgent = cached.mainAgent;
|
||||||
(a, b) =>
|
aggregated = cached.aggregated;
|
||||||
(b.createdAtMs || 0) - (a.createdAtMs || 0) ||
|
resolvedAgents = cached.agents;
|
||||||
(b.agentIndex || 0) - (a.agentIndex || 0) ||
|
|
||||||
(b.stepIndex || 0) - (a.stepIndex || 0)
|
|
||||||
);
|
|
||||||
aggregated.recentSteps = combined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!hasSubagents) {
|
if (!hasSubagents) {
|
||||||
|
const singleScoped =
|
||||||
|
includeSteps && !Array.isArray(active.recentSteps) && Array.isArray(mainAgent.recentSteps)
|
||||||
|
? { ...active, recentSteps: mainAgent.recentSteps }
|
||||||
|
: active;
|
||||||
return {
|
return {
|
||||||
hasSubagents: false,
|
hasSubagents: false,
|
||||||
effectiveScope: 'main',
|
effectiveScope: 'main',
|
||||||
effectiveCtxScope: 'main',
|
effectiveCtxScope: 'main',
|
||||||
agents,
|
agents: resolvedAgents,
|
||||||
subagents: [],
|
subagents: [],
|
||||||
mainAgent,
|
mainAgent,
|
||||||
aggregated,
|
aggregated,
|
||||||
scopedConv: active,
|
scopedConv: singleScoped,
|
||||||
ctxAgent: mainAgent,
|
ctxAgent: mainAgent,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1451,13 +1183,13 @@ export function resolveScopedConversation(
|
|||||||
const scopedConv =
|
const scopedConv =
|
||||||
effectiveScope === 'all'
|
effectiveScope === 'all'
|
||||||
? aggregated
|
? aggregated
|
||||||
: agents.find((a) => a.agentId === effectiveScope) || mainAgent;
|
: resolvedAgents.find((a) => a.agentId === effectiveScope) || mainAgent;
|
||||||
|
|
||||||
let ctxAgent = scopedConv;
|
let ctxAgent = scopedConv;
|
||||||
let effectiveCtxScope = effectiveScope;
|
let effectiveCtxScope = effectiveScope;
|
||||||
if (effectiveScope === 'all') {
|
if (effectiveScope === 'all') {
|
||||||
if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') {
|
if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') {
|
||||||
const matched = agents.find((a) => a.agentId === ctxInspectorAgentId);
|
const matched = resolvedAgents.find((a) => a.agentId === ctxInspectorAgentId);
|
||||||
if (matched) {
|
if (matched) {
|
||||||
ctxAgent = matched;
|
ctxAgent = matched;
|
||||||
effectiveCtxScope = matched.agentId;
|
effectiveCtxScope = matched.agentId;
|
||||||
@@ -1469,8 +1201,8 @@ export function resolveScopedConversation(
|
|||||||
}
|
}
|
||||||
if (effectiveCtxScope === 'auto') {
|
if (effectiveCtxScope === 'auto') {
|
||||||
ctxAgent =
|
ctxAgent =
|
||||||
agents.find((a) => a.agentId === aggregated.activeAgentId) ||
|
resolvedAgents.find((a) => !a.isSideQuestion && a.agentId === aggregated.activeAgentId) ||
|
||||||
agents.find((a) => a.isRunning) ||
|
resolvedAgents.find((a) => !a.isSideQuestion && a.isRunning) ||
|
||||||
mainAgent;
|
mainAgent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1479,7 +1211,7 @@ export function resolveScopedConversation(
|
|||||||
hasSubagents: true,
|
hasSubagents: true,
|
||||||
effectiveScope,
|
effectiveScope,
|
||||||
effectiveCtxScope,
|
effectiveCtxScope,
|
||||||
agents,
|
agents: resolvedAgents,
|
||||||
subagents,
|
subagents,
|
||||||
mainAgent,
|
mainAgent,
|
||||||
aggregated,
|
aggregated,
|
||||||
@@ -1487,3 +1219,21 @@ export function resolveScopedConversation(
|
|||||||
ctxAgent,
|
ctxAgent,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断宿主系统是否为 macOS (`darwin`):优先读取后端遥测或双栖桥接注入的 `platform`,首帧缺省时回退 UA/平台标识。
|
||||||
|
*
|
||||||
|
* @param {Record<string, any>|null|undefined} telemetry
|
||||||
|
* @returns {boolean}
|
||||||
|
*/
|
||||||
|
export function isMacHostPlatform(telemetry) {
|
||||||
|
const p = String(telemetry?.hostPlatform || readInjectedWindowBridge()?.platform || '')
|
||||||
|
.trim()
|
||||||
|
.toLowerCase();
|
||||||
|
if (p) return p === 'darwin';
|
||||||
|
if (typeof navigator !== 'undefined') {
|
||||||
|
const ua = String(navigator.platform || navigator.userAgent || '');
|
||||||
|
return /\b(?:mac|darwin)\b|macintosh|mac\s*os/i.test(ua);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,13 +5,6 @@
|
|||||||
import { createReactiveStore } from '../core/reactive.js';
|
import { createReactiveStore } from '../core/reactive.js';
|
||||||
import { t } from '../i18n/index.js';
|
import { t } from '../i18n/index.js';
|
||||||
|
|
||||||
export const VIEW_TABS = Object.freeze([
|
|
||||||
{ value: 'overview', label: '实时监控', icon: 'pulse' },
|
|
||||||
{ value: 'consumption', label: '用量统计', icon: 'chart-bar' },
|
|
||||||
{ value: 'steps', label: '调用明细', icon: 'table' },
|
|
||||||
{ value: 'settings', label: '偏好设置', icon: 'sliders' },
|
|
||||||
]);
|
|
||||||
|
|
||||||
export function getViewTabs() {
|
export function getViewTabs() {
|
||||||
return [
|
return [
|
||||||
{ value: 'overview', label: t('nav.overview'), icon: 'pulse' },
|
{ value: 'overview', label: t('nav.overview'), icon: 'pulse' },
|
||||||
|
|||||||
@@ -29,15 +29,21 @@ body {
|
|||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
background: var(--surface-bg);
|
background: var(--surface-bg);
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
font-family: var(--font-sans);
|
||||||
font-size: var(--fs-body);
|
font-size: var(--fs-body);
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
}
|
}
|
||||||
|
|
||||||
button,
|
button,
|
||||||
input {
|
input,
|
||||||
|
select,
|
||||||
|
textarea,
|
||||||
|
table,
|
||||||
|
th,
|
||||||
|
td {
|
||||||
font-family: inherit;
|
font-family: inherit;
|
||||||
font-size: inherit;
|
font-size: inherit;
|
||||||
font-stretch: inherit;
|
font-stretch: inherit;
|
||||||
|
|||||||
@@ -117,13 +117,15 @@
|
|||||||
/* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */
|
/* --- 2. 顶部药丸导航栏 (Top Long-Pill Navigation Bar) --- */
|
||||||
.long-pill-nav {
|
.long-pill-nav {
|
||||||
position: relative;
|
position: relative;
|
||||||
|
container-type: inline-size;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(var(--pill-count, 4), 1fr);
|
grid-template-columns: repeat(var(--pill-count, 4), minmax(0, 1fr));
|
||||||
align-items: center;
|
align-items: center;
|
||||||
padding: 3px;
|
padding: 3px;
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
border-radius: var(--radius-pill);
|
border-radius: var(--radius-pill);
|
||||||
|
overflow: hidden;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -149,15 +151,17 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
height: 26px;
|
min-width: 0;
|
||||||
padding: 0 var(--space-2);
|
min-height: calc(26px * var(--ui-font-scale, 1));
|
||||||
|
padding: 2px var(--space-2);
|
||||||
border: none;
|
border: none;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
font-size: var(--fs-base);
|
font-size: var(--fs-base);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
line-height: 1;
|
line-height: 1.15;
|
||||||
border-radius: var(--radius-pill);
|
border-radius: var(--radius-pill);
|
||||||
|
overflow: hidden;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
transition: color var(--dur-instant) var(--ease-fast);
|
transition: color var(--dur-instant) var(--ease-fast);
|
||||||
@@ -171,20 +175,60 @@
|
|||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.pill-tab-label,
|
.pill-tab-label {
|
||||||
.pill-tab-badge {
|
display: block;
|
||||||
display: inline-flex;
|
min-width: 0;
|
||||||
align-items: center;
|
overflow: hidden;
|
||||||
height: 14px;
|
text-overflow: ellipsis;
|
||||||
line-height: 1;
|
white-space: nowrap;
|
||||||
|
line-height: 1.2;
|
||||||
}
|
}
|
||||||
|
|
||||||
.pill-tab-badge {
|
.pill-tab-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-height: 14px;
|
||||||
|
line-height: 1.15;
|
||||||
margin-left: -2px;
|
margin-left: -2px;
|
||||||
font-size: var(--fs-base-sm);
|
font-size: var(--fs-base-sm);
|
||||||
opacity: 0.85;
|
opacity: 0.85;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@container (max-width: 30em) {
|
||||||
|
.pill-tab {
|
||||||
|
gap: 3.5px;
|
||||||
|
padding: 2px 4px;
|
||||||
|
font-size: var(--fs-md);
|
||||||
|
}
|
||||||
|
.pill-tab .svg-icon {
|
||||||
|
width: 13px;
|
||||||
|
height: 13px;
|
||||||
|
}
|
||||||
|
.pill-tab-badge {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@container (max-width: 23em) {
|
||||||
|
.pill-tab {
|
||||||
|
gap: 0;
|
||||||
|
padding: 2px 3px;
|
||||||
|
}
|
||||||
|
.pill-tab .svg-icon {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@container (max-width: 17.5em) {
|
||||||
|
.pill-tab .svg-icon {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
.pill-tab-label {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.pill-tab:hover {
|
.pill-tab:hover {
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
}
|
}
|
||||||
@@ -223,8 +267,8 @@
|
|||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: var(--space-2);
|
gap: var(--space-2);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 24px;
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
padding: 2px 6px;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
border: none;
|
border: none;
|
||||||
@@ -350,7 +394,7 @@
|
|||||||
.number-input {
|
.number-input {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: stretch;
|
align-items: stretch;
|
||||||
height: 28px;
|
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
@@ -410,8 +454,8 @@
|
|||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: var(--space-2);
|
gap: var(--space-2);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 26px;
|
min-height: calc(26px * var(--ui-font-scale, 1));
|
||||||
padding: 0 var(--space-2);
|
padding: 2px var(--space-2);
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
@@ -464,7 +508,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.dt-day {
|
.dt-day {
|
||||||
height: 22px;
|
min-height: calc(22px * var(--ui-font-scale, 1));
|
||||||
border: none;
|
border: none;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
@@ -540,8 +584,8 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
height: 22px;
|
min-height: calc(22px * var(--ui-font-scale, 1));
|
||||||
padding: 0 7px;
|
padding: 2px 7px;
|
||||||
border: none;
|
border: none;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
@@ -650,8 +694,8 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
height: 28px;
|
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||||
padding: 0 var(--space-5);
|
padding: 3px var(--space-5);
|
||||||
background: var(--accent-primary);
|
background: var(--accent-primary);
|
||||||
color: var(--text-inverse);
|
color: var(--text-inverse);
|
||||||
border: 1px solid var(--accent-primary);
|
border: 1px solid var(--accent-primary);
|
||||||
@@ -675,8 +719,8 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
height: 28px;
|
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||||
padding: 0 var(--space-4);
|
padding: 3px var(--space-4);
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
border: 1px solid var(--border-strong);
|
border: 1px solid var(--border-strong);
|
||||||
@@ -714,8 +758,8 @@
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
height: 22px;
|
min-height: calc(22px * var(--ui-font-scale, 1));
|
||||||
padding: 0 7px;
|
padding: 2px 7px;
|
||||||
font-size: var(--fs-md);
|
font-size: var(--fs-md);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
@@ -744,18 +788,12 @@
|
|||||||
min-height: 26px;
|
min-height: 26px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.topbar-header-right {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--space-2);
|
|
||||||
}
|
|
||||||
|
|
||||||
.btn-ghost-sm {
|
.btn-ghost-sm {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
padding: 1px 6px;
|
||||||
font-size: var(--fs-md);
|
font-size: var(--fs-md);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
@@ -781,40 +819,13 @@
|
|||||||
cursor: default;
|
cursor: default;
|
||||||
}
|
}
|
||||||
|
|
||||||
.topbar-slot-list {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 6px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.topbar-slot-row {
|
|
||||||
position: relative;
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
padding: 2px 4px 2px 6px;
|
|
||||||
border: 1px solid var(--border-hairline);
|
|
||||||
border-radius: var(--radius-xs);
|
|
||||||
background: transparent;
|
|
||||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
|
||||||
}
|
|
||||||
|
|
||||||
.topbar-slot-row:focus-within,
|
|
||||||
.topbar-slot-row:has(.is-open) {
|
|
||||||
z-index: 30;
|
|
||||||
border-color: var(--border-strong);
|
|
||||||
}
|
|
||||||
|
|
||||||
.topbar-slot-row .select-menu {
|
|
||||||
max-height: 216px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.slot-index-badge {
|
.slot-index-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
width: 16px;
|
min-width: calc(16px * var(--ui-font-scale, 1));
|
||||||
height: 16px;
|
min-height: calc(16px * var(--ui-font-scale, 1));
|
||||||
|
padding: 0 3px;
|
||||||
font-size: var(--fs-sm);
|
font-size: var(--fs-sm);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
|
|
||||||
/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */
|
/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */
|
||||||
:host(.wm-capsule-host) {
|
:host(.wm-capsule-host) {
|
||||||
--ui-font-scale: 1;
|
--ui-font-scale: 1 !important;
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 6px;
|
gap: 6px;
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
-webkit-app-region: no-drag;
|
-webkit-app-region: no-drag;
|
||||||
pointer-events: auto;
|
pointer-events: auto;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
font-weight: 450;
|
font-weight: 450;
|
||||||
font-stretch: 100%;
|
font-stretch: 100%;
|
||||||
@@ -24,6 +24,7 @@
|
|||||||
letter-spacing: 0.015em;
|
letter-spacing: 0.015em;
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
z-index: 2147482900;
|
z-index: 2147482900;
|
||||||
}
|
}
|
||||||
@@ -77,6 +78,10 @@
|
|||||||
right: 144px;
|
right: 144px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
:host(.wm-capsule-host[data-dock="fixed"][data-os="mac"]) {
|
||||||
|
right: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
@keyframes wm-dot-pulse {
|
@keyframes wm-dot-pulse {
|
||||||
0%, 100% {
|
0%, 100% {
|
||||||
opacity: 1;
|
opacity: 1;
|
||||||
@@ -227,11 +232,11 @@
|
|||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */
|
/* 环形上下文指示器(固定预占宽度 58px:14px 环 + 5px 间距 + 完整容纳四字符 100%) */
|
||||||
.wm-ctx-seg {
|
.wm-ctx-seg {
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
width: 50px;
|
width: 58px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wm-ring-svg {
|
.wm-ring-svg {
|
||||||
@@ -266,8 +271,10 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.wm-ctx-pct {
|
.wm-ctx-pct {
|
||||||
min-width: 27px;
|
min-width: 28px;
|
||||||
max-width: 31px;
|
max-width: none;
|
||||||
|
overflow: visible;
|
||||||
|
text-overflow: clip;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
@@ -518,11 +525,12 @@
|
|||||||
overflow: visible;
|
overflow: visible;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
z-index: 2147483000;
|
z-index: 2147483000;
|
||||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
font-family: var(--font-sans);
|
||||||
font-size: var(--fs-body);
|
font-size: var(--fs-body);
|
||||||
line-height: 1.4;
|
line-height: 1.4;
|
||||||
font-variant-numeric: tabular-nums;
|
font-variant-numeric: tabular-nums;
|
||||||
-webkit-font-smoothing: antialiased;
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -581,7 +589,7 @@
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
top: 42px;
|
top: 42px;
|
||||||
left: 12px;
|
left: 12px;
|
||||||
width: min(522px, calc(100vw - 24px));
|
width: min(calc(522px * var(--ui-panel-scale, 1)), calc(100vw - 24px));
|
||||||
max-height: calc(100vh - 54px);
|
max-height: calc(100vh - 54px);
|
||||||
padding: var(--space-3) var(--space-4);
|
padding: var(--space-3) var(--space-4);
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -605,7 +613,7 @@
|
|||||||
position: fixed;
|
position: fixed;
|
||||||
top: 42px;
|
top: 42px;
|
||||||
left: 12px;
|
left: 12px;
|
||||||
width: min(464px, calc(100vw - 24px));
|
width: min(calc(464px * var(--ui-panel-scale, 1)), calc(100vw - 24px));
|
||||||
max-height: calc(100vh - 54px);
|
max-height: calc(100vh - 54px);
|
||||||
padding: 14px 16px;
|
padding: 14px 16px;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -711,8 +719,8 @@
|
|||||||
.wm-pin-badge {
|
.wm-pin-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 16px;
|
min-height: calc(16px * var(--ui-font-scale, 1));
|
||||||
padding: 0 5px;
|
padding: 1px 5px;
|
||||||
font-size: var(--fs-xs);
|
font-size: var(--fs-xs);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--accent-primary);
|
color: var(--accent-primary);
|
||||||
@@ -724,8 +732,8 @@
|
|||||||
.wm-session-tag {
|
.wm-session-tag {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 16px;
|
min-height: calc(16px * var(--ui-font-scale, 1));
|
||||||
padding: 0 4px;
|
padding: 1px 4px;
|
||||||
font-size: var(--fs-xs);
|
font-size: var(--fs-xs);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
|
|||||||
@@ -6,6 +6,10 @@
|
|||||||
|
|
||||||
:root,
|
:root,
|
||||||
:host {
|
:host {
|
||||||
|
/* Cross-Platform Typography Stacks (macOS SF Pro / SF Mono + Windows / Linux Fallbacks) */
|
||||||
|
--font-sans: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", Roboto, sans-serif;
|
||||||
|
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Monaco, "Cascadia Mono", Consolas, monospace;
|
||||||
|
|
||||||
/* Architectural Geometry: Only Top Nav uses --radius-pill */
|
/* Architectural Geometry: Only Top Nav uses --radius-pill */
|
||||||
--radius-pill: 999px;
|
--radius-pill: 999px;
|
||||||
--radius-sm: 4px;
|
--radius-sm: 4px;
|
||||||
@@ -43,16 +47,15 @@
|
|||||||
--border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%);
|
--border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%);
|
||||||
|
|
||||||
/* Typography Hierarchy & Scalable Font Tokens */
|
/* Typography Hierarchy & Scalable Font Tokens */
|
||||||
--ui-font-scale: 1;
|
--fs-2xs: calc(10.5px * var(--ui-font-scale, 1));
|
||||||
--fs-2xs: calc(9.5px * var(--ui-font-scale, 1));
|
--fs-xs: calc(11px * var(--ui-font-scale, 1));
|
||||||
--fs-xs: calc(10px * var(--ui-font-scale, 1));
|
--fs-sm: calc(11.5px * var(--ui-font-scale, 1));
|
||||||
--fs-sm: calc(10.5px * var(--ui-font-scale, 1));
|
--fs-md: calc(12px * var(--ui-font-scale, 1));
|
||||||
--fs-md: calc(11px * var(--ui-font-scale, 1));
|
--fs-base-sm: calc(12.5px * var(--ui-font-scale, 1));
|
||||||
--fs-base-sm: calc(11.5px * var(--ui-font-scale, 1));
|
--fs-base: calc(13px * var(--ui-font-scale, 1));
|
||||||
--fs-base: calc(12px * var(--ui-font-scale, 1));
|
--fs-body: calc(13px * var(--ui-font-scale, 1));
|
||||||
--fs-body: calc(12.5px * var(--ui-font-scale, 1));
|
--fs-lg: calc(15px * var(--ui-font-scale, 1));
|
||||||
--fs-lg: calc(14.5px * var(--ui-font-scale, 1));
|
--fs-hero: calc(18px * var(--ui-font-scale, 1));
|
||||||
--fs-hero: calc(17px * var(--ui-font-scale, 1));
|
|
||||||
|
|
||||||
--text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%))));
|
--text-primary: var(--foreground, var(--vscode-foreground, var(--vscode-editor-foreground, hsl(215 22% 15%))));
|
||||||
--text-secondary: var(--muted-foreground, var(--vscode-descriptionForeground, hsl(215 12% 44%)));
|
--text-secondary: var(--muted-foreground, var(--vscode-descriptionForeground, hsl(215 12% 44%)));
|
||||||
@@ -120,6 +123,46 @@
|
|||||||
--space-5: 12px;
|
--space-5: 12px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
:root[data-font-scale="sm"],
|
||||||
|
:host([data-font-scale="sm"]),
|
||||||
|
[data-font-scale="sm"] {
|
||||||
|
--ui-font-scale: 0.92;
|
||||||
|
--ui-panel-scale: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-font-scale="md"],
|
||||||
|
:host([data-font-scale="md"]),
|
||||||
|
[data-font-scale="md"] {
|
||||||
|
--ui-font-scale: 1;
|
||||||
|
--ui-panel-scale: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-font-scale="lg"],
|
||||||
|
:host([data-font-scale="lg"]),
|
||||||
|
[data-font-scale="lg"] {
|
||||||
|
--ui-font-scale: 1.14;
|
||||||
|
--ui-panel-scale: 1.09;
|
||||||
|
}
|
||||||
|
|
||||||
|
:root[data-font-scale="xl"],
|
||||||
|
:host([data-font-scale="xl"]),
|
||||||
|
[data-font-scale="xl"] {
|
||||||
|
--ui-font-scale: 1.28;
|
||||||
|
--ui-panel-scale: 1.18;
|
||||||
|
}
|
||||||
|
|
||||||
|
[data-font-scale] {
|
||||||
|
--fs-2xs: calc(10.5px * var(--ui-font-scale, 1));
|
||||||
|
--fs-xs: calc(11px * var(--ui-font-scale, 1));
|
||||||
|
--fs-sm: calc(11.5px * var(--ui-font-scale, 1));
|
||||||
|
--fs-md: calc(12px * var(--ui-font-scale, 1));
|
||||||
|
--fs-base-sm: calc(12.5px * var(--ui-font-scale, 1));
|
||||||
|
--fs-base: calc(13px * var(--ui-font-scale, 1));
|
||||||
|
--fs-body: calc(13px * var(--ui-font-scale, 1));
|
||||||
|
--fs-lg: calc(15px * var(--ui-font-scale, 1));
|
||||||
|
--fs-hero: calc(18px * var(--ui-font-scale, 1));
|
||||||
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
html[data-standalone="true"] {
|
html[data-standalone="true"] {
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
|
|||||||
@@ -45,7 +45,7 @@
|
|||||||
|
|
||||||
.cons-split-3 {
|
.cons-split-3 {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(3, 1fr);
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
}
|
}
|
||||||
|
|
||||||
.cons-matrix-bottom {
|
.cons-matrix-bottom {
|
||||||
@@ -166,8 +166,8 @@
|
|||||||
.cons-row-title {
|
.cons-row-title {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
line-height: 20px;
|
line-height: 1.3;
|
||||||
font-size: var(--fs-base);
|
font-size: var(--fs-base);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
@@ -177,16 +177,16 @@
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
.cons-share-pill {
|
.cons-share-pill {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
line-height: 1;
|
line-height: 1.2;
|
||||||
padding: 0 6px;
|
padding: 1px 6px;
|
||||||
font-size: var(--fs-base);
|
font-size: var(--fs-base);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--metric-ok);
|
color: var(--metric-ok);
|
||||||
@@ -199,8 +199,8 @@
|
|||||||
.cons-row-tok {
|
.cons-row-tok {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
line-height: 1;
|
line-height: 1.25;
|
||||||
font-size: var(--fs-base);
|
font-size: var(--fs-base);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
@@ -209,8 +209,8 @@
|
|||||||
.cons-row-cost {
|
.cons-row-cost {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
line-height: 1;
|
line-height: 1.25;
|
||||||
font-size: var(--fs-base);
|
font-size: var(--fs-base);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
@@ -287,7 +287,7 @@
|
|||||||
top: 2px;
|
top: 2px;
|
||||||
left: var(--peak-x, 50%);
|
left: var(--peak-x, 50%);
|
||||||
transform: translateX(-50%);
|
transform: translateX(-50%);
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
padding: 1px 6px;
|
padding: 1px 6px;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
@@ -306,7 +306,7 @@
|
|||||||
transform: translateX(var(--tip-shift, -50%));
|
transform: translateX(var(--tip-shift, -50%));
|
||||||
width: max-content;
|
width: max-content;
|
||||||
min-width: 152px;
|
min-width: 152px;
|
||||||
max-width: min(300px, calc(100% - 8px));
|
max-width: min(320px, calc(100% - 8px));
|
||||||
padding: 5px 9px;
|
padding: 5px 9px;
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
border: 1px solid var(--border-strong);
|
border: 1px solid var(--border-strong);
|
||||||
@@ -324,7 +324,7 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 10px;
|
gap: 10px;
|
||||||
font-size: 10.5px;
|
font-size: var(--fs-sm);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -336,7 +336,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-calls {
|
.trend-tip-calls {
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
max-width: 190px;
|
max-width: 190px;
|
||||||
@@ -352,7 +352,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-tokens {
|
.trend-tip-tokens {
|
||||||
font-size: 12px;
|
font-size: var(--fs-base);
|
||||||
font-weight: 700;
|
font-weight: 700;
|
||||||
color: var(--accent-primary);
|
color: var(--accent-primary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
@@ -360,7 +360,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-cost {
|
.trend-tip-cost {
|
||||||
font-size: 11px;
|
font-size: var(--fs-md);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
@@ -368,7 +368,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.trend-tip-sub {
|
.trend-tip-sub {
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -391,7 +391,7 @@
|
|||||||
.trend-x-axis {
|
.trend-x-axis {
|
||||||
position: relative;
|
position: relative;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 18px;
|
min-height: calc(18px * var(--ui-font-scale, 1));
|
||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -400,10 +400,10 @@
|
|||||||
top: 0;
|
top: 0;
|
||||||
left: var(--tick-x, 0%);
|
left: var(--tick-x, 0%);
|
||||||
transform: translateX(-50%);
|
transform: translateX(-50%);
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
line-height: 16px;
|
line-height: 1.35;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: color var(--dur-instant) var(--ease-fast);
|
transition: color var(--dur-instant) var(--ease-fast);
|
||||||
}
|
}
|
||||||
@@ -455,21 +455,21 @@
|
|||||||
|
|
||||||
.trend-hm-weekdays {
|
.trend-hm-weekdays {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-rows: 15px repeat(7, var(--hm-cell));
|
grid-template-rows: calc(15px * var(--ui-font-scale, 1)) repeat(7, var(--hm-cell));
|
||||||
row-gap: var(--hm-gap);
|
row-gap: var(--hm-gap);
|
||||||
width: 14px;
|
width: calc(15px * var(--ui-font-scale, 1));
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-hm-month-spacer {
|
.trend-hm-month-spacer {
|
||||||
height: 15px;
|
height: calc(15px * var(--ui-font-scale, 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-hm-wday {
|
.trend-hm-wday {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: flex-start;
|
justify-content: flex-start;
|
||||||
font-size: 9px;
|
font-size: var(--fs-2xs);
|
||||||
line-height: 1;
|
line-height: 1;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
@@ -490,7 +490,7 @@
|
|||||||
|
|
||||||
.trend-hm-months {
|
.trend-hm-months {
|
||||||
position: relative;
|
position: relative;
|
||||||
height: 15px;
|
height: calc(15px * var(--ui-font-scale, 1));
|
||||||
width: 100%;
|
width: 100%;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -498,8 +498,8 @@
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
top: 0;
|
top: 0;
|
||||||
left: calc(var(--hm-col, 0) * (var(--hm-cell) + var(--hm-gap)));
|
left: calc(var(--hm-col, 0) * (var(--hm-cell) + var(--hm-gap)));
|
||||||
font-size: 9.5px;
|
font-size: var(--fs-2xs);
|
||||||
line-height: 14px;
|
line-height: 1.25;
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
@@ -511,6 +511,7 @@
|
|||||||
grid-auto-flow: column;
|
grid-auto-flow: column;
|
||||||
grid-auto-columns: var(--hm-cell);
|
grid-auto-columns: var(--hm-cell);
|
||||||
gap: var(--hm-gap);
|
gap: var(--hm-gap);
|
||||||
|
cursor: pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
.trend-hm-cell {
|
.trend-hm-cell {
|
||||||
@@ -564,7 +565,7 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
min-height: 16px;
|
min-height: 16px;
|
||||||
}
|
}
|
||||||
@@ -581,7 +582,7 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 3px;
|
gap: 3px;
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
font-size: 9.5px;
|
font-size: var(--fs-2xs);
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -642,7 +643,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.month-cost {
|
.month-cost {
|
||||||
font-size: 9.5px;
|
font-size: var(--fs-2xs);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
min-height: 14px;
|
min-height: 14px;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
@@ -686,7 +687,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.month-label {
|
.month-label {
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
padding: 1px 3px;
|
padding: 1px 3px;
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
@@ -700,7 +701,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.month-tok {
|
.month-tok {
|
||||||
font-size: 9px;
|
font-size: var(--fs-2xs);
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
min-height: 12px;
|
min-height: 12px;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
|
|||||||
@@ -94,6 +94,14 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */
|
/* --- 2. 多任务实时运行卡片列表与 4 格测速指标矩阵 (Live Running Tasks List & 4-Cell Telemetry Matrix) --- */
|
||||||
|
.overview-modules-host {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-3);
|
||||||
|
min-width: 0;
|
||||||
|
padding-bottom: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
.live-activity-list {
|
.live-activity-list {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -156,8 +164,8 @@
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 3px;
|
gap: 3px;
|
||||||
height: 18px;
|
min-height: calc(18px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
padding: 1px 6px;
|
||||||
font-size: var(--fs-sm);
|
font-size: var(--fs-sm);
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
@@ -477,7 +485,7 @@
|
|||||||
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
|
/* --- 4. 上下文双列图例网格 (Context 10-Channel Legend Grid) --- */
|
||||||
.ctx-legend-grid {
|
.ctx-legend-grid {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(2, 1fr);
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
gap: 5px var(--space-4);
|
gap: 5px var(--space-4);
|
||||||
padding: 2px 0 0 0;
|
padding: 2px 0 0 0;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
@@ -490,6 +498,7 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
gap: var(--space-2);
|
gap: var(--space-2);
|
||||||
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.legend-left {
|
.legend-left {
|
||||||
@@ -547,8 +556,8 @@
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
height: 20px;
|
min-height: calc(20px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
padding: 1px 6px;
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
background: var(--surface-panel);
|
background: var(--surface-panel);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
|
|||||||
@@ -37,7 +37,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.settings-subnav-bar .seg-btn {
|
.settings-subnav-bar .seg-btn {
|
||||||
height: 24px;
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
font-size: var(--fs-base-sm);
|
font-size: var(--fs-base-sm);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
@@ -55,9 +55,9 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
height: 25px;
|
min-height: calc(25px * var(--ui-font-scale, 1));
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
padding: 0 6px;
|
padding: 2px 6px;
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
background: var(--surface-subtle);
|
background: var(--surface-subtle);
|
||||||
@@ -116,8 +116,8 @@
|
|||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
height: 24px;
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
padding: 0 9px;
|
padding: 2px 9px;
|
||||||
font-size: var(--fs-md);
|
font-size: var(--fs-md);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
@@ -230,19 +230,15 @@
|
|||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- 结构页真实 UI 实时预览画布(无套娃外框,直接呈现真实组件) --- */
|
/* --- 结构页真实 UI 实时预览画布(1:1 零缩放、零套娃外框,直接呈现真实组件) --- */
|
||||||
.structure-preview-canvas {
|
.structure-preview-canvas {
|
||||||
position: relative;
|
position: relative;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: var(--space-2);
|
gap: var(--space-3);
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.structure-preview-canvas.is-scaled {
|
|
||||||
zoom: 0.86;
|
|
||||||
}
|
|
||||||
|
|
||||||
.wm-hover-tip.is-preview {
|
.wm-hover-tip.is-preview {
|
||||||
position: relative;
|
position: relative;
|
||||||
top: auto;
|
top: auto;
|
||||||
@@ -260,10 +256,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.overview-modules-host.is-preview {
|
.overview-modules-host.is-preview {
|
||||||
display: flex;
|
padding-bottom: 0;
|
||||||
flex-direction: column;
|
|
||||||
gap: var(--space-2);
|
|
||||||
min-width: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.structure-preview-empty,
|
.structure-preview-empty,
|
||||||
@@ -286,6 +279,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.preview-capsule-bar {
|
.preview-capsule-bar {
|
||||||
|
--ui-font-scale: 1;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
@@ -295,6 +289,10 @@
|
|||||||
background: var(--surface-bg);
|
background: var(--surface-bg);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
|
font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
user-select: none;
|
user-select: none;
|
||||||
}
|
}
|
||||||
@@ -367,21 +365,6 @@
|
|||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.preview-win-controls {
|
|
||||||
display: inline-flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 5px;
|
|
||||||
padding-left: 4px;
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-win-dot {
|
|
||||||
width: 7px;
|
|
||||||
height: 7px;
|
|
||||||
border-radius: var(--radius-pill);
|
|
||||||
background: color-mix(in srgb, var(--text-secondary) 26%, transparent);
|
|
||||||
}
|
|
||||||
|
|
||||||
.preview-composer-send {
|
.preview-composer-send {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -431,8 +414,8 @@
|
|||||||
.collapsible-badge {
|
.collapsible-badge {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
height: 18px;
|
min-height: calc(18px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
padding: 1px 6px;
|
||||||
font-size: var(--fs-sm);
|
font-size: var(--fs-sm);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
@@ -577,8 +560,8 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
gap: 5px;
|
gap: 5px;
|
||||||
height: 24px;
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
padding: 0 9px;
|
padding: 2px 9px;
|
||||||
font-size: var(--fs-md);
|
font-size: var(--fs-md);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
color: var(--accent-primary);
|
color: var(--accent-primary);
|
||||||
@@ -711,8 +694,8 @@
|
|||||||
.settings-text-input {
|
.settings-text-input {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
height: 28px;
|
min-height: calc(28px * var(--ui-font-scale, 1));
|
||||||
padding: 0 8px;
|
padding: 2px 8px;
|
||||||
background: var(--surface-subtle);
|
background: var(--surface-subtle);
|
||||||
border: 1px solid var(--border-hairline);
|
border: 1px solid var(--border-hairline);
|
||||||
border-radius: var(--radius-xs);
|
border-radius: var(--radius-xs);
|
||||||
@@ -738,7 +721,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.settings-number-wrap .number-input {
|
.settings-number-wrap .number-input {
|
||||||
height: 24px;
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
background: var(--surface-subtle);
|
background: var(--surface-subtle);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -831,7 +814,148 @@
|
|||||||
|
|
||||||
.ctx-risk-accept-btn {
|
.ctx-risk-accept-btn {
|
||||||
margin-top: 2px;
|
margin-top: 2px;
|
||||||
height: 26px;
|
min-height: calc(26px * var(--ui-font-scale, 1));
|
||||||
padding: 0 var(--space-3);
|
padding: 2px var(--space-3);
|
||||||
font-size: var(--fs-md);
|
font-size: var(--fs-md);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* --- CDP / 双栖桥接端口诊断与一键重拉卡片 (.settings-bridge-notice) --- */
|
||||||
|
.app-bridge-banner-slot {
|
||||||
|
padding: 0 var(--space-4) var(--space-2);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.app-bridge-banner-slot[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-notice {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
gap: 5px;
|
||||||
|
padding: var(--space-3) var(--space-4);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
border: 1px solid color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline));
|
||||||
|
background: color-mix(in srgb, var(--surface-panel) 89%, var(--metric-warn) 7%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-notice.is-restart {
|
||||||
|
border-color: color-mix(in srgb, var(--metric-info) 42%, var(--border-hairline));
|
||||||
|
background: color-mix(in srgb, var(--surface-panel) 89%, var(--metric-info) 7%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-notice[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
color: var(--metric-warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-head-main {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-notice.is-restart .settings-bridge-head,
|
||||||
|
.settings-bridge-notice.is-restart .settings-bridge-icon,
|
||||||
|
.settings-bridge-notice.is-restart .settings-bridge-title {
|
||||||
|
color: var(--metric-info);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-icon {
|
||||||
|
color: var(--metric-warn);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-title {
|
||||||
|
font-size: var(--fs-md);
|
||||||
|
font-weight: 600;
|
||||||
|
line-height: 1.35;
|
||||||
|
color: var(--metric-warn);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-dismiss-btn {
|
||||||
|
padding: 2px 4px;
|
||||||
|
min-height: 20px;
|
||||||
|
line-height: 1;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-desc {
|
||||||
|
margin: 0;
|
||||||
|
font-size: var(--fs-sm);
|
||||||
|
line-height: 1.48;
|
||||||
|
color: var(--text-primary);
|
||||||
|
word-break: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-actions {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 2px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-relaunch-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 5px;
|
||||||
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
|
padding: 2px var(--space-3);
|
||||||
|
border-radius: var(--radius-xs);
|
||||||
|
border: 1px solid var(--accent-primary-border);
|
||||||
|
background: var(--accent-primary-soft);
|
||||||
|
color: var(--accent-primary);
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
max-width: 100%;
|
||||||
|
transition:
|
||||||
|
background-color var(--dur-instant) var(--ease-fast),
|
||||||
|
opacity var(--dur-instant) var(--ease-fast);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-relaunch-btn:hover:not(:disabled) {
|
||||||
|
background: color-mix(in srgb, var(--accent-primary) 20%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-relaunch-btn:disabled {
|
||||||
|
opacity: 0.65;
|
||||||
|
cursor: wait;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-relaunch-btn[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-relaunch-text {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-copy-btn {
|
||||||
|
min-height: calc(24px * var(--ui-font-scale, 1));
|
||||||
|
padding: 2px var(--space-3);
|
||||||
|
font-size: var(--fs-xs);
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-bridge-copy-text {
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|||||||
@@ -35,13 +35,14 @@
|
|||||||
.data-table {
|
.data-table {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
border-collapse: collapse;
|
border-collapse: collapse;
|
||||||
font-size: var(--fs-md);
|
font-size: var(--fs-base-sm);
|
||||||
}
|
}
|
||||||
|
|
||||||
.data-table th,
|
.data-table th,
|
||||||
.data-table td {
|
.data-table td {
|
||||||
padding: 5px 4px;
|
padding: calc(5px * var(--ui-font-scale, 1)) calc(4px * var(--ui-font-scale, 1));
|
||||||
text-align: left;
|
text-align: left;
|
||||||
|
font-size: var(--fs-base-sm);
|
||||||
border-bottom: 1px solid var(--border-hairline);
|
border-bottom: 1px solid var(--border-hairline);
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
}
|
}
|
||||||
@@ -78,7 +79,7 @@
|
|||||||
.step-model-cell {
|
.step-model-cell {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: baseline;
|
align-items: baseline;
|
||||||
max-width: var(--step-model-max-w, 176px);
|
max-width: calc(var(--step-model-max-w, 176px) * var(--ui-font-scale, 1));
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
vertical-align: bottom;
|
vertical-align: bottom;
|
||||||
}
|
}
|
||||||
@@ -94,7 +95,7 @@
|
|||||||
.step-model-compact {
|
.step-model-compact {
|
||||||
flex-shrink: 0;
|
flex-shrink: 0;
|
||||||
white-space: nowrap;
|
white-space: nowrap;
|
||||||
color: var(--metric-info, var(--accent-primary));
|
color: var(--accent-primary);
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -133,8 +134,9 @@
|
|||||||
|
|
||||||
.steps-inline-scope-select .select-trigger,
|
.steps-inline-scope-select .select-trigger,
|
||||||
.steps-inline-model-select .select-trigger {
|
.steps-inline-model-select .select-trigger {
|
||||||
height: 22px;
|
min-height: calc(22px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
height: auto;
|
||||||
|
padding: 2px 6px;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -320,8 +322,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.sstep-fit-model-select .select-trigger {
|
.sstep-fit-model-select .select-trigger {
|
||||||
height: 22px;
|
min-height: calc(22px * var(--ui-font-scale, 1));
|
||||||
padding: 0 6px;
|
height: auto;
|
||||||
|
padding: 2px 6px;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
@@ -377,7 +380,7 @@
|
|||||||
.sstep-axis-label {
|
.sstep-axis-label {
|
||||||
fill: var(--text-muted);
|
fill: var(--text-muted);
|
||||||
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, Consolas, monospace);
|
||||||
font-size: 9.5px;
|
font-size: var(--fs-2xs);
|
||||||
user-select: none;
|
user-select: none;
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
}
|
}
|
||||||
@@ -485,7 +488,7 @@
|
|||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
font-size: 11px;
|
font-size: var(--fs-md);
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
z-index: 2;
|
z-index: 2;
|
||||||
}
|
}
|
||||||
@@ -496,7 +499,7 @@
|
|||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: 4px 10px;
|
gap: 4px 10px;
|
||||||
padding-top: 2px;
|
padding-top: 2px;
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -535,7 +538,7 @@
|
|||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
gap: 4px 8px;
|
gap: 4px 8px;
|
||||||
padding-top: 2px;
|
padding-top: 2px;
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
color: var(--text-muted);
|
color: var(--text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -595,7 +598,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.sstep-fit-delta {
|
.sstep-fit-delta {
|
||||||
font-size: 10px;
|
font-size: var(--fs-xs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/* --- 4. 极简高密度模型总览列表 (Minimalist Session Model Summary Cards) --- */
|
/* --- 4. 极简高密度模型总览列表 (Minimalist Session Model Summary Cards) --- */
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import {
|
|||||||
normalizeModelDisplayMode,
|
normalizeModelDisplayMode,
|
||||||
normalizeOrchestratorIdDisplayMode,
|
normalizeOrchestratorIdDisplayMode,
|
||||||
} from '../core/formatters.js';
|
} from '../core/formatters.js';
|
||||||
|
import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs';
|
||||||
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
|
||||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||||
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
import { fetchTelemetry, telemetryStore } from '../store/telemetryStore.js';
|
||||||
@@ -572,22 +573,14 @@ export const ConsumptionView = defineComponent({
|
|||||||
let cachePct = 0;
|
let cachePct = 0;
|
||||||
let outPct = 0;
|
let outPct = 0;
|
||||||
if (totalTokens > 0) {
|
if (totalTokens > 0) {
|
||||||
const rawTenths = [
|
const scaled = scaleBucketsExact(
|
||||||
(inputTokens / totalTokens) * 1000,
|
{ in: inputTokens, cache: cacheTokens, out: outputTokens },
|
||||||
(cacheTokens / totalTokens) * 1000,
|
['in', 'cache', 'out'],
|
||||||
(outputTokens / totalTokens) * 1000,
|
1000
|
||||||
];
|
|
||||||
const floored = rawTenths.map((v) => Math.max(0, Math.floor(v)));
|
|
||||||
const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2]));
|
|
||||||
const order = [0, 1, 2].sort(
|
|
||||||
(a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a])
|
|
||||||
);
|
);
|
||||||
for (let k = 0; k < rem && k < 3; k++) {
|
inPct = +(scaled.in / 10).toFixed(1);
|
||||||
floored[order[k]] += 1;
|
cachePct = +(scaled.cache / 10).toFixed(1);
|
||||||
}
|
outPct = +(scaled.out / 10).toFixed(1);
|
||||||
inPct = +(floored[0] / 10).toFixed(1);
|
|
||||||
cachePct = +(floored[1] / 10).toFixed(1);
|
|
||||||
outPct = +(floored[2] / 10).toFixed(1);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
patchText(inputSharePct, `${inPct}%`);
|
patchText(inputSharePct, `${inPct}%`);
|
||||||
|
|||||||
@@ -31,7 +31,6 @@ export const LiveOverviewView = defineComponent({
|
|||||||
setup({ onCleanup }) {
|
setup({ onCleanup }) {
|
||||||
const overviewInner = h('div', {
|
const overviewInner = h('div', {
|
||||||
className: 'overview-modules-host',
|
className: 'overview-modules-host',
|
||||||
style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;',
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const widgetHost = createDynamicWidgetHost({
|
const widgetHost = createDynamicWidgetHost({
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import { telemetryStore } from '../store/telemetryStore.js';
|
|||||||
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
import { getVisibleMonitorView, uiStore } from '../store/uiStore.js';
|
||||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||||
import { SettingsAccountTab } from './settings/SettingsAccountTab.js';
|
|
||||||
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
import { SettingsGeneralTab } from './settings/SettingsGeneralTab.js';
|
||||||
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
import { SettingsOtherTab } from './settings/SettingsOtherTab.js';
|
||||||
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
import { SettingsStructureTab } from './settings/SettingsStructureTab.js';
|
||||||
@@ -52,7 +51,7 @@ export const SettingsView = defineComponent({
|
|||||||
|
|
||||||
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
|
const generalTab = SettingsGeneralTab({ onLayoutChange: refreshScroll });
|
||||||
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
|
const structureTab = SettingsStructureTab({ onLayoutChange: refreshScroll });
|
||||||
const accountTab = SettingsAccountTab({ onLayoutChange: refreshScroll });
|
const accountTab = null; // SettingsAccountTab kept in src/views/settings/ for future opt-in
|
||||||
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
|
const otherTab = SettingsOtherTab({ onLayoutChange: refreshScroll });
|
||||||
|
|
||||||
let showingAccount = false;
|
let showingAccount = false;
|
||||||
@@ -60,25 +59,27 @@ export const SettingsView = defineComponent({
|
|||||||
const target =
|
const target =
|
||||||
subTab === 'structure' ||
|
subTab === 'structure' ||
|
||||||
subTab === 'other' ||
|
subTab === 'other' ||
|
||||||
(SHOW_ACCOUNT_TAB && subTab === 'account')
|
(accountTab && subTab === 'account')
|
||||||
? subTab
|
? subTab
|
||||||
: 'general';
|
: 'general';
|
||||||
subNavSwitch.setValue(target);
|
subNavSwitch.setValue(target);
|
||||||
patchAttr(generalTab.el, 'hidden', target !== 'general');
|
patchAttr(generalTab.el, 'hidden', target !== 'general');
|
||||||
patchAttr(structureTab.el, 'hidden', target !== 'structure');
|
patchAttr(structureTab.el, 'hidden', target !== 'structure');
|
||||||
patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure');
|
patchAttr(structureTab.refs.thirdNavBar, 'hidden', target !== 'structure');
|
||||||
patchAttr(accountTab.el, 'hidden', !SHOW_ACCOUNT_TAB || target !== 'account');
|
|
||||||
patchAttr(otherTab.el, 'hidden', target !== 'other');
|
patchAttr(otherTab.el, 'hidden', target !== 'other');
|
||||||
const nextShowingAccount = SHOW_ACCOUNT_TAB && target === 'account' && activeView === 'settings';
|
if (accountTab) {
|
||||||
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
|
patchAttr(accountTab.el, 'hidden', target !== 'account');
|
||||||
showingAccount = nextShowingAccount;
|
const nextShowingAccount = target === 'account' && activeView === 'settings';
|
||||||
|
if (nextShowingAccount && !showingAccount) void accountTab.refs.load();
|
||||||
|
showingAccount = nextShowingAccount;
|
||||||
|
}
|
||||||
refreshScroll();
|
refreshScroll();
|
||||||
}
|
}
|
||||||
|
|
||||||
const contentContainer = h(
|
const contentContainer = h(
|
||||||
'div',
|
'div',
|
||||||
{},
|
{},
|
||||||
SHOW_ACCOUNT_TAB
|
accountTab
|
||||||
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
|
? [generalTab.el, structureTab.el, accountTab.el, otherTab.el]
|
||||||
: [generalTab.el, structureTab.el, otherTab.el]
|
: [generalTab.el, structureTab.el, otherTab.el]
|
||||||
);
|
);
|
||||||
@@ -102,10 +103,23 @@ export const SettingsView = defineComponent({
|
|||||||
const telemetry = telemetryStore.getState().telemetry;
|
const telemetry = telemetryStore.getState().telemetry;
|
||||||
const settings = telemetry?.settings;
|
const settings = telemetry?.settings;
|
||||||
if (settingsSubTab === 'structure') {
|
if (settingsSubTab === 'structure') {
|
||||||
if (settings) structureTab.refs.renderSettings(settings);
|
if (settings) {
|
||||||
|
structureTab.refs.renderSettings(
|
||||||
|
settings,
|
||||||
|
telemetry?.windowBridge,
|
||||||
|
telemetry?.hostPlatform
|
||||||
|
);
|
||||||
|
}
|
||||||
} else if (settingsSubTab === 'other') {
|
} else if (settingsSubTab === 'other') {
|
||||||
if (settings) otherTab.refs.renderSettings(settings, telemetry.contextWindowModels || []);
|
if (settings) {
|
||||||
} else if (SHOW_ACCOUNT_TAB && settingsSubTab === 'account') {
|
otherTab.refs.renderSettings(
|
||||||
|
settings,
|
||||||
|
telemetry.contextWindowModels || [],
|
||||||
|
telemetry?.windowBridge,
|
||||||
|
telemetry?.hostPlatform
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else if (accountTab && settingsSubTab === 'account') {
|
||||||
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
|
accountTab.refs.renderAccount(telemetry?.account, telemetry?.quotas);
|
||||||
} else {
|
} else {
|
||||||
if (settings) generalTab.refs.renderSettings(settings);
|
if (settings) generalTab.refs.renderSettings(settings);
|
||||||
@@ -117,6 +131,8 @@ export const SettingsView = defineComponent({
|
|||||||
const unsubTelemetry = telemetryStore.subscribe(
|
const unsubTelemetry = telemetryStore.subscribe(
|
||||||
(st) => ({
|
(st) => ({
|
||||||
settings: st.telemetry?.settings,
|
settings: st.telemetry?.settings,
|
||||||
|
windowBridge: st.telemetry?.windowBridge,
|
||||||
|
hostPlatform: st.telemetry?.hostPlatform,
|
||||||
cloudStatus: st.telemetry?.cloudStatus,
|
cloudStatus: st.telemetry?.cloudStatus,
|
||||||
contextWindowModels: st.telemetry?.contextWindowModels,
|
contextWindowModels: st.telemetry?.contextWindowModels,
|
||||||
account: st.telemetry?.account,
|
account: st.telemetry?.account,
|
||||||
@@ -145,7 +161,7 @@ export const SettingsView = defineComponent({
|
|||||||
});
|
});
|
||||||
generalTab.refs.refreshLabels();
|
generalTab.refs.refreshLabels();
|
||||||
structureTab.refs.refreshLabels();
|
structureTab.refs.refreshLabels();
|
||||||
accountTab.refs.refreshLabels();
|
accountTab?.refs.refreshLabels();
|
||||||
otherTab.refs.refreshLabels();
|
otherTab.refs.refreshLabels();
|
||||||
refreshScroll();
|
refreshScroll();
|
||||||
}
|
}
|
||||||
@@ -158,7 +174,7 @@ export const SettingsView = defineComponent({
|
|||||||
subNavSwitch.destroy();
|
subNavSwitch.destroy();
|
||||||
generalTab.destroy();
|
generalTab.destroy();
|
||||||
structureTab.destroy();
|
structureTab.destroy();
|
||||||
accountTab.destroy();
|
accountTab?.destroy();
|
||||||
otherTab.destroy();
|
otherTab.destroy();
|
||||||
viewScrollbar.destroy();
|
viewScrollbar.destroy();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -435,17 +435,20 @@ export const StepsDetailView = defineComponent({
|
|||||||
let isDirty = false;
|
let isDirty = false;
|
||||||
|
|
||||||
function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) {
|
function resolveDefaultActiveModelKey(scopedConv, chronoSteps, models, availableModelKeys) {
|
||||||
const activeCand = getStepModelGroupKey({
|
if (scopedConv?.hasKnownModel !== false) {
|
||||||
modelLabel: scopedConv?.activeModelLabel,
|
const activeCand = getStepModelGroupKey({
|
||||||
modelShort: scopedConv?.activeModelShort,
|
baseModelLabel: scopedConv?.activeBaseModelLabel,
|
||||||
});
|
baseModelShort: scopedConv?.activeBaseModelShort,
|
||||||
if (
|
modelLabel: scopedConv?.activeModelLabel,
|
||||||
activeCand &&
|
modelShort: scopedConv?.activeModelShort,
|
||||||
activeCand !== '模型未知' &&
|
});
|
||||||
activeCand !== t('fmt.unknownModel') &&
|
if (
|
||||||
availableModelKeys.has(activeCand)
|
activeCand &&
|
||||||
) {
|
activeCand !== t('fmt.unknownModel') &&
|
||||||
return activeCand;
|
availableModelKeys.has(activeCand)
|
||||||
|
) {
|
||||||
|
return activeCand;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (let i = chronoSteps.length - 1; i >= 0; i--) {
|
for (let i = chronoSteps.length - 1; i >= 0; i--) {
|
||||||
const st = chronoSteps[i];
|
const st = chronoSteps[i];
|
||||||
@@ -625,7 +628,7 @@ export const StepsDetailView = defineComponent({
|
|||||||
if (!stepModelOptionMap.has(gk)) {
|
if (!stepModelOptionMap.has(gk)) {
|
||||||
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
const disp = resolveModelDisplayInfo(st, displaySettings, { fallback: gk });
|
||||||
stepModelOptionMap.set(gk, {
|
stepModelOptionMap.set(gk, {
|
||||||
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk,
|
label: disp.baseText || disp.text || gk,
|
||||||
calls: 0,
|
calls: 0,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -656,7 +659,7 @@ export const StepsDetailView = defineComponent({
|
|||||||
});
|
});
|
||||||
perModelOptions.push({
|
perModelOptions.push({
|
||||||
value: gk,
|
value: gk,
|
||||||
label: disp.text.replace(/·(?:压缩|Compact)\s*$/iu, '').trim() || gk,
|
label: disp.baseText || disp.text || gk,
|
||||||
meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }),
|
meta: t('header.convMetaSteps', { count: Number(m.calls || 0) }),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
saveSettingsPatch,
|
saveSettingsPatch,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
import { CustomSelect } from '../../components/ui/CustomSelect.js';
|
||||||
|
import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js';
|
||||||
|
|
||||||
function getStepModelDisplayOptions() {
|
function getStepModelDisplayOptions() {
|
||||||
return [
|
return [
|
||||||
@@ -41,6 +42,8 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
let draftContextRiskAccepted = false;
|
let draftContextRiskAccepted = false;
|
||||||
let acceptingContextRisk = false;
|
let acceptingContextRisk = false;
|
||||||
let latestSettings = null;
|
let latestSettings = null;
|
||||||
|
let latestWindowBridge = null;
|
||||||
|
let latestHostPlatform = 'win32';
|
||||||
let contextWindowModels = [];
|
let contextWindowModels = [];
|
||||||
let contextModelId = '';
|
let contextModelId = '';
|
||||||
let savingContextWindow = false;
|
let savingContextWindow = false;
|
||||||
@@ -190,9 +193,11 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
const ctxBridgeNotice = BridgeStatusNotice({ contextMode: true });
|
||||||
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
|
const ctxModelRow = h('div', { className: 'form-row' }, [ctxModelLabel, ctxModelSelect.el]);
|
||||||
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
|
const ctxWindowRow = h('div', { className: 'form-row' }, [ctxWindowLabel, ctxWindowSelect.el]);
|
||||||
const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [
|
const ctxControlsBody = h('div', { className: 'ctx-controls-body is-locked' }, [
|
||||||
|
ctxBridgeNotice.el,
|
||||||
ctxModelRow,
|
ctxModelRow,
|
||||||
ctxWindowRow,
|
ctxWindowRow,
|
||||||
h('div', { className: 'form-row' }, [ctxHint]),
|
h('div', { className: 'form-row' }, [ctxHint]),
|
||||||
@@ -269,6 +274,13 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
patchAttr(ctxRiskAcceptBtn, 'disabled', acceptingContextRisk);
|
patchAttr(ctxRiskAcceptBtn, 'disabled', acceptingContextRisk);
|
||||||
|
|
||||||
const saved = latestSettings?.modelContextWindows || {};
|
const saved = latestSettings?.modelContextWindows || {};
|
||||||
|
const wbState = String(latestWindowBridge?.state || '').trim();
|
||||||
|
const isBridgeMissing = wbState === 'no_devtools_port' || wbState === 'cdp_unreachable';
|
||||||
|
ctxBridgeNotice.refs.update({
|
||||||
|
visible: unlocked,
|
||||||
|
windowBridge: latestWindowBridge,
|
||||||
|
hostPlatform: latestHostPlatform,
|
||||||
|
});
|
||||||
const models = new Map(contextWindowModels.map((model) => [model.id, model]));
|
const models = new Map(contextWindowModels.map((model) => [model.id, model]));
|
||||||
const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members]));
|
const knownIds = new Set(contextWindowModels.flatMap(({ id, members = [] }) => [id, ...members]));
|
||||||
for (const id of Object.keys(saved)) {
|
for (const id of Object.keys(saved)) {
|
||||||
@@ -313,6 +325,7 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
else if (value) {
|
else if (value) {
|
||||||
const name = formatLimit(value);
|
const name = formatLimit(value);
|
||||||
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
|
if (!isAvailable(model, value)) meta = t('settings.oth.ctxUnavailable', { name });
|
||||||
|
else if (isBridgeMissing) meta = t('settings.oth.ctxPendingBridge', { name });
|
||||||
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
|
else if (/^\d+$/.test(value) && model.reportedLimitTokens && Number(value) !== model.reportedLimitTokens) {
|
||||||
meta = t('settings.oth.ctxConfiguredReported', {
|
meta = t('settings.oth.ctxConfiguredReported', {
|
||||||
name,
|
name,
|
||||||
@@ -483,10 +496,17 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
maintPanel,
|
maintPanel,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
function renderSettings(settings, models = contextWindowModels) {
|
function renderSettings(
|
||||||
|
settings,
|
||||||
|
models = contextWindowModels,
|
||||||
|
windowBridge = latestWindowBridge,
|
||||||
|
hostPlatform = latestHostPlatform
|
||||||
|
) {
|
||||||
if (!settings) return;
|
if (!settings) return;
|
||||||
latestSettings = settings;
|
latestSettings = settings;
|
||||||
contextWindowModels = models;
|
contextWindowModels = models;
|
||||||
|
if (windowBridge !== undefined) latestWindowBridge = windowBridge;
|
||||||
|
if (hostPlatform) latestHostPlatform = hostPlatform;
|
||||||
draftModelDisplayMode = normalizeClientModelDisplayMode(
|
draftModelDisplayMode = normalizeClientModelDisplayMode(
|
||||||
settings.modelDisplayMode,
|
settings.modelDisplayMode,
|
||||||
settings.showUpstreamModel
|
settings.showUpstreamModel
|
||||||
@@ -544,6 +564,7 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
|
if (resetConfirmTimer) clearTimeout(resetConfirmTimer);
|
||||||
stepModelSelect.destroy();
|
stepModelSelect.destroy();
|
||||||
orchestratorIdSelect.destroy();
|
orchestratorIdSelect.destroy();
|
||||||
|
ctxBridgeNotice.destroy();
|
||||||
ctxModelSelect.destroy();
|
ctxModelSelect.destroy();
|
||||||
ctxWindowSelect.destroy();
|
ctxWindowSelect.destroy();
|
||||||
});
|
});
|
||||||
@@ -553,6 +574,7 @@ export const SettingsOtherTab = defineComponent({
|
|||||||
refs: {
|
refs: {
|
||||||
stepModelSelect,
|
stepModelSelect,
|
||||||
orchestratorIdSelect,
|
orchestratorIdSelect,
|
||||||
|
ctxBridgeNotice,
|
||||||
ctxModelSelect,
|
ctxModelSelect,
|
||||||
ctxWindowSelect,
|
ctxWindowSelect,
|
||||||
rebuildCacheBtn,
|
rebuildCacheBtn,
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ import {
|
|||||||
saveSettingsPatch,
|
saveSettingsPatch,
|
||||||
} from '../../store/telemetryStore.js';
|
} from '../../store/telemetryStore.js';
|
||||||
import { getVisibleMonitorView, uiStore } from '../../store/uiStore.js';
|
import { getVisibleMonitorView, uiStore } from '../../store/uiStore.js';
|
||||||
|
import { BridgeStatusNotice } from '../../components/settings/BridgeStatusNotice.js';
|
||||||
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
|
import { CollapsibleSection } from '../../components/settings/CollapsibleSection.js';
|
||||||
import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
|
import { EditableSlotList } from '../../components/settings/EditableSlotList.js';
|
||||||
import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js';
|
import { buildStructurePreviewTelemetry } from '../../components/settings/structurePreviewMock.js';
|
||||||
@@ -119,6 +120,8 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
let rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
let rawStepTokenComboText = DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT;
|
||||||
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
let draftStepColumns = [...DEFAULT_CLIENT_STEP_COLUMNS];
|
||||||
let latestSettings = null;
|
let latestSettings = null;
|
||||||
|
let latestWindowBridge = null;
|
||||||
|
let latestHostPlatform = 'win32';
|
||||||
|
|
||||||
function isStructureVisible() {
|
function isStructureVisible() {
|
||||||
const st = uiStore.getState();
|
const st = uiStore.getState();
|
||||||
@@ -329,6 +332,8 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const mountBridgeNotice = BridgeStatusNotice({});
|
||||||
|
|
||||||
const mountSection = CollapsibleSection({
|
const mountSection = CollapsibleSection({
|
||||||
collapsible: false,
|
collapsible: false,
|
||||||
icon: 'dock',
|
icon: 'dock',
|
||||||
@@ -362,6 +367,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
mountPreviewCanvas,
|
mountPreviewCanvas,
|
||||||
h('div', { className: 'settings-divider' }),
|
h('div', { className: 'settings-divider' }),
|
||||||
h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]),
|
h('div', { className: 'form-row' }, [mountModeLabelEl, windowMountSelect.el]),
|
||||||
|
mountBridgeNotice.el,
|
||||||
h('div', { className: 'form-row' }, [
|
h('div', { className: 'form-row' }, [
|
||||||
h('div', { className: 'settings-inline-row' }, [
|
h('div', { className: 'settings-inline-row' }, [
|
||||||
popoverWidthLabelEl,
|
popoverWidthLabelEl,
|
||||||
@@ -394,6 +400,11 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
modelValue: draftWindowMountMode,
|
modelValue: draftWindowMountMode,
|
||||||
options: getMountModeOptions(),
|
options: getMountModeOptions(),
|
||||||
});
|
});
|
||||||
|
mountBridgeNotice.refs.update({
|
||||||
|
visible: draftWindowMountMode !== 'sidebar',
|
||||||
|
windowBridge: latestWindowBridge,
|
||||||
|
hostPlatform: latestHostPlatform,
|
||||||
|
});
|
||||||
popoverWidthModeToggle.setProps({
|
popoverWidthModeToggle.setProps({
|
||||||
modelValue: draftPopoverWidthMode,
|
modelValue: draftPopoverWidthMode,
|
||||||
options: getPopoverWidthModeOptions(),
|
options: getPopoverWidthModeOptions(),
|
||||||
@@ -449,7 +460,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover',
|
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'hover',
|
||||||
initialModuleKeys: [],
|
initialModuleKeys: [],
|
||||||
});
|
});
|
||||||
const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [
|
const hoverPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [
|
||||||
hoverPreviewTipEl,
|
hoverPreviewTipEl,
|
||||||
hoverPreviewEmptyEl,
|
hoverPreviewEmptyEl,
|
||||||
]);
|
]);
|
||||||
@@ -541,7 +552,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'overview',
|
isVisibleFn: () => isStructureVisible() && activeThirdTab === 'overview',
|
||||||
initialModuleKeys: [],
|
initialModuleKeys: [],
|
||||||
});
|
});
|
||||||
const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas is-scaled' }, [
|
const overviewPreviewCanvas = h('div', { className: 'structure-preview-canvas' }, [
|
||||||
overviewPreviewContainerEl,
|
overviewPreviewContainerEl,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -800,7 +811,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
items: draftStepColumns,
|
items: draftStepColumns,
|
||||||
options: getStepColumnOptions(draftStepTokenComboFormat),
|
options: getStepColumnOptions(draftStepTokenComboFormat),
|
||||||
minItems: 2,
|
minItems: 2,
|
||||||
maxItems: 15,
|
maxItems: 14,
|
||||||
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
addBtnTextFn: (count, max) => t('settings.str.addStepCol', { count, max }),
|
||||||
onPreview: (previewItems) => {
|
onPreview: (previewItems) => {
|
||||||
draftStepColumns = normalizeClientStepColumns(previewItems);
|
draftStepColumns = normalizeClientStepColumns(previewItems);
|
||||||
@@ -983,9 +994,15 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
stepsSection.el,
|
stepsSection.el,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
function renderSettings(settings) {
|
function renderSettings(
|
||||||
|
settings,
|
||||||
|
windowBridge = latestWindowBridge,
|
||||||
|
hostPlatform = latestHostPlatform
|
||||||
|
) {
|
||||||
if (!settings) return;
|
if (!settings) return;
|
||||||
latestSettings = settings;
|
latestSettings = settings;
|
||||||
|
if (windowBridge !== undefined) latestWindowBridge = windowBridge;
|
||||||
|
if (hostPlatform) latestHostPlatform = hostPlatform;
|
||||||
draftWindowMountMode = normalizeClientWindowMountMode(
|
draftWindowMountMode = normalizeClientWindowMountMode(
|
||||||
settings.windowMountMode,
|
settings.windowMountMode,
|
||||||
settings.enableWindowOverlay
|
settings.enableWindowOverlay
|
||||||
@@ -1087,6 +1104,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
unsubUi();
|
unsubUi();
|
||||||
|
mountBridgeNotice.destroy();
|
||||||
capsulePreviewWidget.destroy();
|
capsulePreviewWidget.destroy();
|
||||||
hoverPreviewHost.destroy();
|
hoverPreviewHost.destroy();
|
||||||
overviewPreviewHost.destroy();
|
overviewPreviewHost.destroy();
|
||||||
@@ -1115,6 +1133,7 @@ export const SettingsStructureTab = defineComponent({
|
|||||||
refs: {
|
refs: {
|
||||||
thirdNavBar,
|
thirdNavBar,
|
||||||
capsulePreviewWidget,
|
capsulePreviewWidget,
|
||||||
|
mountBridgeNotice,
|
||||||
hoverPreviewHost,
|
hoverPreviewHost,
|
||||||
overviewPreviewHost,
|
overviewPreviewHost,
|
||||||
stepTablePreview,
|
stepTablePreview,
|
||||||
|
|||||||
+382
-177
File diff suppressed because it is too large
Load Diff
@@ -1,586 +0,0 @@
|
|||||||
import test from 'node:test';
|
|
||||||
import assert from 'node:assert/strict';
|
|
||||||
import fs from 'node:fs';
|
|
||||||
import vm from 'node:vm';
|
|
||||||
import { backendHarness } from './backend-harness.mjs';
|
|
||||||
import {
|
|
||||||
extractContextBreakdown,
|
|
||||||
extractModelSteps,
|
|
||||||
normalizeCachedStep,
|
|
||||||
} from '../speed-metrics.mjs';
|
|
||||||
import {
|
|
||||||
formatCountdown,
|
|
||||||
formatUsd,
|
|
||||||
speedReasonText,
|
|
||||||
} from '../src/core/formatters.js';
|
|
||||||
import { createReactiveStore } from '../src/core/reactive.js';
|
|
||||||
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
|
||||||
|
|
||||||
const nowMs = Date.now();
|
|
||||||
const nowIso = new Date(nowMs - 5_000).toISOString();
|
|
||||||
const doneIso = new Date(nowMs - 3_000).toISOString();
|
|
||||||
|
|
||||||
test('BUG-01 & INCON-01: Google-proxied Claude/GPT/o-series never misclassify as Gemini, and M429/M322/M149/M20 resolve accurately', () => {
|
|
||||||
const h = backendHarness({
|
|
||||||
userStatus: {
|
|
||||||
cascadeModelConfigData: {
|
|
||||||
clientModelConfigs: [
|
|
||||||
{
|
|
||||||
modelOrAlias: { model: 'MODEL_CLAUDE_PROXY' },
|
|
||||||
label: 'Claude Opus 4.6 (Google Vertex)',
|
|
||||||
quotaInfo: { remainingFraction: 0.75, resetTime: new Date(nowMs + 3600_000).toISOString() },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const infoClaude = h.resolveModelInfo('claude-opus-4-6', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
|
||||||
assert.equal(infoClaude.family, 'Claude');
|
|
||||||
const infoO3 = h.resolveModelInfo('o3-mini', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
|
||||||
assert.equal(infoO3.family, 'GPT');
|
|
||||||
|
|
||||||
// Calling resolveModelInfo with omitted dynamicModelMap must not throw (BUG-03)
|
|
||||||
const infoDefaultMap = h.resolveModelInfo('MODEL_PLACEHOLDER_M320');
|
|
||||||
assert.equal(infoDefaultMap.modelId, 'gemini-3.8-flash-low');
|
|
||||||
assert.equal(infoDefaultMap.pricing?.input, 0.3);
|
|
||||||
|
|
||||||
const m429 = h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
|
||||||
assert.equal(m429.modelId, 'gemini-4-carbon-high');
|
|
||||||
assert.equal(m429.shortName, 'carbon-4-high');
|
|
||||||
|
|
||||||
const m322 = h.resolveModelInfo('MODEL_PLACEHOLDER_M322', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
|
||||||
assert.equal(m322.modelId, 'gemini-3.8-flash-tiered');
|
|
||||||
assert.equal(
|
|
||||||
h.computeStepCost(
|
|
||||||
{
|
|
||||||
modelKey: 'MODEL_PLACEHOLDER_M322',
|
|
||||||
inputTokens: 1_000_000,
|
|
||||||
cacheReadTokens: 0,
|
|
||||||
outputTokens: 0,
|
|
||||||
},
|
|
||||||
m322.pricing
|
|
||||||
),
|
|
||||||
0.75
|
|
||||||
);
|
|
||||||
|
|
||||||
const m149 = h.resolveModelInfo('MODEL_PLACEHOLDER_M149', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
|
||||||
assert.equal(m149.modelId, 'gemini-3.5-flash-high');
|
|
||||||
|
|
||||||
const m20 = h.resolveModelInfo('MODEL_PLACEHOLDER_M20', new Map(), 'API_PROVIDER_GOOGLE_GEMINI');
|
|
||||||
assert.equal(m20.modelId, 'gemini-3.5-flash');
|
|
||||||
|
|
||||||
// Gemini Hydrogen ($1.50/$0.075/$7.50) & Helix ($0.30/$0.015/$2.50), shared Gemini pool
|
|
||||||
const dynHydrogenMap = new Map([
|
|
||||||
['MODEL_PLACEHOLDER_M480', { modelId: '', label: 'Gemini 4 Hydrogen (High)' }],
|
|
||||||
['MODEL_PLACEHOLDER_M481', { modelId: '', label: 'Gemini 4 Hydrogen (Low)' }],
|
|
||||||
['MODEL_PLACEHOLDER_M482', { modelId: '', label: 'Gemini 4 Helix' }],
|
|
||||||
]);
|
|
||||||
const hydroHigh = h.resolveModelInfo('MODEL_PLACEHOLDER_M480', dynHydrogenMap);
|
|
||||||
assert.equal(hydroHigh.family, 'Gemini');
|
|
||||||
assert.equal(hydroHigh.shortName, 'hydrogen-4-high');
|
|
||||||
assert.deepEqual(
|
|
||||||
{ i: hydroHigh.pricing?.input, c: hydroHigh.pricing?.cache, o: hydroHigh.pricing?.output },
|
|
||||||
{ i: 1.5, c: 0.075, o: 7.5 }
|
|
||||||
);
|
|
||||||
const hydroLow = h.resolveModelInfo('MODEL_PLACEHOLDER_M481', dynHydrogenMap);
|
|
||||||
assert.equal(hydroLow.shortName, 'hydrogen-4-low');
|
|
||||||
assert.deepEqual(
|
|
||||||
{ i: hydroLow.pricing?.input, c: hydroLow.pricing?.cache, o: hydroLow.pricing?.output },
|
|
||||||
{ i: 1.5, c: 0.075, o: 7.5 }
|
|
||||||
);
|
|
||||||
const hydroCodename = h.resolveModelInfo('gemini-hydrogen');
|
|
||||||
assert.equal(hydroCodename.family, 'Gemini');
|
|
||||||
assert.equal(hydroCodename.label, 'Gemini Hydrogen');
|
|
||||||
assert.equal(hydroCodename.pricing?.input, 1.5);
|
|
||||||
assert.equal(hydroCodename.pricing?.output, 7.5);
|
|
||||||
|
|
||||||
const helixInfo = h.resolveModelInfo('MODEL_PLACEHOLDER_M482', dynHydrogenMap);
|
|
||||||
assert.equal(helixInfo.family, 'Gemini');
|
|
||||||
assert.equal(helixInfo.shortName, 'helix-4');
|
|
||||||
assert.deepEqual(
|
|
||||||
{ i: helixInfo.pricing?.input, c: helixInfo.pricing?.cache, o: helixInfo.pricing?.output },
|
|
||||||
{ i: 0.3, c: 0.015, o: 2.5 }
|
|
||||||
);
|
|
||||||
const helixCodename = h.resolveModelInfo('gemini-helix');
|
|
||||||
assert.equal(helixCodename.family, 'Gemini');
|
|
||||||
assert.equal(helixCodename.label, 'Gemini Helix');
|
|
||||||
assert.equal(helixCodename.pricing?.output, 2.5);
|
|
||||||
|
|
||||||
const { quotaPoolsMap } = h.buildOfficialQuotaPools(null, [
|
|
||||||
{
|
|
||||||
modelOrAlias: { model: 'MODEL_PLACEHOLDER_M480' },
|
|
||||||
label: 'Gemini 4 Hydrogen (High)',
|
|
||||||
quotaInfo: { remainingFraction: 0.8, resetTime: new Date(nowMs + 3600_000).toISOString() },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
modelOrAlias: { model: 'MODEL_PLACEHOLDER_M482' },
|
|
||||||
label: 'Gemini 4 Helix',
|
|
||||||
quotaInfo: { remainingFraction: 0.8, resetTime: new Date(nowMs + 3600_000).toISOString() },
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
assert.equal(quotaPoolsMap.has('Hydrogen'), false, 'Hydrogen has no dedicated quota pool');
|
|
||||||
assert.equal(quotaPoolsMap.has('Helix'), false, 'Helix has no dedicated quota pool');
|
|
||||||
assert.equal(quotaPoolsMap.get('Gemini')?.isAvailable, true);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('BUG-02 & BUG-11: ide:<uuid> external sessions do not double-count live conversations, cross-account entries are isolated, and orphan subagents never leak to top-level list', async () => {
|
|
||||||
const stepObj = {
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
|
||||||
createdAt: nowIso,
|
|
||||||
completedAt: doneIso,
|
|
||||||
modelUsage: {
|
|
||||||
model: 'MODEL_PLACEHOLDER_M318',
|
|
||||||
inputTokens: '10000',
|
|
||||||
cacheReadTokens: '20000',
|
|
||||||
outputTokens: '5000',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const h = backendHarness({
|
|
||||||
userStatus: { email: 'alice@example.com' },
|
|
||||||
deepStats: {
|
|
||||||
accountName: 'alice@example.com',
|
|
||||||
perConvo: {
|
|
||||||
// Same conversation ID as live 'abcd-1234' (case-insensitive, prefixed with 'ide:') -> must deduplicate!
|
|
||||||
'ide:AbCd-1234': {
|
|
||||||
accountName: 'alice@example.com',
|
|
||||||
appSource: 'ide',
|
|
||||||
entries: [
|
|
||||||
{ ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 },
|
|
||||||
{ ts: doneIso, model: 'MODEL_PLACEHOLDER_M318', inp: 10000, cache: 20000, out: 5000, reasoning: 0 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
// Different account -> must be excluded when logged in as alice@example.com!
|
|
||||||
'ide:bob-conv': {
|
|
||||||
accountName: 'bob@example.com',
|
|
||||||
appSource: 'ide',
|
|
||||||
entries: [
|
|
||||||
{ ts: nowIso, model: 'MODEL_PLACEHOLDER_M318', inp: 99000, cache: 0, out: 1000, reasoning: 0 },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
cache: {
|
|
||||||
'orphan-sub': {
|
|
||||||
accountName: 'bob@example.com',
|
|
||||||
isSubagent: true,
|
|
||||||
parentCascadeId: 'deleted-parent',
|
|
||||||
signature: 'v10-model-identity:sub',
|
|
||||||
steps: extractModelSteps([stepObj]),
|
|
||||||
},
|
|
||||||
},
|
|
||||||
summaries: {
|
|
||||||
'abcd-1234': { stepCount: 1, lastModifiedTime: doneIso, status: 'IDLE' },
|
|
||||||
},
|
|
||||||
trajectories: {
|
|
||||||
'abcd-1234': { trajectory: { steps: [stepObj] } },
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const p = await h.buildTelemetryPayloadInternal('abcd-1234', false, { range: 'all' });
|
|
||||||
// ide:AbCd-1234 has 2 entries vs live abcd-1234's 1 step -> deduplicated (no 1 + 2 = 3 double counting!), bob excluded!
|
|
||||||
assert.equal(p.consumption.account.conversationsCount, 1);
|
|
||||||
assert.equal(p.consumption.account.calls, 2);
|
|
||||||
assert.equal(p.consumption.account.totalTokens, 70_000);
|
|
||||||
assert.equal(
|
|
||||||
p.conversations.some((c) => c.cascadeId === 'orphan-sub'),
|
|
||||||
false,
|
|
||||||
'orphan subagent must not appear in top-level conversation dropdown'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('BUG-03, BUG-12 & BUG-16: negative/NaN token sanitization, deferred costUsd rounding, and dynamicModelMap default', async () => {
|
|
||||||
const badStep = {
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
|
||||||
createdAt: nowIso,
|
|
||||||
completedAt: doneIso,
|
|
||||||
modelUsage: {
|
|
||||||
model: 'MODEL_PLACEHOLDER_M318',
|
|
||||||
inputTokens: '-5000',
|
|
||||||
cacheReadTokens: 'NaN',
|
|
||||||
outputTokens: '1000',
|
|
||||||
thinkingOutputTokens: '2500',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
const extracted = extractModelSteps([badStep]);
|
|
||||||
assert.equal(extracted[0].inputTokens, 0);
|
|
||||||
assert.equal(extracted[0].cacheReadTokens, 0);
|
|
||||||
assert.equal(extracted[0].outputTokens, 1000);
|
|
||||||
assert.equal(extracted[0].thinkingTokens, 1000);
|
|
||||||
assert.equal(extracted[0].responseTokens, 0);
|
|
||||||
assert.equal(normalizeCachedStep({ ...extracted[0], inputTokens: -99 }).inputTokens, 0);
|
|
||||||
assert.equal(normalizeCachedStep(null), null);
|
|
||||||
|
|
||||||
// Micro-steps: 100 steps * (1067 output * $3.75 / 1M = $0.00400125) = $0.40 (previously rounded per-step to $0.00 -> $0.00!)
|
|
||||||
const microSteps = Array.from({ length: 100 }, (_, idx) => ({
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
sourceTrajectoryStepInfo: { stepIndex: idx + 1 },
|
|
||||||
createdAt: nowIso,
|
|
||||||
completedAt: doneIso,
|
|
||||||
modelUsage: {
|
|
||||||
model: 'MODEL_PLACEHOLDER_M318', // gemini-3.8-flash-high: $0.75/1M input, $3.75/1M output
|
|
||||||
inputTokens: '0',
|
|
||||||
cacheReadTokens: '0',
|
|
||||||
outputTokens: '1067',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}));
|
|
||||||
const h = backendHarness({
|
|
||||||
summaries: { micro: { stepCount: 100, lastModifiedTime: doneIso, status: 'IDLE' } },
|
|
||||||
trajectories: { micro: { trajectory: { steps: microSteps } } },
|
|
||||||
});
|
|
||||||
const p = await h.buildTelemetryPayloadInternal('micro', false, { range: 'today' });
|
|
||||||
assert.equal(p.consumption.account.costUsd, 0.4);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('BUG-04 & BUG-10: failed RUNNING trajectory fetch enters cooldown instead of hammering RPC every poll, cleared by forceRefresh', async () => {
|
|
||||||
const h = backendHarness({
|
|
||||||
summaries: { run1: { stepCount: 2, lastModifiedTime: doneIso, status: 'CASCADE_RUN_STATUS_RUNNING' } },
|
|
||||||
trajectories: { run1: new Error('LS timeout') },
|
|
||||||
quotaSummary: new Error('Quota RPC down'),
|
|
||||||
});
|
|
||||||
|
|
||||||
await h.buildTelemetryPayloadInternal('run1', false);
|
|
||||||
const callsAfterFirst = h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length;
|
|
||||||
const quotaCallsAfterFirst = h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length;
|
|
||||||
assert.equal(callsAfterFirst, 1);
|
|
||||||
assert.equal(quotaCallsAfterFirst, 1);
|
|
||||||
|
|
||||||
// Immediate second background poll must respect cooldown for both trajectory and quota RPC
|
|
||||||
await h.buildTelemetryPayloadInternal('run1', false);
|
|
||||||
assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 1);
|
|
||||||
assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 1);
|
|
||||||
|
|
||||||
// Manual forceRefresh=true bypasses cooldown immediately
|
|
||||||
await h.buildTelemetryPayloadInternal('run1', true);
|
|
||||||
assert.equal(h.state.calls.filter((c) => c.method === 'GetCascadeTrajectory').length, 2);
|
|
||||||
assert.equal(h.state.calls.filter((c) => c.method === 'RetrieveUserQuotaSummary').length, 2);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('BUG-09, BUG-14 & BUG-15: SemVer 2.0 prerelease/build ordering, future-only exhausted quota inference, and <6h dual-bucket classification', async () => {
|
|
||||||
const h = backendHarness({
|
|
||||||
quotaSummary: {
|
|
||||||
groups: [
|
|
||||||
{
|
|
||||||
displayName: 'Gemini',
|
|
||||||
buckets: [
|
|
||||||
{
|
|
||||||
// Omitted remainingFraction with epoch-0 resetTime must NOT falsely report 0% remaining!
|
|
||||||
resetTime: '1970-01-01T00:00:00Z',
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
displayName: 'Claude & GPT',
|
|
||||||
buckets: [
|
|
||||||
{
|
|
||||||
remainingFraction: 0.4,
|
|
||||||
resetTime: new Date(nowMs + 2 * 3600_000).toISOString(),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
remainingFraction: 0.8,
|
|
||||||
// Weekly bucket that happens to be 4h away from resetting!
|
|
||||||
resetTime: new Date(nowMs + 4 * 3600_000).toISOString(),
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
assert.equal(h.compareSemver('1.4.2+20261110', '1.4.2'), 0);
|
|
||||||
assert.equal(h.compareSemver('1.5.0-beta.2', '1.5.0-alpha.10'), 1);
|
|
||||||
assert.equal(h.compareSemver('1.5.0-alpha.1', '1.5.0-alpha.beta'), -1);
|
|
||||||
|
|
||||||
const p = await h.buildTelemetryPayloadInternal('');
|
|
||||||
const geminiPool = p.quotas.pools.find((x) => x.poolKey === 'Gemini');
|
|
||||||
assert.ok(geminiPool);
|
|
||||||
assert.equal(geminiPool.isAvailable, false, 'epoch-0 omitted remainingFraction must not create fake 0% exhausted pool');
|
|
||||||
assert.equal(geminiPool.remainingPct, null);
|
|
||||||
assert.equal(geminiPool.usedPct, null);
|
|
||||||
|
|
||||||
const claudePool = p.quotas.pools.find((x) => x.poolKey === 'Claude & GPT');
|
|
||||||
assert.ok(claudePool);
|
|
||||||
assert.equal(claudePool.remainingPct, 40);
|
|
||||||
assert.equal(claudePool.weeklyRemainingPct, 80);
|
|
||||||
|
|
||||||
assert.equal(formatCountdown(new Date(nowMs + 30_000).toISOString(), nowMs), '<1分钟后重置');
|
|
||||||
assert.equal(formatCountdown('1969-12-31T23:59:59Z', nowMs), '未知重置时间');
|
|
||||||
assert.equal(formatUsd(0.0004, { precise: true }), '<$0.001');
|
|
||||||
assert.equal(formatUsd(12.34, { unpricedCalls: 1, compactPending: true }), '$12.34');
|
|
||||||
assert.equal(speedReasonText('short_timing'), '耗时过短 (<0.5s)');
|
|
||||||
});
|
|
||||||
|
|
||||||
test('BUG-17 & CANCEL-06: extractContextBreakdown classifies messagePrompts when children are empty and blocks post-compaction carryover', () => {
|
|
||||||
const ctx = extractContextBreakdown({
|
|
||||||
chatStartMetadata: {
|
|
||||||
contextWindowMetadata: {
|
|
||||||
estimatedTokensUsed: 10000,
|
|
||||||
tokenBreakdown: {
|
|
||||||
groups: [
|
|
||||||
{ type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 2000 },
|
|
||||||
{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 8000, children: [] },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
messagePrompts: [
|
|
||||||
{ source: 'CHAT_MESSAGE_SOURCE_USER', prompt: '<USER_REQUEST>hello world</USER_REQUEST>' },
|
|
||||||
{ source: 'CHAT_MESSAGE_SOURCE_MODEL', prompt: 'Assistant reply content here!' },
|
|
||||||
],
|
|
||||||
});
|
|
||||||
assert.ok(ctx);
|
|
||||||
assert.equal(ctx.systemPromptTokens, 2000);
|
|
||||||
assert.ok(ctx.userInputTokens > 0);
|
|
||||||
assert.ok(ctx.assistantTokens > 0);
|
|
||||||
assert.equal(ctx.userInputTokens + ctx.assistantTokens, 8000);
|
|
||||||
|
|
||||||
const stepsWithTrailingCheckpoint = extractModelSteps(
|
|
||||||
[
|
|
||||||
{
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
|
||||||
createdAt: nowIso,
|
|
||||||
completedAt: doneIso,
|
|
||||||
modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '500' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
sourceTrajectoryStepInfo: { stepIndex: 2 },
|
|
||||||
createdAt: nowIso,
|
|
||||||
completedAt: doneIso,
|
|
||||||
modelUsage: { model: 'MODEL_PLACEHOLDER_M318', inputTokens: '180000', outputTokens: '1200' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
[
|
|
||||||
{
|
|
||||||
stepIndices: [1],
|
|
||||||
chatModel: {
|
|
||||||
chatStartMetadata: {
|
|
||||||
contextWindowMetadata: {
|
|
||||||
estimatedTokensUsed: 180_000,
|
|
||||||
tokenBreakdown: {
|
|
||||||
groups: [{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 180_000 }],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]
|
|
||||||
);
|
|
||||||
assert.equal(stepsWithTrailingCheckpoint.length, 2);
|
|
||||||
assert.equal(stepsWithTrailingCheckpoint[1].isCompactionStep, true);
|
|
||||||
assert.equal(
|
|
||||||
stepsWithTrailingCheckpoint[1].contextBreakdown,
|
|
||||||
null,
|
|
||||||
'compaction checkpoint must not inherit pre-compaction 180k contextBreakdown'
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax safety, and IIFE bundle isolation', async () => {
|
|
||||||
const store = createReactiveStore({ a: 1, b: 2 });
|
|
||||||
let calls = 0;
|
|
||||||
store.subscribe((s) => s.a + s.b, () => {
|
|
||||||
calls += 1;
|
|
||||||
}, { immediate: false });
|
|
||||||
|
|
||||||
store.setState({ a: 10 });
|
|
||||||
store.setState({ b: 20 });
|
|
||||||
await new Promise((r) => queueMicrotask(r));
|
|
||||||
assert.equal(calls, 1, 'multiple setState calls in same microtask must batch into 1 subscriber flush');
|
|
||||||
|
|
||||||
const trickyModule = [
|
|
||||||
"import './side-effect.js';",
|
|
||||||
"import { foo,\n bar } from './multi.js';",
|
|
||||||
'const tpl = `\nimport { keepMe } from "tpl";\nexport const KEEP_ME = 42;\n`;',
|
|
||||||
'export async function runTask() { return tpl; }',
|
|
||||||
'export { runTask };',
|
|
||||||
].join('\n');
|
|
||||||
|
|
||||||
const stripped = stripModuleSyntax(trickyModule);
|
|
||||||
assert.ok(stripped.includes('import { keepMe } from "tpl"'));
|
|
||||||
assert.ok(stripped.includes('export const KEEP_ME = 42'));
|
|
||||||
assert.equal(/^\s*import\s/m.test(stripped.replace(/`[\s\S]*?`/g, '')), false);
|
|
||||||
assert.doesNotThrow(() => new vm.Script(stripped));
|
|
||||||
|
|
||||||
const appBundle = fs.readFileSync(new URL('../app.js', import.meta.url), 'utf8');
|
|
||||||
assert.ok(appBundle.startsWith('(() => {\n\'use strict\';'));
|
|
||||||
assert.ok(appBundle.trimEnd().endsWith('})();'));
|
|
||||||
});
|
|
||||||
|
|
||||||
test('Compaction liveActivity: detects in-progress & completed CHECKPOINT over pre-compaction tool operations across RPC and transcript.jsonl', async () => {
|
|
||||||
const convId = '4432b724-3e1e-4421-a375-c6855a7b7b37';
|
|
||||||
|
|
||||||
// Pre-compaction steps (matching real-world step 0..2: planner edit_file x2 + 2 completed tool results)
|
|
||||||
const rpcPreCompactionSteps = [
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
createdAt: '2026-11-11T02:18:21Z',
|
|
||||||
finishedGeneratingAt: '2026-11-11T02:18:35Z',
|
|
||||||
modelUsage: {
|
|
||||||
model: 'MODEL_PLACEHOLDER_M318',
|
|
||||||
inputTokens: '2918',
|
|
||||||
cacheReadTokens: '252465',
|
|
||||||
outputTokens: '814',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
plannerResponse: {
|
|
||||||
toolCalls: [
|
|
||||||
{ name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/backend-harness.mjs' }) },
|
|
||||||
{ name: 'edit_file', argumentsJson: JSON.stringify({ Path: 'f:/repo/04-post-fix-verify.mjs' }) },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_CODE_ACTION',
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:38Z' },
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_CODE_ACTION',
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: { createdAt: '2026-11-11T02:18:35Z', completedAt: '2026-11-11T02:18:40Z' },
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// transcript.jsonl still ends at step_index 2 (since CHECKPOINT only flushes to transcript.jsonl when DONE)
|
|
||||||
const transcriptPreFlush = [
|
|
||||||
{
|
|
||||||
step_index: 0,
|
|
||||||
source: 'MODEL',
|
|
||||||
type: 'PLANNER_RESPONSE',
|
|
||||||
status: 'DONE',
|
|
||||||
created_at: '2026-11-11T02:18:21Z',
|
|
||||||
tool_calls: [
|
|
||||||
{ name: 'edit_file', args: { Path: '"f:\\\\repo\\\\backend-harness.mjs"' } },
|
|
||||||
{ name: 'edit_file', args: { Path: '"f:\\\\repo\\\\04-post-fix-verify.mjs"' } },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
step_index: 1,
|
|
||||||
source: 'MODEL',
|
|
||||||
type: 'GENERIC',
|
|
||||||
status: 'DONE',
|
|
||||||
created_at: '2026-11-11T02:18:35Z',
|
|
||||||
content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:38+09:00\nMade 1 replacement',
|
|
||||||
},
|
|
||||||
{
|
|
||||||
step_index: 2,
|
|
||||||
source: 'MODEL',
|
|
||||||
type: 'GENERIC',
|
|
||||||
status: 'DONE',
|
|
||||||
created_at: '2026-11-11T02:18:35Z',
|
|
||||||
content: 'Created At: 2026-11-11T11:18:35+09:00\nCompleted At: 2026-11-11T11:18:40+09:00\nMade 1 replacement',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
// Phase 1: In-progress CORTEX_STEP_TYPE_CHECKPOINT in RPC WITHOUT metadata.createdAt yet + trailing MEMENTO
|
|
||||||
const h = backendHarness({
|
|
||||||
summaries: {
|
|
||||||
[convId]: {
|
|
||||||
stepCount: 4,
|
|
||||||
lastModifiedTime: '2026-11-11T02:18:35Z',
|
|
||||||
status: 'CASCADE_RUN_STATUS_RUNNING',
|
|
||||||
annotations: { title: 'Audit & Fix Session' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
trajectories: {
|
|
||||||
[convId]: {
|
|
||||||
trajectory: {
|
|
||||||
steps: [
|
|
||||||
...rpcPreCompactionSteps,
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
|
||||||
status: 'CORTEX_STEP_STATUS_RUNNING',
|
|
||||||
metadata: {},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_MEMENTO',
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: { createdAt: '2026-11-11T02:18:40Z' },
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
transcripts: {
|
|
||||||
[convId]: transcriptPreFlush,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const pCompacting = await h.buildTelemetryPayloadInternal(convId);
|
|
||||||
assert.equal(pCompacting.activeConversation.liveActivity.phase, 'compacting');
|
|
||||||
assert.equal(pCompacting.activeConversation.liveActivity.label, '上下文压缩');
|
|
||||||
assert.equal(
|
|
||||||
pCompacting.activeConversation.liveActivity.startedAtMs,
|
|
||||||
Date.parse('2026-11-11T02:18:40Z'),
|
|
||||||
'uses previous tool completion timestamp when in-progress CHECKPOINT lacks createdAt'
|
|
||||||
);
|
|
||||||
assert.equal(pCompacting.runningConversations[0].mainActivity.phase, 'compacting');
|
|
||||||
assert.equal(pCompacting.runningConversations[0].mainActivity.label, '上下文压缩');
|
|
||||||
|
|
||||||
// Phase 2: CHECKPOINT finishes (status=DONE in both RPC & transcript.jsonl) while resuming before next PLANNER_RESPONSE
|
|
||||||
h.state.trajectories[convId] = {
|
|
||||||
trajectory: {
|
|
||||||
steps: [
|
|
||||||
...rpcPreCompactionSteps,
|
|
||||||
{
|
|
||||||
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
|
||||||
status: 'CORTEX_STEP_STATUS_DONE',
|
|
||||||
metadata: {
|
|
||||||
createdAt: '2026-11-11T02:18:40Z',
|
|
||||||
finishedGeneratingAt: '2026-11-11T02:19:33Z',
|
|
||||||
modelUsage: {
|
|
||||||
model: 'MODEL_PLACEHOLDER_M318',
|
|
||||||
inputTokens: '3082',
|
|
||||||
cacheReadTokens: '254224',
|
|
||||||
outputTokens: '4627',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
};
|
|
||||||
h.state.transcripts[convId] = [
|
|
||||||
...transcriptPreFlush,
|
|
||||||
{
|
|
||||||
step_index: 3,
|
|
||||||
source: 'SYSTEM',
|
|
||||||
type: 'CHECKPOINT',
|
|
||||||
status: 'DONE',
|
|
||||||
created_at: '2026-11-11T02:18:40Z',
|
|
||||||
content: '# Resuming from a compaction\n...',
|
|
||||||
},
|
|
||||||
];
|
|
||||||
h.state.transcriptMtimeMs = 2;
|
|
||||||
|
|
||||||
const pResuming = await h.buildTelemetryPayloadInternal(convId);
|
|
||||||
assert.equal(pResuming.activeConversation.liveActivity.phase, 'compacting');
|
|
||||||
assert.equal(pResuming.activeConversation.liveActivity.label, '上下文压缩');
|
|
||||||
assert.equal(pResuming.activeConversation.liveActivity.detail, '已完成压缩,正在恢复推理');
|
|
||||||
assert.equal(
|
|
||||||
pResuming.activeConversation.liveActivity.startedAtMs,
|
|
||||||
Date.parse('2026-11-11T02:19:33Z')
|
|
||||||
);
|
|
||||||
|
|
||||||
// Phase 3: Even when RPC fails/cools down and ONLY transcript.jsonl (with status="DONE" CHECKPOINT) is available,
|
|
||||||
// it STILL detects compaction instead of regressing to pre-compaction "修改文件"
|
|
||||||
h.state.trajectories[convId] = new Error('temporary RPC timeout');
|
|
||||||
const pTranscriptOnly = await h.buildTelemetryPayloadInternal(convId, true);
|
|
||||||
assert.equal(pTranscriptOnly.activeConversation.liveActivity.phase, 'compacting');
|
|
||||||
assert.equal(pTranscriptOnly.activeConversation.liveActivity.label, '上下文压缩');
|
|
||||||
});
|
|
||||||
@@ -4,7 +4,7 @@ import { pathToFileURL } from 'node:url';
|
|||||||
import vm from 'node:vm';
|
import vm from 'node:vm';
|
||||||
import { randomUUID } from 'node:crypto';
|
import { randomUUID } from 'node:crypto';
|
||||||
import { isDeepStrictEqual } from 'node:util';
|
import { isDeepStrictEqual } from 'node:util';
|
||||||
import * as metrics from '../speed-metrics.mjs';
|
import * as metrics from '../trajectory-metrics.mjs';
|
||||||
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
import { stripModuleSyntax } from '../scripts/build-bundle.mjs';
|
||||||
|
|
||||||
const REAL_CATALOG_RAW = JSON.parse(
|
const REAL_CATALOG_RAW = JSON.parse(
|
||||||
@@ -17,11 +17,17 @@ const DEFAULT_BUNDLED_CATALOG = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const BACKEND_MODULE_FILES = [
|
const BACKEND_MODULE_FILES = [
|
||||||
|
'../shared/settings-normalization.mjs',
|
||||||
|
'../shared/telemetry-display-rules.mjs',
|
||||||
|
'../shared/window-bridge-protocol.mjs',
|
||||||
'../backend/context-windows.mjs',
|
'../backend/context-windows.mjs',
|
||||||
'../backend/account-oauth.mjs',
|
'../backend/account-oauth.mjs',
|
||||||
'../backend/account-switch.mjs',
|
'../backend/account-switch.mjs',
|
||||||
|
'../backend/http-helpers.mjs',
|
||||||
'../backend/settings-schema.mjs',
|
'../backend/settings-schema.mjs',
|
||||||
'../backend/config.mjs',
|
'../backend/config.mjs',
|
||||||
|
'../backend/sqlite-client.mjs',
|
||||||
|
'../backend/proto-wire.mjs',
|
||||||
'../backend/cli-sqlite-reader.mjs',
|
'../backend/cli-sqlite-reader.mjs',
|
||||||
'../backend/cli-statusline-config.mjs',
|
'../backend/cli-statusline-config.mjs',
|
||||||
'../backend/ls-discovery.mjs',
|
'../backend/ls-discovery.mjs',
|
||||||
@@ -33,6 +39,7 @@ const BACKEND_MODULE_FILES = [
|
|||||||
'../backend/local-scanner.mjs',
|
'../backend/local-scanner.mjs',
|
||||||
'../backend/usage-aggregator.mjs',
|
'../backend/usage-aggregator.mjs',
|
||||||
'../backend/telemetry-builder.mjs',
|
'../backend/telemetry-builder.mjs',
|
||||||
|
'../backend/desktop-launcher-config.mjs',
|
||||||
'../backend/window-bridge.mjs',
|
'../backend/window-bridge.mjs',
|
||||||
'../backend/api-actions.mjs',
|
'../backend/api-actions.mjs',
|
||||||
'../main.mjs',
|
'../main.mjs',
|
||||||
@@ -63,19 +70,21 @@ export function backendHarness({
|
|||||||
remoteCatalog=null,
|
remoteCatalog=null,
|
||||||
pluginManifest=null,
|
pluginManifest=null,
|
||||||
hasGitDir=false,
|
hasGitDir=false,
|
||||||
|
gitConfigText=null,
|
||||||
pluginRootPath=null,
|
pluginRootPath=null,
|
||||||
remoteFetch=null,
|
remoteFetch=null,
|
||||||
execFileImpl=null,
|
execFileImpl=null,
|
||||||
sourceText=null,
|
sourceText=null,
|
||||||
clock=null,
|
clock=null,
|
||||||
|
timerApi={ setTimeout, clearTimeout },
|
||||||
metricsImplementation=metrics,
|
metricsImplementation=metrics,
|
||||||
}={}) {
|
}={}) {
|
||||||
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
const mainUrl = pluginRootPath ? `file://${pluginRootPath}/sidecars/panel/main.mjs` : 'file:///test/sidecars/panel/main.mjs';
|
||||||
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
const mainPath = pluginRootPath ? `${pluginRootPath}/sidecars/panel/main.mjs` : '/test/sidecars/panel/main.mjs';
|
||||||
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
const source = stripEsmSyntax(sourceText ?? loadCombinedBackendSource(), mainUrl);
|
||||||
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,deepStats,deepStatsMtimeMs:1};
|
const state={calls:[],errors:[],saves:[],settings,trajectories,summaries,transcripts,transcriptMtimeMs:1,userStatus,quotaSummary,localCatalog,remoteCatalog,pluginManifest,hasGitDir,gitConfigText,deepStats,deepStatsMtimeMs:1};
|
||||||
const ctx={
|
const ctx={
|
||||||
...metricsImplementation, URL, AbortSignal, Buffer, isDeepStrictEqual, randomUUID,
|
...metricsImplementation, URL, AbortSignal, Buffer, TextDecoder, ...timerApi, isDeepStrictEqual, randomUUID,
|
||||||
...(clock ? { Date: class extends Date {
|
...(clock ? { Date: class extends Date {
|
||||||
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
constructor(...args) { super(...(args.length ? args : [clock()])); }
|
||||||
static now() { return clock(); }
|
static now() { return clock(); }
|
||||||
@@ -101,7 +110,8 @@ export function backendHarness({
|
|||||||
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
const m = norm.match(/\/brain\/([^/]+)\/\.system_generated\/logs\/transcript\.jsonl$/i);
|
||||||
return Boolean(m && state.transcripts?.[m[1]]);
|
return Boolean(m && state.transcripts?.[m[1]]);
|
||||||
}
|
}
|
||||||
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir);
|
if (norm.endsWith('/.git')) return Boolean(state.hasGitDir || state.gitConfigText);
|
||||||
|
if (norm.endsWith('/.git/config')) return Boolean(state.gitConfigText);
|
||||||
if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true;
|
if (diskDirs && Object.prototype.hasOwnProperty.call(diskDirs, norm)) return true;
|
||||||
return false;
|
return false;
|
||||||
},
|
},
|
||||||
@@ -138,6 +148,7 @@ export function backendHarness({
|
|||||||
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
if (norm.endsWith('pricing-catalog.json')) return JSON.stringify(state.localCatalog);
|
||||||
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
if (norm.endsWith('remote_pricing_cache.json')) return JSON.stringify(state.remoteCatalog);
|
||||||
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
if (norm.endsWith('plugin.json')) return JSON.stringify(state.pluginManifest);
|
||||||
|
if (norm.endsWith('/.git/config')) return String(state.gitConfigText || '');
|
||||||
return JSON.stringify(cache);
|
return JSON.stringify(cache);
|
||||||
},
|
},
|
||||||
writeFileSync:(p,s)=>{
|
writeFileSync:(p,s)=>{
|
||||||
@@ -152,6 +163,7 @@ export function backendHarness({
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
writeTrajectoryCacheFile:(p,data)=>{
|
writeTrajectoryCacheFile:(p,data)=>{
|
||||||
|
if (state.cacheWriteError) throw state.cacheWriteError;
|
||||||
state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))});
|
state.saves.push({path:p,data:JSON.parse(JSON.stringify(data))});
|
||||||
},
|
},
|
||||||
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,delimiter:path.delimiter,pathToFileURL,fileURLToPath:()=>mainPath,
|
homedir:()=>'/test-home',dirname:path.dirname,join:path.join,basename:path.basename,delimiter:path.delimiter,pathToFileURL,fileURLToPath:()=>mainPath,
|
||||||
@@ -176,6 +188,6 @@ export function backendHarness({
|
|||||||
return {ok:true,json:async()=>data};
|
return {ok:true,json:async()=>data};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
vm.runInNewContext(source+'\n globalThis.api={buildTelemetryPayloadInternal,executeTelemetryAction,computeStepCost,resolveModelInfo,resolvePricingAt,inferFamilyFromProviderOrKey,isArgonModelIdentifier,isCarbonModelIdentifier,getBaseModelLabel,formatUpstreamModelId,PLACEHOLDER_MAP,normalizeQuotaFraction,classifyOfficialBucketWindow,classifyQuotaPoolIdentity,buildOfficialQuotaPools,resolveTimeWindow,sanitizeCatalogPayload,rebuildActiveCatalog,getPricingPhaseEpoch,detectCustomGitForkRepo,persistTrajectoryCacheIfNeeded,flushTrajectoryCacheNow,getCachedTrajectory,listCachedTrajectoryEntries,hasPendingTrajectoryCacheSave,syncCloudCatalog,getCloudStatus,isValidSemver,compareSemver,performPluginUpdate,resolveMigratedGitRemoteUrl,loadSettings,executeSettingsAction,executeModelContextWindowAction,executeResetSettingsAction,executeRebuildCacheAction,clearRuntimeCaches,normalizeTopbarCapsuleSlots,normalizeHoverModules,normalizeOverviewModules,normalizeOverviewMetrics,normalizeStepTableColumns,normalizeStepTokenComboFormat,parseStepTokenComboSegments,normalizeModelDisplayMode,normalizePopoverWidthMode,normalizePopoverWidth,normalizeStandalonePort,setStandalonePortListener,parseAnnotationPbtxtTitle,readLocalSummarySnapshot,readLocalSqliteTrajectory,computeSqliteWalSig,buildCliStatusSnapshot,buildCliStatusLineCommand,isManagedCliStatusLineCommand,applyCliStatusLineToSettingsObject,cliDisplayWidth,parseCliModelAndEffort,formatCliStatusLineCapsule};',ctx);
|
||||||
return {...ctx.api,state};
|
return {...ctx.api,state};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -666,7 +666,7 @@ test('cached incomplete timing is refreshed once without invalidating completed
|
|||||||
...structuredClone(raw.trajectory.steps[0]),
|
...structuredClone(raw.trajectory.steps[0]),
|
||||||
status: 'CORTEX_STEP_STATUS_CLEARED',
|
status: 'CORTEX_STEP_STATUS_CLEARED',
|
||||||
};
|
};
|
||||||
const { extractModelSteps } = await import('../speed-metrics.mjs');
|
const { extractModelSteps } = await import('../trajectory-metrics.mjs');
|
||||||
const [completed] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
const [completed] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
||||||
const [incomplete] = extractModelSteps([{ ...incompleteStep, status: 'CORTEX_STEP_STATUS_GENERATING' }]);
|
const [incomplete] = extractModelSteps([{ ...incompleteStep, status: 'CORTEX_STEP_STATUS_GENERATING' }]);
|
||||||
const cacheEntry = (step) => ({
|
const cacheEntry = (step) => ({
|
||||||
@@ -743,6 +743,39 @@ test('display step revisions omit only matching rows and invalidate on timing ch
|
|||||||
assert.equal((await get()).activeConversation.recentSteps[0].tokPerSec, 60);
|
assert.equal((await get()).activeConversation.recentSteps[0].tokPerSec, 60);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('telemetry reuses display rows only for a matching revision', async (t) => {
|
||||||
|
const { fetchTelemetry, telemetryStore } = await import('../src/store/telemetryStore.js');
|
||||||
|
const previousTelemetry = telemetryStore.getState().telemetry;
|
||||||
|
t.after(() => telemetryStore.setState({ telemetry: previousTelemetry }));
|
||||||
|
const recentSteps = [{ stepIndex: 1, tokPerSec: 20 }];
|
||||||
|
const agentSteps = [{ stepIndex: 2, tokPerSec: 40 }];
|
||||||
|
let response = {
|
||||||
|
stepRevision: 'test-revision',
|
||||||
|
activeConversation: { recentSteps, agents: [{ recentSteps: agentSteps }] },
|
||||||
|
};
|
||||||
|
const revisions = [];
|
||||||
|
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||||
|
revisions.push(new URL(url, 'http://localhost').searchParams.get('stepRevision'));
|
||||||
|
return { ok: true, json: async () => structuredClone(response) };
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal((await fetchTelemetry()).stepRevision, 'test-revision');
|
||||||
|
response = {
|
||||||
|
stepsUnchanged: true,
|
||||||
|
stepRevision: 'test-revision',
|
||||||
|
activeConversation: { agents: [{}] },
|
||||||
|
};
|
||||||
|
const refreshed = await fetchTelemetry();
|
||||||
|
assert.equal(revisions[1], 'test-revision');
|
||||||
|
assert.deepEqual(refreshed.activeConversation.recentSteps, recentSteps);
|
||||||
|
assert.deepEqual(refreshed.activeConversation.agents[0].recentSteps, agentSteps);
|
||||||
|
|
||||||
|
const telemetryBeforeMismatch = telemetryStore.getState().telemetry;
|
||||||
|
response.stepRevision = 'unknown-revision';
|
||||||
|
assert.equal(await fetchTelemetry(), null);
|
||||||
|
assert.equal(telemetryStore.getState().telemetry, telemetryBeforeMismatch);
|
||||||
|
});
|
||||||
|
|
||||||
test('simultaneous ranges share the trajectory scan while keeping their own totals', async () => {
|
test('simultaneous ranges share the trajectory scan while keeping their own totals', async () => {
|
||||||
const h = backendHarness({
|
const h = backendHarness({
|
||||||
trajectories: { live: raw },
|
trajectories: { live: raw },
|
||||||
@@ -759,7 +792,7 @@ test('simultaneous ranges share the trajectory scan while keeping their own tota
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('cached usage follows rolling boundaries and reprices unchanged steps', async () => {
|
test('cached usage follows rolling boundaries and reprices unchanged steps', async () => {
|
||||||
const { extractModelSteps } = await import('../speed-metrics.mjs');
|
const { extractModelSteps } = await import('../trajectory-metrics.mjs');
|
||||||
const [step] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
const [step] = extractModelSteps(raw.trajectory.steps, raw.trajectory.generatorMetadata);
|
||||||
const modelKey = 'test-metered-model';
|
const modelKey = 'test-metered-model';
|
||||||
let now = Date.parse('2026-03-08T07:00:00Z');
|
let now = Date.parse('2026-03-08T07:00:00Z');
|
||||||
@@ -806,7 +839,6 @@ test('cached usage follows rolling boundaries and reprices unchanged steps', asy
|
|||||||
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
|
test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakdowns + fit math helpers', async () => {
|
||||||
const {
|
const {
|
||||||
computeLinearFit,
|
computeLinearFit,
|
||||||
computeLoessFit,
|
|
||||||
computePublicationFit,
|
computePublicationFit,
|
||||||
getStepModelGroupKey,
|
getStepModelGroupKey,
|
||||||
toChronologicalSteps,
|
toChronologicalSteps,
|
||||||
@@ -840,7 +872,11 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd
|
|||||||
|
|
||||||
// Warmup cache curve stays clamped within [0, 100]
|
// Warmup cache curve stays clamped within [0, 100]
|
||||||
const cacheSeries = [0, 90, 92, 93, 94, 95, 95];
|
const cacheSeries = [0, 90, 92, 93, 94, 95, 95];
|
||||||
const loessCache = computeLoessFit(cacheSeries, { minVal: 0, maxVal: 100 });
|
const loessCache = computePublicationFit(
|
||||||
|
cacheSeries.map((_, index) => index),
|
||||||
|
cacheSeries,
|
||||||
|
{ minVal: 0, maxVal: 100 }
|
||||||
|
).sampleFits;
|
||||||
assert.equal(loessCache.length, cacheSeries.length);
|
assert.equal(loessCache.length, cacheSeries.length);
|
||||||
assert.ok(
|
assert.ok(
|
||||||
loessCache.every((v) => v >= 0 && v <= 100),
|
loessCache.every((v) => v >= 0 && v <= 100),
|
||||||
@@ -956,6 +992,67 @@ test('modelBreakdown exposes avgTtftSec, cacheHitPct, and subagent scoped breakd
|
|||||||
assert.equal(aggMb.length, 2);
|
assert.equal(aggMb.length, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('saving preferences sends the same legacy values normalized by the backend', async (t) => {
|
||||||
|
const { saveSettingsPatch, stopAsyncTelemetryLoop, telemetryStore } =
|
||||||
|
await import('../src/store/telemetryStore.js');
|
||||||
|
const h = backendHarness({ settings: { themeAccent: 'blue' } });
|
||||||
|
let savedSettings = JSON.parse(JSON.stringify(h.loadSettings()));
|
||||||
|
const previousTelemetry = telemetryStore.getState().telemetry;
|
||||||
|
t.after(() => {
|
||||||
|
stopAsyncTelemetryLoop();
|
||||||
|
telemetryStore.setState({ telemetry: previousTelemetry });
|
||||||
|
});
|
||||||
|
telemetryStore.setState({ telemetry: { settings: savedSettings } });
|
||||||
|
|
||||||
|
const patches = [];
|
||||||
|
let failSave = false;
|
||||||
|
t.mock.method(globalThis, 'fetch', async (path, options) => {
|
||||||
|
if (options.method === 'POST') {
|
||||||
|
assert.equal(path, '/api/settings');
|
||||||
|
const patch = JSON.parse(options.body);
|
||||||
|
patches.push(patch);
|
||||||
|
for (const [key, value] of Object.entries(patch)) {
|
||||||
|
assert.deepEqual(telemetryStore.getState().telemetry.settings[key], value);
|
||||||
|
}
|
||||||
|
if (failSave) {
|
||||||
|
return { ok: false, json: async () => ({ error: 'Failed to persist settings' }) };
|
||||||
|
}
|
||||||
|
const result = h.executeSettingsAction(patch);
|
||||||
|
savedSettings = JSON.parse(result.body);
|
||||||
|
return { ok: result.ok, json: async () => savedSettings };
|
||||||
|
}
|
||||||
|
assert.match(path, /^\/api\/telemetry\?/);
|
||||||
|
return { ok: true, json: async () => ({ settings: savedSettings }) };
|
||||||
|
});
|
||||||
|
|
||||||
|
await saveSettingsPatch({
|
||||||
|
windowMountMode: 'sidebar_only',
|
||||||
|
topbarCapsuleSlots: ['step_cost', 'cost', 'none'],
|
||||||
|
overviewMetrics: ['cost', 'tps'],
|
||||||
|
weeklyLimitMode: 'tokens',
|
||||||
|
});
|
||||||
|
assert.deepEqual(patches[0], {
|
||||||
|
windowMountMode: 'sidebar',
|
||||||
|
enableWindowOverlay: false,
|
||||||
|
topbarCapsuleSlots: ['cost'],
|
||||||
|
overviewMetrics: ['step_cost', 'tps'],
|
||||||
|
weeklyLimitMode: 'custom_tokens',
|
||||||
|
});
|
||||||
|
assert.deepEqual(telemetryStore.getState().telemetry.settings, savedSettings);
|
||||||
|
assert.equal(savedSettings.themeAccent, 'blue');
|
||||||
|
|
||||||
|
await saveSettingsPatch({ topbarCapsuleSlots: [], weeklyLimitMode: 'cost' });
|
||||||
|
assert.deepEqual(patches[1], {
|
||||||
|
topbarCapsuleSlots: ['context'],
|
||||||
|
weeklyLimitMode: 'custom_cost',
|
||||||
|
});
|
||||||
|
|
||||||
|
const telemetryBeforeFailure = telemetryStore.getState().telemetry;
|
||||||
|
failSave = true;
|
||||||
|
await assert.rejects(saveSettingsPatch({ windowMountMode: 'composer' }), /Failed to persist/);
|
||||||
|
assert.equal(telemetryStore.getState().telemetry, telemetryBeforeFailure);
|
||||||
|
});
|
||||||
|
|
||||||
test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => {
|
test('preferences schema defaults match pre-refactor UI, migrate legacy none slots, and support reset & cache rebuild', async () => {
|
||||||
// 1. Default schema matches pre-refactor out-of-box UI 100%
|
// 1. Default schema matches pre-refactor out-of-box UI 100%
|
||||||
const hDefault = backendHarness({});
|
const hDefault = backendHarness({});
|
||||||
|
|||||||
@@ -35,7 +35,23 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs
|
|||||||
latestPluginVersion: '1.5.0',
|
latestPluginVersion: '1.5.0',
|
||||||
downloadUrl: 'https://evil.example.com/malware.zip',
|
downloadUrl: 'https://evil.example.com/malware.zip',
|
||||||
pricing: {
|
pricing: {
|
||||||
'gemini-4.5-ultra': { input: 3.5, cache: 0.35, output: 15.0, short: 'ultra-4.5', family: 'Gemini' },
|
'gemini-4.5-ultra': {
|
||||||
|
input: 3.5,
|
||||||
|
cache: 0.35,
|
||||||
|
output: 15.0,
|
||||||
|
short: 'ultra-4.5',
|
||||||
|
family: 'Gemini',
|
||||||
|
phases: [
|
||||||
|
{ until: '2026-12-01T00:00:00Z', input: 1.75, cache: 0.175, output: 7.5 },
|
||||||
|
{ from: '2026-12-01T00:00:00Z', input: 3.5, cache: 0.35, output: 15.0 },
|
||||||
|
{ until: 'not-a-date', input: 1.0, cache: 0.1, output: 5.0 },
|
||||||
|
{ from: '2026-12-10T00:00:00Z', until: '2026-12-01T00:00:00Z', input: 1.0, cache: 0.1, output: 5.0 },
|
||||||
|
{ input: 1.0, cache: 0.1, output: 5.0 },
|
||||||
|
{ until: '2026-12-01T00:00:00Z', input: -1, cache: 0.1, output: 5.0 },
|
||||||
|
{ until: '2026-12-01T00:00:00Z', input: 0, cache: 0, output: 0 },
|
||||||
|
{ until: '2026-12-01T00:00:00Z', input: '1.0', cache: 0.1, output: 5.0 },
|
||||||
|
],
|
||||||
|
},
|
||||||
'broken-negative': { input: -1, cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
'broken-negative': { input: -1, cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||||
'broken-nan': { input: 'NaN', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
'broken-nan': { input: 'NaN', cache: 0.1, output: 5, short: 'bad', family: 'Gemini' },
|
||||||
'broken-null': { input: null, cache: null, output: null, short: 'bad', family: 'Gemini' },
|
'broken-null': { input: null, cache: null, output: null, short: 'bad', family: 'Gemini' },
|
||||||
@@ -54,9 +70,165 @@ test('sanitizeCatalogPayload filters malformed/null/zero entries, untrusted URLs
|
|||||||
assert.equal(sanitized.latestPluginVersion, '1.5.0');
|
assert.equal(sanitized.latestPluginVersion, '1.5.0');
|
||||||
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan-dev/'));
|
assert.ok(sanitized.downloadUrl.startsWith('https://github.com/yuhuan-dev/'));
|
||||||
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
|
assert.deepEqual(Object.keys(sanitized.pricing), ['gemini-4.5-ultra']);
|
||||||
|
assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases.length, 2);
|
||||||
|
assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases[0].input, 1.75);
|
||||||
|
assert.equal(sanitized.pricing['gemini-4.5-ultra'].phases[1].input, 3.5);
|
||||||
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
|
assert.deepEqual(Object.keys(sanitized.placeholders), ['MODEL_PLACEHOLDER_M999']);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('time-phased promotional pricing resolves exact rates across Carbon/Argon (Dec 1) and 3.6-3.8 Flash (Jan 1) boundaries while preserving historical costs and flat models', async () => {
|
||||||
|
let now = Date.parse('2026-11-30T23:59:59.000Z');
|
||||||
|
const makeTimedStep = (idx, model, isoStart, inTok = 1_000_000, cacheTok = 1_000_000, outTok = 1_000_000) => ({
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: idx },
|
||||||
|
createdAt: isoStart,
|
||||||
|
completedAt: new Date(Date.parse(isoStart) + 1_000).toISOString(),
|
||||||
|
modelUsage: {
|
||||||
|
model,
|
||||||
|
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inputTokens: String(inTok),
|
||||||
|
cacheReadTokens: String(cacheTok),
|
||||||
|
outputTokens: String(outTok),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const steps = [
|
||||||
|
// Step 1: Carbon High right before Nov 30 cutoff -> $2.0 + $0.1 + $10.0 = $12.10 (saved: $1.90)
|
||||||
|
makeTimedStep(1, 'MODEL_PLACEHOLDER_M429', '2026-11-30T23:59:59.999Z'),
|
||||||
|
// Step 2: Carbon High at exact Dec 1 cutoff -> $4.0 + $0.2 + $20.0 = $24.20 (saved: $3.80)
|
||||||
|
makeTimedStep(2, 'MODEL_PLACEHOLDER_M429', '2026-12-01T00:00:00.000Z'),
|
||||||
|
// Step 3: Orchestrator (Argon) in Nov promo -> $2.0 + $0.1 + $10.0 = $12.10
|
||||||
|
makeTimedStep(3, 'MODEL_PLACEHOLDER_M681', '2026-11-20T10:00:00.000Z'),
|
||||||
|
// Step 4: Orchestrator (Argon) in Dec standard -> $4.0 + $0.2 + $20.0 = $24.20
|
||||||
|
makeTimedStep(4, 'MODEL_PLACEHOLDER_M681', '2026-12-05T10:00:00.000Z'),
|
||||||
|
// Step 5: Gemini 3.8 Flash (High) in Dec (still promo!) -> $0.75 + $0.075 + $3.75 = $4.575
|
||||||
|
makeTimedStep(5, 'MODEL_PLACEHOLDER_M318', '2026-12-31T23:59:59.999Z'),
|
||||||
|
// Step 6: Gemini 3.8 Flash (High) on Jan 1, 2027 (standard!) -> $1.50 + $0.15 + $7.50 = $9.15
|
||||||
|
makeTimedStep(6, 'MODEL_PLACEHOLDER_M318', '2027-01-01T00:00:00.000Z'),
|
||||||
|
// Step 7: Gemini 3.8 Flash (Low) in Jan 2027 (flat, no doubling!) -> $0.30 + $0.03 + $2.50 = $2.83
|
||||||
|
makeTimedStep(7, 'MODEL_PLACEHOLDER_M320', '2027-01-15T00:00:00.000Z'),
|
||||||
|
// Step 8: Gemini 3.5 Flash in Nov 2026 (no half-price promo!) -> $1.50 + $0.15 + $9.00 = $10.65
|
||||||
|
makeTimedStep(8, 'MODEL_PLACEHOLDER_M149', '2026-11-17T00:00:00.000Z'),
|
||||||
|
// Step 9: Gemini 3.6 Flash in Jan 2027 -> $1.50 + $0.15 + $7.50 = $9.15
|
||||||
|
makeTimedStep(9, 'MODEL_PLACEHOLDER_M71', '2027-01-02T00:00:00.000Z'),
|
||||||
|
// Step 10: Gemini 3.7 Flash in Nov 2026 -> $0.75 + $0.075 + $3.75 = $4.575
|
||||||
|
makeTimedStep(10, 'MODEL_PLACEHOLDER_M298', '2026-11-17T00:00:00.000Z'),
|
||||||
|
];
|
||||||
|
|
||||||
|
// Advance clock to 2027-01-20: historical Nov & Dec steps must NOT be overwritten with 2027 rates!
|
||||||
|
now = Date.parse('2027-01-20T12:00:00Z');
|
||||||
|
const h = backendHarness({
|
||||||
|
clock: () => now,
|
||||||
|
summaries: { convPhase: { stepCount: steps.length, lastModifiedTime: '2027-01-15T00:00:01Z' } },
|
||||||
|
trajectories: { convPhase: { trajectory: { steps } } },
|
||||||
|
});
|
||||||
|
|
||||||
|
// Direct resolveModelInfo without timestamp uses current clock (2027-01-20 -> post-promo for all phased models)
|
||||||
|
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M429').pricing.input, 4.0);
|
||||||
|
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M417').pricing.output, 20.0);
|
||||||
|
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M318').pricing.input, 1.5);
|
||||||
|
assert.equal(h.resolveModelInfo('MODEL_PLACEHOLDER_M318').pricing.output, 7.5);
|
||||||
|
// Explicit historical timestamp still resolves promo pricing
|
||||||
|
assert.equal(
|
||||||
|
h.resolveModelInfo('MODEL_PLACEHOLDER_M429', new Map(), '', '', '', '2026-11-17T00:00:00Z').pricing.input,
|
||||||
|
2.0
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
h.resolveModelInfo('MODEL_PLACEHOLDER_M318', new Map(), '', '', '', '2026-12-15T00:00:00Z').pricing.input,
|
||||||
|
0.75
|
||||||
|
);
|
||||||
|
|
||||||
|
// computeStepCost honors step timestamp even when passed post-promo pricing object
|
||||||
|
const postPromoCarbonPricing = h.resolveModelInfo('MODEL_PLACEHOLDER_M429').pricing;
|
||||||
|
assert.equal(
|
||||||
|
h.computeStepCost(
|
||||||
|
{ createdAtMs: Date.parse('2026-11-15T00:00:00Z'), inputTokens: 1_000_000, cacheReadTokens: 0, outputTokens: 0 },
|
||||||
|
postPromoCarbonPricing
|
||||||
|
),
|
||||||
|
2.0
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
h.computeStepCost(
|
||||||
|
{ createdAtMs: Date.parse('2026-12-15T00:00:00Z'), inputTokens: 1_000_000, cacheReadTokens: 0, outputTokens: 0 },
|
||||||
|
postPromoCarbonPricing
|
||||||
|
),
|
||||||
|
4.0
|
||||||
|
);
|
||||||
|
|
||||||
|
const p = await h.buildTelemetryPayloadInternal('convPhase');
|
||||||
|
const byIdx = new Map(p.activeConversation.recentSteps.map((s) => [s.stepIndex, s]));
|
||||||
|
|
||||||
|
assert.equal(byIdx.get(1).costUsd, 12.1);
|
||||||
|
assert.equal(byIdx.get(1).inCostUsd, 2.0);
|
||||||
|
assert.equal(byIdx.get(1).cacheCostUsd, 0.1);
|
||||||
|
assert.equal(byIdx.get(1).outCostUsd, 10.0);
|
||||||
|
|
||||||
|
assert.equal(byIdx.get(2).costUsd, 24.2);
|
||||||
|
assert.equal(byIdx.get(2).inCostUsd, 4.0);
|
||||||
|
assert.equal(byIdx.get(2).cacheCostUsd, 0.2);
|
||||||
|
assert.equal(byIdx.get(2).outCostUsd, 20.0);
|
||||||
|
|
||||||
|
assert.equal(byIdx.get(3).costUsd, 12.1);
|
||||||
|
assert.equal(byIdx.get(4).costUsd, 24.2);
|
||||||
|
assert.equal(byIdx.get(5).costUsd, 4.575);
|
||||||
|
assert.equal(byIdx.get(6).costUsd, 9.15);
|
||||||
|
assert.equal(byIdx.get(7).costUsd, 2.83);
|
||||||
|
assert.equal(byIdx.get(8).costUsd, 10.65);
|
||||||
|
assert.equal(byIdx.get(9).costUsd, 9.15);
|
||||||
|
assert.equal(byIdx.get(10).costUsd, 4.575);
|
||||||
|
|
||||||
|
// Total across all 10 steps = 12.1 + 24.2 + 12.1 + 24.2 + 4.575 + 9.15 + 2.83 + 10.65 + 9.15 + 4.575 = 113.53
|
||||||
|
assert.equal(p.activeConversation.sessionCostUsd, 113.53);
|
||||||
|
assert.equal(p.consumption.account.costUsd, 113.53);
|
||||||
|
|
||||||
|
// Verify getPricingPhaseEpoch advances across boundaries (0 -> 1 -> 2) and invalidates cached snapshots for timestamp-less steps
|
||||||
|
assert.equal(h.getPricingPhaseEpoch(Date.parse('2026-11-30T23:59:59Z')), 0);
|
||||||
|
assert.equal(h.getPricingPhaseEpoch(Date.parse('2026-12-15T00:00:00Z')), 1);
|
||||||
|
assert.equal(h.getPricingPhaseEpoch(Date.parse('2027-01-01T00:00:00Z')), 2);
|
||||||
|
|
||||||
|
let dynamicClock = Date.parse('2026-11-30T23:59:59Z');
|
||||||
|
const hBoundary = backendHarness({
|
||||||
|
clock: () => dynamicClock,
|
||||||
|
summaries: { cZeroTs: { stepCount: 1 } },
|
||||||
|
cache: {
|
||||||
|
cZeroTs: {
|
||||||
|
signature: 'v10-model-identity:disk:0',
|
||||||
|
contextLimitTelemetry: true,
|
||||||
|
turnRailTelemetry: true,
|
||||||
|
contextGroupsTelemetry: true,
|
||||||
|
speedClearedTelemetry: true,
|
||||||
|
subagentRefs: [],
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
stepIndex: 1,
|
||||||
|
createdAtMs: 0,
|
||||||
|
modelKey: 'MODEL_PLACEHOLDER_M429',
|
||||||
|
modelIdentityVersion: 1,
|
||||||
|
modelSource: 'usage.model',
|
||||||
|
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
cacheReadTokens: 0,
|
||||||
|
outputTokens: 0,
|
||||||
|
thinkingTokens: 0,
|
||||||
|
responseTokens: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const beforeCutoff = await hBoundary.buildTelemetryPayloadInternal('cZeroTs');
|
||||||
|
assert.equal(beforeCutoff.activeConversation.latestStepCostUsd, 2.0);
|
||||||
|
assert.equal(beforeCutoff.consumption.account.costUsd, 2.0);
|
||||||
|
|
||||||
|
dynamicClock = Date.parse('2026-12-01T00:00:01Z');
|
||||||
|
const afterCutoff = await hBoundary.buildTelemetryPayloadInternal('cZeroTs');
|
||||||
|
assert.equal(afterCutoff.activeConversation.latestStepCostUsd, 4.0);
|
||||||
|
assert.equal(afterCutoff.consumption.account.costUsd, 4.0);
|
||||||
|
});
|
||||||
|
|
||||||
test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newly pushed models', async () => {
|
test('cloud catalog sync fetches from GitHub raw URL and dynamically prices newly pushed models', async () => {
|
||||||
const step = makeStep(1, 'MODEL_PLACEHOLDER_M888');
|
const step = makeStep(1, 'MODEL_PLACEHOLDER_M888');
|
||||||
let fetchedUrl = '';
|
let fetchedUrl = '';
|
||||||
@@ -425,3 +597,58 @@ test('pluginUpdateMode supports manual (default), auto, and off with legacy auto
|
|||||||
await new Promise((r) => setTimeout(r, 20));
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
assert.equal(gitTriggered, true, 'pluginUpdateMode=auto triggers background update check');
|
assert.equal(gitTriggered, true, 'pluginUpdateMode=auto triggers background update check');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('argon-b / argon-trial deployment shards resolve phased pricing without wildcarding unknown single-letter suffixes, and custom Git forks suppress upstream update badges', async () => {
|
||||||
|
const hPromo = backendHarness({ clock: () => Date.parse('2026-11-20T00:00:00Z') });
|
||||||
|
for (const shardSlug of ['gemini-4-argon-b', 'gemini-4-argon-trial']) {
|
||||||
|
const promoInfo = hPromo.resolveModelInfo(shardSlug);
|
||||||
|
assert.equal(promoInfo.label, 'Gemini 4 Argon');
|
||||||
|
assert.equal(promoInfo.shortName, 'argon-4');
|
||||||
|
assert.equal(promoInfo.pricing.input, 2.0);
|
||||||
|
assert.equal(promoInfo.pricing.output, 10.0);
|
||||||
|
|
||||||
|
const postInfo = hPromo.resolveModelInfo(shardSlug, new Map(), '', '', '', '2026-12-05T00:00:00Z');
|
||||||
|
assert.equal(postInfo.pricing.input, 4.0);
|
||||||
|
assert.equal(postInfo.pricing.output, 20.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unverified single-letter shard must NOT recklessly fall back to base model pricing
|
||||||
|
const unknownShard = hPromo.resolveModelInfo('gemini-4-argon-z');
|
||||||
|
assert.equal(unknownShard.pricing, null);
|
||||||
|
|
||||||
|
// Custom Git fork: upstream cloud catalog sync updates model pricing, while suppressing upstream version badge
|
||||||
|
const forkH = backendHarness({
|
||||||
|
hasGitDir: true,
|
||||||
|
gitConfigText: '[core]\n\trepositoryformatversion = 0\n[remote "origin"]\n\turl = https://github.com/custom-contributor/antigravity-usage-monitor.git\n',
|
||||||
|
pluginManifest: { name: 'usage-monitor', version: '1.5.0' },
|
||||||
|
remoteFetch: async () => ({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
schemaVersion: 1,
|
||||||
|
catalogVersion: '2026.12.10.1',
|
||||||
|
updatedAt: '2026-12-10T10:00:00Z',
|
||||||
|
latestPluginVersion: '1.9.0',
|
||||||
|
pricing: {
|
||||||
|
'gemini-5-experimental': {
|
||||||
|
input: 6.0,
|
||||||
|
cache: 0.3,
|
||||||
|
output: 30.0,
|
||||||
|
short: 'gem-5-exp',
|
||||||
|
family: 'Gemini',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(forkH.detectCustomGitForkRepo(), 'custom-contributor/antigravity-usage-monitor');
|
||||||
|
const statusAfterSync = await forkH.syncCloudCatalog({ force: true });
|
||||||
|
assert.equal(statusAfterSync.catalogVersion, '2026.12.10.1');
|
||||||
|
assert.equal(statusAfterSync.updateAvailable, false, 'custom fork must not show false update badge from upstream repo');
|
||||||
|
assert.equal(statusAfterSync.latestPluginVersion, '1.5.0');
|
||||||
|
assert.equal(
|
||||||
|
statusAfterSync.releaseUrl,
|
||||||
|
'https://github.com/custom-contributor/antigravity-usage-monitor/releases/latest'
|
||||||
|
);
|
||||||
|
assert.equal(forkH.resolveModelInfo('gemini-5-experimental').pricing.input, 6.0);
|
||||||
|
});
|
||||||
|
|||||||
@@ -46,9 +46,11 @@ test('saves and restores one model at a time using host presets or verified mode
|
|||||||
assert.equal(carbonModel.id, carbonGroup);
|
assert.equal(carbonModel.id, carbonGroup);
|
||||||
assert.equal(carbonModel.label, 'Gemini 4 Carbon');
|
assert.equal(carbonModel.label, 'Gemini 4 Carbon');
|
||||||
assert.deepEqual(carbonModel.members, [carbon, carbonLow]);
|
assert.deepEqual(carbonModel.members, [carbon, carbonLow]);
|
||||||
assert.equal(carbonModel.options.at(-1).tokens, 636000);
|
assert.deepEqual(carbonModel.options.map(({ tokens }) => tokens), [128000, 256000, 384000, 512000, 636000]);
|
||||||
assert.equal((await update({ modelId: carbonGroup, option: '768000' })).status, 400);
|
assert.equal((await update({ modelId: carbonGroup, option: '768000' })).status, 400);
|
||||||
h.state.settings.modelContextWindows = { [carbon]: '768000', [carbonLow]: '256000' };
|
h.state.settings.modelContextWindows = { [carbon]: '768000', [carbonLow]: '256000' };
|
||||||
|
assert.equal((await update({ modelId: carbonGroup, option: '384000' })).status, 200);
|
||||||
|
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '384000' });
|
||||||
assert.equal((await update({ modelId: carbonGroup, option: '512000' })).status, 200);
|
assert.equal((await update({ modelId: carbonGroup, option: '512000' })).status, 200);
|
||||||
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '512000' });
|
assert.deepEqual({ ...h.loadSettings().modelContextWindows }, { [carbonGroup]: '512000' });
|
||||||
assert.equal((await update({ modelId: carbonGroup, option: null })).status, 200);
|
assert.equal((await update({ modelId: carbonGroup, option: null })).status, 200);
|
||||||
@@ -208,3 +210,97 @@ test('host requests apply a rule only to the exact model across App and IDE tran
|
|||||||
assert.equal(window.fetch, nativeFetch);
|
assert.equal(window.fetch, nativeFetch);
|
||||||
assert.equal(WebSocket.prototype.send, nativeSend);
|
assert.equal(WebSocket.prototype.send, nativeSend);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('Issue #27: syncHostContextWindows falls back to backend pre-resolved rules without __APP_CONFIG__.csrfToken and intercepts StartCascade + Uint8Array / connect+json frames', async () => {
|
||||||
|
const sendPath = '/exa.language_server_pb.LanguageServerService/SendUserCascadeMessage';
|
||||||
|
const startPath = '/exa.language_server_pb.LanguageServerService/StartCascade';
|
||||||
|
const host = 'https://127.0.0.1:26190';
|
||||||
|
const nativeFetch = async (_url, init) => init;
|
||||||
|
class WebSocket {
|
||||||
|
constructor(url) {
|
||||||
|
this.url = url;
|
||||||
|
}
|
||||||
|
send(data) {
|
||||||
|
return data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const window = {
|
||||||
|
location: new URL(host),
|
||||||
|
fetch: nativeFetch,
|
||||||
|
WebSocket,
|
||||||
|
__APP_CONFIG__: {}, // Simulate 2.33.0+ environment without exposed csrfToken on window
|
||||||
|
};
|
||||||
|
const context = vm.createContext({
|
||||||
|
window,
|
||||||
|
URL,
|
||||||
|
TextEncoder,
|
||||||
|
TextDecoder,
|
||||||
|
Headers,
|
||||||
|
Uint8Array,
|
||||||
|
AbortSignal,
|
||||||
|
setTimeout,
|
||||||
|
clearTimeout,
|
||||||
|
});
|
||||||
|
|
||||||
|
const prefs = { [carbonGroup]: '256000' };
|
||||||
|
const fallbackRules = { [carbon]: 256000, [carbonLow]: 256000 };
|
||||||
|
const syncResult = await vm.runInContext(
|
||||||
|
createContextWindowSyncExpression(prefs, 'boot-233', fallbackRules),
|
||||||
|
context
|
||||||
|
);
|
||||||
|
assert.deepEqual({ ...syncResult }, { attached: true, ruleCount: 2 });
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 1. StartCascade on new conversation creation with Uint8Array JSON body
|
||||||
|
const startPayload = {
|
||||||
|
cascadeConfig: {
|
||||||
|
plannerConfig: { planModel: carbon },
|
||||||
|
checkpointConfig: { maxTokenLimit: 512000 },
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const uint8Body = new TextEncoder().encode(JSON.stringify(startPayload));
|
||||||
|
const startOut = await window.fetch(new URL(host + startPath), {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: uint8Body,
|
||||||
|
});
|
||||||
|
assert.equal(startOut.body instanceof Uint8Array, true);
|
||||||
|
assert.equal(
|
||||||
|
JSON.parse(new TextDecoder().decode(startOut.body)).cascadeConfig.checkpointConfig
|
||||||
|
.maxTokenLimit,
|
||||||
|
256000
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. application/connect+json 5-byte envelope on SendUserCascadeMessage
|
||||||
|
const msgBytes = Buffer.from(JSON.stringify(startPayload), 'utf8');
|
||||||
|
const connectFrame = new Uint8Array(5 + msgBytes.length);
|
||||||
|
new DataView(connectFrame.buffer).setUint32(1, msgBytes.length);
|
||||||
|
connectFrame.set(msgBytes, 5);
|
||||||
|
const framedOut = await window.fetch(host + sendPath, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/connect+json' },
|
||||||
|
body: connectFrame,
|
||||||
|
});
|
||||||
|
const decodedJson = JSON.parse(
|
||||||
|
new TextDecoder().decode(framedOut.body.subarray(5))
|
||||||
|
);
|
||||||
|
assert.equal(decodedJson.cascadeConfig.checkpointConfig.maxTokenLimit, 256000);
|
||||||
|
|
||||||
|
// 3. WebSocket StartCascade frame
|
||||||
|
const ws = new WebSocket('wss://127.0.0.1:26190/connect-websocket');
|
||||||
|
const wsFrame = JSON.parse(
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify({
|
||||||
|
type: 'start',
|
||||||
|
stream: false,
|
||||||
|
procedure: startPath,
|
||||||
|
payload: startPayload,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
);
|
||||||
|
assert.equal(wsFrame.payload.cascadeConfig.checkpointConfig.maxTokenLimit, 256000);
|
||||||
|
} finally {
|
||||||
|
await vm.runInContext(createContextWindowSyncExpression({}, 'boot-233', {}), context);
|
||||||
|
}
|
||||||
|
assert.equal(window.fetch, nativeFetch);
|
||||||
|
});
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,548 @@
|
|||||||
|
/**
|
||||||
|
* @fileoverview Shared lightweight W3C-compatible Mock DOM for Node `vm` UI & overlay tests.
|
||||||
|
* Replaces 6 separate copy-pasted inline mock DOM classes across `window-bridge.test.mjs`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const ATTR_TOKEN_RE = /\[\s*([a-zA-Z0-9_:-]+)\s*(?:([*^$~|]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\]]*)))?\s*\]/g;
|
||||||
|
|
||||||
|
function matchCompoundSelector(node, rawCompound) {
|
||||||
|
if (!node || !node.tagName || String(node.tagName).startsWith('#')) return false;
|
||||||
|
let rem = String(rawCompound || '').trim();
|
||||||
|
if (!rem) return false;
|
||||||
|
if (rem === '*') return true;
|
||||||
|
|
||||||
|
// Match attribute clauses `[attr]`, `[attr="v"]`, `[attr^="v"]`, `[attr*="v"]`, `[attr$="v"]`
|
||||||
|
const attrs = [];
|
||||||
|
rem = rem.replace(ATTR_TOKEN_RE, (_m, name, op, dq, sq, bare) => {
|
||||||
|
attrs.push({ name, op: op || '', val: dq ?? sq ?? (bare ? bare.trim() : '') });
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const a of attrs) {
|
||||||
|
if (!a.op) {
|
||||||
|
if (!node.hasAttribute(a.name)) return false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const actual = node.getAttribute(a.name);
|
||||||
|
if (actual === null || actual === undefined) return false;
|
||||||
|
const str = String(actual);
|
||||||
|
if (a.op === '=' && str !== a.val) return false;
|
||||||
|
if (a.op === '^=' && !str.startsWith(a.val)) return false;
|
||||||
|
if (a.op === '*=' && !str.includes(a.val)) return false;
|
||||||
|
if (a.op === '$=' && !str.endsWith(a.val)) return false;
|
||||||
|
if (a.op === '~=' && !str.split(/\s+/).includes(a.val)) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Extract `#id` and `.class` tokens
|
||||||
|
let idReq = '';
|
||||||
|
const classReqs = [];
|
||||||
|
rem = rem.replace(/#([a-zA-Z0-9_-]+)/g, (_m, id) => {
|
||||||
|
idReq = id;
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
rem = rem.replace(/\.([a-zA-Z0-9_@/-]+)/g, (_m, cls) => {
|
||||||
|
classReqs.push(cls);
|
||||||
|
return '';
|
||||||
|
});
|
||||||
|
|
||||||
|
if (idReq && node.id !== idReq) return false;
|
||||||
|
for (const cls of classReqs) {
|
||||||
|
if (!node.classList.contains(cls)) return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const tag = rem.trim();
|
||||||
|
if (tag && node.tagName.toLowerCase() !== tag.toLowerCase()) return false;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
function splitTopLevelCommas(selector) {
|
||||||
|
const out = [];
|
||||||
|
let depth = 0;
|
||||||
|
let quote = '';
|
||||||
|
let start = 0;
|
||||||
|
const s = String(selector || '');
|
||||||
|
for (let i = 0; i < s.length; i++) {
|
||||||
|
const ch = s[i];
|
||||||
|
if (quote) {
|
||||||
|
if (ch === quote && s[i - 1] !== '\\') quote = '';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '"' || ch === "'") {
|
||||||
|
quote = ch;
|
||||||
|
} else if (ch === '[') {
|
||||||
|
depth++;
|
||||||
|
} else if (ch === ']') {
|
||||||
|
depth = Math.max(0, depth - 1);
|
||||||
|
} else if (ch === ',' && depth === 0) {
|
||||||
|
const part = s.slice(start, i).trim();
|
||||||
|
if (part) out.push(part);
|
||||||
|
start = i + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const tail = s.slice(start).trim();
|
||||||
|
if (tail) out.push(tail);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function tokenizeCombinators(singleSelector) {
|
||||||
|
const tokens = [];
|
||||||
|
let depth = 0;
|
||||||
|
let quote = '';
|
||||||
|
let buf = '';
|
||||||
|
let pendingDirect = false;
|
||||||
|
const s = String(singleSelector || '').trim();
|
||||||
|
for (let i = 0; i < s.length; i++) {
|
||||||
|
const ch = s[i];
|
||||||
|
if (quote) {
|
||||||
|
buf += ch;
|
||||||
|
if (ch === quote && s[i - 1] !== '\\') quote = '';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '"' || ch === "'") {
|
||||||
|
quote = ch;
|
||||||
|
buf += ch;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === '[') {
|
||||||
|
depth++;
|
||||||
|
buf += ch;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (ch === ']') {
|
||||||
|
depth = Math.max(0, depth - 1);
|
||||||
|
buf += ch;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (depth === 0 && (ch === '>' || /\s/.test(ch))) {
|
||||||
|
if (buf) {
|
||||||
|
tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' });
|
||||||
|
buf = '';
|
||||||
|
pendingDirect = false;
|
||||||
|
}
|
||||||
|
if (ch === '>') pendingDirect = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
buf += ch;
|
||||||
|
}
|
||||||
|
if (buf) {
|
||||||
|
tokens.push({ compound: buf, combinator: pendingDirect ? '>' : ' ' });
|
||||||
|
}
|
||||||
|
return tokens;
|
||||||
|
}
|
||||||
|
|
||||||
|
function matchChainFromScope(node, scopeRoot, tokens, idx) {
|
||||||
|
const step = tokens[idx];
|
||||||
|
if (step.compound === ':scope') {
|
||||||
|
return node === scopeRoot;
|
||||||
|
}
|
||||||
|
if (!matchCompoundSelector(node, step.compound)) return false;
|
||||||
|
if (idx === 0) return true;
|
||||||
|
|
||||||
|
if (step.combinator === '>') {
|
||||||
|
const p = node.parentNode;
|
||||||
|
if (!p) return false;
|
||||||
|
return matchChainFromScope(p, scopeRoot, tokens, idx - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
let p = node.parentNode;
|
||||||
|
while (p) {
|
||||||
|
if (matchChainFromScope(p, scopeRoot, tokens, idx - 1)) return true;
|
||||||
|
if (p === scopeRoot) break;
|
||||||
|
p = p.parentNode;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MockMutationObserver {
|
||||||
|
constructor(cb, registry = null) {
|
||||||
|
this.cb = cb;
|
||||||
|
this.targets = [];
|
||||||
|
if (Array.isArray(registry)) registry.push(this);
|
||||||
|
}
|
||||||
|
observe(target, options) {
|
||||||
|
this.targets.push({ target, options });
|
||||||
|
}
|
||||||
|
disconnect() {
|
||||||
|
this.targets = [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class MockDomNode {
|
||||||
|
constructor(tag = 'div', rect = null, domOptions = null) {
|
||||||
|
this._domOptions = domOptions || null;
|
||||||
|
this.tagName = String(tag || 'div').toUpperCase();
|
||||||
|
this.nodeName = this.tagName;
|
||||||
|
this.nodeType = this.tagName === '#TEXT' ? 3 : 1;
|
||||||
|
this.id = '';
|
||||||
|
this.value = '';
|
||||||
|
this._text = '';
|
||||||
|
this._rect = null;
|
||||||
|
this._ownRect = rect || null;
|
||||||
|
this.offsetWidth = 0;
|
||||||
|
this.offsetHeight = 0;
|
||||||
|
this.clientWidth = 0;
|
||||||
|
this.scrollWidth = 0;
|
||||||
|
this.dataset = {};
|
||||||
|
this.attributes = new Map();
|
||||||
|
this._classes = new Set();
|
||||||
|
this.children = [];
|
||||||
|
this.parentNode = null;
|
||||||
|
this.shadowRoot = null;
|
||||||
|
this._listeners = new Map();
|
||||||
|
|
||||||
|
const styleVars = new Map();
|
||||||
|
this.style = {
|
||||||
|
width: '',
|
||||||
|
height: '',
|
||||||
|
maxHeight: '',
|
||||||
|
marginLeft: '',
|
||||||
|
top: '',
|
||||||
|
left: '',
|
||||||
|
right: '',
|
||||||
|
display: '',
|
||||||
|
visibility: '',
|
||||||
|
opacity: '',
|
||||||
|
_vars: styleVars,
|
||||||
|
setProperty(k, v) {
|
||||||
|
const s = String(v ?? '');
|
||||||
|
styleVars.set(k, s);
|
||||||
|
this[k] = s;
|
||||||
|
},
|
||||||
|
getPropertyValue(k) {
|
||||||
|
return styleVars.get(k) || this[k] || '';
|
||||||
|
},
|
||||||
|
removeProperty(k) {
|
||||||
|
styleVars.delete(k);
|
||||||
|
delete this[k];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const self = this;
|
||||||
|
this.classList = {
|
||||||
|
add(...tokens) {
|
||||||
|
for (const t of tokens) if (t) self._classes.add(t);
|
||||||
|
self._syncClassAttr();
|
||||||
|
},
|
||||||
|
remove(...tokens) {
|
||||||
|
for (const t of tokens) self._classes.delete(t);
|
||||||
|
self._syncClassAttr();
|
||||||
|
},
|
||||||
|
contains(tok) {
|
||||||
|
return self._classes.has(tok);
|
||||||
|
},
|
||||||
|
toggle(tok, force) {
|
||||||
|
const should = force === undefined ? !self._classes.has(tok) : Boolean(force);
|
||||||
|
if (should) self._classes.add(tok);
|
||||||
|
else self._classes.delete(tok);
|
||||||
|
self._syncClassAttr();
|
||||||
|
return should;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
_syncClassAttr() {
|
||||||
|
const joined = [...this._classes].join(' ');
|
||||||
|
if (joined) this.attributes.set('class', joined);
|
||||||
|
else this.attributes.delete('class');
|
||||||
|
}
|
||||||
|
|
||||||
|
get className() {
|
||||||
|
return [...this._classes].join(' ');
|
||||||
|
}
|
||||||
|
|
||||||
|
set className(v) {
|
||||||
|
this._classes.clear();
|
||||||
|
for (const part of String(v || '').split(/\s+/)) {
|
||||||
|
if (part) this._classes.add(part);
|
||||||
|
}
|
||||||
|
this._syncClassAttr();
|
||||||
|
}
|
||||||
|
|
||||||
|
get textContent() {
|
||||||
|
if (this.children.length === 0) return this._text;
|
||||||
|
return this._text + this.children.map((c) => c.textContent ?? '').join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
set textContent(v) {
|
||||||
|
for (const c of this.children) {
|
||||||
|
if (c) c.parentNode = null;
|
||||||
|
}
|
||||||
|
this.children = [];
|
||||||
|
this._text = String(v ?? '');
|
||||||
|
}
|
||||||
|
|
||||||
|
get parentElement() {
|
||||||
|
return this.parentNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
set parentElement(v) {
|
||||||
|
this.parentNode = v;
|
||||||
|
}
|
||||||
|
|
||||||
|
get firstChild() {
|
||||||
|
return this.children[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get lastChild() {
|
||||||
|
return this.children[this.children.length - 1] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get firstElementChild() {
|
||||||
|
return this.children[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get lastElementChild() {
|
||||||
|
return this.children[this.children.length - 1] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get nextSibling() {
|
||||||
|
if (!this.parentNode) return null;
|
||||||
|
const idx = this.parentNode.children.indexOf(this);
|
||||||
|
return idx >= 0 ? this.parentNode.children[idx + 1] || null : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
get nextElementSibling() {
|
||||||
|
return this.nextSibling;
|
||||||
|
}
|
||||||
|
|
||||||
|
get isConnected() {
|
||||||
|
let cur = this;
|
||||||
|
while (cur) {
|
||||||
|
if (cur.isDocumentRoot) return true;
|
||||||
|
cur = cur.parentNode || cur.host || null;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
setAttribute(k, v) {
|
||||||
|
const s = String(v);
|
||||||
|
if (k === 'class') {
|
||||||
|
this.className = s;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
this.attributes.set(k, s);
|
||||||
|
if (k === 'id') this.id = s;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAttribute(k) {
|
||||||
|
if (k === 'class') return this.attributes.has('class') ? this.className : null;
|
||||||
|
return this.attributes.has(k) ? this.attributes.get(k) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasAttribute(k) {
|
||||||
|
return this.attributes.has(k);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeAttribute(k) {
|
||||||
|
if (k === 'class') {
|
||||||
|
this._classes.clear();
|
||||||
|
}
|
||||||
|
this.attributes.delete(k);
|
||||||
|
}
|
||||||
|
|
||||||
|
appendChild(child) {
|
||||||
|
if (!child) return child;
|
||||||
|
if (child.parentNode?.removeChild) child.parentNode.removeChild(child);
|
||||||
|
child.parentNode = this;
|
||||||
|
this.children.push(child);
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
|
||||||
|
insertBefore(node, refNode) {
|
||||||
|
if (!refNode) return this.appendChild(node);
|
||||||
|
if (node.parentNode?.removeChild) node.parentNode.removeChild(node);
|
||||||
|
const idx = this.children.indexOf(refNode);
|
||||||
|
node.parentNode = this;
|
||||||
|
if (idx < 0) this.children.push(node);
|
||||||
|
else this.children.splice(idx, 0, node);
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
removeChild(child) {
|
||||||
|
const idx = this.children.indexOf(child);
|
||||||
|
if (idx >= 0) {
|
||||||
|
this.children.splice(idx, 1);
|
||||||
|
child.parentNode = null;
|
||||||
|
}
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
|
||||||
|
remove() {
|
||||||
|
if (this.parentNode?.removeChild) this.parentNode.removeChild(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
attachShadow() {
|
||||||
|
const sr = new MockDomNode('#shadow-root', null, this._domOptions);
|
||||||
|
sr.host = this;
|
||||||
|
this.shadowRoot = sr;
|
||||||
|
return sr;
|
||||||
|
}
|
||||||
|
|
||||||
|
contains(other) {
|
||||||
|
let cur = other;
|
||||||
|
while (cur) {
|
||||||
|
if (cur === this) return true;
|
||||||
|
cur = cur.parentNode;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
closest(sel) {
|
||||||
|
let cur = this;
|
||||||
|
while (cur && cur.nodeType === 1) {
|
||||||
|
if (cur.matches(sel)) return cur;
|
||||||
|
cur = cur.parentNode;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
addEventListener(type, fn) {
|
||||||
|
if (!this._listeners.has(type)) this._listeners.set(type, []);
|
||||||
|
this._listeners.get(type).push(fn);
|
||||||
|
}
|
||||||
|
|
||||||
|
removeEventListener(type, fn) {
|
||||||
|
const arr = this._listeners.get(type);
|
||||||
|
if (!arr) return;
|
||||||
|
const idx = arr.indexOf(fn);
|
||||||
|
if (idx >= 0) arr.splice(idx, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
dispatchEvent(ev) {
|
||||||
|
for (const fn of [...(this._listeners.get(ev.type) || [])]) fn(ev);
|
||||||
|
}
|
||||||
|
|
||||||
|
setRect(rect) {
|
||||||
|
this._ownRect = rect;
|
||||||
|
}
|
||||||
|
|
||||||
|
getBoundingClientRect() {
|
||||||
|
if (typeof this._domOptions?.resolveRect === 'function') {
|
||||||
|
const custom = this._domOptions.resolveRect(this);
|
||||||
|
if (custom) return custom;
|
||||||
|
}
|
||||||
|
if (this._ownRect) return this._ownRect;
|
||||||
|
if (this._rect) return this._rect;
|
||||||
|
if (this._domOptions?.inheritAncestorRect) {
|
||||||
|
let cur = this.parentNode || this.host || null;
|
||||||
|
while (cur) {
|
||||||
|
if (cur._ownRect) return cur._ownRect;
|
||||||
|
if (cur._rect) return cur._rect;
|
||||||
|
cur = cur.parentNode || cur.host || null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
this._domOptions?.defaultRect || {
|
||||||
|
left: 900,
|
||||||
|
right: 1080,
|
||||||
|
top: 6,
|
||||||
|
bottom: 32,
|
||||||
|
width: 180,
|
||||||
|
height: 26,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
matches(selector) {
|
||||||
|
const groups = splitTopLevelCommas(selector);
|
||||||
|
if (groups.length === 0) return false;
|
||||||
|
return groups.some((g) => {
|
||||||
|
const tokens = tokenizeCombinators(g);
|
||||||
|
if (tokens.length === 0) return false;
|
||||||
|
return matchChainFromScope(this, null, tokens, tokens.length - 1);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
querySelectorAll(selector) {
|
||||||
|
const groups = splitTopLevelCommas(selector);
|
||||||
|
if (groups.length === 0) return [];
|
||||||
|
const parsedGroups = groups.map(tokenizeCombinators).filter((t) => t.length > 0);
|
||||||
|
if (parsedGroups.length === 0) return [];
|
||||||
|
|
||||||
|
const out = [];
|
||||||
|
const walk = (root) => {
|
||||||
|
for (const child of root.children || []) {
|
||||||
|
if (
|
||||||
|
parsedGroups.some((tokens) =>
|
||||||
|
matchChainFromScope(child, this, tokens, tokens.length - 1)
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
out.push(child);
|
||||||
|
}
|
||||||
|
walk(child);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
walk(this);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
querySelector(selector) {
|
||||||
|
return this.querySelectorAll(selector)[0] || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
_find(pred) {
|
||||||
|
for (const c of this.children) {
|
||||||
|
if (pred(c)) return c;
|
||||||
|
const hit = c._find?.(pred);
|
||||||
|
if (hit) return hit;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMockDom({
|
||||||
|
rootRect = null,
|
||||||
|
defaultRect = null,
|
||||||
|
inheritAncestorRect = false,
|
||||||
|
resolveRect = null,
|
||||||
|
onCreateElement = null,
|
||||||
|
} = {}) {
|
||||||
|
const domOptions = { defaultRect, inheritAncestorRect, resolveRect };
|
||||||
|
const makeElement = (tag, rect = null) => {
|
||||||
|
const node = new MockDomNode(tag, rect, domOptions);
|
||||||
|
if (typeof onCreateElement === 'function') onCreateElement(node, tag);
|
||||||
|
return node;
|
||||||
|
};
|
||||||
|
|
||||||
|
const docRoot = makeElement('html', rootRect);
|
||||||
|
docRoot.isDocumentRoot = true;
|
||||||
|
const head = makeElement('head');
|
||||||
|
const body = makeElement('body', rootRect);
|
||||||
|
docRoot.appendChild(head);
|
||||||
|
docRoot.appendChild(body);
|
||||||
|
|
||||||
|
const docListeners = new Map();
|
||||||
|
const document = {
|
||||||
|
readyState: 'complete',
|
||||||
|
hidden: false,
|
||||||
|
activeElement: null,
|
||||||
|
documentElement: docRoot,
|
||||||
|
head,
|
||||||
|
body,
|
||||||
|
createElement: (tag) => makeElement(tag),
|
||||||
|
createElementNS: (_ns, tag) => makeElement(tag),
|
||||||
|
createTextNode: (txt) => {
|
||||||
|
const t = new MockDomNode('#text', null, domOptions);
|
||||||
|
t.textContent = String(txt ?? '');
|
||||||
|
return t;
|
||||||
|
},
|
||||||
|
getElementById: (id) => docRoot._find((n) => n.id === id),
|
||||||
|
querySelector: (sel) => docRoot.querySelector(sel),
|
||||||
|
querySelectorAll: (sel) => docRoot.querySelectorAll(sel),
|
||||||
|
addEventListener(type, fn) {
|
||||||
|
if (!docListeners.has(type)) docListeners.set(type, []);
|
||||||
|
docListeners.get(type).push(fn);
|
||||||
|
},
|
||||||
|
removeEventListener(type, fn) {
|
||||||
|
const arr = docListeners.get(type);
|
||||||
|
if (!arr) return;
|
||||||
|
const idx = arr.indexOf(fn);
|
||||||
|
if (idx >= 0) arr.splice(idx, 1);
|
||||||
|
},
|
||||||
|
dispatchEvent(ev) {
|
||||||
|
for (const fn of [...(docListeners.get(ev.type) || [])]) fn(ev);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return { docRoot, head, body, document, docListeners, makeElement };
|
||||||
|
}
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import fs from 'node:fs';
|
import { isEquivalentTelemetry } from '../src/store/telemetryStore.js';
|
||||||
import vm from 'node:vm';
|
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../trajectory-metrics.mjs';
|
||||||
import { extractModelSteps, normalizeCachedStep, MODEL_IDENTITY_VERSION } from '../speed-metrics.mjs';
|
|
||||||
import {
|
import {
|
||||||
formatUsd,
|
formatUsd,
|
||||||
mergeModelsByDisplayName,
|
mergeModelsByDisplayName,
|
||||||
@@ -11,7 +10,8 @@ import {
|
|||||||
import { backendHarness } from './backend-harness.mjs';
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
|
|
||||||
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
|
const FLASH = 'MODEL_PLACEHOLDER_M318', ARGON = 'MODEL_PLACEHOLDER_M418';
|
||||||
const createdAtMs = Date.now() - 20_000;
|
const PROMO_CLOCK_MS = Date.parse('2026-11-17T12:00:20Z');
|
||||||
|
const createdAtMs = PROMO_CLOCK_MS - 20_000;
|
||||||
function step(index, model, checkpoint = false) {
|
function step(index, model, checkpoint = false) {
|
||||||
return { type: checkpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
return { type: checkpoint ? 'CORTEX_STEP_TYPE_CHECKPOINT' : 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
status: 'CORTEX_STEP_STATUS_DONE', metadata: {
|
status: 'CORTEX_STEP_STATUS_DONE', metadata: {
|
||||||
@@ -22,7 +22,7 @@ function step(index, model, checkpoint = false) {
|
|||||||
} };
|
} };
|
||||||
}
|
}
|
||||||
async function payload(steps, options = {}) {
|
async function payload(steps, options = {}) {
|
||||||
return backendHarness({ summaries: { test: { stepCount: steps.length } },
|
return backendHarness({ clock: () => PROMO_CLOCK_MS, summaries: { test: { stepCount: steps.length } },
|
||||||
trajectories: { test: { trajectory: { steps } } }, ...options }).buildTelemetryPayloadInternal('test');
|
trajectories: { test: { trajectory: { steps } } }, ...options }).buildTelemetryPayloadInternal('test');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -135,7 +135,7 @@ test('upstream responseModel is preserved alongside placeholder modelKey for Ste
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('server model catalog overrides static placeholder mapping', () => {
|
test('server model catalog overrides static placeholder mapping', () => {
|
||||||
const {resolveModelInfo} = backendHarness();
|
const {resolveModelInfo} = backendHarness({ clock: () => PROMO_CLOCK_MS });
|
||||||
const result = resolveModelInfo(ARGON, new Map([[ARGON, {modelId:'gemini-3.8-flash-high', label:'Gemini 3.8 Flash (High)'}]]));
|
const result = resolveModelInfo(ARGON, new Map([[ARGON, {modelId:'gemini-3.8-flash-high', label:'Gemini 3.8 Flash (High)'}]]));
|
||||||
assert.equal(result.shortName,'flash-3.8-high'); assert.equal(result.pricing.input,0.75);
|
assert.equal(result.shortName,'flash-3.8-high'); assert.equal(result.pricing.input,0.75);
|
||||||
});
|
});
|
||||||
@@ -192,12 +192,9 @@ test('custom cost budget cannot claim a complete remaining percentage when price
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('frontend considers a model-only correction a real telemetry update', () => {
|
test('frontend considers a model-only correction a real telemetry update', () => {
|
||||||
const source = fs.readFileSync(new URL('../src/store/telemetryStore.js',import.meta.url),'utf8');
|
|
||||||
const fn = source.slice(source.indexOf('function isEquivalentTelemetry'),source.indexOf('export async function fetchTelemetry'));
|
|
||||||
const ctx = {}; vm.runInNewContext(fn+'\nglobalThis.compare=isEquivalentTelemetry;',ctx);
|
|
||||||
const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}};
|
const a={activeConversation:{recentSteps:[{modelKey:'unknown',modelShort:'模型未知',costUsd:null}]}};
|
||||||
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
|
const b=structuredClone(a); b.activeConversation.recentSteps[0].modelShort='new-model';
|
||||||
assert.equal(ctx.compare(a,b),false); assert.equal(ctx.compare(a,structuredClone(a)),true);
|
assert.equal(isEquivalentTelemetry(a,b),false); assert.equal(isEquivalentTelemetry(a,structuredClone(a)),true);
|
||||||
});
|
});
|
||||||
|
|
||||||
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
const ORCH_CARBON = 'MODEL_PLACEHOLDER_M667';
|
||||||
@@ -256,6 +253,7 @@ test('Orchestrator (Carbon) direct/planning and inferred compaction steps resolv
|
|||||||
|
|
||||||
test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is not misclassified as Carbon', async () => {
|
test('Orchestrator (Argon) resolves to orch-argon, annotates upstream ID, and is not misclassified as Carbon', async () => {
|
||||||
const h = backendHarness({
|
const h = backendHarness({
|
||||||
|
clock: () => PROMO_CLOCK_MS,
|
||||||
summaries: { test: { stepCount: 1 } },
|
summaries: { test: { stepCount: 1 } },
|
||||||
trajectories: {
|
trajectories: {
|
||||||
test: {
|
test: {
|
||||||
@@ -488,7 +486,7 @@ test('orchestratorIdMode defaults to compact, persists via settings action, and
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('historical placeholders (M15/M16/M47/M84/M132/M133/M264/M330) and verified internal routing slugs resolve and price accurately without wildcarding unknown slugs', () => {
|
test('historical placeholders (M15/M16/M47/M84/M132/M133/M264/M330) and verified internal routing slugs resolve and price accurately without wildcarding unknown slugs', () => {
|
||||||
const { resolveModelInfo } = backendHarness();
|
const { resolveModelInfo } = backendHarness({ clock: () => PROMO_CLOCK_MS });
|
||||||
|
|
||||||
const expectedPlaceholders = [
|
const expectedPlaceholders = [
|
||||||
['MODEL_PLACEHOLDER_M84', 'flash-3.5-high', 1.5, 9.0],
|
['MODEL_PLACEHOLDER_M84', 'flash-3.5-high', 1.5, 9.0],
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import fs from 'node:fs';
|
import { isEquivalentTelemetry } from '../src/store/telemetryStore.js';
|
||||||
import vm from 'node:vm';
|
|
||||||
import { backendHarness } from './backend-harness.mjs';
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
|
|
||||||
const FLASH = 'MODEL_PLACEHOLDER_M318';
|
const FLASH = 'MODEL_PLACEHOLDER_M318';
|
||||||
@@ -285,14 +284,9 @@ test('exhausted 0% bucket omitting remainingFraction in proto3 is reported as 10
|
|||||||
});
|
});
|
||||||
|
|
||||||
test('telemetryStore isEquivalentTelemetry detects quota changes in non-active pools', () => {
|
test('telemetryStore isEquivalentTelemetry detects quota changes in non-active pools', () => {
|
||||||
const source = fs.readFileSync(new URL('../src/store/telemetryStore.js', import.meta.url), 'utf8');
|
const compare = isEquivalentTelemetry;
|
||||||
const fn = source.slice(
|
|
||||||
source.indexOf('function isEquivalentTelemetry'),
|
|
||||||
source.indexOf('export async function fetchTelemetry')
|
|
||||||
);
|
|
||||||
const ctx = {};
|
|
||||||
vm.runInNewContext(fn + '\nglobalThis.compare=isEquivalentTelemetry;', ctx);
|
|
||||||
|
|
||||||
|
const ctx = { compare };
|
||||||
const a = {
|
const a = {
|
||||||
account: { tierName: 'Google AI Pro', planName: 'Pro' },
|
account: { tierName: 'Google AI Pro', planName: 'Pro' },
|
||||||
quotas: {
|
quotas: {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import test from 'node:test';
|
import test from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../speed-metrics.mjs';
|
import {extractContextBreakdown, extractLiveActivity, extractModelSteps, normalizeCachedStep, speedMetric, summarizeSpeed, summarizeTtft} from '../trajectory-metrics.mjs';
|
||||||
|
|
||||||
function sample({total=12,ttft='2s',stream='10s',output=1100,thinking=100,response=1000,
|
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'}={}) {
|
thinkingDuration='4s',tools=false,text=true,status='CORTEX_STEP_STATUS_DONE'}={}) {
|
||||||
|
|||||||
@@ -0,0 +1,788 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import http from 'node:http';
|
||||||
|
import { execFile } from 'node:child_process';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs';
|
||||||
|
import { backendHarness } from './backend-harness.mjs';
|
||||||
|
import { i18nStore } from '../src/i18n/index.js';
|
||||||
|
import {
|
||||||
|
formatAgentBadgeText,
|
||||||
|
formatAgentLabel,
|
||||||
|
resolveScopedConversation,
|
||||||
|
} from '../src/store/telemetryStore.js';
|
||||||
|
|
||||||
|
function encodeVarint(val) {
|
||||||
|
let v = BigInt(val);
|
||||||
|
if (v < 0n) v = BigInt.asUintN(64, v);
|
||||||
|
const out = [];
|
||||||
|
while (v >= 0x80n) {
|
||||||
|
out.push(Number((v & 0x7fn) | 0x80n));
|
||||||
|
v >>= 7n;
|
||||||
|
}
|
||||||
|
out.push(Number(v));
|
||||||
|
return Buffer.from(out);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeFieldVarint(fieldNo, val) {
|
||||||
|
return Buffer.concat([encodeVarint((fieldNo << 3) | 0), encodeVarint(val)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeFieldBytes(fieldNo, bufOrStr) {
|
||||||
|
const b = Buffer.isBuffer(bufOrStr) ? bufOrStr : Buffer.from(String(bufOrStr), 'utf8');
|
||||||
|
return Buffer.concat([encodeVarint((fieldNo << 3) | 2), encodeVarint(b.length), b]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeTimestamp(sec, nanos = 0) {
|
||||||
|
return Buffer.concat([encodeFieldVarint(1, sec), ...(nanos ? [encodeFieldVarint(2, nanos)] : [])]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeStepMeta({
|
||||||
|
createdSec,
|
||||||
|
finishedSec,
|
||||||
|
stepIndex,
|
||||||
|
originCascadeId = '',
|
||||||
|
modelEnumInt = 0,
|
||||||
|
inputTokens = 0,
|
||||||
|
cacheReadTokens = 0,
|
||||||
|
outputTokens = 0,
|
||||||
|
thinkingTokens = 0,
|
||||||
|
responseTokens = 0,
|
||||||
|
}) {
|
||||||
|
const parts = [encodeFieldBytes(1, encodeTimestamp(createdSec))];
|
||||||
|
if (finishedSec) {
|
||||||
|
parts.push(encodeFieldBytes(7, encodeTimestamp(finishedSec)));
|
||||||
|
}
|
||||||
|
if (modelEnumInt || inputTokens || cacheReadTokens || outputTokens) {
|
||||||
|
const muParts = [];
|
||||||
|
if (modelEnumInt) muParts.push(encodeFieldVarint(1, modelEnumInt));
|
||||||
|
if (inputTokens) muParts.push(encodeFieldVarint(2, inputTokens));
|
||||||
|
if (outputTokens) muParts.push(encodeFieldVarint(3, outputTokens));
|
||||||
|
if (cacheReadTokens) muParts.push(encodeFieldVarint(5, cacheReadTokens));
|
||||||
|
muParts.push(encodeFieldVarint(6, 24)); // API_PROVIDER_GOOGLE_GEMINI
|
||||||
|
if (thinkingTokens) muParts.push(encodeFieldVarint(9, thinkingTokens));
|
||||||
|
if (responseTokens) muParts.push(encodeFieldVarint(10, responseTokens));
|
||||||
|
parts.push(encodeFieldBytes(9, Buffer.concat(muParts)));
|
||||||
|
}
|
||||||
|
const siParts = [encodeFieldVarint(2, stepIndex)];
|
||||||
|
if (originCascadeId) {
|
||||||
|
siParts.push(encodeFieldBytes(4, originCascadeId));
|
||||||
|
}
|
||||||
|
parts.push(encodeFieldBytes(20, Buffer.concat(siParts)));
|
||||||
|
return Buffer.concat(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeUserInputPayload(text) {
|
||||||
|
return encodeFieldBytes(19, encodeFieldBytes(2, text));
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodePlannerResponsePayload(text) {
|
||||||
|
return encodeFieldBytes(20, encodeFieldBytes(1, text));
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeGenMeta({
|
||||||
|
stepIndex,
|
||||||
|
cascadeId,
|
||||||
|
responseModel,
|
||||||
|
modelDisplayName,
|
||||||
|
estimatedTokensUsed = 0,
|
||||||
|
maxContextTokens = 256000,
|
||||||
|
userMsgTokens = 0,
|
||||||
|
}) {
|
||||||
|
const groups = [];
|
||||||
|
if (userMsgTokens > 0) {
|
||||||
|
const child = Buffer.concat([
|
||||||
|
encodeFieldBytes(1, '0: USER_INPUT'),
|
||||||
|
encodeFieldVarint(3, userMsgTokens),
|
||||||
|
]);
|
||||||
|
const topGroup = Buffer.concat([
|
||||||
|
encodeFieldBytes(1, 'Chat Messages'),
|
||||||
|
encodeFieldVarint(2, 7), // TOKEN_TYPE_CHAT_MESSAGES
|
||||||
|
encodeFieldVarint(4, userMsgTokens),
|
||||||
|
encodeFieldBytes(5, child),
|
||||||
|
]);
|
||||||
|
groups.push(encodeFieldBytes(1, topGroup));
|
||||||
|
}
|
||||||
|
const cwParts = [];
|
||||||
|
if (estimatedTokensUsed > 0) cwParts.push(encodeFieldVarint(1, estimatedTokensUsed));
|
||||||
|
if (groups.length > 0) cwParts.push(encodeFieldBytes(3, Buffer.concat(groups)));
|
||||||
|
if (maxContextTokens > 0) cwParts.push(encodeFieldVarint(4, maxContextTokens));
|
||||||
|
|
||||||
|
const mapCascade = Buffer.concat([
|
||||||
|
encodeFieldBytes(1, 'cascade_id'),
|
||||||
|
encodeFieldBytes(2, cascadeId),
|
||||||
|
]);
|
||||||
|
const chatParts = [
|
||||||
|
encodeFieldBytes(9, encodeFieldBytes(10, Buffer.concat(cwParts))),
|
||||||
|
encodeFieldBytes(11, encodeTimestamp(1, 0)), // 1s TTFT
|
||||||
|
encodeFieldBytes(19, responseModel),
|
||||||
|
encodeFieldBytes(20, mapCascade),
|
||||||
|
encodeFieldBytes(21, modelDisplayName),
|
||||||
|
];
|
||||||
|
return Buffer.concat([
|
||||||
|
encodeFieldVarint(2, stepIndex),
|
||||||
|
encodeFieldBytes(1, Buffer.concat(chatParts)),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodeSummaryBlob({
|
||||||
|
title = '',
|
||||||
|
stepCount = 0,
|
||||||
|
lastModSec = 0,
|
||||||
|
statusInt = 1,
|
||||||
|
trajectoryType = 0,
|
||||||
|
forkParentId = '',
|
||||||
|
sideQuestionIds = [],
|
||||||
|
sideQuestionTitles = {},
|
||||||
|
parentConversationId = '',
|
||||||
|
subagentSpec = null,
|
||||||
|
}) {
|
||||||
|
const parts = [];
|
||||||
|
if (stepCount > 0) parts.push(encodeFieldVarint(2, stepCount));
|
||||||
|
if (lastModSec > 0) parts.push(encodeFieldBytes(3, encodeTimestamp(lastModSec)));
|
||||||
|
if (statusInt > 0) parts.push(encodeFieldVarint(5, statusInt));
|
||||||
|
|
||||||
|
const annParts = [];
|
||||||
|
if (title) annParts.push(encodeFieldBytes(1, title));
|
||||||
|
for (const sqId of sideQuestionIds) {
|
||||||
|
annParts.push(encodeFieldBytes(17, sqId));
|
||||||
|
}
|
||||||
|
for (const [k, v] of Object.entries(sideQuestionTitles)) {
|
||||||
|
annParts.push(
|
||||||
|
encodeFieldBytes(18, Buffer.concat([encodeFieldBytes(1, k), encodeFieldBytes(2, v)]))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (annParts.length > 0) parts.push(encodeFieldBytes(15, Buffer.concat(annParts)));
|
||||||
|
|
||||||
|
if (parentConversationId || subagentSpec) {
|
||||||
|
const tmParts = [];
|
||||||
|
if (parentConversationId) tmParts.push(encodeFieldBytes(5, parentConversationId));
|
||||||
|
if (subagentSpec) {
|
||||||
|
const specParts = [];
|
||||||
|
if (subagentSpec.typeName) specParts.push(encodeFieldBytes(1, subagentSpec.typeName));
|
||||||
|
if (subagentSpec.role) specParts.push(encodeFieldBytes(2, subagentSpec.role));
|
||||||
|
tmParts.push(encodeFieldBytes(8, Buffer.concat(specParts)));
|
||||||
|
}
|
||||||
|
parts.push(encodeFieldBytes(17, Buffer.concat(tmParts)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trajectoryType > 0) parts.push(encodeFieldVarint(22, trajectoryType));
|
||||||
|
if (forkParentId) parts.push(encodeFieldBytes(24, forkParentId));
|
||||||
|
return Buffer.concat(parts);
|
||||||
|
}
|
||||||
|
|
||||||
|
test('Hybrid SQLite+WAL mode skips trajectory RPCs for local DBs, falls back to RPC when DB is absent, deduplicates cloned Side Question steps, protects mainline context, and renders zh/en badges', async (t) => {
|
||||||
|
const sqliteMod =
|
||||||
|
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||||
|
if (!sqliteMod?.DatabaseSync) {
|
||||||
|
t.skip('node:sqlite DatabaseSync unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { DatabaseSync } = sqliteMod;
|
||||||
|
const tempRoot = mkdtempSync(join(tmpdir(), 'agy-hybrid-sqlite-'));
|
||||||
|
|
||||||
|
const mainCid = '11111111-1111-4111-8111-111111111111';
|
||||||
|
const subCid = '22222222-2222-4222-8222-222222222222';
|
||||||
|
const sideCid = '33333333-3333-4333-8333-333333333333';
|
||||||
|
const emptySideCid = '44444444-4444-4444-8444-444444444444';
|
||||||
|
const rpcOnlyCid = '55555555-5555-4555-8555-555555555555';
|
||||||
|
|
||||||
|
// Use promo-period timestamp: 2026-11-18T00:00:00Z = 1794960000
|
||||||
|
const baseSec = Math.floor(Date.parse('2026-11-18T00:00:00Z') / 1000);
|
||||||
|
const rpcCalls = [];
|
||||||
|
|
||||||
|
const mockLsServer = http.createServer((req, res) => {
|
||||||
|
let rawBody = '';
|
||||||
|
req.on('data', (chunk) => {
|
||||||
|
rawBody += chunk;
|
||||||
|
});
|
||||||
|
req.on('end', () => {
|
||||||
|
const method = req.url.split('/').pop();
|
||||||
|
const body = rawBody ? JSON.parse(rawBody) : {};
|
||||||
|
rpcCalls.push({ method, cascadeId: body.cascadeId || '' });
|
||||||
|
|
||||||
|
res.setHeader('Content-Type', 'application/json');
|
||||||
|
if (method === 'GetUserStatus') {
|
||||||
|
res.end(JSON.stringify({ userStatus: { email: 'dev@example.com' } }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (method === 'RetrieveUserQuotaSummary') {
|
||||||
|
res.end(JSON.stringify({ response: { groups: [] } }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (method === 'GetAvailableModels') {
|
||||||
|
res.end(JSON.stringify({ response: { models: {} } }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (method === 'GetCascadeTrajectory' && body.cascadeId === rpcOnlyCid) {
|
||||||
|
res.end(
|
||||||
|
JSON.stringify({
|
||||||
|
numTotalSteps: 2,
|
||||||
|
trajectory: {
|
||||||
|
steps: [
|
||||||
|
{
|
||||||
|
// Cloned step from mainCid over RPC — must ALSO be stripped by filterClonedTrajectorySteps!
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: new Date((baseSec + 50) * 1000).toISOString(),
|
||||||
|
finishedGeneratingAt: new Date((baseSec + 54) * 1000).toISOString(),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 0, cascadeId: mainCid },
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M429',
|
||||||
|
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inputTokens: '5000000',
|
||||||
|
cacheReadTokens: '0',
|
||||||
|
outputTokens: '0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: new Date((baseSec + 100) * 1000).toISOString(),
|
||||||
|
finishedGeneratingAt: new Date((baseSec + 102) * 1000).toISOString(),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1, cascadeId: rpcOnlyCid },
|
||||||
|
modelUsage: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M320', // gemini-3.8-flash-low: $0.30/M input
|
||||||
|
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||||
|
inputTokens: '1000000',
|
||||||
|
cacheReadTokens: '0',
|
||||||
|
outputTokens: '0',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res.statusCode = 500;
|
||||||
|
res.end(JSON.stringify({ error: `unexpected RPC ${method}` }));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await new Promise((resolve) => mockLsServer.listen(0, '127.0.0.1', resolve));
|
||||||
|
const lsPort = mockLsServer.address().port;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const agyDir = join(tempRoot, 'antigravity');
|
||||||
|
const convDir = join(agyDir, 'conversations');
|
||||||
|
mkdirSync(convDir, { recursive: true });
|
||||||
|
|
||||||
|
// 1. Build conversation_summaries.db in WAL mode
|
||||||
|
const sumDbPath = join(agyDir, 'conversation_summaries.db');
|
||||||
|
const sumDb = new DatabaseSync(sumDbPath);
|
||||||
|
sumDb.exec(`
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
CREATE TABLE conversation_summaries (
|
||||||
|
conversation_id TEXT PRIMARY KEY,
|
||||||
|
title TEXT,
|
||||||
|
preview TEXT,
|
||||||
|
status TEXT,
|
||||||
|
source TEXT,
|
||||||
|
parent_conversation_id TEXT,
|
||||||
|
nesting_depth INTEGER,
|
||||||
|
agent_name TEXT,
|
||||||
|
not_fully_idle INTEGER,
|
||||||
|
killed INTEGER,
|
||||||
|
step_count INTEGER,
|
||||||
|
last_modified_time TEXT,
|
||||||
|
app_data_dir TEXT,
|
||||||
|
raw_summary BLOB
|
||||||
|
);
|
||||||
|
CREATE TABLE conversation_parents (
|
||||||
|
conversation_id TEXT,
|
||||||
|
parent_id TEXT
|
||||||
|
);
|
||||||
|
`);
|
||||||
|
|
||||||
|
const insSum = sumDb.prepare(`
|
||||||
|
INSERT INTO conversation_summaries (
|
||||||
|
conversation_id, title, status, parent_conversation_id, step_count, last_modified_time, app_data_dir, raw_summary
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, 'antigravity', ?)
|
||||||
|
`);
|
||||||
|
|
||||||
|
insSum.run(
|
||||||
|
mainCid,
|
||||||
|
'Main Architecture Task',
|
||||||
|
'CASCADE_RUN_STATUS_IDLE',
|
||||||
|
'',
|
||||||
|
2,
|
||||||
|
'2026-11-18T00:01:35Z',
|
||||||
|
encodeSummaryBlob({
|
||||||
|
title: 'Main Architecture Task',
|
||||||
|
stepCount: 2,
|
||||||
|
lastModSec: baseSec + 95,
|
||||||
|
sideQuestionIds: [sideCid, emptySideCid],
|
||||||
|
sideQuestionTitles: { [sideCid]: '为什么用 WAL 模式?' },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
insSum.run(
|
||||||
|
subCid,
|
||||||
|
'SQLite Researcher',
|
||||||
|
'CASCADE_RUN_STATUS_IDLE',
|
||||||
|
mainCid,
|
||||||
|
2,
|
||||||
|
'2026-11-18T00:01:10Z',
|
||||||
|
encodeSummaryBlob({
|
||||||
|
title: 'SQLite Researcher',
|
||||||
|
stepCount: 2,
|
||||||
|
lastModSec: baseSec + 70,
|
||||||
|
parentConversationId: mainCid,
|
||||||
|
subagentSpec: { typeName: 'research', role: 'SQLite Researcher' },
|
||||||
|
})
|
||||||
|
);
|
||||||
|
insSum.run(
|
||||||
|
sideCid,
|
||||||
|
'',
|
||||||
|
'CASCADE_RUN_STATUS_IDLE',
|
||||||
|
'',
|
||||||
|
4,
|
||||||
|
'2026-11-18T00:02:00Z',
|
||||||
|
encodeSummaryBlob({
|
||||||
|
stepCount: 4,
|
||||||
|
lastModSec: baseSec + 120,
|
||||||
|
trajectoryType: 22,
|
||||||
|
forkParentId: mainCid,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
insSum.run(
|
||||||
|
emptySideCid,
|
||||||
|
'',
|
||||||
|
'CASCADE_RUN_STATUS_IDLE',
|
||||||
|
'',
|
||||||
|
2,
|
||||||
|
'2026-11-18T00:01:30Z',
|
||||||
|
encodeSummaryBlob({
|
||||||
|
stepCount: 2,
|
||||||
|
lastModSec: baseSec + 90,
|
||||||
|
trajectoryType: 22,
|
||||||
|
forkParentId: mainCid,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
// rpcOnlyCid is present in summaries, but has NO local .db file -> must fall back to GetCascadeTrajectory RPC!
|
||||||
|
insSum.run(
|
||||||
|
rpcOnlyCid,
|
||||||
|
'Remote WSL Session',
|
||||||
|
'CASCADE_RUN_STATUS_IDLE',
|
||||||
|
'',
|
||||||
|
1,
|
||||||
|
'2026-11-18T00:00:30Z',
|
||||||
|
encodeSummaryBlob({
|
||||||
|
title: 'Remote WSL Session',
|
||||||
|
stepCount: 1,
|
||||||
|
lastModSec: baseSec + 30,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
sumDb.prepare('INSERT INTO conversation_parents (conversation_id, parent_id) VALUES (?, ?)').run(sideCid, mainCid);
|
||||||
|
sumDb.close();
|
||||||
|
|
||||||
|
const initConvDb = (cid, trajectoryType = 1) => {
|
||||||
|
const db = new DatabaseSync(join(convDir, `${cid}.db`));
|
||||||
|
db.exec(`
|
||||||
|
PRAGMA journal_mode = WAL;
|
||||||
|
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||||
|
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||||
|
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||||
|
`);
|
||||||
|
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, ?, 1)').run(cid, cid, trajectoryType);
|
||||||
|
return db;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 2. Main conversation DB: 1 USER_INPUT ("设计混合 SQLite 读取") + 1 Carbon High response ($12.10, context 120k/256k)
|
||||||
|
const mainDb = initConvDb(mainCid, 1);
|
||||||
|
mainDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: mainCid }),
|
||||||
|
encodeUserInputPayload('设计混合 SQLite 读取')
|
||||||
|
);
|
||||||
|
mainDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: baseSec + 50,
|
||||||
|
finishedSec: baseSec + 54,
|
||||||
|
stepIndex: 1,
|
||||||
|
originCascadeId: mainCid,
|
||||||
|
modelEnumInt: 1429, // MODEL_PLACEHOLDER_M429 -> Carbon High ($2 + $0.1 + $10 = $12.10)
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
cacheReadTokens: 1_000_000,
|
||||||
|
outputTokens: 1_000_000,
|
||||||
|
thinkingTokens: 400_000,
|
||||||
|
responseTokens: 600_000,
|
||||||
|
}),
|
||||||
|
encodePlannerResponsePayload('这是混合架构方案。')
|
||||||
|
);
|
||||||
|
mainDb
|
||||||
|
.prepare('INSERT INTO gen_metadata VALUES (0, ?)')
|
||||||
|
.run(
|
||||||
|
encodeGenMeta({
|
||||||
|
stepIndex: 1,
|
||||||
|
cascadeId: mainCid,
|
||||||
|
responseModel: 'gemini-4-carbon-high',
|
||||||
|
modelDisplayName: 'Gemini 4 Carbon (High)',
|
||||||
|
estimatedTokensUsed: 120_000,
|
||||||
|
maxContextTokens: 256_000,
|
||||||
|
userMsgTokens: 120_000,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
mainDb.close();
|
||||||
|
|
||||||
|
// 3. Regular subagent DB: 1 Flash 3.8 Low step ($0.30)
|
||||||
|
const subDb = initConvDb(subCid, 1);
|
||||||
|
subDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({ createdSec: baseSec + 10, stepIndex: 0, originCascadeId: subCid }),
|
||||||
|
encodeUserInputPayload('调研 SQLite WAL')
|
||||||
|
);
|
||||||
|
subDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: baseSec + 11,
|
||||||
|
finishedSec: baseSec + 13,
|
||||||
|
stepIndex: 1,
|
||||||
|
originCascadeId: subCid,
|
||||||
|
modelEnumInt: 1320, // MODEL_PLACEHOLDER_M320 -> $0.30/1M input
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
}),
|
||||||
|
encodePlannerResponsePayload('WAL 调研完毕')
|
||||||
|
);
|
||||||
|
subDb.close();
|
||||||
|
|
||||||
|
// 4. Side Question DB (trajectory_type = 22):
|
||||||
|
// Contains 2 CLONED parent steps from mainCid ($12.10) + 1 own USER_INPUT + 1 own Flash 3.8 High step ($0.75)
|
||||||
|
// Context watermark in Side Question is tiny (15k) and later than mainCid — must NOT overwrite mainCid's context!
|
||||||
|
const sideDb = initConvDb(sideCid, 22);
|
||||||
|
sideDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (0, 14, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({ createdSec: baseSec + 1, stepIndex: 0, originCascadeId: mainCid }),
|
||||||
|
encodeUserInputPayload('设计混合 SQLite 读取')
|
||||||
|
);
|
||||||
|
sideDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (1, 15, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: baseSec + 50,
|
||||||
|
finishedSec: baseSec + 54,
|
||||||
|
stepIndex: 1,
|
||||||
|
originCascadeId: mainCid, // CLONED FROM PARENT! Must be filtered out!
|
||||||
|
modelEnumInt: 1429,
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
cacheReadTokens: 1_000_000,
|
||||||
|
outputTokens: 1_000_000,
|
||||||
|
}),
|
||||||
|
encodePlannerResponsePayload('克隆的父回复')
|
||||||
|
);
|
||||||
|
sideDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (2, 14, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({ createdSec: baseSec + 80, stepIndex: 2, originCascadeId: sideCid }),
|
||||||
|
encodeUserInputPayload('顺便问下为什么用 WAL?')
|
||||||
|
);
|
||||||
|
sideDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (3, 15, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: baseSec + 81,
|
||||||
|
finishedSec: baseSec + 83,
|
||||||
|
stepIndex: 3,
|
||||||
|
originCascadeId: sideCid,
|
||||||
|
modelEnumInt: 1318, // MODEL_PLACEHOLDER_M318 -> $0.75/1M input
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
}),
|
||||||
|
encodePlannerResponsePayload('因为只读不阻塞 checkpoint。')
|
||||||
|
);
|
||||||
|
sideDb
|
||||||
|
.prepare('INSERT INTO gen_metadata VALUES (0, ?)')
|
||||||
|
.run(
|
||||||
|
encodeGenMeta({
|
||||||
|
stepIndex: 1,
|
||||||
|
cascadeId: mainCid, // Cloned gen_metadata from parent!
|
||||||
|
responseModel: 'gemini-4-carbon-high',
|
||||||
|
modelDisplayName: 'Gemini 4 Carbon (High)',
|
||||||
|
estimatedTokensUsed: 120_000,
|
||||||
|
maxContextTokens: 256_000,
|
||||||
|
userMsgTokens: 120_000,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
sideDb
|
||||||
|
.prepare('INSERT INTO gen_metadata VALUES (1, ?)')
|
||||||
|
.run(
|
||||||
|
encodeGenMeta({
|
||||||
|
stepIndex: 3,
|
||||||
|
cascadeId: sideCid,
|
||||||
|
responseModel: 'gemini-3.8-flash-high',
|
||||||
|
modelDisplayName: 'Gemini 3.8 Flash (High)',
|
||||||
|
estimatedTokensUsed: 15_000,
|
||||||
|
maxContextTokens: 256_000,
|
||||||
|
userMsgTokens: 15_000,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
sideDb.close();
|
||||||
|
|
||||||
|
// 5. Empty Side Question DB: only cloned parent steps, 0 own steps -> must be hidden!
|
||||||
|
const emptySideDb = initConvDb(emptySideCid, 22);
|
||||||
|
emptySideDb
|
||||||
|
.prepare('INSERT INTO steps VALUES (0, 15, 3, ?, ?)')
|
||||||
|
.run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: baseSec + 2,
|
||||||
|
finishedSec: baseSec + 6,
|
||||||
|
stepIndex: 1,
|
||||||
|
originCascadeId: mainCid,
|
||||||
|
modelEnumInt: 1429,
|
||||||
|
inputTokens: 1_000_000,
|
||||||
|
}),
|
||||||
|
null
|
||||||
|
);
|
||||||
|
emptySideDb.close();
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile);
|
||||||
|
const builderUrl = new URL('../backend/telemetry-builder.mjs', import.meta.url).href;
|
||||||
|
const { stdout: rawJson } = await execFileAsync(
|
||||||
|
process.execPath,
|
||||||
|
[
|
||||||
|
'--input-type=module',
|
||||||
|
'-e',
|
||||||
|
`const { buildTelemetryPayload } = await import(${JSON.stringify(builderUrl)});
|
||||||
|
const p = await buildTelemetryPayload(${JSON.stringify(mainCid)}, false, { range: 'all' });
|
||||||
|
process.stdout.write(JSON.stringify(p));`,
|
||||||
|
],
|
||||||
|
{
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
ANTIGRAVITY_GEMINI_DIR: tempRoot,
|
||||||
|
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||||
|
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||||
|
ANTIGRAVITY_EXECUTABLE_DATA_DIR: '',
|
||||||
|
USAGE_MONITOR_DATA_DIR: join(tempRoot, 'sidecar-data'),
|
||||||
|
ANTIGRAVITY_LS_ADDRESS: `127.0.0.1:${lsPort}`,
|
||||||
|
ANTIGRAVITY_CSRF_TOKEN: 'test-csrf',
|
||||||
|
},
|
||||||
|
encoding: 'utf8',
|
||||||
|
maxBuffer: 16 * 1024 * 1024,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const payload = JSON.parse(rawJson);
|
||||||
|
|
||||||
|
// A. Verify RPC calls: ZERO GetAllCascadeTrajectories, ZERO GetCascadeTrajectory for local SQLite DBs,
|
||||||
|
// and exactly ONE GetCascadeTrajectory fallback for rpcOnlyCid!
|
||||||
|
assert.equal(
|
||||||
|
rpcCalls.some((c) => c.method === 'GetAllCascadeTrajectories'),
|
||||||
|
false,
|
||||||
|
'local conversation_summaries.db must eliminate GetAllCascadeTrajectories RPC'
|
||||||
|
);
|
||||||
|
const trajRpcTargets = rpcCalls
|
||||||
|
.filter((c) => c.method === 'GetCascadeTrajectory')
|
||||||
|
.map((c) => c.cascadeId);
|
||||||
|
assert.deepEqual(
|
||||||
|
trajRpcTargets,
|
||||||
|
[rpcOnlyCid],
|
||||||
|
'only conversation missing local .db falls back to GetCascadeTrajectory RPC'
|
||||||
|
);
|
||||||
|
|
||||||
|
// B. Top-level conversations list contains ONLY mainCid and rpcOnlyCid (no orphan/empty side questions or subagents)
|
||||||
|
assert.deepEqual(
|
||||||
|
payload.conversations.map((c) => c.cascadeId).sort(),
|
||||||
|
[mainCid, rpcOnlyCid].sort()
|
||||||
|
);
|
||||||
|
|
||||||
|
// C. Verify Turn Rail prompt decoded directly from SQLite USER_INPUT step_payload
|
||||||
|
const mainUnit = payload.activeConversation.agents.find((a) => a.isMain);
|
||||||
|
assert.ok(mainUnit);
|
||||||
|
assert.equal(payload.activeConversation.recentSteps[0].turnPrompt, '设计混合 SQLite 读取');
|
||||||
|
|
||||||
|
// D. Verify agents under mainCid: [main, subagent #1, side question #1] (emptySideCid hidden!)
|
||||||
|
const agents = payload.activeConversation.agents;
|
||||||
|
assert.equal(agents.length, 3);
|
||||||
|
assert.equal(agents[1].badgeText, '子1');
|
||||||
|
assert.equal(Boolean(agents[1].isSideQuestion), false);
|
||||||
|
assert.equal(agents[2].badgeText, '旁1');
|
||||||
|
assert.equal(agents[2].isSideQuestion, true);
|
||||||
|
assert.equal(agents[2].sideIndex, 1);
|
||||||
|
assert.equal(agents[2].role, '为什么用 WAL 模式?');
|
||||||
|
assert.equal(agents[2].stepCount, 1, 'cloned parent steps must be stripped from Side Question');
|
||||||
|
assert.equal(agents[2].sessionCostUsd, 0.75, 'Side Question bills ONLY its own step ($0.75), never parent ($12.10)');
|
||||||
|
|
||||||
|
// E. Verify total session & account costs have ZERO double-counting:
|
||||||
|
// Session (main $12.10 + sub $0.30 + sideQ $0.75) = $13.15
|
||||||
|
// Account (session $13.15 + rpcOnlyCid $0.30) = $13.45
|
||||||
|
assert.equal(payload.activeConversation.aggregated.sessionCostUsd, 13.15);
|
||||||
|
assert.equal(payload.consumption.account.costUsd, 13.45);
|
||||||
|
assert.equal(payload.activeConversation.aggregated.role, '主代理 + 1 子代理 + 1 旁问');
|
||||||
|
|
||||||
|
// F. Verify mainline context watermark protection (backend aggregated + frontend auto-follow)
|
||||||
|
// Main agent has 3_000_000 tokens (1M in + 1M cache + 1M out), Side Question has 15_000/1_000_000
|
||||||
|
assert.equal(payload.activeConversation.aggregated.activeAgentId, 'main');
|
||||||
|
assert.equal(payload.activeConversation.aggregated.context.totalTokens, mainUnit.context.totalTokens);
|
||||||
|
|
||||||
|
const scopedAuto = resolveScopedConversation(payload, 'all', 'auto', true);
|
||||||
|
assert.equal(scopedAuto.ctxAgent.agentId, 'main', 'auto context inspector locks onto mainline agent');
|
||||||
|
const scopedExplicitSide = resolveScopedConversation(payload, 'all', sideCid, false);
|
||||||
|
assert.equal(scopedExplicitSide.ctxAgent.agentId, sideCid, 'explicitly selecting Side Question pill still inspects it');
|
||||||
|
|
||||||
|
// G. Verify zh-CN & en-US badge and label formatting
|
||||||
|
const prevLocale = i18nStore.getState().locale;
|
||||||
|
try {
|
||||||
|
i18nStore.setState({ locale: 'zh-CN', hostLocale: 'zh-CN' });
|
||||||
|
assert.equal(formatAgentBadgeText(agents[2]), '旁1');
|
||||||
|
assert.equal(formatAgentLabel(agents[2]), '旁路提问 #1 · 为什么用 WAL 模式?');
|
||||||
|
|
||||||
|
i18nStore.setState({ locale: 'en-US', hostLocale: 'en-US' });
|
||||||
|
assert.equal(formatAgentBadgeText(agents[1]), 'S1');
|
||||||
|
assert.equal(formatAgentBadgeText(agents[2]), 'Q1');
|
||||||
|
assert.equal(formatAgentLabel(agents[2]), 'Side Question #1 · 为什么用 WAL 模式?');
|
||||||
|
} finally {
|
||||||
|
i18nStore.setState({ locale: prevLocale });
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await new Promise((resolve) => mockLsServer.close(resolve));
|
||||||
|
rmSync(tempRoot, { recursive: true, force: true });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('persistTrajectoryCacheIfNeeded throttles RUNNING disk writes to 30s and flushes immediately on IDLE or cache rebuild', () => {
|
||||||
|
let now = 1_000_000;
|
||||||
|
const scheduled = new Map();
|
||||||
|
const h = backendHarness({
|
||||||
|
cache: { live: { title: 'Cached session', steps: [] } },
|
||||||
|
clock: () => now,
|
||||||
|
timerApi: {
|
||||||
|
setTimeout(_callback, delay) {
|
||||||
|
const id = Symbol();
|
||||||
|
scheduled.set(id, delay);
|
||||||
|
return id;
|
||||||
|
},
|
||||||
|
clearTimeout(id) {
|
||||||
|
scheduled.delete(id);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 1st save (lastSavedAtMs === 0) flushes immediately even while running
|
||||||
|
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
|
||||||
|
assert.equal(h.state.saves.length, 1);
|
||||||
|
assert.equal(h.hasPendingTrajectoryCacheSave(), false);
|
||||||
|
|
||||||
|
// Subsequent saves within 30s window while RUNNING are throttled in memory
|
||||||
|
now += 2_000;
|
||||||
|
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
|
||||||
|
now += 2_000;
|
||||||
|
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
|
||||||
|
assert.equal(h.state.saves.length, 1, '2s polling during RUNNING must not rewrite disk every tick');
|
||||||
|
assert.equal(h.hasPendingTrajectoryCacheSave(), true);
|
||||||
|
assert.deepEqual([...scheduled.values()], [28_000]);
|
||||||
|
|
||||||
|
// Transitioning to IDLE flushes immediately and clears pending timer
|
||||||
|
now += 2_000;
|
||||||
|
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: false, allowThrottleInTest: true });
|
||||||
|
assert.equal(h.state.saves.length, 2, 'transition to IDLE flushes immediately');
|
||||||
|
assert.equal(h.hasPendingTrajectoryCacheSave(), false);
|
||||||
|
assert.equal(scheduled.size, 0);
|
||||||
|
|
||||||
|
// Re-arming throttle then calling executeRebuildCacheAction cancels timer cleanly
|
||||||
|
now += 2_000;
|
||||||
|
h.persistTrajectoryCacheIfNeeded({ hasRunningSessions: true, allowThrottleInTest: true });
|
||||||
|
assert.equal(scheduled.size, 1);
|
||||||
|
h.state.cacheWriteError = new Error('Disk unavailable');
|
||||||
|
assert.equal(h.executeRebuildCacheAction().status, 500);
|
||||||
|
assert.equal(h.getCachedTrajectory('live').title, 'Cached session');
|
||||||
|
assert.equal(h.hasPendingTrajectoryCacheSave(), true);
|
||||||
|
assert.equal(scheduled.size, 1);
|
||||||
|
|
||||||
|
h.state.cacheWriteError = null;
|
||||||
|
const rebuildRes = h.executeRebuildCacheAction();
|
||||||
|
assert.equal(rebuildRes.ok, true);
|
||||||
|
assert.equal(scheduled.size, 0);
|
||||||
|
assert.equal(h.hasPendingTrajectoryCacheSave(), false);
|
||||||
|
assert.equal(h.listCachedTrajectoryEntries().length, 0);
|
||||||
|
assert.deepEqual(h.state.saves.at(-1).data, {});
|
||||||
|
});
|
||||||
|
|
||||||
|
test('SQLite trajectory reader scans backwards past trailing plannerConfig-only gen_metadata rows to preserve pre-compaction tokenBreakdown', (t) => {
|
||||||
|
const sqliteMod =
|
||||||
|
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||||
|
if (!sqliteMod?.DatabaseSync) {
|
||||||
|
t.skip('node:sqlite DatabaseSync unavailable');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const { DatabaseSync } = sqliteMod;
|
||||||
|
const tempRoot = mkdtempSync(join(tmpdir(), 'agy-sqlite-compact-'));
|
||||||
|
t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
||||||
|
|
||||||
|
const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||||
|
const dbPath = join(tempRoot, `${cid}.db`);
|
||||||
|
const db = new DatabaseSync(dbPath);
|
||||||
|
db.exec(`
|
||||||
|
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||||
|
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||||
|
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||||
|
`);
|
||||||
|
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid);
|
||||||
|
db.prepare('INSERT INTO steps VALUES (0, 15, 3, ?, NULL)').run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: 1794960010,
|
||||||
|
finishedSec: 1794960014,
|
||||||
|
stepIndex: 0,
|
||||||
|
originCascadeId: cid,
|
||||||
|
modelEnumInt: 1429,
|
||||||
|
inputTokens: 10000,
|
||||||
|
cacheReadTokens: 110000,
|
||||||
|
outputTokens: 500,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
// Step 1: CHECKPOINT compaction step (step_type = 23)
|
||||||
|
db.prepare('INSERT INTO steps VALUES (1, 23, 3, ?, NULL)').run(
|
||||||
|
encodeStepMeta({
|
||||||
|
createdSec: 1794960020,
|
||||||
|
finishedSec: 1794960024,
|
||||||
|
stepIndex: 1,
|
||||||
|
originCascadeId: cid,
|
||||||
|
modelEnumInt: 1429,
|
||||||
|
inputTokens: 10000,
|
||||||
|
cacheReadTokens: 110000,
|
||||||
|
outputTokens: 2400,
|
||||||
|
thinkingTokens: 400,
|
||||||
|
responseTokens: 2000,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// gen_metadata[0] has the full tokenBreakdown, followed by 3 plannerConfig-only records [1..3]
|
||||||
|
db.prepare('INSERT INTO gen_metadata VALUES (0, ?)').run(
|
||||||
|
encodeGenMeta({
|
||||||
|
stepIndex: 0,
|
||||||
|
cascadeId: cid,
|
||||||
|
responseModel: 'gemini-4-carbon-high',
|
||||||
|
modelDisplayName: 'Gemini 4 Carbon (High)',
|
||||||
|
estimatedTokensUsed: 120_000,
|
||||||
|
maxContextTokens: 384_000,
|
||||||
|
userMsgTokens: 120_000,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
const plannerOnlyBlob = encodeFieldBytes(3, encodeFieldBytes(28, 'gemini-4-carbon-high'));
|
||||||
|
db.prepare('INSERT INTO gen_metadata VALUES (1, ?)').run(plannerOnlyBlob);
|
||||||
|
db.prepare('INSERT INTO gen_metadata VALUES (2, ?)').run(plannerOnlyBlob);
|
||||||
|
db.prepare('INSERT INTO gen_metadata VALUES (3, ?)').run(plannerOnlyBlob);
|
||||||
|
db.close();
|
||||||
|
|
||||||
|
const res = readLocalSqliteTrajectory(dbPath, { cascadeId: cid });
|
||||||
|
assert.ok(res);
|
||||||
|
assert.equal(res.steps.length, 2);
|
||||||
|
assert.equal(res.steps[1].type, 'CORTEX_STEP_TYPE_CHECKPOINT');
|
||||||
|
const gm0 = res.generatorMetadata.find((g) => g.stepIndices.includes(0));
|
||||||
|
assert.ok(
|
||||||
|
gm0?.chatModel?.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown?.groups?.length > 0,
|
||||||
|
'must decode tokenBreakdown on gen_metadata[0] even with 3 trailing plannerConfig-only records'
|
||||||
|
);
|
||||||
|
});
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -667,6 +667,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
let turnCounter = 0;
|
let turnCounter = 0;
|
||||||
let activeTurnIndex = null;
|
let activeTurnIndex = null;
|
||||||
let pendingTurnPrompts = [];
|
let pendingTurnPrompts = [];
|
||||||
|
let pendingTurnHasMedia = false;
|
||||||
let hasUnconsumedTurn = false;
|
let hasUnconsumedTurn = false;
|
||||||
|
|
||||||
const isUserTurnBoundary = (step) => {
|
const isUserTurnBoundary = (step) => {
|
||||||
@@ -678,7 +679,7 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
return Boolean(step.userInput && typeof step.userInput === 'object');
|
return Boolean(step.userInput && typeof step.userInput === 'object');
|
||||||
};
|
};
|
||||||
|
|
||||||
const extractUserTurnPrompt = (step) => {
|
const extractUserTurnInfo = (step) => {
|
||||||
const ui = step?.userInput;
|
const ui = step?.userInput;
|
||||||
let raw = '';
|
let raw = '';
|
||||||
if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) {
|
if (typeof ui?.userResponse === 'string' && ui.userResponse.trim()) {
|
||||||
@@ -709,24 +710,35 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
? step.media
|
? step.media
|
||||||
: [];
|
: [];
|
||||||
const hasMedia = mediaArr.length > 0;
|
const hasMedia = mediaArr.length > 0;
|
||||||
if (!cleaned) {
|
const cleanText = cleaned.length > 180 ? `${cleaned.slice(0, 179)}…` : cleaned;
|
||||||
return hasMedia ? '[图片/附件提问]' : '';
|
const legacyRaw = !cleaned ? (hasMedia ? '[图片/附件提问]' : '') : hasMedia ? `${cleaned} [附图]` : cleaned;
|
||||||
}
|
const legacyPrompt = legacyRaw.length > 180 ? `${legacyRaw.slice(0, 179)}…` : legacyRaw;
|
||||||
const withMedia = hasMedia ? `${cleaned} [附图]` : cleaned;
|
return { cleanText, legacyPrompt, hasMedia };
|
||||||
return withMedia.length > 180 ? `${withMedia.slice(0, 179)}…` : withMedia;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let pendingTurnCleanPrompts = [];
|
||||||
rawSteps.forEach((s, index) => {
|
rawSteps.forEach((s, index) => {
|
||||||
if (isUserTurnBoundary(s)) {
|
if (isUserTurnBoundary(s)) {
|
||||||
const promptText = extractUserTurnPrompt(s);
|
const { cleanText, legacyPrompt, hasMedia } = extractUserTurnInfo(s);
|
||||||
if (!hasUnconsumedTurn) {
|
if (!hasUnconsumedTurn) {
|
||||||
hasUnconsumedTurn = true;
|
hasUnconsumedTurn = true;
|
||||||
pendingTurnPrompts = promptText ? [promptText] : [];
|
pendingTurnPrompts = legacyPrompt ? [legacyPrompt] : [];
|
||||||
} else if (
|
pendingTurnCleanPrompts = cleanText ? [cleanText] : [];
|
||||||
promptText &&
|
pendingTurnHasMedia = hasMedia;
|
||||||
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== promptText
|
} else {
|
||||||
) {
|
if (
|
||||||
pendingTurnPrompts.push(promptText);
|
legacyPrompt &&
|
||||||
|
pendingTurnPrompts[pendingTurnPrompts.length - 1] !== legacyPrompt
|
||||||
|
) {
|
||||||
|
pendingTurnPrompts.push(legacyPrompt);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
cleanText &&
|
||||||
|
pendingTurnCleanPrompts[pendingTurnCleanPrompts.length - 1] !== cleanText
|
||||||
|
) {
|
||||||
|
pendingTurnCleanPrompts.push(cleanText);
|
||||||
|
}
|
||||||
|
if (hasMedia) pendingTurnHasMedia = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -738,15 +750,25 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
|
|
||||||
let stepIsTurnStart = false;
|
let stepIsTurnStart = false;
|
||||||
let stepTurnPrompt = '';
|
let stepTurnPrompt = '';
|
||||||
|
let stepTurnPromptClean = '';
|
||||||
|
let stepTurnHasMedia = false;
|
||||||
|
let stepTurnMediaOnly = false;
|
||||||
if (hasUnconsumedTurn) {
|
if (hasUnconsumedTurn) {
|
||||||
turnCounter += 1;
|
turnCounter += 1;
|
||||||
activeTurnIndex = turnCounter;
|
activeTurnIndex = turnCounter;
|
||||||
stepIsTurnStart = true;
|
stepIsTurnStart = true;
|
||||||
const joinedPrompt = pendingTurnPrompts.join('\n').trim();
|
const joinedPrompt = pendingTurnPrompts.join('\n').trim();
|
||||||
|
const joinedClean = pendingTurnCleanPrompts.join('\n').trim();
|
||||||
stepTurnPrompt =
|
stepTurnPrompt =
|
||||||
joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt;
|
joinedPrompt.length > 180 ? `${joinedPrompt.slice(0, 179)}…` : joinedPrompt;
|
||||||
|
stepTurnPromptClean =
|
||||||
|
joinedClean.length > 180 ? `${joinedClean.slice(0, 179)}…` : joinedClean;
|
||||||
|
stepTurnHasMedia = pendingTurnHasMedia;
|
||||||
|
stepTurnMediaOnly = Boolean(pendingTurnHasMedia && !stepTurnPromptClean);
|
||||||
hasUnconsumedTurn = false;
|
hasUnconsumedTurn = false;
|
||||||
pendingTurnPrompts = [];
|
pendingTurnPrompts = [];
|
||||||
|
pendingTurnCleanPrompts = [];
|
||||||
|
pendingTurnHasMedia = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
const stepIndex = m.sourceTrajectoryStepInfo?.stepIndex ?? index;
|
||||||
@@ -917,6 +939,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
turnIndex: activeTurnIndex,
|
turnIndex: activeTurnIndex,
|
||||||
isTurnStart: stepIsTurnStart,
|
isTurnStart: stepIsTurnStart,
|
||||||
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
|
...(stepIsTurnStart && stepTurnPrompt ? { turnPrompt: stepTurnPrompt } : {}),
|
||||||
|
...(stepIsTurnStart && stepTurnPromptClean ? { turnPromptClean: stepTurnPromptClean } : {}),
|
||||||
|
...(stepIsTurnStart ? { turnHasMedia: stepTurnHasMedia, turnMediaOnly: stepTurnMediaOnly } : {}),
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1046,12 +1070,17 @@ export function inferCompactionStepModels(steps) {
|
|||||||
step.responseModel || (donorSameModel ? donor.responseModel || '' : '');
|
step.responseModel || (donorSameModel ? donor.responseModel || '' : '');
|
||||||
const nextDisplayName =
|
const nextDisplayName =
|
||||||
step.modelDisplayName || (donorSameModel ? donor.modelDisplayName || '' : '');
|
step.modelDisplayName || (donorSameModel ? donor.modelDisplayName || '' : '');
|
||||||
|
const nextMaxBudget =
|
||||||
|
!step.reportedContextLimitTokens && donor.maxContextBudgetTokens > 0
|
||||||
|
? donor.maxContextBudgetTokens
|
||||||
|
: step.maxContextBudgetTokens;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
nextModelKey === step.modelKey &&
|
nextModelKey === step.modelKey &&
|
||||||
nextModelSource === step.modelSource &&
|
nextModelSource === step.modelSource &&
|
||||||
nextResponseModel === (step.responseModel || '') &&
|
nextResponseModel === (step.responseModel || '') &&
|
||||||
nextDisplayName === (step.modelDisplayName || '')
|
nextDisplayName === (step.modelDisplayName || '') &&
|
||||||
|
nextMaxBudget === step.maxContextBudgetTokens
|
||||||
) {
|
) {
|
||||||
return step;
|
return step;
|
||||||
}
|
}
|
||||||
@@ -1062,6 +1091,7 @@ export function inferCompactionStepModels(steps) {
|
|||||||
modelSource: nextModelSource,
|
modelSource: nextModelSource,
|
||||||
responseModel: nextResponseModel,
|
responseModel: nextResponseModel,
|
||||||
modelDisplayName: nextDisplayName,
|
modelDisplayName: nextDisplayName,
|
||||||
|
maxContextBudgetTokens: nextMaxBudget,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -1591,7 +1621,11 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
rawName = 'edit_file';
|
rawName = 'edit_file';
|
||||||
} else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) {
|
} else if (stepType.includes('GREP_SEARCH') || fallbackStep?.grepSearch) {
|
||||||
rawName = 'grep_search';
|
rawName = 'grep_search';
|
||||||
} else if (stepType.includes('FIND_BY_NAME') || fallbackStep?.findByName) {
|
} else if (
|
||||||
|
stepType.includes('FIND_BY_NAME') ||
|
||||||
|
stepType === 'CORTEX_STEP_TYPE_FIND' ||
|
||||||
|
fallbackStep?.findByName
|
||||||
|
) {
|
||||||
rawName = 'find_by_name';
|
rawName = 'find_by_name';
|
||||||
} else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) {
|
} else if (stepType.includes('SEARCH_WEB') || fallbackStep?.searchWeb) {
|
||||||
rawName = 'search_web';
|
rawName = 'search_web';
|
||||||
@@ -1668,6 +1702,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
: summary || cmdSnippet || '';
|
: summary || cmdSnippet || '';
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'run_command',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '执行命令',
|
label: '执行命令',
|
||||||
detail,
|
detail,
|
||||||
@@ -1694,6 +1729,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
: '';
|
: '';
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'read_file',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '读取文件',
|
label: '读取文件',
|
||||||
detail: file ? `${file}${rangeSuffix}` : '',
|
detail: file ? `${file}${rangeSuffix}` : '',
|
||||||
@@ -1711,6 +1747,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'edit_file',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '修改文件',
|
label: '修改文件',
|
||||||
detail: file || '',
|
detail: file || '',
|
||||||
@@ -1723,6 +1760,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'write_file',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '写入文件',
|
label: '写入文件',
|
||||||
detail: file || '',
|
detail: file || '',
|
||||||
@@ -1738,6 +1776,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
: cleanSingleLineSnippet(query, 48) || searchPath || '';
|
: cleanSingleLineSnippet(query, 48) || searchPath || '';
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'grep_search',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '搜索代码',
|
label: '搜索代码',
|
||||||
detail,
|
detail,
|
||||||
@@ -1749,6 +1788,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path']));
|
const dir = shortBasename(pickField(['SearchDirectory', 'DirectoryPath', 'Path']));
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'find_file',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '查找文件',
|
label: '查找文件',
|
||||||
detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '',
|
detail: pattern && dir ? `${pattern} (${dir})` : pattern || dir || '',
|
||||||
@@ -1760,6 +1800,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const target = pickField(['query', 'Query', 'Url', 'url']);
|
const target = pickField(['query', 'Query', 'Url', 'url']);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: isUrl ? 'read_url' : 'search_web',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: isUrl ? '读取网页' : '网页搜索',
|
label: isUrl ? '读取网页' : '网页搜索',
|
||||||
detail: cleanSingleLineSnippet(target, 52) || '',
|
detail: cleanSingleLineSnippet(target, 52) || '',
|
||||||
@@ -1775,6 +1816,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
String(subSpec.typeName || '').trim();
|
String(subSpec.typeName || '').trim();
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'invoke_subagent',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '调用子代理',
|
label: '调用子代理',
|
||||||
detail: role || '',
|
detail: role || '',
|
||||||
@@ -1785,6 +1827,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const recipient = pickField(['Recipient', 'recipient']);
|
const recipient = pickField(['Recipient', 'recipient']);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'send_message',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '通信子代理',
|
label: '通信子代理',
|
||||||
detail: recipient ? recipient.slice(0, 8) : '',
|
detail: recipient ? recipient.slice(0, 8) : '',
|
||||||
@@ -1795,6 +1838,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const subName = pickField(['Name', 'Action', 'action']);
|
const subName = pickField(['Name', 'Action', 'action']);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'manage_subagents',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '管理子代理',
|
label: '管理子代理',
|
||||||
detail: subName || '',
|
detail: subName || '',
|
||||||
@@ -1806,6 +1850,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const taskId = pickField(['TaskId', 'taskId']);
|
const taskId = pickField(['TaskId', 'taskId']);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'manage_task',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '后台任务',
|
label: '后台任务',
|
||||||
detail: taskId ? `${action || 'status'} (${taskId})` : action || '',
|
detail: taskId ? `${action || 'status'} (${taskId})` : action || '',
|
||||||
@@ -1817,6 +1862,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const cron = pickField(['CronExpression']);
|
const cron = pickField(['CronExpression']);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'schedule',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '定时任务',
|
label: '定时任务',
|
||||||
detail: dur ? `${dur}s` : cron || '',
|
detail: dur ? `${dur}s` : cron || '',
|
||||||
@@ -1833,6 +1879,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
);
|
);
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'ask_question',
|
||||||
isAskUser: true,
|
isAskUser: true,
|
||||||
label: '等待用户选择',
|
label: '等待用户选择',
|
||||||
detail: cleanSingleLineSnippet(qText, 50) || '',
|
detail: cleanSingleLineSnippet(qText, 50) || '',
|
||||||
@@ -1844,6 +1891,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : '';
|
const q = Array.isArray(rawQueries) ? rawQueries.join(', ') : '';
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'search_marketplace',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '查询插件',
|
label: '查询插件',
|
||||||
detail: cleanSingleLineSnippet(q, 48) || '',
|
detail: cleanSingleLineSnippet(q, 48) || '',
|
||||||
@@ -1854,6 +1902,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · ');
|
const mcpClean = nameLower.replace(/^mcp[_-]/i, '').replace(/_/g, ' · ');
|
||||||
return {
|
return {
|
||||||
toolName: nameLower,
|
toolName: nameLower,
|
||||||
|
actionKey: 'mcp_tool',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '调用 MCP',
|
label: '调用 MCP',
|
||||||
detail: mcpClean || '',
|
detail: mcpClean || '',
|
||||||
@@ -1862,6 +1911,7 @@ export function summarizeToolCall(rawToolCall, fallbackStep = null) {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
toolName: nameLower || 'tool',
|
toolName: nameLower || 'tool',
|
||||||
|
actionKey: 'tool_call',
|
||||||
isAskUser: false,
|
isAskUser: false,
|
||||||
label: '调用工具',
|
label: '调用工具',
|
||||||
detail: nameLower || '',
|
detail: nameLower || '',
|
||||||
@@ -1909,6 +1959,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const startMs = Math.floor(fallbackStartMs || 0);
|
const startMs = Math.floor(fallbackStartMs || 0);
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'thinking',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '推理中',
|
label: '推理中',
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -1958,6 +2011,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
if (isCheckpointStep(lastStep)) {
|
if (isCheckpointStep(lastStep)) {
|
||||||
return {
|
return {
|
||||||
phase: 'compacting',
|
phase: 'compacting',
|
||||||
|
actionKey: 'compacting',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '上下文压缩',
|
label: '上下文压缩',
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -1979,11 +2035,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const phase = info.isAskUser ? 'waiting' : 'tool';
|
const phase = info.isAskUser ? 'waiting' : 'tool';
|
||||||
return {
|
return {
|
||||||
phase,
|
phase,
|
||||||
|
toolName: info.toolName,
|
||||||
|
actionKey: info.actionKey,
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: info.label,
|
label: info.label,
|
||||||
detail: info.detail,
|
detail: info.detail,
|
||||||
stepProgress,
|
stepProgress,
|
||||||
startedAtMs: startMs,
|
startedAtMs: startMs,
|
||||||
signature: `planner-tool:${lastStepId}:${tools.length}:${info.label}:${info.detail}`,
|
signature: `planner-tool:${lastStepId}:${tools.length}:${info.actionKey}:${info.detail}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1991,6 +2051,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const snippet = cleanSingleLineSnippet(respText, 52, true);
|
const snippet = cleanSingleLineSnippet(respText, 52, true);
|
||||||
return {
|
return {
|
||||||
phase: 'responding',
|
phase: 'responding',
|
||||||
|
actionKey: 'responding',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '正在输出回复',
|
label: '正在输出回复',
|
||||||
detail: snippet,
|
detail: snippet,
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -2003,6 +2066,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const snippet = cleanSingleLineSnippet(thinkText, 52, true);
|
const snippet = cleanSingleLineSnippet(thinkText, 52, true);
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'thinking',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '推理中',
|
label: '推理中',
|
||||||
detail: snippet,
|
detail: snippet,
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -2013,6 +2079,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'thinking',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '推理中',
|
label: '推理中',
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -2047,16 +2116,21 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
stepProgress = '';
|
stepProgress = '';
|
||||||
}
|
}
|
||||||
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
|
const waiting = isWaitingStepStatus(lastStep?.status) || info.isAskUser;
|
||||||
|
const waitingApproval = Boolean(waiting && !info.isAskUser);
|
||||||
const resolvedStartMs = startMs || prevStepEndMs || 0;
|
const resolvedStartMs = startMs || prevStepEndMs || 0;
|
||||||
const label = waiting && !info.isAskUser ? `等待确认 · ${info.label}` : info.label;
|
const label = waitingApproval ? `等待确认 · ${info.label}` : info.label;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
phase: waiting ? 'waiting' : 'tool',
|
phase: waiting ? 'waiting' : 'tool',
|
||||||
|
toolName: info.toolName,
|
||||||
|
actionKey: info.actionKey,
|
||||||
|
waitingApproval,
|
||||||
|
detailKey: '',
|
||||||
label,
|
label,
|
||||||
detail: info.detail,
|
detail: info.detail,
|
||||||
stepProgress,
|
stepProgress,
|
||||||
startedAtMs: resolvedStartMs,
|
startedAtMs: resolvedStartMs,
|
||||||
signature: `step-run:${lastStepId}:${waiting}:${label}:${stepProgress}:${info.detail}`,
|
signature: `step-run:${lastStepId}:${waiting}:${info.actionKey}:${stepProgress}:${info.detail}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2092,6 +2166,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
Math.floor(fallbackStartMs || 0);
|
Math.floor(fallbackStartMs || 0);
|
||||||
return {
|
return {
|
||||||
phase: 'compacting',
|
phase: 'compacting',
|
||||||
|
actionKey: 'compacting',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: cpFinishMs > 0 ? 'compaction_resuming' : '',
|
||||||
label: '上下文压缩',
|
label: '上下文压缩',
|
||||||
detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '',
|
detail: cpFinishMs > 0 ? '已完成压缩,正在恢复推理' : '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -2134,11 +2211,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
phase,
|
phase,
|
||||||
|
toolName: info.toolName,
|
||||||
|
actionKey: info.actionKey,
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: info.label,
|
label: info.label,
|
||||||
detail: info.detail,
|
detail: info.detail,
|
||||||
stepProgress,
|
stepProgress,
|
||||||
startedAtMs: startMs,
|
startedAtMs: startMs,
|
||||||
signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.label}:${stepProgress}:${info.detail}`,
|
signature: `pending-tool:${plannerStepId}:${completedAfterPlanner}:${info.actionKey}:${stepProgress}:${info.detail}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2148,7 +2229,7 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep)
|
summarizeToolCall(t, toolStepsAfterPlanner[idx] || lastStep)
|
||||||
);
|
);
|
||||||
const lastToolInfo = infos[infos.length - 1];
|
const lastToolInfo = infos[infos.length - 1];
|
||||||
const allSameLabel = infos.every((x) => x.label === lastToolInfo.label);
|
const allSameLabel = infos.every((x) => x.actionKey === lastToolInfo.actionKey);
|
||||||
const detailsList = infos.map((x) => x.detail).filter(Boolean);
|
const detailsList = infos.map((x) => x.detail).filter(Boolean);
|
||||||
const combinedDetail =
|
const combinedDetail =
|
||||||
infos.length > 1 && allSameLabel
|
infos.length > 1 && allSameLabel
|
||||||
@@ -2161,11 +2242,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
toolName: lastToolInfo.toolName,
|
||||||
|
actionKey: lastToolInfo.actionKey,
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: lastToolInfo.label,
|
label: lastToolInfo.label,
|
||||||
detail: combinedDetail,
|
detail: combinedDetail,
|
||||||
stepProgress,
|
stepProgress,
|
||||||
startedAtMs: startMs,
|
startedAtMs: startMs,
|
||||||
signature: `post-tool-think:${lastStepId}:${lastToolInfo.label}:${combinedDetail}`,
|
signature: `post-tool-think:${lastStepId}:${lastToolInfo.actionKey}:${combinedDetail}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2178,11 +2263,15 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
const startMs = getRawStepFinishMs(lastStep) || getRawStepEndMs(lastStep) || 0;
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
toolName: lastInfo.toolName,
|
||||||
|
actionKey: lastInfo.actionKey,
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: lastInfo.label,
|
label: lastInfo.label,
|
||||||
detail: lastInfo.detail,
|
detail: lastInfo.detail,
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
startedAtMs: startMs,
|
startedAtMs: startMs,
|
||||||
signature: `post-step-tool:${lastStepId}:${lastInfo.label}:${lastInfo.detail}`,
|
signature: `post-step-tool:${lastStepId}:${lastInfo.actionKey}:${lastInfo.detail}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2198,6 +2287,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
if (snippet) {
|
if (snippet) {
|
||||||
return {
|
return {
|
||||||
phase: 'responding',
|
phase: 'responding',
|
||||||
|
actionKey: 'responding',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '正在输出回复',
|
label: '正在输出回复',
|
||||||
detail: snippet,
|
detail: snippet,
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -2211,6 +2303,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
if (snippet) {
|
if (snippet) {
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'thinking',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '推理中',
|
label: '推理中',
|
||||||
detail: snippet,
|
detail: snippet,
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
@@ -2226,6 +2321,9 @@ export function extractLiveActivity(rawSteps = [], isRunning = false, fallbackSt
|
|||||||
const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0;
|
const startMs = getRawStepFinishMs(lastStep) || getRawStepStartMs(lastStep) || 0;
|
||||||
return {
|
return {
|
||||||
phase: 'thinking',
|
phase: 'thinking',
|
||||||
|
actionKey: 'thinking',
|
||||||
|
waitingApproval: false,
|
||||||
|
detailKey: '',
|
||||||
label: '推理中',
|
label: '推理中',
|
||||||
detail: '',
|
detail: '',
|
||||||
stepProgress: '',
|
stepProgress: '',
|
||||||
Reference in New Issue
Block a user