mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-27 01:19:25 +08:00
fix(panel): preserve post-compaction context breakdown, fit 100% capsule slot, and align compact badge accent
This commit is contained in:
@@ -1943,19 +1943,17 @@ export function readLocalSqliteTrajectory(dbFilePath, options = {}) {
|
||||
}
|
||||
|
||||
if (ownGenRecords.length > 0) {
|
||||
const lastRec = ownGenRecords[ownGenRecords.length - 1];
|
||||
// 从末尾向前定位最近一条包含完整上下文拆解(tokenBreakdown / promptSections / tools / messagePrompts)的记录,
|
||||
// 避免末尾紧跟 CHECKPOINT 压缩步或多条纯 plannerConfig 记录时漏解压缩前的静态上下文构成。
|
||||
for (let i = ownGenRecords.length - 1; i >= 0; i--) {
|
||||
const rec = ownGenRecords[i];
|
||||
try {
|
||||
const fullLast = decodeProtoGeneratorMeta(lastRec.rawData, true);
|
||||
if (fullLast) lastRec.gm = fullLast;
|
||||
} catch {
|
||||
// 保留轻量版本
|
||||
const fullDecoded = decodeProtoGeneratorMeta(rec.rawData, true);
|
||||
if (fullDecoded) {
|
||||
rec.gm = fullDecoded;
|
||||
if (hasContextBreakdownPayload(fullDecoded.chatModel)) {
|
||||
break;
|
||||
}
|
||||
if (!hasContextBreakdownPayload(lastRec.gm?.chatModel) && ownGenRecords.length >= 2) {
|
||||
const prevRec = ownGenRecords[ownGenRecords.length - 2];
|
||||
try {
|
||||
const fullPrev = decodeProtoGeneratorMeta(prevRec.rawData, true);
|
||||
if (fullPrev && hasContextBreakdownPayload(fullPrev.chatModel)) {
|
||||
prevRec.gm = fullPrev;
|
||||
}
|
||||
} catch {
|
||||
// 保留轻量版本
|
||||
|
||||
@@ -1688,7 +1688,7 @@ export async function enumerateAndSyncConversations({
|
||||
contextLimitTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
contextGroupsTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
steps,
|
||||
subagentRefs,
|
||||
};
|
||||
@@ -1789,7 +1789,7 @@ export async function enumerateAndSyncConversations({
|
||||
contextLimitTelemetry: true,
|
||||
speedClearedTelemetry: true,
|
||||
turnRailTelemetry: true,
|
||||
contextGroupsTelemetry: true,
|
||||
contextGroupsTelemetry: 2,
|
||||
steps: offlineFallback.steps,
|
||||
subagentRefs: offlineFallback.subagentRefs,
|
||||
};
|
||||
@@ -1874,8 +1874,12 @@ export async function enumerateAndSyncConversations({
|
||||
return !Object.prototype.hasOwnProperty.call(lastCachedStep, 'turnIndex');
|
||||
}
|
||||
function hasDroppedContextGroups(cached) {
|
||||
if (cached?.contextGroupsTelemetry) return false;
|
||||
if (cached?.contextGroupsTelemetry === 2) return false;
|
||||
const steps = cached?.steps || [];
|
||||
if (steps.some((st) => st?.isCompactionStep)) {
|
||||
return true;
|
||||
}
|
||||
if (cached?.contextGroupsTelemetry) return false;
|
||||
for (let i = steps.length - 1; i >= 0; i--) {
|
||||
const st = steps[i];
|
||||
if (!st || st.isCompactionStep) break;
|
||||
|
||||
@@ -313,13 +313,53 @@ function scaleBucketsExact(buckets, keys, targetTotal) {
|
||||
return out;
|
||||
}
|
||||
|
||||
function extractRawBreakdownChannels(breakdown) {
|
||||
const rawMessages = Number(breakdown?.messagesTokens || 0);
|
||||
const hasGranularMsgBreakdown =
|
||||
Boolean(breakdown) &&
|
||||
Object.prototype.hasOwnProperty.call(breakdown, 'toolResultsTokens');
|
||||
const channels = {
|
||||
userInput: hasGranularMsgBreakdown
|
||||
? Number(breakdown?.userInputTokens || 0)
|
||||
: rawMessages,
|
||||
assistant: Number(breakdown?.assistantTokens || 0),
|
||||
toolResults: Number(breakdown?.toolResultsTokens || 0),
|
||||
subagent: Number(breakdown?.subagentTokens || 0),
|
||||
checkpoint: Number(breakdown?.checkpointTokens || 0),
|
||||
systemTools: Number(breakdown?.systemToolsTokens || 0),
|
||||
mcpTools: Number(breakdown?.mcpToolsTokens || 0),
|
||||
skills: Number(breakdown?.skillsTokens || 0),
|
||||
systemPrompt: Number(breakdown?.systemPromptTokens || 0),
|
||||
userRules: Number(breakdown?.userRulesTokens || 0),
|
||||
};
|
||||
const msgSubtotal =
|
||||
channels.userInput +
|
||||
channels.assistant +
|
||||
channels.toolResults +
|
||||
channels.subagent +
|
||||
channels.checkpoint;
|
||||
if (rawMessages > msgSubtotal) {
|
||||
channels.userInput += rawMessages - msgSubtotal;
|
||||
}
|
||||
return channels;
|
||||
}
|
||||
|
||||
function resolveCompactionSummaryTokens(compactionStep) {
|
||||
const respTok = Number(compactionStep?.responseTokens || 0);
|
||||
if (respTok > 0) return respTok;
|
||||
return resolveStepOutputTokens(compactionStep);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从当前活跃会话的最新步骤提取上下文 10 通道拆解、自动压缩水位与缓存命中率。
|
||||
*
|
||||
* `chatStartMetadata.contextWindowMetadata` 记录在步骤请求发送前且基于宿主离线估算器:
|
||||
* 1. 先按该步模型 API 真实计费输入(`inputTokens + cacheReadTokens`)对请求前 10 通道做等比整数对齐,消除离线估算偏差;
|
||||
* 2. 再将该步自身新生成的输出(`outputTokens`)补入 `assistantTokens`,并滚动推进后续无独立拆解的步骤,
|
||||
* 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致。
|
||||
* 使上下文窗口总占用与调用明细表的单步 `contextTokens` 严格一致;
|
||||
* 3. 当末尾或最近边界为上下文压缩步骤(`isCompactionStep`)且压缩后尚未产生新的 `contextBreakdown` 时,
|
||||
* 继承压缩前最近一次拆解中的 5 个会话静态通道(`systemPrompt` / `systemTools` / `mcpTools` / `skills` / `userRules`),
|
||||
* 清空已被折叠的历史对话通道,并将压缩步生成的摘要正文计入 `checkpointTokens`,避免误把压缩前全量输入当作压缩后水位。
|
||||
*
|
||||
* @param {object[]} enrichedActiveSteps
|
||||
* @param {object|null} latestEnriched
|
||||
@@ -332,55 +372,30 @@ function extractActiveContextTelemetry(
|
||||
sessionInputTokens,
|
||||
sessionCacheReadTokens
|
||||
) {
|
||||
let latestBreakdown = latestEnriched?.contextBreakdown || null;
|
||||
let breakdownIdx = latestBreakdown ? enrichedActiveSteps.length - 1 : -1;
|
||||
if (!latestBreakdown && !latestEnriched?.isCompactionStep) {
|
||||
let lastCompactionIdx = -1;
|
||||
for (let i = enrichedActiveSteps.length - 1; i >= 0; i--) {
|
||||
if (enrichedActiveSteps[i]?.isCompactionStep) {
|
||||
lastCompactionIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let latestBreakdown = null;
|
||||
let breakdownIdx = -1;
|
||||
for (let i = enrichedActiveSteps.length - 1; i > lastCompactionIdx; i--) {
|
||||
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
||||
latestBreakdown = enrichedActiveSteps[i].contextBreakdown;
|
||||
breakdownIdx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
const rawMessages = Number(latestBreakdown?.messagesTokens || 0);
|
||||
const hasGranularMsgBreakdown =
|
||||
Boolean(latestBreakdown) &&
|
||||
Object.prototype.hasOwnProperty.call(latestBreakdown, 'toolResultsTokens');
|
||||
let channels = {
|
||||
userInput: hasGranularMsgBreakdown
|
||||
? Number(latestBreakdown?.userInputTokens || 0)
|
||||
: rawMessages,
|
||||
assistant: Number(latestBreakdown?.assistantTokens || 0),
|
||||
toolResults: Number(latestBreakdown?.toolResultsTokens || 0),
|
||||
subagent: Number(latestBreakdown?.subagentTokens || 0),
|
||||
checkpoint: Number(latestBreakdown?.checkpointTokens || 0),
|
||||
systemTools: Number(latestBreakdown?.systemToolsTokens || 0),
|
||||
mcpTools: Number(latestBreakdown?.mcpToolsTokens || 0),
|
||||
skills: Number(latestBreakdown?.skillsTokens || 0),
|
||||
systemPrompt: Number(latestBreakdown?.systemPromptTokens || 0),
|
||||
userRules: Number(latestBreakdown?.userRulesTokens || 0),
|
||||
};
|
||||
const msgSubtotal =
|
||||
channels.userInput +
|
||||
channels.assistant +
|
||||
channels.toolResults +
|
||||
channels.subagent +
|
||||
channels.checkpoint;
|
||||
if (rawMessages > msgSubtotal) {
|
||||
channels.userInput += rawMessages - msgSubtotal;
|
||||
}
|
||||
const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
|
||||
|
||||
if (
|
||||
latestBreakdown &&
|
||||
breakdownIdx >= 0 &&
|
||||
!latestEnriched?.isCompactionStep &&
|
||||
rawBreakdownTotal > 0
|
||||
) {
|
||||
let channels = extractRawBreakdownChannels(latestBreakdown);
|
||||
let fallbackPreCompactionLimit = 0;
|
||||
|
||||
if (latestBreakdown && breakdownIdx > lastCompactionIdx) {
|
||||
const rawBreakdownTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
|
||||
if (rawBreakdownTotal > 0) {
|
||||
const bdStep = enrichedActiveSteps[breakdownIdx];
|
||||
const bdPromptTokens =
|
||||
Number(bdStep?.inputTokens || 0) + Number(bdStep?.cacheReadTokens || 0);
|
||||
@@ -414,6 +429,59 @@ function extractActiveContextTelemetry(
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (lastCompactionIdx >= 0) {
|
||||
const compactionStep = enrichedActiveSteps[lastCompactionIdx];
|
||||
let preStep = null;
|
||||
for (let i = lastCompactionIdx - 1; i >= 0; i--) {
|
||||
if (enrichedActiveSteps[i]?.contextBreakdown) {
|
||||
preStep = enrichedActiveSteps[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (preStep) {
|
||||
fallbackPreCompactionLimit = Number(preStep.maxContextBudgetTokens || 0);
|
||||
let preChannels = extractRawBreakdownChannels(preStep.contextBreakdown);
|
||||
const preRawTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + preChannels[k], 0);
|
||||
const prePromptTokens =
|
||||
Number(preStep.inputTokens || 0) + Number(preStep.cacheReadTokens || 0);
|
||||
if (preRawTotal > 0 && prePromptTokens >= preRawTotal * 0.5) {
|
||||
preChannels = scaleBucketsExact(preChannels, CONTEXT_CHANNEL_KEYS, prePromptTokens);
|
||||
}
|
||||
channels.systemTools = preChannels.systemTools;
|
||||
channels.mcpTools = preChannels.mcpTools;
|
||||
channels.skills = preChannels.skills;
|
||||
channels.systemPrompt = preChannels.systemPrompt;
|
||||
channels.userRules = preChannels.userRules;
|
||||
}
|
||||
channels.userInput = 0;
|
||||
channels.assistant = 0;
|
||||
channels.toolResults = 0;
|
||||
channels.subagent = 0;
|
||||
channels.checkpoint = resolveCompactionSummaryTokens(compactionStep);
|
||||
|
||||
let runningTotal = CONTEXT_CHANNEL_KEYS.reduce((sum, k) => sum + channels[k], 0);
|
||||
for (let m = lastCompactionIdx + 1; 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 (mPrompt > 0 && (runningTotal === 0 || mPrompt >= runningTotal * 0.35)) {
|
||||
if (mPrompt > runningTotal) {
|
||||
const delta = mPrompt - runningTotal;
|
||||
if (m > lastCompactionIdx + 1 && 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ctxUserInput = channels.userInput;
|
||||
const ctxAssistant = channels.assistant;
|
||||
@@ -430,17 +498,25 @@ function extractActiveContextTelemetry(
|
||||
const ctxBreakdownTotal =
|
||||
ctxMessages + ctxSystemTools + ctxMcpTools + ctxSkills + ctxSystemPrompt + ctxUserRules;
|
||||
|
||||
const isLatestCompaction = Boolean(latestEnriched?.isCompactionStep);
|
||||
const ctxCached = latestEnriched?.cacheReadTokens || 0;
|
||||
const ctxFreshInput = latestEnriched?.inputTokens || 0;
|
||||
const ctxThinking = latestEnriched?.thinkingTokens || 0;
|
||||
const ctxResponse = latestEnriched?.responseTokens || 0;
|
||||
const ctxOut = resolveStepOutputTokens(latestEnriched);
|
||||
const ctxTotal =
|
||||
ctxBreakdownTotal > 0 ? ctxBreakdownTotal : ctxCached + ctxFreshInput + ctxOut;
|
||||
const compactionLimitTokens = Number(latestEnriched?.maxContextBudgetTokens || 256000);
|
||||
const compactionUsedTokens = Number(
|
||||
ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput
|
||||
const ctxTotal = isLatestCompaction
|
||||
? ctxBreakdownTotal
|
||||
: ctxBreakdownTotal > 0
|
||||
? ctxBreakdownTotal
|
||||
: ctxCached + ctxFreshInput + ctxOut;
|
||||
const compactionLimitTokens = Number(
|
||||
(isLatestCompaction && !latestEnriched?.reportedContextLimitTokens && fallbackPreCompactionLimit > 0
|
||||
? fallbackPreCompactionLimit
|
||||
: latestEnriched?.maxContextBudgetTokens) || 256000
|
||||
);
|
||||
const compactionUsedTokens = isLatestCompaction
|
||||
? Number(ctxTotal)
|
||||
: Number(ctxTotal || latestEnriched?.estimatedContextTokens || ctxCached + ctxFreshInput);
|
||||
const compactionUsedPct =
|
||||
compactionLimitTokens > 0
|
||||
? Math.min(100, +((compactionUsedTokens / compactionLimitTokens) * 100).toFixed(1))
|
||||
@@ -1268,34 +1344,8 @@ export async function buildTelemetryPayloadInternal(
|
||||
|
||||
let contextUsedPct = null;
|
||||
if (lastRootStep) {
|
||||
const limitTokens = Number(lastRootStep.maxContextBudgetTokens || 256000);
|
||||
const cb = lastRootStep.contextBreakdown;
|
||||
const cbTotal = cb
|
||||
? Number(cb.messagesTokens || 0) +
|
||||
Number(cb.systemToolsTokens || 0) +
|
||||
Number(cb.mcpToolsTokens || 0) +
|
||||
Number(cb.skillsTokens || 0) +
|
||||
Number(cb.systemPromptTokens || 0) +
|
||||
Number(cb.userRulesTokens || 0)
|
||||
: 0;
|
||||
const apiPrompt =
|
||||
Number(lastRootStep.inputTokens || 0) + Number(lastRootStep.cacheReadTokens || 0);
|
||||
const apiOut = resolveStepOutputTokens(lastRootStep);
|
||||
const fallbackTotal = apiPrompt + apiOut;
|
||||
const estTotal = Math.max(cbTotal, Number(lastRootStep.estimatedContextTokens || 0));
|
||||
const hasAlignedApiPrompt =
|
||||
!lastRootStep.isCompactionStep &&
|
||||
apiPrompt > 0 &&
|
||||
(estTotal === 0 || apiPrompt >= estTotal * 0.5);
|
||||
const usedTokens = Number(
|
||||
hasAlignedApiPrompt
|
||||
? fallbackTotal
|
||||
: cbTotal > 0
|
||||
? cbTotal
|
||||
: lastRootStep.estimatedContextTokens || fallbackTotal
|
||||
);
|
||||
contextUsedPct =
|
||||
limitTokens > 0 ? Math.min(100, +((usedTokens / limitTokens) * 100).toFixed(1)) : 0;
|
||||
contextUsedPct = extractActiveContextTelemetry(rootSteps, lastRootStep, 0, 0).context
|
||||
.compactionUsedPct;
|
||||
}
|
||||
|
||||
let modelShort = '';
|
||||
|
||||
@@ -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=1794921701656">
|
||||
<link rel="stylesheet" href="/styles.css?v=1794972561672">
|
||||
<script src="/preload.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app-root"></div>
|
||||
<script src="/app.js?v=1794921701656"></script>
|
||||
<script src="/app.js?v=1794972561672"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -232,11 +232,11 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */
|
||||
/* 环形上下文指示器(固定预占宽度 58px:14px 环 + 5px 间距 + 完整容纳四字符 100%) */
|
||||
.wm-ctx-seg {
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
width: 50px;
|
||||
width: 58px;
|
||||
}
|
||||
|
||||
.wm-ring-svg {
|
||||
@@ -271,8 +271,10 @@
|
||||
}
|
||||
|
||||
.wm-ctx-pct {
|
||||
min-width: 27px;
|
||||
max-width: 31px;
|
||||
min-width: 28px;
|
||||
max-width: none;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
|
||||
@@ -95,7 +95,7 @@
|
||||
.step-model-compact {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--metric-info, var(--accent-primary));
|
||||
color: var(--accent-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
|
||||
@@ -2670,7 +2670,7 @@ html[data-standalone="true"] .app-shell {
|
||||
.step-model-compact {
|
||||
flex-shrink: 0;
|
||||
white-space: nowrap;
|
||||
color: var(--metric-info, var(--accent-primary));
|
||||
color: var(--accent-primary);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
@@ -4381,11 +4381,11 @@ html[data-standalone="true"] .app-shell {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* 环形上下文指示器(固定预占宽度 50px:14px 环 + 5px 间距 + 31px 百分比槽位) */
|
||||
/* 环形上下文指示器(固定预占宽度 58px:14px 环 + 5px 间距 + 完整容纳四字符 100%) */
|
||||
.wm-ctx-seg {
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
width: 50px;
|
||||
width: 58px;
|
||||
}
|
||||
|
||||
.wm-ring-svg {
|
||||
@@ -4420,8 +4420,10 @@ html[data-standalone="true"] .app-shell {
|
||||
}
|
||||
|
||||
.wm-ctx-pct {
|
||||
min-width: 27px;
|
||||
max-width: 31px;
|
||||
min-width: 28px;
|
||||
max-width: none;
|
||||
overflow: visible;
|
||||
text-overflow: clip;
|
||||
text-align: left;
|
||||
font-weight: 500;
|
||||
color: var(--text-primary);
|
||||
|
||||
@@ -429,7 +429,7 @@ test('BUG-20 & BUG-24: reactive store microtask deduplication, stripModuleSyntax
|
||||
|
||||
test('bundle validation rejects incompatible imports and duplicate bindings before touching output', (t) => {
|
||||
const tempDir = fs.mkdtempSync(fileURLToPath(new URL('./.bundle-test-', import.meta.url)));
|
||||
t.after(() => fs.rmSync(tempDir, { recursive: true, force: true }));
|
||||
t.after(() => fs.rmSync(tempDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
||||
for (const dir of ['src', 'shared']) {
|
||||
fs.cpSync(new URL(`../${dir}/`, import.meta.url), join(tempDir, dir), { recursive: true });
|
||||
}
|
||||
@@ -650,3 +650,169 @@ test('panel typography scales all view/table/chart CSS rules via --fs-* tokens w
|
||||
assert.equal(rawArtifact.includes('\r\n'), false, `${artifact} must normalize line endings to LF`);
|
||||
}
|
||||
});
|
||||
|
||||
test('post-compaction context preserves static channels + checkpoint summary, capsule fits 100% without ellipsis, and .step-model-compact follows --accent-primary', async () => {
|
||||
const convId = '99999999-8888-4777-8666-555555555555';
|
||||
const preStep = {
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: '2026-11-18T03:00:00Z',
|
||||
finishedGeneratingAt: '2026-11-18T03:00:05Z',
|
||||
sourceTrajectoryStepInfo: { stepIndex: 10 },
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M429',
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '5400',
|
||||
cacheReadTokens: '270000',
|
||||
outputTokens: '1200',
|
||||
},
|
||||
},
|
||||
};
|
||||
const checkpointStep = {
|
||||
type: 'CORTEX_STEP_TYPE_CHECKPOINT',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: '2026-11-18T03:01:00Z',
|
||||
finishedGeneratingAt: '2026-11-18T03:01:06Z',
|
||||
sourceTrajectoryStepInfo: { stepIndex: 12 },
|
||||
modelUsage: {
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '5400',
|
||||
cacheReadTokens: '270000',
|
||||
outputTokens: '3800',
|
||||
thinkingOutputTokens: '800',
|
||||
responseOutputTokens: '3000',
|
||||
},
|
||||
},
|
||||
};
|
||||
const preGeneratorMetadata = [
|
||||
{
|
||||
stepIndices: [10],
|
||||
chatModel: {
|
||||
responseModel: 'gemini-4-carbon-high',
|
||||
modelDisplayName: 'Gemini 4 Carbon (High)',
|
||||
chatStartMetadata: {
|
||||
contextWindowMetadata: {
|
||||
estimatedTokensUsed: 275_400,
|
||||
maxContextTokens: 384_000,
|
||||
tokenBreakdown: {
|
||||
groups: [
|
||||
{
|
||||
type: 'TOKEN_TYPE_SYSTEM_PROMPT',
|
||||
numTokens: 16_000,
|
||||
children: [
|
||||
{ name: 'identity', numTokens: 10_000 },
|
||||
{ name: 'skills', numTokens: 4_000 },
|
||||
{ name: 'user_rules', numTokens: 2_000 },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'TOKEN_TYPE_TOOLS',
|
||||
numTokens: 10_000,
|
||||
children: [
|
||||
{ name: 'run_command', numTokens: 8_000 },
|
||||
{ name: 'mcp_gradio_predict', numTokens: 2_000 },
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'TOKEN_TYPE_CHAT_MESSAGES',
|
||||
numTokens: 249_400,
|
||||
children: [
|
||||
{ name: '1: USER_INPUT', numTokens: 49_400 },
|
||||
{ name: '2: PLANNER_RESPONSE', numTokens: 80_000 },
|
||||
{ name: '3: GENERIC', numTokens: 120_000 },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const h = backendHarness({
|
||||
clock: () => Date.parse('2026-11-18T03:02:00Z'),
|
||||
summaries: {
|
||||
[convId]: {
|
||||
summary: 'Compaction test',
|
||||
stepCount: 2,
|
||||
status: 'CASCADE_RUN_STATUS_IDLE',
|
||||
lastModifiedTime: '2026-11-18T03:01:06Z',
|
||||
},
|
||||
},
|
||||
trajectories: {
|
||||
[convId]: {
|
||||
numTotalSteps: 2,
|
||||
trajectory: {
|
||||
steps: [preStep, checkpointStep],
|
||||
generatorMetadata: preGeneratorMetadata,
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const payload = await h.buildTelemetryPayloadInternal(convId);
|
||||
const ctx = payload.activeConversation.context;
|
||||
|
||||
// Static channels must survive compaction while old chat history resets and checkpoint summary is recorded
|
||||
assert.equal(ctx.systemPromptTokens, 10_000);
|
||||
assert.equal(ctx.skillsTokens, 4_000);
|
||||
assert.equal(ctx.userRulesTokens, 2_000);
|
||||
assert.equal(ctx.systemToolsTokens, 8_000);
|
||||
assert.equal(ctx.mcpToolsTokens, 2_000);
|
||||
assert.equal(ctx.checkpointTokens, 3_000, 'checkpoint summary uses responseTokens excluding thinkingTokens');
|
||||
assert.equal(ctx.userInputTokens, 0);
|
||||
assert.equal(ctx.assistantTokens, 0);
|
||||
assert.equal(ctx.toolResultsTokens, 0);
|
||||
assert.equal(ctx.subagentTokens, 0);
|
||||
assert.equal(ctx.totalTokens, 29_000, 'must not leak 275.4k pre-compaction input into post-compaction total');
|
||||
assert.equal(ctx.compactionLimitTokens, 384_000, 'inherits 384k custom context budget across compaction step');
|
||||
assert.equal(ctx.usedPct, 7.6);
|
||||
assert.equal(payload.conversations[0].contextUsedPct, 7.6, 'Multi-Session quick stats must also reflect post-compaction %');
|
||||
|
||||
// Subsequent lightweight step without its own tokenBreakdown rolls forward cleanly on top of compacted baseline
|
||||
h.state.summaries[convId].stepCount = 3;
|
||||
h.state.summaries[convId].lastModifiedTime = '2026-11-18T03:02:10Z';
|
||||
h.state.trajectories[convId] = {
|
||||
numTotalSteps: 3,
|
||||
trajectory: {
|
||||
steps: [
|
||||
preStep,
|
||||
checkpointStep,
|
||||
{
|
||||
type: 'CORTEX_STEP_TYPE_PLANNER_RESPONSE',
|
||||
status: 'CORTEX_STEP_STATUS_DONE',
|
||||
metadata: {
|
||||
createdAt: '2026-11-18T03:02:05Z',
|
||||
finishedGeneratingAt: '2026-11-18T03:02:10Z',
|
||||
sourceTrajectoryStepInfo: { stepIndex: 14 },
|
||||
modelUsage: {
|
||||
model: 'MODEL_PLACEHOLDER_M429',
|
||||
apiProvider: 'API_PROVIDER_GOOGLE_GEMINI',
|
||||
inputTokens: '1500',
|
||||
cacheReadTokens: '29000',
|
||||
outputTokens: '600',
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
generatorMetadata: preGeneratorMetadata,
|
||||
},
|
||||
};
|
||||
const payloadFollowup = await h.buildTelemetryPayloadInternal(convId, true);
|
||||
const ctx2 = payloadFollowup.activeConversation.context;
|
||||
assert.equal(ctx2.systemPromptTokens, 10_000);
|
||||
assert.equal(ctx2.checkpointTokens, 3_000);
|
||||
assert.equal(ctx2.userInputTokens, 1_500);
|
||||
assert.equal(ctx2.assistantTokens, 600);
|
||||
assert.equal(ctx2.totalTokens, 31_100);
|
||||
|
||||
// Verify capsule 100% slot CSS and non-hardcoded compaction suffix color
|
||||
const stylesCss = fs.readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
|
||||
assert.match(stylesCss, /\.wm-ctx-seg\s*\{[^}]*width:\s*58px;/);
|
||||
assert.match(stylesCss, /\.wm-ctx-pct\s*\{[^}]*max-width:\s*none;[^}]*overflow:\s*visible;[^}]*text-overflow:\s*clip;/s);
|
||||
assert.match(stylesCss, /\.step-model-compact\s*\{[^}]*color:\s*var\(--accent-primary\);/);
|
||||
assert.doesNotMatch(stylesCss, /\.step-model-compact\s*\{[^}]*--metric-info/);
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import { promisify } from 'node:util';
|
||||
import { mkdtempSync, mkdirSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { readLocalSqliteTrajectory } from '../backend/cli-sqlite-reader.mjs';
|
||||
import { backendHarness } from './backend-harness.mjs';
|
||||
import { i18nStore } from '../src/i18n/index.js';
|
||||
import {
|
||||
@@ -708,3 +709,80 @@ test('persistTrajectoryCacheIfNeeded throttles RUNNING disk writes to 30s and fl
|
||||
assert.equal(h.listCachedTrajectoryEntries().length, 0);
|
||||
assert.deepEqual(h.state.saves.at(-1).data, {});
|
||||
});
|
||||
|
||||
test('SQLite trajectory reader scans backwards past trailing plannerConfig-only gen_metadata rows to preserve pre-compaction tokenBreakdown', (t) => {
|
||||
const sqliteMod =
|
||||
typeof process.getBuiltinModule === 'function' ? process.getBuiltinModule('node:sqlite') : null;
|
||||
if (!sqliteMod?.DatabaseSync) {
|
||||
t.skip('node:sqlite DatabaseSync unavailable');
|
||||
return;
|
||||
}
|
||||
const { DatabaseSync } = sqliteMod;
|
||||
const tempRoot = mkdtempSync(join(tmpdir(), 'agy-sqlite-compact-'));
|
||||
t.after(() => rmSync(tempRoot, { recursive: true, force: true, maxRetries: 3, retryDelay: 50 }));
|
||||
|
||||
const cid = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
||||
const dbPath = join(tempRoot, `${cid}.db`);
|
||||
const db = new DatabaseSync(dbPath);
|
||||
db.exec(`
|
||||
CREATE TABLE trajectory_meta (trajectory_id TEXT, cascade_id TEXT, trajectory_type INTEGER, source INTEGER);
|
||||
CREATE TABLE steps (idx INTEGER PRIMARY KEY, step_type INTEGER, status INTEGER, metadata BLOB, step_payload BLOB);
|
||||
CREATE TABLE gen_metadata (idx INTEGER PRIMARY KEY, data BLOB);
|
||||
`);
|
||||
db.prepare('INSERT INTO trajectory_meta VALUES (?, ?, 1, 1)').run(cid, cid);
|
||||
db.prepare('INSERT INTO steps VALUES (0, 15, 3, ?, NULL)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: 1794960010,
|
||||
finishedSec: 1794960014,
|
||||
stepIndex: 0,
|
||||
originCascadeId: cid,
|
||||
modelEnumInt: 1429,
|
||||
inputTokens: 10000,
|
||||
cacheReadTokens: 110000,
|
||||
outputTokens: 500,
|
||||
})
|
||||
);
|
||||
// Step 1: CHECKPOINT compaction step (step_type = 23)
|
||||
db.prepare('INSERT INTO steps VALUES (1, 23, 3, ?, NULL)').run(
|
||||
encodeStepMeta({
|
||||
createdSec: 1794960020,
|
||||
finishedSec: 1794960024,
|
||||
stepIndex: 1,
|
||||
originCascadeId: cid,
|
||||
modelEnumInt: 1429,
|
||||
inputTokens: 10000,
|
||||
cacheReadTokens: 110000,
|
||||
outputTokens: 2400,
|
||||
thinkingTokens: 400,
|
||||
responseTokens: 2000,
|
||||
})
|
||||
);
|
||||
|
||||
// gen_metadata[0] has the full tokenBreakdown, followed by 3 plannerConfig-only records [1..3]
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (0, ?)').run(
|
||||
encodeGenMeta({
|
||||
stepIndex: 0,
|
||||
cascadeId: cid,
|
||||
responseModel: 'gemini-4-carbon-high',
|
||||
modelDisplayName: 'Gemini 4 Carbon (High)',
|
||||
estimatedTokensUsed: 120_000,
|
||||
maxContextTokens: 384_000,
|
||||
userMsgTokens: 120_000,
|
||||
})
|
||||
);
|
||||
const plannerOnlyBlob = encodeFieldBytes(3, encodeFieldBytes(28, 'gemini-4-carbon-high'));
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (1, ?)').run(plannerOnlyBlob);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (2, ?)').run(plannerOnlyBlob);
|
||||
db.prepare('INSERT INTO gen_metadata VALUES (3, ?)').run(plannerOnlyBlob);
|
||||
db.close();
|
||||
|
||||
const res = readLocalSqliteTrajectory(dbPath, { cascadeId: cid });
|
||||
assert.ok(res);
|
||||
assert.equal(res.steps.length, 2);
|
||||
assert.equal(res.steps[1].type, 'CORTEX_STEP_TYPE_CHECKPOINT');
|
||||
const gm0 = res.generatorMetadata.find((g) => g.stepIndices.includes(0));
|
||||
assert.ok(
|
||||
gm0?.chatModel?.chatStartMetadata?.contextWindowMetadata?.tokenBreakdown?.groups?.length > 0,
|
||||
'must decode tokenBreakdown on gen_metadata[0] even with 3 trailing plannerConfig-only records'
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1046,12 +1046,17 @@ export function inferCompactionStepModels(steps) {
|
||||
step.responseModel || (donorSameModel ? donor.responseModel || '' : '');
|
||||
const nextDisplayName =
|
||||
step.modelDisplayName || (donorSameModel ? donor.modelDisplayName || '' : '');
|
||||
const nextMaxBudget =
|
||||
!step.reportedContextLimitTokens && donor.maxContextBudgetTokens > 0
|
||||
? donor.maxContextBudgetTokens
|
||||
: step.maxContextBudgetTokens;
|
||||
|
||||
if (
|
||||
nextModelKey === step.modelKey &&
|
||||
nextModelSource === step.modelSource &&
|
||||
nextResponseModel === (step.responseModel || '') &&
|
||||
nextDisplayName === (step.modelDisplayName || '')
|
||||
nextDisplayName === (step.modelDisplayName || '') &&
|
||||
nextMaxBudget === step.maxContextBudgetTokens
|
||||
) {
|
||||
return step;
|
||||
}
|
||||
@@ -1062,6 +1067,7 @@ export function inferCompactionStepModels(steps) {
|
||||
modelSource: nextModelSource,
|
||||
responseModel: nextResponseModel,
|
||||
modelDisplayName: nextDisplayName,
|
||||
maxContextBudgetTokens: nextMaxBudget,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user