Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8bb3527ea | ||
|
|
6965212ff7 | ||
|
|
376d10cbbb | ||
|
|
34bb7b9a93 | ||
|
|
8fbb954218 | ||
|
|
1f2646e685 | ||
|
|
b4c6cf59df | ||
|
|
945e4b39bd | ||
|
|
77c82adb10 | ||
|
|
26937786b9 | ||
|
|
895c4d9296 | ||
|
|
04f2c1c16a | ||
|
|
7aa4fd50c7 | ||
|
|
dd8a57b234 | ||
|
|
085e692741 | ||
|
|
269a8e0573 | ||
|
|
d2b86a9bf8 | ||
|
|
bf12d4ba8b | ||
|
|
f216473471 |
No files matched your search
@@ -0,0 +1 @@
|
||||
web_search = "disabled"
|
||||
@@ -84,3 +84,6 @@ test-results/
|
||||
*storybook.log
|
||||
storybook-static
|
||||
**/StorybookDecorator.tsx
|
||||
|
||||
# Exclude archive files
|
||||
*.zip
|
||||
+141
-2187
File diff suppressed because it is too large.
Load diff
@@ -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)。
|
||||
|
||||
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -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
@@ -2,7 +2,7 @@
|
||||
"name": "cline-multi",
|
||||
"displayName": "Cline Multi",
|
||||
"description": "%cline.description%",
|
||||
"version": "3.86.6",
|
||||
"version": "4.4.0",
|
||||
"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
@@ -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 令牌(测试用)",
|
||||
|
||||
@@ -55,6 +55,10 @@ service ModelsService {
|
||||
rpc getAihubmixModels(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
|
||||
// Refreshes and returns Vercel AI Gateway models
|
||||
rpc refreshVercelAiGatewayModelsRpc(EmptyRequest) returns (OpenRouterCompatibleModelInfo);
|
||||
// Refreshes models and pricing from models.dev and returns serialized JSON
|
||||
rpc refreshModelsDevModelsRpc(EmptyRequest) returns (String);
|
||||
// Subscribe to models.dev models updates (serialized JSON payload)
|
||||
rpc subscribeToModelsDevModels(EmptyRequest) returns (stream String);
|
||||
}
|
||||
|
||||
// List of VS Code LM models
|
||||
|
||||
@@ -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,9 @@ 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;
|
||||
optional bool models_dev_update_models = 191;
|
||||
optional bool models_dev_update_pricing = 192;
|
||||
}
|
||||
|
||||
message State {
|
||||
@@ -432,6 +440,8 @@ message UpdateSettingsRequest {
|
||||
optional bool double_check_completion_enabled = 41;
|
||||
optional bool show_feature_tips = 42;
|
||||
optional bool lazy_teammate_mode_enabled = 43;
|
||||
optional bool models_dev_update_models = 44;
|
||||
optional bool models_dev_update_pricing = 45;
|
||||
}
|
||||
|
||||
message UpdateTerminalConnectionTimeoutRequest {
|
||||
@@ -485,3 +495,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;
|
||||
}
|
||||
@@ -77,6 +77,14 @@ export async function initialize(storageContext: StorageContext): Promise<Webvie
|
||||
// Clean up orphaned file context warnings (startup cleanup)
|
||||
FileContextTracker.cleanupOrphanedWarnings(stateManager)
|
||||
|
||||
// =============== models.dev model & pricing updates ===============
|
||||
// Fire-and-forget: fetch latest models/pricing from models.dev per user settings
|
||||
// (modelsDevUpdateModels default true / modelsDevUpdatePricing default false) and apply
|
||||
// them onto the static model constants. Never blocks startup; failures are logged.
|
||||
import("./core/controller/models/refreshModelsDevModels")
|
||||
.then(({ refreshModelsDevModels }) => refreshModelsDevModels())
|
||||
.catch((error) => Logger.error("[models.dev] Startup refresh failed:", error))
|
||||
|
||||
telemetryService.captureExtensionActivated()
|
||||
|
||||
return webview
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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 } {
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -699,7 +699,6 @@ export class Controller {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Read OpenRouter models from disk cache
|
||||
async readOpenRouterModels(): Promise<Record<string, ModelInfo> | undefined> {
|
||||
const openRouterModelsFilePath = path.join(await ensureCacheDirectoryExists(), GlobalFileNames.openRouterModels)
|
||||
@@ -849,6 +848,8 @@ export class Controller {
|
||||
const doubleCheckCompletionEnabled = this.stateManager.getGlobalSettingsKey("doubleCheckCompletionEnabled")
|
||||
const lazyTeammateModeEnabled = this.stateManager.getGlobalSettingsKey("lazyTeammateModeEnabled")
|
||||
const showFeatureTips = this.stateManager.getGlobalSettingsKey("showFeatureTips")
|
||||
const modelsDevUpdateModels = this.stateManager.getGlobalSettingsKey("modelsDevUpdateModels")
|
||||
const modelsDevUpdatePricing = this.stateManager.getGlobalSettingsKey("modelsDevUpdatePricing")
|
||||
|
||||
const localClineRulesToggles = this.stateManager.getWorkspaceStateKey("localClineRulesToggles")
|
||||
const localWindsurfRulesToggles = this.stateManager.getWorkspaceStateKey("localWindsurfRulesToggles")
|
||||
@@ -961,6 +962,8 @@ export class Controller {
|
||||
doubleCheckCompletionEnabled,
|
||||
lazyTeammateModeEnabled,
|
||||
showFeatureTips,
|
||||
modelsDevUpdateModels,
|
||||
modelsDevUpdatePricing,
|
||||
banners,
|
||||
welcomeBanners,
|
||||
openAiCodexIsAuthenticated,
|
||||
@@ -990,7 +993,7 @@ export class Controller {
|
||||
|
||||
/*
|
||||
It seems that some API messages do not comply with vscode state requirements. Either the Anthropic library is manipulating these values somehow in the backend in a way that's creating cyclic references, or the API returns a function or a Symbol as part of the message content.
|
||||
VSCode docs about state: "The value must be JSON-stringifyable ... value �A value. MUST not contain cyclic references."
|
||||
VSCode docs about state: "The value must be JSON-stringifyable ... value �A value. MUST not contain cyclic references."
|
||||
For now we'll store the conversation history in memory, and if we need to store in state directly we'd need to do a manual conversion to ensure proper json stringification.
|
||||
*/
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import { ensureCacheDirectoryExists, GlobalFileNames } from "@core/storage/disk"
|
||||
import { fileExistsAtPath } from "@utils/fs"
|
||||
import axios from "axios"
|
||||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { StateManager } from "@/core/storage/StateManager"
|
||||
import {
|
||||
applyModelsDevCatalog,
|
||||
deserializeModelsDevCatalog,
|
||||
type ModelsDevCatalog,
|
||||
parseModelsDevCatalog,
|
||||
serializeModelsDevCatalog,
|
||||
} from "@/shared/models-dev"
|
||||
import { getAxiosSettings } from "@/shared/net"
|
||||
import { Logger } from "@/shared/services/Logger"
|
||||
import { sendModelsDevModelsEvent } from "./subscribeToModelsDevModels"
|
||||
|
||||
// Track pending refresh promise to prevent duplicate concurrent fetches
|
||||
let pendingRefresh: Promise<string> | null = null
|
||||
|
||||
// Last successfully fetched/loaded catalog for this process run.
|
||||
// The webview may subscribe AFTER the startup fetch has completed, so it
|
||||
// actively requests the catalog via RPC; serve it from here without refetching.
|
||||
let lastCatalogJson: string | null = null
|
||||
|
||||
/**
|
||||
* Reads the models.dev settings (update models / update pricing toggles).
|
||||
*/
|
||||
function getModelsDevOptions(): { updateModels: boolean; updatePricing: boolean } {
|
||||
const stateManager = StateManager.get()
|
||||
return {
|
||||
updateModels: stateManager.getGlobalSettingsKey("modelsDevUpdateModels") ?? true,
|
||||
updatePricing: stateManager.getGlobalSettingsKey("modelsDevUpdatePricing") ?? false,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the last cached models.dev catalog as serialized JSON (without fetching).
|
||||
*/
|
||||
export async function readModelsDevCatalogJson(): Promise<string | null> {
|
||||
const filePath = path.join(await ensureCacheDirectoryExists(), GlobalFileNames.modelsDevModels)
|
||||
if (await fileExistsAtPath(filePath)) {
|
||||
try {
|
||||
const contents = await fs.readFile(filePath, "utf8")
|
||||
if (deserializeModelsDevCatalog(contents)) {
|
||||
return contents
|
||||
}
|
||||
} catch (error) {
|
||||
Logger.error("Error reading cached models.dev catalog:", error)
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the models.dev catalogs (models + pricing), applies them onto the static
|
||||
* model constants in this process, caches them to disk, and pushes the result to
|
||||
* webview subscribers.
|
||||
*
|
||||
* Both toggles OFF short-circuits (returns cached data if present).
|
||||
* On network failure the disk cache is used as fallback so models stay consistent.
|
||||
*
|
||||
* @returns Serialized ModelsDevCatalog JSON
|
||||
*/
|
||||
export async function refreshModelsDevModels(force = false): Promise<string> {
|
||||
// Already fetched during this process run: serve cached result without refetching
|
||||
// (unless force is requested, e.g. a toggle was just re-enabled)
|
||||
if (lastCatalogJson && !force) {
|
||||
return lastCatalogJson
|
||||
}
|
||||
|
||||
if (force) {
|
||||
lastCatalogJson = null
|
||||
}
|
||||
|
||||
// If a fetch is already in progress, return the same promise
|
||||
if (pendingRefresh) {
|
||||
return pendingRefresh
|
||||
}
|
||||
|
||||
// Start new fetch and track the promise
|
||||
pendingRefresh = (async () => {
|
||||
try {
|
||||
return await fetchAndCacheModels()
|
||||
} finally {
|
||||
pendingRefresh = null
|
||||
}
|
||||
})()
|
||||
|
||||
return pendingRefresh
|
||||
}
|
||||
|
||||
async function fetchAndCacheModels(): Promise<string> {
|
||||
const filePath = path.join(await ensureCacheDirectoryExists(), GlobalFileNames.modelsDevModels)
|
||||
const { updateModels, updatePricing } = getModelsDevOptions()
|
||||
|
||||
// Both toggles off: nothing to do, return cached catalog if present
|
||||
if (!updateModels && !updatePricing) {
|
||||
const cached = await readModelsDevCatalogJson()
|
||||
return cached ?? serializeModelsDevCatalog({ fetchedAt: new Date(0).toISOString(), providers: {} })
|
||||
}
|
||||
|
||||
let catalog: ModelsDevCatalog | null = null
|
||||
try {
|
||||
// models.json contains limits/modalities/reasoning for every provider/model
|
||||
// api.json contains per-provider pricing (cost) — both are per-million USD
|
||||
const [modelsRes, apiRes] = await Promise.all([
|
||||
axios.get("https://models.dev/models.json?type=all", { timeout: 15000, ...getAxiosSettings() }),
|
||||
axios.get("https://models.dev/api.json", { timeout: 15000, ...getAxiosSettings() }),
|
||||
])
|
||||
catalog = parseModelsDevCatalog(modelsRes.data, apiRes.data)
|
||||
if (!catalog.providers || Object.keys(catalog.providers).length === 0) {
|
||||
throw new Error("models.dev catalog parsed to zero providers")
|
||||
}
|
||||
// Persist to disk cache for offline fallback
|
||||
await fs.writeFile(filePath, serializeModelsDevCatalog(catalog))
|
||||
} catch (error) {
|
||||
Logger.error("Error fetching models.dev catalog:", error)
|
||||
// Fall back to disk cache so previously fetched data stays effective
|
||||
const cached = await readModelsDevCatalogJson()
|
||||
if (cached) {
|
||||
catalog = deserializeModelsDevCatalog(cached)
|
||||
}
|
||||
}
|
||||
|
||||
if (!catalog) {
|
||||
// Nothing fetched and nothing cached: keep static defaults untouched
|
||||
return serializeModelsDevCatalog({ fetchedAt: new Date(0).toISOString(), providers: {} })
|
||||
}
|
||||
|
||||
// Apply onto this process's static model constants
|
||||
const applied = applyModelsDevCatalog(catalog, { updateModels, updatePricing })
|
||||
Logger.log(
|
||||
`[models.dev] catalog applied: ${applied.added} new models added, ${applied.priced} models repriced ` +
|
||||
`(updateModels=${updateModels}, updatePricing=${updatePricing})`,
|
||||
)
|
||||
|
||||
const serialized = serializeModelsDevCatalog(catalog)
|
||||
lastCatalogJson = serialized
|
||||
|
||||
// Push to webview subscribers (they apply the catalog onto their own copies)
|
||||
await sendModelsDevModelsEvent(serialized)
|
||||
|
||||
return serialized
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { EmptyRequest, String } from "@shared/proto/cline/common"
|
||||
import type { Controller } from "../index"
|
||||
import { refreshModelsDevModels } from "./refreshModelsDevModels"
|
||||
|
||||
/**
|
||||
* Refreshes models and pricing from models.dev, applies them to the local
|
||||
* static model constants, caches the catalog, and pushes it to subscribers.
|
||||
* @param controller The controller instance
|
||||
* @param request Empty request (unused but required for gRPC signature)
|
||||
* @returns Serialized ModelsDevCatalog JSON
|
||||
*/
|
||||
export async function refreshModelsDevModelsRpc(_controller: Controller, _request: EmptyRequest): Promise<String> {
|
||||
const catalogJson = await refreshModelsDevModels()
|
||||
return String.create({ value: catalogJson })
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { EmptyRequest, String } from "@shared/proto/cline/common"
|
||||
import { Logger } from "@/shared/services/Logger"
|
||||
import { getRequestRegistry, StreamingResponseHandler } from "../grpc-handler"
|
||||
import { Controller } from "../index"
|
||||
|
||||
// Keep track of active models.dev models subscriptions
|
||||
const activeModelsDevModelsSubscriptions = new Set<StreamingResponseHandler<String>>()
|
||||
|
||||
/**
|
||||
* Subscribe to models.dev models events (serialized ModelsDevCatalog JSON payloads)
|
||||
* @param controller The controller instance
|
||||
* @param request The empty request
|
||||
* @param responseStream The streaming response handler
|
||||
* @param requestId The ID of the request (passed by the gRPC handler)
|
||||
*/
|
||||
export async function subscribeToModelsDevModels(
|
||||
_controller: Controller,
|
||||
_request: EmptyRequest,
|
||||
responseStream: StreamingResponseHandler<String>,
|
||||
requestId?: string,
|
||||
): Promise<void> {
|
||||
// Add this subscription to the active subscriptions
|
||||
activeModelsDevModelsSubscriptions.add(responseStream)
|
||||
|
||||
// Register cleanup when the connection is closed
|
||||
const cleanup = () => {
|
||||
activeModelsDevModelsSubscriptions.delete(responseStream)
|
||||
}
|
||||
|
||||
// Register the cleanup function with the request registry if we have a requestId
|
||||
if (requestId) {
|
||||
getRequestRegistry().registerRequest(requestId, cleanup, { type: "modelsDevModels_subscription" }, responseStream)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a models.dev models event to all active subscribers
|
||||
* @param catalogJson Serialized ModelsDevCatalog JSON
|
||||
*/
|
||||
export async function sendModelsDevModelsEvent(catalogJson: string): Promise<void> {
|
||||
const payload = String.create({ value: catalogJson })
|
||||
// Send the event to all active subscribers
|
||||
const promises = Array.from(activeModelsDevModelsSubscriptions).map(async (responseStream) => {
|
||||
try {
|
||||
await responseStream(
|
||||
payload,
|
||||
false, // Not the last message
|
||||
)
|
||||
} catch (error) {
|
||||
Logger.error("Error sending models.dev models event:", error)
|
||||
// Remove the subscription if there was an error
|
||||
activeModelsDevModelsSubscriptions.delete(responseStream)
|
||||
}
|
||||
})
|
||||
|
||||
await Promise.all(promises)
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
@@ -352,6 +352,28 @@ export async function updateSettings(controller: Controller, request: UpdateSett
|
||||
controller.stateManager.setGlobalState("showFeatureTips", request.showFeatureTips)
|
||||
}
|
||||
|
||||
// Update models.dev integration toggles; trigger a refresh when enabling either toggle
|
||||
if (request.modelsDevUpdateModels !== undefined || request.modelsDevUpdatePricing !== undefined) {
|
||||
const prevModels = controller.stateManager.getGlobalSettingsKey("modelsDevUpdateModels") ?? true
|
||||
const prevPricing = controller.stateManager.getGlobalSettingsKey("modelsDevUpdatePricing") ?? false
|
||||
if (request.modelsDevUpdateModels !== undefined) {
|
||||
controller.stateManager.setGlobalState("modelsDevUpdateModels", request.modelsDevUpdateModels)
|
||||
}
|
||||
if (request.modelsDevUpdatePricing !== undefined) {
|
||||
controller.stateManager.setGlobalState("modelsDevUpdatePricing", request.modelsDevUpdatePricing)
|
||||
}
|
||||
const enabledAny =
|
||||
(request.modelsDevUpdateModels === true && !prevModels) ||
|
||||
(request.modelsDevUpdatePricing === true && !prevPricing)
|
||||
if (enabledAny) {
|
||||
// Fire-and-forget: apply immediately and push the catalog to subscribers
|
||||
// (force bypasses the in-process catalog cache since toggles just changed)
|
||||
import("../models/refreshModelsDevModels")
|
||||
.then(({ refreshModelsDevModels }) => refreshModelsDevModels(true))
|
||||
.catch((error) => Logger.error("Failed to refresh models.dev models:", error))
|
||||
}
|
||||
}
|
||||
|
||||
// Post updated state to webview
|
||||
await controller.postStateToWebview()
|
||||
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -48,6 +48,7 @@ export const GlobalFileNames = {
|
||||
clineRecommendedModels: "cline_recommended_models.json",
|
||||
clineModels: "cline_models.json",
|
||||
openRouterModels: "openrouter_models.json",
|
||||
modelsDevModels: "models_dev_models.json",
|
||||
vercelAiGatewayModels: "vercel_ai_gateway_models.json",
|
||||
groqModels: "groq_models.json",
|
||||
basetenModels: "baseten_models.json",
|
||||
|
||||
@@ -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()
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -110,6 +110,8 @@ export interface ExtensionState {
|
||||
doubleCheckCompletionEnabled?: boolean
|
||||
lazyTeammateModeEnabled?: boolean
|
||||
showFeatureTips?: boolean
|
||||
modelsDevUpdateModels?: boolean
|
||||
modelsDevUpdatePricing?: boolean
|
||||
banners?: BannerCardData[]
|
||||
welcomeBanners?: BannerCardData[]
|
||||
openAiCodexIsAuthenticated?: boolean
|
||||
@@ -349,6 +351,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?: {
|
||||
|
||||
@@ -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[]
|
||||
}
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,297 @@
|
||||
import type { ModelInfo } from "./api"
|
||||
import {
|
||||
anthropicModels,
|
||||
askSageModels,
|
||||
basetenModels,
|
||||
bedrockModels,
|
||||
cerebrasModels,
|
||||
claudeCodeModels,
|
||||
deepSeekModels,
|
||||
doubaoModels,
|
||||
fireworksModels,
|
||||
geminiModels,
|
||||
groqModels,
|
||||
huaweiCloudMaasModels,
|
||||
huggingFaceModels,
|
||||
internationalQwenModels,
|
||||
internationalZAiModels,
|
||||
mainlandQwenModels,
|
||||
mainlandZAiModels,
|
||||
minimaxModels,
|
||||
mistralModels,
|
||||
moonshotModels,
|
||||
nebiusModels,
|
||||
nousResearchModels,
|
||||
openAiNativeModels,
|
||||
sambanovaModels,
|
||||
vertexModels,
|
||||
wandbModels,
|
||||
xaiModels,
|
||||
} from "./api"
|
||||
|
||||
/**
|
||||
* models.dev integration — shared between the extension core and the webview.
|
||||
*
|
||||
* The models.dev catalogs are fetched at startup (core) and pushed to the webview.
|
||||
* Both sides then "apply" the catalog onto the static model constants from
|
||||
* `@shared/api` so that new models appear in pickers and pricing stays current.
|
||||
*/
|
||||
|
||||
/** Raw model entry from https://models.dev/models.json (or api.json). */
|
||||
export interface ModelsDevRawModel {
|
||||
id?: string
|
||||
name?: string
|
||||
description?: string
|
||||
/** modalities.input may contain "text" | "image" | "pdf" | "audio" | ... */
|
||||
modalities?: { input?: string[]; output?: string[] }
|
||||
/** models.json (type=all) embeds limits directly */
|
||||
limit?: { context?: number; output?: number; input?: number }
|
||||
reasoning?: boolean
|
||||
release_date?: string
|
||||
last_updated?: string
|
||||
/** api.json only: pricing per million tokens */
|
||||
cost?: { input?: number; output?: number; cache_read?: number; cache_write?: number }
|
||||
}
|
||||
|
||||
/**
|
||||
* The fetched catalog: for each Cline model constant key (e.g. "anthropicModels"),
|
||||
* the models.dev entries that should be merged into it.
|
||||
*/
|
||||
export interface ModelsDevCatalog {
|
||||
/** ISO timestamp of when the catalog was fetched */
|
||||
fetchedAt: string
|
||||
/** providerKey (Cline constant name) -> modelId -> ModelInfo */
|
||||
providers: Record<string, Record<string, ModelInfo>>
|
||||
}
|
||||
|
||||
/** Model constants registry, keyed by the names used in the catalog. */
|
||||
const MODEL_CONSTANTS: Record<string, Record<string, ModelInfo>> = {
|
||||
anthropicModels,
|
||||
claudeCodeModels,
|
||||
bedrockModels,
|
||||
vertexModels,
|
||||
geminiModels,
|
||||
openAiNativeModels,
|
||||
deepSeekModels,
|
||||
huggingFaceModels,
|
||||
internationalQwenModels,
|
||||
mainlandQwenModels,
|
||||
doubaoModels,
|
||||
mistralModels,
|
||||
askSageModels,
|
||||
nebiusModels,
|
||||
wandbModels,
|
||||
xaiModels,
|
||||
sambanovaModels,
|
||||
cerebrasModels,
|
||||
groqModels,
|
||||
moonshotModels,
|
||||
huaweiCloudMaasModels,
|
||||
basetenModels,
|
||||
internationalZAiModels,
|
||||
mainlandZAiModels,
|
||||
fireworksModels,
|
||||
minimaxModels,
|
||||
nousResearchModels,
|
||||
}
|
||||
|
||||
/**
|
||||
* Mapping from models.dev provider ids to Cline model constant names.
|
||||
* models.dev model ids are "provider/model-id"; the provider prefix is stripped
|
||||
* before looking up the model id in the target constants.
|
||||
*/
|
||||
export const MODELS_DEV_PROVIDER_MAP: Record<string, string[]> = {
|
||||
anthropic: ["anthropicModels", "claudeCodeModels"],
|
||||
google: ["geminiModels"],
|
||||
"google-vertex": ["vertexModels"],
|
||||
"amazon-bedrock": ["bedrockModels"],
|
||||
openai: ["openAiNativeModels"],
|
||||
deepseek: ["deepSeekModels"],
|
||||
xai: ["xaiModels"],
|
||||
moonshotai: ["moonshotModels"],
|
||||
moonshot: ["moonshotModels"],
|
||||
alibaba: ["internationalQwenModels"],
|
||||
"alibaba-cn": ["mainlandQwenModels"],
|
||||
zhipuai: ["internationalZAiModels"],
|
||||
"zhipuai-cn": ["mainlandZAiModels"],
|
||||
minimax: ["minimaxModels"],
|
||||
mistral: ["mistralModels"],
|
||||
cohere: ["askSageModels"],
|
||||
fireworks: ["fireworksModels"],
|
||||
groq: ["groqModels"],
|
||||
cerebras: ["cerebrasModels"],
|
||||
nebius: ["nebiusModels"],
|
||||
sambanova: ["sambanovaModels"],
|
||||
bytedance: ["doubaoModels"],
|
||||
"bytedance-ark": ["doubaoModels"],
|
||||
huggingface: ["huggingFaceModels"],
|
||||
nousresearch: ["nousResearchModels"],
|
||||
wandb: ["wandbModels"],
|
||||
baseten: ["basetenModels"],
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse raw models.dev data (models.json + api.json) into a ModelsDevCatalog.
|
||||
*
|
||||
* - models.json (type=all): flat map "provider/model-id" -> entry (limits, modalities, reasoning)
|
||||
* - api.json: provider -> { models: { modelId -> entry (limits, modalities, cost) } }
|
||||
*
|
||||
* @param modelsJson Raw `models.json` payload (may be undefined to skip)
|
||||
* @param apiJson Raw `api.json` payload (may be undefined to skip)
|
||||
*/
|
||||
export function parseModelsDevCatalog(
|
||||
modelsJson?: Record<string, ModelsDevRawModel>,
|
||||
apiJson?: Record<string, any>,
|
||||
): ModelsDevCatalog {
|
||||
const providers: ModelsDevCatalog["providers"] = {}
|
||||
|
||||
const addModel = (providerKey: string, modelId: string, info: ModelInfo) => {
|
||||
if (!providers[providerKey]) {
|
||||
providers[providerKey] = {}
|
||||
}
|
||||
providers[providerKey][modelId] = info
|
||||
}
|
||||
|
||||
const convert = (raw: ModelsDevRawModel): ModelInfo | null => {
|
||||
const contextWindow = raw.limit?.context
|
||||
if (!contextWindow || contextWindow <= 0) {
|
||||
return null
|
||||
}
|
||||
const inputs = raw.modalities?.input ?? []
|
||||
const supportsReasoning = raw.reasoning === true
|
||||
return {
|
||||
name: raw.name ?? undefined,
|
||||
description: raw.description ?? undefined,
|
||||
contextWindow,
|
||||
maxTokens: raw.limit?.output ?? undefined,
|
||||
supportsImages: inputs.includes("image"),
|
||||
supportsPromptCache: false,
|
||||
inputPrice: raw.cost?.input ?? undefined,
|
||||
outputPrice: raw.cost?.output ?? undefined,
|
||||
cacheReadsPrice: raw.cost?.cache_read ?? undefined,
|
||||
cacheWritesPrice: raw.cost?.cache_write ?? undefined,
|
||||
supportsReasoning,
|
||||
// Reasoning models get a thinking budget placeholder so the thinking UI works
|
||||
thinkingConfig: supportsReasoning ? { maxBudget: 8192 } : undefined,
|
||||
}
|
||||
}
|
||||
|
||||
// --- models.json (type=all): flat "provider/model" keys ---
|
||||
if (modelsJson) {
|
||||
for (const [fullId, raw] of Object.entries(modelsJson)) {
|
||||
const slashIdx = fullId.indexOf("/")
|
||||
if (slashIdx <= 0) {
|
||||
continue
|
||||
}
|
||||
const devProvider = fullId.slice(0, slashIdx)
|
||||
const modelId = fullId.slice(slashIdx + 1)
|
||||
const targets = MODELS_DEV_PROVIDER_MAP[devProvider]
|
||||
if (!targets) {
|
||||
continue
|
||||
}
|
||||
const info = convert(raw)
|
||||
if (!info) {
|
||||
continue
|
||||
}
|
||||
for (const target of targets) {
|
||||
addModel(target, modelId, info)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- api.json: provider -> { models: {...} } ---
|
||||
if (apiJson) {
|
||||
for (const [devProvider, providerData] of Object.entries(apiJson)) {
|
||||
const targets = MODELS_DEV_PROVIDER_MAP[devProvider]
|
||||
if (!targets || !providerData?.models) {
|
||||
continue
|
||||
}
|
||||
for (const [modelId, raw] of Object.entries<any>(providerData.models)) {
|
||||
const info = convert(raw)
|
||||
if (!info) {
|
||||
continue
|
||||
}
|
||||
for (const target of targets) {
|
||||
addModel(target, modelId, info)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { fetchedAt: new Date().toISOString(), providers }
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a models.dev catalog onto Cline's static model constants (mutates them).
|
||||
*
|
||||
* Rules:
|
||||
* - "Update models" ON: new model IDs found in the catalog are ADDED to the constants.
|
||||
* Existing model IDs keep their locally curated metadata (never overwritten).
|
||||
* - "Update pricing" ON: pricing fields (input/output/cache read/write) of EXISTING
|
||||
* models are refreshed from the catalog when the catalog provides them.
|
||||
*
|
||||
* @returns number of new models added and models whose pricing was updated.
|
||||
*/
|
||||
export function applyModelsDevCatalog(
|
||||
catalog: ModelsDevCatalog,
|
||||
options: { updateModels: boolean; updatePricing: boolean },
|
||||
): { added: number; priced: number } {
|
||||
let added = 0
|
||||
let priced = 0
|
||||
|
||||
for (const [constantKey, models] of Object.entries(catalog.providers)) {
|
||||
const target = MODEL_CONSTANTS[constantKey]
|
||||
if (!target) {
|
||||
continue
|
||||
}
|
||||
|
||||
for (const [modelId, incoming] of Object.entries(models)) {
|
||||
const existing = target[modelId]
|
||||
if (!existing) {
|
||||
if (!options.updateModels) {
|
||||
continue
|
||||
}
|
||||
// New model: add with catalog info
|
||||
target[modelId] = incoming
|
||||
added++
|
||||
} else if (options.updatePricing) {
|
||||
// Existing model: refresh pricing when provided
|
||||
let touched = false
|
||||
for (const key of ["inputPrice", "outputPrice", "cacheReadsPrice", "cacheWritesPrice"] as const) {
|
||||
const v = incoming[key]
|
||||
if (v !== undefined && existing[key] !== v) {
|
||||
;(existing as any)[key] = v
|
||||
touched = true
|
||||
}
|
||||
}
|
||||
if (touched) {
|
||||
priced++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { added, priced }
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialize the catalog for transport (gRPC String payloads / disk cache).
|
||||
*/
|
||||
export function serializeModelsDevCatalog(catalog: ModelsDevCatalog): string {
|
||||
return JSON.stringify(catalog)
|
||||
}
|
||||
|
||||
/**
|
||||
* Deserialize a catalog from transport (gRPC String payloads / disk cache).
|
||||
*/
|
||||
export function deserializeModelsDevCatalog(json: string): ModelsDevCatalog | null {
|
||||
try {
|
||||
const parsed = JSON.parse(json)
|
||||
if (!parsed || typeof parsed !== "object" || !parsed.providers || typeof parsed.providers !== "object") {
|
||||
return null
|
||||
}
|
||||
return parsed as ModelsDevCatalog
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
@@ -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 },
|
||||
@@ -290,6 +291,8 @@ const USER_SETTINGS_FIELDS = {
|
||||
doubleCheckCompletionEnabled: { default: false as boolean },
|
||||
lazyTeammateModeEnabled: { default: false as boolean },
|
||||
showFeatureTips: { default: true as boolean },
|
||||
modelsDevUpdateModels: { default: true as boolean },
|
||||
modelsDevUpdatePricing: { default: false as boolean },
|
||||
|
||||
// OpenTelemetry configuration
|
||||
openTelemetryEnabled: { default: true as boolean },
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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}`} />)
|
||||
})
|
||||
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -2,6 +2,11 @@ import { VSCodeLink } from "@vscode/webview-ui-toolkit/react"
|
||||
import { useTranslation } from "react-i18next"
|
||||
import Section from "../Section"
|
||||
|
||||
const PROJECT_GITHUB_URL = "https://github.com/Adam-PAN/cline-multi"
|
||||
const PROJECT_ISSUES_URL = "https://github.com/Adam-PAN/cline-multi/issues"
|
||||
const PROJECT_RELEASES_URL = "https://github.com/Adam-PAN/cline-multi/releases"
|
||||
const UPSTREAM_CLINE_URL = "https://github.com/cline/cline"
|
||||
|
||||
interface AboutSectionProps {
|
||||
version: string
|
||||
renderSectionHeader: (tabId: string) => JSX.Element | null
|
||||
@@ -16,32 +21,29 @@ const AboutSection = ({ version, renderSectionHeader }: AboutSectionProps) => {
|
||||
<h2 className="text-lg font-semibold">{t("settingsSections.aboutVersion", { version })}</h2>
|
||||
<p>{t("settingsSections.aboutDescription")}</p>
|
||||
|
||||
<h3 className="text-md font-semibold">{t("settingsSections.communitySupport")}</h3>
|
||||
<h3 className="text-md font-semibold">{t("settingsSections.coreFeatures")}</h3>
|
||||
<ul className="list-disc pl-5 flex flex-col gap-1">
|
||||
<li>{t("settingsSections.featureMultiModelHotSwap")}</li>
|
||||
<li>{t("settingsSections.featureCnModelAdaptation")}</li>
|
||||
<li>{t("settingsSections.featureFriendlyErrors")}</li>
|
||||
<li>{t("settingsSections.featureCostMonitoring")}</li>
|
||||
<li>{t("settingsSections.featureCnSupport")}</li>
|
||||
<li>{t("settingsSections.featureSmartContext")}</li>
|
||||
</ul>
|
||||
|
||||
<h3 className="text-md font-semibold">{t("settingsSections.projectLinks")}</h3>
|
||||
<p>
|
||||
<VSCodeLink href="https://x.com/cline">X</VSCodeLink>
|
||||
<VSCodeLink href={PROJECT_GITHUB_URL}>GitHub</VSCodeLink>
|
||||
{" • "}
|
||||
<VSCodeLink href="https://discord.gg/cline">Discord</VSCodeLink>
|
||||
<VSCodeLink href={PROJECT_RELEASES_URL}>{t("settingsSections.releases")}</VSCodeLink>
|
||||
{" • "}
|
||||
<VSCodeLink href="https://www.reddit.com/r/cline/"> r/cline</VSCodeLink>
|
||||
<VSCodeLink href={PROJECT_ISSUES_URL}>{t("settingsSections.issues")}</VSCodeLink>
|
||||
</p>
|
||||
|
||||
<h3 className="text-md font-semibold">{t("settingsSections.development")}</h3>
|
||||
<h3 className="text-md font-semibold">{t("settingsSections.acknowledgement")}</h3>
|
||||
<p>
|
||||
<VSCodeLink href="https://github.com/cline/cline">GitHub</VSCodeLink>
|
||||
{" • "}
|
||||
<VSCodeLink href="https://github.com/cline/cline/issues"> {t("settingsSections.issues")}</VSCodeLink>
|
||||
{" • "}
|
||||
<VSCodeLink href="https://github.com/cline/cline/discussions/categories/feature-requests?discussions_q=is%3Aopen+category%3A%22Feature+Requests%22+sort%3Atop">
|
||||
{" "}
|
||||
{t("settingsSections.featureRequests")}
|
||||
</VSCodeLink>
|
||||
</p>
|
||||
|
||||
<h3 className="text-md font-semibold">{t("settingsSections.resources")}</h3>
|
||||
<p>
|
||||
<VSCodeLink href="https://docs.cline.bot/">{t("settingsSections.documentation")}</VSCodeLink>
|
||||
{" • "}
|
||||
<VSCodeLink href="https://cline.bot/">https://cline.bot</VSCodeLink>
|
||||
{t("settingsSections.acknowledgementPrefix")} <VSCodeLink href={UPSTREAM_CLINE_URL}>Cline</VSCodeLink>
|
||||
{t("settingsSections.acknowledgementSuffix")}
|
||||
</p>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -12,7 +12,7 @@ interface GeneralSettingsSectionProps {
|
||||
|
||||
const GeneralSettingsSection = ({ renderSectionHeader }: GeneralSettingsSectionProps) => {
|
||||
const { t } = useTranslation("settings")
|
||||
const { telemetrySetting, remoteConfigSettings } = useExtensionState()
|
||||
const { telemetrySetting, remoteConfigSettings, modelsDevUpdateModels, modelsDevUpdatePricing } = useExtensionState()
|
||||
|
||||
return (
|
||||
<div>
|
||||
@@ -20,6 +20,28 @@ const GeneralSettingsSection = ({ renderSectionHeader }: GeneralSettingsSectionP
|
||||
<Section>
|
||||
<PreferredLanguageSetting />
|
||||
|
||||
<div className="mb-[5px]">
|
||||
<VSCodeCheckbox
|
||||
checked={modelsDevUpdateModels !== false}
|
||||
onChange={(e: any) => {
|
||||
const checked = e.target.checked === true
|
||||
updateSetting("modelsDevUpdateModels", checked)
|
||||
}}>
|
||||
{t("settingsSections.modelsDevUpdateModels")}
|
||||
</VSCodeCheckbox>
|
||||
<p className="text-sm mt-[5px] text-description">{t("settingsSections.modelsDevUpdateDescription")}</p>
|
||||
<div className="mt-[5px]">
|
||||
<VSCodeCheckbox
|
||||
checked={modelsDevUpdatePricing === true}
|
||||
onChange={(e: any) => {
|
||||
const checked = e.target.checked === true
|
||||
updateSetting("modelsDevUpdatePricing", checked)
|
||||
}}>
|
||||
{t("settingsSections.modelsDevUpdatePricing")}
|
||||
</VSCodeCheckbox>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-[5px]">
|
||||
<Tooltip>
|
||||
<TooltipContent hidden={remoteConfigSettings?.telemetrySetting === undefined}>
|
||||
@@ -51,8 +73,7 @@ const GeneralSettingsSection = ({ renderSectionHeader }: GeneralSettingsSectionP
|
||||
style={{ fontSize: "inherit", textDecoration: "underline" }}>
|
||||
{t("settingsSections.telemetryOverview")}
|
||||
</VSCodeLink>{" "}
|
||||
{t("settingsSections.telemetryAnd")}
|
||||
{" "}
|
||||
{t("settingsSections.telemetryAnd")}{" "}
|
||||
<VSCodeLink
|
||||
className="text-inherit"
|
||||
href="https://cline.bot/privacy"
|
||||
|
||||
@@ -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
|
||||
Loaded 100 of 113 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user