Skip to content

Commit 6618866

Browse files
committed
fix(mentions): fail closed on mention authorization
1 parent af01da5 commit 6618866

11 files changed

Lines changed: 209 additions & 16 deletions

‎src/core/assistant-message/__tests__/presentAssistantMessage-images.spec.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -381,13 +381,15 @@ describe("presentAssistantMessage - Image Handling in Native Tool Calling", () =
381381

382382
await presentAssistantMessage(mockTask, baseSnapshot)
383383

384-
// Anthropic rejects user messages where image blocks sit between
385-
// tool_result blocks, so images from both tools must be grouped
386-
// after the last tool_result instead of interleaved.
384+
// Images must come after all tool_result blocks (#1307). Feedback
385+
// text blocks join the tail in push order. No image may appear
386+
// before the second tool_result.
387387
expect(mockTask.userMessageContent.map((block: UserContentBlock) => block.type)).toEqual([
388388
"tool_result",
389389
"tool_result",
390+
"text",
390391
"image",
392+
"text",
391393
"image",
392394
])
393395
expect(
@@ -442,10 +444,14 @@ describe("presentAssistantMessage - Image Handling in Native Tool Calling", () =
442444

443445
await presentAssistantMessage(mockTask, baseSnapshot)
444446

447+
// The image must come after the last tool_result (#1307), never
448+
// between tool_result blocks. Feedback text joins the tail.
445449
expect(mockTask.userMessageContent.map((block: UserContentBlock) => block.type)).toEqual([
446450
"tool_result",
447451
"tool_result",
452+
"text",
448453
"image",
454+
"text",
449455
])
450456
expect(
451457
mockTask.userMessageContent

‎src/core/mentions/__tests__/processUserContentMentions.spec.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ describe("processUserContentMentions authorization", () => {
3434
})
3535

3636
it("expands explicit user input without requiring a textual marker", async () => {
37-
const result = await process([userMentionContent("@/allowed")])
37+
const result = await process([userMentionContent("@/allowed", "@/allowed")])
3838
expect(parseMentions).toHaveBeenCalledWith(
3939
"@/allowed",
4040
"/test",
@@ -64,7 +64,7 @@ describe("processUserContentMentions authorization", () => {
6464
})
6565

6666
it("does not trust restored, copied, or modified blocks", async () => {
67-
const block = userMentionContent("@/allowed")
67+
const block = userMentionContent("@/allowed", "@/allowed")
6868
const copy = { ...block }
6969
block.text += " @/secret"
7070
await process([copy, block, userMentionContent("context @/secret", "")])

‎src/core/mentions/processUserContentMentions.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ type ImagePart = Anthropic.Messages.ImageBlockParam
1212
const authorizedInputs = new WeakMap<TextPart, { text: string; input: string }>()
1313

1414
/** Call only at a user-input boundary, before adding lower-trust context. */
15-
export function userMentionContent(text: string, input: string = text): TextPart {
15+
export function userMentionContent(text: string, input: string): TextPart {
1616
const block: TextPart = { type: "text", text }
1717
if (input && text.includes(input)) authorizedInputs.set(block, { text, input })
1818
return block

‎src/core/task/Task.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3165,7 +3165,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
31653165

31663166
// Task starting
31673167
await this.initiateTaskLoop([
3168-
userMentionContent(`<user_message>\n${task}\n</user_message>`, this.authorizedMentionText ?? task),
3168+
// Child tasks get model-written text. Only an explicit
3169+
// authorizedMentionText may expand there.
3170+
userMentionContent(
3171+
`<user_message>\n${task}\n</user_message>`,
3172+
this.authorizedMentionText ?? (this.parentTask ? "" : (task ?? "")),
3173+
),
31693174
...imageBlocks,
31703175
]).catch((error) => {
31713176
// Swallow loop rejection when the task was intentionally abandoned/aborted

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3511,7 +3511,7 @@ describe("Cline", () => {
35113511
})
35123512

35133513
describe("processUserContentMentions", () => {
3514-
it("should process mentions in user_message tags", async () => {
3514+
it("expands only the authorized user input and leaves tool results unexpanded", async () => {
35153515
const [cline, task] = Task.create({
35163516
provider: mockProvider,
35173517
apiConfiguration: mockApiConfig,
@@ -3525,6 +3525,7 @@ describe("Cline", () => {
35253525
} as const,
35263526
userMentionContent(
35273527
"<user_message>Text with 'some/path' (see below for file content) in user_message tags</user_message>",
3528+
"Text with 'some/path' (see below for file content) in user_message tags",
35283529
),
35293530
{
35303531
type: "tool_result",
@@ -3559,10 +3560,11 @@ describe("Cline", () => {
35593560
"Regular text with 'some/path' (see below for file content)",
35603561
)
35613562

3562-
// Text within user_message tags should be processed
3563+
// Only the authorized input is replaced; the surrounding
3564+
// wrapper text stays intact.
35633565
expect((processedContent[1] as Anthropic.TextBlockParam).text).toContain("processed:")
35643566
expect((processedContent[1] as Anthropic.TextBlockParam).text).toContain(
3565-
"<user_message>Text with 'some/path' (see below for file content) in user_message tags</user_message>",
3567+
"<user_message>processed: Text with 'some/path' (see below for file content) in user_message tags</user_message>",
35663568
)
35673569

35683570
// Tool result markers cannot authorize mention expansion

‎src/core/tools/AskFollowupQuestionTool.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ export class AskFollowupQuestionTool extends BaseTool<"ask_followup_question"> {
7474
const { text, images } = await task.ask("followup", JSON.stringify(follow_up_json), false)
7575
const safeText = text ?? ""
7676
await task.say("user_feedback", safeText, images)
77+
// Authorizes expansion. The tool result repeats the text by design.
7778
task.userMessageContent.push(userMentionContent(`<user_message>\n${safeText}\n</user_message>`, safeText))
7879
pushToolResult(formatResponse.toolResult(`<user_message>\n${safeText}\n</user_message>`, images))
7980
} catch (error) {

‎src/core/tools/AttemptCompletionTool.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,7 @@ export class AttemptCompletionTool extends BaseTool<"attempt_completion"> {
246246
}
247247

248248
const feedbackText = `<user_message>\n${text}\n</user_message>`
249+
// Authorizes expansion. The tool result repeats the text by design.
249250
task.userMessageContent.push(userMentionContent(feedbackText, text ?? ""))
250251
pushToolResult(formatResponse.toolResult(feedbackText, images))
251252
} catch (error) {

‎src/core/tools/__tests__/askFollowupQuestionTool.spec.ts‎

Lines changed: 50 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,24 +6,36 @@ import type { ToolCallbacks } from "../BaseTool"
66
import { AskFollowupQuestionTool, askFollowupQuestionTool } from "../AskFollowupQuestionTool"
77
import { formatResponse } from "../../prompts/responses"
88
import { NativeToolCallParser } from "../../assistant-message/NativeToolCallParser"
9+
import { processUserContentMentions } from "../../mentions/processUserContentMentions"
10+
import { parseMentions } from "../../mentions/index"
11+
import { FileContextTracker } from "../../context-tracking/FileContextTracker"
12+
13+
vi.mock("../../mentions/index", () => ({ parseMentions: vi.fn() }))
914

1015
describe("AskFollowupQuestionTool", () => {
1116
let tool: AskFollowupQuestionTool
1217
let mockTask: Task
1318
let mockCallbacks: ToolCallbacks
19+
// Kept outside the Task double so tests can re-stub answers without casts.
20+
let askMock: ReturnType<typeof vi.fn>
1421

1522
beforeEach(() => {
1623
vi.clearAllMocks()
24+
vi.mocked(parseMentions).mockImplementation(async (text) => ({
25+
text: `parsed: ${text}`,
26+
contentBlocks: [],
27+
}))
1728

1829
tool = new AskFollowupQuestionTool()
1930

31+
askMock = vi.fn().mockResolvedValue({ text: "User answer", images: [] })
2032
mockTask = {
2133
userMessageContent: [],
2234
consecutiveMistakeCount: 0,
2335
recordToolError: vi.fn(),
2436
didToolFailInCurrentTurn: false,
2537
sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing parameter error"),
26-
ask: vi.fn().mockResolvedValue({ text: "User answer", images: [] }),
38+
ask: askMock,
2739
say: vi.fn().mockResolvedValue(undefined),
2840
} as unknown as Task
2941

@@ -198,6 +210,43 @@ describe("AskFollowupQuestionTool", () => {
198210
)
199211
})
200212

213+
it("pushes an authorized feedback block that mention processing expands", async () => {
214+
const params = { question: "What?", follow_up: [{ text: "A" }] }
215+
askMock.mockResolvedValue({ text: "@/allowed", images: [] })
216+
217+
await tool.execute(params, mockTask, mockCallbacks)
218+
219+
// Deleting the push in AskFollowupQuestionTool fails this assertion.
220+
expect(mockTask.userMessageContent).toHaveLength(1)
221+
const block = mockTask.userMessageContent[0]
222+
expect(block).toEqual({ type: "text", text: "<user_message>\n@/allowed\n</user_message>" })
223+
224+
// The pushed block authorizes expansion of its input.
225+
const result = await processUserContentMentions({
226+
userContent: [block],
227+
cwd: "/test",
228+
fileContextTracker: {} as FileContextTracker,
229+
})
230+
expect(vi.mocked(parseMentions).mock.calls[0]?.[0]).toBe("@/allowed")
231+
expect(result.content).toEqual([{ type: "text", text: "<user_message>\nparsed: @/allowed\n</user_message>" }])
232+
})
233+
234+
it("does not authorize the feedback block when the user answer is null", async () => {
235+
const params = { question: "What?", follow_up: [{ text: "A" }] }
236+
askMock.mockResolvedValue({ text: null, images: [] })
237+
238+
await tool.execute(params, mockTask, mockCallbacks)
239+
240+
expect(mockTask.userMessageContent).toHaveLength(1)
241+
const result = await processUserContentMentions({
242+
userContent: [mockTask.userMessageContent[0]],
243+
cwd: "/test",
244+
fileContextTracker: {} as FileContextTracker,
245+
})
246+
expect(parseMentions).not.toHaveBeenCalled()
247+
expect(result.content).toEqual([{ type: "text", text: "<user_message>\n\n</user_message>" }])
248+
})
249+
201250
it("should pass images from user response to toolResult", async () => {
202251
const params = {
203252
question: "Look at this?",

‎src/core/tools/__tests__/attemptCompletionTool.spec.ts‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ import { attemptCompletionTool, AttemptCompletionCallbacks } from "../AttemptCom
3131
import { Task } from "../../task/Task"
3232
import { AskApproval, HandleError, PushToolResult } from "../../../shared/tools"
3333
import * as vscode from "vscode"
34+
import { processUserContentMentions } from "../../mentions/processUserContentMentions"
35+
import { parseMentions } from "../../mentions/index"
36+
import { FileContextTracker } from "../../context-tracking/FileContextTracker"
37+
38+
vi.mock("../../mentions/index", () => ({ parseMentions: vi.fn() }))
3439

3540
describe("attemptCompletionTool", () => {
3641
let mockTask: Partial<Task>
@@ -1162,6 +1167,89 @@ describe("attemptCompletionTool", () => {
11621167
expect(mockPushToolResult).toHaveBeenCalledTimes(1)
11631168
})
11641169

1170+
it("pushes an authorized feedback block that mention processing expands", async () => {
1171+
const block: ToolUse<"attempt_completion"> = {
1172+
type: "tool_use",
1173+
name: "attempt_completion",
1174+
params: { result: "Done" },
1175+
nativeArgs: { result: "Done" },
1176+
partial: false,
1177+
}
1178+
mockTask.ask = vi.fn().mockResolvedValue({
1179+
response: "messageResponse",
1180+
text: "@/allowed",
1181+
images: [],
1182+
})
1183+
vi.mocked(parseMentions).mockImplementation(async (text) => ({
1184+
text: `parsed: ${text}`,
1185+
contentBlocks: [],
1186+
}))
1187+
vi.mocked(parseMentions).mockClear()
1188+
1189+
await attemptCompletionTool.handle(mockTask as Task, block, {
1190+
askApproval: mockAskApproval,
1191+
handleError: mockHandleError,
1192+
pushToolResult: mockPushToolResult,
1193+
toolCallId: "",
1194+
askFinishSubTaskApproval: mockAskFinishSubTaskApproval,
1195+
toolDescription: mockToolDescription,
1196+
})
1197+
1198+
// Deleting the push in AttemptCompletionTool fails this assertion.
1199+
expect(mockTask.userMessageContent).toHaveLength(1)
1200+
const block0 = mockTask.userMessageContent![0]
1201+
expect(block0).toEqual({ type: "text", text: "<user_message>\n@/allowed\n</user_message>" })
1202+
1203+
// The pushed block authorizes expansion of its input.
1204+
const result = await processUserContentMentions({
1205+
userContent: [block0],
1206+
cwd: "/test",
1207+
fileContextTracker: {} as FileContextTracker,
1208+
})
1209+
expect(vi.mocked(parseMentions).mock.calls[0]?.[0]).toBe("@/allowed")
1210+
expect(result.content).toEqual([
1211+
{ type: "text", text: "<user_message>\nparsed: @/allowed\n</user_message>" },
1212+
])
1213+
})
1214+
1215+
it("does not authorize the feedback block when the feedback text is undefined", async () => {
1216+
const block: ToolUse<"attempt_completion"> = {
1217+
type: "tool_use",
1218+
name: "attempt_completion",
1219+
params: { result: "Done" },
1220+
nativeArgs: { result: "Done" },
1221+
partial: false,
1222+
}
1223+
mockTask.ask = vi.fn().mockResolvedValue({
1224+
response: "messageResponse",
1225+
text: undefined,
1226+
images: [],
1227+
})
1228+
vi.mocked(parseMentions).mockImplementation(async (text) => ({
1229+
text: `parsed: ${text}`,
1230+
contentBlocks: [],
1231+
}))
1232+
vi.mocked(parseMentions).mockClear()
1233+
1234+
await attemptCompletionTool.handle(mockTask as Task, block, {
1235+
askApproval: mockAskApproval,
1236+
handleError: mockHandleError,
1237+
pushToolResult: mockPushToolResult,
1238+
toolCallId: "",
1239+
askFinishSubTaskApproval: mockAskFinishSubTaskApproval,
1240+
toolDescription: mockToolDescription,
1241+
})
1242+
1243+
expect(mockTask.userMessageContent).toHaveLength(1)
1244+
const result = await processUserContentMentions({
1245+
userContent: [mockTask.userMessageContent![0]],
1246+
cwd: "/test",
1247+
fileContextTracker: {} as FileContextTracker,
1248+
})
1249+
expect(parseMentions).not.toHaveBeenCalled()
1250+
expect(result.content).toEqual([{ type: "text", text: "<user_message>\nundefined\n</user_message>" }])
1251+
})
1252+
11651253
it("does not clear pending metadata when stale delegation continues without an action id", async () => {
11661254
const block: ToolUse<"attempt_completion"> = {
11671255
type: "tool_use",

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1041,6 +1041,52 @@ describe("ClineProvider", () => {
10411041
sidebarTask.mockRestore()
10421042
tabTask.mockRestore()
10431043
})
1044+
1045+
test.each([
1046+
["explainCode", "EXPLAIN"],
1047+
["fixCode", "FIX"],
1048+
["improveCode", "IMPROVE"],
1049+
] as const)(
1050+
"forwards user-authored code action input as authorizedMentionText for %s",
1051+
async (command, promptType) => {
1052+
const task = new Task(defaultTaskOptions)
1053+
const createTask = vi.spyOn(provider, "createTask").mockResolvedValue(task)
1054+
try {
1055+
await provider.handleCodeAction(command, promptType, {
1056+
selectedText: "selected code",
1057+
userInput: "@/allowed",
1058+
})
1059+
// A regression that always sends "" would fail this assertion.
1060+
expect(createTask).toHaveBeenCalledWith(expect.any(String), undefined, undefined, {
1061+
authorizedMentionText: "@/allowed",
1062+
})
1063+
} finally {
1064+
createTask.mockRestore()
1065+
}
1066+
},
1067+
)
1068+
1069+
test("forwards user-authored terminal action input as authorizedMentionText", async () => {
1070+
const task = new Task(defaultTaskOptions)
1071+
const sidebarTask = vi.spyOn(provider, "createTask").mockResolvedValue(task)
1072+
const tabTask = vi.spyOn(tabProvider, "createTask").mockResolvedValue(task)
1073+
try {
1074+
// No chat focus fired, so the last registered visible provider
1075+
// (the tab) receives the task, as in the fallback test above.
1076+
await ClineProvider.handleTerminalAction("terminalFixCommand", "TERMINAL_FIX", {
1077+
userInput: "@/allowed",
1078+
})
1079+
// A regression that always sends "" would fail this assertion.
1080+
expect(tabTask).toHaveBeenCalledOnce()
1081+
expect(tabTask).toHaveBeenCalledWith(expect.any(String), undefined, undefined, {
1082+
authorizedMentionText: "@/allowed",
1083+
})
1084+
expect(sidebarTask).not.toHaveBeenCalled()
1085+
} finally {
1086+
sidebarTask.mockRestore()
1087+
tabTask.mockRestore()
1088+
}
1089+
})
10441090
})
10451091

10461092
test("loads full model details when preparing an LM Studio task", async () => {

0 commit comments

Comments
 (0)