From e963d2c194b1b5b991d4e4e01d8b9516b3adb8e1 Mon Sep 17 00:00:00 2001 From: Ara Date: Tue, 6 May 2025 01:14:19 +0400 Subject: [PATCH] Introducing Quote a Message in Chat (#3223) * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Adding double click support * Cleanup * Working better * Working better * Working better * add markdown * add markdown * add markdown * add markdown * add markdown * Lower border radius * Lower border radius * Delete webview-ui/.vite-port --------- Co-authored-by: Frostbourne --- .changeset/serious-wolves-trade.md | 5 + src/shared/ExtensionMessage.ts | 1 + src/shared/WebviewMessage.ts | 1 + .../src/components/chat/BrowserSessionRow.tsx | 16 +- webview-ui/src/components/chat/ChatRow.tsx | 147 +++++++++++++++++- .../src/components/chat/ChatTextArea.tsx | 15 +- webview-ui/src/components/chat/ChatView.tsx | 61 +++++++- .../src/components/chat/QuoteButton.tsx | 58 +++++++ .../components/chat/QuotedMessagePreview.tsx | 89 +++++++++++ 9 files changed, 373 insertions(+), 20 deletions(-) create mode 100644 .changeset/serious-wolves-trade.md create mode 100644 webview-ui/src/components/chat/QuoteButton.tsx create mode 100644 webview-ui/src/components/chat/QuotedMessagePreview.tsx diff --git a/.changeset/serious-wolves-trade.md b/.changeset/serious-wolves-trade.md new file mode 100644 index 00000000..efaa4122 --- /dev/null +++ b/.changeset/serious-wolves-trade.md @@ -0,0 +1,5 @@ +--- +"claude-dev": patch +--- + +adding quote reply support diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts index 201eda70..b15989e2 100644 --- a/src/shared/ExtensionMessage.ts +++ b/src/shared/ExtensionMessage.ts @@ -47,6 +47,7 @@ export interface ExtensionMessage { | "relativePathsResponse" // Handles single and multiple path responses | "fileSearchResults" | "grpc_response" // New type for gRPC responses + | "setActiveQuote" text?: string paths?: (string | null)[] // Used for relativePathsResponse action?: diff --git a/src/shared/WebviewMessage.ts b/src/shared/WebviewMessage.ts index 4c60a329..0e1561c0 100644 --- a/src/shared/WebviewMessage.ts +++ b/src/shared/WebviewMessage.ts @@ -72,6 +72,7 @@ export interface WebviewMessage { | "deleteClineRule" | "copyToClipboard" | "updateTerminalConnectionTimeout" + | "setActiveQuote" // | "relaunchChromeDebugMode" text?: string diff --git a/webview-ui/src/components/chat/BrowserSessionRow.tsx b/webview-ui/src/components/chat/BrowserSessionRow.tsx index a721206b..69ac6926 100644 --- a/webview-ui/src/components/chat/BrowserSessionRow.tsx +++ b/webview-ui/src/components/chat/BrowserSessionRow.tsx @@ -19,6 +19,7 @@ interface BrowserSessionRowProps { lastModifiedMessage?: ClineMessage isLast: boolean onHeightChange: (isTaller: boolean) => void + onSetQuote: (text: string) => void } const browserSessionRowContainerInnerStyle: CSSProperties = { @@ -109,7 +110,7 @@ const headerStyle: CSSProperties = { } const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { - const { messages, isLast, onHeightChange, lastModifiedMessage } = props + const { messages, isLast, onHeightChange, lastModifiedMessage, onSetQuote } = props const { browserSettings } = useExtensionState() const prevHeightRef = useRef(0) const [maxActionHeight, setMaxActionHeight] = useState(0) @@ -290,7 +291,13 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { const [actionContent, { height: actionHeight }] = useSize(
{currentPage?.nextAction?.messages.map((message) => ( - + ))} {!isBrowsing && messages.some((m) => m.say === "browser_action_result") && currentPageIndex === 0 && ( @@ -484,9 +491,10 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => { return browserSessionRow }, deepEqual) -interface BrowserSessionRowContentProps extends Omit { +interface BrowserSessionRowContentProps extends Omit { message: ClineMessage setMaxActionHeight: (height: number) => void + onSetQuote: (text: string) => void } const BrowserSessionRowContent = ({ @@ -496,6 +504,7 @@ const BrowserSessionRowContent = ({ lastModifiedMessage, isLast, setMaxActionHeight, + onSetQuote, }: BrowserSessionRowContentProps) => { if (message.ask === "browser_action_launch" || message.say === "browser_action_launch") { return ( @@ -529,6 +538,7 @@ const BrowserSessionRowContent = ({ }} lastModifiedMessage={lastModifiedMessage} isLast={isLast} + onSetQuote={onSetQuote} />
) diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx index 9a0a51cc..57be21ce 100644 --- a/webview-ui/src/components/chat/ChatRow.tsx +++ b/webview-ui/src/components/chat/ChatRow.tsx @@ -1,6 +1,7 @@ import { VSCodeBadge, VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react" import deepEqual from "fast-deep-equal" -import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react" +import React, { memo, useCallback, useEffect, useMemo, useRef, useState, MouseEvent } from "react" + import { useEvent, useSize } from "react-use" import styled from "styled-components" import { @@ -34,6 +35,7 @@ import TaskFeedbackButtons from "@/components/chat/TaskFeedbackButtons" import NewTaskPreview from "./NewTaskPreview" import McpResourceRow from "@/components/mcp/configuration/tabs/installed/server-row/McpResourceRow" import UserMessage from "./UserMessage" +import QuoteButton from "./QuoteButton" const ChatRowContainer = styled.div` padding: 10px 6px 10px 15px; @@ -53,6 +55,14 @@ interface ChatRowProps { onHeightChange: (isTaller: boolean) => void inputValue?: string sendMessageFromChatRow?: (text: string, images: string[]) => void + onSetQuote: (text: string) => void +} + +interface QuoteButtonState { + visible: boolean + top: number + left: number + selectedText: string } interface ChatRowContentProps extends Omit {} @@ -129,10 +139,17 @@ export const ChatRowContent = ({ isLast, inputValue, sendMessageFromChatRow, + onSetQuote, }: ChatRowContentProps) => { const { mcpServers, mcpMarketplaceCatalog } = useExtensionState() const [seeNewChangesDisabled, setSeeNewChangesDisabled] = useState(false) - + const [quoteButtonState, setQuoteButtonState] = useState({ + visible: false, + top: 0, + left: 0, + selectedText: "", + }) + const contentRef = useRef(null) const [cost, apiReqCancelReason, apiReqStreamingFailedMessage] = useMemo(() => { if (message.text != null && message.say === "api_req_started") { const info: ClineApiReqInfo = JSON.parse(message.text) @@ -173,6 +190,77 @@ export const ChatRowContent = ({ useEvent("message", handleMessage) + // --- Quote Button Logic --- + // MOVE handleQuoteClick INSIDE ChatRowContent + const handleQuoteClick = useCallback(() => { + onSetQuote(quoteButtonState.selectedText) + window.getSelection()?.removeAllRanges() // Clear the browser selection + setQuoteButtonState({ visible: false, top: 0, left: 0, selectedText: "" }) + }, [onSetQuote, quoteButtonState.selectedText]) // <-- Use onSetQuote from props + + const handleMouseUp = useCallback((event: MouseEvent) => { + // Get the target element immediately, before the timeout + const targetElement = event.target as Element + const isClickOnButton = !!targetElement.closest(".quote-button-class") + + // Delay the selection check slightly + setTimeout(() => { + // Now, check the selection state *after* the browser has likely updated it + const selection = window.getSelection() + const selectedText = selection?.toString().trim() ?? "" + + let shouldShowButton = false + let buttonTop = 0 + let buttonLeft = 0 + let textToQuote = "" + + // Condition 1: Check if there's a valid, non-collapsed selection within bounds + // Ensure contentRef.current still exists in case component unmounted during timeout + if (selectedText && contentRef.current && selection && selection.rangeCount > 0 && !selection.isCollapsed) { + const range = selection.getRangeAt(0) + const rangeRect = range.getBoundingClientRect() + // Re-check ref inside timeout and ensure containerRect is valid + const containerRect = contentRef.current?.getBoundingClientRect() + + if (containerRect) { + // Check if containerRect was successfully obtained + const tolerance = 5 // Allow for a small pixel overflow (e.g., for margins) + const isSelectionWithin = + rangeRect.top >= containerRect.top && + rangeRect.left >= containerRect.left && + rangeRect.bottom <= containerRect.bottom + tolerance && // Added tolerance + rangeRect.right <= containerRect.right + + if (isSelectionWithin) { + shouldShowButton = true // Mark that we should show the button + const buttonHeight = 30 + // Calculate the raw top position relative to the container, placing it above the selection + const calculatedTop = rangeRect.top - containerRect.top - buttonHeight - 5 // Subtract button height and a small margin + // Allow the button to potentially have a negative top value + buttonTop = calculatedTop + buttonLeft = Math.max(0, rangeRect.left - containerRect.left) // Still prevent going left of container + textToQuote = selectedText + } + } + } + + // Decision: Set the state based on whether we should show or hide + if (shouldShowButton) { + // Scenario A: Valid selection exists -> Show button + setQuoteButtonState({ + visible: true, + top: buttonTop, + left: buttonLeft, + selectedText: textToQuote, + }) + } else if (!isClickOnButton) { + // Scenario B: No valid selection AND click was NOT on button -> Hide button + setQuoteButtonState({ visible: false, top: 0, left: 0, selectedText: "" }) + } + // Scenario C (Click WAS on button): Do nothing here, handleQuoteClick takes over. + }, 0) // Delay of 0ms pushes execution after current event cycle + }, []) // Dependencies remain empty + const [icon, title] = useMemo(() => { switch (type) { case "error": @@ -502,7 +590,7 @@ export const ChatRowContent = ({
{toolIcon("file-code")} {tool.operationIsLocatedInWorkspace === false && - toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")} + toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")} {message.type === "ask" ? "Cline wants to view source code definition names used in this directory:" @@ -813,8 +901,17 @@ export const ChatRowContent = ({ return case "text": return ( -
+
+ {quoteButtonState.visible && ( + { + handleQuoteClick() + }} + /> + )}
) case "reasoning": @@ -1036,11 +1133,21 @@ export const ChatRowContent = ({ />
+ {quoteButtonState.visible && ( + + )}
{message.partial !== true && hasChanges && (
@@ -1189,11 +1296,21 @@ export const ChatRowContent = ({ />
+ {quoteButtonState.visible && ( + + )} {message.partial !== true && hasChanges && (
)} -
+
+ {quoteButtonState.visible && ( + { + handleQuoteClick() + }} + /> + )}
) @@ -1302,7 +1428,7 @@ export const ChatRowContent = ({ response = message.text } return ( -
+
+ {quoteButtonState.visible && ( + { + handleQuoteClick() + }} + /> + )}
) } diff --git a/webview-ui/src/components/chat/ChatTextArea.tsx b/webview-ui/src/components/chat/ChatTextArea.tsx index cee7862c..94e5bb28 100644 --- a/webview-ui/src/components/chat/ChatTextArea.tsx +++ b/webview-ui/src/components/chat/ChatTextArea.tsx @@ -41,6 +41,7 @@ import ClineRulesToggleModal from "../cline-rules/ClineRulesToggleModal" interface ChatTextAreaProps { inputValue: string + activeQuote: string | null setInputValue: (value: string) => void textAreaDisabled: boolean placeholderText: string @@ -50,6 +51,7 @@ interface ChatTextAreaProps { onSelectImages: () => void shouldDisableImages: boolean onHeightChange?: (height: number) => void + onFocusChange?: (isFocused: boolean) => void } interface GitCommit { @@ -224,6 +226,7 @@ const ChatTextArea = forwardRef( ( { inputValue, + activeQuote, setInputValue, textAreaDisabled, placeholderText, @@ -233,6 +236,7 @@ const ChatTextArea = forwardRef( onSelectImages, shouldDisableImages, onHeightChange, + onFocusChange, }, ref, ) => { @@ -722,7 +726,8 @@ const ChatTextArea = forwardRef( setShowSlashCommandsMenu(false) } setIsTextAreaFocused(false) - }, [isMouseDownOnMenu]) + onFocusChange?.(false) // Call prop on blur + }, [isMouseDownOnMenu, onFocusChange]) const handlePaste = useCallback( async (e: React.ClipboardEvent) => { @@ -1061,7 +1066,6 @@ const ChatTextArea = forwardRef( } } } - /** * Handles the drag over event to allow dropping. * Prevents the default behavior to enable drop. @@ -1294,7 +1298,7 @@ const ChatTextArea = forwardRef( />
)} - {!isTextAreaFocused && ( + {!isTextAreaFocused && !activeQuote && (
( }} onKeyDown={handleKeyDown} onKeyUp={handleKeyUp} - onFocus={() => setIsTextAreaFocused(true)} + onFocus={() => { + setIsTextAreaFocused(true) + onFocusChange?.(true) // Call prop on focus + }} onBlur={handleBlur} onPaste={handlePaste} onSelect={updateCursorPosition} diff --git a/webview-ui/src/components/chat/ChatView.tsx b/webview-ui/src/components/chat/ChatView.tsx index dc537ecb..04018b68 100644 --- a/webview-ui/src/components/chat/ChatView.tsx +++ b/webview-ui/src/components/chat/ChatView.tsx @@ -26,6 +26,7 @@ import AutoApproveMenu from "@/components/chat/AutoApproveMenu" import BrowserSessionRow from "@/components/chat/BrowserSessionRow" import ChatRow from "@/components/chat/ChatRow" import ChatTextArea from "@/components/chat/ChatTextArea" +import QuotedMessagePreview from "@/components/chat/QuotedMessagePreview" import TaskHeader from "@/components/chat/TaskHeader" import TelemetryBanner from "@/components/common/TelemetryBanner" import { unified } from "unified" @@ -86,6 +87,8 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie }, [modifiedMessages]) const [inputValue, setInputValue] = useState("") + const [activeQuote, setActiveQuote] = useState(null) + const [isTextAreaFocused, setIsTextAreaFocused] = useState(false) const textAreaRef = useRef(null) const [textAreaDisabled, setTextAreaDisabled] = useState(false) const [selectedImages, setSelectedImages] = useState([]) @@ -345,10 +348,21 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie const handleSendMessage = useCallback( async (text: string, images: string[]) => { - text = text.trim() - if (text || images.length > 0) { + let messageToSend = text.trim() + const hasContent = messageToSend || images.length > 0 + + // Prepend the active quote if it exists + if (activeQuote && hasContent) { + const prefix = "[context] \n> " + const formattedQuote = activeQuote + const suffix = "\n[/context] \n\n" + messageToSend = `${prefix} ${formattedQuote} ${suffix} ${messageToSend}` + } + + if (hasContent) { + console.log("[ChatView] handleSendMessage - Sending message:", messageToSend) if (messages.length === 0) { - await TaskServiceClient.newTask({ text, images }) + await TaskServiceClient.newTask({ text: messageToSend, images }) } else if (clineAsk) { switch (clineAsk) { case "followup": @@ -366,7 +380,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie vscode.postMessage({ type: "askResponse", askResponse: "messageResponse", - text, + text: messageToSend, images, }) break @@ -374,7 +388,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie vscode.postMessage({ type: "askResponse", askResponse: "messageResponse", - text, + text: messageToSend, images, }) break @@ -382,6 +396,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie } } setInputValue("") + setActiveQuote(null) // Clear quote when sending message setTextAreaDisabled(true) setSelectedImages([]) setClineAsk(undefined) @@ -391,10 +406,11 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie disableAutoScrollRef.current = false } }, - [messages.length, clineAsk], + [messages.length, clineAsk, activeQuote], ) const startNewTask = useCallback(async () => { + setActiveQuote(null) // Clear the active quote state await TaskServiceClient.clearTask({}) }, []) @@ -429,6 +445,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie } // Clear input state after sending setInputValue("") + setActiveQuote(null) // Clear quote when using primary button setSelectedImages([]) break case "completion_result": @@ -495,6 +512,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie } // Clear input state after sending setInputValue("") + setActiveQuote(null) // Clear quote when using secondary button setSelectedImages([]) break } @@ -512,6 +530,10 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie startNewTask() }, [startNewTask]) + const handleFocusChange = useCallback((isFocused: boolean) => { + setIsTextAreaFocused(isFocused) + }, []) + const { selectedModelInfo } = useMemo(() => { return normalizeApiConfiguration(apiConfiguration) }, [apiConfiguration]) @@ -856,6 +878,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie [messageTs]: !prev[messageTs], })) }} + onSetQuote={setActiveQuote} /> ) } @@ -872,10 +895,19 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie onHeightChange={handleRowHeightChange} inputValue={inputValue} sendMessageFromChatRow={handleSendMessage} + onSetQuote={setActiveQuote} /> ) }, - [expandedRows, modifiedMessages, groupedMessages.length, toggleRowExpansion, handleRowHeightChange, inputValue], + [ + expandedRows, + modifiedMessages, + groupedMessages.length, + toggleRowExpansion, + handleRowHeightChange, + inputValue, + setActiveQuote, + ], ) return ( @@ -1045,8 +1077,23 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie )} )} + {(() => { + console.log("[ChatView] Rendering - activeQuote:", activeQuote) // Log here + return activeQuote ? ( +
+ setActiveQuote(null)} + isFocused={isTextAreaFocused} + /> +
+ ) : null + })()} + void +} + +// Define props specifically for the styled component using transient props +interface ButtonContainerProps { + $top: number + $left: number +} + +const ButtonContainer = styled.div` + position: absolute; + top: ${(props) => props.$top}px; // Use transient prop $top + left: ${(props) => props.$left}px; // Use transient prop $left + z-index: 10; // Ensure it's above the text + background-color: var(--vscode-button-background); + border: 1px solid var(--vscode-button-border); + border-radius: 4px; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + transition: transform 0.1s ease; + + &:hover { + transform: scale(1.05); + background-color: var(--vscode-button-hoverBackground); + } +` + +const QuoteButton: React.FC = ({ top, left, onClick }) => { + return ( + // Pass transient props to the styled component + + { + e.stopPropagation() // Prevent triggering mouseup on the parent + onClick() + }} + style={{ padding: "2px 4px", height: "auto", minWidth: "auto" }}> + {" "} + {/* Adjust padding */} + {" "} + {/* Adjust font size */} + + + ) +} + +export default QuoteButton diff --git a/webview-ui/src/components/chat/QuotedMessagePreview.tsx b/webview-ui/src/components/chat/QuotedMessagePreview.tsx new file mode 100644 index 00000000..7f848a3d --- /dev/null +++ b/webview-ui/src/components/chat/QuotedMessagePreview.tsx @@ -0,0 +1,89 @@ +import React, { useEffect } from "react" +import styled from "styled-components" +import { VSCodeButton } from "@vscode/webview-ui-toolkit/react" + +const PreviewContainer = styled.div` + background-color: var(--vscode-input-background); /* Outer box matches text area */ + /* border-left: 3px solid var(--vscode-textBlockQuote-border); */ /* Remove left border */ + /* border-top: 1px solid var(--vscode-editorGroup-border); */ /* Remove top border */ + padding: 4px 4px 4px 4px; /* Removed bottom padding */ + margin: 0px 15px 0 15px; /* Remove bottom+top margin, equal left/right */ + border-radius: 2px 2px 0 0; /* Only round top corners */ + display: flex; + /* flex-direction: column; */ /* No longer needed as Label is removed */ + position: relative; /* Keep for button positioning */ +` + +// Removed Label component + +const ContentRow = styled.div` + /* Mix outer background with white to ensure a much lighter inner box */ + background-color: color-mix(in srgb, var(--vscode-input-background) 70%, white 30%); + border-radius: 2px 2px 2px 2px; /* Round top corners, square bottom corners */ + padding: 8px 10px 10px 8px; /* Reduced left padding */ + display: flex; + align-items: flex-start; /* Align items to the top */ + justify-content: space-between; + width: 100%; +` + +const TextContainer = styled.div` + flex-grow: 1; + margin: 0 2px; /* Further reduced space around text */ + white-space: pre-wrap; + word-break: break-word; + overflow: hidden; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-line-clamp: 3; + -webkit-box-orient: vertical; + font-size: var(--vscode-editor-font-size); /* Use editor font size */ + opacity: 0.9; /* Slightly muted text */ + line-height: 1.4; /* Improve readability */ + max-height: calc(1.4 * var(--vscode-editor-font-size) * 3); /* approx 3 lines */ +` + +const DismissButton = styled(VSCodeButton)` + /* margin-left: auto; */ /* Removed as ContentRow handles spacing */ + flex-shrink: 0; /* Prevent button from shrinking */ + min-width: 22px; + height: 22px; + padding: 0; + /* margin-top: 20px; */ /* Remove top margin */ + display: flex; + align-items: center; + justify-content: center; +` + +const ReplyIcon = styled.span` + color: var(--vscode-descriptionForeground); + margin-right: 2px; /* Further reduced space between icon and text */ + flex-shrink: 0; + font-size: 13px; /* Make icon even smaller */ + /* transform: translateY(-1px); */ /* Removed vertical transform */ +` + +interface QuotedMessagePreviewProps { + text: string + onDismiss: () => void + isFocused?: boolean +} + +const QuotedMessagePreview: React.FC = ({ text, onDismiss, isFocused }) => { + const cardClassName = `reply-card ${isFocused ? "reply-card--focused" : ""}` + + return ( + + {/* Removed Label */} + + + {text} + + + + + + ) +} + +export default QuotedMessagePreview