Skip to content

Commit 5327051

Browse files
committed
fix(webview): share first-usable-suggestion rule and add mutation coverage
Address the round-2 mutation-diff results for the blank/missing follow-up suggestion fix: - Add a shared firstUsableSuggestion() helper to @roo-code/types and use it in the extension-host auto-approval path, so the "first usable suggestion" rule lives in one place. - Cover the remaining surviving mutants with regression tests in ChatTextArea, ChatView, and FollowUpSuggest (stale effect deps, cursor handling, trim on shift-click, and the answered state).
1 parent aa48e39 commit 5327051

6 files changed

Lines changed: 270 additions & 7 deletions

File tree

‎packages/types/src/__tests__/followup.test.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
1-
import { followUpDataSchema, hasUsableAnswer, suggestionItemSchema, type SuggestionItem } from "../followup.js"
1+
import {
2+
firstUsableSuggestion,
3+
followUpDataSchema,
4+
hasUsableAnswer,
5+
suggestionItemSchema,
6+
type SuggestionItem,
7+
} from "../followup.js"
28

39
describe("hasUsableAnswer", () => {
410
it("accepts a non-blank string answer", () => {
@@ -32,6 +38,19 @@ describe("hasUsableAnswer", () => {
3238
})
3339
})
3440

41+
describe("firstUsableSuggestion", () => {
42+
it("returns undefined for missing or empty suggestions", () => {
43+
expect(firstUsableSuggestion(undefined)).toBeUndefined()
44+
expect(firstUsableSuggestion(null)).toBeUndefined()
45+
expect(firstUsableSuggestion([])).toBeUndefined()
46+
})
47+
48+
it("skips blank or missing answers and returns the first usable item", () => {
49+
const suggestions: SuggestionItem[] = [{}, { answer: " " }, { answer: " ok " }]
50+
expect(firstUsableSuggestion(suggestions)).toEqual({ answer: " ok " })
51+
})
52+
})
53+
3554
describe("suggestionItemSchema", () => {
3655
it("accepts a suggestion without an answer (issue #1226)", () => {
3756
expect(suggestionItemSchema.parse({ mode: "code" })).toEqual({ mode: "code" })

‎packages/types/src/followup.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,17 @@ export const getSuggestionMode = (mode: unknown): string | undefined => {
5454
*/
5555
export const hasUsableAnswer = (
5656
suggestion: { answer?: unknown } | null | undefined,
57-
): suggestion is { answer: string } => typeof suggestion?.answer === "string" && suggestion.answer.trim().length > 0
57+
): suggestion is SuggestionItem & { answer: string } =>
58+
typeof suggestion?.answer === "string" && suggestion.answer.trim().length > 0
59+
60+
/**
61+
* The first suggestion with a usable answer, if any.
62+
*
63+
* Shared by the extension-host auto-approval (`checkAutoApproval`) and the
64+
* webview so the "first usable suggestion" rule stays in one place.
65+
*/
66+
export const firstUsableSuggestion = (suggestions?: SuggestionItem[] | null): SuggestionItem | undefined =>
67+
(suggestions ?? []).find((s) => hasUsableAnswer(s))
5868

5969
/**
6070
* Zod schema for SuggestionItem

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

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import {
2-
hasUsableAnswer,
2+
firstUsableSuggestion,
33
type ClineAsk,
44
type ClineSayTool,
55
type McpServerUse,
@@ -180,13 +180,11 @@ export async function checkAutoApproval({
180180
if (ask === "followup") {
181181
if (state.alwaysAllowFollowupQuestions === true) {
182182
try {
183-
const suggestions = (JSON.parse(text || "{}") as FollowUpData).suggest ?? []
184-
185183
// A missing or blank answer would auto-approve the follow-up with no
186184
// content after the timeout (issue #1226), so pick the first suggestion
187185
// with a usable answer. This mirrors the webview's visible-suggestions
188186
// filter in FollowUpSuggest.
189-
const suggestion = suggestions.find(hasUsableAnswer)
187+
const suggestion = firstUsableSuggestion((JSON.parse(text || "{}") as FollowUpData).suggest)
190188

191189
if (
192190
suggestion &&

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

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1347,5 +1347,154 @@ describe("ChatTextArea", () => {
13471347
// The URL is inserted at cursor position 0, followed by a space.
13481348
expect(defaultProps.setInputValue).toHaveBeenCalledWith("https://example.com visit ")
13491349
})
1350+
1351+
it("uses the re-rendered input when inserting command text", () => {
1352+
const { container, rerender } = render(<ChatTextArea {...defaultProps} inputValue="hello " />)
1353+
rerender(<ChatTextArea {...defaultProps} inputValue="updated " />)
1354+
// Reset the DOM cursor: JSDOM moves the selection to the end of a
1355+
// re-rendered value, so anchor the insertion at position 0 explicitly.
1356+
getTextarea(container).setSelectionRange(0, 0)
1357+
1358+
act(() => {
1359+
window.dispatchEvent(
1360+
new MessageEvent("message", { data: { type: "insertTextIntoTextarea", text: "/command" } }),
1361+
)
1362+
})
1363+
1364+
// A stale effect would still insert into the original "hello " value.
1365+
expect(defaultProps.setInputValue).toHaveBeenCalledWith("/command updated ")
1366+
})
1367+
1368+
it("posts the trimmed input on enhance and follows a re-rendered value", () => {
1369+
const { rerender } = render(<ChatTextArea {...defaultProps} inputValue=" Test prompt " />)
1370+
1371+
fireEvent.click(getEnhancePromptButton())
1372+
// Surrounding whitespace must not reach the extension.
1373+
expect(mockPostMessage).toHaveBeenCalledWith({ type: "enhancePrompt", text: "Test prompt" })
1374+
1375+
rerender(<ChatTextArea {...defaultProps} inputValue="updated" />)
1376+
fireEvent.click(getEnhancePromptButton())
1377+
// A stale handler would re-post the original "Test prompt" value.
1378+
expect(mockPostMessage).toHaveBeenLastCalledWith({ type: "enhancePrompt", text: "updated" })
1379+
})
1380+
1381+
it("keeps whitespace-only input hidden from the send button and placeholder", () => {
1382+
const getSendButton = (container: HTMLElement) =>
1383+
Array.from(container.querySelectorAll("button")).find((b) => b.querySelector(".lucide-send-horizontal"))
1384+
const { container, rerender } = render(<ChatTextArea {...defaultProps} inputValue=" " />)
1385+
1386+
// Whitespace-only input has no sendable content, and the placeholder only
1387+
// renders for a truly empty value.
1388+
expect(getSendButton(container)).toHaveClass("opacity-0")
1389+
expect(container.querySelector(".left-2.z-30")).toBeNull()
1390+
1391+
// A stale content memo would keep the send button hidden for real text.
1392+
rerender(<ChatTextArea {...defaultProps} inputValue="Text" />)
1393+
expect(getSendButton(container)).toHaveClass("opacity-100")
1394+
})
1395+
1396+
it("moves the cursor to the end of the mention on Backspace at the end of the input", () => {
1397+
const { container } = render(<ChatTextArea {...defaultProps} inputValue="hello @problems " />)
1398+
const textarea = getTextarea(container)
1399+
1400+
textarea.setSelectionRange(16, 16)
1401+
fireEvent.mouseUp(textarea)
1402+
fireEvent.keyDown(textarea, { key: "Backspace" })
1403+
1404+
// Nothing follows the trailing space, so the space is not deleted; the
1405+
// cursor moves to the end of the mention instead.
1406+
expect(textarea.selectionStart).toBe(15)
1407+
expect(defaultProps.setInputValue).not.toHaveBeenCalled()
1408+
})
1409+
1410+
it("does not intercept Backspace when a word follows the mention", () => {
1411+
const { container } = render(<ChatTextArea {...defaultProps} inputValue="@problems done " />)
1412+
const textarea = getTextarea(container)
1413+
1414+
textarea.setSelectionRange(15, 15)
1415+
fireEvent.mouseUp(textarea)
1416+
fireEvent.keyDown(textarea, { key: "Backspace" })
1417+
1418+
// The mention is not at the end of the inspected prefix, so the
1419+
// selection is untouched.
1420+
expect(textarea.selectionStart).toBe(15)
1421+
expect(defaultProps.setInputValue).not.toHaveBeenCalled()
1422+
})
1423+
1424+
it("applies the pending cursor once the pasted value commits", () => {
1425+
const { container, rerender } = render(<ChatTextArea {...defaultProps} inputValue="visit " />)
1426+
const textarea = getTextarea(container)
1427+
1428+
const pasteEvent = new window.Event("paste", { bubbles: true, cancelable: true })
1429+
Object.defineProperty(pasteEvent, "clipboardData", {
1430+
value: { items: [], getData: () => "https://example.com" },
1431+
})
1432+
1433+
act(() => {
1434+
textarea.dispatchEvent(pasteEvent)
1435+
// Commit the value the paste handler produced so the pending cursor
1436+
// (0 + 19 + 1 = 20) is applied against the full 26-char value.
1437+
rerender(<ChatTextArea {...defaultProps} inputValue="https://example.com visit " />)
1438+
})
1439+
1440+
// A stale effect would never re-apply the intended cursor position.
1441+
expect(defaultProps.setInputValue).toHaveBeenLastCalledWith("https://example.com visit ")
1442+
expect(textarea.selectionStart).toBe(20)
1443+
})
1444+
1445+
it("inserts a pasted URL at the cursor and tracks re-rendered input", () => {
1446+
const { container, rerender } = render(<ChatTextArea {...defaultProps} inputValue="visit this" />)
1447+
const textarea = getTextarea(container)
1448+
1449+
textarea.setSelectionRange(6, 6)
1450+
fireEvent.mouseUp(textarea)
1451+
1452+
const pasteEvent = new window.Event("paste", { bubbles: true, cancelable: true })
1453+
Object.defineProperty(pasteEvent, "clipboardData", {
1454+
value: { items: [], getData: () => "https://example.com" },
1455+
})
1456+
1457+
act(() => {
1458+
textarea.dispatchEvent(pasteEvent)
1459+
})
1460+
1461+
// The URL splits "visit this" at the cursor instead of reusing the whole
1462+
// value for the tail.
1463+
expect(defaultProps.setInputValue).toHaveBeenLastCalledWith("visit https://example.com this")
1464+
1465+
rerender(<ChatTextArea {...defaultProps} inputValue="changed " />)
1466+
textarea.setSelectionRange(0, 0)
1467+
fireEvent.mouseUp(textarea)
1468+
act(() => {
1469+
textarea.dispatchEvent(pasteEvent)
1470+
})
1471+
// A stale paste handler would repeat the original "visit this" value.
1472+
expect(defaultProps.setInputValue).toHaveBeenLastCalledWith("https://example.com changed ")
1473+
})
1474+
1475+
it("re-highlights mentions after the input changes", () => {
1476+
const { container, rerender } = render(<ChatTextArea {...defaultProps} inputValue="" />)
1477+
rerender(<ChatTextArea {...defaultProps} inputValue="@problems" />)
1478+
1479+
// A stale highlight effect would keep the empty highlight from the
1480+
// initial render.
1481+
expect(container.querySelector('[data-testid="highlight-layer"]')?.innerHTML).toContain("<mark")
1482+
})
1483+
1484+
it("inserts a dropped path at the cursor and preserves the tail", () => {
1485+
const { container } = render(<ChatTextArea {...defaultProps} inputValue="abcdef" />)
1486+
const textarea = getTextarea(container)
1487+
1488+
textarea.setSelectionRange(3, 3)
1489+
fireEvent.mouseUp(textarea)
1490+
1491+
fireEvent.drop(container.querySelector(".chat-text-area")!, {
1492+
dataTransfer: { getData: () => "/some/path", files: [] },
1493+
preventDefault: vi.fn(),
1494+
})
1495+
1496+
// The remainder after the cursor ("def") is preserved.
1497+
expect(defaultProps.setInputValue).toHaveBeenCalledWith("abc/some/path def")
1498+
})
13501499
})
13511500
})

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

Lines changed: 46 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,15 +54,17 @@ vi.mock("../ChatRow", () => ({
5454
default: function MockChatRow({
5555
message,
5656
onSuggestionClick,
57+
isFollowUpAnswered,
5758
}: {
5859
message: ClineMessage
5960
onSuggestionClick?: (suggestion: SuggestionItem, event?: React.MouseEvent) => void
61+
isFollowUpAnswered?: boolean
6062
}) {
6163
if (message.type === "ask" && message.ask === "followup" && message.text) {
6264
try {
6365
const followUp = JSON.parse(message.text) as { suggest?: SuggestionItem[] }
6466
return (
65-
<div data-testid="chat-row">
67+
<div data-testid="chat-row" data-answered={isFollowUpAnswered === true ? "true" : "false"}>
6668
{followUp.suggest?.map((suggestion) => (
6769
<button
6870
key={suggestion.answer}
@@ -1505,6 +1507,8 @@ describe("ChatView - Follow-up Suggestions", () => {
15051507

15061508
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
15071509
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "mode" }))
1510+
// The ignored click must not mark the follow-up as answered either.
1511+
expect(suggestionButtons[0].closest('[data-testid="chat-row"]')?.getAttribute("data-answered")).toBe("false")
15081512

15091513
// The valid suggestion still sends its answer.
15101514
fireEvent.click(suggestionButtons[1])
@@ -1570,6 +1574,47 @@ describe("ChatView - Follow-up Suggestions", () => {
15701574
await waitFor(() => expect(input.value).toBe("Copy me"))
15711575
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
15721576
})
1577+
1578+
it("trims a padded suggestion answer before appending it on shift-click (issue #1226)", async () => {
1579+
const { getByTestId, getByRole } = renderChatView()
1580+
1581+
mockPostMessage({
1582+
mode: "ask",
1583+
customModes: [],
1584+
clineMessages: [
1585+
{
1586+
type: "say",
1587+
say: "task",
1588+
ts: Date.now() - 1000,
1589+
text: "Initial task",
1590+
},
1591+
{
1592+
type: "ask",
1593+
ask: "followup",
1594+
ts: Date.now(),
1595+
text: JSON.stringify({
1596+
question: "Pick one?",
1597+
suggest: [{ answer: " Padded " }],
1598+
}),
1599+
partial: false,
1600+
},
1601+
],
1602+
})
1603+
1604+
const suggestion = await waitFor(() => getByRole("button", { name: "Padded" }))
1605+
vscodePostMessageMock.cleanup()
1606+
1607+
const input = getByTestId("chat-textarea").querySelector("input")
1608+
if (!input) {
1609+
throw new Error("expected the chat input to be rendered")
1610+
}
1611+
1612+
// The padded answer reaches the input trimmed (issue #1226).
1613+
fireEvent.click(suggestion, { shiftKey: true })
1614+
1615+
await waitFor(() => expect(input.value).toBe("Padded"))
1616+
expect(vscode.postMessage).not.toHaveBeenCalledWith(expect.objectContaining({ type: "askResponse" }))
1617+
})
15731618
})
15741619

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

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -771,5 +771,47 @@ describe("FollowUpSuggest", () => {
771771
// Auto-approval must not select a blank suggestion.
772772
expect(mockOnSuggestionClick).not.toHaveBeenCalled()
773773
})
774+
775+
it("does not call the cancel callback on unmount when no usable suggestion starts the countdown", () => {
776+
const { unmount } = renderWithMalformedSuggestions([{ answer: "" }])
777+
778+
unmount()
779+
780+
// No countdown started, so unmounting must not cancel a backend timeout.
781+
expect(mockOnCancelAutoApproval).not.toHaveBeenCalled()
782+
})
783+
})
784+
785+
describe("stale visible-suggestions memo (issue #1226)", () => {
786+
it("re-renders the suggestion list when the suggestions prop changes", () => {
787+
const { rerender } = renderWithTestProviders(
788+
<FollowUpSuggest
789+
suggestions={[{ answer: "First" }]}
790+
onSuggestionClick={mockOnSuggestionClick}
791+
ts={123}
792+
onCancelAutoApproval={mockOnCancelAutoApproval}
793+
/>,
794+
defaultTestState,
795+
)
796+
797+
expect(screen.getByText("First")).toBeInTheDocument()
798+
799+
// A stale memo would keep rendering the original suggestion.
800+
rerender(
801+
<TestExtensionStateProvider value={defaultTestState}>
802+
<TooltipProvider>
803+
<FollowUpSuggest
804+
suggestions={[{ answer: "Second" }]}
805+
onSuggestionClick={mockOnSuggestionClick}
806+
ts={123}
807+
onCancelAutoApproval={mockOnCancelAutoApproval}
808+
/>
809+
</TooltipProvider>
810+
</TestExtensionStateProvider>,
811+
)
812+
813+
expect(screen.getByText("Second")).toBeInTheDocument()
814+
expect(screen.queryByText("First")).not.toBeInTheDocument()
815+
})
774816
})
775817
})

0 commit comments

Comments
 (0)