@@ -350,6 +350,8 @@ interface OpenCodeSessionContext {
350350 > ;
351351 /** Counter for generic token events without a stable id. */
352352 dedupeCounter : number ;
353+ /** Persistent map from dedupeKey to the turn that created it, for stale-event detection. */
354+ messageTurnMap : Map < string , TurnId > ;
353355 cancellation : OpenCodeCancellation | undefined ;
354356 interruptedTurnId : TurnId | undefined ;
355357 reconcileIdleStatus : boolean ;
@@ -1071,6 +1073,28 @@ export function makeOpenCodeAdapter(
10711073 : "opencode" ;
10721074 if ( id ) modelKey = `${ prov } /${ id } ` ;
10731075 }
1076+ // Stale-event guard: if this dedupeKey was already seen for a different
1077+ // turn, this is a late event from a prior turn that would otherwise
1078+ // contaminate the new turn's totals.
1079+ if ( dedupeKey ) {
1080+ const existingTurnId = context . messageTurnMap . get ( dedupeKey ) ;
1081+ if ( existingTurnId !== undefined ) {
1082+ if ( existingTurnId !== turnId ) {
1083+ yield * emit ( {
1084+ ...( yield * buildEventBase ( {
1085+ threadId : context . session . threadId ,
1086+ turnId,
1087+ raw,
1088+ } ) ) ,
1089+ type : "thread.token-usage.updated" ,
1090+ payload : { usage : snapshot } ,
1091+ } ) ;
1092+ return ;
1093+ }
1094+ } else {
1095+ context . messageTurnMap . set ( dedupeKey , turnId ) ;
1096+ }
1097+ }
10741098 const key = dedupeKey ?? `generic:${ context . dedupeCounter ++ } ` ;
10751099 context . tokenDedupeMap . set ( key , { tokens, cost : costValue , modelKey } ) ;
10761100 // Recompute aggregated totals from the dedupe map.
@@ -2788,6 +2812,7 @@ export function makeOpenCodeAdapter(
27882812 modelUsage : new Map ( ) ,
27892813 tokenDedupeMap : new Map ( ) ,
27902814 dedupeCounter : 0 ,
2815+ messageTurnMap : new Map ( ) ,
27912816 cancellation : undefined ,
27922817 interruptedTurnId : undefined ,
27932818 reconcileIdleStatus : false ,
0 commit comments