mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
refactor(panel): extract overlay anchors and consumption row builders
- Extract host anchor discovery, 4-stage capsule layout hysteresis, and ShadowRoot stylesheet mounting from WindowOverlayShell into overlayHostAnchors - Extract reusable model, client-source, workspace, and top-conversation breakdown row builders from ConsumptionView into ConsumptionBreakdownRows - Add root CHANGELOG.md and regression coverage for extracted P3 modules and export header documentation
This commit is contained in:
+948
-944
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* @fileoverview 本机安全文本文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。
|
||||
* 仅允许导出受控白名单文本扩展名(.json / .csv / .md / .txt),严格清洗文件名防止路径穿越,
|
||||
* 并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。
|
||||
* @fileoverview 本机安全文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。
|
||||
* 仅允许导出受控白名单扩展名(.json / .csv / .md / .txt / .xlsx,含 UTF-8 文本和 Base64 二进制工作簿),
|
||||
* 严格清洗文件名防止路径穿越,并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。
|
||||
*/
|
||||
|
||||
import { spawn } from 'node:child_process';
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1795537835379">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795538353095">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795537835379"></script>
|
||||
<script src="/app.js?v=1795538353095"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -636,6 +636,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
'src/registries/stepColumnRegistry.js',
|
||||
'src/components/widgets/CapsuleBarWidget.js',
|
||||
'src/components/widgets/StepTableWidget.js',
|
||||
'src/components/widgets/ConsumptionBreakdownRows.js',
|
||||
'src/components/settings/structurePreviewMock.js',
|
||||
'src/components/settings/CollapsibleSection.js',
|
||||
'src/components/settings/EditableSlotList.js',
|
||||
@@ -652,6 +653,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
'src/views/StepsDetailView.js',
|
||||
'src/views/SettingsView.js',
|
||||
'src/App.js',
|
||||
'src/components/layout/overlayHostAnchors.js',
|
||||
'src/components/layout/WindowOverlayShell.js',
|
||||
'src/main.js',
|
||||
];
|
||||
|
||||
@@ -66,916 +66,25 @@ import {
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
|
||||
const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule';
|
||||
const PORTAL_HOST_ID = 'ag-usage-monitor-portal';
|
||||
import {
|
||||
CAPSULE_HOST_ID,
|
||||
PORTAL_HOST_ID,
|
||||
attachShadowStyles,
|
||||
computeCapsuleLayoutMode,
|
||||
findNativeTopRightAnchor,
|
||||
getLeftSidebarRightEdge,
|
||||
isIdeExtensionChatFrame,
|
||||
isImmediatelyBeforeNode,
|
||||
resolveActiveDockTarget,
|
||||
} from './overlayHostAnchors.js';
|
||||
|
||||
export { computeCapsuleLayoutMode };
|
||||
|
||||
const FLOATING_CARD_WIDTH = 522;
|
||||
const POPOVER_BASE_WIDTH = 540;
|
||||
const POPOVER_MAX_AUTO_WIDTH = 960;
|
||||
const MULTI_PANEL_WIDTH = 464;
|
||||
|
||||
/**
|
||||
* 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。
|
||||
* 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊;
|
||||
* 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。
|
||||
*
|
||||
* @param {number} availWidth
|
||||
* @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode
|
||||
* @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options]
|
||||
* @returns {'wide'|'compact'|'minimal'|'ring-only'}
|
||||
*/
|
||||
export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) {
|
||||
if (availWidth == null || Number.isNaN(availWidth)) return 'wide';
|
||||
const showMulti = options?.showMulti !== false;
|
||||
const updateReserve = options?.hasUpdate ? 52 : 0;
|
||||
const slotCount = Number(options?.slotCount || 3);
|
||||
const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0;
|
||||
const wideKeep = 256 + extraSlotWidth;
|
||||
const wideEnter = 272 + extraSlotWidth;
|
||||
const baseEffWidth = showMulti ? availWidth : availWidth + 76;
|
||||
const effWidth = baseEffWidth - updateReserve;
|
||||
if (currentMode === 'wide') {
|
||||
if (baseEffWidth < 78) return 'ring-only';
|
||||
if (effWidth < 196) return 'minimal';
|
||||
if (effWidth < wideKeep) return 'compact';
|
||||
return 'wide';
|
||||
}
|
||||
if (currentMode === 'compact') {
|
||||
if (effWidth >= wideEnter) return 'wide';
|
||||
if (baseEffWidth < 78) return 'ring-only';
|
||||
if (effWidth < 196) return 'minimal';
|
||||
return 'compact';
|
||||
}
|
||||
if (currentMode === 'minimal') {
|
||||
if (effWidth >= wideEnter) return 'wide';
|
||||
if (effWidth >= 212) return 'compact';
|
||||
if (baseEffWidth < 78) return 'ring-only';
|
||||
return 'minimal';
|
||||
}
|
||||
if (effWidth >= wideEnter) return 'wide';
|
||||
if (effWidth >= 212) return 'compact';
|
||||
if (baseEffWidth >= 92) return 'minimal';
|
||||
return 'ring-only';
|
||||
}
|
||||
|
||||
function findIdeWorkbenchTitlebar() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const workbench = document.querySelector('.monaco-workbench');
|
||||
if (!workbench?.querySelector) return null;
|
||||
const partTitlebar = workbench.querySelector('.part.titlebar');
|
||||
if (!partTitlebar?.querySelector) return null;
|
||||
if (partTitlebar.getBoundingClientRect) {
|
||||
const pr = partTitlebar.getBoundingClientRect();
|
||||
if (pr.width <= 0 || pr.height <= 0) return null;
|
||||
}
|
||||
const container =
|
||||
partTitlebar.querySelector(':scope > .titlebar-container') ||
|
||||
partTitlebar.querySelector('.titlebar-container');
|
||||
const rightGroup =
|
||||
container?.querySelector?.(':scope > .titlebar-right') ||
|
||||
container?.querySelector?.('.titlebar-right');
|
||||
if (!container || !rightGroup) return null;
|
||||
const actionToolbar =
|
||||
rightGroup.querySelector?.(':scope > .action-toolbar-container') ||
|
||||
rightGroup.querySelector?.('.action-toolbar-container') ||
|
||||
null;
|
||||
return {
|
||||
kind: 'ide-titlebar',
|
||||
workbench,
|
||||
titlebar: container,
|
||||
targetContainer: rightGroup,
|
||||
actionToolbar,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function findHostTitlebar() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const tb = document.querySelector('[class*="@container/titlebar"]');
|
||||
if (tb?.getBoundingClientRect) {
|
||||
const r = tb.getBoundingClientRect();
|
||||
if (r.width <= 0 || r.height <= 0) return null;
|
||||
}
|
||||
return tb;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR =
|
||||
'.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]';
|
||||
const COMPOSER_MODEL_LABEL_RE =
|
||||
/\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i;
|
||||
const COMPOSER_MODEL_ATTR_RE =
|
||||
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
|
||||
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
|
||||
const COMPOSER_MODE_TEXT_RE =
|
||||
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i;
|
||||
const COMPOSER_MODE_ATTR_RE =
|
||||
/\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i;
|
||||
const COMPOSER_ICON_FONT_CLASS_RE =
|
||||
/\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i;
|
||||
|
||||
function querySimpleSelectorList(root, selectors) {
|
||||
if (!root || typeof root.querySelectorAll !== 'function') return [];
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const sel of selectors) {
|
||||
let list = [];
|
||||
try {
|
||||
list = root.querySelectorAll(sel) || [];
|
||||
} catch {
|
||||
list = [];
|
||||
}
|
||||
for (const item of list) {
|
||||
if (item && !seen.has(item)) {
|
||||
seen.add(item);
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractVisibleButtonText(node, isRoot = true) {
|
||||
if (!node) return '';
|
||||
const tag = String(node.tagName || node.nodeName || '').toLowerCase();
|
||||
if (tag === 'svg' || tag === 'style' || tag === 'script') return '';
|
||||
if (!isRoot) {
|
||||
if (node.getAttribute?.('aria-hidden') === 'true') return '';
|
||||
const cls = String(node.className || '');
|
||||
if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return '';
|
||||
}
|
||||
if (tag === '#text' || node.nodeType === 3) {
|
||||
return String(node.nodeValue ?? node.textContent ?? '');
|
||||
}
|
||||
const childNodes = node.childNodes || node.children;
|
||||
if (!childNodes || childNodes.length === 0) {
|
||||
return String(node.textContent || '');
|
||||
}
|
||||
let acc = '';
|
||||
for (const ch of childNodes) {
|
||||
acc += ` ${extractVisibleButtonText(ch, false)}`;
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
function cleanComposerButtonText(btn) {
|
||||
const raw = extractVisibleButtonText(btn, true)
|
||||
.replace(/[\u200B-\u200D\uFEFF]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!raw) return '';
|
||||
return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim();
|
||||
}
|
||||
|
||||
function isComposerModelButtonItem(item) {
|
||||
if (!item) return false;
|
||||
if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true;
|
||||
if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasExcludedComposerAncestor(el) {
|
||||
if (!el) return false;
|
||||
if (typeof el.closest === 'function') {
|
||||
try {
|
||||
if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true;
|
||||
} catch {
|
||||
// 忽略选择器异常并回退祖先链遍历
|
||||
}
|
||||
}
|
||||
let cur = el.parentElement || el.parentNode;
|
||||
while (cur) {
|
||||
const cls = String(cur.className || '');
|
||||
if (
|
||||
cls.includes('@container/titlebar') ||
|
||||
cls.includes('quick-input-widget') ||
|
||||
cls.includes('suggest-widget') ||
|
||||
cls.includes('find-widget') ||
|
||||
cls.includes('scm-editor') ||
|
||||
cls.includes('search-view') ||
|
||||
(cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar')))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isNodeHiddenByStyle(el) {
|
||||
if (!el) return true;
|
||||
if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const cs = window.getComputedStyle(el);
|
||||
if (cs?.display === 'none' || cs?.visibility === 'hidden') return true;
|
||||
} catch {
|
||||
// 忽略样式读取异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getInFlowHostChildren(container, capsuleNode, portalNode) {
|
||||
const rawChildren = container?.children || [];
|
||||
const out = [];
|
||||
for (const ch of rawChildren) {
|
||||
if (!ch || ch === capsuleNode || ch === portalNode) continue;
|
||||
if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue;
|
||||
if (ch.hasAttribute?.('hidden')) continue;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const cs = window.getComputedStyle(ch);
|
||||
if (cs?.display === 'none') continue;
|
||||
if (cs?.position === 'absolute' || cs?.position === 'fixed') continue;
|
||||
} catch {
|
||||
// 忽略计算样式异常
|
||||
}
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isHorizontalFlexContainer(el) {
|
||||
if (!el) return false;
|
||||
const cls = String(el.className || '');
|
||||
if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const cs = window.getComputedStyle(el);
|
||||
const disp = String(cs?.display || '');
|
||||
const dir = String(cs?.flexDirection || 'row');
|
||||
if (disp.includes('flex') && !dir.startsWith('column')) return true;
|
||||
} catch {
|
||||
// 忽略计算样式异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isSpaceDistributedFlexContainer(el) {
|
||||
if (!el) return false;
|
||||
const cls = String(el.className || '');
|
||||
if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const jc = String(window.getComputedStyle(el)?.justifyContent || '');
|
||||
if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// 忽略计算样式异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) {
|
||||
if (!autoBtn || !composerCard) return null;
|
||||
let item = autoBtn;
|
||||
while (
|
||||
(item.parentElement || item.parentNode) &&
|
||||
(item.parentElement || item.parentNode) !== composerCard &&
|
||||
(item.parentElement || item.parentNode) !== document.body
|
||||
) {
|
||||
const parent = item.parentElement || item.parentNode;
|
||||
const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode);
|
||||
if (hostSiblings.length >= 2) break;
|
||||
const grandParent = parent.parentElement || parent.parentNode;
|
||||
const parentCls = String(parent.className || '');
|
||||
const parentInlineMl = String(parent.style?.marginLeft || '').trim();
|
||||
const isSingleClusterInSplitRow =
|
||||
!/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) &&
|
||||
parentInlineMl !== 'auto' &&
|
||||
isHorizontalFlexContainer(parent) &&
|
||||
grandParent &&
|
||||
isSpaceDistributedFlexContainer(grandParent) &&
|
||||
getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2;
|
||||
if (isSingleClusterInSplitRow) {
|
||||
break;
|
||||
}
|
||||
item = parent;
|
||||
}
|
||||
|
||||
const anchorNode = item;
|
||||
const targetContainer = anchorNode.parentElement || anchorNode.parentNode;
|
||||
if (!targetContainer) return null;
|
||||
|
||||
const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode);
|
||||
const anchorIdx = hostChildren.indexOf(anchorNode);
|
||||
const isFirstHostChild = anchorIdx <= 0;
|
||||
|
||||
let needsAutoMarginTransfer = false;
|
||||
let patchMarginNode = null;
|
||||
|
||||
if (!isFirstHostChild) {
|
||||
const cls = String(anchorNode.className || '');
|
||||
const inlineMl = String(anchorNode.style?.marginLeft || '').trim();
|
||||
let computedLargeMl = false;
|
||||
if (
|
||||
patchedNode !== anchorNode &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.getComputedStyle === 'function'
|
||||
) {
|
||||
try {
|
||||
const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0;
|
||||
const prevSib = hostChildren[anchorIdx - 1];
|
||||
const aRect = anchorNode.getBoundingClientRect?.();
|
||||
const pRect = prevSib?.getBoundingClientRect?.();
|
||||
if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) {
|
||||
computedLargeMl = true;
|
||||
}
|
||||
} catch {
|
||||
// 忽略边距测量异常
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
/\b(?:ml-auto|ms-auto)\b/.test(cls) ||
|
||||
inlineMl === 'auto' ||
|
||||
patchedNode === anchorNode ||
|
||||
computedLargeMl
|
||||
) {
|
||||
needsAutoMarginTransfer = true;
|
||||
patchMarginNode = anchorNode;
|
||||
} else if (isSpaceDistributedFlexContainer(targetContainer)) {
|
||||
needsAutoMarginTransfer = true;
|
||||
}
|
||||
}
|
||||
|
||||
const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.();
|
||||
let leftClusterRightEdge = 0;
|
||||
if (autoRect && Array.isArray(bottomRowBtns)) {
|
||||
for (const entry of bottomRowBtns) {
|
||||
if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue;
|
||||
if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) {
|
||||
if (entry.rect.right > leftClusterRightEdge) {
|
||||
leftClusterRightEdge = entry.rect.right;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'composer',
|
||||
workbench: null,
|
||||
titlebar: composerCard,
|
||||
targetContainer,
|
||||
actionToolbar: patchMarginNode,
|
||||
anchorNode,
|
||||
needsAutoMarginTransfer,
|
||||
leftClusterRightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
function buildComposerRightEndDockDescriptor(
|
||||
leftAnchorBtn,
|
||||
composerCard,
|
||||
bottomRowBtns,
|
||||
capsuleNode,
|
||||
portalNode
|
||||
) {
|
||||
if (!leftAnchorBtn || !composerCard) return null;
|
||||
const cardRect = composerCard.getBoundingClientRect?.();
|
||||
const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180;
|
||||
let toolbarRow = null;
|
||||
let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
|
||||
for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) {
|
||||
const r = cur.getBoundingClientRect?.();
|
||||
if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) {
|
||||
toolbarRow = cur;
|
||||
break;
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
if (!toolbarRow) {
|
||||
const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
|
||||
if (!p || !isHorizontalFlexContainer(p)) return null;
|
||||
toolbarRow = p;
|
||||
}
|
||||
|
||||
let leftClusterRightEdge = 0;
|
||||
if (Array.isArray(bottomRowBtns)) {
|
||||
for (const entry of bottomRowBtns) {
|
||||
if (entry?.rect?.right > leftClusterRightEdge) {
|
||||
leftClusterRightEdge = entry.rect.right;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode);
|
||||
const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null;
|
||||
if (
|
||||
lastChild &&
|
||||
!lastChild.contains?.(leftAnchorBtn) &&
|
||||
isHorizontalFlexContainer(lastChild) &&
|
||||
getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0
|
||||
) {
|
||||
return {
|
||||
kind: 'composer',
|
||||
workbench: null,
|
||||
titlebar: composerCard,
|
||||
targetContainer: lastChild,
|
||||
actionToolbar: null,
|
||||
anchorNode: null,
|
||||
needsAutoMarginTransfer: false,
|
||||
leftClusterRightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'composer',
|
||||
workbench: null,
|
||||
titlebar: composerCard,
|
||||
targetContainer: toolbarRow,
|
||||
actionToolbar: null,
|
||||
anchorNode: null,
|
||||
needsAutoMarginTransfer: true,
|
||||
leftClusterRightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) {
|
||||
const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']);
|
||||
const hostBtns = [];
|
||||
for (const btn of rawBtns) {
|
||||
if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue;
|
||||
if (editorEl && btn.contains?.(editorEl)) continue;
|
||||
if (
|
||||
btn.id === CAPSULE_HOST_ID ||
|
||||
btn.id === PORTAL_HOST_ID ||
|
||||
capsuleNode?.contains?.(btn) ||
|
||||
portalNode?.contains?.(btn)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (isNodeHiddenByStyle(btn)) continue;
|
||||
// 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮
|
||||
let nestedInBtn = false;
|
||||
let p = btn.parentElement || btn.parentNode;
|
||||
while (p && p !== container) {
|
||||
const pTag = String(p.tagName || '').toLowerCase();
|
||||
if (pTag === 'button') {
|
||||
nestedInBtn = true;
|
||||
break;
|
||||
}
|
||||
if (
|
||||
(p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) &&
|
||||
!(editorEl && p.contains?.(editorEl))
|
||||
) {
|
||||
const pr = p.getBoundingClientRect?.();
|
||||
if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) {
|
||||
nestedInBtn = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
p = p.parentElement || p.parentNode;
|
||||
}
|
||||
if (nestedInBtn) continue;
|
||||
|
||||
const br = btn.getBoundingClientRect?.();
|
||||
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue;
|
||||
const centerY = (br.top + br.bottom) / 2;
|
||||
if (editorRect && centerY < editorRect.top - 4) continue;
|
||||
hostBtns.push({
|
||||
btn,
|
||||
rect: br,
|
||||
centerY,
|
||||
centerX: (br.left + br.right) / 2,
|
||||
cleanText: cleanComposerButtonText(btn),
|
||||
attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(),
|
||||
});
|
||||
}
|
||||
if (hostBtns.length === 0) return [];
|
||||
let maxCenterY = -Infinity;
|
||||
for (const item of hostBtns) {
|
||||
if (item.centerY > maxCenterY) maxCenterY = item.centerY;
|
||||
}
|
||||
const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22);
|
||||
bottomBand.sort((a, b) => a.rect.left - b.rect.left);
|
||||
return bottomBand;
|
||||
}
|
||||
|
||||
function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) {
|
||||
if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null;
|
||||
const requireModelForFallback = Boolean(options?.requireModelForFallback);
|
||||
const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0;
|
||||
const rightFirst = [
|
||||
...bottomRowBtns.filter((b) => b.centerX >= rightSplitX),
|
||||
...bottomRowBtns.filter((b) => b.centerX < rightSplitX),
|
||||
];
|
||||
|
||||
// Tier 1: 精确文本 Auto / 自动 匹配
|
||||
for (const item of rightFirst) {
|
||||
if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) {
|
||||
return { btn: item.btn, tier: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
// Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮)
|
||||
for (const item of rightFirst) {
|
||||
if (isComposerModelButtonItem(item)) continue;
|
||||
if (
|
||||
(item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) ||
|
||||
(item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText))
|
||||
) {
|
||||
return { btn: item.btn, tier: 2 };
|
||||
}
|
||||
}
|
||||
|
||||
const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem);
|
||||
|
||||
// Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局)
|
||||
if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) {
|
||||
let maxGap = -Infinity;
|
||||
let splitIdx = -1;
|
||||
for (let i = 1; i < bottomRowBtns.length; i += 1) {
|
||||
const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right;
|
||||
if (gap > maxGap) {
|
||||
maxGap = gap;
|
||||
splitIdx = i;
|
||||
}
|
||||
}
|
||||
if (splitIdx >= 1 && maxGap >= 16) {
|
||||
return { btn: bottomRowBtns[splitIdx].btn, tier: 3 };
|
||||
}
|
||||
}
|
||||
|
||||
// Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧
|
||||
if (hasModelBtn && containerRect && containerRect.width >= 200) {
|
||||
const lastItem = bottomRowBtns[bottomRowBtns.length - 1];
|
||||
if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) {
|
||||
return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveComposerEditorRect(ed) {
|
||||
const er = ed?.getBoundingClientRect?.();
|
||||
if (er && er.width >= 80 && er.height >= 12) return er;
|
||||
let cur = ed;
|
||||
for (let d = 0; d < 6 && cur; d += 1) {
|
||||
if (String(cur.className || '').includes('monaco-editor')) {
|
||||
const mr = cur.getBoundingClientRect?.();
|
||||
if (mr && mr.width >= 80 && mr.height >= 12) return mr;
|
||||
break;
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
return er || null;
|
||||
}
|
||||
|
||||
function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null;
|
||||
const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null;
|
||||
const activeRouteId = extractHostRouteCascadeId();
|
||||
|
||||
// 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏与 Auto / 右簇发送按钮
|
||||
const rawEditors = querySimpleSelectorList(document, [
|
||||
'textarea',
|
||||
'[contenteditable]',
|
||||
'[role="textbox"]',
|
||||
'[data-lexical-editor]',
|
||||
'.ProseMirror',
|
||||
'.monaco-editor',
|
||||
]);
|
||||
const scoredEditors = [];
|
||||
for (const ed of rawEditors) {
|
||||
if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue;
|
||||
if (ed.hasAttribute?.('contenteditable')) {
|
||||
const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase();
|
||||
if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue;
|
||||
}
|
||||
if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue;
|
||||
const er = resolveComposerEditorRect(ed);
|
||||
if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue;
|
||||
|
||||
let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2;
|
||||
if (activeRouteId) {
|
||||
let anc = ed.parentElement || ed.parentNode;
|
||||
while (anc) {
|
||||
const cid = anc.getAttribute?.('data-cascade-id');
|
||||
if (cid) {
|
||||
score += cid === activeRouteId ? 4000 : -2000;
|
||||
break;
|
||||
}
|
||||
anc = anc.parentElement || anc.parentNode;
|
||||
}
|
||||
}
|
||||
if (
|
||||
document.activeElement &&
|
||||
(ed === document.activeElement || ed.contains?.(document.activeElement))
|
||||
) {
|
||||
score += 1000;
|
||||
}
|
||||
scoredEditors.push({ ed, rect: er, score });
|
||||
}
|
||||
scoredEditors.sort((a, b) => b.score - a.score);
|
||||
|
||||
for (const { ed, rect: er } of scoredEditors) {
|
||||
const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') ||
|
||||
String(ed.className || '').includes('inputarea');
|
||||
let tier3Candidate = null;
|
||||
let tier4Candidate = null;
|
||||
let cur = ed.parentElement || ed.parentNode;
|
||||
for (let depth = 0; depth < 18 && cur; depth += 1) {
|
||||
if (cur === document.body || cur === document.documentElement) break;
|
||||
const tag = String(cur.tagName || '').toLowerCase();
|
||||
if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break;
|
||||
const cr = cur.getBoundingClientRect?.();
|
||||
if (cr && cr.height > 680) break;
|
||||
if (cr && cr.width >= 180 && cr.height > 0) {
|
||||
const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl);
|
||||
const picked = pickAutoButtonFromRow(bottomRowBtns, cr, {
|
||||
requireModelForFallback: isMonacoCandidate,
|
||||
});
|
||||
if (picked) {
|
||||
if (picked.tier <= 2) {
|
||||
const desc = buildComposerDockDescriptor(
|
||||
picked.btn,
|
||||
cur,
|
||||
bottomRowBtns,
|
||||
capEl,
|
||||
porEl,
|
||||
patchedNode
|
||||
);
|
||||
if (desc) return desc;
|
||||
} else if (picked.tier === 3 && !tier3Candidate) {
|
||||
tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns };
|
||||
} else if (picked.tier === 4 && !tier4Candidate) {
|
||||
tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns };
|
||||
}
|
||||
}
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
if (tier3Candidate) {
|
||||
const desc = buildComposerDockDescriptor(
|
||||
tier3Candidate.btn,
|
||||
tier3Candidate.card,
|
||||
tier3Candidate.bottomRowBtns,
|
||||
capEl,
|
||||
porEl,
|
||||
patchedNode
|
||||
);
|
||||
if (desc) return desc;
|
||||
}
|
||||
if (tier4Candidate) {
|
||||
const desc = buildComposerRightEndDockDescriptor(
|
||||
tier4Candidate.leftAnchorBtn,
|
||||
tier4Candidate.card,
|
||||
tier4Candidate.bottomRowBtns,
|
||||
capEl,
|
||||
porEl
|
||||
);
|
||||
if (desc) return desc;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏
|
||||
const vh = Number(window.innerHeight || 800);
|
||||
const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']);
|
||||
let modelToolbarFallback = null;
|
||||
for (const btn of allBtns) {
|
||||
if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue;
|
||||
if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue;
|
||||
const br = btn.getBoundingClientRect?.();
|
||||
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue;
|
||||
const clean = cleanComposerButtonText(btn);
|
||||
const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim();
|
||||
const itemProbe = { cleanText: clean, attrText: attr };
|
||||
const isModeBtn =
|
||||
COMPOSER_MODE_EXACT_RE.test(clean) ||
|
||||
(!isComposerModelButtonItem(itemProbe) &&
|
||||
((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr))));
|
||||
const isModelBtn = isComposerModelButtonItem(itemProbe);
|
||||
if (!isModeBtn && !isModelBtn) continue;
|
||||
|
||||
let cur = btn.parentElement || btn.parentNode;
|
||||
for (let depth = 0; depth < 12 && cur; depth += 1) {
|
||||
if (cur === document.body || cur === document.documentElement) break;
|
||||
if (String(cur.className || '').includes('monaco-workbench')) break;
|
||||
const cr = cur.getBoundingClientRect?.();
|
||||
if (!cr || cr.height > 560) break;
|
||||
if (cr.width >= 200) {
|
||||
const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl);
|
||||
if (isModeBtn) {
|
||||
const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b));
|
||||
if (hasModelSibling) {
|
||||
const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode);
|
||||
if (desc) return desc;
|
||||
}
|
||||
} else if (isModelBtn && !modelToolbarFallback) {
|
||||
const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true });
|
||||
if (picked) {
|
||||
const desc =
|
||||
picked.tier <= 3 && picked.btn
|
||||
? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode)
|
||||
: picked.tier === 4 && picked.leftAnchorBtn
|
||||
? buildComposerRightEndDockDescriptor(
|
||||
picked.leftAnchorBtn,
|
||||
cur,
|
||||
rowBtns,
|
||||
capEl,
|
||||
porEl
|
||||
)
|
||||
: null;
|
||||
if (desc) {
|
||||
if (picked.tier <= 2) return desc;
|
||||
modelToolbarFallback = desc;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
}
|
||||
if (modelToolbarFallback) return modelToolbarFallback;
|
||||
} catch {
|
||||
// 忽略输入框探测异常
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isImmediatelyBeforeNode(node, refNode) {
|
||||
if (!node || !refNode) return false;
|
||||
if (node.nextElementSibling !== undefined) {
|
||||
return node.nextElementSibling === refNode;
|
||||
}
|
||||
if (node.nextSibling !== undefined) {
|
||||
return node.nextSibling === refNode;
|
||||
}
|
||||
const parent = node.parentElement || node.parentNode;
|
||||
if (!parent?.children) return false;
|
||||
const idx = Array.prototype.indexOf.call(parent.children, node);
|
||||
return idx >= 0 && parent.children[idx + 1] === refNode;
|
||||
}
|
||||
|
||||
function isIdeExtensionChatFrame() {
|
||||
try {
|
||||
if (typeof window === 'undefined') return false;
|
||||
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
|
||||
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolveActiveDockTarget(options = undefined) {
|
||||
const settings = telemetryStore.getState().telemetry?.settings;
|
||||
const rawMode =
|
||||
settings?.windowMountMode ??
|
||||
readInjectedWindowBridge()?.mountMode;
|
||||
const mountMode =
|
||||
options?.mountMode ||
|
||||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
|
||||
if (isIdeExtensionChatFrame()) {
|
||||
if (mountMode !== 'composer') return null;
|
||||
return findHostComposerAutoTarget(
|
||||
options?.capsuleNode || null,
|
||||
options?.portalNode || null,
|
||||
options?.patchedNode || null
|
||||
);
|
||||
}
|
||||
if (mountMode === 'composer') {
|
||||
const composerTarget = findHostComposerAutoTarget(
|
||||
options?.capsuleNode || null,
|
||||
options?.portalNode || null,
|
||||
options?.patchedNode || null
|
||||
);
|
||||
if (composerTarget) return composerTarget;
|
||||
}
|
||||
const ideTarget = findIdeWorkbenchTitlebar();
|
||||
if (ideTarget) return ideTarget;
|
||||
const titlebar = findHostTitlebar();
|
||||
if (!titlebar) return null;
|
||||
let targetContainer = titlebar;
|
||||
try {
|
||||
const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild;
|
||||
if (rightGroup && rightGroup !== titlebar.firstElementChild) {
|
||||
targetContainer = rightGroup;
|
||||
}
|
||||
} catch {
|
||||
// 忽略子选择器不兼容场景
|
||||
}
|
||||
return {
|
||||
kind: 'flow',
|
||||
workbench: null,
|
||||
titlebar,
|
||||
targetContainer,
|
||||
actionToolbar: null,
|
||||
};
|
||||
}
|
||||
|
||||
function findNativeTopRightAnchor() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]');
|
||||
if (auxToggle?.closest) {
|
||||
return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle;
|
||||
}
|
||||
const candidates = document.querySelectorAll('button, a, [role="button"]');
|
||||
for (const btn of candidates) {
|
||||
const text = String(btn.textContent || '').trim();
|
||||
if (
|
||||
(text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) &&
|
||||
btn.getBoundingClientRect?.().top < 52
|
||||
) {
|
||||
return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn;
|
||||
}
|
||||
}
|
||||
return document.querySelector('div.absolute.right-0.top-0');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getLeftSidebarRightEdge(vw) {
|
||||
try {
|
||||
if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
|
||||
if (document.querySelector('.monaco-workbench')) {
|
||||
return 0;
|
||||
}
|
||||
const navEl = document.querySelector('div[role="navigation"]');
|
||||
if (navEl?.getBoundingClientRect) {
|
||||
const nr = navEl.getBoundingClientRect();
|
||||
if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) {
|
||||
return Math.ceil(nr.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略侧栏测量异常
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在主窗口挂载双栖顶栏胶囊与完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。
|
||||
*/
|
||||
const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([
|
||||
'src/styles/views-overview.css',
|
||||
'src/styles/views-consumption.css',
|
||||
'src/styles/views-tables.css',
|
||||
'src/styles/views-settings.css',
|
||||
'src/styles/controls.css',
|
||||
]);
|
||||
|
||||
let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null };
|
||||
|
||||
function buildSlimCapsuleCss(fullCss) {
|
||||
if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss;
|
||||
return fullCss
|
||||
.split(/(?=\/\* --- src\/styles\/)/)
|
||||
.filter((block) => {
|
||||
const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//);
|
||||
return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]);
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) {
|
||||
if (!shadowRoot) return;
|
||||
if (
|
||||
fullCss &&
|
||||
typeof CSSStyleSheet === 'function' &&
|
||||
Array.isArray(shadowRoot.adoptedStyleSheets)
|
||||
) {
|
||||
try {
|
||||
if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) {
|
||||
const sheet = new CSSStyleSheet();
|
||||
sheet.replaceSync(fullCss);
|
||||
sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet };
|
||||
}
|
||||
shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet];
|
||||
return;
|
||||
} catch {
|
||||
// 降级到传统 <style> 节点
|
||||
}
|
||||
}
|
||||
const styleEl = document.createElement('style');
|
||||
styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss;
|
||||
shadowRoot.appendChild(styleEl);
|
||||
}
|
||||
|
||||
export function mountWindowOverlay() {
|
||||
if (typeof window === 'undefined' || typeof document === 'undefined') return null;
|
||||
|
||||
@@ -0,0 +1,919 @@
|
||||
/**
|
||||
* @fileoverview Host IDE/Desktop titlebar & composer button anchor discovery,
|
||||
* 4-stage responsive capsule hysteresis, and shared ShadowRoot CSSStyleSheet mounting
|
||||
* extracted from WindowOverlayShell.js.
|
||||
*/
|
||||
|
||||
import { readInjectedWindowBridge } from '../../../shared/window-bridge-protocol.mjs';
|
||||
import {
|
||||
extractHostRouteCascadeId,
|
||||
normalizeClientWindowMountMode,
|
||||
telemetryStore,
|
||||
} from '../../store/telemetryStore.js';
|
||||
|
||||
export const CAPSULE_HOST_ID = 'ag-usage-monitor-capsule';
|
||||
export const PORTAL_HOST_ID = 'ag-usage-monitor-portal';
|
||||
|
||||
/**
|
||||
* 带迟滞区间(Hysteresis)的四阶段顶栏双胶囊响应式宽度计算,避免临界宽度反复跳动。
|
||||
* 当左侧多会话入口关闭(`showMulti === false`)时自动释放约 76px 预算给右侧指标胶囊;
|
||||
* 当槽位数超过 3 个(4..5 槽)时自动按槽位增量上浮 `wide` 阈值。
|
||||
*
|
||||
* @param {number} availWidth
|
||||
* @param {'wide'|'compact'|'minimal'|'ring-only'} currentMode
|
||||
* @param {{ showMulti?: boolean, hasUpdate?: boolean, slotCount?: number }} [options]
|
||||
* @returns {'wide'|'compact'|'minimal'|'ring-only'}
|
||||
*/
|
||||
export function computeCapsuleLayoutMode(availWidth, currentMode = 'wide', options = undefined) {
|
||||
if (availWidth == null || Number.isNaN(availWidth)) return 'wide';
|
||||
const showMulti = options?.showMulti !== false;
|
||||
const updateReserve = options?.hasUpdate ? 52 : 0;
|
||||
const slotCount = Number(options?.slotCount || 3);
|
||||
const extraSlotWidth = slotCount > 3 ? (slotCount - 3) * 58 : 0;
|
||||
const wideKeep = 256 + extraSlotWidth;
|
||||
const wideEnter = 272 + extraSlotWidth;
|
||||
const baseEffWidth = showMulti ? availWidth : availWidth + 76;
|
||||
const effWidth = baseEffWidth - updateReserve;
|
||||
if (currentMode === 'wide') {
|
||||
if (baseEffWidth < 78) return 'ring-only';
|
||||
if (effWidth < 196) return 'minimal';
|
||||
if (effWidth < wideKeep) return 'compact';
|
||||
return 'wide';
|
||||
}
|
||||
if (currentMode === 'compact') {
|
||||
if (effWidth >= wideEnter) return 'wide';
|
||||
if (baseEffWidth < 78) return 'ring-only';
|
||||
if (effWidth < 196) return 'minimal';
|
||||
return 'compact';
|
||||
}
|
||||
if (currentMode === 'minimal') {
|
||||
if (effWidth >= wideEnter) return 'wide';
|
||||
if (effWidth >= 212) return 'compact';
|
||||
if (baseEffWidth < 78) return 'ring-only';
|
||||
return 'minimal';
|
||||
}
|
||||
if (effWidth >= wideEnter) return 'wide';
|
||||
if (effWidth >= 212) return 'compact';
|
||||
if (baseEffWidth >= 92) return 'minimal';
|
||||
return 'ring-only';
|
||||
}
|
||||
|
||||
function findIdeWorkbenchTitlebar() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const workbench = document.querySelector('.monaco-workbench');
|
||||
if (!workbench?.querySelector) return null;
|
||||
const partTitlebar = workbench.querySelector('.part.titlebar');
|
||||
if (!partTitlebar?.querySelector) return null;
|
||||
if (partTitlebar.getBoundingClientRect) {
|
||||
const pr = partTitlebar.getBoundingClientRect();
|
||||
if (pr.width <= 0 || pr.height <= 0) return null;
|
||||
}
|
||||
const container =
|
||||
partTitlebar.querySelector(':scope > .titlebar-container') ||
|
||||
partTitlebar.querySelector('.titlebar-container');
|
||||
const rightGroup =
|
||||
container?.querySelector?.(':scope > .titlebar-right') ||
|
||||
container?.querySelector?.('.titlebar-right');
|
||||
if (!container || !rightGroup) return null;
|
||||
const actionToolbar =
|
||||
rightGroup.querySelector?.(':scope > .action-toolbar-container') ||
|
||||
rightGroup.querySelector?.('.action-toolbar-container') ||
|
||||
null;
|
||||
return {
|
||||
kind: 'ide-titlebar',
|
||||
workbench,
|
||||
titlebar: container,
|
||||
targetContainer: rightGroup,
|
||||
actionToolbar,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function findHostTitlebar() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const tb = document.querySelector('[class*="@container/titlebar"]');
|
||||
if (tb?.getBoundingClientRect) {
|
||||
const r = tb.getBoundingClientRect();
|
||||
if (r.width <= 0 || r.height <= 0) return null;
|
||||
}
|
||||
return tb;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const COMPOSER_EXCLUDED_ANCESTOR_SELECTOR =
|
||||
'.part.titlebar, .part.statusbar, .quick-input-widget, .suggest-widget, .find-widget, .scm-editor, .search-view, [class*="@container/titlebar"]';
|
||||
const COMPOSER_MODEL_LABEL_RE =
|
||||
/\b(?:gemini|claude|gpt|argon|carbon|neon|hydrogen|helix|flash|sonnet|opus|haiku|orchestrator|llama|deepseek|qwen|mistral|model_placeholder|placeholder_m\d+|o[134](?:-\w+)?)\b/i;
|
||||
const COMPOSER_MODEL_ATTR_RE =
|
||||
/\bmodel[-_\s]?(?:select|picker|switch|selector|menu|name)\b|选择模型|切换模型/i;
|
||||
const COMPOSER_MODE_EXACT_RE = /^(?:auto|自动)$/i;
|
||||
const COMPOSER_MODE_TEXT_RE =
|
||||
/^(?:auto|ask|manual|supervised|autonomous|always\s*allow|turbo|safe|yolo|plan|act|review|confirm|normal|fast|自动|询问|手动|始终允许|受控|规划)(?:\s*(?:mode|模式))?$/i;
|
||||
const COMPOSER_MODE_ATTR_RE =
|
||||
/\b(?:auto(?:nomy|matic)?|execution[-_]?mode|agent[-_]?mode|permission|approval|hitl|policy|mode[-_]?selector|mode[-_]?picker)\b|自动|执行模式|权限模式|审批/i;
|
||||
const COMPOSER_ICON_FONT_CLASS_RE =
|
||||
/\b(?:codicon|material-symbols(?:-\w+)?|material-icons(?:-\w+)?|lucide(?:-\w+)?)\b/i;
|
||||
|
||||
function querySimpleSelectorList(root, selectors) {
|
||||
if (!root || typeof root.querySelectorAll !== 'function') return [];
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const sel of selectors) {
|
||||
let list = [];
|
||||
try {
|
||||
list = root.querySelectorAll(sel) || [];
|
||||
} catch {
|
||||
list = [];
|
||||
}
|
||||
for (const item of list) {
|
||||
if (item && !seen.has(item)) {
|
||||
seen.add(item);
|
||||
out.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractVisibleButtonText(node, isRoot = true) {
|
||||
if (!node) return '';
|
||||
const tag = String(node.tagName || node.nodeName || '').toLowerCase();
|
||||
if (tag === 'svg' || tag === 'style' || tag === 'script') return '';
|
||||
if (!isRoot) {
|
||||
if (node.getAttribute?.('aria-hidden') === 'true') return '';
|
||||
const cls = String(node.className || '');
|
||||
if (cls && COMPOSER_ICON_FONT_CLASS_RE.test(cls)) return '';
|
||||
}
|
||||
if (tag === '#text' || node.nodeType === 3) {
|
||||
return String(node.nodeValue ?? node.textContent ?? '');
|
||||
}
|
||||
const childNodes = node.childNodes || node.children;
|
||||
if (!childNodes || childNodes.length === 0) {
|
||||
return String(node.textContent || '');
|
||||
}
|
||||
let acc = '';
|
||||
for (const ch of childNodes) {
|
||||
acc += ` ${extractVisibleButtonText(ch, false)}`;
|
||||
}
|
||||
return acc;
|
||||
}
|
||||
|
||||
function cleanComposerButtonText(btn) {
|
||||
const raw = extractVisibleButtonText(btn, true)
|
||||
.replace(/[\u200B-\u200D\uFEFF]/g, '')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
if (!raw) return '';
|
||||
return raw.replace(/^[⌃⌄▾▴∨∧^<>›‹+\s]+|[⌃⌄▾▴∨∧^<>›‹\s]+$/g, '').trim();
|
||||
}
|
||||
|
||||
function isComposerModelButtonItem(item) {
|
||||
if (!item) return false;
|
||||
if (item.cleanText && COMPOSER_MODEL_LABEL_RE.test(item.cleanText)) return true;
|
||||
if (item.attrText && COMPOSER_MODEL_ATTR_RE.test(item.attrText)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function hasExcludedComposerAncestor(el) {
|
||||
if (!el) return false;
|
||||
if (typeof el.closest === 'function') {
|
||||
try {
|
||||
if (el.closest(COMPOSER_EXCLUDED_ANCESTOR_SELECTOR)) return true;
|
||||
} catch {
|
||||
// 忽略选择器异常并回退祖先链遍历
|
||||
}
|
||||
}
|
||||
let cur = el.parentElement || el.parentNode;
|
||||
while (cur) {
|
||||
const cls = String(cur.className || '');
|
||||
if (
|
||||
cls.includes('@container/titlebar') ||
|
||||
cls.includes('quick-input-widget') ||
|
||||
cls.includes('suggest-widget') ||
|
||||
cls.includes('find-widget') ||
|
||||
cls.includes('scm-editor') ||
|
||||
cls.includes('search-view') ||
|
||||
(cls.includes('part') && (cls.includes('titlebar') || cls.includes('statusbar')))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isNodeHiddenByStyle(el) {
|
||||
if (!el) return true;
|
||||
if (el.hasAttribute?.('hidden') || el.getAttribute?.('aria-hidden') === 'true') return true;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const cs = window.getComputedStyle(el);
|
||||
if (cs?.display === 'none' || cs?.visibility === 'hidden') return true;
|
||||
} catch {
|
||||
// 忽略样式读取异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function getInFlowHostChildren(container, capsuleNode, portalNode) {
|
||||
const rawChildren = container?.children || [];
|
||||
const out = [];
|
||||
for (const ch of rawChildren) {
|
||||
if (!ch || ch === capsuleNode || ch === portalNode) continue;
|
||||
if (ch.id === CAPSULE_HOST_ID || ch.id === PORTAL_HOST_ID) continue;
|
||||
if (ch.hasAttribute?.('hidden')) continue;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const cs = window.getComputedStyle(ch);
|
||||
if (cs?.display === 'none') continue;
|
||||
if (cs?.position === 'absolute' || cs?.position === 'fixed') continue;
|
||||
} catch {
|
||||
// 忽略计算样式异常
|
||||
}
|
||||
}
|
||||
out.push(ch);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isHorizontalFlexContainer(el) {
|
||||
if (!el) return false;
|
||||
const cls = String(el.className || '');
|
||||
if (/\b(?:inline-)?flex\b/.test(cls) && !/\bflex-col\b/.test(cls)) return true;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const cs = window.getComputedStyle(el);
|
||||
const disp = String(cs?.display || '');
|
||||
const dir = String(cs?.flexDirection || 'row');
|
||||
if (disp.includes('flex') && !dir.startsWith('column')) return true;
|
||||
} catch {
|
||||
// 忽略计算样式异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isSpaceDistributedFlexContainer(el) {
|
||||
if (!el) return false;
|
||||
const cls = String(el.className || '');
|
||||
if (/\bjustify-(?:between|around|evenly)\b/.test(cls)) return true;
|
||||
if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
|
||||
try {
|
||||
const jc = String(window.getComputedStyle(el)?.justifyContent || '');
|
||||
if (jc.includes('space-between') || jc.includes('space-around') || jc.includes('space-evenly')) {
|
||||
return true;
|
||||
}
|
||||
} catch {
|
||||
// 忽略计算样式异常
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function buildComposerDockDescriptor(autoBtn, composerCard, bottomRowBtns, capsuleNode, portalNode, patchedNode) {
|
||||
if (!autoBtn || !composerCard) return null;
|
||||
let item = autoBtn;
|
||||
while (
|
||||
(item.parentElement || item.parentNode) &&
|
||||
(item.parentElement || item.parentNode) !== composerCard &&
|
||||
(item.parentElement || item.parentNode) !== document.body
|
||||
) {
|
||||
const parent = item.parentElement || item.parentNode;
|
||||
const hostSiblings = getInFlowHostChildren(parent, capsuleNode, portalNode);
|
||||
if (hostSiblings.length >= 2) break;
|
||||
const grandParent = parent.parentElement || parent.parentNode;
|
||||
const parentCls = String(parent.className || '');
|
||||
const parentInlineMl = String(parent.style?.marginLeft || '').trim();
|
||||
const isSingleClusterInSplitRow =
|
||||
!/\b(?:relative|ml-auto|ms-auto)\b/.test(parentCls) &&
|
||||
parentInlineMl !== 'auto' &&
|
||||
isHorizontalFlexContainer(parent) &&
|
||||
grandParent &&
|
||||
isSpaceDistributedFlexContainer(grandParent) &&
|
||||
getInFlowHostChildren(grandParent, capsuleNode, portalNode).length >= 2;
|
||||
if (isSingleClusterInSplitRow) {
|
||||
break;
|
||||
}
|
||||
item = parent;
|
||||
}
|
||||
|
||||
const anchorNode = item;
|
||||
const targetContainer = anchorNode.parentElement || anchorNode.parentNode;
|
||||
if (!targetContainer) return null;
|
||||
|
||||
const hostChildren = getInFlowHostChildren(targetContainer, capsuleNode, portalNode);
|
||||
const anchorIdx = hostChildren.indexOf(anchorNode);
|
||||
const isFirstHostChild = anchorIdx <= 0;
|
||||
|
||||
let needsAutoMarginTransfer = false;
|
||||
let patchMarginNode = null;
|
||||
|
||||
if (!isFirstHostChild) {
|
||||
const cls = String(anchorNode.className || '');
|
||||
const inlineMl = String(anchorNode.style?.marginLeft || '').trim();
|
||||
let computedLargeMl = false;
|
||||
if (
|
||||
patchedNode !== anchorNode &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.getComputedStyle === 'function'
|
||||
) {
|
||||
try {
|
||||
const mlPx = parseFloat(window.getComputedStyle(anchorNode)?.marginLeft) || 0;
|
||||
const prevSib = hostChildren[anchorIdx - 1];
|
||||
const aRect = anchorNode.getBoundingClientRect?.();
|
||||
const pRect = prevSib?.getBoundingClientRect?.();
|
||||
if (mlPx > 24 && aRect && pRect && aRect.left - pRect.right >= mlPx - 6) {
|
||||
computedLargeMl = true;
|
||||
}
|
||||
} catch {
|
||||
// 忽略边距测量异常
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
/\b(?:ml-auto|ms-auto)\b/.test(cls) ||
|
||||
inlineMl === 'auto' ||
|
||||
patchedNode === anchorNode ||
|
||||
computedLargeMl
|
||||
) {
|
||||
needsAutoMarginTransfer = true;
|
||||
patchMarginNode = anchorNode;
|
||||
} else if (isSpaceDistributedFlexContainer(targetContainer)) {
|
||||
needsAutoMarginTransfer = true;
|
||||
}
|
||||
}
|
||||
|
||||
const autoRect = anchorNode.getBoundingClientRect?.() || autoBtn.getBoundingClientRect?.();
|
||||
let leftClusterRightEdge = 0;
|
||||
if (autoRect && Array.isArray(bottomRowBtns)) {
|
||||
for (const entry of bottomRowBtns) {
|
||||
if (entry.btn === autoBtn || anchorNode.contains?.(entry.btn)) continue;
|
||||
if (entry.rect.left < autoRect.left - 2 && entry.rect.right <= autoRect.left + 4) {
|
||||
if (entry.rect.right > leftClusterRightEdge) {
|
||||
leftClusterRightEdge = entry.rect.right;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'composer',
|
||||
workbench: null,
|
||||
titlebar: composerCard,
|
||||
targetContainer,
|
||||
actionToolbar: patchMarginNode,
|
||||
anchorNode,
|
||||
needsAutoMarginTransfer,
|
||||
leftClusterRightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
function buildComposerRightEndDockDescriptor(
|
||||
leftAnchorBtn,
|
||||
composerCard,
|
||||
bottomRowBtns,
|
||||
capsuleNode,
|
||||
portalNode
|
||||
) {
|
||||
if (!leftAnchorBtn || !composerCard) return null;
|
||||
const cardRect = composerCard.getBoundingClientRect?.();
|
||||
const minRowWidth = cardRect && cardRect.width > 0 ? cardRect.width * 0.65 : 180;
|
||||
let toolbarRow = null;
|
||||
let cur = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
|
||||
for (let d = 0; d < 8 && cur && cur !== composerCard && cur !== document.body; d += 1) {
|
||||
const r = cur.getBoundingClientRect?.();
|
||||
if (r && r.width >= minRowWidth && r.height > 0 && r.height <= 60 && isHorizontalFlexContainer(cur)) {
|
||||
toolbarRow = cur;
|
||||
break;
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
if (!toolbarRow) {
|
||||
const p = leftAnchorBtn.parentElement || leftAnchorBtn.parentNode;
|
||||
if (!p || !isHorizontalFlexContainer(p)) return null;
|
||||
toolbarRow = p;
|
||||
}
|
||||
|
||||
let leftClusterRightEdge = 0;
|
||||
if (Array.isArray(bottomRowBtns)) {
|
||||
for (const entry of bottomRowBtns) {
|
||||
if (entry?.rect?.right > leftClusterRightEdge) {
|
||||
leftClusterRightEdge = entry.rect.right;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const rowChildren = getInFlowHostChildren(toolbarRow, capsuleNode, portalNode);
|
||||
const lastChild = rowChildren.length >= 2 ? rowChildren[rowChildren.length - 1] : null;
|
||||
if (
|
||||
lastChild &&
|
||||
!lastChild.contains?.(leftAnchorBtn) &&
|
||||
isHorizontalFlexContainer(lastChild) &&
|
||||
getInFlowHostChildren(lastChild, capsuleNode, portalNode).length === 0
|
||||
) {
|
||||
return {
|
||||
kind: 'composer',
|
||||
workbench: null,
|
||||
titlebar: composerCard,
|
||||
targetContainer: lastChild,
|
||||
actionToolbar: null,
|
||||
anchorNode: null,
|
||||
needsAutoMarginTransfer: false,
|
||||
leftClusterRightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'composer',
|
||||
workbench: null,
|
||||
titlebar: composerCard,
|
||||
targetContainer: toolbarRow,
|
||||
actionToolbar: null,
|
||||
anchorNode: null,
|
||||
needsAutoMarginTransfer: true,
|
||||
leftClusterRightEdge,
|
||||
};
|
||||
}
|
||||
|
||||
function collectComposerBottomButtons(container, editorEl, editorRect, capsuleNode, portalNode) {
|
||||
const rawBtns = querySimpleSelectorList(container, ['button', '[role="button"]', '[aria-haspopup]']);
|
||||
const hostBtns = [];
|
||||
for (const btn of rawBtns) {
|
||||
if (!btn || btn === editorEl || editorEl?.contains?.(btn)) continue;
|
||||
if (editorEl && btn.contains?.(editorEl)) continue;
|
||||
if (
|
||||
btn.id === CAPSULE_HOST_ID ||
|
||||
btn.id === PORTAL_HOST_ID ||
|
||||
capsuleNode?.contains?.(btn) ||
|
||||
portalNode?.contains?.(btn)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
if (isNodeHiddenByStyle(btn)) continue;
|
||||
// 仅排除嵌套在真实紧凑按钮内部的图标/子触发器,避免外层卡片级 role="button" 误杀工具栏按钮
|
||||
let nestedInBtn = false;
|
||||
let p = btn.parentElement || btn.parentNode;
|
||||
while (p && p !== container) {
|
||||
const pTag = String(p.tagName || '').toLowerCase();
|
||||
if (pTag === 'button') {
|
||||
nestedInBtn = true;
|
||||
break;
|
||||
}
|
||||
if (
|
||||
(p.getAttribute?.('role') === 'button' || p.hasAttribute?.('aria-haspopup')) &&
|
||||
!(editorEl && p.contains?.(editorEl))
|
||||
) {
|
||||
const pr = p.getBoundingClientRect?.();
|
||||
if (pr && pr.height > 0 && pr.height <= 48 && pr.width > 0 && pr.width <= 360) {
|
||||
nestedInBtn = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
p = p.parentElement || p.parentNode;
|
||||
}
|
||||
if (nestedInBtn) continue;
|
||||
|
||||
const br = btn.getBoundingClientRect?.();
|
||||
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48) continue;
|
||||
const centerY = (br.top + br.bottom) / 2;
|
||||
if (editorRect && centerY < editorRect.top - 4) continue;
|
||||
hostBtns.push({
|
||||
btn,
|
||||
rect: br,
|
||||
centerY,
|
||||
centerX: (br.left + br.right) / 2,
|
||||
cleanText: cleanComposerButtonText(btn),
|
||||
attrText: `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim(),
|
||||
});
|
||||
}
|
||||
if (hostBtns.length === 0) return [];
|
||||
let maxCenterY = -Infinity;
|
||||
for (const item of hostBtns) {
|
||||
if (item.centerY > maxCenterY) maxCenterY = item.centerY;
|
||||
}
|
||||
const bottomBand = hostBtns.filter((item) => Math.abs(item.centerY - maxCenterY) <= 22);
|
||||
bottomBand.sort((a, b) => a.rect.left - b.rect.left);
|
||||
return bottomBand;
|
||||
}
|
||||
|
||||
function pickAutoButtonFromRow(bottomRowBtns, containerRect, options = undefined) {
|
||||
if (!Array.isArray(bottomRowBtns) || bottomRowBtns.length === 0) return null;
|
||||
const requireModelForFallback = Boolean(options?.requireModelForFallback);
|
||||
const rightSplitX = containerRect ? containerRect.left + containerRect.width * 0.35 : 0;
|
||||
const rightFirst = [
|
||||
...bottomRowBtns.filter((b) => b.centerX >= rightSplitX),
|
||||
...bottomRowBtns.filter((b) => b.centerX < rightSplitX),
|
||||
];
|
||||
|
||||
// Tier 1: 精确文本 Auto / 自动 匹配
|
||||
for (const item of rightFirst) {
|
||||
if (COMPOSER_MODE_EXACT_RE.test(item.cleanText)) {
|
||||
return { btn: item.btn, tier: 1 };
|
||||
}
|
||||
}
|
||||
|
||||
// Tier 2: 执行/权限模式文案或无障碍语义属性匹配(排除模型选择器按钮)
|
||||
for (const item of rightFirst) {
|
||||
if (isComposerModelButtonItem(item)) continue;
|
||||
if (
|
||||
(item.cleanText && COMPOSER_MODE_TEXT_RE.test(item.cleanText)) ||
|
||||
(item.attrText && COMPOSER_MODE_ATTR_RE.test(item.attrText))
|
||||
) {
|
||||
return { btn: item.btn, tier: 2 };
|
||||
}
|
||||
}
|
||||
|
||||
const hasModelBtn = bottomRowBtns.some(isComposerModelButtonItem);
|
||||
|
||||
// Tier 3: 几何右簇首按钮兜底(适配 Antigravity IDE 无 Auto 按钮、右侧为发送/语音按钮的输入栏布局)
|
||||
if (bottomRowBtns.length >= 2 && (!requireModelForFallback || hasModelBtn)) {
|
||||
let maxGap = -Infinity;
|
||||
let splitIdx = -1;
|
||||
for (let i = 1; i < bottomRowBtns.length; i += 1) {
|
||||
const gap = bottomRowBtns[i].rect.left - bottomRowBtns[i - 1].rect.right;
|
||||
if (gap > maxGap) {
|
||||
maxGap = gap;
|
||||
splitIdx = i;
|
||||
}
|
||||
}
|
||||
if (splitIdx >= 1 && maxGap >= 16) {
|
||||
return { btn: bottomRowBtns[splitIdx].btn, tier: 3 };
|
||||
}
|
||||
}
|
||||
|
||||
// Tier 4: 输入为空时若右侧发送按钮暂时隐藏、仅左侧存在模型选择器按钮,停靠至工具栏最右侧
|
||||
if (hasModelBtn && containerRect && containerRect.width >= 200) {
|
||||
const lastItem = bottomRowBtns[bottomRowBtns.length - 1];
|
||||
if (lastItem.rect.right <= containerRect.left + containerRect.width * 0.72) {
|
||||
return { btn: null, leftAnchorBtn: lastItem.btn, tier: 4 };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveComposerEditorRect(ed) {
|
||||
const er = ed?.getBoundingClientRect?.();
|
||||
if (er && er.width >= 80 && er.height >= 12) return er;
|
||||
let cur = ed;
|
||||
for (let d = 0; d < 6 && cur; d += 1) {
|
||||
if (String(cur.className || '').includes('monaco-editor')) {
|
||||
const mr = cur.getBoundingClientRect?.();
|
||||
if (mr && mr.width >= 80 && mr.height >= 12) return mr;
|
||||
break;
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
return er || null;
|
||||
}
|
||||
|
||||
function findHostComposerAutoTarget(capsuleNode = null, portalNode = null, patchedNode = null) {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const capEl = capsuleNode || document.getElementById?.(CAPSULE_HOST_ID) || null;
|
||||
const porEl = portalNode || document.getElementById?.(PORTAL_HOST_ID) || null;
|
||||
const activeRouteId = extractHostRouteCascadeId();
|
||||
|
||||
// 1. 优先从活跃会话的输入框编辑器向上定位底部工具栏和 Auto / 右簇发送按钮
|
||||
const rawEditors = querySimpleSelectorList(document, [
|
||||
'textarea',
|
||||
'[contenteditable]',
|
||||
'[role="textbox"]',
|
||||
'[data-lexical-editor]',
|
||||
'.ProseMirror',
|
||||
'.monaco-editor',
|
||||
]);
|
||||
const scoredEditors = [];
|
||||
for (const ed of rawEditors) {
|
||||
if (!ed || capEl?.contains?.(ed) || porEl?.contains?.(ed)) continue;
|
||||
if (ed.hasAttribute?.('contenteditable')) {
|
||||
const ce = String(ed.getAttribute('contenteditable') || '').trim().toLowerCase();
|
||||
if (ce === 'false' && ed.getAttribute?.('role') !== 'textbox') continue;
|
||||
}
|
||||
if (isNodeHiddenByStyle(ed) || hasExcludedComposerAncestor(ed)) continue;
|
||||
const er = resolveComposerEditorRect(ed);
|
||||
if (!er || er.width < 100 || er.height < 12 || er.height > 540) continue;
|
||||
|
||||
let score = Math.min(1200, er.width) + Math.max(0, er.bottom) * 0.2;
|
||||
if (activeRouteId) {
|
||||
let anc = ed.parentElement || ed.parentNode;
|
||||
while (anc) {
|
||||
const cid = anc.getAttribute?.('data-cascade-id');
|
||||
if (cid) {
|
||||
score += cid === activeRouteId ? 4000 : -2000;
|
||||
break;
|
||||
}
|
||||
anc = anc.parentElement || anc.parentNode;
|
||||
}
|
||||
}
|
||||
if (
|
||||
document.activeElement &&
|
||||
(ed === document.activeElement || ed.contains?.(document.activeElement))
|
||||
) {
|
||||
score += 1000;
|
||||
}
|
||||
scoredEditors.push({ ed, rect: er, score });
|
||||
}
|
||||
scoredEditors.sort((a, b) => b.score - a.score);
|
||||
|
||||
for (const { ed, rect: er } of scoredEditors) {
|
||||
const isMonacoCandidate = String(ed.className || '').includes('monaco-editor') ||
|
||||
String(ed.className || '').includes('inputarea');
|
||||
let tier3Candidate = null;
|
||||
let tier4Candidate = null;
|
||||
let cur = ed.parentElement || ed.parentNode;
|
||||
for (let depth = 0; depth < 18 && cur; depth += 1) {
|
||||
if (cur === document.body || cur === document.documentElement) break;
|
||||
const tag = String(cur.tagName || '').toLowerCase();
|
||||
if (tag === 'main' || String(cur.className || '').includes('monaco-workbench')) break;
|
||||
const cr = cur.getBoundingClientRect?.();
|
||||
if (cr && cr.height > 680) break;
|
||||
if (cr && cr.width >= 180 && cr.height > 0) {
|
||||
const bottomRowBtns = collectComposerBottomButtons(cur, ed, er, capEl, porEl);
|
||||
const picked = pickAutoButtonFromRow(bottomRowBtns, cr, {
|
||||
requireModelForFallback: isMonacoCandidate,
|
||||
});
|
||||
if (picked) {
|
||||
if (picked.tier <= 2) {
|
||||
const desc = buildComposerDockDescriptor(
|
||||
picked.btn,
|
||||
cur,
|
||||
bottomRowBtns,
|
||||
capEl,
|
||||
porEl,
|
||||
patchedNode
|
||||
);
|
||||
if (desc) return desc;
|
||||
} else if (picked.tier === 3 && !tier3Candidate) {
|
||||
tier3Candidate = { btn: picked.btn, card: cur, bottomRowBtns };
|
||||
} else if (picked.tier === 4 && !tier4Candidate) {
|
||||
tier4Candidate = { leftAnchorBtn: picked.leftAnchorBtn, card: cur, bottomRowBtns };
|
||||
}
|
||||
}
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
if (tier3Candidate) {
|
||||
const desc = buildComposerDockDescriptor(
|
||||
tier3Candidate.btn,
|
||||
tier3Candidate.card,
|
||||
tier3Candidate.bottomRowBtns,
|
||||
capEl,
|
||||
porEl,
|
||||
patchedNode
|
||||
);
|
||||
if (desc) return desc;
|
||||
}
|
||||
if (tier4Candidate) {
|
||||
const desc = buildComposerRightEndDockDescriptor(
|
||||
tier4Candidate.leftAnchorBtn,
|
||||
tier4Candidate.card,
|
||||
tier4Candidate.bottomRowBtns,
|
||||
capEl,
|
||||
porEl
|
||||
);
|
||||
if (desc) return desc;
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 兜底路径:编辑器自定义封装或暂时只读时,直接扫描底部包含模型选择器或 Auto 按钮的输入工具栏
|
||||
const vh = Number(window.innerHeight || 800);
|
||||
const allBtns = querySimpleSelectorList(document, ['button', '[role="button"]', '[aria-haspopup]']);
|
||||
let modelToolbarFallback = null;
|
||||
for (const btn of allBtns) {
|
||||
if (!btn || capEl?.contains?.(btn) || porEl?.contains?.(btn)) continue;
|
||||
if (isNodeHiddenByStyle(btn) || hasExcludedComposerAncestor(btn)) continue;
|
||||
const br = btn.getBoundingClientRect?.();
|
||||
if (!br || br.width <= 0 || br.height <= 0 || br.height > 48 || br.top < vh * 0.2) continue;
|
||||
const clean = cleanComposerButtonText(btn);
|
||||
const attr = `${btn.getAttribute?.('data-testid') || ''} ${btn.getAttribute?.('aria-label') || ''} ${btn.getAttribute?.('title') || ''}`.trim();
|
||||
const itemProbe = { cleanText: clean, attrText: attr };
|
||||
const isModeBtn =
|
||||
COMPOSER_MODE_EXACT_RE.test(clean) ||
|
||||
(!isComposerModelButtonItem(itemProbe) &&
|
||||
((clean && COMPOSER_MODE_TEXT_RE.test(clean)) || (attr && COMPOSER_MODE_ATTR_RE.test(attr))));
|
||||
const isModelBtn = isComposerModelButtonItem(itemProbe);
|
||||
if (!isModeBtn && !isModelBtn) continue;
|
||||
|
||||
let cur = btn.parentElement || btn.parentNode;
|
||||
for (let depth = 0; depth < 12 && cur; depth += 1) {
|
||||
if (cur === document.body || cur === document.documentElement) break;
|
||||
if (String(cur.className || '').includes('monaco-workbench')) break;
|
||||
const cr = cur.getBoundingClientRect?.();
|
||||
if (!cr || cr.height > 560) break;
|
||||
if (cr.width >= 200) {
|
||||
const rowBtns = collectComposerBottomButtons(cur, null, null, capEl, porEl);
|
||||
if (isModeBtn) {
|
||||
const hasModelSibling = rowBtns.some((b) => b.btn !== btn && isComposerModelButtonItem(b));
|
||||
if (hasModelSibling) {
|
||||
const desc = buildComposerDockDescriptor(btn, cur, rowBtns, capEl, porEl, patchedNode);
|
||||
if (desc) return desc;
|
||||
}
|
||||
} else if (isModelBtn && !modelToolbarFallback) {
|
||||
const picked = pickAutoButtonFromRow(rowBtns, cr, { requireModelForFallback: true });
|
||||
if (picked) {
|
||||
const desc =
|
||||
picked.tier <= 3 && picked.btn
|
||||
? buildComposerDockDescriptor(picked.btn, cur, rowBtns, capEl, porEl, patchedNode)
|
||||
: picked.tier === 4 && picked.leftAnchorBtn
|
||||
? buildComposerRightEndDockDescriptor(
|
||||
picked.leftAnchorBtn,
|
||||
cur,
|
||||
rowBtns,
|
||||
capEl,
|
||||
porEl
|
||||
)
|
||||
: null;
|
||||
if (desc) {
|
||||
if (picked.tier <= 2) return desc;
|
||||
modelToolbarFallback = desc;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
cur = cur.parentElement || cur.parentNode;
|
||||
}
|
||||
}
|
||||
if (modelToolbarFallback) return modelToolbarFallback;
|
||||
} catch {
|
||||
// 忽略输入框探测异常
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function isImmediatelyBeforeNode(node, refNode) {
|
||||
if (!node || !refNode) return false;
|
||||
if (node.nextElementSibling !== undefined) {
|
||||
return node.nextElementSibling === refNode;
|
||||
}
|
||||
if (node.nextSibling !== undefined) {
|
||||
return node.nextSibling === refNode;
|
||||
}
|
||||
const parent = node.parentElement || node.parentNode;
|
||||
if (!parent?.children) return false;
|
||||
const idx = Array.prototype.indexOf.call(parent.children, node);
|
||||
return idx >= 0 && parent.children[idx + 1] === refNode;
|
||||
}
|
||||
|
||||
export function isIdeExtensionChatFrame() {
|
||||
try {
|
||||
if (typeof window === 'undefined') return false;
|
||||
if (readInjectedWindowBridge()?.isIdeChatFrame === true) return true;
|
||||
return /[?&]extension(?:View|Variant)=/i.test(String(window.location?.search || ''));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveActiveDockTarget(options = undefined) {
|
||||
const settings = telemetryStore.getState().telemetry?.settings;
|
||||
const rawMode =
|
||||
settings?.windowMountMode ??
|
||||
readInjectedWindowBridge()?.mountMode;
|
||||
const mountMode =
|
||||
options?.mountMode ||
|
||||
normalizeClientWindowMountMode(rawMode, settings?.enableWindowOverlay);
|
||||
if (isIdeExtensionChatFrame()) {
|
||||
if (mountMode !== 'composer') return null;
|
||||
return findHostComposerAutoTarget(
|
||||
options?.capsuleNode || null,
|
||||
options?.portalNode || null,
|
||||
options?.patchedNode || null
|
||||
);
|
||||
}
|
||||
if (mountMode === 'composer') {
|
||||
const composerTarget = findHostComposerAutoTarget(
|
||||
options?.capsuleNode || null,
|
||||
options?.portalNode || null,
|
||||
options?.patchedNode || null
|
||||
);
|
||||
if (composerTarget) return composerTarget;
|
||||
}
|
||||
const ideTarget = findIdeWorkbenchTitlebar();
|
||||
if (ideTarget) return ideTarget;
|
||||
const titlebar = findHostTitlebar();
|
||||
if (!titlebar) return null;
|
||||
let targetContainer = titlebar;
|
||||
try {
|
||||
const rightGroup = titlebar.querySelector(':scope > div.shrink-0') || titlebar.lastElementChild;
|
||||
if (rightGroup && rightGroup !== titlebar.firstElementChild) {
|
||||
targetContainer = rightGroup;
|
||||
}
|
||||
} catch {
|
||||
// 忽略子选择器不兼容场景
|
||||
}
|
||||
return {
|
||||
kind: 'flow',
|
||||
workbench: null,
|
||||
titlebar,
|
||||
targetContainer,
|
||||
actionToolbar: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function findNativeTopRightAnchor() {
|
||||
try {
|
||||
if (typeof document === 'undefined' || typeof document.querySelector !== 'function') {
|
||||
return null;
|
||||
}
|
||||
const auxToggle = document.querySelector('[data-testid="toggle-aux-sidebar"]');
|
||||
if (auxToggle?.closest) {
|
||||
return auxToggle.closest('div.absolute.right-0.top-0') || auxToggle;
|
||||
}
|
||||
const candidates = document.querySelectorAll('button, a, [role="button"]');
|
||||
for (const btn of candidates) {
|
||||
const text = String(btn.textContent || '').trim();
|
||||
if (
|
||||
(text === 'Open IDE' || text === '打开 IDE' || text.includes('Open IDE') || text.includes('打开 IDE')) &&
|
||||
btn.getBoundingClientRect?.().top < 52
|
||||
) {
|
||||
return btn.closest?.('div.flex.items-center, div.absolute.right-0') || btn;
|
||||
}
|
||||
}
|
||||
return document.querySelector('div.absolute.right-0.top-0');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getLeftSidebarRightEdge(vw) {
|
||||
try {
|
||||
if (typeof document !== 'undefined' && typeof document.querySelector === 'function') {
|
||||
if (document.querySelector('.monaco-workbench')) {
|
||||
return 0;
|
||||
}
|
||||
const navEl = document.querySelector('div[role="navigation"]');
|
||||
if (navEl?.getBoundingClientRect) {
|
||||
const nr = navEl.getBoundingClientRect();
|
||||
if (nr.width > 0 && nr.left <= 8 && nr.right > 0 && nr.right < vw - 280) {
|
||||
return Math.ceil(nr.right);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略侧栏测量异常
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在主窗口挂载双栖顶栏胶囊和完整四标签悬浮面板,并注册 `window.__AGUsageMonitorOverlay` 生命周期句柄。
|
||||
*/
|
||||
const CAPSULE_EXCLUDED_CSS_SECTIONS = new Set([
|
||||
'src/styles/views-overview.css',
|
||||
'src/styles/views-consumption.css',
|
||||
'src/styles/views-tables.css',
|
||||
'src/styles/views-settings.css',
|
||||
'src/styles/controls.css',
|
||||
]);
|
||||
|
||||
let sharedOverlayStyleSheetMemo = { rawCss: '', sheet: null };
|
||||
|
||||
function buildSlimCapsuleCss(fullCss) {
|
||||
if (!fullCss || !fullCss.includes('/* --- src/styles/')) return fullCss;
|
||||
return fullCss
|
||||
.split(/(?=\/\* --- src\/styles\/)/)
|
||||
.filter((block) => {
|
||||
const m = block.match(/^\/\* --- (src\/styles\/[^\s]+) --- \*\//);
|
||||
return !m || !CAPSULE_EXCLUDED_CSS_SECTIONS.has(m[1]);
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
|
||||
export function attachShadowStyles(shadowRoot, fullCss, { slimCapsule = false } = {}) {
|
||||
if (!shadowRoot) return;
|
||||
if (
|
||||
fullCss &&
|
||||
typeof CSSStyleSheet === 'function' &&
|
||||
Array.isArray(shadowRoot.adoptedStyleSheets)
|
||||
) {
|
||||
try {
|
||||
if (sharedOverlayStyleSheetMemo.rawCss !== fullCss || !sharedOverlayStyleSheetMemo.sheet) {
|
||||
const sheet = new CSSStyleSheet();
|
||||
sheet.replaceSync(fullCss);
|
||||
sharedOverlayStyleSheetMemo = { rawCss: fullCss, sheet };
|
||||
}
|
||||
shadowRoot.adoptedStyleSheets = [sharedOverlayStyleSheetMemo.sheet];
|
||||
return;
|
||||
} catch {
|
||||
// 降级到传统 <style> 节点
|
||||
}
|
||||
}
|
||||
const styleEl = document.createElement('style');
|
||||
styleEl.textContent = slimCapsule ? buildSlimCapsuleCss(fullCss) : fullCss;
|
||||
shadowRoot.appendChild(styleEl);
|
||||
}
|
||||
@@ -0,0 +1,887 @@
|
||||
/**
|
||||
* @fileoverview Reusable model, client-source, workspace, and top-conversation breakdown
|
||||
* row builders (`ConsumptionBreakdownRows.js`) extracted from `ConsumptionView.js`.
|
||||
* Consolidates shared long-tail model partitioning, hover-popover event binding, and top-model pill rendering.
|
||||
*/
|
||||
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import {
|
||||
formatCnyApprox,
|
||||
formatMetric,
|
||||
formatPctNumber,
|
||||
formatSpeedMetric,
|
||||
formatTokensPrecise,
|
||||
formatUsd,
|
||||
getCanonicalModelColorSeed,
|
||||
resolveDeterministicModelColor,
|
||||
} from '../../core/formatters.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { createFourSegmentBar } from '../ui/FourSegmentBar.js';
|
||||
|
||||
function createSourceModelSegment() {
|
||||
const segEl = h('div', { className: 'progress-seg cons-model-seg' });
|
||||
return { el: segEl, refs: { segEl } };
|
||||
}
|
||||
|
||||
function createSourceTopModelItem() {
|
||||
const dotEl = h('span', { className: 'dot-swatch cons-model-dot cons-source-top-dot' });
|
||||
const nameEl = h('span', { className: 'cons-source-top-name' });
|
||||
const pctEl = h('strong', { className: 'cons-source-top-pct text-mono' });
|
||||
const itemEl = h('span', { className: 'cons-source-top-item' }, [dotEl, nameEl, pctEl]);
|
||||
return { el: itemEl, refs: { itemEl, dotEl, nameEl, pctEl } };
|
||||
}
|
||||
|
||||
function formatCompactSourceSharePct(pct) {
|
||||
const num = Number(pct || 0);
|
||||
if (!Number.isFinite(num) || num <= 0) return '0%';
|
||||
if (num >= 10) return `${Math.round(num)}%`;
|
||||
return `${num.toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function renderSegmentedModelBarAndTopPills(
|
||||
trackEl,
|
||||
topModelsEl,
|
||||
partitioned,
|
||||
scaleRatio,
|
||||
fallbackKey
|
||||
) {
|
||||
const barItems =
|
||||
partitioned.length > 0
|
||||
? partitioned.map((seg) => ({
|
||||
key: seg.key,
|
||||
segPct: scaleRatio > 0 ? seg.pct * scaleRatio : 0,
|
||||
color: seg.color,
|
||||
}))
|
||||
: scaleRatio > 0
|
||||
? [
|
||||
{
|
||||
key: fallbackKey,
|
||||
segPct: scaleRatio * 100,
|
||||
color: 'var(--accent-primary)',
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
patchKeyedList(trackEl, barItems, {
|
||||
keyFn: (seg) => seg.key,
|
||||
sigFn: (seg) => `${seg.key}:${seg.segPct.toFixed(2)}:${seg.color}`,
|
||||
createRow: createSourceModelSegment,
|
||||
updateRow: (segRefs, seg) => {
|
||||
patchStyleVar(segRefs.segEl, '--seg-w', `${seg.segPct.toFixed(2)}%`);
|
||||
patchStyleVar(segRefs.segEl, '--seg-color', seg.color);
|
||||
},
|
||||
});
|
||||
|
||||
const topModels = partitioned
|
||||
.filter((seg) => !seg.isOther)
|
||||
.slice(0, 3)
|
||||
.map((seg) => ({
|
||||
key: seg.key,
|
||||
label: seg.label,
|
||||
pctText: formatCompactSourceSharePct(seg.pct),
|
||||
color: seg.color,
|
||||
}));
|
||||
patchAttr(topModelsEl, 'hidden', topModels.length === 0);
|
||||
patchKeyedList(topModelsEl, topModels, {
|
||||
keyFn: (m) => m.key,
|
||||
sigFn: (m) => `${m.key}:${m.label}:${m.pctText}:${m.color}`,
|
||||
createRow: createSourceTopModelItem,
|
||||
updateRow: (mRefs, m) => {
|
||||
patchStyleVar(mRefs.dotEl, '--dot-color', m.color);
|
||||
patchText(mRefs.nameEl, m.label);
|
||||
patchText(mRefs.pctEl, m.pctText);
|
||||
patchAttr(mRefs.itemEl, 'title', `${m.label} (${m.pctText})`);
|
||||
},
|
||||
});
|
||||
|
||||
return topModels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collapses long-tail model entries into primary segments + an aggregated "Other (N)" tail.
|
||||
*/
|
||||
export function partitionModelSegments(
|
||||
mergedModels,
|
||||
modelColorMap,
|
||||
{ maxMain = 5, minSharePct = 1.5 } = {}
|
||||
) {
|
||||
if (!Array.isArray(mergedModels) || mergedModels.length === 0) return [];
|
||||
const sumTok = mergedModels.reduce((sum, m) => sum + Number(m.totalTokens || 0), 0);
|
||||
const mainModels = [];
|
||||
const tailModels = [];
|
||||
|
||||
for (let i = 0; i < mergedModels.length; i += 1) {
|
||||
const m = mergedModels[i];
|
||||
const mTok = Number(m.totalTokens || 0);
|
||||
const sharePct = sumTok > 0 ? (mTok / sumTok) * 100 : 0;
|
||||
if (i === 0 || (mainModels.length < maxMain && sharePct >= minSharePct)) {
|
||||
mainModels.push(m);
|
||||
} else {
|
||||
tailModels.push(m);
|
||||
}
|
||||
}
|
||||
|
||||
if (tailModels.length === 1) {
|
||||
mainModels.push(tailModels.pop());
|
||||
}
|
||||
|
||||
const out = mainModels.map((m) => {
|
||||
const seed = getCanonicalModelColorSeed(m);
|
||||
const color =
|
||||
modelColorMap?.get(seed) || resolveDeterministicModelColor(seed || m.displayText);
|
||||
const tok = Number(m.totalTokens || 0);
|
||||
const pct = sumTok > 0 ? (tok / sumTok) * 100 : 0;
|
||||
const label = m.displayText || m.label || m.shortName || '—';
|
||||
const inputTokens = Math.max(0, Number(m.inputTokens || 0));
|
||||
const cacheReadTokens = Math.max(0, Number(m.cacheReadTokens || 0));
|
||||
const thinkingTokens = Math.max(0, Number(m.thinkingTokens || 0));
|
||||
const responseTokens =
|
||||
m.responseTokens != null
|
||||
? Math.max(0, Number(m.responseTokens))
|
||||
: Math.max(0, Number(m.outputTokens || 0) - thinkingTokens);
|
||||
return {
|
||||
key: label,
|
||||
label,
|
||||
tok,
|
||||
pct,
|
||||
inputTokens,
|
||||
cacheReadTokens,
|
||||
thinkingTokens,
|
||||
responseTokens,
|
||||
outputTokens: responseTokens + thinkingTokens,
|
||||
tokText: formatTokensPrecise(tok),
|
||||
pctText: formatPctNumber(pct, { withSymbol: true }),
|
||||
color,
|
||||
isOther: false,
|
||||
};
|
||||
});
|
||||
|
||||
if (tailModels.length >= 2) {
|
||||
let otherTok = 0;
|
||||
let otherIn = 0;
|
||||
let otherCache = 0;
|
||||
let otherThink = 0;
|
||||
let otherResp = 0;
|
||||
for (const m of tailModels) {
|
||||
const mt = Math.max(0, Number(m.thinkingTokens || 0));
|
||||
const mr =
|
||||
m.responseTokens != null
|
||||
? Math.max(0, Number(m.responseTokens))
|
||||
: Math.max(0, Number(m.outputTokens || 0) - mt);
|
||||
otherTok += Number(m.totalTokens || 0);
|
||||
otherIn += Math.max(0, Number(m.inputTokens || 0));
|
||||
otherCache += Math.max(0, Number(m.cacheReadTokens || 0));
|
||||
otherThink += mt;
|
||||
otherResp += mr;
|
||||
}
|
||||
const otherPct = sumTok > 0 ? (otherTok / sumTok) * 100 : 0;
|
||||
const otherLabel = t('cons.otherModelsCount', { count: tailModels.length });
|
||||
out.push({
|
||||
key: '__other__',
|
||||
label: otherLabel,
|
||||
tok: otherTok,
|
||||
pct: otherPct,
|
||||
inputTokens: otherIn,
|
||||
cacheReadTokens: otherCache,
|
||||
thinkingTokens: otherThink,
|
||||
responseTokens: otherResp,
|
||||
outputTokens: otherResp + otherThink,
|
||||
tokText: formatTokensPrecise(otherTok),
|
||||
pctText: formatPctNumber(otherPct, { withSymbol: true }),
|
||||
color: 'var(--cons-other-seg)',
|
||||
isOther: true,
|
||||
});
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a model ranking row (`tokens` | `cost` | `speed` | `calls` sort modes).
|
||||
*/
|
||||
export function createBreakdownItemRow() {
|
||||
const nameTextEl = h('span', { className: 'cons-row-title-text' });
|
||||
const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]);
|
||||
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
|
||||
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const segBar = createFourSegmentBar();
|
||||
|
||||
const inLbl = h('span', { text: t('cons.footInput') });
|
||||
const cacheLbl = h('span', { text: t('cons.footCache') });
|
||||
const outLbl = h('span', { text: t('cons.footOutput') });
|
||||
const thinkLbl = h('span', { text: t('cons.footThinking') });
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
|
||||
const inVal = h('strong', { className: 'text-mono' });
|
||||
const cacheVal = h('strong', { className: 'text-mono' });
|
||||
const outVal = h('strong', { className: 'text-mono' });
|
||||
const thinkVal = h('strong', { className: 'text-mono' });
|
||||
const callsVal = h('strong', { className: 'text-mono' });
|
||||
const metricBarFillEl = h('div', { className: 'progress-seg cons-metric-fill' });
|
||||
const metricBarEl = h(
|
||||
'div',
|
||||
{ className: 'progress-track cons-seg-bar cons-metric-bar', hidden: true },
|
||||
[metricBarFillEl]
|
||||
);
|
||||
const tokenFootEl = h('div', { className: 'cons-item-foot' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
inLbl,
|
||||
inVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
cacheLbl,
|
||||
cacheVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
thinkLbl,
|
||||
thinkVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
outLbl,
|
||||
outVal,
|
||||
]),
|
||||
h('span', { className: 'legend-left' }, [callsLbl, callsVal]),
|
||||
]);
|
||||
const perfMainEl = h('span', { className: 'cons-model-perf-main text-mono' });
|
||||
const perfUnitCostEl = h('span', { className: 'cons-model-unit-cost text-mono', hidden: true });
|
||||
const perfFootEl = h('div', { className: 'cons-model-perf-foot', hidden: true }, [
|
||||
perfMainEl,
|
||||
perfUnitCostEl,
|
||||
]);
|
||||
const focusLeftEl = h('span', { className: 'cons-model-focus-left text-mono' });
|
||||
const focusRightEl = h('span', { className: 'cons-model-focus-right text-mono' });
|
||||
const focusFootEl = h(
|
||||
'div',
|
||||
{ className: 'cons-item-foot cons-model-focus-foot', hidden: true },
|
||||
[focusLeftEl, focusRightEl]
|
||||
);
|
||||
|
||||
const rowEl = h('div', { className: 'cons-item-row' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
nameEl,
|
||||
h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]),
|
||||
]),
|
||||
segBar.el,
|
||||
metricBarEl,
|
||||
tokenFootEl,
|
||||
perfFootEl,
|
||||
focusFootEl,
|
||||
]);
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: {
|
||||
nameEl,
|
||||
nameTextEl,
|
||||
pctBadge,
|
||||
totalTokEl,
|
||||
costEl,
|
||||
segBar,
|
||||
metricBarEl,
|
||||
metricBarFillEl,
|
||||
tokenFootEl,
|
||||
inLbl,
|
||||
cacheLbl,
|
||||
outLbl,
|
||||
thinkLbl,
|
||||
callsLbl,
|
||||
inVal,
|
||||
cacheVal,
|
||||
outVal,
|
||||
thinkVal,
|
||||
callsVal,
|
||||
perfFootEl,
|
||||
perfMainEl,
|
||||
perfUnitCostEl,
|
||||
focusFootEl,
|
||||
focusLeftEl,
|
||||
focusRightEl,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Incrementally patches a model ranking row.
|
||||
*/
|
||||
export function updateBreakdownItemRow(refs, item, totalsCtx, sortMode = 'tokens') {
|
||||
const displayLabel = item.label || item.name || item.shortName || '—';
|
||||
patchText(refs.nameTextEl, displayLabel);
|
||||
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
|
||||
|
||||
const total = Number(item.totalTokens || 0);
|
||||
const costVal = Number(item.costUsd || 0);
|
||||
const callsCount = Number(item.calls || 0);
|
||||
const isAllUnpriced =
|
||||
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
|
||||
const costText = formatUsd(isAllUnpriced ? null : costVal, {
|
||||
precise: costVal > 0 && costVal < 0.1,
|
||||
});
|
||||
|
||||
const avgTps =
|
||||
item.avgTokPerSec != null &&
|
||||
Number.isFinite(Number(item.avgTokPerSec)) &&
|
||||
Number(item.avgTokPerSec) > 0
|
||||
? Number(item.avgTokPerSec)
|
||||
: null;
|
||||
const avgTtft =
|
||||
item.avgTtftSec != null &&
|
||||
Number.isFinite(Number(item.avgTtftSec)) &&
|
||||
Number(item.avgTtftSec) >= 0
|
||||
? Number(item.avgTtftSec)
|
||||
: null;
|
||||
const hasExplicitCachePct =
|
||||
item.cacheHitPct != null && Number.isFinite(Number(item.cacheHitPct));
|
||||
const promptTok = Number(item.inputTokens || 0) + Number(item.cacheReadTokens || 0);
|
||||
const cachePctVal = hasExplicitCachePct
|
||||
? Number(item.cacheHitPct)
|
||||
: promptTok > 0 && Number(item.cacheReadTokens || 0) > 0
|
||||
? +((Number(item.cacheReadTokens || 0) / promptTok) * 100).toFixed(1)
|
||||
: 0;
|
||||
const cachePctStr = formatPctNumber(cachePctVal);
|
||||
const effCostPer1M =
|
||||
!isAllUnpriced && costVal > 0 && total >= 1000 ? costVal / (total / 1_000_000) : null;
|
||||
const outTok = Number(
|
||||
item.outputTokens ?? Number(item.responseTokens || 0) + Number(item.thinkingTokens || 0)
|
||||
);
|
||||
|
||||
if (sortMode === 'cost') {
|
||||
const costBase = Number(totalsCtx?.totalCost || 0);
|
||||
const costShare = costBase > 0 ? +((costVal / costBase) * 100).toFixed(1) : 0;
|
||||
const barPct =
|
||||
costBase > 0 && costVal > 0 ? Math.min(100, Math.max(1, (costVal / costBase) * 100)) : 0;
|
||||
patchAttr(refs.pctBadge, 'hidden', false);
|
||||
patchAttr(refs.pctBadge, 'title', null);
|
||||
patchText(refs.pctBadge, formatPctNumber(costShare, { withSymbol: true }));
|
||||
patchText(refs.totalTokEl, isAllUnpriced ? '' : formatCnyApprox(costVal));
|
||||
patchText(refs.costEl, costText);
|
||||
|
||||
patchAttr(refs.segBar.el, 'hidden', true);
|
||||
patchAttr(refs.metricBarEl, 'hidden', false);
|
||||
patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`);
|
||||
patchClasses(refs.metricBarFillEl, {
|
||||
'tone-cost': true,
|
||||
'tone-speed': false,
|
||||
'tone-calls': false,
|
||||
});
|
||||
|
||||
patchAttr(refs.tokenFootEl, 'hidden', true);
|
||||
patchAttr(refs.perfFootEl, 'hidden', true);
|
||||
patchAttr(refs.focusFootEl, 'hidden', false);
|
||||
const unitPart =
|
||||
effCostPer1M !== null
|
||||
? t('cons.modelUnitCost', {
|
||||
cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }),
|
||||
})
|
||||
: '';
|
||||
const cachePart = t('cons.topConvCacheMeta', { pct: cachePctStr });
|
||||
patchText(refs.focusLeftEl, unitPart ? `${unitPart} · ${cachePart}` : cachePart);
|
||||
patchText(
|
||||
refs.focusRightEl,
|
||||
`${formatTokensPrecise(total)} · ${t('cons.callsCount', { calls: callsCount })}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (sortMode === 'speed') {
|
||||
const maxTps = Number(totalsCtx?.maxAvgTps || 0);
|
||||
const speedPct =
|
||||
maxTps > 0 && avgTps !== null ? Math.min(100, Math.max(2, (avgTps / maxTps) * 100)) : 0;
|
||||
patchAttr(refs.pctBadge, 'hidden', avgTps === null);
|
||||
patchAttr(refs.pctBadge, 'title', avgTps !== null ? t('cons.speedRelTip') : null);
|
||||
patchText(refs.pctBadge, avgTps !== null ? `${Math.round(speedPct)}%` : '');
|
||||
patchText(
|
||||
refs.totalTokEl,
|
||||
avgTtft !== null ? t('cons.focusTtft', { ttft: formatMetric(avgTtft, 's') }) : ''
|
||||
);
|
||||
patchText(refs.costEl, formatSpeedMetric(avgTps, ' tok/s'));
|
||||
|
||||
patchAttr(refs.segBar.el, 'hidden', true);
|
||||
patchAttr(refs.metricBarEl, 'hidden', false);
|
||||
patchStyleVar(refs.metricBarFillEl, '--seg-w', `${speedPct.toFixed(2)}%`);
|
||||
patchClasses(refs.metricBarFillEl, {
|
||||
'tone-cost': false,
|
||||
'tone-speed': true,
|
||||
'tone-calls': false,
|
||||
});
|
||||
|
||||
patchAttr(refs.tokenFootEl, 'hidden', true);
|
||||
patchAttr(refs.perfFootEl, 'hidden', true);
|
||||
patchAttr(refs.focusFootEl, 'hidden', false);
|
||||
patchText(
|
||||
refs.focusLeftEl,
|
||||
t('cons.focusSpeedMeta', {
|
||||
ttft: formatMetric(avgTtft, 's'),
|
||||
cache: cachePctStr,
|
||||
out: formatTokensPrecise(outTok),
|
||||
})
|
||||
);
|
||||
patchText(refs.focusRightEl, t('cons.callsCount', { calls: callsCount }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (sortMode === 'calls') {
|
||||
const callsBase = Number(totalsCtx?.totalCalls || 0);
|
||||
const callsShare = callsBase > 0 ? +((callsCount / callsBase) * 100).toFixed(1) : 0;
|
||||
const barPct =
|
||||
callsBase > 0 && callsCount > 0
|
||||
? Math.min(100, Math.max(1, (callsCount / callsBase) * 100))
|
||||
: 0;
|
||||
patchAttr(refs.pctBadge, 'hidden', false);
|
||||
patchAttr(refs.pctBadge, 'title', null);
|
||||
patchText(refs.pctBadge, formatPctNumber(callsShare, { withSymbol: true }));
|
||||
patchText(refs.totalTokEl, formatTokensPrecise(total));
|
||||
patchText(refs.costEl, t('cons.callsCount', { calls: callsCount }));
|
||||
|
||||
patchAttr(refs.segBar.el, 'hidden', true);
|
||||
patchAttr(refs.metricBarEl, 'hidden', false);
|
||||
patchStyleVar(refs.metricBarFillEl, '--seg-w', `${barPct.toFixed(2)}%`);
|
||||
patchClasses(refs.metricBarFillEl, {
|
||||
'tone-cost': false,
|
||||
'tone-speed': false,
|
||||
'tone-calls': true,
|
||||
});
|
||||
|
||||
patchAttr(refs.tokenFootEl, 'hidden', true);
|
||||
patchAttr(refs.perfFootEl, 'hidden', true);
|
||||
patchAttr(refs.focusFootEl, 'hidden', false);
|
||||
const avgPerCall = callsCount > 0 ? total / callsCount : 0;
|
||||
patchText(
|
||||
refs.focusLeftEl,
|
||||
t('cons.focusCallsMeta', {
|
||||
avgTok: formatTokensPrecise(avgPerCall),
|
||||
cost: costText,
|
||||
})
|
||||
);
|
||||
patchText(refs.focusRightEl, t('cons.topConvCacheMeta', { pct: cachePctStr }));
|
||||
return;
|
||||
}
|
||||
|
||||
patchText(refs.inLbl, t('cons.footInput'));
|
||||
patchText(refs.cacheLbl, t('cons.footCache'));
|
||||
patchText(refs.outLbl, t('cons.footOutput'));
|
||||
patchText(refs.thinkLbl, t('cons.footThinking'));
|
||||
patchText(refs.callsLbl, t('cons.footCalls'));
|
||||
const grandTotalTokens = Number(totalsCtx?.totalTokens || 0);
|
||||
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
|
||||
const scaleRatio =
|
||||
grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.008, total / grandTotalTokens)) : 0;
|
||||
patchAttr(refs.pctBadge, 'hidden', false);
|
||||
patchAttr(refs.pctBadge, 'title', null);
|
||||
patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true }));
|
||||
patchText(refs.totalTokEl, formatTokensPrecise(total));
|
||||
patchText(refs.costEl, costText);
|
||||
|
||||
const responseTok =
|
||||
item.responseTokens != null
|
||||
? Number(item.responseTokens)
|
||||
: Math.max(0, Number(item.outputTokens || 0) - Number(item.thinkingTokens || 0));
|
||||
const thinkingTok = Number(item.thinkingTokens || 0);
|
||||
|
||||
patchAttr(refs.segBar.el, 'hidden', false);
|
||||
patchAttr(refs.metricBarEl, 'hidden', true);
|
||||
refs.segBar.update({
|
||||
inputTokens: Number(item.inputTokens || 0),
|
||||
cacheReadTokens: Number(item.cacheReadTokens || 0),
|
||||
responseTokens: responseTok,
|
||||
thinkingTokens: thinkingTok,
|
||||
scaleRatio,
|
||||
});
|
||||
|
||||
patchAttr(refs.tokenFootEl, 'hidden', false);
|
||||
patchAttr(refs.focusFootEl, 'hidden', true);
|
||||
patchText(refs.inVal, formatTokensPrecise(item.inputTokens || 0));
|
||||
patchText(refs.cacheVal, formatTokensPrecise(item.cacheReadTokens || 0));
|
||||
patchText(refs.outVal, formatTokensPrecise(responseTok));
|
||||
patchText(refs.thinkVal, formatTokensPrecise(thinkingTok));
|
||||
patchText(refs.callsVal, String(callsCount));
|
||||
|
||||
const hasPerfMeta = avgTps !== null || avgTtft !== null || effCostPer1M !== null;
|
||||
patchAttr(refs.perfFootEl, 'hidden', !hasPerfMeta);
|
||||
if (hasPerfMeta) {
|
||||
if (avgTps !== null || avgTtft !== null) {
|
||||
patchText(
|
||||
refs.perfMainEl,
|
||||
t('steps.modelPerfFoot', {
|
||||
tps: formatSpeedMetric(avgTps, ' tok/s'),
|
||||
ttft: formatMetric(avgTtft, 's'),
|
||||
cache: cachePctStr,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
patchText(refs.perfMainEl, t('cons.topConvCacheMeta', { pct: cachePctStr }));
|
||||
}
|
||||
patchAttr(refs.perfUnitCostEl, 'hidden', effCostPer1M === null);
|
||||
patchText(
|
||||
refs.perfUnitCostEl,
|
||||
effCostPer1M !== null
|
||||
? t('cons.modelUnitCost', {
|
||||
cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }),
|
||||
})
|
||||
: ''
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds shared popover hover callbacks to build source-breakdown and workspace/conversation rows.
|
||||
*/
|
||||
export function createConsumptionBreakdownRowBuilders({
|
||||
showPopover,
|
||||
movePopover,
|
||||
hidePopover,
|
||||
isHoveredTarget,
|
||||
onSelectConversation,
|
||||
}) {
|
||||
function isNodeInside(root, node) {
|
||||
if (!root || !node) return false;
|
||||
if (typeof root.contains === 'function') return root.contains(node);
|
||||
let cur = node;
|
||||
while (cur) {
|
||||
if (cur === root) return true;
|
||||
cur = cur.parentNode || null;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function attachUnifiedHoverZone(zoneEl, compatTargets, rowState) {
|
||||
zoneEl.addEventListener('mouseenter', (e) => {
|
||||
if (rowState.hoverPayload) {
|
||||
showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null);
|
||||
}
|
||||
});
|
||||
zoneEl.addEventListener('mousemove', (e) => {
|
||||
if (rowState.hoverPayload && isHoveredTarget(zoneEl)) {
|
||||
movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null);
|
||||
}
|
||||
});
|
||||
zoneEl.addEventListener('mouseleave', () => {
|
||||
if (isHoveredTarget(zoneEl)) hidePopover();
|
||||
});
|
||||
|
||||
for (const childEl of compatTargets) {
|
||||
if (!childEl) continue;
|
||||
childEl.addEventListener('mouseenter', (e) => {
|
||||
if (rowState.hoverPayload) {
|
||||
showPopover(zoneEl, rowState.hoverPayload, e?.clientX ?? null, e?.clientY ?? null);
|
||||
}
|
||||
});
|
||||
childEl.addEventListener('mousemove', (e) => {
|
||||
if (rowState.hoverPayload && isHoveredTarget(zoneEl)) {
|
||||
movePopover(zoneEl, e?.clientX ?? null, e?.clientY ?? null);
|
||||
}
|
||||
});
|
||||
childEl.addEventListener('mouseleave', (e) => {
|
||||
const nextEl = e?.relatedTarget || null;
|
||||
if (isNodeInside(zoneEl, nextEl)) {
|
||||
return;
|
||||
}
|
||||
if (isHoveredTarget(zoneEl)) hidePopover();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function createSourceBreakdownRow() {
|
||||
const nameTextEl = h('span', { className: 'cons-row-title-text' });
|
||||
const nameEl = h('strong', { className: 'cons-row-title' }, [nameTextEl]);
|
||||
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
|
||||
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
||||
const rowState = { hoverPayload: null };
|
||||
|
||||
const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]);
|
||||
const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true });
|
||||
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
const callsVal = h('strong', { className: 'text-mono' });
|
||||
|
||||
const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [
|
||||
barHitEl,
|
||||
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
||||
topModelsEl,
|
||||
h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]),
|
||||
]),
|
||||
]);
|
||||
attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState);
|
||||
|
||||
const rowEl = h('div', { className: 'cons-item-row cons-source-row' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
nameEl,
|
||||
h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]),
|
||||
]),
|
||||
hoverZoneEl,
|
||||
]);
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: {
|
||||
nameEl,
|
||||
nameTextEl,
|
||||
pctBadge,
|
||||
totalTokEl,
|
||||
costEl,
|
||||
hoverZoneEl,
|
||||
barHitEl,
|
||||
trackEl,
|
||||
topModelsEl,
|
||||
callsLbl,
|
||||
callsVal,
|
||||
rowState,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function updateSourceBreakdownRow(refs, item, grandTotalTokens, modelColorMap) {
|
||||
patchText(refs.callsLbl, t('cons.footCalls'));
|
||||
const displayLabel = item.label || item.name || '—';
|
||||
patchText(refs.nameTextEl, displayLabel);
|
||||
patchAttr(refs.nameEl, 'title', item.title || displayLabel);
|
||||
|
||||
const total = Number(item.totalTokens || 0);
|
||||
const share = grandTotalTokens > 0 ? +((total / grandTotalTokens) * 100).toFixed(1) : 0;
|
||||
const scaleRatio =
|
||||
grandTotalTokens > 0 && total > 0 ? Math.min(1, Math.max(0.01, total / grandTotalTokens)) : 0;
|
||||
patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true }));
|
||||
patchText(refs.totalTokEl, formatTokensPrecise(total));
|
||||
|
||||
const costVal = Number(item.costUsd || 0);
|
||||
const callsCount = Number(item.calls || 0);
|
||||
const isAllUnpriced =
|
||||
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
|
||||
const costText = formatUsd(isAllUnpriced ? null : costVal, {
|
||||
precise: costVal > 0 && costVal < 0.1,
|
||||
});
|
||||
patchText(refs.costEl, costText);
|
||||
patchText(refs.callsVal, String(callsCount));
|
||||
|
||||
const sourceModels = Array.isArray(item.mergedModels) ? item.mergedModels : [];
|
||||
const partitioned = partitionModelSegments(sourceModels, modelColorMap, {
|
||||
maxMain: 5,
|
||||
minSharePct: 1.5,
|
||||
});
|
||||
|
||||
renderSegmentedModelBarAndTopPills(
|
||||
refs.trackEl,
|
||||
refs.topModelsEl,
|
||||
partitioned,
|
||||
total > 0 ? scaleRatio : 0,
|
||||
'__source_fallback__'
|
||||
);
|
||||
|
||||
refs.rowState.hoverPayload =
|
||||
total > 0 || callsCount > 0
|
||||
? {
|
||||
title: displayLabel,
|
||||
calls: callsCount,
|
||||
totalTokens: total,
|
||||
costText,
|
||||
inputTokens: item.inputTokens,
|
||||
cacheReadTokens: item.cacheReadTokens,
|
||||
thinkingTokens: item.thinkingTokens,
|
||||
responseTokens: item.responseTokens,
|
||||
outputTokens: item.outputTokens,
|
||||
segments: partitioned,
|
||||
}
|
||||
: null;
|
||||
patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) });
|
||||
}
|
||||
|
||||
function createTopConversationRow() {
|
||||
const titleTextEl = h('span', { className: 'cons-row-title-text' });
|
||||
const wsBadgeEl = h('span', { className: 'cons-ws-sessions-tag text-mono', hidden: true });
|
||||
const titleEl = h('strong', { className: 'cons-row-title cons-top-conv-title' }, [
|
||||
titleTextEl,
|
||||
wsBadgeEl,
|
||||
]);
|
||||
const pctBadge = h('span', { className: 'cons-share-pill text-mono', text: '0%' });
|
||||
const totalTokEl = h('span', { className: 'cons-row-tok text-mono' });
|
||||
const costEl = h('strong', { className: 'cons-row-cost text-mono' });
|
||||
const trackEl = h('div', { className: 'progress-track cons-seg-bar cons-source-model-bar' });
|
||||
const rowState = { cascadeId: '', canJump: false, hoverPayload: null };
|
||||
|
||||
const barHitEl = h('div', { className: 'cons-source-bar-hit' }, [trackEl]);
|
||||
const topModelsEl = h('div', { className: 'cons-source-top-models', hidden: true });
|
||||
|
||||
const fallbackMetaEl = h('span', { className: 'cons-top-conv-meta', hidden: true });
|
||||
const callsLbl = h('span', { text: t('cons.footCalls') });
|
||||
const callsVal = h('strong', { className: 'text-mono' });
|
||||
|
||||
const hoverZoneEl = h('div', { className: 'cons-source-hover-zone' }, [
|
||||
barHitEl,
|
||||
h('div', { className: 'cons-item-foot cons-source-foot' }, [
|
||||
topModelsEl,
|
||||
fallbackMetaEl,
|
||||
h('span', { className: 'legend-left cons-calls-stat' }, [callsLbl, callsVal]),
|
||||
]),
|
||||
]);
|
||||
attachUnifiedHoverZone(hoverZoneEl, [barHitEl, topModelsEl], rowState);
|
||||
|
||||
const rowEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'cons-top-conv-row',
|
||||
onClick: () => {
|
||||
if (!rowState.canJump || !rowState.cascadeId) return;
|
||||
hidePopover();
|
||||
onSelectConversation?.(rowState.cascadeId);
|
||||
},
|
||||
},
|
||||
[
|
||||
h('div', { className: 'panel-header' }, [
|
||||
titleEl,
|
||||
h('span', { className: 'cons-row-metrics' }, [pctBadge, totalTokEl, costEl]),
|
||||
]),
|
||||
hoverZoneEl,
|
||||
]
|
||||
);
|
||||
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: {
|
||||
rowEl,
|
||||
titleEl,
|
||||
titleTextEl,
|
||||
wsBadgeEl,
|
||||
pctBadge,
|
||||
totalTokEl,
|
||||
costEl,
|
||||
hoverZoneEl,
|
||||
barHitEl,
|
||||
trackEl,
|
||||
topModelsEl,
|
||||
fallbackMetaEl,
|
||||
callsLbl,
|
||||
callsVal,
|
||||
rowState,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function updateTopConversationRow(refs, item, bases, modelColorMap, sortMode = 'cost') {
|
||||
patchText(refs.callsLbl, t('cons.footCalls'));
|
||||
const isWorkspaceRow = Boolean(item.isWorkspaceRow);
|
||||
const title = isWorkspaceRow
|
||||
? item.isUnbound
|
||||
? t('cons.workspaceUnbound')
|
||||
: String(item.label || item.workspacePath || '—').trim()
|
||||
: String(item.title || item.cascadeId || '—').trim();
|
||||
refs.rowState.cascadeId = isWorkspaceRow ? '' : String(item.cascadeId || '');
|
||||
refs.rowState.canJump =
|
||||
!isWorkspaceRow && item.canJump !== false && Boolean(refs.rowState.cascadeId);
|
||||
patchClasses(refs.rowEl, {
|
||||
'is-jumpable': refs.rowState.canJump,
|
||||
'cons-workspace-row': isWorkspaceRow,
|
||||
});
|
||||
const baseTip =
|
||||
isWorkspaceRow && item.workspacePath && item.workspacePath !== title
|
||||
? `${title} (${item.workspacePath})`
|
||||
: title;
|
||||
patchAttr(
|
||||
refs.rowEl,
|
||||
'title',
|
||||
refs.rowState.canJump ? `${baseTip} — ${t('cons.topConvJumpTip')}` : baseTip
|
||||
);
|
||||
patchText(refs.titleTextEl, title);
|
||||
if (refs.wsBadgeEl) {
|
||||
const showWsBadge = isWorkspaceRow && Number(item.sessionCount || 0) > 0;
|
||||
patchAttr(refs.wsBadgeEl, 'hidden', !showWsBadge);
|
||||
if (showWsBadge) {
|
||||
patchText(refs.wsBadgeEl, t('cons.workspaceSessions', { count: item.sessionCount }));
|
||||
}
|
||||
}
|
||||
|
||||
const total = Number(item.totalTokens || 0);
|
||||
const costVal = Number(item.costUsd || 0);
|
||||
const callsCount = Number(item.calls || 0);
|
||||
const isAllUnpriced =
|
||||
callsCount > 0 && Number(item.unpricedCalls || 0) >= callsCount && !(costVal > 0);
|
||||
const costText = formatUsd(isAllUnpriced ? null : costVal, {
|
||||
precise: costVal > 0 && costVal < 0.1,
|
||||
});
|
||||
|
||||
const tokBase = Number(bases?.tokens || 0);
|
||||
const costBase = Number(bases?.cost || 0);
|
||||
const useCostBasis = sortMode === 'cost' && costBase > 0;
|
||||
const share = useCostBasis
|
||||
? +((costVal / costBase) * 100).toFixed(1)
|
||||
: tokBase > 0
|
||||
? +((total / tokBase) * 100).toFixed(1)
|
||||
: 0;
|
||||
const scaleRatio = useCostBasis
|
||||
? costVal > 0
|
||||
? Math.min(1, Math.max(0.01, costVal / costBase))
|
||||
: 0
|
||||
: tokBase > 0 && total > 0
|
||||
? Math.min(1, Math.max(0.01, total / tokBase))
|
||||
: 0;
|
||||
|
||||
patchText(refs.pctBadge, formatPctNumber(share, { withSymbol: true }));
|
||||
if (sortMode === 'tokens') {
|
||||
patchText(refs.totalTokEl, costText);
|
||||
patchText(refs.costEl, formatTokensPrecise(total));
|
||||
} else {
|
||||
patchText(refs.totalTokEl, formatTokensPrecise(total));
|
||||
patchText(refs.costEl, costText);
|
||||
}
|
||||
patchText(refs.callsVal, String(callsCount));
|
||||
|
||||
const convModels = Array.isArray(item.mergedModels) ? item.mergedModels : [];
|
||||
const partitioned = partitionModelSegments(convModels, modelColorMap, {
|
||||
maxMain: 5,
|
||||
minSharePct: 1.5,
|
||||
});
|
||||
const topModels = renderSegmentedModelBarAndTopPills(
|
||||
refs.trackEl,
|
||||
refs.topModelsEl,
|
||||
partitioned,
|
||||
scaleRatio,
|
||||
'__conv_fallback__'
|
||||
);
|
||||
|
||||
const showFallbackMeta = topModels.length === 0;
|
||||
patchAttr(refs.fallbackMetaEl, 'hidden', !showFallbackMeta);
|
||||
if (showFallbackMeta) {
|
||||
const srcLabel = item.sourceName || item.appSource || '';
|
||||
const cacheLabel = t('cons.topConvCacheMeta', {
|
||||
pct: formatPctNumber(item.cacheHitPct ?? 0),
|
||||
});
|
||||
patchText(refs.fallbackMetaEl, srcLabel ? `${srcLabel} · ${cacheLabel}` : cacheLabel);
|
||||
}
|
||||
|
||||
refs.rowState.hoverPayload =
|
||||
partitioned.length > 0 && (total > 0 || callsCount > 0)
|
||||
? {
|
||||
title,
|
||||
calls: callsCount,
|
||||
totalTokens: total,
|
||||
costText,
|
||||
inputTokens: item.inputTokens,
|
||||
cacheReadTokens: item.cacheReadTokens,
|
||||
thinkingTokens: item.thinkingTokens,
|
||||
responseTokens: item.responseTokens,
|
||||
outputTokens: item.outputTokens,
|
||||
segments: partitioned,
|
||||
}
|
||||
: null;
|
||||
patchClasses(refs.hoverZoneEl, { 'is-interactive': Boolean(refs.rowState.hoverPayload) });
|
||||
}
|
||||
|
||||
return {
|
||||
createSourceBreakdownRow,
|
||||
updateSourceBreakdownRow,
|
||||
createTopConversationRow,
|
||||
updateTopConversationRow,
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -430,6 +430,9 @@ test('Feature 5: TrendAreaChart drill-down click and unified Models/Sessions seg
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
sidecar: {
|
||||
fetch: (url, init) => globalThis.fetch(url, init),
|
||||
},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
requestAnimationFrame: (cb) => {
|
||||
@@ -621,6 +624,9 @@ test('Feature 6: model ranking multi-metric sort with efficiency footer & valida
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
sidecar: {
|
||||
fetch: (url, init) => globalThis.fetch(url, init),
|
||||
},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
requestAnimationFrame: (cb) => {
|
||||
@@ -1099,6 +1105,9 @@ test('Feature 9: workspace/project cost aggregation (full + fast paths) and Proj
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
sidecar: {
|
||||
fetch: (url, init) => globalThis.fetch(url, init),
|
||||
},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
requestAnimationFrame: (cb) => {
|
||||
@@ -2886,3 +2895,106 @@ test('P2 regressions: bundler regex-after-paren lexer, shared URI/prompt/atomic
|
||||
assert.equal(reimported.patch.experimentalQuotaReservation, true);
|
||||
assert.equal(reimported.patch.accountQuotaRefreshMinutes, 180);
|
||||
});
|
||||
|
||||
test('Feature 16: P3 extracted sub-modules (stepChartMath, overlayHostAnchors, ConsumptionBreakdownRows) and doc-to-code parity guard', async (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
location: { pathname: '/' },
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
requestAnimationFrame: (cb) => setTimeout(cb, 0),
|
||||
cancelAnimationFrame: (id) => clearTimeout(id),
|
||||
};
|
||||
t.after(() => {
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
});
|
||||
|
||||
const [
|
||||
{ computeLinearFit, computeNiceYScale, buildSplinePath },
|
||||
{ computeCapsuleLayoutMode },
|
||||
{ partitionModelSegments },
|
||||
{ DEFAULT_SETTINGS_SCHEMA },
|
||||
{ BRIDGE_API_ROUTE_DEFS },
|
||||
fsMod,
|
||||
pathMod,
|
||||
urlMod,
|
||||
] = await Promise.all([
|
||||
import('../src/components/charts/stepChartMath.js'),
|
||||
import('../src/components/layout/overlayHostAnchors.js'),
|
||||
import('../src/components/widgets/ConsumptionBreakdownRows.js'),
|
||||
import('../backend/settings-schema.mjs'),
|
||||
import('../shared/window-bridge-protocol.mjs'),
|
||||
import('node:fs'),
|
||||
import('node:path'),
|
||||
import('node:url'),
|
||||
]);
|
||||
|
||||
// 1. Extracted chart math + layout hysteresis + model segment partition
|
||||
const fit = computeLinearFit([20, 30, 40], { xs: [1000, 2000, 3000] });
|
||||
assert.ok(fit && Math.abs(fit.slope - 0.01) < 1e-6);
|
||||
const scale = computeNiceYScale(0, 93, 4);
|
||||
assert.ok(scale.max >= 93 && scale.ticks.length >= 2);
|
||||
assert.match(buildSplinePath([{ x: 0, y: 10 }, { x: 20, y: 30 }, { x: 40, y: 15 }]), /^M/);
|
||||
|
||||
assert.equal(computeCapsuleLayoutMode(380, 'wide', { slotCount: 3 }), 'wide');
|
||||
assert.equal(computeCapsuleLayoutMode(260, 'wide', { slotCount: 3 }), 'wide');
|
||||
assert.equal(computeCapsuleLayoutMode(260, 'compact', { slotCount: 3 }), 'compact');
|
||||
assert.equal(computeCapsuleLayoutMode(70, 'minimal', { slotCount: 3 }), 'ring-only');
|
||||
|
||||
const segs = partitionModelSegments(
|
||||
[
|
||||
{ label: '4-neon', totalTokens: 700 },
|
||||
{ label: '4-argon', totalTokens: 300 },
|
||||
],
|
||||
new Map()
|
||||
);
|
||||
assert.equal(segs.length, 2);
|
||||
assert.equal(Math.round(segs[0].pct + segs[1].pct), 100);
|
||||
|
||||
// 2. Repo documentation parity against live schema & route definitions
|
||||
// Note: `docs/` and `plan/` are local engineering directories (.gitignore); guard with existsSync so fresh CI clones pass cleanly while local dev enforces 100% parity.
|
||||
const repoRoot = pathMod.resolve(pathMod.dirname(urlMod.fileURLToPath(import.meta.url)), '..', '..', '..');
|
||||
assert.ok(fsMod.existsSync(pathMod.join(repoRoot, 'CHANGELOG.md')), 'Root CHANGELOG.md must exist');
|
||||
const readmeEn = fsMod.readFileSync(pathMod.join(repoRoot, 'README.md'), 'utf8');
|
||||
const readmeZh = fsMod.readFileSync(pathMod.join(repoRoot, 'README.zh-CN.md'), 'utf8');
|
||||
assert.ok(readmeEn.includes('defineComponent') && !readmeEn.includes('native Web Components'));
|
||||
assert.ok(readmeZh.includes('defineComponent') && !readmeZh.includes('原生 Web Components'));
|
||||
|
||||
const docsDir = pathMod.join(repoRoot, 'docs');
|
||||
if (fsMod.existsSync(docsDir)) {
|
||||
const settingsDoc = fsMod.readFileSync(pathMod.join(docsDir, 'settings-and-cli.md'), 'utf8');
|
||||
for (const key of Object.keys(DEFAULT_SETTINGS_SCHEMA)) {
|
||||
assert.ok(settingsDoc.includes(`\`${key}\``), `docs/settings-and-cli.md must document setting key: ${key}`);
|
||||
}
|
||||
|
||||
const apiDoc = fsMod.readFileSync(pathMod.join(docsDir, 'backend-and-api.md'), 'utf8');
|
||||
for (const route of BRIDGE_API_ROUTE_DEFS) {
|
||||
assert.ok(
|
||||
apiDoc.includes(`${route.method} ${route.path}`),
|
||||
`docs/backend-and-api.md must document route: ${route.method} ${route.path}`
|
||||
);
|
||||
}
|
||||
for (const requiredModule of [
|
||||
'cloudcode-proxy.mjs',
|
||||
'quota-reservation.mjs',
|
||||
'fs-atomic.mjs',
|
||||
'trajectory-cache-store.mjs',
|
||||
'.xlsx',
|
||||
]) {
|
||||
assert.ok(apiDoc.includes(requiredModule), `docs/backend-and-api.md must cover ${requiredModule}`);
|
||||
}
|
||||
|
||||
const feDoc = fsMod.readFileSync(pathMod.join(docsDir, 'frontend-core-and-store.md'), 'utf8');
|
||||
assert.ok(feDoc.includes('xlsxBuilder.js') && feDoc.includes('exportBinaryFileWithFeedback'));
|
||||
}
|
||||
|
||||
const legacyPlanPath = pathMod.join(repoRoot, 'plan', 'code-audit-and-cleanup-plan.md');
|
||||
if (fsMod.existsSync(legacyPlanPath)) {
|
||||
const legacyPlan = fsMod.readFileSync(legacyPlanPath, 'utf8');
|
||||
assert.match(legacyPlan, /ARCHIVED/);
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user