🪝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:
1 parent
3698d2356c
commit
dfd113a6e5
75 files changed
+5055
-799
No files matched your search
+265
-56
@@ -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
|
||||
|
||||
Reference in new issue
Block a user