mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
fix(panel): preserve context window breakdown after conversation undo
- Anchor unindexed (stepIndices: []) trailing generatorMetadata breakdowns to the prior generator watermark and backfill pre-compaction anchor steps without leaking onto compaction checkpoints - Preserve matching historical step contextBreakdown entries and a compact 5-channel static baseline across trajectory rescans so deleting the tail generatorMetadata on undo no longer zeroes out channels - Reconstruct missing context channels from step token deltas and the cached static baseline when no breakdown payload remains, with estimatedContextTokens fallback for zero-usage tail steps
This commit is contained in:
@@ -1807,16 +1807,24 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
|||||||
|
|
||||||
if (ownGenRecords.length > 0) {
|
if (ownGenRecords.length > 0) {
|
||||||
// 从末尾向前定位最近一条包含完整上下文拆解(tokenBreakdown / promptSections / tools / messagePrompts)的记录,
|
// 从末尾向前定位最近一条包含完整上下文拆解(tokenBreakdown / promptSections / tools / messagePrompts)的记录,
|
||||||
// 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成。
|
// 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成;
|
||||||
|
// 若末尾完整记录因回退/中断成为 `stepIndices: []`,继续跳过被宿主裁剪的轻量记录并尝试补解更早的完整带索引记录。
|
||||||
|
let foundUnindexedBreakdown = false;
|
||||||
for (let i = ownGenRecords.length - 1; i >= 0; i--) {
|
for (let i = ownGenRecords.length - 1; i >= 0; i--) {
|
||||||
const rec = ownGenRecords[i];
|
const rec = ownGenRecords[i];
|
||||||
|
if (foundUnindexedBreakdown && Number(rec?.rawData?.byteLength || 0) <= 2048) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const fullDecoded = decodeProtoGeneratorMeta(rec.rawData, true);
|
const fullDecoded = decodeProtoGeneratorMeta(rec.rawData, true);
|
||||||
if (fullDecoded) {
|
if (fullDecoded) {
|
||||||
rec.gm = fullDecoded;
|
rec.gm = fullDecoded;
|
||||||
if (hasContextBreakdownPayload(fullDecoded.chatModel)) {
|
if (hasContextBreakdownPayload(fullDecoded.chatModel)) {
|
||||||
|
if (Array.isArray(fullDecoded.stepIndices) && fullDecoded.stepIndices.length > 0) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
foundUnindexedBreakdown = true;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// 保留轻量版本
|
// 保留轻量版本
|
||||||
|
|||||||
@@ -327,6 +327,146 @@ function normalizeOwnerAccount(value) {
|
|||||||
* - 已存在于旧缓存中的历史步骤保留原归属账号(兼容跨账号续聊同一会话);
|
* - 已存在于旧缓存中的历史步骤保留原归属账号(兼容跨账号续聊同一会话);
|
||||||
* - 切换账号后在该会话中新产生的步骤写入当前活跃账号 `step.accountName`,仅供「可用额度」按账号隔离统计。
|
* - 切换账号后在该会话中新产生的步骤写入当前活跃账号 `step.accountName`,仅供「可用额度」按账号隔离统计。
|
||||||
*/
|
*/
|
||||||
|
const MAX_PRESERVED_BREAKDOWN_STEPS = 64;
|
||||||
|
|
||||||
|
function extractStaticContextFromStep(st) {
|
||||||
|
const bd = st?.contextBreakdown;
|
||||||
|
if (!bd || typeof bd !== 'object') return null;
|
||||||
|
const sysPrompt = Math.max(0, Number(bd.systemPromptTokens || 0));
|
||||||
|
const sysTools = Math.max(0, Number(bd.systemToolsTokens || 0));
|
||||||
|
const mcpTools = Math.max(0, Number(bd.mcpToolsTokens || 0));
|
||||||
|
const skills = Math.max(0, Number(bd.skillsTokens || 0));
|
||||||
|
const userRules = Math.max(0, Number(bd.userRulesTokens || 0));
|
||||||
|
const staticSum = sysPrompt + sysTools + mcpTools + skills + userRules;
|
||||||
|
if (staticSum <= 0) return null;
|
||||||
|
|
||||||
|
const rawTotal =
|
||||||
|
Number(bd.totalTokens || 0) ||
|
||||||
|
staticSum +
|
||||||
|
Math.max(0, Number(bd.messagesTokens || 0)) ||
|
||||||
|
staticSum +
|
||||||
|
Math.max(0, Number(bd.userInputTokens || 0)) +
|
||||||
|
Math.max(0, Number(bd.assistantTokens || 0)) +
|
||||||
|
Math.max(0, Number(bd.toolResultsTokens || 0)) +
|
||||||
|
Math.max(0, Number(bd.subagentTokens || 0)) +
|
||||||
|
Math.max(0, Number(bd.checkpointTokens || 0));
|
||||||
|
const promptTokens =
|
||||||
|
Math.max(0, Number(st?.inputTokens || 0)) + Math.max(0, Number(st?.cacheReadTokens || 0));
|
||||||
|
const scale =
|
||||||
|
rawTotal > 0 && promptTokens >= rawTotal * 0.5 ? promptTokens / rawTotal : 1;
|
||||||
|
|
||||||
|
return {
|
||||||
|
systemPromptTokens: Math.round(sysPrompt * scale),
|
||||||
|
systemToolsTokens: Math.round(sysTools * scale),
|
||||||
|
mcpToolsTokens: Math.round(mcpTools * scale),
|
||||||
|
skillsTokens: Math.round(skills * scale),
|
||||||
|
userRulesTokens: Math.round(userRules * scale),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSameHistoricalStep(nextStep, prevStep) {
|
||||||
|
if (!nextStep || !prevStep || typeof nextStep !== 'object' || typeof prevStep !== 'object') {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (Number(nextStep.stepIndex) !== Number(prevStep.stepIndex)) return false;
|
||||||
|
if (Boolean(nextStep.isCompactionStep) !== Boolean(prevStep.isCompactionStep)) return false;
|
||||||
|
if (
|
||||||
|
Number(nextStep.inputTokens || 0) !== Number(prevStep.inputTokens || 0) ||
|
||||||
|
Number(nextStep.cacheReadTokens || 0) !== Number(prevStep.cacheReadTokens || 0) ||
|
||||||
|
Number(nextStep.outputTokens || 0) !== Number(prevStep.outputTokens || 0)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const nextTs = Number(nextStep.createdAtMs || 0);
|
||||||
|
const prevTs = Number(prevStep.createdAtMs || 0);
|
||||||
|
if (nextTs > 0 && prevTs > 0 && Math.abs(nextTs - prevTs) > 2000) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 宿主只保留末尾一条完整 `gen_metadata` 并裁剪历史拆解;对话运行或回退重扫时,
|
||||||
|
* 为当前活跃窗口内(最近压缩前锚点至末尾,最多保留 64 步)完全匹配的未变更历史步保留已缓存的 `contextBreakdown`,
|
||||||
|
* 同时维护紧凑的 5 通道静态基线,确保回退到任意较早轮次后上下文窗口拆解不归零。
|
||||||
|
*/
|
||||||
|
function preserveCachedContextTelemetry(steps, prev) {
|
||||||
|
if (!Array.isArray(steps) || steps.length === 0) {
|
||||||
|
return {
|
||||||
|
steps,
|
||||||
|
lastKnownStaticContext: prev?.lastKnownStaticContext || null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let preservedSteps = steps;
|
||||||
|
const prevSteps = Array.isArray(prev?.steps) ? prev.steps : [];
|
||||||
|
if (prevSteps.length > 0) {
|
||||||
|
const prevWithBdByIdx = new Map();
|
||||||
|
for (const ps of prevSteps) {
|
||||||
|
if (!ps || typeof ps !== 'object' || !ps.contextBreakdown) continue;
|
||||||
|
const idx = Number(ps.stepIndex);
|
||||||
|
if (Number.isFinite(idx)) {
|
||||||
|
prevWithBdByIdx.set(idx, ps);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (prevWithBdByIdx.size > 0) {
|
||||||
|
let lastCompIdx = -1;
|
||||||
|
for (let i = steps.length - 1; i >= 0; i -= 1) {
|
||||||
|
if (steps[i]?.isCompactionStep) {
|
||||||
|
lastCompIdx = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let keepStartIdx = Math.max(0, steps.length - MAX_PRESERVED_BREAKDOWN_STEPS);
|
||||||
|
if (lastCompIdx >= 0) {
|
||||||
|
const anchorIdx = Math.max(0, lastCompIdx - 1);
|
||||||
|
keepStartIdx = Math.max(keepStartIdx, anchorIdx);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mutated = false;
|
||||||
|
const nextList = steps.map((st, pos) => {
|
||||||
|
if (!st || st.isCompactionStep || st.contextBreakdown || pos < keepStartIdx) {
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
const idx = Number(st.stepIndex);
|
||||||
|
const matchedPrev = Number.isFinite(idx) ? prevWithBdByIdx.get(idx) : null;
|
||||||
|
if (!matchedPrev || !isSameHistoricalStep(st, matchedPrev)) {
|
||||||
|
return st;
|
||||||
|
}
|
||||||
|
mutated = true;
|
||||||
|
return {
|
||||||
|
...st,
|
||||||
|
contextBreakdown: matchedPrev.contextBreakdown,
|
||||||
|
...(!st.reportedContextLimitTokens && matchedPrev.reportedContextLimitTokens
|
||||||
|
? {
|
||||||
|
reportedContextLimitTokens: matchedPrev.reportedContextLimitTokens,
|
||||||
|
maxContextBudgetTokens: matchedPrev.maxContextBudgetTokens,
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
if (mutated) {
|
||||||
|
preservedSteps = nextList;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let lastKnownStaticContext = null;
|
||||||
|
for (let i = preservedSteps.length - 1; i >= 0; i -= 1) {
|
||||||
|
const extracted = extractStaticContextFromStep(preservedSteps[i]);
|
||||||
|
if (extracted) {
|
||||||
|
lastKnownStaticContext = extracted;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!lastKnownStaticContext && prev?.lastKnownStaticContext) {
|
||||||
|
lastKnownStaticContext = prev.lastKnownStaticContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { steps: preservedSteps, lastKnownStaticContext };
|
||||||
|
}
|
||||||
|
|
||||||
function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountName) {
|
function attachStepAccountOwners(steps, prev, currentAccountName, entryAccountName) {
|
||||||
if (!Array.isArray(steps) || steps.length === 0) return steps;
|
if (!Array.isArray(steps) || steps.length === 0) return steps;
|
||||||
const activeOwner = normalizeOwnerAccount(currentAccountName);
|
const activeOwner = normalizeOwnerAccount(currentAccountName);
|
||||||
@@ -2199,8 +2339,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const entryAccountName = prev?.accountName || currentAccountName || '';
|
const entryAccountName = prev?.accountName || currentAccountName || '';
|
||||||
|
const contextPreserved = preserveCachedContextTelemetry(steps, prev);
|
||||||
const stepsWithOwners = attachStepAccountOwners(
|
const stepsWithOwners = attachStepAccountOwners(
|
||||||
steps,
|
contextPreserved.steps,
|
||||||
prev,
|
prev,
|
||||||
currentAccountName,
|
currentAccountName,
|
||||||
entryAccountName
|
entryAccountName
|
||||||
@@ -2218,9 +2359,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
speedClearedTelemetry: true,
|
speedClearedTelemetry: true,
|
||||||
turnRailTelemetry: true,
|
turnRailTelemetry: true,
|
||||||
wakeupTurnTelemetry: true,
|
wakeupTurnTelemetry: true,
|
||||||
contextGroupsTelemetry: 2,
|
contextGroupsTelemetry: 3,
|
||||||
anomalyTelemetry: 1,
|
anomalyTelemetry: 1,
|
||||||
steps: stepsWithOwners,
|
steps: stepsWithOwners,
|
||||||
|
...(contextPreserved.lastKnownStaticContext
|
||||||
|
? { lastKnownStaticContext: contextPreserved.lastKnownStaticContext }
|
||||||
|
: {}),
|
||||||
subagentRefs,
|
subagentRefs,
|
||||||
};
|
};
|
||||||
if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta;
|
if (rpcSwarmMeta) cacheEntry.swarmMeta = rpcSwarmMeta;
|
||||||
@@ -2246,6 +2390,10 @@ export async function enumerateAndSyncConversations({
|
|||||||
!Array.isArray(prev?.subagentRefs) ||
|
!Array.isArray(prev?.subagentRefs) ||
|
||||||
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
|
JSON.stringify(prev?.subagentRefs) !== JSON.stringify(subagentRefs) ||
|
||||||
!isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) ||
|
!isDeepStrictEqual(prev?.swarmMeta || null, cacheEntry.swarmMeta || null) ||
|
||||||
|
!isDeepStrictEqual(
|
||||||
|
prev?.lastKnownStaticContext || null,
|
||||||
|
cacheEntry.lastKnownStaticContext || null
|
||||||
|
) ||
|
||||||
Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) ||
|
Boolean(prev?.parkedOnSwarmWait) !== Boolean(cacheEntry.parkedOnSwarmWait) ||
|
||||||
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') ||
|
(prev?.rootConversationId || '') !== (cacheEntry.rootConversationId || '') ||
|
||||||
Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion);
|
Boolean(prev?.isSideQuestion) !== Boolean(cacheEntry.isSideQuestion);
|
||||||
@@ -2257,7 +2405,7 @@ export async function enumerateAndSyncConversations({
|
|||||||
!prev.contextLimitTelemetry ||
|
!prev.contextLimitTelemetry ||
|
||||||
!prev.speedClearedTelemetry ||
|
!prev.speedClearedTelemetry ||
|
||||||
!prev.turnRailTelemetry ||
|
!prev.turnRailTelemetry ||
|
||||||
!prev.contextGroupsTelemetry ||
|
Number(prev.contextGroupsTelemetry || 0) < 3 ||
|
||||||
!prev.anomalyTelemetry ||
|
!prev.anomalyTelemetry ||
|
||||||
metaChanged ||
|
metaChanged ||
|
||||||
!isDeepStrictEqual(prev.steps, stepsWithOwners);
|
!isDeepStrictEqual(prev.steps, stepsWithOwners);
|
||||||
@@ -2307,8 +2455,9 @@ export async function enumerateAndSyncConversations({
|
|||||||
const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles);
|
const resolvedDiskMtime = conv.diskMtimeMs ?? readConversationMtime(diskFiles);
|
||||||
const offlineAccountName =
|
const offlineAccountName =
|
||||||
prev?.accountName || offlineFallback.accountName || currentAccountName || '';
|
prev?.accountName || offlineFallback.accountName || currentAccountName || '';
|
||||||
|
const offlinePreserved = preserveCachedContextTelemetry(offlineFallback.steps, prev);
|
||||||
const offlineStepsWithOwners = attachStepAccountOwners(
|
const offlineStepsWithOwners = attachStepAccountOwners(
|
||||||
offlineFallback.steps,
|
offlinePreserved.steps,
|
||||||
prev,
|
prev,
|
||||||
offlineFallback.accountName || currentAccountName,
|
offlineFallback.accountName || currentAccountName,
|
||||||
offlineAccountName
|
offlineAccountName
|
||||||
@@ -2327,9 +2476,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
contextLimitTelemetry: true,
|
contextLimitTelemetry: true,
|
||||||
speedClearedTelemetry: true,
|
speedClearedTelemetry: true,
|
||||||
turnRailTelemetry: true,
|
turnRailTelemetry: true,
|
||||||
contextGroupsTelemetry: 2,
|
contextGroupsTelemetry: 3,
|
||||||
anomalyTelemetry: 1,
|
anomalyTelemetry: 1,
|
||||||
steps: offlineStepsWithOwners,
|
steps: offlineStepsWithOwners,
|
||||||
|
...(offlinePreserved.lastKnownStaticContext
|
||||||
|
? { lastKnownStaticContext: offlinePreserved.lastKnownStaticContext }
|
||||||
|
: {}),
|
||||||
subagentRefs: offlineFallback.subagentRefs,
|
subagentRefs: offlineFallback.subagentRefs,
|
||||||
};
|
};
|
||||||
if (conv.isSubagent) {
|
if (conv.isSubagent) {
|
||||||
@@ -2441,8 +2593,12 @@ export async function enumerateAndSyncConversations({
|
|||||||
return !Object.prototype.hasOwnProperty.call(lastCachedStep, 'turnIndex');
|
return !Object.prototype.hasOwnProperty.call(lastCachedStep, 'turnIndex');
|
||||||
}
|
}
|
||||||
function hasDroppedContextGroups(cached) {
|
function hasDroppedContextGroups(cached) {
|
||||||
if (cached?.contextGroupsTelemetry === 2) return false;
|
const grpVer = Number(cached?.contextGroupsTelemetry || 0);
|
||||||
|
if (grpVer >= 3) return false;
|
||||||
const steps = cached?.steps || [];
|
const steps = cached?.steps || [];
|
||||||
|
if (grpVer === 2) {
|
||||||
|
return steps.length > 0 && !steps.some((st) => Boolean(st?.contextBreakdown));
|
||||||
|
}
|
||||||
if (steps.some((st) => st?.isCompactionStep)) {
|
if (steps.some((st) => st?.isCompactionStep)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -325,6 +325,35 @@ const CONTEXT_CHANNEL_KEYS = [
|
|||||||
'userRules',
|
'userRules',
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const STATIC_CONTEXT_CHANNEL_KEYS = [
|
||||||
|
'systemTools',
|
||||||
|
'mcpTools',
|
||||||
|
'skills',
|
||||||
|
'systemPrompt',
|
||||||
|
'userRules',
|
||||||
|
];
|
||||||
|
|
||||||
|
function applyFallbackStaticChannels(channels, fallbackStaticContext, capTotal = 0) {
|
||||||
|
if (!fallbackStaticContext || typeof fallbackStaticContext !== 'object') return 0;
|
||||||
|
let staticMap = {
|
||||||
|
systemTools: Math.max(0, Math.round(Number(fallbackStaticContext.systemToolsTokens || 0))),
|
||||||
|
mcpTools: Math.max(0, Math.round(Number(fallbackStaticContext.mcpToolsTokens || 0))),
|
||||||
|
skills: Math.max(0, Math.round(Number(fallbackStaticContext.skillsTokens || 0))),
|
||||||
|
systemPrompt: Math.max(0, Math.round(Number(fallbackStaticContext.systemPromptTokens || 0))),
|
||||||
|
userRules: Math.max(0, Math.round(Number(fallbackStaticContext.userRulesTokens || 0))),
|
||||||
|
};
|
||||||
|
let staticSum = STATIC_CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + staticMap[k], 0);
|
||||||
|
if (staticSum <= 0) return 0;
|
||||||
|
if (capTotal > 0 && staticSum > capTotal) {
|
||||||
|
staticMap = scaleBucketsExact(staticMap, STATIC_CONTEXT_CHANNEL_KEYS, Math.round(capTotal));
|
||||||
|
staticSum = STATIC_CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + staticMap[k], 0);
|
||||||
|
}
|
||||||
|
for (const k of STATIC_CONTEXT_CHANNEL_KEYS) {
|
||||||
|
channels[k] = staticMap[k];
|
||||||
|
}
|
||||||
|
return staticSum;
|
||||||
|
}
|
||||||
|
|
||||||
function resolveStepOutputTokens(st) {
|
function resolveStepOutputTokens(st) {
|
||||||
const explicitOut = Number(st?.outputTokens || 0);
|
const explicitOut = Number(st?.outputTokens || 0);
|
||||||
if (explicitOut > 0) return explicitOut;
|
if (explicitOut > 0) return explicitOut;
|
||||||
@@ -388,7 +417,8 @@ function extractActiveContextTelemetry(
|
|||||||
enrichedActiveSteps,
|
enrichedActiveSteps,
|
||||||
latestEnriched,
|
latestEnriched,
|
||||||
sessionInputTokens,
|
sessionInputTokens,
|
||||||
sessionCacheReadTokens
|
sessionCacheReadTokens,
|
||||||
|
fallbackStaticContext = null
|
||||||
) {
|
) {
|
||||||
let lastCompactionIdx = -1;
|
let lastCompactionIdx = -1;
|
||||||
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
||||||
@@ -470,6 +500,8 @@ function extractActiveContextTelemetry(
|
|||||||
channels.skills = preChannels.skills;
|
channels.skills = preChannels.skills;
|
||||||
channels.systemPrompt = preChannels.systemPrompt;
|
channels.systemPrompt = preChannels.systemPrompt;
|
||||||
channels.userRules = preChannels.userRules;
|
channels.userRules = preChannels.userRules;
|
||||||
|
} else if (fallbackStaticContext) {
|
||||||
|
applyFallbackStaticChannels(channels, fallbackStaticContext, 0);
|
||||||
}
|
}
|
||||||
channels.userInput = 0;
|
channels.userInput = 0;
|
||||||
channels.assistant = 0;
|
channels.assistant = 0;
|
||||||
@@ -499,6 +531,59 @@ function extractActiveContextTelemetry(
|
|||||||
runningTotal = mPrompt + mOut;
|
runningTotal = mPrompt + mOut;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else if (enrichedActiveSteps.length > 0) {
|
||||||
|
// 当宿主回退或历史裁剪导致全部步骤均无 `contextBreakdown` 且未发生过压缩时,
|
||||||
|
// 基于缓存的 5 通道静态基线(如有)和各步真实计费增量重建上下文通道,避免进度条和 10 项图例全归零。
|
||||||
|
let runningTotal = 0;
|
||||||
|
let seededInitial = false;
|
||||||
|
for (let m = 0; m < enrichedActiveSteps.length; m++) {
|
||||||
|
const stepM = enrichedActiveSteps[m];
|
||||||
|
if (!stepM || stepM.isCompactionStep) continue;
|
||||||
|
const mPrompt =
|
||||||
|
Number(stepM.inputTokens || 0) + Number(stepM.cacheReadTokens || 0);
|
||||||
|
const mOut = resolveStepOutputTokens(stepM);
|
||||||
|
if (!seededInitial) {
|
||||||
|
if (mPrompt <= 0 && mOut <= 0) continue;
|
||||||
|
seededInitial = true;
|
||||||
|
if (mPrompt > 0) {
|
||||||
|
const staticUsed = applyFallbackStaticChannels(
|
||||||
|
channels,
|
||||||
|
fallbackStaticContext,
|
||||||
|
mPrompt
|
||||||
|
);
|
||||||
|
channels.userInput += Math.max(0, mPrompt - staticUsed);
|
||||||
|
}
|
||||||
|
channels.assistant += mOut;
|
||||||
|
runningTotal = mPrompt + mOut;
|
||||||
|
} else if (mPrompt > 0) {
|
||||||
|
if (mPrompt > runningTotal) {
|
||||||
|
const delta = mPrompt - runningTotal;
|
||||||
|
if (enrichedActiveSteps[m - 1]?.hasToolCalls) {
|
||||||
|
channels.toolResults += delta;
|
||||||
|
} else {
|
||||||
|
channels.userInput += delta;
|
||||||
|
}
|
||||||
|
} else if (mPrompt < runningTotal) {
|
||||||
|
channels = scaleBucketsExact(channels, CONTEXT_CHANNEL_KEYS, mPrompt);
|
||||||
|
}
|
||||||
|
channels.assistant += mOut;
|
||||||
|
runningTotal = mPrompt + mOut;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (runningTotal === 0) {
|
||||||
|
const estFallback = Math.max(
|
||||||
|
0,
|
||||||
|
Math.round(Number(latestEnriched?.estimatedContextTokens || 0))
|
||||||
|
);
|
||||||
|
if (estFallback > 0) {
|
||||||
|
const staticUsed = applyFallbackStaticChannels(
|
||||||
|
channels,
|
||||||
|
fallbackStaticContext,
|
||||||
|
estFallback
|
||||||
|
);
|
||||||
|
channels.userInput += Math.max(0, estFallback - staticUsed);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const ctxUserInput = channels.userInput;
|
const ctxUserInput = channels.userInput;
|
||||||
@@ -526,7 +611,7 @@ function extractActiveContextTelemetry(
|
|||||||
? ctxBreakdownTotal
|
? ctxBreakdownTotal
|
||||||
: ctxBreakdownTotal > 0
|
: ctxBreakdownTotal > 0
|
||||||
? ctxBreakdownTotal
|
? ctxBreakdownTotal
|
||||||
: ctxCached + ctxFreshInput + ctxOut;
|
: ctxCached + ctxFreshInput + ctxOut || Number(latestEnriched?.estimatedContextTokens || 0);
|
||||||
const compactionLimitTokens = Number(
|
const compactionLimitTokens = Number(
|
||||||
(isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
|
(isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
|
||||||
? fallbackPreCompactionLimit
|
? fallbackPreCompactionLimit
|
||||||
@@ -598,7 +683,14 @@ function sameFallbackUpstreams(prevMap, fallbackModelKeys, upstream) {
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, reuseInputs) {
|
function prepareAgentSteps(
|
||||||
|
rawSteps,
|
||||||
|
resolveStepModel,
|
||||||
|
upstream,
|
||||||
|
agentFields,
|
||||||
|
reuseInputs,
|
||||||
|
fallbackStaticContext = null
|
||||||
|
) {
|
||||||
const facts = readTrajectoryModelFacts(rawSteps);
|
const facts = readTrajectoryModelFacts(rawSteps);
|
||||||
for (const [key, model] of facts.upstream) upstream.set(key, model);
|
for (const [key, model] of facts.upstream) upstream.set(key, model);
|
||||||
const canCache = Boolean(reuseInputs && Array.isArray(rawSteps));
|
const canCache = Boolean(reuseInputs && Array.isArray(rawSteps));
|
||||||
@@ -610,6 +702,7 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
|
|||||||
previous.catalogRevision === reuseInputs.catalogRevision &&
|
previous.catalogRevision === reuseInputs.catalogRevision &&
|
||||||
previous.phaseEpoch === reuseInputs.phaseEpoch &&
|
previous.phaseEpoch === reuseInputs.phaseEpoch &&
|
||||||
isDeepStrictEqual(previous.dynamicModelMap, reuseInputs.dynamicModelMap) &&
|
isDeepStrictEqual(previous.dynamicModelMap, reuseInputs.dynamicModelMap) &&
|
||||||
|
isDeepStrictEqual(previous.fallbackStaticContext || null, fallbackStaticContext || null) &&
|
||||||
sameFallbackUpstreams(previous.fallbackUpstreams, facts.fallbackModelKeys, upstream)
|
sameFallbackUpstreams(previous.fallbackUpstreams, facts.fallbackModelKeys, upstream)
|
||||||
) {
|
) {
|
||||||
return previous.prepared;
|
return previous.prepared;
|
||||||
@@ -620,8 +713,13 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
|
|||||||
const prepared = {
|
const prepared = {
|
||||||
enrichedRes,
|
enrichedRes,
|
||||||
recentSteps: taggedSteps.slice().reverse(),
|
recentSteps: taggedSteps.slice().reverse(),
|
||||||
ctxRes: extractActiveContextTelemetry(taggedSteps, enrichedRes.latestEnriched,
|
ctxRes: extractActiveContextTelemetry(
|
||||||
enrichedRes.sessionInputTokens, enrichedRes.sessionCacheReadTokens),
|
taggedSteps,
|
||||||
|
enrichedRes.latestEnriched,
|
||||||
|
enrichedRes.sessionInputTokens,
|
||||||
|
enrichedRes.sessionCacheReadTokens,
|
||||||
|
fallbackStaticContext
|
||||||
|
),
|
||||||
modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel),
|
modelBreakdown: buildScopedModelBreakdown(taggedSteps, resolveStepModel),
|
||||||
};
|
};
|
||||||
// 按 rawSteps 数组引用缓存各代理(含多代理子代理)步骤富化结果,步骤变更后由 WeakMap 自动淘汰。
|
// 按 rawSteps 数组引用缓存各代理(含多代理子代理)步骤富化结果,步骤变更后由 WeakMap 自动淘汰。
|
||||||
@@ -631,6 +729,7 @@ function prepareAgentSteps(rawSteps, resolveStepModel, upstream, agentFields, re
|
|||||||
catalogRevision: reuseInputs.catalogRevision,
|
catalogRevision: reuseInputs.catalogRevision,
|
||||||
phaseEpoch: reuseInputs.phaseEpoch,
|
phaseEpoch: reuseInputs.phaseEpoch,
|
||||||
dynamicModelMap: reuseInputs.dynamicModelMap,
|
dynamicModelMap: reuseInputs.dynamicModelMap,
|
||||||
|
fallbackStaticContext: fallbackStaticContext || null,
|
||||||
fallbackUpstreams: snapshotFallbackUpstreams(facts.fallbackModelKeys, upstream),
|
fallbackUpstreams: snapshotFallbackUpstreams(facts.fallbackModelKeys, upstream),
|
||||||
prepared,
|
prepared,
|
||||||
});
|
});
|
||||||
@@ -660,6 +759,7 @@ export function buildAgentUnitTelemetry({
|
|||||||
agentLabel,
|
agentLabel,
|
||||||
status,
|
status,
|
||||||
rawSteps,
|
rawSteps,
|
||||||
|
fallbackStaticContext = null,
|
||||||
liveActivity = null,
|
liveActivity = null,
|
||||||
fallbackLastModMs,
|
fallbackLastModMs,
|
||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
@@ -684,7 +784,8 @@ export function buildAgentUnitTelemetry({
|
|||||||
isSubagent: !isMain,
|
isSubagent: !isMain,
|
||||||
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
|
...(isSideQuestion ? { isSideQuestion: true, sideIndex } : {}),
|
||||||
},
|
},
|
||||||
reuseInputs
|
reuseInputs,
|
||||||
|
fallbackStaticContext
|
||||||
);
|
);
|
||||||
const taggedSteps = enrichedRes.enrichedActiveSteps;
|
const taggedSteps = enrichedRes.enrichedActiveSteps;
|
||||||
const lastModifiedMs =
|
const lastModifiedMs =
|
||||||
@@ -951,6 +1052,7 @@ function buildActiveConversationAssembly({
|
|||||||
activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||||
activeConvSummary?.liveActivity?.signature || '',
|
activeConvSummary?.liveActivity?.signature || '',
|
||||||
activeConvSummary?.liveActivity?.startedAtMs || 0,
|
activeConvSummary?.liveActivity?.startedAtMs || 0,
|
||||||
|
activeEntry?.lastKnownStaticContext || null,
|
||||||
subagentSummaries.map((subSum, idx) => {
|
subagentSummaries.map((subSum, idx) => {
|
||||||
const subEntry = subEntries[idx];
|
const subEntry = subEntries[idx];
|
||||||
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
const subSpec = subSum.subagentSpec || subEntry?.subagentSpec || null;
|
||||||
@@ -967,6 +1069,7 @@ function buildActiveConversationAssembly({
|
|||||||
subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
||||||
subSum.liveActivity?.signature || '',
|
subSum.liveActivity?.signature || '',
|
||||||
subSum.liveActivity?.startedAtMs || 0,
|
subSum.liveActivity?.startedAtMs || 0,
|
||||||
|
subEntry?.lastKnownStaticContext || null,
|
||||||
subSpec?.role || '',
|
subSpec?.role || '',
|
||||||
subSpec?.typeName || '',
|
subSpec?.typeName || '',
|
||||||
];
|
];
|
||||||
@@ -1007,6 +1110,7 @@ function buildActiveConversationAssembly({
|
|||||||
agentLabel: '主代理',
|
agentLabel: '主代理',
|
||||||
status: activeConvSummary?.status || 'IDLE',
|
status: activeConvSummary?.status || 'IDLE',
|
||||||
rawSteps: activeSteps,
|
rawSteps: activeSteps,
|
||||||
|
fallbackStaticContext: activeEntry?.lastKnownStaticContext || null,
|
||||||
liveActivity: activeConvSummary?.liveActivity || null,
|
liveActivity: activeConvSummary?.liveActivity || null,
|
||||||
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
fallbackLastModMs: activeConvSummary?.lastModifiedMs || activeEntry?.lastModifiedMs || 0,
|
||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
@@ -1088,6 +1192,7 @@ function buildActiveConversationAssembly({
|
|||||||
agentLabel,
|
agentLabel,
|
||||||
status: subSum.status || 'IDLE',
|
status: subSum.status || 'IDLE',
|
||||||
rawSteps: subRawSteps,
|
rawSteps: subRawSteps,
|
||||||
|
fallbackStaticContext: subEntry?.lastKnownStaticContext || null,
|
||||||
liveActivity: subSum.liveActivity || null,
|
liveActivity: subSum.liveActivity || null,
|
||||||
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
fallbackLastModMs: subSum.lastModifiedMs || subEntry?.lastModifiedMs || 0,
|
||||||
resolveStepModel,
|
resolveStepModel,
|
||||||
@@ -1884,8 +1989,13 @@ export async function buildTelemetryPayloadInternal(
|
|||||||
|
|
||||||
let contextUsedPct = null;
|
let contextUsedPct = null;
|
||||||
if (lastRootStep) {
|
if (lastRootStep) {
|
||||||
contextUsedPct = extractActiveContextTelemetry(rootSteps, lastRootStep, 0, 0).context
|
contextUsedPct = extractActiveContextTelemetry(
|
||||||
.compactionUsedPct;
|
rootSteps,
|
||||||
|
lastRootStep,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
rootEntry?.lastKnownStaticContext || null
|
||||||
|
).context.compactionUsedPct;
|
||||||
}
|
}
|
||||||
|
|
||||||
let modelShort = '';
|
let modelShort = '';
|
||||||
@@ -2338,10 +2448,13 @@ function resolveValidFastSnapshot(endpoint = null) {
|
|||||||
|
|
||||||
function entryNeedsLazyTelemetryUpgrade(entry) {
|
function entryNeedsLazyTelemetryUpgrade(entry) {
|
||||||
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false;
|
if (!entry || !Array.isArray(entry.steps) || entry.steps.length === 0) return false;
|
||||||
|
const grpVer = Number(entry.contextGroupsTelemetry || 0);
|
||||||
|
const needsUndoCtxUpgrade =
|
||||||
|
grpVer < 2 || (grpVer === 2 && !entry.steps.some((st) => Boolean(st?.contextBreakdown)));
|
||||||
return (
|
return (
|
||||||
!entry.turnRailTelemetry ||
|
!entry.turnRailTelemetry ||
|
||||||
!entry.anomalyTelemetry ||
|
!entry.anomalyTelemetry ||
|
||||||
entry.contextGroupsTelemetry !== 2
|
needsUndoCtxUpgrade
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3455,3 +3455,328 @@ test('CLI statusLine supports --style pill|bar|compact switching, flag persisten
|
|||||||
assert.equal(jsonSnap.quotas.pools[0].remaining5hPct, 40);
|
assert.equal(jsonSnap.quotas.pools[0].remaining5hPct, 40);
|
||||||
assert.equal(jsonSnap.quotas.pools[0].remainingWeeklyPct, 80);
|
assert.equal(jsonSnap.quotas.pools[0].remainingWeeklyPct, 80);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('conversation undo preserves 10-channel context breakdown across unindexed tail gen_metadata, stripped history, and cold fallback', async () => {
|
||||||
|
const baseMs = Date.parse('2026-11-23T17:00:00.000Z');
|
||||||
|
const iso = (offsetSec) => new Date(baseMs + offsetSec * 1000).toISOString();
|
||||||
|
|
||||||
|
// Case 1: Undo after a prior compaction leaves trailing gen_metadata with stepIndices: [] and full tokenBreakdown
|
||||||
|
const undoPostCompactSteps = [
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: iso(0),
|
||||||
|
completedAt: iso(2),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 10 },
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '180000', cacheReadTokens: '0', outputTokens: '800' },
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'before compact' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: iso(5),
|
||||||
|
completedAt: iso(7),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 11 },
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '181000', cacheReadTokens: '0', outputTokens: '3200', responseOutputTokens: '3100' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: iso(15),
|
||||||
|
completedAt: iso(18),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 14 },
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '5000', cacheReadTokens: '95000', outputTokens: '1200' },
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'post compact step' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CORTEX_STEP_TYPE_USER_INPUT',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: { createdAt: iso(25), sourceTrajectoryStepInfo: { stepIndex: 15 } },
|
||||||
|
userInput: { userResponse: 'undone prompt' },
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const undoPostCompactGen = [
|
||||||
|
{
|
||||||
|
stepIndices: [14],
|
||||||
|
chatModel: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 99000, maxContextTokens: 256000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stepIndices: [],
|
||||||
|
chatModel: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
chatStartMetadata: {
|
||||||
|
contextWindowMetadata: {
|
||||||
|
estimatedTokensUsed: 101200,
|
||||||
|
maxContextTokens: 256000,
|
||||||
|
tokenBreakdown: {
|
||||||
|
groups: [
|
||||||
|
{ type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 6000 },
|
||||||
|
{ type: 'TOKEN_TYPE_SKILLS', numTokens: 1800 },
|
||||||
|
{ type: 'TOKEN_TYPE_USER_RULES', numTokens: 2200 },
|
||||||
|
{
|
||||||
|
type: 'TOKEN_TYPE_TOOLS',
|
||||||
|
numTokens: 7000,
|
||||||
|
children: [
|
||||||
|
{ name: 'read_file', numTokens: 6500 },
|
||||||
|
{ name: 'mcp_custom_tool', numTokens: 500 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'TOKEN_TYPE_CHAT_MESSAGES',
|
||||||
|
numTokens: 84200,
|
||||||
|
children: [
|
||||||
|
{ name: '11: CHECKPOINT', numTokens: 3200 },
|
||||||
|
{ name: '12: USER_INPUT', numTokens: 1000 },
|
||||||
|
{ name: '13: GENERIC', numTokens: 45000 },
|
||||||
|
{ name: '14: PLANNER_RESPONSE', numTokens: 35000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const h1 = backendHarness({
|
||||||
|
trajectories: {
|
||||||
|
'conv-undo-si-empty': {
|
||||||
|
trajectory: { steps: undoPostCompactSteps, generatorMetadata: undoPostCompactGen },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summaries: {
|
||||||
|
'conv-undo-si-empty': {
|
||||||
|
annotations: { title: 'Undo Post Compact' },
|
||||||
|
stepCount: 4,
|
||||||
|
lastModifiedTime: iso(25),
|
||||||
|
status: 'IDLE',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const p1 = await h1.buildTelemetryPayloadInternal('conv-undo-si-empty');
|
||||||
|
const ctx1 = p1.activeConversation.context;
|
||||||
|
assert.equal(ctx1.totalTokens, 101200);
|
||||||
|
assert.ok(ctx1.systemPromptTokens > 5500, `sysPrompt=${ctx1.systemPromptTokens}`);
|
||||||
|
assert.ok(ctx1.systemToolsTokens > 6000, `sysTools=${ctx1.systemToolsTokens}`);
|
||||||
|
assert.ok(ctx1.mcpToolsTokens > 400, `mcpTools=${ctx1.mcpToolsTokens}`);
|
||||||
|
assert.ok(ctx1.skillsTokens > 1500, `skills=${ctx1.skillsTokens}`);
|
||||||
|
assert.ok(ctx1.userRulesTokens > 2000, `rules=${ctx1.userRulesTokens}`);
|
||||||
|
assert.equal(
|
||||||
|
ctx1.userInputTokens +
|
||||||
|
ctx1.assistantTokens +
|
||||||
|
ctx1.toolResultsTokens +
|
||||||
|
ctx1.subagentTokens +
|
||||||
|
ctx1.checkpointTokens +
|
||||||
|
ctx1.systemToolsTokens +
|
||||||
|
ctx1.mcpToolsTokens +
|
||||||
|
ctx1.skillsTokens +
|
||||||
|
ctx1.systemPromptTokens +
|
||||||
|
ctx1.userRulesTokens,
|
||||||
|
101200
|
||||||
|
);
|
||||||
|
|
||||||
|
// Case 2: Trailing compaction step with unindexed pre-compaction gen_metadata inherits static channels without inflating checkpoint
|
||||||
|
const h2 = backendHarness({
|
||||||
|
trajectories: {
|
||||||
|
'conv-undo-tail-compact': {
|
||||||
|
trajectory: {
|
||||||
|
steps: undoPostCompactSteps.slice(0, 2),
|
||||||
|
generatorMetadata: [
|
||||||
|
{
|
||||||
|
stepIndices: [10],
|
||||||
|
chatModel: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 180000, maxContextTokens: 512000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
stepIndices: [],
|
||||||
|
chatModel: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
chatStartMetadata: {
|
||||||
|
contextWindowMetadata: {
|
||||||
|
estimatedTokensUsed: 180000,
|
||||||
|
maxContextTokens: 512000,
|
||||||
|
tokenBreakdown: {
|
||||||
|
groups: [
|
||||||
|
{ type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 10000 },
|
||||||
|
{ type: 'TOKEN_TYPE_TOOLS', numTokens: 8000 },
|
||||||
|
{ type: 'TOKEN_TYPE_SKILLS', numTokens: 2000 },
|
||||||
|
{ type: 'TOKEN_TYPE_USER_RULES', numTokens: 3000 },
|
||||||
|
{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 157000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summaries: {
|
||||||
|
'conv-undo-tail-compact': {
|
||||||
|
annotations: { title: 'Tail Compact' },
|
||||||
|
stepCount: 2,
|
||||||
|
lastModifiedTime: iso(7),
|
||||||
|
status: 'IDLE',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const p2 = await h2.buildTelemetryPayloadInternal('conv-undo-tail-compact');
|
||||||
|
const ctx2 = p2.activeConversation.context;
|
||||||
|
assert.equal(ctx2.checkpointTokens, 3100);
|
||||||
|
assert.equal(ctx2.systemPromptTokens, 10000);
|
||||||
|
assert.equal(ctx2.systemToolsTokens, 8000);
|
||||||
|
assert.equal(ctx2.skillsTokens, 2000);
|
||||||
|
assert.equal(ctx2.userRulesTokens, 3000);
|
||||||
|
assert.equal(ctx2.userInputTokens, 0);
|
||||||
|
assert.equal(ctx2.totalTokens, 26100);
|
||||||
|
|
||||||
|
// Case 3: Live multi-turn undo deletes tail gen_metadata leaving only stripped 1KB rows -> cached breakdown + static baseline survive
|
||||||
|
const step1 = {
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: iso(0),
|
||||||
|
completedAt: iso(2),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 1 },
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '20000', cacheReadTokens: '0', outputTokens: '1000' },
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'turn 1', toolCalls: [{ name: 'read_file' }] },
|
||||||
|
};
|
||||||
|
const step2 = {
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: iso(10),
|
||||||
|
completedAt: iso(12),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 3 },
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '5000', cacheReadTokens: '21000', outputTokens: '1500' },
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'turn 2' },
|
||||||
|
};
|
||||||
|
const step3 = {
|
||||||
|
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||||
|
status: 'CORTEX_STEP_STATUS_DONE',
|
||||||
|
metadata: {
|
||||||
|
createdAt: iso(20),
|
||||||
|
completedAt: iso(22),
|
||||||
|
sourceTrajectoryStepInfo: { stepIndex: 5 },
|
||||||
|
modelUsage: { model: 'MODEL_PLACEHOLDER_M37', inputTokens: '4000', cacheReadTokens: '27500', outputTokens: '800' },
|
||||||
|
},
|
||||||
|
plannerResponse: { response: 'turn 3' },
|
||||||
|
};
|
||||||
|
const liveTraj = {
|
||||||
|
trajectory: {
|
||||||
|
steps: [step1, step2, step3],
|
||||||
|
generatorMetadata: [
|
||||||
|
{ stepIndices: [1], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 20000, maxContextTokens: 256000 } } } },
|
||||||
|
{ stepIndices: [3], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 26000, maxContextTokens: 256000 } } } },
|
||||||
|
{
|
||||||
|
stepIndices: [5],
|
||||||
|
chatModel: {
|
||||||
|
model: 'MODEL_PLACEHOLDER_M37',
|
||||||
|
chatStartMetadata: {
|
||||||
|
contextWindowMetadata: {
|
||||||
|
estimatedTokensUsed: 31500,
|
||||||
|
maxContextTokens: 256000,
|
||||||
|
tokenBreakdown: {
|
||||||
|
groups: [
|
||||||
|
{ type: 'TOKEN_TYPE_SYSTEM_PROMPT', numTokens: 6000 },
|
||||||
|
{ type: 'TOKEN_TYPE_TOOLS', numTokens: 7000 },
|
||||||
|
{ type: 'TOKEN_TYPE_SKILLS', numTokens: 1500 },
|
||||||
|
{ type: 'TOKEN_TYPE_USER_RULES', numTokens: 2000 },
|
||||||
|
{ type: 'TOKEN_TYPE_CHAT_MESSAGES', numTokens: 15000 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const liveSum = {
|
||||||
|
annotations: { title: 'Live Undo Session' },
|
||||||
|
stepCount: 3,
|
||||||
|
lastModifiedTime: iso(22),
|
||||||
|
status: 'IDLE',
|
||||||
|
};
|
||||||
|
const h3 = backendHarness({
|
||||||
|
trajectories: { 'conv-live-undo': liveTraj },
|
||||||
|
summaries: { 'conv-live-undo': liveSum },
|
||||||
|
});
|
||||||
|
const beforeUndo = await h3.buildTelemetryPayloadInternal('conv-live-undo');
|
||||||
|
assert.equal(beforeUndo.activeConversation.context.totalTokens, 32300);
|
||||||
|
|
||||||
|
// User clicks Confirm Undo back to step 2 -> step3 and its full gen_metadata[2] are deleted!
|
||||||
|
liveTraj.trajectory.steps = [step1, step2];
|
||||||
|
liveTraj.trajectory.generatorMetadata = liveTraj.trajectory.generatorMetadata.slice(0, 2);
|
||||||
|
liveSum.stepCount = 2;
|
||||||
|
liveSum.lastModifiedTime = iso(30);
|
||||||
|
|
||||||
|
const afterUndo = await h3.buildTelemetryPayloadInternal('conv-live-undo');
|
||||||
|
const ctx3 = afterUndo.activeConversation.context;
|
||||||
|
assert.equal(ctx3.totalTokens, 27500);
|
||||||
|
assert.equal(ctx3.systemPromptTokens, 6000);
|
||||||
|
assert.equal(ctx3.systemToolsTokens, 7000);
|
||||||
|
assert.equal(ctx3.skillsTokens, 1500);
|
||||||
|
assert.equal(ctx3.userRulesTokens, 2000);
|
||||||
|
assert.equal(ctx3.assistantTokens, 2500);
|
||||||
|
assert.equal(ctx3.toolResultsTokens, 5000);
|
||||||
|
assert.equal(ctx3.userInputTokens, 3500);
|
||||||
|
assert.equal(
|
||||||
|
ctx3.userInputTokens +
|
||||||
|
ctx3.assistantTokens +
|
||||||
|
ctx3.toolResultsTokens +
|
||||||
|
ctx3.subagentTokens +
|
||||||
|
ctx3.checkpointTokens +
|
||||||
|
ctx3.systemToolsTokens +
|
||||||
|
ctx3.mcpToolsTokens +
|
||||||
|
ctx3.skillsTokens +
|
||||||
|
ctx3.systemPromptTokens +
|
||||||
|
ctx3.userRulesTokens,
|
||||||
|
27500
|
||||||
|
);
|
||||||
|
|
||||||
|
// Case 4: Cold start on an already-undone session with zero breakdowns and no compaction still populates channels (never all-0)
|
||||||
|
const h4 = backendHarness({
|
||||||
|
trajectories: {
|
||||||
|
'conv-cold-undo': {
|
||||||
|
trajectory: {
|
||||||
|
steps: [step1, step2],
|
||||||
|
generatorMetadata: [
|
||||||
|
{ stepIndices: [1], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 20000, maxContextTokens: 256000 } } } },
|
||||||
|
{ stepIndices: [3], chatModel: { model: 'MODEL_PLACEHOLDER_M37', chatStartMetadata: { contextWindowMetadata: { estimatedTokensUsed: 26000, maxContextTokens: 256000 } } } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
summaries: {
|
||||||
|
'conv-cold-undo': {
|
||||||
|
annotations: { title: 'Cold Undo Session' },
|
||||||
|
stepCount: 2,
|
||||||
|
lastModifiedTime: iso(12),
|
||||||
|
status: 'IDLE',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const coldPayload = await h4.buildTelemetryPayloadInternal('conv-cold-undo');
|
||||||
|
const ctx4 = coldPayload.activeConversation.context;
|
||||||
|
assert.equal(ctx4.totalTokens, 27500);
|
||||||
|
assert.equal(ctx4.assistantTokens, 2500);
|
||||||
|
assert.equal(ctx4.toolResultsTokens, 5000);
|
||||||
|
assert.equal(ctx4.userInputTokens, 20000);
|
||||||
|
assert.equal(ctx4.userInputTokens + ctx4.assistantTokens + ctx4.toolResultsTokens, 27500);
|
||||||
|
});
|
||||||
|
|||||||
@@ -902,6 +902,8 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
};
|
};
|
||||||
let latestBreakdownChat = null;
|
let latestBreakdownChat = null;
|
||||||
let latestBreakdownStepIdx = -1;
|
let latestBreakdownStepIdx = -1;
|
||||||
|
let latestBreakdownUnindexed = false;
|
||||||
|
let lastKnownGmStepIdx = -1;
|
||||||
|
|
||||||
for (const gm of generatorMetadata || []) {
|
for (const gm of generatorMetadata || []) {
|
||||||
collectOrchestratorExecModel(gm?.plannerConfig);
|
collectOrchestratorExecModel(gm?.plannerConfig);
|
||||||
@@ -916,9 +918,13 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
gmMaxIdx = numIdx;
|
gmMaxIdx = numIdx;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if (gmMaxIdx >= 0) {
|
||||||
|
lastKnownGmStepIdx = Math.max(lastKnownGmStepIdx, gmMaxIdx);
|
||||||
|
}
|
||||||
if (extractContextBreakdown(gm.chatModel)) {
|
if (extractContextBreakdown(gm.chatModel)) {
|
||||||
latestBreakdownChat = gm.chatModel;
|
latestBreakdownChat = gm.chatModel;
|
||||||
latestBreakdownStepIdx = gmMaxIdx;
|
latestBreakdownStepIdx = gmMaxIdx >= 0 ? gmMaxIdx : lastKnownGmStepIdx;
|
||||||
|
latestBreakdownUnindexed = gmMaxIdx < 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1401,26 +1407,61 @@ export function extractModelSteps(rawSteps = [], generatorMetadata = []) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 末尾步骤上下文回填:若最后一个非压缩步骤缺少 contextBreakdown,且最近一次有效的 generatorMetadata 未跨过压缩边界,则补齐
|
// 末尾步骤上下文回填:
|
||||||
if (
|
// 1. 末尾为普通步骤且缺少 contextBreakdown 时,只要最近有效 generatorMetadata 未跨过压缩边界即可补齐
|
||||||
result.length > 0 &&
|
// (含回退/中断后末尾 `stepIndices: []` 沿前序位置继承的拆解;若未索引拆解规模显著高于当前步则跳过,避免放大已回退水位);
|
||||||
!result[result.length - 1].isCompactionStep &&
|
// 2. 末尾为压缩步骤且其前序压缩前锚点步骤缺少 contextBreakdown(常见于末尾 `stepIndices: []`)时,回填到该压缩前步骤,
|
||||||
!result[result.length - 1].contextBreakdown &&
|
// 确保压缩后仍可继承 5 个静态上下文通道(绝不直接写到压缩步自身)。
|
||||||
latestBreakdownChat &&
|
if (result.length > 0 && latestBreakdownChat) {
|
||||||
(lastCompactionStepIdx < 0 || latestBreakdownStepIdx > lastCompactionStepIdx)
|
const applyFallbackBreakdown = (targetStep) => {
|
||||||
) {
|
|
||||||
const lastStep = result[result.length - 1];
|
|
||||||
const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat);
|
const fallbackBreakdown = extractContextBreakdown(latestBreakdownChat);
|
||||||
|
if (!fallbackBreakdown) return;
|
||||||
|
const targetPrompt =
|
||||||
|
Number(targetStep?.inputTokens || 0) + Number(targetStep?.cacheReadTokens || 0);
|
||||||
|
const bdTotal = Number(fallbackBreakdown.totalTokens || 0);
|
||||||
|
if (
|
||||||
|
latestBreakdownUnindexed &&
|
||||||
|
targetPrompt > 0 &&
|
||||||
|
bdTotal > 0 &&
|
||||||
|
targetPrompt < bdTotal * 0.5
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
const fallbackCtx =
|
const fallbackCtx =
|
||||||
latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata;
|
latestBreakdownChat?.chatStartMetadata?.contextWindowMetadata;
|
||||||
lastStep.contextBreakdown = fallbackBreakdown;
|
targetStep.contextBreakdown = fallbackBreakdown;
|
||||||
if (!lastStep.estimatedContextTokens) {
|
if (!targetStep.estimatedContextTokens) {
|
||||||
lastStep.estimatedContextTokens = Number(
|
targetStep.estimatedContextTokens = Number(
|
||||||
fallbackCtx?.estimatedTokensUsed || fallbackBreakdown?.totalTokens || 0
|
fallbackCtx?.estimatedTokensUsed || fallbackBreakdown?.totalTokens || 0
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if (fallbackCtx?.maxContextTokens) {
|
if (fallbackCtx?.maxContextTokens) {
|
||||||
lastStep.maxContextBudgetTokens = Number(fallbackCtx.maxContextTokens);
|
targetStep.maxContextBudgetTokens = Number(fallbackCtx.maxContextTokens);
|
||||||
|
if (!targetStep.reportedContextLimitTokens) {
|
||||||
|
targetStep.reportedContextLimitTokens = Number(fallbackCtx.maxContextTokens);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const lastStep = result[result.length - 1];
|
||||||
|
if (
|
||||||
|
!lastStep.isCompactionStep &&
|
||||||
|
!lastStep.contextBreakdown &&
|
||||||
|
(lastCompactionStepIdx < 0 || latestBreakdownStepIdx > lastCompactionStepIdx)
|
||||||
|
) {
|
||||||
|
applyFallbackBreakdown(lastStep);
|
||||||
|
} else if (
|
||||||
|
lastStep.isCompactionStep &&
|
||||||
|
(latestBreakdownStepIdx < 0 || latestBreakdownStepIdx <= lastCompactionStepIdx)
|
||||||
|
) {
|
||||||
|
for (let i = result.length - 2; i >= 0; i -= 1) {
|
||||||
|
const preStep = result[i];
|
||||||
|
if (!preStep || preStep.isCompactionStep) break;
|
||||||
|
if (!preStep.contextBreakdown) {
|
||||||
|
applyFallbackBreakdown(preStep);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user