From 49e62d4baef0a489d9263caf822652934ad08bfe Mon Sep 17 00:00:00 2001 From: Helmi Pradita Date: Thu, 19 Nov 2026 15:13:47 +0700 Subject: [PATCH 1/5] fix(client-runtime): prefer newer completed compaction over stale liveUsage When a conversation is compacted, the context window meter previously remained stuck on stale token counts from earlier turns because liveUsage and providerThread.contextUsage were evaluated before compaction items. Completed compactions newer than the turn usage report now take precedence, and OpenCode 2 clears stale thread contextUsage upon compaction. Prepared with ag/gemini-3.8-flash-high through Antigravity harness. --- apps/web/src/lib/contextWindow.test.ts | 66 ++++++++++++++++++ .../client-runtime/src/state/contextWindow.ts | 69 +++++++++++++++++++ .../src/server/v2/adapter.ts | 8 +++ 3 files changed, 143 insertions(+) diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index 91cdf18682e2a..0577939592c58 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -70,6 +70,72 @@ describe("V2 context window presentation", () => { ?.usedTokens, ).toBe(2_000); }); + + it("prefers a newer completed compaction over older liveUsage", () => { + const olderLiveUsage = decodeTokenUsage({ + usedTokens: 985_000, + maxTokens: 1_000_000, + updatedAt: "2026-11-19T02:00:00.000Z", + }); + const newerCompaction = { + item: { + id: "compaction-1" as never, + threadId: "thread-1" as never, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed" as const, + title: "Context compacted", + startedAt: null, + completedAt: null, + updatedAt: DateTime.makeUnsafe("2026-11-19T02:05:00.000Z"), + type: "compaction" as const, + driver: null, + beforeTokenCount: 985_000, + afterTokenCount: 25_000, + }, + } satisfies { item: ThreadStructureTurnItem }; + + const snapshot = deriveLatestContextWindowSnapshot([newerCompaction], olderLiveUsage); + expect(snapshot?.usedTokens).toBe(25_000); + expect(snapshot?.maxTokens).toBe(1_000_000); + expect(snapshot?.totalProcessedTokens).toBe(985_000); + }); + + it("clears stale liveUsage when a newer completed compaction has no afterTokenCount", () => { + const olderLiveUsage = decodeTokenUsage({ + usedTokens: 985_000, + maxTokens: 1_000_000, + updatedAt: "2026-11-19T02:00:00.000Z", + }); + const newerCompaction = { + item: { + id: "compaction-1" as never, + threadId: "thread-1" as never, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "completed" as const, + title: "Context compacted", + startedAt: null, + completedAt: null, + updatedAt: DateTime.makeUnsafe("2026-11-19T02:05:00.000Z"), + type: "compaction" as const, + driver: null, + }, + } satisfies { item: ThreadStructureTurnItem }; + + const snapshot = deriveLatestContextWindowSnapshot([newerCompaction], olderLiveUsage); + expect(snapshot).toBeNull(); + }); }); describe("live provider-turn usage (#8144)", () => { diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index a8f7e0f88c355..b4d4dee238236 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -83,6 +83,75 @@ export function deriveLatestContextWindowSnapshot( liveUsage?: OrchestrationV2ProviderTurnTokenUsage | null, providerThread?: Pick | null, ): ContextWindowSnapshot | null { + let latestCompaction: Extract | null = null; + let latestCompactionUpdatedAt: string | null = null; + for (let index = entries.length - 1; index >= 0; index -= 1) { + const entry = entries[index]; + if (!entry || entry.item.type !== "compaction" || entry.item.status !== "completed") { + continue; + } + const payload = entry.item; + if ( + providerThread != null && + payload.providerThreadId != null && + payload.providerThreadId !== providerThread.id + ) { + continue; + } + const date = payload.completedAt ?? payload.updatedAt ?? payload.startedAt; + if (date) { + latestCompaction = payload; + latestCompactionUpdatedAt = DateTime.formatIso(date); + break; + } + } + + const fallbackMaxTokens = + liveUsage?.maxTokens ?? asFiniteNumber(providerThread?.contextUsage?.maxTokens) ?? null; + const usageUpdatedAt = + liveUsage?.updatedAt ?? + (providerThread?.updatedAt ? DateTime.formatIso(providerThread.updatedAt) : null); + const compactionIsNewer = + latestCompaction != null && + latestCompactionUpdatedAt != null && + (usageUpdatedAt == null || Date.parse(latestCompactionUpdatedAt) >= Date.parse(usageUpdatedAt)); + + if (compactionIsNewer && latestCompaction != null && latestCompactionUpdatedAt != null) { + const usedTokens = asFiniteNumber(latestCompaction.afterTokenCount); + if (usedTokens === null || usedTokens < 0) { + return null; + } + const maxTokens = fallbackMaxTokens; + const usedPercentage = + maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null; + const remainingTokens = + maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null; + const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null; + return { + usedTokens, + totalProcessedTokens: asFiniteNumber(latestCompaction.beforeTokenCount), + maxTokens, + remainingTokens, + usedPercentage, + remainingPercentage, + inputTokens: null, + cachedInputTokens: null, + outputTokens: null, + reasoningOutputTokens: null, + lastUsedTokens: null, + lastInputTokens: null, + lastCachedInputTokens: null, + lastOutputTokens: null, + lastReasoningOutputTokens: null, + toolUses: null, + durationMs: null, + compactsAutomatically: true, + autoCompactThreshold: null, + cost: null, + updatedAt: latestCompactionUpdatedAt, + }; + } + if (liveUsage != null) { const usedTokens = Math.max(0, liveUsage.usedTokens); const maxTokens = liveUsage.maxTokens ?? null; diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 0072f9d1897b7..3fe66b32b8d2e 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -1499,6 +1499,14 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ...(summary === undefined || summary.length === 0 ? {} : { summary }), }, }); + if (status === "completed" && state.providerThread.contextUsage !== null) { + state.providerThread = { + ...state.providerThread, + contextUsage: null, + updatedAt, + }; + yield* emitProviderThread(state); + } if (status !== "running") turn.compaction = undefined; }); From a7a47723fb5c204502b522b8d27314a13a5b45c2 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 08:42:33 +0000 Subject: [PATCH 2/5] refactor(client-runtime): share the compaction snapshot and test the OpenCode reset Fold the duplicated compaction snapshot builder and retired-thread check into helpers, trim the context window tests to one case on the shared fixture, and cover OpenCode dropping handoff-seeded context usage once a compaction completes. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 33 ++++ apps/web/src/lib/contextWindow.test.ts | 71 ++----- .../client-runtime/src/state/contextWindow.ts | 182 +++++++----------- 3 files changed, 118 insertions(+), 168 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index cd1bdc9044a5c..21d18c9047acf 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -330,6 +330,7 @@ const resumed = ( readonly lastRunOrdinal?: number; readonly pendingBackgroundTasks?: OrchestrationV2ProviderThread["pendingBackgroundTasks"]; readonly goal?: OrchestrationV2ProviderThread["goal"]; + readonly contextUsage?: OrchestrationV2ProviderThread["contextUsage"]; readonly external?: boolean; readonly supervised?: boolean; readonly processExit?: Effect.Effect; @@ -398,6 +399,7 @@ const resumed = ( ? {} : { lastRunOrdinal: options.lastRunOrdinal }), ...(options?.goal === undefined ? {} : { goal: options.goal }), + ...(options?.contextUsage === undefined ? {} : { contextUsage: options.contextUsage }), ...(options?.pendingBackgroundTasks === undefined ? {} : { pendingBackgroundTasks: options.pendingBackgroundTasks }), @@ -509,6 +511,37 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }), ); + it.effect("drops context usage carried over from before a completed compaction", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.compaction.started", { sessionID: SESSION, reason: "manual", recent: "" }), + event("session.compaction.ended", { + sessionID: SESSION, + reason: "manual", + text: "Summary", + recent: "", + }), + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { contextUsage: { usedTokens: 150_000, maxTokens: 160_000 } }, + ); + assert.equal(thread.contextUsage?.usedTokens, 150_000); + const collected = yield* runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const usage = (yield* Fiber.join(collected)).flatMap((event) => + event.type === "provider_thread.updated" ? [event.providerThread.contextUsage] : [], + ); + assert.isNull(usage.at(-1)); + }), + ); + it.effect("never sends a saved variant the catalog model does not list", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index 0577939592c58..5b8dbbdc17624 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -71,70 +71,23 @@ describe("V2 context window presentation", () => { ).toBe(2_000); }); - it("prefers a newer completed compaction over older liveUsage", () => { - const olderLiveUsage = decodeTokenUsage({ + it("prefers a completed compaction over usage reported before it", () => { + const usageBeforeCompaction = decodeTokenUsage({ usedTokens: 985_000, maxTokens: 1_000_000, - updatedAt: "2026-11-19T02:00:00.000Z", + updatedAt: "2026-06-19T23:55:00.000Z", }); - const newerCompaction = { - item: { - id: "compaction-1" as never, - threadId: "thread-1" as never, - runId: null, - nodeId: null, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 2, - status: "completed" as const, - title: "Context compacted", - startedAt: null, - completedAt: null, - updatedAt: DateTime.makeUnsafe("2026-11-19T02:05:00.000Z"), - type: "compaction" as const, - driver: null, - beforeTokenCount: 985_000, - afterTokenCount: 25_000, - }, - } satisfies { item: ThreadStructureTurnItem }; - - const snapshot = deriveLatestContextWindowSnapshot([newerCompaction], olderLiveUsage); - expect(snapshot?.usedTokens).toBe(25_000); + const snapshot = deriveLatestContextWindowSnapshot( + [compactionEntry(null)], + usageBeforeCompaction, + ); + expect(snapshot?.usedTokens).toBe(2_000); expect(snapshot?.maxTokens).toBe(1_000_000); - expect(snapshot?.totalProcessedTokens).toBe(985_000); - }); - it("clears stale liveUsage when a newer completed compaction has no afterTokenCount", () => { - const olderLiveUsage = decodeTokenUsage({ - usedTokens: 985_000, - maxTokens: 1_000_000, - updatedAt: "2026-11-19T02:00:00.000Z", - }); - const newerCompaction = { - item: { - id: "compaction-1" as never, - threadId: "thread-1" as never, - runId: null, - nodeId: null, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 2, - status: "completed" as const, - title: "Context compacted", - startedAt: null, - completedAt: null, - updatedAt: DateTime.makeUnsafe("2026-11-19T02:05:00.000Z"), - type: "compaction" as const, - driver: null, - }, - } satisfies { item: ThreadStructureTurnItem }; - - const snapshot = deriveLatestContextWindowSnapshot([newerCompaction], olderLiveUsage); - expect(snapshot).toBeNull(); + const { afterTokenCount: _, ...withoutCount } = compactionEntry(null).item; + expect( + deriveLatestContextWindowSnapshot([{ item: withoutCount }], usageBeforeCompaction), + ).toBeNull(); }); }); diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index b4d4dee238236..534588096e4ba 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -76,6 +76,54 @@ export function latestProviderTurnTokenUsage( ); } +type CompactionItem = Extract; + +// A retired provider thread's items say nothing about the active conversation. +function isRetiredProviderThreadItem( + item: CompactionItem, + providerThread: Pick | null | undefined, +): boolean { + return ( + providerThread != null && + item.providerThreadId != null && + item.providerThreadId !== providerThread.id + ); +} + +function compactionSnapshot( + item: CompactionItem, + maxTokens: number | null, + updatedAt: string, +): ContextWindowSnapshot | null { + const usedTokens = asFiniteNumber(item.afterTokenCount); + if (usedTokens === null || usedTokens < 0) return null; + const usedPercentage = + maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null; + return { + usedTokens, + totalProcessedTokens: asFiniteNumber(item.beforeTokenCount), + maxTokens, + remainingTokens: maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null, + usedPercentage, + remainingPercentage: usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null, + inputTokens: null, + cachedInputTokens: null, + outputTokens: null, + reasoningOutputTokens: null, + lastUsedTokens: null, + lastInputTokens: null, + lastCachedInputTokens: null, + lastOutputTokens: null, + lastReasoningOutputTokens: null, + toolUses: null, + durationMs: null, + compactsAutomatically: true, + autoCompactThreshold: null, + cost: null, + updatedAt, + }; +} + export function deriveLatestContextWindowSnapshot( entries: ReadonlyArray<{ readonly item: ThreadStructureTurnItem; @@ -83,73 +131,27 @@ export function deriveLatestContextWindowSnapshot( liveUsage?: OrchestrationV2ProviderTurnTokenUsage | null, providerThread?: Pick | null, ): ContextWindowSnapshot | null { - let latestCompaction: Extract | null = null; - let latestCompactionUpdatedAt: string | null = null; - for (let index = entries.length - 1; index >= 0; index -= 1) { - const entry = entries[index]; - if (!entry || entry.item.type !== "compaction" || entry.item.status !== "completed") { - continue; - } - const payload = entry.item; - if ( - providerThread != null && - payload.providerThreadId != null && - payload.providerThreadId !== providerThread.id - ) { - continue; - } - const date = payload.completedAt ?? payload.updatedAt ?? payload.startedAt; - if (date) { - latestCompaction = payload; - latestCompactionUpdatedAt = DateTime.formatIso(date); - break; - } - } - - const fallbackMaxTokens = - liveUsage?.maxTokens ?? asFiniteNumber(providerThread?.contextUsage?.maxTokens) ?? null; + const latestCompletedCompaction = entries.findLast( + (entry): entry is { readonly item: CompactionItem } => + entry.item.type === "compaction" && + entry.item.status === "completed" && + !isRetiredProviderThreadItem(entry.item, providerThread), + )?.item; const usageUpdatedAt = liveUsage?.updatedAt ?? (providerThread?.updatedAt ? DateTime.formatIso(providerThread.updatedAt) : null); - const compactionIsNewer = - latestCompaction != null && - latestCompactionUpdatedAt != null && - (usageUpdatedAt == null || Date.parse(latestCompactionUpdatedAt) >= Date.parse(usageUpdatedAt)); - - if (compactionIsNewer && latestCompaction != null && latestCompactionUpdatedAt != null) { - const usedTokens = asFiniteNumber(latestCompaction.afterTokenCount); - if (usedTokens === null || usedTokens < 0) { - return null; + if (latestCompletedCompaction !== undefined) { + const compactedAt = DateTime.formatIso( + latestCompletedCompaction.completedAt ?? latestCompletedCompaction.updatedAt, + ); + // Usage reported before the compaction describes the context it just discarded. + if (usageUpdatedAt === null || Date.parse(compactedAt) >= Date.parse(usageUpdatedAt)) { + return compactionSnapshot( + latestCompletedCompaction, + liveUsage?.maxTokens ?? asFiniteNumber(providerThread?.contextUsage?.maxTokens), + compactedAt, + ); } - const maxTokens = fallbackMaxTokens; - const usedPercentage = - maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null; - const remainingTokens = - maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null; - const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null; - return { - usedTokens, - totalProcessedTokens: asFiniteNumber(latestCompaction.beforeTokenCount), - maxTokens, - remainingTokens, - usedPercentage, - remainingPercentage, - inputTokens: null, - cachedInputTokens: null, - outputTokens: null, - reasoningOutputTokens: null, - lastUsedTokens: null, - lastInputTokens: null, - lastCachedInputTokens: null, - lastOutputTokens: null, - lastReasoningOutputTokens: null, - toolUses: null, - durationMs: null, - compactsAutomatically: true, - autoCompactThreshold: null, - cost: null, - updatedAt: latestCompactionUpdatedAt, - }; } if (liveUsage != null) { @@ -220,54 +222,16 @@ export function deriveLatestContextWindowSnapshot( }; } for (let index = entries.length - 1; index >= 0; index -= 1) { - const entry = entries[index]; - if (!entry || entry.item.type !== "compaction") { - continue; - } - const payload = entry.item; - // A retired provider thread's compaction says nothing about the active conversation. - if ( - providerThread != null && - payload.providerThreadId != null && - payload.providerThreadId !== providerThread.id - ) { + const item = entries[index]?.item; + if (item?.type !== "compaction" || isRetiredProviderThreadItem(item, providerThread)) { continue; } - const usedTokens = asFiniteNumber(payload.afterTokenCount); - if (usedTokens === null || usedTokens < 0) { - continue; - } - - const maxTokens = null; - const usedPercentage = - maxTokens !== null && maxTokens > 0 ? Math.min(100, (usedTokens / maxTokens) * 100) : null; - const remainingTokens = - maxTokens !== null ? Math.max(0, Math.round(maxTokens - usedTokens)) : null; - const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null; - - return { - usedTokens, - totalProcessedTokens: asFiniteNumber(payload.beforeTokenCount), - maxTokens, - remainingTokens, - usedPercentage, - remainingPercentage, - inputTokens: null, - cachedInputTokens: null, - outputTokens: null, - reasoningOutputTokens: null, - lastUsedTokens: null, - lastInputTokens: null, - lastCachedInputTokens: null, - lastOutputTokens: null, - lastReasoningOutputTokens: null, - toolUses: null, - durationMs: null, - compactsAutomatically: true, - autoCompactThreshold: null, - cost: null, - updatedAt: DateTime.formatIso(payload.startedAt ?? payload.updatedAt), - }; + const snapshot = compactionSnapshot( + item, + null, + DateTime.formatIso(item.startedAt ?? item.updatedAt), + ); + if (snapshot !== null) return snapshot; } return null; From f56a2d75c3e4a8ceccdb46f975ef8307abfc4984 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 08:46:12 +0000 Subject: [PATCH 3/5] fix(client-runtime): keep the newest compaction until usage is actually reported A provider thread's updatedAt only dates usage when it carries some, so metadata-only updates no longer let an older compaction's count back in. OpenCode also drops its retained step when a compaction completes, so a turn settling right after cannot republish the pre-compaction usage. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/OpenCode2AdapterV2.test.ts | 17 ++++++++++++++++- apps/web/src/lib/contextWindow.test.ts | 14 ++++++++++++++ .../client-runtime/src/state/contextWindow.ts | 2 +- .../provider-opencode/src/server/v2/adapter.ts | 2 ++ 4 files changed, 33 insertions(+), 2 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 21d18c9047acf..3a5729aa71f5a 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -517,6 +517,13 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { [ out("session.prompt", { sessionID: SESSION, text: "" }), promptAccepted, + event("session.step.ended", { + sessionID: SESSION, + assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z", + finish: "stop", + cost: 0, + tokens: { input: 150_000, output: 40, reasoning: 0, cache: { read: 0, write: 0 } }, + }), event("session.compaction.started", { sessionID: SESSION, reason: "manual", recent: "" }), event("session.compaction.ended", { sessionID: SESSION, @@ -535,10 +542,18 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { Effect.forkScoped, ); yield* runtime.startTurn(turnInput(thread)); - const usage = (yield* Fiber.join(collected)).flatMap((event) => + const seen = yield* Fiber.join(collected); + const usage = seen.flatMap((event) => event.type === "provider_thread.updated" ? [event.providerThread.contextUsage] : [], ); assert.isNull(usage.at(-1)); + const settled = seen.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + assert.isUndefined( + settled?.type === "provider_turn.updated" ? settled.providerTurn.tokenUsage : "missing", + ); }), ); diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index 5b8dbbdc17624..6b40383ce222f 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -88,6 +88,20 @@ describe("V2 context window presentation", () => { expect( deriveLatestContextWindowSnapshot([{ item: withoutCount }], usageBeforeCompaction), ).toBeNull(); + // A metadata-only provider thread update reports no usage, so an older count stays hidden. + const olderCompaction = { + item: { + ...compactionEntry(null).item, + updatedAt: DateTime.makeUnsafe("2026-06-19T00:00:00.000Z"), + }, + }; + expect( + deriveLatestContextWindowSnapshot([olderCompaction, { item: withoutCount }], null, { + id: ProviderThreadId.make("thread"), + contextUsage: null, + updatedAt: DateTime.makeUnsafe("2026-06-21T00:00:00.000Z"), + }), + ).toBeNull(); }); }); diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index 534588096e4ba..6e470f249f912 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -139,7 +139,7 @@ export function deriveLatestContextWindowSnapshot( )?.item; const usageUpdatedAt = liveUsage?.updatedAt ?? - (providerThread?.updatedAt ? DateTime.formatIso(providerThread.updatedAt) : null); + (providerThread?.contextUsage != null ? DateTime.formatIso(providerThread.updatedAt) : null); if (latestCompletedCompaction !== undefined) { const compactedAt = DateTime.formatIso( latestCompletedCompaction.completedAt ?? latestCompletedCompaction.updatedAt, diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 3fe66b32b8d2e..0da481a474b37 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -1499,6 +1499,8 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr ...(summary === undefined || summary.length === 0 ? {} : { summary }), }, }); + // The pre-compaction step would otherwise settle the turn as its newest usage. + if (status === "completed") turn.lastStep = undefined; if (status === "completed" && state.providerThread.contextUsage !== null) { state.providerThread = { ...state.providerThread, From e3ed130b3a55d70012b0fbecd4153141bd070cfe Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 09:03:03 +0000 Subject: [PATCH 4/5] fix(opencode): clear inherited context usage after a v1 compaction too The v1 adapter kept a provider thread's handoff-seeded contextUsage across a completed compaction, and the turn's settlement re-stamped it as newer than the compaction, so the meter showed the discarded context. It now clears it like the v2 adapter. A compaction also only supersedes usage reported strictly before it: Claude reports post-compaction usage in the compaction's own millisecond, and that report carries the auto-compact threshold the compaction item lacks. Co-Authored-By: Claude Opus 5.5 --- apps/web/src/lib/contextWindow.test.ts | 12 ++++ .../client-runtime/src/state/contextWindow.ts | 5 +- .../src/server/adapter.test.ts | 55 +++++++++++++++++++ .../provider-opencode/src/server/adapter.ts | 3 + 4 files changed, 73 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/contextWindow.test.ts b/apps/web/src/lib/contextWindow.test.ts index 6b40383ce222f..a9bef5448ff6d 100644 --- a/apps/web/src/lib/contextWindow.test.ts +++ b/apps/web/src/lib/contextWindow.test.ts @@ -84,6 +84,18 @@ describe("V2 context window presentation", () => { expect(snapshot?.usedTokens).toBe(2_000); expect(snapshot?.maxTokens).toBe(1_000_000); + // A report in the compaction's own millisecond is the provider's post-compaction usage. + const reportedWithCompaction = decodeTokenUsage({ + usedTokens: 2_000, + maxTokens: 1_000_000, + autoCompactThreshold: 900_000, + updatedAt: "2026-06-20T00:00:00.000Z", + }); + expect( + deriveLatestContextWindowSnapshot([compactionEntry(null)], reportedWithCompaction) + ?.autoCompactThreshold, + ).toBe(900_000); + const { afterTokenCount: _, ...withoutCount } = compactionEntry(null).item; expect( deriveLatestContextWindowSnapshot([{ item: withoutCount }], usageBeforeCompaction), diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index 6e470f249f912..37374b79b1b04 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -144,8 +144,9 @@ export function deriveLatestContextWindowSnapshot( const compactedAt = DateTime.formatIso( latestCompletedCompaction.completedAt ?? latestCompletedCompaction.updatedAt, ); - // Usage reported before the compaction describes the context it just discarded. - if (usageUpdatedAt === null || Date.parse(compactedAt) >= Date.parse(usageUpdatedAt)) { + // Usage reported before the compaction describes the context it just discarded; usage at + // the same instant is the provider's own post-compaction report. + if (usageUpdatedAt === null || Date.parse(compactedAt) > Date.parse(usageUpdatedAt)) { return compactionSnapshot( latestCompletedCompaction, liveUsage?.maxTokens ?? asFiniteNumber(providerThread?.contextUsage?.maxTokens), diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 76ba68319384c..7aacdad9efb16 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -1082,6 +1082,61 @@ describe("OpenCodeAdapterV2", () => { }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); + it.effect("drops context usage carried over from before a completed compaction", () => + Effect.gen(function* () { + const nativeEvents = asyncEventStream(); + let promptId = ""; + const harness = yield* makeOpenCodeRuntimeHarness("compaction-usage", "root", { + event: { subscribe: async () => ({ stream: nativeEvents.stream }) }, + session: { + create: async () => ({ data: { id: "root", time: { created: 1, updated: 1 } } }), + get: async () => ({ data: { id: "root", time: { created: 1, updated: 1 } } }), + promptAsync: async (input: { messageID: string }) => { + promptId = input.messageID; + return { data: true }; + }, + abort: async () => ({ data: true }), + children: async () => ({ data: [] }), + }, + }); + const inherited = yield* harness.runtime.resumeThread({ + providerThread: { + ...harness.providerThread, + contextUsage: { usedTokens: 150_000, maxTokens: 160_000 }, + }, + }); + const received = yield* harness.runtime.events.pipe( + Stream.takeUntil((event) => event.type === "turn.terminal"), + Stream.runCollect, + Effect.forkScoped, + ); + yield* harness.startTurn("hello", inherited); + const status = (type: "busy" | "idle") => ({ + type: "session.status", + properties: { sessionID: "root", status: { type } }, + }); + yield* Effect.promise(() => + nativeEvents.push({ + type: "message.updated", + properties: { + sessionID: "root", + info: { id: promptId, role: "user", time: { created: 1 } }, + }, + }), + ); + yield* Effect.promise(() => nativeEvents.push(status("busy"))); + yield* Effect.promise(() => + nativeEvents.push({ type: "session.compacted", properties: { sessionID: "root" } }), + ); + yield* Effect.promise(() => nativeEvents.push(status("idle"))); + + const usage = Array.from(yield* Fiber.join(received)).flatMap((event) => + event.type === "provider_thread.updated" ? [event.providerThread.contextUsage] : [], + ); + assert.isNull(usage.at(-1)); + }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), + ); + it.effect("fails an explicit compaction that OpenCode reports as a context overflow", () => Effect.gen(function* () { const nativeEvents = asyncEventStream(); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index 0f817ca7242b8..da80dae7d1ae5 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -2637,6 +2637,9 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function updatedAt: now, }, }); + if (state.providerThread.contextUsage !== null) { + yield* updateProviderThread(state, { contextUsage: null }); + } }); const handleMessageUpdated = Effect.fnUntraced(function* ( From 0a730d04557159448eda52232c97c4daf5b85dca Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 09:17:33 +0000 Subject: [PATCH 5/5] fix(opencode): drop the v1 turn's pre-compaction step on compaction A v1 turn settled after a completed compaction republished its last pre-compaction step as tokenUsage stamped with the terminal time, which the context meter read as post-compaction usage. Clear the retained step when the compaction completes, as the v2 adapter does. Co-Authored-By: Claude Opus 5.5 --- .../src/server/adapter.test.ts | 35 ++++++++++++++++++- .../provider-opencode/src/server/adapter.ts | 2 ++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/packages/provider-opencode/src/server/adapter.test.ts b/packages/provider-opencode/src/server/adapter.test.ts index 7aacdad9efb16..96e6cd7aa4ae7 100644 --- a/packages/provider-opencode/src/server/adapter.test.ts +++ b/packages/provider-opencode/src/server/adapter.test.ts @@ -1125,15 +1125,48 @@ describe("OpenCodeAdapterV2", () => { }), ); yield* Effect.promise(() => nativeEvents.push(status("busy"))); + yield* Effect.promise(() => + nativeEvents.push({ + type: "message.updated", + properties: { + sessionID: "root", + info: { id: "assistant", role: "assistant", time: { created: 1 }, parentID: promptId }, + }, + }), + ); + yield* Effect.promise(() => + nativeEvents.push({ + type: "message.part.updated", + properties: { + part: { + type: "step-finish", + id: "pre-compaction-step", + sessionID: "root", + messageID: "assistant", + reason: "stop", + cost: 0, + tokens: { input: 150_000, output: 40, reasoning: 0, cache: { read: 0, write: 0 } }, + }, + }, + }), + ); yield* Effect.promise(() => nativeEvents.push({ type: "session.compacted", properties: { sessionID: "root" } }), ); yield* Effect.promise(() => nativeEvents.push(status("idle"))); - const usage = Array.from(yield* Fiber.join(received)).flatMap((event) => + const events = Array.from(yield* Fiber.join(received)); + const usage = events.flatMap((event) => event.type === "provider_thread.updated" ? [event.providerThread.contextUsage] : [], ); assert.isNull(usage.at(-1)); + const settled = events.findLast( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ); + assert.isUndefined( + settled?.type === "provider_turn.updated" ? settled.providerTurn.tokenUsage : "missing", + ); }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))), ); diff --git a/packages/provider-opencode/src/server/adapter.ts b/packages/provider-opencode/src/server/adapter.ts index da80dae7d1ae5..38fd4070566a3 100644 --- a/packages/provider-opencode/src/server/adapter.ts +++ b/packages/provider-opencode/src/server/adapter.ts @@ -2637,6 +2637,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function updatedAt: now, }, }); + // The pre-compaction step would otherwise settle the turn as its newest usage. + turn.usage.lastStep = null; if (state.providerThread.contextUsage !== null) { yield* updateProviderThread(state, { contextUsage: null }); }