Compare commits

Author SHA1 Message Date
Adam-PAN d8bb3527ea feat: 通过 models.dev 在启动时自动更新各厂商最新模型与定价
E2E Tests / matrix_prep (push) Canceled after 0s
E2E Tests / e2e (push) Canceled after 0s
Tests / Quality Checks (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Tests / test (windows-latest) (push) Canceled after 0s
Tests / test-platform-integration (push) Canceled after 0s
Tests / qlty (push) Canceled after 0s
- 设置 新增两个开关:通过 models.dev 更新模型(默认开)、通过 models.dev 更新定价(默认关)- 勾选时每次启动从 models.dev/models.json 与 api.json 拉取最新模型目录与价格,合并进各厂商模型列表(保留本地精调元数据)- 目录缓存至磁盘作为离线回退,并通过 gRPC 订阅 + 订阅后主动拉取推送至 webview,消除启动竞态- 新增 RPC:refreshModelsDevModelsRpc / subscribeToModelsDevModels- 版本升级至 4.4.0,更新 CHANGELOG
2026-09-29 15:13:59 +08:00
19 changed files with 693 additions and 33 deletions

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# Changelog
## [4.4.0]
### Added
- **models.dev auto-update**: Two new toggles in Settings → General — "Update models via models.dev" (default: on) and "Update pricing via models.dev" (default: off). When enabled, the latest provider model catalog (models.json) and model pricing (api.json) are fetched from models.dev on every startup and merged into the built-in model lists
- New models released by providers (DeepSeek, Qwen, GLM, Kimi, Doubao, MiniMax, etc.) now appear in the model dropdowns without waiting for an extension update — locally fine-tuned metadata (context limits, thinking budgets, vision support) is always preserved
- Fetched catalogs are cached to disk as an offline fallback, and pushed to the webview via a subscription with an active pull-on-subscribe fallback to avoid startup race conditions
## [4.3.1]
### Fixed
+1 -1
View File
@@ -2,7 +2,7 @@
"name": "cline-multi",
"displayName": "Cline Multi",
"description": "%cline.description%",
"version": "4.3.1",
"version": "4.4.0",
"icon": "assets/icons/icon.png",
"workspaces": [
"."
+4
View File
@@ -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
+4
View File
@@ -295,6 +295,8 @@ message Settings {
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 {
@@ -438,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 {
+8
View File
@@ -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
+5 -2
View File
@@ -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)
}
@@ -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()
+1
View File
@@ -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",
+2
View File
@@ -110,6 +110,8 @@ export interface ExtensionState {
doubleCheckCompletionEnabled?: boolean
lazyTeammateModeEnabled?: boolean
showFeatureTips?: boolean
modelsDevUpdateModels?: boolean
modelsDevUpdatePricing?: boolean
banners?: BannerCardData[]
welcomeBanners?: BannerCardData[]
openAiCodexIsAuthenticated?: boolean
+297
View File
@@ -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
}
}
+2
View File
@@ -291,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 },
@@ -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>
@@ -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"
@@ -4,6 +4,7 @@ import { DEFAULT_BROWSER_SETTINGS } from "@shared/BrowserSettings"
import { DEFAULT_PLATFORM, type ExtensionState } from "@shared/ExtensionMessage"
import { DEFAULT_FOCUS_CHAIN_SETTINGS } from "@shared/FocusChainSettings"
import { DEFAULT_MCP_DISPLAY_MODE } from "@shared/McpDisplayMode"
import { applyModelsDevCatalog, deserializeModelsDevCatalog } from "@shared/models-dev"
import type { UserInfo } from "@shared/proto/cline/account"
import { EmptyRequest } from "@shared/proto/cline/common"
import type { OpenRouterCompatibleModelInfo } from "@shared/proto/cline/models"
@@ -300,6 +301,8 @@ export const ExtensionStateContextProvider: React.FC<{
doubleCheckCompletionEnabled: false,
lazyTeammateModeEnabled: false,
showFeatureTips: true,
modelsDevUpdateModels: true,
modelsDevUpdatePricing: false,
globalSkillsToggles: {},
localSkillsToggles: {},
@@ -358,6 +361,30 @@ export const ExtensionStateContextProvider: React.FC<{
const [mcpServers, setMcpServers] = useState<McpServer[]>([])
const [mcpMarketplaceCatalog, setMcpMarketplaceCatalog] = useState<McpMarketplaceCatalog>({ items: [] })
// Keep latest models.dev toggles in refs so subscription callbacks (created once)
// always apply the catalog with the current user settings.
const modelsDevTogglesRef = useRef({ updateModels: true, updatePricing: false })
useEffect(() => {
modelsDevTogglesRef.current = {
updateModels: state.modelsDevUpdateModels ?? true,
updatePricing: state.modelsDevUpdatePricing ?? false,
}
}, [state.modelsDevUpdateModels, state.modelsDevUpdatePricing])
// Apply a serialized models.dev catalog onto this process's model constants
// and force a re-render so pickers re-read the mutated constants.
const applyModelsDevCatalogJson = useCallback((json: string | undefined | null) => {
if (!json) {
return
}
const catalog = deserializeModelsDevCatalog(json)
if (!catalog) {
return
}
applyModelsDevCatalog(catalog, modelsDevTogglesRef.current)
setState((prevState) => ({ ...prevState }))
}, [])
// References to store subscription cancellation functions
const stateSubscriptionRef = useRef<(() => void) | null>(null)
@@ -371,6 +398,7 @@ export const ExtensionStateContextProvider: React.FC<{
const mcpMarketplaceUnsubscribeRef = useRef<(() => void) | null>(null)
const openRouterModelsUnsubscribeRef = useRef<(() => void) | null>(null)
const liteLlmModelsUnsubscribeRef = useRef<(() => void) | null>(null)
const modelsDevModelsUnsubscribeRef = useRef<(() => void) | null>(null)
const workspaceUpdatesUnsubscribeRef = useRef<(() => void) | null>(null)
const relinquishControlUnsubscribeRef = useRef<(() => void) | null>(null)
@@ -603,6 +631,28 @@ export const ExtensionStateContextProvider: React.FC<{
},
})
// Subscribe to models.dev models/pricing catalog updates
modelsDevModelsUnsubscribeRef.current = ModelsServiceClient.subscribeToModelsDevModels(EmptyRequest.create({}), {
onResponse: (response: { value?: string }) => {
applyModelsDevCatalogJson(response.value)
},
onError: (error) => {
console.error("Error in models.dev models subscription:", error)
},
onComplete: () => {
console.log("models.dev models subscription completed")
},
})
// Actively pull the catalog: the core fetches at startup (possibly before this
// webview subscribed), so the push event above may never fire. The RPC returns
// the core's cached catalog (or triggers the fetch) — covering both orderings.
ModelsServiceClient.refreshModelsDevModelsRpc(EmptyRequest.create({}))
.then((response: { value?: string }) => {
applyModelsDevCatalogJson(response.value)
})
.catch((error: Error) => console.error("Failed to fetch models.dev models:", error))
// Subscribe to LiteLLM models updates
liteLlmModelsUnsubscribeRef.current = ModelsServiceClient.subscribeToLiteLlmModels(EmptyRequest.create({}), {
onResponse: (response: OpenRouterCompatibleModelInfo) => {
@@ -710,6 +760,10 @@ export const ExtensionStateContextProvider: React.FC<{
liteLlmModelsUnsubscribeRef.current()
liteLlmModelsUnsubscribeRef.current = null
}
if (modelsDevModelsUnsubscribeRef.current) {
modelsDevModelsUnsubscribeRef.current()
modelsDevModelsUnsubscribeRef.current = null
}
if (workspaceUpdatesUnsubscribeRef.current) {
workspaceUpdatesUnsubscribeRef.current()
workspaceUpdatesUnsubscribeRef.current = null
+5
View File
@@ -116,5 +116,10 @@
"role": "Role",
"dashboard": "Dashboard",
"logOut": "Log out"
},
"settingsSections": {
"modelsDevUpdateModels": "Update models via models.dev",
"modelsDevUpdatePricing": "Update pricing via models.dev",
"modelsDevUpdateDescription": "When enabled, the latest models and prices from providers are fetched from models.dev on every startup."
}
}
+17 -7
View File
@@ -21,7 +21,7 @@
"remoteConfigTooltip": "远程配置字段",
"remoteConfigHeader": "远程配置",
"about": "关于",
"aboutTooltip": "关于 Cline",
"aboutTooltip": "关于 Cline Multi",
"aboutHeader": "关于",
"debug": "调试",
"debugTooltip": "调试工具",
@@ -181,24 +181,35 @@
"markdown": "Markdown"
},
"settingsSections": {
"aboutDescription": "Cline 是一个运行在您编辑器中的 AI 编程助手。",
"aboutDescription": "Cline Multi 是一款基于 Cline 构建的 AI 编程助手,支持多模型配置与热切换,并对国产模型和中文场景做了深度适配。",
"aboutVersion": "版本 {{version}}",
"acknowledgement": "致谢",
"acknowledgementPrefix": "本项目基于开源项目",
"acknowledgementSuffix": " 构建,感谢 Cline 团队的杰出工作。",
"allowErrorUsageReporting": "允许收集错误和使用情况报告",
"modelsDevUpdateModels": "通过 models.dev 更新模型",
"modelsDevUpdatePricing": "通过 models.dev 更新定价",
"modelsDevUpdateDescription": "启用后,每次启动时将从 models.dev 拉取各厂商最新模型与价格数据。",
"backgroundExec": "后台执行",
"checkingConnection": "正在检查连接...",
"communitySupport": "社区支持",
"completeTroubleshootingGuide": "完整的故障排除指南",
"coreFeatures": "核心特性",
"featureMultiModelHotSwap": "多模型热切换:保存多个 API 配置预设,随时一键切换,各配置独立计价",
"featureCnModelAdaptation": "国产模型深度适配:针对 DeepSeek、Kimi、Qwen、GLM 等模型优化提示词",
"featureFriendlyErrors": "友好错误提示:模型不存在、内容拦截、超时等场景显示中文提示卡片",
"featureCostMonitoring": "实时成本监控:聊天界面底部实时显示 Token 用量与费用",
"featureCnSupport": "完整中文支持:界面全面中文化,中文 prompt 优化",
"featureSmartContext": "智能上下文压缩:大上下文模型自动启用 auto-condense,多模态切换自动处理历史图片",
"projectLinks": "项目地址",
"releases": "更新日志",
"connected": "已连接",
"customBrowserArgsDescription": "启动 Chrome 时附加的额外命令行参数。",
"defaultTerminalProfile": "默认终端配置文件",
"defaultTerminalProfileDescription": "选择用于执行命令的默认终端配置文件。",
"development": "开发",
"disableBrowserDescription": "禁用后,Cline 将无法使用浏览器工具。",
"disableBrowserToolUsage": "禁用浏览器工具使用",
"documentation": "文档",
"enableAggressiveTerminalReuse": "启用终端积极复用",
"enterPositiveNumber": "请输入正数",
"featureRequests": "功能请求",
"havingTerminalIssues": "遇到终端问题?",
"issues": "问题",
"launchBrowserDebug": "以调试模式启动 Chrome",
@@ -214,7 +225,6 @@
"remoteBrowserDescription": "允许 Cline 连接到远程 Chrome 实例",
"remoteBrowserHostHint": "或点击下方按钮。输入主机地址,留空则自动发现。",
"resetStateDescription": "这将重置此工作区(或全局)的扩展状态。在遇到 UI 故障时使用。",
"resources": "资源",
"shellIntegrationDescription": "Cline 等待 shell 集成初始化的时间。如果命令输出显示不完整,请尝试增大此值。",
"shellIntegrationPlaceholder": "输入秒数",
"shellIntegrationTimeout": "Shell 集成超时(秒)",