mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): dual-mount topbar capsule, live multi-session HUD, and customizable topbar metrics (v1.4.3)
This commit is contained in:
+19
-14
@@ -51,6 +51,22 @@ export const App = defineComponent({
|
||||
stageEl,
|
||||
]);
|
||||
|
||||
function syncStepsBadge() {
|
||||
const uiSt = uiStore.getState();
|
||||
const scopeForBadge = uiSt.activeView === 'steps' ? uiSt.selectedAgentScope : 'all';
|
||||
const { scopedConv } = resolveScopedConversation(
|
||||
telemetryStore.getState().telemetry,
|
||||
scopeForBadge,
|
||||
uiSt.ctxInspectorAgentId
|
||||
);
|
||||
const stepCount = scopedConv?.stepCount ?? 0;
|
||||
topPillNav.setProps({
|
||||
items: VIEW_TABS.map((t) =>
|
||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
(activeView) => {
|
||||
@@ -65,24 +81,13 @@ export const App = defineComponent({
|
||||
} else if (activeView === 'steps') {
|
||||
stepsView.refs?.stepsScroll?.refresh();
|
||||
stepsView.refs?.modelsScroll?.refresh();
|
||||
} else if (activeView === 'settings') {
|
||||
settingsView.refs?.viewScrollbar?.refresh();
|
||||
}
|
||||
syncStepsBadge();
|
||||
}
|
||||
);
|
||||
|
||||
function syncStepsBadge() {
|
||||
const { scopedConv } = resolveScopedConversation(
|
||||
telemetryStore.getState().telemetry,
|
||||
uiStore.getState().selectedAgentScope,
|
||||
uiStore.getState().ctxInspectorAgentId
|
||||
);
|
||||
const stepCount = scopedConv?.stepCount ?? 0;
|
||||
topPillNav.setProps({
|
||||
items: VIEW_TABS.map((t) =>
|
||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const unsubStepCount = telemetryStore.subscribe(
|
||||
(st) => ({
|
||||
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
|
||||
|
||||
@@ -10,17 +10,22 @@ import { h, patchAttr, patchClasses, patchStyleVar, patchText } from '../../core
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
|
||||
let chartUidCounter = 0;
|
||||
|
||||
function safeSlotTokens(v) {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将二维采样点序列转换为水平张力平滑的三次贝塞尔曲线 SVG 路径 (`M ... C ...`)。
|
||||
* 控制点沿 X 轴取相邻点间距的 `0.42` 张力系数,Y 轴与各自端点齐平,
|
||||
* 保证曲线在极值点处平缓过渡且不会产生上下过冲 (Overshoot)。
|
||||
*
|
||||
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组
|
||||
* @param {Array<{ x: number, y: number }>} points SVG 坐标系下的采样点数组(长度 >= 2)
|
||||
* @returns {string} SVG `<path>` 的 `d` 属性字符串
|
||||
*/
|
||||
function buildSmoothSplinePath(points) {
|
||||
if (!points.length) return '';
|
||||
if (points.length === 1) return `M ${points[0].x} ${points[0].y}`;
|
||||
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`;
|
||||
for (let i = 0; i < points.length - 1; i++) {
|
||||
const p0 = points[i];
|
||||
@@ -77,10 +82,11 @@ export function createTrendAreaChart() {
|
||||
svg.setAttribute('class', 'trend-svg');
|
||||
svg.setAttribute('aria-hidden', 'true');
|
||||
|
||||
// 垂直线性渐变
|
||||
// 垂直线性渐变(每实例独立 ID,避免多图表挂载时 SVG url(#...) 冲突)
|
||||
const gradId = `trend-area-grad-${++chartUidCounter}`;
|
||||
const defs = document.createElementNS(SVG_NS, 'defs');
|
||||
const grad = document.createElementNS(SVG_NS, 'linearGradient');
|
||||
grad.setAttribute('id', 'trend-area-grad');
|
||||
grad.setAttribute('id', gradId);
|
||||
grad.setAttribute('x1', '0');
|
||||
grad.setAttribute('y1', '0');
|
||||
grad.setAttribute('x2', '0');
|
||||
@@ -119,7 +125,7 @@ export function createTrendAreaChart() {
|
||||
svg.appendChild(vGridGroup);
|
||||
|
||||
const areaPath = document.createElementNS(SVG_NS, 'path');
|
||||
areaPath.setAttribute('fill', 'url(#trend-area-grad)');
|
||||
areaPath.setAttribute('fill', `url(#${gradId})`);
|
||||
svg.appendChild(areaPath);
|
||||
|
||||
const linePath = document.createElementNS(SVG_NS, 'path');
|
||||
@@ -202,18 +208,20 @@ export function createTrendAreaChart() {
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
patchText(tipCallsEl, `${Number(slot.calls || 0)} 次`);
|
||||
patchText(tipTokensEl, `${formatTokensPrecise(Number(slot.tokens || 0))} tok`);
|
||||
patchText(tipCallsEl, `${Math.max(0, Math.floor(Number(slot.calls) || 0))} 次`);
|
||||
const slotTok = safeSlotTokens(slot.tokens);
|
||||
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
|
||||
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
|
||||
patchText(
|
||||
tipCostEl,
|
||||
formatUsd(Number(slot.costUsd || 0), {
|
||||
formatUsd(slotCost, {
|
||||
unpricedCalls: slot.unpricedCalls,
|
||||
precise: Number(slot.costUsd || 0) > 0 && Number(slot.costUsd || 0) < 0.1,
|
||||
precise: slotCost > 0 && slotCost < 0.1,
|
||||
})
|
||||
);
|
||||
|
||||
const hasSubBreakdown =
|
||||
Number(slot.tokens || 0) > 0 &&
|
||||
slotTok > 0 &&
|
||||
(slot.inputTokens !== undefined ||
|
||||
slot.cacheReadTokens !== undefined ||
|
||||
slot.outputTokens !== undefined);
|
||||
@@ -221,7 +229,7 @@ export function createTrendAreaChart() {
|
||||
if (hasSubBreakdown) {
|
||||
patchText(
|
||||
tipSubEl,
|
||||
`入 ${formatTokensPrecise(slot.inputTokens || 0)} · 缓 ${formatTokensPrecise(slot.cacheReadTokens || 0)} · 出 ${formatTokensPrecise(slot.outputTokens || 0)}`
|
||||
`入 ${formatTokensPrecise(safeSlotTokens(slot.inputTokens))} · 缓 ${formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens))} · 出 ${formatTokensPrecise(safeSlotTokens(slot.outputTokens))}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -268,7 +276,7 @@ export function createTrendAreaChart() {
|
||||
*/
|
||||
function update(series = []) {
|
||||
const slots =
|
||||
Array.isArray(series) && series.length >= 2
|
||||
Array.isArray(series) && series.length >= 1
|
||||
? series
|
||||
: [
|
||||
{ label: '00:00', fullLabel: '00:00 - 01:00', tokens: 0, calls: 0, costUsd: 0 },
|
||||
@@ -281,7 +289,7 @@ export function createTrendAreaChart() {
|
||||
let maxTokens = 0;
|
||||
let peakIdx = 0;
|
||||
for (let i = 0; i < slots.length; i++) {
|
||||
const t = Number(slots[i].tokens || 0);
|
||||
const t = safeSlotTokens(slots[i]?.tokens);
|
||||
if (t >= maxTokens) {
|
||||
maxTokens = t;
|
||||
peakIdx = i;
|
||||
@@ -289,22 +297,32 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
|
||||
const denom = Math.max(1, maxTokens);
|
||||
const isSingle = slots.length === 1;
|
||||
const pts = slots.map((s, idx) => {
|
||||
const x = LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
||||
const ratio = maxTokens > 0 ? Number(s.tokens || 0) / denom : 0;
|
||||
const tok = safeSlotTokens(s?.tokens);
|
||||
const x = isSingle ? (LEFT_X + RIGHT_X) / 2 : LEFT_X + (idx / Math.max(1, slots.length - 1)) * SPAN_X;
|
||||
const ratio = maxTokens > 0 ? tok / denom : 0;
|
||||
const y = BOTTOM_Y - ratio * SPAN_Y;
|
||||
return { x, y, tokens: Number(s.tokens || 0) };
|
||||
return { x, y, tokens: tok };
|
||||
});
|
||||
currentPts = pts;
|
||||
|
||||
const sig = slots
|
||||
.map((s) => `${s.label}:${s.fullLabel || ''}:${s.tokens}:${s.costUsd}:${s.calls}`)
|
||||
.map((s) => `${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}`)
|
||||
.join('|');
|
||||
|
||||
if (sig !== lastRenderSig) {
|
||||
lastRenderSig = sig;
|
||||
const lineD = buildSmoothSplinePath(pts);
|
||||
const areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
let lineD;
|
||||
let areaD;
|
||||
if (isSingle) {
|
||||
const yStr = pts[0].y.toFixed(1);
|
||||
lineD = `M ${LEFT_X.toFixed(1)} ${yStr} L ${RIGHT_X.toFixed(1)} ${yStr}`;
|
||||
areaD = `${lineD} L ${RIGHT_X.toFixed(1)} ${BOTTOM_Y} L ${LEFT_X.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
} else {
|
||||
lineD = buildSmoothSplinePath(pts);
|
||||
areaD = `${lineD} L ${pts[pts.length - 1].x.toFixed(1)} ${BOTTOM_Y} L ${pts[0].x.toFixed(1)} ${BOTTOM_Y} Z`;
|
||||
}
|
||||
patchAttr(linePath, 'd', lineD);
|
||||
patchAttr(areaPath, 'd', areaD);
|
||||
|
||||
@@ -329,8 +347,8 @@ export function createTrendAreaChart() {
|
||||
vGridGroup.appendChild(vLine);
|
||||
}
|
||||
|
||||
const isFirst = i === 0;
|
||||
const isLast = i === tickIndices.length - 1;
|
||||
const isFirst = !isSingle && i === 0;
|
||||
const isLast = !isSingle && i === tickIndices.length - 1;
|
||||
const pct = (pt.x / VIEW_W) * 100;
|
||||
const tickEl = h('span', {
|
||||
className: `trend-x-tick text-mono${isFirst ? ' is-start' : isLast ? ' is-end' : ''}`,
|
||||
@@ -371,7 +389,9 @@ export function createTrendAreaChart() {
|
||||
const pctLeft = Math.max(12, Math.min(88, (peakPt.x / VIEW_W) * 100));
|
||||
patchStyleVar(peakPill, '--peak-x', `${pctLeft.toFixed(1)}%`);
|
||||
|
||||
if (hoveredIdx >= 0 && hoveredIdx < slots.length) {
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showHoverAtIndex(hoveredIdx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,22 +113,64 @@ export const TopSessionHeader = defineComponent({
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const convs = telemetry?.conversations || [];
|
||||
const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话';
|
||||
const hostRouteId = telSt.hostRouteConversationId || '';
|
||||
const hostMatchedConv = hostRouteId
|
||||
? convs.find((c) => c.cascadeId === hostRouteId) ||
|
||||
(actConv?.cascadeId === hostRouteId ? actConv : null)
|
||||
: null;
|
||||
const defaultOptLabel = hostRouteId
|
||||
? hostMatchedConv?.title
|
||||
? `当前窗口 (${hostMatchedConv.title})`
|
||||
: `当前窗口 (${hostRouteId.slice(0, 8)})`
|
||||
: convs[0]?.title
|
||||
? `最新 (${convs[0].title})`
|
||||
: '跟随最新会话';
|
||||
const defaultOptMeta = hostRouteId
|
||||
? hostMatchedConv
|
||||
? formatConvOptionMeta({
|
||||
stepCount: hostMatchedConv.stepCount,
|
||||
subagentCount: hostMatchedConv.subagentCount,
|
||||
totalStepCount: hostMatchedConv.totalStepCount ?? hostMatchedConv.totalStepsAllAgents,
|
||||
})
|
||||
: ''
|
||||
: convs[0]
|
||||
? formatConvOptionMeta(convs[0])
|
||||
: '';
|
||||
const options = [
|
||||
{ value: '', label: latestTitle, meta: convs[0] ? formatConvOptionMeta(convs[0]) : '' },
|
||||
{ value: '', label: defaultOptLabel, meta: defaultOptMeta },
|
||||
...convs.map((c) => ({
|
||||
value: c.cascadeId,
|
||||
label: c.title || c.cascadeId.slice(0, 8),
|
||||
meta: formatConvOptionMeta(c),
|
||||
})),
|
||||
];
|
||||
const lockedId = telSt.selectedConversationId;
|
||||
if (lockedId && !convs.some((c) => c.cascadeId === lockedId)) {
|
||||
const isLoadedLocked = actConv?.cascadeId === lockedId;
|
||||
const lockedTitle =
|
||||
isLoadedLocked && actConv?.title
|
||||
? actConv.title
|
||||
: `已锁定会话 (${String(lockedId).slice(0, 8)})`;
|
||||
const lockedMeta = isLoadedLocked
|
||||
? formatConvOptionMeta({
|
||||
stepCount: actConv.stepCount,
|
||||
subagentCount: actConv.subagentCount,
|
||||
totalStepCount: actConv.totalStepsAllAgents,
|
||||
})
|
||||
: '已锁定';
|
||||
options.splice(1, 0, {
|
||||
value: lockedId,
|
||||
label: lockedTitle,
|
||||
meta: lockedMeta,
|
||||
});
|
||||
}
|
||||
convSelect.setProps({
|
||||
modelValue: telSt.selectedConversationId,
|
||||
options,
|
||||
});
|
||||
|
||||
const actConv = telemetry?.activeConversation;
|
||||
const hasSubagents = Boolean(actConv?.hasSubagents || (actConv?.subagentCount || 0) > 0);
|
||||
const aggregated = actConv?.aggregated;
|
||||
|
||||
@@ -211,6 +253,7 @@ export const TopSessionHeader = defineComponent({
|
||||
const unsubTelemetry = telemetryStore.subscribe(
|
||||
(st) => ({
|
||||
selectedConversationId: st.selectedConversationId,
|
||||
hostRouteConversationId: st.hostRouteConversationId,
|
||||
syncState: st.syncState,
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,14 @@
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js';
|
||||
import {
|
||||
h,
|
||||
isEventInside,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatCompactDateTime } from '../../core/formatters.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
|
||||
@@ -118,9 +125,9 @@ export const CustomDateTimePicker = defineComponent({
|
||||
function adjustTime(part, delta) {
|
||||
const cur = new Date(getProps().modelValue || Date.now());
|
||||
if (part === 'hour') {
|
||||
cur.setHours((cur.getHours() + delta + 24) % 24);
|
||||
cur.setHours(cur.getHours() + delta);
|
||||
} else {
|
||||
cur.setMinutes((cur.getMinutes() + delta + 60) % 60);
|
||||
cur.setMinutes(cur.getMinutes() + delta);
|
||||
}
|
||||
const nextMs = cur.getTime();
|
||||
viewYear = cur.getFullYear();
|
||||
@@ -251,7 +258,7 @@ export const CustomDateTimePicker = defineComponent({
|
||||
}
|
||||
|
||||
const handleDocClick = (e) => {
|
||||
if (isOpen && !rootEl.contains(e.target)) {
|
||||
if (isOpen && !isEventInside(e, rootEl)) {
|
||||
togglePopover(false);
|
||||
}
|
||||
};
|
||||
@@ -267,16 +274,6 @@ export const CustomDateTimePicker = defineComponent({
|
||||
el: rootEl,
|
||||
refs: { triggerBtn, triggerText, popoverEl, daysGrid, hourValSpan, minValSpan },
|
||||
onPropsChange: syncDisplay,
|
||||
getValue: () => Number(getProps().modelValue || 0),
|
||||
methods: {
|
||||
open: () => togglePopover(true),
|
||||
close: () => togglePopover(false),
|
||||
selectDayByOffset: (daysDelta) => {
|
||||
const cur = new Date(getProps().modelValue || Date.now());
|
||||
cur.setDate(cur.getDate() + daysDelta);
|
||||
emit('update:modelValue', cur.getTime());
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
|
||||
export const CustomNumberInput = defineComponent({
|
||||
name: 'CustomNumberInput',
|
||||
setup({ getProps, emit }) {
|
||||
setup({ getProps, setProps, emit }) {
|
||||
function clampValue(raw) {
|
||||
const { min = -Infinity, max = Infinity, precision = 0 } = getProps();
|
||||
const num = Number(raw);
|
||||
@@ -27,6 +27,7 @@ export const CustomNumberInput = defineComponent({
|
||||
const next = clampValue(current + direction * step * multiplier);
|
||||
syncFieldDisplay(next);
|
||||
if (next !== current) {
|
||||
setProps({ modelValue: next });
|
||||
emit('update:modelValue', next);
|
||||
}
|
||||
}
|
||||
@@ -80,11 +81,22 @@ export const CustomNumberInput = defineComponent({
|
||||
});
|
||||
|
||||
function commitManualInput() {
|
||||
const rawText = String(textField.value || '').replace(/[^0-9.-]/g, '');
|
||||
const next = clampValue(rawText);
|
||||
const raw = String(textField.value ?? '').trim();
|
||||
if (!raw || !/\d/.test(raw)) {
|
||||
syncFieldDisplay(getProps().modelValue);
|
||||
return;
|
||||
}
|
||||
const cleaned = raw.replace(/[^0-9.-]/g, '');
|
||||
const parsed = Number(cleaned);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
syncFieldDisplay(getProps().modelValue);
|
||||
return;
|
||||
}
|
||||
const next = clampValue(parsed);
|
||||
const prev = Number(getProps().modelValue);
|
||||
syncFieldDisplay(next);
|
||||
if (next !== prev) {
|
||||
setProps({ modelValue: next });
|
||||
emit('update:modelValue', next);
|
||||
}
|
||||
}
|
||||
@@ -107,10 +119,8 @@ export const CustomNumberInput = defineComponent({
|
||||
el: rootEl,
|
||||
refs: { decBtn, incBtn, textField },
|
||||
onPropsChange: () => syncFieldDisplay(),
|
||||
getValue: () => clampValue(textField.value),
|
||||
methods: {
|
||||
stepUp: (mult = 1) => applyStep(1, mult),
|
||||
stepDown: (mult = 1) => applyStep(-1, mult),
|
||||
commit: () => commitManualInput(),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* @fileoverview Bespoke custom scrollbar component (零原生滚动条).
|
||||
* Hides native OS scrollbars completely and renders a precision 4px floating
|
||||
* rail + GPU-translated thumb with drag, track-jump, and modelValue ratio emit.
|
||||
* rail + GPU-translated thumb with drag and track-jump support.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
@@ -9,7 +9,7 @@ import { h, patchClasses, patchStyleVar } from '../../core/domPatch.js';
|
||||
|
||||
export const CustomScrollbar = defineComponent({
|
||||
name: 'CustomScrollbar',
|
||||
setup({ getProps, emit, onCleanup }) {
|
||||
setup({ getProps, onCleanup }) {
|
||||
const contentEl = getProps().contentEl || h('div');
|
||||
contentEl.classList.add('custom-scroll-content');
|
||||
|
||||
@@ -61,11 +61,6 @@ export const CustomScrollbar = defineComponent({
|
||||
|
||||
function onContentScroll() {
|
||||
syncThumb();
|
||||
const overflow = (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0);
|
||||
if (overflow > 1) {
|
||||
const ratio = +Math.max(0, Math.min(1, (contentEl.scrollTop || 0) / overflow)).toFixed(3);
|
||||
emit('update:modelValue', ratio);
|
||||
}
|
||||
}
|
||||
|
||||
function onDocMouseMove(e) {
|
||||
@@ -163,12 +158,6 @@ export const CustomScrollbar = defineComponent({
|
||||
refresh() {
|
||||
scheduleSyncThumb();
|
||||
},
|
||||
scrollToRatio(ratio) {
|
||||
const r = Math.max(0, Math.min(1, Number(ratio || 0)));
|
||||
const overflow = Math.max(0, (contentEl.scrollHeight || 0) - (contentEl.clientHeight || 0));
|
||||
contentEl.scrollTop = Math.round(r * overflow);
|
||||
syncThumb();
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -4,12 +4,19 @@
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../core/domPatch.js';
|
||||
import {
|
||||
h,
|
||||
isEventInside,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
|
||||
export const CustomSelect = defineComponent({
|
||||
name: 'CustomSelect',
|
||||
setup({ getProps, emit, onCleanup }) {
|
||||
setup({ getProps, setProps, emit, onCleanup }) {
|
||||
let isOpen = false;
|
||||
let focusedIndex = -1;
|
||||
|
||||
@@ -67,6 +74,7 @@ export const CustomSelect = defineComponent({
|
||||
const prevVal = getProps().modelValue;
|
||||
toggleOpen(false);
|
||||
if (option.value !== prevVal) {
|
||||
setProps({ modelValue: option.value });
|
||||
emit('update:modelValue', option.value);
|
||||
}
|
||||
}
|
||||
@@ -82,6 +90,7 @@ export const CustomSelect = defineComponent({
|
||||
} else {
|
||||
focusedIndex = (focusedIndex + 1) % opts.length;
|
||||
renderMenuOptions();
|
||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
@@ -90,6 +99,7 @@ export const CustomSelect = defineComponent({
|
||||
} else {
|
||||
focusedIndex = (focusedIndex - 1 + opts.length) % opts.length;
|
||||
renderMenuOptions();
|
||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
} else if (e.key === 'Enter' && isOpen) {
|
||||
e.preventDefault();
|
||||
@@ -150,17 +160,17 @@ export const CustomSelect = defineComponent({
|
||||
if (icon) {
|
||||
patchSvgIcon(leadIcon, icon);
|
||||
}
|
||||
const selectedOpt =
|
||||
options.find((o) => o.value === modelValue) ||
|
||||
(!modelValue ? options[0] : undefined);
|
||||
patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder);
|
||||
const matchedOpt = options.find((o) => o.value === modelValue);
|
||||
const selectedOpt = matchedOpt || (!modelValue ? options[0] : undefined);
|
||||
const fallbackText = modelValue ? `${placeholder} (${String(modelValue).slice(0, 8)})` : placeholder;
|
||||
patchText(triggerLabel, selectedOpt ? selectedOpt.label : fallbackText);
|
||||
if (isOpen) {
|
||||
renderMenuOptions();
|
||||
}
|
||||
}
|
||||
|
||||
const handleDocClick = (e) => {
|
||||
if (isOpen && !rootEl.contains(e.target)) {
|
||||
if (isOpen && !isEventInside(e, rootEl)) {
|
||||
toggleOpen(false);
|
||||
}
|
||||
};
|
||||
@@ -176,14 +186,8 @@ export const CustomSelect = defineComponent({
|
||||
el: rootEl,
|
||||
refs: { triggerBtn, triggerLabel, menuEl },
|
||||
onPropsChange: syncTriggerAndMenu,
|
||||
getValue: () => getProps().modelValue,
|
||||
methods: {
|
||||
open: () => toggleOpen(true),
|
||||
close: () => toggleOpen(false),
|
||||
selectByValue: (val) => {
|
||||
const found = (getProps().options || []).find((o) => o.value === val);
|
||||
if (found) chooseOption(found);
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -8,7 +8,7 @@ import { h, patchAttr, patchClasses, patchKeyedList, patchText } from '../../cor
|
||||
|
||||
export const SegmentedControl = defineComponent({
|
||||
name: 'SegmentedControl',
|
||||
setup({ getProps, emit }) {
|
||||
setup({ getProps, setProps, emit }) {
|
||||
const rootEl = h('div', {
|
||||
className: 'segmented',
|
||||
role: 'group',
|
||||
@@ -27,6 +27,7 @@ export const SegmentedControl = defineComponent({
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
if (getProps().modelValue !== opt.value) {
|
||||
setProps({ modelValue: opt.value });
|
||||
emit('update:modelValue', opt.value);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -8,15 +8,6 @@ export function defineComponent({ name, setup }) {
|
||||
return function createInstance(initialProps = {}) {
|
||||
let props = { ...initialProps };
|
||||
const cleanups = [];
|
||||
const eventHandlers = new Map();
|
||||
|
||||
function on(event, fn) {
|
||||
if (!eventHandlers.has(event)) {
|
||||
eventHandlers.set(event, new Set());
|
||||
}
|
||||
eventHandlers.get(event).add(fn);
|
||||
return () => eventHandlers.get(event)?.delete(fn);
|
||||
}
|
||||
|
||||
function emit(event, payload) {
|
||||
// Support Vue-style onUpdateModelValue / onChange prop callbacks
|
||||
@@ -28,12 +19,6 @@ export function defineComponent({ name, setup }) {
|
||||
props.onChange(payload);
|
||||
}
|
||||
}
|
||||
const handlers = eventHandlers.get(event);
|
||||
if (handlers) {
|
||||
for (const fn of handlers) {
|
||||
fn(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function onCleanup(fn) {
|
||||
@@ -42,15 +27,11 @@ export function defineComponent({ name, setup }) {
|
||||
}
|
||||
}
|
||||
|
||||
const setupResult = setup({
|
||||
getProps: () => props,
|
||||
emit,
|
||||
onCleanup,
|
||||
});
|
||||
let setupResult = null;
|
||||
|
||||
function setProps(nextProps = {}) {
|
||||
props = { ...props, ...nextProps };
|
||||
if (typeof setupResult.onPropsChange === 'function') {
|
||||
if (setupResult && typeof setupResult.onPropsChange === 'function') {
|
||||
setupResult.onPropsChange(props);
|
||||
}
|
||||
}
|
||||
@@ -59,11 +40,12 @@ export function defineComponent({ name, setup }) {
|
||||
setProps({ modelValue: nextValue });
|
||||
}
|
||||
|
||||
function getValue() {
|
||||
return typeof setupResult.getValue === 'function'
|
||||
? setupResult.getValue()
|
||||
: props.modelValue;
|
||||
}
|
||||
setupResult = setup({
|
||||
getProps: () => props,
|
||||
setProps,
|
||||
emit,
|
||||
onCleanup,
|
||||
});
|
||||
|
||||
function destroy() {
|
||||
for (const fn of cleanups.splice(0)) {
|
||||
@@ -73,7 +55,6 @@ export function defineComponent({ name, setup }) {
|
||||
console.error(`[${name}] cleanup error:`, err);
|
||||
}
|
||||
}
|
||||
eventHandlers.clear();
|
||||
if (setupResult.el?.parentNode) {
|
||||
setupResult.el.parentNode.removeChild(setupResult.el);
|
||||
}
|
||||
@@ -83,11 +64,8 @@ export function defineComponent({ name, setup }) {
|
||||
name,
|
||||
el: setupResult.el,
|
||||
refs: setupResult.refs || {},
|
||||
on,
|
||||
emit,
|
||||
setProps,
|
||||
setValue,
|
||||
getValue,
|
||||
destroy,
|
||||
...setupResult.methods,
|
||||
};
|
||||
|
||||
@@ -53,18 +53,28 @@ export function patchText(el, nextValue) {
|
||||
export function patchAttr(el, attrName, nextValue) {
|
||||
if (!el) return false;
|
||||
if (nextValue === null || nextValue === undefined || nextValue === false) {
|
||||
if (!el.hasAttribute(attrName)) {
|
||||
return false;
|
||||
let mutated = false;
|
||||
if (el.hasAttribute(attrName)) {
|
||||
el.removeAttribute(attrName);
|
||||
mutated = true;
|
||||
}
|
||||
el.removeAttribute(attrName);
|
||||
return true;
|
||||
if (attrName === 'value' && 'value' in el && el.value !== '') {
|
||||
el.value = '';
|
||||
mutated = true;
|
||||
}
|
||||
return mutated;
|
||||
}
|
||||
const strVal = nextValue === true ? '' : String(nextValue);
|
||||
if (el.getAttribute(attrName) === strVal) {
|
||||
return false;
|
||||
let mutated = false;
|
||||
if (el.getAttribute(attrName) !== strVal) {
|
||||
el.setAttribute(attrName, strVal);
|
||||
mutated = true;
|
||||
}
|
||||
el.setAttribute(attrName, strVal);
|
||||
return true;
|
||||
if (attrName === 'value' && 'value' in el && el.value !== strVal) {
|
||||
el.value = strVal;
|
||||
mutated = true;
|
||||
}
|
||||
return mutated;
|
||||
}
|
||||
|
||||
export function patchClasses(el, classMap) {
|
||||
@@ -72,11 +82,14 @@ export function patchClasses(el, classMap) {
|
||||
let mutated = false;
|
||||
for (const [cls, active] of Object.entries(classMap)) {
|
||||
if (!cls) continue;
|
||||
const has = el.classList.contains(cls);
|
||||
const shouldHave = Boolean(active);
|
||||
if (has !== shouldHave) {
|
||||
el.classList.toggle(cls, shouldHave);
|
||||
mutated = true;
|
||||
const tokens = String(cls).split(/\s+/).filter(Boolean);
|
||||
for (const tok of tokens) {
|
||||
const has = el.classList.contains(tok);
|
||||
if (has !== shouldHave) {
|
||||
el.classList.toggle(tok, shouldHave);
|
||||
mutated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return mutated;
|
||||
@@ -93,6 +106,25 @@ export function patchStyleVar(el, varName, nextValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断事件是否发生在目标节点内部(兼容 Shadow DOM 的 `composedPath()` 穿透)。
|
||||
*
|
||||
* @param {Event|null|undefined} event
|
||||
* @param {Node|null|undefined} element
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isEventInside(event, element) {
|
||||
if (!event || !element) return false;
|
||||
if (typeof event.composedPath === 'function') {
|
||||
const path = event.composedPath();
|
||||
if (Array.isArray(path) && path.includes(element)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
const target = event.target;
|
||||
return Boolean(target && typeof element.contains === 'function' && element.contains(target));
|
||||
}
|
||||
|
||||
const keyedListState = new WeakMap();
|
||||
|
||||
/**
|
||||
@@ -108,11 +140,15 @@ export function patchKeyedList(container, items, { keyFn, sigFn, createRow, upda
|
||||
}
|
||||
|
||||
const nextKeys = new Set();
|
||||
const seenInPass = new Map();
|
||||
const orderedNodes = [];
|
||||
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const key = String(keyFn(item, i));
|
||||
const rawKey = String(keyFn(item, i));
|
||||
const dupIdx = seenInPass.get(rawKey) || 0;
|
||||
seenInPass.set(rawKey, dupIdx + 1);
|
||||
const key = dupIdx === 0 ? rawKey : `${rawKey}__dup_${dupIdx}`;
|
||||
const sig = sigFn ? String(sigFn(item, i)) : JSON.stringify(item);
|
||||
nextKeys.add(key);
|
||||
|
||||
|
||||
@@ -37,15 +37,15 @@ export function formatDateSpanBadge(startMs, endMs) {
|
||||
return `${s.getMonth() + 1}月${s.getDate()}日 ~ ${e.getMonth() + 1}月${e.getDate()}日`;
|
||||
}
|
||||
|
||||
export function formatUsd(amount, { precise = false, estimated = false, unpricedCalls = 0 } = {}) {
|
||||
export function formatUsd(amount, { precise = false, unpricedCalls = 0, compactPending = false } = {}) {
|
||||
if (amount == null || !Number.isFinite(Number(amount))) return '待定';
|
||||
const val = Number(amount || 0);
|
||||
const prefix = estimated ? '≈$' : '$';
|
||||
const suffix = unpricedCalls > 0 ? ' + 待定' : '';
|
||||
const suffix = unpricedCalls > 0 ? (compactPending ? '+' : ' + 待定') : '';
|
||||
if (precise) {
|
||||
return (val >= 1 ? `${prefix}${val.toFixed(2)}` : `${prefix}${val.toFixed(3)}`) + suffix;
|
||||
if (val > 0 && val < 0.001) return `<$0.001${suffix}`;
|
||||
return (val >= 1 ? `$${val.toFixed(2)}` : `$${val.toFixed(3)}`) + suffix;
|
||||
}
|
||||
return `${prefix}${val.toFixed(2)}${suffix}`;
|
||||
return `$${val.toFixed(2)}${suffix}`;
|
||||
}
|
||||
|
||||
export function speedReasonText(reason) {
|
||||
@@ -53,6 +53,7 @@ export function speedReasonText(reason) {
|
||||
incomplete_or_invalid_timing: '生成未完成',
|
||||
invalid_output_tokens: '无有效输出',
|
||||
inconsistent_timing: '耗时数据异常',
|
||||
short_timing: '耗时过短 (<0.5s)',
|
||||
legacy_cache: '旧版缓存记录',
|
||||
})[reason] || '';
|
||||
}
|
||||
@@ -66,9 +67,10 @@ export function sampleSummary(summary) {
|
||||
export function formatCountdown(isoTime, nowMs = Date.now()) {
|
||||
if (!isoTime) return '未知重置时间';
|
||||
const targetMs = Date.parse(isoTime);
|
||||
if (!targetMs || Number.isNaN(targetMs)) return '未知重置时间';
|
||||
if (!Number.isFinite(targetMs) || targetMs <= 0) return '未知重置时间';
|
||||
const diffMs = targetMs - nowMs;
|
||||
if (diffMs <= 0) return '即将重置';
|
||||
if (diffMs < 60_000) return '<1分钟后重置';
|
||||
|
||||
const totalMinutes = Math.floor(diffMs / 60000);
|
||||
const days = Math.floor(totalMinutes / (60 * 24));
|
||||
|
||||
@@ -1,11 +1,123 @@
|
||||
/**
|
||||
* @fileoverview Async HTTP client with AbortController cancellation for stale
|
||||
* polling requests and concurrent GET deduplication.
|
||||
* polling requests, concurrent GET deduplication, and dual-mode transport
|
||||
* (Sidecar Webview `window.sidecar.fetch` + Main Window Loopback Bridge).
|
||||
*/
|
||||
|
||||
const inFlightGets = new Map();
|
||||
const activeControllers = new Map();
|
||||
|
||||
/**
|
||||
* 读取主窗口双栖模式下注入的本地桥接配置(`port`、`token`、`bundleVersion`、`stylesCss`)。
|
||||
*
|
||||
* @returns {{ port: number, token: string, bundleVersion?: string, stylesCss?: string } | null}
|
||||
*/
|
||||
export function getWindowBridgeConfig() {
|
||||
if (typeof window === 'undefined') return null;
|
||||
const br = window.__AGUsageMonitorBridge;
|
||||
const port = Number(br?.port || 0);
|
||||
if (br && Number.isInteger(port) && port > 0 && typeof br.token === 'string' && br.token) {
|
||||
return br;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前脚本是否以双栖悬浮模式运行在宿主主聊天窗口内(而非右侧辅助栏 Webview)。
|
||||
*
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isWindowOverlayMode() {
|
||||
if (typeof window === 'undefined') return false;
|
||||
if (window.sidecar?.fetch) return false;
|
||||
return Boolean(getWindowBridgeConfig());
|
||||
}
|
||||
|
||||
/**
|
||||
* 接收 Sidecar 通过 CDP `Runtime.evaluate` 批量投递的 RPC 响应,完成因 CSP/代理解除 HTTP 直连时的兜底请求。
|
||||
*
|
||||
* @param {Array<{ id: string, ok: boolean, status?: number, data?: any, error?: string }>} responses
|
||||
* @returns {number}
|
||||
*/
|
||||
export function deliverCdpBridgeResponses(responses) {
|
||||
const br = getWindowBridgeConfig();
|
||||
if (!br || !(br.rpcPending instanceof Map) || !Array.isArray(responses)) return 0;
|
||||
let delivered = 0;
|
||||
for (const item of responses) {
|
||||
const entry = br.rpcPending.get(item?.id);
|
||||
if (!entry) continue;
|
||||
br.rpcPending.delete(item.id);
|
||||
delivered += 1;
|
||||
if (item.ok) {
|
||||
entry.resolve(item.data);
|
||||
} else {
|
||||
entry.reject(new Error(item.error || `HTTP ${item.status || 500}`));
|
||||
}
|
||||
}
|
||||
return delivered;
|
||||
}
|
||||
|
||||
function callViaCdpBridge(bridge, path, { method, body, signal }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
reject(abortErr);
|
||||
return;
|
||||
}
|
||||
if (!Array.isArray(bridge.rpcQueue)) bridge.rpcQueue = [];
|
||||
if (!(bridge.rpcPending instanceof Map)) bridge.rpcPending = new Map();
|
||||
|
||||
const reqId = `rpc_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
|
||||
const cleanupQueueItem = () => {
|
||||
if (!Array.isArray(bridge.rpcQueue)) return;
|
||||
const idx = bridge.rpcQueue.findIndex((item) => item?.id === reqId);
|
||||
if (idx >= 0) bridge.rpcQueue.splice(idx, 1);
|
||||
};
|
||||
|
||||
const timeoutId = setTimeout(() => {
|
||||
bridge.rpcPending.delete(reqId);
|
||||
cleanupQueueItem();
|
||||
reject(new Error('CDP bridge timeout'));
|
||||
}, 8000);
|
||||
|
||||
const onAbort = () => {
|
||||
clearTimeout(timeoutId);
|
||||
bridge.rpcPending.delete(reqId);
|
||||
cleanupQueueItem();
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
reject(abortErr);
|
||||
};
|
||||
if (signal) {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
}
|
||||
|
||||
bridge.rpcPending.set(reqId, {
|
||||
resolve: (data) => {
|
||||
clearTimeout(timeoutId);
|
||||
if (signal) signal.removeEventListener('abort', onAbort);
|
||||
resolve(data);
|
||||
},
|
||||
reject: (err) => {
|
||||
clearTimeout(timeoutId);
|
||||
if (signal) signal.removeEventListener('abort', onAbort);
|
||||
reject(err);
|
||||
},
|
||||
});
|
||||
|
||||
if (bridge.rpcQueue.length >= 16) {
|
||||
const dropped = bridge.rpcQueue.shift();
|
||||
if (dropped?.id) {
|
||||
const stale = bridge.rpcPending.get(dropped.id);
|
||||
bridge.rpcPending.delete(dropped.id);
|
||||
stale?.reject(new Error('CDP queue superseded'));
|
||||
}
|
||||
}
|
||||
bridge.rpcQueue.push({ id: reqId, path, method, body });
|
||||
});
|
||||
}
|
||||
|
||||
export async function callSidecarApi(path, { method = 'GET', body, abortKey = '' } = {}) {
|
||||
const upperMethod = method.toUpperCase();
|
||||
const dedupKey = upperMethod === 'GET' && !abortKey ? path : '';
|
||||
@@ -28,16 +140,41 @@ export async function callSidecarApi(path, { method = 'GET', body, abortKey = ''
|
||||
|
||||
const runRequest = async () => {
|
||||
const sidecar = typeof window !== 'undefined' ? window.sidecar : null;
|
||||
const bridge = !sidecar?.fetch ? getWindowBridgeConfig() : null;
|
||||
const fetchFn = sidecar?.fetch
|
||||
? sidecar.fetch.bind(sidecar)
|
||||
: globalThis.fetch.bind(globalThis);
|
||||
: typeof window !== 'undefined' && typeof window.fetch === 'function'
|
||||
? window.fetch.bind(window)
|
||||
: globalThis.fetch.bind(globalThis);
|
||||
|
||||
const res = await fetchFn(path, {
|
||||
method: upperMethod,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
const requestUrl = bridge ? `http://127.0.0.1:${bridge.port}${path}` : path;
|
||||
const headers = {};
|
||||
if (body !== undefined || !bridge) {
|
||||
headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
if (bridge) {
|
||||
headers['X-Usage-Monitor-Token'] = bridge.token;
|
||||
if (bridge.transportMode === 'cdp') {
|
||||
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
|
||||
}
|
||||
}
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await fetchFn(requestUrl, {
|
||||
method: upperMethod,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
} catch (fetchErr) {
|
||||
if (!bridge || signal?.aborted || fetchErr?.name === 'AbortError') {
|
||||
throw fetchErr;
|
||||
}
|
||||
// 当宿主环境的 CSP connect-src、混合内容策略或本地代理阻断 HTTP 直连时,无缝切至 CDP 通道
|
||||
bridge.transportMode = 'cdp';
|
||||
return callViaCdpBridge(bridge, path, { method: upperMethod, body, signal });
|
||||
}
|
||||
if (signal?.aborted) {
|
||||
const abortErr = new Error('Request aborted');
|
||||
abortErr.name = 'AbortError';
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
const pendingJobs = new Set();
|
||||
let isFlushPending = false;
|
||||
|
||||
export function scheduleAsyncJob(job) {
|
||||
function scheduleAsyncJob(job) {
|
||||
pendingJobs.add(job);
|
||||
if (!isFlushPending) {
|
||||
isFlushPending = true;
|
||||
@@ -14,7 +14,7 @@ export function scheduleAsyncJob(job) {
|
||||
}
|
||||
}
|
||||
|
||||
export function flushAsyncJobs() {
|
||||
function flushAsyncJobs() {
|
||||
isFlushPending = false;
|
||||
const jobs = Array.from(pendingJobs);
|
||||
pendingJobs.clear();
|
||||
@@ -23,7 +23,7 @@ export function flushAsyncJobs() {
|
||||
}
|
||||
}
|
||||
|
||||
export function isShallowEqual(a, b) {
|
||||
function isShallowEqual(a, b) {
|
||||
if (Object.is(a, b)) return true;
|
||||
if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
|
||||
return false;
|
||||
@@ -55,6 +55,19 @@ export function createReactiveStore(initialState) {
|
||||
return state;
|
||||
}
|
||||
|
||||
function notifyAll() {
|
||||
for (const sub of Array.from(subscribers)) {
|
||||
if (!subscribers.has(sub)) continue;
|
||||
const nextSlice = sub.selector(state);
|
||||
const equal = sub.compare(sub.lastSlice, nextSlice);
|
||||
if (!equal) {
|
||||
const prevSlice = sub.lastSlice;
|
||||
sub.lastSlice = nextSlice;
|
||||
sub.listener(nextSlice, prevSlice);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setState(patchOrUpdater, { sync = false } = {}) {
|
||||
const patch = typeof patchOrUpdater === 'function' ? patchOrUpdater(state) : patchOrUpdater;
|
||||
if (!patch || typeof patch !== 'object') return;
|
||||
@@ -72,18 +85,6 @@ export function createReactiveStore(initialState) {
|
||||
}
|
||||
state = nextState;
|
||||
|
||||
const notifyAll = () => {
|
||||
for (const sub of subscribers) {
|
||||
const nextSlice = sub.selector(state);
|
||||
const equal = sub.compare(sub.lastSlice, nextSlice);
|
||||
if (!equal) {
|
||||
const prevSlice = sub.lastSlice;
|
||||
sub.lastSlice = nextSlice;
|
||||
sub.listener(nextSlice, prevSlice);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (sync) {
|
||||
notifyAll();
|
||||
} else {
|
||||
|
||||
@@ -73,9 +73,17 @@ export const SVG_ICON_DEFS = Object.freeze({
|
||||
{ tag: 'path', attrs: { d: 'M3.5 8h9' } },
|
||||
],
|
||||
dot: [
|
||||
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '3.2', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '5', fill: 'currentColor', stroke: 'none' } },
|
||||
],
|
||||
'arrow-down': [
|
||||
{ tag: 'path', attrs: { d: 'M8 2.8v10.4M4.2 9.4L8 13.2l3.8-3.8' } },
|
||||
],
|
||||
dock: [
|
||||
{ tag: 'rect', attrs: { x: '1.8', y: '2.5', width: '12.4', height: '11', rx: '1.5' } },
|
||||
{ tag: 'path', attrs: { d: 'M1.8 6h12.4' } },
|
||||
{ tag: 'path', attrs: { d: 'M9.2 4.25h3.2' } },
|
||||
],
|
||||
close: [
|
||||
{ tag: 'path', attrs: { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' } },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
/**
|
||||
* @fileoverview Async entry point for Antigravity Usage & Speed Monitor.
|
||||
* Automatically branches between Auxiliary Sidebar Webview mode (`#app-root`)
|
||||
* and Main Window Dual-Mount Overlay mode (`window.__AGUsageMonitorBridge`).
|
||||
*/
|
||||
|
||||
import { App } from './App.js';
|
||||
import { mountWindowOverlay } from './components/layout/WindowOverlayShell.js';
|
||||
import { isWindowOverlayMode } from './core/httpClient.js';
|
||||
import { startAsyncTelemetryLoop } from './store/telemetryStore.js';
|
||||
|
||||
export async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
||||
async function bootstrapApp(mountTarget = document.getElementById('app-root')) {
|
||||
if (!mountTarget) return null;
|
||||
const appInstance = App();
|
||||
mountTarget.appendChild(appInstance.el);
|
||||
@@ -16,14 +20,22 @@ export async function bootstrapApp(mountTarget = document.getElementById('app-ro
|
||||
};
|
||||
}
|
||||
|
||||
export function init() {
|
||||
function startEntry() {
|
||||
if (isWindowOverlayMode()) {
|
||||
mountWindowOverlay();
|
||||
return;
|
||||
}
|
||||
bootstrapApp();
|
||||
}
|
||||
|
||||
function init() {
|
||||
if (typeof document === 'undefined') return;
|
||||
if (document.readyState === 'loading' && typeof document.addEventListener === 'function') {
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
bootstrapApp();
|
||||
startEntry();
|
||||
});
|
||||
} else {
|
||||
bootstrapApp();
|
||||
startEntry();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,17 +4,31 @@
|
||||
*/
|
||||
|
||||
import { createReactiveStore } from '../core/reactive.js';
|
||||
import { callSidecarApi } from '../core/httpClient.js';
|
||||
import { callSidecarApi, isWindowOverlayMode } from '../core/httpClient.js';
|
||||
|
||||
/**
|
||||
* 在主窗口双栖模式下,从宿主页面路径 `/c/<uuid>` 提取当前正在浏览的会话 ID。
|
||||
*
|
||||
* @returns {string}
|
||||
*/
|
||||
export function extractHostRouteCascadeId() {
|
||||
if (typeof window === 'undefined' || !isWindowOverlayMode()) return '';
|
||||
const pathname = String(window.location?.pathname || '');
|
||||
const m = pathname.match(/^\/c\/([a-f0-9-]{36})(?:\/|$)/i);
|
||||
return m ? m[1] : '';
|
||||
}
|
||||
|
||||
const initialConversationId =
|
||||
(typeof window !== 'undefined' && window.sidecar?.conversationId) || '';
|
||||
|
||||
export const telemetryStore = createReactiveStore({
|
||||
selectedConversationId: initialConversationId,
|
||||
hostRouteConversationId: extractHostRouteCascadeId(),
|
||||
selectedTimeRange: 'today',
|
||||
customStartMs: Date.now() - 24 * 3600 * 1000,
|
||||
customEndMs: Date.now(),
|
||||
syncState: 'idle', // 'idle' | 'syncing' | 'synced' | 'error'
|
||||
minuteTick: 0,
|
||||
telemetry: null,
|
||||
});
|
||||
|
||||
@@ -22,12 +36,49 @@ let pollTimer = null;
|
||||
let feedbackTimer = null;
|
||||
let activeBundleVersion = 0;
|
||||
let latestRequestSeq = 0;
|
||||
let activeForceCount = 0;
|
||||
let loopActive = false;
|
||||
let loopIntervalMs = 2000;
|
||||
let loopTickFn = null;
|
||||
|
||||
export const CLIENT_TOPBAR_SLOT_KEYS = Object.freeze([
|
||||
'context',
|
||||
'tps',
|
||||
'ttft',
|
||||
'cost',
|
||||
'quota_auto',
|
||||
'gemini_5h',
|
||||
'gemini_weekly',
|
||||
'claude_5h',
|
||||
'claude_weekly',
|
||||
'none',
|
||||
]);
|
||||
|
||||
export const DEFAULT_CLIENT_TOPBAR_SLOTS = Object.freeze(['context', 'tps', 'quota_auto']);
|
||||
|
||||
/**
|
||||
* 归一化前端顶栏胶囊三槽位配置数组,非法项回退默认值,且禁止三项同时为 `none`。
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {[string, string, string]}
|
||||
*/
|
||||
export function normalizeClientTopbarSlots(raw) {
|
||||
const arr = Array.isArray(raw) ? raw : [];
|
||||
const slots = [0, 1, 2].map((idx) => {
|
||||
const val = String(arr[idx] ?? '').trim();
|
||||
return CLIENT_TOPBAR_SLOT_KEYS.includes(val) ? val : DEFAULT_CLIENT_TOPBAR_SLOTS[idx];
|
||||
});
|
||||
if (slots.every((s) => s === 'none')) {
|
||||
slots[0] = 'context';
|
||||
}
|
||||
return slots;
|
||||
}
|
||||
|
||||
function isEquivalentTelemetry(prev, next) {
|
||||
if (!prev || !next) return false;
|
||||
if (prev === next) return true;
|
||||
|
||||
// 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关)
|
||||
// 1. 比对系统设置项(模型显示策略、周预算模式与额度、插件自动更新开关、双栖与顶栏槽位配置)
|
||||
const pAct = prev.activeConversation;
|
||||
const nAct = next.activeConversation;
|
||||
if (prev.settings?.showUpstreamModel !== next.settings?.showUpstreamModel) return false;
|
||||
@@ -35,14 +86,28 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (prev.settings?.weeklyTokenBudget !== next.settings?.weeklyTokenBudget) return false;
|
||||
if (prev.settings?.weeklyCostBudget !== next.settings?.weeklyCostBudget) return false;
|
||||
if (prev.settings?.autoUpdatePlugin !== next.settings?.autoUpdatePlugin) return false;
|
||||
if (prev.settings?.enableWindowOverlay !== next.settings?.enableWindowOverlay) return false;
|
||||
if ((prev.settings?.showTopbarMultiSession !== false) !== (next.settings?.showTopbarMultiSession !== false)) {
|
||||
return false;
|
||||
}
|
||||
const pTopSlots = prev.settings?.topbarCapsuleSlots;
|
||||
const nTopSlots = next.settings?.topbarCapsuleSlots;
|
||||
if (
|
||||
(pTopSlots?.[0] ?? 'context') !== (nTopSlots?.[0] ?? 'context') ||
|
||||
(pTopSlots?.[1] ?? 'tps') !== (nTopSlots?.[1] ?? 'tps') ||
|
||||
(pTopSlots?.[2] ?? 'quota_auto') !== (nTopSlots?.[2] ?? 'quota_auto')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 2. 比对云端状态(插件当前/最新版本、价格表版本与模型数量、同步/更新执行状态及错误信息)
|
||||
// 2. 比对云端状态(插件当前/最新版本、安装模式、价格表版本与模型数量、同步/更新执行状态及错误信息)
|
||||
const pCloud = prev.cloudStatus;
|
||||
const nCloud = next.cloudStatus;
|
||||
if (
|
||||
pCloud?.currentPluginVersion !== nCloud?.currentPluginVersion ||
|
||||
pCloud?.latestPluginVersion !== nCloud?.latestPluginVersion ||
|
||||
pCloud?.updateAvailable !== nCloud?.updateAvailable ||
|
||||
pCloud?.installMode !== nCloud?.installMode ||
|
||||
pCloud?.catalogVersion !== nCloud?.catalogVersion ||
|
||||
pCloud?.source !== nCloud?.source ||
|
||||
pCloud?.lastSyncedAtMs !== nCloud?.lastSyncedAtMs ||
|
||||
@@ -56,15 +121,25 @@ function isEquivalentTelemetry(prev, next) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与单步费用)
|
||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与费用)
|
||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
||||
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||
if (pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature) return false;
|
||||
if (
|
||||
pAct?.liveActivity?.signature !== nAct?.liveActivity?.signature ||
|
||||
pAct?.liveActivity?.startedAtMs !== nAct?.liveActivity?.startedAtMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false;
|
||||
if (pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature) return false;
|
||||
if (
|
||||
pAct?.aggregated?.liveActivity?.signature !== nAct?.aggregated?.liveActivity?.signature ||
|
||||
pAct?.aggregated?.liveActivity?.startedAtMs !== nAct?.aggregated?.liveActivity?.startedAtMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (pAct?.aggregated?.liveActivity?.agentId !== nAct?.aggregated?.liveActivity?.agentId) return false;
|
||||
if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false;
|
||||
if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false;
|
||||
@@ -73,17 +148,34 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false;
|
||||
if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false;
|
||||
if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false;
|
||||
if (pAct?.aggregated?.sessionUnpricedCalls !== nAct?.aggregated?.sessionUnpricedCalls) return false;
|
||||
if (pAct?.aggregated?.sessionCacheHitPct !== nAct?.aggregated?.sessionCacheHitPct) return false;
|
||||
if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false;
|
||||
if (pAct?.aggregated?.activeModelUpstream !== nAct?.aggregated?.activeModelUpstream) return false;
|
||||
if (pAct?.aggregated?.latestCacheHitPct !== nAct?.aggregated?.latestCacheHitPct) return false;
|
||||
if (pAct?.aggregated?.latestSpeedReason !== nAct?.aggregated?.latestSpeedReason) return false;
|
||||
if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false;
|
||||
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
|
||||
if (pAct?.avgTokPerSec !== nAct?.avgTokPerSec) return false;
|
||||
if (pAct?.latestCacheHitPct !== nAct?.latestCacheHitPct) return false;
|
||||
if (pAct?.sessionCacheHitPct !== nAct?.sessionCacheHitPct) return false;
|
||||
if (pAct?.latestSpeedReason !== nAct?.latestSpeedReason) return false;
|
||||
if (pAct?.ttftSummary?.avgSec !== nAct?.ttftSummary?.avgSec) return false;
|
||||
if (pAct?.speedSummary?.sampleCount !== nAct?.speedSummary?.sampleCount) return false;
|
||||
if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false;
|
||||
if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false;
|
||||
if (
|
||||
pAct?.activeModelShort !== nAct?.activeModelShort ||
|
||||
pAct?.activeModelLabel !== nAct?.activeModelLabel ||
|
||||
pAct?.activeModelUpstream !== nAct?.activeModelUpstream
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd ||
|
||||
pAct?.sessionCostUsd !== nAct?.sessionCostUsd ||
|
||||
pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const pAgents = pAct?.agents || [];
|
||||
const nAgents = nAct?.agents || [];
|
||||
@@ -91,8 +183,6 @@ function isEquivalentTelemetry(prev, next) {
|
||||
for (let i = 0; i < pAgents.length; i++) {
|
||||
const pa = pAgents[i];
|
||||
const na = nAgents[i];
|
||||
const pLastStep = pa?.recentSteps?.[0];
|
||||
const nLastStep = na?.recentSteps?.[0];
|
||||
if (
|
||||
pa?.agentId !== na?.agentId ||
|
||||
pa?.role !== na?.role ||
|
||||
@@ -103,11 +193,16 @@ function isEquivalentTelemetry(prev, next) {
|
||||
pa?.latestTtftSec !== na?.latestTtftSec ||
|
||||
pa?.avgTokPerSec !== na?.avgTokPerSec ||
|
||||
pa?.latestCacheHitPct !== na?.latestCacheHitPct ||
|
||||
pa?.sessionCacheHitPct !== na?.sessionCacheHitPct ||
|
||||
pa?.latestSpeedReason !== na?.latestSpeedReason ||
|
||||
pa?.latestStepCostUsd !== na?.latestStepCostUsd ||
|
||||
pa?.sessionCostUsd !== na?.sessionCostUsd ||
|
||||
pa?.sessionUnpricedCalls !== na?.sessionUnpricedCalls ||
|
||||
pa?.activeModelShort !== na?.activeModelShort ||
|
||||
pa?.activeModelUpstream !== na?.activeModelUpstream ||
|
||||
pa?.context?.totalTokens !== na?.context?.totalTokens ||
|
||||
pa?.context?.compactionLimitTokens !== na?.context?.compactionLimitTokens ||
|
||||
pa?.context?.limitTokens !== na?.context?.limitTokens ||
|
||||
pa?.context?.messagesTokens !== na?.context?.messagesTokens ||
|
||||
pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens ||
|
||||
pa?.context?.assistantTokens !== na?.context?.assistantTokens ||
|
||||
@@ -118,21 +213,43 @@ function isEquivalentTelemetry(prev, next) {
|
||||
pa?.context?.mcpToolsTokens !== na?.context?.mcpToolsTokens ||
|
||||
pa?.context?.skillsTokens !== na?.context?.skillsTokens ||
|
||||
pa?.context?.systemPromptTokens !== na?.context?.systemPromptTokens ||
|
||||
pa?.context?.userRulesTokens !== na?.context?.userRulesTokens ||
|
||||
pLastStep?.tokPerSec !== nLastStep?.tokPerSec ||
|
||||
pLastStep?.ttftSec !== nLastStep?.ttftSec ||
|
||||
pLastStep?.outputTokens !== nLastStep?.outputTokens ||
|
||||
pLastStep?.modelUpstream !== nLastStep?.modelUpstream ||
|
||||
pLastStep?.costUsd !== nLastStep?.costUsd
|
||||
pa?.context?.userRulesTokens !== na?.context?.userRulesTokens
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const paSteps = pa?.recentSteps || [];
|
||||
const naSteps = na?.recentSteps || [];
|
||||
if (paSteps.length !== naSteps.length) return false;
|
||||
for (let j = 0; j < paSteps.length; j++) {
|
||||
const bs = paSteps[j];
|
||||
const as = naSteps[j];
|
||||
if (
|
||||
bs?.stepIndex !== as?.stepIndex ||
|
||||
bs?.modelKey !== as?.modelKey ||
|
||||
bs?.modelShort !== as?.modelShort ||
|
||||
bs?.modelLabel !== as?.modelLabel ||
|
||||
bs?.modelUpstream !== as?.modelUpstream ||
|
||||
bs?.responseModel !== as?.responseModel ||
|
||||
bs?.modelSource !== as?.modelSource ||
|
||||
bs?.costUsd !== as?.costUsd ||
|
||||
bs?.tokPerSec !== as?.tokPerSec ||
|
||||
bs?.ttftSec !== as?.ttftSec ||
|
||||
bs?.outputTokens !== as?.outputTokens ||
|
||||
bs?.inputTokens !== as?.inputTokens ||
|
||||
bs?.cacheReadTokens !== as?.cacheReadTokens ||
|
||||
bs?.selectedSpeedReason !== as?.selectedSpeedReason
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 比对 10 通道上下文窗口构成及近期步骤明细
|
||||
const pCtx = pAct?.context;
|
||||
const nCtx = nAct?.context;
|
||||
if (pCtx?.totalTokens !== nCtx?.totalTokens) return false;
|
||||
if (pCtx?.compactionLimitTokens !== nCtx?.compactionLimitTokens) return false;
|
||||
if (pCtx?.limitTokens !== nCtx?.limitTokens) return false;
|
||||
if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false;
|
||||
if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false;
|
||||
if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false;
|
||||
@@ -150,6 +267,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (
|
||||
before.modelKey !== after.modelKey ||
|
||||
before.modelShort !== after.modelShort ||
|
||||
before.modelLabel !== after.modelLabel ||
|
||||
before.modelUpstream !== after.modelUpstream ||
|
||||
before.responseModel !== after.responseModel ||
|
||||
before.modelSource !== after.modelSource ||
|
||||
@@ -158,7 +276,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
before.ttftSec !== after.ttftSec ||
|
||||
before.outputTokens !== after.outputTokens ||
|
||||
before.inputTokens !== after.inputTokens ||
|
||||
before.cacheReadTokens !== after.cacheReadTokens
|
||||
before.cacheReadTokens !== after.cacheReadTokens ||
|
||||
before.selectedSpeedReason !== after.selectedSpeedReason
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -181,8 +300,13 @@ function isEquivalentTelemetry(prev, next) {
|
||||
const pAcct = prev.consumption?.account;
|
||||
const nAcct = next.consumption?.account;
|
||||
if (pAcct?.totalTokens !== nAcct?.totalTokens) return false;
|
||||
if (pAcct?.inputTokens !== nAcct?.inputTokens) return false;
|
||||
if (pAcct?.cacheReadTokens !== nAcct?.cacheReadTokens) return false;
|
||||
if (pAcct?.outputTokens !== nAcct?.outputTokens) return false;
|
||||
if (pAcct?.calls !== nAcct?.calls) return false;
|
||||
if (pAcct?.costUsd !== nAcct?.costUsd) return false;
|
||||
if (pAcct?.savedCostUsd !== nAcct?.savedCostUsd) return false;
|
||||
if (pAcct?.cacheHitPct !== nAcct?.cacheHitPct) return false;
|
||||
if (pAcct?.unpricedCalls !== nAcct?.unpricedCalls) return false;
|
||||
|
||||
// 6. 比对历史趋势时间分桶序列与年度分月序列
|
||||
@@ -268,6 +392,7 @@ function isEquivalentTelemetry(prev, next) {
|
||||
if (pQuot?.usedPct !== nQuot?.usedPct) return false;
|
||||
if (pQuot?.remainingPct !== nQuot?.remainingPct) return false;
|
||||
if (pQuot?.weeklyUsedPct !== nQuot?.weeklyUsedPct) return false;
|
||||
if (pQuot?.weeklyRemainingPct !== nQuot?.weeklyRemainingPct) return false;
|
||||
if (prev.quotas?.weekly?.usedPct !== next.quotas?.weekly?.usedPct) return false;
|
||||
if (prev.quotas?.weekly?.remainingPct !== next.quotas?.weekly?.remainingPct) return false;
|
||||
if (prev.quotas?.weekly?.tokens !== next.quotas?.weekly?.tokens) return false;
|
||||
@@ -323,7 +448,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
pr?.isMainRunning !== nr?.isMainRunning ||
|
||||
pr?.subagentCount !== nr?.subagentCount ||
|
||||
pr?.runningSubagentCount !== nr?.runningSubagentCount ||
|
||||
pr?.mainActivity?.signature !== nr?.mainActivity?.signature
|
||||
pr?.mainActivity?.signature !== nr?.mainActivity?.signature ||
|
||||
pr?.mainActivity?.startedAtMs !== nr?.mainActivity?.startedAtMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -336,7 +462,8 @@ function isEquivalentTelemetry(prev, next) {
|
||||
pSubs[j]?.role !== nSubs[j]?.role ||
|
||||
pSubs[j]?.isRunning !== nSubs[j]?.isRunning ||
|
||||
pSubs[j]?.stepCount !== nSubs[j]?.stepCount ||
|
||||
pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature
|
||||
pSubs[j]?.liveActivity?.signature !== nSubs[j]?.liveActivity?.signature ||
|
||||
pSubs[j]?.liveActivity?.startedAtMs !== nSubs[j]?.liveActivity?.startedAtMs
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
@@ -347,25 +474,46 @@ function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
|
||||
export async function fetchTelemetry({ force = false } = {}) {
|
||||
if (!force && activeForceCount > 0) {
|
||||
return telemetryStore.getState().telemetry;
|
||||
}
|
||||
|
||||
const st = telemetryStore.getState();
|
||||
const reqSeq = ++latestRequestSeq;
|
||||
const startMs = Date.now();
|
||||
|
||||
if (force) {
|
||||
activeForceCount += 1;
|
||||
if (pollTimer) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
telemetryStore.setState({ syncState: 'syncing' });
|
||||
}
|
||||
|
||||
try {
|
||||
if (isWindowOverlayMode()) {
|
||||
const liveRouteId = extractHostRouteCascadeId();
|
||||
if (liveRouteId !== st.hostRouteConversationId) {
|
||||
const patch = { hostRouteConversationId: liveRouteId };
|
||||
if (liveRouteId && st.selectedConversationId && st.selectedConversationId !== liveRouteId) {
|
||||
patch.selectedConversationId = '';
|
||||
}
|
||||
telemetryStore.setState(patch);
|
||||
}
|
||||
}
|
||||
const curSt = telemetryStore.getState();
|
||||
const effectiveConvId = curSt.selectedConversationId || curSt.hostRouteConversationId || '';
|
||||
const params = new URLSearchParams();
|
||||
if (st.selectedConversationId) {
|
||||
params.set('conversationId', st.selectedConversationId);
|
||||
if (effectiveConvId) {
|
||||
params.set('conversationId', effectiveConvId);
|
||||
}
|
||||
if (st.selectedTimeRange) {
|
||||
params.set('range', st.selectedTimeRange);
|
||||
if (curSt.selectedTimeRange) {
|
||||
params.set('range', curSt.selectedTimeRange);
|
||||
}
|
||||
if (st.selectedTimeRange === 'custom') {
|
||||
if (st.customStartMs > 0) params.set('startMs', String(st.customStartMs));
|
||||
if (st.customEndMs > 0) params.set('endMs', String(st.customEndMs));
|
||||
if (curSt.selectedTimeRange === 'custom') {
|
||||
if (curSt.customStartMs > 0) params.set('startMs', String(curSt.customStartMs));
|
||||
if (curSt.customEndMs > 0) params.set('endMs', String(curSt.customEndMs));
|
||||
}
|
||||
if (force) {
|
||||
params.set('force', '1');
|
||||
@@ -373,7 +521,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
const qs = params.toString();
|
||||
const payload = await callSidecarApi(`/api/telemetry${qs ? `?${qs}` : ''}`, {
|
||||
method: 'GET',
|
||||
abortKey: 'telemetry-poll',
|
||||
abortKey: force ? 'telemetry-force' : 'telemetry-poll',
|
||||
});
|
||||
|
||||
if (reqSeq !== latestRequestSeq) {
|
||||
@@ -382,7 +530,11 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
|
||||
if (payload?.uiBundleVersion) {
|
||||
if (activeBundleVersion && activeBundleVersion !== payload.uiBundleVersion) {
|
||||
if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') {
|
||||
if (
|
||||
!isWindowOverlayMode() &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.location?.reload === 'function'
|
||||
) {
|
||||
window.location.reload();
|
||||
return payload;
|
||||
}
|
||||
@@ -402,6 +554,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
if (feedbackTimer) clearTimeout(feedbackTimer);
|
||||
telemetryStore.setState({
|
||||
telemetry: payload,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: 'synced',
|
||||
});
|
||||
feedbackTimer = setTimeout(() => {
|
||||
@@ -413,6 +566,7 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
const nextTelemetry = isSame ? latestSt.telemetry : payload;
|
||||
telemetryStore.setState({
|
||||
telemetry: nextTelemetry,
|
||||
minuteTick: Math.floor(Date.now() / 30000),
|
||||
syncState: latestSt.syncState === 'synced' ? 'synced' : 'idle',
|
||||
});
|
||||
}
|
||||
@@ -421,37 +575,46 @@ export async function fetchTelemetry({ force = false } = {}) {
|
||||
if (err?.name === 'AbortError' || reqSeq !== latestRequestSeq) return null;
|
||||
telemetryStore.setState({ syncState: 'error' });
|
||||
return null;
|
||||
} finally {
|
||||
if (force) {
|
||||
activeForceCount = Math.max(0, activeForceCount - 1);
|
||||
if (activeForceCount === 0 && loopActive && loopTickFn && !pollTimer) {
|
||||
pollTimer = setTimeout(loopTickFn, loopIntervalMs);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveSettingsPatch(patch) {
|
||||
const safePatch = patch && typeof patch === 'object' ? { ...patch } : {};
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'weeklyLimitMode')) {
|
||||
const mode = safePatch.weeklyLimitMode;
|
||||
safePatch.weeklyLimitMode =
|
||||
mode === 'custom_tokens' || mode === 'custom_cost' ? mode : 'official';
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'showTopbarMultiSession')) {
|
||||
safePatch.showTopbarMultiSession = Boolean(safePatch.showTopbarMultiSession);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(safePatch, 'topbarCapsuleSlots')) {
|
||||
safePatch.topbarCapsuleSlots = normalizeClientTopbarSlots(safePatch.topbarCapsuleSlots);
|
||||
}
|
||||
const prevTelemetry = telemetryStore.getState().telemetry;
|
||||
if (prevTelemetry?.settings) {
|
||||
telemetryStore.setState({
|
||||
telemetry: {
|
||||
...prevTelemetry,
|
||||
settings: { ...prevTelemetry.settings, ...patch },
|
||||
activeConversation: patch.contextWindowLimit
|
||||
? {
|
||||
...prevTelemetry.activeConversation,
|
||||
context: {
|
||||
...prevTelemetry.activeConversation?.context,
|
||||
limitTokens: patch.contextWindowLimit,
|
||||
usedPct: Math.min(
|
||||
100,
|
||||
Math.round(
|
||||
((prevTelemetry.activeConversation?.context?.totalTokens || 0) /
|
||||
Math.max(1, patch.contextWindowLimit)) *
|
||||
100
|
||||
)
|
||||
),
|
||||
},
|
||||
}
|
||||
: prevTelemetry.activeConversation,
|
||||
settings: { ...prevTelemetry.settings, ...safePatch },
|
||||
},
|
||||
});
|
||||
}
|
||||
await callSidecarApi('/api/settings', { method: 'POST', body: patch });
|
||||
try {
|
||||
await callSidecarApi('/api/settings', { method: 'POST', body: safePatch });
|
||||
} catch (err) {
|
||||
if (prevTelemetry) {
|
||||
telemetryStore.setState({ telemetry: prevTelemetry });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
await fetchTelemetry({ force: true });
|
||||
}
|
||||
|
||||
@@ -465,7 +628,11 @@ export async function triggerPluginUpdate() {
|
||||
const res = await callSidecarApi('/api/plugin-update', { method: 'POST', body: {} });
|
||||
if (res?.ok && res?.restarting) {
|
||||
await new Promise((r) => setTimeout(r, 1100));
|
||||
if (typeof window !== 'undefined' && typeof window.location?.reload === 'function') {
|
||||
if (
|
||||
!isWindowOverlayMode() &&
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.location?.reload === 'function'
|
||||
) {
|
||||
window.location.reload();
|
||||
return res;
|
||||
}
|
||||
@@ -476,27 +643,44 @@ export async function triggerPluginUpdate() {
|
||||
|
||||
export function startAsyncTelemetryLoop(intervalMs = 2000) {
|
||||
stopAsyncTelemetryLoop();
|
||||
let active = true;
|
||||
loopActive = true;
|
||||
loopIntervalMs = intervalMs;
|
||||
|
||||
const resolveNextDelay = () => {
|
||||
if (isWindowOverlayMode() && typeof document !== 'undefined' && document.hidden) {
|
||||
return Math.max(loopIntervalMs, 8000);
|
||||
}
|
||||
return loopIntervalMs;
|
||||
};
|
||||
|
||||
const tick = async () => {
|
||||
if (!active) return;
|
||||
pollTimer = null;
|
||||
if (!loopActive) return;
|
||||
await fetchTelemetry({ force: false });
|
||||
if (!active) return;
|
||||
pollTimer = setTimeout(tick, intervalMs);
|
||||
if (!loopActive || activeForceCount > 0) return;
|
||||
if (!pollTimer) {
|
||||
pollTimer = setTimeout(tick, resolveNextDelay());
|
||||
}
|
||||
};
|
||||
loopTickFn = tick;
|
||||
|
||||
tick();
|
||||
return () => {
|
||||
active = false;
|
||||
stopAsyncTelemetryLoop();
|
||||
};
|
||||
}
|
||||
|
||||
export function stopAsyncTelemetryLoop() {
|
||||
loopActive = false;
|
||||
loopTickFn = null;
|
||||
if (pollTimer) {
|
||||
clearTimeout(pollTimer);
|
||||
pollTimer = null;
|
||||
}
|
||||
if (feedbackTimer) {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedbackTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,12 +14,10 @@
|
||||
@keyframes anim-pulse-dot {
|
||||
0%,
|
||||
100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.22);
|
||||
opacity: 0.62;
|
||||
opacity: 0.22;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,11 @@ button,
|
||||
input {
|
||||
font-family: inherit;
|
||||
font-size: inherit;
|
||||
font-stretch: inherit;
|
||||
font-variation-settings: inherit;
|
||||
line-height: inherit;
|
||||
letter-spacing: inherit;
|
||||
font-variant-numeric: inherit;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
|
||||
@@ -523,10 +523,6 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.custom-scroll-host[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.custom-scroll-content {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
@@ -678,10 +674,6 @@
|
||||
transition: opacity var(--dur-instant) var(--ease-fast), transform var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.update-badge-btn[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.update-badge-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
@@ -689,3 +681,130 @@
|
||||
.update-badge-btn:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
/* --- 9. 顶部栏定制面板专属表单与排序槽位控件 (Topbar Customization Controls) --- */
|
||||
.settings-inline-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
min-height: 26px;
|
||||
}
|
||||
|
||||
.topbar-header-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.btn-ghost-sm {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
background: transparent;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.btn-ghost-sm:hover:not(:disabled) {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.btn-ghost-sm:disabled {
|
||||
opacity: 0.42;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.topbar-slot-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.topbar-slot-row {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 2px 4px 2px 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
background: transparent;
|
||||
transition: border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.topbar-slot-row:focus-within,
|
||||
.topbar-slot-row:has(.is-open) {
|
||||
z-index: 30;
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.topbar-slot-row .select-menu {
|
||||
max-height: 216px;
|
||||
}
|
||||
|
||||
.slot-index-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
font-variant-numeric: tabular-nums;
|
||||
color: var(--text-secondary);
|
||||
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||
border-radius: var(--radius-xs);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.slot-order-btns {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.slot-move-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-xs);
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
cursor: pointer;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.slot-move-btn:hover:not(:disabled) {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.slot-move-btn:active:not(:disabled) {
|
||||
transform: scale(0.94);
|
||||
}
|
||||
|
||||
.slot-move-btn:disabled {
|
||||
opacity: 0.28;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,589 @@
|
||||
/*
|
||||
* 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css).
|
||||
* 严格遵循单层微边框与语义变量规范(零硬编码色值、零 Emoji、硬件加速合成层动画)。
|
||||
*/
|
||||
|
||||
/* --- 1. 顶栏胶囊宿主容器 (Titlebar Capsule Host) --- */
|
||||
:host(.wm-capsule-host) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
flex-shrink: 0;
|
||||
vertical-align: middle;
|
||||
-webkit-app-region: no-drag;
|
||||
pointer-events: auto;
|
||||
user-select: none;
|
||||
font-family: "Google Sans Flex", "Google Sans", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
font-size: 12px;
|
||||
font-weight: 450;
|
||||
font-stretch: 100%;
|
||||
font-variation-settings: normal;
|
||||
line-height: 18px;
|
||||
letter-spacing: 0.015em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: var(--text-primary);
|
||||
z-index: 2147482900;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-dock="flow"]) {
|
||||
position: relative;
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-dock="fixed"]) {
|
||||
position: fixed;
|
||||
top: 6px;
|
||||
right: 144px;
|
||||
}
|
||||
|
||||
@keyframes wm-dot-pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.38;
|
||||
}
|
||||
}
|
||||
|
||||
/* 左侧多会话实时状态触发器(无边框、与宿主顶栏按钮同高 28px、整数行高防压扁) */
|
||||
.wm-multi-btn {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 28px;
|
||||
padding: 0 8px;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
border: none;
|
||||
outline: none;
|
||||
box-shadow: none;
|
||||
border-radius: var(--radius-sm);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 450;
|
||||
line-height: 18px;
|
||||
letter-spacing: 0.015em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: pointer;
|
||||
-webkit-app-region: no-drag;
|
||||
white-space: nowrap;
|
||||
contain: layout style;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.wm-multi-btn[hidden],
|
||||
.wm-cap-slot[hidden],
|
||||
.wm-sep[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.wm-multi-btn:hover {
|
||||
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.wm-multi-btn.is-open {
|
||||
background: color-mix(in srgb, var(--text-primary) 11%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.wm-multi-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 44%, transparent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wm-multi-btn.is-running .wm-multi-dot {
|
||||
background: var(--accent-primary);
|
||||
animation: wm-dot-pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.wm-multi-btn.is-waiting .wm-multi-dot {
|
||||
background: var(--metric-warn);
|
||||
animation: wm-dot-pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.wm-multi-label {
|
||||
display: inline-block;
|
||||
min-width: 46px;
|
||||
line-height: 18px;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wm-multi-btn.is-running .wm-multi-label,
|
||||
.wm-multi-btn.is-waiting .wm-multi-label {
|
||||
color: var(--text-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wm-capsule-btn {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
height: 28px;
|
||||
padding: 0 9px;
|
||||
margin: 0;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
border: none;
|
||||
outline: none;
|
||||
box-shadow: none;
|
||||
border-radius: var(--radius-sm);
|
||||
font-family: inherit;
|
||||
font-size: 12px;
|
||||
font-weight: 450;
|
||||
line-height: 18px;
|
||||
letter-spacing: 0.015em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
cursor: pointer;
|
||||
-webkit-app-region: no-drag;
|
||||
white-space: nowrap;
|
||||
contain: layout style;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.wm-capsule-btn:hover {
|
||||
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.wm-capsule-btn.is-open {
|
||||
background: color-mix(in srgb, var(--text-primary) 11%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
/* 右侧胶囊通用槽位容器与按指标预占定宽(严格防止动态数值跳动,保留舒展字间距) */
|
||||
.wm-cap-slot {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: 18px;
|
||||
line-height: 18px;
|
||||
flex-shrink: 0;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.wm-slot-text {
|
||||
display: inline-block;
|
||||
line-height: 18px;
|
||||
letter-spacing: 0.015em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */
|
||||
.wm-ctx-seg {
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
width: 50px;
|
||||
}
|
||||
|
||||
.wm-ring-svg {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex-shrink: 0;
|
||||
transform: rotate(-90deg);
|
||||
}
|
||||
|
||||
.wm-ring-track {
|
||||
fill: none;
|
||||
stroke: color-mix(in srgb, var(--text-secondary) 24%, transparent);
|
||||
stroke-width: 2;
|
||||
}
|
||||
|
||||
.wm-ring-fill {
|
||||
fill: none;
|
||||
stroke: var(--accent-primary);
|
||||
stroke-width: 2;
|
||||
stroke-linecap: round;
|
||||
transition:
|
||||
stroke-dashoffset var(--dur-normal) var(--ease-fast),
|
||||
stroke var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.wm-ring-fill.tone-warn {
|
||||
stroke: var(--metric-warn);
|
||||
}
|
||||
|
||||
.wm-ring-fill.tone-danger {
|
||||
stroke: var(--metric-danger);
|
||||
}
|
||||
|
||||
.wm-ctx-pct {
|
||||
min-width: 27px;
|
||||
max-width: 31px;
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.wm-sep {
|
||||
width: 1px;
|
||||
height: 12px;
|
||||
background: color-mix(in srgb, var(--text-secondary) 26%, transparent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* 速度槽位(固定预占宽度 58px 居中对齐) */
|
||||
.wm-seg-speed {
|
||||
width: 58px;
|
||||
}
|
||||
|
||||
.wm-speed-text {
|
||||
width: 58px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wm-seg-speed.state-running {
|
||||
color: var(--metric-speed);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* 首字延迟槽位(固定预占宽度 46px 居中对齐,覆盖 0.85s ~ 105s) */
|
||||
.wm-seg-ttft {
|
||||
width: 46px;
|
||||
}
|
||||
|
||||
.wm-ttft-text {
|
||||
width: 46px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* 本次费用槽位(固定预占宽度 52px 居中对齐,覆盖 <$0.001 ~ $99.99) */
|
||||
.wm-seg-cost {
|
||||
width: 52px;
|
||||
}
|
||||
|
||||
.wm-cost-text {
|
||||
width: 52px;
|
||||
text-align: center;
|
||||
color: var(--text-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* 配额槽位(固定预占宽度 52px 居中对齐,完整容纳 余 100% / 余 --% 且在任意槽位对称) */
|
||||
.wm-seg-quota {
|
||||
width: 52px;
|
||||
}
|
||||
|
||||
.wm-quota-text {
|
||||
width: 52px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-warn,
|
||||
.wm-cap-slot.tone-warn .wm-slot-text {
|
||||
color: var(--metric-warn);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.wm-cap-slot.tone-danger,
|
||||
.wm-cap-slot.tone-danger .wm-slot-text {
|
||||
color: var(--metric-danger);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
/* 右上角绝对定位更新圆点,不参与文档流,零宽度抖动 */
|
||||
.wm-update-dot {
|
||||
position: absolute;
|
||||
top: 3px;
|
||||
right: 3px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: var(--metric-ok);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 四级响应式迟滞折叠(基于可见槽位次序 data-vis-rank 与分隔线次序 data-sep-for-rank 动态折叠) */
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="compact"]) .wm-sep[data-sep-for-rank="3"] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-label {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="minimal"]) .wm-multi-btn,
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-btn {
|
||||
padding: 0 7px;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="2"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-sep[data-sep-for-rank="3"],
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"] .wm-ctx-pct,
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-multi-label {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-capsule-btn {
|
||||
padding: 0 6px;
|
||||
}
|
||||
|
||||
:host(.wm-capsule-host[data-layout="ring-only"]) .wm-cap-slot[data-vis-rank="1"].wm-ctx-seg {
|
||||
width: 14px;
|
||||
}
|
||||
|
||||
/* --- 2. 顶层浮层传送门宿主 (Body Portal Host: Multi-Session HUD, Tooltip & Full 4-Tab Popover) --- */
|
||||
:host(.wm-portal-host) {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
overflow: visible;
|
||||
pointer-events: none;
|
||||
z-index: 2147483000;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", Roboto, sans-serif;
|
||||
font-size: 12.5px;
|
||||
line-height: 1.4;
|
||||
font-variant-numeric: tabular-nums;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
@keyframes wm-popover-in {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
.wm-popover-panel {
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(492px, calc(100vw - 24px));
|
||||
height: min(588px, calc(100vh - 54px));
|
||||
max-height: calc(100vh - 54px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--surface-bg);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
pointer-events: auto;
|
||||
overflow: hidden;
|
||||
-webkit-app-region: no-drag;
|
||||
transform-origin: top right;
|
||||
animation: wm-popover-in var(--dur-fast) var(--ease-fast);
|
||||
}
|
||||
|
||||
.wm-popover-panel .app-shell {
|
||||
height: 100%;
|
||||
max-height: 100%;
|
||||
max-width: none;
|
||||
}
|
||||
|
||||
/* 顶栏胶囊悬停全景概览浮层(复用实时概览三卡片架构,全槽位预占,仅就地更新节点不跳动) */
|
||||
.wm-hover-tip {
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(492px, calc(100vw - 24px));
|
||||
max-height: calc(100vh - 54px);
|
||||
padding: var(--space-3) var(--space-4);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
background: var(--surface-bg);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
pointer-events: none;
|
||||
overflow: hidden;
|
||||
contain: layout style;
|
||||
z-index: 2147483001;
|
||||
transform-origin: top right;
|
||||
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
/* 左侧在线多会话实时看板浮层(单层无套娃细线卡片,仅显示在线运行会话,留足呼吸感) */
|
||||
.wm-multi-panel {
|
||||
position: fixed;
|
||||
top: 42px;
|
||||
left: 12px;
|
||||
width: min(484px, calc(100vw - 24px));
|
||||
max-height: calc(100vh - 54px);
|
||||
padding: 14px 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
background: var(--surface-bg);
|
||||
color: var(--text-primary);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
box-shadow: var(--shadow-overlay);
|
||||
pointer-events: auto;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
-webkit-app-region: no-drag;
|
||||
contain: layout style;
|
||||
z-index: 2147483002;
|
||||
transform-origin: top left;
|
||||
animation: wm-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.wm-popover-panel.is-instant,
|
||||
.wm-hover-tip.is-instant,
|
||||
.wm-multi-panel.is-instant {
|
||||
animation: none !important;
|
||||
}
|
||||
|
||||
.wm-hover-tip .cell-label,
|
||||
.wm-hover-tip .legend-item,
|
||||
.wm-hover-tip .legend-left,
|
||||
.wm-hover-tip .panel-header > span {
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wm-hover-tip .panel-header > span:first-child:not(.panel-title) {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.wm-hover-quota-pools {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wm-hover-quota-foot {
|
||||
font-size: 11px;
|
||||
padding-top: 2px;
|
||||
}
|
||||
|
||||
.wm-pin-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 5px;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-radius: var(--radius-xs);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wm-session-tag {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: color-mix(in srgb, var(--text-primary) 7%, transparent);
|
||||
border-radius: var(--radius-xs);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wm-session-tag.is-here {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
}
|
||||
|
||||
.wm-task-metrics {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wm-multi-header {
|
||||
padding-bottom: 10px;
|
||||
border-bottom: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
/* 多会话单层面板内去除重复边框与底色,留足行距与段落呼吸感,仅靠左侧圆点闪烁表达状态 */
|
||||
.wm-multi-panel .live-activity-list {
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-card {
|
||||
gap: 8px;
|
||||
padding: 12px 2px;
|
||||
border: none;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-card:first-child {
|
||||
padding-top: 11px;
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-card:last-child {
|
||||
padding-bottom: 2px;
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-card + .live-task-card {
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.wm-multi-panel .live-task-title {
|
||||
font-size: 12.5px;
|
||||
}
|
||||
|
||||
.wm-multi-empty {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
min-height: 36px;
|
||||
padding: 12px 2px 4px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.wm-multi-empty-left {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wm-idle-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--text-secondary) 38%, transparent);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wm-multi-empty-hint {
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
@@ -4,26 +4,24 @@
|
||||
* eliminating hardcoded hex colors across components and views.
|
||||
*/
|
||||
|
||||
:root {
|
||||
:root,
|
||||
:host {
|
||||
/* Architectural Geometry: Only Top Nav uses --radius-pill */
|
||||
--radius-pill: 999px;
|
||||
--radius-sm: 4px;
|
||||
--radius-xs: 2px;
|
||||
|
||||
/* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode) */
|
||||
/* Host-Bridged Surfaces (Clean, zero-muddy-gray light mode & safe dark fallback) */
|
||||
--surface-bg: var(--background, hsl(0 0% 100%));
|
||||
--surface-panel: var(--card, hsl(0 0% 100%));
|
||||
--surface-panel: var(--card, var(--background, hsl(0 0% 100%)));
|
||||
--surface-subtle: color-mix(in srgb, var(--surface-panel) 97%, var(--text-primary) 3%);
|
||||
--surface-track: color-mix(in srgb, var(--border-hairline) 42%, var(--surface-panel));
|
||||
--surface-elevated: var(--surface-panel);
|
||||
--surface-hover: color-mix(in srgb, var(--accent-primary) 6%, var(--surface-panel));
|
||||
--surface-active: color-mix(in srgb, var(--accent-primary) 12%, var(--surface-panel));
|
||||
--surface-backdrop: color-mix(in srgb, var(--surface-bg) 78%, transparent);
|
||||
|
||||
/* Crisp 1px Hairline Borders */
|
||||
--border-hairline: color-mix(in srgb, var(--border, hsl(214 18% 88%)) 82%, var(--surface-panel));
|
||||
--border-strong: color-mix(in srgb, var(--border-hairline) 72%, var(--text-primary) 28%);
|
||||
--border-focus: var(--accent-primary);
|
||||
|
||||
/* Typography Hierarchy */
|
||||
--text-primary: var(--foreground, hsl(215 22% 15%));
|
||||
@@ -46,10 +44,8 @@
|
||||
--metric-warn-soft: color-mix(in srgb, var(--metric-warn) 15%, transparent);
|
||||
|
||||
--metric-danger: var(--destructive, hsl(0 74% 50%));
|
||||
--metric-danger-soft: color-mix(in srgb, var(--metric-danger) 15%, transparent);
|
||||
|
||||
/* Context Window 10-Channel Palette */
|
||||
--ctx-messages: hsl(217 82% 51%);
|
||||
--ctx-assistant: hsl(217 82% 54%);
|
||||
--ctx-tool-results: hsl(192 82% 43%);
|
||||
--ctx-user-input: hsl(245 72% 62%);
|
||||
@@ -69,7 +65,7 @@
|
||||
|
||||
/* Elevation & Shadows */
|
||||
--shadow-popover: 0 4px 12px rgb(0 0 0 / 0.22);
|
||||
--shadow-glider: 0 1px 2px rgb(0 0 0 / 0.14);
|
||||
--shadow-overlay: 0 16px 38px rgb(0 0 0 / 0.38), 0 3px 10px rgb(0 0 0 / 0.22);
|
||||
|
||||
/* Fast Hardware-Accelerated Motion Tokens */
|
||||
--ease-fast: cubic-bezier(0.22, 1, 0.36, 1);
|
||||
@@ -78,10 +74,8 @@
|
||||
--dur-normal: 180ms;
|
||||
|
||||
/* Spacing & Density */
|
||||
--space-1: 4px;
|
||||
--space-2: 6px;
|
||||
--space-3: 8px;
|
||||
--space-4: 10px;
|
||||
--space-5: 12px;
|
||||
--space-6: 14px;
|
||||
}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
/*
|
||||
* 全景消耗统计视图样式表 (views-consumption.css).
|
||||
* 包含:
|
||||
* 1. 消费概览顶栏与 3+2 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-*, .cons-col)
|
||||
* 1. 消费概览顶栏与 3+3 统一指标矩阵 (.cons-overview-head, .cons-unified-matrix, .cons-split-3, .cons-col)
|
||||
* 2. 4 段比例条与圆点色块 (.dot-swatch, .cons-seg-bar)
|
||||
* 3. 热门模型与数据来源列表项样式 (.cons-row-*, .cons-share-pill, .cons-item-*)
|
||||
* 4. 历史趋势纯 SVG 平滑曲线图与峰值胶囊 (.trend-*)
|
||||
* 5. 12 个月垂直堆叠柱状图与月度图例 (.monthly-*, .month-*)
|
||||
*/
|
||||
|
||||
/* --- 1. 消费概览顶栏与 3+2 组合指标矩阵 (Consumption Overview Matrix) --- */
|
||||
/* --- 1. 消费概览顶栏与 3+3 组合指标矩阵 (Consumption Overview Matrix) --- */
|
||||
.cons-overview-head {
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
@@ -48,15 +48,28 @@
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
}
|
||||
|
||||
.cons-split-2 {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
}
|
||||
|
||||
.cons-matrix-bottom {
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
|
||||
.cons-matrix-bottom .cons-col {
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
@media (max-width: 350px) {
|
||||
.cons-matrix-bottom.cons-split-3 {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
.cons-matrix-bottom .cons-col {
|
||||
padding-left: 0;
|
||||
padding-right: 0;
|
||||
}
|
||||
.cons-matrix-bottom .cons-col.is-bordered-col {
|
||||
border-left: none;
|
||||
border-top: 1px solid var(--border-hairline);
|
||||
}
|
||||
}
|
||||
|
||||
.cons-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -105,10 +118,34 @@
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.cons-mid-num {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
.cons-sub-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-sub-head > span {
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-sub-label {
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-mid-num {
|
||||
font-size: 14.5px;
|
||||
font-weight: 700;
|
||||
line-height: 1.25;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.015em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- 2. 4 段比例条与圆点色块 (Four-Segment Bar & Dot Swatches) --- */
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* 包含:
|
||||
* 1. 通用面板容器与标题头 (.panel, .panel-header, .panel-title, .panel-meta)
|
||||
* 2. 4 格实时测速指标矩阵 (.telemetry-matrix, .matrix-cell, .cell-*)
|
||||
* 3. 6 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill)
|
||||
* 3. 10 段上下文窗口进度条与配额填充条 (.progress-track, .progress-seg, .progress-fill)
|
||||
* 4. 上下文双列图例网格与色块 (.ctx-legend-grid, .legend-*, .swatch)
|
||||
* 5. 双栏布局网格与窄屏响应式断点 (.dual-grid)
|
||||
*/
|
||||
@@ -57,50 +57,42 @@
|
||||
.live-activity-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.live-activity-list[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.live-task-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid var(--accent-primary-border);
|
||||
gap: 7px;
|
||||
padding: 10px 12px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-xs);
|
||||
background: color-mix(in srgb, var(--accent-primary) 5%, var(--surface-panel));
|
||||
background: var(--surface-panel);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.live-task-card.is-waiting {
|
||||
border-color: color-mix(in srgb, var(--metric-warn) 42%, var(--border-hairline));
|
||||
background: color-mix(in srgb, var(--metric-warn) 7%, var(--surface-panel));
|
||||
}
|
||||
|
||||
.live-task-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
gap: var(--space-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.live-task-title-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
gap: 7px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.live-task-title {
|
||||
font-size: 11.5px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
line-height: 1.45;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -116,7 +108,7 @@
|
||||
.live-task-header-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -151,16 +143,13 @@
|
||||
background: var(--accent-primary-soft);
|
||||
}
|
||||
|
||||
.live-sub-toggle[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.live-task-main-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
padding-left: 1px;
|
||||
padding-left: 18px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.live-activity-dot {
|
||||
@@ -174,37 +163,37 @@
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.live-task-card.is-compacting .live-activity-dot {
|
||||
color: var(--ctx-checkpoint);
|
||||
}
|
||||
|
||||
.live-activity-phase {
|
||||
font-size: 11px;
|
||||
font-size: 11.5px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-task-card.is-waiting .live-activity-phase {
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.live-activity-progress {
|
||||
font-size: 10px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
padding: 0 4px;
|
||||
padding: 0 5px;
|
||||
border-radius: var(--radius-xs);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-activity-sep {
|
||||
font-size: 11px;
|
||||
font-size: 11.5px;
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-activity-detail {
|
||||
font-size: 11px;
|
||||
font-size: 11.5px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
@@ -214,38 +203,35 @@
|
||||
}
|
||||
|
||||
.live-activity-elapsed {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
font-size: 11.5px;
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
min-width: 28px;
|
||||
text-align: right;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.live-task-card.is-waiting .live-activity-elapsed {
|
||||
color: var(--metric-warn);
|
||||
}
|
||||
|
||||
.live-sub-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-top: 5px;
|
||||
margin-top: 1px;
|
||||
gap: 8px;
|
||||
padding-top: 9px;
|
||||
margin-top: 3px;
|
||||
margin-left: 18px;
|
||||
border-top: 1px dashed var(--border-hairline);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.live-sub-list[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.live-sub-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
gap: 10px;
|
||||
min-height: 22px;
|
||||
min-width: 0;
|
||||
font-size: 10.5px;
|
||||
font-size: 11.5px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.live-sub-row.is-done {
|
||||
@@ -255,7 +241,7 @@
|
||||
.live-sub-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
gap: 7px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
@@ -266,7 +252,7 @@
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 110px;
|
||||
max-width: 148px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -280,9 +266,11 @@
|
||||
}
|
||||
|
||||
.live-sub-elapsed {
|
||||
font-size: 10.5px;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
min-width: 28px;
|
||||
text-align: right;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
@@ -339,7 +327,7 @@
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
/* --- 3. 6 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */
|
||||
/* --- 3. 10 段上下文进度条与配额池填充条 (Context Segment Meter & Quota Progress Bars) --- */
|
||||
.progress-track {
|
||||
width: 100%;
|
||||
height: 6px;
|
||||
@@ -444,6 +432,7 @@
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.swatch {
|
||||
@@ -463,10 +452,6 @@
|
||||
.swatch.seg-skills { background: var(--ctx-skills); }
|
||||
.swatch.seg-system-prompt { background: var(--ctx-system-prompt); }
|
||||
.swatch.seg-user-rules { background: var(--ctx-user-rules); }
|
||||
.swatch.seg-cached { background: var(--ctx-cached); }
|
||||
.swatch.seg-input { background: var(--ctx-input); }
|
||||
.swatch.seg-thinking { background: var(--ctx-thinking); }
|
||||
.swatch.seg-output { background: var(--ctx-output); }
|
||||
|
||||
/* --- 5. 双栏网格与窄视口响应式折叠 (Dual Grid & Responsive Breakpoints) --- */
|
||||
.dual-grid {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* @fileoverview View 2: ConsumptionView (全景消耗统计视图).
|
||||
* 采用 5 段式分析布局展示指定时间窗口内的全量 Token 与费用消耗:
|
||||
* 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+2 组合矩阵展示总 Token/调用次数、
|
||||
* USD/CNY 预估费用、缓存命中率与命中量、输入/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。
|
||||
* 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡与首/中/末三时间锚点。
|
||||
* 1. 用量概览:支持预设时间段与自定义区间筛选,通过 3+3 组合矩阵展示总 Token/调用次数、
|
||||
* USD/CNY 预估费用、缓存命中率与命中量、新输入/缓存读取(含节省费用)/输出细分占比,以及底部 4 段比例条 (`FourSegmentBar`)。
|
||||
* 2. 历史趋势:基于 `TrendAreaChart` 渲染纯 SVG 三次贝塞尔平滑曲线面积图、峰值气泡、对齐多刻度时间轴与悬停详情浮层。
|
||||
* 3. 热门模型:按 Token 总量降序展示各模型的消耗占比徽章、4 段构成条及输入/缓存/输出/思考/调用明细。
|
||||
* 4. 数据来源:按调用来源聚合展示 Token 构成、占比与费用明细。
|
||||
* 5. 按月细分:12 个月垂直 4 段堆叠柱状图,直观对比全年各月费用、Token 总量与缓存/思考结构。
|
||||
@@ -48,27 +48,45 @@ export const ConsumptionView = defineComponent({
|
||||
name: 'ConsumptionView',
|
||||
setup({ onCleanup }) {
|
||||
// --- 时间筛选栏:快速时间段分段控制器与自定义起止时间选择条 ---
|
||||
let draftStartMs = telemetryStore.getState().customStartMs;
|
||||
let draftEndMs = telemetryStore.getState().customEndMs;
|
||||
let hasUncommittedCustomDraft = false;
|
||||
|
||||
const timeFilterSwitch = SegmentedControl({
|
||||
ariaLabel: '消耗统计时间范围',
|
||||
modelValue: telemetryStore.getState().selectedTimeRange,
|
||||
options: TIME_RANGE_OPTIONS,
|
||||
onUpdateModelValue: (nextRange) => {
|
||||
if (nextRange === 'custom') {
|
||||
const st = telemetryStore.getState();
|
||||
draftStartMs = st.customStartMs;
|
||||
draftEndMs = st.customEndMs;
|
||||
hasUncommittedCustomDraft = false;
|
||||
startPicker.setValue(draftStartMs);
|
||||
endPicker.setValue(draftEndMs);
|
||||
} else {
|
||||
hasUncommittedCustomDraft = false;
|
||||
}
|
||||
telemetryStore.setState({ selectedTimeRange: nextRange });
|
||||
fetchTelemetry({ force: false });
|
||||
},
|
||||
});
|
||||
|
||||
const startPicker = CustomDateTimePicker({
|
||||
modelValue: telemetryStore.getState().customStartMs,
|
||||
modelValue: draftStartMs,
|
||||
onUpdateModelValue: (ms) => {
|
||||
telemetryStore.setState({ customStartMs: ms });
|
||||
draftStartMs = ms;
|
||||
hasUncommittedCustomDraft = true;
|
||||
startPicker.setValue(ms);
|
||||
},
|
||||
});
|
||||
|
||||
const endPicker = CustomDateTimePicker({
|
||||
modelValue: telemetryStore.getState().customEndMs,
|
||||
modelValue: draftEndMs,
|
||||
onUpdateModelValue: (ms) => {
|
||||
telemetryStore.setState({ customEndMs: ms });
|
||||
draftEndMs = ms;
|
||||
hasUncommittedCustomDraft = true;
|
||||
endPicker.setValue(ms);
|
||||
},
|
||||
});
|
||||
|
||||
@@ -79,20 +97,20 @@ export const ConsumptionView = defineComponent({
|
||||
className: 'btn-primary',
|
||||
style: 'height: 26px; padding: 0 10px;',
|
||||
onClick: () => {
|
||||
const st = telemetryStore.getState();
|
||||
const sMs = Number(st.customStartMs || 0);
|
||||
const eMs = Number(st.customEndMs || 0);
|
||||
if (sMs > 0 && eMs > 0 && sMs > eMs) {
|
||||
startPicker.setValue(eMs);
|
||||
endPicker.setValue(sMs);
|
||||
telemetryStore.setState({
|
||||
selectedTimeRange: 'custom',
|
||||
customStartMs: eMs,
|
||||
customEndMs: sMs,
|
||||
});
|
||||
} else {
|
||||
telemetryStore.setState({ selectedTimeRange: 'custom' });
|
||||
}
|
||||
const sMs = Number(draftStartMs || 0);
|
||||
const eMs = Number(draftEndMs || 0);
|
||||
const minMs = sMs > 0 && eMs > 0 ? Math.min(sMs, eMs) : sMs;
|
||||
const maxMs = sMs > 0 && eMs > 0 ? Math.max(sMs, eMs) : eMs;
|
||||
draftStartMs = minMs;
|
||||
draftEndMs = maxMs;
|
||||
hasUncommittedCustomDraft = false;
|
||||
startPicker.setValue(minMs);
|
||||
endPicker.setValue(maxMs);
|
||||
telemetryStore.setState({
|
||||
selectedTimeRange: 'custom',
|
||||
customStartMs: minMs,
|
||||
customEndMs: maxMs,
|
||||
});
|
||||
fetchTelemetry({ force: true });
|
||||
},
|
||||
},
|
||||
@@ -114,7 +132,7 @@ export const ConsumptionView = defineComponent({
|
||||
]
|
||||
);
|
||||
|
||||
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 2 列输入/输出拆分 + 底部 4 段比例条) ---
|
||||
// --- Section 1: 用量概览矩阵 (上层 3 列核心总量 + 下层 3 列新输入/缓存读取/输出拆分 + 底部 4 段比例条) ---
|
||||
const dateSpanBadge = h('span', { className: 'cons-badge text-mono', text: '-- ~ --' });
|
||||
const heroTotalTokens = h('strong', { className: 'cons-hero-num text-mono', text: '0' });
|
||||
const heroTotalCalls = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '0 次' });
|
||||
@@ -126,7 +144,11 @@ export const ConsumptionView = defineComponent({
|
||||
|
||||
const inputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-input); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const inputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '新输入 0 · 缓存 0' });
|
||||
const inputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '未命中缓存输入' });
|
||||
|
||||
const cacheSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-cached); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const cacheMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
const cacheSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: 11px;', text: '节省 $0.00' });
|
||||
|
||||
const outputSharePct = h('span', { className: 'text-mono', style: 'color: var(--ctx-output); font-weight: 600; font-size: 11.5px;', text: '0%' });
|
||||
const outputMainTokens = h('strong', { className: 'cons-mid-num text-mono', text: '0' });
|
||||
@@ -161,27 +183,38 @@ export const ConsumptionView = defineComponent({
|
||||
h('div', { className: 'cons-baseline' }, [cacheHitPctEl, cacheTokensEl]),
|
||||
]),
|
||||
]),
|
||||
h('div', { className: 'cons-split-2 cons-matrix-bottom' }, [
|
||||
h('div', { className: 'cons-split-3 cons-matrix-bottom' }, [
|
||||
h('div', { className: 'cons-col' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输入用量' }),
|
||||
inputMainTokens,
|
||||
h('span', { text: '新输入' }),
|
||||
]),
|
||||
inputSharePct,
|
||||
]),
|
||||
inputMainTokens,
|
||||
inputSubText,
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
h('span', { text: '缓存读取' }),
|
||||
]),
|
||||
cacheSharePct,
|
||||
]),
|
||||
cacheMainTokens,
|
||||
cacheSubText,
|
||||
]),
|
||||
h('div', { className: 'cons-col is-bordered-col' }, [
|
||||
h('div', { className: 'cons-sub-head' }, [
|
||||
h('span', { className: 'legend-left cons-sub-label' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
h('span', { style: 'color: var(--text-primary); font-weight: 600; font-size: 11.5px;', text: '输出用量' }),
|
||||
outputMainTokens,
|
||||
h('span', { text: '输出用量' }),
|
||||
]),
|
||||
outputSharePct,
|
||||
]),
|
||||
outputMainTokens,
|
||||
outputSubText,
|
||||
]),
|
||||
]),
|
||||
@@ -416,8 +449,12 @@ export const ConsumptionView = defineComponent({
|
||||
if (!slice) return;
|
||||
timeFilterSwitch.setValue(slice.range);
|
||||
patchAttr(customRangeBar, 'hidden', slice.range !== 'custom');
|
||||
startPicker.setValue(slice.customStartMs);
|
||||
endPicker.setValue(slice.customEndMs);
|
||||
if (!hasUncommittedCustomDraft) {
|
||||
draftStartMs = slice.customStartMs;
|
||||
draftEndMs = slice.customEndMs;
|
||||
startPicker.setValue(draftStartMs);
|
||||
endPicker.setValue(draftEndMs);
|
||||
}
|
||||
|
||||
const cons = slice.consumption || {};
|
||||
const preset =
|
||||
@@ -436,6 +473,7 @@ export const ConsumptionView = defineComponent({
|
||||
const responseTokens = Number(acct.responseTokens || 0);
|
||||
const thinkingTokens = Number(acct.thinkingTokens || 0);
|
||||
const costUsd = Number(acct.costUsd || 0);
|
||||
const savedCostUsd = Number(acct.savedCostUsd || 0);
|
||||
|
||||
patchText(heroTotalTokens, formatTokensPrecise(totalTokens));
|
||||
patchText(heroTotalCalls, `${acct.calls || 0} 次`);
|
||||
@@ -445,13 +483,37 @@ export const ConsumptionView = defineComponent({
|
||||
patchText(cacheHitPctEl, `${Number(acct.cacheHitPct ?? 0).toFixed(1)}%`);
|
||||
patchText(cacheTokensEl, `命中 ${formatTokensPrecise(cacheTokens)}`);
|
||||
|
||||
const inPct = totalTokens > 0 ? +((inputTokens / totalTokens) * 100).toFixed(1) : 0;
|
||||
const outPct = totalTokens > 0 ? +((outputTokens / totalTokens) * 100).toFixed(1) : 0;
|
||||
let inPct = 0;
|
||||
let cachePct = 0;
|
||||
let outPct = 0;
|
||||
if (totalTokens > 0) {
|
||||
const rawTenths = [
|
||||
(inputTokens / totalTokens) * 1000,
|
||||
(cacheTokens / totalTokens) * 1000,
|
||||
(outputTokens / totalTokens) * 1000,
|
||||
];
|
||||
const floored = rawTenths.map((v) => Math.max(0, Math.floor(v)));
|
||||
const rem = Math.max(0, 1000 - (floored[0] + floored[1] + floored[2]));
|
||||
const order = [0, 1, 2].sort(
|
||||
(a, b) => rawTenths[b] - floored[b] - (rawTenths[a] - floored[a])
|
||||
);
|
||||
for (let k = 0; k < rem && k < 3; k++) {
|
||||
floored[order[k]] += 1;
|
||||
}
|
||||
inPct = +(floored[0] / 10).toFixed(1);
|
||||
cachePct = +(floored[1] / 10).toFixed(1);
|
||||
outPct = +(floored[2] / 10).toFixed(1);
|
||||
}
|
||||
|
||||
patchText(inputSharePct, `${inPct}%`);
|
||||
patchText(inputMainTokens, formatTokensPrecise(inputTokens));
|
||||
patchText(inputSubText, '未命中缓存输入');
|
||||
|
||||
patchText(cacheSharePct, `${cachePct}%`);
|
||||
patchText(cacheMainTokens, formatTokensPrecise(cacheTokens));
|
||||
patchText(
|
||||
inputSubText,
|
||||
`新输入 ${formatTokensPrecise(inputTokens)} · 缓存 ${formatTokensPrecise(cacheTokens)}`
|
||||
cacheSubText,
|
||||
`节省 ${formatUsd(savedCostUsd, { precise: savedCostUsd > 0 && savedCostUsd < 0.01 })}`
|
||||
);
|
||||
|
||||
patchText(outputSharePct, `${outPct}%`);
|
||||
@@ -480,7 +542,8 @@ export const ConsumptionView = defineComponent({
|
||||
);
|
||||
trendChart.update(trendSeries);
|
||||
|
||||
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账)
|
||||
// 3. 同步热门模型列表(按总 Token 数降序排列并执行键值增量对账,遵循模型名称显示格式设置)
|
||||
const showUpstream = Boolean(slice.showUpstreamModel);
|
||||
const models = (slice.modelBreakdown || [])
|
||||
.slice()
|
||||
.sort((a, b) => (b.totalTokens || 0) - (a.totalTokens || 0));
|
||||
@@ -489,9 +552,17 @@ export const ConsumptionView = defineComponent({
|
||||
patchKeyedList(modelsListEl, models, {
|
||||
keyFn: (m) => m.label || m.shortName,
|
||||
sigFn: (m) =>
|
||||
`${m.label}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||
`${showUpstream}:${m.label}:${m.upstreamName || ''}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${m.calls}:${modelsTotalTok}`,
|
||||
createRow: createBreakdownItemRow,
|
||||
updateRow: (refs, m) => updateBreakdownItemRow(refs, m, modelsTotalTok, true),
|
||||
updateRow: (refs, m) =>
|
||||
updateBreakdownItemRow(
|
||||
refs,
|
||||
showUpstream
|
||||
? { ...m, label: m.upstreamName || m.label || m.shortName }
|
||||
: m,
|
||||
modelsTotalTok,
|
||||
true
|
||||
),
|
||||
});
|
||||
|
||||
// 4. 同步数据来源列表
|
||||
@@ -529,8 +600,14 @@ export const ConsumptionView = defineComponent({
|
||||
patchText(col.tokText, '');
|
||||
} else {
|
||||
const cVal = Number(m.costUsd || 0);
|
||||
patchText(col.costText, m.unpricedCalls > 0 ? formatUsd(cVal, { unpricedCalls: m.unpricedCalls })
|
||||
: cVal >= 10 ? `$${Math.round(cVal)}` : `$${cVal.toFixed(2)}`);
|
||||
patchText(
|
||||
col.costText,
|
||||
m.unpricedCalls > 0
|
||||
? formatUsd(cVal, { unpricedCalls: m.unpricedCalls, compactPending: true })
|
||||
: cVal >= 10
|
||||
? `$${Math.round(cVal)}`
|
||||
: `$${cVal.toFixed(2)}`
|
||||
);
|
||||
patchText(col.tokText, formatTokensPrecise(mTot));
|
||||
|
||||
const totalHeightPct = Math.max(8, Math.min(100, (mTot / maxMonthTokens) * 100));
|
||||
@@ -558,6 +635,7 @@ export const ConsumptionView = defineComponent({
|
||||
customEndMs: st.customEndMs,
|
||||
consumption: st.telemetry?.consumption,
|
||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||
}),
|
||||
(slice) => {
|
||||
latestSlice = slice;
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
* @fileoverview View 1: LiveOverviewView (实时监控视图).
|
||||
* 负责展示当前活跃会话的核心实时遥测指标:
|
||||
* 1. 4 格实时测速矩阵:实时吞吐 (TPS)、首 Token 延迟 (TTFT)、会话有效加权均速与本步费用/缓存命中率;
|
||||
* 2. 6 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`),
|
||||
* 通过 6 段进度条与双列图例展示消息、系统工具、MCP 工具、Skill、系统提示词与用户规则的 Token 占用;
|
||||
* 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon 周配额池、Claude & GPT 等动态配额池,
|
||||
* 2. 10 通道上下文窗口构成:自动锚定当前模型的上下文压缩基线 (`compactionLimitTokens`),
|
||||
* 通过 10 段进度条与双列图例展示模型回复、工具结果、用户消息、子代理通知、压缩摘要及系统提示词/工具/MCP/Skill/规则的 Token 占用;
|
||||
* 3. 动态多配额池监控卡片:支持 Gemini、Pro 订阅专属独立 Argon/Carbon 周配额池、Claude & GPT 等动态配额池,
|
||||
* 自动适配 5h/每周双窗口或单窗口模式,并展示本机周累计消耗与 AI 积分脚标。
|
||||
*/
|
||||
|
||||
@@ -52,6 +52,239 @@ function estPillWidth(text) {
|
||||
return Math.ceil(w);
|
||||
}
|
||||
|
||||
/**
|
||||
* 10 通道上下文窗口构成定义(供实时监控主视图与主窗口顶栏悬停概览卡共享)。
|
||||
*/
|
||||
export const CTX_CHANNEL_DEFS = [
|
||||
{
|
||||
key: 'assistant',
|
||||
label: '模型回复',
|
||||
segClass: 'seg-assistant',
|
||||
title: '模型推理思考、回复正文与工具调用入参',
|
||||
getValue: (c) => Number(c.assistantTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'toolResults',
|
||||
label: '工具结果',
|
||||
segClass: 'seg-tool-results',
|
||||
title: '文件读取、终端输出与工具执行返回内容',
|
||||
getValue: (c) => Number(c.toolResultsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userInput',
|
||||
label: '用户消息',
|
||||
segClass: 'seg-user-input',
|
||||
title: '用户提问文本与上传附件',
|
||||
getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{
|
||||
key: 'subagent',
|
||||
label: '子代理通知',
|
||||
segClass: 'seg-subagent-msg',
|
||||
title: '子代理完成汇报与后台任务系统通知',
|
||||
getValue: (c) => Number(c.subagentTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'checkpoint',
|
||||
label: '压缩摘要',
|
||||
segClass: 'seg-checkpoint',
|
||||
title: '自动上下文压缩生成的历史摘要检查点',
|
||||
getValue: (c) => Number(c.checkpointTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemPrompt',
|
||||
label: '系统提示词',
|
||||
segClass: 'seg-system-prompt',
|
||||
title: '核心身份、终端沙箱、制品与环境提示词',
|
||||
getValue: (c) => Number(c.systemPromptTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemTools',
|
||||
label: '系统工具',
|
||||
segClass: 'seg-system-tools',
|
||||
title: '内置系统工具 Schema 定义',
|
||||
getValue: (c) => Number(c.systemToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'mcpTools',
|
||||
label: 'MCP 工具',
|
||||
segClass: 'seg-mcp-tools',
|
||||
title: 'MCP 外部服务工具与资源定义',
|
||||
getValue: (c) => Number(c.mcpToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'skills',
|
||||
label: 'Skill',
|
||||
segClass: 'seg-skills',
|
||||
title: '已挂载的 Skills 技能索引与说明',
|
||||
getValue: (c) => Number(c.skillsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userRules',
|
||||
label: '用户规则',
|
||||
segClass: 'seg-user-rules',
|
||||
title: '全局与工作区自定义规则 (user_rules)',
|
||||
getValue: (c) => Number(c.userRulesTokens || 0),
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* 归一化动态配额池列表;在官方配额尚未返回时回退预占 Gemini 与 Claude & GPT 两个标准池槽位。
|
||||
*
|
||||
* @param {object|null|undefined} quotas
|
||||
* @param {number} minuteTick
|
||||
* @param {{ isPending?: boolean }} [options]
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function buildQuotaPoolItems(quotas, minuteTick = 0, { isPending = false } = {}) {
|
||||
const safeQuotas = quotas || {};
|
||||
const activePool = safeQuotas.activePool || {};
|
||||
const rawPools =
|
||||
Array.isArray(safeQuotas.pools) && safeQuotas.pools.length > 0
|
||||
? safeQuotas.pools
|
||||
: [
|
||||
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
|
||||
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
|
||||
];
|
||||
const weekly = safeQuotas.weekly || {};
|
||||
const poolItems = rawPools.map((p) => {
|
||||
const key = p.poolKey || p.family || p.poolLabel || 'Other';
|
||||
const poolLabel = p.poolLabel || p.family || key;
|
||||
const isActivePool =
|
||||
Boolean(activePool.family) &&
|
||||
(activePool.poolKey === key ||
|
||||
activePool.family === p.family ||
|
||||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
|
||||
return {
|
||||
key,
|
||||
poolLabel,
|
||||
poolData: p,
|
||||
fallbackWeekly: weekly,
|
||||
isActivePool,
|
||||
minuteTick,
|
||||
isPending,
|
||||
};
|
||||
});
|
||||
if (
|
||||
weekly?.isOfficial === false &&
|
||||
poolItems.length > 0 &&
|
||||
!poolItems.some((item) => item.isActivePool)
|
||||
) {
|
||||
poolItems[0].isActivePool = true;
|
||||
}
|
||||
return poolItems;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
||||
*/
|
||||
export function createPoolQuotaRow() {
|
||||
const title5h = h('span', { text: '5h 限额' });
|
||||
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||
const fill5h = h('div', { className: 'progress-fill' });
|
||||
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header' }, [title5h, meta5h]),
|
||||
h('div', { className: 'progress-track' }, [fill5h]),
|
||||
]);
|
||||
|
||||
const titleWk = h('span', { text: '每周限额' });
|
||||
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||
const fillWk = h('div', { className: 'progress-fill' });
|
||||
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
|
||||
h('div', { className: 'progress-track' }, [fillWk]),
|
||||
]);
|
||||
|
||||
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
|
||||
row5h,
|
||||
rowWk,
|
||||
]);
|
||||
|
||||
return {
|
||||
el,
|
||||
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步单个配额池行的 5h 与每周窗口状态:
|
||||
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
||||
* - 对于仅有 5h 限额的配额池自动隐藏每周行;
|
||||
* - 若两个窗口均无数据(首次加载或拉取失败),同时保留两行以维持预占高度不跳动。
|
||||
*/
|
||||
export function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
||||
const { poolData, poolLabel, fallbackWeekly, isActivePool, isPending } = item;
|
||||
patchAttr(
|
||||
rowEl,
|
||||
'style',
|
||||
idx === 0
|
||||
? 'display: flex; flex-direction: column; gap: 8px;'
|
||||
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
|
||||
);
|
||||
|
||||
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
|
||||
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
|
||||
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
|
||||
|
||||
const useCustomWeekly = Boolean(isActivePool && fallbackWeekly?.isOfficial === false);
|
||||
const wkUsedRaw = useCustomWeekly
|
||||
? fallbackWeekly?.usedPct
|
||||
: poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
|
||||
const wkRemRaw = useCustomWeekly
|
||||
? fallbackWeekly?.remainingPct
|
||||
: poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
|
||||
const wkResetRaw = useCustomWeekly
|
||||
? fallbackWeekly?.resetTime || poolData?.weeklyResetTime
|
||||
: poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
|
||||
const hasWk = wkUsedRaw != null && wkRemRaw != null;
|
||||
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
||||
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
||||
|
||||
// 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口
|
||||
const hide5h = !has5h && hasWk;
|
||||
const hideWk = !hasWk && has5h;
|
||||
refs.row5h.hidden = hide5h;
|
||||
refs.row5h.style.display = hide5h ? 'none' : 'flex';
|
||||
refs.rowWk.hidden = hideWk;
|
||||
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
|
||||
|
||||
const fallbackMetaText = isPending ? '读取中...' : '获取失败 (--%)';
|
||||
|
||||
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
|
||||
patchText(
|
||||
refs.meta5h,
|
||||
has5h
|
||||
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
|
||||
: fallbackMetaText
|
||||
);
|
||||
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
|
||||
patchClasses(refs.fill5h, {
|
||||
'tone-warn': used5hVal >= 60 && used5hVal < 85,
|
||||
'tone-danger': used5hVal >= 85,
|
||||
});
|
||||
|
||||
const customTitle =
|
||||
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
|
||||
? fallbackWeekly.title
|
||||
: `每周限额 (${poolLabel})`;
|
||||
patchText(refs.titleWk, customTitle);
|
||||
patchText(
|
||||
refs.metaWk,
|
||||
hasWk
|
||||
? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)`
|
||||
: fallbackMetaText
|
||||
);
|
||||
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
|
||||
patchClasses(refs.fillWk, {
|
||||
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
|
||||
'tone-danger': usedWkVal >= 85,
|
||||
});
|
||||
}
|
||||
|
||||
export function quotaPoolRowSig(item, idx) {
|
||||
return `${idx}:${item.poolLabel}:${item.isActivePool}:${Boolean(item.isPending)}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.remainingPct}:${item.fallbackWeekly?.resetTime}:${item.fallbackWeekly?.title}`;
|
||||
}
|
||||
|
||||
export const LiveOverviewView = defineComponent({
|
||||
name: 'LiveOverviewView',
|
||||
setup({ onCleanup }) {
|
||||
@@ -65,6 +298,7 @@ export const LiveOverviewView = defineComponent({
|
||||
const expandedTaskConvIds = new Set();
|
||||
const activityTimersMap = new Map();
|
||||
let liveTickTimer = null;
|
||||
let countdownTickTimer = null;
|
||||
|
||||
function bindLiveElapsedTimer(timerKey, sig, rawStartMs, targetEl) {
|
||||
const now = Date.now();
|
||||
@@ -90,22 +324,51 @@ export const LiveOverviewView = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
function stopLiveTicker() {
|
||||
function pauseLiveTicker() {
|
||||
if (liveTickTimer) {
|
||||
clearInterval(liveTickTimer);
|
||||
liveTickTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function stopLiveTicker() {
|
||||
pauseLiveTicker();
|
||||
activityTimersMap.clear();
|
||||
}
|
||||
|
||||
function ensureLiveTicker() {
|
||||
if (uiStore.getState().activeView !== 'overview' || activityTimersMap.size === 0) {
|
||||
pauseLiveTicker();
|
||||
return;
|
||||
}
|
||||
if (!liveTickTimer) {
|
||||
liveTickTimer = setInterval(updateLiveElapsedDisplay, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
function stopCountdownTicker() {
|
||||
if (countdownTickTimer) {
|
||||
clearInterval(countdownTickTimer);
|
||||
countdownTickTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureCountdownTicker() {
|
||||
if (uiStore.getState().activeView !== 'overview') {
|
||||
stopCountdownTicker();
|
||||
return;
|
||||
}
|
||||
if (!countdownTickTimer) {
|
||||
countdownTickTimer = setInterval(() => {
|
||||
if (uiStore.getState().activeView === 'overview' && latestData) {
|
||||
renderData(latestData);
|
||||
}
|
||||
}, 30_000);
|
||||
}
|
||||
}
|
||||
|
||||
function createLiveTaskCard() {
|
||||
const dotIcon = createSvgIcon('dot', { size: 9 });
|
||||
const dotIcon = createSvgIcon('dot', { size: 11 });
|
||||
patchClasses(dotIcon, { 'is-pulsing': true });
|
||||
const dotWrap = h('span', { className: 'live-activity-dot' }, [dotIcon]);
|
||||
const titleEl = h('strong', { className: 'live-task-title', text: '当前会话' });
|
||||
@@ -125,7 +388,11 @@ export const LiveOverviewView = defineComponent({
|
||||
h('div', { className: 'live-task-header-right' }, [subToggleBtn, elapsedEl]),
|
||||
]);
|
||||
|
||||
const mainBadge = h('span', { className: 'agent-badge badge-main', text: '主' });
|
||||
const mainBadge = h('span', {
|
||||
className: 'agent-badge badge-main',
|
||||
hidden: true,
|
||||
text: '主',
|
||||
});
|
||||
const mainPhase = h('strong', { className: 'live-activity-phase', text: '推理中' });
|
||||
const mainProgress = h('span', {
|
||||
className: 'live-activity-progress text-mono',
|
||||
@@ -158,6 +425,7 @@ export const LiveOverviewView = defineComponent({
|
||||
titleEl,
|
||||
subToggleBtn,
|
||||
elapsedEl,
|
||||
mainBadge,
|
||||
mainPhase,
|
||||
mainProgress,
|
||||
mainSep,
|
||||
@@ -205,7 +473,7 @@ export const LiveOverviewView = defineComponent({
|
||||
const avgVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const avgSub = h('span', { className: 'cell-sub', text: '有效样本 0/0 步' });
|
||||
|
||||
const costVal = h('strong', { className: 'cell-value', text: '$0.000' });
|
||||
const costVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const cacheSub = h('span', { className: 'cell-sub accent-ok', text: '缓存 0% · 累计 $0.00' });
|
||||
|
||||
const matrixEl = h('section', { className: 'telemetry-matrix', 'aria-label': '实时指标' }, [
|
||||
@@ -256,78 +524,7 @@ export const LiveOverviewView = defineComponent({
|
||||
[ctxPillGroup]
|
||||
);
|
||||
|
||||
const ctxChannels = [
|
||||
{
|
||||
key: 'assistant',
|
||||
label: '模型回复',
|
||||
segClass: 'seg-assistant',
|
||||
title: '模型推理思考、回复正文与工具调用入参',
|
||||
getValue: (c) => Number(c.assistantTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'toolResults',
|
||||
label: '工具结果',
|
||||
segClass: 'seg-tool-results',
|
||||
title: '文件读取、终端输出与工具执行返回内容',
|
||||
getValue: (c) => Number(c.toolResultsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userInput',
|
||||
label: '用户消息',
|
||||
segClass: 'seg-user-input',
|
||||
title: '用户提问文本与上传附件',
|
||||
getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{
|
||||
key: 'subagent',
|
||||
label: '子代理通知',
|
||||
segClass: 'seg-subagent-msg',
|
||||
title: '子代理完成汇报与后台任务系统通知',
|
||||
getValue: (c) => Number(c.subagentTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'checkpoint',
|
||||
label: '压缩摘要',
|
||||
segClass: 'seg-checkpoint',
|
||||
title: '自动上下文压缩生成的历史摘要检查点',
|
||||
getValue: (c) => Number(c.checkpointTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemPrompt',
|
||||
label: '系统提示词',
|
||||
segClass: 'seg-system-prompt',
|
||||
title: '核心身份、终端沙箱、制品与环境提示词',
|
||||
getValue: (c) => Number(c.systemPromptTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemTools',
|
||||
label: '系统工具',
|
||||
segClass: 'seg-system-tools',
|
||||
title: '内置系统工具 Schema 定义',
|
||||
getValue: (c) => Number(c.systemToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'mcpTools',
|
||||
label: 'MCP 工具',
|
||||
segClass: 'seg-mcp-tools',
|
||||
title: 'MCP 外部服务工具与资源定义',
|
||||
getValue: (c) => Number(c.mcpToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'skills',
|
||||
label: 'Skill',
|
||||
segClass: 'seg-skills',
|
||||
title: '已挂载的 Skills 技能索引与说明',
|
||||
getValue: (c) => Number(c.skillsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userRules',
|
||||
label: '用户规则',
|
||||
segClass: 'seg-user-rules',
|
||||
title: '全局与工作区自定义规则 (user_rules)',
|
||||
getValue: (c) => Number(c.userRulesTokens || 0),
|
||||
},
|
||||
].map((ch, idx) => {
|
||||
const ctxChannels = CTX_CHANNEL_DEFS.map((ch, idx) => {
|
||||
const valEl = h('strong', { className: 'text-mono', text: '0' });
|
||||
const itemEl = h('div', { className: 'legend-item', title: ch.title }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
@@ -364,37 +561,6 @@ export const LiveOverviewView = defineComponent({
|
||||
const tierBadge = h('span', { className: 'panel-meta', text: 'Google AI · Pro' });
|
||||
const poolsListEl = h('div', { style: 'display: flex; flex-direction: column; gap: 0;' });
|
||||
|
||||
/**
|
||||
* 创建单个配额池的 DOM 行结构,内含 5h 限额与每周限额两个可独立显隐的子窗口进度条。
|
||||
*/
|
||||
function createPoolQuotaRow() {
|
||||
const title5h = h('span', { text: '5h 限额' });
|
||||
const meta5h = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||
const fill5h = h('div', { className: 'progress-fill' });
|
||||
const row5h = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header' }, [title5h, meta5h]),
|
||||
h('div', { className: 'progress-track' }, [fill5h]),
|
||||
]);
|
||||
|
||||
const titleWk = h('span', { text: '每周限额' });
|
||||
const metaWk = h('span', { className: 'panel-meta text-mono', text: '--' });
|
||||
const fillWk = h('div', { className: 'progress-fill' });
|
||||
const rowWk = h('div', { style: 'display: flex; flex-direction: column; gap: 4px;' }, [
|
||||
h('div', { className: 'panel-header' }, [titleWk, metaWk]),
|
||||
h('div', { className: 'progress-track' }, [fillWk]),
|
||||
]);
|
||||
|
||||
const el = h('div', { style: 'display: flex; flex-direction: column; gap: 8px;' }, [
|
||||
row5h,
|
||||
rowWk,
|
||||
]);
|
||||
|
||||
return {
|
||||
el,
|
||||
refs: { row5h, title5h, meta5h, fill5h, rowWk, titleWk, metaWk, fillWk },
|
||||
};
|
||||
}
|
||||
|
||||
const wkFootLeft = h('span', { className: 'text-muted', text: '本周累计: 0 ($0.00)' });
|
||||
const wkFootRight = h('span', { className: 'text-muted', text: '' });
|
||||
|
||||
@@ -425,75 +591,6 @@ export const LiveOverviewView = defineComponent({
|
||||
className: 'view-pane',
|
||||
});
|
||||
|
||||
/**
|
||||
* 同步单个配额池行的 5h 与每周窗口状态:
|
||||
* - 对于仅有周限额的独立配额池(例如 Google AI Pro 账号下的 Argon 池或 Plus 档位)自动隐藏 5h 行;
|
||||
* - 对于仅有 5h 限额的配额池自动隐藏每周行;
|
||||
* - 若两个窗口均无数据(如首次拉取失败),则同时保留两行并显示“获取失败 (--%)”占位提示。
|
||||
*/
|
||||
function syncPoolQuotaRow(refs, item, idx, rowEl) {
|
||||
const { poolData, poolLabel, fallbackWeekly, isActivePool } = item;
|
||||
patchAttr(
|
||||
rowEl,
|
||||
'style',
|
||||
idx === 0
|
||||
? 'display: flex; flex-direction: column; gap: 8px;'
|
||||
: 'display: flex; flex-direction: column; gap: 8px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border-hairline);'
|
||||
);
|
||||
|
||||
const has5h = poolData?.usedPct != null && poolData?.remainingPct != null;
|
||||
const used5hVal = has5h ? Number(poolData.usedPct) : 0;
|
||||
const rem5hVal = has5h ? Number(poolData.remainingPct) : 0;
|
||||
|
||||
const wkUsedRaw =
|
||||
poolData?.weeklyUsedPct ?? (isActivePool ? fallbackWeekly?.usedPct : null);
|
||||
const wkRemRaw =
|
||||
poolData?.weeklyRemainingPct ?? (isActivePool ? fallbackWeekly?.remainingPct : null);
|
||||
const wkResetRaw =
|
||||
poolData?.weeklyResetTime || (isActivePool ? fallbackWeekly?.resetTime : null);
|
||||
const hasWk = wkUsedRaw != null && wkRemRaw != null;
|
||||
const usedWkVal = hasWk ? Number(wkUsedRaw) : 0;
|
||||
const remWkVal = hasWk ? Number(wkRemRaw) : 0;
|
||||
|
||||
// 在单窗口配额池(如 Pro 账号独立 Argon 周配额池或仅 5h 池)中隐藏不适用的另一窗口
|
||||
const hide5h = !has5h && hasWk;
|
||||
const hideWk = !hasWk && has5h;
|
||||
refs.row5h.hidden = hide5h;
|
||||
refs.row5h.style.display = hide5h ? 'none' : 'flex';
|
||||
refs.rowWk.hidden = hideWk;
|
||||
refs.rowWk.style.display = hideWk ? 'none' : 'flex';
|
||||
|
||||
patchText(refs.title5h, `5h 限额 (${poolLabel})`);
|
||||
patchText(
|
||||
refs.meta5h,
|
||||
has5h
|
||||
? `${formatCountdown(poolData.resetTime)} · 已用 ${used5hVal.toFixed(1)}% (余 ${rem5hVal.toFixed(1)}%)`
|
||||
: '获取失败 (--%)'
|
||||
);
|
||||
patchStyleVar(refs.fill5h, '--fill-w', `${Math.min(100, used5hVal)}%`);
|
||||
patchClasses(refs.fill5h, {
|
||||
'tone-warn': used5hVal >= 60 && used5hVal < 85,
|
||||
'tone-danger': used5hVal >= 85,
|
||||
});
|
||||
|
||||
const customTitle =
|
||||
isActivePool && fallbackWeekly?.isOfficial === false && fallbackWeekly?.title
|
||||
? fallbackWeekly.title
|
||||
: `每周限额 (${poolLabel})`;
|
||||
patchText(refs.titleWk, customTitle);
|
||||
patchText(
|
||||
refs.metaWk,
|
||||
hasWk
|
||||
? `${formatCountdown(wkResetRaw)} · 已用 ${usedWkVal.toFixed(1)}% (余 ${remWkVal.toFixed(1)}%)`
|
||||
: '获取失败 (--%)'
|
||||
);
|
||||
patchStyleVar(refs.fillWk, '--fill-w', `${Math.min(100, usedWkVal)}%`);
|
||||
patchClasses(refs.fillWk, {
|
||||
'tone-warn': usedWkVal >= 60 && usedWkVal < 85,
|
||||
'tone-danger': usedWkVal >= 85,
|
||||
});
|
||||
}
|
||||
|
||||
let latestData = null;
|
||||
let isDirty = false;
|
||||
let ctxPillsExpanded = false;
|
||||
@@ -605,10 +702,10 @@ export const LiveOverviewView = defineComponent({
|
||||
const subSig = (item.subagents || [])
|
||||
.map(
|
||||
(s) =>
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}`
|
||||
`${s.cascadeId}:${s.isRunning}:${s.stepCount}:${s.liveActivity?.signature || ''}:${s.liveActivity?.startedAtMs || 0}`
|
||||
)
|
||||
.join('|');
|
||||
return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${subSig}`;
|
||||
return `${item.cascadeId}:${item.title}:${item.isMainRunning}:${item.subagentCount}:${item.runningSubagentCount}:${isExp}:${item.mainActivity?.signature || ''}:${item.mainActivity?.startedAtMs || 0}:${subSig}`;
|
||||
},
|
||||
createRow: createLiveTaskCard,
|
||||
updateRow: (refs, item) => {
|
||||
@@ -622,7 +719,11 @@ export const LiveOverviewView = defineComponent({
|
||||
};
|
||||
|
||||
const isWaiting = act.phase === 'waiting';
|
||||
patchClasses(refs.cardEl, { 'is-waiting': isWaiting });
|
||||
const isCompacting = act.phase === 'compacting';
|
||||
patchClasses(refs.cardEl, {
|
||||
'is-waiting': isWaiting,
|
||||
'is-compacting': isCompacting,
|
||||
});
|
||||
patchClasses(refs.dotIcon, { 'is-pulsing': true });
|
||||
|
||||
const convTitle = item.title || item.cascadeId?.slice(0, 8) || '当前会话';
|
||||
@@ -639,6 +740,7 @@ export const LiveOverviewView = defineComponent({
|
||||
const subCount = Number(item.subagentCount || item.subagents?.length || 0);
|
||||
const runSubCount = Number(item.runningSubagentCount || 0);
|
||||
const isExpanded = expandedTaskConvIds.has(item.cascadeId);
|
||||
patchAttr(refs.mainBadge, 'hidden', subCount === 0);
|
||||
patchAttr(refs.subToggleBtn, 'hidden', subCount === 0);
|
||||
if (subCount > 0) {
|
||||
const arrow = isExpanded ? '▾' : '▸';
|
||||
@@ -758,14 +860,19 @@ export const LiveOverviewView = defineComponent({
|
||||
ensureLiveTicker();
|
||||
}
|
||||
|
||||
// 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标)
|
||||
// 1. 更新 4 格实时测速矩阵(展示当前会话全局汇总指标,遵循模型名称格式设置)
|
||||
const showUpstream = Boolean(data.settings?.showUpstreamModel);
|
||||
const activeModelDisplay =
|
||||
(showUpstream
|
||||
? active.activeModelUpstream || active.activeModelShort
|
||||
: active.activeModelShort) || '模型未知';
|
||||
patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) });
|
||||
patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s'));
|
||||
const reason = speedReasonText(active.latestSpeedReason);
|
||||
const modelAndAgent =
|
||||
hasSubagents && active.activeAgentBadge
|
||||
? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}`
|
||||
: active.activeModelShort || '模型未知';
|
||||
? `[${active.activeAgentBadge}] ${activeModelDisplay}`
|
||||
: activeModelDisplay;
|
||||
patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent);
|
||||
|
||||
patchText(ttftVal, formatMetric(active.latestTtftSec, 's'));
|
||||
@@ -775,7 +882,11 @@ export const LiveOverviewView = defineComponent({
|
||||
patchText(avgSub, `有效 ${sampleSummary(active.speedSummary)}`);
|
||||
|
||||
const stepCost = active.latestStepCostUsd;
|
||||
patchText(costVal, formatUsd(stepCost, { precise: true }));
|
||||
const hasAnySteps = Number(active.stepCount || 0) > 0;
|
||||
patchText(
|
||||
costVal,
|
||||
!hasAnySteps && stepCost == null ? '—' : formatUsd(stepCost, { precise: true })
|
||||
);
|
||||
patchText(
|
||||
cacheSub,
|
||||
`缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}`
|
||||
@@ -803,10 +914,13 @@ export const LiveOverviewView = defineComponent({
|
||||
|
||||
const allAgentPills = agents.map((ag) => {
|
||||
const agPct = ag.context?.usedPct ?? 0;
|
||||
const agModelDisplay =
|
||||
(showUpstream ? ag.activeModelUpstream || ag.activeModelShort : ag.activeModelShort) ||
|
||||
'模型未知';
|
||||
return {
|
||||
key: ag.agentId,
|
||||
label: `${ag.badgeText || ag.shortLabel} ${agPct}%`,
|
||||
title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`,
|
||||
title: `${formatAgentLabel(ag)} (${agModelDisplay} · ${ag.stepCount || 0}步)`,
|
||||
isActive: effectiveCtxScope === ag.agentId,
|
||||
mode: 'ctx-only',
|
||||
};
|
||||
@@ -888,12 +1002,8 @@ export const LiveOverviewView = defineComponent({
|
||||
if (item.mode === 'toggle-expand') {
|
||||
ctxPillsExpanded = !ctxPillsExpanded;
|
||||
renderData(latestData);
|
||||
} else if (item.mode === 'ctx-only') {
|
||||
uiStore.setState({ ctxInspectorAgentId: item.key });
|
||||
} else if (item.key === 'all') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
} else {
|
||||
uiStore.setState({ selectedAgentScope: item.key });
|
||||
uiStore.setState({ ctxInspectorAgentId: item.key });
|
||||
}
|
||||
};
|
||||
},
|
||||
@@ -928,37 +1038,13 @@ export const LiveOverviewView = defineComponent({
|
||||
tierBadge,
|
||||
`${data.account?.tierName || 'Google AI'} · ${data.account?.planName || 'Pro'}`
|
||||
);
|
||||
const activePool = quotas.activePool || {};
|
||||
const rawPools = Array.isArray(quotas.pools) && quotas.pools.length > 0
|
||||
? quotas.pools
|
||||
: [
|
||||
{ poolKey: 'Gemini', poolLabel: 'Gemini', family: 'Gemini' },
|
||||
{ poolKey: 'Claude & GPT', poolLabel: 'Claude & GPT', family: 'Claude & GPT' },
|
||||
];
|
||||
const weekly = quotas.weekly || {};
|
||||
const minuteTick = Math.floor(Date.now() / 30000);
|
||||
const poolItems = rawPools.map((p) => {
|
||||
const key = p.poolKey || p.family || p.poolLabel || 'Other';
|
||||
const poolLabel = p.poolLabel || p.family || key;
|
||||
const isActivePool =
|
||||
Boolean(activePool.family) &&
|
||||
(activePool.poolKey === key ||
|
||||
activePool.family === p.family ||
|
||||
(key === 'Claude & GPT' && ['Claude', 'GPT'].includes(activePool.family)));
|
||||
return {
|
||||
key,
|
||||
poolLabel,
|
||||
poolData: p,
|
||||
fallbackWeekly: weekly,
|
||||
isActivePool,
|
||||
minuteTick,
|
||||
};
|
||||
});
|
||||
const poolItems = buildQuotaPoolItems(quotas, minuteTick);
|
||||
|
||||
patchKeyedList(poolsListEl, poolItems, {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: (item, idx) =>
|
||||
`${idx}:${item.poolLabel}:${item.isActivePool}:${item.minuteTick}:${item.poolData?.usedPct}:${item.poolData?.remainingPct}:${item.poolData?.resetTime}:${item.poolData?.weeklyUsedPct}:${item.poolData?.weeklyRemainingPct}:${item.poolData?.weeklyResetTime}:${item.fallbackWeekly?.isOfficial}:${item.fallbackWeekly?.usedPct}:${item.fallbackWeekly?.title}`,
|
||||
sigFn: quotaPoolRowSig,
|
||||
createRow: createPoolQuotaRow,
|
||||
updateRow: syncPoolQuotaRow,
|
||||
});
|
||||
@@ -974,12 +1060,13 @@ export const LiveOverviewView = defineComponent({
|
||||
: `本周调用: ${weekly.calls || 0} 次`
|
||||
);
|
||||
|
||||
ensureCountdownTicker();
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
|
||||
const unsub = telemetryStore.subscribe(
|
||||
(st) => st.telemetry,
|
||||
(data) => {
|
||||
(st) => ({ telemetry: st.telemetry, minuteTick: st.minuteTick }),
|
||||
({ telemetry: data }) => {
|
||||
latestData = data;
|
||||
if (uiStore.getState().activeView !== 'overview') {
|
||||
const stillRunning =
|
||||
@@ -1011,12 +1098,18 @@ export const LiveOverviewView = defineComponent({
|
||||
prevCtxTarget = slice.ctxInspectorAgentId;
|
||||
|
||||
if (slice.activeView !== 'overview') {
|
||||
pauseLiveTicker();
|
||||
stopCountdownTicker();
|
||||
if (scopeChanged) isDirty = true;
|
||||
return;
|
||||
}
|
||||
ensureCountdownTicker();
|
||||
if ((isDirty || scopeChanged) && latestData) {
|
||||
isDirty = false;
|
||||
renderData(latestData);
|
||||
} else if (activityTimersMap.size > 0) {
|
||||
updateLiveElapsedDisplay();
|
||||
ensureLiveTicker();
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -1039,6 +1132,7 @@ export const LiveOverviewView = defineComponent({
|
||||
|
||||
onCleanup(() => {
|
||||
stopLiveTicker();
|
||||
stopCountdownTicker();
|
||||
unsub();
|
||||
unsubView();
|
||||
if (ro) ro.disconnect();
|
||||
|
||||
@@ -1,29 +1,26 @@
|
||||
/**
|
||||
* @fileoverview View 4: SettingsView (系统设置视图).
|
||||
* 采用定制的 `CustomSelect` 与 `CustomNumberInput` 替代所有原生表单控件,分为两个设置面板:
|
||||
* 1. 本地配额监控与预算表单:配置模型名称显示方式(内部代号/实际模型名)、周用量计算模式及自定义 Token/USD 预算;
|
||||
* 2. 云端价格同步与插件更新面板:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||
* 采用定制的 `CustomSelect` 与 `SegmentedControl` 替代所有原生表单控件,分为三个单层细线设置面板:
|
||||
* 1. 常规设置:配置面板挂载方式(双栖挂载 / 仅右侧辅助栏)与模型名称格式(精简代号 / 原始模型 ID);
|
||||
* 2. 顶部栏定制:控制左侧「实时运行会话」入口开关,以及自由定义右侧精简胶囊三个数值槽位的显示内容与左右顺序;
|
||||
* 3. 版本更新:配置插件自动更新策略、手动同步云端模型价格表,以及检查并执行 Git/ZIP 双模式插件升级。
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../core/domPatch.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import {
|
||||
DEFAULT_CLIENT_TOPBAR_SLOTS,
|
||||
normalizeClientTopbarSlots,
|
||||
saveSettingsPatch,
|
||||
telemetryStore,
|
||||
triggerCloudSync,
|
||||
triggerPluginUpdate,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { CustomNumberInput } from '../components/ui/CustomNumberInput.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
|
||||
/** 每周配额计算模式可选项 */
|
||||
const WEEKLY_MODE_OPTIONS = [
|
||||
{ value: 'official', label: '跟随官方额度' },
|
||||
{ value: 'custom_tokens', label: '自定义 Token 上限' },
|
||||
{ value: 'custom_cost', label: '自定义费用上限 (USD)' },
|
||||
];
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
|
||||
/** 步骤明细表中的模型名称显示方式可选项 */
|
||||
const STEP_MODEL_DISPLAY_OPTIONS = [
|
||||
@@ -31,6 +28,32 @@ const STEP_MODEL_DISPLAY_OPTIONS = [
|
||||
{ value: 'upstream', label: '原始模型 ID (如 gemini-3.8-flash-n)' },
|
||||
];
|
||||
|
||||
/** 面板挂载模式可选项(顶部栏 + 侧边栏 vs 仅侧边栏) */
|
||||
const WINDOW_MOUNT_OPTIONS = [
|
||||
{ value: 'dual', label: '双栖挂载 (顶部栏 + 侧边栏)' },
|
||||
{ value: 'sidebar', label: '仅侧边栏' },
|
||||
];
|
||||
|
||||
/** 顶栏左侧实时运行会话入口显隐选项 */
|
||||
const TOPBAR_MULTI_TOGGLE_OPTIONS = [
|
||||
{ value: 'show', label: '显示' },
|
||||
{ value: 'hide', label: '隐藏' },
|
||||
];
|
||||
|
||||
/** 顶栏右侧精简胶囊三槽位可选指标项 */
|
||||
const TOPBAR_SLOT_OPTIONS = [
|
||||
{ value: 'context', label: '上下文占用 (%)' },
|
||||
{ value: 'tps', label: '输出速度 (TPS)' },
|
||||
{ value: 'ttft', label: '首字延迟 (TTFT)' },
|
||||
{ value: 'cost', label: '本次费用 ($)' },
|
||||
{ value: 'quota_auto', label: '自动紧俏额度' },
|
||||
{ value: 'gemini_5h', label: 'Gemini 5h 额度' },
|
||||
{ value: 'gemini_weekly', label: 'Gemini 周额度' },
|
||||
{ value: 'claude_5h', label: 'Claude 5h 额度' },
|
||||
{ value: 'claude_weekly', label: 'Claude 周额度' },
|
||||
{ value: 'none', label: '不显示' },
|
||||
];
|
||||
|
||||
/** 插件版本更新策略可选项 */
|
||||
const AUTO_UPDATE_OPTIONS = [
|
||||
{ value: 'manual', label: '仅提示新版本,手动更新 (推荐)' },
|
||||
@@ -55,20 +78,20 @@ function formatSyncTimeText(tsMs, updatedAt) {
|
||||
export const SettingsView = defineComponent({
|
||||
name: 'SettingsView',
|
||||
setup({ onCleanup }) {
|
||||
// --- 面板 1:本地配额监控与预算表单状态与控件 ---
|
||||
let draftMode = 'official';
|
||||
let draftTokens = 150000000;
|
||||
let draftCost = 100;
|
||||
let draftShowUpstreamModel = false;
|
||||
let draftAutoUpdatePlugin = false;
|
||||
let draftEnableWindowOverlay = true;
|
||||
let draftShowTopbarMulti = true;
|
||||
let draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
let statusTimer = null;
|
||||
let topbarTimer = null;
|
||||
let cloudTimer = null;
|
||||
let lastSyncedSettingsSig = '';
|
||||
|
||||
const saveStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const topbarStatusText = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
const cloudStatusMsg = h('span', { className: 'text-muted', style: 'font-size: 11px;', text: '' });
|
||||
|
||||
/** 在本地预算面板右上角展示短暂的保存状态提示 */
|
||||
/** 在常规设置面板右上角展示短暂的保存状态提示 */
|
||||
function showSaveFeedback(text) {
|
||||
if (statusTimer) {
|
||||
clearTimeout(statusTimer);
|
||||
@@ -83,6 +106,21 @@ export const SettingsView = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
/** 在顶部栏定制面板右上角展示短暂的状态提示 */
|
||||
function showTopbarFeedback(text, autoClearMs = 1500) {
|
||||
if (topbarTimer) {
|
||||
clearTimeout(topbarTimer);
|
||||
topbarTimer = null;
|
||||
}
|
||||
patchText(topbarStatusText, text);
|
||||
if (autoClearMs > 0) {
|
||||
topbarTimer = setTimeout(() => {
|
||||
topbarTimer = null;
|
||||
patchText(topbarStatusText, '');
|
||||
}, autoClearMs);
|
||||
}
|
||||
}
|
||||
|
||||
/** 在云端同步面板右上角展示同步或更新进度提示 */
|
||||
function showCloudFeedback(text, autoClearMs = 3500) {
|
||||
if (cloudTimer) {
|
||||
@@ -98,110 +136,54 @@ export const SettingsView = defineComponent({
|
||||
}
|
||||
}
|
||||
|
||||
const modeSelect = CustomSelect({
|
||||
modelValue: draftMode,
|
||||
icon: 'sliders',
|
||||
options: WEEKLY_MODE_OPTIONS,
|
||||
onUpdateModelValue: (val) => {
|
||||
draftMode = val;
|
||||
},
|
||||
});
|
||||
|
||||
// 模型名显示方式切换后立即持久化并刷新遥测数据
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
options: STEP_MODEL_DISPLAY_OPTIONS,
|
||||
// --- 面板 1:常规设置 ---
|
||||
const windowMountSelect = CustomSelect({
|
||||
modelValue: 'dual',
|
||||
icon: 'dock',
|
||||
options: WINDOW_MOUNT_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
draftShowUpstreamModel = val === 'upstream';
|
||||
if (latestSettings) {
|
||||
lastSyncedSettingsSig = settingsSig({
|
||||
...latestSettings,
|
||||
showUpstreamModel: draftShowUpstreamModel,
|
||||
});
|
||||
}
|
||||
const nextEnable = val !== 'sidebar';
|
||||
draftEnableWindowOverlay = nextEnable;
|
||||
windowMountSelect.setValue(nextEnable ? 'dual' : 'sidebar');
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showUpstreamModel: draftShowUpstreamModel,
|
||||
enableWindowOverlay: nextEnable,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
// 插件自动更新策略切换后立即保存至后端
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: AUTO_UPDATE_OPTIONS,
|
||||
const stepModelSelect = CustomSelect({
|
||||
modelValue: 'short',
|
||||
icon: 'table',
|
||||
options: STEP_MODEL_DISPLAY_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
draftAutoUpdatePlugin = val === 'auto';
|
||||
if (latestSettings) {
|
||||
lastSyncedSettingsSig = settingsSig({
|
||||
...latestSettings,
|
||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
||||
});
|
||||
}
|
||||
showCloudFeedback('保存中…', 0);
|
||||
const nextUpstream = val === 'upstream';
|
||||
draftShowUpstreamModel = nextUpstream;
|
||||
stepModelSelect.setValue(nextUpstream ? 'upstream' : 'short');
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
||||
showUpstreamModel: nextUpstream,
|
||||
});
|
||||
showCloudFeedback('已保存', 1800);
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
showCloudFeedback('保存失败', 2500);
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const tokenBudgetInput = CustomNumberInput({
|
||||
modelValue: draftTokens,
|
||||
min: 100000,
|
||||
max: 10000000000,
|
||||
step: 1000000,
|
||||
onUpdateModelValue: (val) => {
|
||||
draftTokens = val;
|
||||
},
|
||||
});
|
||||
|
||||
const costBudgetInput = CustomNumberInput({
|
||||
modelValue: draftCost,
|
||||
min: 1,
|
||||
max: 100000,
|
||||
step: 5,
|
||||
onUpdateModelValue: (val) => {
|
||||
draftCost = val;
|
||||
},
|
||||
});
|
||||
|
||||
const saveBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-primary',
|
||||
onClick: async () => {
|
||||
showSaveFeedback('保存中…');
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
weeklyLimitMode: draftMode,
|
||||
weeklyTokenBudget: draftTokens,
|
||||
weeklyCostBudget: draftCost,
|
||||
showUpstreamModel: draftShowUpstreamModel,
|
||||
autoUpdatePlugin: draftAutoUpdatePlugin,
|
||||
});
|
||||
showSaveFeedback('已保存');
|
||||
} catch {
|
||||
showSaveFeedback('保存失败');
|
||||
}
|
||||
},
|
||||
},
|
||||
[createSvgIcon('check', { size: 13 }), h('span', { text: '保存设置' })]
|
||||
);
|
||||
|
||||
const budgetPanel = h('section', { className: 'panel' }, [
|
||||
const generalPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('sliders', { size: 13 }),
|
||||
@@ -209,31 +191,211 @@ export const SettingsView = defineComponent({
|
||||
]),
|
||||
saveStatusText,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '面板挂载方式' }),
|
||||
windowMountSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '模型名称格式' }),
|
||||
stepModelSelect.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '周额度基准' }),
|
||||
modeSelect.el,
|
||||
]),
|
||||
h('div', { className: 'dual-grid' }, [
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '每周 Token 上限' }),
|
||||
tokenBudgetInput.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '每周费用上限 ($)' }),
|
||||
costBudgetInput.el,
|
||||
]),
|
||||
]),
|
||||
h('div', { style: 'display: flex; justify-content: flex-end;' }, [saveBtn]),
|
||||
]);
|
||||
|
||||
// --- 面板 2:版本更新面板 ---
|
||||
// --- 面板 2:顶部栏定制(实时运行会话开关 + 右侧三槽位指标与顺序自定义) ---
|
||||
const multiSessionToggle = SegmentedControl({
|
||||
ariaLabel: '实时运行会话开关',
|
||||
modelValue: 'show',
|
||||
options: TOPBAR_MULTI_TOGGLE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextShow = val !== 'hide';
|
||||
draftShowTopbarMulti = nextShow;
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showTopbarMultiSession: nextShow,
|
||||
});
|
||||
showTopbarFeedback('已保存', 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function persistTopbarSlots(nextRawSlots, noticeText = '') {
|
||||
const normalized = normalizeClientTopbarSlots(nextRawSlots);
|
||||
draftTopbarSlots = normalized;
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback(noticeText || '保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
topbarCapsuleSlots: normalized,
|
||||
});
|
||||
showTopbarFeedback(noticeText || '已保存', noticeText ? 2000 : 1500);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
}
|
||||
|
||||
function handleSlotMetricChange(slotIndex, nextVal) {
|
||||
const candidate = [...draftTopbarSlots];
|
||||
candidate[slotIndex] = nextVal;
|
||||
const wouldAllBeHidden = candidate.every((item) => item === 'none');
|
||||
void persistTopbarSlots(
|
||||
candidate,
|
||||
wouldAllBeHidden ? '至少保留 1 项显示' : ''
|
||||
);
|
||||
}
|
||||
|
||||
function swapTopbarSlots(idxA, idxB) {
|
||||
if (idxA < 0 || idxA > 2 || idxB < 0 || idxB > 2 || idxA === idxB) return;
|
||||
const candidate = [...draftTopbarSlots];
|
||||
const temp = candidate[idxA];
|
||||
candidate[idxA] = candidate[idxB];
|
||||
candidate[idxB] = temp;
|
||||
void persistTopbarSlots(candidate);
|
||||
}
|
||||
|
||||
const slotSelects = [0, 1, 2].map((idx) =>
|
||||
CustomSelect({
|
||||
modelValue: draftTopbarSlots[idx],
|
||||
options: TOPBAR_SLOT_OPTIONS,
|
||||
onUpdateModelValue: (val) => handleSlotMetricChange(idx, val),
|
||||
})
|
||||
);
|
||||
|
||||
const slotRows = [0, 1, 2].map((idx) => {
|
||||
const upBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
disabled: idx === 0,
|
||||
'aria-label': `槽位 ${idx + 1} 左移`,
|
||||
title: idx === 0 ? '已在最左' : '上移 (在顶栏靠左)',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
swapTopbarSlots(idx, idx - 1);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-up', { size: 12 })]
|
||||
);
|
||||
|
||||
const downBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'slot-move-btn',
|
||||
disabled: idx === 2,
|
||||
'aria-label': `槽位 ${idx + 1} 右移`,
|
||||
title: idx === 2 ? '已在最右' : '下移 (在顶栏靠右)',
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
swapTopbarSlots(idx, idx + 1);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('chevron-down', { size: 12 })]
|
||||
);
|
||||
|
||||
return h('div', { className: 'topbar-slot-row', 'data-slot-row': String(idx) }, [
|
||||
h('span', { className: 'slot-index-badge', text: String(idx + 1) }),
|
||||
slotSelects[idx].el,
|
||||
h('span', { className: 'slot-order-btns' }, [upBtn, downBtn]),
|
||||
]);
|
||||
});
|
||||
|
||||
const resetTopbarBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-ghost-sm',
|
||||
disabled: true,
|
||||
onClick: async () => {
|
||||
draftShowTopbarMulti = true;
|
||||
draftTopbarSlots = [...DEFAULT_CLIENT_TOPBAR_SLOTS];
|
||||
syncTopbarControls();
|
||||
showTopbarFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
showTopbarMultiSession: true,
|
||||
topbarCapsuleSlots: [...DEFAULT_CLIENT_TOPBAR_SLOTS],
|
||||
});
|
||||
showTopbarFeedback('已恢复默认', 1600);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showTopbarFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
},
|
||||
[h('span', { text: '恢复默认' })]
|
||||
);
|
||||
|
||||
function syncTopbarControls() {
|
||||
multiSessionToggle.setValue(draftShowTopbarMulti ? 'show' : 'hide');
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
slotSelects[i].setValue(draftTopbarSlots[i]);
|
||||
}
|
||||
const isDefault =
|
||||
draftShowTopbarMulti === true &&
|
||||
draftTopbarSlots[0] === DEFAULT_CLIENT_TOPBAR_SLOTS[0] &&
|
||||
draftTopbarSlots[1] === DEFAULT_CLIENT_TOPBAR_SLOTS[1] &&
|
||||
draftTopbarSlots[2] === DEFAULT_CLIENT_TOPBAR_SLOTS[2];
|
||||
patchAttr(resetTopbarBtn, 'disabled', isDefault);
|
||||
}
|
||||
|
||||
const topbarPanel = h('section', { className: 'panel topbar-config-panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('dock', { size: 13 }),
|
||||
h('span', { text: '顶部栏定制' }),
|
||||
]),
|
||||
h('span', { className: 'topbar-header-right' }, [topbarStatusText, resetTopbarBtn]),
|
||||
]),
|
||||
h('div', { className: 'settings-inline-row' }, [
|
||||
h('span', { className: 'form-label', text: '实时运行会话' }),
|
||||
multiSessionToggle.el,
|
||||
]),
|
||||
h('div', { className: 'form-row' }, [
|
||||
h('span', { className: 'form-label', text: '胶囊数值与顺序 (左 → 右)' }),
|
||||
h('div', { className: 'topbar-slot-list' }, slotRows),
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- 面板 3:版本更新面板 ---
|
||||
const autoUpdateSelect = CustomSelect({
|
||||
modelValue: 'manual',
|
||||
icon: 'refresh',
|
||||
options: AUTO_UPDATE_OPTIONS,
|
||||
onUpdateModelValue: async (val) => {
|
||||
const nextAuto = val === 'auto';
|
||||
draftAutoUpdatePlugin = nextAuto;
|
||||
autoUpdateSelect.setValue(nextAuto ? 'auto' : 'manual');
|
||||
showCloudFeedback('保存中…', 0);
|
||||
try {
|
||||
await saveSettingsPatch({
|
||||
autoUpdatePlugin: nextAuto,
|
||||
});
|
||||
showCloudFeedback('已保存', 1800);
|
||||
} catch {
|
||||
if (latestSettings) {
|
||||
renderSettings(latestSettings);
|
||||
}
|
||||
showCloudFeedback('保存失败', 2500);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.1' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.3' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
||||
@@ -288,7 +450,7 @@ export const SettingsView = defineComponent({
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.1';
|
||||
const curVer = cs?.currentPluginVersion || '1.4.3';
|
||||
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
||||
return;
|
||||
}
|
||||
@@ -342,38 +504,35 @@ export const SettingsView = defineComponent({
|
||||
h('div', { className: 'cloud-actions-row' }, [syncPricingBtn, updatePluginBtn]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'view-pane' }, [budgetPanel, cloudPanel]);
|
||||
const settingsInner = h(
|
||||
'div',
|
||||
{
|
||||
style: 'display: flex; flex-direction: column; gap: var(--space-3); padding-bottom: 2px;',
|
||||
},
|
||||
[generalPanel, topbarPanel, cloudPanel]
|
||||
);
|
||||
const viewScrollbar = CustomScrollbar({
|
||||
contentEl: settingsInner,
|
||||
className: 'view-pane',
|
||||
});
|
||||
|
||||
let latestSettings = null;
|
||||
let latestCloudStatus = null;
|
||||
let isDirty = false;
|
||||
|
||||
/** 生成设置项签名,避免轮询返回相同配置时覆盖用户正在编辑的草稿值 */
|
||||
function settingsSig(s) {
|
||||
if (!s) return '';
|
||||
return `${s.weeklyLimitMode}:${s.weeklyTokenBudget}:${s.weeklyCostBudget}:${Boolean(s.showUpstreamModel)}:${Boolean(s.autoUpdatePlugin)}`;
|
||||
}
|
||||
|
||||
/** 将后端返回的最新设置同步至表单控件 */
|
||||
function renderSettings(settings) {
|
||||
if (!settings) return;
|
||||
const nextSig = settingsSig(settings);
|
||||
if (nextSig === lastSyncedSettingsSig) return;
|
||||
lastSyncedSettingsSig = nextSig;
|
||||
draftMode =
|
||||
settings.weeklyLimitMode === 'custom_tokens' ||
|
||||
settings.weeklyLimitMode === 'custom_cost'
|
||||
? settings.weeklyLimitMode
|
||||
: 'official';
|
||||
draftTokens = Number(settings.weeklyTokenBudget || 150000000);
|
||||
draftCost = Number(settings.weeklyCostBudget || 100);
|
||||
draftShowUpstreamModel = Boolean(settings.showUpstreamModel);
|
||||
draftAutoUpdatePlugin = Boolean(settings.autoUpdatePlugin);
|
||||
modeSelect.setValue(draftMode);
|
||||
draftEnableWindowOverlay = settings.enableWindowOverlay !== false;
|
||||
draftShowTopbarMulti = settings.showTopbarMultiSession !== false;
|
||||
draftTopbarSlots = normalizeClientTopbarSlots(settings.topbarCapsuleSlots);
|
||||
|
||||
windowMountSelect.setValue(draftEnableWindowOverlay ? 'dual' : 'sidebar');
|
||||
stepModelSelect.setValue(draftShowUpstreamModel ? 'upstream' : 'short');
|
||||
autoUpdateSelect.setValue(draftAutoUpdatePlugin ? 'auto' : 'manual');
|
||||
tokenBudgetInput.setValue(draftTokens);
|
||||
costBudgetInput.setValue(draftCost);
|
||||
syncTopbarControls();
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
|
||||
/** 将云端价格表统计与插件版本对比状态同步至云端面板 */
|
||||
@@ -391,7 +550,7 @@ export const SettingsView = defineComponent({
|
||||
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.1';
|
||||
const curVer = cs.currentPluginVersion || '1.4.3';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
@@ -410,6 +569,7 @@ export const SettingsView = defineComponent({
|
||||
if (!cloudTimer && (cs.lastUpdateError || (cs.lastUpdateResult?.ok === false && cs.lastUpdateResult?.message))) {
|
||||
showCloudFeedback(cs.lastUpdateError || cs.lastUpdateResult.message, 5500);
|
||||
}
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
|
||||
const unsub = telemetryStore.subscribe(
|
||||
@@ -420,42 +580,51 @@ export const SettingsView = defineComponent({
|
||||
(slice) => {
|
||||
latestSettings = slice.settings;
|
||||
latestCloudStatus = slice.cloudStatus;
|
||||
if (uiStore.getState().activeView !== 'settings') {
|
||||
isDirty = true;
|
||||
return;
|
||||
}
|
||||
isDirty = false;
|
||||
renderSettings(slice.settings);
|
||||
renderCloudStatus(slice.cloudStatus);
|
||||
if (uiStore.getState().activeView === 'settings') {
|
||||
renderCloudStatus(slice.cloudStatus);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
(activeView) => {
|
||||
if (activeView === 'settings' && isDirty) {
|
||||
isDirty = false;
|
||||
if (activeView === 'settings') {
|
||||
if (latestSettings) renderSettings(latestSettings);
|
||||
if (latestCloudStatus) renderCloudStatus(latestCloudStatus);
|
||||
viewScrollbar.refresh();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
if (statusTimer) clearTimeout(statusTimer);
|
||||
if (topbarTimer) clearTimeout(topbarTimer);
|
||||
if (cloudTimer) clearTimeout(cloudTimer);
|
||||
unsub();
|
||||
unsubView();
|
||||
modeSelect.destroy();
|
||||
windowMountSelect.destroy();
|
||||
stepModelSelect.destroy();
|
||||
multiSessionToggle.destroy();
|
||||
for (const sel of slotSelects) {
|
||||
sel.destroy();
|
||||
}
|
||||
autoUpdateSelect.destroy();
|
||||
tokenBudgetInput.destroy();
|
||||
costBudgetInput.destroy();
|
||||
viewScrollbar.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: { modeSelect, stepModelSelect, autoUpdateSelect, tokenBudgetInput, costBudgetInput },
|
||||
el: viewScrollbar.el,
|
||||
refs: {
|
||||
windowMountSelect,
|
||||
stepModelSelect,
|
||||
multiSessionToggle,
|
||||
slotSelects,
|
||||
resetTopbarBtn,
|
||||
autoUpdateSelect,
|
||||
viewScrollbar,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -349,7 +349,7 @@ export const StepsDetailView = defineComponent({
|
||||
patchText(refs.speedMain, formatMetric(m.avgTokPerSec, ' tok/s'));
|
||||
patchText(refs.speedSub, `有效 ${sampleSummary(m.speedSummary)}`);
|
||||
patchText(refs.tdTokens, formatTokens(m.totalTokens || 0));
|
||||
patchText(refs.tdCost, formatUsd(m.costUsd, { estimated: m.isEstimatedPrice, unpricedCalls: m.unpricedCalls }));
|
||||
patchText(refs.tdCost, formatUsd(m.costUsd, { unpricedCalls: m.unpricedCalls }));
|
||||
},
|
||||
});
|
||||
|
||||
@@ -367,7 +367,6 @@ export const StepsDetailView = defineComponent({
|
||||
recentSteps: st.telemetry?.activeConversation?.recentSteps,
|
||||
sessionModelBreakdown: st.telemetry?.activeConversation?.modelBreakdown,
|
||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||
rangeLabel: st.telemetry?.consumption?.selectedRange?.label || '全部时间',
|
||||
showUpstreamModel: Boolean(st.telemetry?.settings?.showUpstreamModel),
|
||||
}),
|
||||
(slice) => {
|
||||
|
||||
Reference in New Issue
Block a user