mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
feat(panel): upgrade consumption rankings, pointer-following breakdown popovers, full session search, sortable steps, and settings backup
This commit is contained in:
+2197
-320
File diff suppressed because it is too large
Load Diff
@@ -550,6 +550,104 @@ function extractOfflineUserTitle(rawContent) {
|
||||
return firstLine.length > 48 ? `${firstLine.slice(0, 47)}…` : firstLine;
|
||||
}
|
||||
|
||||
const MAX_TITLE_PROBE_CACHE = 2000;
|
||||
const titleProbeCache = new Map();
|
||||
|
||||
function isMeaningfulTitle(rawTitle, cidLower = '') {
|
||||
const clean = String(rawTitle || '').trim();
|
||||
if (!clean) return false;
|
||||
const low = clean.toLowerCase();
|
||||
if (cidLower && (low === cidLower || low === cidLower.slice(0, 8))) return false;
|
||||
if (UUID_RE.test(clean)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function pickFirstMeaningfulTitle(cidLower, candidates = []) {
|
||||
for (const cand of candidates) {
|
||||
if (isMeaningfulTitle(cand, cidLower)) {
|
||||
return String(cand).trim();
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function extractFirstStepTurnTitle(steps) {
|
||||
if (!Array.isArray(steps) || steps.length === 0) return '';
|
||||
for (let i = 0; i < steps.length; i++) {
|
||||
const st = steps[i];
|
||||
if (!st) continue;
|
||||
const raw = st.turnPromptClean || st.turnPrompt || '';
|
||||
if (!raw) continue;
|
||||
const title = extractOfflineUserTitle(raw);
|
||||
if (title) return title;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function readLocalTranscriptHeadTitle(cidLower) {
|
||||
if (!cidLower || !UUID_RE.test(cidLower)) return '';
|
||||
const transcriptPath = findTranscriptPath(cidLower);
|
||||
if (!transcriptPath || !existsSync(transcriptPath)) return '';
|
||||
try {
|
||||
const fd = openSync(transcriptPath, 'r');
|
||||
let chunk = '';
|
||||
try {
|
||||
const buf = Buffer.allocUnsafe(32768);
|
||||
const bytesRead = readSync(fd, buf, 0, buf.length, 0);
|
||||
if (bytesRead > 0) chunk = buf.toString('utf8', 0, bytesRead);
|
||||
} finally {
|
||||
closeSync(fd);
|
||||
}
|
||||
if (!chunk) return '';
|
||||
for (const rawLine of chunk.split(/\r?\n/)) {
|
||||
const trimmed = rawLine.trim();
|
||||
if (!trimmed || !trimmed.startsWith('{')) continue;
|
||||
let parsed = null;
|
||||
try {
|
||||
parsed = JSON.parse(trimmed);
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
const upperType = String(parsed?.type || '').toUpperCase();
|
||||
if (
|
||||
upperType === 'USER_INPUT' ||
|
||||
upperType === 'CORTEX_STEP_TYPE_USER_INPUT' ||
|
||||
(parsed?.userInput && typeof parsed.userInput === 'object')
|
||||
) {
|
||||
const title = extractOfflineUserTitle(
|
||||
typeof parsed.content === 'string'
|
||||
? parsed.content
|
||||
: parsed.userInput?.userResponse || ''
|
||||
);
|
||||
if (title) return title;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 忽略单文件头部读取异常
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
function probeLocalFallbackTitle(cidLower, mtimeSig = 0) {
|
||||
if (!cidLower) return '';
|
||||
const sig = Number(mtimeSig) || 0;
|
||||
const cached = titleProbeCache.get(cidLower);
|
||||
if (cached && cached.sig === sig) {
|
||||
return cached.title;
|
||||
}
|
||||
const annTitle = readAnnotationTitleForCascade(cidLower);
|
||||
const resolved = isMeaningfulTitle(annTitle, cidLower)
|
||||
? String(annTitle).trim()
|
||||
: readLocalTranscriptHeadTitle(cidLower);
|
||||
const finalTitle = isMeaningfulTitle(resolved, cidLower) ? String(resolved).trim() : '';
|
||||
if (titleProbeCache.size >= MAX_TITLE_PROBE_CACHE && !titleProbeCache.has(cidLower)) {
|
||||
const oldestKey = titleProbeCache.keys().next().value;
|
||||
if (oldestKey !== undefined) titleProbeCache.delete(oldestKey);
|
||||
}
|
||||
titleProbeCache.set(cidLower, { sig, title: finalTitle });
|
||||
return finalTitle;
|
||||
}
|
||||
|
||||
function hasLocalSqliteDb(diskFiles = []) {
|
||||
return Array.isArray(diskFiles) && diskFiles.some((f) => /\.db$/i.test(String(f || '')));
|
||||
}
|
||||
@@ -1519,7 +1617,7 @@ export async function enumerateAndSyncConversations({
|
||||
const rawConversations = [];
|
||||
for (const [cidLower, cascadeId] of canonicalIdByLower.entries()) {
|
||||
const item = summariesByLower.get(cidLower);
|
||||
const localSum = item ? null : localSummaryByLower.get(cidLower) || null;
|
||||
const localSum = localSummaryByLower.get(cidLower) || null;
|
||||
const cached = getEntry(cascadeId);
|
||||
const diskFiles = diskConvMap.get(cidLower) || [];
|
||||
const sqliteDbInfo = sqliteAvailable ? resolveBestSqliteDbInfo(diskFiles) : null;
|
||||
@@ -1621,11 +1719,13 @@ export async function enumerateAndSyncConversations({
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title:
|
||||
sqParentInfo?.title ||
|
||||
item?.annotations?.title ||
|
||||
item?.summary ||
|
||||
cached?.title ||
|
||||
(isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
pickFirstMeaningfulTitle(cidLower, [
|
||||
sqParentInfo?.title,
|
||||
item?.annotations?.title,
|
||||
item?.summary,
|
||||
localSum?.title,
|
||||
cached?.title,
|
||||
]) || (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
stepCount: modelStepCount,
|
||||
rawStepCount: rawSummaryStepCount,
|
||||
status: isKilled ? 'IDLE' : item?.status || '',
|
||||
@@ -1653,10 +1753,11 @@ export async function enumerateAndSyncConversations({
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title:
|
||||
sqParentInfo?.title ||
|
||||
localSum?.title ||
|
||||
cached.title ||
|
||||
(isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
pickFirstMeaningfulTitle(cidLower, [
|
||||
sqParentInfo?.title,
|
||||
localSum?.title,
|
||||
cached.title,
|
||||
]) || (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
stepCount: cachedStepCount,
|
||||
rawStepCount: localSum?.stepCount || cached.rawStepCount || cachedStepCount,
|
||||
status: localStatus,
|
||||
@@ -1687,9 +1788,10 @@ export async function enumerateAndSyncConversations({
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title:
|
||||
sqParentInfo?.title ||
|
||||
localSum?.title ||
|
||||
(isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
pickFirstMeaningfulTitle(cidLower, [
|
||||
sqParentInfo?.title,
|
||||
localSum?.title,
|
||||
]) || (isSideQuestion ? '旁路提问' : cascadeId.slice(0, 8)),
|
||||
stepCount: 0,
|
||||
rawStepCount: localSum?.stepCount || 0,
|
||||
status: localStatus,
|
||||
@@ -2628,6 +2730,7 @@ export async function enumerateAndSyncConversations({
|
||||
}
|
||||
}
|
||||
|
||||
let titleBackfillDirty = false;
|
||||
for (const rootConv of conversations) {
|
||||
const cid = rootConv.cascadeId.toLowerCase();
|
||||
const rootCached = getEntry(rootConv.cascadeId);
|
||||
@@ -2635,11 +2738,32 @@ export async function enumerateAndSyncConversations({
|
||||
const swarmTitle = String(swarmManifest?.title || rootCached?.swarmMeta?.title || '').trim();
|
||||
if (swarmTitle) {
|
||||
rootConv.swarmTitle = swarmTitle;
|
||||
const curTitle = String(rootConv.title || '').trim();
|
||||
if (!curTitle || curTitle.toLowerCase() === cid.slice(0, 8)) {
|
||||
if (!isMeaningfulTitle(rootConv.title, cid)) {
|
||||
rootConv.title = swarmTitle;
|
||||
}
|
||||
}
|
||||
if (!isMeaningfulTitle(rootConv.title, cid)) {
|
||||
const localSumTitle = localSummaryByLower.get(cid)?.title || '';
|
||||
const stepTurnTitle = extractFirstStepTurnTitle(rootCached?.steps);
|
||||
let recoveredTitle = pickFirstMeaningfulTitle(cid, [
|
||||
localSumTitle,
|
||||
rootCached?.title,
|
||||
stepTurnTitle,
|
||||
]);
|
||||
if (!recoveredTitle && !isRemote) {
|
||||
recoveredTitle = probeLocalFallbackTitle(
|
||||
cid,
|
||||
rootConv.diskMtimeMs || rootConv.lastModifiedMs || 0
|
||||
);
|
||||
}
|
||||
if (recoveredTitle) {
|
||||
rootConv.title = recoveredTitle;
|
||||
if (rootCached && rootCached.title !== recoveredTitle) {
|
||||
setEntry(rootConv.cascadeId, { ...rootCached, title: recoveredTitle });
|
||||
titleBackfillDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (swarmManifest?.coordinator?.killed || rootConv.killed) {
|
||||
rootConv.status = 'IDLE';
|
||||
rootConv.liveActivity = null;
|
||||
@@ -2760,6 +2884,13 @@ export async function enumerateAndSyncConversations({
|
||||
rootConv.groupLastModifiedMs = Math.max(rootConv.lastModifiedMs || 0, maxSubModMs);
|
||||
}
|
||||
|
||||
if (titleBackfillDirty) {
|
||||
const hasRunningSessions = rawConversations.some(
|
||||
(c) => c.status === 'CASCADE_RUN_STATUS_RUNNING'
|
||||
);
|
||||
persistCacheIfNeeded({ hasRunningSessions });
|
||||
}
|
||||
|
||||
conversations.sort(
|
||||
(a, b) =>
|
||||
(b.groupLastModifiedMs || b.lastModifiedMs || 0) -
|
||||
|
||||
@@ -55,7 +55,7 @@ import {
|
||||
getNextMondayResetIso,
|
||||
} from './usage-aggregator.mjs';
|
||||
|
||||
const MAX_RECENT_CONVERSATIONS = 30;
|
||||
const MAX_RECENT_QUICK_STATS = 30;
|
||||
const MAX_CONVERSATION_ASSEMBLY_CACHE = 8;
|
||||
const MAX_TELEMETRY_SNAPSHOT_ENDPOINTS = 8;
|
||||
const POOL_PRIORITY_ORDER = ['Gemini', 'Argon', 'Carbon', 'Claude & GPT'];
|
||||
@@ -1659,6 +1659,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
weekBucket,
|
||||
quotaWeekBucket,
|
||||
modelBreakdown,
|
||||
topConversations,
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
} = aggregateMultiWindowUsage({
|
||||
@@ -2091,10 +2092,16 @@ export async function buildTelemetryPayloadInternal(
|
||||
totalConversations: conversations.length,
|
||||
},
|
||||
runningConversations,
|
||||
conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => {
|
||||
const qStats = getConversationQuickStats(c);
|
||||
conversations: conversations.map((c, idx) => {
|
||||
const rawSubs = Array.isArray(c.subagents) ? c.subagents : [];
|
||||
const runningSubCount = rawSubs.filter((s) => s.status === 'CASCADE_RUN_STATUS_RUNNING').length;
|
||||
const isConvRunning = c.status === 'CASCADE_RUN_STATUS_RUNNING' || runningSubCount > 0;
|
||||
const includeQuickStats =
|
||||
idx < MAX_RECENT_QUICK_STATS ||
|
||||
isConvRunning ||
|
||||
(Boolean(activeCascadeId) &&
|
||||
String(c.cascadeId || '').toLowerCase() === String(activeCascadeId).toLowerCase());
|
||||
const qStats = includeQuickStats ? getConversationQuickStats(c) : null;
|
||||
const cSwarmCount = Number(c.swarmCount ?? rawSubs.filter((s) => s.isSwarmWorker).length);
|
||||
const cSideCount = rawSubs.filter((s) => s.isSideQuestion).length;
|
||||
const cNormalSubCount = Math.max(0, rawSubs.length - cSwarmCount - cSideCount);
|
||||
@@ -2110,16 +2117,20 @@ export async function buildTelemetryPayloadInternal(
|
||||
runningSubagentCount: runningSubCount,
|
||||
totalStepCount: c.totalStepCount || c.stepCount || 0,
|
||||
...(rawSubs.length > 0 ? { memberCascadeIds: rawSubs.map((s) => s.cascadeId) } : {}),
|
||||
isRunning: c.status === 'CASCADE_RUN_STATUS_RUNNING' || runningSubCount > 0,
|
||||
isRunning: isConvRunning,
|
||||
status: c.status,
|
||||
lastModifiedTime: c.lastModifiedTime,
|
||||
lastModifiedMs: c.groupLastModifiedMs || c.lastModifiedMs,
|
||||
modelShort: qStats.modelShort,
|
||||
modelUpstream: qStats.modelUpstream,
|
||||
latestTokPerSec: qStats.latestTokPerSec,
|
||||
contextUsedPct: qStats.contextUsedPct,
|
||||
sessionCostUsd: qStats.sessionCostUsd,
|
||||
sessionUnpricedCalls: qStats.sessionUnpricedCalls,
|
||||
...(qStats
|
||||
? {
|
||||
modelShort: qStats.modelShort,
|
||||
modelUpstream: qStats.modelUpstream,
|
||||
latestTokPerSec: qStats.latestTokPerSec,
|
||||
contextUsedPct: qStats.contextUsedPct,
|
||||
sessionCostUsd: qStats.sessionCostUsd,
|
||||
sessionUnpricedCalls: qStats.sessionUnpricedCalls,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
activeConversation: assembledActiveConversation,
|
||||
@@ -2136,6 +2147,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
presets: finalizedPresets,
|
||||
trendSeries,
|
||||
sourcesBreakdown,
|
||||
topConversations: enrichTopConversationTitles(topConversations, conversations),
|
||||
monthlyYear: currentYear,
|
||||
monthlySeries,
|
||||
},
|
||||
@@ -2355,6 +2367,40 @@ function tryBuildFastConversationPayload(requestedConvId, filterOpts = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
function enrichTopConversationTitles(topList, convSummaries) {
|
||||
if (!Array.isArray(topList) || topList.length === 0) return [];
|
||||
const titleMap = new Map();
|
||||
if (Array.isArray(convSummaries)) {
|
||||
for (const c of convSummaries) {
|
||||
const cid = String(c?.cascadeId || '').toLowerCase();
|
||||
const title = String(c?.title || '').trim();
|
||||
if (cid && title && !titleMap.has(cid)) {
|
||||
titleMap.set(cid, title);
|
||||
}
|
||||
if (Array.isArray(c?.subagents)) {
|
||||
for (const sub of c.subagents) {
|
||||
const sid = String(sub?.cascadeId || '').toLowerCase();
|
||||
if (sid && title && !titleMap.has(sid)) {
|
||||
titleMap.set(sid, title);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return topList.map((item) => {
|
||||
if (!item || typeof item !== 'object') return item;
|
||||
const cidLower = String(item.cascadeId || '').toLowerCase();
|
||||
const fallbackTitle = titleMap.get(cidLower) || '';
|
||||
const existingTitle = String(item.title || '').trim();
|
||||
const resolvedTitle = existingTitle || fallbackTitle || (item.cascadeId ? item.cascadeId.slice(0, 8) : '—');
|
||||
return {
|
||||
...item,
|
||||
title: resolvedTitle,
|
||||
canJump: titleMap.has(cidLower),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function tryBuildFastConsumptionPayload(filterOpts = {}) {
|
||||
const endpoint = filterOpts?.endpoint && filterOpts.endpoint.isRemote ? filterOpts.endpoint : null;
|
||||
const snap = resolveValidFastSnapshot(endpoint);
|
||||
@@ -2382,6 +2428,10 @@ function tryBuildFastConsumptionPayload(filterOpts = {}) {
|
||||
account: agg.finalizedSelectedAccount,
|
||||
trendSeries: agg.trendSeries,
|
||||
sourcesBreakdown: agg.sourcesBreakdown,
|
||||
topConversations: enrichTopConversationTitles(
|
||||
agg.topConversations,
|
||||
snap.sessions?.conversations
|
||||
),
|
||||
},
|
||||
modelBreakdown: agg.modelBreakdown,
|
||||
};
|
||||
@@ -2395,13 +2445,23 @@ function tryBuildConsumptionPresetsPayload(filterOpts = {}) {
|
||||
...snap.aggContext,
|
||||
endpoint,
|
||||
});
|
||||
const enrichedRanges = {};
|
||||
for (const [rangeKey, entry] of Object.entries(bundle.ranges || {})) {
|
||||
enrichedRanges[rangeKey] = {
|
||||
...entry,
|
||||
topConversations: enrichTopConversationTitles(
|
||||
entry?.topConversations,
|
||||
snap.sessions?.conversations
|
||||
),
|
||||
};
|
||||
}
|
||||
return {
|
||||
scope: 'consumption-presets',
|
||||
timestamp: new Date().toISOString(),
|
||||
endpoint: snap.basePayload.endpoint,
|
||||
uiBundleVersion: snap.basePayload.uiBundleVersion || computeRuntimeCodeVersion(),
|
||||
usageRevision: bundle.usageRevision,
|
||||
ranges: bundle.ranges,
|
||||
ranges: enrichedRanges,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -532,8 +532,13 @@ function collectUsageEntriesToAggregate(familySet, endpoint = null) {
|
||||
const groupCascadeId = String(
|
||||
entry?.rootConversationId || entry?.parentConversationId || cidLower
|
||||
).toLowerCase();
|
||||
const rootLive = allLiveByLower.get(groupCascadeId);
|
||||
const entryTitle = String(
|
||||
rootLive?.title || entry?.title || extMatch?.title || ''
|
||||
).trim();
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId: groupCascadeId,
|
||||
title: entryTitle,
|
||||
appSource: isRemote ? 'ssh' : entry?.appSource || 'standalone',
|
||||
accountName: entry?.accountName || extMatch?.accountName || '',
|
||||
steps: entry?.steps || [],
|
||||
@@ -548,6 +553,7 @@ function collectUsageEntriesToAggregate(familySet, endpoint = null) {
|
||||
}
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId: extCidLower,
|
||||
title: String(ext.title || liveEntry?.title || '').trim(),
|
||||
appSource: ext.appSource || 'ide',
|
||||
accountName: ext.accountName || liveEntry?.accountName || '',
|
||||
steps: ext.steps || [],
|
||||
@@ -558,6 +564,87 @@ function collectUsageEntriesToAggregate(familySet, endpoint = null) {
|
||||
return allEntriesToAggregate;
|
||||
}
|
||||
|
||||
const MAX_TOP_CONVERSATIONS_LIMIT = 10;
|
||||
|
||||
function accumulateStepIntoConversationMap(
|
||||
perConvMap,
|
||||
entry,
|
||||
srcKey,
|
||||
srcName,
|
||||
stepUsage,
|
||||
tMs,
|
||||
st = null,
|
||||
mInfo = null,
|
||||
stepCost = null
|
||||
) {
|
||||
const cid = String(entry?.cascadeId || '').trim();
|
||||
if (!cid) return;
|
||||
let acc = perConvMap.get(cid);
|
||||
if (!acc) {
|
||||
acc = {
|
||||
cascadeId: cid,
|
||||
title: String(entry?.title || '').trim(),
|
||||
appSource: srcKey,
|
||||
sourceName: srcName,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
responseTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
lastTimestampMs: 0,
|
||||
perModelStats: new Map(),
|
||||
};
|
||||
perConvMap.set(cid, acc);
|
||||
}
|
||||
if (!acc.title && entry?.title) {
|
||||
acc.title = String(entry.title).trim();
|
||||
}
|
||||
acc.calls += 1;
|
||||
acc.inputTokens += stepUsage.inTok;
|
||||
acc.cacheReadTokens += stepUsage.cacheTok;
|
||||
acc.responseTokens += stepUsage.respTok;
|
||||
acc.thinkingTokens += stepUsage.thinkTok;
|
||||
acc.totalTokens += stepUsage.stepTotalTokens;
|
||||
acc.costUsd += stepUsage.resolvedCost;
|
||||
acc.unpricedCalls += stepUsage.unpriced;
|
||||
if (tMs > acc.lastTimestampMs) {
|
||||
acc.lastTimestampMs = tMs;
|
||||
}
|
||||
if (st && mInfo) {
|
||||
accumulateStepIntoModelMap(acc.perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
}
|
||||
|
||||
function finalizeTopConversationsMap(perConvMap, maxItems = MAX_TOP_CONVERSATIONS_LIMIT) {
|
||||
return Array.from(perConvMap.values())
|
||||
.filter((c) => c.totalTokens > 0 || c.calls > 0)
|
||||
.sort((a, b) => b.costUsd - a.costUsd || b.totalTokens - a.totalTokens || b.calls - a.calls)
|
||||
.slice(0, maxItems)
|
||||
.map((c) => {
|
||||
const promptTokens = c.inputTokens + c.cacheReadTokens;
|
||||
return {
|
||||
cascadeId: c.cascadeId,
|
||||
title: c.title,
|
||||
appSource: c.appSource,
|
||||
sourceName: c.sourceName,
|
||||
calls: c.calls,
|
||||
inputTokens: c.inputTokens,
|
||||
cacheReadTokens: c.cacheReadTokens,
|
||||
responseTokens: c.responseTokens,
|
||||
thinkingTokens: c.thinkingTokens,
|
||||
totalTokens: c.totalTokens,
|
||||
costUsd: +c.costUsd.toFixed(6),
|
||||
unpricedCalls: c.unpricedCalls,
|
||||
cacheHitPct: promptTokens > 0 ? +((c.cacheReadTokens / promptTokens) * 100).toFixed(1) : 0,
|
||||
lastTimestampMs: c.lastTimestampMs,
|
||||
models: finalizeModelBreakdownMap(c.perModelStats),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function buildQuotaPoolCycleMap(quotaPoolsMap, nowMs) {
|
||||
const poolCycleBuckets = new Map();
|
||||
if (quotaPoolsMap instanceof Map && quotaPoolsMap.size > 0) {
|
||||
@@ -688,6 +775,8 @@ function buildUsageTrendSeries(
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
calls: 0,
|
||||
@@ -740,6 +829,8 @@ function buildUsageTrendSeries(
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
calls: 0,
|
||||
@@ -781,6 +872,8 @@ function buildUsageTrendSeries(
|
||||
bucket.inputTokens += item.inputTokens || 0;
|
||||
bucket.cacheReadTokens += item.cacheReadTokens || 0;
|
||||
bucket.outputTokens += item.outputTokens || 0;
|
||||
bucket.thinkingTokens += item.thinkingTokens || 0;
|
||||
bucket.responseTokens += item.responseTokens || 0;
|
||||
bucket.costUsd += item.costUsd;
|
||||
bucket.unpricedCalls = (bucket.unpricedCalls || 0) + item.unpricedCalls;
|
||||
bucket.calls += 1;
|
||||
@@ -801,6 +894,11 @@ function buildUsageTrendSeries(
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
unpricedCalls: 0,
|
||||
@@ -815,6 +913,11 @@ function buildUsageTrendSeries(
|
||||
);
|
||||
}
|
||||
bModel.calls += 1;
|
||||
bModel.inputTokens += item.inputTokens || 0;
|
||||
bModel.cacheReadTokens += item.cacheReadTokens || 0;
|
||||
bModel.outputTokens += item.outputTokens || 0;
|
||||
bModel.thinkingTokens += item.thinkingTokens || 0;
|
||||
bModel.responseTokens += item.responseTokens || 0;
|
||||
bModel.totalTokens += item.tokens;
|
||||
bModel.costUsd += item.costUsd;
|
||||
bModel.unpricedCalls += item.unpricedCalls || 0;
|
||||
@@ -1150,6 +1253,7 @@ export function aggregateMultiWindowUsage({
|
||||
const selectedAccountBucket = accountBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const selectedSessionBucket = sessionBuckets[selectedWindow.key] || createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const perConvStats = new Map();
|
||||
const selectedWindowSteps = [];
|
||||
let earliestSelectedStepMs = Infinity;
|
||||
let latestSelectedStepMs = 0;
|
||||
@@ -1401,6 +1505,8 @@ export function aggregateMultiWindowUsage({
|
||||
inputTokens: inTok,
|
||||
cacheReadTokens: cacheTok,
|
||||
outputTokens: outTok,
|
||||
thinkingTokens: thinkTok,
|
||||
responseTokens: respTok,
|
||||
costUsd: resolvedCost,
|
||||
unpricedCalls: unpriced,
|
||||
mInfo,
|
||||
@@ -1433,6 +1539,17 @@ export function aggregateMultiWindowUsage({
|
||||
accumulateStepIntoModelMap(sAgg.perModelStats, st, mInfo, stepCost);
|
||||
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
accumulateStepIntoConversationMap(
|
||||
perConvStats,
|
||||
entry,
|
||||
srcKey,
|
||||
srcName,
|
||||
stepUsage,
|
||||
tMs,
|
||||
st,
|
||||
mInfo,
|
||||
stepCost
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1489,6 +1606,7 @@ export function aggregateMultiWindowUsage({
|
||||
const weekBucket = finalizedPresets.week.account;
|
||||
const finalizedQuotaWeekBucket = finalizeUsageBucket(quotaWeekBucket);
|
||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||
const topConversations = finalizeTopConversationsMap(perConvStats);
|
||||
|
||||
const formatCycleSummary = (b) => {
|
||||
const fin = finalizeUsageBucket(b);
|
||||
@@ -1574,6 +1692,7 @@ export function aggregateMultiWindowUsage({
|
||||
weekBucket,
|
||||
quotaWeekBucket: finalizedQuotaWeekBucket,
|
||||
modelBreakdown,
|
||||
topConversations,
|
||||
poolCycleStats,
|
||||
poolsWeeklySummary,
|
||||
};
|
||||
@@ -1715,6 +1834,7 @@ export function aggregateSelectedWindowUsage({
|
||||
trendSeries: res.trendSeries,
|
||||
sourcesBreakdown: res.sourcesBreakdown,
|
||||
modelBreakdown: res.modelBreakdown,
|
||||
topConversations: res.topConversations || [],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1755,6 +1875,7 @@ export function aggregateSelectedWindowUsage({
|
||||
const selectedSessionBucket = createUsageBucket();
|
||||
const perModelStats = new Map();
|
||||
const perSourceStats = new Map();
|
||||
const perConvStats = new Map();
|
||||
const selectedWindowSteps = [];
|
||||
let earliestSelectedStepMs = Infinity;
|
||||
let latestSelectedStepMs = 0;
|
||||
@@ -1878,6 +1999,8 @@ export function aggregateSelectedWindowUsage({
|
||||
inputTokens: inTok,
|
||||
cacheReadTokens: cacheTok,
|
||||
outputTokens: outTok,
|
||||
thinkingTokens: thinkTok,
|
||||
responseTokens: respTok,
|
||||
costUsd: resolvedCost,
|
||||
unpricedCalls: unpriced,
|
||||
mInfo,
|
||||
@@ -1910,6 +2033,17 @@ export function aggregateSelectedWindowUsage({
|
||||
accumulateStepIntoModelMap(sAgg.perModelStats, st, mInfo, stepCost);
|
||||
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
accumulateStepIntoConversationMap(
|
||||
perConvStats,
|
||||
entry,
|
||||
srcKey,
|
||||
srcName,
|
||||
stepUsage,
|
||||
tMs,
|
||||
st,
|
||||
mInfo,
|
||||
stepCost
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1943,6 +2077,7 @@ export function aggregateSelectedWindowUsage({
|
||||
}))
|
||||
.sort((a, b) => b.totalTokens - a.totalTokens || b.calls - a.calls);
|
||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||
const topConversations = finalizeTopConversationsMap(perConvStats);
|
||||
|
||||
const sliceResult = {
|
||||
usageRevision: sameSnapshot ? snapshot.revision : usageSnapshotRevisionSeq,
|
||||
@@ -1954,6 +2089,7 @@ export function aggregateSelectedWindowUsage({
|
||||
trendSeries,
|
||||
sourcesBreakdown,
|
||||
modelBreakdown,
|
||||
topConversations,
|
||||
};
|
||||
|
||||
if (sameSnapshot) {
|
||||
@@ -2081,6 +2217,7 @@ export function aggregateConsumptionPresetBundle(params) {
|
||||
trendSeries: agg.trendSeries,
|
||||
sourcesBreakdown: agg.sourcesBreakdown,
|
||||
modelBreakdown: agg.modelBreakdown,
|
||||
topConversations: agg.topConversations || [],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,11 +4,11 @@
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>用量监控</title>
|
||||
<link rel="stylesheet" href="/styles.css?v=1795188897587">
|
||||
<link rel="stylesheet" href="/styles.css?v=1795236329148">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1795188897587"></script>
|
||||
<script src="/app.js?v=1795236329148"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -529,6 +529,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
'src/core/domPatch.js',
|
||||
'src/core/component.js',
|
||||
'src/core/formatters.js',
|
||||
'src/core/settingsBackup.js',
|
||||
'src/core/httpClient.js',
|
||||
'src/store/uiStore.js',
|
||||
'src/store/telemetryStore.js',
|
||||
@@ -540,6 +541,7 @@ export function buildBundle(panelDir = PANEL_DIR) {
|
||||
'src/components/ui/SegmentedControl.js',
|
||||
'src/components/ui/ContextSegmentMeter.js',
|
||||
'src/components/ui/FourSegmentBar.js',
|
||||
'src/components/ui/ConsumptionTooltipContent.js',
|
||||
'src/components/charts/TrendAreaChart.js',
|
||||
'src/components/charts/SessionStepCharts.js',
|
||||
'src/registries/metricRegistry.js',
|
||||
|
||||
@@ -9,6 +9,7 @@ import { h, patchAttr } from './core/domPatch.js';
|
||||
import { isWindowOverlayMode } from './core/httpClient.js';
|
||||
import { i18nStore } from './i18n/index.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
normalizeClientWindowMountMode,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
@@ -22,6 +23,27 @@ import { ConsumptionView } from './views/ConsumptionView.js';
|
||||
import { StepsDetailView } from './views/StepsDetailView.js';
|
||||
import { SettingsView } from './views/SettingsView.js';
|
||||
|
||||
const APP_VIEW_SHORTCUT_MAP = Object.freeze({
|
||||
1: 'overview',
|
||||
2: 'consumption',
|
||||
3: 'steps',
|
||||
4: 'settings',
|
||||
});
|
||||
|
||||
function isEditableKeyTarget(e) {
|
||||
const path = typeof e?.composedPath === 'function' ? e.composedPath() : null;
|
||||
const target = (Array.isArray(path) && path[0]) || e?.target;
|
||||
if (!target || typeof target !== 'object') return false;
|
||||
const tag = String(target.tagName || '').toUpperCase();
|
||||
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT') return true;
|
||||
if (target.isContentEditable) return true;
|
||||
if (typeof target.getAttribute === 'function') {
|
||||
const ce = target.getAttribute('contenteditable');
|
||||
if (ce === '' || ce === 'true') return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export const App = defineComponent({
|
||||
name: 'App',
|
||||
setup({ onCleanup }) {
|
||||
@@ -83,11 +105,40 @@ export const App = defineComponent({
|
||||
settingsView.el,
|
||||
]);
|
||||
|
||||
const shellEl = h('main', { className: 'app-shell' }, [
|
||||
h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]),
|
||||
bannerSlotEl,
|
||||
stageEl,
|
||||
]);
|
||||
const shellEl = h(
|
||||
'main',
|
||||
{
|
||||
className: 'app-shell',
|
||||
tabIndex: -1,
|
||||
onKeydown: (e) => {
|
||||
if (!e || e.defaultPrevented || e.ctrlKey || e.metaKey || e.altKey) return;
|
||||
if (isEditableKeyTarget(e)) return;
|
||||
const key = String(e.key || '');
|
||||
const mappedView = APP_VIEW_SHORTCUT_MAP[key];
|
||||
if (mappedView) {
|
||||
e.preventDefault();
|
||||
if (uiStore.getState().activeView !== mappedView) {
|
||||
uiStore.setState({ activeView: mappedView });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (key === 'r' || key === 'R') {
|
||||
e.preventDefault();
|
||||
void fetchTelemetry({ force: true });
|
||||
return;
|
||||
}
|
||||
if (key === '/') {
|
||||
e.preventDefault();
|
||||
sessionHeader.refs?.convSelect?.openAndFocusSearch?.();
|
||||
}
|
||||
},
|
||||
},
|
||||
[
|
||||
h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]),
|
||||
bannerSlotEl,
|
||||
stageEl,
|
||||
]
|
||||
);
|
||||
|
||||
function syncStepsBadge() {
|
||||
const uiSt = uiStore.getState();
|
||||
|
||||
@@ -10,13 +10,13 @@ import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise, formatUsd } from '../../core/formatters.js';
|
||||
import { SVG_NS } from '../../icons/SvgIcon.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { createConsumptionBreakdownContent } from '../ui/ConsumptionTooltipContent.js';
|
||||
|
||||
/** 超过该自然日天数(> 90 天)时,趋势图切换为类 GitHub 每日小格子热力图 */
|
||||
export const HEATMAP_DAYS_THRESHOLD = 90;
|
||||
@@ -196,12 +196,14 @@ function buildHeatmapMonthTicks(slots, firstDow, totalWeeks) {
|
||||
/**
|
||||
* 创建交互式历史趋势组件(<=90 天为 SVG 平滑曲线图,>90 天自动切换为类 GitHub 每日小格子热力图)。
|
||||
*
|
||||
* @param {{ onSelectSlot?: (slot: object) => void }} [options]
|
||||
* @returns {{
|
||||
* el: HTMLElement,
|
||||
* update: (series?: Array<object>) => void
|
||||
* update: (series?: Array<object>) => void,
|
||||
* destroy: () => void
|
||||
* }}
|
||||
*/
|
||||
export function createTrendAreaChart() {
|
||||
export function createTrendAreaChart({ onSelectSlot = null } = {}) {
|
||||
const DEFAULT_VIEW_W = 460;
|
||||
const VIEW_H = 184;
|
||||
const TOP_Y = 26;
|
||||
@@ -304,53 +306,25 @@ export function createTrendAreaChart() {
|
||||
|
||||
const peakPill = h('span', { className: 'trend-peak-pill text-mono', text: '0' });
|
||||
|
||||
function createTooltipModelRow() {
|
||||
const dotEl = h('span', { className: 'dot-swatch cons-model-dot' });
|
||||
const nameEl = h('span', { className: 'cons-pop-model-name' });
|
||||
const tokEl = h('span', { className: 'cons-pop-model-tok' });
|
||||
const pctEl = h('strong', { className: 'cons-pop-model-pct' });
|
||||
const rowEl = h('div', { className: 'cons-pop-model-row' }, [
|
||||
h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]),
|
||||
h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]),
|
||||
]);
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { rowEl, dotEl, nameEl, tokEl, pctEl },
|
||||
};
|
||||
}
|
||||
|
||||
// 共享悬停详情浮层卡片(曲线图与热力格子图共用,含该时段分模型占比明细)
|
||||
const tipTimeEl = h('span', { className: 'trend-tip-time text-mono' });
|
||||
const tipCallsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
||||
const tipTokensEl = h('strong', { className: 'trend-tip-tokens text-mono' });
|
||||
const tipCostEl = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
const tipInLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legInput') });
|
||||
const tipInValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
|
||||
const tipCacheLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legCache') });
|
||||
const tipCacheValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
|
||||
const tipOutLabelEl = h('span', { className: 'trend-tip-stat-label', text: t('cons.legOutput') });
|
||||
const tipOutValEl = h('span', { className: 'trend-tip-stat-val text-mono' });
|
||||
const tipSubEl = h('div', { className: 'trend-tip-sub is-grid', hidden: true }, [
|
||||
h('div', { className: 'trend-tip-stat' }, [tipInLabelEl, tipInValEl]),
|
||||
h('div', { className: 'trend-tip-stat' }, [tipCacheLabelEl, tipCacheValEl]),
|
||||
h('div', { className: 'trend-tip-stat' }, [tipOutLabelEl, tipOutValEl]),
|
||||
]);
|
||||
const tipModelsEl = h('div', { className: 'cons-pop-models', hidden: true });
|
||||
// 共享悬停详情浮层卡片(曲线图和热力格子图共用,含分模型四段进度条及底部四通道明细)
|
||||
const tooltipContent = createConsumptionBreakdownContent({
|
||||
showModelDot: false,
|
||||
monoTitle: true,
|
||||
});
|
||||
|
||||
const tooltipEl = h(
|
||||
'div',
|
||||
{ className: 'trend-tooltip', hidden: true },
|
||||
[
|
||||
h('div', { className: 'trend-tip-head' }, [tipTimeEl, tipCallsEl]),
|
||||
h('div', { className: 'trend-tip-main' }, [tipTokensEl, tipCostEl]),
|
||||
tipSubEl,
|
||||
tipModelsEl,
|
||||
]
|
||||
{ className: 'trend-tooltip is-rich-breakdown', hidden: true },
|
||||
tooltipContent.children
|
||||
);
|
||||
|
||||
// 底部对齐刻度轴(曲线模式)
|
||||
const xAxisEl = h('div', { className: 'trend-x-axis' });
|
||||
const plotStage = h('div', { className: 'trend-plot-stage' }, [peakPill, svg]);
|
||||
const plotStage = h(
|
||||
'div',
|
||||
{ className: `trend-plot-stage${typeof onSelectSlot === 'function' ? ' is-clickable' : ''}` },
|
||||
[peakPill, svg]
|
||||
);
|
||||
|
||||
// 类 GitHub 每日小格子热力图容器(> 90 天模式)
|
||||
const wdayMonEl = h('span', { className: 'trend-hm-wday', text: t('chart.trend.wdayMon') });
|
||||
@@ -412,6 +386,7 @@ export function createTrendAreaChart() {
|
||||
let tickElsByIdx = new Map();
|
||||
let hoveredIdx = -1;
|
||||
let hoveredCellEl = null;
|
||||
let lastPointer = null;
|
||||
let lastRenderSig = '';
|
||||
let tipTrackRaf = 0;
|
||||
|
||||
@@ -443,102 +418,133 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
|
||||
function populateTooltipContent(slot) {
|
||||
patchText(tipTimeEl, slot.fullLabel || slot.label || '--');
|
||||
patchText(
|
||||
tipCallsEl,
|
||||
t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(slot.calls) || 0)) })
|
||||
);
|
||||
const slotTok = safeSlotTokens(slot.tokens);
|
||||
patchText(tipTokensEl, `${formatTokensPrecise(slotTok)} tok`);
|
||||
const slotCost = Number.isFinite(Number(slot.costUsd)) ? Math.max(0, Number(slot.costUsd)) : 0;
|
||||
patchText(
|
||||
tipCostEl,
|
||||
formatUsd(slotCost, {
|
||||
tooltipContent.update({
|
||||
title: slot.fullLabel || slot.label || '--',
|
||||
calls: slot.calls,
|
||||
totalTokens: slotTok,
|
||||
costText: formatUsd(slotCost, {
|
||||
precise: slotCost > 0 && slotCost < 0.1,
|
||||
})
|
||||
);
|
||||
|
||||
const hasSubBreakdown =
|
||||
slotTok > 0 &&
|
||||
(slot.inputTokens !== undefined ||
|
||||
slot.cacheReadTokens !== undefined ||
|
||||
slot.outputTokens !== undefined);
|
||||
patchAttr(tipSubEl, 'hidden', !hasSubBreakdown);
|
||||
if (hasSubBreakdown) {
|
||||
patchText(tipInLabelEl, t('cons.legInput'));
|
||||
patchText(tipCacheLabelEl, t('cons.legCache'));
|
||||
patchText(tipOutLabelEl, t('cons.legOutput'));
|
||||
patchText(tipInValEl, formatTokensPrecise(safeSlotTokens(slot.inputTokens)));
|
||||
patchText(tipCacheValEl, formatTokensPrecise(safeSlotTokens(slot.cacheReadTokens)));
|
||||
patchText(tipOutValEl, formatTokensPrecise(safeSlotTokens(slot.outputTokens)));
|
||||
}
|
||||
|
||||
const modelSegs = Array.isArray(slot.modelSegments) ? slot.modelSegments : [];
|
||||
patchAttr(tipModelsEl, 'hidden', modelSegs.length === 0);
|
||||
patchKeyedList(tipModelsEl, modelSegs, {
|
||||
keyFn: (r) => r.key,
|
||||
sigFn: (r) => `${r.key}:${r.label}:${r.color}:${r.tokText}:${r.pctText}:${r.isOther}`,
|
||||
createRow: createTooltipModelRow,
|
||||
updateRow: (rRefs, r) => {
|
||||
patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) });
|
||||
patchStyleVar(rRefs.dotEl, '--dot-color', r.color);
|
||||
patchText(rRefs.nameEl, r.label);
|
||||
patchText(rRefs.tokEl, r.tokText);
|
||||
patchText(rRefs.pctEl, r.pctText);
|
||||
},
|
||||
}),
|
||||
inputTokens: slot.inputTokens,
|
||||
cacheReadTokens: slot.cacheReadTokens,
|
||||
thinkingTokens: slot.thinkingTokens,
|
||||
responseTokens: slot.responseTokens,
|
||||
outputTokens: slot.outputTokens,
|
||||
segments: Array.isArray(slot.modelSegments) ? slot.modelSegments : [],
|
||||
});
|
||||
}
|
||||
|
||||
function showLineHoverAtIndex(idx) {
|
||||
function positionTooltipNearAnchor(fallbackX, fallbackY, pointer = null) {
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
|
||||
const wrapH =
|
||||
wrapRect && wrapRect.height > 0
|
||||
? wrapRect.height
|
||||
: Number(chartWrap.offsetHeight || VIEW_H);
|
||||
|
||||
const tipRect = tooltipEl.getBoundingClientRect?.() || null;
|
||||
const tipW =
|
||||
Number(tooltipEl.offsetWidth || 0) ||
|
||||
(tipRect && tipRect.width > 0 ? tipRect.width : 216);
|
||||
const tipH =
|
||||
Number(tooltipEl.offsetHeight || 0) ||
|
||||
(tipRect && tipRect.height > 0 ? tipRect.height : 104);
|
||||
|
||||
const hasPointer =
|
||||
pointer &&
|
||||
Number.isFinite(Number(pointer.clientX)) &&
|
||||
Number.isFinite(Number(pointer.clientY)) &&
|
||||
wrapRect &&
|
||||
wrapRect.width > 0 &&
|
||||
wrapRect.height > 0;
|
||||
|
||||
const anchorX = hasPointer ? Number(pointer.clientX) - wrapRect.left : fallbackX;
|
||||
const anchorY = hasPointer ? Number(pointer.clientY) - wrapRect.top : fallbackY;
|
||||
|
||||
const clipEl = chartWrap.closest?.('.view-pane, .cons-view-stage') || null;
|
||||
const clipRect = clipEl?.getBoundingClientRect?.() || null;
|
||||
const hasClip = Boolean(
|
||||
clipRect && clipRect.height > 0 && wrapRect && wrapRect.height > 0
|
||||
);
|
||||
const minY = hasClip ? clipRect.top - wrapRect.top + 6 : -tipH - 16;
|
||||
const maxY = hasClip ? clipRect.bottom - wrapRect.top - tipH - 6 : wrapH + 16;
|
||||
|
||||
const maxLeft = Math.max(4, wrapW - tipW - 4);
|
||||
let leftPx = Math.max(4, Math.min(maxLeft, anchorX - tipW / 2));
|
||||
const aboveY = anchorY - tipH - 14;
|
||||
let topPx;
|
||||
|
||||
if (aboveY >= minY) {
|
||||
topPx = Math.min(maxY, aboveY);
|
||||
} else if (anchorX + 16 + tipW <= wrapW - 4) {
|
||||
leftPx = anchorX + 16;
|
||||
topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2));
|
||||
} else if (anchorX - 16 - tipW >= 4) {
|
||||
leftPx = anchorX - 16 - tipW;
|
||||
topPx = Math.max(minY, Math.min(maxY, anchorY - tipH / 2));
|
||||
} else {
|
||||
topPx = Math.max(minY, Math.min(maxY, anchorY + 18));
|
||||
}
|
||||
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${Math.round(leftPx)}px`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', '0px');
|
||||
patchStyleVar(tooltipEl, '--tip-y', `${Math.round(topPx)}px`);
|
||||
}
|
||||
|
||||
function showLineHoverAtIndex(idx, pointer = null) {
|
||||
if (currentIsHeatmap || idx < 0 || idx >= currentSlots.length || !currentPts[idx]) {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
const changedIdx = idx !== hoveredIdx;
|
||||
hoveredIdx = idx;
|
||||
if (pointer) {
|
||||
lastPointer = pointer;
|
||||
}
|
||||
const slot = currentSlots[idx];
|
||||
const pt = currentPts[idx];
|
||||
|
||||
patchAttr(hoverLine, 'hidden', false);
|
||||
patchAttr(hoverLine, 'x1', pt.x.toFixed(1));
|
||||
patchAttr(hoverLine, 'x2', pt.x.toFixed(1));
|
||||
if (wasHidden || changedIdx) {
|
||||
patchAttr(hoverLine, 'hidden', false);
|
||||
patchAttr(hoverLine, 'x1', pt.x.toFixed(1));
|
||||
patchAttr(hoverLine, 'x2', pt.x.toFixed(1));
|
||||
|
||||
patchAttr(hoverDot, 'hidden', false);
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
patchAttr(hoverDot, 'hidden', false);
|
||||
patchAttr(hoverDot, 'cx', pt.x.toFixed(1));
|
||||
patchAttr(hoverDot, 'cy', pt.y.toFixed(1));
|
||||
|
||||
const isLineLow = pt.y < Math.round((TOP_Y + BOTTOM_Y) / 2);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': isLineLow,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
patchAttr(peakPill, 'hidden', true);
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
|
||||
let tipY = 0;
|
||||
if (isLineLow) {
|
||||
const wrapH = Number(chartWrap.offsetHeight || 0);
|
||||
const tipH = Number(tooltipEl.offsetHeight || 0);
|
||||
if (wrapH > 0 && tipH > 0) {
|
||||
tipY = Math.max(0, wrapH - tipH - 22);
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
}
|
||||
}
|
||||
|
||||
const rawPct = (pt.x / viewW) * 100;
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', `${Math.round(tipY)}px`);
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
|
||||
const fallbackX = (pt.x / Math.max(1, viewW)) * wrapW;
|
||||
const fallbackY = pt.y + 6;
|
||||
positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer);
|
||||
armTooltipTracking(wasHidden);
|
||||
|
||||
for (const [tIdx, el] of tickElsByIdx.entries()) {
|
||||
patchClasses(el, { 'is-hovered': tIdx === idx });
|
||||
}
|
||||
}
|
||||
|
||||
function showHeatmapHoverAtIndex(idx, cellEl) {
|
||||
function showHeatmapHoverAtIndex(idx, cellEl, pointer = null) {
|
||||
if (!currentIsHeatmap || idx < 0 || idx >= currentSlots.length) {
|
||||
clearHover();
|
||||
return;
|
||||
@@ -548,7 +554,12 @@ export function createTrendAreaChart() {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
const changedCell = idx !== hoveredIdx || hoveredCellEl !== targetCell;
|
||||
hoveredIdx = idx;
|
||||
if (pointer) {
|
||||
lastPointer = pointer;
|
||||
}
|
||||
if (hoveredCellEl && hoveredCellEl !== targetCell) {
|
||||
patchClasses(hoveredCellEl, { 'is-hovered': false });
|
||||
}
|
||||
@@ -559,19 +570,25 @@ export function createTrendAreaChart() {
|
||||
const row = Number(targetCell.getAttribute('data-hm-row') || 0);
|
||||
const col = Number(targetCell.getAttribute('data-hm-col') || 0);
|
||||
|
||||
const wasHidden = tooltipEl.hasAttribute('hidden');
|
||||
// 上半区(周一~周四)浮层停靠热力图下方,下半区(周五~周日)停靠热力图上方,互不遮挡被悬停格子且永不越界裁剪
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': row <= 3,
|
||||
'is-hm-top': row > 3,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
if (wasHidden || changedCell) {
|
||||
patchClasses(tooltipEl, {
|
||||
'is-hm-bottom': false,
|
||||
'is-hm-top': false,
|
||||
'is-line-low': false,
|
||||
});
|
||||
patchAttr(tooltipEl, 'hidden', false);
|
||||
populateTooltipContent(slot);
|
||||
}
|
||||
|
||||
const wrapRect = chartWrap.getBoundingClientRect();
|
||||
const cellRect = targetCell.getBoundingClientRect();
|
||||
let rawPct = 50;
|
||||
const wrapRect = chartWrap.getBoundingClientRect?.() || null;
|
||||
const cellRect = targetCell.getBoundingClientRect?.() || null;
|
||||
const wrapW =
|
||||
wrapRect && wrapRect.width > 0
|
||||
? wrapRect.width
|
||||
: Number(chartWrap.clientWidth || viewW || DEFAULT_VIEW_W);
|
||||
let fallbackX =
|
||||
currentHeatmapWeeks > 0 ? ((col + 0.5) / currentHeatmapWeeks) * wrapW : wrapW / 2;
|
||||
let fallbackY = 20 + row * 14;
|
||||
if (
|
||||
wrapRect &&
|
||||
wrapRect.width > 0 &&
|
||||
@@ -579,20 +596,18 @@ export function createTrendAreaChart() {
|
||||
cellRect.width > 0 &&
|
||||
cellRect.width < wrapRect.width
|
||||
) {
|
||||
rawPct = ((cellRect.left + cellRect.width / 2 - wrapRect.left) / wrapRect.width) * 100;
|
||||
} else if (currentHeatmapWeeks > 0) {
|
||||
rawPct = ((col + 0.5) / currentHeatmapWeeks) * 100;
|
||||
fallbackX = cellRect.left + cellRect.width / 2 - wrapRect.left;
|
||||
fallbackY = cellRect.top + cellRect.height / 2 - wrapRect.top;
|
||||
}
|
||||
const clampedPct = Math.max(1, Math.min(99, rawPct));
|
||||
patchStyleVar(tooltipEl, '--tip-x', `${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-shift', `-${clampedPct.toFixed(1)}%`);
|
||||
patchStyleVar(tooltipEl, '--tip-y', '0px');
|
||||
|
||||
positionTooltipNearAnchor(fallbackX, fallbackY, pointer || lastPointer);
|
||||
armTooltipTracking(wasHidden);
|
||||
}
|
||||
|
||||
function clearHover() {
|
||||
cancelTipTrackRaf();
|
||||
hoveredIdx = -1;
|
||||
lastPointer = null;
|
||||
patchAttr(hoverLine, 'hidden', true);
|
||||
patchAttr(hoverDot, 'hidden', true);
|
||||
patchAttr(tooltipEl, 'hidden', true);
|
||||
@@ -645,7 +660,11 @@ export function createTrendAreaChart() {
|
||||
0,
|
||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||
);
|
||||
showLineHoverAtIndex(idx);
|
||||
const pointer =
|
||||
Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY))
|
||||
? { clientX: Number(e.clientX), clientY: Number(e.clientY) }
|
||||
: null;
|
||||
showLineHoverAtIndex(idx, pointer);
|
||||
}
|
||||
|
||||
function findDirectHeatmapCell(e) {
|
||||
@@ -763,8 +782,12 @@ export function createTrendAreaChart() {
|
||||
clearHover();
|
||||
return;
|
||||
}
|
||||
if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl) {
|
||||
showHeatmapHoverAtIndex(hit.idx, hit.cellEl);
|
||||
const pointer =
|
||||
Number.isFinite(Number(e?.clientX)) && Number.isFinite(Number(e?.clientY))
|
||||
? { clientX: Number(e.clientX), clientY: Number(e.clientY) }
|
||||
: null;
|
||||
if (hit.idx !== hoveredIdx || hit.cellEl !== hoveredCellEl || pointer) {
|
||||
showHeatmapHoverAtIndex(hit.idx, hit.cellEl, pointer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -784,12 +807,43 @@ export function createTrendAreaChart() {
|
||||
}
|
||||
}
|
||||
|
||||
function handleLineClick(e) {
|
||||
if (currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return;
|
||||
let idx = hoveredIdx;
|
||||
const rect = svg.getBoundingClientRect?.();
|
||||
if (rect && rect.width > 0 && Number.isFinite(Number(e?.clientX))) {
|
||||
const relX = ((e.clientX - rect.left) / rect.width) * viewW;
|
||||
const { leftX, spanX } = resolvePlotBounds(viewW);
|
||||
const ratio = (relX - leftX) / Math.max(1, spanX);
|
||||
idx = Math.max(
|
||||
0,
|
||||
Math.min(currentSlots.length - 1, Math.round(ratio * (currentSlots.length - 1)))
|
||||
);
|
||||
}
|
||||
const slot = currentSlots[idx];
|
||||
if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) {
|
||||
onSelectSlot(slot);
|
||||
}
|
||||
}
|
||||
|
||||
function handleHeatmapClick(e) {
|
||||
handleHeatmapPointer(e);
|
||||
if (!currentIsHeatmap || !currentSlots.length || typeof onSelectSlot !== 'function') return;
|
||||
const hit = resolveHeatmapCellFromPointer(e);
|
||||
if (!hit || !Number.isFinite(hit.idx)) return;
|
||||
const slot = currentSlots[hit.idx];
|
||||
if (slot && Number(slot.startMs) > 0 && Number(slot.endMs) > Number(slot.startMs)) {
|
||||
onSelectSlot(slot);
|
||||
}
|
||||
}
|
||||
|
||||
plotStage.addEventListener('mousemove', handlePointerMove);
|
||||
plotStage.addEventListener('click', handleLineClick);
|
||||
plotStage.addEventListener('mouseleave', clearHover);
|
||||
|
||||
hmGridEl.addEventListener('mouseover', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('mousemove', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('click', handleHeatmapPointer);
|
||||
hmGridEl.addEventListener('click', handleHeatmapClick);
|
||||
hmGridEl.addEventListener('mouseleave', clearHover);
|
||||
hmScrollEl.addEventListener('wheel', handleHeatmapWheel);
|
||||
|
||||
@@ -815,6 +869,14 @@ export function createTrendAreaChart() {
|
||||
|
||||
function destroy() {
|
||||
cancelTipTrackRaf();
|
||||
plotStage.removeEventListener('mousemove', handlePointerMove);
|
||||
plotStage.removeEventListener('click', handleLineClick);
|
||||
plotStage.removeEventListener('mouseleave', clearHover);
|
||||
hmGridEl.removeEventListener('mouseover', handleHeatmapPointer);
|
||||
hmGridEl.removeEventListener('mousemove', handleHeatmapPointer);
|
||||
hmGridEl.removeEventListener('click', handleHeatmapClick);
|
||||
hmGridEl.removeEventListener('mouseleave', clearHover);
|
||||
hmScrollEl.removeEventListener('wheel', handleHeatmapWheel);
|
||||
resizeObs?.disconnect();
|
||||
resizeObs = null;
|
||||
if (onWinResize && typeof window !== 'undefined' && typeof window.removeEventListener === 'function') {
|
||||
@@ -887,9 +949,14 @@ export function createTrendAreaChart() {
|
||||
slots
|
||||
.map((s) => {
|
||||
const mSig = Array.isArray(s?.modelSegments)
|
||||
? s.modelSegments.map((m) => `${m.key}:${m.color}:${m.pctText}`).join(',')
|
||||
? s.modelSegments
|
||||
.map(
|
||||
(m) =>
|
||||
`${m.key}:${m.color}:${m.pctText}:${m.inputTokens || 0}:${m.cacheReadTokens || 0}:${m.thinkingTokens || 0}:${m.responseTokens || 0}`
|
||||
)
|
||||
.join(',')
|
||||
: '';
|
||||
return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`;
|
||||
return `${s?.startMs || ''}:${s?.label || ''}:${s?.fullLabel || ''}:${safeSlotTokens(s?.tokens)}:${safeSlotTokens(s?.inputTokens)}:${safeSlotTokens(s?.cacheReadTokens)}:${safeSlotTokens(s?.thinkingTokens)}:${safeSlotTokens(s?.responseTokens)}:${Number(s?.costUsd || 0)}:${Number(s?.calls || 0)}:${mSig}`;
|
||||
})
|
||||
.join('|');
|
||||
|
||||
@@ -989,7 +1056,7 @@ export function createTrendAreaChart() {
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx]);
|
||||
showHeatmapHoverAtIndex(hoveredIdx, currentCellEls[hoveredIdx], lastPointer);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -1055,7 +1122,10 @@ export function createTrendAreaChart() {
|
||||
title: slot.fullLabel || slot.label || '',
|
||||
});
|
||||
patchStyleVar(tickEl, '--tick-x', `${pct.toFixed(2)}%`);
|
||||
tickEl.onclick = () => showLineHoverAtIndex(tIdx);
|
||||
tickEl.onclick = () => {
|
||||
lastPointer = null;
|
||||
showLineHoverAtIndex(tIdx);
|
||||
};
|
||||
xAxisEl.appendChild(tickEl);
|
||||
tickElsByIdx.set(tIdx, tickEl);
|
||||
}
|
||||
@@ -1094,7 +1164,7 @@ export function createTrendAreaChart() {
|
||||
if (hoveredIdx >= slots.length) {
|
||||
clearHover();
|
||||
} else if (hoveredIdx >= 0) {
|
||||
showLineHoverAtIndex(hoveredIdx);
|
||||
showLineHoverAtIndex(hoveredIdx, lastPointer);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -31,6 +31,9 @@ export const TopSessionHeader = defineComponent({
|
||||
const convSelect = CustomSelect({
|
||||
modelValue: telemetryStore.getState().selectedConversationId,
|
||||
placeholder: t('header.followLatest'),
|
||||
searchable: true,
|
||||
searchThreshold: 6,
|
||||
searchPlaceholder: t('header.searchSessionPlaceholder'),
|
||||
options: [{ value: '', label: t('header.followLatest') }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
@@ -236,6 +239,7 @@ export const TopSessionHeader = defineComponent({
|
||||
convSelect.setProps({
|
||||
modelValue: telSt.selectedConversationId,
|
||||
placeholder: t('header.followLatest'),
|
||||
searchPlaceholder: t('header.searchSessionPlaceholder'),
|
||||
options,
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
/**
|
||||
* @fileoverview 消耗统计统一悬浮详情内容组件 (ConsumptionTooltipContent).
|
||||
* 供历史趋势(折线/热力图)、客户端来源、会话排行及月度统计悬浮卡片复用:
|
||||
* 1. 顶部标题/日期行 + 右侧调用次数;
|
||||
* 2. 核心大字总量 (`TOKEN`) + 右侧预估费用;
|
||||
* 3. 分模型明细行(模型名/Token/占比 + 同「模型排行」Token 模式一致的四段构成进度条,不显示多余分组标题);
|
||||
* 4. 底部四通道汇总(输入 / 缓存 / 思考 / 输出)。
|
||||
*/
|
||||
|
||||
import {
|
||||
h,
|
||||
patchAttr,
|
||||
patchClasses,
|
||||
patchKeyedList,
|
||||
patchStyleVar,
|
||||
patchText,
|
||||
} from '../../core/domPatch.js';
|
||||
import { formatTokensPrecise } from '../../core/formatters.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { createFourSegmentBar } from './FourSegmentBar.js';
|
||||
|
||||
function safeNonNeg(val) {
|
||||
const n = Number(val);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
function resolveSegmentChannels(seg) {
|
||||
const inputTokens = safeNonNeg(seg?.inputTokens);
|
||||
const cacheReadTokens = safeNonNeg(seg?.cacheReadTokens);
|
||||
const thinkingTokens = safeNonNeg(seg?.thinkingTokens);
|
||||
const responseTokens =
|
||||
seg?.responseTokens != null
|
||||
? safeNonNeg(seg.responseTokens)
|
||||
: Math.max(0, safeNonNeg(seg?.outputTokens) - thinkingTokens);
|
||||
return { inputTokens, cacheReadTokens, thinkingTokens, responseTokens };
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建可增量更新的消耗统计悬浮详情内容结构。
|
||||
*
|
||||
* @param {{ showModelDot?: boolean, monoTitle?: boolean }} [options]
|
||||
* @returns {{
|
||||
* children: HTMLElement[],
|
||||
* update: (payload: {
|
||||
* title?: string,
|
||||
* calls?: number,
|
||||
* totalTokens?: number,
|
||||
* costText?: string,
|
||||
* inputTokens?: number,
|
||||
* cacheReadTokens?: number,
|
||||
* thinkingTokens?: number,
|
||||
* responseTokens?: number,
|
||||
* outputTokens?: number,
|
||||
* segments?: Array<object>,
|
||||
* }) => void,
|
||||
* }}
|
||||
*/
|
||||
export function createConsumptionBreakdownContent({
|
||||
showModelDot = false,
|
||||
monoTitle = false,
|
||||
} = {}) {
|
||||
const titleEl = h('span', {
|
||||
className: monoTitle ? 'trend-tip-time text-mono' : 'trend-tip-time',
|
||||
});
|
||||
const callsEl = h('span', { className: 'trend-tip-calls text-mono' });
|
||||
const headEl = h('div', { className: 'trend-tip-head cons-tip-head' }, [titleEl, callsEl]);
|
||||
|
||||
const heroNumEl = h('span', { className: 'cons-tip-hero-num', text: '0' });
|
||||
const heroUnitEl = h('span', { className: 'cons-tip-hero-unit', text: ' TOKEN' });
|
||||
const tokensEl = h('strong', { className: 'trend-tip-tokens cons-tip-hero text-mono' }, [
|
||||
heroNumEl,
|
||||
heroUnitEl,
|
||||
]);
|
||||
const costEl = h('span', { className: 'trend-tip-cost text-mono' });
|
||||
const mainEl = h('div', { className: 'trend-tip-main cons-tip-main' }, [tokensEl, costEl]);
|
||||
|
||||
function createModelRow() {
|
||||
const dotEl = h('span', {
|
||||
className: 'dot-swatch cons-model-dot',
|
||||
hidden: !showModelDot,
|
||||
});
|
||||
const nameEl = h('span', { className: 'cons-pop-model-name' });
|
||||
const tokEl = h('span', { className: 'cons-pop-model-tok' });
|
||||
const pctEl = h('strong', { className: 'cons-pop-model-pct' });
|
||||
const segBar = createFourSegmentBar();
|
||||
const rowEl = h('div', { className: 'cons-pop-model-row' }, [
|
||||
h('div', { className: 'cons-pop-model-head' }, [
|
||||
h('span', { className: 'cons-pop-model-left' }, [dotEl, nameEl]),
|
||||
h('span', { className: 'cons-pop-model-right text-mono' }, [tokEl, pctEl]),
|
||||
]),
|
||||
segBar.el,
|
||||
]);
|
||||
return {
|
||||
el: rowEl,
|
||||
refs: { rowEl, dotEl, nameEl, tokEl, pctEl, segBar },
|
||||
};
|
||||
}
|
||||
|
||||
const modelsEl = h('div', { className: 'cons-pop-models', hidden: true });
|
||||
|
||||
const inLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legInput') });
|
||||
const inValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
const cacheLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legCache') });
|
||||
const cacheValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
const thinkLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legThinking') });
|
||||
const thinkValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
const outLabelEl = h('span', { className: 'cons-pop-chan-label', text: t('cons.legOutput') });
|
||||
const outValEl = h('strong', { className: 'cons-pop-chan-val text-mono', text: '0' });
|
||||
|
||||
const channelsEl = h('div', { className: 'cons-pop-channels', hidden: true }, [
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-input' }),
|
||||
inLabelEl,
|
||||
]),
|
||||
inValEl,
|
||||
]),
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-cached' }),
|
||||
cacheLabelEl,
|
||||
]),
|
||||
cacheValEl,
|
||||
]),
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-thinking' }),
|
||||
thinkLabelEl,
|
||||
]),
|
||||
thinkValEl,
|
||||
]),
|
||||
h('div', { className: 'cons-pop-chan' }, [
|
||||
h('span', { className: 'cons-pop-chan-head' }, [
|
||||
h('span', { className: 'dot-swatch seg-output' }),
|
||||
outLabelEl,
|
||||
]),
|
||||
outValEl,
|
||||
]),
|
||||
]);
|
||||
|
||||
function update(payload = {}) {
|
||||
patchText(titleEl, payload.title || '--');
|
||||
patchText(
|
||||
callsEl,
|
||||
t('cons.callsCount', { calls: Math.max(0, Math.floor(Number(payload.calls) || 0)) })
|
||||
);
|
||||
const totalTokens = safeNonNeg(payload.totalTokens);
|
||||
patchText(heroNumEl, formatTokensPrecise(totalTokens));
|
||||
patchText(heroUnitEl, ' TOKEN');
|
||||
patchText(costEl, payload.costText || '');
|
||||
|
||||
const rows = Array.isArray(payload.segments) ? payload.segments : [];
|
||||
patchAttr(modelsEl, 'hidden', rows.length === 0);
|
||||
patchKeyedList(modelsEl, rows, {
|
||||
keyFn: (r) => r.key,
|
||||
sigFn: (r) =>
|
||||
`${showModelDot ? 1 : 0}:${r.key}:${r.label}:${r.color || ''}:${r.tokText}:${r.pctText}:${r.isOther ? 1 : 0}:${r.tok || 0}:${r.inputTokens || 0}:${r.cacheReadTokens || 0}:${r.thinkingTokens || 0}:${r.responseTokens ?? ''}:${r.outputTokens ?? ''}`,
|
||||
createRow: createModelRow,
|
||||
updateRow: (rRefs, r) => {
|
||||
patchClasses(rRefs.rowEl, { 'is-other': Boolean(r.isOther) });
|
||||
patchAttr(rRefs.dotEl, 'hidden', !showModelDot);
|
||||
if (showModelDot) {
|
||||
patchStyleVar(rRefs.dotEl, '--dot-color', r.color);
|
||||
}
|
||||
patchText(rRefs.nameEl, r.label);
|
||||
patchText(rRefs.tokEl, r.tokText);
|
||||
patchText(rRefs.pctEl, r.pctText);
|
||||
|
||||
const segTok = safeNonNeg(r.tok);
|
||||
const pct = Math.max(0, Math.min(100, Number(r.pct) || 0));
|
||||
const scaleRatio = segTok > 0 ? Math.min(1, Math.max(0.008, pct / 100)) : 0;
|
||||
const ch = resolveSegmentChannels(r);
|
||||
const chSum = ch.inputTokens + ch.cacheReadTokens + ch.thinkingTokens + ch.responseTokens;
|
||||
if (chSum > 0) {
|
||||
rRefs.segBar.update({
|
||||
inputTokens: ch.inputTokens,
|
||||
cacheReadTokens: ch.cacheReadTokens,
|
||||
thinkingTokens: ch.thinkingTokens,
|
||||
responseTokens: ch.responseTokens,
|
||||
scaleRatio,
|
||||
});
|
||||
} else if (segTok > 0) {
|
||||
rRefs.segBar.update({
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: segTok,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
scaleRatio,
|
||||
});
|
||||
} else {
|
||||
rRefs.segBar.update({
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
scaleRatio: 0,
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const hasExplicitChannels =
|
||||
payload.inputTokens !== undefined ||
|
||||
payload.cacheReadTokens !== undefined ||
|
||||
payload.thinkingTokens !== undefined ||
|
||||
payload.responseTokens !== undefined ||
|
||||
payload.outputTokens !== undefined;
|
||||
let inTok = safeNonNeg(payload.inputTokens);
|
||||
let cacheTok = safeNonNeg(payload.cacheReadTokens);
|
||||
let thinkTok = safeNonNeg(payload.thinkingTokens);
|
||||
let respTok =
|
||||
payload.responseTokens != null
|
||||
? safeNonNeg(payload.responseTokens)
|
||||
: Math.max(0, safeNonNeg(payload.outputTokens) - thinkTok);
|
||||
let hasChannels = hasExplicitChannels;
|
||||
|
||||
if (!hasChannels && rows.length > 0) {
|
||||
let segIn = 0;
|
||||
let segCache = 0;
|
||||
let segThink = 0;
|
||||
let segResp = 0;
|
||||
for (const seg of rows) {
|
||||
const ch = resolveSegmentChannels(seg);
|
||||
segIn += ch.inputTokens;
|
||||
segCache += ch.cacheReadTokens;
|
||||
segThink += ch.thinkingTokens;
|
||||
segResp += ch.responseTokens;
|
||||
}
|
||||
if (segIn + segCache + segThink + segResp > 0) {
|
||||
inTok = segIn;
|
||||
cacheTok = segCache;
|
||||
thinkTok = segThink;
|
||||
respTok = segResp;
|
||||
hasChannels = true;
|
||||
}
|
||||
}
|
||||
|
||||
const showChannels = totalTokens > 0 && hasChannels;
|
||||
patchAttr(channelsEl, 'hidden', !showChannels);
|
||||
if (showChannels) {
|
||||
patchText(inLabelEl, t('cons.legInput'));
|
||||
patchText(cacheLabelEl, t('cons.legCache'));
|
||||
patchText(thinkLabelEl, t('cons.legThinking'));
|
||||
patchText(outLabelEl, t('cons.legOutput'));
|
||||
patchText(inValEl, formatTokensPrecise(inTok));
|
||||
patchText(cacheValEl, formatTokensPrecise(cacheTok));
|
||||
patchText(thinkValEl, formatTokensPrecise(thinkTok));
|
||||
patchText(outValEl, formatTokensPrecise(respTok));
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
children: [headEl, mainEl, modelsEl, channelsEl],
|
||||
update,
|
||||
};
|
||||
}
|
||||
@@ -51,12 +51,36 @@ function sameStringArray(a, b) {
|
||||
return true;
|
||||
}
|
||||
|
||||
export function filterSelectOptionsByQuery(options = [], rawQuery = '') {
|
||||
const q = String(rawQuery || '').trim().toLowerCase();
|
||||
if (!q) return options;
|
||||
const terms = q.split(/\s+/).filter(Boolean);
|
||||
if (terms.length === 0) return options;
|
||||
const out = [];
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const opt = options[i];
|
||||
if (!opt) continue;
|
||||
const haystack =
|
||||
`${opt.label || ''} ${opt.meta || ''} ${opt.title || ''} ${opt.value || ''}`.toLowerCase();
|
||||
let matched = true;
|
||||
for (let k = 0; k < terms.length; k++) {
|
||||
if (!haystack.includes(terms[k])) {
|
||||
matched = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (matched) out.push(opt);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const CustomSelect = defineComponent({
|
||||
name: 'CustomSelect',
|
||||
setup({ getProps, setProps, emit, onCleanup }) {
|
||||
let isOpen = false;
|
||||
let focusedIndex = -1;
|
||||
let lastOpenMenuLayoutSig = '';
|
||||
let searchQuery = '';
|
||||
|
||||
const initialIcon = getProps().icon;
|
||||
const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 });
|
||||
@@ -81,11 +105,61 @@ export const CustomSelect = defineComponent({
|
||||
[leadIcon, triggerLabel, chevronIcon]
|
||||
);
|
||||
|
||||
const menuEl = h('div', {
|
||||
className: 'select-menu',
|
||||
role: 'listbox',
|
||||
hidden: true,
|
||||
const searchIcon = createSvgIcon('search', { size: 12, className: 'select-search-icon' });
|
||||
const searchInput = h('input', {
|
||||
type: 'text',
|
||||
className: 'select-search-input',
|
||||
autocomplete: 'off',
|
||||
spellcheck: 'false',
|
||||
placeholder: getProps().searchPlaceholder || t('select.searchPlaceholder'),
|
||||
onClick: (e) => e.stopPropagation(),
|
||||
onInput: (e) => {
|
||||
searchQuery = String(e?.target?.value ?? searchInput.value ?? '');
|
||||
focusedIndex = 0;
|
||||
renderMenuOptions();
|
||||
},
|
||||
onKeydown: handleKeydown,
|
||||
});
|
||||
const searchClearBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'select-search-clear',
|
||||
hidden: true,
|
||||
'aria-label': t('select.clearSearch'),
|
||||
onClick: (e) => {
|
||||
e.stopPropagation();
|
||||
clearSearchQuery(true);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('close', { size: 10 })]
|
||||
);
|
||||
const searchWrap = h(
|
||||
'div',
|
||||
{
|
||||
className: 'select-search-wrap',
|
||||
hidden: true,
|
||||
onClick: (e) => e.stopPropagation(),
|
||||
},
|
||||
[searchIcon, searchInput, searchClearBtn]
|
||||
);
|
||||
|
||||
const optionsListEl = h('div', { className: 'select-options-list' });
|
||||
const emptyHintEl = h('div', {
|
||||
className: 'select-empty text-muted',
|
||||
hidden: true,
|
||||
text: t('select.noMatches'),
|
||||
});
|
||||
|
||||
const menuEl = h(
|
||||
'div',
|
||||
{
|
||||
className: 'select-menu',
|
||||
role: 'listbox',
|
||||
hidden: true,
|
||||
},
|
||||
[searchWrap, optionsListEl, emptyHintEl]
|
||||
);
|
||||
|
||||
const initialClass = [
|
||||
'custom-select',
|
||||
@@ -96,6 +170,28 @@ export const CustomSelect = defineComponent({
|
||||
.join(' ');
|
||||
const rootEl = h('div', { className: initialClass }, [triggerBtn, menuEl]);
|
||||
|
||||
function isSearchActiveForOptions(options) {
|
||||
const { searchable = false, searchThreshold = 6 } = getProps();
|
||||
return Boolean(searchable) && options.length >= Math.max(1, Number(searchThreshold) || 6);
|
||||
}
|
||||
|
||||
function getVisibleOptions() {
|
||||
const opts = getProps().options || [];
|
||||
if (!isSearchActiveForOptions(opts) || !searchQuery.trim()) return opts;
|
||||
return filterSelectOptionsByQuery(opts, searchQuery);
|
||||
}
|
||||
|
||||
function clearSearchQuery(refocus = false) {
|
||||
if (!searchQuery && !searchInput.value) return;
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
focusedIndex = 0;
|
||||
renderMenuOptions();
|
||||
if (refocus && typeof searchInput.focus === 'function') {
|
||||
searchInput.focus();
|
||||
}
|
||||
}
|
||||
|
||||
function getSelectedSet() {
|
||||
const { multiple, modelValue, options = [], allValue = '' } = getProps();
|
||||
if (!multiple) {
|
||||
@@ -109,7 +205,7 @@ export const CustomSelect = defineComponent({
|
||||
positionAnchoredPopup(rootEl, triggerBtn, menuEl, {
|
||||
margin: 6,
|
||||
gap: 4,
|
||||
maxHeight: 220,
|
||||
maxHeight: isSearchActiveForOptions(getProps().options || []) ? 268 : 220,
|
||||
minFlipSpace: 140,
|
||||
});
|
||||
}
|
||||
@@ -117,7 +213,7 @@ export const CustomSelect = defineComponent({
|
||||
let boundReposition = false;
|
||||
function handleViewportChange(e) {
|
||||
if (!isOpen) return;
|
||||
if (e?.type === 'scroll' && e.target === menuEl) return;
|
||||
if (e?.type === 'scroll' && (e.target === menuEl || e.target === optionsListEl)) return;
|
||||
positionMenu();
|
||||
}
|
||||
|
||||
@@ -136,7 +232,8 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function buildMenuLayoutSig(options = [], labelText = '') {
|
||||
let sig = `${labelText}|${options.length}`;
|
||||
const searchShown = isSearchActiveForOptions(options) ? 1 : 0;
|
||||
let sig = `${labelText}|${searchShown}|${searchQuery}|${options.length}`;
|
||||
for (let i = 0; i < options.length; i++) {
|
||||
const o = options[i];
|
||||
sig += `|${o?.value ?? ''}:${o?.label ?? ''}:${o?.meta ?? ''}`;
|
||||
@@ -144,9 +241,11 @@ export const CustomSelect = defineComponent({
|
||||
return sig;
|
||||
}
|
||||
|
||||
function toggleOpen(nextOpen) {
|
||||
function toggleOpen(nextOpen, { focusSearch = false } = {}) {
|
||||
isOpen = Boolean(nextOpen);
|
||||
if (isOpen) {
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
const opts = getProps().options || [];
|
||||
const selSet = getSelectedSet();
|
||||
focusedIndex = Math.max(
|
||||
@@ -156,6 +255,8 @@ export const CustomSelect = defineComponent({
|
||||
renderMenuOptions();
|
||||
lastOpenMenuLayoutSig = buildMenuLayoutSig(opts, triggerLabel.textContent || '');
|
||||
} else {
|
||||
searchQuery = '';
|
||||
searchInput.value = '';
|
||||
lastOpenMenuLayoutSig = '';
|
||||
}
|
||||
patchClasses(rootEl, { 'is-open': isOpen });
|
||||
@@ -165,6 +266,13 @@ export const CustomSelect = defineComponent({
|
||||
setRepositionListeners(isOpen);
|
||||
if (isOpen) {
|
||||
positionMenu();
|
||||
if (focusSearch && isSearchActiveForOptions(getProps().options || [])) {
|
||||
queueMicrotask(() => {
|
||||
if (isOpen && typeof searchInput.focus === 'function') {
|
||||
searchInput.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,42 +324,69 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function handleKeydown(e) {
|
||||
const opts = getProps().options || [];
|
||||
if (!opts.length) return;
|
||||
const fromSearchInput = e?.target === searchInput;
|
||||
const visibleOpts = getVisibleOptions();
|
||||
|
||||
if (e.key === 'ArrowDown') {
|
||||
if (!visibleOpts.length && isOpen) return;
|
||||
e.preventDefault();
|
||||
if (!isOpen) {
|
||||
toggleOpen(true);
|
||||
} else {
|
||||
focusedIndex = (focusedIndex + 1) % opts.length;
|
||||
} else if (visibleOpts.length > 0) {
|
||||
focusedIndex = (focusedIndex + 1) % visibleOpts.length;
|
||||
renderMenuOptions();
|
||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
optionsListEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
} else if (e.key === 'ArrowUp') {
|
||||
if (!visibleOpts.length && isOpen) return;
|
||||
e.preventDefault();
|
||||
if (!isOpen) {
|
||||
toggleOpen(true);
|
||||
} else {
|
||||
focusedIndex = (focusedIndex - 1 + opts.length) % opts.length;
|
||||
} else if (visibleOpts.length > 0) {
|
||||
focusedIndex = (focusedIndex - 1 + visibleOpts.length) % visibleOpts.length;
|
||||
renderMenuOptions();
|
||||
menuEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
optionsListEl.children[focusedIndex]?.scrollIntoView?.({ block: 'nearest' });
|
||||
}
|
||||
} else if ((e.key === 'Enter' || (e.key === ' ' && isOpen && getProps().multiple)) && isOpen) {
|
||||
} else if (
|
||||
(e.key === 'Enter' || (!fromSearchInput && e.key === ' ' && isOpen && getProps().multiple)) &&
|
||||
isOpen
|
||||
) {
|
||||
if (!visibleOpts.length) return;
|
||||
e.preventDefault();
|
||||
const target = opts[focusedIndex];
|
||||
const target = visibleOpts[focusedIndex] || visibleOpts[0];
|
||||
if (target) chooseOption(target);
|
||||
} else if (e.key === 'Escape' && isOpen) {
|
||||
e.preventDefault();
|
||||
toggleOpen(false);
|
||||
if (fromSearchInput && searchQuery) {
|
||||
clearSearchQuery(true);
|
||||
} else {
|
||||
toggleOpen(false);
|
||||
if (fromSearchInput && typeof triggerBtn.focus === 'function') {
|
||||
triggerBtn.focus();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderMenuOptions() {
|
||||
const { options = [], multiple = false } = getProps();
|
||||
const { options = [], multiple = false, searchPlaceholder } = getProps();
|
||||
const showSearch = isSearchActiveForOptions(options);
|
||||
const visibleOpts = getVisibleOptions();
|
||||
if (focusedIndex >= visibleOpts.length) {
|
||||
focusedIndex = visibleOpts.length > 0 ? 0 : -1;
|
||||
}
|
||||
patchAttr(searchWrap, 'hidden', !showSearch);
|
||||
patchClasses(menuEl, { 'has-search': showSearch });
|
||||
if (showSearch) {
|
||||
patchAttr(searchInput, 'placeholder', searchPlaceholder || t('select.searchPlaceholder'));
|
||||
patchAttr(searchClearBtn, 'hidden', !searchQuery);
|
||||
patchAttr(searchClearBtn, 'aria-label', t('select.clearSearch'));
|
||||
}
|
||||
patchText(emptyHintEl, t('select.noMatches'));
|
||||
patchAttr(emptyHintEl, 'hidden', !showSearch || visibleOpts.length > 0);
|
||||
const selSet = getSelectedSet();
|
||||
patchAttr(menuEl, 'aria-multiselectable', multiple ? 'true' : null);
|
||||
patchKeyedList(menuEl, options, {
|
||||
patchKeyedList(optionsListEl, visibleOpts, {
|
||||
keyFn: (opt) => opt.value,
|
||||
sigFn: (opt, idx) =>
|
||||
`${multiple}::${opt.value}::${opt.label}::${opt.meta || ''}::${Boolean(opt.disabled)}::${selSet.has(opt.value)}::${idx === focusedIndex}`,
|
||||
@@ -384,10 +519,12 @@ export const CustomSelect = defineComponent({
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: { triggerBtn, triggerLabel, menuEl },
|
||||
refs: { triggerBtn, triggerLabel, menuEl, searchInput, optionsListEl },
|
||||
onPropsChange: syncTriggerAndMenu,
|
||||
methods: {
|
||||
close: () => toggleOpen(false),
|
||||
open: () => toggleOpen(true),
|
||||
openAndFocusSearch: () => toggleOpen(true, { focusSearch: true }),
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
speedReasonText,
|
||||
} from '../../core/formatters.js';
|
||||
import { getEffectiveLocale, t } from '../../i18n/index.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import {
|
||||
DEFAULT_STEP_COLUMN_KEYS,
|
||||
STEP_COLUMN_REGISTRY,
|
||||
@@ -389,6 +390,8 @@ export const StepTableWidget = defineComponent({
|
||||
typeof props.onSelectAgentScopes === 'function' ? props.onSelectAgentScopes : null;
|
||||
const onVirtualHeightChange =
|
||||
typeof props.onVirtualHeightChange === 'function' ? props.onVirtualHeightChange : null;
|
||||
const onSortChange =
|
||||
typeof props.onSortChange === 'function' ? props.onSortChange : null;
|
||||
|
||||
const stepsTheadRow = h('tr');
|
||||
const stepsThead = h('thead', {}, [stepsTheadRow]);
|
||||
@@ -397,16 +400,72 @@ export const StepTableWidget = defineComponent({
|
||||
function syncTableHeaderColumns(colKeys, headerCtx = {}) {
|
||||
const locale = getEffectiveLocale();
|
||||
const fmtKey = normalizeClientStepTokenComboFormat(headerCtx?.stepTokenComboFormat);
|
||||
const activeSortKey = String(headerCtx?.sortKey || '');
|
||||
const activeSortDir = headerCtx?.sortDir === 'asc' || headerCtx?.sortDir === 'desc'
|
||||
? headerCtx.sortDir
|
||||
: '';
|
||||
const ctx = { stepTokenComboFormat: fmtKey };
|
||||
patchKeyedList(stepsTheadRow, colKeys, {
|
||||
keyFn: (colKey) => colKey,
|
||||
sigFn: (colKey) => `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}`,
|
||||
sigFn: (colKey) => {
|
||||
const isSorted = activeSortKey === colKey && Boolean(activeSortDir);
|
||||
return `${locale}:${colKey}:${fmtKey}:${STEP_COLUMN_REGISTRY[colKey].thLabel(ctx)}:${onSortChange ? 1 : 0}:${isSorted ? activeSortDir : ''}`;
|
||||
},
|
||||
createRow: (colKey) => {
|
||||
const th = h('th', { text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx) });
|
||||
return { el: th, refs: { th } };
|
||||
const labelSpan = h('span', {
|
||||
className: 'step-th-label',
|
||||
text: STEP_COLUMN_REGISTRY[colKey].thLabel(ctx),
|
||||
});
|
||||
const sortIcon = createSvgIcon('chevron-down', {
|
||||
size: 10,
|
||||
className: 'step-sort-icon',
|
||||
});
|
||||
patchAttr(sortIcon, 'hidden', true);
|
||||
const innerWrap = h('span', { className: 'step-th-inner' }, [labelSpan, sortIcon]);
|
||||
const th = h('th', {}, [innerWrap]);
|
||||
return { el: th, refs: { th, labelSpan, sortIcon } };
|
||||
},
|
||||
updateRow: (refs, colKey) => {
|
||||
patchText(refs.th, STEP_COLUMN_REGISTRY[colKey].thLabel(ctx));
|
||||
const labelText = STEP_COLUMN_REGISTRY[colKey].thLabel(ctx);
|
||||
patchText(refs.labelSpan, labelText);
|
||||
const sortable = Boolean(
|
||||
onSortChange && typeof STEP_COLUMN_REGISTRY[colKey]?.sortValue === 'function'
|
||||
);
|
||||
const isSorted = sortable && activeSortKey === colKey && Boolean(activeSortDir);
|
||||
patchClasses(refs.th, {
|
||||
'is-sortable': sortable,
|
||||
'is-sorted': isSorted,
|
||||
});
|
||||
patchAttr(
|
||||
refs.th,
|
||||
'aria-sort',
|
||||
isSorted ? (activeSortDir === 'asc' ? 'ascending' : 'descending') : sortable ? 'none' : null
|
||||
);
|
||||
patchAttr(
|
||||
refs.th,
|
||||
'title',
|
||||
sortable ? t('steps.sortClickTip', { col: labelText }) : null
|
||||
);
|
||||
patchAttr(refs.sortIcon, 'hidden', !isSorted);
|
||||
if (isSorted) {
|
||||
patchSvgIcon(refs.sortIcon, activeSortDir === 'asc' ? 'chevron-up' : 'chevron-down');
|
||||
}
|
||||
refs.th.onclick = sortable
|
||||
? () => {
|
||||
const defaultDir = STEP_COLUMN_REGISTRY[colKey]?.defaultSortDir || 'desc';
|
||||
let nextKey = colKey;
|
||||
let nextDir = defaultDir;
|
||||
if (activeSortKey === colKey) {
|
||||
if (activeSortDir === defaultDir) {
|
||||
nextDir = defaultDir === 'desc' ? 'asc' : 'desc';
|
||||
} else {
|
||||
nextKey = '';
|
||||
nextDir = '';
|
||||
}
|
||||
}
|
||||
onSortChange(nextKey, nextDir);
|
||||
}
|
||||
: null;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1414,6 +1473,8 @@ export const StepTableWidget = defineComponent({
|
||||
displaySettings = {},
|
||||
allConversationSteps = null,
|
||||
allowNewRowFade = false,
|
||||
sortKey = '',
|
||||
sortDir = '',
|
||||
} = {}
|
||||
) {
|
||||
const normCascadeId = String(cascadeId || '');
|
||||
@@ -1476,11 +1537,15 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
const colOrderSig = colKeys.join(',');
|
||||
const normTokenFmt = normalizeClientStepTokenComboFormat(stepTokenComboFormat);
|
||||
const normSortKey = String(sortKey || '');
|
||||
const normSortDir = sortDir === 'asc' || sortDir === 'desc' ? sortDir : '';
|
||||
const isCustomSorted = Boolean(normSortKey && normSortDir);
|
||||
const effectiveTurnRail = Boolean(showStepTurnRail && !isCustomSorted);
|
||||
const renderOptions = JSON.stringify([
|
||||
cascadeId, locale, colOrderSig, effectiveScopes, hasSubagents, isMergedMultiAgents,
|
||||
showStepTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt,
|
||||
effectiveTurnRail, showStepAgentBadge, showStepSpeedColor, normTokenFmt,
|
||||
displaySettings.modelDisplayMode, displaySettings.showUpstreamModel,
|
||||
displaySettings.orchestratorIdMode,
|
||||
displaySettings.orchestratorIdMode, normSortKey, normSortDir,
|
||||
]);
|
||||
if (
|
||||
lastRenderOptions === renderOptions &&
|
||||
@@ -1497,7 +1562,11 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
syncFontScaleIfChanged();
|
||||
const wantedSet = new Set(colKeys);
|
||||
syncTableHeaderColumns(colKeys, { stepTokenComboFormat: normTokenFmt });
|
||||
syncTableHeaderColumns(colKeys, {
|
||||
stepTokenComboFormat: normTokenFmt,
|
||||
sortKey: normSortKey,
|
||||
sortDir: normSortDir,
|
||||
});
|
||||
|
||||
const showAgentBadge = Boolean(hasSubagents && showStepAgentBadge);
|
||||
const cellCtx = {
|
||||
@@ -1513,7 +1582,7 @@ export const StepTableWidget = defineComponent({
|
||||
|
||||
const useRootTurn = Boolean(hasSubagents && isMergedMultiAgents);
|
||||
let railActive = false;
|
||||
if (showStepTurnRail) {
|
||||
if (effectiveTurnRail) {
|
||||
for (let i = 0; i < tableSteps.length; i++) {
|
||||
const st = tableSteps[i];
|
||||
const tIdx = useRootTurn ? (st?.rootTurnIndex ?? st?.turnIndex) : st?.turnIndex;
|
||||
@@ -1566,7 +1635,7 @@ export const StepTableWidget = defineComponent({
|
||||
cellCtx,
|
||||
railActive,
|
||||
showAgentBadge,
|
||||
showStepTurnRail,
|
||||
showStepTurnRail: effectiveTurnRail,
|
||||
useRootTurn,
|
||||
isVirtualized,
|
||||
hasReasonFlags,
|
||||
|
||||
@@ -0,0 +1,237 @@
|
||||
/**
|
||||
* @fileoverview 偏好设置便携 JSON 备份及恢复工具 (`settingsBackup.js`).
|
||||
* 仅处理经过白名单归一化的用户界面偏好项,不包含账号凭证及高风险上下文窗口覆盖。
|
||||
*/
|
||||
|
||||
import {
|
||||
normalizeFontScale,
|
||||
normalizeHoverModules,
|
||||
normalizeLanguageSetting,
|
||||
normalizeModelDisplayMode,
|
||||
normalizeModernUi,
|
||||
normalizeOrchestratorIdMode,
|
||||
normalizeOverviewMetrics,
|
||||
normalizeOverviewModules,
|
||||
normalizePluginUpdateMode,
|
||||
normalizePopoverWidth,
|
||||
normalizePopoverWidthMode,
|
||||
normalizeStandalonePort,
|
||||
normalizeStepTableColumns,
|
||||
normalizeStepTokenComboFormat,
|
||||
normalizeThemeAccent,
|
||||
normalizeTopbarCapsuleSlots,
|
||||
normalizeWeeklyLimitMode,
|
||||
normalizeWindowMountMode,
|
||||
} from '../../shared/settings-normalization.mjs';
|
||||
|
||||
const SETTINGS_BACKUP_SCHEMA = 'antigravity-usage-monitor.settings';
|
||||
const MAX_SETTINGS_IMPORT_BYTES = 128 * 1024;
|
||||
|
||||
function sanitizePositiveBudgetNum(val) {
|
||||
const num = Number(val);
|
||||
return Number.isFinite(num) && num > 0 ? num : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在浏览器端通过内存 Blob 触发文件下载(零本地磁盘外部写入)。
|
||||
*
|
||||
* @param {string} filename
|
||||
* @param {string} content
|
||||
* @param {string} [mimeType]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function triggerTextFileDownload(
|
||||
filename,
|
||||
content,
|
||||
mimeType = 'application/json;charset=utf-8'
|
||||
) {
|
||||
try {
|
||||
if (
|
||||
typeof Blob === 'undefined' ||
|
||||
typeof URL === 'undefined' ||
|
||||
typeof URL.createObjectURL !== 'function' ||
|
||||
typeof document === 'undefined'
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
const blob = new Blob([String(content ?? '')], { type: mimeType });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.setAttribute('href', url);
|
||||
a.setAttribute('download', String(filename || 'export.json'));
|
||||
a.style.display = 'none';
|
||||
document.body?.appendChild?.(a);
|
||||
a.click?.();
|
||||
a.remove?.();
|
||||
setTimeout(() => {
|
||||
try {
|
||||
URL.revokeObjectURL(url);
|
||||
} catch {}
|
||||
}, 1000);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将当前用户偏好设置序列化为跨设备可迁移的安全 JSON 备份文本(仅包含便携偏好项,不包含凭证或高风险覆盖开关)。
|
||||
*
|
||||
* @param {object} [settings={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function buildExportableSettingsJson(settings = {}) {
|
||||
const src = settings && typeof settings === 'object' ? settings : {};
|
||||
const modelDisplayMode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
||||
const modernUi = src.modernUi !== undefined ? normalizeModernUi(src.modernUi) : true;
|
||||
const payload = {
|
||||
schema: SETTINGS_BACKUP_SCHEMA,
|
||||
version: 1,
|
||||
exportedAt: new Date().toISOString(),
|
||||
settings: {
|
||||
language: normalizeLanguageSetting(src.language),
|
||||
themeAccent: normalizeThemeAccent(src.themeAccent),
|
||||
fontScale: normalizeFontScale(src.fontScale),
|
||||
modernUi,
|
||||
weeklyLimitMode: normalizeWeeklyLimitMode(src.weeklyLimitMode),
|
||||
weeklyTokenBudget: sanitizePositiveBudgetNum(src.weeklyTokenBudget) ?? 150000000,
|
||||
weeklyCostBudget: sanitizePositiveBudgetNum(src.weeklyCostBudget) ?? 100,
|
||||
modelDisplayMode,
|
||||
showUpstreamModel: modelDisplayMode !== 'short',
|
||||
orchestratorIdMode: normalizeOrchestratorIdMode(src.orchestratorIdMode),
|
||||
pluginUpdateMode: normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin),
|
||||
windowMountMode: normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay),
|
||||
popoverWidthMode: normalizePopoverWidthMode(src.popoverWidthMode),
|
||||
popoverWidth: normalizePopoverWidth(src.popoverWidth),
|
||||
enableCliStatusLine: src.enableCliStatusLine !== false,
|
||||
standalonePort: normalizeStandalonePort(src.standalonePort),
|
||||
showTopbarMultiSession: src.showTopbarMultiSession !== false,
|
||||
topbarCapsuleSlots: normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots),
|
||||
hoverModules: normalizeHoverModules(src.hoverModules),
|
||||
overviewModules: normalizeOverviewModules(src.overviewModules),
|
||||
overviewMetrics: normalizeOverviewMetrics(src.overviewMetrics),
|
||||
showStepTurnRail: src.showStepTurnRail === true,
|
||||
showStepAgentBadge: src.showStepAgentBadge !== false,
|
||||
showStepSpeedColor: src.showStepSpeedColor === true,
|
||||
stepTokenComboFormat: normalizeStepTokenComboFormat(src.stepTokenComboFormat),
|
||||
stepTableColumns: normalizeStepTableColumns(src.stepTableColumns),
|
||||
},
|
||||
};
|
||||
return `${JSON.stringify(payload, null, 2)}\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验并解析导入的偏好设置 JSON,仅提取并归一化白名单内的便携配置项。
|
||||
*
|
||||
* @param {string} rawText
|
||||
* @returns {{ ok: true, patch: object, appliedCount: number } | { ok: false, errorCode: string }}
|
||||
*/
|
||||
export function parseImportedSettingsJson(rawText) {
|
||||
if (typeof rawText !== 'string' || !rawText.trim() || rawText.length > MAX_SETTINGS_IMPORT_BYTES) {
|
||||
return { ok: false, errorCode: 'invalid_json' };
|
||||
}
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(rawText);
|
||||
} catch {
|
||||
return { ok: false, errorCode: 'invalid_json' };
|
||||
}
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return { ok: false, errorCode: 'invalid_json' };
|
||||
}
|
||||
|
||||
const hasWrappedSettings =
|
||||
parsed.settings && typeof parsed.settings === 'object' && !Array.isArray(parsed.settings);
|
||||
if (parsed.schema !== undefined && parsed.schema !== SETTINGS_BACKUP_SCHEMA) {
|
||||
return { ok: false, errorCode: 'invalid_schema' };
|
||||
}
|
||||
const src = hasWrappedSettings ? parsed.settings : parsed;
|
||||
const hasKey = (k) => Object.prototype.hasOwnProperty.call(src, k);
|
||||
const patch = {};
|
||||
|
||||
if (hasKey('language')) patch.language = normalizeLanguageSetting(src.language);
|
||||
if (hasKey('themeAccent')) patch.themeAccent = normalizeThemeAccent(src.themeAccent);
|
||||
if (hasKey('fontScale')) patch.fontScale = normalizeFontScale(src.fontScale);
|
||||
if (hasKey('modernUi')) {
|
||||
const val = normalizeModernUi(src.modernUi);
|
||||
patch.modernUi = val;
|
||||
patch.experimentalModernUi = val;
|
||||
}
|
||||
if (hasKey('weeklyLimitMode')) {
|
||||
patch.weeklyLimitMode = normalizeWeeklyLimitMode(src.weeklyLimitMode);
|
||||
}
|
||||
if (hasKey('weeklyTokenBudget')) {
|
||||
const num = sanitizePositiveBudgetNum(src.weeklyTokenBudget);
|
||||
if (num !== null) patch.weeklyTokenBudget = num;
|
||||
}
|
||||
if (hasKey('weeklyCostBudget')) {
|
||||
const num = sanitizePositiveBudgetNum(src.weeklyCostBudget);
|
||||
if (num !== null) patch.weeklyCostBudget = num;
|
||||
}
|
||||
if (hasKey('modelDisplayMode') || hasKey('showUpstreamModel')) {
|
||||
const mode = normalizeModelDisplayMode(src.modelDisplayMode, src.showUpstreamModel);
|
||||
patch.modelDisplayMode = mode;
|
||||
patch.showUpstreamModel = mode !== 'short';
|
||||
}
|
||||
if (hasKey('orchestratorIdMode')) {
|
||||
patch.orchestratorIdMode = normalizeOrchestratorIdMode(src.orchestratorIdMode);
|
||||
}
|
||||
if (hasKey('pluginUpdateMode') || hasKey('autoUpdatePlugin')) {
|
||||
const mode = normalizePluginUpdateMode(src.pluginUpdateMode, src.autoUpdatePlugin);
|
||||
patch.pluginUpdateMode = mode;
|
||||
patch.autoUpdatePlugin = mode === 'auto';
|
||||
}
|
||||
if (hasKey('windowMountMode') || hasKey('enableWindowOverlay')) {
|
||||
const mode = normalizeWindowMountMode(src.windowMountMode, src.enableWindowOverlay);
|
||||
patch.windowMountMode = mode;
|
||||
patch.enableWindowOverlay = mode !== 'sidebar';
|
||||
}
|
||||
if (hasKey('popoverWidthMode')) {
|
||||
patch.popoverWidthMode = normalizePopoverWidthMode(src.popoverWidthMode);
|
||||
}
|
||||
if (hasKey('popoverWidth')) {
|
||||
patch.popoverWidth = normalizePopoverWidth(src.popoverWidth);
|
||||
}
|
||||
if (hasKey('enableCliStatusLine') && typeof src.enableCliStatusLine === 'boolean') {
|
||||
patch.enableCliStatusLine = src.enableCliStatusLine;
|
||||
}
|
||||
if (hasKey('standalonePort')) {
|
||||
patch.standalonePort = normalizeStandalonePort(src.standalonePort);
|
||||
}
|
||||
if (hasKey('showTopbarMultiSession') && typeof src.showTopbarMultiSession === 'boolean') {
|
||||
patch.showTopbarMultiSession = src.showTopbarMultiSession;
|
||||
}
|
||||
if (hasKey('topbarCapsuleSlots') && Array.isArray(src.topbarCapsuleSlots)) {
|
||||
patch.topbarCapsuleSlots = normalizeTopbarCapsuleSlots(src.topbarCapsuleSlots);
|
||||
}
|
||||
if (hasKey('hoverModules') && Array.isArray(src.hoverModules)) {
|
||||
patch.hoverModules = normalizeHoverModules(src.hoverModules);
|
||||
}
|
||||
if (hasKey('overviewModules') && Array.isArray(src.overviewModules)) {
|
||||
patch.overviewModules = normalizeOverviewModules(src.overviewModules);
|
||||
}
|
||||
if (hasKey('overviewMetrics') && Array.isArray(src.overviewMetrics)) {
|
||||
patch.overviewMetrics = normalizeOverviewMetrics(src.overviewMetrics);
|
||||
}
|
||||
if (hasKey('showStepTurnRail') && typeof src.showStepTurnRail === 'boolean') {
|
||||
patch.showStepTurnRail = src.showStepTurnRail;
|
||||
}
|
||||
if (hasKey('showStepAgentBadge') && typeof src.showStepAgentBadge === 'boolean') {
|
||||
patch.showStepAgentBadge = src.showStepAgentBadge;
|
||||
}
|
||||
if (hasKey('showStepSpeedColor') && typeof src.showStepSpeedColor === 'boolean') {
|
||||
patch.showStepSpeedColor = src.showStepSpeedColor;
|
||||
}
|
||||
if (hasKey('stepTokenComboFormat')) {
|
||||
patch.stepTokenComboFormat = normalizeStepTokenComboFormat(src.stepTokenComboFormat);
|
||||
}
|
||||
if (hasKey('stepTableColumns') && Array.isArray(src.stepTableColumns)) {
|
||||
patch.stepTableColumns = normalizeStepTableColumns(src.stepTableColumns);
|
||||
}
|
||||
|
||||
const appliedCount = Object.keys(patch).length;
|
||||
if (appliedCount === 0) {
|
||||
return { ok: false, errorCode: 'empty_patch' };
|
||||
}
|
||||
return { ok: true, patch, appliedCount };
|
||||
}
|
||||
@@ -32,6 +32,10 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'header.statusQuotaCached': 'Quota Cached',
|
||||
'header.statusQuotaOffline': 'Quota Offline',
|
||||
'header.statusLive': 'Monitoring',
|
||||
'header.searchSessionPlaceholder': 'Search sessions by title or ID…',
|
||||
'select.searchPlaceholder': 'Filter options…',
|
||||
'select.noMatches': 'No matching items',
|
||||
'select.clearSearch': 'Clear search',
|
||||
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': 'N/A',
|
||||
@@ -253,6 +257,26 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'cons.footOutput': 'Out ',
|
||||
'cons.footThinking': 'Think ',
|
||||
'cons.footCalls': 'Calls ',
|
||||
'cons.rankTabAria': 'Switch ranking view',
|
||||
'cons.rankTabModelsCount': 'Models ({count})',
|
||||
'cons.rankTabSessions': 'Sessions',
|
||||
'cons.rankTabSessionsCount': 'Sessions ({count})',
|
||||
'cons.topConvsEmpty': 'No session usage in this range',
|
||||
'cons.topConvsSortAria': 'Sort sessions ranking',
|
||||
'cons.topConvsSortCost': 'Cost',
|
||||
'cons.topConvsSortTokens': 'Tokens',
|
||||
'cons.topConvCacheMeta': 'Cache {pct}%',
|
||||
'cons.topConvJumpTip': 'Click to inspect this session in Steps',
|
||||
'cons.modelsSortAria': 'Sort models ranking',
|
||||
'cons.modelsSortTokens': 'Tokens',
|
||||
'cons.modelsSortCost': 'Cost',
|
||||
'cons.modelsSortSpeed': 'Speed',
|
||||
'cons.modelsSortCalls': 'Calls',
|
||||
'cons.modelUnitCost': 'Eff. {cost}/1M',
|
||||
'cons.speedRelTip': 'Speed relative to fastest model in this range',
|
||||
'cons.focusTtft': 'TTFT {ttft}',
|
||||
'cons.focusSpeedMeta': 'TTFT {ttft} · Cache {cache}% · Out {out}',
|
||||
'cons.focusCallsMeta': 'Avg {avgTok}/call · Cost {cost}',
|
||||
|
||||
// Steps Detail View & Step Column Registry
|
||||
'steps.title': 'Step Records',
|
||||
@@ -337,6 +361,7 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'steps.anomalySummaryMeta': '{count} retries/errors ({steps} steps)',
|
||||
'steps.anomalyFilterLabel': 'Anomalies Only ({count})',
|
||||
'steps.anomalyFilterAll': 'Show All Steps',
|
||||
'steps.sortClickTip': 'Click to sort by {col}',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': 'Step',
|
||||
@@ -606,6 +631,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
|
||||
'settings.oth.resetConfirmBtn': 'Click Again to Confirm',
|
||||
'settings.oth.resettingBtn': 'Resetting…',
|
||||
'settings.oth.resetAllDone': 'All preferences restored to defaults',
|
||||
'settings.oth.backupLabel': 'Preferences Backup & Restore',
|
||||
'settings.oth.backupDesc': 'Export or import portable UI, capsule, and table preferences as JSON (excludes credentials)',
|
||||
'settings.oth.exportJsonBtn': 'Export JSON',
|
||||
'settings.oth.importJsonBtn': 'Import JSON',
|
||||
'settings.oth.exportDone': 'Preferences JSON exported',
|
||||
'settings.oth.importDone': 'Restored {count} preference settings',
|
||||
'settings.oth.importInvalid': 'Import failed: invalid JSON or no recognized settings',
|
||||
|
||||
// Structured Live Activity Actions
|
||||
'live.act.run_command': 'Run Command',
|
||||
|
||||
@@ -32,6 +32,10 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'header.statusQuotaCached': '额度缓存',
|
||||
'header.statusQuotaOffline': '额度离线',
|
||||
'header.statusLive': '监控中',
|
||||
'header.searchSessionPlaceholder': '搜索会话标题或 ID…',
|
||||
'select.searchPlaceholder': '输入关键词筛选…',
|
||||
'select.noMatches': '没有匹配的选项',
|
||||
'select.clearSearch': '清空搜索',
|
||||
|
||||
// Formatters & Common Labels
|
||||
'fmt.pending': '待定',
|
||||
@@ -253,6 +257,26 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'cons.footOutput': '输出 ',
|
||||
'cons.footThinking': '思考 ',
|
||||
'cons.footCalls': '调用 ',
|
||||
'cons.rankTabAria': '排行视图切换',
|
||||
'cons.rankTabModelsCount': '模型排行 ({count})',
|
||||
'cons.rankTabSessions': '会话排行',
|
||||
'cons.rankTabSessionsCount': '会话排行 ({count})',
|
||||
'cons.topConvsEmpty': '当前时间范围暂无会话消耗记录',
|
||||
'cons.topConvsSortAria': '会话排行排序方式',
|
||||
'cons.topConvsSortCost': '费用',
|
||||
'cons.topConvsSortTokens': 'Token',
|
||||
'cons.topConvCacheMeta': '缓存 {pct}%',
|
||||
'cons.topConvJumpTip': '点击跳转到该会话调用记录',
|
||||
'cons.modelsSortAria': '模型排行排序方式',
|
||||
'cons.modelsSortTokens': 'Token',
|
||||
'cons.modelsSortCost': '费用',
|
||||
'cons.modelsSortSpeed': '均速',
|
||||
'cons.modelsSortCalls': '调用',
|
||||
'cons.modelUnitCost': '均价 {cost}/1M',
|
||||
'cons.speedRelTip': '相对本时段最快模型的均速比例',
|
||||
'cons.focusTtft': '首字 {ttft}',
|
||||
'cons.focusSpeedMeta': '首字 {ttft} · 缓存 {cache}% · 输出 {out}',
|
||||
'cons.focusCallsMeta': '单次均耗 {avgTok} · 费用 {cost}',
|
||||
|
||||
// Steps Detail View & Step Column Registry
|
||||
'steps.title': '调用记录',
|
||||
@@ -337,6 +361,7 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'steps.anomalySummaryMeta': '异常 {count} 次({steps} 步)',
|
||||
'steps.anomalyFilterLabel': '仅看异常 ({count})',
|
||||
'steps.anomalyFilterAll': '返回全部步骤',
|
||||
'steps.sortClickTip': '点击按「{col}」排序',
|
||||
|
||||
// Step Table Columns (Headers & Option Labels)
|
||||
'stepCol.step.th': '步序',
|
||||
@@ -606,6 +631,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
|
||||
'settings.oth.resetConfirmBtn': '再次点击确认重置',
|
||||
'settings.oth.resettingBtn': '重置中…',
|
||||
'settings.oth.resetAllDone': '已恢复全部默认设置',
|
||||
'settings.oth.backupLabel': '配置备份及恢复',
|
||||
'settings.oth.backupDesc': '导出或导入外观、胶囊、列配置等便携偏好 JSON(不含账号凭证)',
|
||||
'settings.oth.exportJsonBtn': '导出 JSON',
|
||||
'settings.oth.importJsonBtn': '导入 JSON',
|
||||
'settings.oth.exportDone': '配置 JSON 已导出',
|
||||
'settings.oth.importDone': '已恢复 {count} 项偏好设置',
|
||||
'settings.oth.importInvalid': '导入失败:JSON 无效或未包含可识别的偏好项',
|
||||
|
||||
// Structured Live Activity Actions
|
||||
'live.act.run_command': '执行命令',
|
||||
|
||||
@@ -93,6 +93,18 @@ export const SVG_ICON_DEFS = Object.freeze({
|
||||
{ tag: 'rect', attrs: { x: '5.2', y: '5.2', width: '8.3', height: '8.3', rx: '1.3' } },
|
||||
{ tag: 'path', attrs: { d: 'M3.5 10.8H2.8a1.3 1.3 0 0 1-1.3-1.3V3.3A1.3 1.3 0 0 1 2.8 2h6.2a1.3 1.3 0 0 1 1.3 1.3v.7' } },
|
||||
],
|
||||
search: [
|
||||
{ tag: 'circle', attrs: { cx: '7.2', cy: '7.2', r: '4.5' } },
|
||||
{ tag: 'path', attrs: { d: 'M10.6 10.6L14 14' } },
|
||||
],
|
||||
download: [
|
||||
{ tag: 'path', attrs: { d: 'M8 2.4v7.6M5 7.2L8 10.2l3-3' } },
|
||||
{ tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } },
|
||||
],
|
||||
upload: [
|
||||
{ tag: 'path', attrs: { d: 'M8 10.2V2.6M5 5.4L8 2.4l3 3' } },
|
||||
{ tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } },
|
||||
],
|
||||
grip: [
|
||||
{ tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
{ tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
|
||||
|
||||
@@ -34,7 +34,7 @@ const DEFAULT_CLIENT_STEP_TOKEN_COMBO_FORMAT = DEFAULT_STEP_TOKEN_COMBO_FORMAT;
|
||||
const normalizeClientStepTokenComboFormat = normalizeStepTokenComboFormat;
|
||||
const parseClientStepTokenComboSegments = parseStepTokenComboSegments;
|
||||
|
||||
function resolveStepTokenParts(st) {
|
||||
export function resolveStepTokenParts(st) {
|
||||
const inTok = Math.max(0, Number(st?.inputTokens || 0));
|
||||
const cacheTok = Math.max(0, Number(st?.cacheReadTokens || 0));
|
||||
const outTok = Math.max(0, Number(st?.outputTokens || 0));
|
||||
@@ -48,6 +48,14 @@ function resolveStepTokenParts(st) {
|
||||
return { inTok, cacheTok, outTok, thinkTok, respTok, totalTok, ctxTok };
|
||||
}
|
||||
|
||||
function finiteSortNum(val, { allowZero = true } = {}) {
|
||||
if (val == null || val === '') return null;
|
||||
const num = Number(val);
|
||||
if (!Number.isFinite(num)) return null;
|
||||
if (!allowZero && !(num > 0)) return null;
|
||||
return num;
|
||||
}
|
||||
|
||||
function formatPartWithOptionalCost(tokCount, costVal) {
|
||||
const countStr = Math.round(Number(tokCount || 0)).toLocaleString();
|
||||
if (costVal != null && Number.isFinite(Number(costVal))) {
|
||||
@@ -127,6 +135,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.step.th'),
|
||||
optLabel: () => t('stepCol.step.opt'),
|
||||
sigPart: (st) => `${st.stepIndex}`,
|
||||
sortValue: (st) => finiteSortNum(st?.stepIndex),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -142,6 +151,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.time.th'),
|
||||
optLabel: () => t('stepCol.time.opt'),
|
||||
sigPart: (st) => `${st.createdAtMs || 0}`,
|
||||
sortValue: (st) => finiteSortNum(st?.createdAtMs, { allowZero: false }),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', { className: 'text-muted' }, [valEl]);
|
||||
@@ -158,10 +168,15 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
key: 'model',
|
||||
thLabel: () => t('stepCol.model.th'),
|
||||
optLabel: () => t('stepCol.model.opt'),
|
||||
defaultSortDir: 'asc',
|
||||
sigPart: (st, ctx) => {
|
||||
const disp = resolveModelDisplayInfo(st, ctx.displaySettings, { fallback: '—' });
|
||||
return `${disp.baseText}:${disp.title}`;
|
||||
},
|
||||
sortValue: (st, ctx) => {
|
||||
const disp = resolveModelDisplayInfo(st, ctx?.displaySettings, { fallback: '' });
|
||||
return String(disp.baseText || '').toLowerCase() || null;
|
||||
},
|
||||
createCell: () => {
|
||||
const nameEl = h('span', { className: 'step-model-name' });
|
||||
const wrapEl = h('span', { className: 'step-model-cell' }, [nameEl]);
|
||||
@@ -181,6 +196,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
optLabel: () => t('stepCol.tps.opt'),
|
||||
sigPart: (st, ctx) =>
|
||||
`${st.tokPerSec}:${st.selectedSpeedReason || ''}:${ctx?.showStepSpeedColor === true ? 1 : 0}`,
|
||||
sortValue: (st) => finiteSortNum(st?.tokPerSec, { allowZero: false }),
|
||||
createCell: () => {
|
||||
const speedMain = h('strong', {
|
||||
className: 'cell-value tone-muted',
|
||||
@@ -225,6 +241,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.ttft.th'),
|
||||
optLabel: () => t('stepCol.ttft.opt'),
|
||||
sigPart: (st) => `${st.ttftSec}`,
|
||||
sortValue: (st) => finiteSortNum(st?.ttftSec),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -242,6 +259,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.duration.th'),
|
||||
optLabel: () => t('stepCol.duration.opt'),
|
||||
sigPart: (st) => `${st.totalDurationSec ?? st.streamDurationSec ?? ''}`,
|
||||
sortValue: (st) => finiteSortNum(st?.totalDurationSec ?? st?.streamDurationSec),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -259,6 +277,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
optLabel: () => t('stepCol.tokens_combo.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.contextTokens}:${st.outputTokens}:${st.thinkingTokens}:${st.responseTokens}`,
|
||||
sortValue: (st) => resolveStepTokenParts(st).ctxTok,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -288,6 +307,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
optLabel: () => t('stepCol.tokens_io_cache.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.inputTokens || 0}:${st.outputTokens || 0}:${st.cacheReadTokens || 0}:${st.inCostUsd ?? ''}:${st.outCostUsd ?? ''}:${st.cacheCostUsd ?? ''}`,
|
||||
sortValue: (st) => resolveStepTokenParts(st).totalTok,
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -320,6 +340,19 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
}),
|
||||
sigPart: (st, ctx) =>
|
||||
`${normalizeClientStepTokenComboFormat(ctx?.stepTokenComboFormat)}:${st.contextTokens || 0}:${st.inputTokens || 0}:${st.cacheReadTokens || 0}:${st.outputTokens || 0}:${st.thinkingTokens || 0}:${st.responseTokens ?? ''}:${st.costUsd ?? ''}`,
|
||||
sortValue: (st, ctx) => {
|
||||
const firstSeg = parseClientStepTokenComboSegments(ctx?.stepTokenComboFormat)[0] || 'total';
|
||||
const parts = resolveStepTokenParts(st);
|
||||
switch (firstSeg) {
|
||||
case 'context': return parts.ctxTok;
|
||||
case 'in': return parts.inTok;
|
||||
case 'out': return parts.outTok;
|
||||
case 'cache': return parts.cacheTok;
|
||||
case 'think': return parts.thinkTok;
|
||||
case 'reply': return parts.respTok;
|
||||
default: return parts.totalTok;
|
||||
}
|
||||
},
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -346,6 +379,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.input_tokens.th'),
|
||||
optLabel: () => t('stepCol.input_tokens.opt'),
|
||||
sigPart: (st) => `${st.inputTokens || 0}`,
|
||||
sortValue: (st) => finiteSortNum(st?.inputTokens ?? 0),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -361,6 +395,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.cache_tokens.th'),
|
||||
optLabel: () => t('stepCol.cache_tokens.opt'),
|
||||
sigPart: (st) => `${st.cacheReadTokens || 0}`,
|
||||
sortValue: (st) => finiteSortNum(st?.cacheReadTokens ?? 0),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -376,6 +411,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.output_tokens.th'),
|
||||
optLabel: () => t('stepCol.output_tokens.opt'),
|
||||
sigPart: (st) => `${st.outputTokens || 0}`,
|
||||
sortValue: (st) => finiteSortNum(st?.outputTokens ?? 0),
|
||||
createCell: () => {
|
||||
const valEl = h('span');
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -392,6 +428,10 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
optLabel: () => t('stepCol.cache.opt'),
|
||||
sigPart: (st) =>
|
||||
`${st.cacheHitPct ?? 0}:${(st.inputTokens || 0) + (st.cacheReadTokens || 0) > 0 ? 1 : 0}`,
|
||||
sortValue: (st) => {
|
||||
const prompt = Number(st?.inputTokens || 0) + Number(st?.cacheReadTokens || 0);
|
||||
return prompt > 0 ? finiteSortNum(st?.cacheHitPct ?? 0) : null;
|
||||
},
|
||||
createCell: () => {
|
||||
const valEl = h('span', {
|
||||
className: 'cell-value tone-muted',
|
||||
@@ -416,6 +456,7 @@ export const STEP_COLUMN_REGISTRY = Object.freeze({
|
||||
thLabel: () => t('stepCol.cost.th'),
|
||||
optLabel: () => t('stepCol.cost.opt'),
|
||||
sigPart: (st) => `${st.costUsd}`,
|
||||
sortValue: (st) => finiteSortNum(st?.costUsd),
|
||||
createCell: () => {
|
||||
const valEl = h('span', { style: 'font-weight: 600;' });
|
||||
const td = h('td', {}, [valEl]);
|
||||
@@ -439,3 +480,42 @@ export function getStepColumnOptions(
|
||||
label: STEP_COLUMN_REGISTRY[key].optLabel(ctx),
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按指定列对步骤数组进行稳定排序(空值/不可用测速值始终置底)。
|
||||
*
|
||||
* @param {Array<object>} steps
|
||||
* @param {string} sortKey
|
||||
* @param {'asc'|'desc'|''} sortDir
|
||||
* @param {object} [ctx]
|
||||
* @returns {Array<object>}
|
||||
*/
|
||||
export function sortStepsByColumn(steps, sortKey, sortDir, ctx = {}) {
|
||||
if (!Array.isArray(steps) || steps.length <= 1 || !sortKey || !sortDir) {
|
||||
return Array.isArray(steps) ? steps : [];
|
||||
}
|
||||
const col = STEP_COLUMN_REGISTRY[sortKey];
|
||||
if (!col || typeof col.sortValue !== 'function') return steps;
|
||||
const mul = sortDir === 'asc' ? 1 : -1;
|
||||
const decorated = steps.map((st, origIdx) => ({
|
||||
st,
|
||||
origIdx,
|
||||
val: col.sortValue(st, ctx),
|
||||
}));
|
||||
decorated.sort((a, b) => {
|
||||
const aNull = a.val === null || a.val === undefined;
|
||||
const bNull = b.val === null || b.val === undefined;
|
||||
if (aNull && bNull) return a.origIdx - b.origIdx;
|
||||
if (aNull) return 1;
|
||||
if (bNull) return -1;
|
||||
let cmp = 0;
|
||||
if (typeof a.val === 'string' || typeof b.val === 'string') {
|
||||
cmp = String(a.val).localeCompare(String(b.val));
|
||||
} else {
|
||||
cmp = Number(a.val) - Number(b.val);
|
||||
}
|
||||
if (cmp !== 0) return cmp * mul;
|
||||
return a.origIdx - b.origIdx;
|
||||
});
|
||||
return decorated.map((d) => d.st);
|
||||
}
|
||||
|
||||
@@ -354,6 +354,7 @@ function recordConsumptionSliceToCache(
|
||||
account: cons.account,
|
||||
trendSeries: Array.isArray(cons.trendSeries) ? cons.trendSeries : [],
|
||||
sourcesBreakdown: Array.isArray(cons.sourcesBreakdown) ? cons.sourcesBreakdown : [],
|
||||
topConversations: Array.isArray(cons.topConversations) ? cons.topConversations : [],
|
||||
modelBreakdown: Array.isArray(modelBreakdown) ? modelBreakdown : [],
|
||||
});
|
||||
}
|
||||
@@ -371,6 +372,9 @@ function applyCachedConsumptionSlice(baseTelemetry, cachedEntry, targetRevision
|
||||
account: cachedEntry.account ?? prevCons.account,
|
||||
trendSeries: cachedEntry.trendSeries,
|
||||
sourcesBreakdown: cachedEntry.sourcesBreakdown,
|
||||
topConversations: Array.isArray(cachedEntry.topConversations)
|
||||
? cachedEntry.topConversations
|
||||
: [],
|
||||
},
|
||||
modelBreakdown: cachedEntry.modelBreakdown,
|
||||
};
|
||||
@@ -847,7 +851,14 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
a[k]?.costUsd !== b[k]?.costUsd ||
|
||||
a[k]?.unpricedCalls !== b[k]?.unpricedCalls ||
|
||||
a[k]?.totalTokens !== b[k]?.totalTokens ||
|
||||
a[k]?.inputTokens !== b[k]?.inputTokens ||
|
||||
a[k]?.cacheReadTokens !== b[k]?.cacheReadTokens ||
|
||||
a[k]?.thinkingTokens !== b[k]?.thinkingTokens ||
|
||||
a[k]?.responseTokens !== b[k]?.responseTokens ||
|
||||
a[k]?.calls !== b[k]?.calls ||
|
||||
(a[k]?.avgTokPerSec ?? null) !== (b[k]?.avgTokPerSec ?? null) ||
|
||||
(a[k]?.avgTtftSec ?? null) !== (b[k]?.avgTtftSec ?? null) ||
|
||||
(a[k]?.cacheHitPct ?? null) !== (b[k]?.cacheHitPct ?? null) ||
|
||||
Number(a[k]?.anomalyCount || 0) !== Number(b[k]?.anomalyCount || 0) ||
|
||||
Number(a[k]?.anomalySteps || 0) !== Number(b[k]?.anomalySteps || 0)
|
||||
) {
|
||||
@@ -863,6 +874,10 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
for (let i = 0; i < pTrend.length; i++) {
|
||||
if (
|
||||
pTrend[i]?.tokens !== nTrend[i]?.tokens ||
|
||||
pTrend[i]?.inputTokens !== nTrend[i]?.inputTokens ||
|
||||
pTrend[i]?.cacheReadTokens !== nTrend[i]?.cacheReadTokens ||
|
||||
pTrend[i]?.thinkingTokens !== nTrend[i]?.thinkingTokens ||
|
||||
pTrend[i]?.responseTokens !== nTrend[i]?.responseTokens ||
|
||||
pTrend[i]?.calls !== nTrend[i]?.calls ||
|
||||
pTrend[i]?.label !== nTrend[i]?.label ||
|
||||
pTrend[i]?.fullLabel !== nTrend[i]?.fullLabel ||
|
||||
@@ -911,6 +926,22 @@ export function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
}
|
||||
|
||||
const pTopConvs = prev.consumption?.topConversations || [];
|
||||
const nTopConvs = next.consumption?.topConversations || [];
|
||||
if (pTopConvs.length !== nTopConvs.length) return false;
|
||||
for (let i = 0; i < pTopConvs.length; i++) {
|
||||
if (
|
||||
pTopConvs[i]?.cascadeId !== nTopConvs[i]?.cascadeId ||
|
||||
pTopConvs[i]?.title !== nTopConvs[i]?.title ||
|
||||
pTopConvs[i]?.totalTokens !== nTopConvs[i]?.totalTokens ||
|
||||
pTopConvs[i]?.costUsd !== nTopConvs[i]?.costUsd ||
|
||||
pTopConvs[i]?.calls !== nTopConvs[i]?.calls ||
|
||||
!areModelSlicesEqual(pTopConvs[i]?.models, nTopConvs[i]?.models)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 比对账号订阅档位与动态多配额池
|
||||
if (
|
||||
prev.account?.email !== next.account?.email ||
|
||||
@@ -1223,6 +1254,7 @@ async function requestTelemetry(params, force) {
|
||||
account: latestSt.telemetry.consumption.account,
|
||||
trendSeries: latestSt.telemetry.consumption.trendSeries,
|
||||
sourcesBreakdown: latestSt.telemetry.consumption.sourcesBreakdown,
|
||||
topConversations: latestSt.telemetry.consumption.topConversations,
|
||||
},
|
||||
modelBreakdown: latestSt.telemetry.modelBreakdown,
|
||||
};
|
||||
|
||||
@@ -83,6 +83,10 @@ input[type="number"]::-webkit-outer-spin-button {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.app-shell:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
html[data-standalone="true"] .app-shell {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
|
||||
@@ -369,6 +369,100 @@
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-menu.has-search {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 268px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.select-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 4px 7px;
|
||||
margin-bottom: 4px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-bg);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-search-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.select-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-md);
|
||||
line-height: 1.3;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.select-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.select-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-pill);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.select-search-clear[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-options-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.select-menu.has-search .select-options-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.select-empty {
|
||||
padding: 12px 8px;
|
||||
text-align: center;
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.select-empty[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -474,8 +474,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-pop-models {
|
||||
border-top-color: var(--modern-surface-hover);
|
||||
[data-modern-ui="true"] .cons-pop-channels {
|
||||
border-top-color: color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar,
|
||||
@@ -706,6 +706,15 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
animation: anim-modern-tip-fade 120ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-search-wrap {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-search-wrap:focus-within {
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 50%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-menu.is-above,
|
||||
[data-modern-ui="true"] .dt-popover.is-above {
|
||||
transform-origin: bottom right;
|
||||
@@ -732,6 +741,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip.is-rich-breakdown {
|
||||
top: 0;
|
||||
bottom: auto;
|
||||
transform: translate3d(var(--tip-shift, 0px), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip.is-tracking {
|
||||
transition:
|
||||
left 150ms var(--ease-modern),
|
||||
|
||||
@@ -258,6 +258,44 @@
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.cons-seg-bar[hidden],
|
||||
.cons-item-foot[hidden],
|
||||
.cons-share-pill[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-metric-fill.tone-cost {
|
||||
background-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.cons-metric-fill.tone-speed {
|
||||
background-color: var(--metric-ok);
|
||||
}
|
||||
|
||||
.cons-metric-fill.tone-calls {
|
||||
background-color: var(--ctx-cached);
|
||||
}
|
||||
|
||||
.cons-model-focus-foot {
|
||||
justify-content: space-between;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.cons-model-focus-left {
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cons-model-focus-right {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
/* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */
|
||||
.trend-chart-wrap {
|
||||
position: relative;
|
||||
@@ -274,6 +312,10 @@
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.trend-plot-stage.is-clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.trend-svg {
|
||||
width: 100%;
|
||||
height: 184px;
|
||||
@@ -689,6 +731,29 @@
|
||||
}
|
||||
|
||||
/* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */
|
||||
.cons-ranking-head {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
}
|
||||
|
||||
.cons-ranking-sort-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cons-ranking-sort-wrap .segmented[hidden],
|
||||
.cons-item-list[hidden],
|
||||
.cons-ranking-empty[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-ranking-empty {
|
||||
padding: var(--space-4) 0;
|
||||
text-align: center;
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.cons-item-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -701,6 +766,37 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cons-top-conv-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
width: 100%;
|
||||
container-type: inline-size;
|
||||
background: transparent;
|
||||
border-radius: var(--radius-xs);
|
||||
transition: opacity var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.cons-top-conv-row.is-jumpable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cons-top-conv-row.is-jumpable:hover .cons-top-conv-title {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.cons-top-conv-meta {
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cons-top-conv-meta[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-item-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -714,6 +810,33 @@
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cons-model-perf-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.3;
|
||||
color: var(--text-muted);
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
.cons-model-perf-foot[hidden],
|
||||
.cons-model-unit-cost[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-model-perf-main {
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cons-model-unit-cost {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-view-stage {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -846,7 +969,7 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 共享模型构成悬浮详情卡 (Client Sources & Monthly Breakdown Popover) --- */
|
||||
/* --- 共享模型构成悬浮详情卡 (Trend Heatmap / Client Sources / Sessions / Monthly Popover) --- */
|
||||
.cons-breakdown-popover {
|
||||
position: absolute;
|
||||
left: var(--pop-x, 8px);
|
||||
@@ -866,44 +989,126 @@
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.trend-tooltip.is-rich-breakdown {
|
||||
top: 0;
|
||||
bottom: auto;
|
||||
left: var(--tip-x, 0px);
|
||||
transform: translate3d(var(--tip-shift, 0px), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
.trend-tooltip.is-rich-breakdown,
|
||||
.cons-breakdown-popover.is-rich-breakdown {
|
||||
min-width: 212px;
|
||||
max-width: min(276px, calc(100% - 10px));
|
||||
padding: 7px 9px;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .cons-tip-head {
|
||||
padding-bottom: 0;
|
||||
border-bottom: none;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .trend-tip-time {
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
min-width: 0;
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .trend-tip-calls {
|
||||
font-size: var(--fs-2xs);
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .cons-tip-main {
|
||||
align-items: baseline;
|
||||
margin-top: -2px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .cons-tip-hero {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 3px;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.cons-tip-hero-num {
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-tip-hero-unit {
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.03em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.is-rich-breakdown .trend-tip-cost {
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.cons-pop-models {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--border-hairline) 75%, transparent);
|
||||
padding-top: 6px;
|
||||
margin-top: 1px;
|
||||
gap: 5px;
|
||||
border-top: none;
|
||||
padding-top: 2px;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.cons-pop-models[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.trend-tip-sub:not([hidden]) + .cons-pop-models {
|
||||
border-top: none;
|
||||
padding-top: 2px;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
font-size: var(--fs-xs);
|
||||
line-height: 1.3;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.cons-pop-model-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-left {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-pop-model-left .cons-model-dot {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.cons-pop-model-left .cons-model-dot[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-pop-model-name {
|
||||
max-width: 156px;
|
||||
max-width: 128px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 500;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -917,21 +1122,74 @@
|
||||
.cons-pop-model-right {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-tok {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-muted);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-pop-model-pct {
|
||||
min-width: 38px;
|
||||
min-width: 34px;
|
||||
text-align: right;
|
||||
font-size: var(--fs-xs);
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.cons-pop-model-row .cons-seg-bar {
|
||||
height: 3px;
|
||||
border-radius: var(--radius-pill);
|
||||
}
|
||||
|
||||
.cons-pop-channels {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--border-hairline) 65%, transparent);
|
||||
padding-top: 5px;
|
||||
}
|
||||
|
||||
.cons-pop-channels[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-pop-chan {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-pop-chan-head {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-pop-chan-head .dot-swatch {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
.cons-pop-chan-label {
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
line-height: 1.15;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cons-pop-chan-val {
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
|
||||
|
||||
@@ -983,3 +983,15 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.settings-backup-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.settings-hidden-file-input {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
@@ -81,6 +81,40 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table th.is-sortable {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition: color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.data-table th.is-sortable:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.data-table th.is-sorted {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.step-th-inner {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.data-table th:last-child .step-th-inner {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.step-sort-icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.step-sort-icon[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
@@ -1085,13 +1119,13 @@
|
||||
}
|
||||
|
||||
.smodel-seg-bar {
|
||||
height: 3.5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.smodel-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
justify-content: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 10px;
|
||||
font-size: var(--fs-md);
|
||||
@@ -1111,9 +1145,32 @@
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.smodel-perf-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.3;
|
||||
color: var(--text-muted);
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
.smodel-perf {
|
||||
margin-left: auto;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.smodel-unit-cost {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.smodel-unit-cost[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -50,6 +50,7 @@ import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
import { createFourSegmentBar } from '../components/ui/FourSegmentBar.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
import { StepTableWidget } from '../components/widgets/StepTableWidget.js';
|
||||
import { sortStepsByColumn } from '../registries/stepColumnRegistry.js';
|
||||
|
||||
function mergeSelectedAgentUnits(units) {
|
||||
const combinedSteps = [];
|
||||
@@ -229,6 +230,11 @@ export const StepsDetailView = defineComponent({
|
||||
let selectedLineModels = ['__all__'];
|
||||
let onlyAnomalies = false;
|
||||
let anomalyKindFilter = '';
|
||||
let sortKey = '';
|
||||
let sortDir = '';
|
||||
let cachedSortSrc = null;
|
||||
let cachedSortSig = '';
|
||||
let cachedSortedOut = [];
|
||||
|
||||
function applyAgentScopesSelection(nextScopes) {
|
||||
selectedAgentScopes = nextScopes;
|
||||
@@ -296,6 +302,11 @@ export const StepsDetailView = defineComponent({
|
||||
const stepTableWidget = StepTableWidget({
|
||||
onSelectAgentScopes: applyAgentScopesSelection,
|
||||
onVirtualHeightChange: () => stepsScroll?.refresh(),
|
||||
onSortChange: (nextKey, nextDir) => {
|
||||
sortKey = nextKey || '';
|
||||
sortDir = nextDir || '';
|
||||
if (latestSlice) renderStepsData(latestSlice);
|
||||
},
|
||||
});
|
||||
const {
|
||||
stepsTablePane,
|
||||
@@ -607,6 +618,8 @@ export const StepsDetailView = defineComponent({
|
||||
selectedLineModels = ['__all__'];
|
||||
onlyAnomalies = false;
|
||||
anomalyKindFilter = '';
|
||||
sortKey = '';
|
||||
sortDir = '';
|
||||
}
|
||||
fitLockedCascadeId = currentCid;
|
||||
fitUserPicked = false;
|
||||
@@ -804,16 +817,37 @@ export const StepsDetailView = defineComponent({
|
||||
const modelFilteredSteps = tableModelFilterSet
|
||||
? steps.filter((st) => tableModelFilterSet.has(getStepModelGroupKey(st)))
|
||||
: steps;
|
||||
const tableSteps = onlyAnomalies
|
||||
? modelFilteredSteps.filter((st) => {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) return false;
|
||||
if (anomalyKindFilter) {
|
||||
return Number(a.kinds?.[anomalyKindFilter] || 0) > 0;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
: modelFilteredSteps;
|
||||
|
||||
let filteredTableSteps = modelFilteredSteps;
|
||||
if (onlyAnomalies) {
|
||||
filteredTableSteps = modelFilteredSteps.filter((st) => {
|
||||
const a = st?.anomaly;
|
||||
if (!a || !(Number(a.count) > 0)) return false;
|
||||
if (anomalyKindFilter && !(Number(a.kinds?.[anomalyKindFilter] || 0) > 0)) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
const normTokenFmt = normalizeClientStepTokenComboFormat(slice.stepTokenComboFormat);
|
||||
const sortSig = `${sortKey}:${sortDir}:${normTokenFmt}:${displaySettings.modelDisplayMode}:${displaySettings.showUpstreamModel ? 1 : 0}:${displaySettings.orchestratorIdMode}`;
|
||||
let tableSteps = filteredTableSteps;
|
||||
if (sortKey && sortDir) {
|
||||
if (cachedSortSrc === filteredTableSteps && cachedSortSig === sortSig) {
|
||||
tableSteps = cachedSortedOut;
|
||||
} else {
|
||||
tableSteps = sortStepsByColumn(filteredTableSteps, sortKey, sortDir, {
|
||||
stepTokenComboFormat: normTokenFmt,
|
||||
displaySettings,
|
||||
});
|
||||
cachedSortSrc = filteredTableSteps;
|
||||
cachedSortSig = sortSig;
|
||||
cachedSortedOut = tableSteps;
|
||||
}
|
||||
} else {
|
||||
cachedSortSrc = null;
|
||||
cachedSortSig = '';
|
||||
cachedSortedOut = [];
|
||||
}
|
||||
|
||||
const showAnomalyFilterBar = !showModels && onlyAnomalies;
|
||||
patchAttr(anomalyFilterBarEl, 'hidden', !showAnomalyFilterBar);
|
||||
@@ -859,6 +893,8 @@ export const StepsDetailView = defineComponent({
|
||||
displaySettings,
|
||||
allConversationSteps,
|
||||
allowNewRowFade: shouldAnimateNewRows,
|
||||
sortKey,
|
||||
sortDir,
|
||||
});
|
||||
stepsScroll.refresh();
|
||||
fitPinnedWhileVisible = false;
|
||||
@@ -1137,7 +1173,7 @@ export const StepsDetailView = defineComponent({
|
||||
const anomSig = anomSum
|
||||
? `${anomSum.count}:${anomSum.steps}:${anomSum.primaryKind}:${anomSum.severity}:${anomSum.totalDelaySec}`
|
||||
: '';
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`;
|
||||
return `${locale}:${m.displayText}:${m.displayTitle}:${m.calls}:${sumCalls}:${sumTokens}:${displayModels.length}:${m.avgTokPerSec}:${avgTtft}:${m.cacheHitPct}:${m.inputTokens}:${m.cacheReadTokens}:${m.thinkingTokens}:${m.responseTokens}:${m.totalTokens}:${m.costUsd}:${m.unpricedCalls}:${isActiveFit}:${hasMultipleModels}:${anomSig}`;
|
||||
},
|
||||
createRow: () => {
|
||||
const nameEl = h('strong', { className: 'smodel-name' });
|
||||
@@ -1183,6 +1219,8 @@ export const StepsDetailView = defineComponent({
|
||||
]),
|
||||
]);
|
||||
const perfEl = h('span', { className: 'smodel-perf text-mono' });
|
||||
const unitCostEl = h('span', { className: 'smodel-unit-cost text-mono', hidden: true });
|
||||
const perfFootEl = h('div', { className: 'smodel-perf-foot' }, [perfEl, unitCostEl]);
|
||||
|
||||
const cardEl = h('div', { className: 'smodel-card' }, [
|
||||
h('div', { className: 'smodel-head' }, [
|
||||
@@ -1190,7 +1228,8 @@ export const StepsDetailView = defineComponent({
|
||||
h('div', { className: 'smodel-totals' }, [tokEl, costEl]),
|
||||
]),
|
||||
segBar.el,
|
||||
h('div', { className: 'smodel-foot' }, [splitEl, perfEl]),
|
||||
h('div', { className: 'smodel-foot' }, [splitEl]),
|
||||
perfFootEl,
|
||||
]);
|
||||
|
||||
return {
|
||||
@@ -1203,6 +1242,7 @@ export const StepsDetailView = defineComponent({
|
||||
costEl,
|
||||
segBar,
|
||||
perfEl,
|
||||
unitCostEl,
|
||||
splitEl,
|
||||
inLbl,
|
||||
cacheLbl,
|
||||
@@ -1282,7 +1322,8 @@ export const StepsDetailView = defineComponent({
|
||||
? Math.max(0, Number(m.responseTokens))
|
||||
: Math.max(0, outTok - thinkTok);
|
||||
|
||||
patchText(refs.tokEl, formatTokensPrecise(m.totalTokens || 0));
|
||||
const modelTok = Math.max(0, Number(m.totalTokens || 0));
|
||||
patchText(refs.tokEl, formatTokensPrecise(modelTok));
|
||||
const costNum = Number(m.costUsd || 0);
|
||||
const isAllUnpriced =
|
||||
calls > 0 && Number(m.unpricedCalls || 0) >= calls && !(costNum > 0);
|
||||
@@ -1291,11 +1332,16 @@ export const StepsDetailView = defineComponent({
|
||||
formatUsd(isAllUnpriced ? null : costNum, { precise: costNum > 0 && costNum < 0.1 })
|
||||
);
|
||||
|
||||
const scaleRatio =
|
||||
displayModels.length > 1 && sumTokens > 0 && modelTok > 0
|
||||
? Math.min(1, Math.max(0.008, modelTok / sumTokens))
|
||||
: 1;
|
||||
refs.segBar.update({
|
||||
inputTokens: inTok,
|
||||
cacheReadTokens: cacheTok,
|
||||
responseTokens: respTok,
|
||||
thinkingTokens: thinkTok,
|
||||
scaleRatio,
|
||||
});
|
||||
|
||||
const fbTtft = stepTtftFallbackMap.get(gk);
|
||||
@@ -1330,6 +1376,19 @@ export const StepsDetailView = defineComponent({
|
||||
cache: resolvedCachePct,
|
||||
})
|
||||
);
|
||||
const effCostPer1M =
|
||||
!isAllUnpriced && costNum > 0 && modelTok >= 1000
|
||||
? costNum / (modelTok / 1_000_000)
|
||||
: null;
|
||||
patchAttr(refs.unitCostEl, 'hidden', effCostPer1M === null);
|
||||
patchText(
|
||||
refs.unitCostEl,
|
||||
effCostPer1M !== null
|
||||
? t('cons.modelUnitCost', {
|
||||
cost: formatUsd(effCostPer1M, { precise: effCostPer1M < 0.1 }),
|
||||
})
|
||||
: ''
|
||||
);
|
||||
|
||||
const isActiveFit =
|
||||
hasMultipleModels && cardGroupKeys.some((k) => fitActiveKeySet.has(k));
|
||||
|
||||
@@ -8,6 +8,11 @@ import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { createSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { setI18nLanguage, t } from '../../i18n/index.js';
|
||||
import {
|
||||
buildExportableSettingsJson,
|
||||
parseImportedSettingsJson,
|
||||
triggerTextFileDownload,
|
||||
} from '../../core/settingsBackup.js';
|
||||
import {
|
||||
normalizeClientModelDisplayMode,
|
||||
normalizeClientOrchestratorIdMode,
|
||||
@@ -166,6 +171,8 @@ export const SettingsOtherTab = defineComponent({
|
||||
const ctxStatus = h('span', { className: 'text-muted', role: 'status' });
|
||||
const ctxModelSelect = CustomSelect({
|
||||
className: 'settings-context-model',
|
||||
searchable: true,
|
||||
searchThreshold: 8,
|
||||
options: [],
|
||||
onUpdateModelValue: (id) => {
|
||||
if (!draftContextRiskAccepted || savingContextWindow) return;
|
||||
@@ -472,6 +479,102 @@ export const SettingsOtherTab = defineComponent({
|
||||
[resetBtnText]
|
||||
);
|
||||
|
||||
const backupLabelEl = h('span', {
|
||||
className: 'settings-action-title',
|
||||
text: t('settings.oth.backupLabel'),
|
||||
});
|
||||
const backupDescEl = h('span', {
|
||||
className: 'settings-action-desc',
|
||||
text: t('settings.oth.backupDesc'),
|
||||
});
|
||||
const exportJsonBtnText = h('span', { text: t('settings.oth.exportJsonBtn') });
|
||||
const importJsonBtnText = h('span', { text: t('settings.oth.importJsonBtn') });
|
||||
let isImportingSettings = false;
|
||||
|
||||
async function applyImportedSettingsText(rawText) {
|
||||
const parsed = parseImportedSettingsJson(rawText);
|
||||
if (!parsed.ok) {
|
||||
showMaintFeedback(t('settings.oth.importInvalid'), 3200);
|
||||
return false;
|
||||
}
|
||||
isImportingSettings = true;
|
||||
patchAttr(importJsonBtn, 'disabled', true);
|
||||
showMaintFeedback(t('settings.saving'), 0);
|
||||
try {
|
||||
await saveSettingsPatch(parsed.patch);
|
||||
if (parsed.patch.language) {
|
||||
setI18nLanguage(parsed.patch.language);
|
||||
}
|
||||
showMaintFeedback(
|
||||
t('settings.oth.importDone', { count: parsed.appliedCount }),
|
||||
2800
|
||||
);
|
||||
return true;
|
||||
} catch {
|
||||
showMaintFeedback(t('settings.saveFailed'), 2800);
|
||||
return false;
|
||||
} finally {
|
||||
isImportingSettings = false;
|
||||
patchAttr(importJsonBtn, 'disabled', false);
|
||||
}
|
||||
}
|
||||
|
||||
const importFileInput = h('input', {
|
||||
type: 'file',
|
||||
accept: '.json,application/json',
|
||||
className: 'settings-hidden-file-input',
|
||||
hidden: true,
|
||||
});
|
||||
importFileInput.addEventListener?.('change', async () => {
|
||||
const file = importFileInput.files?.[0];
|
||||
importFileInput.value = '';
|
||||
if (!file || isImportingSettings) return;
|
||||
try {
|
||||
const text =
|
||||
typeof file.text === 'function' ? await file.text() : String(file.content || '');
|
||||
await applyImportedSettingsText(text);
|
||||
} catch {
|
||||
showMaintFeedback(t('settings.oth.importInvalid'), 3200);
|
||||
}
|
||||
});
|
||||
|
||||
const exportJsonBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: () => {
|
||||
const json = buildExportableSettingsJson(latestSettings || {});
|
||||
triggerTextFileDownload(
|
||||
'antigravity-usage-monitor-settings.json',
|
||||
json,
|
||||
'application/json;charset=utf-8'
|
||||
);
|
||||
showMaintFeedback(t('settings.oth.exportDone'), 2400);
|
||||
},
|
||||
},
|
||||
[createSvgIcon('download', { size: 12 }), exportJsonBtnText]
|
||||
);
|
||||
|
||||
const importJsonBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'btn-secondary',
|
||||
onClick: () => {
|
||||
if (isImportingSettings) return;
|
||||
importFileInput.click?.();
|
||||
},
|
||||
},
|
||||
[createSvgIcon('upload', { size: 12 }), importJsonBtnText]
|
||||
);
|
||||
|
||||
const backupActionsWrap = h('div', { className: 'settings-backup-actions' }, [
|
||||
exportJsonBtn,
|
||||
importJsonBtn,
|
||||
importFileInput,
|
||||
]);
|
||||
|
||||
const maintPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
@@ -488,6 +591,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
h('div', { className: 'settings-action-info' }, [resetLabelEl, resetDescEl]),
|
||||
resetAllBtn,
|
||||
]),
|
||||
h('div', { className: 'settings-action-block' }, [
|
||||
h('div', { className: 'settings-action-info' }, [backupLabelEl, backupDescEl]),
|
||||
backupActionsWrap,
|
||||
]),
|
||||
]);
|
||||
|
||||
const rootEl = h('div', { className: 'settings-tab-stack' }, [
|
||||
@@ -533,6 +640,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
patchText(baselineTitleEl, t('settings.oth.baselineTitle'));
|
||||
renderContextWindows();
|
||||
patchText(maintTitleEl, t('settings.oth.maintTitle'));
|
||||
patchText(backupLabelEl, t('settings.oth.backupLabel'));
|
||||
patchText(backupDescEl, t('settings.oth.backupDesc'));
|
||||
patchText(exportJsonBtnText, t('settings.oth.exportJsonBtn'));
|
||||
patchText(importJsonBtnText, t('settings.oth.importJsonBtn'));
|
||||
patchText(cacheLabelEl, t('settings.oth.cacheLabel'));
|
||||
patchText(cacheDescEl, t('settings.oth.cacheDesc'));
|
||||
patchText(resetLabelEl, t('settings.oth.resetLabel'));
|
||||
@@ -579,6 +690,10 @@ export const SettingsOtherTab = defineComponent({
|
||||
ctxWindowSelect,
|
||||
rebuildCacheBtn,
|
||||
resetAllBtn,
|
||||
exportJsonBtn,
|
||||
importJsonBtn,
|
||||
importFileInput,
|
||||
applyImportedSettingsText,
|
||||
renderSettings,
|
||||
refreshLabels,
|
||||
},
|
||||
|
||||
+467
-27
@@ -277,6 +277,10 @@ input[type="number"]::-webkit-outer-spin-button {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.app-shell:focus {
|
||||
outline: none;
|
||||
}
|
||||
|
||||
html[data-standalone="true"] .app-shell {
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
@@ -759,6 +763,100 @@ html[data-standalone="true"] .app-shell {
|
||||
animation: anim-popover-in var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.select-menu.has-search {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-height: 268px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.select-search-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 4px 7px;
|
||||
margin-bottom: 4px;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-bg);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-search-wrap[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-search-wrap:focus-within {
|
||||
border-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.select-search-icon {
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-search-input {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: var(--font-sans);
|
||||
font-size: var(--fs-md);
|
||||
line-height: 1.3;
|
||||
outline: none;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.select-search-input::placeholder {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.select-search-clear {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
padding: 0;
|
||||
border: none;
|
||||
border-radius: var(--radius-pill);
|
||||
background: transparent;
|
||||
color: var(--text-muted);
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.select-search-clear:hover {
|
||||
color: var(--text-primary);
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.select-search-clear[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-options-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.select-menu.has-search .select-options-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.select-empty {
|
||||
padding: 12px 8px;
|
||||
text-align: center;
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.select-empty[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.select-option {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -2375,6 +2473,44 @@ html[data-standalone="true"] .app-shell {
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.cons-seg-bar[hidden],
|
||||
.cons-item-foot[hidden],
|
||||
.cons-share-pill[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-metric-fill.tone-cost {
|
||||
background-color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.cons-metric-fill.tone-speed {
|
||||
background-color: var(--metric-ok);
|
||||
}
|
||||
|
||||
.cons-metric-fill.tone-calls {
|
||||
background-color: var(--ctx-cached);
|
||||
}
|
||||
|
||||
.cons-model-focus-foot {
|
||||
justify-content: space-between;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.cons-model-focus-left {
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cons-model-focus-right {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
/* --- 4. 历史趋势交互式 SVG 平滑曲线图 (Interactive Historical Trend SVG Chart) --- */
|
||||
.trend-chart-wrap {
|
||||
position: relative;
|
||||
@@ -2391,6 +2527,10 @@ html[data-standalone="true"] .app-shell {
|
||||
cursor: crosshair;
|
||||
}
|
||||
|
||||
.trend-plot-stage.is-clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.trend-svg {
|
||||
width: 100%;
|
||||
height: 184px;
|
||||
@@ -2806,6 +2946,29 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
/* --- 5. 模型与数据来源明细行容器 (Popular Models & Sources Item Rows) --- */
|
||||
.cons-ranking-head {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 6px;
|
||||
}
|
||||
|
||||
.cons-ranking-sort-wrap {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cons-ranking-sort-wrap .segmented[hidden],
|
||||
.cons-item-list[hidden],
|
||||
.cons-ranking-empty[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-ranking-empty {
|
||||
padding: var(--space-4) 0;
|
||||
text-align: center;
|
||||
font-size: var(--fs-md);
|
||||
}
|
||||
|
||||
.cons-item-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -2818,6 +2981,37 @@ html[data-standalone="true"] .app-shell {
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.cons-top-conv-row {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
width: 100%;
|
||||
container-type: inline-size;
|
||||
background: transparent;
|
||||
border-radius: var(--radius-xs);
|
||||
transition: opacity var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.cons-top-conv-row.is-jumpable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.cons-top-conv-row.is-jumpable:hover .cons-top-conv-title {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.cons-top-conv-meta {
|
||||
font-size: var(--fs-md);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cons-top-conv-meta[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-item-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -2831,6 +3025,33 @@ html[data-standalone="true"] .app-shell {
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
.cons-model-perf-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.3;
|
||||
color: var(--text-muted);
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
.cons-model-perf-foot[hidden],
|
||||
.cons-model-unit-cost[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-model-perf-main {
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cons-model-unit-cost {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-view-stage {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
@@ -2963,7 +3184,7 @@ html[data-standalone="true"] .app-shell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* --- 共享模型构成悬浮详情卡 (Client Sources & Monthly Breakdown Popover) --- */
|
||||
/* --- 共享模型构成悬浮详情卡 (Trend Heatmap / Client Sources / Sessions / Monthly Popover) --- */
|
||||
.cons-breakdown-popover {
|
||||
position: absolute;
|
||||
left: var(--pop-x, 8px);
|
||||
@@ -2983,44 +3204,126 @@ html[data-standalone="true"] .app-shell {
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.trend-tooltip.is-rich-breakdown {
|
||||
top: 0;
|
||||
bottom: auto;
|
||||
left: var(--tip-x, 0px);
|
||||
transform: translate3d(var(--tip-shift, 0px), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
.trend-tooltip.is-rich-breakdown,
|
||||
.cons-breakdown-popover.is-rich-breakdown {
|
||||
min-width: 212px;
|
||||
max-width: min(276px, calc(100% - 10px));
|
||||
padding: 7px 9px;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .cons-tip-head {
|
||||
padding-bottom: 0;
|
||||
border-bottom: none;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .trend-tip-time {
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
min-width: 0;
|
||||
flex-shrink: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .trend-tip-calls {
|
||||
font-size: var(--fs-2xs);
|
||||
color: var(--text-muted);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .cons-tip-main {
|
||||
align-items: baseline;
|
||||
margin-top: -2px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.is-rich-breakdown .cons-tip-hero {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 3px;
|
||||
color: var(--text-primary);
|
||||
line-height: 1.15;
|
||||
}
|
||||
|
||||
.cons-tip-hero-num {
|
||||
font-size: var(--fs-lg);
|
||||
font-weight: 700;
|
||||
letter-spacing: -0.02em;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-tip-hero-unit {
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.03em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.is-rich-breakdown .trend-tip-cost {
|
||||
font-size: var(--fs-sm);
|
||||
font-weight: 600;
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.cons-pop-models {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--border-hairline) 75%, transparent);
|
||||
padding-top: 6px;
|
||||
margin-top: 1px;
|
||||
gap: 5px;
|
||||
border-top: none;
|
||||
padding-top: 2px;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.cons-pop-models[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.trend-tip-sub:not([hidden]) + .cons-pop-models {
|
||||
border-top: none;
|
||||
padding-top: 2px;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
font-size: var(--fs-xs);
|
||||
line-height: 1.3;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.cons-pop-model-head {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-left {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
gap: 5px;
|
||||
min-width: 0;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-pop-model-left .cons-model-dot {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.cons-pop-model-left .cons-model-dot[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-pop-model-name {
|
||||
max-width: 156px;
|
||||
max-width: 128px;
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 500;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
@@ -3034,21 +3337,74 @@ html[data-standalone="true"] .app-shell {
|
||||
.cons-pop-model-right {
|
||||
display: inline-flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cons-pop-model-tok {
|
||||
font-size: var(--fs-xs);
|
||||
color: var(--text-muted);
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.cons-pop-model-pct {
|
||||
min-width: 38px;
|
||||
min-width: 34px;
|
||||
text-align: right;
|
||||
font-size: var(--fs-xs);
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
color: var(--text-secondary);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.cons-pop-model-row .cons-seg-bar {
|
||||
height: 3px;
|
||||
border-radius: var(--radius-pill);
|
||||
}
|
||||
|
||||
.cons-pop-channels {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
gap: 4px;
|
||||
border-top: 1px solid color-mix(in srgb, var(--border-hairline) 65%, transparent);
|
||||
padding-top: 5px;
|
||||
}
|
||||
|
||||
.cons-pop-channels[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.cons-pop-chan {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-pop-chan-head {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.cons-pop-chan-head .dot-swatch {
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
}
|
||||
|
||||
.cons-pop-chan-label {
|
||||
font-size: var(--fs-2xs);
|
||||
font-weight: 500;
|
||||
line-height: 1.15;
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.cons-pop-chan-val {
|
||||
font-size: var(--fs-xs);
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
color: var(--text-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- 6. 12 个月垂直堆叠柱状图 (12-Month Stacked Bar Chart) --- */
|
||||
@@ -3227,6 +3583,40 @@ html[data-standalone="true"] .app-shell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.data-table th.is-sortable {
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
transition: color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.data-table th.is-sortable:hover {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.data-table th.is-sorted {
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.step-th-inner {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.data-table th:last-child .step-th-inner {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.step-sort-icon {
|
||||
flex-shrink: 0;
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.step-sort-icon[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.data-table tbody tr:not(.step-vspacer):not(.step-vsizer):hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
@@ -4231,13 +4621,13 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
.smodel-seg-bar {
|
||||
height: 3.5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.smodel-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
justify-content: flex-start;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 10px;
|
||||
font-size: var(--fs-md);
|
||||
@@ -4257,11 +4647,34 @@ html[data-standalone="true"] .app-shell {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.smodel-perf-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
font-size: var(--fs-sm);
|
||||
line-height: 1.3;
|
||||
color: var(--text-muted);
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
.smodel-perf {
|
||||
margin-left: auto;
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.smodel-unit-cost {
|
||||
font-size: var(--fs-sm);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.smodel-unit-cost[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* --- src/styles/views-settings.css --- */
|
||||
@@ -5251,6 +5664,18 @@ html[data-standalone="true"] .app-shell {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.settings-backup-actions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.settings-hidden-file-input {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* --- src/styles/overlay.css --- */
|
||||
/*
|
||||
* 双栖模式顶栏胶囊与悬浮面板样式表 (overlay.css).
|
||||
@@ -6546,8 +6971,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-pop-models {
|
||||
border-top-color: var(--modern-surface-hover);
|
||||
[data-modern-ui="true"] .cons-pop-channels {
|
||||
border-top-color: color-mix(in srgb, var(--text-primary) 8%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .cons-source-bar-hit:hover .cons-source-model-bar,
|
||||
@@ -6778,6 +7203,15 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
animation: anim-modern-tip-fade 120ms var(--ease-modern);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-search-wrap {
|
||||
border: none;
|
||||
background: var(--modern-surface-subtle);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-search-wrap:focus-within {
|
||||
box-shadow: 0 0 0 1.5px color-mix(in srgb, var(--accent-primary) 50%, transparent);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .select-menu.is-above,
|
||||
[data-modern-ui="true"] .dt-popover.is-above {
|
||||
transform-origin: bottom right;
|
||||
@@ -6804,6 +7238,12 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
|
||||
transform: translate3d(var(--tip-shift, -50%), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip.is-rich-breakdown {
|
||||
top: 0;
|
||||
bottom: auto;
|
||||
transform: translate3d(var(--tip-shift, 0px), var(--tip-y, 0px), 0);
|
||||
}
|
||||
|
||||
[data-modern-ui="true"] .trend-tooltip.is-tracking {
|
||||
transition:
|
||||
left 150ms var(--ease-modern),
|
||||
|
||||
@@ -1847,6 +1847,9 @@ test('Antigravity CLI annotations.pbtxt + SQLite trajectory reader recovers titl
|
||||
env: {
|
||||
...process.env,
|
||||
ANTIGRAVITY_GEMINI_DIR: tempRoot,
|
||||
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||
ANTIGRAVITY_EXECUTABLE_DATA_DIR: '',
|
||||
USAGE_MONITOR_DATA_DIR: join(tempRoot, 'data'),
|
||||
ANTIGRAVITY_LS_ADDRESS: 'test.invalid',
|
||||
ANTIGRAVITY_CSRF_TOKEN: 'test',
|
||||
@@ -2063,6 +2066,9 @@ test('provisions Antigravity CLI statusLine safely and renders live capsule from
|
||||
const installEnv = {
|
||||
...process.env,
|
||||
ANTIGRAVITY_GEMINI_DIR: tempRoot,
|
||||
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||
ANTIGRAVITY_EXECUTABLE_DATA_DIR: '',
|
||||
USAGE_MONITOR_DATA_DIR: dataDir,
|
||||
USAGE_MONITOR_ALLOW_TEST_CLI_SETTINGS: '1',
|
||||
};
|
||||
@@ -2392,6 +2398,9 @@ test('v1.5 feedback settings schema: custom token combo DSL, 3-way model display
|
||||
...process.env,
|
||||
USAGE_MONITOR_DATA_DIR: workerTemp,
|
||||
ANTIGRAVITY_GEMINI_DIR: workerTemp,
|
||||
ANTIGRAVITY_APP_DATA_DIR: '',
|
||||
USAGE_MONITOR_APP_DATA_DIR: '',
|
||||
ANTIGRAVITY_EXECUTABLE_DATA_DIR: '',
|
||||
ANTIGRAVITY_LS_ADDRESS: 'test.invalid',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -224,13 +224,22 @@ test('Backend aggregates per-model breakdown on both sourcesBreakdown and monthl
|
||||
assert.equal(novBucket.totalTokens, 20_000);
|
||||
assert.equal(novBucket.models.length, 2);
|
||||
|
||||
// Active trendSeries bucket carries per-model breakdown while zero-token buckets omit models
|
||||
// Active trendSeries bucket carries 4-channel totals & per-model 4-channel breakdown while zero-token buckets omit models
|
||||
const trendSlots = payload.consumption?.trendSeries || [];
|
||||
const activeTrendSlot = trendSlots.find((s) => s.tokens > 0);
|
||||
const zeroTrendSlot = trendSlots.find((s) => s.tokens === 0);
|
||||
assert.ok(activeTrendSlot);
|
||||
assert.equal(activeTrendSlot.tokens, 20_000);
|
||||
assert.equal(activeTrendSlot.inputTokens, 13_000);
|
||||
assert.equal(activeTrendSlot.cacheReadTokens, 3_000);
|
||||
assert.equal(activeTrendSlot.thinkingTokens, 200);
|
||||
assert.equal(activeTrendSlot.responseTokens, 3_800);
|
||||
assert.equal(activeTrendSlot.models.length, 2);
|
||||
const trendMainModel = activeTrendSlot.models[0];
|
||||
assert.equal(trendMainModel.inputTokens, 9_000);
|
||||
assert.equal(trendMainModel.cacheReadTokens, 3_000);
|
||||
assert.equal(trendMainModel.thinkingTokens, 200);
|
||||
assert.equal(trendMainModel.responseTokens, 2_800);
|
||||
if (zeroTrendSlot) {
|
||||
assert.equal(zeroTrendSlot.models, undefined);
|
||||
}
|
||||
@@ -347,6 +356,8 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
tokens: 100_000,
|
||||
inputTokens: 20_000,
|
||||
cacheReadTokens: 60_000,
|
||||
thinkingTokens: 5_000,
|
||||
responseTokens: 15_000,
|
||||
outputTokens: 20_000,
|
||||
calls: 23,
|
||||
costUsd: 0.96,
|
||||
@@ -444,18 +455,36 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
const appBarSum = appSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(appBarSum - 80) < 0.1);
|
||||
|
||||
// Hovering Client Source bar hit area OR top-models summary opens shared popover with model details + '其他 (3)'
|
||||
// Hovering Client Source bar hit area OR top-models summary opens shared popover with 4-seg model bars + bottom 4-channel totals
|
||||
const popover = view.refs.breakdownPopoverEl;
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
const appBarHit = sourceRows[0].querySelector('.cons-source-bar-hit');
|
||||
appBarHit.dispatchEvent({ type: 'mouseenter', clientX: 120 });
|
||||
assert.equal(popover.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.querySelector('.trend-tip-time')?.textContent, 'Antigravity App');
|
||||
assert.match(popover.querySelector('.trend-tip-tokens')?.textContent || '', /80\.0k TOKEN/);
|
||||
assert.equal((popover.textContent || '').includes('模型细分'), false);
|
||||
const popRows = popover.querySelectorAll('.cons-pop-model-row');
|
||||
assert.equal(popRows.length, 4);
|
||||
assert.equal(popRows[0].querySelector('.cons-pop-model-name')?.textContent, '4-argon');
|
||||
assert.equal(popRows[0].querySelector('.cons-pop-model-pct')?.textContent, '50.0%');
|
||||
assert.equal(popRows[0].querySelector('.cons-model-dot')?.hasAttribute('hidden'), false);
|
||||
assert.equal(
|
||||
popRows[0].querySelector('.cons-model-dot')?.style.getPropertyValue('--dot-color'),
|
||||
argonDotColor
|
||||
);
|
||||
const popArgonBarSum = popRows[0]
|
||||
.querySelectorAll('.progress-seg')
|
||||
.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(popArgonBarSum - 50) < 0.1, `Expected 50% 4-seg width in source popover, got ${popArgonBarSum}`);
|
||||
assert.equal(popRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)');
|
||||
const popChannelsEl = popover.querySelector('.cons-pop-channels');
|
||||
assert.equal(popChannelsEl?.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.children[popover.children.length - 1], popChannelsEl);
|
||||
assert.deepEqual(
|
||||
popChannelsEl.querySelectorAll('.cons-pop-chan-label').map((el) => el.textContent),
|
||||
['输入', '缓存', '思考', '输出']
|
||||
);
|
||||
|
||||
appBarHit.dispatchEvent({ type: 'mouseleave' });
|
||||
assert.equal(popover.hasAttribute('hidden'), true);
|
||||
@@ -474,7 +503,7 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
assert.match(consCss, /\.cons-source-top-models\s*\{[\s\S]*flex-wrap:\s*nowrap/);
|
||||
assert.match(consCss, /@container\s*\(max-width:\s*340px\)\s*\{\s*\.cons-source-top-item:nth-child\(n\s*\+\s*3\)/);
|
||||
|
||||
// 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & hover popover
|
||||
// 3. Monthly Breakdown: old 4-channel legend removed; Nov column renders model-colored vertical segments & unified hover popover
|
||||
assert.equal(view.el.querySelectorAll('.monthly-legend').length, 0);
|
||||
const monthCols = view.el.querySelectorAll('.month-col');
|
||||
const novCol = monthCols[10];
|
||||
@@ -489,8 +518,9 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
assert.equal(popover.hasAttribute('hidden'), false);
|
||||
assert.equal(popover.querySelector('.trend-tip-time')?.textContent, '2026年 11月');
|
||||
assert.equal(popover.querySelectorAll('.cons-pop-model-row').length, 4);
|
||||
assert.equal(popover.querySelector('.cons-pop-channels')?.hasAttribute('hidden'), false);
|
||||
|
||||
// 4. Usage Trend: taller 184px viewBox & hovering x-axis tick opens trend tooltip with identical model colors + long-tail '其他 (3)'
|
||||
// 4. Usage Trend: taller 184px viewBox & hovering x-axis tick opens redesigned tooltip (hero TOKEN, 4-seg model bars, no subtitle/dot clutter, bottom 4 channels)
|
||||
const trendSvg = view.el.querySelector('.trend-svg');
|
||||
assert.match(trendSvg?.getAttribute('viewBox') || '', /\s184$/);
|
||||
const trendTicks = view.el.querySelectorAll('.trend-x-tick');
|
||||
@@ -498,14 +528,27 @@ test('ConsumptionView: Top Models color dot + % bar, clutter-free Client Sources
|
||||
trendTicks[1].onclick();
|
||||
const trendTip = view.el.querySelector('.trend-tooltip');
|
||||
assert.equal(trendTip?.hasAttribute('hidden'), false);
|
||||
assert.match(trendTip.querySelector('.trend-tip-tokens')?.textContent || '', /100\.0k TOKEN/);
|
||||
assert.equal((trendTip.textContent || '').includes('模型细分'), false);
|
||||
const trendTipModelRows = trendTip.querySelectorAll('.cons-pop-model-row');
|
||||
assert.equal(trendTipModelRows.length, 4);
|
||||
assert.equal(trendTipModelRows[0].querySelector('.cons-pop-model-name')?.textContent, '4-argon');
|
||||
assert.equal(
|
||||
trendTipModelRows[0].querySelector('.cons-model-dot')?.style.getPropertyValue('--dot-color'),
|
||||
argonDotColor
|
||||
assert.equal(trendTipModelRows[0].querySelector('.cons-model-dot')?.hasAttribute('hidden'), true);
|
||||
const trendArgonSegs = trendTipModelRows[0].querySelectorAll('.progress-seg');
|
||||
assert.deepEqual(
|
||||
trendArgonSegs.map((el) => el.className.split(/\s+/).find((c) => c.startsWith('seg-'))),
|
||||
['seg-input', 'seg-cached', 'seg-thinking', 'seg-output']
|
||||
);
|
||||
const trendArgonSum = trendArgonSegs.reduce((s, el) => s + parsePctVar(el, '--seg-w'), 0);
|
||||
assert.ok(Math.abs(trendArgonSum - 50) < 0.1, `Expected 50% 4-seg width in trend tooltip, got ${trendArgonSum}`);
|
||||
assert.equal(trendTipModelRows[3].querySelector('.cons-pop-model-name')?.textContent, '其他 (3)');
|
||||
const trendChannelsEl = trendTip.querySelector('.cons-pop-channels');
|
||||
assert.equal(trendChannelsEl?.hasAttribute('hidden'), false);
|
||||
assert.equal(trendTip.children[trendTip.children.length - 1], trendChannelsEl);
|
||||
assert.deepEqual(
|
||||
trendChannelsEl.querySelectorAll('.cons-pop-chan-val').map((el) => el.textContent),
|
||||
['20.0k', '60.0k', '5.0k', '15.0k']
|
||||
);
|
||||
});
|
||||
|
||||
test('selectConsumptionTimeRange serves prefetched presets with 0 network calls, blocks stale 2s poll overwrites, and TrendAreaChart heatmap batches via DocumentFragment', async (t) => {
|
||||
|
||||
@@ -548,26 +548,37 @@ test('SegmentedControl variable-width glider snaps cleanly on reveal and glides
|
||||
);
|
||||
stepTable.destroy();
|
||||
|
||||
// 10. TrendAreaChart tooltip arms 0.15s .is-tracking transition after initial snap and translates --tip-y smoothly
|
||||
// 10. TrendAreaChart tooltip arms 0.15s .is-tracking transition after initial snap and follows pointer steadily without top/bottom jumps
|
||||
const trendChart = createTrendAreaChart();
|
||||
Object.assign(trendChart.el, { offsetHeight: 210 });
|
||||
Object.assign(trendChart.el, {
|
||||
clientWidth: 460,
|
||||
offsetHeight: 210,
|
||||
getBoundingClientRect: () => ({ left: 0, top: 240, width: 460, height: 210, right: 460, bottom: 450 }),
|
||||
});
|
||||
const tipEl = trendChart.el.querySelector('.trend-tooltip');
|
||||
Object.assign(tipEl, { offsetHeight: 82 });
|
||||
Object.assign(tipEl, { offsetWidth: 216, offsetHeight: 82 });
|
||||
const plotStage = trendChart.el.querySelector('.trend-plot-stage');
|
||||
const svgEl = trendChart.el.querySelector('.trend-svg');
|
||||
svgEl.getBoundingClientRect = () => ({ left: 0, top: 246, width: 460, height: 184, right: 460, bottom: 430 });
|
||||
trendChart.update([
|
||||
{ index: 0, label: '00:00', fullLabel: '11月19日 00:00 - 01:00', tokens: 1000, calls: 2, costUsd: 0.1 },
|
||||
{ index: 1, label: '10:00', fullLabel: '11月19日 10:00 - 11:00', tokens: 25_000_000, calls: 80, costUsd: 6.37 },
|
||||
]);
|
||||
const ticks = trendChart.el.querySelectorAll('.trend-x-tick');
|
||||
queuedRaf = null;
|
||||
ticks[0].onclick(); // low valley -> --tip-y = 0px, initial snap has is-tracking = false
|
||||
assert.equal(tipEl.style.getPropertyValue('--tip-y'), '0px');
|
||||
plotStage.dispatchEvent({ type: 'mousemove', clientX: 80, clientY: 360 });
|
||||
const firstY = tipEl.style.getPropertyValue('--tip-y');
|
||||
assert.equal(firstY, '24px');
|
||||
assert.equal(tipEl.classList.contains('is-tracking'), false);
|
||||
queuedRaf?.();
|
||||
assert.equal(tipEl.classList.contains('is-tracking'), true);
|
||||
|
||||
ticks[1].onclick(); // high peak -> --tip-y = 210 - 82 - 22 = 106px while is-tracking remains true
|
||||
assert.equal(tipEl.style.getPropertyValue('--tip-y'), '106px');
|
||||
// Sweeping horizontally from valley to peak at steady cursor Y keeps --tip-y rock steady (no top/bottom ping-pong)
|
||||
plotStage.dispatchEvent({ type: 'mousemove', clientX: 400, clientY: 360 });
|
||||
assert.equal(tipEl.style.getPropertyValue('--tip-y'), firstY);
|
||||
assert.equal(tipEl.classList.contains('is-tracking'), true);
|
||||
// Moving cursor vertically shifts --tip-y smoothly with cursor
|
||||
plotStage.dispatchEvent({ type: 'mousemove', clientX: 400, clientY: 390 });
|
||||
assert.equal(tipEl.style.getPropertyValue('--tip-y'), '54px');
|
||||
trendChart.destroy();
|
||||
|
||||
// 11. ContextWindowWidget + LiveActivityWidget use pure SVG chevrons and animate expand/collapse under [data-modern-ui="true"]
|
||||
|
||||
@@ -0,0 +1,969 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { createMockDom } from './mock-dom.mjs';
|
||||
import { CustomSelect, filterSelectOptionsByQuery } from '../src/components/ui/CustomSelect.js';
|
||||
import { App } from '../src/App.js';
|
||||
import { sortStepsByColumn } from '../src/registries/stepColumnRegistry.js';
|
||||
import {
|
||||
buildExportableSettingsJson,
|
||||
parseImportedSettingsJson,
|
||||
} from '../src/core/settingsBackup.js';
|
||||
import { StepsDetailView } from '../src/views/StepsDetailView.js';
|
||||
import { ConsumptionView } from '../src/views/ConsumptionView.js';
|
||||
import { SettingsOtherTab } from '../src/views/settings/SettingsOtherTab.js';
|
||||
import { createTrendAreaChart } from '../src/components/charts/TrendAreaChart.js';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
import { i18nStore, setI18nLanguage } from '../src/i18n/index.js';
|
||||
import { telemetryStore } from '../src/store/telemetryStore.js';
|
||||
import { uiStore } from '../src/store/uiStore.js';
|
||||
|
||||
test('Feature 1: CustomSelect searchable mode filters by multi-term query, respects threshold, and handles keyboard flow', (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevLocale = i18nStore.getState().locale;
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
innerWidth: 960,
|
||||
innerHeight: 720,
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
setI18nLanguage('zh-CN');
|
||||
|
||||
let picked = null;
|
||||
let comp = null;
|
||||
t.after(() => {
|
||||
comp?.destroy?.();
|
||||
setI18nLanguage(prevLocale);
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
});
|
||||
|
||||
// Pure multi-term matcher
|
||||
const opts = [
|
||||
{ value: '', label: '最新 (主对话)', meta: '12步' },
|
||||
{ value: 'cid-ssh-1', label: 'SSH 远程部署排查', meta: '主4 · 2蜂 (共18步)' },
|
||||
{ value: 'cid-ui-2', label: 'Modern UI 光滑动画', meta: '9步' },
|
||||
{ value: 'cid-bug-3', label: '5h 配额周期对齐', meta: '42步' },
|
||||
{ value: 'cid-sql-4', label: 'SQLite WAL 性能优化', meta: '31步' },
|
||||
{ value: 'cid-perf-5', label: 'Carbon 模型测速对比', meta: '19步' },
|
||||
];
|
||||
assert.equal(filterSelectOptionsByQuery(opts, 'ssh 蜂').length, 1);
|
||||
assert.equal(filterSelectOptionsByQuery(opts, 'cid-bug-3')[0].value, 'cid-bug-3');
|
||||
assert.equal(filterSelectOptionsByQuery(opts, 'no-such-session').length, 0);
|
||||
|
||||
comp = CustomSelect({
|
||||
modelValue: '',
|
||||
searchable: true,
|
||||
searchThreshold: 6,
|
||||
searchPlaceholder: '搜索会话…',
|
||||
options: opts,
|
||||
onUpdateModelValue: (val) => {
|
||||
picked = val;
|
||||
},
|
||||
});
|
||||
document.body.appendChild(comp.el);
|
||||
|
||||
// Below threshold hides search bar
|
||||
comp.setProps({ options: opts.slice(0, 3) });
|
||||
comp.open();
|
||||
assert.equal(comp.el.querySelector('.select-search-wrap').hasAttribute('hidden'), true);
|
||||
comp.close();
|
||||
|
||||
// At/above threshold shows search bar and filters live
|
||||
comp.setProps({ options: opts });
|
||||
let focusedSearch = false;
|
||||
comp.refs.searchInput.focus = () => {
|
||||
focusedSearch = true;
|
||||
};
|
||||
comp.openAndFocusSearch();
|
||||
assert.equal(comp.el.classList.contains('is-open'), true);
|
||||
assert.equal(comp.el.querySelector('.select-search-wrap').hasAttribute('hidden'), false);
|
||||
assert.equal(comp.el.querySelectorAll('.select-option').length, 6);
|
||||
|
||||
// Type query -> filters to 1 match
|
||||
comp.refs.searchInput.value = 'sql wal';
|
||||
comp.refs.searchInput.dispatchEvent({
|
||||
type: 'input',
|
||||
target: comp.refs.searchInput,
|
||||
});
|
||||
let visibleRows = comp.el.querySelectorAll('.select-option');
|
||||
assert.equal(visibleRows.length, 1);
|
||||
assert.equal(visibleRows[0].getAttribute('data-value'), 'cid-sql-4');
|
||||
assert.equal(comp.el.querySelector('.select-empty').hasAttribute('hidden'), true);
|
||||
|
||||
// Unmatched query -> shows empty hint
|
||||
comp.refs.searchInput.value = 'does-not-exist-xyz';
|
||||
comp.refs.searchInput.dispatchEvent({
|
||||
type: 'input',
|
||||
target: comp.refs.searchInput,
|
||||
});
|
||||
assert.equal(comp.el.querySelectorAll('.select-option').length, 0);
|
||||
assert.equal(comp.el.querySelector('.select-empty').hasAttribute('hidden'), false);
|
||||
|
||||
// First Escape clears query instead of closing dropdown
|
||||
comp.refs.searchInput.dispatchEvent({
|
||||
type: 'keydown',
|
||||
key: 'Escape',
|
||||
target: comp.refs.searchInput,
|
||||
preventDefault() {},
|
||||
});
|
||||
assert.equal(comp.el.classList.contains('is-open'), true);
|
||||
assert.equal(comp.refs.searchInput.value, '');
|
||||
assert.equal(comp.el.querySelectorAll('.select-option').length, 6);
|
||||
|
||||
// Filter and press Enter to select
|
||||
comp.refs.searchInput.value = 'carbon';
|
||||
comp.refs.searchInput.dispatchEvent({
|
||||
type: 'input',
|
||||
target: comp.refs.searchInput,
|
||||
});
|
||||
comp.refs.searchInput.dispatchEvent({
|
||||
type: 'keydown',
|
||||
key: 'Enter',
|
||||
target: comp.refs.searchInput,
|
||||
preventDefault() {},
|
||||
});
|
||||
assert.equal(picked, 'cid-perf-5');
|
||||
assert.equal(comp.el.classList.contains('is-open'), false);
|
||||
return Promise.resolve().then(() => {
|
||||
assert.equal(focusedSearch, true);
|
||||
});
|
||||
});
|
||||
|
||||
test('Feature 1: App panel keyboard shortcuts switch tabs (1-4), trigger refresh (r), open search (/), and ignore editable inputs', (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevUi = { ...uiStore.getState() };
|
||||
const prevTel = { ...telemetryStore.getState() };
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
let fetchCalled = 0;
|
||||
globalThis.window = {
|
||||
location: { pathname: '/' },
|
||||
innerWidth: 960,
|
||||
innerHeight: 720,
|
||||
sidecar: {
|
||||
fetch: async () => {
|
||||
fetchCalled += 1;
|
||||
return { ok: true, status: 200, json: async () => ({}) };
|
||||
},
|
||||
},
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
|
||||
uiStore.setState({ activeView: 'overview', monitorVisible: true }, { sync: true });
|
||||
let app = null;
|
||||
t.after(() => {
|
||||
app?.destroy?.();
|
||||
uiStore.setState(prevUi, { sync: true });
|
||||
telemetryStore.setState(prevTel, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
});
|
||||
|
||||
app = App();
|
||||
document.body.appendChild(app.el);
|
||||
|
||||
// Keys 2, 3, 4, 1 switch activeView
|
||||
app.el.dispatchEvent({ type: 'keydown', key: '2', target: app.el, preventDefault() {} });
|
||||
assert.equal(uiStore.getState().activeView, 'consumption');
|
||||
app.el.dispatchEvent({ type: 'keydown', key: '3', target: app.el, preventDefault() {} });
|
||||
assert.equal(uiStore.getState().activeView, 'steps');
|
||||
app.el.dispatchEvent({ type: 'keydown', key: '4', target: app.el, preventDefault() {} });
|
||||
assert.equal(uiStore.getState().activeView, 'settings');
|
||||
app.el.dispatchEvent({ type: 'keydown', key: '1', target: app.el, preventDefault() {} });
|
||||
assert.equal(uiStore.getState().activeView, 'overview');
|
||||
|
||||
// Modifier keys and INPUT targets are ignored
|
||||
app.el.dispatchEvent({
|
||||
type: 'keydown',
|
||||
key: '3',
|
||||
ctrlKey: true,
|
||||
target: app.el,
|
||||
preventDefault() {},
|
||||
});
|
||||
assert.equal(uiStore.getState().activeView, 'overview');
|
||||
|
||||
const fakeInput = document.createElement('input');
|
||||
app.el.dispatchEvent({ type: 'keydown', key: '3', target: fakeInput, preventDefault() {} });
|
||||
assert.equal(uiStore.getState().activeView, 'overview');
|
||||
|
||||
// '/' opens top session picker
|
||||
app.el.dispatchEvent({ type: 'keydown', key: '/', target: app.el, preventDefault() {} });
|
||||
assert.equal(app.refs.sessionHeader.refs.convSelect.el.classList.contains('is-open'), true);
|
||||
|
||||
// 'r' triggers telemetry refresh
|
||||
app.el.dispatchEvent({ type: 'keydown', key: 'r', target: app.el, preventDefault() {} });
|
||||
assert.ok(fetchCalled >= 1);
|
||||
});
|
||||
|
||||
test('Feature 3: Step table supports multi-column sorting (with nulls last), anomaly/compaction quick chips, and live subtotal bar', (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevUi = { ...uiStore.getState() };
|
||||
const prevTel = { ...telemetryStore.getState() };
|
||||
const prevLocale = i18nStore.getState().locale;
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
innerWidth: 960,
|
||||
innerHeight: 720,
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
setI18nLanguage('zh-CN');
|
||||
|
||||
let view = null;
|
||||
t.after(() => {
|
||||
view?.destroy?.();
|
||||
uiStore.setState(prevUi, { sync: true });
|
||||
telemetryStore.setState(prevTel, { sync: true });
|
||||
setI18nLanguage(prevLocale);
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
});
|
||||
|
||||
const sampleSteps = [
|
||||
{
|
||||
stepIndex: 3,
|
||||
createdAtMs: 3000,
|
||||
modelShort: '4-neon',
|
||||
modelLabel: 'Gemini 4 Neon',
|
||||
tokPerSec: 30,
|
||||
ttftSec: 4.5,
|
||||
inputTokens: 10_000,
|
||||
cacheReadTokens: 90_000,
|
||||
outputTokens: 600,
|
||||
thinkingTokens: 400,
|
||||
responseTokens: 200,
|
||||
contextTokens: 100_600,
|
||||
cacheHitPct: 90,
|
||||
costUsd: 0.45,
|
||||
anomaly: { count: 1, severity: 'warn', primaryKind: 'timeout', kinds: { timeout: 1 } },
|
||||
anomalySig: 'timeout:1',
|
||||
},
|
||||
{
|
||||
stepIndex: 2,
|
||||
createdAtMs: 2000,
|
||||
modelShort: '4-carbon',
|
||||
modelLabel: 'Gemini 4 Carbon',
|
||||
tokPerSec: null,
|
||||
ttftSec: null,
|
||||
isCompactionStep: true,
|
||||
inputTokens: 50_000,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 1_000,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 1_000,
|
||||
contextTokens: 51_000,
|
||||
cacheHitPct: 0,
|
||||
costUsd: 0.12,
|
||||
},
|
||||
{
|
||||
stepIndex: 1,
|
||||
createdAtMs: 1000,
|
||||
modelShort: '4-carbon',
|
||||
modelLabel: 'Gemini 4 Carbon',
|
||||
tokPerSec: 60,
|
||||
ttftSec: 1.5,
|
||||
inputTokens: 5_000,
|
||||
cacheReadTokens: 95_000,
|
||||
outputTokens: 1_200,
|
||||
thinkingTokens: 500,
|
||||
responseTokens: 700,
|
||||
contextTokens: 101_200,
|
||||
cacheHitPct: 95,
|
||||
costUsd: 0.08,
|
||||
},
|
||||
];
|
||||
|
||||
// Pure sort keeps nulls last in both desc and asc
|
||||
const byTpsDesc = sortStepsByColumn(sampleSteps, 'tps', 'desc');
|
||||
assert.deepEqual(byTpsDesc.map((s) => s.stepIndex), [1, 3, 2]);
|
||||
const byTpsAsc = sortStepsByColumn(sampleSteps, 'tps', 'asc');
|
||||
assert.deepEqual(byTpsAsc.map((s) => s.stepIndex), [3, 1, 2]);
|
||||
|
||||
// Full StepsDetailView integration: click header sort cycles desc -> asc -> default (no bottom summary bar)
|
||||
uiStore.setState({ activeView: 'steps', stepsSubTab: 'steps', monitorVisible: true }, { sync: true });
|
||||
telemetryStore.setState(
|
||||
{
|
||||
telemetry: {
|
||||
settings: {
|
||||
stepTableColumns: ['step', 'model', 'tps', 'cost'],
|
||||
showStepTurnRail: true,
|
||||
},
|
||||
activeConversation: {
|
||||
cascadeId: 'cid-sort-1',
|
||||
stepCount: 3,
|
||||
recentSteps: sampleSteps,
|
||||
modelBreakdown: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ sync: true }
|
||||
);
|
||||
|
||||
view = StepsDetailView();
|
||||
document.body.appendChild(view.el);
|
||||
|
||||
assert.equal(view.el.querySelector('.steps-summary-bar'), null);
|
||||
|
||||
// Click '费用' header (index 3) -> desc -> asc -> default
|
||||
const ths = view.el.querySelectorAll('thead th');
|
||||
assert.equal(ths.length, 4);
|
||||
ths[3].onclick();
|
||||
assert.equal(ths[3].getAttribute('aria-sort'), 'descending');
|
||||
let rowStepTexts = view.el.querySelectorAll('tbody tr').map((tr) => tr.children[0].textContent);
|
||||
assert.deepEqual(rowStepTexts, ['#3', '#2', '#1']);
|
||||
|
||||
ths[3].onclick();
|
||||
assert.equal(ths[3].getAttribute('aria-sort'), 'ascending');
|
||||
rowStepTexts = view.el.querySelectorAll('tbody tr').map((tr) => tr.children[0].textContent);
|
||||
assert.deepEqual(rowStepTexts, ['#1', '#2', '#3']);
|
||||
|
||||
ths[3].onclick();
|
||||
assert.equal(ths[3].getAttribute('aria-sort'), 'none');
|
||||
rowStepTexts = view.el.querySelectorAll('tbody tr').map((tr) => tr.children[0].textContent);
|
||||
assert.deepEqual(rowStepTexts, ['#3', '#2', '#1']);
|
||||
});
|
||||
|
||||
test('Feature 5: backend aggregates top costly sessions consistently across full and fast paths', async () => {
|
||||
const nowMs = Date.now();
|
||||
const h = (hrsAgo) => nowMs - hrsAgo * 3600 * 1000;
|
||||
|
||||
const harn = backendHarness({
|
||||
cache: {
|
||||
'conv-high-cost': {
|
||||
cascadeId: 'conv-high-cost',
|
||||
title: 'Expensive Refactor',
|
||||
appSource: 'standalone',
|
||||
steps: [
|
||||
{
|
||||
stepIndex: 1,
|
||||
modelKey: 'MODEL_PLACEHOLDER_M18',
|
||||
inputTokens: 200_000,
|
||||
cacheReadTokens: 800_000,
|
||||
outputTokens: 40_000,
|
||||
thinkingTokens: 15_000,
|
||||
responseTokens: 25_000,
|
||||
createdAtMs: h(3),
|
||||
},
|
||||
{
|
||||
stepIndex: 2,
|
||||
modelKey: 'MODEL_PLACEHOLDER_M18',
|
||||
inputTokens: 100_000,
|
||||
cacheReadTokens: 400_000,
|
||||
outputTokens: 20_000,
|
||||
thinkingTokens: 8_000,
|
||||
responseTokens: 12_000,
|
||||
createdAtMs: h(30),
|
||||
},
|
||||
],
|
||||
},
|
||||
'conv-low-cost': {
|
||||
cascadeId: 'conv-low-cost',
|
||||
title: 'Quick Bugfix',
|
||||
appSource: 'ide',
|
||||
steps: [
|
||||
{
|
||||
stepIndex: 1,
|
||||
modelKey: 'MODEL_PLACEHOLDER_M18',
|
||||
inputTokens: 50_000,
|
||||
cacheReadTokens: 200_000,
|
||||
outputTokens: 10_000,
|
||||
thinkingTokens: 3_000,
|
||||
responseTokens: 7_000,
|
||||
createdAtMs: h(2),
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
summaries: {
|
||||
'conv-high-cost': { summary: 'Expensive Refactor', stepCount: 2, lastModifiedTime: new Date(h(3)).toISOString() },
|
||||
'conv-low-cost': { summary: 'Quick Bugfix', stepCount: 1, lastModifiedTime: new Date(h(2)).toISOString() },
|
||||
},
|
||||
});
|
||||
|
||||
const full24h = await harn.buildTelemetryPayloadInternal('conv-high-cost', false, { range: '24h' });
|
||||
const topList = full24h.consumption.topConversations;
|
||||
assert.equal(Array.isArray(topList), true);
|
||||
assert.equal(topList.length, 2);
|
||||
assert.equal(topList[0].cascadeId, 'conv-high-cost');
|
||||
assert.equal(topList[0].title, 'Expensive Refactor');
|
||||
assert.equal(topList[0].totalTokens, 1_040_000);
|
||||
assert.equal(topList[0].cacheHitPct, 80);
|
||||
assert.equal(Array.isArray(topList[0].models), true, 'Each top conversation carries per-model breakdown');
|
||||
assert.equal(topList[0].models.length, 1);
|
||||
assert.equal(topList[0].models[0].totalTokens, 1_040_000);
|
||||
assert.equal(topList[1].cascadeId, 'conv-low-cost');
|
||||
assert.equal(topList[1].totalTokens, 260_000);
|
||||
assert.equal(full24h.consumption.comparison, undefined);
|
||||
|
||||
// Fast consumption slice path matches full path identically
|
||||
const fast24h = JSON.parse(
|
||||
(await harn.executeTelemetryAction({
|
||||
conversationId: 'conv-high-cost',
|
||||
range: '24h',
|
||||
scope: 'consumption',
|
||||
})).body
|
||||
);
|
||||
assert.equal(fast24h.scope, 'consumption');
|
||||
assert.equal(fast24h.consumption.topConversations.length, 2);
|
||||
assert.equal(fast24h.consumption.topConversations[0].cascadeId, 'conv-high-cost');
|
||||
});
|
||||
|
||||
test('Feature 5: TrendAreaChart drill-down click and unified Models/Sessions segmented ranking card', async (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevFetch = globalThis.fetch;
|
||||
const prevLocale = i18nStore.getState().locale;
|
||||
const prevUi = uiStore.getState();
|
||||
const prevTel = telemetryStore.getState();
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
requestAnimationFrame: (cb) => {
|
||||
cb();
|
||||
return 1;
|
||||
},
|
||||
cancelAnimationFrame: () => {},
|
||||
};
|
||||
globalThis.fetch = async () => ({ ok: true, json: async () => ({}) });
|
||||
|
||||
let view = null;
|
||||
let chart = null;
|
||||
t.after(() => {
|
||||
view?.destroy?.();
|
||||
chart?.destroy?.();
|
||||
setI18nLanguage(prevLocale);
|
||||
uiStore.setState(prevUi, { sync: true });
|
||||
telemetryStore.setState(prevTel, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
globalThis.fetch = prevFetch;
|
||||
});
|
||||
|
||||
setI18nLanguage('zh-CN');
|
||||
|
||||
// 1. TrendAreaChart click drill-down on line curve
|
||||
const selectedSlots = [];
|
||||
chart = createTrendAreaChart({ onSelectSlot: (slot) => selectedSlots.push(slot) });
|
||||
const day1Start = new Date(2026, 9, 10, 0, 0, 0, 0).getTime();
|
||||
const day1End = new Date(2026, 9, 10, 23, 59, 59, 999).getTime();
|
||||
const day2Start = new Date(2026, 9, 11, 0, 0, 0, 0).getTime();
|
||||
const day2End = new Date(2026, 9, 11, 23, 59, 59, 999).getTime();
|
||||
chart.update([
|
||||
{ label: '10/10', fullLabel: '2026-10-10', startMs: day1Start, endMs: day1End, tokens: 100_000, calls: 2, costUsd: 0.2 },
|
||||
{ label: '10/11', fullLabel: '2026-10-11', startMs: day2Start, endMs: day2End, tokens: 300_000, calls: 4, costUsd: 0.6 },
|
||||
]);
|
||||
const svgEl = chart.el.querySelector('svg');
|
||||
svgEl.getBoundingClientRect = () => ({ left: 0, width: 400, top: 0, height: 184 });
|
||||
const stageEl = chart.el.querySelector('.trend-plot-stage');
|
||||
stageEl.dispatchEvent({ type: 'click', clientX: 390 });
|
||||
assert.equal(selectedSlots.length, 1);
|
||||
assert.equal(selectedSlots[0].label, '10/11');
|
||||
|
||||
// 2. ConsumptionView renders delta pills, top sessions sorting & click-to-jump, and month bar drill-down
|
||||
uiStore.setState({ activeView: 'consumption', monitorVisible: true }, { sync: true });
|
||||
telemetryStore.setState(
|
||||
{
|
||||
selectedTimeRange: '7d',
|
||||
customStartMs: 0,
|
||||
customEndMs: 0,
|
||||
telemetry: {
|
||||
settings: {},
|
||||
consumption: {
|
||||
revision: 7,
|
||||
selectedRange: { key: '7d', label: '近7天', startMs: day1Start, endMs: day2End },
|
||||
account: {
|
||||
totalTokens: 1_500_000,
|
||||
inputTokens: 200_000,
|
||||
cacheReadTokens: 1_200_000,
|
||||
outputTokens: 100_000,
|
||||
responseTokens: 60_000,
|
||||
thinkingTokens: 40_000,
|
||||
costUsd: 2.5,
|
||||
savedCostUsd: 1.8,
|
||||
cacheHitPct: 85.7,
|
||||
calls: 15,
|
||||
},
|
||||
comparison: {
|
||||
prevTotalTokens: 1_000_000,
|
||||
prevCostUsd: 5.0,
|
||||
prevCalls: 10,
|
||||
tokensDeltaPct: 50,
|
||||
costDeltaPct: -50,
|
||||
},
|
||||
topConversations: [
|
||||
{
|
||||
cascadeId: 'cid-costly',
|
||||
title: 'Costly Session',
|
||||
sourceName: 'Antigravity',
|
||||
calls: 6,
|
||||
inputTokens: 150_000,
|
||||
cacheReadTokens: 300_000,
|
||||
responseTokens: 40_000,
|
||||
thinkingTokens: 10_000,
|
||||
totalTokens: 500_000,
|
||||
costUsd: 1.8,
|
||||
cacheHitPct: 66.7,
|
||||
canJump: true,
|
||||
models: [
|
||||
{ label: '4-neon', shortName: '4-neon', calls: 4, totalTokens: 400_000, costUsd: 1.5 },
|
||||
{ label: '4-carbon', shortName: '4-carbon', calls: 2, totalTokens: 100_000, costUsd: 0.3 },
|
||||
],
|
||||
},
|
||||
{
|
||||
cascadeId: 'cid-heavy-tok',
|
||||
title: 'Heavy Cache Session',
|
||||
sourceName: 'IDE',
|
||||
calls: 9,
|
||||
inputTokens: 50_000,
|
||||
cacheReadTokens: 900_000,
|
||||
responseTokens: 20_000,
|
||||
thinkingTokens: 30_000,
|
||||
totalTokens: 1_000_000,
|
||||
costUsd: 0.7,
|
||||
cacheHitPct: 94.7,
|
||||
canJump: true,
|
||||
models: [
|
||||
{ label: '4-carbon', shortName: '4-carbon', calls: 9, totalTokens: 1_000_000, costUsd: 0.7 },
|
||||
],
|
||||
},
|
||||
],
|
||||
trendSeries: [],
|
||||
sourcesBreakdown: [],
|
||||
monthlyYear: 2026,
|
||||
monthlySeries: Array.from({ length: 12 }, (_, idx) =>
|
||||
idx === 4
|
||||
? { month: 5, totalTokens: 800_000, costUsd: 1.4, calls: 12, models: [] }
|
||||
: { month: idx + 1, totalTokens: 0, costUsd: 0, calls: 0, models: [] }
|
||||
),
|
||||
},
|
||||
modelBreakdown: [],
|
||||
},
|
||||
},
|
||||
{ sync: true }
|
||||
);
|
||||
|
||||
view = ConsumptionView();
|
||||
document.body.appendChild(view.el);
|
||||
|
||||
// Period delta pills removed
|
||||
assert.equal(view.el.querySelectorAll('.cons-delta-pill').length, 0);
|
||||
|
||||
// Unified ranking panel starts on Models tab and hides Sessions list
|
||||
const rankingPanel = view.el.querySelector('.cons-ranking-panel');
|
||||
const rankingTabBtns = rankingPanel.querySelector('.cons-ranking-head > .segmented').querySelectorAll('.seg-btn');
|
||||
assert.equal(rankingTabBtns.length, 2);
|
||||
assert.match(rankingTabBtns[0].textContent, /模型排行/);
|
||||
assert.match(rankingTabBtns[1].textContent, /会话排行 \(2\)/);
|
||||
|
||||
const listContainers = rankingPanel.querySelectorAll('.cons-item-list');
|
||||
assert.equal(listContainers[0].hasAttribute('hidden'), false, 'Models list visible by default');
|
||||
assert.equal(listContainers[1].hasAttribute('hidden'), true, 'Sessions list hidden by default');
|
||||
|
||||
// Switch ranking tab to Sessions -> models list hides, sessions list reveals
|
||||
rankingTabBtns[1].dispatchEvent({ type: 'click', stopPropagation: () => {} });
|
||||
assert.equal(listContainers[0].hasAttribute('hidden'), true);
|
||||
assert.equal(listContainers[1].hasAttribute('hidden'), false);
|
||||
|
||||
// Top sessions default sorted by cost: Costly Session first with cost-share % and multi-model bar
|
||||
let convRows = view.el.querySelectorAll('.cons-top-conv-row');
|
||||
assert.equal(convRows.length, 2);
|
||||
assert.equal(convRows[0].querySelector('.cons-row-title-text').textContent, 'Costly Session');
|
||||
assert.equal(convRows[0].querySelector('.cons-share-pill').textContent, '72.0%');
|
||||
assert.equal(convRows[0].querySelectorAll('.cons-model-seg').length, 2, 'Session bar splits by model colors');
|
||||
assert.equal(convRows[0].querySelectorAll('.cons-source-top-item').length, 2, 'Session footer shows top models');
|
||||
assert.equal(convRows[0].querySelector('.cons-source-top-name').textContent, '4-neon');
|
||||
|
||||
// Switch sessions sort to Tokens: Heavy Cache Session moves to first and share switches to token % (66.7%)
|
||||
const sortSwitches = rankingPanel.querySelectorAll('.cons-ranking-sort-wrap > .segmented');
|
||||
assert.equal(sortSwitches[0].hasAttribute('hidden'), true, 'Models sort switch hidden on Sessions tab');
|
||||
assert.equal(sortSwitches[1].hasAttribute('hidden'), false, 'Sessions sort switch visible on Sessions tab');
|
||||
const topConvSortBtns = sortSwitches[1].querySelectorAll('.seg-btn');
|
||||
topConvSortBtns[1].dispatchEvent({ type: 'click', stopPropagation: () => {} });
|
||||
convRows = view.el.querySelectorAll('.cons-top-conv-row');
|
||||
assert.equal(convRows[0].querySelector('.cons-row-title-text').textContent, 'Heavy Cache Session');
|
||||
assert.equal(convRows[0].querySelector('.cons-share-pill').textContent, '66.7%');
|
||||
|
||||
// Click a monthly bar (May, index 4) to drill down to May 2026 custom range
|
||||
const monthCols = view.el.querySelectorAll('.month-col');
|
||||
monthCols[4].dispatchEvent({ type: 'click' });
|
||||
assert.equal(telemetryStore.getState().selectedTimeRange, 'custom');
|
||||
assert.equal(new Date(telemetryStore.getState().customStartMs).getMonth(), 4);
|
||||
assert.equal(new Date(telemetryStore.getState().customEndMs).getMonth(), 4);
|
||||
|
||||
// Click top session row to jump to steps view with that conversation selected
|
||||
convRows[0].dispatchEvent({ type: 'click' });
|
||||
assert.equal(uiStore.getState().activeView, 'steps');
|
||||
assert.equal(telemetryStore.getState().selectedConversationId, 'cid-heavy-tok');
|
||||
});
|
||||
|
||||
test('Feature 6: model ranking multi-metric sort with efficiency footer & validated settings JSON backup/restore', async (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevFetch = globalThis.fetch;
|
||||
const prevLocale = i18nStore.getState().locale;
|
||||
const prevUi = uiStore.getState();
|
||||
const prevTel = telemetryStore.getState();
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
requestAnimationFrame: (cb) => {
|
||||
cb();
|
||||
return 1;
|
||||
},
|
||||
cancelAnimationFrame: () => {},
|
||||
};
|
||||
|
||||
let savedPatches = [];
|
||||
globalThis.fetch = async (url, opts) => {
|
||||
if (String(url).includes('/api/settings') && opts?.method === 'POST') {
|
||||
const body = JSON.parse(opts.body);
|
||||
savedPatches.push(body);
|
||||
return { ok: true, json: async () => ({ ok: true, settings: body }) };
|
||||
}
|
||||
return { ok: true, json: async () => ({}) };
|
||||
};
|
||||
|
||||
let consView = null;
|
||||
let otherTab = null;
|
||||
t.after(() => {
|
||||
consView?.destroy?.();
|
||||
otherTab?.destroy?.();
|
||||
setI18nLanguage(prevLocale);
|
||||
uiStore.setState(prevUi, { sync: true });
|
||||
telemetryStore.setState(prevTel, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
globalThis.fetch = prevFetch;
|
||||
});
|
||||
|
||||
setI18nLanguage('zh-CN');
|
||||
|
||||
// 1. Model ranking sort & efficiency footer (TPS / TTFT / Cache / Anomaly / $/1M)
|
||||
uiStore.setState({ activeView: 'consumption', monitorVisible: true }, { sync: true });
|
||||
telemetryStore.setState(
|
||||
{
|
||||
selectedTimeRange: '7d',
|
||||
telemetry: {
|
||||
settings: {},
|
||||
consumption: {
|
||||
revision: 9,
|
||||
selectedRange: { key: '7d', label: '近7天', startMs: 1, endMs: 2 },
|
||||
account: { totalTokens: 3_000_000, costUsd: 5.0, calls: 30 },
|
||||
trendSeries: [],
|
||||
sourcesBreakdown: [],
|
||||
monthlyYear: 2026,
|
||||
monthlySeries: [],
|
||||
},
|
||||
modelBreakdown: [
|
||||
{
|
||||
label: 'model-high-tok',
|
||||
shortName: 'model-high-tok',
|
||||
calls: 10,
|
||||
inputTokens: 100_000,
|
||||
cacheReadTokens: 1_800_000,
|
||||
outputTokens: 100_000,
|
||||
thinkingTokens: 40_000,
|
||||
responseTokens: 60_000,
|
||||
totalTokens: 2_000_000,
|
||||
costUsd: 1.5,
|
||||
avgTokPerSec: 32.5,
|
||||
avgTtftSec: 2.1,
|
||||
cacheHitPct: 94.7,
|
||||
anomalyCount: 2,
|
||||
},
|
||||
{
|
||||
label: 'model-fast-costly',
|
||||
shortName: 'model-fast-costly',
|
||||
calls: 20,
|
||||
inputTokens: 300_000,
|
||||
cacheReadTokens: 600_000,
|
||||
outputTokens: 100_000,
|
||||
thinkingTokens: 30_000,
|
||||
responseTokens: 70_000,
|
||||
totalTokens: 1_000_000,
|
||||
costUsd: 3.5,
|
||||
avgTokPerSec: 88.4,
|
||||
avgTtftSec: 0.8,
|
||||
cacheHitPct: 66.7,
|
||||
anomalyCount: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{ sync: true }
|
||||
);
|
||||
|
||||
consView = ConsumptionView();
|
||||
document.body.appendChild(consView.el);
|
||||
|
||||
// Default sorted by Tokens -> model-high-tok first with Token share (66.7%) & full info
|
||||
let rows = consView.el.querySelectorAll('.cons-item-row');
|
||||
assert.equal(rows.length, 2);
|
||||
assert.equal(rows[0].querySelector('.cons-row-title-text').textContent, 'model-high-tok');
|
||||
assert.equal(rows[0].querySelector('.cons-share-pill').textContent, '66.7%');
|
||||
const perfFoot = rows[0].querySelector('.cons-model-perf-foot');
|
||||
assert.equal(perfFoot.hasAttribute('hidden'), false);
|
||||
assert.match(perfFoot.querySelector('.cons-model-perf-main').textContent, /32\.5 tok\/s/);
|
||||
assert.match(perfFoot.querySelector('.cons-model-perf-main').textContent, /2\.1s/);
|
||||
assert.equal(perfFoot.querySelector('.cons-model-anom-tag'), null);
|
||||
assert.match(perfFoot.querySelector('.cons-model-unit-cost').textContent, /\$0\.75\/1M/);
|
||||
assert.equal(rows[0].querySelector('.cons-model-focus-foot').hasAttribute('hidden'), true);
|
||||
|
||||
// Switch model ranking sort to Speed -> model-fast-costly first, pct becomes relative speed (100%), focuses on speed
|
||||
const modelsHeaderBtns = consView.el
|
||||
.querySelector('.cons-ranking-sort-wrap > .segmented')
|
||||
.querySelectorAll('.seg-btn');
|
||||
assert.equal(modelsHeaderBtns.length, 4);
|
||||
modelsHeaderBtns[2].dispatchEvent({ type: 'click', stopPropagation: () => {} });
|
||||
rows = consView.el.querySelectorAll('.cons-item-row');
|
||||
assert.equal(rows[0].querySelector('.cons-row-title-text').textContent, 'model-fast-costly');
|
||||
assert.equal(rows[0].querySelector('.cons-share-pill').textContent, '100%');
|
||||
assert.equal(rows[0].querySelector('.cons-row-cost').textContent, '88.4 tok/s');
|
||||
assert.equal(rows[0].querySelector('.cons-model-perf-foot').hasAttribute('hidden'), true);
|
||||
assert.equal(rows[0].querySelector('.cons-model-focus-foot').hasAttribute('hidden'), false);
|
||||
assert.equal(rows[1].querySelector('.cons-share-pill').textContent, '37%');
|
||||
|
||||
// Switch to Cost -> model-fast-costly ($3.50 / $5.00 = 70.0%), focuses on cost
|
||||
modelsHeaderBtns[1].dispatchEvent({ type: 'click', stopPropagation: () => {} });
|
||||
rows = consView.el.querySelectorAll('.cons-item-row');
|
||||
assert.equal(rows[0].querySelector('.cons-row-title-text').textContent, 'model-fast-costly');
|
||||
assert.equal(rows[0].querySelector('.cons-share-pill').textContent, '70.0%');
|
||||
assert.equal(rows[0].querySelector('.cons-row-cost').textContent, '$3.50');
|
||||
assert.equal(rows[0].querySelector('.cons-model-focus-foot').hasAttribute('hidden'), false);
|
||||
|
||||
// Switch to Calls -> model-fast-costly (20 / 30 = 66.7%), focuses on calls
|
||||
modelsHeaderBtns[3].dispatchEvent({ type: 'click', stopPropagation: () => {} });
|
||||
rows = consView.el.querySelectorAll('.cons-item-row');
|
||||
assert.equal(rows[0].querySelector('.cons-row-title-text').textContent, 'model-fast-costly');
|
||||
assert.equal(rows[0].querySelector('.cons-share-pill').textContent, '66.7%');
|
||||
assert.equal(rows[0].querySelector('.cons-row-cost').textContent, '20 次');
|
||||
|
||||
// 2. Settings JSON Export & Safe Validated Import
|
||||
const exportedJson = buildExportableSettingsJson({
|
||||
language: 'en-US',
|
||||
themeAccent: 'emerald',
|
||||
fontScale: 'lg',
|
||||
modernUi: true,
|
||||
stepTableColumns: ['step', 'model', 'cost'],
|
||||
contextWindowRiskAccepted: true,
|
||||
modelContextWindows: { 'model:foo': '1000000' },
|
||||
});
|
||||
const parsedRaw = JSON.parse(exportedJson);
|
||||
assert.equal(parsedRaw.schema, 'antigravity-usage-monitor.settings');
|
||||
assert.equal(parsedRaw.settings.themeAccent, 'emerald');
|
||||
assert.equal(parsedRaw.settings.contextWindowRiskAccepted, undefined, 'Risk flag must not be exported');
|
||||
assert.equal(parsedRaw.settings.modelContextWindows, undefined, 'Context overrides must not be exported');
|
||||
|
||||
// Import strips unknown/dangerous keys and normalizes valid keys
|
||||
const imported = parseImportedSettingsJson(
|
||||
JSON.stringify({
|
||||
schema: 'antigravity-usage-monitor.settings',
|
||||
settings: {
|
||||
language: 'en-US',
|
||||
themeAccent: 'violet',
|
||||
fontScale: 'INVALID_SCALE',
|
||||
popoverWidth: 99999,
|
||||
contextWindowRiskAccepted: true,
|
||||
unknownSecret: 'nope',
|
||||
},
|
||||
})
|
||||
);
|
||||
assert.equal(imported.ok, true);
|
||||
assert.equal(imported.patch.language, 'en-US');
|
||||
assert.equal(imported.patch.themeAccent, 'violet');
|
||||
assert.equal(imported.patch.fontScale, 'md', 'Invalid scale normalizes safely');
|
||||
assert.equal(imported.patch.popoverWidth, 1080, 'Oversized popover width clamps safely');
|
||||
assert.equal(imported.patch.contextWindowRiskAccepted, undefined);
|
||||
assert.equal(imported.patch.unknownSecret, undefined);
|
||||
|
||||
// Rejects bad JSON and foreign schema
|
||||
assert.equal(parseImportedSettingsJson('{bad json').ok, false);
|
||||
assert.equal(parseImportedSettingsJson(JSON.stringify({ schema: 'other.app', settings: {} })).ok, false);
|
||||
|
||||
// SettingsOtherTab wires import end-to-end
|
||||
otherTab = SettingsOtherTab();
|
||||
otherTab.refs.renderSettings({ language: 'zh-CN', themeAccent: 'host' }, []);
|
||||
const applied = await otherTab.refs.applyImportedSettingsText(exportedJson);
|
||||
assert.equal(applied, true);
|
||||
assert.equal(savedPatches.length, 1);
|
||||
assert.equal(savedPatches[0].themeAccent, 'emerald');
|
||||
assert.equal(i18nStore.getState().locale, 'en-US');
|
||||
});
|
||||
|
||||
test('Feature 7: telemetry exposes all local conversations beyond 30 and recovers missing/hex titles from turn prompts', async () => {
|
||||
const baseMs = Date.parse('2026-11-21T03:00:00.000Z');
|
||||
const summaries = {};
|
||||
const trajectories = {};
|
||||
for (let i = 0; i < 36; i++) {
|
||||
const hex = String(i + 1).padStart(8, '0');
|
||||
const cid = `${hex}-1111-4111-8111-111111111111`;
|
||||
const tsIso = new Date(baseMs - i * 60_000).toISOString();
|
||||
const isUntitled = i === 34;
|
||||
summaries[cid] = {
|
||||
summary: isUntitled ? '' : `Session #${i + 1}`,
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
stepCount: 2,
|
||||
createdTime: tsIso,
|
||||
lastModifiedTime: tsIso,
|
||||
};
|
||||
trajectories[cid] = {
|
||||
trajectory: {
|
||||
steps: [
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
userInput: {
|
||||
userResponse: isUntitled ? '排查热力图悬浮提示抖动问题' : `Prompt #${i + 1}`,
|
||||
},
|
||||
metadata: { createdAt: tsIso },
|
||||
},
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: tsIso,
|
||||
completedAt: new Date(baseMs - i * 60_000 + 2000).toISOString(),
|
||||
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M429',
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '1000',
|
||||
cacheReadTokens: '2000',
|
||||
outputTokens: '500',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const harness = backendHarness({
|
||||
clock: () => baseMs + 5_000,
|
||||
summaries,
|
||||
trajectories,
|
||||
});
|
||||
|
||||
const payload = await harness.buildTelemetryPayloadInternal();
|
||||
assert.equal(payload.conversations.length, 36, 'All 36 local conversations should be exposed without 30-item truncation');
|
||||
assert.equal(payload.account.totalConversations, 36);
|
||||
assert.ok(payload.conversations[0].sessionCostUsd !== undefined, 'Recent conversations keep quick stats');
|
||||
assert.equal(payload.conversations[35].sessionCostUsd, undefined, 'Older historical conversations omit heavy quick stats');
|
||||
|
||||
const recoveredConv = payload.conversations.find((c) => c.cascadeId.startsWith('00000035-'));
|
||||
assert.ok(recoveredConv);
|
||||
assert.equal(recoveredConv.title, '排查热力图悬浮提示抖动问题');
|
||||
});
|
||||
|
||||
test('Feature 8: StepsDetailView model summary cards align with Model Ranking (proportional 4-seg bar + left-aligned perf sub-row + unit cost)', (t) => {
|
||||
const prevDoc = globalThis.document;
|
||||
const prevWin = globalThis.window;
|
||||
const prevLocale = i18nStore.getState().locale;
|
||||
const prevUi = uiStore.getState();
|
||||
const prevTel = telemetryStore.getState();
|
||||
|
||||
const { document } = createMockDom();
|
||||
globalThis.document = document;
|
||||
globalThis.window = {
|
||||
location: { pathname: '/' },
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
requestAnimationFrame: (cb) => setTimeout(cb, 0),
|
||||
cancelAnimationFrame: (id) => clearTimeout(id),
|
||||
};
|
||||
|
||||
let view = null;
|
||||
t.after(() => {
|
||||
if (view) view.destroy();
|
||||
setI18nLanguage(prevLocale);
|
||||
uiStore.setState(prevUi, { sync: true });
|
||||
telemetryStore.setState(prevTel, { sync: true });
|
||||
globalThis.document = prevDoc;
|
||||
globalThis.window = prevWin;
|
||||
});
|
||||
|
||||
setI18nLanguage('zh-CN');
|
||||
uiStore.setState(
|
||||
{ monitorVisible: true, activeView: 'steps', stepsSubTab: 'models', selectedAgentScope: 'all' },
|
||||
{ sync: true }
|
||||
);
|
||||
telemetryStore.setState(
|
||||
{
|
||||
telemetry: {
|
||||
settings: { language: 'zh-CN', modelDisplayMode: 'upstream', showUpstreamModel: true },
|
||||
activeConversation: {
|
||||
cascadeId: 'steps-summary-align',
|
||||
stepCount: 10,
|
||||
recentSteps: [],
|
||||
modelBreakdown: [
|
||||
{
|
||||
label: '4-neon',
|
||||
shortName: '4-neon',
|
||||
upstreamName: '4-neon',
|
||||
calls: 8,
|
||||
inputTokens: 100_000,
|
||||
cacheReadTokens: 600_000,
|
||||
thinkingTokens: 50_000,
|
||||
responseTokens: 50_000,
|
||||
outputTokens: 100_000,
|
||||
totalTokens: 800_000,
|
||||
costUsd: 2.4,
|
||||
avgTokPerSec: 45.2,
|
||||
avgTtftSec: 12.1,
|
||||
cacheHitPct: 85.7,
|
||||
},
|
||||
{
|
||||
label: '4-carbon',
|
||||
shortName: '4-carbon',
|
||||
upstreamName: '4-carbon',
|
||||
calls: 2,
|
||||
inputTokens: 40_000,
|
||||
cacheReadTokens: 140_000,
|
||||
thinkingTokens: 10_000,
|
||||
responseTokens: 10_000,
|
||||
outputTokens: 20_000,
|
||||
totalTokens: 200_000,
|
||||
costUsd: 0.4,
|
||||
avgTokPerSec: 22.0,
|
||||
avgTtftSec: 18.4,
|
||||
cacheHitPct: 77.8,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
{ sync: true }
|
||||
);
|
||||
|
||||
view = StepsDetailView();
|
||||
document.body.appendChild(view.el);
|
||||
|
||||
const cards = view.el.querySelectorAll('.smodel-card');
|
||||
assert.equal(cards.length, 2);
|
||||
const sumBarPct = (card) =>
|
||||
card
|
||||
.querySelectorAll('.progress-seg')
|
||||
.reduce((acc, el) => acc + (Number.parseFloat(el.style.getPropertyValue('--seg-w')) || 0), 0);
|
||||
|
||||
assert.ok(Math.abs(sumBarPct(cards[0]) - 80) < 0.2, `Expected 80% bar width for 4-neon, got ${sumBarPct(cards[0])}`);
|
||||
assert.ok(Math.abs(sumBarPct(cards[1]) - 20) < 0.2, `Expected 20% bar width for 4-carbon, got ${sumBarPct(cards[1])}`);
|
||||
assert.ok(cards[0].querySelector('.smodel-perf-foot > .smodel-perf'), 'Perf metrics live in dedicated left-aligned sub-row');
|
||||
assert.match(cards[0].querySelector('.smodel-unit-cost')?.textContent || '', /均价 \$3\.00\/1M/);
|
||||
});
|
||||
@@ -2148,7 +2148,7 @@ test('Compiled app.js mounts dual Shadow DOM hosts, tracks /c/<uuid> routes, pro
|
||||
const trendTooltipEl = popoverEl.querySelector('.trend-tooltip');
|
||||
assert.equal(trendTooltipEl.hasAttribute('hidden'), false, 'Tooltip opens on heatmap cell hover');
|
||||
assert.equal(activeCell.classList.contains('is-hovered'), true);
|
||||
assert.match(trendTooltipEl.querySelector('.trend-tip-tokens').textContent, /100\.0k tok/);
|
||||
assert.match(trendTooltipEl.querySelector('.trend-tip-tokens').textContent, /100\.0k TOKEN/);
|
||||
|
||||
// Crossing 2px inter-cell gaps keeps highlight/tooltip steady without flickering, and fast jumps snap to nearest cell
|
||||
const hmBodyEl = heatmapStageEl.querySelector('.trend-heatmap-body');
|
||||
|
||||
Reference in New Issue
Block a user