Skip to content

Commit 4f61112

Browse files
committed
fix(webview): ignore blank or missing follow-up suggestion answers
The model can emit follow-up suggestions with a missing or blank answer. Previously the blank suggestion rendered as an empty button, clicking Copy to input on one pushed undefined into the input state and crashed the webview (TypeError reading trim), and the extension-side auto-approval timeout could still fire and silently auto-answer the question with no content. Fixes #1226
1 parent 38d5ee0 commit 4f61112

8 files changed

Lines changed: 321 additions & 11 deletions

File tree

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import { checkAutoApproval } from ".."
2+
3+
describe("Follow-up question auto-approval", () => {
4+
const baseState = {
5+
autoApprovalEnabled: true,
6+
alwaysAllowFollowupQuestions: true,
7+
followupAutoApproveTimeoutMs: 10_000,
8+
}
9+
10+
const followupText = (suggest: unknown) => JSON.stringify({ question: "Pick one?", suggest }) as string
11+
12+
const run = (state: Record<string, unknown>, text: string) =>
13+
checkAutoApproval({ state: state as never, ask: "followup", text })
14+
15+
it("schedules a timeout that auto-answers with the first valid suggestion", async () => {
16+
const result = await run(baseState, followupText([{ answer: "Yes, proceed" }]))
17+
18+
expect(result.decision).toBe("timeout")
19+
if (result.decision === "timeout") {
20+
expect(result.timeout).toBe(10_000)
21+
expect(result.fn()).toEqual({
22+
askResponse: "messageResponse",
23+
text: "Yes, proceed",
24+
})
25+
}
26+
})
27+
28+
it("skips a blank or missing first answer and uses the next valid suggestion (issue #1226)", async () => {
29+
// Mirrors a malformed model response where JSON round-tripping drops
30+
// `answer: undefined` and the first item is unusable.
31+
const result = await run(baseState, followupText([{}, { answer: " " }, { answer: "Valid answer" }]))
32+
33+
expect(result.decision).toBe("timeout")
34+
if (result.decision === "timeout") {
35+
expect(result.fn()).toEqual({
36+
askResponse: "messageResponse",
37+
text: "Valid answer",
38+
})
39+
}
40+
})
41+
42+
it("falls back to asking when every suggestion answer is blank or missing (issue #1226)", async () => {
43+
// Before the #1226 fix this scheduled a timeout that auto-answered the
44+
// follow-up with `undefined` text, silently accepting an empty answer.
45+
const result = await run(baseState, followupText([{ answer: "" }, { answer: " \n\t " }, {}]))
46+
47+
expect(result).toEqual({ decision: "ask" })
48+
})
49+
50+
it("falls back to asking when the suggestion answer is not a string", async () => {
51+
const result = await run(baseState, followupText([{ answer: 42 }]))
52+
53+
expect(result).toEqual({ decision: "ask" })
54+
})
55+
56+
it("falls back to asking when the follow-up has no suggestions", async () => {
57+
const result = await run(baseState, JSON.stringify({ question: "Pick one?" }))
58+
59+
expect(result).toEqual({ decision: "ask" })
60+
})
61+
62+
it("falls back to asking when the follow-up text is not valid JSON", async () => {
63+
const result = await run(baseState, "not-json")
64+
65+
expect(result).toEqual({ decision: "ask" })
66+
})
67+
68+
it("falls back to asking when the auto-approve timeout is not positive", async () => {
69+
const result = await run({ ...baseState, followupAutoApproveTimeoutMs: 0 }, followupText([{ answer: "Yes" }]))
70+
71+
expect(result).toEqual({ decision: "ask" })
72+
})
73+
74+
it("does not auto-approve when follow-up auto-approval is disabled", async () => {
75+
const result = await run(
76+
{ ...baseState, alwaysAllowFollowupQuestions: false },
77+
followupText([{ answer: "Yes" }]),
78+
)
79+
80+
expect(result).toEqual({ decision: "ask" })
81+
})
82+
83+
it("does not auto-approve when global auto-approval is disabled", async () => {
84+
const result = await run({ ...baseState, autoApprovalEnabled: false }, followupText([{ answer: "Yes" }]))
85+
86+
expect(result).toEqual({ decision: "ask" })
87+
})
88+
})

‎src/core/auto-approval/index.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,15 @@ export async function checkAutoApproval({
6767
if (ask === "followup") {
6868
if (state.alwaysAllowFollowupQuestions === true) {
6969
try {
70-
const suggestion = (JSON.parse(text || "{}") as FollowUpData).suggest?.[0]
70+
const suggestions = (JSON.parse(text || "{}") as FollowUpData).suggest ?? []
71+
72+
// A missing or blank answer would auto-approve the follow-up with no
73+
// content after the timeout (issue #1226), so pick the first suggestion
74+
// with a usable answer. This mirrors the webview's visible-suggestions
75+
// filter in FollowUpSuggest.
76+
const suggestion = suggestions.find(
77+
(item) => typeof item?.answer === "string" && item.answer.trim().length > 0,
78+
)
7179

7280
if (
7381
suggestion &&

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -244,7 +244,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
244244
}, [selectedType, searchQuery])
245245

246246
const handleEnhancePrompt = useCallback(() => {
247-
const trimmedInput = inputValue.trim()
247+
const trimmedInput = (inputValue ?? "").trim()
248248

249249
if (trimmedInput) {
250250
setIsEnhancingPrompt(true)
@@ -258,7 +258,7 @@ export const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
258258

259259
// Memoized check for whether the input has content (text or images)
260260
const hasInputContent = useMemo(() => {
261-
return inputValue.trim().length > 0 || selectedImages.length > 0
261+
return (inputValue ?? "").trim().length > 0 || selectedImages.length > 0
262262
}, [inputValue, selectedImages])
263263

264264
// Compute the key combination text for the send button tooltip based on enterBehavior

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

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1431,6 +1431,14 @@ const ChatViewComponent: React.ForwardRefRenderFunction<ChatViewRef, ChatViewPro
14311431

14321432
const handleSuggestionClickInRow = useCallback(
14331433
(suggestion: SuggestionItem, event?: React.MouseEvent) => {
1434+
// The model may emit suggestions with missing or blank answers (issue #1226).
1435+
// Ignore them instead of pushing an undefined value into the input, which
1436+
// would crash the text area (inputValue.trim on undefined).
1437+
const answer = typeof suggestion?.answer === "string" ? suggestion.answer.trim() : ""
1438+
if (!answer) {
1439+
return
1440+
}
1441+
14341442
// Mark that user has responded if this is a manual click (not auto-approval)
14351443
if (event) {
14361444
userRespondedRef.current = true
@@ -1455,13 +1463,13 @@ const ChatViewComponent: React.ForwardRefRenderFunction<ChatViewRef, ChatViewPro
14551463
if (event?.shiftKey) {
14561464
// Always append to existing text, don't overwrite
14571465
setInputValue((currentValue: string) => {
1458-
return currentValue !== "" ? `${currentValue} \n${suggestion.answer}` : suggestion.answer
1466+
return currentValue !== "" ? `${currentValue} \n${answer}` : answer
14591467
})
14601468
} else {
14611469
// Don't clear the input value when sending a follow-up choice
14621470
// The message should be sent but the text area should preserve what the user typed
14631471
const preservedInput = inputValueRef.current
1464-
handleSendMessage(suggestion.answer, [])
1472+
handleSendMessage(answer, [])
14651473
// Restore the input value after sending
14661474
setInputValue(preservedInput)
14671475
}

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

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useEffect, useState } from "react"
1+
import { useCallback, useEffect, useMemo, useState } from "react"
22
import { ClipboardCopy, Timer } from "lucide-react"
33

44
import { Button, StandardTooltip } from "@/components/ui"
@@ -33,14 +33,25 @@ export const FollowUpSuggest = ({
3333
const [suggestionSelected, setSuggestionSelected] = useState(false)
3434
const { t } = useAppTranslation()
3535

36+
// The model may emit suggestions with missing or blank answers. Those render
37+
// as empty buttons, and clicking "Copy to input" on one pushes an undefined
38+
// string into the chat input and crashes the text area (issue #1226), so hide them.
39+
const visibleSuggestions = useMemo(
40+
() =>
41+
suggestions.filter(
42+
(suggestion) => typeof suggestion?.answer === "string" && suggestion.answer.trim().length > 0,
43+
),
44+
[suggestions],
45+
)
46+
3647
// Start countdown timer when auto-approval is enabled for follow-up questions
3748
useEffect(() => {
3849
// Only start countdown if auto-approval is enabled for follow-up questions and no suggestion has been selected
3950
// Also stop countdown if the question has been answered or auto-approval is paused (user is typing)
4051
if (
4152
autoApprovalEnabled &&
4253
alwaysAllowFollowupQuestions &&
43-
suggestions.length > 0 &&
54+
visibleSuggestions.length > 0 &&
4455
!suggestionSelected &&
4556
!isAnswered &&
4657
!isFollowUpAutoApprovalPaused
@@ -78,7 +89,7 @@ export const FollowUpSuggest = ({
7889
}, [
7990
autoApprovalEnabled,
8091
alwaysAllowFollowupQuestions,
81-
suggestions,
92+
visibleSuggestions,
8293
followupAutoApproveTimeoutMs,
8394
suggestionSelected,
8495
onCancelAutoApproval,
@@ -102,14 +113,14 @@ export const FollowUpSuggest = ({
102113
[onSuggestionClick, onCancelAutoApproval],
103114
)
104115

105-
// Don't render if there are no suggestions or no click handler.
106-
if (!suggestions?.length || !onSuggestionClick) {
116+
// Don't render if there are no visible suggestions or no click handler.
117+
if (visibleSuggestions.length === 0 || !onSuggestionClick) {
107118
return null
108119
}
109120

110121
return (
111122
<div className="flex mb-2 flex-col h-full gap-2">
112-
{suggestions.map((suggestion, index) => {
123+
{visibleSuggestions.map((suggestion, index) => {
113124
const isFirstSuggestion = index === 0
114125
const suggestionMode = getSuggestionMode(suggestion.mode)
115126

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

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1205,4 +1205,34 @@ describe("ChatTextArea", () => {
12051205
expect(sendButton).toHaveClass("pointer-events-auto")
12061206
})
12071207
})
1208+
1209+
describe("blank suggestion copy crash (issue #1226)", () => {
1210+
it("renders without crashing and treats an undefined inputValue as empty", () => {
1211+
// Intentionally pass the malformed value that #1226 produced at runtime:
1212+
// clicking "Copy to input" on an empty follow-up suggestion pushed
1213+
// `undefined` into the input state.
1214+
const undefinedInput = { ...defaultProps, inputValue: undefined } as unknown as typeof defaultProps
1215+
const { container } = render(<ChatTextArea {...undefinedInput} />)
1216+
1217+
// Before the #1226 fix, mounting with an undefined inputValue threw
1218+
// "Cannot read properties of undefined (reading 'trim')" in the
1219+
// hasInputContent memo. It should render normally instead.
1220+
1221+
// Clicking "Enhance prompt" with an undefined input must not crash either:
1222+
// the undefined input behaves like an empty one, so nothing is sent.
1223+
mockPostMessage.mockClear()
1224+
fireEvent.click(getEnhancePromptButton())
1225+
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+
)
1230+
1231+
expect(sendButton).toBeInTheDocument()
1232+
1233+
// An undefined input behaves like an empty input: no content to send.
1234+
expect(sendButton).toHaveClass("opacity-0")
1235+
expect(sendButton).toHaveClass("pointer-events-none")
1236+
})
1237+
})
12081238
})

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

Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ vi.mock("../ChatRow", () => ({
6767
<button
6868
key={suggestion.answer}
6969
type="button"
70+
data-testid="followup-suggestion"
7071
onClick={(event) => onSuggestionClick?.(suggestion, event)}>
7172
{suggestion.answer}
7273
</button>
@@ -1460,6 +1461,109 @@ describe("ChatView - Follow-up Suggestions", () => {
14601461
})
14611462
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "mode" }))
14621463
})
1464+
1465+
it("ignores a blank or missing suggestion answer instead of crashing (issue #1226)", async () => {
1466+
const { getAllByTestId } = renderChatView()
1467+
1468+
// JSON.stringify drops `answer: undefined`, mirroring how the extension
1469+
// delivers a malformed follow-up suggestion (no `answer` property).
1470+
mockPostMessage({
1471+
mode: "ask",
1472+
customModes: [],
1473+
clineMessages: [
1474+
{
1475+
type: "say",
1476+
say: "task",
1477+
ts: Date.now() - 1000,
1478+
text: "Initial task",
1479+
},
1480+
{
1481+
type: "ask",
1482+
ask: "followup",
1483+
ts: Date.now(),
1484+
text: JSON.stringify({
1485+
question: "Pick one?",
1486+
suggest: [{ answer: undefined }, { answer: "Valid answer" }],
1487+
}),
1488+
partial: false,
1489+
},
1490+
],
1491+
})
1492+
1493+
const suggestionButtons = await waitFor(() => {
1494+
const buttons = getAllByTestId("followup-suggestion")
1495+
if (buttons.length !== 2) {
1496+
throw new Error(`expected 2 suggestion buttons, got ${buttons.length}`)
1497+
}
1498+
return buttons
1499+
})
1500+
vscodePostMessageMock.cleanup()
1501+
1502+
// Clicking the blank suggestion must be ignored: no response is sent and
1503+
// no undefined value is pushed into the input state.
1504+
fireEvent.click(suggestionButtons[0])
1505+
1506+
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
1507+
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "mode" }))
1508+
1509+
// The valid suggestion still sends its answer.
1510+
fireEvent.click(suggestionButtons[1])
1511+
1512+
await waitFor(() => {
1513+
expect(vscode.postMessage).toHaveBeenCalledWith({
1514+
type: "askResponse",
1515+
askResponse: "messageResponse",
1516+
text: "Valid answer",
1517+
images: [],
1518+
})
1519+
})
1520+
})
1521+
1522+
it("appends a valid suggestion to the input on shift-click without sending it (issue #1226)", async () => {
1523+
const { getByTestId, getByRole } = renderChatView()
1524+
1525+
mockPostMessage({
1526+
mode: "ask",
1527+
customModes: [],
1528+
clineMessages: [
1529+
{
1530+
type: "say",
1531+
say: "task",
1532+
ts: Date.now() - 1000,
1533+
text: "Initial task",
1534+
},
1535+
{
1536+
type: "ask",
1537+
ask: "followup",
1538+
ts: Date.now(),
1539+
text: JSON.stringify({
1540+
question: "Pick one?",
1541+
suggest: [{ answer: undefined }, { answer: "Copy me" }],
1542+
}),
1543+
partial: false,
1544+
},
1545+
],
1546+
})
1547+
1548+
const suggestion = await waitFor(() => getByRole("button", { name: "Copy me" }))
1549+
vscodePostMessageMock.cleanup()
1550+
1551+
// Pre-fill the draft, then shift-click ("Copy to input") the valid suggestion.
1552+
const input = getByTestId("chat-textarea").querySelector("input")
1553+
if (!input) {
1554+
throw new Error("expected the chat input to be rendered")
1555+
}
1556+
1557+
fireEvent.change(input, { target: { value: "Draft text" } })
1558+
1559+
fireEvent.click(suggestion, { shiftKey: true })
1560+
1561+
// The answer is appended to the existing draft instead of being sent.
1562+
// JSDOM strips line breaks from <input> values (HTML spec "strip newlines"),
1563+
// so the appended "\n" is absent from the DOM value.
1564+
await waitFor(() => expect(input.value).toBe("Draft text Copy me"))
1565+
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
1566+
})
14631567
})
14641568

14651569
describe("ChatView - Context Condensing Indicator Tests", () => {

0 commit comments

Comments
 (0)