From bf5e2785c3670901cc5a4adbadd690c05d30df97 Mon Sep 17 00:00:00 2001 From: celestial-vault <58194240+celestial-vault@users.noreply.github.com> Date: Wed, 18 Jun 2025 12:36:01 -0700 Subject: [PATCH] Reorganize task state and refactor out small functions (#4267) * move apiConversationHistory to MessageStateHandler * move clineMessages state to MessageStateManager class * remove unused imports * reorganize task class state variables and refactor out utility functions in recursivelyMakeClineRequests * move task ephemeral state to state class (#4273) --- .../checkpoints/checkpointRestore.ts | 2 +- src/core/controller/index.ts | 14 +- src/core/task/TaskState.ts | 57 ++ src/core/task/index.ts | 652 +++++++++--------- src/core/task/utils.ts | 70 ++ 5 files changed, 461 insertions(+), 334 deletions(-) create mode 100644 src/core/task/TaskState.ts create mode 100644 src/core/task/utils.ts diff --git a/src/core/controller/checkpoints/checkpointRestore.ts b/src/core/controller/checkpoints/checkpointRestore.ts index 9330e0cd..ba7159be 100644 --- a/src/core/controller/checkpoints/checkpointRestore.ts +++ b/src/core/controller/checkpoints/checkpointRestore.ts @@ -9,7 +9,7 @@ export async function checkpointRestore(controller: Controller, request: Checkpo if (request.number) { // wait for messages to be loaded - await pWaitFor(() => controller.task?.isInitialized === true, { + await pWaitFor(() => controller.task?.taskState.isInitialized === true, { timeout: 3_000, }).catch(() => { console.error("Failed to init new cline instance") diff --git a/src/core/controller/index.ts b/src/core/controller/index.ts index f6032534..b7fa62a3 100644 --- a/src/core/controller/index.ts +++ b/src/core/controller/index.ts @@ -445,8 +445,8 @@ export class Controller { if (this.task) { this.task.chatSettings = chatSettings - if (this.task.isAwaitingPlanResponse && didSwitchToActMode) { - this.task.didRespondToPlanAskBySwitchingMode = true + if (this.task.taskState.isAwaitingPlanResponse && didSwitchToActMode) { + this.task.taskState.didRespondToPlanAskBySwitchingMode = true // Use chatContent if provided, otherwise use default message await this.task.handleWebviewAskResponse( "messageResponse", @@ -471,9 +471,9 @@ export class Controller { await pWaitFor( () => this.task === undefined || - this.task.isStreaming === false || - this.task.didFinishAbortingStream || - this.task.isWaitingForFirstChunk, // if only first chunk is processed, then there's no need to wait for graceful abort (closes edits, browser, etc) + this.task.taskState.isStreaming === false || + this.task.taskState.didFinishAbortingStream || + this.task.taskState.isWaitingForFirstChunk, // if only first chunk is processed, then there's no need to wait for graceful abort (closes edits, browser, etc) { timeout: 3_000, }, @@ -482,7 +482,7 @@ export class Controller { }) if (this.task) { // 'abandoned' will prevent this cline instance from affecting future cline instance gui. this may happen if its hanging on a streaming request - this.task.abandoned = true + this.task.taskState.abandoned = true } await this.initTask(undefined, undefined, undefined, historyItem) // clears task again, so we need to abortTask manually above // await this.postStateToWebview() // new Cline instance will post state when it's ready. having this here sent an empty messages array to webview leading to virtuoso having to reload the entire list @@ -1006,7 +1006,7 @@ export class Controller { apiConfiguration, uriScheme: vscode.env.uriScheme, currentTaskItem: this.task?.taskId ? (taskHistory || []).find((item) => item.id === this.task?.taskId) : undefined, - checkpointTrackerErrorMessage: this.task?.checkpointTrackerErrorMessage, + checkpointTrackerErrorMessage: this.task?.taskState.checkpointTrackerErrorMessage, clineMessages: this.task?.messageStateHandler.getClineMessages() || [], taskHistory: (taskHistory || []) .filter((item) => item.ts && item.task) diff --git a/src/core/task/TaskState.ts b/src/core/task/TaskState.ts new file mode 100644 index 00000000..f84f7642 --- /dev/null +++ b/src/core/task/TaskState.ts @@ -0,0 +1,57 @@ +import { Anthropic } from "@anthropic-ai/sdk" +import { AssistantMessageContent } from "@core/assistant-message" +import { StreamingJsonReplacer } from "@core/assistant-message/diff-json" +import { ClineAskResponse } from "@shared/WebviewMessage" + +export class TaskState { + // Streaming flags + isStreaming = false + isWaitingForFirstChunk = false + didCompleteReadingStream = false + + // Content processing + currentStreamingContentIndex = 0 + assistantMessageContent: AssistantMessageContent[] = [] + userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = [] + userMessageContentReady = false + + // Presentation locks + presentAssistantMessageLocked = false + presentAssistantMessageHasPendingUpdates = false + + // Claude 4 experimental JSON streaming + streamingJsonReplacer?: StreamingJsonReplacer + lastProcessedJsonLength: number = 0 + + // Ask/Response handling + askResponse?: ClineAskResponse + askResponseText?: string + askResponseImages?: string[] + askResponseFiles?: string[] + lastMessageTs?: number + + // Plan mode specific state + isAwaitingPlanResponse = false + didRespondToPlanAskBySwitchingMode = false + + // Tool execution flags + didRejectTool = false + didAlreadyUseTool = false + didEditFile: boolean = false + + // Consecutive request tracking + consecutiveAutoApprovedRequestsCount: number = 0 + + // Error tracking + consecutiveMistakeCount: number = 0 + didAutomaticallyRetryFailedApiRequest = false + checkpointTrackerErrorMessage?: string + + // Task Initialization + isInitialized = false + + // Task Abort / Cancellation + abort: boolean = false + didFinishAbortingStream = false + abandoned = false +} diff --git a/src/core/task/index.ts b/src/core/task/index.ts index 9b1cfdda..b9fc2b0c 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -6,7 +6,6 @@ import os from "os" import pTimeout from "p-timeout" import pWaitFor from "p-wait-for" import * as path from "path" -import { serializeError } from "serialize-error" import * as vscode from "vscode" import { Logger } from "@services/logging/Logger" import { ApiHandler, buildApiHandler } from "@api/index" @@ -111,6 +110,9 @@ import { processFilesIntoText } from "@integrations/misc/extract-text" import { StreamingJsonReplacer, ChangeLocation } from "@core/assistant-message/diff-json" import { isClaude4ModelFamily } from "@utils/model-utils" import { MessageStateHandler } from "./message-state" +import { formatErrorWithStatusCode, showNotificationForApprovalIfAutoApprovalEnabled, updateApiReqMsg } from "./utils" +import { serializeError } from "serialize-error" +import { TaskState } from "./TaskState" export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false @@ -121,68 +123,49 @@ type ToolResponse = string | Array export class Task { - private streamingJsonReplacer?: StreamingJsonReplacer - private lastProcessedJsonLength: number = 0 + // Core task variables + readonly taskId: string + private taskIsFavorited?: boolean - // dependencies + taskState: TaskState + + // Task configuration + private enableCheckpoints: boolean + + // Core dependencies private context: vscode.ExtensionContext private mcpHub: McpHub private workspaceTracker: WorkspaceTracker + + // Service handlers + api: ApiHandler + terminalManager: TerminalManager + private urlContentFetcher: UrlContentFetcher + browserSession: BrowserSession + contextManager: ContextManager + private diffViewProvider: DiffViewProvider + private checkpointTracker?: CheckpointTracker + private clineIgnoreController: ClineIgnoreController + + // Metadata tracking + private fileContextTracker: FileContextTracker + private modelContextTracker: ModelContextTracker + + // Callbacks private updateTaskHistory: (historyItem: HistoryItem) => Promise private postStateToWebview: () => Promise private postMessageToWebview: (message: ExtensionMessage) => Promise private reinitExistingTaskFromId: (taskId: string) => Promise private cancelTask: () => Promise - readonly taskId: string - private taskIsFavorited?: boolean - api: ApiHandler - terminalManager: TerminalManager - private urlContentFetcher: UrlContentFetcher - browserSession: BrowserSession - contextManager: ContextManager - private didEditFile: boolean = false + // User chat state autoApprovalSettings: AutoApprovalSettings browserSettings: BrowserSettings chatSettings: ChatSettings - private clineIgnoreController: ClineIgnoreController - private askResponse?: ClineAskResponse - private askResponseText?: string - private askResponseImages?: string[] - private askResponseFiles?: string[] - private lastMessageTs?: number - private consecutiveAutoApprovedRequestsCount: number = 0 - private consecutiveMistakeCount: number = 0 - private abort: boolean = false - didFinishAbortingStream = false - abandoned = false - private diffViewProvider: DiffViewProvider - private checkpointTracker?: CheckpointTracker - checkpointTrackerErrorMessage?: string - conversationHistoryDeletedRange?: [number, number] - isInitialized = false - isAwaitingPlanResponse = false - didRespondToPlanAskBySwitchingMode = false - // Metadata tracking - private fileContextTracker: FileContextTracker - private modelContextTracker: ModelContextTracker - - // streaming - isWaitingForFirstChunk = false - isStreaming = false - private currentStreamingContentIndex = 0 - private assistantMessageContent: AssistantMessageContent[] = [] - private presentAssistantMessageLocked = false - private presentAssistantMessageHasPendingUpdates = false - private userMessageContent: (Anthropic.TextBlockParam | Anthropic.ImageBlockParam)[] = [] - private userMessageContentReady = false - private didRejectTool = false - private didAlreadyUseTool = false - private didCompleteReadingStream = false - private didAutomaticallyRetryFailedApiRequest = false - private enableCheckpoints: boolean + // Message and conversation state messageStateHandler: MessageStateHandler + conversationHistoryDeletedRange?: [number, number] constructor( context: vscode.ExtensionContext, @@ -207,6 +190,7 @@ export class Task { files?: string[], historyItem?: HistoryItem, ) { + this.taskState = new TaskState() this.context = context this.mcpHub = mcpHub this.workspaceTracker = workspaceTracker @@ -361,7 +345,7 @@ export class Task { break } - if (!this.checkpointTracker && !this.checkpointTrackerErrorMessage) { + if (!this.checkpointTracker && !this.taskState.checkpointTrackerErrorMessage) { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, @@ -372,7 +356,7 @@ export class Task { } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown error" console.error("Failed to initialize checkpoint tracker:", errorMessage) - this.checkpointTrackerErrorMessage = errorMessage + this.taskState.checkpointTrackerErrorMessage = errorMessage await this.postStateToWebview() vscode.window.showErrorMessage(errorMessage) didWorkspaceRestoreFail = true @@ -521,7 +505,7 @@ export class Task { } // TODO: handle if this is called from outside original workspace, in which case we need to show user error message we can't show diff outside of workspace? - if (!this.checkpointTracker && this.enableCheckpoints && !this.checkpointTrackerErrorMessage) { + if (!this.checkpointTracker && this.enableCheckpoints && !this.taskState.checkpointTrackerErrorMessage) { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, @@ -532,7 +516,7 @@ export class Task { } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown error" console.error("Failed to initialize checkpoint tracker:", errorMessage) - this.checkpointTrackerErrorMessage = errorMessage + this.taskState.checkpointTrackerErrorMessage = errorMessage await this.postStateToWebview() vscode.window.showErrorMessage(errorMessage) relinquishButton() @@ -643,7 +627,7 @@ export class Task { return false } - if (this.enableCheckpoints && !this.checkpointTracker && !this.checkpointTrackerErrorMessage) { + if (this.enableCheckpoints && !this.checkpointTracker && !this.taskState.checkpointTrackerErrorMessage) { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, @@ -710,7 +694,7 @@ export class Task { files?: string[] }> { // If this Cline instance was aborted by the provider, then the only thing keeping us alive is a promise still running in the background, in which case we don't want to send its result to the webview as it is attached to a new instance of Cline now. So we can safely ignore the result of any active promises, and this class will be deallocated. (Although we set Cline = undefined in provider, that simply removes the reference to this instance, but the instance is still alive until this promise resolves or rejects.) - if (this.abort) { + if (this.taskState.abort) { throw new Error("Cline instance aborted") } let askTs: number @@ -739,7 +723,7 @@ export class Task { // this.askResponseText = undefined // this.askResponseImages = undefined askTs = Date.now() - this.lastMessageTs = askTs + this.taskState.lastMessageTs = askTs await this.messageStateHandler.addToClineMessages({ ts: askTs, type: "ask", @@ -754,10 +738,10 @@ export class Task { // partial=false means its a complete version of a previously partial message if (isUpdatingPreviousPartial) { // this is the complete version of a previously partial message, so replace the partial with the complete version - this.askResponse = undefined - this.askResponseText = undefined - this.askResponseImages = undefined - this.askResponseFiles = undefined + this.taskState.askResponse = undefined + this.taskState.askResponseText = undefined + this.taskState.askResponseImages = undefined + this.taskState.askResponseFiles = undefined /* Bug for the history books: @@ -766,7 +750,7 @@ export class Task { So in this case we must make sure that the message ts is never altered after first setting it. */ askTs = lastMessage.ts - this.lastMessageTs = askTs + this.taskState.lastMessageTs = askTs // lastMessage.ts = askTs await this.messageStateHandler.updateClineMessage(lastMessageIndex, { text, @@ -777,12 +761,12 @@ export class Task { await sendPartialMessageEvent(protoMessage) } else { // this is a new partial=false message, so add it like normal - this.askResponse = undefined - this.askResponseText = undefined - this.askResponseImages = undefined - this.askResponseFiles = undefined + this.taskState.askResponse = undefined + this.taskState.askResponseText = undefined + this.taskState.askResponseImages = undefined + this.taskState.askResponseFiles = undefined askTs = Date.now() - this.lastMessageTs = askTs + this.taskState.lastMessageTs = askTs await this.messageStateHandler.addToClineMessages({ ts: askTs, type: "ask", @@ -795,12 +779,12 @@ export class Task { } else { // this is a new non-partial message, so add it like normal // const lastMessage = this.clineMessages.at(-1) - this.askResponse = undefined - this.askResponseText = undefined - this.askResponseImages = undefined - this.askResponseFiles = undefined + this.taskState.askResponse = undefined + this.taskState.askResponseText = undefined + this.taskState.askResponseImages = undefined + this.taskState.askResponseFiles = undefined askTs = Date.now() - this.lastMessageTs = askTs + this.taskState.lastMessageTs = askTs await this.messageStateHandler.addToClineMessages({ ts: askTs, type: "ask", @@ -810,32 +794,34 @@ export class Task { await this.postStateToWebview() } - await pWaitFor(() => this.askResponse !== undefined || this.lastMessageTs !== askTs, { interval: 100 }) - if (this.lastMessageTs !== askTs) { + await pWaitFor(() => this.taskState.askResponse !== undefined || this.taskState.lastMessageTs !== askTs, { + interval: 100, + }) + if (this.taskState.lastMessageTs !== askTs) { throw new Error("Current ask promise was ignored") // could happen if we send multiple asks in a row i.e. with command_output. It's important that when we know an ask could fail, it is handled gracefully } const result = { - response: this.askResponse!, - text: this.askResponseText, - images: this.askResponseImages, - files: this.askResponseFiles, + response: this.taskState.askResponse!, + text: this.taskState.askResponseText, + images: this.taskState.askResponseImages, + files: this.taskState.askResponseFiles, } - this.askResponse = undefined - this.askResponseText = undefined - this.askResponseImages = undefined - this.askResponseFiles = undefined + this.taskState.askResponse = undefined + this.taskState.askResponseText = undefined + this.taskState.askResponseImages = undefined + this.taskState.askResponseFiles = undefined return result } async handleWebviewAskResponse(askResponse: ClineAskResponse, text?: string, images?: string[], files?: string[]) { - this.askResponse = askResponse - this.askResponseText = text - this.askResponseImages = images - this.askResponseFiles = files + this.taskState.askResponse = askResponse + this.taskState.askResponseText = text + this.taskState.askResponseImages = images + this.taskState.askResponseFiles = files } async say(type: ClineSay, text?: string, images?: string[], files?: string[], partial?: boolean): Promise { - if (this.abort) { + if (this.taskState.abort) { throw new Error("Cline instance aborted") } @@ -855,7 +841,7 @@ export class Task { } else { // this is a new partial message, so add it with partial state const sayTs = Date.now() - this.lastMessageTs = sayTs + this.taskState.lastMessageTs = sayTs await this.messageStateHandler.addToClineMessages({ ts: sayTs, type: "say", @@ -871,7 +857,7 @@ export class Task { // partial=false means its a complete version of a previously partial message if (isUpdatingPreviousPartial) { // this is the complete version of a previously partial message, so replace the partial with the complete version - this.lastMessageTs = lastMessage.ts + this.taskState.lastMessageTs = lastMessage.ts // lastMessage.ts = sayTs lastMessage.text = text lastMessage.images = images @@ -886,7 +872,7 @@ export class Task { } else { // this is a new partial=false message, so add it like normal const sayTs = Date.now() - this.lastMessageTs = sayTs + this.taskState.lastMessageTs = sayTs await this.messageStateHandler.addToClineMessages({ ts: sayTs, type: "say", @@ -901,7 +887,7 @@ export class Task { } else { // this is a new non-partial message, so add it like normal const sayTs = Date.now() - this.lastMessageTs = sayTs + this.taskState.lastMessageTs = sayTs await this.messageStateHandler.addToClineMessages({ ts: sayTs, type: "say", @@ -951,7 +937,7 @@ export class Task { await this.say("text", task, images, files) - this.isInitialized = true + this.taskState.isInitialized = true let imageBlocks: Anthropic.ImageBlockParam[] = formatResponse.imageBlocks(images) @@ -1038,7 +1024,7 @@ export class Task { askType = "resume_task" } - this.isInitialized = true + this.taskState.isInitialized = true const { response, text, images, files } = await this.ask(askType) // calls poststatetowebview let responseText: string | undefined @@ -1161,7 +1147,7 @@ export class Task { private async initiateTaskLoop(userContent: UserContent): Promise { let nextUserContent = userContent let includeFileDetails = true - while (!this.abort) { + while (!this.taskState.abort) { const didEndLoop = await this.recursivelyMakeClineRequests(nextUserContent, includeFileDetails) includeFileDetails = false // we only need file details the first time @@ -1184,13 +1170,13 @@ export class Task { text: formatResponse.noToolsUsed(), }, ] - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ } } } async abortTask() { - this.abort = true // will stop any autonomously running promises + this.taskState.abort = true // will stop any autonomously running promises this.terminalManager.disposeAll() this.urlContentFetcher.closeBrowser() await this.browserSession.dispose() @@ -1224,7 +1210,7 @@ export class Task { } // Initialize checkpoint tracker if it doesn't exist - if (!this.checkpointTracker && !this.checkpointTrackerErrorMessage) { + if (!this.checkpointTracker && !this.taskState.checkpointTrackerErrorMessage) { try { this.checkpointTracker = await CheckpointTracker.create( this.taskId, @@ -1234,7 +1220,7 @@ export class Task { } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown error" console.error("Failed to initialize checkpoint tracker:", errorMessage) - this.checkpointTrackerErrorMessage = errorMessage + this.taskState.checkpointTrackerErrorMessage = errorMessage await this.postStateToWebview() return } @@ -1617,14 +1603,6 @@ export class Task { } } - private formatErrorWithStatusCode(error: any): string { - const statusCode = error.status || error.statusCode || (error.response && error.response.status) - const message = error.message ?? JSON.stringify(serializeError(error), null, 2) - - // Only prepend the statusCode if it's not already part of the message - return statusCode && !message.includes(statusCode.toString()) ? `${statusCode} - ${message}` : message - } - /** * Migrates the disableBrowserTool setting from VSCode configuration to browserSettings */ @@ -1733,17 +1711,17 @@ export class Task { try { // awaiting first chunk to see if it will throw an error - this.isWaitingForFirstChunk = true + this.taskState.isWaitingForFirstChunk = true const firstChunk = await iterator.next() yield firstChunk.value - this.isWaitingForFirstChunk = false + this.taskState.isWaitingForFirstChunk = false } catch (error) { const isOpenRouter = this.api instanceof OpenRouterHandler || this.api instanceof ClineHandler const isAnthropic = this.api instanceof AnthropicHandler const isOpenRouterContextWindowError = checkIsOpenRouterContextWindowError(error) && isOpenRouter const isAnthropicContextWindowError = checkIsAnthropicContextWindowError(error) && isAnthropic - if (isAnthropic && isAnthropicContextWindowError && !this.didAutomaticallyRetryFailedApiRequest) { + if (isAnthropic && isAnthropicContextWindowError && !this.taskState.didAutomaticallyRetryFailedApiRequest) { this.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange( this.messageStateHandler.getApiConversationHistory(), this.conversationHistoryDeletedRange, @@ -1755,8 +1733,8 @@ export class Task { await ensureTaskDirectoryExists(this.getContext(), this.taskId), ) - this.didAutomaticallyRetryFailedApiRequest = true - } else if (isOpenRouter && !this.didAutomaticallyRetryFailedApiRequest) { + this.taskState.didAutomaticallyRetryFailedApiRequest = true + } else if (isOpenRouter && !this.taskState.didAutomaticallyRetryFailedApiRequest) { if (isOpenRouterContextWindowError) { this.conversationHistoryDeletedRange = this.contextManager.getNextTruncationRange( this.messageStateHandler.getApiConversationHistory(), @@ -1772,7 +1750,7 @@ export class Task { console.log("first chunk failed, waiting 1 second before retrying") await setTimeoutPromise(1000) - this.didAutomaticallyRetryFailedApiRequest = true + this.taskState.didAutomaticallyRetryFailedApiRequest = true } else { // request failed after retrying automatically once, ask user if they want to retry again // note that this api_req_failed ask is unique in that we only present this option if the api hasn't streamed any content yet (ie it fails on the first chunk due), as it would allow them to hit a retry button. However if the api failed mid-stream, it could be in any arbitrary state where some tools may have executed, so that error is handled differently and requires cancelling the task entirely. @@ -1787,11 +1765,11 @@ export class Task { // ToDo: Allow the user to change their input if this is the case. if (truncatedConversationHistory.length > 3) { error = new Error("Context window exceeded. Click retry to truncate the conversation and try again.") - this.didAutomaticallyRetryFailedApiRequest = false + this.taskState.didAutomaticallyRetryFailedApiRequest = false } } - const errorMessage = this.formatErrorWithStatusCode(error) + const errorMessage = formatErrorWithStatusCode(error) // Update the 'api_req_started' message to reflect final failure before asking user to manually retry const lastApiReqStartedIndex = findLastIndex( @@ -1840,10 +1818,10 @@ export class Task { currentFullJson: string, ): Promise<{ shouldBreak: boolean; newContent?: string; error?: string }> { // Calculate the delta - what's new since last time - const newJsonChunk = currentFullJson.substring(this.lastProcessedJsonLength) + const newJsonChunk = currentFullJson.substring(this.taskState.lastProcessedJsonLength) if (block.partial) { // Initialize on first chunk - if (!this.streamingJsonReplacer) { + if (!this.taskState.streamingJsonReplacer) { if (!this.diffViewProvider.isEditing) { await this.diffViewProvider.open(relPath) } @@ -1858,42 +1836,42 @@ export class Task { console.error("StreamingJsonReplacer error:", error) console.log("Failed StreamingJsonReplacer update:") // Handle error: push tool result, cleanup - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: formatResponse.toolError(`JSON replacement error: ${error.message}`), }) - this.didAlreadyUseTool = true - this.userMessageContentReady = true - this.streamingJsonReplacer = undefined - this.lastProcessedJsonLength = 0 + this.taskState.didAlreadyUseTool = true + this.taskState.userMessageContentReady = true + this.taskState.streamingJsonReplacer = undefined + this.taskState.lastProcessedJsonLength = 0 throw error } - this.streamingJsonReplacer = new StreamingJsonReplacer( + this.taskState.streamingJsonReplacer = new StreamingJsonReplacer( this.diffViewProvider.originalContent || "", onContentUpdated, onError, ) - this.lastProcessedJsonLength = 0 + this.taskState.lastProcessedJsonLength = 0 } // Feed only the new chunk if (newJsonChunk.length > 0) { try { - this.streamingJsonReplacer.write(newJsonChunk) - this.lastProcessedJsonLength = currentFullJson.length + this.taskState.streamingJsonReplacer.write(newJsonChunk) + this.taskState.lastProcessedJsonLength = currentFullJson.length } catch (e) { // Handle write error return { shouldBreak: true, error: `Write error: ${e}` } } - const newContentParsed = this.streamingJsonReplacer.getSuccessfullyParsedItems() + const newContentParsed = this.taskState.streamingJsonReplacer.getSuccessfullyParsedItems() } return { shouldBreak: true } // Wait for more chunks } else { // Final chunk (!block.partial) - if (!this.streamingJsonReplacer) { + if (!this.taskState.streamingJsonReplacer) { // JSON came all at once, initialize if (!this.diffViewProvider.isEditing) { await this.diffViewProvider.open(relPath) @@ -1908,30 +1886,30 @@ export class Task { const onError = (error: Error) => { console.error("StreamingJsonReplacer error:", error) // Handle error - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: formatResponse.toolError(`JSON replacement error: ${error.message}`), }) - this.didAlreadyUseTool = true - this.userMessageContentReady = true + this.taskState.didAlreadyUseTool = true + this.taskState.userMessageContentReady = true throw error } - this.streamingJsonReplacer = new StreamingJsonReplacer( + this.taskState.streamingJsonReplacer = new StreamingJsonReplacer( this.diffViewProvider.originalContent || "", onContentUpdated, onError, ) // Write the entire JSON at once - this.streamingJsonReplacer.write(currentFullJson) + this.taskState.streamingJsonReplacer.write(currentFullJson) // Get the final content - const newContent = this.streamingJsonReplacer.getCurrentContent() + const newContent = this.taskState.streamingJsonReplacer.getCurrentContent() // Cleanup - this.streamingJsonReplacer = undefined - this.lastProcessedJsonLength = 0 + this.taskState.streamingJsonReplacer = undefined + this.taskState.lastProcessedJsonLength = 0 // Update diff view with final content await this.diffViewProvider.update(newContent, true) @@ -1941,17 +1919,17 @@ export class Task { // Feed final delta if (newJsonChunk.length > 0) { - this.streamingJsonReplacer.write(newJsonChunk) + this.taskState.streamingJsonReplacer.write(newJsonChunk) } - const newContent = this.streamingJsonReplacer.getCurrentContent() + const newContent = this.taskState.streamingJsonReplacer.getCurrentContent() // Get final list of replacements - const allReplacements = this.streamingJsonReplacer.getSuccessfullyParsedItems() + const allReplacements = this.taskState.streamingJsonReplacer.getSuccessfullyParsedItems() // Cleanup - this.streamingJsonReplacer = undefined - this.lastProcessedJsonLength = 0 + this.taskState.streamingJsonReplacer = undefined + this.taskState.lastProcessedJsonLength = 0 // Update diff view with final content await this.diffViewProvider.update(newContent, true) @@ -1961,31 +1939,31 @@ export class Task { } async presentAssistantMessage() { - if (this.abort) { + if (this.taskState.abort) { throw new Error("Cline instance aborted") } - if (this.presentAssistantMessageLocked) { - this.presentAssistantMessageHasPendingUpdates = true + if (this.taskState.presentAssistantMessageLocked) { + this.taskState.presentAssistantMessageHasPendingUpdates = true return } - this.presentAssistantMessageLocked = true - this.presentAssistantMessageHasPendingUpdates = false + this.taskState.presentAssistantMessageLocked = true + this.taskState.presentAssistantMessageHasPendingUpdates = false - if (this.currentStreamingContentIndex >= this.assistantMessageContent.length) { + if (this.taskState.currentStreamingContentIndex >= this.taskState.assistantMessageContent.length) { // this may happen if the last content block was completed before streaming could finish. if streaming is finished, and we're out of bounds then this means we already presented/executed the last content block and are ready to continue to next request - if (this.didCompleteReadingStream) { - this.userMessageContentReady = true + if (this.taskState.didCompleteReadingStream) { + this.taskState.userMessageContentReady = true } - this.presentAssistantMessageLocked = false + this.taskState.presentAssistantMessageLocked = false return //throw new Error("No more content blocks to stream! This shouldn't happen...") // remove and just return after testing } - const block = cloneDeep(this.assistantMessageContent[this.currentStreamingContentIndex]) // need to create copy bc while stream is updating the array, it could be updating the reference block properties too + const block = cloneDeep(this.taskState.assistantMessageContent[this.taskState.currentStreamingContentIndex]) // need to create copy bc while stream is updating the array, it could be updating the reference block properties too switch (block.type) { case "text": { - if (this.didRejectTool || this.didAlreadyUseTool) { + if (this.taskState.didRejectTool || this.taskState.didAlreadyUseTool) { break } let content = block.content @@ -2086,16 +2064,16 @@ export class Task { } } - if (this.didRejectTool) { + if (this.taskState.didRejectTool) { // ignore any tool content after user has rejected tool once if (!block.partial) { - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: `Skipping tool ${toolDescription()} due to user rejecting a previous tool.`, }) } else { // partial tool after user rejected a previous tool - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: `Tool ${toolDescription()} was interrupted and not executed due to user rejecting a previous tool.`, }) @@ -2103,9 +2081,9 @@ export class Task { break } - if (this.didAlreadyUseTool) { + if (this.taskState.didAlreadyUseTool) { // ignore any content after a tool has already been used - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: formatResponse.toolAlreadyUsed(block.name), }) @@ -2118,26 +2096,26 @@ export class Task { if (isClaude4Model && USE_EXPERIMENTAL_CLAUDE4_FEATURES) { // Claude 4 family: Use function_results format - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: `\n${resultText}\n`, }) } else { // Non-Claude 4: Use traditional format with header - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: `${toolDescription()} Result:`, }) - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: resultText, }) } } else { - this.userMessageContent.push(...content) + this.taskState.userMessageContent.push(...content) } // once a tool result has been collected, ignore all other tool uses since we should only ever present one tool result per message - this.didAlreadyUseTool = true + this.taskState.didAlreadyUseTool = true } // The user can approve, reject, or provide feedback (rejection). However the user may also send a message along with an approval, in which case we add a separate user message with this feedback. @@ -2151,12 +2129,12 @@ export class Task { fileContentString, ) if (typeof content === "string") { - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: content, }) } else { - this.userMessageContent.push(...content) + this.taskState.userMessageContent.push(...content) } } @@ -2175,7 +2153,7 @@ export class Task { await this.say("user_feedback", text, images, files) await this.saveCheckpoint() } - this.didRejectTool = true // Prevent further tool uses in this message + this.taskState.didRejectTool = true // Prevent further tool uses in this message return false } else { // User hit the approve button, and may have provided feedback @@ -2193,17 +2171,8 @@ export class Task { } } - const showNotificationForApprovalIfAutoApprovalEnabled = (message: string) => { - if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { - showSystemNotification({ - subtitle: "Approval Required", - message, - }) - } - } - const handleError = async (action: string, error: Error, isClaude4Model: boolean = false) => { - if (this.abandoned) { + if (this.taskState.abandoned) { console.log("Ignoring error since task was abandoned (i.e. from task cancellation after resetting)") return } @@ -2294,7 +2263,6 @@ export class Task { const isClaude4Model = isClaude4ModelFamily(this.api) // Going through claude family of models if (isClaude4Model && USE_EXPERIMENTAL_CLAUDE4_FEATURES && currentFullJson) { - console.log("[EDIT] Streaming JSON replacement") const streamingResult = await this.handleStreamingJsonReplacement( block, relPath, @@ -2402,35 +2370,35 @@ export class Task { break } else { if (!relPath) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError(block.name, "path")) await this.diffViewProvider.reset() await this.saveCheckpoint() break } if (block.name === "replace_in_file" && !diff) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("replace_in_file", "diff")) await this.diffViewProvider.reset() await this.saveCheckpoint() break } if (block.name === "write_to_file" && !content) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("write_to_file", "content")) await this.diffViewProvider.reset() await this.saveCheckpoint() break } if (block.name === "new_rule" && !content) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("new_rule", "content")) await this.diffViewProvider.reset() await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 // if isEditingFile false, that means we have the full contents of the file already. // it's important to note how this function works, you can't make the assumption that the block.partial conditional will always be called since it may immediately get complete, non-partial data. So this part of the logic will always be called. @@ -2460,7 +2428,7 @@ export class Task { if (this.shouldAutoApproveToolWithPath(block.name, relPath)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) // we need an artificial delay to let the diagnostics catch up to the changes @@ -2469,6 +2437,8 @@ export class Task { // If auto-approval is enabled but this tool wasn't auto-approved, send notification showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to ${fileExists ? "edit" : "create"} ${path.basename(relPath)}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "tool") @@ -2497,7 +2467,7 @@ export class Task { await this.say("user_feedback", text, images, askFiles) await this.saveCheckpoint() } - this.didRejectTool = true + this.taskState.didRejectTool = true didApprove = false telemetryService.captureToolUsage( this.taskId, @@ -2539,7 +2509,7 @@ export class Task { const { newProblemsMessage, userEdits, autoFormattingEdits, finalContent } = await this.diffViewProvider.saveChanges() - this.didEditFile = true // used to determine if we should wait for busy terminal to update before sending api request + this.taskState.didEditFile = true // used to determine if we should wait for busy terminal to update before sending api request // Track file edit operation await this.fileContextTracker.trackFileContext(relPath, "cline_edited") @@ -2617,7 +2587,7 @@ export class Task { break } else { if (!relPath) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("read_file", "path")) await this.saveCheckpoint() break @@ -2631,7 +2601,7 @@ export class Task { break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const absolutePath = path.resolve(cwd, relPath) const completeMessage = JSON.stringify({ ...sharedMessageProps, @@ -2641,11 +2611,13 @@ export class Task { if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) // need to be sending partialValue bool, since undefined has its own purpose in that the message is treated neither as a partial or completion of a partial, but as a single complete message - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to read ${path.basename(absolutePath)}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await askApproval("tool", completeMessage) @@ -2710,12 +2682,12 @@ export class Task { break } else { if (!relDirPath) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("list_files", "path"), isClaude4Model) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const absolutePath = path.resolve(cwd, relDirPath) @@ -2735,11 +2707,13 @@ export class Task { if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to view directory ${path.basename(absolutePath)}/`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await askApproval("tool", completeMessage) @@ -2795,13 +2769,13 @@ export class Task { break } else { if (!relDirPath) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("list_code_definition_names", "path")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const absolutePath = path.resolve(cwd, relDirPath) const result = await parseSourceCodeForDefinitionsTopLevel( @@ -2817,11 +2791,13 @@ export class Task { if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to view source code definitions in ${path.basename(absolutePath)}/`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await askApproval("tool", completeMessage) @@ -2882,7 +2858,7 @@ export class Task { break } else { if (!relDirPath) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult( await this.sayAndCreateMissingParamError("search_files", "path"), isClaude4Model, @@ -2891,7 +2867,7 @@ export class Task { break } if (!regex) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult( await this.sayAndCreateMissingParamError("search_files", "regex"), isClaude4Model, @@ -2899,7 +2875,7 @@ export class Task { await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const absolutePath = path.resolve(cwd, relDirPath) const results = await regexSearchFiles( @@ -2918,11 +2894,13 @@ export class Task { if (this.shouldAutoApproveToolWithPath(block.name, block.params.path)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage(this.taskId, block.name, this.api.getModel().id, true, true) } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to search files in ${path.basename(absolutePath)}/`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await askApproval("tool", completeMessage) @@ -2964,7 +2942,7 @@ export class Task { // checking for action to ensure it is complete and valid if (!block.partial) { // if the block is complete and we don't have a valid action this is a mistake - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("browser_action", "action")) await this.browserSession.closeBrowser() await this.saveCheckpoint() @@ -3010,21 +2988,23 @@ export class Task { let browserActionResult: BrowserActionResult if (action === "launch") { if (!url) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("browser_action", "url")) await this.browserSession.closeBrowser() await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 if (this.shouldAutoApproveTool(block.name)) { this.removeLastPartialMessageIfExistsWithType("ask", "browser_action_launch") await this.say("browser_action_launch", url, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to use a browser and launch ${url}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "browser_action_launch") const didApprove = await askApproval("browser_action_launch", url) @@ -3050,7 +3030,7 @@ export class Task { } else { if (action === "click") { if (!coordinate) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult( await this.sayAndCreateMissingParamError("browser_action", "coordinate"), ) @@ -3061,14 +3041,14 @@ export class Task { } if (action === "type") { if (!text) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("browser_action", "text")) await this.browserSession.closeBrowser() await this.saveCheckpoint() break } } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 await this.say( "browser_action", JSON.stringify({ @@ -3157,20 +3137,20 @@ export class Task { break } else { if (!command) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("execute_command", "command")) await this.saveCheckpoint() break } if (!requiresApprovalRaw) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult( await this.sayAndCreateMissingParamError("execute_command", "requires_approval"), ) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 // gemini models tend to use unescaped html entities in commands if (this.api.getModel().id.includes("gemini")) { @@ -3202,11 +3182,13 @@ export class Task { ) { this.removeLastPartialMessageIfExistsWithType("ask", "command") await this.say("command", command, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ didAutoApprove = true } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to execute a command: ${command}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) // this.removeLastPartialMessageIfExistsWithType("say", "command") const didApprove = await askApproval( @@ -3237,7 +3219,7 @@ export class Task { clearTimeout(timeoutId) } if (userRejected) { - this.didRejectTool = true + this.taskState.didRejectTool = true } // Re-populate file paths in case the command modified the workspace (vscode listeners do not trigger unless the user manually creates/deletes files) @@ -3279,13 +3261,13 @@ export class Task { break } else { if (!server_name) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("use_mcp_tool", "server_name")) await this.saveCheckpoint() break } if (!tool_name) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("use_mcp_tool", "tool_name")) await this.saveCheckpoint() break @@ -3301,7 +3283,7 @@ export class Task { try { parsedArguments = JSON.parse(mcp_arguments) } catch (error) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ await this.say( "error", `Cline tried to use ${tool_name} with an invalid JSON argument. Retrying...`, @@ -3315,7 +3297,7 @@ export class Task { break } } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const completeMessage = JSON.stringify({ type: "use_mcp_tool", serverName: server_name, @@ -3330,10 +3312,12 @@ export class Task { if (this.shouldAutoApproveTool(block.name) && isToolAutoApproved) { this.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") await this.say("use_mcp_server", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to use ${tool_name} on ${server_name}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") const didApprove = await askApproval("use_mcp_server", completeMessage) @@ -3429,18 +3413,18 @@ export class Task { break } else { if (!server_name) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("access_mcp_resource", "server_name")) await this.saveCheckpoint() break } if (!uri) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("access_mcp_resource", "uri")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const completeMessage = JSON.stringify({ type: "access_mcp_resource", serverName: server_name, @@ -3450,10 +3434,12 @@ export class Task { if (this.shouldAutoApproveTool(block.name)) { this.removeLastPartialMessageIfExistsWithType("ask", "use_mcp_server") await this.say("use_mcp_server", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ } else { showNotificationForApprovalIfAutoApprovalEnabled( `Cline wants to access ${uri} on ${server_name}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, ) this.removeLastPartialMessageIfExistsWithType("say", "use_mcp_server") const didApprove = await askApproval("use_mcp_server", completeMessage) @@ -3500,12 +3486,12 @@ export class Task { break } else { if (!question) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("ask_followup_question", "question")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { showSystemNotification({ @@ -3569,12 +3555,12 @@ export class Task { break } else { if (!context) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("new_task", "context")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { showSystemNotification({ @@ -3623,12 +3609,12 @@ export class Task { break } else { if (!context) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("condense", "context")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { showSystemNotification({ @@ -3706,37 +3692,37 @@ export class Task { break } else { if (!title) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "title")) await this.saveCheckpoint() break } if (!what_happened) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "what_happened")) await this.saveCheckpoint() break } if (!steps_to_reproduce) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "steps_to_reproduce")) await this.saveCheckpoint() break } if (!api_request_output) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "api_request_output")) await this.saveCheckpoint() break } if (!additional_context) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("report_bug", "additional_context")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { showSystemNotification({ @@ -3847,13 +3833,13 @@ export class Task { break } else { if (!url) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("web_fetch", "url")) await this.saveCheckpoint() break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 const completeMessage = JSON.stringify({ ...sharedMessageProps, operationIsLocatedInWorkspace: false, @@ -3862,7 +3848,7 @@ export class Task { if (this.shouldAutoApproveTool("web_fetch" as ToolUseName)) { this.removeLastPartialMessageIfExistsWithType("ask", "tool") await this.say("tool", completeMessage, undefined, undefined, false) - this.consecutiveAutoApprovedRequestsCount++ + this.taskState.consecutiveAutoApprovedRequestsCount++ telemetryService.captureToolUsage( this.taskId, "web_fetch" as ToolUseName, @@ -3871,7 +3857,11 @@ export class Task { true, ) } else { - showNotificationForApprovalIfAutoApprovalEnabled(`Cline wants to fetch content from ${url}`) + showNotificationForApprovalIfAutoApprovalEnabled( + `Cline wants to fetch content from ${url}`, + this.autoApprovalSettings.enabled, + this.autoApprovalSettings.enableNotifications, + ) this.removeLastPartialMessageIfExistsWithType("say", "tool") const didApprove = await askApproval("tool", completeMessage) if (!didApprove) { @@ -3929,12 +3919,12 @@ export class Task { break } else { if (!response) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("plan_mode_respond", "response")) // break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 // if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { // showSystemNotification({ @@ -3946,13 +3936,13 @@ export class Task { // Store the number of options for telemetry const options = parsePartialArrayString(optionsRaw || "[]") - this.isAwaitingPlanResponse = true + this.taskState.isAwaitingPlanResponse = true let { text, images, files: planResponseFiles, } = await this.ask("plan_mode_respond", JSON.stringify(sharedMessage), false) - this.isAwaitingPlanResponse = false + this.taskState.isAwaitingPlanResponse = false // webview invoke sendMessage will send this marker in order to put webview into the proper state (responding to an ask) and as a flag to extension that the user switched to ACT mode. if (text === "PLAN_MODE_TOGGLE_RESPONSE") { @@ -3992,7 +3982,7 @@ export class Task { fileContentString = await processFilesIntoText(planResponseFiles) } - if (this.didRespondToPlanAskBySwitchingMode) { + if (this.taskState.didRespondToPlanAskBySwitchingMode) { pushToolResult( formatResponse.toolResult( `[The user has switched to ACT MODE, so you may now proceed with the task.]` + @@ -4040,7 +4030,7 @@ export class Task { } case "attempt_completion": { /* - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 let resultToSend = result if (command) { await this.say("completion_result", resultToSend) @@ -4079,6 +4069,7 @@ export class Task { : undefined if ( lastCompletionResultMessage && + lastCompletionResultMessageIndex !== -1 && hasNewChanges && !lastCompletionResultMessage.text?.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ) { @@ -4131,11 +4122,11 @@ export class Task { break } else { if (!result) { - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ pushToolResult(await this.sayAndCreateMissingParamError("attempt_completion", "result")) break } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { showSystemNotification({ @@ -4165,7 +4156,7 @@ export class Task { } const [userRejected, execCommandResult] = await this.executeCommandTool(command!) if (userRejected) { - this.didRejectTool = true + this.taskState.didRejectTool = true pushToolResult(execCommandResult) await this.saveCheckpoint() break @@ -4209,11 +4200,11 @@ export class Task { text: `The user has provided feedback on the results. Consider their input to continue the task, and then attempt completion again.\n\n${text}\n`, }) toolResults.push(...formatResponse.imageBlocks(images)) - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: `${toolDescription()} Result:`, }) - this.userMessageContent.push(...toolResults) + this.taskState.userMessageContent.push(...toolResults) let fileContentString = "" if (completionFiles && completionFiles.length > 0) { @@ -4221,7 +4212,7 @@ export class Task { } if (fileContentString) { - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: fileContentString, }) @@ -4244,20 +4235,20 @@ export class Task { Seeing out of bounds is fine, it means that the next too call is being built up and ready to add to assistantMessageContent to present. When you see the UI inactive during this, it means that a tool is breaking without presenting any UI. For example the write_to_file tool was breaking when relpath was undefined, and for invalid relpath it never presented UI. */ - this.presentAssistantMessageLocked = false // this needs to be placed here, if not then calling this.presentAssistantMessage below would fail (sometimes) since it's locked + this.taskState.presentAssistantMessageLocked = false // this needs to be placed here, if not then calling this.presentAssistantMessage below would fail (sometimes) since it's locked // NOTE: when tool is rejected, iterator stream is interrupted and it waits for userMessageContentReady to be true. Future calls to present will skip execution since didRejectTool and iterate until contentIndex is set to message length and it sets userMessageContentReady to true itself (instead of preemptively doing it in iterator) - if (!block.partial || this.didRejectTool || this.didAlreadyUseTool) { + if (!block.partial || this.taskState.didRejectTool || this.taskState.didAlreadyUseTool) { // block is finished streaming and executing - if (this.currentStreamingContentIndex === this.assistantMessageContent.length - 1) { + if (this.taskState.currentStreamingContentIndex === this.taskState.assistantMessageContent.length - 1) { // its okay that we increment if !didCompleteReadingStream, it'll just return bc out of bounds and as streaming continues it will call presentAssistantMessage if a new block is ready. if streaming is finished then we set userMessageContentReady to true when out of bounds. This gracefully allows the stream to continue on and all potential content blocks be presented. // last block is complete and it is finished executing - this.userMessageContentReady = true // will allow pwaitfor to continue + this.taskState.userMessageContentReady = true // will allow pwaitfor to continue } // call next block if it exists (if not then read stream will call it when its ready) - this.currentStreamingContentIndex++ // need to increment regardless, so when read stream calls this function again it will be streaming the next block + this.taskState.currentStreamingContentIndex++ // need to increment regardless, so when read stream calls this function again it will be streaming the next block - if (this.currentStreamingContentIndex < this.assistantMessageContent.length) { + if (this.taskState.currentStreamingContentIndex < this.taskState.assistantMessageContent.length) { // there are already more content blocks to stream, so we'll call this function ourselves // await this.presentAssistantContent() @@ -4266,13 +4257,13 @@ export class Task { } } // block is partial, but the read stream may have finished - if (this.presentAssistantMessageHasPendingUpdates) { + if (this.taskState.presentAssistantMessageHasPendingUpdates) { this.presentAssistantMessage() } } async recursivelyMakeClineRequests(userContent: UserContent, includeFileDetails: boolean = false): Promise { - if (this.abort) { + if (this.taskState.abort) { throw new Error("Cline instance aborted") } @@ -4284,7 +4275,7 @@ export class Task { } catch {} } - if (this.consecutiveMistakeCount >= 3) { + if (this.taskState.consecutiveMistakeCount >= 3) { if (this.autoApprovalSettings.enabled && this.autoApprovalSettings.enableNotifications) { showSystemNotification({ subtitle: "Error", @@ -4322,12 +4313,12 @@ export class Task { userContent = feedbackUserContent } - this.consecutiveMistakeCount = 0 + this.taskState.consecutiveMistakeCount = 0 } if ( this.autoApprovalSettings.enabled && - this.consecutiveAutoApprovedRequestsCount >= this.autoApprovalSettings.maxRequests + this.taskState.consecutiveAutoApprovedRequestsCount >= this.autoApprovalSettings.maxRequests ) { if (this.autoApprovalSettings.enableNotifications) { showSystemNotification({ @@ -4340,7 +4331,7 @@ export class Task { `Cline has auto-approved ${this.autoApprovalSettings.maxRequests.toString()} API requests. Would you like to reset the count and proceed with the task?`, ) // if we get past the promise it means the user approved and did not start a new task - this.consecutiveAutoApprovedRequestsCount = 0 + this.taskState.consecutiveAutoApprovedRequestsCount = 0 } // get previous api req's index to check token usage and determine if we need to truncate conversation history @@ -4359,7 +4350,12 @@ export class Task { ) // Initialize checkpoint tracker first if enabled and it's the first request - if (isFirstRequest && this.enableCheckpoints && !this.checkpointTracker && !this.checkpointTrackerErrorMessage) { + if ( + isFirstRequest && + this.enableCheckpoints && + !this.checkpointTracker && + !this.taskState.checkpointTrackerErrorMessage + ) { try { this.checkpointTracker = await pTimeout( CheckpointTracker.create(this.taskId, this.context.globalStorageUri.fsPath, this.enableCheckpoints), @@ -4372,7 +4368,7 @@ export class Task { } catch (error) { const errorMessage = error instanceof Error ? error.message : "Unknown error" console.error("Failed to initialize checkpoint tracker:", errorMessage) - this.checkpointTrackerErrorMessage = errorMessage // will be displayed right away since we saveClineMessages next which posts state to webview + this.taskState.checkpointTrackerErrorMessage = errorMessage // will be displayed right away since we saveClineMessages next which posts state to webview } } @@ -4393,7 +4389,12 @@ export class Task { // so no need to call it here unless this is the only modification to this message. // For now, assuming it's handled later. } - } else if (isFirstRequest && this.enableCheckpoints && !this.checkpointTracker && this.checkpointTrackerErrorMessage) { + } else if ( + isFirstRequest && + this.enableCheckpoints && + !this.checkpointTracker && + this.taskState.checkpointTrackerErrorMessage + ) { // Checkpoints are enabled, but tracker failed to initialize. // checkpointTrackerErrorMessage is already set and will be part of the state. // No explicit UI message here, error message will be in ExtensionState. @@ -4436,36 +4437,6 @@ export class Task { let outputTokens = 0 let totalCost: number | undefined - // update api_req_started. we can't use api_req_finished anymore since it's a unique case where it could come after a streaming message (ie in the middle of being updated or executed) - // fortunately api_req_finished was always parsed out for the gui anyways, so it remains solely for legacy purposes to keep track of prices in tasks from history - // (it's worth removing a few months from now) - const updateApiReqMsg = async (cancelReason?: ClineApiReqCancelReason, streamingFailedMessage?: string) => { - const clineMessages = this.messageStateHandler.getClineMessages() - const currentApiReqInfo: ClineApiReqInfo = JSON.parse(clineMessages[lastApiReqIndex].text || "{}") - delete currentApiReqInfo.retryStatus // Clear retry status when request is finalized - - await this.messageStateHandler.updateClineMessage(lastApiReqIndex, { - text: JSON.stringify({ - ...currentApiReqInfo, // Spread the modified info (with retryStatus removed) - tokensIn: inputTokens, - tokensOut: outputTokens, - cacheWrites: cacheWriteTokens, - cacheReads: cacheReadTokens, - cost: - totalCost ?? - calculateApiCostAnthropic( - this.api.getModel().info, - inputTokens, - outputTokens, - cacheWriteTokens, - cacheReadTokens, - ), - cancelReason, - streamingFailedMessage, - } satisfies ClineApiReqInfo), - }) - } - const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => { if (this.diffViewProvider.isEditing) { await this.diffViewProvider.revertChanges() // closes diff view @@ -4499,7 +4470,18 @@ export class Task { }) // update api_req_started to have cancelled and cost, so that we can display the cost of the partial stream - await updateApiReqMsg(cancelReason, streamingFailedMessage) + await updateApiReqMsg({ + messageStateHandler: this.messageStateHandler, + lastApiReqIndex, + inputTokens, + outputTokens, + cacheWriteTokens, + cacheReadTokens, + totalCost, + api: this.api, + cancelReason, + streamingFailedMessage, + }) await this.messageStateHandler.saveClineMessagesAndUpdateHistory() telemetryService.captureConversationTurnEvent( @@ -4511,26 +4493,26 @@ export class Task { ) // signals to provider that it can retrieve the saved messages from disk, as abortTask can not be awaited on in nature - this.didFinishAbortingStream = true + this.taskState.didFinishAbortingStream = true } // reset streaming state - this.currentStreamingContentIndex = 0 - this.assistantMessageContent = [] - this.didCompleteReadingStream = false - this.userMessageContent = [] - this.userMessageContentReady = false - this.didRejectTool = false - this.didAlreadyUseTool = false - this.presentAssistantMessageLocked = false - this.presentAssistantMessageHasPendingUpdates = false - this.didAutomaticallyRetryFailedApiRequest = false + this.taskState.currentStreamingContentIndex = 0 + this.taskState.assistantMessageContent = [] + this.taskState.didCompleteReadingStream = false + this.taskState.userMessageContent = [] + this.taskState.userMessageContentReady = false + this.taskState.didRejectTool = false + this.taskState.didAlreadyUseTool = false + this.taskState.presentAssistantMessageLocked = false + this.taskState.presentAssistantMessageHasPendingUpdates = false + this.taskState.didAutomaticallyRetryFailedApiRequest = false await this.diffViewProvider.reset() const stream = this.attemptApiRequest(previousApiReqIndex) // yields only if the first chunk is successful, otherwise will allow the user to retry the request (most likely due to rate limit error, which gets thrown on the first chunk) let assistantMessage = "" let reasoningMessage = "" - this.isStreaming = true + this.taskState.isStreaming = true let didReceiveUsageChunk = false try { for await (const chunk of stream) { @@ -4550,7 +4532,7 @@ export class Task { // reasoning will always come before assistant message reasoningMessage += chunk.reasoning // fixes bug where cancelling task > aborts task > for loop may be in middle of streaming reasoning > say function throws error before we get a chance to properly clean up and cancel the task. - if (!this.abort) { + if (!this.taskState.abort) { await this.say("reasoning", reasoningMessage, undefined, undefined, true) } break @@ -4561,32 +4543,32 @@ export class Task { } assistantMessage += chunk.text // parse raw assistant message into content blocks - const prevLength = this.assistantMessageContent.length + const prevLength = this.taskState.assistantMessageContent.length const isClaude4Model = isClaude4ModelFamily(this.api) if (isClaude4Model && USE_EXPERIMENTAL_CLAUDE4_FEATURES) { - this.assistantMessageContent = parseAssistantMessageV3(assistantMessage) + this.taskState.assistantMessageContent = parseAssistantMessageV3(assistantMessage) } else { - this.assistantMessageContent = parseAssistantMessageV2(assistantMessage) + this.taskState.assistantMessageContent = parseAssistantMessageV2(assistantMessage) } - if (this.assistantMessageContent.length > prevLength) { - this.userMessageContentReady = false // new content we need to present, reset to false in case previous content set this to true + if (this.taskState.assistantMessageContent.length > prevLength) { + this.taskState.userMessageContentReady = false // new content we need to present, reset to false in case previous content set this to true } // present content to user this.presentAssistantMessage() break } - if (this.abort) { + if (this.taskState.abort) { console.log("aborting stream...") - if (!this.abandoned) { + if (!this.taskState.abandoned) { // only need to gracefully abort if this instance isn't abandoned (sometimes openrouter stream hangs, in which case this would affect future instances of cline) await abortStream("user_cancelled") } break // aborts the stream } - if (this.didRejectTool) { + if (this.taskState.didRejectTool) { // userContent has a tool rejection, so interrupt the assistant's response to present the user's feedback assistantMessage += "\n\n[Response interrupted by user feedback]" // this.userMessageContentReady = true // instead of setting this preemptively, we allow the present iterator to finish and set userMessageContentReady when its ready @@ -4595,7 +4577,7 @@ export class Task { // PREV: we need to let the request finish for openrouter to get generation details // UPDATE: it's better UX to interrupt the request at the cost of the api cost not being retrieved - if (this.didAlreadyUseTool) { + if (this.taskState.didAlreadyUseTool) { assistantMessage += "\n\n[Response interrupted by a tool use result. Only one tool may be used at a time and should be placed at the end of the message.]" break @@ -4603,15 +4585,15 @@ export class Task { } } catch (error) { // abandoned happens when extension is no longer waiting for the cline instance to finish aborting (error is thrown here when any function in the for loop throws due to this.abort) - if (!this.abandoned) { + if (!this.taskState.abandoned) { this.abortTask() // if the stream failed, there's various states the task could be in (i.e. could have streamed some tools the user may have executed), so we just resort to replicating a cancel task - const errorMessage = this.formatErrorWithStatusCode(error) + const errorMessage = formatErrorWithStatusCode(error) await abortStream("streaming_failed", errorMessage) await this.reinitExistingTaskFromId(this.taskId) } } finally { - this.isStreaming = false + this.taskState.isStreaming = false } // OpenRouter/Cline may not return token usage as part of the stream (since it may abort early), so we fetch after the stream is finished @@ -4625,22 +4607,31 @@ export class Task { cacheReadTokens += apiStreamUsage.cacheReadTokens ?? 0 totalCost = apiStreamUsage.totalCost } - await updateApiReqMsg() + await updateApiReqMsg({ + messageStateHandler: this.messageStateHandler, + lastApiReqIndex, + inputTokens, + outputTokens, + cacheWriteTokens, + cacheReadTokens, + api: this.api, + totalCost, + }) await this.messageStateHandler.saveClineMessagesAndUpdateHistory() await this.postStateToWebview() }) } // need to call here in case the stream was aborted - if (this.abort) { + if (this.taskState.abort) { throw new Error("Cline instance aborted") } - this.didCompleteReadingStream = true + this.taskState.didCompleteReadingStream = true // set any blocks to be complete to allow presentAssistantMessage to finish and set userMessageContentReady to true // (could be a text block that had no subsequent tool uses, or a text block at the very end, or an invalid tool use, etc. whatever the case, presentAssistantMessage relies on these blocks either to be completed or the user to reject a block in order to proceed and eventually set userMessageContentReady to true) - const partialBlocks = this.assistantMessageContent.filter((block) => block.partial) + const partialBlocks = this.taskState.assistantMessageContent.filter((block) => block.partial) partialBlocks.forEach((block) => { block.partial = false }) @@ -4649,7 +4640,16 @@ export class Task { this.presentAssistantMessage() // if there is content to update then it will complete and update this.userMessageContentReady to true, which we pwaitfor before making the next request. all this is really doing is presenting the last partial message that we just set to complete } - await updateApiReqMsg() + await updateApiReqMsg({ + messageStateHandler: this.messageStateHandler, + lastApiReqIndex, + inputTokens, + outputTokens, + cacheWriteTokens, + cacheReadTokens, + api: this.api, + totalCost, + }) await this.messageStateHandler.saveClineMessagesAndUpdateHistory() await this.postStateToWebview() @@ -4678,21 +4678,21 @@ export class Task { // this.userMessageContentReady = true // } - await pWaitFor(() => this.userMessageContentReady) + await pWaitFor(() => this.taskState.userMessageContentReady) // if the model did not tool use, then we need to tell it to either use a tool or attempt_completion - const didToolUse = this.assistantMessageContent.some((block) => block.type === "tool_use") + const didToolUse = this.taskState.assistantMessageContent.some((block) => block.type === "tool_use") if (!didToolUse) { // normal request where tool use is required - this.userMessageContent.push({ + this.taskState.userMessageContent.push({ type: "text", text: formatResponse.noToolsUsed(), }) - this.consecutiveMistakeCount++ + this.taskState.consecutiveMistakeCount++ } - const recDidEndLoop = await this.recursivelyMakeClineRequests(this.userMessageContent) + const recDidEndLoop = await this.recursivelyMakeClineRequests(this.taskState.userMessageContent) didEndLoop = recDidEndLoop } else { // if there's no assistant_responses, that means we got no text or tool_use content blocks from API which we should assume is an error @@ -4828,7 +4828,7 @@ export class Task { const inactiveTerminals = this.terminalManager.getTerminals(false) // const allTerminals = [...busyTerminals, ...inactiveTerminals] - if (busyTerminals.length > 0 && this.didEditFile) { + if (busyTerminals.length > 0 && this.taskState.didEditFile) { // || this.didEditFile await setTimeoutPromise(300) // delay after saving file to let terminals catch up } @@ -4860,7 +4860,7 @@ export class Task { } } */ - this.didEditFile = false // reset, this lets us know when to wait for saved files to update terminals + this.taskState.didEditFile = false // reset, this lets us know when to wait for saved files to update terminals // waiting for updated diagnostics lets terminal output be the most up-to-date possible let terminalDetails = "" diff --git a/src/core/task/utils.ts b/src/core/task/utils.ts new file mode 100644 index 00000000..e0ff8d06 --- /dev/null +++ b/src/core/task/utils.ts @@ -0,0 +1,70 @@ +import { showSystemNotification } from "@/integrations/notifications" +import { ClineApiReqCancelReason, ClineApiReqInfo } from "@/shared/ExtensionMessage" +import { serializeError } from "serialize-error" +import { MessageStateHandler } from "./message-state" +import { calculateApiCostAnthropic } from "@/utils/cost" +import { ApiHandler } from "@/api" + +export function formatErrorWithStatusCode(error: any): string { + const statusCode = error.status || error.statusCode || (error.response && error.response.status) + const message = error.message ?? JSON.stringify(serializeError(error), null, 2) + + // Only prepend the statusCode if it's not already part of the message + return statusCode && !message.includes(statusCode.toString()) ? `${statusCode} - ${message}` : message +} + +export const showNotificationForApprovalIfAutoApprovalEnabled = ( + message: string, + autoApprovalSettingsEnabled: boolean, + notificationsEnabled: boolean, +) => { + if (autoApprovalSettingsEnabled && notificationsEnabled) { + showSystemNotification({ + subtitle: "Approval Required", + message, + }) + } +} + +type UpdateApiReqMsgParams = { + messageStateHandler: MessageStateHandler + lastApiReqIndex: number + inputTokens: number + outputTokens: number + cacheWriteTokens: number + cacheReadTokens: number + totalCost?: number + api: ApiHandler + cancelReason?: ClineApiReqCancelReason + streamingFailedMessage?: string +} + +// update api_req_started. we can't use api_req_finished anymore since it's a unique case where it could come after a streaming message (ie in the middle of being updated or executed) +// fortunately api_req_finished was always parsed out for the gui anyways, so it remains solely for legacy purposes to keep track of prices in tasks from history +// (it's worth removing a few months from now) +export const updateApiReqMsg = async (params: UpdateApiReqMsgParams) => { + const clineMessages = params.messageStateHandler.getClineMessages() + const currentApiReqInfo: ClineApiReqInfo = JSON.parse(clineMessages[params.lastApiReqIndex].text || "{}") + delete currentApiReqInfo.retryStatus // Clear retry status when request is finalized + + await params.messageStateHandler.updateClineMessage(params.lastApiReqIndex, { + text: JSON.stringify({ + ...currentApiReqInfo, // Spread the modified info (with retryStatus removed) + tokensIn: params.inputTokens, + tokensOut: params.outputTokens, + cacheWrites: params.cacheWriteTokens, + cacheReads: params.cacheReadTokens, + cost: + params.totalCost ?? + calculateApiCostAnthropic( + params.api.getModel().info, + params.inputTokens, + params.outputTokens, + params.cacheWriteTokens, + params.cacheReadTokens, + ), + cancelReason: params.cancelReason, + streamingFailedMessage: params.streamingFailedMessage, + } satisfies ClineApiReqInfo), + }) +}