Author SHA1 Message Date
Adam-PAN 6965212ff7 fix: resolve Base URL input garbled text and collapsed width in API settings
- Fix scrambled text when typing in Base URL fields: debounced input hook now ignores echo round-trips of its own saves and defers unexpected external updates during an edit grace period

- Serialize API configuration saves through a queue so rapid successive updates are applied in order on the backend

- Fix Base URL input collapsing to tiny width: Radix TooltipTrigger now renders a full-width block wrapper instead of the default shrink-to-fit button

- Trim Base URL values only on commit instead of every keystroke to prevent cursor jumps

- Skip redundant save on mount and flush uncommitted edits on unmount

- Bump version to 4.3.1, update CHANGELOG and README
2026-09-17 02:53:43 +08:00
Adam-PAN 376d10cbbb feat: 使用统计页面 + 简体中文界面优化
- 新增「我的」页面替代原「账户」页面
- 实现使用统计仪表盘(Tokens消耗、成本统计、缓存命中率)
- 添加使用趋势图表(支持按天/周/月/全部筛选)
- 添加模型消耗统计表格
- 优化简体中文翻译
- 修改导航栏标签和工具提示
2026-09-11 20:28:17 +08:00
Adam-PAN 34bb7b9a93 feat: 全界面简体中文化 + Ctrl+Enter 换行
- i18n 固定为简体中文(zh-CN),不再进行语言切换
- 补全 zh-CN 翻译约 400 个缺失 key(featureSettings、providers、account、modelPicker 等)
- 硬编码英文界面文案汉化(调试区、用量/付款记录、远程配置、账户页、导航栏)
- 聊天输入框支持 Ctrl+Enter 在光标处换行(Enter 仍发送消息)
- 首选语言设置固定显示"简体中文"
- 任务历史记录中文化(HistoryItem 相对时间等)
2026-09-11 20:18:48 +08:00
Adam-PAN 8fbb954218 fix: restore modelId param in SubagentRunner.createMessageWithInitialChunkRetry 2026-09-01 23:31:30 +08:00
Adam-PAN 1f2646e685 v4.2.0: context compression improvements & multimodal image stripping
Context Compression:
- auto-condense extended to all models with >=200K context window
- 500K+ context windows use 92% buffer (was conservative formula)
- added summarizeTaskLite template for <200K models
- fileOptimizationThreshold now configurable (default 0.3)

Multimodal Image Handling:
- auto-strip images when switching from vision to text-only models
- one-time notification per task session
- images preserved in history, auto-restored when switching back

Bug Fixes:
- fixed API errors when switching multimodal to text-only model mid-conversation
2026-09-01 23:29:42 +08:00
Adam-PAN b4c6cf59df v4.1.0: EditableModelSelector + massive model updates
- All provider model dropdowns now support free-text custom model input
- Added Anthropic Claude 5 (opus-5, sonnet-5, fable-5, mythos-5)
- Added 60+ new models across DeepSeek, OpenAI, Gemini, Qwen, Kimi, GLM, XAI, Doubao, MiniMax
- DeepSeek: v4-flash-vision-exp, v4-flash-0731 (1.3M ctx), v3.2, v3.1-terminus
- XAI/Grok: grok-4.20 (2M ctx), grok-4.6, grok-4.5, grok-4.3
- Qwen: qwen3.8-max/flash, qwen3.7, qwen3.6, qwen3.5, qwen3-coder variants
- Kimi: kimi-k3 (1M ctx), kimi-k2.7-code
- GLM: glm-5.3-flash (1.3M ctx), glm-5.3, glm-5.2, glm-5-turbo
- Doubao: seed-2-1-turbo, seed-2.0-code, seed-2.0-lite, seed-1.6
- MiniMax: MiniMax-M3 (1M ctx), MiniMax-M1
- EditableModelSelector styled with VS Code theme CSS variables
- normalizeApiConfiguration preserves custom model IDs with defaults
2026-08-28 01:07:25 +08:00
Adam-PAN 945e4b39bd bump version to 3.87.0 2026-08-19 22:13:36 +08:00
Adam-PAN 77c82adb10 docs: update CHANGELOG and README for v3.86.11 2026-08-19 22:07:44 +08:00
Adam-PAN 26937786b9 fix: inline type for profilePayload to avoid missing import 2026-08-19 21:48:36 +08:00
Adam-PAN 895c4d9296 fix: profilePayload return type for TypeScript build 2026-08-19 21:41:10 +08:00
Adam-PAN 04f2c1c16a v3.86.11: friendly error cards, real-time cost display, per-profile pricing
- Add friendly Chinese error cards for ModelNotFound, ContentFiltered, ServerError, Timeout, Network
- Add real-time Token/Cost display bar in chat footer
- Fix #1: per-profile price storage - each API profile independently stores and restores pricing
- Add price input fields for DeepSeek provider
- Fix '400 Invalid assistant message' for DeepSeek V4
- Fix reasoning-only models returning empty responses
- Fix tool_choice from 'required' to 'auto' for reasoning models
- Fix API Key cleared when switching profiles
- Bump version to 3.86.11
- Update CHANGELOG and README
2026-08-19 20:33:48 +08:00
Adam-PAN 7aa4fd50c7 fix: add thinking budget to DeepSeek to reduce verbose reasoning output 2026-08-01 12:58:59 +08:00
Adam-PAN dd8a57b234 fix: disable garbled Chinese tool descriptions causing missing parameter errors 2026-08-01 12:32:06 +08:00
Adam-PAN 085e692741 fix: wrap unfenced code in markdown fences to prevent garbled syntax highlighting 2026-08-01 12:23:19 +08:00
Adam-PAN 269a8e0573 fix: plan mode model ID not set when switching profiles, fix corrupted i18n string 2026-08-01 10:52:14 +08:00
Adam-PAN d2b86a9bf8 fix: force tool_choice=required for reasoning models (Mimo, Qwen, OpenAI-compatible) 2026-08-01 04:07:56 +08:00
Adam-PAN bf12d4ba8b fix: force DeepSeek V4 to use tools, fix API key saving, fix base URL width 2026-08-01 03:59:14 +08:00
Adam-PAN f216473471 v3.86.7: fix API key saving, base URL width, skip bash-dependent lint 2026-08-01 00:39:43 +08:00
102 changed files with 5623 additions and 3770 deletions

No files matched your search

View File
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
web_search = "disabled"
+3
View File
@@ -84,3 +84,6 @@ test-results/
*storybook.log
storybook-static
**/StorybookDecorator.tsx
# Exclude archive files
*.zip
+133 -2187
View File
File diff suppressed because it is too large. Load diff
+32 -9
View File
@@ -1,4 +1,4 @@
# Cline Multi 🌏
# Cline Multi 🌏
<p align="center">
<img src="assets/icons/icon.png" width="128" alt="Cline Multi Icon">
@@ -20,10 +20,14 @@ Cline Multi 基于 [Cline](https://github.com/cline/cline) 构建,是一款支
### 核心特性
- **多模型热切换** — 保存多个 API 配置预设,在工作中随时切换不同模型
- **多模型热切换** — 保存多个 API 配置预设,在工作中随时切换不同模型,每个配置独立存储价格
- **国产模型深度适配** — 针对 DeepSeek、Mimo、Kimi 等国产模型优化提示词,提升中文输入下的表现
- **友好错误提示** — 模型不存在、内容拦截、服务器错误、超时等场景显示中文友好提示卡片
- **实时成本监控** — 聊天界面底部实时显示 Token 用量和费用
- **完整中文支持** — 界面全面中文化,中文 prompt 优化
- **全功能 AI 助手** — 文件读写、终端命令、浏览器操作、MCP 服务器等完整能力
- **智能上下文压缩** — 自动为大上下文模型(200K+)启用 auto-condense,500K+ 模型使用92%高效缓冲,弱模型使用精简摘要模板
- **多模态智能切换** — 从图片识别模型切回纯语言模型时,自动剥离历史图片并提示用户,切回多模态模型后图片自动恢复
## 安装
@@ -53,13 +57,17 @@ Cline Multi 基于 [Cline](https://github.com/cline/cline) 构建,是一款支
| Provider | 示例模型 |
|----------|----------|
| Anthropic | Claude 3.5 Sonnet, Claude 3 Opus |
| OpenAI | GPT-4o, GPT-4 |
| DeepSeek | DeepSeek-V4-Pro, DeepSeek-V4-Flash |
| Google | Gemini 2.5 Pro |
| Mimo | mimo-v2.5-pro |
| Moonshot | Kimi |
| 更多... | Ollama, LM Studio, vLLM 等本地模型 |
| Anthropic | Claude Opus 5, Claude Sonnet 5, Claude Fable 5, Claude Mythos 5 |
| OpenAI | GPT-5.6 Sol/Terra/Luna, GPT-5.5, GPT-5.4, o4-mini |
| DeepSeek | DeepSeek V4 Pro/Flash, V4 Flash Vision, V4 Flash 0731 (1.3M ctx) |
| Google | Gemini 3.7 Flash, Gemini 3.1 Pro, Gemini 2.5 Pro |
| Qwen/通义 | Qwen3.8 Max/Flash, Qwen3 Coder Plus/Flash, Qwen3.7 |
| Kimi/Moonshot | Kimi K3 (1M ctx), Kimi K2.7 Code, Kimi K2.6 |
| GLM/智谱 | GLM-5.3 Flash (1.3M ctx), GLM-5.3, GLM-5.2, GLM-5 |
| XAI/Grok | Grok 4.20 (2M ctx), Grok 4.6, Grok 4.5, Grok 4.3 |
| Doubao/豆包 | Seed 2.1 Turbo, Seed 2.0 Code, Seed 2.0 Lite |
| MiniMax | MiniMax M3 (1M ctx), MiniMax M2.7 |
| 更多... | Ollama, LM Studio, Mistral, Fireworks, Nebius 等 |
## 项目地址
@@ -67,8 +75,23 @@ https://github.com/Adam-PAN/cline-multi
欢迎 Star ⭐、Fork 🍴、提出 Issue 和贡献代码!
## 更新日志
详见 [CHANGELOG.md](CHANGELOG.md)
最近更新 (v4.3.1):
- **修复基础 URL 输入框文字错乱** — 输入不再被慢速状态回流覆盖,配置保存改为串行化防止乱序互相覆盖
- **修复基础 URL 输入框宽度过短** — OpenAI Compatible 等提供商的 Base URL 输入框现在与其他输入框宽度一致
- **上下文压缩增强** — 200K+ 模型自动启用 auto-condense,500K+ 模型使用 92% 高效缓冲
- **多模态智能切换** — 从图片模型切回纯文本模型时自动剥离历史图片防止 API 报错
- 详见 [CHANGELOG.md](CHANGELOG.md)
## 许可证
本项目基于 [Apache-2.0](LICENSE) 许可证开源。
原版 Cline 版权归属于 [Cline 团队](https://github.com/cline/cline)。
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "cline-multi",
"version": "3.86.6",
"version": "4.2.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "cline-multi",
"version": "3.86.6",
"version": "4.2.0",
"license": "Apache-2.0",
"workspaces": [
"."
+2 -2
View File
@@ -2,7 +2,7 @@
"name": "cline-multi",
"displayName": "Cline Multi",
"description": "%cline.description%",
"version": "3.86.6",
"version": "4.3.1",
"icon": "assets/icons/icon.png",
"workspaces": [
"."
@@ -401,7 +401,7 @@
"compile-tests": "node ./scripts/build-tests.js",
"watch-tests": "tsc -p . -w --outDir out",
"check-types": "npm run protos && npx tsc --noEmit && cd webview-ui && npx tsc --noEmit",
"lint": "biome lint --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error && npm run lint:proto",
"lint": "biome lint --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error",
"lint:proto": "bash ./scripts/proto-lint.sh",
"format": "biome format --changed --no-errors-on-unmatched --files-ignore-unknown=true --diagnostic-level=error",
"format:fix": "biome check --changed --no-errors-on-unmatched --files-ignore-unknown=true --write",
+1 -1
View File
@@ -15,7 +15,7 @@
"cline.command.newTask": "新任务",
"cline.command.mcpServers": "MCP 服务器",
"cline.command.history": "历史记录",
"cline.command.account": "账户",
"cline.command.account": "我的",
"cline.command.settings": "设置",
"cline.command.createTestTasks": "创建测试任务",
"cline.command.expireMcpOAuthTokens": "过期 MCP OAuth 令牌(测试用)",
+19
View File
@@ -37,6 +37,11 @@ service StateService {
rpc refreshRemoteConfig(EmptyRequest) returns (Empty);
rpc testOtelConnection(EmptyRequest) returns (TestConnectionResult);
rpc testPromptUploading(EmptyRequest) returns (TestConnectionResult);
// Aggregated usage statistics computed over the FULL task history
rpc getUsageStats(StringRequest) returns (UsageStats);
// Durable API config profiles (persisted in extension globalState, NOT webview localStorage)
rpc getApiProfiles(EmptyRequest) returns (ApiProfilesState);
rpc saveApiProfiles(ApiProfilesState) returns (Empty);
}
message AutoApprovalActions {
@@ -289,6 +294,7 @@ message Settings {
optional bool lazy_teammate_mode_enabled = 183;
optional OpenRouterModelInfo plan_mode_deep_seek_model_info = 188;
optional OpenRouterModelInfo act_mode_deep_seek_model_info = 189;
optional int32 file_optimization_threshold = 190;
}
message State {
@@ -485,3 +491,16 @@ message TestConnectionResult {
optional string message = 2;
optional string error = 3;
}
// Aggregated usage statistics payload (serialized UsageStatsResult JSON).
// Computed over the FULL task history rather than the truncated copy sent to the webview.
message UsageStats {
string usage_json = 1;
}
// Durable API config profiles. Serialized ApiConfigProfile[] JSON in profiles_json,
// plus the id of the currently active profile.
message ApiProfilesState {
string profiles_json = 1;
optional string active_profile_id = 2;
}
+2
View File
@@ -200,6 +200,8 @@ function createHandlerForProvider(
deepSeekApiKey: options.deepSeekApiKey,
apiModelId: mode === "plan" ? options.planModeApiModelId : options.actModeApiModelId,
deepSeekModelInfo: mode === "plan" ? options.planModeDeepSeekModelInfo : options.actModeDeepSeekModelInfo,
thinkingBudgetTokens:
mode === "plan" ? options.planModeThinkingBudgetTokens : options.actModeThinkingBudgetTokens,
})
case "requesty":
return new RequestyHandler({
+23 -1
View File
@@ -16,6 +16,7 @@ interface DeepSeekHandlerOptions extends CommonApiHandlerOptions {
deepSeekApiKey?: string
apiModelId?: string
deepSeekModelInfo?: ModelInfo
thinkingBudgetTokens?: number
}
export class DeepSeekHandler implements ApiHandler {
@@ -98,14 +99,27 @@ export class DeepSeekHandler implements ApiHandler {
stream_options: { include_usage: true },
// Only set temperature for non-thinking models
...(isDeepSeekThinkingModel ? {} : { temperature: 0 }),
...getOpenAIToolParams(tools),
// Limit thinking tokens to reduce verbose reasoning output
...(isDeepSeekThinkingModel && this.options.thinkingBudgetTokens
? { thinking_budget: this.options.thinkingBudgetTokens }
: {}),
// Force tool usage for V4 thinking models to prevent text-only responses
...(tools?.length
? isDeepSeekThinkingModel
? { tools, tool_choice: "auto" as const, parallel_tool_calls: false }
: getOpenAIToolParams(tools)
: { tools: undefined }),
})
const toolCallProcessor = new ToolCallProcessor()
let hasContent = false
let hasToolCalls = false
for await (const chunk of stream) {
const delta = chunk.choices?.[0]?.delta
if (delta?.content) {
hasContent = true
yield {
type: "text",
text: delta.content,
@@ -113,6 +127,7 @@ export class DeepSeekHandler implements ApiHandler {
}
if (delta?.tool_calls) {
hasToolCalls = true
yield* toolCallProcessor.processToolCallDeltas(delta.tool_calls)
}
@@ -127,6 +142,13 @@ export class DeepSeekHandler implements ApiHandler {
yield* this.yieldUsage(model.info, chunk.usage)
}
}
if (!hasContent && !hasToolCalls) {
yield {
type: "text",
text: "No textual response from model.",
}
}
}
getModel(): { id: DeepSeekModelId; info: ModelInfo } {
+12 -3
View File
@@ -34,8 +34,12 @@ export class OpenAiHandler implements ApiHandler {
private getAzureAudienceScope(baseUrl?: string): string {
const url = baseUrl?.toLowerCase() ?? ""
if (url.includes("azure.us")) return "https://cognitiveservices.azure.us/.default"
if (url.includes("azure.com")) return "https://cognitiveservices.azure.com/.default"
if (url.includes("azure.us")) {
return "https://cognitiveservices.azure.us/.default"
}
if (url.includes("azure.com")) {
return "https://cognitiveservices.azure.com/.default"
}
return "https://cognitiveservices.azure.com/.default"
}
@@ -141,7 +145,12 @@ export class OpenAiHandler implements ApiHandler {
reasoning_effort: reasoningEffort,
stream: true,
stream_options: { include_usage: true },
...getOpenAIToolParams(tools),
// Force tool usage for reasoning models to prevent text-only/empty responses
...(tools?.length
? isReasoningModelFamily || this.options.openAiModelInfo?.supportsReasoning
? { tools, tool_choice: "auto" as const, parallel_tool_calls: false }
: getOpenAIToolParams(tools)
: { tools: undefined }),
})
const toolCallProcessor = new ToolCallProcessor()
+6 -1
View File
@@ -118,7 +118,12 @@ export class QwenHandler implements ApiHandler {
stream_options: { include_usage: true },
temperature,
...thinkingArgs,
...getOpenAIToolParams(tools),
// Force tool usage for reasoning models to prevent text-only/empty responses
...(tools?.length
? isReasoningModelFamily || isDeepseekReasoner
? { tools, tool_choice: "auto" as const, parallel_tool_calls: false }
: getOpenAIToolParams(tools)
: { tools: undefined }),
})
const toolCallProcessor = new ToolCallProcessor()
+5 -3
View File
@@ -1,4 +1,4 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { ApiProvider } from "@/shared/api"
import {
@@ -254,7 +254,7 @@ export function convertToOpenAiMessages(
// Set content to blank when tool_calls are present but content has no text, per OpenAI API spec
const hasToolCalls = tool_calls.length > 0
const hasMeaningfulContent = content !== undefined && content.trim() !== ""
const finalContent = hasMeaningfulContent ? content : hasToolCalls ? null : undefined
const finalContent = hasMeaningfulContent ? content : hasToolCalls ? null : ""
const consolidatedReasoningDetails =
reasoningDetails.length > 0 ? consolidateReasoningDetails(reasoningDetails as any) : []
@@ -308,7 +308,9 @@ function consolidateReasoningDetails(reasoningDetails: ReasoningDetail[]): Reaso
// Drop corrupted encrypted reasoning blocks that would otherwise trigger:
// "Invalid input: expected string, received undefined" for reasoning_details.*.data
// See: https://github.com/cline/cline/issues/8214
if (detail.type === "reasoning.encrypted" && !detail.data) continue
if (detail.type === "reasoning.encrypted" && !detail.data) {
continue
}
const index = detail.index ?? 0
if (!groupedByIndex.has(index)) {
+2 -2
View File
@@ -1,4 +1,4 @@
import { Anthropic } from "@anthropic-ai/sdk"
import { Anthropic } from "@anthropic-ai/sdk"
import OpenAI from "openai"
import { ClineAssistantThinkingBlock, ClineStorageMessage } from "@/shared/messages/content"
@@ -135,7 +135,7 @@ export function convertToR1Format(messages: Anthropic.Messages.MessageParam[]):
if (message.role === "assistant") {
const newMessage: OpenAI.Chat.ChatCompletionAssistantMessageParam = {
role: "assistant",
content: messageContent as OpenAI.Chat.ChatCompletionAssistantMessageParam["content"],
content: (messageContent || "") as OpenAI.Chat.ChatCompletionAssistantMessageParam["content"],
}
merged.push(newMessage)
} else {
@@ -627,6 +627,7 @@ export class ContextManager {
apiConversationHistory: Anthropic.Messages.MessageParam[],
conversationHistoryDeletedRange: [number, number] | undefined,
timestamp: number,
threshold: number = 0.3,
): {
anyContextUpdates: boolean
needToTruncate: boolean
@@ -651,7 +652,7 @@ export class ContextManager {
return {
anyContextUpdates: true,
needToTruncate: percentSaved < 0.3,
needToTruncate: percentSaved < threshold,
}
}
@@ -664,6 +665,7 @@ export class ContextManager {
clineMessages: ClineMessage[],
previousApiReqIndex: number,
taskDirectory: string,
threshold: number = 0.3,
): Promise<boolean> {
// Extract timestamp using same logic as getNewContextMessagesAndMetadata
if (previousApiReqIndex < 0) {
@@ -681,6 +683,7 @@ export class ContextManager {
apiConversationHistory,
conversationHistoryDeletedRange,
timestamp,
threshold,
)
if (anyContextUpdates) {
@@ -20,8 +20,26 @@ export function getContextWindowInfo(api: ApiHandler) {
maxAllowedSize = contextWindow - 40_000
break
default:
maxAllowedSize = Math.max(contextWindow - 40_000, contextWindow * 0.8) // for deepseek, 80% of 64k meant only ~10k buffer which was too small and resulted in users getting context window errors.
// For very large context windows (500K+), use 92% to maximize usable space
// For smaller windows, keep the existing conservative formula
if (contextWindow >= 500_000) {
maxAllowedSize = Math.floor(contextWindow * 0.92)
} else {
maxAllowedSize = Math.max(contextWindow - 40_000, contextWindow * 0.8)
}
}
return { contextWindow, maxAllowedSize }
}
/**
* Determines if a model supports auto-condense (automatic context summarization).
* Uses context window size as the signal: models with >= 200K context window
* are considered capable enough to handle the summarize_task flow reliably.
* This replaces the previous isNextGenModelFamily() check which was too restrictive
* and excluded capable models like DeepSeek V3, Qwen-Long, Kimi, etc.
*/
export function supportsAutoCondense(api: ApiHandler): boolean {
const contextWindow = api.getModel().info.contextWindow || 128_000
return contextWindow >= 200_000
}
@@ -0,0 +1,17 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { ApiProfilesState } from "@shared/proto/cline/state"
import type { Controller } from "../index"
/**
* Returns the durable API config profiles persisted in extension globalState
* (NOT webview localStorage, which is wiped whenever the extension is
* reinstalled/updated or VSCode clears webview storage).
*/
export async function getApiProfiles(controller: Controller, _request: EmptyRequest): Promise<ApiProfilesState> {
const profiles = controller.stateManager.getGlobalStateKey("apiProfiles") ?? []
const activeProfileId = controller.stateManager.getGlobalStateKey("activeApiProfileId")
return ApiProfilesState.create({
profilesJson: JSON.stringify(profiles ?? []),
activeProfileId: activeProfileId,
})
}
@@ -0,0 +1,41 @@
import { usageLog } from "@core/storage/usage-log"
import { StringRequest } from "@shared/proto/cline/common"
import { UsageStats } from "@shared/proto/cline/state"
import { aggregateUsageEntries, aggregateUsageStats, type UsageStatsResult, type UsageTimeRange } from "@/shared/usage-stats"
import type { Controller } from "../index"
const VALID_RANGES: UsageTimeRange[] = ["today", "week", "month", "all"]
/**
* Aggregates usage statistics over the durable usage log (usage-log.jsonl),
* which records every model call independently of task history — so stats
* stay stable even when tasks are deleted. Falls back to aggregating the
* full task history when the log is empty (e.g. users who haven't made any
* requests since this log was introduced), so pre-existing history still shows.
* @param controller The controller instance
* @param request The request containing the time range ("today" | "week" | "month" | "all")
* @returns UsageStats with the serialized UsageStatsResult JSON payload
*/
export async function getUsageStats(controller: Controller, request: StringRequest): Promise<UsageStats> {
const range = VALID_RANGES.includes(request.value as UsageTimeRange) ? (request.value as UsageTimeRange) : "all"
// Prefer the durable per-request log; it survives task deletion and
// aggregates are unaffected by VSCode-side history truncation.
const logEntries = usageLog.readAll()
let result: UsageStatsResult
if (logEntries.length > 0) {
result = aggregateUsageEntries(logEntries, range)
} else {
// Fallback: aggregate from task history (legacy data before the log existed).
const taskHistory = controller.stateManager.getGlobalStateKey("taskHistory")
result = aggregateUsageStats(taskHistory, range)
}
return UsageStats.create({
usageJson: JSON.stringify({
totals: result.totals,
modelStats: Array.from(result.modelStats.entries()),
trend: result.trend,
}),
})
}
@@ -0,0 +1,22 @@
import { Empty } from "@shared/proto/cline/common"
import type { ApiProfilesState } from "@shared/proto/cline/state"
import type { Controller } from "../index"
/**
* Persists API config profiles to extension globalState so they survive
* extension reinstalls/updates and webview storage clears (unlike the previous
* webview localStorage implementation).
*/
export async function saveApiProfiles(controller: Controller, request: ApiProfilesState): Promise<Empty> {
try {
const parsed = JSON.parse(request.profilesJson || "[]")
if (!Array.isArray(parsed)) {
throw new Error("profilesJson must be an array")
}
controller.stateManager.setGlobalState("apiProfiles", parsed)
controller.stateManager.setGlobalState("activeApiProfileId", request.activeProfileId || undefined)
} catch (error) {
console.error("Failed to save API profiles:", error)
}
return Empty.create()
}
+39
View File
@@ -109,6 +109,45 @@ ${
`
}
/**
* Lite version of summarizeTask for weaker models (context window < 200K).
* Reduced from 10 sections to 4, much simpler instructions.
*/
export const summarizeTaskLite = (focusChainSettings?: { enabled: boolean }, cwd?: string) => {
const CWD = cwd ? cwd.toPosix() : ""
return `<explicit_instructions type="summarize_task">
The conversation is running out of context. Create a summary to continue work.
You have two options:
1. If all tasks are done, call attempt_completion
2. Otherwise, call summarize_task with a detailed summary
You MUST use one of these two tools. When summarizing, include:
<thinking>Organize your summary here</thinking>
<summarize_task>
<context>
1. What the user asked for
2. Key files and code changes made
3. What was completed and what remains
4. Current working state and next steps
</context>
${
focusChainSettings?.enabled
? `<task_progress>
- [x] Done items
- [ ] Remaining items
</task_progress>`
: ""
}
</summarize_task>
Working directory: ${CWD}
</explicit_instructions>\n
`
}
export const continuationPrompt = (summaryText: string) => `
This session is being continued from a previous conversation that ran out of context. The conversation is summarized below:
${summaryText}.
@@ -12,5 +12,8 @@ export function getLocaleText<T>(locale: string | undefined, texts: { en: T; "zh
* Check if the locale is Chinese
*/
export function isZhCN(locale: string | undefined): boolean {
return locale === "zh-CN"
// Temporarily disabled: Chinese translations contain mojibake (garbled text)
// that causes models to misunderstand tool parameter requirements.
// All prompts use English until Chinese strings are properly re-encoded.
return false
}
+8 -2
View File
@@ -67,7 +67,7 @@ export class StateManager {
/**
* File-backed storage context. All reads/writes to persistent state go through here.
* Do NOT access VSCode's ExtensionContext for storage — use this instead.
* Do NOT access VSCode's ExtensionContext for storage 鈥?use this instead.
*/
private storage: StorageContext
private isInitialized = false
@@ -865,7 +865,13 @@ export class StateManager {
const entries: Record<string, string | undefined> = {}
for (const key of keys) {
const value = this.secretsCache[key]
entries[key] = value || undefined // Convert empty strings to undefined (delete)
if (value) {
entries[key] = value
} else {
// Preserve existing secret when new value is empty/undefined
const existing = await this.storage.secrets.get(key as SecretKey)
entries[key] = existing ?? undefined
}
}
this.storage.secrets.setBatch(entries)
}
+110
View File
@@ -0,0 +1,110 @@
import fsSync from "node:fs"
import os from "node:os"
import path from "node:path"
import type { UsageLogEntry } from "@shared/usage-stats"
/**
* Durable, append-only usage log.
*
* Every completed model call is appended as a single JSON line to
* `<cline-dir>/data/usage-log.jsonl`. Usage statistics are aggregated from this
* log instead of task history, so records survive task deletion and stay stable
* across extension reinstalls.
*
* Writes are buffered and flushed to disk on a short debounce to avoid one
* synchronous write per request, while keeping data loss on crash limited to
* at most the few entries in the pending buffer.
*/
const FLUSH_INTERVAL_MS = 2000
export class UsageLog {
private filePath: string
private buffer: UsageLogEntry[] = []
private flushTimer: NodeJS.Timeout | null = null
constructor() {
const clineDir = process.env.CLINE_DIR || path.join(os.homedir(), ".cline")
const dataDir = path.join(clineDir, "data")
this.filePath = path.join(dataDir, "usage-log.jsonl")
fsSync.mkdirSync(dataDir, { recursive: true })
}
/** Override the log file location (used by tests). Creates parent dirs. */
setFilePath(filePath: string): void {
this.filePath = filePath
fsSync.mkdirSync(path.dirname(filePath), { recursive: true })
}
getFilePath(): string {
return this.filePath
}
/**
* Record one model call. The entry is buffered and flushed to disk within
* FLUSH_INTERVAL_MS (or on the next flush()/readAll() call).
*/
append(entry: UsageLogEntry): void {
this.buffer.push(entry)
if (!this.flushTimer) {
this.flushTimer = setTimeout(() => {
this.flushTimer = null
this.flush()
}, FLUSH_INTERVAL_MS)
// Never keep the process alive just for a pending flush.
this.flushTimer.unref?.()
}
}
/** Write all pending entries to disk. Failures keep entries queued for retry. */
flush(): void {
if (this.flushTimer) {
clearTimeout(this.flushTimer)
this.flushTimer = null
}
if (this.buffer.length === 0) {
return
}
const pending = this.buffer
this.buffer = []
try {
const lines = pending.map((entry) => JSON.stringify(entry)).join("\n")
fsSync.appendFileSync(this.filePath, lines + "\n", "utf8")
} catch (error) {
// Put entries back at the front so nothing is lost; the next flush retries.
this.buffer = [...pending, ...this.buffer]
console.error("UsageLog: failed to append to usage log:", error)
}
}
/**
* Read every logged entry. Flushes pending writes first so callers always
* see the complete history. Tolerates torn/corrupt lines (skips them).
*/
readAll(): UsageLogEntry[] {
this.flush()
let content: string
try {
content = fsSync.readFileSync(this.filePath, "utf8")
} catch {
// Missing file simply means no usage recorded yet.
return []
}
const entries: UsageLogEntry[] = []
for (const line of content.split("\n")) {
const trimmed = line.trim()
if (!trimmed) {
continue
}
try {
entries.push(JSON.parse(trimmed) as UsageLogEntry)
} catch {
// Torn line (e.g. crash mid-write) — skip rather than fail the read.
}
}
return entries
}
}
/** Shared singleton used by the task pipeline to record model calls. */
export const usageLog = new UsageLog()
+1
View File
@@ -55,6 +55,7 @@ export class TaskState {
consecutiveMistakeCount = 0
doubleCheckCompletionPending = false
didAutomaticallyRetryFailedApiRequest = false
hasNotifiedImageStripping = false
checkpointManagerErrorMessage?: string
// Retry tracking for auto-retry feature
+71 -33
View File
@@ -4,7 +4,7 @@ import { ApiStream } from "@core/api/transform/stream"
import { AssistantMessageContent, parseAssistantMessageV2, ToolUse } from "@core/assistant-message"
import { ContextManager } from "@core/context/context-management/ContextManager"
import { checkContextWindowExceededError } from "@core/context/context-management/context-error-handling"
import { getContextWindowInfo } from "@core/context/context-management/context-window-utils"
import { getContextWindowInfo, supportsAutoCondense } from "@core/context/context-management/context-window-utils"
import { EnvironmentContextTracker } from "@core/context/context-tracking/EnvironmentContextTracker"
import { FileContextTracker } from "@core/context/context-tracking/FileContextTracker"
import { ModelContextTracker } from "@core/context/context-tracking/ModelContextTracker"
@@ -27,7 +27,7 @@ import { executePreCompactHookWithCleanup, HookCancellationError, HookExecution
import { ClineIgnoreController } from "@core/ignore/ClineIgnoreController"
import { parseMentions } from "@core/mentions"
import { CommandPermissionController } from "@core/permissions"
import { summarizeTask } from "@core/prompts/contextManagement"
import { summarizeTask, summarizeTaskLite } from "@core/prompts/contextManagement"
import { formatResponse } from "@core/prompts/responses"
import { parseSlashCommands } from "@core/slash-commands"
import {
@@ -64,13 +64,7 @@ import { USER_CONTENT_TAGS } from "@shared/messages/constants"
import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message"
import { ClineDefaultTool, READ_ONLY_TOOLS } from "@shared/tools"
import { ClineAskResponse } from "@shared/WebviewMessage"
import {
isClaude4PlusModelFamily,
isGPT5ModelFamily,
isLocalModel,
isNextGenModelFamily,
isParallelToolCallingEnabled,
} from "@utils/model-utils"
import { isClaude4PlusModelFamily, isGPT5ModelFamily, isLocalModel, isParallelToolCallingEnabled } from "@utils/model-utils"
import { arePathsEqual, getDesktopDir } from "@utils/path"
import { filterExistingFiles } from "@utils/tabFiltering"
import cloneDeep from "clone-deep"
@@ -102,6 +96,7 @@ import {
ClineTextContentBlock,
ClineToolResponseContent,
ClineUserContent,
stripImagesFromMessages,
} from "@/shared/messages"
import { ApiFormat } from "@/shared/proto/cline/models"
import { ShowMessageType } from "@/shared/proto/index.host"
@@ -163,6 +158,10 @@ export class Task {
private taskIsFavorited?: boolean
private cwd: string
private taskInitializationStartTime: number
/** Provider id the task was started with — recorded on each durable usage-log entry. */
private startProvider?: string
/** Mode ("plan" | "act") the task was started with — recorded on each durable usage-log entry. */
private startMode?: string
taskState: TaskState
@@ -488,6 +487,10 @@ export class Task {
}
const mode = this.stateManager.getGlobalSettingsKey("mode")
const currentProvider = mode === "plan" ? apiConfiguration.planModeApiProvider : apiConfiguration.actModeApiProvider
// Remember the provider/mode this task was started with so each finalized
// API request can be attributed in the durable usage log.
this.startProvider = currentProvider
this.startMode = mode
// Now that ulid is initialized, we can build the API handler
this.api = buildApiHandler(effectiveApiConfiguration, mode)
@@ -571,7 +574,7 @@ export class Task {
// awaits remoteWorkspaceDetectionPromise before the first flush is scheduled.
// If it does fire, we fall back to the local cadence (safe default).
Logger.warn(
`[Task ${taskId}] getDelayMs called before remote workspace detection settled — using local cadence as fallback`,
`[Task ${taskId}] getDelayMs called before remote workspace detection settled 鈥?using local cadence as fallback`,
)
}
return getPresentationCadenceMs(this.isRemoteWorkspaceEnvironment, priority)
@@ -1883,23 +1886,23 @@ export class Task {
const preferredLanguageRaw = this.stateManager.getGlobalSettingsKey("preferredLanguage")
const preferredLanguage = getLanguageKey(preferredLanguageRaw as LanguageDisplay)
const languageInstructionMap: Record<string, string> = {
"zh-CN": "Simplified Chinese (简体中文)",
"zh-TW": "Traditional Chinese (繁體中文)",
ja: "Japanese (日本語)",
ko: "Korean (한국어)",
fr: "French (Français)",
"zh-CN": "Simplified Chinese (绠€浣撲腑鏂?",
"zh-TW": "Traditional Chinese (绻侀珨涓枃)",
ja: "Japanese (鏃ユ湰瑾?",
ko: "Korean (頃滉淡鞏?",
fr: "French (Fran莽ais)",
de: "German (Deutsch)",
es: "Spanish (Español)",
"pt-BR": "Brazilian Portuguese (Português Brasileiro)",
"pt-PT": "Portuguese (Português)",
es: "Spanish (Espa帽ol)",
"pt-BR": "Brazilian Portuguese (Portugu锚s Brasileiro)",
"pt-PT": "Portuguese (Portugu锚s)",
it: "Italian (Italiano)",
ru: "Russian (Русский)",
ar: "Arabic (العربية)",
hi: "Hindi (हिन्दी)",
cs: "Czech (Čeština)",
ru: "Russian (袪褍褋褋泻懈泄)",
ar: "Arabic (丕賱毓乇亘賷丞)",
hi: "Hindi (啶灌た啶ㄠ啶︵)",
cs: "Czech (膶e拧tina)",
hu: "Hungarian (Magyar)",
pl: "Polish (Polski)",
tr: "Turkish (Türkçe)",
tr: "Turkish (T眉rk莽e)",
en: "English",
}
const preferredLanguageInstructions =
@@ -2031,7 +2034,7 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
this.taskState.conversationHistoryDeletedRange,
previousApiReqIndex,
await ensureTaskDirectoryExists(this.taskId),
this.stateManager.getGlobalSettingsKey("useAutoCondense") && isNextGenModelFamily(this.api.getModel().id),
this.stateManager.getGlobalSettingsKey("useAutoCondense") && supportsAutoCondense(this.api),
)
if (contextManagementMetadata.updatedConversationHistoryDeletedRange) {
@@ -2041,6 +2044,25 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
}
// Response API requires native tool calls to be enabled
// Strip images from conversation history if the current model does not support vision.
// This prevents API errors when switching from a multimodal model to a text-only model.
const modelSupportsImages = this.api.getModel().info.supportsImages ?? false
if (!modelSupportsImages) {
const { messages: strippedMessages, imagesStripped } = stripImagesFromMessages(
contextManagementMetadata.truncatedConversationHistory,
)
if (imagesStripped) {
contextManagementMetadata.truncatedConversationHistory = strippedMessages
if (!this.taskState.hasNotifiedImageStripping) {
await this.say(
"text",
"⚠️ 已自动移除历史对话中的图片内容,因为当前模型不支持图片输入。如需图片分析,请切换到支持图片的模型。",
)
this.taskState.hasNotifiedImageStripping = true
}
}
}
const stream = this.api.createMessage(systemPrompt, contextManagementMetadata.truncatedConversationHistory, tools)
const iterator = stream[Symbol.asyncIterator]()
@@ -2144,6 +2166,8 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
api: this.api,
cancelReason: "streaming_failed",
streamingFailedMessage,
provider: this.startProvider,
mode: this.startMode,
})
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
await this.postStateToWebview()
@@ -2424,7 +2448,7 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
"mistake_limit_reached",
this.api.getModel().id.includes("claude")
? `This may indicate a failure in Cline's thought process or inability to use a tool properly, which can be mitigated with some user guidance (e.g. "Try breaking down the task into smaller steps").`
: "Cline uses complex prompts and iterative task execution that may be challenging for less capable models. For best results, it's recommended to use Claude 4.5 Sonnet for its advanced agentic coding capabilities.",
: "Cline Multi 检测到当前模型出现了连续错误。请尝试将任务拆分为更小的步骤,或检查模型配置。",
)
if (response === "messageResponse") {
// Display the user's message in the chat UI
@@ -2536,7 +2560,7 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
let shouldCompact = false
const useAutoCondense = this.stateManager.getGlobalSettingsKey("useAutoCondense")
if (useAutoCondense && isNextGenModelFamily(this.api.getModel().id)) {
if (useAutoCondense && supportsAutoCondense(this.api)) {
// When we initially trigger context cleanup, we increase the context window size, so we need state `currentlySummarizing`
// to track if we've already started the context summarization flow. After summarizing, we increment
// conversationHistoryDeletedRange to mask out the summarization-trigger user & assistant response messages
@@ -2583,6 +2607,7 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
this.messageStateHandler.getClineMessages(),
previousApiReqIndex,
await ensureTaskDirectoryExists(this.taskId),
this.stateManager.getGlobalSettingsKey("fileOptimizationThreshold"),
)
}
}
@@ -2629,11 +2654,13 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
if (shouldCompact) {
userContent.push({
type: "text",
text: summarizeTask(
this.stateManager.getGlobalSettingsKey("focusChainSettings"),
this.cwd,
isMultiRootEnabled(this.stateManager),
),
text: (() => {
const ctxWindow = this.api.getModel().info.contextWindow || 128_000
const focusChain = this.stateManager.getGlobalSettingsKey("focusChainSettings")
return ctxWindow < 200_000
? summarizeTaskLite(focusChain, this.cwd)
: summarizeTask(focusChain, this.cwd, isMultiRootEnabled(this.stateManager))
})(),
})
}
@@ -2706,6 +2733,8 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
totalCost: taskMetrics.totalCost,
cancelReason,
streamingFailedMessage,
provider: this.startProvider,
mode: this.startMode,
})
}
@@ -3119,11 +3148,20 @@ Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
}
// Stored the assistant API response immediately after the stream finishes in the same turn
// Check if the stream produced any content — either text or native tool calls.
// Check if the stream produced any content 鈥?either text or native tool calls.
// toolUseHandler may have accumulated tool_use blocks even when useNativeToolCalls is false
// (e.g., from Claude Code provider when the model returns native tool_use blocks).
const hasAccumulatedToolCalls = toolUseHandler.getAllFinalizedToolUses().length > 0
const assistantHasContent = assistantMessage.length > 0 || this.useNativeToolCalls || hasAccumulatedToolCalls
if (assistantMessage.length === 0) {
const reasoningOnly = reasonsHandler.getCurrentReasoning()
if (reasoningOnly?.thinking) {
assistantMessage = reasoningOnly.thinking
}
}
const hasReasoning = !!reasonsHandler.getCurrentReasoning()?.thinking
const assistantHasContent =
assistantMessage.length > 0 || this.useNativeToolCalls || hasAccumulatedToolCalls || hasReasoning
if (assistantHasContent) {
telemetryService.captureConversationTurnEvent(
this.ulid,
+11
View File
@@ -10,6 +10,7 @@ import { getApiMetrics } from "@/shared/getApiMetrics"
import { HistoryItem } from "@/shared/HistoryItem"
import { ClineStorageMessage } from "@/shared/messages/content"
import { Logger } from "@/shared/services/Logger"
import { extractUsageEntries } from "@/shared/usage-stats"
import { getCwd, getDesktopDir } from "@/utils/path"
import { ensureTaskDirectoryExists, saveApiConversationHistory, saveClineMessages } from "../storage/disk"
import { TaskState } from "./TaskState"
@@ -90,6 +91,10 @@ export class MessageStateHandler extends EventEmitter<MessageStateHandlerEvents>
return await this.stateMutex.withLock(fn)
}
getTaskId(): string {
return this.taskId
}
getApiConversationHistory(): ClineStorageMessage[] {
return this.apiConversationHistory
}
@@ -142,6 +147,10 @@ export class MessageStateHandler extends EventEmitter<MessageStateHandlerEvents>
Logger.error("Failed to get task directory size:", taskDir, error)
}
const cwd = await getCwd(getDesktopDir())
const { usageEntries, apiRequestCount } = extractUsageEntries(
combineApiRequests(combineCommandSequences(this.clineMessages.slice(1))),
)
await this.updateTaskHistory({
id: this.taskId,
ulid: this.ulid,
@@ -152,6 +161,8 @@ export class MessageStateHandler extends EventEmitter<MessageStateHandlerEvents>
cacheWrites: apiMetrics.totalCacheWrites,
cacheReads: apiMetrics.totalCacheReads,
totalCost: apiMetrics.totalCost,
apiRequests: apiRequestCount,
usageEntries,
size: taskDirSize,
shadowGitConfigWorkTree: await this.checkpointTracker?.getShadowGitConfigWorkTree(),
cwdOnTaskInitialization: cwd,
+18 -5
View File
@@ -2,12 +2,19 @@ import * as path from "node:path"
import { setTimeout as delay } from "node:timers/promises"
import type { ApiHandler, buildApiHandler } from "@core/api"
import { parseAssistantMessageV2, ToolUse } from "@core/assistant-message"
import { supportsAutoCondense } from "@core/context/context-management/context-window-utils"
import { discoverAvailableSkills } from "@core/context/instructions/user-instructions/skills"
import { formatResponse } from "@core/prompts/responses"
import { PromptRegistry } from "@core/prompts/system-prompt"
import type { SystemPromptContext } from "@core/prompts/system-prompt/types"
import { StreamResponseHandler } from "@core/task/StreamResponseHandler"
import { ClineAssistantToolUseBlock, ClineStorageMessage, ClineTextContentBlock, ClineUserContent } from "@shared/messages"
import {
ClineAssistantToolUseBlock,
ClineStorageMessage,
ClineTextContentBlock,
ClineUserContent,
stripImagesFromMessages,
} from "@shared/messages"
import { Logger } from "@shared/services/Logger"
import { ClineDefaultTool, ClineTool } from "@shared/tools"
import { ContextManager } from "@/core/context/context-management/ContextManager"
@@ -17,7 +24,6 @@ import { HostRegistryInfo } from "@/registry"
import { ClineError, ClineErrorType } from "@/services/error"
import { ApiFormat } from "@/shared/proto/cline/models"
import { calculateApiCostAnthropic } from "@/utils/cost"
import { isNextGenModelFamily } from "@/utils/model-utils"
import { TaskState } from "../../TaskState"
import { ToolExecutorCoordinator } from "../ToolExecutorCoordinator"
import { ToolValidator } from "../ToolValidator"
@@ -810,11 +816,11 @@ export class SubagentRunner {
private shouldCompactBeforeNextRequest(
requestTotalTokens: number,
api: ReturnType<typeof buildApiHandler>,
modelId: string,
_modelId: string,
): boolean {
const { contextWindow, maxAllowedSize } = getContextWindowInfo(api)
const useAutoCondense = this.baseConfig.services.stateManager.getGlobalSettingsKey("useAutoCondense")
if (useAutoCondense && isNextGenModelFamily(modelId)) {
if (useAutoCondense && supportsAutoCondense(api)) {
const autoCondenseThreshold = 0.75
const roundedThreshold = autoCondenseThreshold ? Math.floor(contextWindow * autoCondenseThreshold) : maxAllowedSize
const thresholdTokens = Math.min(roundedThreshold, maxAllowedSize)
@@ -835,9 +841,16 @@ export class SubagentRunner {
contextState: SubagentContextState,
) {
for (let attempt = 1; attempt <= MAX_INITIAL_STREAM_ATTEMPTS; attempt += 1) {
const truncatedConversation = contextManager
let truncatedConversation = contextManager
.getTruncatedMessages(fullConversation, contextState.conversationHistoryDeletedRange)
.map((message) => message as ClineStorageMessage)
// Strip images if model does not support vision
const modelSupportsImages = api.getModel().info.supportsImages ?? false
if (!modelSupportsImages) {
const { messages: strippedMsgs } = stripImagesFromMessages(truncatedConversation)
truncatedConversation = strippedMsgs
}
const stream = api.createMessage(systemPrompt, truncatedConversation, nativeTools)
const iterator = stream[Symbol.asyncIterator]()
+53 -11
View File
@@ -1,8 +1,9 @@
import { ApiHandler } from "@core/api"
import { usageLog } from "@core/storage/usage-log"
import { execSync } from "child_process"
import { showApprovalNotification } from "@/integrations/notifications"
import { ClineApiReqCancelReason, ClineApiReqInfo } from "@/shared/ExtensionMessage"
import { calculateApiCostAnthropic } from "@/utils/cost"
import type { ClineApiReqCancelReason, ClineApiReqInfo } from "@/shared/ExtensionMessage"
import { calculateApiCostBreakdownAnthropic } from "@/utils/cost"
import { MessageStateHandler } from "./message-state"
export const showNotificationForApproval = (message: string, notificationsEnabled: boolean) => {
@@ -20,6 +21,12 @@ type UpdateApiReqMsgParams = {
api: ApiHandler
cancelReason?: ClineApiReqCancelReason
streamingFailedMessage?: string
/** API provider id of the request (e.g. "openai", "openrouter") */
provider?: string
/** "plan" | "act" — the mode the request was made in */
mode?: string
/** Human readable task snippet to attach to the durable usage log */
taskSnippet?: string
}
// update api_req_started. we can't use api_req_finished anymore since it's a unique case where it could come after a streaming message (ie in the middle of being updated or executed)
@@ -30,6 +37,23 @@ export const updateApiReqMsg = async (params: UpdateApiReqMsgParams) => {
const currentApiReqInfo: ClineApiReqInfo = JSON.parse(clineMessages[params.lastApiReqIndex].text || "{}")
delete currentApiReqInfo.retryStatus // Clear retry status when request is finalized
// Compute the per-component cost breakdown (input / cache writes / cache reads / output)
// using the model's four pricing components. When an external totalCost is provided,
// scale the components so they still sum exactly to the recorded total.
const model = params.api.getModel()
const breakdown = calculateApiCostBreakdownAnthropic(
model.info,
params.inputTokens,
params.outputTokens,
params.cacheWriteTokens,
params.cacheReadTokens,
)
const totalCost = params.totalCost ?? breakdown.totalCost
const scale =
breakdown.totalCost > 0 && params.totalCost !== undefined && params.totalCost !== breakdown.totalCost
? params.totalCost / breakdown.totalCost
: 1
await params.messageStateHandler.updateClineMessage(params.lastApiReqIndex, {
text: JSON.stringify({
...currentApiReqInfo, // Spread the modified info (with retryStatus removed)
@@ -37,19 +61,37 @@ export const updateApiReqMsg = async (params: UpdateApiReqMsgParams) => {
tokensOut: params.outputTokens,
cacheWrites: params.cacheWriteTokens,
cacheReads: params.cacheReadTokens,
cost:
params.totalCost ??
calculateApiCostAnthropic(
params.api.getModel().info,
params.inputTokens,
params.outputTokens,
params.cacheWriteTokens,
params.cacheReadTokens,
),
// Record which model served this request so usage stats can attribute tokens/cost per model
modelId: model.id,
cost: totalCost,
inputCost: breakdown.inputCost * scale,
outputCost: breakdown.outputCost * scale,
cacheWritesCost: breakdown.cacheWritesCost * scale,
cacheReadsCost: breakdown.cacheReadsCost * scale,
cancelReason: params.cancelReason,
streamingFailedMessage: params.streamingFailedMessage,
} satisfies ClineApiReqInfo),
})
// Durable per-request usage record — survives task deletion and extension
// reinstalls so usage statistics stay complete and stable over time.
usageLog.append({
ts: Date.now(),
tokensIn: params.inputTokens,
tokensOut: params.outputTokens,
cacheWrites: params.cacheWriteTokens,
cacheReads: params.cacheReadTokens,
cost: totalCost,
inputCost: breakdown.inputCost * scale,
outputCost: breakdown.outputCost * scale,
cacheWritesCost: breakdown.cacheWritesCost * scale,
cacheReadsCost: breakdown.cacheReadsCost * scale,
modelId: model.id,
taskId: params.messageStateHandler.getTaskId(),
provider: params.provider,
mode: params.mode,
taskSnippet: params.taskSnippet,
})
}
/**
+65 -62
View File
@@ -8,68 +8,73 @@ export enum ClineErrorType {
Balance = "balance",
SpendLimit = "spendLimit",
QuotaExceeded = "quotaExceeded",
ModelNotFound = "modelNotFound",
ContentFiltered = "contentFiltered",
ServerError = "serverError",
Timeout = "timeout",
}
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]
const MODEL_NOT_FOUND_PATTERNS = [
/model.{0,20}not found/i,
/model.{0,20}does not exist/i,
/invalid.{0,20}model/i,
/unknown model/i,
/no such model/i,
/404.{0,30}model/i,
]
const CONTENT_FILTERED_PATTERNS = [
/content.{0,20}policy/i,
/content.{0,20}filter/i,
/content.{0,20}violation/i,
/safety.{0,20}block/i,
/blocked.{0,20}content/i,
/harmful/i,
/sensitive.{0,20}content/i,
/moderation/i,
]
const NETWORK_ERROR_PATTERNS = [
/econnrefused/i,
/enotfound/i,
/etimedout/i,
/econnreset/i,
/network.{0,20}error/i,
/socket hang up/i,
/failed to fetch/i,
/request.{0,20}timeout/i,
/timed out/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 || error?.response?.message || String(error) || error?.cause?.means
super(message)
// Extract status from multiple possible locations
const status = error.status || error.statusCode || error.response?.status
this.modelId = modelId || error.modelId
this.providerId = providerId || error.providerId
// Construct the error details object to includes relevant information
// And ensure it has a consistent structure
this._error = {
...error,
message: raw.message || message,
@@ -82,15 +87,11 @@ export class ClineError extends Error {
code: error.code || error?.cause?.code,
modelId: this.modelId,
providerId: this.providerId,
details: error.details || error.error, // Additional details provided by the server
stack: undefined, // Avoid serializing stack trace to keep the error object clean
details: error.details || error.error,
stack: undefined,
}
}
/**
* 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,
@@ -103,9 +104,6 @@ export class ClineError extends Error {
})
}
/**
* Parses a stringified error into a ClineError instance.
*/
static parse(errorStr?: string, modelId?: string): ClineError | undefined {
if (!errorStr || typeof errorStr !== "string") {
return undefined
@@ -113,13 +111,8 @@ export class ClineError extends Error {
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 {
// If already a ClineError, return it directly to prevent infinite recursion
if (error instanceof ClineError) {
return error
}
@@ -133,47 +126,57 @@ export class ClineError extends Error {
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
const message = (err._error?.message || err.message || JSON.stringify(err._error))?.toLowerCase()
// Check balance error first (most specific)
if (code === "insufficient_credits" && typeof details?.current_balance === "number") {
return ClineErrorType.Balance
}
// Check spend limit exceeded (org-enforced budget cap, 429 SPEND_LIMIT_EXCEEDED)
// Must be checked before the generic rate-limit check since both use 429
if (code === "SPEND_LIMIT_EXCEEDED" || details?.code === "SPEND_LIMIT_EXCEEDED") {
return ClineErrorType.SpendLimit
}
// Check auth errors
const isAuthStatus = status !== undefined && status > 400 && status < 429
if (code === "ERR_BAD_REQUEST" || err instanceof AuthInvalidTokenError || isAuthStatus) {
return ClineErrorType.Auth
}
if (code === "INFERENCE_CAP_ERROR") {
return ClineErrorType.QuotaExceeded
}
// Server errors (5xx)
if (status !== undefined && status >= 500 && status < 600) {
return ClineErrorType.ServerError
}
const isAuthStatus = status !== undefined && status >= 400 && status < 429
if (code === "ERR_BAD_REQUEST" || err instanceof AuthInvalidTokenError || isAuthStatus) {
return ClineErrorType.Auth
}
if (message) {
// Check for specific error codes/messages if applicable
const authErrorRegex = [/(?:in)?valid[-_ ]?(?:api )?(?:token|key)/i, /authentication[-_ ]?failed/i, /unauthorized/i]
if (message?.includes(CLINE_ACCOUNT_AUTH_ERROR_MESSAGE) || authErrorRegex.some((regex) => regex.test(message))) {
return ClineErrorType.Auth
}
// Check rate limit patterns
const lowerMessage = message.toLowerCase()
if (RATE_LIMIT_PATTERNS.some((pattern) => pattern.test(lowerMessage))) {
if (RATE_LIMIT_PATTERNS.some((pattern) => pattern.test(message))) {
return ClineErrorType.RateLimit
}
if (MODEL_NOT_FOUND_PATTERNS.some((pattern) => pattern.test(message))) {
return ClineErrorType.ModelNotFound
}
if (CONTENT_FILTERED_PATTERNS.some((pattern) => pattern.test(message))) {
return ClineErrorType.ContentFiltered
}
if (NETWORK_ERROR_PATTERNS.some((pattern) => pattern.test(message))) {
return ClineErrorType.Network
}
if (status === 408 || /timeout/i.test(message)) {
return ClineErrorType.Timeout
}
}
return undefined
+7
View File
@@ -349,6 +349,13 @@ export interface ClineApiReqInfo {
cacheWrites?: number
cacheReads?: number
cost?: number
/** Cost breakdown by pricing component (input / cache writes / cache reads / output) */
inputCost?: number
outputCost?: number
cacheWritesCost?: number
cacheReadsCost?: number
/** Model that served this API request (used for accurate per-model usage stats) */
modelId?: string
cancelReason?: ClineApiReqCancelReason
streamingFailedMessage?: string
retryStatus?: {
+7
View File
@@ -1,3 +1,5 @@
import type { UsageEntry } from "./usage-stats"
export type HistoryItem = {
id: string
ulid?: string // ULID for better tracking and metrics
@@ -17,4 +19,9 @@ export type HistoryItem = {
checkpointManagerErrorMessage?: string
modelId?: string
/** Number of API requests made in this task (accurate request count, not task count) */
apiRequests?: number
/** Per-request usage details captured while the task ran (tokens/cost/model per request) */
usageEntries?: UsageEntry[]
}
+531
View File
@@ -0,0 +1,531 @@
import { strict as assert } from "node:assert"
import fsSync from "node:fs"
import os from "node:os"
import path from "node:path"
import { describe, it } from "mocha"
import type { ClineMessage } from "../ExtensionMessage"
import type { HistoryItem } from "../HistoryItem"
import {
aggregateUsageEntries,
aggregateUsageStats,
extractUsageEntries,
getTimeRangeCutoff,
normalizeUsageEntries,
type UsageLogEntry,
} from "../usage-stats"
function makeHistoryItem(overrides: Partial<HistoryItem> = {}): HistoryItem {
return {
id: "task-1",
ts: Date.now(),
task: "test task",
tokensIn: 0,
tokensOut: 0,
totalCost: 0,
...overrides,
}
}
function makeApiReqMessage(overrides: {
ts?: number
tokensIn?: number
tokensOut?: number
cacheWrites?: number
cacheReads?: number
cost?: number
modelId?: string
}): ClineMessage {
const { ts = Date.now(), ...data } = overrides
return {
ts,
type: "say",
say: "api_req_started",
text: JSON.stringify(data),
}
}
describe("extractUsageEntries", () => {
it("collects finalized api_req_started messages with modelId", () => {
const messages: ClineMessage[] = [
makeApiReqMessage({ ts: 1000, tokensIn: 10, tokensOut: 20, cost: 0.5, modelId: "model-a" }),
makeApiReqMessage({ ts: 2000, tokensIn: 5, tokensOut: 8, cost: 0.25, modelId: "model-b" }),
// placeholder message without usage data should be counted as request but produce no entry
{ ts: 3000, type: "say", say: "api_req_started", text: JSON.stringify({ request: "hi" }) },
]
const { usageEntries, apiRequestCount } = extractUsageEntries(messages)
assert.equal(apiRequestCount, 3)
assert.equal(usageEntries.length, 2)
assert.equal(usageEntries[0].modelId, "model-a")
assert.equal(usageEntries[0].tokensIn, 10)
assert.equal(usageEntries[1].modelId, "model-b")
})
it("collects per-component cost breakdown from api_req_started", () => {
const messages: ClineMessage[] = [
{
ts: 1000,
type: "say",
say: "api_req_started",
text: JSON.stringify({
tokensIn: 100,
tokensOut: 50,
cacheWrites: 20,
cacheReads: 30,
cost: 0.9,
inputCost: 0.3,
outputCost: 0.4,
cacheWritesCost: 0.15,
cacheReadsCost: 0.05,
modelId: "model-a",
}),
},
]
const { usageEntries } = extractUsageEntries(messages)
assert.equal(usageEntries.length, 1)
assert.equal(usageEntries[0].inputCost, 0.3)
assert.equal(usageEntries[0].outputCost, 0.4)
assert.equal(usageEntries[0].cacheWritesCost, 0.15)
assert.equal(usageEntries[0].cacheReadsCost, 0.05)
})
it("includes deleted_api_reqs and subagent_usage snapshots", () => {
const messages: ClineMessage[] = [
{
ts: 1000,
type: "say",
say: "deleted_api_reqs",
text: JSON.stringify({ tokensIn: 100, tokensOut: 50, cost: 1 }),
},
{
ts: 2000,
type: "say",
say: "subagent_usage",
text: JSON.stringify({ source: "subagents", tokensIn: 20, tokensOut: 10, cost: 0.5 }),
},
]
const { usageEntries, apiRequestCount } = extractUsageEntries(messages)
assert.equal(apiRequestCount, 0)
assert.equal(usageEntries.length, 2)
assert.equal(usageEntries[0].tokensIn, 100)
assert.equal(usageEntries[1].tokensIn, 20)
})
it("ignores malformed payloads", () => {
const messages: ClineMessage[] = [
{ ts: 1000, type: "say", say: "api_req_started", text: "not-json" },
{ ts: 2000, type: "say", say: "api_req_started", text: JSON.stringify({ tokensIn: "oops" }) },
]
const { usageEntries, apiRequestCount } = extractUsageEntries(messages)
assert.equal(apiRequestCount, 2)
assert.equal(usageEntries.length, 0)
})
})
describe("normalizeUsageEntries", () => {
it("prefers per-request usageEntries when present", () => {
const item = makeHistoryItem({
tokensIn: 999,
tokensOut: 999,
totalCost: 9,
usageEntries: [
{ ts: 1, tokensIn: 1, tokensOut: 2, cacheWrites: 0, cacheReads: 0, cost: 0.1 },
{ ts: 2, tokensIn: 3, tokensOut: 4, cacheWrites: 0, cacheReads: 0, cost: 0.2 },
],
})
const entries = normalizeUsageEntries(item)
assert.equal(entries.length, 2)
assert.equal(entries[0].tokensIn, 1)
})
it("falls back to task-level totals for legacy items", () => {
const item = makeHistoryItem({ tokensIn: 10, tokensOut: 20, totalCost: 0.5, modelId: "model-a" })
const entries = normalizeUsageEntries(item)
assert.equal(entries.length, 1)
assert.equal(entries[0].tokensIn, 10)
assert.equal(entries[0].modelId, "model-a")
})
it("returns empty for items without usage", () => {
const entries = normalizeUsageEntries(makeHistoryItem({}))
assert.equal(entries.length, 0)
})
})
describe("getTimeRangeCutoff", () => {
it("today starts at local midnight", () => {
const now = new Date(2026, 8, 12, 15, 30).getTime() // Sep 12 2026 15:30 local
const cutoff = getTimeRangeCutoff("today", now)
assert.equal(cutoff, new Date(2026, 8, 12, 0, 0, 0, 0).getTime())
})
it("all covers everything", () => {
assert.equal(getTimeRangeCutoff("all", Date.now()), 0)
})
})
describe("aggregateUsageStats", () => {
it("aggregates across the full history with per-model attribution", () => {
const now = Date.now()
const items: HistoryItem[] = [
makeHistoryItem({
id: "task-1",
ts: now - 1000,
usageEntries: [
{
ts: now - 1000,
tokensIn: 100,
tokensOut: 200,
cacheWrites: 10,
cacheReads: 30,
cost: 1,
modelId: "model-a",
},
{ ts: now - 500, tokensIn: 50, tokensOut: 25, cacheWrites: 5, cacheReads: 15, cost: 0.5, modelId: "model-b" },
],
}),
makeHistoryItem({
id: "task-2",
ts: now - 2000,
// legacy item without usageEntries
tokensIn: 10,
tokensOut: 20,
totalCost: 0.1,
modelId: "model-a",
}),
]
const result = aggregateUsageStats(items, "all", now)
assert.equal(result.totals.requests, 3)
assert.equal(result.totals.tasks, 2)
assert.equal(result.totals.tokensIn, 160)
assert.equal(result.totals.tokensOut, 245)
assert.deepEqual(result.totals.cost, 1.6)
const modelA = result.modelStats.get("model-a")!
assert.equal(modelA.requests, 2)
assert.equal(modelA.tokensIn, 110)
const modelB = result.modelStats.get("model-b")!
assert.equal(modelB.requests, 1)
assert.equal(modelB.tokensOut, 25)
})
it("aggregates the four-component cost breakdown across tasks and models", () => {
const now = Date.now()
const items: HistoryItem[] = [
makeHistoryItem({
id: "task-1",
ts: now,
usageEntries: [
{
ts: now,
tokensIn: 100,
tokensOut: 50,
cacheWrites: 20,
cacheReads: 30,
cost: 0.9,
inputCost: 0.3,
outputCost: 0.4,
cacheWritesCost: 0.15,
cacheReadsCost: 0.05,
modelId: "model-a",
},
],
}),
makeHistoryItem({
id: "task-2",
ts: now - 1000,
usageEntries: [
{
ts: now - 1000,
tokensIn: 10,
tokensOut: 5,
cacheWrites: 2,
cacheReads: 3,
cost: 0.1,
inputCost: 0.04,
outputCost: 0.04,
cacheWritesCost: 0.01,
cacheReadsCost: 0.01,
modelId: "model-b",
},
],
}),
]
const result = aggregateUsageStats(items, "all", now)
assert.deepEqual(result.totals.inputCost, 0.34)
assert.deepEqual(result.totals.outputCost, 0.44)
assert.deepEqual(result.totals.cacheWritesCost, 0.16)
assert.deepEqual(result.totals.cacheReadsCost, 0.06)
const modelA = result.modelStats.get("model-a")!
assert.equal(modelA.inputCost, 0.3)
assert.equal(modelA.outputCost, 0.4)
assert.equal(modelA.cacheWritesCost, 0.15)
assert.equal(modelA.cacheReadsCost, 0.05)
// trend buckets carry the breakdown too
const todayBucket = result.trend[result.trend.length - 1]
assert.deepEqual(todayBucket.inputCost, 0.34)
assert.deepEqual(todayBucket.cacheReadsCost, 0.06)
})
it("respects the time range cutoff", () => {
const now = Date.now()
const old = now - 10 * 24 * 60 * 60 * 1000 // 10 days ago
const items: HistoryItem[] = [
makeHistoryItem({
id: "old-task",
ts: old,
usageEntries: [{ ts: old, tokensIn: 1000, tokensOut: 1000, cacheWrites: 0, cacheReads: 0, cost: 5 }],
}),
makeHistoryItem({
id: "new-task",
ts: now,
usageEntries: [{ ts: now, tokensIn: 1, tokensOut: 2, cacheWrites: 0, cacheReads: 0, cost: 0.01 }],
}),
]
const weekResult = aggregateUsageStats(items, "week", now)
assert.equal(weekResult.totals.requests, 1)
assert.equal(weekResult.totals.tokensIn, 1)
const allResult = aggregateUsageStats(items, "all", now)
assert.equal(allResult.totals.requests, 2)
})
it("zero-fills calendar buckets so the trend aligns to dates", () => {
const now = new Date(2026, 8, 12, 18, 0).getTime() // Sep 12 2026 18:00 local
const threeDaysAgo = new Date(2026, 8, 9, 10, 0).getTime()
const items: HistoryItem[] = [
makeHistoryItem({
id: "task-1",
ts: threeDaysAgo,
usageEntries: [{ ts: threeDaysAgo, tokensIn: 10, tokensOut: 5, cacheWrites: 0, cacheReads: 0, cost: 0.1 }],
}),
makeHistoryItem({
id: "task-2",
ts: now,
usageEntries: [{ ts: now, tokensIn: 20, tokensOut: 8, cacheWrites: 0, cacheReads: 0, cost: 0.2 }],
}),
]
const result = aggregateUsageStats(items, "week", now)
// Sep 6..12 => 7 day buckets
assert.equal(result.trend.length, 7)
assert.equal(result.trend[0].label, "9/6")
assert.equal(result.trend[6].label, "9/12")
// gap days are zero-filled; Sep 9 is index 3 (Sep 6 is index 0)
assert.equal(result.trend[1].tokensIn, 0)
assert.equal(result.trend[2].tokensIn, 0)
assert.equal(result.trend[3].tokensIn, 10) // Sep 9 has usage
assert.equal(result.trend[6].tokensIn, 20) // today
})
it("today view buckets usage by hour across the whole day", () => {
const now = new Date(2026, 8, 12, 18, 30).getTime()
const morning = new Date(2026, 8, 12, 8, 15).getTime()
const items: HistoryItem[] = [
makeHistoryItem({
id: "task-1",
ts: morning,
usageEntries: [{ ts: morning, tokensIn: 10, tokensOut: 5, cacheWrites: 0, cacheReads: 0, cost: 0.1 }],
}),
makeHistoryItem({
id: "task-2",
ts: now,
usageEntries: [{ ts: now, tokensIn: 20, tokensOut: 8, cacheWrites: 0, cacheReads: 0, cost: 0.2 }],
}),
]
const result = aggregateUsageStats(items, "today", now)
assert.equal(result.trend.length, 24)
assert.equal(result.trend[8].tokensIn, 10)
assert.equal(result.trend[18].tokensIn, 20)
assert.equal(result.trend[0].tokensIn, 0)
})
it("counts tasks with usage data even when task text is empty", () => {
const now = Date.now()
const items: HistoryItem[] = [
makeHistoryItem({
id: "image-task",
ts: now,
task: "", // e.g. images-only task; previously filtered out of stats
usageEntries: [{ ts: now, tokensIn: 5, tokensOut: 5, cacheWrites: 0, cacheReads: 0, cost: 0.01 }],
}),
]
const result = aggregateUsageStats(items, "all", now)
assert.equal(result.totals.tasks, 1)
assert.equal(result.totals.requests, 1)
assert.equal(result.totals.tokensIn, 5)
})
})
function makeLogEntry(overrides: Partial<UsageLogEntry> = {}): UsageLogEntry {
return {
ts: Date.now(),
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
cost: 0,
...overrides,
}
}
describe("aggregateUsageEntries", () => {
it("aggregates log entries with per-model attribution and task dedup", () => {
const now = Date.now()
const entries: UsageLogEntry[] = [
makeLogEntry({
ts: now - 2000,
tokensIn: 100,
tokensOut: 50,
cacheWrites: 10,
cacheReads: 20,
cost: 0.5,
inputCost: 0.2,
outputCost: 0.2,
cacheWritesCost: 0.05,
cacheReadsCost: 0.05,
modelId: "model-a",
taskId: "task-1",
}),
makeLogEntry({
ts: now - 1000,
tokensIn: 30,
tokensOut: 20,
cost: 0.2,
modelId: "model-a",
taskId: "task-1", // same task — deduped in task count
}),
makeLogEntry({
ts: now,
tokensIn: 10,
tokensOut: 5,
cost: 0.1,
modelId: "model-b",
taskId: "task-2",
}),
]
const result = aggregateUsageEntries(entries, "all", now)
assert.equal(result.totals.requests, 3)
assert.equal(result.totals.tasks, 2) // task-1 counted once despite 2 entries
assert.equal(result.totals.tokensIn, 140)
assert.equal(result.totals.tokensOut, 75)
assert.deepEqual(result.totals.cost, 0.8)
assert.deepEqual(result.totals.cacheWrites, 10)
assert.deepEqual(result.totals.cacheReads, 20)
const modelA = result.modelStats.get("model-a")!
assert.equal(modelA.requests, 2)
assert.equal(modelA.tokensIn, 130)
assert.equal(modelA.tokensOut, 70)
const modelB = result.modelStats.get("model-b")!
assert.equal(modelB.requests, 1)
assert.equal(modelB.tokensIn, 10)
// trend carries the same totals
const totalTrendTokensIn = result.trend.reduce((sum, bucket) => sum + bucket.tokensIn, 0)
assert.equal(totalTrendTokensIn, 140)
})
it("entries without taskId still count as requests and one task", () => {
const now = Date.now()
const entries: UsageLogEntry[] = [makeLogEntry({ ts: now, tokensIn: 5, tokensOut: 5, cost: 0.01, modelId: "model-a" })]
const result = aggregateUsageEntries(entries, "all", now)
assert.equal(result.totals.requests, 1)
assert.equal(result.totals.tasks, 1)
})
it("respects the time range cutoff", () => {
const now = Date.now()
const old = now - 10 * 24 * 60 * 60 * 1000 // 10 days ago
const entries: UsageLogEntry[] = [
makeLogEntry({ ts: old, tokensIn: 1000, tokensOut: 1000, cost: 5, modelId: "model-a", taskId: "old" }),
makeLogEntry({ ts: now, tokensIn: 1, tokensOut: 2, cost: 0.01, modelId: "model-a", taskId: "new" }),
]
const weekResult = aggregateUsageEntries(entries, "week", now)
assert.equal(weekResult.totals.requests, 1)
assert.equal(weekResult.totals.tokensIn, 1)
const allResult = aggregateUsageEntries(entries, "all", now)
assert.equal(allResult.totals.requests, 2)
})
})
describe("UsageLog", () => {
it("persists entries to disk and reads them back", async () => {
const { UsageLog } = await import("../../core/storage/usage-log")
const dir = fsSync.mkdtempSync(path.join(os.tmpdir(), "cline-usage-log-"))
try {
const log = new UsageLog()
log.setFilePath(path.join(dir, "usage-log.jsonl"))
log.append(makeLogEntry({ ts: 1000, tokensIn: 10, tokensOut: 20, cost: 0.5, modelId: "model-a", taskId: "t1" }))
log.append(makeLogEntry({ ts: 2000, tokensIn: 5, tokensOut: 8, cost: 0.25, modelId: "model-b", taskId: "t2" }))
// readAll flushes pending writes first
const entries = log.readAll()
assert.equal(entries.length, 2)
assert.equal(entries[0].modelId, "model-a")
assert.equal(entries[0].tokensIn, 10)
assert.equal(entries[1].modelId, "model-b")
// entries survive re-reading with a fresh instance (durable on disk)
const log2 = new UsageLog()
log2.setFilePath(path.join(dir, "usage-log.jsonl"))
assert.equal(log2.readAll().length, 2)
} finally {
fsSync.rmSync(dir, { recursive: true, force: true })
}
})
it("tolerates torn lines and missing files", async () => {
const { UsageLog } = await import("../../core/storage/usage-log")
const dir = fsSync.mkdtempSync(path.join(os.tmpdir(), "cline-usage-log-"))
try {
const log = new UsageLog()
const filePath = path.join(dir, "usage-log.jsonl")
// missing file reads as empty
log.setFilePath(filePath)
assert.equal(log.readAll().length, 0)
// torn line is skipped, valid lines are kept
const valid = JSON.stringify(makeLogEntry({ ts: 3000, tokensIn: 1, tokensOut: 2, cost: 0.01 }))
fsSync.writeFileSync(filePath, `{"ts":1000,"tokensIn":\n${valid}\n`, "utf8")
const entries = log.readAll()
assert.equal(entries.length, 1)
assert.equal(entries[0].ts, 3000)
} finally {
fsSync.rmSync(dir, { recursive: true, force: true })
}
})
})
+878 -3
View File
@@ -162,10 +162,79 @@ export const hicapModelInfoSaneDefaults: HicapCompatibleModelInfo = {
// Anthropic
// https://docs.anthropic.com/en/docs/about-claude/models // prices updated 2025-01-02
export type AnthropicModelId = keyof typeof anthropicModels
export const anthropicDefaultModelId: AnthropicModelId = "claude-sonnet-4-5-20250929"
export const anthropicDefaultModelId: AnthropicModelId = "claude-sonnet-5"
export const ANTHROPIC_MIN_THINKING_BUDGET = 1_024
export const ANTHROPIC_MAX_THINKING_BUDGET = 6_000
export const anthropicModels = {
"claude-opus-5": {
maxTokens: 128_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 5.0,
outputPrice: 25.0,
cacheWritesPrice: 6.25,
cacheReadsPrice: 0.5,
},
"claude-opus-5:1m": {
maxTokens: 128_000,
contextWindow: 1_000_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 5.0,
outputPrice: 25.0,
cacheWritesPrice: 6.25,
cacheReadsPrice: 0.5,
tiers: CLAUDE_OPUS_1M_TIERS,
},
"claude-sonnet-5": {
maxTokens: 64_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
},
"claude-sonnet-5:1m": {
maxTokens: 64_000,
contextWindow: 1_000_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
tiers: CLAUDE_SONNET_1M_TIERS,
},
"claude-fable-5": {
maxTokens: 64_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
},
"claude-mythos-5": {
maxTokens: 128_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 10.0,
outputPrice: 50.0,
cacheWritesPrice: 12.5,
cacheReadsPrice: 1.0,
description: "Claude Mythos 5 - most capable model for complex tasks",
},
"claude-sonnet-4-6": {
maxTokens: 64_000,
contextWindow: 200_000,
@@ -431,13 +500,33 @@ export const anthropicModels = {
// Claude Code
export type ClaudeCodeModelId = keyof typeof claudeCodeModels
export const claudeCodeDefaultModelId: ClaudeCodeModelId = "claude-sonnet-4-5-20250929"
export const claudeCodeDefaultModelId: ClaudeCodeModelId = "claude-sonnet-5"
export const claudeCodeModels = {
sonnet: {
...anthropicModels["claude-sonnet-4-5-20250929"],
supportsImages: false,
supportsPromptCache: false,
},
"claude-opus-5": {
...anthropicModels["claude-opus-5"],
supportsImages: false,
supportsPromptCache: false,
},
"claude-sonnet-5": {
...anthropicModels["claude-sonnet-5"],
supportsImages: false,
supportsPromptCache: false,
},
"claude-fable-5": {
...anthropicModels["claude-fable-5"],
supportsImages: false,
supportsPromptCache: false,
},
"claude-mythos-5": {
...anthropicModels["claude-mythos-5"],
supportsImages: false,
supportsPromptCache: false,
},
"sonnet[1m]": {
...anthropicModels["claude-sonnet-4-5-20250929:1m"],
supportsImages: false,
@@ -548,6 +637,54 @@ export const claudeCodeModels = {
export type BedrockModelId = keyof typeof bedrockModels
export const bedrockDefaultModelId: BedrockModelId = "anthropic.claude-sonnet-4-5-20250929-v1:0"
export const bedrockModels = {
"anthropic.claude-opus-5": {
maxTokens: 128_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
supportsGlobalEndpoint: true,
inputPrice: 5.0,
outputPrice: 25.0,
cacheWritesPrice: 6.25,
cacheReadsPrice: 0.5,
},
"anthropic.claude-sonnet-5": {
maxTokens: 64_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
supportsGlobalEndpoint: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
},
"anthropic.claude-fable-5": {
maxTokens: 64_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
supportsGlobalEndpoint: true,
inputPrice: 3.0,
outputPrice: 15.0,
cacheWritesPrice: 3.75,
cacheReadsPrice: 0.3,
},
"anthropic.claude-mythos-5": {
maxTokens: 128_000,
contextWindow: 200_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
supportsGlobalEndpoint: true,
inputPrice: 10.0,
outputPrice: 50.0,
cacheWritesPrice: 12.5,
cacheReadsPrice: 1.0,
},
"anthropic.claude-sonnet-4-6": {
maxTokens: 64_000,
contextWindow: 200_000,
@@ -1039,6 +1176,49 @@ export const OPENROUTER_PROVIDER_PREFERENCES: Record<string, { order: string[];
export type VertexModelId = keyof typeof vertexModels
export const vertexDefaultModelId: VertexModelId = "gemini-3-pro-preview"
export const vertexModels = {
"gemini-3.7-flash": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.15,
outputPrice: 0.6,
cacheReadsPrice: 0.015,
supportsReasoning: true,
thinkingConfig: {
geminiThinkingLevel: "low",
supportsThinkingLevel: true,
},
description: "Latest Gemini 3.7 Flash - fast and efficient",
},
"gemini-3.6-flash": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.15,
outputPrice: 0.6,
cacheReadsPrice: 0.015,
supportsReasoning: true,
thinkingConfig: {
geminiThinkingLevel: "low",
supportsThinkingLevel: true,
},
},
"gemini-3.5-flash-lite": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.075,
outputPrice: 0.3,
cacheReadsPrice: 0.0075,
supportsReasoning: true,
thinkingConfig: {
geminiThinkingLevel: "low",
supportsThinkingLevel: true,
},
},
"gemini-3.5-flash": {
maxTokens: 65536,
contextWindow: 1_048_576,
@@ -1055,6 +1235,50 @@ export const vertexModels = {
supportsThinkingLevel: true,
},
},
"gemini-3.1-pro": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 2.0,
outputPrice: 12.0,
cacheReadsPrice: 0.2,
supportsReasoning: true,
thinkingConfig: {
geminiThinkingLevel: "high",
supportsThinkingLevel: true,
},
tiers: [
{
contextWindow: 200000,
inputPrice: 1.25,
outputPrice: 10,
cacheReadsPrice: 0.125,
},
{
contextWindow: Number.POSITIVE_INFINITY,
inputPrice: 2.5,
outputPrice: 15,
cacheReadsPrice: 0.25,
},
],
description: "Gemini 3.1 Pro - GA release, latest pro model",
},
"gemini-3.1-flash-lite": {
maxTokens: 65536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.075,
outputPrice: 0.3,
cacheReadsPrice: 0.0075,
supportsReasoning: true,
thinkingConfig: {
geminiThinkingLevel: "low",
supportsThinkingLevel: true,
},
description: "Gemini 3.1 Flash Lite - GA release, cost-effective",
},
"gemini-3.1-pro-preview": {
maxTokens: 8192,
contextWindow: 1_048_576,
@@ -1840,6 +2064,153 @@ export const geminiModels = {
export type OpenAiNativeModelId = keyof typeof openAiNativeModels
export const openAiNativeDefaultModelId: OpenAiNativeModelId = "gpt-5.5"
export const openAiNativeModels = {
"gpt-5.6-sol": {
maxTokens: 16_384,
contextWindow: 256_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 10.0,
outputPrice: 40.0,
cacheReadsPrice: 1.0,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.6 Sol - Latest frontier agentic coding model",
},
"gpt-5.6-terra": {
maxTokens: 16_384,
contextWindow: 256_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 7.0,
outputPrice: 28.0,
cacheReadsPrice: 0.7,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.6 Terra - Balanced agentic coding model",
},
"gpt-5.6-luna": {
maxTokens: 16_384,
contextWindow: 128_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 3.0,
outputPrice: 12.0,
cacheReadsPrice: 0.3,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.6 Luna - Fast and affordable agentic model",
},
"gpt-5.6-sol-pro": {
maxTokens: 16_384,
contextWindow: 1_050_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 2.0,
outputPrice: 8.0,
cacheReadsPrice: 0.2,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.6 Sol Pro - pro tier agentic coding model",
},
"gpt-5.6-terra-pro": {
maxTokens: 16_384,
contextWindow: 1_050_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 2.0,
outputPrice: 8.0,
cacheReadsPrice: 0.2,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.6 Terra Pro - pro tier balanced model",
},
"gpt-5.6-luna-pro": {
maxTokens: 16_384,
contextWindow: 1_050_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.2,
outputPrice: 0.8,
cacheReadsPrice: 0.02,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.6 Luna Pro - pro tier fast and affordable",
},
"gpt-5.4-pro": {
maxTokens: 16_384,
contextWindow: 1_050_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 30.0,
outputPrice: 60.0,
cacheReadsPrice: 3.0,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.4 Pro - pro tier for complex tasks",
},
"gpt-5.5-pro": {
maxTokens: 16_384,
contextWindow: 1_050_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 15.0,
outputPrice: 60.0,
cacheReadsPrice: 1.5,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.5 Pro - Pro tier for complex tasks (Responses-only)",
},
"gpt-5.2-pro": {
maxTokens: 16_384,
contextWindow: 272_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 5.0,
outputPrice: 30.0,
cacheReadsPrice: 0.5,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
supportsReasoning: true,
supportsReasoningEffort: true,
description: "GPT-5.2 Pro - Pro tier for complex tasks",
},
"gpt-5.1-mini": {
maxTokens: 16_384,
contextWindow: 272_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 0.4,
outputPrice: 1.6,
cacheReadsPrice: 0.04,
apiFormat: ApiFormat.OPENAI_RESPONSES,
temperature: 1,
systemRole: "developer",
},
"gpt-5.5": {
maxTokens: 8_192,
contextWindow: 1_050_000,
@@ -2325,11 +2696,65 @@ export const deepSeekModels = {
supportsImages: false,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 0, // all input is either a cache hit or miss
inputPrice: 0,
outputPrice: 0.87,
cacheWritesPrice: 0.435,
cacheReadsPrice: 0.003625,
},
"deepseek-v4-flash-vision-exp": {
maxTokens: 384_000,
contextWindow: 1_000_000,
supportsImages: true,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 0,
outputPrice: 0.28,
cacheWritesPrice: 0.14,
cacheReadsPrice: 0.0028,
description: "DeepSeek V4 Flash with vision/image support",
},
"deepseek-v4-flash-0731": {
maxTokens: 384_000,
contextWindow: 1_310_720,
supportsImages: false,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 0,
outputPrice: 0.14,
cacheWritesPrice: 0.07,
cacheReadsPrice: 0.0014,
description: "DeepSeek V4 Flash 0731 - 1.3M context, latest fast model",
},
"deepseek-v3.2": {
maxTokens: 16_384,
contextWindow: 163_840,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 0,
outputPrice: 0.56,
cacheWritesPrice: 0.14,
cacheReadsPrice: 0.035,
},
"deepseek-v3.1-terminus": {
maxTokens: 16_384,
contextWindow: 163_840,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 0,
outputPrice: 0.56,
cacheWritesPrice: 0.14,
cacheReadsPrice: 0.035,
},
"deepseek-chat-v3.1": {
maxTokens: 16_384,
contextWindow: 163_840,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 0,
outputPrice: 1.1,
cacheWritesPrice: 0.27,
cacheReadsPrice: 0.07,
},
"deepseek-chat": {
maxTokens: 8_000,
contextWindow: 128_000,
@@ -2444,6 +2869,104 @@ export const huggingFaceModels = {
// https://bailian.console.aliyun.com/
// The first model in the list is used as the default model for each region
export const internationalQwenModels = {
"qwen3.8-max": {
maxTokens: 65_536,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 2,
outputPrice: 10,
supportsReasoning: true,
thinkingConfig: { maxBudget: 38_912, outputPrice: 20 },
description: "Qwen3.8 Max - latest flagship reasoning model",
},
"qwen3.8-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
supportsReasoning: true,
thinkingConfig: { maxBudget: 38_912, outputPrice: 5 },
description: "Qwen3.8 Flash - 1M context, fast + affordable",
},
"qwen3.7-max": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1.5,
outputPrice: 7,
supportsReasoning: true,
thinkingConfig: { maxBudget: 38_912, outputPrice: 15 },
},
"qwen3.7-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1,
outputPrice: 5,
},
"qwen3.7-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
},
"qwen3.6-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1,
outputPrice: 5,
},
"qwen3.6-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
},
"qwen3.5-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1,
outputPrice: 5,
},
"qwen3.5-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
},
"qwen3-coder-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
description: "Qwen3 Coder Flash - fast coding model, 1M context",
},
"qwen3-coder-next": {
maxTokens: 65_536,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1.5,
outputPrice: 7.5,
description: "Qwen3 Coder Next - next-gen open coder (480B MoE)",
},
"qwen3-coder-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
@@ -3142,6 +3665,56 @@ export const mainlandQwenDefaultModelId: MainlandQwenModelId = Object.keys(mainl
export type DoubaoModelId = keyof typeof doubaoModels
export const doubaoDefaultModelId: DoubaoModelId = "doubao-1-5-pro-256k-250115"
export const doubaoModels = {
"seed-2-1-turbo": {
maxTokens: 32_768,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2.0,
description: "Seed 2.1 Turbo - ByteDance latest fast model",
},
"seed-2.0-code": {
maxTokens: 32_768,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2.0,
description: "Seed 2.0 Code - coding specialist",
},
"seed-2.0-lite": {
maxTokens: 32_768,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.25,
outputPrice: 1.0,
},
"seed-2.0-mini": {
maxTokens: 32_768,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.1,
outputPrice: 0.4,
},
"seed-1.6-flash": {
maxTokens: 32_768,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.08,
outputPrice: 0.32,
},
"seed-1.6": {
maxTokens: 32_768,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.25,
outputPrice: 1.0,
},
"doubao-1-5-pro-256k-250115": {
maxTokens: 12_288,
contextWindow: 256_000,
@@ -3819,6 +4392,53 @@ export const wandbDefaultModelId = "meta-llama/Llama-3.3-70B-Instruct" satisfies
export type XAIModelId = keyof typeof xaiModels
export const xaiDefaultModelId: XAIModelId = "grok-4"
export const xaiModels = {
"grok-4.20": {
maxTokens: 131_072,
contextWindow: 2_000_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 1.25,
outputPrice: 5.0,
cacheReadsPrice: 0.125,
description: "Grok 4.20 - latest flagship, 2M context",
},
"grok-4.20-multi-agent": {
maxTokens: 131_072,
contextWindow: 2_000_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 1.25,
outputPrice: 5.0,
cacheReadsPrice: 0.125,
description: "Grok 4.20 Multi-Agent - optimized for multi-agent workflows",
},
"grok-4.6": {
maxTokens: 131_072,
contextWindow: 500_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 2.0,
outputPrice: 8.0,
cacheReadsPrice: 0.2,
},
"grok-4.5": {
maxTokens: 131_072,
contextWindow: 500_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 2.0,
outputPrice: 8.0,
cacheReadsPrice: 0.2,
},
"grok-4.3": {
maxTokens: 131_072,
contextWindow: 1_000_000,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 1.25,
outputPrice: 5.0,
cacheReadsPrice: 0.125,
},
"grok-4-1-fast-reasoning": {
contextWindow: 2_000_000,
supportsImages: false,
@@ -4611,6 +5231,28 @@ export const sapAiCoreModels = {
// Moonshot AI Studio
// https://platform.moonshot.ai/docs/pricing/chat
export const moonshotModels = {
"kimi-k3": {
maxTokens: 65_536,
contextWindow: 1_048_576,
supportsImages: true,
supportsPromptCache: true,
inputPrice: 1.2,
outputPrice: 5.0,
cacheReadsPrice: 0.2,
temperature: 1.0,
description: "Kimi K3 - Moonshot AI latest flagship model, 1M context",
},
"kimi-k2.7-code": {
maxTokens: 32_000,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: true,
inputPrice: 0.6,
outputPrice: 2.5,
cacheReadsPrice: 0.1,
temperature: 0.6,
description: "Kimi K2.7 Code - coding specialist model",
},
"kimi-k2.6": {
maxTokens: 32_000,
contextWindow: 262_144,
@@ -4724,6 +5366,104 @@ export const huaweiCloudMaasModels = {
outputPrice: 2.2,
},
},
"qwen3.8-max": {
maxTokens: 65_536,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 2,
outputPrice: 10,
supportsReasoning: true,
thinkingConfig: { maxBudget: 38_912, outputPrice: 20 },
description: "Qwen3.8 Max - latest flagship reasoning model",
},
"qwen3.8-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
supportsReasoning: true,
thinkingConfig: { maxBudget: 38_912, outputPrice: 5 },
description: "Qwen3.8 Flash - 1M context, fast + affordable",
},
"qwen3.7-max": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1.5,
outputPrice: 7,
supportsReasoning: true,
thinkingConfig: { maxBudget: 38_912, outputPrice: 15 },
},
"qwen3.7-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1,
outputPrice: 5,
},
"qwen3.7-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
},
"qwen3.6-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1,
outputPrice: 5,
},
"qwen3.6-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
},
"qwen3.5-plus": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1,
outputPrice: 5,
},
"qwen3.5-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
},
"qwen3-coder-flash": {
maxTokens: 65_536,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0.5,
outputPrice: 2,
description: "Qwen3 Coder Flash - fast coding model, 1M context",
},
"qwen3-coder-next": {
maxTokens: 65_536,
contextWindow: 262_144,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 1.5,
outputPrice: 7.5,
description: "Qwen3 Coder Next - next-gen open coder (480B MoE)",
},
"qwen3-235b-a22b": {
maxTokens: 8_192,
contextWindow: 32_000,
@@ -4905,6 +5645,63 @@ export const basetenDefaultModelId = "zai-org/GLM-4.6" satisfies BasetenModelId
export type internationalZAiModelId = keyof typeof internationalZAiModels
export const internationalZAiDefaultModelId: internationalZAiModelId = "glm-5.1"
export const internationalZAiModels = {
"glm-5.3-flash": {
maxTokens: 128_000,
contextWindow: 1_310_720,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.05,
inputPrice: 0.3,
outputPrice: 1.2,
description: "GLM-5.3 Flash - latest fast model, 1.3M context",
},
"glm-5.3": {
maxTokens: 128_000,
contextWindow: 1_048_576,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.15,
inputPrice: 0.8,
outputPrice: 3.0,
description: "GLM-5.3 - latest generation, 1M context",
},
"glm-5.2": {
maxTokens: 128_000,
contextWindow: 1_048_576,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.15,
inputPrice: 0.8,
outputPrice: 3.0,
},
"glm-5-turbo": {
maxTokens: 128_000,
contextWindow: 202_752,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.05,
inputPrice: 0.3,
outputPrice: 1.2,
},
"glm-5v-turbo": {
maxTokens: 128_000,
contextWindow: 202_752,
supportsImages: true,
supportsPromptCache: true,
cacheReadsPrice: 0.05,
inputPrice: 0.3,
outputPrice: 1.2,
description: "GLM-5V Turbo - vision + text model",
},
"glm-4.7-flash": {
maxTokens: 128_000,
contextWindow: 202_752,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.03,
inputPrice: 0.1,
outputPrice: 0.5,
},
"glm-5.1": {
maxTokens: 128_000,
contextWindow: 200_000,
@@ -4970,6 +5767,63 @@ export const internationalZAiModels = {
export type mainlandZAiModelId = keyof typeof mainlandZAiModels
export const mainlandZAiDefaultModelId: mainlandZAiModelId = "glm-5.1"
export const mainlandZAiModels = {
"glm-5.3-flash": {
maxTokens: 128_000,
contextWindow: 1_310_720,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.05,
inputPrice: 0.3,
outputPrice: 1.2,
description: "GLM-5.3 Flash - latest fast model, 1.3M context",
},
"glm-5.3": {
maxTokens: 128_000,
contextWindow: 1_048_576,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.15,
inputPrice: 0.8,
outputPrice: 3.0,
description: "GLM-5.3 - latest generation, 1M context",
},
"glm-5.2": {
maxTokens: 128_000,
contextWindow: 1_048_576,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.15,
inputPrice: 0.8,
outputPrice: 3.0,
},
"glm-5-turbo": {
maxTokens: 128_000,
contextWindow: 202_752,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.05,
inputPrice: 0.3,
outputPrice: 1.2,
},
"glm-5v-turbo": {
maxTokens: 128_000,
contextWindow: 202_752,
supportsImages: true,
supportsPromptCache: true,
cacheReadsPrice: 0.05,
inputPrice: 0.3,
outputPrice: 1.2,
description: "GLM-5V Turbo - vision + text model",
},
"glm-4.7-flash": {
maxTokens: 128_000,
contextWindow: 202_752,
supportsImages: false,
supportsPromptCache: true,
cacheReadsPrice: 0.03,
inputPrice: 0.1,
outputPrice: 0.5,
},
"glm-5.1": {
maxTokens: 128_000,
contextWindow: 200_000,
@@ -5213,6 +6067,27 @@ export const qwenCodeDefaultModelId: QwenCodeModelId = "qwen3-coder-plus"
export type MinimaxModelId = keyof typeof minimaxModels
export const minimaxDefaultModelId: MinimaxModelId = "MiniMax-M2.7"
export const minimaxModels = {
"MiniMax-M3": {
maxTokens: 128_000,
contextWindow: 1_048_576,
supportsImages: false,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 0.3,
outputPrice: 1.2,
cacheReadsPrice: 0.06,
description: "MiniMax M3 - latest flagship, 1M context",
},
"MiniMax-M1": {
maxTokens: 128_000,
contextWindow: 1_000_000,
supportsImages: false,
supportsPromptCache: true,
supportsReasoning: true,
inputPrice: 0.55,
outputPrice: 2.2,
cacheReadsPrice: 0.11,
},
"MiniMax-M2.7": {
maxTokens: 128_000,
contextWindow: 192_000,
+64
View File
@@ -104,6 +104,70 @@ export interface ClineStorageMessage extends Anthropic.MessageParam {
ts?: number
}
/**
/**
* Strips image blocks from conversation history, replacing them with text placeholders.
* Used when switching from a multimodal model to a text-only model to prevent API errors.
*
* @param messages - Array of ClineStorageMessage to strip images from
* @returns An object with the stripped messages and whether any images were removed
*/
export function stripImagesFromMessages(messages: ClineStorageMessage[]): {
messages: ClineStorageMessage[]
imagesStripped: boolean
} {
let imagesStripped = false
const stripped = messages.map((msg) => {
if (typeof msg.content === "string") {
return msg
}
if (!Array.isArray(msg.content)) {
return msg
}
let hasImage = false
const newContent = msg.content.map((block: any) => {
if (block.type === "image") {
hasImage = true
return {
type: "text" as const,
text: "[Image: content not supported by current model]",
}
}
// Handle tool_result blocks that may contain image content
if (block.type === "tool_result" && Array.isArray(block.content)) {
const innerHasImage = block.content.some((inner: any) => inner.type === "image")
if (innerHasImage) {
hasImage = true
return {
...block,
content: block.content.map((inner: any) => {
if (inner.type === "image") {
return {
type: "text" as const,
text: "[Image: content not supported by current model]",
}
}
return inner
}),
}
}
}
return block
})
if (hasImage) {
imagesStripped = true
}
return hasImage ? { ...msg, content: newContent } : msg
})
return { messages: stripped, imagesStripped }
}
/**
* Converts ClineStorageMessage to Anthropic.MessageParam by removing Cline-specific fields
* Cline-specific fields (like modelInfo, reasoning_details) are properly omitted.
+6 -1
View File
@@ -16,5 +16,10 @@ export type {
ClineUserContent,
ClineUserToolResultContentBlock,
} from "./content"
export { cleanContentBlock, convertClineStorageToAnthropicMessage, REASONING_DETAILS_PROVIDERS } from "./content"
export {
cleanContentBlock,
convertClineStorageToAnthropicMessage,
REASONING_DETAILS_PROVIDERS,
stripImagesFromMessages,
} from "./content"
export type { ClineMessageMetricsInfo, ClineMessageModelInfo } from "./metrics"
+6 -5
View File
@@ -1,4 +1,4 @@
import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings"
import { AutoApprovalSettings, DEFAULT_AUTO_APPROVAL_SETTINGS } from "@shared/AutoApprovalSettings"
import {
ApiProvider,
DEFAULT_API_PROVIDER,
@@ -157,7 +157,7 @@ const API_HANDLER_SETTINGS_FIELDS = {
// Plan mode configurations
planModeApiModelId: { default: undefined as string | undefined },
planModeThinkingBudgetTokens: { default: undefined as number | undefined },
planModeThinkingBudgetTokens: { default: 4096 as number },
geminiPlanModeThinkingLevel: { default: undefined as string | undefined },
planModeReasoningEffort: { default: undefined as string | undefined },
planModeVerbosity: { default: undefined as string | undefined },
@@ -202,7 +202,7 @@ const API_HANDLER_SETTINGS_FIELDS = {
// Act mode configurations
actModeApiModelId: { default: undefined as string | undefined },
actModeThinkingBudgetTokens: { default: undefined as number | undefined },
actModeThinkingBudgetTokens: { default: 4096 as number },
geminiActModeThinkingLevel: { default: undefined as string | undefined },
actModeReasoningEffort: { default: undefined as string | undefined },
actModeVerbosity: { default: undefined as string | undefined },
@@ -272,16 +272,17 @@ const USER_SETTINGS_FIELDS = {
shellIntegrationTimeout: { default: 4000 as number },
defaultTerminalProfile: { default: "default" as string },
terminalOutputLineLimit: { default: 500 as number },
maxConsecutiveMistakes: { default: 3 as number },
maxConsecutiveMistakes: { default: 5 as number },
strictPlanModeEnabled: { default: false as boolean },
hooksEnabled: { default: true as boolean },
yoloModeToggled: { default: false as boolean },
autoApproveAllToggled: { default: false as boolean },
useAutoCondense: { default: false as boolean },
fileOptimizationThreshold: { default: 0.3 as number },
subagentsEnabled: { default: false as boolean },
clineWebToolsEnabled: { default: true as boolean },
worktreesEnabled: { default: false as boolean },
preferredLanguage: { default: "Simplified Chinese - 简体中文" as string },
preferredLanguage: { default: "Simplified Chinese - ��������" as string },
mode: { default: "act" as Mode },
focusChainSettings: { default: DEFAULT_FOCUS_CHAIN_SETTINGS as FocusChainSettings },
customPrompt: { default: undefined as "compact" | undefined },
+510
View File
@@ -0,0 +1,510 @@
import type { ClineMessage } from "./ExtensionMessage"
import type { HistoryItem } from "./HistoryItem"
export type UsageTimeRange = "today" | "week" | "month" | "all"
/** Usage recorded for a single API request (or an aggregated snapshot such as deleted_api_reqs / subagent_usage). */
export interface UsageEntry {
/** Timestamp (ms) of the API request / usage snapshot */
ts: number
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
/** Cost breakdown by pricing component (input / cache writes / cache reads / output) */
inputCost?: number
outputCost?: number
cacheWritesCost?: number
cacheReadsCost?: number
/** Model that served this request, if known */
modelId?: string
}
export interface ModelUsageStats {
requests: number
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
/** Cost breakdown by pricing component (input / cache writes / cache reads / output) */
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
}
export interface UsageTotals {
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
/** Cost breakdown by pricing component (input / cache writes / cache reads / output) */
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
/** Number of API requests (not tasks) */
requests: number
/** Number of tasks contributing usage in the range */
tasks: number
}
/** A calendar-aligned bucket used to render the usage trend chart. */
export interface UsageTrendBucket {
/** "YYYY-MM-DD" for day buckets, "HH" for hour buckets */
key: string
/** Human readable label, e.g. "9/12" or "08:00" */
label: string
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
/** Cost breakdown by pricing component (input / cache writes / cache reads / output) */
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
}
export interface UsageStatsResult {
totals: UsageTotals
modelStats: Map<string, ModelUsageStats>
/** Ordered old -> new, with missing days/hours zero-filled so the chart aligns to the calendar. */
trend: UsageTrendBucket[]
}
/**
* A durable per-request usage log record persisted to disk (usage-log.jsonl).
* Unlike UsageEntry (which lives inside task history and disappears when a task
* is deleted), these records survive task deletion so usage statistics remain
* complete and stable over time.
*/
export interface UsageLogEntry extends UsageEntry {
/** Task that made the request */
taskId?: string
/** API provider id (e.g. "openai", "openrouter", "anthropic") */
provider?: string
/** "plan" | "act" */
mode?: string
/** Human readable task text snippet for the record */
taskSnippet?: string
}
/** Aggregation result over raw usage-log entries (no per-task grouping needed). */
export interface UsageLogAggregate {
totals: UsageTotals
modelStats: Map<string, ModelUsageStats>
trend: UsageTrendBucket[]
}
const DAY_MS = 24 * 60 * 60 * 1000
export const UNKNOWN_MODEL_KEY = "unknown"
export function getTimeRangeCutoff(range: UsageTimeRange, now = Date.now()): number {
switch (range) {
case "today":
return new Date(now).setHours(0, 0, 0, 0)
case "week":
return now - 7 * DAY_MS
case "month":
return now - 30 * DAY_MS
default:
return 0
}
}
function toNumber(value: unknown): number {
return typeof value === "number" && Number.isFinite(value) ? value : 0
}
function hasUsageData(entry: { tokensIn?: unknown; tokensOut?: unknown; cost?: unknown }): boolean {
return typeof entry.tokensIn === "number" || typeof entry.tokensOut === "number" || typeof entry.cost === "number"
}
/**
* Extracts per-request usage entries from a task's clineMessages.
* Sources:
* - `api_req_started` messages (finalized ones carry tokens/cost and the modelId of the request)
* - `deleted_api_reqs` messages (aggregate of messages removed by checkpoint restores / truncation)
* - `subagent_usage` messages (aggregate usage of subagent batches)
*/
export function extractUsageEntries(messages: ClineMessage[]): { usageEntries: UsageEntry[]; apiRequestCount: number } {
const usageEntries: UsageEntry[] = []
let apiRequestCount = 0
for (const message of messages) {
if (message.type !== "say" || !message.text) {
continue
}
if (message.say === "api_req_started") {
apiRequestCount++
try {
const data = JSON.parse(message.text)
if (hasUsageData(data)) {
usageEntries.push({
ts: message.ts,
tokensIn: toNumber(data.tokensIn),
tokensOut: toNumber(data.tokensOut),
cacheWrites: toNumber(data.cacheWrites),
cacheReads: toNumber(data.cacheReads),
cost: toNumber(data.cost),
inputCost: toNumber(data.inputCost),
outputCost: toNumber(data.outputCost),
cacheWritesCost: toNumber(data.cacheWritesCost),
cacheReadsCost: toNumber(data.cacheReadsCost),
modelId: typeof data.modelId === "string" && data.modelId ? data.modelId : undefined,
})
}
} catch {
// Ignore malformed usage payloads
}
} else if (message.say === "deleted_api_reqs" || message.say === "subagent_usage") {
try {
const data = JSON.parse(message.text)
if (hasUsageData(data)) {
usageEntries.push({
ts: message.ts,
tokensIn: toNumber(data.tokensIn),
tokensOut: toNumber(data.tokensOut),
cacheWrites: toNumber(data.cacheWrites),
cacheReads: toNumber(data.cacheReads),
cost: toNumber(data.cost),
inputCost: toNumber(data.inputCost),
outputCost: toNumber(data.outputCost),
cacheWritesCost: toNumber(data.cacheWritesCost),
cacheReadsCost: toNumber(data.cacheReadsCost),
})
}
} catch {
// Ignore malformed usage payloads
}
}
}
return { usageEntries, apiRequestCount }
}
/**
* Normalizes a history item into per-request usage entries.
* New items carry `usageEntries` captured per API request; older items only have
* task-level totals, which we fall back to as a single approximate entry.
*/
export function normalizeUsageEntries(item: HistoryItem): UsageEntry[] {
if (item.usageEntries && item.usageEntries.length > 0) {
return item.usageEntries
}
if (!hasUsageData(item) && !item.cacheWrites && !item.cacheReads) {
return []
}
if (toNumber(item.tokensIn) === 0 && toNumber(item.tokensOut) === 0 && toNumber(item.totalCost) === 0) {
return []
}
return [
{
ts: item.ts,
tokensIn: toNumber(item.tokensIn),
tokensOut: toNumber(item.tokensOut),
cacheWrites: toNumber(item.cacheWrites),
cacheReads: toNumber(item.cacheReads),
cost: toNumber(item.totalCost),
modelId: item.modelId,
},
]
}
function getDayKey(ts: number): string {
const d = new Date(ts)
const month = `${d.getMonth() + 1}`.padStart(2, "0")
const day = `${d.getDate()}`.padStart(2, "0")
return `${d.getFullYear()}-${month}-${day}`
}
function createEmptyBucket(key: string, label: string): UsageTrendBucket {
return {
key,
label,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
cost: 0,
inputCost: 0,
outputCost: 0,
cacheWritesCost: 0,
cacheReadsCost: 0,
}
}
function accumulateBucket(bucket: UsageTrendBucket, entry: UsageEntry): void {
bucket.tokensIn += entry.tokensIn
bucket.tokensOut += entry.tokensOut
bucket.cacheWrites += entry.cacheWrites
bucket.cacheReads += entry.cacheReads
bucket.cost += entry.cost
bucket.inputCost += toNumber(entry.inputCost)
bucket.outputCost += toNumber(entry.outputCost)
bucket.cacheWritesCost += toNumber(entry.cacheWritesCost)
bucket.cacheReadsCost += toNumber(entry.cacheReadsCost)
}
function buildHourBuckets(entries: UsageEntry[]): UsageTrendBucket[] {
const buckets: UsageTrendBucket[] = []
for (let hour = 0; hour < 24; hour++) {
const key = `${hour}`.padStart(2, "0")
buckets.push(createEmptyBucket(key, `${key}:00`))
}
for (const entry of entries) {
const bucket = buckets[new Date(entry.ts).getHours()]
if (bucket) {
accumulateBucket(bucket, entry)
}
}
return buckets
}
function buildDayBuckets(entries: UsageEntry[], fromDayStart: number, toDayStart: number): UsageTrendBucket[] {
const bucketsByDayStart = new Map<number, UsageTrendBucket>()
const cursor = new Date(fromDayStart)
const last = new Date(toDayStart)
// Iterate calendar days (DST-safe via setDate)
while (cursor.getTime() <= last.getTime()) {
const dayStart = new Date(cursor).setHours(0, 0, 0, 0)
const d = new Date(dayStart)
bucketsByDayStart.set(dayStart, createEmptyBucket(getDayKey(dayStart), `${d.getMonth() + 1}/${d.getDate()}`))
cursor.setDate(cursor.getDate() + 1)
}
for (const entry of entries) {
const bucket = bucketsByDayStart.get(new Date(entry.ts).setHours(0, 0, 0, 0))
if (bucket) {
accumulateBucket(bucket, entry)
}
}
return Array.from(bucketsByDayStart.values())
}
function roundBucketCosts(bucket: UsageTrendBucket): UsageTrendBucket {
bucket.cost = round6(bucket.cost)
bucket.inputCost = round6(bucket.inputCost)
bucket.outputCost = round6(bucket.outputCost)
bucket.cacheWritesCost = round6(bucket.cacheWritesCost)
bucket.cacheReadsCost = round6(bucket.cacheReadsCost)
return bucket
}
function buildTrend(entries: UsageEntry[], range: UsageTimeRange, now: number): UsageTrendBucket[] {
if (entries.length === 0) {
return []
}
if (range === "today") {
return buildHourBuckets(entries).map(roundBucketCosts)
}
const todayStart = new Date(now).setHours(0, 0, 0, 0)
if (range === "week") {
return buildDayBuckets(entries, todayStart - 6 * DAY_MS, todayStart).map(roundBucketCosts)
}
if (range === "month") {
return buildDayBuckets(entries, todayStart - 29 * DAY_MS, todayStart).map(roundBucketCosts)
}
// "all": span from the earliest entry's day through today
let earliest = now
for (const entry of entries) {
earliest = Math.min(earliest, entry.ts)
}
const earliestDayStart = new Date(earliest).setHours(0, 0, 0, 0)
return buildDayBuckets(entries, earliestDayStart, todayStart).map(roundBucketCosts)
}
function round6(value: number): number {
return Math.round(value * 1e6) / 1e6
}
/**
* Aggregates usage across the FULL task history (not truncated), producing
* totals, per-model stats and a calendar-aligned trend series.
*/
export function aggregateUsageStats(items: HistoryItem[], range: UsageTimeRange, now = Date.now()): UsageStatsResult {
const cutoff = getTimeRangeCutoff(range, now)
const totals: UsageTotals = {
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
cost: 0,
inputCost: 0,
outputCost: 0,
cacheWritesCost: 0,
cacheReadsCost: 0,
requests: 0,
tasks: 0,
}
const modelStats = new Map<string, ModelUsageStats>()
const allEntries: UsageEntry[] = []
for (const item of items) {
if (!item.ts || item.ts < cutoff) {
continue
}
totals.tasks++
const entries = normalizeUsageEntries(item)
for (const entry of entries) {
allEntries.push(entry)
totals.tokensIn += entry.tokensIn
totals.tokensOut += entry.tokensOut
totals.cacheWrites += entry.cacheWrites
totals.cacheReads += entry.cacheReads
totals.cost += entry.cost
totals.inputCost += toNumber(entry.inputCost)
totals.outputCost += toNumber(entry.outputCost)
totals.cacheWritesCost += toNumber(entry.cacheWritesCost)
totals.cacheReadsCost += toNumber(entry.cacheReadsCost)
totals.requests++
const modelKey = entry.modelId || UNKNOWN_MODEL_KEY
const model = modelStats.get(modelKey) ?? {
requests: 0,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
cost: 0,
inputCost: 0,
outputCost: 0,
cacheWritesCost: 0,
cacheReadsCost: 0,
}
model.requests++
model.tokensIn += entry.tokensIn
model.tokensOut += entry.tokensOut
model.cacheWrites += entry.cacheWrites
model.cacheReads += entry.cacheReads
model.cost += entry.cost
model.inputCost += toNumber(entry.inputCost)
model.outputCost += toNumber(entry.outputCost)
model.cacheWritesCost += toNumber(entry.cacheWritesCost)
model.cacheReadsCost += toNumber(entry.cacheReadsCost)
modelStats.set(modelKey, model)
}
}
totals.cost = round6(totals.cost)
totals.inputCost = round6(totals.inputCost)
totals.outputCost = round6(totals.outputCost)
totals.cacheWritesCost = round6(totals.cacheWritesCost)
totals.cacheReadsCost = round6(totals.cacheReadsCost)
for (const model of modelStats.values()) {
model.cost = round6(model.cost)
model.inputCost = round6(model.inputCost)
model.outputCost = round6(model.outputCost)
model.cacheWritesCost = round6(model.cacheWritesCost)
model.cacheReadsCost = round6(model.cacheReadsCost)
}
return { totals, modelStats, trend: buildTrend(allEntries, range, now) }
}
/**
* Aggregates raw usage-log entries (from the durable usage-log.jsonl) into
* totals, per-model stats and a calendar-aligned trend series.
* The cutoff is applied per-entry using its own timestamp.
*/
export function aggregateUsageEntries(entries: UsageLogEntry[], range: UsageTimeRange, now = Date.now()): UsageLogAggregate {
const cutoff = getTimeRangeCutoff(range, now)
const totals: UsageTotals = {
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
cost: 0,
inputCost: 0,
outputCost: 0,
cacheWritesCost: 0,
cacheReadsCost: 0,
requests: 0,
tasks: 0,
}
const modelStats = new Map<string, ModelUsageStats>()
const activeTaskIds = new Set<string>()
const inRange: UsageEntry[] = []
for (const entry of entries) {
if (!entry || typeof entry.ts !== "number" || entry.ts < cutoff) {
continue
}
// Entries without a taskId (e.g. legacy records) still represent one
// task session — count them under a sentinel so tasks stays >= 1.
activeTaskIds.add(entry.taskId || "__unknown_task__")
const normalized: UsageEntry = {
ts: entry.ts,
tokensIn: toNumber(entry.tokensIn),
tokensOut: toNumber(entry.tokensOut),
cacheWrites: toNumber(entry.cacheWrites),
cacheReads: toNumber(entry.cacheReads),
cost: toNumber(entry.cost),
inputCost: toNumber(entry.inputCost),
outputCost: toNumber(entry.outputCost),
cacheWritesCost: toNumber(entry.cacheWritesCost),
cacheReadsCost: toNumber(entry.cacheReadsCost),
modelId: entry.modelId,
}
inRange.push(normalized)
totals.tokensIn += normalized.tokensIn
totals.tokensOut += normalized.tokensOut
totals.cacheWrites += normalized.cacheWrites
totals.cacheReads += normalized.cacheReads
totals.cost += normalized.cost
totals.inputCost += toNumber(normalized.inputCost)
totals.outputCost += toNumber(normalized.outputCost)
totals.cacheWritesCost += toNumber(normalized.cacheWritesCost)
totals.cacheReadsCost += toNumber(normalized.cacheReadsCost)
totals.requests++
const modelKey = normalized.modelId || UNKNOWN_MODEL_KEY
const model = modelStats.get(modelKey) ?? {
requests: 0,
tokensIn: 0,
tokensOut: 0,
cacheWrites: 0,
cacheReads: 0,
cost: 0,
inputCost: 0,
outputCost: 0,
cacheWritesCost: 0,
cacheReadsCost: 0,
}
model.requests++
model.tokensIn += normalized.tokensIn
model.tokensOut += normalized.tokensOut
model.cacheWrites += normalized.cacheWrites
model.cacheReads += normalized.cacheReads
model.cost += normalized.cost
model.inputCost += toNumber(normalized.inputCost)
model.outputCost += toNumber(normalized.outputCost)
model.cacheWritesCost += toNumber(normalized.cacheWritesCost)
model.cacheReadsCost += toNumber(normalized.cacheReadsCost)
modelStats.set(modelKey, model)
}
totals.tasks = activeTaskIds.size
totals.cost = round6(totals.cost)
totals.inputCost = round6(totals.inputCost)
totals.outputCost = round6(totals.outputCost)
totals.cacheWritesCost = round6(totals.cacheWritesCost)
totals.cacheReadsCost = round6(totals.cacheReadsCost)
for (const model of modelStats.values()) {
model.cost = round6(model.cost)
model.inputCost = round6(model.inputCost)
model.outputCost = round6(model.outputCost)
model.cacheWritesCost = round6(model.cacheWritesCost)
model.cacheReadsCost = round6(model.cacheReadsCost)
}
return { totals, modelStats, trend: buildTrend(inRange, range, now) }
}
+60 -4
View File
@@ -1,6 +1,14 @@
import { ModelInfo } from "@shared/api"
function calculateApiCostInternal(
export interface ApiCostBreakdown {
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
totalCost: number
}
function calculateApiCostInternalWithBreakdown(
modelInfo: ModelInfo,
inputTokens: number, // Note: For OpenAI-style, this is non-cached tokens. For Anthropic-style, this is total input tokens.
outputTokens: number,
@@ -8,7 +16,7 @@ function calculateApiCostInternal(
cacheReadInputTokens: number,
totalInputTokensForPricing?: number, // The *total* input tokens, used for tiered pricing lookup
thinkingBudgetTokens?: number, // Add thinking budget info
): number {
): ApiCostBreakdown {
const usedThinkingBudget = thinkingBudgetTokens && thinkingBudgetTokens > 0
// Default prices
@@ -59,7 +67,33 @@ function calculateApiCostInternal(
const outputCost = (effectiveOutputPrice / 1_000_000) * outputTokens
const totalCost = cacheWritesCost + cacheReadsCost + baseInputCost + outputCost
return totalCost
return {
inputCost: baseInputCost,
outputCost,
cacheWritesCost,
cacheReadsCost,
totalCost,
}
}
function calculateApiCostInternal(
modelInfo: ModelInfo,
inputTokens: number, // Note: For OpenAI-style, this is non-cached tokens. For Anthropic-style, this is total input tokens.
outputTokens: number,
cacheCreationInputTokens: number,
cacheReadInputTokens: number,
totalInputTokensForPricing?: number, // The *total* input tokens, used for tiered pricing lookup
thinkingBudgetTokens?: number, // Add thinking budget info
): number {
return calculateApiCostInternalWithBreakdown(
modelInfo,
inputTokens,
outputTokens,
cacheCreationInputTokens,
cacheReadInputTokens,
totalInputTokensForPricing,
thinkingBudgetTokens,
).totalCost
}
// For Anthropic compliant usage, the input tokens count does NOT include the cached tokens
export function calculateApiCostAnthropic(
@@ -70,12 +104,34 @@ export function calculateApiCostAnthropic(
cacheReadInputTokens?: number,
thinkingBudgetTokens?: number,
): number {
return calculateApiCostBreakdownAnthropic(
modelInfo,
inputTokens,
outputTokens,
cacheCreationInputTokens,
cacheReadInputTokens,
thinkingBudgetTokens,
).totalCost
}
/**
* Same pricing rules as calculateApiCostAnthropic, but returns the per-component
* cost breakdown (input / output / cache writes / cache reads) in addition to the total.
*/
export function calculateApiCostBreakdownAnthropic(
modelInfo: ModelInfo,
inputTokens: number,
outputTokens: number,
cacheCreationInputTokens?: number,
cacheReadInputTokens?: number,
thinkingBudgetTokens?: number,
): ApiCostBreakdown {
const cacheCreationInputTokensNum = cacheCreationInputTokens || 0
const cacheReadInputTokensNum = cacheReadInputTokens || 0
// Anthropic style: inputTokens already represents the total, so pass it directly for tiered pricing lookup if needed
// (though Anthropic models currently don't use tiered pricing based on input size)
// Anthropic style doesn't need totalInputTokensForPricing as its inputTokens already represents the total
return calculateApiCostInternal(
return calculateApiCostInternalWithBreakdown(
modelInfo,
inputTokens,
outputTokens,
+2 -7
View File
@@ -1,6 +1,6 @@
import type { Boolean, EmptyRequest } from "@shared/proto/cline/common"
import { useCallback, useEffect } from "react"
import AccountView from "./components/account/AccountView"
import UsageStatsView from "./components/usage-stats/UsageStatsView"
import ChatView from "./components/chat/ChatView"
import HistoryView from "./components/history/HistoryView"
import McpView from "./components/mcp/configuration/McpConfigurationView"
@@ -70,12 +70,7 @@ const AppContent = () => {
{showHistory && <HistoryView onDone={hideHistory} />}
{showMcp && <McpView initialTab={mcpTab} onDone={closeMcpView} />}
{showAccount && (
<AccountView
activeOrganization={activeOrganization}
clineUser={clineUser}
onDone={hideAccount}
organizations={organizations}
/>
<UsageStatsView onDone={hideAccount} />
)}
{showWorktrees && <WorktreesView onDone={hideWorktrees} />}
{/* Do not conditionally load ChatView, it's expensive and there's state we don't want to lose (user input, disableInput, askResponse promise, etc.) */}
@@ -360,7 +360,7 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
disabled={isLoading || isLockedByRemoteConfig}
onChange={handleOrganizationChange}>
<VSCodeOption key="personal" value={uid}>
Personal
个人
</VSCodeOption>
{userOrganizations?.map((org: UserOrganization) => (
<VSCodeOption key={org.organizationId} value={org.organizationId}>
@@ -21,11 +21,11 @@ const CreditsHistoryTable = memo(({ isLoading, usageData, paymentsData, showPaym
{/* Tabs container */}
<div className="flex border-b border-(--vscode-panel-border)">
<TabButton isActive={activeTab === "usage"} onClick={() => setActiveTab("usage")}>
USAGE HISTORY
使用记录
</TabButton>
{showPayments && (
<TabButton isActive={activeTab === "payments"} onClick={() => setActiveTab("payments")}>
PAYMENTS HISTORY
付款记录
</TabButton>
)}
</div>
@@ -42,18 +42,18 @@ const CreditsHistoryTable = memo(({ isLoading, usageData, paymentsData, showPaym
(usageData.length > 0 ? (
<VSCodeDataGrid>
<VSCodeDataGridRow row-type="header">
<VSCodeDataGridCell cell-type="columnheader" grid-column="1">
Date
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="2">
Model
</VSCodeDataGridCell>
{/* <VSCodeDataGridCell cell-type="columnheader" grid-column="3">
Tokens Used
</VSCodeDataGridCell> */}
<VSCodeDataGridCell cell-type="columnheader" grid-column="3">
Credits Used
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="1">
日期
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="2">
模型
</VSCodeDataGridCell>
{/* <VSCodeDataGridCell cell-type="columnheader" grid-column="3">
Tokens Used
</VSCodeDataGridCell> */}
<VSCodeDataGridCell cell-type="columnheader" grid-column="3">
已用额度
</VSCodeDataGridCell>
</VSCodeDataGridRow>
{usageData.map((row, index) => (
@@ -88,13 +88,13 @@ const CreditsHistoryTable = memo(({ isLoading, usageData, paymentsData, showPaym
<VSCodeDataGrid>
<VSCodeDataGridRow row-type="header">
<VSCodeDataGridCell cell-type="columnheader" grid-column="1">
Date
日期
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="2">
Total Cost
总费用
</VSCodeDataGridCell>
<VSCodeDataGridCell cell-type="columnheader" grid-column="3">
Credits
额度
</VSCodeDataGridCell>
</VSCodeDataGridRow>
@@ -639,16 +639,28 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
}
}
// Safari does not support InputEvent.isComposing (always false), so we need to fallback to keyCode === 229 for it
const isComposing = isSafari ? event.nativeEvent.keyCode === 229 : (event.nativeEvent?.isComposing ?? false)
if (event.key === "Enter" && !event.shiftKey && !isComposing) {
event.preventDefault()
// Safari does not support InputEvent.isComposing (always false), so we need to fallback to keyCode === 229 for it
const isComposing = isSafari ? event.nativeEvent.keyCode === 229 : (event.nativeEvent?.isComposing ?? false)
// Ctrl/Cmd + Enter: insert a newline at cursor instead of sending
if (event.key === "Enter" && (event.ctrlKey || event.metaKey) && !isComposing) {
event.preventDefault()
const textArea = event.currentTarget
const start = textArea.selectionStart ?? inputValue.length
const end = textArea.selectionEnd ?? inputValue.length
const newValue = `${inputValue.slice(0, start)}\n${inputValue.slice(end)}`
setInputValue(newValue)
setCursorPosition(start + 1)
setIntendedCursorPosition(start + 1)
return
}
if (event.key === "Enter" && !event.shiftKey && !isComposing) {
event.preventDefault()
if (!sendingDisabled) {
setIsTextAreaFocused(false)
onSend()
}
if (!sendingDisabled) {
setIsTextAreaFocused(false)
onSend()
}
}
if (event.key === "Backspace" && !isComposing) {
const charBeforeCursor = inputValue[cursorPosition - 1]
@@ -13,6 +13,7 @@ import { useShowNavbar } from "@/context/PlatformContext"
import { FileServiceClient, UiServiceClient } from "@/services/grpc-client"
import { Navbar } from "../menu/Navbar"
import AutoApproveBar from "./auto-approve-menu/AutoApproveBar"
import CostBar from "./CostBar"
// Import utilities and hooks from the new structure
import {
ActionButtons,
@@ -366,6 +367,7 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
)}
</div>
<footer className="bg-(--vscode-sidebar-background)" style={{ gridRow: "2" }}>
<CostBar messages={messages} />
<AutoApproveBar />
<ActionButtons
chatState={chatState}
@@ -0,0 +1,60 @@
import type { ClineMessage } from "@shared/ExtensionMessage"
import { getApiMetrics } from "@shared/getApiMetrics"
import { memo, useMemo } from "react"
interface CostBarProps {
messages: ClineMessage[]
}
const CostBar = memo(({ messages }: CostBarProps) => {
const metrics = useMemo(() => getApiMetrics(messages), [messages])
const formatTokens = (n: number): string => {
if (n >= 1_000_000) {
return `${(n / 1_000_000).toFixed(1)}M`
}
if (n >= 1_000) {
return `${(n / 1_000).toFixed(1)}K`
}
return n.toString()
}
const formatCost = (cost: number): string => {
if (cost < 0.01) {
return `$${cost.toFixed(4)}`
}
return `$${cost.toFixed(2)}`
}
if (metrics.totalTokensIn === 0 && metrics.totalTokensOut === 0 && metrics.totalCost === 0) {
return null
}
return (
<div className="flex items-center justify-between px-3 py-1.5 text-xs text-description border-t border-(--vscode-panel-border) bg-(--vscode-editor-background)/50">
<div className="flex items-center gap-3">
<span className="flex items-center gap-1">
<span className="codicon codicon-arrow-down text-[10px] opacity-60" />
{formatTokens(metrics.totalTokensIn)} in
</span>
<span className="flex items-center gap-1">
<span className="codicon codicon-arrow-up text-[10px] opacity-60" />
{formatTokens(metrics.totalTokensOut)} out
</span>
{metrics.totalCacheReads != null && metrics.totalCacheReads > 0 && (
<span className="flex items-center gap-1 opacity-70">
<span className="codicon codicon-database text-[10px]" />
{formatTokens(metrics.totalCacheReads)} cached
</span>
)}
</div>
<div className="flex items-center gap-1 font-medium">
{metrics.totalCost > 0 ? formatCost(metrics.totalCost) : "..."}
</div>
</div>
)
})
CostBar.displayName = "CostBar"
export default CostBar
+93 -11
View File
@@ -27,15 +27,14 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
switch (errorType) {
case "error":
case "mistake_limit_reached":
// Handle API request errors with special error parsing
if (rawApiError) {
// FIXME: ClineError parsing should not be applied to non-Cline providers, but it seems we're using clineErrorMessage below in the default error display
const clineError = ClineError.parse(rawApiError)
const errorMessage = clineError?._error?.message || clineError?.message || rawApiError
const requestId = clineError?._error?.request_id
const providerId = clineError?.providerId || clineError?._error?.providerId
const isClineProvider = providerId === "cline"
const errorCode = clineError?._error?.code
const status = clineError?._error?.status
if (clineError?.isErrorType(ClineErrorType.Balance)) {
const errorDetails = clineError._error?.details
@@ -77,9 +76,100 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
return <p className="m-0 whitespace-pre-wrap text-error wrap-anywhere">{detailMessage}</p>
}
if (clineError?.isErrorType(ClineErrorType.ModelNotFound)) {
return (
<div className="m-0 flex flex-col gap-2 text-error wrap-anywhere">
<div className="flex items-center gap-2">
<span className="codicon codicon-warning" />
<span className="font-bold">模型不存在</span>
</div>
<p className="m-0 text-sm opacity-90">
配置的模型 ID 不正确或已下线。
{providerId && <span>(Provider: {providerId})</span>}
请在设置中检查模型名称是否正确。
</p>
{requestId && <div className="text-xs opacity-60">Request ID: {requestId}</div>}
<div className="mt-2">
<span className="text-description">{t("error.clickRetry")}</span>
</div>
</div>
)
}
if (clineError?.isErrorType(ClineErrorType.ContentFiltered)) {
return (
<div className="m-0 flex flex-col gap-2 text-error wrap-anywhere">
<div className="flex items-center gap-2">
<span className="codicon codicon-shield" />
<span className="font-bold">内容被拦截</span>
</div>
<p className="m-0 text-sm opacity-90">
模型的安全策略拦截了本次请求。请调整任务描述,或切换其他模型后重试。
</p>
{requestId && <div className="text-xs opacity-60">Request ID: {requestId}</div>}
<div className="mt-2">
<span className="text-description">{t("error.clickRetry")}</span>
</div>
</div>
)
}
if (clineError?.isErrorType(ClineErrorType.ServerError)) {
return (
<div className="m-0 flex flex-col gap-2 text-error wrap-anywhere">
<div className="flex items-center gap-2">
<span className="codicon codicon-server" />
<span className="font-bold">服务商暂时不可用</span>
</div>
<p className="m-0 text-sm opacity-90">
API 服务返回了服务器错误({status})。通常是临时问题,系统会自动重试。
{providerId && <span>(Provider: {providerId})</span>}
</p>
{requestId && <div className="text-xs opacity-60">Request ID: {requestId}</div>}
<div className="mt-2">
<span className="text-description">{t("error.clickRetry")}</span>
</div>
</div>
)
}
if (clineError?.isErrorType(ClineErrorType.Timeout)) {
return (
<div className="m-0 flex flex-col gap-2 text-error wrap-anywhere">
<div className="flex items-center gap-2">
<span className="codicon codicon-clock" />
<span className="font-bold">请求超时</span>
</div>
<p className="m-0 text-sm opacity-90">
API 请求超时,可能是网络不稳定或模型响应过慢。请检查网络连接后重试。
</p>
<div className="mt-2">
<span className="text-description">{t("error.clickRetry")}</span>
</div>
</div>
)
}
if (clineError?.isErrorType(ClineErrorType.Network)) {
return (
<div className="m-0 flex flex-col gap-2 text-error wrap-anywhere">
<div className="flex items-center gap-2">
<span className="codicon codicon-cloud-offline" />
<span className="font-bold">网络连接失败</span>
</div>
<p className="m-0 text-sm opacity-90">
无法连接到 API 服务。请检查网络连接或代理设置。
{providerId && <span>(Provider: {providerId})</span>}
</p>
<div className="mt-2">
<span className="text-description">{t("error.clickRetry")}</span>
</div>
</div>
)
}
if (clineError?.isErrorType(ClineErrorType.Auth) && isClineProvider) {
return !clineUser ? (
// User is using Cline provider and is not logged in
<div className="flex flex-col gap-3">
<div className="flex items-center justify-center rounded border border-neutral-500/30 bg-vscode-editor-background p-6 text-center text-vscode-foreground">
{t("error.loggedOut")}
@@ -94,7 +184,6 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
</Button>
</div>
) : (
// Don't show sign in button after the user has logged in, just ask them to retry
<div className="mt-4">
<span className="text-description">{t("error.clickRetry")}</span>
</div>
@@ -103,8 +192,6 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
return (
<p className="m-0 whitespace-pre-wrap text-error wrap-anywhere flex flex-col gap-3">
{/* Display the well-formatted error extracted from the ClineError instance */}
<header>
{providerId && <span className="uppercase">[{providerId}] </span>}
{errorCode && <span>{errorCode}</span>}
@@ -112,7 +199,6 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
{requestId && <div>Request ID: {requestId}</div>}
</header>
{/* Windows Powershell Issue */}
{errorMessage?.toLowerCase()?.includes("powershell") && (
<div>
{t("error.powershellIssue")}{" "}
@@ -125,7 +211,6 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
</div>
)}
{/* Display raw API error if different from parsed error message */}
{errorMessage !== rawApiError && <div>{rawApiError}</div>}
<div className="mt-4">
@@ -135,7 +220,6 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
)
}
// Regular error message
return <p className="m-0 mt-0 whitespace-pre-wrap text-error wrap-anywhere">{message.text}</p>
case "diff_error":
@@ -161,12 +245,10 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
}
}
// 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()
})
@@ -108,8 +108,61 @@ const MemoizedMarkdownBlock = memo(
MemoizedMarkdownBlock.displayName = "MemoizedMarkdownBlock"
function preprocessContent(content: string): string {
// Detect unfenced code-like patterns and wrap them in markdown code fences
// This fixes models (like DeepSeek) that output code without proper backtick fences,
// causing rehype-highlight to mangle the output with wrong syntax colors
const codeLikePatterns = [
/<content>[\s\S]*?<\/content>/,
/<replace>[\s\S]*?<\/replace>/,
/<path>[\s\S]*?<\/path>/,
/<command>[\s\S]*?<\/command>/,
/<instructions>[\s\S]*?<\/instructions>/,
]
for (const pattern of codeLikePatterns) {
if (pattern.test(content)) {
// Wrap the entire content in a code fence if it contains unfenced tool call patterns
// Only if it doesn't already have code fences
const hasCodeFences = /```[\s\S]*?```/.test(content)
if (!hasCodeFences) {
return "```\n" + content + "\n```"
}
}
}
// Also detect multi-line code-like patterns (lines with JS code but no fences)
const lines = content.split("\n")
let codeLineCount = 0
let totalLines = 0
for (const line of lines) {
const trimmed = line.trim()
if (!trimmed) continue
totalLines++
if (
/^\s*(\/\/|const |let |var |function |return |if\s*\(|for\s*\(|while\s*\(|\.replace\(|\.forEach\(|=>\s*{)/.test(
trimmed,
) ||
/^<\w+>/.test(trimmed)
) {
codeLineCount++
}
}
// If more than 60% of non-empty lines look like code, wrap in fences
if (totalLines > 3 && codeLineCount / totalLines > 0.6) {
const hasCodeFences = /```[\s\S]*?```/.test(content)
if (!hasCodeFences) {
return "```\n" + content + "\n```"
}
}
return content
}
const MemoizedMarkdown = memo(({ content, id }: { content: string; id: string }) => {
const blocks = useMemo(() => parseMarkdownIntoBlocks(content), [content])
const preprocessed = useMemo(() => preprocessContent(content), [content])
const blocks = useMemo(() => parseMarkdownIntoBlocks(preprocessed), [preprocessed])
return blocks?.map((block, index) => <MemoizedMarkdownBlock content={block} key={`${id}-block_${index}`} />)
})
+3 -2
View File
@@ -50,8 +50,8 @@ export const Navbar = () => {
},
{
id: "account",
name: "Account",
tooltip: t("navbar.account"),
name: "我的",
tooltip: "我的",
icon: UserCircleIcon,
navigate: navigateToAccount,
},
@@ -90,3 +90,4 @@ export const Navbar = () => {
</nav>
)
}
+122 -23
View File
@@ -7,7 +7,7 @@ import { KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from
import { useTranslation } from "react-i18next"
import { useInterval } from "react-use"
import styled from "styled-components"
import { normalizeApiConfiguration } from "@/components/settings/utils/providerUtils"
import { getModeSpecificFields, normalizeApiConfiguration } from "@/components/settings/utils/providerUtils"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { PLATFORM_CONFIG, PlatformType } from "@/config/platform.config"
import { useExtensionState } from "@/context/ExtensionStateContext"
@@ -108,6 +108,7 @@ export const ProfileManager: React.FC<{ currentMode: Mode; showCards?: boolean;
const { selectedProvider } = normalizeApiConfiguration(apiConfiguration, currentMode)
const [dragIdx, setDragIdx] = useState<number | null>(null)
const [overIdx, setOverIdx] = useState<number | null>(null)
const [savedToast, setSavedToast] = useState(false)
const getProviderDisplayName = (pv: string) => PROVIDERS.list.find((p: any) => p.value === pv)?.label || pv
@@ -117,32 +118,120 @@ export const ProfileManager: React.FC<{ currentMode: Mode; showCards?: boolean;
}
const getCurrentApiKey = () => {
if (!apiConfiguration) return ""
if (!apiConfiguration) {
return ""
}
const cfg = apiConfiguration as Record<string, any>
return cfg[`${selectedProvider}ApiKey`] || cfg.apiKey || ""
const providerApiKeyField: Record<string, string> = {
anthropic: "apiKey",
"claude-code": "apiKey",
openrouter: "openRouterApiKey",
bedrock: "awsBedrockApiKey",
openai: "openAiApiKey",
ollama: "ollamaApiKey",
lmstudio: "lmStudioApiKey",
gemini: "geminiApiKey",
"openai-native": "openAiNativeApiKey",
"openai-codex": "openAiCodexApiKey",
deepseek: "deepSeekApiKey",
qwen: "qwenApiKey",
"qwen-code": "qwenCodeApiKey",
doubao: "doubaoApiKey",
mistral: "mistralApiKey",
litellm: "liteLlmApiKey",
moonshot: "moonshotApiKey",
nebius: "nebiusApiKey",
fireworks: "fireworksApiKey",
asksage: "asksageApiKey",
xai: "xaiApiKey",
sambanova: "sambanovaApiKey",
cerebras: "cerebrasApiKey",
sapaicore: "sapAiCoreApiKey",
groq: "groqApiKey",
huggingface: "huggingFaceApiKey",
"huawei-cloud-maas": "huaweiCloudMaasApiKey",
dify: "difyApiKey",
baseten: "basetenApiKey",
"vercel-ai-gateway": "vercelAiGatewayApiKey",
zai: "zaiApiKey",
minimax: "minimaxApiKey",
hicap: "hicapApiKey",
aihubmix: "aihubmixApiKey",
requesty: "requestyApiKey",
together: "togetherApiKey",
nousResearch: "nousResearchApiKey",
cline: "clineApiKey",
"vscode-lm": "",
wandb: "wandbApiKey",
}
const field = providerApiKeyField[selectedProvider]
return (field && cfg[field]) || cfg.apiKey || ""
}
const getCurrentBaseUrl = () => {
if (!apiConfiguration) return ""
const cfg = apiConfiguration as Record<string, any>
const keys = [`${selectedProvider}BaseUrl`, `${selectedProvider}Endpoint`, `${selectedProvider}ApiUrl`]
if (selectedProvider === "openai-native" || selectedProvider === "openai") keys.push("openAiBaseUrl")
if (selectedProvider === "ollama") keys.push("ollamaBaseUrl")
if (selectedProvider === "lmstudio") keys.push("lmStudioBaseUrl")
if (selectedProvider === "litellm") keys.push("litellmBaseUrl")
if (selectedProvider === "dify") keys.push("difyBaseUrl")
for (const k of keys) {
if (cfg[k]) return cfg[k]
if (!apiConfiguration) {
return ""
}
return ""
const cfg = apiConfiguration as Record<string, any>
const baseUrlFields: Record<string, string> = {
openai: "openAiBaseUrl",
ollama: "ollamaBaseUrl",
lmstudio: "lmStudioBaseUrl",
litellm: "liteLlmBaseUrl",
anthropic: "anthropicBaseUrl",
"openai-native": "openAiNativeBaseUrl",
deepseek: "deepSeekBaseUrl",
requesty: "requestyBaseUrl",
dify: "difyBaseUrl",
gemini: "geminiBaseUrl",
}
const field = baseUrlFields[selectedProvider]
return (field && cfg[field]) || ""
}
const profilePayload = () => ({
provider: selectedProvider,
apiKey: getCurrentApiKey(),
modelId: getCurrentModelId(),
baseUrl: getCurrentBaseUrl(),
})
const getCurrentModelInfo = () => {
if (!apiConfiguration) {
return undefined
}
const fields = getModeSpecificFields(apiConfiguration, currentMode)
const modelInfoMap: Record<string, any> = {
openai: fields.openAiModelInfo,
deepseek: fields.deepSeekModelInfo,
openrouter: fields.openRouterModelInfo,
cline: fields.clineModelInfo,
requesty: fields.requestyModelInfo,
groq: fields.groqModelInfo,
baseten: fields.basetenModelInfo,
huggingface: fields.huggingFaceModelInfo,
"huawei-cloud-maas": fields.huaweiCloudMaasModelInfo,
litellm: fields.liteLlmModelInfo,
aihubmix: fields.aihubmixModelInfo,
hicap: fields.hicapModelInfo,
"vercel-ai-gateway": fields.vercelAiGatewayModelInfo,
oca: fields.ocaModelInfo,
}
return modelInfoMap[selectedProvider]
}
const profilePayload = () => {
const modelInfo = getCurrentModelInfo()
const payload: {
provider: typeof selectedProvider
apiKey: string
modelId: string
baseUrl: string
extra?: Record<string, unknown>
} = {
provider: selectedProvider,
apiKey: getCurrentApiKey(),
modelId: getCurrentModelId(),
baseUrl: getCurrentBaseUrl(),
}
if (modelInfo) {
payload.extra = { profileModelInfo: modelInfo }
}
return payload
}
const handleSave = () => {
if (activeApiProfileId) {
@@ -154,6 +243,8 @@ export const ProfileManager: React.FC<{ currentMode: Mode; showCards?: boolean;
...profilePayload(),
})
}
setSavedToast(true)
setTimeout(() => setSavedToast(false), 1500)
}
const handleAdd = () => {
@@ -182,7 +273,9 @@ export const ProfileManager: React.FC<{ currentMode: Mode; showCards?: boolean;
}
const handleDrop = (e: React.DragEvent, i: number) => {
e.preventDefault()
if (dragIdx !== null && dragIdx !== i) reorderApiProfiles(dragIdx, i)
if (dragIdx !== null && dragIdx !== i) {
reorderApiProfiles(dragIdx, i)
}
setDragIdx(null)
setOverIdx(null)
}
@@ -211,7 +304,7 @@ export const ProfileManager: React.FC<{ currentMode: Mode; showCards?: boolean;
borderRadius: 4,
border: "1px solid var(--vscode-focusBorder)",
background: "transparent",
color: "var(--vscode-focusBorder)",
color: savedToast ? "var(--vscode-testing-iconPassed)" : "var(--vscode-focusBorder)",
cursor: "pointer",
fontSize: 12,
whiteSpace: "nowrap",
@@ -223,7 +316,9 @@ export const ProfileManager: React.FC<{ currentMode: Mode; showCards?: boolean;
}
// Cards grid
if (!showCards) return null
if (!showCards) {
return null
}
return (
<div style={{ marginBottom: 4 }}>
<div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8 }}>
@@ -536,6 +631,10 @@ const ApiOptions = ({
<style>
{`
vscode-text-field {
display: block !important;
width: 100% !important;
}
vscode-text-field::part(control) {
width: 100% !important;
}
.provider-item-highlight {
@@ -1,51 +1,21 @@
import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react"
import React from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { updateSetting } from "./utils/settingsHandlers"
// 项目已统一为简体中文,语言设置固定为简体中文,不再提供切换。
const PreferredLanguageSetting: React.FC = () => {
const { t } = useTranslation("settings")
const { preferredLanguage } = useExtensionState()
const handleLanguageChange = (newLanguage: string) => {
updateSetting("preferredLanguage", newLanguage)
}
return (
<div style={{}}>
<label className="block mb-1 text-base font-medium" htmlFor="preferred-language-dropdown">
{t("settings.preferredLanguage")}
</label>
<VSCodeDropdown
currentValue={preferredLanguage || "Simplified Chinese - 简体中文"}
id="preferred-language-dropdown"
onChange={(e: any) => {
handleLanguageChange(e.target.value)
}}
style={{ width: "100%" }}>
<VSCodeOption value="English">English</VSCodeOption>
<VSCodeOption value="Arabic - العربية">Arabic - العربية</VSCodeOption>
<VSCodeOption value="Portuguese - Português (Brasil)">Portuguese - Português (Brasil)</VSCodeOption>
<VSCodeOption value="Czech - Čeština">Czech - Čeština</VSCodeOption>
<VSCodeOption value="French - Français">French - Français</VSCodeOption>
<VSCodeOption value="German - Deutsch">German - Deutsch</VSCodeOption>
<VSCodeOption value="Hindi - हिन्दी">Hindi - हिन्दी</VSCodeOption>
<VSCodeOption value="Hungarian - Magyar">Hungarian - Magyar</VSCodeOption>
<VSCodeOption value="Italian - Italiano">Italian - Italiano</VSCodeOption>
<VSCodeOption value="Japanese - 日本語">Japanese - 日本語</VSCodeOption>
<VSCodeOption value="Korean - 한국어">Korean - 한국어</VSCodeOption>
<VSCodeOption value="Polish - Polski">Polish - Polski</VSCodeOption>
<VSCodeOption value="Portuguese - Português (Portugal)">Portuguese - Português (Portugal)</VSCodeOption>
<VSCodeOption value="Russian - Русский">Russian - Русский</VSCodeOption>
<VSCodeOption value="Simplified Chinese - 简体中文">Simplified Chinese - 简体中文</VSCodeOption>
<VSCodeOption value="Spanish - Español">Spanish - Español</VSCodeOption>
<VSCodeOption value="Traditional Chinese - 繁體中文">Traditional Chinese - 繁體中文</VSCodeOption>
<VSCodeOption value="Turkish - Türkçe">Turkish - Türkçe</VSCodeOption>
</VSCodeDropdown>
<div className="vscode-dropdown" id="preferred-language-dropdown" style={{ width: "100%" }}>
简体中文
</div>
<p className="text-sm text-description mt-1">{t("settings.preferredLanguageDescription")}</p>
</div>
)
}
export default React.memo(PreferredLanguageSetting)
export default React.memo(PreferredLanguageSetting)
@@ -1,4 +1,5 @@
import { VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { useDebouncedInput } from "../utils/useDebouncedInput"
@@ -27,6 +28,7 @@ export const ApiKeyField = ({
}: ApiKeyFieldProps) => {
const { t } = useTranslation("settings")
const [localValue, setLocalValue] = useDebouncedInput(initialValue, onChange)
const [showKey, setShowKey] = useState(false)
return (
<div>
@@ -35,9 +37,16 @@ export const ApiKeyField = ({
placeholder={placeholder}
required={true}
style={{ width: "100%" }}
type="password"
type={showKey ? "text" : "password"}
value={localValue}>
<span style={{ fontWeight: 500 }}>{t("commonFields.apiKey", { provider: providerName })}</span>
<span
className={showKey ? "codicon codicon-eye" : "codicon codicon-eye-closed"}
onClick={() => setShowKey(!showKey)}
slot="end"
style={{ cursor: "pointer", padding: "0 4px", fontSize: 14, opacity: 0.7 }}
title={showKey ? "闅愯棌瀵归挜" : "鏄剧ず瀵归挜"}
/>
</VSCodeTextField>
<p
style={{
@@ -30,7 +30,9 @@ export const BaseUrlField = ({
const { t } = useTranslation("settings")
const resolvedLabel = label ?? t("settings.useCustomBaseUrl")
const [isEnabled, setIsEnabled] = useState(!!initialValue)
const [localValue, setLocalValue] = useDebouncedInput(initialValue || "", onChange)
// Trim only on commit - trimming on every keystroke rewrites the controlled value
// mid-typing, which moves the cursor and swallows intentional characters.
const [localValue, setLocalValue] = useDebouncedInput(initialValue || "", (value) => onChange(value.trim()))
const handleToggle = (e: any) => {
const checked = e.target.checked === true
@@ -41,7 +43,7 @@ export const BaseUrlField = ({
}
return (
<div>
<div style={{ width: "100%", display: "block" }}>
<div className="flex items-center gap-2">
<VSCodeCheckbox checked={isEnabled} disabled={disabled} onChange={handleToggle}>
{resolvedLabel}
@@ -52,9 +54,9 @@ export const BaseUrlField = ({
{isEnabled && (
<VSCodeTextField
disabled={disabled}
onInput={(e: any) => setLocalValue(e.target.value.trim())}
onInput={(e: any) => setLocalValue(e.target.value)}
placeholder={placeholder}
style={{ width: "100%", marginTop: 3 }}
style={{ display: "block", width: "100%", marginTop: 3 }}
type="text"
value={localValue}
/>
@@ -33,6 +33,12 @@ export const DebouncedTextField = ({
}: DebouncedTextFieldProps) => {
const [localValue, setLocalValue] = useDebouncedInput(initialValue, onChange)
const mergedStyle: React.CSSProperties = {
display: "block",
width: "100%",
...(otherProps.style || {}),
}
return (
<VSCodeTextField
{...otherProps}
@@ -41,6 +47,7 @@ export const DebouncedTextField = ({
const value = e.target.value
setLocalValue(value)
}}
style={mergedStyle}
type={type}
value={localValue}>
{children}
@@ -0,0 +1,119 @@
import { ModelInfo } from "@shared/api"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
interface EditableModelSelectorProps {
models: Record<string, ModelInfo>
selectedModelId: string | undefined
onChange: (e: any) => void
label?: string
placeholder?: string
zIndex?: number
}
const Container = styled.div<{ $zIndex?: number }>`
position: relative;
z-index: ${(p) => p.$zIndex ?? 1000};
/* Force datalist dropdown to open downward */
& input::-webkit-calendar-picker-indicator {
opacity: 0.6;
cursor: pointer;
}
`
const Label = styled.label`
display: block;
margin-bottom: 4px;
span {
font-weight: 500;
font-size: var(--vscode-font-size, 13px);
color: var(--color-foreground);
}
`
const SelectWrapper = styled.div`
position: relative;
width: 100%;
`
const StyledInput = styled.input`
width: 100%;
box-sizing: border-box;
padding: 4px 28px 4px 8px;
height: 26px;
font-family: var(--font-base);
font-size: var(--vscode-font-size, 13px);
color: var(--color-input-foreground);
background-color: var(--color-input-background);
border: 1px solid var(--color-input-border);
border-radius: 2px;
outline: none;
&:focus {
border-color: var(--color-border);
}
&::placeholder {
color: var(--color-input-placeholder);
}
&::-webkit-calendar-picker-indicator {
position: absolute;
right: 6px;
top: 50%;
transform: translateY(-50%);
}
`
const ArrowIcon = styled.div`
position: absolute;
right: 8px;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
width: 0;
height: 0;
border-left: 4px solid transparent;
border-right: 4px solid transparent;
border-top: 5px solid var(--color-foreground, #cccccc);
opacity: 0.6;
`
export const EditableModelSelector = ({
models,
selectedModelId,
onChange,
label,
placeholder,
zIndex,
}: EditableModelSelectorProps) => {
const { t } = useTranslation("settings")
const labelValue = label ?? t("settings.model")
const placeholderValue = placeholder ?? t("settings.selectModel")
return (
<Container $zIndex={zIndex}>
<Label>
<span>{labelValue}</span>
</Label>
<SelectWrapper>
<StyledInput
list="editable-model-id-options"
onChange={(e) => onChange(e)}
placeholder={placeholderValue}
spellCheck={false}
type="text"
value={selectedModelId ?? ""}
/>
<ArrowIcon />
<datalist id="editable-model-id-options">
{Object.keys(models).map((modelId) => (
<option key={modelId} value={modelId} />
))}
</datalist>
</SelectWrapper>
</Container>
)
}
@@ -6,7 +6,11 @@ export function RemotelyConfiguredInputWrapper({ hidden, children }: React.Props
return (
<Tooltip>
<TooltipContent hidden={hidden}>{t("settings.remotelyConfiguredMessage")}</TooltipContent>
<TooltipTrigger>{children}</TooltipTrigger>
{/* asChild + block wrapper: without asChild, Radix renders a <button> which
shrinks to fit its content and collapses full-width inputs inside it. */}
<TooltipTrigger asChild>
<div style={{ display: "block", width: "100%" }}>{children}</div>
</TooltipTrigger>
</Tooltip>
)
}
@@ -6,8 +6,8 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ModelsServiceClient } from "@/services/grpc-client"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -92,7 +92,7 @@ export const AIhubmixProvider = ({ showModelOptions, isPopup, currentMode }: AIh
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={models}
onChange={(e) => {
@@ -6,8 +6,8 @@ import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { BaseUrlField } from "../common/BaseUrlField"
import { ContextWindowSwitcher } from "../common/ContextWindowSwitcher"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { RemotelyConfiguredInputWrapper } from "../common/RemotelyConfiguredInputWrapper"
import ReasoningEffortSelector from "../ReasoningEffortSelector"
import ThinkingBudgetSlider from "../ThinkingBudgetSlider"
@@ -79,7 +79,7 @@ export const AnthropicProvider = ({ showModelOptions, isPopup, currentMode }: An
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={anthropicModels}
onChange={(e) =>
@@ -5,8 +5,8 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { DebouncedTextField } from "../common/DebouncedTextField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -89,7 +89,7 @@ export const AskSageProvider = ({ showModelOptions, isPopup, currentMode }: AskS
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={availableModels}
onChange={(e) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -39,7 +39,7 @@ export const CerebrasProvider = ({ showModelOptions, isPopup, currentMode }: Cer
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={cerebrasModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { DebouncedTextField } from "../common/DebouncedTextField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import ThinkingBudgetSlider from "../ThinkingBudgetSlider"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -65,7 +65,7 @@ export const ClaudeCodeProvider = ({ showModelOptions, isPopup, currentMode }: C
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={claudeCodeModels}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) =>
@@ -4,8 +4,8 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { DebouncedTextField } from "../common/DebouncedTextField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -41,7 +41,7 @@ export const DeepSeekProvider = ({ showModelOptions, isPopup, currentMode }: Dee
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={deepSeekModels}
onChange={(e: any) => {
@@ -91,6 +91,70 @@ export const DeepSeekProvider = ({ showModelOptions, isPopup, currentMode }: Dee
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.maxOutputTokens")}</span>
</DebouncedTextField>
</div>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
<DebouncedTextField
initialValue={selectedModelInfo.inputPrice?.toString() ?? ""}
onChange={(value) => {
const modelInfo = deepSeekModelInfo ? { ...deepSeekModelInfo } : { ...selectedModelInfo }
modelInfo.inputPrice = value ? Number(value) : undefined
handleModeFieldChange(
{ plan: "planModeDeepSeekModelInfo", act: "actModeDeepSeekModelInfo" },
modelInfo,
currentMode,
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.inputPricePerMillion")}</span>
</DebouncedTextField>
<DebouncedTextField
initialValue={selectedModelInfo.outputPrice?.toString() ?? ""}
onChange={(value) => {
const modelInfo = deepSeekModelInfo ? { ...deepSeekModelInfo } : { ...selectedModelInfo }
modelInfo.outputPrice = value ? Number(value) : undefined
handleModeFieldChange(
{ plan: "planModeDeepSeekModelInfo", act: "actModeDeepSeekModelInfo" },
modelInfo,
currentMode,
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.outputPricePerMillion")}</span>
</DebouncedTextField>
</div>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
<DebouncedTextField
initialValue={selectedModelInfo.cacheWritesPrice?.toString() ?? ""}
onChange={(value) => {
const modelInfo = deepSeekModelInfo ? { ...deepSeekModelInfo } : { ...selectedModelInfo }
modelInfo.cacheWritesPrice = value ? Number(value) : undefined
handleModeFieldChange(
{ plan: "planModeDeepSeekModelInfo", act: "actModeDeepSeekModelInfo" },
modelInfo,
currentMode,
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.cacheWritesPricePerMillion")}</span>
</DebouncedTextField>
<DebouncedTextField
initialValue={selectedModelInfo.cacheReadsPrice?.toString() ?? ""}
onChange={(value) => {
const modelInfo = deepSeekModelInfo ? { ...deepSeekModelInfo } : { ...selectedModelInfo }
modelInfo.cacheReadsPrice = value ? Number(value) : undefined
handleModeFieldChange(
{ plan: "planModeDeepSeekModelInfo", act: "actModeDeepSeekModelInfo" },
modelInfo,
currentMode,
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.cacheReadsPricePerMillion")}</span>
</DebouncedTextField>
</div>
</>
)}
</div>
@@ -6,7 +6,6 @@ import { DebouncedTextField } from "../common/DebouncedTextField"
import { ModelInfoView } from "../common/ModelInfoView"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
import { useDebouncedInput } from "../utils/useDebouncedInput"
interface DifyProviderProps {
showModelOptions: boolean
@@ -19,15 +18,6 @@ export const DifyProvider = ({ showModelOptions, isPopup, currentMode }: DifyPro
const { apiConfiguration } = useExtensionState()
const { handleFieldChange } = useApiConfigurationHandlers()
// Use debounced input for proper state management
const [_baseUrlValue, _setBaseUrlValue] = useDebouncedInput(apiConfiguration?.difyBaseUrl || "", (value) =>
handleFieldChange("difyBaseUrl", value),
)
const [_apiKeyValue, _setApiKeyValue] = useDebouncedInput(apiConfiguration?.difyApiKey || "", (value) =>
handleFieldChange("difyApiKey", value),
)
// Get the normalized configuration
const { selectedModelId, selectedModelInfo } = normalizeApiConfiguration(apiConfiguration, currentMode)
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -39,7 +39,7 @@ export const DoubaoProvider = ({ showModelOptions, isPopup, currentMode }: Douba
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={doubaoModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -35,7 +35,7 @@ export const FireworksProvider = ({ currentMode, isPopup, showModelOptions }: Fi
providerName="Fireworks"
signupUrl="https://fireworks.ai/"
/>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={fireworksModels}
onChange={(e: any) => {
@@ -4,8 +4,8 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { BaseUrlField } from "../common/BaseUrlField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import ReasoningEffortSelector from "../ReasoningEffortSelector"
import { normalizeApiConfiguration, supportsReasoningEffortForModelId } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -49,7 +49,7 @@ export const GeminiProvider = ({ showModelOptions, isPopup, currentMode }: Gemin
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={geminiModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -31,7 +31,7 @@ export const HuaweiCloudMaasProvider = ({ showModelOptions, isPopup, currentMode
/>
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={huaweiCloudMaasModels}
onChange={(e: any) => {
@@ -4,8 +4,9 @@ import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { DropdownContainer, ModelSelector } from "../common/ModelSelector"
import { DropdownContainer } from "../common/ModelSelector"
import ThinkingBudgetSlider from "../ThinkingBudgetSlider"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -70,7 +71,7 @@ export const MinimaxProvider = ({ showModelOptions, isPopup, currentMode }: Mini
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={minimaxModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -39,7 +39,7 @@ export const MistralProvider = ({ showModelOptions, isPopup, currentMode }: Mist
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={mistralModels}
onChange={(e: any) =>
@@ -6,8 +6,9 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ModelsServiceClient } from "@/services/grpc-client"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { DropdownContainer, ModelSelector } from "../common/ModelSelector"
import { DropdownContainer } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
/**
@@ -84,7 +85,7 @@ export const MoonshotProvider = ({ showModelOptions, isPopup, currentMode }: Moo
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={moonshotModels}
onChange={async (e: any) => {
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -39,7 +39,7 @@ export const NebiusProvider = ({ showModelOptions, isPopup, currentMode }: Nebiu
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={nebiusModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -38,7 +38,7 @@ export const NousResearchProvider = ({ showModelOptions, isPopup, currentMode }:
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={nousResearchModels}
onChange={(e: any) =>
@@ -76,32 +76,32 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod
return (
<div>
<Tooltip>
<TooltipTrigger>
<div className="mb-2.5">
<div className="mb-2.5">
<Tooltip>
<TooltipTrigger>
<div className="flex items-center gap-2 mb-1">
<span style={{ fontWeight: 500 }}>{t("commonFields.baseUrl")}</span>
{remoteConfigSettings?.openAiBaseUrl !== undefined && (
<i className="codicon codicon-lock text-description text-sm" />
)}
</div>
<DebouncedTextField
disabled={remoteConfigSettings?.openAiBaseUrl !== undefined}
initialValue={apiConfiguration?.openAiBaseUrl || ""}
onChange={(value) => {
handleFieldChange("openAiBaseUrl", value)
debouncedRefreshOpenAiModels(value, apiConfiguration?.openAiApiKey)
}}
placeholder={t("commonFields.enterBaseUrl")}
style={{ width: "100%", marginBottom: 10 }}
type="text"
/>
</div>
</TooltipTrigger>
<TooltipContent hidden={remoteConfigSettings?.openAiBaseUrl === undefined}>
{t("settings.remotelyConfiguredMessage")}
</TooltipContent>
</Tooltip>
</TooltipTrigger>
<TooltipContent hidden={remoteConfigSettings?.openAiBaseUrl === undefined}>
{t("settings.remotelyConfiguredMessage")}
</TooltipContent>
</Tooltip>
<DebouncedTextField
disabled={remoteConfigSettings?.openAiBaseUrl !== undefined}
initialValue={apiConfiguration?.openAiBaseUrl || ""}
onChange={(value) => {
handleFieldChange("openAiBaseUrl", value)
debouncedRefreshOpenAiModels(value, apiConfiguration?.openAiApiKey)
}}
placeholder={t("commonFields.enterBaseUrl")}
style={{ width: "100%", marginBottom: 10 }}
type="text"
/>
</div>
<ApiKeyField
initialValue={apiConfiguration?.openAiApiKey || ""}
@@ -156,8 +156,8 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod
</div>
<div>
{headerEntries.map(([key, value], index) => (
<div key={index} style={{ display: "flex", gap: 5, marginTop: 5 }}>
{headerEntries.map(([key, value]) => (
<div key={key} style={{ display: "flex", gap: 5, marginTop: 5 }}>
<DebouncedTextField
disabled={remoteConfigSettings?.openAiHeaders !== undefined}
initialValue={key}
@@ -204,15 +204,17 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod
{remoteConfigSettings?.azureApiVersion !== undefined ? (
<Tooltip>
<TooltipTrigger>
<BaseUrlField
disabled={true}
initialValue={apiConfiguration?.azureApiVersion}
label={t("providers.openaiCompatible.setAzureApiVersion")}
onChange={(value) => handleFieldChange("azureApiVersion", value)}
placeholder={`Default: ${azureOpenAiDefaultApiVersion}`}
showLockIcon={true}
/>
<TooltipTrigger asChild>
<div style={{ display: "block", width: "100%" }}>
<BaseUrlField
disabled={true}
initialValue={apiConfiguration?.azureApiVersion}
label={t("providers.openaiCompatible.setAzureApiVersion")}
onChange={(value) => handleFieldChange("azureApiVersion", value)}
placeholder={`Default: ${azureOpenAiDefaultApiVersion}`}
showLockIcon={true}
/>
</div>
</TooltipTrigger>
<TooltipContent>This setting is managed by your organization's remote configuration</TooltipContent>
</Tooltip>
@@ -371,6 +373,42 @@ export const OpenAICompatibleProvider = ({ showModelOptions, isPopup, currentMod
</DebouncedTextField>
</div>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
<DebouncedTextField
initialValue={
openAiModelInfo?.cacheWritesPrice !== undefined ? openAiModelInfo.cacheWritesPrice.toString() : ""
}
onChange={(value) => {
const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults }
modelInfo.cacheWritesPrice = value ? parsePrice(value, 0) : undefined
handleModeFieldChange(
{ plan: "planModeOpenAiModelInfo", act: "actModeOpenAiModelInfo" },
modelInfo,
currentMode,
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.cacheWritesPricePerMillion")}</span>
</DebouncedTextField>
<DebouncedTextField
initialValue={
openAiModelInfo?.cacheReadsPrice !== undefined ? openAiModelInfo.cacheReadsPrice.toString() : ""
}
onChange={(value) => {
const modelInfo = openAiModelInfo ? openAiModelInfo : { ...openAiModelInfoSaneDefaults }
modelInfo.cacheReadsPrice = value ? parsePrice(value, 0) : undefined
handleModeFieldChange(
{ plan: "planModeOpenAiModelInfo", act: "actModeOpenAiModelInfo" },
modelInfo,
currentMode,
)
}}
style={{ flex: 1 }}>
<span style={{ fontWeight: 500 }}>{t("providers.openaiCompatible.cacheReadsPricePerMillion")}</span>
</DebouncedTextField>
</div>
<div style={{ display: "flex", gap: 10, marginTop: "5px" }}>
<DebouncedTextField
initialValue={
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import ReasoningEffortSelector from "../ReasoningEffortSelector"
import { normalizeApiConfiguration, supportsReasoningEffortForModelId } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -41,7 +41,7 @@ export const OpenAINativeProvider = ({ showModelOptions, isPopup, currentMode }:
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={openAiNativeModels}
onChange={(e: any) =>
@@ -4,8 +4,8 @@ import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { AccountServiceClient } from "@/services/grpc-client"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import ReasoningEffortSelector from "../ReasoningEffortSelector"
import { normalizeApiConfiguration, supportsReasoningEffortForModelId } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -73,7 +73,7 @@ export const OpenAiCodexProvider = ({ showModelOptions, isPopup, currentMode }:
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={openAiCodexModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -63,7 +63,7 @@ export const QwenCodeProvider = ({ showModelOptions, isPopup, currentMode }: Qwe
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={qwenCodeModels}
onChange={(modelId) => {
@@ -6,8 +6,9 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { DROPDOWN_Z_INDEX } from "../ApiOptions"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { DropdownContainer, ModelSelector } from "../common/ModelSelector"
import { DropdownContainer } from "../common/ModelSelector"
import ThinkingBudgetSlider from "../ThinkingBudgetSlider"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -94,7 +95,7 @@ export const QwenProvider = ({ showModelOptions, isPopup, currentMode }: QwenPro
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={qwenModels}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -39,7 +39,7 @@ export const SambanovaProvider = ({ showModelOptions, isPopup, currentMode }: Sa
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={sambanovaModels}
onChange={(e: any) =>
@@ -7,8 +7,8 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { DROPDOWN_Z_INDEX, DropdownContainer } from "../ApiOptions"
import { DebouncedTextField } from "../common/DebouncedTextField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { LockIcon, RemotelyConfiguredInputWrapper } from "../common/RemotelyConfiguredInputWrapper"
import ReasoningEffortSelector from "../ReasoningEffortSelector"
import ThinkingBudgetSlider from "../ThinkingBudgetSlider"
@@ -127,7 +127,7 @@ export const VertexProvider = ({ showModelOptions, isPopup, currentMode }: Verte
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={modelsToUse}
onChange={(e: any) =>
@@ -3,8 +3,8 @@ import { Mode } from "@shared/storage/types"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { ModelSelector } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -33,7 +33,7 @@ export const WandbProvider = ({ showModelOptions, isPopup, currentMode }: WandbP
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={wandbModels}
onChange={(e: any) =>
@@ -6,8 +6,9 @@ import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { DROPDOWN_Z_INDEX } from "../ApiOptions"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { DropdownContainer, ModelSelector } from "../common/ModelSelector"
import { DropdownContainer } from "../common/ModelSelector"
import { getModeSpecificFields, normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -57,7 +58,7 @@ export const XaiProvider = ({ showModelOptions, isPopup, currentMode }: XaiProvi
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={xaiModels}
onChange={(e: any) =>
@@ -5,8 +5,9 @@ import { useMemo } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ApiKeyField } from "../common/ApiKeyField"
import { EditableModelSelector } from "../common/EditableModelSelector"
import { ModelInfoView } from "../common/ModelInfoView"
import { DropdownContainer, ModelSelector } from "../common/ModelSelector"
import { DropdownContainer } from "../common/ModelSelector"
import { normalizeApiConfiguration } from "../utils/providerUtils"
import { useApiConfigurationHandlers } from "../utils/useApiConfigurationHandlers"
@@ -75,7 +76,7 @@ export const ZAiProvider = ({ showModelOptions, isPopup, currentMode }: ZAiProvi
{showModelOptions && (
<>
<ModelSelector
<EditableModelSelector
label={t("settings.model")}
models={zaiModels}
onChange={(e: any) =>
@@ -15,6 +15,14 @@ interface BrowserSettingsSectionProps {
renderSectionHeader: (tabId: string) => JSX.Element | null
}
// Viewport preset display labels (Chinese), the value remains the English preset name
const VIEWPORT_PRESET_LABELS: Record<string, string> = {
"Large Desktop (1280x800)": "大桌面 (1280x800)",
"Small Desktop (900x600)": "小桌面 (900x600)",
"Tablet (768x1024)": "平板 (768x1024)",
"Mobile (360x640)": "手机 (360x640)",
}
const ConnectionStatusIndicator = ({
isChecking,
isConnected,
@@ -149,7 +157,7 @@ export const BrowserSettingsSection: React.FC<BrowserSettingsSectionProps> = ({
console.error("Error relaunching Chrome:", error)
setRelaunchResult({
success: false,
message: `Error relaunching Chrome: ${error.message}`,
message: t("settingsSections.relaunchError", { message: error.message }),
})
setDebugMode(false)
})
@@ -204,7 +212,7 @@ export const BrowserSettingsSection: React.FC<BrowserSettingsSectionProps> = ({
}>
{Object.entries(BROWSER_VIEWPORT_PRESETS).map(([name]) => (
<VSCodeOption key={name} value={name}>
{name}
{VIEWPORT_PRESET_LABELS[name] ?? name}
</VSCodeOption>
))}
</VSCodeDropdown>
@@ -259,18 +267,16 @@ export const BrowserSettingsSection: React.FC<BrowserSettingsSectionProps> = ({
: detectedChromePath
? ` (${detectedChromePath})`
: ""}
. You can specify a custom path below. Using a remote browser connection requires starting Chrome
in debug mode
{t("settingsSections.remoteBrowserCustomPathHint")}
{browserSettings.remoteBrowserEnabled ? (
<>
{" "}
{t("settingsSections.remoteBrowserDebugManually")} (
<code>--remote-debugging-port=9222</code>) or using the button below. Enter the host
address or leave it blank for automatic discovery.
{t("settingsSections.remoteBrowserDebugHint")}
<code>--remote-debugging-port=9222</code>
{t("settingsSections.remoteBrowserDebugManually")}
{t("settingsSections.remoteBrowserHostHint")}
</>
) : (
"."
)}
) : null}
</p>
{/* Moved remote-specific settings to appear directly after enabling remote connection */}
{browserSettings.remoteBrowserEnabled && (
@@ -337,7 +343,7 @@ export const BrowserSettingsSection: React.FC<BrowserSettingsSectionProps> = ({
id="chrome-executable-path"
initialValue={browserSettings.chromeExecutablePath || ""}
onChange={(value) => updateSetting("browserSettings", { chromeExecutablePath: value })}
placeholder="e.g., /usr/bin/google-chrome or C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"
placeholder={t("settingsSections.browser.chromePathPlaceholder")}
style={{ width: "100%" }}
/>
<p
@@ -360,7 +366,7 @@ export const BrowserSettingsSection: React.FC<BrowserSettingsSectionProps> = ({
id="custom-browser-args"
initialValue={browserSettings.customArgs || ""}
onChange={(value) => updateSetting("browserSettings", { customArgs: value })}
placeholder="e.g., --no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu --no-first-run --no-zygote"
placeholder={t("settingsSections.browser.customArgsPlaceholder")}
style={{ width: "100%" }}
/>
<p
@@ -16,12 +16,12 @@ const DebugSection = ({ onResetState, renderSectionHeader }: DebugSectionProps)
<div>
{renderSectionHeader("debug")}
<Section>
<Button onClick={() => onResetState()} variant="error">
Reset Workspace State
</Button>
<Button onClick={() => onResetState(true)} variant="error">
Reset Global State
</Button>
<Button onClick={() => onResetState()} variant="error">
重置工作区状态
</Button>
<Button onClick={() => onResetState(true)} variant="error">
重置全局状态
</Button>
<p className="text-xs mt-[5px] text-(--vscode-descriptionForeground)">
{t("settingsSections.resetStateDescription")}
</p>
@@ -34,7 +34,7 @@ const DebugSection = ({ onResetState, renderSectionHeader }: DebugSectionProps)
.finally(() => setShowWelcome(true))
}
variant="secondary">
Reset Onboarding State
重置引导状态
</Button>
</Section>
</div>
@@ -59,7 +59,7 @@ function RefreshButton() {
className={`w-full rounded-xs ${isLoading ? "animate-pulse" : ""}`}
disabled={isLoading || (retryIn !== null && retryIn > 0)}
onClick={() => onRefresh()}>
Refresh {retryIn && retryIn > 0 && <>(Retry in: {retryIn} seconds)</>}
刷新 {retryIn && retryIn > 0 && <>({retryIn} 秒后可重试)</>}
</VSCodeButton>
)
}
@@ -182,7 +182,7 @@ function OtelSettingsSection() {
<div className="mb-4">
<h4 className="text-sm font-medium mb-2 flex items-center gap-2">
<i className="codicon codicon-pulse" />
OpenTelemetry Configuration
OpenTelemetry 配置
</h4>
<div className="bg-vscode-textBlockQuote-background rounded p-3 mb-2">
<SettingRow label={t("remoteConfig.otelEnabled")} value={otelEnabled} />
@@ -271,7 +271,7 @@ function PromptUploadingSection() {
<div className="mb-4">
<h4 className="text-sm font-medium mb-2 flex items-center gap-2">
<i className="codicon codicon-cloud-upload" />
Prompt Uploading Configuration
提示词上传配置
</h4>
<div className="bg-vscode-textBlockQuote-background rounded p-3 mb-2">
<SettingRow label={t("remoteConfig.storageType")} value={blobStoreConfig.adapterType?.toUpperCase()} />
@@ -325,11 +325,11 @@ export function RemoteConfigSection({ renderSectionHeader }: RemoteConfigSection
<BaseRemoteConfigSection renderSectionHeader={renderSectionHeader}>
<div className="flex flex-col justify-center gap-4">
<h3>
You haven't configured remote config yet. Do so through our{" "}
您尚未配置远程配置。请前往{" "}
<VSCodeLink href="https://app.cline.bot/dashboard/organization?tab=settings">
{t("remoteConfig.dashboard")}
</VSCodeLink>
.
进行设置。
</h3>
<RefreshButton />
@@ -183,6 +183,17 @@ export function normalizeApiConfiguration(
if (modelId && modelId in models) {
selectedModelId = modelId
selectedModelInfo = models[modelId]
} else if (modelId) {
// Custom model ID - use it with sane defaults
selectedModelId = modelId
selectedModelInfo = {
maxTokens: 8192,
contextWindow: 128_000,
supportsImages: false,
supportsPromptCache: false,
inputPrice: 0,
outputPrice: 0,
}
} else {
selectedModelId = defaultId
selectedModelInfo = models[defaultId]
@@ -5,31 +5,48 @@ import { Mode } from "@shared/storage/types"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { ModelsServiceClient } from "@/services/grpc-client"
/**
* Serializes configuration saves so rapid successive updates can't race each other.
* Without this, an older save can resolve after a newer one and overwrite the newer
* value on the backend, which then echoes the stale value back into the webview
* (visible as scrambled/garbled text in input fields).
*/
let configSaveQueue: Promise<unknown> = Promise.resolve()
function enqueueConfigSave(save: () => Promise<unknown>): Promise<unknown> {
const next = configSaveQueue.then(save, save)
// Keep the chain alive even if a save rejects
configSaveQueue = next.catch(() => {})
return next
}
export const useApiConfigurationHandlers = () => {
const { apiConfiguration, planActSeparateModelsSetting } = useExtensionState()
/**
* Updates a single field in the API configuration.
*
* **Warning**: If this function is called multiple times in rapid succession,
* it can lead to race conditions where later calls may overwrite changes from
* earlier calls. For updating multiple fields, use `handleFieldsChange` instead.
* Calls are serialized through a queue so rapid successive updates are applied
* to the backend in the order they were made. Each save always builds on the
* latest config state available at call time.
*
* @param field - The field key to update
* @param value - The new value for the field
*/
const handleFieldChange = async <K extends keyof ApiConfiguration>(field: K, value: ApiConfiguration[K]) => {
const updatedConfig = {
...apiConfiguration,
[field]: value,
}
await enqueueConfigSave(async () => {
const updatedConfig = {
...apiConfiguration,
[field]: value,
}
const protoConfig = convertApiConfigurationToProto(updatedConfig)
await ModelsServiceClient.updateApiConfigurationProto(
UpdateApiConfigurationRequest.create({
apiConfiguration: protoConfig,
}),
)
const protoConfig = convertApiConfigurationToProto(updatedConfig)
await ModelsServiceClient.updateApiConfigurationProto(
UpdateApiConfigurationRequest.create({
apiConfiguration: protoConfig,
}),
)
})
}
/**
@@ -42,17 +59,19 @@ export const useApiConfigurationHandlers = () => {
* @param updates - An object containing the fields to update and their new values
*/
const handleFieldsChange = async (updates: Partial<ApiConfiguration>) => {
const updatedConfig = {
...apiConfiguration,
...updates,
}
await enqueueConfigSave(async () => {
const updatedConfig = {
...apiConfiguration,
...updates,
}
const protoConfig = convertApiConfigurationToProto(updatedConfig)
await ModelsServiceClient.updateApiConfigurationProto(
UpdateApiConfigurationRequest.create({
apiConfiguration: protoConfig,
}),
)
const protoConfig = convertApiConfigurationToProto(updatedConfig)
await ModelsServiceClient.updateApiConfigurationProto(
UpdateApiConfigurationRequest.create({
apiConfiguration: protoConfig,
}),
)
})
}
const handleModeFieldChange = async <PlanK extends keyof ApiConfiguration, ActK extends keyof ApiConfiguration>(
@@ -1,13 +1,28 @@
import { useEffect, useRef, useState } from "react"
import { useDebounceEffect } from "@/utils/useDebounceEffect"
import { useCallback, useEffect, useRef, useState } from "react"
/**
* Grace period (ms) after a local edit during which unrecognized external value updates
* are deferred, so an unexpected state broadcast can't overwrite text the user just typed.
* Covers the debounce window plus the backend save round-trip.
*/
const EDIT_GRACE_PERIOD_MS = 1000
/**
* A custom hook that provides debounced input handling to prevent jumpy text inputs
* when saving changes directly to backend on every keystroke.
*
* The debounced save is echoed back through the extension state as a new `initialValue`.
* To keep typing stable, this hook:
* 1. Never saves on mount (the initial value is already persisted) and flushes any
* uncommitted edit immediately on unmount, so rapid field/tab switches can't lose text.
* 2. Ignores echoes of values we committed ourselves (echoing an older value back into
* the input mid-typing was garbling/scrambling the text).
* 3. Defers unrecognized external updates for a short grace period after the last local
* edit, then applies the latest one only if the user has no uncommitted changes.
*
* @param initialValue - The initial value for the input
* @param onChange - Callback function to save the value (e.g., to backend)
* @param debounceMs - Debounce delay in milliseconds (default: 500ms)
* @param debounceMs - Debounce delay in milliseconds (default: 100ms)
* @returns A tuple of [currentValue, setValue] similar to useState
*/
export function useDebouncedInput<T>(initialValue: T, onChange: (value: T) => void, debounceMs = 100): [T, (value: T) => void] {
@@ -15,24 +30,120 @@ export function useDebouncedInput<T>(initialValue: T, onChange: (value: T) => vo
const [localValue, setLocalValue] = useState(initialValue)
// Track previous initialValue to detect external changes
const prevInitialValueRef = useRef<T>(initialValue)
const prevInitialValueRef = useRef(initialValue)
// Always-fresh views for use inside timers and the unmount flush
const latestInitialValueRef = useRef(initialValue)
latestInitialValueRef.current = initialValue
const latestLocalValueRef = useRef(localValue)
latestLocalValueRef.current = localValue
const onChangeRef = useRef(onChange)
onChangeRef.current = onChange
const debounceMsRef = useRef(debounceMs)
debounceMsRef.current = debounceMs
// Values committed via the debounced onChange that haven't been echoed back yet.
// Echoes of our own saves must never be written back into the input.
const pendingEchoesRef = useRef<Set<T>>(new Set())
// Last value committed through the debounced save, used to detect uncommitted edits
const lastCommittedValueRef = useRef(initialValue)
// Timestamp of the last local edit, used to protect in-flight typing from external overwrites
const lastEditTimeRef = useRef(0)
const saveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const deferredSyncTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const scheduleSave = useCallback(() => {
if (saveTimerRef.current) {
clearTimeout(saveTimerRef.current)
}
saveTimerRef.current = setTimeout(() => {
saveTimerRef.current = null
const value = latestLocalValueRef.current
lastCommittedValueRef.current = value
pendingEchoesRef.current.add(value)
onChangeRef.current(value)
}, debounceMsRef.current)
}, [])
const setValue = useCallback(
(value: T) => {
lastEditTimeRef.current = Date.now()
setLocalValue(value)
scheduleSave()
},
[scheduleSave],
)
// Sync local state when initialValue changes externally (e.g., when switching Plan/Act tabs)
useEffect(() => {
if (prevInitialValueRef.current !== initialValue) {
if (prevInitialValueRef.current === initialValue) {
return
}
prevInitialValueRef.current = initialValue
// Ignore the echo of our own debounced save
if (pendingEchoesRef.current.has(initialValue)) {
pendingEchoesRef.current.delete(initialValue)
return
}
// Genuinely external change (e.g. Plan/Act switch, remote config): stale pending
// echoes are no longer meaningful, and if the user isn't mid-edit we can apply it now.
pendingEchoesRef.current.clear()
const sinceEditMs = Date.now() - lastEditTimeRef.current
if (sinceEditMs >= EDIT_GRACE_PERIOD_MS) {
lastCommittedValueRef.current = initialValue
setLocalValue(initialValue)
prevInitialValueRef.current = initialValue
return
}
// The user just typed: defer applying the external value until the grace period ends
// so an unexpected broadcast can't clobber in-flight keystrokes.
deferredSyncTimerRef.current = setTimeout(() => {
deferredSyncTimerRef.current = null
const current = latestLocalValueRef.current
const externalValue = latestInitialValueRef.current
// Take the latest external value only once the user's edits have settled
// (i.e. there is no uncommitted edit pending).
if (current === lastCommittedValueRef.current) {
lastCommittedValueRef.current = externalValue
setLocalValue(externalValue)
}
}, EDIT_GRACE_PERIOD_MS - sinceEditMs)
return () => {
if (deferredSyncTimerRef.current) {
clearTimeout(deferredSyncTimerRef.current)
deferredSyncTimerRef.current = null
}
}
}, [initialValue])
// Debounced backend save - saves after user stops changing value
useDebounceEffect(
() => {
onChange(localValue)
},
debounceMs,
[localValue],
)
// Flush any uncommitted edit on unmount - the debounce timer alone would silently
// drop the user's last keystrokes when the field is removed (e.g. switching providers).
useEffect(() => {
return () => {
if (saveTimerRef.current) {
clearTimeout(saveTimerRef.current)
saveTimerRef.current = null
}
if (deferredSyncTimerRef.current) {
clearTimeout(deferredSyncTimerRef.current)
deferredSyncTimerRef.current = null
}
const value = latestLocalValueRef.current
if (value !== lastCommittedValueRef.current) {
onChangeRef.current(value)
}
}
}, [])
return [localValue, setLocalValue]
return [localValue, setValue]
}
@@ -0,0 +1,171 @@
import { useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
type ModelStats = {
requests: number
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
}
type ModelStatsTableProps = {
modelStats: Map<string, ModelStats>
isLoading?: boolean
}
function formatNumber(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(2) + "M"
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + "K"
}
return num.toLocaleString()
}
function formatCost(cost: number): string {
return "$" + cost.toFixed(4)
}
export const ModelStatsTable = ({ modelStats, isLoading }: ModelStatsTableProps) => {
const { t } = useTranslation("settings")
const [sortField, setSortField] = useState<"requests" | "tokens" | "cost">("tokens")
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("desc")
const sortedModels = useMemo(() => {
const models = Array.from(modelStats.entries()).map(([name, stats]) => ({
name,
...stats,
totalTokens: stats.tokensIn + stats.tokensOut,
}))
models.sort((a, b) => {
let aVal: number, bVal: number
switch (sortField) {
case "requests":
aVal = a.requests
bVal = b.requests
break
case "tokens":
aVal = a.totalTokens
bVal = b.totalTokens
break
case "cost":
aVal = a.cost
bVal = b.cost
break
default:
aVal = a.totalTokens
bVal = b.totalTokens
}
return sortDirection === "desc" ? bVal - aVal : aVal - bVal
})
return models
}, [modelStats, sortField, sortDirection])
const handleSort = (field: "requests" | "tokens" | "cost") => {
if (sortField === field) {
setSortDirection(sortDirection === "desc" ? "asc" : "desc")
} else {
setSortField(field)
setSortDirection("desc")
}
}
const SortIcon = ({ field }: { field: string }) => {
if (sortField !== field) return <span className="ml-1 text-[var(--vscode-descriptionForeground)]">↕</span>
return <span className="ml-1 text-[var(--vscode-foreground)]">{sortDirection === "desc" ? "↓" : "↑"}</span>
}
return (
<div className="bg-[var(--vscode-editorWidget-background)] border border-[var(--vscode-widget-border)] rounded-lg overflow-hidden">
<h3 className="text-lg font-semibold text-[var(--vscode-foreground)] p-6 pb-4">{t("usageStats.modelStats")}</h3>
{sortedModels.length === 0 ? (
<div className="text-center text-[var(--vscode-descriptionForeground)] py-8">
{isLoading ? t("usageStats.loading") : t("usageStats.noData")}
</div>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="border-b border-[var(--vscode-widget-border)]">
<th className="text-left p-4 text-[var(--vscode-descriptionForeground)] font-medium">
{t("usageStats.tableHeaders.model")}
</th>
<th
className="text-right p-4 text-[var(--vscode-descriptionForeground)] font-medium cursor-pointer hover:text-[var(--vscode-foreground)]"
onClick={() => handleSort("requests")}>
{t("usageStats.tableHeaders.requests")}
<SortIcon field="requests" />
</th>
<th className="text-right p-4 text-[var(--vscode-descriptionForeground)] font-medium">
{t("usageStats.tableHeaders.cacheWrites")}
</th>
<th className="text-right p-4 text-[var(--vscode-descriptionForeground)] font-medium">
{t("usageStats.tableHeaders.cacheReads")}
</th>
<th
className="text-right p-4 text-[var(--vscode-descriptionForeground)] font-medium cursor-pointer hover:text-[var(--vscode-foreground)]"
onClick={() => handleSort("tokens")}>
{t("usageStats.tableHeaders.tokens")}
<SortIcon field="tokens" />
</th>
<th
className="text-right p-4 text-[var(--vscode-descriptionForeground)] font-medium cursor-pointer hover:text-[var(--vscode-foreground)]"
onClick={() => handleSort("cost")}>
{t("usageStats.tableHeaders.totalCost")}
<SortIcon field="cost" />
</th>
<th className="text-right p-4 text-[var(--vscode-descriptionForeground)] font-medium">
{t("usageStats.tableHeaders.avgCost")}
</th>
</tr>
</thead>
<tbody>
{sortedModels.map((model) => (
<tr
className="border-b border-[var(--vscode-widget-border)] last:border-0 hover:bg-[var(--vscode-list-hoverBackground)]"
key={model.name}>
<td className="p-4 text-[var(--vscode-foreground)] font-medium">{model.name}</td>
<td className="p-4 text-right text-[var(--vscode-foreground)]">{model.requests}</td>
<td className="p-4 text-right text-[var(--vscode-foreground)]">
{formatNumber(model.cacheWrites)}
</td>
<td className="p-4 text-right text-[var(--vscode-foreground)]">
{formatNumber(model.cacheReads)}
</td>
<td className="p-4 text-right text-[var(--vscode-foreground)]">
{formatNumber(model.totalTokens)}
</td>
<td
className="p-4 text-right text-[var(--vscode-foreground)]"
title={[
`${t("usageStats.costBreakdown.input")}: ${formatCost(model.inputCost)}`,
`${t("usageStats.costBreakdown.cacheWrites")}: ${formatCost(model.cacheWritesCost)}`,
`${t("usageStats.costBreakdown.cacheReads")}: ${formatCost(model.cacheReadsCost)}`,
`${t("usageStats.costBreakdown.output")}: ${formatCost(model.outputCost)}`,
].join("\n")}>
{formatCost(model.cost)}
</td>
<td className="p-4 text-right text-[var(--vscode-foreground)]">
{model.requests > 0 ? formatCost(model.cost / model.requests) : "$0.0000"}
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
)
}
export default ModelStatsTable
@@ -0,0 +1,180 @@
import { StringRequest } from "@shared/proto/cline/common"
import type { UsageTimeRange } from "@shared/usage-stats"
import { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { StateServiceClient } from "@/services/grpc-client"
import ViewHeader from "../common/ViewHeader"
import { ModelStatsTable } from "./ModelStatsTable"
import { UsageSummaryCard } from "./UsageSummaryCard"
import { UsageTrendChart } from "./UsageTrendChart"
type UsageStatsViewProps = {
onDone: () => void
}
export type CostBreakdown = {
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
}
export type UsageStatsData = {
totalTokensIn: number
totalTokensOut: number
totalCacheWrites: number
totalCacheReads: number
totalCost: number
costBreakdown: CostBreakdown
totalRequests: number
totalTasks: number
modelStats: Map<
string,
{
requests: number
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
}
>
trend: Array<{
key: string
label: string
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
inputCost: number
outputCost: number
cacheWritesCost: number
cacheReadsCost: number
}>
}
const EMPTY_STATS: UsageStatsData = {
totalTokensIn: 0,
totalTokensOut: 0,
totalCacheWrites: 0,
totalCacheReads: 0,
totalCost: 0,
costBreakdown: { inputCost: 0, outputCost: 0, cacheWritesCost: 0, cacheReadsCost: 0 },
totalRequests: 0,
totalTasks: 0,
modelStats: new Map(),
trend: [],
}
const TIME_RANGES: UsageTimeRange[] = ["today", "week", "month", "all"]
export const UsageStatsView = ({ onDone }: UsageStatsViewProps) => {
const { t } = useTranslation("settings")
// taskHistory updates (e.g. after every API request finishes) trigger a refresh,
// so stats stay up to date while the view is open.
const { environment, taskHistory = [] } = useExtensionState()
const [timeRange, setTimeRange] = useState<UsageTimeRange>("all")
const [statsData, setStatsData] = useState<UsageStatsData>(EMPTY_STATS)
const [isLoading, setIsLoading] = useState(true)
const statsVersion = useMemo(() => {
// Bump whenever the underlying history changes so effects can re-run
const last = taskHistory[0]
return `${taskHistory.length}:${last?.ts ?? 0}:${last?.totalCost ?? 0}:${last?.tokensIn ?? 0}:${last?.tokensOut ?? 0}`
}, [taskHistory])
const fetchStats = useCallback(async (range: UsageTimeRange) => {
setIsLoading(true)
try {
const response = await StateServiceClient.getUsageStats(StringRequest.create({ value: range }))
if (!response.usageJson) {
setStatsData(EMPTY_STATS)
return
}
const parsed = JSON.parse(response.usageJson)
setStatsData({
totalTokensIn: parsed.totals?.tokensIn ?? 0,
totalTokensOut: parsed.totals?.tokensOut ?? 0,
totalCacheWrites: parsed.totals?.cacheWrites ?? 0,
totalCacheReads: parsed.totals?.cacheReads ?? 0,
totalCost: parsed.totals?.cost ?? 0,
costBreakdown: {
inputCost: parsed.totals?.inputCost ?? 0,
outputCost: parsed.totals?.outputCost ?? 0,
cacheWritesCost: parsed.totals?.cacheWritesCost ?? 0,
cacheReadsCost: parsed.totals?.cacheReadsCost ?? 0,
},
totalRequests: parsed.totals?.requests ?? 0,
totalTasks: parsed.totals?.tasks ?? 0,
modelStats: new Map(parsed.modelStats ?? []),
trend: parsed.trend ?? [],
})
} catch (error) {
console.error("Failed to load usage stats:", error)
} finally {
setIsLoading(false)
}
}, [])
// Use a ref so refreshes caused by state pushes don't re-create the fetch callback
const fetchStatsRef = useRef(fetchStats)
fetchStatsRef.current = fetchStats
useEffect(() => {
fetchStatsRef.current(timeRange)
}, [timeRange, statsVersion])
const handleTimeRangeChange = useCallback((range: UsageTimeRange) => {
setTimeRange(range)
}, [])
return (
<div className="fixed inset-0 flex flex-col overflow-hidden">
<ViewHeader environment={environment} onDone={onDone} title={t("usageStats.title")} />
<div className="flex-1 overflow-y-auto px-5 pb-6">
{/* Time Range Selector */}
<div className="flex gap-2 mb-6">
{TIME_RANGES.map((range) => (
<button
className={`px-3 py-1.5 rounded text-sm ${
timeRange === range
? "bg-[var(--vscode-button-background)] text-[var(--vscode-button-foreground)]"
: "bg-[var(--vscode-input-background)] text-[var(--vscode-foreground)] hover:bg-[var(--vscode-inputOption-activeBackground)]"
}`}
key={range}
onClick={() => handleTimeRangeChange(range)}>
{t(`usageStats.timeRange.${range}`)}
</button>
))}
</div>
{/* Summary Cards */}
<UsageSummaryCard
costBreakdown={statsData.costBreakdown}
isLoading={isLoading}
totalCacheReads={statsData.totalCacheReads}
totalCost={statsData.totalCost}
totalRequests={statsData.totalRequests}
totalTokens={statsData.totalTokensIn + statsData.totalTokensOut}
totalTokensIn={statsData.totalTokensIn}
totalTokensOut={statsData.totalTokensOut}
/>
{/* Usage Trend Chart */}
<UsageTrendChart isLoading={isLoading} timeRange={timeRange} trend={statsData.trend} />
{/* Model Statistics Table */}
<ModelStatsTable isLoading={isLoading} modelStats={statsData.modelStats} />
</div>
</div>
)
}
export default UsageStatsView
@@ -0,0 +1,163 @@
import { useTranslation } from "react-i18next"
import type { CostBreakdown } from "./UsageStatsView"
type UsageSummaryCardProps = {
totalTokens: number
totalTokensIn: number
totalTokensOut: number
totalCacheReads: number
totalCost: number
costBreakdown: CostBreakdown
totalRequests: number
isLoading?: boolean
}
function formatNumber(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(2) + "M"
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + "K"
}
return num.toLocaleString()
}
function formatCost(cost: number): string {
return "$" + cost.toFixed(4)
}
export const UsageSummaryCard = ({
totalTokens,
totalTokensIn,
totalTokensOut,
totalCacheReads,
totalCost,
costBreakdown,
totalRequests,
isLoading,
}: UsageSummaryCardProps) => {
const { t } = useTranslation("settings")
// Calculate cache hit rate based on input tokens
const cacheHitRate = totalTokensIn > 0 ? (totalCacheReads / totalTokensIn) * 100 : 0
// Cost breakdown by pricing component (input / cache writes / cache reads / output)
const costComponents = [
{ key: "inputCost", label: t("usageStats.costBreakdown.input"), value: costBreakdown.inputCost, color: "#3b82f6" },
{
key: "cacheWritesCost",
label: t("usageStats.costBreakdown.cacheWrites"),
value: costBreakdown.cacheWritesCost,
color: "#f97316",
},
{
key: "cacheReadsCost",
label: t("usageStats.costBreakdown.cacheReads"),
value: costBreakdown.cacheReadsCost,
color: "#8b5cf6",
},
{ key: "outputCost", label: t("usageStats.costBreakdown.output"), value: costBreakdown.outputCost, color: "#22c55e" },
]
const costTotal = costComponents.reduce((acc, c) => acc + c.value, 0)
return (
<div className="bg-[var(--vscode-editorWidget-background)] border border-[var(--vscode-widget-border)] rounded-lg p-6 mb-6">
{/* Top row: Total tokens + Total requests + Total cost */}
<div className="flex items-center gap-4 mb-4">
<div className="flex items-center gap-3">
<div className="w-10 h-10 rounded-full bg-[var(--vscode-primediffEditor-insertedTextBackground)] flex items-center justify-center">
<span className="text-lg">⚡</span>
</div>
<div>
<div className="text-sm text-[var(--vscode-descriptionForeground)]">{t("usageStats.tokensConsumed")}</div>
<div className="text-3xl font-bold text-[var(--vscode-foreground)]">
{isLoading ? "..." : formatNumber(totalTokens)}
</div>
</div>
</div>
<div className="ml-auto flex items-center gap-6">
<div className="text-right">
<div className="text-sm text-[var(--vscode-descriptionForeground)]">{t("usageStats.totalRequests")}</div>
<div className="text-xl font-semibold text-[var(--vscode-foreground)]">
{isLoading ? "..." : totalRequests}
</div>
</div>
{/* Divider line */}
<div className="h-10 w-px bg-[var(--vscode-widget-border)] opacity-50" />
<div className="text-right">
<div className="text-sm text-[var(--vscode-descriptionForeground)]">{t("usageStats.totalCost")}</div>
<div className="text-xl font-semibold text-[var(--vscode-foreground)]">
{isLoading ? "..." : formatCost(totalCost)}
</div>
</div>
</div>
</div>
{/* Cost breakdown by pricing component: input / cache writes / cache reads / output */}
{!isLoading && costTotal > 0 && (
<div className="mb-4">
<div className="flex justify-between text-sm mb-1">
<span className="text-[var(--vscode-descriptionForeground)]">{t("usageStats.costBreakdown.title")}</span>
</div>
<div className="flex h-2.5 rounded-full overflow-hidden bg-[var(--vscode-editor-background)]">
{costComponents.map(
(component) =>
component.value > 0 && (
<div
className="h-full"
key={component.key}
style={{
width: `${(component.value / costTotal) * 100}%`,
backgroundColor: component.color,
}}
title={`${component.label}: ${formatCost(component.value)}`}
/>
),
)}
</div>
<div className="flex flex-wrap gap-x-4 gap-y-1 mt-1.5 text-xs">
{costComponents.map((component) => (
<div className="flex items-center gap-1.5" key={`${component.key}-legend`}>
<span className="inline-block w-2 h-2 rounded-sm" style={{ backgroundColor: component.color }} />
<span className="text-[var(--vscode-descriptionForeground)]">{component.label}</span>
<span className="text-[var(--vscode-foreground)] font-medium">{formatCost(component.value)}</span>
</div>
))}
</div>
</div>
)}
{/* Middle row: Input / Output / Cache Hits - three columns */}
<div className="grid grid-cols-3 gap-4 mb-4">
<div className="bg-[var(--vscode-editor-background)] rounded-lg p-4">
<div className="text-sm text-[var(--vscode-descriptionForeground)] mb-1">↓ {t("usageStats.input")}</div>
<div className="text-xl font-semibold text-[var(--vscode-foreground)]">{formatNumber(totalTokensIn)}</div>
</div>
<div className="bg-[var(--vscode-editor-background)] rounded-lg p-4">
<div className="text-sm text-[var(--vscode-descriptionForeground)] mb-1">↑ {t("usageStats.output")}</div>
<div className="text-xl font-semibold text-[var(--vscode-foreground)]">{formatNumber(totalTokensOut)}</div>
</div>
<div className="bg-[var(--vscode-editor-background)] rounded-lg p-4">
<div className="text-sm text-[var(--vscode-descriptionForeground)] mb-1">🎯 {t("usageStats.cacheHits")}</div>
<div className="text-xl font-semibold text-[var(--vscode-foreground)]">{formatNumber(totalCacheReads)}</div>
</div>
</div>
{/* Cache hit rate bar */}
<div>
<div className="flex justify-between text-sm mb-1">
<span className="text-[var(--vscode-descriptionForeground)]">{t("usageStats.cacheHitRate")}</span>
<span className="text-[var(--vscode-foreground)] font-medium">{cacheHitRate.toFixed(1)}%</span>
</div>
<div className="h-2.5 bg-[var(--vscode-editor-background)] rounded-full overflow-hidden">
<div
className="h-full bg-green-500 transition-all duration-300"
style={{ width: `${Math.min(cacheHitRate, 100)}%` }}
/>
</div>
</div>
</div>
)
}
export default UsageSummaryCard
@@ -0,0 +1,278 @@
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
import type { UsageTimeRange } from "@shared/usage-stats"
type TrendBucket = {
key: string
label: string
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
}
type UsageTrendChartProps = {
trend: TrendBucket[]
timeRange: UsageTimeRange
isLoading?: boolean
}
function formatNumber(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + "M"
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + "K"
}
return num.toString()
}
export const UsageTrendChart = ({ trend, timeRange, isLoading }: UsageTrendChartProps) => {
const { t } = useTranslation("settings")
const chartData = trend
// Pick calendar-aligned tick labels so the x-axis matches real dates/hours
const xAxisLabels = useMemo(() => {
if (chartData.length === 0) {
return []
}
if (timeRange === "today") {
// every 2 hours
return chartData.filter((_, i) => i % 2 === 0).map((d) => d.label)
}
const total = chartData.length
if (total <= 7) {
return chartData.map((d) => d.label)
}
// ~10 evenly spaced calendar ticks
const step = Math.max(1, Math.ceil(total / 10))
const labels: string[] = []
for (let i = 0; i < total; i += step) {
labels.push(chartData[i].label)
}
return labels
}, [chartData, timeRange])
const maxValue = useMemo(() => {
if (chartData.length === 0) return 1000000
return Math.max(...chartData.map((d) => d.tokensIn + d.tokensOut + d.cacheReads)) * 1.1 || 1000000
}, [chartData])
const maxCost = useMemo(() => {
if (chartData.length === 0) return 1
return Math.max(...chartData.map((d) => d.cost)) * 1.1 || 1
}, [chartData])
if (isLoading || chartData.length === 0) {
return (
<div className="bg-[var(--vscode-editorWidget-background)] border border-[var(--vscode-widget-border)] rounded-lg p-6 mb-6">
<h3 className="text-lg font-semibold text-[var(--vscode-foreground)] mb-4">{t("usageStats.usageTrend")}</h3>
<div className="text-center text-[var(--vscode-descriptionForeground)] py-8">
{isLoading ? t("usageStats.loading") : t("usageStats.noData")}
</div>
</div>
)
}
return (
<div className="bg-[var(--vscode-editorWidget-background)] border border-[var(--vscode-widget-border)] rounded-lg p-6 mb-6">
<h3 className="text-lg font-semibold text-[var(--vscode-foreground)] mb-4">{t("usageStats.usageTrend")}</h3>
<div className="w-full" style={{ height: "220px" }}>
<svg className="w-full h-full" preserveAspectRatio="xMidYMid meet" viewBox="0 0 500 200">
{/* Chart area: x from 50 to 450, y from 10 to 150 */}
{/* Grid lines */}
{[0.25, 0.5, 0.75, 1].map((ratio) => (
<line
key={`grid-${ratio}`}
stroke="var(--vscode-widget-border, #444)"
strokeDasharray="4,4"
strokeWidth="0.5"
x1="50"
x2="450"
y1={150 - ratio * 140}
y2={150 - ratio * 140}
/>
))}
{/* Y-axis labels (tokens) */}
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="12">
{formatNumber(maxValue)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="47">
{formatNumber(maxValue * 0.75)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="82">
{formatNumber(maxValue * 0.5)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="117">
{formatNumber(maxValue * 0.25)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="152">
0
</text>
{/* Y-axis labels (cost) */}
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="12">
${maxCost.toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="47">
${(maxCost * 0.75).toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="82">
${(maxCost * 0.5).toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="117">
${(maxCost * 0.25).toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="152">
$0
</text>
{/* Axes */}
<line stroke="var(--vscode-widget-border, #444)" strokeWidth="1" x1="50" x2="450" y1="150" y2="150" />
<line stroke="var(--vscode-widget-border, #444)" strokeWidth="1" x1="50" x2="50" y1="10" y2="150" />
{/* X-axis tick marks and labels (calendar-aligned) */}
{xAxisLabels.map((label, i) => {
const step = timeRange === "today" ? 2 : Math.max(1, Math.ceil(chartData.length / 10))
const dataIndex = timeRange === "today" ? i * 2 : i * step
if (dataIndex >= chartData.length) {
return null
}
const x = 50 + (dataIndex / (chartData.length - 1)) * 400
return (
<g key={`tick-${label}-${i}`}>
<line
stroke="var(--vscode-widget-border, #444)"
strokeWidth="1"
x1={x}
x2={x}
y1="150"
y2="155"
/>
<text fill="var(--vscode-descriptionForeground)" fontSize="8" textAnchor="middle" x={x} y="168">
{label}
</text>
</g>
)
})}
{/* Data lines - each data point sits exactly on its calendar bucket */}
{chartData.map((d, i) => {
const x = 50 + (i / (chartData.length - 1 || 1)) * 400
const inputY = 150 - (d.tokensIn / maxValue) * 140
const outputY = 150 - (d.tokensOut / maxValue) * 140
const cacheReadsY = 150 - (d.cacheReads / maxValue) * 140
const costY = 150 - (d.cost / maxCost) * 140
return (
<g key={d.key}>
{/* Input tokens line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevInputY = 150 - (chartData[i - 1].tokensIn / maxValue) * 140
return (
<line
fill="none"
stroke="#3b82f6"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevInputY}
y2={inputY}
/>
)
})()}
<circle cx={x} cy={inputY} fill="#3b82f6" r="3" />
{/* Output tokens line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevOutputY = 150 - (chartData[i - 1].tokensOut / maxValue) * 140
return (
<line
fill="none"
stroke="#22c55e"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevOutputY}
y2={outputY}
/>
)
})()}
<circle cx={x} cy={outputY} fill="#22c55e" r="3" />
{/* Cache reads line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevCacheReadsY = 150 - (chartData[i - 1].cacheReads / maxValue) * 140
return (
<line
fill="none"
stroke="#8b5cf6"
strokeDasharray="6,3"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevCacheReadsY}
y2={cacheReadsY}
/>
)
})()}
<circle cx={x} cy={cacheReadsY} fill="#8b5cf6" r="3" />
{/* Cost line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevCostY = 150 - (chartData[i - 1].cost / maxCost) * 140
return (
<line
fill="none"
stroke="#ef4444"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevCostY}
y2={costY}
/>
)
})()}
<circle cx={x} cy={costY} fill="#ef4444" r="3" />
</g>
)
})}
</svg>
</div>
{/* Legend */}
<div className="flex flex-wrap justify-center gap-4 mt-4 text-sm">
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#3b82f6]" />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.input")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#22c55e]" />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.output")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#8b5cf6]" style={{ borderTop: "2px dashed #8b5cf6", height: 0 }} />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.cacheHits")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#ef4444]" />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.cost")}</span>
</div>
</div>
</div>
)
}
export default UsageTrendChart
@@ -0,0 +1,278 @@
import type { UsageTimeRange } from "@shared/usage-stats"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
type TrendBucket = {
key: string
label: string
tokensIn: number
tokensOut: number
cacheWrites: number
cacheReads: number
cost: number
}
type UsageTrendChartProps = {
trend: TrendBucket[]
timeRange: UsageTimeRange
isLoading?: boolean
}
function formatNumber(num: number): string {
if (num >= 1000000) {
return (num / 1000000).toFixed(1) + "M"
}
if (num >= 1000) {
return (num / 1000).toFixed(1) + "K"
}
return num.toString()
}
export const UsageTrendChart = ({ trend, timeRange, isLoading }: UsageTrendChartProps) => {
const { t } = useTranslation("settings")
const chartData = trend
// Pick calendar-aligned tick labels so the x-axis matches real dates/hours
const xAxisLabels = useMemo(() => {
if (chartData.length === 0) {
return []
}
if (timeRange === "today") {
// every 2 hours
return chartData.filter((_, i) => i % 2 === 0).map((d) => d.label)
}
const total = chartData.length
if (total <= 7) {
return chartData.map((d) => d.label)
}
// ~10 evenly spaced calendar ticks
const step = Math.max(1, Math.ceil(total / 10))
const labels: string[] = []
for (let i = 0; i < total; i += step) {
labels.push(chartData[i].label)
}
return labels
}, [chartData, timeRange])
const maxValue = useMemo(() => {
if (chartData.length === 0) return 1000000
return Math.max(...chartData.map((d) => d.tokensIn + d.tokensOut + d.cacheReads)) * 1.1 || 1000000
}, [chartData])
const maxCost = useMemo(() => {
if (chartData.length === 0) return 1
return Math.max(...chartData.map((d) => d.cost)) * 1.1 || 1
}, [chartData])
if (isLoading || chartData.length === 0) {
return (
<div className="bg-[var(--vscode-editorWidget-background)] border border-[var(--vscode-widget-border)] rounded-lg p-6 mb-6">
<h3 className="text-lg font-semibold text-[var(--vscode-foreground)] mb-4">{t("usageStats.usageTrend")}</h3>
<div className="text-center text-[var(--vscode-descriptionForeground)] py-8">
{isLoading ? t("usageStats.loading") : t("usageStats.noData")}
</div>
</div>
)
}
return (
<div className="bg-[var(--vscode-editorWidget-background)] border border-[var(--vscode-widget-border)] rounded-lg p-6 mb-6">
<h3 className="text-lg font-semibold text-[var(--vscode-foreground)] mb-4">{t("usageStats.usageTrend")}</h3>
<div className="w-full" style={{ height: "220px" }}>
<svg className="w-full h-full" preserveAspectRatio="xMidYMid meet" viewBox="0 0 500 200">
{/* Chart area: x from 50 to 450, y from 10 to 150 */}
{/* Grid lines */}
{[0.25, 0.5, 0.75, 1].map((ratio) => (
<line
key={`grid-${ratio}`}
stroke="var(--vscode-widget-border, #444)"
strokeDasharray="4,4"
strokeWidth="0.5"
x1="50"
x2="450"
y1={150 - ratio * 140}
y2={150 - ratio * 140}
/>
))}
{/* Y-axis labels (tokens) */}
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="12">
{formatNumber(maxValue)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="47">
{formatNumber(maxValue * 0.75)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="82">
{formatNumber(maxValue * 0.5)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="117">
{formatNumber(maxValue * 0.25)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="end" x="45" y="152">
0
</text>
{/* Y-axis labels (cost) */}
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="12">
${maxCost.toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="47">
${(maxCost * 0.75).toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="82">
${(maxCost * 0.5).toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="117">
${(maxCost * 0.25).toFixed(2)}
</text>
<text fill="var(--vscode-descriptionForeground)" fontSize="9" textAnchor="start" x="455" y="152">
$0
</text>
{/* Axes */}
<line stroke="var(--vscode-widget-border, #444)" strokeWidth="1" x1="50" x2="450" y1="150" y2="150" />
<line stroke="var(--vscode-widget-border, #444)" strokeWidth="1" x1="50" x2="50" y1="10" y2="150" />
{/* X-axis tick marks and labels (calendar-aligned) */}
{xAxisLabels.map((label, i) => {
const step = timeRange === "today" ? 2 : Math.max(1, Math.ceil(chartData.length / 10))
const dataIndex = timeRange === "today" ? i * 2 : i * step
if (dataIndex >= chartData.length) {
return null
}
const x = 50 + (dataIndex / (chartData.length - 1)) * 400
return (
<g key={`tick-${label}-${i}`}>
<line
stroke="var(--vscode-widget-border, #444)"
strokeWidth="1"
x1={x}
x2={x}
y1="150"
y2="155"
/>
<text fill="var(--vscode-descriptionForeground)" fontSize="8" textAnchor="middle" x={x} y="168">
{label}
</text>
</g>
)
})}
{/* Data lines - each data point sits exactly on its calendar bucket */}
{chartData.map((d, i) => {
const x = 50 + (i / (chartData.length - 1 || 1)) * 400
const inputY = 150 - (d.tokensIn / maxValue) * 140
const outputY = 150 - (d.tokensOut / maxValue) * 140
const cacheReadsY = 150 - (d.cacheReads / maxValue) * 140
const costY = 150 - (d.cost / maxCost) * 140
return (
<g key={d.key}>
{/* Input tokens line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevInputY = 150 - (chartData[i - 1].tokensIn / maxValue) * 140
return (
<line
fill="none"
stroke="#3b82f6"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevInputY}
y2={inputY}
/>
)
})()}
<circle cx={x} cy={inputY} fill="#3b82f6" r="3" />
{/* Output tokens line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevOutputY = 150 - (chartData[i - 1].tokensOut / maxValue) * 140
return (
<line
fill="none"
stroke="#22c55e"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevOutputY}
y2={outputY}
/>
)
})()}
<circle cx={x} cy={outputY} fill="#22c55e" r="3" />
{/* Cache reads line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevCacheReadsY = 150 - (chartData[i - 1].cacheReads / maxValue) * 140
return (
<line
fill="none"
stroke="#8b5cf6"
strokeDasharray="6,3"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevCacheReadsY}
y2={cacheReadsY}
/>
)
})()}
<circle cx={x} cy={cacheReadsY} fill="#8b5cf6" r="3" />
{/* Cost line */}
{i > 0 &&
(() => {
const prevX = 50 + ((i - 1) / (chartData.length - 1)) * 400
const prevCostY = 150 - (chartData[i - 1].cost / maxCost) * 140
return (
<line
fill="none"
stroke="#ef4444"
strokeWidth="2"
x1={prevX}
x2={x}
y1={prevCostY}
y2={costY}
/>
)
})()}
<circle cx={x} cy={costY} fill="#ef4444" r="3" />
</g>
)
})}
</svg>
</div>
{/* Legend */}
<div className="flex flex-wrap justify-center gap-4 mt-4 text-sm">
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#3b82f6]" />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.input")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#22c55e]" />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.output")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#8b5cf6]" style={{ borderTop: "2px dashed #8b5cf6", height: 0 }} />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.cacheHits")}</span>
</div>
<div className="flex items-center gap-2">
<div className="w-4 h-0.5 bg-[#ef4444]" />
<span className="text-[var(--vscode-foreground)]">{t("usageStats.cost")}</span>
</div>
</div>
</div>
)
}
export default UsageTrendChart
@@ -0,0 +1,4 @@
export { ModelStatsTable } from "./ModelStatsTable"
export { UsageStatsView } from "./UsageStatsView"
export { UsageSummaryCard } from "./UsageSummaryCard"
export { UsageTrendChart } from "./UsageTrendChart"
@@ -35,6 +35,7 @@ import {
removeProfile,
reorderProfiles,
setActiveProfileId,
syncProfilesFromRemote,
updateProfile,
} from "../utils/api-profiles"
@@ -325,6 +326,19 @@ export const ExtensionStateContextProvider: React.FC<{
const [hicapModels, setHicapModels] = useState<Record<string, ModelInfo>>({})
const [apiProfiles, setApiProfiles] = useState<ApiConfigProfile[]>(() => loadProfiles())
const [activeApiProfileIdState, setActiveApiProfileIdState] = useState<string | undefined>(() => getActiveProfileId())
// Hydrate profiles from the durable extension-side storage on startup.
// localStorage alone is wiped on extension reinstall/update, so the
// extension globalState copy is the source of truth (with one-time
// migration of legacy localStorage data into it).
useEffect(() => {
syncProfilesFromRemote().then((result) => {
if (result) {
setApiProfiles(result.profiles)
setActiveApiProfileIdState(result.activeId)
}
})
}, [])
const [liteLlmModels, setLiteLlmModels] = useState<Record<string, ModelInfo>>({})
const [totalTasksSize, setTotalTasksSize] = useState<number | null>(null)
const [availableTerminalProfiles, setAvailableTerminalProfiles] = useState<TerminalProfile[]>([])
@@ -833,7 +847,7 @@ export const ExtensionStateContextProvider: React.FC<{
setApiProfiles(reorderProfiles(fromIndex, toIndex))
}, [])
const clearActiveProfile = useCallback(() => {
const _clearActiveProfile = useCallback(() => {
setActiveProfileId(undefined)
setActiveApiProfileIdState(undefined)
}, [])
@@ -841,7 +855,9 @@ export const ExtensionStateContextProvider: React.FC<{
const applyApiProfile = useCallback(
async (profileId: string) => {
const profile = loadProfiles().find((p) => p.id === profileId)
if (!profile) return
if (!profile) {
return
}
setActiveProfileId(profileId)
setActiveApiProfileIdState(profileId)
@@ -938,6 +954,113 @@ export const ExtensionStateContextProvider: React.FC<{
planModeApiProvider: profile.provider,
}
// Clear ALL provider-specific fields to avoid stale data from previous provider
const allApiKeyFields = [
"apiKey",
"openRouterApiKey",
"awsBedrockApiKey",
"openAiApiKey",
"ollamaApiKey",
"lmStudioApiKey",
"geminiApiKey",
"openAiNativeApiKey",
"openAiCodexApiKey",
"deepSeekApiKey",
"qwenApiKey",
"qwenCodeApiKey",
"doubaoApiKey",
"mistralApiKey",
"liteLlmApiKey",
"moonshotApiKey",
"nebiusApiKey",
"fireworksApiKey",
"asksageApiKey",
"xaiApiKey",
"sambanovaApiKey",
"cerebrasApiKey",
"sapAiCoreApiKey",
"groqApiKey",
"huggingFaceApiKey",
"huaweiCloudMaasApiKey",
"difyApiKey",
"basetenApiKey",
"vercelAiGatewayApiKey",
"zaiApiKey",
"minimaxApiKey",
"hicapApiKey",
"aihubmixApiKey",
"requestyApiKey",
"togetherApiKey",
"nousResearchApiKey",
"clineApiKey",
]
const allModelIdFields = [
"actModeApiModelId",
"planModeApiModelId",
"actModeOpenRouterModelId",
"planModeOpenRouterModelId",
"actModeOpenAiModelId",
"planModeOpenAiModelId",
"actModeTogetherModelId",
"planModeTogetherModelId",
"actModeOllamaModelId",
"planModeOllamaModelId",
"actModeLmStudioModelId",
"planModeLmStudioModelId",
"actModeLiteLlmModelId",
"planModeLiteLlmModelId",
"actModeRequestyModelId",
"planModeRequestyModelId",
"actModeGroqModelId",
"planModeGroqModelId",
"actModeFireworksModelId",
"planModeFireworksModelId",
"actModeHuggingFaceModelId",
"planModeHuggingFaceModelId",
"actModeBasetenModelId",
"planModeBasetenModelId",
"actModeVercelAiGatewayModelId",
"planModeVercelAiGatewayModelId",
"actModeHuaweiCloudMaasModelId",
"planModeHuaweiCloudMaasModelId",
"actModeOcaModelId",
"planModeOcaModelId",
"actModeAihubmixModelId",
"planModeAihubmixModelId",
"actModeHicapModelId",
"planModeHicapModelId",
"actModeNousResearchModelId",
"planModeNousResearchModelId",
"actModeSambanovaModelId",
"planModeSambanovaModelId",
"actModeCerebrasModelId",
"planModeCerebrasModelId",
"actModeClineModelId",
"planModeClineModelId",
]
const allBaseUrlFields = [
"openAiBaseUrl",
"ollamaBaseUrl",
"lmStudioBaseUrl",
"liteLlmBaseUrl",
"anthropicBaseUrl",
"openAiNativeBaseUrl",
"deepSeekBaseUrl",
"requestyBaseUrl",
"difyBaseUrl",
"geminiBaseUrl",
]
for (const f of allApiKeyFields) {
updates[f] = ""
}
for (const f of allModelIdFields) {
updates[f] = ""
}
for (const f of allBaseUrlFields) {
updates[f] = ""
}
const keyField = providerApiKeyField[profile.provider]
if (keyField && profile.apiKey) {
updates[keyField] = profile.apiKey
@@ -946,6 +1069,11 @@ export const ExtensionStateContextProvider: React.FC<{
const modelField = providerModelIdField[profile.provider]
if (modelField && profile.modelId) {
updates[modelField] = profile.modelId
// Also set the corresponding planMode field
const planField = modelField.replace(/^actMode/, "planMode")
if (planField !== modelField) {
updates[planField] = profile.modelId
}
}
if (profile.baseUrl) {
@@ -959,11 +1087,40 @@ export const ExtensionStateContextProvider: React.FC<{
deepseek: "deepSeekBaseUrl",
}
const bf = baseUrlFields[profile.provider]
if (bf) updates[bf] = profile.baseUrl
if (bf) {
updates[bf] = profile.baseUrl
}
}
if (profile.extra) {
Object.assign(updates, profile.extra)
const { profileModelInfo: _, ...restExtra } = profile.extra as any
Object.assign(updates, restExtra)
}
// Restore profile-specific modelInfo (prices, etc.)
const profileModelInfo = profile.extra?.profileModelInfo
if (profileModelInfo) {
const providerModelInfoField: Record<string, { plan: string; act: string }> = {
openai: { plan: "planModeOpenAiModelInfo", act: "actModeOpenAiModelInfo" },
deepseek: { plan: "planModeDeepSeekModelInfo", act: "actModeDeepSeekModelInfo" },
openrouter: { plan: "planModeOpenRouterModelInfo", act: "actModeOpenRouterModelInfo" },
cline: { plan: "planModeClineModelInfo", act: "actModeClineModelInfo" },
requesty: { plan: "planModeRequestyModelInfo", act: "actModeRequestyModelInfo" },
groq: { plan: "planModeGroqModelInfo", act: "actModeGroqModelInfo" },
baseten: { plan: "planModeBasetenModelInfo", act: "actModeBasetenModelInfo" },
huggingface: { plan: "planModeHuggingFaceModelInfo", act: "actModeHuggingFaceModelInfo" },
"huawei-cloud-maas": { plan: "planModeHuaweiCloudMaasModelInfo", act: "actModeHuaweiCloudMaasModelInfo" },
litellm: { plan: "planModeLiteLlmModelInfo", act: "actModeLiteLlmModelInfo" },
aihubmix: { plan: "planModeAihubmixModelInfo", act: "actModeAihubmixModelInfo" },
hicap: { plan: "planModeHicapModelInfo", act: "actModeHicapModelInfo" },
"vercel-ai-gateway": { plan: "planModeVercelAiGatewayModelInfo", act: "actModeVercelAiGatewayModelInfo" },
oca: { plan: "planModeOcaModelInfo", act: "actModeOcaModelInfo" },
}
const fields = providerModelInfoField[profile.provider]
if (fields) {
updates[fields.plan] = profileModelInfo
updates[fields.act] = profileModelInfo
}
}
// Apply via the existing RPC
+12 -15
View File
@@ -1,34 +1,31 @@
import i18n from "i18next"
import { initReactI18next } from "react-i18next"
import enCommon from "../locales/en/common.json"
import enMisc from "../locales/en/common-misc.json"
import enSettings from "../locales/en/settings.json"
import zhCommon from "../locales/zh-CN/common.json"
import zhMisc from "../locales/zh-CN/common-misc.json"
import zhSettings from "../locales/zh-CN/settings.json"
// 项目已统一为简体中文:所有语言资源均指向中文文件,
// 回退语言也是中文,确保界面始终显示简体中文。
const zhResources = {
common: zhCommon,
settings: zhSettings,
misc: zhMisc,
}
const resources = {
en: {
common: enCommon,
settings: enSettings,
misc: enMisc,
},
"zh-CN": {
common: zhCommon,
settings: zhSettings,
misc: zhMisc,
},
en: zhResources,
"zh-CN": zhResources,
}
i18n.use(initReactI18next).init({
resources,
lng: "zh-CN",
fallbackLng: "en",
fallbackLng: "zh-CN",
defaultNS: "common",
interpolation: {
escapeValue: false,
},
})
export default i18n
export default i18n
+12
View File
@@ -69,3 +69,15 @@
margin: calc(var(--design-unit) * 1px) 0;
}
}
/* Force vscode-text-field to full width */
vscode-text-field {
display: block !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
vscode-text-field::part(root) {
width: 100% !important;
max-width: 100% !important;
}
+2 -1
View File
@@ -226,7 +226,7 @@
"newTask": "New Task",
"mcpServers": "MCP Servers",
"history": "History",
"account": "Account",
"account": "My",
"settings": "Settings"
},
"browser": {
@@ -455,3 +455,4 @@
"favorited": "Favorited"
}
}
+37 -588
View File
@@ -71,601 +71,50 @@
"modeSwitchPersistDescription": "Switching between Plan and Act mode will persist the API and model used in the previous mode. This may be helpful e.g. when using a strong reasoning model to architect a plan for a cheaper coding model to act on.",
"thinkingBudgetLabel": "Thinking budget: {{value}} tokens"
},
"settingsSections": {
"allowErrorReporting": "Allow error and usage reporting",
"telemetryDescription": "Help improve Cline by sending usage data and error reports. No code, prompts, or personal information are ever sent. See our",
"telemetryOverview": "telemetry overview",
"privacyPolicy": "privacy policy",
"forMoreDetails": "for more details.",
"disableBrowser": "Disable browser tool usage",
"disableBrowserDescription": "Prevent Cline from using browser actions (e.g. launch, click, type).",
"viewportSize": "Viewport size",
"viewportSizeDescription": "Set the size of the browser viewport for screenshots and interactions.",
"useRemoteBrowser": "Use remote browser connection",
"remoteBrowserDescription": "Enable Cline to use your Chrome",
"notDetectedOnMachine": "(not detected on your machine)",
"remoteBrowserRequiresDebug": ". You can specify a custom path below. Using a remote browser connection requires starting Chrome in debug mode",
"remoteBrowserDebugManually": "manually",
"remoteBrowserDebugOrButton": "or using the button below. Enter the host address or leave it blank for automatic discovery.",
"launchBrowserDebug": "Launch Browser with Debug Mode",
"launchingBrowser": "Launching Browser...",
"chromeExecutablePath": "Chrome Executable Path (Optional)",
"chromePathPlaceholder": "e.g., /usr/bin/google-chrome or C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
"leaveBlankAutoDetect": "Leave blank to auto-detect.",
"customBrowserArgs": "Custom Browser Arguments (Optional)",
"customBrowserArgsPlaceholder": "e.g., --no-sandbox --disable-setuid-sandbox --disable-dev-shm-usage --disable-gpu --no-first-run --no-zygote",
"customBrowserArgsDescription": "Space-separated arguments to pass to the browser executable.",
"checkingConnection": "Checking connection...",
"connected": "Connected",
"notConnected": "Not connected",
"defaultTerminalProfile": "Default Terminal Profile",
"defaultTerminalProfileDescription": "Select the default terminal Cline will use. 'Default' uses your VSCode global setting.",
"shellIntegrationTimeout": "Shell integration timeout (seconds)",
"shellIntegrationPlaceholder": "Enter timeout in seconds",
"enterPositiveNumber": "Please enter a positive number",
"shellIntegrationDescription": "Set how long Cline waits for shell integration to activate before executing commands. Increase this value if you experience terminal connection timeouts.",
"enableAggressiveTerminalReuse": "Enable aggressive terminal reuse",
"terminalReuseDescription": "When enabled, Cline will reuse existing terminal windows that aren't in the current working directory. Disable this if you experience issues with task lockout after a terminal command.",
"terminalExecutionMode": "Terminal Execution Mode",
"vsCodeTerminal": "VS Code Terminal",
"backgroundExec": "Background Exec",
"terminalExecutionModeDescription": "Choose whether Cline runs commands in the VS Code terminal or a background process.",
"havingTerminalIssues": "Having terminal issues?",
"terminalQuickFixes": "Terminal Quick Fixes",
"completeTroubleshootingGuide": "Complete Troubleshooting Guide",
"resetWorkspaceState": "Reset Workspace State",
"resetGlobalState": "Reset Global State",
"resetStateDescription": "This will reset all global state and secret storage in the extension.",
"resetOnboardingState": "Reset Onboarding State",
"aboutVersion": "Cline v{{version}}",
"aboutDescription": "An AI assistant that can use your CLI and Editor. Cline can handle complex software development tasks step-by-step with tools that let him create & edit files, explore large projects, use the browser, and execute terminal commands (after you grant permission).",
"communitySupport": "Community & Support",
"development": "Development",
"resources": "Resources",
"documentation": "Documentation",
"issues": "Issues",
"featureRequests": "Feature Requests",
"browser": {
"chromeExecutablePath": "Chrome Executable Path (Optional)",
"customBrowserArgs": "Custom Browser Arguments (Optional)"
},
"disableBrowserToolUsage": "Disable browser tool usage",
"useRemoteBrowserConnection": "Use remote browser connection",
"allowErrorUsageReporting": "Allow error and usage reporting",
"telemetryAnd": ""
},
"featureSettings": {
"agent": "Agent",
"editor": "Editor",
"experimental": "Experimental",
"advanced": "Advanced",
"subagents": "Subagents",
"subagentsDescription": "Let Cline run focused subagents in parallel to explore the codebase for you.",
"nativeToolCall": "Native Tool Call",
"nativeToolCallDescription": "Use native function calling when available",
"parallelToolCalling": "Parallel Tool Calling",
"parallelToolCallingDescription": "Execute multiple tool calls simultaneously",
"strictPlanMode": "Strict Plan Mode",
"strictPlanModeDescription": "Prevents file edits while in Plan mode",
"autoCompact": "Auto Compact",
"autoCompactDescription": "Automatically compress conversation history.",
"focusChain": "Focus Chain",
"focusChainDescription": "Maintain context focus across interactions",
"featureTips": "Feature Tips",
"featureTipsDescription": "Show rotating tips during the thinking phase to help you discover Cline features.",
"backgroundEdit": "Background Edit",
"backgroundEditDescription": "Allow edits without stealing editor focus",
"checkpoints": "Checkpoints",
"checkpointsDescription": "Save progress at key points for easy rollback",
"clineWebTools": "Cline Web Tools",
"clineWebToolsDescription": "Access web browsing and search capabilities",
"worktrees": "Worktrees",
"worktreesDescription": "Enables git worktree management for running parallel Cline tasks.",
"yoloMode": "Yolo Mode",
"yoloModeDescription": "Execute tasks without user's confirmation. Auto-switches from Plan to Act mode and disables the ask question tool. Use with extreme caution.",
"doubleCheckCompletion": "Double-Check Completion",
"doubleCheckCompletionDescription": "Rejects the first completion attempt and asks the model to re-verify its work against the original task requirements before accepting.",
"lazyTeammateMode": "Lazy Teammate Mode",
"lazyTeammateModeDescription": "Sometimes Cline just isn't feeling it today. For entertainment purposes only.",
"hooks": "Hooks",
"hooksDescription": "Enable lifecycle and tool hooks during task execution.",
"mcpDisplayMode": "MCP Display Mode",
"mcpDisplayModeDescription": "Controls how MCP responses are displayed",
"plainText": "Plain Text",
"richDisplay": "Rich Display",
"markdown": "Markdown"
},
"remoteConfig": {
"refresh": "Refresh",
"retryIn": "Retry in:",
"seconds": "seconds",
"notConfigured": "Not configured",
"enabled": "Enabled",
"disabled": "Disabled",
"testing": "Testing...",
"success": "Success!",
"failed": "Failed",
"test": "Test",
"flushedBuffers": "Flushed buffers! Please check the output channel for more detailed information",
"settingsManagedByOrg": "These settings are managed by your organization's remote configuration.",
"optedOut": "You have opted out of remote config. Opt back in to apply it and see it here.",
"notConfiguredYet": "You haven't configured remote config yet. Do so through our",
"dashboard": "dashboard",
"openTelemetryConfig": "OpenTelemetry Configuration",
"promptUploadingConfig": "Prompt Uploading Configuration",
"otelEnabled": "Enabled",
"metricsExporter": "Metrics Exporter",
"logsExporter": "Logs Exporter",
"otlpProtocol": "OTLP Protocol",
"otlpEndpoint": "OTLP Endpoint",
"metricsEndpoint": "Metrics Endpoint",
"logsEndpoint": "Logs Endpoint",
"otlpHeaders": "OTLP Headers",
"headerCount": "{{count}} header(s)",
"metricExportInterval": "Metric Export Interval",
"otlpInsecure": "OTLP Insecure",
"logBatchSize": "Log Batch Size",
"logBatchTimeout": "Log Batch Timeout",
"logMaxQueueSize": "Log Max Queue Size",
"testUpload": "Test Upload",
"storageType": "Storage Type",
"bucket": "Bucket",
"region": "Region",
"endpoint": "Endpoint",
"accountId": "Account ID",
"accessKeyId": "Access Key ID",
"secretAccessKey": "Secret Access Key",
"syncInterval": "Sync Interval",
"batchSize": "Batch Size",
"maxRetries": "Max Retries",
"maxQueueSize": "Max Queue Size",
"backfillEnabled": "Backfill Enabled"
},
"commonFields": {
"apiKey": "{{provider}} API Key",
"enterApiKey": "Enter API Key...",
"apiKeyStoredLocally": "This key is stored locally and only used to make API requests from this extension.",
"getApiKeySignup": "You can get a {{provider}} API key by signing up here.",
"baseUrl": "Base URL",
"baseUrlOptional": "Base URL (optional)",
"enterBaseUrl": "Enter base URL...",
"context": "Context:",
"input": "Input:",
"output": "Output:",
"advanced": "Advanced",
"images": "Images",
"browser": "Browser",
"promptCaching": "Prompt Caching",
"cacheReads": "Cache Reads",
"usageStats": {
"title": "Usage Statistics",
"tokensConsumed": "Tokens Consumed",
"totalRequests": "Total Requests",
"totalTasks": "Tasks",
"totalCost": "Total Cost",
"input": "Input",
"output": "Output",
"cacheWrites": "Cache Writes",
"tieredPricing": "Tiered Pricing:",
"inputLabel": "Input:",
"outputLabel": "Output:",
"tokens": "tokens",
"providerRouting": "Provider Routing",
"providerRoutingDefault": "Load balance across providers (AWS, Google Vertex, etc.), prioritizing price while considering uptime",
"providerRoutingPrice": "Sort by price, prioritizing the lowest cost provider",
"providerRoutingThroughput": "Sort by throughput, prioritizing highest throughput (may increase cost)",
"providerRoutingLatency": "Sort by response time, prioritizing lowest latency",
"default": "Default",
"price": "Price",
"throughput": "Throughput",
"latency": "Latency",
"yes": "Yes",
"no": "No",
"free": "Free",
"na": "N/A",
"modelSuggestions": "Model suggestions",
"remove": "Remove",
"addHeader": "Add Header",
"headerName": "Header name",
"headerValue": "Header value",
"addHeaderButton": "Add Header"
},
"providers": {
"anthropic": {
"name": "Anthropic",
"useCustomBaseUrl": "Use custom base URL",
"defaultBaseUrl": "Default: https://api.anthropic.com"
"cacheHits": "Cache Hits",
"cacheHitRate": "Cache Hit Rate",
"usageTrend": "Usage Trend",
"modelStats": "Model Statistics",
"cost": "Cost",
"costBreakdown": {
"title": "Cost Breakdown",
"input": "Input",
"output": "Output",
"cacheWrites": "Cache Writes",
"cacheReads": "Cache Reads"
},
"openaiNative": {
"name": "OpenAI"
"loading": "Loading...",
"noData": "No data available",
"timeRange": {
"today": "Today",
"week": "Last Week",
"month": "Last Month",
"all": "All Time"
},
"openaiCompatible": {
"name": "OpenAI Compatible",
"baseUrl": "Base URL",
"modelId": "Model ID",
"enterModelId": "Enter Model ID...",
"customHeaders": "Custom Headers",
"setAzureApiVersion": "Set Azure API version",
"useAzureIdentity": "Use Azure Identity Authentication",
"modelConfiguration": "Model Configuration",
"supportsImages": "Supports Images",
"enableR1Format": "Enable R1 messages format",
"contextWindowSize": "Context Window Size",
"maxOutputTokens": "Max Output Tokens",
"inputPricePerMillion": "Input Price / 1M tokens",
"outputPricePerMillion": "Output Price / 1M tokens",
"temperature": "Temperature",
"noteComplexPrompts": "Note: Cline uses complex prompts and works best with Claude models. Less capable models may not work as expected."
},
"openRouter": {
"name": "OpenRouter",
"apiKey": "OpenRouter API Key",
"getApiKey": "Get OpenRouter API Key",
"balance": "Balance:",
"loading": "Loading...",
"keyStoredLocally": "This key is stored locally and only used to make API requests from this extension.",
"autoFetchModels": "The extension automatically fetches the latest list of models available on",
"openRouter": "OpenRouter",
"unsureModelChoice": "If you're unsure which model to choose, Cline works best with",
"recommendedModel": "anthropic/claude-sonnet-4.6",
"trySearchingFree": "You can also try searching \"free\" for no-cost options currently available."
},
"deepseek": {
"name": "DeepSeek"
},
"gemini": {
"name": "Gemini",
"useCustomBaseUrl": "Use custom base URL",
"defaultBaseUrl": "Default: https://generativelanguage.googleapis.com"
},
"bedrock": {
"apiKeyOption": "API Key",
"awsProfileOption": "AWS Profile",
"awsCredentialsOption": "AWS Credentials",
"awsProfileName": "AWS Profile Name",
"enterProfileName": "Enter profile name (default if empty)",
"awsBedrockApiKey": "AWS Bedrock Api Key",
"enterBedrockApiKey": "Enter Bedrock Api Key",
"awsAccessKey": "AWS Access Key",
"enterAccessKey": "Enter Access Key...",
"awsSecretKey": "AWS Secret Key",
"enterSecretKey": "Enter Secret Key...",
"awsSessionToken": "AWS Session Token",
"enterSessionToken": "Enter Session Token...",
"awsRegion": "AWS Region",
"searchOrEnterRegion": "Search or enter custom region...",
"useCustomVpcEndpoint": "Use custom VPC endpoint",
"enterVpcEndpoint": "Enter VPC Endpoint URL (optional)",
"useCrossRegionInference": "Use cross-region inference",
"useGlobalInference": "Use global inference profile",
"usePromptCaching": "Use prompt caching",
"awsProfileCredentials": "Using AWS Profile credentials from ~/.aws/credentials. Leave profile name empty to use the default profile. These credentials are only used locally to make API requests from this extension.",
"awsKeyCredentials": "Authenticate by either providing the keys above or use the default AWS credential providers, i.e. ~/.aws/credentials or environment variables. These credentials are only used locally to make API requests from this extension.",
"customOption": "Custom",
"customModelDescription": "Select \"Custom\" when using the Application Inference Profile in Bedrock. Enter the Application Inference Profile ARN in the Model ID field.",
"enterCustomModelId": "Enter custom model ID...",
"baseInferenceModel": "Base Inference Model"
},
"vertex": {
"googleCloudProjectId": "Google Cloud Project ID",
"enterProjectId": "Enter Project ID...",
"googleCloudRegion": "Google Cloud Region",
"selectRegion": "Select a region...",
"setupInstructions": "To use Google Cloud Vertex AI, you need to",
"step1": "1) create a Google Cloud account › enable the Vertex AI API › enable the desired Claude models,",
"step2": "2) install the Google Cloud CLI › configure Application Default Credentials."
},
"ollama": {
"name": "Ollama",
"useCustomBaseUrl": "Use custom base URL",
"defaultBaseUrl": "Default: http://localhost:11434",
"optionalApiKey": "Optional API key for authenticated Ollama instances or cloud services. Leave empty for local installations.",
"enterApiKeyOptional": "Enter API Key (optional)...",
"unableToFetch": "Unable to fetch models from Ollama server. Please ensure Ollama is running and accessible, or enter the model ID manually above.",
"modelContextWindow": "Model Context Window",
"requestTimeout": "Request Timeout (ms)",
"requestTimeoutDefault": "Default: 30000 (30 seconds)",
"requestTimeoutDescription": "Maximum time in milliseconds to wait for API responses before timing out.",
"quickstartGuide": "quickstart guide.",
"ollamaInstructions": "Ollama allows you to run models locally on your computer. For instructions on how to get started, see their",
"noteComplexPrompts": "Note: Cline uses complex prompts and works best with Claude models. Less capable models may not work as expected.",
"seeQuickstart": "Ollama allows you to run models locally on your computer. For instructions on how to get started, see their quickstart guide.",
"modelExample": "e.g. llama3.1",
"contextLengthExample": "e.g. 32768"
},
"lmstudio": {
"useCustomBaseUrl": "Use custom base URL",
"runModelsLocally": "LM Studio allows you to run models locally on your computer. For instructions on how to get started, see their",
"needToStartServer": "You will also need to start LM Studio's",
"serverFeatureWithCode": "feature with",
"contextWindow": "Context Window"
},
"together": {
"name": "Together",
"modelId": "Model ID",
"noteComplexPrompts": "Note: Cline uses complex prompts and works best with Claude models. Less capable models may not work as expected.",
"modelIdPlaceholder": "Enter Model ID..."
},
"xai": {
"name": "X AI",
"noteComplexPrompts": "Note: Cline uses complex prompts and works best with Claude models. Less capable models may not work as expected.",
"reasoningEffort": "Reasoning Effort"
},
"groq": {
"name": "Groq",
"autoFetchModels": "The extension automatically fetches the latest list of models available on",
"groq": "Groq",
"unsureModelChoice": "If you're unsure which model to choose, Cline works best with",
"recommendedModel": "llama-3.3-70b-versatile"
},
"fireworks": {
"name": "Fireworks"
},
"cerebras": {
"name": "Cerebras"
},
"mistral": {
"name": "Mistral"
},
"nebius": {
"name": "Nebius"
},
"nousresearch": {
"name": "NousResearch",
"noteComplexPrompts": "Note: Cline uses complex prompts and works best with Claude models. Less capable models may not work as expected."
},
"sambanova": {
"name": "SambaNova"
},
"doubao": {
"name": "Doubao"
},
"qwen": {
"name": "Qwen",
"alibabaApiLine": "Alibaba API Line"
},
"qwenCode": {
"title": "Qwen Code",
"oauthCredsPath": "OAuth Credentials Path",
"credsPathDescription": "Path to your Qwen OAuth credentials file. Use ~/.qwen/oauth_creds.json or provide a custom path.",
"oauthExplanation": "Qwen Code is an OAuth-based API that requires authentication through the official Qwen client. You'll need to set up OAuth credentials first.",
"getStartedSteps": "To get started:<br />1. Install the official Qwen client<br />2. Authenticate using your account<br />3. OAuth credentials will be stored automatically",
"setupInstructions": "Setup Instructions"
},
"moonshot": {
"name": "Moonshot",
"entrypoint": "Moonshot Entrypoint"
},
"minimax": {
"name": "MiniMax",
"entrypoint": "MiniMax Entrypoint",
"selectApiEndpoint": "Select the API endpoint according to your region:",
"forChina": "for China, or",
"forOtherLocations": "for all other locations."
},
"huaweiCloudMaas": {
"name": "Huawei Cloud MaaS"
},
"aihubmix": {
"name": "AIhubmix"
},
"askSage": {
"name": "AskSage",
"apiUrl": "AskSage API URL"
},
"baseten": {
"name": "Baseten",
"autoFetchModels": "The extension automatically fetches the latest list of models available on",
"baseten": "Baseten",
"unsureModelChoice": "If you're unsure which model to choose, Cline works best with",
"recommendedModel": "moonshotai/Kimi-K2-Instruct"
},
"claudeCode": {
"cliPath": "Claude Code CLI Path",
"defaultClaudePlaceholder": "Default: claude",
"cliPathDescription": "Path to the Claude Code CLI."
},
"cline": {
"name": "Cline"
},
"dify": {
"name": "Dify",
"baseUrl": "Base URL",
"noteModelSelection": "Note: The model selection is handled within your Dify application configuration.",
"platformDescription": "Dify is a platform that provides access to various AI models through a unified API. Configure your Dify instance URL and API key to get started.",
"baseUrlPlaceholder": "Enter base URL..."
},
"hicap": {
"apiKey": "Hicap API Key"
},
"huggingface": {
"apiKey": "Hugging Face API Key",
"keyStoredLocally": "This key is stored locally and only used to make API requests from this extension. We don't show pricing here because it depends on your Hugging Face provider settings and isn't consistently available via their API"
},
"litellm": {
"baseUrlOptional": "Base URL (optional)",
"apiKey": "API Key",
"defaultNoopPlaceholder": "Default: noop",
"searchModelPlaceholder": "Search or enter a custom model ID...",
"seeQuickstart": "LiteLLM provides a unified interface to access various LLM providers' models. See their quickstart guide for more information.",
"extendedThinkingAvailable": "Extended thinking is available for models such as Sonnet-4, o3-mini, Deepseek R1, etc. More info on",
"thinkingModeConfiguration": "thinking mode configuration"
},
"requesty": {
"name": "Requesty",
"customBaseUrl": "Custom base URL",
"autoFetchModels": "The extension automatically fetches the latest list of models available on",
"requesty": "Requesty",
"unsureModelChoice": "If you're unsure which model to choose, Cline works best with",
"recommendedModel": "anthropic/claude-3-7-sonnet-latest"
},
"sapaicore": {
"orchestrationMode": "Orchestration Mode",
"credentialsStoredLocally": "Your credentials are stored locally and are only used to make API requests from this extension.",
"moreInfoLink": "More information",
"configureCredentials": "Please configure your SAP AI Core credentials first.",
"clientId": "Client ID",
"clientIdSet": "Client ID is set",
"enterClientId": "Enter your SAP AI Core Client ID",
"clientSecret": "Client Secret",
"clientSecretSet": "Client Secret is set",
"enterClientSecret": "Enter your SAP AI Core Client Secret",
"baseUrl": "Base URL",
"enterBaseUrl": "e.g., https://api.ai.prod.eu-central-1.aws.ml.hana.ondemand.com",
"authUrl": "Authentication URL",
"enterAuthUrl": "e.g., https://<subaccount>.authentication.sap.hana.ondemand.com",
"resourceGroup": "Resource Group",
"enterResourceGroup": "Enter your SAP AI Core Resource Group",
"fetchModelsFailed": "Failed to fetch models from SAP AI Core",
"loadingModels": "Loading models...",
"orchestrationDescription": "Orchestration mode allows the SAP AI Core to orchestrate multiple models and tools in a single request.",
"orchestrationDisabled": "Orchestration mode is only available when your SAP AI Core service instance supports it.",
"retry": "Retry",
"unableToFetchModels": "Unable to fetch models from SAP AI Core service instance. Please check your SAP AI Core configuration or ensure your deployments are deployed and running in the service instance."
},
"vercelAiGateway": {
"apiKey": "Vercel AI Gateway API Key",
"enterApiKeyToLoadModels": "Enter your Vercel AI Gateway API key above to load available models. You can get an API key from",
"vercelAiGateway": "Vercel AI Gateway",
"selectModelFromDropdown": "Select a model from the dropdown above. The extension fetches available models from your Vercel AI Gateway configuration."
},
"vscodeLm": {
"languageModel": "Language Model",
"description": "Use models from your GitHub Copilot subscription. Install the",
"copilotExtension": "Copilot extension",
"enableClaudeModels": "and enable Claude models in Copilot settings to get started."
},
"openAiCodex": {
"signedIn": "Signed in to OpenAI Codex",
"signIn": "Sign in to OpenAI Codex",
"signInDescription": "Sign in to use OpenAI Codex (ChatGPT Plus/Pro subscription required)"
},
"oca": {
"signedIn": "Signed in",
"signIn": "Sign in with Oracle Code Assist",
"signInAgain": "Sign in again",
"logOut": "Log out",
"retry": "Retry",
"oracleEmployment": "Oracle employment",
"oracleEmployee": "I'm an Oracle Employee",
"itAdminMessage": "Please ask your IT administrator to set up Oracle Code Assist as a model provider. Oracle Employees, please see the",
"quickstartGuide": "quickstart guide",
"failedRefreshModels": "Failed to refresh models. Check your session or network.",
"customBaseUrlOptional": "Custom Base URL (optional)",
"haveIdea": "Have an idea for Oracle Code Assist?",
"provideFeedback": "Provide feedback",
"pleaseSeeThe": "please see the"
},
"wandb": {
"name": "Wandb"
},
"zai": {
"name": "Z AI",
"entrypoint": "API Entrypoint",
"entrypointDescription": "Please select the appropriate API entrypoint based on your location. If you are in China, choose open.bigmodel.cn. Otherwise, choose api.z.ai."
},
"lmStudio": {
"name": "LM Studio",
"modelExample": "e.g. meta-llama-3.1-8b-instruct"
},
"liteLlm": {
"defaultBaseUrl": "Default: http://localhost:4000"
"tableHeaders": {
"model": "Model",
"requests": "Requests",
"tokens": "Tokens",
"cacheWrites": "Cache Writes",
"cacheReads": "Cache Hits",
"totalCost": "Total Cost",
"avgCost": "Avg Cost"
}
},
"modelPicker": {
"noModelsFound": "No models found",
"refreshing": "Refreshing...",
"refresh": "Refresh",
"searchModel": "Search model...",
"otherOptions": "other options",
"noResultFound": "No result found for \"{{term}}\""
},
"modelAutocomplete": {
"modelLabel": "Model",
"searchPlaceholder": "Search and select a model...",
"clearSearch": "Clear search",
"modelSuggestions": "Model suggestions"
},
"account": {
"title": "Account",
"title": "My",
"personal": "Personal",
"role": "Role",
"dashboard": "Dashboard",
"logOut": "Log out",
"signUpDescription": "Sign up for an account to get access to the latest models, billing dashboard to view usage and credits, and more upcoming features.",
"signUpWithCline": "Sign up with Cline",
"agreeToTerms": "By continuing, you agree to the",
"termsOfService": "Terms of Service",
"privacyPolicyAnd": "Privacy Policy.",
"currentBalance": "CURRENT BALANCE",
"lastUpdated": "Last updated:",
"addCredits": "Add Credits",
"usageHistory": "USAGE HISTORY",
"paymentsHistory": "PAYMENTS HISTORY",
"loading": "Loading...",
"date": "Date",
"model": "Model",
"creditsUsed": "Credits Used",
"totalCost": "Total Cost",
"credits": "Credits",
"noUsageHistory": "No usage history",
"noPaymentHistory": "No payment history",
"webSearch": "Web Search",
"webFetch": "Web Fetch",
"webFetchLlm": "Web Fetch (LLM)",
"optOutOfRemoteConfig": "Opt out of remote config",
"cannotChangeWithRemoteConfig": "This cannot be changed while your organization has remote configuration enabled.",
"clineEnvironment": "Cline Environment",
"owner": "Owner",
"admin": "Admin",
"member": "Member",
"production": "Production",
"staging": "Staging",
"local": "Local",
"profile": "Profile"
},
"onboarding": {
"howWillYouUse": "How will you use Cline?",
"selectOption": "Select an option below to get started.",
"continue": "Continue",
"loginToCline": "Login to Cline",
"selectFreeModel": "Select a free model",
"selectYourModel": "Select your model",
"configureYourProvider": "Configure your provider",
"createMyAccount": "Create my Account",
"back": "Back",
"almostThere": "Almost there!",
"completeInBrowser": "Complete account creation in your browser. Then come back here to finish up.",
"absolutelyFree": "Absolutely Free",
"getStartedNoCost": "Get started at no cost",
"frontierModel": "Frontier Model",
"frontierModelDescription": "Claude, GPT Codex, Gemini, etc.",
"bringOwnKey": "Bring my own API key",
"bringOwnKeyDescription": "Use Cline with your provider of choice",
"canChangeLater": "You can change this later in settings",
"freeGroup": "free",
"frontierGroup": "frontier",
"openSourceGroup": "open source",
"support": "Support:",
"speed": "Speed:",
"context": "Context:",
"topPerformer": "Top Performer",
"great": "Great",
"good": "Good",
"average": "Average",
"belowAverage": "Below Average",
"instant": "Instant",
"fast": "Fast",
"slow": "Slow"
},
"history": {
"newest": "Newest",
"oldest": "Oldest",
"mostExpensive": "Most Expensive",
"mostTokens": "Most Tokens",
"mostRelevant": "Most Relevant",
"workspaceOnly": "Workspace Only",
"favoritesOnly": "Favorites Only",
"searchPlaceholder": "Fuzzy search history...",
"deleteSelected": "Delete selected items",
"deleteAll": "Delete all history",
"today": "Today",
"older": "Older",
"selectAll": "Select All",
"selectNone": "Select None",
"deleteSelectedCount": "Delete {{count}} Selected",
"deleteAllHistory": "Delete All History"
"logOut": "Log out"
}
}
}
@@ -94,7 +94,8 @@
"staging": "预发布",
"local": "本地",
"selfHosted": "自托管"
}
},
"clearSearch": "清除搜索"
},
"mcp": {
"configuration": {
@@ -226,7 +227,7 @@
"newTask": "新任务",
"mcpServers": "MCP 服务器",
"history": "历史记录",
"account": "账户",
"account": "我的",
"settings": "设置"
},
"browser": {
@@ -439,7 +440,8 @@
"older": "更早",
"selectAll": "全选",
"selectNone": "取消全选",
"deleteAllHistory": "删除所有历史记录"
"deleteAllHistory": "删除所有历史记录",
"deleteSelectedCount": "删除已选中的 {{count}} 项"
},
"historyView": {
"tokens": "Token",
@@ -452,6 +454,7 @@
},
"historyPreview": {
"viewAll": "查看全部",
"favorited": "已收藏"
"favorited": "已收藏",
"noRecentTasks": "暂无最近任务"
}
}
+56 -2
View File
@@ -30,7 +30,7 @@
"chat": {
"typeMessage": "输入消息...",
"typeTask": "在此输入你的任务...",
"contextHint": "输入 @ 添加上下文,输入 / 使用斜杠命令和工作流,按住 Shift 拖入文件/图片",
"contextHint": "Enter 发送,Ctrl+Enter 换行;输入 @ 添加上下文,输入 / 使用斜杠命令和工作流",
"addContext": "添加上下文",
"addFilesImages": "添加文件和图片",
"openApiSettings": "打开 API 设置",
@@ -371,7 +371,8 @@
"used": "已用:",
"total": "总计:",
"remaining": "剩余:",
"tokenUsage": "令牌使用量"
"tokenUsage": "令牌使用量",
"contextWindowUsage": "上下文窗口使用情况"
},
"focusChain": {
"allCompleted": "所有任务已完成!",
@@ -439,5 +440,58 @@
"dify": {
"workflowDescription": "Dify 工作流 - 模型选择已在您的 Dify 应用中配置"
}
},
"historyView": {
"addToFavorites": "添加收藏",
"delete": "删除",
"export": "导出",
"model": "模型",
"removeFromFavorites": "取消收藏",
"size": "大小",
"tokens": "Token"
},
"onboarding": {
"absolutelyFree": "完全免费",
"almostThere": "马上就好!",
"back": "返回",
"bringOwnKey": "使用自己的 API 密钥",
"bringOwnKeyDescription": "使用您的 API 密钥连接 Anthropic、OpenAI、OpenRouter、Google 或其他提供商。",
"completeInBrowser": "请在浏览器中完成账户设置...",
"configureYourProvider": "配置您的提供商",
"continue": "继续",
"createMyAccount": "创建我的账户",
"frontierModel": "旗舰模型",
"frontierModelDescription": "访问 Claude Sonnet 4.6 和 GPT-5 等旗舰模型进行复杂任务。",
"getStartedNoCost": "免费开始使用 Cline 提供的模型。",
"howWillYouUse": "您打算如何使用 Cline?",
"loginToCline": "登录 Cline",
"selectFreeModel": "选择一个免费模型",
"selectOption": "选择最适合您的选项。",
"selectYourModel": "选择您的模型"
},
"settings": {
"freeModel": "免费模型",
"recommendedModel": "推荐模型"
},
"settingsSections": {
"checkingConnection": "正在检查连接...",
"connected": "已连接",
"customBrowserArgsDescription": "启动 Chrome 时附加的额外命令行参数。",
"disableBrowserDescription": "禁用后,Cline 将无法使用浏览器工具。",
"disableBrowserToolUsage": "禁用浏览器工具使用",
"launchBrowserDebug": "以调试模式启动 Chrome",
"launchingBrowser": "正在启动浏览器...",
"leaveBlankAutoDetect": "留空可自动检测 Chrome 路径。",
"notConnected": "未连接",
"notDetectedOnMachine": "(未在您的电脑上检测到 Chrome)",
"remoteBrowserDebugManually": "这需要手动以调试模式启动 Chrome",
"remoteBrowserDescription": "允许 Cline 连接到远程 Chrome 实例。",
"useRemoteBrowserConnection": "使用远程浏览器连接",
"viewportSize": "视口大小",
"viewportSizeDescription": "浏览器工具使用的视口分辨率。",
"browser": {
"chromeExecutablePath": "Chrome 可执行文件路径",
"customBrowserArgs": "自定义浏览器参数"
}
}
}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more