mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
feat(panel): subagent monitoring and 10-channel context window (v1.4.1)
This commit is contained in:
+981
-236
File diff suppressed because it is too large
Load Diff
@@ -167,6 +167,146 @@ export function loadExternalDeepStatsCache() {
|
||||
return convos;
|
||||
}
|
||||
|
||||
const MAX_CONCURRENT_RPC = 4;
|
||||
const LEGACY_MIGRATION_BATCH_SIZE = 8;
|
||||
const MAX_SUBAGENT_RECONCILE_DEPTH = 4;
|
||||
const FAILED_RPC_COOLDOWN_MS = 60_000;
|
||||
const failedFetchCooldownMap = new Map();
|
||||
|
||||
/**
|
||||
* 清洗并裁剪 `subagentSpec`,仅保留 UI 与分组所需的 `typeName` 和 `role`,
|
||||
* 剔除体积较大的 `initialPrompt`,避免膨胀 `trajectory_usage_cache.json`。
|
||||
*
|
||||
* @param {object|null|undefined} rawSpec
|
||||
* @returns {{ typeName: string, role: string } | null}
|
||||
*/
|
||||
function sanitizeSubagentSpec(rawSpec) {
|
||||
if (!rawSpec || typeof rawSpec !== 'object') return null;
|
||||
const typeName = String(rawSpec.typeName || '').trim();
|
||||
const role = String(rawSpec.role || '').trim();
|
||||
if (!typeName && !role) return null;
|
||||
return { typeName, role };
|
||||
}
|
||||
|
||||
/**
|
||||
* 按字段合并两个来源的 `subagentSpec`,避免仅含 `typeName` 的元数据覆盖掉父步骤中的 `role`。
|
||||
*
|
||||
* @param {object|null|undefined} primary
|
||||
* @param {object|null|undefined} secondary
|
||||
* @returns {{ typeName: string, role: string } | null}
|
||||
*/
|
||||
function mergeSubagentSpecs(primary, secondary) {
|
||||
const a = sanitizeSubagentSpec(primary);
|
||||
const b = sanitizeSubagentSpec(secondary);
|
||||
if (!a && !b) return null;
|
||||
return {
|
||||
typeName: a?.typeName || b?.typeName || '',
|
||||
role: a?.role || b?.role || '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 从主/父会话的原始轨迹步骤 (`CORTEX_STEP_TYPE_INVOKE_SUBAGENT`) 中提取派生子代理列表。
|
||||
* Antigravity 重启后 `GetAllCascadeTrajectories` 不再返回历史子代理摘要,
|
||||
* 通过解析父轨迹内的 `invokeSubagent` 步骤即可完整找回所有子代理及其角色名称与启动顺序。
|
||||
*
|
||||
* @param {object[]} [rawSteps=[]]
|
||||
* @returns {Array<{ cascadeId: string, role: string, typeName: string, createdTimeMs: number, spawnOrder: number }>}
|
||||
*/
|
||||
export function extractSubagentRefsFromSteps(rawSteps = []) {
|
||||
const refsMap = new Map();
|
||||
let orderCounter = 0;
|
||||
for (const st of rawSteps || []) {
|
||||
const inv = st?.invokeSubagent;
|
||||
if (!inv) continue;
|
||||
let toolArgs = {};
|
||||
const argsJson = st?.metadata?.toolCall?.argumentsJson;
|
||||
if (typeof argsJson === 'string' && argsJson.trim()) {
|
||||
try {
|
||||
toolArgs = JSON.parse(argsJson);
|
||||
} catch {
|
||||
// 忽略非标准 JSON
|
||||
}
|
||||
}
|
||||
const subSpecs = Array.isArray(inv.subagents) ? inv.subagents : [];
|
||||
const results = Array.isArray(inv.results) ? inv.results : [];
|
||||
const createdTimeMs = parseIsoMs(st?.metadata?.createdAt) || 0;
|
||||
const count = Math.max(
|
||||
subSpecs.length,
|
||||
results.length,
|
||||
inv.conversationId || inv.subagentConversationId ? 1 : 0
|
||||
);
|
||||
for (let idx = 0; idx < count; idx++) {
|
||||
const resItem = results[idx] || {};
|
||||
const specItem = subSpecs[idx] || (subSpecs.length === 1 ? subSpecs[0] : {}) || {};
|
||||
const fallbackInvCid =
|
||||
idx === 0 || count === 1 ? inv.conversationId || inv.subagentConversationId || '' : '';
|
||||
const cid = String(
|
||||
resItem.conversationId ||
|
||||
resItem.subagentConversationId ||
|
||||
resItem.cascadeId ||
|
||||
specItem.conversationId ||
|
||||
specItem.subagentConversationId ||
|
||||
specItem.cascadeId ||
|
||||
fallbackInvCid
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (!cid) continue;
|
||||
const role = String(specItem.role || toolArgs.Role || toolArgs.role || '').trim();
|
||||
const typeName = String(
|
||||
specItem.typeName || toolArgs.TypeName || toolArgs.typeName || ''
|
||||
).trim();
|
||||
const prev = refsMap.get(cid);
|
||||
refsMap.set(cid, {
|
||||
cascadeId: cid,
|
||||
role: role || prev?.role || '',
|
||||
typeName: typeName || prev?.typeName || '',
|
||||
createdTimeMs: createdTimeMs || prev?.createdTimeMs || 0,
|
||||
spawnOrder: prev ? prev.spawnOrder : orderCounter++,
|
||||
});
|
||||
}
|
||||
}
|
||||
return Array.from(refsMap.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 `GetCascadeTrajectory` 响应的 `trajectory.metadata` 中提取子代理归属关系与角色元数据。
|
||||
*
|
||||
* @param {object} trajRes
|
||||
* @param {object} [fallback={}]
|
||||
*/
|
||||
function extractTrajectorySubagentMeta(trajRes, fallback = {}) {
|
||||
const meta =
|
||||
trajRes?.trajectory?.metadata ||
|
||||
trajRes?.trajectory?.trajectoryMetadata ||
|
||||
trajRes?.trajectoryMetadata ||
|
||||
{};
|
||||
const parentConversationId = String(
|
||||
meta.parentConversationId || fallback.parentConversationId || ''
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const rootConversationId = String(
|
||||
meta.rootConversationId || fallback.rootConversationId || parentConversationId || ''
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
const subagentSpec = mergeSubagentSpecs(meta.subagentSpec, fallback.subagentSpec);
|
||||
const agentScriptName = String(
|
||||
meta.agentScript?.name || fallback.agentScriptName || ''
|
||||
).trim();
|
||||
const createdTimeMs =
|
||||
parseIsoMs(meta.createdAt || meta.createdTime) || fallback.createdTimeMs || 0;
|
||||
return {
|
||||
parentConversationId,
|
||||
rootConversationId,
|
||||
subagentSpec,
|
||||
agentScriptName,
|
||||
createdTimeMs,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 枚举所有会话(合并 LS `trajectorySummaries`、本地磁盘文件与 `trajectoryCache`),
|
||||
* 选定当前活跃会话,并以最多 4 路并发增量同步更新了的会话轨迹。
|
||||
@@ -193,8 +333,19 @@ export async function enumerateAndSyncConversations({
|
||||
...diskConvMap.keys(),
|
||||
...Object.keys(trajectoryCache),
|
||||
]);
|
||||
const existingLowerIds = new Set(Array.from(allCascadeIds, (id) => id.toLowerCase()));
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
for (const ref of entry?.subagentRefs || []) {
|
||||
const refCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||
if (refCid && !existingLowerIds.has(refCid)) {
|
||||
allCascadeIds.add(refCid);
|
||||
existingLowerIds.add(refCid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const conversations = [];
|
||||
const reqLower = String(requestedConvId || '').trim().toLowerCase();
|
||||
const rawConversations = [];
|
||||
for (const cascadeId of allCascadeIds) {
|
||||
const item = summariesObj[cascadeId];
|
||||
const cached = trajectoryCache[cascadeId];
|
||||
@@ -207,141 +358,534 @@ export async function enumerateAndSyncConversations({
|
||||
continue;
|
||||
}
|
||||
const diskMtimeMs = diskConvMap.get(cascadeId) || 0;
|
||||
const rawMeta = item?.trajectoryMetadata || item?.metadata || {};
|
||||
const parentConversationId = String(
|
||||
rawMeta.parentConversationId || cached?.parentConversationId || ''
|
||||
).toLowerCase();
|
||||
const rootConversationId = String(
|
||||
rawMeta.rootConversationId || cached?.rootConversationId || parentConversationId || ''
|
||||
).toLowerCase();
|
||||
const subagentSpec = mergeSubagentSpecs(rawMeta.subagentSpec, cached?.subagentSpec);
|
||||
const agentScriptName = rawMeta.agentScript?.name || cached?.agentScriptName || '';
|
||||
const createdTimeMs =
|
||||
parseIsoMs(item?.createdTime || rawMeta?.createdAt) || cached?.createdTimeMs || 0;
|
||||
const spawnOrder = Number.isFinite(cached?.spawnOrder) ? cached.spawnOrder : null;
|
||||
const subagentRefs = Array.isArray(cached?.subagentRefs) ? cached.subagentRefs : null;
|
||||
const isSubagent =
|
||||
Boolean(parentConversationId) ||
|
||||
Boolean(rootConversationId && rootConversationId !== cascadeId.toLowerCase());
|
||||
|
||||
if (item) {
|
||||
const lastModifiedTime = item?.lastModifiedTime || item?.createdTime || '';
|
||||
const lastModifiedMs =
|
||||
parseIsoMs(lastModifiedTime) || diskMtimeMs || cached?.lastModifiedMs || 0;
|
||||
conversations.push({
|
||||
const rawSummaryStepCount = Number(item?.stepCount || 0);
|
||||
const modelStepCount = Array.isArray(cached?.steps)
|
||||
? cached.steps.length
|
||||
: rawSummaryStepCount;
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title:
|
||||
item?.annotations?.title || item?.summary || cached?.title || cascadeId.slice(0, 8),
|
||||
stepCount: Number(item?.stepCount || cached?.steps?.length || 0),
|
||||
stepCount: modelStepCount,
|
||||
rawStepCount: rawSummaryStepCount,
|
||||
status: item?.status || '',
|
||||
lastModifiedTime,
|
||||
lastModifiedMs,
|
||||
diskMtimeMs,
|
||||
inSummaries: true,
|
||||
isSubagent,
|
||||
parentConversationId,
|
||||
rootConversationId,
|
||||
subagentSpec,
|
||||
agentScriptName,
|
||||
createdTimeMs,
|
||||
spawnOrder,
|
||||
subagentRefs,
|
||||
});
|
||||
} else if (cached) {
|
||||
const lastStepMs = cached.steps?.[cached.steps.length - 1]?.createdAtMs || 0;
|
||||
conversations.push({
|
||||
const cachedStepCount = Number(cached.steps?.length || 0);
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title: cached.title || cascadeId.slice(0, 8),
|
||||
stepCount: Number(cached.steps?.length || 0),
|
||||
stepCount: cachedStepCount,
|
||||
rawStepCount: cachedStepCount,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: Math.max(cached.lastModifiedMs || 0, lastStepMs, diskMtimeMs),
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
isSubagent,
|
||||
parentConversationId,
|
||||
rootConversationId,
|
||||
subagentSpec,
|
||||
agentScriptName,
|
||||
createdTimeMs,
|
||||
spawnOrder,
|
||||
subagentRefs,
|
||||
});
|
||||
} else {
|
||||
conversations.push({
|
||||
rawConversations.push({
|
||||
cascadeId,
|
||||
title: cascadeId.slice(0, 8),
|
||||
stepCount: 0,
|
||||
rawStepCount: 0,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: diskMtimeMs,
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
needsInitialLoad: true,
|
||||
isSubagent: false,
|
||||
parentConversationId: '',
|
||||
rootConversationId: '',
|
||||
subagentSpec: null,
|
||||
agentScriptName: '',
|
||||
createdTimeMs: 0,
|
||||
spawnOrder: null,
|
||||
subagentRefs: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
conversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
||||
|
||||
// 选定当前活跃会话:若指定了有效 requestedConvId 则优先使用,否则取最近修改的会话
|
||||
const activeConvSummary =
|
||||
conversations.find((c) => c.cascadeId === requestedConvId) || conversations[0] || null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
|
||||
rawConversations.sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);
|
||||
|
||||
let cacheDirty = cacheState.needsSave;
|
||||
const attemptedFetchIds = new Set();
|
||||
const nowPollMs = Date.now();
|
||||
|
||||
const toFetch = conversations.filter((conv) => {
|
||||
function buildConvSig(conv) {
|
||||
return conv.inSummaries
|
||||
? `${CACHE_SCHEMA_VERSION}:${conv.rawStepCount ?? conv.stepCount}:${conv.lastModifiedTime}`
|
||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||
}
|
||||
|
||||
function isFetchInCooldown(conv, sig) {
|
||||
if (conv.status === 'CASCADE_RUN_STATUS_RUNNING') return false;
|
||||
if (reqLower && conv.cascadeId.toLowerCase() === reqLower) return false;
|
||||
const key = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||
const failedAt = failedFetchCooldownMap.get(key);
|
||||
if (!failedAt) return false;
|
||||
if (nowPollMs - failedAt >= FAILED_RPC_COOLDOWN_MS) {
|
||||
failedFetchCooldownMap.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查缓存条目是否缺少最新分解字段(含 10 通道上下文细分字段 `toolResultsTokens`)。
|
||||
*/
|
||||
function hasMissingStepFields(cached) {
|
||||
const steps = cached?.steps || [];
|
||||
const lastCachedStep = steps[steps.length - 1];
|
||||
if (!lastCachedStep) return false;
|
||||
if (!Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown')) {
|
||||
return true;
|
||||
}
|
||||
if (steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel'))) {
|
||||
return true;
|
||||
}
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
if (steps[i]?.contextBreakdown) {
|
||||
return !Object.prototype.hasOwnProperty.call(
|
||||
steps[i].contextBreakdown,
|
||||
'toolResultsTokens'
|
||||
);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量拉取会话轨迹并提取步骤、子代理元数据 (`trajectory.metadata`) 与子代理调用引用 (`invokeSubagent`)。
|
||||
*
|
||||
* @param {object[]} targetConvs
|
||||
*/
|
||||
async function fetchTrajectoryBatch(targetConvs) {
|
||||
for (const c of targetConvs) {
|
||||
attemptedFetchIds.add(c.cascadeId.toLowerCase());
|
||||
}
|
||||
for (let i = 0; i < targetConvs.length; i += MAX_CONCURRENT_RPC) {
|
||||
const batch = targetConvs.slice(i, i + MAX_CONCURRENT_RPC);
|
||||
await Promise.all(
|
||||
batch.map(async (conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
const cooldownKey = `${conv.cascadeId.toLowerCase()}::${sig}`;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const prev = trajectoryCache[conv.cascadeId];
|
||||
try {
|
||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||
throw new Error('Trajectory steps unavailable');
|
||||
}
|
||||
const rawSteps = trajRes.trajectory.steps;
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
}
|
||||
failedFetchCooldownMap.delete(cooldownKey);
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const nextLast = steps[steps.length - 1];
|
||||
|
||||
// 提取轨迹内携带的子代理归属元数据与派生的子代理引用列表
|
||||
const extractedMeta = extractTrajectorySubagentMeta(trajRes, conv);
|
||||
conv.parentConversationId = extractedMeta.parentConversationId;
|
||||
conv.rootConversationId = extractedMeta.rootConversationId;
|
||||
conv.subagentSpec = extractedMeta.subagentSpec;
|
||||
conv.agentScriptName = extractedMeta.agentScriptName;
|
||||
conv.createdTimeMs = extractedMeta.createdTimeMs;
|
||||
conv.isSubagent =
|
||||
Boolean(conv.parentConversationId) ||
|
||||
Boolean(
|
||||
conv.rootConversationId &&
|
||||
conv.rootConversationId !== conv.cascadeId.toLowerCase()
|
||||
);
|
||||
|
||||
const subagentRefs = extractSubagentRefsFromSteps(rawSteps);
|
||||
conv.subagentRefs = subagentRefs;
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs);
|
||||
conv.lastModifiedMs = resolvedLastModMs;
|
||||
conv.stepCount = steps.length;
|
||||
|
||||
const cacheEntry = {
|
||||
signature: sig,
|
||||
accountName: currentAccountName || prev?.accountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
wasRunning: isRunning,
|
||||
steps,
|
||||
subagentRefs,
|
||||
};
|
||||
if (conv.isSubagent) {
|
||||
cacheEntry.parentConversationId = conv.parentConversationId;
|
||||
cacheEntry.rootConversationId = conv.rootConversationId;
|
||||
if (conv.subagentSpec) cacheEntry.subagentSpec = conv.subagentSpec;
|
||||
if (conv.agentScriptName) cacheEntry.agentScriptName = conv.agentScriptName;
|
||||
if (conv.createdTimeMs) cacheEntry.createdTimeMs = conv.createdTimeMs;
|
||||
if (Number.isFinite(conv.spawnOrder)) cacheEntry.spawnOrder = conv.spawnOrder;
|
||||
}
|
||||
|
||||
const metaChanged =
|
||||
!Array.isArray(prev?.subagentRefs) ||
|
||||
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
|
||||
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '');
|
||||
const stepsChanged =
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
metaChanged ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
|
||||
trajectoryCache[conv.cascadeId] = cacheEntry;
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||
if (!isRunning) {
|
||||
failedFetchCooldownMap.set(cooldownKey, nowPollMs);
|
||||
}
|
||||
if (
|
||||
prev &&
|
||||
String(prev.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
|
||||
!Array.isArray(prev.subagentRefs)
|
||||
) {
|
||||
prev.subagentRefs = [];
|
||||
cacheDirty = true;
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 阶段 1:拉取常规新增/变更会话,以及摘要列表中尚未提取 subagentRefs 的会话
|
||||
const toFetch = rawConversations.filter((conv) => {
|
||||
const sig = buildConvSig(conv);
|
||||
if (isFetchInCooldown(conv, sig)) return false;
|
||||
const cached = trajectoryCache[conv.cascadeId];
|
||||
if (!cached || conv.needsInitialLoad) return true;
|
||||
const hasCurrentSchema = String(cached.signature || '').startsWith(
|
||||
`${CACHE_SCHEMA_VERSION}:`
|
||||
);
|
||||
if (!hasCurrentSchema) return true;
|
||||
const lastCachedStep = cached.steps?.[cached.steps.length - 1];
|
||||
const missingBreakdownField =
|
||||
Boolean(lastCachedStep) &&
|
||||
(!Object.prototype.hasOwnProperty.call(lastCachedStep, 'contextBreakdown') ||
|
||||
cached.steps.some((s) => !Object.prototype.hasOwnProperty.call(s, 'responseModel')));
|
||||
if (missingBreakdownField) return true;
|
||||
if (hasMissingStepFields(cached)) return true;
|
||||
const missingSubagentRefs = !Array.isArray(cached.subagentRefs);
|
||||
if (!conv.inSummaries) {
|
||||
if (missingSubagentRefs && conv.cascadeId.toLowerCase() === reqLower) {
|
||||
return true;
|
||||
}
|
||||
return (
|
||||
conv.diskMtimeMs > 0 &&
|
||||
conv.diskMtimeMs > (cached.diskMtimeMs || cached.lastModifiedMs || 0)
|
||||
);
|
||||
}
|
||||
const sig = `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`;
|
||||
if (missingSubagentRefs) return true;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
return cached.signature !== sig || isRunning || Boolean(cached.wasRunning);
|
||||
});
|
||||
|
||||
// 限制并发度为 4,批量拉取需要更新的会话轨迹
|
||||
const CONCURRENCY = 4;
|
||||
for (let i = 0; i < toFetch.length; i += CONCURRENCY) {
|
||||
const batch = toFetch.slice(i, i + CONCURRENCY);
|
||||
await Promise.all(
|
||||
batch.map(async (conv) => {
|
||||
const sig = conv.inSummaries
|
||||
? `${CACHE_SCHEMA_VERSION}:${conv.stepCount}:${conv.lastModifiedTime}`
|
||||
: `${CACHE_SCHEMA_VERSION}:disk:${Math.floor(conv.diskMtimeMs || conv.lastModifiedMs || 0)}`;
|
||||
const isRunning = conv.status === 'CASCADE_RUN_STATUS_RUNNING';
|
||||
const prev = trajectoryCache[conv.cascadeId];
|
||||
try {
|
||||
const trajRes = await callLsRpc('GetCascadeTrajectory', { cascadeId: conv.cascadeId });
|
||||
if (!Array.isArray(trajRes?.trajectory?.steps)) {
|
||||
throw new Error('Trajectory steps unavailable');
|
||||
}
|
||||
const rawSteps = trajRes.trajectory.steps;
|
||||
if (Number(trajRes.numTotalSteps) > rawSteps.length) {
|
||||
throw new Error('Incomplete trajectory; retaining cached usage');
|
||||
}
|
||||
const generatorMeta = trajRes?.trajectory?.generatorMetadata || [];
|
||||
const steps = extractModelSteps(rawSteps, generatorMeta);
|
||||
const nextLast = steps[steps.length - 1];
|
||||
const stepsChanged =
|
||||
!prev ||
|
||||
prev.signature !== sig ||
|
||||
Boolean(prev.wasRunning) !== isRunning ||
|
||||
JSON.stringify(prev.steps) !== JSON.stringify(steps);
|
||||
await fetchTrajectoryBatch(toFetch);
|
||||
|
||||
const lastStepMs = nextLast?.createdAtMs || 0;
|
||||
const resolvedLastModMs = Math.max(conv.lastModifiedMs || 0, lastStepMs);
|
||||
conv.lastModifiedMs = resolvedLastModMs;
|
||||
if (!conv.inSummaries) {
|
||||
conv.stepCount = rawSteps.length || steps.length;
|
||||
/**
|
||||
* 阶段 2:根据父会话的 `subagentRefs` 将子代理归属关系、角色名称与启动顺序回填至子代理会话,
|
||||
* 支持多层嵌套子代理(主会话 -> 子代理 -> 二级子代理)逐层补拉与归属收敛。
|
||||
*/
|
||||
async function reconcileParentSubagentRefs() {
|
||||
for (let depth = 0; depth < MAX_SUBAGENT_RECONCILE_DEPTH; depth++) {
|
||||
const byLowerId = new Map(rawConversations.map((c) => [c.cascadeId.toLowerCase(), c]));
|
||||
const missingSubagentsToFetch = [];
|
||||
|
||||
for (const parentConv of [...rawConversations]) {
|
||||
const parentCached = trajectoryCache[parentConv.cascadeId];
|
||||
const refs = parentConv.subagentRefs || parentCached?.subagentRefs || [];
|
||||
if (!Array.isArray(refs) || refs.length === 0) continue;
|
||||
|
||||
const parentId = parentConv.cascadeId.toLowerCase();
|
||||
const rootId = (
|
||||
parentConv.rootConversationId ||
|
||||
parentConv.parentConversationId ||
|
||||
parentId
|
||||
).toLowerCase();
|
||||
|
||||
for (const ref of refs) {
|
||||
const subCid = String(ref?.cascadeId || '').trim().toLowerCase();
|
||||
if (!subCid || subCid === parentId) continue;
|
||||
|
||||
let subConv = byLowerId.get(subCid);
|
||||
const subCached = trajectoryCache[subConv?.cascadeId || subCid];
|
||||
if (!subConv) {
|
||||
const diskMtimeMs = diskConvMap.get(subCid) || 0;
|
||||
const lastStepMs = subCached?.steps?.[subCached.steps.length - 1]?.createdAtMs || 0;
|
||||
const stepCount = Number(subCached?.steps?.length || 0);
|
||||
subConv = {
|
||||
cascadeId: subCid,
|
||||
title: ref.role || subCached?.title || subCid.slice(0, 8),
|
||||
stepCount,
|
||||
rawStepCount: stepCount,
|
||||
status: 'IDLE',
|
||||
lastModifiedTime: '',
|
||||
lastModifiedMs: Math.max(
|
||||
subCached?.lastModifiedMs || 0,
|
||||
lastStepMs,
|
||||
diskMtimeMs,
|
||||
ref.createdTimeMs || 0
|
||||
),
|
||||
diskMtimeMs,
|
||||
inSummaries: false,
|
||||
needsInitialLoad: !subCached,
|
||||
isSubagent: true,
|
||||
parentConversationId: parentId,
|
||||
rootConversationId: rootId,
|
||||
subagentSpec: mergeSubagentSpecs(ref, subCached?.subagentSpec),
|
||||
agentScriptName: subCached?.agentScriptName || '',
|
||||
createdTimeMs: ref.createdTimeMs || subCached?.createdTimeMs || 0,
|
||||
spawnOrder: Number.isFinite(ref.spawnOrder) ? ref.spawnOrder : null,
|
||||
subagentRefs: Array.isArray(subCached?.subagentRefs) ? subCached.subagentRefs : null,
|
||||
};
|
||||
rawConversations.push(subConv);
|
||||
byLowerId.set(subCid, subConv);
|
||||
} else {
|
||||
subConv.isSubagent = true;
|
||||
subConv.parentConversationId = subConv.parentConversationId || parentId;
|
||||
subConv.rootConversationId = subConv.rootConversationId || rootId;
|
||||
subConv.subagentSpec = mergeSubagentSpecs(subConv.subagentSpec, ref);
|
||||
if (ref.createdTimeMs && !subConv.createdTimeMs) {
|
||||
subConv.createdTimeMs = ref.createdTimeMs;
|
||||
}
|
||||
if (Number.isFinite(ref.spawnOrder) && !Number.isFinite(subConv.spawnOrder)) {
|
||||
subConv.spawnOrder = ref.spawnOrder;
|
||||
}
|
||||
if (Array.isArray(subCached?.steps)) {
|
||||
subConv.stepCount = subCached.steps.length;
|
||||
}
|
||||
}
|
||||
|
||||
trajectoryCache[conv.cascadeId] = {
|
||||
signature: sig,
|
||||
accountName: currentAccountName || prev?.accountName || '',
|
||||
title: conv.title,
|
||||
lastModifiedMs: resolvedLastModMs,
|
||||
diskMtimeMs: conv.diskMtimeMs || 0,
|
||||
wasRunning: isRunning,
|
||||
steps,
|
||||
};
|
||||
if (stepsChanged) {
|
||||
cacheDirty = true;
|
||||
const targetCacheKey = subConv.cascadeId;
|
||||
const existingSubCache = trajectoryCache[targetCacheKey];
|
||||
const hasValidSubCache =
|
||||
existingSubCache &&
|
||||
String(existingSubCache.signature || '').startsWith(`${CACHE_SCHEMA_VERSION}:`) &&
|
||||
!hasMissingStepFields(existingSubCache);
|
||||
|
||||
if (hasValidSubCache) {
|
||||
let subMetaUpdated = false;
|
||||
if (existingSubCache.parentConversationId !== subConv.parentConversationId) {
|
||||
existingSubCache.parentConversationId = subConv.parentConversationId;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (existingSubCache.rootConversationId !== subConv.rootConversationId) {
|
||||
existingSubCache.rootConversationId = subConv.rootConversationId;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
const nextSpec = sanitizeSubagentSpec(subConv.subagentSpec);
|
||||
if (
|
||||
nextSpec &&
|
||||
JSON.stringify(existingSubCache.subagentSpec || null) !== JSON.stringify(nextSpec)
|
||||
) {
|
||||
existingSubCache.subagentSpec = nextSpec;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (
|
||||
subConv.createdTimeMs &&
|
||||
existingSubCache.createdTimeMs !== subConv.createdTimeMs
|
||||
) {
|
||||
existingSubCache.createdTimeMs = subConv.createdTimeMs;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (
|
||||
Number.isFinite(subConv.spawnOrder) &&
|
||||
existingSubCache.spawnOrder !== subConv.spawnOrder
|
||||
) {
|
||||
existingSubCache.spawnOrder = subConv.spawnOrder;
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (!Array.isArray(existingSubCache.subagentRefs)) {
|
||||
existingSubCache.subagentRefs = [];
|
||||
subMetaUpdated = true;
|
||||
}
|
||||
if (subMetaUpdated) {
|
||||
cacheDirty = true;
|
||||
}
|
||||
} else {
|
||||
const subSig = buildConvSig(subConv);
|
||||
if (!attemptedFetchIds.has(subCid) && !isFetchInCooldown(subConv, subSig)) {
|
||||
missingSubagentsToFetch.push(subConv);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed loading trajectory ${conv.cascadeId}: ${err.message}`);
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
if (missingSubagentsToFetch.length === 0) break;
|
||||
await fetchTrajectoryBatch(missingSubagentsToFetch);
|
||||
}
|
||||
}
|
||||
|
||||
await reconcileParentSubagentRefs();
|
||||
|
||||
// 阶段 3:对剩余尚未标记 subagentRefs 的纯磁盘历史会话每次增量迁移最多 8 个,避免单次轮询阻塞
|
||||
const remainingLegacyDiskConvs = rawConversations
|
||||
.filter((c) => {
|
||||
const sig = buildConvSig(c);
|
||||
if (attemptedFetchIds.has(c.cascadeId.toLowerCase()) || isFetchInCooldown(c, sig)) {
|
||||
return false;
|
||||
}
|
||||
const cached = trajectoryCache[c.cascadeId];
|
||||
return cached && !Array.isArray(cached.subagentRefs);
|
||||
})
|
||||
.slice(0, LEGACY_MIGRATION_BATCH_SIZE);
|
||||
|
||||
if (remainingLegacyDiskConvs.length > 0) {
|
||||
await fetchTrajectoryBatch(remainingLegacyDiskConvs);
|
||||
await reconcileParentSubagentRefs();
|
||||
}
|
||||
|
||||
// 阶段 4:将多层嵌套子代理的 rootConversationId 沿着父链向上收敛至最顶层根会话,防止二级子代理丢失
|
||||
const byId = new Map(rawConversations.map((c) => [c.cascadeId.toLowerCase(), c]));
|
||||
for (const conv of rawConversations) {
|
||||
if (!conv.isSubagent) continue;
|
||||
const cid = conv.cascadeId.toLowerCase();
|
||||
let candidate = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase();
|
||||
const visited = new Set([cid]);
|
||||
while (candidate && !visited.has(candidate)) {
|
||||
visited.add(candidate);
|
||||
const ancestor = byId.get(candidate);
|
||||
if (!ancestor || !ancestor.isSubagent) break;
|
||||
const nextUp = (
|
||||
ancestor.parentConversationId ||
|
||||
ancestor.rootConversationId ||
|
||||
''
|
||||
).toLowerCase();
|
||||
if (!nextUp || nextUp === candidate) break;
|
||||
candidate = nextUp;
|
||||
}
|
||||
if (candidate && candidate !== conv.rootConversationId) {
|
||||
conv.rootConversationId = candidate;
|
||||
const cached = trajectoryCache[conv.cascadeId];
|
||||
if (cached && cached.rootConversationId !== candidate) {
|
||||
cached.rootConversationId = candidate;
|
||||
cacheDirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cacheDirty) {
|
||||
cacheState.needsSave = !saveJson(CACHE_FILE, trajectoryCache);
|
||||
}
|
||||
|
||||
// 按最终收敛的 rootConversationId 将所有层级的子代理挂载至对应顶层根会话下
|
||||
const subagentsByRoot = new Map();
|
||||
const conversations = [];
|
||||
|
||||
for (const conv of rawConversations) {
|
||||
const cid = conv.cascadeId.toLowerCase();
|
||||
const rootId = (conv.rootConversationId || conv.parentConversationId || '').toLowerCase();
|
||||
const rootTarget = byId.get(rootId);
|
||||
if (conv.isSubagent && rootId && rootId !== cid && rootTarget && !rootTarget.isSubagent) {
|
||||
if (!subagentsByRoot.has(rootId)) {
|
||||
subagentsByRoot.set(rootId, []);
|
||||
}
|
||||
subagentsByRoot.get(rootId).push(conv);
|
||||
} else if (!conv.isSubagent || !rootTarget) {
|
||||
conversations.push(conv);
|
||||
}
|
||||
}
|
||||
|
||||
for (const rootConv of conversations) {
|
||||
const cid = rootConv.cascadeId.toLowerCase();
|
||||
const subs = subagentsByRoot.get(cid) || [];
|
||||
subs.sort((a, b) => {
|
||||
if (
|
||||
a.parentConversationId === b.parentConversationId &&
|
||||
Number.isFinite(a.spawnOrder) &&
|
||||
Number.isFinite(b.spawnOrder) &&
|
||||
a.spawnOrder !== b.spawnOrder
|
||||
) {
|
||||
return a.spawnOrder - b.spawnOrder;
|
||||
}
|
||||
const aStart =
|
||||
a.createdTimeMs ||
|
||||
trajectoryCache[a.cascadeId]?.steps?.[0]?.createdAtMs ||
|
||||
a.lastModifiedMs ||
|
||||
0;
|
||||
const bStart =
|
||||
b.createdTimeMs ||
|
||||
trajectoryCache[b.cascadeId]?.steps?.[0]?.createdAtMs ||
|
||||
b.lastModifiedMs ||
|
||||
0;
|
||||
return aStart - bStart || String(a.cascadeId).localeCompare(String(b.cascadeId));
|
||||
});
|
||||
rootConv.subagents = subs;
|
||||
rootConv.subagentCount = subs.length;
|
||||
rootConv.totalStepCount =
|
||||
Number(rootConv.stepCount || 0) +
|
||||
subs.reduce((sum, s) => sum + Number(s.stepCount || 0), 0);
|
||||
const maxSubModMs = subs.reduce((m, s) => Math.max(m, s.lastModifiedMs || 0), 0);
|
||||
rootConv.groupLastModifiedMs = Math.max(rootConv.lastModifiedMs || 0, maxSubModMs);
|
||||
}
|
||||
|
||||
conversations.sort(
|
||||
(a, b) =>
|
||||
(b.groupLastModifiedMs || b.lastModifiedMs || 0) -
|
||||
(a.groupLastModifiedMs || a.lastModifiedMs || 0)
|
||||
);
|
||||
|
||||
// 选定当前活跃根会话:若指定了有效 requestedConvId(支持根会话 ID 或子代理 ID)则优先使用,否则取最近修改的根会话
|
||||
const activeConvSummary =
|
||||
(reqLower &&
|
||||
(conversations.find((c) => c.cascadeId.toLowerCase() === reqLower) ||
|
||||
conversations.find((c) =>
|
||||
(c.subagents || []).some((s) => s.cascadeId.toLowerCase() === reqLower)
|
||||
))) ||
|
||||
conversations[0] ||
|
||||
null;
|
||||
const activeCascadeId = activeConvSummary?.cascadeId || requestedConvId || null;
|
||||
|
||||
return {
|
||||
conversations,
|
||||
activeConvSummary,
|
||||
|
||||
@@ -195,7 +195,7 @@ export function compareSemver(a, b) {
|
||||
export function readInstalledPluginVersion() {
|
||||
const manifest = loadJson(PLUGIN_MANIFEST_FILE, null);
|
||||
const ver = typeof manifest?.version === 'string' ? manifest.version.trim() : '';
|
||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.0';
|
||||
return isValidSemver(ver) ? ver.replace(/^v/i, '') : '1.4.1';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,24 +36,18 @@ import { getCloudStatus } from './pricing-catalog.mjs';
|
||||
import { buildOfficialQuotaPools } from './quota-pools.mjs';
|
||||
import {
|
||||
aggregateMultiWindowUsage,
|
||||
buildScopedModelBreakdown,
|
||||
getNextMondayResetIso,
|
||||
} from './usage-aggregator.mjs';
|
||||
|
||||
/**
|
||||
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {Map<string, object>} dynamicModelMap 动态模型字典
|
||||
*/
|
||||
export function enrichActiveConversationSteps(activeSteps, dynamicModelMap) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionUnpricedCalls = 0;
|
||||
let sessionInputTokens = 0;
|
||||
let sessionCacheReadTokens = 0;
|
||||
const MAX_RECENT_CONVERSATIONS = 30;
|
||||
|
||||
// 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁
|
||||
/**
|
||||
* 构建全局 `modelKey -> responseModel` 已知映射表(单次轮询仅扫描一次 `trajectoryCache`)。
|
||||
*
|
||||
* @returns {Map<string, string>}
|
||||
*/
|
||||
function buildKnownUpstreamModelMap() {
|
||||
const knownUpstreamByModelKey = new Map();
|
||||
for (const entry of Object.values(trajectoryCache)) {
|
||||
for (const s of entry?.steps || []) {
|
||||
@@ -62,6 +56,30 @@ export function enrichActiveConversationSteps(activeSteps, dynamicModelMap) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return knownUpstreamByModelKey;
|
||||
}
|
||||
|
||||
/**
|
||||
* 为当前活跃会话的步骤补充模型标签、上游响应模型、单步费用、缓存命中率与生成速率指标。
|
||||
*
|
||||
* @param {object[]} activeSteps 当前会话的原始缓存步骤
|
||||
* @param {Map<string, object>} dynamicModelMap 动态模型字典
|
||||
* @param {Map<string, string>} [sharedUpstreamMap=null] 预先构建的已知上游模型映射表
|
||||
*/
|
||||
export function enrichActiveConversationSteps(
|
||||
activeSteps,
|
||||
dynamicModelMap,
|
||||
sharedUpstreamMap = null
|
||||
) {
|
||||
const sessionSpeed = summarizeSpeed(activeSteps);
|
||||
const sessionTtft = summarizeTtft(activeSteps);
|
||||
let sessionCostUsd = 0;
|
||||
let sessionUnpricedCalls = 0;
|
||||
let sessionInputTokens = 0;
|
||||
let sessionCacheReadTokens = 0;
|
||||
|
||||
// 记录已知的 modelKey -> 最近观测到的上游 responseModel,避免正在生成的步骤因尚未收到 generatorMetadata 而闪烁
|
||||
const knownUpstreamByModelKey = sharedUpstreamMap || buildKnownUpstreamModelMap();
|
||||
for (const s of activeSteps) {
|
||||
if (s?.modelKey && s.modelKey !== 'unknown' && s.responseModel) {
|
||||
knownUpstreamByModelKey.set(s.modelKey, s.responseModel);
|
||||
@@ -163,6 +181,16 @@ export function extractActiveContextTelemetry(
|
||||
}
|
||||
}
|
||||
const ctxMessages = Number(latestBreakdown?.messagesTokens || 0);
|
||||
const hasGranularMsgBreakdown =
|
||||
Boolean(latestBreakdown) &&
|
||||
Object.prototype.hasOwnProperty.call(latestBreakdown, 'toolResultsTokens');
|
||||
const ctxUserInput = hasGranularMsgBreakdown
|
||||
? Number(latestBreakdown?.userInputTokens || 0)
|
||||
: ctxMessages;
|
||||
const ctxAssistant = Number(latestBreakdown?.assistantTokens || 0);
|
||||
const ctxToolResults = Number(latestBreakdown?.toolResultsTokens || 0);
|
||||
const ctxSubagent = Number(latestBreakdown?.subagentTokens || 0);
|
||||
const ctxCheckpoint = Number(latestBreakdown?.checkpointTokens || 0);
|
||||
const ctxSystemTools = Number(latestBreakdown?.systemToolsTokens || 0);
|
||||
const ctxMcpTools = Number(latestBreakdown?.mcpToolsTokens || 0);
|
||||
const ctxSkills = Number(latestBreakdown?.skillsTokens || 0);
|
||||
@@ -207,6 +235,11 @@ export function extractActiveContextTelemetry(
|
||||
compactionLimitTokens,
|
||||
compactionUsedPct,
|
||||
messagesTokens: ctxMessages,
|
||||
userInputTokens: ctxUserInput,
|
||||
assistantTokens: ctxAssistant,
|
||||
toolResultsTokens: ctxToolResults,
|
||||
subagentTokens: ctxSubagent,
|
||||
checkpointTokens: ctxCheckpoint,
|
||||
systemToolsTokens: ctxSystemTools,
|
||||
mcpToolsTokens: ctxMcpTools,
|
||||
skillsTokens: ctxSkills,
|
||||
@@ -220,6 +253,88 @@ export function extractActiveContextTelemetry(
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建单个代理(主代理或子代理)的标准遥测单元对象,消除主/子代理 25 字段重复组装。
|
||||
*/
|
||||
function buildAgentUnitTelemetry({
|
||||
agentId,
|
||||
cascadeId,
|
||||
isMain,
|
||||
index,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
role,
|
||||
typeName,
|
||||
agentLabel,
|
||||
status,
|
||||
rawSteps,
|
||||
fallbackLastModMs,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps = true,
|
||||
}) {
|
||||
const enrichedRes = enrichActiveConversationSteps(
|
||||
rawSteps,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey
|
||||
);
|
||||
const taggedSteps = enrichedRes.enrichedActiveSteps.map((st) => ({
|
||||
...st,
|
||||
agentId,
|
||||
agentCascadeId: cascadeId,
|
||||
agentLabel,
|
||||
agentBadge: badgeText,
|
||||
agentRole: role,
|
||||
agentIndex: index,
|
||||
isSubagent: !isMain,
|
||||
}));
|
||||
const ctxRes = extractActiveContextTelemetry(
|
||||
taggedSteps,
|
||||
enrichedRes.latestEnriched,
|
||||
enrichedRes.sessionInputTokens,
|
||||
enrichedRes.sessionCacheReadTokens
|
||||
);
|
||||
const modelBreakdown = buildScopedModelBreakdown(taggedSteps, dynamicModelMap);
|
||||
const lastModifiedMs =
|
||||
enrichedRes.latestEnriched?.createdAtMs || fallbackLastModMs || 0;
|
||||
|
||||
return {
|
||||
enrichedRes,
|
||||
taggedSteps,
|
||||
ctxRes,
|
||||
telemetryUnit: {
|
||||
agentId,
|
||||
cascadeId,
|
||||
isMain,
|
||||
index,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
role,
|
||||
typeName,
|
||||
isRunning: status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: status || 'IDLE',
|
||||
stepCount: taggedSteps.length,
|
||||
latestTokPerSec: enrichedRes.latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: enrichedRes.latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: enrichedRes.latestEnriched?.selectedSpeedReason ?? null,
|
||||
avgTokPerSec: enrichedRes.sessionAvgTokPerSec,
|
||||
speedSummary: enrichedRes.sessionSpeed,
|
||||
ttftSummary: enrichedRes.sessionTtft,
|
||||
latestStepCostUsd: enrichedRes.latestEnriched?.costUsd ?? null,
|
||||
sessionCostUsd: +enrichedRes.sessionCostUsd.toFixed(2),
|
||||
sessionUnpricedCalls: enrichedRes.sessionUnpricedCalls,
|
||||
latestCacheHitPct: ctxRes.latestCacheHitPct,
|
||||
sessionCacheHitPct: ctxRes.sessionCacheHitPct,
|
||||
activeModelShort: enrichedRes.latestEnriched?.modelShort || '模型未知',
|
||||
activeModelLabel: enrichedRes.latestEnriched?.modelLabel || '模型未知',
|
||||
context: ctxRes.context,
|
||||
...(includeRecentSteps ? { recentSteps: taggedSteps.slice().reverse() } : {}),
|
||||
modelBreakdown,
|
||||
lastModifiedMs,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建完整的前端遥测载荷(核心内部实现,直接供单元测试沙箱调用)。
|
||||
*
|
||||
@@ -273,11 +388,31 @@ export async function buildTelemetryPayloadInternal(
|
||||
requestedConvId,
|
||||
});
|
||||
|
||||
// 3. 计算当前活跃会话的步骤指标与上下文拆解
|
||||
// 3. 计算当前活跃根会话及其子代理的步骤指标、6 通道上下文拆解与按模型汇总
|
||||
const knownUpstreamByModelKey = buildKnownUpstreamModelMap();
|
||||
const activeEntry = activeCascadeId ? trajectoryCache[activeCascadeId] : null;
|
||||
const activeSteps = activeEntry?.steps || [];
|
||||
const mainUnit = buildAgentUnitTelemetry({
|
||||
agentId: 'main',
|
||||
cascadeId: activeCascadeId,
|
||||
isMain: true,
|
||||
index: 0,
|
||||
shortLabel: '主代理',
|
||||
badgeText: '主',
|
||||
role: '主代理',
|
||||
typeName: 'root',
|
||||
agentLabel: '主代理',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
rawSteps: activeSteps,
|
||||
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
// 主代理步骤通过 activeConversation.recentSteps 下发一次,避免 JSON 重复序列化
|
||||
includeRecentSteps: false,
|
||||
});
|
||||
|
||||
const enrichedActiveSteps = mainUnit.taggedSteps;
|
||||
const {
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionSpeed,
|
||||
sessionTtft,
|
||||
@@ -286,25 +421,162 @@ export async function buildTelemetryPayloadInternal(
|
||||
sessionUnpricedCalls,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens,
|
||||
} = enrichActiveConversationSteps(activeSteps, dynamicModelMap);
|
||||
} = mainUnit.enrichedRes;
|
||||
const { latestCacheHitPct, sessionCacheHitPct, context } = mainUnit.ctxRes;
|
||||
const mainAgentTelemetry = mainUnit.telemetryUnit;
|
||||
const mainModelBreakdown = mainAgentTelemetry.modelBreakdown;
|
||||
|
||||
const { latestCacheHitPct, sessionCacheHitPct, context } = extractActiveContextTelemetry(
|
||||
enrichedActiveSteps,
|
||||
latestEnriched,
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens
|
||||
);
|
||||
const subagentSummaries = activeConvSummary?.subagents || [];
|
||||
const activeFamilyCascadeIds = new Set(activeCascadeId ? [activeCascadeId.toLowerCase()] : []);
|
||||
const subAgentTelemetries = [];
|
||||
const allCombinedRawSteps = [...activeSteps];
|
||||
const allCombinedEnrichedSteps = [...enrichedActiveSteps];
|
||||
let totalRawSessionCostUsd = sessionCostUsd;
|
||||
let totalFamilyInputTokens = sessionInputTokens;
|
||||
let totalFamilyCacheReadTokens = sessionCacheReadTokens;
|
||||
|
||||
// 4. 识别当前活跃会话绑定的模型池及其官方 5h / 周限重置锚点
|
||||
const latestIsArgon = latestEnriched
|
||||
for (let idx = 0; idx < subagentSummaries.length; idx++) {
|
||||
const subSum = subagentSummaries[idx];
|
||||
const subCid = subSum.cascadeId;
|
||||
activeFamilyCascadeIds.add(String(subCid || '').toLowerCase());
|
||||
const subEntry = trajectoryCache[subCid] || null;
|
||||
const subRawSteps = subEntry?.steps || [];
|
||||
allCombinedRawSteps.push(...subRawSteps);
|
||||
|
||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||
const rawRole =
|
||||
subSpec?.role || subSum.agentScriptName || subEntry?.agentScriptName || subSpec?.typeName || '';
|
||||
const subIndex = idx + 1;
|
||||
const shortLabel = `子代理 #${subIndex}`;
|
||||
const badgeText = `子${subIndex}`;
|
||||
const roleLabel = rawRole || '子代理';
|
||||
const typeName = subSpec?.typeName || '';
|
||||
|
||||
const subUnit = buildAgentUnitTelemetry({
|
||||
agentId: subCid,
|
||||
cascadeId: subCid,
|
||||
isMain: false,
|
||||
index: subIndex,
|
||||
shortLabel,
|
||||
badgeText,
|
||||
role: roleLabel,
|
||||
typeName,
|
||||
agentLabel: rawRole ? `${shortLabel} · ${rawRole}` : shortLabel,
|
||||
status: subSum.status || 'IDLE',
|
||||
rawSteps: subRawSteps,
|
||||
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
||||
dynamicModelMap,
|
||||
knownUpstreamByModelKey,
|
||||
includeRecentSteps: true,
|
||||
});
|
||||
|
||||
allCombinedEnrichedSteps.push(...subUnit.taggedSteps);
|
||||
totalRawSessionCostUsd += subUnit.enrichedRes.sessionCostUsd;
|
||||
totalFamilyInputTokens += subUnit.enrichedRes.sessionInputTokens;
|
||||
totalFamilyCacheReadTokens += subUnit.enrichedRes.sessionCacheReadTokens;
|
||||
subAgentTelemetries.push(subUnit.telemetryUnit);
|
||||
}
|
||||
|
||||
const allAgents = [mainAgentTelemetry, ...subAgentTelemetries];
|
||||
let aggregatedTelemetry = mainAgentTelemetry;
|
||||
|
||||
if (subAgentTelemetries.length > 0) {
|
||||
allCombinedRawSteps.sort(
|
||||
(a, b) => (a.createdAtMs || 0) - (b.createdAtMs || 0) || (a.stepIndex || 0) - (b.stepIndex || 0)
|
||||
);
|
||||
allCombinedEnrichedSteps.sort(
|
||||
(a, b) =>
|
||||
(a.createdAtMs || 0) - (b.createdAtMs || 0) ||
|
||||
(a.agentIndex || 0) - (b.agentIndex || 0) ||
|
||||
(a.stepIndex || 0) - (b.stepIndex || 0)
|
||||
);
|
||||
const combinedSpeed = summarizeSpeed(allCombinedRawSteps);
|
||||
const combinedTtft = summarizeTtft(allCombinedRawSteps);
|
||||
const combinedAvgTokPerSec = roundMetric(combinedSpeed.avgTokPerSec);
|
||||
const combinedModelBreakdown = buildScopedModelBreakdown(
|
||||
allCombinedEnrichedSteps,
|
||||
dynamicModelMap
|
||||
);
|
||||
|
||||
const runningAgent = allAgents.find((a) => a.isRunning);
|
||||
const latestActiveAgent =
|
||||
runningAgent ||
|
||||
allAgents
|
||||
.slice()
|
||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||
mainAgentTelemetry;
|
||||
|
||||
// 若刚启动的子代理尚无已完成步骤 (stepCount === 0),实时速率与上下文回退取最近有步骤的代理,避免闪现空白
|
||||
const agentsWithSteps = allAgents.filter((a) => a.stepCount > 0);
|
||||
const latestMetricAgent =
|
||||
latestActiveAgent.stepCount > 0
|
||||
? latestActiveAgent
|
||||
: agentsWithSteps.find((a) => a.isRunning) ||
|
||||
agentsWithSteps
|
||||
.slice()
|
||||
.sort((a, b) => (b.lastModifiedMs || 0) - (a.lastModifiedMs || 0))[0] ||
|
||||
latestActiveAgent;
|
||||
|
||||
const totalCostUsd = +totalRawSessionCostUsd.toFixed(2);
|
||||
const totalUnpricedCalls = allAgents.reduce(
|
||||
(sum, a) => sum + (a.sessionUnpricedCalls || 0),
|
||||
0
|
||||
);
|
||||
const totalFamilyPromptTokens = totalFamilyInputTokens + totalFamilyCacheReadTokens;
|
||||
const combinedSessionCacheHitPct =
|
||||
totalFamilyPromptTokens > 0
|
||||
? Math.round((totalFamilyCacheReadTokens / totalFamilyPromptTokens) * 100)
|
||||
: 0;
|
||||
|
||||
aggregatedTelemetry = {
|
||||
agentId: 'all',
|
||||
cascadeId: activeCascadeId,
|
||||
isMain: false,
|
||||
index: -1,
|
||||
shortLabel: '全部汇总',
|
||||
badgeText: '全部',
|
||||
role: `主代理 + ${subAgentTelemetries.length} 子代理`,
|
||||
typeName: 'all',
|
||||
activeAgentId: latestActiveAgent.agentId,
|
||||
activeAgentShortLabel: latestActiveAgent.shortLabel,
|
||||
activeAgentBadge: latestActiveAgent.badgeText,
|
||||
activeAgentRole: latestActiveAgent.role,
|
||||
isRunning: allAgents.some((a) => a.isRunning),
|
||||
status: allAgents.some((a) => a.isRunning) ? 'CASCADE_RUN_STATUS_RUNNING' : 'IDLE',
|
||||
stepCount: allCombinedEnrichedSteps.length,
|
||||
latestTokPerSec: latestMetricAgent.latestTokPerSec,
|
||||
latestTtftSec: latestMetricAgent.latestTtftSec,
|
||||
latestSpeedReason: latestMetricAgent.latestSpeedReason,
|
||||
avgTokPerSec: combinedAvgTokPerSec,
|
||||
speedSummary: combinedSpeed,
|
||||
ttftSummary: combinedTtft,
|
||||
latestStepCostUsd: latestMetricAgent.latestStepCostUsd,
|
||||
sessionCostUsd: totalCostUsd,
|
||||
sessionUnpricedCalls: totalUnpricedCalls,
|
||||
latestCacheHitPct: latestMetricAgent.latestCacheHitPct,
|
||||
sessionCacheHitPct: combinedSessionCacheHitPct,
|
||||
activeModelShort: latestMetricAgent.activeModelShort,
|
||||
activeModelLabel: latestMetricAgent.activeModelLabel,
|
||||
context: latestMetricAgent.context,
|
||||
modelBreakdown: combinedModelBreakdown,
|
||||
lastModifiedMs: latestActiveAgent.lastModifiedMs,
|
||||
};
|
||||
}
|
||||
|
||||
// 4. 识别当前活跃会话家族绑定的模型池及其官方 5h / 周限重置锚点
|
||||
const latestFamilyStep =
|
||||
allCombinedEnrichedSteps.length > 0
|
||||
? allCombinedEnrichedSteps[allCombinedEnrichedSteps.length - 1]
|
||||
: latestEnriched;
|
||||
const latestIsArgon = latestFamilyStep
|
||||
? isArgonModelIdentifier(
|
||||
latestEnriched.modelKey,
|
||||
latestEnriched.responseModel,
|
||||
latestEnriched.modelUpstream,
|
||||
latestEnriched.modelLabel
|
||||
latestFamilyStep.modelKey,
|
||||
latestFamilyStep.responseModel,
|
||||
latestFamilyStep.modelUpstream,
|
||||
latestFamilyStep.modelLabel
|
||||
)
|
||||
: false;
|
||||
const rawActiveFamily = latestEnriched?.family || 'Other';
|
||||
const rawActiveFamily = latestFamilyStep?.family || 'Other';
|
||||
const activePoolKey =
|
||||
latestIsArgon && quotaPoolsMap.has('Argon')
|
||||
? 'Argon'
|
||||
@@ -355,6 +627,7 @@ export async function buildTelemetryPayloadInternal(
|
||||
cycleAnchors,
|
||||
currentAccountName,
|
||||
activeCascadeId,
|
||||
activeFamilyCascadeIds,
|
||||
dynamicModelMap,
|
||||
});
|
||||
|
||||
@@ -446,13 +719,25 @@ export async function buildTelemetryPayloadInternal(
|
||||
aiCredits: realAiCredits > 0 ? realAiCredits : null,
|
||||
totalConversations: conversations.length,
|
||||
},
|
||||
conversations: conversations.slice(0, 30),
|
||||
conversations: conversations.slice(0, MAX_RECENT_CONVERSATIONS).map((c) => ({
|
||||
cascadeId: c.cascadeId,
|
||||
title: c.title,
|
||||
stepCount: c.stepCount,
|
||||
subagentCount: c.subagentCount || 0,
|
||||
totalStepCount: c.totalStepCount || c.stepCount || 0,
|
||||
status: c.status,
|
||||
lastModifiedTime: c.lastModifiedTime,
|
||||
lastModifiedMs: c.lastModifiedMs,
|
||||
})),
|
||||
activeConversation: {
|
||||
cascadeId: activeCascadeId,
|
||||
title: activeConvSummary?.title || '当前会话',
|
||||
isRunning: activeConvSummary?.status === 'CASCADE_RUN_STATUS_RUNNING',
|
||||
status: activeConvSummary?.status || 'IDLE',
|
||||
stepCount: enrichedActiveSteps.length,
|
||||
hasSubagents: subAgentTelemetries.length > 0,
|
||||
subagentCount: subAgentTelemetries.length,
|
||||
totalStepsAllAgents: allCombinedEnrichedSteps.length,
|
||||
latestTokPerSec: latestEnriched?.tokPerSec ?? null,
|
||||
latestTtftSec: latestEnriched?.ttftSec ?? null,
|
||||
latestSpeedReason: latestEnriched?.selectedSpeedReason ?? null,
|
||||
@@ -468,6 +753,9 @@ export async function buildTelemetryPayloadInternal(
|
||||
activeModelLabel: latestEnriched?.modelLabel || '模型未知',
|
||||
context,
|
||||
recentSteps: enrichedActiveSteps.slice().reverse(),
|
||||
modelBreakdown: mainModelBreakdown,
|
||||
agents: allAgents,
|
||||
aggregated: aggregatedTelemetry,
|
||||
},
|
||||
consumption: {
|
||||
selectedRange: {
|
||||
|
||||
@@ -227,6 +227,108 @@ export function finalizeUsageBucket(bucket) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 将单步统计数据累加至按模型分组的映射表中(供单代理、主+子汇总与全局时间范围共用)。
|
||||
*
|
||||
* @param {Map<string, object>} perModelStats
|
||||
* @param {object} st
|
||||
* @param {object} mInfo
|
||||
* @param {number|null} stepCost
|
||||
*/
|
||||
function accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost) {
|
||||
const stepTotalTokens =
|
||||
(st.inputTokens || 0) + (st.cacheReadTokens || 0) + (st.outputTokens || 0);
|
||||
const unpriced = stepCost === null ? 1 : 0;
|
||||
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
||||
|
||||
if (!perModelStats.has(modelGroupKey)) {
|
||||
perModelStats.set(modelGroupKey, {
|
||||
label: modelGroupKey,
|
||||
shortName: mInfo.shortName,
|
||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
if (st.responseModel) {
|
||||
agg.upstreamModelCounts.set(
|
||||
st.responseModel,
|
||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
||||
);
|
||||
}
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens || 0;
|
||||
agg.cacheReadTokens += st.cacheReadTokens || 0;
|
||||
agg.outputTokens += st.outputTokens || 0;
|
||||
agg.thinkingTokens += st.thinkingTokens || 0;
|
||||
agg.responseTokens += st.responseTokens || 0;
|
||||
agg.totalTokens += stepTotalTokens;
|
||||
agg.costUsd += stepCost ?? 0;
|
||||
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将按模型分组的统计映射表定型并排序为前端可渲染数组。
|
||||
*
|
||||
* @param {Map<string, object>} perModelStats
|
||||
* @returns {object[]}
|
||||
*/
|
||||
function finalizeModelBreakdownMap(perModelStats) {
|
||||
return Array.from(perModelStats.values())
|
||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||
.map(({ speedAccumulator, upstreamModelCounts, fallbackModelId, ...m }) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
const finishedSpeed = finishSpeed(speedAccumulator);
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec: roundMetric(finishedSpeed.avgTokPerSec),
|
||||
speedSummary: finishedSpeed,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 针对给定步骤数组构建按模型聚合的统计列表(供单代理、主+子汇总及全局时间范围复用)。
|
||||
*
|
||||
* @param {object[]} steps
|
||||
* @param {Map<string, object>} dynamicModelMap
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function buildScopedModelBreakdown(steps = [], dynamicModelMap) {
|
||||
const perModelStats = new Map();
|
||||
for (const st of steps) {
|
||||
const mInfo = resolveModelInfo(
|
||||
st.modelKey,
|
||||
dynamicModelMap,
|
||||
st.apiProvider,
|
||||
st.modelDisplayName,
|
||||
st.responseModel
|
||||
);
|
||||
const stepCost = computeStepCost(st, mInfo.pricing);
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
return finalizeModelBreakdownMap(perModelStats);
|
||||
}
|
||||
|
||||
/**
|
||||
* 聚合所有预设时间窗口、当前选定窗口、12 段趋势图、年度月序列、来源占比与分模型统计。
|
||||
*
|
||||
@@ -235,6 +337,7 @@ export function finalizeUsageBucket(bucket) {
|
||||
* cycleAnchors?: { fiveHourResetMs?: number, weeklyResetMs?: number },
|
||||
* currentAccountName?: string,
|
||||
* activeCascadeId?: string|null,
|
||||
* activeFamilyCascadeIds?: Set<string>|null,
|
||||
* dynamicModelMap: Map<string, object>
|
||||
* }} params
|
||||
*/
|
||||
@@ -243,8 +346,16 @@ export function aggregateMultiWindowUsage({
|
||||
cycleAnchors = {},
|
||||
currentAccountName = '',
|
||||
activeCascadeId = null,
|
||||
activeFamilyCascadeIds = null,
|
||||
dynamicModelMap,
|
||||
}) {
|
||||
const rawFamilyIds =
|
||||
activeFamilyCascadeIds instanceof Set
|
||||
? Array.from(activeFamilyCascadeIds)
|
||||
: activeCascadeId
|
||||
? [activeCascadeId]
|
||||
: [];
|
||||
const familySet = new Set(rawFamilyIds.map((id) => String(id || '').toLowerCase()));
|
||||
const nowMs = Date.now();
|
||||
const selectedWindow = resolveTimeWindow(
|
||||
filterOpts.range || 'all',
|
||||
@@ -293,24 +404,29 @@ export function aggregateMultiWindowUsage({
|
||||
const allEntriesToAggregate = [];
|
||||
|
||||
for (const [cascadeId, entry] of Object.entries(trajectoryCache)) {
|
||||
const cidLower = String(cascadeId || '').toLowerCase();
|
||||
if (
|
||||
entry?.accountName &&
|
||||
currentAccountName &&
|
||||
entry.accountName !== currentAccountName &&
|
||||
cascadeId !== activeCascadeId
|
||||
!familySet.has(cidLower)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const groupCascadeId = String(
|
||||
entry?.rootConversationId || entry?.parentConversationId || cascadeId
|
||||
).toLowerCase();
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId,
|
||||
cascadeId: groupCascadeId,
|
||||
appSource: entry?.appSource || 'standalone',
|
||||
steps: entry?.steps || [],
|
||||
isCurrentConv: cascadeId === activeCascadeId,
|
||||
isCurrentConv: familySet.has(cidLower),
|
||||
});
|
||||
}
|
||||
|
||||
for (const ext of externalConvos.values()) {
|
||||
const liveEntry = trajectoryCache[ext.cascadeId];
|
||||
const extCidLower = String(ext.cascadeId || '').toLowerCase();
|
||||
const liveEntry = trajectoryCache[ext.cascadeId] || trajectoryCache[extCidLower];
|
||||
if (
|
||||
ext.appSource === 'standalone' &&
|
||||
liveEntry &&
|
||||
@@ -319,10 +435,10 @@ export function aggregateMultiWindowUsage({
|
||||
continue;
|
||||
}
|
||||
allEntriesToAggregate.push({
|
||||
cascadeId: `${ext.appSource}:${ext.cascadeId}`,
|
||||
cascadeId: `${ext.appSource}:${extCidLower}`,
|
||||
appSource: ext.appSource || 'ide',
|
||||
steps: ext.steps || [],
|
||||
isCurrentConv: ext.cascadeId === activeCascadeId && !liveEntry,
|
||||
isCurrentConv: familySet.has(extCidLower) && !liveEntry,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -412,43 +528,7 @@ export function aggregateMultiWindowUsage({
|
||||
sAgg.costUsd += stepCost ?? 0;
|
||||
sAgg.unpricedCalls = (sAgg.unpricedCalls || 0) + unpriced;
|
||||
|
||||
const modelGroupKey = mInfo.baseLabel || mInfo.label;
|
||||
if (!perModelStats.has(modelGroupKey)) {
|
||||
perModelStats.set(modelGroupKey, {
|
||||
label: modelGroupKey,
|
||||
shortName: mInfo.shortName,
|
||||
fallbackModelId: mInfo.modelId && mInfo.modelId !== 'unknown' ? mInfo.modelId : '',
|
||||
upstreamModelCounts: new Map(),
|
||||
family: mInfo.family,
|
||||
calls: 0,
|
||||
inputTokens: 0,
|
||||
cacheReadTokens: 0,
|
||||
outputTokens: 0,
|
||||
thinkingTokens: 0,
|
||||
responseTokens: 0,
|
||||
totalTokens: 0,
|
||||
costUsd: 0,
|
||||
speedAccumulator: createSpeedAccumulator(),
|
||||
});
|
||||
}
|
||||
const agg = perModelStats.get(modelGroupKey);
|
||||
if (st.responseModel) {
|
||||
agg.upstreamModelCounts.set(
|
||||
st.responseModel,
|
||||
(agg.upstreamModelCounts.get(st.responseModel) || 0) + 1
|
||||
);
|
||||
}
|
||||
accumulateSpeed(agg.speedAccumulator, st);
|
||||
|
||||
agg.calls += 1;
|
||||
agg.inputTokens += st.inputTokens;
|
||||
agg.cacheReadTokens += st.cacheReadTokens;
|
||||
agg.outputTokens += st.outputTokens;
|
||||
agg.thinkingTokens += st.thinkingTokens || 0;
|
||||
agg.responseTokens += st.responseTokens || 0;
|
||||
agg.totalTokens += stepTotalTokens;
|
||||
agg.costUsd += stepCost ?? 0;
|
||||
agg.unpricedCalls = (agg.unpricedCalls || 0) + unpriced;
|
||||
accumulateStepIntoModelMap(perModelStats, st, mInfo, stepCost);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -517,24 +597,7 @@ export function aggregateMultiWindowUsage({
|
||||
|
||||
const todayBucket = finalizedPresets.today.account;
|
||||
const weekBucket = finalizedPresets.week.account;
|
||||
|
||||
const modelBreakdown = Array.from(perModelStats.values())
|
||||
.sort((a, b) => b.calls - a.calls || String(a.label).localeCompare(String(b.label)))
|
||||
.map(({ speedAccumulator, upstreamModelCounts, fallbackModelId, ...m }) => {
|
||||
const sortedUpstream = Array.from((upstreamModelCounts || new Map()).entries())
|
||||
.sort((a, b) => b[1] - a[1])
|
||||
.map(([name]) => name);
|
||||
const primaryUpstream =
|
||||
sortedUpstream.length > 0 ? sortedUpstream[0] : fallbackModelId || m.shortName || m.label;
|
||||
return {
|
||||
...m,
|
||||
upstreamName: primaryUpstream,
|
||||
upstreamModels: sortedUpstream,
|
||||
costUsd: +m.costUsd.toFixed(3),
|
||||
avgTokPerSec: roundMetric(finishSpeed(speedAccumulator).avgTokPerSec),
|
||||
speedSummary: finishSpeed(speedAccumulator),
|
||||
};
|
||||
});
|
||||
const modelBreakdown = finalizeModelBreakdownMap(perModelStats);
|
||||
|
||||
return {
|
||||
selectedWindow,
|
||||
|
||||
@@ -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=1793683297213">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794061385634">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1793683297213"></script>
|
||||
<script src="/app.js?v=1794061385634"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "usage-monitor-panel",
|
||||
"version": "1.4.0",
|
||||
"version": "1.4.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Sidecar backend and web UI for Antigravity Usage & Speed Monitor.",
|
||||
|
||||
@@ -217,6 +217,35 @@ function isMcpToolItem(name, source = '', type = '') {
|
||||
* totalTokens: number
|
||||
* } | null} 上下文 Token 构成明细,无任何可用元数据时返回 null
|
||||
*/
|
||||
/**
|
||||
* 识别 `TOKEN_TYPE_CHAT_MESSAGES` 子项(如 `"391: CHECKPOINT"`、`"404: GENERIC"`)所属的对话细分类型。
|
||||
*
|
||||
* @param {object} child
|
||||
* @returns {'checkpoint'|'assistant'|'subagent'|'userInput'|'toolResults'}
|
||||
*/
|
||||
function classifyChatMessageChild(child) {
|
||||
const rawName = String(child?.name || child?.type || '').trim().toUpperCase();
|
||||
const stepType = rawName.replace(/^\d+:\s*/, '');
|
||||
if (stepType.includes('CHECKPOINT') || stepType.includes('SUMMARY')) {
|
||||
return 'checkpoint';
|
||||
}
|
||||
if (
|
||||
stepType.includes('PLANNER_RESPONSE') ||
|
||||
stepType.includes('ASSISTANT') ||
|
||||
stepType.includes('MODEL')
|
||||
) {
|
||||
return 'assistant';
|
||||
}
|
||||
if (stepType.includes('SYSTEM_MESSAGE') || stepType.includes('SUBAGENT')) {
|
||||
return 'subagent';
|
||||
}
|
||||
if (stepType.includes('USER_INPUT') || stepType === 'USER') {
|
||||
return 'userInput';
|
||||
}
|
||||
// GENERIC, VIEW_FILE, RUN_COMMAND, CODE_ACTION 等均为工具调用返回结果
|
||||
return 'toolResults';
|
||||
}
|
||||
|
||||
export function extractContextBreakdown(chat) {
|
||||
if (!chat || typeof chat !== 'object') {
|
||||
return null;
|
||||
@@ -240,7 +269,11 @@ export function extractContextBreakdown(chat) {
|
||||
return null;
|
||||
}
|
||||
|
||||
let messagesTokens = 0;
|
||||
let userInputTokens = 0;
|
||||
let assistantTokens = 0;
|
||||
let toolResultsTokens = 0;
|
||||
let subagentTokens = 0;
|
||||
let checkpointTokens = 0;
|
||||
let systemToolsTokens = 0;
|
||||
let mcpToolsTokens = 0;
|
||||
let skillsTokens = 0;
|
||||
@@ -251,7 +284,7 @@ export function extractContextBreakdown(chat) {
|
||||
let hasToolsGroup = false;
|
||||
let hasMessagesGroup = false;
|
||||
|
||||
// 第一阶段:从原生 tokenBreakdown.groups 树状结构中提取并拆分 6 大上下文分类
|
||||
// 第一阶段:从原生 tokenBreakdown.groups 树状结构中提取并拆分 10 大上下文分类
|
||||
for (const g of groups) {
|
||||
const gType = String(g?.type || '').toUpperCase();
|
||||
const gName = String(g?.name || '').trim().toLowerCase();
|
||||
@@ -321,12 +354,29 @@ export function extractContextBreakdown(chat) {
|
||||
gName === 'messages'
|
||||
) {
|
||||
hasMessagesGroup = true;
|
||||
if (gTokens > 0) {
|
||||
messagesTokens += gTokens;
|
||||
} else {
|
||||
if (children.length > 0) {
|
||||
let childSum = 0;
|
||||
for (const c of children) {
|
||||
messagesTokens += Math.max(0, Number(c?.numTokens || 0));
|
||||
const tok = Math.max(0, Number(c?.numTokens || 0));
|
||||
childSum += tok;
|
||||
const msgBucket = classifyChatMessageChild(c);
|
||||
if (msgBucket === 'checkpoint') {
|
||||
checkpointTokens += tok;
|
||||
} else if (msgBucket === 'assistant') {
|
||||
assistantTokens += tok;
|
||||
} else if (msgBucket === 'subagent') {
|
||||
subagentTokens += tok;
|
||||
} else if (msgBucket === 'userInput') {
|
||||
userInputTokens += tok;
|
||||
} else {
|
||||
toolResultsTokens += tok;
|
||||
}
|
||||
}
|
||||
if (gTokens > childSum) {
|
||||
userInputTokens += gTokens - childSum;
|
||||
}
|
||||
} else if (gTokens > 0) {
|
||||
userInputTokens += gTokens;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -367,17 +417,36 @@ export function extractContextBreakdown(chat) {
|
||||
}
|
||||
}
|
||||
|
||||
// 第二阶段(C):当 groups 缺失对话消息分组时,回退到 messagePrompts 列表按文本字节数估算
|
||||
// 第二阶段(C):当 groups 缺失对话消息分组时,回退到 messagePrompts 列表按来源与内容特征分类估算
|
||||
if (!hasMessagesGroup && messagePrompts.length > 0) {
|
||||
for (const m of messagePrompts) {
|
||||
const text = String(m?.prompt ?? m?.content ?? '');
|
||||
const tok =
|
||||
Number.isFinite(Number(m?.numTokens)) && Number(m?.numTokens) >= 0
|
||||
? Number(m.numTokens)
|
||||
: estimateUtf8Tokens(m?.prompt ?? m?.content ?? '');
|
||||
messagesTokens += tok;
|
||||
: estimateUtf8Tokens(text);
|
||||
const src = String(m?.source || '').toUpperCase();
|
||||
if (src.includes('TOOL')) {
|
||||
toolResultsTokens += tok;
|
||||
} else if (src.includes('SYSTEM') || src.includes('ASSISTANT') || src.includes('MODEL')) {
|
||||
assistantTokens += tok;
|
||||
} else if (text.startsWith('<CONTEXT_SUMMARY>')) {
|
||||
checkpointTokens += tok;
|
||||
} else if (text.includes('<SYSTEM_MESSAGE>')) {
|
||||
subagentTokens += tok;
|
||||
} else {
|
||||
userInputTokens += tok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const messagesTokens =
|
||||
userInputTokens +
|
||||
assistantTokens +
|
||||
toolResultsTokens +
|
||||
subagentTokens +
|
||||
checkpointTokens;
|
||||
|
||||
const totalTokens =
|
||||
messagesTokens +
|
||||
systemToolsTokens +
|
||||
@@ -388,6 +457,11 @@ export function extractContextBreakdown(chat) {
|
||||
|
||||
return {
|
||||
messagesTokens,
|
||||
userInputTokens,
|
||||
assistantTokens,
|
||||
toolResultsTokens,
|
||||
subagentTokens,
|
||||
checkpointTokens,
|
||||
systemToolsTokens,
|
||||
mcpToolsTokens,
|
||||
skillsTokens,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
import { defineComponent } from './core/component.js';
|
||||
import { h, patchAttr } from './core/domPatch.js';
|
||||
import { telemetryStore } from './store/telemetryStore.js';
|
||||
import { resolveScopedConversation, telemetryStore } from './store/telemetryStore.js';
|
||||
import { uiStore, VIEW_TABS } from './store/uiStore.js';
|
||||
import { TopSessionHeader } from './components/layout/TopSessionHeader.js';
|
||||
import { TopLongPillNav } from './components/ui/TopLongPillNav.js';
|
||||
@@ -69,20 +69,38 @@ export const App = defineComponent({
|
||||
}
|
||||
);
|
||||
|
||||
function syncStepsBadge() {
|
||||
const { scopedConv } = resolveScopedConversation(
|
||||
telemetryStore.getState().telemetry,
|
||||
uiStore.getState().selectedAgentScope,
|
||||
uiStore.getState().ctxInspectorAgentId
|
||||
);
|
||||
const stepCount = scopedConv?.stepCount ?? 0;
|
||||
topPillNav.setProps({
|
||||
items: VIEW_TABS.map((t) =>
|
||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const unsubStepCount = telemetryStore.subscribe(
|
||||
(st) => st.telemetry?.activeConversation?.stepCount ?? 0,
|
||||
(stepCount) => {
|
||||
topPillNav.setProps({
|
||||
items: VIEW_TABS.map((t) =>
|
||||
t.value === 'steps' ? { ...t, badge: stepCount > 0 ? stepCount : '' } : t
|
||||
),
|
||||
});
|
||||
}
|
||||
(st) => ({
|
||||
stepCount: st.telemetry?.activeConversation?.stepCount ?? 0,
|
||||
totalStepsAllAgents: st.telemetry?.activeConversation?.totalStepsAllAgents ?? 0,
|
||||
subagentCount: st.telemetry?.activeConversation?.subagentCount ?? 0,
|
||||
}),
|
||||
() => syncStepsBadge()
|
||||
);
|
||||
|
||||
const unsubScopeBadge = uiStore.subscribe(
|
||||
(st) => st.selectedAgentScope,
|
||||
() => syncStepsBadge()
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubUi();
|
||||
unsubStepCount();
|
||||
unsubScopeBadge();
|
||||
sessionHeader.destroy();
|
||||
topPillNav.destroy();
|
||||
overviewView.destroy();
|
||||
|
||||
@@ -6,20 +6,36 @@
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
|
||||
import { formatUsd } from '../../core/formatters.js';
|
||||
import { createSvgIcon, patchSvgIcon } from '../../icons/SvgIcon.js';
|
||||
import { fetchTelemetry, telemetryStore, triggerPluginUpdate } from '../../store/telemetryStore.js';
|
||||
import {
|
||||
fetchTelemetry,
|
||||
formatAgentLabel,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
triggerPluginUpdate,
|
||||
} from '../../store/telemetryStore.js';
|
||||
import { uiStore } from '../../store/uiStore.js';
|
||||
import { CustomSelect } from '../ui/CustomSelect.js';
|
||||
|
||||
function formatConvOptionMeta(c) {
|
||||
if (!c) return '';
|
||||
const subs = Number(c.subagentCount || 0);
|
||||
if (subs > 0) {
|
||||
return `主${c.stepCount || 0} · ${subs}子 (共${c.totalStepCount || c.stepCount || 0}步)`;
|
||||
}
|
||||
return `${c.stepCount || 0}步`;
|
||||
}
|
||||
|
||||
export const TopSessionHeader = defineComponent({
|
||||
name: 'TopSessionHeader',
|
||||
setup({ onCleanup }) {
|
||||
const convSelect = CustomSelect({
|
||||
modelValue: telemetryStore.getState().selectedConversationId,
|
||||
icon: 'bolt',
|
||||
placeholder: '跟随最新会话',
|
||||
options: [{ value: '', label: '跟随最新会话' }],
|
||||
onUpdateModelValue: (nextConvId) => {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
telemetryStore.setState({ selectedConversationId: nextConvId });
|
||||
fetchTelemetry({ force: false });
|
||||
},
|
||||
@@ -76,116 +92,237 @@ export const TopSessionHeader = defineComponent({
|
||||
[createSvgIcon('refresh', { size: 13 })]
|
||||
);
|
||||
|
||||
const headerEl = h('header', { className: 'session-header' }, [
|
||||
const headerRowEl = h('div', { className: 'session-header' }, [
|
||||
h('div', { className: 'session-left' }, [convSelect.el]),
|
||||
h('div', { className: 'session-right' }, [updateBtn, statusTag, refreshBtn]),
|
||||
]);
|
||||
|
||||
// --- 方案 A:顶栏二级主/子代理切换条 (.agent-scope-bar,无子代理时自动隐藏) ---
|
||||
const scopeAllBtnText = h('span', { text: '全部汇总' });
|
||||
const scopeAllBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'scope-pill-btn is-active',
|
||||
onClick: () =>
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' }),
|
||||
},
|
||||
[scopeAllBtnText]
|
||||
);
|
||||
|
||||
const scopeMainBtnText = h('span', { text: '主代理' });
|
||||
const scopeMainBtn = h(
|
||||
'button',
|
||||
{
|
||||
type: 'button',
|
||||
className: 'scope-pill-btn',
|
||||
onClick: () => uiStore.setState({ selectedAgentScope: 'main' }),
|
||||
},
|
||||
[scopeMainBtnText]
|
||||
);
|
||||
|
||||
const subagentSelect = CustomSelect({
|
||||
modelValue: '',
|
||||
icon: 'cpu',
|
||||
placeholder: '子代理 (0)',
|
||||
className: 'scope-subagent-select',
|
||||
options: [],
|
||||
onUpdateModelValue: (nextSubId) => {
|
||||
if (nextSubId) {
|
||||
uiStore.setState({ selectedAgentScope: nextSubId });
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const scopeRightText = h('span', { className: 'agent-scope-right text-mono', text: '' });
|
||||
|
||||
const scopeBarEl = h(
|
||||
'div',
|
||||
{ className: 'agent-scope-bar', hidden: true },
|
||||
[
|
||||
h('div', { className: 'agent-scope-left' }, [
|
||||
scopeAllBtn,
|
||||
scopeMainBtn,
|
||||
subagentSelect.el,
|
||||
]),
|
||||
scopeRightText,
|
||||
]
|
||||
);
|
||||
|
||||
const headerEl = h('header', { className: 'top-session-stack' }, [headerRowEl, scopeBarEl]);
|
||||
|
||||
let lastActiveCascadeId = '';
|
||||
|
||||
function renderHeaderState() {
|
||||
const telSt = telemetryStore.getState();
|
||||
const uiSt = uiStore.getState();
|
||||
const telemetry = telSt.telemetry;
|
||||
const currentCascadeId = telemetry?.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && lastActiveCascadeId && currentCascadeId !== lastActiveCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
if (uiSt.selectedAgentScope !== 'all' || uiSt.ctxInspectorAgentId !== 'auto') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
return;
|
||||
}
|
||||
} else if (currentCascadeId) {
|
||||
lastActiveCascadeId = currentCascadeId;
|
||||
}
|
||||
|
||||
const convs = telemetry?.conversations || [];
|
||||
const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话';
|
||||
const options = [
|
||||
{ value: '', label: latestTitle, meta: convs[0] ? formatConvOptionMeta(convs[0]) : '' },
|
||||
...convs.map((c) => ({
|
||||
value: c.cascadeId,
|
||||
label: c.title || c.cascadeId.slice(0, 8),
|
||||
meta: formatConvOptionMeta(c),
|
||||
})),
|
||||
];
|
||||
convSelect.setProps({
|
||||
modelValue: telSt.selectedConversationId,
|
||||
options,
|
||||
});
|
||||
|
||||
const {
|
||||
hasSubagents,
|
||||
effectiveScope,
|
||||
subagents,
|
||||
mainAgent,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
} = resolveScopedConversation(telemetry, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId);
|
||||
|
||||
patchAttr(scopeBarEl, 'hidden', !hasSubagents);
|
||||
if (hasSubagents) {
|
||||
patchText(scopeAllBtnText, `全部 (${aggregated?.stepCount ?? 0})`);
|
||||
patchClasses(scopeAllBtn, { 'is-active': effectiveScope === 'all' });
|
||||
|
||||
patchText(scopeMainBtnText, `主代理 (${mainAgent?.stepCount ?? 0})`);
|
||||
patchClasses(scopeMainBtn, { 'is-active': effectiveScope === 'main' });
|
||||
|
||||
const isSubSelected = effectiveScope !== 'all' && effectiveScope !== 'main';
|
||||
patchClasses(subagentSelect.el, { 'is-active-sub': isSubSelected });
|
||||
const subOptions = subagents.map((s) => ({
|
||||
value: s.agentId,
|
||||
label: formatAgentLabel(s),
|
||||
meta: `${s.stepCount || 0}步 · 窗${s.context?.usedPct ?? 0}%`,
|
||||
}));
|
||||
subagentSelect.setProps({
|
||||
modelValue: isSubSelected ? effectiveScope : '',
|
||||
placeholder: `子代理 (${subagents.length})`,
|
||||
options: subOptions,
|
||||
});
|
||||
|
||||
patchText(
|
||||
scopeRightText,
|
||||
formatUsd(scopedConv?.sessionCostUsd || 0, {
|
||||
unpricedCalls: scopedConv?.sessionUnpricedCalls,
|
||||
})
|
||||
);
|
||||
} else {
|
||||
subagentSelect.close();
|
||||
}
|
||||
|
||||
const cloudStatus = telemetry?.cloudStatus;
|
||||
const hasUpdate = Boolean(cloudStatus?.updateAvailable);
|
||||
patchAttr(updateBtn, 'hidden', !hasUpdate);
|
||||
if (hasUpdate && !isHeaderUpdating) {
|
||||
patchText(
|
||||
updateBtnText,
|
||||
cloudStatus?.latestPluginVersion
|
||||
? `升级 v${cloudStatus.latestPluginVersion}`
|
||||
: '有新版本'
|
||||
);
|
||||
}
|
||||
|
||||
const isSyncing = telSt.syncState === 'syncing';
|
||||
const isSynced = telSt.syncState === 'synced';
|
||||
const isError = telSt.syncState === 'error';
|
||||
const isRunning = Boolean(aggregated?.isRunning || telemetry?.activeConversation?.isRunning);
|
||||
const quotaMeta = telemetry?.quotas?.meta;
|
||||
const quotaStale = Boolean(quotaMeta?.refreshFailed || quotaMeta?.isStale);
|
||||
|
||||
patchClasses(refreshBtn, { 'is-spinning': isSyncing });
|
||||
patchAttr(refreshBtn, 'disabled', isSyncing);
|
||||
|
||||
if (isSyncing) {
|
||||
patchSvgIcon(statusIcon, 'refresh');
|
||||
patchText(statusText, '同步中');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
'state-warn': false,
|
||||
});
|
||||
} else if (isSynced) {
|
||||
patchSvgIcon(statusIcon, 'check');
|
||||
patchText(statusText, '已刷新');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
'state-warn': false,
|
||||
});
|
||||
} else if (isError) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, '重试中');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
'state-warn': true,
|
||||
});
|
||||
} else if (isRunning) {
|
||||
const runningAgent = (telemetry?.activeConversation?.agents || []).find((a) => a.isRunning);
|
||||
const runSuffix =
|
||||
hasSubagents && runningAgent ? ` · ${runningAgent.badgeText || runningAgent.shortLabel}` : '';
|
||||
patchSvgIcon(statusIcon, 'bolt');
|
||||
patchText(statusText, `生成中${runSuffix}`);
|
||||
patchClasses(statusTag, {
|
||||
'state-running': true,
|
||||
'state-synced': false,
|
||||
'state-warn': false,
|
||||
});
|
||||
} else if (quotaStale) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
'state-warn': true,
|
||||
});
|
||||
} else {
|
||||
patchSvgIcon(statusIcon, 'pulse');
|
||||
patchText(statusText, '实时 2s');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
'state-warn': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const unsubTelemetry = telemetryStore.subscribe(
|
||||
(st) => ({
|
||||
selectedConversationId: st.selectedConversationId,
|
||||
syncState: st.syncState,
|
||||
conversations: st.telemetry?.conversations,
|
||||
isRunning: st.telemetry?.activeConversation?.isRunning,
|
||||
quotaMeta: st.telemetry?.quotas?.meta,
|
||||
cloudStatus: st.telemetry?.cloudStatus,
|
||||
telemetry: st.telemetry,
|
||||
}),
|
||||
(slice) => {
|
||||
const convs = slice.conversations || [];
|
||||
const latestTitle = convs[0]?.title ? `最新 (${convs[0].title})` : '跟随最新会话';
|
||||
const options = [
|
||||
{ value: '', label: latestTitle, meta: convs[0] ? `${convs[0].stepCount}步` : '' },
|
||||
...convs.map((c) => ({
|
||||
value: c.cascadeId,
|
||||
label: c.title || c.cascadeId.slice(0, 8),
|
||||
meta: `${c.stepCount || 0}步`,
|
||||
})),
|
||||
];
|
||||
convSelect.setProps({
|
||||
modelValue: slice.selectedConversationId,
|
||||
options,
|
||||
});
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
const hasUpdate = Boolean(slice.cloudStatus?.updateAvailable);
|
||||
patchAttr(updateBtn, 'hidden', !hasUpdate);
|
||||
if (hasUpdate && !isHeaderUpdating) {
|
||||
patchText(
|
||||
updateBtnText,
|
||||
slice.cloudStatus?.latestPluginVersion
|
||||
? `升级 v${slice.cloudStatus.latestPluginVersion}`
|
||||
: '有新版本'
|
||||
);
|
||||
}
|
||||
|
||||
const isSyncing = slice.syncState === 'syncing';
|
||||
const isSynced = slice.syncState === 'synced';
|
||||
const isError = slice.syncState === 'error';
|
||||
const isRunning = Boolean(slice.isRunning);
|
||||
const quotaStale = Boolean(slice.quotaMeta?.refreshFailed || slice.quotaMeta?.isStale);
|
||||
|
||||
patchClasses(refreshBtn, { 'is-spinning': isSyncing });
|
||||
patchAttr(refreshBtn, 'disabled', isSyncing);
|
||||
|
||||
if (isSyncing) {
|
||||
patchSvgIcon(statusIcon, 'refresh');
|
||||
patchText(statusText, '同步中');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
'state-warn': false,
|
||||
});
|
||||
} else if (isSynced) {
|
||||
patchSvgIcon(statusIcon, 'check');
|
||||
patchText(statusText, '已刷新');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': true,
|
||||
'state-warn': false,
|
||||
});
|
||||
} else if (isError) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, '重试中');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
'state-warn': true,
|
||||
});
|
||||
} else if (isRunning) {
|
||||
patchSvgIcon(statusIcon, 'bolt');
|
||||
patchText(statusText, '生成中');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': true,
|
||||
'state-synced': false,
|
||||
'state-warn': false,
|
||||
});
|
||||
} else if (quotaStale) {
|
||||
patchSvgIcon(statusIcon, 'warning');
|
||||
patchText(statusText, slice.quotaMeta?.hasOfficialData ? '额度缓存' : '额度离线');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
'state-warn': true,
|
||||
});
|
||||
} else {
|
||||
patchSvgIcon(statusIcon, 'pulse');
|
||||
patchText(statusText, '实时 2s');
|
||||
patchClasses(statusTag, {
|
||||
'state-running': false,
|
||||
'state-synced': false,
|
||||
'state-warn': false,
|
||||
});
|
||||
}
|
||||
}
|
||||
const unsubUi = uiStore.subscribe(
|
||||
(st) => st.selectedAgentScope,
|
||||
() => renderHeaderState()
|
||||
);
|
||||
|
||||
onCleanup(() => {
|
||||
unsubTelemetry();
|
||||
unsubUi();
|
||||
convSelect.destroy();
|
||||
subagentSelect.destroy();
|
||||
});
|
||||
|
||||
return {
|
||||
el: headerEl,
|
||||
refs: { convSelect, statusTag, refreshBtn },
|
||||
refs: { convSelect, subagentSelect, statusTag, refreshBtn, scopeBarEl },
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,20 +1,37 @@
|
||||
/**
|
||||
* @fileoverview 6-channel segmented context window progress bar updated via
|
||||
* CSS custom variables against the current model's automatic compaction baseline.
|
||||
* @fileoverview 10-channel segmented context window progress bar updated via
|
||||
* CSS custom variables against the current model's automatic compaction baseline,
|
||||
* dynamically ordered from largest to smallest segment.
|
||||
*/
|
||||
|
||||
import { defineComponent } from '../../core/component.js';
|
||||
import { h, patchAttr, patchStyleVar } from '../../core/domPatch.js';
|
||||
|
||||
const SEGMENT_DEFS = [
|
||||
{ key: 'assistant', cls: 'seg-assistant', getVal: (c) => Number(c.assistantTokens || 0) },
|
||||
{ key: 'toolResults', cls: 'seg-tool-results', getVal: (c) => Number(c.toolResultsTokens || 0) },
|
||||
{
|
||||
key: 'userInput',
|
||||
cls: 'seg-user-input',
|
||||
getVal: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{ key: 'subagent', cls: 'seg-subagent-msg', getVal: (c) => Number(c.subagentTokens || 0) },
|
||||
{ key: 'checkpoint', cls: 'seg-checkpoint', getVal: (c) => Number(c.checkpointTokens || 0) },
|
||||
{ key: 'systemPrompt', cls: 'seg-system-prompt', getVal: (c) => Number(c.systemPromptTokens || 0) },
|
||||
{ key: 'systemTools', cls: 'seg-system-tools', getVal: (c) => Number(c.systemToolsTokens || 0) },
|
||||
{ key: 'mcpTools', cls: 'seg-mcp-tools', getVal: (c) => Number(c.mcpToolsTokens || 0) },
|
||||
{ key: 'skills', cls: 'seg-skills', getVal: (c) => Number(c.skillsTokens || 0) },
|
||||
{ key: 'userRules', cls: 'seg-user-rules', getVal: (c) => Number(c.userRulesTokens || 0) },
|
||||
];
|
||||
|
||||
export const ContextSegmentMeter = defineComponent({
|
||||
name: 'ContextSegmentMeter',
|
||||
setup({ getProps }) {
|
||||
const segMessages = h('div', { className: 'progress-seg seg-messages' });
|
||||
const segSystemTools = h('div', { className: 'progress-seg seg-system-tools' });
|
||||
const segMcpTools = h('div', { className: 'progress-seg seg-mcp-tools' });
|
||||
const segSkills = h('div', { className: 'progress-seg seg-skills' });
|
||||
const segSystemPrompt = h('div', { className: 'progress-seg seg-system-prompt' });
|
||||
const segUserRules = h('div', { className: 'progress-seg seg-user-rules' });
|
||||
const segments = SEGMENT_DEFS.map((def, idx) => ({
|
||||
...def,
|
||||
defaultOrder: idx,
|
||||
el: h('div', { className: `progress-seg ${def.cls}` }),
|
||||
}));
|
||||
|
||||
const trackEl = h(
|
||||
'div',
|
||||
@@ -24,25 +41,30 @@ export const ContextSegmentMeter = defineComponent({
|
||||
'aria-valuemin': '0',
|
||||
'aria-valuemax': '100',
|
||||
},
|
||||
[segMessages, segSystemTools, segMcpTools, segSkills, segSystemPrompt, segUserRules]
|
||||
segments.map((s) => s.el)
|
||||
);
|
||||
|
||||
let lastOrderSig = segments.map((s) => s.key).join(',');
|
||||
|
||||
function syncMeter() {
|
||||
const ctx = getProps().context || {};
|
||||
const limit = Math.max(1, Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000));
|
||||
const pctMessages = Math.min(100, ((ctx.messagesTokens || 0) / limit) * 100);
|
||||
const pctSystemTools = Math.min(100, ((ctx.systemToolsTokens || 0) / limit) * 100);
|
||||
const pctMcpTools = Math.min(100, ((ctx.mcpToolsTokens || 0) / limit) * 100);
|
||||
const pctSkills = Math.min(100, ((ctx.skillsTokens || 0) / limit) * 100);
|
||||
const pctSystemPrompt = Math.min(100, ((ctx.systemPromptTokens || 0) / limit) * 100);
|
||||
const pctUserRules = Math.min(100, ((ctx.userRulesTokens || 0) / limit) * 100);
|
||||
const scored = segments.map((seg) => {
|
||||
const val = seg.getVal(ctx);
|
||||
const pct = Math.min(100, (val / limit) * 100);
|
||||
patchStyleVar(seg.el, '--seg-w', `${pct.toFixed(2)}%`);
|
||||
return { seg, val };
|
||||
});
|
||||
|
||||
scored.sort((a, b) => b.val - a.val || a.seg.defaultOrder - b.seg.defaultOrder);
|
||||
const nextOrderSig = scored.map((x) => x.seg.key).join(',');
|
||||
if (nextOrderSig !== lastOrderSig) {
|
||||
lastOrderSig = nextOrderSig;
|
||||
for (const { seg } of scored) {
|
||||
trackEl.appendChild(seg.el);
|
||||
}
|
||||
}
|
||||
|
||||
patchStyleVar(segMessages, '--seg-w', `${pctMessages.toFixed(2)}%`);
|
||||
patchStyleVar(segSystemTools, '--seg-w', `${pctSystemTools.toFixed(2)}%`);
|
||||
patchStyleVar(segMcpTools, '--seg-w', `${pctMcpTools.toFixed(2)}%`);
|
||||
patchStyleVar(segSkills, '--seg-w', `${pctSkills.toFixed(2)}%`);
|
||||
patchStyleVar(segSystemPrompt, '--seg-w', `${pctSystemPrompt.toFixed(2)}%`);
|
||||
patchStyleVar(segUserRules, '--seg-w', `${pctUserRules.toFixed(2)}%`);
|
||||
patchAttr(trackEl, 'aria-valuenow', Math.round(ctx.compactionUsedPct ?? ctx.usedPct ?? 0));
|
||||
}
|
||||
|
||||
@@ -50,14 +72,7 @@ export const ContextSegmentMeter = defineComponent({
|
||||
|
||||
return {
|
||||
el: trackEl,
|
||||
refs: {
|
||||
segMessages,
|
||||
segSystemTools,
|
||||
segMcpTools,
|
||||
segSkills,
|
||||
segSystemPrompt,
|
||||
segUserRules,
|
||||
},
|
||||
refs: { segments },
|
||||
onPropsChange: syncMeter,
|
||||
};
|
||||
},
|
||||
|
||||
@@ -13,7 +13,9 @@ export const CustomSelect = defineComponent({
|
||||
let isOpen = false;
|
||||
let focusedIndex = -1;
|
||||
|
||||
const leadIcon = createSvgIcon(getProps().icon || 'bolt', { size: 13 });
|
||||
const initialIcon = getProps().icon;
|
||||
const leadIcon = createSvgIcon(initialIcon || 'bolt', { size: 13 });
|
||||
patchAttr(leadIcon, 'hidden', !initialIcon);
|
||||
const triggerLabel = h('span', { className: 'select-label' });
|
||||
const chevronIcon = createSvgIcon('chevron-down', { size: 13 });
|
||||
|
||||
@@ -40,7 +42,8 @@ export const CustomSelect = defineComponent({
|
||||
hidden: true,
|
||||
});
|
||||
|
||||
const rootEl = h('div', { className: 'custom-select' }, [triggerBtn, menuEl]);
|
||||
const initialClass = ['custom-select', getProps().className].filter(Boolean).join(' ');
|
||||
const rootEl = h('div', { className: initialClass }, [triggerBtn, menuEl]);
|
||||
|
||||
function toggleOpen(nextOpen) {
|
||||
isOpen = Boolean(nextOpen);
|
||||
@@ -142,9 +145,16 @@ export const CustomSelect = defineComponent({
|
||||
}
|
||||
|
||||
function syncTriggerAndMenu() {
|
||||
const { options = [], modelValue, placeholder = '请选择', icon = 'bolt' } = getProps();
|
||||
patchSvgIcon(leadIcon, icon);
|
||||
const selectedOpt = options.find((o) => o.value === modelValue) || options[0];
|
||||
const { options = [], modelValue, placeholder = '请选择', icon } = getProps();
|
||||
patchAttr(leadIcon, 'hidden', !icon);
|
||||
if (icon) {
|
||||
patchSvgIcon(leadIcon, icon);
|
||||
}
|
||||
const selectedOpt =
|
||||
options.find((o) => o.value === modelValue) ||
|
||||
(modelValue !== '' && modelValue !== null && modelValue !== undefined
|
||||
? options[0]
|
||||
: undefined);
|
||||
patchText(triggerLabel, selectedOpt ? selectedOpt.label : placeholder);
|
||||
if (isOpen) {
|
||||
renderMenuOptions();
|
||||
|
||||
@@ -50,12 +50,9 @@ export function formatUsd(amount, { precise = false, estimated = false, unpriced
|
||||
|
||||
export function speedReasonText(reason) {
|
||||
return ({
|
||||
compaction: '自动压缩步骤,不计入均速',
|
||||
incomplete_or_invalid_timing: '生成未完成',
|
||||
invalid_output_tokens: '无有效输出',
|
||||
inconsistent_timing: '耗时数据异常',
|
||||
short_timing: '耗时过短,不计入',
|
||||
short_sample: '输出过短,不计入均速',
|
||||
legacy_cache: '旧版缓存记录',
|
||||
})[reason] || '';
|
||||
}
|
||||
|
||||
@@ -56,20 +56,69 @@ function isEquivalentTelemetry(prev, next) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、运行状态、TPS、TTFT、当前模型标识与单步费用)
|
||||
// 3. 比对活跃会话的实时测速指标(会话 ID、步数、子代理拓扑、运行状态、TPS、TTFT、当前模型标识与单步费用)
|
||||
if (pAct?.cascadeId !== nAct?.cascadeId) return false;
|
||||
if (pAct?.stepCount !== nAct?.stepCount) return false;
|
||||
if (pAct?.subagentCount !== nAct?.subagentCount) return false;
|
||||
if (pAct?.totalStepsAllAgents !== nAct?.totalStepsAllAgents) return false;
|
||||
if (pAct?.isRunning !== nAct?.isRunning) return false;
|
||||
if (pAct?.aggregated?.isRunning !== nAct?.aggregated?.isRunning) return false;
|
||||
if (pAct?.aggregated?.activeAgentId !== nAct?.aggregated?.activeAgentId) return false;
|
||||
if (pAct?.aggregated?.activeAgentBadge !== nAct?.aggregated?.activeAgentBadge) return false;
|
||||
if (pAct?.aggregated?.latestTokPerSec !== nAct?.aggregated?.latestTokPerSec) return false;
|
||||
if (pAct?.aggregated?.latestTtftSec !== nAct?.aggregated?.latestTtftSec) return false;
|
||||
if (pAct?.aggregated?.avgTokPerSec !== nAct?.aggregated?.avgTokPerSec) return false;
|
||||
if (pAct?.aggregated?.latestStepCostUsd !== nAct?.aggregated?.latestStepCostUsd) return false;
|
||||
if (pAct?.aggregated?.sessionCostUsd !== nAct?.aggregated?.sessionCostUsd) return false;
|
||||
if (pAct?.aggregated?.activeModelShort !== nAct?.aggregated?.activeModelShort) return false;
|
||||
if (pAct?.latestTokPerSec !== nAct?.latestTokPerSec) return false;
|
||||
if (pAct?.latestTtftSec !== nAct?.latestTtftSec) return false;
|
||||
if (pAct?.activeModelShort !== nAct?.activeModelShort || pAct?.activeModelLabel !== nAct?.activeModelLabel) return false;
|
||||
if (pAct?.latestStepCostUsd !== nAct?.latestStepCostUsd || pAct?.sessionUnpricedCalls !== nAct?.sessionUnpricedCalls) return false;
|
||||
|
||||
const pAgents = pAct?.agents || [];
|
||||
const nAgents = nAct?.agents || [];
|
||||
if (pAgents.length !== nAgents.length) return false;
|
||||
for (let i = 0; i < pAgents.length; i++) {
|
||||
const pa = pAgents[i];
|
||||
const na = nAgents[i];
|
||||
const pLastStep = pa?.recentSteps?.[0];
|
||||
const nLastStep = na?.recentSteps?.[0];
|
||||
if (
|
||||
pa?.agentId !== na?.agentId ||
|
||||
pa?.role !== na?.role ||
|
||||
pa?.stepCount !== na?.stepCount ||
|
||||
pa?.isRunning !== na?.isRunning ||
|
||||
pa?.latestTokPerSec !== na?.latestTokPerSec ||
|
||||
pa?.latestTtftSec !== na?.latestTtftSec ||
|
||||
pa?.avgTokPerSec !== na?.avgTokPerSec ||
|
||||
pa?.latestStepCostUsd !== na?.latestStepCostUsd ||
|
||||
pa?.sessionCostUsd !== na?.sessionCostUsd ||
|
||||
pa?.activeModelShort !== na?.activeModelShort ||
|
||||
pa?.context?.totalTokens !== na?.context?.totalTokens ||
|
||||
pa?.context?.messagesTokens !== na?.context?.messagesTokens ||
|
||||
pa?.context?.toolResultsTokens !== na?.context?.toolResultsTokens ||
|
||||
pa?.context?.assistantTokens !== na?.context?.assistantTokens ||
|
||||
pLastStep?.tokPerSec !== nLastStep?.tokPerSec ||
|
||||
pLastStep?.ttftSec !== nLastStep?.ttftSec ||
|
||||
pLastStep?.outputTokens !== nLastStep?.outputTokens ||
|
||||
pLastStep?.modelUpstream !== nLastStep?.modelUpstream ||
|
||||
pLastStep?.costUsd !== nLastStep?.costUsd
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 比对 6 通道上下文窗口构成(总 Token 与消息/系统工具/MCP/Skill/系统提示词/用户规则)及近期步骤明细
|
||||
const pCtx = pAct?.context;
|
||||
const nCtx = nAct?.context;
|
||||
if (pCtx?.totalTokens !== nCtx?.totalTokens) return false;
|
||||
if (pCtx?.messagesTokens !== nCtx?.messagesTokens) return false;
|
||||
if (pCtx?.assistantTokens !== nCtx?.assistantTokens) return false;
|
||||
if (pCtx?.toolResultsTokens !== nCtx?.toolResultsTokens) return false;
|
||||
if (pCtx?.userInputTokens !== nCtx?.userInputTokens) return false;
|
||||
if (pCtx?.subagentTokens !== nCtx?.subagentTokens) return false;
|
||||
if (pCtx?.checkpointTokens !== nCtx?.checkpointTokens) return false;
|
||||
if (pCtx?.systemToolsTokens !== nCtx?.systemToolsTokens) return false;
|
||||
if (pCtx?.mcpToolsTokens !== nCtx?.mcpToolsTokens) return false;
|
||||
if (pCtx?.skillsTokens !== nCtx?.skillsTokens) return false;
|
||||
@@ -179,7 +228,20 @@ function isEquivalentTelemetry(prev, next) {
|
||||
}
|
||||
}
|
||||
|
||||
if ((prev.conversations?.length || 0) !== (next.conversations?.length || 0)) return false;
|
||||
const pConvs = prev.conversations || [];
|
||||
const nConvs = next.conversations || [];
|
||||
if (pConvs.length !== nConvs.length) return false;
|
||||
for (let i = 0; i < pConvs.length; i++) {
|
||||
if (
|
||||
pConvs[i]?.cascadeId !== nConvs[i]?.cascadeId ||
|
||||
pConvs[i]?.title !== nConvs[i]?.title ||
|
||||
pConvs[i]?.stepCount !== nConvs[i]?.stepCount ||
|
||||
pConvs[i]?.subagentCount !== nConvs[i]?.subagentCount ||
|
||||
pConvs[i]?.totalStepCount !== nConvs[i]?.totalStepCount
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -336,3 +398,128 @@ export function stopAsyncTelemetryLoop() {
|
||||
pollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据代理索引返回对应的微边框语义徽章样式类名。
|
||||
*
|
||||
* @param {number} [index=0]
|
||||
* @param {boolean} [isMain=false]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function getAgentBadgeClass(index = 0, isMain = false) {
|
||||
if (isMain || index <= 0) return 'badge-main';
|
||||
const slot = ((index - 1) % 3) + 1;
|
||||
return `badge-sub-${slot}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 格式化主/子代理的完整显示名称(如 `子代理 #1 · Codebase Researcher`)。
|
||||
*
|
||||
* @param {object|null|undefined} agent
|
||||
* @returns {string}
|
||||
*/
|
||||
export function formatAgentLabel(agent) {
|
||||
if (!agent) return '主代理';
|
||||
if (agent.isMain) return agent.shortLabel || '主代理';
|
||||
const rolePart = agent.role && agent.role !== '子代理' ? ` · ${agent.role}` : '';
|
||||
return `${agent.shortLabel || '子代理'}${rolePart}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析当前选中的主/子代理作用域视图数据与独立上下文窗口检视目标。
|
||||
* 同时在客户端按需组装主代理与全部汇总的 `recentSteps`,避免后端 JSON 载荷重复序列化 2-3 倍步骤列表。
|
||||
*
|
||||
* @param {object|null} telemetry
|
||||
* @param {string} [selectedAgentScope='all']
|
||||
* @param {string} [ctxInspectorAgentId='auto']
|
||||
*/
|
||||
export function resolveScopedConversation(
|
||||
telemetry,
|
||||
selectedAgentScope = 'all',
|
||||
ctxInspectorAgentId = 'auto'
|
||||
) {
|
||||
const active = telemetry?.activeConversation || {};
|
||||
const agents = Array.isArray(active.agents) && active.agents.length > 0 ? active.agents : [];
|
||||
const hasSubagents = Boolean(active.hasSubagents && agents.length > 1);
|
||||
const subagents = agents.filter((a) => !a.isMain);
|
||||
const mainAgent = agents.find((a) => a.isMain) || active;
|
||||
if (mainAgent && !Array.isArray(mainAgent.recentSteps) && Array.isArray(active.recentSteps)) {
|
||||
mainAgent.recentSteps = active.recentSteps;
|
||||
}
|
||||
const aggregated = active.aggregated || active;
|
||||
if (hasSubagents && aggregated && !Array.isArray(aggregated.recentSteps)) {
|
||||
const combined = [];
|
||||
for (const ag of agents) {
|
||||
const steps = ag.isMain ? ag.recentSteps || active.recentSteps || [] : ag.recentSteps || [];
|
||||
combined.push(...steps);
|
||||
}
|
||||
combined.sort(
|
||||
(a, b) =>
|
||||
(b.createdAtMs || 0) - (a.createdAtMs || 0) ||
|
||||
(b.agentIndex || 0) - (a.agentIndex || 0) ||
|
||||
(b.stepIndex || 0) - (a.stepIndex || 0)
|
||||
);
|
||||
aggregated.recentSteps = combined;
|
||||
}
|
||||
|
||||
if (!hasSubagents) {
|
||||
return {
|
||||
hasSubagents: false,
|
||||
effectiveScope: 'main',
|
||||
effectiveCtxScope: 'main',
|
||||
agents,
|
||||
subagents: [],
|
||||
mainAgent,
|
||||
aggregated,
|
||||
scopedConv: active,
|
||||
ctxAgent: mainAgent,
|
||||
};
|
||||
}
|
||||
|
||||
const isValidSub = subagents.some((s) => s.agentId === selectedAgentScope);
|
||||
const effectiveScope =
|
||||
selectedAgentScope === 'main'
|
||||
? 'main'
|
||||
: isValidSub
|
||||
? selectedAgentScope
|
||||
: 'all';
|
||||
|
||||
const scopedConv =
|
||||
effectiveScope === 'all'
|
||||
? aggregated
|
||||
: agents.find((a) => a.agentId === effectiveScope) || mainAgent;
|
||||
|
||||
let ctxAgent = scopedConv;
|
||||
let effectiveCtxScope = effectiveScope;
|
||||
if (effectiveScope === 'all') {
|
||||
if (ctxInspectorAgentId && ctxInspectorAgentId !== 'auto') {
|
||||
const matched = agents.find((a) => a.agentId === ctxInspectorAgentId);
|
||||
if (matched) {
|
||||
ctxAgent = matched;
|
||||
effectiveCtxScope = matched.agentId;
|
||||
} else {
|
||||
effectiveCtxScope = 'auto';
|
||||
}
|
||||
} else {
|
||||
effectiveCtxScope = 'auto';
|
||||
}
|
||||
if (effectiveCtxScope === 'auto') {
|
||||
ctxAgent =
|
||||
agents.find((a) => a.agentId === aggregated.activeAgentId) ||
|
||||
agents.find((a) => a.isRunning) ||
|
||||
mainAgent;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hasSubagents: true,
|
||||
effectiveScope,
|
||||
effectiveCtxScope,
|
||||
agents,
|
||||
subagents,
|
||||
mainAgent,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
ctxAgent,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,6 +14,8 @@ export const VIEW_TABS = Object.freeze([
|
||||
export const uiStore = createReactiveStore({
|
||||
activeView: 'overview',
|
||||
stepsSubTab: 'steps', // 'steps' | 'models'
|
||||
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
|
||||
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
|
||||
showAllPools: true,
|
||||
ctxBreakdownOpen: true,
|
||||
});
|
||||
|
||||
@@ -11,7 +11,13 @@
|
||||
* 8. 设置表单行与主次操作按钮 (.form-row, .btn-primary, .btn-secondary, .cloud-actions-row)
|
||||
*/
|
||||
|
||||
/* --- 1. 顶部会话控制栏 (Top Session Control Header) --- */
|
||||
/* --- 1. 顶部会话控制栏与二级代理切换条 (Top Session Control Header & Agent Scope Bar) --- */
|
||||
.top-session-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.session-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -23,6 +29,93 @@
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.agent-scope-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 4px var(--space-3);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.agent-scope-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.scope-pill-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11.5px;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.scope-pill-btn:hover {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.scope-pill-btn.is-active {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scope-subagent-select {
|
||||
flex: 1 1 115px;
|
||||
min-width: 105px;
|
||||
}
|
||||
|
||||
.scope-subagent-select .select-trigger {
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
font-size: 11.5px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
.scope-subagent-select.is-active-sub .select-trigger {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scope-subagent-select .select-menu,
|
||||
.steps-inline-scope-select .select-menu {
|
||||
left: auto;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.agent-scope-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.session-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -48,13 +48,18 @@
|
||||
--metric-danger: var(--destructive, hsl(0 74% 50%));
|
||||
--metric-danger-soft: color-mix(in srgb, var(--metric-danger) 15%, transparent);
|
||||
|
||||
/* Context Window 6-Channel Palette */
|
||||
/* Context Window 10-Channel Palette */
|
||||
--ctx-messages: hsl(217 82% 51%);
|
||||
--ctx-assistant: hsl(217 82% 54%);
|
||||
--ctx-tool-results: hsl(192 82% 43%);
|
||||
--ctx-user-input: hsl(245 72% 62%);
|
||||
--ctx-subagent-msg: hsl(280 70% 58%);
|
||||
--ctx-checkpoint: hsl(38 90% 50%);
|
||||
--ctx-system-tools: hsl(22 86% 50%);
|
||||
--ctx-mcp-tools: hsl(268 72% 56%);
|
||||
--ctx-mcp-tools: hsl(316 72% 54%);
|
||||
--ctx-skills: hsl(145 64% 38%);
|
||||
--ctx-system-prompt: hsl(190 80% 38%);
|
||||
--ctx-user-rules: hsl(340 76% 52%);
|
||||
--ctx-system-prompt: hsl(168 72% 40%);
|
||||
--ctx-user-rules: hsl(346 78% 54%);
|
||||
|
||||
/* Legacy 4-Channel Palette (retained for compatibility) */
|
||||
--ctx-cached: hsl(217 82% 51%);
|
||||
|
||||
@@ -34,6 +34,13 @@
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.panel-title > span:not(.agent-badge) {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.panel-meta {
|
||||
@@ -42,6 +49,8 @@
|
||||
gap: 6px;
|
||||
font-size: 11.5px;
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- 2. 4 格实时测速指标矩阵 (4-Cell Telemetry Matrix) --- */
|
||||
@@ -117,6 +126,21 @@
|
||||
.progress-seg.seg-messages {
|
||||
background: var(--ctx-messages);
|
||||
}
|
||||
.progress-seg.seg-assistant {
|
||||
background: var(--ctx-assistant);
|
||||
}
|
||||
.progress-seg.seg-tool-results {
|
||||
background: var(--ctx-tool-results);
|
||||
}
|
||||
.progress-seg.seg-user-input {
|
||||
background: var(--ctx-user-input);
|
||||
}
|
||||
.progress-seg.seg-subagent-msg {
|
||||
background: var(--ctx-subagent-msg);
|
||||
}
|
||||
.progress-seg.seg-checkpoint {
|
||||
background: var(--ctx-checkpoint);
|
||||
}
|
||||
.progress-seg.seg-system-tools {
|
||||
background: var(--ctx-system-tools);
|
||||
}
|
||||
@@ -193,6 +217,11 @@
|
||||
}
|
||||
|
||||
.swatch.seg-messages { background: var(--ctx-messages); }
|
||||
.swatch.seg-assistant { background: var(--ctx-assistant); }
|
||||
.swatch.seg-tool-results { background: var(--ctx-tool-results); }
|
||||
.swatch.seg-user-input { background: var(--ctx-user-input); }
|
||||
.swatch.seg-subagent-msg { background: var(--ctx-subagent-msg); }
|
||||
.swatch.seg-checkpoint { background: var(--ctx-checkpoint); }
|
||||
.swatch.seg-system-tools { background: var(--ctx-system-tools); }
|
||||
.swatch.seg-mcp-tools { background: var(--ctx-mcp-tools); }
|
||||
.swatch.seg-skills { background: var(--ctx-skills); }
|
||||
@@ -210,6 +239,121 @@
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
/* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */
|
||||
.ctx-inspector-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.ctx-pill-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.ctx-agent-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.ctx-agent-pill:hover {
|
||||
border-color: var(--border-strong);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-active {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-more-toggle {
|
||||
border-style: dashed;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-more-toggle:hover {
|
||||
border-style: solid;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.panel-title .agent-badge {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.agent-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 1px 5px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.agent-badge.is-clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.agent-badge.is-clickable:hover {
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.agent-badge.badge-main {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
.agent-badge.badge-sub-1 {
|
||||
color: var(--ctx-mcp-tools);
|
||||
background: color-mix(in srgb, var(--ctx-mcp-tools) 13%, transparent);
|
||||
border-color: color-mix(in srgb, var(--ctx-mcp-tools) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
.agent-badge.badge-sub-2 {
|
||||
color: var(--metric-speed);
|
||||
background: var(--metric-speed-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-speed) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
.agent-badge.badge-sub-3 {
|
||||
color: var(--metric-ok);
|
||||
background: var(--metric-ok-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-ok) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.telemetry-matrix {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
|
||||
@@ -65,3 +65,23 @@
|
||||
.data-table tbody tr:hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.steps-header-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.steps-inline-scope-select {
|
||||
flex: 1 1 120px;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.steps-inline-scope-select .select-trigger {
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
font-size: 11px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
@@ -26,11 +26,30 @@ import {
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { telemetryStore } from '../store/telemetryStore.js';
|
||||
import {
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { ContextSegmentMeter } from '../components/ui/ContextSegmentMeter.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
|
||||
const PILL_BASE_PAD_PX = 14;
|
||||
const CJK_CHAR_PX = 11;
|
||||
const ASCII_CHAR_PX = 6.1;
|
||||
const PILL_GAP_PX = 4;
|
||||
const DEFAULT_BAR_WIDTH_PX = 310;
|
||||
|
||||
function estPillWidth(text) {
|
||||
let w = PILL_BASE_PAD_PX;
|
||||
for (const ch of String(text || '')) {
|
||||
w += ch.charCodeAt(0) > 255 ? CJK_CHAR_PX : ASCII_CHAR_PX;
|
||||
}
|
||||
return Math.ceil(w);
|
||||
}
|
||||
|
||||
export const LiveOverviewView = defineComponent({
|
||||
name: 'LiveOverviewView',
|
||||
setup({ onCleanup }) {
|
||||
@@ -80,70 +99,124 @@ export const LiveOverviewView = defineComponent({
|
||||
]),
|
||||
]);
|
||||
|
||||
// --- 2. 6 段上下文窗口构成面板(自动锚定模型上下文压缩基线) ---
|
||||
// --- 2. 6 段上下文窗口构成面板(自动锚定模型上下文压缩基线 + 方案 B 内嵌独立 256k 窗口检视条) ---
|
||||
const ctxAgentBadge = h('span', {
|
||||
className: 'agent-badge badge-main',
|
||||
hidden: true,
|
||||
text: '主代理',
|
||||
});
|
||||
const ctxSummaryText = h('span', { className: 'text-mono', text: '0 / 256.0k (0%)' });
|
||||
const ctxSegmentBar = ContextSegmentMeter({ context: {} });
|
||||
|
||||
const bdMessages = h('strong', { className: 'text-mono', text: '0' });
|
||||
const bdSystemTools = h('strong', { className: 'text-mono', text: '0' });
|
||||
const bdMcpTools = h('strong', { className: 'text-mono', text: '0' });
|
||||
const bdSkills = h('strong', { className: 'text-mono', text: '0' });
|
||||
const bdSystemPrompt = h('strong', { className: 'text-mono', text: '0' });
|
||||
const bdUserRules = h('strong', { className: 'text-mono', text: '0' });
|
||||
const ctxPillGroup = h('div', { className: 'ctx-pill-group' });
|
||||
const ctxInspectorBar = h(
|
||||
'div',
|
||||
{ className: 'ctx-inspector-bar', hidden: true },
|
||||
[ctxPillGroup]
|
||||
);
|
||||
|
||||
const ctxChannels = [
|
||||
{
|
||||
key: 'assistant',
|
||||
label: '模型回复',
|
||||
segClass: 'seg-assistant',
|
||||
title: '模型推理思考、回复正文与工具调用入参',
|
||||
getValue: (c) => Number(c.assistantTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'toolResults',
|
||||
label: '工具结果',
|
||||
segClass: 'seg-tool-results',
|
||||
title: '文件读取、终端输出与工具执行返回内容',
|
||||
getValue: (c) => Number(c.toolResultsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userInput',
|
||||
label: '用户消息',
|
||||
segClass: 'seg-user-input',
|
||||
title: '用户提问文本与上传附件',
|
||||
getValue: (c) => Number(c.userInputTokens ?? c.messagesTokens ?? 0),
|
||||
},
|
||||
{
|
||||
key: 'subagent',
|
||||
label: '子代理通知',
|
||||
segClass: 'seg-subagent-msg',
|
||||
title: '子代理完成汇报与后台任务系统通知',
|
||||
getValue: (c) => Number(c.subagentTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'checkpoint',
|
||||
label: '压缩摘要',
|
||||
segClass: 'seg-checkpoint',
|
||||
title: '自动上下文压缩生成的历史摘要检查点',
|
||||
getValue: (c) => Number(c.checkpointTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemPrompt',
|
||||
label: '系统提示词',
|
||||
segClass: 'seg-system-prompt',
|
||||
title: '核心身份、终端沙箱、制品与环境提示词',
|
||||
getValue: (c) => Number(c.systemPromptTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'systemTools',
|
||||
label: '系统工具',
|
||||
segClass: 'seg-system-tools',
|
||||
title: '内置系统工具 Schema 定义',
|
||||
getValue: (c) => Number(c.systemToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'mcpTools',
|
||||
label: 'MCP 工具',
|
||||
segClass: 'seg-mcp-tools',
|
||||
title: 'MCP 外部服务工具与资源定义',
|
||||
getValue: (c) => Number(c.mcpToolsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'skills',
|
||||
label: 'Skill',
|
||||
segClass: 'seg-skills',
|
||||
title: '已挂载的 Skills 技能索引与说明',
|
||||
getValue: (c) => Number(c.skillsTokens || 0),
|
||||
},
|
||||
{
|
||||
key: 'userRules',
|
||||
label: '用户规则',
|
||||
segClass: 'seg-user-rules',
|
||||
title: '全局与工作区自定义规则 (user_rules)',
|
||||
getValue: (c) => Number(c.userRulesTokens || 0),
|
||||
},
|
||||
].map((ch, idx) => {
|
||||
const valEl = h('strong', { className: 'text-mono', text: '0' });
|
||||
const itemEl = h('div', { className: 'legend-item', title: ch.title }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: `swatch ${ch.segClass}` }),
|
||||
h('span', { text: ch.label }),
|
||||
]),
|
||||
valEl,
|
||||
]);
|
||||
return { ...ch, defaultOrder: idx, valEl, itemEl };
|
||||
});
|
||||
|
||||
const ctxLegendGrid = h(
|
||||
'div',
|
||||
{ className: 'ctx-legend-grid' },
|
||||
ctxChannels.map((ch) => ch.itemEl)
|
||||
);
|
||||
let lastLegendOrderSig = ctxChannels.map((ch) => ch.key).join(',');
|
||||
|
||||
const ctxPanel = h('section', { className: 'panel' }, [
|
||||
h('div', { className: 'panel-header' }, [
|
||||
h('span', { className: 'panel-title' }, [
|
||||
createSvgIcon('layers', { size: 13 }),
|
||||
h('span', { text: '上下文占用' }),
|
||||
h('span', { text: '上下文窗口' }),
|
||||
ctxAgentBadge,
|
||||
]),
|
||||
h('span', { className: 'panel-meta' }, [ctxSummaryText]),
|
||||
]),
|
||||
ctxInspectorBar,
|
||||
ctxSegmentBar.el,
|
||||
h('div', { className: 'ctx-legend-grid' }, [
|
||||
h('div', { className: 'legend-item' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'swatch seg-messages' }),
|
||||
h('span', { text: '消息' }),
|
||||
]),
|
||||
bdMessages,
|
||||
]),
|
||||
h('div', { className: 'legend-item' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'swatch seg-system-tools' }),
|
||||
h('span', { text: '系统工具' }),
|
||||
]),
|
||||
bdSystemTools,
|
||||
]),
|
||||
h('div', { className: 'legend-item' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'swatch seg-mcp-tools' }),
|
||||
h('span', { text: 'MCP 工具' }),
|
||||
]),
|
||||
bdMcpTools,
|
||||
]),
|
||||
h('div', { className: 'legend-item' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'swatch seg-skills' }),
|
||||
h('span', { text: 'Skill' }),
|
||||
]),
|
||||
bdSkills,
|
||||
]),
|
||||
h('div', { className: 'legend-item' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'swatch seg-system-prompt' }),
|
||||
h('span', { text: '系统提示词' }),
|
||||
]),
|
||||
bdSystemPrompt,
|
||||
]),
|
||||
h('div', { className: 'legend-item' }, [
|
||||
h('span', { className: 'legend-left' }, [
|
||||
h('span', { className: 'swatch seg-user-rules' }),
|
||||
h('span', { text: '用户规则' }),
|
||||
]),
|
||||
bdUserRules,
|
||||
]),
|
||||
]),
|
||||
ctxLegendGrid,
|
||||
]);
|
||||
|
||||
// --- 3. 官方动态多配额池监控面板 (Gemini / Pro 独立 Argon 池 / Claude & GPT) ---
|
||||
@@ -282,24 +355,55 @@ export const LiveOverviewView = defineComponent({
|
||||
|
||||
let latestData = null;
|
||||
let isDirty = false;
|
||||
let ctxPillsExpanded = false;
|
||||
let lastCascadeId = '';
|
||||
let cachedBarWidth = 0;
|
||||
|
||||
/**
|
||||
* 将最新遥测载荷渲染至 4 格测速矩阵、6 段上下文进度条与动态配额池列表。
|
||||
* 将最新遥测载荷渲染至 4 格测速矩阵、6 段上下文进度条(支持主/子代理切换检视)与动态配额池列表。
|
||||
*/
|
||||
function renderData(data) {
|
||||
if (!data) return;
|
||||
const active = data.activeConversation || {};
|
||||
const ctx = active.context || {};
|
||||
// 在本帧任何 DOM 写入前先读取容器宽度,避免写后读触发浏览器强制同步重排 (Forced Reflow)
|
||||
const measuredWidth =
|
||||
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
|
||||
if (measuredWidth > 160) {
|
||||
cachedBarWidth = measuredWidth;
|
||||
}
|
||||
const availRowWidth = cachedBarWidth > 160 ? cachedBarWidth : DEFAULT_BAR_WIDTH_PX;
|
||||
|
||||
const currentCascadeId = data.activeConversation?.cascadeId || '';
|
||||
if (currentCascadeId && currentCascadeId !== lastCascadeId) {
|
||||
if (lastCascadeId) {
|
||||
ctxPillsExpanded = false;
|
||||
}
|
||||
lastCascadeId = currentCascadeId;
|
||||
}
|
||||
|
||||
const uiSt = uiStore.getState();
|
||||
const {
|
||||
hasSubagents,
|
||||
effectiveScope,
|
||||
effectiveCtxScope,
|
||||
agents,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
ctxAgent,
|
||||
} = resolveScopedConversation(data, uiSt.selectedAgentScope, uiSt.ctxInspectorAgentId);
|
||||
|
||||
const active = scopedConv || data.activeConversation || {};
|
||||
const ctx = ctxAgent?.context || active.context || {};
|
||||
const quotas = data.quotas || {};
|
||||
|
||||
// 1. 更新 4 格实时测速矩阵
|
||||
// 1. 更新 4 格实时测速矩阵(根据当前代理作用域动态展示全部汇总或单代理指标)
|
||||
patchClasses(pulseDot, { 'is-pulsing': Boolean(active.isRunning) });
|
||||
patchText(tpsVal, formatMetric(active.latestTokPerSec, ' tok/s'));
|
||||
const reason = speedReasonText(active.latestSpeedReason);
|
||||
patchText(
|
||||
tpsSub,
|
||||
reason ? `${active.activeModelShort || '模型未知'} · ${reason}` : active.activeModelShort || '模型未知'
|
||||
);
|
||||
const modelAndAgent =
|
||||
hasSubagents && effectiveScope === 'all' && active.activeAgentBadge
|
||||
? `[${active.activeAgentBadge}] ${active.activeModelShort || '模型未知'}`
|
||||
: active.activeModelShort || '模型未知';
|
||||
patchText(tpsSub, reason ? `${modelAndAgent} · ${reason}` : modelAndAgent);
|
||||
|
||||
patchText(ttftVal, formatMetric(active.latestTtftSec, 's'));
|
||||
patchText(ttftSub, `均值 ${formatMetric(active.ttftSummary?.avgSec, 's')}`);
|
||||
@@ -314,7 +418,138 @@ export const LiveOverviewView = defineComponent({
|
||||
`缓存 ${active.latestCacheHitPct ?? 0}% · 累计 ${formatUsd(active.sessionCostUsd || 0, { unpricedCalls: active.sessionUnpricedCalls })}`
|
||||
);
|
||||
|
||||
// 2. 更新 6 段上下文窗口构成(优先使用模型自动压缩基线 compactionLimitTokens)
|
||||
// 2. 更新 6 段上下文窗口构成与方案 B 内嵌上下文窗口检视胶囊条
|
||||
patchAttr(ctxAgentBadge, 'hidden', !hasSubagents);
|
||||
patchAttr(ctxInspectorBar, 'hidden', !hasSubagents);
|
||||
if (hasSubagents && ctxAgent) {
|
||||
const badgeCls = getAgentBadgeClass(ctxAgent.index || 0, Boolean(ctxAgent.isMain));
|
||||
patchAttr(ctxAgentBadge, 'class', `agent-badge ${badgeCls}`);
|
||||
const badgeFullText = formatAgentLabel(ctxAgent);
|
||||
patchText(ctxAgentBadge, badgeFullText);
|
||||
patchAttr(ctxAgentBadge, 'title', badgeFullText);
|
||||
|
||||
const pillItems = [];
|
||||
if (effectiveScope === 'all') {
|
||||
pillItems.push({
|
||||
key: 'auto',
|
||||
label: `跟随活跃 (${aggregated?.activeAgentBadge || '主'})`,
|
||||
title: '自动展示当前正在运行或最新活跃的代理上下文窗口',
|
||||
isActive: effectiveCtxScope === 'auto',
|
||||
mode: 'ctx-only',
|
||||
});
|
||||
} else {
|
||||
pillItems.push({
|
||||
key: 'all',
|
||||
label: `全部汇总 (${aggregated?.stepCount ?? 0}步)`,
|
||||
title: '切回全部代理汇总视图',
|
||||
isActive: false,
|
||||
mode: 'scope',
|
||||
});
|
||||
}
|
||||
|
||||
const allAgentPills = agents.map((ag) => {
|
||||
const agPct = ag.context?.usedPct ?? 0;
|
||||
const isAct =
|
||||
effectiveScope === 'all'
|
||||
? effectiveCtxScope === ag.agentId
|
||||
: effectiveScope === ag.agentId;
|
||||
return {
|
||||
key: ag.agentId,
|
||||
label: `${ag.badgeText || ag.shortLabel} ${agPct}%`,
|
||||
title: `${formatAgentLabel(ag)} (${ag.activeModelShort || '模型未知'} · ${ag.stepCount || 0}步)`,
|
||||
isActive: isAct,
|
||||
mode: effectiveScope === 'all' ? 'ctx-only' : 'scope',
|
||||
};
|
||||
});
|
||||
|
||||
// 根据当前卡片的实际像素宽度估算单行可容纳的胶囊数量,尽可能塞满整行右侧空间
|
||||
const firstPillWidth = pillItems.length > 0 ? estPillWidth(pillItems[0].label) : 0;
|
||||
const totalAllWidth = allAgentPills.reduce(
|
||||
(sum, p) => sum + PILL_GAP_PX + estPillWidth(p.label),
|
||||
firstPillWidth
|
||||
);
|
||||
const needsCollapse = totalAllWidth > availRowWidth && allAgentPills.length > 2;
|
||||
|
||||
if (needsCollapse && !ctxPillsExpanded) {
|
||||
const toggleReservePx = PILL_GAP_PX + estPillWidth(`+${allAgentPills.length} 展开 ▾`);
|
||||
let usedW = firstPillWidth;
|
||||
let fitCount = 0;
|
||||
for (let i = 0; i < allAgentPills.length; i++) {
|
||||
const pw = PILL_GAP_PX + estPillWidth(allAgentPills[i].label);
|
||||
if (fitCount >= 1 && usedW + pw + toggleReservePx > availRowWidth) {
|
||||
break;
|
||||
}
|
||||
usedW += pw;
|
||||
fitCount++;
|
||||
}
|
||||
// 至少折叠 2 个胶囊(避免出现比胶囊本身还宽的 "+1 展开 ▾")
|
||||
const maxKeep = Math.max(1, allAgentPills.length - 2);
|
||||
const maxCollapsedCount = Math.max(1, Math.min(maxKeep, fitCount));
|
||||
const visibleAgentPills = allAgentPills.slice(0, maxCollapsedCount);
|
||||
const activeHiddenPill = allAgentPills
|
||||
.slice(maxCollapsedCount)
|
||||
.find((p) => p.isActive);
|
||||
if (activeHiddenPill) {
|
||||
if (visibleAgentPills.length >= 2) {
|
||||
visibleAgentPills[visibleAgentPills.length - 1] = activeHiddenPill;
|
||||
} else {
|
||||
visibleAgentPills.push(activeHiddenPill);
|
||||
}
|
||||
}
|
||||
const hiddenCount = allAgentPills.length - visibleAgentPills.length;
|
||||
pillItems.push(...visibleAgentPills, {
|
||||
key: '__toggle_more__',
|
||||
label: `+${hiddenCount} 展开 ▾`,
|
||||
title: `展开全部 ${allAgentPills.length - 1} 个子代理的上下文窗口胶囊`,
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
} else {
|
||||
pillItems.push(...allAgentPills);
|
||||
if (needsCollapse) {
|
||||
pillItems.push({
|
||||
key: '__toggle_more__',
|
||||
label: '收起 ▴',
|
||||
title: '折叠多余子代理胶囊',
|
||||
isActive: false,
|
||||
isMoreToggle: true,
|
||||
mode: 'toggle-expand',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
patchKeyedList(ctxPillGroup, pillItems, {
|
||||
keyFn: (item) => item.key,
|
||||
sigFn: (item) =>
|
||||
`${item.key}:${item.label}:${item.isActive}:${item.isMoreToggle}:${item.mode}:${item.title}`,
|
||||
createRow: () => {
|
||||
const btn = h('button', { type: 'button', className: 'ctx-agent-pill' });
|
||||
return { el: btn, refs: { btn } };
|
||||
},
|
||||
updateRow: (refs, item) => {
|
||||
patchText(refs.btn, item.label);
|
||||
patchAttr(refs.btn, 'title', item.title);
|
||||
patchClasses(refs.btn, {
|
||||
'is-active': item.isActive,
|
||||
'is-more-toggle': Boolean(item.isMoreToggle),
|
||||
});
|
||||
refs.btn.onclick = () => {
|
||||
if (item.mode === 'toggle-expand') {
|
||||
ctxPillsExpanded = !ctxPillsExpanded;
|
||||
renderData(latestData);
|
||||
} else if (item.mode === 'ctx-only') {
|
||||
uiStore.setState({ ctxInspectorAgentId: item.key });
|
||||
} else if (item.key === 'all') {
|
||||
uiStore.setState({ selectedAgentScope: 'all', ctxInspectorAgentId: 'auto' });
|
||||
} else {
|
||||
uiStore.setState({ selectedAgentScope: item.key });
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const limitTokens = Number(ctx.compactionLimitTokens || ctx.limitTokens || 256000);
|
||||
const totalTokens = Number(ctx.totalTokens || 0);
|
||||
const usedPct =
|
||||
@@ -324,12 +559,19 @@ export const LiveOverviewView = defineComponent({
|
||||
`${formatTokens(totalTokens)} / ${formatTokens(limitTokens)} (${usedPct}%)`
|
||||
);
|
||||
ctxSegmentBar.setProps({ context: { ...ctx, limitTokens, usedPct } });
|
||||
patchText(bdMessages, formatTokens(ctx.messagesTokens || 0));
|
||||
patchText(bdSystemTools, formatTokens(ctx.systemToolsTokens || 0));
|
||||
patchText(bdMcpTools, formatTokens(ctx.mcpToolsTokens || 0));
|
||||
patchText(bdSkills, formatTokens(ctx.skillsTokens || 0));
|
||||
patchText(bdSystemPrompt, formatTokens(ctx.systemPromptTokens || 0));
|
||||
patchText(bdUserRules, formatTokens(ctx.userRulesTokens || 0));
|
||||
const scoredChannels = ctxChannels.map((ch) => {
|
||||
const val = ch.getValue(ctx);
|
||||
patchText(ch.valEl, formatTokens(val));
|
||||
return { ch, val };
|
||||
});
|
||||
scoredChannels.sort((a, b) => b.val - a.val || a.ch.defaultOrder - b.ch.defaultOrder);
|
||||
const nextLegendOrderSig = scoredChannels.map((x) => x.ch.key).join(',');
|
||||
if (nextLegendOrderSig !== lastLegendOrderSig) {
|
||||
lastLegendOrderSig = nextLegendOrderSig;
|
||||
for (const { ch } of scoredChannels) {
|
||||
ctxLegendGrid.appendChild(ch.itemEl);
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 更新动态配额池列表(支持 Gemini、Pro 独立 Argon 池、Claude & GPT 等)
|
||||
patchText(
|
||||
@@ -398,21 +640,52 @@ export const LiveOverviewView = defineComponent({
|
||||
}
|
||||
);
|
||||
|
||||
let prevScope = uiStore.getState().selectedAgentScope;
|
||||
let prevCtxTarget = uiStore.getState().ctxInspectorAgentId;
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
(activeView) => {
|
||||
if (activeView === 'overview' && isDirty) {
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
selectedAgentScope: st.selectedAgentScope,
|
||||
ctxInspectorAgentId: st.ctxInspectorAgentId,
|
||||
}),
|
||||
(slice) => {
|
||||
const scopeChanged =
|
||||
slice.selectedAgentScope !== prevScope || slice.ctxInspectorAgentId !== prevCtxTarget;
|
||||
prevScope = slice.selectedAgentScope;
|
||||
prevCtxTarget = slice.ctxInspectorAgentId;
|
||||
|
||||
if (slice.activeView !== 'overview') {
|
||||
if (scopeChanged) isDirty = true;
|
||||
return;
|
||||
}
|
||||
if ((isDirty || scopeChanged) && latestData) {
|
||||
isDirty = false;
|
||||
if (latestData) {
|
||||
renderData(latestData);
|
||||
}
|
||||
renderData(latestData);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let ro = null;
|
||||
if (typeof ResizeObserver !== 'undefined') {
|
||||
ro = new ResizeObserver(() => {
|
||||
if (uiStore.getState().activeView !== 'overview') return;
|
||||
const nextW =
|
||||
ctxInspectorBar.clientWidth || (ctxPanel.clientWidth ? ctxPanel.clientWidth - 24 : 0);
|
||||
if (nextW > 160 && Math.abs(nextW - cachedBarWidth) >= 6) {
|
||||
cachedBarWidth = nextW;
|
||||
if (latestData?.activeConversation?.hasSubagents) {
|
||||
renderData(latestData);
|
||||
}
|
||||
}
|
||||
});
|
||||
ro.observe(ctxPanel);
|
||||
}
|
||||
|
||||
onCleanup(() => {
|
||||
unsub();
|
||||
unsubView();
|
||||
if (ro) ro.disconnect();
|
||||
ctxSegmentBar.destroy();
|
||||
viewScrollbar.destroy();
|
||||
});
|
||||
|
||||
@@ -221,7 +221,7 @@ export const SettingsView = defineComponent({
|
||||
// --- 面板 2:版本更新面板 ---
|
||||
const pricingCountVal = h('strong', { className: 'cell-value', text: '—' });
|
||||
const pricingSyncSub = h('span', { className: 'cell-sub', text: '读取中…' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.0' });
|
||||
const versionVal = h('strong', { className: 'cell-value', text: 'v1.4.1' });
|
||||
const versionSub = h('span', { className: 'cell-sub', text: '检查中…' });
|
||||
|
||||
const syncPricingBtnText = h('span', { text: '更新价格表' });
|
||||
@@ -276,7 +276,7 @@ export const SettingsView = defineComponent({
|
||||
return;
|
||||
}
|
||||
if (!cs?.updateAvailable) {
|
||||
const curVer = cs?.currentPluginVersion || '1.4.0';
|
||||
const curVer = cs?.currentPluginVersion || '1.4.1';
|
||||
showCloudFeedback(`当前已是最新版本 (v${curVer})`, 4500);
|
||||
return;
|
||||
}
|
||||
@@ -379,7 +379,7 @@ export const SettingsView = defineComponent({
|
||||
`${srcLabel} · ${formatSyncTimeText(cs.lastSyncedAtMs, cs.catalogUpdatedAt)}`
|
||||
);
|
||||
|
||||
const curVer = cs.currentPluginVersion || '1.4.0';
|
||||
const curVer = cs.currentPluginVersion || '1.4.1';
|
||||
const latVer = cs.latestPluginVersion || curVer;
|
||||
const modeTag = cs.installMode === 'git' ? 'Git' : 'ZIP';
|
||||
patchText(versionVal, `v${curVer}`);
|
||||
|
||||
@@ -22,14 +22,38 @@ import {
|
||||
speedReasonText,
|
||||
} from '../core/formatters.js';
|
||||
import { createSvgIcon } from '../icons/SvgIcon.js';
|
||||
import { telemetryStore } from '../store/telemetryStore.js';
|
||||
import {
|
||||
formatAgentLabel,
|
||||
getAgentBadgeClass,
|
||||
resolveScopedConversation,
|
||||
telemetryStore,
|
||||
} from '../store/telemetryStore.js';
|
||||
import { uiStore } from '../store/uiStore.js';
|
||||
import { CustomScrollbar } from '../components/ui/CustomScrollbar.js';
|
||||
import { CustomSelect } from '../components/ui/CustomSelect.js';
|
||||
import { SegmentedControl } from '../components/ui/SegmentedControl.js';
|
||||
|
||||
export const StepsDetailView = defineComponent({
|
||||
name: 'StepsDetailView',
|
||||
setup({ onCleanup }) {
|
||||
// 方案 B:明细面板标题栏内嵌代理筛选下拉框(与顶栏代理切换条双向同步)
|
||||
const inlineScopeSelect = CustomSelect({
|
||||
modelValue: uiStore.getState().selectedAgentScope,
|
||||
icon: 'layers',
|
||||
placeholder: '全部代理',
|
||||
className: 'steps-inline-scope-select',
|
||||
options: [{ value: 'all', label: '全部代理' }],
|
||||
onUpdateModelValue: (nextScope) => {
|
||||
if (nextScope) {
|
||||
uiStore.setState({
|
||||
selectedAgentScope: nextScope,
|
||||
...(nextScope === 'all' ? { ctxInspectorAgentId: 'auto' } : {}),
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
inlineScopeSelect.el.setAttribute('hidden', '');
|
||||
|
||||
// 顶部子表分段切换器:在“按步查看”与“按模型汇总”之间切换
|
||||
const subTabSwitch = SegmentedControl({
|
||||
ariaLabel: '明细表视图切换',
|
||||
@@ -100,7 +124,10 @@ export const StepsDetailView = defineComponent({
|
||||
createSvgIcon('table', { size: 13 }),
|
||||
h('span', { text: '调用记录' }),
|
||||
]),
|
||||
subTabSwitch.el,
|
||||
h('div', { className: 'steps-header-controls' }, [
|
||||
inlineScopeSelect.el,
|
||||
subTabSwitch.el,
|
||||
]),
|
||||
]),
|
||||
stepsScroll.el,
|
||||
modelsScroll.el,
|
||||
@@ -128,26 +155,82 @@ export const StepsDetailView = defineComponent({
|
||||
*/
|
||||
function renderStepsData(slice) {
|
||||
if (!slice) return;
|
||||
const steps = slice.recentSteps || [];
|
||||
const models = slice.modelBreakdown || [];
|
||||
const uiSt = uiStore.getState();
|
||||
const {
|
||||
hasSubagents,
|
||||
effectiveScope,
|
||||
subagents,
|
||||
mainAgent,
|
||||
aggregated,
|
||||
scopedConv,
|
||||
} = resolveScopedConversation(
|
||||
{ activeConversation: slice.activeConversation },
|
||||
uiSt.selectedAgentScope,
|
||||
uiSt.ctxInspectorAgentId
|
||||
);
|
||||
|
||||
patchAttr(inlineScopeSelect.el, 'hidden', !hasSubagents);
|
||||
if (hasSubagents) {
|
||||
const scopeOpts = [
|
||||
{
|
||||
value: 'all',
|
||||
label: '全部汇总',
|
||||
meta: `${aggregated?.stepCount ?? 0}步`,
|
||||
},
|
||||
{
|
||||
value: 'main',
|
||||
label: '主代理',
|
||||
meta: `${mainAgent?.stepCount ?? 0}步`,
|
||||
},
|
||||
...subagents.map((s) => ({
|
||||
value: s.agentId,
|
||||
label: formatAgentLabel(s),
|
||||
meta: `${s.stepCount || 0}步`,
|
||||
})),
|
||||
];
|
||||
inlineScopeSelect.setProps({
|
||||
modelValue: effectiveScope,
|
||||
options: scopeOpts,
|
||||
});
|
||||
} else {
|
||||
inlineScopeSelect.close();
|
||||
}
|
||||
|
||||
const steps =
|
||||
(hasSubagents ? scopedConv?.recentSteps : slice.recentSteps) ||
|
||||
slice.recentSteps ||
|
||||
[];
|
||||
const models =
|
||||
hasSubagents && Array.isArray(scopedConv?.modelBreakdown)
|
||||
? scopedConv.modelBreakdown
|
||||
: slice.modelBreakdown || [];
|
||||
const showUpstream = Boolean(slice.showUpstreamModel);
|
||||
const modelsTabBadge = hasSubagents
|
||||
? effectiveScope === 'all'
|
||||
? '本会话汇总'
|
||||
: scopedConv?.shortLabel || '当前代理'
|
||||
: slice.rangeLabel;
|
||||
|
||||
subTabSwitch.setProps({
|
||||
options: [
|
||||
{ value: 'steps', label: `按步查看 (${steps.length})` },
|
||||
{ value: 'models', label: `按模型汇总 (${slice.rangeLabel})` },
|
||||
{ value: 'models', label: `按模型汇总 (${modelsTabBadge})` },
|
||||
],
|
||||
});
|
||||
|
||||
// 1. 单步测速表增量对账:以 `<cascadeId>-<stepIndex>` 为稳定行键,仅在签名变化时刷新单元格
|
||||
// 1. 单步测速表增量对账:以 `<agentCascadeId>-<stepIndex>` 为稳定行键,仅在签名变化时刷新单元格
|
||||
patchKeyedList(stepsTbody, steps, {
|
||||
keyFn: (st) => `${slice.cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
keyFn: (st) => `${st.agentCascadeId || slice.cascadeId || 'conv'}-${st.stepIndex}`,
|
||||
sigFn: (st) =>
|
||||
`${st.stepIndex}:${showUpstream ? st.modelUpstream || st.responseModel || st.modelShort : st.modelShort}:${st.tokPerSec}:${st.ttftSec}:${st.contextTokens}:${st.outputTokens}:${st.cacheHitPct}:${st.costUsd}:${st.selectedSpeedReason}`,
|
||||
`${hasSubagents}:${effectiveScope}:${st.agentId || 'main'}:${st.stepIndex}:${showUpstream ? st.modelUpstream || st.responseModel || st.modelShort : st.modelShort}:${st.tokPerSec}:${st.ttftSec}:${st.contextTokens}:${st.outputTokens}:${st.cacheHitPct}:${st.costUsd}:${st.selectedSpeedReason}`,
|
||||
createRow: () => {
|
||||
const agentBadgeEl = h('span', {
|
||||
className: 'agent-badge is-clickable',
|
||||
hidden: true,
|
||||
style: 'margin-right: 4px;',
|
||||
});
|
||||
const stepNumText = h('span');
|
||||
const compIcon = createSvgIcon('bolt', { size: 11, className: 'text-muted' });
|
||||
const tdStep = h('td', {}, [stepNumText, compIcon]);
|
||||
const tdStep = h('td', {}, [agentBadgeEl, stepNumText]);
|
||||
|
||||
const tdModel = h('td', {
|
||||
style: 'max-width: 140px; overflow: hidden; text-overflow: ellipsis;',
|
||||
@@ -171,8 +254,8 @@ export const StepsDetailView = defineComponent({
|
||||
return {
|
||||
el: tr,
|
||||
refs: {
|
||||
agentBadgeEl,
|
||||
stepNumText,
|
||||
compIcon,
|
||||
tdModel,
|
||||
speedMain,
|
||||
speedReason,
|
||||
@@ -184,8 +267,28 @@ export const StepsDetailView = defineComponent({
|
||||
};
|
||||
},
|
||||
updateRow: (refs, st) => {
|
||||
patchText(refs.stepNumText, `#${Number(st.stepIndex)} `);
|
||||
patchAttr(refs.compIcon, 'hidden', !st.isCompactionStep);
|
||||
patchAttr(refs.agentBadgeEl, 'hidden', !hasSubagents);
|
||||
if (hasSubagents) {
|
||||
const badgeCls = getAgentBadgeClass(st.agentIndex || 0, !st.isSubagent);
|
||||
patchAttr(refs.agentBadgeEl, 'class', `agent-badge is-clickable ${badgeCls}`);
|
||||
patchText(refs.agentBadgeEl, st.agentBadge || (st.isSubagent ? '子' : '主'));
|
||||
patchAttr(
|
||||
refs.agentBadgeEl,
|
||||
'title',
|
||||
effectiveScope === 'all'
|
||||
? `点击仅过滤查看 ${st.agentLabel || '该代理'}`
|
||||
: '点击切回全部汇总'
|
||||
);
|
||||
refs.agentBadgeEl.onclick = () => {
|
||||
const targetScope = st.agentId || 'main';
|
||||
const nextScope = effectiveScope === targetScope ? 'all' : targetScope;
|
||||
uiStore.setState({
|
||||
selectedAgentScope: nextScope,
|
||||
...(nextScope === 'all' ? { ctxInspectorAgentId: 'auto' } : {}),
|
||||
});
|
||||
};
|
||||
}
|
||||
patchText(refs.stepNumText, `#${Number(st.stepIndex)}`);
|
||||
const modelText =
|
||||
(showUpstream ? st.modelUpstream || st.responseModel : st.modelShort) ||
|
||||
st.modelShort ||
|
||||
@@ -250,12 +353,16 @@ export const StepsDetailView = defineComponent({
|
||||
},
|
||||
});
|
||||
|
||||
stepsScroll.refresh();
|
||||
modelsScroll.refresh();
|
||||
if (uiSt.stepsSubTab === 'models') {
|
||||
modelsScroll.refresh();
|
||||
} else {
|
||||
stepsScroll.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
const unsubTelemetry = telemetryStore.subscribe(
|
||||
(st) => ({
|
||||
activeConversation: st.telemetry?.activeConversation,
|
||||
cascadeId: st.telemetry?.activeConversation?.cascadeId,
|
||||
recentSteps: st.telemetry?.activeConversation?.recentSteps,
|
||||
modelBreakdown: st.telemetry?.modelBreakdown,
|
||||
@@ -273,14 +380,23 @@ export const StepsDetailView = defineComponent({
|
||||
}
|
||||
);
|
||||
|
||||
let prevScope = uiStore.getState().selectedAgentScope;
|
||||
|
||||
const unsubView = uiStore.subscribe(
|
||||
(st) => st.activeView,
|
||||
(activeView) => {
|
||||
if (activeView === 'steps' && isDirty) {
|
||||
(st) => ({
|
||||
activeView: st.activeView,
|
||||
selectedAgentScope: st.selectedAgentScope,
|
||||
}),
|
||||
(uiSlice) => {
|
||||
const scopeChanged = uiSlice.selectedAgentScope !== prevScope;
|
||||
prevScope = uiSlice.selectedAgentScope;
|
||||
if (uiSlice.activeView !== 'steps') {
|
||||
if (scopeChanged) isDirty = true;
|
||||
return;
|
||||
}
|
||||
if ((isDirty || scopeChanged) && latestSlice) {
|
||||
isDirty = false;
|
||||
if (latestSlice) {
|
||||
renderStepsData(latestSlice);
|
||||
}
|
||||
renderStepsData(latestSlice);
|
||||
}
|
||||
}
|
||||
);
|
||||
@@ -289,6 +405,7 @@ export const StepsDetailView = defineComponent({
|
||||
unsubUi();
|
||||
unsubTelemetry();
|
||||
unsubView();
|
||||
inlineScopeSelect.destroy();
|
||||
subTabSwitch.destroy();
|
||||
stepsScroll.destroy();
|
||||
modelsScroll.destroy();
|
||||
@@ -296,7 +413,14 @@ export const StepsDetailView = defineComponent({
|
||||
|
||||
return {
|
||||
el: rootEl,
|
||||
refs: { stepsTbody, modelsTbody, subTabSwitch, stepsScroll, modelsScroll },
|
||||
refs: {
|
||||
stepsTbody,
|
||||
modelsTbody,
|
||||
inlineScopeSelect,
|
||||
subTabSwitch,
|
||||
stepsScroll,
|
||||
modelsScroll,
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
+267
-5
@@ -49,13 +49,18 @@
|
||||
--metric-danger: var(--destructive, hsl(0 74% 50%));
|
||||
--metric-danger-soft: color-mix(in srgb, var(--metric-danger) 15%, transparent);
|
||||
|
||||
/* Context Window 6-Channel Palette */
|
||||
/* Context Window 10-Channel Palette */
|
||||
--ctx-messages: hsl(217 82% 51%);
|
||||
--ctx-assistant: hsl(217 82% 54%);
|
||||
--ctx-tool-results: hsl(192 82% 43%);
|
||||
--ctx-user-input: hsl(245 72% 62%);
|
||||
--ctx-subagent-msg: hsl(280 70% 58%);
|
||||
--ctx-checkpoint: hsl(38 90% 50%);
|
||||
--ctx-system-tools: hsl(22 86% 50%);
|
||||
--ctx-mcp-tools: hsl(268 72% 56%);
|
||||
--ctx-mcp-tools: hsl(316 72% 54%);
|
||||
--ctx-skills: hsl(145 64% 38%);
|
||||
--ctx-system-prompt: hsl(190 80% 38%);
|
||||
--ctx-user-rules: hsl(340 76% 52%);
|
||||
--ctx-system-prompt: hsl(168 72% 40%);
|
||||
--ctx-user-rules: hsl(346 78% 54%);
|
||||
|
||||
/* Legacy 4-Channel Palette (retained for compatibility) */
|
||||
--ctx-cached: hsl(217 82% 51%);
|
||||
@@ -257,7 +262,13 @@ input {
|
||||
* 8. 设置表单行与主次操作按钮 (.form-row, .btn-primary, .btn-secondary, .cloud-actions-row)
|
||||
*/
|
||||
|
||||
/* --- 1. 顶部会话控制栏 (Top Session Control Header) --- */
|
||||
/* --- 1. 顶部会话控制栏与二级代理切换条 (Top Session Control Header & Agent Scope Bar) --- */
|
||||
.top-session-stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
}
|
||||
|
||||
.session-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -269,6 +280,93 @@ input {
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.agent-scope-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
padding: 4px var(--space-3);
|
||||
background: var(--surface-panel);
|
||||
border: 1px solid var(--border-hairline);
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
.agent-scope-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.scope-pill-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
height: 22px;
|
||||
padding: 0 7px;
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11.5px;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.scope-pill-btn:hover {
|
||||
background: var(--surface-hover);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.scope-pill-btn.is-active {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scope-subagent-select {
|
||||
flex: 1 1 115px;
|
||||
min-width: 105px;
|
||||
}
|
||||
|
||||
.scope-subagent-select .select-trigger {
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
font-size: 11.5px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
.scope-subagent-select.is-active-sub .select-trigger {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.scope-subagent-select .select-menu,
|
||||
.steps-inline-scope-select .select-menu {
|
||||
left: auto;
|
||||
right: 0;
|
||||
}
|
||||
|
||||
.agent-scope-right {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.session-left {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -968,6 +1066,13 @@ input {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.panel-title > span:not(.agent-badge) {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.panel-meta {
|
||||
@@ -976,6 +1081,8 @@ input {
|
||||
gap: 6px;
|
||||
font-size: 11.5px;
|
||||
color: var(--text-secondary);
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* --- 2. 4 格实时测速指标矩阵 (4-Cell Telemetry Matrix) --- */
|
||||
@@ -1051,6 +1158,21 @@ input {
|
||||
.progress-seg.seg-messages {
|
||||
background: var(--ctx-messages);
|
||||
}
|
||||
.progress-seg.seg-assistant {
|
||||
background: var(--ctx-assistant);
|
||||
}
|
||||
.progress-seg.seg-tool-results {
|
||||
background: var(--ctx-tool-results);
|
||||
}
|
||||
.progress-seg.seg-user-input {
|
||||
background: var(--ctx-user-input);
|
||||
}
|
||||
.progress-seg.seg-subagent-msg {
|
||||
background: var(--ctx-subagent-msg);
|
||||
}
|
||||
.progress-seg.seg-checkpoint {
|
||||
background: var(--ctx-checkpoint);
|
||||
}
|
||||
.progress-seg.seg-system-tools {
|
||||
background: var(--ctx-system-tools);
|
||||
}
|
||||
@@ -1127,6 +1249,11 @@ input {
|
||||
}
|
||||
|
||||
.swatch.seg-messages { background: var(--ctx-messages); }
|
||||
.swatch.seg-assistant { background: var(--ctx-assistant); }
|
||||
.swatch.seg-tool-results { background: var(--ctx-tool-results); }
|
||||
.swatch.seg-user-input { background: var(--ctx-user-input); }
|
||||
.swatch.seg-subagent-msg { background: var(--ctx-subagent-msg); }
|
||||
.swatch.seg-checkpoint { background: var(--ctx-checkpoint); }
|
||||
.swatch.seg-system-tools { background: var(--ctx-system-tools); }
|
||||
.swatch.seg-mcp-tools { background: var(--ctx-mcp-tools); }
|
||||
.swatch.seg-skills { background: var(--ctx-skills); }
|
||||
@@ -1144,6 +1271,121 @@ input {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
/* --- 6. 上下文窗口内联代理切换器与代理徽章 (Scheme B Context Inspector & Agent Badges) --- */
|
||||
.ctx-inspector-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
background: transparent;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.ctx-pill-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
width: 100%;
|
||||
gap: 4px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.ctx-agent-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 20px;
|
||||
padding: 0 6px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-panel);
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
border-radius: var(--radius-xs);
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
transition:
|
||||
background-color var(--dur-instant) var(--ease-fast),
|
||||
color var(--dur-instant) var(--ease-fast),
|
||||
border-color var(--dur-instant) var(--ease-fast);
|
||||
}
|
||||
|
||||
.ctx-agent-pill:hover {
|
||||
border-color: var(--border-strong);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-active {
|
||||
background: var(--accent-primary-soft);
|
||||
color: var(--accent-primary);
|
||||
border-color: var(--accent-primary-border);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-more-toggle {
|
||||
border-style: dashed;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.ctx-agent-pill.is-more-toggle:hover {
|
||||
border-style: solid;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.panel-title .agent-badge {
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: inline-block;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.agent-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
padding: 1px 5px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
border-radius: var(--radius-xs);
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.agent-badge.is-clickable {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.agent-badge.is-clickable:hover {
|
||||
border-color: var(--border-strong);
|
||||
}
|
||||
|
||||
.agent-badge.badge-main {
|
||||
color: var(--accent-primary);
|
||||
background: var(--accent-primary-soft);
|
||||
border-color: var(--accent-primary-border);
|
||||
}
|
||||
|
||||
.agent-badge.badge-sub-1 {
|
||||
color: var(--ctx-mcp-tools);
|
||||
background: color-mix(in srgb, var(--ctx-mcp-tools) 13%, transparent);
|
||||
border-color: color-mix(in srgb, var(--ctx-mcp-tools) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
.agent-badge.badge-sub-2 {
|
||||
color: var(--metric-speed);
|
||||
background: var(--metric-speed-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-speed) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
.agent-badge.badge-sub-3 {
|
||||
color: var(--metric-ok);
|
||||
background: var(--metric-ok-soft);
|
||||
border-color: color-mix(in srgb, var(--metric-ok) 35%, var(--border-hairline));
|
||||
}
|
||||
|
||||
@media (max-width: 390px) {
|
||||
.telemetry-matrix {
|
||||
grid-template-columns: repeat(2, 1fr);
|
||||
@@ -1596,3 +1838,23 @@ input {
|
||||
.data-table tbody tr:hover {
|
||||
background: var(--surface-hover);
|
||||
}
|
||||
|
||||
.steps-header-controls {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.steps-inline-scope-select {
|
||||
flex: 1 1 120px;
|
||||
min-width: 120px;
|
||||
}
|
||||
|
||||
.steps-inline-scope-select .select-trigger {
|
||||
height: 22px;
|
||||
padding: 0 6px;
|
||||
font-size: 11px;
|
||||
border: 1px solid var(--border-hairline);
|
||||
background: var(--surface-subtle);
|
||||
}
|
||||
|
||||
@@ -71,3 +71,264 @@ test('a TTFT-only correction is persisted even when usage, duration and signatur
|
||||
assert.equal(h.state.saves.length,2);
|
||||
assert.equal(h.state.saves[1].data.test.steps[0].ttftSec,9);
|
||||
});
|
||||
|
||||
test('groups subagents under root conversation and computes both per-agent and aggregated telemetry',async()=>{
|
||||
const subRaw={trajectory:{steps:[{status:'CORTEX_STEP_STATUS_DONE',metadata:{
|
||||
createdAt:'2026-01-01T00:00:20Z',finishedGeneratingAt:'2026-01-01T00:00:25Z',
|
||||
modelUsage:{inputTokens:'300',cacheReadTokens:'400',outputTokens:'250',thinkingOutputTokens:'50',responseOutputTokens:'200'},
|
||||
},plannerResponse:{response:'sub answer',thinkingDuration:'1s'}}],generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'1s',streamingDuration:'4s',chatStartMetadata:{contextWindowMetadata:{tokenBreakdown:{groups:[{type:'TOKEN_TYPE_CHAT_MESSAGES',numTokens:12000},{type:'TOKEN_TYPE_TOOLS',numTokens:3000}]}}}}}]}};
|
||||
const h=backendHarness({
|
||||
trajectories:{root1:raw,sub1:subRaw},
|
||||
summaries:{
|
||||
root1:{stepCount:1,lastModifiedTime:'2026-01-01T00:00:10Z',status:'IDLE',annotations:{title:'Root Task'}},
|
||||
sub1:{stepCount:1,createdTime:'2026-01-01T00:00:20Z',lastModifiedTime:'2026-01-01T00:00:25Z',status:'CASCADE_RUN_STATUS_RUNNING',trajectoryMetadata:{rootConversationId:'root1',parentConversationId:'root1',subagentSpec:{typeName:'research',role:'Codebase Researcher'}}},
|
||||
},
|
||||
});
|
||||
const p=await h.buildTelemetryPayloadInternal('');
|
||||
// Top-level conversations list only contains root1, not raw sub1
|
||||
assert.equal(p.conversations.length,1);
|
||||
assert.equal(p.conversations[0].cascadeId,'root1');
|
||||
assert.equal(p.conversations[0].subagentCount,1);
|
||||
assert.equal(p.conversations[0].totalStepCount,2);
|
||||
// Active conversation has both individual agents and aggregated view
|
||||
assert.equal(p.activeConversation.hasSubagents,true);
|
||||
assert.equal(p.activeConversation.subagentCount,1);
|
||||
assert.equal(p.activeConversation.agents.length,2);
|
||||
assert.equal(p.activeConversation.agents[0].agentId,'main');
|
||||
assert.equal(p.activeConversation.agents[0].stepCount,1);
|
||||
assert.equal(p.activeConversation.agents[1].agentId,'sub1');
|
||||
assert.equal(p.activeConversation.agents[1].role,'Codebase Researcher');
|
||||
assert.equal(p.activeConversation.agents[1].context.messagesTokens,12000);
|
||||
assert.equal(p.activeConversation.aggregated.stepCount,2);
|
||||
assert.equal(p.activeConversation.aggregated.isRunning,true);
|
||||
assert.equal(p.activeConversation.aggregated.activeAgentId,'sub1');
|
||||
// Session consumption includes both root1 (900) and sub1 (950)
|
||||
assert.equal(p.consumption.session.totalTokens,1850);
|
||||
});
|
||||
|
||||
test('discovers and links subagents from parent invokeSubagent steps after Antigravity restart when omitted from trajectorySummaries',async()=>{
|
||||
const rootWithInvoke={
|
||||
trajectory:{
|
||||
metadata:{rootConversationId:'root-audit'},
|
||||
steps:[
|
||||
{
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{
|
||||
createdAt:'2026-01-01T00:00:00Z',
|
||||
finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
||||
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
|
||||
},
|
||||
plannerResponse:{response:'spawning subagents',thinkingDuration:'5s'},
|
||||
},
|
||||
{
|
||||
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{
|
||||
createdAt:'2026-01-01T00:00:12Z',
|
||||
toolCall:{name:'invoke_subagent',argumentsJson:JSON.stringify({Role:'Build & Baseline Verifier',TypeName:'issue_verifier'})},
|
||||
},
|
||||
invokeSubagent:{
|
||||
subagents:[{typeName:'issue_verifier',role:'Build & Baseline Verifier',initialPrompt:'long prompt...'}],
|
||||
results:[{conversationId:'sub-cached-1'}],
|
||||
},
|
||||
},
|
||||
{
|
||||
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{
|
||||
createdAt:'2026-01-01T00:00:15Z',
|
||||
toolCall:{name:'invoke_subagent',argumentsJson:JSON.stringify({Role:'P0 Disk Quiz Patch Verifier',TypeName:'issue_verifier'})},
|
||||
},
|
||||
invokeSubagent:{
|
||||
subagents:[{typeName:'issue_verifier',role:'P0 Disk Quiz Patch Verifier',initialPrompt:'long prompt 2...'}],
|
||||
results:[{conversationId:'sub-uncached-2'}],
|
||||
},
|
||||
},
|
||||
],
|
||||
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'3s',streamingDuration:'7s'}}],
|
||||
},
|
||||
};
|
||||
const sub2Raw={
|
||||
trajectory:{
|
||||
metadata:{
|
||||
parentConversationId:'root-audit',
|
||||
rootConversationId:'root-audit',
|
||||
subagentSpec:{typeName:'issue_verifier',role:'P0 Disk Quiz Patch Verifier',initialPrompt:'huge prompt'},
|
||||
},
|
||||
steps:[{
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{
|
||||
createdAt:'2026-01-01T00:00:20Z',
|
||||
finishedGeneratingAt:'2026-01-01T00:00:25Z',
|
||||
modelUsage:{inputTokens:'400',cacheReadTokens:'600',outputTokens:'300',thinkingOutputTokens:'50',responseOutputTokens:'250'},
|
||||
},
|
||||
plannerResponse:{response:'sub2 report',thinkingDuration:'1s'},
|
||||
}],
|
||||
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'1s',streamingDuration:'4s'}}],
|
||||
},
|
||||
};
|
||||
// Simulate pre-existing v10 cache entries saved before subagentRefs existed
|
||||
const preCachedSub1Step={
|
||||
stepIndex:1,
|
||||
createdAt:'2026-01-01T00:00:14Z',
|
||||
createdAtMs:Date.parse('2026-01-01T00:00:14Z'),
|
||||
modelKey:'MODEL_PLACEHOLDER_M417',
|
||||
responseModel:'gemini-3.1-pro-high',
|
||||
modelIdentityVersion:2,
|
||||
modelSource:'explicit',
|
||||
inputTokens:200,
|
||||
cacheReadTokens:300,
|
||||
outputTokens:500,
|
||||
thinkingTokens:100,
|
||||
responseTokens:400,
|
||||
contextBreakdown:{messagesTokens:18000,userInputTokens:2000,assistantTokens:6000,toolResultsTokens:10000,subagentTokens:0,checkpointTokens:0,systemToolsTokens:4000,mcpToolsTokens:0,skillsTokens:1000,systemPromptTokens:5000,userRulesTokens:2000},
|
||||
};
|
||||
const h=backendHarness({
|
||||
cache:{
|
||||
'root-audit':{
|
||||
signature:'v10-model-identity:3:2026-01-01T00:00:15Z',
|
||||
title:'Frontend Issue Audit Verification',
|
||||
lastModifiedMs:Date.parse('2026-01-01T00:00:15Z'),
|
||||
steps:[{...preCachedSub1Step,inputTokens:100,cacheReadTokens:200,outputTokens:600}],
|
||||
},
|
||||
'sub-cached-1':{
|
||||
signature:'v10-model-identity:disk:1767225614000',
|
||||
title:'sub-cach',
|
||||
lastModifiedMs:Date.parse('2026-01-01T00:00:14Z'),
|
||||
steps:[preCachedSub1Step],
|
||||
},
|
||||
},
|
||||
trajectories:{
|
||||
'root-audit':rootWithInvoke,
|
||||
'sub-uncached-2':sub2Raw,
|
||||
},
|
||||
// After restart, GetAllCascadeTrajectories only returns root-audit!
|
||||
summaries:{
|
||||
'root-audit':{
|
||||
stepCount:3,
|
||||
lastModifiedTime:'2026-01-01T00:00:15Z',
|
||||
status:'IDLE',
|
||||
annotations:{title:'Frontend Issue Audit Verification'},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const p=await h.buildTelemetryPayloadInternal('root-audit');
|
||||
assert.equal(p.conversations.length,1);
|
||||
assert.equal(p.conversations[0].cascadeId,'root-audit');
|
||||
assert.equal(p.conversations[0].subagentCount,2);
|
||||
assert.equal(p.activeConversation.hasSubagents,true);
|
||||
assert.equal(p.activeConversation.subagentCount,2);
|
||||
assert.equal(p.activeConversation.agents.length,3);
|
||||
assert.equal(p.activeConversation.agents[1].agentId,'sub-cached-1');
|
||||
assert.equal(p.activeConversation.agents[1].role,'Build & Baseline Verifier');
|
||||
assert.equal(p.activeConversation.agents[1].context.messagesTokens,18000);
|
||||
assert.equal(p.activeConversation.agents[2].agentId,'sub-uncached-2');
|
||||
assert.equal(p.activeConversation.agents[2].role,'P0 Disk Quiz Patch Verifier');
|
||||
assert.equal(p.activeConversation.aggregated.stepCount,3);
|
||||
// Verify initialPrompt was stripped from persisted cache
|
||||
const savedSub2=h.state.saves[h.state.saves.length-1].data['sub-uncached-2'];
|
||||
assert.equal(savedSub2.subagentSpec.initialPrompt,undefined);
|
||||
assert.equal(savedSub2.subagentSpec.role,'P0 Disk Quiz Patch Verifier');
|
||||
// Conversation dropdown stepCount matches model step count (1, not 3 raw steps)
|
||||
assert.equal(p.conversations[0].stepCount,1);
|
||||
assert.equal(p.conversations[0].totalStepCount,3);
|
||||
});
|
||||
|
||||
test('converges multi-level nested subagents to ultimate root and preserves metrics when a newly spawned subagent has 0 steps',async()=>{
|
||||
const rootTraj={
|
||||
trajectory:{
|
||||
steps:[
|
||||
{
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{
|
||||
createdAt:'2026-01-01T00:00:00Z',
|
||||
finishedGeneratingAt:'2026-01-01T00:00:10Z',
|
||||
modelUsage:{inputTokens:'100',cacheReadTokens:'200',outputTokens:'600',thinkingOutputTokens:'100',responseOutputTokens:'500'},
|
||||
},
|
||||
plannerResponse:{response:'root step',thinkingDuration:'5s'},
|
||||
},
|
||||
{
|
||||
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{createdAt:'2026-01-01T00:00:11Z'},
|
||||
invokeSubagent:{
|
||||
subagents:[{typeName:'self',role:'Level 1 Orchestrator'}],
|
||||
results:[{conversationId:'sub-l1'}],
|
||||
},
|
||||
},
|
||||
],
|
||||
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'2s',streamingDuration:'8s'}}],
|
||||
},
|
||||
};
|
||||
const subL1Traj={
|
||||
trajectory:{
|
||||
metadata:{
|
||||
parentConversationId:'root-multi',
|
||||
subagentSpec:{typeName:'self'},
|
||||
},
|
||||
steps:[
|
||||
{
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{
|
||||
createdAt:'2026-01-01T00:00:15Z',
|
||||
finishedGeneratingAt:'2026-01-01T00:00:20Z',
|
||||
modelUsage:{inputTokens:'200',cacheReadTokens:'300',outputTokens:'400',thinkingOutputTokens:'50',responseOutputTokens:'350'},
|
||||
},
|
||||
plannerResponse:{response:'l1 step',thinkingDuration:'1s'},
|
||||
},
|
||||
{
|
||||
type:'CORTEX_STEP_TYPE_INVOKE_SUBAGENT',
|
||||
status:'CORTEX_STEP_STATUS_DONE',
|
||||
metadata:{createdAt:'2026-01-01T00:00:21Z'},
|
||||
invokeSubagent:{
|
||||
subagents:[{typeName:'research',role:'Level 2 Deep Worker'}],
|
||||
results:[{conversationId:'sub-l2'}],
|
||||
},
|
||||
},
|
||||
],
|
||||
generatorMetadata:[{stepIndices:[0],chatModel:{timeToFirstToken:'1s',streamingDuration:'4s',chatStartMetadata:{contextWindowMetadata:{tokenBreakdown:{groups:[{type:'TOKEN_TYPE_CHAT_MESSAGES',numTokens:24000}]}}}}}],
|
||||
},
|
||||
};
|
||||
// Level 2 subagent is currently running with 0 completed model steps so far
|
||||
const subL2Traj={
|
||||
trajectory:{
|
||||
metadata:{
|
||||
parentConversationId:'sub-l1',
|
||||
rootConversationId:'sub-l1',
|
||||
},
|
||||
steps:[],
|
||||
generatorMetadata:[],
|
||||
},
|
||||
};
|
||||
|
||||
const h=backendHarness({
|
||||
trajectories:{
|
||||
'root-multi':rootTraj,
|
||||
'sub-l1':subL1Traj,
|
||||
'sub-l2':subL2Traj,
|
||||
},
|
||||
summaries:{
|
||||
'root-multi':{stepCount:2,lastModifiedTime:'2026-01-01T00:00:11Z',status:'IDLE',annotations:{title:'Multi-Level Task'}},
|
||||
'sub-l1':{stepCount:2,lastModifiedTime:'2026-01-01T00:00:21Z',status:'IDLE',trajectoryMetadata:{parentConversationId:'root-multi'}},
|
||||
'sub-l2':{stepCount:0,lastModifiedTime:'2026-01-01T00:00:25Z',status:'CASCADE_RUN_STATUS_RUNNING',trajectoryMetadata:{parentConversationId:'sub-l1',rootConversationId:'sub-l1'}},
|
||||
},
|
||||
});
|
||||
|
||||
const p=await h.buildTelemetryPayloadInternal('root-multi');
|
||||
assert.equal(p.conversations.length,1);
|
||||
assert.equal(p.conversations[0].subagentCount,2);
|
||||
assert.equal(p.activeConversation.subagentCount,2);
|
||||
assert.equal(p.activeConversation.agents.length,3);
|
||||
// Partial subagentSpec ({typeName:'self'}) merged with invokeSubagent role ('Level 1 Orchestrator')
|
||||
assert.equal(p.activeConversation.agents[1].role,'Level 1 Orchestrator');
|
||||
assert.equal(p.activeConversation.agents[2].agentId,'sub-l2');
|
||||
assert.equal(p.activeConversation.agents[2].role,'Level 2 Deep Worker');
|
||||
// Even though sub-l2 is running with 0 steps, aggregated telemetry retains valid speed & context from sub-l1
|
||||
assert.equal(p.activeConversation.aggregated.activeAgentId,'sub-l2');
|
||||
assert.equal(p.activeConversation.aggregated.latestTokPerSec,80);
|
||||
assert.equal(p.activeConversation.aggregated.context.messagesTokens,24000);
|
||||
// Main agent steps are not duplicated in agents[0].recentSteps or aggregated.recentSteps
|
||||
assert.equal(p.activeConversation.agents[0].recentSteps,undefined);
|
||||
assert.equal(p.activeConversation.aggregated.recentSteps,undefined);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user