chore: reapply cline-chinese localization baseline on v3.86.1

This commit is contained in:
HybridTalentComputing committed 2026-06-01 19:39:51 +08:00
1 parent 1bd829e583
commit f17f13370c
182 files changed
+2396 -1730

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
# Cline-Chinese (Cline中文汉化版) 🌏
> 🎉 截止到2026.5.1,Cline Chinese在VS Code插件市场的下载量突破224k啦!感谢大家的支持!
<p align="center">
[![MCP市场](https://img.shields.io/badge/MCP%E5%B8%82%E5%9C%BA-访问-blue)](https://www.mcp-home.com/) [![Cline Chinese文档](https://img.shields.io/badge/Cline%20Chinese-文档-blue)](https://hybridtalentcomputing.gitbook.io/cline-chinese-doc/) [![Discord](https://img.shields.io/badge/Discord-加入讨论-7289DA)](https://discord.gg/fhj9hqy89t) [![Version](https://img.shields.io/visual-studio-marketplace/v/HybridTalentComputing.cline-chinese)](https://marketplace.visualstudio.com/items?itemName=HybridTalentComputing.cline-chinese) [![Downloads](https://img.shields.io/visual-studio-marketplace/d/HybridTalentComputing.cline-chinese)](https://marketplace.visualstudio.com/items?itemName=HybridTalentComputing.cline-chinese) [![Rating](https://img.shields.io/visual-studio-marketplace/r/HybridTalentComputing.cline-chinese)](https://marketplace.visualstudio.com/items?itemName=HybridTalentComputing.cline-chinese)
</p>
## 项目地址
https://github.com/HybridTalentComputing/cline-chinese
欢迎大家star,fork,提出issue,贡献代码,一起完善这个项目。
## 文档(感谢[@flyfreee](https://github.com/flyfreee)的翻译工作)
https://hybridtalentcomputing.gitbook.io/cline-chinese-doc/
## Supremum(更适合Vibe Coding的AI终端)
https://github.com/HybridTalentComputing/Supremum
如果您也在使用Claude Code/Codex 等CLI工具, 不妨看看我这个新项目。
## 赞助商
<img width="100%" alt="胜算云" src="https://github.com/user-attachments/assets/19091f07-c171-4cf6-b7af-4e11f549364a" />
## 功能展示
<video width="100%" controls src="https://github.com/user-attachments/assets/a6db47a9-08d7-4d20-afa0-110d23b71a81"></video>
## 安装使用
Cline-Chinese已发布到VSCode插件市场,欢迎感兴趣的小伙伴们下载体验。
## 简介
这个项目是基于 [Cline](https://github.com/cline/cline) 的汉化版本。旨在优化由于英文 prompt 导致 Cline 在中文输入下+国产大模型(如:deepseek)表现不佳的问题, 并提供更符合中文用户习惯的UI界面和功能。目前已测试[DeepSeek-R1/DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-R1)工作良好。
日常使用cline等编程助手时发现使用某些模型推理速度较慢(如deepseek-R1, Claude-3.5-Sonnet),这个项目优先尝试在中文输入下,对轻量化LLM进行实验(如Deepseek-R1-Distill-Qwen-7B/14B),优化中文prompt, 以提升推理速度,大大减少等待的时间。
## 背景
本人是一名AI从业者+爱好者,在使用Cline时,发现Cline的UI界面和提示词均为英文,使用中文输入时,有时会出现奇奇怪怪的输出,影响体验。因此,决定自己动手,汉化Cline。
另外,秉着学习的态度,未来将着手修改Cline的核心代码,增加新的功能,以提升体验。
## 特色功能
1. 支持Dify Provider (已受cline官方支持,欢迎体验)
## 版本更新说明
## 2026.02.08 (ver.3.46.9)
修复defaultChatParticipant报错问题
## 2026.01.31 (ver.3.46.7)
1.修复https代理失效的问题
2.修复胜算云登录及模型无法使用问题
3.修复“claude code xxx” 报错问题
### 2026.01.28(ver.3.46.6)
修复openai compatible生成效果异常的问题
### 2026.01.23(ver.3.46.5)
1. 同步近期cline更新。
### 2025.08.25(ver.3.25.2)
1. 同步近期cline更新。(上下文压缩,添加claude code provider)
### 2025.06.17(ver.3.17.11)
1. 同步近期cline更新。
2. 接入胜算云.
### 2025.05.19(ver.3.16.1)
1. 同步近期cline更新。
### 2025.04.01(ver.3.8.4)
1. Cline Chinese特色功能:新增Dify Provider,感谢@lofyer,代码来自:https://github.com/lofyer/cline-dify/tree/main
2. 合入cline 3.8新增特性和问题修复:
关键特性:
1. 添加到 Cline:在任何文件或终端中右键单击选定的文本,以快速将上下文添加到您当前的任务中!此外,当您看到灯泡图标时,选择“使用Cline 修复”让 Cline 修复您代码中的错误。
2. 更快的推理:Cline/OpenRouter用户可以按吞吐量、价格和延迟对使用的底层提供商进行排序。按吞吐量排序将输出更快的生成结果(成本更高)。
3. 增强的 MCP 支持:支持 GIF 的动态图像加载,以及一个新的删除按钮来清理失败的服务器。
4. 近期新增模型支持,如gemini 2.5 pro, Deepseek-V3-0324,claude 3.7 sonnet-thinking.
## 欢迎关注我的自媒体账号
欢迎关注我的自媒体账号,获取更多AI开发和技术分享:
- 微信公众号:Leo的AI世界
## 加入社群
感兴趣的可以扫码加入微信社群,一起交流学习AI(如果二维码失效,请查看github项目中的首页中,相同位置的群二维码, 或者加入Discord频道):
<div align="center">
<img src="https://github.com/user-attachments/assets/d80d30e2-71b7-44e4-83e3-1166da0044bf" alt="微信群二维码" width="250" />
</div>
GitHub 项目地址:https://github.com/HybridTalentComputing/cline-chinese
Discord 频道:https://discord.gg/fhj9hqy89t
## 免责声明
1. **使用风险**:本项目是一个开源的VSCode插件,用户在使用过程中可能会遇到的任何问题或风险,开发者不承担任何责任。
2. **数据安全**:本插件不会收集或存储任何用户数据。但在使用过程中,用户应注意保护自己的敏感信息和代码安全。
3. **知识产权**:
- 本项目是基于Cline的汉化版本,原版权归属于Cline团队。
- 汉化部分的内容采用与原版Cline相同的Apache-2.0许可证。
- 用户在使用过程中应遵守相关的开源协议。
4. **免责声明**:
- 本项目不提供任何明示或暗示的保证,包括但不限于适销性和特定用途适用性的保证。
- 开发者不对任何直接或间接损失负责,包括但不限于利润损失、数据丢失等。
- 用户使用本插件即表示同意承担使用过程中的所有风险。
5. **更新和维护**:
- 开发者将努力维护本项目,但不保证及时更新或修复所有问题。
- 本项目可能随时变更或终止,会及时同步到本项目中。
6. **合规使用**:
- 用户在使用本插件时,必须遵守当地法律法规。
- **严禁将本插件用于任何违法违规行为**(包括但不限于网络攻击、非法侵入、数据窃取、传播非法信息等)。
- 开发者对用户利用本插件进行的任何违法行为及其产生的后果不承担任何法律责任。
---
> 注:本项目是个人维护的汉化版本,与原版 Cline 团队无关。如果您喜欢这个项目,也请给原版 [Cline](https://github.com/cline/cline) 一个 star ⭐️
+40 -40
View File
@@ -1,7 +1,7 @@
{
"name": "claude-dev",
"displayName": "Cline",
"description": "Autonomous coding agent right in your IDE, capable of creating/editing files, running commands, using the browser, and more with your permission every step of the way.",
"name": "cline-chinese",
"displayName": "Cline Chinese",
"description": "%cline.description%",
"version": "3.86.1",
"icon": "assets/icons/icon.png",
"workspaces": [
@@ -11,15 +11,15 @@
"vscode": "^1.84.0"
},
"author": {
"name": "Cline Bot Inc."
"name": "HybridTalentComputing"
},
"license": "Apache-2.0",
"publisher": "saoudrizwan",
"publisher": "HybridTalentComputing",
"repository": {
"type": "git",
"url": "https://github.com/cline/cline"
"url": "https://github.com/HybridTalentComputing/cline-chinese"
},
"homepage": "https://cline.bot",
"homepage": "https://github.com/HybridTalentComputing/cline-chinese",
"categories": [
"AI",
"Chat",
@@ -62,45 +62,45 @@
"walkthroughs": [
{
"id": "ClineWalkthrough",
"title": "Meet Cline, your new coding partner",
"description": "Cline codes like a developer because it thinks like one. Here are 5 ways to put it to work:",
"title": "%cline.walkthrough.title%",
"description": "%cline.walkthrough.description%",
"steps": [
{
"id": "welcome",
"title": "Start with a Goal, Not Just a Prompt",
"description": "Tell Cline what you want to achieve. It plans, asks, and then codes, like a true partner.",
"title": "%cline.walkthrough.step1.title%",
"description": "%cline.walkthrough.step1.description%",
"media": {
"markdown": "walkthrough/step1.md"
}
},
{
"id": "learn",
"title": "Let Cline Learn Your Codebase",
"description": "Point Cline to your project. It builds understanding to make smart, context-aware changes.",
"title": "%cline.walkthrough.step2.title%",
"description": "%cline.walkthrough.step2.description%",
"media": {
"markdown": "walkthrough/step2.md"
}
},
{
"id": "advanced-features",
"title": "Always Use the Best AI Models",
"description": "Cline empowers you with State-of-the-Art AI, connecting to top models (Anthropic, Gemini, OpenAI & more).",
"title": "%cline.walkthrough.step3.title%",
"description": "%cline.walkthrough.step3.description%",
"media": {
"markdown": "walkthrough/step3.md"
}
},
{
"id": "mcp",
"title": "Extend with Powerful Tools (MCP)",
"description": "Connect to databases, APIs, or discover new capabilities in the MCP Marketplace.",
"title": "%cline.walkthrough.step4.title%",
"description": "%cline.walkthrough.step4.description%",
"media": {
"markdown": "walkthrough/step4.md"
}
},
{
"id": "getting-started",
"title": "You're Always in Control",
"description": "Review Cline's plans and diffs. Approve changes before they happen. No surprises.",
"title": "%cline.walkthrough.step5.title%",
"description": "%cline.walkthrough.step5.description%",
"media": {
"markdown": "walkthrough/step5.md"
},
@@ -133,115 +133,115 @@
"commands": [
{
"command": "cline.plusButtonClicked",
"title": "New Task",
"title": "%cline.command.newTask%",
"icon": "$(add)"
},
{
"command": "cline.mcpButtonClicked",
"title": "MCP Servers",
"title": "%cline.command.mcpServers%",
"icon": "$(server)"
},
{
"command": "cline.historyButtonClicked",
"title": "History",
"title": "%cline.command.history%",
"icon": "$(history)"
},
{
"command": "cline.accountButtonClicked",
"title": "Account",
"title": "%cline.command.account%",
"icon": "$(account)"
},
{
"command": "cline.settingsButtonClicked",
"title": "Settings",
"title": "%cline.command.settings%",
"icon": "$(settings-gear)"
},
{
"command": "cline.dev.createTestTasks",
"title": "Create Test Tasks",
"title": "%cline.command.createTestTasks%",
"category": "Cline",
"when": "cline.isDevMode"
},
{
"command": "cline.dev.expireMcpOAuthTokens",
"title": "Expire MCP OAuth Tokens (for testing)",
"title": "%cline.command.expireMcpOAuthTokens%",
"category": "Cline",
"when": "cline.isDevMode"
},
{
"command": "cline.addToChat",
"title": "Add to Cline",
"title": "%cline.command.addToChat%",
"category": "Cline"
},
{
"command": "cline.addTerminalOutputToChat",
"title": "Add to Cline",
"title": "%cline.command.addTerminalToChat%",
"category": "Cline"
},
{
"command": "cline.focusChatInput",
"title": "Jump to Chat Input",
"title": "%cline.command.focusChatInput%",
"category": "Cline"
},
{
"command": "cline.generateGitCommitMessage",
"title": "Generate Commit Message with Cline",
"title": "%cline.command.generateCommitMessage%",
"category": "Cline",
"icon": "$(cline-icon)"
},
{
"command": "cline.abortGitCommitMessage",
"title": "Generate Commit Message with Cline - Stop",
"title": "%cline.command.abortCommitMessage%",
"category": "Cline",
"icon": "$(debug-stop)"
},
{
"command": "cline.explainCode",
"title": "Explain with Cline",
"title": "%cline.command.explainCode%",
"category": "Cline"
},
{
"command": "cline.improveCode",
"title": "Improve with Cline",
"title": "%cline.command.improveCode%",
"category": "Cline"
},
{
"command": "cline.jupyterGenerateCell",
"title": "Generate Jupyter Cell with Cline",
"title": "%cline.command.jupyterGenerate%",
"category": "Cline",
"icon": "$(sparkle)"
},
{
"command": "cline.jupyterExplainCell",
"title": "Explain Jupyter Cell with Cline",
"title": "%cline.command.jupyterExplain%",
"category": "Cline",
"icon": "$(question)"
},
{
"command": "cline.jupyterImproveCell",
"title": "Improve Jupyter Cell with Cline",
"title": "%cline.command.jupyterImprove%",
"category": "Cline",
"icon": "$(lightbulb)"
},
{
"command": "cline.openWalkthrough",
"title": "Open Walkthrough",
"title": "%cline.command.openWalkthrough%",
"category": "Cline"
},
{
"command": "cline.reconstructTaskHistory",
"title": "Reconstruct Task History",
"title": "%cline.command.reconstructHistory%",
"category": "Cline"
},
{
"command": "cline.reviewComment.reply",
"title": "Reply",
"title": "%cline.command.reply%",
"category": "Cline",
"enablement": "!commentIsEmpty"
},
{
"command": "cline.reviewComment.addToChat",
"title": "Add to Cline Chat",
"title": "%cline.command.addToChat%",
"category": "Cline",
"icon": "$(link-external)"
}
+25 -3
View File
@@ -59,7 +59,7 @@ import { combineApiRequests } from "@shared/combineApiRequests"
import { combineCommandSequences } from "@shared/combineCommandSequences"
import { ClineApiReqCancelReason, ClineApiReqInfo, ClineAsk, ClineMessage, ClineSay } from "@shared/ExtensionMessage"
import { HistoryItem } from "@shared/HistoryItem"
import { DEFAULT_LANGUAGE_SETTINGS, getLanguageKey, LanguageDisplay } from "@shared/Languages"
import { getLanguageKey, LanguageDisplay } from "@shared/Languages"
import { USER_CONTENT_TAGS } from "@shared/messages/constants"
import { convertClineMessageToProto } from "@shared/proto-conversions/cline-message"
import { ClineDefaultTool, READ_ONLY_TOOLS } from "@shared/tools"
@@ -1882,9 +1882,31 @@ export class Task {
const supportsBrowserUse = modelSupportsBrowserUse && !disableBrowserTool // only enable browser use if the model supports it and the user hasn't disabled it
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)",
de: "German (Deutsch)",
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)",
hu: "Hungarian (Magyar)",
pl: "Polish (Polski)",
tr: "Turkish (Türkçe)",
en: "English",
}
const preferredLanguageInstructions =
preferredLanguage && preferredLanguage !== DEFAULT_LANGUAGE_SETTINGS
? `# Preferred Language\n\nSpeak in ${preferredLanguage}.`
preferredLanguage && preferredLanguage !== "en"
? `# Preferred Language
Speak in ${languageInstructionMap[preferredLanguage] || preferredLanguage}.`
: ""
const { globalToggles, localToggles } = await refreshClineRulesToggles(this.controller, this.cwd)
+1 -1
View File
@@ -38,7 +38,7 @@ export type LanguageDisplay =
| "Traditional Chinese - 繁體中文"
| "Turkish - Türkçe"
export const DEFAULT_LANGUAGE_SETTINGS: LanguageKey = "en"
export const DEFAULT_LANGUAGE_SETTINGS: LanguageKey = "zh-CN"
export const languageOptions: { key: LanguageKey; display: LanguageDisplay }[] = [
{ key: "en", display: "English" },
+78 -1
View File
@@ -33,12 +33,14 @@
"framer-motion": "^12.7.4",
"fuse.js": "^7.0.0",
"fzf": "^0.5.2",
"i18next": "^24.2.2",
"lucide-react": "^0.511.0",
"mermaid": "11.12.3",
"posthog-js": "^1.224.0",
"pretty-bytes": "^6.1.1",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^15.4.1",
"react-markdown": "^10.1.0",
"react-remark": "^2.1.0",
"react-textarea-autosize": "^8.5.7",
@@ -9008,6 +9010,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/html-parse-stringify": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
"integrity": "sha512-KknJ50kTInJ7qIScF3jeaFRpMpE8/lfiTdzf/twXyPBLAGrLRTmkz3AdTnKeh40X8k9L2fdYwEp/42WGXIRGcg==",
"license": "MIT",
"dependencies": {
"void-elements": "3.1.0"
}
},
"node_modules/html-url-attributes": {
"version": "3.0.1",
"license": "MIT",
@@ -9056,6 +9067,37 @@
"version": "1.1.0",
"license": "BSD-3-Clause"
},
"node_modules/i18next": {
"version": "24.2.3",
"resolved": "https://registry.npmjs.org/i18next/-/i18next-24.2.3.tgz",
"integrity": "sha512-lfbf80OzkocvX7nmZtu7nSTNbrTYR52sLWxPtlXX1zAhVw8WEnFk4puUkCR4B1dNQwbSpEHHHemcZu//7EcB7A==",
"funding": [
{
"type": "individual",
"url": "https://locize.com"
},
{
"type": "individual",
"url": "https://locize.com/i18next.html"
},
{
"type": "individual",
"url": "https://www.i18next.com/how-to/faq#i18next-is-awesome.-how-can-i-support-the-project"
}
],
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.26.10"
},
"peerDependencies": {
"typescript": "^5"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/iconv-lite": {
"version": "0.6.3",
"license": "MIT",
@@ -12019,6 +12061,32 @@
"react": "^18.3.1"
}
},
"node_modules/react-i18next": {
"version": "15.7.4",
"resolved": "https://registry.npmjs.org/react-i18next/-/react-i18next-15.7.4.tgz",
"integrity": "sha512-nyU8iKNrI5uDJch0z9+Y5XEr34b0wkyYj3Rp+tfbahxtlswxSCjcUL9H0nqXo9IR3/t5Y5PKIA3fx3MfUyR9Xw==",
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.27.6",
"html-parse-stringify": "^3.0.1"
},
"peerDependencies": {
"i18next": ">= 23.4.0",
"react": ">= 16.8.0",
"typescript": "^5"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
},
"typescript": {
"optional": true
}
}
},
"node_modules/react-is": {
"version": "17.0.2",
"dev": true,
@@ -13486,7 +13554,7 @@
},
"node_modules/typescript": {
"version": "5.9.2",
"dev": true,
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -14033,6 +14101,15 @@
"dev": true,
"license": "MIT"
},
"node_modules/void-elements": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/void-elements/-/void-elements-3.1.0.tgz",
"integrity": "sha512-Dhxzh5HZuiHQhbvTW9AMetFfBHDMYpo23Uo9btPXgdYP+3T5S+p+jgNy7spra+veYhBP2dCSgxR/i2Y02h5/6w==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/vscode-jsonrpc": {
"version": "8.2.0",
"resolved": "https://registry.npmjs.org/vscode-jsonrpc/-/vscode-jsonrpc-8.2.0.tgz",
+2
View File
@@ -45,8 +45,10 @@
"mermaid": "11.12.3",
"posthog-js": "^1.224.0",
"pretty-bytes": "^6.1.1",
"i18next": "^24.2.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-i18next": "^15.4.1",
"react-markdown": "^10.1.0",
"react-remark": "^2.1.0",
"react-textarea-autosize": "^8.5.7",
@@ -5,6 +5,7 @@ import { EmptyRequest } from "@shared/proto/cline/common"
import { VSCodeButton, VSCodeDivider, VSCodeDropdown, VSCodeOption, VSCodeTag } from "@vscode/webview-ui-toolkit/react"
import deepEqual from "fast-deep-equal"
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useInterval } from "react-use"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { type ClineUser, handleSignOut } from "@/context/ClineAuthContext"
@@ -43,11 +44,12 @@ type CachedData = {
const ClineEnvOptions = ["Production", "Staging", "Local"] as const
const AccountView = ({ onDone, clineUser, organizations, activeOrganization }: AccountViewProps) => {
const { t } = useTranslation("settings")
const { environment } = useExtensionState()
return (
<div className="fixed inset-0 flex flex-col overflow-hidden">
<ViewHeader environment={environment} onDone={onDone} showEnvironmentSuffix title="Account" />
<ViewHeader environment={environment} onDone={onDone} showEnvironmentSuffix title={t("account.title")} />
<div className="grow flex flex-col px-5 overflow-y-auto">
{clineUser?.uid ? (
<ClineAccountView
@@ -66,6 +68,7 @@ const AccountView = ({ onDone, clineUser, organizations, activeOrganization }: A
}
export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganization, clineEnv }: ClineAccountViewProps) => {
const { t } = useTranslation("settings")
const { email, displayName, appBaseUrl, uid } = clineUser
const { remoteConfigSettings, environment } = useExtensionState()
@@ -338,11 +341,11 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
</VSCodeDropdown>
</TooltipTrigger>
<TooltipContent hidden={!isLockedByRemoteConfig}>
This cannot be changed while your organization has remote configuration enabled.
t("account.cannotChangeWithRemoteConfig")
</TooltipContent>
</Tooltip>
{activeOrganization && (
<VSCodeTag className="text-xs p-2" title="Role">
<VSCodeTag className="text-xs p-2" title={t("account.role")}>
{getMainRole(activeOrganization.roles)}
</VSCodeTag>
)}
@@ -390,7 +393,7 @@ export const ClineAccountView = ({ clineUser, userOrganizations, activeOrganizat
{isClineTester && environment !== "selfHosted" && (
<div className="w-full gap-1 items-end">
<VSCodeDivider className="w-full my-3" />
<div className="text-sm font-semibold">Cline Environment</div>
<div className="text-sm font-semibold">{t("account.clineEnvironment")}</div>
<VSCodeDropdown
className="w-full mt-1"
currentValue={clineEnv}
@@ -1,4 +1,5 @@
import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import { useClineSignIn } from "@/context/ClineAuthContext"
import { useExtensionState } from "@/context/ExtensionStateContext"
import ClineLogoVariable from "../../assets/ClineLogoVariable"
@@ -7,6 +8,7 @@ import ClineLogoVariable from "../../assets/ClineLogoVariable"
// <div className="flex flex-col items-center pr-3 gap-2.5">
// <ClineLogoWhite className="size-16 mb-4" />
export const AccountWelcomeView = () => {
const { t } = useTranslation("settings")
const { environment } = useExtensionState()
const { isLoginLoading, handleSignIn } = useClineSignIn()
@@ -14,23 +16,21 @@ export const AccountWelcomeView = () => {
<div className="flex flex-col items-center gap-2.5">
<ClineLogoVariable className="size-16 mb-4" environment={environment} />
<p>
Sign up for an account to get access to the latest models, billing dashboard to view usage and credits, and more
upcoming features.
</p>
<p>{t("account.signUpDescription")}</p>
<VSCodeButton className="w-full mb-4" disabled={isLoginLoading} onClick={handleSignIn}>
Sign up with Cline
{isLoginLoading && (
<span className="ml-1 animate-spin">
<span className="codicon codicon-refresh"></span>
<span className="codicon codicon-refresh" />
</span>
)}
</VSCodeButton>
<p className="text-(--vscode-descriptionForeground) text-xs text-center m-0">
By continuing, you agree to the <VSCodeLink href="https://cline.bot/tos">Terms of Service</VSCodeLink> and{" "}
<VSCodeLink href="https://cline.bot/privacy">Privacy Policy.</VSCodeLink>
{t("account.agreeToTerms")} <VSCodeLink href="https://cline.bot/tos">{t("account.termsOfService")}</VSCodeLink>{" "}
{t("settingsSections.privacyPolicy").replace("privacy policy", "")}{" "}
<VSCodeLink href="https://cline.bot/privacy">{t("account.privacyPolicyAnd")}</VSCodeLink>
</p>
</div>
)
@@ -1,4 +1,5 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import VSCodeButtonLink from "../common/VSCodeButtonLink"
import { StyledCreditDisplay } from "./StyledCreditDisplay"
@@ -11,11 +12,14 @@ type CreditBalanceProps = {
}
export const CreditBalance = ({ balance, fetchCreditBalance, creditUrl, lastFetchTime, isLoading }: CreditBalanceProps) => {
const { t } = useTranslation("settings")
return (
<div
className="w-full flex flex-col items-center"
title={`Last updated: ${new Date(lastFetchTime).toLocaleTimeString()}`}>
<div className="text-sm text-(--vscode-descriptionForeground) mb-3 font-azeret-mono font-light">CURRENT BALANCE</div>
<div className="text-sm text-(--vscode-descriptionForeground) mb-3 font-azeret-mono font-light">
{t("account.currentBalance")}
</div>
<div className="font-bold text-2xl mb-6 flex items-center gap-2">
{balance === null ? <span>----</span> : <StyledCreditDisplay balance={balance} />}
@@ -24,7 +28,7 @@ export const CreditBalance = ({ balance, fetchCreditBalance, creditUrl, lastFetc
className={`mt-1 ${isLoading ? "animate-spin" : ""}`}
disabled={isLoading}
onClick={fetchCreditBalance}>
<span className="codicon codicon-refresh"></span>
<span className="codicon codicon-refresh" />
</VSCodeButton>
</div>
@@ -1,11 +1,13 @@
import { UpdateSettingsRequest, UserOrganization } from "@shared/proto/index.cline"
import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react"
import { useRef } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { StateServiceClient } from "@/services/grpc-client"
import { isAdminOrOwner } from "./helpers"
export function RemoteConfigToggle({ activeOrganization }: { activeOrganization: UserOrganization | null }) {
const { t } = useTranslation("settings")
const { optOutOfRemoteConfig } = useExtensionState()
const hadOptedOutOfRemoteConfig = useRef(optOutOfRemoteConfig)
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from "react"
import { formatCreditsBalance } from "@/utils/format"
// Custom hook for animated credit display with styled decimals
const useAnimatedCredits = (targetValue: number, duration: number = 660) => {
const useAnimatedCredits = (targetValue: number, duration = 660) => {
const [currentValue, setCurrentValue] = useState(0)
const animationRef = useRef<number>()
const startTimeRef = useRef<number>()
@@ -1,6 +1,7 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { BrowserServiceClient } from "../../services/grpc-client"
@@ -11,6 +12,7 @@ interface ConnectionInfo {
}
export const BrowserSettingsMenu = () => {
const { t } = useTranslation("misc")
const { browserSettings, navigateToSettings } = useExtensionState()
const containerRef = useRef<HTMLDivElement>(null)
const [showInfoPopover, setShowInfoPopover] = useState(false)
@@ -92,20 +94,19 @@ export const BrowserSettingsMenu = () => {
const getIconClass = () => {
if (connectionInfo.isRemote) {
return "codicon-remote"
} else {
return connectionInfo.isConnected ? "codicon-vm-running" : "codicon-info"
}
return connectionInfo.isConnected ? "codicon-vm-running" : "codicon-info"
}
// Determine icon color based on connection state
const getIconColor = () => {
if (connectionInfo.isRemote) {
return connectionInfo.isConnected ? "var(--vscode-charts-blue)" : "var(--vscode-foreground)"
} else if (connectionInfo.isConnected) {
return "var(--vscode-charts-green)"
} else {
return "var(--vscode-foreground)"
}
if (connectionInfo.isConnected) {
return "var(--vscode-charts-green)"
}
return "var(--vscode-foreground)"
}
// Check connection status every second to keep icon in sync using gRPC
@@ -140,7 +141,7 @@ export const BrowserSettingsMenu = () => {
className="browser-info-icon"
onClick={toggleInfoPopover}
style={{ marginRight: "4px" }}
title="Browser connection info">
title={t("browser.connectionInfo")}>
<i
className={`codicon ${getIconClass()}`}
style={{
@@ -160,11 +161,11 @@ export const BrowserSettingsMenu = () => {
border: "1px solid var(--vscode-widget-border)",
boxShadow: "0 2px 8px rgba(0, 0, 0, 0.15)",
}}>
<h4 style={{ margin: "0 0 8px 0" }}>Browser Connection</h4>
<h4 style={{ margin: "0 0 8px 0" }}>{t("browser.browserConnection")}</h4>
{/* InfoRow - Status row container */}
<div className="flex flex-wrap whitespace-nowrap mb-1">
{/* InfoLabel - Fixed-width label */}
<div className="flex-none w-[90px] font-medium">Status:</div>
<div className="flex-none w-[90px] font-medium">{t("browser.status")}</div>
{/* InfoValue - Flexible value container */}
<div
className="flex-1 break-words"
@@ -173,23 +174,25 @@ export const BrowserSettingsMenu = () => {
? "var(--vscode-charts-green)"
: "var(--vscode-errorForeground)",
}}>
{connectionInfo.isConnected ? "Connected" : "Disconnected"}
{connectionInfo.isConnected ? t("browser.connected") : t("browser.disconnected")}
</div>
</div>
{connectionInfo.isConnected && (
// InfoRow - Type row container
<div className="flex flex-wrap whitespace-nowrap mb-1">
{/* InfoLabel - Fixed-width label */}
<div className="flex-none w-[90px] font-medium">Type:</div>
<div className="flex-none w-[90px] font-medium">{t("browser.type")}</div>
{/* InfoValue - Flexible value container */}
<div className="flex-1 break-words">{connectionInfo.isRemote ? "Remote" : "Local"}</div>
<div className="flex-1 break-words">
{connectionInfo.isRemote ? t("browser.remote") : t("browser.local")}
</div>
</div>
)}
{connectionInfo.isConnected && connectionInfo.isRemote && connectionInfo.host && (
// InfoRow - Remote host row container
<div className="flex flex-wrap whitespace-nowrap mb-1">
{/* InfoLabel - Fixed-width label */}
<div className="flex-none w-[90px] font-medium">Remote Host:</div>
<div className="flex-none w-[90px] font-medium">{t("browser.remoteHost")}</div>
{/* InfoValue - Flexible value container */}
<div className="flex-1 break-words">{connectionInfo.host}</div>
</div>
@@ -5,6 +5,7 @@ import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import deepEqual from "fast-deep-equal"
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import React, { CSSProperties, memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useSize } from "react-use"
import styled from "styled-components"
import { BrowserSettingsMenu } from "@/components/browser/BrowserSettingsMenu"
@@ -107,6 +108,8 @@ const headerStyle: CSSProperties = {
const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
const { messages, isLast, onHeightChange, lastModifiedMessage, onSetQuote } = props
const { browserSettings } = useExtensionState()
tconst
t = useTranslation("common")
const prevHeightRef = useRef(0)
const [maxActionHeight, setMaxActionHeight] = useState(0)
const [consoleLogsExpanded, setConsoleLogsExpanded] = useState(false)
@@ -305,7 +308,7 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
)
useEffect(() => {
if (actionHeight === 0 || actionHeight === Infinity) {
if (actionHeight === 0 || actionHeight === Number.POSITIVE_INFINITY) {
return
}
if (actionHeight > maxActionHeight) {
@@ -357,10 +360,10 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
{isBrowsing && !isLastMessageResume ? (
<ProgressIndicator />
) : (
<span className="codicon codicon-inspect" style={browserIconStyle}></span>
<span className="codicon codicon-inspect" style={browserIconStyle} />
)}
<span style={approveTextStyle}>
{isAutoApproved ? "Cline is using the browser:" : "Cline wants to use the browser:"}
{isAutoApproved ? t("browserSession.clineUsingBrowser") : t("browserSession.clineWantsBrowser")}
</span>
</div>
<div
@@ -399,7 +402,7 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
}}>
{displayState.screenshot ? (
<img
alt="Browser screenshot"
alt={t("browserSession.browserScreenshot")}
onClick={() =>
FileServiceClient.openImage(StringRequest.create({ value: displayState.screenshot })).catch(
(err) => console.error("Failed to open image:", err),
@@ -417,8 +420,8 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
<BrowserCursor
style={{
position: "absolute",
top: `${(parseInt(mousePosition.split(",")[1]) / browserSettings.viewport.height) * 100}%`,
left: `${(parseInt(mousePosition.split(",")[0]) / browserSettings.viewport.width) * 100}%`,
top: `${(Number.parseInt(mousePosition.split(",")[1]) / browserSettings.viewport.height) * 100}%`,
left: `${(Number.parseInt(mousePosition.split(",")[0]) / browserSettings.viewport.width) * 100}%`,
transition: "top 0.3s ease-out, left 0.3s ease-out",
}}
/>
@@ -440,10 +443,12 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
padding: `9px 8px ${consoleLogsExpanded ? 0 : 8}px 8px`,
}}>
{consoleLogsExpanded ? <ChevronDownIcon size={16} /> : <ChevronRightIcon size={16} />}
<span style={consoleLogsTextStyle}>Console Logs</span>
<span style={consoleLogsTextStyle}>{t("browserSession.consoleLogs")}</span>
</div>
{consoleLogsExpanded && (
<CodeBlock source={`${"```"}shell\n${displayState.consoleLogs || "(No new logs)"}\n${"```"}`} />
<CodeBlock
source={`${"```"}shell\n${displayState.consoleLogs || "{t('browserSession.noNewLogs')}"}\n${"```"}`}
/>
)}
</div>
</div>
@@ -454,19 +459,17 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
{/* Pagination moved to bottom */}
{pages.length > 1 && (
<div style={paginationContainerStyle}>
<div>
Step {currentPageIndex + 1} of {pages.length}
</div>
<div>{t("browserSession.step", { current: currentPageIndex + 1, total: pages.length })}</div>
<div style={paginationButtonGroupStyle}>
<VSCodeButton
disabled={currentPageIndex === 0 || isBrowsing}
onClick={() => setCurrentPageIndex((i) => i - 1)}>
Previous
{t("browserSession.previous")}
</VSCodeButton>
<VSCodeButton
disabled={currentPageIndex === pages.length - 1 || isBrowsing}
onClick={() => setCurrentPageIndex((i) => i + 1)}>
Next
{t("browserSession.next")}
</VSCodeButton>
</div>
</div>
@@ -479,7 +482,7 @@ const BrowserSessionRow = memo((props: BrowserSessionRowProps) => {
// Height change effect
useEffect(() => {
const isInitialRender = prevHeightRef.current === 0
if (isLast && height !== 0 && height !== Infinity && height !== prevHeightRef.current) {
if (isLast && height !== 0 && height !== Number.POSITIVE_INFINITY && height !== prevHeightRef.current) {
if (!isInitialRender) {
onHeightChange(height > prevHeightRef.current)
}
@@ -517,7 +520,7 @@ const BrowserSessionRowContent = memo(
return (
<>
<div style={headerStyle}>
<span style={browserSessionStartedTextStyle}>Browser Session Started</span>
<span style={browserSessionStartedTextStyle}>{t("browserSession.sessionStarted")}</span>
</div>
<div style={codeBlockContainerStyle}>
<CodeBlock forceWrap={true} source={`${"```"}shell\n${message.text}\n${"```"}`} />
@@ -571,20 +574,21 @@ const BrowserSessionRowContent = memo(
)
const BrowserActionBox = ({ action, coordinate, text }: { action: BrowserAction; coordinate?: string; text?: string }) => {
const { t } = useTranslation("common")
const getBrowserActionText = (action: BrowserAction, coordinate?: string, text?: string) => {
switch (action) {
case "launch":
return `Launch browser at ${text}`
return t("browserSession.launchBrowser", { url: text })
case "click":
return `Click (${coordinate?.replace(",", ", ")})`
return t("browserSession.click", { coordinate: coordinate?.replace(",", ", ") })
case "type":
return `Type "${text}"`
return t("browserSession.type", { text })
case "scroll_down":
return "Scroll down"
return t("browserSession.scrollDown")
case "scroll_up":
return "Scroll up"
return t("browserSession.scrollUp")
case "close":
return "Close browser"
return t("browserSession.closeBrowser")
default:
return action
}
@@ -594,7 +598,7 @@ const BrowserActionBox = ({ action, coordinate, text }: { action: BrowserAction;
<div style={browserActionBoxContainerInnerStyle}>
<div style={browseActionRowContainerStyle}>
<span style={browseActionRowStyle}>
<span style={browseActionTextStyle}>Browse Action: </span>
<span style={browseActionTextStyle}>{t("browserSession.browseAction")}</span>
{getBrowserActionText(action, coordinate, text)}
</span>
</div>
@@ -1,3 +1,4 @@
import i18next from "i18next"
import React from "react"
interface ChatErrorBoundaryProps {
@@ -47,8 +48,11 @@ export class ChatErrorBoundary extends React.Component<ChatErrorBoundaryProps, C
borderRadius: "4px",
backgroundColor: "var(--vscode-inputValidation-errorBackground, rgba(255, 0, 0, 0.1))",
}}>
<h3 style={{ margin: "0 0 8px 0" }}>{errorTitle || "Something went wrong displaying this content"}</h3>
<p style={{ margin: "0" }}>{errorBody || `Error: ${this.state.error?.message || "Unknown error"}`}</p>
<h3 style={{ margin: "0 0 8px 0" }}>{errorTitle || i18next.t("chatErrorBoundary.defaultTitle")}</h3>
<p style={{ margin: "0" }}>
{errorBody ||
`${i18next.t("chatErrorBoundary.errorPrefix")}${this.state.error?.message || i18next.t("chatErrorBoundary.unknownError")}`}
</p>
</div>
)
}
@@ -121,7 +125,10 @@ export class ErrorAfterDelay extends React.Component<ErrorAfterDelayProps, Error
borderRadius: "0 0 0 4px",
zIndex: 100,
}}>
Error in {this.state.tickCount}/{this.props.numSecondsToWait ?? 5} seconds
{i18next.t("chatErrorBoundary.errorIn", {
current: this.state.tickCount,
total: this.props.numSecondsToWait ?? 5,
})}
</div>
)
}
+70 -71
View File
@@ -37,6 +37,7 @@ import {
TriangleAlertIcon,
} from "lucide-react"
import { MouseEvent, memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useSize } from "react-use"
import { OptionsButtons } from "@/components/chat/OptionsButtons"
import { CheckmarkControl } from "@/components/common/CheckmarkControl"
@@ -148,6 +149,7 @@ export const ChatRowContent = memo(
reasoningContent,
responseStarted,
}: ChatRowContentProps) => {
const { t } = useTranslation("common")
const {
backgroundEditEnabled,
mcpServers,
@@ -315,17 +317,17 @@ export const ChatRowContent = memo(
case "error":
return [
<span className="codicon codicon-error text-error mb-[-1.5px]" />,
<span className="text-error font-bold">Error</span>,
<span className="text-error font-bold">{t("chatRow.error")}</span>,
]
case "mistake_limit_reached":
return [
<CircleXIcon className="text-error size-2" />,
<span className="text-error font-bold">Cline is having trouble...</span>,
<span className="text-error font-bold">{t("chatRow.mistakeLimit")}</span>,
]
case "command":
return [
<TerminalIcon className="text-foreground size-2" />,
<span className="font-bold text-foreground">Cline wants to execute this command:</span>,
<span className="font-bold text-foreground">{t("chatRow.wantsToExecute")}</span>,
]
case "use_mcp_server":
const mcpServerUse = JSON.parse(message.text || "{}") as ClineAskUseMcpServer
@@ -336,17 +338,20 @@ export const ChatRowContent = memo(
<span className="codicon codicon-server text-foreground mb-[-1.5px]" />
),
<span className="ph-no-capture font-bold text-foreground break-words">
Cline wants to {mcpServerUse.type === "use_mcp_tool" ? "use a tool" : "access a resource"} on the{" "}
{mcpServerUse.type === "use_mcp_tool"
? t("chatRow.wantsToUseTool")
: t("chatRow.wantsToAccessResource")}{" "}
{t("chatRow.onTheServer")}{" "}
<code className="break-all">
{getMcpServerDisplayName(mcpServerUse.serverName, mcpMarketplaceCatalog)}
</code>{" "}
MCP server:
{t("chatRow.mcpServer")}
</span>,
]
case "completion_result":
return [
<span className="codicon codicon-check text-success mb-[-1.5px]" />,
<span className="text-success font-bold">Task Completed</span>,
<span className="text-success font-bold">{t("chatRow.taskCompleted")}</span>,
]
case "api_req_started":
// API request rows no longer render the request payload/cost accordion.
@@ -355,7 +360,7 @@ export const ChatRowContent = memo(
case "followup":
return [
<span className="codicon codicon-question text-foreground mb-[-1.5px]" />,
<span className="font-bold text-foreground">Cline has a question:</span>,
<span className="font-bold text-foreground">{t("chatRow.hasQuestion")}</span>,
]
default:
return [null, null]
@@ -369,6 +374,7 @@ export const ChatRowContent = memo(
apiReqCancelReason,
isMcpServerResponding,
message.text,
t,
])
const tool = useMemo(() => {
@@ -404,7 +410,7 @@ export const ChatRowContent = memo(
const names = conditionalRulesInfo.rules.map((r: { name: string }) => r.name).join(", ")
return (
<div className={HEADER_CLASSNAMES}>
<span style={{ fontWeight: "bold" }}>Conditional rules applied:</span>
<span style={{ fontWeight: "bold" }}>{t("chatRow.conditionalRules")}</span>
<span className="ph-no-capture break-words whitespace-pre-wrap">{names}</span>
</div>
)
@@ -432,15 +438,13 @@ export const ChatRowContent = memo(
case "editedExistingFile":
const content = tool?.content || ""
const isApplyingPatch = content?.startsWith("%%bash") && !content.endsWith("*** End Patch\nEOF")
const editToolTitle = isApplyingPatch
? "Cline is creating patches to edit this file:"
: "Cline wants to edit this file:"
const editToolTitle = isApplyingPatch ? t("chatRow.creatingPatches") : t("chatRow.wantsToEdit")
return (
<div>
<div className={HEADER_CLASSNAMES}>
<PencilIcon className="size-2" />
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")}
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideWorkspace"))}
<span style={{ fontWeight: "bold" }}>{editToolTitle}</span>
</div>
{backgroundEditEnabled && tool.path && tool.content ? (
@@ -467,8 +471,8 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
<SquareMinusIcon className="size-2" />
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")}
<span style={{ fontWeight: "bold" }}>Cline wants to delete this file:</span>
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideWorkspace"))}
<span style={{ fontWeight: "bold" }}>{t("chatRow.wantsToDelete")}</span>
</div>
<CodeAccordian
// isLoading={message.partial}
@@ -485,8 +489,8 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
<FilePlus2Icon className="size-2" />
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")}
<span className="font-bold">Cline wants to create a new file:</span>
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideWorkspace"))}
<span className="font-bold">{t("chatRow.wantsToCreate")}</span>
</div>
{backgroundEditEnabled && tool.path && tool.content ? (
<DiffEditRow patch={tool.content} path={tool.path} startLineNumbers={tool.startLineNumbers} />
@@ -508,8 +512,8 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
{isImage ? <ImageUpIcon className="size-2" /> : <FileCode2Icon className="size-2" />}
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")}
<span className="font-bold">Cline wants to read this file:</span>
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideWorkspace"))}
<span className="font-bold">{t("chatRow.wantsToRead")}</span>
</div>
<div className="bg-code rounded-sm overflow-hidden border border-editor-group-border">
<div
@@ -546,11 +550,9 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
{toolIcon("folder-opened")}
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")}
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideOfWorkspace"))}
<span style={{ fontWeight: "bold" }}>
{message.type === "ask"
? "Cline wants to view the top level files in this directory:"
: "Cline viewed the top level files in this directory:"}
{message.type === "ask" ? t("chatRow.wantsToViewTopLevel") : t("chatRow.viewedTopLevel")}
</span>
</div>
<CodeAccordian
@@ -568,11 +570,9 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
{toolIcon("folder-opened")}
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")}
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideOfWorkspace"))}
<span style={{ fontWeight: "bold" }}>
{message.type === "ask"
? "Cline wants to recursively view all files in this directory:"
: "Cline recursively viewed all files in this directory:"}
{message.type === "ask" ? t("chatRow.wantsToViewRecursive") : t("chatRow.viewedRecursive")}
</span>
</div>
<CodeAccordian
@@ -590,11 +590,11 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
{toolIcon("file-code")}
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This file is outside of your workspace")}
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideWorkspace"))}
<span style={{ fontWeight: "bold" }}>
{message.type === "ask"
? "Cline wants to view source code definition names used in this directory:"
: "Cline viewed source code definition names used in this directory:"}
? t("chatRow.wantsToViewDefinitions")
: t("chatRow.viewedDefinitions")}
</span>
</div>
<CodeAccordian
@@ -611,9 +611,9 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
{toolIcon("search")}
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This is outside of your workspace")}
toolIcon("sign-out", "yellow", -90, t("chatRow.outsideOfWorkspace"))}
<span className="font-bold">
Cline wants to search this directory for <code className="break-all">{tool.regex}</code>:
{t("chatRow.wantsToSearch")} <code className="break-all">{tool.regex}</code>:
</span>
</div>
<SearchResultsDisplay
@@ -630,11 +630,11 @@ export const ChatRowContent = memo(
<div>
<div className={HEADER_CLASSNAMES}>
<FoldVerticalIcon className="size-2" />
<span className="font-bold">Cline is condensing the conversation:</span>
<span className="font-bold">{t("chatRow.condensing")}</span>
</div>
<div className="bg-code overflow-hidden border border-editor-group-border rounded-[3px]">
<div
aria-label={isExpanded ? "Collapse summary" : "Expand summary"}
aria-label={isExpanded ? t("chatRow.collapseSummary") : t("chatRow.expandSummary")}
className="text-description py-2 px-2.5 cursor-pointer select-none"
onClick={handleToggle}
onKeyDown={(e) => {
@@ -648,7 +648,7 @@ export const ChatRowContent = memo(
{isExpanded ? (
<div>
<div className="flex items-center mb-2">
<span className="font-bold mr-1">Summary:</span>
<span className="font-bold mr-1">{t("chatRow.summary")}</span>
<div className="grow" />
<ChevronDownIcon className="my-0.5 shrink-0 size-4" />
</div>
@@ -672,11 +672,9 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
<Link2Icon className="size-2" />
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This URL is external")}
toolIcon("sign-out", "yellow", -90, t("chatRow.urlExternal"))}
<span className="font-bold">
{message.type === "ask"
? "Cline wants to fetch content from this URL:"
: "Cline fetched content from this URL:"}
{message.type === "ask" ? t("chatRow.wantsToFetch") : t("chatRow.fetched")}
</span>
</div>
<div
@@ -701,11 +699,9 @@ export const ChatRowContent = memo(
<div className={HEADER_CLASSNAMES}>
<SearchIcon className="size-2 rotate-90" />
{tool.operationIsLocatedInWorkspace === false &&
toolIcon("sign-out", "yellow", -90, "This search is external")}
toolIcon("sign-out", "yellow", -90, t("chatRow.searchExternal"))}
<span className="font-bold">
{message.type === "ask"
? "Cline wants to search the web for:"
: "Cline searched the web for:"}
{message.type === "ask" ? t("chatRow.wantsToSearchWeb") : t("chatRow.searchedWeb")}
</span>
</div>
<div className="bg-code border border-editor-group-border overflow-hidden rounded-xs select-text py-[9px] px-2.5">
@@ -720,7 +716,7 @@ export const ChatRowContent = memo(
<div>
<div className={HEADER_CLASSNAMES}>
<LightbulbIcon className="size-2" />
<span className="font-bold">Cline loaded the skill:</span>
<span className="font-bold">{t("chatRow.loadedSkill")}</span>
</div>
<div className="bg-code border border-editor-group-border overflow-hidden rounded-xs py-[9px] px-2.5">
<span className="ph-no-capture font-medium">{tool.path}</span>
@@ -823,7 +819,7 @@ export const ChatRowContent = memo(
</div>
{useMcpServer.arguments && useMcpServer.arguments !== "{}" && (
<div className="mt-2">
<div className="mb-1 opacity-80 uppercase">Arguments</div>
<div className="mb-1 opacity-80 uppercase">{t("chatRow.arguments")}</div>
<CodeAccordian
code={useMcpServer.arguments}
isExpanded={true}
@@ -866,7 +862,7 @@ export const ChatRowContent = memo(
<div className="flex items-start gap-2 py-2.5 px-3 bg-quote rounded-sm text-base text-foreground opacity-90 mb-2">
<BellIcon className="mt-0.5 size-2 text-notification-foreground shrink-0" />
<div className="break-words flex-1">
<span className="font-medium">MCP Notification: </span>
<span className="font-medium">{t("chatRow.mcpNotification")}</span>
<span className="ph-no-capture">{message.text}</span>
</div>
</div>
@@ -908,7 +904,7 @@ export const ChatRowContent = memo(
reasoningContent={message.text}
showChevron={!isReasoningStreaming || hasReasoningText}
showTitle={true}
title={isReasoningStreaming ? "Thinking..." : "Thinking"}
title={isReasoningStreaming ? t("chatRow.thinkingDots") : t("chatRow.thinking")}
/>
{isReasoningStreaming && showFeatureTips !== false && <FeatureTip />}
</div>
@@ -948,7 +944,7 @@ export const ChatRowContent = memo(
return (
<div className="text-foreground flex items-center opacity-70 text-[12px] py-1 px-0">
<i className="codicon codicon-book mr-1.5" />
Loading MCP documentation
{t("chatRow.loadingMcpDocs")}
</div>
)
case "generate_explanation": {
@@ -989,12 +985,12 @@ export const ChatRowContent = memo(
)}
<span className="font-semibold">
{isGenerating
? "Generating explanation"
? t("chatRow.generatingExplanation")
: isError
? "Failed to generate explanation"
? t("chatRow.failedExplanation")
: wasCancelled
? "Explanation cancelled"
: "Generated explanation"}
? t("chatRow.explanationCancelled")
: t("chatRow.generatedExplanation")}
</span>
</div>
{isError && explanationInfo.error && (
@@ -1010,7 +1006,7 @@ export const ChatRowContent = memo(
</code>
<ArrowRightIcon className="inline size-2 mx-1" />
<code className="bg-quote rounded-sm py-0.5 px-1.5">
{explanationInfo.toRef || "working directory"}
{explanationInfo.toRef || t("chatRow.workingDirectory")}
</code>
</div>
)}
@@ -1042,17 +1038,20 @@ export const ChatRowContent = memo(
<div className="flex flex-col bg-warning/20 p-2 rounded-xs border border-error">
<div className="flex items-center mb-1">
<TriangleAlertIcon className="mr-2 size-2 stroke-3 text-error" />
<span className="font-medium text-foreground">Shell Integration Unavailable</span>
<span className="font-medium text-foreground">
{t("chatRow.shellIntegrationUnavailable")}
</span>
</div>
<div className="text-foreground opacity-80">
Cline may have trouble viewing the command's output. Please update VSCode (
<code>CMD/CTRL + Shift + P</code> → "Update") and make sure you're using a supported shell:
zsh, bash, fish, or PowerShell (<code>CMD/CTRL + Shift + P</code> → "Terminal: Select Default
Profile").
{t("chatRow.shellIntegrationMessage")}
<code>CMD/CTRL + Shift + P</code> → {t("chatRow.shellIntegrationUpdate")}) and make sure
you're using a supported shell: zsh, bash, fish, or PowerShell (
<code>CMD/CTRL + Shift + P</code> → {t("chatRow.shellIntegrationProfile")}
).
<a
className="px-1"
href="https://github.com/cline/cline/wiki/Troubleshooting-%E2%80%90-Shell-Integration-Unavailable">
Still having trouble?
{t("chatRow.shellIntegrationStillTrouble")}
</a>
</div>
</div>
@@ -1076,19 +1075,20 @@ export const ChatRowContent = memo(
<RefreshCwIcon className="mr-2 size-2 animate-spin" />
)}
<span className="font-medium text-foreground">
{isFailed ? "Auto-Retry Failed" : "Auto-Retry in Progress"}
{isFailed ? t("chatRow.autoRetryFailed") : t("chatRow.autoRetryInProgress")}
</span>
</div>
<div className="text-foreground opacity-80">
{isFailed ? (
<span>
Auto-retry failed after <strong>{maxAttempts}</strong> attempts. Manual
intervention required.
{t("chatRow.autoRetryFailedAfter")} <strong>{maxAttempts}</strong>{" "}
{t("chatRow.attempts")}
</span>
) : (
<span>
Attempt <strong>{attempt}</strong> of <strong>{maxAttempts}</strong> -
Retrying in {delaySeconds} seconds...
{t("chatRow.attemptOf")} <strong>{attempt}</strong> {t("chatRow.of")}{" "}
<strong>{maxAttempts}</strong> -{t("chatRow.retryingIn")} {delaySeconds}{" "}
{t("chatRow.seconds")}
</span>
)}
</div>
@@ -1116,11 +1116,10 @@ export const ChatRowContent = memo(
<div className="p-2 bg-link/10 border border-link/30 rounded-xs">
<div className="flex items-center mb-1">
<LightbulbIcon className="mr-1.5 size-2 text-link" />
<span className="font-medium text-foreground">Shell integration issues</span>
<span className="font-medium text-foreground">{t("chatRow.shellIntegrationIssues")}</span>
</div>
<div className="text-foreground opacity-90 mb-2">
Since you're experiencing repeated shell integration issues, we recommend switching to
Background Terminal mode for better reliability.
{t("chatRow.shellIntegrationRecommendation")}
</div>
<button
className={cn(
@@ -1140,8 +1139,8 @@ export const ChatRowContent = memo(
}}>
<SettingsIcon className="size-2" />
{isBackgroundModeEnabled
? "Background Terminal Enabled"
: "Enable Background Terminal (Recommended)"}
? t("chatRow.backgroundTerminalEnabled")
: t("chatRow.enableBackgroundTerminal")}
</button>
</div>
)
@@ -1244,7 +1243,7 @@ export const ChatRowContent = memo(
<div>
<div className={HEADER_CLASSNAMES}>
<FilePlus2Icon className="size-2" />
<span className="text-foreground font-bold">Cline wants to start a new task:</span>
<span className="text-foreground font-bold">{t("chatRow.wantsToStartNewTask")}</span>
</div>
<NewTaskPreview context={message.text || ""} />
</div>
@@ -1254,7 +1253,7 @@ export const ChatRowContent = memo(
<div>
<div className={HEADER_CLASSNAMES}>
<FilePlus2Icon className="size-2" />
<span className="text-foreground font-bold">Cline wants to condense your conversation:</span>
<span className="text-foreground font-bold">{t("chatRow.wantsToCondense")}</span>
</div>
<NewTaskPreview context={message.text || ""} />
</div>
@@ -1264,7 +1263,7 @@ export const ChatRowContent = memo(
<div>
<div className={HEADER_CLASSNAMES}>
<FilePlus2Icon className="size-2" />
<span className="text-foreground font-bold">Cline wants to create a Github issue:</span>
<span className="text-foreground font-bold">{t("chatRow.wantsToCreateIssue")}</span>
</div>
<ReportBugPreview data={message.text || ""} />
</div>
+19 -11
View File
@@ -8,6 +8,7 @@ import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { AtSignIcon, PlusIcon } from "lucide-react"
import type React from "react"
import { forwardRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import DynamicTextArea from "react-textarea-autosize"
import styled from "styled-components"
import ContextMenu from "@/components/chat/ContextMenu"
@@ -224,6 +225,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
navigateToSettingsModelPicker,
mcpServers,
} = useExtensionState()
const { t } = useTranslation("common")
const [isTextAreaFocused, setIsTextAreaFocused] = useState(false)
const [isDraggingOver, setIsDraggingOver] = useState(false)
const [gitCommits, setGitCommits] = useState<GitCommit[]>([])
@@ -1372,12 +1374,12 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
onDrop={onDrop}>
{showDimensionError && (
<div className="absolute inset-2.5 bg-[rgba(var(--vscode-errorForeground-rgb),0.1)] border-2 border-error rounded-xs flex items-center justify-center z-10 pointer-events-none">
<span className="text-error font-bold text-xs text-center">Image dimensions exceed 7500px</span>
<span className="text-error font-bold text-xs text-center">{t("chat.imageDimensionError")}</span>
</div>
)}
{showUnsupportedFileError && (
<div className="absolute inset-2.5 bg-[rgba(var(--vscode-errorForeground-rgb),0.1)] border-2 border-error rounded-xs flex items-center justify-center z-10 pointer-events-none">
<span className="text-error font-bold text-xs">Files other than images are currently disabled</span>
<span className="text-error font-bold text-xs">{t("chat.unsupportedFileError")}</span>
</div>
)}
{showSlashCommandsMenu && (
@@ -1512,7 +1514,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
/>
{!inputValue && selectedImages.length === 0 && selectedFiles.length === 0 && (
<div className="text-xs absolute bottom-5 left-6.5 right-16 text-(--vscode-input-placeholderForeground)/50 whitespace-nowrap overflow-hidden text-ellipsis pointer-events-none z-1">
Type @ for context, / for slash commands & workflows, hold shift to drag in files/images
{t("chat.contextHint")}
</div>
)}
{(selectedImages.length > 0 || selectedFiles.length > 0) && (
@@ -1555,11 +1557,11 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
{/* ButtonGroup - always in DOM but visibility controlled */}
<ButtonGroup className="absolute top-0 left-0 right-0 ease-in-out w-full h-5 z-10 flex items-center">
<Tooltip>
<TooltipContent>Add Context</TooltipContent>
<TooltipContent>{t("chat.addContext")}</TooltipContent>
<TooltipTrigger>
<VSCodeButton
appearance="icon"
aria-label="Add Context"
aria-label={t("chat.addContext")}
className="p-0 m-0 flex items-center"
data-testid="context-button"
onClick={handleContextButtonClick}>
@@ -1571,11 +1573,11 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
</Tooltip>
<Tooltip>
<TooltipContent>Add Files & Images</TooltipContent>
<TooltipContent>{t("chat.addFilesImages")}</TooltipContent>
<TooltipTrigger>
<VSCodeButton
appearance="icon"
aria-label="Add Files & Images"
aria-label={t("chat.addFilesImages")}
className="p-0 m-0 flex items-center"
data-testid="files-button"
disabled={shouldDisableFilesAndImages}
@@ -1602,7 +1604,7 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
onClick={handleModelButtonClick}
role="button"
tabIndex={0}
title="Open API Settings">
title={t("chat.openApiSettings")}>
<ModelButtonContent className="text-xs">{modelDisplayName}</ModelButtonContent>
</ModelDisplayButton>
</ModelButtonWrapper>
@@ -1615,15 +1617,21 @@ const ChatTextArea = forwardRef<HTMLTextAreaElement, ChatTextAreaProps>(
className="text-xs px-2 flex flex-col gap-1"
hidden={shownTooltipMode === null}
side="top">
{`In ${shownTooltipMode === "act" ? "Act" : "Plan"} mode, Cline will ${shownTooltipMode === "act" ? "complete the task immediately" : "gather information to architect a plan"}`}
{t("chat.planActTooltip", {
mode: shownTooltipMode === "act" ? t("chat.actMode") : t("chat.planMode"),
action:
shownTooltipMode === "act"
? t("chat.planActTooltipActAction")
: t("chat.planActTooltipPlanAction"),
})}
<p className="text-description/80 text-xs mb-0">
Toggle w/ <kbd className="text-muted-foreground mx-1">{togglePlanActKeys}</kbd>
{t("chat.planActTooltipToggle", { keys: togglePlanActKeys })}
</p>
</TooltipContent>
<TooltipTrigger>
<SwitchContainer data-testid="mode-switch" disabled={false} onClick={onModeToggle}>
<Slider isAct={mode === "act"} isPlan={mode === "plan"} />
{["Plan", "Act"].map((m) => (
{[t("chat.planMode"), t("chat.actMode")].map((m) => (
<div
aria-checked={mode === m.toLowerCase()}
className={cn(
+4 -2
View File
@@ -5,6 +5,7 @@ import { combineHookSequences } from "@shared/combineHookSequences"
import { getApiMetrics, getLastApiReqTotalTokens } from "@shared/getApiMetrics"
import { BooleanRequest, StringRequest } from "@shared/proto/cline/common"
import { useCallback, useEffect, useMemo } from "react"
import { useTranslation } from "react-i18next"
import { useMount } from "react-use"
import { normalizeApiConfiguration } from "@/components/settings/utils/providerUtils"
import { useExtensionState } from "@/context/ExtensionStateContext"
@@ -42,6 +43,7 @@ const MAX_IMAGES_AND_FILES_PER_MESSAGE = CHAT_CONSTANTS.MAX_IMAGES_AND_FILES_PER
const QUICK_WINS_HISTORY_THRESHOLD = 3
const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryView }: ChatViewProps) => {
const { t } = useTranslation("common")
const showNavbar = useShowNavbar()
const {
version,
@@ -325,9 +327,9 @@ const ChatView = ({ isHidden, showAnnouncement, hideAnnouncement, showHistoryVie
const scrollBehavior = useScrollBehavior(messages, visibleMessages, groupedMessages, expandedRows, setExpandedRows)
const placeholderText = useMemo(() => {
const text = task ? "Type a message..." : "Type your task here..."
const text = task ? t("chat.typeMessage") : t("chat.typeTask")
return text
}, [task])
}, [task, t])
return (
<ChatLayout isHidden={isHidden}>
@@ -2,6 +2,7 @@ import { COMMAND_OUTPUT_STRING, COMMAND_REQ_APP_STRING } from "@shared/combineCo
import { ClineMessage } from "@shared/ExtensionMessage"
import { StringRequest } from "@shared/proto/cline/common"
import { memo, useEffect, useRef } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
import { FileServiceClient } from "@/services/grpc-client"
@@ -46,7 +47,7 @@ export const CommandOutputContent = memo(
}
// Check if output contains a log file path indicator
const logFilePathMatch = output.match(/📋 Output is being logged to: ([^\n]+)/)
const logFilePathMatch = output.match(/📋 Output logged to ([^\n]+)/)
const logFilePath = logFilePathMatch ? logFilePathMatch[1].trim() : null
// Render output with clickable log file path
@@ -56,7 +57,7 @@ export const CommandOutputContent = memo(
}
// Split output into parts: before log path, log path line, after log path
const logPathLineStart = output.indexOf("📋 Output is being logged to:")
const logPathLineStart = output.indexOf("📋 Output logged to")
const logPathLineEnd = output.indexOf("\n", logPathLineStart)
const beforeLogPath = output.substring(0, logPathLineStart)
const afterLogPath = logPathLineEnd !== -1 ? output.substring(logPathLineEnd) : ""
@@ -75,7 +76,7 @@ export const CommandOutputContent = memo(
)
}}
title={`Click to open: ${logFilePath}`}>
<span className="shrink-0">📋 Output is being logged to:</span>
<span className="shrink-0">📋 {t("commandOutput.outputLoggedTo")}</span>
<span className="text-vscode-textLink-foreground underline break-all">{fileName}</span>
</div>
{afterLogPath && <CodeBlock forceWrap={true} source={`${"```"}shell\n${afterLogPath}\n${"```"}`} />}
@@ -130,6 +131,7 @@ export const CommandOutputRow = memo(
isOutputFullyExpanded: boolean
setIsOutputFullyExpanded: (expanded: boolean) => void
}) => {
const { t } = useTranslation("common")
const splitMessage = (text: string) => {
const outputIndex = text.indexOf(COMMAND_OUTPUT_STRING)
if (outputIndex === -1) {
@@ -214,7 +216,7 @@ export const CommandOutputRow = memo(
}}
size="sm"
variant="secondary">
{isBackgroundExec ? "cancel" : "stop"}
{isBackgroundExec ? t("commandOutput.cancel") : t("commandOutput.stop")}
</Button>
)}
</div>
@@ -237,7 +239,7 @@ export const CommandOutputRow = memo(
{requestsApproval && (
<div className="flex items-center gap-2.5 p-2 text-[12px] text-editor-warning-foreground">
<i className="codicon codicon-warning" />
<span>The model has determined this command requires explicit approval.</span>
<span>{t("commandOutput.requiresApproval")}</span>
</div>
)}
</>
@@ -247,14 +249,14 @@ export const CommandOutputRow = memo(
CommandOutputRow.displayName = "CommandOutputRow"
const CommandStatusMap = {
executing: "Running",
pending: "Pending",
completed: "Completed",
skipped: "Skipped",
}
function getCommandStatusText(isExecuting: boolean, isPending: boolean, isCompleted: boolean): string {
const { t } = useTranslation("common")
const CommandStatusMap = {
executing: t("commandOutput.running"),
pending: t("commandOutput.pending"),
completed: t("commandOutput.completed"),
skipped: t("commandOutput.skipped"),
}
if (isExecuting) {
return CommandStatusMap.executing
}
@@ -1,13 +1,14 @@
import { memo } from "react"
import { cn } from "@/lib/utils"
import { MarkdownRow } from "./MarkdownRow"
import { Int64Request } from "@shared/proto/cline/common"
import { CheckIcon } from "lucide-react"
import { memo } from "react"
import { useTranslation } from "react-i18next"
import { PLATFORM_CONFIG, PlatformType } from "@/config/platform.config"
import { cn } from "@/lib/utils"
import { TaskServiceClient } from "@/services/grpc-client"
import { CopyButton } from "../common/CopyButton"
import SuccessButton from "../common/SuccessButton"
import { QuoteButtonState } from "./ChatRow"
import { MarkdownRow } from "./MarkdownRow"
import QuoteButton from "./QuoteButton"
interface CompletionOutputRowProps {
@@ -36,6 +37,7 @@ export const CompletionOutputRow = memo(
messageTs,
handleQuoteClick,
}: CompletionOutputRowProps) => {
const { t } = useTranslation("common")
return (
<div>
<div className="rounded-sm border border-success/20 overflow-visible bg-success/10 p-2 pt-3">
@@ -43,7 +45,7 @@ export const CompletionOutputRow = memo(
<div className={cn(headClassNames, "justify-between px-1")}>
<div className="flex gap-2 items-center">
<CheckIcon className="size-3 text-success" />
<span className="text-success font-bold">Task Completed</span>
<span className="text-success font-bold">{t("completionOutput.taskCompleted")}</span>
</div>
<CopyButton className="text-success" textToCopy={text} />
</div>
@@ -88,6 +90,7 @@ const CompletionOutputActionRow = memo(
setExplainChangesDisabled: (value: boolean) => void
messageTs: number
}) => {
const { t } = useTranslation("common")
return (
<div style={{ paddingTop: 10, display: "flex", flexDirection: "column", gap: 8 }}>
<SuccessButton
@@ -126,7 +129,7 @@ const CompletionOutputActionRow = memo(
width: "100%",
}}>
<i className="codicon codicon-comment-discussion" style={{ marginRight: 6 }} />
{explainChangesDisabled ? "Explaining..." : "Explain Changes"}
{explainChangesDisabled ? t("completionOutput.explainingChanges") : t("completionOutput.explainChanges")}
</SuccessButton>
)}
</div>
+14 -10
View File
@@ -95,10 +95,10 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
// Shared label definitions for simple option types
const SIMPLE_OPTION_LABELS: Partial<Record<ContextMenuOptionType, string>> = {
[ContextMenuOptionType.Problems]: "Problems",
[ContextMenuOptionType.Terminal]: "Terminal",
[ContextMenuOptionType.URL]: "Paste URL to fetch contents",
[ContextMenuOptionType.NoResults]: "No results found",
[ContextMenuOptionType.Problems]: t("contextMenu.problems"),
[ContextMenuOptionType.Terminal]: t("contextMenu.terminal"),
[ContextMenuOptionType.URL]: t("contextMenu.pasteUrl"),
[ContextMenuOptionType.NoResults]: t("contextMenu.noResults"),
}
// Get accessible label for an option (used for screen readers and aria-label)
@@ -114,13 +114,13 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
if (option.value) {
return `${option.label}${option.description ? `, ${option.description}` : ""}`
}
return "Git Commits"
return t("contextMenu.gitCommits")
case ContextMenuOptionType.File:
case ContextMenuOptionType.Folder:
if (option.value) {
return option.label || option.value
}
return `Add ${option.type === ContextMenuOptionType.File ? "File" : "Folder"}`
return option.type === ContextMenuOptionType.File ? t("contextMenu.addFile") : t("contextMenu.addFolder")
default:
return option.label || option.value || ""
}
@@ -156,7 +156,7 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
</div>
)
}
return <span>Git Commits</span>
return <span>{t("contextMenu.gitCommits")}</span>
case ContextMenuOptionType.File:
case ContextMenuOptionType.Folder:
if (option.value) {
@@ -182,7 +182,11 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
</>
)
}
return <span>Add {option.type === ContextMenuOptionType.File ? "File" : "Folder"}</span>
return (
<span>
{option.type === ContextMenuOptionType.File ? t("contextMenu.addFile") : t("contextMenu.addFolder")}
</span>
)
default:
return null
}
@@ -251,7 +255,7 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
? `context-menu-item-${selectedIndex}`
: undefined
}
aria-label="Context mentions"
aria-label={t("contextMenu.ariaLabel")}
ref={menuRef}
role="listbox"
style={{
@@ -276,7 +280,7 @@ const ContextMenu: React.FC<ContextMenuProps> = ({
opacity: 0.7,
}}>
<i className="codicon codicon-loading codicon-modifier-spin" style={{ fontSize: "14px" }} />
<span>Searching...</span>
<span>{t("contextMenu.searching")}</span>
</div>
)}
{filteredOptions.map((option, index) => {
@@ -1,6 +1,7 @@
import { AskResponseRequest } from "@shared/proto/cline/task"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import React, { useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import VSCodeButtonLink from "@/components/common/VSCodeButtonLink"
import { useClineAuth } from "@/context/ClineAuthContext"
import { AccountServiceClient, TaskServiceClient } from "@/services/grpc-client"
@@ -19,12 +20,13 @@ const DEFAULT_BUY_CREDITS_URL = {
}
const CreditLimitError: React.FC<CreditLimitErrorProps> = ({
message = "You have run out of credits.",
message,
buyCreditsUrl,
currentBalance,
totalPromotions,
totalSpent,
}) => {
const { t } = useTranslation("common")
const { activeOrganization } = useClineAuth()
const [fullBuyCreditsUrl, setFullBuyCreditsUrl] = useState<string>("")
@@ -52,23 +54,32 @@ const CreditLimitError: React.FC<CreditLimitErrorProps> = ({
return (
<div className="p-2 border-none rounded-md mb-2 bg-(--vscode-textBlockQuote-background)">
<div className="mb-3 font-azeret-mono">
<div className="text-error mb-2">{message}</div>
<div className="text-error mb-2">{message || t("creditLimit.defaultMessage")}</div>
<div className="mb-3">
{currentBalance ? (
<div className="text-foreground">
Current Balance: <span className="font-bold">{currentBalance.toFixed(2)}</span>
{t("creditLimit.currentBalance")}
<span className="font-bold">{currentBalance.toFixed(2)}</span>
</div>
) : null}
{totalSpent ? (
<div className="text-foreground">
{t("creditLimit.totalSpent")}
{totalSpent.toFixed(2)}
</div>
) : null}
{totalSpent ? <div className="text-foreground">Total Spent: {totalSpent.toFixed(2)}</div> : null}
{totalPromotions ? (
<div className="text-foreground">Total Promotions: {totalPromotions.toFixed(2)}</div>
<div className="text-foreground">
{t("creditLimit.totalPromotions")}
{totalPromotions.toFixed(2)}
</div>
) : null}
</div>
</div>
<VSCodeButtonLink className="w-full mb-2" href={fullBuyCreditsUrl}>
<span className="codicon codicon-credit-card mr-[6px] text-[14px]" />
Buy Credits
{t("creditLimit.buyCredits")}
</VSCodeButtonLink>
<VSCodeButton
@@ -86,7 +97,7 @@ const CreditLimitError: React.FC<CreditLimitErrorProps> = ({
}
}}>
<span className="codicon codicon-refresh mr-1.5" />
Retry Request
{t("creditLimit.retryRequest")}
</VSCodeButton>
</div>
)
@@ -1,6 +1,7 @@
import { StringRequest } from "@shared/proto/cline/common"
import { FilePlus, FileText, FileX, SquareArrowOutUpRightIcon } from "lucide-react"
import { memo, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { cn } from "@/lib/utils"
import { FileServiceClient } from "@/services/grpc-client"
@@ -37,6 +38,8 @@ interface DiffEditRowProps {
}
export const DiffEditRow = memo<DiffEditRowProps>(({ patch, path, isLoading, startLineNumbers }) => {
tconst
t = useTranslation("common")
const { parsedFiles, isStreaming } = useMemo(() => {
const parsed = parsePatch(patch, path)
return {
@@ -148,7 +151,7 @@ const FileBlock = memo<{ file: Patch; isStreaming: boolean; startLineNumber?: nu
<span
className="font-medium truncate hover:underline hover:text-link"
onClick={handleOpenFile}
title="Open file in editor">
title={t("diffEdit.openFileInEditor")}>
{file.path}
</span>
</div>
@@ -158,7 +161,7 @@ const FileBlock = memo<{ file: Patch; isStreaming: boolean; startLineNumber?: nu
<span
className="p-1 hover:bg-description/20 rounded-xs transition-colors"
onClick={handleOpenFile}
title="Open file in editor">
title={t("diffEdit.openFileInEditor")}>
<SquareArrowOutUpRightIcon className="size-2 text-description hover:text-foreground" />
</span>
</div>
@@ -15,11 +15,11 @@ interface ErrorBlockTitleProps {
}
export const ErrorBlockTitle = ({
cost,
apiReqCancelReason,
apiRequestFailedMessage,
retryStatus,
}: ErrorBlockTitleProps): [React.ReactElement, React.ReactElement] => {
const { t } = useTranslation("common")
const getIconSpan = (iconName: string, colorClass: string) => (
<div className="w-4 h-4 flex items-center justify-center">
<span className={`codicon codicon-${iconName} text-base -mb-0.5 ${colorClass}`} />
@@ -43,31 +43,31 @@ export const ErrorBlockTitle = ({
const title = (() => {
// Default loading state
const details = { title: "API Request...", classNames: ["font-bold"] }
const details = { title: t("errorBlock.apiRequestLoading"), classNames: ["font-bold"] }
// Handle cancellation states first
if (apiReqCancelReason === "user_cancelled") {
details.title = "API Request Cancelled"
details.title = t("errorBlock.apiRequestCancelled")
details.classNames.push("text-(--vscode-foreground)")
} else if (apiReqCancelReason != null) {
details.title = "API Request Failed"
details.title = t("errorBlock.apiRequestFailed")
details.classNames.push("text-(--vscode-errorForeground)")
} else if (cost != null) {
// Handle completed request
details.title = "API Request"
details.title = t("errorBlock.apiRequest")
details.classNames.push("text-(--vscode-foreground)")
} else if (apiRequestFailedMessage) {
// Handle failed request
const clineError = ClineError.parse(apiRequestFailedMessage)
const titleText = clineError?.isErrorType(ClineErrorType.Balance)
? "Credit Limit Reached"
? t("errorBlock.creditLimitReached")
: clineError?.isErrorType(ClineErrorType.SpendLimit)
? "Spend Limit Reached"
: "API Request Failed"
? t("errorBlock.spendLimitReached")
: t("errorBlock.apiRequestFailed")
details.title = titleText
details.classNames.push("font-bold text-(--vscode-errorForeground)")
} else if (retryStatus) {
// Handle retry state
details.title = "API Request"
details.title = t("errorBlock.apiRequest")
details.classNames.push("text-(--vscode-foreground)")
}
+11 -7
View File
@@ -1,5 +1,6 @@
import { ClineMessage } from "@shared/ExtensionMessage"
import { memo } from "react"
import { useTranslation } from "react-i18next"
import CreditLimitError from "@/components/chat/CreditLimitError"
import SpendLimitError from "@/components/chat/SpendLimitError"
import { Button } from "@/components/ui/button"
@@ -16,6 +17,8 @@ interface ErrorRowProps {
}
const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStreamingFailedMessage }: ErrorRowProps) => {
tconst
t = useTranslation("common")
const { clineUser } = useClineAuth()
const rawApiError = apiRequestFailedMessage || apiReqStreamingFailedMessage
@@ -80,7 +83,7 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
// 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">
Whoops looks like you're logged out – click below to sign in
{t("error.loggedOut")}
</div>
<Button className="w-full" disabled={isLoginLoading} onClick={handleSignIn}>
Sign in to Cline
@@ -94,7 +97,7 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
) : (
// 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">(Click "Retry" below)</span>
<span className="text-description">{t("error.clickRetry")}</span>
</div>
)
}
@@ -113,11 +116,11 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
{/* Windows Powershell Issue */}
{errorMessage?.toLowerCase()?.includes("powershell") && (
<div>
It seems like you're having Windows PowerShell issues, please see this{" "}
{t("error.powershellIssue")}{" "}
<a
className="underline text-inherit"
href="https://github.com/cline/cline/wiki/TroubleShooting-%E2%80%90-%22PowerShell-is-not-recognized-as-an-internal-or-external-command%22">
troubleshooting guide
{t("error.troubleshootingGuide")}
</a>
.
</div>
@@ -127,7 +130,7 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
{errorMessage !== rawApiError && <div>{rawApiError}</div>}
<div className="mt-4">
<span className="text-description">(Click "Retry" below)</span>
<span className="text-description">{t("error.clickRetry")}</span>
</div>
</p>
)
@@ -139,7 +142,7 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
case "diff_error":
return (
<div className="flex flex-col p-2 rounded text-xs opacity-80 bg-quote text-foreground">
<div>The model used search patterns that don't match anything in the file. Retrying...</div>
<div>{t("error.diffError")}</div>
</div>
)
@@ -147,7 +150,8 @@ const ErrorRow = memo(({ message, errorType, apiRequestFailedMessage, apiReqStre
return (
<div className="flex flex-col p-2 rounded text-xs opacity-80 bg-quote text-foreground">
<div>
Cline tried to access <code>{message.text}</code> which is blocked by the <code>.clineignore</code>
{t("error.clineignoreError")} <code>{message.text}</code> {t("error.clineignoreBlocked")}{" "}
<code>.clineignore</code> {t("error.clineignoreFile")}
file.
</div>
</div>
@@ -1,5 +1,7 @@
import i18next from "i18next"
import { LightbulbIcon } from "lucide-react"
import { memo, useCallback, useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { cn } from "@/lib/utils"
interface FeatureTipItem {
@@ -8,7 +10,7 @@ interface FeatureTipItem {
const FEATURE_TIPS: FeatureTipItem[] = [
{
text: 'Enable "Double-Check Completion" in settings to have Cline verify its work before finishing a task.',
text: i18next.t("featureTips.doubleCheckCompletion"),
},
{
text: "Add a .clinerules file to your project root to give Cline project-specific instructions.",
@@ -44,7 +46,7 @@ const FEATURE_TIPS: FeatureTipItem[] = [
text: "Use /reportbug to quickly file a GitHub issue with diagnostic context included.",
},
{
text: 'You can disable these tips in Settings → Features → "Feature Tips".',
text: i18next.t("featureTips.disableTips"),
},
]
@@ -57,6 +59,8 @@ const FADE_DURATION_MS = 300
* Appears after a brief delay and cycles through tips while Cline is thinking.
*/
export const FeatureTip = memo(() => {
tconst
t = useTranslation("common")
const [isVisible, setIsVisible] = useState(false)
const [hasFadedIn, setHasFadedIn] = useState(false)
const [isFading, setIsFading] = useState(false)
@@ -108,7 +112,7 @@ export const FeatureTip = memo(() => {
)}>
<LightbulbIcon className="size-3 text-description shrink-0 mt-[1px]" />
<span className="text-xs text-description leading-relaxed">
<span className="font-medium">Tip:</span> {currentTip.text}
<span className="font-medium">{t("featureTips.tip")}</span> {currentTip.text}
</span>
</div>
)
@@ -1,6 +1,7 @@
import { ClineMessage } from "@shared/ExtensionMessage"
import { EmptyRequest } from "@shared/proto/cline/common"
import { memo, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import { TaskServiceClient } from "@/services/grpc-client"
import { CHAT_ROW_EXPANDED_BG_COLOR } from "../common/CodeBlock"
import { HOOK_OUTPUT_STRING } from "./constants"
@@ -81,6 +82,8 @@ interface HookMetadata {
* - Running hooks: Always shows pending tool info
*/
const HookMessage = memo(({ message, CommandOutput }: HookMessageProps) => {
tconst
t = useTranslation("common")
// Parse hook metadata and output
const { metadata, output } = useMemo(() => {
const splitMessage = (text: string) => {
@@ -147,8 +150,9 @@ const HookMessage = memo(({ message, CommandOutput }: HookMessageProps) => {
style={{
color: normalColor,
marginBottom: "-1.5px",
}}></span>
<span style={{ color: normalColor, fontWeight: "bold" }}>Hook:</span>
}}
/>
<span style={{ color: normalColor, fontWeight: "bold" }}>{t("hookMessage.hook")}</span>
<span style={{ color: normalColor }}>{metadata.hookName}</span>
{metadata.toolName && (
<span style={{ color: "var(--vscode-descriptionForeground)", fontSize: "0.9em" }}>({metadata.toolName})</span>
@@ -258,7 +262,7 @@ const HookMessage = memo(({ message, CommandOutput }: HookMessageProps) => {
fontSize: "13px",
color: "var(--vscode-descriptionForeground)",
}}>
Took longer than 30 seconds. Check for infinite loops or add timeouts to network requests.
t("hookMessage.timeoutError")
</div>
)}
@@ -270,7 +274,7 @@ const HookMessage = memo(({ message, CommandOutput }: HookMessageProps) => {
fontSize: "13px",
color: "var(--vscode-descriptionForeground)",
}}>
Hook returned invalid JSON. See error details below for more information.
t("hookMessage.validationError")
</div>
)}
@@ -6,9 +6,11 @@ interface NewTaskPreviewProps {
}
const NewTaskPreview: React.FC<NewTaskPreviewProps> = ({ context }) => {
tconst
t = useTranslation("common")
return (
<div className="bg-(--vscode-badge-background) text-(--vscode-badge-foreground) rounded-[3px] p-[14px] pb-[6px]">
<span style={{ fontWeight: "bold" }}>Task</span>
<span style={{ fontWeight: "bold" }}>{t("newTaskPreview.task")}</span>
<MarkdownBlock markdown={context} />
</div>
)
@@ -1,5 +1,6 @@
import { NotepadTextIcon } from "lucide-react"
import { memo } from "react"
import { useTranslation } from "react-i18next"
import { CopyButton } from "@/components/common/CopyButton"
import MarkdownBlock from "@/components/common/MarkdownBlock"
import { cn } from "@/lib/utils"
@@ -15,13 +16,15 @@ interface PlanCompletionOutputProps {
* Uses grayscale colors to distinguish from Act Mode's green success theme
*/
const PlanCompletionOutputRow = memo(({ text, headClassNames }: PlanCompletionOutputProps) => {
tconst
t = useTranslation("common")
return (
<div className="rounded-sm border border-description/50 overflow-visible bg-code p-2 pt-3">
{/* Header */}
<div className={cn(headClassNames, "justify-between px-1")}>
<div className="flex gap-2 items-center">
<NotepadTextIcon className="size-2" />
<span className="text-foreground font-bold">Plan Created</span>
<span className="text-foreground font-bold">{t("planCompletion.planCreated")}</span>
</div>
<CopyButton textToCopy={text || ""} />
</div>
@@ -21,18 +21,20 @@ const ButtonContainer = styled.div<ButtonContainerProps>`
`
const QuoteButton: React.FC<QuoteButtonProps> = ({ top, left, onClick }) => {
tconst
t = useTranslation("common")
return (
// Pass transient props to the styled component
<ButtonContainer $left={left} $top={top} className="quote-button-class absolute">
<Button
aria-label="Quote selection"
aria-label={t("quoteButton.quoteSelection")}
className="p-3 h-auto min-w-auto rounded-md shadow-sm transition-transform hover:scale-105 z-10"
onClick={(e) => {
e.stopPropagation() // Prevent triggering mouseup on the parent
onClick()
}}
size="sm"
title="Quote selection in reply">
title={t("quoteButton.quoteInReply")}>
<QuoteIcon className="size-2 fill-button-foreground rotate-180 stroke-1" />
</Button>
</ButtonContainer>
@@ -70,16 +70,18 @@ interface QuotedMessagePreviewProps {
}
const QuotedMessagePreview: React.FC<QuotedMessagePreviewProps> = ({ text, onDismiss, isFocused }) => {
tconst
t = useTranslation("common")
const _cardClassName = `reply-card ${isFocused ? "reply-card--focused" : ""}`
return (
<PreviewContainer>
{/* Removed Label */}
<ContentRow>
<ReplyIcon className="codicon codicon-reply"></ReplyIcon>
<ReplyIcon className="codicon codicon-reply" />
<TextContainer title={text}>{text}</TextContainer>
<DismissButton appearance="icon" aria-label="Dismiss quote" onClick={onDismiss}>
<span className="codicon codicon-close"></span>
<DismissButton appearance="icon" aria-label={t("quotedMessage.dismissQuote")} onClick={onDismiss}>
<span className="codicon codicon-close" />
</DismissButton>
</ContentRow>
</PreviewContainer>
@@ -6,6 +6,8 @@ interface ReportBugPreviewProps {
}
const ReportBugPreview: React.FC<ReportBugPreviewProps> = ({ data }) => {
tconst
t = useTranslation("common")
// Parse the JSON data from the context string
const bugData = React.useMemo(() => {
try {
@@ -18,61 +20,61 @@ const ReportBugPreview: React.FC<ReportBugPreviewProps> = ({ data }) => {
return (
<div className="bg-badge-background/50 text-badge-foreground rounded-xs p-3">
<h2 className="font-bold mb-3">{bugData.title || "Bug Report"}</h2>
<h2 className="font-bold mb-3">{bugData.title || t("reportBug.title")}</h2>
<div className="space-y-3 text-sm">
{bugData.what_happened && (
<div>
<div className="font-semibold">What Happened?</div>
<div className="font-semibold">{t("reportBug.whatHappened")}</div>
<MarkdownBlock markdown={bugData.what_happened} />
</div>
)}
{bugData.steps_to_reproduce && (
<div>
<div className="font-semibold">Steps to Reproduce</div>
<div className="font-semibold">{t("reportBug.stepsToReproduce")}</div>
<MarkdownBlock markdown={bugData.steps_to_reproduce} />
</div>
)}
{bugData.api_request_output && (
<div>
<div className="font-semibold">Relevant API Request Output</div>
<div className="font-semibold">{t("reportBug.apiOutput")}</div>
<MarkdownBlock markdown={bugData.api_request_output} />
</div>
)}
{bugData.provider_and_model && (
<div>
<div className="font-semibold">Provider/Model</div>
<div className="font-semibold">{t("reportBug.providerModel")}</div>
<MarkdownBlock markdown={bugData.provider_and_model} />
</div>
)}
{bugData.operating_system && (
<div>
<div className="font-semibold">Operating System</div>
<div className="font-semibold">{t("reportBug.operatingSystem")}</div>
<MarkdownBlock markdown={bugData.operating_system} />
</div>
)}
{bugData.system_info && (
<div>
<div className="font-semibold">System Info</div>
<div className="font-semibold">{t("reportBug.systemInfo")}</div>
<MarkdownBlock markdown={bugData.system_info} />
</div>
)}
{bugData.cline_version && (
<div>
<div className="font-semibold">Cline Version</div>
<div className="font-semibold">{t("reportBug.clineVersion")}</div>
<MarkdownBlock markdown={bugData.cline_version} />
</div>
)}
{bugData.additional_context && (
<div>
<div className="font-semibold">Additional Context</div>
<div className="font-semibold">{t("reportBug.additionalContext")}</div>
<MarkdownBlock markdown={bugData.additional_context} />
</div>
)}
@@ -42,10 +42,10 @@ const getActivityText = (tool: ClineSayTool): string | null => {
const cleanedPath = cleanPathPrefix(tool.path || "")
switch (tool.tool) {
case "readFile":
return tool.path ? `Reading ${cleanedPath}...` : null
return tool.path ? t("requestStart.reading", { path: cleanPathPrefix(tool.path || "") }) : null
case "listFilesTopLevel":
case "listFilesRecursive":
return tool.path ? `Exploring ${cleanedPath}/...` : null
return tool.path ? t("requestStart.exploring", { path: cleanedPath }) : null
case "searchFiles":
return tool.regex && tool.path ? `Searching ${formatSearchRegex(tool.regex, tool.path, tool.filePattern)}...` : null
case "listCodeDefinitionNames":
@@ -90,7 +90,7 @@ const SearchResultsDisplay: React.FC<SearchResultsDisplayProps> = ({
border: "1px solid var(--vscode-editorGroup-border)",
}}>
<div
aria-label={isExpanded ? "Collapse search results" : "Expand search results"}
aria-label={isExpanded ? t("searchResults.collapseResults") : t("searchResults.expandResults")}
onClick={onToggleExpand}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") {
@@ -121,7 +121,7 @@ const SearchResultsDisplay: React.FC<SearchResultsDisplayProps> = ({
}}>
{path + (filePattern ? `/(${filePattern})` : "")}
</span>
<div style={{ flexGrow: 1 }}></div>
<div style={{ flexGrow: 1 }} />
{isExpanded ? (
<ChevronDownIcon size={16} style={{ margin: "1px 0" }} />
) : (
@@ -162,7 +162,8 @@ const SearchResultsDisplay: React.FC<SearchResultsDisplayProps> = ({
style={{
fontSize: "14px",
color: "var(--vscode-symbolIcon-folderForeground)",
}}></span>
}}
/>
<span
style={{
fontWeight: "500",
@@ -3,6 +3,7 @@ import { McpServers } from "@shared/proto/cline/mcp"
import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import React, { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useClickAway, useWindowSize } from "react-use"
import PopupModalContainer from "@/components/common/PopupModalContainer"
import ServersToggleList from "@/components/mcp/configuration/tabs/installed/ServersToggleList"
@@ -11,6 +12,8 @@ import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
const ServersToggleModal: React.FC = () => {
tconst
t = useTranslation("common")
const { mcpServers, navigateToMcp, setMcpServers } = useExtensionState()
const [isVisible, setIsVisible] = useState(false)
const buttonRef = useRef<HTMLDivElement>(null)
@@ -55,11 +58,11 @@ const ServersToggleModal: React.FC = () => {
<div className="inline-flex min-w-0 max-w-full items-center" ref={modalRef}>
<div className="inline-flex w-full items-center" ref={buttonRef}>
<Tooltip>
{!isVisible && <TooltipContent>Manage MCP Servers</TooltipContent>}
{!isVisible && <TooltipContent>{t("serversToggle.manage")}</TooltipContent>}
<TooltipTrigger>
<VSCodeButton
appearance="icon"
aria-label={isVisible ? "Hide MCP Servers" : "Show MCP Servers"}
aria-label={isVisible ? t("serversToggle.hide") : t("serversToggle.show")}
className="p-0 m-0 flex items-center"
onClick={() => setIsVisible(!isVisible)}>
<i className="codicon codicon-server" style={{ fontSize: "12.5px" }} />
@@ -72,15 +75,15 @@ const ServersToggleModal: React.FC = () => {
<PopupModalContainer $arrowPosition={arrowPosition} $menuPosition={menuPosition}>
<div className="flex-shrink-0 px-3 pt-2">
<div className="flex justify-between items-center mb-2.5">
<div className="m-0 text-sm font-medium">MCP Servers</div>
<div className="m-0 text-sm font-medium">{t("serversToggle.title")}</div>
<VSCodeButton
appearance="icon"
aria-label="Go to MCP server settings"
aria-label={t("serversToggle.goToSettings")}
onClick={() => {
setIsVisible(false)
navigateToMcp("configure")
}}>
<span className="codicon codicon-gear text-[10px]"></span>
<span className="codicon codicon-gear text-[10px]" />
</VSCodeButton>
</div>
</div>
@@ -1,8 +1,8 @@
import type { McpServer } from "@shared/mcp"
import type { SlashCommand } from "@/utils/slash-commands"
import React, { useCallback, useEffect, useRef } from "react"
import ScreenReaderAnnounce from "@/components/common/ScreenReaderAnnounce"
import { useMenuAnnouncement } from "@/hooks/useMenuAnnouncement"
import type { SlashCommand } from "@/utils/slash-commands"
import { getMatchingSlashCommands } from "@/utils/slash-commands"
interface SlashCommandMenuProps {
@@ -131,25 +131,32 @@ const SlashCommandMenu: React.FC<SlashCommandMenuProps> = ({
<ScreenReaderAnnounce message={announcement} />
<div
aria-activedescendant={filteredCommands.length > 0 ? `slash-command-menu-item-${selectedIndex}` : undefined}
aria-label="Slash commands"
aria-label={t("slashCommandMenu.ariaLabel")}
className="bg-(--vscode-dropdown-background) border border-(--vscode-editorGroup-border) rounded-[3px] shadow-[0_4px_10px_rgba(0,0,0,0.25)] flex flex-col overflow-y-auto"
ref={menuRef}
role="listbox"
style={{ maxHeight: "min(200px, calc(50vh))", overscrollBehavior: "contain" }}>
{filteredCommands.length > 0 ? (
<>
{renderCommandSection(defaultCommands, "Default Commands", 0, true)}
{renderCommandSection(workflowCommands, "Workflow Commands", defaultCommands.length, false)}
{renderCommandSection(defaultCommands, t("slashCommandMenu.defaultCommands"), 0, true)}
{renderCommandSection(
workflowCommands,
t("slashCommandMenu.workflowCommands"),
defaultCommands.length,
false,
)}
{renderCommandSection(
mcpCommands,
"MCP Prompts",
t("slashCommandMenu.mcpPrompts"),
defaultCommands.length + workflowCommands.length,
true,
)}
</>
) : (
<div aria-selected="false" className="py-2 px-3 cursor-default flex flex-col" role="option">
<div className="text-[0.85em] text-(--vscode-descriptionForeground)">No matching commands found</div>
<div className="text-[0.85em] text-(--vscode-descriptionForeground)">
{t("slashCommandMenu.noMatching")}
</div>
</div>
)}
</div>
@@ -1,5 +1,6 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import React, { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { AccountServiceClient } from "@/services/grpc-client"
const COOLDOWN_MS = 5 * 60 * 1000 // 5 minutes
@@ -37,6 +38,8 @@ interface SpendLimitErrorProps {
}
const SpendLimitError: React.FC<SpendLimitErrorProps> = ({ message, budgetPeriod, limitUsd, spentUsd, resetsAt }) => {
tconst
t = useTranslation("common")
const displayMessage =
limitUsd != null && budgetPeriod ? `$${limitUsd.toFixed(2)} ${budgetPeriod} limit has been reached.` : message
@@ -96,7 +99,7 @@ const SpendLimitError: React.FC<SpendLimitErrorProps> = ({ message, budgetPeriod
<div className="mb-3">
{spentUsd != null && limitUsd != null && (
<div className="text-foreground" style={{ fontSize: "var(--vscode-font-size)", lineHeight: 1.3 }}>
{periodLabel ? `${periodLabel} usage` : "Usage"}:{" "}
{periodLabel ? `${periodLabel} ${t("spendLimit.usage")}` : t("spendLimit.usage")}:{" "}
<span className="font-bold">
${spentUsd.toFixed(2)} / ${limitUsd.toFixed(2)}
</span>
@@ -111,7 +114,7 @@ const SpendLimitError: React.FC<SpendLimitErrorProps> = ({ message, budgetPeriod
<div className="text-(--vscode-descriptionForeground) mt-2 text-xs inline-flex items-center">
<span className="codicon codicon-organization mr-1" />
Limits set by your organization.
{t("spendLimit.limitsByOrg")}
</div>
</div>
</div>
@@ -16,6 +16,7 @@ import {
NetworkIcon,
} from "lucide-react"
import { useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import MarkdownBlock from "../common/MarkdownBlock"
interface SubagentStatusRowProps {
@@ -120,6 +121,7 @@ function parseSubagentRowData(message: ClineMessage): SubagentRowData | null {
}
function SubagentPromptText({ prompt, isExpanded, onShowMore }: SubagentPromptTextProps) {
const { t } = useTranslation("common")
const promptRef = useRef<HTMLDivElement | null>(null)
const [showMoreVisible, setShowMoreVisible] = useState(false)
@@ -160,7 +162,7 @@ function SubagentPromptText({ prompt, isExpanded, onShowMore }: SubagentPromptTe
</div>
{!isExpanded && showMoreVisible && (
<button
aria-label="Show full subagent prompt"
aria-label={t("subagent.showFullPrompt")}
className="absolute right-0 bottom-0 z-10 text-[11px] text-link border-0 px-1 py-[1px] cursor-pointer leading-none rounded-[2px]"
onClick={onShowMore}
style={{ backgroundColor: "var(--vscode-editor-background)" }}
@@ -178,12 +180,13 @@ function SubagentPromptText({ prompt, isExpanded, onShowMore }: SubagentPromptTe
}
export default function SubagentStatusRow({ message, isLast, lastModifiedMessage }: SubagentStatusRowProps) {
const { t } = useTranslation("common")
const [expandedItems, setExpandedItems] = useState<Record<number, boolean>>({})
const [expandedPrompts, setExpandedPrompts] = useState<Record<number, boolean>>({})
const data = useMemo(() => parseSubagentRowData(message), [message])
if (!data) {
return <div className="text-foreground opacity-80">Subagent status update unavailable.</div>
return <div className="text-foreground opacity-80">{t("subagent.statusUnavailable")}</div>
}
const resumedBeforeNextVisibleMessage =
@@ -197,7 +200,7 @@ export default function SubagentStatusRow({ message, isLast, lastModifiedMessage
resumedBeforeNextVisibleMessage)
const singular = data.items.length === 1
const title = singular ? "Cline wants to use a subagent:" : "Cline wants to use subagents:"
const title = singular ? t("subagent.wantsSubagentSingular") : t("subagent.wantsSubagentPlural")
const isPromptConstructionRow = message.ask === "use_subagents" || message.say === "use_subagents"
const toggleItem = (index: number) => {
setExpandedItems((prev) => ({
@@ -253,7 +256,7 @@ export default function SubagentStatusRow({ message, isLast, lastModifiedMessage
)}
{shouldShowStats && hasDetails && (
<button
aria-label={isExpanded ? "Hide subagent output" : "Show subagent output"}
aria-label={isExpanded ? t("subagent.hideSubagentOutput") : t("subagent.showSubagentOutput")}
className="mt-1 text-[11px] opacity-80 flex items-center gap-1 bg-transparent border-0 p-0 cursor-pointer text-left text-foreground w-full"
onClick={() => toggleItem(entry.index)}
type="button">
@@ -2,6 +2,7 @@ import { StringRequest } from "@shared/proto/cline/common"
import { TaskFeedbackType } from "@shared/WebviewMessage"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import React, { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import { cn } from "@/lib/utils"
import { TaskServiceClient } from "@/services/grpc-client"
@@ -21,6 +22,8 @@ const ButtonWrapper = styled.div`
`
const TaskFeedbackButtons: React.FC<TaskFeedbackButtonsProps> = ({ messageTs, isFromHistory = false, classNames }) => {
tconst
t = useTranslation("common")
const [feedback, setFeedback] = useState<TaskFeedbackType | null>(null)
const [shouldShow, setShouldShow] = useState<boolean>(true)
@@ -77,10 +80,10 @@ const TaskFeedbackButtons: React.FC<TaskFeedbackButtonsProps> = ({ messageTs, is
<ButtonWrapper>
<VSCodeButton
appearance="icon"
aria-label="This was helpful"
aria-label={t("taskFeedback.helpful")}
disabled={feedback !== null}
onClick={() => handleFeedback("thumbs_up")}
title="This was helpful">
title={t("taskFeedback.helpful")}>
<IconWrapper>
<span
className={`codicon ${feedback === "thumbs_up" ? "codicon-thumbsup-filled" : "codicon-thumbsup"}`}
@@ -91,10 +94,10 @@ const TaskFeedbackButtons: React.FC<TaskFeedbackButtonsProps> = ({ messageTs, is
<ButtonWrapper>
<VSCodeButton
appearance="icon"
aria-label="This wasn't helpful"
aria-label={t("taskFeedback.notHelpful")}
disabled={feedback !== null && feedback !== "thumbs_down"}
onClick={() => handleFeedback("thumbs_down")}
title="This wasn't helpful">
title={t("taskFeedback.notHelpful")}>
<IconWrapper>
<span
className={`codicon ${feedback === "thumbs_down" ? "codicon-thumbsdown-filled" : "codicon-thumbsdown"}`}
@@ -1,5 +1,6 @@
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import { memo, useCallback, useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
@@ -21,10 +22,12 @@ export const ThinkingRow = memo(
isVisible,
isExpanded,
onToggle,
title = "Thinking",
title,
isStreaming = false,
showChevron = true,
}: ThinkingRowProps) => {
const { t } = useTranslation("common")
const displayTitle = title ?? t("chatRow.thinking")
const scrollRef = useRef<HTMLDivElement>(null)
const [canScrollUp, setCanScrollUp] = useState(false)
const [canScrollDown, setCanScrollDown] = useState(false)
@@ -75,7 +78,7 @@ export const ThinkingRow = memo(
isStreaming,
"select-none": isStreaming,
})}>
{title}
{displayTitle}
</span>
{showChevron &&
(isExpanded ? (
@@ -1,6 +1,7 @@
import { CheckpointRestoreRequest } from "@shared/proto/cline/checkpoints"
import { ClineCheckpointRestore } from "@shared/WebviewMessage"
import React, { forwardRef, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import DynamicTextArea from "react-textarea-autosize"
import Thumbnails from "@/components/common/Thumbnails"
import { useExtensionState } from "@/context/ExtensionStateContext"
@@ -16,6 +17,8 @@ interface UserMessageProps {
}
const UserMessage: React.FC<UserMessageProps> = ({ text, images, files, messageTs, sendMessageFromChatRow }) => {
tconst
t = useTranslation("common")
const [isEditing, setIsEditing] = useState(false)
const [editedText, setEditedText] = useState(text || "")
const textAreaRef = useRef<HTMLTextAreaElement>(null)
@@ -127,19 +130,19 @@ const UserMessage: React.FC<UserMessageProps> = ({ text, images, files, messageT
{!checkpointManagerErrorMessage && (
<RestoreButton
isPrimary={false}
label="Restore All"
label={t("userMessage.restoreAll")}
onClick={handleRestoreWorkspace}
ref={restoreAllButtonRef}
title="Restore both the chat and workspace files to this checkpoint and send your edited message"
title={t("userMessage.restoreAllTitle")}
type="taskAndWorkspace"
/>
)}
<RestoreButton
isPrimary={true}
label="Restore Chat"
label={t("userMessage.restoreChat")}
onClick={handleRestoreWorkspace}
ref={restoreChatButtonRef}
title="Restore just the chat to this checkpoint and send your edited message"
title={t("userMessage.restoreChatTitle")}
type="task"
/>
</div>
@@ -1,5 +1,6 @@
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import { useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { getAsVar, VSC_TITLEBAR_INACTIVE_FOREGROUND } from "@/utils/vscStyles"
import AutoApproveModal from "./AutoApproveModal"
@@ -10,6 +11,8 @@ interface AutoApproveBarProps {
}
const AutoApproveBar = ({ style }: AutoApproveBarProps) => {
tconst
t = useTranslation("common")
const { autoApprovalSettings, yoloModeToggled, navigateToSettings } = useExtensionState()
const [isModalVisible, setIsModalVisible] = useState(false)
@@ -47,7 +50,7 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => {
})
if (actionsToShow.length === 0) {
return <span className={baseClasses}>None</span>
return <span className={baseClasses}>{t("autoApprove.none")}</span>
}
return (
@@ -100,7 +103,7 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => {
/>
<div className="pt-4 pb-3.5 px-3.5">
<div className="text-sm mb-1">Auto-approve: YOLO</div>
<div className="text-sm mb-1">{t("autoApprove.yolo")}</div>
<div className="text-muted-foreground text-xs">
YOLO mode is enabled.{" "}
<span className="underline cursor-pointer hover:text-foreground" onClick={handleNavigateToFeatures}>
@@ -144,7 +147,7 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => {
/>
<div
aria-label={isModalVisible ? "Close auto-approve settings" : "Open auto-approve settings"}
aria-label={isModalVisible ? t("autoApprove.closeSettings") : t("autoApprove.openSettings")}
className="group cursor-pointer pt-3 pb-3.5 pr-2 px-3.5 flex items-center justify-between gap-0"
onClick={() => {
setIsModalVisible((prev) => !prev)
@@ -159,7 +162,7 @@ const AutoApproveBar = ({ style }: AutoApproveBarProps) => {
ref={buttonRef}
tabIndex={0}>
<div className="flex flex-nowrap items-center gap-1 min-w-0 flex-1">
<span className="whitespace-nowrap">Auto-approve:</span>
<span className="whitespace-nowrap">{t("autoApprove.label")}</span>
{getEnabledActionsText()}
</div>
{isModalVisible ? <ChevronDownIcon size={16} /> : <ChevronRightIcon size={16} />}
@@ -44,7 +44,7 @@ const AutoApproveMenuItem = ({ action, isChecked, onToggle, showIcon = true, dis
<CheckboxWrapper $disabled={disabled} className="w-full" onClick={onChange}>
<VSCodeCheckbox checked={checked} disabled={disabled}>
<div className="w-full flex text-sm items-center justify-start text-foreground gap-2">
{showIcon && <span className={`codicon ${action.icon} icon`}></span>}
{showIcon && <span className={`codicon ${action.icon} icon`} />}
<span className="label">{action.label}</span>
</div>
</VSCodeCheckbox>
@@ -1,5 +1,6 @@
import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react"
import React, { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useClickAway } from "react-use"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { useAutoApproveActions } from "@/hooks/useAutoApproveActions"
@@ -18,6 +19,7 @@ interface AutoApproveModalProps {
}
const AutoApproveModal: React.FC<AutoApproveModalProps> = ({ isVisible, setIsVisible, buttonRef, ACTION_METADATA }) => {
const { t } = useTranslation("common")
const { autoApprovalSettings } = useExtensionState()
const { isChecked, updateAction } = useAutoApproveActions()
const modalRef = useRef<HTMLDivElement>(null)
@@ -129,12 +131,10 @@ const AutoApproveModal: React.FC<AutoApproveModalProps> = ({ isVisible, setIsVis
enableNotifications: checked,
})
}}>
<span className="text-sm">Enable notifications</span>
<span className="text-sm">{t("autoApprove.enableNotifications")}</span>
</VSCodeCheckbox>
</div>
<div className="mt-1 text-xs text-muted-foreground">
Notifications may show abbreviated tool details for safety and privacy.
</div>
<div className="mt-1 text-xs text-muted-foreground">{t("autoApprove.notificationsDescription")}</div>
</div>
</div>
)
@@ -132,7 +132,7 @@ export const ActionButtons: React.FC<ActionButtonsProps> = ({
<div className="flex px-3.5">
<VSCodeButton
appearance="icon"
aria-label={showScrollToBottom ? "Scroll to bottom" : "Scroll to top"}
aria-label={showScrollToBottom ? t("buttons.scrollToBottom") : t("buttons.scrollToTop")}
className="text-lg text-(--vscode-primaryButton-foreground) bg-[color-mix(in_srgb,var(--vscode-toolbar-hoverBackground)_55%,transparent)] rounded-[3px] overflow-hidden cursor-pointer flex justify-center items-center flex-1 h-[25px] hover:bg-[color-mix(in_srgb,var(--vscode-toolbar-hoverBackground)_90%,transparent)] active:bg-[color-mix(in_srgb,var(--vscode-toolbar-hoverBackground)_70%,transparent)] border-0"
onClick={showScrollToBottom ? handleScrollToBottom : handleScrollToTop}
onKeyDown={(e) => {
@@ -4,6 +4,7 @@ import type { Worktree } from "@shared/proto/cline/worktree"
import { TrackWorktreeViewOpenedRequest } from "@shared/proto/cline/worktree"
import { GitBranch } from "lucide-react"
import React, { useCallback, useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import BannerCarousel from "@/components/common/BannerCarousel"
import WhatsNewModal from "@/components/common/WhatsNewModal"
import HistoryPreview from "@/components/history/HistoryPreview"
@@ -31,6 +32,7 @@ export const WelcomeSection: React.FC<WelcomeSectionProps> = ({
taskHistory,
shouldShowQuickWins,
}) => {
const { t } = useTranslation("common")
const { lastDismissedInfoBannerVersion, lastDismissedCliBannerVersion, lastDismissedModelBannerVersion, dismissedBanners } =
useExtensionState()
@@ -295,7 +297,7 @@ export const WelcomeSection: React.FC<WelcomeSectionProps> = ({
<div className="flex items-center gap-1.5 text-xs">
<GitBranch className="w-3 h-3 stroke-[2.5] flex-shrink-0" />
<span className="break-all text-center">
<span className="font-semibold">Current:</span>{" "}
<span className="font-semibold">{t("taskHeader.currentBranch")}</span>{" "}
{currentWorktree.branch || "detached HEAD"}
</span>
</div>
@@ -304,9 +306,7 @@ export const WelcomeSection: React.FC<WelcomeSectionProps> = ({
</span>
</button>
</TooltipTrigger>
<TooltipContent side="bottom">
View and manage git worktrees. Great for running parallel Cline tasks.
</TooltipContent>
<TooltipContent side="bottom">{t("taskHeader.viewManageWorktrees")}</TooltipContent>
</Tooltip>
)}
</div>
@@ -1,5 +1,6 @@
import { ClineMessage, ClineSayTool } from "@shared/ExtensionMessage"
import { StringRequest } from "@shared/proto/cline/common"
import i18next from "i18next"
import { memo, useCallback, useMemo, useState } from "react"
import { TypewriterText } from "@/components/chat/TypewriterText"
import { cleanPathPrefix } from "@/components/common/CodeAccordian"
@@ -35,8 +36,8 @@ const getActivityText = (tool: ClineSayTool): string | null => {
.filter(Boolean)
.join(" | ")
return filePattern && filePattern !== "*"
? `"${terms}" in ${cleanedPath}/ (${filePattern})`
: `"${terms}" in ${cleanedPath}/`
? i18next.t("toolGroup.searchInPathWithPattern", { terms, path: cleanedPath, pattern: filePattern })
: i18next.t("toolGroup.searchInPath", { terms, path: cleanedPath })
}
switch (tool.tool) {
@@ -45,16 +46,20 @@ const getActivityText = (tool: ClineSayTool): string | null => {
return null
}
const lineHint =
tool.readLineStart != null && tool.readLineEnd != null ? ` (lines ${tool.readLineStart}-${tool.readLineEnd})` : ""
return `Reading ${cleanedPath}${lineHint}...`
tool.readLineStart != null && tool.readLineEnd != null
? i18next.t("toolGroup.lines", { start: tool.readLineStart, end: tool.readLineEnd })
: ""
return i18next.t("toolGroup.reading", { path: cleanedPath, lineHint })
}
case "listFilesTopLevel":
case "listFilesRecursive":
return tool.path ? `Exploring ${cleanedPath}/...` : null
return tool.path ? i18next.t("toolGroup.exploring", { path: cleanedPath }) : null
case "searchFiles":
return tool.regex && tool.path ? `Searching ${formatSearchRegex(tool.regex, tool.path, tool.filePattern)}...` : null
return tool.regex && tool.path
? i18next.t("toolGroup.searching", { query: formatSearchRegex(tool.regex, tool.path, tool.filePattern) })
: null
case "listCodeDefinitionNames":
return tool.path ? `Analyzing ${cleanedPath}/...` : null
return tool.path ? i18next.t("toolGroup.analyzing", { path: cleanedPath }) : null
default:
return null
}
@@ -301,7 +306,7 @@ function getToolDisplayInfo(tool: ClineSayTool) {
switch (tool.tool) {
case "readFile": {
const lineNote =
tool.readLineStart != null && tool.readLineEnd != null ? `lines ${tool.readLineStart}-${tool.readLineEnd}` : null
tool.readLineStart != null && tool.readLineEnd != null ? `${tool.readLineStart}-${tool.readLineEnd}` : null
return {
icon,
path: filePath,
@@ -337,14 +342,16 @@ function formatSearchDisplay(regex: string, path: string, filePattern?: string):
.map((t) => t.trim().replace(/\\b/g, "").replace(/\\s\?/g, " "))
.filter(Boolean)
const termDisplay = terms.length > 3 ? `${terms.length} patterns` : `"${terms.join(" | ")}"`
let result = `${termDisplay} in ${cleanPathPrefix(path)}/`
const termDisplay =
terms.length > 3 ? i18next.t("toolGroup.patternsCount", { count: terms.length }) : `"${terms.join(" | ")}"`
if (filePattern && filePattern !== "*") {
result += ` (${filePattern})`
}
return result
return filePattern && filePattern !== "*"
? i18next.t("toolGroup.searchInPathWithPattern", {
terms: termDisplay,
path: cleanPathPrefix(path),
pattern: filePattern,
})
: i18next.t("toolGroup.searchInPath", { terms: termDisplay, path: cleanPathPrefix(path) })
}
/**
@@ -372,20 +379,24 @@ export function getToolGroupSummaryFromParsedTools(tools: ClineSayTool[]): strin
}
const parts: string[] = []
const action = counts.read > 0 || counts.list > 0 ? " read " : " "
const action = counts.read > 0 || counts.list > 0 ? i18next.t("toolGroup.read") : " "
if (counts.read > 0) {
parts.push(`${counts.read} file${counts.read > 1 ? "s" : ""}`)
parts.push(`${counts.read} ${i18next.t(counts.read > 1 ? "toolGroup.files" : "toolGroup.file")}`)
}
if (counts.list > 0) {
parts.push(`${counts.list} folder${counts.list > 1 ? "s" : ""}`)
parts.push(`${counts.list} ${i18next.t(counts.list > 1 ? "toolGroup.folders" : "toolGroup.folder")}`)
}
if (counts.def > 0) {
parts.push(`${counts.def} definition${counts.def > 1 ? "s" : ""}`)
parts.push(`${counts.def} ${i18next.t(counts.def > 1 ? "toolGroup.definitions" : "toolGroup.definition")}`)
}
if (counts.search > 0) {
parts.push(`performed ${counts.search} search${counts.search > 1 ? "es" : ""}`)
parts.push(
`${i18next.t("toolGroup.performed")} ${counts.search} ${i18next.t(counts.search > 1 ? "toolGroup.searches" : "toolGroup.search")}`,
)
}
return parts.length === 0 ? "Context" : "Cline" + action + parts.join(", ")
return parts.length === 0
? i18next.t("toolGroup.context")
: i18next.t("toolGroup.summaryClineAction", { action, parts: parts.join(i18next.t("toolGroup.summaryPartsSeparator")) })
}
@@ -1,6 +1,7 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import debounce from "debounce"
import React, { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { HoverCard, HoverCardContent, HoverCardTrigger } from "@/components/ui/hover-card"
import { Progress } from "@/components/ui/progress"
import { formatLargeNumber as formatTokenNumber } from "@/utils/format"
@@ -26,30 +27,33 @@ interface ContextWindowProgressProps extends ContextWindowInfoProps {
const ConfirmationDialog = memo<{
onConfirm: (e: React.MouseEvent) => void
onCancel: (e: React.MouseEvent) => void
}>(({ onConfirm, onCancel }) => (
<div className="text-sm my-2 flex items-center gap-0 justify-between">
<span className="font-semibold text-sm">Compact the current task?</span>
<span className="flex gap-1">
<VSCodeButton
appearance="secondary"
className="text-sm"
onClick={onCancel}
title="No, keep the task as is"
type="button">
Cancel
</VSCodeButton>
<VSCodeButton
appearance="primary"
autoFocus={true}
className="text-sm"
onClick={onConfirm}
title="Yes, compact the task"
type="button">
Yes
</VSCodeButton>
</span>
</div>
))
}>(({ onConfirm, onCancel }) => {
const { t } = useTranslation("common")
return (
<div className="text-sm my-2 flex items-center gap-0 justify-between">
<span className="font-semibold text-sm">{t("taskHeader.compactQuestion")}?</span>
<span className="flex gap-1">
<VSCodeButton
appearance="secondary"
className="text-sm"
onClick={onCancel}
title={t("taskHeader.no")}
type="button">
Cancel
</VSCodeButton>
<VSCodeButton
appearance="primary"
autoFocus={true}
className="text-sm"
onClick={onConfirm}
title={t("taskHeader.yes")}
type="button">
Yes
</VSCodeButton>
</span>
</div>
)
})
ConfirmationDialog.displayName = "ConfirmationDialog"
const ContextWindow: React.FC<ContextWindowProgressProps> = ({
@@ -62,6 +66,7 @@ const ContextWindow: React.FC<ContextWindowProgressProps> = ({
cacheWrites,
cacheReads,
}) => {
const { t } = useTranslation("common")
const [isOpened, setIsOpened] = useState(false)
const [confirmationNeeded, setConfirmationNeeded] = useState(false)
const progressBarRef = useRef<HTMLDivElement>(null)
@@ -166,7 +171,7 @@ const ContextWindow: React.FC<ContextWindowProgressProps> = ({
onFocus={handleFocus}
ref={progressBarRef}>
<Progress
aria-label="Context window usage progress"
aria-label={t("contextWindow.contextWindowUsage")}
color="success"
value={tokenData.percentage}
/>
@@ -1,5 +1,6 @@
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import React, { memo, useCallback, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import { formatLargeNumber as formatTokenNumber } from "@/utils/format"
interface TokenUsageInfoProps {
@@ -58,28 +59,32 @@ const AccordionItem = memo<{
})
AccordionItem.displayName = "AccordionItem"
// Constants
const TOKEN_DETAILS_CONFIG: Omit<TokenDetail, "value">[] = [
{ title: "Prompt Tokens", icon: "codicon-arrow-up" },
{ title: "Completion Tokens", icon: "codicon-arrow-down" },
{ title: "Cache Writes", icon: "codicon-arrow-left" },
{ title: "Cache Reads", icon: "codicon-arrow-right" },
]
const useTokenDetailTitles = () => {
const { t } = useTranslation("common")
return [
{ title: t("contextWindow.promptTokens"), icon: "codicon-arrow-up" },
{ title: t("contextWindow.completionTokens"), icon: "codicon-arrow-down" },
{ title: t("contextWindow.cacheWrites"), icon: "codicon-arrow-left" },
{ title: t("contextWindow.cacheReads"), icon: "codicon-arrow-right" },
]
}
const TokenUsageDetails = memo<TokenUsageInfoProps>(({ tokensIn, tokensOut, cacheWrites, cacheReads }) => {
const { t } = useTranslation("common")
const TOKEN_DETAILS_CONFIG = useTokenDetailTitles()
const contextTokenDetails = useMemo(() => {
const values = [tokensIn, tokensOut, cacheWrites || 0, cacheReads || 0]
return TOKEN_DETAILS_CONFIG.map((config, index) => ({ ...config, value: values[index] })).filter((item) => item.value)
}, [tokensIn, tokensOut, cacheWrites, cacheReads])
}, [tokensIn, tokensOut, cacheWrites, cacheReads, TOKEN_DETAILS_CONFIG])
if (!tokensIn) {
return <div>No token usage data available</div>
return <div>{t("contextWindow.noTokenData")}</div>
}
return (
<div className="space-y-1">
{contextTokenDetails.map((item) => (
<div className="flex justify-between">
<div className="flex justify-between" key={item.title}>
<span>{item.title}</span>
<span className="font-mono">{formatTokenNumber(item.value || 0)}</span>
</div>
@@ -99,6 +104,7 @@ export const ContextWindowSummary: React.FC<TaskContextWindowButtonsProps> = ({
percentage,
autoCompactThreshold = 0,
}) => {
const { t } = useTranslation("common")
// Accordion state
const [expandedSections, setExpandedSections] = useState<Set<string>>(new Set())
@@ -126,7 +132,7 @@ export const ContextWindowSummary: React.FC<TaskContextWindowButtonsProps> = ({
<AccordionItem
isExpanded={expandedSections.has("threshold")}
onToggle={(event) => toggleSection("threshold", event)}
title="Auto Condense Threshold"
title={t("contextWindow.autoCondenseThreshold")}
value={<span className="text-muted-foreground">{`${(autoCompactThreshold * 100).toFixed(0)}%`}</span>}>
<div className="space-y-1">
<p className="text-xs leading-relaxed text-white">
@@ -142,19 +148,19 @@ export const ContextWindowSummary: React.FC<TaskContextWindowButtonsProps> = ({
<AccordionItem
isExpanded={expandedSections.has("context")}
onToggle={(event) => toggleSection("context", event)}
title="Context Window"
title={t("contextWindow.contextWindow")}
value={percentage ? `${percentage.toFixed(1)}%` : formatTokenNumber(contextWindow)}>
<div className="space-y-1">
<div className="flex justify-between">
<span>Used:</span>
<span>{t("contextWindow.used")}</span>
<span className="font-mono">{formatTokenNumber(tokenUsed)}</span>
</div>
<div className="flex justify-between">
<span>Total:</span>
<span>{t("contextWindow.total")}</span>
<span className="font-mono">{formatTokenNumber(contextWindow)}</span>
</div>
<div className="flex justify-between">
<span>Remaining:</span>
<span>{t("contextWindow.remaining")}</span>
<span className="font-mono">{formatTokenNumber(contextWindow - tokenUsed)}</span>
</div>
</div>
@@ -164,7 +170,7 @@ export const ContextWindowSummary: React.FC<TaskContextWindowButtonsProps> = ({
<AccordionItem
isExpanded={expandedSections.has("tokens")}
onToggle={(event) => toggleSection("tokens", event)}
title="Token Usage"
title={t("contextWindow.tokenUsage")}
value={`${formatTokenNumber(totalTokens)}`}>
<TokenUsageDetails
cacheReads={cacheReads}
@@ -1,8 +1,10 @@
import { cn } from "@heroui/react"
import { isCompletedFocusChainItem, isFocusChainItem } from "@shared/focus-chain-utils"
import { StringRequest } from "@shared/proto/cline/common"
import i18next from "i18next"
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import React, { memo, useCallback, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import ChecklistRenderer from "@/components/common/ChecklistRenderer"
import LightMarkdown from "@/components/common/LightMarkdown"
import { FileServiceClient } from "@/services/grpc-client"
@@ -23,10 +25,10 @@ interface FocusChainProps {
}
// Static strings to avoid recreating them
const COMPLETED_MESSAGE = "All tasks have been completed!"
const TODO_LIST_LABEL = "To-Do list"
const NEW_STEPS_MESSAGE = "New steps will be generated if you continue the task"
const CLICK_TO_EDIT_TITLE = "Click to edit to-do list in file"
const COMPLETED_MESSAGE = i18next.t("focusChain.allCompleted")
const TODO_LIST_LABEL = i18next.t("focusChain.todoListLabel")
const NEW_STEPS_MESSAGE = i18next.t("focusChain.newStepsMessage")
const CLICK_TO_EDIT_TITLE = i18next.t("focusChain.clickToEdit")
// Optimized header component with minimal re-renders
const ToDoListHeader = memo<{
@@ -159,6 +161,7 @@ const parseCurrentTodoInfo = (text: string): TodoInfo | null => {
// Main component with aggressive optimization
export const FocusChain: React.FC<FocusChainProps> = memo(
({ currentTaskItemId, lastProgressMessageText, showPlaceholderWhenEmpty }) => {
const { t } = useTranslation("common")
const [isExpanded, setIsExpanded] = useState(false)
// Parse todo info with caching
@@ -194,7 +197,7 @@ export const FocusChain: React.FC<FocusChainProps> = memo(
<span className="rounded-lg px-2 py-0.25 inline-block shrink-0 bg-badge-foreground/20 text-foreground text-sm">
0/0
</span>
<span className="text-sm text-foreground/80 truncate">TODOs</span>
<span className="text-sm text-foreground/80 truncate">{t("focusChain.todos")}</span>
</div>
)
}
@@ -207,7 +210,7 @@ export const FocusChain: React.FC<FocusChainProps> = memo(
return (
<div
aria-label={isExpanded ? "Collapse focus chain" : "Expand focus chain"}
aria-label={isExpanded ? t("focusChain.collapseFocusChain") : t("focusChain.expandFocusChain")}
className="relative rounded-sm bg-toolbar-hover/65 flex flex-col gap-1.5 select-none hover:bg-toolbar-hover overflow-hidden opacity-80 hover:opacity-100 transition-[transform,box-shadow] duration-200 cursor-pointer"
onClick={handleToggle}
onKeyDown={(e) => {
@@ -1,5 +1,6 @@
import { ClineMessage } from "@shared/ExtensionMessage"
import React, { memo, useCallback } from "react"
import { useTranslation } from "react-i18next"
import { cn } from "@/lib/utils"
import { highlightText } from "./Highlights"
@@ -15,6 +16,8 @@ interface StickyUserMessageProps {
*/
export const StickyUserMessage: React.FC<StickyUserMessageProps> = memo(
({ lastUserMessage, onScrollToMessage, isVisible }) => {
const { t } = useTranslation("common")
const handleClick = useCallback(() => {
if (onScrollToMessage) {
onScrollToMessage()
@@ -42,7 +45,7 @@ export const StickyUserMessage: React.FC<StickyUserMessageProps> = memo(
return (
<div
aria-label={`Scroll to your message: ${messageText}`}
aria-label={t("stickyUserMessage.scrollToMessage", { text: messageText })}
className={cn(
"relative flex items-center px-2.5 pt-2 pb-2 cursor-pointer select-none",
"backdrop-blur-sm",
@@ -56,7 +59,7 @@ export const StickyUserMessage: React.FC<StickyUserMessageProps> = memo(
borderRadius: "3px",
}}
tabIndex={0}
title="Click to scroll to your message">
title={t("stickyUserMessage.clickToScroll")}>
{/* Message text (truncated via CSS text-ellipsis) */}
<div
className={cn(
@@ -133,7 +133,7 @@ const TaskHeader: React.FC<TaskHeaderProps> = ({
}}>
{/* Task Title */}
<div
aria-label={isTaskExpanded ? "Collapse task header" : "Expand task header"}
aria-label={isTaskExpanded ? t("taskHeader.collapseHeader") : t("taskHeader.expandHeader")}
className="flex justify-between items-center cursor-pointer"
onClick={toggleTaskExpanded}
onKeyDown={(e) => {
@@ -29,13 +29,15 @@ export const getColor = (message: ClineMessage): string => {
toolData.tool === "searchFiles"
) {
return COLOR_BEIGE // Beige for file read operations
} else if (
}
if (
toolData.tool === "editedExistingFile" ||
toolData.tool === "newFileCreated" ||
toolData.tool === "deletedFile"
) {
return COLOR_BLUE // Blue for file edit/create operations
} else if (toolData.tool === "webFetch" || toolData.tool === "webSearch") {
}
if (toolData.tool === "webFetch" || toolData.tool === "webSearch") {
return COLOR_PURPLE // Purple for web fetch/search operations
}
} catch (_e) {
@@ -54,7 +56,8 @@ export const getColor = (message: ClineMessage): string => {
default:
return COLOR_DARK_GRAY // Dark gray for unknown
}
} else if (message.type === "ask") {
}
if (message.type === "ask") {
switch (message.ask) {
case "followup":
return COLOR_GRAY // Gray for user messages
@@ -73,13 +76,15 @@ export const getColor = (message: ClineMessage): string => {
toolData.tool === "searchFiles"
) {
return COLOR_BEIGE // Beige for file read operations
} else if (
}
if (
toolData.tool === "editedExistingFile" ||
toolData.tool === "newFileCreated" ||
toolData.tool === "deletedFile"
) {
return COLOR_BLUE // Blue for file edit/create operations
} else if (toolData.tool === "webFetch" || toolData.tool === "webSearch") {
}
if (toolData.tool === "webFetch" || toolData.tool === "webSearch") {
return COLOR_PURPLE // Purple for web fetch/search operations
}
} catch (_e) {
@@ -13,6 +13,7 @@ import {
} from "@shared/proto/cline/file"
import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import React, { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useClickAway, useWindowSize } from "react-use"
import styled from "styled-components"
import PopupModalContainer from "@/components/common/PopupModalContainer"
@@ -52,6 +53,7 @@ const ClineRulesToggleModal: React.FC = () => {
setRemoteRulesToggles,
setRemoteWorkflowToggles,
} = useExtensionState()
const { t } = useTranslation("misc")
const [globalHooks, setGlobalHooks] = useState<Array<{ name: string; enabled: boolean; absolutePath: string }>>([])
const [workspaceHooks, setWorkspaceHooks] = useState<
Array<{ workspaceName: string; hooks: Array<{ name: string; enabled: boolean; absolutePath: string }> }>
@@ -437,11 +439,11 @@ const ClineRulesToggleModal: React.FC = () => {
<div className="inline-flex min-w-0 max-w-full items-center" ref={modalRef}>
<div className="inline-flex w-full items-center" ref={buttonRef}>
<Tooltip>
{!isVisible && <TooltipContent>Manage Cline Rules & Workflows</TooltipContent>}
{!isVisible && <TooltipContent>{t("rules.manageRules")}</TooltipContent>}
<TooltipTrigger>
<VSCodeButton
appearance="icon"
aria-label={isVisible ? "Hide Cline Rules & Workflows" : "Show Cline Rules & Workflows"}
aria-label={isVisible ? t("rules.hideRules") : t("rules.showRules")}
className="p-0 m-0 flex items-center"
onClick={() => setIsVisible(!isVisible)}>
<i className="codicon codicon-law" style={{ fontSize: "12.5px" }} />
@@ -470,18 +472,18 @@ const ClineRulesToggleModal: React.FC = () => {
flexWrap: "wrap",
}}>
<TabButton isActive={currentView === "rules"} onClick={() => setCurrentView("rules")}>
Rules
{t("rules.tabs.rules")}
</TabButton>
<TabButton isActive={currentView === "workflows"} onClick={() => setCurrentView("workflows")}>
Workflows
{t("rules.tabs.workflows")}
</TabButton>
{hooksEnabled && (
<TabButton isActive={currentView === "hooks"} onClick={() => setCurrentView("hooks")}>
Hooks
{t("rules.tabs.hooks")}
</TabButton>
)}
<TabButton isActive={currentView === "skills"} onClick={() => setCurrentView("skills")}>
Skills
{t("rules.tabs.skills")}
</TabButton>
</div>
</div>
@@ -491,9 +493,7 @@ const ClineRulesToggleModal: React.FC = () => {
<div className="flex items-center gap-2 px-3 py-3 mb-4 bg-vscode-textBlockQuote-background border-l-[3px] border-vscode-textLink-foreground">
<i className="codicon codicon-lock text-sm" />
<span className="text-base">
{currentView === "rules"
? "Your organization manages some rules"
: "Your organization manages some workflows"}
{currentView === "rules" ? t("rules.orgManagesRules") : t("rules.orgManagesWorkflows")}
</span>
</div>
) : null}
@@ -502,37 +502,33 @@ const ClineRulesToggleModal: React.FC = () => {
<div className="text-xs text-description mb-4">
{currentView === "rules" ? (
<p>
Rules allow you to provide Cline with system-level guidance. Think of them as a persistent way
to include context and preferences for your projects or globally for every conversation.{" "}
{t("rules.rulesDescription")}
<VSCodeLink
className="text-xs"
href="https://docs.cline.bot/features/cline-rules"
style={{ display: "inline", fontSize: "inherit" }}>
Docs
{t("rules.docs")}
</VSCodeLink>
</p>
) : currentView === "workflows" ? (
<p>
Workflows allow you to define a series of steps to guide Cline through a repetitive set of
tasks, such as deploying a service or submitting a PR. To invoke a workflow, type{" "}
<span className="text-foreground font-bold">/workflow-name</span> in the chat.{" "}
{t("rules.workflowsDescription")}
<span className="text-foreground font-bold">/workflow-name</span>
{t("rules.workflowsInvoke")}{" "}
<VSCodeLink
className="text-xs inline"
href="https://docs.cline.bot/features/slash-commands/workflows">
Docs
{t("rules.docs")}
</VSCodeLink>
</p>
) : currentView === "skills" ? (
<p>
Skills are reusable instruction sets that Cline can activate on-demand. When a task matches a
skill's description, Cline uses the <span className="font-bold">use_skill</span> tool to load
the full instructions.
{t("rules.skillsDescription")}
<span className="font-bold">use_skill</span>
{t("rules.skillsTool")}
</p>
) : (
<p>
Hooks allow you to execute custom scripts at specific points in Cline's execution lifecycle,
enabling automation and integration with external tools.
</p>
<p>{t("rules.hooksDescription")}</p>
)}
</div>
</div>
@@ -544,7 +540,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Remote Rules Section */}
{hasRemoteRules && (
<div className="mb-3">
<div className="text-sm font-normal mb-2">Enterprise Rules</div>
<div className="text-sm font-normal mb-2">{t("rules.enterpriseRules")}</div>
<div className="flex flex-col gap-0">
{remoteGlobalRules.map((rule) => {
const enabled = rule.alwaysEnabled || remoteRulesToggles[rule.name] === true
@@ -567,7 +563,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Global Rules Section */}
<div className="mb-3">
<div className="text-sm font-normal mb-2">Global Rules</div>
<div className="text-sm font-normal mb-2">{t("rules.globalRules")}</div>
{/* File-based Global Rules */}
<RulesToggleList
@@ -583,7 +579,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Local Rules Section */}
<div className="-mb-2.5">
<div className="text-sm font-normal mb-2">Workspace Rules</div>
<div className="text-sm font-normal mb-2">{t("rules.workspaceRules")}</div>
<RulesToggleList
isGlobal={false}
listGap="small"
@@ -628,7 +624,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Remote Workflows Section */}
{hasRemoteWorkflows && (
<div className="mb-3">
<div className="text-sm font-normal mb-2">Enterprise Workflows</div>
<div className="text-sm font-normal mb-2">{t("rules.enterpriseWorkflows")}</div>
<div className="flex flex-col gap-0">
{remoteGlobalWorkflows.map((workflow) => {
const enabled =
@@ -652,7 +648,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Global Workflows Section */}
<div className="mb-3">
<div className="text-sm font-normal mb-2">Global Workflows</div>
<div className="text-sm font-normal mb-2">{t("rules.globalWorkflows")}</div>
{/* File-based Global Workflows */}
<RulesToggleList
@@ -668,7 +664,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Local Workflows Section */}
<div className="-mb-2.5">
<div className="text-sm font-normal mb-2">Workspace Workflows</div>
<div className="text-sm font-normal mb-2">{t("rules.workspaceWorkflows")}</div>
<RulesToggleList
isGlobal={false}
listGap="small"
@@ -684,14 +680,12 @@ const ClineRulesToggleModal: React.FC = () => {
<>
<div className="text-xs text-description mb-4">
<p>
{isWindows
? "On Windows, hooks execute whenever the hook file exists."
: "Toggle to enable/disable (chmod +x/-x)."}{" "}
{isWindows ? t("rules.hookWindowsToggle") : t("rules.hookUnixToggle")}{" "}
<VSCodeLink
className="text-xs"
href="https://docs.cline.bot/features/hooks"
style={{ display: "inline", fontSize: "inherit" }}>
Docs
{t("rules.docs")}
</VSCodeLink>
</p>
</div>
@@ -700,17 +694,13 @@ const ClineRulesToggleModal: React.FC = () => {
{isWindows && (
<div className="flex items-center gap-2 px-3 py-3 mb-4 bg-vscode-inputValidation-warningBackground border-l-[3px] border-vscode-inputValidation-warningBorder">
<i className="codicon codicon-warning text-sm" />
<span className="text-base">
Hook toggling is not yet supported on Windows in this foundation PR. Hooks can be
created, edited, and deleted, and execute whenever the hook file exists. Coming next:
JSON-backed hook enabled/disabled state across platforms.
</span>
<span className="text-base">{t("rules.hookWindowsWarning")}</span>
</div>
)}
{/* Global Hooks */}
<div className="mb-3">
<div className="text-sm font-normal mb-2">Global Hooks</div>
<div className="text-sm font-normal mb-2">{t("rules.globalHooks")}</div>
<div className="flex flex-col gap-0">
{globalHooks
.sort((a, b) => a.name.localeCompare(b.name))
@@ -785,7 +775,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Enterprise Skills Section (remote) */}
{globalSkills.some((s) => s.path.startsWith("remote:")) && (
<div className="mb-3">
<div className="text-sm font-normal mb-2">Enterprise Skills</div>
<div className="text-sm font-normal mb-2">{t("rules.enterpriseSkills")}</div>
<div className="flex flex-col gap-0">
{globalSkills
.filter((s) => s.path.startsWith("remote:"))
@@ -808,7 +798,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Global Skills Section */}
<div className="mb-3">
<div className="text-sm font-normal mb-2">Global Skills</div>
<div className="text-sm font-normal mb-2">{t("rules.globalSkills")}</div>
<div className="flex flex-col gap-0">
{globalSkills
.filter((s) => !s.path.startsWith("remote:"))
@@ -829,7 +819,7 @@ const ClineRulesToggleModal: React.FC = () => {
{/* Workspace Skills Section */}
<div className="-mb-2.5">
<div className="text-sm font-normal mb-2">Workspace Skills</div>
<div className="text-sm font-normal mb-2">{t("rules.workspaceSkills")}</div>
<div className="flex flex-col gap-0">
{localSkills
.sort((a, b) => a.name.localeCompare(b.name))
@@ -1,6 +1,7 @@
import { StringRequest } from "@shared/proto/cline/common"
import { DeleteHookRequest, HooksToggles } from "@shared/proto/cline/file"
import { PenIcon, Trash2Icon } from "lucide-react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { FileServiceClient } from "@/services/grpc-client"
@@ -26,6 +27,8 @@ const HookRow: React.FC<HookRowProps> = ({
onToggle,
onDelete,
}) => {
const { t } = useTranslation("misc")
const handleEditClick = () => {
FileServiceClient.openFile(StringRequest.create({ value: absolutePath })).catch((err) =>
console.error("Failed to open file:", err),
@@ -57,12 +60,7 @@ const HookRow: React.FC<HookRowProps> = ({
{/* Toggle Switch */}
<div className="flex items-center space-x-2 gap-2">
<div
title={
isWindows
? "Hook toggling is not yet supported on Windows in this foundation PR. Hooks execute when the hook file exists."
: undefined
}>
<div title={isWindows ? t("rules.hookTogglingNotSupported") : undefined}>
<Switch
checked={enabled}
className="mx-1"
@@ -72,14 +70,19 @@ const HookRow: React.FC<HookRowProps> = ({
style={isWindows ? { opacity: 0.5, cursor: "not-allowed" } : undefined}
/>
</div>
<Button aria-label="Edit hook file" onClick={handleEditClick} size="xs" title="Edit hook file" variant="icon">
<Button
aria-label={t("rules.editHookFile")}
onClick={handleEditClick}
size="xs"
title={t("rules.editHookFile")}
variant="icon">
<PenIcon />
</Button>
<Button
aria-label="Delete hook file"
aria-label={t("rules.deleteHookFile")}
onClick={handleDeleteClick}
size="xs"
title="Delete hook file"
title={t("rules.deleteHookFile")}
variant="icon">
<Trash2Icon />
</Button>
@@ -1,6 +1,7 @@
import { CreateHookRequest, CreateSkillRequest, RuleFileRequest } from "@shared/proto/index.cline"
import { PlusIcon } from "lucide-react"
import { useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useClickAway } from "react-use"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
@@ -14,17 +15,18 @@ interface NewRuleRowProps {
}
const HOOK_TYPES = [
{ name: "TaskStart", description: "Executes when a new task begins" },
{ name: "TaskResume", description: "Executes when a task is resumed" },
{ name: "TaskCancel", description: "Executes when a task is cancelled" },
{ name: "TaskComplete", description: "Executes when a task completes" },
{ name: "PreToolUse", description: "Executes before any tool is used" },
{ name: "PostToolUse", description: "Executes after any tool is used" },
{ name: "UserPromptSubmit", description: "Executes when user submits a prompt" },
{ name: "PreCompact", description: "Executes before conversation compaction" },
{ name: "TaskStart", descriptionKey: "rules.hookTypes.taskStart" },
{ name: "TaskResume", descriptionKey: "rules.hookTypes.taskResume" },
{ name: "TaskCancel", descriptionKey: "rules.hookTypes.taskCancel" },
{ name: "TaskComplete", descriptionKey: "rules.hookTypes.taskComplete" },
{ name: "PreToolUse", descriptionKey: "rules.hookTypes.preToolUse" },
{ name: "PostToolUse", descriptionKey: "rules.hookTypes.postToolUse" },
{ name: "UserPromptSubmit", descriptionKey: "rules.hookTypes.userPromptSubmit" },
{ name: "PreCompact", descriptionKey: "rules.hookTypes.preCompact" },
]
const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHooks = [], workspaceName }) => {
const { t } = useTranslation("misc")
const [isExpanded, setIsExpanded] = useState(false)
const [filename, setFilename] = useState("")
const inputRef = useRef<HTMLInputElement>(null)
@@ -88,7 +90,7 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
if (ruleType === "skill") {
// Validate skill name - only allow alphanumeric, dashes, underscores
if (!/^[a-zA-Z0-9_-]+$/.test(trimmedFilename)) {
setError("Skill name can only contain letters, numbers, dashes, and underscores")
setError(t("rules.newRule.skillNameInvalid"))
return
}
@@ -111,7 +113,7 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
const extension = getExtension(trimmedFilename)
if (!isValidExtension(extension)) {
setError("Only .md, .txt, or no file extension allowed")
setError(t("rules.newRule.extensionInvalid"))
return
}
@@ -164,15 +166,14 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
{ruleType === "hook" ? (
<>
<label className="sr-only" htmlFor="hook-type-select">
Select hook type to create
{t("rules.newRule.selectHookType")}
</label>
<span className="sr-only" id="hook-select-description">
Choose a hook type to create. Hooks execute at specific points in Cline's lifecycle. Available:{" "}
{availableHookTypes.map((h) => h.name).join(", ")}
{t("rules.newRule.chooseHookType")} {availableHookTypes.map((h) => h.name).join(", ")}
</span>
<select
aria-describedby="hook-select-description"
aria-label="Select hook type to create"
aria-label={t("rules.newRule.selectHookType")}
className="flex-1 bg-input-background text-input-foreground border-0 outline-0 rounded focus:outline-none focus:ring-0 focus:border-transparent px-2 cursor-pointer"
disabled={availableHookTypes.length === 0}
id="hook-type-select"
@@ -193,10 +194,12 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
}}
value="">
<option disabled value="">
{availableHookTypes.length === 0 ? "All hooks created" : "New hook..."}
{availableHookTypes.length === 0
? t("rules.newRule.allHooksCreated")
: t("rules.newRule.newHook")}
</option>
{availableHookTypes.map((hook) => (
<option key={hook.name} title={hook.description} value={hook.name}>
<option key={hook.name} title={t(hook.descriptionKey)} value={hook.name}>
{hook.name}
</option>
))}
@@ -215,15 +218,15 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
placeholder={
isExpanded
? ruleType === "workflow"
? "workflow-name (.md, .txt, or no extension)"
? t("rules.newRule.workflowPlaceholder")
: ruleType === "skill"
? "skill-name (letters, numbers, dashes, underscores)"
: "rule-name (.md, .txt, or no extension)"
? t("rules.newRule.skillPlaceholder")
: t("rules.newRule.rulePlaceholder")
: ruleType === "workflow"
? "New workflow file..."
? t("rules.newRule.newWorkflowFile")
: ruleType === "skill"
? "New skill..."
: "New rule file..."
? t("rules.newRule.newSkill")
: t("rules.newRule.newRuleFile")
}
ref={inputRef}
type="text"
@@ -234,13 +237,13 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
aria-label={
isExpanded
? ruleType === "skill"
? "Create skill"
: "Create file"
? t("rules.newRule.createSkill")
: t("rules.newRule.createFile")
: ruleType === "workflow"
? "New workflow file..."
? t("rules.newRule.newWorkflowFile")
: ruleType === "skill"
? "New skill..."
: "New rule file..."
? t("rules.newRule.newSkill")
: t("rules.newRule.newRuleFile")
}
className="mx-0.5"
onClick={(e) => {
@@ -250,7 +253,13 @@ const NewRuleRow: React.FC<NewRuleRowProps> = ({ isGlobal, ruleType, existingHoo
}
}}
size="icon"
title={isExpanded ? (ruleType === "skill" ? "Create skill" : "Create file") : "New file"}
title={
isExpanded
? ruleType === "skill"
? t("rules.newRule.createSkill")
: t("rules.newRule.createFile")
: t("rules.newRule.newFile")
}
type={isExpanded ? "submit" : "button"}
variant="icon">
<PlusIcon />
@@ -2,6 +2,7 @@ import { StringRequest } from "@shared/proto/cline/common"
import { DeleteSkillRequest, RuleFileRequest } from "@shared/proto/index.cline"
import { REMOTE_URI_SCHEME } from "@shared/remote-config/constants"
import { EyeIcon, InfoIcon, PenIcon, Trash2Icon } from "lucide-react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
@@ -38,6 +39,7 @@ const RuleRow: React.FC<{
alwaysEnabled?: boolean
onDeleteSkill?: () => void
}> = ({ rulePath, enabled, isGlobal, toggleRule, ruleType, isRemote = false, alwaysEnabled = false, onDeleteSkill }) => {
const { t } = useTranslation("misc")
const displayName = getDisplayNameFromPath(rulePath)
const skillDisplayName = getSkillDisplayNameFromSkillMdPath(rulePath)
@@ -146,9 +148,7 @@ const RuleRow: React.FC<{
<TooltipTrigger asChild className="cursor-help">
<InfoIcon className="ml-1.5 opacity-70 size-[0.85rem]" />
</TooltipTrigger>
<TooltipContent>
Searches recursively for all AGENTS.md files in the workspace when a top-level AGENTS.md exists
</TooltipContent>
<TooltipContent>{t("rules.ruleRow.agentsTooltip")}</TooltipContent>
</Tooltip>
)}
</span>
@@ -161,22 +161,30 @@ const RuleRow: React.FC<{
disabled={isDisabled}
key={rulePath}
onClick={() => toggleRule(rulePath, !enabled)}
title={isDisabled ? "This rule is required and cannot be disabled" : undefined}
title={isDisabled ? t("rules.ruleRow.ruleRequired") : undefined}
/>
<Button
aria-label={isRemote ? `View ${ruleType} file` : `Edit ${ruleType} file`}
aria-label={
isRemote
? t("rules.ruleRow.viewFile", { type: ruleType })
: t("rules.ruleRow.editFile", { type: ruleType })
}
onClick={handleEditClick}
size="xs"
title={isRemote ? `View ${ruleType} file (read-only)` : `Edit ${ruleType} file`}
title={
isRemote
? t("rules.ruleRow.viewFileReadonly", { type: ruleType })
: t("rules.ruleRow.editFile", { type: ruleType })
}
variant="icon">
{isRemote ? <EyeIcon /> : <PenIcon />}
</Button>
<Button
aria-label={`Delete ${ruleType} file`}
aria-label={t("rules.ruleRow.deleteFile", { type: ruleType })}
disabled={isRemote}
onClick={handleDeleteClick}
size="xs"
title={`Delete ${ruleType} file`}
title={t("rules.ruleRow.deleteFile", { type: ruleType })}
variant="icon">
<Trash2Icon />
</Button>
@@ -1,3 +1,4 @@
import { useTranslation } from "react-i18next"
import NewRuleRow from "./NewRuleRow"
import RuleRow from "./RuleRow"
@@ -22,6 +23,8 @@ const RulesToggleList = ({
isRemote?: boolean
alwaysEnabledMap?: Record<string, boolean>
}) => {
const { t } = useTranslation("misc")
const gapClasses = {
small: "gap-0",
medium: "gap-2.5",
@@ -52,7 +55,7 @@ const RulesToggleList = ({
<>
{showNoRules && (
<div className="flex flex-col items-center gap-3 my-3 text-(--vscode-descriptionForeground)">
{ruleType === "workflow" ? "No workflows found" : "No rules found"}
{ruleType === "workflow" ? t("rules.noWorkflowsFound") : t("rules.noRulesFound")}
</div>
)}
{showNewRule && <NewRuleRow isGlobal={isGlobal} ruleType={ruleType} />}
@@ -1,6 +1,7 @@
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { AlertTriangle } from "lucide-react"
import React, { ReactNode } from "react"
import { useTranslation } from "react-i18next"
import { OPENROUTER_MODEL_PICKER_Z_INDEX } from "../settings/OpenRouterModelPicker"
interface AlertDialogProps {
@@ -79,10 +80,10 @@ export function UnsavedChangesDialog({
onConfirm,
onCancel,
onSave,
title = "Unsaved Changes",
description = "You have unsaved changes. Are you sure you want to discard them?",
confirmText = "Discard Changes",
saveText = "Save & Continue",
title,
description,
confirmText,
saveText,
showSaveOption = false,
}: {
open: boolean
@@ -96,21 +97,26 @@ export function UnsavedChangesDialog({
saveText?: string
showSaveOption?: boolean
}) {
const { t } = useTranslation("misc")
const resolvedTitle = title ?? t("common.alert.unsavedTitle")
const resolvedDescription = description ?? t("common.alert.unsavedDescription")
const resolvedConfirmText = confirmText ?? t("common.alert.discardChanges")
const resolvedSaveText = saveText ?? t("common.alert.saveAndContinue")
return (
<AlertDialog onOpenChange={onOpenChange} open={open}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
<AlertTriangle className="w-5 h-5 text-(--vscode-errorForeground)" />
{title}
{resolvedTitle}
</AlertDialogTitle>
<AlertDialogDescription>{description}</AlertDialogDescription>
<AlertDialogDescription>{resolvedDescription}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={onCancel}>Cancel</AlertDialogCancel>
{showSaveOption && onSave && <AlertDialogAction onClick={onSave}>{saveText}</AlertDialogAction>}
<AlertDialogCancel onClick={onCancel}>{t("common.alert.cancel")}</AlertDialogCancel>
{showSaveOption && onSave && <AlertDialogAction onClick={onSave}>{resolvedSaveText}</AlertDialogAction>}
<AlertDialogAction appearance={showSaveOption ? "secondary" : "primary"} onClick={onConfirm}>
{confirmText}
{resolvedConfirmText}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
@@ -1,5 +1,6 @@
import { ChevronLeft, ChevronRight, XIcon } from "lucide-react"
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useRemark } from "react-remark"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
@@ -76,6 +77,7 @@ const BannerCardContent: React.FC<BannerCardContentProps> = ({ banner, isActive,
}
export const BannerCarousel: React.FC<BannerCarouselProps> = ({ banners }) => {
const { t } = useTranslation("misc")
const [currentIndex, setCurrentIndex] = useState(0)
const [isPaused, setIsPaused] = useState(false)
const [isTransitioning, setIsTransitioning] = useState(false)
@@ -149,7 +151,7 @@ export const BannerCarousel: React.FC<BannerCarouselProps> = ({ banners }) => {
return (
<div
aria-label="Announcements"
aria-label={t("common.banner.announcements")}
aria-live="polite"
aria-roledescription="carousel"
className="mx-3 mb-3"
@@ -161,7 +163,7 @@ export const BannerCarousel: React.FC<BannerCarouselProps> = ({ banners }) => {
{/* Dismiss button - shows on each card that has onDismiss defined */}
{showDismissButton && (
<Button
aria-label="Dismiss banner"
aria-label={t("common.banner.dismissBanner")}
className="absolute top-2.5 right-2 z-10"
data-testid="banner-dismiss-button"
onClick={(e) => {
@@ -203,10 +205,14 @@ export const BannerCarousel: React.FC<BannerCarouselProps> = ({ banners }) => {
{/* Navigation arrows */}
<div className="flex gap-0.5">
<Button aria-label="Previous banner" onClick={handlePrevious} size="icon" variant="icon">
<Button
aria-label={t("common.banner.previousBanner")}
onClick={handlePrevious}
size="icon"
variant="icon">
<ChevronLeft className="size-4" />
</Button>
<Button aria-label="Next banner" onClick={handleNext} size="icon" variant="icon">
<Button aria-label={t("common.banner.nextBanner")} onClick={handleNext} size="icon" variant="icon">
<ChevronRight className="size-4" />
</Button>
</div>
@@ -5,6 +5,7 @@ import { ClineCheckpointRestore } from "@shared/WebviewMessage"
import { BookmarkIcon } from "lucide-react"
import { useCallback, useEffect, useRef, useState } from "react"
import { createPortal } from "react-dom"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
import { Button } from "@/components/ui/button"
@@ -18,6 +19,7 @@ interface CheckmarkControlProps {
}
export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: CheckmarkControlProps) => {
const { t } = useTranslation("misc")
const [compareDisabled, setCompareDisabled] = useState(false)
const [restoreTaskDisabled, setRestoreTaskDisabled] = useState(false)
const [restoreWorkspaceDisabled, setRestoreWorkspaceDisabled] = useState(false)
@@ -183,7 +185,7 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar
className={cn("text-[9px] text-description shrink-0", {
"text-link": isCheckpointCheckedOut,
})}>
{isCheckpointCheckedOut ? "Checkpoint (restored)" : "Checkpoint"}
{isCheckpointCheckedOut ? t("common.checkpoint.checkpointRestored") : t("common.checkpoint.checkpoint")}
</span>
<DottedLine $isCheckedOut={isCheckpointCheckedOut} />
<ButtonGroup>
@@ -205,7 +207,7 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar
}
}}
style={{ cursor: compareDisabled ? "wait" : "pointer" }}>
Compare
{t("common.checkpoint.compare")}
</CustomButton>
<DottedLine $isCheckedOut={isCheckpointCheckedOut} small />
<div ref={refs.setReference} style={{ position: "relative", marginTop: -2 }}>
@@ -213,7 +215,7 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar
$isCheckedOut={isCheckpointCheckedOut}
isActive={showRestoreConfirm}
onClick={() => setShowRestoreConfirm(true)}>
Restore
{t("common.checkpoint.restore")}
</CustomButton>
{showRestoreConfirm &&
createPortal(
@@ -231,13 +233,13 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar
cursor: restoreBothDisabled ? "wait" : "pointer",
}}>
<i className="codicon codicon-debug-restart" style={{ marginRight: "6px" }} />
Restore Files & Task
{t("common.checkpoint.restoreFilesAndTask")}
</Button>
<p>Revert files and clear messages after this point</p>
<p>{t("common.checkpoint.restoreFilesAndTaskDesc")}</p>
</PrimaryRestoreOption>
<MoreOptionsToggle onClick={() => setShowMoreOptions(!showMoreOptions)}>
More options
{t("common.checkpoint.moreOptions")}
<i
className={`codicon codicon-chevron-${showMoreOptions ? "up" : "down"}`}
style={{ marginLeft: "4px", fontSize: "10px" }}
@@ -262,9 +264,9 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar
className="codicon codicon-file-symlink-directory"
style={{ marginRight: "6px" }}
/>
Restore Files Only
{t("common.checkpoint.restoreFilesOnly")}
</Button>
<p>Revert files to this checkpoint</p>
<p>{t("common.checkpoint.restoreFilesOnlyDesc")}</p>
</RestoreOption>
<RestoreOption>
<Button
@@ -278,9 +280,9 @@ export const CheckmarkControl = ({ messageTs, isCheckpointCheckedOut }: Checkmar
className="codicon codicon-comment-discussion"
style={{ marginRight: "6px" }}
/>
Restore Task Only
{t("common.checkpoint.restoreTaskOnlyAlt")}
</Button>
<p>Clear messages after this point</p>
<p>{t("common.checkpoint.restoreTaskOnlyAltDesc")}</p>
</RestoreOption>
</AdditionalOptions>
)}
@@ -2,6 +2,7 @@ import { CheckpointRestoreRequest } from "@shared/proto/cline/checkpoints"
import { Int64Request } from "@shared/proto/cline/common"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useClickAway } from "react-use"
import styled from "styled-components"
import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
@@ -13,6 +14,7 @@ interface CheckpointOverlayProps {
}
export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => {
const { t } = useTranslation("misc")
const [compareDisabled, setCompareDisabled] = useState(false)
const [restoreTaskDisabled, setRestoreTaskDisabled] = useState(false)
const [restoreWorkspaceDisabled, setRestoreWorkspaceDisabled] = useState(false)
@@ -138,7 +140,7 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => {
}
}}
style={{ cursor: compareDisabled ? "wait" : "pointer" }}
title="Compare">
title={t("common.checkpoint.compare")}>
<i className="codicon codicon-diff-multiple" style={{ position: "absolute" }} />
</VSCodeButton>
<div ref={containerRef} style={{ position: "relative" }}>
@@ -146,7 +148,7 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => {
appearance="secondary"
onClick={() => setShowRestoreConfirm(true)}
style={{ cursor: "pointer" }}
title="Restore">
title={t("common.checkpoint.restore")}>
<i className="codicon codicon-discard" style={{ position: "absolute" }} />
</VSCodeButton>
{showRestoreConfirm && (
@@ -158,9 +160,9 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => {
style={{
cursor: restoreBothDisabled ? "wait" : "pointer",
}}>
Restore Task and Workspace
{t("common.checkpoint.restoreTaskAndWorkspace")}
</VSCodeButton>
<p>Restores the task and your project's files back to a snapshot taken at this point</p>
<p>{t("common.checkpoint.restoreTaskAndWorkspaceDesc")}</p>
</RestoreOption>
<RestoreOption>
<VSCodeButton
@@ -169,9 +171,9 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => {
style={{
cursor: restoreTaskDisabled ? "wait" : "pointer",
}}>
Restore Task Only
{t("common.checkpoint.restoreTaskOnly")}
</VSCodeButton>
<p>Deletes messages after this point (does not affect workspace)</p>
<p>{t("common.checkpoint.restoreTaskOnlyDesc")}</p>
</RestoreOption>
<RestoreOption>
<VSCodeButton
@@ -180,9 +182,9 @@ export const CheckpointOverlay = ({ messageTs }: CheckpointOverlayProps) => {
style={{
cursor: restoreWorkspaceDisabled ? "wait" : "pointer",
}}>
Restore Workspace Only
{t("common.checkpoint.restoreWorkspaceOnly")}
</VSCodeButton>
<p>Restores your project's files to a snapshot taken at this point (task may become out of sync)</p>
<p>{t("common.checkpoint.restoreWorkspaceOnlyDesc")}</p>
</RestoreOption>
</RestoreConfirmTooltip>
)}
@@ -1,5 +1,6 @@
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import { memo, useMemo } from "react"
import { useTranslation } from "react-i18next"
import CodeBlock from "@/components/common/CodeBlock"
import { cn } from "@/lib/utils"
import { getLanguageFromPath } from "@/utils/getLanguageFromPath"
@@ -23,7 +24,7 @@ We need to remove leading non-alphanumeric characters from the path in order for
[^a-zA-Z0-9]+: Matches one or more characters that are not alphanumeric.
The replace method removes these matched characters, effectively trimming the string up to the first alphanumeric character.
*/
export const cleanPathPrefix = (path: string): string => path.replace(/^[^\u4e00-\u9fa5a-zA-Z0-9]+/, "")
export const cleanPathPrefix = (path: string): string => path.replace(/^[^一-龥a-zA-Z0-9]+/, "")
const CodeAccordian = ({
code,
@@ -36,6 +37,7 @@ const CodeAccordian = ({
onToggleExpand,
isLoading,
}: CodeAccordianProps) => {
const { t } = useTranslation("misc")
const inferredLanguage = useMemo(
() => code && (language ?? (path ? getLanguageFromPath(path) : undefined)),
[path, language, code],
@@ -52,7 +54,9 @@ const CodeAccordian = ({
<div className="bg-code overflow-hidden rounded-xs border border-editor-group-border">
{(path || isFeedback || isConsoleLogs) && (
<Button
aria-label={isExpanded ? "Collapse code block" : "Expand code block"}
aria-label={
isExpanded ? t("common.codeAccordian.collapseCodeBlock") : t("common.codeAccordian.expandCodeBlock")
}
className={cn("text-description flex items-center cursor-pointer select-none w-full py-[9px] px-2.5", {
"cursor-wait opacity-70": isLoading,
})}
@@ -72,14 +76,14 @@ const CodeAccordian = ({
<div className="flex items-center">
<span className={`mr-1.5 codicon codicon-${isFeedback ? "feedback" : "output"}`} />
<span className="whitespace-nowrap overflow-hidden text-ellipsis mr-2">
{isFeedback ? "User Edits" : "Console Logs"}
{isFeedback ? t("common.codeAccordian.userEdits") : t("common.codeAccordian.consoleLogs")}
</span>
</div>
) : (
<span className="whitespace-nowrap overflow-hidden text-ellipsis mr-2 [direction: rtl] text-left">
{path?.startsWith(".") && <span>.</span>}
{path && !path.startsWith(".") && <span>/</span>}
{cleanPathPrefix(path ?? "") + "\u200E"}
{cleanPathPrefix(path ?? "") + "‎"}
</span>
)}
<div className="grow" />
@@ -1,5 +1,6 @@
import { CheckCheckIcon, CopyIcon } from "lucide-react"
import { forwardRef, useCallback, useState } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { cn } from "@/lib/utils"
@@ -33,6 +34,7 @@ const POSITION_CLASSES = {
* Base copy button component with clipboard functionality
*/
export const CopyButton: React.FC<CopyButtonProps> = ({ textToCopy, onCopy, className, ariaLabel }) => {
const { t } = useTranslation("misc")
const [copied, setCopied] = useState(false)
const handleCopy = useCallback(() => {
@@ -52,7 +54,7 @@ export const CopyButton: React.FC<CopyButtonProps> = ({ textToCopy, onCopy, clas
return (
<Button
aria-label={copied ? "Copied" : ariaLabel || "Copy"}
aria-label={copied ? t("common.copyButton.copied") : ariaLabel || t("common.copyButton.copy")}
className={cn("scale-90", className)}
onClick={handleCopy}
size="icon"
+20 -18
View File
@@ -19,33 +19,35 @@ import {
VSCodeTextArea,
VSCodeTextField,
} from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
function Demo() {
const { t } = useTranslation("misc")
const rowData = [
{
cell1: "Cell Data",
cell2: "Cell Data",
cell3: "Cell Data",
cell4: "Cell Data",
cell1: t("demo.cellData"),
cell2: t("demo.cellData"),
cell3: t("demo.cellData"),
cell4: t("demo.cellData"),
},
{
cell1: "Cell Data",
cell2: "Cell Data",
cell3: "Cell Data",
cell4: "Cell Data",
cell1: t("demo.cellData"),
cell2: t("demo.cellData"),
cell3: t("demo.cellData"),
cell4: t("demo.cellData"),
},
{
cell1: "Cell Data",
cell2: "Cell Data",
cell3: "Cell Data",
cell4: "Cell Data",
cell1: t("demo.cellData"),
cell2: t("demo.cellData"),
cell3: t("demo.cellData"),
cell4: t("demo.cellData"),
},
]
return (
<main>
<h1>Hello World!</h1>
<VSCodeButton>Howdy!</VSCodeButton>
<h1>{t("demo.helloWorld")}</h1>
<VSCodeButton>{t("demo.howdy")}</VSCodeButton>
<div className="grid gap-3 p-2 place-items-start">
<VSCodeDataGrid>
@@ -76,17 +78,17 @@ function Demo() {
<VSCodeTextField>
<section slot="end" style={{ display: "flex", alignItems: "center" }}>
<VSCodeButton appearance="icon" aria-label="Match Case">
<span className="codicon codicon-case-sensitive"></span>
<span className="codicon codicon-case-sensitive" />
</VSCodeButton>
<VSCodeButton appearance="icon" aria-label="Match Whole Word">
<span className="codicon codicon-whole-word"></span>
<span className="codicon codicon-whole-word" />
</VSCodeButton>
<VSCodeButton appearance="icon" aria-label="Use Regular Expression">
<span className="codicon codicon-regex"></span>
<span className="codicon codicon-regex" />
</VSCodeButton>
</section>
</VSCodeTextField>
<span className="codicon codicon-chevron-right" slot="end"></span>
<span className="codicon codicon-chevron-right" slot="end" />
<span className="flex gap-3">
<VSCodeProgressRing />
@@ -62,11 +62,10 @@ function parseInlineEmphasis(text: string, nextKey: () => string): React.ReactNo
i = endIdx + 2
segmentStart = i
continue
} else {
// unmatched bold opener - treat the first '*' as literal and continue
i = starIdx + 1
continue
}
// unmatched bold opener - treat the first '*' as literal and continue
i = starIdx + 1
continue
}
// Italic start (*)
@@ -138,18 +137,17 @@ function parseTextToNodes(text: string, compact: boolean): React.ReactNode {
}
}
return <>{flat}</>
} else {
// Block-level lines; keys applied at line level
return (
<React.Fragment>
{lines.map((line) => (
<span key={nextKey()} style={{ display: "block" }}>
{parseInlineEmphasis(line, nextKey)}
</span>
))}
</React.Fragment>
)
}
// Block-level lines; keys applied at line level
return (
<React.Fragment>
{lines.map((line) => (
<span key={nextKey()} style={{ display: "block" }}>
{parseInlineEmphasis(line, nextKey)}
</span>
))}
</React.Fragment>
)
}
const LightMarkdown: React.FC<LightMarkdownProps> = ({ text, compact = false }) => {
@@ -4,6 +4,7 @@ import { SquareArrowOutUpRightIcon } from "lucide-react"
import { marked } from "marked"
import type { ComponentProps } from "react"
import React, { memo, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import ReactMarkdown from "react-markdown"
import rehypeHighlight, { Options } from "rehype-highlight"
import remarkGfm from "remark-gfm"
@@ -118,6 +119,7 @@ MemoizedMarkdown.displayName = "MemoizedMarkdown"
* A component for Act Mode text that contains a clickable toggle and keyboard shortcut hint.
*/
const ActModeHighlight: React.FC = () => {
const { t } = useTranslation("misc")
const { mode } = useExtensionState()
return (
@@ -136,7 +138,7 @@ const ActModeHighlight: React.FC = () => {
)
}
}}
title={mode === "plan" ? "Click to toggle to Act Mode" : "Already in Act Mode"}>
title={mode === "plan" ? t("common.markdownBlock.clickToToggleActMode") : t("common.markdownBlock.alreadyInActMode")}>
<div className="p-1 rounded-md bg-code flex items-center justify-end w-7 border border-input-border">
<div className="rounded-full bg-link w-2 h-2" />
</div>
@@ -312,6 +314,7 @@ const remarkPreventBoldFilenames = () => {
}
const PreWithCopyButton = ({ children, ...preProps }: React.HTMLAttributes<HTMLPreElement>) => {
const { t } = useTranslation("misc")
const preRef = useRef<HTMLPreElement>(null)
const handleCopy = () => {
@@ -328,7 +331,7 @@ const PreWithCopyButton = ({ children, ...preProps }: React.HTMLAttributes<HTMLP
}
return (
<WithCopyButton ariaLabel="Copy code" onCopy={handleCopy} position="top-right">
<WithCopyButton ariaLabel={t("common.markdownBlock.copyCode")} onCopy={handleCopy} position="top-right">
<pre {...preProps} ref={preRef}>
{children}
</pre>
@@ -361,6 +364,7 @@ const remarkMarkPotentialFilePaths = () => {
* Shows the code immediately, then adds the file link icon when confirmed
*/
const InlineCodeWithFileCheck: React.FC<ComponentProps<"code"> & { [key: string]: any }> = (props) => {
const { t } = useTranslation("misc")
const [isFilePath, setIsFilePath] = useState<boolean | null>(null)
const filePath = typeof props.children === "string" ? props.children : String(props.children || "")
const isPotentialFilePath = props["data-potential-file-path"] === "true"
@@ -398,7 +402,7 @@ const InlineCodeWithFileCheck: React.FC<ComponentProps<"code"> & { [key: string]
className="p-0 ml-0.5 leading-none align-middle transition-opacity text-preformat gap-0.5 inline text-left"
onClick={() => FileServiceClient.openFileRelativePath({ value: filePath })}
size="icon"
title={`Open ${filePath} in editor`}
title={t("common.markdownBlock.openInEditor", { path: filePath })}
type="button"
variant="icon">
<code {...props} />
@@ -2,6 +2,7 @@ import { StringRequest } from "@shared/proto/cline/common"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import mermaid from "mermaid"
import { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import { FileServiceClient } from "@/services/grpc-client"
import { useDebounceEffect } from "@/utils/useDebounceEffect"
@@ -81,6 +82,7 @@ interface MermaidBlockProps {
}
export default function MermaidBlock({ code }: MermaidBlockProps) {
const { t } = useTranslation("misc")
const containerRef = useRef<HTMLDivElement>(null)
const [isLoading, setIsLoading] = useState(false)
@@ -154,10 +156,13 @@ export default function MermaidBlock({ code }: MermaidBlockProps) {
return (
<MermaidBlockContainer>
{isLoading && <LoadingMessage>Generating mermaid diagram...</LoadingMessage>}
{isLoading && <LoadingMessage>{t("common.mermaid.generating")}</LoadingMessage>}
<ButtonContainer>
<StyledVSCodeButton aria-label="Copy Code" onClick={handleCopyCode} title="Copy Code">
<span className="codicon codicon-copy"></span>
<StyledVSCodeButton
aria-label={t("common.mermaid.copyCode")}
onClick={handleCopyCode}
title={t("common.mermaid.copyCode")}>
<span className="codicon codicon-copy" />
</StyledVSCodeButton>
</ButtonContainer>
<SvgContainer $isLoading={isLoading} onClick={handleClick} ref={containerRef} />
@@ -1,5 +1,6 @@
import { TelemetrySettingEnum, TelemetrySettingRequest } from "@shared/proto/cline/state"
import { useCallback } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { StateServiceClient } from "@/services/grpc-client"
@@ -8,6 +9,7 @@ const telemetryRequest = TelemetrySettingRequest.create({
})
export const TelemetryBanner: React.FC = () => {
const { t } = useTranslation("misc")
const { navigateToSettings } = useExtensionState()
const handleClose = useCallback(() => {
@@ -21,23 +23,20 @@ export const TelemetryBanner: React.FC = () => {
return (
<div className="bg-banner-background text-banner-foreground px-3 py-2 flex flex-col gap-1 shrink-0 mb-1 relative text-sm m-4">
<h3 className="m-0">Help Improve Cline</h3>
<i>(and access experimental features)</i>
<h3 className="m-0">{t("common.telemetry.title")}</h3>
<i>{t("common.telemetry.subtitle")}</i>
<p className="m-0">{t("common.telemetry.description")}</p>
<p className="m-0">
Cline collects error and usage data to help us fix bugs and improve the extension. No code, prompts, or personal
information is ever sent.
</p>
<p className="m-0">
<span>You can turn this setting off in </span>
<span>{t("common.telemetry.youCanTurnOff")}</span>
<span className="text-link cursor-pointer" onClick={handleOpenSettings}>
settings
{t("common.telemetry.settings")}
</span>
.
</p>
{/* Close button */}
<button
aria-label="Close banner and enable telemetry"
aria-label={t("common.telemetry.closeBannerEnableTelemetry")}
className="absolute top-3 right-3 opacity-70 hover:opacity-100 cursor-pointer border-0 bg-transparent p-0 text-inherit"
onClick={handleClose}
type="button">
@@ -103,7 +103,8 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange,
color: "var(--vscode-foreground)",
fontSize: 10,
fontWeight: "bold",
}}></span>
}}
/>
</div>
)}
</div>
@@ -137,7 +138,8 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange,
style={{
fontSize: 16,
color: "var(--vscode-foreground)",
}}></span>
}}
/>
<span
style={{
fontSize: 7,
@@ -174,7 +176,8 @@ const Thumbnails = ({ images, files, style, setImages, setFiles, onHeightChange,
color: "var(--vscode-foreground)",
fontSize: 10,
fontWeight: "bold",
}}></span>
}}
/>
</div>
)}
</div>
@@ -1,10 +1,12 @@
import type { ComponentProps } from "react"
import React, { useState } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
type UnsafeImageProps = ComponentProps<"img">
const UnsafeImage: React.FC<UnsafeImageProps> = ({ src = "", alt = "", ...imgProps }) => {
const { t } = useTranslation("misc")
const [approvedSrc, setApprovedSrc] = useState<string>()
const isApproved = approvedSrc === src
@@ -16,18 +18,20 @@ const UnsafeImage: React.FC<UnsafeImageProps> = ({ src = "", alt = "", ...imgPro
if (!isApproved && !src.startsWith("data:")) {
return (
<span className="my-2 block flex flex-col rounded-md border border-input-border bg-code p-3">
<span className="block m-0 text-sm font-medium">External image blocked pending consent</span>
<span className="block m-0 text-sm font-medium">{t("common.unsafeImage.blocked")}</span>
<span className="block mt-2 mb-0 break-all text-xs text-muted-foreground">
Source: <code>{src}</code>
{t("common.unsafeImage.source")}
<code>{src}</code>
{alt && (
<>
<br />
Alt: <code>{alt}</code>
{t("common.unsafeImage.alt")}
<code>{alt}</code>
</>
)}
</span>
<Button className="mt-3" onClick={() => setApprovedSrc(src)} type="button" variant="outline">
Load image
{t("common.unsafeImage.loadImage")}
</Button>
</span>
)
@@ -1,3 +1,4 @@
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { getEnvironmentColor } from "@/utils/environmentColors"
import type { Environment } from "../../../../src/shared/config-types"
@@ -17,6 +18,7 @@ type ViewHeaderProps = {
}
const ViewHeader = ({ title, onDone, showEnvironmentSuffix, environment }: ViewHeaderProps) => {
const { t } = useTranslation("misc")
const showSubtext = showEnvironmentSuffix && environment && environment !== "production"
const capitalizedEnv = environment ? ENV_DISPLAY_NAMES[environment] : ""
const titleColor = getEnvironmentColor(environment)
@@ -29,12 +31,12 @@ const ViewHeader = ({ title, onDone, showEnvironmentSuffix, environment }: ViewH
</h3>
{showSubtext && (
<span className="absolute left-0 top-8 -translate-y-1 text-xs text-description whitespace-nowrap">
{capitalizedEnv} environment
{t("common.viewHeader.environment", { env: capitalizedEnv })}
</span>
)}
</div>
<Button size="header" onClick={onDone}>
Done
<Button onClick={onDone} size="header">
{t("common.viewHeader.done")}
</Button>
</div>
)
@@ -1,5 +1,6 @@
import { BannerAction, BannerCardData } from "@shared/cline/banner"
import React from "react"
import { useTranslation } from "react-i18next"
import { useMount } from "react-use"
import DiscordIcon from "@/assets/DiscordIcon"
import GitHubIcon from "@/assets/GitHubIcon"
@@ -19,6 +20,7 @@ interface WhatsNewModalProps {
}
export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, version, welcomeBanners, onBannerAction }) => {
const { t } = useTranslation("misc")
const { refreshOpenRouterModels } = useExtensionState()
// Get latest model list in case user hits shortcut button to set model
@@ -43,7 +45,7 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
className="text-lg font-semibold mb-3 pr-6"
id="whats-new-title"
style={{ color: "var(--vscode-editor-foreground)" }}>
🎉 New in v{version}
🎉 {t("common.whatsNew.title", { version })}
</h2>
<WhatsNewItems
@@ -59,7 +61,7 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
<div className="flex items-center gap-4">
{/* X/Twitter */}
<a
aria-label="Follow us on X"
aria-label={t("common.whatsNew.followOnX")}
className="text-[var(--vscode-foreground)] hover:text-[var(--vscode-textLink-activeForeground)] transition-colors"
href="https://x.com/cline"
rel="noopener noreferrer"
@@ -69,7 +71,7 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
{/* Discord */}
<a
aria-label="Join our Discord"
aria-label={t("common.whatsNew.joinDiscord")}
className="text-[var(--vscode-foreground)] hover:text-[var(--vscode-textLink-activeForeground)] transition-colors"
href="https://discord.gg/cline"
rel="noopener noreferrer"
@@ -79,7 +81,7 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
{/* GitHub */}
<a
aria-label="Star us on GitHub"
aria-label={t("common.whatsNew.starOnGitHub")}
className="text-[var(--vscode-foreground)] hover:text-[var(--vscode-textLink-activeForeground)] transition-colors"
href="https://github.com/cline/cline"
rel="noopener noreferrer"
@@ -89,7 +91,7 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
{/* Reddit */}
<a
aria-label="Join our subreddit"
aria-label={t("common.whatsNew.joinSubreddit")}
className="text-[var(--vscode-foreground)] hover:text-[var(--vscode-textLink-activeForeground)] transition-colors"
href="https://www.reddit.com/r/cline/"
rel="noopener noreferrer"
@@ -99,7 +101,7 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
{/* LinkedIn */}
<a
aria-label="Follow us on LinkedIn"
aria-label={t("common.whatsNew.followOnLinkedIn")}
className="text-[var(--vscode-foreground)] hover:text-[var(--vscode-textLink-activeForeground)] transition-colors"
href="https://www.linkedin.com/company/clinebot/"
rel="noopener noreferrer"
@@ -110,13 +112,13 @@ export const WhatsNewModal: React.FC<WhatsNewModalProps> = ({ open, onClose, ver
{/* GitHub Star CTA */}
<p className="text-sm text-center" style={{ color: "var(--vscode-descriptionForeground)" }}>
Please support Cline by{" "}
{t("common.whatsNew.supportByStarring")}
<a
href="https://github.com/cline/cline"
rel="noopener noreferrer"
style={{ color: "var(--vscode-textLink-foreground)" }}
target="_blank">
starring us on GitHub
{t("common.whatsNew.starringOnGitHub")}
</a>
.
</p>
@@ -118,7 +118,8 @@ const HistoryPreview = ({ showHistoryView }: HistoryPreviewProps) => {
style={{
marginRight: "4px",
transform: "scale(0.9)",
}}></span>
}}
/>
<span
style={{
fontWeight: 500,
@@ -157,9 +157,8 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
setSelectedItems((prev) => {
if (checked) {
return [...prev, itemId]
} else {
return prev.filter((id) => id !== itemId)
}
return prev.filter((id) => id !== itemId)
})
}, [])
@@ -460,7 +459,7 @@ const HistoryView = ({ onDone }: HistoryViewProps) => {
}
// https://gist.github.com/evenfrost/1ba123656ded32fb7a0cd4651efd4db0
export const highlight = (fuseSearchResult: FuseResult<any>[], highlightClassName: string = "history-item-highlight") => {
export const highlight = (fuseSearchResult: FuseResult<any>[], highlightClassName = "history-item-highlight") => {
const set = (obj: Record<string, any>, path: string, value: any) => {
const pathValue = path.split(".")
let i: number
@@ -1,6 +1,7 @@
import { StringRequest } from "@shared/proto/cline/common"
import DOMPurify from "dompurify"
import React from "react"
import { useTranslation } from "react-i18next"
import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary"
import { FileServiceClient, WebServiceClient } from "@/services/grpc-client"
import { checkIfImageUrl, formatUrlForOpening, getSafeHostname } from "./utils/mcpRichUtil"
@@ -9,325 +10,289 @@ interface ImagePreviewProps {
url: string
}
// Use a class component to ensure complete isolation between instances
class ImagePreview extends React.Component<
ImagePreviewProps,
{
loading: boolean
error: string | null
fetchStartTime: number
}
> {
private imgRef = React.createRef<HTMLImageElement>()
private timeoutId: NodeJS.Timeout | null = null
private heartbeatId: NodeJS.Timeout | null = null
// Wrapper component that provides i18n context to the class component
const ImagePreviewInner: React.FC<ImagePreviewProps> = (props) => {
const { t } = useTranslation("misc")
constructor(props: ImagePreviewProps) {
super(props)
this.state = {
loading: true,
error: null,
fetchStartTime: Date.now(),
}
}
// Use a class-like approach with hooks
const [state, setState] = React.useState({
loading: true,
error: null as string | null,
fetchStartTime: Date.now(),
})
const [aspectRatio, setAspectRatio] = React.useState(1)
const imgRef = React.createRef<HTMLImageElement>()
const timeoutRef = React.useRef<NodeJS.Timeout | null>(null)
const heartbeatRef = React.useRef<NodeJS.Timeout | null>(null)
const [elapsedSeconds, setElapsedSeconds] = React.useState(0)
// Track aspect ratio for proper display
private aspectRatio: number = 1
const aspectRatioRef = React.useRef(1)
componentDidMount() {
// Set up a timeout to handle cases where the image never loads or errors
this.timeoutId = setTimeout(() => {
console.log(`Image load timeout for ${this.props.url}`)
if (this.state.loading) {
this.setState({
const cleanup = React.useCallback(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current)
timeoutRef.current = null
}
if (heartbeatRef.current) {
clearInterval(heartbeatRef.current)
heartbeatRef.current = null
}
}, [])
const handleImageLoad = React.useCallback(() => {
setState((prev) => ({ ...prev, loading: false }))
cleanup()
}, [cleanup])
const handleImageError = React.useCallback(() => {
setState({
loading: false,
error: `Failed to load image: ${props.url}`,
})
cleanup()
}, [props.url, cleanup])
const checkContentType = React.useCallback(
(url: string) => {
checkIfImageUrl(url)
.then((isImage) => {
if (isImage) {
loadImage(url)
} else {
handleImageError()
}
})
.catch(() => {
handleImageError()
})
},
[handleImageError],
)
const loadImage = React.useCallback(
(url: string) => {
const isSvg = /\.svg(\?.*)?$/i.test(url)
if (isSvg) {
aspectRatioRef.current = 1
handleImageLoad()
return
}
const testImg = new Image()
testImg.onload = () => {
if (testImg.width > 0 && testImg.height > 0) {
aspectRatioRef.current = testImg.width / testImg.height
}
handleImageLoad()
}
testImg.onerror = () => {
handleImageError()
}
testImg.crossOrigin = "anonymous"
},
[handleImageLoad, handleImageError],
)
React.useEffect(() => {
timeoutRef.current = setTimeout(() => {
if (state.loading) {
setState({
loading: false,
error: `Timeout loading image: ${this.props.url}`,
error: `Timeout loading image: ${props.url}`,
})
}
}, 15000)
// Set up a heartbeat to update the UI with elapsed time
this.heartbeatId = setInterval(() => {
if (this.state.loading) {
this.forceUpdate() // Just update the component to show new elapsed time
heartbeatRef.current = setInterval(() => {
if (state.loading) {
setElapsedSeconds(Math.floor((Date.now() - state.fetchStartTime) / 1000))
}
}, 1000)
// First, check the content type to verify it's actually an image
this.checkContentType(this.props.url)
}
checkContentType(props.url)
// Check if the URL is an image using content type verification
checkContentType(url: string) {
// Always verify content type, even for URLs that look like images by extension
checkIfImageUrl(url)
.then((isImage) => {
if (isImage) {
console.log(`URL is confirmed as image: ${url}`)
this.loadImage(url)
} else {
console.log(`URL is not an image: ${url}`)
this.handleImageError()
}
})
.catch((error) => {
console.log(`Error checking if URL is an image: ${error}`)
// Don't fallback to direct image loading on error
// Instead, report the error so the URL can be handled as a non-image
this.handleImageError()
})
}
// Load the image after content type check or as fallback
loadImage(url: string) {
const isSvg = /\.svg(\?.*)?$/i.test(url)
// For SVG files, we don't need to calculate aspect ratio as they're vector-based
if (isSvg) {
console.log(`SVG image detected, skipping aspect ratio calculation: ${url}`)
// Default aspect ratio for SVGs
this.aspectRatio = 1
this.handleImageLoad()
return
return () => {
cleanup()
}
}, [props.url])
// Create a test image to check if the URL loads and get dimensions
const testImg = new Image()
testImg.onload = () => {
console.log(`Test image loaded successfully: ${url}`)
// Calculate aspect ratio for proper display
if (testImg.width > 0 && testImg.height > 0) {
this.aspectRatio = testImg.width / testImg.height
}
this.handleImageLoad()
}
testImg.onerror = () => {
console.log(`Test image failed to load: ${url}`)
this.handleImageError()
}
// Force CORS mode to be anonymous to avoid CORS issues
testImg.crossOrigin = "anonymous"
}
componentWillUnmount() {
this.cleanup()
}
private cleanup() {
if (this.timeoutId) {
clearTimeout(this.timeoutId)
this.timeoutId = null
}
if (this.heartbeatId) {
clearInterval(this.heartbeatId)
this.heartbeatId = null
}
}
// Handle image load event
handleImageLoad = () => {
console.log(`Image loaded successfully: ${this.props.url}`)
this.setState({ loading: false })
this.cleanup()
}
// Handle image error event
handleImageError = () => {
console.log(`Image failed to load: ${this.props.url}`)
this.setState({
loading: false,
error: `Failed to load image: ${this.props.url}`,
})
this.cleanup()
}
render() {
const { url } = this.props
const { loading, error, fetchStartTime } = this.state
// Calculate elapsed time for loading state
const elapsedSeconds = loading ? Math.floor((Date.now() - fetchStartTime) / 1000) : 0
// Fallback display while loading
if (loading) {
return (
<div
className="image-preview-loading"
style={{
padding: "12px",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
height: "128px",
maxWidth: "512px",
}}>
<div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
<div
className="loading-spinner"
style={{
marginRight: "8px",
width: "16px",
height: "16px",
border: "2px solid rgba(127, 127, 127, 0.3)",
borderTopColor: "var(--vscode-textLink-foreground, #3794ff)",
borderRadius: "50%",
animation: "spin 1s linear infinite",
}}
/>
<style>
{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}
</style>
Loading image from {getSafeHostname(url)}...
</div>
{elapsedSeconds > 3 && (
<div style={{ fontSize: "11px", color: "var(--vscode-descriptionForeground)" }}>
{elapsedSeconds > 60
? `Waiting for ${Math.floor(elapsedSeconds / 60)}m ${elapsedSeconds % 60}s...`
: `Waiting for ${elapsedSeconds}s...`}
</div>
)}
{/* Hidden image that we'll use to detect load/error events */}
{/\.svg(\?.*)?$/i.test(url) ? (
<object
data={DOMPurify.sanitize(url)}
onError={this.handleImageError}
onLoad={this.handleImageLoad}
style={{ display: "none" }}
type="image/svg+xml"
/>
) : (
<img
alt=""
onError={this.handleImageError}
onLoad={this.handleImageLoad}
ref={this.imgRef}
src={DOMPurify.sanitize(url)}
style={{ display: "none" }}
/>
)}
</div>
)
}
// Handle error state
if (error) {
return (
<div
className="image-preview-error"
onClick={async () => {
try {
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(url),
}),
)
} catch (err) {
console.error("Error opening URL in browser:", err)
}
}}
style={{
padding: "12px",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
color: "var(--vscode-errorForeground)",
}}>
<div style={{ fontWeight: "bold" }}>Failed to load image</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(url)}</div>
<div style={{ fontSize: "11px", marginTop: "8px", color: "var(--vscode-textLink-foreground)" }}>
Click to open in browser
</div>
</div>
)
}
// Render the image
if (state.loading) {
const currentElapsed = Math.floor((Date.now() - state.fetchStartTime) / 1000)
return (
<div
className="image-preview"
className="image-preview-loading"
style={{
padding: "12px",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
height: "128px",
maxWidth: "512px",
}}>
<div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
<div
className="loading-spinner"
style={{
marginRight: "8px",
width: "16px",
height: "16px",
border: "2px solid rgba(127, 127, 127, 0.3)",
borderTopColor: "var(--vscode-textLink-foreground, #3794ff)",
borderRadius: "50%",
animation: "spin 1s linear infinite",
}}
/>
<style>
{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}
</style>
{t("mcp.chatDisplay.loadingImage", { host: getSafeHostname(props.url) })}
</div>
{currentElapsed > 3 && (
<div style={{ fontSize: "11px", color: "var(--vscode-descriptionForeground)" }}>
{currentElapsed > 60
? t("mcp.chatDisplay.waitingFor", {
time: `${Math.floor(currentElapsed / 60)}m ${currentElapsed % 60}s`,
})
: t("mcp.chatDisplay.waitingFor", { time: `${currentElapsed}s` })}
</div>
)}
{/* Hidden image that we'll use to detect load/error events */}
{/\.svg(\?.*)?$/i.test(props.url) ? (
<object
data={DOMPurify.sanitize(props.url)}
onError={handleImageError}
onLoad={handleImageLoad}
style={{ display: "none" }}
type="image/svg+xml"
/>
) : (
<img
alt=""
onError={handleImageError}
onLoad={handleImageLoad}
ref={imgRef}
src={DOMPurify.sanitize(props.url)}
style={{ display: "none" }}
/>
)}
</div>
)
}
if (state.error) {
return (
<div
className="image-preview-error"
onClick={async () => {
try {
// For data URIs, open in VS Code editor (like mermaid diagrams)
if (url.startsWith("data:")) {
await FileServiceClient.openImage(StringRequest.create({ value: url }))
} else {
// For regular URLs, open in browser
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(formatUrlForOpening(url)),
}),
)
}
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(props.url),
}),
)
} catch (err) {
console.error("Error opening image:", err)
console.error("Error opening URL in browser:", err)
}
}}
style={{
margin: "10px 0",
maxWidth: "100%",
cursor: "pointer",
padding: "12px",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
color: "var(--vscode-errorForeground)",
}}>
{/\.svg(\?.*)?$/i.test(url) ? (
// Special handling for SVG images
<object
aria-label={`SVG from ${getSafeHostname(url)}`}
data={DOMPurify.sanitize(url)}
style={{
width: "100%",
height: "auto",
borderRadius: "4px",
}}
type="image/svg+xml">
{/* Fallback if object tag fails */}
<img
alt={`SVG from ${getSafeHostname(url)}`}
src={DOMPurify.sanitize(url)}
style={{
width: "100%",
height: "auto",
borderRadius: "4px",
}}
/>
</object>
) : (
<div style={{ fontWeight: "bold" }}>{t("mcp.chatDisplay.failedToLoadImage")}</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(props.url)}</div>
<div style={{ fontSize: "11px", marginTop: "8px", color: "var(--vscode-textLink-foreground)" }}>
{t("mcp.chatDisplay.clickToOpenBrowser")}
</div>
</div>
)
}
// Render the image
return (
<div
className="image-preview"
onClick={async () => {
try {
// For data URIs, open in VS Code editor (like mermaid diagrams)
if (props.url.startsWith("data:")) {
await FileServiceClient.openImage(StringRequest.create({ value: props.url }))
} else {
// For regular URLs, open in browser
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(formatUrlForOpening(props.url)),
}),
)
}
} catch (err) {
console.error("Error opening image:", err)
}
}}
style={{
margin: "10px 0",
maxWidth: "100%",
cursor: "pointer",
}}>
{/\.svg(\?.*)?$/i.test(props.url) ? (
// Special handling for SVG images
<object
aria-label={t("mcp.chatDisplay.svgFrom", { host: getSafeHostname(props.url) })}
data={DOMPurify.sanitize(props.url)}
style={{
width: "100%",
height: "auto",
borderRadius: "4px",
}}
type="image/svg+xml">
{/* Fallback if object tag fails */}
<img
alt={`Image from ${getSafeHostname(url)}`}
loading="eager"
src={DOMPurify.sanitize(url)}
alt={t("mcp.chatDisplay.svgFrom", { host: getSafeHostname(props.url) })}
src={DOMPurify.sanitize(props.url)}
style={{
width: "100%",
height: "auto",
borderRadius: "4px",
}}
/>
)}
</div>
)
}
</object>
) : (
<img
alt={t("mcp.chatDisplay.imageFrom", { host: getSafeHostname(props.url) })}
loading="eager"
src={DOMPurify.sanitize(props.url)}
style={{
width: "100%",
height: "auto",
borderRadius: "4px",
}}
/>
)}
</div>
)
}
// Create a wrapper component that memoizes the ImagePreview to prevent unnecessary re-renders
const MemoizedImagePreview = React.memo(
(props: ImagePreviewProps) => <ImagePreview {...props} />,
(props: ImagePreviewProps) => <ImagePreviewInner {...props} />,
(prevProps, nextProps) => prevProps.url === nextProps.url, // Only re-render if URL changes
)
// Wrap the ImagePreview component with an error boundary
const ImagePreviewWithErrorBoundary: React.FC<ImagePreviewProps> = (props) => {
const { t } = useTranslation("misc")
return (
<ChatErrorBoundary errorTitle="Something went wrong displaying this image">
<ChatErrorBoundary errorTitle={t("mcp.chatDisplay.somethingWrongImage")}>
<MemoizedImagePreview {...props} />
</ChatErrorBoundary>
)
@@ -1,6 +1,7 @@
import { StringRequest } from "@shared/proto/cline/common"
import DOMPurify from "dompurify"
import React from "react"
import { useTranslation } from "react-i18next"
import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary"
import { WebServiceClient } from "@/services/grpc-client"
import { getSafeHostname, normalizeRelativeUrl } from "./utils/mcpRichUtil"
@@ -36,243 +37,142 @@ interface LinkPreviewState {
// Error types for better UI feedback
type ErrorType = "timeout" | "network" | "general" | null
// Use a class component to ensure complete isolation between instances
class LinkPreview extends React.Component<LinkPreviewProps, LinkPreviewState> {
private messageListener: ((event: MessageEvent) => void) | null = null
private timeoutId: NodeJS.Timeout | null = null
private heartbeatId: NodeJS.Timeout | null = null
// Use a function component with hooks instead of class component
const LinkPreview: React.FC<LinkPreviewProps> = ({ url }) => {
const { t } = useTranslation("misc")
const [loading, setLoading] = React.useState(true)
const [error, setError] = React.useState<ErrorType>(null)
const [errorMessage, setErrorMessage] = React.useState<string | null>(null)
const [ogData, setOgData] = React.useState<OpenGraphData | null>(null)
const [hasCompletedFetch, setHasCompletedFetch] = React.useState(false)
const [fetchStartTime, setFetchStartTime] = React.useState(Date.now())
const heartbeatRef = React.useRef<NodeJS.Timeout | null>(null)
constructor(props: LinkPreviewProps) {
super(props)
this.state = {
loading: true,
error: null,
errorMessage: null,
ogData: null,
hasCompletedFetch: false,
fetchStartTime: 0,
const cleanup = React.useCallback(() => {
if (heartbeatRef.current) {
clearInterval(heartbeatRef.current)
heartbeatRef.current = null
}
}
}, [])
componentDidMount() {
// Only fetch if we haven't completed a fetch yet
if (!this.state.hasCompletedFetch) {
this.fetchOpenGraphData()
}
}
React.useEffect(() => {
setFetchStartTime(Date.now())
componentWillUnmount() {
this.cleanup()
}
const fetchOpenGraphData = async () => {
try {
const response = await WebServiceClient.fetchOpenGraphData(
StringRequest.create({
value: url,
}),
)
// Prevent updates if fetch has completed
shouldComponentUpdate(nextProps: LinkPreviewProps, nextState: LinkPreviewState) {
// If URL changes, allow update
if (nextProps.url !== this.props.url) {
return true
}
if (response) {
const data: OpenGraphData = {
title: response.title || undefined,
description: response.description || undefined,
image: response.image || undefined,
url: response.url || undefined,
siteName: response.siteName || undefined,
type: response.type || undefined,
}
// If we've completed a fetch and state hasn't changed, prevent update
if (
this.state.hasCompletedFetch &&
this.state.loading === nextState.loading &&
this.state.error === nextState.error &&
this.state.ogData === nextState.ogData
) {
return false
}
return true
}
private cleanup() {
// Clean up event listeners and timeouts
if (this.messageListener) {
window.removeEventListener("message", this.messageListener)
this.messageListener = null
}
if (this.timeoutId) {
clearTimeout(this.timeoutId)
this.timeoutId = null
}
if (this.heartbeatId) {
clearInterval(this.heartbeatId)
this.heartbeatId = null
}
}
private async fetchOpenGraphData() {
try {
// Record fetch start time
const startTime = Date.now()
this.setState({ fetchStartTime: startTime })
// Use the gRPC client to fetch Open Graph data
const response = await WebServiceClient.fetchOpenGraphData(
StringRequest.create({
value: this.props.url,
}),
)
// Process the response
if (response) {
const ogData: OpenGraphData = {
title: response.title || undefined,
description: response.description || undefined,
image: response.image || undefined,
url: response.url || undefined,
siteName: response.siteName || undefined,
type: response.type || undefined,
setOgData(data)
setLoading(false)
setHasCompletedFetch(true)
} else {
setError("network")
setErrorMessage("Failed to fetch Open Graph data")
setLoading(false)
setHasCompletedFetch(true)
}
this.setState({
ogData,
loading: false,
hasCompletedFetch: true,
})
} else {
this.setState({
error: "network",
errorMessage: "Failed to fetch Open Graph data",
loading: false,
hasCompletedFetch: true,
})
cleanup()
heartbeatRef.current = setInterval(() => {
// Force update for elapsed time display
}, 1000)
} catch (err) {
setError("general")
setErrorMessage(err instanceof Error ? err.message : "Unknown error occurred")
setLoading(false)
setHasCompletedFetch(true)
cleanup()
}
// Clean up the heartbeat interval
// (No message listener is needed with gRPC, unlike the previous message-based approach)
this.cleanup()
// Set up heartbeat for loading indicator
this.heartbeatId = setInterval(() => {
const elapsedSeconds = Math.floor((Date.now() - startTime) / 1000)
if (elapsedSeconds > 0) {
this.forceUpdate() // Just update the component to show new elapsed time
}
}, 1000)
} catch (err) {
this.setState({
error: "general",
errorMessage: err instanceof Error ? err.message : "Unknown error occurred",
loading: false,
hasCompletedFetch: true, // Mark as completed on error
})
this.cleanup()
}
}
render() {
const { url } = this.props
const { loading, error, errorMessage, ogData, fetchStartTime } = this.state
// Calculate elapsed time for loading state
const elapsedSeconds = loading ? Math.floor((Date.now() - fetchStartTime) / 1000) : 0
// Fallback display while loading
if (loading) {
return (
<div
className="link-preview-loading"
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
height: "128px",
maxWidth: "512px",
}}>
<div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
<div
className="loading-spinner"
style={{
marginRight: "8px",
width: "16px",
height: "16px",
border: "2px solid rgba(127, 127, 127, 0.3)",
borderTopColor: "var(--vscode-textLink-foreground, #3794ff)",
borderRadius: "50%",
animation: "spin 1s linear infinite",
}}
/>
<style>
{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}
</style>
Loading preview for {getSafeHostname(url)}...
</div>
{elapsedSeconds > 5 && (
<div style={{ fontSize: "11px", color: "var(--vscode-descriptionForeground)" }}>
{elapsedSeconds > 60
? `Waiting for ${Math.floor(elapsedSeconds / 60)}m ${elapsedSeconds % 60}s...`
: `Waiting for ${elapsedSeconds}s...`}
</div>
)}
</div>
)
}
// Handle different error states with specific messages
if (error) {
let errorDisplay = "Unable to load preview"
fetchOpenGraphData()
if (error === "timeout") {
errorDisplay = "Preview request timed out"
} else if (error === "network") {
errorDisplay = "Network error loading preview"
}
return (
<div
className="link-preview-error"
onClick={async () => {
try {
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(url),
}),
)
} catch (err) {
console.error("Error opening URL in browser:", err)
}
}}
style={{
padding: "12px",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
color: "var(--vscode-errorForeground)",
height: "128px",
maxWidth: "512px",
overflow: "auto",
}}>
<div style={{ fontWeight: "bold" }}>{errorDisplay}</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(url)}</div>
{errorMessage && <div style={{ fontSize: "11px", marginTop: "4px", opacity: 0.8 }}>{errorMessage}</div>}
<div style={{ fontSize: "11px", marginTop: "8px", color: "var(--vscode-textLink-foreground)" }}>
Click to open in browser
</div>
</div>
)
return () => {
cleanup()
}
}, [url])
// Create a fallback object if ogData is null
const data = ogData || {
title: getSafeHostname(url),
description: "No description available",
siteName: getSafeHostname(url),
url: url,
}
// Calculate elapsed time for loading state
const elapsedSeconds = loading ? Math.floor((Date.now() - fetchStartTime) / 1000) : 0
// Render the Open Graph preview
// Fallback display while loading
if (loading) {
return (
<div
className="link-preview"
className="link-preview-loading"
style={{
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
height: "128px",
maxWidth: "512px",
}}>
<div style={{ display: "flex", alignItems: "center", marginBottom: "8px" }}>
<div
className="loading-spinner"
style={{
marginRight: "8px",
width: "16px",
height: "16px",
border: "2px solid rgba(127, 127, 127, 0.3)",
borderTopColor: "var(--vscode-textLink-foreground, #3794ff)",
borderRadius: "50%",
animation: "spin 1s linear infinite",
}}
/>
<style>
{`
@keyframes spin {
to { transform: rotate(360deg); }
}
`}
</style>
{t("mcp.chatDisplay.loadingPreview", { host: getSafeHostname(url) })}
</div>
{elapsedSeconds > 5 && (
<div style={{ fontSize: "11px", color: "var(--vscode-descriptionForeground)" }}>
{elapsedSeconds > 60
? t("mcp.chatDisplay.waitingFor", {
time: `${Math.floor(elapsedSeconds / 60)}m ${elapsedSeconds % 60}s`,
})
: t("mcp.chatDisplay.waitingFor", { time: `${elapsedSeconds}s` })}
</div>
)}
</div>
)
}
// Handle different error states with specific messages
if (error) {
let errorDisplay = t("mcp.chatDisplay.unableToLoad")
if (error === "timeout") {
errorDisplay = t("mcp.chatDisplay.timedOut")
} else if (error === "network") {
errorDisplay = t("mcp.chatDisplay.networkError")
}
return (
<div
className="link-preview-error"
onClick={async () => {
try {
await WebServiceClient.openInBrowser(
@@ -285,113 +185,154 @@ class LinkPreview extends React.Component<LinkPreviewProps, LinkPreviewState> {
}
}}
style={{
display: "flex",
padding: "12px",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
overflow: "hidden",
cursor: "pointer",
color: "var(--vscode-errorForeground)",
height: "128px",
maxWidth: "512px",
overflow: "auto",
}}>
{data.image && (
<div className="link-preview-image" style={{ width: "128px", height: "128px", flexShrink: 0 }}>
<img
alt=""
onError={(e) => {
console.log(`Image could not be loaded: ${data.image}`)
// Hide the broken image
;(e.target as HTMLImageElement).style.display = "none"
}}
onLoad={(e) => {
// Check aspect ratio to determine if we should use contain or cover
const img = e.currentTarget
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
const aspectRatio = img.naturalWidth / img.naturalHeight
// Use contain for extreme aspect ratios (logos), cover for photos
if (aspectRatio > 2.5 || aspectRatio < 0.4) {
img.style.objectFit = "contain"
} else {
img.style.objectFit = "cover"
}
}
}}
src={DOMPurify.sanitize(normalizeRelativeUrl(data.image, url))}
style={{
width: "100%",
height: "100%",
objectFit: "contain", // Use contain for link preview thumbnails to handle logos
objectPosition: "center", // Center the image
}}
/>
</div>
)}
<div
className="link-preview-content"
style={{
flex: 1,
padding: "12px",
display: "flex",
flexDirection: "column",
overflow: "hidden",
height: "100%", // Ensure full height
}}>
{/* Top section with title and URL - top aligned */}
<div className="link-preview-top">
<div
className="link-preview-title"
style={{
fontWeight: "bold",
marginBottom: "4px",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}>
{data.title || "No title"}
</div>
<div
className="link-preview-url"
style={{
fontSize: "12px",
color: "var(--vscode-textLink-foreground, #3794ff)",
marginBottom: "8px", // Increased for better separation
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}>
{data.siteName || getSafeHostname(url)}
</div>
</div>
{/* Description with space-around in the remaining space */}
<div
className="link-preview-description-container"
style={{
flex: 1, // Take up remaining space
display: "flex",
flexDirection: "column",
justifyContent: "space-around", // Space around in the remaining area
}}>
<div
className="link-preview-description"
style={{
fontSize: "12px",
color: "var(--vscode-descriptionForeground, rgba(204, 204, 204, 0.7))",
overflow: "hidden",
display: "-webkit-box",
WebkitLineClamp: 3,
WebkitBoxOrient: "vertical",
textOverflow: "ellipsis",
}}>
{data.description || "No description available"}
</div>
</div>
<div style={{ fontWeight: "bold" }}>{errorDisplay}</div>
<div style={{ fontSize: "12px", marginTop: "4px" }}>{getSafeHostname(url)}</div>
{errorMessage && <div style={{ fontSize: "11px", marginTop: "4px", opacity: 0.8 }}>{errorMessage}</div>}
<div style={{ fontSize: "11px", marginTop: "8px", color: "var(--vscode-textLink-foreground)" }}>
{t("mcp.chatDisplay.clickToOpenBrowser")}
</div>
</div>
)
}
// Create a fallback object if ogData is null
const data = ogData || {
title: getSafeHostname(url),
description: t("mcp.chatDisplay.noDescription"),
siteName: getSafeHostname(url),
url: url,
}
// Render the Open Graph preview
return (
<div
className="link-preview"
onClick={async () => {
try {
await WebServiceClient.openInBrowser(
StringRequest.create({
value: DOMPurify.sanitize(url),
}),
)
} catch (err) {
console.error("Error opening URL in browser:", err)
}
}}
style={{
display: "flex",
border: "1px solid var(--vscode-editorWidget-border, rgba(127, 127, 127, 0.3))",
borderRadius: "4px",
overflow: "hidden",
cursor: "pointer",
height: "128px",
maxWidth: "512px",
}}>
{data.image && (
<div className="link-preview-image" style={{ width: "128px", height: "128px", flexShrink: 0 }}>
<img
alt=""
onError={(e) => {
console.log(`Image could not be loaded: ${data.image}`)
// Hide the broken image
;(e.target as HTMLImageElement).style.display = "none"
}}
onLoad={(e) => {
// Check aspect ratio to determine if we should use contain or cover
const img = e.currentTarget
if (img.naturalWidth > 0 && img.naturalHeight > 0) {
const aspectRatio = img.naturalWidth / img.naturalHeight
// Use contain for extreme aspect ratios (logos), cover for photos
if (aspectRatio > 2.5 || aspectRatio < 0.4) {
img.style.objectFit = "contain"
} else {
img.style.objectFit = "cover"
}
}
}}
src={DOMPurify.sanitize(normalizeRelativeUrl(data.image, url))}
style={{
width: "100%",
height: "100%",
objectFit: "contain", // Use contain for link preview thumbnails to handle logos
objectPosition: "center", // Center the image
}}
/>
</div>
)}
<div
className="link-preview-content"
style={{
flex: 1,
padding: "12px",
display: "flex",
flexDirection: "column",
overflow: "hidden",
height: "100%", // Ensure full height
}}>
{/* Top section with title and URL - top aligned */}
<div className="link-preview-top">
<div
className="link-preview-title"
style={{
fontWeight: "bold",
marginBottom: "4px",
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}>
{data.title || t("mcp.chatDisplay.noTitle")}
</div>
<div
className="link-preview-url"
style={{
fontSize: "12px",
color: "var(--vscode-textLink-foreground, #3794ff)",
marginBottom: "8px", // Increased for better separation
whiteSpace: "nowrap",
overflow: "hidden",
textOverflow: "ellipsis",
}}>
{data.siteName || getSafeHostname(url)}
</div>
</div>
{/* Description with space-around in the remaining space */}
<div
className="link-preview-description-container"
style={{
flex: 1, // Take up remaining space
display: "flex",
flexDirection: "column",
justifyContent: "space-around", // Space around in the remaining area
}}>
<div
className="link-preview-description"
style={{
fontSize: "12px",
color: "var(--vscode-descriptionForeground, rgba(204, 204, 204, 0.7))",
overflow: "hidden",
display: "-webkit-box",
WebkitLineClamp: 3,
WebkitBoxOrient: "vertical",
textOverflow: "ellipsis",
}}>
{data.description || t("mcp.chatDisplay.noDescription")}
</div>
</div>
</div>
</div>
)
}
// Create a wrapper component that memoizes the LinkPreview to prevent unnecessary re-renders
@@ -402,8 +343,9 @@ const MemoizedLinkPreview = React.memo(
// Wrap the LinkPreview component with an error boundary
const LinkPreviewWithErrorBoundary: React.FC<LinkPreviewProps> = (props) => {
const { t } = useTranslation("misc")
return (
<ChatErrorBoundary errorTitle="Something went wrong displaying this link preview">
<ChatErrorBoundary errorTitle={t("mcp.chatDisplay.somethingWrongLink")}>
<MemoizedLinkPreview {...props} />
</ChatErrorBoundary>
)
@@ -1,6 +1,7 @@
import { McpDisplayMode } from "@shared/McpDisplayMode"
import { VSCodeDropdown, VSCodeOption } from "@vscode/webview-ui-toolkit/react"
import React from "react"
import { useTranslation } from "react-i18next"
interface McpDisplayModeDropdownProps {
value: McpDisplayMode
@@ -12,6 +13,8 @@ interface McpDisplayModeDropdownProps {
}
const McpDisplayModeDropdown: React.FC<McpDisplayModeDropdownProps> = ({ value, onChange, id, className, style, onClick }) => {
const { t } = useTranslation("misc")
const handleChange = (e: any) => {
const newMode = e.target.value as McpDisplayMode
onChange(newMode)
@@ -19,9 +22,9 @@ const McpDisplayModeDropdown: React.FC<McpDisplayModeDropdownProps> = ({ value,
return (
<VSCodeDropdown className={className} id={id} onChange={handleChange} onClick={onClick} style={style} value={value}>
<VSCodeOption value="plain">Plain Text</VSCodeOption>
<VSCodeOption value="rich">Rich Display</VSCodeOption>
<VSCodeOption value="markdown">Markdown</VSCodeOption>
<VSCodeOption value="plain">{t("mcp.chatDisplay.plainText")}</VSCodeOption>
<VSCodeOption value="rich">{t("mcp.chatDisplay.richDisplay")}</VSCodeOption>
<VSCodeOption value="markdown">{t("mcp.chatDisplay.markdown")}</VSCodeOption>
</VSCodeDropdown>
)
}
@@ -2,6 +2,7 @@ import { McpDisplayMode } from "@shared/McpDisplayMode"
import { VSCodeProgressRing } from "@vscode/webview-ui-toolkit/react"
import { ChevronDownIcon, ChevronRightIcon } from "lucide-react"
import React, { useCallback, useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import ChatErrorBoundary from "@/components/chat/ChatErrorBoundary"
import { CODE_BLOCK_BG_COLOR } from "@/components/common/CodeBlock"
@@ -77,6 +78,7 @@ interface McpResponseDisplayProps {
}
const McpResponseDisplay: React.FC<McpResponseDisplayProps> = ({ responseText }) => {
const { t } = useTranslation("misc")
const { mcpResponsesCollapsed, mcpDisplayMode } = useExtensionState() // Get setting from context
const [isExpanded, setIsExpanded] = useState(!mcpResponsesCollapsed) // Initialize with context setting
const [isLoading, setIsLoading] = useState(false) // Initial loading state for rich content
@@ -229,7 +231,7 @@ const McpResponseDisplay: React.FC<McpResponseDisplayProps> = ({ responseText })
) : (
<ChevronRightIcon className="header-icon" size={16} />
)}
Response
{t("mcp.chatDisplay.response")}
</div>
<DropdownContainer
style={{ minWidth: isExpanded ? "auto" : "0", visibility: isExpanded ? "visible" : "hidden" }}>
@@ -257,12 +259,12 @@ const McpResponseDisplay: React.FC<McpResponseDisplayProps> = ({ responseText })
) : (
<ChevronRightIcon className="header-icon" size={16} />
)}
Response (Error)
{t("mcp.chatDisplay.responseError")}
</div>
</ResponseHeader>
{isExpanded && (
<div className="response-content">
<div style={{ color: "var(--vscode-errorForeground)" }}>Error parsing response:</div>
<div style={{ color: "var(--vscode-errorForeground)" }}>{t("mcp.chatDisplay.errorParsingResponse")}</div>
<UrlText>{responseText}</UrlText>
</div>
)}
@@ -116,19 +116,19 @@ export const normalizeRelativeUrl = (relativeUrl: string, baseUrl: string): stri
if (relativeUrl.startsWith("//")) {
// Protocol-relative URL
return `${baseUrlObj.protocol}${relativeUrl}`
} else if (relativeUrl.startsWith("/")) {
}
if (relativeUrl.startsWith("/")) {
// Root-relative URL
return `${baseUrlObj.protocol}//${baseUrlObj.host}${relativeUrl}`
} else {
// Path-relative URL
// Get the directory part of the URL
let basePath = baseUrlObj.pathname
if (!basePath.endsWith("/")) {
// If the path doesn't end with a slash, remove the file part
basePath = basePath.substring(0, basePath.lastIndexOf("/") + 1)
}
return `${baseUrlObj.protocol}//${baseUrlObj.host}${basePath}${relativeUrl}`
}
// Path-relative URL
// Get the directory part of the URL
let basePath = baseUrlObj.pathname
if (!basePath.endsWith("/")) {
// If the path doesn't end with a slash, remove the file part
basePath = basePath.substring(0, basePath.lastIndexOf("/") + 1)
}
return `${baseUrlObj.protocol}//${baseUrlObj.host}${basePath}${relativeUrl}`
} catch (error) {
console.log(`Error normalizing relative URL: ${error}`)
return relativeUrl // Return original on error
@@ -215,7 +215,7 @@ export const checkIfImageUrl = async (url: string): Promise<boolean> => {
* @param maxUrls - Maximum number of URLs to extract (default: 50)
* @returns Array of URL matches sorted by position in text
*/
export const extractUrlsFromText = (text: string, maxUrls: number = 50): UrlMatch[] => {
export const extractUrlsFromText = (text: string, maxUrls = 50): UrlMatch[] => {
const matches: UrlMatch[] = []
const urlRegex = /(?:https?:\/\/|data:image)[^\s<>"']+/g
let urlMatch: RegExpExecArray | null
@@ -3,6 +3,7 @@ import { EmptyRequest } from "@shared/proto/cline/common"
import { McpServers } from "@shared/proto/cline/mcp"
import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
@@ -17,6 +18,7 @@ type McpViewProps = {
}
const McpConfigurationView = ({ onDone, initialTab }: McpViewProps) => {
const { t } = useTranslation("misc")
const { remoteConfigSettings, setMcpServers, environment } = useExtensionState()
// Show marketplace by default unless remote config explicitly disables it
const showMarketplace = remoteConfigSettings?.mcpMarketplaceEnabled !== false
@@ -74,7 +76,7 @@ const McpConfigurationView = ({ onDone, initialTab }: McpViewProps) => {
display: "flex",
flexDirection: "column",
}}>
<ViewHeader environment={environment} onDone={onDone} title="MCP Servers" />
<ViewHeader environment={environment} onDone={onDone} title={t("mcp.configuration.title")} />
<div style={{ flex: 1, overflow: "auto" }}>
{/* Tabs container */}
@@ -87,16 +89,16 @@ const McpConfigurationView = ({ onDone, initialTab }: McpViewProps) => {
}}>
{showMarketplace && (
<TabButton isActive={activeTab === "marketplace"} onClick={() => handleTabChange("marketplace")}>
Marketplace
{t("mcp.configuration.marketplace")}
</TabButton>
)}
{showRemoteServers && (
<TabButton isActive={activeTab === "addRemote"} onClick={() => handleTabChange("addRemote")}>
Remote Servers
{t("mcp.configuration.remoteServers")}
</TabButton>
)}
<TabButton isActive={activeTab === "configure"} onClick={() => handleTabChange("configure")}>
Configure
{t("mcp.configuration.configure")}
</TabButton>
</div>
@@ -1,5 +1,6 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import { LINKS } from "@/constants"
import { McpServiceClient } from "@/services/grpc-client"
@@ -9,13 +10,16 @@ type AddLocalServerFormProps = {
}
const AddLocalServerForm = ({}: AddLocalServerFormProps) => {
const { t } = useTranslation("misc")
return (
<FormContainer>
<div className="text-(--vscode-foreground)">
Add a local MCP server by configuring it in <code>cline_mcp_settings.json</code>. You'll need to specify the
server name, command, arguments, and any required environment variables in the JSON configuration. Learn more
{t("mcp.addLocalServer.description")}
<code>{t("mcp.addLocalServer.settingsFileName")}</code>
{t("mcp.addLocalServer.descriptionSuffix")}
<VSCodeLink href={LINKS.DOCUMENTATION.LOCAL_MCP_SERVER_DOCS} style={{ display: "inline" }}>
here.
{t("mcp.addLocalServer.here")}
</VSCodeLink>
</div>
@@ -27,7 +31,7 @@ const AddLocalServerForm = ({}: AddLocalServerFormProps) => {
})
}}
style={{ width: "100%", marginBottom: "5px", marginTop: 8 }}>
Open cline_mcp_settings.json
{t("mcp.addLocalServer.openSettings")}
</VSCodeButton>
</FormContainer>
)
@@ -3,6 +3,7 @@ import { AddRemoteMcpServerRequest, McpServers } from "@shared/proto/cline/mcp"
import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import { VSCodeButton, VSCodeLink, VSCodeRadio, VSCodeRadioGroup, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { LINKS } from "@/constants"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
@@ -10,6 +11,7 @@ import { McpServiceClient } from "@/services/grpc-client"
type TransportType = "streamableHttp" | "sse"
const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) => {
const { t } = useTranslation("misc")
const [serverName, setServerName] = useState("")
const [serverUrl, setServerUrl] = useState("")
const [transportType, setTransportType] = useState<TransportType>("streamableHttp")
@@ -21,19 +23,19 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
e.preventDefault()
if (!serverName.trim()) {
setError("Server name is required")
setError(t("mcp.addRemoteServer.serverNameRequired"))
return
}
if (!serverUrl.trim()) {
setError("Server URL is required")
setError(t("mcp.addRemoteServer.serverUrlRequired"))
return
}
try {
new URL(serverUrl)
} catch (_err) {
setError("Invalid URL format")
setError(t("mcp.addRemoteServer.invalidUrl"))
return
}
@@ -59,16 +61,16 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
onServerAdded()
} catch (error) {
setIsSubmitting(false)
setError(error instanceof Error ? error.message : "Failed to add server")
setError(error instanceof Error ? error.message : t("mcp.addRemoteServer.failedToAdd"))
}
}
return (
<div className="p-4 px-5">
<div className="text-(--vscode-foreground) mb-2">
Add a remote MCP server by providing a name and its URL endpoint. Learn more{" "}
{t("mcp.addRemoteServer.description")}
<VSCodeLink href={LINKS.DOCUMENTATION.REMOTE_MCP_SERVER_DOCS} style={{ display: "inline" }}>
here.
{t("mcp.addRemoteServer.here")}
</VSCodeLink>
</div>
@@ -83,7 +85,7 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
}}
placeholder="mcp-server"
value={serverName}>
Server Name
{t("mcp.addRemoteServer.serverName")}
</VSCodeTextField>
</div>
@@ -97,12 +99,14 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
}}
placeholder="https://example.com/mcp-server"
value={serverUrl}>
Server URL
{t("mcp.addRemoteServer.serverUrl")}
</VSCodeTextField>
</div>
<div className="mb-3">
<label className={`block text-sm font-medium mb-2 ${isSubmitting ? "opacity-50" : ""}`}>Transport Type</label>
<label className={`block text-sm font-medium mb-2 ${isSubmitting ? "opacity-50" : ""}`}>
{t("mcp.addRemoteServer.transportType")}
</label>
<VSCodeRadioGroup
disabled={isSubmitting}
onChange={(e) => {
@@ -111,10 +115,10 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
}}
value={transportType}>
<VSCodeRadio checked={transportType === "streamableHttp"} value="streamableHttp">
Streamable HTTP
{t("mcp.addRemoteServer.streamableHttp")}
</VSCodeRadio>
<VSCodeRadio checked={transportType === "sse"} value="sse">
SSE (Legacy)
{t("mcp.addRemoteServer.sseLegacy")}
</VSCodeRadio>
</VSCodeRadioGroup>
</div>
@@ -122,7 +126,7 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
{error && <div className="mb-3 text-(--vscode-errorForeground)">{error}</div>}
<VSCodeButton className="w-full" disabled={isSubmitting} type="submit">
{isSubmitting ? "Connecting..." : "Add Server"}
{isSubmitting ? t("mcp.addRemoteServer.connecting") : t("mcp.addRemoteServer.addServer")}
</VSCodeButton>
<VSCodeButton
@@ -133,7 +137,7 @@ const AddRemoteServerForm = ({ onServerAdded }: { onServerAdded: () => void }) =
})
}}
style={{ width: "100%", marginBottom: "5px", marginTop: 15 }}>
Edit Configuration
{t("mcp.addRemoteServer.editConfiguration")}
</VSCodeButton>
</form>
</div>
@@ -1,10 +1,12 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { VSCodeButton, VSCodeLink } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
import ServersToggleList from "./ServersToggleList"
const ConfigureServersView = () => {
const { t } = useTranslation("misc")
const { mcpServers: servers, navigateToSettings, remoteConfigSettings } = useExtensionState()
// Check if there are remote MCP servers configured
@@ -19,18 +21,17 @@ const ConfigureServersView = () => {
marginBottom: "16px",
marginTop: "5px",
}}>
The{" "}
{t("mcp.configureView.protocolIntro")}
<VSCodeLink href="https://github.com/modelcontextprotocol" style={{ display: "inline" }}>
Model Context Protocol
{t("mcp.configureView.modelContextProtocol")}
</VSCodeLink>{" "}
enables communication with locally running MCP servers that provide additional tools and resources to extend
Cline's capabilities. You can use{" "}
{t("mcp.configureView.protocolDescription")}
<VSCodeLink href="https://github.com/modelcontextprotocol/servers" style={{ display: "inline" }}>
community-made servers
{t("mcp.configureView.communityServers")}
</VSCodeLink>{" "}
or ask Cline to create new tools specific to your workflow (e.g., "add a tool that gets the latest npm docs").{" "}
{t("mcp.configureView.protocolDescriptionSuffix")}{" "}
<VSCodeLink href="https://x.com/sdrzn/status/1867271665086074969" style={{ display: "inline" }}>
See a demo here.
{t("mcp.configureView.seeDemo")}
</VSCodeLink>
</div>
@@ -38,7 +39,7 @@ const ConfigureServersView = () => {
{hasRemoteMCPServers && (
<div className="flex items-center gap-2 px-5 py-3 mb-4 bg-vscode-textBlockQuote-background border-l-[3px] border-vscode-textLink-foreground">
<i className="codicon codicon-lock text-sm" />
<span className="text-base">Your organization manages some MCP servers</span>
<span className="text-base">{t("mcp.configureView.orgManages")}</span>
</div>
)}
@@ -54,13 +55,13 @@ const ConfigureServersView = () => {
})
}}
style={{ width: "100%", marginBottom: "5px" }}>
<span className="codicon codicon-server" style={{ marginRight: "6px" }}></span>
Configure MCP Servers
<span className="codicon codicon-server" style={{ marginRight: "6px" }} />
{t("mcp.configureView.configureMcpServers")}
</VSCodeButton>
<div style={{ textAlign: "center" }}>
<VSCodeLink onClick={() => navigateToSettings("features")} style={{ fontSize: "12px" }}>
Advanced MCP Settings
{t("mcp.configureView.advancedSettings")}
</VSCodeLink>
</div>
</div>
@@ -1,4 +1,5 @@
import { McpServer } from "@shared/mcp"
import { useTranslation } from "react-i18next"
import ServerRow from "./server-row/ServerRow"
const ServersToggleList = ({
@@ -12,6 +13,8 @@ const ServersToggleList = ({
hasTrashIcon: boolean
listGap?: "small" | "medium" | "large"
}) => {
const { t } = useTranslation("misc")
const gapClasses = {
small: "gap-0",
medium: "gap-2.5",
@@ -28,7 +31,7 @@ const ServersToggleList = ({
</div>
) : (
<div className="flex flex-col items-center gap-3 my-5 text-(--vscode-descriptionForeground)">
No MCP servers installed
{t("mcp.configureView.noServersInstalled")}
</div>
)
}
@@ -1,4 +1,5 @@
import { McpPrompt } from "@shared/mcp"
import { useTranslation } from "react-i18next"
type McpPromptRowProps = {
prompt: McpPrompt
@@ -6,6 +7,8 @@ type McpPromptRowProps = {
}
const McpPromptRow = ({ prompt, serverName }: McpPromptRowProps) => {
const { t } = useTranslation("misc")
return (
<div
key={prompt.name}
@@ -17,7 +20,7 @@ const McpPromptRow = ({ prompt, serverName }: McpPromptRowProps) => {
onClick={(e) => e.stopPropagation()}
style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: "4px" }}>
<div style={{ display: "flex", alignItems: "center", minWidth: 0, flex: "1 1 auto" }}>
<span className="codicon codicon-comment-discussion" style={{ marginRight: "6px", flexShrink: 0 }}></span>
<span className="codicon codicon-comment-discussion" style={{ marginRight: "6px", flexShrink: 0 }} />
<span style={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis" }}>
{prompt.title || prompt.name}
</span>
@@ -50,7 +53,7 @@ const McpPromptRow = ({ prompt, serverName }: McpPromptRowProps) => {
fontSize: "11px",
textTransform: "uppercase",
}}>
Arguments
{t("mcp.serverRow.arguments")}
</div>
{prompt.arguments.map((arg) => (
<div
@@ -81,7 +84,7 @@ const McpPromptRow = ({ prompt, serverName }: McpPromptRowProps) => {
overflowWrap: "break-word",
wordBreak: "break-word",
}}>
{arg.description || "No description"}
{arg.description || t("mcp.serverRow.noDescription")}
</span>
</div>
))}
@@ -1,10 +1,12 @@
import { McpResource, McpResourceTemplate } from "@shared/mcp"
import { useTranslation } from "react-i18next"
type McpResourceRowProps = {
item: McpResource | McpResourceTemplate
}
const McpResourceRow = ({ item }: McpResourceRowProps) => {
const { t } = useTranslation("misc")
const hasUri = "uri" in item
const uri = hasUri ? item.uri : item.uriTemplate
@@ -35,13 +37,13 @@ const McpResourceRow = ({ item }: McpResourceRowProps) => {
? item.description
: !item.description && item.name
? item.name
: "No description"}
: t("mcp.serverRow.noDescription")}
</div>
<div
style={{
fontSize: "12px",
}}>
<span style={{ opacity: 0.8 }}>Returns </span>
<span style={{ opacity: 0.8 }}>{t("mcp.marketplace.returns")} </span>
<code
style={{
color: "var(--vscode-textPreformat-foreground)",
@@ -49,7 +51,7 @@ const McpResourceRow = ({ item }: McpResourceRowProps) => {
padding: "1px 4px",
borderRadius: "3px",
}}>
{item.mimeType || "Unknown"}
{item.mimeType || t("mcp.marketplace.unknown")}
</code>
</div>
</div>
@@ -2,6 +2,7 @@ import { McpTool } from "@shared/mcp"
import { ToggleToolAutoApproveRequest } from "@shared/proto/cline/mcp"
import { convertProtoMcpServersToMcpServers } from "@shared/proto-conversions/mcp/mcp-server-conversion"
import { VSCodeCheckbox } from "@vscode/webview-ui-toolkit/react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
@@ -11,6 +12,7 @@ type McpToolRowProps = {
}
const McpToolRow = ({ tool, serverName }: McpToolRowProps) => {
const { t } = useTranslation("misc")
const { autoApprovalSettings } = useExtensionState()
const { setMcpServers } = useExtensionState()
@@ -47,7 +49,7 @@ const McpToolRow = ({ tool, serverName }: McpToolRowProps) => {
onClick={(e) => e.stopPropagation()}
style={{ display: "flex", alignItems: "center", justifyContent: "space-between", flexWrap: "wrap", gap: "4px" }}>
<div style={{ display: "flex", alignItems: "center", minWidth: 0, flex: "1 1 auto" }}>
<span className="codicon codicon-symbol-method" style={{ marginRight: "6px", flexShrink: 0 }}></span>
<span className="codicon codicon-symbol-method" style={{ marginRight: "6px", flexShrink: 0 }} />
<span style={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis" }}>{tool.name}</span>
</div>
{serverName && autoApprovalSettings.actions.useMcp && (
@@ -56,7 +58,7 @@ const McpToolRow = ({ tool, serverName }: McpToolRowProps) => {
data-tool={tool.name}
onChange={handleAutoApproveChange}
style={{ fontSize: "11px" }}>
Auto-approve
{t("mcp.serverRow.autoApprove")}
</VSCodeCheckbox>
)}
</div>
@@ -89,7 +91,7 @@ const McpToolRow = ({ tool, serverName }: McpToolRowProps) => {
fontSize: "11px",
textTransform: "uppercase",
}}>
Parameters
{t("mcp.serverRow.parameters")}
</div>
{Object.entries(tool.inputSchema.properties as Record<string, any>).map(([paramName, schema]) => {
const isRequired =
@@ -127,7 +129,7 @@ const McpToolRow = ({ tool, serverName }: McpToolRowProps) => {
overflowWrap: "break-word",
wordBreak: "break-word",
}}>
{schema.description || "No description"}
{schema.description || t("mcp.serverRow.noDescription")}
</span>
</div>
)
@@ -17,6 +17,7 @@ import {
} from "@vscode/webview-ui-toolkit/react"
import { RefreshCcwIcon, Trash2Icon } from "lucide-react"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { Switch } from "@/components/ui/switch"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
@@ -30,17 +31,13 @@ import McpToolRow from "./McpToolRow"
// constant JSX.Elements
const TimeoutOptions = [
{ value: "30", label: "30 seconds" },
{ value: "60", label: "1 minute" },
{ value: "300", label: "5 minutes" },
{ value: "600", label: "10 minutes" },
{ value: "1800", label: "30 minutes" },
{ value: "3600", label: "1 hour" },
].map((option) => (
<VSCodeOption key={option.value} value={option.value}>
{option.label}
</VSCodeOption>
))
{ value: "30", labelKey: "mcp.timeout.30seconds" },
{ value: "60", labelKey: "mcp.timeout.1minute" },
{ value: "300", labelKey: "mcp.timeout.5minutes" },
{ value: "600", labelKey: "mcp.timeout.10minutes" },
{ value: "1800", labelKey: "mcp.timeout.30minutes" },
{ value: "3600", labelKey: "mcp.timeout.1hour" },
]
const ServerRow = ({
server,
@@ -51,6 +48,7 @@ const ServerRow = ({
isExpandable?: boolean
hasTrashIcon?: boolean
}) => {
const { t } = useTranslation("misc")
const { mcpMarketplaceCatalog, autoApprovalSettings, setMcpServers, remoteConfigSettings } = useExtensionState()
const [isExpanded, setIsExpanded] = useState(false)
@@ -93,7 +91,7 @@ const ServerRow = ({
const handleTimeoutChange = (e: any) => {
const select = e.target as HTMLSelectElement
const value = select.value
const num = parseInt(value)
const num = Number.parseInt(value)
setTimeoutValue(value)
McpServiceClient.updateMcpTimeout({
@@ -230,7 +228,7 @@ const ServerRow = ({
handleRestart()
}}
size="icon"
title="Restart Server"
title={t("mcp.serverRow.restartServer")}
variant="icon">
<RefreshCcwIcon />
</Button>
@@ -243,7 +241,7 @@ const ServerRow = ({
handleDelete()
}}
size="icon"
title="Delete Server"
title={t("mcp.serverRow.deleteServer")}
variant="icon">
<Trash2Icon />
</Button>
@@ -265,7 +263,7 @@ const ServerRow = ({
</div>
</TooltipTrigger>
<TooltipContent className="max-w-xs" hidden={!isAlwaysEnabled} side="top">
This server can't be disabled because it is enabled by your organization
{t("mcp.serverRow.cantDisable")}
</TooltipContent>
</Tooltip>
<div
@@ -288,7 +286,7 @@ const ServerRow = ({
McpServiceClient.authenticateMcpServer(StringRequest.create({ value: server.name }))
}}
variant="default">
Authenticate
{t("mcp.serverRow.authenticate")}
</Button>
) : (
<Button
@@ -296,7 +294,9 @@ const ServerRow = ({
disabled={server.status === "connecting"}
onClick={handleRestart}
variant="secondary">
{server.status === "connecting" || isRestarting ? "Retrying..." : "Retry Connection"}
{server.status === "connecting" || isRestarting
? t("mcp.serverRow.retrying")
: t("mcp.serverRow.retryConnection")}
</Button>
)}
@@ -306,7 +306,7 @@ const ServerRow = ({
disabled={isDeleting}
onClick={handleDelete}
variant="danger">
{isDeleting ? "Deleting..." : "Delete Server"}
{isDeleting ? t("mcp.serverRow.deleting") : t("mcp.serverRow.deleteServerBtn")}
</Button>
)}
</div>
@@ -314,11 +314,17 @@ const ServerRow = ({
isExpanded && (
<div className="bg-text-block-background p-2.5 pt-0 text-sm rounded-b-sm">
<VSCodePanels>
<VSCodePanelTab id="tools">Tools ({server.tools?.length || 0})</VSCodePanelTab>
<VSCodePanelTab id="tools">
{t("mcp.serverRow.tools", { count: server.tools?.length || 0 })}
</VSCodePanelTab>
<VSCodePanelTab id="resources">
Resources ({[...(server.resourceTemplates || []), ...(server.resources || [])].length || 0})
{t("mcp.serverRow.resources", {
count: [...(server.resourceTemplates || []), ...(server.resources || [])].length || 0,
})}
</VSCodePanelTab>
<VSCodePanelTab id="prompts">
{t("mcp.serverRow.prompts", { count: server.prompts?.length || 0 })}
</VSCodePanelTab>
<VSCodePanelTab id="prompts">Prompts ({server.prompts?.length || 0})</VSCodePanelTab>
<VSCodePanelView id="tools-view">
{server.tools && server.tools.length > 0 ? (
@@ -329,7 +335,7 @@ const ServerRow = ({
className="mb-1 text-xs"
data-tool="all-tools"
onChange={handleAutoApproveChange}>
Auto-approve all tools
{t("mcp.serverRow.autoApproveAll")}
</VSCodeCheckbox>
)}
{server.tools.map((tool) => (
@@ -337,7 +343,7 @@ const ServerRow = ({
))}
</div>
) : (
<div className="text-description py-2.5">No tools found</div>
<div className="text-description py-2.5">{t("mcp.serverRow.noToolsFound")}</div>
)}
</VSCodePanelView>
@@ -353,7 +359,7 @@ const ServerRow = ({
))}
</div>
) : (
<div className="py-2.5 text-description">No resources found</div>
<div className="py-2.5 text-description">{t("mcp.serverRow.noResourcesFound")}</div>
)}
</VSCodePanelView>
@@ -377,16 +383,20 @@ const ServerRow = ({
padding: "10px 0",
color: "var(--vscode-descriptionForeground)",
}}>
No prompts found
{t("mcp.serverRow.noPromptsFound")}
</div>
)}
</VSCodePanelView>
</VSCodePanels>
<div className="my-2.5 mx-1.5">
<label className="block mb-1 text-[13px]">Request Timeout</label>
<label className="block mb-1 text-[13px]">{t("mcp.serverRow.requestTimeout")}</label>
<VSCodeDropdown className="w-full" onChange={handleTimeoutChange} value={timeoutValue}>
{TimeoutOptions}
{TimeoutOptions.map((option) => (
<VSCodeOption key={option.value} value={option.value}>
{t(option.labelKey)}
</VSCodeOption>
))}
</VSCodeDropdown>
</div>
<Button
@@ -394,7 +404,11 @@ const ServerRow = ({
disabled={server.status === "connecting" || isRestarting || server.disabled}
onClick={handleRestart}
variant="secondary">
{server.status === "connecting" || isRestarting ? "Restarting..." : server.disabled ? "Server Disabled" : "Restart Server"}
{server.status === "connecting" || isRestarting
? t("mcp.serverRow.restarting")
: server.disabled
? t("mcp.serverRow.serverDisabled")
: t("mcp.serverRow.restartServerBtn")}
</Button>
{!isRemoteManagedServer && (
@@ -403,7 +417,7 @@ const ServerRow = ({
disabled={isDeleting}
onClick={handleDelete}
variant="danger">
{isDeleting ? "Deleting..." : "Delete Server"}
{isDeleting ? t("mcp.serverRow.deleting") : t("mcp.serverRow.deleteServerBtn")}
</Button>
)}
</div>
@@ -1,6 +1,7 @@
import { McpMarketplaceItem, McpServer } from "@shared/mcp"
import { StringRequest } from "@shared/proto/cline/common"
import { useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import styled from "styled-components"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
@@ -12,6 +13,7 @@ interface McpMarketplaceCardProps {
}
const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplaceCardProps) => {
const { t } = useTranslation("misc")
const isInstalled = installedServers.some((server) => server.name === item.mcpId)
const [isDownloading, setIsDownloading] = useState(false)
const [isLoading, setIsLoading] = useState(false)
@@ -128,7 +130,11 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace
}}
style={{}}>
<StyledInstallButton $isInstalled={isInstalled} disabled={isInstalled || isDownloading}>
{isInstalled ? "Installed" : isDownloading ? "Installing..." : "Install"}
{isInstalled
? t("mcp.marketplace.installed")
: isDownloading
? t("mcp.marketplace.installing")
: t("mcp.marketplace.install")}
</StyledInstallButton>
</div>
</div>
@@ -201,7 +207,11 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace
<span style={{ wordBreak: "break-all" }}>{item.downloadCount?.toLocaleString() ?? 0}</span>
</div>
{item.requiresApiKey && (
<span className="codicon codicon-key" style={{ flexShrink: 0 }} title="Requires API key" />
<span
className="codicon codicon-key"
style={{ flexShrink: 0 }}
title={t("mcp.serverRow.requiresApiKey")}
/>
)}
</div>
</div>
@@ -209,22 +219,6 @@ const McpMarketplaceCard = ({ item, installedServers, setError }: McpMarketplace
{/* Description and tags */}
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
{/* {!item.isRecommended && (
<div
style={{
display: "flex",
alignItems: "center",
gap: "4px",
fontSize: "12px",
color: "var(--vscode-notificationsWarningIcon-foreground)",
marginTop: -3,
marginBottom: -3,
}}>
<span className="codicon codicon-warning" style={{ fontSize: "14px" }} />
<span>Community Made (use at your own risk)</span>
</div>
)} */}
<p style={{ fontSize: "13px", margin: 0 }}>{item.description}</p>
<div
onScroll={(e) => {
@@ -9,12 +9,14 @@ import {
VSCodeTextField,
} from "@vscode/webview-ui-toolkit/react"
import { useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { McpServiceClient } from "@/services/grpc-client"
import McpMarketplaceCard from "./McpMarketplaceCard"
import McpSubmitCard from "./McpSubmitCard"
const McpMarketplaceView = () => {
const { t } = useTranslation("misc")
const { mcpServers, mcpMarketplaceCatalog, setMcpMarketplaceCatalog, remoteConfigSettings } = useExtensionState()
const showMarketplace = remoteConfigSettings?.mcpMarketplaceEnabled !== false
@@ -73,7 +75,7 @@ const McpMarketplaceView = () => {
}
}, [mcpMarketplaceCatalog])
const fetchMarketplace = (forceRefresh: boolean = false) => {
const fetchMarketplace = (forceRefresh = false) => {
if (forceRefresh) {
setIsRefreshing(true)
} else {
@@ -88,7 +90,7 @@ const McpMarketplaceView = () => {
})
.catch((error) => {
console.error("Error refreshing MCP marketplace:", error)
setError("Failed to load marketplace data")
setError(t("mcp.marketplace.failedToLoad"))
setIsLoading(false)
setIsRefreshing(false)
})
@@ -125,7 +127,7 @@ const McpMarketplaceView = () => {
<div style={{ color: "var(--vscode-errorForeground)" }}>{error}</div>
<VSCodeButton appearance="secondary" onClick={() => fetchMarketplace(true)}>
<span className="codicon codicon-refresh" style={{ marginRight: "6px" }} />
Retry
{t("mcp.marketplace.retry")}
</VSCodeButton>
</div>
)
@@ -142,7 +144,7 @@ const McpMarketplaceView = () => {
{/* Search row */}
<VSCodeTextField
onInput={(e) => setSearchQuery((e.target as HTMLInputElement).value)}
placeholder="Search MCPs..."
placeholder={t("mcp.marketplace.searchMcp")}
style={{ width: "100%" }}
value={searchQuery}>
<div
@@ -155,7 +157,7 @@ const McpMarketplaceView = () => {
/>
{searchQuery && (
<div
aria-label="Clear search"
aria-label={t("mcp.marketplace.clearSearch")}
className="codicon codicon-close"
onClick={() => setSearchQuery("")}
slot="end"
@@ -185,7 +187,7 @@ const McpMarketplaceView = () => {
fontWeight: 500,
flexShrink: 0,
}}>
Filter:
{t("mcp.marketplace.filter")}
</span>
<div
style={{
@@ -199,7 +201,7 @@ const McpMarketplaceView = () => {
width: "100%",
}}
value={selectedCategory || ""}>
<VSCodeOption value="">All Categories</VSCodeOption>
<VSCodeOption value="">{t("mcp.marketplace.allCategories")}</VSCodeOption>
{categories.map((category) => (
<VSCodeOption key={category} value={category}>
{category}
@@ -223,7 +225,7 @@ const McpMarketplaceView = () => {
fontWeight: 500,
marginTop: "3px",
}}>
Sort:
{t("mcp.marketplace.sort")}
</span>
<VSCodeRadioGroup
onChange={(e) => setSortBy((e.target as HTMLInputElement).value as typeof sortBy)}
@@ -233,10 +235,10 @@ const McpMarketplaceView = () => {
marginTop: "-2.5px",
}}
value={sortBy}>
<VSCodeRadio value="downloadCount">Most Installs</VSCodeRadio>
<VSCodeRadio value="newest">Newest</VSCodeRadio>
<VSCodeRadio value="stars">GitHub Stars</VSCodeRadio>
<VSCodeRadio value="name">Name</VSCodeRadio>
<VSCodeRadio value="downloadCount">{t("mcp.marketplace.mostInstalls")}</VSCodeRadio>
<VSCodeRadio value="newest">{t("mcp.marketplace.newest")}</VSCodeRadio>
<VSCodeRadio value="stars">{t("mcp.marketplace.githubStars")}</VSCodeRadio>
<VSCodeRadio value="name">{t("mcp.marketplace.name")}</VSCodeRadio>
</VSCodeRadioGroup>
</div>
</div>
@@ -265,7 +267,7 @@ const McpMarketplaceView = () => {
{remoteConfigSettings?.allowedMCPServers && (
<div className="flex items-center gap-2 px-5 py-3 mx-5 mb-4 bg-vscode-textBlockQuote-background border-l-[3px] border-vscode-textLink-foreground">
<i className="codicon codicon-lock text-sm" />
<span className="text-[13px]">Your organization has pre-configured the available MCP servers</span>
<span className="text-[13px]">{t("mcp.marketplace.orgPreconfigured")}</span>
</div>
)}
@@ -280,9 +282,7 @@ const McpMarketplaceView = () => {
padding: "20px",
color: "var(--vscode-descriptionForeground)",
}}>
{searchQuery || selectedCategory
? "No matching MCP servers found"
: "No MCP servers found in the marketplace"}
{searchQuery || selectedCategory ? t("mcp.marketplace.noMatching") : t("mcp.marketplace.noMarketplace")}
</div>
) : (
filteredItems.map((item) => (
@@ -1,4 +1,8 @@
import { useTranslation } from "react-i18next"
const McpSubmitCard = () => {
const { t } = useTranslation("misc")
return (
<div
style={{
@@ -31,10 +35,10 @@ const McpSubmitCard = () => {
fontWeight: 600,
color: "var(--vscode-foreground)",
}}>
Submit MCP Server
{t("mcp.marketplace.submitTitle")}
</h3>
<p style={{ fontSize: "13px", margin: 0, color: "var(--vscode-descriptionForeground)" }}>
Help others discover great MCP servers by submitting an issue to{" "}
{t("mcp.marketplace.submitDescription")}
<a href="https://github.com/cline/mcp-marketplace">github.com/cline/mcp-marketplace</a>
</p>
</div>
+8 -6
View File
@@ -1,5 +1,6 @@
import { HistoryIcon, PlusIcon, SettingsIcon, UserCircleIcon } from "lucide-react"
import { useMemo } from "react"
import { useTranslation } from "react-i18next"
import { Button } from "@/components/ui/button"
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"
import { TaskServiceClient } from "@/services/grpc-client"
@@ -14,6 +15,7 @@ const McpServerIcon = ({ className, size }: { className?: string; size?: number
)
export const Navbar = () => {
const { t } = useTranslation("misc")
const { navigateToHistory, navigateToSettings, navigateToAccount, navigateToMcp, navigateToChat } = useExtensionState()
const SETTINGS_TABS = useMemo(
@@ -21,7 +23,7 @@ export const Navbar = () => {
{
id: "chat",
name: "Chat",
tooltip: "New Task",
tooltip: t("navbar.newTask"),
icon: PlusIcon,
navigate: () => {
// Close the current task, then navigate to the chat view
@@ -35,33 +37,33 @@ export const Navbar = () => {
{
id: "mcp",
name: "MCP",
tooltip: "MCP Servers",
tooltip: t("navbar.mcpServers"),
icon: McpServerIcon,
navigate: navigateToMcp,
},
{
id: "history",
name: "History",
tooltip: "History",
tooltip: t("navbar.history"),
icon: HistoryIcon,
navigate: navigateToHistory,
},
{
id: "account",
name: "Account",
tooltip: "Account",
tooltip: t("navbar.account"),
icon: UserCircleIcon,
navigate: navigateToAccount,
},
{
id: "settings",
name: "Settings",
tooltip: "Settings",
tooltip: t("navbar.settings"),
icon: SettingsIcon,
navigate: navigateToSettings,
},
],
[navigateToAccount, navigateToChat, navigateToHistory, navigateToMcp, navigateToSettings],
[navigateToAccount, navigateToChat, navigateToHistory, navigateToMcp, navigateToSettings, t],
)
return (
@@ -2,6 +2,7 @@ import type { ModelInfo } from "@shared/api"
import type { OnboardingModel, OnboardingModelGroup, OpenRouterModelInfo } from "@shared/proto/index.cline"
import { AlertCircleIcon, CircleCheckIcon, CircleIcon, ListIcon, LoaderCircleIcon, ZapIcon } from "lucide-react"
import { useCallback, useEffect, useMemo, useState } from "react"
import { useTranslation } from "react-i18next"
import ClineLogoWhite from "@/assets/ClineLogoWhite"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
@@ -20,7 +21,7 @@ import {
getSpeedLabel,
type OnboardingModelsByGroup,
} from "./data-models"
import { NEW_USER_TYPE, STEP_CONFIG, USER_TYPE_SELECTIONS } from "./data-steps"
import { getStepConfig, getUserTypeSelections, NEW_USER_TYPE } from "./data-steps"
import { useOnboardingModels } from "./useOnboardingModels"
type ModelSelectionProps = {
@@ -79,7 +80,7 @@ const ModelSelection = ({
</ItemTitle>
{isSelected && model.info && (
<ItemDescription>
<span className="text-foreground/70 text-sm">Support: </span>
<span className="text-foreground/70 text-sm">{t("onboarding.support")} </span>
<span className="text-foreground text-sm">{getCapabilities(model.info).join(", ")}</span>
</ItemDescription>
)}
@@ -89,14 +90,14 @@ const ModelSelection = ({
<div className="flex flex-col gap-3">
<div className="inline-flex gap-1 [&_svg]:stroke-success [&_svg]:size-3 items-center text-sm">
<ZapIcon />
<span>Speed: </span>
<span>{t("onboarding.speed")} </span>
<span className="text-foreground/70">{getSpeedLabel(model.latency)}</span>
</div>
{model.info && (
<div className="flex w-full justify-between">
<div className="inline-flex gap-1 [&_svg]:stroke-foreground [&_svg]:size-3 items-center text-sm">
<ListIcon />
<span>Context: </span>
<span>{t("onboarding.context")} </span>
<span className="text-foreground/70">{(model?.info.contextWindow || 0) / 1000}k</span>
</div>
<Badge>{getPriceRange(model.info)}</Badge>
@@ -125,7 +126,7 @@ const ModelSelection = ({
{/* SEARCH MODEL */}
<div className="flex w-full max-w-lg flex-col gap-6 my-4 border-t border-muted-foreground">
<div className="flex flex-col gap-3 mt-6" key="search-results">
<h4 className="text-sm font-bold text-foreground/70 uppercase mb-2">other options</h4>
<h4 className="text-sm font-bold text-foreground/70 uppercase mb-2">{t("modelPicker.otherOptions")}</h4>
<Input
autoFocus={false}
className="focus-visible:border-button-background"
@@ -178,7 +179,9 @@ const ModelSelection = ({
return <ModelItem id={id} isSelected={isSelected} key={id} model={onboardingModel} />
})}
{searchTerm.length > 0 && searchedModels.length === 0 && (
<p className="px-1 mt-1 text-sm text-foreground/70">No result found for "{searchTerm}"</p>
<p className="px-1 mt-1 text-sm text-foreground/70">
{t("modelPicker.noResultFound", { term: searchTerm })}
</p>
)}
</div>
</div>
@@ -195,7 +198,7 @@ type UserTypeSelectionProps = {
const UserTypeSelectionStep = ({ userType, onSelectUserType }: UserTypeSelectionProps) => (
<div className="flex flex-col w-full items-center">
<div className="flex w-full max-w-lg flex-col gap-3 my-2">
{USER_TYPE_SELECTIONS.map((option) => {
{getUserTypeSelections(t).map((option) => {
const isSelected = userType === option.type
return (
@@ -266,6 +269,7 @@ const OnboardingStepContent = ({
}
const OnboardingViewContent = ({ onboardingModels }: { onboardingModels: OnboardingModelGroup }) => {
const { t } = useTranslation("settings")
const { handleFieldsChange } = useApiConfigurationHandlers()
const { openRouterModels, hideSettings, hideAccount, setShowWelcome } = useExtensionState()
@@ -362,10 +366,10 @@ const OnboardingViewContent = ({ onboardingModels }: { onboardingModels: Onboard
)
const stepDisplayInfo = useMemo(() => {
const step = stepNumber === 0 || stepNumber === 2 ? STEP_CONFIG[stepNumber] : null
const title = step ? step.title : userType ? STEP_CONFIG[userType].title : STEP_CONFIG[0].title
const step = stepNumber === 0 || stepNumber === 2 ? getStepConfig(t)[stepNumber] : null
const title = step ? step.title : userType ? getStepConfig(t)[userType].title : getStepConfig(t)[0].title
const description = step ? step.description : null
const buttons = step ? step.buttons : userType ? STEP_CONFIG[userType].buttons : STEP_CONFIG[0].buttons
const buttons = step ? step.buttons : userType ? getStepConfig(t)[userType].buttons : getStepConfig(t)[0].buttons
return { title, description, buttons }
}, [stepNumber, userType])
@@ -411,7 +415,7 @@ const OnboardingViewContent = ({ onboardingModels }: { onboardingModels: Onboard
{stepNumber !== 2 && (
<div className="items-center justify-center flex text-sm text-foreground gap-2 mb-3 text-pretty">
<AlertCircleIcon className="shrink-0 size-2" /> You can change this later in settings
<AlertCircleIcon className="shrink-0 size-2" /> {t("onboarding.canChangeLater")}
</div>
)}
</footer>
@@ -1,3 +1,5 @@
import type { TFunction } from "i18next"
export enum NEW_USER_TYPE {
FREE = "free",
POWER = "power",
@@ -10,45 +12,45 @@ type UserTypeSelection = {
type: NEW_USER_TYPE
}
export const STEP_CONFIG = {
export const getStepConfig = (t: TFunction) => ({
0: {
title: "How will you use Cline?",
description: "Select an option below to get started.",
title: t("onboarding.howWillYouUse"),
description: t("onboarding.selectOption"),
buttons: [
{ text: "Continue", action: "next", variant: "default" },
{ text: "Login to Cline", action: "signin", variant: "secondary" },
{ text: t("onboarding.continue"), action: "next", variant: "default" },
{ text: t("onboarding.loginToCline"), action: "signin", variant: "secondary" },
],
},
[NEW_USER_TYPE.FREE]: {
title: "Select a free model",
title: t("onboarding.selectFreeModel"),
buttons: [
{ text: "Create my Account", action: "signup", variant: "default" },
{ text: "Back", action: "back", variant: "secondary" },
{ text: t("onboarding.createMyAccount"), action: "signup", variant: "default" },
{ text: t("onboarding.back"), action: "back", variant: "secondary" },
],
},
[NEW_USER_TYPE.POWER]: {
title: "Select your model",
title: t("onboarding.selectYourModel"),
buttons: [
{ text: "Create my Account", action: "signup", variant: "default" },
{ text: "Back", action: "back", variant: "secondary" },
{ text: t("onboarding.createMyAccount"), action: "signup", variant: "default" },
{ text: t("onboarding.back"), action: "back", variant: "secondary" },
],
},
[NEW_USER_TYPE.BYOK]: {
title: "Configure your provider",
title: t("onboarding.configureYourProvider"),
buttons: [
{ text: "Continue", action: "done", variant: "default" },
{ text: "Back", action: "back", variant: "secondary" },
{ text: t("onboarding.continue"), action: "done", variant: "default" },
{ text: t("onboarding.back"), action: "back", variant: "secondary" },
],
},
2: {
title: "Almost there!",
description: "Complete account creation in your browser. Then come back here to finish up.",
buttons: [{ text: "Back", action: "back", variant: "secondary" }],
title: t("onboarding.almostThere"),
description: t("onboarding.completeInBrowser"),
buttons: [{ text: t("onboarding.back"), action: "back", variant: "secondary" }],
},
} as const
})
export const USER_TYPE_SELECTIONS: UserTypeSelection[] = [
{ title: "Absolutely Free", description: "Get started at no cost", type: NEW_USER_TYPE.FREE },
{ title: "Frontier Model", description: "Claude, GPT Codex, Gemini, etc.", type: NEW_USER_TYPE.POWER },
{ title: "Bring my own API key", description: "Use Cline with your provider of choice", type: NEW_USER_TYPE.BYOK },
export const getUserTypeSelections = (t: TFunction): UserTypeSelection[] => [
{ title: t("onboarding.absolutelyFree"), description: t("onboarding.getStartedNoCost"), type: NEW_USER_TYPE.FREE },
{ title: t("onboarding.frontierModel"), description: t("onboarding.frontierModelDescription"), type: NEW_USER_TYPE.POWER },
{ title: t("onboarding.bringOwnKey"), description: t("onboarding.bringOwnKeyDescription"), type: NEW_USER_TYPE.BYOK },
]
@@ -4,6 +4,7 @@ import { Mode } from "@shared/storage/types"
import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import Fuse from "fuse.js"
import { KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useInterval } from "react-use"
import styled from "styled-components"
import { normalizeApiConfiguration } from "@/components/settings/utils/providerUtils"
@@ -97,6 +98,7 @@ const ApiOptions = ({
currentMode,
initialModelTab,
}: ApiOptionsProps) => {
const { t } = useTranslation("settings")
// Use full context state for immediate save payload
const { apiConfiguration, remoteConfigSettings } = useExtensionState()
@@ -282,16 +284,16 @@ const ApiOptions = ({
<TooltipTrigger>
<div className="flex items-center gap-2 mb-1">
<label htmlFor="api-provider">
<span style={{ fontWeight: 500 }}>API Provider</span>
<span style={{ fontWeight: 500 }}>{t("settings.apiProvider")}</span>
</label>
<i className="codicon codicon-lock text-description text-sm" />
</div>
</TooltipTrigger>
<TooltipContent>Provider options are managed by your organization's remote configuration</TooltipContent>
<TooltipContent>{t("settings.providerManagedByOrg")}</TooltipContent>
</Tooltip>
) : (
<label htmlFor="api-provider">
<span style={{ fontWeight: 500 }}>API Provider</span>
<span style={{ fontWeight: 500 }}>{t("settings.apiProvider")}</span>
</label>
)}
<ProviderDropdownWrapper ref={dropdownRef}>
@@ -307,7 +309,7 @@ const ApiOptions = ({
setIsDropdownVisible(true)
}}
onKeyDown={handleKeyDown}
placeholder="Search and select provider..."
placeholder={t("settings.searchSelectProvider")}
role="combobox"
style={{
width: "100%",
@@ -318,7 +320,7 @@ const ApiOptions = ({
value={searchTerm}>
{searchTerm && searchTerm !== currentProviderLabel && (
<div
aria-label="Clear search"
aria-label={t("settings.clearSearch")}
className="input-icon-button codicon codicon-close"
onClick={() => {
setSearchTerm("")
@@ -3,6 +3,7 @@ import { Mode } from "@shared/storage/types"
import { VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import Fuse from "fuse.js"
import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useExtensionState } from "../../context/ExtensionStateContext"
import { highlight } from "../history/HistoryView"
import { ModelInfoView } from "./common/ModelInfoView"
@@ -15,6 +16,7 @@ export interface BasetenModelPickerProps {
}
const BasetenModelPicker: React.FC<BasetenModelPickerProps> = ({ isPopup, currentMode }) => {
const { t } = useTranslation("settings")
const { apiConfiguration, basetenModels: dynamicBasetenModels } = useExtensionState()
const { handleModeFieldsChange } = useApiConfigurationHandlers()
const modeFields = getModeSpecificFields(apiConfiguration, currentMode)
@@ -195,7 +197,7 @@ const BasetenModelPicker: React.FC<BasetenModelPickerProps> = ({ isPopup, curren
</style>
<div className="flex flex-col">
<label htmlFor="model-search">
<span className="font-medium">Model</span>
<span className="font-medium">{t("settings.model")}</span>
</label>
<div className="relative w-full" ref={dropdownRef}>
<VSCodeTextField
@@ -206,7 +208,7 @@ const BasetenModelPicker: React.FC<BasetenModelPickerProps> = ({ isPopup, curren
setIsDropdownVisible(true)
}}
onKeyDown={handleKeyDown}
placeholder="Search and select a model..."
placeholder={t("settings.searchSelectModel")}
role="combobox"
style={{
width: "100%",
@@ -1,11 +1,13 @@
import { EmptyRequest } from "@shared/proto/cline/common"
import { VSCodeButton } from "@vscode/webview-ui-toolkit/react"
import { useState } from "react"
import { useTranslation } from "react-i18next"
import { useClineAuth } from "@/context/ClineAuthContext"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { AccountServiceClient } from "@/services/grpc-client"
export const ClineAccountInfoCard = () => {
const { t } = useTranslation("settings")
const { clineUser } = useClineAuth()
const { navigateToAccount } = useExtensionState()
const [isLoading, setIsLoading] = useState(false)
@@ -29,15 +31,15 @@ export const ClineAccountInfoCard = () => {
<div className="max-w-[600px]">
{user ? (
<VSCodeButton appearance="secondary" onClick={handleShowAccount}>
View Billing & Usage
{t("settings.viewBillingUsage")}
</VSCodeButton>
) : (
<div>
<VSCodeButton className="mt-0" disabled={isLoading} onClick={handleLogin}>
Sign Up with Cline
{t("settings.signUpWithCline")}
{isLoading && (
<span className="ml-1 animate-spin">
<span className="codicon codicon-refresh"></span>
<span className="codicon codicon-refresh" />
</span>
)}
</VSCodeButton>
@@ -6,8 +6,10 @@ import type { Mode } from "@shared/storage/types"
import { isClaudeOpusAdaptiveThinkingModel, resolveClaudeOpusAdaptiveThinking } from "@shared/utils/reasoning-support"
import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import Fuse from "fuse.js"
import i18next from "i18next"
import type React from "react"
import { type KeyboardEvent, useCallback, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useMount } from "react-use"
import styled from "styled-components"
import { useExtensionState } from "@/context/ExtensionStateContext"
@@ -79,7 +81,9 @@ function toFeaturedModelCardEntry(
return {
id: model.id,
description: model.description || (fallbackLabel === "FREE" ? "Free model" : "Recommended model"),
description:
model.description ||
(fallbackLabel === "FREE" ? i18next.t("settings.freeModel") : i18next.t("settings.recommendedModel")),
label: normalizedLabel || fallbackLabel,
}
}
@@ -93,6 +97,7 @@ const FREE_MODELS_FALLBACK: FeaturedModelCardEntry[] = CLINE_RECOMMENDED_MODELS_
.filter((model): model is FeaturedModelCardEntry => model !== null)
const ClineModelPicker: React.FC<ClineModelPickerProps> = ({ isPopup, currentMode, showProviderRouting, initialTab }) => {
const { t } = useTranslation("settings")
const { handleModeFieldsChange, handleFieldChange } = useApiConfigurationHandlers()
const { apiConfiguration, favoritedModelIds, clineModels, refreshClineModels } = useExtensionState()
const modeFields = getModeSpecificFields(apiConfiguration, currentMode)
@@ -391,7 +396,7 @@ const ClineModelPicker: React.FC<ClineModelPickerProps> = ({ isPopup, currentMod
</style>
<div style={{ display: "flex", flexDirection: "column" }}>
<label htmlFor="model-search">
<span style={{ fontWeight: 500 }}>Model</span>
<span style={{ fontWeight: 500 }}>{t("settings.model")}</span>
</label>
<>
@@ -452,7 +457,7 @@ const ClineModelPicker: React.FC<ClineModelPickerProps> = ({ isPopup, currentMod
setIsDropdownVisible(true)
}}
onKeyDown={handleKeyDown}
placeholder="Search and select a model..."
placeholder={t("settings.searchSelectModel")}
role="combobox"
style={{
width: "100%",
@@ -571,11 +576,7 @@ const ClineModelPicker: React.FC<ClineModelPickerProps> = ({ isPopup, currentMod
}
currentMode={currentMode}
defaultEffort={showAdaptiveThinkingEffort ? adaptiveThinkingDefaultEffort : "medium"}
description={
showAdaptiveThinkingEffort
? "Use None to disable adaptive thinking. Higher effort increases response detail and token usage."
: undefined
}
description={showAdaptiveThinkingEffort ? t("settings.adaptiveThinkingDescription") : undefined}
label={showAdaptiveThinkingEffort ? "Adaptive Thinking" : undefined}
/>
)}
@@ -596,8 +597,7 @@ const ClineModelPicker: React.FC<ClineModelPickerProps> = ({ isPopup, currentMod
marginTop: 0,
color: "var(--vscode-descriptionForeground)",
}}>
The extension automatically fetches the latest Cline model list. If you're unsure which model to choose, Cline
works best with <strong>anthropic/claude-sonnet-4.5</strong>.
{t("settings.autoFetchModelList")} <strong>anthropic/claude-sonnet-4.5</strong>.
</p>
)}
</div>
@@ -5,6 +5,7 @@ import { Mode } from "@shared/storage/types"
import { VSCodeLink, VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import Fuse from "fuse.js"
import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useMount } from "react-use"
import { useExtensionState } from "../../context/ExtensionStateContext"
import { ModelsServiceClient } from "../../services/grpc-client"
@@ -19,6 +20,7 @@ export interface GroqModelPickerProps {
}
const GroqModelPicker: React.FC<GroqModelPickerProps> = ({ isPopup, currentMode }) => {
const { t } = useTranslation("settings")
const { apiConfiguration, groqModels: dynamicGroqModels, setGroqModels } = useExtensionState()
const { handleModeFieldsChange } = useApiConfigurationHandlers()
const modeFields = getModeSpecificFields(apiConfiguration, currentMode)
@@ -192,7 +194,7 @@ const GroqModelPicker: React.FC<GroqModelPickerProps> = ({ isPopup, currentMode
</style>
<div className="flex flex-col">
<label htmlFor="model-search">
<span className="font-medium">Model</span>
<span className="font-medium">{t("settings.model")}</span>
</label>
<div className="relative w-full" ref={dropdownRef}>
<VSCodeTextField
@@ -203,7 +205,7 @@ const GroqModelPicker: React.FC<GroqModelPickerProps> = ({ isPopup, currentMode
setIsDropdownVisible(true)
}}
onKeyDown={handleKeyDown}
placeholder="Search and select a model..."
placeholder={t("settings.searchSelectModel")}
role="combobox"
style={{
width: "100%",
@@ -3,6 +3,7 @@ import { Mode } from "@shared/storage/types"
import { VSCodeTextField } from "@vscode/webview-ui-toolkit/react"
import Fuse from "fuse.js"
import React, { KeyboardEvent, useEffect, useMemo, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useMount } from "react-use"
import { useExtensionState } from "@/context/ExtensionStateContext"
import { StateServiceClient } from "@/services/grpc-client"
@@ -29,6 +30,7 @@ export interface HicapModelPickerProps {
}
const HicapModelPicker: React.FC<HicapModelPickerProps> = ({ isPopup, currentMode }) => {
const { t } = useTranslation("settings")
const { handleModeFieldsChange } = useApiConfigurationHandlers()
const { apiConfiguration, favoritedModelIds, hicapModels, refreshHicapModels } = useExtensionState()
@@ -165,7 +167,7 @@ const HicapModelPicker: React.FC<HicapModelPickerProps> = ({ isPopup, currentMod
<div className="w-full">
<div className="flex flex-col">
<label htmlFor="model-search">
<span className="font-medium">Model ID</span>
<span className="font-medium">{t("providers.openaiCompatible.modelId")}</span>
</label>
<div className="relative w-full" ref={dropdownRef}>
@@ -179,7 +181,7 @@ const HicapModelPicker: React.FC<HicapModelPickerProps> = ({ isPopup, currentMod
setIsDropdownVisible(true)
}}
onKeyDown={handleKeyDown}
placeholder="Search and select a model..."
placeholder={t("settings.searchSelectModel")}
role="combobox"
style={{ zIndex: HICAP_MODEL_PICKER_Z_INDEX }}
value={searchTerm}>
Loaded 100 of 182 files, more files were not shown because too many files have changed in this diff. Show more