From b858277da3f0e8a5e2f9d50d9fe8f68bb9b8d1b8 Mon Sep 17 00:00:00 2001 From: Bee <68532117+abeatrix@users.noreply.github.com> Date: Thu, 11 Sep 2025 11:39:46 -0700 Subject: [PATCH] Add ESC key listener for task cancellation (#6121) * - Add ESC key listener for task cancellation - Refactor action buttons to use typed button actions to clean up unused code - Replace string-based button handling with ButtonActionType enum - Add ActionButtonConfig interface for better type safety - Implement executeButtonAction method for centralized action handling - Consolidate button click logic into reusable handlers * clean up * add changeset --- .changeset/cool-pumas-report.md | 5 + .../components/layout/ActionButtons.tsx | 124 +++++++++--------- .../chat-view/hooks/useMessageHandlers.ts | 52 +------- .../chat/chat-view/shared/buttonConfig.ts | 4 +- .../chat/chat-view/types/chatTypes.ts | 3 +- 5 files changed, 72 insertions(+), 116 deletions(-) create mode 100644 .changeset/cool-pumas-report.md diff --git a/.changeset/cool-pumas-report.md b/.changeset/cool-pumas-report.md new file mode 100644 index 00000000..38d0db20 --- /dev/null +++ b/.changeset/cool-pumas-report.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +Adds ESC key listener and refactors button handling to use typed actions diff --git a/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx b/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx index 02b2a529..a7e1ce1e 100644 --- a/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx +++ b/webview-ui/src/components/chat/chat-view/components/layout/ActionButtons.tsx @@ -2,8 +2,8 @@ import type { ClineMessage } from "@shared/ExtensionMessage" import type { Mode } from "@shared/storage/types" import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" import type React from "react" -import { useEffect, useMemo, useState } from "react" -import { BUTTON_CONFIGS, getButtonConfig } from "../../shared/buttonConfig" +import { useCallback, useEffect, useMemo, useRef } from "react" +import { ButtonActionType, getButtonConfig } from "../../shared/buttonConfig" import type { ChatState, MessageHandlers } from "../../types/chatTypes" interface ActionButtonsProps { @@ -31,19 +31,25 @@ export const ActionButtons: React.FC = ({ scrollBehavior, }) => { const { inputValue, selectedImages, selectedFiles, setSendingDisabled } = chatState + const isProcessingRef = useRef(false) - const isStreaming = useMemo(() => task?.partial === true, [task]) - - const [primaryButtonText, setPrimaryButtonText] = useState(undefined) - const [secondaryButtonText, setSecondaryButtonText] = useState(undefined) - - const [enableButtons, setEnableButtons] = useState(false) - const [isProcessingClick, setIsProcessingClick] = useState(false) - + // Memoize last messages to avoid unnecessary recalculations const [lastMessage, secondLastMessage] = useMemo(() => { - return [messages.at(-1), messages.at(-2)] + const len = messages.length + return len > 0 ? [messages[len - 1], messages[len - 2]] : [undefined, undefined] }, [messages]) + // Memoize button configuration to avoid recalculation on every render + const buttonConfig = useMemo(() => { + return lastMessage ? getButtonConfig(lastMessage, mode) : { sendingDisabled: false, enableButtons: false } + }, [lastMessage, mode]) + + // Single effect to handle all configuration updates + useEffect(() => { + setSendingDisabled(buttonConfig.sendingDisabled) + isProcessingRef.current = false + }, [buttonConfig, setSendingDisabled]) + // Clear input when transitioning from command_output to api_req // This happens when user provides feedback during command execution useEffect(() => { @@ -52,30 +58,36 @@ export const ActionButtons: React.FC = ({ chatState.setSelectedImages([]) chatState.setSelectedFiles([]) } - }, [chatState, lastMessage, secondLastMessage]) + }, [lastMessage?.type, lastMessage?.say, secondLastMessage?.ask, chatState]) - // Apply button configuration with a single batched update - useEffect(() => { - const buttonConfig = getButtonConfig(lastMessage, mode) - setEnableButtons(buttonConfig.enableButtons) - setSendingDisabled(buttonConfig.sendingDisabled) - setPrimaryButtonText(buttonConfig.primaryText) - setSecondaryButtonText(buttonConfig.secondaryText) - // Reset processing state when configuration changes (new message received) - setIsProcessingClick(false) - }, [lastMessage, mode, setSendingDisabled]) + // Optimized action handler with ref to avoid processing state updates + const handleActionClick = useCallback( + (action: ButtonActionType, text?: string, images?: string[], files?: string[]) => { + if (isProcessingRef.current) { + return + } + isProcessingRef.current = true + messageHandlers.executeButtonAction(action, text, images, files) + }, + [messageHandlers], + ) + + // Keyboard event handler + const handleKeyDown = useCallback( + (event: KeyboardEvent) => { + if (event.key === "Escape") { + event.preventDefault() + event.stopPropagation() + messageHandlers.executeButtonAction("cancel") + } + }, + [messageHandlers], + ) useEffect(() => { - if (!messages?.length) { - const buttonConfig = BUTTON_CONFIGS.default - setEnableButtons(buttonConfig.enableButtons) - setSendingDisabled(buttonConfig.sendingDisabled) - setPrimaryButtonText(buttonConfig.primaryText) - setSecondaryButtonText(buttonConfig.secondaryText) - // Reset processing state when no messages - setIsProcessingClick(false) - } - }, [messages, setSendingDisabled]) + window.addEventListener("keydown", handleKeyDown) + return () => window.removeEventListener("keydown", handleKeyDown) + }, [handleKeyDown]) if (!task) { return null @@ -83,6 +95,7 @@ export const ActionButtons: React.FC = ({ const { showScrollToBottom, scrollToBottomSmooth, disableAutoScrollRef } = scrollBehavior + // Early return for scroll button to avoid unnecessary computation if (showScrollToBottom) { const handleScrollToBottom = () => { scrollToBottomSmooth() @@ -108,48 +121,35 @@ export const ActionButtons: React.FC = ({ ) } - const shouldShowButtons = primaryButtonText || secondaryButtonText - const enableAndNotProcessing = enableButtons && !isProcessingClick - const opacity = shouldShowButtons ? (enableAndNotProcessing || isStreaming ? 1 : 0.5) : 0 + const { primaryText, secondaryText, primaryAction, secondaryAction, enableButtons } = buttonConfig + const hasButtons = primaryText || secondaryText + const isStreaming = task.partial === true + const canInteract = enableButtons && !isProcessingRef.current - const handlePrimaryClick = async () => { - if (!primaryButtonText) { - return - } - setIsProcessingClick(true) - if (primaryButtonText === "Start New Task") { - messageHandlers.startNewTask() - } else { - messageHandlers.handleButtonClick(primaryButtonText, inputValue, selectedImages, selectedFiles) - } + if (!hasButtons) { + return null } - const handleSecondaryClick = async () => { - if (!secondaryButtonText) { - return - } - setIsProcessingClick(true) - messageHandlers.handleButtonClick(secondaryButtonText, inputValue, selectedImages, selectedFiles) - } + const opacity = canInteract || isStreaming ? 1 : 0.5 return (
- {primaryButtonText && ( + {primaryText && primaryAction && ( - {primaryButtonText} + className={secondaryText ? "flex-1 mr-[6px]" : "flex-[2]"} + disabled={!canInteract} + onClick={() => handleActionClick(primaryAction, inputValue, selectedImages, selectedFiles)}> + {primaryText} )} - {secondaryButtonText && ( + {secondaryText && secondaryAction && ( - {secondaryButtonText} + className={primaryText ? "flex-1 mr-[6px]" : "flex-[2]"} + disabled={!canInteract} + onClick={() => handleActionClick(secondaryAction, inputValue, selectedImages, selectedFiles)}> + {secondaryText} )}
diff --git a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts index 13daf2f5..d9f86fea 100644 --- a/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts +++ b/webview-ui/src/components/chat/chat-view/hooks/useMessageHandlers.ts @@ -189,12 +189,6 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat case "new_task": if (clineAsk === "new_task") { - console.info("new task button clicked!", { - lastMessage, - messages, - clineAsk, - text, - }) await TaskServiceClient.newTask( NewTaskRequest.create({ text: lastMessage?.text, @@ -234,50 +228,6 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat [clineAsk, lastMessage, messages, clearInputState, handleSendMessage, startNewTask, chatState], ) - // Unified button click handler that takes action directly - const handleButtonClick = useCallback( - async (action: string, text?: string, images?: string[], files?: string[]) => { - // Map action strings to ButtonActionType - let actionType: ButtonActionType - - switch (action) { - case "Approve": - case "Save": - case "Run Command": - case "Retry": - case "Switch to Act Mode": - actionType = "approve" - break - case "Reject": - actionType = "reject" - break - case "Proceed": - case "Proceed Anyways": - case "Proceed While Running": - case "Resume Task": - actionType = "proceed" - break - case "Start New Task": - case "Start New Task with Context": - actionType = "new_task" - break - case "Cancel": - actionType = "cancel" - break - case "Condense Conversation": - case "Report GitHub issue": - actionType = "utility" - break - default: - console.warn(`Unknown action: ${action}`) - return - } - - await executeButtonAction(actionType, text, images, files) - }, - [executeButtonAction], - ) - // Handle task close button click const handleTaskCloseButtonClick = useCallback(() => { startNewTask() @@ -285,7 +235,7 @@ export function useMessageHandlers(messages: ClineMessage[], chatState: ChatStat return { handleSendMessage, - handleButtonClick, + executeButtonAction, handleTaskCloseButtonClick, startNewTask, } diff --git a/webview-ui/src/components/chat/chat-view/shared/buttonConfig.ts b/webview-ui/src/components/chat/chat-view/shared/buttonConfig.ts index 28c2e25d..9a87ab7f 100644 --- a/webview-ui/src/components/chat/chat-view/shared/buttonConfig.ts +++ b/webview-ui/src/components/chat/chat-view/shared/buttonConfig.ts @@ -183,7 +183,7 @@ export const BUTTON_CONFIGS: Record = { sendingDisabled: true, enableButtons: true, primaryText: undefined, - secondaryText: "Cancel", + secondaryText: "Cancel (ESC)", primaryAction: undefined, secondaryAction: "cancel", }, @@ -201,7 +201,7 @@ export const BUTTON_CONFIGS: Record = { sendingDisabled: true, enableButtons: true, primaryText: undefined, - secondaryText: "Cancel", + secondaryText: "Cancel (ESC)", primaryAction: undefined, secondaryAction: "cancel", }, diff --git a/webview-ui/src/components/chat/chat-view/types/chatTypes.ts b/webview-ui/src/components/chat/chat-view/types/chatTypes.ts index 5b491bd2..7cb896f0 100644 --- a/webview-ui/src/components/chat/chat-view/types/chatTypes.ts +++ b/webview-ui/src/components/chat/chat-view/types/chatTypes.ts @@ -4,6 +4,7 @@ import { ClineAsk, ClineMessage } from "@shared/ExtensionMessage" import { VirtuosoHandle } from "react-virtuoso" +import { ButtonActionType } from "../shared/buttonConfig" /** * Main ChatView component props @@ -65,8 +66,8 @@ export interface ChatState { * Message handlers interface */ export interface MessageHandlers { + executeButtonAction: (action: ButtonActionType, text?: string, images?: string[], files?: string[]) => Promise handleSendMessage: (text: string, images: string[], files: string[]) => Promise - handleButtonClick: (action: string, text?: string, images?: string[], files?: string[]) => Promise handleTaskCloseButtonClick: () => void startNewTask: () => Promise }