feat(server): show OpenCode session context window usage #7072
ClosedTerrigible(GitHub profile, opens in a new tab)wants to merge 13 commits into
main fromrefs/pull/7072/headopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 859OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -685,0 +839,21 @@839+ */840+ const loadContextUsageMetadata = Effect.fn("loadContextUsageMetadata")(function* (841+ context: OpenCodeSessionContext,842+ ) {843+ if (context.modelContextWindowCacheLoaded) {844+ return;845+ }846+ context.modelContextWindowCacheLoaded = true;847+ const metadata = yield* Effect.all(848+ [849+ runOpenCodeSdk("config.providers", () =>850+ context.client.config.providers({ directory: context.directory }),851+ ).pipe(Effect.exit),852+ runOpenCodeSdk("config.get", () =>853+ context.client.config.get({ directory: context.directory }),854+ ).pipe(Effect.exit),855+ ],856+ { concurrency: "unbounded" },857+ ).pipe(Effect.timeoutOption(OPENCODE_CONTEXT_METADATA_PROBE_TIMEOUT_MS));858+ if (Option.isNone(metadata)) {859+ return;
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 864OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -685,0 +844,21 @@844+ ) {845+ if (context.modelContextWindowCacheLoaded) {846+ return;847+ }848+ context.modelContextWindowCacheLoaded = true;849+ const [providersProbe, configProbe] = yield* Effect.all(850+ [851+ runOpenCodeSdk("config.providers", () =>852+ context.client.config.providers({ directory: context.directory }),853+ )854+ .pipe(Effect.exit)855+ .pipe(Effect.timeoutOption(OPENCODE_CONTEXT_METADATA_PROBE_TIMEOUT_MS)),856+ runOpenCodeSdk("config.get", () =>857+ context.client.config.get({ directory: context.directory }),858+ )859+ .pipe(Effect.exit)860+ .pipe(Effect.timeoutOption(OPENCODE_CONTEXT_METADATA_PROBE_TIMEOUT_MS)),861+ ],862+ { concurrency: "unbounded" },863+ );864+ if (Option.isNone(providersProbe)) {
Terrigible(GitHub profile, opens in a new tab) changed the title
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 918OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -685,0 +898,21 @@898+ */899+ const emitContextWindowUsage = Effect.fn("emitContextWindowUsage")(function* (900+ context: OpenCodeSessionContext,901+ tokens: OpenCodeAssistantTokenCounts,902+ providerID: string,903+ modelID: string,904+ turnId: TurnId | undefined,905+ raw: unknown,906+ ) {907+ yield* loadContextUsageMetadata(context).pipe(Effect.ignore);908+ const usage = buildOpenCodeContextWindowUsage({909+ tokens,910+ modelContextWindow: resolveModelContextWindow(context, providerID, modelID),911+ compactsAutomatically: context.compactsAutomatically,912+ });913+ if (914+ usage === undefined ||915+ isSameOpenCodeContextWindowUsage(context.lastEmittedContextWindowUsage, usage)916+ ) {917+ return;918+ }
- apps/server/src/provider/Layers/OpenCodeAdapter.ts lines 229 to 232Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -169,0 +230,21 @@230+ */231+export function buildOpenCodeContextWindowUsage(input: {232+ readonly tokens: OpenCodeAssistantTokenCounts | null | undefined;233+ readonly modelContextWindow?: number | null | undefined;234+ readonly compactsAutomatically?: boolean | undefined;235+}): ThreadTokenUsageSnapshot | undefined {236+ const inputTokens = openCodeTokenCounter(input.tokens?.input);237+ const outputTokens = openCodeTokenCounter(input.tokens?.output);238+ const reasoningTokens = openCodeTokenCounter(input.tokens?.reasoning);239+ const cachedReadTokens = openCodeTokenCounter(input.tokens?.cache?.read);240+ const cachedWriteTokens = openCodeTokenCounter(input.tokens?.cache?.write);241+ const rawUsedTokens =242+ inputTokens + outputTokens + reasoningTokens + cachedReadTokens + cachedWriteTokens;243+ if (rawUsedTokens <= 0) {244+ return undefined;245+ }246+247+ const modelContextWindow =248+ typeof input.modelContextWindow === "number" &&249+ Number.isFinite(input.modelContextWindow) &&250+ input.modelContextWindow > 0
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2660Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1958,3 +2210,15 @@19582210 }19592211 yield* emitAssistantTextDelta(context, part, turnId, event);19602212 }2213+ // Assistant messages carry cumulative context-window token counts2214+ // once complete; surface them as the live usage snapshot.2215+ if (event.properties.info.tokens !== undefined) {2216+ yield* emitContextWindowUsage(2217+ context,2218+ event.properties.info.tokens,2219+ event.properties.info.providerID,2220+ event.properties.info.modelID,2221+ turnId,2222+ event,2223+ );2224+ }
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 2180OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1907,3 +2161,20 @@19072161 event.type === "message.part.updated" ||19082162 (event.type === "message.updated" && event.properties.info.role === "assistant"));19092163 if (suppressInterruptedParentOutput) {2164+ // Token usage is not display output — keep the meter accurate even2165+ // for interrupted turns. Without this, an aborted assistant message2166+ // that already carried the latest cumulative counts would be dropped2167+ // and the meter would underreport until the next completed message.2168+ if (2169+ event.type === "message.updated" &&2170+ event.properties.info.role === "assistant" &&2171+ event.properties.info.tokens !== undefined2172+ ) {2173+ yield* emitContextWindowUsage(2174+ context,2175+ event.properties.info.tokens,2176+ event.properties.info.providerID,2177+ event.properties.info.modelID,2178+ turnId,2179+ event,2180+ );
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1219OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1072,0 +1199,21 @@1199+ }1200+ }1201+ }1202+ if (Option.isSome(configProbe) && Exit.isSuccess(configProbe.value)) {1203+ const auto = configProbe.value.value.data?.compaction?.auto;1204+ if (typeof auto === "boolean") context.compactsAutomatically = auto;1205+ }1206+ });1207+1208+ // Emit deduped token-usage snapshot. Bails early on zero tokens so the1209+ // sequential pump doesn't stall on config round-trips for empty broadcasts.1210+ const emitContextWindowUsage = Effect.fn("emitContextWindowUsage")(function* (1211+ context: OpenCodeSessionContext,1212+ tokens: OpenCodeAssistantTokenCounts,1213+ providerID: string,1214+ modelID: string,1215+ turnId: TurnId | undefined,1216+ raw: unknown,1217+ ) {1218+ if (openCodeTokenTotal(tokens) <= 0) return;1219+ yield* loadContextUsageMetadata(context).pipe(Effect.ignore);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1252OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -1072,0 +1232,21 @@1232+ type: "thread.token-usage.updated",1233+ payload: { usage },1234+ });1235+ });1236+1237+ // Emit deduped token-usage snapshot. Bails early on zero tokens so empty1238+ // broadcasts spawn no probe. The metadata probe runs in a session-scoped1239+ // background fiber — never inline: the first token-bearing message would1240+ // otherwise stall the sequential event pump for up to the probe timeout1241+ // while config.providers/config.get is wedged, delaying text deltas,1242+ // approvals, and idle/completion events queued behind it.1243+ const emitContextWindowUsage = Effect.fn("emitContextWindowUsage")(function* (1244+ context: OpenCodeSessionContext,1245+ tokens: OpenCodeAssistantTokenCounts,1246+ providerID: string,1247+ modelID: string,1248+ turnId: TurnId | undefined,1249+ raw: unknown,1250+ ) {1251+ if (openCodeTokenTotal(tokens) <= 0) return;1252+ if (context.modelContextWindowCacheLoaded) {
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1346Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1072,0 +1242,21 @@1242+ // approvals, and idle/completion events queued behind it.1243+ const emitContextWindowUsage = Effect.fn("emitContextWindowUsage")(function* (1244+ context: OpenCodeSessionContext,1245+ tokens: OpenCodeAssistantTokenCounts,1246+ providerID: string,1247+ modelID: string,1248+ turnId: TurnId | undefined,1249+ raw: unknown,1250+ ) {1251+ if (openCodeTokenTotal(tokens) <= 0) return;1252+ if (context.modelContextWindowCacheLoaded) {1253+ yield* emitUsageSnapshot(context, tokens, providerID, modelID, turnId, raw);1254+ return;1255+ }1256+ yield* Effect.gen(function* () {1257+ yield* loadContextUsageMetadata(context).pipe(Effect.ignore);1258+ yield* emitUsageSnapshot(context, tokens, providerID, modelID, turnId, raw);1259+ }).pipe(1260+ Effect.catchCause(() => Effect.void),1261+ Effect.forkIn(context.sessionScope),1262+ );
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1308OutdatedResolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1072,0 +1288,21 @@1288+ tokens,1289+ providerID,1290+ modelID,1291+ turnId,1292+ raw,1293+ };1294+ const existing = context.modelContextWindowQueue;1295+ if (existing !== undefined) {1296+ yield* Queue.offer(existing, pending);1297+ return;1298+ }1299+ // Single-flight: every caller runs on the sequential pump and the1300+ // queue field is only assigned here, so exactly one worker exists per1301+ // session and every input flows through it in arrival order.1302+ const queue = yield* Queue.unbounded<PendingOpenCodeContextWindowUsage>();1303+ context.modelContextWindowQueue = queue;1304+ yield* Queue.offer(queue, pending);1305+ yield* runContextWindowUsageWorker(context, queue).pipe(1306+ Effect.catchCause((cause) =>1307+ Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.void,1308+ ),
- apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1304Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1072,0 +1255,21 @@1255+ // escapes to end the loop when the session scope closes.1256+ const runContextWindowUsageWorker = Effect.fn("runContextWindowUsageWorker")(function* (1257+ context: OpenCodeSessionContext,1258+ queue: Queue.Queue<PendingOpenCodeContextWindowUsage>,1259+ ) {1260+ while (true) {1261+ const pending = yield* Queue.take(queue);1262+ yield* Effect.gen(function* () {1263+ yield* loadContextUsageMetadata(context).pipe(Effect.ignore);1264+ yield* emitUsageSnapshot(1265+ context,1266+ pending.tokens,1267+ pending.providerID,1268+ pending.modelID,1269+ pending.turnId,1270+ pending.raw,1271+ );1272+ }).pipe(1273+ Effect.catchCause((cause) =>1274+ Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.void,1275+ ),apps/server/src/provider/Layers/OpenCodeAdapter.ts line 1304Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -1072,0 +1255,21 @@1255+ // escapes to end the loop when the session scope closes.1256+ const runContextWindowUsageWorker = Effect.fn("runContextWindowUsageWorker")(function* (1257+ context: OpenCodeSessionContext,1258+ queue: Queue.Queue<PendingOpenCodeContextWindowUsage>,1259+ ) {1260+ while (true) {1261+ const pending = yield* Queue.take(queue);1262+ yield* Effect.gen(function* () {1263+ yield* loadContextUsageMetadata(context).pipe(Effect.ignore);1264+ yield* emitUsageSnapshot(1265+ context,1266+ pending.tokens,1267+ pending.providerID,1268+ pending.modelID,1269+ pending.turnId,1270+ pending.raw,1271+ );1272+ }).pipe(1273+ Effect.catchCause((cause) =>1274+ Cause.hasInterruptsOnly(cause) ? Effect.interrupt : Effect.void,1275+ ),
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
juliusmarminge closed this
Sign in to join this conversation.


Important
Review skipped#
Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
.coderabbit.yamlfile in this repository. To trigger a single review, invoke the@coderabbitai reviewcommand.⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID:
8dc09198-c739-4d62-9750-479650fdb4d2You can disable this status message by setting the
reviews.review_statustofalsein the CodeRabbit configuration file.Use the checkbox below for a quick retry:
Warning
Your free Security trial is over. An organization admin can upgrade to Advanced for continuous pull request security review or dismiss this notice.
Comment `@coderabbitai help` to get the list of available commands.