🪝Hooks: Gorgeous UI [ENG-994] (#7126)

* feat(hooks): Initial implementation of hooks UI using background terminal UI

* Hooks UI improvements

* Hook discovery improvements

* Separate hooks UI into separate files

* Fix failing tests

* Add missing docs

* Hooks hardening and handling edge cases

* Improvements to hooks error messaging

* Improve TaskCancel hook UI

* Simplify and improve console.log() output from hooks

* Changes from usability feedback

* test: verify linting fixes

* fix: resolve cancel functionality in PostToolUse hook using flag pattern

* fix: add cancel button support for TaskResume and UserPromptSubmit hooks

* Getting things working again

* Fixing cancel behaviors

* Trying another fix

* Demoed

* Add examples to .clinerules/hooks/ directory

* Refactored away loadTaskStateWithoutWorkflow

* Fix unsafe return in finally block

Refactored PostToolUse hook execution to avoid using return statement
in finally block, which the linter flags as unsafe. Instead of early
return, wrapped the hook logic in a conditional check for abort status.

This resolves the biome lint error:
lint/correctness/noUnsafeFinally - Unsafe usage of 'return' in finally block

* Remove unnecessary files from branch

* remove cancelHookExecution() in favor of cancelTask()

* Remove unnecessary polling pattern for hook cancellation

* Fixing cancel behavior

* Fixing cancel behavior

* Fix resume

* Sqaush commits to improve merge tool behavior

Plan out the work needed to resolve race conditions

Fix race conditions (1)

Fix race conditions (2)

Fix race conditions (3)

Fix race conditions (4)

Fix race conditions (5)

Fix unit tests

Updated implementation plan doc

Code quality improvement

Temporary logging to troubleshoot race conditions in hooks UI blocks

Fix streaming output for hooks

Remove in-progress planning file

Revert breakage

Remove unneeded arg output in PreToolUse hook UI

Fix race condition with PreToolUse and PostToolUse hooks

Fix PreToolUse attempt_completion use case

Fix ChatTextArea prompt input

Fixed part of the rersume bug

Clean-up before code review

Change cancel button to abort button

Fixed TaskCancel behavior

Fixing resume behavior (partially fixed)

Make notch arrow visible in hooks block up expand/contract toggle

Prevent cancel/abort from clearing unsent user message

Change 'Cancelled' to 'Aborted' in hook UI block

Use color styles consistent with background terminal

Fix npm compile issue

Remove unneeded hot-cold tracking from hooks

Remove unused constant as per PR feedback

Minor changes

Skip combineHookSequences() if hooks feature setting not enabled

Improve mutex pattern for general use and fix additional race condition

Refactor to reduce duplication (keep it DRY)

Refactor to reduce duplication (keep it DRY) part 2

Fix tests

Skip some tests on Windows (not yet supported)

Hooks unsupported on Windows

Fix broken unit tests

* Fix broken unit tests

* Bee and Eve fixing 'API Request...' test in e2e tests

* Add comment as per ellipsis-dev PR feedback

* Changes as per PR feedback from Evan

* Remove if that always resolves to true

* Don't use vscode API; use cross-compatible solutions instead

* Remove mention of obsolete clineAsk handler
This commit is contained in:
CandiedUniverse authored and GitHub committed 2025-10-31 05:50:18 -07:00
1 parent 3698d2356c
commit dfd113a6e5
75 files changed
+5055 -799

No files matched your search

+8
View File
@@ -61,6 +61,14 @@ export class TaskState {
didFinishAbortingStream = false
abandoned = false
// Hook execution tracking for cancellation
activeHookExecution?: {
hookName: string
toolName?: string
messageTs: number
abortController: AbortController
}
// Auto-context summarization
currentlySummarizing: boolean = false
lastAutoCompactTriggerIndex?: number
+265 -56
View File
@@ -13,7 +13,6 @@ import * as vscode from "vscode"
import { modelDoesntSupportWebp } from "@/utils/model-utils"
import { ToolUse } from "../assistant-message"
import { ContextManager } from "../context/context-management/ContextManager"
import { HookFactory } from "../hooks/hook-factory"
import { formatResponse } from "../prompts/responses"
import { StateManager } from "../storage/StateManager"
import { WorkspaceRootManager } from "../workspace"
@@ -113,6 +112,11 @@ export class ToolExecutor {
private doesLatestTaskCompletionHaveNewChanges: () => Promise<boolean>,
private updateFCListFromToolResponse: (taskProgress: string | undefined) => Promise<void>,
private switchToActMode: () => Promise<boolean>,
// Atomic hook state helpers from Task
private setActiveHookExecution: (hookExecution: NonNullable<typeof taskState.activeHookExecution>) => Promise<void>,
private clearActiveHookExecution: () => Promise<void>,
private getActiveHookExecution: () => Promise<typeof taskState.activeHookExecution>,
) {
this.autoApprover = new AutoApprove(this.stateManager)
@@ -230,7 +234,14 @@ export class ToolExecutor {
}
/**
* Handles errors during tool execution
* Handles errors during tool execution.
*
* Logs the error, displays it to the user via the UI, and adds an error
* result to the conversation context so the AI can see what went wrong.
*
* @param action Description of what was being attempted (e.g., "executing read_file")
* @param error The error that occurred
* @param block The tool use block that caused the error
*/
private async handleError(action: string, error: Error, block: ToolUse): Promise<void> {
console.log(error)
@@ -242,6 +253,17 @@ export class ToolExecutor {
this.pushToolResult(errorResponse, block)
}
/**
* Pushes a tool result to the user message content.
*
* This is a critical method that:
* - Formats the tool result appropriately for the API
* - Adds it to the conversation context
* - Marks that a tool has been used in this turn
*
* @param content The tool response content to add
* @param block The tool use block that generated this result
*/
private pushToolResult = (content: ToolResponse, block: ToolUse) => {
// Use the ToolResultUtils to properly format and push the tool result
ToolResultUtils.pushToolResult(
@@ -268,7 +290,18 @@ export class ToolExecutor {
]
/**
* Execute a tool through the coordinator if it's registered
* Execute a tool through the coordinator if it's registered.
*
* This is the main entry point for tool execution, called by the Task class.
* It handles:
* - Checking if the tool is registered with the coordinator
* - Validating tool execution is allowed (not rejected, not already used, etc.)
* - Enforcing plan mode restrictions on file modification tools
* - Delegating to partial or complete block handlers
* - Error handling and checkpointing
*
* @param block The tool use block to execute
* @returns true if the tool was handled (even if execution failed), false if not registered
*/
private async execute(block: ToolUse): Promise<boolean> {
// Note: MCP tool name transformation happens earlier in ToolUseHandler.getPartialToolUsesAsContent()
@@ -336,14 +369,27 @@ export class ToolExecutor {
}
/**
* Check if a tool is restricted in plan mode
* Check if a tool is restricted in plan mode.
*
* In strict plan mode, file modification tools (write_to_file, editedExistingFile, etc.)
* are blocked. The AI must switch to Act mode to use these tools.
*
* @param toolName The name of the tool to check
* @returns true if the tool is restricted in plan mode, false otherwise
*/
private isPlanModeToolRestricted(toolName: ClineDefaultTool): boolean {
return ToolExecutor.PLAN_MODE_RESTRICTED_TOOLS.includes(toolName)
}
/**
* Create a tool rejection message and add it to user message content
* Create a tool rejection message and add it to user message content.
*
* Used when a tool cannot be executed (e.g., user rejected a previous tool,
* tool was interrupted, etc.). Adds a text message to the conversation explaining
* why the tool was not executed.
*
* @param block The tool use block that was rejected
* @param reason Human-readable explanation of why the tool was rejected
*/
private createToolRejectionMessage(block: ToolUse, reason: string): void {
this.taskState.userMessageContent.push({
@@ -391,7 +437,74 @@ export class ToolExecutor {
}
/**
* Handle partial block streaming UI updates
* Runs the PostToolUse hook after tool execution.
* This is extracted from handleCompleteBlock to eliminate code duplication
* between success and error paths.
*
* @param block The tool use block that was executed
* @param toolResult The result from the tool execution
* @param executionSuccess Whether the tool executed successfully
* @param executionStartTime The timestamp when tool execution started
* @returns true if hook requested cancellation, false otherwise
*/
private async runPostToolUseHook(
block: ToolUse,
toolResult: any,
executionSuccess: boolean,
executionStartTime: number,
): Promise<boolean> {
const { executeHook } = await import("../hooks/hook-executor")
const executionTimeMs = Date.now() - executionStartTime
console.log(`[HOOK-UI] PostToolUse executing for tool: ${block.name}`)
const postToolResult = await executeHook({
hookName: "PostToolUse",
hookInput: {
postToolUse: {
toolName: block.name,
parameters: block.params,
result: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult),
success: executionSuccess,
executionTimeMs,
},
},
isCancellable: true,
say: this.say,
setActiveHookExecution: this.setActiveHookExecution,
clearActiveHookExecution: this.clearActiveHookExecution,
messageStateHandler: this.messageStateHandler,
taskId: this.taskId,
hooksEnabled: true, // Already checked by caller
toolName: block.name,
})
// Handle cancellation request
if (postToolResult.cancel === true) {
const errorMessage = postToolResult.errorMessage || "Hook requested task cancellation"
await this.say("error", errorMessage)
return true
}
// Add context modification to the conversation if provided
if (postToolResult.contextModification) {
this.addHookContextToConversation(postToolResult.contextModification, "PostToolUse")
}
return false
}
/**
* Handle partial block streaming UI updates.
*
* During streaming API responses, the AI sends partial tool use blocks as they're
* generated. This method updates the UI to show the tool being constructed in real-time.
*
* NOTE: This is ONLY for UI updates. No tool results are pushed to the conversation
* during partial block handling. The complete block handler will add the final result.
*
* @param block The partial tool use block with incomplete parameters
* @param config The task configuration containing all necessary context
*/
private async handlePartialBlock(block: ToolUse, config: TaskConfig): Promise<void> {
// NOTE: We don't push tool results in partial blocks because this is only for UI streaming.
@@ -408,87 +521,183 @@ export class ToolExecutor {
}
/**
* Handle complete block execution
* Handle complete block execution.
*
* This is the main execution flow for a tool:
* 1. Run PreToolUse hooks (if enabled) - can block execution
* 2. Execute the actual tool
* 3. Run PostToolUse hooks (if enabled) - cannot block, only observe
* 4. Add hook context modifications to the conversation
* 5. Update focus chain tracking
*
* Hooks are executed with streaming output to provide real-time feedback.
* PreToolUse hooks can prevent tool execution by returning shouldContinue: false.
* PostToolUse hooks are for observation/logging only and cannot block.
*
* @param block The complete tool use block with all parameters
* @param config The task configuration containing all necessary context
*/
private async handleCompleteBlock(block: ToolUse, config: any): Promise<void> {
// Check abort flag at the very start to prevent execution after cancellation
if (this.taskState.abort) {
return
}
// Check if hooks are enabled (both feature flag and user setting must be true)
const featureFlagEnabled = featureFlagsService.getHooksEnabled()
const userEnabled = this.stateManager.getGlobalSettingsKey("hooksEnabled")
const hooksEnabled = featureFlagEnabled && userEnabled
let executionSuccess = true
let toolResult: any = null
// Track if we need to cancel after hooks complete
let shouldCancelAfterHook = false
// Run PreToolUse hook, if enabled
// ============================================================
// PHASE 1: Run PreToolUse hook (OUTSIDE try-catch-finally)
// This allows early return on cancellation without triggering finally block
// ============================================================
if (hooksEnabled) {
let preToolUseResult: any = null
try {
const hookFactory = new HookFactory()
const preToolUseHook = await hookFactory.create("PreToolUse")
const { executeHook } = await import("../hooks/hook-executor")
preToolUseResult = await preToolUseHook.run({
taskId: this.taskId,
// Build pending tool info for display
const pendingToolInfo: any = {
tool: block.name,
}
// Add relevant parameters for display based on tool type
if (block.params.path) {
pendingToolInfo.path = block.params.path
}
if (block.params.command) {
pendingToolInfo.command = block.params.command
}
if (block.params.content && typeof block.params.content === "string") {
pendingToolInfo.content = block.params.content.slice(0, 200)
}
if (block.params.diff && typeof block.params.diff === "string") {
pendingToolInfo.diff = block.params.diff.slice(0, 200)
}
if (block.params.regex) {
pendingToolInfo.regex = block.params.regex
}
if (block.params.url) {
pendingToolInfo.url = block.params.url
}
// For MCP operations, show tool/resource identifiers
if (block.params.tool_name) {
pendingToolInfo.mcpTool = block.params.tool_name
}
if (block.params.server_name) {
pendingToolInfo.mcpServer = block.params.server_name
}
if (block.params.uri) {
pendingToolInfo.resourceUri = block.params.uri
}
console.log(`[HOOK-UI] PreToolUse executing for tool: ${block.name}`)
const preToolResult = await executeHook({
hookName: "PreToolUse",
hookInput: {
preToolUse: {
toolName: block.name,
parameters: block.params,
},
})
},
isCancellable: true,
say: this.say,
setActiveHookExecution: this.setActiveHookExecution,
clearActiveHookExecution: this.clearActiveHookExecution,
messageStateHandler: this.messageStateHandler,
taskId: this.taskId,
hooksEnabled,
toolName: block.name,
pendingToolInfo,
})
// Check if hook wants to stop execution
if (!preToolUseResult.shouldContinue) {
const errorMessage = preToolUseResult.errorMessage || "PreToolUse hook prevented tool execution"
await this.say("error", errorMessage)
this.pushToolResult(formatResponse.toolError(errorMessage), block)
return
}
// Add context modification to the conversation if provided by the hook
this.addHookContextToConversation(preToolUseResult.contextModification, "PreToolUse")
} catch (hookError) {
const errorMessage = `PreToolUse hook failed: ${hookError.toString()}`
await this.say("error", errorMessage)
this.pushToolResult(formatResponse.toolError(errorMessage), block)
// Handle cancellation from hook
if (preToolResult.cancel === true) {
// Trigger task cancellation (same as clicking cancel button)
await config.callbacks.cancelTask()
// Early return - never enters try-catch-finally, so PostToolUse won't run
return
}
// If task was aborted (e.g., via cancel button during hook), stop execution
if (this.taskState.abort) {
shouldCancelAfterHook = true
}
// Add context modification to the conversation if provided by the hook
if (preToolResult.contextModification) {
this.addHookContextToConversation(preToolResult.contextModification, "PreToolUse")
}
}
// ============================================================
// PHASE 2: Execute tool with PostToolUse hook in finally block
// This only runs if PreToolUse didn't cancel above
// ============================================================
// Check abort again before tool execution (could have been set by PreToolUse hook)
if (this.taskState.abort) {
return
}
let executionSuccess = true
let toolResult: any = null
let toolWasExecuted = false
const executionStartTime = Date.now()
try {
// Final abort check immediately before tool execution
if (this.taskState.abort) {
return
}
// Execute the actual tool
toolResult = await this.coordinator.execute(config, block)
toolWasExecuted = true
this.pushToolResult(toolResult, block)
// Check abort before running PostToolUse hook (success path)
if (this.taskState.abort) {
return
}
// Run PostToolUse hook for successful tool execution
// Skip for attempt_completion since it marks task completion, not actual work
if (hooksEnabled && block.name !== "attempt_completion") {
const hookRequestedCancel = await this.runPostToolUseHook(block, toolResult, executionSuccess, executionStartTime)
if (hookRequestedCancel) {
await config.callbacks.cancelTask()
shouldCancelAfterHook = true
}
}
} catch (error) {
executionSuccess = false
toolResult = formatResponse.toolError(`Tool execution failed: ${error}`)
// Don't push tool result here - let the outer catch block (handleError) handle it
// to avoid duplicate tool_result blocks
throw error
} finally {
// Run PostToolUse hook if enabled
if (hooksEnabled) {
const hookFactory = new HookFactory()
const postToolUseHook = await hookFactory.create("PostToolUse")
const executionTimeMs = Date.now() - executionStartTime
const postToolUseResult = await postToolUseHook.run({
taskId: this.taskId,
postToolUse: {
toolName: block.name,
parameters: block.params,
result: typeof toolResult === "string" ? toolResult : JSON.stringify(toolResult),
success: executionSuccess,
executionTimeMs,
},
})
// Check abort before running PostToolUse hook (error path)
if (this.taskState.abort) {
throw error
}
// Add context modification to the conversation if provided by the hook
this.addHookContextToConversation(postToolUseResult.contextModification, "PostToolUse")
// Log any error messages from the hook
if (postToolUseResult.errorMessage) {
this.say("error", postToolUseResult.errorMessage)
// Run PostToolUse hook for failed tool execution
// Skip for attempt_completion since it marks task completion, not actual work
if (toolWasExecuted && hooksEnabled && block.name !== "attempt_completion") {
const hookRequestedCancel = await this.runPostToolUseHook(block, toolResult, executionSuccess, executionStartTime)
if (hookRequestedCancel) {
await config.callbacks.cancelTask()
shouldCancelAfterHook = true
}
}
// Re-throw the error after PostToolUse completes
throw error
}
// Early return if hook requested cancellation
if (shouldCancelAfterHook) {
return
}
// Handle focus chain updates
+427 -189
View File
@@ -72,6 +72,7 @@ import { arePathsEqual, getDesktopDir } from "@utils/path"
import { filterExistingFiles } from "@utils/tabFiltering"
import cloneDeep from "clone-deep"
import { execa } from "execa"
import Mutex from "p-mutex"
import pWaitFor from "p-wait-for"
import * as path from "path"
import { ulid } from "ulid"
@@ -139,6 +140,50 @@ export class Task {
taskState: TaskState
// ONE mutex for ALL state modifications to prevent race conditions
private stateMutex = new Mutex()
/**
* Execute function with exclusive lock on all task state
* Use this for ANY state modification to prevent races
*/
private async withStateLock<T>(fn: () => T | Promise<T>): Promise<T> {
return await this.stateMutex.withLock(fn)
}
/**
* Atomically set active hook execution with mutex protection
* Prevents TOCTOU races when setting hook execution state
* PUBLIC: Exposed for ToolExecutor to use
*/
public async setActiveHookExecution(hookExecution: NonNullable<typeof this.taskState.activeHookExecution>): Promise<void> {
await this.withStateLock(() => {
this.taskState.activeHookExecution = hookExecution
})
}
/**
* Atomically clear active hook execution with mutex protection
* Prevents TOCTOU races when clearing hook execution state
* PUBLIC: Exposed for ToolExecutor to use
*/
public async clearActiveHookExecution(): Promise<void> {
await this.withStateLock(() => {
this.taskState.activeHookExecution = undefined
})
}
/**
* Atomically read active hook execution state with mutex protection
* Returns a snapshot of the current state to prevent TOCTOU races
* PUBLIC: Exposed for ToolExecutor to use
*/
public async getActiveHookExecution(): Promise<typeof this.taskState.activeHookExecution> {
return await this.withStateLock(() => {
return this.taskState.activeHookExecution
})
}
// Core dependencies
private controller: Controller
private mcpHub: McpHub
@@ -437,12 +482,9 @@ export class Task {
// Set ulid on browserSession for telemetry tracking
this.browserSession.setUlid(this.ulid)
// Continue with task initialization
if (historyItem) {
this.resumeTaskFromHistory()
} else if (task || images || files) {
this.startTask(task, images, files)
}
// Note: Task initialization (startTask/resumeTaskFromHistory) is now called
// from Controller.initTask() AFTER the task instance is fully assigned.
// This prevents race conditions where hooks run before controller.task is ready.
// Set up focus chain file watcher (async, runs in background) only if focus chain is enabled
if (this.FocusChainManager) {
@@ -494,6 +536,10 @@ export class Task {
() => this.checkpointManager?.doesLatestTaskCompletionHaveNewChanges() ?? Promise.resolve(false),
this.FocusChainManager?.updateFCListFromToolResponse.bind(this.FocusChainManager) || (async () => {}),
this.switchToActModeCallback.bind(this),
// Atomic hook state helpers for ToolExecutor
this.setActiveHookExecution.bind(this),
this.clearActiveHookExecution.bind(this),
this.getActiveHookExecution.bind(this),
)
}
@@ -511,8 +557,8 @@ export class Task {
files?: string[]
askTs?: number
}> {
// 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.taskState.abort) {
// Allow resume asks even when aborted to enable resume button after cancellation
if (this.taskState.abort && type !== "resume_task" && type !== "resume_completed_task") {
throw new Error("Cline instance aborted")
}
let askTs: number
@@ -646,7 +692,8 @@ export class Task {
files?: string[],
partial?: boolean,
): Promise<number | undefined> {
if (this.taskState.abort) {
// Allow hook messages even when aborted to enable proper cleanup
if (this.taskState.abort && type !== "hook" && type !== "hook_output") {
throw new Error("Cline instance aborted")
}
@@ -759,54 +806,66 @@ export class Task {
private async runUserPromptSubmitHook(
userContent: UserContent,
context: "initial_task" | "resume" | "feedback",
): Promise<{ shouldContinue: boolean; contextModification?: string; errorMessage?: string }> {
_context: "initial_task" | "resume" | "feedback",
): Promise<{ cancel?: boolean; contextModification?: string; errorMessage?: string }> {
const hooksEnabled = featureFlagsService.getHooksEnabled() && this.stateManager.getGlobalSettingsKey("hooksEnabled")
if (!hooksEnabled) {
return { shouldContinue: true }
return {}
}
try {
const { HookFactory } = await import("../hooks/hook-factory")
const hookFactory = new HookFactory()
const hook = await hookFactory.create("UserPromptSubmit")
const { executeHook } = await import("../hooks/hook-executor")
// Serialize UserContent to string for the hook
const promptText = userContent
.map((block) => {
if (block.type === "text") {
return block.text
}
if (block.type === "image") {
return "[IMAGE]"
}
return ""
})
.join("\n\n")
// Serialize UserContent to string for the hook
const promptText = userContent
.map((block) => {
if (block.type === "text") {
return block.text
}
if (block.type === "image") {
return "[IMAGE]"
}
return ""
})
.join("\n\n")
const result = await hook.run({
taskId: this.taskId,
const userPromptResult = await executeHook({
hookName: "UserPromptSubmit",
hookInput: {
userPromptSubmit: {
prompt: promptText,
attachments: [], // Images are inline in UserContent
attachments: [],
},
})
},
isCancellable: true,
say: this.say.bind(this),
setActiveHookExecution: this.setActiveHookExecution.bind(this),
clearActiveHookExecution: this.clearActiveHookExecution.bind(this),
messageStateHandler: this.messageStateHandler,
taskId: this.taskId,
hooksEnabled,
})
return {
shouldContinue: result.shouldContinue,
contextModification: result.contextModification,
errorMessage: result.errorMessage,
}
} catch (error) {
console.error("UserPromptSubmit hook failed:", error)
return { shouldContinue: true }
// Handle cancellation from hook
if (userPromptResult.cancel === true && userPromptResult.wasCancelled) {
// Set flag to allow Controller.cancelTask() to proceed
this.taskState.didFinishAbortingStream = true
// Save BOTH files so Controller.cancelTask() can find the task
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.messageStateHandler.overwriteApiConversationHistory(this.messageStateHandler.getApiConversationHistory())
await this.postStateToWebview()
}
return {
cancel: userPromptResult.cancel,
contextModification: userPromptResult.contextModification,
errorMessage: userPromptResult.errorMessage,
}
}
// Task lifecycle
private async startTask(task?: string, images?: string[], files?: string[]): Promise<void> {
public async startTask(task?: string, images?: string[], files?: string[]): Promise<void> {
try {
await this.clineIgnoreController.initialize()
} catch (error) {
@@ -845,16 +904,13 @@ export class Task {
}
// Add TaskStart hook context to the conversation if provided
// This follows the same pattern as PreToolUse, PostToolUse, and UserPromptSubmit hooks
const hooksEnabled = featureFlagsService.getHooksEnabled() && this.stateManager.getGlobalSettingsKey("hooksEnabled")
if (hooksEnabled) {
try {
const { HookFactory } = await import("../hooks/hook-factory")
const hookFactory = new HookFactory()
const taskStartHook = await hookFactory.create("TaskStart")
const { executeHook } = await import("../hooks/hook-executor")
const taskStartResult = await taskStartHook.run({
taskId: this.taskId,
const taskStartResult = await executeHook({
hookName: "TaskStart",
hookInput: {
taskStart: {
taskMetadata: {
taskId: this.taskId,
@@ -862,40 +918,75 @@ export class Task {
initialTask: task || "",
},
},
})
},
isCancellable: true,
say: this.say.bind(this),
setActiveHookExecution: this.setActiveHookExecution.bind(this),
clearActiveHookExecution: this.clearActiveHookExecution.bind(this),
messageStateHandler: this.messageStateHandler,
taskId: this.taskId,
hooksEnabled,
})
if (!taskStartResult.shouldContinue) {
const errorMessage = taskStartResult.errorMessage || "TaskStart hook prevented task from starting"
await this.say("error", errorMessage)
// Ensure the error message is saved and posted before aborting
// Handle cancellation from hook
if (taskStartResult.cancel === true) {
// If hook was cancelled by user, save state for resume
if (taskStartResult.wasCancelled) {
console.log(`[TaskStart Hook] User cancelled, saving messages for task ${this.taskId}`)
// Set flag to allow Controller.cancelTask() to proceed
this.taskState.didFinishAbortingStream = true
// Save BOTH clineMessages AND apiConversationHistory so Controller.cancelTask() can find the task
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.messageStateHandler.overwriteApiConversationHistory(
this.messageStateHandler.getApiConversationHistory(),
)
await this.postStateToWebview()
this.abortTask()
return
console.log(`[TaskStart Hook] Messages saved successfully, returning from hook`)
}
// Add context modification to the conversation if provided
if (taskStartResult.contextModification) {
const contextText = taskStartResult.contextModification.trim()
if (contextText) {
userContent.push({
type: "text",
text: `<hook_context source="TaskStart">\n${contextText}\n</hook_context>`,
})
}
}
} catch (hookError) {
const errorMessage = `TaskStart hook failed: ${hookError instanceof Error ? hookError.message : String(hookError)}`
Logger.error(errorMessage, hookError)
// Show error to user but continue with task (non-fatal)
await this.say("error", errorMessage)
// abortTask will handle cleanup
this.abortTask()
return
}
// Add context modification to the conversation if provided
if (taskStartResult.contextModification) {
const contextText = taskStartResult.contextModification.trim()
if (contextText) {
userContent.push({
type: "text",
text: `<hook_context source="TaskStart">\n${contextText}\n</hook_context>`,
})
}
}
}
// Run UserPromptSubmit hook for initial task (after TaskStart for UI ordering)
const userPromptHookResult = await this.runUserPromptSubmitHook(userContent, "initial_task")
// Defensive check: Verify task wasn't aborted during hook execution (handles async cancellation)
if (this.taskState.abort) {
return
}
// Handle hook cancellation - but DON'T call abortTask()
// Controller.cancelTask() already called it, calling again causes double TaskCancel
if (userPromptHookResult.cancel === true) {
return
}
// Add hook context if provided
if (userPromptHookResult.contextModification) {
userContent.push({
type: "text",
text: `<hook_context source="UserPromptSubmit">\n${userPromptHookResult.contextModification}\n</hook_context>`,
})
}
await this.initiateTaskLoop(userContent)
}
private async resumeTaskFromHistory() {
public async resumeTaskFromHistory() {
try {
await this.clineIgnoreController.initialize()
} catch (error) {
@@ -952,21 +1043,22 @@ export class Task {
}
this.taskState.isInitialized = true
this.taskState.abort = false // Reset abort flag when resuming task
const { response, text, images, files } = await this.ask(askType) // calls poststatetowebview
// Initialize newUserContent array for hook context
const newUserContent: UserContent = []
// Run TaskResume hook
// Run TaskResume hook AFTER user clicks resume button
const hooksEnabled = featureFlagsService.getHooksEnabled() && this.stateManager.getGlobalSettingsKey("hooksEnabled")
if (hooksEnabled) {
try {
const { HookFactory } = await import("../hooks/hook-factory")
const hookFactory = new HookFactory()
const taskResumeHook = await hookFactory.create("TaskResume")
const { executeHook } = await import("../hooks/hook-executor")
const clineMessages = this.messageStateHandler.getClineMessages()
const taskResumeResult = await taskResumeHook.run({
taskId: this.taskId,
const clineMessages = this.messageStateHandler.getClineMessages()
const taskResumeResult = await executeHook({
hookName: "TaskResume",
hookInput: {
taskResume: {
taskMetadata: {
taskId: this.taskId,
@@ -978,32 +1070,46 @@ export class Task {
conversationHistoryDeleted: (this.taskState.conversationHistoryDeletedRange !== undefined).toString(),
},
},
},
isCancellable: true,
say: this.say.bind(this),
setActiveHookExecution: this.setActiveHookExecution.bind(this),
clearActiveHookExecution: this.clearActiveHookExecution.bind(this),
messageStateHandler: this.messageStateHandler,
taskId: this.taskId,
hooksEnabled,
})
// Handle cancellation from hook
if (taskResumeResult.cancel === true) {
// If hook was cancelled by user, save state for resume
if (taskResumeResult.wasCancelled) {
// Set flag to allow Controller.cancelTask() to proceed
this.taskState.didFinishAbortingStream = true
// Save BOTH clineMessages AND apiConversationHistory so Controller.cancelTask() can find the task
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.messageStateHandler.overwriteApiConversationHistory(
this.messageStateHandler.getApiConversationHistory(),
)
await this.postStateToWebview()
}
// Return without continuing task - Controller.cancelTask() will handle showing resume button
return
}
// Add context if provided
if (taskResumeResult.contextModification) {
newUserContent.push({
type: "text",
text: `<hook_context source="TaskResume" type="general">\n${taskResumeResult.contextModification}\n</hook_context>`,
})
// Check if hook indicates an error condition (non-blocking)
if (!taskResumeResult.shouldContinue && taskResumeResult.errorMessage) {
await this.say("error", taskResumeResult.errorMessage)
}
// Add context if provided
if (taskResumeResult.contextModification) {
newUserContent.push({
type: "text",
text: `<hook_context source="TaskResume" type="general">\n${taskResumeResult.contextModification}\n</hook_context>`,
})
}
} catch (hookError) {
const errorMessage = `TaskResume hook failed: ${hookError instanceof Error ? hookError.message : String(hookError)}`
await this.say("error", errorMessage)
// Non-fatal: continue with resume
}
}
const { response, text, images, files } = await this.ask(askType) // calls poststatetowebview
let responseText: string | undefined
let responseImages: string[] | undefined
let responseFiles: string[] | undefined
if (response === "messageResponse") {
if (response === "messageResponse" || text || (images && images.length > 0) || (files && files.length > 0)) {
await this.say("user_feedback", text, images, files)
await this.checkpointManager?.saveCheckpoint()
responseText = text
@@ -1013,9 +1119,9 @@ export class Task {
// need to make sure that the api conversation history can be resumed by the api, even if it goes out of sync with cline messages
const existingApiConversationHistory: Anthropic.Messages.MessageParam[] = await getSavedApiConversationHistory(
this.taskId,
)
// Use the already-loaded API conversation history from memory instead of reloading from disk
// This prevents issues where the file might be empty or stale after hook execution
const existingApiConversationHistory = this.messageStateHandler.getApiConversationHistory()
// Remove the last user message so we can update it with the resume message
let modifiedOldUserContent: UserContent // either the last message if its user message, or the user message before the last (assistant) message
@@ -1035,7 +1141,10 @@ export class Task {
throw new Error("Unexpected: Last message is not a user or assistant message")
}
} else {
throw new Error("Unexpected: No existing API conversation history")
// No API conversation history yet (e.g., cancelled during hook before first API request)
// Start fresh with empty history and no previous content
modifiedApiConversationHistory = []
modifiedOldUserContent = []
}
// Add previous content to newUserContent array
@@ -1114,6 +1223,29 @@ export class Task {
})
}
// Run UserPromptSubmit hook for task resumption AFTER all content is assembled
const userPromptHookResult = await this.runUserPromptSubmitHook(newUserContent, "resume")
// Defensive check: Verify task wasn't aborted during hook execution (handles async cancellation)
if (this.taskState.abort) {
return
}
// Handle hook cancellation request
if (userPromptHookResult.cancel === true) {
// The hook already updated its status to "cancelled" internally and saved state
this.abortTask()
return
}
// Add hook context if provided (after all other content)
if (userPromptHookResult.contextModification) {
newUserContent.push({
type: "text",
text: `<hook_context source="UserPromptSubmit">\n${userPromptHookResult.contextModification}\n</hook_context>`,
})
}
await this.messageStateHandler.overwriteApiConversationHistory(modifiedApiConversationHistory)
await this.initiateTaskLoop(newUserContent)
}
@@ -1148,72 +1280,149 @@ export class Task {
}
}
/**
* Determines if the TaskCancel hook should run.
* Only runs if there's actual active work happening or if work was started in this session.
* Does NOT run when just showing the resume button with no active work.
* @returns true if the hook should run, false otherwise
*/
private async shouldRunTaskCancelHook(): Promise<boolean> {
// Atomically check for active hook execution (work happening now)
const activeHook = await this.getActiveHookExecution()
if (activeHook) {
return true
}
// Run if the API is currently streaming (work happening now)
if (this.taskState.isStreaming) {
return true
}
// Run if we're waiting for the first chunk (work happening now)
if (this.taskState.isWaitingForFirstChunk) {
return true
}
// Run if there's active background command (work happening now)
if (this.activeBackgroundCommand) {
return true
}
// Check if we're at the resume button state (no active work, just waiting)
const clineMessages = this.messageStateHandler.getClineMessages()
const lastMessage = clineMessages.at(-1)
const isAtResumeButton =
lastMessage?.type === "ask" && (lastMessage.ask === "resume_task" || lastMessage.ask === "resume_completed_task")
if (isAtResumeButton) {
// At resume button - DON'T run hook because we're just waiting for user input
// The resume button appears in two scenarios:
// 1. Opening from history (no new work)
// 2. After cancelling during active work (but work already stopped)
// In both cases, we shouldn't run TaskCancel hook
return false
}
// Not at resume button - we're in the middle of work or just finished something
// Run the hook since cancelling would interrupt actual work
return true
}
async abortTask() {
try {
// Run TaskCancel hook
const hooksEnabled = featureFlagsService.getHooksEnabled() && this.stateManager.getGlobalSettingsKey("hooksEnabled")
if (hooksEnabled) {
// PHASE 1: Check if TaskCancel should run BEFORE any cleanup
// We must capture this state now because subsequent cleanup will
// clear the active work indicators that shouldRunTaskCancelHook checks
const shouldRunTaskCancelHook = await this.shouldRunTaskCancelHook()
// PHASE 2: Set abort flag to prevent race conditions
// This must happen before canceling hooks so that hook catch blocks
// can properly detect the abort state
this.taskState.abort = true
// PHASE 3: Cancel any running hook execution
const activeHook = await this.getActiveHookExecution()
if (activeHook) {
try {
const { HookFactory } = await import("../hooks/hook-factory")
const hookFactory = new HookFactory()
const taskCancelHook = await hookFactory.create("TaskCancel")
const taskCancelResult = await taskCancelHook.run({
taskId: this.taskId,
taskCancel: {
taskMetadata: {
taskId: this.taskId,
ulid: this.ulid,
completionStatus: this.taskState.abandoned ? "abandoned" : "cancelled",
},
},
})
// Surface errors from hook but don't block cancellation
// Only try to display errors if not already aborted (to prevent blocking cleanup)
if (!this.taskState.abort) {
// Display error message if present, or default message if shouldContinue is false
if (taskCancelResult.errorMessage) {
await this.say("error", taskCancelResult.errorMessage).catch(() => {
// If say() fails, log to console instead
console.error("TaskCancel hook error:", taskCancelResult.errorMessage)
})
} else if (!taskCancelResult.shouldContinue) {
// For consistency with other hooks, show a default error when shouldContinue: false with no message
await this.say("error", "TaskCancel hook indicated an issue but provided no error message").catch(
() => {
console.error("TaskCancel hook indicated an issue (shouldContinue: false)")
},
)
}
} else {
// Already aborted, just log to console
if (taskCancelResult.errorMessage) {
console.error("TaskCancel hook error (already aborted):", taskCancelResult.errorMessage)
} else if (!taskCancelResult.shouldContinue) {
console.error("TaskCancel hook indicated an issue (already aborted, shouldContinue: false)")
}
}
// TaskCancel is fire-and-forget - we don't block cancellation based on hook result
} catch (hookError) {
const errorMessage = `TaskCancel hook failed: ${hookError instanceof Error ? hookError.message : String(hookError)}`
Logger.error(errorMessage, hookError)
// Show error to user but continue with abort (non-fatal)
// Only display if not already aborted
if (!this.taskState.abort) {
await this.say("error", errorMessage).catch(() => {
// If say() fails, already logged above
})
}
await this.cancelHookExecution()
// Clear activeHookExecution after hook is signaled
await this.clearActiveHookExecution()
} catch (error) {
Logger.error("Failed to cancel hook during task abort", error)
// Still clear state even on error to prevent stuck state
await this.clearActiveHookExecution()
}
}
// Check for incomplete progress before aborting
// PHASE 4: Run TaskCancel hook
// This allows the hook UI to appear in the webview
// Use the shouldRunTaskCancelHook value we captured in Phase 1
const hooksEnabled = featureFlagsService.getHooksEnabled() && this.stateManager.getGlobalSettingsKey("hooksEnabled")
if (hooksEnabled && shouldRunTaskCancelHook) {
try {
const { executeHook } = await import("../hooks/hook-executor")
const taskCancelResult = await executeHook({
hookName: "TaskCancel",
hookInput: {
taskCancel: {
taskMetadata: {
taskId: this.taskId,
ulid: this.ulid,
completionStatus: this.taskState.abandoned ? "abandoned" : "cancelled",
},
},
},
isCancellable: false, // TaskCancel is NOT cancellable
say: this.say.bind(this),
// No setActiveHookExecution or clearActiveHookExecution for non-cancellable hooks
messageStateHandler: this.messageStateHandler,
taskId: this.taskId,
hooksEnabled,
})
// TaskCancel completed successfully
// Present resume button after successful TaskCancel hook
const lastClineMessage = this.messageStateHandler
.getClineMessages()
.slice()
.reverse()
.find((m) => !(m.ask === "resume_task" || m.ask === "resume_completed_task"))
let askType: ClineAsk
if (lastClineMessage?.ask === "completion_result") {
askType = "resume_completed_task"
} else {
askType = "resume_task"
}
// Present the resume ask - this will show the resume button in the UI
// We don't await this because we want to set the abort flag immediately
// The ask will be waiting when the user decides to resume
this.ask(askType).catch((error) => {
// If ask fails (e.g., task was cleared), that's okay - just log it
console.log("[TaskCancel] Resume ask failed (task may have been cleared):", error)
})
} catch (error) {
// TaskCancel hook failed - non-fatal, just log
console.error("[TaskCancel Hook] Failed (non-fatal):", error)
}
}
// PHASE 5: Immediately update UI to reflect abort state
try {
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.postStateToWebview()
} catch (error) {
Logger.error("Failed to post state after setting abort flag", error)
}
// PHASE 6: Check for incomplete progress
if (this.FocusChainManager) {
this.FocusChainManager.checkIncompleteProgressOnCompletion()
}
this.taskState.abort = true // will stop any autonomously running promises
// PHASE 7: Clean up resources
this.terminalManager.disposeAll()
this.urlContentFetcher.closeBrowser()
await this.browserSession.dispose()
@@ -1238,6 +1447,13 @@ export class Task {
console.error(`[Task ${this.taskId}] Failed to release task lock:`, error)
}
}
// Final state update to notify UI that abort is complete
try {
await this.postStateToWebview()
} catch (error) {
Logger.error("Failed to post final state after abort", error)
}
}
}
@@ -1697,6 +1913,49 @@ export class Task {
return true
}
/**
* Cancel a currently running hook execution
* @returns true if a hook was cancelled, false if no hook was running
*/
public async cancelHookExecution(): Promise<boolean> {
const activeHook = await this.getActiveHookExecution()
if (!activeHook) {
return false
}
const { hookName, toolName, messageTs, abortController } = activeHook
try {
// Abort the hook process
abortController.abort()
// Update hook message status to "cancelled"
const clineMessages = this.messageStateHandler.getClineMessages()
const hookMessageIndex = clineMessages.findIndex((m) => m.ts === messageTs)
if (hookMessageIndex !== -1) {
const cancelledMetadata = {
hookName,
toolName,
status: "cancelled",
exitCode: 130, // Standard SIGTERM exit code
}
await this.messageStateHandler.updateClineMessage(hookMessageIndex, {
text: JSON.stringify(cancelledMetadata),
})
}
// Notify UI that hook was cancelled
await this.say("hook_output", "\nHook execution cancelled by user")
// Return success - let caller (abortTask) handle next steps
// DON'T call abortTask() here to avoid infinite recursion
return true
} catch (error) {
Logger.error("Failed to cancel hook execution", error)
return false
}
}
/**
* Migrates the disableBrowserTool setting from VSCode configuration to browserSettings
*/
@@ -2145,8 +2404,9 @@ export class Task {
}
async recursivelyMakeClineRequests(userContent: UserContent, includeFileDetails: boolean = false): Promise<boolean> {
// Check abort flag at the very start to prevent any execution after cancellation
if (this.taskState.abort) {
throw new Error("Cline instance aborted")
throw new Error("Task instance aborted")
}
// Increment API request counter for focus chain list management
@@ -2217,15 +2477,6 @@ export class Task {
// Save checkpoint if this is the first API request
const isFirstRequest = this.messageStateHandler.getClineMessages().filter((m) => m.say === "api_req_started").length === 0
// getting verbose details is an expensive operation, it uses globby to top-down build file structure of project which for large projects can take a few seconds
// for the best UX we show a placeholder api_req_started message with a loading spinner as this happens
await this.say(
"api_req_started",
JSON.stringify({
request: userContent.map((block) => formatContentBlockToMarkdown(block)).join("\n\n") + "\n\nLoading...",
}),
)
// Initialize checkpointManager first if enabled and it's the first request
if (
isFirstRequest &&
@@ -2399,28 +2650,15 @@ export class Task {
userContent.push({ type: "text", text: environmentDetails })
}
// Run UserPromptSubmit hook before sending to API
const hookResult = await this.runUserPromptSubmitHook(
userContent,
this.taskState.apiRequestCount === 1 ? "initial_task" : "feedback",
// getting verbose details is an expensive operation, it uses globby to top-down build file structure of project which for large projects can take a few seconds
// for the best UX we show a placeholder api_req_started message with a loading spinner as this happens
await this.say(
"api_req_started",
JSON.stringify({
request: userContent.map((block) => formatContentBlockToMarkdown(block)).join("\n\n") + "\n\nLoading...",
}),
)
// Handle hook blocking
if (!hookResult.shouldContinue) {
const errorMessage = hookResult.errorMessage || "UserPromptSubmit hook prevented this request"
await this.say("error", errorMessage)
// Return true to end the loop gracefully
return true
}
// Add hook context if provided
if (hookResult.contextModification) {
userContent.push({
type: "text",
text: `<hook_context source="UserPromptSubmit">\n${hookResult.contextModification}\n</hook_context>`,
})
}
await this.messageStateHandler.addToApiConversationHistory({
role: "user",
content: userContent,
+95 -20
View File
@@ -1,6 +1,7 @@
import Anthropic from "@anthropic-ai/sdk"
import CheckpointTracker from "@integrations/checkpoints/CheckpointTracker"
import getFolderSize from "get-folder-size"
import Mutex from "p-mutex"
import { findLastIndex } from "@/shared/array"
import { combineApiRequests } from "@/shared/combineApiRequests"
import { combineCommandSequences } from "@/shared/combineCommandSequences"
@@ -30,6 +31,12 @@ export class MessageStateHandler {
private ulid: string
private taskState: TaskState
// Mutex to prevent concurrent state modifications (RC-4)
// Protects against data loss from race conditions when multiple
// operations try to modify message state simultaneously
// This follows the same pattern as Task.stateMutex for consistency
private stateMutex = new Mutex()
constructor(params: MessageStateHandlerParams) {
this.taskId = params.taskId
this.ulid = params.ulid
@@ -42,6 +49,15 @@ export class MessageStateHandler {
this.checkpointTracker = tracker
}
/**
* Execute function with exclusive lock on message state
* Use this for ANY state modification to prevent race conditions
* This follows the same pattern as Task.withStateLock for consistency
*/
private async withStateLock<T>(fn: () => T | Promise<T>): Promise<T> {
return await this.stateMutex.withLock(fn)
}
getApiConversationHistory(): Anthropic.MessageParam[] {
return this.apiConversationHistory
}
@@ -58,7 +74,12 @@ export class MessageStateHandler {
this.clineMessages = newMessages
}
async saveClineMessagesAndUpdateHistory(): Promise<void> {
/**
* Internal method to save messages and update history (without mutex protection)
* This is used by methods that already hold the stateMutex lock
* Should NOT be called directly - use saveClineMessagesAndUpdateHistory() instead
*/
private async saveClineMessagesAndUpdateHistoryInternal(): Promise<void> {
try {
await saveClineMessages(this.taskId, this.clineMessages)
@@ -104,39 +125,93 @@ export class MessageStateHandler {
}
}
/**
* Save cline messages and update task history (public API with mutex protection)
* This is the main entry point for saving message state from external callers
*/
async saveClineMessagesAndUpdateHistory(): Promise<void> {
return await this.withStateLock(async () => {
await this.saveClineMessagesAndUpdateHistoryInternal()
})
}
async addToApiConversationHistory(message: Anthropic.MessageParam) {
this.apiConversationHistory.push(message)
await saveApiConversationHistory(this.taskId, this.apiConversationHistory)
// Protect with mutex to prevent concurrent modifications from corrupting data (RC-4)
return await this.withStateLock(async () => {
this.apiConversationHistory.push(message)
await saveApiConversationHistory(this.taskId, this.apiConversationHistory)
})
}
async overwriteApiConversationHistory(newHistory: Anthropic.MessageParam[]): Promise<void> {
this.apiConversationHistory = newHistory
await saveApiConversationHistory(this.taskId, this.apiConversationHistory)
// Protect with mutex to prevent concurrent modifications from corrupting data (RC-4)
return await this.withStateLock(async () => {
this.apiConversationHistory = newHistory
await saveApiConversationHistory(this.taskId, this.apiConversationHistory)
})
}
/**
* Add a new message to clineMessages array with proper index tracking
* CRITICAL: This entire operation must be atomic to prevent race conditions (RC-4)
* The conversationHistoryIndex must be set correctly based on the current state,
* and the message must be added and saved without any interleaving operations
*/
async addToClineMessages(message: ClineMessage) {
// these values allow us to reconstruct the conversation history at the time this cline message was created
// it's important that apiConversationHistory is initialized before we add cline messages
message.conversationHistoryIndex = this.apiConversationHistory.length - 1 // NOTE: this is the index of the last added message which is the user message, and once the clinemessages have been presented we update the apiconversationhistory with the completed assistant message. This means when resetting to a message, we need to +1 this index to get the correct assistant message that this tool use corresponds to
message.conversationHistoryDeletedRange = this.taskState.conversationHistoryDeletedRange
this.clineMessages.push(message)
await this.saveClineMessagesAndUpdateHistory()
return await this.withStateLock(async () => {
// these values allow us to reconstruct the conversation history at the time this cline message was created
// it's important that apiConversationHistory is initialized before we add cline messages
message.conversationHistoryIndex = this.apiConversationHistory.length - 1 // NOTE: this is the index of the last added message which is the user message, and once the clinemessages have been presented we update the apiconversationhistory with the completed assistant message. This means when resetting to a message, we need to +1 this index to get the correct assistant message that this tool use corresponds to
message.conversationHistoryDeletedRange = this.taskState.conversationHistoryDeletedRange
this.clineMessages.push(message)
await this.saveClineMessagesAndUpdateHistoryInternal()
})
}
/**
* Replace the entire clineMessages array with new messages
* Protected by mutex to prevent concurrent modifications (RC-4)
*/
async overwriteClineMessages(newMessages: ClineMessage[]) {
this.clineMessages = newMessages
await this.saveClineMessagesAndUpdateHistory()
return await this.withStateLock(async () => {
this.clineMessages = newMessages
await this.saveClineMessagesAndUpdateHistoryInternal()
})
}
/**
* Update a specific message in the clineMessages array
* The entire operation (validate, update, save) is atomic to prevent races (RC-4)
*/
async updateClineMessage(index: number, updates: Partial<ClineMessage>): Promise<void> {
if (index < 0 || index >= this.clineMessages.length) {
throw new Error(`Invalid message index: ${index}`)
}
return await this.withStateLock(async () => {
if (index < 0 || index >= this.clineMessages.length) {
throw new Error(`Invalid message index: ${index}`)
}
// Apply updates to the message
Object.assign(this.clineMessages[index], updates)
// Apply updates to the message
Object.assign(this.clineMessages[index], updates)
// Save changes and update history
await this.saveClineMessagesAndUpdateHistory()
// Save changes and update history
await this.saveClineMessagesAndUpdateHistoryInternal()
})
}
/**
* Delete a specific message from the clineMessages array
* The entire operation (validate, delete, save) is atomic to prevent races (RC-4)
*/
async deleteClineMessage(index: number): Promise<void> {
return await this.withStateLock(async () => {
if (index < 0 || index >= this.clineMessages.length) {
throw new Error(`Invalid message index: ${index}`)
}
// Remove the message at the specified index
this.clineMessages.splice(index, 1)
// Save changes and update history
await this.saveClineMessagesAndUpdateHistoryInternal()
})
}
}
@@ -80,6 +80,22 @@ export class AttemptCompletionHandler implements IToolHandler, IPartialBlockHand
}
}
// Remove any partial completion_result message that may exist
// PreToolUse hook inserts messages after the partial, so we need to search backwards to find it
const clineMessages = config.messageState.getClineMessages()
const partialCompletionIndex = findLastIndex(
clineMessages,
(m) => m.partial === true && m.type === "say" && m.say === "completion_result",
)
if (partialCompletionIndex !== -1) {
const updatedMessages = [
...clineMessages.slice(0, partialCompletionIndex),
...clineMessages.slice(partialCompletionIndex + 1),
]
config.messageState.setClineMessages(updatedMessages)
await config.messageState.saveClineMessagesAndUpdateHistory()
}
let commandResult: any
const lastMessage = config.messageState.getClineMessages().at(-1)
@@ -115,6 +131,7 @@ export class AttemptCompletionHandler implements IToolHandler, IPartialBlockHand
// user didn't reject, but the command may have output
commandResult = execCommandResult
} else {
// Send the complete completion_result message (partial was already removed above)
const completionMessageTs = await config.callbacks.say("completion_result", result, undefined, undefined, false)
await config.callbacks.saveCheckpoint(true, completionMessageTs)
await addNewChangesFlagToLastCompletionResultMessage()