diff --git a/packages/types/src/__tests__/global-settings.test.ts b/packages/types/src/__tests__/global-settings.test.ts index f2b2e7e8e5..1a90a41151 100644 --- a/packages/types/src/__tests__/global-settings.test.ts +++ b/packages/types/src/__tests__/global-settings.test.ts @@ -51,3 +51,25 @@ describe("collapseCommandOutputByDefault global setting", () => { expect(globalSettingsSchema.safeParse({ collapseCommandOutputByDefault: "true" }).success).toBe(false) }) }) + +describe("allowedMaxTokens global setting", () => { + it("accepts and exposes the persisted setting", () => { + expect(globalSettingsSchema.parse({ allowedMaxTokens: 50_000 })).toEqual({ + allowedMaxTokens: 50_000, + }) + expect(GLOBAL_SETTINGS_KEYS).toContain("allowedMaxTokens") + }) + + it("accepts nullish values for unset budget", () => { + expect(globalSettingsSchema.parse({ allowedMaxTokens: null })).toEqual({ + allowedMaxTokens: null, + }) + expect(globalSettingsSchema.parse({ allowedMaxTokens: undefined })).toEqual({ + allowedMaxTokens: undefined, + }) + }) + + it("rejects non-number values", () => { + expect(globalSettingsSchema.safeParse({ allowedMaxTokens: "50000" }).success).toBe(false) + }) +}) diff --git a/packages/types/src/__tests__/index.test.ts b/packages/types/src/__tests__/index.test.ts index 15441d48fd..1328fa4bd5 100644 --- a/packages/types/src/__tests__/index.test.ts +++ b/packages/types/src/__tests__/index.test.ts @@ -7,6 +7,12 @@ describe("GLOBAL_STATE_KEYS", () => { expect(GLOBAL_STATE_KEYS).toContain("autoApprovalEnabled") }) + it("should contain auto-approval limit keys", () => { + expect(GLOBAL_STATE_KEYS).toContain("allowedMaxRequests") + expect(GLOBAL_STATE_KEYS).toContain("allowedMaxCost") + expect(GLOBAL_STATE_KEYS).toContain("allowedMaxTokens") + }) + it("should contain provider settings keys", () => { expect(GLOBAL_STATE_KEYS).toContain("anthropicBaseUrl") }) diff --git a/packages/types/src/global-settings.ts b/packages/types/src/global-settings.ts index 2bd5573039..46565faf02 100644 --- a/packages/types/src/global-settings.ts +++ b/packages/types/src/global-settings.ts @@ -188,6 +188,7 @@ export const globalSettingsSchema = z.object({ preventCompletionWithOpenTodos: z.boolean().optional(), allowedMaxRequests: z.number().nullish(), allowedMaxCost: z.number().nullish(), + allowedMaxTokens: z.number().nullish(), autoCondenseContext: z.boolean().optional(), autoCondenseContextPercent: z.number().optional(), diff --git a/packages/types/src/vscode-extension-host.ts b/packages/types/src/vscode-extension-host.ts index 3e23a7934c..0fac2029f0 100644 --- a/packages/types/src/vscode-extension-host.ts +++ b/packages/types/src/vscode-extension-host.ts @@ -336,6 +336,7 @@ export type ExtensionState = Pick< | "deniedCommands" | "allowedMaxRequests" | "allowedMaxCost" + | "allowedMaxTokens" | "ttsEnabled" | "ttsSpeed" | "soundEnabled" diff --git a/src/core/auto-approval/AutoApprovalHandler.ts b/src/core/auto-approval/AutoApprovalHandler.ts index 638baa1c92..590e6126dc 100644 --- a/src/core/auto-approval/AutoApprovalHandler.ts +++ b/src/core/auto-approval/AutoApprovalHandler.ts @@ -1,12 +1,13 @@ import { GlobalState, ClineMessage, ClineAsk } from "@roo-code/types" import { getApiMetrics } from "../../shared/getApiMetrics" +import { findLastIndex } from "../../shared/array" import { ClineAskResponse } from "../../shared/WebviewMessage" export interface AutoApprovalResult { shouldProceed: boolean requiresApproval: boolean - approvalType?: "requests" | "cost" + approvalType?: "requests" | "cost" | "tokens" approvalCount?: number | string } @@ -14,6 +15,7 @@ export class AutoApprovalHandler { private lastResetMessageIndex: number = 0 private consecutiveAutoApprovedRequestsCount: number = 0 private consecutiveAutoApprovedCost: number = 0 + private consecutiveAutoApprovedTokens: number = 0 /** * Check if auto-approval limits have been reached and handle user approval if needed @@ -34,7 +36,13 @@ export class AutoApprovalHandler { // Check cost limit const costResult = await this.checkCostLimit(state, messages, askForApproval) - return costResult + if (!costResult.shouldProceed || costResult.requiresApproval) { + return costResult + } + + // Check token limit (token circuit breaker) + const tokenResult = await this.checkTokenLimit(state, messages, askForApproval) + return tokenResult } /** @@ -134,6 +142,55 @@ export class AutoApprovalHandler { return { shouldProceed: true, requiresApproval: false } } + /** + * Calculate current tokens and check if limit is exceeded (Token Circuit Breaker) + */ + private async checkTokenLimit( + state: GlobalState | undefined, + messages: ClineMessage[], + askForApproval: ( + type: ClineAsk, + data: string, + ) => Promise<{ response: ClineAskResponse; text?: string; images?: string[] }>, + ): Promise { + const maxTokens = state?.allowedMaxTokens || Infinity + + // Calculate total tokens from messages after the last reset point + const messagesAfterReset = messages.slice(this.lastResetMessageIndex) + const metrics = getApiMetrics(messagesAfterReset) + this.consecutiveAutoApprovedTokens = (metrics.totalTokensIn || 0) + (metrics.totalTokensOut || 0) + + if (this.consecutiveAutoApprovedTokens > maxTokens) { + const { response } = await askForApproval( + "auto_approval_max_req_reached", + JSON.stringify({ count: maxTokens.toLocaleString(), type: "tokens" }), + ) + + // If we get past the promise, it means the user approved and did not start a new task + if (response === "yesButtonClicked") { + // Reset tracking: exclude completed, approved usage but leave the current + // unfinished api_req_started entry in the next token window. + const lastApiReqIndex = findLastIndex(messages, (m) => m.say === "api_req_started") + this.lastResetMessageIndex = lastApiReqIndex !== -1 ? lastApiReqIndex : messages.length + return { + shouldProceed: true, + requiresApproval: true, + approvalType: "tokens", + approvalCount: maxTokens.toLocaleString(), + } + } + + return { + shouldProceed: false, + requiresApproval: true, + approvalType: "tokens", + approvalCount: maxTokens.toLocaleString(), + } + } + + return { shouldProceed: true, requiresApproval: false } + } + /** * Reset the tracking (typically called when starting a new task) */ @@ -141,15 +198,17 @@ export class AutoApprovalHandler { this.lastResetMessageIndex = 0 this.consecutiveAutoApprovedRequestsCount = 0 this.consecutiveAutoApprovedCost = 0 + this.consecutiveAutoApprovedTokens = 0 } /** * Get current approval state for debugging/testing */ - getApprovalState(): { requestCount: number; currentCost: number } { + getApprovalState(): { requestCount: number; currentCost: number; currentTokens: number } { return { requestCount: this.consecutiveAutoApprovedRequestsCount, currentCost: this.consecutiveAutoApprovedCost, + currentTokens: this.consecutiveAutoApprovedTokens, } } } diff --git a/src/core/auto-approval/__tests__/AutoApprovalHandler.spec.ts b/src/core/auto-approval/__tests__/AutoApprovalHandler.spec.ts index 5277425d43..0781e04b8e 100644 --- a/src/core/auto-approval/__tests__/AutoApprovalHandler.spec.ts +++ b/src/core/auto-approval/__tests__/AutoApprovalHandler.spec.ts @@ -295,6 +295,143 @@ describe("AutoApprovalHandler", () => { expect(result.requiresApproval).toBe(true) expect(result.approvalType).toBe("requests") }) + + it("should trigger token limit when tokens exceed allowedMaxTokens", async () => { + mockState.allowedMaxTokens = 50_000 + const completedMessage: ClineMessage = { type: "say", say: "api_req_started", text: "{}", ts: 1000 } + const currentMessage: ClineMessage = { type: "say", say: "api_req_started", text: "{}", ts: 1500 } + const messages: ClineMessage[] = [completedMessage, currentMessage] + + // Under token limit + mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 20_000, totalTokensOut: 10_000 }) + let result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + expect(result.shouldProceed).toBe(true) + expect(result.requiresApproval).toBe(false) + expect(mockAskForApproval).not.toHaveBeenCalled() + + // Exceeds token limit (40k in + 20k out = 60k > 50k) + mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 40_000, totalTokensOut: 20_000 }) + mockAskForApproval.mockResolvedValue({ response: "yesButtonClicked" }) + result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + + expect(mockAskForApproval).toHaveBeenCalledWith( + "auto_approval_max_req_reached", + JSON.stringify({ count: (50_000).toLocaleString(), type: "tokens" }), + ) + expect(result.shouldProceed).toBe(true) + expect(result.requiresApproval).toBe(true) + expect(result.approvalType).toBe("tokens") + + // Subsequent check below new limit: verifies reset boundary excludes completedMessage and leaves currentMessage + mockAskForApproval.mockClear() + mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 15_000, totalTokensOut: 5_000 }) + result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + + expect(mockGetApiMetrics).toHaveBeenLastCalledWith([currentMessage]) + expect(result.shouldProceed).toBe(true) + expect(result.requiresApproval).toBe(false) + expect(mockAskForApproval).not.toHaveBeenCalled() + }) + + it("leaves unfinished api_req_started in next token window after approval and counts increased usage", async () => { + mockState.allowedMaxTokens = 50_000 + const completedMessage: ClineMessage = { + type: "say", + say: "api_req_started", + text: JSON.stringify({ tokensIn: 30_000, tokensOut: 25_000, cost: 0.1 }), + ts: 1000, + } + const unfinishedMessage: ClineMessage = { + type: "say", + say: "api_req_started", + text: JSON.stringify({ apiProtocol: "anthropic" }), + ts: 2000, + } + const messages: ClineMessage[] = [completedMessage, unfinishedMessage] + + // Initial check: completed usage exceeds token limit (55k > 50k) + mockGetApiMetrics.mockReturnValue({ totalCost: 0.1, totalTokensIn: 30_000, totalTokensOut: 25_000 }) + mockAskForApproval.mockResolvedValue({ response: "yesButtonClicked" }) + + const result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + expect(result.shouldProceed).toBe(true) + expect(result.requiresApproval).toBe(true) + expect(result.approvalType).toBe("tokens") + + // After approval, the unfinished message's usage increases during execution + mockAskForApproval.mockClear() + mockGetApiMetrics.mockReturnValue({ totalCost: 0.05, totalTokensIn: 10_000, totalTokensOut: 5_000 }) + + const nextResult = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + + // Verifies the slice excludes completedMessage and retains unfinishedMessage in the window + expect(mockGetApiMetrics).toHaveBeenLastCalledWith([unfinishedMessage]) + expect(nextResult.shouldProceed).toBe(true) + expect(nextResult.requiresApproval).toBe(false) + expect(mockAskForApproval).not.toHaveBeenCalled() + }) + + it("should not proceed and not reset token window when user rejects token limit approval", async () => { + mockState.allowedMaxTokens = 50_000 + const messages: ClineMessage[] = [{ type: "say", say: "api_req_started", text: "{}", ts: 1000 }] + + // Exceeds token limit + mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 40_000, totalTokensOut: 20_000 }) + mockAskForApproval.mockResolvedValue({ response: "noButtonClicked" }) + const result = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + + expect(mockAskForApproval).toHaveBeenCalledWith( + "auto_approval_max_req_reached", + JSON.stringify({ count: (50_000).toLocaleString(), type: "tokens" }), + ) + expect(result.shouldProceed).toBe(false) + expect(result.requiresApproval).toBe(true) + expect(result.approvalType).toBe("tokens") + + // Repeat check with same usage: token window was not reset, so it prompts again + mockAskForApproval.mockClear() + mockAskForApproval.mockResolvedValue({ response: "noButtonClicked" }) + const repeatResult = await handler.checkAutoApprovalLimits(mockState, messages, mockAskForApproval) + + expect(mockAskForApproval).toHaveBeenCalledTimes(1) + expect(repeatResult.shouldProceed).toBe(false) + expect(repeatResult.requiresApproval).toBe(true) + expect(mockGetApiMetrics).toHaveBeenLastCalledWith(messages) + }) + + it("should trigger token limit using state constructed from provider state values", async () => { + const providerState = { + allowedMaxTokens: 50_000, + } as GlobalState + const messages: ClineMessage[] = [{ type: "say", say: "api_req_started", text: "{}", ts: 1000 }] + + // When token limit is exceeded on state returned from provider + mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 40_000, totalTokensOut: 20_000 }) + mockAskForApproval.mockResolvedValue({ response: "yesButtonClicked" }) + const result = await handler.checkAutoApprovalLimits(providerState, messages, mockAskForApproval) + + expect(mockAskForApproval).toHaveBeenCalledWith( + "auto_approval_max_req_reached", + JSON.stringify({ count: (50_000).toLocaleString(), type: "tokens" }), + ) + expect(result.shouldProceed).toBe(true) + expect(result.requiresApproval).toBe(true) + expect(result.approvalType).toBe("tokens") + }) + + it("should fall back to Infinity when allowedMaxTokens is unset", async () => { + const unsetState = { + allowedMaxTokens: undefined, + } as GlobalState + const messages: ClineMessage[] = [{ type: "say", say: "api_req_started", text: "{}", ts: 1000 }] + + mockGetApiMetrics.mockReturnValue({ totalCost: 0, totalTokensIn: 1_000_000, totalTokensOut: 1_000_000 }) + const result = await handler.checkAutoApprovalLimits(unsetState, messages, mockAskForApproval) + + expect(result.shouldProceed).toBe(true) + expect(result.requiresApproval).toBe(false) + expect(mockAskForApproval).not.toHaveBeenCalled() + }) }) describe("resetRequestCount", () => { diff --git a/src/core/task/Task.ts b/src/core/task/Task.ts index 77a1333b39..2ed6d1db6b 100644 --- a/src/core/task/Task.ts +++ b/src/core/task/Task.ts @@ -254,6 +254,7 @@ export interface TaskOptions extends CreateTaskOptions { enableCheckpoints?: boolean checkpointTimeout?: number consecutiveMistakeLimit?: number + tokenCircuitBreakerLimit?: number task?: string images?: string[] historyItem?: HistoryItem @@ -439,6 +440,7 @@ export class Task extends EventEmitter implements TaskLike { private retiredApis = new Set() private rateLimitClock: RateLimitClock private autoApprovalHandler: AutoApprovalHandler + tokenCircuitBreakerLimit: number = 0 toolRepetitionDetector: ToolRepetitionDetector rooIgnoreController?: RooIgnoreController @@ -709,6 +711,7 @@ export class Task extends EventEmitter implements TaskLike { enableCheckpoints = true, checkpointTimeout = DEFAULT_CHECKPOINT_TIMEOUT_SECONDS, consecutiveMistakeLimit = DEFAULT_CONSECUTIVE_MISTAKE_LIMIT, + tokenCircuitBreakerLimit = 0, toolRepetitionSoftLimit = DEFAULT_TOOL_REPETITION_SOFT_LIMIT, taskId, task, @@ -779,6 +782,7 @@ export class Task extends EventEmitter implements TaskLike { this.api = buildApiHandler(this.apiConfiguration) this.rateLimitClock = rateLimitClock ?? createRateLimitClock() this.autoApprovalHandler = new AutoApprovalHandler() + this.tokenCircuitBreakerLimit = tokenCircuitBreakerLimit ?? 0 this.consecutiveMistakeLimit = consecutiveMistakeLimit ?? DEFAULT_CONSECUTIVE_MISTAKE_LIMIT this.toolRepetitionSoftLimit = normalizeToolRepetitionSoftLimit( @@ -4012,6 +4016,34 @@ export class Task extends EventEmitter implements TaskLike { this.consecutiveMistakeCount = 0 } + // Token Circuit Breaker: Halt runaway loops if cumulative tokens exceed configured limit + if (this.tokenCircuitBreakerLimit > 0) { + const metrics = this.getTokenUsage() + const totalTokens = (metrics.totalTokensIn || 0) + (metrics.totalTokensOut || 0) + if (totalTokens >= this.tokenCircuitBreakerLimit) { + const { response, text } = await this.ask( + "mistake_limit_reached", + `Token circuit breaker tripped: cumulative token limit reached (${totalTokens.toLocaleString()} / ${this.tokenCircuitBreakerLimit.toLocaleString()} tokens). Please review and decide whether to proceed.`, + ) + + if (response === "yesButtonClicked" || response === "messageResponse") { + currentUserContent.push({ + type: "text" as const, + text: + response === "messageResponse" && text + ? `User approved exceeding token budget: ${text}` + : "User approved continuing beyond token circuit breaker limit.", + }) + // Bump threshold to allow subsequent turns up to the next budget checkpoint + this.tokenCircuitBreakerLimit = totalTokens + this.tokenCircuitBreakerLimit + } else { + throw new Error( + `[TokenCircuitBreaker] Cumulative token limit of ${this.tokenCircuitBreakerLimit.toLocaleString()} tokens exceeded. Task paused.`, + ) + } + } + } + // Getting verbose details is an expensive operation, it uses ripgrep to // top-down build file structure of project which for large projects can // take a few seconds. For the best UX we show a placeholder api_req_started @@ -4185,6 +4217,16 @@ export class Task extends EventEmitter implements TaskLike { cancelReason, streamingFailedMessage, } satisfies ClineApiReqInfo) + + // Token Circuit Breaker: warn if turn tokens approach or exceed limit + if (this.tokenCircuitBreakerLimit > 0) { + const turnTokens = (costResult.totalInputTokens || 0) + (costResult.totalOutputTokens || 0) + if (turnTokens >= this.tokenCircuitBreakerLimit) { + console.warn( + `[TokenCircuitBreaker] Turn token consumption (${turnTokens.toLocaleString()}) reached or exceeded configured threshold (${this.tokenCircuitBreakerLimit.toLocaleString()}).`, + ) + } + } } const abortStream = async (cancelReason: ClineApiReqCancelReason, streamingFailedMessage?: string) => { diff --git a/src/core/task/__tests__/Task.token-circuit-breaker.spec.ts b/src/core/task/__tests__/Task.token-circuit-breaker.spec.ts new file mode 100644 index 0000000000..678a035ee1 --- /dev/null +++ b/src/core/task/__tests__/Task.token-circuit-breaker.spec.ts @@ -0,0 +1,92 @@ +import type { Anthropic } from "@anthropic-ai/sdk" + +import { providerIdentifiers } from "@roo-code/types/provider-identifiers" + +import { setAbortLatch } from "../../../test-utils/run-state" +import { Task } from "../Task" + +describe("Task Token Circuit Breaker", () => { + function createTestTask(tokenCircuitBreakerLimit: number, totalTokens: number) { + const task = Object.create(Task.prototype) as Task + setAbortLatch(task, false) + const stopError = new Error("STOP_AFTER_CIRCUIT_BREAKER") + + Object.assign(task, { + taskId: "task-test-cb", + instanceId: "inst-test-cb", + apiConfiguration: { apiProvider: providerIdentifiers.anthropic }, + tokenCircuitBreakerLimit, + consecutiveMistakeLimit: 0, + consecutiveMistakeCount: 0, + getTokenUsage: vi.fn().mockReturnValue({ + totalTokensIn: totalTokens, + totalTokensOut: 0, + }), + ask: vi.fn(), + maybeWaitForProviderRateLimit: vi.fn().mockRejectedValue(stopError), + }) + + return { task, stopError } + } + + it("treats yesButtonClicked as approval, advances the threshold, and appends approval text", async () => { + const initialLimit = 50_000 + const currentTokens = 60_000 + const { task, stopError } = createTestTask(initialLimit, currentTokens) + task.ask = vi.fn().mockResolvedValue({ response: "yesButtonClicked" }) + + const userContent: Anthropic.Messages.ContentBlockParam[] = [] + + await expect(task.recursivelyMakeClineRequests(userContent)).rejects.toThrow(stopError) + + expect(task.ask).toHaveBeenCalledWith( + "mistake_limit_reached", + expect.stringContaining( + "Token circuit breaker tripped: cumulative token limit reached (60,000 / 50,000 tokens)", + ), + ) + // Advanced threshold: currentTokens (60k) + initialLimit (50k) = 110k + expect(task.tokenCircuitBreakerLimit).toBe(110_000) + expect(userContent).toContainEqual({ + type: "text", + text: "User approved continuing beyond token circuit breaker limit.", + }) + }) + + it("treats messageResponse as approval with custom feedback text", async () => { + const initialLimit = 50_000 + const currentTokens = 60_000 + const { task, stopError } = createTestTask(initialLimit, currentTokens) + task.ask = vi.fn().mockResolvedValue({ + response: "messageResponse", + text: "Authorized an additional 50k tokens", + }) + + const userContent: Anthropic.Messages.ContentBlockParam[] = [] + + await expect(task.recursivelyMakeClineRequests(userContent)).rejects.toThrow(stopError) + + expect(task.tokenCircuitBreakerLimit).toBe(110_000) + expect(userContent).toContainEqual({ + type: "text", + text: "User approved exceeding token budget: Authorized an additional 50k tokens", + }) + }) + + it("rejects and pauses task when user declines approval", async () => { + const initialLimit = 50_000 + const currentTokens = 60_000 + const { task } = createTestTask(initialLimit, currentTokens) + task.ask = vi.fn().mockResolvedValue({ response: "noButtonClicked" }) + + const userContent: Anthropic.Messages.ContentBlockParam[] = [] + + await expect(task.recursivelyMakeClineRequests(userContent)).rejects.toThrow( + "[TokenCircuitBreaker] Cumulative token limit of 50,000 tokens exceeded. Task paused.", + ) + + // Limit remains unchanged + expect(task.tokenCircuitBreakerLimit).toBe(50_000) + expect(userContent).toHaveLength(0) + }) +}) diff --git a/src/core/tools/ExecuteCommandTool.ts b/src/core/tools/ExecuteCommandTool.ts index 9855e6e417..696d17632e 100644 --- a/src/core/tools/ExecuteCommandTool.ts +++ b/src/core/tools/ExecuteCommandTool.ts @@ -13,10 +13,11 @@ import { buildAutoDenyReason, checkAutoApproval } from "../auto-approval" import { BLANKET_DENY_AUTO_DENY_KINDS, isBlanketDenyEngaged, Task } from "../task/Task" import type { ClineProvider } from "../webview/ClineProvider" +import "../../utils/path" import type { DcgDecision } from "../../services/destructive-command-guard" -import { ToolUse, ToolResponse } from "../../shared/tools" +import type { ToolUse, ToolResponse } from "../../shared/tools" import { formatResponse } from "../prompts/responses" -import { unescapeHtmlEntities } from "../../utils/text-normalization" +import { unescapeHtmlEntities, stripAnsi, truncateTerminalOutput } from "../../utils/text-normalization" import { parseCommand } from "../../shared/parse-command" import { ExitCodeDetails, @@ -706,17 +707,20 @@ export async function executeCommandInTerminal( } const exitStatus = formatExitStatus(exitDetails) + // Inline completed output is retained up to compressTerminalOutput limits (500 lines / 50K chars); + // head/tail truncation is reserved for persisted artifacts in formatPersistedOutput. + const sanitizedResult = stripAnsi(result) return [ false, - `Command executed in terminal within working directory '${currentWorkingDir}'. ${exitStatus}\nOutput:\n${result}`, + `Command executed in terminal within working directory '${currentWorkingDir}'. ${exitStatus}\nOutput:\n${sanitizedResult}`, ] } else { return [ false, [ `Command is still running in terminal ${workingDir ? ` from '${workingDir.toPosix()}'` : ""}.`, - result.length > 0 ? `Here's the output so far:\n${result}\n` : "\n", + result.length > 0 ? `Here's the output so far:\n${truncateTerminalOutput(result)}\n` : "\n", "You will be updated on the terminal status and new output in the future.", ].join("\n"), ] @@ -762,6 +766,7 @@ function formatPersistedOutput( const exitStatus = formatExitStatus(exitDetails) const sizeStr = formatBytes(result.totalBytes) const artifactId = result.artifactPath ? path.basename(result.artifactPath) : "" + const cleanPreview = truncateTerminalOutput(result.preview) return [ `Command executed in '${workingDir}'. ${exitStatus}`, @@ -769,7 +774,7 @@ function formatPersistedOutput( `Output (${sizeStr}) persisted. Artifact ID: ${artifactId}`, "", "Preview:", - result.preview, + cleanPreview, "", "Use read_command_output tool to view full output if needed.", ].join("\n") diff --git a/src/core/tools/ReadFileTool.ts b/src/core/tools/ReadFileTool.ts index e4e69b30ad..96bc06b405 100644 --- a/src/core/tools/ReadFileTool.ts +++ b/src/core/tools/ReadFileTool.ts @@ -24,6 +24,11 @@ import { getReadablePath } from "../../utils/path" import { extractTextFromFile, addLineNumbers, getSupportedBinaryFormats } from "../../integrations/misc/extract-text" import { readWithIndentation, readWithSlice } from "../../integrations/misc/indentation-reader" import { DEFAULT_LINE_LIMIT } from "../prompts/tools/native-tools/read_file" +import { + truncateFileOutput, + ADAPTIVE_FULL_READ_THRESHOLD, + SLIDING_WINDOW_PREVIEW_LIMIT, +} from "../../utils/text-normalization" import type { ToolUse, PushToolResult } from "../../shared/tools" import { @@ -313,7 +318,47 @@ export class ReadFileTool extends BaseTool<"read_file"> { let output = result.content - if (result.wasTruncated) { + // Solution 1: Adaptive sliding-window truncation. + // When both offset and limit are omitted, files <= ADAPTIVE_FULL_READ_THRESHOLD (300 lines) are returned in full + // to eliminate multi-turn round trip penalties. Files > 300 lines get a 200-line head/tail window. + let adaptiveTruncated = false + let adaptiveHeadCount = 0 + let adaptiveTailStart = 0 + let adaptiveDisplayedLines = 0 + let adaptiveOmittedStart = 0 + let adaptiveOmittedCount = 0 + + if ( + entry.offset === undefined && + entry.limit === undefined && + result.totalLines > ADAPTIVE_FULL_READ_THRESHOLD + ) { + const truncated = truncateFileOutput( + addLineNumbers(content, 1), + SLIDING_WINDOW_PREVIEW_LIMIT, + result.totalLines, + ) + if (truncated.wasTruncated) { + output = truncated.content + adaptiveTruncated = true + adaptiveHeadCount = Math.floor(SLIDING_WINDOW_PREVIEW_LIMIT / 2) + const tailCount = SLIDING_WINDOW_PREVIEW_LIMIT - adaptiveHeadCount + adaptiveTailStart = result.totalLines - tailCount + 1 + adaptiveOmittedStart = adaptiveHeadCount + 1 + const omittedEnd = adaptiveTailStart - 1 + adaptiveOmittedCount = omittedEnd - adaptiveOmittedStart + 1 + adaptiveDisplayedLines = truncated.returnedLines + } + } + + if (adaptiveTruncated) { + // Put truncation warning at TOP (before content) to match @ mention format + output = `IMPORTANT: File content truncated. + Status: Showing lines 1-${adaptiveHeadCount} and ${adaptiveTailStart}-${result.totalLines} (${adaptiveDisplayedLines} lines) of ${result.totalLines} total lines. + To read more: Use the read_file tool with offset=${adaptiveOmittedStart} and limit=${adaptiveOmittedCount}. + + ${output}` + } else if (result.wasTruncated) { const startLine = offset1 const endLine = offset1 + result.returnedLines - 1 const nextOffset = endLine + 1 @@ -322,7 +367,7 @@ export class ReadFileTool extends BaseTool<"read_file"> { Status: Showing lines ${startLine}-${endLine} of ${result.totalLines} total lines. To read more: Use the read_file tool with offset=${nextOffset} and limit=${limit}. - ${result.content}` + ${output}` } else if (result.returnedLines === 0 && result.totalLines === 0) { output = "Note: File is empty" } @@ -770,7 +815,13 @@ export class ReadFileTool extends BaseTool<"read_file"> { } // Read text file - const rawContent = await fs.readFile(fullPath, "utf8") + const fileData = await fs.readFile(fullPath, "utf8") + const rawContent = + typeof fileData === "string" + ? fileData + : Buffer.isBuffer(fileData) + ? fileData.toString("utf-8") + : String(fileData ?? "") // Handle line ranges if specified let content: string @@ -792,6 +843,13 @@ export class ReadFileTool extends BaseTool<"read_file"> { // Read with default limits using slice mode const result = readWithSlice(rawContent, 0, DEFAULT_LINE_LIMIT) content = result.content + if (result.totalLines > ADAPTIVE_FULL_READ_THRESHOLD) { + content = truncateFileOutput( + addLineNumbers(rawContent, 1), + SLIDING_WINDOW_PREVIEW_LIMIT, + result.totalLines, + ).content + } if (result.wasTruncated) { content += `\n\n[File truncated: showing ${result.returnedLines} of ${result.totalLines} total lines]` } diff --git a/src/core/tools/__tests__/executeCommand.spec.ts b/src/core/tools/__tests__/executeCommand.spec.ts index 774601c5ca..c95a55d96b 100644 --- a/src/core/tools/__tests__/executeCommand.spec.ts +++ b/src/core/tools/__tests__/executeCommand.spec.ts @@ -80,6 +80,7 @@ describe("executeCommand", () => { // Mock TerminalRegistry.getOrCreateTerminal ;(TerminalRegistry.getOrCreateTerminal as any).mockResolvedValue(mockTerminal) vitest.mocked(Terminal.isActiveShellCmdExe).mockReturnValue(false) + vitest.mocked(Terminal.compressTerminalOutput).mockImplementation((input: string) => input) }) afterEach(() => { @@ -515,6 +516,34 @@ describe("executeCommand", () => { expect(result).toContain("within working directory '/test/project'") }) + it("should retain all lines for inline completed output without head/tail truncation", async () => { + const multiLineOutput = Array.from({ length: 200 }, (_, i) => `line ${i + 1}`).join("\n") + mockTerminal.getCurrentWorkingDirectory.mockReturnValue("/test/project") + mockTerminal.runCommand.mockImplementation((_command: string, callbacks: RooTerminalCallbacks) => { + setTimeout(() => { + void callbacks.onCompleted(multiLineOutput, mockProcess) + callbacks.onShellExecutionComplete({ exitCode: 0 }, mockProcess) + }, 0) + return mockProcess + }) + + const options: ExecuteCommandOptions = { + executionId: "test-multiline", + toolCallId: "test-tool-call-multiline", + command: "seq 1 200", + terminalShellIntegrationDisabled: false, + } + + const [rejected, result] = await executeCommandInTerminal(mockTask, options) + + expect(rejected).toBe(false) + expect(result).toContain("line 1\n") + expect(result).toContain("line 100\n") + expect(result).toContain("line 105\n") + expect(result).toContain("line 200") + expect(result).not.toContain("lines omitted") + }) + it("should handle command terminated by signal", async () => { mockTerminal.getCurrentWorkingDirectory.mockReturnValue("/test/project") mockTerminal.runCommand.mockImplementation((_command: string, callbacks: RooTerminalCallbacks) => { diff --git a/src/core/tools/__tests__/readFileTool.spec.ts b/src/core/tools/__tests__/readFileTool.spec.ts index 52e04415ea..a5226d6af6 100644 --- a/src/core/tools/__tests__/readFileTool.spec.ts +++ b/src/core/tools/__tests__/readFileTool.spec.ts @@ -48,9 +48,10 @@ vi.mock("isbinaryfile") vi.mock("../../../integrations/misc/extract-text", () => ({ extractTextFromFile: vi.fn(), - addLineNumbers: vi.fn().mockImplementation((text: string, startLine = 1) => { + addLineNumbers: vi.fn().mockImplementation((text: string | Buffer, startLine = 1) => { if (!text) return "" - const lines = text.split("\n") + const str = typeof text === "string" ? text : Buffer.from(text).toString("utf-8") + const lines = str.split("\n") return lines.map((line, i) => `${startLine + i} | ${line}`).join("\n") }), getSupportedBinaryFormats: vi.fn(() => [".pdf", ".docx", ".ipynb"]), @@ -609,6 +610,154 @@ describe("ReadFileTool", () => { expect(callbacks.pushToolResult).not.toHaveBeenCalledWith(expect.stringContaining("Note: File is empty")) }) + describe("adaptive sliding-window truncation vs explicit parameters", () => { + it("applies adaptive preview when both offset and limit are omitted on large files", async () => { + const mockTask = createMockTask() + const callbacks = createMockCallbacks() + const lines = Array.from({ length: 400 }, (_, i) => `line ${i + 1}`) + + mockedFsReadFile.mockResolvedValue(Buffer.from(lines.join("\n"))) + mockedReadWithSlice.mockReturnValue({ + content: lines.map((l, i) => `${i + 1} | ${l}`).join("\n"), + returnedLines: 400, + totalLines: 400, + wasTruncated: false, + includedRanges: [[1, 400]], + }) + + await readFileTool.execute({ path: "large.ts" }, mockTask as unknown as Task, callbacks) + + const result = callbacks.pushToolResult.mock.calls[0][0] + expect(result).toMatch(/\[\.\.\.(?:SKIPPED|TRUNCATED)/) + }) + + it("does not apply adaptive preview when explicit offset is provided without limit", async () => { + const mockTask = createMockTask() + const callbacks = createMockCallbacks() + const sliceLines = Array.from({ length: 150 }, (_, i) => `${i + 200} | line ${i + 200}`) + + mockedFsReadFile.mockResolvedValue(Buffer.from("lots of content...")) + mockedReadWithSlice.mockReturnValue({ + content: sliceLines.join("\n"), + returnedLines: 150, + totalLines: 500, + wasTruncated: false, + includedRanges: [[200, 349]], + }) + + await readFileTool.execute({ path: "large.ts", offset: 200 }, mockTask as unknown as Task, callbacks) + + const result = callbacks.pushToolResult.mock.calls[0][0] + expect(result).toContain("200 | line 200") + expect(result).toContain("349 | line 349") + expect(result).not.toMatch(/\[\.\.\.(?:SKIPPED|TRUNCATED)/) + }) + + it("does not apply adaptive preview when explicit limit is provided", async () => { + const mockTask = createMockTask() + const callbacks = createMockCallbacks() + const sliceLines = Array.from({ length: 50 }, (_, i) => `${i + 1} | line ${i + 1}`) + + mockedFsReadFile.mockResolvedValue(Buffer.from("lots of content...")) + mockedReadWithSlice.mockReturnValue({ + content: sliceLines.join("\n"), + returnedLines: 50, + totalLines: 500, + wasTruncated: true, + includedRanges: [[1, 50]], + }) + + await readFileTool.execute({ path: "large.ts", limit: 50 }, mockTask as unknown as Task, callbacks) + + const result = callbacks.pushToolResult.mock.calls[0][0] + expect(result).toContain("Showing lines 1-50 of 500 total lines") + expect(result).toContain("1 | line 1") + expect(result).toContain("50 | line 50") + expect(result).not.toMatch(/\[\.\.\.(?:SKIPPED|TRUNCATED)/) + }) + + it("includes true end of file in adaptive preview when file exceeds default line limit", async () => { + const mockTask = createMockTask() + const callbacks = createMockCallbacks() + const lines = Array.from({ length: 2500 }, (_, i) => `line ${i + 1}`) + + mockedFsReadFile.mockResolvedValue(Buffer.from(lines.join("\n"))) + mockedReadWithSlice.mockReturnValue({ + content: lines + .slice(0, 2000) + .map((l, i) => `${i + 1} | ${l}`) + .join("\n"), + returnedLines: 2000, + totalLines: 2500, + wasTruncated: true, + includedRanges: [[1, 2000]], + }) + + await readFileTool.execute({ path: "very-large.ts" }, mockTask as unknown as Task, callbacks) + + const result = callbacks.pushToolResult.mock.calls[0][0] + expect(result).toMatch(/\[\.\.\.(?:SKIPPED|TRUNCATED)/) + expect(result).toContain("Status: Showing lines 1-100 and 2401-2500 (200 lines) of 2500 total lines.") + expect(result).toContain("To read more: Use the read_file tool with offset=101 and limit=2300.") + expect(result).not.toContain("Showing lines 1-2000") + expect(result).toContain("1 | line 1") + expect(result).toContain("2500 | line 2500") + }) + + it("constructs pagination metadata reflecting the 200-line preview ranges and retrieval instructions for omitted lines", async () => { + const mockTask = createMockTask() + const callbacks = createMockCallbacks() + const lines = Array.from({ length: 2000 }, (_, i) => `line ${i + 1}`) + + mockedFsReadFile.mockResolvedValue(Buffer.from(lines.join("\n"))) + mockedReadWithSlice.mockReturnValue({ + content: lines.map((l, i) => `${i + 1} | ${l}`).join("\n"), + returnedLines: 2000, + totalLines: 2000, + wasTruncated: false, + includedRanges: [[1, 2000]], + }) + + await readFileTool.execute({ path: "two-thousand.ts" }, mockTask as unknown as Task, callbacks) + + const result = callbacks.pushToolResult.mock.calls[0][0] + expect(result).toContain("IMPORTANT: File content truncated.") + expect(result).toContain("Status: Showing lines 1-100 and 1901-2000 (200 lines) of 2000 total lines.") + expect(result).toContain("To read more: Use the read_file tool with offset=101 and limit=1800.") + expect(result).not.toContain("Showing lines 1-2000") + }) + + it("includes true end of file in legacy adaptive preview when file exceeds default line limit", async () => { + const mockTask = createMockTask() + const callbacks = createMockCallbacks() + const lines = Array.from({ length: 2500 }, (_, i) => `line ${i + 1}`) + + mockTask.ask.mockResolvedValue({ response: "yesButtonClicked", text: undefined, images: undefined }) + mockedFsReadFile.mockResolvedValue(Buffer.from(lines.join("\n"))) + mockedReadWithSlice.mockReturnValue({ + content: lines + .slice(0, 2000) + .map((l, i) => `${i + 1} | ${l}`) + .join("\n"), + returnedLines: 2000, + totalLines: 2500, + wasTruncated: true, + includedRanges: [[1, 2000]], + }) + + await readFileTool.execute( + { files: [{ path: "very-large-legacy.ts" }], _legacyFormat: true }, + mockTask as unknown as Task, + callbacks, + ) + + const result = callbacks.pushToolResult.mock.calls[0][0] + expect(result).toMatch(/\[\.\.\.(?:SKIPPED|TRUNCATED)/) + expect(result).toContain("1 | line 1") + expect(result).toContain("2500 | line 2500") + }) + }) + // Integration counterpart to the mocked case above: the real readWithSlice // producer runs against a real file, so the error text and its 1-based // offset are proven end-to-end instead of being asserted against a stub. @@ -1281,8 +1430,8 @@ describe("ReadFileTool", () => { path: "test.ts", mode: "indentation", offset: 5, - } as any, - mockTask as any, + }, + mockTask as unknown as Task, callbacks, ) @@ -1309,8 +1458,8 @@ describe("ReadFileTool", () => { { path: "test.ts", mode: "indentation", - } as any, - mockTask as any, + }, + mockTask as unknown as Task, callbacks, ) @@ -1597,8 +1746,8 @@ describe("ReadFileTool", () => { path: "test.ts", mode: "indentation", offset: 7, - } as any, - mockTask as any, + }, + mockTask as unknown as Task, callbacks, ) diff --git a/src/core/tools/__tests__/writeToFileTool.spec.ts b/src/core/tools/__tests__/writeToFileTool.spec.ts index 7cb9d01585..96e044a791 100644 --- a/src/core/tools/__tests__/writeToFileTool.spec.ts +++ b/src/core/tools/__tests__/writeToFileTool.spec.ts @@ -121,7 +121,7 @@ describe("writeToFileTool", () => { mockedIsPathOutsideWorkspace.mockReturnValue(false) mockedGetReadablePath.mockReturnValue("test/path.txt") mockedUnescapeHtmlEntities.mockImplementation((content) => { - return content + return content ?? "" }) mockedEveryLineHasLineNumbers.mockReturnValue(false) mockedStripLineNumbers.mockImplementation((content) => { diff --git a/src/core/webview/ClineProvider.ts b/src/core/webview/ClineProvider.ts index 6c9182fcfb..0a262343e3 100644 --- a/src/core/webview/ClineProvider.ts +++ b/src/core/webview/ClineProvider.ts @@ -3209,6 +3209,7 @@ export class ClineProvider alwaysAllowSubtasks, allowedMaxRequests, allowedMaxCost, + allowedMaxTokens, autoCondenseContext, autoCondenseContextPercent, soundEnabled, @@ -3374,6 +3375,7 @@ export class ClineProvider alwaysAllowSubtasks: alwaysAllowSubtasks ?? false, allowedMaxRequests, allowedMaxCost, + allowedMaxTokens, autoCondenseContext: autoCondenseContext ?? true, autoCondenseContextPercent: autoCondenseContextPercent ?? 100, uriScheme: vscode.env.uriScheme, @@ -3626,6 +3628,7 @@ export class ClineProvider diagnosticsEnabled: stateValues.diagnosticsEnabled ?? true, allowedMaxRequests: stateValues.allowedMaxRequests, allowedMaxCost: stateValues.allowedMaxCost, + allowedMaxTokens: stateValues.allowedMaxTokens, autoCondenseContext: stateValues.autoCondenseContext ?? true, autoCondenseContextPercent: stateValues.autoCondenseContextPercent ?? 100, taskHistory: includeTaskHistory ? this.taskHistoryStore.getAll() : [], diff --git a/src/core/webview/__tests__/ClineProvider.spec.ts b/src/core/webview/__tests__/ClineProvider.spec.ts index 67b1e00853..e0b7e29c2f 100644 --- a/src/core/webview/__tests__/ClineProvider.spec.ts +++ b/src/core/webview/__tests__/ClineProvider.spec.ts @@ -4664,6 +4664,17 @@ describe("ClineProvider", () => { expect(state.diffFuzzyThreshold).toBe(0.5) }) + it("getState and getStateToPostToWebview pass through allowedMaxTokens", async () => { + await provider.resolveWebviewView(mockWebviewView) + await provider.contextProxy.setValue("allowedMaxTokens", 50_000) + + const state = await provider.getState() + expect(state.allowedMaxTokens).toBe(50_000) + + const stateToWebview = await provider.getStateToPostToWebview() + expect(stateToWebview.allowedMaxTokens).toBe(50_000) + }) + it("loads saved API config when switching modes", async () => { await provider.resolveWebviewView(mockWebviewView) const messageHandler = (mockWebviewView.webview.onDidReceiveMessage as any).mock.calls[0][0] diff --git a/src/eslint-suppressions.json b/src/eslint-suppressions.json index d5b845997a..5dc0fbb83c 100644 --- a/src/eslint-suppressions.json +++ b/src/eslint-suppressions.json @@ -856,7 +856,7 @@ }, "core/tools/__tests__/readFileTool.spec.ts": { "@typescript-eslint/no-explicit-any": { - "count": 96 + "count": 90 } }, "core/tools/__tests__/runSlashCommandTool.spec.ts": { diff --git a/src/utils/__tests__/text-normalization.spec.ts b/src/utils/__tests__/text-normalization.spec.ts index e672617d18..6f15f68769 100644 --- a/src/utils/__tests__/text-normalization.spec.ts +++ b/src/utils/__tests__/text-normalization.spec.ts @@ -1,4 +1,14 @@ -import { normalizeString, unescapeHtmlEntities } from "../text-normalization" +import { describe, it, expect } from "vitest" + +import { + normalizeString, + unescapeHtmlEntities, + stripAnsi, + truncateTerminalOutput, + truncateFileOutput, + ADAPTIVE_FULL_READ_THRESHOLD, + SLIDING_WINDOW_PREVIEW_LIMIT, +} from "../text-normalization" describe("Text normalization utilities", () => { describe("normalizeString", () => { @@ -73,7 +83,8 @@ describe("Text normalization utilities", () => { it("handles empty or undefined input", () => { expect(unescapeHtmlEntities("")).toBe("") - expect(unescapeHtmlEntities(undefined as unknown as string)).toBe(undefined) + expect(unescapeHtmlEntities(undefined)).toBe(undefined) + expect(unescapeHtmlEntities()).toBe(undefined) }) it("unescapes square bracket entities (numeric)", () => { @@ -101,4 +112,133 @@ describe("Text normalization utilities", () => { expect(unescapeHtmlEntities(input)).toBe(expected) }) }) + + describe("stripAnsi", () => { + it("removes ANSI color and formatting sequences", () => { + const input = "\u001b[31mRed Error\u001b[0m and \u001b[1mBold Text\u001b[0m" + expect(stripAnsi(input)).toBe("Red Error and Bold Text") + }) + + it("handles empty or clean strings", () => { + expect(stripAnsi("")).toBe("") + expect(stripAnsi("Clean text")).toBe("Clean text") + }) + }) + + describe("truncateTerminalOutput", () => { + it("leaves output under maxLines unchanged", () => { + const text = "line 1\nline 2\nline 3" + expect(truncateTerminalOutput(text, 5)).toBe(text) + }) + + it("truncates output exceeding maxLines preserving head and tail", () => { + const lines = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`) + const text = lines.join("\n") + const result = truncateTerminalOutput(text, 6) + + expect(result).toContain("[...14 intermediate lines omitted for context conservation...]") + expect(result.startsWith("line 1\nline 2\nline 3")).toBe(true) + expect(result.endsWith("line 18\nline 19\nline 20")).toBe(true) + }) + + it("strips ANSI while truncating", () => { + const lines = Array.from({ length: 10 }, (_, i) => `\u001b[32mline ${i + 1}\u001b[0m`) + const text = lines.join("\n") + const result = truncateTerminalOutput(text, 4) + + expect(result).not.toContain("\u001b[32m") + expect(result).toContain("line 1") + expect(result).toContain("line 10") + }) + + it("handles Windows CRLF line endings cleanly", () => { + const lines = Array.from({ length: 10 }, (_, i) => `line ${i + 1}\r\n`) + const text = lines.join("") + const result = truncateTerminalOutput(text, 4) + + expect(result).not.toContain("\r") + expect(result).toContain("line 1") + expect(result).toContain("line 10") + expect(result).toContain("[...6 intermediate lines omitted for context conservation...]") + }) + + it("pins critical compiler/test diagnostics when errors occur in the middle slice (Solution 3)", () => { + const lines = Array.from({ length: 120 }, (_, i) => `Step ${i + 1}: running task...`) + lines[60] = "FAILED: AssertionError: expected false to be true at OrderService.spec.ts:145" + lines[61] = " --> src/core/orders/OrderService.ts:88:12" + const text = lines.join("\n") + const result = truncateTerminalOutput(text, 40) + + expect(result).toContain("DIAGNOSTIC / ERROR CAPTURE") + expect(result).toContain("FAILED: AssertionError: expected false to be true") + expect(result).toContain("Step 1: running task...") + expect(result).toContain("Step 120: running task...") + }) + }) + + describe("truncateFileOutput", () => { + it("returns small file unchanged without truncation", () => { + const text = "export const a = 1;\nexport const b = 2;" + const result = truncateFileOutput(text, 100) + + expect(result.wasTruncated).toBe(false) + expect(result.content).toBe(text) + expect(result.returnedLines).toBe(2) + expect(result.omittedLines).toBe(0) + }) + + it("truncates large file preserving head and tail with informative marker", () => { + const lines = Array.from( + { length: 500 }, + (_, i) => `// Line ${i + 1}: export const item${i + 1} = ${i + 1};`, + ) + const text = lines.join("\n") + const result = truncateFileOutput(text, 100, 500) + + expect(result.wasTruncated).toBe(true) + expect(result.returnedLines).toBe(100) + expect(result.omittedLines).toBe(400) + expect(result.content).toContain( + "[...TRUNCATED 400 LINES: Showing first 50 and last 50 lines of 500 total lines", + ) + expect(result.content).toContain("Line 1:") + expect(result.content).toContain("Line 50:") + expect(result.content).toContain("Line 451:") + expect(result.content).toContain("Line 500:") + }) + + it("supports adaptive 300-line threshold and 200-line preview window (Solution 1)", () => { + expect(ADAPTIVE_FULL_READ_THRESHOLD).toBe(300) + expect(SLIDING_WINDOW_PREVIEW_LIMIT).toBe(200) + + const lines = Array.from({ length: 400 }, (_, i) => `// Line ${i + 1}`) + const result = truncateFileOutput(lines.join("\n"), SLIDING_WINDOW_PREVIEW_LIMIT, 400) + + expect(result.wasTruncated).toBe(true) + expect(result.returnedLines).toBe(200) + expect(result.omittedLines).toBe(200) + expect(result.content).toContain("first 100 and last 100 lines") + }) + + it("folds omitted middle block into semantic symbol skeleton (Solution 2)", () => { + const lines = Array.from({ length: 450 }, (_, i) => `let local_var_${i} = ${i};`) + // Insert declarations in middle block (around lines 150-250) + lines[140] = "export class OrderService {" + lines[180] = " async calculateTax(order: Order): Promise {" + lines[220] = " async processPayment(details: Payment): Promise {" + lines[260] = "export function formatReceipt(receipt: Receipt): string {" + + const result = truncateFileOutput(lines.join("\n"), 100, 450) + + expect(result.wasTruncated).toBe(true) + expect(result.content).toContain("[...SKIPPED 350 LINES: Middle Symbol Skeleton...]") + expect(result.content).toContain("• Line 141: export class OrderService") + expect(result.content).toContain("• Line 181: async calculateTax(order: Order): Promise") + expect(result.content).toContain("• Line 221: async processPayment(details: Payment): Promise") + expect(result.content).toContain("• Line 261: export function formatReceipt(receipt: Receipt): string") + expect(result.content).toContain( + "To inspect any implementation, call read_file with offset= and limit=40", + ) + }) + }) }) diff --git a/src/utils/text-normalization.ts b/src/utils/text-normalization.ts index 9e25d140c4..d094686fd6 100644 --- a/src/utils/text-normalization.ts +++ b/src/utils/text-normalization.ts @@ -82,8 +82,12 @@ export function normalizeString(str: string, options: NormalizeOptions = DEFAULT * @param text The string containing HTML entities to unescape * @returns The unescaped string with HTML entities converted to their literal characters */ -export function unescapeHtmlEntities(text: string): string { - if (!text) return text +export function unescapeHtmlEntities(text: string): string +export function unescapeHtmlEntities(text?: undefined): undefined +export function unescapeHtmlEntities(text?: string | null): string | undefined +export function unescapeHtmlEntities(text?: string | null): string | undefined { + if (text === undefined) return undefined + if (!text) return "" return text .replace(/</g, "<") @@ -97,3 +101,202 @@ export function unescapeHtmlEntities(text: string): string { .replace(/]/g, "]") .replace(/&/g, "&") } + +/** + * Strips ANSI escape codes from terminal output to eliminate useless tokens. + * Constructed dynamically via String.fromCharCode to avoid triggering no-control-regex. + */ +const ANSI_PATTERN = new RegExp(String.fromCharCode(0x1b) + "(?:[@-Z\\\\-_]|\\[[0-?]*[ -/]*[@-~])", "g") + +export function stripAnsi(text: string): string { + if (!text) return text + return text.replace(ANSI_PATTERN, "") +} + +/** + * Regex matching critical error markers in terminal logs to ensure middle stack traces + * are pinned during sliding-window truncation. + */ +const DIAGNOSTIC_PATTERN = /(?:error(?:\[E\d+\])?|fail(?:ed|ure)?|exception|traceback|syntaxerror|panicked at|fatal)/i + +/** + * Truncates terminal output to a maximum number of lines, preserving head and tail lines + * to conserve LLM context window while retaining critical error diagnostics. + * If error/panic diagnostics occur in the omitted middle slice, pins that diagnostic block. + * Robust against Windows CRLF (\r\n) line endings. + */ +export function truncateTerminalOutput(text: string, maxLines: number = 100): string { + if (!text) return text + + const clean = stripAnsi(text) + const lines = clean.split(/\r?\n/) + if (lines.length > 0 && lines[lines.length - 1] === "") { + lines.pop() + } + + if (lines.length <= maxLines || maxLines <= 0) { + return clean + } + + const headCount = Math.floor(maxLines / 2) + const tailCount = maxLines - headCount + const omitted = lines.length - maxLines + + // Solution 3: Diagnostic-Aware Scan - check if middle omitted slice holds critical compiler/test errors + const middleLines = lines.slice(headCount, lines.length - tailCount) + const relErrorIdx = middleLines.findIndex((line) => DIAGNOSTIC_PATTERN.test(line)) + + if (relErrorIdx !== -1 && maxLines >= 30) { + const errorIdx = headCount + relErrorIdx + const headBudget = Math.max(10, Math.floor(maxLines * 0.25)) + const tailBudget = Math.max(10, Math.floor(maxLines * 0.25)) + const errorBudget = maxLines - headBudget - tailBudget + + const halfErrorBudget = Math.floor(errorBudget / 2) + let errorStart = Math.max(headBudget, errorIdx - halfErrorBudget) + const errorEnd = Math.min(lines.length - tailBudget, errorStart + errorBudget) + if (errorEnd - errorStart < errorBudget) { + errorStart = Math.max(headBudget, errorEnd - errorBudget) + } + + const head = lines.slice(0, headBudget).join("\n") + const errorBlock = lines.slice(errorStart, errorEnd).join("\n") + const tail = lines.slice(-tailBudget).join("\n") + + const gap1 = errorStart - headBudget + const gap2 = lines.length - tailBudget - errorEnd + + return `${head}\n\n[...${gap1} lines omitted...]\n[=== DIAGNOSTIC / ERROR CAPTURE: around line ${errorStart + 1} ===]\n${errorBlock}\n\n[...${gap2} lines omitted...]\n${tail}` + } + + const head = lines.slice(0, headCount).join("\n") + const tail = lines.slice(-tailCount).join("\n") + + return `${head}\n\n[...${omitted} intermediate lines omitted for context conservation...]\n\n${tail}` +} + +/** Threshold below which files are returned in full without multi-turn pagination penalties (Solution 1) */ +export const ADAPTIVE_FULL_READ_THRESHOLD = 300 + +/** Default maximum lines returned for file reads when sliding window truncation engages */ +export const SLIDING_WINDOW_PREVIEW_LIMIT = 200 + +export interface FileTruncationResult { + content: string + wasTruncated: boolean + returnedLines: number + omittedLines: number +} + +/** + * Polyglot pattern matching structural declarations (functions, classes, interfaces, methods, etc.) + */ +const DECLARATION_PATTERN = + /^\s*(?:\d+\s*\|\s*)?(?:(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|enum|struct|impl|trait|fn|def|func|pub\s+(?:fn|struct|enum))\b|(?:(?:public|private|protected|static|readonly|async|override)\s+)+[a-zA-Z0-9_$]+\s*\([^)]*\)|(?:export\s+)?const\s+[a-zA-Z0-9_$]+\s*=\s*(?:async\s*)?(?:\([^)]*\)|[a-zA-Z0-9_$]+)\s*=>)/ + +export interface SkeletonSymbol { + lineNumber: number + signature: string +} + +/** + * Solution 2: Semantic Skeleton Folding. + * Extracts a lightweight structural symbol skeleton from lines of code. + * Enables the LLM to understand what functions/classes exist in an omitted middle block + * without paying the token cost of their full implementation bodies. + */ +export function extractSemanticSkeleton( + lines: string[], + startLineNumber: number = 1, + maxSymbols: number = 15, +): { symbols: SkeletonSymbol[]; formattedSkeleton: string | null } { + const symbols: SkeletonSymbol[] = [] + + for (let i = 0; i < lines.length; i++) { + const rawLine = lines[i] + if (!rawLine || rawLine.trim() === "") continue + + if (DECLARATION_PATTERN.test(rawLine)) { + // Extract line number (from prefix "123 | ..." or computed startLineNumber + i) + const linePrefixMatch = rawLine.match(/^\s*(\d+)\s*\|\s*(.*)$/) + const lineNum = linePrefixMatch ? parseInt(linePrefixMatch[1], 10) : startLineNumber + i + const codePart = linePrefixMatch ? linePrefixMatch[2] : rawLine + + // Clean signature: trim leading whitespace, trailing block openers/colons/braces + const cleaned = codePart + .trim() + .replace(/[\s{;:]+$/, "") + .trim() + + if (cleaned.length > 0) { + symbols.push({ lineNumber: lineNum, signature: cleaned }) + } + } + } + + if (symbols.length === 0) { + return { symbols: [], formattedSkeleton: null } + } + + const displaySymbols = symbols.slice(0, maxSymbols) + const items = displaySymbols.map((s) => ` • Line ${s.lineNumber}: ${s.signature}`).join("\n") + + let overflowNote = "" + if (symbols.length > maxSymbols) { + overflowNote = `\n ... and ${symbols.length - maxSymbols} more declarations in omitted block ...` + } + + const formattedSkeleton = `[...SKIPPED ${lines.length} LINES: Middle Symbol Skeleton...]\n${items}${overflowNote}\n[To inspect any implementation, call read_file with offset= and limit=40]` + + return { symbols, formattedSkeleton } +} + +/** + * Truncates file content to a maximum number of lines using a sliding window (head + tail), + * preventing token blowup while giving the LLM immediate visibility into both the start + * (imports, types, headers) and end (exports, bottom definitions) of a file. + * Integrates Solution 2 (Semantic Skeleton Folding) to eliminate middle-blindness. + */ +export function truncateFileOutput( + content: string, + maxLines: number = SLIDING_WINDOW_PREVIEW_LIMIT, + totalLines?: number, +): FileTruncationResult { + if (!content) return { content, wasTruncated: false, returnedLines: 0, omittedLines: 0 } + + const lines = content.split(/\r?\n/) + if (lines.length > 0 && lines[lines.length - 1] === "") { + lines.pop() + } + + const count = lines.length + + if (count <= maxLines || maxLines <= 0) { + return { content, wasTruncated: false, returnedLines: count, omittedLines: 0 } + } + + const headCount = Math.floor(maxLines / 2) + const tailCount = maxLines - headCount + const omitted = count - maxLines + + const head = lines.slice(0, headCount).join("\n") + const tail = lines.slice(-tailCount).join("\n") + const total = totalLines ?? count + + // Solution 2: Semantic Skeleton Folding for middle omitted block + const middleLines = lines.slice(headCount, lines.length - tailCount) + const { formattedSkeleton } = extractSemanticSkeleton(middleLines, headCount + 1) + + const omittedBlock = + formattedSkeleton ?? + `[...TRUNCATED ${omitted} LINES: Showing first ${headCount} and last ${tailCount} lines of ${total} total lines. To view intermediate code, call read_file with offset and limit...]` + + const truncatedContent = `${head}\n\n${omittedBlock}\n\n${tail}` + + return { + content: truncatedContent, + wasTruncated: true, + returnedLines: maxLines, + omittedLines: omitted, + } +} diff --git a/webview-ui/src/components/chat/AutoApprovedRequestLimitWarning.tsx b/webview-ui/src/components/chat/AutoApprovedRequestLimitWarning.tsx index 7207efb750..a8b68b3ef6 100644 --- a/webview-ui/src/components/chat/AutoApprovedRequestLimitWarning.tsx +++ b/webview-ui/src/components/chat/AutoApprovedRequestLimitWarning.tsx @@ -21,15 +21,22 @@ export const AutoApprovedRequestLimitWarning = memo(({ message }: AutoApprovedRe } const isCostLimit = type === "cost" + const isTokenLimit = type === "tokens" const titleKey = isCostLimit ? "ask.autoApprovedCostLimitReached.title" - : "ask.autoApprovedRequestLimitReached.title" + : isTokenLimit + ? "ask.autoApprovedTokenLimitReached.title" + : "ask.autoApprovedRequestLimitReached.title" const descriptionKey = isCostLimit ? "ask.autoApprovedCostLimitReached.description" - : "ask.autoApprovedRequestLimitReached.description" + : isTokenLimit + ? "ask.autoApprovedTokenLimitReached.description" + : "ask.autoApprovedRequestLimitReached.description" const buttonKey = isCostLimit ? "ask.autoApprovedCostLimitReached.button" - : "ask.autoApprovedRequestLimitReached.button" + : isTokenLimit + ? "ask.autoApprovedTokenLimitReached.button" + : "ask.autoApprovedRequestLimitReached.button" return ( <> diff --git a/webview-ui/src/components/chat/__tests__/AutoApprovedRequestLimitWarning.spec.tsx b/webview-ui/src/components/chat/__tests__/AutoApprovedRequestLimitWarning.spec.tsx new file mode 100644 index 0000000000..7eda1db4aa --- /dev/null +++ b/webview-ui/src/components/chat/__tests__/AutoApprovedRequestLimitWarning.spec.tsx @@ -0,0 +1,99 @@ +import React from "react" +import { render, screen, fireEvent } from "@/utils/test-utils" +import { vscode } from "@/utils/vscode" +import type { ClineMessage } from "@roo-code/types" +import { AutoApprovedRequestLimitWarning } from "../AutoApprovedRequestLimitWarning" + +// Mock vscode messaging +vi.mock("@/utils/vscode", () => ({ + vscode: { + postMessage: vi.fn(), + }, +})) + +// Mock react-i18next +vi.mock("react-i18next", () => ({ + Trans: ({ i18nKey, values }: { i18nKey: string; values?: Record }) => ( + + {i18nKey} + {values?.count ? `:${values.count}` : ""} + + ), +})) + +// Mock i18n TranslationContext +vi.mock("@src/i18n/TranslationContext", () => ({ + useAppTranslation: () => ({ + t: (key: string) => key, + }), +})) + +describe("AutoApprovedRequestLimitWarning", () => { + beforeEach(() => { + vi.clearAllMocks() + }) + + it("renders token limit warning when type is tokens", () => { + const message: ClineMessage = { + ts: 1000, + type: "ask", + ask: "auto_approval_max_req_reached", + text: JSON.stringify({ count: "50,000", type: "tokens" }), + } + + render() + + expect(screen.getByText("ask.autoApprovedTokenLimitReached.title")).toBeInTheDocument() + expect(screen.getByText("ask.autoApprovedTokenLimitReached.description:50,000")).toBeInTheDocument() + expect(screen.getByText("ask.autoApprovedTokenLimitReached.button")).toBeInTheDocument() + }) + + it("renders cost limit warning when type is cost", () => { + const message: ClineMessage = { + ts: 1000, + type: "ask", + ask: "auto_approval_max_req_reached", + text: JSON.stringify({ count: "5.00", type: "cost" }), + } + + render() + + expect(screen.getByText("ask.autoApprovedCostLimitReached.title")).toBeInTheDocument() + expect(screen.getByText("ask.autoApprovedCostLimitReached.description:5.00")).toBeInTheDocument() + expect(screen.getByText("ask.autoApprovedCostLimitReached.button")).toBeInTheDocument() + }) + + it("renders request limit warning when type is requests or omitted", () => { + const message: ClineMessage = { + ts: 1000, + type: "ask", + ask: "auto_approval_max_req_reached", + text: JSON.stringify({ count: 20 }), + } + + render() + + expect(screen.getByText("ask.autoApprovedRequestLimitReached.title")).toBeInTheDocument() + expect(screen.getByText("ask.autoApprovedRequestLimitReached.description:20")).toBeInTheDocument() + expect(screen.getByText("ask.autoApprovedRequestLimitReached.button")).toBeInTheDocument() + }) + + it("posts yesButtonClicked message when button is clicked", () => { + const message: ClineMessage = { + ts: 1000, + type: "ask", + ask: "auto_approval_max_req_reached", + text: JSON.stringify({ count: "50,000", type: "tokens" }), + } + + render() + + const button = screen.getByRole("button") + fireEvent.click(button) + + expect(vscode.postMessage).toHaveBeenCalledWith({ + type: "askResponse", + askResponse: "yesButtonClicked", + }) + }) +}) diff --git a/webview-ui/src/components/settings/providers/VSCodeLM.tsx b/webview-ui/src/components/settings/providers/VSCodeLM.tsx index b14c38c9a7..3ebf293f64 100644 --- a/webview-ui/src/components/settings/providers/VSCodeLM.tsx +++ b/webview-ui/src/components/settings/providers/VSCodeLM.tsx @@ -1,12 +1,12 @@ import { useState, useCallback, useMemo } from "react" import { useEvent } from "react-use" -import { LanguageModelChatSelector } from "vscode" import { LoaderCircle, LogIn, RefreshCw, UserCog } from "lucide-react" import { type ProviderSettings, type ExtensionMessage, type ModelInfo, + type LanguageModelChatSelector, VsCodeLmModelsMessageType, providerIdentifiers, } from "@roo-code/types" diff --git a/webview-ui/src/i18n/locales/ca/chat.json b/webview-ui/src/i18n/locales/ca/chat.json index 2d26f0a76f..baf9630286 100644 --- a/webview-ui/src/i18n/locales/ca/chat.json +++ b/webview-ui/src/i18n/locales/ca/chat.json @@ -364,6 +364,11 @@ "title": "S'ha arribat al límit de cost d'aprovació automàtica", "button": "Restableix i continua", "description": "Zoo ha arribat al límit de cost aprovat automàticament de ${{count}}. Vols restablir el cost i continuar amb la tasca?" + }, + "autoApprovedTokenLimitReached": { + "title": "S'ha arribat al límit de tokens aprovats automàticament", + "description": "Zoo ha arribat al límit aprovat automàticament de {{count}} tokens. Vols reiniciar el comptador i continuar amb la tasca?", + "button": "Reiniciar i continuar" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/de/chat.json b/webview-ui/src/i18n/locales/de/chat.json index dacd85c138..42719c1a55 100644 --- a/webview-ui/src/i18n/locales/de/chat.json +++ b/webview-ui/src/i18n/locales/de/chat.json @@ -360,6 +360,11 @@ "description": "Zoo hat das automatisch genehmigte Kostenlimit von ${{count}} erreicht. Möchten Sie die Kosten zurücksetzen und mit der Aufgabe fortfahren?", "title": "Kostengrenze für automatische Genehmigung erreicht", "button": "Zurücksetzen und Fortfahren" + }, + "autoApprovedTokenLimitReached": { + "title": "Limit für automatisch genehmigte Tokens erreicht", + "description": "Zoo hat das automatisch genehmigte Limit von {{count}} Tokens erreicht. Möchtest du den Zähler zurücksetzen und mit der Aufgabe fortfahren?", + "button": "Zurücksetzen und fortfahren" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/en/chat.json b/webview-ui/src/i18n/locales/en/chat.json index 154c54ac86..4087213a5e 100644 --- a/webview-ui/src/i18n/locales/en/chat.json +++ b/webview-ui/src/i18n/locales/en/chat.json @@ -387,6 +387,11 @@ "title": "Auto-Approved Cost Limit Reached", "description": "Zoo has reached the auto-approved cost limit of ${{count}}. Would you like to reset the cost and proceed with the task?", "button": "Reset and Continue" + }, + "autoApprovedTokenLimitReached": { + "title": "Auto-Approved Token Limit Reached", + "description": "Zoo has reached the auto-approved limit of {{count}} tokens. Would you like to reset the count and proceed with the task?", + "button": "Reset and Continue" } }, "indexingStatus": { diff --git a/webview-ui/src/i18n/locales/es/chat.json b/webview-ui/src/i18n/locales/es/chat.json index b06a430390..4ed1333ba6 100644 --- a/webview-ui/src/i18n/locales/es/chat.json +++ b/webview-ui/src/i18n/locales/es/chat.json @@ -364,6 +364,11 @@ "title": "Límite de Costo Auto-Aprobado Alcanzado", "description": "Zoo ha alcanzado el límite de costo autoaprobado de ${{count}}. ¿Le gustaría reiniciar el costo y continuar con la tarea?", "button": "Reiniciar y continuar" + }, + "autoApprovedTokenLimitReached": { + "title": "Límite de Tokens Auto-aprobados Alcanzado", + "description": "Zoo ha alcanzado el límite auto-aprobado de {{count}} tokens. ¿Deseas reiniciar el contador y continuar con la tarea?", + "button": "Reiniciar y Continuar" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/fr/chat.json b/webview-ui/src/i18n/locales/fr/chat.json index da67cefa6b..4f65a93836 100644 --- a/webview-ui/src/i18n/locales/fr/chat.json +++ b/webview-ui/src/i18n/locales/fr/chat.json @@ -364,6 +364,11 @@ "title": "Limite de coût en auto-approbation atteinte", "description": "Zoo a atteint la limite de coût auto-approuvée de ${{count}}. Souhaitez-vous réinitialiser le coût et poursuivre la tâche ?", "button": "Réinitialiser et Continuer" + }, + "autoApprovedTokenLimitReached": { + "title": "Limite de tokens auto-approuvés atteinte", + "description": "Zoo a atteint la limite auto-approuvée de {{count}} tokens. Souhaitez-vous réinitialiser le compteur et poursuivre la tâche ?", + "button": "Réinitialiser et continuer" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/hi/chat.json b/webview-ui/src/i18n/locales/hi/chat.json index 78868aea1a..e0e0fb1610 100644 --- a/webview-ui/src/i18n/locales/hi/chat.json +++ b/webview-ui/src/i18n/locales/hi/chat.json @@ -360,6 +360,11 @@ "title": "स्वत:-अनुमोदित लागत सीमा पहुँच गई", "button": "रीसेट करें और जारी रखें", "description": "Zoo ने स्वचालित-स्वीकृत लागत सीमा ${{count}} तक पहुंच गई है। क्या आप लागत को रीसेट करके कार्य जारी रखना चाहेंगे?" + }, + "autoApprovedTokenLimitReached": { + "title": "स्वत:-स्वीकृत टोकन सीमा पहुंची", + "description": "Zoo {{count}} टोकन की स्वत:-स्वीकृत सीमा तक पहुंच गया है। क्या आप गणना को रीसेट करके कार्य जारी रखना चाहते हैं?", + "button": "रीसेट करें और जारी रखें" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/id/chat.json b/webview-ui/src/i18n/locales/id/chat.json index e52338371e..44c379238d 100644 --- a/webview-ui/src/i18n/locales/id/chat.json +++ b/webview-ui/src/i18n/locales/id/chat.json @@ -392,6 +392,11 @@ "title": "Batas Biaya yang Disetujui Otomatis Tercapai", "description": "Zoo telah mencapai batas biaya yang disetujui otomatis sebesar ${{count}}. Apakah Anda ingin mengatur ulang biaya dan melanjutkan tugas?", "button": "Setel Ulang dan Lanjutkan" + }, + "autoApprovedTokenLimitReached": { + "title": "Batas Token yang Disetujui Otomatis Tercapai", + "description": "Zoo telah mencapai batas {{count}} token yang disetujui otomatis. Apakah Anda ingin mengatur ulang hitungan dan melanjutkan tugas?", + "button": "Setel Ulang dan Lanjutkan" } }, "indexingStatus": { diff --git a/webview-ui/src/i18n/locales/it/chat.json b/webview-ui/src/i18n/locales/it/chat.json index 2c598aa32a..2f51150e25 100644 --- a/webview-ui/src/i18n/locales/it/chat.json +++ b/webview-ui/src/i18n/locales/it/chat.json @@ -364,6 +364,11 @@ "title": "Limite di costo auto-approvato raggiunto", "button": "Reimposta e Continua", "description": "Zoo ha raggiunto il limite di costo approvato automaticamente di ${{count}}. Vuoi reimpostare il costo e procedere con l'attività?" + }, + "autoApprovedTokenLimitReached": { + "title": "Limite di Token Auto-approvati Raggiunto", + "description": "Zoo ha raggiunto il limite auto-approvato di {{count}} token. Vuoi reimpostare il contatore e procedere con l'attività?", + "button": "Reimposta e Continua" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/ja/chat.json b/webview-ui/src/i18n/locales/ja/chat.json index 480fbe40a8..86db85f456 100644 --- a/webview-ui/src/i18n/locales/ja/chat.json +++ b/webview-ui/src/i18n/locales/ja/chat.json @@ -356,6 +356,11 @@ "title": "自動承認コスト制限に達しました", "description": "Zooは自動承認されたコスト制限の${{count}}に達しました。コストをリセットしてタスクを続行しますか?", "button": "リセットして続ける" + }, + "autoApprovedTokenLimitReached": { + "title": "自動承認トークン制限に達しました", + "description": "Zooは{{count}}トークンの自動承認制限に達しました。カウントをリセットしてタスクを続行しますか?", + "button": "リセットして続行" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/ko/chat.json b/webview-ui/src/i18n/locales/ko/chat.json index 6fcbaf5861..56be4e8a94 100644 --- a/webview-ui/src/i18n/locales/ko/chat.json +++ b/webview-ui/src/i18n/locales/ko/chat.json @@ -356,6 +356,11 @@ "description": "Zoo가 자동 승인된 비용 한도인 ${{count}}에 도달했습니다. 비용을 초기화하고 작업을 계속하시겠습니까?", "title": "자동 승인 비용 한도에 도달함", "button": "재설정 후 계속하기" + }, + "autoApprovedTokenLimitReached": { + "title": "자동 승인 토큰 한도 도달", + "description": "Zoo가 {{count}}개의 토큰에 대한 자동 승인 한도에 도달했습니다. 카운트를 재설정하고 작업을 계속하시겠습니까?", + "button": "재설정 후 계속" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/nl/chat.json b/webview-ui/src/i18n/locales/nl/chat.json index 70bf979678..ef718c0c04 100644 --- a/webview-ui/src/i18n/locales/nl/chat.json +++ b/webview-ui/src/i18n/locales/nl/chat.json @@ -360,6 +360,11 @@ "title": "Limiet voor automatisch goedgekeurde kosten bereikt", "button": "Resetten en doorgaan", "description": "Zoo heeft de automatisch goedgekeurde kostenlimiet van ${{count}} bereikt. Wilt u de kosten resetten en doorgaan met de taak?" + }, + "autoApprovedTokenLimitReached": { + "title": "Limiet voor automatisch goedgekeurde tokens bereikt", + "description": "Zoo heeft de automatisch goedgekeurde limiet van {{count}} tokens bereikt. Wil je de teller resetten en doorgaan met de taak?", + "button": "Resetten en doorgaan" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/pl/chat.json b/webview-ui/src/i18n/locales/pl/chat.json index 0cfb5d95da..ac9aa463b3 100644 --- a/webview-ui/src/i18n/locales/pl/chat.json +++ b/webview-ui/src/i18n/locales/pl/chat.json @@ -368,6 +368,11 @@ "button": "Zresetuj i Kontynuuj", "title": "Osiągnięto limit kosztów z automatycznym zatwierdzaniem", "description": "Zoo osiągnął automatycznie zatwierdzony limit kosztów wynoszący ${{count}}. Czy chcesz zresetować koszt i kontynuować zadanie?" + }, + "autoApprovedTokenLimitReached": { + "title": "Osiągnięto limit automatycznie zatwierdzonych tokenów", + "description": "Zoo osiągnął automatycznie zatwierdzony limit {{count}} tokenów. Czy chcesz zresetować licznik i kontynuować zadanie?", + "button": "Zresetuj i kontynuuj" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/pt-BR/chat.json b/webview-ui/src/i18n/locales/pt-BR/chat.json index 36548aab7d..924d805cf5 100644 --- a/webview-ui/src/i18n/locales/pt-BR/chat.json +++ b/webview-ui/src/i18n/locales/pt-BR/chat.json @@ -364,6 +364,11 @@ "title": "Limite de Custo com Aprovação Automática Atingido", "description": "Zoo atingiu o limite de custo com aprovação automática de US${{count}}. Você gostaria de redefinir o custo e prosseguir com a tarefa?", "button": "Redefinir e Continuar" + }, + "autoApprovedTokenLimitReached": { + "title": "Limite de Tokens Auto-aprobados Atingido", + "description": "Zoo atingiu o limite auto-aprovado de {{count}} tokens. Deseja redefinir a contagem e prosseguir com a tarefa?", + "button": "Redefinir e Continuar" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/ru/chat.json b/webview-ui/src/i18n/locales/ru/chat.json index c350fe1c45..59ade4d975 100644 --- a/webview-ui/src/i18n/locales/ru/chat.json +++ b/webview-ui/src/i18n/locales/ru/chat.json @@ -369,6 +369,11 @@ "title": "Достигнут лимит автоматически одобряемых расходов", "button": "Сбросить и продолжить", "description": "Zoo достиг автоматически утвержденного лимита расходов в размере ${{count}}. Хотите сбросить расходы и продолжить выполнение задачи?" + }, + "autoApprovedTokenLimitReached": { + "title": "Достигнут лимит автоматически одобренных токенов", + "description": "Zoo достиг автоматически одобренного лимита в {{count}} токенов. Хотите сбросить счетчик и продолжить задачу?", + "button": "Сбросить и продолжить" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/tr/chat.json b/webview-ui/src/i18n/locales/tr/chat.json index ae70fbd967..a232c09ed4 100644 --- a/webview-ui/src/i18n/locales/tr/chat.json +++ b/webview-ui/src/i18n/locales/tr/chat.json @@ -361,6 +361,11 @@ "title": "Otomatik Onaylanan Maliyet Sınırına Ulaşıldı", "description": "Zoo otomatik olarak onaylanmış ${{count}} maliyet sınırına ulaştı. Maliyeti sıfırlamak ve göreve devam etmek ister misiniz?", "button": "Sıfırla ve Devam Et" + }, + "autoApprovedTokenLimitReached": { + "title": "Otomatik Onaylanan Belirteç Limiti Aşıldı", + "description": "Zoo, {{count}} belirteç için otomatik onaylanan limite ulaştı. Sayacı sıfırlamak ve göreve devam etmek istiyor musunuz?", + "button": "Sıfırla ve Devam Et" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/vi/chat.json b/webview-ui/src/i18n/locales/vi/chat.json index f2b08ec110..be46b8b265 100644 --- a/webview-ui/src/i18n/locales/vi/chat.json +++ b/webview-ui/src/i18n/locales/vi/chat.json @@ -357,6 +357,11 @@ "button": "Đặt lại và Tiếp tục", "title": "Đã Đạt Giới Hạn Chi Phí Tự Động Phê Duyệt", "description": "Zoo đã đạt đến giới hạn chi phí tự động phê duyệt là ${{count}}. Bạn có muốn đặt lại chi phí và tiếp tục với nhiệm vụ không?" + }, + "autoApprovedTokenLimitReached": { + "title": "Đã Đạt Giới Hạn Token Tự Động Phê Duyệt", + "description": "Zoo đã đạt đến giới hạn tự động phê duyệt là {{count}} token. Bạn có muốn đặt lại bộ đếm và tiếp tục nhiệm vụ không?", + "button": "Đặt lại và Tiếp tục" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/zh-CN/chat.json b/webview-ui/src/i18n/locales/zh-CN/chat.json index 4edfa1da27..a1f4afe317 100644 --- a/webview-ui/src/i18n/locales/zh-CN/chat.json +++ b/webview-ui/src/i18n/locales/zh-CN/chat.json @@ -357,6 +357,11 @@ "title": "已达到自动批准的费用限额", "description": "Zoo已经达到了${{count}}的自动批准成本限制。您想重置成本并继续任务吗?", "button": "重置并继续" + }, + "autoApprovedTokenLimitReached": { + "title": "已达自动批准代币限制", + "description": "Zoo 已达到 {{count}} 个代币的自动批准限制。您想重置计数并继续任务吗?", + "button": "重置并继续" } }, "codebaseSearch": { diff --git a/webview-ui/src/i18n/locales/zh-TW/chat.json b/webview-ui/src/i18n/locales/zh-TW/chat.json index 7612d282f4..48dcd84b41 100644 --- a/webview-ui/src/i18n/locales/zh-TW/chat.json +++ b/webview-ui/src/i18n/locales/zh-TW/chat.json @@ -385,6 +385,11 @@ "title": "已達自動核准費用上限", "description": "Zoo 已達到 ${{count}} 的自動核准費用上限。您想重設費用並繼續工作嗎?", "button": "重設並繼續" + }, + "autoApprovedTokenLimitReached": { + "title": "已達自動核准 Token 上限", + "description": "Zoo 已達到 {{count}} 個 Token 的自動核准上限。您想重設計數並繼續工作嗎?", + "button": "重設並繼續" } }, "indexingStatus": {