Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions packages/types/src/provider-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@ import {

export const DEFAULT_CONSECUTIVE_MISTAKE_LIMIT = 3

/**
* Number of identical consecutive tool calls allowed before the tool is
* soft-blocked. When reached, the tool is not executed and the model is
* asked to justify why it needs to repeat the call. Set to 0 to disable.
*/
export const DEFAULT_TOOL_REPETITION_SOFT_LIMIT = 2

/**
* DynamicProvider
*
Expand Down Expand Up @@ -191,6 +198,7 @@ const baseProviderSettingsSchema = z.object({
modelTemperature: z.number().nullish(),
rateLimitSeconds: z.number().optional(),
consecutiveMistakeLimit: z.number().min(0).optional(),
toolRepetitionSoftLimit: z.number().min(0).optional(),

// Model reasoning.
enableReasoningEffort: z.boolean().optional(),
Expand Down
1 change: 1 addition & 0 deletions packages/types/src/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ export interface CreateTaskOptions {
taskId?: string
enableCheckpoints?: boolean
consecutiveMistakeLimit?: number
toolRepetitionSoftLimit?: number
experiments?: Record<string, boolean>
initialTodos?: TodoItem[]
/** Initial status for the task's history item (e.g., "active" for child tasks) */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ describe("presentAssistantMessage - Custom Tool Recording", () => {
recordToolUsage: vi.fn(),
recordToolError: vi.fn(),
toolRepetitionDetector: {
check: vi.fn().mockReturnValue({ allowExecution: true }),
check: vi.fn().mockReturnValue({ action: "allow" }),
},
providerRef: {
deref: () => ({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ describe("presentAssistantMessage - Image Handling in Native Tool Calling", () =
},
recordToolUsage: vi.fn(),
toolRepetitionDetector: {
check: vi.fn().mockReturnValue({ allowExecution: true }),
check: vi.fn().mockReturnValue({ action: "allow" }),
},
providerRef: {
deref: () => ({
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,261 @@
// npx vitest src/core/assistant-message/__tests__/presentAssistantMessage-tool-repetition.spec.ts

import { presentAssistantMessage } from "../presentAssistantMessage"

// Mock dependencies
vi.mock("../../task/Task")
vi.mock("../../tools/validateToolUse", () => ({
validateToolUse: vi.fn(),
isValidToolName: vi.fn(() => true),
}))

// Mock the read_file tool so we can assert the normal execution path is taken
// when the repetition detector allows a tool call. The handle spy simulates a
// successful tool run by pushing a tool_result, mirroring the real tool.
// `vi.hoisted` is required because `vi.mock` factories are hoisted above
// top-level variable declarations.
const { readFileHandle } = vi.hoisted(() => ({
readFileHandle: vi.fn(async (_cline: any, block: any, { pushToolResult }: any) => {
pushToolResult(`[read_file for '${block?.params?.path ?? block?.nativeArgs?.path}'] Result`)
}),
}))

vi.mock("../../tools/ReadFileTool", () => ({
readFileTool: {
handle: readFileHandle,
getReadFileToolDescription: vi.fn(() => "[read_file]"),
},
}))

const captureConsecutiveMistakeError = vi.fn()
const captureException = vi.fn()
const captureToolUsage = vi.fn()

vi.mock("@roo-code/telemetry", () => ({
TelemetryService: {
instance: {
get captureToolUsage() {
return captureToolUsage
},
get captureConsecutiveMistakeError() {
return captureConsecutiveMistakeError
},
get captureException() {
return captureException
},
captureEvent: vi.fn(),
},
},
}))

describe("presentAssistantMessage - Tool Repetition Detection", () => {
let mockTask: any

beforeEach(() => {
vi.clearAllMocks()

mockTask = {
taskId: "test-task-id",
instanceId: "test-instance",
abort: false,
presentAssistantMessageLocked: false,
presentAssistantMessageHasPendingUpdates: false,
currentStreamingContentIndex: 0,
assistantMessageContent: [],
userMessageContent: [],
didCompleteReadingStream: false,
didRejectTool: false,
didAlreadyUseTool: false,
consecutiveMistakeCount: 0,
consecutiveMistakeLimit: 5,
clineMessages: [],
apiConfiguration: { apiProvider: "anthropic" },
api: {
getModel: () => ({ id: "test-model", info: {} }),
},
recordToolUsage: vi.fn(),
recordToolError: vi.fn(),
toolRepetitionDetector: {
check: vi.fn().mockReturnValue({ action: "allow" }),
},
providerRef: {
deref: () => ({
getState: vi.fn().mockResolvedValue({
mode: "code",
customModes: [],
}),
}),
},
say: vi.fn().mockResolvedValue(undefined),
ask: vi.fn().mockResolvedValue({ response: "yesButtonClicked" }),
}

mockTask.pushToolResultToUserContent = vi.fn().mockImplementation((toolResult: any) => {
const existingResult = mockTask.userMessageContent.find(
(block: any) => block.type === "tool_result" && block.tool_use_id === toolResult.tool_use_id,
)
if (existingResult) {
return false
}
mockTask.userMessageContent.push(toolResult)
return true
})
})

it("should soft block without involving the user and return an error to the model", async () => {
const toolCallId = "tool_call_soft_block"
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: toolCallId,
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]

mockTask.toolRepetitionDetector.check = vi.fn().mockReturnValue({
action: "soft_block",
message: "The tool 'read_file' was blocked because it was just called with identical parameters.",
})

await presentAssistantMessage(mockTask)

// The user should NOT have been asked anything for a soft block.
expect(mockTask.ask).not.toHaveBeenCalled()

// A tool_result with the soft block message should have been pushed.
const toolResult = mockTask.userMessageContent.find(
(item: any) => item.type === "tool_result" && item.tool_use_id === toolCallId,
)
expect(toolResult).toBeDefined()
expect(toolResult.content).toContain("read_file")
expect(toolResult.content).toContain("identical parameters")

// No telemetry escalation for a soft block.
expect(captureConsecutiveMistakeError).not.toHaveBeenCalled()
expect(captureException).not.toHaveBeenCalled()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This checks ask wasn't called and the right tool_result was pushed, but is there an assertion anywhere that the tool itself (readFileHandle) was NOT invoked? A missing break after the soft-block branch would fall through to dispatch and this test would still pass.

})

it("should hard block, ask the user for guidance, and record telemetry", async () => {
const toolCallId = "tool_call_hard_block"
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: toolCallId,
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]

mockTask.toolRepetitionDetector.check = vi.fn().mockReturnValue({
action: "hard_block",
askUser: {
messageKey: "mistake_limit_reached",
messageDetail: "Roo appears to be stuck in a loop calling {toolName} repeatedly.",
},
})

mockTask.ask = vi.fn().mockResolvedValue({ response: "yesButtonClicked" })

await presentAssistantMessage(mockTask)

// The user must be asked for guidance with the resolved message key.
expect(mockTask.ask).toHaveBeenCalledWith(
"mistake_limit_reached",
expect.stringContaining("read_file"),
)

// Telemetry escalation should have fired for a hard block.
expect(captureConsecutiveMistakeError).toHaveBeenCalledWith("test-task-id")
expect(captureException).toHaveBeenCalled()

// A tool_result describing the repetition limit should have been pushed.
const toolResult = mockTask.userMessageContent.find(
(item: any) => item.type === "tool_result" && item.tool_use_id === toolCallId,
)
expect(toolResult).toBeDefined()
expect(toolResult.content).toContain("read_file")
})

it("should incorporate user feedback when the user responds to a hard block", async () => {
const toolCallId = "tool_call_hard_block_feedback"
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: toolCallId,
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]

mockTask.toolRepetitionDetector.check = vi.fn().mockReturnValue({
action: "hard_block",
askUser: {
messageKey: "mistake_limit_reached",
messageDetail: "Stuck calling {toolName} repeatedly.",
},
})

mockTask.ask = vi.fn().mockResolvedValue({
response: "messageResponse",
text: "try a different file",
images: [],
})

await presentAssistantMessage(mockTask)

// User feedback should have been surfaced to the chat.
expect(mockTask.say).toHaveBeenCalledWith("user_feedback", "try a different file", [])

// And appended to the user message content.
const feedbackBlock = mockTask.userMessageContent.find(
(item: any) => item.type === "text" && String(item.text).includes("try a different file"),
)
expect(feedbackBlock).toBeDefined()
expect(feedbackBlock.text).toContain("Tool repetition limit reached")
})

it("should execute the tool normally when the detector allows it", async () => {
const toolCallId = "tool_call_allow"
mockTask.assistantMessageContent = [
{
type: "tool_use",
id: toolCallId,
name: "read_file",
params: { path: "test.txt" },
nativeArgs: { path: "test.txt" },
partial: false,
},
]

mockTask.toolRepetitionDetector.check = vi.fn().mockReturnValue({ action: "allow" })

await presentAssistantMessage(mockTask)

// The detector should have been consulted.
expect(mockTask.toolRepetitionDetector.check).toHaveBeenCalled()
// No hard block ask should have occurred.
expect(mockTask.ask).not.toHaveBeenCalledWith("mistake_limit_reached", expect.anything())

// The tool must have actually continued into normal execution: the
// read_file tool runner should have been dispatched with this block.
expect(readFileHandle).toHaveBeenCalledTimes(1)
const [, dispatchedBlock] = readFileHandle.mock.calls[0]
expect(dispatchedBlock).toMatchObject({ name: "read_file", id: toolCallId })

// And the normal execution path should have produced a tool_result
// (no soft/hard block error message).
const toolResult = mockTask.userMessageContent.find(
(item: any) => item.type === "tool_result" && item.tool_use_id === toolCallId,
)
expect(toolResult).toBeDefined()
expect(toolResult.content).toContain("read_file")
expect(toolResult.is_error).toBeUndefined()
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
})
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ describe("presentAssistantMessage - Unknown Tool Handling", () => {
recordToolUsage: vi.fn(),
recordToolError: vi.fn(),
toolRepetitionDetector: {
check: vi.fn().mockReturnValue({ allowExecution: true }),
check: vi.fn().mockReturnValue({ action: "allow" }),
},
providerRef: {
deref: () => ({
Expand Down
13 changes: 11 additions & 2 deletions src/core/assistant-message/presentAssistantMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -629,8 +629,17 @@ export async function presentAssistantMessage(cline: Task) {
// block directly.
const repetitionCheck = cline.toolRepetitionDetector.check(block)

// If execution is not allowed, notify user and break.
if (!repetitionCheck.allowExecution && repetitionCheck.askUser) {
// Soft block: do NOT involve the user. Return an error to the
// model asking it to justify repeating the call (or try a
// different approach). The detector keeps counting so continued
// repetition will eventually escalate to a hard block.
if (repetitionCheck.action === "soft_block") {
pushToolResult(formatResponse.toolError(repetitionCheck.message))
break
}

// Hard block: stop and ask the user for guidance.
if (repetitionCheck.action === "hard_block") {
// Handle repetition similar to mistake_limit_reached pattern.
const { response, text, images } = await cline.ask(
repetitionCheck.askUser.messageKey as ClineAsk,
Expand Down
22 changes: 22 additions & 0 deletions src/core/config/ProviderSettingsManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
isSecretStateKey,
ProviderSettingsEntry,
DEFAULT_CONSECUTIVE_MISTAKE_LIMIT,
DEFAULT_TOOL_REPETITION_SOFT_LIMIT,
getModelId,
type ProviderName,
isProviderName,
Expand Down Expand Up @@ -43,6 +44,7 @@ export const providerProfilesSchema = z.object({
rateLimitSecondsMigrated: z.boolean().optional(),
openAiHeadersMigrated: z.boolean().optional(),
consecutiveMistakeLimitMigrated: z.boolean().optional(),
toolRepetitionLimitsMigrated: z.boolean().optional(),
todoListEnabledMigrated: z.boolean().optional(),
claudeCodeLegacySettingsMigrated: z.boolean().optional(),
routerProviderMigrated: z.boolean().optional(),
Expand All @@ -68,6 +70,7 @@ export class ProviderSettingsManager {
rateLimitSecondsMigrated: true, // Mark as migrated on fresh installs
openAiHeadersMigrated: true, // Mark as migrated on fresh installs
consecutiveMistakeLimitMigrated: true, // Mark as migrated on fresh installs
toolRepetitionLimitsMigrated: true, // Mark as migrated on fresh installs
todoListEnabledMigrated: true, // Mark as migrated on fresh installs
claudeCodeLegacySettingsMigrated: true, // Mark as migrated on fresh installs
routerProviderMigrated: true, // Mark as migrated on fresh installs
Expand Down Expand Up @@ -174,6 +177,12 @@ export class ProviderSettingsManager {
isDirty = true
}

if (!providerProfiles.migrations.toolRepetitionLimitsMigrated) {
await this.migrateToolRepetitionLimits(providerProfiles)
providerProfiles.migrations.toolRepetitionLimitsMigrated = true
isDirty = true
}

if (!providerProfiles.migrations.todoListEnabledMigrated) {
await this.migrateTodoListEnabled(providerProfiles)
providerProfiles.migrations.todoListEnabledMigrated = true
Expand Down Expand Up @@ -271,6 +280,19 @@ export class ProviderSettingsManager {
}
}

private async migrateToolRepetitionLimits(providerProfiles: ProviderProfiles) {
try {
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
// Default the soft warning threshold.
if (apiConfig.toolRepetitionSoftLimit == null) {
apiConfig.toolRepetitionSoftLimit = DEFAULT_TOOL_REPETITION_SOFT_LIMIT
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This defaults toolRepetitionSoftLimit to 2 without looking at the profile's existing consecutiveMistakeLimit. If a user previously set consecutiveMistakeLimit to 0 (docs say this fully disables the safety mechanism) or to 1/2, won't this migration leave soft >= hard, making the soft-block tier permanently unreachable (or, worse, silently soft-blocking forever for the 0 case since the hard check is skipped entirely when hardStopLimit is 0)? Should this read the profile's hard limit and clamp accordingly?

}
} catch (error) {
console.error(`[MigrateToolRepetitionLimits] Failed to migrate tool repetition limits:`, error)
}
}

private async migrateTodoListEnabled(providerProfiles: ProviderProfiles) {
try {
for (const [_name, apiConfig] of Object.entries(providerProfiles.apiConfigs)) {
Expand Down
Loading
Loading