Unify error handling and display logic (#4984)
* Unify error handling and display Several improvements to error handling and reporting within the Cline extension, focusing on providing more informative error messages to the user and improving telemetry data. - **Error Handling:** - Introduces a `ClineError` class to encapsulate Cline-specific errors, providing structured data about the error (status code, request ID, etc.). - The `ErrorService` now creates and logs `ClineError` instances, improving error reporting to Sentry and telemetry. - Removes redundant error formatting logic from `src/core/task/utils.ts`, relying on the `ClineError` class for consistent error representation. - The Cline API handler now throws the raw error, allowing the `ClineError` class to handle the error formatting. - **UI Improvements:** - Introduces new UI components (`ErrorRow`, `ErrorBlockTitle`) to display error messages in a more user-friendly format within the chat interface. - Displays credit limit errors with detailed information and a link to purchase credits. - Improves the display of rate limit errors and authentication errors. - Adds specific handling for PowerShell-related errors, providing a link to a troubleshooting guide. - **Telemetry:** - Captures provider API errors using `ClineError` data, providing more detailed information about the error in telemetry reports. - **Other Changes:** - Fixes an import path in `src/services/posthog/PostHogClientProvider.ts`. - Adds tests for the new UI components. - Adds `error` field to `ClineMessage` to transport `ClineError` instances to the webview. These changes aim to provide a better user experience by displaying more informative error messages and improving the overall reliability of the Cline extension. * include provider id * includes model and provider id * fix test * return gracefully for empty response
This commit is contained in:
12 files changed
+726
-407
No files matched your search
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+48
-44
@@ -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<Anthropic.TextBlockParam | Anthropic.ImageBlockParam>
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<string>("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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 (
|
||||
<span
|
||||
style={{
|
||||
color: normalColor,
|
||||
fontWeight: "bold",
|
||||
}}>
|
||||
{`API Request (Retrying failed attempt ${attempt}/${retryOperations}`}
|
||||
{remainingSeconds > 0 && ` in ${remainingSeconds} seconds`}
|
||||
)...
|
||||
</span>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
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<QuoteButtonState>({
|
||||
@@ -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(
|
||||
<span style={{ color: successColor, fontWeight: "bold" }}>Task Completed</span>,
|
||||
]
|
||||
case "api_req_started":
|
||||
const getIconSpan = (iconName: string, color: string) => (
|
||||
<div
|
||||
style={{
|
||||
width: 16,
|
||||
height: 16,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}>
|
||||
<span
|
||||
className={`codicon codicon-${iconName}`}
|
||||
style={{
|
||||
color,
|
||||
fontSize: 16,
|
||||
marginBottom: "-1.5px",
|
||||
}}></span>
|
||||
</div>
|
||||
)
|
||||
return [
|
||||
apiReqCancelReason != null ? (
|
||||
apiReqCancelReason === "user_cancelled" ? (
|
||||
getIconSpan("error", cancelledColor)
|
||||
) : (
|
||||
getIconSpan("error", errorColor)
|
||||
)
|
||||
) : cost != null ? (
|
||||
getIconSpan("check", successColor)
|
||||
) : apiRequestFailedMessage ? (
|
||||
getIconSpan("error", errorColor)
|
||||
) : (
|
||||
<ProgressIndicator />
|
||||
),
|
||||
(() => {
|
||||
if (apiReqCancelReason != null) {
|
||||
return apiReqCancelReason === "user_cancelled" ? (
|
||||
<span style={{ color: normalColor, fontWeight: "bold" }}>API Request Cancelled</span>
|
||||
) : (
|
||||
<span style={{ color: errorColor, fontWeight: "bold" }}>API Streaming Failed</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (cost != null) {
|
||||
return <span style={{ color: normalColor, fontWeight: "bold" }}>API Request</span>
|
||||
}
|
||||
|
||||
if (apiRequestFailedMessage) {
|
||||
const errorData = parseErrorText(apiRequestFailedMessage)
|
||||
if (errorData?.code === "insufficient_credits") {
|
||||
return <span style={{ color: errorColor, fontWeight: "bold" }}>Credit Limit Reached</span>
|
||||
}
|
||||
return <span style={{ color: errorColor, fontWeight: "bold" }}>API Request Failed</span>
|
||||
}
|
||||
// New: Check for retryStatus to modify the title
|
||||
if (retryStatus && cost == null && !apiReqCancelReason) {
|
||||
const retryOperations = retryStatus.maxAttempts > 0 ? retryStatus.maxAttempts - 1 : 0
|
||||
return (
|
||||
<RetryMessage
|
||||
seconds={retryStatus.delaySec}
|
||||
attempt={retryStatus.attempt}
|
||||
retryOperations={retryOperations}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return <span style={{ color: normalColor, fontWeight: "bold" }}>API Request...</span>
|
||||
})(),
|
||||
]
|
||||
return ErrorBlockTitle({
|
||||
cost,
|
||||
apiReqCancelReason,
|
||||
apiRequestFailedMessage,
|
||||
retryStatus,
|
||||
})
|
||||
case "followup":
|
||||
return [
|
||||
<span
|
||||
@@ -946,92 +847,12 @@ export const ChatRowContent = memo(
|
||||
<span className={`codicon codicon-chevron-${isExpanded ? "up" : "down"}`}></span>
|
||||
</div>
|
||||
{((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 (
|
||||
<CreditLimitError
|
||||
currentBalance={errorData.current_balance}
|
||||
totalSpent={errorData.total_spent}
|
||||
totalPromotions={errorData.total_promotions}
|
||||
message={errorData.message}
|
||||
buyCreditsUrl={errorData.buy_credits_url}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<p
|
||||
style={{
|
||||
...pStyle,
|
||||
color: "var(--vscode-errorForeground)",
|
||||
}}>
|
||||
{apiRequestFailedMessage || apiReqStreamingFailedMessage}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
// Default error display
|
||||
return (
|
||||
<p
|
||||
style={{
|
||||
...pStyle,
|
||||
color: "var(--vscode-errorForeground)",
|
||||
}}>
|
||||
{apiRequestFailedMessage || apiReqStreamingFailedMessage}
|
||||
{apiRequestFailedMessage?.toLowerCase().includes("powershell") && (
|
||||
<>
|
||||
<br />
|
||||
<br />
|
||||
It seems like you're having Windows PowerShell issues, please see this{" "}
|
||||
<a
|
||||
href="https://github.com/cline/cline/wiki/TroubleShooting-%E2%80%90-%22PowerShell-is-not-recognized-as-an-internal-or-external-command%22"
|
||||
style={{
|
||||
color: "inherit",
|
||||
textDecoration: "underline",
|
||||
}}>
|
||||
troubleshooting guide
|
||||
</a>
|
||||
.
|
||||
</>
|
||||
)}
|
||||
{apiRequestFailedMessage?.includes(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE) && (
|
||||
<>
|
||||
<br />
|
||||
<br />
|
||||
{clineUser ? (
|
||||
<span style={{ color: "var(--vscode-descriptionForeground)" }}>
|
||||
(Click "Retry" below)
|
||||
</span>
|
||||
) : (
|
||||
<VSCodeButton onClick={handleSignIn} className="w-full mb-4">
|
||||
Sign in to Cline
|
||||
</VSCodeButton>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
})()}
|
||||
</>
|
||||
<ErrorRow
|
||||
message={message}
|
||||
errorType="error"
|
||||
apiRequestFailedMessage={apiRequestFailedMessage}
|
||||
apiReqStreamingFailedMessage={apiReqStreamingFailedMessage}
|
||||
/>
|
||||
)}
|
||||
|
||||
{isExpanded && (
|
||||
@@ -1183,97 +1004,11 @@ export const ChatRowContent = memo(
|
||||
</div>
|
||||
)
|
||||
case "error":
|
||||
return (
|
||||
<>
|
||||
{title && (
|
||||
<div style={headerStyle}>
|
||||
{icon}
|
||||
{title}
|
||||
</div>
|
||||
)}
|
||||
<p
|
||||
style={{
|
||||
...pStyle,
|
||||
color: "var(--vscode-errorForeground)",
|
||||
}}>
|
||||
{message.text}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
return <ErrorRow message={message} errorType="error" />
|
||||
case "diff_error":
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
backgroundColor: "var(--vscode-textBlockQuote-background)",
|
||||
padding: 8,
|
||||
borderRadius: 3,
|
||||
fontSize: 12,
|
||||
color: "var(--vscode-foreground)",
|
||||
opacity: 0.8,
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
marginBottom: 4,
|
||||
}}>
|
||||
<i
|
||||
className="codicon codicon-warning"
|
||||
style={{
|
||||
marginRight: 8,
|
||||
fontSize: 14,
|
||||
color: "var(--vscode-descriptionForeground)",
|
||||
}}></i>
|
||||
<span style={{ fontWeight: 500 }}>Diff Edit Mismatch</span>
|
||||
</div>
|
||||
<div>The model used search patterns that don't match anything in the file. Retrying...</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
return <ErrorRow message={message} errorType="diff_error" />
|
||||
case "clineignore_error":
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
backgroundColor: "rgba(255, 191, 0, 0.1)",
|
||||
padding: 8,
|
||||
borderRadius: 3,
|
||||
fontSize: 12,
|
||||
}}>
|
||||
<div
|
||||
style={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
marginBottom: 4,
|
||||
}}>
|
||||
<i
|
||||
className="codicon codicon-error"
|
||||
style={{
|
||||
marginRight: 8,
|
||||
fontSize: 18,
|
||||
color: "#FFA500",
|
||||
}}></i>
|
||||
<span
|
||||
style={{
|
||||
fontWeight: 500,
|
||||
color: "#FFA500",
|
||||
}}>
|
||||
Access Denied
|
||||
</span>
|
||||
</div>
|
||||
<div>
|
||||
Cline tried to access <code>{message.text}</code> which is blocked by the{" "}
|
||||
<code>.clineignore</code>
|
||||
file.
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
return <ErrorRow message={message} errorType="clineignore_error" />
|
||||
case "checkpoint_created":
|
||||
return (
|
||||
<>
|
||||
@@ -1433,37 +1168,9 @@ export const ChatRowContent = memo(
|
||||
case "ask":
|
||||
switch (message.ask) {
|
||||
case "mistake_limit_reached":
|
||||
return (
|
||||
<>
|
||||
<div style={headerStyle}>
|
||||
{icon}
|
||||
{title}
|
||||
</div>
|
||||
<p
|
||||
style={{
|
||||
...pStyle,
|
||||
color: "var(--vscode-errorForeground)",
|
||||
}}>
|
||||
{message.text}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
return <ErrorRow message={message} errorType="mistake_limit_reached" />
|
||||
case "auto_approval_max_req_reached":
|
||||
return (
|
||||
<>
|
||||
<div style={headerStyle}>
|
||||
{icon}
|
||||
{title}
|
||||
</div>
|
||||
<p
|
||||
style={{
|
||||
...pStyle,
|
||||
color: "var(--vscode-errorForeground)",
|
||||
}}>
|
||||
{message.text}
|
||||
</p>
|
||||
</>
|
||||
)
|
||||
return <ErrorRow message={message} errorType="auto_approval_max_req_reached" />
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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 (
|
||||
<span className="font-bold text-[var(--vscode-foreground)]">
|
||||
{`API Request (Retrying failed attempt ${attempt}/${retryOperations}`}
|
||||
{remainingSeconds > 0 && ` in ${remainingSeconds} seconds`}
|
||||
)...
|
||||
</span>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
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) => (
|
||||
<div className="w-4 h-4 flex items-center justify-center">
|
||||
<span className={`codicon codicon-${iconName} text-base -mb-0.5 ${colorClass}`}></span>
|
||||
</div>
|
||||
)
|
||||
|
||||
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)]")
|
||||
) : (
|
||||
<ProgressIndicator />
|
||||
)
|
||||
|
||||
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 <RetryMessage seconds={retryStatus.delaySec} attempt={retryStatus.attempt} retryOperations={retryOperations} />
|
||||
}
|
||||
|
||||
return <span className={details.classNames.join(" ")}>{details.title}</span>
|
||||
})()
|
||||
|
||||
return [icon, title]
|
||||
}
|
||||
@@ -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 }) => <div data-testid="credit-limit-error">{message}</div>,
|
||||
}))
|
||||
|
||||
// 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(<ErrorRow message={mockMessage} errorType="error" />)
|
||||
|
||||
expect(screen.getByText("Test error message")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders mistake limit reached error", () => {
|
||||
const mistakeMessage = { ...mockMessage, text: "Mistake limit reached" }
|
||||
render(<ErrorRow message={mistakeMessage} errorType="mistake_limit_reached" />)
|
||||
|
||||
expect(screen.getByText("Mistake limit reached")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders auto approval max requests error", () => {
|
||||
const maxReqMessage = { ...mockMessage, text: "Max requests reached" }
|
||||
render(<ErrorRow message={maxReqMessage} errorType="auto_approval_max_req_reached" />)
|
||||
|
||||
expect(screen.getByText("Max requests reached")).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it("renders diff error", () => {
|
||||
render(<ErrorRow message={mockMessage} errorType="diff_error" />)
|
||||
|
||||
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(<ErrorRow message={clineignoreMessage} errorType="clineignore_error" />)
|
||||
|
||||
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(<ErrorRow message={mockMessage} errorType="error" apiRequestFailedMessage="Insufficient credits error" />)
|
||||
|
||||
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(<ErrorRow message={mockMessage} errorType="error" apiRequestFailedMessage="Rate limit exceeded" />)
|
||||
|
||||
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(<ErrorRow message={mockMessage} errorType="error" apiRequestFailedMessage="Authentication failed" />)
|
||||
|
||||
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(
|
||||
<ErrorRow
|
||||
message={mockMessage}
|
||||
errorType="error"
|
||||
apiRequestFailedMessage="PowerShell is not recognized as an internal or external command"
|
||||
/>,
|
||||
)
|
||||
|
||||
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(<ErrorRow message={mockMessage} errorType="error" apiReqStreamingFailedMessage="Streaming failed" />)
|
||||
|
||||
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(<ErrorRow message={mockMessage} errorType="error" apiRequestFailedMessage="Some API error" />)
|
||||
|
||||
// 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(<ErrorRow message={mockMessage} errorType="error" />)
|
||||
|
||||
expect(screen.getByText("Test error message")).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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 (
|
||||
<CreditLimitError
|
||||
currentBalance={errorDetails?.current_balance}
|
||||
totalSpent={errorDetails?.total_spent}
|
||||
totalPromotions={errorDetails?.total_promotions}
|
||||
message={errorDetails?.message}
|
||||
buyCreditsUrl={errorDetails?.buy_credits_url}
|
||||
/>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (clineError?.isErrorType(ClineErrorType.RateLimit)) {
|
||||
return (
|
||||
<p className="m-0 whitespace-pre-wrap text-[var(--vscode-errorForeground)] wrap-anywhere">
|
||||
{clineErrorMessage}
|
||||
{requestId && <div>Request ID: {requestId}</div>}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
// Default error display
|
||||
return (
|
||||
<p className="m-0 whitespace-pre-wrap text-[var(--vscode-errorForeground)] wrap-anywhere">
|
||||
{clineErrorMessage}
|
||||
{requestId && <div>Request ID: {requestId}</div>}
|
||||
{clineErrorMessage?.toLowerCase()?.includes("powershell") && (
|
||||
<>
|
||||
<br />
|
||||
<br />
|
||||
It seems like you're having Windows PowerShell issues, please see this{" "}
|
||||
<a
|
||||
href="https://github.com/cline/cline/wiki/TroubleShooting-%E2%80%90-%22PowerShell-is-not-recognized-as-an-internal-or-external-command%22"
|
||||
className="underline text-inherit">
|
||||
troubleshooting guide
|
||||
</a>
|
||||
.
|
||||
</>
|
||||
)}
|
||||
{clineError?.isErrorType(ClineErrorType.Auth) && (
|
||||
<>
|
||||
<br />
|
||||
<br />
|
||||
{/* The user is signed in or not using cline provider */}
|
||||
{clineUser && !isClineProvider ? (
|
||||
<span className="mb-4 text-[var(--vscode-descriptionForeground)]">
|
||||
(Click "Retry" below)
|
||||
</span>
|
||||
) : (
|
||||
<VSCodeButton onClick={handleSignIn} className="w-full mb-4">
|
||||
Sign in to Cline
|
||||
</VSCodeButton>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
|
||||
// Regular error message
|
||||
return (
|
||||
<p className="m-0 whitespace-pre-wrap text-[var(--vscode-errorForeground)] wrap-anywhere">{message.text}</p>
|
||||
)
|
||||
|
||||
case "diff_error":
|
||||
return (
|
||||
<div className="flex flex-col p-2 rounded text-xs opacity-80 bg-[var(--vscode-textBlockQuote-background)] text-[var(--vscode-foreground)]">
|
||||
<div>The model used search patterns that don't match anything in the file. Retrying...</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
case "clineignore_error":
|
||||
return (
|
||||
<div className="flex flex-col p-2 rounded text-xs bg-[var(--vscode-textBlockQuote-background)] text-[var(--vscode-foreground)] opacity-80">
|
||||
<div>
|
||||
Cline tried to access <code>{message.text}</code> which is blocked by the <code>.clineignore</code>
|
||||
file.
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
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
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user