Skip to content

Commit 0972810

Browse files
committed
harden(webview): normalize non-string chat input and cover remaining branches
Address CodeRabbit review on #1226: normalize inputValue once by type check (not only nullish) so every string operation in ChatTextArea is safe, and treat any non-string value as empty. Add non-string regression tests, an empty-draft shift-click case, and a no-text follow-up auto-approval case so the previously partial branches are covered.
1 parent 4f61112 commit 0972810

4 files changed

Lines changed: 67 additions & 28 deletions

File tree

‎src/core/auto-approval/__tests__/followup.spec.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ describe("Follow-up question auto-approval", () => {
2525
}
2626
})
2727

28+
it("falls back to asking when the follow-up has no text payload", async () => {
29+
// Exercises the `text || "{}"` fallback: a follow-up without any payload must
30+
// not schedule an auto-answer timeout.
31+
const result = await checkAutoApproval({ state: baseState as never, ask: "followup" })
32+
33+
expect(result).toEqual({ decision: "ask" })
34+
})
35+
2836
it("skips a blank or missing first answer and uses the next valid suggestion (issue #1226)", async () => {
2937
// Mirrors a malformed model response where JSON round-tripping drops
3038
// `answer: undefined` and the first item is unusable.

‎webview-ui/src/components/chat/ChatTextArea.tsx‎

Lines changed: 31 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,11 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
8282
},
8383
ref,
8484
) => {
85+
// A malformed follow-up answer can push a non-string value into the input state
86+
// (issue #1226). Normalize once so every string operation below (trim, slice,
87+
// indexing, paste, drop, and the textarea value) is safe.
88+
const normalizedInputValue = typeof inputValue === "string" ? inputValue : ""
89+
8590
const { t } = useAppTranslation()
8691
const {
8792
filePaths,
@@ -159,7 +164,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
159164
if (message.text && textAreaRef.current) {
160165
// Insert the command text at the current cursor position
161166
const textarea = textAreaRef.current
162-
const currentValue = inputValue
167+
const currentValue = normalizedInputValue
163168
const cursorPos = textarea.selectionStart || 0
164169

165170
// Check if we need to add a space before the command
@@ -205,7 +210,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
205210

206211
window.addEventListener("message", messageHandler)
207212
return () => window.removeEventListener("message", messageHandler)
208-
}, [setInputValue, searchRequestId, inputValue])
213+
}, [setInputValue, searchRequestId, normalizedInputValue])
209214

210215
const [isDraggingOver, setIsDraggingOver] = useState(false)
211216
const [textAreaBaseHeight, setTextAreaBaseHeight] = useState<number | undefined>(undefined)
@@ -228,7 +233,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
228233
clineMessages,
229234
taskHistory,
230235
cwd,
231-
inputValue,
236+
inputValue: normalizedInputValue,
232237
setInputValue,
233238
})
234239

@@ -244,22 +249,22 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
244249
}, [selectedType, searchQuery])
245250

246251
const handleEnhancePrompt = useCallback(() => {
247-
const trimmedInput = (inputValue ?? "").trim()
252+
const trimmedInput = normalizedInputValue.trim()
248253

249254
if (trimmedInput) {
250255
setIsEnhancingPrompt(true)
251256
vscode.postMessage({ type: "enhancePrompt" as const, text: trimmedInput })
252257
} else {
253258
setInputValue(t("chat:enhancePromptDescription"))
254259
}
255-
}, [inputValue, setInputValue, t])
260+
}, [normalizedInputValue, setInputValue, t])
256261

257262
const allModes = useMemo(() => getAllModes(customModes), [customModes])
258263

259264
// Memoized check for whether the input has content (text or images)
260265
const hasInputContent = useMemo(() => {
261-
return (inputValue ?? "").trim().length > 0 || selectedImages.length > 0
262-
}, [inputValue, selectedImages])
266+
return normalizedInputValue.trim().length > 0 || selectedImages.length > 0
267+
}, [normalizedInputValue, selectedImages])
263268

264269
// Compute the key combination text for the send button tooltip based on enterBehavior
265270
const sendKeyCombination = useMemo(() => {
@@ -508,8 +513,8 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
508513
}
509514

510515
if (event.key === "Backspace" && !isComposing) {
511-
const charBeforeCursor = inputValue[cursorPosition - 1]
512-
const charAfterCursor = inputValue[cursorPosition + 1]
516+
const charBeforeCursor = normalizedInputValue[cursorPosition - 1]
517+
const charAfterCursor = normalizedInputValue[cursorPosition + 1]
513518

514519
const charBeforeIsWhitespace =
515520
charBeforeCursor === " " || charBeforeCursor === "\n" || charBeforeCursor === "\r\n"
@@ -521,7 +526,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
521526
if (
522527
charBeforeIsWhitespace &&
523528
// "$" is added to ensure the match occurs at the end of the string.
524-
inputValue.slice(0, cursorPosition - 1).match(new RegExp(mentionRegex.source + "$"))
529+
normalizedInputValue.slice(0, cursorPosition - 1).match(new RegExp(mentionRegex.source + "$"))
525530
) {
526531
const newCursorPosition = cursorPosition - 1
527532
// If mention is followed by another word, then instead
@@ -536,9 +541,9 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
536541
setCursorPosition(newCursorPosition)
537542
setJustDeletedSpaceAfterMention(true)
538543
} else if (justDeletedSpaceAfterMention) {
539-
const { newText, newPosition } = removeMention(inputValue, cursorPosition)
544+
const { newText, newPosition } = removeMention(normalizedInputValue, cursorPosition)
540545

541-
if (newText !== inputValue) {
546+
if (newText !== normalizedInputValue) {
542547
event.preventDefault()
543548
setInputValue(newText)
544549
setIntendedCursorPosition(newPosition) // Store the new cursor position in state
@@ -558,7 +563,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
558563
selectedMenuIndex,
559564
handleMentionSelect,
560565
selectedType,
561-
inputValue,
566+
normalizedInputValue,
562567
cursorPosition,
563568
setInputValue,
564569
justDeletedSpaceAfterMention,
@@ -577,7 +582,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
577582
textAreaRef.current.setSelectionRange(intendedCursorPosition, intendedCursorPosition)
578583
setIntendedCursorPosition(null) // Reset the state.
579584
}
580-
}, [inputValue, intendedCursorPosition])
585+
}, [normalizedInputValue, intendedCursorPosition])
581586

582587
// Ref to store the search timeout.
583588
const searchTimeoutRef = useRef<NodeJS.Timeout | null>(null)
@@ -677,7 +682,10 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
677682
e.preventDefault()
678683
const trimmedUrl = pastedText.trim()
679684
const newValue =
680-
inputValue.slice(0, cursorPosition) + trimmedUrl + " " + inputValue.slice(cursorPosition)
685+
normalizedInputValue.slice(0, cursorPosition) +
686+
trimmedUrl +
687+
" " +
688+
normalizedInputValue.slice(cursorPosition)
681689
setInputValue(newValue)
682690
const newCursorPosition = cursorPosition + trimmedUrl.length + 1
683691
setCursorPosition(newCursorPosition)
@@ -740,7 +748,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
740748
}
741749
}
742750
},
743-
[shouldDisableImages, setSelectedImages, cursorPosition, setInputValue, inputValue, t],
751+
[shouldDisableImages, setSelectedImages, cursorPosition, setInputValue, normalizedInputValue, t],
744752
)
745753

746754
const handleMenuMouseDown = useCallback(() => {
@@ -790,7 +798,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
790798

791799
useLayoutEffect(() => {
792800
updateHighlights()
793-
}, [inputValue, updateHighlights])
801+
}, [normalizedInputValue, updateHighlights])
794802

795803
const updateCursorPosition = useCallback(() => {
796804
if (textAreaRef.current) {
@@ -822,7 +830,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
822830

823831
if (lines.length > 0) {
824832
// Process each line as a separate file path
825-
let newValue = inputValue.slice(0, cursorPosition)
833+
let newValue = normalizedInputValue.slice(0, cursorPosition)
826834
let totalLength = 0
827835

828836
// Using a standard for loop instead of forEach for potential performance gains.
@@ -841,7 +849,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
841849
}
842850

843851
// Add space after the last mention and append the rest of the input
844-
newValue += " " + inputValue.slice(cursorPosition)
852+
newValue += " " + normalizedInputValue.slice(cursorPosition)
845853
totalLength += 1
846854

847855
setInputValue(newValue)
@@ -902,7 +910,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
902910
[
903911
cursorPosition,
904912
cwd,
905-
inputValue,
913+
normalizedInputValue,
906914
setInputValue,
907915
setCursorPosition,
908916
setIntendedCursorPosition,
@@ -995,7 +1003,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
9951003
<ContextMenu
9961004
onSelect={handleMentionSelect}
9971005
searchQuery={searchQuery}
998-
inputValue={inputValue}
1006+
inputValue={normalizedInputValue}
9991007
onMouseDown={handleMenuMouseDown}
10001008
selectedIndex={selectedMenuIndex}
10011009
setSelectedIndex={setSelectedMenuIndex}
@@ -1058,7 +1066,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
10581066
}
10591067
textAreaRef.current = el
10601068
}}
1061-
value={inputValue}
1069+
value={normalizedInputValue}
10621070
onChange={(e) => {
10631071
handleInputChange(e)
10641072
updateHighlights()
@@ -1264,7 +1272,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
12641272
</StandardTooltip>
12651273
</div>
12661274

1267-
{!inputValue && (
1275+
{!normalizedInputValue && (
12681276
<div
12691277
className={cn(
12701278
"absolute left-2 z-30 flex items-center h-8 font-vscode-font-family text-vscode-editor-font-size leading-vscode-editor-line-height",

‎webview-ui/src/components/chat/__tests__/ChatTextArea.spec.tsx‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1207,6 +1207,11 @@ describe("ChatTextArea", () => {
12071207
})
12081208

12091209
describe("blank suggestion copy crash (issue #1226)", () => {
1210+
const getSendButton = (container: HTMLElement) => {
1211+
const buttons = container.querySelectorAll("button")
1212+
return Array.from(buttons).find((button) => button.querySelector(".lucide-send-horizontal") !== null)
1213+
}
1214+
12101215
it("renders without crashing and treats an undefined inputValue as empty", () => {
12111216
// Intentionally pass the malformed value that #1226 produced at runtime:
12121217
// clicking "Copy to input" on an empty follow-up suggestion pushed
@@ -1223,14 +1228,26 @@ describe("ChatTextArea", () => {
12231228
mockPostMessage.mockClear()
12241229
fireEvent.click(getEnhancePromptButton())
12251230
expect(mockPostMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "enhancePrompt" }))
1226-
const buttons = container.querySelectorAll("button")
1227-
const sendButton = Array.from(buttons).find(
1228-
(button) => button.querySelector(".lucide-send-horizontal") !== null,
1229-
)
12301231

1232+
// An undefined input behaves like an empty input: no content to send.
1233+
const sendButton = getSendButton(container)
12311234
expect(sendButton).toBeInTheDocument()
1235+
expect(sendButton).toHaveClass("opacity-0")
1236+
expect(sendButton).toHaveClass("pointer-events-none")
1237+
})
12321238

1233-
// An undefined input behaves like an empty input: no content to send.
1239+
it.each([0, false, { answer: "nope" }])("treats a non-string inputValue of %p as empty", (value) => {
1240+
// Only nullish values were normalized before the #1226 follow-up fix;
1241+
// any other non-string value must be treated as empty, not crash.
1242+
const badInput = { ...defaultProps, inputValue: value } as unknown as typeof defaultProps
1243+
const { container } = render(<ChatTextArea {...badInput} />)
1244+
1245+
mockPostMessage.mockClear()
1246+
fireEvent.click(getEnhancePromptButton())
1247+
expect(mockPostMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "enhancePrompt" }))
1248+
1249+
const sendButton = getSendButton(container)
1250+
expect(sendButton).toBeInTheDocument()
12341251
expect(sendButton).toHaveClass("opacity-0")
12351252
expect(sendButton).toHaveClass("pointer-events-none")
12361253
})

‎webview-ui/src/components/chat/__tests__/ChatView.spec.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1563,6 +1563,12 @@ describe("ChatView - Follow-up Suggestions", () => {
15631563
// so the appended "\n" is absent from the DOM value.
15641564
await waitFor(() => expect(input.value).toBe("Draft text Copy me"))
15651565
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
1566+
1567+
// With an empty draft the answer is set as-is (no dangling "\n" prefix).
1568+
fireEvent.change(input, { target: { value: "" } })
1569+
fireEvent.click(suggestion, { shiftKey: true })
1570+
await waitFor(() => expect(input.value).toBe("Copy me"))
1571+
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
15661572
})
15671573
})
15681574

0 commit comments

Comments
 (0)