diff --git a/src/api/providers/cline.ts b/src/api/providers/cline.ts
index 15b03d96..406ef221 100644
--- a/src/api/providers/cline.ts
+++ b/src/api/providers/cline.ts
@@ -177,17 +177,7 @@ export class ClineHandler implements ApiHandler {
}
} catch (error) {
console.error("Cline API Error:", error)
- const requestId = error?.request_id ? `\n | Request ID: ${error.request_id}` : ""
- if (error.code === "ERR_BAD_REQUEST" || error.status === 401) {
- throw new Error(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE + requestId)
- } else if (error.code === "insufficient_credits" || error.status === 402) {
- if (error.error) {
- throw new Error(JSON.stringify(error.error))
- }
- }
- const _error = error instanceof Error ? error : new Error(String(error))
- _error.message = _error.message + requestId
- throw _error
+ throw error
}
}
diff --git a/src/core/task/index.ts b/src/core/task/index.ts
index 924abaf4..f74fd5ae 100644
--- a/src/core/task/index.ts
+++ b/src/core/task/index.ts
@@ -81,9 +81,10 @@ import { refreshWorkflowToggles } from "../context/instructions/user-instruction
import { MessageStateHandler } from "./message-state"
import { TaskState } from "./TaskState"
import { ToolExecutor } from "./ToolExecutor"
-import { extractErrorDetails, formatErrorWithStatusCode, updateApiReqMsg } from "./utils"
-import { createDiffViewProvider, getHostBridgeProvider } from "@/hosts/host-providers"
-
+import { updateApiReqMsg } from "./utils"
+import { createDiffViewProvider } from "@/hosts/host-providers"
+import { ErrorService } from "@/services/error/ErrorService"
+import { ClineErrorType } from "@/services/error/ClineError"
export const USE_EXPERIMENTAL_CLAUDE4_FEATURES = false
export type ToolResponse = string | Array
@@ -1588,6 +1589,12 @@ export class Task {
}
}
+ private async getCurrentProviderInfo(): Promise<{ modelId: string; providerId: string }> {
+ const modelId = this.api.getModel()?.id
+ const providerId = (await getGlobalState(this.getContext(), "apiProvider")) as string
+ return { modelId, providerId }
+ }
+
async *attemptApiRequest(previousApiReqIndex: number): ApiStream {
// Wait for MCP servers to be connected before generating system prompt
await pWaitFor(() => this.mcpHub.isConnecting !== true, { timeout: 10_000 }).catch(() => {
@@ -1682,16 +1689,17 @@ export class Task {
const isAnthropic = this.api instanceof AnthropicHandler
const isOpenRouterContextWindowError = checkIsOpenRouterContextWindowError(error) && isOpenRouter
const isAnthropicContextWindowError = checkIsAnthropicContextWindowError(error) && isAnthropic
+ const { modelId, providerId } = await this.getCurrentProviderInfo()
+ const clineError = ErrorService.toClineError(error, modelId, providerId)
- const { statusCode, message, requestId } = extractErrorDetails(error)
-
- // Capture provider failure telemetry
+ // Capture provider failure telemetry using clineError
+ // TODO: Move into ErrorService
telemetryService.captureProviderApiError({
taskId: this.taskId,
model: modelInfo.id,
- errorMessage: message,
- errorStatus: statusCode,
- requestId,
+ errorMessage: clineError.message,
+ errorStatus: clineError._error?.status,
+ requestId: clineError._error?.request_id,
})
if (isAnthropic && isAnthropicContextWindowError && !this.taskState.didAutomaticallyRetryFailedApiRequest) {
@@ -1737,12 +1745,12 @@ export class Task {
// If the conversation has more than 3 messages, we can truncate again. If not, then the conversation is bricked.
// ToDo: Allow the user to change their input if this is the case.
if (truncatedConversationHistory.length > 3) {
- error = new Error("Context window exceeded. Click retry to truncate the conversation and try again.")
+ clineError.message = "Context window exceeded. Click retry to truncate the conversation and try again."
this.taskState.didAutomaticallyRetryFailedApiRequest = false
}
}
- const errorMessage = formatErrorWithStatusCode(error)
+ const streamingFailedMessage = clineError.serialize()
// Update the 'api_req_started' message to reflect final failure before asking user to manually retry
const lastApiReqStartedIndex = findLastIndex(
@@ -1758,19 +1766,24 @@ export class Task {
text: JSON.stringify({
...currentApiReqInfo, // Spread the modified info (with retryStatus removed)
// cancelReason: "retries_exhausted", // Indicate that automatic retries failed
- streamingFailedMessage: errorMessage,
+ streamingFailedMessage,
} satisfies ClineApiReqInfo),
})
// this.ask will trigger postStateToWebview, so this change should be picked up.
}
- const { response } = await this.ask("api_req_failed", errorMessage)
+ const { response } = await this.ask("api_req_failed", streamingFailedMessage)
if (response !== "yesButtonClicked") {
// this will never happen since if noButtonClicked, we will clear current task, aborting this instance
throw new Error("API request failed")
}
+ // Do not retry automatically again if currently unauthenticated
+ if (clineError.isErrorType(ClineErrorType.Auth)) {
+ return
+ }
+
await this.say("api_req_retried")
}
// delegate generator output from the recursive call
@@ -1906,10 +1919,10 @@ export class Task {
}
// Used to know what models were used in the task if user wants to export metadata for error reporting purposes
- const currentProviderId = (await getGlobalState(this.getContext(), "apiProvider")) as string
- if (currentProviderId && this.api.getModel().id) {
+ const { modelId, providerId } = await this.getCurrentProviderInfo()
+ if (providerId && modelId) {
try {
- await this.modelContextTracker.recordModelUsage(currentProviderId, this.api.getModel().id, this.chatSettings.mode)
+ await this.modelContextTracker.recordModelUsage(providerId, modelId, this.chatSettings.mode)
} catch {}
}
@@ -2087,7 +2100,7 @@ export class Task {
content: userContent,
})
- telemetryService.captureConversationTurnEvent(this.taskId, currentProviderId, this.api.getModel().id, "user")
+ telemetryService.captureConversationTurnEvent(this.taskId, providerId, modelId, "user")
// since we sent off a placeholder api_req_started message to update the webview while waiting to actually start the API request (to load potential details for example), we need to update the text of that message
const lastApiReqIndex = findLastIndex(this.messageStateHandler.getClineMessages(), (m) => m.say === "api_req_started")
@@ -2152,19 +2165,13 @@ export class Task {
})
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
- telemetryService.captureConversationTurnEvent(
- this.taskId,
- currentProviderId,
- this.api.getModel().id,
- "assistant",
- {
- tokensIn: inputTokens,
- tokensOut: outputTokens,
- cacheWriteTokens,
- cacheReadTokens,
- totalCost,
- },
- )
+ telemetryService.captureConversationTurnEvent(this.taskId, providerId, this.api.getModel().id, "assistant", {
+ tokensIn: inputTokens,
+ tokensOut: outputTokens,
+ cacheWriteTokens,
+ cacheReadTokens,
+ totalCost,
+ })
// signals to provider that it can retrieve the saved messages from disk, as abortTask can not be awaited on in nature
this.taskState.didFinishAbortingStream = true
@@ -2261,7 +2268,8 @@ export class Task {
// abandoned happens when extension is no longer waiting for the cline instance to finish aborting (error is thrown here when any function in the for loop throws due to this.abort)
if (!this.taskState.abandoned) {
this.abortTask() // if the stream failed, there's various states the task could be in (i.e. could have streamed some tools the user may have executed), so we just resort to replicating a cancel task
- const errorMessage = formatErrorWithStatusCode(error)
+ const clineError = ErrorService.toClineError(error, this.api.getModel().id)
+ const errorMessage = clineError.serialize()
await abortStream("streaming_failed", errorMessage)
await this.reinitExistingTaskFromId(this.taskId)
@@ -2331,19 +2339,13 @@ export class Task {
// need to save assistant responses to file before proceeding to tool use since user can exit at any moment and we wouldn't be able to save the assistant's response
let didEndLoop = false
if (assistantMessage.length > 0) {
- telemetryService.captureConversationTurnEvent(
- this.taskId,
- currentProviderId,
- this.api.getModel().id,
- "assistant",
- {
- tokensIn: inputTokens,
- tokensOut: outputTokens,
- cacheWriteTokens,
- cacheReadTokens,
- totalCost,
- },
- )
+ telemetryService.captureConversationTurnEvent(this.taskId, providerId, modelId, "assistant", {
+ tokensIn: inputTokens,
+ tokensOut: outputTokens,
+ cacheWriteTokens,
+ cacheReadTokens,
+ totalCost,
+ })
await this.messageStateHandler.addToApiConversationHistory({
role: "assistant",
@@ -2389,6 +2391,8 @@ export class Task {
},
],
})
+ // Returns early to avoid retry since no assistant message was received
+ return true
}
return didEndLoop // will always be false for now
diff --git a/src/core/task/utils.ts b/src/core/task/utils.ts
index b1c6bd94..c8da5d17 100644
--- a/src/core/task/utils.ts
+++ b/src/core/task/utils.ts
@@ -1,25 +1,9 @@
import { showSystemNotification } from "@/integrations/notifications"
import { ClineApiReqCancelReason, ClineApiReqInfo } from "@/shared/ExtensionMessage"
-import { serializeError } from "serialize-error"
import { MessageStateHandler } from "./message-state"
import { calculateApiCostAnthropic } from "@/utils/cost"
import { ApiHandler } from "@/api"
-export function formatErrorWithStatusCode(error: any): string {
- const { statusCode, message } = extractErrorDetails(error)
-
- // Only prepend the statusCode if it's not already part of the message
- return statusCode && !message.includes(statusCode.toString()) ? `${statusCode} - ${message}` : message
-}
-
-export function extractErrorDetails(error: any): { message: string; statusCode?: number; requestId?: string } {
- const statusCode = error.status || error.statusCode || (error.response && error.response?.status)
- const message = error.message ?? JSON.stringify(serializeError(error), null, 2)
- const requestId = error.request_id || error.response?.request_id || undefined
-
- return { message, statusCode, requestId }
-}
-
export const showNotificationForApprovalIfAutoApprovalEnabled = (
message: string,
autoApprovalSettingsEnabled: boolean,
diff --git a/src/services/error/ClineError.ts b/src/services/error/ClineError.ts
new file mode 100644
index 00000000..0dc053d4
--- /dev/null
+++ b/src/services/error/ClineError.ts
@@ -0,0 +1,157 @@
+import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "../../shared/ClineAccount"
+import { serializeError } from "serialize-error"
+
+export enum ClineErrorType {
+ Auth = "auth",
+ Network = "network",
+ RateLimit = "rateLimit",
+ Balance = "balance",
+}
+
+interface ErrorDetails {
+ /**
+ * The HTTP status code of the error, if applicable.
+ */
+ status?: number
+ /**
+ * The request ID associated with the error, if available.
+ * This can be useful for debugging and support.
+ */
+ request_id?: string
+ /**
+ * Specific error code provided by the API or service.
+ */
+ code?: string
+ /**
+ * The model ID associated with the error, if applicable.
+ * This is useful for identifying which model the error relates to.
+ */
+ modelId?: string
+ /**
+ * The provider ID associated with the error, if applicable.
+ * This is useful for identifying which provider the error relates to.
+ */
+ providerId?: string
+ /**
+ * The error message associated with the error, if applicable.
+ */
+ message?: string
+ // Additional details that might be present in the error
+ // This can include things like current balance, error messages, etc.
+ details?: any
+}
+
+const RATE_LIMIT_PATTERNS = [/status code 429/i, /rate limit/i, /too many requests/i, /quota exceeded/i, /resource exhausted/i]
+
+export class ClineError extends Error {
+ readonly title = "ClineError"
+ readonly _error: ErrorDetails
+
+ // Error details per providers:
+ // Cline: error?.error
+ // Ollama: error?.cause
+ // tbc
+ constructor(
+ raw: any,
+ public readonly modelId?: string,
+ public readonly providerId?: string,
+ ) {
+ const error = serializeError(raw)
+
+ const message = error.message || String(error) || error?.cause?.means
+ super(message)
+
+ // Extract status from multiple possible locations
+ const status = error.status || error.statusCode || error.response?.status
+
+ // Construct the error details object to includes relevant information
+ // And ensure it has a consistent structure
+ this._error = {
+ message: raw.message || message,
+ status,
+ request_id: error.request_id || error.response?.request_id,
+ code: error.code || error?.cause?.code,
+ modelId,
+ providerId,
+ details: error.details || error.error, // Additional details provided by the server
+ ...error,
+ stack: undefined, // Avoid serializing stack trace to keep the error object clean
+ }
+ }
+
+ /**
+ * Serializes the error to a JSON string that allows for easy transmission and storage.
+ * This is useful for logging or sending error details to a webviews.
+ */
+ public serialize(): string {
+ return JSON.stringify({
+ message: this.message,
+ status: this._error.status,
+ request_id: this._error.request_id,
+ code: this._error.code,
+ modelId: this.modelId,
+ providerId: this.providerId,
+ details: this._error.details,
+ })
+ }
+
+ /**
+ * Parses a stringified error into a ClineError instance.
+ */
+ static parse(errorStr?: string, modelId?: string): ClineError | undefined {
+ if (!errorStr || typeof errorStr !== "string") {
+ return undefined
+ }
+ return ClineError.transform(errorStr, modelId)
+ }
+
+ /**
+ * Transforms any object into a ClineError instance.
+ * Always returns a ClineError, even if the input is not a valid error object.
+ */
+ static transform(error: any, modelId?: string, providerId?: string): ClineError {
+ try {
+ return new ClineError(JSON.parse(error), modelId, providerId)
+ } catch {
+ return new ClineError(error, modelId, providerId)
+ }
+ }
+
+ public isErrorType(type: ClineErrorType): boolean {
+ return ClineError.getErrorType(this) === type
+ }
+
+ /**
+ * Is known error type based on the error code, status, and details.
+ * This is useful for determining how to handle the error in the UI or logic.
+ */
+ static getErrorType(err: ClineError): ClineErrorType | undefined {
+ const { code, status, details } = err._error
+
+ // Check balance error first (most specific)
+ if (code === "insufficient_credits" && typeof details?.current_balance === "number") {
+ return ClineErrorType.Balance
+ }
+
+ // Check auth errors
+ if (code === "ERR_BAD_REQUEST" || status === 401) {
+ return ClineErrorType.Auth
+ }
+
+ // Check for auth message (only if message exists)
+ const message = err.message
+ if (message?.includes(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE)) {
+ return ClineErrorType.Auth
+ }
+
+ // Check rate limit patterns
+ if (message) {
+ const lowerMessage = message.toLowerCase()
+ if (RATE_LIMIT_PATTERNS.some((pattern) => pattern.test(lowerMessage))) {
+ return ClineErrorType.RateLimit
+ }
+ }
+
+ return undefined
+ }
+}
diff --git a/src/services/error/ErrorService.ts b/src/services/error/ErrorService.ts
index f2da4371..13f31bfa 100644
--- a/src/services/error/ErrorService.ts
+++ b/src/services/error/ErrorService.ts
@@ -1,7 +1,8 @@
import * as Sentry from "@sentry/browser"
import * as vscode from "vscode"
-import { telemetryService } from "@/services/posthog/telemetry/TelemetryService"
+import { telemetryService } from "../posthog/telemetry/TelemetryService"
import * as pkg from "../../../package.json"
+import { ClineError } from "./ClineError"
let telemetryLevel = vscode.workspace.getConfiguration("telemetry").get("telemetryLevel", "all")
let isTelemetryEnabled = ["all", "error"].includes(telemetryLevel)
@@ -15,6 +16,8 @@ vscode.workspace.onDidChangeConfiguration(() => {
}
})
+const isDev = process.env.IS_DEV === "true"
+
export class ErrorService {
private static serviceEnabled: boolean
private static serviceLevel: string
@@ -29,7 +32,7 @@ export class ErrorService {
beforeSend(event) {
// TelemetryService keeps track of whether the user has opted in to telemetry/error reporting
const isUserManuallyOptedIn = telemetryService.isTelemetryEnabled()
- if (isUserManuallyOptedIn && ErrorService.isEnabled()) {
+ if (isUserManuallyOptedIn && ErrorService.isEnabled() && !isDev) {
return event
}
return null
@@ -65,7 +68,7 @@ export class ErrorService {
}
}
- static logException(error: Error): void {
+ static logException(error: Error | ClineError): void {
// Don't log if telemetry is off
const isUserManuallyOptedIn = telemetryService.isTelemetryEnabled()
if (!isUserManuallyOptedIn || !ErrorService.isEnabled()) {
@@ -93,4 +96,8 @@ export class ErrorService {
static isEnabled(): boolean {
return ErrorService.serviceEnabled
}
+
+ static toClineError(rawError: any, modelId?: string, providerId?: string): ClineError {
+ return ClineError.transform(rawError, modelId, providerId)
+ }
}
diff --git a/src/services/posthog/PostHogClientProvider.ts b/src/services/posthog/PostHogClientProvider.ts
index dab585aa..7f540f8a 100644
--- a/src/services/posthog/PostHogClientProvider.ts
+++ b/src/services/posthog/PostHogClientProvider.ts
@@ -1,5 +1,5 @@
import { PostHog } from "posthog-node"
-import { posthogConfig } from "@/shared/services/config/posthog-config"
+import { posthogConfig } from "../../shared/services/config/posthog-config"
class PostHogClientProvider {
private static instance: PostHogClientProvider
diff --git a/src/shared/ExtensionMessage.ts b/src/shared/ExtensionMessage.ts
index a05571c8..08a5f2f7 100644
--- a/src/shared/ExtensionMessage.ts
+++ b/src/shared/ExtensionMessage.ts
@@ -7,7 +7,7 @@ import { HistoryItem } from "./HistoryItem"
import { TelemetrySetting } from "./TelemetrySetting"
import { ClineRulesToggles } from "./cline-rules"
import { UserInfo } from "./UserInfo"
-import { McpDisplayMode, DEFAULT_MCP_DISPLAY_MODE } from "./McpDisplayMode"
+import { McpDisplayMode } from "./McpDisplayMode"
// webview will hold state
export interface ExtensionMessage {
diff --git a/webview-ui/src/components/chat/ChatRow.tsx b/webview-ui/src/components/chat/ChatRow.tsx
index 2978b72c..446f257e 100644
--- a/webview-ui/src/components/chat/ChatRow.tsx
+++ b/webview-ui/src/components/chat/ChatRow.tsx
@@ -1,10 +1,9 @@
-import { VSCodeBadge, VSCodeButton, VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react"
+import { VSCodeBadge, VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react"
import deepEqual from "fast-deep-equal"
import React, { memo, MouseEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
import styled from "styled-components"
import { useSize } from "react-use"
-import CreditLimitError from "@/components/chat/CreditLimitError"
import { OptionsButtons } from "@/components/chat/OptionsButtons"
import TaskFeedbackButtons from "@/components/chat/TaskFeedbackButtons"
import { CheckmarkControl } from "@/components/common/CheckmarkControl"
@@ -36,8 +35,8 @@ import NewTaskPreview from "./NewTaskPreview"
import ReportBugPreview from "./ReportBugPreview"
import UserMessage from "./UserMessage"
import QuoteButton from "./QuoteButton"
-import { useClineAuth } from "@/context/ClineAuthContext"
-import { CLINE_ACCOUNT_AUTH_ERROR_MESSAGE } from "@shared/ClineAccount"
+import ErrorRow from "./ErrorRow"
+import { ErrorBlockTitle } from "./ErrorBlockTitle"
const normalColor = "var(--vscode-foreground)"
const errorColor = "var(--vscode-errorForeground)"
@@ -104,42 +103,6 @@ const Markdown = memo(({ markdown }: { markdown?: string }) => {
)
})
-const RetryMessage = memo(
- ({ seconds, attempt, retryOperations }: { retryOperations: number; attempt: number; seconds?: number }) => {
- const [remainingSeconds, setRemainingSeconds] = useState(seconds || 0)
-
- useEffect(() => {
- if (seconds && seconds > 0) {
- setRemainingSeconds(seconds)
-
- const interval = setInterval(() => {
- setRemainingSeconds((prev) => {
- if (prev <= 1) {
- clearInterval(interval)
- return 0
- }
- return prev - 1
- })
- }, 1000)
-
- return () => clearInterval(interval)
- }
- }, [seconds])
-
- return (
-
- {`API Request (Retrying failed attempt ${attempt}/${retryOperations}`}
- {remainingSeconds > 0 && ` in ${remainingSeconds} seconds`}
- )...
-
- )
- },
-)
-
const ChatRow = memo(
(props: ChatRowProps) => {
const { isLast, onHeightChange, message, lastModifiedMessage, inputValue } = props
@@ -186,7 +149,6 @@ export const ChatRowContent = memo(
sendMessageFromChatRow,
onSetQuote,
}: ChatRowContentProps) => {
- const { handleSignIn, clineUser } = useClineAuth()
const { mcpServers, mcpMarketplaceCatalog, onRelinquishControl, apiConfiguration } = useExtensionState()
const [seeNewChangesDisabled, setSeeNewChangesDisabled] = useState(false)
const [quoteButtonState, setQuoteButtonState] = useState({
@@ -201,7 +163,7 @@ export const ChatRowContent = memo(
const info: ClineApiReqInfo = JSON.parse(message.text)
return [info.cost, info.cancelReason, info.streamingFailedMessage, info.retryStatus]
}
- return [undefined, undefined, undefined, undefined]
+ return [undefined, undefined, undefined, undefined, undefined]
}, [message.text, message.say])
// when resuming task last won't be api_req_failed but a resume_task message so api_req_started will show loading spinner. that's why we just remove the last api_req_started that failed without streaming anything
@@ -381,73 +343,12 @@ export const ChatRowContent = memo(
Task Completed,
]
case "api_req_started":
- const getIconSpan = (iconName: string, color: string) => (
-
-
-
- )
- return [
- apiReqCancelReason != null ? (
- apiReqCancelReason === "user_cancelled" ? (
- getIconSpan("error", cancelledColor)
- ) : (
- getIconSpan("error", errorColor)
- )
- ) : cost != null ? (
- getIconSpan("check", successColor)
- ) : apiRequestFailedMessage ? (
- getIconSpan("error", errorColor)
- ) : (
-
- ),
- (() => {
- if (apiReqCancelReason != null) {
- return apiReqCancelReason === "user_cancelled" ? (
- API Request Cancelled
- ) : (
- API Streaming Failed
- )
- }
-
- if (cost != null) {
- return API Request
- }
-
- if (apiRequestFailedMessage) {
- const errorData = parseErrorText(apiRequestFailedMessage)
- if (errorData?.code === "insufficient_credits") {
- return Credit Limit Reached
- }
- return API Request Failed
- }
- // New: Check for retryStatus to modify the title
- if (retryStatus && cost == null && !apiReqCancelReason) {
- const retryOperations = retryStatus.maxAttempts > 0 ? retryStatus.maxAttempts - 1 : 0
- return (
-
- )
- }
-
- return API Request...
- })(),
- ]
+ return ErrorBlockTitle({
+ cost,
+ apiReqCancelReason,
+ apiRequestFailedMessage,
+ retryStatus,
+ })
case "followup":
return [
{((cost == null && apiRequestFailedMessage) || apiReqStreamingFailedMessage) && (
- <>
- {(() => {
- // Try to parse the error message as JSON for credit limit error
- const errorData = parseErrorText(
- apiRequestFailedMessage || apiReqStreamingFailedMessage,
- )
- if (errorData) {
- if (
- errorData.code === "insufficient_credits" &&
- typeof errorData.current_balance === "number"
- ) {
- return (
-
- )
- }
- }
-
- // Check for rate limit errors (status code 429)
- const isRateLimitError =
- apiRequestFailedMessage?.includes("status code 429") ||
- apiRequestFailedMessage?.toLowerCase().includes("rate limit") ||
- apiRequestFailedMessage?.toLowerCase().includes("too many requests") ||
- apiRequestFailedMessage?.toLowerCase().includes("quota exceeded") ||
- apiRequestFailedMessage?.toLowerCase().includes("resource exhausted")
-
- if (isRateLimitError) {
- return (
-
- {apiRequestFailedMessage || apiReqStreamingFailedMessage}
-
- )
- }
-
- // Default error display
- return (
-
- {apiRequestFailedMessage || apiReqStreamingFailedMessage}
- {apiRequestFailedMessage?.toLowerCase().includes("powershell") && (
- <>
-
-
- It seems like you're having Windows PowerShell issues, please see this{" "}
-
- troubleshooting guide
-
- .
- >
- )}
- {apiRequestFailedMessage?.includes(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE) && (
- <>
-
-
- {clineUser ? (
-
- (Click "Retry" below)
-
- ) : (
-
- Sign in to Cline
-
- )}
- >
- )}
-
- )
- })()}
- >
+
)}
{isExpanded && (
@@ -1183,97 +1004,11 @@ export const ChatRowContent = memo(
)
case "error":
- return (
- <>
- {title && (
-
- {icon}
- {title}
-
- )}
-
- {message.text}
-
- >
- )
+ return
case "diff_error":
- return (
- <>
-
-
-
- Diff Edit Mismatch
-
-
The model used search patterns that don't match anything in the file. Retrying...
-
- >
- )
+ return
case "clineignore_error":
- return (
- <>
-
-
-
-
- Access Denied
-
-
-
- Cline tried to access {message.text} which is blocked by the{" "}
- .clineignore
- file.
-
-
- >
- )
+ return
case "checkpoint_created":
return (
<>
@@ -1433,37 +1168,9 @@ export const ChatRowContent = memo(
case "ask":
switch (message.ask) {
case "mistake_limit_reached":
- return (
- <>
-
- {icon}
- {title}
-
-
- {message.text}
-
- >
- )
+ return
case "auto_approval_max_req_reached":
- return (
- <>
-
- {icon}
- {title}
-
-
- {message.text}
-
- >
- )
+ return
case "completion_result":
if (message.text) {
const hasChanges = message.text.endsWith(COMPLETION_RESULT_CHANGES_FLAG) ?? false
@@ -1686,20 +1393,3 @@ export const ChatRowContent = memo(
}
},
)
-
-function parseErrorText(text: string | undefined) {
- if (!text) {
- return undefined
- }
- try {
- const startIndex = text.indexOf("{")
- const endIndex = text.lastIndexOf("}")
- if (startIndex !== -1 && endIndex !== -1) {
- const jsonStr = text.substring(startIndex, endIndex + 1)
- const errorObject = JSON.parse(jsonStr)
- return errorObject
- }
- } catch (e) {
- // Not JSON or missing required fields
- }
-}
diff --git a/webview-ui/src/components/chat/ErrorBlockTitle.tsx b/webview-ui/src/components/chat/ErrorBlockTitle.tsx
new file mode 100644
index 00000000..013fd17d
--- /dev/null
+++ b/webview-ui/src/components/chat/ErrorBlockTitle.tsx
@@ -0,0 +1,106 @@
+import React from "react"
+import { ClineError, ClineErrorType } from "../../../../src/services/error/ClineError"
+import { ProgressIndicator } from "./ChatRow"
+
+const RetryMessage = React.memo(
+ ({ seconds, attempt, retryOperations }: { retryOperations: number; attempt: number; seconds?: number }) => {
+ const [remainingSeconds, setRemainingSeconds] = React.useState(seconds || 0)
+
+ React.useEffect(() => {
+ if (seconds && seconds > 0) {
+ setRemainingSeconds(seconds)
+
+ const interval = setInterval(() => {
+ setRemainingSeconds((prev) => {
+ if (prev <= 1) {
+ clearInterval(interval)
+ return 0
+ }
+ return prev - 1
+ })
+ }, 1000)
+
+ return () => clearInterval(interval)
+ }
+ }, [seconds])
+
+ return (
+
+ {`API Request (Retrying failed attempt ${attempt}/${retryOperations}`}
+ {remainingSeconds > 0 && ` in ${remainingSeconds} seconds`}
+ )...
+
+ )
+ },
+)
+
+interface ErrorBlockTitleProps {
+ cost?: number
+ apiReqCancelReason?: string
+ apiRequestFailedMessage?: string
+ retryStatus?: {
+ attempt: number
+ maxAttempts: number
+ delaySec?: number
+ errorSnippet?: string
+ }
+}
+
+export const ErrorBlockTitle = ({
+ cost,
+ apiReqCancelReason,
+ apiRequestFailedMessage,
+ retryStatus,
+}: ErrorBlockTitleProps): [React.ReactElement, React.ReactElement] => {
+ const getIconSpan = (iconName: string, colorClass: string) => (
+
+
+
+ )
+
+ const icon =
+ apiReqCancelReason != null ? (
+ apiReqCancelReason === "user_cancelled" ? (
+ getIconSpan("error", "text-[var(--vscode-descriptionForeground)]")
+ ) : (
+ getIconSpan("error", "text-[var(--vscode-errorForeground)]")
+ )
+ ) : cost != null ? (
+ getIconSpan("check", "text-[var(--vscode-charts-green)]")
+ ) : apiRequestFailedMessage ? (
+ getIconSpan("error", "text-[var(--vscode-errorForeground)]")
+ ) : (
+
+ )
+
+ const title = (() => {
+ // Default loading state
+ const details = { title: "API Request...", classNames: ["font-bold"] }
+ // Handle cancellation states first
+ if (apiReqCancelReason === "user_cancelled") {
+ details.title = "API Request Cancelled"
+ details.classNames.push("text-[var(--vscode-foreground)]")
+ } else if (apiReqCancelReason != null) {
+ details.title = "API Streaming Failed"
+ details.classNames.push("text-[var(--vscode-errorForeground)]")
+ } else if (cost != null) {
+ // Handle completed request
+ details.title = "API Request"
+ details.classNames.push("text-[var(--vscode-foreground)]")
+ } else if (apiRequestFailedMessage) {
+ // Handle failed request
+ const clineError = ClineError.parse(apiRequestFailedMessage)
+ const titleText = clineError?.isErrorType(ClineErrorType.Balance) ? "Credit Limit Reached" : "API Request Failed"
+ details.title = titleText
+ details.classNames.push("font-bold text-[var(--vscode-errorForeground)]")
+ } else if (retryStatus) {
+ // Handle retry state
+ const retryOperations = Math.max(0, retryStatus.maxAttempts - 1)
+ return
+ }
+
+ return {details.title}
+ })()
+
+ return [icon, title]
+}
diff --git a/webview-ui/src/components/chat/ErrorRow.test.tsx b/webview-ui/src/components/chat/ErrorRow.test.tsx
new file mode 100644
index 00000000..8a7e9cbd
--- /dev/null
+++ b/webview-ui/src/components/chat/ErrorRow.test.tsx
@@ -0,0 +1,200 @@
+import { render, screen } from "@testing-library/react"
+import { describe, it, expect, vi } from "vitest"
+import ErrorRow from "./ErrorRow"
+import { ClineMessage } from "@shared/ExtensionMessage"
+
+// Mock the auth context
+const mockHandleSignIn = vi.fn()
+vi.mock("@/context/ClineAuthContext", () => ({
+ useClineAuth: () => ({
+ handleSignIn: mockHandleSignIn,
+ clineUser: null,
+ }),
+}))
+
+// Mock CreditLimitError component
+vi.mock("@/components/chat/CreditLimitError", () => ({
+ default: ({ message }: { message: string }) => {message}
,
+}))
+
+// Mock ClineError
+vi.mock("../../../../src/services/error/ClineError", () => ({
+ ClineError: {
+ parse: vi.fn(),
+ },
+ ClineErrorType: {
+ Balance: "balance",
+ RateLimit: "rateLimit",
+ Auth: "auth",
+ },
+}))
+
+describe("ErrorRow", () => {
+ const mockMessage: ClineMessage = {
+ ts: 123456789,
+ type: "say",
+ say: "error",
+ text: "Test error message",
+ }
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it("renders basic error message", () => {
+ render()
+
+ expect(screen.getByText("Test error message")).toBeInTheDocument()
+ })
+
+ it("renders mistake limit reached error", () => {
+ const mistakeMessage = { ...mockMessage, text: "Mistake limit reached" }
+ render()
+
+ expect(screen.getByText("Mistake limit reached")).toBeInTheDocument()
+ })
+
+ it("renders auto approval max requests error", () => {
+ const maxReqMessage = { ...mockMessage, text: "Max requests reached" }
+ render()
+
+ expect(screen.getByText("Max requests reached")).toBeInTheDocument()
+ })
+
+ it("renders diff error", () => {
+ render()
+
+ expect(
+ screen.getByText("The model used search patterns that don't match anything in the file. Retrying..."),
+ ).toBeInTheDocument()
+ })
+
+ it("renders clineignore error", () => {
+ const clineignoreMessage = { ...mockMessage, text: "/path/to/file.txt" }
+ render()
+
+ expect(screen.getByText(/Cline tried to access/)).toBeInTheDocument()
+ expect(screen.getByText("/path/to/file.txt")).toBeInTheDocument()
+ })
+
+ describe("API error handling", () => {
+ it("renders credit limit error when balance error is detected", async () => {
+ const mockClineError = {
+ message: "Insufficient credits",
+ isErrorType: vi.fn((type) => type === "balance"),
+ _error: {
+ details: {
+ current_balance: 0,
+ total_spent: 10.5,
+ total_promotions: 5.0,
+ message: "You have run out of credit.",
+ buy_credits_url: "https://app.cline.bot/dashboard",
+ },
+ },
+ }
+
+ const { ClineError } = await import("../../../../src/services/error/ClineError")
+ vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any)
+
+ render()
+
+ expect(screen.getByTestId("credit-limit-error")).toBeInTheDocument()
+ expect(screen.getByText("You have run out of credit.")).toBeInTheDocument()
+ })
+
+ it("renders rate limit error with request ID", async () => {
+ const mockClineError = {
+ message: "Rate limit exceeded",
+ isErrorType: vi.fn((type) => type === "rateLimit"),
+ _error: {
+ request_id: "req_123456",
+ },
+ }
+
+ const { ClineError } = await import("../../../../src/services/error/ClineError")
+ vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any)
+
+ render()
+
+ expect(screen.getByText("Rate limit exceeded")).toBeInTheDocument()
+ expect(screen.getByText("Request ID: req_123456")).toBeInTheDocument()
+ })
+
+ it("renders auth error with sign in button when user is not signed in", async () => {
+ const mockClineError = {
+ message: "Authentication failed",
+ isErrorType: vi.fn((type) => type === "auth"),
+ providerId: "cline",
+ _error: {},
+ }
+
+ const { ClineError } = await import("../../../../src/services/error/ClineError")
+ vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any)
+
+ render()
+
+ expect(screen.getByText("Authentication failed")).toBeInTheDocument()
+ expect(screen.getByText("Sign in to Cline")).toBeInTheDocument()
+ })
+
+ it("renders PowerShell troubleshooting link when error mentions PowerShell", async () => {
+ const mockClineError = {
+ message: "PowerShell is not recognized as an internal or external command",
+ isErrorType: vi.fn(() => false),
+ _error: {},
+ }
+
+ const { ClineError } = await import("../../../../src/services/error/ClineError")
+ vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any)
+
+ render(
+ ,
+ )
+
+ expect(screen.getByText(/PowerShell is not recognized/)).toBeInTheDocument()
+ expect(screen.getByText("troubleshooting guide")).toBeInTheDocument()
+ expect(screen.getByRole("link", { name: "troubleshooting guide" })).toHaveAttribute(
+ "href",
+ "https://github.com/cline/cline/wiki/TroubleShooting-%E2%80%90-%22PowerShell-is-not-recognized-as-an-internal-or-external-command%22",
+ )
+ })
+
+ it("handles apiReqStreamingFailedMessage instead of apiRequestFailedMessage", async () => {
+ const mockClineError = {
+ message: "Streaming failed",
+ isErrorType: vi.fn(() => false),
+ _error: {},
+ }
+
+ const { ClineError } = await import("../../../../src/services/error/ClineError")
+ vi.mocked(ClineError.parse).mockReturnValue(mockClineError as any)
+
+ render()
+
+ expect(screen.getByText("Streaming failed")).toBeInTheDocument()
+ })
+
+ it("falls back to regular error message when ClineError.parse returns null", async () => {
+ const { ClineError } = await import("../../../../src/services/error/ClineError")
+ vi.mocked(ClineError.parse).mockReturnValue(undefined)
+
+ render()
+
+ // When ClineError.parse returns null, clineErrorMessage is undefined, so it renders an empty paragraph
+ // The fallback to message.text only happens when there's no apiRequestFailedMessage at all
+ const paragraph = screen.getByRole("paragraph")
+ expect(paragraph).toBeInTheDocument()
+ expect(paragraph).toBeEmptyDOMElement()
+ })
+
+ it("renders regular error message when no API error messages are provided", () => {
+ render()
+
+ expect(screen.getByText("Test error message")).toBeInTheDocument()
+ })
+ })
+})
diff --git a/webview-ui/src/components/chat/ErrorRow.tsx b/webview-ui/src/components/chat/ErrorRow.tsx
new file mode 100644
index 00000000..a320f8bf
--- /dev/null
+++ b/webview-ui/src/components/chat/ErrorRow.tsx
@@ -0,0 +1,130 @@
+import { memo } from "react"
+import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
+import { ClineMessage } from "@shared/ExtensionMessage"
+import { ClineError, ClineErrorType } from "../../../../src/services/error/ClineError"
+import CreditLimitError from "@/components/chat/CreditLimitError"
+import { useClineAuth } from "@/context/ClineAuthContext"
+
+const errorColor = "var(--vscode-errorForeground)"
+
+interface ErrorRowProps {
+ message: ClineMessage
+ errorType: "error" | "mistake_limit_reached" | "auto_approval_max_req_reached" | "diff_error" | "clineignore_error"
+ apiRequestFailedMessage?: string
+ apiReqStreamingFailedMessage?: string
+}
+
+const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStreamingFailedMessage }: ErrorRowProps) => {
+ const { handleSignIn, clineUser } = useClineAuth()
+
+ const renderErrorContent = () => {
+ switch (errorType) {
+ case "error":
+ case "mistake_limit_reached":
+ case "auto_approval_max_req_reached":
+ // Handle API request errors with special error parsing
+ if (apiRequestFailedMessage || apiReqStreamingFailedMessage) {
+ const clineError = ClineError.parse(apiRequestFailedMessage || apiReqStreamingFailedMessage)
+ const clineErrorMessage = clineError?.message
+ const requestId = clineError?._error?.request_id
+ const isClineProvider = clineError?.providerId === "cline"
+
+ if (clineError) {
+ if (clineError.isErrorType(ClineErrorType.Balance)) {
+ const errorDetails = clineError._error?.details
+ return (
+
+ )
+ }
+ }
+
+ if (clineError?.isErrorType(ClineErrorType.RateLimit)) {
+ return (
+
+ {clineErrorMessage}
+ {requestId &&
Request ID: {requestId}
}
+
+ )
+ }
+
+ // Default error display
+ return (
+
+ {clineErrorMessage}
+ {requestId &&
Request ID: {requestId}
}
+ {clineErrorMessage?.toLowerCase()?.includes("powershell") && (
+ <>
+
+
+ It seems like you're having Windows PowerShell issues, please see this{" "}
+
+ troubleshooting guide
+
+ .
+ >
+ )}
+ {clineError?.isErrorType(ClineErrorType.Auth) && (
+ <>
+
+
+ {/* The user is signed in or not using cline provider */}
+ {clineUser && !isClineProvider ? (
+
+ (Click "Retry" below)
+
+ ) : (
+
+ Sign in to Cline
+
+ )}
+ >
+ )}
+
+ )
+ }
+
+ // Regular error message
+ return (
+ {message.text}
+ )
+
+ case "diff_error":
+ return (
+
+
The model used search patterns that don't match anything in the file. Retrying...
+
+ )
+
+ case "clineignore_error":
+ return (
+
+
+ Cline tried to access {message.text} which is blocked by the .clineignore
+ file.
+
+
+ )
+
+ default:
+ return null
+ }
+ }
+
+ // For diff_error and clineignore_error, we don't show the header separately
+ if (errorType === "diff_error" || errorType === "clineignore_error") {
+ return <>{renderErrorContent()}>
+ }
+
+ // For other error types, show header + content
+ return <>{renderErrorContent()}>
+})
+
+export default ErrorRow
diff --git a/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx b/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx
new file mode 100644
index 00000000..27e45688
--- /dev/null
+++ b/webview-ui/src/components/chat/__tests__/ErrorBlockTitle.spec.tsx
@@ -0,0 +1,51 @@
+import { describe, it, expect } from "vitest"
+import { ErrorBlockTitle } from "../ErrorBlockTitle"
+
+describe("ErrorBlockTitle", () => {
+ it("should return icon and title for API request cancelled", () => {
+ const [icon, title] = ErrorBlockTitle({
+ apiReqCancelReason: "user_cancelled",
+ })
+
+ expect(icon).toBeDefined()
+ expect(title).toBeDefined()
+ })
+
+ it("should return icon and title for completed API request", () => {
+ const [icon, title] = ErrorBlockTitle({
+ cost: 0.001,
+ })
+
+ expect(icon).toBeDefined()
+ expect(title).toBeDefined()
+ })
+
+ it("should return icon and title for failed API request", () => {
+ const [icon, title] = ErrorBlockTitle({
+ apiRequestFailedMessage: "Request failed",
+ })
+
+ expect(icon).toBeDefined()
+ expect(title).toBeDefined()
+ })
+
+ it("should return icon and title for retry status", () => {
+ const [icon, title] = ErrorBlockTitle({
+ retryStatus: {
+ attempt: 2,
+ maxAttempts: 3,
+ delaySec: 5,
+ },
+ })
+
+ expect(icon).toBeDefined()
+ expect(title).toBeDefined()
+ })
+
+ it("should return icon and title for default API request", () => {
+ const [icon, title] = ErrorBlockTitle({})
+
+ expect(icon).toBeDefined()
+ expect(title).toBeDefined()
+ })
+})