@@ -9,7 +9,6 @@ import { AskIgnoredError } from "./AskIgnoredError"
99
1010import { Anthropic } from "@anthropic-ai/sdk"
1111import OpenAI from "openai"
12- import debounce from "lodash.debounce"
1312import delay from "delay"
1413import pWaitFor from "p-wait-for"
1514import { serializeError } from "serialize-error"
@@ -64,10 +63,7 @@ import { maybeRemoveImageBlocks } from "../../api/transform/image-cleaning"
6463
6564// shared
6665import { findLastIndex } from "../../shared/array"
67- import { combineApiRequests } from "../../shared/combineApiRequests"
68- import { combineCommandSequences } from "../../shared/combineCommandSequences"
6966import { t } from "../../i18n"
70- import { getApiMetrics , hasTokenUsageChanged , hasToolUsageChanged } from "../../shared/getApiMetrics"
7167import { ClineAskResponse } from "../../shared/WebviewMessage"
7268import { defaultModeSlug , getModeBySlug } from "../../shared/modes"
7369import { DiffStrategy , type ToolUse , type ToolParamName , toolParamNames } from "../../shared/tools"
@@ -132,6 +128,7 @@ import { AutoApprovalHandler, checkAutoApproval } from "../auto-approval"
132128import { MessageManager } from "../message-manager"
133129import { validateAndFixToolResultIds } from "./validateToolResultIds"
134130import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages"
131+ import { UsageTracker } from "./UsageTracker"
135132
136133const MAX_EXPONENTIAL_BACKOFF_SECONDS = 600 // 10 minutes
137134const DEFAULT_USAGE_COLLECTION_TIMEOUT_MS = 5000 // 5 seconds
@@ -323,7 +320,6 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
323320 consecutiveMistakeCountForEditFile : Map < string , number > = new Map ( )
324321 consecutiveNoToolUseCount : number = 0
325322 consecutiveNoAssistantMessagesCount : number = 0
326- toolUsage : ToolUsage = { }
327323
328324 // Checkpoints
329325 enableCheckpoints : boolean
@@ -397,16 +393,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
397393 // This prevents excessive getModel() calls during tool execution
398394 cachedStreamingModel ?: { id : string ; info : ModelInfo }
399395
400- // Token Usage Cache
401- private tokenUsageSnapshot ?: TokenUsage
402- private tokenUsageSnapshotAt ?: number
403-
404- // Tool Usage Cache
405- private toolUsageSnapshot ?: ToolUsage
406-
407- // Token Usage Throttling - Debounced emit function
408- private readonly TOKEN_USAGE_EMIT_INTERVAL_MS = 2000 // 2 seconds
409- private debouncedEmitTokenUsage : ReturnType < typeof debounce >
396+ private usageTracker : UsageTracker
410397
411398 // Historical cloud sync tracking retained only to avoid task resume churn.
412399 private cloudSyncedMessageTimestamps : Set < number > = new Set ( )
@@ -541,27 +528,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
541528 this . todoList = initialTodos
542529 }
543530
544- // Initialize debounced token usage emit function
545- // Uses debounce with maxWait to achieve throttle-like behavior:
546- // - leading: true - Emit immediately on first call
547- // - trailing: true - Emit final state when updates stop
548- // - maxWait - Ensures at most one emit per interval during rapid updates (throttle behavior)
549- this . debouncedEmitTokenUsage = debounce (
550- ( tokenUsage : TokenUsage , toolUsage : ToolUsage ) => {
551- const tokenChanged = hasTokenUsageChanged ( tokenUsage , this . tokenUsageSnapshot )
552- const toolChanged = hasToolUsageChanged ( toolUsage , this . toolUsageSnapshot )
553-
554- if ( tokenChanged || toolChanged ) {
555- this . emit ( RooCodeEventName . TaskTokenUsageUpdated , this . taskId , tokenUsage , toolUsage )
556- this . tokenUsageSnapshot = tokenUsage
557- this . tokenUsageSnapshotAt = this . clineMessages . at ( - 1 ) ?. ts
558- // Deep copy tool usage for snapshot
559- this . toolUsageSnapshot = JSON . parse ( JSON . stringify ( toolUsage ) )
560- }
561- } ,
562- this . TOKEN_USAGE_EMIT_INTERVAL_MS ,
563- { leading : true , trailing : true , maxWait : this . TOKEN_USAGE_EMIT_INTERVAL_MS } ,
564- )
531+ this . usageTracker = new UsageTracker ( {
532+ taskId : this . taskId ,
533+ getMessages : ( ) => this . clineMessages ,
534+ getLastMessageTs : ( ) => this . clineMessages . at ( - 1 ) ?. ts ,
535+ emit : ( event , ...args ) => ( this . emit as any ) ( event , ...args ) ,
536+ } )
565537
566538 onCreated ?.( this )
567539
@@ -1238,7 +1210,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
12381210 // - Immediate first emit (leading: true)
12391211 // - At most one emit per interval during rapid updates (maxWait)
12401212 // - Final state is emitted when updates stop (trailing: true)
1241- this . debouncedEmitTokenUsage ( tokenUsage , this . toolUsage )
1213+ this . usageTracker . emitTokenUsageUpdate ( tokenUsage )
12421214
12431215 await this . providerRef . deref ( ) ?. updateTaskHistory ( historyItem )
12441216 return true
@@ -2249,9 +2221,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
22492221 * Triggers the debounce with current values and immediately flushes to ensure emit.
22502222 */
22512223 public emitFinalTokenUsageUpdate ( ) : void {
2252- const tokenUsage = this . getTokenUsage ( )
2253- this . debouncedEmitTokenUsage ( tokenUsage , this . toolUsage )
2254- this . debouncedEmitTokenUsage . flush ( )
2224+ this . usageTracker . emitFinalTokenUsageUpdate ( )
22552225 }
22562226
22572227 public async abortTask ( isAbandoned = false ) {
@@ -4638,31 +4608,19 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
46384608 // Metrics
46394609
46404610 public combineMessages ( messages : ClineMessage [ ] ) {
4641- return combineApiRequests ( combineCommandSequences ( messages ) )
4611+ return this . usageTracker . combineMessages ( messages )
46424612 }
46434613
46444614 public getTokenUsage ( ) : TokenUsage {
4645- return getApiMetrics ( this . combineMessages ( this . clineMessages . slice ( 1 ) ) )
4615+ return this . usageTracker . getTokenUsage ( )
46464616 }
46474617
46484618 public recordToolUsage ( toolName : ToolName ) {
4649- if ( ! this . toolUsage [ toolName ] ) {
4650- this . toolUsage [ toolName ] = { attempts : 0 , failures : 0 }
4651- }
4652-
4653- this . toolUsage [ toolName ] . attempts ++
4619+ this . usageTracker . recordToolUsage ( toolName )
46544620 }
46554621
46564622 public recordToolError ( toolName : ToolName , error ?: string ) {
4657- if ( ! this . toolUsage [ toolName ] ) {
4658- this . toolUsage [ toolName ] = { attempts : 0 , failures : 0 }
4659- }
4660-
4661- this . toolUsage [ toolName ] . failures ++
4662-
4663- if ( error ) {
4664- this . emit ( RooCodeEventName . TaskToolFailed , this . taskId , toolName , error )
4665- }
4623+ this . usageTracker . recordToolError ( toolName , error )
46664624 }
46674625
46684626 // Getters
@@ -4692,14 +4650,15 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
46924650 }
46934651
46944652 public get tokenUsage ( ) : TokenUsage | undefined {
4695- if ( this . tokenUsageSnapshot && this . tokenUsageSnapshotAt ) {
4696- return this . tokenUsageSnapshot
4697- }
4653+ return this . usageTracker . tokenUsage
4654+ }
46984655
4699- this . tokenUsageSnapshot = this . getTokenUsage ( )
4700- this . tokenUsageSnapshotAt = this . clineMessages . at ( - 1 ) ?. ts
4656+ public get toolUsage ( ) : ToolUsage {
4657+ return this . usageTracker . toolUsage
4658+ }
47014659
4702- return this . tokenUsageSnapshot
4660+ public set toolUsage ( toolUsage : ToolUsage ) {
4661+ this . usageTracker . toolUsage = toolUsage
47034662 }
47044663
47054664 public get cwd ( ) {
0 commit comments